@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/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * LangGraph workflows as DSH tools, with durable threads.
2
+ * LangGraph graphs as DSH tools, with durable threads.
3
3
  *
4
4
  * A graph module exports `id`, an optional `description`, an optional `input` JSON
5
5
  * Schema for its initial state, and `build(api)` where `api` carries the LangGraph API
@@ -20,9 +20,10 @@ import { readdir } from 'node:fs/promises'
20
20
  import { fileURLToPath, pathToFileURL } from 'node:url'
21
21
  import * as langgraph from '@langchain/langgraph'
22
22
  import { Command } from '@langchain/langgraph'
23
- import { MemorySaver } from '@langchain/langgraph-checkpoint'
23
+ import { InMemoryStore, MemorySaver } from '@langchain/langgraph-checkpoint'
24
24
  import { DshChatModel, AIMessage, HumanMessage, SystemMessage, ToolMessage } from './dsh-chat-model.js'
25
25
  import { openCheckpointStore } from './dsh-checkpointer.js'
26
+ import { openDshStore } from './dsh-store.js'
26
27
  import { createTracer } from './dsh-trace.js'
27
28
  import { langchainTool } from './dsh-tools.js'
28
29
 
@@ -123,20 +124,74 @@ function describeInput(entry) {
123
124
  }
124
125
  }
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 graphs are profile-registered, named graphs run by `langgraph_run`. '
138
+ + 'They are not the `workflow` tool (`workflow` runs an ad-hoc JavaScript fan-out script).'
139
+ if (!ready) {
140
+ return `${intro} Call it with no \`graph\` to list the registered graphs and their input schemas.`
141
+ }
142
+ const available = [...registry.values()]
143
+ .filter(entry => entry.error === undefined)
144
+ .sort((left, right) => left.id.localeCompare(right.id))
145
+ if (available.length === 0) {
146
+ return `${intro}\n\nNo graph is registered yet; call it with no \`graph\` to re-check.`
147
+ }
148
+ const limit = 24
149
+ const lines = available.slice(0, limit).map(entry => {
150
+ const description = typeof entry.description === 'string' ? entry.description.replace(/\s+/g, ' ').trim() : ''
151
+ return `- ${entry.id}${description === '' ? '' : `: ${description}`}`
152
+ })
153
+ if (available.length > limit) {
154
+ lines.push(`- … and ${available.length - limit} more; call \`langgraph_run\` with no graph for the full list.`)
155
+ }
156
+ return [
157
+ intro,
158
+ 'Use `langgraph_run` when:\n'
159
+ + '- the user names one of the graph ids below;\n'
160
+ + '- a registered graph\'s description matches the requested output; use that graph instead of '
161
+ + 'hand-rolling its steps with bash, subagent, or ad-hoc calls;\n'
162
+ + '- the task needs a durable LangGraph thread, a background run (a DSH job), checkpoint '
163
+ + 'history or replay, a Trajectory sub-call record, or the graph description says it interrupts.',
164
+ 'When no graph\'s output matches, use ordinary DSH tools; do not wrap a single tool call in a graph '
165
+ + 'just for ceremony, and do not use the `workflow` tool as a substitute for a named graph.',
166
+ 'A LangGraph thread is a durable checkpoint chain for one graph run, not a DSH Session. '
167
+ + 'Use `langgraph_threads` to list, inspect, time-travel, or delete threads, or read a graph\'s topology.',
168
+ `Registered graphs:\n${lines.join('\n')}`,
169
+ 'Omit `graph` to list input schemas.',
170
+ ].join('\n\n')
171
+ }
172
+
126
173
  /**
127
174
  * Register the graph tools and the graph registry for one activation.
128
175
  * @param {import('@deepseek-ai/cordis').Context} ctx - the plugin's context.
129
- * @param {{ graphs?: { id?: string, module: string }[], recursionLimit?: number, model?: { provider?: string, model?: string, reasoningEffort?: string } }} [config]
130
- * row config: extra graph modules, the default LangGraph recursion limit, and the
176
+ * @param {{ graphs?: { id?: string, module: string }[], recursionLimit?: number, model?: { provider?: string, model?: string, reasoningEffort?: string }, store?: boolean, retention?: number }} [config]
177
+ * row config: extra graph modules, the default LangGraph recursion limit, the
131
178
  * model route graph nodes use through `helpers.callModel` (defaults to this
132
- * deployment's selected model).
179
+ * deployment's selected model), whether graphs get a long-term BaseStore
180
+ * (`store: false` passes none), and how many checkpoints each thread keeps
181
+ * (default 200; `0` is unlimited).
133
182
  */
134
183
  export function apply(ctx, config) {
135
184
  const extra = Array.isArray(config?.graphs) ? config.graphs : []
136
185
  const recursionLimit = Number.isInteger(config?.recursionLimit) ? config.recursionLimit : DEFAULT_RECURSION_LIMIT
137
186
  const configuredModel = config?.model ?? {}
138
187
  const traceEnabled = config?.trace !== false
188
+ const promptEnabled = config?.prompt !== false
139
189
  const backgroundEnabled = config?.background !== false
190
+ const storeEnabled = config?.store !== false
191
+ // Keep bounded thread history by default; 0 keeps every checkpoint, which a
192
+ // graph that time-travels further back needs.
193
+ const retention = Number.isInteger(config?.retention) && config.retention >= 0 ? config.retention : 200
194
+ const uiEnabled = config?.ui !== false
140
195
  const configuredSubagentProvider = typeof config?.subagentProvider === 'string' && config.subagentProvider !== ''
141
196
  ? config.subagentProvider
142
197
  : 'spawn'
@@ -150,10 +205,12 @@ export function apply(ctx, config) {
150
205
  // still gets working threads through `MemorySaver`, but they end with the process.
151
206
  let opened
152
207
  let openFailure
208
+ let openedGraphStore
153
209
  let disposed = false
154
210
  ctx.effect(() => () => {
155
211
  disposed = true
156
212
  if (opened !== undefined) void opened.close()
213
+ if (openedGraphStore !== undefined) void openedGraphStore.close()
157
214
  })
158
215
 
159
216
  /** @type {Promise<object | undefined> | undefined} */
@@ -172,7 +229,7 @@ export function apply(ctx, config) {
172
229
  return undefined
173
230
  }
174
231
  try {
175
- const store = await openCheckpointStore(storageDomain)
232
+ const store = await openCheckpointStore(storageDomain, { retention })
176
233
  if (disposed) {
177
234
  await store.close()
178
235
  return undefined
@@ -195,6 +252,47 @@ export function apply(ctx, config) {
195
252
  return { saver: memorySaver, durable: false, store: undefined }
196
253
  }
197
254
 
255
+ // --- long-term store ----------------------------------------------------------
256
+ // The store is a second domain, opened lazily for the same reason. A profile
257
+ // without `storageDomain` gets an InMemoryStore, so a graph that uses memory
258
+ // still runs; only its memories end with the process.
259
+ /** @type {Promise<object | undefined> | undefined} */
260
+ let graphStorePromise
261
+ /** @type {import('@langchain/langgraph-checkpoint').InMemoryStore | undefined} */
262
+ let memoryGraphStore
263
+ let graphStoreFailure
264
+
265
+ /** Open the durable BaseStore once, or resolve undefined without a storage domain. */
266
+ function openGraphStore() {
267
+ graphStorePromise ??= (async () => {
268
+ const storageDomain = ctx.get('storageDomain')
269
+ if (storageDomain === undefined) return undefined
270
+ try {
271
+ const openedStore = await openDshStore(storageDomain)
272
+ if (disposed) {
273
+ await openedStore.close()
274
+ return undefined
275
+ }
276
+ openedGraphStore = openedStore
277
+ return openedStore.store
278
+ } catch (error) {
279
+ graphStoreFailure = error
280
+ ctx.logger?.warn(`langgraph: durable store unavailable, falling back to memory: ${error?.message ?? error}`)
281
+ return undefined
282
+ }
283
+ })()
284
+ return graphStorePromise
285
+ }
286
+
287
+ /** The BaseStore for one run plus whether it outlives the process. */
288
+ async function ensureGraphStore() {
289
+ if (!storeEnabled) return { store: undefined, durableStore: false }
290
+ const store = await openGraphStore()
291
+ if (store !== undefined) return { store, durableStore: true }
292
+ memoryGraphStore ??= new InMemoryStore()
293
+ return { store: memoryGraphStore, durableStore: false }
294
+ }
295
+
198
296
  /**
199
297
  * Why this caller may not use a thread, or undefined when it may. A durable
200
298
  * thread is owned by the graph and session that created it; resuming it from
@@ -292,13 +390,21 @@ export function apply(ctx, config) {
292
390
  }
293
391
 
294
392
  /** Helpers bound to one run: they close over the calling agent and its cancellation. */
295
- function createHelpers(exec, tracer) {
393
+ function createHelpers(exec, tracer, store) {
296
394
  const agent = exec?.agent
297
395
  const signal = exec?.signal ?? new AbortController().signal
298
396
  const helpersRef = {
299
397
 
300
398
  agent,
301
399
  sessionId: agent?.id,
400
+ /**
401
+ * The LangGraph long-term store for this run. With a storage domain it is
402
+ * durable across turns and Host processes; otherwise it is an InMemoryStore.
403
+ * @returns {object | undefined} the BaseStore, or undefined when `config.store` is false.
404
+ */
405
+ store() {
406
+ return store
407
+ },
302
408
  /** LangChain message classes, so a graph module needs no LangChain dependency of its own. */
303
409
  messages: { AIMessage, HumanMessage, SystemMessage, ToolMessage },
304
410
  /**
@@ -430,6 +536,60 @@ export function apply(ctx, config) {
430
536
  tracer?.finish(trace, { content: settled?.content ?? [{ type: 'text', text }] })
431
537
  return text
432
538
  },
539
+ /**
540
+ * Ask the user through DSH's native `ask_user_question` tool. The question
541
+ * renders in the stock question UI, so no client code is needed; the call
542
+ * blocks the node until the user answers (or the profile's wait times out).
543
+ * @param {Array<{ id?: string, question: string, header?: string, options?: Array<string | { label: string, description?: string }>, multi_select?: boolean }>} questions
544
+ * one or more questions; a missing `id` becomes `q1`, `q2`, …
545
+ * @returns {Promise<{ answers: Array<{ id: string, selected: string[], custom?: string }> }>}
546
+ * one answer per question; `selected: []` with no `custom` means the user skipped it.
547
+ */
548
+ async askUser(questions) {
549
+ if (!Array.isArray(questions) || questions.length === 0) {
550
+ throw new Error('askUser needs at least one question')
551
+ }
552
+ const normalized = questions.map((question, index) => {
553
+ if (question === null || typeof question !== 'object') {
554
+ throw new Error(`askUser: question ${index + 1} must be an object`)
555
+ }
556
+ if (typeof question.question !== 'string' || question.question.trim() === '') {
557
+ throw new Error(`askUser: question ${index + 1} needs a non-empty \`question\``)
558
+ }
559
+ const id = typeof question.id === 'string' && question.id !== '' ? question.id : `q${index + 1}`
560
+ const options = question.options === undefined ? undefined : question.options.map((option, optionIndex) => {
561
+ if (typeof option === 'string') return { label: option }
562
+ if (option === null || typeof option !== 'object' || typeof option.label !== 'string') {
563
+ throw new Error(`askUser: option ${optionIndex + 1} of question "${id}" needs a label`)
564
+ }
565
+ return { label: option.label, ...(option.description === undefined ? {} : { description: option.description }) }
566
+ })
567
+ return {
568
+ id,
569
+ question: question.question,
570
+ ...(question.header === undefined ? {} : { header: question.header }),
571
+ ...(options === undefined ? {} : { options }),
572
+ ...(question.multi_select === undefined ? {} : { multi_select: question.multi_select }),
573
+ }
574
+ })
575
+ const text = await helpersRef.callTool('ask_user_question', { questions: normalized })
576
+ let parsed
577
+ try {
578
+ parsed = JSON.parse(text)
579
+ } catch {
580
+ throw new Error(`askUser: unexpected answer format: ${text.slice(0, 500)}`)
581
+ }
582
+ if (!Array.isArray(parsed?.answers)) {
583
+ throw new Error(`askUser: unexpected answer format: ${text.slice(0, 500)}`)
584
+ }
585
+ return {
586
+ answers: parsed.answers.map(answer => ({
587
+ id: String(answer?.id ?? ''),
588
+ selected: Array.isArray(answer?.selected) ? answer.selected.map(String) : [],
589
+ ...(typeof answer?.custom === 'string' ? { custom: answer.custom } : {}),
590
+ })),
591
+ }
592
+ },
433
593
  /**
434
594
  * Delegate one task to a DSH subagent from inside a graph node.
435
595
  *
@@ -525,7 +685,7 @@ export function apply(ctx, config) {
525
685
  // --- tools --------------------------------------------------------------------
526
686
  async function describeGraphs() {
527
687
  await scan()
528
- if (registry.size === 0) return 'No LangGraph workflow is registered.'
688
+ if (registry.size === 0) return 'No LangGraph graph is registered.'
529
689
  const lines = [...registry.values()]
530
690
  .sort((left, right) => left.id.localeCompare(right.id))
531
691
  .map(entry => {
@@ -546,15 +706,59 @@ export function apply(ctx, config) {
546
706
  * @param {{ build: (api: object) => object | Promise<object> }} entry - registry entry.
547
707
  * @param {object} saver - the checkpointer for this run.
548
708
  * @param {object} helpers - run helpers.
709
+ * @param {object | undefined} store - the BaseStore for this run.
549
710
  * @returns {Promise<object>} the compiled graph.
550
711
  */
551
- async function compile(entry, saver, helpers) {
552
- const built = await entry.build({ ...langgraph, helpers, checkpointer: saver })
712
+ async function compile(entry, saver, helpers, store) {
713
+ const built = await entry.build({ ...langgraph, helpers, checkpointer: saver, store })
553
714
  if (isCompiled(built)) return built
554
715
  if (typeof built?.compile !== 'function') {
555
716
  throw new Error(`graph "${entry.id}" build(api) must return a StateGraph or a compiled graph`)
556
717
  }
557
- return built.compile({ checkpointer: saver })
718
+ return built.compile({ checkpointer: saver, ...(store === undefined ? {} : { store }) })
719
+ }
720
+
721
+ /**
722
+ * Compile one graph and return its drawable topology, as plain JSON.
723
+ * @param {{ id: string }} entry - registry entry.
724
+ * @returns {Promise<object>} `{ graph, description?, input?, nodes, edges }`.
725
+ */
726
+ async function topologyOf(entry) {
727
+ const { saver } = await ensureSaver()
728
+ const { store: graphStore } = await ensureGraphStore()
729
+ const helpers = createHelpers(undefined, undefined, graphStore)
730
+ const compiled = await compile(entry, saver, helpers, graphStore)
731
+ if (typeof compiled.getGraph !== 'function' && typeof compiled.getGraphAsync !== 'function') {
732
+ throw new Error(`graph "${entry.id}" does not expose a topology`)
733
+ }
734
+ const drawable = typeof compiled.getGraphAsync === 'function'
735
+ ? await compiled.getGraphAsync()
736
+ : compiled.getGraph()
737
+ // `Graph.toJSON()` yields arrays; the object form is keyed by node id.
738
+ const snapshot = typeof drawable?.toJSON === 'function' ? drawable.toJSON() : drawable
739
+ const rawNodes = Array.isArray(snapshot?.nodes)
740
+ ? snapshot.nodes
741
+ : Object.entries(snapshot?.nodes ?? {}).map(([nodeId, node]) => ({ id: nodeId, ...(node ?? {}) }))
742
+ const nodes = rawNodes.map(node => ({
743
+ id: node?.id,
744
+ ...(node?.type === undefined ? {} : { type: node.type }),
745
+ ...(typeof (node?.name ?? node?.data?.name) === 'string' ? { name: node.name ?? node.data.name } : {}),
746
+ ...(typeof (node?.description ?? node?.data?.description) === 'string'
747
+ ? { description: node.description ?? node.data.description }
748
+ : {}),
749
+ }))
750
+ const edges = (Array.isArray(snapshot?.edges) ? snapshot.edges : []).map(edge => ({
751
+ source: edge?.source,
752
+ target: edge?.target,
753
+ ...(edge?.conditional === true ? { conditional: true } : {}),
754
+ }))
755
+ return {
756
+ graph: entry.id,
757
+ ...(entry.description === undefined ? {} : { description: entry.description }),
758
+ ...(entry.input === undefined ? {} : { input: toJsonSafe(entry.input) }),
759
+ nodes,
760
+ edges,
761
+ }
558
762
  }
559
763
 
560
764
  /** Bound one background job's model-facing result text. */
@@ -590,14 +794,23 @@ export function apply(ctx, config) {
590
794
  }
591
795
  }
592
796
 
797
+ const requestedCheckpoint = typeof args?.checkpoint === 'string' && args.checkpoint.trim() !== ''
798
+ ? args.checkpoint.trim()
799
+ : undefined
593
800
  const config = {
594
801
  recursionLimit: Number.isInteger(args?.maxSteps) ? args.maxSteps : recursionLimit,
595
- ...(thread === undefined ? {} : { configurable: { thread_id: thread } }),
802
+ ...(thread === undefined ? {} : {
803
+ configurable: {
804
+ thread_id: thread,
805
+ ...(requestedCheckpoint === undefined ? {} : { checkpoint_id: requestedCheckpoint }),
806
+ },
807
+ }),
596
808
  ...(signal === undefined ? {} : { signal }),
597
809
  }
598
810
 
599
811
  // An explicit `resume` answers an interrupt; an explicit `input` applies new input;
600
- // otherwise a thread that is still mid-run continues from its last checkpoint.
812
+ // otherwise a thread that is still mid-run continues from its last checkpoint. A
813
+ // checkpoint id replays from that snapshot instead of the thread head.
601
814
  let input
602
815
  let mode
603
816
  if (args?.resume !== undefined) {
@@ -607,8 +820,27 @@ export function apply(ctx, config) {
607
820
  input = args.input
608
821
  mode = 'input'
609
822
  } else if (checkpointed && requestedThread !== undefined && typeof compiled.getState === 'function') {
610
- const snapshot = await compiled.getState(config)
611
- if ((snapshot?.next?.length ?? 0) > 0) {
823
+ // `getState` synthesizes an empty snapshot for an unknown checkpoint id
824
+ // instead of failing, so ask the saver whether that checkpoint exists.
825
+ if (requestedCheckpoint !== undefined && typeof compiled.checkpointer?.getTuple === 'function') {
826
+ const tuple = await compiled.checkpointer.getTuple(config).catch(() => undefined)
827
+ if (tuple === undefined) {
828
+ return { error: `checkpoint "${requestedCheckpoint}" was not found in thread "${thread}"` }
829
+ }
830
+ }
831
+ let snapshot
832
+ try {
833
+ snapshot = await compiled.getState(config)
834
+ } catch (error) {
835
+ return { error: `checkpoint "${requestedCheckpoint}" was not found in thread "${thread}"` }
836
+ }
837
+ if (snapshot === undefined) {
838
+ return { error: `checkpoint "${requestedCheckpoint}" was not found in thread "${thread}"` }
839
+ }
840
+ if (requestedCheckpoint !== undefined) {
841
+ input = null
842
+ mode = 'replay'
843
+ } else if ((snapshot?.next?.length ?? 0) > 0) {
612
844
  input = null
613
845
  mode = 'continue'
614
846
  } else {
@@ -628,6 +860,7 @@ export function apply(ctx, config) {
628
860
  mode,
629
861
  durable: checkpointed,
630
862
  ...(thread === undefined ? {} : { thread }),
863
+ ...(requestedCheckpoint === undefined ? {} : { checkpoint: requestedCheckpoint }),
631
864
  }
632
865
  if (interrupts !== undefined) {
633
866
  return {
@@ -648,7 +881,7 @@ export function apply(ctx, config) {
648
881
  * @param {object} run - prepared run facts.
649
882
  * @returns {object} a background handle, or a model-facing error.
650
883
  */
651
- function startBackgroundRun({ args, exec, entry, saver, durable, store, id, requestedThread, thread, sessionId }) {
884
+ function startBackgroundRun({ args, exec, entry, saver, durable, store, graphStore, id, requestedThread, thread, sessionId }) {
652
885
  const jobs = ctx.get('jobs')
653
886
  if (jobs === undefined) {
654
887
  return { error: 'background jobs are unavailable in this profile: load @deepseek-ai/dsh-jobs-local and @deepseek-ai/dsh-tool-jobs' }
@@ -674,10 +907,10 @@ export function apply(ctx, config) {
674
907
  // Progress is best-effort; the graph must not fail on a job write.
675
908
  }
676
909
  })
677
- const helpers = createHelpers(runExec, tracer)
910
+ const helpers = createHelpers(runExec, tracer, graphStore)
678
911
  const done = (async () => {
679
912
  try {
680
- const compiled = await compile(entry, saver, helpers)
913
+ const compiled = await compile(entry, saver, helpers, graphStore)
681
914
  const checkpointed = durable || compiled.checkpointer !== undefined
682
915
  if (requestedThread !== undefined && !checkpointed) {
683
916
  return { status: 'failed', detail: `graph "${id}" does not carry a checkpointer, so thread "${requestedThread}" cannot be continued` }
@@ -736,20 +969,25 @@ export function apply(ctx, config) {
736
969
  return { error: `graph "${id}" is unavailable: ${entry.error.message}` }
737
970
  }
738
971
 
739
- const { saver, durable, store } = await ensureSaver()
972
+ const { saver, durable, store: checkpointStore } = await ensureSaver()
973
+ const { store: graphStore } = await ensureGraphStore()
740
974
  const sessionId = exec?.agent?.id
741
975
  const requestedThread = typeof args.thread === 'string' && args.thread.trim() !== '' ? args.thread.trim() : undefined
976
+ const requestedCheckpoint = typeof args?.checkpoint === 'string' && args.checkpoint.trim() !== '' ? args.checkpoint.trim() : undefined
977
+ if (requestedCheckpoint !== undefined && requestedThread === undefined) {
978
+ return { error: '`checkpoint` requires `thread`: a checkpoint id belongs to one thread' }
979
+ }
742
980
 
743
981
  if (args?.run_in_background === true) {
744
982
  if (!backgroundEnabled) return { error: 'run_in_background is disabled for this plugin' }
745
983
  if (sessionId === undefined) return { error: 'background runs need a calling agent' }
746
984
  const thread = requestedThread ?? `lg_${id}_${Date.now().toString(36)}_${callSeq++}`
747
- return startBackgroundRun({ args, exec, entry, saver, durable, store, id, requestedThread, thread, sessionId })
985
+ return startBackgroundRun({ args, exec, entry, saver, durable, store: checkpointStore, graphStore, id, requestedThread, thread, sessionId })
748
986
  }
749
987
 
750
988
  const tracer = createTracer(exec, id, traceEnabled)
751
- const helpers = createHelpers(exec, tracer)
752
- const compiled = await compile(entry, saver, helpers)
989
+ const helpers = createHelpers(exec, tracer, graphStore)
990
+ const compiled = await compile(entry, saver, helpers, graphStore)
753
991
  const checkpointed = durable || compiled.checkpointer !== undefined
754
992
  if (requestedThread !== undefined && !checkpointed) {
755
993
  return { error: `graph "${id}" does not carry a checkpointer, so thread "${requestedThread}" cannot be continued` }
@@ -757,12 +995,12 @@ export function apply(ctx, config) {
757
995
  const thread = checkpointed
758
996
  ? requestedThread ?? `lg_${id}_${Date.now().toString(36)}_${callSeq++}`
759
997
  : undefined
760
- const conflict = thread === undefined ? undefined : threadConflict(store, thread, sessionId, id)
998
+ const conflict = thread === undefined ? undefined : threadConflict(checkpointStore, thread, sessionId, id)
761
999
  if (conflict !== undefined) return { error: conflict }
762
1000
  return await executeRun({
763
1001
  id,
764
1002
  compiled,
765
- store,
1003
+ store: checkpointStore,
766
1004
  thread,
767
1005
  requestedThread,
768
1006
  checkpointed,
@@ -801,46 +1039,178 @@ export function apply(ctx, config) {
801
1039
  await withThreadLock(thread, () => store.forgetThreadRecords(thread))
802
1040
  return { deleted: thread }
803
1041
  }
804
- if (action === 'state') {
1042
+ if (action === 'topology') {
1043
+ const id = typeof args?.graph === 'string' ? args.graph.trim() : ''
1044
+ if (id === '') return { error: '`graph` is required to read a topology' }
1045
+ const entry = registry.get(id)
1046
+ if (entry === undefined) return { error: `unknown graph "${id}"` }
1047
+ if (entry.error !== undefined) return { error: `graph "${id}" is unavailable: ${entry.error.message}` }
1048
+ try {
1049
+ return await topologyOf(entry)
1050
+ } catch (error) {
1051
+ return { error: error?.message ?? String(error) }
1052
+ }
1053
+ }
1054
+ if (action === 'state' || action === 'history' || action === 'edit') {
805
1055
  const id = typeof args?.graph === 'string' ? args.graph.trim() : ''
806
1056
  const thread = typeof args?.thread === 'string' ? args.thread.trim() : ''
807
- if (id === '' || thread === '') return { error: '`graph` and `thread` are required to read a thread state' }
1057
+ if (id === '' || thread === '') {
1058
+ return { error: `\`graph\` and \`thread\` are required to ${action === 'edit' ? 'edit' : 'read'} a thread` }
1059
+ }
808
1060
  const entry = registry.get(id)
809
1061
  if (entry === undefined) return { error: `unknown graph "${id}"` }
810
1062
  if (entry.error !== undefined) return { error: `graph "${id}" is unavailable: ${entry.error.message}` }
811
1063
  const conflict = threadConflict(store, thread, sessionId, id)
812
1064
  if (conflict !== undefined) return { error: conflict }
813
1065
  const { saver } = await ensureSaver()
814
- const helpers = createHelpers(exec)
815
- const compiled = await compile(entry, saver, helpers)
1066
+ const { store: graphStore } = await ensureGraphStore()
1067
+ const helpers = createHelpers(exec, undefined, graphStore)
1068
+ const compiled = await compile(entry, saver, helpers, graphStore)
816
1069
  if (typeof compiled.getState !== 'function' || compiled.checkpointer === undefined) {
817
1070
  return { error: `graph "${id}" does not carry a checkpointer` }
818
1071
  }
819
- const snapshot = await withThreadLock(thread, () => compiled.getState({ configurable: { thread_id: thread } }))
1072
+ const checkpoint = typeof args?.checkpoint === 'string' ? args.checkpoint.trim() : ''
1073
+ const checkpointConfig = {
1074
+ configurable: {
1075
+ thread_id: thread,
1076
+ ...(checkpoint === '' ? {} : { checkpoint_id: checkpoint }),
1077
+ },
1078
+ }
1079
+ // `getState` returns an empty snapshot for an unknown id; validate against
1080
+ // the saver so `state` and `edit` cannot silently act on a missing checkpoint.
1081
+ const checkpointSaver = compiled.checkpointer ?? saver
1082
+ if (checkpoint !== '' && action !== 'history' && typeof checkpointSaver?.getTuple === 'function') {
1083
+ const tuple = await checkpointSaver.getTuple(checkpointConfig).catch(() => undefined)
1084
+ if (tuple === undefined) {
1085
+ return { error: `checkpoint "${checkpoint}" was not found in thread "${thread}"` }
1086
+ }
1087
+ }
1088
+
1089
+ if (action === 'history') {
1090
+ if (typeof compiled.getStateHistory !== 'function') {
1091
+ return { error: `graph "${id}" cannot list checkpoint history` }
1092
+ }
1093
+ const limit = Number.isInteger(args?.limit) && args.limit > 0 ? Math.min(args.limit, 200) : 20
1094
+ const checkpoints = await withThreadLock(thread, async () => {
1095
+ const list = []
1096
+ for await (const snapshot of compiled.getStateHistory({ configurable: { thread_id: thread } })) {
1097
+ list.push({
1098
+ checkpoint: snapshot.config?.configurable?.checkpoint_id,
1099
+ step: snapshot.metadata?.step,
1100
+ source: snapshot.metadata?.source,
1101
+ createdAt: snapshot.createdAt,
1102
+ next: toJsonSafe(snapshot.next ?? []),
1103
+ paused: (snapshot.tasks ?? []).some(task => (task.interrupts?.length ?? 0) > 0),
1104
+ })
1105
+ if (list.length >= limit) break
1106
+ }
1107
+ return list
1108
+ })
1109
+ return {
1110
+ graph: id,
1111
+ thread,
1112
+ checkpoints,
1113
+ hint: 'Read one with `state` and its checkpoint, or replay it with `langgraph_run({ graph, thread, checkpoint })`.',
1114
+ }
1115
+ }
1116
+
1117
+ if (action === 'edit') {
1118
+ const values = args?.values
1119
+ if (values === null || typeof values !== 'object' || Array.isArray(values)) {
1120
+ return { error: '`values` must be a JSON object to edit a thread state' }
1121
+ }
1122
+ if (typeof compiled.updateState !== 'function') {
1123
+ return { error: `graph "${id}" cannot update state` }
1124
+ }
1125
+ const asNode = typeof args?.asNode === 'string' && args.asNode.trim() !== '' ? args.asNode.trim() : undefined
1126
+ const updated = await withThreadLock(thread, () => compiled.updateState(checkpointConfig, values, asNode))
1127
+ const newCheckpoint = updated?.configurable?.checkpoint_id
1128
+ const snapshot = await compiled.getState(updated)
1129
+ return {
1130
+ graph: id,
1131
+ thread,
1132
+ checkpoint: newCheckpoint,
1133
+ ...(checkpoint === '' ? {} : { editedFrom: checkpoint }),
1134
+ values: toJsonSafe(withoutInterrupts(snapshot?.values ?? {})),
1135
+ next: toJsonSafe(snapshot?.next ?? []),
1136
+ hint: 'Replay the edit with `langgraph_run({ graph, thread, checkpoint })`.',
1137
+ }
1138
+ }
1139
+
1140
+ let snapshot
1141
+ try {
1142
+ snapshot = await withThreadLock(thread, () => compiled.getState(checkpointConfig))
1143
+ } catch {
1144
+ snapshot = undefined
1145
+ }
1146
+ if (snapshot === undefined) {
1147
+ return {
1148
+ error: checkpoint === ''
1149
+ ? `thread "${thread}" has no state for graph "${id}"`
1150
+ : `checkpoint "${checkpoint}" was not found in thread "${thread}"`,
1151
+ }
1152
+ }
820
1153
  return {
821
1154
  graph: id,
822
1155
  thread,
1156
+ checkpoint: checkpoint === '' ? snapshot.config?.configurable?.checkpoint_id : checkpoint,
823
1157
  values: toJsonSafe(withoutInterrupts(snapshot?.values ?? {})),
824
1158
  next: toJsonSafe(snapshot?.next ?? []),
825
1159
  interrupts: toJsonSafe(snapshot?.tasks?.flatMap(task => task.interrupts ?? []) ?? []),
826
1160
  }
827
1161
  }
828
- return { error: `unknown action "${action}"; expected list, state, or delete` }
1162
+ return { error: `unknown action "${action}"; expected list, state, history, edit, topology, or delete` }
1163
+ }
1164
+
1165
+ // --- model-facing guidance ----------------------------------------------------
1166
+ // A system-prompt section, not another tool: the model should know which
1167
+ // graphs exist before it decides to call `langgraph_run`. The section is
1168
+ // effect-owned and retires with this plugin; no DSH source is touched.
1169
+ if (promptEnabled) {
1170
+ const systemPrompt = ctx.get('systemPrompt')
1171
+ if (systemPrompt !== undefined) {
1172
+ let scannedReady = false
1173
+ void scan().then(() => { scannedReady = true }).catch(error => {
1174
+ ctx.logger?.warn(`langgraph: graph scan failed: ${error?.message ?? error}`)
1175
+ })
1176
+ // Sit after the `workflow` tool's "only when the user asks" rule and just
1177
+ // before subagent guidance. The old TOOL_WORKFLOW slot put this section
1178
+ // next to a second "workflow" rule, which read as one instruction.
1179
+ let order = 2790
1180
+ try {
1181
+ if (typeof systemPrompt.getSectionOrder === 'function') {
1182
+ order = systemPrompt.getSectionOrder('TOOL_SUBAGENT') - 10
1183
+ }
1184
+ } catch {
1185
+ // A future DSH may rename the order; 2790 is just before subagents.
1186
+ }
1187
+ ctx.effect(() => systemPrompt.section({
1188
+ name: 'tool:langgraph',
1189
+ order,
1190
+ text: () => renderGraphPrompt(registry, scannedReady),
1191
+ retirement: 'The langgraph_run graph guidance no longer applies.',
1192
+ }), 'langgraph: prompt section')
1193
+ }
829
1194
  }
830
1195
 
831
1196
  ctx.effect(() => ctx.tools.register({
832
1197
  name: RUN_TOOL,
833
- description: 'Run a registered LangGraph workflow. Workflows coordinate work in this workspace: '
834
- + 'their nodes call the same tools you have, in this session and sandbox. Omit `graph` to list them '
835
- + 'with their input schemas. Threads are durable: pass `thread` to continue one, and `resume` to answer '
836
- + 'an interrupted graph. Set `run_in_background` to return a job id immediately; read it with '
837
- + 'job_output and stop it with job_kill.',
1198
+ description: 'Run one registered LangGraph graph by id. Use it when the user names a graph, a graph\'s '
1199
+ + 'description matches the requested output, or the task needs a durable thread, background job, '
1200
+ + 'checkpoint replay, or Trajectory record; it is not the `workflow` tool. Omit `graph` to list graphs '
1201
+ + 'and input schemas. Threads are durable LangGraph checkpoint chains (not DSH Sessions): pass `thread` '
1202
+ + 'to continue one, `resume` to answer an interrupt, and `checkpoint` to replay a snapshot from '
1203
+ + '`langgraph_threads` history. `run_in_background` returns a DSH job id for `job_output`/`job_kill`.',
838
1204
  parameters: {
839
1205
  type: 'object',
840
1206
  properties: {
841
- graph: { type: 'string', description: 'Graph id. Omit to list the registered graphs.' },
1207
+ graph: { type: 'string', description: 'Registered graph id; omit to list graphs and input schemas.' },
842
1208
  input: { type: 'object', description: 'Initial graph state, as a JSON object.', additionalProperties: true },
843
- thread: { type: 'string', description: 'Thread to continue. Omit to start a new durable thread.' },
1209
+ thread: { type: 'string', description: 'LangGraph thread to continue; omit to start a new durable thread. Not a DSH Session id.' },
1210
+ checkpoint: {
1211
+ type: 'string',
1212
+ description: 'Checkpoint id to replay from (langgraph_threads action "history"); requires `thread`.',
1213
+ },
844
1214
  resume: { description: 'Value handed to an interrupted graph, resuming it where it stopped.' },
845
1215
  maxSteps: { type: 'integer', description: 'Upper bound on graph supersteps for this run.' },
846
1216
  ...(backgroundEnabled ? {
@@ -866,16 +1236,21 @@ export function apply(ctx, config) {
866
1236
 
867
1237
  ctx.effect(() => ctx.tools.register({
868
1238
  name: THREADS_TOOL,
869
- description: 'List, inspect, or delete durable LangGraph threads. Threads of this session are listed by '
870
- + 'default; `state` shows a thread\'s current values and what it is waiting on.',
1239
+ description: 'Manage durable LangGraph threads and a graph\'s topology. `list` (this session by default), '
1240
+ + '`state` (values, next, interrupts), `history` (checkpoint ids), `edit` (fork a checkpoint with new '
1241
+ + 'values), `topology` (nodes/edges), or `delete`. A thread is a LangGraph checkpoint chain, not a '
1242
+ + 'DSH Session. Replay an edit with `langgraph_run({ checkpoint })`.',
871
1243
  parameters: {
872
1244
  type: 'object',
873
1245
  properties: {
874
- action: { type: 'string', enum: ['list', 'state', 'delete'], description: 'Defaults to list.' },
875
- graph: { type: 'string', description: 'Restrict to one graph id.' },
876
- thread: { type: 'string', description: 'Thread id, required by state and delete.' },
1246
+ action: { type: 'string', enum: ['list', 'state', 'history', 'edit', 'topology', 'delete'], description: 'Defaults to list.' },
1247
+ graph: { type: 'string', description: 'Graph id; required by state, history, edit, and topology.' },
1248
+ thread: { type: 'string', description: 'LangGraph thread id; required by state, history, edit, and delete. Not a DSH Session id.' },
1249
+ checkpoint: { type: 'string', description: 'Checkpoint id for state, edit, or replay; defaults to the thread head.' },
1250
+ values: { type: 'object', description: 'State fields to write in an edit, as a JSON object.', additionalProperties: true },
1251
+ asNode: { type: 'string', description: 'Attribute an edit to this node, when the graph needs one.' },
877
1252
  all: { type: 'boolean', description: 'List threads of every session, not only this one.' },
878
- limit: { type: 'integer', description: 'Maximum threads to list (default 25).' },
1253
+ limit: { type: 'integer', description: 'Maximum threads (default 25) or checkpoints (default 20) to return.' },
879
1254
  },
880
1255
  required: [],
881
1256
  additionalProperties: false,
@@ -886,4 +1261,67 @@ export function apply(ctx, config) {
886
1261
  },
887
1262
  execute: (args, exec) => manageThreads(args ?? {}, exec),
888
1263
  }), 'langgraph: threads tool')
1264
+
1265
+ // --- owner UI routes ----------------------------------------------------------
1266
+ // The optional client panel reads these authenticated, owner-only exact routes.
1267
+ // A headless Host has no `connection` service, so nothing is served; no DSH
1268
+ // source is touched. `config.ui: false` keeps the routes off in a Web profile.
1269
+ if (uiEnabled && typeof ctx.inject === 'function') {
1270
+ ctx.inject(['connection'], (scope) => {
1271
+ const connection = scope.get('connection')
1272
+ if (typeof connection?.fetch?.register !== 'function') return
1273
+ const json = (value, status = 200) => new Response(JSON.stringify(value), {
1274
+ status,
1275
+ headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' },
1276
+ })
1277
+ scope.effect(() => connection.fetch.register({
1278
+ path: '/api/plugins/langgraph/ui',
1279
+ methods: ['GET'],
1280
+ requestBody: 'buffered',
1281
+ fetch: async () => {
1282
+ await scan()
1283
+ const { store } = await ensureSaver()
1284
+ const byGraph = {}
1285
+ let total = 0
1286
+ if (store !== undefined) {
1287
+ for (const thread of store.listThreads({})) {
1288
+ total += 1
1289
+ const key = typeof thread.graph === 'string' ? thread.graph : '(unknown)'
1290
+ byGraph[key] = (byGraph[key] ?? 0) + 1
1291
+ }
1292
+ }
1293
+ return json({
1294
+ graphs: [...registry.values()]
1295
+ .sort((left, right) => left.id.localeCompare(right.id))
1296
+ .map(entry => entry.error === undefined
1297
+ ? {
1298
+ id: entry.id,
1299
+ ...(entry.description === undefined ? {} : { description: entry.description }),
1300
+ ...(entry.input === undefined ? {} : { input: toJsonSafe(entry.input) }),
1301
+ }
1302
+ : { id: entry.id, error: entry.error.message }),
1303
+ threads: { total, byGraph, durable: store !== undefined },
1304
+ })
1305
+ },
1306
+ }), 'langgraph: ui route')
1307
+ scope.effect(() => connection.fetch.register({
1308
+ path: '/api/plugins/langgraph/topology',
1309
+ methods: ['GET'],
1310
+ requestBody: 'buffered',
1311
+ fetch: async request => {
1312
+ await scan()
1313
+ const id = new URL(request.url).searchParams.get('graph') ?? ''
1314
+ if (id === '') return json({ error: '`graph` query parameter is required' }, 400)
1315
+ const entry = registry.get(id)
1316
+ if (entry === undefined) return json({ error: `unknown graph "${id}"` }, 404)
1317
+ if (entry.error !== undefined) return json({ error: `graph "${id}" is unavailable: ${entry.error.message}` }, 500)
1318
+ try {
1319
+ return json(await topologyOf(entry))
1320
+ } catch (error) {
1321
+ return json({ error: error?.message ?? String(error) }, 500)
1322
+ }
1323
+ },
1324
+ }), 'langgraph: topology route')
1325
+ })
1326
+ }
889
1327
  }