/** * ============================================================ * plugins/workflow-runner/src/jsonSchema.ts —— JSON Schema 子集校验 * ------------------------------------------------------------ * 为什么手写而不是引 ajv: * ① 工作流的结构化输出契约采用可序列化的 JSON Schema 子集,便于参与 journal * 指纹并跨 provider 使用。 * ② 校验结果要**回喂给模型做修复**,所以错误消息比规范覆盖度重要得多 —— * 「`branches[2].score` 应为 number,实际是 string」比一句 * `must be number` 有用,而通用库的默认文案偏向后者。 * ③ 项目一贯取向:能用基本类型说清就不引第三方(见 CLAUDE.md 设计原则)。 * * 支持的关键字:type(含数组联合)/ properties / required / items / * enum / additionalProperties:false / minItems / maxItems / minimum / maximum / * nullable。**不支持**的关键字一律**忽略**(宽松),不报错 —— 校验器的职责是 * 挡住畸形输出,不是当规范警察;误伤一个合法产出的代价比放过一个边角约束大。 * ============================================================ */ export interface JsonSchema { type?: string | string[]; properties?: Record; required?: string[]; items?: JsonSchema; enum?: unknown[]; additionalProperties?: boolean | JsonSchema; minItems?: number; maxItems?: number; minimum?: number; maximum?: number; nullable?: boolean; [k: string]: unknown; } /** 校验失败的具体位置与原因(要拿去喂模型,所以必须是人话 + 路径)。 */ export interface SchemaViolation { path: string; message: string; } function typeOf(v: unknown): string { if (v === null) return 'null'; if (Array.isArray(v)) return 'array'; if (Number.isInteger(v)) return 'integer'; return typeof v; } /** `integer` 也满足 `number`;其余按 typeof 对齐。 */ function typeMatches(want: string, v: unknown): boolean { const actual = typeOf(v); if (want === actual) return true; if (want === 'number') return actual === 'integer' || actual === 'number'; if (want === 'integer') return actual === 'integer'; return false; } function describe(v: unknown): string { const t = typeOf(v); if (t === 'string') return `string(${JSON.stringify(String(v)).slice(0, 40)})`; if (t === 'array') return `array(长度 ${(v as unknown[]).length})`; if (t === 'object') return `object(键 ${Object.keys(v as object).join('/')})`; return `${t}(${String(v)})`; } function walk( value: unknown, schema: JsonSchema, path: string, out: SchemaViolation[], ): void { if (!schema || typeof schema !== 'object') return; if (value === null && schema.nullable === true) return; if (schema.enum && Array.isArray(schema.enum)) { if (!schema.enum.some((e) => e === value)) { out.push({ path, message: `应为 [${schema.enum.map((e) => JSON.stringify(e)).join(', ')}] 之一,实际是 ${describe(value)}`, }); return; } } if (schema.type !== undefined) { const wants = Array.isArray(schema.type) ? schema.type : [schema.type]; if (!wants.some((w) => typeMatches(w, value))) { out.push({ path, message: `应为 ${wants.join(' 或 ')},实际是 ${describe(value)}`, }); return; // 类型都不对,再查下去只会刷屏 } } const t = typeOf(value); if (t === 'object') { const obj = value as Record; for (const key of schema.required ?? []) { if (!(key in obj)) { out.push({ path: path ? `${path}.${key}` : key, message: '缺少必填字段' }); } } if (schema.properties) { for (const [key, sub] of Object.entries(schema.properties)) { if (key in obj) walk(obj[key], sub, path ? `${path}.${key}` : key, out); } if (schema.additionalProperties === false) { for (const key of Object.keys(obj)) { if (!(key in schema.properties)) { out.push({ path: path ? `${path}.${key}` : key, message: '不允许的额外字段', }); } } } } } if (t === 'array') { const arr = value as unknown[]; if (typeof schema.minItems === 'number' && arr.length < schema.minItems) { out.push({ path, message: `至少要 ${schema.minItems} 项,实际 ${arr.length} 项` }); } if (typeof schema.maxItems === 'number' && arr.length > schema.maxItems) { out.push({ path, message: `最多 ${schema.maxItems} 项,实际 ${arr.length} 项` }); } if (schema.items) { arr.forEach((el, i) => walk(el, schema.items!, `${path}[${i}]`, out)); } } if (t === 'number' || t === 'integer') { const n = value as number; if (typeof schema.minimum === 'number' && n < schema.minimum) { out.push({ path, message: `不得小于 ${schema.minimum},实际 ${n}` }); } if (typeof schema.maximum === 'number' && n > schema.maximum) { out.push({ path, message: `不得大于 ${schema.maximum},实际 ${n}` }); } } } /** 校验一个值。返回空数组 = 通过。 */ export function validateAgainstSchema( value: unknown, schema: JsonSchema, ): SchemaViolation[] { const out: SchemaViolation[] = []; walk(value, schema, '', out); return out; } /** 把违规列表渲染成给**模型**看的修复指令(不是给人看的报错)。 */ export function renderViolations(violations: SchemaViolation[]): string { return violations .slice(0, 20) .map((v) => ` · ${v.path || '(根)'}:${v.message}`) .join('\n'); }