harn-vm 0.10.168

Async bytecode virtual machine for the Harn programming language
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
use super::{
    build_assistant_response_message, build_assistant_tool_message, collect_tool_schemas, json,
    normalize_tool_args, sample_tool_registry, validate_tool_args, vm_bool, vm_dict, vm_list,
    vm_str, vm_tools_to_native, VmValue,
};
use std::collections::BTreeMap;

#[test]
fn validate_tool_args_enforces_required_parameters() {
    let tools = sample_tool_registry();
    let schemas = collect_tool_schemas(Some(&tools), None);
    for args in [
        json!({"action": "create"}),
        json!({"action": "create", "path": null}),
    ] {
        let error = validate_tool_args("edit", &args, &schemas).expect_err("path is required");
        assert!(error.contains("path"));
    }
    assert!(validate_tool_args(
        "edit",
        &json!({"action": "create", "path": "test.go"}),
        &schemas,
    )
    .is_ok());
    assert!(validate_tool_args("unknown", &json!({}), &schemas).is_ok());
}

#[test]
fn agent_schema_collection_excludes_tools_without_the_agent_audience() {
    let governance = |audiences: Vec<VmValue>| vm_dict(&[("audiences", vm_list(audiences))]);
    let tools = vm_dict(&[(
        "tools",
        vm_list(vec![
            vm_dict(&[
                ("name", vm_str("agent_visible")),
                ("parameters", vm_dict(&[])),
                ("governance", governance(vec![vm_str("agent")])),
            ]),
            vm_dict(&[
                ("name", vm_str("operator_only")),
                ("parameters", vm_dict(&[])),
                ("governance", governance(vec![vm_str("cli")])),
            ]),
        ]),
    )]);

    let names = collect_tool_schemas(Some(&tools), None)
        .into_iter()
        .map(|schema| schema.name)
        .collect::<Vec<_>>();
    assert_eq!(names, ["agent_visible"]);

    let native = vm_tools_to_native(&tools, "openai", "gpt-5.4").unwrap();
    let names = native
        .iter()
        .filter_map(|tool| tool["function"]["name"].as_str())
        .collect::<Vec<_>>();
    assert_eq!(names, ["agent_visible"]);
}

fn normalization_registry() -> VmValue {
    let mut parameters = BTreeMap::new();
    parameters.insert(
        "action".to_string(),
        vm_dict(&[
            ("type", vm_str("string")),
            (
                "enum",
                vm_list(vec![vm_str("create"), vm_str("delete_range")]),
            ),
        ]),
    );
    parameters.insert(
        "overwrite".to_string(),
        vm_dict(&[("type", vm_str("bool"))]),
    );
    parameters.insert(
        "ops".to_string(),
        vm_dict(&[("type", vm_str("list")), ("required", vm_bool(false))]),
    );
    vm_dict(&[(
        "tools",
        vm_list(vec![vm_dict(&[
            ("name", vm_str("edit")),
            ("parameters", VmValue::dict(parameters)),
        ])]),
    )])
}

#[test]
fn normalize_tool_args_coerces_schema_guided_scalars_and_lists() {
    let tools = normalization_registry();
    for (raw, expected) in [
        ("True", true),
        ("true", true),
        ("FALSE", false),
        ("false", false),
    ] {
        let normalized = normalize_tool_args("edit", json!({"overwrite": raw}), Some(&tools));
        assert_eq!(normalized["overwrite"], json!(expected));
    }
    let normalized = normalize_tool_args(
        "edit",
        json!({"ops": "[{\"op\":\"replace_range\",\"range_start\":3}]"}),
        Some(&tools),
    );
    assert_eq!(
        normalized["ops"],
        json!([{"op": "replace_range", "range_start": 3}])
    );
    let malformed = "[{\"call_id\":\"1\",tool\":\"look\"";
    let normalized = normalize_tool_args("edit", json!({"ops": malformed}), Some(&tools));
    assert_eq!(normalized["ops"], json!(malformed));
    let conservative = normalize_tool_args(
        "edit",
        json!({"overwrite": "yes", "action": "true"}),
        Some(&tools),
    );
    assert_eq!(conservative["overwrite"], json!("yes"));
    assert_eq!(conservative["action"], json!("true"));
}

#[test]
fn normalize_tool_args_flattens_only_unambiguous_registered_actions() {
    let tools = normalization_registry();
    let normalized = normalize_tool_args(
        "edit",
        json!({"delete_range": {"path": "a.cpp", "range_start": 7, "range_end": 9}}),
        Some(&tools),
    );
    assert_eq!(
        normalized,
        json!({"action": "delete_range", "path": "a.cpp", "range_start": 7, "range_end": 9})
    );
    for arguments in [
        json!({"invent_action": {"path": "a.cpp"}}),
        json!({"delete_range": {"path": "a.cpp"}, "path": "outer.cpp"}),
        json!({"delete_range": "a.cpp"}),
        json!({"delete_range": {"action": "create", "path": "a.cpp"}}),
    ] {
        assert_eq!(
            normalize_tool_args("edit", arguments.clone(), Some(&tools)),
            arguments
        );
    }
}

#[test]
fn normalize_tool_args_unwraps_only_complete_heredoc_values() {
    let body = "fn f(a: u32) u32 {\n    return a << 2;\n}";
    for wrapped in [
        format!("<<EOF\n{body}\nEOF"),
        format!("  <<EOF\n{body}\nEOF\n  "),
    ] {
        let normalized = normalize_tool_args("edit", json!({"content": wrapped}), None);
        assert_eq!(normalized["content"], body);
    }
    let nested = normalize_tool_args(
        "edit",
        json!({"ops": [{"new_body": format!("<<EOF\n{body}\nEOF")}]}),
        None,
    );
    assert_eq!(nested["ops"][0]["new_body"], body);

    for value in [
        body.to_string(),
        "<<EOF\nbody\nEOF\ntrailing".to_string(),
        "# Title\n\n```rust\nfn main() {}\n```".to_string(),
    ] {
        let normalized = normalize_tool_args("edit", json!({"content": value.clone()}), None);
        assert_eq!(normalized["content"], value);
    }
}

#[test]
fn assistant_toolset_messages_preserve_member_identity() {
    let calls = [
        json!({"id": "native", "name": "screenshot", "toolset_name": "computer", "arguments": {}}),
        json!({"id": "ordinary", "name": "screenshot", "arguments": {}}),
    ];
    let message = build_assistant_response_message("", &[], &calls, None);
    assert_eq!(message["tool_calls"][0]["toolset_name"], "computer");
    assert!(message["tool_calls"][1].get("toolset_name").is_none());
}

#[test]
fn assistant_messages_use_one_provider_neutral_shape() {
    let calls = [json!({
        "id": "call_001",
        "name": "read",
        "arguments": {"path": "main.rs"},
        "thought_signature": "tool-signature",
    })];
    let message = build_assistant_tool_message("checking", &calls);
    assert_eq!(message["role"], "assistant");
    assert_eq!(message["content"], "checking");
    assert_eq!(
        message["tool_calls"],
        json!([{
            "id": "call_001",
            "name": "read",
            "arguments": {"path": "main.rs"},
            "provider_metadata": {"gemini": {"thought_signature": "tool-signature"}},
        }])
    );
    assert!(!message.to_string().contains("functionCall"));
    assert!(!message.to_string().contains("tool_use"));
}

#[test]
fn assistant_response_message_preserves_reasoning_and_gemini_signatures() {
    let calls = [json!({
        "id": "call_001",
        "name": "read",
        "arguments": {"path": "main.rs"},
        "thought_signature": "tool-signature",
    })];
    let reasoning = build_assistant_response_message("", &[], &calls, Some("inspect first"));
    assert_eq!(reasoning["reasoning"], "inspect first");

    let gemini = build_assistant_response_message(
        "checking",
        &[
            json!({
                "type": "output_text",
                "text": "checking",
                "provider_metadata": {"gemini": {"thought_signature": "text-signature"}},
            }),
            json!({
                "type": "tool_call",
                "id": "call_001",
                "name": "read",
                "arguments": {"path": "main.rs"},
                "thought_signature": "tool-signature",
            }),
        ],
        &calls,
        None,
    );
    assert_eq!(gemini["content"], "checking");
    assert_eq!(
        gemini["tool_calls"][0]["provider_metadata"]["gemini"]["thought_signature"],
        "tool-signature"
    );
}

#[test]
fn local_read_file_honors_offset_and_limit() {
    use super::super::handle_tool_locally;
    use std::io::Write;

    let dir = tempfile::tempdir().expect("tempdir");
    let path = dir.path().join("offset.txt");
    let mut file = std::fs::File::create(&path).expect("create fixture");
    for line in 1..=20 {
        writeln!(file, "line {line}").expect("write fixture");
    }
    let path = path.to_str().expect("UTF-8 path");
    let result = handle_tool_locally("read_file", &json!({"path": path, "offset": 5, "limit": 3}))
        .expect("local read");
    assert!(result.contains("5\tline 5"));
    assert!(result.contains("7\tline 7"));
    assert!(!result.contains("8\tline 8"));
    assert!(result.contains("offset=8"));
}

/// OpenAI strict mode marks every property required, so a model fills the
/// optional arguments it does not use: a host's `look` tool arrived as
/// `{"file": "calc.py", "folder": ""}` and path validation refused the empty
/// folder before the read ran. An empty optional path is absent; a required
/// one keeps its value for validation to judge.
///
/// The strict projection now lets each optional property accept `null` for
/// "not used", so `null` on an optional argument whose type rejects it is
/// absent too, at any object depth. Where `null` is a legal value, or the
/// argument is required, it stays.
#[test]
fn normalize_tool_args_drops_unused_optional_arguments() {
    let optional = |ty: &str| vm_dict(&[("type", vm_str(ty)), ("required", vm_bool(false))]);
    let mut range_fields = BTreeMap::new();
    range_fields.insert("start".to_string(), vm_dict(&[("type", vm_str("int"))]));
    range_fields.insert("end".to_string(), vm_dict(&[("type", vm_str("int"))]));
    let mut parameters = BTreeMap::new();
    parameters.insert("path".to_string(), vm_dict(&[("type", vm_str("string"))]));
    parameters.insert("file".to_string(), optional("string"));
    parameters.insert("content".to_string(), optional("string"));
    parameters.insert("limit".to_string(), optional("int"));
    parameters.insert(
        "label".to_string(),
        vm_dict(&[
            ("type", vm_list(vec![vm_str("string"), vm_str("null")])),
            ("required", vm_bool(false)),
        ]),
    );
    parameters.insert(
        "range".to_string(),
        vm_dict(&[
            ("type", vm_str("object")),
            ("required", vm_bool(false)),
            ("properties", VmValue::dict(range_fields)),
        ]),
    );
    let tools = vm_dict(&[(
        "tools",
        vm_list(vec![vm_dict(&[
            ("name", vm_str("look")),
            ("parameters", VmValue::dict(parameters)),
        ])]),
    )]);

    let normalized = normalize_tool_args(
        "look",
        json!({
            "path": "",
            "file": "",
            "content": "",
            "limit": null,
            "label": null,
            "range": {"start": 3, "end": null}
        }),
        Some(&tools),
    );
    assert_eq!(
        normalized,
        json!({"path": "", "content": "", "label": null, "range": {"start": 3}}),
        "an empty optional path and a null optional int are unused, and so is \
         a null optional field of a nested object; an empty non-path string \
         is a value, a null where null is legal stays, and a required path \
         keeps its value"
    );
    let normalized =
        normalize_tool_args("look", json!({"path": null, "range": null}), Some(&tools));
    assert_eq!(
        normalized,
        json!({"path": null}),
        "a required argument keeps an explicit null for validation to refuse"
    );
    let normalized = normalize_tool_args(
        "look",
        json!({"path": "src", "file": "calc.py", "limit": 80}),
        Some(&tools),
    );
    assert_eq!(
        normalized,
        json!({"path": "src", "file": "calc.py", "limit": 80})
    );
}

/// harn#9816: a path parameter declared only by the dispatch-time policy
/// annotations is unknown to `normalize_tool_args`, so its empty value must be
/// dropped again once those annotations are known, or path validation refuses
/// an argument the model meant to omit.
#[test]
fn dispatch_drops_empty_optional_paths_declared_by_policy_annotations() {
    let mut parameters = BTreeMap::new();
    parameters.insert(
        "folder".to_string(),
        vm_dict(&[("type", vm_str("string")), ("required", vm_bool(false))]),
    );
    parameters.insert(
        "file".to_string(),
        vm_dict(&[("type", vm_str("string")), ("required", vm_bool(true))]),
    );
    let tools = vm_dict(&[(
        "tools",
        vm_list(vec![vm_dict(&[
            ("name", vm_str("look")),
            ("parameters", VmValue::dict(parameters)),
        ])]),
    )]);
    let annotations: crate::tool_annotations::ToolAnnotations = serde_json::from_value(json!({
        "kind": "read", "arg_schema": {"path_params": ["folder", "file"]}
    }))
    .unwrap();

    let mut args = normalize_tool_args("look", json!({"file": "a.rs", "folder": ""}), Some(&tools));
    assert_eq!(
        args["folder"],
        json!(""),
        "normalization alone cannot see the policy's path params"
    );
    crate::llm::tools::messages::drop_unused_optional_path_args(
        "look",
        &mut args,
        Some(&tools),
        Some(&annotations),
    );
    assert_eq!(args, json!({"file": "a.rs"}));
    crate::tool_annotations::path_inputs::validate_arguments(&args, Some(&annotations))
        .expect("the omitted optional path no longer fails validation");

    // A required path sent empty is not an omission; it stays and is refused.
    let mut required = json!({"file": ""});
    crate::llm::tools::messages::drop_unused_optional_path_args(
        "look",
        &mut required,
        Some(&tools),
        Some(&annotations),
    );
    assert!(crate::tool_annotations::path_inputs::validate_arguments(
        &required,
        Some(&annotations)
    )
    .is_err());
}