@lzn1998/dsh-langgraph 1.0.1 → 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.
@@ -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
+ }
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Resolve a graph id to a registry entry or a stored composed spec.
3
+ *
4
+ * Registered graphs win, so a profile graph can never be shadowed by a spec.
5
+ * Composed specs carry the same `{ id, description, input, build }` shape the
6
+ * runtime already compiles and runs; the only extra job is an owner check and a
7
+ * per-owner entry cache (specs are immutable).
8
+ */
9
+
10
+ import { LIMITS } from './constants.js'
11
+ import { analyze } from './analysis.js'
12
+ import { buildSpecGraph } from './build.js'
13
+ import { isSpecId } from './specs.js'
14
+
15
+ /** JSON Schema of one state field, for the model-facing input hint. */
16
+ function fieldSchema(definition) {
17
+ switch (definition.type) {
18
+ case 'string':
19
+ return { type: 'string' }
20
+ case 'number':
21
+ return { type: 'number' }
22
+ case 'boolean':
23
+ return { type: 'boolean' }
24
+ case 'json':
25
+ return {}
26
+ case 'string[]':
27
+ return { type: 'array', items: { type: 'string' } }
28
+ case 'number[]':
29
+ return { type: 'array', items: { type: 'number' } }
30
+ default:
31
+ return {}
32
+ }
33
+ }
34
+
35
+ /**
36
+ * Graph input schema: every state field is optional because its default fills
37
+ * it; the defaults are shown as JSON Schema `default` annotations.
38
+ * @param {object} spec - a GraphSpec.
39
+ * @returns {object} a JSON Schema object.
40
+ */
41
+ export function inputSchemaOf(spec) {
42
+ const properties = {}
43
+ for (const [field, definition] of Object.entries(spec.state)) {
44
+ properties[field] = {
45
+ ...fieldSchema(definition),
46
+ ...(definition.default === undefined ? {} : { default: definition.default }),
47
+ }
48
+ }
49
+ return { type: 'object', properties, additionalProperties: false }
50
+ }
51
+
52
+ /**
53
+ * Create the resolver used by `langgraph_run`, `langgraph_threads`, and the
54
+ * topology route.
55
+ * @param {object} options - resolver dependencies.
56
+ * @param {Map<string, object>} options.registry - registered graph entries.
57
+ * @param {() => Promise<object | undefined> | object | undefined} options.getStore - the spec store.
58
+ * @param {Map<string, object>} [options.cache] - owner-qualified entry cache.
59
+ * @returns {(id: string, sessionId: string | undefined, options?: { allSessions?: boolean }) => Promise<object | undefined>} the resolver.
60
+ */
61
+ export function createResolver({ registry, getStore, cache = new Map() }) {
62
+ return async function resolveEntry(id, sessionId, options = {}) {
63
+ const registered = registry.get(id)
64
+ if (registered !== undefined) return registered
65
+ if (!isSpecId(id)) return undefined
66
+
67
+ const cacheKey = `${options.allSessions === true ? '*' : sessionId ?? ''}\u0000${id}`
68
+ const cached = cache.get(cacheKey)
69
+ if (cached !== undefined) return cached
70
+
71
+ const store = await getStore()
72
+ if (store === undefined) return undefined
73
+ const record = store.getRecord(id, sessionId, { allSessions: options.allSessions === true })
74
+ if (record === undefined) return undefined
75
+
76
+ const spec = record.spec
77
+ const mapLimits = spec.nodes
78
+ .filter(node => node.do === 'map')
79
+ .map(node => node.maxConcurrency ?? LIMITS.defaultMaxConcurrency)
80
+ const entry = {
81
+ id,
82
+ composed: true,
83
+ spec,
84
+ analysis: analyze(spec),
85
+ ...(typeof spec.name === 'string' ? { name: spec.name } : {}),
86
+ ...(typeof spec.description === 'string' ? { description: spec.description } : {}),
87
+ input: inputSchemaOf(spec),
88
+ build: api => buildSpecGraph(api, spec),
89
+ maxSteps: Number.isInteger(spec.maxSteps) ? spec.maxSteps : LIMITS.defaultMaxSteps,
90
+ // v1 applies the strictest map cap as the run's global LangGraph cap.
91
+ ...(mapLimits.length === 0 ? {} : { maxConcurrency: Math.min(...mapLimits) }),
92
+ ...(Array.isArray(spec.output) ? { output: spec.output } : {}),
93
+ }
94
+ cache.set(cacheKey, entry)
95
+ return entry
96
+ }
97
+ }