@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,46 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { escalationContextBlock } from "./handoff-block.js";
|
|
4
|
+
import { inheritedJobDigest } from "./handoff-digest.js";
|
|
5
|
+
import { HANDOFF_FILES_DIR, inputProvenance, writeHandoffFiles } from "./handoff-files.js";
|
|
6
|
+
import { inheritableReceipts, inheritableUnknowns } from "./handoff-receipts.js";
|
|
7
|
+
/** The one place a handoff is built: the escalation row and effects of an open journal, rendered as the continuation's
|
|
8
|
+
* first turn. The row must be one the driver committed. Deterministic for a journal and a workspace. */
|
|
9
|
+
export async function buildHandoff(journal, options) {
|
|
10
|
+
const snapshot = journal.state;
|
|
11
|
+
const row = snapshot?.escalation;
|
|
12
|
+
if (!row)
|
|
13
|
+
throw new Error("A handoff is built from an escalation the driver committed");
|
|
14
|
+
const effects = journal.effects();
|
|
15
|
+
const routes = snapshot?.pin?.routes && typeof snapshot.pin.routes === "object" && !Array.isArray(snapshot.pin.routes) ? { ...snapshot.pin.routes } : {};
|
|
16
|
+
let files = [];
|
|
17
|
+
let effectFiles = {};
|
|
18
|
+
let filesError;
|
|
19
|
+
try {
|
|
20
|
+
({ files, effectFiles } = await writeHandoffFiles(options.cwd, row, { effects, routes }, options.input));
|
|
21
|
+
}
|
|
22
|
+
catch (error) {
|
|
23
|
+
filesError = String(error?.message ?? error);
|
|
24
|
+
}
|
|
25
|
+
const evidenceDir = path.join(options.cwd, "evidence");
|
|
26
|
+
const gathered = await fs.readdir(evidenceDir).then((names) => names.some((name) => name !== path.basename(HANDOFF_FILES_DIR)), () => false);
|
|
27
|
+
const evidence = gathered ? (row.evidence_dir ?? evidenceDir) : null;
|
|
28
|
+
const block = escalationContextBlock({ ...row, evidence_dir: evidence, report_path: options.reportPath ?? null, files,
|
|
29
|
+
inputs: options.input === undefined ? [] : inputProvenance(options.input), budget: options.budget ?? null });
|
|
30
|
+
let digest = null;
|
|
31
|
+
let digestError;
|
|
32
|
+
try {
|
|
33
|
+
digest = inheritedJobDigest({
|
|
34
|
+
runId: options.runId, transcriptOf: options.transcriptOf ?? (() => null), cwd: options.cwd, evidenceDir: evidence,
|
|
35
|
+
sessions: [...(options.sessions ?? [])],
|
|
36
|
+
effects: effects.map((e) => ({ id: e.id, name: e.name, status: e.status, ...(e.status === "completed" ? { result: e.result } : {}) })),
|
|
37
|
+
files: snapshot?.files && typeof snapshot.files === "object" ? snapshot.files : {}, effectFiles,
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
digestError = `digest unavailable: ${String(error?.message ?? error)}`;
|
|
42
|
+
}
|
|
43
|
+
return { block, digest, files, receipts: inheritableReceipts(effects), unknown: inheritableUnknowns(effects), ...(filesError ? { filesError } : {}), ...(digestError && digest === null ? { digestError } : {}) };
|
|
44
|
+
}
|
|
45
|
+
/** The continuation's first turn: the escalation block, then the digest. Deterministic from its inputs. */
|
|
46
|
+
export const handoffFirstTurn = (handoff) => [handoff.block, handoff.digest].filter(Boolean).join("\n\n");
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export type { RecoveryBinding, RecoveryEffect, RecoveryIntent, RecoveryJournal, RecoveryNote, RecoveryStore } from "./store.js";
|
|
2
|
+
export { openRecovery, recoveryBinding, recoveryBound, routeTaken, workspaceFiles, type RecoveryEffectParams, type RecoveryFiles, type RecoveryOptions, type RecoveryStop } from "./driver.js";
|
|
3
|
+
export { withRecovery, type RecoveryAdapters, type RecoveryDriver, type RecoveryNodeParams, type RecoveryStep, type WithRecoveryOptions } from "./with-recovery.js";
|
|
4
|
+
export { memoryStore } from "./memory-store.js";
|
|
5
|
+
export { fileStore } from "./file-store.js";
|
|
6
|
+
export { openJournal, type JournalBackend, type JournalRecord } from "./journal.js";
|
|
7
|
+
export { RecoveryError, asRecoveryError, isRecoveryError, runStopOf, runStoppedError } from "./errors.js";
|
|
8
|
+
export { bindingDigests, bindingMismatch, LEDGER_FORMAT } from "./binding.js";
|
|
9
|
+
export { canonicalHash, canonicalSha256 } from "./canonical-hash.js";
|
|
10
|
+
export { callKey, heldCallKey, CALL_KEY_BYTES } from "./call-key.js";
|
|
11
|
+
export { FROZEN_SNAPSHOT_SCHEMA, validateFrozenSnapshot, openedFrozenSnapshot, serializeFrozenSnapshot, emptyPathFrame, frozenStepSessionId, frozenStepId, frozenEffectId, frozenEffectPath, admitFrozenStep, closeFrozenStepAttempt, frozenStop, type FrozenSnapshot, type PathFrame, type RouteDecision, type QuestionReceipts, type FrameTag, type StepRecord, type EscalationRow, type FrozenShape, } from "./frozen-snapshot.js";
|
|
12
|
+
export { chainStep, childrenOf, completedIteration, enclosingChains, enclosingIterations, isWithin, nodeAt, pathSegments, topLevelCompletion } from "./execution-path.js";
|
|
13
|
+
export { TypedEffectFailure, EffectEnvelopeFailure, classifyEffectFailure } from "./effect-failure.js";
|
|
14
|
+
export { effectRetryClass, transportFactOf, type TransportFact } from "./transport-facts.js";
|
|
15
|
+
export { buildHandoff, handoffFirstTurn, type Handoff, type HandoffOptions } from "./handoff.js";
|
|
16
|
+
export { gatewayIntentOf, inheritableReceipts, inheritableUnknowns, returnedFailure, type InheritedReceipt, type InheritedUnknown } from "./handoff-receipts.js";
|
|
17
|
+
export { inputProvenance, judgedRecords, type InputProvenance } from "./handoff-files.js";
|
|
18
|
+
export { type InheritedSession, type InheritedEffect, type TranscriptMessage } from "./handoff-digest.js";
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export { openRecovery, recoveryBinding, recoveryBound, routeTaken, workspaceFiles } from "./driver.js";
|
|
2
|
+
export { withRecovery } from "./with-recovery.js";
|
|
3
|
+
export { memoryStore } from "./memory-store.js";
|
|
4
|
+
export { fileStore } from "./file-store.js";
|
|
5
|
+
export { openJournal } from "./journal.js";
|
|
6
|
+
export { RecoveryError, asRecoveryError, isRecoveryError, runStopOf, runStoppedError } from "./errors.js";
|
|
7
|
+
export { bindingDigests, bindingMismatch, LEDGER_FORMAT } from "./binding.js";
|
|
8
|
+
export { canonicalHash, canonicalSha256 } from "./canonical-hash.js";
|
|
9
|
+
export { callKey, heldCallKey, CALL_KEY_BYTES } from "./call-key.js";
|
|
10
|
+
export { FROZEN_SNAPSHOT_SCHEMA, validateFrozenSnapshot, openedFrozenSnapshot, serializeFrozenSnapshot, emptyPathFrame, frozenStepSessionId, frozenStepId, frozenEffectId, frozenEffectPath, admitFrozenStep, closeFrozenStepAttempt, frozenStop, } from "./frozen-snapshot.js";
|
|
11
|
+
export { chainStep, childrenOf, completedIteration, enclosingChains, enclosingIterations, isWithin, nodeAt, pathSegments, topLevelCompletion } from "./execution-path.js";
|
|
12
|
+
export { TypedEffectFailure, EffectEnvelopeFailure, classifyEffectFailure } from "./effect-failure.js";
|
|
13
|
+
export { effectRetryClass, transportFactOf } from "./transport-facts.js";
|
|
14
|
+
export { buildHandoff, handoffFirstTurn } from "./handoff.js";
|
|
15
|
+
export { gatewayIntentOf, inheritableReceipts, inheritableUnknowns, returnedFailure } from "./handoff-receipts.js";
|
|
16
|
+
export { inputProvenance, judgedRecords } from "./handoff-files.js";
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { RecoveryBinding, RecoveryEffect, RecoveryJournal, RecoveryNote } from "./store.js";
|
|
2
|
+
/** A journal as a backend keeps it: what it is bound to, who owns it, its state, its notes, and its effects in
|
|
3
|
+
* admission order, each with the outside calls it made. */
|
|
4
|
+
export type JournalRecord = {
|
|
5
|
+
binding: string | null;
|
|
6
|
+
inputs: Record<string, string> | null;
|
|
7
|
+
generation: number;
|
|
8
|
+
revision: number;
|
|
9
|
+
state: unknown;
|
|
10
|
+
notes: RecoveryNote[];
|
|
11
|
+
effects: Array<RecoveryEffect & {
|
|
12
|
+
calls?: unknown;
|
|
13
|
+
}>;
|
|
14
|
+
};
|
|
15
|
+
export type JournalBackend = {
|
|
16
|
+
/** Take the journal for one owner, or throw when it has a live one. Resolves to what lets go of it. */
|
|
17
|
+
acquire(): Promise<() => Promise<void>>;
|
|
18
|
+
/** The record as the last `write` left it, or undefined before the first. The caller may change what it gets. */
|
|
19
|
+
read(): Promise<JournalRecord | undefined>;
|
|
20
|
+
/** Replace the record: whole or not at all, and durable before the promise resolves. */
|
|
21
|
+
write(record: JournalRecord): Promise<void>;
|
|
22
|
+
};
|
|
23
|
+
/** Open the journal a backend keeps and take ownership of it: a journal with a live owner refuses, a binding that
|
|
24
|
+
* differs refuses naming the inputs that moved, and the generation advances. */
|
|
25
|
+
export declare function openJournal(backend: JournalBackend, bound: RecoveryBinding): Promise<RecoveryJournal>;
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
// A journal over a record that a backend keeps whole: ownership, the generation check, the revision counter and the
|
|
2
|
+
// six writes. A backend only takes the journal for one owner, reads the record and replaces it, whole and durably.
|
|
3
|
+
// The memory store and the file store are this journal over two backends.
|
|
4
|
+
import { bindingMismatch } from "./binding.js";
|
|
5
|
+
import { RecoveryError, asRecoveryError } from "./errors.js";
|
|
6
|
+
/** A value as a journal stores it: plain JSON, every number finite. */
|
|
7
|
+
function json(value) {
|
|
8
|
+
return value === undefined ? null : JSON.parse(JSON.stringify(value, (_key, item) => {
|
|
9
|
+
if (typeof item === "bigint" || typeof item === "function" || typeof item === "symbol" || (typeof item === "number" && !Number.isFinite(item))) {
|
|
10
|
+
throw new RecoveryError("A journal holds finite JSON values only");
|
|
11
|
+
}
|
|
12
|
+
return item;
|
|
13
|
+
}));
|
|
14
|
+
}
|
|
15
|
+
const publicEffect = ({ id, name, argsHash, status, session, result, intent, args, calls }) => ({ id, name, argsHash, status, session, result, ...(intent ? { intent: { tool: intent.tool, argsHash: intent.argsHash } } : {}), ...(args !== undefined ? { args } : {}), ...(Array.isArray(calls) ? { calls } : {}) });
|
|
16
|
+
/** Open the journal a backend keeps and take ownership of it: a journal with a live owner refuses, a binding that
|
|
17
|
+
* differs refuses naming the inputs that moved, and the generation advances. */
|
|
18
|
+
export async function openJournal(backend, bound) {
|
|
19
|
+
const release = await backend.acquire();
|
|
20
|
+
let opened;
|
|
21
|
+
let existing;
|
|
22
|
+
try {
|
|
23
|
+
opened = (await backend.read()) ?? { binding: null, inputs: null, generation: 0, revision: 0, state: null, notes: [], effects: [] };
|
|
24
|
+
existing = opened.binding !== null;
|
|
25
|
+
if (existing && opened.binding !== bound.binding)
|
|
26
|
+
throw bindingMismatch(opened.inputs ? JSON.stringify(opened.inputs) : null, bound.inputs);
|
|
27
|
+
if (!existing) {
|
|
28
|
+
opened.binding = bound.binding;
|
|
29
|
+
opened.inputs = bound.inputs ? { ...bound.inputs } : null;
|
|
30
|
+
}
|
|
31
|
+
opened.generation += 1;
|
|
32
|
+
await backend.write(opened);
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
await release();
|
|
36
|
+
throw asRecoveryError(error);
|
|
37
|
+
}
|
|
38
|
+
const generation = opened.generation;
|
|
39
|
+
const effects = new Map(opened.effects.map((effect) => [effect.id, publicEffect(effect)]));
|
|
40
|
+
const notes = [...opened.notes];
|
|
41
|
+
let revision = opened.revision;
|
|
42
|
+
let closed = false;
|
|
43
|
+
/** Writes run one at a time, in the order they were asked for, each with its checks: two asked for together never
|
|
44
|
+
* both pass a check the first one's commit would fail. A failed write does not stop the next, and one asked for
|
|
45
|
+
* before `close` still lands. */
|
|
46
|
+
let queue = Promise.resolve();
|
|
47
|
+
const inOrder = (write) => {
|
|
48
|
+
if (closed)
|
|
49
|
+
return Promise.reject(new RecoveryError("The journal is closed"));
|
|
50
|
+
const done = queue.then(write).catch((error) => { throw asRecoveryError(error); });
|
|
51
|
+
queue = done.catch(() => undefined);
|
|
52
|
+
return done;
|
|
53
|
+
};
|
|
54
|
+
/** One commit, inside a write: it checks this open still owns the journal, advances the revision, and lets `change`
|
|
55
|
+
* alter the record with that revision. The record is replaced only when `change` returns. */
|
|
56
|
+
const commit = async (change) => {
|
|
57
|
+
const record = await backend.read();
|
|
58
|
+
if (!record || record.generation !== generation)
|
|
59
|
+
throw new RecoveryError("Run owner generation is not acquired");
|
|
60
|
+
const next = record.revision + 1;
|
|
61
|
+
change(record, next);
|
|
62
|
+
record.revision = next;
|
|
63
|
+
await backend.write(record);
|
|
64
|
+
revision = next;
|
|
65
|
+
return next;
|
|
66
|
+
};
|
|
67
|
+
const stored = (record, id) => record.effects.find((effect) => effect.id === id);
|
|
68
|
+
return {
|
|
69
|
+
existing, generation, state: json(opened.state),
|
|
70
|
+
get revision() { return revision; },
|
|
71
|
+
effects: () => [...effects.values()],
|
|
72
|
+
effect: (id) => effects.get(id),
|
|
73
|
+
notes: () => [...notes],
|
|
74
|
+
save: (state, note) => inOrder(async () => {
|
|
75
|
+
let entry;
|
|
76
|
+
const committed = await commit((record, next) => {
|
|
77
|
+
record.state = json(typeof state === "function" ? state(next) : state);
|
|
78
|
+
if (note) {
|
|
79
|
+
entry = { revision: next, kind: note.kind, detail: json(note.detail), at: new Date().toISOString() };
|
|
80
|
+
record.notes.push(entry);
|
|
81
|
+
}
|
|
82
|
+
});
|
|
83
|
+
if (entry)
|
|
84
|
+
notes.push(entry);
|
|
85
|
+
return committed;
|
|
86
|
+
}),
|
|
87
|
+
note: (kind, detail) => inOrder(async () => {
|
|
88
|
+
const entry = { kind, detail: json(detail), at: new Date().toISOString() };
|
|
89
|
+
const committed = await commit((record, next) => { record.notes.push({ revision: next, ...entry }); });
|
|
90
|
+
notes.push({ revision: committed, ...entry });
|
|
91
|
+
return committed;
|
|
92
|
+
}),
|
|
93
|
+
admit: (id, name, argsHash, state, session = null, intent, args) => inOrder(async () => {
|
|
94
|
+
const known = effects.get(id);
|
|
95
|
+
if (known)
|
|
96
|
+
return known;
|
|
97
|
+
const effect = { id, name, argsHash, status: "unknown", session, result: null, ...(intent ? { intent: json(intent) } : {}), ...(args !== undefined ? { args: json(args) } : {}) };
|
|
98
|
+
await commit((record) => { record.effects.push({ ...effect }); record.state = json(state); });
|
|
99
|
+
effects.set(id, effect);
|
|
100
|
+
return "new";
|
|
101
|
+
}),
|
|
102
|
+
complete: (id, result, state = opened.state) => inOrder(async () => {
|
|
103
|
+
const known = effects.get(id);
|
|
104
|
+
if (!known)
|
|
105
|
+
throw new RecoveryError(`Effect ${id} completes without an admission`);
|
|
106
|
+
if (known.status === "completed")
|
|
107
|
+
throw new RecoveryError(`Effect ${id} completes once`);
|
|
108
|
+
const value = json(result);
|
|
109
|
+
await commit((record) => { Object.assign(stored(record, id), { status: "completed", result: value }); record.state = json(state); });
|
|
110
|
+
effects.set(id, { ...known, status: "completed", result: value });
|
|
111
|
+
}),
|
|
112
|
+
called: (id, calls) => inOrder(async () => {
|
|
113
|
+
if (!effects.has(id))
|
|
114
|
+
throw new RecoveryError(`Effect ${id} records calls without an admission`);
|
|
115
|
+
const value = json(calls);
|
|
116
|
+
await commit((record) => { stored(record, id).calls = value; });
|
|
117
|
+
effects.set(id, { ...effects.get(id), ...(Array.isArray(value) ? { calls: value } : {}) });
|
|
118
|
+
}),
|
|
119
|
+
async close() {
|
|
120
|
+
if (closed)
|
|
121
|
+
return;
|
|
122
|
+
closed = true;
|
|
123
|
+
await queue;
|
|
124
|
+
await release();
|
|
125
|
+
},
|
|
126
|
+
};
|
|
127
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { RecoveryError } from "./errors.js";
|
|
2
|
+
import { openJournal } from "./journal.js";
|
|
3
|
+
/** A store that keeps one run's journal in this process: for tests, and for a host that wants the driver's rules
|
|
4
|
+
* within one process and no resume after it. */
|
|
5
|
+
export function memoryStore() {
|
|
6
|
+
let record;
|
|
7
|
+
let owned = false;
|
|
8
|
+
return {
|
|
9
|
+
open: (bound) => openJournal({
|
|
10
|
+
async acquire() {
|
|
11
|
+
if (owned)
|
|
12
|
+
throw new RecoveryError("Run already has a live owner");
|
|
13
|
+
owned = true;
|
|
14
|
+
return async () => { owned = false; };
|
|
15
|
+
},
|
|
16
|
+
read: async () => record && structuredClone(record),
|
|
17
|
+
write: async (next) => { record = structuredClone(next); },
|
|
18
|
+
}, bound),
|
|
19
|
+
};
|
|
20
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/** What a journal is bound to: one digest over everything that must not change between two opens of the same run, and
|
|
2
|
+
* the digest of each input it covers, by name, so that a refused open names the inputs that moved. */
|
|
3
|
+
export type RecoveryBinding = {
|
|
4
|
+
binding: string;
|
|
5
|
+
inputs?: Record<string, string>;
|
|
6
|
+
};
|
|
7
|
+
/** A decision recorded beside the state, with the revision of the commit that wrote it. */
|
|
8
|
+
export type RecoveryNote = {
|
|
9
|
+
revision: number;
|
|
10
|
+
kind: "escalation" | "handoff" | "inherited";
|
|
11
|
+
detail: unknown;
|
|
12
|
+
at: string;
|
|
13
|
+
};
|
|
14
|
+
/** The external call an effect stands for: the tool it calls and the hash of the arguments it calls it with
|
|
15
|
+
* (`canonicalHash` of the arguments). A continuation's own call is keyed the same way, so a call that repeats an
|
|
16
|
+
* effect is known for one whatever the effect's status. */
|
|
17
|
+
export type RecoveryIntent = {
|
|
18
|
+
tool: string;
|
|
19
|
+
argsHash: string;
|
|
20
|
+
};
|
|
21
|
+
/** An effect as the journal holds it. `unknown` is admitted and never completed: nobody knows whether it happened, and
|
|
22
|
+
* it is never dispatched again. `session` names the identity it was admitted under, or is null. `intent` names the
|
|
23
|
+
* external call it was admitted for, when it makes one; an effect admitted without one has no `intent` key. */
|
|
24
|
+
export type RecoveryEffect = {
|
|
25
|
+
id: string;
|
|
26
|
+
name: string;
|
|
27
|
+
argsHash: string;
|
|
28
|
+
status: "unknown" | "completed";
|
|
29
|
+
session: string | null;
|
|
30
|
+
result: unknown;
|
|
31
|
+
intent?: RecoveryIntent;
|
|
32
|
+
args?: unknown;
|
|
33
|
+
calls?: unknown[];
|
|
34
|
+
};
|
|
35
|
+
/** One run's journal, held by the driver that opened it. Every write is one commit: it lands whole or not at all, it is
|
|
36
|
+
* durable before its promise resolves, it is refused once a later open has taken the journal, and it advances the
|
|
37
|
+
* revision by one. Values are stored as plain JSON with finite numbers. */
|
|
38
|
+
export type RecoveryJournal = {
|
|
39
|
+
/** Whether an earlier open bound this journal. */
|
|
40
|
+
readonly existing: boolean;
|
|
41
|
+
/** This open's ownership generation: one more than the open before it. */
|
|
42
|
+
readonly generation: number;
|
|
43
|
+
/** The state the last commit before this open left, or null before the first. */
|
|
44
|
+
readonly state: unknown;
|
|
45
|
+
/** The revision of the last commit: the journal's own counter, one per commit, never reused. */
|
|
46
|
+
readonly revision: number;
|
|
47
|
+
/** Every effect admitted so far, in any status. */
|
|
48
|
+
effects(): RecoveryEffect[];
|
|
49
|
+
effect(id: string): RecoveryEffect | undefined;
|
|
50
|
+
notes(): RecoveryNote[];
|
|
51
|
+
/** Commit a state computed with the commit's own revision, so a row that names its revision is never durable without
|
|
52
|
+
* it, and a note when the state records a decision. Resolves to that revision. */
|
|
53
|
+
save(state: (revision: number) => unknown, note?: Pick<RecoveryNote, "kind" | "detail">): Promise<number>;
|
|
54
|
+
/** Commit the state, and a note when the state records a decision. Resolves to the commit's revision. */
|
|
55
|
+
save(state: unknown, note?: Pick<RecoveryNote, "kind" | "detail">): Promise<number>;
|
|
56
|
+
/** Commit a note with no state change. Resolves to the commit's revision. */
|
|
57
|
+
note(kind: RecoveryNote["kind"], detail: unknown): Promise<number>;
|
|
58
|
+
/** Admit an effect before it is dispatched, with the state that admits it, in one commit, and the external call it
|
|
59
|
+
* makes when it makes one: the intent is kept with the effect from its admission, through its completion, at every
|
|
60
|
+
* later open. `args` are the call's arguments as the driver admitted it, kept with the effect as the host's door is sent them
|
|
61
|
+
* (an optional field: a record without them reads as it always did). A store that does not keep them leaves a call that was
|
|
62
|
+
* admitted and never sent unsettleable: a host's `reconcile` cannot re-send it, and the resume refuses it
|
|
63
|
+
* (`FROZEN_EFFECT_UNKNOWN`). An id already admitted is returned as it stands and nothing is written. */
|
|
64
|
+
admit(id: string, name: string, argsHash: string, state: unknown, session?: string | null, intent?: RecoveryIntent, args?: unknown): Promise<"new" | RecoveryEffect>;
|
|
65
|
+
/** Complete an admitted effect with its result, and the state that follows, in one commit. An effect completes once,
|
|
66
|
+
* and never without an admission. With no state given, the state stays as this open found it: that is how an
|
|
67
|
+
* operator reconciles an unknown effect. */
|
|
68
|
+
complete(id: string, result: unknown, state?: unknown): Promise<void>;
|
|
69
|
+
/** Keep the outside calls an admitted effect made, whether or not the effect completes: the list given replaces the one the
|
|
70
|
+
* effect held, and the effect's `calls` carries it from then on, at every later open. They are evidence for the host; no
|
|
71
|
+
* resume depends on them. A caller that adds to the calls an earlier process kept passes the earlier ones first. */
|
|
72
|
+
called(id: string, calls: unknown): Promise<void>;
|
|
73
|
+
/** Let go of the journal. No later commit is made through this open, and the next open is the next generation. */
|
|
74
|
+
close(): Promise<void>;
|
|
75
|
+
};
|
|
76
|
+
/** Where one run's journal lives. `open` takes ownership of it: a journal that is already open is refused, a binding
|
|
77
|
+
* that differs from the one the journal was first opened under is refused naming the inputs that moved, and the
|
|
78
|
+
* generation advances. */
|
|
79
|
+
export type RecoveryStore = {
|
|
80
|
+
open(bound: RecoveryBinding): Promise<RecoveryJournal>;
|
|
81
|
+
};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// The store contract of durable recovery: where one run's journal lives, and the only way a recovery driver reads and
|
|
2
|
+
// writes it. A driver decides what is stored; a store keeps it, one atomic commit per write. The at-most-once rule for
|
|
3
|
+
// effects rests on three things every store must hold: an admission is durable, together with the state it carries,
|
|
4
|
+
// before `admit` resolves; an effect admitted and never completed stays `unknown` across every later open; and a
|
|
5
|
+
// journal has one owner at a time.
|
|
6
|
+
export {};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { RecoveryStore } from "../store.js";
|
|
2
|
+
/** Registers the suite as `node:test` tests named under `name`. `create` returns a new, empty store on every call;
|
|
3
|
+
* the suite opens one store several times, as the successive processes of one run would. */
|
|
4
|
+
export declare function registerStoreConformance(name: string, create: () => RecoveryStore | Promise<RecoveryStore>): void;
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
// The store conformance suite: what a RecoveryStore must hold for the driver's rules to rest on it. A store that
|
|
2
|
+
// passes carries them; a host that writes its own store registers this suite in its own tests.
|
|
3
|
+
import assert from "node:assert/strict";
|
|
4
|
+
import { test } from "node:test";
|
|
5
|
+
import { RecoveryError } from "../errors.js";
|
|
6
|
+
const BOUND = { binding: "binding-1", inputs: { workflow: "digest-a", "config.question": "digest-b" } };
|
|
7
|
+
const refused = (pattern) => (error) => {
|
|
8
|
+
assert.ok(error instanceof RecoveryError, `a store refuses with a RecoveryError, got ${String(error)}`);
|
|
9
|
+
if (pattern)
|
|
10
|
+
assert.match(error.message, pattern);
|
|
11
|
+
return true;
|
|
12
|
+
};
|
|
13
|
+
/** Registers the suite as `node:test` tests named under `name`. `create` returns a new, empty store on every call;
|
|
14
|
+
* the suite opens one store several times, as the successive processes of one run would. */
|
|
15
|
+
export function registerStoreConformance(name, create) {
|
|
16
|
+
const it = (title, body) => test(`${name}: ${title}`, async () => body(await create()));
|
|
17
|
+
it("a new journal is unbound and empty, and its first open is generation 1", async (store) => {
|
|
18
|
+
const journal = await store.open(BOUND);
|
|
19
|
+
assert.deepEqual([journal.existing, journal.generation, journal.state, journal.revision], [false, 1, null, 0]);
|
|
20
|
+
assert.deepEqual([journal.effects(), journal.notes(), journal.effect("absent")], [[], [], undefined]);
|
|
21
|
+
await journal.close();
|
|
22
|
+
});
|
|
23
|
+
it("every write is one commit: the revision advances by one, and the next open reads what was committed", async (store) => {
|
|
24
|
+
const first = await store.open(BOUND);
|
|
25
|
+
assert.equal(await first.save({ step: 1 }), 1);
|
|
26
|
+
assert.equal(await first.save((revision) => ({ step: 2, at: revision }), { kind: "escalation", detail: { why: "gate" } }), 2);
|
|
27
|
+
assert.equal(await first.note("inherited", { level: "full" }), 3);
|
|
28
|
+
assert.equal(first.revision, 3);
|
|
29
|
+
assert.deepEqual(first.notes().map((note) => [note.revision, note.kind, note.detail]), [[2, "escalation", { why: "gate" }], [3, "inherited", { level: "full" }]]);
|
|
30
|
+
await first.close();
|
|
31
|
+
const second = await store.open(BOUND);
|
|
32
|
+
assert.deepEqual([second.existing, second.generation, second.revision], [true, 2, 3]);
|
|
33
|
+
assert.deepEqual(second.state, { step: 2, at: 2 });
|
|
34
|
+
assert.deepEqual(second.notes().map((note) => [note.revision, note.kind, note.detail]), [[2, "escalation", { why: "gate" }], [3, "inherited", { level: "full" }]]);
|
|
35
|
+
assert.ok(second.notes().every((note) => !Number.isNaN(Date.parse(note.at))));
|
|
36
|
+
await second.close();
|
|
37
|
+
});
|
|
38
|
+
it("commits asked for together land one at a time, in the order they were asked for", async (store) => {
|
|
39
|
+
const journal = await store.open(BOUND);
|
|
40
|
+
const revisions = await Promise.all([journal.save({ n: 1 }), journal.save({ n: 2 }), journal.note("handoff", {}), journal.save({ n: 3 })]);
|
|
41
|
+
assert.deepEqual(revisions, [1, 2, 3, 4]);
|
|
42
|
+
await journal.close();
|
|
43
|
+
const next = await store.open(BOUND);
|
|
44
|
+
assert.deepEqual([next.state, next.revision], [{ n: 3 }, 4]);
|
|
45
|
+
await next.close();
|
|
46
|
+
});
|
|
47
|
+
it("admit commits the effect with the state that admits it; an id already admitted is returned as it stands and writes nothing", async (store) => {
|
|
48
|
+
const first = await store.open(BOUND);
|
|
49
|
+
assert.equal(await first.admit("e1", "lookup", "args-1", { admitted: ["e1"] }, "run-1"), "new");
|
|
50
|
+
assert.equal(first.revision, 1);
|
|
51
|
+
const held = { id: "e1", name: "lookup", argsHash: "args-1", status: "unknown", session: "run-1", result: null };
|
|
52
|
+
assert.deepEqual(await first.admit("e1", "other", "args-2", { admitted: [] }), held);
|
|
53
|
+
assert.equal(first.revision, 1);
|
|
54
|
+
await first.close();
|
|
55
|
+
const second = await store.open(BOUND);
|
|
56
|
+
assert.deepEqual(second.state, { admitted: ["e1"] });
|
|
57
|
+
assert.deepEqual(second.effects(), [held]);
|
|
58
|
+
assert.deepEqual(second.effect("e1"), held);
|
|
59
|
+
await second.close();
|
|
60
|
+
});
|
|
61
|
+
it("admit keeps the external call it is given with the effect, through its completion, at every later open; an effect admitted without one has none", async (store) => {
|
|
62
|
+
const intent = { tool: "registry_lookup", argsHash: "intent-1" };
|
|
63
|
+
const first = await store.open(BOUND);
|
|
64
|
+
assert.equal(await first.admit("e1", "lookup", "args-1", {}, "run-1", intent), "new");
|
|
65
|
+
assert.equal(await first.admit("e2", "render", "args-2", {}, "run-1"), "new");
|
|
66
|
+
const admitted = { id: "e1", name: "lookup", argsHash: "args-1", status: "unknown", session: "run-1", result: null, intent };
|
|
67
|
+
const plain = { id: "e2", name: "render", argsHash: "args-2", status: "unknown", session: "run-1", result: null };
|
|
68
|
+
assert.deepEqual([first.effect("e1"), first.effect("e2")], [admitted, plain]);
|
|
69
|
+
await first.close();
|
|
70
|
+
const second = await store.open(BOUND);
|
|
71
|
+
assert.deepEqual(second.effects(), [admitted, plain]);
|
|
72
|
+
await second.complete("e1", { value: 1 }, {});
|
|
73
|
+
await second.close();
|
|
74
|
+
const third = await store.open(BOUND);
|
|
75
|
+
assert.deepEqual(third.effects(), [{ ...admitted, status: "completed", result: { value: 1 } }, plain]);
|
|
76
|
+
assert.equal(Object.hasOwn(third.effect("e2"), "intent"), false);
|
|
77
|
+
await third.close();
|
|
78
|
+
});
|
|
79
|
+
it("admit keeps the arguments it is given with the effect, through its completion, at every later open; an effect admitted without them has none", async (store) => {
|
|
80
|
+
const args = { id: 7, nested: { list: [1, 2] } };
|
|
81
|
+
const first = await store.open(BOUND);
|
|
82
|
+
assert.equal(await first.admit("e1", "lookup", "args-1", {}, "run-1", undefined, args), "new");
|
|
83
|
+
assert.equal(await first.admit("e2", "render", "args-2", {}, "run-1", undefined, null), "new");
|
|
84
|
+
assert.equal(await first.admit("e3", "plain", "args-3", {}, "run-1"), "new");
|
|
85
|
+
const kept = { id: "e1", name: "lookup", argsHash: "args-1", status: "unknown", session: "run-1", result: null, args };
|
|
86
|
+
const empty = { id: "e2", name: "render", argsHash: "args-2", status: "unknown", session: "run-1", result: null, args: null };
|
|
87
|
+
const plain = { id: "e3", name: "plain", argsHash: "args-3", status: "unknown", session: "run-1", result: null };
|
|
88
|
+
assert.deepEqual(first.effects(), [kept, empty, plain]);
|
|
89
|
+
await first.close();
|
|
90
|
+
const second = await store.open(BOUND);
|
|
91
|
+
assert.deepEqual(second.effects(), [kept, empty, plain]);
|
|
92
|
+
await second.complete("e1", { value: 1 }, {});
|
|
93
|
+
await second.close();
|
|
94
|
+
const third = await store.open(BOUND);
|
|
95
|
+
assert.deepEqual(third.effects(), [{ ...kept, status: "completed", result: { value: 1 } }, empty, plain]);
|
|
96
|
+
assert.equal(Object.hasOwn(third.effect("e3"), "args"), false);
|
|
97
|
+
await third.close();
|
|
98
|
+
});
|
|
99
|
+
it("called keeps the outside calls with the effect: effects() carries them, replaced by each list given, through completion and at every later open", async (store) => {
|
|
100
|
+
const first = await store.open(BOUND);
|
|
101
|
+
await first.admit("e1", "lookup", "args-1", {});
|
|
102
|
+
await first.admit("e2", "render", "args-2", {});
|
|
103
|
+
await first.called("e1", [{ outcome: "applied" }]);
|
|
104
|
+
assert.deepEqual(first.effect("e1").calls, [{ outcome: "applied" }]);
|
|
105
|
+
await first.called("e1", [{ outcome: "applied" }, { outcome: "applied", again: true }]);
|
|
106
|
+
assert.equal(Object.hasOwn(first.effect("e2"), "calls"), false);
|
|
107
|
+
await first.close();
|
|
108
|
+
const second = await store.open(BOUND);
|
|
109
|
+
assert.deepEqual(second.effect("e1").calls, [{ outcome: "applied" }, { outcome: "applied", again: true }]);
|
|
110
|
+
await second.complete("e1", { value: 1 }, {});
|
|
111
|
+
assert.deepEqual(second.effect("e1").calls, [{ outcome: "applied" }, { outcome: "applied", again: true }]);
|
|
112
|
+
await second.close();
|
|
113
|
+
const third = await store.open(BOUND);
|
|
114
|
+
assert.deepEqual(third.effects().map((effect) => [effect.id, effect.status, effect.calls]), [["e1", "completed", [{ outcome: "applied" }, { outcome: "applied", again: true }]], ["e2", "unknown", undefined]]);
|
|
115
|
+
await third.close();
|
|
116
|
+
});
|
|
117
|
+
it("an effect admitted and never completed is unknown at every later open", async (store) => {
|
|
118
|
+
const first = await store.open(BOUND);
|
|
119
|
+
await first.admit("e1", "lookup", "args-1", {});
|
|
120
|
+
await first.called("e1", [{ tool: "lookup", ok: false }]);
|
|
121
|
+
await first.close();
|
|
122
|
+
for (const generation of [2, 3]) {
|
|
123
|
+
const later = await store.open(BOUND);
|
|
124
|
+
assert.deepEqual([later.generation, later.effect("e1")?.status, later.effect("e1")?.result, later.effect("e1")?.session], [generation, "unknown", null, null]);
|
|
125
|
+
await later.close();
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
it("complete stores the result with the state that follows, once, and never without an admission", async (store) => {
|
|
129
|
+
const first = await store.open(BOUND);
|
|
130
|
+
await first.admit("e1", "lookup", "args-1", { phase: "admitted" });
|
|
131
|
+
await assert.rejects(first.complete("e0", { value: 1 }, {}), refused());
|
|
132
|
+
await first.complete("e1", { value: 7, files: {} }, { phase: "completed" });
|
|
133
|
+
await assert.rejects(first.complete("e1", { value: 8 }, { phase: "twice" }), refused());
|
|
134
|
+
assert.deepEqual([first.effect("e1")?.status, first.effect("e1")?.result], ["completed", { value: 7, files: {} }]);
|
|
135
|
+
await first.close();
|
|
136
|
+
const second = await store.open(BOUND);
|
|
137
|
+
assert.deepEqual([second.state, second.effect("e1")?.status, second.effect("e1")?.result], [{ phase: "completed" }, "completed", { value: 7, files: {} }]);
|
|
138
|
+
await second.close();
|
|
139
|
+
});
|
|
140
|
+
it("an effect completed with no state keeps the state the open found: a reconciliation", async (store) => {
|
|
141
|
+
const first = await store.open(BOUND);
|
|
142
|
+
await first.admit("e1", "lookup", "args-1", { phase: "admitted" });
|
|
143
|
+
await first.close();
|
|
144
|
+
const operator = await store.open(BOUND);
|
|
145
|
+
await operator.complete("e1", { value: 7 });
|
|
146
|
+
await operator.close();
|
|
147
|
+
const third = await store.open(BOUND);
|
|
148
|
+
assert.deepEqual([third.state, third.effect("e1")?.status, third.effect("e1")?.result], [{ phase: "admitted" }, "completed", { value: 7 }]);
|
|
149
|
+
await third.close();
|
|
150
|
+
});
|
|
151
|
+
it("calls are kept only for an admitted effect, and keeping them completes nothing", async (store) => {
|
|
152
|
+
const journal = await store.open(BOUND);
|
|
153
|
+
await assert.rejects(journal.called("e1", []), refused());
|
|
154
|
+
await journal.admit("e1", "lookup", "args-1", {});
|
|
155
|
+
await journal.called("e1", [{ tool: "lookup" }]);
|
|
156
|
+
assert.deepEqual([journal.revision, journal.effect("e1")?.status], [2, "unknown"]);
|
|
157
|
+
await journal.close();
|
|
158
|
+
});
|
|
159
|
+
it("a journal has one owner: a second open of a live journal is refused, and closing lets the next one in", async (store) => {
|
|
160
|
+
const owner = await store.open(BOUND);
|
|
161
|
+
await owner.save({ by: "owner" });
|
|
162
|
+
await assert.rejects(store.open(BOUND), refused());
|
|
163
|
+
await owner.save({ by: "owner", still: true });
|
|
164
|
+
await owner.close();
|
|
165
|
+
await owner.close();
|
|
166
|
+
const next = await store.open(BOUND);
|
|
167
|
+
assert.deepEqual([next.generation, next.state], [2, { by: "owner", still: true }]);
|
|
168
|
+
await next.close();
|
|
169
|
+
});
|
|
170
|
+
it("a closed journal commits nothing", async (store) => {
|
|
171
|
+
const first = await store.open(BOUND);
|
|
172
|
+
await first.save({ kept: true });
|
|
173
|
+
await first.close();
|
|
174
|
+
await assert.rejects(first.save({ kept: false }), refused());
|
|
175
|
+
await assert.rejects(first.admit("e1", "lookup", "args-1", {}), refused());
|
|
176
|
+
const second = await store.open(BOUND);
|
|
177
|
+
assert.deepEqual([second.state, second.revision, second.effects()], [{ kept: true }, 1, []]);
|
|
178
|
+
await second.close();
|
|
179
|
+
});
|
|
180
|
+
it("a binding that differs is refused naming the inputs that moved; the journal stays as it was", async (store) => {
|
|
181
|
+
const first = await store.open(BOUND);
|
|
182
|
+
await first.save({ kept: true });
|
|
183
|
+
await first.close();
|
|
184
|
+
const moved = { binding: "binding-2", inputs: { workflow: "digest-a", "config.question": "digest-c", cwd: "digest-d" } };
|
|
185
|
+
await assert.rejects(store.open(moved), (error) => {
|
|
186
|
+
refused(/^Run store binding mismatch: config\.question, cwd \(new\) changed since the run was bound$/)(error);
|
|
187
|
+
assert.deepEqual([error.code, error.moved], ["RUN_STORE_BINDING_MISMATCH", ["config.question", "cwd"]]);
|
|
188
|
+
return true;
|
|
189
|
+
});
|
|
190
|
+
await assert.rejects(store.open({ binding: "binding-2" }), refused(/^Run store binding mismatch: the opener named no input digests, so the input that moved cannot be named$/));
|
|
191
|
+
const again = await store.open(BOUND);
|
|
192
|
+
assert.deepEqual([again.existing, again.generation, again.state], [true, 2, { kept: true }]);
|
|
193
|
+
await again.close();
|
|
194
|
+
});
|
|
195
|
+
it("values are stored as plain JSON, and a write that cannot be stored writes nothing at all", async (store) => {
|
|
196
|
+
const first = await store.open(BOUND);
|
|
197
|
+
await first.save({ kept: 1, dropped: undefined, nested: [undefined, { at: new Date(0) }] });
|
|
198
|
+
await assert.rejects(first.save({ bad: Number.NaN }), refused());
|
|
199
|
+
await assert.rejects(first.admit("e1", "lookup", "args-1", { bad: Number.POSITIVE_INFINITY }), refused());
|
|
200
|
+
assert.deepEqual([first.revision, first.effects()], [1, []]);
|
|
201
|
+
assert.equal(await first.save(undefined), 2);
|
|
202
|
+
await first.close();
|
|
203
|
+
const second = await store.open(BOUND);
|
|
204
|
+
assert.deepEqual([second.state, second.revision, second.effects()], [null, 2, []]);
|
|
205
|
+
await second.close();
|
|
206
|
+
const third = await store.open(BOUND);
|
|
207
|
+
await third.save({ kept: 1, dropped: undefined, nested: [undefined, { at: new Date(0) }] });
|
|
208
|
+
await third.close();
|
|
209
|
+
const fourth = await store.open(BOUND);
|
|
210
|
+
assert.deepEqual(fourth.state, { kept: 1, nested: [null, { at: "1970-01-01T00:00:00.000Z" }] });
|
|
211
|
+
await fourth.close();
|
|
212
|
+
});
|
|
213
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export declare const CRASH_POINTS: readonly ["admit", "dispatch", "settle", "commit", "session", "request", "submit"];
|
|
2
|
+
export type CrashPoint = (typeof CRASH_POINTS)[number];
|
|
3
|
+
/** The environment variable that carries the plan to the child, as JSON. */
|
|
4
|
+
export declare const CRASH_PLAN_ENV = "AGENTRUN_CRASH_PLAN";
|
|
5
|
+
export type CrashPlan = {
|
|
6
|
+
mode: "census";
|
|
7
|
+
file: string;
|
|
8
|
+
} | {
|
|
9
|
+
mode: "kill";
|
|
10
|
+
point: CrashPoint;
|
|
11
|
+
nth: number;
|
|
12
|
+
};
|
|
13
|
+
/** Cross `point`. Without a plan it does nothing; in a census it records the crossing; in a kill plan the nth crossing
|
|
14
|
+
* of the planned point ends this process with SIGKILL, and never returns. */
|
|
15
|
+
export declare function crossing(point: CrashPoint): Promise<void>;
|
|
16
|
+
/** Make `crossing` reachable as `globalThis[Symbol.for("agentrun.crash.crossing")]`, for a child whose code does not
|
|
17
|
+
* import this module. */
|
|
18
|
+
export declare function installCrossing(): void;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// The child side of a crash sweep: a process that crosses named points of a run, and either counts the crossings (the
|
|
2
|
+
// census) or kills itself at one of them. A point is crossed just before the step it names:
|
|
3
|
+
// admit before an effect is admitted: nothing of it is durable
|
|
4
|
+
// dispatch after the admission is durable, before the call goes out
|
|
5
|
+
// settle after the call returned, before its result is committed
|
|
6
|
+
// commit before the node that ran is committed
|
|
7
|
+
// session before an agent step's conversation is created
|
|
8
|
+
// request while a model request is in flight
|
|
9
|
+
// submit while the step's submission is being taken
|
|
10
|
+
import { appendFileSync } from "node:fs";
|
|
11
|
+
export const CRASH_POINTS = ["admit", "dispatch", "settle", "commit", "session", "request", "submit"];
|
|
12
|
+
/** The environment variable that carries the plan to the child, as JSON. */
|
|
13
|
+
export const CRASH_PLAN_ENV = "AGENTRUN_CRASH_PLAN";
|
|
14
|
+
const SLOT = Symbol.for("agentrun.crash.crossing");
|
|
15
|
+
function planOf(env) {
|
|
16
|
+
const text = env[CRASH_PLAN_ENV];
|
|
17
|
+
return text ? JSON.parse(text) : undefined;
|
|
18
|
+
}
|
|
19
|
+
const crossed = new Map();
|
|
20
|
+
/** Cross `point`. Without a plan it does nothing; in a census it records the crossing; in a kill plan the nth crossing
|
|
21
|
+
* of the planned point ends this process with SIGKILL, and never returns. */
|
|
22
|
+
export async function crossing(point) {
|
|
23
|
+
const plan = planOf(process.env);
|
|
24
|
+
if (!plan)
|
|
25
|
+
return;
|
|
26
|
+
if (plan.mode === "census") {
|
|
27
|
+
appendFileSync(plan.file, `${point}\n`);
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
if (plan.point !== point)
|
|
31
|
+
return;
|
|
32
|
+
const nth = (crossed.get(point) ?? 0) + 1;
|
|
33
|
+
crossed.set(point, nth);
|
|
34
|
+
if (nth !== plan.nth)
|
|
35
|
+
return;
|
|
36
|
+
process.kill(process.pid, "SIGKILL");
|
|
37
|
+
await new Promise(() => { });
|
|
38
|
+
}
|
|
39
|
+
/** Make `crossing` reachable as `globalThis[Symbol.for("agentrun.crash.crossing")]`, for a child whose code does not
|
|
40
|
+
* import this module. */
|
|
41
|
+
export function installCrossing() {
|
|
42
|
+
globalThis[SLOT] = crossing;
|
|
43
|
+
}
|