@lzn1998/dsh-langgraph 0.5.0 → 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 CHANGED
@@ -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,133 @@ 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 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
+
38
174
  ## Trajectory trace
39
175
 
40
176
  A run is not a black box. The `langgraph_run` row in **Trajectory** expands into the
@@ -133,6 +269,33 @@ return { summary: result.text, stopReason: result.stopReason }
133
269
  does not wait for the child, and the parent later receives a completion notice. Use
134
270
  `helpers.subagent` when the graph needs the child's result to continue.
135
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
+
136
299
  ## Writing a graph (TypeScript or JavaScript)
137
300
 
138
301
  ```ts
@@ -159,7 +322,9 @@ export function build({ StateGraph, Annotation, START, END, helpers }) {
159
322
  ```
160
323
 
161
324
  `build(api)` returns a `StateGraph` (preferred) or an already-compiled graph. The API
162
- object carries the LangGraph namespace, `helpers`, and `checkpointer`.
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).
163
328
 
164
329
  On Node 24.22+ a `graphs/*.ts` module loads directly (Node's type stripping), so a typed
165
330
  graph needs no build step. Keep to erasable syntax: no `enum`, `namespace`, parameter
@@ -184,18 +349,33 @@ An interrupt gate:
184
349
  | `recursionLimit` | default LangGraph superstep bound per run (default 25) |
185
350
  | `model` | `{ provider, model, reasoningEffort }` used by `helpers.callModel`; defaults to the profile's selection |
186
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`) |
187
353
  | `background` | expose `run_in_background` on `langgraph_run` (default `true`; `false` rejects the flag) |
188
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) |
189
358
 
190
359
  Threads live in the `langgraph_checkpoints` storage domain (tables `checkpoints`,
191
360
  `writes`, `threads`). `langgraph_threads({ action: 'delete', thread })` reclaims one.
361
+ Long-term memories live in `langgraph_store` (table `items`).
192
362
 
193
363
  ## Limits
194
364
 
195
365
  - 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.
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.
199
379
  - `langgraph_threads` lists the calling session's threads by default; `all: true` lists
200
380
  every session's.
201
381
  - What a graph inherits from the agent: **tools**, resolved in the calling agent's scope,
@@ -226,14 +406,17 @@ Threads live in the `langgraph_checkpoints` storage domain (tables `checkpoints`
226
406
  stay under the same Trajectory row while the session is live. If append fails — for example
227
407
  a profile without the PTC event vocabulary — tracing disables for that run and the job's
228
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.
229
412
  - A subagent child has its own Session and tool scope. Its own tool/model activity is not in
230
413
  the parent graph's model context; it may message the parent through tools the profile grants
231
414
  (`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`
415
+ - Seven example graphs ship in `graphs/`: `scan-report` (tool only), `typed-report`
233
416
  (TypeScript, tool only), `ask-workspace` (tool plus one model call), `ask-tools`
234
417
  (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).
418
+ (caller-delivered DSH child), `ask-user` (native question UI), and `approval-gate`
419
+ (an `interrupt()` that waits for a decision before it scans).
237
420
  - LangGraph only accepts tools that are LangChain Runnables, so `helpers.tools()` builds
238
421
  real `tool()` instances with a zod schema converted from the DSH tool's JSON schema; the
239
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.
@@ -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
  }