@buildanagent/agent-safety 0.0.0-stage → 0.1.0-alpha.29

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 +514 -2
  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 +107 -3
@@ -0,0 +1,196 @@
1
+ import type { ApprovalSigner } from "./signer.js";
2
+ /**
3
+ * How a step behaves if the plan fails. `compensable`: a later step's failure can undo it. `pivot`: the point of no
4
+ * return, which can't be undone; once it runs, every later step must run. `retryable`: runs after the pivot and is
5
+ * safe to retry, because it is idempotent.
6
+ */
7
+ export type StepClass = "compensable" | "pivot" | "retryable";
8
+ /** One signed step of a plan: its tool and the hash of its exact input, with a summary for the approval card. */
9
+ export interface PlanStep {
10
+ /** The step's id, unique within the plan. */
11
+ readonly id: string;
12
+ /** The name of the tool the step calls. */
13
+ readonly tool: string;
14
+ /** How the step behaves if the plan fails. */
15
+ readonly class: StepClass;
16
+ /** `canonicalInputHash()` of the step's input. */
17
+ readonly inputHash: string;
18
+ /** The business key the step's write runs under, if it has one. */
19
+ readonly businessKey?: string;
20
+ /** One line that tells the approver what the step does. */
21
+ readonly summary: string;
22
+ }
23
+ /** A value the plan was computed from: where to read it, and under which key. */
24
+ export interface StateRead {
25
+ /** The system that holds the value, such as `orders`. */
26
+ readonly source: string;
27
+ /** The value's key in that system, such as `order:4417:refunded`. */
28
+ readonly key: string;
29
+ }
30
+ /** A value the plan read, with where it was read from. Use `null` for a value that was absent. */
31
+ export interface StateValue extends StateRead {
32
+ /** The value as read. It must have a canonical JSON form. */
33
+ readonly value: unknown;
34
+ }
35
+ /**
36
+ * A signed plan approval. `signature` covers `planId`, `expiresAt`, `stateHash`, `stateReads` and every field of
37
+ * every step, in order, under the key `keyId` names. Store it as JSON and pass it back to `verifyPlanBeforeStep()`
38
+ * before each step.
39
+ */
40
+ export interface PlanApproval {
41
+ /** The plan's own id, which the step ledger records claims under. */
42
+ readonly planId: string;
43
+ /** The steps, in the order they run. */
44
+ readonly steps: readonly PlanStep[];
45
+ /** `stateHash()` of the values the plan was computed from, as they were when the person approved it. */
46
+ readonly stateHash: string;
47
+ /** What to re-read before each step up to and including the pivot, in the order `stateHash` covers them. */
48
+ readonly stateReads: readonly StateRead[];
49
+ /** When the approval lapses for steps up to and including the pivot, as an ISO 8601 timestamp. */
50
+ readonly expiresAt: string;
51
+ /** The id of the key that made `signature`. */
52
+ readonly keyId: string;
53
+ /** The signature, as base64url. */
54
+ readonly signature: string;
55
+ }
56
+ /** What `lintPlan()` returns: `ok`, or every problem it found with the order of the steps. */
57
+ export type PlanLint = {
58
+ readonly ok: true;
59
+ } | {
60
+ readonly ok: false;
61
+ readonly problems: readonly string[];
62
+ };
63
+ /** A step as the host plans it, with its input in place of the input's hash. */
64
+ export interface PlanStepInit {
65
+ readonly id: string;
66
+ readonly tool: string;
67
+ readonly class: StepClass;
68
+ /** The step's exact input. `signPlan()` stores its `canonicalInputHash()`, never the input itself. */
69
+ readonly input: unknown;
70
+ readonly businessKey?: string;
71
+ readonly summary: string;
72
+ }
73
+ /** The plan a person approved: its steps, the state it was computed from, and how long the approval lasts. */
74
+ export interface PlanFields {
75
+ /** The steps, in the order they run. */
76
+ readonly steps: readonly PlanStepInit[];
77
+ /** Every value the steps' inputs were computed from, as read when the plan was made. */
78
+ readonly state: readonly StateValue[];
79
+ /** How long the approval lasts for steps up to and including the pivot, in milliseconds. */
80
+ readonly expiresInMs: number;
81
+ }
82
+ /** Where `signPlan()` takes its plan id and time from. Tests pass fixed ones. */
83
+ export interface SignPlanOptions {
84
+ /**
85
+ * Returns a fresh plan id. Defaults to `crypto.randomUUID()`. Each approval needs its own id: the ledger tracks
86
+ * progress by id, so a second approval with a repeated id is refused as `"replayed"` or `"out_of_order"`.
87
+ */
88
+ readonly generateId?: () => string;
89
+ /** Returns the current time. Defaults to `new Date()`. */
90
+ readonly now?: () => Date;
91
+ }
92
+ /** The step a host is about to run, as it has the step now, not as the approval records it. */
93
+ export interface PlanStepCall {
94
+ readonly stepId: string;
95
+ readonly tool: string;
96
+ readonly input: unknown;
97
+ }
98
+ /**
99
+ * Records which steps of each plan have passed verification. `claim()` must be atomic: it records step `stepIndex`
100
+ * of `planId` only when every earlier step is recorded and this one isn't, and answers `replayed` when this step is
101
+ * already recorded and `out_of_order` when an earlier one isn't. Two claims of one step that arrive together must
102
+ * get one `claimed` between them.
103
+ */
104
+ export interface PlanLedger {
105
+ /**
106
+ * Records step `stepIndex` of plan `planId` as passed. Resolves `"claimed"` when every earlier step is recorded and
107
+ * this one isn't, `"replayed"` when this one already is, and `"out_of_order"` when an earlier step is missing.
108
+ */
109
+ claim(planId: string, stepIndex: number): Promise<"claimed" | "replayed" | "out_of_order">;
110
+ }
111
+ /** The options of `verifyPlanBeforeStep()`. */
112
+ export interface VerifyPlanStepOptions {
113
+ /** A signer that holds the key the approval names. */
114
+ readonly signer: ApprovalSigner;
115
+ /** Where each step's claim is recorded, so no step passes twice and none passes before the steps ahead of it. */
116
+ readonly ledger: PlanLedger;
117
+ /**
118
+ * Re-reads the approval's `stateReads` now and returns their values in the same order. Return `null` for an absent
119
+ * value, as the plan recorded it: `undefined` has no canonical form, so it counts as a changed value.
120
+ */
121
+ readonly readState: (reads: readonly StateRead[]) => Promise<readonly unknown[]>;
122
+ /** Returns the current time. Defaults to `new Date()`. */
123
+ readonly now?: () => Date;
124
+ }
125
+ /**
126
+ * What `verifyPlanBeforeStep()` found. `ok`: run the step. `stale_approval`: a value the plan was computed from has
127
+ * changed. `expired`: the approval has lapsed. `tampered`: the record is malformed, its signature fails or names an
128
+ * unknown key, or the step's tool or input differs from the signed one. `step_not_in_plan`: no signed step has the
129
+ * id. `replayed`: the step already passed once. `out_of_order`: a step ahead of it hasn't passed yet.
130
+ */
131
+ export type PlanStepCheck = "ok" | "stale_approval" | "expired" | "tampered" | "step_not_in_plan" | "replayed" | "out_of_order";
132
+ /**
133
+ * Checks the order of a plan's steps: every compensable step comes before the pivot, a plan has at most one pivot,
134
+ * and every retryable step comes after it, so a plan without a pivot holds compensable steps only. It also needs at
135
+ * least one step and unique, non-empty step ids. Returns `ok: true`, or `ok: false` with every problem it found.
136
+ */
137
+ export declare function lintPlan(steps: readonly Pick<PlanStep, "id" | "class">[]): PlanLint;
138
+ /**
139
+ * Copies a state list once and checks it: every entry has a source and a key, and no read appears twice. `planCard()`
140
+ * shares it. Not exported from the package.
141
+ */
142
+ export declare function copyState(state: unknown): StateValue[];
143
+ /**
144
+ * Hashes the values a plan was computed from: the SHA-256 of the canonical JSON (RFC 8785) of each value with its
145
+ * source and key, in order, under a fixed tag, as 64 lowercase hex digits. Any changed value, read or order gives a
146
+ * different hash.
147
+ *
148
+ * Rejects with a `SafetyError`, code `invalid_plan`, for an entry without a source or key or a read listed twice, and
149
+ * code `invalid_input` for a value with no canonical JSON form, `undefined` included: write an absent value as `null`.
150
+ */
151
+ export declare function stateHash(state: readonly StateValue[]): Promise<string>;
152
+ /**
153
+ * Copies a plan's steps once, checks each field and the order, and hashes each input. Each input is read once, into
154
+ * canonical JSON text: the hash covers that text, and `inputs` holds it parsed back, so `planCard()`, which shares this
155
+ * with `signPlan()`, shows exactly the input each hash covers. Not exported from the package.
156
+ */
157
+ export declare function hashSteps(steps: unknown): Promise<{
158
+ inputs: unknown[];
159
+ signed: PlanStep[];
160
+ }>;
161
+ /**
162
+ * Signs a plan approval. Call it once the person has approved the plan's card, with the steps and state you built
163
+ * the card from and kept on your server, never with fields the client sends back. It checks the steps with
164
+ * `lintPlan()`, hashes each input with `canonicalInputHash()` and the state with `stateHash()`, signs the result with
165
+ * the signer's current key, and returns the record to store. The inputs and state values themselves aren't stored.
166
+ *
167
+ * Throws a `SafetyError`, code `invalid_plan`, for a blank or malformed field, steps out of order, a read listed
168
+ * twice or an `expiresInMs` that isn't a finite number of at least 1, and code `invalid_input` for an input or state value with no
169
+ * canonical JSON form.
170
+ */
171
+ export declare function signPlan(fields: PlanFields, signer: ApprovalSigner, options?: SignPlanOptions): Promise<PlanApproval>;
172
+ /**
173
+ * The plan approval as a trusted copy, or `undefined` when the record is malformed, its signature fails or names an
174
+ * unknown key, or its steps break `lintPlan()`. `runPlan()` reads a plan's steps from this copy, so a resume that
175
+ * finds every step already recorded still checks the approval it resumes under.
176
+ */
177
+ export declare function checkedPlanApproval(approval: unknown, signer: ApprovalSigner): Promise<PlanApproval | undefined>;
178
+ /**
179
+ * Checks a plan approval before one of its steps runs, failing closed. Run the step only when it resolves to `"ok"`.
180
+ *
181
+ * For every step, the record must be well formed and its signature must verify under a key the signer holds; the
182
+ * step's id must be in the plan; and its tool and input must match the signed tool and input hash. For steps up to
183
+ * and including the pivot, the approval must not have expired, and `readState` must return values whose
184
+ * `stateHash()` equals the signed one. Steps after the pivot skip the clock and the state, because the pivot itself
185
+ * changes the state and nothing after it may stop on a person or a clock. Last, the step's claim goes to the ledger,
186
+ * so no step passes twice and none passes before the steps ahead of it. A failed check claims nothing.
187
+ *
188
+ * The ledger records that a step passed this check, not that it ran. So `"ok"` for a step after the pivot means the
189
+ * pivot passed, not that its write succeeded. A second check of a step up to the pivot can also return
190
+ * `"stale_approval"` or `"expired"` before the ledger can answer `"replayed"`. Track which steps ran yourself, run the
191
+ * next step only after the last one succeeded, and never compensate once the pivot has run.
192
+ *
193
+ * It returns the first failure it finds. It never throws for a bad record or call, and a signer that throws counts as
194
+ * `"tampered"`. It rejects only when `readState` or the ledger rejects, and then the step must not run either.
195
+ */
196
+ export declare function verifyPlanBeforeStep(approval: unknown, call: PlanStepCall, options: VerifyPlanStepOptions): Promise<PlanStepCheck>;
@@ -0,0 +1,357 @@
1
+ /**
2
+ * The plan approval: one signed record that lets a person approve a whole multi-step plan once, before its first
3
+ * step, when one step can't be undone. The record binds every step's tool and input hash, the order of the steps and
4
+ * a hash of the state the plan was computed from, under a payload of its own whose fixed tag differs from the pending
5
+ * request's, so a plan signature never verifies as a tool approval and a tool approval never verifies as a plan.
6
+ *
7
+ * The rules for which step checks what are our synthesis of the sagas report in docs/research/reversible-actions, not
8
+ * a vendor design: steps up to and including the pivot check the clock and re-read the state, and steps after it
9
+ * check only that they are the signed step, because the pivot itself changes the state and nothing after it may wait
10
+ * on a person or a clock.
11
+ */
12
+ import { constantTimeEqual } from "./bytes.js";
13
+ import { SafetyError } from "./errors.js";
14
+ import { canonicalInputHash, canonicalJson, canonicalTextHash } from "./hash.js";
15
+ // Ties a signature to this record and its layout. The pending request's tag is "buildanagent.pending.v1", so the two
16
+ // payloads differ in their first element and no byte string is both.
17
+ const PLAN_TAG = "buildanagent.plan-approval.v1";
18
+ // Keeps the state hash apart from any tool input hash, which shares canonicalInputHash().
19
+ const STATE_TAG = "buildanagent.plan-state.v1";
20
+ const CLASSES = ["compensable", "pivot", "retryable"];
21
+ const HASH = /^[0-9a-f]{64}$/;
22
+ const ENCODER = new TextEncoder();
23
+ function isText(value) {
24
+ return typeof value === "string" && value !== "" && value.isWellFormed();
25
+ }
26
+ function isRecord(value) {
27
+ return typeof value === "object" && value !== null;
28
+ }
29
+ function invalidPlan(message) {
30
+ return new SafetyError("invalid_plan", message);
31
+ }
32
+ // Names a class without converting it to a string, which throws for an object with no prototype.
33
+ function describeClass(stepClass) {
34
+ if (stepClass === undefined)
35
+ return "no class";
36
+ return typeof stepClass === "string"
37
+ ? `the class ${JSON.stringify(stepClass)}`
38
+ : `a class that is a ${typeof stepClass}`;
39
+ }
40
+ function orderProblem(id, stepClass, pivot, hasPivot) {
41
+ if (typeof stepClass !== "string" || !CLASSES.includes(stepClass))
42
+ return `step ${id} has ${describeClass(stepClass)}`;
43
+ if (stepClass === "compensable" && pivot !== undefined)
44
+ return `step ${id} is compensable but comes after the pivot`;
45
+ if (stepClass === "retryable" && pivot === undefined) {
46
+ return hasPivot
47
+ ? `step ${id} is retryable but comes before the pivot`
48
+ : `step ${id} is retryable but the plan has no pivot`;
49
+ }
50
+ return undefined;
51
+ }
52
+ function checkId(id, name, seen) {
53
+ if (!isText(id))
54
+ return `step ${name} needs a non-empty, well-formed id`;
55
+ if (seen.has(id))
56
+ return `two steps share the id ${name}`;
57
+ seen.add(id);
58
+ return undefined;
59
+ }
60
+ /**
61
+ * Checks the order of a plan's steps: every compensable step comes before the pivot, a plan has at most one pivot,
62
+ * and every retryable step comes after it, so a plan without a pivot holds compensable steps only. It also needs at
63
+ * least one step and unique, non-empty step ids. Returns `ok: true`, or `ok: false` with every problem it found.
64
+ */
65
+ export function lintPlan(steps) {
66
+ if (!Array.isArray(steps) || steps.length === 0)
67
+ return { ok: false, problems: ["a plan needs at least one step"] };
68
+ // Each step's id and class are read once, so a getter can't answer one check differently from the next.
69
+ const list = Array.from(steps, (step) => {
70
+ const { id, class: stepClass } = isRecord(step) ? step : {};
71
+ return { id, stepClass };
72
+ });
73
+ const hasPivot = list.some(({ stepClass }) => stepClass === "pivot");
74
+ const problems = [];
75
+ const seen = new Set();
76
+ let pivot;
77
+ for (const [index, { id, stepClass }] of list.entries()) {
78
+ const name = isText(id) ? JSON.stringify(id) : `${index + 1}`;
79
+ const idProblem = checkId(id, name, seen);
80
+ if (idProblem !== undefined)
81
+ problems.push(idProblem);
82
+ const problem = orderProblem(name, stepClass, pivot, hasPivot);
83
+ if (problem !== undefined)
84
+ problems.push(problem);
85
+ if (stepClass === "pivot") {
86
+ if (pivot !== undefined)
87
+ problems.push(`the plan has two pivots: ${pivot} and ${name}`);
88
+ pivot ??= name;
89
+ }
90
+ }
91
+ return problems.length === 0 ? { ok: true } : { ok: false, problems };
92
+ }
93
+ function copyStateValue(value, index) {
94
+ const { source, key, value: read } = isRecord(value) ? value : {};
95
+ if (!isText(source) || !isText(key)) {
96
+ throw invalidPlan(`state value ${index + 1} needs a non-empty, well-formed source and key`);
97
+ }
98
+ return { source, key, value: read };
99
+ }
100
+ /**
101
+ * Copies a state list once and checks it: every entry has a source and a key, and no read appears twice. `planCard()`
102
+ * shares it. Not exported from the package.
103
+ */
104
+ export function copyState(state) {
105
+ if (!Array.isArray(state))
106
+ throw invalidPlan("a plan's state must be an array of { source, key, value }");
107
+ const copies = Array.from(state, copyStateValue);
108
+ const seen = new Set();
109
+ for (const { source, key } of copies) {
110
+ const id = JSON.stringify([source, key]);
111
+ if (seen.has(id))
112
+ throw invalidPlan(`the state reads ${source} ${JSON.stringify(key)} twice`);
113
+ seen.add(id);
114
+ }
115
+ return copies;
116
+ }
117
+ /**
118
+ * Hashes the values a plan was computed from: the SHA-256 of the canonical JSON (RFC 8785) of each value with its
119
+ * source and key, in order, under a fixed tag, as 64 lowercase hex digits. Any changed value, read or order gives a
120
+ * different hash.
121
+ *
122
+ * Rejects with a `SafetyError`, code `invalid_plan`, for an entry without a source or key or a read listed twice, and
123
+ * code `invalid_input` for a value with no canonical JSON form, `undefined` included: write an absent value as `null`.
124
+ */
125
+ export async function stateHash(state) {
126
+ const copies = copyState(state);
127
+ return canonicalInputHash([STATE_TAG, copies.map(({ source, key, value }) => [source, key, value])]);
128
+ }
129
+ /** The bytes a plan signature covers: a JSON array of fixed shape whose every string is well formed. */
130
+ function planPayload(signed) {
131
+ const reads = signed.stateReads.map(({ source, key }) => [source, key]);
132
+ const steps = signed.steps.map((s) => [s.id, s.tool, s.class, s.inputHash, s.businessKey ?? null, s.summary]);
133
+ return ENCODER.encode(JSON.stringify([PLAN_TAG, signed.planId, signed.expiresAt, signed.stateHash, reads, steps]));
134
+ }
135
+ function copyStepInit(step, index) {
136
+ const { id, tool, class: stepClass, input, businessKey, summary } = isRecord(step) ? step : {};
137
+ const bad = (what) => invalidPlan(`step ${index + 1}'s ${what}`);
138
+ if (!isText(id) || !isText(tool) || !isText(summary))
139
+ throw bad("id, tool and summary must be non-empty strings");
140
+ if (businessKey !== undefined && !isText(businessKey))
141
+ throw bad("businessKey must be a non-empty string when set");
142
+ if (!CLASSES.includes(stepClass))
143
+ throw bad(`class must be "compensable", "pivot" or "retryable"`);
144
+ const copy = { id, tool, class: stepClass, input, summary };
145
+ return businessKey === undefined ? copy : { ...copy, businessKey };
146
+ }
147
+ /**
148
+ * Copies a plan's steps once, checks each field and the order, and hashes each input. Each input is read once, into
149
+ * canonical JSON text: the hash covers that text, and `inputs` holds it parsed back, so `planCard()`, which shares this
150
+ * with `signPlan()`, shows exactly the input each hash covers. Not exported from the package.
151
+ */
152
+ export async function hashSteps(steps) {
153
+ if (!Array.isArray(steps))
154
+ throw invalidPlan("a plan's steps must be an array");
155
+ const inits = Array.from(steps, copyStepInit);
156
+ const lint = lintPlan(inits);
157
+ if (!lint.ok)
158
+ throw invalidPlan(`the plan's steps fail lintPlan(): ${lint.problems.join("; ")}`);
159
+ const texts = inits.map(({ input }) => canonicalJson(input));
160
+ const signed = await Promise.all(inits.map(async ({ input: _input, ...step }, index) => ({
161
+ ...step,
162
+ inputHash: await canonicalTextHash(texts[index]),
163
+ })));
164
+ return { inputs: texts.map((text) => JSON.parse(text)), signed };
165
+ }
166
+ function expiryOf(now, expiresInMs) {
167
+ if (typeof expiresInMs !== "number" || !Number.isFinite(expiresInMs) || expiresInMs < 1) {
168
+ // Dates hold whole milliseconds, so anything under 1 would sign an approval that is expired when issued.
169
+ throw invalidPlan("expiresInMs must be a finite number of milliseconds, at least 1");
170
+ }
171
+ const at = new Date(now.getTime() + expiresInMs);
172
+ if (Number.isNaN(at.getTime()))
173
+ throw invalidPlan("now() plus expiresInMs must be a valid time");
174
+ return at.toISOString();
175
+ }
176
+ /**
177
+ * Signs a plan approval. Call it once the person has approved the plan's card, with the steps and state you built
178
+ * the card from and kept on your server, never with fields the client sends back. It checks the steps with
179
+ * `lintPlan()`, hashes each input with `canonicalInputHash()` and the state with `stateHash()`, signs the result with
180
+ * the signer's current key, and returns the record to store. The inputs and state values themselves aren't stored.
181
+ *
182
+ * Throws a `SafetyError`, code `invalid_plan`, for a blank or malformed field, steps out of order, a read listed
183
+ * twice or an `expiresInMs` that isn't a finite number of at least 1, and code `invalid_input` for an input or state value with no
184
+ * canonical JSON form.
185
+ */
186
+ export async function signPlan(fields, signer, options = {}) {
187
+ const planId = (options.generateId ?? (() => crypto.randomUUID()))();
188
+ if (!isText(planId))
189
+ throw invalidPlan("a plan's id must be a non-empty, well-formed string");
190
+ const { steps, state, expiresInMs } = isRecord(fields) ? fields : {};
191
+ // Copy the steps and the state before the first await, as `planCard()` does, so a change made while the hashes are
192
+ // pending can't give the signature a state the person never saw on the card.
193
+ const hashing = hashSteps(steps);
194
+ const reads = copyState(state);
195
+ const { signed: signedSteps } = await hashing;
196
+ const signed = {
197
+ planId,
198
+ steps: signedSteps,
199
+ stateHash: await stateHash(reads),
200
+ stateReads: reads.map(({ source, key }) => ({ source, key })),
201
+ expiresAt: expiryOf((options.now ?? (() => new Date()))(), expiresInMs),
202
+ };
203
+ const signature = await signer.sign(planPayload(signed));
204
+ return { ...signed, keyId: signer.keyId, signature };
205
+ }
206
+ function isTimestamp(value) {
207
+ if (typeof value !== "string")
208
+ return false;
209
+ const time = Date.parse(value);
210
+ return Number.isFinite(time) && new Date(time).toISOString() === value;
211
+ }
212
+ function copySignedStep(step) {
213
+ const { id, tool, class: stepClass, inputHash, businessKey, summary } = isRecord(step) ? step : {};
214
+ if (![id, tool, summary].every(isText) || !CLASSES.includes(stepClass))
215
+ return undefined;
216
+ if (typeof inputHash !== "string" || !HASH.test(inputHash))
217
+ return undefined;
218
+ if (businessKey !== undefined && !isText(businessKey))
219
+ return undefined;
220
+ const copy = { id, tool, class: stepClass, inputHash, summary };
221
+ return businessKey === undefined ? copy : { ...copy, businessKey };
222
+ }
223
+ function copyRead(read) {
224
+ const { source, key } = isRecord(read) ? read : {};
225
+ return isText(source) && isText(key) ? { source, key } : undefined;
226
+ }
227
+ function copyList(value, copy) {
228
+ if (!Array.isArray(value))
229
+ return undefined;
230
+ const items = Array.from(value, copy);
231
+ return items.every((item) => item !== undefined) ? items : undefined;
232
+ }
233
+ /**
234
+ * Reads each field of an untrusted record once into a plain copy, or returns `undefined` if any field is malformed.
235
+ * Every later check reads the copy, so a getter or a Proxy can't show the signature one value and the checks another.
236
+ */
237
+ function copyApproval(value) {
238
+ if (!isRecord(value))
239
+ return undefined;
240
+ const { planId, steps, stateHash: hash, stateReads, expiresAt, keyId, signature } = value;
241
+ if (![planId, keyId, signature].every(isText) || typeof hash !== "string" || !HASH.test(hash))
242
+ return undefined;
243
+ if (!isTimestamp(expiresAt))
244
+ return undefined;
245
+ const stepCopies = copyList(steps, copySignedStep);
246
+ const readCopies = copyList(stateReads, copyRead);
247
+ if (stepCopies === undefined || readCopies === undefined)
248
+ return undefined;
249
+ return {
250
+ planId: planId,
251
+ steps: stepCopies,
252
+ stateHash: hash,
253
+ stateReads: readCopies,
254
+ expiresAt,
255
+ keyId: keyId,
256
+ signature: signature,
257
+ };
258
+ }
259
+ function hashesEqual(a, b) {
260
+ return constantTimeEqual(ENCODER.encode(a), ENCODER.encode(b));
261
+ }
262
+ async function inputMatches(inputHash, input) {
263
+ try {
264
+ return hashesEqual(await canonicalInputHash(input), inputHash);
265
+ }
266
+ catch {
267
+ // An input with no canonical form can't be the one that was signed, which had one.
268
+ return false;
269
+ }
270
+ }
271
+ async function stateMatches(approval, values) {
272
+ if (!Array.isArray(values) || values.length !== approval.stateReads.length)
273
+ return false;
274
+ const read = Array.from(values);
275
+ try {
276
+ const fresh = await stateHash(approval.stateReads.map((r, index) => ({ ...r, value: read[index] })));
277
+ return hashesEqual(fresh, approval.stateHash);
278
+ }
279
+ catch {
280
+ // A value with no canonical form can't equal one that had one, so the state counts as changed.
281
+ return false;
282
+ }
283
+ }
284
+ async function checkFreshness(approval, options) {
285
+ const now = (options.now ?? (() => new Date()))().getTime();
286
+ // Written as "not before", so an invalid clock reading (NaN) counts as expired.
287
+ if (!(now < Date.parse(approval.expiresAt)))
288
+ return "expired";
289
+ const values = await options.readState(approval.stateReads.map(({ source, key }) => ({ source, key })));
290
+ return (await stateMatches(approval, values)) ? "ok" : "stale_approval";
291
+ }
292
+ async function signatureHolds(signer, record) {
293
+ try {
294
+ return (await signer.verify(record.keyId, planPayload(record), record.signature)) === true;
295
+ }
296
+ catch {
297
+ return false;
298
+ }
299
+ }
300
+ /**
301
+ * The plan approval as a trusted copy, or `undefined` when the record is malformed, its signature fails or names an
302
+ * unknown key, or its steps break `lintPlan()`. `runPlan()` reads a plan's steps from this copy, so a resume that
303
+ * finds every step already recorded still checks the approval it resumes under.
304
+ */
305
+ export async function checkedPlanApproval(approval, signer) {
306
+ const record = copyApproval(approval);
307
+ if (record === undefined || !(await signatureHolds(signer, record)))
308
+ return undefined;
309
+ return lintPlan(record.steps).ok ? record : undefined;
310
+ }
311
+ /**
312
+ * Checks a plan approval before one of its steps runs, failing closed. Run the step only when it resolves to `"ok"`.
313
+ *
314
+ * For every step, the record must be well formed and its signature must verify under a key the signer holds; the
315
+ * step's id must be in the plan; and its tool and input must match the signed tool and input hash. For steps up to
316
+ * and including the pivot, the approval must not have expired, and `readState` must return values whose
317
+ * `stateHash()` equals the signed one. Steps after the pivot skip the clock and the state, because the pivot itself
318
+ * changes the state and nothing after it may stop on a person or a clock. Last, the step's claim goes to the ledger,
319
+ * so no step passes twice and none passes before the steps ahead of it. A failed check claims nothing.
320
+ *
321
+ * The ledger records that a step passed this check, not that it ran. So `"ok"` for a step after the pivot means the
322
+ * pivot passed, not that its write succeeded. A second check of a step up to the pivot can also return
323
+ * `"stale_approval"` or `"expired"` before the ledger can answer `"replayed"`. Track which steps ran yourself, run the
324
+ * next step only after the last one succeeded, and never compensate once the pivot has run.
325
+ *
326
+ * It returns the first failure it finds. It never throws for a bad record or call, and a signer that throws counts as
327
+ * `"tampered"`. It rejects only when `readState` or the ledger rejects, and then the step must not run either.
328
+ */
329
+ export async function verifyPlanBeforeStep(approval, call, options) {
330
+ const record = copyApproval(approval);
331
+ if (record === undefined)
332
+ return "tampered";
333
+ // The signature comes first: until it verifies, no other field of the stored record is trusted.
334
+ // A signer that throws (a malformed signature, a key-store error) refuses the step instead of rejecting the call.
335
+ if (!(await signatureHolds(options.signer, record)))
336
+ return "tampered";
337
+ if (!lintPlan(record.steps).ok)
338
+ return "tampered";
339
+ const { stepId, tool, input } = isRecord(call) ? call : {};
340
+ const index = record.steps.findIndex((step) => step.id === stepId);
341
+ const step = record.steps[index];
342
+ if (step === undefined)
343
+ return "step_not_in_plan";
344
+ if (tool !== step.tool || !(await inputMatches(step.inputHash, input)))
345
+ return "tampered";
346
+ if (step.class !== "retryable") {
347
+ const fresh = await checkFreshness(record, options);
348
+ if (fresh !== "ok")
349
+ return fresh;
350
+ }
351
+ const claim = await options.ledger.claim(record.planId, index);
352
+ if (claim === "claimed")
353
+ return "ok";
354
+ // Anything else a ledger answers, even a value outside its type, counts as a refusal.
355
+ return claim === "replayed" ? "replayed" : "out_of_order";
356
+ }
357
+ //# sourceMappingURL=plan-approval.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plan-approval.js","sourceRoot":"","sources":["../src/plan-approval.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,OAAO,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAC/C,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAoJjF,qHAAqH;AACrH,qEAAqE;AACrE,MAAM,QAAQ,GAAG,+BAA+B,CAAC;AACjD,0FAA0F;AAC1F,MAAM,SAAS,GAAG,4BAA4B,CAAC;AAC/C,MAAM,OAAO,GAAsB,CAAC,aAAa,EAAE,OAAO,EAAE,WAAW,CAAC,CAAC;AACzE,MAAM,IAAI,GAAG,gBAAgB,CAAC;AAC9B,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAElC,SAAS,MAAM,CAAC,KAAc;IAC5B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,EAAE,IAAI,KAAK,CAAC,YAAY,EAAE,CAAC;AAC3E,CAAC;AAED,SAAS,QAAQ,CAAC,KAAc;IAC9B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAA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B,CAAC;IAClD,IAAI,IAAI,KAAK,IAAI,CAAC,IAAI,IAAI,CAAC,CAAC,MAAM,YAAY,CAAC,IAAI,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;QAAE,OAAO,UAAU,CAAC;IAC1F,IAAI,IAAI,CAAC,KAAK,KAAK,WAAW,EAAE,CAAC;QAC/B,MAAM,KAAK,GAAG,MAAM,cAAc,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QACpD,IAAI,KAAK,KAAK,IAAI;YAAE,OAAO,KAAK,CAAC;IACnC,CAAC;IACD,MAAM,KAAK,GAAG,MAAM,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IAC/D,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO,IAAI,CAAC;IACrC,sFAAsF;IACtF,OAAO,KAAK,KAAK,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,cAAc,CAAC;AAC5D,CAAC","sourcesContent":["/**\n * The plan approval: one signed record that lets a person approve a whole multi-step plan once, before its first\n * step, when one step can't be undone. The record binds every step's tool and input hash, the order of the steps and\n * a hash of the state the plan was computed from, under a payload of its own whose fixed tag differs from the pending\n * request's, so a plan signature never verifies as a tool approval and a tool approval never verifies as a plan.\n *\n * The rules for which step checks what are our synthesis of the sagas report in docs/research/reversible-actions, not\n * a vendor design: steps up to and including the pivot check the clock and re-read the state, and steps after it\n * check only that they are the signed step, because the pivot itself changes the state and nothing after it may wait\n * on a person or a clock.\n */\nimport { constantTimeEqual } from \"./bytes.js\";\nimport { SafetyError } from \"./errors.js\";\nimport { canonicalInputHash, canonicalJson, canonicalTextHash } from \"./hash.js\";\nimport type { ApprovalSigner } from \"./signer.js\";\n\n/**\n * How a step behaves if the plan fails. `compensable`: a later step's failure can undo it. `pivot`: the point of no\n * return, which can't be undone; once it runs, every later step must run. `retryable`: runs after the pivot and is\n * safe to retry, because it is idempotent.\n */\nexport type StepClass = \"compensable\" | \"pivot\" | \"retryable\";\n\n/** One signed step of a plan: its tool and the hash of its exact input, with a summary for the approval card. */\nexport interface PlanStep {\n /** The step's id, unique within the plan. */\n readonly id: string;\n /** The name of the tool the step calls. */\n readonly tool: string;\n /** How the step behaves if the plan fails. */\n readonly class: StepClass;\n /** `canonicalInputHash()` of the step's input. */\n readonly inputHash: string;\n /** The business key the step's write runs under, if it has one. */\n readonly businessKey?: string;\n /** One line that tells the approver what the step does. */\n readonly summary: string;\n}\n\n/** A value the plan was computed from: where to read it, and under which key. */\nexport interface StateRead {\n /** The system that holds the value, such as `orders`. */\n readonly source: string;\n /** The value's key in that system, such as `order:4417:refunded`. */\n readonly key: string;\n}\n\n/** A value the plan read, with where it was read from. Use `null` for a value that was absent. */\nexport interface StateValue extends StateRead {\n /** The value as read. It must have a canonical JSON form. */\n readonly value: unknown;\n}\n\n/**\n * A signed plan approval. `signature` covers `planId`, `expiresAt`, `stateHash`, `stateReads` and every field of\n * every step, in order, under the key `keyId` names. Store it as JSON and pass it back to `verifyPlanBeforeStep()`\n * before each step.\n */\nexport interface PlanApproval {\n /** The plan's own id, which the step ledger records claims under. */\n readonly planId: string;\n /** The steps, in the order they run. */\n readonly steps: readonly PlanStep[];\n /** `stateHash()` of the values the plan was computed from, as they were when the person approved it. */\n readonly stateHash: string;\n /** What to re-read before each step up to and including the pivot, in the order `stateHash` covers them. */\n readonly stateReads: readonly StateRead[];\n /** When the approval lapses for steps up to and including the pivot, as an ISO 8601 timestamp. */\n readonly expiresAt: string;\n /** The id of the key that made `signature`. */\n readonly keyId: string;\n /** The signature, as base64url. */\n readonly signature: string;\n}\n\n/** What `lintPlan()` returns: `ok`, or every problem it found with the order of the steps. */\nexport type PlanLint = { readonly ok: true } | { readonly ok: false; readonly problems: readonly string[] };\n\n/** A step as the host plans it, with its input in place of the input's hash. */\nexport interface PlanStepInit {\n readonly id: string;\n readonly tool: string;\n readonly class: StepClass;\n /** The step's exact input. `signPlan()` stores its `canonicalInputHash()`, never the input itself. */\n readonly input: unknown;\n readonly businessKey?: string;\n readonly summary: string;\n}\n\n/** The plan a person approved: its steps, the state it was computed from, and how long the approval lasts. */\nexport interface PlanFields {\n /** The steps, in the order they run. */\n readonly steps: readonly PlanStepInit[];\n /** Every value the steps' inputs were computed from, as read when the plan was made. */\n readonly state: readonly StateValue[];\n /** How long the approval lasts for steps up to and including the pivot, in milliseconds. */\n readonly expiresInMs: number;\n}\n\n/** Where `signPlan()` takes its plan id and time from. Tests pass fixed ones. */\nexport interface SignPlanOptions {\n /**\n * Returns a fresh plan id. Defaults to `crypto.randomUUID()`. Each approval needs its own id: the ledger tracks\n * progress by id, so a second approval with a repeated id is refused as `\"replayed\"` or `\"out_of_order\"`.\n */\n readonly generateId?: () => string;\n /** Returns the current time. Defaults to `new Date()`. */\n readonly now?: () => Date;\n}\n\n/** The step a host is about to run, as it has the step now, not as the approval records it. */\nexport interface PlanStepCall {\n readonly stepId: string;\n readonly tool: string;\n readonly input: unknown;\n}\n\n/**\n * Records which steps of each plan have passed verification. `claim()` must be atomic: it records step `stepIndex`\n * of `planId` only when every earlier step is recorded and this one isn't, and answers `replayed` when this step is\n * already recorded and `out_of_order` when an earlier one isn't. Two claims of one step that arrive together must\n * get one `claimed` between them.\n */\nexport interface PlanLedger {\n /**\n * Records step `stepIndex` of plan `planId` as passed. Resolves `\"claimed\"` when every earlier step is recorded and\n * this one isn't, `\"replayed\"` when this one already is, and `\"out_of_order\"` when an earlier step is missing.\n */\n claim(planId: string, stepIndex: number): Promise<\"claimed\" | \"replayed\" | \"out_of_order\">;\n}\n\n/** The options of `verifyPlanBeforeStep()`. */\nexport interface VerifyPlanStepOptions {\n /** A signer that holds the key the approval names. */\n readonly signer: ApprovalSigner;\n /** Where each step's claim is recorded, so no step passes twice and none passes before the steps ahead of it. */\n readonly ledger: PlanLedger;\n /**\n * Re-reads the approval's `stateReads` now and returns their values in the same order. Return `null` for an absent\n * value, as the plan recorded it: `undefined` has no canonical form, so it counts as a changed value.\n */\n readonly readState: (reads: readonly StateRead[]) => Promise<readonly unknown[]>;\n /** Returns the current time. Defaults to `new Date()`. */\n readonly now?: () => Date;\n}\n\n/**\n * What `verifyPlanBeforeStep()` found. `ok`: run the step. `stale_approval`: a value the plan was computed from has\n * changed. `expired`: the approval has lapsed. `tampered`: the record is malformed, its signature fails or names an\n * unknown key, or the step's tool or input differs from the signed one. `step_not_in_plan`: no signed step has the\n * id. `replayed`: the step already passed once. `out_of_order`: a step ahead of it hasn't passed yet.\n */\nexport type PlanStepCheck =\n | \"ok\"\n | \"stale_approval\"\n | \"expired\"\n | \"tampered\"\n | \"step_not_in_plan\"\n | \"replayed\"\n | \"out_of_order\";\n\n// Ties a signature to this record and its layout. The pending request's tag is \"buildanagent.pending.v1\", so the two\n// payloads differ in their first element and no byte string is both.\nconst PLAN_TAG = \"buildanagent.plan-approval.v1\";\n// Keeps the state hash apart from any tool input hash, which shares canonicalInputHash().\nconst STATE_TAG = \"buildanagent.plan-state.v1\";\nconst CLASSES: readonly string[] = [\"compensable\", \"pivot\", \"retryable\"];\nconst HASH = /^[0-9a-f]{64}$/;\nconst ENCODER = new TextEncoder();\n\nfunction isText(value: unknown): value is string {\n return typeof value === \"string\" && value !== \"\" && value.isWellFormed();\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\nfunction invalidPlan(message: string): SafetyError {\n return new SafetyError(\"invalid_plan\", message);\n}\n\n// Names a class without converting it to a string, which throws for an object with no prototype.\nfunction describeClass(stepClass: unknown): string {\n if (stepClass === undefined) return \"no class\";\n return typeof stepClass === \"string\"\n ? `the class ${JSON.stringify(stepClass)}`\n : `a class that is a ${typeof stepClass}`;\n}\n\nfunction orderProblem(\n id: string,\n stepClass: unknown,\n pivot: string | undefined,\n hasPivot: boolean,\n): string | undefined {\n if (typeof stepClass !== \"string\" || !CLASSES.includes(stepClass))\n return `step ${id} has ${describeClass(stepClass)}`;\n if (stepClass === \"compensable\" && pivot !== undefined) return `step ${id} is compensable but comes after the pivot`;\n if (stepClass === \"retryable\" && pivot === undefined) {\n return hasPivot\n ? `step ${id} is retryable but comes before the pivot`\n : `step ${id} is retryable but the plan has no pivot`;\n }\n return undefined;\n}\n\nfunction checkId(id: unknown, name: string, seen: Set<string>): string | undefined {\n if (!isText(id)) return `step ${name} needs a non-empty, well-formed id`;\n if (seen.has(id)) return `two steps share the id ${name}`;\n seen.add(id);\n return undefined;\n}\n\n/**\n * Checks the order of a plan's steps: every compensable step comes before the pivot, a plan has at most one pivot,\n * and every retryable step comes after it, so a plan without a pivot holds compensable steps only. It also needs at\n * least one step and unique, non-empty step ids. Returns `ok: true`, or `ok: false` with every problem it found.\n */\nexport function lintPlan(steps: readonly Pick<PlanStep, \"id\" | \"class\">[]): PlanLint {\n if (!Array.isArray(steps) || steps.length === 0) return { ok: false, problems: [\"a plan needs at least one step\"] };\n // Each step's id and class are read once, so a getter can't answer one check differently from the next.\n const list = Array.from(steps as readonly unknown[], (step) => {\n const { id, class: stepClass } = isRecord(step) ? step : {};\n return { id, stepClass };\n });\n const hasPivot = list.some(({ stepClass }) => stepClass === \"pivot\");\n const problems: string[] = [];\n const seen = new Set<string>();\n let pivot: string | undefined;\n for (const [index, { id, stepClass }] of list.entries()) {\n const name = isText(id) ? JSON.stringify(id) : `${index + 1}`;\n const idProblem = checkId(id, name, seen);\n if (idProblem !== undefined) problems.push(idProblem);\n const problem = orderProblem(name, stepClass, pivot, hasPivot);\n if (problem !== undefined) problems.push(problem);\n if (stepClass === \"pivot\") {\n if (pivot !== undefined) problems.push(`the plan has two pivots: ${pivot} and ${name}`);\n pivot ??= name;\n }\n }\n return problems.length === 0 ? { ok: true } : { ok: false, problems };\n}\n\nfunction copyStateValue(value: unknown, index: number): StateValue {\n const { source, key, value: read } = isRecord(value) ? value : {};\n if (!isText(source) || !isText(key)) {\n throw invalidPlan(`state value ${index + 1} needs a non-empty, well-formed source and key`);\n }\n return { source, key, value: read };\n}\n\n/**\n * Copies a state list once and checks it: every entry has a source and a key, and no read appears twice. `planCard()`\n * shares it. Not exported from the package.\n */\nexport function copyState(state: unknown): StateValue[] {\n if (!Array.isArray(state)) throw invalidPlan(\"a plan's state must be an array of { source, key, value }\");\n const copies = Array.from(state as readonly unknown[], copyStateValue);\n const seen = new Set<string>();\n for (const { source, key } of copies) {\n const id = JSON.stringify([source, key]);\n if (seen.has(id)) throw invalidPlan(`the state reads ${source} ${JSON.stringify(key)} twice`);\n seen.add(id);\n }\n return copies;\n}\n\n/**\n * Hashes the values a plan was computed from: the SHA-256 of the canonical JSON (RFC 8785) of each value with its\n * source and key, in order, under a fixed tag, as 64 lowercase hex digits. Any changed value, read or order gives a\n * different hash.\n *\n * Rejects with a `SafetyError`, code `invalid_plan`, for an entry without a source or key or a read listed twice, and\n * code `invalid_input` for a value with no canonical JSON form, `undefined` included: write an absent value as `null`.\n */\nexport async function stateHash(state: readonly StateValue[]): Promise<string> {\n const copies = copyState(state);\n return canonicalInputHash([STATE_TAG, copies.map(({ source, key, value }) => [source, key, value])]);\n}\n\n/** The bytes a plan signature covers: a JSON array of fixed shape whose every string is well formed. */\nfunction planPayload(signed: Omit<PlanApproval, \"keyId\" | \"signature\">): Uint8Array {\n const reads = signed.stateReads.map(({ source, key }) => [source, key]);\n const steps = signed.steps.map((s) => [s.id, s.tool, s.class, s.inputHash, s.businessKey ?? null, s.summary]);\n return ENCODER.encode(JSON.stringify([PLAN_TAG, signed.planId, signed.expiresAt, signed.stateHash, reads, steps]));\n}\n\nfunction copyStepInit(step: unknown, index: number): PlanStepInit {\n const { id, tool, class: stepClass, input, businessKey, summary } = isRecord(step) ? step : {};\n const bad = (what: string) => invalidPlan(`step ${index + 1}'s ${what}`);\n if (!isText(id) || !isText(tool) || !isText(summary)) throw bad(\"id, tool and summary must be non-empty strings\");\n if (businessKey !== undefined && !isText(businessKey)) throw bad(\"businessKey must be a non-empty string when set\");\n if (!CLASSES.includes(stepClass as string)) throw bad(`class must be \"compensable\", \"pivot\" or \"retryable\"`);\n const copy = { id, tool, class: stepClass as StepClass, input, summary };\n return businessKey === undefined ? copy : { ...copy, businessKey };\n}\n\n/**\n * Copies a plan's steps once, checks each field and the order, and hashes each input. Each input is read once, into\n * canonical JSON text: the hash covers that text, and `inputs` holds it parsed back, so `planCard()`, which shares this\n * with `signPlan()`, shows exactly the input each hash covers. Not exported from the package.\n */\nexport async function hashSteps(steps: unknown): Promise<{ inputs: unknown[]; signed: PlanStep[] }> {\n if (!Array.isArray(steps)) throw invalidPlan(\"a plan's steps must be an array\");\n const inits = Array.from(steps as readonly unknown[], copyStepInit);\n const lint = lintPlan(inits);\n if (!lint.ok) throw invalidPlan(`the plan's steps fail lintPlan(): ${lint.problems.join(\"; \")}`);\n const texts = inits.map(({ input }) => canonicalJson(input));\n const signed = await Promise.all(\n inits.map(\n async ({ input: _input, ...step }, index): Promise<PlanStep> => ({\n ...step,\n inputHash: await canonicalTextHash(texts[index] as string),\n }),\n ),\n );\n return { inputs: texts.map((text) => JSON.parse(text) as unknown), signed };\n}\n\nfunction expiryOf(now: Date, expiresInMs: unknown): string {\n if (typeof expiresInMs !== \"number\" || !Number.isFinite(expiresInMs) || expiresInMs < 1) {\n // Dates hold whole milliseconds, so anything under 1 would sign an approval that is expired when issued.\n throw invalidPlan(\"expiresInMs must be a finite number of milliseconds, at least 1\");\n }\n const at = new Date(now.getTime() + expiresInMs);\n if (Number.isNaN(at.getTime())) throw invalidPlan(\"now() plus expiresInMs must be a valid time\");\n return at.toISOString();\n}\n\n/**\n * Signs a plan approval. Call it once the person has approved the plan's card, with the steps and state you built\n * the card from and kept on your server, never with fields the client sends back. It checks the steps with\n * `lintPlan()`, hashes each input with `canonicalInputHash()` and the state with `stateHash()`, signs the result with\n * the signer's current key, and returns the record to store. The inputs and state values themselves aren't stored.\n *\n * Throws a `SafetyError`, code `invalid_plan`, for a blank or malformed field, steps out of order, a read listed\n * twice or an `expiresInMs` that isn't a finite number of at least 1, and code `invalid_input` for an input or state value with no\n * canonical JSON form.\n */\nexport async function signPlan(\n fields: PlanFields,\n signer: ApprovalSigner,\n options: SignPlanOptions = {},\n): Promise<PlanApproval> {\n const planId = (options.generateId ?? (() => crypto.randomUUID()))();\n if (!isText(planId)) throw invalidPlan(\"a plan's id must be a non-empty, well-formed string\");\n const { steps, state, expiresInMs } = isRecord(fields) ? fields : ({} as Record<string, unknown>);\n // Copy the steps and the state before the first await, as `planCard()` does, so a change made while the hashes are\n // pending can't give the signature a state the person never saw on the card.\n const hashing = hashSteps(steps);\n const reads = copyState(state);\n const { signed: signedSteps } = await hashing;\n const signed = {\n planId,\n steps: signedSteps,\n stateHash: await stateHash(reads),\n stateReads: reads.map(({ source, key }) => ({ source, key })),\n expiresAt: expiryOf((options.now ?? (() => new Date()))(), expiresInMs),\n };\n const signature = await signer.sign(planPayload(signed));\n return { ...signed, keyId: signer.keyId, signature };\n}\n\nfunction isTimestamp(value: unknown): value is string {\n if (typeof value !== \"string\") return false;\n const time = Date.parse(value);\n return Number.isFinite(time) && new Date(time).toISOString() === value;\n}\n\nfunction copySignedStep(step: unknown): PlanStep | undefined {\n const { id, tool, class: stepClass, inputHash, businessKey, summary } = isRecord(step) ? step : {};\n if (![id, tool, summary].every(isText) || !CLASSES.includes(stepClass as string)) return undefined;\n if (typeof inputHash !== \"string\" || !HASH.test(inputHash)) return undefined;\n if (businessKey !== undefined && !isText(businessKey)) return undefined;\n const copy = { id, tool, class: stepClass, inputHash, summary } as PlanStep;\n return businessKey === undefined ? copy : { ...copy, businessKey };\n}\n\nfunction copyRead(read: unknown): StateRead | undefined {\n const { source, key } = isRecord(read) ? read : {};\n return isText(source) && isText(key) ? { source, key } : undefined;\n}\n\nfunction copyList<T>(value: unknown, copy: (item: unknown) => T | undefined): T[] | undefined {\n if (!Array.isArray(value)) return undefined;\n const items = Array.from(value as readonly unknown[], copy);\n return items.every((item) => item !== undefined) ? (items as T[]) : undefined;\n}\n\n/**\n * Reads each field of an untrusted record once into a plain copy, or returns `undefined` if any field is malformed.\n * Every later check reads the copy, so a getter or a Proxy can't show the signature one value and the checks another.\n */\nfunction copyApproval(value: unknown): PlanApproval | undefined {\n if (!isRecord(value)) return undefined;\n const { planId, steps, stateHash: hash, stateReads, expiresAt, keyId, signature } = value;\n if (![planId, keyId, signature].every(isText) || typeof hash !== \"string\" || !HASH.test(hash)) return undefined;\n if (!isTimestamp(expiresAt)) return undefined;\n const stepCopies = copyList(steps, copySignedStep);\n const readCopies = copyList(stateReads, copyRead);\n if (stepCopies === undefined || readCopies === undefined) return undefined;\n return {\n planId: planId as string,\n steps: stepCopies,\n stateHash: hash,\n stateReads: readCopies,\n expiresAt,\n keyId: keyId as string,\n signature: signature as string,\n };\n}\n\nfunction hashesEqual(a: string, b: string): boolean {\n return constantTimeEqual(ENCODER.encode(a), ENCODER.encode(b));\n}\n\nasync function inputMatches(inputHash: string, input: unknown): Promise<boolean> {\n try {\n return hashesEqual(await canonicalInputHash(input), inputHash);\n } catch {\n // An input with no canonical form can't be the one that was signed, which had one.\n return false;\n }\n}\n\nasync function stateMatches(approval: PlanApproval, values: unknown): Promise<boolean> {\n if (!Array.isArray(values) || values.length !== approval.stateReads.length) return false;\n const read = Array.from(values as readonly unknown[]);\n try {\n const fresh = await stateHash(approval.stateReads.map((r, index) => ({ ...r, value: read[index] })));\n return hashesEqual(fresh, approval.stateHash);\n } catch {\n // A value with no canonical form can't equal one that had one, so the state counts as changed.\n return false;\n }\n}\n\nasync function checkFreshness(approval: PlanApproval, options: VerifyPlanStepOptions): Promise<PlanStepCheck> {\n const now = (options.now ?? (() => new Date()))().getTime();\n // Written as \"not before\", so an invalid clock reading (NaN) counts as expired.\n if (!(now < Date.parse(approval.expiresAt))) return \"expired\";\n const values = await options.readState(approval.stateReads.map(({ source, key }) => ({ source, key })));\n return (await stateMatches(approval, values)) ? \"ok\" : \"stale_approval\";\n}\n\nasync function signatureHolds(signer: ApprovalSigner, record: PlanApproval): Promise<boolean> {\n try {\n return (await signer.verify(record.keyId, planPayload(record), record.signature)) === true;\n } catch {\n return false;\n }\n}\n\n/**\n * The plan approval as a trusted copy, or `undefined` when the record is malformed, its signature fails or names an\n * unknown key, or its steps break `lintPlan()`. `runPlan()` reads a plan's steps from this copy, so a resume that\n * finds every step already recorded still checks the approval it resumes under.\n */\nexport async function checkedPlanApproval(\n approval: unknown,\n signer: ApprovalSigner,\n): Promise<PlanApproval | undefined> {\n const record = copyApproval(approval);\n if (record === undefined || !(await signatureHolds(signer, record))) return undefined;\n return lintPlan(record.steps).ok ? record : undefined;\n}\n\n/**\n * Checks a plan approval before one of its steps runs, failing closed. Run the step only when it resolves to `\"ok\"`.\n *\n * For every step, the record must be well formed and its signature must verify under a key the signer holds; the\n * step's id must be in the plan; and its tool and input must match the signed tool and input hash. For steps up to\n * and including the pivot, the approval must not have expired, and `readState` must return values whose\n * `stateHash()` equals the signed one. Steps after the pivot skip the clock and the state, because the pivot itself\n * changes the state and nothing after it may stop on a person or a clock. Last, the step's claim goes to the ledger,\n * so no step passes twice and none passes before the steps ahead of it. A failed check claims nothing.\n *\n * The ledger records that a step passed this check, not that it ran. So `\"ok\"` for a step after the pivot means the\n * pivot passed, not that its write succeeded. A second check of a step up to the pivot can also return\n * `\"stale_approval\"` or `\"expired\"` before the ledger can answer `\"replayed\"`. Track which steps ran yourself, run the\n * next step only after the last one succeeded, and never compensate once the pivot has run.\n *\n * It returns the first failure it finds. It never throws for a bad record or call, and a signer that throws counts as\n * `\"tampered\"`. It rejects only when `readState` or the ledger rejects, and then the step must not run either.\n */\nexport async function verifyPlanBeforeStep(\n approval: unknown,\n call: PlanStepCall,\n options: VerifyPlanStepOptions,\n): Promise<PlanStepCheck> {\n const record = copyApproval(approval);\n if (record === undefined) return \"tampered\";\n // The signature comes first: until it verifies, no other field of the stored record is trusted.\n // A signer that throws (a malformed signature, a key-store error) refuses the step instead of rejecting the call.\n if (!(await signatureHolds(options.signer, record))) return \"tampered\";\n if (!lintPlan(record.steps).ok) return \"tampered\";\n const { stepId, tool, input } = isRecord(call) ? call : ({} as Record<string, unknown>);\n const index = record.steps.findIndex((step) => step.id === stepId);\n const step = record.steps[index];\n if (step === undefined) return \"step_not_in_plan\";\n if (tool !== step.tool || !(await inputMatches(step.inputHash, input))) return \"tampered\";\n if (step.class !== \"retryable\") {\n const fresh = await checkFreshness(record, options);\n if (fresh !== \"ok\") return fresh;\n }\n const claim = await options.ledger.claim(record.planId, index);\n if (claim === \"claimed\") return \"ok\";\n // Anything else a ledger answers, even a value outside its type, counts as a refusal.\n return claim === \"replayed\" ? \"replayed\" : \"out_of_order\";\n}\n"]}