taugraph 0.0.0-stage → 0.2.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 (74) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +233 -2
  3. package/README.zh-CN.md +234 -0
  4. package/dist/core/engine.d.ts +51 -0
  5. package/dist/core/engine.d.ts.map +1 -0
  6. package/dist/core/engine.js +412 -0
  7. package/dist/core/engine.js.map +1 -0
  8. package/dist/core/errors.d.ts +48 -0
  9. package/dist/core/errors.d.ts.map +1 -0
  10. package/dist/core/errors.js +30 -0
  11. package/dist/core/errors.js.map +1 -0
  12. package/dist/core/graph.d.ts +11 -0
  13. package/dist/core/graph.d.ts.map +1 -0
  14. package/dist/core/graph.js +134 -0
  15. package/dist/core/graph.js.map +1 -0
  16. package/dist/core/node.d.ts +7 -0
  17. package/dist/core/node.d.ts.map +1 -0
  18. package/dist/core/node.js +22 -0
  19. package/dist/core/node.js.map +1 -0
  20. package/dist/core/standard-schema.d.ts +39 -0
  21. package/dist/core/standard-schema.d.ts.map +1 -0
  22. package/dist/core/standard-schema.js +2 -0
  23. package/dist/core/standard-schema.js.map +1 -0
  24. package/dist/core/trace.d.ts +90 -0
  25. package/dist/core/trace.d.ts.map +1 -0
  26. package/dist/core/trace.js +290 -0
  27. package/dist/core/trace.js.map +1 -0
  28. package/dist/core/types.d.ts +175 -0
  29. package/dist/core/types.d.ts.map +1 -0
  30. package/dist/core/types.js +2 -0
  31. package/dist/core/types.js.map +1 -0
  32. package/dist/core/util.d.ts +19 -0
  33. package/dist/core/util.d.ts.map +1 -0
  34. package/dist/core/util.js +85 -0
  35. package/dist/core/util.js.map +1 -0
  36. package/dist/index.d.ts +9 -0
  37. package/dist/index.d.ts.map +1 -0
  38. package/dist/index.js +7 -0
  39. package/dist/index.js.map +1 -0
  40. package/dist/nodes/code.d.ts +12 -0
  41. package/dist/nodes/code.d.ts.map +1 -0
  42. package/dist/nodes/code.js +9 -0
  43. package/dist/nodes/code.js.map +1 -0
  44. package/dist/nodes/human.d.ts +17 -0
  45. package/dist/nodes/human.d.ts.map +1 -0
  46. package/dist/nodes/human.js +18 -0
  47. package/dist/nodes/human.js.map +1 -0
  48. package/dist/nodes/index.d.ts +4 -0
  49. package/dist/nodes/index.d.ts.map +1 -0
  50. package/dist/nodes/index.js +6 -0
  51. package/dist/nodes/index.js.map +1 -0
  52. package/dist/nodes/llm.d.ts +63 -0
  53. package/dist/nodes/llm.d.ts.map +1 -0
  54. package/dist/nodes/llm.js +54 -0
  55. package/dist/nodes/llm.js.map +1 -0
  56. package/dist/nodes/util.d.ts +5 -0
  57. package/dist/nodes/util.d.ts.map +1 -0
  58. package/dist/nodes/util.js +11 -0
  59. package/dist/nodes/util.js.map +1 -0
  60. package/package.json +74 -4
  61. package/src/core/engine.ts +552 -0
  62. package/src/core/errors.ts +70 -0
  63. package/src/core/graph.ts +166 -0
  64. package/src/core/node.ts +24 -0
  65. package/src/core/standard-schema.ts +47 -0
  66. package/src/core/trace.ts +346 -0
  67. package/src/core/types.ts +206 -0
  68. package/src/core/util.ts +81 -0
  69. package/src/index.ts +46 -0
  70. package/src/nodes/code.ts +18 -0
  71. package/src/nodes/human.ts +33 -0
  72. package/src/nodes/index.ts +15 -0
  73. package/src/nodes/llm.ts +123 -0
  74. package/src/nodes/util.ts +13 -0
@@ -0,0 +1,206 @@
1
+ export type MaybePromise<T> = T | PromiseLike<T>;
2
+
3
+ // ---------------------------------------------------------------------------
4
+ // Trace
5
+ // ---------------------------------------------------------------------------
6
+
7
+ /** Event types written by the kernel. Nodes cannot append these. */
8
+ export type KernelEventType = "run_start" | "enter" | "exit" | "error" | "pause" | "resume" | "run_end";
9
+
10
+ /** Event types reserved by convention for plugin nodes. */
11
+ export type PluginEventType = "llm_call" | "tool_call";
12
+
13
+ export type TraceEventType = KernelEventType | PluginEventType | (string & {});
14
+
15
+ /** One immutable, JSON-serializable record in the append-only transcript. */
16
+ export interface TraceEvent {
17
+ /** Position in the run, starting at 0. Strictly increasing. */
18
+ readonly seq: number;
19
+ readonly runId: string;
20
+ readonly type: TraceEventType;
21
+ /** Milliseconds since epoch. */
22
+ readonly timestamp: number;
23
+ readonly nodeId?: string;
24
+ /** Index of the node execution this event belongs to, starting at 0. */
25
+ readonly step?: number;
26
+ readonly input?: unknown;
27
+ readonly output?: unknown;
28
+ readonly meta?: Readonly<Record<string, unknown>>;
29
+ }
30
+
31
+ /** A full run transcript. Serialize it with `toJSONL`, replay it with `graph.replay`. */
32
+ export type Trace = readonly TraceEvent[];
33
+
34
+ /** What a node may append through `ctx.trace.append`. The kernel fills in the rest. */
35
+ export interface PluginEvent {
36
+ readonly type: TraceEventType;
37
+ readonly input?: unknown;
38
+ readonly output?: unknown;
39
+ readonly meta?: Record<string, unknown>;
40
+ }
41
+
42
+ // ---------------------------------------------------------------------------
43
+ // Node
44
+ // ---------------------------------------------------------------------------
45
+
46
+ /**
47
+ * What running a node does to the outside world.
48
+ * - `read`: safe to run again (queries, LLM calls, pure code).
49
+ * - `write`: changes something outside the run (placing an order, sending a message).
50
+ * Replay never re-executes a write node unless you pass `allowWrites: true`.
51
+ * Undeclared nodes are treated like `read`.
52
+ */
53
+ export type Effect = "read" | "write";
54
+
55
+ export interface RunContext {
56
+ readonly meta: {
57
+ readonly runId: string;
58
+ readonly nodeId: string;
59
+ readonly step: number;
60
+ /** 1-based attempt number when the node has a retry policy. */
61
+ readonly attempt: number;
62
+ /**
63
+ * True when this step was already running when the trace ended (e.g. the process crashed)
64
+ * and `resume` started it again. A write node should check whether its effect already happened.
65
+ */
66
+ readonly recovered: boolean;
67
+ };
68
+ /** Aborted when the caller cancels the run. Pass it to fetch / model clients. */
69
+ readonly signal: AbortSignal;
70
+ readonly trace: {
71
+ /** Append a side-effect record (llm_call, tool_call, ...) to the transcript. */
72
+ append(event: PluginEvent): void;
73
+ };
74
+ /**
75
+ * Asks the outside world for a value and pauses the run until `graph.resume(trace, value)`.
76
+ * On resume the node runs again from the top and this call returns the value.
77
+ * The n-th call in a node returns the n-th value delivered to this step.
78
+ * Code before the call runs again on resume, so keep it free of side effects.
79
+ * `request` (plain JSON) is recorded in the `pause` event and returned as `pending.request`.
80
+ */
81
+ interrupt<T = unknown>(request?: unknown): T;
82
+ }
83
+
84
+ export interface RetryPolicy {
85
+ /** Total attempts including the first one. Must be an integer >= 1. */
86
+ readonly maxAttempts: number;
87
+ }
88
+
89
+ /** Receives the current (deeply frozen) state and returns a brand-new state. */
90
+ export type NodeFn<S> = (state: S, ctx: RunContext) => MaybePromise<S>;
91
+
92
+ export interface NodeMeta {
93
+ /** Free-form label recorded in `enter` events, e.g. "code" or "llm". */
94
+ readonly kind?: string;
95
+ readonly retry?: RetryPolicy;
96
+ readonly effect?: Effect;
97
+ }
98
+
99
+ /** Any function with the `NodeFn` signature is a node. Plugins attach metadata with `defineNode`. */
100
+ export type Node<S> = NodeFn<S> & NodeMeta;
101
+
102
+ // ---------------------------------------------------------------------------
103
+ // Graph
104
+ // ---------------------------------------------------------------------------
105
+
106
+ export interface Edge<K extends string> {
107
+ readonly from: K;
108
+ readonly to: K;
109
+ }
110
+
111
+ export interface ConditionalEdge<S, K extends string> {
112
+ readonly from: K;
113
+ /** Pure, synchronous routing function. Put side effects in a node instead. */
114
+ readonly route: (state: NoInfer<S>) => K;
115
+ /** Optional allow-list of targets, checked at build time and at run time. */
116
+ readonly targets?: readonly K[];
117
+ }
118
+
119
+ /** Graph shape. The state schema is passed separately: `createGraph(schema, definition)`. */
120
+ export interface GraphDefinition<S, K extends string> {
121
+ readonly start: NoInfer<K>;
122
+ readonly nodes: { readonly [P in K]: Node<NoInfer<S>> };
123
+ readonly edges?: readonly Edge<NoInfer<K>>[];
124
+ readonly conditionalEdges?: readonly ConditionalEdge<S, NoInfer<K>>[];
125
+ readonly endNodes: readonly NoInfer<K>[];
126
+ }
127
+
128
+ export interface RunOptions {
129
+ /** Defaults to a random UUID. */
130
+ readonly runId?: string;
131
+ readonly signal?: AbortSignal;
132
+ /** Upper bound on node executions, guards against unbounded loops. Defaults to 100. */
133
+ readonly maxSteps?: number;
134
+ /**
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.
137
+ */
138
+ readonly onEvent?: (event: TraceEvent) => void;
139
+ }
140
+
141
+ export type ReplayMode = "recorded" | "live";
142
+
143
+ export interface ReplayOptions<S, K extends string> extends RunOptions {
144
+ /** Replace node implementations for this replay only, e.g. swap a model or mock a tool. */
145
+ readonly overrides?: { readonly [P in K]?: Node<S> };
146
+ /**
147
+ * - `recorded` (default): a non-overridden node reuses its recorded output when it sees
148
+ * exactly the recorded input state; otherwise it runs live.
149
+ * - `live`: every node runs again.
150
+ * In both modes, values delivered by `resume` are fed to `ctx.interrupt` again when the
151
+ * step sees the recorded input state.
152
+ */
153
+ readonly mode?: ReplayMode;
154
+ /** Let `write` nodes run live. Off by default so a replay never repeats a real side effect. */
155
+ readonly allowWrites?: boolean;
156
+ }
157
+
158
+ export interface ResumeOptions extends Omit<RunOptions, "runId"> {
159
+ /** Required to restart a `write` node that was running when the trace ended. */
160
+ readonly allowWrites?: boolean;
161
+ }
162
+
163
+ /** Where a paused run is waiting. Compare `step` with your latest trace to reject stale answers. */
164
+ export interface Pending<K extends string = string> {
165
+ readonly nodeId: K;
166
+ readonly step: number;
167
+ readonly request: unknown;
168
+ }
169
+
170
+ interface RunResultBase<S, K extends string> {
171
+ readonly runId: string;
172
+ /** Final state, or for a paused run the state the waiting node received. */
173
+ readonly state: S;
174
+ readonly trace: Trace;
175
+ /** Node ids in execution order, across pauses. */
176
+ readonly path: readonly K[];
177
+ }
178
+
179
+ export interface CompletedRun<S, K extends string = string> extends RunResultBase<S, K> {
180
+ readonly status: "completed";
181
+ }
182
+
183
+ export interface PausedRun<S, K extends string = string> extends RunResultBase<S, K> {
184
+ readonly status: "paused";
185
+ readonly pending: Pending<K>;
186
+ }
187
+
188
+ export type RunResult<S, K extends string = string> = CompletedRun<S, K> | PausedRun<S, K>;
189
+
190
+ export interface Graph<S, I, K extends string> {
191
+ readonly start: K;
192
+ readonly nodeIds: readonly K[];
193
+ readonly endNodes: readonly K[];
194
+ run(input: I, options?: RunOptions): Promise<RunResult<S, K>>;
195
+ /** Runs without Promises. Throws ASYNC_IN_SYNC_RUN if a node or the schema returns a Promise. */
196
+ runSync(input: I, options?: RunOptions): RunResult<S, K>;
197
+ /**
198
+ * Continues a trace under the same runId, appending to it.
199
+ * - Paused trace: `value` is returned by the waiting node's `ctx.interrupt`.
200
+ * - Trace that ended without `run_end` (crash): restarts from the last unfinished step; omit `value`.
201
+ */
202
+ resume(trace: Trace, value?: unknown, options?: ResumeOptions): Promise<RunResult<S, K>>;
203
+ resumeSync(trace: Trace, value?: unknown, options?: ResumeOptions): RunResult<S, K>;
204
+ /** Re-runs a recorded trace from its original input under a new runId. */
205
+ replay(trace: Trace, options?: ReplayOptions<S, K>): Promise<RunResult<S, K>>;
206
+ }
@@ -0,0 +1,81 @@
1
+ export function isThenable(value: unknown): value is PromiseLike<unknown> {
2
+ return (
3
+ value !== null &&
4
+ (typeof value === "object" || typeof value === "function") &&
5
+ typeof (value as { then?: unknown }).then === "function"
6
+ );
7
+ }
8
+
9
+ export class NotJsonError extends Error {
10
+ constructor(
11
+ readonly path: string,
12
+ readonly reason: string,
13
+ ) {
14
+ super(`${path === "" ? "(root)" : path}: ${reason}`);
15
+ }
16
+ }
17
+
18
+ /**
19
+ * Returns a deeply frozen copy of a plain-JSON value.
20
+ *
21
+ * Throws `NotJsonError` for anything that would not survive a JSON round trip
22
+ * (Date, Map, class instances, functions, bigint, NaN, cycles). This is what makes
23
+ * an in-memory trace and a trace loaded from JSONL replay identically.
24
+ * `undefined` object properties are kept (JSON drops them; `jsonEqual` ignores them).
25
+ */
26
+ export function freezeJson<T>(value: T): T {
27
+ return copy(value, "", new Set()) as T;
28
+ }
29
+
30
+ function copy(value: unknown, path: string, ancestors: Set<object>): unknown {
31
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
32
+ if (typeof value === "number") {
33
+ if (!Number.isFinite(value)) throw new NotJsonError(path, `non-finite number ${value}`);
34
+ return value;
35
+ }
36
+ if (typeof value !== "object") throw new NotJsonError(path, `${typeof value} is not JSON`);
37
+ if (ancestors.has(value)) throw new NotJsonError(path, "circular reference");
38
+
39
+ ancestors.add(value);
40
+ let result: unknown;
41
+ if (Array.isArray(value)) {
42
+ result = value.map((item, i) => {
43
+ if (item === undefined) throw new NotJsonError(`${path}[${i}]`, "undefined in array");
44
+ return copy(item, `${path}[${i}]`, ancestors);
45
+ });
46
+ } else {
47
+ const proto = Object.getPrototypeOf(value);
48
+ if (proto !== Object.prototype && proto !== null) {
49
+ const name = (value as { constructor?: { name?: string } }).constructor?.name ?? "object";
50
+ throw new NotJsonError(path, `${name} is not a plain object (use strings / numbers / arrays / objects)`);
51
+ }
52
+ const out: Record<string, unknown> = {};
53
+ for (const [key, item] of Object.entries(value)) {
54
+ out[key] = item === undefined ? undefined : copy(item, path === "" ? key : `${path}.${key}`, ancestors);
55
+ }
56
+ result = out;
57
+ }
58
+ ancestors.delete(value);
59
+ return Object.freeze(result);
60
+ }
61
+
62
+ /** Structural equality for JSON values. Object properties set to `undefined` count as absent. */
63
+ export function jsonEqual(a: unknown, b: unknown): boolean {
64
+ if (a === b) return true;
65
+ if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
66
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
67
+ if (Array.isArray(a) && Array.isArray(b)) {
68
+ return a.length === b.length && a.every((item, i) => jsonEqual(item, b[i]));
69
+ }
70
+ const ra = a as Record<string, unknown>;
71
+ const rb = b as Record<string, unknown>;
72
+ const ka = Object.keys(ra).filter((k) => ra[k] !== undefined);
73
+ const kb = Object.keys(rb).filter((k) => rb[k] !== undefined);
74
+ return ka.length === kb.length && ka.every((k) => Object.hasOwn(rb, k) && jsonEqual(ra[k], rb[k]));
75
+ }
76
+
77
+ export function randomId(): string {
78
+ const cryptoApi = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;
79
+ if (typeof cryptoApi?.randomUUID === "function") return cryptoApi.randomUUID();
80
+ return `run-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
81
+ }
package/src/index.ts ADDED
@@ -0,0 +1,46 @@
1
+ // taugraph kernel: graph definition, runtime, typed state, append-only trace.
2
+ // Plugin nodes (CodeNode, LLMNode, ...) live in "taugraph/nodes" and only use this public API.
3
+
4
+ export type { TaugraphErrorCode, TaugraphErrorDetails } from "./core/errors.js";
5
+ export { isTaugraphError, TaugraphError } from "./core/errors.js";
6
+ export { createGraph } from "./core/graph.js";
7
+ export { defineNode } from "./core/node.js";
8
+ export type { StandardSchemaV1 } from "./core/standard-schema.js";
9
+ export type { RecordedStep, TraceDiff } from "./core/trace.js";
10
+ export {
11
+ assertTrace,
12
+ diffTraces,
13
+ fromJSONL,
14
+ recordedSteps,
15
+ TRACE_FORMAT,
16
+ TRACE_VERSION,
17
+ toJSONL,
18
+ tracePath,
19
+ } from "./core/trace.js";
20
+ export type {
21
+ CompletedRun,
22
+ ConditionalEdge,
23
+ Edge,
24
+ Effect,
25
+ Graph,
26
+ GraphDefinition,
27
+ KernelEventType,
28
+ MaybePromise,
29
+ Node,
30
+ NodeFn,
31
+ NodeMeta,
32
+ PausedRun,
33
+ Pending,
34
+ PluginEvent,
35
+ PluginEventType,
36
+ ReplayMode,
37
+ ReplayOptions,
38
+ ResumeOptions,
39
+ RetryPolicy,
40
+ RunContext,
41
+ RunOptions,
42
+ RunResult,
43
+ Trace,
44
+ TraceEvent,
45
+ TraceEventType,
46
+ } from "./core/types.js";
@@ -0,0 +1,18 @@
1
+ import { defineNode, type Effect, type MaybePromise, type Node, type RetryPolicy, type RunContext } from "../index.js";
2
+
3
+ export interface CodeNodeOptions {
4
+ readonly retry?: RetryPolicy;
5
+ /** Declare `"write"` for code that changes the outside world, so replay will not repeat it. */
6
+ readonly effect?: Effect;
7
+ }
8
+
9
+ /**
10
+ * Deterministic transformation from state to state. Labelled `kind: "code"` in the trace.
11
+ * `S` is inferred from the graph schema; outside a graph, annotate it: `CodeNode<State>(...)`.
12
+ */
13
+ export function CodeNode<S>(
14
+ fn: (state: S, ctx: RunContext) => MaybePromise<NoInfer<S>>,
15
+ options: CodeNodeOptions = {},
16
+ ): Node<S> {
17
+ return defineNode(fn, { kind: "code", ...options });
18
+ }
@@ -0,0 +1,33 @@
1
+ import { defineNode, type MaybePromise, type Node, type StandardSchemaV1 } from "../index.js";
2
+ import { andThen, issuesMessage } from "./util.js";
3
+
4
+ export interface HumanNodeConfig<S, T> {
5
+ /**
6
+ * Builds what the human sees. Returned as `pending.request` by the paused run.
7
+ * `error` is set when the previous answer failed the `answer` schema, so you can ask again.
8
+ */
9
+ readonly ask: (state: S, error?: string) => unknown;
10
+ /** Validates the value passed to `graph.resume`. An invalid value pauses again with `error` set. */
11
+ readonly answer?: StandardSchemaV1<unknown, T>;
12
+ readonly update: (state: S, answer: T) => NoInfer<S>;
13
+ }
14
+
15
+ /**
16
+ * Pauses the run until a human (or any outside system) answers through `graph.resume(trace, value)`.
17
+ * Built only on `ctx.interrupt`; the kernel knows nothing about humans.
18
+ */
19
+ export function HumanNode<S, T = unknown>(config: HumanNodeConfig<S, T>): Node<S> {
20
+ return defineNode<S>(
21
+ (state, ctx) => {
22
+ const ask = (error?: string): MaybePromise<S> => {
23
+ const value = ctx.interrupt<unknown>(config.ask(state, error));
24
+ if (!config.answer) return config.update(state, value as T);
25
+ return andThen(config.answer["~standard"].validate(value), (result) =>
26
+ result.issues ? ask(issuesMessage(result.issues)) : config.update(state, result.value),
27
+ );
28
+ };
29
+ return ask();
30
+ },
31
+ { kind: "human" },
32
+ );
33
+ }
@@ -0,0 +1,15 @@
1
+ // Plugin nodes. Not part of the kernel: everything here is built on the public
2
+ // `defineNode` + `ctx.trace.append` API, the same way third-party nodes are.
3
+
4
+ export { CodeNode, type CodeNodeOptions } from "./code.js";
5
+ export { HumanNode, type HumanNodeConfig } from "./human.js";
6
+ export {
7
+ type ChatMessage,
8
+ type LLMModel,
9
+ LLMNode,
10
+ LLMOutputError,
11
+ type LLMRequest,
12
+ type LLMResponse,
13
+ type LLMStructuredNodeConfig,
14
+ type LLMTextNodeConfig,
15
+ } from "./llm.js";
@@ -0,0 +1,123 @@
1
+ import { defineNode, type MaybePromise, type Node, type RetryPolicy, type StandardSchemaV1 } from "../index.js";
2
+ import { andThen, issuesMessage } from "./util.js";
3
+
4
+ // ---------------------------------------------------------------------------
5
+ // Model contract. taugraph ships no provider; adapt any SDK or HTTP API to this.
6
+ // ---------------------------------------------------------------------------
7
+
8
+ export interface ChatMessage {
9
+ readonly role: "system" | "user" | "assistant";
10
+ readonly content: string;
11
+ }
12
+
13
+ /** Everything in a request is recorded in the trace, so keep it plain JSON. */
14
+ export interface LLMRequest {
15
+ readonly messages: readonly ChatMessage[];
16
+ readonly temperature?: number;
17
+ readonly maxTokens?: number;
18
+ /** Hint for adapters that support JSON mode. */
19
+ readonly responseFormat?: "text" | "json";
20
+ /** Provider-specific options, passed through by the adapter. */
21
+ readonly extra?: Readonly<Record<string, unknown>>;
22
+ }
23
+
24
+ export interface LLMResponse {
25
+ readonly content: string;
26
+ readonly model?: string;
27
+ readonly finishReason?: string;
28
+ readonly usage?: { readonly inputTokens?: number; readonly outputTokens?: number };
29
+ }
30
+
31
+ export interface LLMModel {
32
+ /** Recorded in every `llm_call` event, e.g. "openai:gpt-4o-mini" or "ollama:qwen3". */
33
+ readonly id: string;
34
+ complete(request: LLMRequest, options: { readonly signal: AbortSignal }): MaybePromise<LLMResponse>;
35
+ }
36
+
37
+ // ---------------------------------------------------------------------------
38
+ // LLMNode
39
+ // ---------------------------------------------------------------------------
40
+
41
+ interface LLMNodeBase<S> {
42
+ readonly model: LLMModel;
43
+ /** Builds the request from state. A string becomes a single user message. */
44
+ readonly prompt: (state: S) => LLMRequest | string;
45
+ /** Retries the whole call, including output parsing. */
46
+ readonly retry?: RetryPolicy;
47
+ }
48
+
49
+ export interface LLMTextNodeConfig<S> extends LLMNodeBase<S> {
50
+ /** Folds the reply into state. The return type does not drive inference; the graph does. */
51
+ readonly update: (state: S, text: string, response: LLMResponse) => NoInfer<S>;
52
+ }
53
+
54
+ export interface LLMStructuredNodeConfig<S, T> extends LLMNodeBase<S> {
55
+ /** Parses the response content as JSON (code fences allowed) and validates it. */
56
+ readonly output: StandardSchemaV1<unknown, T>;
57
+ readonly update: (state: S, data: T, response: LLMResponse) => NoInfer<S>;
58
+ }
59
+
60
+ /** Thrown when structured output is not JSON or fails its schema. Retryable. */
61
+ export class LLMOutputError extends Error {
62
+ override readonly name = "LLMOutputError";
63
+ constructor(
64
+ message: string,
65
+ readonly content: string,
66
+ readonly issues?: readonly StandardSchemaV1.Issue[],
67
+ ) {
68
+ super(message);
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Calls a model and folds the result into state. Every call is appended to the trace
74
+ * as an `llm_call` event (request in `input`, response in `output`).
75
+ * Stays synchronous when the model does, so mock models work with `runSync`.
76
+ */
77
+ export function LLMNode<S, T>(config: LLMStructuredNodeConfig<S, T>): Node<S>;
78
+ export function LLMNode<S>(config: LLMTextNodeConfig<S>): Node<S>;
79
+ export function LLMNode<S, T>(config: LLMTextNodeConfig<S> | LLMStructuredNodeConfig<S, T>): Node<S> {
80
+ const { model, prompt } = config;
81
+ return defineNode<S>(
82
+ (state, ctx) => {
83
+ const built = prompt(state);
84
+ const request: LLMRequest = typeof built === "string" ? { messages: [{ role: "user", content: built }] } : built;
85
+ const startedAt = Date.now();
86
+
87
+ return andThen(model.complete(request, { signal: ctx.signal }), (response) => {
88
+ if (typeof response?.content !== "string") {
89
+ throw new TypeError(`Model "${model.id}" returned a response without a string \`content\``);
90
+ }
91
+ ctx.trace.append({
92
+ type: "llm_call",
93
+ input: request,
94
+ output: response,
95
+ meta: { model: model.id, durationMs: Date.now() - startedAt },
96
+ });
97
+ if (!("output" in config)) return config.update(state, response.content, response);
98
+ return andThen(parseStructured(config.output, response.content), (data) =>
99
+ config.update(state, data, response),
100
+ );
101
+ });
102
+ },
103
+ { kind: "llm", ...(config.retry && { retry: config.retry }) },
104
+ );
105
+ }
106
+
107
+ function parseStructured<T>(schema: StandardSchemaV1<unknown, T>, content: string): MaybePromise<T> {
108
+ const fenced = /```(?:json)?\s*([\s\S]*?)```/i.exec(content);
109
+ const text = (fenced?.[1] ?? content).trim();
110
+ let json: unknown;
111
+ try {
112
+ json = JSON.parse(text);
113
+ } catch {
114
+ throw new LLMOutputError("Model output is not valid JSON", content);
115
+ }
116
+ return andThen(schema["~standard"].validate(json), (result) => {
117
+ if (result.issues) {
118
+ const detail = issuesMessage(result.issues);
119
+ throw new LLMOutputError(`Model output does not match the schema: ${detail}`, content, result.issues);
120
+ }
121
+ return result.value;
122
+ });
123
+ }
@@ -0,0 +1,13 @@
1
+ import type { MaybePromise, StandardSchemaV1 } from "../index.js";
2
+
3
+ /** Chains without introducing a Promise when the value is synchronous, so nodes stay `runSync`-friendly. */
4
+ export function andThen<A, B>(value: MaybePromise<A>, fn: (value: A) => MaybePromise<B>): MaybePromise<B> {
5
+ if (value !== null && typeof value === "object" && typeof (value as PromiseLike<A>).then === "function") {
6
+ return Promise.resolve(value).then(fn);
7
+ }
8
+ return fn(value as A);
9
+ }
10
+
11
+ export function issuesMessage(issues: readonly StandardSchemaV1.Issue[]): string {
12
+ return issues.map((issue) => issue.message).join("; ");
13
+ }