harn-cli 0.10.41

CLI for the Harn programming language — run, test, REPL, format, and lint
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
use harn_serve::adapters::acp::{
    ACP_PROMPT_ERROR_DATA_SCHEMA, ACP_SCHEMA_COMPATIBILITY, HARN_AGENT_EVENT_KINDS,
    HARN_AGENT_EVENT_METHOD, HARN_CONTENT_EXTENSION_FIELDS, HARN_PROMPT_RESULT_EXTENSION_FIELDS,
    HARN_PROVIDER_CATALOG_METHOD, HARN_SESSION_UPDATE_EXTENSIONS,
    HARN_TOOL_LIFECYCLE_EXTENSION_FIELDS,
};

use super::constants::*;
use super::support::*;
use super::values::*;

/// Emit the Rust binding.
///
/// Downstream hosts vendor this module verbatim. It carries both the canonical
/// wire-name vocabulary and serde DTOs for the permission and agent-event
/// paths, where a hand-maintained parallel shape would otherwise drift.
#[cfg(test)]
pub(super) fn generate_rust() -> String {
    generate_rust_for_version(env!("CARGO_PKG_VERSION"))
}

pub(super) fn generate_rust_for_version(artifact_version: &str) -> String {
    let mut out = String::new();
    out.push_str("// GENERATED by `harn dump-protocol-artifacts` - do not edit by hand.\n");
    out.push_str("// Source: Harn adapter schemas and Rust wire vocabulary.\n\n");
    out.push_str("//! Rust bindings for Harn's host/integrator protocol surface.\n");
    out.push_str("//!\n");
    out.push_str("//! Mirrors the TypeScript, Swift, Python, and Go artifacts generated\n");
    out.push_str("//! alongside this module. Constants carry literal JSON wire strings, while\n");
    out.push_str("//! serde DTOs own the canonical ACP permission and Harn agent-event shapes.\n");
    out.push_str("//! Adding a wire value or optional field is minor-version compatible.\n");
    out.push_str("#![allow(dead_code)]\n\n");
    out.push_str("use serde::{Deserialize, Deserializer, Serialize, Serializer};\n");
    out.push_str("use serde_json::{Map, Value};\n\n");

    out.push_str("/// Harn release that generated this binding.\n");
    out.push_str(&format!(
        "pub const HARN_PROTOCOL_ARTIFACT_VERSION: &str = {};\n\n",
        json_string_literal(artifact_version)
    ));
    out.push_str("/// Upstream ACP schema version Harn tracks.\n");
    out.push_str(&format!(
        "pub const ACP_SCHEMA_COMPATIBILITY: &str = {};\n\n",
        json_string_literal(ACP_SCHEMA_COMPATIBILITY)
    ));
    out.push_str("/// JSON-RPC method for `_harn/agentEvent` extension notifications.\n");
    out.push_str(&format!(
        "pub const HARN_AGENT_EVENT_METHOD: &str = {};\n\n",
        json_string_literal(HARN_AGENT_EVENT_METHOD)
    ));
    out.push_str("/// JSON-RPC method for Harn's provider catalog extension.\n");
    out.push_str(&format!(
        "pub const HARN_PROVIDER_CATALOG_METHOD: &str = {};\n\n",
        json_string_literal(HARN_PROVIDER_CATALOG_METHOD)
    ));
    out.push_str("/// Schema discriminator for typed `session/prompt` JSON-RPC error data.\n");
    out.push_str(&format!(
        "pub const ACP_PROMPT_ERROR_DATA_SCHEMA: &str = {};\n\n",
        json_string_literal(ACP_PROMPT_ERROR_DATA_SCHEMA)
    ));
    out.push_str(&rust_wire_types());

    out.push_str(&rust_const_group(
        "ACP_AGENT_METHOD",
        "ACP_AGENT_METHODS",
        "Stable host-facing ACP agent methods (matches the TypeScript/Swift/Python/Go bindings).",
        ACP_AGENT_METHODS,
    ));
    out.push_str(&rust_const_group(
        "ACP_DISPATCHED_METHOD",
        "ACP_DISPATCHED_METHODS",
        "Every JSON-RPC method the ACP adapter actually dispatches, including the \
         workspace-management, workflow-control, and HITL methods the stable \
         bindings do not yet expose as typed enums. Reconciled against the \
         `match` arms in `harn-serve`'s ACP adapter.",
        ACP_DISPATCHED_METHODS,
    ));
    out.push_str(&rust_const_group(
        "ACP_TRANSPORT_CONTROL_METHOD",
        "ACP_TRANSPORT_CONTROL_METHODS",
        "ACP control frames consumed by the transport before regular adapter \
         dispatch.",
        ACP_TRANSPORT_CONTROL_METHODS,
    ));
    let handled_methods =
        concat_unique_wire_values(&[ACP_TRANSPORT_CONTROL_METHODS, ACP_DISPATCHED_METHODS]);
    out.push_str(&rust_const_group_owned(
        "ACP_HANDLED_METHOD",
        "ACP_HANDLED_METHODS",
        "Every inbound ACP method Harn handles, whether by transport preemption \
         or regular adapter dispatch.",
        &handled_methods,
    ));
    out.push_str(&rust_const_group(
        "ACP_CLIENT_METHOD",
        "ACP_CLIENT_METHODS",
        "ACP client methods the agent calls back into the host for.",
        ACP_CLIENT_METHODS,
    ));
    out.push_str(&rust_const_group(
        "HARN_SESSION_TIMELINE_METHOD",
        "HARN_SESSION_TIMELINE_METHODS",
        "Session-timeline extension methods Harn accepts or emits.",
        HARN_SESSION_TIMELINE_METHODS,
    ));
    out.push_str(&rust_const_group(
        "ACP_AGENT_NOTIFICATION",
        "ACP_AGENT_NOTIFICATIONS",
        "ACP notifications the agent emits to the host.",
        ACP_AGENT_NOTIFICATIONS,
    ));

    let session_updates = all_acp_session_updates();
    out.push_str(&rust_const_group_owned(
        "ACP_SESSION_UPDATE",
        "ACP_SESSION_UPDATES",
        "Every `session/update` discriminator Harn emits (canonical ACP variants \
         plus Harn extensions), the union the Swift binding exposes as \
         `acpSessionUpdateExtensions` merged with the base ACP set.",
        &session_updates,
    ));
    out.push_str(&rust_const_group(
        "HARN_ACP_SESSION_UPDATE_EXTENSION",
        "HARN_ACP_SESSION_UPDATE_EXTENSIONS",
        "Harn-specific `session/update` discriminators beyond the canonical ACP \
         set (the values Swift publishes as `acpSessionUpdateExtensions`).",
        HARN_SESSION_UPDATE_EXTENSIONS,
    ));
    out.push_str(&rust_const_group(
        "HARN_AGENT_EVENT_KIND",
        "HARN_AGENT_EVENT_KINDS",
        "Pipeline-loop milestone kinds emitted via `_harn/agentEvent`.",
        HARN_AGENT_EVENT_KINDS,
    ));
    out.push_str(&rust_const_group_owned(
        "AGENT_TERMINAL_CLASS",
        "AGENT_TERMINAL_CLASSES",
        "Stable terminal classes carried by typed ACP prompt-error data.",
        &agent_terminal_class_values(),
    ));
    out.push_str(&rust_const_group_owned(
        "AGENT_TERMINAL_KIND",
        "AGENT_TERMINAL_KINDS",
        "Producer-owned agent terminal outcome kinds.",
        &agent_terminal_kind_values(),
    ));
    out.push_str(&rust_const_group_owned(
        "AGENT_TERMINAL_OWNER",
        "AGENT_TERMINAL_OWNERS",
        "Owners attributed by producer-owned agent terminal outcomes.",
        &agent_terminal_owner_values(),
    ));
    out.push_str(&rust_const_group(
        "HARN_PROMPT_RESULT_EXTENSION_FIELD",
        "HARN_PROMPT_RESULT_EXTENSION_FIELDS",
        "`_meta.harn` extension keys on successful ACP prompt results.",
        HARN_PROMPT_RESULT_EXTENSION_FIELDS,
    ));
    out.push_str(&rust_const_group(
        "HARN_CONTENT_EXTENSION_FIELD",
        "HARN_CONTENT_EXTENSION_FIELDS",
        "`_meta.harn` extension keys Harn attaches to ACP content.",
        HARN_CONTENT_EXTENSION_FIELDS,
    ));
    out.push_str(&rust_const_group(
        "HARN_TOOL_LIFECYCLE_EXTENSION_FIELD",
        "HARN_TOOL_LIFECYCLE_EXTENSION_FIELDS",
        "`_meta.harn` tool-lifecycle extension keys on tool_call / \
         tool_call_update notifications.",
        HARN_TOOL_LIFECYCLE_EXTENSION_FIELDS,
    ));

    out
}

fn rust_wire_types() -> String {
    let mut out = String::from(
        r#"/// Closed ACP permission-option vocabulary.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ACPPermissionOptionKind {
    AllowOnce,
    AllowAlways,
    RejectOnce,
    RejectAlways,
}

/// One option offered by `session/request_permission`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ACPPermissionOption {
    pub option_id: String,
    pub name: String,
    pub kind: ACPPermissionOptionKind,
}

/// Canonical ACP tool-call fields carried by a permission request.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ACPPermissionToolCall {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub session_update: Option<String>,
    pub tool_call_id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub kind: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub content: Option<Vec<Value>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub raw_input: Option<Value>,
    #[serde(default, rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub meta: Option<Value>,
}

/// Params for the ACP `session/request_permission` client request.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ACPSessionRequestPermissionParams {
    pub session_id: String,
    pub tool_call: ACPPermissionToolCall,
    pub options: Vec<ACPPermissionOption>,
}

/// User decision returned to an ACP permission request.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "outcome", rename_all = "snake_case")]
pub enum ACPPermissionOutcome {
    Selected {
        #[serde(rename = "optionId")]
        option_id: String,
    },
    Cancelled,
}

/// Result envelope for an ACP `session/request_permission` client request.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ACPSessionRequestPermissionResult {
    pub outcome: ACPPermissionOutcome,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

/// Harn agent-event discriminator.
///
/// Unknown values remain lossless so older clients can ignore newly added
/// events while still proxying or recording the original notification.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum HarnAgentEventKind {
"#,
    );
    for value in HARN_AGENT_EVENT_KINDS {
        out.push_str("    ");
        out.push_str(&rust_type_name(value));
        out.push_str(",\n");
    }
    out.push_str("    Other(String),\n}\n\n");

    out.push_str("impl HarnAgentEventKind {\n");
    out.push_str("    pub fn as_str(&self) -> &str {\n");
    out.push_str("        match self {\n");
    for value in HARN_AGENT_EVENT_KINDS {
        out.push_str("            Self::");
        out.push_str(&rust_type_name(value));
        out.push_str(" => ");
        out.push_str(&json_string_literal(value));
        out.push_str(",\n");
    }
    out.push_str("            Self::Other(value) => value,\n");
    out.push_str("        }\n");
    out.push_str("    }\n");
    out.push_str("}\n\n");

    out.push_str(
        r"impl Serialize for HarnAgentEventKind {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for HarnAgentEventKind {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        Ok(match value.as_str() {
",
    );
    for value in HARN_AGENT_EVENT_KINDS {
        out.push_str("            ");
        out.push_str(&json_string_literal(value));
        out.push_str(" => Self::");
        out.push_str(&rust_type_name(value));
        out.push_str(",\n");
    }
    out.push_str("            _ => Self::Other(value),\n");
    out.push_str("        })\n");
    out.push_str("    }\n");
    out.push_str("}\n\n");

    out.push_str(
        r#"/// Params carried by a `_harn/agentEvent` notification.
///
/// `sessionId` and `kind` are stable. Kind-specific fields stay flattened so
/// the generated binding round-trips every current and future event payload.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct HarnAgentEventParams {
    pub session_id: String,
    pub kind: HarnAgentEventKind,
    #[serde(default, flatten)]
    pub fields: Map<String, Value>,
}

/// JSON-RPC envelope for `_harn/agentEvent`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HarnAgentEventNotification {
    pub jsonrpc: String,
    pub method: String,
    pub params: HarnAgentEventParams,
    #[serde(default, flatten)]
    pub fields: Map<String, Value>,
}

"#,
    );
    out
}

/// Render a `pub const` per wire value plus a published slice of all of them.
pub(super) fn rust_const_group(
    const_prefix: &str,
    slice_name: &str,
    doc: &str,
    values: &[&str],
) -> String {
    rust_const_group_owned(const_prefix, slice_name, doc, &strs_to_strings(values))
}

pub(super) fn rust_const_group_owned(
    const_prefix: &str,
    slice_name: &str,
    doc: &str,
    values: &[String],
) -> String {
    let mut out = String::new();
    for value in values {
        out.push_str(&format!(
            "pub const {}: &str = {};\n",
            rust_const_name(const_prefix, value),
            json_string_literal(value)
        ));
    }
    out.push('\n');
    out.push_str(&rust_doc_comment(doc));
    out.push_str(&format!("pub const {slice_name}: &[&str] = &[\n"));
    for value in values {
        out.push_str("    ");
        out.push_str(&json_string_literal(value));
        out.push_str(",\n");
    }
    out.push_str("];\n\n");
    out
}

/// Build a valid SCREAMING_SNAKE_CASE Rust const identifier from a wire value.
///
/// Wire values carry `/`, `.`, `-`, and `_` separators (e.g. `session/prompt`,
/// `harn.hitl.respond`, `tool_call_update`); all collapse to `_`, runs are
/// merged, and a leading digit is prefixed with `_`.
pub(super) fn rust_const_name(prefix: &str, value: &str) -> String {
    let mut suffix = String::with_capacity(value.len());
    for ch in value.chars() {
        if ch.is_ascii_alphanumeric() {
            suffix.extend(ch.to_uppercase());
        } else {
            suffix.push('_');
        }
    }
    let suffix = collapse_repeated_underscores(suffix.trim_matches('_'));
    let name = if suffix.is_empty() {
        prefix.to_string()
    } else {
        format!("{prefix}_{suffix}")
    };
    if name.chars().next().is_some_and(|ch| ch.is_ascii_digit()) {
        format!("_{name}")
    } else {
        name
    }
}

pub(super) fn rust_type_name(value: &str) -> String {
    let mut out = String::new();
    let mut capitalize = true;
    for ch in value.chars() {
        if ch.is_ascii_alphanumeric() {
            if capitalize {
                out.extend(ch.to_uppercase());
            } else {
                out.push(ch);
            }
            capitalize = false;
        } else {
            capitalize = true;
        }
    }
    if out.chars().next().is_some_and(|ch| ch.is_ascii_digit()) {
        out.insert(0, '_');
    }
    out
}

pub(super) fn rust_doc_comment(doc: &str) -> String {
    let mut out = String::new();
    // Collapse the whitespace that Rust string continuations introduce so the
    // emitted doc comment is a single tidy line.
    let normalized = doc.split_whitespace().collect::<Vec<_>>().join(" ");
    out.push_str("/// ");
    out.push_str(&normalized);
    out.push('\n');
    out
}