@buildanagent/agent-safety 0.0.0-bootstrap.0 → 0.1.0-alpha.28

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 (138) hide show
  1. package/LICENSE +54 -0
  2. package/LICENSE-APACHE +202 -0
  3. package/LICENSE-MIT +21 -0
  4. package/README.md +515 -0
  5. package/dist/agents/index.d.ts +5 -0
  6. package/dist/agents/index.js +6 -0
  7. package/dist/agents/index.js.map +1 -0
  8. package/dist/ai/index.d.ts +10 -0
  9. package/dist/ai/index.js +11 -0
  10. package/dist/ai/index.js.map +1 -0
  11. package/dist/ai/interrupted-write.d.ts +28 -0
  12. package/dist/ai/interrupted-write.js +52 -0
  13. package/dist/ai/interrupted-write.js.map +1 -0
  14. package/dist/ai/settle-denied.d.ts +17 -0
  15. package/dist/ai/settle-denied.js +25 -0
  16. package/dist/ai/settle-denied.js.map +1 -0
  17. package/dist/ai/tool-approval.d.ts +68 -0
  18. package/dist/ai/tool-approval.js +219 -0
  19. package/dist/ai/tool-approval.js.map +1 -0
  20. package/dist/ai/tool-result.d.ts +23 -0
  21. package/dist/ai/tool-result.js +20 -0
  22. package/dist/ai/tool-result.js.map +1 -0
  23. package/dist/byok/default-provider.d.ts +12 -0
  24. package/dist/byok/default-provider.js +72 -0
  25. package/dist/byok/default-provider.js.map +1 -0
  26. package/dist/byok/explicit-provider.d.ts +39 -0
  27. package/dist/byok/explicit-provider.js +80 -0
  28. package/dist/byok/explicit-provider.js.map +1 -0
  29. package/dist/byok/index.d.ts +8 -0
  30. package/dist/byok/index.js +9 -0
  31. package/dist/byok/index.js.map +1 -0
  32. package/dist/bytes.d.ts +17 -0
  33. package/dist/bytes.js +59 -0
  34. package/dist/bytes.js.map +1 -0
  35. package/dist/cost/ai-types.d.ts +26 -0
  36. package/dist/cost/ai-types.js +2 -0
  37. package/dist/cost/ai-types.js.map +1 -0
  38. package/dist/cost/budget-exceeded.d.ts +39 -0
  39. package/dist/cost/budget-exceeded.js +49 -0
  40. package/dist/cost/budget-exceeded.js.map +1 -0
  41. package/dist/cost/cost-guard.d.ts +63 -0
  42. package/dist/cost/cost-guard.js +278 -0
  43. package/dist/cost/cost-guard.js.map +1 -0
  44. package/dist/cost/estimate.d.ts +76 -0
  45. package/dist/cost/estimate.js +320 -0
  46. package/dist/cost/estimate.js.map +1 -0
  47. package/dist/cost/guarded-provider.d.ts +24 -0
  48. package/dist/cost/guarded-provider.js +19 -0
  49. package/dist/cost/guarded-provider.js.map +1 -0
  50. package/dist/cost/index.d.ts +12 -0
  51. package/dist/cost/index.js +12 -0
  52. package/dist/cost/index.js.map +1 -0
  53. package/dist/cost/spend.d.ts +13 -0
  54. package/dist/cost/spend.js +15 -0
  55. package/dist/cost/spend.js.map +1 -0
  56. package/dist/effect-key.d.ts +31 -0
  57. package/dist/effect-key.js +61 -0
  58. package/dist/effect-key.js.map +1 -0
  59. package/dist/effect-store-conformance.d.ts +24 -0
  60. package/dist/effect-store-conformance.js +140 -0
  61. package/dist/effect-store-conformance.js.map +1 -0
  62. package/dist/effect-store.d.ts +71 -0
  63. package/dist/effect-store.js +38 -0
  64. package/dist/effect-store.js.map +1 -0
  65. package/dist/egress.d.ts +74 -0
  66. package/dist/egress.js +174 -0
  67. package/dist/egress.js.map +1 -0
  68. package/dist/errors.d.ts +32 -0
  69. package/dist/errors.js +26 -0
  70. package/dist/errors.js.map +1 -0
  71. package/dist/guarded-write.d.ts +99 -0
  72. package/dist/guarded-write.js +245 -0
  73. package/dist/guarded-write.js.map +1 -0
  74. package/dist/hash.d.ts +24 -0
  75. package/dist/hash.js +121 -0
  76. package/dist/hash.js.map +1 -0
  77. package/dist/index.d.ts +27 -0
  78. package/dist/index.js +28 -0
  79. package/dist/index.js.map +1 -0
  80. package/dist/key-store.d.ts +37 -0
  81. package/dist/key-store.js +53 -0
  82. package/dist/key-store.js.map +1 -0
  83. package/dist/model-routes.d.ts +54 -0
  84. package/dist/model-routes.js +117 -0
  85. package/dist/model-routes.js.map +1 -0
  86. package/dist/model-url.d.ts +39 -0
  87. package/dist/model-url.js +79 -0
  88. package/dist/model-url.js.map +1 -0
  89. package/dist/outcome.d.ts +88 -0
  90. package/dist/outcome.js +140 -0
  91. package/dist/outcome.js.map +1 -0
  92. package/dist/pending-store.d.ts +45 -0
  93. package/dist/pending-store.js +36 -0
  94. package/dist/pending-store.js.map +1 -0
  95. package/dist/pending.d.ts +144 -0
  96. package/dist/pending.js +161 -0
  97. package/dist/pending.js.map +1 -0
  98. package/dist/plan-approval.d.ts +196 -0
  99. package/dist/plan-approval.js +357 -0
  100. package/dist/plan-approval.js.map +1 -0
  101. package/dist/plan-card.d.ts +34 -0
  102. package/dist/plan-card.js +56 -0
  103. package/dist/plan-card.js.map +1 -0
  104. package/dist/plan-ledger-conformance.d.ts +24 -0
  105. package/dist/plan-ledger-conformance.js +99 -0
  106. package/dist/plan-ledger-conformance.js.map +1 -0
  107. package/dist/plan-ledger.d.ts +14 -0
  108. package/dist/plan-ledger.js +42 -0
  109. package/dist/plan-ledger.js.map +1 -0
  110. package/dist/plan-run.d.ts +133 -0
  111. package/dist/plan-run.js +438 -0
  112. package/dist/plan-run.js.map +1 -0
  113. package/dist/render.d.ts +40 -0
  114. package/dist/render.js +92 -0
  115. package/dist/render.js.map +1 -0
  116. package/dist/signer.d.ts +42 -0
  117. package/dist/signer.js +128 -0
  118. package/dist/signer.js.map +1 -0
  119. package/dist/stores/cloudflare.d.ts +34 -0
  120. package/dist/stores/cloudflare.js +84 -0
  121. package/dist/stores/cloudflare.js.map +1 -0
  122. package/dist/stores/dynamodb.d.ts +27 -0
  123. package/dist/stores/dynamodb.js +139 -0
  124. package/dist/stores/dynamodb.js.map +1 -0
  125. package/dist/stores/lost-claim.d.ts +8 -0
  126. package/dist/stores/lost-claim.js +11 -0
  127. package/dist/stores/lost-claim.js.map +1 -0
  128. package/dist/stores/postgres.d.ts +30 -0
  129. package/dist/stores/postgres.js +79 -0
  130. package/dist/stores/postgres.js.map +1 -0
  131. package/dist/test-signer.d.ts +13 -0
  132. package/dist/test-signer.js +18 -0
  133. package/dist/test-signer.js.map +1 -0
  134. package/dist/testing.d.ts +8 -0
  135. package/dist/testing.js +9 -0
  136. package/dist/testing.js.map +1 -0
  137. package/llms.txt +212 -0
  138. package/package.json +108 -5
@@ -0,0 +1,438 @@
1
+ /**
2
+ * `runPlan()`: runs an approved plan in order and tells the model what is true afterwards. Each step is a guarded
3
+ * write, so a crash never repeats one. A failure before the pivot compensates the steps that ran, in reverse order,
4
+ * and each compensation is a guarded write under a key of its own. Once the pivot has run, nothing is undone: the
5
+ * remaining steps run forward, and a step that can't finish is handed to a person.
6
+ *
7
+ * The compensation log is the step records themselves. A step's key is fixed by the plan id and the step id, or by its
8
+ * business key alone when it has one, and each record names the plan and step of the call that wrote it. So the
9
+ * records of an interrupted plan, read in plan order, say which steps this plan ran, and a resumed plan compensates
10
+ * exactly those, in reverse, once each. A step that another plan applied under the same business key is not undone.
11
+ * The one extra record is the plan's decision to compensate, which a resume reads first, so a step that failed is
12
+ * never retried while its plan is half undone.
13
+ *
14
+ * The rules are our synthesis of the sagas report in docs/research/reversible-actions, not a vendor design.
15
+ */
16
+ import { checkEffectScope, effectKey } from "./effect-key.js";
17
+ import { SafetyError } from "./errors.js";
18
+ import { guardedWrite } from "./guarded-write.js";
19
+ import { canonicalInputHash } from "./hash.js";
20
+ import { writeOutcome } from "./outcome.js";
21
+ import { checkedPlanApproval, verifyPlanBeforeStep, } from "./plan-approval.js";
22
+ import { renderOutcome } from "./render.js";
23
+ const FAILED_OPERATION = "plan_failed";
24
+ // Marks a compensation's business key, so it can't equal the business key of any step's own write. `checkSteps()`
25
+ // refuses a business key that starts with it.
26
+ const COMPENSATION_KEY = "buildanagent.plan-compensation:";
27
+ function invalid(message) {
28
+ return new SafetyError("invalid_plan", message);
29
+ }
30
+ const label = (impl) => `${impl.step.id}: ${impl.step.summary}`;
31
+ /** Checks that one of the host's steps is the signed step at its place, and that only compensable steps undo. */
32
+ function checkStep(impl, signed, position) {
33
+ const { step } = impl;
34
+ if (step.id !== signed.id || step.tool !== signed.tool || step.class !== signed.class) {
35
+ throw invalid(`step ${position} of runPlan is not the plan's signed step ${signed.id}`);
36
+ }
37
+ if (step.businessKey !== signed.businessKey)
38
+ throw invalid(`step ${signed.id} has another business key than signed`);
39
+ if (step.businessKey?.startsWith(COMPENSATION_KEY)) {
40
+ throw invalid(`step ${signed.id} has a business key that starts with ${COMPENSATION_KEY}, which compensations use`);
41
+ }
42
+ const undoes = impl.compensate !== undefined || impl.reconcileCompensation !== undefined;
43
+ if (step.class === "compensable" && impl.compensate === undefined) {
44
+ throw invalid(`step ${step.id} is compensable and needs a compensate function`);
45
+ }
46
+ if (step.class !== "compensable" && undoes) {
47
+ throw invalid(`step ${step.id} is ${step.class}, which can't be undone, so it takes no compensate function`);
48
+ }
49
+ }
50
+ /** Checks that the host's steps are the signed ones, in order. */
51
+ function checkSteps(approval, steps) {
52
+ if (steps.length !== approval.steps.length) {
53
+ throw invalid(`runPlan got ${steps.length} steps for a plan that signs ${approval.steps.length}`);
54
+ }
55
+ for (const [index, impl] of steps.entries())
56
+ checkStep(impl, approval.steps[index], index + 1);
57
+ }
58
+ function stepScope(run, id, part) {
59
+ const { planId } = run.approval;
60
+ // A JSON tuple, so no plan id or step id can make one call's id equal another's, whatever characters it holds.
61
+ const toolCallId = JSON.stringify(part === "failed" ? ["decision", planId] : [part, planId, id]);
62
+ return { ...run.options.scope, toolCallId };
63
+ }
64
+ const forwardKey = (run, impl) => effectKey(stepScope(run, impl.step.id, "run"), impl.step.businessKey);
65
+ /** Runs one step, or its compensation, as a guarded write. */
66
+ function write(run, impl, part) {
67
+ const { step } = impl;
68
+ const forward = part === "run";
69
+ const call = forward ? impl.run : impl.compensate;
70
+ const reconcile = forward ? impl.reconcile : impl.reconcileCompensation;
71
+ return guardedWrite({
72
+ store: run.options.store,
73
+ scope: stepScope(run, step.id, part),
74
+ ...(step.businessKey === undefined
75
+ ? {}
76
+ : { businessKey: forward ? step.businessKey : `${COMPENSATION_KEY}${step.businessKey}` }),
77
+ operation: forward ? step.tool : `${step.tool}:compensate`,
78
+ input: impl.input,
79
+ dedupe: forward ? impl.dedupe : "idempotency_key",
80
+ run: (key) => call.call(impl, key),
81
+ toOutcome: (outcome) => outcome,
82
+ ...(reconcile === undefined ? {} : { reconcile: (key) => reconcile.call(impl, key) }),
83
+ ...(run.options.leaseMs === undefined ? {} : { leaseMs: run.options.leaseMs }),
84
+ now: () => run.now().getTime(),
85
+ });
86
+ }
87
+ function stateOf(outcome) {
88
+ if (outcome.reason === "IN_PROGRESS")
89
+ return { kind: "unknown", inProgress: true };
90
+ switch (outcome.kind) {
91
+ case "applied":
92
+ return { kind: "applied" };
93
+ case "partial":
94
+ return { kind: "partial" };
95
+ case "unknown":
96
+ return { kind: "unknown", inProgress: false };
97
+ default:
98
+ // A write that was rejected, or that took effect and was undone by its own tool, left nothing behind.
99
+ return { kind: "failed" };
100
+ }
101
+ }
102
+ /** The plan's decision to compensate, kept as a settled record so a resume reads it before any step runs. */
103
+ async function writeDecision(run, stop) {
104
+ const impl = run.options.steps[stop.index];
105
+ const outcome = writeOutcome({
106
+ kind: stop.leftEffects ? "partial" : "not_applied",
107
+ operation: FAILED_OPERATION,
108
+ reason: stop.reason,
109
+ retry: "never",
110
+ next: "The plan stopped and is being undone.",
111
+ });
112
+ const scope = stepScope(run, "plan", "failed");
113
+ const key = await effectKey(scope);
114
+ const at = run.now().toISOString();
115
+ const record = {
116
+ key,
117
+ scope,
118
+ businessKey: impl.step.id,
119
+ operation: FAILED_OPERATION,
120
+ inputHash: await canonicalInputHash({ plan: run.approval.planId }),
121
+ attempt: 1,
122
+ state: "settled",
123
+ outcome,
124
+ startedAt: at,
125
+ leaseUntil: at,
126
+ settledAt: at,
127
+ };
128
+ const claim = await run.options.store.begin(record);
129
+ // The first decision wins, so two processes that disagree about a failed step both unwind for the same one.
130
+ return claim === "started" ? stop : decisionOf(run, claim.existing);
131
+ }
132
+ function decisionOf(run, record) {
133
+ const index = run.options.steps.findIndex((impl) => impl.step.id === record.businessKey);
134
+ // A decision for a step this call doesn't have means the host passed other steps than the plan that decided.
135
+ if (index < 0)
136
+ throw invalid(`the plan's stored decision names step ${String(record.businessKey)}, which is not a step`);
137
+ const outcome = record.outcome;
138
+ return {
139
+ index,
140
+ reason: outcome.reason,
141
+ leftEffects: outcome.kind === "partial",
142
+ };
143
+ }
144
+ async function readDecision(run) {
145
+ const existing = await run.options.store.get(await effectKey(stepScope(run, "plan", "failed")));
146
+ return existing === undefined || existing.outcome === undefined ? undefined : decisionOf(run, existing);
147
+ }
148
+ /** Undoes the steps that ran, last first, and stops at the first compensation that does not finish. */
149
+ async function unwind(run, stop, undo) {
150
+ const { steps } = run.options;
151
+ const failed = steps[stop.index];
152
+ const ran = [];
153
+ for (const impl of steps.slice(0, stop.index)) {
154
+ const record = await run.options.store.get(await forwardKey(run, impl));
155
+ // Only a step this plan ran is undone. With a business key, a step may have been applied by another plan, whose
156
+ // record this plan reads, and undoing that effect is not this plan's to do.
157
+ const own = record?.scope.toolCallId === stepScope(run, impl.step.id, "run").toolCallId;
158
+ if (own && record?.state === "settled" && record.outcome?.kind === "applied" && impl.compensate !== undefined) {
159
+ ran.push(impl);
160
+ }
161
+ }
162
+ const undone = [];
163
+ const left = [];
164
+ let reason = stop.reason;
165
+ for (const [position, impl] of ran.toReversed().entries()) {
166
+ if (!undo) {
167
+ left.push(label(impl));
168
+ continue;
169
+ }
170
+ const outcome = await write(run, impl, "compensate");
171
+ // Another process is undoing this step right now, so the unwind waits for it instead of failing.
172
+ if (outcome.reason === "IN_PROGRESS")
173
+ return pending(run, impl, "running");
174
+ if (outcome.kind === "applied") {
175
+ undone.push(label(impl));
176
+ continue;
177
+ }
178
+ // The first compensation that fails stops the unwind: a step before it may depend on this one being undone.
179
+ reason = "COMPENSATION_FAILED";
180
+ left.push(...ran.toReversed().slice(position).map(label));
181
+ break;
182
+ }
183
+ const outstanding = [...(stop.leftEffects ? [`${label(failed)} (may have taken effect)`] : []), ...left];
184
+ if (outstanding.length === 0) {
185
+ return {
186
+ status: "failed_compensated",
187
+ planId: run.approval.planId,
188
+ failedStep: failed.step.id,
189
+ reason,
190
+ undone,
191
+ next: `Tell the user the plan stopped at step ${failed.step.id} and everything that had run was undone.`,
192
+ };
193
+ }
194
+ return {
195
+ status: "failed_needs_human",
196
+ planId: run.approval.planId,
197
+ failedStep: failed.step.id,
198
+ reason,
199
+ undone,
200
+ held: left,
201
+ outstanding,
202
+ avoid: "Do not say that the plan completed or failed cleanly, do not run any of its steps again, " +
203
+ "and do not undo anything yourself.",
204
+ };
205
+ }
206
+ const VERDICT = {
207
+ stale_approval: "STALE_APPROVAL",
208
+ expired: "EXPIRED",
209
+ };
210
+ /** Verifies a step that this plan has not started, and says how to stop when it fails. */
211
+ async function verify(run, impl) {
212
+ const { signer, ledger, readState, approval } = run.options;
213
+ const call = { stepId: impl.step.id, tool: impl.step.tool, input: impl.input };
214
+ const check = await verifyPlanBeforeStep(approval, call, { signer, ledger, readState, now: run.now });
215
+ // A replay means this plan's earlier attempt claimed the step before it stopped, and every other check passed now.
216
+ if (check === "ok" || check === "replayed")
217
+ return { check };
218
+ return { check, stop: VERDICT[check] ?? "NOT_VERIFIED" };
219
+ }
220
+ /** Says why nothing ran: a failed check before any step took effect. */
221
+ function notRun(run, check) {
222
+ const planId = run.approval.planId;
223
+ if (check === "stale_approval")
224
+ return {
225
+ status: "stale_approval",
226
+ planId,
227
+ reason: "A value the plan was computed from has changed since it was approved.",
228
+ };
229
+ if (check === "expired")
230
+ return { status: "expired", planId, reason: "The approval lapsed before the plan's first step ran." };
231
+ return { status: "rejected", planId, reason: `The approval did not verify for this plan (${check}).` };
232
+ }
233
+ function pending(run, impl, phase) {
234
+ return { status: "pending", planId: run.approval.planId, phase, stepId: impl.step.id };
235
+ }
236
+ /** Hands a plan to a person from `index` on: the steps before it hold, and it and the steps after it are theirs. */
237
+ function handedOver(run, index, reason, maybeApplied) {
238
+ const { steps } = run.options;
239
+ const outstanding = steps
240
+ .slice(index)
241
+ .map((later, offset) => offset === 0 && maybeApplied ? `${label(later)} (may have taken effect)` : `${label(later)} (not run)`);
242
+ return {
243
+ status: "failed_needs_human",
244
+ planId: run.approval.planId,
245
+ failedStep: steps[index].step.id,
246
+ reason,
247
+ undone: [],
248
+ held: steps.slice(0, index).map(label),
249
+ outstanding,
250
+ avoid: "Do not say that the plan completed, do not undo the steps that ran, " +
251
+ "and do not run these steps again as a new request.",
252
+ };
253
+ }
254
+ /** The outcome of a failed or unfinished step after the pivot, where nothing can be undone. */
255
+ function afterPivot(run, index, state, outcome) {
256
+ const impl = run.options.steps[index];
257
+ // A step that may still succeed, or whose result a check can settle, is tried again by the next call.
258
+ const retry = state.kind !== "partial" && (outcome.retry === "same_key" || outcome.retry === "reconcile_first");
259
+ if (retry || (state.kind === "unknown" && state.inProgress))
260
+ return pending(run, impl, "running");
261
+ const reason = state.kind === "partial" ? "STEP_PARTIAL" : state.kind === "unknown" ? "STEP_UNKNOWN" : "RETRY_REFUSED";
262
+ return handedOver(run, index, reason, state.kind !== "failed");
263
+ }
264
+ /**
265
+ * The result a step's own settled record gives, or `undefined` when the step should run. A step this plan already
266
+ * settled as failed is not run again before the pivot, because the plan is unwinding; after the pivot it runs again.
267
+ * A step settled as unknown is never final: running it checks the earlier attempt with its `reconcile` hook.
268
+ */
269
+ function settledResult(existing, afterThePivot) {
270
+ if (existing.state !== "settled" || existing.outcome === undefined)
271
+ return undefined;
272
+ const state = stateOf(existing.outcome);
273
+ // An unknown record goes back through the guarded write, which reconciles it, whatever step it belongs to.
274
+ if (state.kind === "unknown")
275
+ return undefined;
276
+ return state.kind === "applied" || !afterThePivot ? { state, outcome: existing.outcome } : undefined;
277
+ }
278
+ /** Applies a cancel and the approval's checks to a step this plan has not started. */
279
+ async function admit(run, impl, index, afterThePivot) {
280
+ if (!afterThePivot && run.options.signal?.aborted === true) {
281
+ return { stop: { index, reason: "CANCELLED", leftEffects: false } };
282
+ }
283
+ const verdict = await verify(run, impl);
284
+ return verdict.stop === undefined
285
+ ? undefined
286
+ : { stop: { index, reason: verdict.stop, leftEffects: false }, check: verdict.check };
287
+ }
288
+ /** Runs one step: its own record if it has one, else the approval's checks and then the guarded write. */
289
+ async function forward(run, index, pivotIndex) {
290
+ const impl = run.options.steps[index];
291
+ const afterThePivot = pivotIndex >= 0 && index > pivotIndex;
292
+ const existing = await run.options.store.get(await forwardKey(run, impl));
293
+ if (existing?.scope.toolCallId === stepScope(run, impl.step.id, "run").toolCallId) {
294
+ const settled = settledResult(existing, afterThePivot);
295
+ if (settled !== undefined)
296
+ return settled;
297
+ }
298
+ else {
299
+ const halt = await admit(run, impl, index, afterThePivot);
300
+ if (halt !== undefined)
301
+ return halt;
302
+ }
303
+ const outcome = await write(run, impl, "run");
304
+ return { state: stateOf(outcome), outcome };
305
+ }
306
+ /** Whether a stopped plan may undo the steps that ran: not when the pivot itself left effects behind. */
307
+ const canUndo = (run, stop) => !(stop.leftEffects && run.options.steps[stop.index]?.step.class === "pivot");
308
+ /** A step the approval's checks or a cancel refused: nothing ran if it is the first, else the plan unwinds. */
309
+ async function halted(run, halt, ranAny, pivotIndex) {
310
+ if (!ranAny && halt.check !== undefined)
311
+ return notRun(run, halt.check);
312
+ // After the pivot nothing is undone, so a step the approval refuses there goes to a person with the rest.
313
+ if (pivotIndex >= 0 && halt.stop.index > pivotIndex)
314
+ return handedOver(run, halt.stop.index, halt.stop.reason, false);
315
+ return unwind(run, await writeDecision(run, halt.stop), true);
316
+ }
317
+ /** A step that ran and did not apply: the plan waits, hands over, or unwinds, as the pivot decides. */
318
+ async function notApplied(run, index, pivotIndex, result) {
319
+ const { state, outcome } = result;
320
+ const impl = run.options.steps[index];
321
+ if (pivotIndex >= 0 && index > pivotIndex)
322
+ return afterPivot(run, index, state, outcome);
323
+ if (state.kind === "unknown" && (state.inProgress || index === pivotIndex)) {
324
+ return pending(run, impl, state.inProgress ? "running" : "pivot_unknown");
325
+ }
326
+ const reason = state.kind === "failed" ? "STEP_FAILED" : state.kind === "partial" ? "STEP_PARTIAL" : "STEP_UNKNOWN";
327
+ const stop = await writeDecision(run, { index, reason, leftEffects: state.kind !== "failed" });
328
+ return unwind(run, stop, canUndo(run, stop));
329
+ }
330
+ async function runForward(run) {
331
+ const { steps } = run.options;
332
+ const pivotIndex = run.approval.steps.findIndex((step) => step.class === "pivot");
333
+ let ranAny = false;
334
+ for (const index of steps.keys()) {
335
+ const result = await forward(run, index, pivotIndex);
336
+ if ("stop" in result)
337
+ return halted(run, result, ranAny, pivotIndex);
338
+ if (result.state.kind !== "applied")
339
+ return notApplied(run, index, pivotIndex, result);
340
+ ranAny = true;
341
+ }
342
+ return { status: "completed", planId: run.approval.planId, effects: steps.map(label) };
343
+ }
344
+ /**
345
+ * Runs the approved plan, in order, and reports what is true afterwards. Call it again with the same approval to
346
+ * resume a plan that stopped, crashed or came back `pending`: it reads the records, repeats no step, and carries on.
347
+ *
348
+ * - Before each step up to and including the pivot, the approval is verified, and a cancel stops the plan.
349
+ * - A step that fails before the pivot unwinds the steps that ran, in reverse, and the pivot never runs.
350
+ * - A pivot whose result is not known returns `pending` with `pivot_unknown`: nothing is undone, and nothing runs
351
+ * again under a fresh key. A later call reconciles it and, if it took effect, runs forward.
352
+ * - After the pivot nothing is undone: a step that can't finish is retried, or handed to a person.
353
+ *
354
+ * It throws a `SafetyError`, code `invalid_plan`, when the steps are not the signed ones or a compensable step has no
355
+ * `compensate`, and code `invalid_effect` for an empty scope field. A malformed or forged approval returns `rejected`.
356
+ */
357
+ export async function runPlan(options) {
358
+ checkEffectScope({ ...options.scope, toolCallId: "plan" });
359
+ const approval = await checkedPlanApproval(options.approval, options.signer);
360
+ if (approval === undefined) {
361
+ return {
362
+ status: "rejected",
363
+ planId: "unknown",
364
+ reason: "The approval is malformed, or its signature does not verify.",
365
+ };
366
+ }
367
+ checkSteps(approval, options.steps);
368
+ const run = { options, approval, now: options.now ?? (() => new Date()) };
369
+ const decided = await readDecision(run);
370
+ return decided === undefined ? runForward(run) : unwind(run, decided, canUndo(run, decided));
371
+ }
372
+ /**
373
+ * The write outcome a plan outcome stands for, in the five kinds the model already reads: `completed` is `applied`,
374
+ * `failed_compensated` is `compensated`, `failed_needs_human` is `partial`, `pending` is `unknown`, and the three
375
+ * statuses that mean no step ran are `not_applied`.
376
+ */
377
+ export function planWriteOutcome(outcome) {
378
+ const operation = "run_plan";
379
+ switch (outcome.status) {
380
+ case "completed":
381
+ return writeOutcome({
382
+ kind: "applied",
383
+ operation,
384
+ applied: outcome.effects,
385
+ next: "Tell the user the plan completed.",
386
+ });
387
+ case "failed_compensated":
388
+ return writeOutcome({
389
+ kind: "compensated",
390
+ operation,
391
+ reverted: outcome.undone,
392
+ reason: outcome.reason,
393
+ currentState: `The plan stopped at step ${outcome.failedStep}, and every step that had run was undone.`,
394
+ next: outcome.next,
395
+ });
396
+ case "failed_needs_human": {
397
+ const handle = outcome.outstanding.join("; ");
398
+ return writeOutcome({
399
+ kind: "partial",
400
+ operation,
401
+ applied: outcome.held,
402
+ reverted: outcome.undone,
403
+ reason: outcome.reason,
404
+ retry: "never",
405
+ currentState: `The plan stopped at step ${outcome.failedStep}. A person must handle: ${handle}.`,
406
+ next: "Tell the user a person must finish or undo the plan, and say which steps are still in effect.",
407
+ avoid: outcome.avoid,
408
+ });
409
+ }
410
+ case "pending":
411
+ return writeOutcome({
412
+ kind: "unknown",
413
+ operation,
414
+ retry: outcome.phase === "pivot_unknown" ? "reconcile_first" : "never",
415
+ reason: outcome.phase === "pivot_unknown" ? "PIVOT_UNKNOWN" : "PLAN_RUNNING",
416
+ currentState: outcome.phase === "pivot_unknown"
417
+ ? `It is not known whether step ${outcome.stepId}, the point of no return, took effect.`
418
+ : `The plan is still running at step ${outcome.stepId}.`,
419
+ next: outcome.phase === "pivot_unknown"
420
+ ? "Tell the user the plan is waiting on a check, and do not say it failed."
421
+ : "Tell the user the plan is still running, and wait for its result.",
422
+ });
423
+ default:
424
+ return writeOutcome({
425
+ kind: "not_applied",
426
+ operation,
427
+ retry: "new_operation_only",
428
+ reason: outcome.status === "rejected" ? "NOT_VERIFIED" : outcome.status.toUpperCase(),
429
+ currentState: outcome.reason,
430
+ next: "Tell the user the plan did not run, and ask for a new approval if they still want it.",
431
+ });
432
+ }
433
+ }
434
+ /** Renders a plan outcome for the model: `planWriteOutcome()` through `renderOutcome()`. */
435
+ export function renderPlanOutcome(outcome) {
436
+ return renderOutcome(planWriteOutcome(outcome));
437
+ }
438
+ //# sourceMappingURL=plan-run.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plan-run.js","sourceRoot":"","sources":["../src/plan-run.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAE,gBAAgB,EAAoB,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAEhF,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,YAAY,EAAoB,MAAM,oBAAoB,CAAC;AACpE,OAAO,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAC/C,OAAO,EAAqB,YAAY,EAAE,MAAM,cAAc,CAAC;AAC/D,OAAO,EACL,mBAAmB,EAMnB,oBAAoB,GACrB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAwB,aAAa,EAAE,MAAM,aAAa,CAAC;AA2GlE,MAAM,gBAAgB,GAAG,aAAa,CAAC;AACvC,kHAAkH;AAClH,8CAA8C;AAC9C,MAAM,gBAAgB,GAAG,iCAAiC,CAAC;AAQ3D,SAAS,OAAO,CAAC,OAAe;IAC9B,OAAO,IAAI,WAAW,CAAC,cAAc,EAAE,OAAO,CAAC,CAAC;AAClD,CAAC;AAED,MAAM,KAAK,GAAG,CAAC,IAAkB,EAAU,EAAE,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,KAAK,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;AAEtF,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CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC,CAAC;AAClD,CAAC","sourcesContent":["/**\n * `runPlan()`: runs an approved plan in order and tells the model what is true afterwards. Each step is a guarded\n * write, so a crash never repeats one. A failure before the pivot compensates the steps that ran, in reverse order,\n * and each compensation is a guarded write under a key of its own. Once the pivot has run, nothing is undone: the\n * remaining steps run forward, and a step that can't finish is handed to a person.\n *\n * The compensation log is the step records themselves. A step's key is fixed by the plan id and the step id, or by its\n * business key alone when it has one, and each record names the plan and step of the call that wrote it. So the\n * records of an interrupted plan, read in plan order, say which steps this plan ran, and a resumed plan compensates\n * exactly those, in reverse, once each. A step that another plan applied under the same business key is not undone.\n * The one extra record is the plan's decision to compensate, which a resume reads first, so a step that failed is\n * never retried while its plan is half undone.\n *\n * The rules are our synthesis of the sagas report in docs/research/reversible-actions, not a vendor design.\n */\nimport { checkEffectScope, type EffectScope, effectKey } from \"./effect-key.js\";\nimport type { EffectRecord, EffectStore } from \"./effect-store.js\";\nimport { SafetyError } from \"./errors.js\";\nimport { guardedWrite, type WriteDedupe } from \"./guarded-write.js\";\nimport { canonicalInputHash } from \"./hash.js\";\nimport { type WriteOutcome, writeOutcome } from \"./outcome.js\";\nimport {\n checkedPlanApproval,\n type PlanApproval,\n type PlanLedger,\n type PlanStep,\n type PlanStepCheck,\n type StateRead,\n verifyPlanBeforeStep,\n} from \"./plan-approval.js\";\nimport { type RenderedOutcome, renderOutcome } from \"./render.js\";\nimport type { ApprovalSigner } from \"./signer.js\";\n\n/** One signed step as the host runs it: the step, its exact input and the calls that perform and undo it. */\nexport interface PlanStepImpl {\n /** The step as the approval signs it. Its id, tool, class and business key must match the signed step. */\n readonly step: PlanStep;\n /** The step's exact input. The approval signs its hash, and a different input is refused as not verified. */\n readonly input: unknown;\n /** How a retry of `run` finds out what an earlier attempt did, as for `guardedWrite()`. */\n readonly dedupe: WriteDedupe;\n /** Performs the step. Send `key` to the external API's idempotency header, or where `reconcile` can find it. */\n run(key: string): Promise<WriteOutcome>;\n /** Reads the external system's state for `run`'s key, as for `guardedWrite()`. */\n reconcile?(key: string): Promise<WriteOutcome | \"not_found\">;\n /**\n * Undoes the step, and returns an `applied` outcome once it has. Required for a `compensable` step and refused for\n * the others. It runs as a guarded write with its own key, so it must be idempotent under that key.\n */\n compensate?(key: string): Promise<WriteOutcome>;\n /** Reads the external system's state for `compensate`'s key, so a compensation that crashed can be checked. */\n reconcileCompensation?(key: string): Promise<WriteOutcome | \"not_found\">;\n}\n\n/** Where a plan runs: the tenant, session and branch its writes are keyed under. */\nexport type PlanScope = Omit<EffectScope, \"toolCallId\">;\n\n/** The options of `runPlan()`. */\nexport interface RunPlanOptions {\n /** The signed plan approval, as `signPlan()` returned it. */\n readonly approval: unknown;\n /** The steps, in the order the approval signs them. */\n readonly steps: readonly PlanStepImpl[];\n /** Where the effect records live. Use a durable store wherever a plan must resume after a crash. */\n readonly store: EffectStore;\n /** The tenant, session and branch the plan's writes belong to. */\n readonly scope: PlanScope;\n /** A signer that holds the key the approval names. */\n readonly signer: ApprovalSigner;\n /** Where each step's claim is recorded. Use a durable ledger wherever a plan must resume after a crash. */\n readonly ledger: PlanLedger;\n /** Re-reads the approval's `stateReads` now, as for `verifyPlanBeforeStep()`. */\n readonly readState: (reads: readonly StateRead[]) => Promise<readonly unknown[]>;\n /**\n * A cancel. Checked before each step up to and including the pivot starts: a cancel then compensates the steps that\n * ran. Once the pivot has started it is ignored, and the plan runs forward.\n */\n readonly signal?: AbortSignal;\n /** How long a started write counts as live, in milliseconds, as for `guardedWrite()`. */\n readonly leaseMs?: number;\n /** Returns the current time. Defaults to `new Date()`. */\n readonly now?: () => Date;\n}\n\n/** Why a plan that began could not finish. */\nexport type PlanFailureReason =\n | \"STEP_FAILED\"\n | \"STEP_PARTIAL\"\n | \"STEP_UNKNOWN\"\n | \"CANCELLED\"\n | \"STALE_APPROVAL\"\n | \"EXPIRED\"\n | \"NOT_VERIFIED\"\n | \"COMPENSATION_FAILED\"\n | \"RETRY_REFUSED\";\n\n/**\n * What a plan did, computed by the harness and never by the model. `completed`: every step ran. `failed_compensated`:\n * a step failed and every step that had run was undone. `failed_needs_human`: something still holds that the harness\n * could not undo, listed in `outstanding`. `pending`: the plan has not finished; call `runPlan()` again, and tell the\n * user nothing final. The last three mean no step ran.\n */\nexport type PlanOutcome =\n | { readonly status: \"completed\"; readonly planId: string; readonly effects: readonly string[] }\n | {\n readonly status: \"failed_compensated\";\n readonly planId: string;\n readonly failedStep: string;\n readonly reason: PlanFailureReason;\n readonly undone: readonly string[];\n readonly next: string;\n }\n | {\n readonly status: \"failed_needs_human\";\n readonly planId: string;\n readonly failedStep: string;\n readonly reason: PlanFailureReason;\n readonly undone: readonly string[];\n /** The steps that took effect and still hold. */\n readonly held: readonly string[];\n /** What a person must finish or undo: the stopped step, the steps not run, and any step not undone. */\n readonly outstanding: readonly string[];\n readonly avoid: string;\n }\n | {\n readonly status: \"pending\";\n readonly planId: string;\n /** `running`: a step is in flight or waiting for a retry. `pivot_unknown`: the pivot's result is not known. */\n readonly phase: \"running\" | \"pivot_unknown\";\n readonly stepId: string;\n }\n | {\n readonly status: \"stale_approval\" | \"expired\" | \"rejected\";\n readonly planId: string;\n readonly reason: string;\n };\n\nconst FAILED_OPERATION = \"plan_failed\";\n// Marks a compensation's business key, so it can't equal the business key of any step's own write. `checkSteps()`\n// refuses a business key that starts with it.\nconst COMPENSATION_KEY = \"buildanagent.plan-compensation:\";\n\ninterface Run {\n readonly options: RunPlanOptions;\n readonly approval: PlanApproval;\n readonly now: () => Date;\n}\n\nfunction invalid(message: string): SafetyError {\n return new SafetyError(\"invalid_plan\", message);\n}\n\nconst label = (impl: PlanStepImpl): string => `${impl.step.id}: ${impl.step.summary}`;\n\n/** Checks that one of the host's steps is the signed step at its place, and that only compensable steps undo. */\nfunction checkStep(impl: PlanStepImpl, signed: PlanStep, position: number): void {\n const { step } = impl;\n if (step.id !== signed.id || step.tool !== signed.tool || step.class !== signed.class) {\n throw invalid(`step ${position} of runPlan is not the plan's signed step ${signed.id}`);\n }\n if (step.businessKey !== signed.businessKey) throw invalid(`step ${signed.id} has another business key than signed`);\n if (step.businessKey?.startsWith(COMPENSATION_KEY)) {\n throw invalid(`step ${signed.id} has a business key that starts with ${COMPENSATION_KEY}, which compensations use`);\n }\n const undoes = impl.compensate !== undefined || impl.reconcileCompensation !== undefined;\n if (step.class === \"compensable\" && impl.compensate === undefined) {\n throw invalid(`step ${step.id} is compensable and needs a compensate function`);\n }\n if (step.class !== \"compensable\" && undoes) {\n throw invalid(`step ${step.id} is ${step.class}, which can't be undone, so it takes no compensate function`);\n }\n}\n\n/** Checks that the host's steps are the signed ones, in order. */\nfunction checkSteps(approval: PlanApproval, steps: readonly PlanStepImpl[]): void {\n if (steps.length !== approval.steps.length) {\n throw invalid(`runPlan got ${steps.length} steps for a plan that signs ${approval.steps.length}`);\n }\n for (const [index, impl] of steps.entries()) checkStep(impl, approval.steps[index] as PlanStep, index + 1);\n}\n\nfunction stepScope(run: Run, id: string, part: \"run\" | \"compensate\" | \"failed\"): EffectScope {\n const { planId } = run.approval;\n // A JSON tuple, so no plan id or step id can make one call's id equal another's, whatever characters it holds.\n const toolCallId = JSON.stringify(part === \"failed\" ? [\"decision\", planId] : [part, planId, id]);\n return { ...run.options.scope, toolCallId };\n}\n\nconst forwardKey = (run: Run, impl: PlanStepImpl) =>\n effectKey(stepScope(run, impl.step.id, \"run\"), impl.step.businessKey);\n\n/** Runs one step, or its compensation, as a guarded write. */\nfunction write(run: Run, impl: PlanStepImpl, part: \"run\" | \"compensate\"): Promise<WriteOutcome> {\n const { step } = impl;\n const forward = part === \"run\";\n const call = forward ? impl.run : (impl.compensate as PlanStepImpl[\"run\"]);\n const reconcile = forward ? impl.reconcile : impl.reconcileCompensation;\n return guardedWrite<WriteOutcome>({\n store: run.options.store,\n scope: stepScope(run, step.id, part),\n ...(step.businessKey === undefined\n ? {}\n : { businessKey: forward ? step.businessKey : `${COMPENSATION_KEY}${step.businessKey}` }),\n operation: forward ? step.tool : `${step.tool}:compensate`,\n input: impl.input,\n dedupe: forward ? impl.dedupe : \"idempotency_key\",\n run: (key) => call.call(impl, key),\n toOutcome: (outcome) => outcome,\n ...(reconcile === undefined ? {} : { reconcile: (key: string) => reconcile.call(impl, key) }),\n ...(run.options.leaseMs === undefined ? {} : { leaseMs: run.options.leaseMs }),\n now: () => run.now().getTime(),\n });\n}\n\n/** The state of one forward step, as a run or its records show it. */\ntype StepState =\n | { readonly kind: \"applied\" }\n | { readonly kind: \"failed\" }\n | { readonly kind: \"partial\" }\n | { readonly kind: \"unknown\"; readonly inProgress: boolean };\n\nfunction stateOf(outcome: WriteOutcome): StepState {\n if (outcome.reason === \"IN_PROGRESS\") return { kind: \"unknown\", inProgress: true };\n switch (outcome.kind) {\n case \"applied\":\n return { kind: \"applied\" };\n case \"partial\":\n return { kind: \"partial\" };\n case \"unknown\":\n return { kind: \"unknown\", inProgress: false };\n default:\n // A write that was rejected, or that took effect and was undone by its own tool, left nothing behind.\n return { kind: \"failed\" };\n }\n}\n\n/** What stops a run: the step, why, and whether that step itself may have left effects that need a person. */\ninterface Stop {\n readonly index: number;\n readonly reason: PlanFailureReason;\n readonly leftEffects: boolean;\n}\n\n/** The plan's decision to compensate, kept as a settled record so a resume reads it before any step runs. */\nasync function writeDecision(run: Run, stop: Stop): Promise<Stop> {\n const impl = run.options.steps[stop.index] as PlanStepImpl;\n const outcome = writeOutcome({\n kind: stop.leftEffects ? \"partial\" : \"not_applied\",\n operation: FAILED_OPERATION,\n reason: stop.reason,\n retry: \"never\",\n next: \"The plan stopped and is being undone.\",\n });\n const scope = stepScope(run, \"plan\", \"failed\");\n const key = await effectKey(scope);\n const at = run.now().toISOString();\n const record: EffectRecord = {\n key,\n scope,\n businessKey: impl.step.id,\n operation: FAILED_OPERATION,\n inputHash: await canonicalInputHash({ plan: run.approval.planId }),\n attempt: 1,\n state: \"settled\",\n outcome,\n startedAt: at,\n leaseUntil: at,\n settledAt: at,\n };\n const claim = await run.options.store.begin(record);\n // The first decision wins, so two processes that disagree about a failed step both unwind for the same one.\n return claim === \"started\" ? stop : decisionOf(run, claim.existing);\n}\n\nfunction decisionOf(run: Run, record: EffectRecord): Stop {\n const index = run.options.steps.findIndex((impl) => impl.step.id === record.businessKey);\n // A decision for a step this call doesn't have means the host passed other steps than the plan that decided.\n if (index < 0)\n throw invalid(`the plan's stored decision names step ${String(record.businessKey)}, which is not a step`);\n const outcome = record.outcome as WriteOutcome;\n return {\n index,\n reason: outcome.reason as PlanFailureReason,\n leftEffects: outcome.kind === \"partial\",\n };\n}\n\nasync function readDecision(run: Run): Promise<Stop | undefined> {\n const existing = await run.options.store.get(await effectKey(stepScope(run, \"plan\", \"failed\")));\n return existing === undefined || existing.outcome === undefined ? undefined : decisionOf(run, existing);\n}\n\n/** Undoes the steps that ran, last first, and stops at the first compensation that does not finish. */\nasync function unwind(run: Run, stop: Stop, undo: boolean): Promise<PlanOutcome> {\n const { steps } = run.options;\n const failed = steps[stop.index] as PlanStepImpl;\n const ran: PlanStepImpl[] = [];\n for (const impl of steps.slice(0, stop.index)) {\n const record = await run.options.store.get(await forwardKey(run, impl));\n // Only a step this plan ran is undone. With a business key, a step may have been applied by another plan, whose\n // record this plan reads, and undoing that effect is not this plan's to do.\n const own = record?.scope.toolCallId === stepScope(run, impl.step.id, \"run\").toolCallId;\n if (own && record?.state === \"settled\" && record.outcome?.kind === \"applied\" && impl.compensate !== undefined) {\n ran.push(impl);\n }\n }\n const undone: string[] = [];\n const left: string[] = [];\n let reason = stop.reason;\n for (const [position, impl] of ran.toReversed().entries()) {\n if (!undo) {\n left.push(label(impl));\n continue;\n }\n const outcome = await write(run, impl, \"compensate\");\n // Another process is undoing this step right now, so the unwind waits for it instead of failing.\n if (outcome.reason === \"IN_PROGRESS\") return pending(run, impl, \"running\");\n if (outcome.kind === \"applied\") {\n undone.push(label(impl));\n continue;\n }\n // The first compensation that fails stops the unwind: a step before it may depend on this one being undone.\n reason = \"COMPENSATION_FAILED\";\n left.push(...ran.toReversed().slice(position).map(label));\n break;\n }\n const outstanding = [...(stop.leftEffects ? [`${label(failed)} (may have taken effect)`] : []), ...left];\n if (outstanding.length === 0) {\n return {\n status: \"failed_compensated\",\n planId: run.approval.planId,\n failedStep: failed.step.id,\n reason,\n undone,\n next: `Tell the user the plan stopped at step ${failed.step.id} and everything that had run was undone.`,\n };\n }\n return {\n status: \"failed_needs_human\",\n planId: run.approval.planId,\n failedStep: failed.step.id,\n reason,\n undone,\n held: left,\n outstanding,\n avoid:\n \"Do not say that the plan completed or failed cleanly, do not run any of its steps again, \" +\n \"and do not undo anything yourself.\",\n };\n}\n\nconst VERDICT: Partial<Record<PlanStepCheck, PlanFailureReason>> = {\n stale_approval: \"STALE_APPROVAL\",\n expired: \"EXPIRED\",\n};\n\n/** Verifies a step that this plan has not started, and says how to stop when it fails. */\nasync function verify(\n run: Run,\n impl: PlanStepImpl,\n): Promise<{ readonly stop?: PlanFailureReason; readonly check: PlanStepCheck }> {\n const { signer, ledger, readState, approval } = run.options;\n const call = { stepId: impl.step.id, tool: impl.step.tool, input: impl.input };\n const check = await verifyPlanBeforeStep(approval, call, { signer, ledger, readState, now: run.now });\n // A replay means this plan's earlier attempt claimed the step before it stopped, and every other check passed now.\n if (check === \"ok\" || check === \"replayed\") return { check };\n return { check, stop: VERDICT[check] ?? \"NOT_VERIFIED\" };\n}\n\n/** Says why nothing ran: a failed check before any step took effect. */\nfunction notRun(run: Run, check: PlanStepCheck): PlanOutcome {\n const planId = run.approval.planId;\n if (check === \"stale_approval\")\n return {\n status: \"stale_approval\",\n planId,\n reason: \"A value the plan was computed from has changed since it was approved.\",\n };\n if (check === \"expired\")\n return { status: \"expired\", planId, reason: \"The approval lapsed before the plan's first step ran.\" };\n return { status: \"rejected\", planId, reason: `The approval did not verify for this plan (${check}).` };\n}\n\nfunction pending(run: Run, impl: PlanStepImpl, phase: \"running\" | \"pivot_unknown\"): PlanOutcome {\n return { status: \"pending\", planId: run.approval.planId, phase, stepId: impl.step.id };\n}\n\n/** Hands a plan to a person from `index` on: the steps before it hold, and it and the steps after it are theirs. */\nfunction handedOver(run: Run, index: number, reason: PlanFailureReason, maybeApplied: boolean): PlanOutcome {\n const { steps } = run.options;\n const outstanding = steps\n .slice(index)\n .map((later, offset) =>\n offset === 0 && maybeApplied ? `${label(later)} (may have taken effect)` : `${label(later)} (not run)`,\n );\n return {\n status: \"failed_needs_human\",\n planId: run.approval.planId,\n failedStep: (steps[index] as PlanStepImpl).step.id,\n reason,\n undone: [],\n held: steps.slice(0, index).map(label),\n outstanding,\n avoid:\n \"Do not say that the plan completed, do not undo the steps that ran, \" +\n \"and do not run these steps again as a new request.\",\n };\n}\n\n/** The outcome of a failed or unfinished step after the pivot, where nothing can be undone. */\nfunction afterPivot(run: Run, index: number, state: StepState, outcome: WriteOutcome): PlanOutcome {\n const impl = run.options.steps[index] as PlanStepImpl;\n // A step that may still succeed, or whose result a check can settle, is tried again by the next call.\n const retry = state.kind !== \"partial\" && (outcome.retry === \"same_key\" || outcome.retry === \"reconcile_first\");\n if (retry || (state.kind === \"unknown\" && state.inProgress)) return pending(run, impl, \"running\");\n const reason =\n state.kind === \"partial\" ? \"STEP_PARTIAL\" : state.kind === \"unknown\" ? \"STEP_UNKNOWN\" : \"RETRY_REFUSED\";\n return handedOver(run, index, reason, state.kind !== \"failed\");\n}\n\n/** What a step that ran or was already recorded came to. */\ninterface Done {\n readonly state: StepState;\n readonly outcome: WriteOutcome;\n}\n\n/** A step that did not run, and why; `check` is set when the approval's verification refused it. */\ninterface Halt {\n readonly stop: Stop;\n readonly check?: PlanStepCheck;\n}\n\n/**\n * The result a step's own settled record gives, or `undefined` when the step should run. A step this plan already\n * settled as failed is not run again before the pivot, because the plan is unwinding; after the pivot it runs again.\n * A step settled as unknown is never final: running it checks the earlier attempt with its `reconcile` hook.\n */\nfunction settledResult(existing: EffectRecord, afterThePivot: boolean): Done | undefined {\n if (existing.state !== \"settled\" || existing.outcome === undefined) return undefined;\n const state = stateOf(existing.outcome);\n // An unknown record goes back through the guarded write, which reconciles it, whatever step it belongs to.\n if (state.kind === \"unknown\") return undefined;\n return state.kind === \"applied\" || !afterThePivot ? { state, outcome: existing.outcome } : undefined;\n}\n\n/** Applies a cancel and the approval's checks to a step this plan has not started. */\nasync function admit(run: Run, impl: PlanStepImpl, index: number, afterThePivot: boolean): Promise<Halt | undefined> {\n if (!afterThePivot && run.options.signal?.aborted === true) {\n return { stop: { index, reason: \"CANCELLED\", leftEffects: false } };\n }\n const verdict = await verify(run, impl);\n return verdict.stop === undefined\n ? undefined\n : { stop: { index, reason: verdict.stop, leftEffects: false }, check: verdict.check };\n}\n\n/** Runs one step: its own record if it has one, else the approval's checks and then the guarded write. */\nasync function forward(run: Run, index: number, pivotIndex: number): Promise<Done | Halt> {\n const impl = run.options.steps[index] as PlanStepImpl;\n const afterThePivot = pivotIndex >= 0 && index > pivotIndex;\n const existing = await run.options.store.get(await forwardKey(run, impl));\n if (existing?.scope.toolCallId === stepScope(run, impl.step.id, \"run\").toolCallId) {\n const settled = settledResult(existing, afterThePivot);\n if (settled !== undefined) return settled;\n } else {\n const halt = await admit(run, impl, index, afterThePivot);\n if (halt !== undefined) return halt;\n }\n const outcome = await write(run, impl, \"run\");\n return { state: stateOf(outcome), outcome };\n}\n\n/** Whether a stopped plan may undo the steps that ran: not when the pivot itself left effects behind. */\nconst canUndo = (run: Run, stop: Stop): boolean =>\n !(stop.leftEffects && run.options.steps[stop.index]?.step.class === \"pivot\");\n\n/** A step the approval's checks or a cancel refused: nothing ran if it is the first, else the plan unwinds. */\nasync function halted(run: Run, halt: Halt, ranAny: boolean, pivotIndex: number): Promise<PlanOutcome> {\n if (!ranAny && halt.check !== undefined) return notRun(run, halt.check);\n // After the pivot nothing is undone, so a step the approval refuses there goes to a person with the rest.\n if (pivotIndex >= 0 && halt.stop.index > pivotIndex) return handedOver(run, halt.stop.index, halt.stop.reason, false);\n return unwind(run, await writeDecision(run, halt.stop), true);\n}\n\n/** A step that ran and did not apply: the plan waits, hands over, or unwinds, as the pivot decides. */\nasync function notApplied(run: Run, index: number, pivotIndex: number, result: Done): Promise<PlanOutcome> {\n const { state, outcome } = result;\n const impl = run.options.steps[index] as PlanStepImpl;\n if (pivotIndex >= 0 && index > pivotIndex) return afterPivot(run, index, state, outcome);\n if (state.kind === \"unknown\" && (state.inProgress || index === pivotIndex)) {\n return pending(run, impl, state.inProgress ? \"running\" : \"pivot_unknown\");\n }\n const reason: PlanFailureReason =\n state.kind === \"failed\" ? \"STEP_FAILED\" : state.kind === \"partial\" ? \"STEP_PARTIAL\" : \"STEP_UNKNOWN\";\n const stop = await writeDecision(run, { index, reason, leftEffects: state.kind !== \"failed\" });\n return unwind(run, stop, canUndo(run, stop));\n}\n\nasync function runForward(run: Run): Promise<PlanOutcome> {\n const { steps } = run.options;\n const pivotIndex = run.approval.steps.findIndex((step) => step.class === \"pivot\");\n let ranAny = false;\n for (const index of steps.keys()) {\n const result = await forward(run, index, pivotIndex);\n if (\"stop\" in result) return halted(run, result, ranAny, pivotIndex);\n if (result.state.kind !== \"applied\") return notApplied(run, index, pivotIndex, result);\n ranAny = true;\n }\n return { status: \"completed\", planId: run.approval.planId, effects: steps.map(label) };\n}\n\n/**\n * Runs the approved plan, in order, and reports what is true afterwards. Call it again with the same approval to\n * resume a plan that stopped, crashed or came back `pending`: it reads the records, repeats no step, and carries on.\n *\n * - Before each step up to and including the pivot, the approval is verified, and a cancel stops the plan.\n * - A step that fails before the pivot unwinds the steps that ran, in reverse, and the pivot never runs.\n * - A pivot whose result is not known returns `pending` with `pivot_unknown`: nothing is undone, and nothing runs\n * again under a fresh key. A later call reconciles it and, if it took effect, runs forward.\n * - After the pivot nothing is undone: a step that can't finish is retried, or handed to a person.\n *\n * It throws a `SafetyError`, code `invalid_plan`, when the steps are not the signed ones or a compensable step has no\n * `compensate`, and code `invalid_effect` for an empty scope field. A malformed or forged approval returns `rejected`.\n */\nexport async function runPlan(options: RunPlanOptions): Promise<PlanOutcome> {\n checkEffectScope({ ...options.scope, toolCallId: \"plan\" });\n const approval = await checkedPlanApproval(options.approval, options.signer);\n if (approval === undefined) {\n return {\n status: \"rejected\",\n planId: \"unknown\",\n reason: \"The approval is malformed, or its signature does not verify.\",\n };\n }\n checkSteps(approval, options.steps);\n const run: Run = { options, approval, now: options.now ?? (() => new Date()) };\n const decided = await readDecision(run);\n return decided === undefined ? runForward(run) : unwind(run, decided, canUndo(run, decided));\n}\n\n/**\n * The write outcome a plan outcome stands for, in the five kinds the model already reads: `completed` is `applied`,\n * `failed_compensated` is `compensated`, `failed_needs_human` is `partial`, `pending` is `unknown`, and the three\n * statuses that mean no step ran are `not_applied`.\n */\nexport function planWriteOutcome(outcome: PlanOutcome): WriteOutcome {\n const operation = \"run_plan\";\n switch (outcome.status) {\n case \"completed\":\n return writeOutcome({\n kind: \"applied\",\n operation,\n applied: outcome.effects,\n next: \"Tell the user the plan completed.\",\n });\n case \"failed_compensated\":\n return writeOutcome({\n kind: \"compensated\",\n operation,\n reverted: outcome.undone,\n reason: outcome.reason,\n currentState: `The plan stopped at step ${outcome.failedStep}, and every step that had run was undone.`,\n next: outcome.next,\n });\n case \"failed_needs_human\": {\n const handle = outcome.outstanding.join(\"; \");\n return writeOutcome({\n kind: \"partial\",\n operation,\n applied: outcome.held,\n reverted: outcome.undone,\n reason: outcome.reason,\n retry: \"never\",\n currentState: `The plan stopped at step ${outcome.failedStep}. A person must handle: ${handle}.`,\n next: \"Tell the user a person must finish or undo the plan, and say which steps are still in effect.\",\n avoid: outcome.avoid,\n });\n }\n case \"pending\":\n return writeOutcome({\n kind: \"unknown\",\n operation,\n retry: outcome.phase === \"pivot_unknown\" ? \"reconcile_first\" : \"never\",\n reason: outcome.phase === \"pivot_unknown\" ? \"PIVOT_UNKNOWN\" : \"PLAN_RUNNING\",\n currentState:\n outcome.phase === \"pivot_unknown\"\n ? `It is not known whether step ${outcome.stepId}, the point of no return, took effect.`\n : `The plan is still running at step ${outcome.stepId}.`,\n next:\n outcome.phase === \"pivot_unknown\"\n ? \"Tell the user the plan is waiting on a check, and do not say it failed.\"\n : \"Tell the user the plan is still running, and wait for its result.\",\n });\n default:\n return writeOutcome({\n kind: \"not_applied\",\n operation,\n retry: \"new_operation_only\",\n reason: outcome.status === \"rejected\" ? \"NOT_VERIFIED\" : outcome.status.toUpperCase(),\n currentState: outcome.reason,\n next: \"Tell the user the plan did not run, and ask for a new approval if they still want it.\",\n });\n }\n}\n\n/** Renders a plan outcome for the model: `planWriteOutcome()` through `renderOutcome()`. */\nexport function renderPlanOutcome(outcome: PlanOutcome): RenderedOutcome {\n return renderOutcome(planWriteOutcome(outcome));\n}\n"]}
@@ -0,0 +1,40 @@
1
+ /**
2
+ * `renderOutcome()`: turns a write outcome into what the model reads. The outcome travels in the tool result's body,
3
+ * as a sentence and a structured payload, with the provider's error flag set as well, because some adapters drop the
4
+ * flag and some SDKs hide text blocks once structured content is set (server rollback report).
5
+ */
6
+ import { type OutcomeKind, type Retry, type WriteOutcome } from "./outcome.js";
7
+ /**
8
+ * The structured half of a rendered outcome: the outcome's own fields, as plain JSON. Optional fields the outcome
9
+ * leaves out are left out here too.
10
+ */
11
+ export type OutcomePayload = {
12
+ readonly kind: OutcomeKind;
13
+ readonly operation: string;
14
+ readonly effectKey?: string;
15
+ readonly applied: readonly string[];
16
+ readonly reverted: readonly string[];
17
+ readonly notReversible: readonly string[];
18
+ readonly currentState?: string;
19
+ readonly retry: Retry;
20
+ readonly next: string;
21
+ readonly avoid?: string;
22
+ readonly reason?: string;
23
+ };
24
+ /** A write outcome as the model reads it. */
25
+ export interface RenderedOutcome {
26
+ /** Sentences that say what happened, what to do next and what not to do. */
27
+ readonly text: string;
28
+ /** The outcome's fields, for a model or a harness that reads structured results. */
29
+ readonly payload: OutcomePayload;
30
+ /** True for every kind except `applied`: the provider's error flag, where the provider has one. */
31
+ readonly isError: boolean;
32
+ }
33
+ /**
34
+ * Renders a write outcome for the model: sentences that name what happened, what to do next and what not to do, the
35
+ * outcome's fields as a JSON payload, and whether the provider's error flag should be set. Put both the text and the
36
+ * payload in the tool result, because some SDKs show the model only one of them. It first checks the outcome as
37
+ * `writeOutcome()` does, so an outcome built by hand that breaks a rule throws a `SafetyError`, code
38
+ * `invalid_outcome`.
39
+ */
40
+ export declare function renderOutcome(outcome: WriteOutcome): RenderedOutcome;