@lzn1998/dsh-langgraph 0.0.0-stage → 0.13.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/docs/DETAIL.md ADDED
@@ -0,0 +1,422 @@
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`, `history`, `edit`, `topology`, and `delete`.
10
+ A checkpoint can be inspected, forked with new values, and replayed; a graph's nodes
11
+ and edges are available as JSON for a client view.
12
+ - **Durable threads.** Every superstep is checkpointed in a DSH storage domain
13
+ (`langgraph_checkpoints`), so a thread survives the turn and the Host process. Pass
14
+ `thread` back to continue it; a profile without `storageDomain` falls back to an
15
+ in-process saver and says so.
16
+ - **Interrupts.** A node that calls LangGraph's `interrupt(...)` stops the run; the tool
17
+ reports `status: "interrupted"` with the payload, and
18
+ `langgraph_run({ graph, thread, resume: <value> })` resumes exactly there.
19
+ - **Long-term memory.** Graphs also get a LangGraph `BaseStore`, durable in the
20
+ `langgraph_store` domain: nodes use LangGraph's own `getStore(config)`, `build(api)`
21
+ sees `api.store`, and `helpers.store()` returns the same instance.
22
+ - **Native HITL.** `helpers.askUser(questions)` puts a question in DSH's stock question
23
+ UI and returns the answer to the node; no custom client is involved.
24
+ - **Web panel.** A sidebar **LangGraph** panel lists the registry and draws a graph's
25
+ topology; it reads the plugin's owner-only `/api/plugins/langgraph/*` routes.
26
+ - **Background runs.** `run_in_background: true` registers the run on `ctx.jobs` and returns
27
+ `{ kind: "background", jobId, thread }` immediately. The model reads progress and the final
28
+ value with `job_output`, and stops it with `job_kill`; the graph keeps its thread and its
29
+ Trajectory sub-calls.
30
+ - **Subagent delegation.** `helpers.subagent(prompt, options)` starts a caller-delivered DSH
31
+ child through `ctx.subagents`, awaits its result, and disposes that exact activation. The
32
+ child has its own Session and tool scope; the graph receives text/structured output.
33
+ - A graph registry read from this package's `graphs/*.js` and from `config.graphs`
34
+ (`[{ "id": "...", "module": "..." }]`).
35
+ - A bridge for nodes: `helpers.callTool(name, args)` runs a real DSH tool in the calling
36
+ agent's scope — same sandbox, same approvals. The call is recorded as a log-only trace
37
+ sub-call (see [Trajectory trace](#trajectory-trace)), not as a model-visible
38
+ `tool/call`; only the enclosing `langgraph_run` call enters model history.
39
+ - A model bridge for nodes: `helpers.callModel(prompt, { system, provider, model, temperature, maxTokens })`
40
+ returns `{ text, usage }` from this deployment's model (default route: the profile's
41
+ selected model, overridable per call or with `config.model`).
42
+ - LangChain bridges: `helpers.chatModel()` is a `BaseChatModel` over that same route
43
+ (supports `bindTools`), `helpers.tools([...names])` wraps DSH tools as LangChain tools,
44
+ and `helpers.createReactAgent({...})` is LangGraph's prebuilt ReAct agent wired to both.
45
+ `helpers.messages` re-exports the LangChain message classes.
46
+
47
+ ## Model-facing guidance
48
+
49
+ While the plugin is active it registers a system-prompt section through DSH's public
50
+ `ctx.systemPrompt.section` API — no DSH source change. The section names `langgraph_run`,
51
+ says when to prefer it, and lists the registered graph ids with their one-line descriptions
52
+ (up to 24; input schemas stay out of the prompt). The model therefore knows what exists
53
+ without spending a discovery call; `langgraph_run` with no `graph` still returns the full
54
+ list and input schemas.
55
+
56
+ - The registry is scanned when the plugin activates, so graph modules should keep top-level
57
+ code side-effect free.
58
+ - The section text is a function: after the asynchronous scan completes, the next prompt
59
+ assembly replaces the short "call it to list" hint with the actual graph list.
60
+ - `config.prompt: false` disables the section (and the eager scan).
61
+ - The section is effect-owned: unloading the plugin retires the guidance.
62
+
63
+ ## Long-term store
64
+
65
+ Checkpoints belong to one thread; a store is shared memory. Every run is compiled with a
66
+ LangGraph `BaseStore` that survives the turn and the Host process:
67
+
68
+ ```ts
69
+ .addNode('remember', async (_state, config) => {
70
+ const store = getStore(config) // LangGraph's standard accessor
71
+ await store.put(['memories', userId], 'preference', { tone: 'concise' })
72
+ return { preference: (await store.get(['memories', userId], 'preference')).value.tone }
73
+ })
74
+ ```
75
+
76
+ `build(api)` also receives `api.store`, and `helpers.store()` returns the same instance.
77
+ Inside a node, `getStore(config)` is LangGraph's `AsyncBatchedStore` wrapper over that same
78
+ `DshStore` (LangGraph batches node writes), so the wrapper is still backed by this domain.
79
+
80
+ - Backed by the `langgraph_store` storage domain, one record per `(namespace, key)`;
81
+ writes resolve after the domain has accepted them.
82
+ - Supports `get`, `put`, `delete`, `search({ filter, limit, offset })`, and
83
+ `listNamespaces({ prefix, suffix, maxDepth, limit, offset })`. Filters cover dotted
84
+ field paths and `$eq`, `$ne`, `$gt`, `$gte`, `$lt`, `$lte`; search results are newest
85
+ first (then by key).
86
+ - Values must be JSON objects. Vector search (`search({ query })`) is rejected with a
87
+ clear error instead of returning unranked rows; use an embeddings-backed store when a
88
+ graph needs similarity.
89
+ - Without a `storageDomain` service the plugin uses `InMemoryStore`, so the graph still
90
+ runs and only loses memories at process exit. `config.store: false` passes no store
91
+ (`getStore(config)` returns `undefined` and `helpers.store()` is `undefined`).
92
+ - Long-term memory is separate from thread ownership: any run of any session sees the
93
+ same namespaces. Namespace the data yourself (for example by user or workspace) when
94
+ that matters.
95
+
96
+ ## Time travel
97
+
98
+ Every checkpoint is addressable, so a thread is not a write-only log:
99
+
100
+ ```text
101
+ langgraph_threads({ action: 'history', graph, thread }) → checkpoints, newest first
102
+ langgraph_threads({ action: 'state', graph, thread, checkpoint }) → values, next, interrupts
103
+ langgraph_threads({ action: 'edit', graph, thread, checkpoint, values }) → new checkpoint
104
+ langgraph_run({ graph, thread, checkpoint }) → replay from that snapshot
105
+ ```
106
+
107
+ - `history` returns `checkpoint`, `step`, `source`, `createdAt`, `next`, and `paused` for
108
+ each snapshot, newest first; `limit` defaults to 20 (max 200).
109
+ - `state` and `edit` default to the thread head. `edit` writes the given `values` on top
110
+ of that snapshot and returns the new checkpoint; `next` tells you what would run.
111
+ - `langgraph_run({ checkpoint })` uses `checkpoint_id` instead of the thread head. With no
112
+ `input` or `resume` it runs that snapshot's pending tasks. A checkpoint whose `next` is
113
+ empty has nothing to run, so a replay is a no-op; pick one from `history` that lists
114
+ the node you want to rerun, or edit it first.
115
+ - An edit creates a fork: the original checkpoints stay, and the thread head becomes the
116
+ fork when it is replayed. An unknown checkpoint id is rejected rather than treated as
117
+ an empty state.
118
+ - History is bounded by `retention` (default 200 checkpoints per thread); older
119
+ checkpoints and their writes are pruned, so a checkpoint that is no longer in `history`
120
+ cannot be replayed.
121
+
122
+ ## Topology
123
+
124
+ `langgraph_threads({ action: 'topology', graph })` compiles the graph and returns its
125
+ drawable structure without needing a thread:
126
+
127
+ ```json
128
+ {
129
+ "graph": "scan-report",
130
+ "description": "…",
131
+ "input": { "type": "object", "…": "…" },
132
+ "nodes": [{ "id": "__start__", "type": "schema" }, { "id": "scan", "type": "runnable", "name": "scan" }],
133
+ "edges": [{ "source": "__start__", "target": "scan" }, { "source": "scan", "target": "__end__" }]
134
+ }
135
+ ```
136
+
137
+ - The response is plain JSON (`Graph.toJSON()`), safe to hand to a client panel; a
138
+ conditional edge carries `conditional: true`.
139
+ - Compiling runs `build(api)`, so a graph module's build must stay side-effect free.
140
+ - This is the host half of the client view; it works from the model-facing tool and from
141
+ any host code that can call the tool. A dedicated topology panel is a client change
142
+ outside this package's host-only scope.
143
+
144
+ ## Web panel
145
+
146
+ In a Web profile the package's `dsh.client` entry loads `lib/client.js`, a browser bundle
147
+ that contributes a **LangGraph** sidebar row and a `main` panel. The panel shows:
148
+
149
+ - the registered graphs with their descriptions and per-graph durable-thread counts;
150
+ - the selected graph's topology from `Graph.toJSON()` — left-to-right columns, dashed
151
+ conditional edges, start/end nodes.
152
+
153
+ It reads two exact, owner-only routes registered through the public
154
+ `ctx.connection.fetch.register` service:
155
+
156
+ | route | answer |
157
+ |---|---|
158
+ | `GET /api/plugins/langgraph/ui` | `{ graphs, threads: { total, byGraph, durable } }` |
159
+ | `GET /api/plugins/langgraph/topology?graph=<id>` | the same payload as the `topology` action |
160
+
161
+ - The routes are optional: a headless Host has no `connection` service, so they are not
162
+ registered. `config.ui: false` disables them in a Web profile too.
163
+ - The panel is read-only and polls `/ui` every 5 seconds. It does not read Session logs,
164
+ thread contents, or tokens; run activity stays in Trajectory and `langgraph_threads`.
165
+ - The bundle imports only `react` and `react/jsx-runtime`, which the Web shell seeds into
166
+ its module table. Rebuild it with the TypeScript compiler from a DSH checkout:
167
+
168
+ ```bash
169
+ DSH_TYPESCRIPT=/path/to/deepseek-harness/node_modules/typescript npm run build:client
170
+ ```
171
+
172
+ `lib/client.js` is committed, so installing from npm needs no build step.
173
+
174
+ ## Trajectory trace
175
+
176
+ A run is not a black box. The `langgraph_run` row in **Trajectory** expands into the
177
+ graph's own activity:
178
+
179
+ ```
180
+ langgraph_run
181
+ └─ langgraph:node scan
182
+ └─ langgraph:tool glob args: {"pattern":"**/*.js"}
183
+ └─ langgraph:node large
184
+ ```
185
+
186
+ Nested LangGraph agents add their own level:
187
+
188
+ ```
189
+ langgraph_run
190
+ └─ langgraph:node react
191
+ └─ langgraph:node agent
192
+ └─ langgraph:model messages + model output + usage
193
+ └─ langgraph:node tools
194
+ └─ langgraph:tool read args + result
195
+ ```
196
+
197
+ How it works, without changing either project:
198
+
199
+ - **Source:** LangGraph's public callback surface (`on_chain_*`, `on_tool_*`,
200
+ `on_chat_model_*`, `on_llm_*`) is attached to the run's `invoke` config. Node boundaries
201
+ come from `metadata.langgraph_node` plus the `graph:step:*` tag; inner runnables inherit
202
+ their node's trace.
203
+ - **Sink:** DSH's log-only `tool/ptc-dispatch-start` / `tool/ptc-dispatch` session events.
204
+ They are the stock Trajectory view's nested sub-call vocabulary; `deriveMessages()`
205
+ ignores them, so traces never enter model context.
206
+ - **Manual bridges:** `helpers.callTool` and `helpers.callModel` emit the same two events
207
+ directly. `helpers.tools()` lets LangGraph's prebuilt ToolNode call DSH tools; the
208
+ helper knows the real tool name where the ToolNode callback only exposes a wrapper.
209
+ - Traces are best-effort: a rejected append disables tracing for that run and never fails
210
+ the graph. Node/tool/model payloads are clipped at 4,000 characters. A direct helper
211
+ call inside a fan-out graph attaches to the most recently started node; LangChain
212
+ callbacks keep exact nesting for prebuilt agents.
213
+
214
+ ## Background runs
215
+
216
+ Set `run_in_background: true` on `langgraph_run`. The call returns before the graph starts:
217
+
218
+ ```json
219
+ { "kind": "background", "jobId": "langgraph-…", "graph": "typed-report", "thread": "lg_typed-report_…", "status": "started" }
220
+ ```
221
+
222
+ - The job is owned by the calling session; `job_kill` aborts the graph's `AbortController`,
223
+ which reaches `compiled.invoke`, node tool calls, and model calls.
224
+ - `job_output` returns the job's progress ring followed by the final run envelope. Progress
225
+ lines are `▶ langgraph:node scan`, `✓ langgraph:tool glob`, and so on.
226
+ - The returned `thread` is meaningful for a graph compiled with a checkpointer; a graph
227
+ that returns its own compiled graph without one fails the job and the thread is unused.
228
+ An interrupted background run reports `detail: "interrupted"` and can be resumed with the
229
+ returned `thread`.
230
+ - Trajectory still nests the node/tool/model sub-calls under the `langgraph_run` row, even
231
+ though those log-only events arrive after the tool result.
232
+ - Background runs require `ctx.jobs` (`@deepseek-ai/dsh-jobs-local` plus
233
+ `@deepseek-ai/dsh-tool-jobs` in the shipped profiles). Without them the call returns an
234
+ error naming the missing pieces.
235
+
236
+ ## Subagent delegation
237
+
238
+ A node can delegate one task to a DSH child agent:
239
+
240
+ ```ts
241
+ const result = await helpers.subagent('Read README.md and summarize it.', {
242
+ label: 'readme summary',
243
+ // provider: 'spawn', // default; row config `subagentProvider` overrides
244
+ // schema: { type: 'object', properties: { summary: { type: 'string' } }, required: ['summary'] },
245
+ })
246
+ return { summary: result.text, stopReason: result.stopReason }
247
+ ```
248
+
249
+ - `delivery: 'caller'` means no parent completion notice; the helper awaits and disposes the
250
+ activation. The child's final output is in `result.text` / `result.output`, with
251
+ `result.structured` when `schema` was supplied.
252
+ - The child is a real DSH agent with its own Session, tools, sandbox and model route. Its own
253
+ activity is visible in the child Session's Trajectory, not in the parent graph's model context.
254
+ - Trajectory shows the delegation as `langgraph:subagent` under the enclosing node, with
255
+ provider, label, prompt, output and stop reason.
256
+ - A graph node cannot start a nested LangGraph run; delegate that work to a subagent or another
257
+ top-level `langgraph_run` call instead.
258
+ - Requires `ctx.subagents` plus a registered provider. The default is `spawn`; set
259
+ `config.subagentProvider` or pass `provider` per call. A local child stays in the parent's
260
+ subagent catalog after disposal and can be continued with the usual subagent tools.
261
+ - **Shared tree, not a second registry.** The graph is not a subagent level: a
262
+ `helpers.subagent` child is a child of the DSH agent that called `langgraph_run`. It therefore
263
+ shares the parent's subagent tree, `maxActiveSubagents` capacity, child-name namespace, and
264
+ the profile's `maxDepth` policy with the model-facing `subagent` tool. At capacity it fails
265
+ with `ACTIVATION_LIMIT_REACHED`; at the depth limit it fails with `DEPTH_EXCEEDED`. Cancelling
266
+ the graph disposes the child through the activation signal.
267
+ - If a graph exposes the stock `subagent` tool through `helpers.tools(['subagent'])`, the model
268
+ inside LangGraph can call it. That is the stock tool path (`delivery: 'parent'`): the node
269
+ does not wait for the child, and the parent later receives a completion notice. Use
270
+ `helpers.subagent` when the graph needs the child's result to continue.
271
+
272
+ ## Asking the user
273
+
274
+ A node can ask a question through the same tool the model uses:
275
+
276
+ ```js
277
+ const { answers } = await helpers.askUser([
278
+ { id: 'ship', question: 'Ship it?', options: ['Yes', 'No'] },
279
+ { id: 'note', question: 'Anything to add?', header: 'Optional' },
280
+ ])
281
+ const ship = answers.find(answer => answer.id === 'ship')
282
+ ```
283
+
284
+ - DSH's stock `ask_user_question` tool renders the question, so the native question card
285
+ (options, free text, skip) is the whole UI. The helper normalizes short strings into
286
+ `{ label }` options and defaults a missing `id` to `q1`, `q2`, ….
287
+ - The result is `{ answers: [{ id, selected, custom? }] }`. For a single-select question
288
+ `custom` overrides `selected`; `selected: []` with no `custom` means the user skipped it
289
+ — continue without that answer and do not treat the skip as permission.
290
+ - The node waits for the answer. A profile without a question answerer fails with the
291
+ tool's error (`no user-questions answerer accepted the request`), and headless runs may
292
+ wait until the profile's question wait releases the turn.
293
+ - DSH rejects human interaction from subagent-origin sessions. Run the graph from a
294
+ top-level session when it needs to ask; a graph started inside a child agent should
295
+ return the question as its result instead.
296
+ - The ask is a normal tool call in this session and is traced as
297
+ `langgraph:tool ask_user_question` under the node.
298
+
299
+ ## Writing a graph (TypeScript or JavaScript)
300
+
301
+ ```ts
302
+ export const id = 'my-workflow'
303
+ export const description = 'One line the agent sees when it lists workflows.'
304
+ export const input = {
305
+ type: 'object',
306
+ properties: { pattern: { type: 'string', description: 'Glob to scan.' } },
307
+ additionalProperties: false,
308
+ }
309
+
310
+ export function build({ StateGraph, Annotation, START, END, helpers }) {
311
+ const State = Annotation.Root({
312
+ pattern: Annotation({ reducer: (_, b) => b, default: () => '**/*.md' }),
313
+ files: Annotation({ reducer: (_, b) => b, default: () => '' }),
314
+ })
315
+ // Return the uncompiled StateGraph: the plugin compiles it with the durable
316
+ // checkpointer. Returning a graph you compiled yourself opts out of durability.
317
+ return new StateGraph(State)
318
+ .addNode('scan', async state => ({ files: await helpers.callTool('glob', { pattern: state.pattern }) }))
319
+ .addEdge(START, 'scan')
320
+ .addEdge('scan', END)
321
+ }
322
+ ```
323
+
324
+ `build(api)` returns a `StateGraph` (preferred) or an already-compiled graph. The API
325
+ object carries the LangGraph namespace, `helpers`, `checkpointer`, and `store`.
326
+ Custom LangChain packages, vector stores, LangSmith, and streaming are covered in
327
+ [ECOSYSTEM.md](ECOSYSTEM.md).
328
+
329
+ On Node 24.22+ a `graphs/*.ts` module loads directly (Node's type stripping), so a typed
330
+ graph needs no build step. Keep to erasable syntax: no `enum`, `namespace`, parameter
331
+ properties, or decorators. The package exports `GraphApi` and `GraphModule` types; a
332
+ typed module can use `import type` and `defineGraph(module)` without importing the plugin
333
+ at runtime. Build with the `StateGraph`/`Annotation` from `api` rather than importing a
334
+ second copy of `@langchain/langgraph`; the plugin compiles the graph with its own
335
+ checkpointer and LangGraph instance. A `.js` graph remains the portable option for older
336
+ Node releases.
337
+
338
+ An interrupt gate:
339
+
340
+ ```ts
341
+ .addNode('gate', async () => ({ approved: interrupt({ question: 'Ship it?' }) }))
342
+ ```
343
+
344
+ ## Configuration
345
+
346
+ | key | meaning |
347
+ |---|---|
348
+ | `graphs` | extra `{ id, module }` entries; `module` is relative to the package or absolute |
349
+ | `recursionLimit` | default LangGraph superstep bound per run (default 25) |
350
+ | `model` | `{ provider, model, reasoningEffort }` used by `helpers.callModel`; defaults to the profile's selection |
351
+ | `trace` | log node/tool/model activity as Trajectory sub-calls (default `true`; `false` disables it) |
352
+ | `prompt` | register the model-facing system-prompt guidance with the graph list (default `true`) |
353
+ | `background` | expose `run_in_background` on `langgraph_run` (default `true`; `false` rejects the flag) |
354
+ | `subagentProvider` | default provider for `helpers.subagent` (default `spawn`; a per-call `provider` overrides it) |
355
+ | `store` | give graphs the long-term `BaseStore` (default `true`; `false` passes none) |
356
+ | `retention` | checkpoints kept per thread and namespace (default `200`; `0` keeps every checkpoint) |
357
+ | `ui` | serve the owner-only Web panel routes (default `true`; `false` registers none) |
358
+
359
+ Threads live in the `langgraph_checkpoints` storage domain (tables `checkpoints`,
360
+ `writes`, `threads`). `langgraph_threads({ action: 'delete', thread })` reclaims one.
361
+ Long-term memories live in `langgraph_store` (table `items`).
362
+
363
+ ## Limits
364
+
365
+ - Graphs run in the Host process, not in a separate sandbox: a node's blast radius is
366
+ what its DSH tool calls are allowed to do. DSH's `ctx.sandbox` confines shell and
367
+ filesystem execution, not JavaScript, so it is not an isolation boundary for a graph
368
+ module; the trust boundary is the graph author, like any installed plugin.
369
+ - Process-isolating a graph would need remote checkpointer, store, model, tool, question,
370
+ subagent, and trace bridges over IPC. Until such a worker exists, the plugin does not
371
+ pretend to offer it.
372
+ - Every stored checkpoint is loaded when the domain opens; loading is not lazy. History
373
+ is bounded per thread and namespace by `retention` (default 200), so a completed
374
+ thread cannot grow without bound; `retention: 0` keeps everything. Pruned checkpoints
375
+ cannot be read or replayed, so a graph that time-travels far back needs a larger
376
+ window or `0`. Delete finished threads you no longer need.
377
+ - The long-term store has no TTL or eviction: entries remain until the graph deletes
378
+ them. Vector search is not implemented, so `search({ query })` throws.
379
+ - `langgraph_threads` lists the calling session's threads by default; `all: true` lists
380
+ every session's.
381
+ - What a graph inherits from the agent: **tools**, resolved in the calling agent's scope,
382
+ but only those the graph names — `helpers.tools([...])` reads
383
+ `ctx.tools.definitions(agent)` and throws with the visible names when one is missing,
384
+ and `helpers.callTool` runs through the same executor. **Not inherited**: the session's
385
+ system prompt, and with it the skill catalog, the runtime context (cwd, date), and
386
+ AGENTS.md instructions. `helpers.chatModel()` therefore starts with no bound tools, and
387
+ a model call does not know the working directory — either pass `{ system }`, bind tools
388
+ explicitly, or let a DSH tool resolve a path in the session's cwd. To read a skill, call
389
+ the `skill` tool through `helpers.callTool` and pass its text to `helpers.callModel`,
390
+ or enumerate skills with `ctx.get('sessionSkillCatalog').list({ sessionId })`.
391
+ - A forked session inherits the session log, not the plugin's storage domain: threads do
392
+ not follow a fork.
393
+ - A run's internal work is trace-only, not model-visible. The outer `langgraph_run` call
394
+ is the model-facing `tool/call`/`tool/result` pair; node, tool, and model activity is
395
+ recorded as log-only `tool/ptc-dispatch-start` / `tool/ptc-dispatch` events and appears
396
+ in Trajectory, but `deriveMessages()` ignores it, so it never enters model context.
397
+ `helpers.callTool` still executes in the calling agent's scope (sandbox and approval
398
+ policy apply), and `helpers.callModel` uses the deployment route.
399
+ - A thread is owned by the graph and session that created it. Another session cannot
400
+ resume, read, or delete it; `langgraph_threads` lists only this session's threads by
401
+ default, and `all: true` is required for a cross-session listing.
402
+ - A node cannot start a nested LangGraph run; use `helpers.subagent` for a DSH child agent,
403
+ or call another top-level `langgraph_run`. `helpers.callModel` is text-only (no tool
404
+ calling inside that model request).
405
+ - A background run's trace events arrive after its `tool/result`; they are still log-only and
406
+ stay under the same Trajectory row while the session is live. If append fails — for example
407
+ a profile without the PTC event vocabulary — tracing disables for that run and the job's
408
+ output ring remains the progress record.
409
+ - The system-prompt guidance is global to the profile while the plugin is active. An agent
410
+ whose tool policy hides `langgraph_run` still sees the section; use `config.prompt: false`
411
+ in a profile/preset that should not advertise graphs.
412
+ - A subagent child has its own Session and tool scope. Its own tool/model activity is not in
413
+ the parent graph's model context; it may message the parent through tools the profile grants
414
+ (`send_message`), and it remains in the parent's subagent catalog after disposal.
415
+ - Seven example graphs ship in `graphs/`: `scan-report` (tool only), `typed-report`
416
+ (TypeScript, tool only), `ask-workspace` (tool plus one model call), `ask-tools`
417
+ (LangGraph's prebuilt ReAct agent over DSH tools and the DSH model), `ask-subagent`
418
+ (caller-delivered DSH child), `ask-user` (native question UI), and `approval-gate`
419
+ (an `interrupt()` that waits for a decision before it scans).
420
+ - LangGraph only accepts tools that are LangChain Runnables, so `helpers.tools()` builds
421
+ real `tool()` instances with a zod schema converted from the DSH tool's JSON schema; the
422
+ original JSON schema is what the chat model sends to the provider.
@@ -0,0 +1,134 @@
1
+ # Using the LangChain ecosystem
2
+
3
+ The plugin is a bridge, not a fork: LangGraph and LangChain stay the libraries you
4
+ already know, and DSH stays the runtime. This page covers the seams that are already
5
+ wired and how to add an integration that is not bundled.
6
+
7
+ ## What is already bridged
8
+
9
+ | Need | Use | Notes |
10
+ |---|---|---|
11
+ | Run a DSH tool from a node | `helpers.callTool(name, args)` | Same session, sandbox, approvals; traced as `langgraph:tool`. |
12
+ | Expose DSH tools to LangGraph | `helpers.tools([...names])` | Real LangChain `tool()` instances; visible names only. |
13
+ | One text completion | `helpers.callModel(prompt, options)` | Deployment model route; text only. |
14
+ | A LangChain chat model | `helpers.chatModel(options)` | Supports `bindTools`; reports usage. |
15
+ | Prebuilt ReAct agent | `helpers.createReactAgent(options)` | Wraps the DSH model and tools; returns an uncompiled graph. |
16
+ | Message classes | `helpers.messages` | `AIMessage`, `HumanMessage`, `SystemMessage`, `ToolMessage`. |
17
+ | Durable checkpoints | `api.checkpointer` | The plugin compiles your graph with it by default. |
18
+ | Long-term memory | `getStore(config)`, `api.store`, `helpers.store()` | `DshStore` over `langgraph_store`; filters/pagination, no vector search. |
19
+ | A DSH child agent | `helpers.subagent(prompt, options)` | Caller-delivered; shares the session's subagent tree. |
20
+ | Ask the user | `helpers.askUser(questions)` | Stock `ask_user_question` UI; no client code. |
21
+ | DSH Trajectory | automatic | LangGraph callbacks → log-only PTC events. |
22
+ | LangSmith | environment variables | Independent of the DSH trace; see below. |
23
+
24
+ ## Adding your own LangChain packages
25
+
26
+ A graph module is an ordinary ES module, so it can import any package resolvable from
27
+ its own location. Two practical rules:
28
+
29
+ - **Put custom graphs in their own package.** Declare the LangChain/LangGraph packages
30
+ you use there, then register the built file with
31
+ `config.graphs: [{ id, module: "/abs/path/to/graph.js" }]`. A module inside this
32
+ package resolves against this package's dependencies, which is convenient but couples
33
+ it to the plugin's versions.
34
+ - **Do not load a second `@langchain/core`.** LangChain and LangGraph use `instanceof`
35
+ and class identity across packages; two copies in one Host can reject each other's
36
+ messages and tools. Prefer the classes from `api` (`api.StateGraph`, `api.Annotation`,
37
+ `api.messages`, …) instead of importing a second copy, and pin one version of
38
+ `@langchain/core` in the Host.
39
+
40
+ The versions this plugin is built and tested against are in `package.json`:
41
+ `@langchain/core` 1.5, `@langchain/langgraph` 1.7, and
42
+ `@langchain/langgraph-checkpoint` 1.2.
43
+
44
+ ## Retrieval and vector stores
45
+
46
+ The built-in `DshStore` deliberately implements only the filter/pagination surface.
47
+ `search({ query })` throws instead of returning unranked rows, because a fake similarity
48
+ result is worse than no result.
49
+
50
+ For embeddings, compile the graph yourself with a store that implements them:
51
+
52
+ ```ts
53
+ import { InMemoryStore } from '@langchain/langgraph-checkpoint'
54
+ import { OpenAIEmbeddings } from '@langchain/openai'
55
+
56
+ export function build({ StateGraph, Annotation, START, END, checkpointer }) {
57
+ const store = new InMemoryStore({
58
+ index: {
59
+ embed: new OpenAIEmbeddings({ model: 'text-embedding-3-small' }),
60
+ dims: 1536,
61
+ },
62
+ })
63
+ return new StateGraph(State)
64
+ // … nodes …
65
+ .compile({ checkpointer, store })
66
+ }
67
+ ```
68
+
69
+ - Returning a compiled graph opts out of the plugin's automatic compile, including its
70
+ `DshStore`; pass `checkpointer` if you still want durable threads.
71
+ - `InMemoryStore` is process-local. A durable vector store (pgvector, a managed vector
72
+ service, …) needs its own package and client; pass it to `compile({ store })` the same
73
+ way.
74
+ - A graph can also keep a vector store in a module-level variable. Modules are cached for
75
+ the Host process, so the store survives runs but not restarts.
76
+ - The plugin's `api.store` / `helpers.store()` still point at the `DshStore`; a custom
77
+ compiled graph simply does not use them.
78
+
79
+ ## LangSmith
80
+
81
+ LangChain's own tracing is respected by the underlying runnables. Start the Host with:
82
+
83
+ ```bash
84
+ export LANGSMITH_TRACING=true
85
+ export LANGSMITH_API_KEY=...
86
+ export LANGSMITH_PROJECT=dsh-langgraph
87
+ ```
88
+
89
+ `LANGCHAIN_TRACING_V2` / `LANGCHAIN_API_KEY` are still accepted by the installed
90
+ `@langchain/core`. The plugin does not read or forward these variables.
91
+
92
+ - LangSmith and DSH Trajectory are independent traces: LangSmith sees LangGraph runnables,
93
+ models, and tool callbacks; DSH Trajectory sees one `langgraph_run` row with
94
+ `langgraph:node` / `langgraph:tool` / `langgraph:model` sub-calls.
95
+ - LangSmith captures prompts and outputs. Do not enable it for profiles that handle data
96
+ you cannot send to that account.
97
+ - This bridge was not exercised in this repository's tests (it needs an external key);
98
+ the environment variables are the ones the installed LangChain version reads.
99
+
100
+ ## Prebuilt agents and tools
101
+
102
+ `helpers.createReactAgent(options)` is LangGraph's prebuilt ReAct agent wired to the DSH
103
+ model and tools:
104
+
105
+ ```js
106
+ const agent = await helpers.createReactAgent({
107
+ llm: helpers.chatModel(),
108
+ tools: helpers.tools(['read', 'glob', 'bash']),
109
+ })
110
+ return agent // a StateGraph; the plugin compiles it with its checkpointer and store
111
+ ```
112
+
113
+ Pass the uncompiled graph back. LangGraph only accepts LangChain Runnables as tools, so
114
+ use `helpers.tools` rather than raw DSH tool names; the original DSH JSON schema is what
115
+ the model sees.
116
+
117
+ ## Streaming
118
+
119
+ A DSH tool returns one result, so `langgraph_run` cannot stream tokens into the model's
120
+ message. Two seams exist today:
121
+
122
+ - **Background runs** report node/tool progress through the job's output ring
123
+ (`job_output`), not tokens.
124
+ - **Inside a node**, `helpers.chatModel().stream()` and LangGraph's own streaming APIs
125
+ work as usual for the graph's own logic. Delivering those chunks to the DSH client is a
126
+ client-side feature (a separate view subscribing to session events), not something the
127
+ tool result can carry.
128
+
129
+ ## What is not a LangChain concern
130
+
131
+ - DSH's agent loop, permissions, sandbox, subagent tree, and question UI stay DSH's.
132
+ Graphs use them through helpers; they do not reimplement them.
133
+ - LangGraph Platform/Studio is not emulated. Threads and the store live in the DSH
134
+ storage domains; there is no hosted API or graph server.