harn-vm 0.10.69

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
//! Canonical ACP `session/request_permission` wire helpers.
//!
//! ACP v0.12.2 makes the request/response shapes for
//! `session/request_permission` canonical:
//!
//! - Request (agent -> client):
//!   `{ sessionId, toolCall: <ToolCallUpdate>, options: [{ optionId, name, kind }] }`
//! - Response (client -> agent):
//!   `{ outcome: { outcome: "selected", optionId } }` or
//!   `{ outcome: { outcome: "cancelled" } }`.
//!
//! There is no `{ outcome: "approved" }` / `{ granted }` in canonical ACP.
//!
//! This module owns *only* the canonical wire vocabulary. Harn's internal
//! permission *policy* decision (allow / deny / suspend), the
//! `ApprovalPolicy` receipt, and the out-of-band `harn.hitl.respond` HITL
//! path are deliberately untouched — they are harn semantics carried as
//! vendor extensions alongside the canonical fields.

use std::collections::BTreeSet;

use serde_json::{json, Value as JsonValue};

use crate::workspace_path::is_absolute_path_syntax;

/// Canonical ACP method for asking the client to decide a tool permission.
pub(crate) const METHOD_REQUEST_PERMISSION: &str = "session/request_permission";
/// Stable `optionId` for the canonical "allow this call" option. The
/// agent maps a `selected` response on this id to a grant.
pub(crate) const OPTION_ALLOW: &str = "allow";
/// Stable `optionId` for the canonical "reject this call" option.
pub(crate) const OPTION_REJECT: &str = "reject";

/// The canonical [`PermissionOption`]s the agent offers for a host-gated tool
/// call. Harn only offers semantics it can honor; clients may remember a
/// one-shot grant locally, but the runtime does not advertise persistence.
fn canonical_options() -> JsonValue {
    json!([
        { "optionId": OPTION_ALLOW, "name": "Allow", "kind": "allow_once" },
        { "optionId": OPTION_REJECT, "name": "Reject", "kind": "reject_once" },
    ])
}

/// Canonical ACP `RequestPermissionResponse` granting the call.
pub(crate) fn allow_response() -> JsonValue {
    json!({
        "outcome": { "outcome": "selected", "optionId": OPTION_ALLOW }
    })
}

/// Canonical ACP `RequestPermissionResponse` rejecting the call.
pub(crate) fn reject_response(reason: Option<String>) -> JsonValue {
    let mut response = json!({
        "outcome": { "outcome": "selected", "optionId": OPTION_REJECT }
    });
    if let Some(reason) = reason {
        response
            .as_object_mut()
            .expect("object")
            .insert("reason".to_string(), JsonValue::String(reason));
    }
    response
}

/// Build the canonical `session/request_permission` request params.
///
/// `tool_call` is rooted as a canonical ACP `ToolCallUpdate`
/// (`{ sessionUpdate, toolCallId, title, kind, rawInput }`). Harn's
/// vendor extensions — the HITL `approvalRequest` envelope and the
/// `policyDecision` receipt — ride along under `toolCall._meta.harn` so
/// the canonical fields stay clean while harn-aware hosts (an IDE,
/// the REST surface) can still read them.
pub(crate) fn request_params(
    session_id: Option<&str>,
    tool_call_id: &str,
    tool_name: &str,
    raw_input: &JsonValue,
    approval_request: JsonValue,
    policy_decision: &JsonValue,
    tool_descriptor: Option<JsonValue>,
    tool_kind: crate::tool_annotations::ToolKind,
) -> JsonValue {
    let mut params = serde_json::Map::new();
    if let Some(session_id) = session_id {
        params.insert("sessionId".to_string(), json!(session_id));
    }
    // The full tool descriptor (description + inputSchema, plus the rug-pull
    // `schemaChanged` flag) rides along so the host renders the *complete*
    // model-visible tool text at approval time, closing the tool-poisoning
    // visibility gap. Omitted when the catalog has no entry for the tool.
    let mut harn_meta = json!({
        "toolName": tool_name,
        "approvalRequest": approval_request,
        "policyDecision": policy_decision,
    });
    if let (Some(descriptor), Some(obj)) = (tool_descriptor, harn_meta.as_object_mut()) {
        obj.insert("toolDescriptor".to_string(), descriptor);
    }
    let content = permission_content(&approval_request);
    let locations = permission_locations(&approval_request);
    let mut tool_call = json!({
        "sessionUpdate": "tool_call_update",
        "toolCallId": tool_call_id,
        "title": tool_name,
        "kind": tool_kind,
        "rawInput": raw_input,
        "_meta": { "harn": harn_meta }
    });
    if !content.is_empty() {
        tool_call
            .as_object_mut()
            .expect("tool call object")
            .insert("content".to_string(), JsonValue::Array(content));
    }
    if !locations.is_empty() {
        tool_call
            .as_object_mut()
            .expect("tool call object")
            .insert("locations".to_string(), JsonValue::Array(locations));
    }
    params.insert("toolCall".to_string(), tool_call);
    params.insert("options".to_string(), canonical_options());
    JsonValue::Object(params)
}

fn permission_locations(approval_request: &JsonValue) -> Vec<JsonValue> {
    approval_request
        .get("evidence_refs")
        .and_then(JsonValue::as_array)
        .into_iter()
        .flatten()
        .filter(|evidence| {
            evidence.get("kind").and_then(JsonValue::as_str) == Some("file_mutation_diff")
        })
        .filter_map(|evidence| evidence.get("path").and_then(JsonValue::as_str))
        .filter(|path| is_absolute_path_syntax(path))
        .collect::<BTreeSet<_>>()
        .into_iter()
        .map(|path| json!({ "path": path }))
        .collect()
}

fn permission_content(approval_request: &JsonValue) -> Vec<JsonValue> {
    approval_request
        .get("evidence_refs")
        .and_then(JsonValue::as_array)
        .into_iter()
        .flatten()
        .filter(|evidence| evidence.get("kind").and_then(JsonValue::as_str) == Some("file_mutation_diff"))
        .filter_map(|evidence| {
            let path = evidence.get("path")?.as_str()?;
            let new_text = evidence.get("newText")?.as_str()?;
            let old_text = evidence.get("oldText").cloned().unwrap_or(JsonValue::Null);
            let preview_meta = json!({
                "source": evidence.get("source").cloned().unwrap_or_else(|| json!("pre_approval")),
                "preimageSha256": evidence.get("preimageSha256").cloned().unwrap_or(JsonValue::Null),
                "byteCount": evidence.get("byteCount").cloned().unwrap_or(JsonValue::Null),
            });
            Some(json!({
                "type": "diff",
                "path": path,
                "oldText": old_text,
                "newText": new_text,
                "_meta": {
                    "harn": {
                        "permission_preview": preview_meta
                    }
                }
            }))
        })
        .collect()
}

/// The agent's interpretation of a canonical permission response.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum WireOutcome {
    /// The selected canonical `allow_once` option.
    Allowed,
    /// `{ outcome: { outcome: "selected", optionId: "reject" } }` or a
    /// `cancelled` outcome (the client dismissed the prompt). Both stop
    /// the tool call; `cancelled` is distinguished only by the default
    /// reason.
    Rejected { reason: String },
}

/// Parse a canonical `RequestPermissionResponse` result into a
/// [`WireOutcome`].
///
/// Canonical only: the response `result` is `{ outcome: <outcome> }` where
/// `<outcome>` is `{ outcome: "selected", optionId }` or
/// `{ outcome: "cancelled" }`. A `selected` outcome whose `optionId` is
/// not the offered allow option (including a missing id) is treated as a rejection
/// — fail closed.
pub(crate) fn parse_response(response: &JsonValue) -> WireOutcome {
    let outcome = response.get("outcome");
    let kind = outcome
        .and_then(|outcome| outcome.get("outcome"))
        .and_then(JsonValue::as_str)
        .unwrap_or("");
    match kind {
        "selected" => {
            let option_id = outcome
                .and_then(|outcome| outcome.get("optionId"))
                .and_then(JsonValue::as_str)
                .unwrap_or("");
            if option_id == OPTION_ALLOW {
                WireOutcome::Allowed
            } else {
                WireOutcome::Rejected {
                    reason: response
                        .get("reason")
                        .and_then(JsonValue::as_str)
                        .map(str::to_string)
                        .unwrap_or_else(|| "host rejected the tool call".to_string()),
                }
            }
        }
        "cancelled" => WireOutcome::Rejected {
            reason: "permission request was cancelled".to_string(),
        },
        _ => WireOutcome::Rejected {
            reason: "host did not return a canonical permission outcome".to_string(),
        },
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tool_annotations::ToolKind;

    #[test]
    fn request_params_carry_canonical_options_and_tool_call() {
        let params = request_params(
            Some("session-1"),
            "tool-1",
            "edit",
            &json!({"path": "src/lib.rs"}),
            json!({"id": "tool-1", "action": "edit"}),
            &json!({"decision": "ask"}),
            None,
            ToolKind::Other,
        );
        assert_eq!(params["sessionId"], "session-1");
        assert_eq!(params["toolCall"]["sessionUpdate"], "tool_call_update");
        assert_eq!(params["toolCall"]["toolCallId"], "tool-1");
        assert_eq!(params["toolCall"]["title"], "edit");
        assert_eq!(params["toolCall"]["kind"], "other");
        assert_eq!(params["toolCall"]["rawInput"]["path"], "src/lib.rs");
        assert_eq!(params["toolCall"]["_meta"]["harn"]["toolName"], "edit");
        assert_eq!(
            params["toolCall"]["_meta"]["harn"]["policyDecision"]["decision"],
            "ask"
        );
        let options = params["options"].as_array().expect("options array");
        assert_eq!(options.len(), 2);
        assert_eq!(options[0]["optionId"], OPTION_ALLOW);
        assert_eq!(options[0]["kind"], "allow_once");
        assert_eq!(options[1]["optionId"], OPTION_REJECT);
        assert_eq!(options[1]["kind"], "reject_once");
    }

    #[test]
    fn request_params_project_file_evidence_into_canonical_diff_content() {
        let params = request_params(
            Some("session-1"),
            "tool-1",
            "edit",
            &json!({"path": "src/lib.rs"}),
            json!({
                "id": "tool-1",
                "action": "edit",
                "evidence_refs": [
                    {
                        "kind": "file_mutation_diff",
                        "path": "/workspace/src/lib.rs",
                        "oldText": "old\n",
                        "newText": "new\n",
                        "preimageSha256": "abc123",
                        "byteCount": 4,
                        "source": "pre_approval"
                    },
                    {
                        "kind": "file_mutation_diff",
                        "path": "/workspace/src/a.rs",
                        "newText": "new\n"
                    },
                    {
                        "kind": "file_mutation_diff",
                        "path": "/workspace/src/lib.rs",
                        "newText": "duplicate path\n"
                    },
                    {
                        "kind": "file_mutation_diff",
                        "path": r"C:\workspace\src\win.rs",
                        "newText": "windows path\n"
                    },
                    {
                        "kind": "command",
                        "path": "/workspace/ignored.rs"
                    },
                    {
                        "kind": "file_mutation_diff",
                        "path": "relative/not-valid-acp-location.rs",
                        "newText": "ignored\n"
                    }
                ]
            }),
            &json!({"decision": "ask"}),
            None,
            ToolKind::Edit,
        );

        let diff = &params["toolCall"]["content"][0];
        assert_eq!(diff["type"], "diff");
        assert_eq!(diff["path"], "/workspace/src/lib.rs");
        assert_eq!(diff["oldText"], "old\n");
        assert_eq!(diff["newText"], "new\n");
        assert_eq!(
            diff["_meta"]["harn"]["permission_preview"]["preimageSha256"],
            "abc123"
        );
        assert_eq!(
            params["toolCall"]["locations"],
            json!([
                { "path": "/workspace/src/a.rs" },
                { "path": "/workspace/src/lib.rs" },
                { "path": r"C:\workspace\src\win.rs" }
            ]),
            "file scopes are canonical, deterministic, and deduplicated"
        );
    }

    #[test]
    fn request_params_omit_locations_without_file_evidence() {
        let params = request_params(
            Some("session-1"),
            "tool-1",
            "run",
            &json!({"command": "pwd"}),
            json!({"id": "tool-1", "evidence_refs": []}),
            &json!({"decision": "ask"}),
            None,
            ToolKind::Execute,
        );

        assert!(params["toolCall"].get("locations").is_none());
    }

    #[test]
    fn request_params_use_the_declared_acp_tool_kind() {
        let params = request_params(
            Some("session-1"),
            "tool-1",
            "edit",
            &json!({"path": "src/lib.rs"}),
            json!({"id": "tool-1", "evidence_refs": []}),
            &json!({"decision": "ask"}),
            None,
            ToolKind::Edit,
        );

        assert_eq!(params["toolCall"]["kind"], "edit");
    }

    #[test]
    fn selected_allow_is_allowed() {
        let response = allow_response();
        assert_eq!(parse_response(&response), WireOutcome::Allowed);
    }

    #[test]
    fn every_offered_option_has_a_defined_parser_outcome() {
        for option in canonical_options().as_array().expect("options") {
            let option_id = option["optionId"].as_str().expect("option id");
            let kind = option["kind"].as_str().expect("option kind");
            let response = json!({
                "outcome": { "outcome": "selected", "optionId": option_id }
            });
            assert_eq!(
                matches!(parse_response(&response), WireOutcome::Allowed),
                kind.starts_with("allow_"),
                "offered option {option_id} ({kind})"
            );
        }
    }

    #[test]
    fn selected_reject_is_rejected() {
        let response = reject_response(None);
        assert!(matches!(
            parse_response(&response),
            WireOutcome::Rejected { .. }
        ));
    }

    #[test]
    fn cancelled_is_rejected() {
        let response = json!({"outcome": {"outcome": "cancelled"}});
        match parse_response(&response) {
            WireOutcome::Rejected { reason } => assert!(reason.contains("cancelled")),
            other => panic!("expected rejection, got {other:?}"),
        }
    }

    #[test]
    fn non_canonical_outcome_fails_closed() {
        assert!(matches!(
            parse_response(&json!({"outcome": "approved"})),
            WireOutcome::Rejected { .. }
        ));
        assert!(matches!(
            parse_response(&json!({"granted": true})),
            WireOutcome::Rejected { .. }
        ));
    }

    #[test]
    fn selected_missing_option_id_fails_closed() {
        let response = json!({"outcome": {"outcome": "selected"}});
        assert!(matches!(
            parse_response(&response),
            WireOutcome::Rejected { .. }
        ));
    }
}