@lzn1998/dsh-langgraph 0.0.0-stage → 0.5.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 lznnnnn1998
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,31 @@
1
- # Temporary Holding Version
1
+ # dsh-langgraph
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
+ A DSH bundle that registers LangGraph workflows and exposes them to the agent as the
4
+ `langgraph_run` and `langgraph_threads` tools. Graph nodes call the session's own DSH
5
+ tools through `helpers.callTool`; threads are checkpointed in a DSH storage domain, so a
6
+ run survives the turn — and the Host process — and an `interrupt()`ed graph resumes
7
+ where it stopped.
8
+
9
+ - `langgraph_run` (`graph`, `input`, `thread`, `resume`, `maxSteps`, `run_in_background`;
10
+ omit `graph` to list). A background run returns a DSH job id; read it with `job_output`
11
+ and stop it with `job_kill`.
12
+ - `langgraph_threads` (`action`: `list` | `state` | `delete`).
13
+ - Registry: `graphs/*.js` (and `graphs/*.ts` on Node 24.22+) in this package plus `config.graphs`.
14
+ - Node helpers: `helpers.callTool(name, args)` for DSH tools, `helpers.subagent(prompt, options)`
15
+ for a caller-delivered DSH child agent, `helpers.callModel(prompt, options)` for this
16
+ deployment's model, and `helpers.chatModel()` / `helpers.tools([...])` /
17
+ `helpers.createReactAgent({...})` when you want LangGraph's prebuilt agent to drive DSH
18
+ tools with the DSH model. Node-level calls keep the agent's sandbox and approval scope.
19
+ - **Trajectory trace:** each run shows up as one `langgraph_run` row; its graph nodes, DSH
20
+ tool calls, and model calls appear as nested sub-calls in **Trajectory** — `langgraph:node`,
21
+ `langgraph:tool`, `langgraph:model`, `langgraph:subagent`. The trace uses DSH's log-only
22
+ `tool/ptc-dispatch-start` / `tool/ptc-dispatch` events, so it never enters the model's
23
+ context. Neither DSH nor LangGraph source is modified: LangGraph's own callbacks are the
24
+ source, and DSH's existing session-event vocabulary is the sink. Background runs keep the
25
+ same trace under their `langgraph_run` row even though the events arrive after the tool result.
26
+ - Threads are owned by the session and graph that created them; another session cannot
27
+ resume or delete them.
28
+ - See `docs/DETAIL.md` for the graph module contract, trace mapping, thread semantics, and limits.
29
+
30
+ From npm: `dsh plugin --profile <name> add @lzn1998/dsh-langgraph`, then restart that
31
+ profile's host. From a local checkout: `dsh plugin --profile <name> add <path-to-this-directory>`.
@@ -0,0 +1,11 @@
1
+ # Registers the LangGraph workflow tools. Graphs live in the package's `graphs/`
2
+ # directory; `config.graphs` adds more modules, `config.recursionLimit` bounds a run,
3
+ # `config.model` overrides the route graph nodes use for model calls, `config.trace:
4
+ # false` turns off the Trajectory sub-call trace, `config.background: false` hides
5
+ # background runs, and `config.subagentProvider` selects the provider for
6
+ # `helpers.subagent` (default `spawn`). Threads are checkpointed in the
7
+ # `langgraph_checkpoints` storage domain.
8
+ - insert:
9
+ - id: langgraph
10
+ name: '@lzn1998/dsh-langgraph'
11
+ config: {}
package/docs/DETAIL.md ADDED
@@ -0,0 +1,239 @@
1
+ # LangGraph workflows
2
+
3
+ Run a LangGraph graph from inside a DSH agent session, and continue it later.
4
+
5
+ ## What it adds
6
+
7
+ - `langgraph_run` — run a graph by id with an initial state. Omitting `graph` lists
8
+ the registered graphs **with their input schemas**.
9
+ - `langgraph_threads` — `list`, `state`, and `delete` durable threads.
10
+ - **Durable threads.** Every superstep is checkpointed in a DSH storage domain
11
+ (`langgraph_checkpoints`), so a thread survives the turn and the Host process. Pass
12
+ `thread` back to continue it; a profile without `storageDomain` falls back to an
13
+ in-process saver and says so.
14
+ - **Interrupts.** A node that calls LangGraph's `interrupt(...)` stops the run; the tool
15
+ reports `status: "interrupted"` with the payload, and
16
+ `langgraph_run({ graph, thread, resume: <value> })` resumes exactly there.
17
+ - **Background runs.** `run_in_background: true` registers the run on `ctx.jobs` and returns
18
+ `{ kind: "background", jobId, thread }` immediately. The model reads progress and the final
19
+ value with `job_output`, and stops it with `job_kill`; the graph keeps its thread and its
20
+ Trajectory sub-calls.
21
+ - **Subagent delegation.** `helpers.subagent(prompt, options)` starts a caller-delivered DSH
22
+ child through `ctx.subagents`, awaits its result, and disposes that exact activation. The
23
+ child has its own Session and tool scope; the graph receives text/structured output.
24
+ - A graph registry read from this package's `graphs/*.js` and from `config.graphs`
25
+ (`[{ "id": "...", "module": "..." }]`).
26
+ - A bridge for nodes: `helpers.callTool(name, args)` runs a real DSH tool in the calling
27
+ agent's scope — same sandbox, same approvals. The call is recorded as a log-only trace
28
+ sub-call (see [Trajectory trace](#trajectory-trace)), not as a model-visible
29
+ `tool/call`; only the enclosing `langgraph_run` call enters model history.
30
+ - A model bridge for nodes: `helpers.callModel(prompt, { system, provider, model, temperature, maxTokens })`
31
+ returns `{ text, usage }` from this deployment's model (default route: the profile's
32
+ selected model, overridable per call or with `config.model`).
33
+ - LangChain bridges: `helpers.chatModel()` is a `BaseChatModel` over that same route
34
+ (supports `bindTools`), `helpers.tools([...names])` wraps DSH tools as LangChain tools,
35
+ and `helpers.createReactAgent({...})` is LangGraph's prebuilt ReAct agent wired to both.
36
+ `helpers.messages` re-exports the LangChain message classes.
37
+
38
+ ## Trajectory trace
39
+
40
+ A run is not a black box. The `langgraph_run` row in **Trajectory** expands into the
41
+ graph's own activity:
42
+
43
+ ```
44
+ langgraph_run
45
+ └─ langgraph:node scan
46
+ └─ langgraph:tool glob args: {"pattern":"**/*.js"}
47
+ └─ langgraph:node large
48
+ ```
49
+
50
+ Nested LangGraph agents add their own level:
51
+
52
+ ```
53
+ langgraph_run
54
+ └─ langgraph:node react
55
+ └─ langgraph:node agent
56
+ └─ langgraph:model messages + model output + usage
57
+ └─ langgraph:node tools
58
+ └─ langgraph:tool read args + result
59
+ ```
60
+
61
+ How it works, without changing either project:
62
+
63
+ - **Source:** LangGraph's public callback surface (`on_chain_*`, `on_tool_*`,
64
+ `on_chat_model_*`, `on_llm_*`) is attached to the run's `invoke` config. Node boundaries
65
+ come from `metadata.langgraph_node` plus the `graph:step:*` tag; inner runnables inherit
66
+ their node's trace.
67
+ - **Sink:** DSH's log-only `tool/ptc-dispatch-start` / `tool/ptc-dispatch` session events.
68
+ They are the stock Trajectory view's nested sub-call vocabulary; `deriveMessages()`
69
+ ignores them, so traces never enter model context.
70
+ - **Manual bridges:** `helpers.callTool` and `helpers.callModel` emit the same two events
71
+ directly. `helpers.tools()` lets LangGraph's prebuilt ToolNode call DSH tools; the
72
+ helper knows the real tool name where the ToolNode callback only exposes a wrapper.
73
+ - Traces are best-effort: a rejected append disables tracing for that run and never fails
74
+ the graph. Node/tool/model payloads are clipped at 4,000 characters. A direct helper
75
+ call inside a fan-out graph attaches to the most recently started node; LangChain
76
+ callbacks keep exact nesting for prebuilt agents.
77
+
78
+ ## Background runs
79
+
80
+ Set `run_in_background: true` on `langgraph_run`. The call returns before the graph starts:
81
+
82
+ ```json
83
+ { "kind": "background", "jobId": "langgraph-…", "graph": "typed-report", "thread": "lg_typed-report_…", "status": "started" }
84
+ ```
85
+
86
+ - The job is owned by the calling session; `job_kill` aborts the graph's `AbortController`,
87
+ which reaches `compiled.invoke`, node tool calls, and model calls.
88
+ - `job_output` returns the job's progress ring followed by the final run envelope. Progress
89
+ lines are `▶ langgraph:node scan`, `✓ langgraph:tool glob`, and so on.
90
+ - The returned `thread` is meaningful for a graph compiled with a checkpointer; a graph
91
+ that returns its own compiled graph without one fails the job and the thread is unused.
92
+ An interrupted background run reports `detail: "interrupted"` and can be resumed with the
93
+ returned `thread`.
94
+ - Trajectory still nests the node/tool/model sub-calls under the `langgraph_run` row, even
95
+ though those log-only events arrive after the tool result.
96
+ - Background runs require `ctx.jobs` (`@deepseek-ai/dsh-jobs-local` plus
97
+ `@deepseek-ai/dsh-tool-jobs` in the shipped profiles). Without them the call returns an
98
+ error naming the missing pieces.
99
+
100
+ ## Subagent delegation
101
+
102
+ A node can delegate one task to a DSH child agent:
103
+
104
+ ```ts
105
+ const result = await helpers.subagent('Read README.md and summarize it.', {
106
+ label: 'readme summary',
107
+ // provider: 'spawn', // default; row config `subagentProvider` overrides
108
+ // schema: { type: 'object', properties: { summary: { type: 'string' } }, required: ['summary'] },
109
+ })
110
+ return { summary: result.text, stopReason: result.stopReason }
111
+ ```
112
+
113
+ - `delivery: 'caller'` means no parent completion notice; the helper awaits and disposes the
114
+ activation. The child's final output is in `result.text` / `result.output`, with
115
+ `result.structured` when `schema` was supplied.
116
+ - The child is a real DSH agent with its own Session, tools, sandbox and model route. Its own
117
+ activity is visible in the child Session's Trajectory, not in the parent graph's model context.
118
+ - Trajectory shows the delegation as `langgraph:subagent` under the enclosing node, with
119
+ provider, label, prompt, output and stop reason.
120
+ - A graph node cannot start a nested LangGraph run; delegate that work to a subagent or another
121
+ top-level `langgraph_run` call instead.
122
+ - Requires `ctx.subagents` plus a registered provider. The default is `spawn`; set
123
+ `config.subagentProvider` or pass `provider` per call. A local child stays in the parent's
124
+ subagent catalog after disposal and can be continued with the usual subagent tools.
125
+ - **Shared tree, not a second registry.** The graph is not a subagent level: a
126
+ `helpers.subagent` child is a child of the DSH agent that called `langgraph_run`. It therefore
127
+ shares the parent's subagent tree, `maxActiveSubagents` capacity, child-name namespace, and
128
+ the profile's `maxDepth` policy with the model-facing `subagent` tool. At capacity it fails
129
+ with `ACTIVATION_LIMIT_REACHED`; at the depth limit it fails with `DEPTH_EXCEEDED`. Cancelling
130
+ the graph disposes the child through the activation signal.
131
+ - If a graph exposes the stock `subagent` tool through `helpers.tools(['subagent'])`, the model
132
+ inside LangGraph can call it. That is the stock tool path (`delivery: 'parent'`): the node
133
+ does not wait for the child, and the parent later receives a completion notice. Use
134
+ `helpers.subagent` when the graph needs the child's result to continue.
135
+
136
+ ## Writing a graph (TypeScript or JavaScript)
137
+
138
+ ```ts
139
+ export const id = 'my-workflow'
140
+ export const description = 'One line the agent sees when it lists workflows.'
141
+ export const input = {
142
+ type: 'object',
143
+ properties: { pattern: { type: 'string', description: 'Glob to scan.' } },
144
+ additionalProperties: false,
145
+ }
146
+
147
+ export function build({ StateGraph, Annotation, START, END, helpers }) {
148
+ const State = Annotation.Root({
149
+ pattern: Annotation({ reducer: (_, b) => b, default: () => '**/*.md' }),
150
+ files: Annotation({ reducer: (_, b) => b, default: () => '' }),
151
+ })
152
+ // Return the uncompiled StateGraph: the plugin compiles it with the durable
153
+ // checkpointer. Returning a graph you compiled yourself opts out of durability.
154
+ return new StateGraph(State)
155
+ .addNode('scan', async state => ({ files: await helpers.callTool('glob', { pattern: state.pattern }) }))
156
+ .addEdge(START, 'scan')
157
+ .addEdge('scan', END)
158
+ }
159
+ ```
160
+
161
+ `build(api)` returns a `StateGraph` (preferred) or an already-compiled graph. The API
162
+ object carries the LangGraph namespace, `helpers`, and `checkpointer`.
163
+
164
+ On Node 24.22+ a `graphs/*.ts` module loads directly (Node's type stripping), so a typed
165
+ graph needs no build step. Keep to erasable syntax: no `enum`, `namespace`, parameter
166
+ properties, or decorators. The package exports `GraphApi` and `GraphModule` types; a
167
+ typed module can use `import type` and `defineGraph(module)` without importing the plugin
168
+ at runtime. Build with the `StateGraph`/`Annotation` from `api` rather than importing a
169
+ second copy of `@langchain/langgraph`; the plugin compiles the graph with its own
170
+ checkpointer and LangGraph instance. A `.js` graph remains the portable option for older
171
+ Node releases.
172
+
173
+ An interrupt gate:
174
+
175
+ ```ts
176
+ .addNode('gate', async () => ({ approved: interrupt({ question: 'Ship it?' }) }))
177
+ ```
178
+
179
+ ## Configuration
180
+
181
+ | key | meaning |
182
+ |---|---|
183
+ | `graphs` | extra `{ id, module }` entries; `module` is relative to the package or absolute |
184
+ | `recursionLimit` | default LangGraph superstep bound per run (default 25) |
185
+ | `model` | `{ provider, model, reasoningEffort }` used by `helpers.callModel`; defaults to the profile's selection |
186
+ | `trace` | log node/tool/model activity as Trajectory sub-calls (default `true`; `false` disables it) |
187
+ | `background` | expose `run_in_background` on `langgraph_run` (default `true`; `false` rejects the flag) |
188
+ | `subagentProvider` | default provider for `helpers.subagent` (default `spawn`; a per-call `provider` overrides it) |
189
+
190
+ Threads live in the `langgraph_checkpoints` storage domain (tables `checkpoints`,
191
+ `writes`, `threads`). `langgraph_threads({ action: 'delete', thread })` reclaims one.
192
+
193
+ ## Limits
194
+
195
+ - Graphs run in the Host process, not in a separate sandbox: a node's blast radius is
196
+ what its DSH tool calls are allowed to do.
197
+ - Every checkpoint of every thread is loaded when the domain opens; there is no
198
+ retention policy yet, so delete finished threads you no longer need.
199
+ - `langgraph_threads` lists the calling session's threads by default; `all: true` lists
200
+ every session's.
201
+ - What a graph inherits from the agent: **tools**, resolved in the calling agent's scope,
202
+ but only those the graph names — `helpers.tools([...])` reads
203
+ `ctx.tools.definitions(agent)` and throws with the visible names when one is missing,
204
+ and `helpers.callTool` runs through the same executor. **Not inherited**: the session's
205
+ system prompt, and with it the skill catalog, the runtime context (cwd, date), and
206
+ AGENTS.md instructions. `helpers.chatModel()` therefore starts with no bound tools, and
207
+ a model call does not know the working directory — either pass `{ system }`, bind tools
208
+ explicitly, or let a DSH tool resolve a path in the session's cwd. To read a skill, call
209
+ the `skill` tool through `helpers.callTool` and pass its text to `helpers.callModel`,
210
+ or enumerate skills with `ctx.get('sessionSkillCatalog').list({ sessionId })`.
211
+ - A forked session inherits the session log, not the plugin's storage domain: threads do
212
+ not follow a fork.
213
+ - A run's internal work is trace-only, not model-visible. The outer `langgraph_run` call
214
+ is the model-facing `tool/call`/`tool/result` pair; node, tool, and model activity is
215
+ recorded as log-only `tool/ptc-dispatch-start` / `tool/ptc-dispatch` events and appears
216
+ in Trajectory, but `deriveMessages()` ignores it, so it never enters model context.
217
+ `helpers.callTool` still executes in the calling agent's scope (sandbox and approval
218
+ policy apply), and `helpers.callModel` uses the deployment route.
219
+ - A thread is owned by the graph and session that created it. Another session cannot
220
+ resume, read, or delete it; `langgraph_threads` lists only this session's threads by
221
+ default, and `all: true` is required for a cross-session listing.
222
+ - A node cannot start a nested LangGraph run; use `helpers.subagent` for a DSH child agent,
223
+ or call another top-level `langgraph_run`. `helpers.callModel` is text-only (no tool
224
+ calling inside that model request).
225
+ - A background run's trace events arrive after its `tool/result`; they are still log-only and
226
+ stay under the same Trajectory row while the session is live. If append fails — for example
227
+ a profile without the PTC event vocabulary — tracing disables for that run and the job's
228
+ output ring remains the progress record.
229
+ - A subagent child has its own Session and tool scope. Its own tool/model activity is not in
230
+ the parent graph's model context; it may message the parent through tools the profile grants
231
+ (`send_message`), and it remains in the parent's subagent catalog after disposal.
232
+ - Six example graphs ship in `graphs/`: `scan-report` (tool only), `typed-report`
233
+ (TypeScript, tool only), `ask-workspace` (tool plus one model call), `ask-tools`
234
+ (LangGraph's prebuilt ReAct agent over DSH tools and the DSH model), `ask-subagent`
235
+ (caller-delivered DSH child), and `approval-gate` (an `interrupt()` that waits for a
236
+ decision before it scans).
237
+ - LangGraph only accepts tools that are LangChain Runnables, so `helpers.tools()` builds
238
+ real `tool()` instances with a zod schema converted from the DSH tool's JSON schema; the
239
+ original JSON schema is what the chat model sends to the provider.
@@ -0,0 +1,117 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="1240" height="1010" viewBox="0 0 1240 1010" font-family="-apple-system, BlinkMacSystemFont, 'PingFang SC', 'Helvetica Neue', Arial, sans-serif" role="img" aria-label="dsh-langgraph v0.4 architecture">
2
+ <defs>
3
+ <marker id="arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z" fill="#94a3b8"/></marker>
4
+ <marker id="dot" viewBox="0 0 6 6" refX="1" refY="3" markerWidth="5" markerHeight="5"><circle cx="3" cy="3" r="2.5" fill="#94a3b8"/></marker>
5
+ </defs>
6
+ <rect width="1240" height="1010" fill="#ffffff"/>
7
+ <text x="60" y="46" font-family="-apple-system, BlinkMacSystemFont, 'PingFang SC', 'Helvetica Neue', Arial, sans-serif" font-size="21" font-weight="700" fill="#0f172a" text-anchor="start">dsh-langgraph v0.5 — 运行时架构</text>
8
+ <text x="60" y="70" font-family="-apple-system, BlinkMacSystemFont, 'PingFang SC', 'Helvetica Neue', Arial, sans-serif" font-size="12.5" font-weight="400" fill="#64748b" text-anchor="start">LangGraph 负责流程与状态契约,DSH 负责执行、鉴权、存储与审计</text>
9
+ <rect x="790" y="52" width="12" height="12" rx="3" fill="#eff6ff" stroke="#2563eb" stroke-width="1.5"/>
10
+ <text x="808" y="63" font-family="-apple-system, BlinkMacSystemFont, 'PingFang SC', 'Helvetica Neue', Arial, sans-serif" font-size="12" font-weight="400" fill="#64748b" text-anchor="start">DSH</text>
11
+ <rect x="855" y="52" width="12" height="12" rx="3" fill="#ecfdf5" stroke="#059669" stroke-width="1.5"/>
12
+ <text x="873" y="63" font-family="-apple-system, BlinkMacSystemFont, 'PingFang SC', 'Helvetica Neue', Arial, sans-serif" font-size="12" font-weight="400" fill="#64748b" text-anchor="start">本插件</text>
13
+ <rect x="920" y="52" width="12" height="12" rx="3" fill="#f5f3ff" stroke="#7c3aed" stroke-width="1.5"/>
14
+ <text x="938" y="63" font-family="-apple-system, BlinkMacSystemFont, 'PingFang SC', 'Helvetica Neue', Arial, sans-serif" font-size="12" font-weight="400" fill="#64748b" text-anchor="start">LangGraph</text>
15
+ <rect x="60" y="96" width="420" height="76" rx="10" fill="#eff6ff" stroke="#2563eb" stroke-width="1.5"/>
16
+ <text x="78" y="126" font-family="-apple-system, BlinkMacSystemFont, 'PingFang SC', 'Helvetica Neue', Arial, sans-serif" font-size="15" font-weight="600" fill="#0f172a" text-anchor="start">Agent(模型)</text>
17
+ <text x="78" y="148" font-family="-apple-system, BlinkMacSystemFont, 'PingFang SC', 'Helvetica Neue', Arial, sans-serif" font-size="11.5" font-weight="400" fill="#64748b" text-anchor="start">读工具 schema → 选图 → 带 thread / resume 调用</text>
18
+ <rect x="780" y="96" width="400" height="76" rx="10" fill="#eff6ff" stroke="#2563eb" stroke-width="1.5"/>
19
+ <text x="798" y="126" font-family="-apple-system, BlinkMacSystemFont, 'PingFang SC', 'Helvetica Neue', Arial, sans-serif" font-size="15" font-weight="600" fill="#0f172a" text-anchor="start">Session log(唯一真相)</text>
20
+ <text x="798" y="148" font-family="-apple-system, BlinkMacSystemFont, 'PingFang SC', 'Helvetica Neue', Arial, sans-serif" font-size="11.5" font-weight="400" fill="#64748b" text-anchor="start">外层 langgraph_run + 子调用(Trajectory 可见,log-only)</text>
21
+ <path d="M300,172 L300,196" fill="none" stroke="#94a3b8" stroke-width="1.6" stroke-linecap="round" marker-end="url(#arrow)"/>
22
+ <rect x="280.6" y="167.0" width="38.8" height="16" rx="4" fill="#ffffff" opacity="0.92"/>
23
+ <text x="300.0" y="180.0" font-family="'SF Mono', SFMono-Regular, Menlo, Consolas, monospace" font-size="11" font-weight="400" fill="#64748b" text-anchor="middle">工具调用</text>
24
+ <path d="M1000,172 L1000,196" fill="none" stroke="#94a3b8" stroke-width="1.6" stroke-linecap="round" marker-end="url(#arrow)"/>
25
+ <rect x="60" y="200" width="1120" height="104" rx="10" fill="#ffffff" stroke="#2563eb" stroke-width="1.4" stroke-dasharray="5 4"/>
26
+ <text x="78" y="224" font-family="-apple-system, BlinkMacSystemFont, 'PingFang SC', 'Helvetica Neue', Arial, sans-serif" font-size="14" font-weight="600" fill="#0f172a" text-anchor="start">DSH tools registry</text>
27
+ <text x="210" y="224" font-family="'SF Mono', SFMono-Regular, Menlo, Consolas, monospace" font-size="11.5" font-weight="400" fill="#64748b" text-anchor="start">作用域 = 本 session 的 agent</text>
28
+ <rect x="84" y="240" width="330" height="46" rx="8" fill="#eff6ff" stroke="#2563eb" stroke-width="1.2"/>
29
+ <text x="98" y="261" font-family="'SF Mono', SFMono-Regular, Menlo, Consolas, monospace" font-size="13" font-weight="600" fill="#0f172a" text-anchor="start">langgraph_run</text>
30
+ <text x="98" y="278" font-family="-apple-system, BlinkMacSystemFont, 'PingFang SC', 'Helvetica Neue', Arial, sans-serif" font-size="11" font-weight="400" fill="#64748b" text-anchor="start">graph / input / thread / resume / maxSteps</text>
31
+ <rect x="444" y="240" width="330" height="46" rx="8" fill="#eff6ff" stroke="#2563eb" stroke-width="1.2"/>
32
+ <text x="458" y="261" font-family="'SF Mono', SFMono-Regular, Menlo, Consolas, monospace" font-size="13" font-weight="600" fill="#0f172a" text-anchor="start">langgraph_threads</text>
33
+ <text x="458" y="278" font-family="-apple-system, BlinkMacSystemFont, 'PingFang SC', 'Helvetica Neue', Arial, sans-serif" font-size="11" font-weight="400" fill="#64748b" text-anchor="start">action: list / state / delete</text>
34
+ <rect x="804" y="240" width="330" height="46" rx="8" fill="#f8fafc" stroke="#64748b" stroke-width="1.2"/>
35
+ <text x="818" y="261" font-family="'SF Mono', SFMono-Regular, Menlo, Consolas, monospace" font-size="13" font-weight="600" fill="#0f172a" text-anchor="start">…… 会话里的其它工具</text>
36
+ <text x="818" y="278" font-family="-apple-system, BlinkMacSystemFont, 'PingFang SC', 'Helvetica Neue', Arial, sans-serif" font-size="11" font-weight="400" fill="#64748b" text-anchor="start">glob / read / bash / write …</text>
37
+ <path d="M600,304 L600,332" fill="none" stroke="#94a3b8" stroke-width="1.6" stroke-linecap="round" marker-end="url(#arrow)"/>
38
+ <rect x="587.8" y="301.0" width="24.4" height="16" rx="4" fill="#ffffff" opacity="0.92"/>
39
+ <text x="600.0" y="314.0" font-family="'SF Mono', SFMono-Regular, Menlo, Consolas, monospace" font-size="11" font-weight="400" fill="#64748b" text-anchor="middle">调用</text>
40
+ <rect x="60" y="336" width="1120" height="314" rx="10" fill="#ecfdf5" stroke="#059669" stroke-width="1.8"/>
41
+ <text x="78" y="362" font-family="-apple-system, BlinkMacSystemFont, 'PingFang SC', 'Helvetica Neue', Arial, sans-serif" font-size="14.5" font-weight="600" fill="#065f46" text-anchor="start">dsh-langgraph 插件(Host 进程内)</text>
42
+ <rect x="84" y="378" width="330" height="252" rx="10" fill="#ffffff" stroke="#059669" stroke-width="1.6"/>
43
+ <rect x="84" y="378" width="330" height="34" rx="10" fill="#059669"/>
44
+ <rect x="84" y="398" width="330" height="14" fill="#059669"/>
45
+ <text x="98" y="401" font-family="'SF Mono', SFMono-Regular, Menlo, Consolas, monospace" font-size="13.5" font-weight="600" fill="#ffffff" text-anchor="start">图注册表 + helpers</text>
46
+ <text x="98" y="440" font-family="'SF Mono', SFMono-Regular, Menlo, Consolas, monospace" font-size="12" font-weight="400" fill="#0f172a" text-anchor="start">graphs/*.js → 图模块</text>
47
+ <text x="98" y="465" font-family="'SF Mono', SFMono-Regular, Menlo, Consolas, monospace" font-size="12" font-weight="400" fill="#0f172a" text-anchor="start"> · id / description</text>
48
+ <text x="98" y="490" font-family="'SF Mono', SFMono-Regular, Menlo, Consolas, monospace" font-size="12" font-weight="400" fill="#0f172a" text-anchor="start"> · input(JSON Schema)</text>
49
+ <text x="98" y="515" font-family="'SF Mono', SFMono-Regular, Menlo, Consolas, monospace" font-size="12" font-weight="400" fill="#0f172a" text-anchor="start"> · build(api) → StateGraph</text>
50
+ <text x="98" y="565" font-family="'SF Mono', SFMono-Regular, Menlo, Consolas, monospace" font-size="12" font-weight="400" fill="#0f172a" text-anchor="start">helpers.callTool(name, args)</text>
51
+ <text x="98" y="590" font-family="'SF Mono', SFMono-Regular, Menlo, Consolas, monospace" font-size="12" font-weight="400" fill="#0f172a" text-anchor="start">helpers.callModel / chatModel()</text>
52
+ <text x="98" y="615" font-family="'SF Mono', SFMono-Regular, Menlo, Consolas, monospace" font-size="12" font-weight="400" fill="#0f172a" text-anchor="start">helpers.tools([...]) / createReactAgent()</text>
53
+ <rect x="444" y="378" width="356" height="252" rx="10" fill="#f5f3ff" stroke="#7c3aed" stroke-width="1.6"/>
54
+ <rect x="444" y="378" width="356" height="34" rx="10" fill="#7c3aed"/>
55
+ <rect x="444" y="398" width="356" height="14" fill="#7c3aed"/>
56
+ <text x="458" y="401" font-family="'SF Mono', SFMono-Regular, Menlo, Consolas, monospace" font-size="13.5" font-weight="600" fill="#ffffff" text-anchor="start">LangGraph 运行时</text>
57
+ <text x="458" y="440" font-family="'SF Mono', SFMono-Regular, Menlo, Consolas, monospace" font-size="12" font-weight="400" fill="#0f172a" text-anchor="start">StateGraph → compile({ checkpointer })</text>
58
+ <text x="458" y="465" font-family="'SF Mono', SFMono-Regular, Menlo, Consolas, monospace" font-size="12" font-weight="400" fill="#0f172a" text-anchor="start">superstep 循环(recursionLimit)</text>
59
+ <text x="458" y="490" font-family="'SF Mono', SFMono-Regular, Menlo, Consolas, monospace" font-size="12" font-weight="400" fill="#0f172a" text-anchor="start">interrupt() → 暂停并返回 payload</text>
60
+ <text x="458" y="515" font-family="'SF Mono', SFMono-Regular, Menlo, Consolas, monospace" font-size="12" font-weight="400" fill="#0f172a" text-anchor="start">Command({ resume }) → 从原节点继续</text>
61
+ <text x="458" y="540" font-family="'SF Mono', SFMono-Regular, Menlo, Consolas, monospace" font-size="12" font-weight="400" fill="#0f172a" text-anchor="start">serde(JsonPlusSerializer)</text>
62
+ <text x="458" y="590" font-family="'SF Mono', SFMono-Regular, Menlo, Consolas, monospace" font-size="12" font-weight="400" fill="#4c1d95" text-anchor="start" opacity="0.9">→ 差异化:可恢复 · 可中断 · 有结构</text>
63
+ <rect x="830" y="378" width="326" height="252" rx="10" fill="#ecfdf5" stroke="#059669" stroke-width="1.6"/>
64
+ <rect x="830" y="378" width="326" height="34" rx="10" fill="#059669"/>
65
+ <rect x="830" y="398" width="326" height="14" fill="#059669"/>
66
+ <text x="844" y="401" font-family="'SF Mono', SFMono-Regular, Menlo, Consolas, monospace" font-size="13.5" font-weight="600" fill="#ffffff" text-anchor="start">DshCheckpointSaver</text>
67
+ <text x="1142" y="400" font-family="-apple-system, BlinkMacSystemFont, 'PingFang SC', 'Helvetica Neue', Arial, sans-serif" font-size="10.5" font-weight="500" fill="#ffffff" text-anchor="end" opacity="0.85">实现 LangGraph 契约</text>
68
+ <text x="844" y="440" font-family="'SF Mono', SFMono-Regular, Menlo, Consolas, monospace" font-size="12" font-weight="400" fill="#0f172a" text-anchor="start">extends BaseCheckpointSaver</text>
69
+ <text x="844" y="465" font-family="'SF Mono', SFMono-Regular, Menlo, Consolas, monospace" font-size="12" font-weight="400" fill="#0f172a" text-anchor="start">put / putWrites 写入</text>
70
+ <text x="844" y="490" font-family="'SF Mono', SFMono-Regular, Menlo, Consolas, monospace" font-size="12" font-weight="400" fill="#0f172a" text-anchor="start">getTuple / list 读取</text>
71
+ <text x="844" y="515" font-family="'SF Mono', SFMono-Regular, Menlo, Consolas, monospace" font-size="12" font-weight="400" fill="#0f172a" text-anchor="start">deleteThread 回收</text>
72
+ <text x="844" y="540" font-family="'SF Mono', SFMono-Regular, Menlo, Consolas, monospace" font-size="12" font-weight="400" fill="#0f172a" text-anchor="start">线程簿记(graph、session)</text>
73
+ <text x="844" y="590" font-family="'SF Mono', SFMono-Regular, Menlo, Consolas, monospace" font-size="12" font-weight="400" fill="#0f172a" text-anchor="start">key = base64url(复合键)</text>
74
+ <path d="M414,504 L444,504" fill="none" stroke="#94a3b8" stroke-width="1.6" stroke-linecap="round" marker-end="url(#arrow)"/>
75
+ <path d="M800,490 L830,490" fill="none" stroke="#94a3b8" stroke-width="1.6" stroke-linecap="round" marker-end="url(#arrow)" marker-start="url(#dot)"/>
76
+ <rect x="84" y="690" width="330" height="86" rx="10" fill="#eff6ff" stroke="#2563eb" stroke-width="1.5"/>
77
+ <text x="102" y="718" font-family="'SF Mono', SFMono-Regular, Menlo, Consolas, monospace" font-size="13.5" font-weight="600" fill="#0f172a" text-anchor="start">ctx.tools.execute</text>
78
+ <text x="102" y="740" font-family="-apple-system, BlinkMacSystemFont, 'PingFang SC', 'Helvetica Neue', Arial, sans-serif" font-size="11.5" font-weight="400" fill="#64748b" text-anchor="start">在调用方 agent 作用域执行真实工具</text>
79
+ <text x="102" y="758" font-family="-apple-system, BlinkMacSystemFont, 'PingFang SC', 'Helvetica Neue', Arial, sans-serif" font-size="11.5" font-weight="400" fill="#64748b" text-anchor="start">同沙箱、同审批、同会话</text>
80
+ <rect x="444" y="690" width="356" height="86" rx="10" fill="#eff6ff" stroke="#2563eb" stroke-width="1.5"/>
81
+ <text x="462" y="718" font-family="'SF Mono', SFMono-Regular, Menlo, Consolas, monospace" font-size="13.5" font-weight="600" fill="#0f172a" text-anchor="start">ctx.llm.stream</text>
82
+ <text x="462" y="740" font-family="-apple-system, BlinkMacSystemFont, 'PingFang SC', 'Helvetica Neue', Arial, sans-serif" font-size="11.5" font-weight="400" fill="#64748b" text-anchor="start">部署自己的模型路由</text>
83
+ <text x="462" y="758" font-family="-apple-system, BlinkMacSystemFont, 'PingFang SC', 'Helvetica Neue', Arial, sans-serif" font-size="11.5" font-weight="400" fill="#64748b" text-anchor="start">provider / model / reasoningEffort</text>
84
+ <rect x="830" y="690" width="326" height="86" rx="10" fill="#eff6ff" stroke="#2563eb" stroke-width="1.5"/>
85
+ <text x="848" y="718" font-family="'SF Mono', SFMono-Regular, Menlo, Consolas, monospace" font-size="13.5" font-weight="600" fill="#0f172a" text-anchor="start">storageDomain</text>
86
+ <text x="848" y="740" font-family="-apple-system, BlinkMacSystemFont, 'PingFang SC', 'Helvetica Neue', Arial, sans-serif" font-size="11.5" font-weight="400" fill="#64748b" text-anchor="start">→ storage-json(per-record)</text>
87
+ <text x="848" y="758" font-family="-apple-system, BlinkMacSystemFont, 'PingFang SC', 'Helvetica Neue', Arial, sans-serif" font-size="11.5" font-weight="400" fill="#64748b" text-anchor="start">zod 校验 · 同步读 · 写即持久</text>
88
+ <path d="M230,630 L230,690" fill="none" stroke="#94a3b8" stroke-width="1.6" stroke-linecap="round" marker-end="url(#arrow)"/>
89
+ <rect x="196.2" y="648" width="67.6" height="16" rx="4" fill="#ffffff" opacity="0.92"/>
90
+ <text x="230" y="661" font-family="'SF Mono', SFMono-Regular, Menlo, Consolas, monospace" font-size="11" font-weight="400" fill="#64748b" text-anchor="middle">callTool</text>
91
+ <path d="M360,630 L360,660 L600,660 L600,690" fill="none" stroke="#94a3b8" stroke-width="1.6" stroke-linecap="round" marker-end="url(#arrow)"/>
92
+ <rect x="432.6" y="648" width="74.8" height="16" rx="4" fill="#ffffff" opacity="0.92"/>
93
+ <text x="470" y="661" font-family="'SF Mono', SFMono-Regular, Menlo, Consolas, monospace" font-size="11" font-weight="400" fill="#64748b" text-anchor="middle">callModel</text>
94
+ <path d="M990,630 L990,690" fill="none" stroke="#94a3b8" stroke-width="1.6" stroke-linecap="round" marker-end="url(#arrow)"/>
95
+ <rect x="952.6" y="648" width="74.8" height="16" rx="4" fill="#ffffff" opacity="0.92"/>
96
+ <text x="990" y="661" font-family="'SF Mono', SFMono-Regular, Menlo, Consolas, monospace" font-size="11" font-weight="400" fill="#64748b" text-anchor="middle">putRecord</text>
97
+ <rect x="84" y="806" width="330" height="68" rx="8" fill="#f8fafc" stroke="#94a3b8" stroke-width="1.1" stroke-dasharray="4 3"/>
98
+ <text x="100" y="832" font-family="'SF Mono', SFMono-Regular, Menlo, Consolas, monospace" font-size="12" font-weight="600" fill="#0f172a" text-anchor="start">沙箱 · 审批策略</text>
99
+ <text x="100" y="852" font-family="'SF Mono', SFMono-Regular, Menlo, Consolas, monospace" font-size="11" font-weight="400" fill="#64748b" text-anchor="start">拦截仍生效;执行记入 Trajectory 子调用</text>
100
+ <rect x="444" y="806" width="356" height="68" rx="8" fill="#f8fafc" stroke="#94a3b8" stroke-width="1.1" stroke-dasharray="4 3"/>
101
+ <text x="460" y="832" font-family="'SF Mono', SFMono-Regular, Menlo, Consolas, monospace" font-size="12" font-weight="600" fill="#0f172a" text-anchor="start">provider · model</text>
102
+ <text x="460" y="852" font-family="'SF Mono', SFMono-Regular, Menlo, Consolas, monospace" font-size="11" font-weight="400" fill="#64748b" text-anchor="start">可在 config.model 覆盖</text>
103
+ <rect x="830" y="806" width="326" height="68" rx="8" fill="#f8fafc" stroke="#94a3b8" stroke-width="1.1" stroke-dasharray="4 3"/>
104
+ <text x="846" y="832" font-family="'SF Mono', SFMono-Regular, Menlo, Consolas, monospace" font-size="12" font-weight="600" fill="#0f172a" text-anchor="start">~/.dsh/storages/langgraph_checkpoints/</text>
105
+ <text x="846" y="852" font-family="'SF Mono', SFMono-Regular, Menlo, Consolas, monospace" font-size="11" font-weight="400" fill="#64748b" text-anchor="start">checkpoints/ writes/ threads/</text>
106
+ <path d="M249,776 L249,806" fill="none" stroke="#94a3b8" stroke-width="1.6" stroke-linecap="round" marker-end="url(#arrow)"/>
107
+ <path d="M622,776 L622,806" fill="none" stroke="#94a3b8" stroke-width="1.6" stroke-linecap="round" marker-end="url(#arrow)"/>
108
+ <path d="M993,776 L993,806" fill="none" stroke="#94a3b8" stroke-width="1.6" stroke-linecap="round" marker-end="url(#arrow)"/>
109
+ <rect x="60" y="906" width="550" height="68" rx="10" fill="#fffbeb" stroke="#d97706" stroke-width="1.3" stroke-dasharray="5 4"/>
110
+ <text x="78" y="930" font-family="-apple-system, BlinkMacSystemFont, 'PingFang SC', 'Helvetica Neue', Arial, sans-serif" font-size="12.5" font-weight="600" fill="#92400e" text-anchor="start">没有 storageDomain 时</text>
111
+ <text x="78" y="950" font-family="-apple-system, BlinkMacSystemFont, 'PingFang SC', 'Helvetica Neue', Arial, sans-serif" font-size="11.5" font-weight="400" fill="#78350f" text-anchor="start">退回 LangGraph 自带 MemorySaver(进程内),重启即失</text>
112
+ <text x="78" y="966" font-family="'SF Mono', SFMono-Regular, Menlo, Consolas, monospace" font-size="11.5" font-weight="400" fill="#78350f" text-anchor="start">工具列表会明说 Threads are not durable</text>
113
+ <rect x="630" y="906" width="550" height="68" rx="10" fill="#fffbeb" stroke="#d97706" stroke-width="1.5" stroke-dasharray="5 4"/>
114
+ <text x="648" y="930" font-family="-apple-system, BlinkMacSystemFont, 'PingFang SC', 'Helvetica Neue', Arial, sans-serif" font-size="12.5" font-weight="600" fill="#92400e" text-anchor="start">节点内部动作不进会话日志</text>
115
+ <text x="648" y="950" font-family="-apple-system, BlinkMacSystemFont, 'PingFang SC', 'Helvetica Neue', Arial, sans-serif" font-size="11.5" font-weight="400" fill="#78350f" text-anchor="start">记录 tool/call 需要 turn/step,只有 agent loop 会传</text>
116
+ <text x="648" y="966" font-family="'SF Mono', SFMono-Regular, Menlo, Consolas, monospace" font-size="11.5" font-weight="400" fill="#78350f" text-anchor="start">→ 所以可恢复状态另存;Chat 里每次运行只有一行</text>
117
+ </svg>
@@ -0,0 +1,157 @@
1
+ /**
2
+ * A LangChain chat model backed by the DSH `llm` service.
3
+ *
4
+ * It lets a LangGraph node use the deployment's own model route, and it supports the
5
+ * tool-calling protocol LangGraph's prebuilt agents expect: `bindTools` records the
6
+ * LangChain tools, `_generate` passes their JSON schemas to DSH, and tool calls come
7
+ * back as an `AIMessage` with `tool_calls`.
8
+ * @module dsh-langgraph/chat-model
9
+ */
10
+
11
+ import { BaseChatModel } from '@langchain/core/language_models/chat_models'
12
+ import { AIMessage, HumanMessage, SystemMessage, ToolMessage } from '@langchain/core/messages'
13
+
14
+ /** Text of one LangChain message's content blocks. */
15
+ function textOf(message) {
16
+ const content = message?.content
17
+ if (typeof content === 'string') return content
18
+ if (!Array.isArray(content)) return ''
19
+ return content
20
+ .map(part => (typeof part === 'string' ? part : part?.type === 'text' ? part.text : ''))
21
+ .filter(Boolean)
22
+ .join('\n')
23
+ }
24
+
25
+ /**
26
+ * Convert one LangChain message into a DSH request message.
27
+ * @param {object} message - LangChain BaseMessage.
28
+ * @param {{ provider: string, model: string }} route - route used for assistant provenance.
29
+ * @returns {{ role: string, content: object[], source?: object, toolCallId?: string } | undefined}
30
+ */
31
+ function toRequestMessage(message, route) {
32
+ const text = textOf(message)
33
+ const type = message?.getType?.() ?? message?._getType?.()
34
+ if (type === 'human') return { role: 'user', content: [{ type: 'text', text }] }
35
+ if (type === 'ai') {
36
+ const content = [{ type: 'text', text }]
37
+ for (const call of message.tool_calls ?? []) {
38
+ content.push({ type: 'tool-call', id: call.id ?? `call_${content.length}`, name: call.name, arguments: JSON.stringify(call.args ?? {}) })
39
+ }
40
+ return { role: 'assistant', content, source: { kind: 'model', provider: route.provider, model: route.model } }
41
+ }
42
+ if (type === 'tool') {
43
+ const callId = message.tool_call_id ?? message.additional_kwargs?.tool_call_id
44
+ return { role: 'tool', content: [{ type: 'text', text }], source: { kind: 'tool', callId }, toolCallId: callId }
45
+ }
46
+ return undefined
47
+ }
48
+
49
+ /** The LangChain tool schema a DSH tool exposes to the model. */
50
+ function toolSchema(tool) {
51
+ return {
52
+ name: tool.name,
53
+ description: tool.description ?? '',
54
+ parameters: tool.dshParameters ?? { type: 'object', properties: {}, additionalProperties: false },
55
+ }
56
+ }
57
+
58
+ /** A chat model over one DSH route, bound to one run's cancellation and session. */
59
+ export class DshChatModel extends BaseChatModel {
60
+ /**
61
+ * @param {{ stream: Function, route: { provider: string, model: string, reasoningEffort?: string }, sessionId?: string, signal?: AbortSignal, tools?: object[] }} fields
62
+ */
63
+ constructor(fields) {
64
+ super({})
65
+ this.streamFn = fields.stream
66
+ this.route = fields.route
67
+ this.sessionId = fields.sessionId
68
+ this.signal = fields.signal
69
+ this.tools = fields.tools ?? []
70
+ }
71
+
72
+ /** @returns {string} provider family name shown by LangChain. */
73
+ _llmType() {
74
+ return 'dsh'
75
+ }
76
+
77
+ /**
78
+ * Record tools for the next call; LangGraph's prebuilt agents call this.
79
+ * @param {object[]} tools - LangChain tools.
80
+ * @returns {DshChatModel} a model bound to these tools.
81
+ */
82
+ bindTools(tools) {
83
+ return new DshChatModel({
84
+ stream: this.streamFn,
85
+ route: this.route,
86
+ sessionId: this.sessionId,
87
+ signal: this.signal,
88
+ tools: [...this.tools, ...tools],
89
+ })
90
+ }
91
+
92
+ /**
93
+ * One generation against the DSH model route.
94
+ * @param {object[]} messages - LangChain messages.
95
+ * @returns {Promise<{ generations: object[] }>} LangChain chat result.
96
+ */
97
+ async _generate(messages) {
98
+ const system = messages
99
+ .filter(message => (message?.getType?.() ?? message?._getType?.()) === 'system')
100
+ .map(textOf)
101
+ .filter(Boolean)
102
+ .join('\n\n')
103
+ const request = messages
104
+ .filter(message => (message?.getType?.() ?? message?._getType?.()) !== 'system')
105
+ .map(message => toRequestMessage(message, this.route))
106
+ .filter(Boolean)
107
+ let text = ''
108
+ let usage
109
+ const calls = new Map()
110
+ let finish
111
+ for await (const chunk of this.streamFn({
112
+ provider: this.route.provider,
113
+ model: this.route.model,
114
+ ...(this.route.reasoningEffort === undefined ? {} : { reasoningEffort: this.route.reasoningEffort }),
115
+ messages: request,
116
+ ...(system === '' ? {} : { system }),
117
+ ...(this.tools.length === 0 ? {} : { tools: this.tools.map(toolSchema) }),
118
+ ...(this.sessionId === undefined ? {} : { sessionId: this.sessionId }),
119
+ signal: this.signal,
120
+ })) {
121
+ if (chunk.type === 'text-delta') text += chunk.text
122
+ else if (chunk.type === 'usage') usage = chunk.usage
123
+ else if (chunk.type === 'tool-call-delta') {
124
+ const entry = calls.get(chunk.id) ?? { id: chunk.id, name: '', arguments: '' }
125
+ if (chunk.name !== undefined) entry.name = chunk.name
126
+ entry.arguments += chunk.argumentsDelta
127
+ calls.set(chunk.id, entry)
128
+ } else if (chunk.type === 'block-end' && chunk.block?.type === 'tool-call') {
129
+ const block = chunk.block
130
+ const previous = calls.get(block.id)
131
+ calls.set(block.id, {
132
+ id: block.id,
133
+ name: block.name ?? previous?.name ?? '',
134
+ arguments: block.arguments ?? previous?.arguments ?? '',
135
+ })
136
+ } else if (chunk.type === 'finish') finish = chunk.reason
137
+ }
138
+ if (finish?.kind === 'error') throw new Error(`model call failed: ${finish.failure.message}`)
139
+ const toolCalls = [...calls.values()].filter(entry => typeof entry.name === 'string' && entry.name !== '').map(entry => {
140
+ let args = {}
141
+ try {
142
+ args = entry.arguments === '' ? {} : JSON.parse(entry.arguments)
143
+ } catch {
144
+ args = {}
145
+ }
146
+ return { id: entry.id, name: entry.name, args }
147
+ })
148
+ const message = new AIMessage({ content: text, tool_calls: toolCalls })
149
+ return {
150
+ generations: [{ text, message }],
151
+ ...(usage === undefined ? {} : { llmOutput: { tokenUsage: usage } }),
152
+ }
153
+ }
154
+ }
155
+
156
+ /** Re-exported so graph modules can build message arrays without their own dependency. */
157
+ export { AIMessage, HumanMessage, SystemMessage, ToolMessage }