@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/README.md CHANGED
@@ -1,10 +1,10 @@
1
1
  # dsh-langgraph
2
2
 
3
- A DSH bundle that registers LangGraph graphs and exposes them to the agent as the
4
- `langgraph_run` and `langgraph_threads` tools. Graph nodes call the session's own DSH
5
- tools through `helpers.callTool`; threads are checkpointed in a DSH storage domain, so a
6
- run survives the turn — and the Host process — and an `interrupt()`ed graph resumes
7
- where it stopped.
3
+ A DSH bundle that registers LangGraph graphs, composes session-owned ones at runtime, and
4
+ exposes them to the agent as the `langgraph_run`, `langgraph_threads`, and
5
+ `langgraph_compose` tools. Graph nodes call the session's own DSH tools through
6
+ `helpers.callTool`; threads are checkpointed in a DSH storage domain, so a run survives
7
+ the turn — and the Host process — and an `interrupt()`ed graph resumes where it stopped.
8
8
 
9
9
  - `langgraph_run` (`graph`, `input`, `thread`, `resume`, `maxSteps`, `run_in_background`;
10
10
  omit `graph` to list). A background run returns a DSH job id; read it with `job_output`
@@ -13,7 +13,13 @@ where it stopped.
13
13
  `history` lists checkpoints, `state` reads one by `checkpoint`, and `edit` forks a
14
14
  checkpoint with new values. Replay the fork with `langgraph_run({ graph, thread, checkpoint })`.
15
15
  `topology` returns a graph's JSON-safe nodes and edges for a client view.
16
+ - `langgraph_compose` (`action`: `describe` | `validate` | `compose` | `list` | `get` | `delete` | `fork`).
17
+ A composed graph is a strict JSON `GraphSpec` stored as an immutable, session-owned
18
+ spec (`lg_adhoc_...`); `langgraph_run` runs it with the same threads, interrupts,
19
+ background jobs, traces, and time travel. `fork` returns an editable downstream spec
20
+ after a failure. See [docs/COMPOSE.md](docs/COMPOSE.md).
16
21
  - Registry: `graphs/*.js` (and `graphs/*.ts` on Node 24.22+) in this package plus `config.graphs`.
22
+ Composed specs are a separate, session-owned source and do not enter the profile registry.
17
23
  - Node helpers: `helpers.callTool(name, args)` for DSH tools, `helpers.askUser(questions)`
18
24
  for a question in DSH's native question UI, `helpers.subagent(prompt, options)` for a
19
25
  caller-delivered DSH child agent, `helpers.callModel(prompt, options)` for this
@@ -28,7 +34,10 @@ where it stopped.
28
34
  it falls back to `InMemoryStore`; `config.store: false` passes no store at all.
29
35
  - **Model-facing guidance:** while loaded, a system-prompt section lists the registered
30
36
  graph ids and descriptions, distinguishes `langgraph_run` from the `workflow` tool, and
31
- tells the model to use a matching graph rather than reimplement it. `config.prompt: false`
37
+ tells the model to use a matching graph rather than reimplement it. It also states the
38
+ compose principle (seams, coarse graph, open work in `agent`), that a composed graph is
39
+ immutable and session-owned, and how to recover from a failed run. The numeric
40
+ thresholds live in the advisory lint and the on-demand `describe`. `config.prompt: false`
32
41
  disables it.
33
42
  - **Trajectory trace:** each run shows up as one `langgraph_run` row; its graph nodes, DSH
34
43
  tool calls, and model calls appear as nested sub-calls in **Trajectory** — `langgraph:node`,
@@ -45,6 +54,8 @@ where it stopped.
45
54
  (nodes, edges, conditional branches). It reads two owner-only `/api/plugins/langgraph/*`
46
55
  routes; `config.ui: false` registers neither. Token-level streaming is not part of this
47
56
  panel; runs stay visible in Trajectory.
57
+ - See `docs/COMPOSE.md` for the JSON IR, the compose tool, map/fan-out semantics,
58
+ structured failures, recovery, fork, and limits.
48
59
  - See `docs/DETAIL.md` for the graph module contract, trace mapping, thread semantics, and limits.
49
60
  - See `docs/CONTEXT.md` for what is injected into the model context, the vocabulary, and
50
61
  how it stays distinct from DSH's `workflow`, `subagent`, and question tools.
@@ -0,0 +1,359 @@
1
+ /**
2
+ * Graph analysis for the GraphSpec IR: adjacency, Tarjan SCCs, reachability,
3
+ * writer/reducer checks for static fan-out, and advisory lint.
4
+ *
5
+ * Analysis never mutates a spec and never builds a graph. The compiler uses it
6
+ * for validation; the failure report and the future `fork` action use it to name
7
+ * a failed node's cycle and downstream.
8
+ */
9
+
10
+ import { END, START } from './constants.js'
11
+ import { hasStateKey, isPlainObject } from './template.js'
12
+
13
+ /** Group edges by source, keeping the spec's edge order. */
14
+ function groupBySource(spec) {
15
+ const outgoing = new Map()
16
+ for (const edge of spec.edges ?? []) {
17
+ if (!outgoing.has(edge.from)) outgoing.set(edge.from, [])
18
+ outgoing.get(edge.from).push(edge)
19
+ }
20
+ return outgoing
21
+ }
22
+
23
+ /** Group edges by target. */
24
+ function groupByTarget(spec) {
25
+ const incoming = new Map()
26
+ for (const edge of spec.edges ?? []) {
27
+ if (!incoming.has(edge.to)) incoming.set(edge.to, [])
28
+ incoming.get(edge.to).push(edge)
29
+ }
30
+ return incoming
31
+ }
32
+
33
+ /** Breadth-first reachability over `outgoing` edges. */
34
+ function reachable(outgoing, starts) {
35
+ const seen = new Set(starts)
36
+ const queue = [...starts]
37
+ while (queue.length > 0) {
38
+ const id = queue.shift()
39
+ for (const edge of outgoing.get(id) ?? []) {
40
+ if (!seen.has(edge.to)) {
41
+ seen.add(edge.to)
42
+ queue.push(edge.to)
43
+ }
44
+ }
45
+ }
46
+ return seen
47
+ }
48
+
49
+ /** Breadth-first reachability over `incoming` edges. */
50
+ function reverseReachable(incoming, starts) {
51
+ const seen = new Set(starts)
52
+ const queue = [...starts]
53
+ while (queue.length > 0) {
54
+ const id = queue.shift()
55
+ for (const edge of incoming.get(id) ?? []) {
56
+ if (!seen.has(edge.from)) {
57
+ seen.add(edge.from)
58
+ queue.push(edge.from)
59
+ }
60
+ }
61
+ }
62
+ return seen
63
+ }
64
+
65
+ /**
66
+ * Tarjan's strongly connected components over the spec's real nodes. START and
67
+ * END are excluded; a self-loop counts as a cycle.
68
+ * @param {Set<string>} nodeIds - real node ids.
69
+ * @param {(id: string) => string[]} successors - sorted successor node ids.
70
+ * @returns {string[][]} SCCs, each sorted, and the list sorted by first member.
71
+ */
72
+ function tarjan(nodeIds, successors) {
73
+ let nextIndex = 0
74
+ const index = new Map()
75
+ const low = new Map()
76
+ const stack = []
77
+ const onStack = new Set()
78
+ const components = []
79
+
80
+ function connect(id) {
81
+ index.set(id, nextIndex)
82
+ low.set(id, nextIndex)
83
+ nextIndex += 1
84
+ stack.push(id)
85
+ onStack.add(id)
86
+ for (const next of successors(id)) {
87
+ if (!index.has(next)) {
88
+ connect(next)
89
+ low.set(id, Math.min(low.get(id), low.get(next)))
90
+ } else if (onStack.has(next)) {
91
+ low.set(id, Math.min(low.get(id), index.get(next)))
92
+ }
93
+ }
94
+ if (low.get(id) === index.get(id)) {
95
+ const component = []
96
+ let member
97
+ do {
98
+ member = stack.pop()
99
+ onStack.delete(member)
100
+ component.push(member)
101
+ } while (member !== id)
102
+ components.push(component.sort())
103
+ }
104
+ }
105
+
106
+ for (const id of [...nodeIds].sort()) {
107
+ if (!index.has(id)) connect(id)
108
+ }
109
+ components.sort((left, right) => left[0].localeCompare(right[0]))
110
+ return components
111
+ }
112
+
113
+ /**
114
+ * Analyze one spec.
115
+ * @param {object} spec - a structurally valid GraphSpec.
116
+ * @returns {object} nodes, adjacency, SCCs, reachability, and the SCC of each node.
117
+ */
118
+ export function analyze(spec) {
119
+ const nodes = new Map((spec.nodes ?? []).map(node => [node.id, node]))
120
+ const outgoing = new Map()
121
+ const incoming = new Map()
122
+ for (const id of [START, ...nodes.keys(), END]) {
123
+ outgoing.set(id, [])
124
+ incoming.set(id, [])
125
+ }
126
+ for (const edge of spec.edges ?? []) {
127
+ const sourceExists = outgoing.has(edge.from)
128
+ const targetExists = incoming.has(edge.to)
129
+ if (!sourceExists || !targetExists) continue
130
+ outgoing.get(edge.from).push(edge)
131
+ incoming.get(edge.to).push(edge)
132
+ }
133
+
134
+ const nodeSuccessors = id => [...new Set(
135
+ (outgoing.get(id) ?? [])
136
+ .map(edge => edge.to)
137
+ .filter(target => nodes.has(target)),
138
+ )].sort()
139
+ const sccs = tarjan(new Set(nodes.keys()), nodeSuccessors)
140
+ const sccOf = new Map()
141
+ sccs.forEach((component, componentIndex) => {
142
+ for (const id of component) sccOf.set(id, componentIndex)
143
+ })
144
+
145
+ return {
146
+ nodes,
147
+ outgoing,
148
+ incoming,
149
+ sccs,
150
+ sccOf,
151
+ reachableFromStart: reachable(outgoing, [START]),
152
+ canReachEnd: reverseReachable(incoming, [END]),
153
+ }
154
+ }
155
+
156
+ /** Whether a node writes a state field through `out`, `set`, or a map body. */
157
+ export function writesField(node, field) {
158
+ if (node === undefined || node === null) return false
159
+ if (node.out !== undefined && Object.prototype.hasOwnProperty.call(node.out, field)) return true
160
+ if (node.do === 'set' && isPlainObject(node.values) && Object.prototype.hasOwnProperty.call(node.values, field)) return true
161
+ if (node.do === 'map' && writesField(node.body, field)) return true
162
+ return false
163
+ }
164
+
165
+ /** All node ids reachable from the given node ids, including them and END. */
166
+ export function downstreamOf(analysis, ids) {
167
+ const starts = Array.isArray(ids) ? ids : [ids]
168
+ return [...reachable(analysis.outgoing, starts)].sort()
169
+ }
170
+
171
+ /** All node ids that can reach the given node ids, including them and START. */
172
+ export function upstreamOf(analysis, ids) {
173
+ const starts = Array.isArray(ids) ? ids : [ids]
174
+ return [...reverseReachable(analysis.incoming, starts)].sort()
175
+ }
176
+
177
+ /**
178
+ * Validate the writer/reducer contract for static fan-out: when one node has
179
+ * two or more unconditional out-edges, every state field written by more than
180
+ * one of those branches must use a mergeable reducer.
181
+ * @param {object} spec - a structurally valid GraphSpec.
182
+ * @param {object} analysis - the result of `analyze(spec)`.
183
+ * @returns {Array<{ path: string, message: string, expected?: string }>} problems.
184
+ */
185
+ export function fanOutProblems(spec, analysis) {
186
+ const problems = []
187
+ const state = isPlainObject(spec.state) ? spec.state : {}
188
+ for (const source of [START, ...analysis.nodes.keys()]) {
189
+ const unconditional = (analysis.outgoing.get(source) ?? [])
190
+ .filter(edge => edge.when === undefined)
191
+ .map(edge => edge.to)
192
+ const branches = [...new Set(unconditional)]
193
+ .filter(target => analysis.nodes.has(target))
194
+ .sort()
195
+ if (branches.length < 2) continue
196
+ for (const field of Object.keys(state).sort()) {
197
+ const writers = branches.filter(branch => writesField(analysis.nodes.get(branch), field))
198
+ if (writers.length < 2) continue
199
+ const reducer = state[field]?.reducer ?? 'replace'
200
+ if (reducer !== 'replace') continue
201
+ problems.push({
202
+ path: `state.${field}`,
203
+ message: `field "${field}" is written by parallel branches ${writers.join(', ')} from "${source}" but has no mergeable reducer`,
204
+ expected: 'append | add | max | min | merge',
205
+ })
206
+ }
207
+ }
208
+ return problems
209
+ }
210
+
211
+ /**
212
+ * Advisory lint. None of these block a spec; they name shapes that usually mean
213
+ * the graph is too fine, cannot finish, or has unreachable work.
214
+ * @param {object} spec - a structurally valid GraphSpec.
215
+ * @param {object} analysis - the result of `analyze(spec)`.
216
+ * @returns {Array<{ path: string, message: string, code: string }>} warnings.
217
+ */
218
+ export function lintWarnings(spec, analysis) {
219
+ const warnings = []
220
+ const warn = (path, message, code) => warnings.push({ path, message, code })
221
+ const state = isPlainObject(spec.state) ? spec.state : {}
222
+
223
+ for (const node of spec.nodes ?? []) {
224
+ if ((analysis.outgoing.get(node.id) ?? []).length === 0) {
225
+ warn(`nodes.${node.id}`, 'node has no outgoing edge; the run ends here — connect it to END for clarity', 'terminal')
226
+ }
227
+ }
228
+
229
+ for (const id of [...analysis.nodes.keys()].sort()) {
230
+ if (!analysis.reachableFromStart.has(id)) {
231
+ warn(`nodes.${id}`, 'node is not reachable from START', 'unreachable')
232
+ } else if (!analysis.canReachEnd.has(id)) {
233
+ warn(`nodes.${id}`, 'node cannot reach END', 'dead-end')
234
+ }
235
+ }
236
+
237
+ if ((analysis.outgoing.get(START) ?? []).some(edge => edge.to === END)) {
238
+ warn('edges', 'START goes directly to END', 'empty-graph')
239
+ }
240
+
241
+ for (const [source, edges] of analysis.outgoing) {
242
+ if (source === END || edges.length === 0) continue
243
+ if (edges.every(edge => edge.when !== undefined) && !edges.some(edge => edge.when === true)) {
244
+ warn(`nodes.${source}`, 'choice has no `when: true` fallback; the run fails if no guard matches', 'no-fallback')
245
+ }
246
+ }
247
+
248
+ for (const node of spec.nodes ?? []) {
249
+ if (node.do !== 'gate' || !Array.isArray(node.options) || node.options.length === 0) continue
250
+ for (const [field, kind] of Object.entries(node.out ?? {})) {
251
+ if (kind !== 'bool') continue
252
+ warn(`nodes.${node.id}.out.${field}`, 'gate options are labels; bool accepts only true/false. Use out { decision: "text" } with an eq guard, or resume true/false.', 'gate-bool-options')
253
+ }
254
+ }
255
+
256
+ const numericWriter = node => {
257
+ const fields = []
258
+ if (node?.out !== undefined) fields.push(...Object.keys(node.out))
259
+ if (node?.do === 'set' && isPlainObject(node.values)) fields.push(...Object.keys(node.values))
260
+ if (node?.do === 'map' && node.body?.out !== undefined) fields.push(...Object.keys(node.body.out))
261
+ return fields.some(field => state[field]?.type === 'number')
262
+ }
263
+
264
+ for (const component of analysis.sccs) {
265
+ const members = [...component].sort()
266
+ const cyclic = members.length > 1
267
+ || (analysis.outgoing.get(members[0]) ?? []).some(edge => edge.to === members[0])
268
+ if (!cyclic) continue
269
+ warn(`nodes.${members[0]}`, `cycle: ${members.join(', ')}; bounded by maxSteps`, 'cycle')
270
+ const exits = members
271
+ .flatMap(id => analysis.outgoing.get(id) ?? [])
272
+ .filter(edge => !members.includes(edge.to))
273
+ if (!exits.some(edge => edge.when !== undefined)) {
274
+ warn(`nodes.${members[0]}`, 'cycle has no conditional exit; it runs until maxSteps', 'cycle-exit')
275
+ }
276
+ if (!members.some(id => numericWriter(analysis.nodes.get(id)))) {
277
+ warn(`nodes.${members[0]}`, 'cycle has no numeric counter; it may never terminate', 'cycle-counter')
278
+ }
279
+ if (spec.maxSteps === undefined) {
280
+ warn('maxSteps', 'cycle relies on the default 25-step budget; set maxSteps explicitly', 'cycle-budget')
281
+ }
282
+ }
283
+
284
+ // --- over-decomposition lint ------------------------------------------------
285
+ // Advisory only. The main failure mode of a composed graph is turning every
286
+ // tool call into a node; these warnings point at an `agent` node or ordinary
287
+ // tools instead.
288
+ const nodes = spec.nodes ?? []
289
+ if (nodes.length > 12) {
290
+ warn('nodes', `${nodes.length} nodes; coarse-first graphs usually use 4-8 phase nodes`, 'too-many-nodes')
291
+ }
292
+
293
+ const containsStateRef = value => {
294
+ if (hasStateKey(value)) return true
295
+ if (Array.isArray(value)) return value.some(containsStateRef)
296
+ if (isPlainObject(value)) return Object.values(value).some(containsStateRef)
297
+ return false
298
+ }
299
+
300
+ for (const node of nodes) {
301
+ if (node.do === 'tool') {
302
+ const component = analysis.sccs[analysis.sccOf.get(node.id)]
303
+ const cyclic = (component?.length ?? 1) > 1
304
+ || (analysis.outgoing.get(node.id) ?? []).some(edge => edge.to === node.id)
305
+ if (!cyclic && Object.values(node.args ?? {}).every(value => !containsStateRef(value))) {
306
+ warn(`nodes.${node.id}`, 'tool node has only literal arguments and runs once; consider merging it into an agent node', 'literal-tool')
307
+ }
308
+ }
309
+ if (node.do === 'model') {
310
+ const outgoing = analysis.outgoing.get(node.id) ?? []
311
+ if (outgoing.length === 1 && analysis.nodes.get(outgoing[0].to)?.do === 'tool') {
312
+ warn(`nodes.${node.id}`, 'model feeds a single tool node; an agent node usually covers that step better', 'model-then-tool')
313
+ }
314
+ }
315
+ }
316
+
317
+ if (nodes.length > 0 && nodes.length <= 2
318
+ && nodes.every(node => !['agent', 'gate', 'map', 'subagent'].includes(node.do))
319
+ && nodes.every(node => (analysis.outgoing.get(node.id) ?? []).length <= 1
320
+ && (analysis.incoming.get(node.id) ?? []).length <= 1
321
+ && analysis.reachableFromStart.has(node.id)
322
+ && analysis.canReachEnd.has(node.id))) {
323
+ warn('nodes', 'a one- or two-step linear graph; use ordinary DSH tools instead', 'tiny-graph')
324
+ }
325
+
326
+ // Longest chain in the SCC condensation, so a loop counts as one phase.
327
+ const relevant = new Set([...analysis.reachableFromStart].filter(id => analysis.canReachEnd.has(id)))
328
+ const components = analysis.sccs
329
+ const adjacency = components.map(() => new Set())
330
+ for (const [source, edges] of analysis.outgoing) {
331
+ if (!analysis.sccOf.has(source)) continue
332
+ const from = analysis.sccOf.get(source)
333
+ if (!components[from].some(id => relevant.has(id))) continue
334
+ for (const edge of edges) {
335
+ if (!analysis.sccOf.has(edge.to)) continue
336
+ const to = analysis.sccOf.get(edge.to)
337
+ if (from !== to) adjacency[from].add(to)
338
+ }
339
+ }
340
+ const lengths = new Map()
341
+ const longestFrom = index => {
342
+ if (lengths.has(index)) return lengths.get(index)
343
+ let best = 1
344
+ for (const next of adjacency[index]) best = Math.max(best, 1 + longestFrom(next))
345
+ lengths.set(index, best)
346
+ return best
347
+ }
348
+ let longest = { length: 0, index: -1 }
349
+ components.forEach((component, index) => {
350
+ if (!component.some(id => relevant.has(id))) return
351
+ const length = longestFrom(index)
352
+ if (length > longest.length) longest = { length, index }
353
+ })
354
+ if (longest.length > 8) {
355
+ warn(`nodes.${components[longest.index][0]}`, `linear chain of ${longest.length} phases; coarse-first graphs usually use 4-8 nodes`, 'long-chain')
356
+ }
357
+
358
+ return warnings
359
+ }
@@ -0,0 +1,274 @@
1
+ /**
2
+ * Deterministic GraphSpec -> LangGraph StateGraph compiler.
3
+ *
4
+ * The compiler validates the spec, turns every declared state field into an
5
+ * Annotation channel with its reducer, wraps each node executor so errors carry
6
+ * the IR node id, and then emits sequence, choice, static fan-out, or map edges.
7
+ * It calls no model and performs no I/O; the same spec always produces the same
8
+ * graph.
9
+ *
10
+ * A `map` is compiled into three nodes: a fanout dispatcher, the item body (the
11
+ * spec's node id), and a join. LangGraph `Send` runs the body once per item; the
12
+ * join runs once after every item and then follows the spec's out-edges, so a
13
+ * guard after a map sees the aggregated state, not one item's state.
14
+ */
15
+
16
+ import { END as SPEC_END, LIMITS, START as SPEC_START } from './constants.js'
17
+ import { evaluateGuard } from './guard.js'
18
+ import { createRunner } from './nodes.js'
19
+ import { assertSpec } from './schema.js'
20
+ import { isPlainObject, renderParts, resolveValue } from './template.js'
21
+
22
+ /** Clone a JSON default so each channel starts with its own array/object. */
23
+ function cloneJson(value) {
24
+ if (typeof structuredClone === 'function') return structuredClone(value)
25
+ return JSON.parse(JSON.stringify(value))
26
+ }
27
+
28
+ /** The reducer function for one state field. */
29
+ function reducerFor(definition) {
30
+ switch (definition.reducer ?? 'replace') {
31
+ case 'replace':
32
+ return (_current, next) => next
33
+ case 'append':
34
+ return (current, next) => {
35
+ const base = Array.isArray(current) ? current : []
36
+ if (Array.isArray(next)) return base.concat(next)
37
+ return next === undefined ? base : base.concat([next])
38
+ }
39
+ case 'add':
40
+ return (current, next) => (typeof current === 'number' ? current : 0) + (typeof next === 'number' ? next : 0)
41
+ case 'max':
42
+ return (current, next) => Math.max(
43
+ typeof current === 'number' ? current : Number.NEGATIVE_INFINITY,
44
+ typeof next === 'number' ? next : Number.NEGATIVE_INFINITY,
45
+ )
46
+ case 'min':
47
+ return (current, next) => Math.min(
48
+ typeof current === 'number' ? current : Number.POSITIVE_INFINITY,
49
+ typeof next === 'number' ? next : Number.POSITIVE_INFINITY,
50
+ )
51
+ case 'merge':
52
+ return (current, next) => ({
53
+ ...(isPlainObject(current) ? current : {}),
54
+ ...(isPlainObject(next) ? next : {}),
55
+ })
56
+ default:
57
+ throw new Error(`unsupported reducer "${definition.reducer}"`)
58
+ }
59
+ }
60
+
61
+ /** Build Annotation.Root channels from the spec's state. */
62
+ function annotationShape(spec, Annotation) {
63
+ const shape = {}
64
+ for (const [field, definition] of Object.entries(spec.state)) {
65
+ shape[field] = Annotation({
66
+ reducer: reducerFor(definition),
67
+ default: () => cloneJson(definition.default),
68
+ })
69
+ }
70
+ return shape
71
+ }
72
+
73
+ /**
74
+ * Attach the IR node id (and, for a map item, its index) to an error without
75
+ * swallowing LangGraph control flow. `is_bubble_up` marks interrupts and
76
+ * recursion errors, which must pass through unchanged for resume and for the
77
+ * run's recursion budget to work.
78
+ */
79
+ function annotateError(error, nodeId, itemIndex) {
80
+ if (error !== null && typeof error === 'object') {
81
+ if (error.is_bubble_up === true || error.nodeId !== undefined) return error
82
+ }
83
+ const message = error !== null && typeof error === 'object' && typeof error.message === 'string'
84
+ ? error.message
85
+ : String(error)
86
+ const wrapped = new Error(message)
87
+ if (error !== null && typeof error === 'object') {
88
+ if (typeof error.name === 'string') wrapped.name = error.name
89
+ if (typeof error.code === 'string') wrapped.code = error.code
90
+ wrapped.cause = error
91
+ }
92
+ wrapped.nodeId = nodeId
93
+ wrapped.node = nodeId
94
+ if (itemIndex !== undefined) wrapped.itemIndex = itemIndex
95
+ return wrapped
96
+ }
97
+
98
+ /** Wrap one function with error annotation. */
99
+ function wrapFunction(fn, nodeId, itemIndexOf) {
100
+ return async state => {
101
+ try {
102
+ return await fn(state)
103
+ } catch (error) {
104
+ throw annotateError(error, nodeId, itemIndexOf === undefined ? undefined : itemIndexOf(state))
105
+ }
106
+ }
107
+ }
108
+
109
+ /** Wrap one node executor with error annotation. */
110
+ function wrapNode(runner, node) {
111
+ return wrapFunction(state => runner.run(node, state), node.id)
112
+ }
113
+
114
+ /** A node id that does not collide with the spec's own ids. */
115
+ function uniqueNodeId(base, used) {
116
+ if (!used.has(base)) return base
117
+ let index = 2
118
+ while (used.has(`${base}_${index}`)) index += 1
119
+ return `${base}_${index}`
120
+ }
121
+
122
+ /** Resolve one item's body inputs at dispatch time. */
123
+ function mapPayload(body, state) {
124
+ if (body.do === 'tool') return { args: resolveValue(body.args, state) }
125
+ return { prompt: renderParts(body.prompt, state) }
126
+ }
127
+
128
+ /** Plan the hidden nodes for one map. */
129
+ function mapPlanOf(spec, node, used) {
130
+ const fanoutId = uniqueNodeId(`${node.id}__fanout`, used)
131
+ used.add(fanoutId)
132
+ const hasOut = spec.edges.some(edge => edge.from === node.id)
133
+ let joinId
134
+ if (hasOut) {
135
+ joinId = uniqueNodeId(`${node.id}__join`, used)
136
+ used.add(joinId)
137
+ }
138
+ return {
139
+ node,
140
+ fanoutId,
141
+ joinId,
142
+ itemType: spec.state[node.over]?.type === 'number[]' ? 'number' : 'string',
143
+ }
144
+ }
145
+
146
+ /** Add the fanout, item body, and join for one map. */
147
+ function addMapNodes(graph, plan, runner, Send) {
148
+ if (typeof Send !== 'function') throw new Error('map nodes need LangGraph Send, which this runtime did not provide')
149
+ const { node, fanoutId, joinId, itemType } = plan
150
+ const maxItems = node.maxItems ?? LIMITS.defaultMapItems
151
+
152
+ graph.addNode(fanoutId, wrapFunction(async state => {
153
+ const over = state[node.over]
154
+ if (!Array.isArray(over)) {
155
+ throw new Error(`map "${node.id}" needs "${node.over}" to be an array`)
156
+ }
157
+ if (over.length > maxItems) {
158
+ throw new Error(`map "${node.id}" has ${over.length} items; maxItems is ${maxItems}`)
159
+ }
160
+ const itemOk = itemType === 'number'
161
+ ? value => typeof value === 'number' && Number.isFinite(value)
162
+ : value => typeof value === 'string'
163
+ if (!over.every(itemOk)) {
164
+ throw new Error(`map "${node.id}" needs every "${node.over}" item to be a ${itemType}`)
165
+ }
166
+ return {}
167
+ }, node.id))
168
+
169
+ // The body receives a small Send payload, not the whole parent state, so a
170
+ // large fan-out does not copy the state once per item.
171
+ graph.addNode(node.id, wrapFunction(
172
+ state => runner.runMapBody(node.body, state, node.id),
173
+ node.id,
174
+ state => state?.__mapIndex,
175
+ ))
176
+
177
+ if (joinId !== undefined) graph.addNode(joinId, async () => ({}))
178
+
179
+ graph.addConditionalEdges(fanoutId, state => {
180
+ const over = state[node.over]
181
+ const items = Array.isArray(over) ? over : []
182
+ if (items.length === 0) {
183
+ // A sentinel item lets the join run and the graph continue with the
184
+ // aggregate defaults instead of silently ending at an empty fan-out.
185
+ return [new Send(node.id, { __mapEmpty: true })]
186
+ }
187
+ return items.map((item, index) => {
188
+ const synthetic = { ...state, item, index }
189
+ return new Send(node.id, {
190
+ ...mapPayload(node.body, synthetic),
191
+ __mapItem: item,
192
+ __mapIndex: index,
193
+ })
194
+ })
195
+ })
196
+
197
+ // Every item schedules the same join; LangGraph runs it once with the
198
+ // aggregated state, and only then evaluates the spec's out-edges.
199
+ if (joinId !== undefined) graph.addEdge(node.id, joinId)
200
+ }
201
+
202
+ /** Emit the spec's edges, one source at a time. */
203
+ function connectEdges(graph, spec, langGraphStart, langGraphEnd, plans) {
204
+ const bySource = new Map()
205
+ for (const edge of spec.edges) {
206
+ if (!bySource.has(edge.from)) bySource.set(edge.from, [])
207
+ bySource.get(edge.from).push(edge)
208
+ }
209
+ const sourceOf = id => plans.get(id)?.joinId ?? id
210
+ const targetOf = id => id === SPEC_END
211
+ ? langGraphEnd
212
+ : plans.get(id)?.fanoutId ?? id
213
+
214
+ for (const edge of bySource.get(SPEC_START) ?? []) {
215
+ graph.addEdge(langGraphStart, targetOf(edge.to))
216
+ }
217
+ for (const node of spec.nodes) {
218
+ const edges = bySource.get(node.id) ?? []
219
+ if (edges.length === 0) continue
220
+ const source = sourceOf(node.id)
221
+ if (source === node.id && plans.has(node.id)) continue
222
+ if (edges.some(edge => edge.when !== undefined)) {
223
+ // Choice: guards are evaluated in the spec's edge order; the first match
224
+ // wins. A spec with no match is a graph bug and fails the run.
225
+ graph.addConditionalEdges(source, state => {
226
+ for (const edge of edges) {
227
+ if (edge.when === undefined) continue
228
+ if (evaluateGuard(edge.when, state)) return targetOf(edge.to)
229
+ }
230
+ throw new Error(`no outgoing edge matched at node "${node.id}"`)
231
+ })
232
+ } else {
233
+ // Sequence (one edge) or static fan-out (two or more): every successor
234
+ // runs in the same superstep, and LangGraph joins them at a shared target.
235
+ for (const edge of edges) graph.addEdge(source, targetOf(edge.to))
236
+ }
237
+ }
238
+ }
239
+
240
+ /**
241
+ * Compile one spec into an uncompiled StateGraph. The caller compiles it with
242
+ * the run's checkpointer and store, exactly like a registered graph module.
243
+ * @param {object} api - the LangGraph API plus `helpers` and `interrupt`.
244
+ * @param {object} spec - the GraphSpec.
245
+ * @param {{ tools?: string[] | Set<string> }} [options] - visible tool names to check.
246
+ * @returns {object} a StateGraph.
247
+ */
248
+ export function buildSpecGraph(api, spec, options = {}) {
249
+ if (api?.helpers === undefined) throw new Error('buildSpecGraph needs api.helpers')
250
+ assertSpec(spec, options)
251
+ const { StateGraph, Annotation, START, END, Send } = api
252
+ const State = Annotation.Root(annotationShape(spec, Annotation))
253
+ const graph = new StateGraph(State)
254
+ const runner = createRunner({ helpers: api.helpers, interrupt: api.interrupt })
255
+ const plans = new Map()
256
+ // Hidden fanout/join ids must not collide with a node id or a state channel:
257
+ // LangGraph refuses a node name that is also a state attribute.
258
+ const usedIds = new Set([
259
+ SPEC_START,
260
+ SPEC_END,
261
+ ...Object.keys(spec.state),
262
+ ...spec.nodes.map(node => node.id),
263
+ ])
264
+ for (const node of spec.nodes) {
265
+ if (node.do === 'map') plans.set(node.id, mapPlanOf(spec, node, usedIds))
266
+ }
267
+ for (const node of spec.nodes) {
268
+ const plan = plans.get(node.id)
269
+ if (plan !== undefined) addMapNodes(graph, plan, runner, Send)
270
+ else graph.addNode(node.id, wrapNode(runner, node))
271
+ }
272
+ connectEdges(graph, spec, START, END, plans)
273
+ return graph
274
+ }