@parcha/agentrun-dsl 0.1.0-beta.32 → 0.1.0-beta.320

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 (67) hide show
  1. package/NOTICE +2 -0
  2. package/README.md +13 -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 +9 -3
  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.js +2 -1
  19. package/dist/index.d.ts +10 -8
  20. package/dist/index.js +12 -8
  21. package/dist/pattern-screen.d.ts +14 -0
  22. package/dist/pattern-screen.js +451 -0
  23. package/dist/pointer-warning.d.ts +14 -0
  24. package/dist/pointer-warning.js +22 -0
  25. package/dist/predicates.d.ts +23 -3
  26. package/dist/predicates.js +48 -6
  27. package/dist/record.d.ts +4 -0
  28. package/dist/record.js +6 -0
  29. package/dist/recovery/binding.js +2 -1
  30. package/dist/recovery/call-key.d.ts +0 -4
  31. package/dist/recovery/call-key.js +0 -7
  32. package/dist/recovery/driver.d.ts +9 -14
  33. package/dist/recovery/driver.js +29 -26
  34. package/dist/recovery/frozen-snapshot.js +8 -8
  35. package/dist/recovery/handoff-receipts.d.ts +0 -35
  36. package/dist/recovery/handoff-receipts.js +2 -44
  37. package/dist/recovery/index.d.ts +2 -7
  38. package/dist/recovery/index.js +2 -6
  39. package/dist/recovery/item-state.d.ts +2 -1
  40. package/dist/recovery/item-state.js +7 -13
  41. package/dist/recovery/with-recovery.js +4 -2
  42. package/dist/submit-envelope.d.ts +1 -1
  43. package/dist/submit-envelope.js +11 -7
  44. package/dist/system-one.d.ts +0 -4
  45. package/dist/system-one.js +7 -8
  46. package/dist/vocabulary.d.ts +7 -2
  47. package/dist/vocabulary.js +7 -1
  48. package/dist/workflow-shape.js +4 -2
  49. package/dist/workflow.d.ts +58 -13
  50. package/dist/workflow.js +399 -180
  51. package/dist/zod-json-contract.js +6 -8
  52. package/package.json +18 -2
  53. package/schema/workflow.schema.json +93 -0
  54. package/skills/author/references/jev-decisions.md +10 -5
  55. package/skills/author/references/language.md +5 -4
  56. package/dist/recovery/effect-failure.d.ts +0 -34
  57. package/dist/recovery/effect-failure.js +0 -62
  58. package/dist/recovery/handoff-block.d.ts +0 -36
  59. package/dist/recovery/handoff-block.js +0 -148
  60. package/dist/recovery/handoff-digest.d.ts +0 -58
  61. package/dist/recovery/handoff-digest.js +0 -195
  62. package/dist/recovery/handoff-files.d.ts +0 -54
  63. package/dist/recovery/handoff-files.js +0 -162
  64. package/dist/recovery/handoff-redact.d.ts +0 -12
  65. package/dist/recovery/handoff-redact.js +0 -44
  66. package/dist/recovery/handoff.d.ts +0 -44
  67. package/dist/recovery/handoff.js +0 -46
@@ -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
- }
@@ -207,6 +207,10 @@ export declare function openRecovery(store: RecoveryStore, workflow: Workflow, o
207
207
  admitDecision(executionPath: unknown, request: Pick<DecisionRequest, "decision_id" | "kind" | "label" | "model" | "request_sha256">): DecisionRequest | undefined;
208
208
  /** A request `admitDecision` admitted is no longer in flight. */
209
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;
210
214
  /** A decision request's one outcome, with its spend (null when unknown), in the driver's next commit, together with
211
215
  * whatever `alongside` records (the answer's spend, a route's decision): no commit holds the one without the other.
212
216
  * It never applies a stop: a request the run asked ends whatever stops the run. */
@@ -216,24 +220,15 @@ export declare function openRecovery(store: RecoveryStore, workflow: Workflow, o
216
220
  * continuation identity, whatever fires again. */
217
221
  escalate(row: Omit<EscalationRow, "tail" | "revision">): Promise<EscalationRow>;
218
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>;
219
228
  /** The driver's frame as it stands, serialized: what a host shows of a live run while its store is held. */
220
229
  pinJson(): string;
221
230
  /** How many effects the driver admitted. */
222
231
  effectCalls(): number;
223
- /** What the continuation inherited, against the escalation that admitted it: the level, the sizes of what it
224
- * read and its identity. */
225
- annotateHandoff(detail: {
226
- escalation_revision: number;
227
- tail: string;
228
- inherit: string;
229
- block_chars: number;
230
- digest_chars: number;
231
- }): Promise<void>;
232
- /** The run's spend at the moment its continuation is admitted. Spend may land under this run after
233
- * the escalation commit, so the row the continuation reads the spend from is brought current here,
234
- * by one `handoff` commit that names the escalation. The escalation's revision, what the
235
- * continuation binds on, does not change. */
236
- handoff(spend: Pick<EscalationRow, "cost_usd" | "turns" | "effect_calls">): Promise<EscalationRow>;
237
232
  /** The state the document's committed top-level prefix left behind, plus what a failed map's finished
238
233
  * items produced under the map's key: what an escalation on a failure carries. */
239
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
@@ -1151,6 +1153,20 @@ export async function openRecovery(store, workflow, options) {
1151
1153
  },
1152
1154
  /** A request `admitDecision` admitted is no longer in flight. */
1153
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
+ },
1154
1170
  /** A decision request's one outcome, with its spend (null when unknown), in the driver's next commit, together with
1155
1171
  * whatever `alongside` records (the answer's spend, a route's decision): no commit holds the one without the other.
1156
1172
  * It never applies a stop: a request the run asked ends whatever stops the run. */
@@ -1193,33 +1209,20 @@ export async function openRecovery(store, workflow, options) {
1193
1209
  return snapshot.escalation;
1194
1210
  },
1195
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
+ },
1196
1222
  /** The driver's frame as it stands, serialized: what a host shows of a live run while its store is held. */
1197
1223
  pinJson() { return JSON.stringify(snapshot.pin); },
1198
1224
  /** How many effects the driver admitted. */
1199
1225
  effectCalls() { return journal.effects().length; },
1200
- /** What the continuation inherited, against the escalation that admitted it: the level, the sizes of what it
1201
- * read and its identity. */
1202
- async annotateHandoff(detail) {
1203
- await persist(() => journal.note("inherited", detail));
1204
- },
1205
- /** The run's spend at the moment its continuation is admitted. Spend may land under this run after
1206
- * the escalation commit, so the row the continuation reads the spend from is brought current here,
1207
- * by one `handoff` commit that names the escalation. The escalation's revision, what the
1208
- * continuation binds on, does not change. */
1209
- async handoff(spend) {
1210
- guard();
1211
- const row = snapshot.escalation;
1212
- if (!row)
1213
- throw failure("FROZEN_CHECKPOINT_INVALID", "A handoff follows an escalation; none is recorded");
1214
- if (row.cost_usd === spend.cost_usd && row.turns === spend.turns && row.effect_calls === spend.effect_calls)
1215
- return row;
1216
- const detail = { escalation_revision: row.revision, previous_cost_usd: row.cost_usd,
1217
- cost_usd: spend.cost_usd, turns: spend.turns, effect_calls: spend.effect_calls };
1218
- Object.assign(row, spend);
1219
- const write = writeOf();
1220
- await persist(() => journal.save(write.state, { kind: "handoff", detail }, write.parts));
1221
- return row;
1222
- },
1223
1226
  /** The state the document's committed top-level prefix left behind, plus what a failed map's finished
1224
1227
  * items produced under the map's key: what an escalation on a failure carries. */
1225
1228
  lastState() {
@@ -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. */
@@ -6,26 +6,20 @@ export function canonicalJson(value) {
6
6
  ? Object.fromEntries(Object.keys(item).sort().map((key) => [key, item[key]])) : item);
7
7
  }
8
8
  const sameValue = (a, b) => a === b || JSON.stringify(a) === JSON.stringify(b);
9
- /** `state` against `base`, as a map item keeps it. */
9
+ /** `state` against `base`, as a map item keeps it. Each object is built from its entries (Object.fromEntries), so every
10
+ * key is an own one, `__proto__` too: an assignment of that key would set the object's prototype and drop the key. */
10
11
  export function stateDelta(base, state, sha256) {
11
- const set = {};
12
- for (const [key, value] of Object.entries(state))
13
- if (!Object.hasOwn(base, key) || !sameValue(base[key], value))
14
- set[key] = value;
12
+ const set = Object.fromEntries(Object.entries(state).filter(([key, value]) => !Object.hasOwn(base, key) || !sameValue(base[key], value)));
15
13
  return { set, unset: Object.keys(base).filter((key) => !Object.hasOwn(state, key)), sha256 };
16
14
  }
17
15
  /** 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
18
16
  * base), then the keys it added. */
19
17
  export function applyStateDelta(base, delta) {
20
18
  const unset = new Set(delta.unset);
21
- const state = {};
22
- for (const key of Object.keys(base))
23
- if (!unset.has(key))
24
- state[key] = Object.hasOwn(delta.set, key) ? delta.set[key] : base[key];
25
- for (const [key, value] of Object.entries(delta.set))
26
- if (!Object.hasOwn(base, key))
27
- state[key] = value;
28
- return state;
19
+ return Object.fromEntries([
20
+ ...Object.keys(base).filter((key) => !unset.has(key)).map((key) => [key, Object.hasOwn(delta.set, key) ? delta.set[key] : base[key]]),
21
+ ...Object.entries(delta.set).filter(([key]) => !Object.hasOwn(base, key)),
22
+ ]);
29
23
  }
30
24
  const isObject = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
31
25
  /** A map item's state at `path`, rebuilt as the driver rebuilds it: the `agentrun.states` value its `base` names, with
@@ -68,8 +68,10 @@ export function withRecovery(driver, deps, options = {}) {
68
68
  throw error;
69
69
  }
70
70
  // A cut call (a cancel, the run's failure) has no outcome: a later open finds it asked and unanswered. A call
71
- // that ended on its own failed, and the next process asks again.
72
- if (!driver.signal.aborted && !params.signal?.aborted)
71
+ // that ended on its own failed, and the next process asks again; so does one that never left (`unsent`, a host's
72
+ // refusal before it sent anything), whatever stopped the run meanwhile: nothing went out to answer.
73
+ const unsent = error instanceof DecisionProviderError && error.unsent === true;
74
+ if (unsent || (!driver.signal.aborted && !params.signal?.aborted))
73
75
  driver.decisionEnded(params.executionPath, decisionId, "failed", null);
74
76
  throw error;
75
77
  }
@@ -4,6 +4,6 @@
4
4
  * against, so each local `$ref` (`#`, `#/...`) is relocated under `#/properties/value`. A subschema
5
5
  * that sets its own `$id` is a separate resource: its local references do not move. Every runner that
6
6
  * delivers a node's record through a tool call uses this one envelope, so a schema behaves the same on
7
- * every harness. A keyword of the DSL's own (`criteria`) is left out of every schema in it, never a property or
7
+ * every harness. A keyword the host alone reads (`criteria`, any `x-` one) is left out of every schema in it, never a property or
8
8
  * definition of that name; the submission is still checked against the node's schema as written. */
9
9
  export declare function submitParameters(schema: unknown): Record<string, unknown>;
@@ -1,35 +1,39 @@
1
- // DSL vocabulary that may sit on a schema but is not JSON Schema: System One's question keyword. The model never sees it.
2
- const DSL_ONLY_SCHEMA_KEYWORDS = new Set(["criteria"]);
1
+ import { isRecord } from "./record.js";
2
+ // Keywords that may sit on a schema but are not JSON Schema, read by the host alone: the DSL's `criteria` (System One's
3
+ // question keyword) and every `x-` annotation (AgentRun's `x-carried`, the fields of an agent's answer its next run reads
4
+ // back, which a learned workflow's output node can copy from the agent's output schema). Google's OpenAPI-subset
5
+ // `parameters` refuses a field it does not know. The model never sees them.
6
+ const hostOnlyKeyword = (key) => key === "criteria" || key.startsWith("x-");
3
7
  /** The input schema of a node runner's `submit` tool: the node's output schema under `value`, as
4
8
  * `{ value: <schema> }`. A node schema is not a valid tool input as it stands (a root `$ref` or `$defs`
5
9
  * is not an object schema), and embedding it moves the document root its local pointers resolve
6
10
  * against, so each local `$ref` (`#`, `#/...`) is relocated under `#/properties/value`. A subschema
7
11
  * that sets its own `$id` is a separate resource: its local references do not move. Every runner that
8
12
  * delivers a node's record through a tool call uses this one envelope, so a schema behaves the same on
9
- * every harness. A keyword of the DSL's own (`criteria`) is left out of every schema in it, never a property or
13
+ * every harness. A keyword the host alone reads (`criteria`, any `x-` one) is left out of every schema in it, never a property or
10
14
  * definition of that name; the submission is still checked against the node's schema as written. */
11
15
  export function submitParameters(schema) {
12
16
  const maps = new Set(["properties", "patternProperties", "$defs", "definitions", "dependentSchemas"]);
13
17
  const singles = new Set(["additionalProperties", "unevaluatedProperties", "propertyNames", "items", "additionalItems", "contains", "unevaluatedItems", "not", "if", "then", "else", "contentSchema"]);
14
18
  const arrays = new Set(["allOf", "anyOf", "oneOf", "prefixItems"]);
15
19
  const relocate = (node, resourceScope = false) => {
16
- if (!node || typeof node !== "object" || Array.isArray(node))
20
+ if (!isRecord(node))
17
21
  return structuredClone(node);
18
22
  // $id establishes a separate schema resource: its local references do not move.
19
23
  resourceScope ||= typeof node.$id === "string" && node.$id !== "";
20
24
  const child = (value) => relocate(value, resourceScope);
21
- return Object.fromEntries(Object.entries(node).filter(([key]) => !DSL_ONLY_SCHEMA_KEYWORDS.has(key)).map(([key, value]) => {
25
+ return Object.fromEntries(Object.entries(node).filter(([key]) => !hostOnlyKeyword(key)).map(([key, value]) => {
22
26
  if (!resourceScope && key === "$ref" && typeof value === "string" && (value === "#" || value.startsWith("#/"))) {
23
27
  return [key, `#/properties/value${value.slice(1)}`];
24
28
  }
25
- if (maps.has(key) && value && typeof value === "object" && !Array.isArray(value)) {
29
+ if (maps.has(key) && isRecord(value)) {
26
30
  return [key, Object.fromEntries(Object.entries(value).map(([name, value]) => [name, child(value)]))];
27
31
  }
28
32
  if (arrays.has(key) && Array.isArray(value))
29
33
  return [key, value.map(child)];
30
34
  if (singles.has(key))
31
35
  return [key, Array.isArray(value) ? value.map(child) : child(value)];
32
- if (key === "dependencies" && value && typeof value === "object" && !Array.isArray(value)) {
36
+ if (key === "dependencies" && isRecord(value)) {
33
37
  return [key, Object.fromEntries(Object.entries(value).map(([name, value]) => [name, Array.isArray(value) ? structuredClone(value) : child(value)]))];
34
38
  }
35
39
  // Annotations and literal values are data, not schemas (including a literal $ref).
@@ -65,7 +65,6 @@ export declare const SYSTEM_ONE_LIMITS: {
65
65
  readonly minScoreLevels: 2;
66
66
  readonly maxScoreLevels: 10;
67
67
  };
68
- export declare const SYSTEM_ONE_DEFAULT_MODEL = "jev-latest";
69
68
  export type CompiledQuestions = Record<string, SystemOneQuestion>;
70
69
  export declare function compileQuestions(schema: Record<string, unknown>, definitions?: Record<string, unknown>): {
71
70
  ok: true;
@@ -97,9 +96,6 @@ export declare class SystemOneError extends Error {
97
96
  export declare function validateAnswers(questions: Record<string, SystemOneQuestion>, answers: unknown): asserts answers is Record<string, SystemOneAnswer>;
98
97
  /** The questions whose answer is a refusal, in answer order. */
99
98
  export declare function refusedQuestions(answers: Record<string, unknown>): string[];
100
- /** What `answersToValue` throws for a refused answer: the backstop. A decision node never gets this far, since `decide()`
101
- * escalates the run for review (DECISION_REFUSED) on a refusal first. */
102
- export declare function refusalError(ids: string[]): SystemOneError;
103
99
  /** The confidence TypeSafe documents for Jev (docs.typesafe.ai/confidence), computed from an answer's probabilities: for a
104
100
  * choice of n options, (p - 1/n) / (1 - 1/n) for the chosen option's p, floored at 0; for a score of n levels, 1 minus
105
101
  * the probability-weighted distance from the most likely level (the lowest, on a tie) over that distance for an even