@lzn1998/dsh-langgraph 0.5.0 → 1.0.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 CHANGED
@@ -1,4 +1,4 @@
1
- # LangGraph workflows
1
+ # LangGraph graphs
2
2
 
3
3
  Run a LangGraph graph from inside a DSH agent session, and continue it later.
4
4
 
@@ -6,7 +6,9 @@ Run a LangGraph graph from inside a DSH agent session, and continue it later.
6
6
 
7
7
  - `langgraph_run` — run a graph by id with an initial state. Omitting `graph` lists
8
8
  the registered graphs **with their input schemas**.
9
- - `langgraph_threads` — `list`, `state`, and `delete` durable threads.
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.
10
12
  - **Durable threads.** Every superstep is checkpointed in a DSH storage domain
11
13
  (`langgraph_checkpoints`), so a thread survives the turn and the Host process. Pass
12
14
  `thread` back to continue it; a profile without `storageDomain` falls back to an
@@ -14,6 +16,13 @@ Run a LangGraph graph from inside a DSH agent session, and continue it later.
14
16
  - **Interrupts.** A node that calls LangGraph's `interrupt(...)` stops the run; the tool
15
17
  reports `status: "interrupted"` with the payload, and
16
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.
17
26
  - **Background runs.** `run_in_background: true` registers the run on `ctx.jobs` and returns
18
27
  `{ kind: "background", jobId, thread }` immediately. The model reads progress and the final
19
28
  value with `job_output`, and stops it with `job_kill`; the graph keeps its thread and its
@@ -35,6 +44,142 @@ Run a LangGraph graph from inside a DSH agent session, and continue it later.
35
44
  and `helpers.createReactAgent({...})` is LangGraph's prebuilt ReAct agent wired to both.
36
45
  `helpers.messages` re-exports the LangChain message classes.
37
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 defines the vocabulary
51
+ (profile-registered graphs, not the `workflow` tool), the trigger policy (a named graph,
52
+ a description match, or a graph-specific need such as a durable thread, background job,
53
+ interrupt/resume, checkpoint replay, or Trajectory sub-calls), and the registry (up to 24
54
+ ids and descriptions; input schemas stay out of the prompt). The model therefore knows
55
+ what exists without spending a discovery call; `langgraph_run` with no `graph` still
56
+ returns the full list and input schemas.
57
+
58
+ - The section sits just before the subagent guidance, after the `workflow` tool's
59
+ "only when the user asks" rule. An earlier placement at `TOOL_WORKFLOW` made the two
60
+ "workflow" instructions read as one.
61
+ - Apart from the section and the two tool schemas, the plugin injects no runtime context;
62
+ per-session thread facts are read on demand with `langgraph_threads`. See
63
+ [CONTEXT.md](CONTEXT.md) for the mapping and the maintenance rules.
64
+
65
+ - The registry is scanned when the plugin activates, so graph modules should keep top-level
66
+ code side-effect free.
67
+ - The section text is a function: after the asynchronous scan completes, the next prompt
68
+ assembly replaces the short "call it to list" hint with the actual graph list.
69
+ - `config.prompt: false` disables the section (and the eager scan).
70
+ - The section is effect-owned: unloading the plugin retires the guidance.
71
+
72
+ ## Long-term store
73
+
74
+ Checkpoints belong to one thread; a store is shared memory. Every run is compiled with a
75
+ LangGraph `BaseStore` that survives the turn and the Host process:
76
+
77
+ ```ts
78
+ .addNode('remember', async (_state, config) => {
79
+ const store = getStore(config) // LangGraph's standard accessor
80
+ await store.put(['memories', userId], 'preference', { tone: 'concise' })
81
+ return { preference: (await store.get(['memories', userId], 'preference')).value.tone }
82
+ })
83
+ ```
84
+
85
+ `build(api)` also receives `api.store`, and `helpers.store()` returns the same instance.
86
+ Inside a node, `getStore(config)` is LangGraph's `AsyncBatchedStore` wrapper over that same
87
+ `DshStore` (LangGraph batches node writes), so the wrapper is still backed by this domain.
88
+
89
+ - Backed by the `langgraph_store` storage domain, one record per `(namespace, key)`;
90
+ writes resolve after the domain has accepted them.
91
+ - Supports `get`, `put`, `delete`, `search({ filter, limit, offset })`, and
92
+ `listNamespaces({ prefix, suffix, maxDepth, limit, offset })`. Filters cover dotted
93
+ field paths and `$eq`, `$ne`, `$gt`, `$gte`, `$lt`, `$lte`; search results are newest
94
+ first (then by key).
95
+ - Values must be JSON objects. Vector search (`search({ query })`) is rejected with a
96
+ clear error instead of returning unranked rows; use an embeddings-backed store when a
97
+ graph needs similarity.
98
+ - Without a `storageDomain` service the plugin uses `InMemoryStore`, so the graph still
99
+ runs and only loses memories at process exit. `config.store: false` passes no store
100
+ (`getStore(config)` returns `undefined` and `helpers.store()` is `undefined`).
101
+ - Long-term memory is separate from thread ownership: any run of any session sees the
102
+ same namespaces. Namespace the data yourself (for example by user or workspace) when
103
+ that matters.
104
+
105
+ ## Time travel
106
+
107
+ Every checkpoint is addressable, so a thread is not a write-only log:
108
+
109
+ ```text
110
+ langgraph_threads({ action: 'history', graph, thread }) → checkpoints, newest first
111
+ langgraph_threads({ action: 'state', graph, thread, checkpoint }) → values, next, interrupts
112
+ langgraph_threads({ action: 'edit', graph, thread, checkpoint, values }) → new checkpoint
113
+ langgraph_run({ graph, thread, checkpoint }) → replay from that snapshot
114
+ ```
115
+
116
+ - `history` returns `checkpoint`, `step`, `source`, `createdAt`, `next`, and `paused` for
117
+ each snapshot, newest first; `limit` defaults to 20 (max 200).
118
+ - `state` and `edit` default to the thread head. `edit` writes the given `values` on top
119
+ of that snapshot and returns the new checkpoint; `next` tells you what would run.
120
+ - `langgraph_run({ checkpoint })` uses `checkpoint_id` instead of the thread head. With no
121
+ `input` or `resume` it runs that snapshot's pending tasks. A checkpoint whose `next` is
122
+ empty has nothing to run, so a replay is a no-op; pick one from `history` that lists
123
+ the node you want to rerun, or edit it first.
124
+ - An edit creates a fork: the original checkpoints stay, and the thread head becomes the
125
+ fork when it is replayed. An unknown checkpoint id is rejected rather than treated as
126
+ an empty state.
127
+ - History is bounded by `retention` (default 200 checkpoints per thread); older
128
+ checkpoints and their writes are pruned, so a checkpoint that is no longer in `history`
129
+ cannot be replayed.
130
+
131
+ ## Topology
132
+
133
+ `langgraph_threads({ action: 'topology', graph })` compiles the graph and returns its
134
+ drawable structure without needing a thread:
135
+
136
+ ```json
137
+ {
138
+ "graph": "scan-report",
139
+ "description": "…",
140
+ "input": { "type": "object", "…": "…" },
141
+ "nodes": [{ "id": "__start__", "type": "schema" }, { "id": "scan", "type": "runnable", "name": "scan" }],
142
+ "edges": [{ "source": "__start__", "target": "scan" }, { "source": "scan", "target": "__end__" }]
143
+ }
144
+ ```
145
+
146
+ - The response is plain JSON (`Graph.toJSON()`), safe to hand to a client panel; a
147
+ conditional edge carries `conditional: true`.
148
+ - Compiling runs `build(api)`, so a graph module's build must stay side-effect free.
149
+ - This is the host half of the client view; it works from the model-facing tool and from
150
+ any host code that can call the tool. A dedicated topology panel is a client change
151
+ outside this package's host-only scope.
152
+
153
+ ## Web panel
154
+
155
+ In a Web profile the package's `dsh.client` entry loads `lib/client.js`, a browser bundle
156
+ that contributes a **LangGraph** sidebar row and a `main` panel. The panel shows:
157
+
158
+ - the registered graphs with their descriptions and per-graph durable-thread counts;
159
+ - the selected graph's topology from `Graph.toJSON()` — left-to-right columns, dashed
160
+ conditional edges, start/end nodes.
161
+
162
+ It reads two exact, owner-only routes registered through the public
163
+ `ctx.connection.fetch.register` service:
164
+
165
+ | route | answer |
166
+ |---|---|
167
+ | `GET /api/plugins/langgraph/ui` | `{ graphs, threads: { total, byGraph, durable } }` |
168
+ | `GET /api/plugins/langgraph/topology?graph=<id>` | the same payload as the `topology` action |
169
+
170
+ - The routes are optional: a headless Host has no `connection` service, so they are not
171
+ registered. `config.ui: false` disables them in a Web profile too.
172
+ - The panel is read-only and polls `/ui` every 5 seconds. It does not read Session logs,
173
+ thread contents, or tokens; run activity stays in Trajectory and `langgraph_threads`.
174
+ - The bundle imports only `react` and `react/jsx-runtime`, which the Web shell seeds into
175
+ its module table. Rebuild it with the TypeScript compiler from a DSH checkout:
176
+
177
+ ```bash
178
+ DSH_TYPESCRIPT=/path/to/deepseek-harness/node_modules/typescript npm run build:client
179
+ ```
180
+
181
+ `lib/client.js` is committed, so installing from npm needs no build step.
182
+
38
183
  ## Trajectory trace
39
184
 
40
185
  A run is not a black box. The `langgraph_run` row in **Trajectory** expands into the
@@ -133,11 +278,38 @@ return { summary: result.text, stopReason: result.stopReason }
133
278
  does not wait for the child, and the parent later receives a completion notice. Use
134
279
  `helpers.subagent` when the graph needs the child's result to continue.
135
280
 
281
+ ## Asking the user
282
+
283
+ A node can ask a question through the same tool the model uses:
284
+
285
+ ```js
286
+ const { answers } = await helpers.askUser([
287
+ { id: 'ship', question: 'Ship it?', options: ['Yes', 'No'] },
288
+ { id: 'note', question: 'Anything to add?', header: 'Optional' },
289
+ ])
290
+ const ship = answers.find(answer => answer.id === 'ship')
291
+ ```
292
+
293
+ - DSH's stock `ask_user_question` tool renders the question, so the native question card
294
+ (options, free text, skip) is the whole UI. The helper normalizes short strings into
295
+ `{ label }` options and defaults a missing `id` to `q1`, `q2`, ….
296
+ - The result is `{ answers: [{ id, selected, custom? }] }`. For a single-select question
297
+ `custom` overrides `selected`; `selected: []` with no `custom` means the user skipped it
298
+ — continue without that answer and do not treat the skip as permission.
299
+ - The node waits for the answer. A profile without a question answerer fails with the
300
+ tool's error (`no user-questions answerer accepted the request`), and headless runs may
301
+ wait until the profile's question wait releases the turn.
302
+ - DSH rejects human interaction from subagent-origin sessions. Run the graph from a
303
+ top-level session when it needs to ask; a graph started inside a child agent should
304
+ return the question as its result instead.
305
+ - The ask is a normal tool call in this session and is traced as
306
+ `langgraph:tool ask_user_question` under the node.
307
+
136
308
  ## Writing a graph (TypeScript or JavaScript)
137
309
 
138
310
  ```ts
139
- export const id = 'my-workflow'
140
- export const description = 'One line the agent sees when it lists workflows.'
311
+ export const id = 'my-graph'
312
+ export const description = 'One line the agent sees when it lists graphs.'
141
313
  export const input = {
142
314
  type: 'object',
143
315
  properties: { pattern: { type: 'string', description: 'Glob to scan.' } },
@@ -159,7 +331,9 @@ export function build({ StateGraph, Annotation, START, END, helpers }) {
159
331
  ```
160
332
 
161
333
  `build(api)` returns a `StateGraph` (preferred) or an already-compiled graph. The API
162
- object carries the LangGraph namespace, `helpers`, and `checkpointer`.
334
+ object carries the LangGraph namespace, `helpers`, `checkpointer`, and `store`.
335
+ Custom LangChain packages, vector stores, LangSmith, and streaming are covered in
336
+ [ECOSYSTEM.md](ECOSYSTEM.md).
163
337
 
164
338
  On Node 24.22+ a `graphs/*.ts` module loads directly (Node's type stripping), so a typed
165
339
  graph needs no build step. Keep to erasable syntax: no `enum`, `namespace`, parameter
@@ -184,18 +358,33 @@ An interrupt gate:
184
358
  | `recursionLimit` | default LangGraph superstep bound per run (default 25) |
185
359
  | `model` | `{ provider, model, reasoningEffort }` used by `helpers.callModel`; defaults to the profile's selection |
186
360
  | `trace` | log node/tool/model activity as Trajectory sub-calls (default `true`; `false` disables it) |
361
+ | `prompt` | register the model-facing system-prompt guidance with the graph list (default `true`) |
187
362
  | `background` | expose `run_in_background` on `langgraph_run` (default `true`; `false` rejects the flag) |
188
363
  | `subagentProvider` | default provider for `helpers.subagent` (default `spawn`; a per-call `provider` overrides it) |
364
+ | `store` | give graphs the long-term `BaseStore` (default `true`; `false` passes none) |
365
+ | `retention` | checkpoints kept per thread and namespace (default `200`; `0` keeps every checkpoint) |
366
+ | `ui` | serve the owner-only Web panel routes (default `true`; `false` registers none) |
189
367
 
190
368
  Threads live in the `langgraph_checkpoints` storage domain (tables `checkpoints`,
191
369
  `writes`, `threads`). `langgraph_threads({ action: 'delete', thread })` reclaims one.
370
+ Long-term memories live in `langgraph_store` (table `items`).
192
371
 
193
372
  ## Limits
194
373
 
195
374
  - 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.
375
+ what its DSH tool calls are allowed to do. DSH's `ctx.sandbox` confines shell and
376
+ filesystem execution, not JavaScript, so it is not an isolation boundary for a graph
377
+ module; the trust boundary is the graph author, like any installed plugin.
378
+ - Process-isolating a graph would need remote checkpointer, store, model, tool, question,
379
+ subagent, and trace bridges over IPC. Until such a worker exists, the plugin does not
380
+ pretend to offer it.
381
+ - Every stored checkpoint is loaded when the domain opens; loading is not lazy. History
382
+ is bounded per thread and namespace by `retention` (default 200), so a completed
383
+ thread cannot grow without bound; `retention: 0` keeps everything. Pruned checkpoints
384
+ cannot be read or replayed, so a graph that time-travels far back needs a larger
385
+ window or `0`. Delete finished threads you no longer need.
386
+ - The long-term store has no TTL or eviction: entries remain until the graph deletes
387
+ them. Vector search is not implemented, so `search({ query })` throws.
199
388
  - `langgraph_threads` lists the calling session's threads by default; `all: true` lists
200
389
  every session's.
201
390
  - What a graph inherits from the agent: **tools**, resolved in the calling agent's scope,
@@ -226,14 +415,17 @@ Threads live in the `langgraph_checkpoints` storage domain (tables `checkpoints`
226
415
  stay under the same Trajectory row while the session is live. If append fails — for example
227
416
  a profile without the PTC event vocabulary — tracing disables for that run and the job's
228
417
  output ring remains the progress record.
418
+ - The system-prompt guidance is global to the profile while the plugin is active. An agent
419
+ whose tool policy hides `langgraph_run` still sees the section; use `config.prompt: false`
420
+ in a profile/preset that should not advertise graphs.
229
421
  - A subagent child has its own Session and tool scope. Its own tool/model activity is not in
230
422
  the parent graph's model context; it may message the parent through tools the profile grants
231
423
  (`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`
424
+ - Seven example graphs ship in `graphs/`: `scan-report` (tool only), `typed-report`
233
425
  (TypeScript, tool only), `ask-workspace` (tool plus one model call), `ask-tools`
234
426
  (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).
427
+ (caller-delivered DSH child), `ask-user` (native question UI), and `approval-gate`
428
+ (an `interrupt()` that waits for a decision before it scans).
237
429
  - LangGraph only accepts tools that are LangChain Runnables, so `helpers.tools()` builds
238
430
  real `tool()` instances with a zod schema converted from the DSH tool's JSON schema; the
239
431
  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.
@@ -4,7 +4,7 @@
4
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
5
  </defs>
6
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>
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.6 — 运行时架构</text>
8
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
9
  <rect x="790" y="52" width="12" height="12" rx="3" fill="#eff6ff" stroke="#2563eb" stroke-width="1.5"/>
10
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>
@@ -169,11 +169,16 @@ function parseThreadKey(key) {
169
169
  export class DshCheckpointSaver extends BaseCheckpointSaver {
170
170
  /**
171
171
  * @param {object} domain - an open storage domain shaped by {@link DOMAIN}.
172
+ * @param {{ retention?: number }} [options] - checkpoints to keep per thread and
173
+ * namespace; `0` keeps every checkpoint. Defaults to 200.
172
174
  */
173
- constructor(domain) {
175
+ constructor(domain, options = {}) {
174
176
  super()
175
177
  /** @type {object} */
176
178
  this.domain = domain
179
+ const retention = options.retention
180
+ /** @type {number} checkpoints kept per thread and namespace; 0 means unlimited. */
181
+ this.retention = Number.isInteger(retention) && retention >= 0 ? retention : 200
177
182
  }
178
183
 
179
184
  /** @param {'checkpoints' | 'writes' | 'threads'} table - table name. @returns {any} the table handle. */
@@ -332,6 +337,7 @@ export class DshCheckpointSaver extends BaseCheckpointSaver {
332
337
  createdAt: Date.now(),
333
338
  })
334
339
  await this.touchThread(thread, 'checkpoints')
340
+ await this.prune(thread, ns)
335
341
  return { configurable: { thread_id: thread, checkpoint_ns: ns, checkpoint_id: checkpoint.id } }
336
342
  }
337
343
 
@@ -466,6 +472,64 @@ export class DshCheckpointSaver extends BaseCheckpointSaver {
466
472
  await table.update(key, current => ({ ...current, updatedAt: now, [field]: current[field] + 1 }))
467
473
  }
468
474
 
475
+ /**
476
+ * Keep only the newest `retention` checkpoints of one thread and namespace,
477
+ * deleting the checkpoints that fell out of the window together with their
478
+ * writes, and reconcile the thread's counters with what is actually stored.
479
+ *
480
+ * Retention is lossy by design: a pruned checkpoint can no longer be read or
481
+ * replayed, and a retained checkpoint's `parent` may point outside the window.
482
+ * That is why 0 (unlimited) is supported for graphs that need full history.
483
+ * @param {string} thread - thread id.
484
+ * @param {string} ns - checkpoint namespace.
485
+ */
486
+ async prune(thread, ns) {
487
+ if (this.retention <= 0) return
488
+ const rows = []
489
+ let threadCheckpoints = 0
490
+ for (const [key, record] of this.table('checkpoints').entries()) {
491
+ let parsed
492
+ try {
493
+ parsed = parseCheckpointKey(key)
494
+ } catch {
495
+ continue
496
+ }
497
+ if (parsed[0] !== thread) continue
498
+ threadCheckpoints += 1
499
+ if (parsed[1] === ns) rows.push({ key, id: parsed[2] })
500
+ }
501
+ if (rows.length <= this.retention) return
502
+ rows.sort((left, right) => (left.id < right.id ? 1 : left.id > right.id ? -1 : 0))
503
+ const removed = rows.slice(this.retention)
504
+ const removedIds = new Set(removed.map(row => row.id))
505
+ await this.table('checkpoints').deleteMany(removed.map(row => row.key))
506
+
507
+ const writeKeys = []
508
+ let threadWrites = 0
509
+ for (const key of this.table('writes').keys()) {
510
+ let parsed
511
+ try {
512
+ parsed = parseWritesKey(key)
513
+ } catch {
514
+ continue
515
+ }
516
+ if (parsed[0] !== thread) continue
517
+ if (parsed[1] === ns && removedIds.has(parsed[2])) writeKeys.push(key)
518
+ else threadWrites += 1
519
+ }
520
+ if (writeKeys.length > 0) await this.table('writes').deleteMany(writeKeys)
521
+
522
+ const table = this.table('threads')
523
+ const key = threadKey(thread)
524
+ if (table.get(key) !== undefined) {
525
+ await table.update(key, current => ({
526
+ ...current,
527
+ checkpoints: threadCheckpoints - removed.length,
528
+ writes: threadWrites,
529
+ }))
530
+ }
531
+ }
532
+
469
533
  /**
470
534
  * List known threads, newest first.
471
535
  * @param {{ sessionId?: string, graph?: string, limit?: number }} [options] - filters.
@@ -511,10 +575,11 @@ export class DshCheckpointSaver extends BaseCheckpointSaver {
511
575
  /**
512
576
  * Open the checkpoint domain.
513
577
  * @param {object} storageDomain - the `storageDomain` service.
578
+ * @param {{ retention?: number }} [options] - checkpoints to keep per thread and namespace.
514
579
  * @returns {Promise<{ saver: DshCheckpointSaver, close: () => Promise<void> }>} the open store.
515
580
  */
516
- export async function openCheckpointStore(storageDomain) {
581
+ export async function openCheckpointStore(storageDomain, options = {}) {
517
582
  const domain = await storageDomain.open(DOMAIN)
518
- const saver = new DshCheckpointSaver(domain)
583
+ const saver = new DshCheckpointSaver(domain, options)
519
584
  return { saver, close: () => domain.close() }
520
585
  }