@parcha/agentrun-dsl 0.1.0-beta.12 → 0.1.0-beta.13
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/dist/author.d.ts +9 -2
- package/dist/author.js +6 -3
- package/dist/decision-receipts.d.ts +98 -0
- package/dist/decision-receipts.js +51 -0
- package/dist/index.d.ts +5 -3
- package/dist/index.js +2 -1
- package/dist/recovery/binding.d.ts +10 -0
- package/dist/recovery/binding.js +43 -0
- package/dist/recovery/call-key.d.ts +13 -0
- package/dist/recovery/call-key.js +24 -0
- package/dist/recovery/canonical-hash.d.ts +7 -0
- package/dist/recovery/canonical-hash.js +22 -0
- package/dist/recovery/driver.d.ts +186 -0
- package/dist/recovery/driver.js +777 -0
- package/dist/recovery/effect-failure.d.ts +34 -0
- package/dist/recovery/effect-failure.js +62 -0
- package/dist/recovery/errors.d.ts +31 -0
- package/dist/recovery/errors.js +51 -0
- package/dist/recovery/execution-path.d.ts +45 -0
- package/dist/recovery/execution-path.js +153 -0
- package/dist/recovery/file-store.d.ts +7 -0
- package/dist/recovery/file-store.js +131 -0
- package/dist/recovery/frozen-snapshot.d.ts +149 -0
- package/dist/recovery/frozen-snapshot.js +136 -0
- package/dist/recovery/handoff-block.d.ts +36 -0
- package/dist/recovery/handoff-block.js +148 -0
- package/dist/recovery/handoff-digest.d.ts +58 -0
- package/dist/recovery/handoff-digest.js +195 -0
- package/dist/recovery/handoff-files.d.ts +54 -0
- package/dist/recovery/handoff-files.js +162 -0
- package/dist/recovery/handoff-receipts.d.ts +42 -0
- package/dist/recovery/handoff-receipts.js +53 -0
- package/dist/recovery/handoff-redact.d.ts +12 -0
- package/dist/recovery/handoff-redact.js +44 -0
- package/dist/recovery/handoff.d.ts +44 -0
- package/dist/recovery/handoff.js +46 -0
- package/dist/recovery/index.d.ts +18 -0
- package/dist/recovery/index.js +16 -0
- package/dist/recovery/journal.d.ts +25 -0
- package/dist/recovery/journal.js +127 -0
- package/dist/recovery/memory-store.d.ts +4 -0
- package/dist/recovery/memory-store.js +20 -0
- package/dist/recovery/store.d.ts +81 -0
- package/dist/recovery/store.js +6 -0
- package/dist/recovery/testing/conformance.d.ts +4 -0
- package/dist/recovery/testing/conformance.js +213 -0
- package/dist/recovery/testing/crash-points.d.ts +18 -0
- package/dist/recovery/testing/crash-points.js +43 -0
- package/dist/recovery/testing/crash-sweep.d.ts +65 -0
- package/dist/recovery/testing/crash-sweep.js +146 -0
- package/dist/recovery/testing/index.d.ts +3 -0
- package/dist/recovery/testing/index.js +4 -0
- package/dist/recovery/testing/preload.d.ts +1 -0
- package/dist/recovery/testing/preload.js +3 -0
- package/dist/recovery/transport-facts.d.ts +23 -0
- package/dist/recovery/transport-facts.js +46 -0
- package/dist/recovery/with-recovery.d.ts +44 -0
- package/dist/recovery/with-recovery.js +84 -0
- package/dist/workflow.d.ts +28 -0
- package/dist/workflow.js +247 -87
- package/package.json +9 -1
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
export declare const FROZEN_SNAPSHOT_SCHEMA = "agentrun.frozen_run.v3";
|
|
2
|
+
type State = Record<string, unknown>;
|
|
3
|
+
/** What a question's receipts need beyond its answer: the request's producer invocation, its size and its
|
|
4
|
+
* latency. */
|
|
5
|
+
export type QuestionReceipts = {
|
|
6
|
+
invocation: string;
|
|
7
|
+
request_bytes: number;
|
|
8
|
+
latency_ms: number;
|
|
9
|
+
};
|
|
10
|
+
/** A committed route: the judge's answer for the route's question, whole, so a resume re-derives the
|
|
11
|
+
* same branch from it without asking again; the branch it runs (the node's unsure branch when the answer
|
|
12
|
+
* was unsure), with the answer's choice and the unsure flag beside it (a checkpoint that holds a decision
|
|
13
|
+
* without those two fields has neither: the driver derives all three from `result` when it opens). `receipts`
|
|
14
|
+
* is set in the commit that decides and cleared by the save after the host has written what it keeps of the
|
|
15
|
+
* answer: a resume that finds it set writes them, so a crash between the two never leaves the spend without
|
|
16
|
+
* its receipts. A host that keeps nothing commits null. */
|
|
17
|
+
export type RouteDecision = {
|
|
18
|
+
label: string;
|
|
19
|
+
branch: string;
|
|
20
|
+
choice: string;
|
|
21
|
+
unsure: boolean;
|
|
22
|
+
request_sha256: string | null;
|
|
23
|
+
result: Record<string, unknown>;
|
|
24
|
+
receipts: QuestionReceipts | null;
|
|
25
|
+
};
|
|
26
|
+
/** What one document's run committed, by execution path. `done` is every committed path in commit
|
|
27
|
+
* order; `states` keeps the committed state of the paths a resume may still be answered from (a
|
|
28
|
+
* chain's frontier step, a finished map item or parallel branch whose structure has not committed, a
|
|
29
|
+
* loop's iterations); `chains` names each chain's frontier; `loops` counts each loop's completed
|
|
30
|
+
* iterations; `routes` holds each route's committed decision; `inputs` binds each started, uncommitted
|
|
31
|
+
* path to the state it started from; `steps` holds each LLM step's execution record. */
|
|
32
|
+
export type PathFrame = {
|
|
33
|
+
/** The state the document started from, bound at its first resume: every later process starts the
|
|
34
|
+
* document from the same bytes or is refused. */
|
|
35
|
+
input: string | null;
|
|
36
|
+
done: string[];
|
|
37
|
+
states: Record<string, State>;
|
|
38
|
+
chains: Record<string, {
|
|
39
|
+
index: number;
|
|
40
|
+
path: string;
|
|
41
|
+
}>;
|
|
42
|
+
loops: Record<string, number>;
|
|
43
|
+
routes: Record<string, RouteDecision>;
|
|
44
|
+
inputs: Record<string, string>;
|
|
45
|
+
steps: Record<string, StepRecord>;
|
|
46
|
+
/** A map that ended on an item's failure: the finished items' results, keyed by the map's `as`, so
|
|
47
|
+
* the handoff carries the completed child work and a redispatch never loses it. */
|
|
48
|
+
partial?: {
|
|
49
|
+
path: string;
|
|
50
|
+
as: string;
|
|
51
|
+
results: unknown[];
|
|
52
|
+
};
|
|
53
|
+
};
|
|
54
|
+
/** The recovery driver's durable state. It lives whole in the journal; each commit replaces it. No run
|
|
55
|
+
* clock: clocks exist only per effect. */
|
|
56
|
+
export type FrozenSnapshot = {
|
|
57
|
+
schema: typeof FROZEN_SNAPSHOT_SCHEMA;
|
|
58
|
+
/** What the run of the workflow document committed. */
|
|
59
|
+
pin: PathFrame;
|
|
60
|
+
startedAt: number;
|
|
61
|
+
status: "running" | "paused" | "cancelled";
|
|
62
|
+
/** Effect-level clocks (poll windows, attempt deadlines), absolute, keyed by effect. */
|
|
63
|
+
clocks: Record<string, number>;
|
|
64
|
+
files: Record<string, string>;
|
|
65
|
+
unknownResponses?: Record<string, unknown>;
|
|
66
|
+
/** Spend by question nodes, which have no session of their own: metered per answer, carried with the frames. */
|
|
67
|
+
questionSpendUsd?: number;
|
|
68
|
+
/** The durable form of the escalation that ended the run; set once, reused on resume. */
|
|
69
|
+
escalation?: EscalationRow;
|
|
70
|
+
};
|
|
71
|
+
export type StepRecord = {
|
|
72
|
+
label: string;
|
|
73
|
+
attempt: number;
|
|
74
|
+
attemptsAllowed: number;
|
|
75
|
+
status: "running" | "closed" | "failed" | "submitted";
|
|
76
|
+
};
|
|
77
|
+
export type EscalationRow = {
|
|
78
|
+
kind: string;
|
|
79
|
+
stage: string;
|
|
80
|
+
summary: string;
|
|
81
|
+
state: Record<string, unknown>;
|
|
82
|
+
workflow_sha_used: string;
|
|
83
|
+
pin_sha256: string;
|
|
84
|
+
/** The node that ended the run: the gate that fired or the LLM step that failed. */
|
|
85
|
+
step_label: string;
|
|
86
|
+
step_exec_id: string | null;
|
|
87
|
+
cost_usd: number;
|
|
88
|
+
turns: number;
|
|
89
|
+
effect_calls: number;
|
|
90
|
+
evidence_dir: string;
|
|
91
|
+
/** The identity the continuation of an escalated run runs under. */
|
|
92
|
+
tail: string;
|
|
93
|
+
/** The escalation commit's revision: what the continuation binds on. */
|
|
94
|
+
revision: number;
|
|
95
|
+
/** The typed failure that ended the attempt, when one did: its code and its typed detail (a rail's
|
|
96
|
+
* limit), so the handoff keeps the classification a resume reads back. */
|
|
97
|
+
failure?: {
|
|
98
|
+
code: string;
|
|
99
|
+
detail?: Record<string, number | string>;
|
|
100
|
+
};
|
|
101
|
+
};
|
|
102
|
+
/** What a saved snapshot is checked against: whether a path resolves in the run's document. */
|
|
103
|
+
export type FrozenShape = {
|
|
104
|
+
resolves: (path: string) => boolean;
|
|
105
|
+
};
|
|
106
|
+
export declare const emptyPathFrame: () => PathFrame;
|
|
107
|
+
/** Refuses a saved snapshot the driver could not have produced for this run. */
|
|
108
|
+
export declare function validateFrozenSnapshot(saved: any, shape: FrozenShape): void;
|
|
109
|
+
/** The snapshot a driver runs under: the saved one (a paused run resumes running, retired keys
|
|
110
|
+
* dropped), or a fresh one. */
|
|
111
|
+
export declare function openedFrozenSnapshot(saved: FrozenSnapshot | null | undefined): FrozenSnapshot;
|
|
112
|
+
/** The snapshot as the journal stores it. Workflow state contains optional internal fields; this
|
|
113
|
+
* matches its JSON checkpoint semantics, while refusing non-finite values instead of silently
|
|
114
|
+
* changing them to null. */
|
|
115
|
+
export declare function serializeFrozenSnapshot(snapshot: FrozenSnapshot): FrozenSnapshot;
|
|
116
|
+
/** The namespace a frame's sessions and effects are named under. The driver writes `step`; `adapt` names the
|
|
117
|
+
* sessions and effects of a second document's frame in an older journal. */
|
|
118
|
+
export type FrameTag = "step" | "adapt";
|
|
119
|
+
/** The session an LLM step's attempt runs in: the step's label (for the reader: labels repeat across
|
|
120
|
+
* loop iterations and map items), its frame and execution path (what makes it unique), and the
|
|
121
|
+
* attempt. */
|
|
122
|
+
export declare function frozenStepSessionId(driver: string, label: string, frame: FrameTag, path: string, attempt: number): string;
|
|
123
|
+
/** A step's short identity where a name must be short and file-safe (its files, the continuation an
|
|
124
|
+
* escalation hands off to): a digest of its frame and execution path, so it is the same in every process. */
|
|
125
|
+
export declare function frozenStepId(frame: FrameTag, path: string): string;
|
|
126
|
+
/** The receipt id of a call's `ordinal`th effect at an execution path. */
|
|
127
|
+
export declare function frozenEffectId(frame: FrameTag, path: string, ordinal: number): string;
|
|
128
|
+
/** The execution path and ordinal an effect id names: the inverse of `frozenEffectId`. */
|
|
129
|
+
export declare function frozenEffectPath(id: string): {
|
|
130
|
+
path: string;
|
|
131
|
+
ordinal: number;
|
|
132
|
+
} | undefined;
|
|
133
|
+
/** An LLM step's execution record under admission. The first call fixes the label the interpreter
|
|
134
|
+
* names the step by and the retry limit; a later call gets the same
|
|
135
|
+
* record. A closed attempt advances to the next attempt here, and only here, when an admission asks
|
|
136
|
+
* and an attempt remains, else the step fails. `changed` says the snapshot owes a save. */
|
|
137
|
+
export declare function admitFrozenStep(steps: Record<string, StepRecord>, path: string, label: string, admission?: {
|
|
138
|
+
attemptsAllowed: number;
|
|
139
|
+
}): {
|
|
140
|
+
step: StepRecord;
|
|
141
|
+
changed: boolean;
|
|
142
|
+
};
|
|
143
|
+
/** The current attempt ended without a submission: `closed` until a retry is admitted, or
|
|
144
|
+
* `failed` when the failure is final or no attempt remains. */
|
|
145
|
+
export declare function closeFrozenStepAttempt(step: StepRecord, final: boolean): void;
|
|
146
|
+
/** The run-wide stop the driver applies: the host's pause or cancel it was handed, or null when it keeps
|
|
147
|
+
* running. A cancelled snapshot stays cancelled. */
|
|
148
|
+
export declare function frozenStop(status: FrozenSnapshot["status"], requested: "pause" | "cancel" | undefined): "paused" | "cancelled" | null;
|
|
149
|
+
export {};
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
// The recovery driver's durable state and its workflow-free transitions. Everything the driver runs is
|
|
2
|
+
// addressed by the interpreter's execution path, an opaque string here: the driver (`driver.ts`) reads
|
|
3
|
+
// the path grammar, maps nodes onto these records and owns the store's lifecycle.
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
5
|
+
import { RecoveryError } from "./errors.js";
|
|
6
|
+
const failure = (code, message) => new RecoveryError(message, code);
|
|
7
|
+
export const FROZEN_SNAPSHOT_SCHEMA = "agentrun.frozen_run.v3";
|
|
8
|
+
export const emptyPathFrame = () => ({ input: null, done: [], states: {}, chains: {}, loops: {}, routes: {}, inputs: {}, steps: {} });
|
|
9
|
+
const record = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
10
|
+
const SHA256 = /^[a-f0-9]{64}$/;
|
|
11
|
+
/** `value` as an object whose fields can be read, or null. */
|
|
12
|
+
const fields = (value) => record(value) ? value : null;
|
|
13
|
+
const entriesOf = (value) => { const object = fields(value); return object ? Object.entries(object) : null; };
|
|
14
|
+
const nonNegativeInt = (value) => Number.isSafeInteger(value) && value >= 0;
|
|
15
|
+
/** Whether a saved frame is one the driver could have written for its document. */
|
|
16
|
+
function validFrame(value, resolves) {
|
|
17
|
+
const frame = fields(value);
|
|
18
|
+
if (!frame || !Array.isArray(frame.done) || !frame.done.every((path) => typeof path === "string" && resolves(path)))
|
|
19
|
+
return false;
|
|
20
|
+
const doneList = frame.done;
|
|
21
|
+
const done = new Set(doneList);
|
|
22
|
+
if (done.size !== doneList.length)
|
|
23
|
+
return false;
|
|
24
|
+
if (!(frame.input === null ? doneList.length === 0 : typeof frame.input === "string" && SHA256.test(frame.input)))
|
|
25
|
+
return false;
|
|
26
|
+
const [states, chains, loops, routes, inputs, steps] = [frame.states, frame.chains, frame.loops, frame.routes, frame.inputs, frame.steps].map(entriesOf);
|
|
27
|
+
const partial = frame.partial === undefined ? undefined : fields(frame.partial);
|
|
28
|
+
return Boolean(states && states.every(([path, state]) => done.has(path) && record(state))
|
|
29
|
+
&& chains && chains.every(([, head]) => { const at = fields(head); return Boolean(at && nonNegativeInt(at.index) && typeof at.path === "string" && done.has(at.path)); })
|
|
30
|
+
&& loops && loops.every(([loop, count]) => resolves(loop) && nonNegativeInt(count))
|
|
31
|
+
&& routes && routes.every(([route, decision]) => {
|
|
32
|
+
const at = fields(decision);
|
|
33
|
+
const receipts = fields(at?.receipts);
|
|
34
|
+
return Boolean(at && resolves(route) && typeof at.label === "string" && typeof at.branch === "string" && ((typeof at.choice === "string" && typeof at.unsure === "boolean") || (at.choice === undefined && at.unsure === undefined)) && record(at.result) && (at.request_sha256 === null || typeof at.request_sha256 === "string")
|
|
35
|
+
&& (at.receipts === null || (receipts && typeof receipts.invocation === "string" && nonNegativeInt(receipts.request_bytes) && Number.isFinite(receipts.latency_ms))));
|
|
36
|
+
})
|
|
37
|
+
&& inputs && inputs.every(([path, digest]) => resolves(path) && !done.has(path) && typeof digest === "string" && SHA256.test(digest))
|
|
38
|
+
&& steps && steps.every(([path, step]) => {
|
|
39
|
+
const at = fields(step);
|
|
40
|
+
return Boolean(at && resolves(path) && typeof at.label === "string"
|
|
41
|
+
&& nonNegativeInt(at.attempt) && Number.isSafeInteger(at.attemptsAllowed) && at.attemptsAllowed >= 1
|
|
42
|
+
&& ["running", "closed", "failed", "submitted"].includes(String(at.status)));
|
|
43
|
+
})
|
|
44
|
+
&& (partial === undefined || (partial && typeof partial.path === "string" && resolves(partial.path) && typeof partial.as === "string" && Array.isArray(partial.results))));
|
|
45
|
+
}
|
|
46
|
+
/** Refuses a saved snapshot the driver could not have produced for this run. */
|
|
47
|
+
export function validateFrozenSnapshot(saved, shape) {
|
|
48
|
+
if (!record(saved) || saved.schema !== FROZEN_SNAPSHOT_SCHEMA || !Number.isFinite(saved.startedAt)
|
|
49
|
+
|| (saved.questionSpendUsd !== undefined && !(Number.isFinite(saved.questionSpendUsd) && saved.questionSpendUsd >= 0))
|
|
50
|
+
|| !["running", "paused", "cancelled"].includes(saved.status)
|
|
51
|
+
|| !record(saved.clocks) || !Object.values(saved.clocks).every(Number.isFinite)
|
|
52
|
+
|| !record(saved.files) || !Object.values(saved.files).every(value => typeof value === "string" && SHA256.test(value))
|
|
53
|
+
|| !validFrame(saved.pin, shape.resolves)
|
|
54
|
+
|| (saved.escalation !== undefined && (!record(saved.escalation) || typeof saved.escalation.tail !== "string" || typeof saved.escalation.kind !== "string" || !Number.isSafeInteger(saved.escalation.revision)))
|
|
55
|
+
// A checkpoint that holds a second document's frame is refused: the driver runs one document.
|
|
56
|
+
|| saved.adaptation !== undefined) {
|
|
57
|
+
throw failure("FROZEN_CHECKPOINT_INVALID", "Invalid frozen recovery checkpoint");
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
/** Keys an older journal may hold that the driver neither reads nor writes: dropped on open, so a
|
|
61
|
+
* checkpoint that has them does not carry them forward as stale counts. */
|
|
62
|
+
const RETIRED_SNAPSHOT_KEYS = ["unpricedQuestions", "effectCalls", "effectGrants", "effectSpendUsd", "effectHoldsUsd", "effectRecoveredUsd", "lookSpendUsd"];
|
|
63
|
+
/** The snapshot a driver runs under: the saved one (a paused run resumes running, retired keys
|
|
64
|
+
* dropped), or a fresh one. */
|
|
65
|
+
export function openedFrozenSnapshot(saved) {
|
|
66
|
+
const snapshot = saved ?? { schema: FROZEN_SNAPSHOT_SCHEMA, pin: emptyPathFrame(), startedAt: Date.now(), status: "running", clocks: {}, files: {} };
|
|
67
|
+
if (snapshot.status === "paused")
|
|
68
|
+
snapshot.status = "running";
|
|
69
|
+
for (const key of RETIRED_SNAPSHOT_KEYS)
|
|
70
|
+
delete snapshot[key];
|
|
71
|
+
return snapshot;
|
|
72
|
+
}
|
|
73
|
+
/** The snapshot as the journal stores it. Workflow state contains optional internal fields; this
|
|
74
|
+
* matches its JSON checkpoint semantics, while refusing non-finite values instead of silently
|
|
75
|
+
* changing them to null. */
|
|
76
|
+
export function serializeFrozenSnapshot(snapshot) {
|
|
77
|
+
return JSON.parse(JSON.stringify(snapshot, (_key, value) => {
|
|
78
|
+
if (typeof value === "number" && !Number.isFinite(value))
|
|
79
|
+
throw failure("FROZEN_CHECKPOINT_INVALID", "Non-finite workflow state");
|
|
80
|
+
return value;
|
|
81
|
+
}));
|
|
82
|
+
}
|
|
83
|
+
/** The session an LLM step's attempt runs in: the step's label (for the reader: labels repeat across
|
|
84
|
+
* loop iterations and map items), its frame and execution path (what makes it unique), and the
|
|
85
|
+
* attempt. */
|
|
86
|
+
export function frozenStepSessionId(driver, label, frame, path, attempt) {
|
|
87
|
+
return `${driver}:${label}:${frame}:${path}:a${attempt}`;
|
|
88
|
+
}
|
|
89
|
+
/** A step's short identity where a name must be short and file-safe (its files, the continuation an
|
|
90
|
+
* escalation hands off to): a digest of its frame and execution path, so it is the same in every process. */
|
|
91
|
+
export function frozenStepId(frame, path) {
|
|
92
|
+
return createHash("sha256").update(`${frame}:${path}`).digest("hex").slice(0, 10);
|
|
93
|
+
}
|
|
94
|
+
/** The receipt id of a call's `ordinal`th effect at an execution path. */
|
|
95
|
+
export function frozenEffectId(frame, path, ordinal) {
|
|
96
|
+
return `${frame}:${path}#call:${ordinal}`;
|
|
97
|
+
}
|
|
98
|
+
/** The execution path and ordinal an effect id names: the inverse of `frozenEffectId`. */
|
|
99
|
+
export function frozenEffectPath(id) {
|
|
100
|
+
const match = /^[^:]+:(.*)#call:(\d+)$/s.exec(id);
|
|
101
|
+
return match ? { path: match[1], ordinal: Number(match[2]) } : undefined;
|
|
102
|
+
}
|
|
103
|
+
/** An LLM step's execution record under admission. The first call fixes the label the interpreter
|
|
104
|
+
* names the step by and the retry limit; a later call gets the same
|
|
105
|
+
* record. A closed attempt advances to the next attempt here, and only here, when an admission asks
|
|
106
|
+
* and an attempt remains, else the step fails. `changed` says the snapshot owes a save. */
|
|
107
|
+
export function admitFrozenStep(steps, path, label, admission) {
|
|
108
|
+
let step = steps[path];
|
|
109
|
+
if (!step) {
|
|
110
|
+
if (!admission)
|
|
111
|
+
throw failure("FROZEN_PATH_INVALID", `The step at ${path} is admitted with its retry limit`);
|
|
112
|
+
step = { label, attempt: 0, attemptsAllowed: Math.max(1, admission.attemptsAllowed), status: "running" };
|
|
113
|
+
steps[path] = step;
|
|
114
|
+
return { step, changed: true };
|
|
115
|
+
}
|
|
116
|
+
if (step.status === "closed" && admission) {
|
|
117
|
+
if (step.attempt + 1 >= step.attemptsAllowed)
|
|
118
|
+
step.status = "failed";
|
|
119
|
+
else {
|
|
120
|
+
step.attempt += 1;
|
|
121
|
+
step.status = "running";
|
|
122
|
+
}
|
|
123
|
+
return { step, changed: true };
|
|
124
|
+
}
|
|
125
|
+
return { step, changed: false };
|
|
126
|
+
}
|
|
127
|
+
/** The current attempt ended without a submission: `closed` until a retry is admitted, or
|
|
128
|
+
* `failed` when the failure is final or no attempt remains. */
|
|
129
|
+
export function closeFrozenStepAttempt(step, final) {
|
|
130
|
+
step.status = final || step.attempt + 1 >= step.attemptsAllowed ? "failed" : "closed";
|
|
131
|
+
}
|
|
132
|
+
/** The run-wide stop the driver applies: the host's pause or cancel it was handed, or null when it keeps
|
|
133
|
+
* running. A cancelled snapshot stays cancelled. */
|
|
134
|
+
export function frozenStop(status, requested) {
|
|
135
|
+
return status === "cancelled" || requested === "cancel" ? "cancelled" : requested === "pause" ? "paused" : null;
|
|
136
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { type InputProvenance } from "./handoff-files.js";
|
|
2
|
+
/** What the block says of the escalation. */
|
|
3
|
+
export type HandoffBlockInput = {
|
|
4
|
+
kind: string;
|
|
5
|
+
stage: string;
|
|
6
|
+
summary: string;
|
|
7
|
+
step_label?: string | null;
|
|
8
|
+
step_exec_id?: string | null;
|
|
9
|
+
state?: Record<string, unknown> | null;
|
|
10
|
+
workflow_sha_used?: string | null;
|
|
11
|
+
cost_usd?: number | null;
|
|
12
|
+
evidence_dir?: string | null;
|
|
13
|
+
/** Where the attempt's report.md was moved, when one existed. */
|
|
14
|
+
report_path?: string | null;
|
|
15
|
+
/** Workspace-relative paths the attempt's files were written to. */
|
|
16
|
+
files?: readonly string[] | null;
|
|
17
|
+
/** Where each input the attempt started from came from, and its form. */
|
|
18
|
+
inputs?: readonly InputProvenance[] | null;
|
|
19
|
+
/** The host's sizes for the continuation, stated as one line. */
|
|
20
|
+
budget?: {
|
|
21
|
+
max_tool_calls?: number;
|
|
22
|
+
max_seconds?: number;
|
|
23
|
+
} | null;
|
|
24
|
+
};
|
|
25
|
+
/** The state at the gate is rendered whole up to this size; beyond it the block points at state.json. */
|
|
26
|
+
export declare const STATE_LIMIT: number;
|
|
27
|
+
/** Strings above the limit become a prefix plus a marker with the omitted length; nested values recurse. */
|
|
28
|
+
export declare function boundedValue(value: unknown, limit?: number): unknown;
|
|
29
|
+
/** One line per completed output in the state: the key the workflow wrote and the shape it holds. */
|
|
30
|
+
export declare function stateShapes(state: Record<string, unknown> | null | undefined): string[];
|
|
31
|
+
/** The one line that states the host's sizes for the continuation, or "" when the host sent none. */
|
|
32
|
+
export declare function escalationBudgetLine(budget: HandoffBlockInput["budget"]): string;
|
|
33
|
+
/** The block the continuation reads first. Deterministic for a given row; policy-agnostic. The reason is the
|
|
34
|
+
* workflow's own text, whole; the state at the gate is whole up to STATE_LIMIT, and beyond it the
|
|
35
|
+
* block points at the file that holds it. */
|
|
36
|
+
export declare function escalationContextBlock(context: HandoffBlockInput): string;
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { redactSensitiveValue, redactText } from "./handoff-redact.js";
|
|
3
|
+
import { HANDOFF_FILES_DIR } from "./handoff-files.js";
|
|
4
|
+
const VALUE_LIMIT = 400;
|
|
5
|
+
const ARRAY_LIMIT = 20;
|
|
6
|
+
/** The state at the gate is rendered whole up to this size; beyond it the block points at state.json. */
|
|
7
|
+
export const STATE_LIMIT = 48 * 1024;
|
|
8
|
+
/** The Files section lists this many paths, then counts the rest by directory. */
|
|
9
|
+
const FILES_LIST_LIMIT = 200;
|
|
10
|
+
const SHAPES_LIMIT = 3 * 1024;
|
|
11
|
+
const SHAPE_LINE_LIMIT = 160;
|
|
12
|
+
/** Strings above the limit become a prefix plus a marker with the omitted length; nested values recurse. */
|
|
13
|
+
export function boundedValue(value, limit = VALUE_LIMIT) {
|
|
14
|
+
if (typeof value === "string")
|
|
15
|
+
return value.length > limit ? `${value.slice(0, limit)}<${value.length - limit} more chars>` : value;
|
|
16
|
+
if (Array.isArray(value)) {
|
|
17
|
+
const head = value.slice(0, ARRAY_LIMIT).map(v => boundedValue(v, limit));
|
|
18
|
+
return value.length > ARRAY_LIMIT ? [...head, `<${value.length - ARRAY_LIMIT} more items>`] : head;
|
|
19
|
+
}
|
|
20
|
+
if (value && typeof value === "object")
|
|
21
|
+
return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, boundedValue(v, limit)]));
|
|
22
|
+
return value;
|
|
23
|
+
}
|
|
24
|
+
/** One line per completed output in the state: the key the workflow wrote and the shape it holds. */
|
|
25
|
+
export function stateShapes(state) {
|
|
26
|
+
if (!state || typeof state !== "object")
|
|
27
|
+
return [];
|
|
28
|
+
return Object.entries(state).map(([key, value]) => {
|
|
29
|
+
let line;
|
|
30
|
+
if (value === null || value === undefined)
|
|
31
|
+
line = `- ${key}: empty`;
|
|
32
|
+
else if (Array.isArray(value))
|
|
33
|
+
line = `- ${key}: array of ${value.length}`;
|
|
34
|
+
else if (typeof value === "object") {
|
|
35
|
+
const keys = Object.keys(value);
|
|
36
|
+
line = `- ${key}: object {${keys.slice(0, 12).join(", ")}${keys.length > 12 ? ", …" : ""}}`;
|
|
37
|
+
}
|
|
38
|
+
else if (typeof value === "string")
|
|
39
|
+
line = `- ${key}: string (${value.length} chars)`;
|
|
40
|
+
else
|
|
41
|
+
line = `- ${key}: ${typeof value}`;
|
|
42
|
+
return line.length > SHAPE_LINE_LIMIT ? `${line.slice(0, SHAPE_LINE_LIMIT)}…` : line;
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
/** The shapes section under its own budget: whole lines until the budget is spent, then a count. */
|
|
46
|
+
function shapesSection(shapes, budget) {
|
|
47
|
+
if (!shapes.length)
|
|
48
|
+
return ["- none"];
|
|
49
|
+
const kept = [];
|
|
50
|
+
let used = 0;
|
|
51
|
+
for (const line of shapes) {
|
|
52
|
+
if (used + line.length + 1 > budget)
|
|
53
|
+
break;
|
|
54
|
+
kept.push(line);
|
|
55
|
+
used += line.length + 1;
|
|
56
|
+
}
|
|
57
|
+
if (kept.length < shapes.length)
|
|
58
|
+
kept.push(`- …and ${shapes.length - kept.length} more keys (${shapes.length} in total)`);
|
|
59
|
+
return kept;
|
|
60
|
+
}
|
|
61
|
+
/** The block lists this many inputs, then counts the rest; inputs.json lists every one. */
|
|
62
|
+
const INPUT_LINE_LIMIT = 100;
|
|
63
|
+
const INPUT_VALUE_LIMIT = 200;
|
|
64
|
+
/** The inputs section: one line per input, its path, its form and its value (a long value by size). */
|
|
65
|
+
function inputsSection(inputs, filed) {
|
|
66
|
+
if (!inputs?.length)
|
|
67
|
+
return [];
|
|
68
|
+
const label = (form) => form === "email" ? "identifier (email address)" : form === "url" ? "identifier (URL)" : form === "text" ? "typed text" : form;
|
|
69
|
+
return ["", `Inputs the run started from, as the dispatch carried them (path: form: value)${filed ? `; whole in \`${HANDOFF_FILES_DIR}/inputs.json\`` : ""}. An identifier is a value of a fixed form a source can be matched on; typed text is what was written in:`,
|
|
70
|
+
...inputs.slice(0, INPUT_LINE_LIMIT).map((input) => `- ${input.path}: ${label(input.form)}: ${input.value.length > INPUT_VALUE_LIMIT ? `(${input.value.length} chars)` : input.value.replace(/\s+/g, " ")}`),
|
|
71
|
+
...(inputs.length > INPUT_LINE_LIMIT ? [`- …${inputs.length - INPUT_LINE_LIMIT} more inputs (${inputs.length} in total)${filed ? `, each with its path and form in \`${HANDOFF_FILES_DIR}/inputs.json\`` : ""}`] : [])];
|
|
72
|
+
}
|
|
73
|
+
/** The one line that states the host's sizes for the continuation, or "" when the host sent none. */
|
|
74
|
+
export function escalationBudgetLine(budget) {
|
|
75
|
+
if (!budget)
|
|
76
|
+
return "";
|
|
77
|
+
const sizes = [
|
|
78
|
+
...(budget.max_tool_calls !== undefined ? [`${budget.max_tool_calls} external tool calls`] : []),
|
|
79
|
+
...(budget.max_seconds !== undefined ? [`${budget.max_seconds} seconds`] : []),
|
|
80
|
+
];
|
|
81
|
+
return sizes.length ? `Budget for this continuation (set by the host): ${sizes.join(" and ")}.` : "";
|
|
82
|
+
}
|
|
83
|
+
/** The Files section: every path the attempt left for the continuation. */
|
|
84
|
+
function filesSection(context) {
|
|
85
|
+
const frozen = [...(context.files ?? [])];
|
|
86
|
+
const lines = [];
|
|
87
|
+
const described = {
|
|
88
|
+
[`${HANDOFF_FILES_DIR}/state.json`]: "the workflow state at the gate, whole",
|
|
89
|
+
[`${HANDOFF_FILES_DIR}/gate.json`]: "the gate: kind, stage, step, reason, its state and every committed route decision",
|
|
90
|
+
[`${HANDOFF_FILES_DIR}/inputs.json`]: "the inputs the frozen attempt started from, with each one's path and form",
|
|
91
|
+
};
|
|
92
|
+
const shown = frozen.slice(0, FILES_LIST_LIMIT);
|
|
93
|
+
for (const file of shown)
|
|
94
|
+
lines.push(`- ${file}${described[file] ? `: ${described[file]}` : ""}`);
|
|
95
|
+
if (frozen.length > shown.length) {
|
|
96
|
+
const rest = new Map();
|
|
97
|
+
for (const file of frozen.slice(shown.length)) {
|
|
98
|
+
const dir = path.posix.dirname(file);
|
|
99
|
+
rest.set(dir, (rest.get(dir) ?? 0) + 1);
|
|
100
|
+
}
|
|
101
|
+
for (const [dir, count] of rest)
|
|
102
|
+
lines.push(`- …${count} more under ${dir}/`);
|
|
103
|
+
}
|
|
104
|
+
if (!lines.length)
|
|
105
|
+
return [];
|
|
106
|
+
const items = frozen.some((file) => file.startsWith(`${HANDOFF_FILES_DIR}/items/`));
|
|
107
|
+
const effects = frozen.some((file) => file.startsWith(`${HANDOFF_FILES_DIR}/effects/`));
|
|
108
|
+
return ["", "Files the frozen attempt left in the workspace (read them; they are whole where this text is not):",
|
|
109
|
+
...(items ? [`Each file under ${HANDOFF_FILES_DIR}/items/ is one record the workflow judged, with its text and its scores.`] : []),
|
|
110
|
+
...(effects ? [`Each file under ${HANDOFF_FILES_DIR}/effects/ is one paid call: its arguments and its full result.`] : []),
|
|
111
|
+
...lines];
|
|
112
|
+
}
|
|
113
|
+
/** The block the continuation reads first. Deterministic for a given row; policy-agnostic. The reason is the
|
|
114
|
+
* workflow's own text, whole; the state at the gate is whole up to STATE_LIMIT, and beyond it the
|
|
115
|
+
* block points at the file that holds it. */
|
|
116
|
+
export function escalationContextBlock(context) {
|
|
117
|
+
const step = context.step_label ?? context.stage;
|
|
118
|
+
const summary = redactText(String(context.summary || "").trim()) || "(no summary recorded)";
|
|
119
|
+
const budget = escalationBudgetLine(context.budget);
|
|
120
|
+
const header = [
|
|
121
|
+
"## YOU ARE CONTINUING A RUN THAT ESCALATED",
|
|
122
|
+
"",
|
|
123
|
+
`A reviewed workflow${context.workflow_sha_used ? ` (${String(context.workflow_sha_used).slice(0, 12)})` : ""} ran first and stopped at step \`${step}\`${context.step_exec_id ? ` (execution ${context.step_exec_id})` : ""}: ${context.kind}${context.stage && context.stage !== step ? ` at stage ${context.stage}` : ""}.`,
|
|
124
|
+
"",
|
|
125
|
+
"Why it stopped:",
|
|
126
|
+
summary,
|
|
127
|
+
...(budget ? ["", budget] : []),
|
|
128
|
+
"",
|
|
129
|
+
];
|
|
130
|
+
const footer = [
|
|
131
|
+
"",
|
|
132
|
+
...(context.evidence_dir ? [`Evidence gathered so far is under \`${context.evidence_dir}\`.`] : []),
|
|
133
|
+
...(context.report_path ? [`The frozen attempt's report was moved to \`${context.report_path}\`.`] : []),
|
|
134
|
+
...(typeof context.cost_usd === "number"
|
|
135
|
+
? [`The frozen attempt spent $${context.cost_usd.toFixed(4)}.`]
|
|
136
|
+
: []),
|
|
137
|
+
"",
|
|
138
|
+
"Continue the job from this state. Do not redo completed work; build on it. When you explain what happened, cite this escalation (its step and reason) rather than inventing a cause.",
|
|
139
|
+
];
|
|
140
|
+
const shapes = shapesSection(stateShapes(context.state), SHAPES_LIMIT);
|
|
141
|
+
const stateFile = (context.files ?? []).includes(`${HANDOFF_FILES_DIR}/state.json`) ? `${HANDOFF_FILES_DIR}/state.json` : null;
|
|
142
|
+
const stateJson = JSON.stringify(redactSensitiveValue(context.state ?? {}), null, 2);
|
|
143
|
+
const state = stateJson.length <= STATE_LIMIT
|
|
144
|
+
? ["", `State at the gate (whole${stateFile ? `; also in \`${stateFile}\`` : ""}):`, "```json", stateJson, "```"]
|
|
145
|
+
: ["", `State body is ${stateJson.length} chars (${Object.keys(context.state ?? {}).length} keys), beyond what this text carries; ${stateFile ? `read it whole in \`${stateFile}\`` : "the list above names every key with its type and size"}.`];
|
|
146
|
+
const filedInputs = (context.files ?? []).includes(`${HANDOFF_FILES_DIR}/inputs.json`);
|
|
147
|
+
return redactText([...header, "Completed outputs it left in the workflow state (do not redo this work):", ...shapes, ...state, ...inputsSection(context.inputs, filedInputs), ...filesSection(context), ...footer].join("\n"));
|
|
148
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/** One step's transcript message, as a host's reader returns it. */
|
|
2
|
+
export type TranscriptMessage = {
|
|
3
|
+
role: "user" | "assistant" | "toolResult";
|
|
4
|
+
content?: unknown;
|
|
5
|
+
toolCallId?: string;
|
|
6
|
+
toolName?: string;
|
|
7
|
+
isError?: boolean;
|
|
8
|
+
stopReason?: string;
|
|
9
|
+
};
|
|
10
|
+
export declare const DIGEST_STEP_LIMIT: number;
|
|
11
|
+
export declare const DIGEST_LIMIT: number;
|
|
12
|
+
/** A step's spend: `usd` is a floor when `state` is `partial` and unknown when null; a spend recorded without a state
|
|
13
|
+
* (a recorded trace's `session.spent` row) is complete. */
|
|
14
|
+
export type InheritedSession = {
|
|
15
|
+
id: string;
|
|
16
|
+
role: string;
|
|
17
|
+
state: string;
|
|
18
|
+
file: string | null;
|
|
19
|
+
spend?: {
|
|
20
|
+
usd: number | null;
|
|
21
|
+
turns: number;
|
|
22
|
+
state?: "complete" | "partial" | "unavailable";
|
|
23
|
+
toolCalls?: number;
|
|
24
|
+
};
|
|
25
|
+
};
|
|
26
|
+
export type InheritedEffect = {
|
|
27
|
+
id: string;
|
|
28
|
+
name: string;
|
|
29
|
+
status: string;
|
|
30
|
+
session?: string | null;
|
|
31
|
+
result?: unknown;
|
|
32
|
+
};
|
|
33
|
+
export type InheritedJob = {
|
|
34
|
+
runId: string;
|
|
35
|
+
/** A step's transcript by its session id (the run's durable file holds them), or null when there is none. */
|
|
36
|
+
transcriptOf: (sessionId: string) => readonly TranscriptMessage[] | null;
|
|
37
|
+
cwd: string;
|
|
38
|
+
evidenceDir?: string | null;
|
|
39
|
+
sessions: InheritedSession[];
|
|
40
|
+
effects: InheritedEffect[];
|
|
41
|
+
/** Workspace-relative produced files with the sha256 the driver committed for them. */
|
|
42
|
+
files: Record<string, string>;
|
|
43
|
+
/** The file writeFrozenEvidence wrote each effect's whole receipt to, by effect id. */
|
|
44
|
+
effectFiles?: Record<string, string>;
|
|
45
|
+
};
|
|
46
|
+
/** The label a step's identity carries, distinct for every session the frozen driver admits. A step's
|
|
47
|
+
* session is `<run>:<label>:<step|adapt>:<execution path>:a<attempt>` (the label as the
|
|
48
|
+
* interpreter names the node: a child's step `invocation/step`, a plan's `adapt:<gate>/step`, and a
|
|
49
|
+
* label may hold colons), read as the label with each map item index its path runs under as `[k]` and
|
|
50
|
+
* each loop iteration as `#k`. */
|
|
51
|
+
export declare function stepLabelOf(runId: string, sessionId: string): string | null;
|
|
52
|
+
/** One completed LLM step, from its transcript (`transcriptOf`): what it was asked, what it called, what it concluded and
|
|
53
|
+
* what it submitted. Bounded per step; a step whose transcript is absent or unreadable says so. */
|
|
54
|
+
export declare function stepDigest(runId: string, session: InheritedSession, transcriptOf: (sessionId: string) => readonly TranscriptMessage[] | null): string;
|
|
55
|
+
/** The digest the continuation reads after the escalation block: the completed
|
|
56
|
+
* LLM steps' transcripts, the evidence gathered, the files produced with their receipts, and the
|
|
57
|
+
* one rule that this is a continuation. Deterministic for a given ledger and workspace. */
|
|
58
|
+
export declare function inheritedJobDigest(job: InheritedJob): string;
|