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
package/CHANGELOG.md ADDED
@@ -0,0 +1,62 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses [Semantic Versioning](https://semver.org/).
4
+
5
+ ## [Unreleased]
6
+
7
+ ## [0.3.0] - 2026-11-25
8
+
9
+ Tool calling, images and reasoning models in the model contract, plus two plugin entry points: `taugraph/agent` (the model ↔ tools loop as a graph) and `taugraph/openai` (an adapter for any OpenAI-compatible endpoint).
10
+
11
+ ### Changed
12
+
13
+ - **Breaking:** the `content` of `user` and `tool` messages is `string | ContentPart[]`, so they can carry images. Code that builds messages is unaffected; code that reads `content` as a string no longer compiles. An adapter that sends text only replaces `m.content` with `textOf(m.content)`, which throws on images unless given `{ imagePlaceholder }`. Template strings, `+` and `String()` still compile but turn parts into `[object Object]`, and JavaScript adapters get no compile error, so search for reads of `content` too.
14
+ - Types: `ChatMessage` is now a union by `role` and includes `role: "tool"`. Code that only reads `role` and `content` is unaffected, and nothing changes at run time for code that sends no tool messages. An adapter that maps `role` into a provider SDK's message type, or switches over `role` exhaustively, needs a `tool` branch; TypeScript points to the line.
15
+
16
+ ### Added
17
+
18
+ - Tool calling in the model contract: optional `tools` and `toolChoice` on `LLMRequest`, `toolCalls` on `LLMResponse`, `tool` messages and assistant `toolCalls` in `ChatMessage`. Tool definitions follow MCP (`name`, `description`, `inputSchema`); arguments are parsed JSON.
19
+ - `taugraph/agent`: `createAgent` runs the model ↔ tools loop as a graph with one step per model call and one per tool call, so tracing, replay, write protection, crash recovery and approvals (`approve` → `ctx.interrupt`) apply to each call. `tool()` takes a Standard Schema for arguments and derives the JSON Schema through Standard JSON Schema. Bounded by `maxRounds` (default 8) and 32 calls per reply; calls beyond 32 get error answers after the results of the calls that ran. For adapter authors: assistant messages written by the agent always carry `model`, may carry `reasoning`, and tool calls may carry `signature`; strict endpoints such as OpenAI's refuse these fields, so build the provider's message from `role` and `content` (and tool fields) instead of forwarding messages as they are.
20
+ - `taugraph/openai`: the OpenAI-compatible adapter, formerly an example, as a plugin entry point. `openAICompatible({ baseURL, model, apiKey?, resolveImage?, reasoningParams?, sendReasoning?, fetch? })` adds no dependencies and uses the global `fetch` unless given one. It translates tools, tool calls and tool results (`pnpm example:agent`); missing call ids become `call_<round>_<index>`, and error results that do not already start with `Error` get an `Error: ` prefix because OpenAI's tool messages have no error flag. It sends images, reads image references with `resolveImage`, and moves images from tool results into a user message after the tool messages. It sends `reasoning_effort` or your `reasoningParams`, reads `reasoning_content` and `reasoning`, and sends the model's own reasoning back unless `sendReasoning: false`. `fetch` replaces the global one, e.g. for a proxy, retries or tests.
21
+ - Images in messages: `TextPart`, `ImagePart` (base64 `data` + `mimeType`, or a `url` that may be a reference of your own) and `ContentPart` in `taugraph/nodes`. `resolveImages(messages, resolve)` reads references when a request is sent, so traces can keep a few bytes per image; `textOf(content)` gives the text for text-only adapters.
22
+ - Agent tools can return text and images (`{ content: ContentPart[] }`); the state schema checks parts and points at the bad one.
23
+ - Reasoning models: `reasoning` on `LLMRequest` (seven levels, `"off"` to `"max"`), what the model thought in `LLMResponse.reasoning` and `usage.reasoningTokens`, `ToolCall.signature`, and `reasoning` and `model` on assistant messages, so a tool loop can send a model's own thinking back as DeepSeek V4, Claude and Gemini 3 require. `createAgent({ reasoning })` sets the level for every call and records which model wrote each message.
24
+
25
+ ## [0.2.0] - 2026-11-19
26
+
27
+ First release on npm.
28
+
29
+ ### Added
30
+
31
+ - Pause and resume: `ctx.interrupt(request)` pauses a run; `graph.resume(trace, value)` / `resumeSync` continues it under the same runId, appending to the same trace. Runs now return `status: "completed" | "paused"`, and paused runs carry `pending: { nodeId, step, request }`.
32
+ - Crash recovery: `resume(trace)` continues a trace that ended without `run_end`. An unfinished `write` step fails with `UNKNOWN_OUTCOME` unless `allowWrites: true`; restarted steps see `ctx.meta.recovered`.
33
+ - Effects: nodes can declare `effect: "read" | "write"` (`defineNode`, `CodeNode`). Replay blocks live `write` nodes with `WRITE_BLOCKED` unless overridden or `allowWrites: true`, including when a paused replay is resumed.
34
+ - Replay feeds values delivered by `resume` back to `ctx.interrupt` when a step sees its recorded state, in both modes.
35
+ - `HumanNode` plugin: pause for an answer, validate it with a schema, ask again with the error.
36
+ - Kernel events `pause` and `resume`; `run_end.meta.status` can be `paused`. Error codes `WRITE_BLOCKED`, `UNKNOWN_OUTCOME`, `NOT_RESUMABLE`, `SINK_FAILED`.
37
+ - Example `examples/checkout.ts`: the model only picks one of a fixed set of commands, and code does the rest.
38
+
39
+ ### Changed
40
+
41
+ - `onEvent` failures stop the run with `SINK_FAILED` instead of being rethrown asynchronously while the run continued.
42
+ - `RunResult` is now a union of `CompletedRun` and `PausedRun`; check `status` before reading `pending`.
43
+ - Removed the conventional `human_pause` plugin event type; pausing is now the kernel's `pause` event.
44
+
45
+ ## [0.1.0] - 2026-11-19
46
+
47
+ GitHub only, not published to npm.
48
+
49
+ ### Added
50
+
51
+ - Kernel: `createGraph` with static validation, sequential and conditional edges, end nodes, `maxSteps`.
52
+ - Runtime: `run` (async) and `runSync` sharing one generator-based loop; per-node retry policy; cancellation via `AbortSignal`.
53
+ - State: Standard Schema validation of input and every node output; JSON-only, deeply frozen state.
54
+ - Trace: append-only event log (format version 1), `onEvent` streaming, `toJSONL` / `fromJSONL`, `diffTraces`.
55
+ - Replay: `graph.replay` with node overrides and `recorded` / `live` modes.
56
+ - Plugin nodes (`taugraph/nodes`): `CodeNode`, `LLMNode` with a provider-agnostic `LLMModel` contract and structured output.
57
+ - Examples: quick start, retrieval with retry loop, OpenAI-compatible adapter.
58
+
59
+ [Unreleased]: https://github.com/wangcao-hub/taugraph/compare/v0.3.0...HEAD
60
+ [0.3.0]: https://github.com/wangcao-hub/taugraph/compare/v0.2.0...v0.3.0
61
+ [0.2.0]: https://github.com/wangcao-hub/taugraph/compare/v0.1.0...v0.2.0
62
+ [0.1.0]: https://github.com/wangcao-hub/taugraph/releases/tag/v0.1.0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 taugraph contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,448 @@
1
- # Temporary Holding Version
1
+ # taugraph (τ)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![CI](https://github.com/wangcao-hub/taugraph/actions/workflows/ci.yml/badge.svg)](https://github.com/wangcao-hub/taugraph/actions/workflows/ci.yml) [![npm](https://img.shields.io/npm/v/taugraph)](https://www.npmjs.com/package/taugraph) [![license](https://img.shields.io/badge/license-MIT-blue)](./LICENSE)
4
+
5
+ **Minimal typed agent graph harness.**
6
+
7
+ > Pi is a loop. τ is the trajectory.
8
+
9
+ A tiny kernel that runs a graph of nodes over one schema-validated, immutable state, and writes every step to an append-only, replayable transcript. LLM calls, tools, sub-agents and humans are plugin nodes. The kernel knows nothing about them.
10
+
11
+ [中文文档](./README.zh-CN.md) · [Design notes](./docs/design.md) · [Trace format](./docs/trace-format.md)
12
+
13
+ ```
14
+ npm install taugraph zod # or any Standard Schema library: valibot, arktype, ...
15
+ ```
16
+
17
+ ## Why τ
18
+
19
+ In reinforcement learning, τ is the standard symbol for a trajectory: the sequence of states and actions an agent goes through. A taugraph run is exactly that, a path through the graph with a state snapshot at every step, recorded so it can be replayed. The name is also a nod to [Pi](https://pi.dev), whose minimal, append-only design taugraph follows (and to τ = 2π).
20
+
21
+ ## Why put the flow in code
22
+
23
+ If a model decides every step and gets each one right 95% of the time, a 3-step flow succeeds about 86% of the time and a 5-step flow about 77%. Better prompts move 95% to 97%, never to 100%. taugraph takes everything that can be written down in advance (what runs next, when to stop and ask, which calls change the world) out of the model and into a typed graph. The model is left with what only it can do, such as understanding a reply and picking one of a few allowed commands.
24
+
25
+ ## How it works
26
+
27
+ A model is one kind of node among others. It writes a value into state; code reads that value and decides what happens next.
28
+
29
+ ```mermaid
30
+ flowchart LR
31
+ reply(["user reply<br/>resume(trace, value)"]) --> ask
32
+ ask["confirm<br/>HumanNode · ctx.interrupt"] --> classify
33
+ classify["classify<br/>LLMNode<br/>output: one of 4 commands"] --> route{"conditional edge<br/>pure code"}
34
+ route -->|confirm| place["place order<br/>effect: write"]
35
+ route -->|modify| quote["quote<br/>code"]
36
+ route -->|explore| explain["explain<br/>code"]
37
+ route -->|cancel| cancelled["cancelled<br/>code"]
38
+ quote -.-> ask
39
+ explain -.-> ask
40
+ classDef human fill:#fef3c7,stroke:#d97706,color:#111
41
+ classDef model fill:#ede9fe,stroke:#7c3aed,color:#111
42
+ classDef code fill:#e0f2fe,stroke:#0284c7,color:#111
43
+ classDef write fill:#fee2e2,stroke:#dc2626,color:#111
44
+ class reply,ask human
45
+ class classify model
46
+ class route,quote,explain,cancelled code
47
+ class place write
48
+ ```
49
+
50
+ <sub>The graph of [`examples/checkout.ts`](./examples/checkout.ts). Yellow waits for a person. Purple is the only place a model runs, and its output must parse as one of four commands. Blue is code you can unit-test. Red changes the outside world, so replays block it unless you allow it.</sub>
51
+
52
+ Everything taugraph does after a run is computed from one append-only log. There is no second store to keep in sync.
53
+
54
+ ```mermaid
55
+ flowchart LR
56
+ exec["run · resume"] -- "append, write-ahead" --> trace[("trace · JSONL<br/>state at every step<br/>LLM and tool calls<br/>human answers")]
57
+ trace -- "resume(trace, value)" --> pause["pause and resume<br/>no checkpointer"]
58
+ trace -- "resume(trace)" --> recover["crash recovery<br/>unfinished write: UNKNOWN_OUTCOME"]
59
+ trace -- "replay(trace, overrides)" --> cf["counterfactual replay<br/>writes blocked"]
60
+ trace -- "diffTraces · export" --> evals["regression evals"]
61
+ classDef log fill:#f1f5f9,stroke:#475569,color:#111
62
+ class trace log
63
+ ```
64
+
65
+ ## What's new in the design
66
+
67
+ 1. **The trace is the checkpoint.** Pause, resume and crash recovery are all derived from the append-only log, so the kernel has no checkpointer, thread store or storage interface. Store the JSONL wherever you like. (LangGraph's `interrupt()` needs a checkpointer and a thread id.)
68
+ 2. **Counterfactual replay.** A replayed step reuses its recorded output only when it receives exactly the recorded input state; any step that sees a different state runs live. "What if step 2 had used another model?" is one call, and the steps before the first change cost nothing. (LangGraph's replay re-executes every node after the checkpoint, LLM and API calls included. Durable-execution engines such as Temporal treat a divergence from history as a non-determinism error.)
69
+
70
+ ```mermaid
71
+ flowchart LR
72
+ s0["step 0 · quote<br/>recorded"] --> s1["step 1 · confirm<br/>recorded answer: make it 2"] --> s2["step 2 · classify<br/>new model says: confirm"] --> s3["step 3 · place order<br/>WRITE_BLOCKED"]
73
+ classDef rec fill:#f1f5f9,stroke:#94a3b8,color:#111
74
+ classDef new fill:#ede9fe,stroke:#7c3aed,color:#111
75
+ classDef stop fill:#fee2e2,stroke:#dc2626,color:#111
76
+ class s0,s1 rec
77
+ class s2 new
78
+ class s3 stop
79
+ ```
80
+
81
+ <sub>The checkout conversation replayed with an over-eager classifier. Steps 0 and 1 come from the trace, including the person's answer. The new model reads "make it 2" as a confirmation, so the run would now place an order; the replay stops there instead.</sub>
82
+
83
+ 3. **Replays don't repeat side effects unless you say so.** `effect: "write"` is part of the node, not a convention. Replays, and resumed replays, refuse to run a write node live unless you override it or pass `allowWrites: true`. A write that was running when the process died becomes `UNKNOWN_OUTCOME`, never a silent retry.
84
+ 4. **Conversations become test cases.** Human answers are stored in the trace as inputs. Replaying a human-in-the-loop run needs no human: each `ctx.interrupt` gets its recorded answer as long as the step sees the recorded state. (LangGraph fires interrupts again on replay.)
85
+ 5. **Models choose, code routes.** Routers are synchronous functions of the state; an async router is rejected at run time. A model can only write a schema-checked value into state, such as one of four commands, and the edge reads it. A router cannot await a model call, so model decisions happen in nodes, where the trace records them.
86
+
87
+ ## Where it sits
88
+
89
+ | | Pi | LangGraph | taugraph |
90
+ | --------------- | ------------------------------- | ----------------------------------------- | --------------------------------------------- |
91
+ | Kernel | single-agent loop (LLM ↔ tools) | stateful graph with channels and reducers | graph scheduler + typed state |
92
+ | Orchestration | extension | core | core |
93
+ | State | message transcript | channels, checkpoint per step | one schema-checked, frozen JSON object |
94
+ | Pause for input | the conversation itself | `interrupt()` + a checkpointer | `ctx.interrupt()`, resumed from the trace |
95
+ | Log | append-only session | checkpoints in a persistence backend | append-only event stream with state snapshots |
96
+ | LLM / tools | built in | bring your own, often LangChain | plugin nodes, none in the kernel |
97
+ | Runtime deps | provider SDKs | LangChain core and friends | **none** |
98
+
99
+ ## Rules of the kernel
100
+
101
+ 1. The kernel runs graphs, validates state and appends to the trace. It has **no LLM, no tools, no RAG, no memory**.
102
+ 2. State has a schema ([Standard Schema](https://standardschema.dev): Zod ≥ 3.24, Valibot ≥ 1, ArkType ≥ 2).
103
+ 3. The trace is append-only. Events are frozen and never edited.
104
+ 4. A run is a serializable trace. Replay it at any time, with any node or model swapped.
105
+ 5. No hidden magic. Side effects are recorded as explicit events, and nodes that change the world declare `effect: "write"` so a replay never repeats them.
106
+ 6. Sync first, async optional. `runSync` never touches a Promise; no async runtime is assumed.
107
+ 7. Zero runtime dependencies. Works in Node ≥ 22, Bun, Deno and browsers (CI runs Node 22 and 24; Bun was checked by hand for 0.3.0, Deno and Chrome for 0.2.0).
108
+
109
+ These are enforced by tests (`test/architecture.test.ts`), not only by convention.
110
+
111
+ ## Quick start
112
+
113
+ ```ts
114
+ import { createGraph, diffTraces, toJSONL } from "taugraph";
115
+ import { CodeNode, LLMNode, type LLMModel, textOf } from "taugraph/nodes";
116
+ import { z } from "zod";
117
+
118
+ const State = z.object({
119
+ question: z.string(),
120
+ raw: z.string().nullable().default(null),
121
+ final: z.string().nullable().default(null),
122
+ });
123
+
124
+ // Any provider fits this contract; taugraph/openai covers OpenAI-compatible endpoints.
125
+ const model: LLMModel = {
126
+ id: "mock:echo",
127
+ complete: (req) => ({ content: `echo: ${textOf(req.messages.at(-1)?.content ?? "")}` }),
128
+ };
129
+
130
+ const graph = createGraph(State, {
131
+ start: "fetch",
132
+ nodes: {
133
+ fetch: CodeNode((s) => ({ ...s, raw: `notes about ${s.question}` })),
134
+ answer: LLMNode({
135
+ model,
136
+ prompt: (s) => `Use these notes: ${s.raw}\nQuestion: ${s.question}`,
137
+ update: (s, text) => ({ ...s, final: text }),
138
+ }),
139
+ },
140
+ edges: [{ from: "fetch", to: "answer" }],
141
+ endNodes: ["answer"],
142
+ });
143
+
144
+ const { state, trace } = await graph.run({ question: "What is agent orchestration?" });
145
+ const jsonl = toJSONL(trace); // one event per line, ready for a file or an eval harness
146
+
147
+ // Replay with the answer node mocked. `fetch` reuses its recorded output.
148
+ const replay = await graph.replay(trace, {
149
+ overrides: { answer: CodeNode((s) => ({ ...s, final: "mock answer" })) },
150
+ });
151
+ console.log(diffTraces(trace, replay.trace)); // { equal: false, firstDivergence: { step: 1, ... }, changedKeys: ["final"] }
152
+ ```
153
+
154
+ State, input and node ids are all inferred from the schema and `nodes`. A typo in an edge, or a node that returns the wrong shape, is a compile error.
155
+
156
+ With TypeScript older than 5.9, a node that returns a literal value (for example `outcome: "ordered"` for a union field) is not inferred; write `CodeNode<State>(...)` there. TypeScript 5.9 and 7 need no annotation.
157
+
158
+ ## Concepts
159
+
160
+ ### State
161
+
162
+ One object, described by a schema. Every node receives the current state **deeply frozen** and returns a **new** state. The kernel validates every output against the schema and fails with an explicit error:
163
+
164
+ ```ts
165
+ error.code; // "INVALID_STATE"
166
+ error.message; // Node "answer" (step 1) returned invalid state:
167
+ // - final: Invalid input: expected string, received number
168
+ ```
169
+
170
+ State must be plain JSON (no `Date`, `Map`, class instances). That is what makes a trace loaded from disk replay exactly like one held in memory.
171
+
172
+ ### Node
173
+
174
+ ```ts
175
+ type Node<S> = (state: S, ctx: RunContext) => S | Promise<S>;
176
+
177
+ interface RunContext {
178
+ meta: { runId: string; nodeId: string; step: number; attempt: number; recovered: boolean };
179
+ signal: AbortSignal; // pass it to fetch / model clients
180
+ trace: { append(event: PluginEvent): void }; // record a side effect
181
+ interrupt<T>(request?: unknown): T; // pause the run until resume(trace, value)
182
+ }
183
+ ```
184
+
185
+ Any function with this signature is a node. The context deliberately contains no models, tools or stores; nodes bring their own dependencies.
186
+
187
+ ### Graph
188
+
189
+ Start node, plain edges, conditional edges, end nodes. That is all.
190
+
191
+ ```ts
192
+ conditionalEdges: [{ from: "search", route: (s) => (s.docs ? "answer" : "rewrite"), targets: ["answer", "rewrite"] }];
193
+ ```
194
+
195
+ The graph is checked when it is built: unknown nodes, dead ends, end nodes with outgoing edges and fan-out (two edges leaving one node) are rejected. Routers are pure and synchronous; if routing needs an LLM, do that in a node and route on its result. `maxSteps` (default 100) stops runaway loops.
196
+
197
+ ### Trace
198
+
199
+ An append-only list of frozen events:
200
+
201
+ ```
202
+ run_start → enter → [llm_call | tool_call | ...] → exit → enter → pause → run_end(paused)
203
+ → resume → enter → exit → ... → run_end
204
+ ```
205
+
206
+ `enter` carries the input state, `exit` the output state, so the stream doubles as a sequence of snapshots. Nodes add their own events with `ctx.trace.append`. Kernel event types are reserved.
207
+
208
+ `run(input, { onEvent })` hands every event to your sink before the run continues. If the sink throws, the run stops with `SINK_FAILED`, so no step runs without being logged. Full spec: [docs/trace-format.md](./docs/trace-format.md).
209
+
210
+ ### Pause and resume
211
+
212
+ A node calls `ctx.interrupt(request)` to wait for something from outside: a human approval, a button click, a webhook. The run returns `{ status: "paused", pending: { nodeId, step, request } }`. Store the trace anywhere, exit the process, and later:
213
+
214
+ ```ts
215
+ const result = await graph.resume(trace, value); // same runId, appended to the same trace
216
+ ```
217
+
218
+ On resume the waiting node runs again from the top and `ctx.interrupt` returns `value`; code before the call runs twice, so keep it free of side effects. The n-th `interrupt` in a node gets the n-th value, and each visit of a looping node gets its own values. **The trace is the checkpoint**: no database or checkpointer is involved. Resume a paused trace once; to reject stale answers (an old button clicked twice), compare `pending.step` with the latest trace you stored.
219
+
220
+ `resume(trace)` without a value also recovers a trace that ended mid-run, for example after a crash: it continues after the last finished step. If a `write` node was running at that moment, its outcome is unknown, so resume stops with `UNKNOWN_OUTCOME`. Check the outside system, then call `resume(trace, undefined, { allowWrites: true })`; the node sees `ctx.meta.recovered === true`.
221
+
222
+ ### Effects
223
+
224
+ ```ts
225
+ CodeNode(placeOrder, { effect: "write" });
226
+ ```
227
+
228
+ `write` marks a node whose call changes the outside world. It is recorded on `enter` events, and replay refuses to run it live (`WRITE_BLOCKED`) unless you override it with a mock or pass `allowWrites: true`. This also holds when you resume a replay that paused. Undeclared nodes count as `read`.
229
+
230
+ ### Replay
231
+
232
+ ```ts
233
+ graph.replay(trace, { overrides?, mode?: "recorded" | "live", allowWrites? })
234
+ ```
235
+
236
+ The run restarts from the recorded input under a new runId. In `recorded` mode (default), a node that is not overridden and sees exactly the recorded input state reuses its recorded output, with no side effects. As soon as the state diverges, nodes run live. `live` re-executes everything. Values delivered by `resume` are fed back to `ctx.interrupt` whenever a step sees the recorded state, so a human-in-the-loop conversation replays without anyone answering again. `write` nodes are blocked as described above. Use `diffTraces(a, b)` to find the first diverging step and the changed state keys.
237
+
238
+ Typical uses: swap a model and compare answers, mock a flaky tool, rerun a failed production trace locally after a fix, build regression evals from recorded traces.
239
+
240
+ ### Errors and retries
241
+
242
+ Every failure is a `TaugraphError` with a `code` (`INVALID_GRAPH`, `INVALID_STATE`, `INVALID_ROUTE`, `NODE_FAILED`, `MAX_STEPS`, `ABORTED`, `ASYNC_IN_SYNC_RUN`, `INVALID_TRACE`, `INVALID_EVENT`, `WRITE_BLOCKED`, `UNKNOWN_OUTCOME`, `NOT_RESUMABLE`, `SINK_FAILED`), plus `nodeId`, `step`, schema `issues`, the original `cause`, and the `trace` up to the failure. Nodes can opt into retries: `CodeNode(fn, { retry: { maxAttempts: 3 } })`. Each failed attempt is an `error` event.
243
+
244
+ ## Plugin nodes (`taugraph/nodes`)
245
+
246
+ | Node | What it does |
247
+ | ----------- | --------------------------------------------------------------------------------------------------------------- |
248
+ | `CodeNode` | Deterministic state transformation. |
249
+ | `LLMNode` | Calls an `LLMModel` (tools included), records an `llm_call` event, optionally parses JSON output with a schema. |
250
+ | `HumanNode` | Pauses for an answer via `ctx.interrupt`, validates it with a schema, asks again if invalid. |
251
+
252
+ `LLMNode` only defines the call contract (`{ id, complete(request, { signal }) }`); bring any other provider through a small adapter. [`taugraph/openai`](#openai-compatible-models-taugraphopenai) covers OpenAI-compatible endpoints. Messages can carry images; see [Images](#images).
253
+
254
+ Writing your own node type takes one call to `defineNode`:
255
+
256
+ ```ts
257
+ import { defineNode } from "taugraph";
258
+
259
+ interface Tool {
260
+ name: string;
261
+ run(input: unknown, signal: AbortSignal): Promise<unknown>;
262
+ }
263
+
264
+ export const ToolNode = <S>(tool: Tool, apply: (s: S, out: unknown) => S) =>
265
+ defineNode<S>(
266
+ async (state, ctx) => {
267
+ const output = await tool.run(state, ctx.signal);
268
+ ctx.trace.append({ type: "tool_call", input: { tool: tool.name }, output });
269
+ return apply(state, output);
270
+ },
271
+ { kind: "tool" },
272
+ );
273
+ ```
274
+
275
+ ## Agent (`taugraph/agent`)
276
+
277
+ `createAgent` turns the model ↔ tools loop into an ordinary taugraph graph. Each model call and each tool call is a step of its own, so everything above applies to every single call: it is in the trace, replay reuses it, a replay never repeats a write, a crash mid-write stops with `UNKNOWN_OUTCOME`, and a call can wait for a human.
278
+
279
+ ```ts
280
+ import { createAgent, tool } from "taugraph/agent";
281
+ import { z } from "zod";
282
+
283
+ const weather = tool({
284
+ name: "weather",
285
+ description: "Today's weather for a city",
286
+ input: z.object({ city: z.string() }), // validates arguments and becomes the JSON Schema the model sees
287
+ run: ({ city }) => `${city}: cloudy, -2~5°C`,
288
+ });
289
+
290
+ const addTodo = tool({
291
+ name: "add_todo",
292
+ effect: "write", // runs in a write step
293
+ input: z.object({ text: z.string() }),
294
+ run: ({ text }) => `added "${text}"`,
295
+ });
296
+
297
+ const agent = createAgent({
298
+ model, // any LLMModel whose adapter supports tools
299
+ tools: [weather, addTodo],
300
+ system: "You help with the day.",
301
+ approve: (call, t) => (t.effect === "write" ? "ask" : "run"),
302
+ });
303
+
304
+ const result = await agent.run({ messages: [{ role: "user", content: "What should I wear today?" }] });
305
+ // paused on add_todo: result.pending.request is { type: "tool_approval", call, effect: "write" }
306
+ const done = await agent.resume(result.trace, true); // or false, or { approved: false, reason }
307
+ console.log(done.state.final);
308
+ ```
309
+
310
+ ```
311
+ think ──a read call──▶ act ───────┐
312
+ ▲ ──a write call─▶ act_write ─┤ more calls: act / act_write
313
+ └───────────────────────────────┘ none left: think
314
+ think ──no calls, or maxRounds──▶ finish
315
+ ```
316
+
317
+ - The state is `{ messages, pending, rounds, final, stop }`, validated by a built-in Standard Schema (no validator needed).
318
+ - Tool definitions follow MCP (`name`, `description`, `inputSchema` as JSON Schema). A tool's JSON Schema comes from `inputSchema` if given, else from `input` through [Standard JSON Schema](https://standardschema.dev/json-schema) (Zod 4, Valibot, ArkType).
319
+ - Invalid arguments, unknown tools, unreadable arguments and thrown errors go back to the model as error results; the loop continues.
320
+ - `maxRounds` (default 8) bounds model calls; at most 32 calls run per reply. Each tool run is a `tool_call` event.
321
+ - Models: the call contract gained optional `tools`, `toolChoice` and `toolCalls`, and `tool` messages. An adapter that maps `role` itself needs a `tool` branch. The [OpenAI-compatible adapter](#openai-compatible-models-taugraphopenai) translates them. `pnpm example:agent` runs the whole thing. Tool results may carry images (see [Images](#images)).
322
+
323
+ ## OpenAI-compatible models (`taugraph/openai`)
324
+
325
+ `openAICompatible` turns any OpenAI-compatible `/chat/completions` endpoint into an `LLMModel`: OpenAI, DeepSeek, Qwen, Kimi, Ollama, vLLM, LM Studio and others. It translates tool calls, images and reasoning, uses the global `fetch`, and adds no dependencies. The kernel and `taugraph/nodes` contain no provider code; this entry is an optional plugin, like `taugraph/agent`.
326
+
327
+ ```ts
328
+ import { openAICompatible } from "taugraph/openai";
329
+
330
+ const model = openAICompatible({
331
+ baseURL: "https://api.deepseek.com",
332
+ model: "deepseek-flash",
333
+ apiKey: process.env.DEEPSEEK_API_KEY,
334
+ });
335
+ ```
336
+
337
+ | Option | What it does |
338
+ | ----------------- | ---------------------------------------------------------------------------------------------------- |
339
+ | `baseURL` | The part before `/chat/completions`, e.g. `https://api.openai.com/v1` or `http://localhost:11434/v1` |
340
+ | `model` | The model name the endpoint expects |
341
+ | `apiKey` | Optional; sent as a Bearer token |
342
+ | `resolveImage` | Reads image references such as `media:abc` when a request is sent; see [Images](#images) |
343
+ | `reasoningParams` | Maps a reasoning level to request parameters; see [Reasoning models](#reasoning-models) |
344
+ | `sendReasoning` | `false` stops sending the model's own reasoning back, for endpoints that refuse the field |
345
+ | `fetch` | Used instead of the global `fetch`, e.g. for a proxy, retries or tests |
346
+
347
+ The model's `id` is `openai-compatible:<model>`. It is recorded in every `llm_call` event, and assistant messages with that `model` count as this model's own when reasoning is sent back.
348
+
349
+ Any other provider fits the same contract through a small adapter of your own: an `LLMModel` is `{ id, complete(request, { signal }) }`.
350
+
351
+ ## Images
352
+
353
+ User messages and tool results can carry images. Their `content` is then an array of parts, in order; `system` and `assistant` messages stay text.
354
+
355
+ ```ts
356
+ const question: ChatMessage = {
357
+ role: "user",
358
+ content: [
359
+ { type: "text", text: "Which of these is the receipt?" },
360
+ { type: "image", data: base64, mimeType: "image/png" }, // the bytes, in base64
361
+ { type: "image", url: "media:9f2c" }, // or a reference the adapter reads when it calls the model
362
+ ],
363
+ };
364
+ ```
365
+
366
+ - A URL may be `https:`, `data:` or a reference of your own. The trace stores the state at every step and every request, so a base64 image is stored again and again, while a reference costs a few bytes. In `recorded` replay, a step that sees its recorded state reuses its recorded result, so a reference only has to resolve for steps that run again.
367
+ - Tools return images the same way: `run: () => ({ content: [{ type: "text", text: "the page" }, { type: "image", url: "media:shot1" }] })`.
368
+ - An MCP tool result can be returned as it is when it holds text and image blocks; other blocks, such as audio or resources, fail the run, so convert them first.
369
+ - For adapters, `resolveImages(messages, resolve)` turns `data:` URLs into base64 and every other URL into what `resolve` returns. An adapter that sends text only uses `textOf(m.content)`, which throws on images unless given `{ imagePlaceholder }`, so a model never answers about a picture it did not get.
370
+ - The [OpenAI-compatible adapter](#openai-compatible-models-taugraphopenai) sends http(s) and `data:` URLs as they are and reads the rest with `resolveImage`. OpenAI's tool messages take text only, so it moves tool images into a user message right after them.
371
+
372
+ ```ts
373
+ const model = openAICompatible({
374
+ baseURL: "https://api.openai.com/v1",
375
+ model: "gpt-4o-mini",
376
+ resolveImage: async (url) => {
377
+ const id = /^media:([\w-]+)$/.exec(url)?.[1];
378
+ if (!id) throw new Error(`Unknown image reference: ${url}`);
379
+ return { type: "image", mimeType: "image/png", data: (await readFile(`media/${id}.png`)).toString("base64") };
380
+ },
381
+ });
382
+ ```
383
+
384
+ ## Reasoning models
385
+
386
+ `reasoning` on a request says how much the model should think first: `"off"`, `"minimal"`, `"low"`, `"medium"`, `"high"`, `"xhigh"` or `"max"`. Leave it out and the adapter sends nothing, so the model uses its default. Adapters map the level to the provider's setting; one that knows the model's levels rounds to the nearest, and one for a provider that takes a token budget turns levels into budgets.
387
+
388
+ ```ts
389
+ const agent = createAgent({ model, tools, reasoning: "high" }); // every model call in the run
390
+ ```
391
+
392
+ - Replies carry what the model thought in `response.reasoning` (`{ text, signature?, redacted? }[]`) and its token count in `usage.reasoningTokens`, which is part of `outputTokens`. Both are in the `llm_call` event.
393
+ - Some providers refuse the next request of a tool loop unless the model's earlier thinking comes back unchanged: DeepSeek V4 (`reasoning_content`), Claude (signed thinking blocks) and Gemini 3 (a `thoughtSignature` on the first tool call of a step, kept in `ToolCall.signature`). The agent stores reasoning and signatures in the assistant messages it writes, so the next round sends them.
394
+ - A signature is only valid for the model that wrote it, so every assistant message the agent writes records `model`, the `LLMModel.id`. Adapters send reasoning and signatures back only when `m.model` is their own `id`, so a replay that swaps the model never sends one model's signatures to another.
395
+ - Assistant messages record `model`, so a replay that swaps the model diverges at the first model call that runs again, even if the new model answers the same; later steps run live and write steps stop with `WRITE_BLOCKED`.
396
+ - The [OpenAI-compatible adapter](#openai-compatible-models-taugraphopenai) sends the level as `reasoning_effort` as it is (`"off"` as `"none"`), reads `reasoning_content` or `reasoning` from replies, and sends its own `reasoning_content` back; set `sendReasoning: false` for endpoints that refuse that field, such as Groq and Cerebras. When a provider has its own switch, or refuses a level, map levels in `reasoningParams`:
397
+
398
+ ```ts
399
+ // DeepSeek V4: a thinking switch; it maps the levels itself
400
+ const deepseek = (level: ReasoningLevel) =>
401
+ level === "off" ? { thinking: { type: "disabled" } } : { thinking: { type: "enabled" }, reasoning_effort: level };
402
+ // Qwen on vLLM or SGLang
403
+ const qwen = (level: ReasoningLevel) => ({ chat_template_kwargs: { enable_thinking: level !== "off" } });
404
+
405
+ const model = openAICompatible({
406
+ baseURL: "https://api.deepseek.com",
407
+ model: "deepseek-flash",
408
+ reasoningParams: deepseek,
409
+ });
410
+ ```
411
+
412
+ ## Integrations
413
+
414
+ | Package | Use it to |
415
+ | ----------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
416
+ | [taugraph-mcp](https://github.com/wangcao-hub/taugraph-mcp) | Serve flows as MCP tools to any MCP client: Claude, Cursor, Kiro, AgentScope Java and others. `npx -y taugraph-mcp ./flows` |
417
+ | [taugraph-pi](https://github.com/wangcao-hub/taugraph-pi) | Run flows as tools inside the [Pi](https://pi.dev) coding agent. `pi install npm:taugraph-pi` |
418
+
419
+ Both keep the trace format, so runs recorded through them can be replayed and diffed with this package.
420
+
421
+ ## Not in the kernel, on purpose
422
+
423
+ Persistence backends, distributed workers, parallel nodes, nested subgraphs, built-in tools, memory, vector stores, visual editors, event routing, triggers and schedulers. Parallel calls inside one step are fine: use `Promise.all` in a node. Some will arrive as separate plugin packages; none will enter the kernel.
424
+
425
+ ## Roadmap
426
+
427
+ - `taugraph/tools`: shell and filesystem tool nodes
428
+ - `taugraph/subagent`: delegate to external agents (ACP, Pi instances)
429
+ - `taugraph/compact`: trace and state compaction
430
+ - `taugraph/tui`: terminal trace viewer
431
+
432
+ ## Development
433
+
434
+ ```
435
+ pnpm install
436
+ pnpm check # typecheck + lint + test
437
+ pnpm build
438
+ pnpm example:rag # retrieval -> answer with a retry loop, JSONL trace, replay
439
+ pnpm example:checkout # human in the loop: pause/resume, LLM picks a command, replay never re-orders
440
+ ```
441
+
442
+ Set `TAUGRAPH_BASE_URL` and `TAUGRAPH_MODEL` (and `TAUGRAPH_API_KEY` if needed) to run the examples against a real OpenAI-compatible endpoint, e.g. Ollama at `http://localhost:11434/v1`.
443
+
444
+ See [CONTRIBUTING.md](./CONTRIBUTING.md).
445
+
446
+ ## License
447
+
448
+ [MIT](./LICENSE)