harn-stdlib 0.10.130

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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
pub import { agent_autocompact_if_needed, agent_emergency_compact } from "std/agent/autocompact"
pub import {
  agent_budget_post_call_blocked,
  agent_budget_post_call_stop_reason,
  agent_budget_pre_call_blocked,
} from "std/agent/budget"
import { AgentLoopTerminalError, AgentResult } from "std/agent/contracts"
pub import {
  agent_loop_apply_command,
  agent_loop_control_invoke,
  agent_loop_snapshot_state,
} from "std/agent/control"
pub import { agent_daemon_snapshot, agent_daemon_step } from "std/agent/daemon"
pub import {
  agent_feedback_compose,
  agent_feedback_emit,
  agent_feedback_tool_example,
} from "std/agent/feedback"
pub import {
  __agent_input_guardrail_fail_open,
  __agent_input_guardrail_normalize,
} from "std/agent/guardrails"
pub import {
  agent_completion_adjudicator_declared,
  agent_completion_review,
  agent_evaluate_completion,
  agent_verify_completion_judge_cap,
} from "std/agent/judge"
pub import { agent_invoke_llm } from "std/agent/llm_dispatch"
import { __drain_audit_flushes } from "std/agent/loop_audit_flushes"
pub import {
  agent_mcp_admit_bootstrap,
  agent_mcp_bootstrap_if_needed,
  agent_mcp_mount_additional,
} from "std/agent/mcp"
pub import {
  agent_monologue_actuation_observe_completed_dispatch,
  agent_monologue_actuation_take_for_turn,
} from "std/agent/monologue_actuation"
pub import {
  agent_loop_options,
  agent_merge_llm_options,
  agent_refresh_tool_format_for_route,
  agent_sanitize_model_options,
  agent_tool_format,
} from "std/agent/options"
pub import { agent_compute_post_turn, agent_compute_terminal_callback } from "std/agent/postturn"
pub import { agent_prefill_eligibility, agent_take_one_shot_prefill } from "std/agent/prefill"
pub import {
  agent_build_turn_messages,
  agent_build_turn_system_fragments,
  agent_completion_prompt_bindings,
  agent_tool_call_paradigm,
} from "std/agent/preflight"
pub import { agent_dispatch_tool_call, agent_parse_tool_calls } from "std/agent/primitives"
pub import { agent_progress_apply_options } from "std/agent/progress"
pub import { native_tool_contract_feedback_prompt, parse_guidance_prompt } from "std/agent/prompts"
pub import {
  agent_required_tools_enforce,
  agent_required_tools_inject_feedback,
  agent_required_tools_missing_from_session,
} from "std/agent/required_tools"
pub import { agent_scratchpad_init, agent_scratchpad_reorganize_if_due } from "std/agent/scratchpad"
pub import { agent_skills_match } from "std/agent/skills"
pub import {
  agent_stall_apply_result,
  agent_stall_clear_current_failure,
  agent_stall_initial_state,
  agent_stall_inject_feedback,
  agent_stall_no_net_progress,
  agent_stall_observe_completed_dispatch,
  agent_stall_observe_tool_calls,
  agent_stall_repair_config,
  agent_stall_repeated_verified_pass,
  agent_stall_verified_write_satisfied,
} from "std/agent/stall"
pub import {
  agent_stance_apply,
  agent_stance_post_turn,
  agent_stance_prepare,
} from "std/agent/stance"
pub import {
  AgentSessionFinalization,
  agent_emit_event,
  agent_record_native_tool_fallback,
  agent_reminder_providers_fire,
  agent_session_commit_directives,
  agent_session_drain_bridge_injections,
  agent_session_drain_feedback,
  agent_session_drain_host_injections,
  agent_session_finalize,
  agent_session_flush,
  agent_session_init,
  agent_session_inject_feedback,
  agent_session_messages,
  agent_session_pair_orphaned_tool_use,
  agent_session_pop_last_assistant,
  agent_session_record_assistant,
  agent_session_record_tool_results,
  agent_session_record_undispatched_tool_results,
  agent_session_record_usage,
  agent_session_totals,
} from "std/agent/state"
pub import { agent_step_judge } from "std/agent/step_judge"
pub import {
  agent_collapse_duplicate_read_calls,
  agent_tool_annotations,
  agent_tool_calls_are_read_only,
  agent_tool_entry_annotations,
} from "std/agent/tool_annotations"
pub import {
  agent_tool_lifecycle_error_category,
  agent_tool_mutation_status,
} from "std/agent/tool_lifecycle"
pub import {
  agent_tool_search_emit_queries,
  agent_tool_search_inject_if_needed,
  agent_tool_search_record_results,
} from "std/agent/tool_search"
import { __tool_surface_tool_allowed } from "std/agent/tool_surface"
pub import {
  agent_apply_tool_surface_narrowing,
  agent_reset_tool_surface_narrowing,
} from "std/agent/tool_surface"
pub import {
  agent_has_turn_end_condition,
  agent_stall_turn_end_judge_due,
  agent_turn_end_judge_cap,
} from "std/agent/turn_end"
pub import {
  AgentAwaitResumptionRequest,
  __agent_await_resumption_from_tool,
  agent_await_resumption,
  agent_lifecycle_tools,
  list_agents,
  suspend_agent,
} from "std/agent/workers"
pub import { omit } from "std/json"
pub import {
  llm_arm_one_shot_prefill,
  llm_clear_one_shot_prefill,
  llm_enable_equivalent_failover,
} from "std/llm/options"
import { exact_tool_call_output_schema } from "std/llm/structural_validator"
pub import { env_bool } from "std/os"

pub fn __agent_loop_llm_overrides(opts: dict) {
  const overrides = opts?.llm_options
  if type_of(overrides) == "dict" {
    return overrides
  }
  return {}
}

pub type AgentLoopOutputContract = {schema: any?}

pub fn __agent_loop_output_contract(opts: dict) -> AgentLoopOutputContract? {
  const output = opts?.output
  if output == nil || output == "text" {
    return nil
  }
  if output == "json" {
    return {schema: nil}
  }
  if type_of(output) == "dict" && output?.schema != nil {
    return {schema: output.schema}
  }
  if type_of(output) == "dict" {
    return {schema: output}
  }
  return nil
}

pub fn __agent_loop_has_terminal_output_contract(opts: dict) -> bool {
  return __agent_loop_output_contract(opts) != nil
}

pub fn __agent_loop_ordinary_turn_llm_options(opts: dict) {
  // `output` constrains the final answer, not intermediate tool-calling turns.
  if !__agent_loop_has_terminal_output_contract(opts) {
    return opts
  }
  return omit(opts, ["output"])
}

pub fn __agent_loop_next_tool_output_contract(opts: dict) -> any? {
  const claim = opts?._next_tool_claim
  if claim == nil {
    return nil
  }
  if claim?.source == "missing_tool_call_recovery" {
    const recovery = opts?.missing_tool_call_recovery
    if type_of(recovery) == "bool" && !recovery {
      return nil
    }
    if type_of(recovery) == "dict" && !(recovery?.output_contract ?? true) {
      return nil
    }
  }
  const tool_name = claim?.tool_name ?? ""
  if !__tool_surface_tool_allowed(opts?.tools, opts?.policy, tool_name) {
    throw "agent_loop: next-turn `next_tool_claim` names unavailable or policy-denied tool `"
      + tool_name
      + "`"
  }
  const schema = exact_tool_call_output_schema(opts?.tools, tool_name)
  if schema == nil {
    throw "agent_loop: next-turn `next_tool_claim` names unavailable tool `" + tool_name + "`"
  }
  return schema
}

pub fn __agent_loop_next_tool_claim_receipt(
  agent: HarnessAgent,
  session_id: any,
  opts: dict,
  iteration_index: int,
) -> nil {
  if !(opts?._next_tool_claim_applied ?? false) {
    return nil
  }
  const claim = opts?._next_tool_claim
  agent_emit_event(
    agent,
    session_id,
    "typed_checkpoint",
    {
      schema: "harn.agent_next_tool_claim_receipt.v1",
      kind: "next_tool_claim_applied",
      receipt_kind: "next_tool_claim_applied",
      status: "applied",
      iteration: iteration_index + 1,
      tool_name: claim?.tool_name ?? "",
      source: claim?.source ?? "post_turn_callback",
    },
  )
}

pub fn __turn_llm_opts(harness: Harness, session: dict, opts: dict?, iteration_index: int) -> dict {
  return __agent_loop_effective_llm_options(harness.llm, opts)
}

pub fn __agent_loop_effective_llm_options(llm: HarnessLlm, opts: dict?) {
  const base = opts ?? {}
  let merged = agent_merge_llm_options(base, __agent_loop_llm_overrides(base))
  const claim_schema = __agent_loop_next_tool_output_contract(merged)
  if claim_schema != nil {
    merged = merged
      + {
        output: {schema: claim_schema},
        _next_tool_claim_applied: true,
        // JSON Schema constrains a text response to the canonical bare call
        // envelope regardless of the ambient tool dialect. Result projection
        // consumes this marker so parser and contract cannot diverge.
        _next_tool_claim_parser_format: "json",
      }
  }
  const call_opts = if (merged?._next_tool_claim_applied ?? false)
    || (merged?._output_contract_repair
      ?? false) {
    merged
  } else {
    __agent_loop_ordinary_turn_llm_options(merged)
  }
  const routed = agent_sanitize_model_options(
    llm,
    agent_refresh_tool_format_for_route(llm, call_opts),
  )
  const completion = agent_completion_prompt_bindings(llm, call_opts)
  return routed
    + {
      mock_scope: call_opts?.mock_scope ?? call_opts?.call_role ?? "agent.main",
      _done_sentinel: completion.done_sentinel,
      _done_sentinel_form: completion.done_sentinel_form,
    }
}

/**
 * Project validated agent-loop options onto the provider request boundary.
 *
 * A next-tool claim derives its output schema from the full registry before
 * this projection. The provider then receives one bare JSON-envelope grammar,
 * without a competing native-tool grammar. The loop retains the unprojected
 * turn options for response parsing, policy, and dispatch.
 *
 * @effects: []
 * @errors: []
 */
pub fn __agent_loop_provider_request_options(opts: dict) -> dict {
  return if opts?._next_tool_claim_applied ?? false {
    opts + {tools: nil, tool_choice: nil}
  } else {
    opts
  }
}

pub fn __agent_loop_route_options(provider: string?, model: string?, tool_format: string?) {
  return {
    provider: to_string(provider ?? ""),
    model: to_string(model ?? ""),
    tool_format: to_string(tool_format ?? ""),
  }
}

pub fn __agent_loop_enable_equivalent_failover(
  llm_opts: dict,
  primary_provider: string,
  primary_model: string,
  loop_opts: dict,
) {
  const provider = to_string(llm_opts?.provider ?? "")
  const model = to_string(llm_opts?.model ?? "")
  const has_primary = primary_provider != "" || primary_model != ""
  const has_current = provider != "" || model != ""
  const partial_route_patch = (loop_opts?._agent_loop_last_llm_route_patch_seen ?? false)
    && !(loop_opts?._agent_loop_last_llm_route_patch_complete
      ?? false)
  const changed_partial_route = has_primary && has_current
    && (provider != primary_provider
      || model
        != primary_model)
    && partial_route_patch
  return llm_enable_equivalent_failover(llm_opts, changed_partial_route)
}

fn __agent_loop_terminal_error(
  error: unknown,
  provider_call_count: int?,
) -> AgentLoopTerminalError {
  const details = type_of(error) == "dict" ? error : {}
  return details
    + {
      kind: to_string(details?.kind ?? "agent_loop_terminal"),
      category: to_string(details?.category ?? error_category(error)),
      reason: to_string(details?.reason ?? "uncaught_exception"),
      message: to_string(details?.message ?? error),
      cause: details?.cause ?? error,
      provider_call_count: provider_call_count,
    }
}

fn __agent_loop_measured_error(
  agent: HarnessAgent,
  session: dict,
  error: unknown,
) -> AgentLoopTerminalError {
  const measured = try {
    agent_session_totals(agent, session.session_id)
  }
  if is_err(measured) {
    return __agent_loop_terminal_error(
      {
        kind: "agent_loop_measurement_unavailable",
        category: "internal",
        reason: "session_totals_unavailable",
        message: "agent session totals could not be read",
        cause: {terminal_error: error, measurement_error: unwrap_err(measured)},
      },
      nil,
    )
  }
  const totals = unwrap(measured)
  if type_of(totals?.provider_call_count) != "int" {
    return __agent_loop_terminal_error(
      {
        kind: "agent_loop_measurement_unavailable",
        category: "internal",
        reason: "provider_call_count_missing",
        message: "agent session totals did not report provider_call_count",
        cause: error,
      },
      nil,
    )
  }
  return __agent_loop_terminal_error(error, max(0, totals.provider_call_count))
}

/**
 * The terminal a boundary throw seals, given what the throw actually was.
 *
 * A throw that reaches the loop boundary is not automatically a failure. When
 * a stop is accepted, the session is torn down under whatever call was in
 * flight, and that call throws because its session vanished, not because
 * anything went wrong. Stamping every boundary throw `failed`/`error` recorded
 * a deliberate stop as a runtime error with a failed lifecycle, so a run that
 * was told to stop and a run that broke were indistinguishable downstream.
 *
 * The category is the evidence and it is already computed: a torn-down
 * execution carries the `cancelled` category, which three sibling paths in
 * this directory (tool dispatch, post-turn, guardrails) already read as "the
 * caller is tearing this run down" before rethrowing. The terminal classifier
 * already maps a `cancelled` status to a user-cancelled kind, ahead of its
 * error arm, so this seam is the only place the distinction was being lost.
 *
 * The cancelled record deliberately carries no `error` key. It is not an
 * error, and passing one fires the session-error hook, which is the other half
 * of the failed lifecycle. The cause is not lost: the same terminal record is
 * returned to the caller and rethrown.
 *
 * @effects: []
 * @errors: []
 * @api_stability: internal
 * @example: __agent_loop_boundary_terminal_record("cancelled", 3, error)
 */
pub fn __agent_loop_boundary_terminal_record(
  category: string,
  iteration: int,
  error: unknown,
) -> AgentSessionFinalization {
  if category == "cancelled" {
    return {final_status: "cancelled", stop_reason: "cancelled", iterations: iteration}
  }
  return {final_status: "failed", stop_reason: "error", iterations: iteration, error: error}
}

pub fn __agent_loop_finalize_failed(
  agent: HarnessAgent,
  session: dict,
  iteration: int,
  error: unknown,
) -> AgentLoopTerminalError {
  const terminal = __agent_loop_measured_error(agent, session, error)
  const finalized = try {
    agent_session_finalize(
      agent,
      session.session_id,
      __agent_loop_boundary_terminal_record(to_string(terminal?.category ?? ""), iteration, error),
    )
  }
  if is_err(finalized) {
    return __agent_loop_terminal_error(
      {
        kind: "agent_loop_terminal_persistence_failed",
        category: "internal",
        reason: "terminal_persistence_failed",
        message: "agent loop failed and its terminal record could not be persisted",
        retry: {
          kind: "agent_session_finalize",
          session_id: session.session_id,
          run_id: session.run_id,
        },
        cause: {terminal_error: terminal, persistence_error: unwrap_err(finalized)},
      },
      terminal.provider_call_count,
    )
  }
  return terminal
}

/**
 * Normalize failures from the public loop boundary without double-finalizing
 * errors already normalized by the inner run owner.
 *
 * Before a session exists, no provider transport is reachable, so zero is a
 * measured invariant. Once a session exists, its ledger is authoritative.
 *
 * @effects: [agent]
 * @errors: [runtime]
 */
pub fn __agent_loop_normalize_boundary_error(
  agent: HarnessAgent,
  session: dict?,
  error: unknown,
  session_finalized: bool = false,
) -> AgentLoopTerminalError {
  if session != nil {
    if session_finalized {
      return __agent_loop_measured_error(agent, session, error)
    }
    return __agent_loop_finalize_failed(agent, session, 0, error)
  }
  return __agent_loop_terminal_error(error, 0)
}

pub type AgentLoopRunExitState = {
  iteration: int,
  session_finalized: bool,
  audit_background_tasks: list,
}

/** Private control-flow result returned to the public agent-loop boundary. */
fn __agent_loop_failed_outcome(
  agent: HarnessAgent,
  session: dict,
  state: AgentLoopRunExitState,
  error: unknown,
) {
  if state.session_finalized {
    return {kind: "failed", error: __agent_loop_measured_error(agent, session, error)}
  }
  return {
    kind: "failed",
    error: __agent_loop_finalize_failed(agent, session, state.iteration, error),
  }
}

/**
 * Return a tagged completed or failed outcome. The public boundary owns the
 * eventual throw, so normalized failures never need a forgeable public marker.
 *
 * @effects: [agent]
 * @errors: [runtime]
 */
pub fn __agent_loop_finish_run(
  agent: HarnessAgent,
  session: dict,
  state: AgentLoopRunExitState,
  run: unknown,
) -> {kind: "completed", result: AgentResult} | {kind: "failed", error: AgentLoopTerminalError} {
  if is_ok(run) {
    const result = unwrap(run)
    if !schema_is(result, schema_of(AgentResult)) {
      return __agent_loop_failed_outcome(
        agent,
        session,
        state,
        "agent_loop: terminal result violated AgentResult",
      )
    }
    return {kind: "completed", result: result}
  }
  const drained = try {
    __drain_audit_flushes(state.audit_background_tasks)
  }
  if is_err(drained) {
    return __agent_loop_failed_outcome(agent, session, state, unwrap_err(drained))
  }
  return __agent_loop_failed_outcome(agent, session, state, unwrap_err(run))
}

pub fn __agent_loop_current_worker(agents: HarnessAgent, runtime: HarnessRuntime) {
  const ctx = runtime.context()
  const worker_id = ctx?.worker_id
  if type_of(worker_id) != "string" || worker_id == "" {
    return nil
  }
  for worker in list_agents(agents) {
    if worker?.id == worker_id {
      return worker
    }
  }
  return nil
}

pub fn __agent_loop_suspend_reminder_body(reason: string) {
  if type_of(reason) == "string" && reason != "" {
    return "Worker suspended before the next turn: " + reason
  }
  return "Worker suspended before the next turn."
}

pub fn __agent_loop_suspend_initiator(value: string?) {
  let text = to_string(value ?? "operator")
  if text == "self_initiated" {
    return "self"
  }
  return text
}

pub fn __agent_loop_suspend_checkpoint(
  agent: HarnessAgent,
  runtime: HarnessRuntime,
  session: dict,
  iteration: int,
) {
  const worker = __agent_loop_current_worker(agent, runtime)
  if worker == nil || worker?.status != "suspended" {
    return nil
  }
  const suspension = worker?.suspension ?? {}
  const reason = to_string(suspension?.reason ?? "")
  const initiator = __agent_loop_suspend_initiator(suspension?.initiator)
  const conditions = suspension?.conditions
  const payload = {
    status: "suspended",
    handle: worker,
    worker: worker,
    reason: reason,
    initiator: initiator,
    conditions: conditions,
    iterations_completed: iteration,
    session_id: session.session_id,
  }
  agent.inject(
    session.session_id,
    transcript_reminder_event(
      {
        body: __agent_loop_suspend_reminder_body(reason),
        source: "in_pipeline",
        tags: ["agent_loop", "worker_suspend"],
        dedupe_key: "worker_suspend:" + worker.id,
        ttl_turns: 1,
        fired_at_turn: iteration + 1,
      },
    ),
  )
  return payload
}

pub fn __agent_loop_with_llm_render_context(harness: Harness, opts: dict?, render: unknown) {
  const effective = __agent_loop_effective_llm_options(harness.llm, opts)
  const provider = to_string(effective?.provider ?? "")
  const model = to_string(effective?.model ?? "")
  const pushed = harness.agent.push_llm_render_context(provider, model)
  defer {
    if pushed {
      harness.agent.pop_llm_render_context()
    }
  }
  return render(harness, effective)
}

pub fn __agent_loop_build_turn_prompt(
  harness: Harness,
  session: dict,
  opts: dict?,
  iteration: int,
) {
  // Commit active directives before reading this turn's history. Every later
  // request then sends those exact bytes at the same message index.
  let _ = agent_session_commit_directives(harness.agent, session.session_id)
  return __agent_loop_with_llm_render_context(
    harness,
    opts,
    { render_harness, effective ->
      const fragments = agent_build_turn_system_fragments(
        render_harness,
        session,
        effective,
        iteration,
      )
      let parts = []
      for fragment in fragments {
        parts = parts.appending(fragment.body)
      }
      return {
        fragments: fragments,
        system: join(parts, "\n\n"),
        messages: agent_build_turn_messages(
          render_harness.agent,
          render_harness.clock,
          session,
          effective,
          iteration,
        ),
      }
    },
  )
}