@parcha/agentrun-dsl 0.1.0-beta.14 → 0.1.0-beta.140

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 (88) hide show
  1. package/NOTICE +2 -0
  2. package/README.md +155 -16
  3. package/dist/author-references.d.ts +8 -0
  4. package/dist/author-references.js +8 -0
  5. package/dist/author.d.ts +4 -3
  6. package/dist/author.js +20 -11
  7. package/dist/authoring.js +5 -4
  8. package/dist/cli.js +19 -13
  9. package/dist/code-exec.d.ts +19 -0
  10. package/dist/code-exec.js +54 -5
  11. package/dist/decision-provider.d.ts +166 -0
  12. package/dist/decision-provider.js +238 -0
  13. package/dist/decision-receipts.d.ts +64 -3
  14. package/dist/decision-receipts.js +50 -8
  15. package/dist/dry-run.d.ts +41 -1
  16. package/dist/dry-run.js +158 -27
  17. package/dist/evidence.d.ts +19 -0
  18. package/dist/evidence.js +63 -0
  19. package/dist/graph.d.ts +169 -0
  20. package/dist/graph.js +433 -0
  21. package/dist/index.d.ts +19 -12
  22. package/dist/index.js +17 -10
  23. package/dist/inspection.d.ts +5 -0
  24. package/dist/inspection.js +14 -1
  25. package/dist/job.d.ts +14 -0
  26. package/dist/job.js +5 -0
  27. package/dist/pattern-screen.d.ts +14 -0
  28. package/dist/pattern-screen.js +451 -0
  29. package/dist/predicates.d.ts +29 -0
  30. package/dist/predicates.js +62 -3
  31. package/dist/record.d.ts +4 -0
  32. package/dist/record.js +6 -0
  33. package/dist/recovery/binding.js +2 -1
  34. package/dist/recovery/call-key.d.ts +0 -4
  35. package/dist/recovery/call-key.js +0 -7
  36. package/dist/recovery/canonical-hash.d.ts +1 -1
  37. package/dist/recovery/canonical-hash.js +3 -3
  38. package/dist/recovery/driver.d.ts +79 -24
  39. package/dist/recovery/driver.js +634 -78
  40. package/dist/recovery/execution-path.d.ts +8 -0
  41. package/dist/recovery/execution-path.js +14 -0
  42. package/dist/recovery/frozen-snapshot.d.ts +128 -3
  43. package/dist/recovery/frozen-snapshot.js +63 -12
  44. package/dist/recovery/handoff-receipts.d.ts +0 -35
  45. package/dist/recovery/handoff-receipts.js +2 -44
  46. package/dist/recovery/index.d.ts +6 -10
  47. package/dist/recovery/index.js +5 -8
  48. package/dist/recovery/item-state.d.ts +48 -0
  49. package/dist/recovery/item-state.js +89 -0
  50. package/dist/recovery/journal.d.ts +6 -3
  51. package/dist/recovery/journal.js +20 -8
  52. package/dist/recovery/store.d.ts +33 -9
  53. package/dist/recovery/testing/conformance.js +55 -0
  54. package/dist/recovery/with-recovery.d.ts +9 -3
  55. package/dist/recovery/with-recovery.js +78 -18
  56. package/dist/submit-envelope.d.ts +9 -0
  57. package/dist/submit-envelope.js +44 -0
  58. package/dist/system-one.d.ts +37 -2
  59. package/dist/system-one.js +112 -18
  60. package/dist/testing/decision-provider.d.ts +32 -0
  61. package/dist/testing/decision-provider.js +183 -0
  62. package/dist/testing/index.d.ts +1 -0
  63. package/dist/testing/index.js +2 -0
  64. package/dist/vocabulary.d.ts +11 -3
  65. package/dist/vocabulary.js +19 -9
  66. package/dist/workflow-shape.d.ts +7 -0
  67. package/dist/workflow-shape.js +116 -70
  68. package/dist/workflow.d.ts +173 -18
  69. package/dist/workflow.js +1103 -398
  70. package/dist/zod-json-contract.js +6 -8
  71. package/package.json +19 -4
  72. package/schema/workflow.schema.json +366 -1
  73. package/skills/author/SKILL.md +6 -1
  74. package/skills/author/references/jev-decisions.md +50 -5
  75. package/skills/author/references/language.md +19 -14
  76. package/skills/author/references/sdk-authoring.md +2 -0
  77. package/dist/recovery/effect-failure.d.ts +0 -34
  78. package/dist/recovery/effect-failure.js +0 -62
  79. package/dist/recovery/handoff-block.d.ts +0 -36
  80. package/dist/recovery/handoff-block.js +0 -148
  81. package/dist/recovery/handoff-digest.d.ts +0 -58
  82. package/dist/recovery/handoff-digest.js +0 -195
  83. package/dist/recovery/handoff-files.d.ts +0 -54
  84. package/dist/recovery/handoff-files.js +0 -162
  85. package/dist/recovery/handoff-redact.d.ts +0 -12
  86. package/dist/recovery/handoff-redact.js +0 -44
  87. package/dist/recovery/handoff.d.ts +0 -44
  88. package/dist/recovery/handoff.js +0 -46
@@ -0,0 +1,89 @@
1
+ // A map item's state in the keyed layout, rebuilt from its record and its base. This module imports nothing, so a
2
+ // reader with no Node (the static viewer inlines it) runs the same rebuild the driver runs; the SHA-256 is the caller's.
3
+ /** The JSON a state's digest is taken over: every object's keys sorted. */
4
+ export function canonicalJson(value) {
5
+ return JSON.stringify(value, (_key, item) => item && typeof item === "object" && !Array.isArray(item)
6
+ ? Object.fromEntries(Object.keys(item).sort().map((key) => [key, item[key]])) : item);
7
+ }
8
+ const sameValue = (a, b) => a === b || JSON.stringify(a) === JSON.stringify(b);
9
+ /** `state` against `base`, as a map item keeps it. */
10
+ 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;
15
+ return { set, unset: Object.keys(base).filter((key) => !Object.hasOwn(state, key)), sha256 };
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
18
+ * base), then the keys it added. */
19
+ export function applyStateDelta(base, delta) {
20
+ 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;
29
+ }
30
+ const isObject = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
31
+ /** A map item's state at `path`, rebuilt as the driver rebuilds it: the `agentrun.states` value its `base` names, with
32
+ * the item's `set` and `unset` for that path applied, checked against that path's `sha256`. `item` is an
33
+ * `agentrun.items` value; `states` holds `agentrun.states` values by SHA-256; `sha256` hashes a text's UTF-8 bytes.
34
+ * When the base is missing, or a digest differs, it says why and never guesses. */
35
+ export function itemState(item, states, path, { sha256 }) {
36
+ if (typeof sha256 !== "function")
37
+ throw new TypeError("itemState needs a sha256 function");
38
+ if (!isObject(item) || typeof item.base !== "string" || !isObject(item.frame) || !isObject(item.frame.states))
39
+ return { unreadable: "not a map item's record" };
40
+ const delta = item.frame.states[path];
41
+ if (delta === undefined)
42
+ return { unreadable: `the item keeps no state at ${path}` };
43
+ if (!isObject(delta) || !isObject(delta.set) || !Array.isArray(delta.unset) || !delta.unset.every((key) => typeof key === "string") || typeof delta.sha256 !== "string") {
44
+ return { unreadable: `the state at ${path} is not a delta` };
45
+ }
46
+ const held = states instanceof Map ? states.get(item.base) : Object.hasOwn(states, item.base) ? states[item.base] : undefined;
47
+ if (!isObject(held) || !isObject(held.state))
48
+ return { unreadable: `its base ${item.base} is missing` };
49
+ if (sha256(canonicalJson(held.state)) !== item.base)
50
+ return { unreadable: `its base does not match its SHA-256 ${item.base}` };
51
+ const state = applyStateDelta(held.state, delta);
52
+ if (sha256(canonicalJson(state)) !== delta.sha256)
53
+ return { unreadable: `the state at ${path} does not rebuild to its SHA-256 ${delta.sha256}` };
54
+ return { state };
55
+ }
56
+ /** A failed map's finished results, read as the driver reads them: `partial` is the driver state's `pin.partial`. In the
57
+ * keyed layout its `results` is one SHA-256 naming the `agentrun.states` value that lists each slot (null, or the
58
+ * SHA-256 of that item's result); `states` holds `agentrun.states` values by SHA-256, and every digest is checked. A
59
+ * whole-state run's `results` is the list itself. A document that is missing or does not match its digest is
60
+ * unreadable, never guessed: the list as a whole, or one slot. */
61
+ export function partialResults(partial, states, { sha256 }) {
62
+ if (typeof sha256 !== "function")
63
+ throw new TypeError("partialResults needs a sha256 function");
64
+ if (!isObject(partial) || typeof partial.path !== "string" || typeof partial.as !== "string")
65
+ return { unreadable: "not a failed map's results" };
66
+ if (Array.isArray(partial.results))
67
+ return { slots: partial.results.map((result) => (result === null ? null : { result })) };
68
+ if (typeof partial.results !== "string")
69
+ return { unreadable: "not a failed map's results" };
70
+ const read = (digest) => {
71
+ const held = states instanceof Map ? states.get(digest) : Object.hasOwn(states, digest) ? states[digest] : undefined;
72
+ if (!isObject(held) || !Object.hasOwn(held, "state"))
73
+ return { unreadable: `${digest} is missing` };
74
+ if (sha256(canonicalJson(held.state)) !== digest)
75
+ return { unreadable: `${digest} does not match its SHA-256` };
76
+ return { value: held.state };
77
+ };
78
+ const list = read(partial.results);
79
+ if ("unreadable" in list)
80
+ return { unreadable: `the list of results ${list.unreadable}` };
81
+ if (!Array.isArray(list.value) || !list.value.every((slot) => slot === null || (typeof slot === "string" && /^[a-f0-9]{64}$/.test(slot))))
82
+ return { unreadable: "the list of results is not a list of digests" };
83
+ return { slots: list.value.map((slot) => {
84
+ if (slot === null)
85
+ return null;
86
+ const result = read(slot);
87
+ return "unreadable" in result ? { unreadable: `the result ${result.unreadable}` } : { result: result.value };
88
+ }) };
89
+ }
@@ -1,6 +1,7 @@
1
- import type { RecoveryBinding, RecoveryEffect, RecoveryJournal, RecoveryNote } from "./store.js";
2
- /** A journal as a backend keeps it: what it is bound to, who owns it, its state, its notes, and its effects in
3
- * admission order, each with the outside calls it made. */
1
+ import type { RecoveryBinding, RecoveryEffect, RecoveryItem, RecoveryJournal, RecoveryNote } from "./store.js";
2
+ /** A journal as a backend keeps it: what it is bound to, who owns it, its state, its notes, its effects in admission
3
+ * order, each with the outside calls it made, and the parts written beside the state (map items' records by path,
4
+ * states by digest). */
4
5
  export type JournalRecord = {
5
6
  binding: string | null;
6
7
  inputs: Record<string, string> | null;
@@ -11,6 +12,8 @@ export type JournalRecord = {
11
12
  effects: Array<RecoveryEffect & {
12
13
  calls?: unknown;
13
14
  }>;
15
+ items?: Record<string, RecoveryItem>;
16
+ states?: Record<string, unknown>;
14
17
  };
15
18
  export type JournalBackend = {
16
19
  /** Take the journal for one owner, or throw when it has a live one. Resolves to what lets go of it. */
@@ -52,13 +52,22 @@ export async function openJournal(backend, bound) {
52
52
  return done;
53
53
  };
54
54
  /** One commit, inside a write: it checks this open still owns the journal, advances the revision, and lets `change`
55
- * alter the record with that revision. The record is replaced only when `change` returns. */
56
- const commit = async (change) => {
55
+ * alter the record with that revision, then lays the parts beside it. The record is replaced only when both return. */
56
+ const commit = async (change, parts) => {
57
57
  const record = await backend.read();
58
58
  if (!record || record.generation !== generation)
59
59
  throw new RecoveryError("Run owner generation is not acquired");
60
60
  const next = record.revision + 1;
61
61
  change(record, next);
62
+ const laid = parts?.(next);
63
+ if (laid?.items)
64
+ record.items = { ...record.items, ...json(laid.items) };
65
+ if (laid?.states) {
66
+ const states = record.states ??= {};
67
+ for (const [sha256, state] of Object.entries(laid.states))
68
+ if (!Object.hasOwn(states, sha256))
69
+ states[sha256] = json(state);
70
+ }
62
71
  record.revision = next;
63
72
  await backend.write(record);
64
73
  revision = next;
@@ -71,7 +80,7 @@ export async function openJournal(backend, bound) {
71
80
  effects: () => [...effects.values()],
72
81
  effect: (id) => effects.get(id),
73
82
  notes: () => [...notes],
74
- save: (state, note) => inOrder(async () => {
83
+ save: (state, note, parts) => inOrder(async () => {
75
84
  let entry;
76
85
  const committed = await commit((record, next) => {
77
86
  record.state = json(typeof state === "function" ? state(next) : state);
@@ -79,7 +88,7 @@ export async function openJournal(backend, bound) {
79
88
  entry = { revision: next, kind: note.kind, detail: json(note.detail), at: new Date().toISOString() };
80
89
  record.notes.push(entry);
81
90
  }
82
- });
91
+ }, parts);
83
92
  if (entry)
84
93
  notes.push(entry);
85
94
  return committed;
@@ -90,23 +99,24 @@ export async function openJournal(backend, bound) {
90
99
  notes.push({ revision: committed, ...entry });
91
100
  return committed;
92
101
  }),
93
- admit: (id, name, argsHash, state, session = null, intent, args) => inOrder(async () => {
102
+ // A record kept whole lists every effect itself, an owned one too.
103
+ admit: (id, name, argsHash, state, session = null, intent, args, parts) => inOrder(async () => {
94
104
  const known = effects.get(id);
95
105
  if (known)
96
106
  return known;
97
107
  const effect = { id, name, argsHash, status: "unknown", session, result: null, ...(intent ? { intent: json(intent) } : {}), ...(args !== undefined ? { args: json(args) } : {}) };
98
- await commit((record) => { record.effects.push({ ...effect }); record.state = json(state); });
108
+ await commit((record) => { record.effects.push({ ...effect }); record.state = json(state); }, parts);
99
109
  effects.set(id, effect);
100
110
  return "new";
101
111
  }),
102
- complete: (id, result, state = opened.state) => inOrder(async () => {
112
+ complete: (id, result, state = opened.state, parts) => inOrder(async () => {
103
113
  const known = effects.get(id);
104
114
  if (!known)
105
115
  throw new RecoveryError(`Effect ${id} completes without an admission`);
106
116
  if (known.status === "completed")
107
117
  throw new RecoveryError(`Effect ${id} completes once`);
108
118
  const value = json(result);
109
- await commit((record) => { Object.assign(stored(record, id), { status: "completed", result: value }); record.state = json(state); });
119
+ await commit((record) => { Object.assign(stored(record, id), { status: "completed", result: value }); record.state = json(state); }, parts);
110
120
  effects.set(id, { ...known, status: "completed", result: value });
111
121
  }),
112
122
  called: (id, calls) => inOrder(async () => {
@@ -123,5 +133,7 @@ export async function openJournal(backend, bound) {
123
133
  await queue;
124
134
  await release();
125
135
  },
136
+ items: async (paths) => { const record = await backend.read(); return paths.map((path) => (record?.items && Object.hasOwn(record.items, path) ? json(record.items[path]) : undefined)); },
137
+ stateOf: async (sha256) => { const record = await backend.read(); return record?.states && Object.hasOwn(record.states, sha256) ? json(record.states[sha256]) : undefined; },
126
138
  };
127
139
  }
@@ -4,13 +4,27 @@ export type RecoveryBinding = {
4
4
  binding: string;
5
5
  inputs?: Record<string, string>;
6
6
  };
7
- /** A decision recorded beside the state, with the revision of the commit that wrote it. */
7
+ /** A decision recorded beside the state, with the revision of the commit that wrote it. `layout` says once per open
8
+ * that the driver keeps the whole state in one record although the host asked for the keyed layout, and why. */
8
9
  export type RecoveryNote = {
9
10
  revision: number;
10
- kind: "escalation" | "handoff" | "inherited";
11
+ kind: "escalation" | "handoff" | "inherited" | "layout";
11
12
  detail: unknown;
12
13
  at: string;
13
14
  };
15
+ /** A map item's record, as a store keeps it beside the state: plain JSON the driver writes and reads back. The store
16
+ * reads one field of it, `effects`: the ids of the effects admitted with this item as their owner. */
17
+ export type RecoveryItem = {
18
+ effects: string[];
19
+ [field: string]: unknown;
20
+ };
21
+ /** What a write keeps beside the state, in the same commit: map items' records by item path, each replacing the one
22
+ * before it whole, and states by their digest (`canonicalHash`), each written once and never changed. Computed with
23
+ * the commit's revision, after the state. */
24
+ export type RecoveryParts = {
25
+ items?: Record<string, RecoveryItem>;
26
+ states?: Record<string, unknown>;
27
+ };
14
28
  /** The external call an effect stands for: the tool it calls and the hash of the arguments it calls it with
15
29
  * (`canonicalHash` of the arguments). A continuation's own call is keyed the same way, so a call that repeats an
16
30
  * effect is known for one whatever the effect's status. */
@@ -49,10 +63,11 @@ export type RecoveryJournal = {
49
63
  effect(id: string): RecoveryEffect | undefined;
50
64
  notes(): RecoveryNote[];
51
65
  /** Commit a state computed with the commit's own revision, so a row that names its revision is never durable without
52
- * it, and a note when the state records a decision. Resolves to that revision. */
53
- save(state: (revision: number) => unknown, note?: Pick<RecoveryNote, "kind" | "detail">): Promise<number>;
54
- /** Commit the state, and a note when the state records a decision. Resolves to the commit's revision. */
55
- save(state: unknown, note?: Pick<RecoveryNote, "kind" | "detail">): Promise<number>;
66
+ * it, and a note when the state records a decision, and the parts that go with it. Resolves to that revision. */
67
+ save(state: (revision: number) => unknown, note?: Pick<RecoveryNote, "kind" | "detail">, parts?: (revision: number) => RecoveryParts): Promise<number>;
68
+ /** Commit the state, and a note when the state records a decision, and the parts that go with it. Resolves to the
69
+ * commit's revision. */
70
+ save(state: unknown, note?: Pick<RecoveryNote, "kind" | "detail">, parts?: (revision: number) => RecoveryParts): Promise<number>;
56
71
  /** Commit a note with no state change. Resolves to the commit's revision. */
57
72
  note(kind: RecoveryNote["kind"], detail: unknown): Promise<number>;
58
73
  /** Admit an effect before it is dispatched, with the state that admits it, in one commit, and the external call it
@@ -60,18 +75,27 @@ export type RecoveryJournal = {
60
75
  * later open. `args` are the call's arguments as the driver admitted it, kept with the effect as the host's door is sent them
61
76
  * (an optional field: a record without them reads as it always did). A store that does not keep them leaves a call that was
62
77
  * admitted and never sent unsettleable: a host's `reconcile` cannot re-send it, and the resume refuses it
63
- * (`FROZEN_EFFECT_UNKNOWN`). An id already admitted is returned as it stands and nothing is written. */
64
- admit(id: string, name: string, argsHash: string, state: unknown, session?: string | null, intent?: RecoveryIntent, args?: unknown): Promise<"new" | RecoveryEffect>;
78
+ * (`FROZEN_EFFECT_UNKNOWN`). An id already admitted is returned as it stands and nothing is written. `owner` names the
79
+ * map item whose record lists the effect, written in `parts` in the same commit: a store that keeps parts lists the
80
+ * effect there, and needs not list it again. */
81
+ admit(id: string, name: string, argsHash: string, state: unknown, session?: string | null, intent?: RecoveryIntent, args?: unknown, parts?: (revision: number) => RecoveryParts, owner?: string): Promise<"new" | RecoveryEffect>;
65
82
  /** Complete an admitted effect with its result, and the state that follows, in one commit. An effect completes once,
66
83
  * and never without an admission. With no state given, the state stays as this open found it: that is how an
67
84
  * operator reconciles an unknown effect. */
68
- complete(id: string, result: unknown, state?: unknown): Promise<void>;
85
+ complete(id: string, result: unknown, state?: unknown, parts?: (revision: number) => RecoveryParts): Promise<void>;
69
86
  /** Keep the outside calls an admitted effect made, whether or not the effect completes: the list given replaces the one the
70
87
  * effect held, and the effect's `calls` carries it from then on, at every later open. They are evidence for the host; no
71
88
  * resume depends on them. A caller that adds to the calls an earlier process kept passes the earlier ones first. */
72
89
  called(id: string, calls: unknown): Promise<void>;
73
90
  /** Let go of the journal. No later commit is made through this open, and the next open is the next generation. */
74
91
  close(): Promise<void>;
92
+ /** The records of the map items at `paths`, as the last commit that wrote each left it (undefined for one never
93
+ * written), so a driver reads back what it wrote in `parts`. The effects they list are then in `effects()` too.
94
+ * A store that keeps parts has both `items` and `stateOf`; a store without them cannot keep the keyed layout, and the
95
+ * driver keeps the whole state in one record there. */
96
+ items?(paths: string[]): Promise<Array<RecoveryItem | undefined>>;
97
+ /** The state written in `parts` under `sha256`, or undefined. */
98
+ stateOf?(sha256: string): Promise<unknown>;
75
99
  };
76
100
  /** Where one run's journal lives. `open` takes ownership of it: a journal that is already open is refused, a binding
77
101
  * that differs from the one the journal was first opened under is refused naming the inputs that moved, and the
@@ -210,4 +210,59 @@ export function registerStoreConformance(name, create) {
210
210
  assert.deepEqual(fourth.state, { kept: 1, nested: [null, { at: "1970-01-01T00:00:00.000Z" }] });
211
211
  await fourth.close();
212
212
  });
213
+ // Parts: a store that keeps them declares it with both reads, `items` and `stateOf`; a store with neither keeps the
214
+ // driver's whole state in one record, and these cases hold for it trivially.
215
+ const keeps = (journal) => {
216
+ assert.equal(typeof journal.items === "function", typeof journal.stateOf === "function", "a store declares both items and stateOf, or neither");
217
+ return typeof journal.items === "function";
218
+ };
219
+ const ITEM = "/root/steps/0/items/0";
220
+ it("parts are kept beside the state, in the same commit: an item's record replaced whole at each write, a state written once", async (store) => {
221
+ const first = await store.open(BOUND);
222
+ if (!keeps(first)) {
223
+ await first.close();
224
+ return;
225
+ }
226
+ assert.equal(await first.save({ n: 1 }, undefined, (revision) => ({ items: { [ITEM]: { effects: [], status: "running", revision } }, states: { "sha-a": { a: 1 } } })), 1);
227
+ assert.equal(await first.save({ n: 2 }, undefined, (revision) => ({ items: { [ITEM]: { effects: [], revision } }, states: { "sha-a": { a: "rewritten" }, "sha-b": { b: 2 } } })), 2);
228
+ await first.close();
229
+ const second = await store.open(BOUND);
230
+ assert.deepEqual(await second.items([ITEM, "/root/steps/0/items/1"]), [{ effects: [], revision: 2 }, undefined]);
231
+ assert.deepEqual([await second.stateOf("sha-a"), await second.stateOf("sha-b")], [{ a: 1 }, { b: 2 }]);
232
+ assert.deepEqual(second.state, { n: 2 });
233
+ await second.close();
234
+ });
235
+ it("an effect admitted with an owner is listed by the owner's record, and by effects() once that record is read", async (store) => {
236
+ const first = await store.open(BOUND);
237
+ if (!keeps(first)) {
238
+ await first.close();
239
+ return;
240
+ }
241
+ const owned = (ids) => () => ({ items: { [ITEM]: { effects: ids } } });
242
+ assert.equal(await first.admit("e1", "lookup", "args-1", { n: 1 }, "run-1", undefined, { id: 1 }, owned(["e1"]), ITEM), "new");
243
+ assert.equal(await first.admit("e2", "lookup", "args-2", { n: 2 }, "run-1", undefined, undefined, owned(["e1", "e2"]), ITEM), "new");
244
+ await first.complete("e1", { value: 1 }, { n: 3 }, owned(["e1", "e2"]));
245
+ await first.close();
246
+ const second = await store.open(BOUND);
247
+ const [record] = await second.items([ITEM]);
248
+ assert.deepEqual(record?.effects, ["e1", "e2"]);
249
+ assert.deepEqual(second.effects().map((effect) => [effect.id, effect.status, effect.result]).sort(), [["e1", "completed", { value: 1 }], ["e2", "unknown", null]]);
250
+ assert.deepEqual(second.effect("e1")?.args, { id: 1 });
251
+ assert.deepEqual(second.state, { n: 3 });
252
+ await second.close();
253
+ });
254
+ it("a write whose parts cannot be stored writes nothing at all, its state included", async (store) => {
255
+ const first = await store.open(BOUND);
256
+ if (!keeps(first)) {
257
+ await first.close();
258
+ return;
259
+ }
260
+ await first.save({ kept: 1 });
261
+ await assert.rejects(first.save({ kept: 2 }, undefined, () => ({ items: { [ITEM]: { effects: [], bad: Number.POSITIVE_INFINITY } } })), refused());
262
+ assert.equal(first.revision, 1);
263
+ await first.close();
264
+ const second = await store.open(BOUND);
265
+ assert.deepEqual([second.state, second.revision, await second.items([ITEM])], [{ kept: 1 }, 1, [undefined]]);
266
+ await second.close();
267
+ });
213
268
  }
@@ -1,5 +1,7 @@
1
- import type { WorkflowDeps } from "../workflow.js";
1
+ import { type WorkflowDeps } from "../workflow.js";
2
2
  import type { openRecovery, RecoveryEffectParams } from "./driver.js";
3
+ import { DECISION_INTERRUPTED } from "../decision-receipts.js";
4
+ export { DECISION_INTERRUPTED };
3
5
  /** A recovery driver, as `openRecovery` returns it. */
4
6
  export type RecoveryDriver = Awaited<ReturnType<typeof openRecovery>>;
5
7
  /** The attempt of an LLM step a node runner is asked to run, as the driver admitted it. One attempt is one session:
@@ -32,8 +34,12 @@ export type WithRecoveryOptions = {
32
34
  * things they have no slot for are applied to the host's adapters here:
33
35
  * - `runEffect`: each effect is admitted before it is dispatched, a completed one is answered from its receipt, and
34
36
  * one admitted and never completed is refused;
35
- * - `runJudge`: a route's answer is committed as its decision before any branch step runs, and a resume inside the
36
- * branch follows it without asking again; every answer's spend is committed with the driver's state;
37
+ * - `runJudge`: each request is committed (`decision.request`) before the judge is asked, and ends with one outcome:
38
+ * answered, or failed in its own process (asked again as its next attempt). A later open that finds it asked and
39
+ * never answered (the process died, or a cancel cut the call) books it once at an unknown cost and ends the run
40
+ * escalated (`decision_interrupted`) instead of asking again. A route's answer is committed as its decision before
41
+ * any branch step runs, and a resume inside the branch follows it without asking again; every answer's spend is
42
+ * committed with the driver's state;
37
43
  * - `runNode`: an LLM step's record is committed before the step runs, with two attempts, each handed to the
38
44
  * runner as its `step`. A failed attempt is followed at once by the second, unless the runner marked the
39
45
  * failure final; a step that spent both is refused at every later open. A process that dies inside a step spends
@@ -1,10 +1,19 @@
1
+ import { chargedCost, DecisionProviderError } from "../decision-provider.js";
1
2
  import { validateAnswers } from "../system-one.js";
3
+ import { EscalationSignal } from "../workflow.js";
4
+ import { canonicalHash } from "./canonical-hash.js";
5
+ import { DECISION_INTERRUPTED } from "../decision-receipts.js";
6
+ export { DECISION_INTERRUPTED };
2
7
  /** The dependencies to run a workflow with under `driver`. The interpreter's `recovery` hooks cover nodes; three
3
8
  * things they have no slot for are applied to the host's adapters here:
4
9
  * - `runEffect`: each effect is admitted before it is dispatched, a completed one is answered from its receipt, and
5
10
  * one admitted and never completed is refused;
6
- * - `runJudge`: a route's answer is committed as its decision before any branch step runs, and a resume inside the
7
- * branch follows it without asking again; every answer's spend is committed with the driver's state;
11
+ * - `runJudge`: each request is committed (`decision.request`) before the judge is asked, and ends with one outcome:
12
+ * answered, or failed in its own process (asked again as its next attempt). A later open that finds it asked and
13
+ * never answered (the process died, or a cancel cut the call) books it once at an unknown cost and ends the run
14
+ * escalated (`decision_interrupted`) instead of asking again. A route's answer is committed as its decision before
15
+ * any branch step runs, and a resume inside the branch follows it without asking again; every answer's spend is
16
+ * committed with the driver's state;
8
17
  * - `runNode`: an LLM step's record is committed before the step runs, with two attempts, each handed to the
9
18
  * runner as its `step`. A failed attempt is followed at once by the second, unless the runner marked the
10
19
  * failure final; a step that spent both is refused at every later open. A process that dies inside a step spends
@@ -23,22 +32,70 @@ export function withRecovery(driver, deps, options = {}) {
23
32
  const decided = params.kind === "route" ? driver.routeDecision(params.executionPath) : undefined;
24
33
  if (decided)
25
34
  return decided.result;
26
- const result = await runJudge(params);
27
- const cost = typeof result.cost_usd === "number" && Number.isFinite(result.cost_usd) ? result.cost_usd : null;
28
- // An answer the interpreter would refuse is spent at its price and is never a decision: the question is
29
- // asked again by the next process.
35
+ await driver.seam();
36
+ const decisionId = params.decisionId ?? canonicalHash(["decision-request", params.executionPath, params.kind, params.questions, params.state]);
37
+ const open = driver.admitDecision(params.executionPath, { decision_id: decisionId, kind: params.kind, label: params.label, model: params.model ?? null,
38
+ request_sha256: canonicalHash({ kind: params.kind, label: params.label, state: params.state, questions: params.questions }) });
39
+ if (open) {
40
+ // An earlier process asked and its answer never reached a receipt: never asked again, booked once at an unknown
41
+ // cost, and the run goes to review. The unknown cost is counted with the outcome in one commit, the way the
42
+ // answered and failed paths commit theirs, so the run's spend reads incomplete and never omits it.
43
+ if (open.status === "requested")
44
+ driver.decisionEnded(params.executionPath, decisionId, "interrupted", null, () => driver.recordQuestionSpend(null));
45
+ await driver.flush();
46
+ throw new EscalationSignal({ kind: DECISION_INTERRUPTED, stage: "decision", executionPath: params.executionPath, label: params.label, state: driver.lastState(),
47
+ summary: `The decision "${params.label}" was asked by an earlier process and its answer never reached a receipt; it is not asked again.` });
48
+ }
30
49
  try {
31
- validateAnswers(params.questions, result.answers);
50
+ // The request is durable before the judge is asked.
51
+ await driver.flush();
52
+ let result;
53
+ try {
54
+ result = await runJudge(params);
55
+ }
56
+ catch (error) {
57
+ // A request sent whose outcome was lost may have been answered and billed: it is interrupted, never asked again,
58
+ // and its estimate (or an unknown cost, which makes the spend read incomplete) is booked with that outcome.
59
+ const charge = chargedCost(error);
60
+ if (error instanceof DecisionProviderError && error.code === "outcome_unknown") {
61
+ driver.decisionEnded(params.executionPath, decisionId, "interrupted", charge ?? null, () => driver.recordQuestionSpend(charge ?? null));
62
+ throw error;
63
+ }
64
+ // An answer rejected after it was paid for failed, and its cost (or an unknown one) is booked with that outcome:
65
+ // the next process asks again.
66
+ if (charge !== undefined) {
67
+ driver.decisionEnded(params.executionPath, decisionId, "failed", charge, () => driver.recordQuestionSpend(charge));
68
+ throw error;
69
+ }
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; 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))
75
+ driver.decisionEnded(params.executionPath, decisionId, "failed", null);
76
+ throw error;
77
+ }
78
+ const cost = typeof result.cost_usd === "number" && Number.isFinite(result.cost_usd) ? result.cost_usd : null;
79
+ // An answer the interpreter would refuse is spent at its price and is never a decision: the question is
80
+ // asked again by the next process.
81
+ try {
82
+ validateAnswers(params.questions, result.answers);
83
+ }
84
+ catch (error) {
85
+ driver.decisionEnded(params.executionPath, decisionId, "failed", cost, () => driver.recordQuestionSpend(cost));
86
+ throw error;
87
+ }
88
+ // The outcome, the spend and a route's decision are one commit.
89
+ driver.decisionEnded(params.executionPath, decisionId, "answered", cost, () => driver.recordQuestionSpend(cost, params.kind === "route"
90
+ ? { executionPath: params.executionPath, label: params.label, result: result, receipts: null } : undefined));
91
+ // The decision is durable before the interpreter acts on the answer, and a stop taken meanwhile ends the run here.
92
+ await driver.flush();
93
+ driver.checkStop();
94
+ return result;
32
95
  }
33
- catch (error) {
34
- driver.recordQuestionSpend(cost);
35
- throw error;
96
+ finally {
97
+ driver.decisionSettled();
36
98
  }
37
- driver.recordQuestionSpend(cost, params.kind === "route" ? { executionPath: params.executionPath, label: params.label, result: result, receipts: null } : undefined);
38
- // The decision is durable before the interpreter acts on the answer, and a stop taken meanwhile ends the run here.
39
- await driver.flush();
40
- driver.checkStop();
41
- return result;
42
99
  }),
43
100
  runNode: runNode && (async (params) => {
44
101
  const admit = () => driver.stepSession(params.executionPath, params.label, { attemptsAllowed: 2 });
@@ -50,8 +107,11 @@ export function withRecovery(driver, deps, options = {}) {
50
107
  driver.stepAttemptFailed(params.executionPath);
51
108
  admission = admit();
52
109
  }
53
- if (admission.status === "failed")
54
- throw new Error(`${params.label} failed after ${admission.attemptsAllowed} attempts`);
110
+ // A step that failed on an item failure is refused with it, so the item it lies in ends on the same failure.
111
+ if (admission.status === "failed") {
112
+ throw admission.failure ? Object.assign(new Error(admission.failure.message), { code: admission.failure.code, itemFailure: true })
113
+ : new Error(`${params.label} failed after ${admission.attemptsAllowed} attempts`);
114
+ }
55
115
  // The step's record is durable before the attempt runs. A stop or a caller's cancellation that landed
56
116
  // meanwhile ends the step here: the runner is not called, and no attempt is spent. A pause waiting for an
57
117
  // effect in flight holds the step here until it is taken.
@@ -71,7 +131,7 @@ export function withRecovery(driver, deps, options = {}) {
71
131
  // A failure the runner marked final (an attempt that ended on a bound of its own) gets no second attempt: it
72
132
  // would spend the same again.
73
133
  const final = error?.final === true;
74
- driver.stepAttemptFailed(params.executionPath, final);
134
+ driver.stepAttemptFailed(params.executionPath, final, error);
75
135
  if (final)
76
136
  throw error;
77
137
  admission = admit();
@@ -0,0 +1,9 @@
1
+ /** The input schema of a node runner's `submit` tool: the node's output schema under `value`, as
2
+ * `{ value: <schema> }`. A node schema is not a valid tool input as it stands (a root `$ref` or `$defs`
3
+ * is not an object schema), and embedding it moves the document root its local pointers resolve
4
+ * against, so each local `$ref` (`#`, `#/...`) is relocated under `#/properties/value`. A subschema
5
+ * that sets its own `$id` is a separate resource: its local references do not move. Every runner that
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 the host alone reads (`criteria`, any `x-` one) is left out of every schema in it, never a property or
8
+ * definition of that name; the submission is still checked against the node's schema as written. */
9
+ export declare function submitParameters(schema: unknown): Record<string, unknown>;
@@ -0,0 +1,44 @@
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-");
7
+ /** The input schema of a node runner's `submit` tool: the node's output schema under `value`, as
8
+ * `{ value: <schema> }`. A node schema is not a valid tool input as it stands (a root `$ref` or `$defs`
9
+ * is not an object schema), and embedding it moves the document root its local pointers resolve
10
+ * against, so each local `$ref` (`#`, `#/...`) is relocated under `#/properties/value`. A subschema
11
+ * that sets its own `$id` is a separate resource: its local references do not move. Every runner that
12
+ * delivers a node's record through a tool call uses this one envelope, so a schema behaves the same on
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
14
+ * definition of that name; the submission is still checked against the node's schema as written. */
15
+ export function submitParameters(schema) {
16
+ const maps = new Set(["properties", "patternProperties", "$defs", "definitions", "dependentSchemas"]);
17
+ const singles = new Set(["additionalProperties", "unevaluatedProperties", "propertyNames", "items", "additionalItems", "contains", "unevaluatedItems", "not", "if", "then", "else", "contentSchema"]);
18
+ const arrays = new Set(["allOf", "anyOf", "oneOf", "prefixItems"]);
19
+ const relocate = (node, resourceScope = false) => {
20
+ if (!isRecord(node))
21
+ return structuredClone(node);
22
+ // $id establishes a separate schema resource: its local references do not move.
23
+ resourceScope ||= typeof node.$id === "string" && node.$id !== "";
24
+ const child = (value) => relocate(value, resourceScope);
25
+ return Object.fromEntries(Object.entries(node).filter(([key]) => !hostOnlyKeyword(key)).map(([key, value]) => {
26
+ if (!resourceScope && key === "$ref" && typeof value === "string" && (value === "#" || value.startsWith("#/"))) {
27
+ return [key, `#/properties/value${value.slice(1)}`];
28
+ }
29
+ if (maps.has(key) && isRecord(value)) {
30
+ return [key, Object.fromEntries(Object.entries(value).map(([name, value]) => [name, child(value)]))];
31
+ }
32
+ if (arrays.has(key) && Array.isArray(value))
33
+ return [key, value.map(child)];
34
+ if (singles.has(key))
35
+ return [key, Array.isArray(value) ? value.map(child) : child(value)];
36
+ if (key === "dependencies" && isRecord(value)) {
37
+ return [key, Object.fromEntries(Object.entries(value).map(([name, value]) => [name, Array.isArray(value) ? structuredClone(value) : child(value)]))];
38
+ }
39
+ // Annotations and literal values are data, not schemas (including a literal $ref).
40
+ return [key, structuredClone(value)];
41
+ }));
42
+ };
43
+ return { type: "object", properties: { value: relocate(schema) }, required: ["value"], additionalProperties: false };
44
+ }
@@ -13,6 +13,18 @@ export type SystemOneQuestion = {
13
13
  type: "score";
14
14
  instructions: string;
15
15
  criteria: string[];
16
+ }
17
+ /** Locates what its instructions describe in the request's image. A host-side question: no workflow node declares one, and it needs an image sent with the request. */
18
+ | {
19
+ type: "box";
20
+ instructions: string;
21
+ };
22
+ /** A box's edges as fractions of the image's height (`top`, `bottom`) and width (`left`, `right`), from the top left corner. */
23
+ export type SystemOneBox = {
24
+ top: number;
25
+ bottom: number;
26
+ left: number;
27
+ right: number;
16
28
  };
17
29
  export type SystemOneAnswer = {
18
30
  type: "choice";
@@ -28,6 +40,14 @@ export type SystemOneAnswer = {
28
40
  legend: Record<string, string>;
29
41
  probabilities: Record<string, number>;
30
42
  confidence: number;
43
+ } | {
44
+ type: "box";
45
+ box: SystemOneBox;
46
+ confidence: number | null;
47
+ }
48
+ /** The provider declined to answer this question. It is never decoded as a value. */
49
+ | {
50
+ type: "refusal";
31
51
  };
32
52
  export type SystemOneResult = {
33
53
  answers: Record<string, SystemOneAnswer>;
@@ -45,7 +65,6 @@ export declare const SYSTEM_ONE_LIMITS: {
45
65
  readonly minScoreLevels: 2;
46
66
  readonly maxScoreLevels: 10;
47
67
  };
48
- export declare const SYSTEM_ONE_DEFAULT_MODEL = "jev-latest";
49
68
  export type CompiledQuestions = Record<string, SystemOneQuestion>;
50
69
  export declare function compileQuestions(schema: Record<string, unknown>, definitions?: Record<string, unknown>): {
51
70
  ok: true;
@@ -65,7 +84,7 @@ export type AnswersSidecar = {
65
84
  export declare function answersSidecar(answers: Record<string, SystemOneAnswer>): AnswersSidecar;
66
85
  export declare function synthesizeAnswers(questions: Record<string, SystemOneQuestion>): Record<string, SystemOneAnswer>;
67
86
  export type SystemOneRetryClass = "http_429" | "http_5xx" | "connection" | "timeout";
68
- declare const responseReasons: readonly ["answers_shape", "answer_keys", "answer_shape", "answer_type", "noul_probability", "confidence", "probabilities", "probability_keys", "probability_mass", "score_legend", "score_consistency", "choice_option", "score_range"];
87
+ declare const responseReasons: readonly ["answers_shape", "answer_keys", "answer_shape", "answer_type", "noul_probability", "confidence", "box_coordinates", "probabilities", "probability_keys", "probability_mass", "score_legend", "score_consistency", "choice_option", "score_range", "refusal"];
69
88
  export type SystemOneResponseReason = typeof responseReasons[number];
70
89
  export declare function isSystemOneResponseReason(value: unknown): value is SystemOneResponseReason;
71
90
  export declare class SystemOneError extends Error {
@@ -75,4 +94,20 @@ export declare class SystemOneError extends Error {
75
94
  constructor(message: string, retryClass: SystemOneRetryClass | null, status?: number | undefined, responseReason?: SystemOneResponseReason);
76
95
  }
77
96
  export declare function validateAnswers(questions: Record<string, SystemOneQuestion>, answers: unknown): asserts answers is Record<string, SystemOneAnswer>;
97
+ /** The questions whose answer is a refusal, in answer order. */
98
+ export declare function refusedQuestions(answers: Record<string, unknown>): string[];
99
+ /** The confidence TypeSafe documents for Jev (docs.typesafe.ai/confidence), computed from an answer's probabilities: for a
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
101
+ * the probability-weighted distance from the most likely level (the lowest, on a tie) over that distance for an even
102
+ * spread, floored at 0. Null when the probabilities are missing or are not a distribution over the answer's options. */
103
+ export declare function deriveConfidence(answer: unknown): number | null;
104
+ /** Where an answer's confidence came from: the provider's response, or derived from its probabilities. */
105
+ export type ConfidenceSource = "provider" | "derived";
106
+ /** The answers with every choice and score carrying a confidence: the provider's own when it gave one in [0, 1], else
107
+ * one derived from the probabilities (deriveConfidence), else 0, which validation then refuses with the probabilities
108
+ * that left nothing to derive from. `confidence_source` names each choice and score answer's source. */
109
+ export declare function completeConfidence(questions: Record<string, SystemOneQuestion>, answers: Record<string, unknown>): {
110
+ answers: Record<string, unknown>;
111
+ confidence_source: Record<string, ConfidenceSource>;
112
+ };
78
113
  export {};