taugraph 0.2.0 → 0.4.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.
- package/CHANGELOG.md +89 -0
- package/README.md +283 -22
- package/README.zh-CN.md +283 -22
- package/dist/agent/index.d.ts +74 -0
- package/dist/agent/index.d.ts.map +1 -0
- package/dist/agent/index.js +254 -0
- package/dist/agent/index.js.map +1 -0
- package/dist/agent/state.d.ts +30 -0
- package/dist/agent/state.d.ts.map +1 -0
- package/dist/agent/state.js +135 -0
- package/dist/agent/state.js.map +1 -0
- package/dist/agent/util.d.ts +19 -0
- package/dist/agent/util.d.ts.map +1 -0
- package/dist/agent/util.js +59 -0
- package/dist/agent/util.js.map +1 -0
- package/dist/core/engine.d.ts +1 -1
- package/dist/core/engine.d.ts.map +1 -1
- package/dist/core/engine.js +237 -35
- package/dist/core/engine.js.map +1 -1
- package/dist/core/errors.d.ts +2 -0
- package/dist/core/errors.d.ts.map +1 -1
- package/dist/core/errors.js.map +1 -1
- package/dist/core/graph.d.ts.map +1 -1
- package/dist/core/graph.js +9 -1
- package/dist/core/graph.js.map +1 -1
- package/dist/core/node.d.ts +6 -1
- package/dist/core/node.d.ts.map +1 -1
- package/dist/core/node.js +55 -6
- package/dist/core/node.js.map +1 -1
- package/dist/core/patch.d.ts +26 -0
- package/dist/core/patch.d.ts.map +1 -0
- package/dist/core/patch.js +192 -0
- package/dist/core/patch.js.map +1 -0
- package/dist/core/retry.d.ts +20 -0
- package/dist/core/retry.d.ts.map +1 -0
- package/dist/core/retry.js +79 -0
- package/dist/core/retry.js.map +1 -0
- package/dist/core/trace.d.ts +39 -8
- package/dist/core/trace.d.ts.map +1 -1
- package/dist/core/trace.js +222 -29
- package/dist/core/trace.js.map +1 -1
- package/dist/core/types.d.ts +35 -4
- package/dist/core/types.d.ts.map +1 -1
- package/dist/core/util.d.ts +5 -1
- package/dist/core/util.d.ts.map +1 -1
- package/dist/core/util.js +41 -9
- package/dist/core/util.js.map +1 -1
- package/dist/file/index.d.ts +26 -0
- package/dist/file/index.d.ts.map +1 -0
- package/dist/file/index.js +373 -0
- package/dist/file/index.js.map +1 -0
- package/dist/index.d.ts +4 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/nodes/code.d.ts +5 -0
- package/dist/nodes/code.d.ts.map +1 -1
- package/dist/nodes/code.js.map +1 -1
- package/dist/nodes/content.d.ts +18 -0
- package/dist/nodes/content.d.ts.map +1 -0
- package/dist/nodes/content.js +88 -0
- package/dist/nodes/content.js.map +1 -0
- package/dist/nodes/index.d.ts +2 -1
- package/dist/nodes/index.d.ts.map +1 -1
- package/dist/nodes/index.js +1 -0
- package/dist/nodes/index.js.map +1 -1
- package/dist/nodes/llm.d.ts +100 -4
- package/dist/nodes/llm.d.ts.map +1 -1
- package/dist/nodes/llm.js +5 -1
- package/dist/nodes/llm.js.map +1 -1
- package/dist/openai/index.d.ts +55 -0
- package/dist/openai/index.d.ts.map +1 -0
- package/dist/openai/index.js +208 -0
- package/dist/openai/index.js.map +1 -0
- package/package.json +20 -4
- package/src/agent/index.ts +359 -0
- package/src/agent/state.ts +147 -0
- package/src/agent/util.ts +74 -0
- package/src/core/engine.ts +241 -34
- package/src/core/errors.ts +2 -0
- package/src/core/graph.ts +7 -1
- package/src/core/node.ts +55 -6
- package/src/core/patch.ts +173 -0
- package/src/core/retry.ts +89 -0
- package/src/core/trace.ts +222 -29
- package/src/core/types.ts +37 -4
- package/src/core/util.ts +43 -10
- package/src/file/index.ts +408 -0
- package/src/index.ts +5 -1
- package/src/nodes/code.ts +5 -0
- package/src/nodes/content.ts +100 -0
- package/src/nodes/index.ts +10 -0
- package/src/nodes/llm.ts +109 -7
- package/src/openai/index.ts +286 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
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.4.0] - 2026-11-26
|
|
8
|
+
|
|
9
|
+
Traces grow linearly instead of with the square of the run, in memory and in JSONL (format version 2), and `taugraph/file` stores them as crash-safe files that a restarted process can continue. Retries now wait and skip errors that cannot heal, nodes and tools can time out, and `onEvent` can be async.
|
|
10
|
+
|
|
11
|
+
### Changed
|
|
12
|
+
|
|
13
|
+
- **Breaking:** trace format version 2: `toJSONL` writes each `input` / `output` as a JSON Patch against a base value when the patch is under 4096 characters or not longer than the value, so traces grow with what changed instead of with the square of the run. That holds for items appended to arrays and for changes to object keys; inserting at the front of a long array or reordering an object's keys still rewrites that array or object. `fromJSONL`, `resume` and `replay` read versions 1 and 2. In memory, events keep their shape, and consecutive states share the parts that did not change. taugraph 0.3 and older reject version 2 files. Code that parses `toJSONL` or `fileStore` lines itself now meets `inputPatch` / `outputPatch` instead of `input` / `output`, so read them with `fromJSONL` from 0.4. Custom sinks now see `run_start.meta.version` 2, which taugraph 0.3 rejects, so even files they write in full no longer load there.
|
|
14
|
+
- **Breaking:** retries wait between attempts: exponential backoff from 500 ms, doubling up to 30 s, minus up to half at random, or at least the error's `retryAfterMs`. Pass `backoff: false` for the old immediate retries. `runSync` blocks the thread for the wait, and fails with `ASYNC_IN_SYNC_RUN` where it may not block.
|
|
15
|
+
- **Breaking:** errors that another attempt cannot fix are no longer retried: HTTP 4xx other than 408, 409, 425 and 429 (a numeric `status` on the error or its `cause` chain), and the codes `INVALID_STATE`, `INVALID_ROUTE`, `WRITE_BLOCKED`, `UNKNOWN_OUTCOME` and `NOT_RESUMABLE`. A node that returns invalid state now fails at once; pass `retryOn` to keep retrying it.
|
|
16
|
+
- **Breaking:** a `write` node with `retry` must set `retry.idempotent: true`. Otherwise `defineNode` throws a `TypeError`, and `createGraph` an `INVALID_GRAPH` error for nodes built without `defineNode`.
|
|
17
|
+
- **Breaking:** a sink that returns a Promise is now awaited: `run` waits for it, a rejection stops the run with `SINK_FAILED`, and `runSync` refuses it with `ASYNC_IN_SYNC_RUN`. In 0.3 the Promise was ignored. To keep a fire-and-forget sink, do not return the Promise (`(e) => { void store.write(e); }`).
|
|
18
|
+
- `toJSONL([])` returns `""` (was `"\n"`).
|
|
19
|
+
- `fromJSONL` returns frozen `input` / `output` values; events and their `meta` stay plain objects.
|
|
20
|
+
- `freezeJson` (state and payload checks) now rejects arrays with holes (`INVALID_STATE`; before, holes became `null` on disk), and a `__proto__` key in state is kept as an ordinary key.
|
|
21
|
+
- `taugraph/openai` throws `HTTPError` (with `status`, `url` and `retryAfterMs`) instead of a plain `Error` for responses outside 2xx. The message is unchanged. `String(error)` now starts with `HTTPError:`.
|
|
22
|
+
- Types: `TaugraphErrorCode` gains `TIMEOUT`, so an exhaustive `switch` over it needs a branch, and `RunContext.meta` gains `idempotencyKey`, so a hand-built `ctx` in tests needs one.
|
|
23
|
+
|
|
24
|
+
### Added
|
|
25
|
+
|
|
26
|
+
- `taugraph/file`: `fileStore(dir, { durability })` stores one JSONL file per run, appended before each step continues; `load` ignores a half-written last line, and continuing a run cuts it off; a lock file per run keeps two processes on one machine from writing the same run; `list()` reports `running`, `interrupted`, `paused`, `completed` or `failed`. `durability` is `"writes"` (default: fsync before write steps, at pauses and at the end), `"every"` or `"none"`.
|
|
27
|
+
- `runStatus(trace)`, `createTraceEncoder(prefix)`, `toJSONL(trace, { from })` and `fromJSONL(text, { tornTail: "drop" })`.
|
|
28
|
+
- Retry policy: `backoff`, `retryOn` and `idempotent` on `RetryPolicy`; `isRetryable(error)`, the default rule; `ctx.meta.idempotencyKey` (`<runId>:<step>`); `delayMs` in `error` events.
|
|
29
|
+
- Timeouts: `timeoutMs` on nodes (`defineNode`, `CodeNode`, `LLMNode`), on `createAgent` for each model call, and on agent tools. An attempt that times out fails with the new code `TIMEOUT`, which is retryable, and its `ctx.signal` aborts. A `write` node's attempt that ends in a timeout or an abort has `outcome: "unknown"` in its `error` event. A read tool that times out answers the model with an error; a write tool fails the run.
|
|
30
|
+
- Async sinks: `onEvent` may return a Promise. `run` awaits it after each kernel event and awaits the events a node appended before the step's `exit`; calls never overlap; a rejection stops the run with `SINK_FAILED`. `runSync` refuses an async sink with `ASYNC_IN_SYNC_RUN`.
|
|
31
|
+
- `taugraph/openai`: `tokenLimit: "max_completion_tokens"` for OpenAI's reasoning models.
|
|
32
|
+
|
|
33
|
+
## [0.3.0] - 2026-11-25
|
|
34
|
+
|
|
35
|
+
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).
|
|
36
|
+
|
|
37
|
+
### Changed
|
|
38
|
+
|
|
39
|
+
- **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.
|
|
40
|
+
- 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.
|
|
41
|
+
|
|
42
|
+
### Added
|
|
43
|
+
|
|
44
|
+
- 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.
|
|
45
|
+
- `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.
|
|
46
|
+
- `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.
|
|
47
|
+
- 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.
|
|
48
|
+
- Agent tools can return text and images (`{ content: ContentPart[] }`); the state schema checks parts and points at the bad one.
|
|
49
|
+
- 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.
|
|
50
|
+
|
|
51
|
+
## [0.2.0] - 2026-11-19
|
|
52
|
+
|
|
53
|
+
First release on npm.
|
|
54
|
+
|
|
55
|
+
### Added
|
|
56
|
+
|
|
57
|
+
- 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 }`.
|
|
58
|
+
- 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`.
|
|
59
|
+
- 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.
|
|
60
|
+
- Replay feeds values delivered by `resume` back to `ctx.interrupt` when a step sees its recorded state, in both modes.
|
|
61
|
+
- `HumanNode` plugin: pause for an answer, validate it with a schema, ask again with the error.
|
|
62
|
+
- Kernel events `pause` and `resume`; `run_end.meta.status` can be `paused`. Error codes `WRITE_BLOCKED`, `UNKNOWN_OUTCOME`, `NOT_RESUMABLE`, `SINK_FAILED`.
|
|
63
|
+
- Example `examples/checkout.ts`: the model only picks one of a fixed set of commands, and code does the rest.
|
|
64
|
+
|
|
65
|
+
### Changed
|
|
66
|
+
|
|
67
|
+
- `onEvent` failures stop the run with `SINK_FAILED` instead of being rethrown asynchronously while the run continued.
|
|
68
|
+
- `RunResult` is now a union of `CompletedRun` and `PausedRun`; check `status` before reading `pending`.
|
|
69
|
+
- Removed the conventional `human_pause` plugin event type; pausing is now the kernel's `pause` event.
|
|
70
|
+
|
|
71
|
+
## [0.1.0] - 2026-11-19
|
|
72
|
+
|
|
73
|
+
GitHub only, not published to npm.
|
|
74
|
+
|
|
75
|
+
### Added
|
|
76
|
+
|
|
77
|
+
- Kernel: `createGraph` with static validation, sequential and conditional edges, end nodes, `maxSteps`.
|
|
78
|
+
- Runtime: `run` (async) and `runSync` sharing one generator-based loop; per-node retry policy; cancellation via `AbortSignal`.
|
|
79
|
+
- State: Standard Schema validation of input and every node output; JSON-only, deeply frozen state.
|
|
80
|
+
- Trace: append-only event log (format version 1), `onEvent` streaming, `toJSONL` / `fromJSONL`, `diffTraces`.
|
|
81
|
+
- Replay: `graph.replay` with node overrides and `recorded` / `live` modes.
|
|
82
|
+
- Plugin nodes (`taugraph/nodes`): `CodeNode`, `LLMNode` with a provider-agnostic `LLMModel` contract and structured output.
|
|
83
|
+
- Examples: quick start, retrieval with retry loop, OpenAI-compatible adapter.
|
|
84
|
+
|
|
85
|
+
[Unreleased]: https://github.com/wangcao-hub/taugraph/compare/v0.4.0...HEAD
|
|
86
|
+
[0.4.0]: https://github.com/wangcao-hub/taugraph/compare/v0.3.0...v0.4.0
|
|
87
|
+
[0.3.0]: https://github.com/wangcao-hub/taugraph/compare/v0.2.0...v0.3.0
|
|
88
|
+
[0.2.0]: https://github.com/wangcao-hub/taugraph/compare/v0.1.0...v0.2.0
|
|
89
|
+
[0.1.0]: https://github.com/wangcao-hub/taugraph/releases/tag/v0.1.0
|
package/README.md
CHANGED
|
@@ -22,16 +22,79 @@ In reinforcement learning, τ is the standard symbol for a trajectory: the seque
|
|
|
22
22
|
|
|
23
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
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, and a failed write is retried only when it is declared idempotent.
|
|
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
|
+
|
|
25
87
|
## Where it sits
|
|
26
88
|
|
|
27
|
-
|
|
|
28
|
-
|
|
|
29
|
-
| Kernel
|
|
30
|
-
| Orchestration
|
|
31
|
-
| State
|
|
32
|
-
|
|
|
33
|
-
|
|
|
34
|
-
|
|
|
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** |
|
|
35
98
|
|
|
36
99
|
## Rules of the kernel
|
|
37
100
|
|
|
@@ -41,7 +104,7 @@ If a model decides every step and gets each one right 95% of the time, a 3-step
|
|
|
41
104
|
4. A run is a serializable trace. Replay it at any time, with any node or model swapped.
|
|
42
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.
|
|
43
106
|
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.
|
|
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.4.0, Deno and Chrome for 0.2.0).
|
|
45
108
|
|
|
46
109
|
These are enforced by tests (`test/architecture.test.ts`), not only by convention.
|
|
47
110
|
|
|
@@ -49,7 +112,7 @@ These are enforced by tests (`test/architecture.test.ts`), not only by conventio
|
|
|
49
112
|
|
|
50
113
|
```ts
|
|
51
114
|
import { createGraph, diffTraces, toJSONL } from "taugraph";
|
|
52
|
-
import { CodeNode, LLMNode, type LLMModel } from "taugraph/nodes";
|
|
115
|
+
import { CodeNode, LLMNode, type LLMModel, textOf } from "taugraph/nodes";
|
|
53
116
|
import { z } from "zod";
|
|
54
117
|
|
|
55
118
|
const State = z.object({
|
|
@@ -58,8 +121,11 @@ const State = z.object({
|
|
|
58
121
|
final: z.string().nullable().default(null),
|
|
59
122
|
});
|
|
60
123
|
|
|
61
|
-
// Any provider fits this contract
|
|
62
|
-
const model: LLMModel = {
|
|
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
|
+
};
|
|
63
129
|
|
|
64
130
|
const graph = createGraph(State, {
|
|
65
131
|
start: "fetch",
|
|
@@ -87,6 +153,8 @@ console.log(diffTraces(trace, replay.trace)); // { equal: false, firstDivergence
|
|
|
87
153
|
|
|
88
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.
|
|
89
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
|
+
|
|
90
158
|
## Concepts
|
|
91
159
|
|
|
92
160
|
### State
|
|
@@ -107,7 +175,7 @@ State must be plain JSON (no `Date`, `Map`, class instances). That is what makes
|
|
|
107
175
|
type Node<S> = (state: S, ctx: RunContext) => S | Promise<S>;
|
|
108
176
|
|
|
109
177
|
interface RunContext {
|
|
110
|
-
meta: { runId: string; nodeId: string; step: number; attempt: number; recovered: boolean };
|
|
178
|
+
meta: { runId: string; nodeId: string; step: number; attempt: number; recovered: boolean; idempotencyKey: string };
|
|
111
179
|
signal: AbortSignal; // pass it to fetch / model clients
|
|
112
180
|
trace: { append(event: PluginEvent): void }; // record a side effect
|
|
113
181
|
interrupt<T>(request?: unknown): T; // pause the run until resume(trace, value)
|
|
@@ -137,7 +205,9 @@ run_start → enter → [llm_call | tool_call | ...] → exit → enter → paus
|
|
|
137
205
|
|
|
138
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.
|
|
139
207
|
|
|
140
|
-
`
|
|
208
|
+
Consecutive snapshots share whatever did not change. In memory this always holds; on disk it holds when you write with `toJSONL`, `createTraceEncoder` or `fileStore`. These write format v2, which stores each snapshot as a patch against the one before, so a trace grows with what changed rather than with the size of the state. That holds for items appended to arrays and for changes to object keys; inserting at the front of a long array or reordering an object's keys still rewrites that array or object.
|
|
209
|
+
|
|
210
|
+
`run(input, { onEvent })` hands every event to your sink before the run continues. The sink may return a Promise: `run` waits for it after every kernel event, so a `write` step's `enter` is stored before the node runs, and the events a node appends are stored before its step ends. Calls never overlap. If the sink throws or rejects, the run stops with `SINK_FAILED`, so no step runs without being logged. `runSync` takes synchronous sinks only. Full spec: [docs/trace-format.md](./docs/trace-format.md).
|
|
141
211
|
|
|
142
212
|
### Pause and resume
|
|
143
213
|
|
|
@@ -171,17 +241,26 @@ Typical uses: swap a model and compare answers, mock a flaky tool, rerun a faile
|
|
|
171
241
|
|
|
172
242
|
### Errors and retries
|
|
173
243
|
|
|
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.
|
|
244
|
+
Every failure is a `TaugraphError` with a `code` (`INVALID_GRAPH`, `INVALID_STATE`, `INVALID_ROUTE`, `NODE_FAILED`, `MAX_STEPS`, `ABORTED`, `TIMEOUT`, `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.
|
|
245
|
+
|
|
246
|
+
```ts
|
|
247
|
+
CodeNode(fetchPrices, { retry: { maxAttempts: 4 }, timeoutMs: 10_000 });
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
- **What is retried.** By default `isRetryable(error)` decides. Kernel errors that another attempt cannot fix (`INVALID_STATE`, `ABORTED`, `SINK_FAILED`, ...) are not retried, and neither are HTTP 4xx errors other than 408, 409, 425 and 429, read from a numeric `status` on the error or its `cause` chain. Everything else is retried, including errors it knows nothing about. Pass `retryOn(error)` to decide yourself; it gets the error the node threw.
|
|
251
|
+
- **How long it waits.** Exponential backoff: 500 ms, twice as long each time, at most 30 s, minus up to half at random (`backoff: { initialMs, factor, maxMs, jitter }`, or `false` to retry at once). A `retryAfterMs` on the error, which `taugraph/openai` reads from `Retry-After`, makes it wait at least that long. It is not capped by `maxMs`; pass `retryOn` or abort the run if a server may ask for very long waits (in `runSync` the thread blocks for the whole wait). `run` waits with a timer and stops at once when aborted; `runSync` blocks the thread, and fails with `ASYNC_IN_SYNC_RUN` where it may not (a browser's main thread). Each failed attempt is an `error` event with `willRetry`, and `delayMs` when it will retry.
|
|
252
|
+
- **Write nodes.** A `write` node with `retry` must set `idempotent: true`, or `defineNode` throws: a repeated order is a second order. `ctx.meta.idempotencyKey` (`<runId>:<step>`) is the same for every attempt of a step and after a crash; pass it to the API (as an `Idempotency-Key` header, say) so repeats are safe.
|
|
253
|
+
- **Timeouts.** `timeoutMs` on a node fails the attempt with `TIMEOUT` when its Promise has not settled in time, and aborts `ctx.signal`. `TIMEOUT` is retried like other errors. Synchronous code cannot be interrupted. When a `write` node stops on a timeout or an abort, its `error` event says `outcome: "unknown"`: the effect may or may not have happened.
|
|
175
254
|
|
|
176
255
|
## Plugin nodes (`taugraph/nodes`)
|
|
177
256
|
|
|
178
|
-
| Node | What it does
|
|
179
|
-
| ----------- |
|
|
180
|
-
| `CodeNode` | Deterministic state transformation.
|
|
181
|
-
| `LLMNode` | Calls an `LLMModel
|
|
182
|
-
| `HumanNode` | Pauses for an answer via `ctx.interrupt`, validates it with a schema, asks again if invalid.
|
|
257
|
+
| Node | What it does |
|
|
258
|
+
| ----------- | --------------------------------------------------------------------------------------------------------------- |
|
|
259
|
+
| `CodeNode` | Deterministic state transformation. |
|
|
260
|
+
| `LLMNode` | Calls an `LLMModel` (tools included), records an `llm_call` event, optionally parses JSON output with a schema. |
|
|
261
|
+
| `HumanNode` | Pauses for an answer via `ctx.interrupt`, validates it with a schema, asks again if invalid. |
|
|
183
262
|
|
|
184
|
-
`LLMNode` only defines the call contract (`{ id, complete(request, { signal }) }`); bring
|
|
263
|
+
`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).
|
|
185
264
|
|
|
186
265
|
Writing your own node type takes one call to `defineNode`:
|
|
187
266
|
|
|
@@ -204,9 +283,191 @@ export const ToolNode = <S>(tool: Tool, apply: (s: S, out: unknown) => S) =>
|
|
|
204
283
|
);
|
|
205
284
|
```
|
|
206
285
|
|
|
286
|
+
## Agent (`taugraph/agent`)
|
|
287
|
+
|
|
288
|
+
`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.
|
|
289
|
+
|
|
290
|
+
```ts
|
|
291
|
+
import { createAgent, tool } from "taugraph/agent";
|
|
292
|
+
import { z } from "zod";
|
|
293
|
+
|
|
294
|
+
const weather = tool({
|
|
295
|
+
name: "weather",
|
|
296
|
+
description: "Today's weather for a city",
|
|
297
|
+
input: z.object({ city: z.string() }), // validates arguments and becomes the JSON Schema the model sees
|
|
298
|
+
run: ({ city }) => `${city}: cloudy, -2~5°C`,
|
|
299
|
+
});
|
|
300
|
+
|
|
301
|
+
const addTodo = tool({
|
|
302
|
+
name: "add_todo",
|
|
303
|
+
effect: "write", // runs in a write step
|
|
304
|
+
input: z.object({ text: z.string() }),
|
|
305
|
+
run: ({ text }) => `added "${text}"`,
|
|
306
|
+
});
|
|
307
|
+
|
|
308
|
+
const agent = createAgent({
|
|
309
|
+
model, // any LLMModel whose adapter supports tools
|
|
310
|
+
tools: [weather, addTodo],
|
|
311
|
+
system: "You help with the day.",
|
|
312
|
+
approve: (call, t) => (t.effect === "write" ? "ask" : "run"),
|
|
313
|
+
});
|
|
314
|
+
|
|
315
|
+
const result = await agent.run({ messages: [{ role: "user", content: "What should I wear today?" }] });
|
|
316
|
+
// paused on add_todo: result.pending.request is { type: "tool_approval", call, effect: "write" }
|
|
317
|
+
const done = await agent.resume(result.trace, true); // or false, or { approved: false, reason }
|
|
318
|
+
console.log(done.state.final);
|
|
319
|
+
```
|
|
320
|
+
|
|
321
|
+
```
|
|
322
|
+
think ──a read call──▶ act ───────┐
|
|
323
|
+
▲ ──a write call─▶ act_write ─┤ more calls: act / act_write
|
|
324
|
+
└───────────────────────────────┘ none left: think
|
|
325
|
+
think ──no calls, or maxRounds──▶ finish
|
|
326
|
+
```
|
|
327
|
+
|
|
328
|
+
- The state is `{ messages, pending, rounds, final, stop }`, validated by a built-in Standard Schema (no validator needed).
|
|
329
|
+
- 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).
|
|
330
|
+
- Invalid arguments, unknown tools, unreadable arguments and thrown errors go back to the model as error results; the loop continues.
|
|
331
|
+
- `maxRounds` (default 8) bounds model calls; at most 32 calls run per reply. Each tool run is a `tool_call` event.
|
|
332
|
+
- `timeoutMs` on `createAgent` limits each model call (`TIMEOUT`, which `retry` retries). `timeoutMs` on a tool limits each run of it: a read tool that takes longer answers the model with an error and the loop goes on; a write tool fails the run with `TIMEOUT`, because its effect is unknown.
|
|
333
|
+
- 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)).
|
|
334
|
+
|
|
335
|
+
## OpenAI-compatible models (`taugraph/openai`)
|
|
336
|
+
|
|
337
|
+
`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`.
|
|
338
|
+
|
|
339
|
+
```ts
|
|
340
|
+
import { openAICompatible } from "taugraph/openai";
|
|
341
|
+
|
|
342
|
+
const model = openAICompatible({
|
|
343
|
+
baseURL: "https://api.deepseek.com",
|
|
344
|
+
model: "deepseek-flash",
|
|
345
|
+
apiKey: process.env.DEEPSEEK_API_KEY,
|
|
346
|
+
});
|
|
347
|
+
```
|
|
348
|
+
|
|
349
|
+
| Option | What it does |
|
|
350
|
+
| ----------------- | ---------------------------------------------------------------------------------------------------- |
|
|
351
|
+
| `baseURL` | The part before `/chat/completions`, e.g. `https://api.openai.com/v1` or `http://localhost:11434/v1` |
|
|
352
|
+
| `model` | The model name the endpoint expects |
|
|
353
|
+
| `apiKey` | Optional; sent as a Bearer token |
|
|
354
|
+
| `resolveImage` | Reads image references such as `media:abc` when a request is sent; see [Images](#images) |
|
|
355
|
+
| `reasoningParams` | Maps a reasoning level to request parameters; see [Reasoning models](#reasoning-models) |
|
|
356
|
+
| `sendReasoning` | `false` stops sending the model's own reasoning back, for endpoints that refuse the field |
|
|
357
|
+
| `tokenLimit` | `"max_completion_tokens"` for OpenAI's reasoning models; default `"max_tokens"` |
|
|
358
|
+
| `fetch` | Used instead of the global `fetch`, e.g. for a proxy or tests |
|
|
359
|
+
|
|
360
|
+
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.
|
|
361
|
+
|
|
362
|
+
A response outside 2xx throws `HTTPError` with `status`, `url` and `retryAfterMs` (read from `Retry-After`), so an `LLMNode` with `retry` retries 408, 409, 425, 429 and 5xx, waiting at least as long as `Retry-After` asks, and gives up on other 4xx at once.
|
|
363
|
+
|
|
364
|
+
Any other provider fits the same contract through a small adapter of your own: an `LLMModel` is `{ id, complete(request, { signal }) }`.
|
|
365
|
+
|
|
366
|
+
## Images
|
|
367
|
+
|
|
368
|
+
User messages and tool results can carry images. Their `content` is then an array of parts, in order; `system` and `assistant` messages stay text.
|
|
369
|
+
|
|
370
|
+
```ts
|
|
371
|
+
const question: ChatMessage = {
|
|
372
|
+
role: "user",
|
|
373
|
+
content: [
|
|
374
|
+
{ type: "text", text: "Which of these is the receipt?" },
|
|
375
|
+
{ type: "image", data: base64, mimeType: "image/png" }, // the bytes, in base64
|
|
376
|
+
{ type: "image", url: "media:9f2c" }, // or a reference the adapter reads when it calls the model
|
|
377
|
+
],
|
|
378
|
+
};
|
|
379
|
+
```
|
|
380
|
+
|
|
381
|
+
- A URL may be `https:`, `data:` or a reference of your own. The trace records the state at every step and every request. `toJSONL` and `fileStore` write a base64 image that a tool returns three times (the `tool_call` output, the `exit` patch that adds it to the state, and the next request) and one that the user sends twice (when it enters the state and in the first request that sends it), but a sink of your own that writes `JSON.stringify(event)` for each event repeats it at every step. A reference costs a few bytes either way. 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.
|
|
382
|
+
- Tools return images the same way: `run: () => ({ content: [{ type: "text", text: "the page" }, { type: "image", url: "media:shot1" }] })`.
|
|
383
|
+
- 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.
|
|
384
|
+
- 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.
|
|
385
|
+
- 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.
|
|
386
|
+
|
|
387
|
+
```ts
|
|
388
|
+
const model = openAICompatible({
|
|
389
|
+
baseURL: "https://api.openai.com/v1",
|
|
390
|
+
model: "gpt-4o-mini",
|
|
391
|
+
resolveImage: async (url) => {
|
|
392
|
+
const id = /^media:([\w-]+)$/.exec(url)?.[1];
|
|
393
|
+
if (!id) throw new Error(`Unknown image reference: ${url}`);
|
|
394
|
+
return { type: "image", mimeType: "image/png", data: (await readFile(`media/${id}.png`)).toString("base64") };
|
|
395
|
+
},
|
|
396
|
+
});
|
|
397
|
+
```
|
|
398
|
+
|
|
399
|
+
## Reasoning models
|
|
400
|
+
|
|
401
|
+
`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.
|
|
402
|
+
|
|
403
|
+
```ts
|
|
404
|
+
const agent = createAgent({ model, tools, reasoning: "high" }); // every model call in the run
|
|
405
|
+
```
|
|
406
|
+
|
|
407
|
+
- 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.
|
|
408
|
+
- 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.
|
|
409
|
+
- 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.
|
|
410
|
+
- 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`.
|
|
411
|
+
- 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`:
|
|
412
|
+
|
|
413
|
+
```ts
|
|
414
|
+
// DeepSeek V4: a thinking switch; it maps the levels itself
|
|
415
|
+
const deepseek = (level: ReasoningLevel) =>
|
|
416
|
+
level === "off" ? { thinking: { type: "disabled" } } : { thinking: { type: "enabled" }, reasoning_effort: level };
|
|
417
|
+
// Qwen on vLLM or SGLang
|
|
418
|
+
const qwen = (level: ReasoningLevel) => ({ chat_template_kwargs: { enable_thinking: level !== "off" } });
|
|
419
|
+
|
|
420
|
+
const model = openAICompatible({
|
|
421
|
+
baseURL: "https://api.deepseek.com",
|
|
422
|
+
model: "deepseek-flash",
|
|
423
|
+
reasoningParams: deepseek,
|
|
424
|
+
});
|
|
425
|
+
```
|
|
426
|
+
|
|
427
|
+
## Saving to files (`taugraph/file`)
|
|
428
|
+
|
|
429
|
+
`fileStore(dir)` keeps one JSONL file per run and appends every event before the run takes its next step. After a crash, find the runs that did not finish and continue them:
|
|
430
|
+
|
|
431
|
+
```ts
|
|
432
|
+
import { fileStore } from "taugraph/file";
|
|
433
|
+
|
|
434
|
+
const store = fileStore("./runs");
|
|
435
|
+
await graph.run(input, { onEvent: store.sink });
|
|
436
|
+
|
|
437
|
+
// after a restart
|
|
438
|
+
for (const run of store.list()) {
|
|
439
|
+
if (run.status !== "interrupted") continue;
|
|
440
|
+
try {
|
|
441
|
+
await graph.resume(store.load(run.runId)!, undefined, { onEvent: store.sink });
|
|
442
|
+
} catch (error) {
|
|
443
|
+
// UNKNOWN_OUTCOME: a write step was running. Check the outside system, then resume with { allowWrites: true }.
|
|
444
|
+
console.error(run.runId, error);
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
```
|
|
448
|
+
|
|
449
|
+
- Use one directory per graph: the recovery loop above resumes every interrupted run in the directory with one graph.
|
|
450
|
+
- `list()` reports `running` (a live process holds the run's lock), `interrupted` (no end and nobody writing it), `paused`, `completed` or `failed`. It skips files it cannot read as a trace; `load` throws `INVALID_TRACE` for them.
|
|
451
|
+
- A crash can leave the last line half-written. `load` ignores it, and the store cuts it off before it continues the run. For a write step that was running, `resume` throws `UNKNOWN_OUTCOME` instead of running it again.
|
|
452
|
+
- `durability` decides when to `fsync`: `"writes"` (default) before a write step runs, at a pause and at the end; `"every"` after each event; `"none"` never. With `"writes"`, a power cut can lose read steps, which are safe to run again, but cannot make a write step run twice. It can also lose a new run entirely if the run has not yet reached a write step, a pause or its end.
|
|
453
|
+
- Each run has a lock file while it is written, so two processes cannot append to the same run. A lock left by a process that died is taken over.
|
|
454
|
+
- The lock works between processes on one machine (one pid namespace). Containers that share a volume cannot see each other's processes, so do not let two of them write the same directory.
|
|
455
|
+
- Two stores in one thread cannot write the same run; on Node this also holds across worker threads. Bun and Deno give the lock no way to tell worker threads apart, so write a directory from one thread there. A worker stopped with `worker.terminate()` keeps its locks until the process exits.
|
|
456
|
+
- A process that dies at the wrong moment can leave `<runId>.lock.takeover`. The error names the file; remove it if no process is writing the run. On a file system without hard links, such a process or a power cut can also leave an empty `<runId>.lock`: `list()` reports the run as `running` and the store refuses the lock until it is 10 seconds old, then takes it over. A crash can also leave `<runId>.lock.<pid>.<random>` temp files, which are harmless and safe to delete.
|
|
457
|
+
- It uses `node:fs` (Node, Bun, Deno) and adds no dependencies. Run ids may contain ASCII letters, digits, `_`, `-` and `.` (not first), up to 128 characters.
|
|
458
|
+
|
|
459
|
+
## Integrations
|
|
460
|
+
|
|
461
|
+
| Package | Use it to |
|
|
462
|
+
| ----------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
|
|
463
|
+
| [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` |
|
|
464
|
+
| [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` |
|
|
465
|
+
|
|
466
|
+
Both keep the trace format, so runs recorded through them can be replayed and diffed with this package.
|
|
467
|
+
|
|
207
468
|
## Not in the kernel, on purpose
|
|
208
469
|
|
|
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.
|
|
470
|
+
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. `taugraph/file` is an optional entry point outside the kernel, like `taugraph/agent`.
|
|
210
471
|
|
|
211
472
|
## Roadmap
|
|
212
473
|
|