harn-stdlib 0.10.200

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
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
import "std/schema"

/** The callback result is retained as a VM value; event payloads are JSON. */
pub type AgentEventCapture<T> = {result: T, events: list<unknown>}

pub type AgentEvent = {type: string, ...dict}

pub type AgentValidatedEventCapture = {result?: unknown, events: list<AgentEvent>, ...dict}

pub type AgentMutationStatus = "applied" | "unchanged" | "not_applied" | "unknown"

pub type AgentToolExecutor = "harn" | "host_bridge" | "mcp_server" | "provider_native"

type AgentToolEventFields = {
  tool_call_id: string,
  tool_name: string,
  raw_input?: unknown,
  raw_output?: unknown,
  error?: unknown,
  duration_ms?: int | float,
  execution_duration_ms?: int | float,
  error_category?: string,
  executor?: unknown,
}

pub type AgentToolPendingEvent = {
  type: "tool_call",
  status: "pending",
  ...AgentToolEventFields,
  ...dict,
}

pub type AgentToolUpdateEvent = {
  type: "tool_call_update",
  status: "pending" | "in_progress" | "completed" | "failed",
  mutation_status: AgentMutationStatus,
  changed_paths?: list<string>,
  data?: unknown,
  ...AgentToolEventFields,
  ...dict,
}

pub type AgentToolLifecycleEvent = AgentToolPendingEvent | AgentToolUpdateEvent

pub type AgentToolCallReceipt = {
  schema_version: 1,
  session_id: string,
  run_id: string?,
  tool_call_id: string,
  tool_name: string,
  iteration: int,
  turn_index: int?,
  emit_order: int,
  reason: string?,
  kind: string?,
  executor: AgentToolExecutor?,
  status: "ok" | "schema_violation" | "consent_denied" | "timeout" | "error",
  error_category: string?,
  duration_ms: int,
  args_hash: string,
  result_hash: string?,
  audit: unknown,
  emitted_at: string,
  model: string?,
  provider: string?,
}

pub type AgentToolAuditEvent = {
  type: "tool_call_audit",
  tool_call_id: string,
  tool_name: string,
  audit?: dict<string, unknown>,
  receipt?: AgentToolCallReceipt,
  ...dict,
}

pub type AgentToolBatchPhase = "observation" \
  | "mutation" \
  | "process_verification" \
  | "terminal" \
  | "provider_native"

pub type AgentToolBatchDispositionReceipt = {
  schema: "harn.agent_tool_batch_disposition.v1",
  batch_id: string,
  source_batch_id: string?,
  call_index: int,
  tool_call_id: string,
  tool_name: string,
  phase: AgentToolBatchPhase,
  selected_phase: AgentToolBatchPhase,
  disposition: "executed" | "deferred" | "skipped_after_blocking_result",
  proposal_status: "new" | "re_proposed",
  reason: string,
  planned_at_ms: int | float,
  started_at_ms: int | float | nil,
  finished_at_ms: int | float | nil,
  duration_ms: int | float | nil,
  blocking_tool_call_id: string?,
  blocking_tool_name: string?,
  blocking_mutation_status: string?,
}

pub type AgentToolBatchDispositionEvent = {
  type: "tool_batch_disposition",
  receipt: AgentToolBatchDispositionReceipt,
  ...dict,
}

pub type AgentTypedCheckpoint = {
  kind: string,
  phase?: string,
  iteration?: int,
  attempt?: int,
  context_overflow_recovery_attempt?: int,
  provider?: string,
  model?: string,
  tool_format?: string,
  final_wrapup?: bool,
  ...dict,
}

pub type AgentTypedCheckpointEvent = {
  type: "typed_checkpoint",
  checkpoint: AgentTypedCheckpoint,
  ...dict,
}

pub type AgentFeedbackInjectedEvent = {
  type: "feedback_injected",
  kind: string,
  content: string,
  streak?: int,
  ...dict,
}

pub type AgentNextToolClaimReceipt = {
  iteration: int,
  kind: "next_tool_claim_applied",
  receipt_kind: "next_tool_claim_applied",
  schema: "harn.agent_next_tool_claim_receipt.v1",
  source: string,
  status: "applied",
  tool_name: string,
}

/**
 * A shape owns presence and field types. Refinements retain the stricter
 * value constraints, including optional fields that reject explicit nil.
 */
fn __agent_event_fields<T>(shape: Schema<T>, constraints: dict) -> Schema<T> {
  return schema_refine(
    shape,
    schema_object(
      constraints.map_values({ rule -> schema_field(rule, false) }),
      {additional_properties: schema_any()},
    ),
  )
}

fn __agent_closed_event_schema<T>(shape: Schema<T>) -> Schema<T> {
  return schema_refine(shape, schema_extend(shape, {additional_properties: false}))
}

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() -> Schema<AgentEvent> {
  return schema_of(AgentEvent)
}

/**
 * Schema for captured event envelopes returned by `agent_capture_events`.
 *
 * @effects: []
 * @errors: []
 * @api_stability: experimental
 */
pub fn agent_event_capture_schema() -> Schema<AgentValidatedEventCapture> {
  return schema_of(AgentValidatedEventCapture)
}

/**
 * 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() -> Schema<AgentToolLifecycleEvent> {
  return schema_refine(
    __agent_event_fields(
      schema_of(AgentToolLifecycleEvent),
      {
        duration_ms: __agent_event_number_schema(),
        execution_duration_ms: __agent_event_number_schema(),
        error_category: schema_string(),
      },
    ),
    schema_union(
      [
        schema_of(AgentToolPendingEvent),
        __agent_event_fields(
          schema_of(AgentToolUpdateEvent),
          {changed_paths: schema_list(schema_string())},
        ),
      ],
    ),
  )
}

/**
 * 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() -> Schema<AgentToolCallReceipt> {
  return __agent_event_fields(
    __agent_closed_event_schema(schema_of(AgentToolCallReceipt)),
    {
      session_id: schema_string() + {min_length: 1},
      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(),
      duration_ms: __agent_event_nonnegative_int_schema(),
      args_hash: __agent_event_digest_schema(),
      result_hash: schema_nullable(__agent_event_digest_schema()),
    },
  )
}

/**
 * Schema for tool-call audit events emitted by agent tooling and subagents.
 *
 * @effects: []
 * @errors: []
 * @api_stability: experimental
 */
pub fn agent_tool_audit_event_schema() -> Schema<AgentToolAuditEvent> {
  return __agent_event_fields(
    schema_of(AgentToolAuditEvent),
    {audit: schema_dict(schema_any()), receipt: agent_tool_call_receipt_schema()},
  )
}

/**
 * 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() -> Schema<AgentToolBatchDispositionReceipt> {
  return __agent_event_fields(
    __agent_closed_event_schema(schema_of(AgentToolBatchDispositionReceipt)),
    {
      batch_id: __agent_event_digest_schema(),
      source_batch_id: schema_nullable(__agent_event_digest_schema()),
      call_index: __agent_event_nonnegative_int_schema(),
      tool_name: schema_string() + {min_length: 1},
      reason: schema_string() + {min_length: 1},
    },
  )
}

/**
 * Agent event carrying a tool-batch disposition receipt.
 *
 * @effects: []
 * @errors: []
 * @api_stability: experimental
 */
pub fn agent_tool_batch_disposition_event_schema() -> Schema<AgentToolBatchDispositionEvent> {
  return __agent_event_fields(
    schema_of(AgentToolBatchDispositionEvent),
    {receipt: agent_tool_batch_disposition_receipt_schema()},
  )
}

/**
 * Schema for typed checkpoint events used by control, replay, and eval
 * diagnostics.
 *
 * @effects: []
 * @errors: []
 * @api_stability: experimental
 */
pub fn agent_typed_checkpoint_event_schema() -> Schema<AgentTypedCheckpointEvent> {
  return __agent_event_fields(
    schema_of(AgentTypedCheckpointEvent),
    {
      checkpoint: __agent_event_fields(
        schema_of(AgentTypedCheckpoint),
        {
          phase: schema_string(),
          iteration: schema_int(),
          attempt: schema_int(),
          context_overflow_recovery_attempt: schema_int(),
          provider: schema_string(),
          model: schema_string(),
          tool_format: schema_string(),
          final_wrapup: schema_bool(),
        },
      ),
    },
  )
}

/**
 * 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() -> Schema<AgentFeedbackInjectedEvent> {
  return __agent_event_fields(
    schema_of(AgentFeedbackInjectedEvent),
    {kind: schema_string() + {min_length: 1}, streak: __agent_event_nonnegative_int_schema()},
  )
}

/**
 * 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() -> Schema<AgentNextToolClaimReceipt> {
  return __agent_event_fields(
    __agent_closed_event_schema(schema_of(AgentNextToolClaimReceipt)),
    {
      iteration: __agent_event_nonnegative_int_schema(),
      source: schema_string() + {min_length: 1},
      tool_name: schema_string() + {min_length: 1},
    },
  )
}

type AgentEventContractFailure = SchemaReport<never> & {ok: bool}

fn __agent_event_contract_report(value: unknown) -> AgentEventContractFailure? {
  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<T>(
  value: unknown,
  schema: dict | Schema<T> | nil = nil,
  apply_defaults: bool = false,
) -> SchemaReport<T> {
  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<T>(
  value: unknown,
  schema: dict | Schema<T> | nil = nil,
  apply_defaults: bool = false,
) -> T {
  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: unknown,
  apply_defaults: bool = false,
) -> SchemaReport<AgentValidatedEventCapture> {
  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: unknown,
  apply_defaults: bool = false,
) -> AgentValidatedEventCapture {
  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<T>(
  agent: HarnessAgent,
  session_id: string,
  body: fn() -> T,
) -> AgentEventCapture<T> {
  const captured = agent.capture_events(session_id, body)
  return {result: captured.result, events: captured.events}
}