@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.
- package/LICENSE +54 -0
- package/LICENSE-APACHE +202 -0
- package/LICENSE-MIT +21 -0
- package/README.md +514 -2
- package/dist/agents/index.d.ts +5 -0
- package/dist/agents/index.js +6 -0
- package/dist/agents/index.js.map +1 -0
- package/dist/ai/index.d.ts +10 -0
- package/dist/ai/index.js +11 -0
- package/dist/ai/index.js.map +1 -0
- package/dist/ai/interrupted-write.d.ts +28 -0
- package/dist/ai/interrupted-write.js +52 -0
- package/dist/ai/interrupted-write.js.map +1 -0
- package/dist/ai/settle-denied.d.ts +17 -0
- package/dist/ai/settle-denied.js +25 -0
- package/dist/ai/settle-denied.js.map +1 -0
- package/dist/ai/tool-approval.d.ts +68 -0
- package/dist/ai/tool-approval.js +219 -0
- package/dist/ai/tool-approval.js.map +1 -0
- package/dist/ai/tool-result.d.ts +23 -0
- package/dist/ai/tool-result.js +20 -0
- package/dist/ai/tool-result.js.map +1 -0
- package/dist/byok/default-provider.d.ts +12 -0
- package/dist/byok/default-provider.js +72 -0
- package/dist/byok/default-provider.js.map +1 -0
- package/dist/byok/explicit-provider.d.ts +39 -0
- package/dist/byok/explicit-provider.js +80 -0
- package/dist/byok/explicit-provider.js.map +1 -0
- package/dist/byok/index.d.ts +8 -0
- package/dist/byok/index.js +9 -0
- package/dist/byok/index.js.map +1 -0
- package/dist/bytes.d.ts +17 -0
- package/dist/bytes.js +59 -0
- package/dist/bytes.js.map +1 -0
- package/dist/cost/ai-types.d.ts +26 -0
- package/dist/cost/ai-types.js +2 -0
- package/dist/cost/ai-types.js.map +1 -0
- package/dist/cost/budget-exceeded.d.ts +39 -0
- package/dist/cost/budget-exceeded.js +49 -0
- package/dist/cost/budget-exceeded.js.map +1 -0
- package/dist/cost/cost-guard.d.ts +63 -0
- package/dist/cost/cost-guard.js +278 -0
- package/dist/cost/cost-guard.js.map +1 -0
- package/dist/cost/estimate.d.ts +76 -0
- package/dist/cost/estimate.js +320 -0
- package/dist/cost/estimate.js.map +1 -0
- package/dist/cost/guarded-provider.d.ts +24 -0
- package/dist/cost/guarded-provider.js +19 -0
- package/dist/cost/guarded-provider.js.map +1 -0
- package/dist/cost/index.d.ts +12 -0
- package/dist/cost/index.js +12 -0
- package/dist/cost/index.js.map +1 -0
- package/dist/cost/spend.d.ts +13 -0
- package/dist/cost/spend.js +15 -0
- package/dist/cost/spend.js.map +1 -0
- package/dist/effect-key.d.ts +31 -0
- package/dist/effect-key.js +61 -0
- package/dist/effect-key.js.map +1 -0
- package/dist/effect-store-conformance.d.ts +24 -0
- package/dist/effect-store-conformance.js +140 -0
- package/dist/effect-store-conformance.js.map +1 -0
- package/dist/effect-store.d.ts +71 -0
- package/dist/effect-store.js +38 -0
- package/dist/effect-store.js.map +1 -0
- package/dist/egress.d.ts +74 -0
- package/dist/egress.js +174 -0
- package/dist/egress.js.map +1 -0
- package/dist/errors.d.ts +32 -0
- package/dist/errors.js +26 -0
- package/dist/errors.js.map +1 -0
- package/dist/guarded-write.d.ts +99 -0
- package/dist/guarded-write.js +245 -0
- package/dist/guarded-write.js.map +1 -0
- package/dist/hash.d.ts +24 -0
- package/dist/hash.js +121 -0
- package/dist/hash.js.map +1 -0
- package/dist/index.d.ts +27 -0
- package/dist/index.js +28 -0
- package/dist/index.js.map +1 -0
- package/dist/key-store.d.ts +37 -0
- package/dist/key-store.js +53 -0
- package/dist/key-store.js.map +1 -0
- package/dist/model-routes.d.ts +54 -0
- package/dist/model-routes.js +117 -0
- package/dist/model-routes.js.map +1 -0
- package/dist/model-url.d.ts +39 -0
- package/dist/model-url.js +79 -0
- package/dist/model-url.js.map +1 -0
- package/dist/outcome.d.ts +88 -0
- package/dist/outcome.js +140 -0
- package/dist/outcome.js.map +1 -0
- package/dist/pending-store.d.ts +45 -0
- package/dist/pending-store.js +36 -0
- package/dist/pending-store.js.map +1 -0
- package/dist/pending.d.ts +144 -0
- package/dist/pending.js +161 -0
- package/dist/pending.js.map +1 -0
- package/dist/plan-approval.d.ts +196 -0
- package/dist/plan-approval.js +357 -0
- package/dist/plan-approval.js.map +1 -0
- package/dist/plan-card.d.ts +34 -0
- package/dist/plan-card.js +56 -0
- package/dist/plan-card.js.map +1 -0
- package/dist/plan-ledger-conformance.d.ts +24 -0
- package/dist/plan-ledger-conformance.js +99 -0
- package/dist/plan-ledger-conformance.js.map +1 -0
- package/dist/plan-ledger.d.ts +14 -0
- package/dist/plan-ledger.js +42 -0
- package/dist/plan-ledger.js.map +1 -0
- package/dist/plan-run.d.ts +133 -0
- package/dist/plan-run.js +438 -0
- package/dist/plan-run.js.map +1 -0
- package/dist/render.d.ts +40 -0
- package/dist/render.js +92 -0
- package/dist/render.js.map +1 -0
- package/dist/signer.d.ts +42 -0
- package/dist/signer.js +128 -0
- package/dist/signer.js.map +1 -0
- package/dist/stores/cloudflare.d.ts +34 -0
- package/dist/stores/cloudflare.js +84 -0
- package/dist/stores/cloudflare.js.map +1 -0
- package/dist/stores/dynamodb.d.ts +27 -0
- package/dist/stores/dynamodb.js +139 -0
- package/dist/stores/dynamodb.js.map +1 -0
- package/dist/stores/lost-claim.d.ts +8 -0
- package/dist/stores/lost-claim.js +11 -0
- package/dist/stores/lost-claim.js.map +1 -0
- package/dist/stores/postgres.d.ts +30 -0
- package/dist/stores/postgres.js +79 -0
- package/dist/stores/postgres.js.map +1 -0
- package/dist/test-signer.d.ts +13 -0
- package/dist/test-signer.js +18 -0
- package/dist/test-signer.js.map +1 -0
- package/dist/testing.d.ts +8 -0
- package/dist/testing.js +9 -0
- package/dist/testing.js.map +1 -0
- package/llms.txt +212 -0
- package/package.json +107 -3
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { type PlanFields, type StateValue, type StepClass } from "./plan-approval.js";
|
|
2
|
+
/** One step as the approval card shows it. */
|
|
3
|
+
export interface PlanCardStep {
|
|
4
|
+
/** The step's place in the plan, from 1. */
|
|
5
|
+
readonly position: number;
|
|
6
|
+
readonly id: string;
|
|
7
|
+
readonly tool: string;
|
|
8
|
+
readonly class: StepClass;
|
|
9
|
+
/** True for the pivot, the step that can't be undone. */
|
|
10
|
+
readonly isPivot: boolean;
|
|
11
|
+
readonly summary: string;
|
|
12
|
+
/** The step's exact input, as JSON data: a copy, so later changes to the plan's objects don't reach the card. */
|
|
13
|
+
readonly input: unknown;
|
|
14
|
+
/** `canonicalInputHash()` of `input`, the hash `signPlan()` signs for this step. */
|
|
15
|
+
readonly inputHash: string;
|
|
16
|
+
readonly businessKey?: string;
|
|
17
|
+
}
|
|
18
|
+
/** The approval card's payload: the steps in the order they run, the pivot's id, and the state the plan read. */
|
|
19
|
+
export interface PlanCard {
|
|
20
|
+
readonly steps: readonly PlanCardStep[];
|
|
21
|
+
/** The id of the pivot, or `null` for a plan whose steps can all be undone. */
|
|
22
|
+
readonly pivot: string | null;
|
|
23
|
+
/** Every value the plan was computed from, as JSON data. */
|
|
24
|
+
readonly state: readonly StateValue[];
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Builds the approval card for a plan, from the same fields you will pass to `signPlan()` once the person approves.
|
|
28
|
+
* Each step carries its exact input and the input's hash, and `isPivot` marks the step that can't be undone. The
|
|
29
|
+
* card is plain JSON data, ready to send to a UI.
|
|
30
|
+
*
|
|
31
|
+
* Throws a `SafetyError`, code `invalid_plan`, for the cases `signPlan()` throws it for, except `expiresInMs`, which a
|
|
32
|
+
* card doesn't use, and code `invalid_input` for an input or state value with no canonical JSON form.
|
|
33
|
+
*/
|
|
34
|
+
export declare function planCard(fields: Pick<PlanFields, "steps" | "state">): Promise<PlanCard>;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `planCard()`: the payload an approval card shows before a person approves a plan. It lists every step's exact
|
|
3
|
+
* input beside the hash that `signPlan()` will sign, marks the pivot, and shows the state the plan was computed from.
|
|
4
|
+
* Drawing the card is each product's job; this file only builds the data.
|
|
5
|
+
*/
|
|
6
|
+
import { canonicalJson } from "./hash.js";
|
|
7
|
+
import { copyState, hashSteps } from "./plan-approval.js";
|
|
8
|
+
// Reads a value once, into the canonical text `stateHash()` and `canonicalInputHash()` hash, and parses it back, so
|
|
9
|
+
// the card holds exactly what a hash covers, with `undefined` properties dropped as the hash drops them. It throws
|
|
10
|
+
// `invalid_input` for a value with no canonical form, as `signPlan()` would.
|
|
11
|
+
function canonicalCopy(value) {
|
|
12
|
+
return JSON.parse(canonicalJson(value));
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Builds the approval card for a plan, from the same fields you will pass to `signPlan()` once the person approves.
|
|
16
|
+
* Each step carries its exact input and the input's hash, and `isPivot` marks the step that can't be undone. The
|
|
17
|
+
* card is plain JSON data, ready to send to a UI.
|
|
18
|
+
*
|
|
19
|
+
* Throws a `SafetyError`, code `invalid_plan`, for the cases `signPlan()` throws it for, except `expiresInMs`, which a
|
|
20
|
+
* card doesn't use, and code `invalid_input` for an input or state value with no canonical JSON form.
|
|
21
|
+
*/
|
|
22
|
+
export async function planCard(fields) {
|
|
23
|
+
// The steps and the state are both read before the first await, so a change made while the hashes are pending
|
|
24
|
+
// reaches neither the card nor its hashes. A step's error still wins over a state error, as in signPlan().
|
|
25
|
+
const hashing = hashSteps(fields?.steps);
|
|
26
|
+
let state;
|
|
27
|
+
let stateError;
|
|
28
|
+
try {
|
|
29
|
+
state = copyState(fields?.state).map(({ source, key, value }) => ({ source, key, value: canonicalCopy(value) }));
|
|
30
|
+
}
|
|
31
|
+
catch (error) {
|
|
32
|
+
stateError = error;
|
|
33
|
+
}
|
|
34
|
+
const { inputs, signed } = await hashing;
|
|
35
|
+
if (state === undefined)
|
|
36
|
+
throw stateError;
|
|
37
|
+
const steps = signed.map((step, index) => {
|
|
38
|
+
const card = {
|
|
39
|
+
position: index + 1,
|
|
40
|
+
id: step.id,
|
|
41
|
+
tool: step.tool,
|
|
42
|
+
class: step.class,
|
|
43
|
+
isPivot: step.class === "pivot",
|
|
44
|
+
summary: step.summary,
|
|
45
|
+
input: inputs[index],
|
|
46
|
+
inputHash: step.inputHash,
|
|
47
|
+
};
|
|
48
|
+
return step.businessKey === undefined ? card : { ...card, businessKey: step.businessKey };
|
|
49
|
+
});
|
|
50
|
+
return {
|
|
51
|
+
steps,
|
|
52
|
+
pivot: signed.find((step) => step.class === "pivot")?.id ?? null,
|
|
53
|
+
state,
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
//# sourceMappingURL=plan-card.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"plan-card.js","sourceRoot":"","sources":["../src/plan-card.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,SAAS,EAAE,SAAS,EAAoD,MAAM,oBAAoB,CAAC;AA4B5G,oHAAoH;AACpH,mHAAmH;AACnH,6EAA6E;AAC7E,SAAS,aAAa,CAAC,KAAc;IACnC,OAAO,IAAI,CAAC,KAAK,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC,CAAC;AAC1C,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,QAAQ,CAAC,MAA2C;IACxE,8GAA8G;IAC9G,2GAA2G;IAC3G,MAAM,OAAO,GAAG,SAAS,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IACzC,IAAI,KAA+B,CAAC;IACpC,IAAI,UAAmB,CAAC;IACxB,IAAI,CAAC;QACH,KAAK,GAAG,SAAS,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,GAAG,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,GAAG,EAAE,KAAK,EAAE,aAAa,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC;IACnH,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,UAAU,GAAG,KAAK,CAAC;IACrB,CAAC;IACD,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,OAAO,CAAC;IACzC,IAAI,KAAK,KAAK,SAAS;QAAE,MAAM,UAAU,CAAC;IAC1C,MAAM,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,KAAK,EAAgB,EAAE;QACrD,MAAM,IAAI,GAAG;YACX,QAAQ,EAAE,KAAK,GAAG,CAAC;YACnB,EAAE,EAAE,IAAI,CAAC,EAAE;YACX,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,KAAK,EAAE,IAAI,CAAC,KAAK;YACjB,OAAO,EAAE,IAAI,CAAC,KAAK,KAAK,OAAO;YAC/B,OAAO,EAAE,IAAI,CAAC,OAAO;YACrB,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC;YACpB,SAAS,EAAE,IAAI,CAAC,SAAS;SAC1B,CAAC;QACF,OAAO,IAAI,CAAC,WAAW,KAAK,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,GAAG,IAAI,EAAE,WAAW,EAAE,IAAI,CAAC,WAAW,EAAE,CAAC;IAC5F,CAAC,CAAC,CAAC;IACH,OAAO;QACL,KAAK;QACL,KAAK,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,KAAK,KAAK,OAAO,CAAC,EAAE,EAAE,IAAI,IAAI;QAChE,KAAK;KACN,CAAC;AACJ,CAAC","sourcesContent":["/**\n * `planCard()`: the payload an approval card shows before a person approves a plan. It lists every step's exact\n * input beside the hash that `signPlan()` will sign, marks the pivot, and shows the state the plan was computed from.\n * Drawing the card is each product's job; this file only builds the data.\n */\nimport { canonicalJson } from \"./hash.js\";\nimport { copyState, hashSteps, type PlanFields, type StateValue, type StepClass } from \"./plan-approval.js\";\n\n/** One step as the approval card shows it. */\nexport interface PlanCardStep {\n /** The step's place in the plan, from 1. */\n readonly position: number;\n readonly id: string;\n readonly tool: string;\n readonly class: StepClass;\n /** True for the pivot, the step that can't be undone. */\n readonly isPivot: boolean;\n readonly summary: string;\n /** The step's exact input, as JSON data: a copy, so later changes to the plan's objects don't reach the card. */\n readonly input: unknown;\n /** `canonicalInputHash()` of `input`, the hash `signPlan()` signs for this step. */\n readonly inputHash: string;\n readonly businessKey?: string;\n}\n\n/** The approval card's payload: the steps in the order they run, the pivot's id, and the state the plan read. */\nexport interface PlanCard {\n readonly steps: readonly PlanCardStep[];\n /** The id of the pivot, or `null` for a plan whose steps can all be undone. */\n readonly pivot: string | null;\n /** Every value the plan was computed from, as JSON data. */\n readonly state: readonly StateValue[];\n}\n\n// Reads a value once, into the canonical text `stateHash()` and `canonicalInputHash()` hash, and parses it back, so\n// the card holds exactly what a hash covers, with `undefined` properties dropped as the hash drops them. It throws\n// `invalid_input` for a value with no canonical form, as `signPlan()` would.\nfunction canonicalCopy(value: unknown): unknown {\n return JSON.parse(canonicalJson(value));\n}\n\n/**\n * Builds the approval card for a plan, from the same fields you will pass to `signPlan()` once the person approves.\n * Each step carries its exact input and the input's hash, and `isPivot` marks the step that can't be undone. The\n * card is plain JSON data, ready to send to a UI.\n *\n * Throws a `SafetyError`, code `invalid_plan`, for the cases `signPlan()` throws it for, except `expiresInMs`, which a\n * card doesn't use, and code `invalid_input` for an input or state value with no canonical JSON form.\n */\nexport async function planCard(fields: Pick<PlanFields, \"steps\" | \"state\">): Promise<PlanCard> {\n // The steps and the state are both read before the first await, so a change made while the hashes are pending\n // reaches neither the card nor its hashes. A step's error still wins over a state error, as in signPlan().\n const hashing = hashSteps(fields?.steps);\n let state: StateValue[] | undefined;\n let stateError: unknown;\n try {\n state = copyState(fields?.state).map(({ source, key, value }) => ({ source, key, value: canonicalCopy(value) }));\n } catch (error) {\n stateError = error;\n }\n const { inputs, signed } = await hashing;\n if (state === undefined) throw stateError;\n const steps = signed.map((step, index): PlanCardStep => {\n const card = {\n position: index + 1,\n id: step.id,\n tool: step.tool,\n class: step.class,\n isPivot: step.class === \"pivot\",\n summary: step.summary,\n input: inputs[index],\n inputHash: step.inputHash,\n };\n return step.businessKey === undefined ? card : { ...card, businessKey: step.businessKey };\n });\n return {\n steps,\n pivot: signed.find((step) => step.class === \"pivot\")?.id ?? null,\n state,\n };\n}\n"]}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `PlanLedger` conformance cases: what every ledger must do for a plan's steps to pass verification once each, in
|
|
3
|
+
* order. The memory ledger runs them in this package's tests, and each durable ledger runs the same list. The cases
|
|
4
|
+
* throw plain `Error`s and import no test runner, so any runner, and workerd, can call them.
|
|
5
|
+
*/
|
|
6
|
+
import type { PlanLedger } from "./plan-approval.js";
|
|
7
|
+
/** One conformance case: a name a test runner can show, and a check that rejects if the ledger breaks the rule. */
|
|
8
|
+
export interface PlanLedgerCase {
|
|
9
|
+
/** What the case checks, as a sentence. */
|
|
10
|
+
readonly name: string;
|
|
11
|
+
/** Runs the check against a fresh, empty ledger from `makeLedger`. */
|
|
12
|
+
run(makeLedger: () => PlanLedger | Promise<PlanLedger>): Promise<void>;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* The cases every `PlanLedger` must pass. Run each against a fresh ledger:
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```ts
|
|
19
|
+
* for (const conformance of planLedgerConformance()) {
|
|
20
|
+
* test(conformance.name, () => conformance.run(() => myPlanLedger()));
|
|
21
|
+
* }
|
|
22
|
+
* ```
|
|
23
|
+
*/
|
|
24
|
+
export declare function planLedgerConformance(): readonly PlanLedgerCase[];
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
function check(condition, message) {
|
|
2
|
+
if (!condition)
|
|
3
|
+
throw new Error(`PlanLedger conformance: ${message}`);
|
|
4
|
+
}
|
|
5
|
+
const CASES = [
|
|
6
|
+
{
|
|
7
|
+
name: "claim passes each step once, in order, and answers replayed for a step that already passed",
|
|
8
|
+
async run(makeLedger) {
|
|
9
|
+
const ledger = await makeLedger();
|
|
10
|
+
check((await ledger.claim("plan-1", 0)) === "claimed", "the first step must be claimed");
|
|
11
|
+
check((await ledger.claim("plan-1", 1)) === "claimed", "the next step must be claimed");
|
|
12
|
+
check((await ledger.claim("plan-1", 0)) === "replayed", "a step that passed must be replayed");
|
|
13
|
+
check((await ledger.claim("plan-1", 1)) === "replayed", "the latest step that passed must be replayed");
|
|
14
|
+
},
|
|
15
|
+
},
|
|
16
|
+
{
|
|
17
|
+
name: "claim refuses a step whose earlier steps have not passed, as out_of_order",
|
|
18
|
+
async run(makeLedger) {
|
|
19
|
+
const ledger = await makeLedger();
|
|
20
|
+
check((await ledger.claim("plan-1", 1)) === "out_of_order", "a first claim of step 2 must be out of order");
|
|
21
|
+
check((await ledger.claim("plan-1", 5)) === "out_of_order", "a claim far ahead must be out of order");
|
|
22
|
+
await ledger.claim("plan-1", 0);
|
|
23
|
+
check((await ledger.claim("plan-1", 2)) === "out_of_order", "a claim that skips a step must be out of order");
|
|
24
|
+
},
|
|
25
|
+
},
|
|
26
|
+
{
|
|
27
|
+
name: "a refused claim uses nothing up: the step it named can still be claimed in its turn",
|
|
28
|
+
async run(makeLedger) {
|
|
29
|
+
const ledger = await makeLedger();
|
|
30
|
+
await ledger.claim("plan-1", 2);
|
|
31
|
+
await ledger.claim("plan-1", 1);
|
|
32
|
+
check((await ledger.claim("plan-1", 0)) === "claimed", "step 1 must still be claimable after refused claims");
|
|
33
|
+
check((await ledger.claim("plan-1", 1)) === "claimed", "step 2 must still be claimable after a refused claim");
|
|
34
|
+
check((await ledger.claim("plan-1", 2)) === "claimed", "step 3 must still be claimable after a refused claim");
|
|
35
|
+
},
|
|
36
|
+
},
|
|
37
|
+
{
|
|
38
|
+
name: "a replayed claim uses nothing up: the next step is still claimed once",
|
|
39
|
+
async run(makeLedger) {
|
|
40
|
+
const ledger = await makeLedger();
|
|
41
|
+
await ledger.claim("plan-1", 0);
|
|
42
|
+
for (let i = 0; i < 4; i++)
|
|
43
|
+
await ledger.claim("plan-1", 0);
|
|
44
|
+
check((await ledger.claim("plan-1", 1)) === "claimed", "the next step must be claimed after replays");
|
|
45
|
+
check((await ledger.claim("plan-1", 1)) === "replayed", "and claimed only once");
|
|
46
|
+
},
|
|
47
|
+
},
|
|
48
|
+
{
|
|
49
|
+
name: "of many concurrent claims of one step, exactly one is claimed and the rest are replayed",
|
|
50
|
+
async run(makeLedger) {
|
|
51
|
+
const ledger = await makeLedger();
|
|
52
|
+
const answers = await Promise.all(Array.from({ length: 8 }, () => ledger.claim("plan-1", 0)));
|
|
53
|
+
check(answers.filter((answer) => answer === "claimed").length === 1, "exactly one claim must win");
|
|
54
|
+
check(answers.every((answer) => answer === "claimed" || answer === "replayed"), "the rest must be replayed");
|
|
55
|
+
const next = await Promise.all(Array.from({ length: 8 }, () => ledger.claim("plan-1", 1)));
|
|
56
|
+
check(next.filter((answer) => answer === "claimed").length === 1, "exactly one claim of the next step must win");
|
|
57
|
+
},
|
|
58
|
+
},
|
|
59
|
+
{
|
|
60
|
+
name: "claim rejects a step index that is not a whole number from 0 to 2 ** 31 - 1, and uses nothing up",
|
|
61
|
+
async run(makeLedger) {
|
|
62
|
+
const ledger = await makeLedger();
|
|
63
|
+
await ledger.claim("plan-1", 0);
|
|
64
|
+
for (const bad of [-1, 0.5, Number.NaN, Number.POSITIVE_INFINITY, 2 ** 31, 2 ** 60]) {
|
|
65
|
+
let rejected = false;
|
|
66
|
+
await ledger.claim("plan-1", bad).catch(() => {
|
|
67
|
+
rejected = true;
|
|
68
|
+
});
|
|
69
|
+
check(rejected, `a claim of step ${String(bad)} must be rejected`);
|
|
70
|
+
}
|
|
71
|
+
check((await ledger.claim("plan-1", 1)) === "claimed", "the next step must still be claimed after the rejections");
|
|
72
|
+
},
|
|
73
|
+
},
|
|
74
|
+
{
|
|
75
|
+
name: "plans keep separate progress",
|
|
76
|
+
async run(makeLedger) {
|
|
77
|
+
const ledger = await makeLedger();
|
|
78
|
+
await ledger.claim("plan-a", 0);
|
|
79
|
+
await ledger.claim("plan-a", 1);
|
|
80
|
+
check((await ledger.claim("plan-b", 0)) === "claimed", "another plan's first step must be claimed");
|
|
81
|
+
check((await ledger.claim("plan-b", 2)) === "out_of_order", "another plan's progress must not count");
|
|
82
|
+
check((await ledger.claim("plan-a", 2)) === "claimed", "a plan must keep its own progress");
|
|
83
|
+
},
|
|
84
|
+
},
|
|
85
|
+
];
|
|
86
|
+
/**
|
|
87
|
+
* The cases every `PlanLedger` must pass. Run each against a fresh ledger:
|
|
88
|
+
*
|
|
89
|
+
* @example
|
|
90
|
+
* ```ts
|
|
91
|
+
* for (const conformance of planLedgerConformance()) {
|
|
92
|
+
* test(conformance.name, () => conformance.run(() => myPlanLedger()));
|
|
93
|
+
* }
|
|
94
|
+
* ```
|
|
95
|
+
*/
|
|
96
|
+
export function planLedgerConformance() {
|
|
97
|
+
return CASES;
|
|
98
|
+
}
|
|
99
|
+
//# sourceMappingURL=plan-ledger-conformance.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"plan-ledger-conformance.js","sourceRoot":"","sources":["../src/plan-ledger-conformance.ts"],"names":[],"mappings":"AAeA,SAAS,KAAK,CAAC,SAAkB,EAAE,OAAe;IAChD,IAAI,CAAC,SAAS;QAAE,MAAM,IAAI,KAAK,CAAC,2BAA2B,OAAO,EAAE,CAAC,CAAC;AACxE,CAAC;AAED,MAAM,KAAK,GAA8B;IACvC;QACE,IAAI,EAAE,4FAA4F;QAClG,KAAK,CAAC,GAAG,CAAC,UAAU;YAClB,MAAM,MAAM,GAAG,MAAM,UAAU,EAAE,CAAC;YAClC,KAAK,CAAC,CAAC,MAAM,MAAM,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,KAAK,SAAS,EAAE,gCAAgC,CAAC,CAAC;YACzF,KAAK,CAAC,CAAC,MAAM,MAAM,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC,C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C,GAAG,CAAC,mBAAmB,CAAC,CAAC;YACrE,CAAC;YACD,KAAK,CACH,CAAC,MAAM,MAAM,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,KAAK,SAAS,EAC/C,0DAA0D,CAC3D,CAAC;QACJ,CAAC;KACF;IACD;QACE,IAAI,EAAE,8BAA8B;QACpC,KAAK,CAAC,GAAG,CAAC,UAAU;YAClB,MAAM,MAAM,GAAG,MAAM,UAAU,EAAE,CAAC;YAClC,MAAM,MAAM,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC;YAChC,MAAM,MAAM,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC;YAChC,KAAK,CAAC,CAAC,MAAM,MAAM,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,KAAK,SAAS,EAAE,2CAA2C,CAAC,CAAC;YACpG,KAAK,CAAC,CAAC,MAAM,MAAM,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,KAAK,cAAc,EAAE,wCAAwC,CAAC,CAAC;YACtG,KAAK,CAAC,CAAC,MAAM,MAAM,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,KAAK,SAAS,EAAE,mCAAmC,CAAC,CAAC;QAC9F,CAAC;KACF;CACF,CAAC;AAEF;;;;;;;;;GASG;AACH,MAAM,UAAU,qBAAqB;IACnC,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["/**\n * The `PlanLedger` conformance cases: what every ledger must do for a plan's steps to pass verification once each, in\n * order. The memory ledger runs them in this package's tests, and each durable ledger runs the same list. The cases\n * throw plain `Error`s and import no test runner, so any runner, and workerd, can call them.\n */\nimport type { PlanLedger } from \"./plan-approval.js\";\n\n/** One conformance case: a name a test runner can show, and a check that rejects if the ledger breaks the rule. */\nexport interface PlanLedgerCase {\n /** What the case checks, as a sentence. */\n readonly name: string;\n /** Runs the check against a fresh, empty ledger from `makeLedger`. */\n run(makeLedger: () => PlanLedger | Promise<PlanLedger>): Promise<void>;\n}\n\nfunction check(condition: boolean, message: string): void {\n if (!condition) throw new Error(`PlanLedger conformance: ${message}`);\n}\n\nconst CASES: readonly PlanLedgerCase[] = [\n {\n name: \"claim passes each step once, in order, and answers replayed for a step that already passed\",\n async run(makeLedger) {\n const ledger = await makeLedger();\n check((await ledger.claim(\"plan-1\", 0)) === \"claimed\", \"the first step must be claimed\");\n check((await ledger.claim(\"plan-1\", 1)) === \"claimed\", \"the next step must be claimed\");\n check((await ledger.claim(\"plan-1\", 0)) === \"replayed\", \"a step that passed must be replayed\");\n check((await ledger.claim(\"plan-1\", 1)) === \"replayed\", \"the latest step that passed must be replayed\");\n },\n },\n {\n name: \"claim refuses a step whose earlier steps have not passed, as out_of_order\",\n async run(makeLedger) {\n const ledger = await makeLedger();\n check((await ledger.claim(\"plan-1\", 1)) === \"out_of_order\", \"a first claim of step 2 must be out of order\");\n check((await ledger.claim(\"plan-1\", 5)) === \"out_of_order\", \"a claim far ahead must be out of order\");\n await ledger.claim(\"plan-1\", 0);\n check((await ledger.claim(\"plan-1\", 2)) === \"out_of_order\", \"a claim that skips a step must be out of order\");\n },\n },\n {\n name: \"a refused claim uses nothing up: the step it named can still be claimed in its turn\",\n async run(makeLedger) {\n const ledger = await makeLedger();\n await ledger.claim(\"plan-1\", 2);\n await ledger.claim(\"plan-1\", 1);\n check((await ledger.claim(\"plan-1\", 0)) === \"claimed\", \"step 1 must still be claimable after refused claims\");\n check((await ledger.claim(\"plan-1\", 1)) === \"claimed\", \"step 2 must still be claimable after a refused claim\");\n check((await ledger.claim(\"plan-1\", 2)) === \"claimed\", \"step 3 must still be claimable after a refused claim\");\n },\n },\n {\n name: \"a replayed claim uses nothing up: the next step is still claimed once\",\n async run(makeLedger) {\n const ledger = await makeLedger();\n await ledger.claim(\"plan-1\", 0);\n for (let i = 0; i < 4; i++) await ledger.claim(\"plan-1\", 0);\n check((await ledger.claim(\"plan-1\", 1)) === \"claimed\", \"the next step must be claimed after replays\");\n check((await ledger.claim(\"plan-1\", 1)) === \"replayed\", \"and claimed only once\");\n },\n },\n {\n name: \"of many concurrent claims of one step, exactly one is claimed and the rest are replayed\",\n async run(makeLedger) {\n const ledger = await makeLedger();\n const answers = await Promise.all(Array.from({ length: 8 }, () => ledger.claim(\"plan-1\", 0)));\n check(answers.filter((answer) => answer === \"claimed\").length === 1, \"exactly one claim must win\");\n check(\n answers.every((answer) => answer === \"claimed\" || answer === \"replayed\"),\n \"the rest must be replayed\",\n );\n const next = await Promise.all(Array.from({ length: 8 }, () => ledger.claim(\"plan-1\", 1)));\n check(next.filter((answer) => answer === \"claimed\").length === 1, \"exactly one claim of the next step must win\");\n },\n },\n {\n name: \"claim rejects a step index that is not a whole number from 0 to 2 ** 31 - 1, and uses nothing up\",\n async run(makeLedger) {\n const ledger = await makeLedger();\n await ledger.claim(\"plan-1\", 0);\n for (const bad of [-1, 0.5, Number.NaN, Number.POSITIVE_INFINITY, 2 ** 31, 2 ** 60]) {\n let rejected = false;\n await ledger.claim(\"plan-1\", bad).catch(() => {\n rejected = true;\n });\n check(rejected, `a claim of step ${String(bad)} must be rejected`);\n }\n check(\n (await ledger.claim(\"plan-1\", 1)) === \"claimed\",\n \"the next step must still be claimed after the rejections\",\n );\n },\n },\n {\n name: \"plans keep separate progress\",\n async run(makeLedger) {\n const ledger = await makeLedger();\n await ledger.claim(\"plan-a\", 0);\n await ledger.claim(\"plan-a\", 1);\n check((await ledger.claim(\"plan-b\", 0)) === \"claimed\", \"another plan's first step must be claimed\");\n check((await ledger.claim(\"plan-b\", 2)) === \"out_of_order\", \"another plan's progress must not count\");\n check((await ledger.claim(\"plan-a\", 2)) === \"claimed\", \"a plan must keep its own progress\");\n },\n },\n];\n\n/**\n * The cases every `PlanLedger` must pass. Run each against a fresh ledger:\n *\n * @example\n * ```ts\n * for (const conformance of planLedgerConformance()) {\n * test(conformance.name, () => conformance.run(() => myPlanLedger()));\n * }\n * ```\n */\nexport function planLedgerConformance(): readonly PlanLedgerCase[] {\n return CASES;\n}\n"]}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { PlanLedger } from "./plan-approval.js";
|
|
2
|
+
/**
|
|
3
|
+
* Refuses a step index that is not a whole number from 0 to 2 ** 31 - 1. Every ledger checks its argument with this
|
|
4
|
+
* before it reads anything, because a negative index would compare as "already passed" and a fractional one as "out of
|
|
5
|
+
* order", and neither names a step. Throws a `SafetyError`, code `invalid_plan`.
|
|
6
|
+
*/
|
|
7
|
+
export declare function assertStepIndex(stepIndex: unknown): asserts stepIndex is number;
|
|
8
|
+
/**
|
|
9
|
+
* A `PlanLedger` that keeps each plan's progress in memory, for tests and single-process hosts. It forgets
|
|
10
|
+
* everything when the process ends, after which a replayed approval would pass again, so a host whose plans can
|
|
11
|
+
* resume in another process needs a durable ledger. It never forgets a plan while the process lives, because
|
|
12
|
+
* forgetting one would let its approval run again; each plan costs one map entry.
|
|
13
|
+
*/
|
|
14
|
+
export declare function memoryPlanLedger(): PlanLedger;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `memoryPlanLedger()`: the in-memory `PlanLedger`, which records each plan step that passed verification so a
|
|
3
|
+
* replayed approval can't run a step twice and no step runs before the steps ahead of it.
|
|
4
|
+
*/
|
|
5
|
+
import { SafetyError } from "./errors.js";
|
|
6
|
+
// The largest step index a ledger accepts, which a 32-bit integer column holds, as Postgres's does. A plan has a
|
|
7
|
+
// handful of steps, so the bound costs nothing, and every ledger answers an index beyond it the same way.
|
|
8
|
+
const MAX_STEP_INDEX = 2 ** 31 - 1;
|
|
9
|
+
/**
|
|
10
|
+
* Refuses a step index that is not a whole number from 0 to 2 ** 31 - 1. Every ledger checks its argument with this
|
|
11
|
+
* before it reads anything, because a negative index would compare as "already passed" and a fractional one as "out of
|
|
12
|
+
* order", and neither names a step. Throws a `SafetyError`, code `invalid_plan`.
|
|
13
|
+
*/
|
|
14
|
+
export function assertStepIndex(stepIndex) {
|
|
15
|
+
if (!Number.isSafeInteger(stepIndex) || stepIndex < 0 || stepIndex > MAX_STEP_INDEX) {
|
|
16
|
+
throw new SafetyError("invalid_plan", "a plan ledger's step index must be a whole number from 0 to 2147483647");
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* A `PlanLedger` that keeps each plan's progress in memory, for tests and single-process hosts. It forgets
|
|
21
|
+
* everything when the process ends, after which a replayed approval would pass again, so a host whose plans can
|
|
22
|
+
* resume in another process needs a durable ledger. It never forgets a plan while the process lives, because
|
|
23
|
+
* forgetting one would let its approval run again; each plan costs one map entry.
|
|
24
|
+
*/
|
|
25
|
+
export function memoryPlanLedger() {
|
|
26
|
+
// The number of steps of each plan that have passed, so the next step to claim is at this index.
|
|
27
|
+
const passed = new Map();
|
|
28
|
+
return Object.freeze({
|
|
29
|
+
async claim(planId, stepIndex) {
|
|
30
|
+
assertStepIndex(stepIndex);
|
|
31
|
+
const next = passed.get(planId) ?? 0;
|
|
32
|
+
if (stepIndex < next)
|
|
33
|
+
return "replayed";
|
|
34
|
+
if (stepIndex > next)
|
|
35
|
+
return "out_of_order";
|
|
36
|
+
// No await between the read and the write, so two claims of one step can't both pass.
|
|
37
|
+
passed.set(planId, next + 1);
|
|
38
|
+
return "claimed";
|
|
39
|
+
},
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
//# sourceMappingURL=plan-ledger.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"plan-ledger.js","sourceRoot":"","sources":["../src/plan-ledger.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAG1C,iHAAiH;AACjH,0GAA0G;AAC1G,MAAM,cAAc,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;AAEnC;;;;GAIG;AACH,MAAM,UAAU,eAAe,CAAC,SAAkB;IAChD,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,SAAS,CAAC,IAAK,SAAoB,GAAG,CAAC,IAAK,SAAoB,GAAG,cAAc,EAAE,CAAC;QAC5G,MAAM,IAAI,WAAW,CAAC,cAAc,EAAE,wEAAwE,CAAC,CAAC;IAClH,CAAC;AACH,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,gBAAgB;IAC9B,iGAAiG;IACjG,MAAM,MAAM,GAAG,IAAI,GAAG,EAAkB,CAAC;IACzC,OAAO,MAAM,CAAC,MAAM,CAAC;QACnB,KAAK,CAAC,KAAK,CAAC,MAAc,EAAE,SAAiB;YAC3C,eAAe,CAAC,SAAS,CAAC,CAAC;YAC3B,MAAM,IAAI,GAAG,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;YACrC,IAAI,SAAS,GAAG,IAAI;gBAAE,OAAO,UAAmB,CAAC;YACjD,IAAI,SAAS,GAAG,IAAI;gBAAE,OAAO,cAAuB,CAAC;YACrD,sFAAsF;YACtF,MAAM,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,GAAG,CAAC,CAAC,CAAC;YAC7B,OAAO,SAAkB,CAAC;QAC5B,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * `memoryPlanLedger()`: the in-memory `PlanLedger`, which records each plan step that passed verification so a\n * replayed approval can't run a step twice and no step runs before the steps ahead of it.\n */\nimport { SafetyError } from \"./errors.js\";\nimport type { PlanLedger } from \"./plan-approval.js\";\n\n// The largest step index a ledger accepts, which a 32-bit integer column holds, as Postgres's does. A plan has a\n// handful of steps, so the bound costs nothing, and every ledger answers an index beyond it the same way.\nconst MAX_STEP_INDEX = 2 ** 31 - 1;\n\n/**\n * Refuses a step index that is not a whole number from 0 to 2 ** 31 - 1. Every ledger checks its argument with this\n * before it reads anything, because a negative index would compare as \"already passed\" and a fractional one as \"out of\n * order\", and neither names a step. Throws a `SafetyError`, code `invalid_plan`.\n */\nexport function assertStepIndex(stepIndex: unknown): asserts stepIndex is number {\n if (!Number.isSafeInteger(stepIndex) || (stepIndex as number) < 0 || (stepIndex as number) > MAX_STEP_INDEX) {\n throw new SafetyError(\"invalid_plan\", \"a plan ledger's step index must be a whole number from 0 to 2147483647\");\n }\n}\n\n/**\n * A `PlanLedger` that keeps each plan's progress in memory, for tests and single-process hosts. It forgets\n * everything when the process ends, after which a replayed approval would pass again, so a host whose plans can\n * resume in another process needs a durable ledger. It never forgets a plan while the process lives, because\n * forgetting one would let its approval run again; each plan costs one map entry.\n */\nexport function memoryPlanLedger(): PlanLedger {\n // The number of steps of each plan that have passed, so the next step to claim is at this index.\n const passed = new Map<string, number>();\n return Object.freeze({\n async claim(planId: string, stepIndex: number) {\n assertStepIndex(stepIndex);\n const next = passed.get(planId) ?? 0;\n if (stepIndex < next) return \"replayed\" as const;\n if (stepIndex > next) return \"out_of_order\" as const;\n // No await between the read and the write, so two claims of one step can't both pass.\n passed.set(planId, next + 1);\n return \"claimed\" as const;\n },\n });\n}\n"]}
|
|
@@ -0,0 +1,133 @@
|
|
|
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 { type EffectScope } from "./effect-key.js";
|
|
17
|
+
import type { EffectStore } from "./effect-store.js";
|
|
18
|
+
import { type WriteDedupe } from "./guarded-write.js";
|
|
19
|
+
import { type WriteOutcome } from "./outcome.js";
|
|
20
|
+
import { type PlanLedger, type PlanStep, type StateRead } from "./plan-approval.js";
|
|
21
|
+
import { type RenderedOutcome } from "./render.js";
|
|
22
|
+
import type { ApprovalSigner } from "./signer.js";
|
|
23
|
+
/** One signed step as the host runs it: the step, its exact input and the calls that perform and undo it. */
|
|
24
|
+
export interface PlanStepImpl {
|
|
25
|
+
/** The step as the approval signs it. Its id, tool, class and business key must match the signed step. */
|
|
26
|
+
readonly step: PlanStep;
|
|
27
|
+
/** The step's exact input. The approval signs its hash, and a different input is refused as not verified. */
|
|
28
|
+
readonly input: unknown;
|
|
29
|
+
/** How a retry of `run` finds out what an earlier attempt did, as for `guardedWrite()`. */
|
|
30
|
+
readonly dedupe: WriteDedupe;
|
|
31
|
+
/** Performs the step. Send `key` to the external API's idempotency header, or where `reconcile` can find it. */
|
|
32
|
+
run(key: string): Promise<WriteOutcome>;
|
|
33
|
+
/** Reads the external system's state for `run`'s key, as for `guardedWrite()`. */
|
|
34
|
+
reconcile?(key: string): Promise<WriteOutcome | "not_found">;
|
|
35
|
+
/**
|
|
36
|
+
* Undoes the step, and returns an `applied` outcome once it has. Required for a `compensable` step and refused for
|
|
37
|
+
* the others. It runs as a guarded write with its own key, so it must be idempotent under that key.
|
|
38
|
+
*/
|
|
39
|
+
compensate?(key: string): Promise<WriteOutcome>;
|
|
40
|
+
/** Reads the external system's state for `compensate`'s key, so a compensation that crashed can be checked. */
|
|
41
|
+
reconcileCompensation?(key: string): Promise<WriteOutcome | "not_found">;
|
|
42
|
+
}
|
|
43
|
+
/** Where a plan runs: the tenant, session and branch its writes are keyed under. */
|
|
44
|
+
export type PlanScope = Omit<EffectScope, "toolCallId">;
|
|
45
|
+
/** The options of `runPlan()`. */
|
|
46
|
+
export interface RunPlanOptions {
|
|
47
|
+
/** The signed plan approval, as `signPlan()` returned it. */
|
|
48
|
+
readonly approval: unknown;
|
|
49
|
+
/** The steps, in the order the approval signs them. */
|
|
50
|
+
readonly steps: readonly PlanStepImpl[];
|
|
51
|
+
/** Where the effect records live. Use a durable store wherever a plan must resume after a crash. */
|
|
52
|
+
readonly store: EffectStore;
|
|
53
|
+
/** The tenant, session and branch the plan's writes belong to. */
|
|
54
|
+
readonly scope: PlanScope;
|
|
55
|
+
/** A signer that holds the key the approval names. */
|
|
56
|
+
readonly signer: ApprovalSigner;
|
|
57
|
+
/** Where each step's claim is recorded. Use a durable ledger wherever a plan must resume after a crash. */
|
|
58
|
+
readonly ledger: PlanLedger;
|
|
59
|
+
/** Re-reads the approval's `stateReads` now, as for `verifyPlanBeforeStep()`. */
|
|
60
|
+
readonly readState: (reads: readonly StateRead[]) => Promise<readonly unknown[]>;
|
|
61
|
+
/**
|
|
62
|
+
* A cancel. Checked before each step up to and including the pivot starts: a cancel then compensates the steps that
|
|
63
|
+
* ran. Once the pivot has started it is ignored, and the plan runs forward.
|
|
64
|
+
*/
|
|
65
|
+
readonly signal?: AbortSignal;
|
|
66
|
+
/** How long a started write counts as live, in milliseconds, as for `guardedWrite()`. */
|
|
67
|
+
readonly leaseMs?: number;
|
|
68
|
+
/** Returns the current time. Defaults to `new Date()`. */
|
|
69
|
+
readonly now?: () => Date;
|
|
70
|
+
}
|
|
71
|
+
/** Why a plan that began could not finish. */
|
|
72
|
+
export type PlanFailureReason = "STEP_FAILED" | "STEP_PARTIAL" | "STEP_UNKNOWN" | "CANCELLED" | "STALE_APPROVAL" | "EXPIRED" | "NOT_VERIFIED" | "COMPENSATION_FAILED" | "RETRY_REFUSED";
|
|
73
|
+
/**
|
|
74
|
+
* What a plan did, computed by the harness and never by the model. `completed`: every step ran. `failed_compensated`:
|
|
75
|
+
* a step failed and every step that had run was undone. `failed_needs_human`: something still holds that the harness
|
|
76
|
+
* could not undo, listed in `outstanding`. `pending`: the plan has not finished; call `runPlan()` again, and tell the
|
|
77
|
+
* user nothing final. The last three mean no step ran.
|
|
78
|
+
*/
|
|
79
|
+
export type PlanOutcome = {
|
|
80
|
+
readonly status: "completed";
|
|
81
|
+
readonly planId: string;
|
|
82
|
+
readonly effects: readonly string[];
|
|
83
|
+
} | {
|
|
84
|
+
readonly status: "failed_compensated";
|
|
85
|
+
readonly planId: string;
|
|
86
|
+
readonly failedStep: string;
|
|
87
|
+
readonly reason: PlanFailureReason;
|
|
88
|
+
readonly undone: readonly string[];
|
|
89
|
+
readonly next: string;
|
|
90
|
+
} | {
|
|
91
|
+
readonly status: "failed_needs_human";
|
|
92
|
+
readonly planId: string;
|
|
93
|
+
readonly failedStep: string;
|
|
94
|
+
readonly reason: PlanFailureReason;
|
|
95
|
+
readonly undone: readonly string[];
|
|
96
|
+
/** The steps that took effect and still hold. */
|
|
97
|
+
readonly held: readonly string[];
|
|
98
|
+
/** What a person must finish or undo: the stopped step, the steps not run, and any step not undone. */
|
|
99
|
+
readonly outstanding: readonly string[];
|
|
100
|
+
readonly avoid: string;
|
|
101
|
+
} | {
|
|
102
|
+
readonly status: "pending";
|
|
103
|
+
readonly planId: string;
|
|
104
|
+
/** `running`: a step is in flight or waiting for a retry. `pivot_unknown`: the pivot's result is not known. */
|
|
105
|
+
readonly phase: "running" | "pivot_unknown";
|
|
106
|
+
readonly stepId: string;
|
|
107
|
+
} | {
|
|
108
|
+
readonly status: "stale_approval" | "expired" | "rejected";
|
|
109
|
+
readonly planId: string;
|
|
110
|
+
readonly reason: string;
|
|
111
|
+
};
|
|
112
|
+
/**
|
|
113
|
+
* Runs the approved plan, in order, and reports what is true afterwards. Call it again with the same approval to
|
|
114
|
+
* resume a plan that stopped, crashed or came back `pending`: it reads the records, repeats no step, and carries on.
|
|
115
|
+
*
|
|
116
|
+
* - Before each step up to and including the pivot, the approval is verified, and a cancel stops the plan.
|
|
117
|
+
* - A step that fails before the pivot unwinds the steps that ran, in reverse, and the pivot never runs.
|
|
118
|
+
* - A pivot whose result is not known returns `pending` with `pivot_unknown`: nothing is undone, and nothing runs
|
|
119
|
+
* again under a fresh key. A later call reconciles it and, if it took effect, runs forward.
|
|
120
|
+
* - After the pivot nothing is undone: a step that can't finish is retried, or handed to a person.
|
|
121
|
+
*
|
|
122
|
+
* It throws a `SafetyError`, code `invalid_plan`, when the steps are not the signed ones or a compensable step has no
|
|
123
|
+
* `compensate`, and code `invalid_effect` for an empty scope field. A malformed or forged approval returns `rejected`.
|
|
124
|
+
*/
|
|
125
|
+
export declare function runPlan(options: RunPlanOptions): Promise<PlanOutcome>;
|
|
126
|
+
/**
|
|
127
|
+
* The write outcome a plan outcome stands for, in the five kinds the model already reads: `completed` is `applied`,
|
|
128
|
+
* `failed_compensated` is `compensated`, `failed_needs_human` is `partial`, `pending` is `unknown`, and the three
|
|
129
|
+
* statuses that mean no step ran are `not_applied`.
|
|
130
|
+
*/
|
|
131
|
+
export declare function planWriteOutcome(outcome: PlanOutcome): WriteOutcome;
|
|
132
|
+
/** Renders a plan outcome for the model: `planWriteOutcome()` through `renderOutcome()`. */
|
|
133
|
+
export declare function renderPlanOutcome(outcome: PlanOutcome): RenderedOutcome;
|