@agenticprimitives/orchestration 0.0.0-alpha.1 → 0.0.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/dist/admission.d.ts +87 -0
  2. package/dist/admission.d.ts.map +1 -0
  3. package/dist/admission.js +193 -0
  4. package/dist/admission.js.map +1 -0
  5. package/dist/artifacts.d.ts +137 -0
  6. package/dist/artifacts.d.ts.map +1 -0
  7. package/dist/artifacts.js +232 -0
  8. package/dist/artifacts.js.map +1 -0
  9. package/dist/authority.d.ts +431 -0
  10. package/dist/authority.d.ts.map +1 -0
  11. package/dist/authority.js +2 -0
  12. package/dist/authority.js.map +1 -0
  13. package/dist/durable.d.ts +44 -0
  14. package/dist/durable.d.ts.map +1 -0
  15. package/dist/durable.js +15 -0
  16. package/dist/durable.js.map +1 -0
  17. package/dist/flow-trace.d.ts +105 -0
  18. package/dist/flow-trace.d.ts.map +1 -0
  19. package/dist/flow-trace.js +60 -0
  20. package/dist/flow-trace.js.map +1 -0
  21. package/dist/index.d.ts +20 -1
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +21 -1
  24. package/dist/index.js.map +1 -1
  25. package/dist/input.d.ts +165 -0
  26. package/dist/input.d.ts.map +1 -0
  27. package/dist/input.js +33 -0
  28. package/dist/input.js.map +1 -0
  29. package/dist/loop.d.ts +115 -3
  30. package/dist/loop.d.ts.map +1 -1
  31. package/dist/loop.js +656 -30
  32. package/dist/loop.js.map +1 -1
  33. package/dist/metrics.d.ts +35 -0
  34. package/dist/metrics.d.ts.map +1 -0
  35. package/dist/metrics.js +98 -0
  36. package/dist/metrics.js.map +1 -0
  37. package/dist/planner-wire.d.ts +11 -0
  38. package/dist/planner-wire.d.ts.map +1 -0
  39. package/dist/planner-wire.js +53 -0
  40. package/dist/planner-wire.js.map +1 -0
  41. package/dist/planner.d.ts +33 -0
  42. package/dist/planner.d.ts.map +1 -1
  43. package/dist/planner.js.map +1 -1
  44. package/dist/record.d.ts +151 -0
  45. package/dist/record.d.ts.map +1 -0
  46. package/dist/record.js +72 -0
  47. package/dist/record.js.map +1 -0
  48. package/dist/spans.d.ts +200 -0
  49. package/dist/spans.d.ts.map +1 -0
  50. package/dist/spans.js +522 -0
  51. package/dist/spans.js.map +1 -0
  52. package/dist/tool-invoker.d.ts +7 -0
  53. package/dist/tool-invoker.d.ts.map +1 -1
  54. package/dist/trace-context.d.ts +26 -0
  55. package/dist/trace-context.d.ts.map +1 -0
  56. package/dist/trace-context.js +59 -0
  57. package/dist/trace-context.js.map +1 -0
  58. package/dist/types.d.ts +180 -3
  59. package/dist/types.d.ts.map +1 -1
  60. package/dist/types.js.map +1 -1
  61. package/package.json +4 -1
package/dist/loop.js CHANGED
@@ -1,4 +1,22 @@
1
+ // runIntent — the agentic loop (intent → plan → execute → observe → bounded re-plan). The capstone primitive
2
+ // of ADR-0044: a first-party surface posts a GOAL; this loop decides + composes tools to satisfy it. Pure:
3
+ // the planner, the tool invoker and the authority ports are injected; this module owns only the control
4
+ // flow + fail-closed gates.
5
+ //
6
+ // Spec 350 §4 — for every step whose TOOL declares a capability, the loop runs the authority path BEFORE
7
+ // invoking it, and again after any approval:
8
+ //
9
+ // verify ─▶ deny ─▶ receipt(denied) ─▶ run outcome `denied`. NO re-plan, NO fallback: a
10
+ // │ denial is not a tool failure, and a planner that could route around
11
+ // │ one would be an authority escalation.
12
+ // ├─▶ approval-required ─▶ policy adds obligations ─▶ ApprovalPort ─▶ discharged? ─▶ RE-VERIFY
13
+ // └─▶ allow ─▶ policy adds obligations ─▶ (same, if any) ─▶ execute ─▶ receipt
14
+ //
15
+ // A step with no capability skips the path and still emits a receipt: the trace is the product, and
16
+ // "nothing was verified" is itself a fact worth recording.
17
+ import { compactObservations } from './artifacts.js';
1
18
  import { OrchestrationError } from './types.js';
19
+ import { inputsFor, isInputRequired, receiptPending } from './input.js';
2
20
  /** Read a dot/index path (e.g. `list.record_types.0.record_type`) out of the ref store. A bare name with no
3
21
  * dots is a plain top-level lookup. A missing segment short-circuits to `undefined` (the tool then validates
4
22
  * its own args — fail-closed, no path traversal / eval). */
@@ -26,6 +44,29 @@ function resolveValue(v, refs) {
26
44
  function resolveArgs(args, refs) {
27
45
  return resolveValue(args, refs);
28
46
  }
47
+ /** Per-item substitution for a fanned-out step: the literal `'$item'` becomes the element; an
48
+ * `{ $item: 'path' }` object becomes a field of it. Applied at EXPANSION, so each expanded step's args
49
+ * are concrete before normalisation, verification, or anything else reads them. */
50
+ function substituteItem(args, item) {
51
+ const walk = (v) => {
52
+ if (v === '$item')
53
+ return item;
54
+ if (v && typeof v === 'object' && !Array.isArray(v)) {
55
+ const o = v;
56
+ if (typeof o.$item === 'string') {
57
+ let out = item;
58
+ for (const seg of o.$item.split('.').filter(Boolean))
59
+ out = out?.[seg];
60
+ return out;
61
+ }
62
+ return Object.fromEntries(Object.entries(o).map(([k, x]) => [k, walk(x)]));
63
+ }
64
+ if (Array.isArray(v))
65
+ return v.map(walk);
66
+ return v;
67
+ };
68
+ return walk(args);
69
+ }
29
70
  /** Assert every step targets an exposed tool — fail-closed before any invocation (ADR-0013). */
30
71
  function assertKnownTools(plan, toolIds) {
31
72
  for (const step of plan.steps) {
@@ -46,68 +87,653 @@ async function callPlanner(planner, input) {
46
87
  throw new OrchestrationError('planner_failed', e instanceof Error ? e.message : String(e));
47
88
  }
48
89
  }
90
+ /** The step joined to its tool's declaration — what the authority layer judges. Risk and capability come
91
+ * from the TOOL; the plan cannot lower them. */
92
+ function resolveStep(runRef, index, step, tool, args) {
93
+ const stepRef = step.id ?? `s${index}`;
94
+ const cap = tool.capability;
95
+ const risk = !cap ? 'informational' : tool.irreversible ? 'critical' : (tool.risk ?? 'low');
96
+ const resourceRaw = cap?.resourceArg ? args[cap.resourceArg] : undefined;
97
+ const authorityRaw = cap?.authorityArg ? args[cap.authorityArg] : undefined;
98
+ const needsKey = risk === 'medium' || risk === 'high' || risk === 'critical';
99
+ return {
100
+ runRef, stepRef, index, step, tool, args,
101
+ capability: cap
102
+ ? {
103
+ id: cap.id, action: cap.action,
104
+ ...(typeof resourceRaw === 'string' ? { resource: resourceRaw } : {}),
105
+ ...(typeof authorityRaw === 'string' ? { authority: authorityRaw } : {}),
106
+ }
107
+ : { id: '', action: '' },
108
+ risk,
109
+ ...(needsKey || step.idempotencyKey ? { idempotencyKey: step.idempotencyKey ?? `${runRef}:${stepRef}` } : {}),
110
+ };
111
+ }
112
+ const randomRef = () => `run-${Math.random().toString(36).slice(2, 10)}${Date.now().toString(36)}`;
113
+ /** A stable digest is the sink's job (it has the hashing deps); here we record a cheap structural fingerprint
114
+ * so two receipts for the same input compare equal. Never treated as a cryptographic commitment. */
115
+ function fingerprint(v) {
116
+ try {
117
+ return `json:${JSON.stringify(v, (_k, x) => (typeof x === 'bigint' ? x.toString() : x))}`.slice(0, 2048);
118
+ }
119
+ catch {
120
+ return 'json:<unserializable>';
121
+ }
122
+ }
123
+ /** Does a declared branch hold against the results so far? Absent/empty is false for `exists`; `equals`
124
+ * compares by fingerprint (the same JSON is the same value). */
125
+ function holds(when, refs) {
126
+ const v = getPath(refs, when.ref);
127
+ if (when.equals !== undefined)
128
+ return fingerprint(v) === fingerprint(when.equals);
129
+ if (when.exists === false)
130
+ return v === undefined || v === null || (Array.isArray(v) && v.length === 0);
131
+ return !(v === undefined || v === null || (Array.isArray(v) && v.length === 0));
132
+ }
133
+ /** Every `name` a step's args `$ref`, by the first path segment. */
134
+ function refsUsed(args) {
135
+ const out = new Set();
136
+ const walk = (v) => {
137
+ if (!v || typeof v !== 'object')
138
+ return;
139
+ if (Array.isArray(v)) {
140
+ v.forEach(walk);
141
+ return;
142
+ }
143
+ const o = v;
144
+ if (typeof o.$ref === 'string')
145
+ out.add(o.$ref.split('.')[0]);
146
+ Object.values(o).forEach(walk);
147
+ };
148
+ walk(args);
149
+ return out;
150
+ }
151
+ /**
152
+ * The indices of the batch starting at `i`: the step and the consecutive steps after it that may run
153
+ * beside it (spec 370 P3). A step runs beside others only when its tool exercises no capability, it fans
154
+ * nothing out, no `after` edge points into the batch, none of its `$ref`s (or its `when`) name a result the
155
+ * batch produces, and it is not a replay (a replay is instant; keeping it alone keeps the order obvious).
156
+ */
157
+ function independentBatch(plan, i, toolsById, completed) {
158
+ const concurrent = (j) => {
159
+ const st = plan.steps[j];
160
+ const t = toolsById.get(st.toolId);
161
+ return !!t && !t.capability && !st.forEach && !completed.has(st.id ?? `s${j}`);
162
+ };
163
+ const batch = [i];
164
+ if (!concurrent(i))
165
+ return batch;
166
+ const first = plan.steps[i];
167
+ const produced = new Set(first.ref ? [first.ref] : []);
168
+ const ids = new Set([first.id ?? `s${i}`]);
169
+ for (let j = i + 1; j < plan.steps.length; j++) {
170
+ const st = plan.steps[j];
171
+ if (!concurrent(j))
172
+ break;
173
+ if (st.after?.some((id) => ids.has(id)))
174
+ break;
175
+ if ([...refsUsed(st.args)].some((r) => produced.has(r)))
176
+ break;
177
+ if (st.when && produced.has(st.when.ref.split('.')[0]))
178
+ break;
179
+ batch.push(j);
180
+ if (st.ref)
181
+ produced.add(st.ref);
182
+ ids.add(st.id ?? `s${j}`);
183
+ }
184
+ return batch;
185
+ }
49
186
  /**
50
187
  * Run an intent to a terminal result. Plans, executes the steps in order (threading `ref` results into later
51
188
  * args), observes, and re-plans (bounded) when a step throws. Returns `completed` with the last successful
52
- * step's result, or `failed` with the error. Fail-closed throughout: an unknown tool, an empty plan, no plan,
53
- * or an exhausted step budget all produce a `failed` RunResult (never a misleading empty success).
189
+ * step's result, `failed` with the error, `denied` when authority refused a step, or `suspended` when an
190
+ * approval is pending. Fail-closed throughout: an unknown tool, an empty plan, no plan, an exhausted step
191
+ * budget, a capability step with no verifier, or a denial all produce a non-completed RunResult — never a
192
+ * misleading empty success.
54
193
  */
55
194
  export async function runIntent(intent, opts) {
56
- const maxSteps = opts.maxSteps ?? 8;
195
+ // THE STEP BUDGET bounds what a PLANNER may keep proposing (a re-plan loop that never ends), not what a
196
+ // declared fan-out enumerates: that is capped by the ontology's binding (spec 358 W4 `maxItems`) at the
197
+ // point of expansion, and an expansion of N items widens the budget by N − 1 so "ask each of nine
198
+ // members" is not refused for being nine (spec 380).
199
+ let maxSteps = opts.maxSteps ?? 8;
57
200
  const maxReplans = opts.maxReplans ?? 1;
58
- const toolIds = new Set(opts.tools.map((t) => t.id));
201
+ const runRef = opts.runRef ?? randomRef();
202
+ const now = opts.now ?? (() => Math.floor(Date.now() / 1000));
203
+ const ports = opts.ports ?? {};
204
+ const presentedAll = opts.presented == null ? [] : Array.isArray(opts.presented) ? opts.presented : [opts.presented];
205
+ if (presentedAll.length > 1 && !opts.selectPresentation) {
206
+ throw new OrchestrationError('keyring_needs_selector', 'several mandates were presented and no selectPresentation was provided — the loop does not guess which authority a step spends');
207
+ }
208
+ const toolsById = new Map(opts.tools.map((t) => [t.id, t]));
209
+ const toolIds = new Set(toolsById.keys());
59
210
  const allObservations = [];
211
+ const receipts = [];
212
+ /** Executed steps whose tool declares a compensation, newest first — unwound on failure. */
213
+ const compensable = [];
60
214
  const refs = {};
61
215
  let executed = 0;
62
216
  let replans = 0;
63
217
  let lastResult;
218
+ // Spec 390 W3 — every event is stamped as it leaves, so a record can be read back as a timeline.
219
+ const sink = ports.events;
220
+ const emit = (e) => { sink?.({ ...e, at: Date.now() }); };
221
+ const record = async (r) => {
222
+ // The playbook shaped the whole run (it selected the tools + instructions at admission), so every
223
+ // step it produced cites the same skillRef. Stamped at the one chokepoint every receipt passes.
224
+ if (opts.skillRef && r.skillRef === undefined)
225
+ r.skillRef = opts.skillRef;
226
+ receipts.push(r);
227
+ emit({ type: 'ReceiptCreated', runRef, stepRef: r.stepRef, status: r.status });
228
+ if (ports.receiptSink)
229
+ await ports.receiptSink.record(r);
230
+ };
231
+ const base = (rs, startedAt) => ({
232
+ runRef, stepRef: rs.stepRef, index: rs.index, toolId: rs.tool.id, risk: rs.risk, startedAt,
233
+ ...(rs.risk !== 'informational' ? { capability: rs.capability } : {}),
234
+ ...(rs.idempotencyKey ? { idempotencyKey: rs.idempotencyKey } : {}),
235
+ inputDigest: fingerprint(rs.args),
236
+ // Spec 367 §5 — the binding the step was admitted under, pinned by the harness that knows the
237
+ // intent, the principal and where each argument came from. Recorded on every receipt of the step.
238
+ ...(() => { const b = opts.bindingFor?.(rs); return b ? { binding: b } : {}; })(),
239
+ });
240
+ /** The one mandate THIS step is judged under (spec 358 W4 keyring). Null = none fits this step, which
241
+ * the caller turns into authority-required for THIS step's args — never a denial borrowed from a
242
+ * mandate meant for a different item. The selector runs whenever it is provided AND anything is
243
+ * presented, INCLUDING a single mandate: a lone key that does not name this payee must ask for the
244
+ * right one, not be judged and denied under the wrong one. */
245
+ const presentedFor = (rs) => presentedAll.length === 0
246
+ ? null
247
+ : opts.selectPresentation
248
+ ? opts.selectPresentation(rs, presentedAll)
249
+ : presentedAll[0];
250
+ /** The authority path for one step. Returns the decision to execute under, or a terminal RunResult. */
251
+ async function authorize(rs, startedAt, plan) {
252
+ if (!ports.mandateVerifier)
253
+ throw new OrchestrationError('no_authority_port', `step ${rs.stepRef} exercises ${rs.capability.id} and no MandateVerifier is configured`);
254
+ // Spec 358 W4 — the keyring: with several mandates presented, the selector names the one THIS step is
255
+ // judged under. Selection is by declared fit (payee, resource); the verifier then judges that one
256
+ // alone. A step no key fits reports authority-required for ITS OWN args — never a denial borrowed
257
+ // from a mandate that was meant for a different item.
258
+ const presented = presentedFor(rs);
259
+ if (!presented) {
260
+ if (opts.onMissingMandate !== 'report')
261
+ throw new OrchestrationError('no_mandate_presented', `step ${rs.stepRef} exercises ${rs.capability.id} and the caller presented no mandate`);
262
+ // 401, not 403. Nothing was verified and nothing ran; the receipt records that the plan reached a
263
+ // step it had no authority for, and the caller is told WHICH step so it can go and get one.
264
+ emit({ type: 'RunSuspended', runRef, stepRef: rs.stepRef, resumeToken: rs.stepRef });
265
+ await record({ ...base(rs, startedAt), status: 'authority-required', completedAt: now() });
266
+ return {
267
+ outcome: 'authority-required', plan, steps: allObservations, receipts, runRef,
268
+ required: { stepRef: rs.stepRef, toolId: rs.tool.id, capability: rs.capability, risk: rs.risk, args: rs.args },
269
+ };
270
+ }
271
+ const req = { intent, presented, step: rs, afterApproval: false };
272
+ let decision = await ports.mandateVerifier.verify(req);
273
+ emit({ type: 'MandateChecked', runRef, stepRef: rs.stepRef, decision: decision.decision, afterApproval: false });
274
+ if (decision.decision === 'deny') {
275
+ emit({ type: 'MandateDenied', runRef, stepRef: rs.stepRef, reasons: decision.reasons });
276
+ await record({ ...base(rs, startedAt), status: 'denied', authority: { presentedRef: presented.ref, decision, afterApproval: false }, completedAt: now(), error: decision.reasons.map((r) => `${r.code}: ${r.message}`).join('; ') });
277
+ return { outcome: 'denied', plan, steps: allObservations, receipts, runRef, error: decision.reasons.map((r) => `${r.code}: ${r.message}`).join('; ') };
278
+ }
279
+ // Obligations: the verifier's, plus whatever policy adds for this risk class. Never fewer.
280
+ let obligations = [...decision.obligations];
281
+ if (ports.policyEvaluator) {
282
+ const extra = await ports.policyEvaluator.evaluate({ ...req, decision });
283
+ obligations = [...obligations, ...extra.obligations];
284
+ }
285
+ let approvalRecords = [];
286
+ if (obligations.length > 0) {
287
+ if (!ports.approvalPort)
288
+ throw new OrchestrationError('no_approval_port', `step ${rs.stepRef} carries ${obligations.length} obligation(s) and no ApprovalPort is configured`);
289
+ emit({ type: 'ApprovalRequested', runRef, stepRef: rs.stepRef, obligations });
290
+ const outcome = await ports.approvalPort.request({ runRef, stepRef: rs.stepRef, intent, step: rs, obligations, evidence: decision.evidence });
291
+ if (outcome.status === 'pending') {
292
+ emit({ type: 'RunSuspended', runRef, stepRef: rs.stepRef, resumeToken: outcome.resumeToken });
293
+ const prompt = outcome.prompt ? { ...outcome.prompt, stepRef: rs.stepRef, toolId: rs.tool.id } : undefined;
294
+ await record({
295
+ ...base(rs, startedAt), status: 'suspended',
296
+ authority: { presentedRef: presented.ref, decision, afterApproval: false },
297
+ ...(prompt ? { pendingInput: receiptPending(prompt) } : {}),
298
+ completedAt: now(),
299
+ });
300
+ return { outcome: 'suspended', plan, steps: allObservations, receipts, runRef, resumeToken: outcome.resumeToken, ...(prompt ? { prompt } : {}) };
301
+ }
302
+ if (outcome.status === 'refused') {
303
+ emit({ type: 'ApprovalRefused', runRef, stepRef: rs.stepRef, ...(outcome.reason ? { reason: outcome.reason } : {}) });
304
+ const error = `approval refused${outcome.by ? ` by ${outcome.by}` : ''}${outcome.reason ? `: ${outcome.reason}` : ''}`;
305
+ await record({ ...base(rs, startedAt), status: 'denied', authority: { presentedRef: presented.ref, decision, afterApproval: false }, completedAt: now(), error });
306
+ return { outcome: 'denied', plan, steps: allObservations, receipts, runRef, error };
307
+ }
308
+ approvalRecords = outcome.records;
309
+ emit({ type: 'ApprovalDischarged', runRef, stepRef: rs.stepRef, records: approvalRecords });
310
+ // RE-VERIFY. An approval is an input to the verifier, not a bypass of it: the mandate may have been
311
+ // revoked while the approver was deciding.
312
+ decision = await ports.mandateVerifier.verify({ ...req, afterApproval: true });
313
+ emit({ type: 'MandateChecked', runRef, stepRef: rs.stepRef, decision: decision.decision, afterApproval: true });
314
+ if (decision.decision !== 'allow') {
315
+ const reasons = decision.decision === 'deny' ? decision.reasons : [{ code: 'still-obligated', message: 'obligations remain after approval' }];
316
+ emit({ type: 'MandateDenied', runRef, stepRef: rs.stepRef, reasons });
317
+ const error = reasons.map((r) => `${r.code}: ${r.message}`).join('; ');
318
+ await record({ ...base(rs, startedAt), status: 'denied', authority: { presentedRef: presented.ref, decision, afterApproval: true }, approvalRecords, completedAt: now(), error });
319
+ return { outcome: 'denied', plan, steps: allObservations, receipts, runRef, error };
320
+ }
321
+ }
322
+ return { decision, approvalRecords, used: presented };
323
+ }
324
+ /** Unwind executed steps that declared compensation, newest first. Best effort: a compensation that
325
+ * fails is recorded, not retried — the receipt is the honest record. Compensations are AUTHORIZED
326
+ * like any other capability step; a denied compensation is recorded as such. */
327
+ async function compensate() {
328
+ for (const { resolved, result } of compensable.reverse()) {
329
+ const comp = resolved.tool.compensation;
330
+ const compTool = toolsById.get(comp.toolId);
331
+ const startedAt = now();
332
+ const args = resolveValue(comp.args, { ...refs, $result: result });
333
+ const crs = compTool
334
+ ? resolveStep(runRef, resolved.index, { toolId: comp.toolId, args, id: `${resolved.stepRef}:compensate` }, compTool, args)
335
+ : { ...resolved, stepRef: `${resolved.stepRef}:compensate`, tool: { id: comp.toolId, description: '' }, args, risk: 'informational', capability: { id: '', action: '' } };
336
+ let ok = false;
337
+ let error;
338
+ try {
339
+ const compPresented = presentedFor(crs);
340
+ if (crs.risk !== 'informational' && ports.mandateVerifier && compPresented) {
341
+ const d = await ports.mandateVerifier.verify({ intent, presented: compPresented, step: crs, afterApproval: false });
342
+ if (d.decision !== 'allow') {
343
+ error = `compensation not authorized: ${d.decision}`;
344
+ }
345
+ }
346
+ if (!error) {
347
+ await opts.invoke(comp.toolId, args, { intent, step: crs.step, index: crs.index, ...(crs.idempotencyKey ? { idempotencyKey: crs.idempotencyKey } : {}) });
348
+ ok = true;
349
+ }
350
+ }
351
+ catch (e) {
352
+ error = e instanceof Error ? e.message : String(e);
353
+ }
354
+ emit({ type: 'StepCompensated', runRef, stepRef: resolved.stepRef, by: comp.toolId, ok });
355
+ await record({ ...base(crs, startedAt), status: ok ? 'compensated' : 'failed', completedAt: now(), ...(error ? { error } : {}) });
356
+ }
357
+ compensable.length = 0;
358
+ }
359
+ emit({ type: 'RunStarted', runRef, intent, presentedRef: presentedAll[0]?.ref ?? null });
360
+ let plan = { steps: [] };
361
+ const completedByRef = new Map((opts.resume?.completed ?? []).map((c) => [c.stepRef, c]));
64
362
  try {
65
- let plan = await callPlanner(opts.planner, { intent, tools: opts.tools });
363
+ plan = opts.resume ? { ...opts.resume.plan, steps: [...opts.resume.plan.steps] } : await callPlanner(opts.planner, { intent, tools: opts.tools });
66
364
  assertKnownTools(plan, toolIds);
67
- // The plan loop: walk the current plan; on a step failure, re-plan (bounded) and restart with a fresh plan.
365
+ // ── PLAN ADMISSION (spec 367 W1) — is this the plan the sentence asked for? Deterministic, reads the
366
+ // tools' declarations; refused ⇒ ONE re-plan told exactly what was wrong; refused again ⇒ denied, with
367
+ // the violations as the answer. Nothing has run at this point, so a denial here costs nobody anything
368
+ // but a wrong act they did not get.
369
+ if (ports.planAdmission) {
370
+ let verdict = await ports.planAdmission.admit({ intent, plan, tools: opts.tools });
371
+ // A PLACEHOLDER IS AN UNANSWERED QUESTION, NOT A REFUSAL. A violation whose recovery is `ask` names
372
+ // an argument the planner could not fill ("<UNKNOWN>" for the amount); dropping that argument turns
373
+ // it into one the step declares and lacks — which §3.5 then ASKS the person for. Refusing instead,
374
+ // twice, put the placeholder itself into the refusal a person read ("send money to bob" → a wall of
375
+ // <UNKNOWN>), when "how much?" was the whole answer.
376
+ if (!verdict.admitted && verdict.violations.every((v) => v.recovery === 'ask' && v.stepIndex !== undefined && v.field)) {
377
+ const asked = verdict.violations.map((v) => `${v.stepIndex}:${v.field}`);
378
+ plan = { ...plan, steps: plan.steps.map((st, i) => {
379
+ const drop = verdict.admitted ? [] : verdict.violations.filter((v) => v.stepIndex === i).map((v) => v.field);
380
+ if (!drop.length)
381
+ return st;
382
+ const args = { ...st.args };
383
+ for (const k of drop)
384
+ delete args[k];
385
+ return { ...st, args };
386
+ }) };
387
+ emit({ type: 'PlanRefused', runRef, violations: verdict.violations, replanning: false });
388
+ verdict = await ports.planAdmission.admit({ intent, plan, tools: opts.tools });
389
+ if (verdict.admitted)
390
+ emit({ type: 'PlanCreated', runRef, steps: plan.steps.length, rationale: `placeholders dropped to be asked for: ${asked.join(', ')}` });
391
+ }
392
+ // A REFUSAL IS TERMINAL (spec 379). A violation whose recovery is `refuse` names something no re-plan
393
+ // may cure by leaving it out: a value-moving step aimed at an outside agent, re-planned without the
394
+ // executor, would be this harness quietly doing what the person asked another to do. Denied as asked.
395
+ if (!verdict.admitted && verdict.violations.some((v) => v.recovery === 'refuse')) {
396
+ emit({ type: 'PlanRefused', runRef, violations: verdict.violations, replanning: false });
397
+ const error = `plan_refused: ${verdict.violations.map((v) => v.message).join(' | ')}`;
398
+ return { outcome: 'denied', plan, steps: allObservations, receipts, runRef, error };
399
+ }
400
+ if (!verdict.admitted) {
401
+ emit({ type: 'PlanRefused', runRef, violations: verdict.violations, replanning: true });
402
+ const told = { ...intent, context: { ...(intent.context ?? {}), admission: verdict.violations.map((v) => v.message) } };
403
+ plan = await callPlanner(opts.planner, { intent: told, tools: opts.tools });
404
+ assertKnownTools(plan, toolIds);
405
+ verdict = await ports.planAdmission.admit({ intent, plan, tools: opts.tools });
406
+ if (!verdict.admitted) {
407
+ emit({ type: 'PlanRefused', runRef, violations: verdict.violations, replanning: false });
408
+ const error = `plan_refused: ${verdict.violations.map((v) => v.message).join(' | ')}`;
409
+ return { outcome: 'denied', plan, steps: allObservations, receipts, runRef, error };
410
+ }
411
+ }
412
+ }
413
+ emit({ type: 'PlanCreated', runRef, steps: plan.steps.length, ...(plan.rationale ? { rationale: plan.rationale } : {}) });
414
+ const attempt = async (i, step) => {
415
+ const tool = toolsById.get(step.toolId);
416
+ // ── ALREADY RAN (spec 370 P1) — replayed as evidence, never as permission. ────────────────
417
+ // A resume used to re-execute every completed step: a planner call, every read again, and a
418
+ // correctness that rested on each invoker noticing its own earlier act. The recorded outcome
419
+ // stands in for it here; the invoker and the verifier are not called because nothing is being
420
+ // attempted. The steps that follow are judged as if for the first time.
421
+ const done = completedByRef.get(step.id ?? `s${i}`);
422
+ if (done) {
423
+ const stepRef = step.id ?? `s${i}`;
424
+ const obs = { step, ok: true, result: done.result, stepRef, replayed: true };
425
+ if (step.ref)
426
+ refs[step.ref] = done.result;
427
+ if (done.receipt)
428
+ receipts.push(done.receipt);
429
+ emit({ type: 'StepReplayed', runRef, stepRef, toolId: step.toolId });
430
+ return { kind: 'done', obs };
431
+ }
432
+ // ── A DECLARED BRANCH (spec 370 P3) — taken or not by a prior result, never by a second plan. ──
433
+ if (step.when && !holds(step.when, refs)) {
434
+ const stepRef = step.id ?? `s${i}`;
435
+ const rs = resolveStep(runRef, i, step, tool, resolveArgs(step.args, refs));
436
+ const because = `${step.when.ref} ${step.when.equals !== undefined ? `≠ ${fingerprint(step.when.equals)}` : 'is absent'}`;
437
+ emit({ type: 'StepSkipped', runRef, stepRef, toolId: tool.id, because });
438
+ await record({ ...base(rs, now()), status: 'skipped', completedAt: now(), error: `not taken: ${because}` });
439
+ return { kind: 'done', obs: { step, ok: true, stepRef, skipped: true } };
440
+ }
441
+ let args = resolveArgs(step.args, refs);
442
+ // ── ANSWERS THE PERSON ALREADY GAVE ARE PART OF THIS STEP'S ARGUMENTS ──────────────────────
443
+ // A `data` question raised while NORMALISING (§3.5) — "which Nathan do you mean?" — is answered
444
+ // against the step, not against a tool that has not run yet. Without this the answer travelled in
445
+ // `ctx.supplied`, which only an invoker ever reads, so normalisation re-ran on the planner's
446
+ // original words and asked the identical question forever. Every disambiguation was unanswerable.
447
+ //
448
+ // Only names the TOOL declares are accepted: `supplied` arrives from a client, and a question we
449
+ // asked is not a licence to set arguments we did not ask about.
450
+ const declaredArgs = tool.inputSchema?.properties;
451
+ for (const answer of inputsFor(opts.supplied, step.id ?? `s${i}`)) {
452
+ for (const [name, value] of Object.entries(answer.data ?? {})) {
453
+ if (value === undefined || value === '')
454
+ continue;
455
+ if (declaredArgs && !(name in declaredArgs))
456
+ continue;
457
+ args = { ...args, [name]: value };
458
+ }
459
+ }
460
+ const startedAt = now();
461
+ if (opts.normalizeArgs) {
462
+ // Normalisation may not be able to finish alone: "send it to alice" names a person the substrate
463
+ // has to identify, and there may be several Alices or none. That is a QUESTION, not a failure —
464
+ // the same suspension a tool raises, from the one place that turns words into canonical values.
465
+ // Guessing a counterparty would be the worst possible way to be helpful.
466
+ try {
467
+ args = await opts.normalizeArgs({ toolId: step.toolId, tool, args });
468
+ if (opts.resolveExecutor && typeof step.executor === 'string' && step.executor.trim()) {
469
+ const executor = await opts.resolveExecutor({ step, tool });
470
+ const { executor: _named, ...rest } = step;
471
+ step = executor ? { ...rest, executor } : rest;
472
+ }
473
+ }
474
+ catch (e) {
475
+ if (!isInputRequired(e))
476
+ throw e;
477
+ const pending = resolveStep(runRef, i, step, tool, args);
478
+ const request = { ...e.request, stepRef: pending.stepRef, toolId: tool.id };
479
+ emit({ type: 'RunSuspended', runRef, stepRef: pending.stepRef, resumeToken: pending.stepRef });
480
+ await record({ ...base(pending, startedAt), status: 'suspended', pendingInput: receiptPending(request), completedAt: now() });
481
+ return { kind: 'exit', result: { outcome: 'suspended', plan, steps: allObservations, receipts, runRef, resumeToken: pending.stepRef, prompt: request }, compensate: false };
482
+ }
483
+ }
484
+ const rs = resolveStep(runRef, i, step, tool, args);
485
+ emit({ type: 'StepProposed', runRef, stepRef: rs.stepRef, toolId: tool.id, risk: rs.risk });
486
+ // ── authority, for every step that exercises a capability ──
487
+ let authority;
488
+ let approvalRecords = [];
489
+ // Spec 374 §1 — THE ASK IS ROUTED; THE MANDATE IS NOT. A step whose subject is another agent is
490
+ // sent there (spec 366 R1), and THAT agent judges its authority under its own playbook, asks its own
491
+ // steward, and answers. Judging it here would ask the asker for a mandate the subject never
492
+ // delegated to them — which is what happened when this branch did not exist: a member was asked
493
+ // for the organization's mandate before the step ever left. Recorded as routed, never as allowed:
494
+ // this run holds only what the subject answers, and its receipt says so.
495
+ const judgedAt = rs.risk !== 'informational' && opts.authorityJudgedElsewhere ? opts.authorityJudgedElsewhere(rs) : null;
496
+ if (judgedAt) {
497
+ authority = {
498
+ presentedRef: 'routed',
499
+ decision: {
500
+ decision: 'allow', obligations: [],
501
+ evidence: { mandateRef: `routed:${judgedAt}`, intentDigest: fingerprint(intent), evaluatedAt: now(), verdicts: [{ enforcer: 'routed', allowed: true, reason: `the step's subject is ${judgedAt}; its authority is judged at that agent, under its own playbook and its own steward — this run holds only what it answers` }] },
502
+ },
503
+ afterApproval: false,
504
+ };
505
+ }
506
+ else if (rs.risk !== 'informational' && tool.selfAuthorized) {
507
+ // SELF-ACTING (see `ToolSpec.selfAuthorized`): the actor, the owner and the beneficiary are one
508
+ // principal, so the session is the authority and there is no second party to ask. It is still a
509
+ // WRITE and still gets a receipt — recorded as authorized by `self`, so a reader can tell an act
510
+ // backed by a session from one backed by a signature without inferring it from a missing field.
511
+ authority = {
512
+ // `self`, not null: null is what an informational step records, and this one WROTE.
513
+ presentedRef: 'self',
514
+ decision: {
515
+ decision: 'allow', obligations: [],
516
+ // The evidence names the basis honestly — there is no mandate to reference, and inventing a
517
+ // mandateRef would make a receipt claim a signature that never happened.
518
+ evidence: { mandateRef: 'self', intentDigest: fingerprint(intent), evaluatedAt: now(), verdicts: [{ enforcer: 'self', allowed: true, reason: 'the run\'s own principal owns what this touches; the session is the authority' }] },
519
+ },
520
+ afterApproval: false,
521
+ };
522
+ }
523
+ else if (rs.risk !== 'informational') {
524
+ const a = await authorize(rs, startedAt, plan);
525
+ if ('outcome' in a)
526
+ return { kind: 'exit', result: a, compensate: true };
527
+ authority = { presentedRef: a.used.ref, decision: a.decision, afterApproval: a.approvalRecords.length > 0 };
528
+ approvalRecords = a.approvalRecords;
529
+ }
530
+ // ── execute ──
531
+ const suppliedHere = inputsFor(opts.supplied, rs.stepRef);
532
+ const ctx = { intent, step, index: i, ...(rs.idempotencyKey ? { idempotencyKey: rs.idempotencyKey } : {}), ...(suppliedHere.length ? { supplied: suppliedHere } : {}) };
533
+ executed++;
534
+ let obs;
535
+ try {
536
+ const result = await opts.invoke(step.toolId, args, ctx);
537
+ obs = { step, ok: true, result, stepRef: rs.stepRef };
538
+ if (step.ref)
539
+ refs[step.ref] = result;
540
+ lastResult = result;
541
+ if (tool.compensation && rs.risk !== 'informational')
542
+ compensable.push({ resolved: rs, result });
543
+ }
544
+ catch (e) {
545
+ if (isInputRequired(e)) {
546
+ // The tool asked the person for something (spec 350 §3.4). Not a failure — nothing is re-planned
547
+ // around a question — and not a denial: authority was verified and stands. The run suspends with
548
+ // the prompt; the resume re-runs the intent with the answers, through every gate again. Steps
549
+ // already executed are NOT compensated: they stand, and the resume re-invokes them idempotently.
550
+ const request = { ...e.request, stepRef: rs.stepRef, toolId: tool.id };
551
+ emit({ type: 'RunSuspended', runRef, stepRef: rs.stepRef, resumeToken: rs.stepRef });
552
+ await record({
553
+ ...base(rs, startedAt),
554
+ status: 'suspended',
555
+ ...(authority ? { authority } : {}),
556
+ ...(approvalRecords.length ? { approvalRecords } : {}),
557
+ pendingInput: receiptPending(request),
558
+ completedAt: now(),
559
+ });
560
+ return { kind: 'exit', result: { outcome: 'suspended', plan, steps: allObservations, receipts, runRef, resumeToken: rs.stepRef, prompt: request }, compensate: false };
561
+ }
562
+ obs = { step, ok: false, error: e instanceof Error ? e.message : String(e), stepRef: rs.stepRef };
563
+ }
564
+ emit({ type: 'ToolInvoked', runRef, stepRef: rs.stepRef, toolId: tool.id, ok: obs.ok });
565
+ const decisions = opts.decisionsFor?.(tool.id, args) ?? [];
566
+ const stepReceipt = {
567
+ ...base(rs, startedAt),
568
+ status: obs.ok ? 'executed' : 'failed',
569
+ // What was decided FOR the person on the way here, and on what basis (spec 363 W6).
570
+ ...(decisions.length ? { decisions: [...decisions] } : {}),
571
+ ...(authority ? { authority } : {}),
572
+ ...(approvalRecords.length ? { approvalRecords } : {}),
573
+ ...(obs.ok ? { outputDigest: fingerprint(obs.result) } : { error: obs.error }),
574
+ completedAt: now(),
575
+ };
576
+ await record(stepReceipt);
577
+ // ── DECLARED EFFECTS — spec 360. What the playbook promised FOLLOWS this act.
578
+ //
579
+ // Only on success: you do not tell someone about a payment that did not happen, and an effect is
580
+ // never a way to reach a party before authority exists.
581
+ //
582
+ // ISOLATED, ALWAYS. The step already happened, possibly on chain. A receipt that could un-do a
583
+ // payment would be worse than no receipt — so a throw here is caught and emitted as its own fact.
584
+ // The step stays `executed`; failing to disclose and failing to pay are different failures and a
585
+ // caller that cannot tell them apart will report a transfer as lost that actually settled.
586
+ if (obs.ok && ports.effectSink && opts.declaredEffects) {
587
+ // `resolveStep` gives a tool with no capability `{ id: '', action: '' }` rather than undefined,
588
+ // so this is `||` and not `??`: an informational step's effects are keyed by its TOOL id.
589
+ const capabilityId = rs.capability.id || tool.id;
590
+ try {
591
+ // Resolving is part of the effect path, so a resolver that throws is the same kind of event
592
+ // as a discharge that throws: reported, never fatal to an act that already happened.
593
+ const declared = typeof opts.declaredEffects === 'function'
594
+ ? await opts.declaredEffects(capabilityId, rs)
595
+ : (opts.declaredEffects[capabilityId] ?? []);
596
+ const effectOutcomes = [];
597
+ for (const effect of declared ?? []) {
598
+ const produces = String(effect.produces ?? '');
599
+ try {
600
+ await ports.effectSink.discharge({ runRef, stepRef: rs.stepRef, effect, step: rs, result: obs.result, receipt: stepReceipt });
601
+ effectOutcomes.push({ produces, ok: true });
602
+ }
603
+ catch (e) {
604
+ const error = e instanceof Error ? e.message : String(e);
605
+ effectOutcomes.push({ produces, ok: false, error });
606
+ emit({ type: 'EffectFailed', runRef, stepRef: rs.stepRef, error });
607
+ }
608
+ }
609
+ // ON THE RECEIPT, not only in the event stream: "the payment stood but the payee was not
610
+ // told" is evidence a caller must be able to SEE (memory: evidence before diagnosis) — an
611
+ // invisible EffectFailed left every silent-delivery bug looking like success.
612
+ if (effectOutcomes.length)
613
+ stepReceipt.effects = effectOutcomes;
614
+ }
615
+ catch (e) {
616
+ emit({ type: 'EffectFailed', runRef, stepRef: rs.stepRef, error: `could not resolve declared effects: ${e instanceof Error ? e.message : String(e)}` });
617
+ }
618
+ }
619
+ return { kind: 'done', obs };
620
+ };
68
621
  for (;;) {
69
622
  let failedMidPlan = false;
70
- for (let i = 0; i < plan.steps.length; i++) {
623
+ for (let i = 0; i < plan.steps.length;) {
71
624
  if (executed >= maxSteps)
72
625
  throw new OrchestrationError('max_steps', `step budget of ${maxSteps} exhausted`);
73
- const step = plan.steps[i];
74
- const ctx = { intent, step, index: i };
75
- const args = resolveArgs(step.args, refs);
76
- executed++;
77
- let obs;
78
- try {
79
- const result = await opts.invoke(step.toolId, args, ctx);
80
- obs = { step, ok: true, result };
81
- if (step.ref)
82
- refs[step.ref] = result;
83
- lastResult = result;
626
+ let step = plan.steps[i];
627
+ // ── FAN-OUT — spec 358 W4. One planned step over an enumerated set becomes N ordinary steps,
628
+ // spliced in place, each with its own id, its own receipt, its own idempotency key, and its own
629
+ // pass through the verifier below: a mandate per item, never one verdict stretched over N.
630
+ //
631
+ // Fail-closed three ways, each named: the PRODUCING tool must declare which relation its result
632
+ // enumerates (an array being array-shaped says nothing — a search page is not a payee list); the
633
+ // relation must be bound fan-out-able by the injected ontology policy; and the item count must
634
+ // fit the binding's cap, because "every member" of a 25-person org is a plan and of a 10,000-row
635
+ // result it is an incident.
636
+ if (step.forEach) {
637
+ const [refName, ...path] = step.forEach.ref.split('.');
638
+ const producer = plan.steps.find((p) => p.ref === refName);
639
+ const producerTool = producer ? toolsById.get(producer.toolId) : undefined;
640
+ const relation = producerTool?.enumerates?.relation;
641
+ if (!relation) {
642
+ throw new OrchestrationError('fan_out_unbound', `forEach over "${step.forEach.ref}": the producing tool ${producerTool?.id ?? '(unknown)'} does not declare what its result enumerates`);
643
+ }
644
+ const binding = opts.fanOut?.(relation) ?? null;
645
+ if (!binding) {
646
+ throw new OrchestrationError('fan_out_unbound', `forEach over relation <${relation}> is not bound fan-out-able — the ontology's plan-shapes binding decides, and absence fails closed`);
647
+ }
648
+ let items = refs[refName];
649
+ // A PRODUCER THAT WAS REFUSED has no set to fan out over, and the reason is the producer's refusal,
650
+ // not the shape of what it returned: "Missio Nexus refused: no standing" is the answer a stranger
651
+ // gets; "resolved to nothing, not an array" was what they got before this line (spec 380).
652
+ const producerRefusal = items && typeof items === 'object' && typeof items.refused === 'string' ? items.refused : null;
653
+ if (producerRefusal)
654
+ throw new OrchestrationError('fan_out_refused', `forEach over "${step.forEach.ref}": the step that enumerates it was refused — ${producerRefusal}`);
655
+ for (const seg of path)
656
+ items = items?.[seg];
657
+ if (!Array.isArray(items)) {
658
+ throw new OrchestrationError('fan_out_not_array', `forEach ref "${step.forEach.ref}" resolved to ${items === undefined ? 'nothing' : typeof items}, not an array`);
659
+ }
660
+ if (items.length > binding.maxItems) {
661
+ throw new OrchestrationError('fan_out_over_limit', `forEach over <${relation}> names ${items.length} items; the binding allows ${binding.maxItems}`);
662
+ }
663
+ const baseId = step.id ?? `s${i}`;
664
+ const expanded = items.map((item, k) => ({
665
+ toolId: step.toolId,
666
+ args: substituteItem(step.args, item),
667
+ id: `${baseId}#${k + 1}`,
668
+ }));
669
+ emit({ type: 'PlanCreated', runRef, steps: expanded.length, rationale: `fan-out of ${baseId} over <${relation}> into ${expanded.length} steps` });
670
+ maxSteps += Math.max(0, expanded.length - 1);
671
+ plan = { ...plan, steps: [...plan.steps.slice(0, i), ...expanded, ...plan.steps.slice(i + 1)] };
672
+ if (expanded.length === 0)
673
+ continue; // an empty set fans out to nothing, which is a fine answer (the step is gone; `i` now names the next)
674
+ step = plan.steps[i];
84
675
  }
85
- catch (e) {
86
- obs = { step, ok: false, error: e instanceof Error ? e.message : String(e) };
676
+ // ── THE BATCH (spec 370 P3): this step and the consecutive INDEPENDENT read-only steps after it. ──
677
+ // Independent = no `after` edge into the batch, no `$ref` into a result the batch produces, no branch
678
+ // on one. Read-only = the tool exercises no capability: a step that spends authority runs alone,
679
+ // both because one verdict is one step's and because two userOps from one account race on its
680
+ // nonce. The DO is single-threaded and the steps are I/O-bound, so this is real wall-clock, safely.
681
+ const batch = independentBatch(plan, i, toolsById, completedByRef);
682
+ if (executed + batch.length > maxSteps)
683
+ throw new OrchestrationError('max_steps', `step budget of ${maxSteps} exhausted`);
684
+ const outcomes = batch.length === 1
685
+ ? [await attempt(i, step)]
686
+ : await Promise.all(batch.map((j) => attempt(j, plan.steps[j])));
687
+ // Receipts land in completion order inside a batch; the record is read by index.
688
+ if (batch.length > 1)
689
+ receipts.sort((a, b) => a.index - b.index || (a.stepRef.endsWith(':compensate') ? 1 : 0));
690
+ // What completed is recorded first, in plan order — a checkpoint taken now carries it — then the
691
+ // earliest exit (a question, a denial, a missing mandate) is the run's answer.
692
+ let exit;
693
+ for (const o of outcomes) {
694
+ if (o.kind === 'done') {
695
+ allObservations.push(o.obs);
696
+ opts.onObserve?.(o.obs);
697
+ if (o.obs.ok && !o.obs.skipped)
698
+ lastResult = o.obs.result;
699
+ if (!o.obs.ok)
700
+ failedMidPlan = true;
701
+ }
702
+ else if (!exit)
703
+ exit = o;
87
704
  }
88
- allObservations.push(obs);
89
- opts.onObserve?.(obs);
90
- if (!obs.ok) {
91
- failedMidPlan = true;
92
- break; // stop this plan; decide whether to re-plan below
705
+ if (exit) {
706
+ if (exit.compensate)
707
+ await compensate();
708
+ return exit.result;
93
709
  }
710
+ if (failedMidPlan)
711
+ break; // stop this plan; decide whether to re-plan below
712
+ i += batch.length;
94
713
  }
95
714
  if (!failedMidPlan) {
96
- return { outcome: 'completed', plan, steps: allObservations, result: lastResult };
715
+ emit({ type: 'RunCompleted', runRef });
716
+ return { outcome: 'completed', plan, steps: allObservations, receipts, runRef, result: lastResult };
97
717
  }
98
718
  if (replans >= maxReplans) {
99
719
  const last = allObservations[allObservations.length - 1];
100
- return { outcome: 'failed', plan, steps: allObservations, error: last?.error ?? 'step failed' };
720
+ await compensate();
721
+ const error = last?.error ?? 'step failed';
722
+ emit({ type: 'RunFailed', runRef, error });
723
+ return { outcome: 'failed', plan, steps: allObservations, receipts, runRef, error };
101
724
  }
102
725
  replans++;
103
- plan = await callPlanner(opts.planner, { intent, tools: opts.tools, observations: allObservations });
726
+ // Spec 391 W2 — the planner sees what each prior step WAS and how big, not a 40 KB body in its prompt.
727
+ plan = await callPlanner(opts.planner, { intent, tools: opts.tools, observations: compactObservations(allObservations) });
104
728
  assertKnownTools(plan, toolIds);
729
+ emit({ type: 'PlanCreated', runRef, steps: plan.steps.length, ...(plan.rationale ? { rationale: plan.rationale } : {}) });
105
730
  }
106
731
  }
107
732
  catch (e) {
108
733
  const error = e instanceof OrchestrationError ? `${e.code}: ${e.message}` : e instanceof Error ? e.message : String(e);
109
- // No plan was ever produced if allObservations is empty + we threw before the loop.
110
- return { outcome: 'failed', plan: { steps: [] }, steps: allObservations, error };
734
+ await compensate();
735
+ emit({ type: 'RunFailed', runRef, error });
736
+ return { outcome: 'failed', plan, steps: allObservations, receipts, runRef, error };
111
737
  }
112
738
  }
113
739
  //# sourceMappingURL=loop.js.map