@lzn1998/dsh-langgraph 1.0.0 → 1.5.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
@@ -26,6 +26,10 @@ import { openCheckpointStore } from './dsh-checkpointer.js'
26
26
  import { openDshStore } from './dsh-store.js'
27
27
  import { createTracer } from './dsh-trace.js'
28
28
  import { langchainTool } from './dsh-tools.js'
29
+ import { downstreamOf, upstreamOf } from './compose/analysis.js'
30
+ import { createResolver } from './compose/resolve.js'
31
+ import { createMemorySpecStore, isSpecId, openSpecStore } from './compose/specs.js'
32
+ import { COMPOSE_ACTIONS, createComposeTool } from './compose/tool.js'
29
33
 
30
34
  /**
31
35
  * Identity helper for graph modules written in TypeScript.
@@ -52,6 +56,7 @@ export const inject = ['tools']
52
56
 
53
57
  const RUN_TOOL = 'langgraph_run'
54
58
  const THREADS_TOOL = 'langgraph_threads'
59
+ const COMPOSE_TOOL = 'langgraph_compose'
55
60
  const DEFAULT_RECURSION_LIMIT = 25
56
61
  let callSeq = 0
57
62
 
@@ -114,6 +119,37 @@ function withoutInterrupts(state) {
114
119
  return rest
115
120
  }
116
121
 
122
+ /** The innermost error our node wrapper annotated, or the outer error. */
123
+ function annotatedError(error) {
124
+ let current = error
125
+ for (let depth = 0; current !== null && current !== undefined && depth < 10; depth += 1) {
126
+ if (current.nodeId !== undefined) return current
127
+ current = current.cause
128
+ }
129
+ return error
130
+ }
131
+
132
+ /** Bound one failure snapshot's state by the spec's output fields and length. */
133
+ function boundedValues(values, output) {
134
+ if (values === null || typeof values !== 'object') return values
135
+ const picked = Array.isArray(output)
136
+ ? Object.fromEntries(output
137
+ .filter(field => Object.prototype.hasOwnProperty.call(values, field))
138
+ .map(field => [field, values[field]]))
139
+ : values
140
+ const safe = toJsonSafe(withoutInterrupts(picked))
141
+ let text
142
+ try {
143
+ text = JSON.stringify(safe)
144
+ } catch {
145
+ text = String(safe)
146
+ }
147
+ if (typeof text === 'string' && text.length > 4000) {
148
+ return { truncated: true, preview: text.slice(0, 4000) }
149
+ }
150
+ return safe
151
+ }
152
+
117
153
  /** One-line rendering of a graph's input schema for the agent-facing listing. */
118
154
  function describeInput(entry) {
119
155
  if (entry.input === undefined) return undefined
@@ -134,16 +170,47 @@ function describeInput(entry) {
134
170
  * @returns {string} section text.
135
171
  */
136
172
  export function renderGraphPrompt(registry, ready) {
137
- const intro = 'LangGraph graphs are profile-registered, named graphs run by `langgraph_run`. '
173
+ const intro = 'LangGraph graphs are named graphs run by `langgraph_run`. A graph is either '
174
+ + 'profile-registered or composed with `langgraph_compose` for this session. '
138
175
  + 'They are not the `workflow` tool (`workflow` runs an ad-hoc JavaScript fan-out script).'
176
+ const composeGuidance = [
177
+ 'Compose when the work has seams that should not be re-decided every turn: it must survive across '
178
+ + 'turns, fan out and aggregate, pause for a human, or retry at a boundary. A composed graph is a '
179
+ + 'contract: state is the ledger between seams, nodes are roles, edges are handoffs. Otherwise stay '
180
+ + 'in the ordinary loop; prefer a registered graph when one matches.',
181
+ 'Start from the ledger and the seams, not the boxes. Keep the graph coarse: put open-ended work in '
182
+ + 'an `agent` node and let its brief carry the detail; use a smaller node only when that step is '
183
+ + 'itself the contract. Put "how" in the brief and "what/when" in the edges.',
184
+ 'Before the first compose, call `langgraph_compose({ action: "describe" })`: read its guide first '
185
+ + 'for the method, then its law as the normative contract. The reference and archetype examples '
186
+ + 'follow. The compiler is deterministic and never uses a model to translate the IR.',
187
+ 'A composed graph is an immutable session-owned spec, not a file and not a DSH Session; change it '
188
+ + 'by composing a new spec. It does not appear in the registered list: call '
189
+ + '`langgraph_compose({ action: "list" })` or `langgraph_run` with no graph. Use ordinary DSH tools '
190
+ + 'for one-off or still-unclear work; a shape worth reusing belongs in a profile graph module.',
191
+ 'When a composed run fails, read the `status: "failed"` result: `failedScc`, `upstream`, '
192
+ + '`downstream`, `pending`, and `lastSupersteps` name the boundary and the state. Retry a transient '
193
+ + 'error with the same thread; fix a bad state with `langgraph_threads edit` and replay; for a graph '
194
+ + 'bug, call `langgraph_compose({ action: "fork", graph, from: failedNode })`, edit the returned '
195
+ + 'spec, compose it, and run it with the current state.',
196
+ ]
197
+ const threadGuidance = 'A LangGraph thread is a durable checkpoint chain for one graph run, not a DSH Session. '
198
+ + 'Use `langgraph_threads` to list, inspect, time-travel, or delete threads, or read a graph\'s topology.'
199
+ const discovery = 'Call it with no `graph` to list the registered graphs, composed graphs, and their input schemas.'
139
200
  if (!ready) {
140
- return `${intro} Call it with no \`graph\` to list the registered graphs and their input schemas.`
201
+ return [intro, ...composeGuidance, threadGuidance, discovery].join('\n\n')
141
202
  }
142
203
  const available = [...registry.values()]
143
204
  .filter(entry => entry.error === undefined)
144
205
  .sort((left, right) => left.id.localeCompare(right.id))
145
206
  if (available.length === 0) {
146
- return `${intro}\n\nNo graph is registered yet; call it with no \`graph\` to re-check.`
207
+ return [
208
+ intro,
209
+ ...composeGuidance,
210
+ threadGuidance,
211
+ 'No graph is registered yet; call it with no `graph` to re-check, or compose one with `langgraph_compose`.',
212
+ 'Omit `graph` to list input schemas, or composed graphs in this session.',
213
+ ].join('\n\n')
147
214
  }
148
215
  const limit = 24
149
216
  const lines = available.slice(0, limit).map(entry => {
@@ -161,12 +228,10 @@ export function renderGraphPrompt(registry, ready) {
161
228
  + 'hand-rolling its steps with bash, subagent, or ad-hoc calls;\n'
162
229
  + '- the task needs a durable LangGraph thread, a background run (a DSH job), checkpoint '
163
230
  + '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.',
231
+ ...composeGuidance,
232
+ threadGuidance,
168
233
  `Registered graphs:\n${lines.join('\n')}`,
169
- 'Omit `graph` to list input schemas.',
234
+ 'Omit `graph` to list input schemas, or composed graphs in this session.',
170
235
  ].join('\n\n')
171
236
  }
172
237
 
@@ -206,11 +271,13 @@ export function apply(ctx, config) {
206
271
  let opened
207
272
  let openFailure
208
273
  let openedGraphStore
274
+ let openedSpecStore
209
275
  let disposed = false
210
276
  ctx.effect(() => () => {
211
277
  disposed = true
212
278
  if (opened !== undefined) void opened.close()
213
279
  if (openedGraphStore !== undefined) void openedGraphStore.close()
280
+ if (openedSpecStore !== undefined) void openedSpecStore.close()
214
281
  })
215
282
 
216
283
  /** @type {Promise<object | undefined> | undefined} */
@@ -293,6 +360,56 @@ export function apply(ctx, config) {
293
360
  return { store: memoryGraphStore, durableStore: false }
294
361
  }
295
362
 
363
+ // --- composed graph specs -----------------------------------------------------
364
+ // A third domain, opened lazily like the others. Without `storageDomain` the
365
+ // store is process-local, matching the in-memory checkpoint fallback. Specs do
366
+ // not enter the registry or the system-prompt graph list; a session resolves
367
+ // its own ids only.
368
+ /** @type {Promise<object | undefined> | undefined} */
369
+ let specStorePromise
370
+ /** @type {ReturnType<typeof createMemorySpecStore> | undefined} */
371
+ let memorySpecStore
372
+ let specStoreFailure
373
+
374
+ /** Open the durable spec store once, or resolve undefined without a storage domain. */
375
+ function openSpecs() {
376
+ specStorePromise ??= (async () => {
377
+ const storageDomain = ctx.get('storageDomain')
378
+ if (storageDomain === undefined) return undefined
379
+ try {
380
+ const openedStore = await openSpecStore(storageDomain)
381
+ if (disposed) {
382
+ await openedStore.close()
383
+ return undefined
384
+ }
385
+ openedSpecStore = openedStore
386
+ return openedStore.store
387
+ } catch (error) {
388
+ specStoreFailure = error
389
+ ctx.logger?.warn(`langgraph: composed graph store unavailable, falling back to memory: ${error?.message ?? error}`)
390
+ return undefined
391
+ }
392
+ })()
393
+ return specStorePromise
394
+ }
395
+
396
+ /** The spec store for this process, durable when a storage domain is mounted. */
397
+ async function ensureSpecStore() {
398
+ const store = await openSpecs()
399
+ if (store !== undefined) return store
400
+ memorySpecStore ??= createMemorySpecStore()
401
+ return memorySpecStore
402
+ }
403
+
404
+ /** Resolve a registered graph or one of this session's composed specs. */
405
+ const resolveEntry = createResolver({ registry, getStore: ensureSpecStore })
406
+
407
+ /** Model-facing message for an id that is neither registered nor owned. */
408
+ function unknownGraphMessage(id, withList = false) {
409
+ if (isSpecId(id)) return `unknown or not owned composed graph "${id}"`
410
+ return `unknown graph "${id}"${withList ? `. Registered: ${[...registry.keys()].join(', ') || '(none)'}` : ''}`
411
+ }
412
+
296
413
  /**
297
414
  * Why this caller may not use a thread, or undefined when it may. A durable
298
415
  * thread is owned by the graph and session that created it; resuming it from
@@ -683,17 +800,37 @@ export function apply(ctx, config) {
683
800
  }
684
801
 
685
802
  // --- tools --------------------------------------------------------------------
686
- async function describeGraphs() {
803
+ async function describeGraphs(exec) {
687
804
  await scan()
688
- if (registry.size === 0) return 'No LangGraph graph is registered.'
689
- const lines = [...registry.values()]
690
- .sort((left, right) => left.id.localeCompare(right.id))
691
- .map(entry => {
692
- if (entry.error !== undefined) return `- ${entry.id}: unavailable (${entry.error.message})`
693
- const input = describeInput(entry)
694
- return `- ${entry.id}${entry.description === undefined ? '' : `: ${entry.description}`}`
695
- + (input === undefined ? '' : `\n input: ${input}`)
696
- })
805
+ const lines = []
806
+ if (registry.size === 0) {
807
+ lines.push('No LangGraph graph is registered.')
808
+ } else {
809
+ lines.push(...[...registry.values()]
810
+ .sort((left, right) => left.id.localeCompare(right.id))
811
+ .map(entry => {
812
+ if (entry.error !== undefined) return `- ${entry.id}: unavailable (${entry.error.message})`
813
+ const input = describeInput(entry)
814
+ return `- ${entry.id}${entry.description === undefined ? '' : `: ${entry.description}`}`
815
+ + (input === undefined ? '' : `\n input: ${input}`)
816
+ }))
817
+ }
818
+ const sessionId = exec?.agent?.id
819
+ if (sessionId !== undefined) {
820
+ try {
821
+ const specs = (await ensureSpecStore()).listSpecs(sessionId, { limit: 20 })
822
+ if (specs.length > 0) {
823
+ lines.push('', 'Composed graphs in this session:')
824
+ for (const spec of specs) {
825
+ lines.push(`- ${spec.id}`
826
+ + (spec.name === undefined ? '' : ` (${spec.name})`)
827
+ + (spec.description === undefined ? '' : `: ${spec.description}`))
828
+ }
829
+ }
830
+ } catch (error) {
831
+ lines.push('', `Composed graphs could not be listed: ${error?.message ?? error}`)
832
+ }
833
+ }
697
834
  const { durable } = await ensureSaver()
698
835
  lines.push('', durable
699
836
  ? 'Threads are durable: pass `thread` to continue a thread, `resume` to answer an interrupt.'
@@ -761,6 +898,41 @@ export function apply(ctx, config) {
761
898
  }
762
899
  }
763
900
 
901
+ /** Read a composed thread's head state for a fork. */
902
+ async function readComposedState(id, thread, sessionId) {
903
+ const entry = await resolveEntry(id, sessionId)
904
+ if (entry === undefined || entry.composed !== true) {
905
+ throw new Error(`no composed graph "${id}" in this session`)
906
+ }
907
+ const { saver, store: checkpointStore } = await ensureSaver()
908
+ const conflict = threadConflict(checkpointStore, thread, sessionId, id)
909
+ if (conflict !== undefined) throw new Error(conflict)
910
+ const { store: graphStore } = await ensureGraphStore()
911
+ const helpers = createHelpers(undefined, undefined, graphStore)
912
+ const compiled = await compile(entry, saver, helpers, graphStore)
913
+ if (typeof compiled.getState !== 'function') return undefined
914
+ if (typeof compiled.checkpointer?.getTuple === 'function') {
915
+ const tuple = await compiled.checkpointer.getTuple({ configurable: { thread_id: thread } }).catch(() => undefined)
916
+ if (tuple === undefined) throw new Error(`thread "${thread}" has no state for graph "${id}"`)
917
+ }
918
+ const snapshot = await compiled.getState({ configurable: { thread_id: thread } })
919
+ return toJsonSafe(withoutInterrupts(snapshot?.values ?? {}))
920
+ }
921
+
922
+ // --- compose tool ------------------------------------------------------------
923
+ // Composed specs share the runtime with registered graphs; this tool only
924
+ // validates, stores, previews, and forks them. `langgraph_run` executes the id.
925
+ const composeGraph = createComposeTool({
926
+ ensureSpecStore,
927
+ ensureSaver,
928
+ topologyOf,
929
+ withThreadLock,
930
+ getVisibleTools: exec => ctx.tools.definitions(exec?.agent),
931
+ getSessionId: exec => exec?.agent?.id,
932
+ getCwd: exec => exec?.agent?.cwd ?? exec?.cwd,
933
+ readStateOf: readComposedState,
934
+ })
935
+
764
936
  /** Bound one background job's model-facing result text. */
765
937
  function renderJobResult(result) {
766
938
  let text
@@ -772,13 +944,125 @@ export function apply(ctx, config) {
772
944
  return text.length > 50000 ? `${text.slice(0, 50000)}\n… [truncated ${text.length - 50000} chars]` : text
773
945
  }
774
946
 
947
+ /**
948
+ * Build the structured failure result: the failed node's cycle, what was
949
+ * pending, the dependency boundary, and the last few checkpoint snapshots.
950
+ * For a composed graph the SCC/reachability sets come from its IR analysis;
951
+ * a registered graph gets the error and thread history only.
952
+ */
953
+ async function failureResult({ id, entry, compiled, config, thread, checkpointed, error }) {
954
+ const annotated = annotatedError(error)
955
+ let failedNode = typeof annotated?.nodeId === 'string' ? annotated.nodeId : undefined
956
+ const itemIndex = Number.isInteger(annotated?.itemIndex) ? annotated.itemIndex : undefined
957
+
958
+ // Hidden map nodes (`<id>__fanout`, `<id>__join`) are compiler details;
959
+ // report the spec's map id instead.
960
+ const displayNode = node => {
961
+ if (typeof node !== 'string') return node
962
+ for (const mapNode of entry?.spec?.nodes ?? []) {
963
+ if (mapNode.do !== 'map') continue
964
+ if (node === `${mapNode.id}__fanout` || node.startsWith(`${mapNode.id}__fanout_`)) return mapNode.id
965
+ if (node === `${mapNode.id}__join` || node.startsWith(`${mapNode.id}__join_`)) return mapNode.id
966
+ }
967
+ return node
968
+ }
969
+
970
+ const lastSupersteps = []
971
+ let checkpoint
972
+ let pending = []
973
+ let state
974
+ if (thread !== undefined && typeof compiled.getStateHistory === 'function') {
975
+ try {
976
+ for await (const snapshot of compiled.getStateHistory({ configurable: { thread_id: thread } })) {
977
+ lastSupersteps.push({
978
+ step: snapshot.metadata?.step,
979
+ source: snapshot.metadata?.source,
980
+ checkpoint: snapshot.config?.configurable?.checkpoint_id,
981
+ next: toJsonSafe(snapshot.next ?? []).map(displayNode),
982
+ tasks: (snapshot.tasks ?? []).map(task => ({
983
+ id: displayNode(task.name ?? task.id ?? 'unknown'),
984
+ error: task.error === undefined || task.error === null
985
+ ? null
986
+ : { name: task.error.name ?? 'Error', message: task.error.message ?? String(task.error) },
987
+ })),
988
+ values: boundedValues(snapshot.values ?? {}, entry?.output),
989
+ })
990
+ if (lastSupersteps.length >= 3) break
991
+ }
992
+ } catch {
993
+ // History is best-effort; the failure is still reportable without it.
994
+ }
995
+ checkpoint = lastSupersteps[0]?.checkpoint
996
+ const next = lastSupersteps[0]?.next
997
+ if (Array.isArray(next) && next.length > 0) {
998
+ pending = [...new Set(next)]
999
+ }
1000
+ state = lastSupersteps[0]?.values
1001
+ }
1002
+
1003
+ // A registered graph module has no IR wrapper to annotate its node, but
1004
+ // the boundary checkpoint names the task that held the error.
1005
+ const failedTask = lastSupersteps[0]?.tasks.find(task => task.error !== null)
1006
+ if (failedNode === undefined && failedTask !== undefined) failedNode = failedTask.id
1007
+ if (failedNode === undefined && entry?.analysis !== undefined) {
1008
+ // A choice with no matching guard throws from the path function, outside
1009
+ // the node wrapper. The message still names the source node.
1010
+ const message = typeof annotated?.message === 'string' ? annotated.message : String(error)
1011
+ const match = /no outgoing edge matched at node "([^"]+)"/.exec(message)
1012
+ if (match !== null && entry.analysis.nodes.has(match[1])) failedNode = match[1]
1013
+ }
1014
+ if (pending.length === 0 && failedNode !== undefined) pending = [failedNode]
1015
+
1016
+ const analysis = entry?.analysis
1017
+ let failedScc = []
1018
+ if (analysis !== undefined && failedNode !== undefined && analysis.sccOf.has(failedNode)) {
1019
+ failedScc = [...analysis.sccs[analysis.sccOf.get(failedNode)]]
1020
+ }
1021
+ const upstream = analysis !== undefined && failedNode !== undefined
1022
+ ? upstreamOf(analysis, [failedNode]).filter(node => node !== failedNode && !failedScc.includes(node))
1023
+ : undefined
1024
+ const downstream = analysis !== undefined && failedNode !== undefined
1025
+ ? downstreamOf(analysis, failedScc.length > 0 ? failedScc : [failedNode])
1026
+ : undefined
1027
+
1028
+ const annotatedNode = annotated !== null && annotated !== undefined && annotated.nodeId !== undefined
1029
+ const errorInfo = {
1030
+ name: annotatedNode
1031
+ ? (typeof annotated.name === 'string' ? annotated.name : 'Error')
1032
+ : (failedTask?.error?.name ?? (typeof annotated?.name === 'string' ? annotated.name : 'Error')),
1033
+ message: annotatedNode
1034
+ ? (typeof annotated.message === 'string' ? annotated.message : String(annotated))
1035
+ : (failedTask?.error?.message ?? (typeof annotated?.message === 'string' ? annotated.message : String(error))),
1036
+ ...(failedNode === undefined ? {} : { node: failedNode }),
1037
+ ...(itemIndex === undefined ? {} : { itemIndex }),
1038
+ }
1039
+ return {
1040
+ status: 'failed',
1041
+ graph: id,
1042
+ durable: checkpointed,
1043
+ ...(thread === undefined ? {} : { thread }),
1044
+ ...(checkpoint === undefined ? {} : { checkpoint }),
1045
+ ...(failedNode === undefined ? {} : { failedNode }),
1046
+ ...(failedScc.length === 0 ? {} : { failedScc }),
1047
+ pending,
1048
+ ...(downstream === undefined ? {} : { downstream }),
1049
+ ...(upstream === undefined ? {} : { upstream }),
1050
+ lastSupersteps,
1051
+ error: errorInfo,
1052
+ ...(state === undefined ? {} : { state }),
1053
+ hint: entry?.composed === true
1054
+ ? 'transient -> resume with the same thread; state -> edit/replay; graph -> fork the downstream and compose'
1055
+ : 'transient -> resume with the same thread; state -> edit/replay',
1056
+ }
1057
+ }
1058
+
775
1059
  /**
776
1060
  * Execute one prepared graph run under its thread lock. Shared by the
777
1061
  * foreground tool path and a background job.
778
1062
  * @param {object} run - prepared run facts.
779
1063
  * @returns {Promise<object>} the model-facing run result.
780
1064
  */
781
- async function executeRun({ id, compiled, store, thread, requestedThread, checkpointed, args, tracer, signal, sessionId }) {
1065
+ async function executeRun({ id, entry, compiled, store, thread, requestedThread, checkpointed, args, tracer, signal, sessionId, maxSteps, maxConcurrency }) {
782
1066
  return await withThreadLock(thread, async () => {
783
1067
  if (thread !== undefined) {
784
1068
  const owner = { graph: id, ...(sessionId === undefined ? {} : { sessionId }) }
@@ -798,7 +1082,10 @@ export function apply(ctx, config) {
798
1082
  ? args.checkpoint.trim()
799
1083
  : undefined
800
1084
  const config = {
801
- recursionLimit: Number.isInteger(args?.maxSteps) ? args.maxSteps : recursionLimit,
1085
+ recursionLimit: Number.isInteger(args?.maxSteps)
1086
+ ? args.maxSteps
1087
+ : Number.isInteger(maxSteps) ? maxSteps : recursionLimit,
1088
+ ...(maxConcurrency === undefined ? {} : { maxConcurrency }),
802
1089
  ...(thread === undefined ? {} : {
803
1090
  configurable: {
804
1091
  thread_id: thread,
@@ -852,9 +1139,28 @@ export function apply(ctx, config) {
852
1139
  mode = 'input'
853
1140
  }
854
1141
 
855
- const output = await compiled.invoke(input, { ...config, callbacks: tracer.callbacks })
1142
+ const startedAt = Date.now()
1143
+ let output
1144
+ try {
1145
+ output = await compiled.invoke(input, { ...config, callbacks: tracer.callbacks })
1146
+ } catch (error) {
1147
+ // A cancelled run is not a graph failure; cancellation is handled by
1148
+ // the caller or by the background job's cancel path.
1149
+ if (signal?.aborted || error?.name === 'AbortError') throw error
1150
+ return await failureResult({ id, entry, compiled, config, thread, checkpointed, error })
1151
+ }
856
1152
  const interrupts = output?.__interrupt__
857
1153
  const state = toJsonSafe(withoutInterrupts(output))
1154
+ let steps
1155
+ if (typeof compiled.getState === 'function') {
1156
+ try {
1157
+ const snapshot = await compiled.getState(config)
1158
+ if (Number.isInteger(snapshot?.metadata?.step)) steps = snapshot.metadata.step
1159
+ } catch {
1160
+ // A non-checkpointed graph has no persisted step count.
1161
+ }
1162
+ }
1163
+ const report = { durationMs: Date.now() - startedAt, ...(steps === undefined ? {} : { steps }) }
858
1164
  const head = {
859
1165
  graph: id,
860
1166
  mode,
@@ -869,9 +1175,10 @@ export function apply(ctx, config) {
869
1175
  interrupts: toJsonSafe(interrupts),
870
1176
  hint: 'Answer with `langgraph_run({ graph, thread, resume: <value> })`.',
871
1177
  state,
1178
+ report,
872
1179
  }
873
1180
  }
874
- return { ...head, status: 'completed', state }
1181
+ return { ...head, status: 'completed', state, report }
875
1182
  })
876
1183
  }
877
1184
 
@@ -917,6 +1224,7 @@ export function apply(ctx, config) {
917
1224
  }
918
1225
  const result = await executeRun({
919
1226
  id,
1227
+ entry,
920
1228
  compiled,
921
1229
  store,
922
1230
  thread: checkpointed ? thread : undefined,
@@ -926,7 +1234,17 @@ export function apply(ctx, config) {
926
1234
  tracer,
927
1235
  signal: controller.signal,
928
1236
  sessionId,
1237
+ maxSteps: entry.maxSteps,
1238
+ maxConcurrency: entry.maxConcurrency,
929
1239
  })
1240
+ if (result?.status === 'failed') {
1241
+ job.updateProgress('failed')
1242
+ return {
1243
+ status: 'failed',
1244
+ detail: result.error?.message ?? 'the graph run failed',
1245
+ result: renderJobResult(result),
1246
+ }
1247
+ }
930
1248
  if (result?.error !== undefined) return { status: 'failed', detail: result.error }
931
1249
  job.updateProgress(result.status === 'interrupted' ? 'interrupted' : 'completed')
932
1250
  return {
@@ -960,10 +1278,11 @@ export function apply(ctx, config) {
960
1278
  async function runGraph(args, exec) {
961
1279
  await scan()
962
1280
  const id = typeof args?.graph === 'string' ? args.graph.trim() : ''
963
- if (id === '') return { answer: await describeGraphs() }
964
- const entry = registry.get(id)
1281
+ if (id === '') return { answer: await describeGraphs(exec) }
1282
+ const sessionId = exec?.agent?.id
1283
+ const entry = await resolveEntry(id, sessionId)
965
1284
  if (entry === undefined) {
966
- return { error: `unknown graph "${id}". Registered: ${[...registry.keys()].join(', ') || '(none)'}` }
1285
+ return { error: unknownGraphMessage(id, true) }
967
1286
  }
968
1287
  if (entry.error !== undefined) {
969
1288
  return { error: `graph "${id}" is unavailable: ${entry.error.message}` }
@@ -971,7 +1290,6 @@ export function apply(ctx, config) {
971
1290
 
972
1291
  const { saver, durable, store: checkpointStore } = await ensureSaver()
973
1292
  const { store: graphStore } = await ensureGraphStore()
974
- const sessionId = exec?.agent?.id
975
1293
  const requestedThread = typeof args.thread === 'string' && args.thread.trim() !== '' ? args.thread.trim() : undefined
976
1294
  const requestedCheckpoint = typeof args?.checkpoint === 'string' && args.checkpoint.trim() !== '' ? args.checkpoint.trim() : undefined
977
1295
  if (requestedCheckpoint !== undefined && requestedThread === undefined) {
@@ -999,6 +1317,7 @@ export function apply(ctx, config) {
999
1317
  if (conflict !== undefined) return { error: conflict }
1000
1318
  return await executeRun({
1001
1319
  id,
1320
+ entry,
1002
1321
  compiled,
1003
1322
  store: checkpointStore,
1004
1323
  thread,
@@ -1008,6 +1327,8 @@ export function apply(ctx, config) {
1008
1327
  tracer,
1009
1328
  signal: exec?.signal,
1010
1329
  sessionId,
1330
+ maxSteps: entry.maxSteps,
1331
+ maxConcurrency: entry.maxConcurrency,
1011
1332
  })
1012
1333
  }
1013
1334
 
@@ -1042,8 +1363,8 @@ export function apply(ctx, config) {
1042
1363
  if (action === 'topology') {
1043
1364
  const id = typeof args?.graph === 'string' ? args.graph.trim() : ''
1044
1365
  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}"` }
1366
+ const entry = await resolveEntry(id, sessionId)
1367
+ if (entry === undefined) return { error: unknownGraphMessage(id) }
1047
1368
  if (entry.error !== undefined) return { error: `graph "${id}" is unavailable: ${entry.error.message}` }
1048
1369
  try {
1049
1370
  return await topologyOf(entry)
@@ -1057,8 +1378,8 @@ export function apply(ctx, config) {
1057
1378
  if (id === '' || thread === '') {
1058
1379
  return { error: `\`graph\` and \`thread\` are required to ${action === 'edit' ? 'edit' : 'read'} a thread` }
1059
1380
  }
1060
- const entry = registry.get(id)
1061
- if (entry === undefined) return { error: `unknown graph "${id}"` }
1381
+ const entry = await resolveEntry(id, sessionId)
1382
+ if (entry === undefined) return { error: unknownGraphMessage(id) }
1062
1383
  if (entry.error !== undefined) return { error: `graph "${id}" is unavailable: ${entry.error.message}` }
1063
1384
  const conflict = threadConflict(store, thread, sessionId, id)
1064
1385
  if (conflict !== undefined) return { error: conflict }
@@ -1195,12 +1516,13 @@ export function apply(ctx, config) {
1195
1516
 
1196
1517
  ctx.effect(() => ctx.tools.register({
1197
1518
  name: RUN_TOOL,
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`.',
1519
+ description: 'Run one LangGraph graph by id: a registered graph or one composed with `langgraph_compose` '
1520
+ + 'in this session. Use it when the user names a graph, a graph\'s description matches the requested '
1521
+ + 'output, or the task needs a durable thread, background job, checkpoint replay, or Trajectory record; '
1522
+ + 'it is not the `workflow` tool. Omit `graph` to list graphs and input schemas. Threads are durable '
1523
+ + 'LangGraph checkpoint chains (not DSH Sessions): pass `thread` to continue one, `resume` to answer '
1524
+ + 'an interrupt, and `checkpoint` to replay a snapshot from `langgraph_threads` history. '
1525
+ + '`run_in_background` returns a DSH job id for `job_output`/`job_kill`.',
1204
1526
  parameters: {
1205
1527
  type: 'object',
1206
1528
  properties: {
@@ -1236,10 +1558,11 @@ export function apply(ctx, config) {
1236
1558
 
1237
1559
  ctx.effect(() => ctx.tools.register({
1238
1560
  name: THREADS_TOOL,
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 })`.',
1561
+ description: 'Manage durable LangGraph threads and a graph\'s topology, for registered and composed '
1562
+ + 'graphs. `list` (this session by default), `state` (values, next, interrupts), `history` '
1563
+ + '(checkpoint ids), `edit` (fork a checkpoint with new values), `topology` (nodes/edges), or '
1564
+ + '`delete`. A thread is a LangGraph checkpoint chain, not a DSH Session. Replay an edit with '
1565
+ + '`langgraph_run({ checkpoint })`.',
1243
1566
  parameters: {
1244
1567
  type: 'object',
1245
1568
  properties: {
@@ -1262,6 +1585,62 @@ export function apply(ctx, config) {
1262
1585
  execute: (args, exec) => manageThreads(args ?? {}, exec),
1263
1586
  }), 'langgraph: threads tool')
1264
1587
 
1588
+ ctx.effect(() => ctx.tools.register({
1589
+ name: COMPOSE_TOOL,
1590
+ description: 'Compose a session-owned LangGraph graph from a strict JSON GraphSpec, then run it with '
1591
+ + '`langgraph_run`. Actions: `describe` (the guide, law, reference and archetype examples), `validate`, '
1592
+ + '`compose`, `list`, `get`, `delete`, `fork`. Read the guide before the first compose; it is the '
1593
+ + 'whole contract. Keep the graph coarse; open-ended work belongs in an `agent` node. A composed graph is an immutable '
1594
+ + 'session spec, not a file and not a DSH Session. After a failure, `fork` from the failed node '
1595
+ + 'returns an editable downstream spec.',
1596
+ parameters: {
1597
+ type: 'object',
1598
+ properties: {
1599
+ action: {
1600
+ type: 'string',
1601
+ enum: [...COMPOSE_ACTIONS],
1602
+ description: 'describe, validate, compose, list, get, or delete.',
1603
+ },
1604
+ spec: {
1605
+ type: 'object',
1606
+ description: 'The GraphSpec IR object; required by validate and compose unless `path` is given.',
1607
+ additionalProperties: true,
1608
+ },
1609
+ path: {
1610
+ type: 'string',
1611
+ description: 'Workspace-relative .json spec file; an alternative to `spec`.',
1612
+ },
1613
+ graph: {
1614
+ type: 'string',
1615
+ description: 'Composed graph id (lg_adhoc_...); required by get, delete, and fork.',
1616
+ },
1617
+ from: {
1618
+ type: 'string',
1619
+ description: 'Fork: the node to rewrite from, usually the failure result\'s `failedNode`.',
1620
+ },
1621
+ thread: {
1622
+ type: 'string',
1623
+ description: 'Fork: the thread whose head state becomes the new graph\'s input.',
1624
+ },
1625
+ limit: {
1626
+ type: 'integer',
1627
+ description: 'Maximum composed graphs to list (default 20).',
1628
+ },
1629
+ delete_threads: {
1630
+ type: 'boolean',
1631
+ description: 'Delete the graph\'s threads with it; otherwise delete refuses while threads exist.',
1632
+ },
1633
+ },
1634
+ required: ['action'],
1635
+ additionalProperties: false,
1636
+ },
1637
+ output: {
1638
+ schema: { type: 'object', additionalProperties: true },
1639
+ render: (_args, value) => [{ type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) }],
1640
+ },
1641
+ execute: (args, exec) => composeGraph(args ?? {}, exec),
1642
+ }), 'langgraph: compose tool')
1643
+
1265
1644
  // --- owner UI routes ----------------------------------------------------------
1266
1645
  // The optional client panel reads these authenticated, owner-only exact routes.
1267
1646
  // A headless Host has no `connection` service, so nothing is served; no DSH
@@ -1312,8 +1691,10 @@ export function apply(ctx, config) {
1312
1691
  await scan()
1313
1692
  const id = new URL(request.url).searchParams.get('graph') ?? ''
1314
1693
  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)
1694
+ // The route is already owner-only at the DSH layer; the panel may show
1695
+ // any of this user's sessions' composed graphs by id.
1696
+ const entry = await resolveEntry(id, undefined, { allSessions: true })
1697
+ if (entry === undefined) return json({ error: unknownGraphMessage(id) }, 404)
1317
1698
  if (entry.error !== undefined) return json({ error: `graph "${id}" is unavailable: ${entry.error.message}` }, 500)
1318
1699
  try {
1319
1700
  return json(await topologyOf(entry))