taugraph 0.3.0 → 0.4.0

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 (79) hide show
  1. package/CHANGELOG.md +28 -1
  2. package/README.md +55 -8
  3. package/README.zh-CN.md +55 -8
  4. package/dist/agent/index.d.ts +8 -0
  5. package/dist/agent/index.d.ts.map +1 -1
  6. package/dist/agent/index.js +30 -4
  7. package/dist/agent/index.js.map +1 -1
  8. package/dist/agent/util.d.ts +10 -0
  9. package/dist/agent/util.d.ts.map +1 -1
  10. package/dist/agent/util.js +31 -0
  11. package/dist/agent/util.js.map +1 -1
  12. package/dist/core/engine.d.ts +1 -1
  13. package/dist/core/engine.d.ts.map +1 -1
  14. package/dist/core/engine.js +237 -35
  15. package/dist/core/engine.js.map +1 -1
  16. package/dist/core/errors.d.ts +2 -0
  17. package/dist/core/errors.d.ts.map +1 -1
  18. package/dist/core/errors.js.map +1 -1
  19. package/dist/core/graph.d.ts.map +1 -1
  20. package/dist/core/graph.js +9 -1
  21. package/dist/core/graph.js.map +1 -1
  22. package/dist/core/node.d.ts +6 -1
  23. package/dist/core/node.d.ts.map +1 -1
  24. package/dist/core/node.js +55 -6
  25. package/dist/core/node.js.map +1 -1
  26. package/dist/core/patch.d.ts +26 -0
  27. package/dist/core/patch.d.ts.map +1 -0
  28. package/dist/core/patch.js +192 -0
  29. package/dist/core/patch.js.map +1 -0
  30. package/dist/core/retry.d.ts +20 -0
  31. package/dist/core/retry.d.ts.map +1 -0
  32. package/dist/core/retry.js +79 -0
  33. package/dist/core/retry.js.map +1 -0
  34. package/dist/core/trace.d.ts +39 -8
  35. package/dist/core/trace.d.ts.map +1 -1
  36. package/dist/core/trace.js +222 -29
  37. package/dist/core/trace.js.map +1 -1
  38. package/dist/core/types.d.ts +35 -4
  39. package/dist/core/types.d.ts.map +1 -1
  40. package/dist/core/util.d.ts +5 -1
  41. package/dist/core/util.d.ts.map +1 -1
  42. package/dist/core/util.js +41 -9
  43. package/dist/core/util.js.map +1 -1
  44. package/dist/file/index.d.ts +26 -0
  45. package/dist/file/index.d.ts.map +1 -0
  46. package/dist/file/index.js +373 -0
  47. package/dist/file/index.js.map +1 -0
  48. package/dist/index.d.ts +4 -3
  49. package/dist/index.d.ts.map +1 -1
  50. package/dist/index.js +2 -1
  51. package/dist/index.js.map +1 -1
  52. package/dist/nodes/code.d.ts +5 -0
  53. package/dist/nodes/code.d.ts.map +1 -1
  54. package/dist/nodes/code.js.map +1 -1
  55. package/dist/nodes/llm.d.ts +2 -0
  56. package/dist/nodes/llm.d.ts.map +1 -1
  57. package/dist/nodes/llm.js +5 -1
  58. package/dist/nodes/llm.js.map +1 -1
  59. package/dist/openai/index.d.ts +17 -1
  60. package/dist/openai/index.d.ts.map +1 -1
  61. package/dist/openai/index.js +32 -2
  62. package/dist/openai/index.js.map +1 -1
  63. package/package.json +6 -2
  64. package/src/agent/index.ts +47 -3
  65. package/src/agent/util.ts +39 -0
  66. package/src/core/engine.ts +241 -34
  67. package/src/core/errors.ts +2 -0
  68. package/src/core/graph.ts +7 -1
  69. package/src/core/node.ts +55 -6
  70. package/src/core/patch.ts +173 -0
  71. package/src/core/retry.ts +89 -0
  72. package/src/core/trace.ts +222 -29
  73. package/src/core/types.ts +37 -4
  74. package/src/core/util.ts +43 -10
  75. package/src/file/index.ts +408 -0
  76. package/src/index.ts +5 -1
  77. package/src/nodes/code.ts +5 -0
  78. package/src/nodes/llm.ts +7 -1
  79. package/src/openai/index.ts +43 -3
@@ -0,0 +1,173 @@
1
+ // A JSON Patch (RFC 6902) subset for trace format v2: add, remove and replace. Diffs are tuned for
2
+ // state that mostly grows, so new object keys and items appended to arrays stay small.
3
+ import { jsonEqual } from "./util.js";
4
+
5
+ export type PatchOp =
6
+ | { readonly op: "add"; readonly path: string; readonly value: unknown }
7
+ | { readonly op: "replace"; readonly path: string; readonly value: unknown }
8
+ | { readonly op: "remove"; readonly path: string };
9
+
10
+ const escapeKey = (key: string) => key.replace(/~/g, "~0").replace(/\//g, "~1");
11
+ const unescapeToken = (token: string) => token.replace(/~1/g, "/").replace(/~0/g, "~");
12
+ const isRecord = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v);
13
+ /** Own properties only: `o.constructor` or `o.toString` must not count as keys that are there. */
14
+ const own = (o: Record<string, unknown>, key: string): unknown => (Object.hasOwn(o, key) ? o[key] : undefined);
15
+ /** Sets an own data property. Assigning `o["__proto__"] = x` would set the prototype instead. */
16
+ const define = (o: Record<string, unknown>, key: string, value: unknown): void => {
17
+ Object.defineProperty(o, key, { value, enumerable: true, writable: true, configurable: true });
18
+ };
19
+ const OPS: ReadonlySet<unknown> = new Set(["add", "remove", "replace"]);
20
+
21
+ /** Like `jsonEqual`, but object keys (those with defined values) must also be in the same order. */
22
+ function sameJson(x: unknown, y: unknown): boolean {
23
+ if (x === y) return true;
24
+ if (Array.isArray(x) && Array.isArray(y)) {
25
+ return x.length === y.length && x.every((item, i) => sameJson(item, y[i]));
26
+ }
27
+ if (isRecord(x) && isRecord(y)) {
28
+ const kx = Object.keys(x).filter((key) => own(x, key) !== undefined);
29
+ const ky = Object.keys(y).filter((key) => own(y, key) !== undefined);
30
+ return kx.length === ky.length && kx.every((key, i) => key === ky[i] && sameJson(own(x, key), own(y, key)));
31
+ }
32
+ return jsonEqual(x, y);
33
+ }
34
+
35
+ /** Operations that turn `from` into `to`; `[]` when they are equal. Object keys set to `undefined` count as absent. */
36
+ export function diffJson(from: unknown, to: unknown): PatchOp[] {
37
+ const ops: PatchOp[] = [];
38
+ walk(from, to, "", ops);
39
+ return ops;
40
+ }
41
+
42
+ function walk(a: unknown, b: unknown, path: string, ops: PatchOp[]): void {
43
+ if (a === b) return;
44
+ if (Array.isArray(a) && Array.isArray(b)) {
45
+ if (b.length >= a.length && a.every((item, i) => sameJson(item, b[i]))) {
46
+ for (let i = a.length; i < b.length; i++) ops.push({ op: "add", path: `${path}/-`, value: b[i] });
47
+ return;
48
+ }
49
+ if (a.length === b.length) {
50
+ for (let i = 0; i < a.length; i++) walk(a[i], b[i], `${path}/${i}`, ops);
51
+ return;
52
+ }
53
+ ops.push({ op: "replace", path, value: b });
54
+ return;
55
+ }
56
+ if (isRecord(a) && isRecord(b)) {
57
+ // The per-key operations keep the keys that stay in their order and add new ones at the end. If that is not the
58
+ // order of `b`, replace the object.
59
+ const before = Object.keys(a).filter((key) => own(a, key) !== undefined);
60
+ const after = Object.keys(b).filter((key) => own(b, key) !== undefined);
61
+ const expected = [
62
+ ...before.filter((key) => own(b, key) !== undefined),
63
+ ...after.filter((key) => own(a, key) === undefined),
64
+ ];
65
+ if (after.length !== expected.length || after.some((key, i) => key !== expected[i])) {
66
+ ops.push({ op: "replace", path, value: b });
67
+ return;
68
+ }
69
+ for (const key of before) {
70
+ if (own(b, key) === undefined) ops.push({ op: "remove", path: `${path}/${escapeKey(key)}` });
71
+ }
72
+ for (const key of after) {
73
+ const next = own(b, key);
74
+ const prev = own(a, key);
75
+ if (prev === undefined) ops.push({ op: "add", path: `${path}/${escapeKey(key)}`, value: next });
76
+ else walk(prev, next, `${path}/${escapeKey(key)}`, ops);
77
+ }
78
+ return;
79
+ }
80
+ if (!jsonEqual(a, b)) ops.push({ op: "replace", path, value: b });
81
+ }
82
+
83
+ /**
84
+ * Applies `ops` to `base` without changing it. Parts the operations do not touch keep their identity.
85
+ * Only the subset is accepted: `add` to an array takes `-` (append) or an index from 0 to its length (insert),
86
+ * and `replace` / `remove` need the key or index to exist.
87
+ */
88
+ export function applyPatch(base: unknown, ops: readonly PatchOp[]): unknown {
89
+ let doc = base;
90
+ for (const op of ops) {
91
+ if (!OPS.has(op.op)) throw new Error(`patch op ${String(op.op)} is not supported`);
92
+ if (op.path === "") {
93
+ if (op.op === "remove") throw new Error("patch cannot remove the whole value");
94
+ doc = op.value;
95
+ continue;
96
+ }
97
+ if (!op.path.startsWith("/")) throw new Error(`patch path ${op.path} must start with "/"`);
98
+ doc = setIn(doc, op.path.slice(1).split("/").map(unescapeToken), 0, op);
99
+ }
100
+ return doc;
101
+ }
102
+
103
+ function setIn(node: unknown, tokens: readonly string[], i: number, op: PatchOp): unknown {
104
+ const token = tokens[i] as string;
105
+ const last = i === tokens.length - 1;
106
+ if (Array.isArray(node)) {
107
+ const copy = node.slice();
108
+ if (last && op.op === "add" && token === "-") {
109
+ copy.push(op.value);
110
+ return copy;
111
+ }
112
+ const at = Number(token);
113
+ const end = last && op.op === "add" ? copy.length : copy.length - 1;
114
+ if (!/^(0|[1-9]\d*)$/.test(token) || at > end) throw new Error(`patch path ${op.path} does not exist`);
115
+ if (last) {
116
+ if (op.op === "add") copy.splice(at, 0, op.value);
117
+ else if (op.op === "remove") copy.splice(at, 1);
118
+ else copy[at] = op.value;
119
+ return copy;
120
+ }
121
+ copy[at] = setIn(copy[at], tokens, i + 1, op);
122
+ return copy;
123
+ }
124
+ if (isRecord(node)) {
125
+ // Spreading keeps an own `__proto__` key as an own data property.
126
+ const copy: Record<string, unknown> = { ...node };
127
+ if (last && op.op === "add") define(copy, token, op.value);
128
+ else if (!Object.hasOwn(copy, token)) throw new Error(`patch path ${op.path} does not exist`);
129
+ else if (!last) define(copy, token, setIn(copy[token], tokens, i + 1, op));
130
+ else if (op.op === "remove") delete copy[token];
131
+ else define(copy, token, op.value);
132
+ return copy;
133
+ }
134
+ throw new Error(`patch path ${op.path} does not exist`);
135
+ }
136
+
137
+ /**
138
+ * `JSON.stringify(value).length` when that is at most `limit`, otherwise some number greater than `limit`.
139
+ * It stops as soon as the count passes `limit`, so a large value costs about `limit` characters of work.
140
+ */
141
+ export function jsonLengthAtMost(value: unknown, limit: number): number {
142
+ let length = 0;
143
+ const fits = (v: unknown): boolean => {
144
+ if (typeof v === "string") {
145
+ // Quotes and escapes only add characters, so the escaped form is checked only when the raw one fits.
146
+ length += v.length + 2;
147
+ if (length <= limit) length += JSON.stringify(v).length - v.length - 2;
148
+ } else if (typeof v === "number") {
149
+ length += Number.isFinite(v) ? String(v).length : 4;
150
+ } else if (typeof v === "boolean") {
151
+ length += v ? 4 : 5;
152
+ } else if (Array.isArray(v)) {
153
+ length += Math.max(2, v.length + 1);
154
+ for (let i = 0; i < v.length && length <= limit; i++) fits(v[i] ?? null);
155
+ } else if (isRecord(v)) {
156
+ length += 2;
157
+ let first = true;
158
+ for (const key of Object.keys(v)) {
159
+ if (length > limit) break;
160
+ const item = v[key];
161
+ if (item === undefined) continue;
162
+ length += first ? 1 : 2;
163
+ first = false;
164
+ if (fits(key)) fits(item);
165
+ }
166
+ } else {
167
+ length += 4;
168
+ }
169
+ return length <= limit;
170
+ };
171
+ fits(value);
172
+ return length;
173
+ }
@@ -0,0 +1,89 @@
1
+ import { TaugraphError, type TaugraphErrorCode } from "./errors.js";
2
+ import type { RetryPolicy } from "./types.js";
3
+
4
+ /** Kernel errors that another attempt cannot fix. */
5
+ const PERMANENT: ReadonlySet<TaugraphErrorCode> = new Set<TaugraphErrorCode>([
6
+ "INVALID_STATE",
7
+ "INVALID_ROUTE",
8
+ "INVALID_EVENT",
9
+ "WRITE_BLOCKED",
10
+ "UNKNOWN_OUTCOME",
11
+ "NOT_RESUMABLE",
12
+ "ABORTED",
13
+ "ASYNC_IN_SYNC_RUN",
14
+ "SINK_FAILED",
15
+ ]);
16
+
17
+ /** Never retried, whatever `retryOn` says: the run itself is stopping. */
18
+ export const FATAL: ReadonlySet<TaugraphErrorCode> = new Set<TaugraphErrorCode>([
19
+ "ABORTED",
20
+ "ASYNC_IN_SYNC_RUN",
21
+ "SINK_FAILED",
22
+ ]);
23
+
24
+ /** 4xx statuses that mean "later": request timeout, conflict, too early, too many requests. */
25
+ const RETRYABLE_4XX: ReadonlySet<number> = new Set([408, 409, 425, 429]);
26
+
27
+ /** Levels of `cause` searched below the error itself. */
28
+ const CAUSE_DEPTH = 5;
29
+
30
+ /** The longest wait a timer can take (about 24.8 days); a longer one would fire at once. */
31
+ export const MAX_DELAY_MS = 2_147_483_647;
32
+
33
+ /** The nearest finite number under `key` on the error or its `cause` chain. */
34
+ function fromChain(error: unknown, key: "status" | "retryAfterMs"): number | undefined {
35
+ let current = error;
36
+ for (let depth = 0; depth <= CAUSE_DEPTH; depth++) {
37
+ if (typeof current !== "object" || current === null) return undefined;
38
+ const value = (current as Record<string, unknown>)[key];
39
+ if (typeof value === "number" && Number.isFinite(value)) return value;
40
+ current = (current as { cause?: unknown }).cause;
41
+ }
42
+ return undefined;
43
+ }
44
+
45
+ /**
46
+ * Whether another attempt may succeed. False for kernel errors that a retry cannot fix (`INVALID_STATE`, `ABORTED`,
47
+ * `SINK_FAILED`, ...) and for HTTP 4xx other than 408, 409, 425 and 429, read from a numeric `status` on the error or
48
+ * its `cause` chain. True for everything else, including errors it knows nothing about.
49
+ */
50
+ export function isRetryable(error: unknown): boolean {
51
+ if (error instanceof TaugraphError && PERMANENT.has(error.code)) return false;
52
+ const status = fromChain(error, "status");
53
+ return status === undefined || status < 400 || status >= 500 || RETRYABLE_4XX.has(status);
54
+ }
55
+
56
+ /**
57
+ * Milliseconds to wait before retry number `retry` (1 for the first): exponential backoff with jitter, or the error's
58
+ * `retryAfterMs` when that is longer.
59
+ */
60
+ export function retryDelay(
61
+ policy: RetryPolicy,
62
+ retry: number,
63
+ error: unknown,
64
+ random: () => number = Math.random,
65
+ ): number {
66
+ let delay = 0;
67
+ if (policy.backoff !== false) {
68
+ const backoff = policy.backoff ?? {};
69
+ const initialMs = backoff.initialMs ?? 500;
70
+ const factor = backoff.factor ?? 2;
71
+ const maxMs = backoff.maxMs ?? 30_000;
72
+ const jitter = backoff.jitter ?? 0.5;
73
+ delay = Math.min(maxMs, initialMs * factor ** (retry - 1)) * (1 - jitter * random());
74
+ }
75
+ const after = fromChain(error, "retryAfterMs");
76
+ if (after !== undefined && after > delay) delay = after;
77
+ return Math.min(MAX_DELAY_MS, Math.max(0, Math.round(delay)));
78
+ }
79
+
80
+ /** A frozen copy of a checked policy, so changing the object passed in cannot change the node. */
81
+ export function freezeRetry(retry: RetryPolicy): RetryPolicy {
82
+ const { backoff } = retry;
83
+ return Object.freeze({
84
+ maxAttempts: retry.maxAttempts,
85
+ ...(backoff !== undefined && { backoff: backoff === false ? false : Object.freeze({ ...backoff }) }),
86
+ ...(retry.retryOn !== undefined && { retryOn: retry.retryOn }),
87
+ ...(retry.idempotent !== undefined && { idempotent: retry.idempotent }),
88
+ });
89
+ }
package/src/core/trace.ts CHANGED
@@ -1,9 +1,11 @@
1
1
  import { TaugraphError } from "./errors.js";
2
- import type { KernelEventType, Trace, TraceEvent, TraceEventType } from "./types.js";
3
- import { freezeJson, jsonEqual } from "./util.js";
2
+ import { applyPatch, diffJson, jsonLengthAtMost, type PatchOp } from "./patch.js";
3
+ import type { KernelEventType, MaybePromise, Trace, TraceEvent, TraceEventType } from "./types.js";
4
+ import { freezeJson, isThenable, jsonEqual } from "./util.js";
4
5
 
5
6
  export const TRACE_FORMAT = "taugraph.trace";
6
- export const TRACE_VERSION = 1;
7
+ export const TRACE_VERSION = 2;
8
+ const READABLE_VERSIONS: ReadonlySet<unknown> = new Set([1, 2]);
7
9
 
8
10
  export const KERNEL_EVENT_TYPES: ReadonlySet<string> = new Set<KernelEventType>([
9
11
  "run_start",
@@ -24,21 +26,26 @@ export interface EventDraft {
24
26
  readonly meta?: Readonly<Record<string, unknown>> | undefined;
25
27
  }
26
28
 
29
+ type Sink = (event: TraceEvent) => MaybePromise<void>;
30
+
27
31
  /**
28
32
  * Append-only event log for one run. Payloads must already be frozen JSON
29
33
  * (see `freezeJson`); the log only assigns seq / runId / timestamp and freezes the envelope.
30
34
  *
31
- * Every event is handed to `onEvent` before `append` returns. If the sink throws, `append`
32
- * throws SINK_FAILED and keeps throwing, so the run cannot take another step unlogged.
35
+ * Every event goes to `onEvent` in order, one call at a time: while an async call is unfinished, later events wait in
36
+ * a chain, and `pending()` gives the engine that chain to wait on. If the sink throws or rejects, `append` throws
37
+ * SINK_FAILED and keeps throwing, so the run cannot take another step unlogged.
33
38
  */
34
39
  export class TraceLog {
35
40
  readonly #events: TraceEvent[];
36
41
  readonly #runId: string;
37
- readonly #onEvent: ((event: TraceEvent) => void) | undefined;
42
+ #onEvent: Sink | undefined;
38
43
  #sinkError: { readonly cause: unknown } | undefined;
44
+ /** Unfinished calls of an async sink, chained in event order. */
45
+ #tail: Promise<void> | undefined;
39
46
 
40
47
  /** `prefix` continues an existing trace (resume); it is not sent to `onEvent` again. */
41
- constructor(runId: string, onEvent?: (event: TraceEvent) => void, prefix: Trace = []) {
48
+ constructor(runId: string, onEvent?: Sink, prefix: Trace = []) {
42
49
  this.#runId = runId;
43
50
  this.#onEvent = onEvent;
44
51
  this.#events = prefix.map((event) => freezeJson(event));
@@ -64,6 +71,26 @@ export class TraceLog {
64
71
  return event;
65
72
  }
66
73
 
74
+ /**
75
+ * Resolves once an async sink has stored every event so far, or rejects with SINK_FAILED. Undefined when no call
76
+ * is unfinished, which is always the case with a synchronous sink.
77
+ */
78
+ pending(): Promise<void> | undefined {
79
+ const tail = this.#tail;
80
+ if (!tail) return undefined;
81
+ const done = tail.then(() => {
82
+ if (this.#tail === tail) this.#tail = undefined;
83
+ });
84
+ // An aborted run stops waiting without a handler; awaiting `done` still sees the rejection.
85
+ done.catch(() => {});
86
+ return done;
87
+ }
88
+
89
+ /** Stops calling the sink: `runSync` does this once the sink returned a Promise it cannot wait for. */
90
+ detach(): void {
91
+ this.#onEvent = undefined;
92
+ }
93
+
67
94
  snapshot(): Trace {
68
95
  return Object.freeze(this.#events.slice());
69
96
  }
@@ -86,14 +113,43 @@ export class TraceLog {
86
113
  }
87
114
 
88
115
  #emit(event: TraceEvent): void {
89
- if (!this.#onEvent) return;
116
+ const sink = this.#onEvent;
117
+ if (!sink) return;
118
+ if (this.#tail) {
119
+ // Read the sink when the call is due, so detach() also stops calls queued before it.
120
+ this.#chain(
121
+ this.#tail.then(() => {
122
+ const due = this.#onEvent;
123
+ return due ? this.#call(due, event) : undefined;
124
+ }),
125
+ );
126
+ return;
127
+ }
128
+ const result = this.#call(sink, event);
129
+ if (isThenable(result)) this.#chain(Promise.resolve(result));
130
+ }
131
+
132
+ /** Calls the sink. A synchronous throw marks the log as failed and becomes SINK_FAILED. */
133
+ #call(sink: Sink, event: TraceEvent): unknown {
90
134
  try {
91
- this.#onEvent(event);
135
+ return sink(event);
92
136
  } catch (cause) {
93
- this.#sinkError = { cause };
94
- throw sinkFailed(cause);
137
+ if (!this.#sinkError) this.#sinkError = { cause };
138
+ throw sinkFailed(this.#sinkError.cause);
95
139
  }
96
140
  }
141
+
142
+ #chain(work: Promise<unknown>): void {
143
+ const tail = work.then(
144
+ () => undefined,
145
+ (reason: unknown) => {
146
+ if (!this.#sinkError) this.#sinkError = { cause: reason };
147
+ throw sinkFailed(this.#sinkError.cause);
148
+ },
149
+ );
150
+ tail.catch(() => {}); // the engine sees the failure through pending(); never an unhandled rejection
151
+ this.#tail = tail;
152
+ }
97
153
  }
98
154
 
99
155
  function sinkFailed(cause: unknown): TaugraphError {
@@ -105,27 +161,149 @@ function sinkFailed(cause: unknown): TaugraphError {
105
161
  // Serialization
106
162
  // ---------------------------------------------------------------------------
107
163
 
108
- /** One JSON object per line, the same layout as an append-only log file. */
109
- export function toJSONL(trace: Trace): string {
110
- return trace
111
- .map((event) => JSON.stringify(event))
112
- .join("\n")
113
- .concat("\n");
164
+ type Field = "input" | "output";
165
+ const FIELDS: readonly Field[] = ["input", "output"];
166
+ const PATCH = { input: "inputPatch", output: "outputPatch" } as const;
167
+ const SHORT_PATCH = 4096;
168
+
169
+ /** Base values for v2 patches, updated event by event in the same way when writing and reading. */
170
+ class Bases {
171
+ #state: { readonly value: unknown } | undefined;
172
+ readonly #enters = new Map<number, unknown>();
173
+ readonly #last = new Map<string, unknown>();
174
+
175
+ get(event: TraceEvent, field: Field): { readonly value: unknown } | undefined {
176
+ if ((event.type === "enter" && field === "input") || (event.type === "run_end" && field === "output")) {
177
+ return this.#state;
178
+ }
179
+ if (event.type === "exit" && field === "output") {
180
+ return event.step !== undefined && this.#enters.has(event.step)
181
+ ? { value: this.#enters.get(event.step) }
182
+ : undefined;
183
+ }
184
+ const key = `${event.type}\u0000${event.nodeId ?? ""}\u0000${field}`;
185
+ return this.#last.has(key) ? { value: this.#last.get(key) } : undefined;
186
+ }
187
+
188
+ update(event: TraceEvent): void {
189
+ for (const field of FIELDS) {
190
+ const value = event[field];
191
+ if (value === undefined) continue;
192
+ if (event.type === "run_start" && field === "input") this.#state = { value };
193
+ else if (event.type === "exit" && field === "output") this.#state = { value };
194
+ else if (event.type === "enter" && field === "input" && event.step !== undefined)
195
+ this.#enters.set(event.step, value);
196
+ else this.#last.set(`${event.type}\u0000${event.nodeId ?? ""}\u0000${field}`, value);
197
+ }
198
+ }
199
+ }
200
+
201
+ function encodeEvent(event: TraceEvent, bases: Bases): string {
202
+ const out: Record<string, unknown> = { ...event };
203
+ if (event.type === "run_start") out.meta = { ...event.meta, version: TRACE_VERSION };
204
+ let patches = "";
205
+ for (const field of FIELDS) {
206
+ const value = event[field];
207
+ if (value === undefined) continue;
208
+ const base = bases.get(event, field);
209
+ if (!base) continue;
210
+ const patch = JSON.stringify(diffJson(base.value, value));
211
+ if (patch.length < SHORT_PATCH || patch.length <= jsonLengthAtMost(value, patch.length)) {
212
+ delete out[field];
213
+ patches += `,"${PATCH[field]}":${patch}`;
214
+ }
215
+ }
216
+ const line = JSON.stringify(out);
217
+ if (patches === "") return line;
218
+ // The patch keys go last, in the order of FIELDS, as if they had been added to `out`.
219
+ return `${line.slice(0, -1)}${line === "{}" ? patches.slice(1) : patches}}`;
114
220
  }
115
221
 
116
- export function fromJSONL(text: string): Trace {
117
- const events: unknown[] = [];
118
- text.split(/\r?\n/).forEach((line, index) => {
119
- if (line.trim() === "") return;
222
+ /**
223
+ * Encodes events one by one in format v2. `prefix` holds events already stored, so new ones can use them as bases.
224
+ * A file keeps the format of its header: after a version 1 prefix, events are written in full, without patches.
225
+ */
226
+ export function createTraceEncoder(prefix: Trace = []): { encode(event: TraceEvent): string } {
227
+ if (prefix[0]?.meta?.version === 1) return { encode: (event) => JSON.stringify(event) };
228
+ const bases = new Bases();
229
+ for (const event of prefix) bases.update(event);
230
+ return {
231
+ encode(event) {
232
+ const line = encodeEvent(event, bases);
233
+ bases.update(event);
234
+ return line;
235
+ },
236
+ };
237
+ }
238
+
239
+ /**
240
+ * One JSON object per line in format v2. `from` writes the events from that index on, using earlier ones as bases;
241
+ * for a trace read from version 1, `from` above 0 writes full lines, so the file stays version 1.
242
+ */
243
+ export function toJSONL(trace: Trace, options: { readonly from?: number } = {}): string {
244
+ const from = options.from ?? 0;
245
+ const encoder = createTraceEncoder(trace.slice(0, from));
246
+ const lines = trace.slice(from).map((event) => encoder.encode(event));
247
+ return lines.length === 0 ? "" : `${lines.join("\n")}\n`;
248
+ }
249
+
250
+ /**
251
+ * Reads format v1 and v2. `tornTail: "drop"` drops a last line that was cut short by a crash: the text does not end
252
+ * with a newline and the line is not valid JSON. Any other broken line is an `INVALID_TRACE` error.
253
+ */
254
+ export function fromJSONL(text: string, options: { readonly tornTail?: "drop" | "error" } = {}): Trace {
255
+ const lines = text.split(/\r?\n/);
256
+ let lastLine = lines.length - 1;
257
+ while (lastLine >= 0 && (lines[lastLine] as string).trim() === "") lastLine--;
258
+ const mayDrop = options.tornTail === "drop" && !text.endsWith("\n");
259
+ const raw: Record<string, unknown>[] = [];
260
+ for (const [index, line] of lines.entries()) {
261
+ if (line.trim() === "") continue;
262
+ let event: unknown;
120
263
  try {
121
- events.push(JSON.parse(line));
264
+ event = JSON.parse(line);
122
265
  } catch (cause) {
266
+ if (mayDrop && index === lastLine) break;
123
267
  throw new TaugraphError("INVALID_TRACE", `Line ${index + 1} is not valid JSON`, { cause });
124
268
  }
269
+ if (!isRecord(event)) throw new TaugraphError("INVALID_TRACE", `Event ${raw.length} is not an object`);
270
+ raw.push(event);
271
+ }
272
+ // Check the header before applying any patch: a newer version may use patches this reader does not know.
273
+ if (raw[0] !== undefined) assertHeader(raw[0]);
274
+ const bases = new Bases();
275
+ const events = raw.map((event, index) => {
276
+ const decoded = decodeEvent(event, index, bases);
277
+ bases.update(decoded);
278
+ return decoded;
125
279
  });
126
280
  return assertTrace(events);
127
281
  }
128
282
 
283
+ function decodeEvent(raw: Record<string, unknown>, index: number, bases: Bases): TraceEvent {
284
+ // `input` and `output` go before `meta`, where TraceLog puts them, also when they were written as patches.
285
+ const out: Record<string, unknown> = { ...raw };
286
+ for (const key of ["input", "output", "meta", PATCH.input, PATCH.output]) delete out[key];
287
+ for (const field of FIELDS) {
288
+ const ops = raw[PATCH[field]];
289
+ const base = bases.get(out as unknown as TraceEvent, field);
290
+ try {
291
+ if (ops !== undefined) {
292
+ if (!Array.isArray(ops)) throw new Error(`${PATCH[field]} is not an array`);
293
+ if (!base) throw new Error(`${PATCH[field]} has no base`);
294
+ out[field] = freezeJson(applyPatch(base.value, ops as PatchOp[]), base.value);
295
+ } else if (raw[field] !== undefined) {
296
+ out[field] = freezeJson(raw[field], base?.value);
297
+ }
298
+ } catch (cause) {
299
+ const reason = cause instanceof Error ? cause.message : String(cause);
300
+ throw new TaugraphError("INVALID_TRACE", `Event ${index}: ${reason}`, { cause });
301
+ }
302
+ }
303
+ if (Object.hasOwn(raw, "meta")) out.meta = raw.meta;
304
+ return out as unknown as TraceEvent;
305
+ }
306
+
129
307
  /** Checks that a value is a well-formed taugraph trace and returns it typed. */
130
308
  export function assertTrace(value: unknown): Trace {
131
309
  const fail = (message: string): never => {
@@ -134,13 +312,7 @@ export function assertTrace(value: unknown): Trace {
134
312
  if (!Array.isArray(value) || value.length === 0) fail("Trace must be a non-empty array of events");
135
313
  const events = value as Record<string, unknown>[];
136
314
  const first = events[0] as Record<string, unknown>;
137
- const meta = first.meta as Record<string, unknown> | undefined;
138
- if (first.type !== "run_start" || meta?.format !== TRACE_FORMAT) {
139
- fail(`First event must be a "${TRACE_FORMAT}" run_start event`);
140
- }
141
- if (meta?.version !== TRACE_VERSION) {
142
- fail(`Unsupported trace version ${String(meta?.version)} (expected ${TRACE_VERSION})`);
143
- }
315
+ assertHeader(first);
144
316
  events.forEach((event, index) => {
145
317
  if (typeof event !== "object" || event === null) fail(`Event ${index} is not an object`);
146
318
  if (event.seq !== index) fail(`Event ${index} has seq ${String(event.seq)}; traces must be complete and ordered`);
@@ -151,6 +323,17 @@ export function assertTrace(value: unknown): Trace {
151
323
  return value as Trace;
152
324
  }
153
325
 
326
+ /** The first event must be a run_start in a format and version this reader knows. */
327
+ function assertHeader(first: Record<string, unknown>): void {
328
+ const meta = first.meta as Record<string, unknown> | undefined;
329
+ if (first.type !== "run_start" || meta?.format !== TRACE_FORMAT) {
330
+ throw new TaugraphError("INVALID_TRACE", `First event must be a "${TRACE_FORMAT}" run_start event`);
331
+ }
332
+ if (!READABLE_VERSIONS.has(meta?.version)) {
333
+ throw new TaugraphError("INVALID_TRACE", `Unsupported trace version ${String(meta?.version)} (expected 1 or 2)`);
334
+ }
335
+ }
336
+
154
337
  // ---------------------------------------------------------------------------
155
338
  // Inspection
156
339
  // ---------------------------------------------------------------------------
@@ -178,6 +361,16 @@ export function recordedSteps(trace: Trace): Map<number, RecordedStep> {
178
361
  return steps;
179
362
  }
180
363
 
364
+ export type RunStatus = "running" | "paused" | "completed" | "failed";
365
+
366
+ /** Where a run stands, from its last event: no `run_end` yet is `"running"` (or interrupted, if nothing is writing it). */
367
+ export function runStatus(trace: Trace): RunStatus {
368
+ const last = trace[trace.length - 1];
369
+ if (last?.type !== "run_end") return "running";
370
+ const status = last.meta?.status;
371
+ return status === "paused" || status === "completed" ? status : "failed";
372
+ }
373
+
181
374
  /** Node ids in execution order. */
182
375
  export function tracePath(trace: Trace): string[] {
183
376
  const path: string[] = [];
package/src/core/types.ts CHANGED
@@ -60,10 +60,15 @@ export interface RunContext {
60
60
  /** 1-based attempt number when the node has a retry policy. */
61
61
  readonly attempt: number;
62
62
  /**
63
- * True when this step was already running when the trace ended (e.g. the process crashed)
63
+ * True when this step was already running when the trace ended (e.g. after a crash)
64
64
  * and `resume` started it again. A write node should check whether its effect already happened.
65
65
  */
66
66
  readonly recovered: boolean;
67
+ /**
68
+ * `<runId>:<step>`: the same for every attempt of this step, and when a crashed step is restarted. Pass it to an
69
+ * API that deduplicates (an `Idempotency-Key` header, say) so a retried write takes effect once.
70
+ */
71
+ readonly idempotencyKey: string;
67
72
  };
68
73
  /** Aborted when the caller cancels the run. Pass it to fetch / model clients. */
69
74
  readonly signal: AbortSignal;
@@ -81,9 +86,29 @@ export interface RunContext {
81
86
  interrupt<T = unknown>(request?: unknown): T;
82
87
  }
83
88
 
89
+ export interface RetryBackoff {
90
+ /** Wait before the first retry, in milliseconds. Default 500. */
91
+ readonly initialMs?: number;
92
+ /** Each further retry waits this many times longer. Default 2. */
93
+ readonly factor?: number;
94
+ /** Upper bound for the computed wait. Default 30_000. A longer `retryAfterMs` on the error still wins. */
95
+ readonly maxMs?: number;
96
+ /** Share of each wait taken off at random, 0 to 1. Default 0.5: a wait is 50% to 100% of the computed one. */
97
+ readonly jitter?: number;
98
+ }
99
+
84
100
  export interface RetryPolicy {
85
101
  /** Total attempts including the first one. Must be an integer >= 1. */
86
102
  readonly maxAttempts: number;
103
+ /** Wait between attempts. Default `{ initialMs: 500, factor: 2, maxMs: 30_000, jitter: 0.5 }`; `false` retries at once. */
104
+ readonly backoff?: false | RetryBackoff;
105
+ /** Whether an error is worth another attempt. Gets the error the node threw. Default: `isRetryable`. */
106
+ readonly retryOn?: (error: unknown) => boolean;
107
+ /**
108
+ * Required on `write` nodes with a retry policy: repeating the node is safe, for example because it passes
109
+ * `ctx.meta.idempotencyKey` to an API that deduplicates.
110
+ */
111
+ readonly idempotent?: boolean;
87
112
  }
88
113
 
89
114
  /** Receives the current (deeply frozen) state and returns a brand-new state. */
@@ -94,6 +119,11 @@ export interface NodeMeta {
94
119
  readonly kind?: string;
95
120
  readonly retry?: RetryPolicy;
96
121
  readonly effect?: Effect;
122
+ /**
123
+ * Fails the attempt with TIMEOUT when the node's Promise has not settled after this many milliseconds, and aborts
124
+ * `ctx.signal`. An integer from 1 to 2147483647. Synchronous code cannot be interrupted.
125
+ */
126
+ readonly timeoutMs?: number;
97
127
  }
98
128
 
99
129
  /** Any function with the `NodeFn` signature is a node. Plugins attach metadata with `defineNode`. */
@@ -132,10 +162,13 @@ export interface RunOptions {
132
162
  /** Upper bound on node executions, guards against unbounded loops. Defaults to 100. */
133
163
  readonly maxSteps?: number;
134
164
  /**
135
- * Called synchronously for every appended event, before the run continues. Use it to write
136
- * the trace to durable storage. If it throws, the run stops with SINK_FAILED.
165
+ * Called for every appended event, in order, before the run continues: use it to write the trace to durable
166
+ * storage. It may return a Promise. `run` then waits for it after each kernel event, so a `write` step's `enter` is
167
+ * stored before the node runs, and waits for the events a node appended before that step's `exit`. Calls never
168
+ * overlap. If it throws or rejects, the run stops with SINK_FAILED. `runSync` takes synchronous sinks only.
137
169
  */
138
- readonly onEvent?: (event: TraceEvent) => void;
170
+ // Two signatures, not `=> MaybePromise<void>`: only a plain `void` return accepts sinks like `(e) => events.push(e)`.
171
+ readonly onEvent?: ((event: TraceEvent) => void) | ((event: TraceEvent) => PromiseLike<void>);
139
172
  }
140
173
 
141
174
  export type ReplayMode = "recorded" | "live";