@lzn1998/dsh-langgraph 0.5.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -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,66 @@ 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 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
+
126
165
  /**
127
166
  * Register the graph tools and the graph registry for one activation.
128
167
  * @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
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
131
170
  * model route graph nodes use through `helpers.callModel` (defaults to this
132
- * deployment's selected model).
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).
133
174
  */
134
175
  export function apply(ctx, config) {
135
176
  const extra = Array.isArray(config?.graphs) ? config.graphs : []
136
177
  const recursionLimit = Number.isInteger(config?.recursionLimit) ? config.recursionLimit : DEFAULT_RECURSION_LIMIT
137
178
  const configuredModel = config?.model ?? {}
138
179
  const traceEnabled = config?.trace !== false
180
+ const promptEnabled = config?.prompt !== false
139
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
140
187
  const configuredSubagentProvider = typeof config?.subagentProvider === 'string' && config.subagentProvider !== ''
141
188
  ? config.subagentProvider
142
189
  : 'spawn'
@@ -150,10 +197,12 @@ export function apply(ctx, config) {
150
197
  // still gets working threads through `MemorySaver`, but they end with the process.
151
198
  let opened
152
199
  let openFailure
200
+ let openedGraphStore
153
201
  let disposed = false
154
202
  ctx.effect(() => () => {
155
203
  disposed = true
156
204
  if (opened !== undefined) void opened.close()
205
+ if (openedGraphStore !== undefined) void openedGraphStore.close()
157
206
  })
158
207
 
159
208
  /** @type {Promise<object | undefined> | undefined} */
@@ -172,7 +221,7 @@ export function apply(ctx, config) {
172
221
  return undefined
173
222
  }
174
223
  try {
175
- const store = await openCheckpointStore(storageDomain)
224
+ const store = await openCheckpointStore(storageDomain, { retention })
176
225
  if (disposed) {
177
226
  await store.close()
178
227
  return undefined
@@ -195,6 +244,47 @@ export function apply(ctx, config) {
195
244
  return { saver: memorySaver, durable: false, store: undefined }
196
245
  }
197
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
+
198
288
  /**
199
289
  * Why this caller may not use a thread, or undefined when it may. A durable
200
290
  * thread is owned by the graph and session that created it; resuming it from
@@ -292,13 +382,21 @@ export function apply(ctx, config) {
292
382
  }
293
383
 
294
384
  /** Helpers bound to one run: they close over the calling agent and its cancellation. */
295
- function createHelpers(exec, tracer) {
385
+ function createHelpers(exec, tracer, store) {
296
386
  const agent = exec?.agent
297
387
  const signal = exec?.signal ?? new AbortController().signal
298
388
  const helpersRef = {
299
389
 
300
390
  agent,
301
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
+ },
302
400
  /** LangChain message classes, so a graph module needs no LangChain dependency of its own. */
303
401
  messages: { AIMessage, HumanMessage, SystemMessage, ToolMessage },
304
402
  /**
@@ -430,6 +528,60 @@ export function apply(ctx, config) {
430
528
  tracer?.finish(trace, { content: settled?.content ?? [{ type: 'text', text }] })
431
529
  return text
432
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
+ },
433
585
  /**
434
586
  * Delegate one task to a DSH subagent from inside a graph node.
435
587
  *
@@ -546,15 +698,59 @@ export function apply(ctx, config) {
546
698
  * @param {{ build: (api: object) => object | Promise<object> }} entry - registry entry.
547
699
  * @param {object} saver - the checkpointer for this run.
548
700
  * @param {object} helpers - run helpers.
701
+ * @param {object | undefined} store - the BaseStore for this run.
549
702
  * @returns {Promise<object>} the compiled graph.
550
703
  */
551
- async function compile(entry, saver, helpers) {
552
- const built = await entry.build({ ...langgraph, helpers, checkpointer: saver })
704
+ async function compile(entry, saver, helpers, store) {
705
+ const built = await entry.build({ ...langgraph, helpers, checkpointer: saver, store })
553
706
  if (isCompiled(built)) return built
554
707
  if (typeof built?.compile !== 'function') {
555
708
  throw new Error(`graph "${entry.id}" build(api) must return a StateGraph or a compiled graph`)
556
709
  }
557
- return built.compile({ checkpointer: saver })
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
+ }
558
754
  }
559
755
 
560
756
  /** Bound one background job's model-facing result text. */
@@ -590,14 +786,23 @@ export function apply(ctx, config) {
590
786
  }
591
787
  }
592
788
 
789
+ const requestedCheckpoint = typeof args?.checkpoint === 'string' && args.checkpoint.trim() !== ''
790
+ ? args.checkpoint.trim()
791
+ : undefined
593
792
  const config = {
594
793
  recursionLimit: Number.isInteger(args?.maxSteps) ? args.maxSteps : recursionLimit,
595
- ...(thread === undefined ? {} : { configurable: { thread_id: thread } }),
794
+ ...(thread === undefined ? {} : {
795
+ configurable: {
796
+ thread_id: thread,
797
+ ...(requestedCheckpoint === undefined ? {} : { checkpoint_id: requestedCheckpoint }),
798
+ },
799
+ }),
596
800
  ...(signal === undefined ? {} : { signal }),
597
801
  }
598
802
 
599
803
  // 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.
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.
601
806
  let input
602
807
  let mode
603
808
  if (args?.resume !== undefined) {
@@ -607,8 +812,27 @@ export function apply(ctx, config) {
607
812
  input = args.input
608
813
  mode = 'input'
609
814
  } else if (checkpointed && requestedThread !== undefined && typeof compiled.getState === 'function') {
610
- const snapshot = await compiled.getState(config)
611
- if ((snapshot?.next?.length ?? 0) > 0) {
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) {
612
836
  input = null
613
837
  mode = 'continue'
614
838
  } else {
@@ -628,6 +852,7 @@ export function apply(ctx, config) {
628
852
  mode,
629
853
  durable: checkpointed,
630
854
  ...(thread === undefined ? {} : { thread }),
855
+ ...(requestedCheckpoint === undefined ? {} : { checkpoint: requestedCheckpoint }),
631
856
  }
632
857
  if (interrupts !== undefined) {
633
858
  return {
@@ -648,7 +873,7 @@ export function apply(ctx, config) {
648
873
  * @param {object} run - prepared run facts.
649
874
  * @returns {object} a background handle, or a model-facing error.
650
875
  */
651
- function startBackgroundRun({ args, exec, entry, saver, durable, store, id, requestedThread, thread, sessionId }) {
876
+ function startBackgroundRun({ args, exec, entry, saver, durable, store, graphStore, id, requestedThread, thread, sessionId }) {
652
877
  const jobs = ctx.get('jobs')
653
878
  if (jobs === undefined) {
654
879
  return { error: 'background jobs are unavailable in this profile: load @deepseek-ai/dsh-jobs-local and @deepseek-ai/dsh-tool-jobs' }
@@ -674,10 +899,10 @@ export function apply(ctx, config) {
674
899
  // Progress is best-effort; the graph must not fail on a job write.
675
900
  }
676
901
  })
677
- const helpers = createHelpers(runExec, tracer)
902
+ const helpers = createHelpers(runExec, tracer, graphStore)
678
903
  const done = (async () => {
679
904
  try {
680
- const compiled = await compile(entry, saver, helpers)
905
+ const compiled = await compile(entry, saver, helpers, graphStore)
681
906
  const checkpointed = durable || compiled.checkpointer !== undefined
682
907
  if (requestedThread !== undefined && !checkpointed) {
683
908
  return { status: 'failed', detail: `graph "${id}" does not carry a checkpointer, so thread "${requestedThread}" cannot be continued` }
@@ -736,20 +961,25 @@ export function apply(ctx, config) {
736
961
  return { error: `graph "${id}" is unavailable: ${entry.error.message}` }
737
962
  }
738
963
 
739
- const { saver, durable, store } = await ensureSaver()
964
+ const { saver, durable, store: checkpointStore } = await ensureSaver()
965
+ const { store: graphStore } = await ensureGraphStore()
740
966
  const sessionId = exec?.agent?.id
741
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
+ }
742
972
 
743
973
  if (args?.run_in_background === true) {
744
974
  if (!backgroundEnabled) return { error: 'run_in_background is disabled for this plugin' }
745
975
  if (sessionId === undefined) return { error: 'background runs need a calling agent' }
746
976
  const thread = requestedThread ?? `lg_${id}_${Date.now().toString(36)}_${callSeq++}`
747
- return startBackgroundRun({ args, exec, entry, saver, durable, store, id, requestedThread, thread, sessionId })
977
+ return startBackgroundRun({ args, exec, entry, saver, durable, store: checkpointStore, graphStore, id, requestedThread, thread, sessionId })
748
978
  }
749
979
 
750
980
  const tracer = createTracer(exec, id, traceEnabled)
751
- const helpers = createHelpers(exec, tracer)
752
- const compiled = await compile(entry, saver, helpers)
981
+ const helpers = createHelpers(exec, tracer, graphStore)
982
+ const compiled = await compile(entry, saver, helpers, graphStore)
753
983
  const checkpointed = durable || compiled.checkpointer !== undefined
754
984
  if (requestedThread !== undefined && !checkpointed) {
755
985
  return { error: `graph "${id}" does not carry a checkpointer, so thread "${requestedThread}" cannot be continued` }
@@ -757,12 +987,12 @@ export function apply(ctx, config) {
757
987
  const thread = checkpointed
758
988
  ? requestedThread ?? `lg_${id}_${Date.now().toString(36)}_${callSeq++}`
759
989
  : undefined
760
- const conflict = thread === undefined ? undefined : threadConflict(store, thread, sessionId, id)
990
+ const conflict = thread === undefined ? undefined : threadConflict(checkpointStore, thread, sessionId, id)
761
991
  if (conflict !== undefined) return { error: conflict }
762
992
  return await executeRun({
763
993
  id,
764
994
  compiled,
765
- store,
995
+ store: checkpointStore,
766
996
  thread,
767
997
  requestedThread,
768
998
  checkpointed,
@@ -801,31 +1031,155 @@ export function apply(ctx, config) {
801
1031
  await withThreadLock(thread, () => store.forgetThreadRecords(thread))
802
1032
  return { deleted: thread }
803
1033
  }
804
- if (action === 'state') {
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') {
805
1047
  const id = typeof args?.graph === 'string' ? args.graph.trim() : ''
806
1048
  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' }
1049
+ if (id === '' || thread === '') {
1050
+ return { error: `\`graph\` and \`thread\` are required to ${action === 'edit' ? 'edit' : 'read'} a thread` }
1051
+ }
808
1052
  const entry = registry.get(id)
809
1053
  if (entry === undefined) return { error: `unknown graph "${id}"` }
810
1054
  if (entry.error !== undefined) return { error: `graph "${id}" is unavailable: ${entry.error.message}` }
811
1055
  const conflict = threadConflict(store, thread, sessionId, id)
812
1056
  if (conflict !== undefined) return { error: conflict }
813
1057
  const { saver } = await ensureSaver()
814
- const helpers = createHelpers(exec)
815
- const compiled = await compile(entry, saver, helpers)
1058
+ const { store: graphStore } = await ensureGraphStore()
1059
+ const helpers = createHelpers(exec, undefined, graphStore)
1060
+ const compiled = await compile(entry, saver, helpers, graphStore)
816
1061
  if (typeof compiled.getState !== 'function' || compiled.checkpointer === undefined) {
817
1062
  return { error: `graph "${id}" does not carry a checkpointer` }
818
1063
  }
819
- const snapshot = await withThreadLock(thread, () => compiled.getState({ configurable: { thread_id: thread } }))
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
+ }
820
1145
  return {
821
1146
  graph: id,
822
1147
  thread,
1148
+ checkpoint: checkpoint === '' ? snapshot.config?.configurable?.checkpoint_id : checkpoint,
823
1149
  values: toJsonSafe(withoutInterrupts(snapshot?.values ?? {})),
824
1150
  next: toJsonSafe(snapshot?.next ?? []),
825
1151
  interrupts: toJsonSafe(snapshot?.tasks?.flatMap(task => task.interrupts ?? []) ?? []),
826
1152
  }
827
1153
  }
828
- return { error: `unknown action "${action}"; expected list, state, or delete` }
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
+ }
829
1183
  }
830
1184
 
831
1185
  ctx.effect(() => ctx.tools.register({
@@ -841,6 +1195,10 @@ export function apply(ctx, config) {
841
1195
  graph: { type: 'string', description: 'Graph id. Omit to list the registered graphs.' },
842
1196
  input: { type: 'object', description: 'Initial graph state, as a JSON object.', additionalProperties: true },
843
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
+ },
844
1202
  resume: { description: 'Value handed to an interrupted graph, resuming it where it stopped.' },
845
1203
  maxSteps: { type: 'integer', description: 'Upper bound on graph supersteps for this run.' },
846
1204
  ...(backgroundEnabled ? {
@@ -866,16 +1224,21 @@ export function apply(ctx, config) {
866
1224
 
867
1225
  ctx.effect(() => ctx.tools.register({
868
1226
  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.',
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.',
871
1231
  parameters: {
872
1232
  type: 'object',
873
1233
  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.' },
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.' },
877
1240
  all: { type: 'boolean', description: 'List threads of every session, not only this one.' },
878
- limit: { type: 'integer', description: 'Maximum threads to list (default 25).' },
1241
+ limit: { type: 'integer', description: 'Maximum threads (default 25) or checkpoints (default 20) to return.' },
879
1242
  },
880
1243
  required: [],
881
1244
  additionalProperties: false,
@@ -886,4 +1249,67 @@ export function apply(ctx, config) {
886
1249
  },
887
1250
  execute: (args, exec) => manageThreads(args ?? {}, exec),
888
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
+ }
889
1315
  }