@lzn1998/dsh-langgraph 1.0.1 → 1.6.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/README.md +172 -51
- package/bench/README.md +54 -0
- package/bench/demo-video.mjs +208 -0
- package/bench/results-harness.json +125 -0
- package/bench/run.mjs +139 -0
- package/compose/analysis.js +359 -0
- package/compose/build.js +274 -0
- package/compose/constants.js +83 -0
- package/compose/guard.js +72 -0
- package/compose/nodes.js +214 -0
- package/compose/resolve.js +97 -0
- package/compose/schema.js +975 -0
- package/compose/specs.js +218 -0
- package/compose/template.js +260 -0
- package/compose/tool.js +713 -0
- package/docs/BENCHMARK.md +116 -0
- package/docs/COMPOSE.md +376 -0
- package/docs/CONTEXT.md +34 -18
- package/docs/DETAIL.md +48 -1
- package/docs/ECOSYSTEM.md +30 -5
- package/gallery/README.md +69 -0
- package/gallery/assets/gallery.png +0 -0
- package/gallery/assets/session.png +0 -0
- package/gallery/index.html +516 -0
- package/gallery/specs/approval-plan.lg.json +51 -0
- package/gallery/specs/data-extract.lg.json +75 -0
- package/gallery/specs/incident-triage.lg.json +64 -0
- package/gallery/specs/pr-review.lg.json +49 -0
- package/gallery/specs/repo-scan.lg.json +54 -0
- package/gallery/specs/research-brief.lg.json +94 -0
- package/index.d.ts +136 -0
- package/index.js +423 -46
- package/media/dsh-langgraph-demo.webm +0 -0
- package/media/raw/page@0d0adc4d6eb7b946d722093988db7e67.webm +0 -0
- package/media/raw/page@0fceaacbda6d8f2da8485736c565ed87.webm +0 -0
- package/media/raw/page@49c6bb9135c0c35ed8cf9054a8e05711.webm +0 -0
- package/media/raw/page@86f5e37e1c1218697f8724a6bafda8d2.webm +0 -0
- package/media/raw/page@9b5b70b442c0ace7d4b135fc80edba73.webm +0 -0
- package/media/raw/page@beb9164240f13ad017c3fa7e8f20a772.webm +0 -0
- package/media/raw/page@db4ee1834adcc9e8d5b4708eabe4eb5c.webm +0 -0
- package/media/raw/page@e9c63a0029d3181e41506fc4bf8da05a.webm +0 -0
- package/media/raw/page@eaf729b06925fe86e9e9e4bf48e2cdcc.webm +0 -0
- package/media/raw/page@f0d6fd1a2534e69bc2f228b30ae19a9c.webm +0 -0
- package/package.json +7 -3
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
|
|
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
|
|
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
|
|
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,16 +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
|
-
|
|
165
|
-
|
|
166
|
-
'`langgraph_run` only runs graphs already registered with this profile; it cannot define a new one, '
|
|
167
|
-
+ 'so do not invent an id. For one-off or still-unclear work, compose ordinary DSH tools (or use '
|
|
168
|
-
+ '`workflow` for an ad-hoc fan-out). A shape worth reusing belongs in a profile graph module, '
|
|
169
|
-
+ 'which then appears in this list.',
|
|
170
|
-
'A LangGraph thread is a durable checkpoint chain for one graph run, not a DSH Session. '
|
|
171
|
-
+ 'Use `langgraph_threads` to list, inspect, time-travel, or delete threads, or read a graph\'s topology.',
|
|
231
|
+
...composeGuidance,
|
|
232
|
+
threadGuidance,
|
|
172
233
|
`Registered graphs:\n${lines.join('\n')}`,
|
|
173
|
-
'Omit `graph` to list input schemas.',
|
|
234
|
+
'Omit `graph` to list input schemas, or composed graphs in this session.',
|
|
174
235
|
].join('\n\n')
|
|
175
236
|
}
|
|
176
237
|
|
|
@@ -210,11 +271,13 @@ export function apply(ctx, config) {
|
|
|
210
271
|
let opened
|
|
211
272
|
let openFailure
|
|
212
273
|
let openedGraphStore
|
|
274
|
+
let openedSpecStore
|
|
213
275
|
let disposed = false
|
|
214
276
|
ctx.effect(() => () => {
|
|
215
277
|
disposed = true
|
|
216
278
|
if (opened !== undefined) void opened.close()
|
|
217
279
|
if (openedGraphStore !== undefined) void openedGraphStore.close()
|
|
280
|
+
if (openedSpecStore !== undefined) void openedSpecStore.close()
|
|
218
281
|
})
|
|
219
282
|
|
|
220
283
|
/** @type {Promise<object | undefined> | undefined} */
|
|
@@ -297,6 +360,56 @@ export function apply(ctx, config) {
|
|
|
297
360
|
return { store: memoryGraphStore, durableStore: false }
|
|
298
361
|
}
|
|
299
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
|
+
|
|
300
413
|
/**
|
|
301
414
|
* Why this caller may not use a thread, or undefined when it may. A durable
|
|
302
415
|
* thread is owned by the graph and session that created it; resuming it from
|
|
@@ -687,17 +800,37 @@ export function apply(ctx, config) {
|
|
|
687
800
|
}
|
|
688
801
|
|
|
689
802
|
// --- tools --------------------------------------------------------------------
|
|
690
|
-
async function describeGraphs() {
|
|
803
|
+
async function describeGraphs(exec) {
|
|
691
804
|
await scan()
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
.
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
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
|
+
}
|
|
701
834
|
const { durable } = await ensureSaver()
|
|
702
835
|
lines.push('', durable
|
|
703
836
|
? 'Threads are durable: pass `thread` to continue a thread, `resume` to answer an interrupt.'
|
|
@@ -765,6 +898,41 @@ export function apply(ctx, config) {
|
|
|
765
898
|
}
|
|
766
899
|
}
|
|
767
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
|
+
|
|
768
936
|
/** Bound one background job's model-facing result text. */
|
|
769
937
|
function renderJobResult(result) {
|
|
770
938
|
let text
|
|
@@ -776,13 +944,125 @@ export function apply(ctx, config) {
|
|
|
776
944
|
return text.length > 50000 ? `${text.slice(0, 50000)}\n… [truncated ${text.length - 50000} chars]` : text
|
|
777
945
|
}
|
|
778
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
|
+
|
|
779
1059
|
/**
|
|
780
1060
|
* Execute one prepared graph run under its thread lock. Shared by the
|
|
781
1061
|
* foreground tool path and a background job.
|
|
782
1062
|
* @param {object} run - prepared run facts.
|
|
783
1063
|
* @returns {Promise<object>} the model-facing run result.
|
|
784
1064
|
*/
|
|
785
|
-
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 }) {
|
|
786
1066
|
return await withThreadLock(thread, async () => {
|
|
787
1067
|
if (thread !== undefined) {
|
|
788
1068
|
const owner = { graph: id, ...(sessionId === undefined ? {} : { sessionId }) }
|
|
@@ -802,7 +1082,10 @@ export function apply(ctx, config) {
|
|
|
802
1082
|
? args.checkpoint.trim()
|
|
803
1083
|
: undefined
|
|
804
1084
|
const config = {
|
|
805
|
-
recursionLimit: Number.isInteger(args?.maxSteps)
|
|
1085
|
+
recursionLimit: Number.isInteger(args?.maxSteps)
|
|
1086
|
+
? args.maxSteps
|
|
1087
|
+
: Number.isInteger(maxSteps) ? maxSteps : recursionLimit,
|
|
1088
|
+
...(maxConcurrency === undefined ? {} : { maxConcurrency }),
|
|
806
1089
|
...(thread === undefined ? {} : {
|
|
807
1090
|
configurable: {
|
|
808
1091
|
thread_id: thread,
|
|
@@ -856,9 +1139,28 @@ export function apply(ctx, config) {
|
|
|
856
1139
|
mode = 'input'
|
|
857
1140
|
}
|
|
858
1141
|
|
|
859
|
-
const
|
|
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
|
+
}
|
|
860
1152
|
const interrupts = output?.__interrupt__
|
|
861
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 }) }
|
|
862
1164
|
const head = {
|
|
863
1165
|
graph: id,
|
|
864
1166
|
mode,
|
|
@@ -873,9 +1175,10 @@ export function apply(ctx, config) {
|
|
|
873
1175
|
interrupts: toJsonSafe(interrupts),
|
|
874
1176
|
hint: 'Answer with `langgraph_run({ graph, thread, resume: <value> })`.',
|
|
875
1177
|
state,
|
|
1178
|
+
report,
|
|
876
1179
|
}
|
|
877
1180
|
}
|
|
878
|
-
return { ...head, status: 'completed', state }
|
|
1181
|
+
return { ...head, status: 'completed', state, report }
|
|
879
1182
|
})
|
|
880
1183
|
}
|
|
881
1184
|
|
|
@@ -921,6 +1224,7 @@ export function apply(ctx, config) {
|
|
|
921
1224
|
}
|
|
922
1225
|
const result = await executeRun({
|
|
923
1226
|
id,
|
|
1227
|
+
entry,
|
|
924
1228
|
compiled,
|
|
925
1229
|
store,
|
|
926
1230
|
thread: checkpointed ? thread : undefined,
|
|
@@ -930,7 +1234,17 @@ export function apply(ctx, config) {
|
|
|
930
1234
|
tracer,
|
|
931
1235
|
signal: controller.signal,
|
|
932
1236
|
sessionId,
|
|
1237
|
+
maxSteps: entry.maxSteps,
|
|
1238
|
+
maxConcurrency: entry.maxConcurrency,
|
|
933
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
|
+
}
|
|
934
1248
|
if (result?.error !== undefined) return { status: 'failed', detail: result.error }
|
|
935
1249
|
job.updateProgress(result.status === 'interrupted' ? 'interrupted' : 'completed')
|
|
936
1250
|
return {
|
|
@@ -964,10 +1278,11 @@ export function apply(ctx, config) {
|
|
|
964
1278
|
async function runGraph(args, exec) {
|
|
965
1279
|
await scan()
|
|
966
1280
|
const id = typeof args?.graph === 'string' ? args.graph.trim() : ''
|
|
967
|
-
if (id === '') return { answer: await describeGraphs() }
|
|
968
|
-
const
|
|
1281
|
+
if (id === '') return { answer: await describeGraphs(exec) }
|
|
1282
|
+
const sessionId = exec?.agent?.id
|
|
1283
|
+
const entry = await resolveEntry(id, sessionId)
|
|
969
1284
|
if (entry === undefined) {
|
|
970
|
-
return { error:
|
|
1285
|
+
return { error: unknownGraphMessage(id, true) }
|
|
971
1286
|
}
|
|
972
1287
|
if (entry.error !== undefined) {
|
|
973
1288
|
return { error: `graph "${id}" is unavailable: ${entry.error.message}` }
|
|
@@ -975,7 +1290,6 @@ export function apply(ctx, config) {
|
|
|
975
1290
|
|
|
976
1291
|
const { saver, durable, store: checkpointStore } = await ensureSaver()
|
|
977
1292
|
const { store: graphStore } = await ensureGraphStore()
|
|
978
|
-
const sessionId = exec?.agent?.id
|
|
979
1293
|
const requestedThread = typeof args.thread === 'string' && args.thread.trim() !== '' ? args.thread.trim() : undefined
|
|
980
1294
|
const requestedCheckpoint = typeof args?.checkpoint === 'string' && args.checkpoint.trim() !== '' ? args.checkpoint.trim() : undefined
|
|
981
1295
|
if (requestedCheckpoint !== undefined && requestedThread === undefined) {
|
|
@@ -1003,6 +1317,7 @@ export function apply(ctx, config) {
|
|
|
1003
1317
|
if (conflict !== undefined) return { error: conflict }
|
|
1004
1318
|
return await executeRun({
|
|
1005
1319
|
id,
|
|
1320
|
+
entry,
|
|
1006
1321
|
compiled,
|
|
1007
1322
|
store: checkpointStore,
|
|
1008
1323
|
thread,
|
|
@@ -1012,6 +1327,8 @@ export function apply(ctx, config) {
|
|
|
1012
1327
|
tracer,
|
|
1013
1328
|
signal: exec?.signal,
|
|
1014
1329
|
sessionId,
|
|
1330
|
+
maxSteps: entry.maxSteps,
|
|
1331
|
+
maxConcurrency: entry.maxConcurrency,
|
|
1015
1332
|
})
|
|
1016
1333
|
}
|
|
1017
1334
|
|
|
@@ -1046,8 +1363,8 @@ export function apply(ctx, config) {
|
|
|
1046
1363
|
if (action === 'topology') {
|
|
1047
1364
|
const id = typeof args?.graph === 'string' ? args.graph.trim() : ''
|
|
1048
1365
|
if (id === '') return { error: '`graph` is required to read a topology' }
|
|
1049
|
-
const entry =
|
|
1050
|
-
if (entry === undefined) return { error:
|
|
1366
|
+
const entry = await resolveEntry(id, sessionId)
|
|
1367
|
+
if (entry === undefined) return { error: unknownGraphMessage(id) }
|
|
1051
1368
|
if (entry.error !== undefined) return { error: `graph "${id}" is unavailable: ${entry.error.message}` }
|
|
1052
1369
|
try {
|
|
1053
1370
|
return await topologyOf(entry)
|
|
@@ -1061,8 +1378,8 @@ export function apply(ctx, config) {
|
|
|
1061
1378
|
if (id === '' || thread === '') {
|
|
1062
1379
|
return { error: `\`graph\` and \`thread\` are required to ${action === 'edit' ? 'edit' : 'read'} a thread` }
|
|
1063
1380
|
}
|
|
1064
|
-
const entry =
|
|
1065
|
-
if (entry === undefined) return { error:
|
|
1381
|
+
const entry = await resolveEntry(id, sessionId)
|
|
1382
|
+
if (entry === undefined) return { error: unknownGraphMessage(id) }
|
|
1066
1383
|
if (entry.error !== undefined) return { error: `graph "${id}" is unavailable: ${entry.error.message}` }
|
|
1067
1384
|
const conflict = threadConflict(store, thread, sessionId, id)
|
|
1068
1385
|
if (conflict !== undefined) return { error: conflict }
|
|
@@ -1199,12 +1516,13 @@ export function apply(ctx, config) {
|
|
|
1199
1516
|
|
|
1200
1517
|
ctx.effect(() => ctx.tools.register({
|
|
1201
1518
|
name: RUN_TOOL,
|
|
1202
|
-
description: 'Run one
|
|
1203
|
-
+ '
|
|
1204
|
-
+ '
|
|
1205
|
-
+ '
|
|
1206
|
-
+ '
|
|
1207
|
-
+ '
|
|
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`.',
|
|
1208
1526
|
parameters: {
|
|
1209
1527
|
type: 'object',
|
|
1210
1528
|
properties: {
|
|
@@ -1240,10 +1558,11 @@ export function apply(ctx, config) {
|
|
|
1240
1558
|
|
|
1241
1559
|
ctx.effect(() => ctx.tools.register({
|
|
1242
1560
|
name: THREADS_TOOL,
|
|
1243
|
-
description: 'Manage durable LangGraph threads and a graph\'s topology
|
|
1244
|
-
+ '`
|
|
1245
|
-
+ 'values), `topology` (nodes/edges), or
|
|
1246
|
-
+ 'DSH Session. Replay an edit with
|
|
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 })`.',
|
|
1247
1566
|
parameters: {
|
|
1248
1567
|
type: 'object',
|
|
1249
1568
|
properties: {
|
|
@@ -1266,6 +1585,62 @@ export function apply(ctx, config) {
|
|
|
1266
1585
|
execute: (args, exec) => manageThreads(args ?? {}, exec),
|
|
1267
1586
|
}), 'langgraph: threads tool')
|
|
1268
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
|
+
|
|
1269
1644
|
// --- owner UI routes ----------------------------------------------------------
|
|
1270
1645
|
// The optional client panel reads these authenticated, owner-only exact routes.
|
|
1271
1646
|
// A headless Host has no `connection` service, so nothing is served; no DSH
|
|
@@ -1316,8 +1691,10 @@ export function apply(ctx, config) {
|
|
|
1316
1691
|
await scan()
|
|
1317
1692
|
const id = new URL(request.url).searchParams.get('graph') ?? ''
|
|
1318
1693
|
if (id === '') return json({ error: '`graph` query parameter is required' }, 400)
|
|
1319
|
-
|
|
1320
|
-
|
|
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)
|
|
1321
1698
|
if (entry.error !== undefined) return json({ error: `graph "${id}" is unavailable: ${entry.error.message}` }, 500)
|
|
1322
1699
|
try {
|
|
1323
1700
|
return json(await topologyOf(entry))
|
|
Binary file
|
|
Binary file
|