harn-stdlib 0.10.70

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
import { checkpoint_stage_keyed } from "std/checkpoint"
import {
  ExternalActionAdapter,
  ExternalActionAdapterOutcome,
  ExternalActionAdapterResult,
  ExternalActionError,
  ExternalActionGrant,
  ExternalActionIntent,
  ExternalActionNextAction,
  ExternalActionOutcome,
  ExternalActionReceipt,
  ExternalActionReceiptStatus,
  external_action_error,
  external_action_grant_check,
  external_action_grant_integrity_check,
  external_action_intent_is_exact,
} from "std/external_action/contracts"

const EXTERNAL_ACTION_RECEIPT_TOPIC = "external_actions.receipts"

fn __external_action_is_callable(value) -> bool {
  const kind = type_of(value)
  return kind == "closure" || kind == "function"
}

fn __external_action_evidence_result(raw) -> Result<list<string>, ExternalActionError> {
  if raw == nil {
    return Ok([])
  }
  if type_of(raw) != "list" || len(raw) > 20 {
    return Err(
      external_action_error(
        "malformed_adapter_result",
        "invalid_evidence_refs",
        "adapter evidence must be a bounded list of references",
      ),
    )
  }
  let refs: list<string> = []
  for item in raw {
    const reference = trim(to_string(item))
    if reference == "" || len(reference) > 512 || reference.contains("\n")
      || !reference.contains(":") {
      return Err(
        external_action_error(
          "malformed_adapter_result",
          "invalid_evidence_ref",
          "adapter evidence entries must be compact reference identifiers",
        ),
      )
    }
    refs = refs + [reference]
  }
  return Ok(refs)
}

fn __external_action_adapter_result(
  raw: unknown,
) -> Result<ExternalActionAdapterResult, ExternalActionError> {
  if type_of(raw) != "dict" {
    return Err(
      external_action_error(
        "malformed_adapter_result",
        "invalid_adapter_result",
        "adapter result must be an object",
      ),
    )
  }
  const raw_outcome = lowercase(trim(to_string(raw?.outcome ?? "")))
  if raw_outcome != "confirmed" && raw_outcome != "failed_before_dispatch"
    && raw_outcome
    != "indeterminate" {
    return Err(
      external_action_error(
        "malformed_adapter_result",
        "invalid_adapter_outcome",
        "adapter outcome is unsupported",
      ),
    )
  }
  const evidence = __external_action_evidence_result(raw?.evidence_refs)
  if !is_ok(evidence) {
    return Err(unwrap_err(evidence))
  }
  const provider_action_id = trim(to_string(raw?.provider_action_id ?? ""))
  if provider_action_id != "" {
    if len(provider_action_id) > 512 || provider_action_id.contains("\n") {
      return Err(
        external_action_error(
          "malformed_adapter_result",
          "invalid_provider_action_id",
          "provider action id must be a compact identifier",
        ),
      )
    }
  }
  const error_code = trim(to_string(raw?.error_code ?? ""))
  if error_code != "" {
    if regex_match("^[A-Za-z0-9._:-]{1,128}$", error_code) == nil {
      return Err(
        external_action_error(
          "malformed_adapter_result",
          "invalid_adapter_error_code",
          "adapter error code must be a compact machine identifier",
        ),
      )
    }
  }
  if raw_outcome == "confirmed" {
    return Ok(
      __external_action_adapter_result_fields(
        "confirmed",
        unwrap(evidence),
        provider_action_id,
        error_code,
      ),
    )
  }
  if raw_outcome == "failed_before_dispatch" {
    return Ok(
      __external_action_adapter_result_fields(
        "failed_before_dispatch",
        unwrap(evidence),
        provider_action_id,
        error_code,
      ),
    )
  }
  return Ok(
    __external_action_adapter_result_fields(
      "indeterminate",
      unwrap(evidence),
      provider_action_id,
      error_code,
    ),
  )
}

fn __external_action_adapter_result_fields(
  outcome: ExternalActionAdapterOutcome,
  evidence_refs: list<string>,
  provider_action_id: string = "",
  error_code: string = "",
) -> ExternalActionAdapterResult {
  let result: ExternalActionAdapterResult = {outcome: outcome}
  if len(evidence_refs) > 0 {
    result.evidence_refs = evidence_refs
  }
  if provider_action_id != "" {
    result.provider_action_id = provider_action_id
  }
  if error_code != "" {
    result.error_code = error_code
  }
  return result
}

fn __external_action_indeterminate_result(code: string) -> ExternalActionAdapterResult {
  return __external_action_adapter_result_fields("indeterminate", [], "", code)
}

fn __external_action_receipt_fields(
  intent: ExternalActionIntent,
  adapter_id: string,
  outcome: ExternalActionOutcome,
  status: ExternalActionReceiptStatus,
  next_action: ExternalActionNextAction,
  dispatch_attempted: bool,
  recorded_at_ms: int,
  provider_action_id: string?,
  evidence_refs: list<string>,
  error: ExternalActionError?,
  reconciliation,
) -> ExternalActionReceipt {
  let receipt: ExternalActionReceipt = {
    schema: "harn.external_action_receipt.v1",
    id: "receipt_"
      + substring(
      sha256(
        json_stringify(
          {
            action: intent.fingerprint,
            adapter: adapter_id,
            outcome: outcome,
            provider_action_id: provider_action_id,
            reconciliation: reconciliation,
            error_code: error?.code,
          },
        ),
      ),
      0,
      24,
    ),
    action_id: intent.id,
    intent_fingerprint: intent.fingerprint,
    idempotency_key: intent.idempotency_key,
    provider: intent.provider,
    capability: intent.capability,
    operation: intent.operation,
    environment: intent.environment,
    adapter_id: adapter_id,
    outcome: outcome,
    status: status,
    next_action: next_action,
    dispatch_attempted: dispatch_attempted,
    recorded_at_ms: recorded_at_ms,
    evidence_refs: evidence_refs,
  }
  if provider_action_id != nil {
    receipt.provider_action_id = provider_action_id
  }
  if error != nil {
    receipt.error = error
  }
  if reconciliation != nil {
    receipt.reconciliation = reconciliation
  }
  return receipt
}

fn __external_action_receipt(
  intent: ExternalActionIntent,
  adapter_id: string,
  result: ExternalActionAdapterResult,
  recorded_at_ms: int,
  options = {},
) -> ExternalActionReceipt {
  const opts = options ?? {}
  const outcome = result.outcome
  let error: ExternalActionError? = nil
  if result.error_code != nil {
    error = external_action_error(
      "adapter_failure",
      result.error_code,
      outcome == "indeterminate" ? "The provider outcome is unknown and must be reconciled." : "The provider rejected the action before dispatch.",
      outcome == "indeterminate",
    )
  }
  if opts?.error != nil {
    error = opts.error
  }
  if outcome == "confirmed" {
    return __external_action_receipt_fields(
      intent,
      adapter_id,
      "confirmed",
      "confirmed",
      "none",
      opts?.dispatch_attempted ?? true,
      recorded_at_ms,
      result.provider_action_id,
      result.evidence_refs ?? [],
      error,
      opts?.reconciliation,
    )
  }
  if outcome == "failed_before_dispatch" {
    return __external_action_receipt_fields(
      intent,
      adapter_id,
      "failed_before_dispatch",
      "failed_before_dispatch",
      "none",
      opts?.dispatch_attempted ?? false,
      recorded_at_ms,
      result.provider_action_id,
      result.evidence_refs ?? [],
      error,
      opts?.reconciliation,
    )
  }
  return __external_action_receipt_fields(
    intent,
    adapter_id,
    "indeterminate",
    "reconciliation_required",
    "reconcile",
    opts?.dispatch_attempted ?? true,
    recorded_at_ms,
    result.provider_action_id,
    result.evidence_refs ?? [],
    error,
    opts?.reconciliation,
  )
}

fn __external_action_denied_receipt(
  intent: ExternalActionIntent,
  adapter_id: string,
  error: ExternalActionError,
  recorded_at_ms: int,
) -> ExternalActionReceipt {
  return __external_action_receipt_fields(
    intent,
    adapter_id,
    "denied",
    "denied",
    "none",
    false,
    recorded_at_ms,
    nil,
    [],
    error,
    nil,
  )
}

fn __external_action_emit(obs: HarnessObs, receipt: ExternalActionReceipt) {
  obs.event_log_emit(
    EXTERNAL_ACTION_RECEIPT_TOPIC,
    "external_action_receipt",
    receipt,
    {schema: receipt.schema, action_id: receipt.action_id, status: receipt.status},
  )
}

fn __external_action_adapter_id(adapter: ExternalActionAdapter) -> string {
  const id = trim(to_string(adapter.id ?? ""))
  return id == "" ? "unavailable" : id
}

/**
 * Dispatch one exact action at most once for its fingerprint.
 *
 * Invalid grants are not checkpointed, so a later valid authorization may run.
 * Once dispatch begins, even thrown or malformed adapter responses become a
 * durable reconciliation-required receipt and are never blindly retried.
 *
 * @effects: [runtime, observability, external]
 * @errors: []
 */
pub fn external_action_execute(
  harness: Harness,
  intent: ExternalActionIntent,
  grant: ExternalActionGrant,
  adapter: ExternalActionAdapter,
) -> ExternalActionReceipt {
  const adapter_id = __external_action_adapter_id(adapter)
  const now_ms = harness.clock.now_ms()
  if !external_action_intent_is_exact(intent) {
    const denied = __external_action_denied_receipt(
      intent,
      adapter_id,
      external_action_error(
        "invalid_grant",
        "intent_fingerprint_mismatch",
        "intent fingerprint does not match its effect",
      ),
      now_ms,
    )
    __external_action_emit(harness.obs, denied)
    return denied
  }
  if !__external_action_is_callable(adapter.dispatch) {
    const denied = __external_action_denied_receipt(
      intent,
      adapter_id,
      external_action_error(
        "adapter_unavailable",
        "dispatch_unavailable",
        "external action adapter has no dispatch function",
      ),
      now_ms,
    )
    __external_action_emit(harness.obs, denied)
    return denied
  }
  const attempted = try {
    checkpoint_stage_keyed(
      harness.runtime,
      "external_action.dispatch." + substring(intent.fingerprint, 7, len(intent.fingerprint)),
      {intent_fingerprint: intent.fingerprint},
      fn() {
        const grant_check = external_action_grant_check(intent, grant, harness.clock.now_ms())
        if !is_ok(grant_check) {
          throw {external_action_denied: true, error: unwrap_err(grant_check)}
        }
        const request = {
          schema: "harn.external_action_dispatch_request.v1",
          intent: intent,
          grant: grant,
          idempotency_key: intent.idempotency_key,
        }
        const raw = try {
          adapter.dispatch(harness, request)
        }
        const receipt = if !is_ok(raw) {
          __external_action_receipt(
            intent,
            adapter_id,
            __external_action_indeterminate_result("adapter_threw"),
            harness.clock.now_ms(),
            {
              error: external_action_error(
                "adapter_failure",
                "adapter_threw",
                "The provider outcome is unknown and must be reconciled.",
                true,
              ),
            },
          )
        } else {
          const normalized = __external_action_adapter_result(unwrap(raw))
          if !is_ok(normalized) {
            __external_action_receipt(
              intent,
              adapter_id,
              __external_action_indeterminate_result("malformed_adapter_result"),
              harness.clock.now_ms(),
              {error: unwrap_err(normalized)},
            )
          } else {
            __external_action_receipt(
              intent,
              adapter_id,
              unwrap(normalized),
              harness.clock.now_ms(),
            )
          }
        }
        __external_action_emit(harness.obs, receipt)
        return receipt
      },
    )
  }
  if is_ok(attempted) {
    return unwrap(attempted)
  }
  const thrown = unwrap_err(attempted)
  const error = if type_of(thrown) == "dict" && thrown?.external_action_denied == true {
    thrown.error
  } else {
    external_action_error(
      "adapter_failure",
      "dispatch_checkpoint_failed",
      "The action did not reach the provider.",
    )
  }
  const denied = __external_action_denied_receipt(intent, adapter_id, error, now_ms)
  __external_action_emit(harness.obs, denied)
  return denied
}

/**
 * Query an ambiguous provider outcome without invoking dispatch again.
 * Callers supply a stable `attempt_id`; replay of that attempt is checkpointed,
 * while a later polling attempt can use a new id.
 *
 * @effects: [runtime, observability, external]
 * @errors: [invalid_reconciliation]
 */
pub fn external_action_reconcile(
  harness: Harness,
  intent: ExternalActionIntent,
  grant: ExternalActionGrant,
  receipt: ExternalActionReceipt,
  adapter: ExternalActionAdapter,
  attempt_id: string,
) -> ExternalActionReceipt {
  const normalized_attempt = trim(attempt_id)
  require normalized_attempt != "", "external_action_reconcile: attempt_id is required"
  require external_action_intent_is_exact(intent),
    "external_action_reconcile: intent fingerprint mismatch"
  require receipt.intent_fingerprint == intent.fingerprint
    && receipt.status
    == "reconciliation_required",
    "external_action_reconcile: receipt is not reconcilable"
  const grant_integrity = external_action_grant_integrity_check(intent, grant)
  require is_ok(grant_integrity), "external_action_reconcile: grant does not match the action"
  require __external_action_is_callable(adapter.reconcile),
    "external_action_reconcile: adapter has no reconcile function"
  const completed = checkpoint_stage_keyed(
    harness.runtime,
    "external_action.reconcile."
      + substring(intent.fingerprint, 7, len(intent.fingerprint))
      + "."
      + sha256(normalized_attempt),
    {
      intent_fingerprint: intent.fingerprint,
      receipt_id: receipt.id,
      attempt_id: normalized_attempt,
    },
    fn() {
      const request = {
        schema: "harn.external_action_reconcile_request.v1",
        intent: intent,
        grant: grant,
        receipt: receipt,
        attempt_id: normalized_attempt,
      }
      const raw = try {
        adapter.reconcile(harness, request)
      }
      const normalized: Result<ExternalActionAdapterResult, ExternalActionError> = if !is_ok(raw) {
        Ok(__external_action_indeterminate_result("reconcile_threw"))
      } else {
        __external_action_adapter_result(unwrap(raw))
      }
      const next = if !is_ok(normalized) {
        __external_action_receipt(
          intent,
          __external_action_adapter_id(adapter),
          __external_action_indeterminate_result("malformed_reconcile_result"),
          harness.clock.now_ms(),
          {
            error: unwrap_err(normalized),
            reconciliation: {attempt_id: normalized_attempt, previous_receipt_id: receipt.id},
          },
        )
      } else {
        __external_action_receipt(
          intent,
          __external_action_adapter_id(adapter),
          unwrap(normalized),
          harness.clock.now_ms(),
          {reconciliation: {attempt_id: normalized_attempt, previous_receipt_id: receipt.id}},
        )
      }
      __external_action_emit(harness.obs, next)
      return next
    },
  )
  require type_of(completed) == "dict"
    && completed?.schema == "harn.external_action_receipt.v1"
    && completed?.intent_fingerprint
    == intent
    .fingerprint,
    "external_action_reconcile: checkpoint returned an invalid receipt"
  const typed: any = completed
  return typed
}