harn-stdlib 0.9.16

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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
// @harn-entrypoint-category agent.stdlib
//
// Generic role and captain-shaped presets for `agent_loop`. Harness
// authors say "audit", "repair", "summary", "verify" for the generic
// roles, or "merge_captain", "review_captain", "oncall_captain",
// "release_captain" for opinionated captain templates. The presets bundle
// completion behavior, iteration budgeting, provider-aware reasoning policy,
// the LLM handler stack from `std/llm/handlers`, and the tool middleware stack
// from `std/llm/tool_middleware` so durable personas declare their service
// contracts by name instead of re-deriving the knobs at every call site. All
// defaults remain caller-overridable.
import { agent_tool_format_resolution } from "std/agent/options"
import { pin_kinds } from "std/agent/pins"
import {
  compose,
  default_llm_caller,
  with_logging,
  with_retry,
  with_routing,
} from "std/llm/handlers"
import {
  compose_tool_callers,
  with_audit_log,
  with_consent,
  with_dry_run,
  with_handoff_artifact,
  with_rate_limit,
  with_telemetry,
} from "std/llm/tool_middleware"

// -------------------------------------------------------------------------------------------------

// Preset kind registry: user-defined kinds are first-class and discoverable
// through the same register/validate path the built-in kinds are registered
// through (no hardcoded kind lists). A spec is `{family, pack}` — `family`
// selects the behavior template and `pack` carries the fill-nil option rows.

// -------------------------------------------------------------------------------------------------

// Fill-nil pack keys a spec may carry. Each is a lower-priority default that
// fills ONLY a nil/absent option key; an explicit caller value always wins.
// `completion_gate` carries a `CompletionGateOptions` spec so a preset can ship a
// default done-time gate; a consumer lowers it with `agent_completion_gate(...)`
// (std/agent/judge) and spreads the result into `agent_loop` options.
// `lane_policy` carries `{rows, task_key?, hard_keep?}` — a consumer reads the
// task text out of its own opts (e.g. `opts.task_key`) and lowers it with
// `lane_policy(pack.lane_policy.rows, task, opts, pack.lane_policy)`
// (std/agent/lanes). `overlay_policy` carries `{rows, mode, lane?, overrides?}` —
// lowered with `overlay_policy(pack.overlay_policy.rows, pack.overlay_policy.mode,
// opts, pack.overlay_policy)` (std/agent/overlays).
// `pin_policy` carries a preset's default compaction-pin policy (see
// std/agent/pins) — e.g. `{kinds: [...], preserve_on_compact: true}` — filled
// into `opts.pin_policy` for pin-aware harnesses.
let __PRESET_PACK_KEYS = [
  "budget",
  "completion_gate",
  "fallback_chain",
  "lane_policy",
  "model_ladder",
  "overlay_policy",
  "pin_policy",
  "provider",
  "timeout_ms",
]

fn __preset_kind_string(value) {
  if value == nil {
    throw "agent_preset(kind, options?): kind is required"
  }
  if type_of(value) != "string" {
    throw "agent_preset(kind, options?): kind must be a string; got " + type_of(value)
  }
  return lowercase(trim(value))
}

/**
 * Validate a preset spec and return its normalized `{family, pack}` shape.
 * Shared by the built-in registration and `agent_preset_register` so
 * user-defined kinds are held to the same contract as the built-ins.
 */
fn __validate_preset_spec(kind, spec) {
  if type_of(spec) != "dict" {
    throw "agent_preset_register(\"" + kind + "\"): spec must be a dict; got " + type_of(spec)
  }
  let family = spec?.family ?? "generic"
  if family != "generic" && family != "captain" {
    throw "agent_preset_register(\"" + kind + "\"): spec.family must be \"generic\" or \"captain\"; got "
      + to_string(family)
  }
  let pack = spec?.pack ?? {}
  if type_of(pack) != "dict" {
    throw "agent_preset_register(\"" + kind + "\"): spec.pack must be a dict; got " + type_of(pack)
  }
  for key in pack.keys() {
    if !contains(__PRESET_PACK_KEYS, key) {
      throw "agent_preset_register(\"" + kind + "\"): spec.pack has unknown key \"" + key
        + "\"; allowed: "
        + join(__PRESET_PACK_KEYS, ", ")
    }
  }
  __validate_pin_policy(kind, pack?.pin_policy)
  return {family: family, pack: pack}
}

/**
 * A pin_policy pack row carries default compaction-pin behavior (see
 * std/agent/pins). Validate it loudly so a typo like `kinds: ["goals"]` fails at
 * registration instead of silently carrying an unknown pin kind downstream.
 */
fn __validate_pin_policy(kind, pin_policy) {
  if pin_policy == nil {
    return nil
  }
  if type_of(pin_policy) != "dict" {
    throw "agent_preset_register(\"" + kind + "\"): spec.pack.pin_policy must be a dict; got "
      + type_of(pin_policy)
  }
  if pin_policy?.kinds != nil {
    if type_of(pin_policy.kinds) != "list" {
      throw "agent_preset_register(\"" + kind + "\"): pin_policy.kinds must be a list; got "
        + type_of(pin_policy.kinds)
    }
    for k in pin_policy.kinds {
      if !contains(pin_kinds(), k) {
        throw "agent_preset_register(\"" + kind + "\"): pin_policy.kinds has unknown pin kind \""
          + to_string(k)
          + "\"; allowed: "
          + join(pin_kinds(), ", ")
      }
    }
  }
  return nil
}

/**
 * Per-kind pack rows: the provider / transport-timeout / cost-budget /
 * model-ladder defaults callers used to hand-roll around agent_preset,
 * promoted to fill-nil data rows. Captains carry longer timeouts and larger
 * budgets by design.
 *
 * TODO(PR-C): `model_ladder` is a plain models list today; once the
 * `[model_ladders.*]` catalog rows land, replace these with catalog
 * ladder-name references and lower them into `fallback_chain` at resolve time.
 * Budgets are session-cumulative (`total_budget_usd`), NOT per-call ceilings:
 * `budget.max_cost_usd` is pre-flight-checked against the worst-case
 * projection (full `max_tokens` as output), so a tight per-call default would
 * preemptively kill legitimate calls.
 */
fn __builtin_preset_specs() {
  let frontier_ladder = ["claude-opus-4-8", "claude-sonnet-4-5"]
  let cheap_ladder = ["gpt-4o-mini"]
  // Long-running captains pin their binding context (goal, constraints, key
  // decisions) so it survives compaction by construction (see std/agent/pins).
  let captain_pins = {kinds: ["constraint", "decision", "goal"], preserve_on_compact: true}
  return {
    audit: {
      family: "generic",
      pack: {
        budget: {total_budget_usd: 5.0},
        model_ladder: frontier_ladder,
        provider: "anthropic",
        timeout_ms: 120000,
      },
    },
    merge_captain: {
      family: "captain",
      pack: {
        budget: {total_budget_usd: 25.0},
        model_ladder: frontier_ladder,
        pin_policy: captain_pins,
        provider: "anthropic",
        timeout_ms: 300000,
      },
    },
    oncall_captain: {
      family: "captain",
      pack: {
        budget: {total_budget_usd: 15.0},
        model_ladder: frontier_ladder,
        pin_policy: captain_pins,
        provider: "anthropic",
        timeout_ms: 180000,
      },
    },
    release_captain: {
      family: "captain",
      pack: {
        budget: {total_budget_usd: 25.0},
        model_ladder: frontier_ladder,
        pin_policy: captain_pins,
        provider: "anthropic",
        timeout_ms: 300000,
      },
    },
    repair: {
      family: "generic",
      pack: {
        budget: {total_budget_usd: 10.0},
        // Mirrors `std/agent/lanes::default_lane_rows()` inline (presets.harn
        // intentionally does not import std/agent/lanes — see the pack-key
        // comment above `__PRESET_PACK_KEYS`); a consumer may just as well
        // pass `default_lane_rows()` directly instead of this row.
        lane_policy: {
          hard_keep: [],
          rows: [
            {
              match: {explicit_target_paths: {max: 4, min: 1}},
              name: "explicit_patch",
              tool_names: [
                "look",
                "search",
                "edit",
                "run",
                "poll_command",
                "wait_command",
                "kill_command",
                "read_command_output",
              ],
            },
            {default: true, name: "general"},
          ],
        },
        model_ladder: frontier_ladder,
        provider: "anthropic",
        timeout_ms: 180000,
      },
    },
    review_captain: {
      family: "captain",
      pack: {
        budget: {total_budget_usd: 15.0},
        model_ladder: frontier_ladder,
        // Mirrors `std/agent/overlays::default_overlay_rows()`'s `agent` row
        // inline (see the lane_policy comment above on why presets.harn
        // avoids importing the sibling module).
        overlay_policy: {
          mode: "agent",
          rows: [
            {
              lines: [
                "Batch related read-only tool calls together before acting; avoid narrating between them.",
                "Prefer acting on information the task and current tools already provide over asking a clarifying question.",
              ],
              mode: "agent",
            },
          ],
        },
        pin_policy: captain_pins,
        provider: "anthropic",
        timeout_ms: 240000,
      },
    },
    summary: {
      family: "generic",
      pack: {budget: {total_budget_usd: 1.0}, model_ladder: cheap_ladder, provider: "openai", timeout_ms: 60000},
    },
    verify: {
      family: "generic",
      pack: {budget: {total_budget_usd: 1.0}, model_ladder: cheap_ladder, provider: "openai", timeout_ms: 60000},
    },
  }
}

// Built-in registration is lazy (module-level initializers cannot call local
// fns) but dogfoods the same validation path user kinds go through.
var __BUILTIN_PRESETS = {}

var __USER_PRESETS = {}

fn __preset_registry() {
  if len(__BUILTIN_PRESETS.keys()) == 0 {
    let specs = __builtin_preset_specs()
    var reg = {}
    for kind in specs.keys() {
      reg = reg + {[kind]: __validate_preset_spec(kind, specs[kind])}
    }
    __BUILTIN_PRESETS = reg
  }
  return __BUILTIN_PRESETS + __USER_PRESETS
}

/**
 * agent_preset_register(kind, spec) registers (or overrides) a preset kind so
 * `agent_preset(kind, ...)` and `agent_preset_kinds()` see it. `spec` is
 * `{family?: "generic" | "captain", pack?: dict}`: `family` selects the
 * behavior template (captains additionally compose the opt-in tool/LLM
 * middleware layers), and `pack` supplies fill-nil option defaults
 * (`provider`, `timeout_ms`, `budget`, `fallback_chain`, `model_ladder`,
 * `completion_gate`, `lane_policy`, `overlay_policy`, `pin_policy`) that fill
 * ONLY nil/absent keys. The spec shape is validated; an invalid family or
 * unknown pack key throws. Returns the normalized kind string.
 *
 * @effects: []
 * @errors: []
 */
pub fn agent_preset_register(kind, spec) {
  let normalized = __preset_kind_string(kind)
  if normalized == "" {
    throw "agent_preset_register: kind must be a non-empty string"
  }
  __USER_PRESETS = __USER_PRESETS + {[normalized]: __validate_preset_spec(normalized, spec)}
  return normalized
}

/**
 * agent_preset_kinds() returns the registered preset kinds (built-in plus any
 * user-registered), sorted. Discovery surface for tooling and pickers.
 *
 * @effects: []
 * @errors: []
 */
pub fn agent_preset_kinds() {
  return __preset_registry().keys().sort()
}

fn __dict_or_empty(value) {
  if value == nil {
    return {}
  }
  if type_of(value) != "dict" {
    throw "agent_preset: options must be a dict or nil; got " + type_of(value)
  }
  return value
}

fn __has_key(opts, key) {
  return contains(opts.keys(), key)
}

fn __is_captain(kind) {
  let registry = __preset_registry()
  return registry[kind]?.family == "captain"
}

fn __preset_kind(value) {
  let kind = __preset_kind_string(value)
  let registry = __preset_registry()
  if !contains(registry.keys(), kind) {
    throw "agent_preset: kind must be one of "
      + join(registry.keys().sort(), ", ")
      + "; got "
      + value
  }
  return kind
}

fn __caller_set_low_level_reasoning(opts) {
  if __has_key(opts, "thinking") || __has_key(opts, "reasoning_effort") {
    return true
  }
  let llm_overrides = opts?.llm_options
  if type_of(llm_overrides) == "dict"
    && (contains(llm_overrides.keys(), "thinking")
    || contains(llm_overrides.keys(), "reasoning_effort")) {
    return true
  }
  return false
}

fn __caller_set_reasoning_policy(opts) {
  return __has_key(opts, "reasoning_policy") || __has_key(opts, "thinking_policy")
}

fn __caller_set_reasoning_scale(opts) {
  return __has_key(opts, "reasoning_scale") || __has_key(opts, "problem_scale")
}

fn __caller_set_reasoning_task(opts) {
  return __has_key(opts, "reasoning_task") || __has_key(opts, "task_kind") || __has_key(opts, "task")
}

fn __reasoning_task_for_kind(kind) {
  if kind == "summary" {
    return "summarize"
  }
  if kind == "verify" || kind == "audit" {
    return "verify"
  }
  if kind == "repair" {
    return "code"
  }
  return "agent"
}

fn __default_budget_for_kind(kind) {
  if kind == "audit" {
    return {mode: "adaptive", initial: 4, max: 12, extend_by: 2}
  }
  if kind == "repair" {
    return {mode: "adaptive", initial: 4, max: 16, extend_by: 2}
  }
  if kind == "summary" {
    return {mode: "fixed", initial: 1, max: 1, extend_by: 0}
  }
  if kind == "verify" {
    return {mode: "adaptive", initial: 1, max: 5, extend_by: 1}
  }
  if kind == "merge_captain" {
    // Merge sweeps span repair turns, validation, and approval cycles
    // Long-running by design.
    return {mode: "adaptive", initial: 8, max: 60, extend_by: 4}
  }
  if kind == "review_captain" {
    return {mode: "adaptive", initial: 6, max: 30, extend_by: 3}
  }
  if kind == "oncall_captain" {
    return {mode: "adaptive", initial: 6, max: 24, extend_by: 3}
  }
  if kind == "release_captain" {
    return {mode: "adaptive", initial: 8, max: 40, extend_by: 4}
  }
  return {mode: "fixed", initial: 50, max: 50, extend_by: 0}
}

fn __resolve_iteration_budget(kind, opts) {
  if __has_key(opts, "iteration_budget") {
    let raw = opts.iteration_budget
    if type_of(raw) == "string" {
      // Sugar: `iteration_budget: "adaptive"` keeps the kind's defaults
      // but forces adaptive mode.
      let defaults = __default_budget_for_kind(kind)
      return defaults + {mode: raw}
    }
    return raw
  }
  if __has_key(opts, "max_iterations") {
    return nil
  }
  return __default_budget_for_kind(kind)
}

fn __turn_policy_for_kind(kind, opts) {
  if __has_key(opts, "turn_policy") {
    return opts.turn_policy
  }
  if kind == "summary" {
    return {allow_done_sentinel: false, max_prose_chars: 8000}
  }
  if kind == "verify" {
    return {allow_done_sentinel: false, max_prose_chars: 12000}
  }
  // Captains can emit longer per-turn rationales: sweep summaries,
  // approval rationale, and release notes.
  if __is_captain(kind) {
    return {allow_done_sentinel: false, max_prose_chars: 60000}
  }
  return {allow_done_sentinel: false, max_prose_chars: 30000}
}

fn __summary_defaults(opts) {
  return {profile: "completer", loop_until_done: false, done_sentinel: nil, done_judge: nil, max_nudges: 0}
}

fn __verify_defaults() {
  return {profile: "verifier", loop_until_done: false, max_nudges: 0, done_judge: true}
}

fn __tool_using_defaults(kind) {
  let profile = if kind == "audit" {
    "verifier"
  } else {
    "tool_using"
  }
  let max_nudges = if kind == "audit" {
    1
  } else if __is_captain(kind) {
    3
  } else {
    2
  }
  return {
    profile: profile,
    loop_until_done: true,
    done_judge: nil,
    native_tool_fallback: "allow_once",
    max_nudges: max_nudges,
    // The repair knobs ride inside `stall_diagnostics` (where
    // `__agent_stall_config` parses them) and default OFF; `repair_aware:false`
    // makes every repair field inert until a harness opts into the behavior.
    stall_diagnostics: {
      enabled: true,
      threshold: 3,
      inject_feedback: true,
      max_feedback: 1,
      repair_aware: false,
      stuck_same_diagnostic_after: 3,
      post_edit_reverify: true,
      no_net_progress_extend_guard: false,
      no_net_progress_extend_after: 3,
      no_net_progress_hard_cap_after: 16,
    },
    // Discovery surface (#repair-diagnostics). Mirrors the repair knobs above
    // so consumers (e.g. Burin, via a feature flag) can find and opt into the
    // evidence-aware repair loop without spelunking `stall_diagnostics`.
    // Subsumes Burin's futile-retry-guard.harn.
    repair_diagnostics: {
      repair_aware: false,
      stuck_same_diagnostic_after: 3,
      post_edit_reverify: true,
      no_net_progress_extend_guard: false,
      no_net_progress_extend_after: 3,
      no_net_progress_hard_cap_after: 16,
      reserved_terminal_verify: false,
      reserved_terminal_verify_iterations: 2,
    },
  }
}

fn __apply_tool_format(opts, kind) {
  if kind == "summary" || kind == "verify" {
    return opts
  }
  let resolved = agent_tool_format_resolution(opts)
  if resolved?.tool_format == nil {
    return opts
  }
  if resolved?.capability_gap_event != nil {
    return opts
  }
  return opts + {tool_format: resolved.tool_format}
}

fn __kind_defaults(kind, opts) {
  if kind == "summary" {
    return __summary_defaults(opts)
  }
  if kind == "verify" {
    return __verify_defaults()
  }
  return __tool_using_defaults(kind)
}

fn __apply_reasoning_defaults(opts, kind) {
  if __caller_set_low_level_reasoning(opts) {
    return opts
  }
  var resolved = opts
  if !__caller_set_reasoning_policy(opts) {
    resolved = resolved + {reasoning_policy: "auto"}
  }
  if !__caller_set_reasoning_scale(opts) {
    resolved = resolved + {reasoning_scale: "small"}
  }
  if !__caller_set_reasoning_task(opts) {
    resolved = resolved + {reasoning_task: __reasoning_task_for_kind(kind)}
  }
  return resolved
}

fn __apply_iteration_budget(opts, kind) {
  let budget = __resolve_iteration_budget(kind, opts)
  if budget == nil {
    return opts
  }
  return opts + {iteration_budget: budget}
}

fn __apply_turn_policy(opts, kind) {
  return opts + {turn_policy: __turn_policy_for_kind(kind, opts)}
}

fn __apply_kind_defaults(kind, raw_opts) {
  let defaults = __kind_defaults(kind, raw_opts)
  return defaults + raw_opts
}

// -------------------------------------------------------------------------------------------------

// Captain composition: build the tool-middleware + LLM-handler stacks
// each captain ships by default. Layers are opt-in: every captain only
// adds a layer when the caller has supplied the matching dependency
// (sink, callable, rate-limit cap, etc.). Captains stay a no-op
// behavior shim if the caller doesn't provide any layer inputs, which
// keeps the preset useful as a pure budget/profile bundle as well.

// -------------------------------------------------------------------------------------------------

fn __captain_consent_default(kind) {
  if kind == "merge_captain" {
    // Approve read-only annotated tools without prompting; require an
    // explicit consent callable for everything that mutates state.
    return { call ->
      let hints = call?.annotations ?? {}
      let kind_label = to_string(hints?.kind ?? "")
      if kind_label == "read" || kind_label == "search" || kind_label == "fetch"
        || kind_label == "think" {
        return {decision: "approved", decided_by: "merge_captain.read_default"}
      }
      return {
        decision: "denied",
        reason: "merge_captain requires explicit `consent` for write tools",
        decided_by: "merge_captain.write_default",
      }
    }
  }
  return nil
}

fn __captain_rate_limit_default(kind) {
  if kind == "oncall_captain" {
    return {max_calls: 50, message: "oncall_captain rate-limit reached"}
  }
  return nil
}

/**
 * Resolve a captain layer's value, honoring the convention that an
 * explicit `false` (or `nil`) opts the caller out of that layer
 * entirely. If the caller passed nothing for `key`, returns the
 * supplied `default_value`.
 */
fn __captain_layer_value(opts, key, default_value) {
  if !__has_key(opts, key) {
    return default_value
  }
  let supplied = opts[key]
  if supplied == nil || (type_of(supplied) == "bool" && !supplied) {
    return nil
  }
  return supplied
}

fn __captain_tool_layers(kind, opts) {
  var layers = []
  let audit_sink = __captain_layer_value(opts, "audit_sink", nil)
  if audit_sink != nil {
    layers = layers.push(with_audit_log(audit_sink))
  }
  let telemetry = __captain_layer_value(opts, "telemetry", nil)
  if telemetry != nil {
    layers = layers.push(with_telemetry(telemetry))
  }
  if kind == "merge_captain" {
    let consent_fn = __captain_layer_value(opts, "consent", __captain_consent_default(kind))
    if consent_fn != nil {
      layers = layers.push(with_consent(consent_fn))
    }
  }
  if kind == "oncall_captain" {
    let rate_limit = __captain_layer_value(opts, "rate_limit", __captain_rate_limit_default(kind))
    if rate_limit != nil {
      layers = layers.push(with_rate_limit(rate_limit))
    }
  }
  if kind == "release_captain" {
    let dry_value = __captain_layer_value(opts, "dry_run", nil)
    if dry_value != nil {
      let dry = if type_of(dry_value) == "dict" {
        dry_value
      } else {
        {message: "release_captain preview"}
      }
      layers = layers.push(with_dry_run(dry))
    }
  }
  let handoff_sink = __captain_layer_value(opts, "handoff_sink", nil)
  if handoff_sink != nil {
    layers = layers
      .push(with_handoff_artifact({sink: handoff_sink, source: opts?.persona ?? kind}))
  }
  return layers
}

fn __apply_captain_tool_caller(opts, kind) {
  if !__is_captain(kind) {
    return opts
  }
  if __has_key(opts, "tool_caller") {
    return opts
  }
  let layers = __captain_tool_layers(kind, opts)
  if len(layers) == 0 {
    return opts
  }
  return opts + {tool_caller: compose_tool_callers(layers)}
}

fn __captain_handler_layers(opts) {
  var layers = []
  let logging_sink = opts?.logging_sink
  if logging_sink != nil {
    let logging_opts = if type_of(opts?.logging_options) == "dict" {
      opts.logging_options + {sink: logging_sink}
    } else {
      {sink: logging_sink}
    }
    layers = layers.push(with_logging(logging_opts))
  }
  return layers
}

fn __apply_captain_llm_caller(opts, kind) {
  if !__is_captain(kind) {
    return opts
  }
  if __has_key(opts, "llm_caller") {
    return opts
  }
  let cheap = opts?.cheap_caller
  let frontier = opts?.frontier_caller
  let escalate = opts?.escalate_predicate
  let logging_layers = __captain_handler_layers(opts)
  if cheap == nil && len(logging_layers) == 0 {
    return opts
  }
  let base = if cheap != nil {
    let routes = if frontier != nil && escalate != nil {
      [{name: "frontier", when: escalate, caller: frontier}]
    } else {
      []
    }
    with_routing({default: cheap, routes: routes})
  } else {
    default_llm_caller()
  }
  let composed = if len(logging_layers) > 0 {
    let wrap = compose(logging_layers)
    wrap(base)
  } else {
    base
  }
  return opts + {llm_caller: composed}
}

// -------------------------------------------------------------------------------------------------

// Fill-nil pack + default transport retry: the two lower-priority seams that
// sit under the caller's explicit input.

// -------------------------------------------------------------------------------------------------

/**
 * Fill the kind's pack rows (provider / timeout / budget / model ladder) into
 * ONLY the nil/absent option keys. Explicit caller input at a higher-priority
 * seam is never overridden — this is the data-over-code default layer.
 */
fn __apply_preset_pack(opts, kind) {
  let spec = __preset_registry()[kind]
  let pack = spec?.pack ?? {}
  var resolved = opts
  for key in pack.keys() {
    if resolved?[key] == nil {
      resolved = resolved + {[key]: pack[key]}
    }
  }
  return resolved
}

/**
 * Bake a bounded default transport retry onto the `llm_caller:` seam. Since
 * v0.10 removed the per-call `llm_retries` budget (agent_loop is now fail-fast
 * on transient transport errors), presets re-introduce resilience here by
 * wrapping whatever caller is in effect — a caller-supplied `llm_caller`, a
 * captain-composed routing caller, or the stdlib default caller — with
 * `with_retry`. Its default predicate retries only transport-class failures
 * (transient / rate_limited / timeout / network / provider_5xx /
 * stream_interrupt / exception) and NEVER schema_validation, auth, budget,
 * context-window, or policy failures. Pass `retry: false` to opt out (stay
 * fail-fast) or `retry: {max_attempts, base_ms, ...}` to tune it.
 */
fn __apply_default_retry(opts) {
  let requested = opts?.retry
  if type_of(requested) == "bool" && !requested {
    return opts
  }
  let retry_cfg = if type_of(requested) == "dict" {
    requested
  } else {
    {max_attempts: 3}
  }
  let base = opts?.llm_caller ?? default_llm_caller()
  return opts + {llm_caller: with_retry(base, retry_cfg)}
}

// Twin of the removed profile default `llm_retries: 2` (2 retries after
// the first attempt == max_attempts 3).
/**
 * agent_preset is THE way to build `agent_loop` options: it returns a
 * normalized `agent_loop` options dict for a generic role or a captain-shaped
 * persona template. Pass the result straight to `agent_loop(...)`, or merge
 * further overrides on top — caller input always wins over the preset's
 * defaults.
 *
 * At the `llm_call` tier there is no equivalent preset machinery: a "preset"
 * there is just a plain typed `LlmCallOptions` value you spread per call.
 * Preset machinery (budgets, completion policy, middleware stacks, transport
 * retry) only exists at the agent-cell tier this function serves.
 *
 * `kind` is one of:
 *   - generic:  "audit", "repair", "summary", "verify"
 *   - captain:  "merge_captain", "review_captain", "oncall_captain",
 *               "release_captain"
 *
 * The kind set is the registry (`agent_preset_kinds()`); register your own
 * with `agent_preset_register(kind, spec)`.
 *
 * The returned dict is a plain `agent_loop` options dict. Callers can
 * spread it into `agent_loop(...)` directly, or merge further overrides
 * on top. Every kind additionally fills its pack rows (provider, transport
 * timeout, cost budget, model ladder, completion_gate, lane_policy,
 * overlay_policy, pin policy) into nil/absent keys, and bakes a
 * bounded default transport retry onto the `llm_caller:` seam (opt out with
 * `retry: false`). Captain presets additionally compose:
 *   - a `tool_caller` middleware stack from any of `audit_sink`,
 *     `telemetry`, `consent`, `rate_limit`, `dry_run`,
 *     `handoff_sink` the caller supplied;
 *   - an `llm_caller` handler stack from `cheap_caller` +
 *     `frontier_caller` + `escalate_predicate` (cheap-default with
 *     frontier escalation per the cost-moat substrate) and an optional
 *     `logging_sink` for receipts.
 *
 * Layers default to the captain's documented persona shape (e.g.
 * `oncall_captain` defaults `rate_limit` to `{max_calls: 50}`,
 * `merge_captain` defaults `consent` to "auto-approve read tools, deny
 * writes without explicit prompt"). Passing an explicit `false` (or
 * `nil`) for that key opts the caller out of the layer entirely;
 * passing `tool_caller`/`llm_caller` directly bypasses captain
 * composition outright.
 *
 * @effects: []
 * @errors: []
 */
pub fn agent_preset(kind, options = nil) {
  let resolved_kind = __preset_kind(kind)
  var opts = __dict_or_empty(options)
  opts = __apply_kind_defaults(resolved_kind, opts)
  opts = __apply_iteration_budget(opts, resolved_kind)
  opts = __apply_turn_policy(opts, resolved_kind)
  opts = __apply_reasoning_defaults(opts, resolved_kind)
  opts = __apply_captain_tool_caller(opts, resolved_kind)
  opts = __apply_captain_llm_caller(opts, resolved_kind)
  opts = __apply_preset_pack(opts, resolved_kind)
  opts = __apply_default_retry(opts)
  opts = __apply_tool_format(opts, resolved_kind)
  return opts + {_preset_kind: resolved_kind}
}