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,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,100 @@
1
+ // Helpers for adapters: the text of a message, and images given by URL turned into what they stand for.
2
+ import type { MaybePromise } from "../index.js";
3
+ import type { ChatMessage, ContentPart, ImagePart, MessageContent } from "./llm.js";
4
+ import { andThen } from "./util.js";
5
+
6
+ export interface TextOfOptions {
7
+ /** Written in place of each image. Without it, an image is an error. */
8
+ readonly imagePlaceholder?: string;
9
+ }
10
+
11
+ /** The text of a message's content, for adapters that send text only. Images are an error unless replaced. */
12
+ export function textOf(content: MessageContent, options: TextOfOptions = {}): string {
13
+ if (typeof content === "string") return content;
14
+ let text = "";
15
+ for (const part of content) {
16
+ if (part.type === "text") text += part.text;
17
+ else if (options.imagePlaceholder !== undefined) text += options.imagePlaceholder;
18
+ else {
19
+ throw new TypeError(
20
+ "textOf: the content has images and this adapter sends text only; pass { imagePlaceholder } to replace them",
21
+ );
22
+ }
23
+ }
24
+ return text;
25
+ }
26
+
27
+ /** Reads an image URL an adapter cannot send as it is, e.g. `media:abc` from your own store. */
28
+ export type ImageResolver = (url: string) => MaybePromise<ImagePart>;
29
+
30
+ const DATA_URL = /^data:([\w.+-]+\/[\w.+-]+);base64,([A-Za-z0-9+/]*={0,2})$/i;
31
+
32
+ const shown = (url: string): string => (url.length > 100 ? `${url.slice(0, 100)}…` : url);
33
+
34
+ const isURLImage = (part: ContentPart): boolean => part.type === "image" && !("data" in part);
35
+
36
+ function isImagePart(value: unknown): value is ImagePart {
37
+ if (typeof value !== "object" || value === null) return false;
38
+ const v = value as Record<string, unknown>;
39
+ if (v.type !== "image") return false;
40
+ if (typeof v.data === "string") return typeof v.mimeType === "string";
41
+ return typeof v.url === "string" && (v.mimeType === undefined || typeof v.mimeType === "string");
42
+ }
43
+
44
+ function fromDataURL(url: string): ImagePart {
45
+ const match = DATA_URL.exec(url);
46
+ if (!match) throw new TypeError(`resolveImages: only base64 data: URLs are supported, got "${shown(url)}"`);
47
+ return { type: "image", mimeType: match[1] as string, data: match[2] as string };
48
+ }
49
+
50
+ function resolveParts(parts: readonly ContentPart[], resolve: ImageResolver | undefined): MaybePromise<ContentPart[]> {
51
+ const out: ContentPart[] = [];
52
+ const from = (start: number): MaybePromise<ContentPart[]> => {
53
+ for (let i = start; i < parts.length; i++) {
54
+ const part = parts[i] as ContentPart;
55
+ if (part.type === "text" || "data" in part) {
56
+ out.push(part);
57
+ continue;
58
+ }
59
+ const { url } = part;
60
+ if (/^data:/i.test(url)) {
61
+ out.push(fromDataURL(url));
62
+ continue;
63
+ }
64
+ if (!resolve) throw new TypeError(`resolveImages: no resolver for image URL "${shown(url)}"`);
65
+ return andThen(resolve(url), (image) => {
66
+ if (!isImagePart(image))
67
+ throw new TypeError(`resolveImages: the resolver did not return an image for "${shown(url)}"`);
68
+ out.push(!("data" in image) && /^data:/i.test(image.url) ? fromDataURL(image.url) : image);
69
+ return from(i + 1);
70
+ });
71
+ }
72
+ return out;
73
+ };
74
+ return from(0);
75
+ }
76
+
77
+ /**
78
+ * Replaces each image given by URL in user and tool messages: every `data:` URL, including one `resolve` returns,
79
+ * becomes a base64 image; other URLs become what `resolve` returns (which may be another URL). URLs are read one after
80
+ * another, and the result is synchronous when `resolve` is. Messages without such images are returned as the same
81
+ * objects.
82
+ */
83
+ export function resolveImages(messages: readonly ChatMessage[], resolve?: ImageResolver): MaybePromise<ChatMessage[]> {
84
+ const out: ChatMessage[] = [];
85
+ const from = (start: number): MaybePromise<ChatMessage[]> => {
86
+ for (let i = start; i < messages.length; i++) {
87
+ const m = messages[i] as ChatMessage;
88
+ if ((m.role !== "user" && m.role !== "tool") || typeof m.content === "string" || !m.content.some(isURLImage)) {
89
+ out.push(m);
90
+ continue;
91
+ }
92
+ return andThen(resolveParts(m.content, resolve), (content) => {
93
+ out.push({ ...m, content });
94
+ return from(i + 1);
95
+ });
96
+ }
97
+ return out;
98
+ };
99
+ return from(0);
100
+ }
@@ -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,25 @@
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 { type ImageResolver, resolveImages, type TextOfOptions, textOf } from "./content.js";
6
+ export { HumanNode, type HumanNodeConfig } from "./human.js";
7
+ export {
8
+ type ChatMessage,
9
+ type ContentPart,
10
+ type ImagePart,
11
+ type LLMModel,
12
+ LLMNode,
13
+ LLMOutputError,
14
+ type LLMRequest,
15
+ type LLMResponse,
16
+ type LLMStructuredNodeConfig,
17
+ type LLMTextNodeConfig,
18
+ type MessageContent,
19
+ type ReasoningLevel,
20
+ type ReasoningPart,
21
+ type TextPart,
22
+ type ToolCall,
23
+ type ToolChoice,
24
+ type ToolSpec,
25
+ } from "./llm.js";