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
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,234 @@
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
+ ## Where it sits
26
+
27
+ | | Pi | LangGraph | taugraph |
28
+ | ------------- | ------------------------------- | ----------------------------------------- | --------------------------------------------- |
29
+ | Kernel | single-agent loop (LLM ↔ tools) | stateful graph with channels and reducers | graph scheduler + typed state |
30
+ | Orchestration | extension | core | core |
31
+ | State | message transcript | channels, checkpoint per step | one schema-checked, frozen JSON object |
32
+ | Log | append-only session | checkpoints in a persistence backend | append-only event stream with state snapshots |
33
+ | LLM / tools | built in | bring your own, often LangChain | plugin nodes, none in the kernel |
34
+ | Runtime deps | provider SDKs | LangChain core and friends | **none** |
35
+
36
+ ## Rules of the kernel
37
+
38
+ 1. The kernel runs graphs, validates state and appends to the trace. It has **no LLM, no tools, no RAG, no memory**.
39
+ 2. State has a schema ([Standard Schema](https://standardschema.dev): Zod ≥ 3.24, Valibot ≥ 1, ArkType ≥ 2).
40
+ 3. The trace is append-only. Events are frozen and never edited.
41
+ 4. A run is a serializable trace. Replay it at any time, with any node or model swapped.
42
+ 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.
43
+ 6. Sync first, async optional. `runSync` never touches a Promise; no async runtime is assumed.
44
+ 7. Zero runtime dependencies. Works in Node ≥ 22, Bun, Deno and browsers.
45
+
46
+ These are enforced by tests (`test/architecture.test.ts`), not only by convention.
47
+
48
+ ## Quick start
49
+
50
+ ```ts
51
+ import { createGraph, diffTraces, toJSONL } from "taugraph";
52
+ import { CodeNode, LLMNode, type LLMModel } from "taugraph/nodes";
53
+ import { z } from "zod";
54
+
55
+ const State = z.object({
56
+ question: z.string(),
57
+ raw: z.string().nullable().default(null),
58
+ final: z.string().nullable().default(null),
59
+ });
60
+
61
+ // Any provider fits this contract. See examples/adapters/openai-compatible.ts.
62
+ const model: LLMModel = { id: "mock:echo", complete: (req) => ({ content: `echo: ${req.messages.at(-1)?.content}` }) };
63
+
64
+ const graph = createGraph(State, {
65
+ start: "fetch",
66
+ nodes: {
67
+ fetch: CodeNode((s) => ({ ...s, raw: `notes about ${s.question}` })),
68
+ answer: LLMNode({
69
+ model,
70
+ prompt: (s) => `Use these notes: ${s.raw}\nQuestion: ${s.question}`,
71
+ update: (s, text) => ({ ...s, final: text }),
72
+ }),
73
+ },
74
+ edges: [{ from: "fetch", to: "answer" }],
75
+ endNodes: ["answer"],
76
+ });
77
+
78
+ const { state, trace } = await graph.run({ question: "What is agent orchestration?" });
79
+ const jsonl = toJSONL(trace); // one event per line, ready for a file or an eval harness
80
+
81
+ // Replay with the answer node mocked. `fetch` reuses its recorded output.
82
+ const replay = await graph.replay(trace, {
83
+ overrides: { answer: CodeNode((s) => ({ ...s, final: "mock answer" })) },
84
+ });
85
+ console.log(diffTraces(trace, replay.trace)); // { equal: false, firstDivergence: { step: 1, ... }, changedKeys: ["final"] }
86
+ ```
87
+
88
+ 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.
89
+
90
+ ## Concepts
91
+
92
+ ### State
93
+
94
+ 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:
95
+
96
+ ```ts
97
+ error.code; // "INVALID_STATE"
98
+ error.message; // Node "answer" (step 1) returned invalid state:
99
+ // - final: Invalid input: expected string, received number
100
+ ```
101
+
102
+ 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.
103
+
104
+ ### Node
105
+
106
+ ```ts
107
+ type Node<S> = (state: S, ctx: RunContext) => S | Promise<S>;
108
+
109
+ interface RunContext {
110
+ meta: { runId: string; nodeId: string; step: number; attempt: number; recovered: boolean };
111
+ signal: AbortSignal; // pass it to fetch / model clients
112
+ trace: { append(event: PluginEvent): void }; // record a side effect
113
+ interrupt<T>(request?: unknown): T; // pause the run until resume(trace, value)
114
+ }
115
+ ```
116
+
117
+ Any function with this signature is a node. The context deliberately contains no models, tools or stores; nodes bring their own dependencies.
118
+
119
+ ### Graph
120
+
121
+ Start node, plain edges, conditional edges, end nodes. That is all.
122
+
123
+ ```ts
124
+ conditionalEdges: [{ from: "search", route: (s) => (s.docs ? "answer" : "rewrite"), targets: ["answer", "rewrite"] }];
125
+ ```
126
+
127
+ 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.
128
+
129
+ ### Trace
130
+
131
+ An append-only list of frozen events:
132
+
133
+ ```
134
+ run_start → enter → [llm_call | tool_call | ...] → exit → enter → pause → run_end(paused)
135
+ → resume → enter → exit → ... → run_end
136
+ ```
137
+
138
+ `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.
139
+
140
+ `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).
141
+
142
+ ### Pause and resume
143
+
144
+ 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:
145
+
146
+ ```ts
147
+ const result = await graph.resume(trace, value); // same runId, appended to the same trace
148
+ ```
149
+
150
+ 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.
151
+
152
+ `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`.
153
+
154
+ ### Effects
155
+
156
+ ```ts
157
+ CodeNode(placeOrder, { effect: "write" });
158
+ ```
159
+
160
+ `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`.
161
+
162
+ ### Replay
163
+
164
+ ```ts
165
+ graph.replay(trace, { overrides?, mode?: "recorded" | "live", allowWrites? })
166
+ ```
167
+
168
+ 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.
169
+
170
+ 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.
171
+
172
+ ### Errors and retries
173
+
174
+ 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.
175
+
176
+ ## Plugin nodes (`taugraph/nodes`)
177
+
178
+ | Node | What it does |
179
+ | ----------- | ---------------------------------------------------------------------------------------------- |
180
+ | `CodeNode` | Deterministic state transformation. |
181
+ | `LLMNode` | Calls an `LLMModel`, records an `llm_call` event, optionally parses JSON output with a schema. |
182
+ | `HumanNode` | Pauses for an answer via `ctx.interrupt`, validates it with a schema, asks again if invalid. |
183
+
184
+ `LLMNode` only defines the call contract (`{ id, complete(request, { signal }) }`); bring OpenAI, Ollama or anything else through a small adapter. A 40-line OpenAI-compatible one is in [`examples/adapters`](./examples/adapters/openai-compatible.ts).
185
+
186
+ Writing your own node type takes one call to `defineNode`:
187
+
188
+ ```ts
189
+ import { defineNode } from "taugraph";
190
+
191
+ interface Tool {
192
+ name: string;
193
+ run(input: unknown, signal: AbortSignal): Promise<unknown>;
194
+ }
195
+
196
+ export const ToolNode = <S>(tool: Tool, apply: (s: S, out: unknown) => S) =>
197
+ defineNode<S>(
198
+ async (state, ctx) => {
199
+ const output = await tool.run(state, ctx.signal);
200
+ ctx.trace.append({ type: "tool_call", input: { tool: tool.name }, output });
201
+ return apply(state, output);
202
+ },
203
+ { kind: "tool" },
204
+ );
205
+ ```
206
+
207
+ ## Not in the kernel, on purpose
208
+
209
+ 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.
210
+
211
+ ## Roadmap
212
+
213
+ - `taugraph/tools`: shell and filesystem tool nodes
214
+ - `taugraph/subagent`: delegate to external agents (ACP, Pi instances)
215
+ - `taugraph/compact`: trace and state compaction
216
+ - `taugraph/tui`: terminal trace viewer
217
+
218
+ ## Development
219
+
220
+ ```
221
+ pnpm install
222
+ pnpm check # typecheck + lint + test
223
+ pnpm build
224
+ pnpm example:rag # retrieval -> answer with a retry loop, JSONL trace, replay
225
+ pnpm example:checkout # human in the loop: pause/resume, LLM picks a command, replay never re-orders
226
+ ```
227
+
228
+ 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`.
229
+
230
+ See [CONTRIBUTING.md](./CONTRIBUTING.md).
231
+
232
+ ## License
233
+
234
+ [MIT](./LICENSE)
@@ -0,0 +1,234 @@
1
+ # taugraph (τ)
2
+
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
+ **最小的带类型状态的 Agent 图编排底座(Minimal typed agent graph harness)。**
6
+
7
+ > Pi 是循环,τ 是轨迹。
8
+
9
+ 一个很小的内核:在一个经过 schema 校验、不可变的状态上运行节点图,并把每一步写进只追加、可回放的 transcript。LLM 调用、工具、子 Agent、人工审批都是插件节点,内核对它们一无所知。
10
+
11
+ [English](./README.md) · [设计说明](./docs/design.md) · [Trace 格式](./docs/trace-format.md)
12
+
13
+ ```
14
+ npm install taugraph zod # 也可以用任何 Standard Schema 库:valibot、arktype ...
15
+ ```
16
+
17
+ ## 为什么叫 τ
18
+
19
+ 在强化学习里,τ 是"轨迹"(trajectory)的标准符号,指 Agent 依次经历的状态和动作序列。taugraph 的一次运行正是这样一条轨迹:在图中走过的路径,每一步都带状态快照,并完整记录下来以便回放。这个名字也是向 [Pi](https://pi.dev) 致意:taugraph 沿用了它极简、只追加的设计(顺便一提,τ = 2π)。
20
+
21
+ ## 为什么把流程写进代码
22
+
23
+ 如果每一步都由模型决定,且每步正确率是 95%,三步流程全程不出错的概率约 86%,五步约 77%。提示词优化能把 95% 提到 97%,但到不了 100%。taugraph 把能事先写清楚的事(下一步跑什么、什么时候停下来问人、哪些调用会改变外部世界)从模型手里拿出来,放进类型化的图;模型只做只有它能做的事,比如理解一句回复、从几个允许的命令里选一个。
24
+
25
+ ## 定位
26
+
27
+ | | Pi | LangGraph | taugraph |
28
+ | ---------- | ------------------------------- | ----------------------------- | ------------------------------------ |
29
+ | 内核 | 单 Agent 思考循环(LLM ↔ 工具) | 带 channel / reducer 的状态图 | 图调度 + 类型化状态 |
30
+ | 编排 | 扩展 | 内核 | 内核 |
31
+ | 状态 | 消息 transcript | channel,每步一个 checkpoint | 一个经 schema 校验、冻结的 JSON 对象 |
32
+ | 日志 | 只追加的 session | 持久化后端里的 checkpoint | 只追加的事件流,附带状态快照 |
33
+ | LLM / 工具 | 内置 | 自带,常用 LangChain | 插件节点,内核里没有 |
34
+ | 运行时依赖 | 各家模型 SDK | LangChain core 等 | **无** |
35
+
36
+ ## 内核戒律
37
+
38
+ 1. 内核只做三件事:跑图、校验状态、追加日志。**不内置 LLM、工具、RAG、记忆**。
39
+ 2. 状态必须有 schema([Standard Schema](https://standardschema.dev):Zod ≥ 3.24、Valibot ≥ 1、ArkType ≥ 2)。
40
+ 3. 日志只追加,事件冻结,永不原地修改。
41
+ 4. 一次执行就是一条可序列化的 trace,随时 replay,可替换任意节点或模型。
42
+ 5. 没有隐式魔法:副作用都以显式事件记录;会改变外部世界的节点声明 `effect: "write"`,回放永远不会重复执行它。
43
+ 6. 同步优先,异步可选。`runSync` 全程不碰 Promise,内核不绑定任何异步运行时。
44
+ 7. 零运行时依赖。支持 Node ≥ 22、Bun、Deno 和浏览器。
45
+
46
+ 这些规则由测试(`test/architecture.test.ts`)强制执行,不只是约定。
47
+
48
+ ## 快速开始
49
+
50
+ ```ts
51
+ import { createGraph, diffTraces, toJSONL } from "taugraph";
52
+ import { CodeNode, LLMNode, type LLMModel } from "taugraph/nodes";
53
+ import { z } from "zod";
54
+
55
+ const State = z.object({
56
+ question: z.string(),
57
+ raw: z.string().nullable().default(null),
58
+ final: z.string().nullable().default(null),
59
+ });
60
+
61
+ // 任何模型提供方都能适配这个契约,参见 examples/adapters/openai-compatible.ts
62
+ const model: LLMModel = { id: "mock:echo", complete: (req) => ({ content: `echo: ${req.messages.at(-1)?.content}` }) };
63
+
64
+ const graph = createGraph(State, {
65
+ start: "fetch",
66
+ nodes: {
67
+ fetch: CodeNode((s) => ({ ...s, raw: `关于 ${s.question} 的参考信息` })),
68
+ answer: LLMNode({
69
+ model,
70
+ prompt: (s) => `参考:${s.raw}\n问题:${s.question}`,
71
+ update: (s, text) => ({ ...s, final: text }),
72
+ }),
73
+ },
74
+ edges: [{ from: "fetch", to: "answer" }],
75
+ endNodes: ["answer"],
76
+ });
77
+
78
+ const { state, trace } = await graph.run({ question: "什么是 Agent 编排" });
79
+ const jsonl = toJSONL(trace); // 每行一个事件,可直接落盘或喂给评测
80
+
81
+ // 回放:answer 换成 mock,fetch 复用录制的输出,不会重新执行
82
+ const replay = await graph.replay(trace, {
83
+ overrides: { answer: CodeNode((s) => ({ ...s, final: "mock答案" })) },
84
+ });
85
+ console.log(diffTraces(trace, replay.trace)); // { equal: false, firstDivergence: { step: 1, ... }, changedKeys: ["final"] }
86
+ ```
87
+
88
+ 状态类型、输入类型、节点 id 全部从 schema 和 `nodes` 推断。边里写错节点名、节点返回结构不对,都是编译错误。
89
+
90
+ ## 核心概念
91
+
92
+ ### State
93
+
94
+ 一个对象,由 schema 描述。每个节点拿到的是**深度冻结**的当前状态,返回一个**新**状态。内核校验每次输出,失败时给出明确错误:
95
+
96
+ ```ts
97
+ error.code; // "INVALID_STATE"
98
+ error.message; // Node "answer" (step 1) returned invalid state:
99
+ // - final: Invalid input: expected string, received number
100
+ ```
101
+
102
+ 状态必须是纯 JSON(不能有 `Date`、`Map`、类实例)。正因如此,从磁盘加载的 trace 和内存中的 trace 回放结果完全一致。
103
+
104
+ ### Node
105
+
106
+ ```ts
107
+ type Node<S> = (state: S, ctx: RunContext) => S | Promise<S>;
108
+
109
+ interface RunContext {
110
+ meta: { runId: string; nodeId: string; step: number; attempt: number; recovered: boolean };
111
+ signal: AbortSignal; // 传给 fetch / 模型客户端
112
+ trace: { append(event: PluginEvent): void }; // 记录一次副作用
113
+ interrupt<T>(request?: unknown): T; // 暂停运行,直到 resume(trace, value)
114
+ }
115
+ ```
116
+
117
+ 任何符合这个签名的函数都是节点。ctx 里刻意不放模型、工具、向量库,这些由节点自己注入。
118
+
119
+ ### Graph
120
+
121
+ 起始节点、普通边、条件边、终止节点,仅此而已。
122
+
123
+ ```ts
124
+ conditionalEdges: [{ from: "search", route: (s) => (s.docs ? "answer" : "rewrite"), targets: ["answer", "rewrite"] }];
125
+ ```
126
+
127
+ 图在构建时就做静态检查:未知节点、死胡同、带出边的终止节点、扇出(一个节点两条出边)都会被拒绝。路由函数必须是纯同步函数;如果路由需要 LLM 判断,就在节点里做,把结果写进状态再路由。`maxSteps`(默认 100)防止死循环。
128
+
129
+ ### Trace
130
+
131
+ 只追加的冻结事件列表:
132
+
133
+ ```
134
+ run_start → enter → [llm_call | tool_call | ...] → exit → enter → pause → run_end(paused)
135
+ → resume → enter → exit → ... → run_end
136
+ ```
137
+
138
+ `enter` 携带输入状态,`exit` 携带输出状态,所以事件流同时也是快照序列(兼顾 Pi 的事件流和 LangGraph 的 snapshot)。节点用 `ctx.trace.append` 追加自己的事件,内核事件类型是保留的。
139
+
140
+ `run(input, { onEvent })` 会在运行继续之前把每个事件交给你的 sink。sink 抛错时运行以 `SINK_FAILED` 停止,保证没有哪一步是在没写日志的情况下执行的。完整格式见 [docs/trace-format.md](./docs/trace-format.md)。
141
+
142
+ ### 暂停与恢复
143
+
144
+ 节点调用 `ctx.interrupt(request)` 等待外部输入:人工确认、按钮点击、webhook 回调。运行返回 `{ status: "paused", pending: { nodeId, step, request } }`。trace 存到哪里都行,进程可以退出,之后:
145
+
146
+ ```ts
147
+ const result = await graph.resume(trace, value); // 同一个 runId,追加到同一条 trace
148
+ ```
149
+
150
+ 恢复时,等待中的节点从头再跑一次,`ctx.interrupt` 返回 `value`;调用之前的代码会执行两次,所以那部分不要有副作用。一个节点里第 n 次 `interrupt` 拿到第 n 个值;循环中多次经过同一个节点,每次都有各自的值。**trace 本身就是 checkpoint**,不需要数据库或 checkpointer。一条暂停的 trace 只恢复一次;要拦住过期的回答(比如旧按钮被点了两次),拿 `pending.step` 和你存的最新 trace 对比。
151
+
152
+ 不带值调用 `resume(trace)` 还能恢复中途中断的 trace(比如进程崩溃):从最后一个完成的步骤继续。如果中断时正在执行 `write` 节点,它的结果未知,resume 会以 `UNKNOWN_OUTCOME` 停下。先去外部系统查证,再调用 `resume(trace, undefined, { allowWrites: true })`,节点会看到 `ctx.meta.recovered === true`。
153
+
154
+ ### 副作用声明
155
+
156
+ ```ts
157
+ CodeNode(placeOrder, { effect: "write" });
158
+ ```
159
+
160
+ `write` 标记调用会改变外部世界的节点。它会记录在 `enter` 事件里;回放时内核拒绝实际执行它(`WRITE_BLOCKED`),除非用 mock 覆盖它,或者显式传 `allowWrites: true`。恢复一条停在半路的回放 trace 时同样如此。没声明的节点按 `read` 处理。
161
+
162
+ ### Replay
163
+
164
+ ```ts
165
+ graph.replay(trace, { overrides?, mode?: "recorded" | "live", allowWrites? })
166
+ ```
167
+
168
+ 以新的 runId 从录制的输入重新开始。`recorded` 模式(默认)下,未被覆盖、且收到的输入状态与录制完全一致的节点直接复用录制输出,没有副作用;一旦状态出现分歧,后续节点实时执行。`live` 模式全部重跑。只要某一步看到的状态和录制时一致,通过 `resume` 送进来的值会再次交给 `ctx.interrupt`,所以带人工交互的对话回放时不需要有人再回答一遍。`write` 节点按上一节的规则拦截。`diffTraces(a, b)` 给出第一个分歧步骤和变化的状态字段。
169
+
170
+ 典型用途:换模型对比回答、mock 不稳定的工具、修复后在本地重跑失败的线上 trace、用录制的 trace 做回归评测(如 τ²-bench 一类基准)。
171
+
172
+ ### 错误与重试
173
+
174
+ 所有失败都是 `TaugraphError`,带 `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`),以及 `nodeId`、`step`、schema `issues`、原始 `cause`,还有截至失败时的 `trace`。节点可以声明重试:`CodeNode(fn, { retry: { maxAttempts: 3 } })`,每次失败都记录为一条 `error` 事件。
175
+
176
+ ## 插件节点(`taugraph/nodes`)
177
+
178
+ | 节点 | 作用 |
179
+ | ----------- | ------------------------------------------------------------------------- |
180
+ | `CodeNode` | 确定性的状态转换 |
181
+ | `LLMNode` | 调用 `LLMModel`,记录 `llm_call` 事件,可选用 schema 解析 JSON 结构化输出 |
182
+ | `HumanNode` | 通过 `ctx.interrupt` 暂停等待回答,用 schema 校验,不合法就再问一次 |
183
+
184
+ `LLMNode` 只定义调用契约(`{ id, complete(request, { signal }) }`),OpenAI、Ollama 等通过小适配器接入。[`examples/adapters`](./examples/adapters/openai-compatible.ts) 里有一个 40 行的 OpenAI 兼容适配器。
185
+
186
+ 自定义节点类型只需要一次 `defineNode`:
187
+
188
+ ```ts
189
+ import { defineNode } from "taugraph";
190
+
191
+ interface Tool {
192
+ name: string;
193
+ run(input: unknown, signal: AbortSignal): Promise<unknown>;
194
+ }
195
+
196
+ export const ToolNode = <S>(tool: Tool, apply: (s: S, out: unknown) => S) =>
197
+ defineNode<S>(
198
+ async (state, ctx) => {
199
+ const output = await tool.run(state, ctx.signal);
200
+ ctx.trace.append({ type: "tool_call", input: { tool: tool.name }, output });
201
+ return apply(state, output);
202
+ },
203
+ { kind: "tool" },
204
+ );
205
+ ```
206
+
207
+ ## 内核刻意不做
208
+
209
+ 持久化后端、分布式 worker、并行节点、嵌套子图、内置工具、记忆、向量库、可视化画布、事件路由、触发器和调度器。同一步里的并发调用没问题:在节点里用 `Promise.all`。其中一部分会以独立插件包出现,但都不会进入内核。
210
+
211
+ ## 路线图
212
+
213
+ - `taugraph/tools`:shell、文件系统等工具节点
214
+ - `taugraph/subagent`:委派外部 Agent(ACP、Pi 实例)
215
+ - `taugraph/compact`:trace 与状态压缩
216
+ - `taugraph/tui`:终端 trace 查看器
217
+
218
+ ## 开发
219
+
220
+ ```
221
+ pnpm install
222
+ pnpm check # 类型检查 + lint + 测试
223
+ pnpm build
224
+ pnpm example:rag # 检索 → 回答,带重试分支、JSONL trace 和回放
225
+ pnpm example:checkout # 人工交互:暂停/恢复、LLM 只选命令、回放不会重复下单
226
+ ```
227
+
228
+ 设置 `TAUGRAPH_BASE_URL`、`TAUGRAPH_MODEL`(需要时加 `TAUGRAPH_API_KEY`)即可让示例连接真实的 OpenAI 兼容接口,例如 Ollama:`http://localhost:11434/v1`。
229
+
230
+ 参见 [CONTRIBUTING.md](./CONTRIBUTING.md)。
231
+
232
+ ## 许可证
233
+
234
+ [MIT](./LICENSE)
@@ -0,0 +1,51 @@
1
+ import type { StandardSchemaV1 } from "./standard-schema.js";
2
+ import { type RecordedAnswers, type RecordedStep, type ResumePoint } from "./trace.js";
3
+ import type { Node, ReplayMode, RunOptions, RunResult, Trace } from "./types.js";
4
+ export declare const DEFAULT_MAX_STEPS = 100;
5
+ export type Outgoing<S> = {
6
+ readonly kind: "edge";
7
+ readonly to: string;
8
+ } | {
9
+ readonly kind: "route";
10
+ readonly route: (state: S) => string;
11
+ readonly targets?: ReadonlySet<string>;
12
+ };
13
+ export interface CompiledGraph<S> {
14
+ readonly schema: StandardSchemaV1<unknown, S>;
15
+ readonly start: string;
16
+ readonly nodes: Readonly<Record<string, Node<S>>>;
17
+ readonly outgoing: ReadonlyMap<string, Outgoing<S>>;
18
+ readonly endNodes: ReadonlySet<string>;
19
+ }
20
+ export interface ReplayPlan<S> {
21
+ readonly sourceRunId: string;
22
+ readonly mode: ReplayMode;
23
+ readonly overrides: Readonly<Record<string, Node<S> | undefined>>;
24
+ readonly recorded: ReadonlyMap<number, RecordedStep>;
25
+ readonly answers: ReadonlyMap<number, RecordedAnswers>;
26
+ readonly allowWrites: boolean;
27
+ }
28
+ /** Checked by `graph.resume` before anything is appended. */
29
+ export interface ResumePlan {
30
+ readonly trace: Trace;
31
+ readonly point: ResumePoint;
32
+ /** Frozen JSON value for a paused step, otherwise undefined. */
33
+ readonly value: unknown;
34
+ /** The trace is a replay and the caller did not pass allowWrites: keep blocking writes. */
35
+ readonly blockWrites: boolean;
36
+ }
37
+ export interface ExecuteParams<S> {
38
+ readonly graph: CompiledGraph<S>;
39
+ readonly options: RunOptions;
40
+ /** Raw run input. Ignored when resuming. */
41
+ readonly input?: unknown;
42
+ readonly replay?: ReplayPlan<S>;
43
+ readonly resume?: ResumePlan;
44
+ }
45
+ type Effects<T> = Generator<unknown, T, unknown>;
46
+ export declare function execute<S>(params: ExecuteParams<S>): Effects<RunResult<S>>;
47
+ export declare function toJson<T>(value: T, message: string, nodeId?: string, step?: number): T;
48
+ export declare function driveSync<T>(effects: Effects<T>): T;
49
+ export declare function driveAsync<T>(effects: Effects<T>, signal?: AbortSignal): Promise<T>;
50
+ export {};
51
+ //# sourceMappingURL=engine.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"engine.d.ts","sourceRoot":"","sources":["../../src/core/engine.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAC7D,OAAO,EAGL,KAAK,eAAe,EACpB,KAAK,YAAY,EACjB,KAAK,WAAW,EAKjB,MAAM,YAAY,CAAC;AACpB,OAAO,KAAK,EAAE,IAAI,EAAe,UAAU,EAAc,UAAU,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAG1G,eAAO,MAAM,iBAAiB,MAAM,CAAC;AAErC,MAAM,MAAM,QAAQ,CAAC,CAAC,IAClB;IAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAA;CAAE,GAC9C;IAAE,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC;IAAC,QAAQ,CAAC,KAAK,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,MAAM,CAAC;IAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,WAAW,CAAC,MAAM,CAAC,CAAA;CAAE,CAAC;AAE7G,MAAM,WAAW,aAAa,CAAC,CAAC;IAC9B,QAAQ,CAAC,MAAM,EAAE,gBAAgB,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;IAC9C,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,KAAK,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAClD,QAAQ,CAAC,QAAQ,EAAE,WAAW,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC;IACpD,QAAQ,CAAC,QAAQ,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;CACxC;AAED,MAAM,WAAW,UAAU,CAAC,CAAC;IAC3B,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,IAAI,EAAE,UAAU,CAAC;IAC1B,QAAQ,CAAC,SAAS,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC,GAAG,SAAS,CAAC,CAAC,CAAC;IAClE,QAAQ,CAAC,QAAQ,EAAE,WAAW,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;IACrD,QAAQ,CAAC,OAAO,EAAE,WAAW,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC;IACvD,QAAQ,CAAC,WAAW,EAAE,OAAO,CAAC;CAC/B;AAED,6DAA6D;AAC7D,MAAM,WAAW,UAAU;IACzB,QAAQ,CAAC,KAAK,EAAE,KAAK,CAAC;IACtB,QAAQ,CAAC,KAAK,EAAE,WAAW,CAAC;IAC5B,gEAAgE;IAChE,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC;IACxB,2FAA2F;IAC3F,QAAQ,CAAC,WAAW,EAAE,OAAO,CAAC;CAC/B;AAED,MAAM,WAAW,aAAa,CAAC,CAAC;IAC9B,QAAQ,CAAC,KAAK,EAAE,aAAa,CAAC,CAAC,CAAC,CAAC;IACjC,QAAQ,CAAC,OAAO,EAAE,UAAU,CAAC;IAC7B,4CAA4C;IAC5C,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC;IACzB,QAAQ,CAAC,MAAM,CAAC,EAAE,UAAU,CAAC,CAAC,CAAC,CAAC;IAChC,QAAQ,CAAC,MAAM,CAAC,EAAE,UAAU,CAAC;CAC9B;AAED,KAAK,OAAO,CAAC,CAAC,IAAI,SAAS,CAAC,OAAO,EAAE,CAAC,EAAE,OAAO,CAAC,CAAC;AA6BjD,wBAAiB,OAAO,CAAC,CAAC,EAAE,MAAM,EAAE,aAAa,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAsE3E;AAkSD,wBAAgB,MAAM,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,CAAC,CAOtF;AAyCD,wBAAgB,SAAS,CAAC,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,CAanD;AAED,wBAAsB,UAAU,CAAC,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,CAAC,CAAC,CAazF"}