taugraph 0.0.0-stage → 0.3.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 (100) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/LICENSE +21 -0
  3. package/README.md +447 -2
  4. package/README.zh-CN.md +448 -0
  5. package/dist/agent/index.d.ts +66 -0
  6. package/dist/agent/index.d.ts.map +1 -0
  7. package/dist/agent/index.js +228 -0
  8. package/dist/agent/index.js.map +1 -0
  9. package/dist/agent/state.d.ts +30 -0
  10. package/dist/agent/state.d.ts.map +1 -0
  11. package/dist/agent/state.js +135 -0
  12. package/dist/agent/state.js.map +1 -0
  13. package/dist/agent/util.d.ts +9 -0
  14. package/dist/agent/util.d.ts.map +1 -0
  15. package/dist/agent/util.js +28 -0
  16. package/dist/agent/util.js.map +1 -0
  17. package/dist/core/engine.d.ts +51 -0
  18. package/dist/core/engine.d.ts.map +1 -0
  19. package/dist/core/engine.js +412 -0
  20. package/dist/core/engine.js.map +1 -0
  21. package/dist/core/errors.d.ts +48 -0
  22. package/dist/core/errors.d.ts.map +1 -0
  23. package/dist/core/errors.js +30 -0
  24. package/dist/core/errors.js.map +1 -0
  25. package/dist/core/graph.d.ts +11 -0
  26. package/dist/core/graph.d.ts.map +1 -0
  27. package/dist/core/graph.js +134 -0
  28. package/dist/core/graph.js.map +1 -0
  29. package/dist/core/node.d.ts +7 -0
  30. package/dist/core/node.d.ts.map +1 -0
  31. package/dist/core/node.js +22 -0
  32. package/dist/core/node.js.map +1 -0
  33. package/dist/core/standard-schema.d.ts +39 -0
  34. package/dist/core/standard-schema.d.ts.map +1 -0
  35. package/dist/core/standard-schema.js +2 -0
  36. package/dist/core/standard-schema.js.map +1 -0
  37. package/dist/core/trace.d.ts +90 -0
  38. package/dist/core/trace.d.ts.map +1 -0
  39. package/dist/core/trace.js +290 -0
  40. package/dist/core/trace.js.map +1 -0
  41. package/dist/core/types.d.ts +175 -0
  42. package/dist/core/types.d.ts.map +1 -0
  43. package/dist/core/types.js +2 -0
  44. package/dist/core/types.js.map +1 -0
  45. package/dist/core/util.d.ts +19 -0
  46. package/dist/core/util.d.ts.map +1 -0
  47. package/dist/core/util.js +85 -0
  48. package/dist/core/util.js.map +1 -0
  49. package/dist/index.d.ts +9 -0
  50. package/dist/index.d.ts.map +1 -0
  51. package/dist/index.js +7 -0
  52. package/dist/index.js.map +1 -0
  53. package/dist/nodes/code.d.ts +12 -0
  54. package/dist/nodes/code.d.ts.map +1 -0
  55. package/dist/nodes/code.js +9 -0
  56. package/dist/nodes/code.js.map +1 -0
  57. package/dist/nodes/content.d.ts +18 -0
  58. package/dist/nodes/content.d.ts.map +1 -0
  59. package/dist/nodes/content.js +88 -0
  60. package/dist/nodes/content.js.map +1 -0
  61. package/dist/nodes/human.d.ts +17 -0
  62. package/dist/nodes/human.d.ts.map +1 -0
  63. package/dist/nodes/human.js +18 -0
  64. package/dist/nodes/human.js.map +1 -0
  65. package/dist/nodes/index.d.ts +5 -0
  66. package/dist/nodes/index.d.ts.map +1 -0
  67. package/dist/nodes/index.js +7 -0
  68. package/dist/nodes/index.js.map +1 -0
  69. package/dist/nodes/llm.d.ts +157 -0
  70. package/dist/nodes/llm.d.ts.map +1 -0
  71. package/dist/nodes/llm.js +54 -0
  72. package/dist/nodes/llm.js.map +1 -0
  73. package/dist/nodes/util.d.ts +5 -0
  74. package/dist/nodes/util.d.ts.map +1 -0
  75. package/dist/nodes/util.js +11 -0
  76. package/dist/nodes/util.js.map +1 -0
  77. package/dist/openai/index.d.ts +39 -0
  78. package/dist/openai/index.d.ts.map +1 -0
  79. package/dist/openai/index.js +178 -0
  80. package/dist/openai/index.js.map +1 -0
  81. package/package.json +86 -4
  82. package/src/agent/index.ts +315 -0
  83. package/src/agent/state.ts +147 -0
  84. package/src/agent/util.ts +35 -0
  85. package/src/core/engine.ts +552 -0
  86. package/src/core/errors.ts +70 -0
  87. package/src/core/graph.ts +166 -0
  88. package/src/core/node.ts +24 -0
  89. package/src/core/standard-schema.ts +47 -0
  90. package/src/core/trace.ts +346 -0
  91. package/src/core/types.ts +206 -0
  92. package/src/core/util.ts +81 -0
  93. package/src/index.ts +46 -0
  94. package/src/nodes/code.ts +18 -0
  95. package/src/nodes/content.ts +100 -0
  96. package/src/nodes/human.ts +33 -0
  97. package/src/nodes/index.ts +25 -0
  98. package/src/nodes/llm.ts +219 -0
  99. package/src/nodes/util.ts +13 -0
  100. package/src/openai/index.ts +246 -0
@@ -0,0 +1,166 @@
1
+ import {
2
+ type CompiledGraph,
3
+ driveAsync,
4
+ driveSync,
5
+ execute,
6
+ type Outgoing,
7
+ type ResumePlan,
8
+ toJson,
9
+ } from "./engine.js";
10
+ import { TaugraphError } from "./errors.js";
11
+ import type { StandardSchemaV1 } from "./standard-schema.js";
12
+ import { assertTrace, recordedAnswers, recordedSteps, resumePoint } from "./trace.js";
13
+ import type { Graph, GraphDefinition, Node, ReplayOptions, ResumeOptions, RunOptions, Trace } from "./types.js";
14
+
15
+ /**
16
+ * Declares a graph and checks it statically. Throws `INVALID_GRAPH` on any inconsistency,
17
+ * so a graph that builds can only fail at run time because of its nodes or routers.
18
+ *
19
+ * The schema comes first so TypeScript infers the state type from it before checking
20
+ * the nodes; plugin factories such as `CodeNode(...)` then get a typed `state` parameter.
21
+ */
22
+ export function createGraph<S, I, K extends string>(
23
+ schema: StandardSchemaV1<I, S>,
24
+ definition: GraphDefinition<S, K>,
25
+ ): Graph<S, I, K> {
26
+ const graph = compile(schema as StandardSchemaV1<unknown, S>, definition as unknown as GraphDefinition<S, string>);
27
+ const nodeIds = Object.freeze(Object.keys(definition.nodes) as K[]);
28
+
29
+ /** Every check that can reject a resume runs here, before anything is appended to the trace. */
30
+ const planResume = (trace: Trace, value: unknown, options: ResumeOptions): ResumePlan => {
31
+ const events = assertTrace(trace);
32
+ const point = resumePoint(events);
33
+ const isReplay = (events[0] as Trace[number]).meta?.replayOf !== undefined;
34
+ const blockWrites = isReplay && options.allowWrites !== true;
35
+ if (value !== undefined && point.kind !== "paused") {
36
+ throw new TaugraphError(
37
+ "NOT_RESUMABLE",
38
+ "The run is not waiting for a value. To continue an interrupted trace, call resume(trace) without a value.",
39
+ );
40
+ }
41
+ if (point.kind === "start") return { trace: events, point, value: undefined, blockWrites };
42
+ const node = graph.nodes[point.nodeId];
43
+ if (!Object.hasOwn(graph.nodes, point.nodeId) || !node) {
44
+ throw new TaugraphError(
45
+ "NOT_RESUMABLE",
46
+ `The trace continues at node "${point.nodeId}", which this graph does not have`,
47
+ );
48
+ }
49
+ if (point.kind === "running" && node.effect === "write" && !options.allowWrites) {
50
+ throw new TaugraphError(
51
+ "UNKNOWN_OUTCOME",
52
+ `Write node "${point.nodeId}" (step ${point.step}) was running when the trace ended, so its effect may or may not have happened. Check the external system, then resume with { allowWrites: true }; the node will see ctx.meta.recovered === true.`,
53
+ { nodeId: point.nodeId, step: point.step },
54
+ );
55
+ }
56
+ const json = value === undefined ? undefined : toJson(value, "Resume value is not plain JSON");
57
+ return { trace: events, point, value: json, blockWrites };
58
+ };
59
+
60
+ return Object.freeze({
61
+ start: definition.start,
62
+ nodeIds,
63
+ endNodes: Object.freeze([...definition.endNodes]),
64
+
65
+ run(input: I, options: RunOptions = {}) {
66
+ return driveAsync(execute({ graph, input, options }), options.signal) as never;
67
+ },
68
+
69
+ runSync(input: I, options: RunOptions = {}) {
70
+ return driveSync(execute({ graph, input, options })) as never;
71
+ },
72
+
73
+ async resume(trace: Trace, value?: unknown, options: ResumeOptions = {}) {
74
+ const resume = planResume(trace, value, options);
75
+ return driveAsync(execute({ graph, options, resume }), options.signal) as never;
76
+ },
77
+
78
+ resumeSync(trace: Trace, value?: unknown, options: ResumeOptions = {}) {
79
+ const resume = planResume(trace, value, options);
80
+ return driveSync(execute({ graph, options, resume })) as never;
81
+ },
82
+
83
+ async replay(trace: Trace, options: ReplayOptions<S, K> = {}) {
84
+ const events = assertTrace(trace);
85
+ const first = events[0] as Trace[number];
86
+ const overrides: Record<string, Node<S> | undefined> = { ...options.overrides };
87
+ for (const [id, node] of Object.entries(overrides)) {
88
+ if (!Object.hasOwn(definition.nodes, id)) {
89
+ throw new TaugraphError("INVALID_GRAPH", `Cannot override unknown node "${id}"`);
90
+ }
91
+ if (node !== undefined && typeof node !== "function") {
92
+ throw new TaugraphError("INVALID_GRAPH", `Override for node "${id}" is not a function`);
93
+ }
94
+ }
95
+ const mode = options.mode ?? "recorded";
96
+ const replay = {
97
+ sourceRunId: first.runId,
98
+ mode,
99
+ overrides,
100
+ recorded: mode === "recorded" ? recordedSteps(events) : new Map(),
101
+ answers: recordedAnswers(events),
102
+ allowWrites: options.allowWrites === true,
103
+ };
104
+ return driveAsync(execute({ graph, input: first.input, options, replay }), options.signal) as never;
105
+ },
106
+ });
107
+ }
108
+
109
+ function compile<S>(schema: StandardSchemaV1<unknown, S>, def: GraphDefinition<S, string>): CompiledGraph<S> {
110
+ const fail = (message: string): never => {
111
+ throw new TaugraphError("INVALID_GRAPH", message);
112
+ };
113
+
114
+ if (typeof schema?.["~standard"]?.validate !== "function") {
115
+ fail("`schema` must implement Standard Schema v1 (Zod >= 3.24, Valibot >= 1, ArkType >= 2, ...)");
116
+ }
117
+
118
+ const nodes = def.nodes ?? {};
119
+ const ids = Object.keys(nodes);
120
+ if (ids.length === 0) fail("Graph has no nodes");
121
+ for (const id of ids) {
122
+ if (typeof nodes[id] !== "function") fail(`Node "${id}" is not a function`);
123
+ }
124
+ const exists = (id: unknown): id is string => typeof id === "string" && Object.hasOwn(nodes, id);
125
+ const requireNode = (id: unknown, role: string): string => {
126
+ if (!exists(id)) fail(`${role} "${String(id)}" is not a defined node`);
127
+ return id as string;
128
+ };
129
+
130
+ const start = requireNode(def.start, "Start node");
131
+
132
+ const outgoing = new Map<string, Outgoing<S>>();
133
+ const addOutgoing = (from: unknown, out: Outgoing<S>) => {
134
+ const id = requireNode(from, "Edge source");
135
+ if (outgoing.has(id)) {
136
+ fail(
137
+ `Node "${id}" has more than one outgoing edge. Parallel fan-out is not supported; use one conditional edge to pick the next node.`,
138
+ );
139
+ }
140
+ outgoing.set(id, out);
141
+ };
142
+
143
+ for (const edge of def.edges ?? []) {
144
+ addOutgoing(edge.from, { kind: "edge", to: requireNode(edge.to, `Target of edge from "${edge.from}"`) });
145
+ }
146
+ for (const edge of def.conditionalEdges ?? []) {
147
+ if (typeof edge.route !== "function") fail(`Conditional edge from "${edge.from}" has no route function`);
148
+ const targets = edge.targets?.map((t) => requireNode(t, `Declared target of "${edge.from}"`));
149
+ addOutgoing(edge.from, {
150
+ kind: "route",
151
+ route: edge.route,
152
+ ...(targets && { targets: new Set(targets) }),
153
+ });
154
+ }
155
+
156
+ if (!def.endNodes || def.endNodes.length === 0) fail("Graph needs at least one end node");
157
+ const endNodes = new Set(def.endNodes.map((id) => requireNode(id, "End node")));
158
+ for (const id of endNodes) {
159
+ if (outgoing.has(id)) fail(`End node "${id}" must not have outgoing edges`);
160
+ }
161
+ for (const id of ids) {
162
+ if (!endNodes.has(id) && !outgoing.has(id)) fail(`Node "${id}" has no outgoing edge and is not an end node`);
163
+ }
164
+
165
+ return Object.freeze({ schema, start, nodes, outgoing, endNodes });
166
+ }
@@ -0,0 +1,24 @@
1
+ import type { Node, NodeFn, NodeMeta } from "./types.js";
2
+
3
+ /**
4
+ * Wraps a node function with metadata (kind, retry policy, effect). This is the only hook
5
+ * plugin node packages need: `CodeNode`, `LLMNode` and friends are built on it.
6
+ */
7
+ export function defineNode<S>(fn: NodeFn<S>, meta: NodeMeta = {}): Node<S> {
8
+ if (typeof fn !== "function") throw new TypeError("defineNode: expected a function");
9
+ const retry = meta.retry;
10
+ if (retry !== undefined && !(Number.isInteger(retry.maxAttempts) && retry.maxAttempts >= 1)) {
11
+ throw new TypeError(`defineNode: retry.maxAttempts must be an integer >= 1, got ${String(retry.maxAttempts)}`);
12
+ }
13
+ if (meta.effect !== undefined && meta.effect !== "read" && meta.effect !== "write") {
14
+ throw new TypeError(`defineNode: effect must be "read" or "write", got ${String(meta.effect)}`);
15
+ }
16
+ const node: NodeFn<S> = (state, ctx) => fn(state, ctx);
17
+ return Object.freeze(
18
+ Object.assign(node, {
19
+ ...(meta.kind !== undefined && { kind: meta.kind }),
20
+ ...(meta.effect !== undefined && { effect: meta.effect }),
21
+ ...(retry !== undefined && { retry: Object.freeze({ maxAttempts: retry.maxAttempts }) }),
22
+ }),
23
+ );
24
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Standard Schema v1 interface (https://standardschema.dev), vendored as types only.
3
+ *
4
+ * The spec explicitly allows copying this interface so that libraries can accept
5
+ * Zod (>=3.24), Valibot (>=1.0), ArkType (>=2.0) and others without a runtime dependency.
6
+ */
7
+ export interface StandardSchemaV1<Input = unknown, Output = Input> {
8
+ readonly "~standard": StandardSchemaV1.Props<Input, Output>;
9
+ }
10
+
11
+ export declare namespace StandardSchemaV1 {
12
+ export interface Props<Input = unknown, Output = Input> {
13
+ readonly version: 1;
14
+ readonly vendor: string;
15
+ readonly validate: (value: unknown) => Result<Output> | Promise<Result<Output>>;
16
+ readonly types?: Types<Input, Output> | undefined;
17
+ }
18
+
19
+ export type Result<Output> = SuccessResult<Output> | FailureResult;
20
+
21
+ export interface SuccessResult<Output> {
22
+ readonly value: Output;
23
+ readonly issues?: undefined;
24
+ }
25
+
26
+ export interface FailureResult {
27
+ readonly issues: ReadonlyArray<Issue>;
28
+ }
29
+
30
+ export interface Issue {
31
+ readonly message: string;
32
+ readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;
33
+ }
34
+
35
+ export interface PathSegment {
36
+ readonly key: PropertyKey;
37
+ }
38
+
39
+ export interface Types<Input = unknown, Output = Input> {
40
+ readonly input: Input;
41
+ readonly output: Output;
42
+ }
43
+
44
+ export type InferInput<Schema extends StandardSchemaV1> = NonNullable<Schema["~standard"]["types"]>["input"];
45
+
46
+ export type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema["~standard"]["types"]>["output"];
47
+ }
@@ -0,0 +1,346 @@
1
+ import { TaugraphError } from "./errors.js";
2
+ import type { KernelEventType, Trace, TraceEvent, TraceEventType } from "./types.js";
3
+ import { freezeJson, jsonEqual } from "./util.js";
4
+
5
+ export const TRACE_FORMAT = "taugraph.trace";
6
+ export const TRACE_VERSION = 1;
7
+
8
+ export const KERNEL_EVENT_TYPES: ReadonlySet<string> = new Set<KernelEventType>([
9
+ "run_start",
10
+ "enter",
11
+ "exit",
12
+ "error",
13
+ "pause",
14
+ "resume",
15
+ "run_end",
16
+ ]);
17
+
18
+ export interface EventDraft {
19
+ readonly type: TraceEventType;
20
+ readonly nodeId?: string | undefined;
21
+ readonly step?: number | undefined;
22
+ readonly input?: unknown;
23
+ readonly output?: unknown;
24
+ readonly meta?: Readonly<Record<string, unknown>> | undefined;
25
+ }
26
+
27
+ /**
28
+ * Append-only event log for one run. Payloads must already be frozen JSON
29
+ * (see `freezeJson`); the log only assigns seq / runId / timestamp and freezes the envelope.
30
+ *
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.
33
+ */
34
+ export class TraceLog {
35
+ readonly #events: TraceEvent[];
36
+ readonly #runId: string;
37
+ readonly #onEvent: ((event: TraceEvent) => void) | undefined;
38
+ #sinkError: { readonly cause: unknown } | undefined;
39
+
40
+ /** `prefix` continues an existing trace (resume); it is not sent to `onEvent` again. */
41
+ constructor(runId: string, onEvent?: (event: TraceEvent) => void, prefix: Trace = []) {
42
+ this.#runId = runId;
43
+ this.#onEvent = onEvent;
44
+ this.#events = prefix.map((event) => freezeJson(event));
45
+ }
46
+
47
+ append(draft: EventDraft): TraceEvent {
48
+ const event = this.#push(draft);
49
+ if (this.#sinkError) throw sinkFailed(this.#sinkError.cause);
50
+ this.#emit(event);
51
+ return event;
52
+ }
53
+
54
+ /** For the closing `run_end` of a failing run: never throws, skips a sink that already failed. */
55
+ appendFinal(draft: EventDraft): TraceEvent {
56
+ const event = this.#push(draft);
57
+ if (!this.#sinkError) {
58
+ try {
59
+ this.#emit(event);
60
+ } catch {
61
+ // Already failing; the original error is the one to report.
62
+ }
63
+ }
64
+ return event;
65
+ }
66
+
67
+ snapshot(): Trace {
68
+ return Object.freeze(this.#events.slice());
69
+ }
70
+
71
+ #push(draft: EventDraft): TraceEvent {
72
+ const event: Record<string, unknown> = {
73
+ seq: this.#events.length,
74
+ runId: this.#runId,
75
+ type: draft.type,
76
+ timestamp: Date.now(),
77
+ };
78
+ if (draft.nodeId !== undefined) event.nodeId = draft.nodeId;
79
+ if (draft.step !== undefined) event.step = draft.step;
80
+ if (draft.input !== undefined) event.input = draft.input;
81
+ if (draft.output !== undefined) event.output = draft.output;
82
+ if (draft.meta !== undefined) event.meta = Object.isFrozen(draft.meta) ? draft.meta : freezeJson(draft.meta);
83
+ const frozen = Object.freeze(event) as unknown as TraceEvent;
84
+ this.#events.push(frozen);
85
+ return frozen;
86
+ }
87
+
88
+ #emit(event: TraceEvent): void {
89
+ if (!this.#onEvent) return;
90
+ try {
91
+ this.#onEvent(event);
92
+ } catch (cause) {
93
+ this.#sinkError = { cause };
94
+ throw sinkFailed(cause);
95
+ }
96
+ }
97
+ }
98
+
99
+ function sinkFailed(cause: unknown): TaugraphError {
100
+ const reason = cause instanceof Error ? cause.message : String(cause);
101
+ return new TaugraphError("SINK_FAILED", `onEvent threw: ${reason}`, { cause });
102
+ }
103
+
104
+ // ---------------------------------------------------------------------------
105
+ // Serialization
106
+ // ---------------------------------------------------------------------------
107
+
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");
114
+ }
115
+
116
+ export function fromJSONL(text: string): Trace {
117
+ const events: unknown[] = [];
118
+ text.split(/\r?\n/).forEach((line, index) => {
119
+ if (line.trim() === "") return;
120
+ try {
121
+ events.push(JSON.parse(line));
122
+ } catch (cause) {
123
+ throw new TaugraphError("INVALID_TRACE", `Line ${index + 1} is not valid JSON`, { cause });
124
+ }
125
+ });
126
+ return assertTrace(events);
127
+ }
128
+
129
+ /** Checks that a value is a well-formed taugraph trace and returns it typed. */
130
+ export function assertTrace(value: unknown): Trace {
131
+ const fail = (message: string): never => {
132
+ throw new TaugraphError("INVALID_TRACE", message);
133
+ };
134
+ if (!Array.isArray(value) || value.length === 0) fail("Trace must be a non-empty array of events");
135
+ const events = value as Record<string, unknown>[];
136
+ 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
+ }
144
+ events.forEach((event, index) => {
145
+ if (typeof event !== "object" || event === null) fail(`Event ${index} is not an object`);
146
+ if (event.seq !== index) fail(`Event ${index} has seq ${String(event.seq)}; traces must be complete and ordered`);
147
+ if (event.runId !== first.runId) fail(`Event ${index} belongs to a different run`);
148
+ if (typeof event.type !== "string") fail(`Event ${index} has no type`);
149
+ if (typeof event.timestamp !== "number") fail(`Event ${index} has no timestamp`);
150
+ });
151
+ return value as Trace;
152
+ }
153
+
154
+ // ---------------------------------------------------------------------------
155
+ // Inspection
156
+ // ---------------------------------------------------------------------------
157
+
158
+ export interface RecordedStep {
159
+ readonly nodeId: string;
160
+ readonly input: unknown;
161
+ readonly output: unknown;
162
+ readonly seq: number;
163
+ }
164
+
165
+ /** Successful node executions keyed by step, pairing each `exit` with its `enter`. */
166
+ export function recordedSteps(trace: Trace): Map<number, RecordedStep> {
167
+ const enters = new Map<number, TraceEvent>();
168
+ const steps = new Map<number, RecordedStep>();
169
+ for (const event of trace) {
170
+ if (event.step === undefined || event.nodeId === undefined) continue;
171
+ if (event.type === "enter") enters.set(event.step, event);
172
+ if (event.type === "exit") {
173
+ const enter = enters.get(event.step);
174
+ if (enter)
175
+ steps.set(event.step, { nodeId: event.nodeId, input: enter.input, output: event.output, seq: event.seq });
176
+ }
177
+ }
178
+ return steps;
179
+ }
180
+
181
+ /** Node ids in execution order. */
182
+ export function tracePath(trace: Trace): string[] {
183
+ const path: string[] = [];
184
+ for (const event of trace) {
185
+ if (event.type === "enter" && event.step === path.length && event.nodeId !== undefined) path.push(event.nodeId);
186
+ }
187
+ return path;
188
+ }
189
+
190
+ // ---------------------------------------------------------------------------
191
+ // Pause / resume (internal; used by the engine)
192
+ // ---------------------------------------------------------------------------
193
+
194
+ /**
195
+ * Where a trace can continue from.
196
+ * - `start`: nothing ran yet.
197
+ * - `after`: `step` finished; route on from its output.
198
+ * - `paused`: `step` is waiting for a value.
199
+ * - `resumed`: a value was delivered to `step` but the node had not started again.
200
+ * - `running`: `step` was executing when the trace ended; its outcome is unknown.
201
+ */
202
+ export type ResumePoint =
203
+ | { readonly kind: "start" }
204
+ | {
205
+ readonly kind: "after" | "paused" | "resumed" | "running";
206
+ readonly step: number;
207
+ readonly nodeId: string;
208
+ /** Output of the step for `after`, otherwise the state the step received. */
209
+ readonly state: unknown;
210
+ };
211
+
212
+ export function resumePoint(trace: Trace): ResumePoint {
213
+ const last = trace[trace.length - 1] as TraceEvent;
214
+ const status = last.type === "run_end" ? last.meta?.status : undefined;
215
+ if (last.type === "run_end" && status !== "paused") {
216
+ throw new TaugraphError(
217
+ "NOT_RESUMABLE",
218
+ `Run is ${String(status)}; only paused or interrupted runs can be resumed. Use graph.replay to run it again.`,
219
+ );
220
+ }
221
+
222
+ // The step to continue is the one of the last step event that is not a delivered value.
223
+ let target: number | undefined;
224
+ for (let i = trace.length - 1; i >= 0 && target === undefined; i--) {
225
+ const event = trace[i] as TraceEvent;
226
+ if (event.step !== undefined && event.type !== "resume") target = event.step;
227
+ }
228
+ if (target === undefined) return { kind: "start" };
229
+
230
+ let enter: TraceEvent | undefined;
231
+ let output: unknown;
232
+ let phase: "after" | "paused" | "resumed" | "running" = "running";
233
+ for (const event of trace) {
234
+ if (event.step !== target) continue;
235
+ if (event.type === "enter") {
236
+ enter ??= event;
237
+ phase = "running";
238
+ } else if (event.type === "exit") {
239
+ phase = "after";
240
+ output = event.output;
241
+ } else if (event.type === "pause") {
242
+ phase = "paused";
243
+ } else if (event.type === "resume") {
244
+ phase = "resumed";
245
+ } else if (event.type === "error") {
246
+ phase = "running";
247
+ }
248
+ }
249
+ if (!enter || enter.nodeId === undefined) {
250
+ throw new TaugraphError("INVALID_TRACE", `Step ${target} has events but no enter event`);
251
+ }
252
+ if (status === "paused" && phase !== "paused") {
253
+ throw new TaugraphError("INVALID_TRACE", `run_end says the run is paused, but step ${target} is not`);
254
+ }
255
+ return { kind: phase, step: target, nodeId: enter.nodeId, state: phase === "after" ? output : enter.input };
256
+ }
257
+
258
+ /** Values delivered to `ctx.interrupt` at `step`, in order. */
259
+ export function deliveredValues(trace: Trace, step: number): unknown[] {
260
+ return trace
261
+ .filter((event) => event.type === "resume" && event.step === step && event.meta?.reason !== "recovered")
262
+ .map((event) => event.input);
263
+ }
264
+
265
+ export interface RecordedAnswers {
266
+ readonly nodeId: string;
267
+ /** State the step received. Answers are only reused when a replay sees the same state. */
268
+ readonly input: unknown;
269
+ readonly values: readonly unknown[];
270
+ }
271
+
272
+ /** Values delivered by `resume`, keyed by step, for replays to feed back to `ctx.interrupt`. */
273
+ export function recordedAnswers(trace: Trace): Map<number, RecordedAnswers> {
274
+ const enters = new Map<number, TraceEvent>();
275
+ const values = new Map<number, unknown[]>();
276
+ for (const event of trace) {
277
+ if (event.step === undefined) continue;
278
+ if (event.type === "enter" && !enters.has(event.step)) enters.set(event.step, event);
279
+ if (event.type === "resume" && event.meta?.reason !== "recovered") {
280
+ const value = event.input === undefined ? undefined : freezeJson(event.input);
281
+ values.set(event.step, [...(values.get(event.step) ?? []), value]);
282
+ }
283
+ }
284
+ const answers = new Map<number, RecordedAnswers>();
285
+ for (const [step, list] of values) {
286
+ const enter = enters.get(step);
287
+ if (enter?.nodeId !== undefined) answers.set(step, { nodeId: enter.nodeId, input: enter.input, values: list });
288
+ }
289
+ return answers;
290
+ }
291
+
292
+ export interface TraceDiff {
293
+ /** Same path, same per-step outputs, same final state. */
294
+ readonly equal: boolean;
295
+ readonly path: { readonly a: readonly string[]; readonly b: readonly string[] };
296
+ /** First step whose node or output differs. */
297
+ readonly firstDivergence?: { readonly step: number; readonly a?: string; readonly b?: string };
298
+ /** Top-level keys of the final state that differ. `(root)` if the states are not both objects. */
299
+ readonly changedKeys: readonly string[];
300
+ }
301
+
302
+ /** Compares two runs, e.g. an original trace and its replay with a swapped model. */
303
+ export function diffTraces(a: Trace, b: Trace): TraceDiff {
304
+ const pathA = tracePath(a);
305
+ const pathB = tracePath(b);
306
+ const stepsA = recordedSteps(a);
307
+ const stepsB = recordedSteps(b);
308
+
309
+ let firstDivergence: TraceDiff["firstDivergence"];
310
+ for (let step = 0; step < Math.max(pathA.length, pathB.length); step++) {
311
+ const sameNode = pathA[step] === pathB[step];
312
+ if (!sameNode || !jsonEqual(stepsA.get(step)?.output, stepsB.get(step)?.output)) {
313
+ firstDivergence = { step, ...(pathA[step] && { a: pathA[step] }), ...(pathB[step] && { b: pathB[step] }) };
314
+ break;
315
+ }
316
+ }
317
+
318
+ const finalA = finalState(a);
319
+ const finalB = finalState(b);
320
+ const changedKeys: string[] = [];
321
+ if (isRecord(finalA) && isRecord(finalB)) {
322
+ for (const key of new Set([...Object.keys(finalA), ...Object.keys(finalB)])) {
323
+ if (!jsonEqual(finalA[key], finalB[key])) changedKeys.push(key);
324
+ }
325
+ } else if (!jsonEqual(finalA, finalB)) {
326
+ changedKeys.push("(root)");
327
+ }
328
+
329
+ return {
330
+ equal: firstDivergence === undefined && changedKeys.length === 0,
331
+ path: { a: pathA, b: pathB },
332
+ ...(firstDivergence && { firstDivergence }),
333
+ changedKeys,
334
+ };
335
+ }
336
+
337
+ function finalState(trace: Trace): unknown {
338
+ for (let i = trace.length - 1; i >= 0; i--) {
339
+ if (trace[i]?.type === "run_end") return trace[i]?.output;
340
+ }
341
+ return undefined;
342
+ }
343
+
344
+ function isRecord(value: unknown): value is Record<string, unknown> {
345
+ return typeof value === "object" && value !== null && !Array.isArray(value);
346
+ }