harn-stdlib 0.10.110

Embedded Harn standard library source catalog
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
import "std/schema"

fn __agent_event_number_schema() {
  return schema_union([schema_int(), schema_float()])
}

fn __agent_event_nonnegative_int_schema() {
  return schema_int() + {min: 0}
}

fn __agent_event_digest_schema() {
  return schema_string() + {pattern: "^[a-f0-9]{64}$"}
}

/**
 * Generic schema for agent events captured by `agent_capture_events`.
 *
 * The runtime event stream is intentionally extensible: event-specific payload
 * fields live beside the required `type` discriminator. Use the narrower
 * schemas below when a consumer relies on a specific event family.
 *
 * @effects: []
 * @errors: []
 * @api_stability: experimental
 */
pub fn agent_event_schema() {
  return schema_object({type: schema_string()}, {additional_properties: schema_any()})
}

/**
 * Schema for captured event envelopes returned by `agent_capture_events`.
 *
 * @effects: []
 * @errors: []
 * @api_stability: experimental
 */
pub fn agent_event_capture_schema() {
  return schema_object(
    {result: schema_field(schema_any(), false), events: schema_list(agent_event_schema())},
    {additional_properties: schema_any()},
  )
}

/**
 * Schema for tool lifecycle events emitted by the agent loop.
 *
 * Covers `tool_call` and `tool_call_update` events that drive TUI/ACP tool
 * progress, transcript integrity audits, and replay/debug tooling.
 *
 * @effects: []
 * @errors: []
 * @api_stability: experimental
 */
pub fn agent_tool_lifecycle_event_schema() {
  const common = {
    tool_call_id: schema_string(),
    tool_name: schema_string(),
    status: schema_enum(["pending", "in_progress", "completed", "failed"]),
    raw_input: schema_field(schema_any(), false),
    raw_output: schema_field(schema_any(), false),
    error: schema_field(schema_any(), false),
    duration_ms: schema_field(__agent_event_number_schema(), false),
    execution_duration_ms: schema_field(__agent_event_number_schema(), false),
    error_category: schema_field(schema_string(), false),
    executor: schema_field(schema_any(), false),
  }
  return schema_union(
    [
      schema_object(
        common + {type: schema_literal("tool_call"), status: schema_literal("pending")},
        {additional_properties: schema_any()},
      ),
      schema_object(
        common
          + {
          type: schema_literal("tool_call_update"),
          mutation_status: schema_enum(["applied", "unchanged", "not_applied", "unknown"]),
          changed_paths: schema_field(schema_list(schema_string()), false),
          data: schema_field(schema_any(), false),
        },
        {additional_properties: schema_any()},
      ),
    ],
  )
}

/**
 * Schema for typed tool-call receipts attached to `tool_call_audit` events.
 *
 * Matches the runtime's `ToolCallReceipt` wire shape: arguments/results are
 * represented by hashes and nullable metadata fields serialize as explicit
 * `nil` values.
 *
 * @effects: []
 * @errors: []
 * @api_stability: experimental
 */
pub fn agent_tool_call_receipt_schema() {
  const nullable_string = schema_nullable(schema_string())
  return schema_object(
    {
      schema_version: schema_literal(1),
      session_id: schema_string() + {min_length: 1},
      run_id: nullable_string,
      tool_call_id: schema_string() + {min_length: 1},
      tool_name: schema_string() + {min_length: 1},
      iteration: __agent_event_nonnegative_int_schema(),
      turn_index: schema_nullable(__agent_event_nonnegative_int_schema()),
      emit_order: __agent_event_nonnegative_int_schema(),
      reason: nullable_string,
      kind: nullable_string,
      executor: schema_nullable(
        schema_enum(["harn", "host_bridge", "mcp_server", "provider_native"]),
      ),
      status: schema_enum(["ok", "schema_violation", "consent_denied", "timeout", "error"]),
      error_category: nullable_string,
      duration_ms: __agent_event_nonnegative_int_schema(),
      args_hash: __agent_event_digest_schema(),
      result_hash: schema_nullable(__agent_event_digest_schema()),
      audit: schema_any(),
      emitted_at: schema_string(),
      model: nullable_string,
      provider: nullable_string,
    },
    {additional_properties: false},
  )
}

/**
 * Schema for tool-call audit events emitted by agent tooling and subagents.
 *
 * @effects: []
 * @errors: []
 * @api_stability: experimental
 */
pub fn agent_tool_audit_event_schema() {
  return schema_object(
    {
      type: schema_literal("tool_call_audit"),
      tool_call_id: schema_string(),
      tool_name: schema_string(),
      audit: schema_field(schema_dict(schema_any()), false),
      receipt: schema_field(agent_tool_call_receipt_schema(), false),
    },
    {additional_properties: schema_any()},
  )
}

/**
 * Typed disposition/timing receipt for one call proposed in a model tool batch.
 *
 * @effects: []
 * @errors: []
 * @api_stability: experimental
 */
pub fn agent_tool_batch_disposition_receipt_schema() -> dict {
  const nullable_number = schema_union([schema_int(), schema_float(), schema_literal(nil)])
  const nullable_string = schema_nullable(schema_string())
  return schema_object(
    {
      schema: schema_literal("harn.agent_tool_batch_disposition.v1"),
      batch_id: __agent_event_digest_schema(),
      source_batch_id: schema_nullable(__agent_event_digest_schema()),
      call_index: __agent_event_nonnegative_int_schema(),
      tool_call_id: schema_string(),
      tool_name: schema_string() + {min_length: 1},
      phase: schema_enum(
        ["observation", "mutation", "process_verification", "terminal", "provider_native"],
      ),
      selected_phase: schema_enum(
        ["observation", "mutation", "process_verification", "terminal", "provider_native"],
      ),
      disposition: schema_enum(["executed", "deferred", "skipped_after_blocking_result"]),
      proposal_status: schema_enum(["new", "re_proposed"]),
      reason: schema_string() + {min_length: 1},
      planned_at_ms: __agent_event_number_schema(),
      started_at_ms: nullable_number,
      finished_at_ms: nullable_number,
      duration_ms: nullable_number,
      blocking_tool_call_id: nullable_string,
      blocking_tool_name: nullable_string,
      blocking_mutation_status: nullable_string,
    },
    {additional_properties: false},
  )
}

/**
 * Agent event carrying a tool-batch disposition receipt.
 *
 * @effects: []
 * @errors: []
 * @api_stability: experimental
 */
pub fn agent_tool_batch_disposition_event_schema() -> dict {
  return schema_object(
    {
      type: schema_literal("tool_batch_disposition"),
      receipt: agent_tool_batch_disposition_receipt_schema(),
    },
    {additional_properties: schema_any()},
  )
}

/**
 * Schema for typed checkpoint events used by control, replay, and eval
 * diagnostics.
 *
 * @effects: []
 * @errors: []
 * @api_stability: experimental
 */
pub fn agent_typed_checkpoint_event_schema() {
  return schema_object(
    {
      type: schema_literal("typed_checkpoint"),
      checkpoint: schema_object(
        {
          kind: schema_string(),
          phase: schema_field(schema_string(), false),
          iteration: schema_field(schema_int(), false),
          attempt: schema_field(schema_int(), false),
          context_overflow_recovery_attempt: schema_field(schema_int(), false),
          provider: schema_field(schema_string(), false),
          model: schema_field(schema_string(), false),
          tool_format: schema_field(schema_string(), false),
          final_wrapup: schema_field(schema_bool(), false),
        },
        {additional_properties: schema_any()},
      ),
    },
    {additional_properties: schema_any()},
  )
}

/**
 * Schema for runtime feedback injected into an agent session.
 *
 * The `kind` field is the semantic identity consumers should route on; the
 * human-facing `content` may change without invalidating the event contract.
 *
 * @effects: []
 * @errors: []
 * @api_stability: experimental
 */
pub fn agent_feedback_injected_event_schema() {
  return schema_object(
    {
      type: schema_literal("feedback_injected"),
      kind: schema_string() + {min_length: 1},
      content: schema_string(),
      streak: schema_field(__agent_event_nonnegative_int_schema(), false),
    },
    {additional_properties: schema_any()},
  )
}

/**
 * Schema for convergence-guard receipts emitted by std/agent/governors.
 *
 * @effects: []
 * @errors: []
 * @api_stability: experimental
 */
pub fn agent_convergence_guard_receipt_schema() {
  const nullable_recovery = schema_nullable(
    schema_object(
      {
        args: schema_field(schema_dict(schema_any()), false),
        verb: schema_string() + {min_length: 1},
      },
      {additional_properties: schema_any()},
    ),
  )
  return schema_object(
    {
      confidence: schema_field(__agent_event_number_schema(), false),
      evidence: schema_field(schema_dict(schema_any()), false),
      iteration: schema_field(__agent_event_nonnegative_int_schema(), false),
      kind: schema_literal("convergence_guard"),
      reason: schema_field(schema_string(), false),
      recovery: schema_field(nullable_recovery, false),
      schema: schema_literal("harn.agent_convergence_guard_receipt.v1"),
      session_id: schema_field(schema_string(), false),
      shape: schema_field(schema_string(), false),
      status: schema_enum(["fired", "skipped"]),
    },
    {additional_properties: false},
  )
}

/**
 * Schema for a one-turn exact-tool contract applied to a model request. This
 * receipt proves request actuation, not successful provider completion or tool
 * execution; those have their own lifecycle events.
 *
 * @effects: []
 * @errors: []
 * @api_stability: experimental
 */
pub fn agent_next_tool_claim_receipt_schema() -> dict {
  return schema_object(
    {
      iteration: __agent_event_nonnegative_int_schema(),
      kind: schema_literal("next_tool_claim_applied"),
      receipt_kind: schema_literal("next_tool_claim_applied"),
      schema: schema_literal("harn.agent_next_tool_claim_receipt.v1"),
      source: schema_string() + {min_length: 1},
      status: schema_literal("applied"),
      tool_name: schema_string() + {min_length: 1},
    },
    {additional_properties: false},
  )
}

fn __agent_event_contract_report(value) {
  if type_of(value) != "dict" {
    return nil
  }
  const event_type = to_string(value?.type ?? "")
  if event_type == "tool_call" && to_string(value?.status ?? "") != "pending" {
    const message = "tool_call lifecycle events must have status 'pending'"
    return {ok: false, message: message, errors: [message], issues: []}
  }
  if event_type != "tool_call_update" {
    return nil
  }
  if value?.mutation_status == nil {
    const message = "missing required key 'mutation_status'"
    return {ok: false, message: message, errors: [message], issues: []}
  }
  const mutation_status = to_string(value.mutation_status)
  if !contains(["applied", "unchanged", "not_applied", "unknown"], mutation_status) {
    const message = "mutation_status must be one of applied, unchanged, not_applied, unknown"
    return {ok: false, message: message, errors: [message], issues: []}
  }
  return nil
}

/**
 * Validate one captured agent event and return a structured schema report.
 *
 * @effects: []
 * @errors: []
 * @api_stability: experimental
 */
pub fn agent_event_report(value, schema = nil, apply_defaults = false) {
  const contract_report = __agent_event_contract_report(value)
  if contract_report != nil {
    return contract_report
  }
  return get_typed_report(value, schema ?? agent_event_schema(), apply_defaults)
}

/**
 * Validate one captured agent event and return the typed value, throwing on
 * validation failure.
 *
 * @effects: []
 * @errors: [runtime]
 * @api_stability: experimental
 */
pub fn agent_event_value(value, schema = nil, apply_defaults = false) {
  const contract_report = __agent_event_contract_report(value)
  if contract_report != nil {
    throw contract_report.message
  }
  return get_typed_value(value, schema ?? agent_event_schema(), apply_defaults)
}

/**
 * Validate an `agent_capture_events` result and return a structured report.
 *
 * @effects: []
 * @errors: []
 * @api_stability: experimental
 */
pub fn agent_event_capture_report(value, apply_defaults = false) {
  return get_typed_report(value, agent_event_capture_schema(), apply_defaults)
}

/**
 * Validate an `agent_capture_events` result and return the typed value,
 * throwing on validation failure.
 *
 * @effects: []
 * @errors: [runtime]
 * @api_stability: experimental
 */
pub fn agent_event_capture_value(value, apply_defaults = false) {
  return get_typed_value(value, agent_event_capture_schema(), apply_defaults)
}

/**
 * Capture agent events for session_id while body runs.
 *
 * @effects: [host]
 * @errors: []
 * @api_stability: experimental
 */
pub fn agent_capture_events(agent: HarnessAgent, session_id, body) {
  return agent.capture_events(session_id, body)
}