harn-vm 0.10.162

Async bytecode virtual machine for the Harn programming language
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
//! Final ToolRegistry exposure guard for model-requested dispatch.
//!
//! Agent options are projected before prompt construction and discovery, but
//! a model can still forge a name it was never served. Once an explicit
//! registry exists, this module makes that projected registry the complete
//! callable surface before dispatch can fall through to a VM builtin or host
//! bridge. Calls without an explicit registry retain the legacy ambient
//! builtin surface.

use super::agent_tools::ToolDispatchOutcome;
use crate::stdlib::macros::harn_builtin;
use crate::tool_registry::PreparedToolCatalog;
use crate::value::{ErrorCategory, VmError, VmResourceHandle, VmValue};

const REGISTRY_PROVENANCE_KEY: &str = "_agent_registry_provenance";
const AMBIENT_PROVENANCE_LABEL: &str = "agent_registry_ambient_host";
const PREPARED_CATALOG_KEY: &str = "_agent_prepared_catalog";

#[derive(Debug)]
struct AgentPreparedCatalog {
    tools: VmValue,
    components: Option<VmValue>,
    prepared: std::sync::Arc<PreparedToolCatalog>,
}

impl AgentPreparedCatalog {
    fn matches(&self, registry: &crate::value::DictMap) -> bool {
        let same_tools = matches!((&self.tools, registry.get("tools")),
            (VmValue::List(original), Some(VmValue::List(current)))
                if std::sync::Arc::ptr_eq(original, current));
        let same_components = match (&self.components, registry.get("components")) {
            (None, None) => true,
            (Some(VmValue::Dict(original)), Some(VmValue::Dict(current))) => {
                std::sync::Arc::ptr_eq(original, current)
            }
            _ => false,
        };
        same_tools && same_components
    }
}

pub(super) fn prepared_handler_catalog(
    registry: &VmValue,
    name: &str,
) -> Result<std::sync::Arc<PreparedToolCatalog>, VmError> {
    if let Some(registry) = registry.as_dict() {
        if let Some(VmValue::Resource(resource)) = registry.get(PREPARED_CATALOG_KEY) {
            if let Some(owned) = resource.downcast::<AgentPreparedCatalog>() {
                if owned.matches(registry) {
                    return Ok(owned.prepared.clone());
                }
            }
        }
    }
    prepare_catalog(crate::tool_registry::tool_registry_catalog_for_tool(
        registry, name,
    )?)
}

fn prepare_catalog(
    catalog: crate::tool_registry::ToolCatalog,
) -> Result<std::sync::Arc<PreparedToolCatalog>, VmError> {
    PreparedToolCatalog::prepare(catalog)
        .map(std::sync::Arc::new)
        .map_err(|error| VmError::CategorizedError {
            message: error.to_string(),
            category: ErrorCategory::SchemaValidation,
        })
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) enum AgentRegistryOrigin {
    Explicit,
    AmbientHost,
}

impl AgentRegistryOrigin {
    pub(super) fn parse(value: &str) -> Option<Self> {
        match value {
            "explicit" => Some(Self::Explicit),
            "ambient_host" => Some(Self::AmbientHost),
            _ => None,
        }
    }
}

#[derive(Debug)]
struct AmbientHostRegistryProvenance;

pub(super) fn own_lifecycle_registry(
    registry: &VmValue,
    origin: AgentRegistryOrigin,
) -> Result<VmValue, VmError> {
    let prepared = prepare_catalog(crate::tool_registry::tool_registry_catalog(registry)?)?;
    let mut owned = registry
        .as_dict()
        .expect("validated tool registry must be a dictionary")
        .as_ref()
        .clone();
    owned.insert(
        PREPARED_CATALOG_KEY.into(),
        VmValue::resource(VmResourceHandle::new(
            "agent_prepared_catalog",
            AgentPreparedCatalog {
                tools: owned
                    .get("tools")
                    .expect("validated registry has tools")
                    .clone(),
                components: owned.get("components").cloned(),
                prepared,
            },
        )),
    );
    match origin {
        AgentRegistryOrigin::Explicit => {
            owned.remove(REGISTRY_PROVENANCE_KEY);
        }
        AgentRegistryOrigin::AmbientHost => {
            owned.insert(
                REGISTRY_PROVENANCE_KEY.into(),
                VmValue::resource(VmResourceHandle::new(
                    AMBIENT_PROVENANCE_LABEL,
                    AmbientHostRegistryProvenance,
                )),
            );
        }
    }
    Ok(VmValue::dict(owned))
}

#[harn_builtin(
    exposure = "runtime_internal",
    effects = [],
    sig = "__host_agent_own_lifecycle_registry(registry: dict, origin: \"explicit\" | \"ambient_host\") -> dict",
    category = "agent.host",
    runtime_only = true
)]
fn host_agent_own_lifecycle_registry_impl(
    args: &[VmValue],
    _out: &mut String,
) -> Result<VmValue, VmError> {
    let registry = args.first().ok_or_else(|| {
        VmError::Runtime("__host_agent_own_lifecycle_registry: missing registry".into())
    })?;
    let origin = args
        .get(1)
        .and_then(|value| match value {
            VmValue::String(value) => Some(value.as_str()),
            _ => None,
        })
        .and_then(AgentRegistryOrigin::parse)
        .ok_or_else(|| {
            VmError::Runtime(
                "__host_agent_own_lifecycle_registry: origin must be explicit or ambient_host"
                    .into(),
            )
        })?;
    own_lifecycle_registry(registry, origin)
}

pub(super) fn registry_dispatch_rejection(
    tools_val: Option<&VmValue>,
    tool_name: &str,
) -> Option<ToolDispatchOutcome> {
    require_registry_membership(tools_val, tool_name)
        .err()
        .map(|message| ToolDispatchOutcome {
            result: Err(VmError::CategorizedError {
                message,
                category: ErrorCategory::ToolRejected,
            }),
            executor: None,
            handler_outcome: None,
        })
}

pub(super) fn require_registry_membership(
    tools_val: Option<&VmValue>,
    tool_name: &str,
) -> Result<(), String> {
    let Some(tools_val) = tools_val else {
        return Ok(());
    };
    let Some(dict) = tools_val.as_dict() else {
        return Err(malformed_registry_message(tool_name));
    };
    let origin = match dict.get(REGISTRY_PROVENANCE_KEY) {
        None => AgentRegistryOrigin::Explicit,
        Some(VmValue::Resource(handle))
            if handle.downcast::<AmbientHostRegistryProvenance>().is_some() =>
        {
            AgentRegistryOrigin::AmbientHost
        }
        Some(_) => return Err(malformed_registry_message(tool_name)),
    };
    let Some(VmValue::List(tools)) = dict.get("tools") else {
        return Err(malformed_registry_message(tool_name));
    };
    let entry = tools.iter().find_map(|tool| {
        let VmValue::Dict(entry) = tool else {
            return None;
        };
        (entry.get("name").map(VmValue::display).as_deref() == Some(tool_name)).then_some(entry)
    });
    let Some(entry) = entry else {
        if origin == AgentRegistryOrigin::AmbientHost {
            // `agent_loop` adds lifecycle controls to an otherwise absent
            // registry. That synthesized registry is not a declaration that
            // the host bridge has no other tools. Explicit caller registries
            // remain closed and cannot take this compatibility path.
            return Ok(());
        }
        return Err(format!(
            "tool '{tool_name}' is not present in the active agent tool registry"
        ));
    };
    match crate::tool_registry::tool_entry_allows_audience(
        entry,
        crate::tool_registry::ToolAudience::Agent,
    ) {
        Ok(true) => Ok(()),
        Ok(false) => Err(format!(
            "tool '{tool_name}' is not exposed to the agent/model adapter"
        )),
        Err(error) => Err(format!(
            "tool '{tool_name}' has invalid agent/model governance: {error}"
        )),
    }
}

fn malformed_registry_message(tool_name: &str) -> String {
    format!(
        "tool '{tool_name}' cannot be dispatched because the active agent tool registry is malformed"
    )
}

#[cfg(test)]
mod tests {
    use std::sync::{
        atomic::{AtomicBool, Ordering},
        Arc, Mutex as StdMutex,
    };

    use tokio::sync::Mutex;

    use super::*;
    use crate::value::{DictMap, VmDictExt};

    fn excluded_registry(name: &str, mut entry: DictMap) -> VmValue {
        let mut governance = DictMap::new();
        governance.insert(
            crate::value::intern_key("audiences"),
            VmValue::List(Arc::new(vec![VmValue::String("cli".into())])),
        );
        entry.insert(
            crate::value::intern_key("governance"),
            VmValue::dict(governance),
        );
        entry.put_str("name", name);
        let mut registry = DictMap::new();
        registry.insert(
            crate::value::intern_key("tools"),
            VmValue::List(Arc::new(vec![VmValue::dict(entry)])),
        );
        let raw = VmValue::dict(registry);
        crate::tool_registry::project_tools_for_audience(
            &raw,
            crate::tool_registry::ToolAudience::Agent,
        )
        .expect("project registry")
    }

    fn registry(entries: Vec<VmValue>) -> VmValue {
        let mut registry = DictMap::new();
        registry.put_str("_type", "tool_registry");
        registry.insert("tools".into(), VmValue::List(Arc::new(entries)));
        VmValue::dict(registry)
    }

    #[test]
    fn lifecycle_catalog_is_reused_but_cannot_validate_a_changed_registry() {
        let entry = crate::schema::json_to_vm_value(&serde_json::json!({
            "name": "payload", "parameters": {}, "outputSchema": {"type": "integer"}
        }));
        let owned = own_lifecycle_registry(&registry(vec![entry]), AgentRegistryOrigin::Explicit)
            .expect("own catalog");
        let first = prepared_handler_catalog(&owned, "payload").expect("prepared catalog");
        let second = prepared_handler_catalog(&owned, "payload").expect("reuse catalog");
        assert!(Arc::ptr_eq(&first, &second));
        first
            .validate_output("payload", &serde_json::json!(7))
            .expect("known positive");
        assert!(first
            .validate_output("payload", &serde_json::json!("invalid"))
            .is_err());

        let mut changed = owned.as_dict().unwrap().as_ref().clone();
        changed.insert(
            "tools".into(),
            VmValue::List(Arc::new(vec![crate::schema::json_to_vm_value(
                &serde_json::json!({
                    "name": "payload", "parameters": {}, "outputSchema": {"type": "string"}
                }),
            )])),
        );
        let current = prepared_handler_catalog(&VmValue::dict(changed), "payload")
            .expect("changed source gets its own contract");
        assert!(!Arc::ptr_eq(&first, &current));
        assert!(current
            .validate_output("payload", &serde_json::json!(7))
            .is_err());
        current
            .validate_output("payload", &serde_json::json!("current"))
            .expect("new contract reached");
    }

    fn responding_bridge(
        requests: Arc<StdMutex<Vec<serde_json::Value>>>,
    ) -> Arc<crate::bridge::HostBridge> {
        let pending = Arc::new(Mutex::new(std::collections::HashMap::new()));
        let response_pending = Arc::clone(&pending);
        let writer = Arc::new(move |line: &str| {
            let request: serde_json::Value = serde_json::from_str(line)
                .map_err(|error| format!("invalid bridge request: {error}"))?;
            requests
                .lock()
                .map_err(|_| "request lock poisoned".to_string())?
                .push(request.clone());
            let id = request["id"]
                .as_u64()
                .ok_or_else(|| "missing request id".to_string())?;
            let sender: tokio::sync::oneshot::Sender<serde_json::Value> = response_pending
                .try_lock()
                .map_err(|_| "pending lock busy".to_string())?
                .remove(&id)
                .ok_or_else(|| "request was not pending".to_string())?;
            sender
                .send(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": id,
                    "result": {"status": "stopped"},
                }))
                .map_err(|_| "bridge caller dropped".to_string())
        });
        Arc::new(crate::bridge::HostBridge::from_parts_with_writer(
            pending,
            Arc::new(AtomicBool::new(false)),
            writer,
            1,
        ))
    }

    fn tool_entry(name: &str) -> VmValue {
        let mut entry = DictMap::new();
        entry.put_str("name", name);
        VmValue::dict(entry)
    }

    #[tokio::test(flavor = "current_thread")]
    async fn lifecycle_owned_ambient_registry_reaches_host_but_explicit_empty_stays_closed() {
        let ambient = own_lifecycle_registry(
            &registry(vec![tool_entry("agent_await_resumption")]),
            AgentRegistryOrigin::AmbientHost,
        )
        .expect("own ambient lifecycle registry");
        let explicit_empty =
            own_lifecycle_registry(&registry(Vec::new()), AgentRegistryOrigin::Explicit)
                .expect("own explicit empty registry");
        let requests = Arc::new(StdMutex::new(Vec::new()));
        let bridge = responding_bridge(Arc::clone(&requests));

        let reached = super::super::agent_tools::dispatch_tool_execution_with_mcp(
            None,
            "session_stop",
            &serde_json::json!({"reason": "operator stop"}),
            Some(&ambient),
            None,
            Some(&bridge),
            0,
            0,
        )
        .await;
        assert!(
            reached.result.is_ok(),
            "ambient host call failed: {:?}",
            reached.result
        );
        assert_eq!(
            reached.executor,
            Some(crate::agent_events::ToolExecutor::HostBridge)
        );
        let reached_count = requests.lock().expect("request lock").len();
        assert_eq!(
            reached_count, 1,
            "known-positive ambient call did not reach host"
        );

        let denied = super::super::agent_tools::dispatch_tool_execution_with_mcp(
            None,
            "session_stop",
            &serde_json::json!({"reason": "operator stop"}),
            Some(&explicit_empty),
            None,
            Some(&bridge),
            0,
            0,
        )
        .await;
        assert!(denied.result.is_err());
        assert!(denied.executor.is_none());
        assert_eq!(
            requests.lock().expect("request lock").len(),
            reached_count,
            "explicit empty registry reached the host after the known-positive control"
        );
    }

    #[test]
    fn script_visible_marker_shapes_cannot_downgrade_an_explicit_registry() {
        for forged in [VmValue::Bool(false), VmValue::String("ambient_host".into())] {
            let registry = registry(Vec::new());
            let mut forged_registry = registry.as_dict().expect("registry dict").as_ref().clone();
            forged_registry.insert(REGISTRY_PROVENANCE_KEY.into(), forged);
            let error =
                require_registry_membership(Some(&VmValue::dict(forged_registry)), "session_stop")
                    .expect_err("script-visible marker must fail closed");
            assert!(error.contains("malformed"));
        }
    }

    #[tokio::test(flavor = "current_thread")]
    async fn projected_registry_blocks_excluded_host_bridge_fallthrough() {
        let bridge_called = Arc::new(AtomicBool::new(false));
        let writer_called = Arc::clone(&bridge_called);
        let bridge = Arc::new(crate::bridge::HostBridge::from_parts_with_writer(
            Arc::new(Mutex::new(std::collections::HashMap::new())),
            Arc::new(AtomicBool::new(false)),
            Arc::new(move |_| {
                writer_called.store(true, Ordering::SeqCst);
                Err("excluded tool reached host bridge".to_string())
            }),
            1,
        ));
        let mut entry = DictMap::new();
        entry.put_str("executor", "host_bridge");
        entry.put_str("host_capability", "operator.inspect");
        let tools = excluded_registry("operator_inspect", entry);

        let outcome = super::super::agent_tools::dispatch_tool_execution(
            "operator_inspect",
            &serde_json::json!({}),
            Some(&tools),
            Some(&bridge),
            0,
            0,
        )
        .await;

        assert!(!bridge_called.load(Ordering::SeqCst));
        assert!(outcome.executor.is_none());
        let error = outcome.result.unwrap_err().to_string();
        assert!(error.contains("not present in the active agent tool registry"));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn projected_registry_blocks_excluded_local_short_circuit_fallthrough() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("private.txt");
        std::fs::write(&path, "LOCAL_SHORT_CIRCUIT_RAN").expect("write fixture");
        let tools = excluded_registry("read_file", DictMap::new());

        let outcome = super::super::agent_tools::dispatch_tool_execution(
            "read_file",
            &serde_json::json!({"path": path}),
            Some(&tools),
            None,
            0,
            0,
        )
        .await;

        assert!(outcome.executor.is_none());
        let error = outcome.result.unwrap_err().to_string();
        assert!(error.contains("not present in the active agent tool registry"));
        assert!(!error.contains("LOCAL_SHORT_CIRCUIT_RAN"));
    }
}