harn-stdlib 0.7.57

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
/**
 * std/personas/prelude — small orchestration primitives for persona scripts.
 *
 * The helpers return explicit envelopes so callers can persist, render, or
 * compose them without depending on ambient host state.
 */
fn __prelude_is_callable(value) -> bool {
  let kind = type_of(value)
  return kind == "function" || kind == "closure" || kind == "fn"
}

fn __prelude_digest(value) {
  if value == nil {
    return nil
  }
  return "sha256:" + sha256(json_stringify(value))
}

fn __prelude_error_object(error) {
  if error == nil {
    return nil
  }
  if type_of(error) == "dict" {
    return error
  }
  return {message: to_string(error)}
}

fn __prelude_error_message(error) -> string {
  if error == nil {
    return ""
  }
  if type_of(error) == "dict" {
    return error?.message ?? json_stringify(error)
  }
  return to_string(error)
}

fn __prelude_as_result(value) {
  let ok_probe = try {
    is_ok(value)
  }
  if is_ok(ok_probe) && unwrap(ok_probe) {
    return {ok: true, value: unwrap(value), error: nil}
  }
  let err_probe = try {
    is_err(value)
  }
  if is_ok(err_probe) && unwrap(err_probe) {
    return {ok: false, value: nil, error: unwrap_err(value)}
  }
  if type_of(value) == "dict" && value?.ok != nil {
    return {ok: value.ok, value: value?.value ?? value?.result, error: value?.error}
  }
  if type_of(value) == "dict" && value?.status != nil {
    let status = lowercase(to_string(value.status))
    let ok = contains(["ok", "pass", "passed", "success", "succeeded"], status)
    return {
      ok: ok,
      value: value,
      error: if ok {
        nil
      } else {
        value
      },
    }
  }
  if type_of(value) == "bool" {
    return {
      ok: value,
      value: value,
      error: if value {
        nil
      } else {
        {message: "predicate returned false"}
      },
    }
  }
  return {
    ok: value != nil,
    value: value,
    error: if value == nil {
      {message: "predicate returned nil"}
    } else {
      nil
    },
  }
}

fn __prelude_receipt_id(opts, status, calls) -> string {
  if opts?.id != nil {
    return opts.id
  }
  let seed = {
    persona: opts?.persona ?? "persona_prelude",
    step: opts?.step,
    trace_id: opts?.trace_id ?? "",
    started_at: opts?.started_at ?? "",
    status: status,
    inputs_digest: opts?.inputs_digest ?? __prelude_digest(opts?.input),
    calls: calls,
  }
  return "receipt-" + substring(sha256(json_stringify(seed)), 0, 16)
}

fn __prelude_receipt(opts, status, result, error, calls, approvals, side_effects) {
  let options = opts ?? {}
  let started_at = options?.started_at ?? date_iso()
  let completed_at = options?.completed_at ?? started_at
  let persona = options?.persona ?? "persona_prelude"
  let input_digest = options?.inputs_digest ?? __prelude_digest(options?.input)
  let output_digest = options?.outputs_digest ?? __prelude_digest(result)
  return {
    schema: "harn.receipt.v1",
    id: __prelude_receipt_id(options + {started_at: started_at}, status, calls),
    parent_run_id: options?.parent_run_id,
    persona: persona,
    step: options?.step,
    trace_id: options?.trace_id ?? ("trace-" + substring(sha256(started_at + ":" + persona), 0, 16)),
    started_at: started_at,
    completed_at: completed_at,
    status: status,
    inputs_digest: input_digest,
    outputs_digest: output_digest,
    model_calls: options?.model_calls ?? [],
    tool_calls: calls ?? [],
    cost_usd: options?.cost_usd ?? 0.0,
    approvals: approvals ?? [],
    handoffs: options?.handoffs ?? [],
    side_effects: side_effects ?? [],
    error: __prelude_error_object(error),
    redaction_class: options?.redaction_class ?? "internal",
    metadata: options?.metadata ?? {},
  }
}

fn __prelude_call_record(name, status, value, error) {
  return {
    name: name,
    status: status,
    outputs_digest: __prelude_digest(value),
    error: __prelude_error_object(error),
  }
}

/**
 * Run a deterministic verifier, then run actor only when the verifier
 * returns an ok-shaped value.
 */
pub fn verify_then_act(verifier, actor, options = nil) {
  let opts = options ?? {}
  let started_at = opts?.started_at ?? date_iso()
  let verifier_name = opts?.verifier_name ?? "verifier"
  let actor_name = opts?.actor_name ?? "actor"
  let verified_raw = try {
    verifier()
  }
  if is_err(verified_raw) {
    let error = unwrap_err(verified_raw)
    let calls = [__prelude_call_record(verifier_name, "failure", nil, error)]
    return {
      ok: false,
      status: "verification_error",
      verified: false,
      acted: false,
      result: nil,
      error: __prelude_error_object(error),
      receipt: __prelude_receipt(opts + {started_at: started_at}, "failure", nil, error, calls, [], []),
    }
  }
  let verified = __prelude_as_result(unwrap(verified_raw))
  var calls = [
    __prelude_call_record(
      verifier_name,
      if verified.ok {
        "success"
      } else {
        "denied"
      },
      verified.value,
      verified.error,
    ),
  ]
  if !verified.ok {
    return {
      ok: false,
      status: "verification_failed",
      verified: false,
      acted: false,
      result: nil,
      error: __prelude_error_object(verified.error),
      receipt: __prelude_receipt(opts + {started_at: started_at}, "denied", nil, verified.error, calls, [], []),
    }
  }
  let acted = try {
    actor()
  }
  if is_err(acted) {
    let error = unwrap_err(acted)
    calls = calls + [__prelude_call_record(actor_name, "failure", nil, error)]
    return {
      ok: false,
      status: "actor_error",
      verified: true,
      acted: true,
      result: nil,
      error: __prelude_error_object(error),
      receipt: __prelude_receipt(opts + {started_at: started_at}, "failure", nil, error, calls, [], []),
    }
  }
  let result = unwrap(acted)
  calls = calls + [__prelude_call_record(actor_name, "success", result, nil)]
  return {
    ok: true,
    status: "success",
    verified: true,
    acted: true,
    result: result,
    error: nil,
    receipt: __prelude_receipt(opts + {started_at: started_at}, "success", result, nil, calls, [], []),
  }
}

/**
 * Run step_fn(state) until it reports done, makes no progress, or exhausts
 * the supplied iteration/time budget.
 */
pub fn bounded_loop(state_init, step_fn, options = nil) {
  let opts = options ?? {}
  let started_at = opts?.started_at ?? date_iso()
  let started_ms = timestamp() * 1000
  let max_iterations = opts?.max_iterations ?? 10
  let max_duration_ms = opts?.max_duration_ms ?? opts?.max_duration
  let progress_required = opts?.progress_required ?? false
  var state = nil
  if __prelude_is_callable(state_init) {
    let init_outcome = try {
      state_init()
    }
    if is_err(init_outcome) {
      let error = unwrap_err(init_outcome)
      let calls = [__prelude_call_record("state_init", "failure", nil, error)]
      return {
        ok: false,
        status: "failure",
        state: nil,
        iterations: 0,
        stopped_reason: "state_init_error",
        history: [],
        error: __prelude_error_object(error),
        receipt: __prelude_receipt(opts + {started_at: started_at}, "failure", nil, error, calls, [], []),
      }
    }
    state = unwrap(init_outcome)
  } else {
    state = state_init
  }
  var history = []
  var iterations = 0
  var stopped_reason = "max_iterations"
  while iterations < max_iterations {
    if max_duration_ms != nil && timestamp() * 1000 - started_ms >= max_duration_ms {
      stopped_reason = "max_duration"
      break
    }
    let before_digest = __prelude_digest(state)
    let step_outcome = try {
      step_fn(state)
    }
    iterations += 1
    if is_err(step_outcome) {
      let error = unwrap_err(step_outcome)
      let calls = [__prelude_call_record("loop_step", "failure", nil, error)]
      return {
        ok: false,
        status: "failure",
        state: state,
        iterations: iterations,
        stopped_reason: "error",
        history: history,
        error: __prelude_error_object(error),
        receipt: __prelude_receipt(opts + {started_at: started_at}, "failure", state, error, calls, [], []),
      }
    }
    let step_value = unwrap(step_outcome)
    let is_envelope = type_of(step_value) == "dict"
      && (step_value?.state != nil || step_value?.done != nil || step_value?.progress != nil
      || step_value?.progress_made != nil)
    let next_state = if is_envelope && step_value?.state != nil {
      step_value.state
    } else {
      step_value
    }
    let next_digest = __prelude_digest(next_state)
    let progressed = if is_envelope && step_value?.progress != nil {
      step_value.progress
    } else {
      if is_envelope && step_value?.progress_made != nil {
        step_value.progress_made
      } else {
        next_digest != before_digest
      }
    }
    let done = is_envelope && step_value?.done ?? false
    history = history + [{iteration: iterations, progress: progressed, done: done}]
    state = next_state
    if done {
      stopped_reason = "done"
      break
    }
    if progress_required && !progressed {
      stopped_reason = "no_progress"
      break
    }
  }
  let status = if stopped_reason == "done" {
    "completed"
  } else {
    "stopped"
  }
  let calls = [__prelude_call_record("bounded_loop", status, state, nil)]
  return {
    ok: status == "completed" || stopped_reason == "max_iterations" || stopped_reason == "no_progress",
    status: status,
    state: state,
    iterations: iterations,
    stopped_reason: stopped_reason,
    history: history,
    receipt: __prelude_receipt(
      opts + {started_at: started_at},
      if status == "completed" {
        "success"
      } else {
        "noop"
      },
      state,
      nil,
      calls,
      [],
      [],
    ),
  }
}

fn __prelude_invoke_model(input, model_spec, options) {
  let opts = options ?? {}
  if __prelude_is_callable(model_spec) {
    return model_spec(input)
  }
  if type_of(model_spec) == "dict" {
    let prompt = to_string(model_spec?.prompt ?? input)
    let system = model_spec?.system ?? opts?.system
    return llm_call(prompt, system, opts + model_spec)
  }
  return llm_call(to_string(input), opts?.system, opts + {model: model_spec})
}

fn __prelude_confidence(value) {
  if type_of(value) == "dict" && value?.confidence != nil {
    return value.confidence
  }
  return 1.0
}

/**
 * Classify with a cheap route first, then escalate when confidence is low
 * or the caller-supplied predicate returns true.
 */
pub fn cheap_classify_then_escalate(
  input,
  cheap_model,
  escalate_model,
  escalation_predicate,
  options = nil,
) {
  let opts = options ?? {}
  let started_at = opts?.started_at ?? date_iso()
  let min_confidence = opts?.min_confidence ?? 0.7
  let cheap_result = try {
    __prelude_invoke_model(input, cheap_model, opts?.cheap_options ?? {})
  }
  var calls = []
  if is_err(cheap_result) {
    let cheap_error = unwrap_err(cheap_result)
    calls = calls + [__prelude_call_record("cheap_classify", "failure", nil, cheap_error)]
    let escalated_after_error = try {
      __prelude_invoke_model(input, escalate_model, opts?.escalate_options ?? {})
    }
    if is_err(escalated_after_error) {
      let error = unwrap_err(escalated_after_error)
      calls = calls + [__prelude_call_record("escalate_classify", "failure", nil, error)]
      return {
        ok: false,
        status: "failure",
        escalated: true,
        result: nil,
        cheap: nil,
        error: __prelude_error_object(error),
        receipt: __prelude_receipt(opts + {started_at: started_at}, "failure", nil, error, calls, [], []),
      }
    }
    let result = unwrap(escalated_after_error)
    calls = calls + [__prelude_call_record("escalate_classify", "success", result, nil)]
    return {
      ok: true,
      status: "escalated",
      escalated: true,
      result: result,
      cheap: nil,
      error: nil,
      receipt: __prelude_receipt(opts + {started_at: started_at}, "success", result, nil, calls, [], []),
    }
  }
  let cheap = unwrap(cheap_result)
  calls = calls + [__prelude_call_record("cheap_classify", "success", cheap, nil)]
  var should_escalate = __prelude_confidence(cheap) < min_confidence
  if __prelude_is_callable(escalation_predicate) {
    let predicate_outcome = try {
      escalation_predicate(cheap)
    }
    if is_err(predicate_outcome) {
      let predicate_error = unwrap_err(predicate_outcome)
      calls = calls + [__prelude_call_record("escalation_predicate", "failure", nil, predicate_error)]
      should_escalate = true
    } else if unwrap(predicate_outcome) {
      should_escalate = true
    }
  }
  if !should_escalate {
    return {
      ok: true,
      status: "cheap",
      escalated: false,
      result: cheap,
      cheap: cheap,
      error: nil,
      receipt: __prelude_receipt(opts + {started_at: started_at}, "success", cheap, nil, calls, [], []),
    }
  }
  let escalated = try {
    __prelude_invoke_model(input, escalate_model, opts?.escalate_options ?? {})
  }
  if is_err(escalated) {
    let error = unwrap_err(escalated)
    calls = calls + [__prelude_call_record("escalate_classify", "failure", nil, error)]
    return {
      ok: false,
      status: "failure",
      escalated: true,
      result: nil,
      cheap: cheap,
      error: __prelude_error_object(error),
      receipt: __prelude_receipt(opts + {started_at: started_at}, "failure", nil, error, calls, [], []),
    }
  }
  let result = unwrap(escalated)
  calls = calls + [__prelude_call_record("escalate_classify", "success", result, nil)]
  return {
    ok: true,
    status: "escalated",
    escalated: true,
    result: result,
    cheap: cheap,
    error: nil,
    receipt: __prelude_receipt(opts + {started_at: started_at}, "success", result, nil, calls, [], []),
  }
}

/**
 * Execute items in bounded parallel batches and stop scheduling new work when
 * failures reach the circuit-breaker threshold.
 */
pub fn parallel_sweep_with_circuit_breaker(items, step_fn, options = nil) {
  let opts = options ?? {}
  let started_at = opts?.started_at ?? date_iso()
  var max_concurrent = opts?.max_concurrent ?? 4
  if max_concurrent < 1 {
    max_concurrent = 1
  }
  let max_failures = opts?.max_failures ?? 1
  var index = 0
  var succeeded = 0
  var failed = 0
  var results = []
  var broken = false
  while index < len(items) {
    var end_index = index + max_concurrent
    if end_index > len(items) {
      end_index = len(items)
    }
    let batch = items[index:end_index]
    let settled = parallel settle batch { item ->
      step_fn(item)
    }
    for item_result in settled.results {
      if is_ok(item_result) {
        let value = unwrap(item_result)
        succeeded += 1
        results = results + [{ok: true, value: value, error: nil}]
      } else {
        let error = unwrap_err(item_result)
        failed += 1
        results = results + [{ok: false, value: nil, error: __prelude_error_object(error)}]
      }
    }
    index = end_index
    if failed >= max_failures {
      broken = true
      break
    }
  }
  let skipped = len(items) - index
  if broken && __prelude_is_callable(opts?.on_break) {
    opts.on_break({failed: failed, skipped: skipped, succeeded: succeeded})
  }
  let status = if broken {
    "circuit_open"
  } else {
    "completed"
  }
  let calls = [
    __prelude_call_record(
      "parallel_sweep",
      status,
      {succeeded: succeeded, failed: failed, skipped: skipped},
      nil,
    ),
  ]
  return {
    ok: !broken,
    status: status,
    circuit_open: broken,
    succeeded: succeeded,
    failed: failed,
    skipped: skipped,
    results: results,
    receipt: __prelude_receipt(
      opts + {started_at: started_at},
      if broken {
        "failure"
      } else {
        "success"
      },
      results,
      nil,
      calls,
      [],
      [],
    ),
  }
}

/** Return a wrapper that runs a step and attaches a canonical receipt envelope. */
pub fn with_audit_receipt(step_fn, options = nil) {
  let opts = options ?? {}
  return fn() {
    let started_at = opts?.started_at ?? date_iso()
    let outcome = try {
      step_fn()
    }
    if is_err(outcome) {
      let error = unwrap_err(outcome)
      let calls = [__prelude_call_record(opts?.step ?? "step", "failure", nil, error)]
      return {
        ok: false,
        status: "failure",
        result: nil,
        error: __prelude_error_object(error),
        receipt: __prelude_receipt(opts + {started_at: started_at}, "failure", nil, error, calls, [], []),
      }
    }
    let result = unwrap(outcome)
    let calls = [__prelude_call_record(opts?.step ?? "step", "success", result, nil)]
    return {
      ok: true,
      status: "success",
      result: result,
      error: nil,
      receipt: __prelude_receipt(opts + {started_at: started_at}, "success", result, nil, calls, [], []),
    }
  }
}

/**
 * Return a wrapper that requires an approval record before running a step.
 * Without an approval record or `request_approval: true`, the wrapper returns
 * a suspended envelope instead of blocking indefinitely.
 */
pub fn with_approval_gate(approval_kind, step_fn, options = nil) {
  let opts = options ?? {}
  return fn() {
    let started_at = opts?.started_at ?? date_iso()
    var approval = opts?.approval
    if approval == nil && opts?.request_approval ?? false {
      let requested = try {
        request_approval(to_string(approval_kind), opts?.approval_options ?? {})
      }
      if is_err(requested) {
        let error = unwrap_err(requested)
        let status = if __prelude_error_message(error).contains("timeout") {
          "suspended"
        } else {
          "denied"
        }
        let calls = [__prelude_call_record("approval_gate", status, nil, error)]
        return {
          ok: false,
          status: status,
          approval_required: true,
          approval_kind: approval_kind,
          result: nil,
          error: __prelude_error_object(error),
          receipt: __prelude_receipt(
            opts + {started_at: started_at, step: opts?.step ?? to_string(approval_kind)},
            if status == "denied" {
              "denied"
            } else {
              "running"
            },
            nil,
            error,
            calls,
            [],
            [],
          ),
        }
      }
      approval = unwrap(requested)
    }
    if approval == nil {
      let calls = [__prelude_call_record("approval_gate", "suspended", nil, nil)]
      return {
        ok: false,
        status: "suspended",
        approval_required: true,
        approval_kind: approval_kind,
        result: nil,
        error: nil,
        receipt: __prelude_receipt(
          opts + {started_at: started_at, step: opts?.step ?? to_string(approval_kind)},
          "running",
          nil,
          nil,
          calls,
          [],
          [],
        ),
      }
    }
    if !(approval?.approved ?? false) {
      let error = {message: approval?.reason ?? "approval denied"}
      let calls = [__prelude_call_record("approval_gate", "denied", nil, error)]
      return {
        ok: false,
        status: "denied",
        approval_required: true,
        approval_kind: approval_kind,
        result: nil,
        error: error,
        receipt: __prelude_receipt(
          opts + {started_at: started_at, step: opts?.step ?? to_string(approval_kind)},
          "denied",
          nil,
          error,
          calls,
          [approval],
          [],
        ),
      }
    }
    let outcome = try {
      step_fn()
    }
    if is_err(outcome) {
      let error = unwrap_err(outcome)
      let calls = [
        __prelude_call_record("approval_gate", "success", approval, nil),
        __prelude_call_record(opts?.step ?? "approved_step", "failure", nil, error),
      ]
      return {
        ok: false,
        status: "failure",
        approval_required: false,
        approval_kind: approval_kind,
        result: nil,
        error: __prelude_error_object(error),
        receipt: __prelude_receipt(
          opts + {started_at: started_at, step: opts?.step ?? to_string(approval_kind)},
          "failure",
          nil,
          error,
          calls,
          [approval],
          [],
        ),
      }
    }
    let result = unwrap(outcome)
    let calls = [
      __prelude_call_record("approval_gate", "success", approval, nil),
      __prelude_call_record(opts?.step ?? "approved_step", "success", result, nil),
    ]
    return {
      ok: true,
      status: "success",
      approval_required: false,
      approval_kind: approval_kind,
      result: result,
      error: nil,
      receipt: __prelude_receipt(
        opts + {started_at: started_at, step: opts?.step ?? to_string(approval_kind)},
        "success",
        result,
        nil,
        calls,
        [approval],
        [],
      ),
    }
  }
}