@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/index.js ADDED
@@ -0,0 +1,1315 @@
1
+ /**
2
+ * LangGraph workflows as DSH tools, with durable threads.
3
+ *
4
+ * A graph module exports `id`, an optional `description`, an optional `input` JSON
5
+ * Schema for its initial state, and `build(api)` where `api` carries the LangGraph API
6
+ * plus `helpers` and the store's `checkpointer`. `helpers.callTool(name, args)` runs a
7
+ * real DSH tool in the calling agent's scope (same sandbox, approvals, session), so a
8
+ * graph coordinates DSH work instead of becoming a second runtime.
9
+ *
10
+ * Graphs are discovered from `graphs/*.js` in this package and from `config.graphs`
11
+ * (`[{ id, module }]`, `module` relative to this package or an absolute path).
12
+ *
13
+ * Runs are checkpointed in a DSH storage domain, so a thread can be resumed in a later
14
+ * turn — or a later Host process — with `langgraph_run({ graph, thread })`, and an
15
+ * interrupted graph resumes with `langgraph_run({ graph, thread, resume })`.
16
+ * @module dsh-langgraph
17
+ */
18
+
19
+ import { readdir } from 'node:fs/promises'
20
+ import { fileURLToPath, pathToFileURL } from 'node:url'
21
+ import * as langgraph from '@langchain/langgraph'
22
+ import { Command } from '@langchain/langgraph'
23
+ import { InMemoryStore, MemorySaver } from '@langchain/langgraph-checkpoint'
24
+ import { DshChatModel, AIMessage, HumanMessage, SystemMessage, ToolMessage } from './dsh-chat-model.js'
25
+ import { openCheckpointStore } from './dsh-checkpointer.js'
26
+ import { openDshStore } from './dsh-store.js'
27
+ import { createTracer } from './dsh-trace.js'
28
+ import { langchainTool } from './dsh-tools.js'
29
+
30
+ /**
31
+ * Identity helper for graph modules written in TypeScript.
32
+ *
33
+ * It is deliberately a runtime no-op: it gives an editor the `GraphModule` type
34
+ * from this package's declaration file without making a graph module import the
35
+ * plugin at runtime.
36
+ * @template {object} T
37
+ * @param {T} module - the graph module.
38
+ * @returns {T} the same module.
39
+ */
40
+ export function defineGraph(module) {
41
+ if (module === null || typeof module !== 'object') {
42
+ throw new TypeError('defineGraph(module): module must be an object')
43
+ }
44
+ return module
45
+ }
46
+
47
+ /** Loader plugin name. */
48
+ export const name = 'langgraph'
49
+
50
+ /** The tool registry is the only hard dependency; storage, `llm` and the default model are looked up optionally per call. */
51
+ export const inject = ['tools']
52
+
53
+ const RUN_TOOL = 'langgraph_run'
54
+ const THREADS_TOOL = 'langgraph_threads'
55
+ const DEFAULT_RECURSION_LIMIT = 25
56
+ let callSeq = 0
57
+
58
+ /** Tail of the in-process queue for each thread id. */
59
+ const threadQueues = new Map()
60
+
61
+ /**
62
+ * Serialize work on one durable thread. Distinct threads stay independent; the
63
+ * storage domain already serializes its own writes, but a graph run also reads
64
+ * state and compiles a graph, so two runs of the same thread must not interleave.
65
+ * @template T
66
+ * @param {string | undefined} thread - thread id, or undefined for a one-off run.
67
+ * @param {() => Promise<T> | T} work - work to run.
68
+ * @returns {Promise<T>} the work's result.
69
+ */
70
+ async function withThreadLock(thread, work) {
71
+ if (thread === undefined) return await work()
72
+ const previous = threadQueues.get(thread) ?? Promise.resolve()
73
+ let release
74
+ const gate = new Promise(resolve => { release = resolve })
75
+ const tail = previous.then(() => gate)
76
+ threadQueues.set(thread, tail)
77
+ await previous.catch(() => {})
78
+ try {
79
+ return await work()
80
+ } finally {
81
+ release()
82
+ if (threadQueues.get(thread) === tail) threadQueues.delete(thread)
83
+ }
84
+ }
85
+
86
+ /** JSON-safe copy of a LangGraph state object. */
87
+ function toJsonSafe(value) {
88
+ try {
89
+ return JSON.parse(JSON.stringify(value, (_key, item) => (typeof item === 'bigint' ? String(item) : item)))
90
+ } catch {
91
+ return String(value)
92
+ }
93
+ }
94
+
95
+ /** Concatenated text of one DSH tool result's content blocks. */
96
+ function textOf(result) {
97
+ const content = result?.content ?? []
98
+ const text = content
99
+ .filter(block => block?.type === 'text' && typeof block.text === 'string')
100
+ .map(block => block.text)
101
+ .join('\n')
102
+ return text.trim()
103
+ }
104
+
105
+ /** Whether a graph module returned an already-compiled graph. */
106
+ function isCompiled(graph) {
107
+ return typeof graph?.invoke === 'function'
108
+ }
109
+
110
+ /** Remove LangGraph's interrupt carrier from a returned state map. */
111
+ function withoutInterrupts(state) {
112
+ if (state === null || typeof state !== 'object') return state
113
+ const { __interrupt__, ...rest } = state
114
+ return rest
115
+ }
116
+
117
+ /** One-line rendering of a graph's input schema for the agent-facing listing. */
118
+ function describeInput(entry) {
119
+ if (entry.input === undefined) return undefined
120
+ try {
121
+ return JSON.stringify(entry.input)
122
+ } catch {
123
+ return undefined
124
+ }
125
+ }
126
+
127
+ /**
128
+ * Render the model-facing graph guidance. It is a system-prompt section rather
129
+ * than a second tool: the model should know which graphs exist before deciding
130
+ * to call `langgraph_run`. Input schemas stay out of the prompt; the tool's
131
+ * no-argument listing returns them on demand.
132
+ * @param {Map<string, object>} registry - graph registry.
133
+ * @param {boolean} ready - whether the initial registry scan has completed.
134
+ * @returns {string} section text.
135
+ */
136
+ export function renderGraphPrompt(registry, ready) {
137
+ const intro = 'LangGraph workflows are available through the `langgraph_run` tool.'
138
+ if (!ready) {
139
+ return `${intro} Call it with no \`graph\` to list the registered workflows and their input schemas.`
140
+ }
141
+ const available = [...registry.values()]
142
+ .filter(entry => entry.error === undefined)
143
+ .sort((left, right) => left.id.localeCompare(right.id))
144
+ if (available.length === 0) {
145
+ return `${intro}\n\nNo workflow is registered yet; call it with no \`graph\` to re-check.`
146
+ }
147
+ const limit = 24
148
+ const lines = available.slice(0, limit).map(entry => {
149
+ const description = typeof entry.description === 'string' ? entry.description.replace(/\s+/g, ' ').trim() : ''
150
+ return `- ${entry.id}${description === '' ? '' : `: ${description}`}`
151
+ })
152
+ if (available.length > limit) {
153
+ lines.push(`- … and ${available.length - limit} more; call \`langgraph_run\` with no graph for the full list.`)
154
+ }
155
+ return [
156
+ intro,
157
+ 'Use it when a task benefits from durable multi-step execution, background runs, '
158
+ + 'interrupts/resume, or traced node/tool/model activity. '
159
+ + 'Use `langgraph_threads` to list, inspect, or delete durable threads.',
160
+ `Registered workflows:\n${lines.join('\n')}`,
161
+ 'Omit `graph` to see each workflow\'s input schema.',
162
+ ].join('\n\n')
163
+ }
164
+
165
+ /**
166
+ * Register the graph tools and the graph registry for one activation.
167
+ * @param {import('@deepseek-ai/cordis').Context} ctx - the plugin's context.
168
+ * @param {{ graphs?: { id?: string, module: string }[], recursionLimit?: number, model?: { provider?: string, model?: string, reasoningEffort?: string }, store?: boolean, retention?: number }} [config]
169
+ * row config: extra graph modules, the default LangGraph recursion limit, the
170
+ * model route graph nodes use through `helpers.callModel` (defaults to this
171
+ * deployment's selected model), whether graphs get a long-term BaseStore
172
+ * (`store: false` passes none), and how many checkpoints each thread keeps
173
+ * (default 200; `0` is unlimited).
174
+ */
175
+ export function apply(ctx, config) {
176
+ const extra = Array.isArray(config?.graphs) ? config.graphs : []
177
+ const recursionLimit = Number.isInteger(config?.recursionLimit) ? config.recursionLimit : DEFAULT_RECURSION_LIMIT
178
+ const configuredModel = config?.model ?? {}
179
+ const traceEnabled = config?.trace !== false
180
+ const promptEnabled = config?.prompt !== false
181
+ const backgroundEnabled = config?.background !== false
182
+ const storeEnabled = config?.store !== false
183
+ // Keep bounded thread history by default; 0 keeps every checkpoint, which a
184
+ // graph that time-travels further back needs.
185
+ const retention = Number.isInteger(config?.retention) && config.retention >= 0 ? config.retention : 200
186
+ const uiEnabled = config?.ui !== false
187
+ const configuredSubagentProvider = typeof config?.subagentProvider === 'string' && config.subagentProvider !== ''
188
+ ? config.subagentProvider
189
+ : 'spawn'
190
+ /** id -> { id, description, input, build } | { id, error } */
191
+ const registry = new Map()
192
+ let scanned
193
+
194
+ // --- durable checkpoint store -------------------------------------------------
195
+ // The domain opens once per activation, on the first call that needs it, so a
196
+ // `storageDomain` mounted after this plugin is still found. A profile without it
197
+ // still gets working threads through `MemorySaver`, but they end with the process.
198
+ let opened
199
+ let openFailure
200
+ let openedGraphStore
201
+ let disposed = false
202
+ ctx.effect(() => () => {
203
+ disposed = true
204
+ if (opened !== undefined) void opened.close()
205
+ if (openedGraphStore !== undefined) void openedGraphStore.close()
206
+ })
207
+
208
+ /** @type {Promise<object | undefined> | undefined} */
209
+ let storePromise
210
+ /** @type {import('@langchain/langgraph-checkpoint').MemorySaver | undefined} */
211
+ let memorySaver
212
+ /** thread id -> { graph, sessionId } for the in-process fallback store. */
213
+ const memoryThreads = new Map()
214
+
215
+ /** Open the checkpoint store once, or resolve undefined when the profile has none. */
216
+ function openStore() {
217
+ storePromise ??= (async () => {
218
+ const storageDomain = ctx.get('storageDomain')
219
+ if (storageDomain === undefined) {
220
+ openFailure = new Error('the storageDomain service is unavailable in this profile')
221
+ return undefined
222
+ }
223
+ try {
224
+ const store = await openCheckpointStore(storageDomain, { retention })
225
+ if (disposed) {
226
+ await store.close()
227
+ return undefined
228
+ }
229
+ opened = store
230
+ return store
231
+ } catch (error) {
232
+ openFailure = error
233
+ return undefined
234
+ }
235
+ })()
236
+ return storePromise
237
+ }
238
+
239
+ /** The saver for one run plus whether threads outlive the process. */
240
+ async function ensureSaver() {
241
+ const store = await openStore()
242
+ if (store !== undefined) return { saver: store.saver, durable: true, store: store.saver }
243
+ memorySaver ??= new MemorySaver()
244
+ return { saver: memorySaver, durable: false, store: undefined }
245
+ }
246
+
247
+ // --- long-term store ----------------------------------------------------------
248
+ // The store is a second domain, opened lazily for the same reason. A profile
249
+ // without `storageDomain` gets an InMemoryStore, so a graph that uses memory
250
+ // still runs; only its memories end with the process.
251
+ /** @type {Promise<object | undefined> | undefined} */
252
+ let graphStorePromise
253
+ /** @type {import('@langchain/langgraph-checkpoint').InMemoryStore | undefined} */
254
+ let memoryGraphStore
255
+ let graphStoreFailure
256
+
257
+ /** Open the durable BaseStore once, or resolve undefined without a storage domain. */
258
+ function openGraphStore() {
259
+ graphStorePromise ??= (async () => {
260
+ const storageDomain = ctx.get('storageDomain')
261
+ if (storageDomain === undefined) return undefined
262
+ try {
263
+ const openedStore = await openDshStore(storageDomain)
264
+ if (disposed) {
265
+ await openedStore.close()
266
+ return undefined
267
+ }
268
+ openedGraphStore = openedStore
269
+ return openedStore.store
270
+ } catch (error) {
271
+ graphStoreFailure = error
272
+ ctx.logger?.warn(`langgraph: durable store unavailable, falling back to memory: ${error?.message ?? error}`)
273
+ return undefined
274
+ }
275
+ })()
276
+ return graphStorePromise
277
+ }
278
+
279
+ /** The BaseStore for one run plus whether it outlives the process. */
280
+ async function ensureGraphStore() {
281
+ if (!storeEnabled) return { store: undefined, durableStore: false }
282
+ const store = await openGraphStore()
283
+ if (store !== undefined) return { store, durableStore: true }
284
+ memoryGraphStore ??= new InMemoryStore()
285
+ return { store: memoryGraphStore, durableStore: false }
286
+ }
287
+
288
+ /**
289
+ * Why this caller may not use a thread, or undefined when it may. A durable
290
+ * thread is owned by the graph and session that created it; resuming it from
291
+ * another session or as another graph would mix two runs' state.
292
+ * @param {object | undefined} store - the durable saver, when one is open.
293
+ * @param {string} thread - thread id.
294
+ * @param {string | undefined} sessionId - calling session.
295
+ * @param {string | undefined} graph - graph the caller wants to run.
296
+ * @returns {string | undefined} a model-facing error.
297
+ */
298
+ function threadConflict(store, thread, sessionId, graph) {
299
+ const meta = store === undefined ? memoryThreads.get(thread) : store.threadMeta(thread)
300
+ if (meta === undefined) return undefined
301
+ if (typeof meta.graph === 'string' && graph !== undefined && meta.graph !== graph) {
302
+ return `thread "${thread}" belongs to graph "${meta.graph}", not "${graph}"`
303
+ }
304
+ if (meta.sessionId !== null && meta.sessionId !== undefined && meta.sessionId !== sessionId) {
305
+ return `thread "${thread}" belongs to another session`
306
+ }
307
+ return undefined
308
+ }
309
+
310
+ /**
311
+ * Record ownership for the in-process fallback store, or return a conflict.
312
+ * @param {string} thread - thread id.
313
+ * @param {{ graph: string, sessionId?: string }} meta - owner facts.
314
+ * @returns {string | undefined} a model-facing error on conflict.
315
+ */
316
+ function claimMemoryThread(thread, meta) {
317
+ const conflict = threadConflict(undefined, thread, meta.sessionId, meta.graph)
318
+ if (conflict !== undefined) return conflict
319
+ const existing = memoryThreads.get(thread)
320
+ if (existing === undefined) {
321
+ memoryThreads.set(thread, { graph: meta.graph, sessionId: meta.sessionId ?? null })
322
+ } else if (meta.sessionId !== undefined) {
323
+ existing.sessionId = meta.sessionId
324
+ }
325
+ return undefined
326
+ }
327
+
328
+ // --- graph registry -----------------------------------------------------------
329
+ async function scan() {
330
+ if (scanned) return scanned
331
+ scanned = (async () => {
332
+ const dir = new URL('./graphs/', import.meta.url)
333
+ let files = []
334
+ try {
335
+ files = (await readdir(dir))
336
+ .filter(file => file.endsWith('.js') || file.endsWith('.mjs') || (file.endsWith('.ts') && !file.endsWith('.d.ts')))
337
+ .sort()
338
+ } catch (error) {
339
+ if (error?.code !== 'ENOENT') throw error
340
+ }
341
+ const sources = [
342
+ ...files.map(file => ({ module: fileURLToPath(new URL(file, dir)) })),
343
+ ...extra.map(entry => ({ id: entry.id, module: entry.module })),
344
+ ]
345
+ for (const source of sources) {
346
+ let url
347
+ try {
348
+ url = source.module.startsWith('.')
349
+ ? new URL(source.module, import.meta.url)
350
+ : pathToFileURL(source.module)
351
+ } catch (error) {
352
+ registry.set(source.id ?? source.module, { id: source.id ?? source.module, error })
353
+ continue
354
+ }
355
+ try {
356
+ const module = await import(url.href)
357
+ const id = source.id ?? module.id
358
+ if (typeof id !== 'string' || id === '') throw new Error('graph module must export a string `id`')
359
+ if (typeof module.build !== 'function') throw new Error('graph module must export `build(api)`')
360
+ registry.set(id, { id, description: module.description, input: module.input, build: module.build })
361
+ } catch (error) {
362
+ registry.set(source.id ?? source.module, { id: source.id ?? source.module, error })
363
+ }
364
+ }
365
+ return registry
366
+ })()
367
+ return scanned
368
+ }
369
+
370
+ /** Resolve the model route for one call: explicit request, row config, then the deployment default. */
371
+ function resolveRoute(requested) {
372
+ const llm = ctx.get('llm')
373
+ if (llm === undefined) throw new Error('the llm service is unavailable in this profile')
374
+ const selection = ctx.get('agentDefaultModel')?.currentSelection?.() ?? {}
375
+ const provider = requested?.provider ?? configuredModel.provider ?? selection.provider
376
+ const model = requested?.model ?? configuredModel.model ?? selection.model
377
+ if (typeof provider !== 'string' || typeof model !== 'string') {
378
+ throw new Error('no model route: set config.model.provider/model or ask for one explicitly')
379
+ }
380
+ const reasoningEffort = requested?.reasoningEffort ?? configuredModel.reasoningEffort ?? selection.reasoningEffort
381
+ return { llm, provider, model, reasoningEffort }
382
+ }
383
+
384
+ /** Helpers bound to one run: they close over the calling agent and its cancellation. */
385
+ function createHelpers(exec, tracer, store) {
386
+ const agent = exec?.agent
387
+ const signal = exec?.signal ?? new AbortController().signal
388
+ const helpersRef = {
389
+
390
+ agent,
391
+ sessionId: agent?.id,
392
+ /**
393
+ * The LangGraph long-term store for this run. With a storage domain it is
394
+ * durable across turns and Host processes; otherwise it is an InMemoryStore.
395
+ * @returns {object | undefined} the BaseStore, or undefined when `config.store` is false.
396
+ */
397
+ store() {
398
+ return store
399
+ },
400
+ /** LangChain message classes, so a graph module needs no LangChain dependency of its own. */
401
+ messages: { AIMessage, HumanMessage, SystemMessage, ToolMessage },
402
+ /**
403
+ * A LangChain chat model over this deployment's model route; supports `bindTools`.
404
+ * @param {{ provider?: string, model?: string, reasoningEffort?: string }} [options]
405
+ * @returns {DshChatModel} the model.
406
+ */
407
+ chatModel(options = {}) {
408
+ const route = resolveRoute(options)
409
+ return new DshChatModel({
410
+ stream: options2 => route.llm.stream(options2),
411
+ route: { provider: route.provider, model: route.model, ...(route.reasoningEffort === undefined ? {} : { reasoningEffort: route.reasoningEffort }) },
412
+ ...(agent === undefined ? {} : { sessionId: agent.id }),
413
+ signal,
414
+ })
415
+ },
416
+ /**
417
+ * Wrap DSH tools as LangChain tools, so a LangGraph prebuilt agent can call them.
418
+ * @param {string[]} names - tool names visible to this agent.
419
+ * @returns {object[]} LangChain tools; each call runs the DSH tool in this scope.
420
+ */
421
+ tools(names) {
422
+ const visible = new Map(ctx.tools.definitions(agent).map(definition => [definition.name, definition]))
423
+ const built = []
424
+ for (const toolName of names) {
425
+ const definition = visible.get(toolName)
426
+ if (definition === undefined) {
427
+ throw new Error(`tool "${toolName}" is not visible to this agent; visible: ${[...visible.keys()].sort().join(', ')}`)
428
+ }
429
+ // LangGraph's prebuilt ToolNode serializes its wrapper, not the tool,
430
+ // so its callback cannot name this call. The helper knows the real
431
+ // name; the tracer skips the unnamed callback to avoid a second row.
432
+ built.push(langchainTool(definition, (name, args) => helpersRef.callTool(name, args)))
433
+ }
434
+ return built
435
+ },
436
+ /**
437
+ * LangGraph's prebuilt ReAct agent, using the helpers above.
438
+ * @param {object} options - the prebuilt options; `llm` defaults to `chatModel()`.
439
+ * @returns {object} a compiled graph.
440
+ */
441
+ async createReactAgent(options = {}) {
442
+ const { createReactAgent } = await import('@langchain/langgraph/prebuilt')
443
+ return createReactAgent({ llm: options.llm ?? this.chatModel(), ...options })
444
+ },
445
+ /**
446
+ * One text completion on this deployment's model, from inside a graph node.
447
+ * @param {string} prompt - user text for this call.
448
+ * @param {{ system?: string, provider?: string, model?: string, reasoningEffort?: string, temperature?: number, maxTokens?: number }} [options]
449
+ * @returns {Promise<{ text: string, usage?: object }>}
450
+ */
451
+ async callModel(prompt, options = {}) {
452
+ if (typeof prompt !== 'string' || prompt.trim() === '') throw new Error('callModel needs a non-empty prompt string')
453
+ const route = resolveRoute(options)
454
+ const trace = tracer?.begin('langgraph:model', {
455
+ provider: route.provider,
456
+ model: route.model,
457
+ ...(options.system === undefined ? {} : { system: options.system }),
458
+ prompt,
459
+ })
460
+ try {
461
+ const messages = [{ role: 'user', content: [{ type: 'text', text: prompt }] }]
462
+ let text = ''
463
+ let usage
464
+ for await (const chunk of route.llm.stream({
465
+ provider: route.provider,
466
+ model: route.model,
467
+ messages,
468
+ ...(options.system === undefined ? {} : { system: options.system }),
469
+ ...(options.temperature === undefined ? {} : { temperature: options.temperature }),
470
+ ...(options.maxTokens === undefined ? {} : { maxTokens: options.maxTokens }),
471
+ ...(route.reasoningEffort === undefined ? {} : { reasoningEffort: route.reasoningEffort }),
472
+ ...(agent === undefined ? {} : { sessionId: agent.id }),
473
+ signal,
474
+ })) {
475
+ if (chunk.type === 'text-delta') text += chunk.text
476
+ else if (chunk.type === 'usage') usage = chunk.usage
477
+ else if (chunk.type === 'finish' && chunk.reason.kind === 'error') {
478
+ throw new Error(`model call failed: ${chunk.reason.failure.message}`)
479
+ }
480
+ }
481
+ tracer?.finish(trace, {
482
+ content: [{ type: 'text', text: text.trim() }],
483
+ ...(usage === undefined ? {} : { meta: { usage } }),
484
+ })
485
+ return { text: text.trim(), ...(usage === undefined ? {} : { usage }) }
486
+ } catch (error) {
487
+ tracer?.finish(trace, {
488
+ isError: true,
489
+ content: [{ type: 'text', text: String(error?.message ?? error) }],
490
+ error: { name: error?.name ?? 'Error', code: 'LANGGRAPH_MODEL_ERROR' },
491
+ })
492
+ throw error
493
+ }
494
+ },
495
+ /** Run one DSH tool in the calling agent's scope and return its text content. */
496
+ async callTool(toolName, args = {}, options = {}) {
497
+ const trace = options.trace === false ? undefined : tracer?.begin(`langgraph:tool ${toolName}`, args)
498
+ let batch
499
+ try {
500
+ batch = await ctx.tools.execute({
501
+ calls: [{
502
+ type: 'tool-call',
503
+ id: `${RUN_TOOL}-${Date.now()}-${callSeq++}`,
504
+ name: toolName,
505
+ arguments: JSON.stringify(args ?? {}),
506
+ }],
507
+ signal,
508
+ ...(agent === undefined ? {} : { agent }),
509
+ })
510
+ } catch (error) {
511
+ tracer?.finish(trace, {
512
+ isError: true,
513
+ content: [{ type: 'text', text: String(error?.message ?? error) }],
514
+ error: { name: error?.name ?? 'Error', code: 'LANGGRAPH_TOOL_ERROR' },
515
+ })
516
+ throw error
517
+ }
518
+ const settled = batch.results[0]?.result
519
+ const text = textOf(settled)
520
+ if (settled?.isError === true) {
521
+ tracer?.finish(trace, {
522
+ isError: true,
523
+ content: settled?.content ?? [{ type: 'text', text }],
524
+ ...(settled?.error?.info === undefined ? {} : { error: settled.error.info }),
525
+ })
526
+ throw new Error(text === '' ? `tool "${toolName}" failed` : text)
527
+ }
528
+ tracer?.finish(trace, { content: settled?.content ?? [{ type: 'text', text }] })
529
+ return text
530
+ },
531
+ /**
532
+ * Ask the user through DSH's native `ask_user_question` tool. The question
533
+ * renders in the stock question UI, so no client code is needed; the call
534
+ * blocks the node until the user answers (or the profile's wait times out).
535
+ * @param {Array<{ id?: string, question: string, header?: string, options?: Array<string | { label: string, description?: string }>, multi_select?: boolean }>} questions
536
+ * one or more questions; a missing `id` becomes `q1`, `q2`, …
537
+ * @returns {Promise<{ answers: Array<{ id: string, selected: string[], custom?: string }> }>}
538
+ * one answer per question; `selected: []` with no `custom` means the user skipped it.
539
+ */
540
+ async askUser(questions) {
541
+ if (!Array.isArray(questions) || questions.length === 0) {
542
+ throw new Error('askUser needs at least one question')
543
+ }
544
+ const normalized = questions.map((question, index) => {
545
+ if (question === null || typeof question !== 'object') {
546
+ throw new Error(`askUser: question ${index + 1} must be an object`)
547
+ }
548
+ if (typeof question.question !== 'string' || question.question.trim() === '') {
549
+ throw new Error(`askUser: question ${index + 1} needs a non-empty \`question\``)
550
+ }
551
+ const id = typeof question.id === 'string' && question.id !== '' ? question.id : `q${index + 1}`
552
+ const options = question.options === undefined ? undefined : question.options.map((option, optionIndex) => {
553
+ if (typeof option === 'string') return { label: option }
554
+ if (option === null || typeof option !== 'object' || typeof option.label !== 'string') {
555
+ throw new Error(`askUser: option ${optionIndex + 1} of question "${id}" needs a label`)
556
+ }
557
+ return { label: option.label, ...(option.description === undefined ? {} : { description: option.description }) }
558
+ })
559
+ return {
560
+ id,
561
+ question: question.question,
562
+ ...(question.header === undefined ? {} : { header: question.header }),
563
+ ...(options === undefined ? {} : { options }),
564
+ ...(question.multi_select === undefined ? {} : { multi_select: question.multi_select }),
565
+ }
566
+ })
567
+ const text = await helpersRef.callTool('ask_user_question', { questions: normalized })
568
+ let parsed
569
+ try {
570
+ parsed = JSON.parse(text)
571
+ } catch {
572
+ throw new Error(`askUser: unexpected answer format: ${text.slice(0, 500)}`)
573
+ }
574
+ if (!Array.isArray(parsed?.answers)) {
575
+ throw new Error(`askUser: unexpected answer format: ${text.slice(0, 500)}`)
576
+ }
577
+ return {
578
+ answers: parsed.answers.map(answer => ({
579
+ id: String(answer?.id ?? ''),
580
+ selected: Array.isArray(answer?.selected) ? answer.selected.map(String) : [],
581
+ ...(typeof answer?.custom === 'string' ? { custom: answer.custom } : {}),
582
+ })),
583
+ }
584
+ },
585
+ /**
586
+ * Delegate one task to a DSH subagent from inside a graph node.
587
+ *
588
+ * The child is caller-delivered: it emits no parent completion notice, and
589
+ * this helper awaits and disposes the exact activation. The child gets its
590
+ * own Session and tool scope, so a graph can fan work out without making
591
+ * the graph itself the agent loop.
592
+ * @param {string} prompt - the child's initial task.
593
+ * @param {{ provider?: string, label?: string, name?: string, cwd?: string, agentPreset?: string, agentOptions?: object, schema?: object }} [options]
594
+ * @returns {Promise<{ text: string, output: object[], structured?: unknown, stopReason: string, name: string, childId: string }>}
595
+ */
596
+ async subagent(prompt, options = {}) {
597
+ if (typeof prompt !== 'string' || prompt.trim() === '') throw new Error('subagent needs a non-empty prompt string')
598
+ if (agent === undefined) throw new Error('subagent needs a calling agent')
599
+ const subagents = ctx.get('subagents')
600
+ if (subagents === undefined) throw new Error('the subagents service is unavailable in this profile')
601
+ const provider = typeof options.provider === 'string' && options.provider !== ''
602
+ ? options.provider
603
+ : configuredSubagentProvider
604
+ // Respect the profile's delegation depth policy, the same one the
605
+ // model-facing subagent tool resolves; a graph must not bypass it.
606
+ const maxDepth = typeof subagents.resolveMaxDepth === 'function' ? subagents.resolveMaxDepth() : undefined
607
+ const trace = tracer?.begin('langgraph:subagent', {
608
+ provider,
609
+ ...(options.label === undefined ? {} : { label: options.label }),
610
+ ...(maxDepth === undefined ? {} : { maxDepth }),
611
+ prompt,
612
+ })
613
+ let started
614
+ let disposeChild
615
+ try {
616
+ started = await subagents.startActivation({
617
+ provider,
618
+ label: options.label ?? `langgraph:${agent.id}`,
619
+ ...(options.name === undefined ? {} : { name: options.name }),
620
+ prompt: [{ type: 'text', text: prompt }],
621
+ parent: agent,
622
+ signal,
623
+ delivery: 'caller',
624
+ ...(maxDepth === undefined ? {} : { maxDepth }),
625
+ ...(options.schema === undefined ? {} : { outputSchema: options.schema }),
626
+ ...(options.cwd === undefined ? {} : { cwd: options.cwd }),
627
+ ...(options.agentPreset === undefined ? {} : { agentPreset: options.agentPreset }),
628
+ ...(options.agentOptions === undefined ? {} : { agentOptions: options.agentOptions }),
629
+ })
630
+ // A published activation is not cancelled by the caller signal alone;
631
+ // dispose it on abort so cancelling the graph also stops the child.
632
+ let disposing
633
+ disposeChild = () => {
634
+ disposing ??= started.dispose().catch(() => {})
635
+ return disposing
636
+ }
637
+ const onAbort = () => { void disposeChild() }
638
+ if (signal.aborted) onAbort()
639
+ else signal.addEventListener('abort', onAbort, { once: true })
640
+ let result
641
+ try {
642
+ result = await started.result
643
+ } finally {
644
+ signal.removeEventListener('abort', onAbort)
645
+ }
646
+ const text = textOf({ content: result.output })
647
+ const failed = result.stopReason !== 'completed'
648
+ tracer?.finish(trace, {
649
+ isError: failed,
650
+ content: result.output,
651
+ ...(failed ? { error: { name: 'SubagentError', code: `SUBAGENT_${String(result.stopReason).toUpperCase()}` } } : {}),
652
+ })
653
+ return {
654
+ text,
655
+ output: result.output,
656
+ ...(result.structured === undefined ? {} : { structured: result.structured }),
657
+ stopReason: result.stopReason,
658
+ name: started.name,
659
+ childId: started.childId,
660
+ }
661
+ } catch (error) {
662
+ tracer?.finish(trace, {
663
+ isError: true,
664
+ content: [{ type: 'text', text: String(error?.message ?? error) }],
665
+ error: { name: error?.name ?? 'Error', code: 'LANGGRAPH_SUBAGENT_ERROR' },
666
+ })
667
+ throw error
668
+ } finally {
669
+ if (disposeChild !== undefined) await disposeChild()
670
+ }
671
+ },
672
+ }
673
+
674
+ return helpersRef
675
+ }
676
+
677
+ // --- tools --------------------------------------------------------------------
678
+ async function describeGraphs() {
679
+ await scan()
680
+ if (registry.size === 0) return 'No LangGraph workflow is registered.'
681
+ const lines = [...registry.values()]
682
+ .sort((left, right) => left.id.localeCompare(right.id))
683
+ .map(entry => {
684
+ if (entry.error !== undefined) return `- ${entry.id}: unavailable (${entry.error.message})`
685
+ const input = describeInput(entry)
686
+ return `- ${entry.id}${entry.description === undefined ? '' : `: ${entry.description}`}`
687
+ + (input === undefined ? '' : `\n input: ${input}`)
688
+ })
689
+ const { durable } = await ensureSaver()
690
+ lines.push('', durable
691
+ ? 'Threads are durable: pass `thread` to continue a thread, `resume` to answer an interrupt.'
692
+ : `Threads are not durable in this profile${openFailure === undefined ? '' : ` (${openFailure.message})`}: a run ends with this process.`)
693
+ return lines.join('\n')
694
+ }
695
+
696
+ /**
697
+ * Build and compile one graph.
698
+ * @param {{ build: (api: object) => object | Promise<object> }} entry - registry entry.
699
+ * @param {object} saver - the checkpointer for this run.
700
+ * @param {object} helpers - run helpers.
701
+ * @param {object | undefined} store - the BaseStore for this run.
702
+ * @returns {Promise<object>} the compiled graph.
703
+ */
704
+ async function compile(entry, saver, helpers, store) {
705
+ const built = await entry.build({ ...langgraph, helpers, checkpointer: saver, store })
706
+ if (isCompiled(built)) return built
707
+ if (typeof built?.compile !== 'function') {
708
+ throw new Error(`graph "${entry.id}" build(api) must return a StateGraph or a compiled graph`)
709
+ }
710
+ return built.compile({ checkpointer: saver, ...(store === undefined ? {} : { store }) })
711
+ }
712
+
713
+ /**
714
+ * Compile one graph and return its drawable topology, as plain JSON.
715
+ * @param {{ id: string }} entry - registry entry.
716
+ * @returns {Promise<object>} `{ graph, description?, input?, nodes, edges }`.
717
+ */
718
+ async function topologyOf(entry) {
719
+ const { saver } = await ensureSaver()
720
+ const { store: graphStore } = await ensureGraphStore()
721
+ const helpers = createHelpers(undefined, undefined, graphStore)
722
+ const compiled = await compile(entry, saver, helpers, graphStore)
723
+ if (typeof compiled.getGraph !== 'function' && typeof compiled.getGraphAsync !== 'function') {
724
+ throw new Error(`graph "${entry.id}" does not expose a topology`)
725
+ }
726
+ const drawable = typeof compiled.getGraphAsync === 'function'
727
+ ? await compiled.getGraphAsync()
728
+ : compiled.getGraph()
729
+ // `Graph.toJSON()` yields arrays; the object form is keyed by node id.
730
+ const snapshot = typeof drawable?.toJSON === 'function' ? drawable.toJSON() : drawable
731
+ const rawNodes = Array.isArray(snapshot?.nodes)
732
+ ? snapshot.nodes
733
+ : Object.entries(snapshot?.nodes ?? {}).map(([nodeId, node]) => ({ id: nodeId, ...(node ?? {}) }))
734
+ const nodes = rawNodes.map(node => ({
735
+ id: node?.id,
736
+ ...(node?.type === undefined ? {} : { type: node.type }),
737
+ ...(typeof (node?.name ?? node?.data?.name) === 'string' ? { name: node.name ?? node.data.name } : {}),
738
+ ...(typeof (node?.description ?? node?.data?.description) === 'string'
739
+ ? { description: node.description ?? node.data.description }
740
+ : {}),
741
+ }))
742
+ const edges = (Array.isArray(snapshot?.edges) ? snapshot.edges : []).map(edge => ({
743
+ source: edge?.source,
744
+ target: edge?.target,
745
+ ...(edge?.conditional === true ? { conditional: true } : {}),
746
+ }))
747
+ return {
748
+ graph: entry.id,
749
+ ...(entry.description === undefined ? {} : { description: entry.description }),
750
+ ...(entry.input === undefined ? {} : { input: toJsonSafe(entry.input) }),
751
+ nodes,
752
+ edges,
753
+ }
754
+ }
755
+
756
+ /** Bound one background job's model-facing result text. */
757
+ function renderJobResult(result) {
758
+ let text
759
+ try {
760
+ text = JSON.stringify(result, null, 2)
761
+ } catch {
762
+ text = String(result)
763
+ }
764
+ return text.length > 50000 ? `${text.slice(0, 50000)}\n… [truncated ${text.length - 50000} chars]` : text
765
+ }
766
+
767
+ /**
768
+ * Execute one prepared graph run under its thread lock. Shared by the
769
+ * foreground tool path and a background job.
770
+ * @param {object} run - prepared run facts.
771
+ * @returns {Promise<object>} the model-facing run result.
772
+ */
773
+ async function executeRun({ id, compiled, store, thread, requestedThread, checkpointed, args, tracer, signal, sessionId }) {
774
+ return await withThreadLock(thread, async () => {
775
+ if (thread !== undefined) {
776
+ const owner = { graph: id, ...(sessionId === undefined ? {} : { sessionId }) }
777
+ if (store === undefined) {
778
+ const conflict = claimMemoryThread(thread, owner)
779
+ if (conflict !== undefined) return { error: conflict }
780
+ } else {
781
+ try {
782
+ await store.claimThread(thread, owner)
783
+ } catch (error) {
784
+ return { error: error?.message ?? String(error) }
785
+ }
786
+ }
787
+ }
788
+
789
+ const requestedCheckpoint = typeof args?.checkpoint === 'string' && args.checkpoint.trim() !== ''
790
+ ? args.checkpoint.trim()
791
+ : undefined
792
+ const config = {
793
+ recursionLimit: Number.isInteger(args?.maxSteps) ? args.maxSteps : recursionLimit,
794
+ ...(thread === undefined ? {} : {
795
+ configurable: {
796
+ thread_id: thread,
797
+ ...(requestedCheckpoint === undefined ? {} : { checkpoint_id: requestedCheckpoint }),
798
+ },
799
+ }),
800
+ ...(signal === undefined ? {} : { signal }),
801
+ }
802
+
803
+ // An explicit `resume` answers an interrupt; an explicit `input` applies new input;
804
+ // otherwise a thread that is still mid-run continues from its last checkpoint. A
805
+ // checkpoint id replays from that snapshot instead of the thread head.
806
+ let input
807
+ let mode
808
+ if (args?.resume !== undefined) {
809
+ input = new Command({ resume: args.resume })
810
+ mode = 'resume'
811
+ } else if (args?.input !== undefined && args.input !== null) {
812
+ input = args.input
813
+ mode = 'input'
814
+ } else if (checkpointed && requestedThread !== undefined && typeof compiled.getState === 'function') {
815
+ // `getState` synthesizes an empty snapshot for an unknown checkpoint id
816
+ // instead of failing, so ask the saver whether that checkpoint exists.
817
+ if (requestedCheckpoint !== undefined && typeof compiled.checkpointer?.getTuple === 'function') {
818
+ const tuple = await compiled.checkpointer.getTuple(config).catch(() => undefined)
819
+ if (tuple === undefined) {
820
+ return { error: `checkpoint "${requestedCheckpoint}" was not found in thread "${thread}"` }
821
+ }
822
+ }
823
+ let snapshot
824
+ try {
825
+ snapshot = await compiled.getState(config)
826
+ } catch (error) {
827
+ return { error: `checkpoint "${requestedCheckpoint}" was not found in thread "${thread}"` }
828
+ }
829
+ if (snapshot === undefined) {
830
+ return { error: `checkpoint "${requestedCheckpoint}" was not found in thread "${thread}"` }
831
+ }
832
+ if (requestedCheckpoint !== undefined) {
833
+ input = null
834
+ mode = 'replay'
835
+ } else if ((snapshot?.next?.length ?? 0) > 0) {
836
+ input = null
837
+ mode = 'continue'
838
+ } else {
839
+ input = {}
840
+ mode = 'input'
841
+ }
842
+ } else {
843
+ input = {}
844
+ mode = 'input'
845
+ }
846
+
847
+ const output = await compiled.invoke(input, { ...config, callbacks: tracer.callbacks })
848
+ const interrupts = output?.__interrupt__
849
+ const state = toJsonSafe(withoutInterrupts(output))
850
+ const head = {
851
+ graph: id,
852
+ mode,
853
+ durable: checkpointed,
854
+ ...(thread === undefined ? {} : { thread }),
855
+ ...(requestedCheckpoint === undefined ? {} : { checkpoint: requestedCheckpoint }),
856
+ }
857
+ if (interrupts !== undefined) {
858
+ return {
859
+ ...head,
860
+ status: 'interrupted',
861
+ interrupts: toJsonSafe(interrupts),
862
+ hint: 'Answer with `langgraph_run({ graph, thread, resume: <value> })`.',
863
+ state,
864
+ }
865
+ }
866
+ return { ...head, status: 'completed', state }
867
+ })
868
+ }
869
+
870
+ /**
871
+ * Start one background run as a DSH job. The job owns cancellation and
872
+ * progress; the tool returns its id immediately.
873
+ * @param {object} run - prepared run facts.
874
+ * @returns {object} a background handle, or a model-facing error.
875
+ */
876
+ function startBackgroundRun({ args, exec, entry, saver, durable, store, graphStore, id, requestedThread, thread, sessionId }) {
877
+ const jobs = ctx.get('jobs')
878
+ if (jobs === undefined) {
879
+ return { error: 'background jobs are unavailable in this profile: load @deepseek-ai/dsh-jobs-local and @deepseek-ai/dsh-tool-jobs' }
880
+ }
881
+ const conflict = thread === undefined ? undefined : threadConflict(store, thread, sessionId, id)
882
+ if (conflict !== undefined) return { error: conflict }
883
+ const jobId = jobs.start({
884
+ kind: 'langgraph',
885
+ label: `${id}${thread === undefined ? '' : ` (${thread})`}`,
886
+ ...(sessionId === undefined ? {} : { owner: sessionId }),
887
+ ...(exec?.callId === undefined ? {} : {
888
+ toolCall: { callId: exec.callId, rootCallId: exec.rootCallId ?? exec.callId },
889
+ }),
890
+ run: (job) => {
891
+ const controller = new AbortController()
892
+ const runExec = { ...exec, signal: controller.signal }
893
+ const tracer = createTracer(runExec, id, traceEnabled, (event) => {
894
+ try {
895
+ if (event.phase === 'start') job.append(`▶ ${event.name}\n`)
896
+ else job.append(`${event.isError ? '✗' : '✓'} ${event.name}\n`)
897
+ job.updateProgress(event.name)
898
+ } catch {
899
+ // Progress is best-effort; the graph must not fail on a job write.
900
+ }
901
+ })
902
+ const helpers = createHelpers(runExec, tracer, graphStore)
903
+ const done = (async () => {
904
+ try {
905
+ const compiled = await compile(entry, saver, helpers, graphStore)
906
+ const checkpointed = durable || compiled.checkpointer !== undefined
907
+ if (requestedThread !== undefined && !checkpointed) {
908
+ return { status: 'failed', detail: `graph "${id}" does not carry a checkpointer, so thread "${requestedThread}" cannot be continued` }
909
+ }
910
+ const result = await executeRun({
911
+ id,
912
+ compiled,
913
+ store,
914
+ thread: checkpointed ? thread : undefined,
915
+ requestedThread,
916
+ checkpointed,
917
+ args,
918
+ tracer,
919
+ signal: controller.signal,
920
+ sessionId,
921
+ })
922
+ if (result?.error !== undefined) return { status: 'failed', detail: result.error }
923
+ job.updateProgress(result.status === 'interrupted' ? 'interrupted' : 'completed')
924
+ return {
925
+ status: 'completed',
926
+ detail: result.status === 'interrupted' ? 'interrupted' : `${id} completed`,
927
+ result: renderJobResult(result),
928
+ }
929
+ } catch (error) {
930
+ if (controller.signal.aborted) {
931
+ return { status: 'killed', detail: String(controller.signal.reason ?? 'cancelled') }
932
+ }
933
+ return { status: 'failed', detail: error?.message ?? String(error) }
934
+ }
935
+ })()
936
+ return {
937
+ cancel: (reason) => { controller.abort(reason ?? 'background langgraph run cancelled') },
938
+ done,
939
+ }
940
+ },
941
+ })
942
+ return {
943
+ kind: 'background',
944
+ jobId,
945
+ graph: id,
946
+ status: 'started',
947
+ ...(thread === undefined ? {} : { thread }),
948
+ hint: 'The run continues as a DSH job. Read it with job_output, stop it with job_kill.',
949
+ }
950
+ }
951
+
952
+ async function runGraph(args, exec) {
953
+ await scan()
954
+ const id = typeof args?.graph === 'string' ? args.graph.trim() : ''
955
+ if (id === '') return { answer: await describeGraphs() }
956
+ const entry = registry.get(id)
957
+ if (entry === undefined) {
958
+ return { error: `unknown graph "${id}". Registered: ${[...registry.keys()].join(', ') || '(none)'}` }
959
+ }
960
+ if (entry.error !== undefined) {
961
+ return { error: `graph "${id}" is unavailable: ${entry.error.message}` }
962
+ }
963
+
964
+ const { saver, durable, store: checkpointStore } = await ensureSaver()
965
+ const { store: graphStore } = await ensureGraphStore()
966
+ const sessionId = exec?.agent?.id
967
+ const requestedThread = typeof args.thread === 'string' && args.thread.trim() !== '' ? args.thread.trim() : undefined
968
+ const requestedCheckpoint = typeof args?.checkpoint === 'string' && args.checkpoint.trim() !== '' ? args.checkpoint.trim() : undefined
969
+ if (requestedCheckpoint !== undefined && requestedThread === undefined) {
970
+ return { error: '`checkpoint` requires `thread`: a checkpoint id belongs to one thread' }
971
+ }
972
+
973
+ if (args?.run_in_background === true) {
974
+ if (!backgroundEnabled) return { error: 'run_in_background is disabled for this plugin' }
975
+ if (sessionId === undefined) return { error: 'background runs need a calling agent' }
976
+ const thread = requestedThread ?? `lg_${id}_${Date.now().toString(36)}_${callSeq++}`
977
+ return startBackgroundRun({ args, exec, entry, saver, durable, store: checkpointStore, graphStore, id, requestedThread, thread, sessionId })
978
+ }
979
+
980
+ const tracer = createTracer(exec, id, traceEnabled)
981
+ const helpers = createHelpers(exec, tracer, graphStore)
982
+ const compiled = await compile(entry, saver, helpers, graphStore)
983
+ const checkpointed = durable || compiled.checkpointer !== undefined
984
+ if (requestedThread !== undefined && !checkpointed) {
985
+ return { error: `graph "${id}" does not carry a checkpointer, so thread "${requestedThread}" cannot be continued` }
986
+ }
987
+ const thread = checkpointed
988
+ ? requestedThread ?? `lg_${id}_${Date.now().toString(36)}_${callSeq++}`
989
+ : undefined
990
+ const conflict = thread === undefined ? undefined : threadConflict(checkpointStore, thread, sessionId, id)
991
+ if (conflict !== undefined) return { error: conflict }
992
+ return await executeRun({
993
+ id,
994
+ compiled,
995
+ store: checkpointStore,
996
+ thread,
997
+ requestedThread,
998
+ checkpointed,
999
+ args,
1000
+ tracer,
1001
+ signal: exec?.signal,
1002
+ sessionId,
1003
+ })
1004
+ }
1005
+
1006
+ async function manageThreads(args, exec) {
1007
+ await scan()
1008
+ const { store } = await ensureSaver()
1009
+ const sessionId = exec?.agent?.id
1010
+ const action = typeof args?.action === 'string' ? args.action : 'list'
1011
+ if (action === 'list') {
1012
+ if (store === undefined) {
1013
+ return { error: 'threads are not durable in this profile: no storage domain is mounted' }
1014
+ }
1015
+ if (args?.all !== true && sessionId === undefined) {
1016
+ return { error: 'this call has no session; pass `all: true` to list every session\'s threads' }
1017
+ }
1018
+ const threads = store.listThreads({
1019
+ graph: typeof args?.graph === 'string' && args.graph.trim() !== '' ? args.graph.trim() : undefined,
1020
+ sessionId: args?.all === true ? undefined : sessionId,
1021
+ ...(Number.isInteger(args?.limit) ? { limit: args.limit } : { limit: 25 }),
1022
+ })
1023
+ return { threads }
1024
+ }
1025
+ if (action === 'delete') {
1026
+ const thread = typeof args?.thread === 'string' ? args.thread.trim() : ''
1027
+ if (thread === '') return { error: '`thread` is required to delete a thread' }
1028
+ if (store === undefined) return { error: 'threads are not durable in this profile: no storage domain is mounted' }
1029
+ const conflict = threadConflict(store, thread, sessionId, undefined)
1030
+ if (conflict !== undefined) return { error: conflict }
1031
+ await withThreadLock(thread, () => store.forgetThreadRecords(thread))
1032
+ return { deleted: thread }
1033
+ }
1034
+ if (action === 'topology') {
1035
+ const id = typeof args?.graph === 'string' ? args.graph.trim() : ''
1036
+ if (id === '') return { error: '`graph` is required to read a topology' }
1037
+ const entry = registry.get(id)
1038
+ if (entry === undefined) return { error: `unknown graph "${id}"` }
1039
+ if (entry.error !== undefined) return { error: `graph "${id}" is unavailable: ${entry.error.message}` }
1040
+ try {
1041
+ return await topologyOf(entry)
1042
+ } catch (error) {
1043
+ return { error: error?.message ?? String(error) }
1044
+ }
1045
+ }
1046
+ if (action === 'state' || action === 'history' || action === 'edit') {
1047
+ const id = typeof args?.graph === 'string' ? args.graph.trim() : ''
1048
+ const thread = typeof args?.thread === 'string' ? args.thread.trim() : ''
1049
+ if (id === '' || thread === '') {
1050
+ return { error: `\`graph\` and \`thread\` are required to ${action === 'edit' ? 'edit' : 'read'} a thread` }
1051
+ }
1052
+ const entry = registry.get(id)
1053
+ if (entry === undefined) return { error: `unknown graph "${id}"` }
1054
+ if (entry.error !== undefined) return { error: `graph "${id}" is unavailable: ${entry.error.message}` }
1055
+ const conflict = threadConflict(store, thread, sessionId, id)
1056
+ if (conflict !== undefined) return { error: conflict }
1057
+ const { saver } = await ensureSaver()
1058
+ const { store: graphStore } = await ensureGraphStore()
1059
+ const helpers = createHelpers(exec, undefined, graphStore)
1060
+ const compiled = await compile(entry, saver, helpers, graphStore)
1061
+ if (typeof compiled.getState !== 'function' || compiled.checkpointer === undefined) {
1062
+ return { error: `graph "${id}" does not carry a checkpointer` }
1063
+ }
1064
+ const checkpoint = typeof args?.checkpoint === 'string' ? args.checkpoint.trim() : ''
1065
+ const checkpointConfig = {
1066
+ configurable: {
1067
+ thread_id: thread,
1068
+ ...(checkpoint === '' ? {} : { checkpoint_id: checkpoint }),
1069
+ },
1070
+ }
1071
+ // `getState` returns an empty snapshot for an unknown id; validate against
1072
+ // the saver so `state` and `edit` cannot silently act on a missing checkpoint.
1073
+ const checkpointSaver = compiled.checkpointer ?? saver
1074
+ if (checkpoint !== '' && action !== 'history' && typeof checkpointSaver?.getTuple === 'function') {
1075
+ const tuple = await checkpointSaver.getTuple(checkpointConfig).catch(() => undefined)
1076
+ if (tuple === undefined) {
1077
+ return { error: `checkpoint "${checkpoint}" was not found in thread "${thread}"` }
1078
+ }
1079
+ }
1080
+
1081
+ if (action === 'history') {
1082
+ if (typeof compiled.getStateHistory !== 'function') {
1083
+ return { error: `graph "${id}" cannot list checkpoint history` }
1084
+ }
1085
+ const limit = Number.isInteger(args?.limit) && args.limit > 0 ? Math.min(args.limit, 200) : 20
1086
+ const checkpoints = await withThreadLock(thread, async () => {
1087
+ const list = []
1088
+ for await (const snapshot of compiled.getStateHistory({ configurable: { thread_id: thread } })) {
1089
+ list.push({
1090
+ checkpoint: snapshot.config?.configurable?.checkpoint_id,
1091
+ step: snapshot.metadata?.step,
1092
+ source: snapshot.metadata?.source,
1093
+ createdAt: snapshot.createdAt,
1094
+ next: toJsonSafe(snapshot.next ?? []),
1095
+ paused: (snapshot.tasks ?? []).some(task => (task.interrupts?.length ?? 0) > 0),
1096
+ })
1097
+ if (list.length >= limit) break
1098
+ }
1099
+ return list
1100
+ })
1101
+ return {
1102
+ graph: id,
1103
+ thread,
1104
+ checkpoints,
1105
+ hint: 'Read one with `state` and its checkpoint, or replay it with `langgraph_run({ graph, thread, checkpoint })`.',
1106
+ }
1107
+ }
1108
+
1109
+ if (action === 'edit') {
1110
+ const values = args?.values
1111
+ if (values === null || typeof values !== 'object' || Array.isArray(values)) {
1112
+ return { error: '`values` must be a JSON object to edit a thread state' }
1113
+ }
1114
+ if (typeof compiled.updateState !== 'function') {
1115
+ return { error: `graph "${id}" cannot update state` }
1116
+ }
1117
+ const asNode = typeof args?.asNode === 'string' && args.asNode.trim() !== '' ? args.asNode.trim() : undefined
1118
+ const updated = await withThreadLock(thread, () => compiled.updateState(checkpointConfig, values, asNode))
1119
+ const newCheckpoint = updated?.configurable?.checkpoint_id
1120
+ const snapshot = await compiled.getState(updated)
1121
+ return {
1122
+ graph: id,
1123
+ thread,
1124
+ checkpoint: newCheckpoint,
1125
+ ...(checkpoint === '' ? {} : { editedFrom: checkpoint }),
1126
+ values: toJsonSafe(withoutInterrupts(snapshot?.values ?? {})),
1127
+ next: toJsonSafe(snapshot?.next ?? []),
1128
+ hint: 'Replay the edit with `langgraph_run({ graph, thread, checkpoint })`.',
1129
+ }
1130
+ }
1131
+
1132
+ let snapshot
1133
+ try {
1134
+ snapshot = await withThreadLock(thread, () => compiled.getState(checkpointConfig))
1135
+ } catch {
1136
+ snapshot = undefined
1137
+ }
1138
+ if (snapshot === undefined) {
1139
+ return {
1140
+ error: checkpoint === ''
1141
+ ? `thread "${thread}" has no state for graph "${id}"`
1142
+ : `checkpoint "${checkpoint}" was not found in thread "${thread}"`,
1143
+ }
1144
+ }
1145
+ return {
1146
+ graph: id,
1147
+ thread,
1148
+ checkpoint: checkpoint === '' ? snapshot.config?.configurable?.checkpoint_id : checkpoint,
1149
+ values: toJsonSafe(withoutInterrupts(snapshot?.values ?? {})),
1150
+ next: toJsonSafe(snapshot?.next ?? []),
1151
+ interrupts: toJsonSafe(snapshot?.tasks?.flatMap(task => task.interrupts ?? []) ?? []),
1152
+ }
1153
+ }
1154
+ return { error: `unknown action "${action}"; expected list, state, history, edit, topology, or delete` }
1155
+ }
1156
+
1157
+ // --- model-facing guidance ----------------------------------------------------
1158
+ // A system-prompt section, not another tool: the model should know which
1159
+ // graphs exist before it decides to call `langgraph_run`. The section is
1160
+ // effect-owned and retires with this plugin; no DSH source is touched.
1161
+ if (promptEnabled) {
1162
+ const systemPrompt = ctx.get('systemPrompt')
1163
+ if (systemPrompt !== undefined) {
1164
+ let scannedReady = false
1165
+ void scan().then(() => { scannedReady = true }).catch(error => {
1166
+ ctx.logger?.warn(`langgraph: graph scan failed: ${error?.message ?? error}`)
1167
+ })
1168
+ let order = 2600
1169
+ try {
1170
+ if (typeof systemPrompt.getSectionOrder === 'function') {
1171
+ order = systemPrompt.getSectionOrder('TOOL_WORKFLOW')
1172
+ }
1173
+ } catch {
1174
+ // A future DSH may rename the order; 2600 is the tool-guidance band.
1175
+ }
1176
+ ctx.effect(() => systemPrompt.section({
1177
+ name: 'tool:langgraph',
1178
+ order,
1179
+ text: () => renderGraphPrompt(registry, scannedReady),
1180
+ retirement: 'The langgraph_run workflow guidance no longer applies.',
1181
+ }), 'langgraph: prompt section')
1182
+ }
1183
+ }
1184
+
1185
+ ctx.effect(() => ctx.tools.register({
1186
+ name: RUN_TOOL,
1187
+ description: 'Run a registered LangGraph workflow. Workflows coordinate work in this workspace: '
1188
+ + 'their nodes call the same tools you have, in this session and sandbox. Omit `graph` to list them '
1189
+ + 'with their input schemas. Threads are durable: pass `thread` to continue one, and `resume` to answer '
1190
+ + 'an interrupted graph. Set `run_in_background` to return a job id immediately; read it with '
1191
+ + 'job_output and stop it with job_kill.',
1192
+ parameters: {
1193
+ type: 'object',
1194
+ properties: {
1195
+ graph: { type: 'string', description: 'Graph id. Omit to list the registered graphs.' },
1196
+ input: { type: 'object', description: 'Initial graph state, as a JSON object.', additionalProperties: true },
1197
+ thread: { type: 'string', description: 'Thread to continue. Omit to start a new durable thread.' },
1198
+ checkpoint: {
1199
+ type: 'string',
1200
+ description: 'Checkpoint id to replay from. Requires `thread`; list them with langgraph_threads action "history".',
1201
+ },
1202
+ resume: { description: 'Value handed to an interrupted graph, resuming it where it stopped.' },
1203
+ maxSteps: { type: 'integer', description: 'Upper bound on graph supersteps for this run.' },
1204
+ ...(backgroundEnabled ? {
1205
+ run_in_background: {
1206
+ type: 'boolean',
1207
+ description: 'Run as a background DSH job: return a job id immediately instead of waiting. '
1208
+ + 'The run keeps going after this tool call; its result is read with job_output.',
1209
+ },
1210
+ } : {}),
1211
+ },
1212
+ required: [],
1213
+ additionalProperties: false,
1214
+ },
1215
+ output: {
1216
+ schema: { type: 'object', additionalProperties: true },
1217
+ render: (_args, value) => [{ type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) }],
1218
+ },
1219
+ // Two runs are safe to overlap: the per-thread queue serializes the same
1220
+ // thread, and distinct threads share only the storage domain's own write chain.
1221
+ isConcurrencySafe: () => true,
1222
+ execute: (args, exec) => runGraph(args ?? {}, exec),
1223
+ }), 'langgraph: run tool')
1224
+
1225
+ ctx.effect(() => ctx.tools.register({
1226
+ name: THREADS_TOOL,
1227
+ description: 'List, inspect, time-travel, or delete durable LangGraph threads, or read a graph\'s topology. '
1228
+ + 'Threads of this session are listed by default; `state` shows a thread\'s values and what it waits on; '
1229
+ + '`history` lists checkpoints; `edit` forks a checkpoint with new values, then replay it with '
1230
+ + 'langgraph_run({ checkpoint }); `topology` returns a graph\'s nodes and edges.',
1231
+ parameters: {
1232
+ type: 'object',
1233
+ properties: {
1234
+ action: { type: 'string', enum: ['list', 'state', 'history', 'edit', 'topology', 'delete'], description: 'Defaults to list.' },
1235
+ graph: { type: 'string', description: 'Graph id; required by state, history, and edit.' },
1236
+ thread: { type: 'string', description: 'Thread id; required by state, history, edit, and delete.' },
1237
+ checkpoint: { type: 'string', description: 'Checkpoint id for state, edit, or replay; defaults to the thread head.' },
1238
+ values: { type: 'object', description: 'State fields to write in an edit, as a JSON object.', additionalProperties: true },
1239
+ asNode: { type: 'string', description: 'Attribute an edit to this node, when the graph needs one.' },
1240
+ all: { type: 'boolean', description: 'List threads of every session, not only this one.' },
1241
+ limit: { type: 'integer', description: 'Maximum threads (default 25) or checkpoints (default 20) to return.' },
1242
+ },
1243
+ required: [],
1244
+ additionalProperties: false,
1245
+ },
1246
+ output: {
1247
+ schema: { type: 'object', additionalProperties: true },
1248
+ render: (_args, value) => [{ type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) }],
1249
+ },
1250
+ execute: (args, exec) => manageThreads(args ?? {}, exec),
1251
+ }), 'langgraph: threads tool')
1252
+
1253
+ // --- owner UI routes ----------------------------------------------------------
1254
+ // The optional client panel reads these authenticated, owner-only exact routes.
1255
+ // A headless Host has no `connection` service, so nothing is served; no DSH
1256
+ // source is touched. `config.ui: false` keeps the routes off in a Web profile.
1257
+ if (uiEnabled && typeof ctx.inject === 'function') {
1258
+ ctx.inject(['connection'], (scope) => {
1259
+ const connection = scope.get('connection')
1260
+ if (typeof connection?.fetch?.register !== 'function') return
1261
+ const json = (value, status = 200) => new Response(JSON.stringify(value), {
1262
+ status,
1263
+ headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' },
1264
+ })
1265
+ scope.effect(() => connection.fetch.register({
1266
+ path: '/api/plugins/langgraph/ui',
1267
+ methods: ['GET'],
1268
+ requestBody: 'buffered',
1269
+ fetch: async () => {
1270
+ await scan()
1271
+ const { store } = await ensureSaver()
1272
+ const byGraph = {}
1273
+ let total = 0
1274
+ if (store !== undefined) {
1275
+ for (const thread of store.listThreads({})) {
1276
+ total += 1
1277
+ const key = typeof thread.graph === 'string' ? thread.graph : '(unknown)'
1278
+ byGraph[key] = (byGraph[key] ?? 0) + 1
1279
+ }
1280
+ }
1281
+ return json({
1282
+ graphs: [...registry.values()]
1283
+ .sort((left, right) => left.id.localeCompare(right.id))
1284
+ .map(entry => entry.error === undefined
1285
+ ? {
1286
+ id: entry.id,
1287
+ ...(entry.description === undefined ? {} : { description: entry.description }),
1288
+ ...(entry.input === undefined ? {} : { input: toJsonSafe(entry.input) }),
1289
+ }
1290
+ : { id: entry.id, error: entry.error.message }),
1291
+ threads: { total, byGraph, durable: store !== undefined },
1292
+ })
1293
+ },
1294
+ }), 'langgraph: ui route')
1295
+ scope.effect(() => connection.fetch.register({
1296
+ path: '/api/plugins/langgraph/topology',
1297
+ methods: ['GET'],
1298
+ requestBody: 'buffered',
1299
+ fetch: async request => {
1300
+ await scan()
1301
+ const id = new URL(request.url).searchParams.get('graph') ?? ''
1302
+ if (id === '') return json({ error: '`graph` query parameter is required' }, 400)
1303
+ const entry = registry.get(id)
1304
+ if (entry === undefined) return json({ error: `unknown graph "${id}"` }, 404)
1305
+ if (entry.error !== undefined) return json({ error: `graph "${id}" is unavailable: ${entry.error.message}` }, 500)
1306
+ try {
1307
+ return json(await topologyOf(entry))
1308
+ } catch (error) {
1309
+ return json({ error: error?.message ?? String(error) }, 500)
1310
+ }
1311
+ },
1312
+ }), 'langgraph: topology route')
1313
+ })
1314
+ }
1315
+ }