harn-stdlib 0.8.163

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
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
// @harn-entrypoint-category agent.stdlib
import { agent_emit_event } from "std/agent/state"
import { filter_nil, pick_keys } from "std/collections"

type ResumeTimeoutAction = "resume_with_summary" | "fail" | "resume_with_input"

type ResumeTimeoutSpec = {duration_minutes: int, on_timeout: ResumeTimeoutAction?}

type ResumeConditions = {trigger: dict?, timeout: ResumeTimeoutSpec?, on_event: string?}

type ResumeByResult = {handled: bool, mechanism: string, reason?: string}

type ResumeByCallback = fn(Harness, dict) -> ResumeByResult | dict | nil

type AgentStopOptions = {graceful?: bool, reason?: string}

type AgentAwaitResumptionRequest = {
  reason: string,
  conditions: ResumeConditions?,
  resume_by?: ResumeByCallback,
}

fn __agent_option_keys() {
  return [
    "provider",
    "model",
    "model_tier",
    "temperature",
    "top_p",
    "top_k",
    "max_tokens",
    "thinking",
    "reasoning_effort",
    "reasoning_policy",
    "thinking_policy",
    "reasoning_scale",
    "problem_scale",
    "reasoning_task",
    "tools",
    "subagents",
    "subagent_tools",
    "max_iterations",
    "max_nudges",
    "nudge",
    "turn_policy",
    "tool_format",
    "native_tool_fallback",
    "structural_experiment",
    "context_callback",
    "context_filter",
    "tool_retries",
    "tool_backoff_ms",
  ]
}

/**
 * agent creates an agent spec dict.
 *
 * @effects: []
 * @errors: []
 * @api_stability: experimental
 */
pub fn agent(name, config = nil) {
  if type_of(name) != "string" {
    throw "agent: name must be a string"
  }
  let cfg = config ?? {}
  if type_of(cfg) != "dict" {
    throw "agent: second argument must be a config dict"
  }
  return cfg + {_type: "agent", name: name}
}

/**
 * agent_name reads an agent spec name.
 *
 * @effects: []
 * @errors: []
 * @api_stability: experimental
 */
pub fn agent_name(spec) {
  if type_of(spec) != "dict" {
    throw "agent_name: argument must be an agent"
  }
  return spec?.name
}

/**
 * agent_config builds prompt/system/options for an agent spec.
 *
 * @effects: [agent]
 * @errors: []
 * @api_stability: experimental
 */
pub fn agent_config(spec, prompt) {
  if type_of(spec) != "dict" || spec?._type != "agent" {
    throw "agent_config: first argument must be an agent (created with agent())"
  }
  let options = pick_keys(spec, __agent_option_keys(), {drop_nil: true})
  return {prompt: prompt, system: spec?.system, options: options}
}

fn __worker_dict(value) {
  if type_of(value) == "dict" {
    return value
  }
  return {}
}

fn __worker_list(value) {
  if type_of(value) == "list" {
    return value
  }
  return []
}

fn __worker_options(value, label) {
  if value == nil {
    return {}
  }
  if type_of(value) == "dict" {
    return value
  }
  throw label + ": options must be a dict or nil"
}

fn __agent_stop_options(options, label) {
  let opts = __worker_options(options, label)
  let graceful = opts?.graceful ?? false
  if type_of(graceful) != "bool" {
    throw label + ": options.graceful must be a bool"
  }
  if opts?.reason != nil && type_of(opts.reason) != "string" {
    throw label + ": options.reason must be a string"
  }
  let reason = trim(to_string(opts?.reason ?? ""))
  return filter_nil({graceful: graceful, reason: reason == "" ? nil : reason})
}

fn __worker_resume_options(options) {
  if options?.resume_when == nil {
    return options
  }
  return options + {resume_when: parse_resume_conditions(options.resume_when)}
}

fn __agent_tool_entry_name(entry) {
  if type_of(entry) != "dict" {
    return ""
  }
  if entry?.name != nil {
    return to_string(entry.name)
  }
  let func = entry?.function
  if type_of(func) == "dict" {
    return to_string(func?.name ?? "")
  }
  return ""
}

fn __agent_tool_registry_has(registry, name) {
  let entries = registry?.tools ?? []
  if type_of(entries) != "list" {
    return false
  }
  for entry in entries {
    if __agent_tool_entry_name(entry) == name {
      return true
    }
  }
  return false
}

fn __agent_lifecycle_tool_audit(tool_name, initiator, reason, handle = nil, conditions = nil) {
  let session_id = agent_session_current_id()
  if session_id == nil || session_id == "" {
    return
  }
  let _ = try {
    agent_emit_event(
      session_id,
      "tool_call_audit",
      {
        tool_call_id: "",
        tool_name: tool_name,
        audit: filter_nil(
          {
            layer: "agent_lifecycle",
            status: "invoked",
            initiator: initiator,
            reason: reason,
            handle: handle,
            conditions: conditions,
          },
        ),
      },
    )
  }
}

fn __subagent_pause_tool(args) {
  let handle = args?.handle
  if handle == nil || trim(to_string(handle)) == "" {
    throw "subagent_pause: handle is required"
  }
  let reason = trim(to_string(args?.reason ?? ""))
  if reason == "" {
    throw "subagent_pause: reason is required"
  }
  __agent_lifecycle_tool_audit("subagent_pause", "parent", reason, handle)
  return suspend_agent(handle, reason, {initiator: "parent"})
}

fn __subagent_resume_tool(args) {
  let handle = args?.handle
  if handle == nil || trim(to_string(handle)) == "" {
    throw "subagent_resume: handle is required"
  }
  let continue_transcript = args?.continue_transcript ?? true
  if type_of(continue_transcript) != "bool" {
    throw "subagent_resume: continue_transcript must be a bool"
  }
  __agent_lifecycle_tool_audit("subagent_resume", "parent", "resume requested", handle)
  return resume_agent(handle, args?.input, continue_transcript)
}

fn __subagent_stop_tool(args) {
  let handle = args?.handle
  if handle == nil || trim(to_string(handle)) == "" {
    throw "subagent_stop: handle is required"
  }
  let graceful = args?.graceful ?? true
  if type_of(graceful) != "bool" {
    throw "subagent_stop: graceful must be a bool"
  }
  var reason = trim(to_string(args?.reason ?? "parent requested stop"))
  if reason == "" {
    reason = "parent requested stop"
  }
  __agent_lifecycle_tool_audit("subagent_stop", "parent", reason, handle)
  return agent_stop(handle, {graceful: graceful, reason: reason})
}

fn __agent_await_resumption_tool(_args) {
  throw "HARN-SUS-005: agent_await_resumption is handled structurally by agent_loop and cannot be invoked directly"
}

fn __agent_lifecycle_has_subagent_capability(registry, opts) {
  if opts?.subagents ?? false {
    return true
  }
  if opts?.subagent_tools ?? false {
    return true
  }
  return __agent_tool_registry_has(registry, "sub_agent_run")
    || __agent_tool_registry_has(registry, "spawn_agent")
}

fn __agent_lifecycle_await_enabled(opts) {
  let value = opts?.agent_await_resumption_enabled
  if value == nil {
    return true
  }
  if type_of(value) != "bool" {
    throw "agent_lifecycle_tools: agent_await_resumption_enabled must be bool or nil"
  }
  return value
}

fn __agent_lifecycle_add_await_tool(registry) {
  if __agent_tool_registry_has(registry, "agent_await_resumption") {
    return registry
  }
  return tool_define(
    registry,
    "agent_await_resumption",
    "Suspend this agent and return control to its caller until a parent, operator, or resume trigger wakes it.",
    {
      handler: __agent_await_resumption_tool,
      parameters: {
        reason: {type: "string", description: "Why this agent is parking."},
        conditions: {
          type: "object",
          required: false,
          description: "Optional ResumeConditions with trigger, timeout, or on_event fields.",
        },
      },
      returns: {type: "object"},
      annotations: {agent_lifecycle: true, structural: true, initiator: "self"},
    },
  )
}

fn __agent_lifecycle_add_subagent_tools(registry) {
  var tools = registry
  if !__agent_tool_registry_has(tools, "subagent_pause") {
    tools = tool_define(
      tools,
      "subagent_pause",
      "Cooperatively pause a running subagent after its current turn settles. Returns a resumable handle.",
      {
        handler: __subagent_pause_tool,
        parameters: {
          handle: {type: "string", description: "Worker id or worker handle to pause."},
          reason: {type: "string", description: "Why the child should pause."},
        },
        returns: {type: "object"},
        annotations: {agent_lifecycle: true, initiator: "parent"},
      },
    )
  }
  if !__agent_tool_registry_has(tools, "subagent_resume") {
    tools = tool_define(
      tools,
      "subagent_resume",
      "Resume a suspended subagent with optional input.",
      {
        handler: __subagent_resume_tool,
        parameters: {
          handle: {type: "string", description: "Worker id or worker handle to resume."},
          input: {type: "any", required: false, description: "Optional input for the resumed turn."},
          continue_transcript: {
            type: "boolean",
            required: false,
            description: "Keep prior transcript context when resuming; defaults to true.",
          },
        },
        returns: {type: "object"},
        annotations: {agent_lifecycle: true, initiator: "parent"},
      },
    )
  }
  if !__agent_tool_registry_has(tools, "subagent_stop") {
    tools = tool_define(
      tools,
      "subagent_stop",
      "Stop a subagent. Defaults to a graceful recursive handoff summary; pass graceful=false for a hard cancel.",
      {
        handler: __subagent_stop_tool,
        parameters: {
          handle: {type: "string", description: "Worker id or worker handle to stop."},
          graceful: {
            type: "boolean",
            required: false,
            description: "Collect a typed handoff before stopping; defaults to true.",
          },
          reason: {type: "string", required: false, description: "Why the child should stop."},
        },
        returns: {type: "object"},
        annotations: {agent_lifecycle: true, initiator: "parent", handoff: true},
      },
    )
  }
  return tools
}

/**
 * agent_lifecycle_tools adds model-facing suspend/resume lifecycle tools.
 *
 * Every returned registry includes `agent_await_resumption` unless the caller
 * passes `{agent_await_resumption_enabled: false}`. Parent-side
 * `subagent_pause`, `subagent_resume`, and `subagent_stop` are added only when
 * the caller opts into subagent lifecycle control with `{subagents: true}` or
 * `{subagent_tools: true}`, or when the supplied registry already exposes a
 * `sub_agent_run` / `spawn_agent` tool.
 *
 * @effects: []
 * @errors: []
 * @api_stability: experimental
 */
pub fn agent_lifecycle_tools(registry = nil, options = nil) {
  let opts = __worker_options(options, "agent_lifecycle_tools")
  let base = registry ?? tool_registry()
  var tools = if __agent_lifecycle_await_enabled(opts) {
    __agent_lifecycle_add_await_tool(base)
  } else {
    base
  }
  if __agent_lifecycle_has_subagent_capability(base, opts) {
    tools = __agent_lifecycle_add_subagent_tools(tools)
  }
  return tools
}

fn __worker_mode(config) {
  if config?.graph != nil {
    return "workflow"
  }
  return "stage"
}

fn __worker_workflow_config(config) {
  let options = __worker_resume_options(__worker_dict(config?.options))
  return filter_nil(
    config
      + {graph: workflow_graph(config.graph), artifacts: __worker_list(config?.artifacts), options: options},
  )
}

fn __worker_stage_config(config) {
  return filter_nil(
    config
      + {
      artifacts: __worker_list(config?.artifacts),
      options: __worker_resume_options(__worker_dict(config?.options)),
    },
  )
}

fn __worker_config(config) {
  let cfg = __worker_dict(config)
  let mode = __worker_mode(cfg)
  if mode == "workflow" {
    return __worker_workflow_config(cfg)
  }
  return __worker_stage_config(cfg)
}

/**
 * spawn_agent.
 *
 * @effects: [host]
 * @errors: []
 * @api_stability: experimental
 */
pub fn spawn_agent(config) {
  return __host_worker_spawn(__worker_config(config))
}

/**
 * parse_resume_conditions.
 *
 * Validate and normalize a ResumeConditions dict used by self-parking
 * agents and `spawn_agent({options: {resume_when: ...}})`. `trigger`
 * is validated through the same trigger-spec parser used by
 * `trigger_register`; `timeout.duration_minutes` must be positive; and
 * `on_event` must be a non-empty EventLog topic.
 *
 * @effects: [host]
 * @errors: [HARN-SUS-002]
 * @api_stability: experimental
 */
pub fn parse_resume_conditions(conditions = nil) -> ResumeConditions? {
  return __host_resume_conditions_parse(conditions)
}

/**
 * agent_await_resumption.
 *
 * Build the normalized request used by the model-facing
 * `agent_await_resumption` lifecycle tool. `agent_loop` decides whether that
 * request becomes a worker suspension, a top-level suspension checkpoint, or
 * daemon idle metadata.
 *
 * The optional `resume_by` argument names the callback that owns this
 * suspension's resume responsibility. Pass any `(harness, suspension) ->
 * {handled, mechanism}` closure — typically
 * one of the four `ResumeBy.*` presets from `std/agent/resume_by`, or a
 * `first_available(...)` chain. When omitted, the runtime calls
 * `default_resume_by(...)` to pick a sensible default based on the
 * presence of `conditions` and the active cloud session.
 *
 * @effects: [host]
 * @errors: [HARN-SUS-002, HARN-SUS-005]
 * @api_stability: experimental
 * @example: agent_await_resumption("waiting on review", {timeout: {duration_minutes: 5}})
 */
pub fn agent_await_resumption(reason, conditions = nil, resume_by = nil) -> AgentAwaitResumptionRequest {
  let normalized_reason = trim(to_string(reason ?? ""))
  if normalized_reason == "" {
    throw "HARN-SUS-005: agent_await_resumption reason is required"
  }
  return {reason: normalized_reason, conditions: parse_resume_conditions(conditions), resume_by: resume_by}
}

/**
 * send_input.
 *
 * @effects: [host]
 * @errors: []
 * @api_stability: experimental
 */
pub fn send_input(worker, task) {
  return __host_worker_send_input(worker, task)
}

/**
 * worker_trigger.
 *
 * @effects: [host]
 * @errors: []
 * @api_stability: experimental
 */
pub fn worker_trigger(worker, payload) {
  return __host_worker_trigger(worker, payload)
}

fn __is_pool_task(value) {
  return type_of(value) == "dict" && value?._type == "pool_task"
}

/**
 * wait_agent.
 *
 * @effects: [host]
 * @errors: []
 * @api_stability: experimental
 */
pub fn wait_agent(worker_or_workers) {
  if __is_pool_task(worker_or_workers) {
    return __pool_wait(worker_or_workers)
  }
  if type_of(worker_or_workers) == "list" {
    var results = []
    for item in worker_or_workers {
      results = results.push(wait_agent(item))
    }
    return results
  }
  return __host_worker_wait(worker_or_workers)
}

/**
 * agent_stop.
 *
 * Stop a worker. By default this is a hard cancel. Pass
 * `{graceful: true}` to return a recursive typed handoff summary before the
 * worker is stopped.
 *
 * @effects: [host]
 * @errors: []
 * @api_stability: experimental
 * @example: agent_stop(worker, {graceful: true})
 */
pub fn agent_stop(worker, options: AgentStopOptions = nil) {
  return __host_worker_stop(worker, __agent_stop_options(options, "agent_stop"))
}

/**
 * close_agent.
 *
 * @effects: [host]
 * @errors: []
 * @api_stability: experimental
 */
pub fn close_agent(worker) {
  return __host_worker_close(worker)
}

/**
 * suspend_agent.
 *
 * Cooperatively mark a worker as suspended, persist its resumable snapshot,
 * and return the worker summary with `status: "suspended"` plus
 * `suspension` metadata.
 *
 * @effects: [host]
 * @errors: [HARN-SUS-001, HARN-SUS-002, HARN-SUS-007, HARN-SUS-008]
 * @api_stability: experimental
 */
pub fn suspend_agent(worker, reason = "", options = nil) {
  return __host_worker_suspend(worker, reason, options)
}

/**
 * resume_agent.
 *
 * Resume a suspended worker, optionally wiring new input into the resumed
 * task, or restore a persisted worker snapshot into the current runtime.
 * By default the resumed worker keeps its transcript. Pass
 * `continue_transcript = false` to resume from the prior transcript summary
 * plus the new input only.
 *
 * @effects: [host]
 * @errors: [HARN-SUS-003, HARN-SUS-004, HARN-SUS-006, HARN-SUS-009, HARN-SUS-010]
 * @api_stability: experimental
 */
pub fn resume_agent(worker_or_snapshot, resume_input = nil, continue_transcript = true) {
  return __host_worker_resume(
    worker_or_snapshot,
    {input: resume_input, continue_transcript: continue_transcript},
  )
}

/**
 * list_agents.
 *
 * @effects: [host]
 * @errors: []
 * @api_stability: experimental
 */
pub fn list_agents() {
  return __host_worker_list()
}

fn __sub_agent_string(value, fallback = "") {
  if type_of(value) != "string" {
    return fallback
  }
  let text = trim(value)
  if text == "" {
    return fallback
  }
  return value
}

fn __sub_agent_string_list(value, label) {
  if value == nil {
    return []
  }
  if type_of(value) != "list" {
    throw label + ": expected a list of strings"
  }
  var out = []
  for item in value {
    if type_of(item) != "string" {
      throw label + ": expected a list of strings"
    }
    let text = trim(item)
    if text != "" && !contains(out, text) {
      out = out.push(text)
    }
  }
  return out
}

fn __sub_agent_base_tools(opts) {
  if opts?.tools != nil {
    return opts.tools
  }
  return __host_current_tool_registry()
}

fn __sub_agent_selected_tools(opts, allowed_tools) {
  let base = __sub_agent_base_tools(opts)
  if len(allowed_tools) == 0 {
    return base
  }
  if base == nil {
    return nil
  }
  return tool_select(base, allowed_tools)
}

fn __sub_agent_options(opts, session_id, selected_tools) {
  var out = {}
  let internal = [
    "background",
    "carry",
    "returns",
    "allowed_tools",
    "name",
    "execution",
    "system",
    "session_id",
    "policy",
    "reminder_propagation",
  ]
  for key in opts.keys() {
    if !contains(internal, key) {
      out = out + {[key]: opts[key]}
    }
  }
  out = out + {session_id: session_id}
  if selected_tools != nil {
    out = out + {tools: selected_tools}
  }
  return out
}

/**
 * sub_agent_request builds the Harn-owned child-agent request envelope.
 *
 * @effects: []
 * @errors: []
 * @api_stability: experimental
 */
pub fn sub_agent_request(task, options = nil) {
  let task_text = __sub_agent_string(task)
  if task_text == "" {
    throw "sub_agent_run: task is required"
  }
  let opts = __worker_resume_options(__worker_options(options, "sub_agent_run"))
  let allowed_tools = __sub_agent_string_list(opts?.allowed_tools, "sub_agent_run.allowed_tools")
  let selected_tools = __sub_agent_selected_tools(opts, allowed_tools)
  let session_id = __sub_agent_string(opts?.session_id, "sub_agent_session_" + uuid_v7())
  return filter_nil(
    {
      _type: "sub_agent_request",
      name: __sub_agent_string(opts?.name, "sub-agent"),
      task: task_text,
      system: __sub_agent_string(opts?.system, nil),
      options: __sub_agent_options(opts, session_id, selected_tools),
      returns_schema: opts?.returns?.schema,
      session_id: session_id,
      background: opts?.background ? true : false,
      carry: opts?.carry,
      execution: opts?.execution,
      policy: opts?.policy,
      anchor: opts?.anchor,
      reminder_propagation: opts?.reminder_propagation,
      allowed_tools: allowed_tools,
    },
  )
}

/**
 * sub_agent_run.
 *
 * @effects: [host]
 * @errors: []
 * @api_stability: experimental
 */
pub fn sub_agent_run(task, options = nil) {
  return __host_sub_agent_run(sub_agent_request(task, options))
}

fn __fanout_options(options) {
  if options == nil {
    return {}
  }
  if type_of(options) == "dict" {
    return options
  }
  throw "agent_fanout: options must be a dict or nil"
}

fn __fanout_max_parallel(options) {
  let raw = options?.max_parallel
  if raw == nil {
    return 8
  }
  if type_of(raw) != "int" {
    throw "agent_fanout: max_parallel must be an int"
  }
  if raw < 1 {
    return 1
  }
  return raw
}

fn __fanout_normalize_request(entry, index) {
  let fallback_label = "unit-" + to_string(index + 1)
  if type_of(entry) == "string" {
    let task = trim(entry)
    if task == "" {
      throw "agent_fanout: request #" + to_string(index + 1) + " has an empty task"
    }
    return {task: task, options: {}, label: fallback_label}
  }
  if type_of(entry) != "dict" {
    throw "agent_fanout: request #" + to_string(index + 1)
      + " must be a string or {task, options?, label?}"
  }
  let task = trim(to_string(entry?.task ?? ""))
  if task == "" {
    throw "agent_fanout: request #" + to_string(index + 1) + " is missing a non-empty task"
  }
  let raw_label = trim(to_string(entry?.label ?? entry?.name ?? ""))
  let label = if raw_label == "" {
    fallback_label
  } else {
    raw_label
  }
  return {task: task, options: __fanout_options(entry?.options), label: label}
}

fn __fanout_chunks(items, width) {
  let size = if width < 1 {
    1
  } else {
    width
  }
  var chunks = []
  var current = []
  for item in items {
    current = current.push(item)
    if len(current) >= size {
      chunks = chunks.push(current)
      current = []
    }
  }
  if len(current) > 0 {
    chunks = chunks.push(current)
  }
  return chunks
}

fn __fanout_envelope(summary) {
  let result = summary?.result
  if type_of(result) == "dict" {
    return result
  }
  return {}
}

fn __fanout_ok(summary) {
  let envelope = __fanout_envelope(summary)
  if type_of(envelope?.ok) == "bool" {
    return envelope.ok
  }
  let status = trim(to_string(summary?.status ?? "")).lower()
  return contains(["completed", "done", "succeeded", "success"], status)
}

fn __fanout_error(summary) {
  let envelope_error = __fanout_envelope(summary)?.error
  if envelope_error != nil {
    return envelope_error
  }
  return summary?.error
}

fn __fanout_result(request, index, summary) {
  return {
    label: request.label,
    index: index,
    status: trim(to_string(summary?.status ?? "unknown")),
    ok: __fanout_ok(summary),
    result: __fanout_envelope(summary),
    error: __fanout_error(summary),
  }
}

/**
 * __fanout_spawn_error_summary turns a spawn-time throw into a synthetic worker
 * summary shaped exactly like a terminal failure: `__fanout_envelope` reads the
 * `ok: false` envelope, `__fanout_ok` returns false, and `__fanout_error`
 * surfaces the spawn fault — so a child that never launched still produces a
 * 1:1 ok:false result at its own offset instead of aborting the wave.
 *
 * @effects: []
 * @errors: []
 * @api_stability: experimental
 */
fn __fanout_spawn_error_summary(error) {
  return {
    status: "failed",
    result: {ok: false, error: __sub_agent_string(error, "sub_agent_run: spawn failed")},
  }
}

/**
 * agent_fanout runs many sub-agent requests CONCURRENTLY in bounded waves and
 * joins them, returning one normalized result per request in input order.
 *
 * This is the general building block for parallel agent fan-out: map a list of
 * independent units onto concurrent child agents. Each request is launched as a
 * background `sub_agent_run(task, options + {background: true})`, so a whole
 * wave's LLM turns overlap in wall-clock time; `wait_agent` then joins the wave
 * before the next one starts. Harnesses layer their own per-unit tool surface,
 * capability policy, model, and prompts on top by setting each request's
 * `options` — `agent_fanout` owns only the concurrency, the wave bound, the
 * join, and result normalization.
 *
 * requests: a list whose entries are either a bare task string (shorthand for
 *   `{task: <string>}`) or `{task, options?, label?}`. `task` is the child
 *   prompt; `options` is forwarded verbatim to `sub_agent_run` (tools, policy,
 *   system, model, max_iterations, ...) — `background: true` and `name: label`
 *   are always set, overriding any caller value, because concurrency and a
 *   stable registry label are part of the contract. `label` (or `name`) names
 *   the unit in the result and the worker registry.
 * options: `{max_parallel?: int}`. `max_parallel` bounds how many children run
 *   at once (default 8, floored to 1); requests beyond it run in later waves so
 *   a large fan-out cannot exhaust provider rate budget or host resources.
 *
 * Returns a list of `{label, index, status, ok, result, error}`, one per request
 * in INPUT order regardless of completion order: `status` is the worker
 * lifecycle string, `result` the sub-agent envelope, `ok` its success flag
 * (falling back to the terminal status when no envelope was produced), and
 * `error` the first of the envelope error or a worker-level fault (nil on
 * success).
 *
 * @effects: [host]
 * @errors: []
 * @api_stability: experimental
 * @example: agent_fanout([{task: "port a", options: child_opts, label: "a"}], {max_parallel: 4})
 */
pub fn agent_fanout(requests, options = nil) {
  if type_of(requests) != "list" {
    throw "agent_fanout: requests must be a list of {task, options?, label?}"
  }
  let opts = __fanout_options(options)
  let max_parallel = __fanout_max_parallel(opts)
  var normalized = []
  var index = 0
  for entry in requests {
    normalized = normalized.push(__fanout_normalize_request(entry, index))
    index = index + 1
  }
  var results = []
  var base = 0
  for wave in __fanout_chunks(normalized, max_parallel) {
    // Spawn the whole wave as background workers BEFORE joining: each
    // background `sub_agent_run` returns its handle immediately, so the
    // children's turns overlap while `wait_agent` awaits them.
    //
    // A spawn can throw SYNCHRONOUSLY (bad request `options`, e.g. a malformed
    // `allowed_tools`, or a host worker-spawn fault) before any handle exists.
    // We catch each spawn so one failing unit becomes that unit's ok:false
    // result instead of aborting the whole wave and every later wave. The
    // outcome list stays positionally aligned with `wave`; only the units that
    // actually spawned are joined via `wait_agent`.
    var outcomes = []
    for request in wave {
      let outcome = try {
        let handle = sub_agent_run(request.task, request.options + {background: true, name: request.label})
        {spawned: true, handle: handle}
      } catch (spawn_error) {
        {spawned: false, error: spawn_error}
      }
      outcomes = outcomes.push(outcome)
    }
    var live_handles = []
    for outcome in outcomes {
      if outcome.spawned {
        live_handles = live_handles.push(outcome.handle)
      }
    }
    let waited = wait_agent(live_handles)
    var offset = 0
    var live_index = 0
    for request in wave {
      let outcome = outcomes[offset]
      var summary = {}
      if outcome.spawned {
        if type_of(waited) == "list" {
          summary = waited[live_index] ?? {}
        }
        live_index = live_index + 1
      } else {
        summary = __fanout_spawn_error_summary(outcome.error)
      }
      results = results.push(__fanout_result(request, base + offset, summary))
      offset = offset + 1
    }
    base = base + len(wave)
  }
  return results
}