@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.
Files changed (44) hide show
  1. package/README.md +172 -51
  2. package/bench/README.md +54 -0
  3. package/bench/demo-video.mjs +208 -0
  4. package/bench/results-harness.json +125 -0
  5. package/bench/run.mjs +139 -0
  6. package/compose/analysis.js +359 -0
  7. package/compose/build.js +274 -0
  8. package/compose/constants.js +83 -0
  9. package/compose/guard.js +72 -0
  10. package/compose/nodes.js +214 -0
  11. package/compose/resolve.js +97 -0
  12. package/compose/schema.js +975 -0
  13. package/compose/specs.js +218 -0
  14. package/compose/template.js +260 -0
  15. package/compose/tool.js +713 -0
  16. package/docs/BENCHMARK.md +116 -0
  17. package/docs/COMPOSE.md +376 -0
  18. package/docs/CONTEXT.md +34 -18
  19. package/docs/DETAIL.md +48 -1
  20. package/docs/ECOSYSTEM.md +30 -5
  21. package/gallery/README.md +69 -0
  22. package/gallery/assets/gallery.png +0 -0
  23. package/gallery/assets/session.png +0 -0
  24. package/gallery/index.html +516 -0
  25. package/gallery/specs/approval-plan.lg.json +51 -0
  26. package/gallery/specs/data-extract.lg.json +75 -0
  27. package/gallery/specs/incident-triage.lg.json +64 -0
  28. package/gallery/specs/pr-review.lg.json +49 -0
  29. package/gallery/specs/repo-scan.lg.json +54 -0
  30. package/gallery/specs/research-brief.lg.json +94 -0
  31. package/index.d.ts +136 -0
  32. package/index.js +423 -46
  33. package/media/dsh-langgraph-demo.webm +0 -0
  34. package/media/raw/page@0d0adc4d6eb7b946d722093988db7e67.webm +0 -0
  35. package/media/raw/page@0fceaacbda6d8f2da8485736c565ed87.webm +0 -0
  36. package/media/raw/page@49c6bb9135c0c35ed8cf9054a8e05711.webm +0 -0
  37. package/media/raw/page@86f5e37e1c1218697f8724a6bafda8d2.webm +0 -0
  38. package/media/raw/page@9b5b70b442c0ace7d4b135fc80edba73.webm +0 -0
  39. package/media/raw/page@beb9164240f13ad017c3fa7e8f20a772.webm +0 -0
  40. package/media/raw/page@db4ee1834adcc9e8d5b4708eabe4eb5c.webm +0 -0
  41. package/media/raw/page@e9c63a0029d3181e41506fc4bf8da05a.webm +0 -0
  42. package/media/raw/page@eaf729b06925fe86e9e9e4bf48e2cdcc.webm +0 -0
  43. package/media/raw/page@f0d6fd1a2534e69bc2f228b30ae19a9c.webm +0 -0
  44. package/package.json +7 -3
@@ -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
+ }
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Constants shared by the GraphSpec IR compiler.
3
+ *
4
+ * The IR is deliberately small and closed: a model can learn it from one
5
+ * `langgraph_compose({ action: 'describe' })` reply, and the compiler translates
6
+ * it without a model, randomness, or I/O.
7
+ */
8
+
9
+ /** IR version this compiler reads. */
10
+ export const IR_VERSION = 1
11
+
12
+ /** Pseudo-node that starts a graph. */
13
+ export const START = 'START'
14
+
15
+ /** Pseudo-node that ends a graph. */
16
+ export const END = 'END'
17
+
18
+ /** Node kinds this compiler version can build. */
19
+ export const NODE_KINDS = Object.freeze(['tool', 'model', 'agent', 'gate', 'map', 'set', 'subagent'])
20
+
21
+ /** Node kinds allowed inside a `map` body. A gate and a nested map are not. */
22
+ export const MAP_BODY_KINDS = Object.freeze(['tool', 'model', 'agent', 'subagent'])
23
+
24
+ /** State field types. There is no `any`: every value has a declared shape. */
25
+ export const STATE_TYPES = Object.freeze(['string', 'number', 'boolean', 'json', 'string[]', 'number[]'])
26
+
27
+ /** Reducers a state field may use. `replace` is the default. */
28
+ export const REDUCERS = Object.freeze(['replace', 'append', 'add', 'max', 'min', 'merge'])
29
+
30
+ /** Result transforms a node applies before writing a state field. */
31
+ export const TRANSFORMS = Object.freeze(['text', 'lines', 'json', 'bool', 'number', 'first', 'count'])
32
+
33
+ /** Guard operators. There is no expression string and no `eval`. */
34
+ export const GUARD_OPS = Object.freeze(['eq', 'ne', 'in', 'gt', 'gte', 'lt', 'lte', 'exists', 'and', 'or', 'not'])
35
+
36
+ /** Hard budgets. A spec past these is rejected, never truncated. */
37
+ export const LIMITS = Object.freeze({
38
+ nodes: 64,
39
+ edges: 128,
40
+ stateFields: 64,
41
+ specBytes: 256 * 1024,
42
+ defaultMaxSteps: 25,
43
+ maxSteps: 200,
44
+ defaultMapItems: 50,
45
+ maxMapItems: 100,
46
+ defaultMaxConcurrency: 8,
47
+ maxMapConcurrency: 16,
48
+ })
49
+
50
+ /** The fields each node kind may carry; anything else is a typo and rejected. */
51
+ export const NODE_FIELDS = Object.freeze({
52
+ tool: Object.freeze(['id', 'do', 'tool', 'args', 'out']),
53
+ model: Object.freeze(['id', 'do', 'prompt', 'system', 'schema', 'out']),
54
+ agent: Object.freeze(['id', 'do', 'prompt', 'tools', 'out']),
55
+ gate: Object.freeze(['id', 'do', 'question', 'options', 'out']),
56
+ map: Object.freeze(['id', 'do', 'over', 'body', 'maxItems', 'maxConcurrency']),
57
+ set: Object.freeze(['id', 'do', 'values']),
58
+ subagent: Object.freeze(['id', 'do', 'prompt', 'schema', 'out']),
59
+ })
60
+
61
+ /** Fields a map body may carry; its `id` is optional and ignored. */
62
+ export const MAP_BODY_FIELDS = Object.freeze({
63
+ tool: Object.freeze(['id', 'do', 'tool', 'args', 'out']),
64
+ model: Object.freeze(['id', 'do', 'prompt', 'system', 'schema', 'out']),
65
+ agent: Object.freeze(['id', 'do', 'prompt', 'tools', 'out']),
66
+ subagent: Object.freeze(['id', 'do', 'prompt', 'schema', 'out']),
67
+ })
68
+
69
+ /** The JSON type a transform produces. */
70
+ export const TRANSFORM_TYPES = Object.freeze({
71
+ text: 'string',
72
+ lines: 'string[]',
73
+ json: 'json',
74
+ bool: 'boolean',
75
+ number: 'number',
76
+ first: 'string',
77
+ count: 'number',
78
+ })
79
+
80
+ /** Whether a reducer can combine concurrent writes. */
81
+ export function isMergeableReducer(reducer) {
82
+ return reducer !== undefined && reducer !== 'replace'
83
+ }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Structured guard evaluation for graph edges.
3
+ *
4
+ * A guard is `true`, `false`, or `{ op, args }`; there is no expression string
5
+ * and no `eval`. Missing state, a type mismatch, or a non-finite number makes a
6
+ * comparison false instead of throwing, so an edge can never crash the run.
7
+ */
8
+
9
+ import { deepEqual, isPlainObject, isStateRef, readState } from './template.js'
10
+
11
+ /** Resolve one guard operand: a state reference or a literal. */
12
+ export function evaluateOperand(value, state) {
13
+ if (isStateRef(value)) return readState(state, value.$state)
14
+ return value
15
+ }
16
+
17
+ /** Two operands, when both are finite numbers; otherwise undefined. */
18
+ function numbers(left, right) {
19
+ if (typeof left !== 'number' || !Number.isFinite(left)) return undefined
20
+ if (typeof right !== 'number' || !Number.isFinite(right)) return undefined
21
+ return [left, right]
22
+ }
23
+
24
+ /**
25
+ * Evaluate one guard against the current state.
26
+ * @param {true | false | { op: string, args: unknown[] }} guard - the guard.
27
+ * @param {object} state - the current graph state.
28
+ * @returns {boolean} whether the edge is taken.
29
+ */
30
+ export function evaluateGuard(guard, state) {
31
+ if (guard === true) return true
32
+ if (guard === false || guard === undefined || guard === null) return false
33
+ if (!isPlainObject(guard)) return false
34
+ const args = Array.isArray(guard.args) ? guard.args : []
35
+ switch (guard.op) {
36
+ case 'and':
37
+ return args.every(item => evaluateGuard(item, state))
38
+ case 'or':
39
+ return args.some(item => evaluateGuard(item, state))
40
+ case 'not':
41
+ return !evaluateGuard(args[0], state)
42
+ case 'exists':
43
+ return evaluateOperand(args[0], state) !== undefined
44
+ case 'eq':
45
+ return deepEqual(evaluateOperand(args[0], state), evaluateOperand(args[1], state))
46
+ case 'ne':
47
+ return !deepEqual(evaluateOperand(args[0], state), evaluateOperand(args[1], state))
48
+ case 'in': {
49
+ const needle = evaluateOperand(args[0], state)
50
+ const haystack = evaluateOperand(args[1], state)
51
+ return Array.isArray(haystack) && haystack.some(item => deepEqual(item, needle))
52
+ }
53
+ case 'gt': {
54
+ const pair = numbers(evaluateOperand(args[0], state), evaluateOperand(args[1], state))
55
+ return pair !== undefined && pair[0] > pair[1]
56
+ }
57
+ case 'gte': {
58
+ const pair = numbers(evaluateOperand(args[0], state), evaluateOperand(args[1], state))
59
+ return pair !== undefined && pair[0] >= pair[1]
60
+ }
61
+ case 'lt': {
62
+ const pair = numbers(evaluateOperand(args[0], state), evaluateOperand(args[1], state))
63
+ return pair !== undefined && pair[0] < pair[1]
64
+ }
65
+ case 'lte': {
66
+ const pair = numbers(evaluateOperand(args[0], state), evaluateOperand(args[1], state))
67
+ return pair !== undefined && pair[0] <= pair[1]
68
+ }
69
+ default:
70
+ return false
71
+ }
72
+ }
@@ -0,0 +1,214 @@
1
+ /**
2
+ * Node executors for the GraphSpec IR.
3
+ *
4
+ * Each executor receives the IR node and the current graph state and returns a
5
+ * partial state update. The compiler wraps them with error annotation; this
6
+ * module only runs the action and converts its result through the node's `out`
7
+ * transforms.
8
+ *
9
+ * `agent` nodes use LangGraph's prebuilt ReAct agent over the calling session's
10
+ * own tools, which is the IR's "open work" unit: the brief is prose, and the
11
+ * compiler never inspects it.
12
+ */
13
+
14
+ import { validateSchemaValue } from './schema.js'
15
+ import { messageText, parseJsonText, renderParts, resolveValue, transform } from './template.js'
16
+
17
+ /**
18
+ * Build the executor for one spec. Agent nodes are compiled lazily on their
19
+ * first run, so building a topology does not need the model service.
20
+ * @param {object} api - `{ helpers, interrupt }` bound to one run.
21
+ * @returns {{ run: (node: object, state: object) => Promise<object> | object }} the runner.
22
+ */
23
+ export function createRunner(api) {
24
+ const helpers = api.helpers
25
+ const interrupt = api.interrupt
26
+ const agents = new Map()
27
+
28
+ function getAgent(node, key = node.id) {
29
+ const cached = agents.get(key)
30
+ if (cached !== undefined) return cached
31
+ const promise = (async () => {
32
+ const tools = node.tools.length === 0 ? [] : helpers.tools(node.tools)
33
+ return await helpers.createReactAgent({ llm: helpers.chatModel(), tools })
34
+ })()
35
+ agents.set(key, promise)
36
+ // A failed build (for example a model route that is not ready yet) should
37
+ // not poison every later retry on the same thread.
38
+ promise.catch(() => {
39
+ if (agents.get(key) === promise) agents.delete(key)
40
+ })
41
+ return promise
42
+ }
43
+
44
+ function applyOut(node, base, parsed) {
45
+ const patch = {}
46
+ for (const [field, kind] of Object.entries(node.out ?? {})) {
47
+ if (kind === 'json' && parsed !== undefined) patch[field] = parsed
48
+ else if (kind === 'text' && parsed !== undefined && typeof parsed === 'string') patch[field] = parsed
49
+ else patch[field] = transform(base, kind)
50
+ }
51
+ return patch
52
+ }
53
+
54
+ function runSet(node, state) {
55
+ const patch = {}
56
+ for (const [field, value] of Object.entries(node.values)) {
57
+ patch[field] = resolveValue(value, state)
58
+ }
59
+ return patch
60
+ }
61
+
62
+ async function runTool(node, state) {
63
+ const args = resolveValue(node.args, state)
64
+ const text = await helpers.callTool(node.tool, args)
65
+ return applyOut(node, text)
66
+ }
67
+
68
+ async function callModelWithSchema(node, prompt) {
69
+ if (typeof helpers.callModel !== 'function') {
70
+ throw new Error('model nodes need helpers.callModel, which this runtime did not provide')
71
+ }
72
+ const request = node.schema === undefined
73
+ ? prompt
74
+ : `${prompt}\n\nReply with a single JSON value only, matching this JSON Schema:\n${JSON.stringify(node.schema)}`
75
+ const result = await helpers.callModel(request, node.system === undefined ? {} : { system: node.system })
76
+ const text = typeof result === 'string' ? result : String(result?.text ?? '')
77
+ let parsed
78
+ if (node.schema !== undefined) {
79
+ parsed = parseJsonText(text)
80
+ const problems = validateSchemaValue(parsed, node.schema)
81
+ if (problems.length > 0) {
82
+ throw new Error(`model output does not match its schema: ${problems.join('; ')}`)
83
+ }
84
+ }
85
+ return { text, parsed }
86
+ }
87
+
88
+ async function runModel(node, state) {
89
+ const prompt = renderParts(node.prompt, state)
90
+ if (prompt.trim() === '') throw new Error('the model prompt rendered empty')
91
+ const { text, parsed } = await callModelWithSchema(node, prompt)
92
+ return applyOut(node, text, parsed)
93
+ }
94
+
95
+ async function callSubagent(node, prompt) {
96
+ if (typeof helpers.subagent !== 'function') {
97
+ throw new Error('subagent nodes need helpers.subagent, which this runtime did not provide')
98
+ }
99
+ const result = await helpers.subagent(prompt, node.schema === undefined ? {} : { schema: node.schema })
100
+ if (result.stopReason !== 'completed') {
101
+ throw new Error(`subagent stopped: ${result.stopReason}`)
102
+ }
103
+ let parsed = result.structured
104
+ if (node.schema !== undefined) {
105
+ if (parsed === undefined) parsed = parseJsonText(result.text)
106
+ const problems = validateSchemaValue(parsed, node.schema)
107
+ if (problems.length > 0) {
108
+ throw new Error(`subagent output does not match its schema: ${problems.join('; ')}`)
109
+ }
110
+ }
111
+ return { text: String(result.text ?? ''), parsed }
112
+ }
113
+
114
+ async function runSubagent(node, state) {
115
+ const prompt = renderParts(node.prompt, state)
116
+ if (prompt.trim() === '') throw new Error('the subagent brief rendered empty')
117
+ const { text, parsed } = await callSubagent(node, prompt)
118
+ return applyOut(node, text, parsed)
119
+ }
120
+
121
+ async function runAgent(node, state) {
122
+ if (typeof helpers.createReactAgent !== 'function') {
123
+ throw new Error('agent nodes need helpers.createReactAgent, which this runtime did not provide')
124
+ }
125
+ const brief = renderParts(node.prompt, state)
126
+ if (brief.trim() === '') throw new Error('the agent brief rendered empty')
127
+ const agent = await getAgent(node)
128
+ const result = await agent.invoke({ messages: [['human', brief]] })
129
+ const messages = result?.messages
130
+ const text = Array.isArray(messages) && messages.length > 0
131
+ ? messageText(messages[messages.length - 1])
132
+ : ''
133
+ if (text.trim() === '') throw new Error('the agent returned an empty answer')
134
+ return applyOut(node, text)
135
+ }
136
+
137
+ async function runGate(node, state) {
138
+ if (typeof interrupt !== 'function') {
139
+ throw new Error('gate nodes need LangGraph interrupt, which this runtime did not provide')
140
+ }
141
+ const answer = interrupt({
142
+ node: node.id,
143
+ question: node.question,
144
+ ...(node.options === undefined ? {} : { options: node.options }),
145
+ })
146
+ return applyOut(node, answer)
147
+ }
148
+
149
+ /**
150
+ * Run one `map` item. The dispatcher has already resolved the body's args or
151
+ * prompt, so this only calls the helper and applies `out`.
152
+ * @param {object} body - a validated map body node.
153
+ * @param {object} state - the Send payload (`args`/`prompt`, item index).
154
+ * @param {string} mapId - the map node id, used to cache an agent body.
155
+ */
156
+ async function runMapBody(body, state, mapId) {
157
+ if (state?.__mapEmpty === true) return {}
158
+ switch (body.do) {
159
+ case 'tool':
160
+ return applyOut(body, await helpers.callTool(body.tool, state.args ?? {}))
161
+ case 'model': {
162
+ const prompt = typeof state.prompt === 'string' ? state.prompt : ''
163
+ if (prompt.trim() === '') throw new Error('the model prompt rendered empty')
164
+ const { text, parsed } = await callModelWithSchema(body, prompt)
165
+ return applyOut(body, text, parsed)
166
+ }
167
+ case 'agent': {
168
+ if (typeof helpers.createReactAgent !== 'function') {
169
+ throw new Error('agent nodes need helpers.createReactAgent, which this runtime did not provide')
170
+ }
171
+ const brief = typeof state.prompt === 'string' ? state.prompt : ''
172
+ if (brief.trim() === '') throw new Error('the agent brief rendered empty')
173
+ const agent = await getAgent(body, mapId)
174
+ const result = await agent.invoke({ messages: [['human', brief]] })
175
+ const messages = result?.messages
176
+ const text = Array.isArray(messages) && messages.length > 0
177
+ ? messageText(messages[messages.length - 1])
178
+ : ''
179
+ if (text.trim() === '') throw new Error('the agent returned an empty answer')
180
+ return applyOut(body, text)
181
+ }
182
+ case 'subagent': {
183
+ const prompt = typeof state.prompt === 'string' ? state.prompt : ''
184
+ if (prompt.trim() === '') throw new Error('the subagent brief rendered empty')
185
+ const { text, parsed } = await callSubagent(body, prompt)
186
+ return applyOut(body, text, parsed)
187
+ }
188
+ default:
189
+ throw new Error(`unsupported map body kind "${body.do}"`)
190
+ }
191
+ }
192
+
193
+ return {
194
+ async run(node, state) {
195
+ switch (node.do) {
196
+ case 'set':
197
+ return runSet(node, state)
198
+ case 'tool':
199
+ return await runTool(node, state)
200
+ case 'model':
201
+ return await runModel(node, state)
202
+ case 'agent':
203
+ return await runAgent(node, state)
204
+ case 'gate':
205
+ return await runGate(node, state)
206
+ case 'subagent':
207
+ return await runSubagent(node, state)
208
+ default:
209
+ throw new Error(`unsupported node kind "${node.do}"`)
210
+ }
211
+ },
212
+ runMapBody,
213
+ }
214
+ }