@parcha/agentrun-dsl 0.1.0-beta.30 → 0.1.0-beta.300

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/NOTICE +2 -0
  2. package/README.md +11 -7
  3. package/dist/author-references.d.ts +2 -2
  4. package/dist/author-references.js +2 -2
  5. package/dist/author.d.ts +0 -2
  6. package/dist/author.js +7 -6
  7. package/dist/authoring.js +3 -2
  8. package/dist/cli.js +2 -1
  9. package/dist/code-exec.d.ts +19 -0
  10. package/dist/code-exec.js +54 -5
  11. package/dist/decision-provider.d.ts +11 -2
  12. package/dist/decision-provider.js +12 -4
  13. package/dist/decision-receipts.d.ts +19 -3
  14. package/dist/dry-run.d.ts +31 -1
  15. package/dist/dry-run.js +103 -14
  16. package/dist/edit.d.ts +158 -0
  17. package/dist/edit.js +1486 -0
  18. package/dist/evidence.d.ts +19 -0
  19. package/dist/evidence.js +63 -0
  20. package/dist/index.d.ts +12 -9
  21. package/dist/index.js +14 -9
  22. package/dist/pattern-screen.d.ts +14 -0
  23. package/dist/pattern-screen.js +451 -0
  24. package/dist/pointer-warning.d.ts +14 -0
  25. package/dist/pointer-warning.js +22 -0
  26. package/dist/predicates.d.ts +23 -3
  27. package/dist/predicates.js +48 -6
  28. package/dist/record.d.ts +4 -0
  29. package/dist/record.js +6 -0
  30. package/dist/recovery/binding.js +2 -1
  31. package/dist/recovery/call-key.d.ts +0 -4
  32. package/dist/recovery/call-key.js +0 -7
  33. package/dist/recovery/driver.d.ts +20 -14
  34. package/dist/recovery/driver.js +48 -26
  35. package/dist/recovery/frozen-snapshot.js +8 -8
  36. package/dist/recovery/handoff-receipts.d.ts +0 -35
  37. package/dist/recovery/handoff-receipts.js +2 -44
  38. package/dist/recovery/index.d.ts +2 -7
  39. package/dist/recovery/index.js +2 -6
  40. package/dist/recovery/item-state.d.ts +2 -1
  41. package/dist/recovery/item-state.js +7 -13
  42. package/dist/recovery/with-recovery.js +4 -2
  43. package/dist/submit-envelope.d.ts +1 -1
  44. package/dist/submit-envelope.js +11 -7
  45. package/dist/system-one.d.ts +0 -4
  46. package/dist/system-one.js +7 -8
  47. package/dist/vocabulary.d.ts +7 -2
  48. package/dist/vocabulary.js +7 -1
  49. package/dist/workflow-shape.js +4 -2
  50. package/dist/workflow.d.ts +64 -13
  51. package/dist/workflow.js +506 -202
  52. package/dist/zod-json-contract.js +6 -8
  53. package/package.json +7 -3
  54. package/schema/workflow.schema.json +93 -0
  55. package/skills/author/references/jev-decisions.md +10 -5
  56. package/skills/author/references/language.md +5 -4
  57. package/dist/recovery/effect-failure.d.ts +0 -34
  58. package/dist/recovery/effect-failure.js +0 -62
  59. package/dist/recovery/handoff-block.d.ts +0 -36
  60. package/dist/recovery/handoff-block.js +0 -148
  61. package/dist/recovery/handoff-digest.d.ts +0 -58
  62. package/dist/recovery/handoff-digest.js +0 -195
  63. package/dist/recovery/handoff-files.d.ts +0 -54
  64. package/dist/recovery/handoff-files.js +0 -162
  65. package/dist/recovery/handoff-redact.d.ts +0 -12
  66. package/dist/recovery/handoff-redact.js +0 -44
  67. package/dist/recovery/handoff.d.ts +0 -44
  68. package/dist/recovery/handoff.js +0 -46
@@ -0,0 +1,22 @@
1
+ // A warning about one part of a workflow, as text: its code, the JSON Pointer of what it is about, and its words. The
2
+ // validator writes one when it checks references against keys it derived from the input schema (a finding that would be
3
+ // an error with the input given), and a reader (the console's canvas, say) reads the pointer back to draw the warning on
4
+ // its node. Both sides use this pair, so the format has one definition. This module imports nothing: a reader takes it
5
+ // without the validator.
6
+ /** `<code> at <pointer>: <message>`, or `<code>: <message>` for the pointer "". A route branch's name may hold ": ", and
7
+ * so may a pointer through it: in the text, the pointer's ":" is written `%3A` and its "%" `%25` (as a URI fragment
8
+ * writes them), so the first ":" after " at " ends the pointer. A pointer with neither reads as it is. */
9
+ export function formatPointerWarning(code, pointer, message) {
10
+ return `${code}${pointer ? ` at ${pointer.replace(/[%:]/g, (c) => (c === "%" ? "%25" : "%3A"))}` : ""}: ${message}`;
11
+ }
12
+ const POINTER_WARNING = /^([A-Z][A-Z0-9_]*)(?: at ([^:]+))?: ([\s\S]*)$/;
13
+ /** The parts of a text `formatPointerWarning` wrote, its pointer as written in the workflow, or null for any other text
14
+ * (or a value that is not a string). */
15
+ export function parsePointerWarning(text) {
16
+ if (typeof text !== "string")
17
+ return null;
18
+ const parts = POINTER_WARNING.exec(text);
19
+ if (!parts)
20
+ return null;
21
+ return { code: parts[1], pointer: (parts[2] ?? "").replace(/%(25|3A)/g, (_, hex) => (hex === "25" ? "%" : ":")), message: parts[3] };
22
+ }
@@ -33,16 +33,36 @@ export type AcceptPredicate = StopPredicate | {
33
33
  predicate: "field_type";
34
34
  path: string;
35
35
  type: FieldType;
36
- } | NotPredicate;
36
+ } | QuoteMissingPredicate | NotPredicate;
37
+ /** Holds when a quote at `path` is in none of the page text at `pages`. `path` names a quote (a string) or a list of them;
38
+ * with `field`, a list (or one record) of records, each holding its quote at `field`. Each of `pages` names a state value
39
+ * this run wrote, a call's result most often: every string under it is page text. */
40
+ export type QuoteMissingPredicate = {
41
+ predicate: "quote_missing";
42
+ path: string;
43
+ field?: string;
44
+ pages: string[];
45
+ };
37
46
  /** Holds when `of` does not. `of` is mechanical: a judged question never sits inside a negation. */
38
47
  export type NotPredicate = {
39
48
  predicate: "not";
40
49
  of: AcceptPredicate;
41
50
  };
42
51
  export declare const MECHANICAL_PREDICATE_NAMES: ReadonlySet<string>;
43
- /** Resolve a dotted state path the one way every reader does: a record by key, an array by a
52
+ /** Resolve a dotted state path the one way every reader does: a record by its own key, an array by a
44
53
  * non-negative integer index, anything else (a string, a number, a missing value) to undefined.
45
54
  * `requires`, interpolation, `itemsPath`, `output.path` and predicates all read through here, so a
46
- * path that names a value for one names it for all. */
55
+ * path that names a value for one names it for all. A key is the record's own: `constructor` or
56
+ * `toString` that nothing wrote is undefined, never the prototype's. */
47
57
  export declare function getPath(value: unknown, key: string): unknown;
58
+ /** A quote shorter than this, normalised, is not checked: too short to say which page it came from. */
59
+ export declare const QUOTE_MIN_CHARS = 8;
60
+ /** quote_missing's reading of `value`: how many quotes it checked (each at least QUOTE_MIN_CHARS once normalised) and how
61
+ * many of them are in no page. A quote is found when its normalised text is in one page string's (each string under the
62
+ * pages read alone, so no quote runs from one into the next), or when its letters and digits are in that string's; the
63
+ * pages are only what `value` holds, the run's own state. Counts alone: no quote or page text leaves here. */
64
+ export declare function quoteCheck(predicate: QuoteMissingPredicate, value: unknown): {
65
+ checked: number;
66
+ missed: number;
67
+ };
48
68
  export declare function predicateMatches(predicate: StopPredicate | AcceptPredicate, value: unknown): boolean;
@@ -1,18 +1,17 @@
1
+ import { isRecord } from "./record.js";
1
2
  import { MECHANICAL_PREDICATES } from "./vocabulary.js";
2
3
  export const MECHANICAL_PREDICATE_NAMES = new Set(MECHANICAL_PREDICATES);
3
- function isRecord(value) {
4
- return typeof value === "object" && value !== null && !Array.isArray(value);
5
- }
6
- /** Resolve a dotted state path the one way every reader does: a record by key, an array by a
4
+ /** Resolve a dotted state path the one way every reader does: a record by its own key, an array by a
7
5
  * non-negative integer index, anything else (a string, a number, a missing value) to undefined.
8
6
  * `requires`, interpolation, `itemsPath`, `output.path` and predicates all read through here, so a
9
- * path that names a value for one names it for all. */
7
+ * path that names a value for one names it for all. A key is the record's own: `constructor` or
8
+ * `toString` that nothing wrote is undefined, never the prototype's. */
10
9
  export function getPath(value, key) {
11
10
  if (!key)
12
11
  return value;
13
12
  return key.split(".").reduce((current, part) => {
14
13
  if (isRecord(current))
15
- return current[part];
14
+ return Object.hasOwn(current, part) ? current[part] : undefined;
16
15
  if (Array.isArray(current)) {
17
16
  // Only a position inside the array resolves: a canonical integer below its length. Anything
18
17
  // else (a property name, an out-of-range or non-canonical number) is not an element.
@@ -37,6 +36,47 @@ function hasType(value, type) {
37
36
  throw new Error(`agentrun: unsupported field_type type "${String(type)}" — fail closed, never silently false`);
38
37
  }
39
38
  }
39
+ /** A quote shorter than this, normalised, is not checked: too short to say which page it came from. */
40
+ export const QUOTE_MIN_CHARS = 8;
41
+ const QUOTE_MARKS = { "‘": "'", "’": "'", "“": "\"", "”": "\"", "–": "-", "—": "-" };
42
+ /** A quote or a page as quote_missing compares them: lowercase, curly quotes straight, en and em dashes "-", each run of
43
+ * whitespace one space, trimmed. */
44
+ const quoteText = (text) => text.toLowerCase().replace(/[‘’“”–—]/g, (mark) => QUOTE_MARKS[mark]).replace(/\s+/g, " ").trim();
45
+ /** The looser reading: the letters and digits of `text` alone, each run joined by one space. */
46
+ const quoteTokens = (text) => (text.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? []).join(" ");
47
+ /** How deep under a page path strings are read: past it a value is no page. */
48
+ const PAGE_DEPTH = 64;
49
+ function pageStrings(value, out, depth = 0) {
50
+ if (typeof value === "string")
51
+ out.push(value);
52
+ else if (depth < PAGE_DEPTH && value !== null && typeof value === "object")
53
+ for (const inner of Array.isArray(value) ? value : Object.values(value))
54
+ pageStrings(inner, out, depth + 1);
55
+ }
56
+ function quotesAt(value, field) {
57
+ if (field === undefined)
58
+ return typeof value === "string" ? [value] : Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
59
+ const records = Array.isArray(value) ? value : isRecord(value) ? [value] : [];
60
+ return records.map((record) => getPath(record, field)).filter((quote) => typeof quote === "string");
61
+ }
62
+ /** quote_missing's reading of `value`: how many quotes it checked (each at least QUOTE_MIN_CHARS once normalised) and how
63
+ * many of them are in no page. A quote is found when its normalised text is in one page string's (each string under the
64
+ * pages read alone, so no quote runs from one into the next), or when its letters and digits are in that string's; the
65
+ * pages are only what `value` holds, the run's own state. Counts alone: no quote or page text leaves here. */
66
+ export function quoteCheck(predicate, value) {
67
+ const quotes = quotesAt(getPath(value, predicate.path), predicate.field).map(quoteText).filter((quote) => quote.length >= QUOTE_MIN_CHARS);
68
+ if (!quotes.length)
69
+ return { checked: 0, missed: 0 };
70
+ const strings = [];
71
+ for (const page of predicate.pages)
72
+ pageStrings(getPath(value, page), strings);
73
+ const texts = strings.map((string) => { const text = quoteText(string); return { text, tokens: quoteTokens(text) }; });
74
+ const missed = quotes.filter((quote) => {
75
+ const loose = quoteTokens(quote);
76
+ return !texts.some(({ text, tokens }) => text.includes(quote) || (loose !== "" && tokens.includes(loose)));
77
+ }).length;
78
+ return { checked: quotes.length, missed };
79
+ }
40
80
  export function predicateMatches(predicate, value) {
41
81
  switch (predicate.predicate) {
42
82
  case "field_equals":
@@ -69,6 +109,8 @@ export function predicateMatches(predicate, value) {
69
109
  }
70
110
  case "field_type":
71
111
  return hasType(getPath(value, predicate.path), predicate.type);
112
+ case "quote_missing":
113
+ return quoteCheck(predicate, value).missed > 0;
72
114
  case "not":
73
115
  // A judged `of` reaches the default case below and throws: validation refuses it first.
74
116
  return !predicateMatches(predicate.of, value);
@@ -0,0 +1,4 @@
1
+ /** Whether `value` is an object that is not null and not an array. That is all it checks: a class instance, a Map, a
2
+ * Date or a null-prototype object passes too. The package's modules use this one copy, except graph.ts and
3
+ * recovery/item-state.ts: each of those imports nothing, so a static viewer can bundle it alone, and keeps its own. */
4
+ export declare function isRecord(value: unknown): value is Record<string, unknown>;
package/dist/record.js ADDED
@@ -0,0 +1,6 @@
1
+ /** Whether `value` is an object that is not null and not an array. That is all it checks: a class instance, a Map, a
2
+ * Date or a null-prototype object passes too. The package's modules use this one copy, except graph.ts and
3
+ * recovery/item-state.ts: each of those imports nothing, so a static viewer can bundle it alone, and keeps its own. */
4
+ export function isRecord(value) {
5
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6
+ }
@@ -2,6 +2,7 @@
2
2
  // per-input digests let a refused open name the inputs that moved.
3
3
  import { canonicalHash } from "./canonical-hash.js";
4
4
  import { RecoveryError } from "./errors.js";
5
+ import { isRecord } from "../record.js";
5
6
  /** The digest of each input a binding covers, named by its path: one entry per key of `parts`, and
6
7
  * one per key of a part that is itself an object ("config.question", "binding.budget"). Stored beside
7
8
  * the binding, they let a mismatch name the inputs that moved instead of only saying one did. */
@@ -12,7 +13,7 @@ export function bindingDigests(parts) {
12
13
  for (const [name, value] of Object.entries(parts)) {
13
14
  if (value === undefined)
14
15
  continue;
15
- if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length) {
16
+ if (isRecord(value) && Object.keys(value).length) {
16
17
  for (const [key, inner] of Object.entries(value))
17
18
  if (inner !== undefined)
18
19
  digests[`${name}.${key}`] = canonicalHash(inner);
@@ -7,7 +7,3 @@ export declare const CALL_KEY_BYTES = 256;
7
7
  * call always has the same key, and two different wide ids share a key only on a digest collision.
8
8
  * Only keys use it: what goes back to the provider is always the id it minted. */
9
9
  export declare function callKey(callId: string): string;
10
- /** The key a ledger holds a call under. Writes always use `callKey`; a read also accepts a row a
11
- * ledger already keys by the raw id (`holds` answers for the raw id), so a run whose ledger keyed a
12
- * wide id as it was resumes against its own receipts and never re-runs a recorded call. */
13
- export declare function heldCallKey(callId: string, holds: (rawKey: string) => boolean): string;
@@ -15,10 +15,3 @@ export function callKey(callId) {
15
15
  const prefix = callId.slice(0, PREFIX_CHARS).replace(/[^A-Za-z0-9_.-]/g, "_");
16
16
  return `${prefix}~${createHash("sha256").update(callId).digest("hex").slice(0, DIGEST_HEX)}`;
17
17
  }
18
- /** The key a ledger holds a call under. Writes always use `callKey`; a read also accepts a row a
19
- * ledger already keys by the raw id (`holds` answers for the raw id), so a run whose ledger keyed a
20
- * wide id as it was resumes against its own receipts and never re-runs a recorded call. */
21
- export function heldCallKey(callId, holds) {
22
- const key = callKey(callId);
23
- return key !== callId && holds(callId) ? callId : key;
24
- }
@@ -48,6 +48,11 @@ export type RecoveryOptions = {
48
48
  /** Closes the session of an LLM step's attempt that ended without a submission. It runs on the driver's commit
49
49
  * chain, before the commit that records the attempt as closed; its failure is the run's. */
50
50
  closeStepSession?: (sessionId: string) => Promise<unknown>;
51
+ /** The host's barrier for an effect's admission: called on the driver's commit chain right after the admission's commit
52
+ * and before the effect is dispatched, so a host whose store syncs between commits (a run store at synchronous NORMAL)
53
+ * makes the admission durable first. Its failure is the run's, and the effect, admitted, is never dispatched: it stays
54
+ * unknown, for a reconcile. Absent, nothing runs between the admission and the dispatch. */
55
+ afterAdmit?: () => Promise<void>;
51
56
  /** Settles effects a killed process left unknown, through the driver's own open of the run (one generation per process).
52
57
  * `openRecovery` calls it once, after the open and before anything resumes, when the journal holds an effect that was
53
58
  * admitted and never completed; `unknown` is those effects, with their `intent` and the `args` the call was admitted with (what the host's door is sent; absent on a record written before args were kept). `complete(id, value, receipt)`
@@ -186,6 +191,12 @@ export declare function openRecovery(store: RecoveryStore, workflow: Workflow, o
186
191
  * receipts a resume would write. */
187
192
  routeReceipted(executionPath: unknown): void;
188
193
  /** The committed decision of the route at `executionPath`, if it was answered in an earlier process. */
194
+ /** Moves the poll window of the call node at `executionPath` back by `ms`, the time its host held the call (a pause
195
+ * for a raise of the run's spend cap, which no deadline is for), durably: a later open reads the moved window, and
196
+ * the next effect's check (wrapEffect) and the interpreter's poll start (pollStartedAt) take it. A node with no poll
197
+ * window started, or no time held, moves nothing. `hold` names the hold (the host's id for it): one hold moves the
198
+ * window once, however often a resume reports it again. */
199
+ holdPoll(executionPath: unknown, ms: number, hold: string): void;
189
200
  routeDecision(executionPath: unknown): RouteDecision | undefined;
190
201
  /** Every decision request this run committed, by decision id. */
191
202
  decisionRequests(): Record<string, DecisionRequest>;
@@ -196,6 +207,10 @@ export declare function openRecovery(store: RecoveryStore, workflow: Workflow, o
196
207
  admitDecision(executionPath: unknown, request: Pick<DecisionRequest, "decision_id" | "kind" | "label" | "model" | "request_sha256">): DecisionRequest | undefined;
197
208
  /** A request `admitDecision` admitted is no longer in flight. */
198
209
  decisionSettled(): void;
210
+ /** Work the host does for a running step outside the driver's records (a model node's request to its model), in
211
+ * flight until the returned release: a pause waits for it, as for an effect, and is taken once it is released. A stop
212
+ * already taken refuses it. Released once; a second release does nothing. */
213
+ hold(): () => void;
199
214
  /** A decision request's one outcome, with its spend (null when unknown), in the driver's next commit, together with
200
215
  * whatever `alongside` records (the answer's spend, a route's decision): no commit holds the one without the other.
201
216
  * It never applies a stop: a request the run asked ends whatever stops the run. */
@@ -205,24 +220,15 @@ export declare function openRecovery(store: RecoveryStore, workflow: Workflow, o
205
220
  * continuation identity, whatever fires again. */
206
221
  escalate(row: Omit<EscalationRow, "tail" | "revision">): Promise<EscalationRow>;
207
222
  escalation(): EscalationRow | undefined;
223
+ /** The run failed: its frame is committed once more, so the journal holds every node the run began and never
224
+ * committed. A node's start is otherwise durable only with the next commit, and a step that failed before anything
225
+ * under it was written (a read of a state path no node wrote) would leave no trace of where the run failed. A
226
+ * stopped driver, or one whose commit failed, writes nothing; a failed write is thrown, as `flush` throws it. */
227
+ failed(): Promise<void>;
208
228
  /** The driver's frame as it stands, serialized: what a host shows of a live run while its store is held. */
209
229
  pinJson(): string;
210
230
  /** How many effects the driver admitted. */
211
231
  effectCalls(): number;
212
- /** What the continuation inherited, against the escalation that admitted it: the level, the sizes of what it
213
- * read and its identity. */
214
- annotateHandoff(detail: {
215
- escalation_revision: number;
216
- tail: string;
217
- inherit: string;
218
- block_chars: number;
219
- digest_chars: number;
220
- }): Promise<void>;
221
- /** The run's spend at the moment its continuation is admitted. Spend may land under this run after
222
- * the escalation commit, so the row the continuation reads the spend from is brought current here,
223
- * by one `handoff` commit that names the escalation. The escalation's revision, what the
224
- * continuation binds on, does not change. */
225
- handoff(spend: Pick<EscalationRow, "cost_usd" | "turns" | "effect_calls">): Promise<EscalationRow>;
226
232
  /** The state the document's committed top-level prefix left behind, plus what a failed map's finished
227
233
  * items produced under the map's key: what an escalation on a failure carries. */
228
234
  lastState(): Record<string, unknown>;
@@ -6,6 +6,8 @@ import path from "node:path";
6
6
  import { createHash } from "node:crypto";
7
7
  import { desugarWorkflow, isItemFailure } from "../workflow.js";
8
8
  import { setLongTimeout } from "../long-timer.js";
9
+ import { isRecord } from "../record.js";
10
+ import { getPath } from "../predicates.js";
9
11
  import { chainStep, childrenOf, completedIteration, enclosingChains, enclosingIterations, isWithin, mapItemOf, nodeAt, topLevelCompletion } from "./execution-path.js";
10
12
  import { bindingDigests, LEDGER_FORMAT } from "./binding.js";
11
13
  import { canonicalHash as hash } from "./canonical-hash.js";
@@ -210,7 +212,7 @@ export async function openRecovery(store, workflow, options) {
210
212
  /** A state the run references by digest, read back and checked against it. */
211
213
  const stateBy = async (sha256) => {
212
214
  const state = await journal.stateOf(sha256);
213
- if (!state || typeof state !== "object" || Array.isArray(state) || hash(state) !== sha256)
215
+ if (!isRecord(state) || hash(state) !== sha256)
214
216
  throw invalid(`The state ${sha256} the run references is missing or changed`);
215
217
  writtenStates.add(sha256);
216
218
  digests.set(state, sha256);
@@ -224,7 +226,6 @@ export async function openRecovery(store, workflow, options) {
224
226
  writtenStates.add(sha256);
225
227
  return value;
226
228
  };
227
- const isRecord = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
228
229
  const validEntry = (entry) => isRecord(entry) && Number.isSafeInteger(entry.length) && entry.length >= 0
229
230
  && Number.isSafeInteger(entry.items) && entry.items >= 0 && typeof entry.base === "string" && SHA.test(entry.base);
230
231
  /** The path of map item `index` of the map at `mapPath`: the prefix the interpreter gives every path inside it. */
@@ -829,7 +830,8 @@ export async function openRecovery(store, workflow, options) {
829
830
  throw pathFault(at, "A committed path was asked for again after its state was released");
830
831
  // A map that starts, or starts again, names the base its items are kept against: the state it starts from.
831
832
  if ((layoutV4 || moving) && node.node === "map") {
832
- const list = String(node.itemsPath).split(".").reduce((value, key) => value?.[key], state);
833
+ // Read as the interpreter reads it (getPath: own keys, an array by its positions), so both count the same items.
834
+ const list = getPath(state, String(node.itemsPath));
833
835
  maps.set(at, { length: Array.isArray(list) ? list.length : 0, items: maps.get(at)?.items ?? 0, base: digestOf(state), baseState: state });
834
836
  }
835
837
  // A node started in an earlier process starts again from the same state, or not at all. The
@@ -1105,6 +1107,22 @@ export async function openRecovery(store, workflow, options) {
1105
1107
  save();
1106
1108
  },
1107
1109
  /** The committed decision of the route at `executionPath`, if it was answered in an earlier process. */
1110
+ /** Moves the poll window of the call node at `executionPath` back by `ms`, the time its host held the call (a pause
1111
+ * for a raise of the run's spend cap, which no deadline is for), durably: a later open reads the moved window, and
1112
+ * the next effect's check (wrapEffect) and the interpreter's poll start (pollStartedAt) take it. A node with no poll
1113
+ * window started, or no time held, moves nothing. `hold` names the hold (the host's id for it): one hold moves the
1114
+ * window once, however often a resume reports it again. */
1115
+ holdPoll(executionPath, ms, hold) {
1116
+ const { tag, doc } = active();
1117
+ const at = placed(executionPath, doc);
1118
+ const key = `poll:${tag}:${at}`;
1119
+ const once = `hold:${tag}:${at}:${hold}`;
1120
+ if (snapshot.clocks[key] === undefined || snapshot.clocks[once] !== undefined || !(Number.isFinite(ms) && ms > 0))
1121
+ return;
1122
+ snapshot.clocks[key] += ms;
1123
+ snapshot.clocks[once] = ms;
1124
+ void save();
1125
+ },
1108
1126
  routeDecision(executionPath) {
1109
1127
  const { frame, doc } = active();
1110
1128
  return frame.routes[placed(executionPath, doc)];
@@ -1135,6 +1153,20 @@ export async function openRecovery(store, workflow, options) {
1135
1153
  },
1136
1154
  /** A request `admitDecision` admitted is no longer in flight. */
1137
1155
  decisionSettled() { settled(); },
1156
+ /** Work the host does for a running step outside the driver's records (a model node's request to its model), in
1157
+ * flight until the returned release: a pause waits for it, as for an effect, and is taken once it is released. A stop
1158
+ * already taken refuses it. Released once; a second release does nothing. */
1159
+ hold() {
1160
+ guard();
1161
+ inFlight += 1;
1162
+ let released = false;
1163
+ return () => {
1164
+ if (released)
1165
+ return;
1166
+ released = true;
1167
+ settled();
1168
+ };
1169
+ },
1138
1170
  /** A decision request's one outcome, with its spend (null when unknown), in the driver's next commit, together with
1139
1171
  * whatever `alongside` records (the answer's spend, a route's decision): no commit holds the one without the other.
1140
1172
  * It never applies a stop: a request the run asked ends whatever stops the run. */
@@ -1177,33 +1209,20 @@ export async function openRecovery(store, workflow, options) {
1177
1209
  return snapshot.escalation;
1178
1210
  },
1179
1211
  escalation() { return snapshot.escalation; },
1212
+ /** The run failed: its frame is committed once more, so the journal holds every node the run began and never
1213
+ * committed. A node's start is otherwise durable only with the next commit, and a step that failed before anything
1214
+ * under it was written (a read of a state path no node wrote) would leave no trace of where the run failed. A
1215
+ * stopped driver, or one whose commit failed, writes nothing; a failed write is thrown, as `flush` throws it. */
1216
+ async failed() {
1217
+ if (fatal || stopping)
1218
+ return;
1219
+ void save();
1220
+ await flush();
1221
+ },
1180
1222
  /** The driver's frame as it stands, serialized: what a host shows of a live run while its store is held. */
1181
1223
  pinJson() { return JSON.stringify(snapshot.pin); },
1182
1224
  /** How many effects the driver admitted. */
1183
1225
  effectCalls() { return journal.effects().length; },
1184
- /** What the continuation inherited, against the escalation that admitted it: the level, the sizes of what it
1185
- * read and its identity. */
1186
- async annotateHandoff(detail) {
1187
- await persist(() => journal.note("inherited", detail));
1188
- },
1189
- /** The run's spend at the moment its continuation is admitted. Spend may land under this run after
1190
- * the escalation commit, so the row the continuation reads the spend from is brought current here,
1191
- * by one `handoff` commit that names the escalation. The escalation's revision, what the
1192
- * continuation binds on, does not change. */
1193
- async handoff(spend) {
1194
- guard();
1195
- const row = snapshot.escalation;
1196
- if (!row)
1197
- throw failure("FROZEN_CHECKPOINT_INVALID", "A handoff follows an escalation; none is recorded");
1198
- if (row.cost_usd === spend.cost_usd && row.turns === spend.turns && row.effect_calls === spend.effect_calls)
1199
- return row;
1200
- const detail = { escalation_revision: row.revision, previous_cost_usd: row.cost_usd,
1201
- cost_usd: spend.cost_usd, turns: spend.turns, effect_calls: spend.effect_calls };
1202
- Object.assign(row, spend);
1203
- const write = writeOf();
1204
- await persist(() => journal.save(write.state, { kind: "handoff", detail }, write.parts));
1205
- return row;
1206
- },
1207
1226
  /** The state the document's committed top-level prefix left behind, plus what a failed map's finished
1208
1227
  * items produced under the map's key: what an escalation on a failure carries. */
1209
1228
  lastState() {
@@ -1262,6 +1281,9 @@ export async function openRecovery(store, workflow, options) {
1262
1281
  const admitted = await persist(() => journal.admit(id, String(params.node.label), argsHash, admission.state, driver, external, params.input ?? null, admission.parts, admission.owner));
1263
1282
  if (admitted !== "new")
1264
1283
  throw failure("FROZEN_EFFECT_UNKNOWN", `Reconcile ${id} before dispatch`);
1284
+ // The admission durable before the dispatch, where the host's store needs a barrier for it (afterAdmit).
1285
+ if (options.afterAdmit)
1286
+ await persist(options.afterAdmit);
1265
1287
  // What landed while the admission was being committed still counts: after a cancel, the caller's own
1266
1288
  // cancellation or the effect's deadline, the effect stays admitted and unknown and the adapter is never called.
1267
1289
  // A pause lets it dispatch and complete.
@@ -4,6 +4,7 @@
4
4
  import { createHash } from "node:crypto";
5
5
  import { RecoveryError } from "./errors.js";
6
6
  import { itemState as rebuildItemState, partialResults as readPartialResults } from "./item-state.js";
7
+ import { isRecord } from "../record.js";
7
8
  export const failure = (code, message) => new RecoveryError(message, code);
8
9
  export const FROZEN_SNAPSHOT_SCHEMA = "agentrun.frozen_run.v3";
9
10
  /** The keyed layout: what lies in a map item is kept in that item's record beside the state, and a state the driver
@@ -26,10 +27,9 @@ export function partialResults(partial, states, options = {}) {
26
27
  }
27
28
  export const DECISION_REQUEST = "decision.request";
28
29
  export const emptyPathFrame = () => ({ input: null, done: [], states: {}, chains: {}, loops: {}, routes: {}, inputs: {}, steps: {} });
29
- const record = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
30
30
  export const SHA256 = /^[a-f0-9]{64}$/;
31
31
  /** `value` as an object whose fields can be read, or null. */
32
- const fields = (value) => record(value) ? value : null;
32
+ const fields = (value) => isRecord(value) ? value : null;
33
33
  const entriesOf = (value) => { const object = fields(value); return object ? Object.entries(object) : null; };
34
34
  const isStepFailure = (value) => {
35
35
  const at = fields(value);
@@ -68,7 +68,7 @@ function validFrame(value, resolves) {
68
68
  const failures = frame.failures === undefined ? [] : entriesOf(frame.failures);
69
69
  const decisions = frame.decisions === undefined ? [] : entriesOf(frame.decisions);
70
70
  return Boolean(decisions && decisions.every(([path, requests]) => resolves(path) && (entriesOf(requests)?.every(([id, request]) => isDecisionRequest(id, request)) ?? false))
71
- && states && states.every(([path, state]) => done.has(path) && record(state))
71
+ && states && states.every(([path, state]) => done.has(path) && isRecord(state))
72
72
  && failures && failures.every(([item, outcome]) => /\/items\/(?:0|[1-9]\d*)$/.test(item) && resolves(`${item}/body`) && isItemOutcome(outcome))
73
73
  && chains && chains.every(([, head]) => { const at = fields(head); return Boolean(at && nonNegativeInt(at.index) && typeof at.path === "string" && done.has(at.path)); })
74
74
  && loops && loops.every(([loop, count]) => resolves(loop) && nonNegativeInt(count))
@@ -78,7 +78,7 @@ function validFrame(value, resolves) {
78
78
  return Boolean(at && resolves(route) && typeof at.label === "string" && typeof at.branch === "string"
79
79
  // A refused route took its unsure branch and chose none: a named branch, a null choice, never "" for either.
80
80
  && (at.refused === undefined ? (typeof at.choice === "string" && typeof at.unsure === "boolean") || (at.choice === undefined && at.unsure === undefined) : at.refused === true && at.branch !== "" && at.choice === null && at.unsure === true)
81
- && record(at.result) && (at.request_sha256 === null || typeof at.request_sha256 === "string")
81
+ && isRecord(at.result) && (at.request_sha256 === null || typeof at.request_sha256 === "string")
82
82
  && (at.receipts === null || (receipts && typeof receipts.invocation === "string" && nonNegativeInt(receipts.request_bytes) && Number.isFinite(receipts.latency_ms))));
83
83
  })
84
84
  && inputs && inputs.every(([path, digest]) => resolves(path) && !done.has(path) && typeof digest === "string" && SHA256.test(digest))
@@ -93,14 +93,14 @@ function validFrame(value, resolves) {
93
93
  }
94
94
  /** Refuses a saved snapshot the driver could not have produced for this run. */
95
95
  export function validateFrozenSnapshot(saved, shape) {
96
- if (!record(saved) || saved.schema !== FROZEN_SNAPSHOT_SCHEMA || !Number.isFinite(saved.startedAt)
96
+ if (!saved || typeof saved !== "object" || Array.isArray(saved) || saved.schema !== FROZEN_SNAPSHOT_SCHEMA || !Number.isFinite(saved.startedAt)
97
97
  || (saved.questionSpendUsd !== undefined && !(Number.isFinite(saved.questionSpendUsd) && saved.questionSpendUsd >= 0))
98
98
  || (saved.unpricedQuestionCount !== undefined && !nonNegativeInt(saved.unpricedQuestionCount))
99
99
  || !["running", "paused", "cancelled"].includes(saved.status)
100
- || !record(saved.clocks) || !Object.values(saved.clocks).every(Number.isFinite)
101
- || !record(saved.files) || !Object.values(saved.files).every(value => typeof value === "string" && SHA256.test(value))
100
+ || !isRecord(saved.clocks) || !Object.values(saved.clocks).every(Number.isFinite)
101
+ || !isRecord(saved.files) || !Object.values(saved.files).every(value => typeof value === "string" && SHA256.test(value))
102
102
  || !validFrame(saved.pin, shape.resolves)
103
- || (saved.escalation !== undefined && (!record(saved.escalation) || typeof saved.escalation.tail !== "string" || typeof saved.escalation.kind !== "string" || !Number.isSafeInteger(saved.escalation.revision)))
103
+ || (saved.escalation !== undefined && (!isRecord(saved.escalation) || typeof saved.escalation.tail !== "string" || typeof saved.escalation.kind !== "string" || !Number.isSafeInteger(saved.escalation.revision)))
104
104
  // A checkpoint that holds a second document's frame is refused: the driver runs one document.
105
105
  || saved.adaptation !== undefined) {
106
106
  throw failure("FROZEN_CHECKPOINT_INVALID", "Invalid frozen recovery checkpoint");
@@ -1,38 +1,3 @@
1
- import type { RecoveryEffect, RecoveryIntent } from "./store.js";
2
- /** A completed tool effect a continuation may answer an exact repeat from: the external call it paid for, and its value. */
3
- export type InheritedReceipt = {
4
- id: string;
5
- name: string;
6
- tool: string;
7
- argsHash: string;
8
- result: unknown;
9
- session: string | null;
10
- };
11
- /** An effect whose outcome is unknown: its call is never dispatched again. `intent` is the external call it was admitted
12
- * for, when its journal recorded one. */
13
- export type InheritedUnknown = {
14
- id: string;
15
- name: string;
16
- argsHash: string;
17
- session: string | null;
18
- intent?: RecoveryIntent;
19
- };
20
- /** A tool value that is itself a returned failure: an error envelope (`ok: false`, `isError: true`, `outcome: "error"`) as
21
- * an object or as its JSON text. Such a value is not a paid result; the continuation may make the call again. Structural,
22
- * never prose. */
23
- export declare function returnedFailure(value: unknown): boolean;
24
- /** The receipts a journal hands to its continuation: completed effects whose receipt names the external call (tool
25
- * effects; shell and executor effects have no external call to repeat) and whose value is a result, not a returned
26
- * failure. */
27
- export declare function inheritableReceipts(effects: readonly RecoveryEffect[]): InheritedReceipt[];
28
- /** The effects a continuation must not dispatch again: every effect whose outcome is unknown, by the name and argument
29
- * hash its admission recorded, and by the external call it was admitted for when the journal holds one. A call the
30
- * continuation's own tools make is matched by `reuseReceipts` on either key. A session effect's name and hash are
31
- * already a tool's name and the hash of its arguments. A tool effect the driver admitted for a workflow node is named
32
- * by the node's label and hashed over the node's whole invocation, so it is matched by its intent (the tool and the
33
- * hash of its arguments, keyed as `gatewayIntentOf` keys a call); one a journal admitted before intents were recorded
34
- * has none, and is matched by name and hash only. */
35
- export declare function inheritableUnknowns(effects: readonly RecoveryEffect[]): InheritedUnknown[];
36
1
  /** The external call a model tool call stands for: the gateway tool and the hash of its arguments. Only a `fetch`
37
2
  * wrapper names the gateway tool in its arguments; every other tool is its own name, whatever its arguments look like.
38
3
  * The same key is computed for an effect from its receipt's intent. */
@@ -1,53 +1,11 @@
1
1
  import { canonicalHash } from "./canonical-hash.js";
2
- /** A tool value that is itself a returned failure: an error envelope (`ok: false`, `isError: true`, `outcome: "error"`) as
3
- * an object or as its JSON text. Such a value is not a paid result; the continuation may make the call again. Structural,
4
- * never prose. */
5
- export function returnedFailure(value) {
6
- const failed = (parsed) => Boolean(parsed && typeof parsed === "object" && !Array.isArray(parsed) && (parsed.ok === false || parsed.isError === true || parsed.outcome === "error"));
7
- if (typeof value !== "string")
8
- return failed(value);
9
- // The envelope may be the whole text (pretty-printed or not) or one line of it with guidance appended; each
10
- // candidate is parsed structurally, never matched as prose.
11
- for (const candidate of [value.trim(), ...value.split("\n").map((line) => line.trim())]) {
12
- if (!candidate.startsWith("{"))
13
- continue;
14
- try {
15
- if (failed(JSON.parse(candidate)))
16
- return true;
17
- }
18
- catch { /* not this candidate */ }
19
- }
20
- return false;
21
- }
22
- /** The receipts a journal hands to its continuation: completed effects whose receipt names the external call (tool
23
- * effects; shell and executor effects have no external call to repeat) and whose value is a result, not a returned
24
- * failure. */
25
- export function inheritableReceipts(effects) {
26
- return effects.filter((e) => e.status === "completed" && e.result && typeof e.result === "object" && e.result.intent && typeof e.result.intent.tool === "string" && !returnedFailure(e.result.value))
27
- .map((e) => {
28
- const receipt = e.result;
29
- // Keyed as a continuation's own call is: a node that reached the gateway through the fetch wrapper paid for the tool the wrapper names.
30
- const { tool, argsHash } = gatewayIntentOf(receipt.intent.tool, receipt.intent.args ?? {});
31
- return { id: e.id, name: e.name, tool, argsHash, result: receipt.value, session: e.session };
32
- });
33
- }
34
- /** The effects a continuation must not dispatch again: every effect whose outcome is unknown, by the name and argument
35
- * hash its admission recorded, and by the external call it was admitted for when the journal holds one. A call the
36
- * continuation's own tools make is matched by `reuseReceipts` on either key. A session effect's name and hash are
37
- * already a tool's name and the hash of its arguments. A tool effect the driver admitted for a workflow node is named
38
- * by the node's label and hashed over the node's whole invocation, so it is matched by its intent (the tool and the
39
- * hash of its arguments, keyed as `gatewayIntentOf` keys a call); one a journal admitted before intents were recorded
40
- * has none, and is matched by name and hash only. */
41
- export function inheritableUnknowns(effects) {
42
- return effects.filter((e) => e.status === "unknown").map((e) => ({ id: e.id, name: e.name, argsHash: e.argsHash, session: e.session,
43
- ...(e.intent ? { intent: { tool: e.intent.tool, argsHash: e.intent.argsHash } } : {}) }));
44
- }
2
+ import { isRecord } from "../record.js";
45
3
  /** The external call a model tool call stands for: the gateway tool and the hash of its arguments. Only a `fetch`
46
4
  * wrapper names the gateway tool in its arguments; every other tool is its own name, whatever its arguments look like.
47
5
  * The same key is computed for an effect from its receipt's intent. */
48
6
  export function gatewayIntentOf(name, args) {
49
7
  const a = args;
50
- if (name === "fetch" && a && typeof a === "object" && typeof a.tool === "string" && a.args && typeof a.args === "object" && !Array.isArray(a.args))
8
+ if (name === "fetch" && a && typeof a === "object" && typeof a.tool === "string" && isRecord(a.args))
51
9
  return { tool: a.tool, argsHash: canonicalHash(a.args) };
52
10
  return { tool: name, argsHash: canonicalHash(args ?? {}) };
53
11
  }
@@ -8,12 +8,7 @@ export { openJournal, type JournalBackend, type JournalRecord } from "./journal.
8
8
  export { RecoveryError, asRecoveryError, isRecoveryError, runStopOf, runStoppedError } from "./errors.js";
9
9
  export { bindingDigests, bindingMismatch, LEDGER_FORMAT } from "./binding.js";
10
10
  export { canonicalHash, canonicalSha256 } from "./canonical-hash.js";
11
- export { callKey, heldCallKey, CALL_KEY_BYTES } from "./call-key.js";
12
- export { FROZEN_SNAPSHOT_SCHEMA, FROZEN_SNAPSHOT_SCHEMA_V4, DECISION_REQUEST, validateFrozenSnapshot, openedFrozenSnapshot, serializeFrozenSnapshot, emptyPathFrame, stateDelta, applyStateDelta, itemState, partialResults, canonicalJson, frozenStepSessionId, frozenStepId, frozenEffectId, frozenEffectPath, admitFrozenStep, closeFrozenStepAttempt, frozenStop, type FrozenSnapshot, type FrozenSnapshotV4, type ItemRecord, type MapEntry, type StateDelta, type Sha256, type PartialSlot, type PathFrame, type RouteDecision, type DecisionRequest, type QuestionReceipts, type FrameTag, type StepRecord, type EscalationRow, type FrozenShape, } from "./frozen-snapshot.js";
11
+ export { callKey, CALL_KEY_BYTES } from "./call-key.js";
12
+ export { FROZEN_SNAPSHOT_SCHEMA, FROZEN_SNAPSHOT_SCHEMA_V4, DECISION_REQUEST, validateFrozenSnapshot, openedFrozenSnapshot, serializeFrozenSnapshot, emptyPathFrame, stateDelta, applyStateDelta, itemState, partialResults, frozenStepId, admitFrozenStep, closeFrozenStepAttempt, frozenStop, type FrozenSnapshot, type FrozenSnapshotV4, type ItemRecord, type MapEntry, type StateDelta, type Sha256, type PartialSlot, type PathFrame, type RouteDecision, type DecisionRequest, type QuestionReceipts, type FrameTag, type StepRecord, type EscalationRow, type FrozenShape, } from "./frozen-snapshot.js";
13
13
  export { chainStep, childrenOf, completedIteration, enclosingChains, enclosingIterations, isWithin, mapItemOf, nodeAt, pathSegments, topLevelCompletion } from "./execution-path.js";
14
- export { TypedEffectFailure, EffectEnvelopeFailure, classifyEffectFailure } from "./effect-failure.js";
15
14
  export { effectRetryClass, transportFactOf, type TransportFact } from "./transport-facts.js";
16
- export { buildHandoff, handoffFirstTurn, type Handoff, type HandoffOptions } from "./handoff.js";
17
- export { gatewayIntentOf, inheritableReceipts, inheritableUnknowns, returnedFailure, type InheritedReceipt, type InheritedUnknown } from "./handoff-receipts.js";
18
- export { inputProvenance, judgedRecords, type InputProvenance } from "./handoff-files.js";
19
- export { type InheritedSession, type InheritedEffect, type TranscriptMessage } from "./handoff-digest.js";
@@ -7,11 +7,7 @@ export { openJournal } from "./journal.js";
7
7
  export { RecoveryError, asRecoveryError, isRecoveryError, runStopOf, runStoppedError } from "./errors.js";
8
8
  export { bindingDigests, bindingMismatch, LEDGER_FORMAT } from "./binding.js";
9
9
  export { canonicalHash, canonicalSha256 } from "./canonical-hash.js";
10
- export { callKey, heldCallKey, CALL_KEY_BYTES } from "./call-key.js";
11
- export { FROZEN_SNAPSHOT_SCHEMA, FROZEN_SNAPSHOT_SCHEMA_V4, DECISION_REQUEST, validateFrozenSnapshot, openedFrozenSnapshot, serializeFrozenSnapshot, emptyPathFrame, stateDelta, applyStateDelta, itemState, partialResults, canonicalJson, frozenStepSessionId, frozenStepId, frozenEffectId, frozenEffectPath, admitFrozenStep, closeFrozenStepAttempt, frozenStop, } from "./frozen-snapshot.js";
10
+ export { callKey, CALL_KEY_BYTES } from "./call-key.js";
11
+ export { FROZEN_SNAPSHOT_SCHEMA, FROZEN_SNAPSHOT_SCHEMA_V4, DECISION_REQUEST, validateFrozenSnapshot, openedFrozenSnapshot, serializeFrozenSnapshot, emptyPathFrame, stateDelta, applyStateDelta, itemState, partialResults, frozenStepId, admitFrozenStep, closeFrozenStepAttempt, frozenStop, } from "./frozen-snapshot.js";
12
12
  export { chainStep, childrenOf, completedIteration, enclosingChains, enclosingIterations, isWithin, mapItemOf, nodeAt, pathSegments, topLevelCompletion } from "./execution-path.js";
13
- export { TypedEffectFailure, EffectEnvelopeFailure, classifyEffectFailure } from "./effect-failure.js";
14
13
  export { effectRetryClass, transportFactOf } from "./transport-facts.js";
15
- export { buildHandoff, handoffFirstTurn } from "./handoff.js";
16
- export { gatewayIntentOf, inheritableReceipts, inheritableUnknowns, returnedFailure } from "./handoff-receipts.js";
17
- export { inputProvenance, judgedRecords } from "./handoff-files.js";
@@ -11,7 +11,8 @@ export type StateDelta = {
11
11
  export type Sha256 = (text: string) => string;
12
12
  /** The JSON a state's digest is taken over: every object's keys sorted. */
13
13
  export declare function canonicalJson(value: unknown): string;
14
- /** `state` against `base`, as a map item keeps it. */
14
+ /** `state` against `base`, as a map item keeps it. Each object is built from its entries (Object.fromEntries), so every
15
+ * key is an own one, `__proto__` too: an assignment of that key would set the object's prototype and drop the key. */
15
16
  export declare function stateDelta(base: State, state: State, sha256: string): StateDelta;
16
17
  /** The state a delta was taken from, in its own key order: the base's keys first (a map item starts from a copy of its
17
18
  * base), then the keys it added. */