harn-stdlib 0.8.52

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
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
import { completion_judge_feedback_prompt, completion_judge_system_prompt } from "std/agent/prompts"
import { agent_reasoning_apply } from "std/agent/reasoning"

fn __profile_defaults(profile) {
  if profile == "tool_using" {
    return {max_iterations: 50, max_nudges: 8, tool_retries: 0, llm_retries: 2, schema_retries: 0}
  }
  if profile == "researcher" {
    return {max_iterations: 30, max_nudges: 4, tool_retries: 0, llm_retries: 2, schema_retries: 0}
  }
  if profile == "verifier" {
    return {max_iterations: 5, max_nudges: 0, tool_retries: 0, llm_retries: 2, schema_retries: 3}
  }
  if profile == "completer" {
    return {max_iterations: 1, max_nudges: 0, tool_retries: 0, llm_retries: 2, schema_retries: 0}
  }
  throw "agent_loop: profile must be one of tool_using, researcher, verifier, completer"
}

fn __completion_judge_defaults(value, opts) {
  if type_of(value) == "bool" && value {
    return {
      system: completion_judge_system_prompt(opts),
      feedback_fallback: completion_judge_feedback_prompt(opts),
    }
  }
  return value
}

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

fn __judge_enabled(value) {
  if value == nil {
    return false
  }
  if type_of(value) == "bool" {
    return value
  }
  if type_of(value) == "dict" {
    let enabled = value?.enabled
    if enabled == nil {
      return true
    }
    return enabled
  }
  return true
}

fn __client_tool_search_requested(value) {
  return type_of(value) == "dict" && value?.mode == "client"
}

fn __fallback_tool_format() {
  return "text"
}

fn __tool_format_auto(value) {
  if value == nil {
    return true
  }
  let text = lowercase(trim(to_string(value)))
  return text == "" || text == "auto"
}

fn __explicit_tool_format(opts) {
  if !__has_key(opts, "tool_format") || __tool_format_auto(opts?.tool_format) {
    return nil
  }
  return lowercase(trim(to_string(opts.tool_format)))
}

fn __explicit_provider(opts) {
  let provider = trim(to_string(opts?.provider ?? ""))
  if provider == "" || lowercase(provider) == "auto" {
    return nil
  }
  return provider
}

fn __resolved_model_id(model) {
  let resolved = try {
    llm_resolve_model(model)
  }
  if is_err(resolved) {
    return to_string(model)
  }
  return unwrap(resolved)?.id ?? to_string(model)
}

fn __tool_format_pair(opts) {
  let raw_model = opts?.model
  if raw_model == nil || trim(to_string(raw_model)) == "" {
    return nil
  }
  let provider = __explicit_provider(opts)
  if provider != nil {
    return {provider: provider, model: __resolved_model_id(raw_model)}
  }
  let resolved = try {
    llm_resolve_model(raw_model)
  }
  if is_err(resolved) {
    return nil
  }
  let info = unwrap(resolved)
  let inferred_provider = trim(to_string(info?.provider ?? ""))
  let model = trim(to_string(info?.id ?? ""))
  if inferred_provider == "" || model == "" {
    return nil
  }
  return {provider: inferred_provider, model: model}
}

fn __valid_tool_format(value) {
  let format = lowercase(trim(to_string(value ?? "")))
  if format == "native" || format == "text" {
    return format
  }
  return nil
}

fn __optional_text(value) {
  if value == nil {
    return nil
  }
  let text = trim(to_string(value))
  if text == "" {
    return nil
  }
  return text
}

fn __catalog_parity(value) {
  let text = __optional_text(value)
  if text == nil {
    return "unknown"
  }
  return lowercase(text)
}

fn __parity_recommended_tool_format(parity) {
  if parity == "native_unreliable" || parity == "text_only" {
    return "text"
  }
  if parity == "text_unreliable" || parity == "native_only" {
    return "native"
  }
  return nil
}

fn __parity_conflicts_with_requested(parity, requested) {
  if parity == "native_unreliable" {
    return requested == "native"
  }
  if parity == "text_unreliable" {
    return requested == "text"
  }
  if parity == "native_only" {
    return requested == "text"
  }
  if parity == "text_only" {
    return requested == "native"
  }
  return false
}

fn __tool_format_override_event(pair, requested, preferred, parity, override_reason) {
  if pair == nil {
    return nil
  }
  let requested_format = __valid_tool_format(requested)
  if requested_format == nil {
    return nil
  }
  let catalog_parity = __catalog_parity(parity)
  let recommended = preferred ?? __parity_recommended_tool_format(catalog_parity)
  if recommended == nil {
    return nil
  }
  let conflicts_with_recommendation = requested_format != recommended
  let conflicts_with_parity = __parity_conflicts_with_requested(catalog_parity, requested_format)
  if !conflicts_with_recommendation && !conflicts_with_parity {
    return nil
  }
  let event = {
    provider: pair.provider,
    model: pair.model,
    requested_format: requested_format,
    recommended_format: recommended,
    catalog_parity: catalog_parity,
  }
  if override_reason != nil {
    return event + {override_reason: override_reason}
  }
  return event
}

/**
 * Render one `tool_format_override` event as the CLI's single-line warning.
 *
 * @effects: []
 * @allocation: heap
 * @errors: []
 * @api_stability: experimental
 * @example: agent_tool_format_override_warning_text(event)
 */
pub fn agent_tool_format_override_warning_text(event) {
  if event == nil {
    return nil
  }
  let payload = event?.metadata ?? event
  let provider = payload?.provider ?? "unknown"
  let model = payload?.model ?? "unknown"
  let requested = payload?.requested_format ?? "unknown"
  let recommended = payload?.recommended_format ?? "unknown"
  let parity = payload?.catalog_parity ?? "unknown"
  let override_reason = trim(to_string(payload?.override_reason ?? ""))
  let needs_reason = (parity == "native_unreliable" && requested == "native")
    || (parity == "text_unreliable" && requested == "text")
  var line = "warning: tool_format override: "
    + provider
    + ":"
    + model
    + " requested "
    + requested
    + " over recommended "
    + recommended
    + " (parity: "
    + parity
    + ")"
  if override_reason != "" {
    line = line + "; reason: " + override_reason
  } else if needs_reason {
    line = line + "; missing --override-reason while forcing the catalog-marked unreliable side"
  }
  return line
}

/**
 * Render the first `tool_format_override` event in an event list, if present.
 *
 * @effects: []
 * @allocation: heap
 * @errors: []
 * @api_stability: experimental
 * @example: agent_first_tool_format_override_warning_text(events)
 */
pub fn agent_first_tool_format_override_warning_text(events) {
  for event in events {
    if event?.kind == "tool_format_override" || event?.type == "tool_format_override" {
      return agent_tool_format_override_warning_text(event)
    }
  }
  return nil
}

fn __capability_gap_event(pair, requested, fallback) {
  return {
    level: "warning",
    capability: "preferred_tool_format",
    provider: pair.provider,
    model: pair.model,
    requested_tool_format: requested,
    fallback_tool_format: fallback,
    message: "No preferred_tool_format recommendation for provider/model; using fallback tool_format.",
  }
}

/**
 * Resolve the effective agent tool format without mutating the caller's
 * options. `tool_format: "auto"` is intentionally treated the same as an
 * omitted value.
 *
 * @effects: []
 * @allocation: heap
 * @errors: []
 * @api_stability: experimental
 * @example: agent_tool_format_resolution(options)
 */
pub fn agent_tool_format_resolution(options = nil) {
  let opts = options ?? {}
  let explicit = __explicit_tool_format(opts)
  if explicit != nil {
    let pair = __tool_format_pair(opts)
    var preferred = nil
    var parity = nil
    if pair != nil {
      let caps = try {
        provider_capabilities(pair.provider, pair.model)
      }
      if !is_err(caps) {
        let resolved_caps = unwrap(caps)
        preferred = __valid_tool_format(resolved_caps?.preferred_tool_format)
        parity = resolved_caps?.tool_mode_parity
      }
    }
    return {
      tool_format: explicit,
      source: "explicit",
      capability_gap_event: nil,
      tool_format_override_event: __tool_format_override_event(
        pair,
        explicit,
        preferred,
        parity,
        __optional_text(opts?.tool_format_override_reason),
      ),
    }
  }
  let pair = __tool_format_pair(opts)
  if pair != nil {
    let caps = try {
      provider_capabilities(pair.provider, pair.model)
    }
    if !is_err(caps) {
      let preferred = __valid_tool_format(unwrap(caps)?.preferred_tool_format)
      if preferred != nil {
        return {
          tool_format: preferred,
          source: "capabilities",
          provider: pair.provider,
          model: pair.model,
          capability_gap_event: nil,
          tool_format_override_event: nil,
        }
      }
    }
    let fallback = __fallback_tool_format()
    return {
      tool_format: fallback,
      source: "fallback",
      provider: pair.provider,
      model: pair.model,
      capability_gap_event: __capability_gap_event(pair, opts?.tool_format, fallback),
      tool_format_override_event: nil,
    }
  }
  if __has_key(opts, "tool_format") {
    return {
      tool_format: __fallback_tool_format(),
      source: "fallback",
      capability_gap_event: nil,
      tool_format_override_event: nil,
    }
  }
  return {tool_format: nil, source: "unresolved", capability_gap_event: nil, tool_format_override_event: nil}
}

/**
 * Return the concrete tool format a prompt-building helper should use.
 *
 * @effects: []
 * @allocation: heap
 * @errors: []
 * @api_stability: experimental
 * @example: agent_tool_format(options)
 */
pub fn agent_tool_format(options = nil) {
  let resolved = agent_tool_format_resolution(options)
  if resolved?.tool_format != nil {
    return resolved.tool_format
  }
  return __fallback_tool_format()
}

fn __native_tools_complete_naturally(opts) {
  return opts?.tools != nil && opts?.tool_format == "native"
}

fn __task_ledger_deliverable_text(value) {
  let text = if type_of(value) == "string" {
    value
  } else {
    to_string(value)
  }
  return trim(text)
}

fn __task_ledger_from_shorthand(opts) {
  let root_task = trim(opts?.root_task ?? "")
  var deliverables = []
  let shorthand = opts?.deliverables
  if type_of(shorthand) == "list" {
    for (index, item) in iter(shorthand).enumerate() {
      let text = __task_ledger_deliverable_text(item)
      if text != "" {
        deliverables = deliverables
          .push({id: "deliverable-" + to_string(index + 1), text: text, status: "open", note: nil})
      }
    }
  }
  if root_task == "" && len(deliverables) == 0 {
    return nil
  }
  return {root_task: root_task, deliverables: deliverables, rationale: "", observations: []}
}

fn __with_task_ledger_shorthand(opts) {
  if __has_key(opts, "task_ledger") {
    return opts
  }
  let ledger = __task_ledger_from_shorthand(opts)
  if ledger == nil {
    return opts
  }
  return opts + {task_ledger: ledger}
}

fn __validate_done_sentinel(value) {
  if value == nil {
    return
  }
  let kind = type_of(value)
  if kind != "string" {
    throw "agent_loop: `done_sentinel` must be a non-empty string or nil; got " + kind
  }
  if trim(value) == "" {
    throw "agent_loop: `done_sentinel` must be a non-empty string or nil; got empty string"
  }
}

fn __validate_verify_completion(value) {
  if value == nil {
    return
  }
  if type_of(value) != "closure" {
    throw "agent_loop: `verify_completion` must be a closure or nil; got " + type_of(value)
  }
}

fn __validate_judge_dict_or_bool(label, value) {
  if value == nil {
    return
  }
  let kind = type_of(value)
  if kind != "dict" && kind != "bool" {
    throw "agent_loop: `" + label + "` must be a dict, bool, or nil; got " + kind
  }
}

fn __validate_optional_positive_int(label, field, value) {
  if value == nil {
    return
  }
  if type_of(value) != "int" {
    throw "agent_loop: `" + label + "." + field + "` must be an integer or nil; got "
      + type_of(value)
  }
  if value < 1 {
    throw "agent_loop: `" + label + "." + field + "` must be >= 1"
  }
}

fn __validate_optional_nonnegative_int(label, field, value) {
  if value == nil {
    return
  }
  if type_of(value) != "int" {
    throw "agent_loop: `" + label + "." + field + "` must be an integer or nil; got "
      + type_of(value)
  }
  if value < 0 {
    throw "agent_loop: `" + label + "." + field + "` must be >= 0"
  }
}

fn __validate_judge_cadence(label, value) {
  if value == nil {
    return
  }
  if type_of(value) != "dict" {
    throw "agent_loop: `" + label + "` must be a dict or nil; got " + type_of(value)
  }
  __validate_optional_positive_int(label, "every", value?.every)
  __validate_optional_nonnegative_int(label, "max_invocations", value?.max_invocations)
  __validate_optional_nonnegative_int(
    label,
    "min_iterations_before_first",
    value?.min_iterations_before_first,
  )
  let when = value?.when
  if when == nil {
    return
  }
  let kind = type_of(when)
  if kind == "closure" {
    return
  }
  if kind == "string" && (when == "always" || when == "stalled") {
    return
  }
  throw "agent_loop: `" + label + ".when` must be \"always\", \"stalled\", a closure, or nil; got "
    + to_string(when)
}

fn __validate_done_judge_cadence(value) {
  if type_of(value) == "dict" {
    __validate_judge_cadence("done_judge.cadence", value?.cadence)
  }
}

fn __positive_int_budget_field(value, fallback, label) {
  if value == nil {
    return fallback
  }
  if type_of(value) != "int" {
    throw "agent_loop: `" + label + "` must be a positive integer; got " + type_of(value)
  }
  if value < 1 {
    throw "agent_loop: `" + label + "` must be a positive integer; got " + to_string(value)
  }
  return value
}

fn __nonnegative_int_budget_field(value, fallback, label) {
  if value == nil {
    return fallback
  }
  if type_of(value) != "int" {
    throw "agent_loop: `" + label + "` must be a non-negative integer; got " + type_of(value)
  }
  if value < 0 {
    throw "agent_loop: `" + label + "` must be a non-negative integer; got " + to_string(value)
  }
  return value
}

fn __positive_float_budget_field(value, fallback, label) {
  if value == nil {
    return fallback
  }
  let kind = type_of(value)
  if kind != "float" && kind != "int" {
    throw "agent_loop: `" + label + "` must be a positive number; got " + kind
  }
  let parsed = to_float(value)
  if parsed <= 0.0 {
    throw "agent_loop: `" + label + "` must be a positive number; got " + to_string(value)
  }
  return parsed
}

fn __normalize_consecutive_failure_budget(value) {
  if value == nil {
    return nil
  }
  if type_of(value) != "dict" {
    throw "agent_loop: `iteration_budget.consecutive_failures` must be a dict or nil; got "
      + type_of(value)
  }
  if value?.max == nil {
    throw "agent_loop: `iteration_budget.consecutive_failures.max` is required"
  }
  let max_count = __positive_int_budget_field(value?.max, nil, "iteration_budget.consecutive_failures.max")
  let kinds = value?.kinds ?? ["transient", "rate_limit", "provider_5xx"]
  if type_of(kinds) != "list" {
    throw "agent_loop: `iteration_budget.consecutive_failures.kinds` must be a list of strings; got "
      + type_of(kinds)
  }
  if len(kinds) == 0 {
    throw "agent_loop: `iteration_budget.consecutive_failures.kinds` must not be empty"
  }
  for kind in kinds {
    if type_of(kind) != "string" || kind == "" {
      throw "agent_loop: `iteration_budget.consecutive_failures.kinds` must contain non-empty strings"
    }
  }
  return {
    max: max_count,
    kinds: kinds,
    paused_for_ms: __nonnegative_int_budget_field(
      value?.paused_for_ms,
      0,
      "iteration_budget.consecutive_failures.paused_for_ms",
    ),
  }
}

fn __validate_loop_control(value) {
  if value == nil {
    return
  }
  if type_of(value) != "closure" {
    throw "agent_loop: `loop_control` must be a closure or nil; got " + type_of(value)
  }
}

fn __validate_llm_caller(value) {
  if value == nil {
    return
  }
  if type_of(value) != "closure" {
    throw "agent_loop: `llm_caller` must be a closure or nil; got " + type_of(value)
  }
}

fn __validate_tool_caller(value) {
  if value == nil {
    return
  }
  if type_of(value) != "closure" {
    throw "agent_loop: `tool_caller` must be a closure or nil; got " + type_of(value)
  }
}

fn __validate_structural_validator(value) {
  if value == nil {
    return
  }
  if type_of(value) != "closure" {
    throw "agent_loop: `structural_validator` must be a closure or nil; got " + type_of(value)
  }
}

fn __validate_pre_turn_scope_classifier(value) {
  if value == nil {
    return
  }
  if type_of(value) != "closure" {
    throw "agent_loop: `pre_turn_scope_classifier` must be a closure or nil; got " + type_of(value)
  }
}

fn __validate_max_concurrent_tools(value) {
  if value == nil {
    return
  }
  if type_of(value) != "int" {
    throw "agent_loop: `max_concurrent_tools` must be an integer or nil; got " + type_of(value)
  }
  if value < 1 {
    throw "agent_loop: `max_concurrent_tools` must be >= 1; got " + to_string(value)
  }
}

fn __validate_prefetch_next_turn(value) {
  if value == nil {
    return
  }
  if type_of(value) != "bool" {
    throw "agent_loop: `prefetch_next_turn` must be a bool or nil; got " + type_of(value)
  }
}

fn __validate_string_list(label, value) {
  if value == nil {
    return
  }
  if type_of(value) != "list" {
    throw label + " must be a list of strings or nil; got " + type_of(value)
  }
  for item in value {
    if type_of(item) != "string" || item == "" {
      throw label + " entries must be non-empty strings"
    }
  }
}

fn __default_tool_surface_hard_keep() {
  return [
    "look",
    "search",
    "lookup",
    "replace_symbol",
    "done_sentinel",
    "load_skill",
    "agent_await_resumption",
  ]
}

fn __normalize_tool_surface_narrowing(value) {
  let defaults = {enabled: true, window_turns: 5, hard_keep: __default_tool_surface_hard_keep()}
  if value == nil {
    return defaults
  }
  if type_of(value) == "bool" {
    return defaults + {enabled: value}
  }
  if type_of(value) != "dict" {
    throw "agent_loop: `tool_surface_narrowing` must be a dict, bool, or nil; got " + type_of(value)
  }
  let enabled = value?.enabled ?? defaults.enabled
  if type_of(enabled) != "bool" {
    throw "agent_loop: `tool_surface_narrowing.enabled` must be a bool"
  }
  let window_turns = value?.window_turns ?? value?.narrow_window_turns ?? defaults.window_turns
  if type_of(window_turns) != "int" {
    throw "agent_loop: `tool_surface_narrowing.window_turns` must be an integer"
  }
  if window_turns < 1 {
    throw "agent_loop: `tool_surface_narrowing.window_turns` must be >= 1"
  }
  let hard_keep = value?.hard_keep ?? defaults.hard_keep
  __validate_string_list("agent_loop: `tool_surface_narrowing.hard_keep`", hard_keep)
  return defaults + value + {enabled: enabled, window_turns: window_turns, hard_keep: hard_keep}
}

fn __validate_removed_agent_loop_options(opts) {
  if __has_key(opts, "persistent") {
    throw "agent_loop: `persistent` was removed; use `loop_until_done` for completion looping and `session_id` for transcript persistence"
  }
}

fn __validate_agent_loop_completion_options(opts) {
  if __has_key(opts, "done_sentinel") {
    __validate_done_sentinel(opts.done_sentinel)
  }
  if __has_key(opts, "verify_completion") {
    __validate_verify_completion(opts.verify_completion)
  }
  if __has_key(opts, "verify_completion_judge") {
    __validate_judge_dict_or_bool("verify_completion_judge", opts.verify_completion_judge)
  }
  if __has_key(opts, "done_judge") {
    __validate_judge_dict_or_bool("done_judge", opts.done_judge)
    __validate_done_judge_cadence(opts.done_judge)
  }
}

fn __validate_transcript_projection(value) {
  if value == nil {
    return
  }
  if type_of(value) == "string" {
    let policy = value
    if policy != "raw" && policy != "clean_tool_repair" && policy != "squash_failed_calls"
      && policy != "summary_prefix"
      && policy != "custom" {
      throw "agent_loop: `transcript_projection` policy must be one of raw, clean_tool_repair, squash_failed_calls, summary_prefix, custom; got "
        + policy
    }
    return
  }
  if type_of(value) != "dict" {
    throw "agent_loop: `transcript_projection` must be a string, dict, or nil; got " + type_of(value)
  }
  let policy = value?.policy ?? "raw"
  if type_of(policy) != "string" {
    throw "agent_loop: `transcript_projection.policy` must be a string"
  }
  if policy != "raw" && policy != "clean_tool_repair" && policy != "squash_failed_calls"
    && policy != "summary_prefix"
    && policy != "custom" {
    throw "agent_loop: `transcript_projection.policy` must be one of raw, clean_tool_repair, squash_failed_calls, summary_prefix, custom; got "
      + policy
  }
  if policy == "custom" {
    let projector = value?.projector ?? value?.custom
    if projector == nil || type_of(projector) != "closure" {
      throw "agent_loop: `transcript_projection.policy = \"custom\"` requires a `projector` closure"
    }
  }
  if policy == "summary_prefix" {
    let keep_last = value?.keep_last
    if keep_last != nil && (type_of(keep_last) != "int" || keep_last < 0) {
      throw "agent_loop: `transcript_projection.keep_last` must be a non-negative integer"
    }
  }
}

fn __validate_agent_loop_callback_options(opts) {
  if __has_key(opts, "loop_control") {
    __validate_loop_control(opts.loop_control)
  }
  if __has_key(opts, "llm_caller") {
    __validate_llm_caller(opts.llm_caller)
  }
  if __has_key(opts, "tool_caller") {
    __validate_tool_caller(opts.tool_caller)
  }
  if __has_key(opts, "structural_validator") {
    __validate_structural_validator(opts.structural_validator)
  }
  if __has_key(opts, "pre_turn_scope_classifier") {
    __validate_pre_turn_scope_classifier(opts.pre_turn_scope_classifier)
  }
  if __has_key(opts, "max_concurrent_tools") {
    __validate_max_concurrent_tools(opts.max_concurrent_tools)
  }
  if __has_key(opts, "prefetch_next_turn") {
    __validate_prefetch_next_turn(opts.prefetch_next_turn)
  }
  if __has_key(opts, "tool_surface_narrowing") {
    __normalize_tool_surface_narrowing(opts.tool_surface_narrowing)
  }
  if __has_key(opts, "transcript_projection") {
    __validate_transcript_projection(opts.transcript_projection)
  }
}

fn __normalize_reminder_provider_options(opts) {
  if !__has_key(opts, "reminders") {
    return opts + {reminders: {}}
  }
  if type_of(opts.reminders) == "list" {
    return opts + {reminders: {providers: opts.reminders}}
  }
  return opts
}

fn __with_resolved_tool_format(opts, resolution) {
  if resolution?.tool_format == nil {
    return opts
  }
  var next = opts + {tool_format: resolution.tool_format}
  if resolution?.capability_gap_event != nil {
    next = next + {_tool_format_capability_gap: resolution.capability_gap_event}
  }
  if resolution?.tool_format_override_event != nil {
    next = next + {_tool_format_override: resolution.tool_format_override_event}
  }
  return next
}

fn __normalize_iteration_budget(opts) {
  let raw = opts?.iteration_budget
  let legacy = opts?.max_iterations
  if raw == nil && legacy == nil {
    return {mode: "fixed", initial: 50, max: 50, extend_by: 0, expose_decisions: false}
  }
  let user_budget = if type_of(raw) == "string" {
    {mode: raw}
  } else {
    raw
  }
  if user_budget == nil {
    let cap = __positive_int_budget_field(legacy, 50, "max_iterations")
    return {mode: "fixed", initial: cap, max: cap, extend_by: 0, expose_decisions: false}
  }
  if type_of(user_budget) != "dict" {
    throw "agent_loop: iteration_budget must be a dict, string, or nil; got "
      + type_of(user_budget)
  }
  let mode = user_budget.mode ?? "fixed"
  if mode != "fixed" && mode != "adaptive" {
    throw "agent_loop: iteration_budget.mode must be \"fixed\" or \"adaptive\"; got "
      + to_string(mode)
  }
  let legacy_cap = if legacy != nil {
    __positive_int_budget_field(legacy, 50, "max_iterations")
  } else {
    nil
  }
  let max_default = if mode == "adaptive" {
    16
  } else if legacy_cap != nil {
    legacy_cap
  } else {
    50
  }
  let max_cap = __positive_int_budget_field(user_budget?.max, max_default, "iteration_budget.max")
  let initial_default = if mode == "adaptive" {
    let candidate = max_cap / 4
    if candidate < 1 {
      1
    } else {
      candidate
    }
  } else {
    max_cap
  }
  let initial = __positive_int_budget_field(user_budget?.initial, initial_default, "iteration_budget.initial")
  if initial > max_cap {
    throw "agent_loop: `iteration_budget.initial` must be less than or equal to `iteration_budget.max`; got initial="
      + to_string(initial)
      + ", max="
      + to_string(max_cap)
  }
  let extend_by = if mode == "adaptive" {
    __positive_int_budget_field(user_budget?.extend_by, 2, "iteration_budget.extend_by")
  } else {
    0
  }
  let expose_decisions = if user_budget?.expose_decisions != nil {
    if type_of(user_budget.expose_decisions) != "bool" {
      throw "agent_loop: `iteration_budget.expose_decisions` must be a bool; got "
        + type_of(user_budget.expose_decisions)
    }
    user_budget.expose_decisions
  } else {
    mode == "adaptive"
  }
  return {
    mode: mode,
    initial: initial,
    max: max_cap,
    extend_by: extend_by,
    expose_decisions: expose_decisions,
    wall_clock_ms: __positive_int_budget_field(user_budget?.wall_clock_ms, nil, "iteration_budget.wall_clock_ms"),
    total_cost_usd: __positive_float_budget_field(user_budget?.total_cost_usd, nil, "iteration_budget.total_cost_usd"),
    consecutive_failures: __normalize_consecutive_failure_budget(user_budget?.consecutive_failures),
  }
}

fn __autonomy_tier(value) {
  let tier = value ?? "act_auto"
  if tier == "shadow" || tier == "suggest" || tier == "act_with_approval" || tier == "act_auto" {
    return tier
  }
  throw "autonomy_policy: tier must be one of shadow, suggest, act_with_approval, act_auto"
}

/**
 * autonomy_policy returns the VM-enforced autonomy assignment for an agent.
 *
 * @effects: []
 * @allocation: heap
 * @errors: []
 * @api_stability: experimental
 * @example: autonomy_policy(tier, options)
 */
pub fn autonomy_policy(tier = "act_auto", options = nil) {
  let opts = options ?? {}
  return {
    agent_id: opts?.agent_id ?? opts?.agent,
    autonomy_tier: __autonomy_tier(tier),
    action_tiers: opts?.action_tiers ?? {},
    agent_tiers: opts?.agent_tiers ?? {},
    agent_action_tiers: opts?.agent_action_tiers ?? {},
    reviewers: opts?.reviewers ?? [],
  }
}

/**
 * agent_loop_options.
 *
 * @effects: []
 * @allocation: heap
 * @errors: []
 * @api_stability: experimental
 * @example: agent_loop_options(options)
 */
pub fn agent_loop_options(options = nil) {
  var opts = options ?? {}
  __validate_removed_agent_loop_options(opts)
  __validate_agent_loop_completion_options(opts)
  __validate_agent_loop_callback_options(opts)
  let llm_caller = opts?.llm_caller
  let tool_caller = opts?.tool_caller
  let structural_validator = opts?.structural_validator
  let pre_turn_scope_classifier = opts?.pre_turn_scope_classifier
  let profile = opts?.profile ?? "tool_using"
  let defaults = __profile_defaults(profile)
  opts = defaults + opts
  let tool_format_resolution = agent_tool_format_resolution(opts)
  if __has_key(opts, "tool_format") || opts?.tools != nil {
    opts = __with_resolved_tool_format(opts, tool_format_resolution)
  }
  if !__has_key(opts, "tool_format")
    && (opts?.tools == nil || __client_tool_search_requested(opts?.tool_search)) {
    opts = opts + {tool_format: __fallback_tool_format()}
  }
  if opts?.loop_until_done ?? false && !__has_key(opts, "done_sentinel") {
    opts = opts
      + {
      done_sentinel: if __native_tools_complete_naturally(opts) {
        nil
      } else {
        "##DONE##"
      },
    }
  }
  if __has_key(opts, "done_judge") && __judge_enabled(opts?.done_judge)
    && !__has_key(opts, "done_sentinel")
    && !__native_tools_complete_naturally(opts) {
    opts = opts + {done_sentinel: "##DONE##"}
  }
  if __has_key(opts, "verify_completion_judge") {
    if __judge_enabled(opts?.verify_completion_judge) {
      opts = opts
        + {verify_completion_judge: __completion_judge_defaults(opts?.verify_completion_judge, opts)}
    } else {
      opts = opts + {verify_completion_judge: nil}
    }
  }
  if __has_key(opts, "done_judge") {
    if __judge_enabled(opts?.done_judge) {
      opts = opts + {done_judge: __completion_judge_defaults(opts?.done_judge, opts)}
    } else {
      opts = opts + {done_judge: nil}
    }
  }
  opts = __with_task_ledger_shorthand(opts)
  let budget = __normalize_iteration_budget(opts)
  opts = opts
    + {
    iteration_budget: budget,
    max_iterations: budget.max,
    tool_surface_narrowing: __normalize_tool_surface_narrowing(opts?.tool_surface_narrowing),
  }
  opts = agent_reasoning_apply(opts)
  opts = __normalize_reminder_provider_options(opts)
  opts = opts
    + {
    _llm_caller: llm_caller,
    _tool_caller: tool_caller,
    _structural_validator: structural_validator,
    _pre_turn_scope_classifier: pre_turn_scope_classifier,
  }
  return opts
}