@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 +17 -6
- 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/COMPOSE.md +376 -0
- package/docs/CONTEXT.md +44 -13
- package/docs/DETAIL.md +53 -1
- package/docs/ECOSYSTEM.md +30 -5
- package/index.d.ts +136 -0
- package/index.js +423 -42
- package/package.json +3 -2
|
@@ -0,0 +1,975 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Strict validation for the GraphSpec IR.
|
|
3
|
+
*
|
|
4
|
+
* The validator is deliberately hand-written instead of a permissive schema
|
|
5
|
+
* library: every error carries the exact IR path (`nodes[2].do`, `edges[3].to`)
|
|
6
|
+
* and the expected shape, so a model can repair a spec from the reply alone.
|
|
7
|
+
*
|
|
8
|
+
* `validateSpec` checks structure, references, types, budgets, edge rules, the
|
|
9
|
+
* static fan-out writer/reducer contract, and returns advisory lint warnings.
|
|
10
|
+
* It never throws and never mutates the input.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import {
|
|
14
|
+
END,
|
|
15
|
+
GUARD_OPS,
|
|
16
|
+
IR_VERSION,
|
|
17
|
+
LIMITS,
|
|
18
|
+
MAP_BODY_FIELDS,
|
|
19
|
+
MAP_BODY_KINDS,
|
|
20
|
+
NODE_FIELDS,
|
|
21
|
+
NODE_KINDS,
|
|
22
|
+
REDUCERS,
|
|
23
|
+
START,
|
|
24
|
+
STATE_TYPES,
|
|
25
|
+
TRANSFORMS,
|
|
26
|
+
TRANSFORM_TYPES,
|
|
27
|
+
} from './constants.js'
|
|
28
|
+
import { analyze, fanOutProblems, lintWarnings } from './analysis.js'
|
|
29
|
+
import {
|
|
30
|
+
deepEqual,
|
|
31
|
+
hasStateKey,
|
|
32
|
+
isJsonValue,
|
|
33
|
+
isPlainObject,
|
|
34
|
+
isStateRef,
|
|
35
|
+
jsonKind,
|
|
36
|
+
matchesStateType,
|
|
37
|
+
stableStringify,
|
|
38
|
+
} from './template.js'
|
|
39
|
+
|
|
40
|
+
/** Thrown by `assertSpec` and by `buildSpecGraph` when a spec is invalid. */
|
|
41
|
+
export class SpecError extends Error {
|
|
42
|
+
/**
|
|
43
|
+
* @param {Array<{ path: string, message: string, expected?: string }>} errors - validation errors.
|
|
44
|
+
*/
|
|
45
|
+
constructor(errors) {
|
|
46
|
+
const detail = errors
|
|
47
|
+
.slice(0, 3)
|
|
48
|
+
.map(error => `${error.path === '' ? '(root)' : error.path}: ${error.message}`)
|
|
49
|
+
.join('; ')
|
|
50
|
+
super(`invalid graph spec: ${detail}${errors.length > 3 ? ` (+${errors.length - 3} more)` : ''}`)
|
|
51
|
+
this.name = 'SpecError'
|
|
52
|
+
this.errors = errors
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Whether a reducer can be used with a state type and default value. */
|
|
57
|
+
function reducerFits(reducer, type, defaultValue) {
|
|
58
|
+
switch (reducer) {
|
|
59
|
+
case 'replace':
|
|
60
|
+
return true
|
|
61
|
+
case 'append':
|
|
62
|
+
return type === 'string[]' || type === 'number[]' || (type === 'json' && Array.isArray(defaultValue))
|
|
63
|
+
case 'add':
|
|
64
|
+
case 'max':
|
|
65
|
+
case 'min':
|
|
66
|
+
return type === 'number'
|
|
67
|
+
case 'merge':
|
|
68
|
+
return type === 'json' && isPlainObject(defaultValue)
|
|
69
|
+
default:
|
|
70
|
+
return false
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Normalize the tools option into visible names and, when the caller passed
|
|
76
|
+
* full DSH definitions, their JSON schemas for argument checking.
|
|
77
|
+
*/
|
|
78
|
+
function normalizeTools(tools) {
|
|
79
|
+
if (tools instanceof Set) return { names: tools, schemas: new Map() }
|
|
80
|
+
if (Array.isArray(tools)) {
|
|
81
|
+
const names = new Set()
|
|
82
|
+
const schemas = new Map()
|
|
83
|
+
for (const item of tools) {
|
|
84
|
+
if (typeof item === 'string') {
|
|
85
|
+
names.add(item)
|
|
86
|
+
continue
|
|
87
|
+
}
|
|
88
|
+
if (item === null || typeof item !== 'object' || typeof item.name !== 'string') continue
|
|
89
|
+
names.add(item.name)
|
|
90
|
+
const schema = item.parameters ?? item.inputSchema ?? item.schema
|
|
91
|
+
if (schema !== undefined && schema !== null) schemas.set(item.name, schema)
|
|
92
|
+
}
|
|
93
|
+
return { names, schemas }
|
|
94
|
+
}
|
|
95
|
+
return undefined
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Short single-line preview of a value for an error message. */
|
|
99
|
+
function preview(value) {
|
|
100
|
+
let text
|
|
101
|
+
try {
|
|
102
|
+
text = JSON.stringify(value)
|
|
103
|
+
} catch {
|
|
104
|
+
text = String(value)
|
|
105
|
+
}
|
|
106
|
+
if (text === undefined) text = String(value)
|
|
107
|
+
return text.length > 80 ? `${text.slice(0, 77)}...` : text
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Reject fields the IR does not define, so a typo is visible. */
|
|
111
|
+
function checkKeys(object, allowed, path, fail) {
|
|
112
|
+
for (const key of Object.keys(object)) {
|
|
113
|
+
if (allowed.includes(key)) continue
|
|
114
|
+
fail(path === '' ? key : `${path}.${key}`, `unknown field "${key}"`, allowed.join(' | '))
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Find a `$state` key nested below a literal value, for a clearer error. */
|
|
119
|
+
function findStateKey(value, path = '') {
|
|
120
|
+
if (hasStateKey(value)) return path
|
|
121
|
+
if (Array.isArray(value)) {
|
|
122
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
123
|
+
const found = findStateKey(value[index], `${path}[${index}]`)
|
|
124
|
+
if (found !== undefined) return found
|
|
125
|
+
}
|
|
126
|
+
return undefined
|
|
127
|
+
}
|
|
128
|
+
if (isPlainObject(value)) {
|
|
129
|
+
for (const [key, item] of Object.entries(value)) {
|
|
130
|
+
const found = findStateKey(item, path === '' ? key : `${path}.${key}`)
|
|
131
|
+
if (found !== undefined) return found
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
return undefined
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** JSON Schema `type` check used for model output. */
|
|
138
|
+
function matchesSchemaType(value, type) {
|
|
139
|
+
switch (type) {
|
|
140
|
+
case 'string':
|
|
141
|
+
return typeof value === 'string'
|
|
142
|
+
case 'number':
|
|
143
|
+
return typeof value === 'number' && Number.isFinite(value)
|
|
144
|
+
case 'integer':
|
|
145
|
+
return typeof value === 'number' && Number.isInteger(value)
|
|
146
|
+
case 'boolean':
|
|
147
|
+
return typeof value === 'boolean'
|
|
148
|
+
case 'object':
|
|
149
|
+
return isPlainObject(value)
|
|
150
|
+
case 'array':
|
|
151
|
+
return Array.isArray(value)
|
|
152
|
+
case 'null':
|
|
153
|
+
return value === null
|
|
154
|
+
default:
|
|
155
|
+
return false
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Validate a model result against the subset of JSON Schema the IR uses.
|
|
161
|
+
* @param {unknown} value - parsed model output.
|
|
162
|
+
* @param {object | boolean} schema - the node's schema.
|
|
163
|
+
* @param {string} [path] - where the value sits, for messages.
|
|
164
|
+
* @returns {string[]} problems; empty means valid.
|
|
165
|
+
*/
|
|
166
|
+
export function validateSchemaValue(value, schema, path = '$') {
|
|
167
|
+
const problems = []
|
|
168
|
+
validateAgainst(value, schema, path, problems)
|
|
169
|
+
return problems
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function validateAgainst(value, schema, path, problems) {
|
|
173
|
+
if (schema === true) return
|
|
174
|
+
if (schema === false) {
|
|
175
|
+
problems.push(`${path}: no value is allowed`)
|
|
176
|
+
return
|
|
177
|
+
}
|
|
178
|
+
if (!isPlainObject(schema)) {
|
|
179
|
+
problems.push(`${path}: schema must be an object or boolean`)
|
|
180
|
+
return
|
|
181
|
+
}
|
|
182
|
+
if (Object.prototype.hasOwnProperty.call(schema, 'const') && !deepEqual(value, schema.const)) {
|
|
183
|
+
problems.push(`${path}: expected ${JSON.stringify(schema.const)}`)
|
|
184
|
+
}
|
|
185
|
+
if (Array.isArray(schema.enum) && !schema.enum.some(item => deepEqual(value, item))) {
|
|
186
|
+
problems.push(`${path}: expected one of ${JSON.stringify(schema.enum)}`)
|
|
187
|
+
}
|
|
188
|
+
if (schema.type !== undefined) {
|
|
189
|
+
const types = Array.isArray(schema.type) ? schema.type : [schema.type]
|
|
190
|
+
if (!types.some(type => matchesSchemaType(value, type))) {
|
|
191
|
+
problems.push(`${path}: expected ${types.join(' | ')}`)
|
|
192
|
+
return
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
if (isPlainObject(value)) {
|
|
196
|
+
if (Array.isArray(schema.required)) {
|
|
197
|
+
for (const key of schema.required) {
|
|
198
|
+
if (typeof key === 'string' && !Object.prototype.hasOwnProperty.call(value, key)) {
|
|
199
|
+
problems.push(`${path}.${key}: required`)
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
const properties = isPlainObject(schema.properties) ? schema.properties : {}
|
|
204
|
+
for (const [key, subSchema] of Object.entries(properties)) {
|
|
205
|
+
if (Object.prototype.hasOwnProperty.call(value, key)) {
|
|
206
|
+
validateAgainst(value[key], subSchema, `${path}.${key}`, problems)
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
if (schema.additionalProperties === false) {
|
|
210
|
+
for (const key of Object.keys(value)) {
|
|
211
|
+
if (!Object.prototype.hasOwnProperty.call(properties, key)) {
|
|
212
|
+
problems.push(`${path}.${key}: unexpected property`)
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
} else if (isPlainObject(schema.additionalProperties)) {
|
|
216
|
+
for (const key of Object.keys(value)) {
|
|
217
|
+
if (!Object.prototype.hasOwnProperty.call(properties, key)) {
|
|
218
|
+
validateAgainst(value[key], schema.additionalProperties, `${path}.${key}`, problems)
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
if (Array.isArray(value)) {
|
|
224
|
+
if (isPlainObject(schema.items)) {
|
|
225
|
+
value.forEach((item, index) => validateAgainst(item, schema.items, `${path}[${index}]`, problems))
|
|
226
|
+
}
|
|
227
|
+
if (Number.isInteger(schema.minItems) && value.length < schema.minItems) {
|
|
228
|
+
problems.push(`${path}: expected at least ${schema.minItems} items`)
|
|
229
|
+
}
|
|
230
|
+
if (Number.isInteger(schema.maxItems) && value.length > schema.maxItems) {
|
|
231
|
+
problems.push(`${path}: expected at most ${schema.maxItems} items`)
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
if (typeof value === 'string') {
|
|
235
|
+
if (Number.isInteger(schema.minLength) && value.length < schema.minLength) {
|
|
236
|
+
problems.push(`${path}: expected at least ${schema.minLength} characters`)
|
|
237
|
+
}
|
|
238
|
+
if (Number.isInteger(schema.maxLength) && value.length > schema.maxLength) {
|
|
239
|
+
problems.push(`${path}: expected at most ${schema.maxLength} characters`)
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
if (typeof value === 'number') {
|
|
243
|
+
if (typeof schema.minimum === 'number' && value < schema.minimum) {
|
|
244
|
+
problems.push(`${path}: expected at least ${schema.minimum}`)
|
|
245
|
+
}
|
|
246
|
+
if (typeof schema.maximum === 'number' && value > schema.maximum) {
|
|
247
|
+
problems.push(`${path}: expected at most ${schema.maximum}`)
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Validate one GraphSpec.
|
|
254
|
+
* @param {unknown} input - the parsed spec.
|
|
255
|
+
* @param {{ tools?: string[] | Set<string> | object[] }} [options] - visible tool names or definitions to check.
|
|
256
|
+
* @returns {{ ok: boolean, errors: object[], warnings: object[] }} the result.
|
|
257
|
+
*/
|
|
258
|
+
export function validateSpec(input, options = {}) {
|
|
259
|
+
const errors = []
|
|
260
|
+
const warnings = []
|
|
261
|
+
const fail = (path, message, expected, hint) => {
|
|
262
|
+
errors.push({
|
|
263
|
+
path,
|
|
264
|
+
message,
|
|
265
|
+
...(expected === undefined ? {} : { expected }),
|
|
266
|
+
...(hint === undefined ? {} : { hint }),
|
|
267
|
+
})
|
|
268
|
+
}
|
|
269
|
+
const warn = (path, message, code) => {
|
|
270
|
+
warnings.push({ path, message, code })
|
|
271
|
+
}
|
|
272
|
+
const stateFields = new Map()
|
|
273
|
+
const nodes = new Map()
|
|
274
|
+
const normalizedTools = normalizeTools(options.tools)
|
|
275
|
+
const visibleTools = normalizedTools?.names
|
|
276
|
+
const toolSchemas = normalizedTools?.schemas ?? new Map()
|
|
277
|
+
|
|
278
|
+
function resolveRefType(ref, path) {
|
|
279
|
+
const target = ref.$state
|
|
280
|
+
const dot = target.indexOf('.')
|
|
281
|
+
const base = dot === -1 ? target : target.slice(0, dot)
|
|
282
|
+
const field = stateFields.get(base)
|
|
283
|
+
if (field === undefined) {
|
|
284
|
+
fail(path, `state reference "${target}" does not name a declared field`, [...stateFields.keys()].sort().join(' | ') || undefined)
|
|
285
|
+
return undefined
|
|
286
|
+
}
|
|
287
|
+
if (dot !== -1 && field.type !== 'json') {
|
|
288
|
+
fail(path, `dotted state reference "${target}" requires "${base}" to be a json field`)
|
|
289
|
+
return undefined
|
|
290
|
+
}
|
|
291
|
+
return field.type
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
function checkStateValue(value, path) {
|
|
295
|
+
if (hasStateKey(value)) {
|
|
296
|
+
if (!isStateRef(value)) {
|
|
297
|
+
fail(path, 'a state reference must be exactly { "$state": "<field>" }')
|
|
298
|
+
return
|
|
299
|
+
}
|
|
300
|
+
resolveRefType(value, path)
|
|
301
|
+
return
|
|
302
|
+
}
|
|
303
|
+
if (Array.isArray(value)) {
|
|
304
|
+
value.forEach((item, index) => checkStateValue(item, `${path}[${index}]`))
|
|
305
|
+
return
|
|
306
|
+
}
|
|
307
|
+
if (isPlainObject(value)) {
|
|
308
|
+
for (const [key, item] of Object.entries(value)) checkStateValue(item, `${path}.${key}`)
|
|
309
|
+
return
|
|
310
|
+
}
|
|
311
|
+
if (!isJsonValue(value)) {
|
|
312
|
+
fail(path, 'value must be JSON (string, number, boolean, null, array, or object)')
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function checkAssignment(value, targetType, path) {
|
|
317
|
+
if (hasStateKey(value)) {
|
|
318
|
+
if (!isStateRef(value)) {
|
|
319
|
+
fail(path, 'a state reference must be exactly { "$state": "<field>" }')
|
|
320
|
+
return
|
|
321
|
+
}
|
|
322
|
+
const refType = resolveRefType(value, path)
|
|
323
|
+
if (refType !== undefined && refType !== targetType && targetType !== 'json') {
|
|
324
|
+
fail(path, `cannot assign a ${refType} state value to a ${targetType} field`, targetType)
|
|
325
|
+
}
|
|
326
|
+
return
|
|
327
|
+
}
|
|
328
|
+
if (Array.isArray(value) || isPlainObject(value)) {
|
|
329
|
+
const nested = findStateKey(value)
|
|
330
|
+
if (nested !== undefined) {
|
|
331
|
+
fail(path, `a state reference is only allowed as the whole value; found one at ${nested}`)
|
|
332
|
+
return
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
if (!matchesStateType(value, targetType)) {
|
|
336
|
+
fail(path, `value ${preview(value)} does not match state type "${targetType}"`, targetType)
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
function checkPrompt(parts, path) {
|
|
341
|
+
if (!Array.isArray(parts)) {
|
|
342
|
+
fail(path, '`prompt` must be an array of strings and state references', 'array')
|
|
343
|
+
return
|
|
344
|
+
}
|
|
345
|
+
if (parts.length === 0) {
|
|
346
|
+
fail(path, '`prompt` must have at least one part')
|
|
347
|
+
return
|
|
348
|
+
}
|
|
349
|
+
let hasRef = false
|
|
350
|
+
let text = ''
|
|
351
|
+
parts.forEach((part, index) => {
|
|
352
|
+
const partPath = `${path}[${index}]`
|
|
353
|
+
if (typeof part === 'string') {
|
|
354
|
+
text += part
|
|
355
|
+
return
|
|
356
|
+
}
|
|
357
|
+
if (isStateRef(part)) {
|
|
358
|
+
hasRef = true
|
|
359
|
+
resolveRefType(part, partPath)
|
|
360
|
+
return
|
|
361
|
+
}
|
|
362
|
+
fail(partPath, 'a prompt part must be a string or { "$state": "<field>" }')
|
|
363
|
+
})
|
|
364
|
+
if (!hasRef && text.trim() === '') {
|
|
365
|
+
fail(path, '`prompt` must contain text or a state reference')
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
function transformFitsMap(kind, fieldType) {
|
|
370
|
+
const produced = TRANSFORM_TYPES[kind]
|
|
371
|
+
if (produced === fieldType) return true
|
|
372
|
+
if (fieldType === 'json') return kind === 'json'
|
|
373
|
+
if (fieldType === 'string[]') return kind === 'text' || kind === 'first'
|
|
374
|
+
if (fieldType === 'number[]') return kind === 'number' || kind === 'count'
|
|
375
|
+
return false
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
function checkOut(node, path, options = {}) {
|
|
379
|
+
if (!isPlainObject(node.out)) {
|
|
380
|
+
fail(`${path}.out`, '`out` must be an object mapping state fields to transforms', 'object')
|
|
381
|
+
return
|
|
382
|
+
}
|
|
383
|
+
const map = options.map === true
|
|
384
|
+
const schemaType = isPlainObject(node.schema) && typeof node.schema.type === 'string'
|
|
385
|
+
? node.schema.type
|
|
386
|
+
: undefined
|
|
387
|
+
for (const [field, kind] of Object.entries(node.out)) {
|
|
388
|
+
const outPath = `${path}.out.${field}`
|
|
389
|
+
if (map && (field === 'item' || field === 'index')) {
|
|
390
|
+
fail(outPath, `"${field}" is reserved by a map body; write a parent state field instead`)
|
|
391
|
+
continue
|
|
392
|
+
}
|
|
393
|
+
const definition = stateFields.get(field)
|
|
394
|
+
if (definition === undefined) {
|
|
395
|
+
fail(outPath, `"${field}" is not a declared state field`, [...stateFields.keys()].sort().join(' | ') || undefined)
|
|
396
|
+
continue
|
|
397
|
+
}
|
|
398
|
+
if (!TRANSFORMS.includes(kind)) {
|
|
399
|
+
fail(outPath, `unknown transform ${JSON.stringify(kind)}`, TRANSFORMS.join(' | '))
|
|
400
|
+
continue
|
|
401
|
+
}
|
|
402
|
+
if (map) {
|
|
403
|
+
const reducer = definition.reducer ?? 'replace'
|
|
404
|
+
if (reducer === 'replace') {
|
|
405
|
+
fail(outPath, `a map body writes "${field}" concurrently; give the field a mergeable reducer`, 'append | add | max | min | merge', 'Declare the field with reducer "append" for a list (string[]/number[], or json with default []), or "merge" for one json object; text into string[] + append adds one element per item.')
|
|
406
|
+
continue
|
|
407
|
+
}
|
|
408
|
+
if (!transformFitsMap(kind, definition.type)) {
|
|
409
|
+
fail(outPath, `transform "${kind}" cannot aggregate into a ${definition.type} field`, `a transform that writes ${definition.type}`)
|
|
410
|
+
}
|
|
411
|
+
continue
|
|
412
|
+
}
|
|
413
|
+
const produced = TRANSFORM_TYPES[kind]
|
|
414
|
+
const compatible = produced === definition.type
|
|
415
|
+
|| definition.type === 'json'
|
|
416
|
+
|| (kind === 'json' && schemaType === definition.type)
|
|
417
|
+
if (!compatible) {
|
|
418
|
+
fail(outPath, `transform "${kind}" produces ${produced}, but "${field}" is ${definition.type}`, `a transform producing ${definition.type}`)
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
function checkSchemaField(node, path) {
|
|
424
|
+
if (node.schema !== undefined && !isPlainObject(node.schema)) {
|
|
425
|
+
fail(`${path}.schema`, '`schema` must be a JSON Schema object', 'object')
|
|
426
|
+
} else if (node.schema !== undefined && !isJsonValue(node.schema)) {
|
|
427
|
+
fail(`${path}.schema`, '`schema` must be JSON-serializable')
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
function checkToolFields(node, path, options = {}) {
|
|
432
|
+
if (typeof node.tool !== 'string' || node.tool.trim() === '') {
|
|
433
|
+
fail(`${path}.tool`, '`tool` must be a non-empty tool name')
|
|
434
|
+
} else {
|
|
435
|
+
checkVisibleTool(node.tool, `${path}.tool`)
|
|
436
|
+
}
|
|
437
|
+
if (!isPlainObject(node.args)) {
|
|
438
|
+
fail(`${path}.args`, '`args` must be an object (use {} for no arguments)', 'object')
|
|
439
|
+
} else {
|
|
440
|
+
for (const [key, value] of Object.entries(node.args)) {
|
|
441
|
+
checkStateValue(value, `${path}.args.${key}`)
|
|
442
|
+
}
|
|
443
|
+
if (typeof node.tool === 'string') checkToolArgs(node.tool, node.args, `${path}.args`)
|
|
444
|
+
}
|
|
445
|
+
checkOut(node, path, options)
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
function checkModelFields(node, path, options = {}) {
|
|
449
|
+
checkPrompt(node.prompt, `${path}.prompt`)
|
|
450
|
+
if (node.system !== undefined && (typeof node.system !== 'string' || node.system.trim() === '')) {
|
|
451
|
+
fail(`${path}.system`, '`system` must be a non-empty string')
|
|
452
|
+
}
|
|
453
|
+
checkSchemaField(node, path)
|
|
454
|
+
checkOut(node, path, options)
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
function checkAgentFields(node, path, options = {}) {
|
|
458
|
+
checkPrompt(node.prompt, `${path}.prompt`)
|
|
459
|
+
if (!Array.isArray(node.tools)) {
|
|
460
|
+
fail(`${path}.tools`, '`tools` must be an array of tool names', 'array')
|
|
461
|
+
} else {
|
|
462
|
+
const seen = new Set()
|
|
463
|
+
node.tools.forEach((tool, toolIndex) => {
|
|
464
|
+
const toolPath = `${path}.tools[${toolIndex}]`
|
|
465
|
+
if (typeof tool !== 'string' || tool.trim() === '') {
|
|
466
|
+
fail(toolPath, 'a tool name must be a non-empty string')
|
|
467
|
+
} else if (seen.has(tool)) {
|
|
468
|
+
fail(toolPath, `duplicate tool "${tool}"`)
|
|
469
|
+
} else {
|
|
470
|
+
seen.add(tool)
|
|
471
|
+
checkVisibleTool(tool, toolPath)
|
|
472
|
+
}
|
|
473
|
+
})
|
|
474
|
+
}
|
|
475
|
+
checkOut(node, path, options)
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
function checkSubagentFields(node, path, options = {}) {
|
|
479
|
+
checkPrompt(node.prompt, `${path}.prompt`)
|
|
480
|
+
checkSchemaField(node, path)
|
|
481
|
+
checkOut(node, path, options)
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
function checkMapBody(node, path, itemType) {
|
|
485
|
+
if (!isPlainObject(node.body)) {
|
|
486
|
+
fail(`${path}.body`, '`body` must be one node object', 'object')
|
|
487
|
+
return
|
|
488
|
+
}
|
|
489
|
+
const body = node.body
|
|
490
|
+
const bodyPath = `${path}.body`
|
|
491
|
+
if (!MAP_BODY_KINDS.includes(body.do)) {
|
|
492
|
+
fail(`${bodyPath}.do`, `a map body must be one of ${MAP_BODY_KINDS.join(' | ')}`, MAP_BODY_KINDS.join(' | '))
|
|
493
|
+
return
|
|
494
|
+
}
|
|
495
|
+
if (body.id !== undefined && (typeof body.id !== 'string' || body.id.trim() === '' || /\s/.test(body.id))) {
|
|
496
|
+
fail(`${bodyPath}.id`, '`id` must be a non-empty string without whitespace when present')
|
|
497
|
+
}
|
|
498
|
+
checkKeys(body, MAP_BODY_FIELDS[body.do], bodyPath, fail)
|
|
499
|
+
const previousItem = stateFields.get('item')
|
|
500
|
+
const previousIndex = stateFields.get('index')
|
|
501
|
+
stateFields.set('item', { type: itemType, reducer: 'replace', default: undefined })
|
|
502
|
+
stateFields.set('index', { type: 'number', reducer: 'replace', default: 0 })
|
|
503
|
+
try {
|
|
504
|
+
switch (body.do) {
|
|
505
|
+
case 'tool':
|
|
506
|
+
checkToolFields(body, bodyPath, { map: true })
|
|
507
|
+
break
|
|
508
|
+
case 'model':
|
|
509
|
+
checkModelFields(body, bodyPath, { map: true })
|
|
510
|
+
break
|
|
511
|
+
case 'agent':
|
|
512
|
+
checkAgentFields(body, bodyPath, { map: true })
|
|
513
|
+
break
|
|
514
|
+
case 'subagent':
|
|
515
|
+
checkSubagentFields(body, bodyPath, { map: true })
|
|
516
|
+
break
|
|
517
|
+
default:
|
|
518
|
+
break
|
|
519
|
+
}
|
|
520
|
+
} finally {
|
|
521
|
+
if (previousItem === undefined) stateFields.delete('item')
|
|
522
|
+
else stateFields.set('item', previousItem)
|
|
523
|
+
if (previousIndex === undefined) stateFields.delete('index')
|
|
524
|
+
else stateFields.set('index', previousIndex)
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
function checkVisibleTool(name, path) {
|
|
529
|
+
if (visibleTools === undefined) return
|
|
530
|
+
if (visibleTools.has(name)) return
|
|
531
|
+
fail(path, `tool "${name}" is not visible to this agent`, [...visibleTools].sort().join(' | ') || 'no tools')
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
/** Check a tool node's args against the visible tool's own JSON schema. */
|
|
535
|
+
function checkToolArgs(toolName, args, path) {
|
|
536
|
+
const schema = toolSchemas.get(toolName)
|
|
537
|
+
if (!isPlainObject(schema)) return
|
|
538
|
+
const required = Array.isArray(schema.required) ? schema.required.filter(key => typeof key === 'string') : []
|
|
539
|
+
const properties = isPlainObject(schema.properties) ? schema.properties : {}
|
|
540
|
+
for (const key of required) {
|
|
541
|
+
if (!Object.prototype.hasOwnProperty.call(args, key)) {
|
|
542
|
+
fail(path, `tool "${toolName}" requires argument "${key}"`, required.join(' | '), 'A tool node\'s args pass through unchanged; use the tool\'s own schema (for read: file_path).')
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
if (schema.additionalProperties === false) {
|
|
546
|
+
for (const key of Object.keys(args)) {
|
|
547
|
+
if (!Object.prototype.hasOwnProperty.call(properties, key)) {
|
|
548
|
+
fail(`${path}.${key}`, `"${key}" is not an argument of tool "${toolName}"`, Object.keys(properties).sort().join(' | ') || undefined, 'A tool node\'s args pass through unchanged; use the tool\'s own schema.')
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
for (const [key, value] of Object.entries(args)) {
|
|
553
|
+
const propSchema = properties[key]
|
|
554
|
+
if (hasStateKey(value)) {
|
|
555
|
+
const ref = isPlainObject(value) && typeof value.$state === 'string' ? value.$state : undefined
|
|
556
|
+
const expected = isPlainObject(propSchema) && typeof propSchema.type === 'string' ? propSchema.type : undefined
|
|
557
|
+
if (ref !== undefined && expected !== undefined && !ref.includes('.')) {
|
|
558
|
+
const field = stateFields.get(ref)
|
|
559
|
+
const fits = field === undefined || field.type === 'json'
|
|
560
|
+
? true
|
|
561
|
+
: expected === 'string'
|
|
562
|
+
? field.type === 'string'
|
|
563
|
+
: expected === 'number' || expected === 'integer'
|
|
564
|
+
? field.type === 'number'
|
|
565
|
+
: expected === 'boolean'
|
|
566
|
+
? field.type === 'boolean'
|
|
567
|
+
: expected === 'array'
|
|
568
|
+
? field.type === 'string[]' || field.type === 'number[]'
|
|
569
|
+
: true
|
|
570
|
+
if (!fits) {
|
|
571
|
+
fail(`${path}.${key}`, `state reference "${ref}" is ${field.type}, but tool "${toolName}" expects ${expected}`, expected, 'A $state reference must match the tool argument type; use a field of the expected type.')
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
continue
|
|
575
|
+
}
|
|
576
|
+
if (!isPlainObject(propSchema)) continue
|
|
577
|
+
for (const problem of validateSchemaValue(value, propSchema, `${path}.${key}`)) {
|
|
578
|
+
fail(`${path}.${key}`, problem, undefined, `Argument "${key}" of tool "${toolName}" does not match the tool's schema.`)
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
function operandType(value, path) {
|
|
584
|
+
if (hasStateKey(value)) {
|
|
585
|
+
if (!isStateRef(value)) {
|
|
586
|
+
fail(path, 'a state reference must be exactly { "$state": "<field>" }')
|
|
587
|
+
return undefined
|
|
588
|
+
}
|
|
589
|
+
return resolveRefType(value, path)
|
|
590
|
+
}
|
|
591
|
+
if (isPlainObject(value) && Object.prototype.hasOwnProperty.call(value, 'op')) {
|
|
592
|
+
fail(path, 'a nested guard is only allowed inside "and", "or", or "not"')
|
|
593
|
+
return undefined
|
|
594
|
+
}
|
|
595
|
+
if (!isJsonValue(value)) {
|
|
596
|
+
fail(path, 'a guard operand must be a JSON value or a state reference')
|
|
597
|
+
return undefined
|
|
598
|
+
}
|
|
599
|
+
return jsonKind(value)
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
function checkGuard(guard, path) {
|
|
603
|
+
if (guard === true || guard === false) return
|
|
604
|
+
if (!isPlainObject(guard)) {
|
|
605
|
+
fail(path, 'a guard must be true, false, or { "op": "...", "args": [...] }')
|
|
606
|
+
return
|
|
607
|
+
}
|
|
608
|
+
if (hasStateKey(guard)) {
|
|
609
|
+
fail(path, 'a guard must be true, false, or { "op": "...", "args": [...] }, not a state reference')
|
|
610
|
+
return
|
|
611
|
+
}
|
|
612
|
+
checkKeys(guard, ['op', 'args'], path, fail)
|
|
613
|
+
if (!GUARD_OPS.includes(guard.op)) {
|
|
614
|
+
fail(`${path}.op`, `unknown guard op ${JSON.stringify(guard.op)}`, GUARD_OPS.join(' | '))
|
|
615
|
+
return
|
|
616
|
+
}
|
|
617
|
+
if (!Array.isArray(guard.args)) {
|
|
618
|
+
fail(`${path}.args`, 'guard `args` must be an array', 'array')
|
|
619
|
+
return
|
|
620
|
+
}
|
|
621
|
+
const op = guard.op
|
|
622
|
+
if (op === 'and' || op === 'or') {
|
|
623
|
+
if (guard.args.length === 0) fail(`${path}.args`, `"${op}" needs at least one guard`)
|
|
624
|
+
guard.args.forEach((item, index) => checkGuard(item, `${path}.args[${index}]`))
|
|
625
|
+
return
|
|
626
|
+
}
|
|
627
|
+
if (op === 'not') {
|
|
628
|
+
if (guard.args.length !== 1) fail(`${path}.args`, '"not" takes exactly one guard')
|
|
629
|
+
if (guard.args.length >= 1) checkGuard(guard.args[0], `${path}.args[0]`)
|
|
630
|
+
return
|
|
631
|
+
}
|
|
632
|
+
const arity = op === 'exists' ? 1 : 2
|
|
633
|
+
if (guard.args.length !== arity) {
|
|
634
|
+
fail(`${path}.args`, `"${op}" takes exactly ${arity} operand${arity === 1 ? '' : 's'}`)
|
|
635
|
+
}
|
|
636
|
+
const types = guard.args.map((arg, index) => operandType(arg, `${path}.args[${index}]`))
|
|
637
|
+
if (op === 'gt' || op === 'gte' || op === 'lt' || op === 'lte') {
|
|
638
|
+
types.forEach((type, index) => {
|
|
639
|
+
if (type !== undefined && type !== 'number' && type !== 'json') {
|
|
640
|
+
fail(`${path}.args[${index}]`, `"${op}" compares numbers; this operand is ${type}`, 'number')
|
|
641
|
+
}
|
|
642
|
+
})
|
|
643
|
+
}
|
|
644
|
+
if (op === 'in') {
|
|
645
|
+
const haystack = types[1]
|
|
646
|
+
if (haystack !== undefined && !['array', 'string[]', 'number[]', 'json'].includes(haystack)) {
|
|
647
|
+
fail(`${path}.args[1]`, `"in" needs an array on the right; this operand is ${haystack}`, 'array')
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
if (op === 'eq' || op === 'ne') {
|
|
651
|
+
const primitive = type => type === 'string' || type === 'number' || type === 'boolean' || type === 'null'
|
|
652
|
+
if (primitive(types[0]) && primitive(types[1]) && types[0] !== types[1]) {
|
|
653
|
+
fail(path, `"${op}" compares ${types[0]} with ${types[1]}; they can never be equal`, 'matching types')
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
if (!isPlainObject(input)) {
|
|
659
|
+
fail('', 'the spec must be a JSON object', 'object')
|
|
660
|
+
return { ok: false, errors, warnings }
|
|
661
|
+
}
|
|
662
|
+
checkKeys(input, ['ir', 'name', 'description', 'state', 'nodes', 'edges', 'output', 'maxSteps'], '', fail)
|
|
663
|
+
|
|
664
|
+
if (input.ir !== IR_VERSION) {
|
|
665
|
+
fail('ir', `unsupported IR version ${JSON.stringify(input.ir)}; this compiler reads ir: ${IR_VERSION}`, String(IR_VERSION))
|
|
666
|
+
}
|
|
667
|
+
if (input.name !== undefined && (typeof input.name !== 'string' || input.name.trim() === '')) {
|
|
668
|
+
fail('name', '`name` must be a non-empty string')
|
|
669
|
+
}
|
|
670
|
+
if (input.description !== undefined && (typeof input.description !== 'string' || input.description.trim() === '')) {
|
|
671
|
+
fail('description', '`description` must be a non-empty string')
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
// --- state ------------------------------------------------------------------
|
|
675
|
+
if (!isPlainObject(input.state)) {
|
|
676
|
+
fail('state', '`state` must be an object of field definitions', 'object')
|
|
677
|
+
} else {
|
|
678
|
+
const entries = Object.entries(input.state)
|
|
679
|
+
if (entries.length === 0) fail('state', '`state` must declare at least one field')
|
|
680
|
+
if (entries.length > LIMITS.stateFields) {
|
|
681
|
+
fail('state', `too many state fields (${entries.length}); the limit is ${LIMITS.stateFields}`)
|
|
682
|
+
}
|
|
683
|
+
for (const [name, field] of entries) {
|
|
684
|
+
const path = `state.${name}`
|
|
685
|
+
if (name === '' || name.includes('.') || /\s/.test(name)) {
|
|
686
|
+
fail(path, 'state field names must be non-empty and may not contain "." or whitespace')
|
|
687
|
+
continue
|
|
688
|
+
}
|
|
689
|
+
if (name === '__interrupt__' || name === '__start__' || name === '__end__') {
|
|
690
|
+
fail(path, `"${name}" is reserved by LangGraph`)
|
|
691
|
+
continue
|
|
692
|
+
}
|
|
693
|
+
if (!isPlainObject(field)) {
|
|
694
|
+
fail(path, 'a state field must be an object', '{ "type", "default", "reducer"? }')
|
|
695
|
+
continue
|
|
696
|
+
}
|
|
697
|
+
checkKeys(field, ['type', 'default', 'reducer'], path, fail)
|
|
698
|
+
const typeKnown = STATE_TYPES.includes(field.type)
|
|
699
|
+
if (!typeKnown) {
|
|
700
|
+
fail(`${path}.type`, `unknown state type ${JSON.stringify(field.type)}`, STATE_TYPES.join(' | '))
|
|
701
|
+
}
|
|
702
|
+
if (!Object.prototype.hasOwnProperty.call(field, 'default')) {
|
|
703
|
+
fail(`${path}.default`, '`default` is required', field.type)
|
|
704
|
+
} else if (typeKnown && !matchesStateType(field.default, field.type)) {
|
|
705
|
+
fail(`${path}.default`, `default ${preview(field.default)} does not match type "${field.type}"`, field.type)
|
|
706
|
+
}
|
|
707
|
+
const reducer = field.reducer ?? 'replace'
|
|
708
|
+
if (field.reducer !== undefined && !REDUCERS.includes(field.reducer)) {
|
|
709
|
+
fail(`${path}.reducer`, `unknown reducer ${JSON.stringify(field.reducer)}`, REDUCERS.join(' | '))
|
|
710
|
+
} else if (typeKnown && !reducerFits(reducer, field.type, field.default)) {
|
|
711
|
+
fail(`${path}.reducer`, `reducer "${reducer}" is not compatible with type "${field.type}" and this default`, 'replace', 'For a json list, use type json, default [], reducer append; for a json object, use type json, default {}, reducer merge. merge shallow-merges objects and does not concatenate arrays.')
|
|
712
|
+
}
|
|
713
|
+
// Keep a best-effort entry even after a type error, so later messages do
|
|
714
|
+
// not cascade into "unknown field" for every reference.
|
|
715
|
+
stateFields.set(name, {
|
|
716
|
+
type: typeKnown ? field.type : 'json',
|
|
717
|
+
reducer,
|
|
718
|
+
default: field.default,
|
|
719
|
+
})
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
// --- nodes ------------------------------------------------------------------
|
|
724
|
+
if (!Array.isArray(input.nodes)) {
|
|
725
|
+
fail('nodes', '`nodes` must be an array', 'array')
|
|
726
|
+
} else {
|
|
727
|
+
if (input.nodes.length === 0) fail('nodes', '`nodes` must have at least one node')
|
|
728
|
+
if (input.nodes.length > LIMITS.nodes) {
|
|
729
|
+
fail('nodes', `too many nodes (${input.nodes.length}); the limit is ${LIMITS.nodes}`)
|
|
730
|
+
}
|
|
731
|
+
input.nodes.forEach((node, index) => {
|
|
732
|
+
const path = `nodes[${index}]`
|
|
733
|
+
if (!isPlainObject(node)) {
|
|
734
|
+
fail(path, 'a node must be an object')
|
|
735
|
+
return
|
|
736
|
+
}
|
|
737
|
+
if (typeof node.id !== 'string' || node.id.trim() === '' || /\s/.test(node.id)) {
|
|
738
|
+
fail(`${path}.id`, '`id` must be a non-empty string without whitespace')
|
|
739
|
+
return
|
|
740
|
+
}
|
|
741
|
+
if (node.id === START || node.id === END) {
|
|
742
|
+
fail(`${path}.id`, `"${node.id}" is reserved`)
|
|
743
|
+
return
|
|
744
|
+
}
|
|
745
|
+
if (node.id === '__start__' || node.id === '__end__' || node.id === '__interrupt__') {
|
|
746
|
+
fail(`${path}.id`, `"${node.id}" is reserved by LangGraph`)
|
|
747
|
+
return
|
|
748
|
+
}
|
|
749
|
+
if (nodes.has(node.id)) {
|
|
750
|
+
fail(`${path}.id`, `duplicate node id "${node.id}"`)
|
|
751
|
+
return
|
|
752
|
+
}
|
|
753
|
+
if (stateFields.has(node.id)) {
|
|
754
|
+
fail(`${path}.id`, `"${node.id}" is also a state field; node ids and state field names must differ`)
|
|
755
|
+
}
|
|
756
|
+
if (!NODE_KINDS.includes(node.do)) {
|
|
757
|
+
fail(`${path}.do`, `unknown node kind ${JSON.stringify(node.do)}`, NODE_KINDS.join(' | '))
|
|
758
|
+
return
|
|
759
|
+
}
|
|
760
|
+
nodes.set(node.id, node)
|
|
761
|
+
checkKeys(node, NODE_FIELDS[node.do], path, fail)
|
|
762
|
+
switch (node.do) {
|
|
763
|
+
case 'tool':
|
|
764
|
+
checkToolFields(node, path)
|
|
765
|
+
break
|
|
766
|
+
case 'model':
|
|
767
|
+
checkModelFields(node, path)
|
|
768
|
+
break
|
|
769
|
+
case 'agent':
|
|
770
|
+
checkAgentFields(node, path)
|
|
771
|
+
break
|
|
772
|
+
case 'subagent':
|
|
773
|
+
checkSubagentFields(node, path)
|
|
774
|
+
break
|
|
775
|
+
case 'map': {
|
|
776
|
+
if (typeof node.over !== 'string' || node.over === '' || node.over.includes('.')) {
|
|
777
|
+
fail(`${path}.over`, '`over` must be a top-level array state field name')
|
|
778
|
+
} else {
|
|
779
|
+
const over = stateFields.get(node.over)
|
|
780
|
+
if (over === undefined) {
|
|
781
|
+
fail(`${path}.over`, `"${node.over}" is not a declared state field`, [...stateFields.keys()].sort().join(' | ') || undefined, 'To turn a glob result into files, put out: { files: "lines" } on the glob tool node and map over "files".')
|
|
782
|
+
} else if (over.type !== 'string[]' && over.type !== 'number[]') {
|
|
783
|
+
fail(`${path}.over`, `"${node.over}" is ${over.type}; a map needs a string[] or number[] field`, 'string[] | number[]', 'To turn a glob result into files, put out: { files: "lines" } on the glob tool node and map over "files".')
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
if (node.maxItems !== undefined && (!Number.isInteger(node.maxItems) || node.maxItems < 1 || node.maxItems > LIMITS.maxMapItems)) {
|
|
787
|
+
fail(`${path}.maxItems`, `\`maxItems\` must be an integer between 1 and ${LIMITS.maxMapItems}`, `integer 1..${LIMITS.maxMapItems}`)
|
|
788
|
+
}
|
|
789
|
+
if (node.maxConcurrency !== undefined && (!Number.isInteger(node.maxConcurrency) || node.maxConcurrency < 1 || node.maxConcurrency > LIMITS.maxMapConcurrency)) {
|
|
790
|
+
fail(`${path}.maxConcurrency`, `\`maxConcurrency\` must be an integer between 1 and ${LIMITS.maxMapConcurrency}`, `integer 1..${LIMITS.maxMapConcurrency}`)
|
|
791
|
+
}
|
|
792
|
+
const over = typeof node.over === 'string' ? stateFields.get(node.over) : undefined
|
|
793
|
+
checkMapBody(node, path, over?.type === 'number[]' ? 'number' : 'string')
|
|
794
|
+
break
|
|
795
|
+
}
|
|
796
|
+
case 'gate':
|
|
797
|
+
if (typeof node.question !== 'string' || node.question.trim() === '') {
|
|
798
|
+
fail(`${path}.question`, '`question` must be a non-empty string')
|
|
799
|
+
}
|
|
800
|
+
if (node.options !== undefined) {
|
|
801
|
+
if (!Array.isArray(node.options) || node.options.length === 0) {
|
|
802
|
+
fail(`${path}.options`, '`options` must be a non-empty array of strings', 'array')
|
|
803
|
+
} else {
|
|
804
|
+
const seen = new Set()
|
|
805
|
+
node.options.forEach((option, optionIndex) => {
|
|
806
|
+
const optionPath = `${path}.options[${optionIndex}]`
|
|
807
|
+
if (typeof option !== 'string' || option.trim() === '') {
|
|
808
|
+
fail(optionPath, 'an option must be a non-empty string')
|
|
809
|
+
} else if (seen.has(option)) {
|
|
810
|
+
fail(optionPath, `duplicate option ${JSON.stringify(option)}`)
|
|
811
|
+
} else {
|
|
812
|
+
seen.add(option)
|
|
813
|
+
}
|
|
814
|
+
})
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
checkOut(node, path)
|
|
818
|
+
break
|
|
819
|
+
case 'set':
|
|
820
|
+
if (!isPlainObject(node.values)) {
|
|
821
|
+
fail(`${path}.values`, '`values` must be an object mapping state fields to values', 'object')
|
|
822
|
+
} else {
|
|
823
|
+
if (Object.keys(node.values).length === 0) {
|
|
824
|
+
warn(`${path}.values`, 'this set node writes nothing', 'no-op')
|
|
825
|
+
}
|
|
826
|
+
for (const [field, value] of Object.entries(node.values)) {
|
|
827
|
+
const valuePath = `${path}.values.${field}`
|
|
828
|
+
const definition = stateFields.get(field)
|
|
829
|
+
if (definition === undefined) {
|
|
830
|
+
fail(valuePath, `"${field}" is not a declared state field`, [...stateFields.keys()].sort().join(' | ') || undefined)
|
|
831
|
+
continue
|
|
832
|
+
}
|
|
833
|
+
checkAssignment(value, definition.type, valuePath)
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
break
|
|
837
|
+
default:
|
|
838
|
+
// `NODE_KINDS` gates the switch; this is unreachable.
|
|
839
|
+
break
|
|
840
|
+
}
|
|
841
|
+
})
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
// --- edges ------------------------------------------------------------------
|
|
845
|
+
const validEdges = []
|
|
846
|
+
if (!Array.isArray(input.edges)) {
|
|
847
|
+
fail('edges', '`edges` must be an array', 'array')
|
|
848
|
+
} else {
|
|
849
|
+
if (input.edges.length === 0) {
|
|
850
|
+
fail('edges', '`edges` must have at least one edge (START -> first node)')
|
|
851
|
+
}
|
|
852
|
+
if (input.edges.length > LIMITS.edges) {
|
|
853
|
+
fail('edges', `too many edges (${input.edges.length}); the limit is ${LIMITS.edges}`)
|
|
854
|
+
}
|
|
855
|
+
const seenEdges = new Map()
|
|
856
|
+
input.edges.forEach((edge, index) => {
|
|
857
|
+
const path = `edges[${index}]`
|
|
858
|
+
if (!isPlainObject(edge)) {
|
|
859
|
+
fail(path, 'an edge must be an object')
|
|
860
|
+
return
|
|
861
|
+
}
|
|
862
|
+
checkKeys(edge, ['from', 'to', 'when'], path, fail)
|
|
863
|
+
let fromOk = false
|
|
864
|
+
let toOk = false
|
|
865
|
+
if (typeof edge.from !== 'string') {
|
|
866
|
+
fail(`${path}.from`, '`from` must be a node id or "START"')
|
|
867
|
+
} else if (edge.from === END) {
|
|
868
|
+
fail(`${path}.from`, 'END cannot have outgoing edges')
|
|
869
|
+
} else if (edge.from !== START && !nodes.has(edge.from)) {
|
|
870
|
+
fail(`${path}.from`, `unknown source "${edge.from}"`, [START, ...nodes.keys()].join(' | '))
|
|
871
|
+
} else {
|
|
872
|
+
fromOk = true
|
|
873
|
+
}
|
|
874
|
+
if (typeof edge.to !== 'string') {
|
|
875
|
+
fail(`${path}.to`, '`to` must be a node id or "END"')
|
|
876
|
+
} else if (edge.to === START) {
|
|
877
|
+
fail(`${path}.to`, 'START cannot be a target')
|
|
878
|
+
} else if (edge.to !== END && !nodes.has(edge.to)) {
|
|
879
|
+
fail(`${path}.to`, `unknown target "${edge.to}"`, [...nodes.keys(), END].join(' | '))
|
|
880
|
+
} else {
|
|
881
|
+
toOk = true
|
|
882
|
+
}
|
|
883
|
+
if (edge.from === START && edge.when !== undefined) {
|
|
884
|
+
fail(`${path}.when`, 'START edges must be unconditional')
|
|
885
|
+
}
|
|
886
|
+
if (edge.when !== undefined) checkGuard(edge.when, `${path}.when`)
|
|
887
|
+
let guardKey
|
|
888
|
+
try {
|
|
889
|
+
guardKey = edge.when === undefined ? 'always' : stableStringify(edge.when)
|
|
890
|
+
} catch {
|
|
891
|
+
guardKey = String(edge.when)
|
|
892
|
+
}
|
|
893
|
+
const key = `${edge.from}\u0000${edge.to}\u0000${guardKey}`
|
|
894
|
+
if (seenEdges.has(key)) {
|
|
895
|
+
fail(path, `duplicate of edges[${seenEdges.get(key)}]`)
|
|
896
|
+
} else {
|
|
897
|
+
seenEdges.set(key, index)
|
|
898
|
+
}
|
|
899
|
+
if (fromOk && toOk) validEdges.push(edge)
|
|
900
|
+
})
|
|
901
|
+
|
|
902
|
+
if (!validEdges.some(edge => edge.from === START)) {
|
|
903
|
+
fail('edges', 'the graph needs at least one edge from START', 'START -> node')
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
for (const id of nodes.keys()) {
|
|
907
|
+
const outgoing = validEdges.filter(edge => edge.from === id)
|
|
908
|
+
if (outgoing.length === 0) continue
|
|
909
|
+
const conditional = outgoing.filter(edge => edge.when !== undefined)
|
|
910
|
+
const unconditional = outgoing.filter(edge => edge.when === undefined)
|
|
911
|
+
if (conditional.length > 0 && unconditional.length > 0) {
|
|
912
|
+
fail(`nodes.${id}`, 'outgoing edges mix conditional and unconditional edges; use sequence, choice, or parallel', 'one of sequence, choice, parallel')
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
// --- output / budget --------------------------------------------------------
|
|
918
|
+
if (input.output !== undefined) {
|
|
919
|
+
if (!Array.isArray(input.output)) {
|
|
920
|
+
fail('output', '`output` must be an array of state field names', 'array')
|
|
921
|
+
} else {
|
|
922
|
+
const seen = new Set()
|
|
923
|
+
input.output.forEach((field, index) => {
|
|
924
|
+
const path = `output[${index}]`
|
|
925
|
+
if (typeof field !== 'string' || field === '') {
|
|
926
|
+
fail(path, 'an output field must be a non-empty string')
|
|
927
|
+
} else if (!stateFields.has(field)) {
|
|
928
|
+
fail(path, `"${field}" is not a declared state field`, [...stateFields.keys()].sort().join(' | ') || undefined)
|
|
929
|
+
} else if (seen.has(field)) {
|
|
930
|
+
fail(path, `duplicate output field "${field}"`)
|
|
931
|
+
} else {
|
|
932
|
+
seen.add(field)
|
|
933
|
+
}
|
|
934
|
+
})
|
|
935
|
+
if (input.output.length === 0) warn('output', '`output` is empty; the run returns no state field', 'no-output')
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
if (input.maxSteps !== undefined && (!Number.isInteger(input.maxSteps) || input.maxSteps < 1 || input.maxSteps > LIMITS.maxSteps)) {
|
|
940
|
+
fail('maxSteps', `\`maxSteps\` must be an integer between 1 and ${LIMITS.maxSteps}`, `integer 1..${LIMITS.maxSteps}`)
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
let serialized
|
|
944
|
+
try {
|
|
945
|
+
serialized = JSON.stringify(input)
|
|
946
|
+
} catch {
|
|
947
|
+
fail('', 'the spec must be JSON-serializable')
|
|
948
|
+
}
|
|
949
|
+
if (serialized !== undefined) {
|
|
950
|
+
const bytes = Buffer.byteLength(serialized, 'utf8')
|
|
951
|
+
if (bytes > LIMITS.specBytes) {
|
|
952
|
+
fail('', `the spec is ${bytes} bytes; the limit is ${LIMITS.specBytes}`, `<= ${LIMITS.specBytes} bytes`)
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
if (errors.length === 0) {
|
|
957
|
+
const analysis = analyze(input)
|
|
958
|
+
warnings.push(...lintWarnings(input, analysis))
|
|
959
|
+
errors.push(...fanOutProblems(input, analysis))
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
return { ok: errors.length === 0, errors, warnings }
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
/**
|
|
966
|
+
* Validate a spec or throw a `SpecError` carrying every error.
|
|
967
|
+
* @param {unknown} spec - the parsed spec.
|
|
968
|
+
* @param {{ tools?: string[] | Set<string> }} [options] - visible tool names.
|
|
969
|
+
* @returns {{ ok: true, errors: [], warnings: object[] }} the result.
|
|
970
|
+
*/
|
|
971
|
+
export function assertSpec(spec, options = {}) {
|
|
972
|
+
const result = validateSpec(spec, options)
|
|
973
|
+
if (!result.ok) throw new SpecError(result.errors)
|
|
974
|
+
return result
|
|
975
|
+
}
|