@agentsmarket/pipeline-runtime 0.5.0 → 0.5.2

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 (88) hide show
  1. package/README.md +86 -1
  2. package/dist/adapters/minimax.d.ts +16 -8
  3. package/dist/adapters/minimax.js +105 -26
  4. package/dist/adapters/multimodal-convert.d.ts +54 -0
  5. package/dist/adapters/multimodal-convert.js +105 -0
  6. package/dist/adapters/openrouter.d.ts +5 -0
  7. package/dist/adapters/openrouter.js +53 -6
  8. package/dist/index.d.ts +20 -4
  9. package/dist/index.js +15 -3
  10. package/dist/loop.d.ts +90 -0
  11. package/dist/loop.js +200 -0
  12. package/dist/memory.d.ts +73 -0
  13. package/dist/memory.js +119 -0
  14. package/dist/model-resolver.d.ts +52 -1
  15. package/dist/multimodal.d.ts +43 -0
  16. package/dist/multimodal.js +23 -0
  17. package/dist/output-errors.d.ts +93 -0
  18. package/dist/output-errors.js +128 -0
  19. package/dist/output-schema-validate.d.ts +10 -0
  20. package/dist/output-schema-validate.js +149 -0
  21. package/dist/output-schema.d.ts +66 -0
  22. package/dist/output-schema.js +141 -0
  23. package/dist/pipeline-refs.d.ts +15 -0
  24. package/dist/pipeline-refs.js +155 -0
  25. package/dist/provider-registry.d.ts +22 -1
  26. package/dist/provider-registry.js +62 -2
  27. package/dist/providers/anthropic.d.ts +28 -0
  28. package/dist/providers/anthropic.js +118 -0
  29. package/dist/providers/openai-chat.d.ts +28 -0
  30. package/dist/providers/openai-chat.js +106 -0
  31. package/dist/providers/openai-dalle.d.ts +19 -0
  32. package/dist/providers/openai-dalle.js +41 -0
  33. package/dist/providers/openai-tts.d.ts +19 -0
  34. package/dist/providers/openai-tts.js +46 -0
  35. package/dist/providers/openai-vision.d.ts +15 -0
  36. package/dist/providers/openai-vision.js +43 -0
  37. package/dist/providers/openai-whisper.d.ts +16 -0
  38. package/dist/providers/openai-whisper.js +43 -0
  39. package/dist/providers/replicate.d.ts +19 -0
  40. package/dist/providers/replicate.js +61 -0
  41. package/dist/providers/types.d.ts +23 -0
  42. package/dist/providers/types.js +31 -0
  43. package/dist/runtime-constraints.d.ts +2 -1
  44. package/dist/stages.d.ts +14 -2
  45. package/dist/stages.js +339 -34
  46. package/dist/streaming-events.d.ts +17 -2
  47. package/dist/streaming-events.js +12 -0
  48. package/dist/testing/assertions.d.ts +17 -0
  49. package/dist/testing/assertions.js +149 -0
  50. package/dist/testing/conformance.d.ts +3 -0
  51. package/dist/testing/conformance.js +28 -0
  52. package/dist/testing/coverage.d.ts +11 -0
  53. package/dist/testing/coverage.js +35 -0
  54. package/dist/testing/index.d.ts +9 -0
  55. package/dist/testing/index.js +9 -0
  56. package/dist/testing/reporters/json.d.ts +5 -0
  57. package/dist/testing/reporters/json.js +23 -0
  58. package/dist/testing/reporters/junit.d.ts +5 -0
  59. package/dist/testing/reporters/junit.js +31 -0
  60. package/dist/testing/reporters/text.d.ts +5 -0
  61. package/dist/testing/reporters/text.js +36 -0
  62. package/dist/testing/runner.d.ts +25 -0
  63. package/dist/testing/runner.js +222 -0
  64. package/dist/testing/spec-parser.d.ts +366 -0
  65. package/dist/testing/spec-parser.js +60 -0
  66. package/dist/testing/stage-extractor.d.ts +16 -0
  67. package/dist/testing/stage-extractor.js +25 -0
  68. package/dist/tools/audio-transcribe.d.ts +11 -0
  69. package/dist/tools/audio-transcribe.js +45 -0
  70. package/dist/tools/image-describe.d.ts +12 -0
  71. package/dist/tools/image-describe.js +47 -0
  72. package/dist/tools/image-generate.d.ts +12 -0
  73. package/dist/tools/image-generate.js +47 -0
  74. package/dist/tools/memory-recall.d.ts +13 -0
  75. package/dist/tools/memory-recall.js +63 -0
  76. package/dist/tools/memory-shared.d.ts +8 -0
  77. package/dist/tools/memory-shared.js +8 -0
  78. package/dist/tools/memory-store.d.ts +14 -0
  79. package/dist/tools/memory-store.js +68 -0
  80. package/dist/tools/tool-skills.js +14 -0
  81. package/dist/tools/tts-synthesize.d.ts +12 -0
  82. package/dist/tools/tts-synthesize.js +50 -0
  83. package/dist/tools/video-generate.d.ts +12 -0
  84. package/dist/tools/video-generate.js +47 -0
  85. package/dist/types.d.ts +8 -0
  86. package/dist/validate-inputs.d.ts +115 -0
  87. package/dist/validate-inputs.js +273 -0
  88. package/package.json +3 -3
@@ -0,0 +1,93 @@
1
+ /**
2
+ * M5 — Output validation error + retry mode primitives.
3
+ *
4
+ * OutputValidationError is thrown by `runPipelineV2` after the configured
5
+ * retry budget (none|single|loop) is exhausted. The server route
6
+ * `packages/server/src/routes/pipelines/invoke.ts` catches it and
7
+ * surfaces a structured HTTP 500 envelope (see PIPELINE.md §"Stage
8
+ * output validation (M5)").
9
+ *
10
+ * `rawOutput` (added M-diagnostics): the truncated text the model emitted
11
+ * on the final attempt, so the server side can persist the actual model
12
+ * response next to `failure_reason` instead of forcing operators to
13
+ * reverse-engineer whether the LLM emitted JSON, a JSON-in-quotes string,
14
+ * or a prose block — that is the breadcrumb that makes
15
+ * `$: expected type object, got string` actionable in one glance.
16
+ *
17
+ * The `truncatedChars` counter tells the server how many characters were
18
+ * dropped from the middle: callers that already know the model wasn't
19
+ * truncated benefit from the exact size; callers that only have the
20
+ * stored envelope can show `[...truncated N chars...]` without guessing.
21
+ */
22
+ import type { OutputValidationViolation } from './output-schema.js';
23
+ /**
24
+ * Maximum total characters of the model output we will keep on a single
25
+ * failed run. The total budget is split evenly between the head (often
26
+ * contains the LLM's prose preamble, the opening quote, or the start of
27
+ * a JSON block) and the tail (often contains the trailing garbage, the
28
+ * cropped close brace, or the explanation the model tacked on after
29
+ * closing the JSON). 3000 chars is enough to capture both ends of any
30
+ * realistic validation-failure diagnostic while keeping the persisted
31
+ * row well under the 4 KB cap of cheap D1/SQLite TEXT indexing and a
32
+ * comfortable headroom for surrounding envelope JSON.
33
+ *
34
+ * Rationale (3000 vs the 2000–4000 range the brief considered):
35
+ * - 2000 is too tight once the model answers with a one-paragraph
36
+ * apology + a 1 KB payload + a stray trailing comma. We have seen
37
+ * those in prod; trimming at 2000 eats one of the two edges every
38
+ * time.
39
+ * - 4000 starts to leak tens of KBs of large nested arrays that the
40
+ * validator never reached, into a column that is mirrored by
41
+ * receipts and page-rendering paths.
42
+ * - 3000 is the cautious middle: enough room for the diagnostic, far
43
+ * below the small-text ceiling of every consumer that parses
44
+ * `output_json` back into JSON.
45
+ */
46
+ export declare const MAX_RAW_OUTPUT_CHARS = 3000;
47
+ export interface TruncatedRawOutput {
48
+ /** Kept head of the model output (always present, never empty). */
49
+ readonly head: string;
50
+ /** Kept tail of the model output. Empty when the original was shorter than HEAD_CHARS. */
51
+ readonly tail: string;
52
+ /** Number of characters dropped from the middle, 0 when not truncated. */
53
+ readonly truncatedChars: number;
54
+ }
55
+ /**
56
+ * Truncate model output while preserving both ends. Used by
57
+ * `OutputValidationError` to carry a bounded diagnostic with the
58
+ * failure — a 50 KB LLM response is collapsed to a few KB without
59
+ * losing the opening quote, the closing brace, or anything in
60
+ * between that mattered for the validation failure.
61
+ *
62
+ * When the input is shorter than `MAX_RAW_OUTPUT_CHARS`, the head
63
+ * contains the entire input and the tail is empty (and
64
+ * `truncatedChars` is 0).
65
+ */
66
+ export declare function truncateRawOutput(text: string): TruncatedRawOutput;
67
+ /** Build the canonical truncation marker with the dropped count baked in. */
68
+ export declare function formatTruncatedRawOutput(t: TruncatedRawOutput): string;
69
+ export declare class OutputValidationError extends Error {
70
+ readonly stageId: string;
71
+ readonly attempt: number;
72
+ readonly violations: OutputValidationViolation[];
73
+ readonly lastError: string;
74
+ /**
75
+ * Bounded raw model output that failed validation. `undefined` when
76
+ * the throw site had no text to attach (e.g. a malformed schema
77
+ * detected before any LLM call). When present, `rawOutput` is at
78
+ * most `MAX_RAW_OUTPUT_CHARS` characters, may include a
79
+ * `[...truncated N chars...]` marker in the middle, and is the
80
+ * single source of truth for "what did the model actually return".
81
+ */
82
+ readonly rawOutput?: string;
83
+ /**
84
+ * Character count dropped from the middle of `rawOutput`. Pair with
85
+ * `rawOutput` so consumers can show "kept N of M" without re-walking
86
+ * the marker. `undefined` exactly when `rawOutput` is undefined.
87
+ */
88
+ readonly truncatedChars?: number;
89
+ constructor(stageId: string, attempt: number, violations: OutputValidationViolation[], rawOutput?: string, truncatedChars?: number);
90
+ }
91
+ export type OutputValidationMode = 'none' | 'single' | 'loop';
92
+ export declare const OUTPUT_VALIDATION_RETRY_ATTEMPTS: Record<OutputValidationMode, number>;
93
+ export declare function isOutputValidationMode(value: unknown): value is OutputValidationMode;
@@ -0,0 +1,128 @@
1
+ /**
2
+ * M5 — Output validation error + retry mode primitives.
3
+ *
4
+ * OutputValidationError is thrown by `runPipelineV2` after the configured
5
+ * retry budget (none|single|loop) is exhausted. The server route
6
+ * `packages/server/src/routes/pipelines/invoke.ts` catches it and
7
+ * surfaces a structured HTTP 500 envelope (see PIPELINE.md §"Stage
8
+ * output validation (M5)").
9
+ *
10
+ * `rawOutput` (added M-diagnostics): the truncated text the model emitted
11
+ * on the final attempt, so the server side can persist the actual model
12
+ * response next to `failure_reason` instead of forcing operators to
13
+ * reverse-engineer whether the LLM emitted JSON, a JSON-in-quotes string,
14
+ * or a prose block — that is the breadcrumb that makes
15
+ * `$: expected type object, got string` actionable in one glance.
16
+ *
17
+ * The `truncatedChars` counter tells the server how many characters were
18
+ * dropped from the middle: callers that already know the model wasn't
19
+ * truncated benefit from the exact size; callers that only have the
20
+ * stored envelope can show `[...truncated N chars...]` without guessing.
21
+ */
22
+ /**
23
+ * Maximum total characters of the model output we will keep on a single
24
+ * failed run. The total budget is split evenly between the head (often
25
+ * contains the LLM's prose preamble, the opening quote, or the start of
26
+ * a JSON block) and the tail (often contains the trailing garbage, the
27
+ * cropped close brace, or the explanation the model tacked on after
28
+ * closing the JSON). 3000 chars is enough to capture both ends of any
29
+ * realistic validation-failure diagnostic while keeping the persisted
30
+ * row well under the 4 KB cap of cheap D1/SQLite TEXT indexing and a
31
+ * comfortable headroom for surrounding envelope JSON.
32
+ *
33
+ * Rationale (3000 vs the 2000–4000 range the brief considered):
34
+ * - 2000 is too tight once the model answers with a one-paragraph
35
+ * apology + a 1 KB payload + a stray trailing comma. We have seen
36
+ * those in prod; trimming at 2000 eats one of the two edges every
37
+ * time.
38
+ * - 4000 starts to leak tens of KBs of large nested arrays that the
39
+ * validator never reached, into a column that is mirrored by
40
+ * receipts and page-rendering paths.
41
+ * - 3000 is the cautious middle: enough room for the diagnostic, far
42
+ * below the small-text ceiling of every consumer that parses
43
+ * `output_json` back into JSON.
44
+ */
45
+ export const MAX_RAW_OUTPUT_CHARS = 3000;
46
+ const HEAD_CHARS = Math.floor(MAX_RAW_OUTPUT_CHARS / 2);
47
+ const TAIL_CHARS = MAX_RAW_OUTPUT_CHARS - HEAD_CHARS;
48
+ /**
49
+ * Marker inserted between the kept head and kept tail when truncation
50
+ * occurs. Keeps the ellipsis count so the envelope is self-describing
51
+ * even without `truncatedChars` (e.g. when surfaced through a route
52
+ * that flattens the JSON).
53
+ */
54
+ const TRUNCATION_MARKER = '\n\n[...truncated {N} chars of middle...]\n\n';
55
+ /**
56
+ * Truncate model output while preserving both ends. Used by
57
+ * `OutputValidationError` to carry a bounded diagnostic with the
58
+ * failure — a 50 KB LLM response is collapsed to a few KB without
59
+ * losing the opening quote, the closing brace, or anything in
60
+ * between that mattered for the validation failure.
61
+ *
62
+ * When the input is shorter than `MAX_RAW_OUTPUT_CHARS`, the head
63
+ * contains the entire input and the tail is empty (and
64
+ * `truncatedChars` is 0).
65
+ */
66
+ export function truncateRawOutput(text) {
67
+ if (typeof text !== 'string') {
68
+ return { head: '', tail: '', truncatedChars: 0 };
69
+ }
70
+ if (text.length <= MAX_RAW_OUTPUT_CHARS) {
71
+ return { head: text, tail: '', truncatedChars: 0 };
72
+ }
73
+ const truncatedChars = text.length - HEAD_CHARS - TAIL_CHARS;
74
+ const head = text.slice(0, HEAD_CHARS);
75
+ const tail = text.slice(text.length - TAIL_CHARS);
76
+ return { head, tail, truncatedChars };
77
+ }
78
+ /** Build the canonical truncation marker with the dropped count baked in. */
79
+ export function formatTruncatedRawOutput(t) {
80
+ if (t.truncatedChars <= 0)
81
+ return t.head;
82
+ const marker = TRUNCATION_MARKER.replace('{N}', String(t.truncatedChars));
83
+ return t.head + marker + t.tail;
84
+ }
85
+ export class OutputValidationError extends Error {
86
+ stageId;
87
+ attempt;
88
+ violations;
89
+ lastError;
90
+ /**
91
+ * Bounded raw model output that failed validation. `undefined` when
92
+ * the throw site had no text to attach (e.g. a malformed schema
93
+ * detected before any LLM call). When present, `rawOutput` is at
94
+ * most `MAX_RAW_OUTPUT_CHARS` characters, may include a
95
+ * `[...truncated N chars...]` marker in the middle, and is the
96
+ * single source of truth for "what did the model actually return".
97
+ */
98
+ rawOutput;
99
+ /**
100
+ * Character count dropped from the middle of `rawOutput`. Pair with
101
+ * `rawOutput` so consumers can show "kept N of M" without re-walking
102
+ * the marker. `undefined` exactly when `rawOutput` is undefined.
103
+ */
104
+ truncatedChars;
105
+ constructor(stageId, attempt, violations, rawOutput, truncatedChars) {
106
+ const summary = violations.length > 0
107
+ ? violations.map((v) => `${v.path}: ${v.message}`).join('; ')
108
+ : 'unknown validation failure';
109
+ super(`Output validation failed for stage '${stageId}' after ${attempt} attempt(s): ${summary}`);
110
+ this.name = 'OUTPUT_VALIDATION_FAILED';
111
+ this.stageId = stageId;
112
+ this.attempt = attempt;
113
+ this.violations = violations;
114
+ this.lastError = summary;
115
+ if (rawOutput !== undefined) {
116
+ this.rawOutput = rawOutput;
117
+ this.truncatedChars = truncatedChars ?? 0;
118
+ }
119
+ }
120
+ }
121
+ export const OUTPUT_VALIDATION_RETRY_ATTEMPTS = {
122
+ none: 1,
123
+ single: 2,
124
+ loop: 3,
125
+ };
126
+ export function isOutputValidationMode(value) {
127
+ return value === 'none' || value === 'single' || value === 'loop';
128
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * M5 — Runtime JSON Schema validator.
3
+ *
4
+ * Walks `value` against `schema` collecting `OutputValidationViolation`
5
+ * entries. Recursion is bounded by `MAX_VALIDATION_DEPTH` (32) defined
6
+ * in `./output-schema.ts`. Pure function — no side effects, safe to call
7
+ * from any environment (Workers, Node, browser).
8
+ */
9
+ import { type JsonSchema, type OutputValidationViolation } from './output-schema.js';
10
+ export declare function validateAgainstSchema(value: unknown, schema: JsonSchema, path?: string, schemaPath?: string, depth?: number): OutputValidationViolation[];
@@ -0,0 +1,149 @@
1
+ /**
2
+ * M5 — Runtime JSON Schema validator.
3
+ *
4
+ * Walks `value` against `schema` collecting `OutputValidationViolation`
5
+ * entries. Recursion is bounded by `MAX_VALIDATION_DEPTH` (32) defined
6
+ * in `./output-schema.ts`. Pure function — no side effects, safe to call
7
+ * from any environment (Workers, Node, browser).
8
+ */
9
+ import { MAX_VALIDATION_DEPTH, deepEqual, isPlainObject, jsonTypeOf, typeMatches, } from './output-schema.js';
10
+ export function validateAgainstSchema(value, schema, path = '$', schemaPath = '$', depth = 0) {
11
+ if (depth > MAX_VALIDATION_DEPTH) {
12
+ return [{
13
+ path,
14
+ message: `schema nesting exceeds MAX_VALIDATION_DEPTH (${MAX_VALIDATION_DEPTH})`,
15
+ schema_path: schemaPath,
16
+ }];
17
+ }
18
+ const violations = [];
19
+ if (schema.enum !== undefined) {
20
+ if (!schema.enum.some((v) => deepEqual(v, value))) {
21
+ violations.push({
22
+ path,
23
+ message: `value is not one of the allowed enum values`,
24
+ schema_path: `${schemaPath}.enum`,
25
+ });
26
+ }
27
+ return violations;
28
+ }
29
+ if (schema.type !== undefined) {
30
+ const expected = Array.isArray(schema.type) ? schema.type : [schema.type];
31
+ const actual = jsonTypeOf(value);
32
+ const isMatch = expected.some((t) => typeMatches(t, actual, value));
33
+ if (!isMatch) {
34
+ violations.push({
35
+ path,
36
+ message: `expected type ${expected.join(' | ')}, got ${actual}`,
37
+ schema_path: `${schemaPath}.type`,
38
+ });
39
+ return violations;
40
+ }
41
+ }
42
+ if (typeof value === 'string') {
43
+ checkStringConstraints(value, schema, path, schemaPath, violations);
44
+ }
45
+ if (Array.isArray(value)) {
46
+ checkArrayConstraints(value, schema, path, schemaPath, depth, violations);
47
+ }
48
+ if (isPlainObject(value)) {
49
+ checkObjectConstraints(value, schema, path, schemaPath, depth, violations);
50
+ }
51
+ return violations;
52
+ }
53
+ function checkStringConstraints(value, schema, path, schemaPath, violations) {
54
+ if (schema.minLength !== undefined && value.length < schema.minLength) {
55
+ violations.push({
56
+ path,
57
+ message: `string length ${value.length} is less than minLength ${schema.minLength}`,
58
+ schema_path: `${schemaPath}.minLength`,
59
+ });
60
+ }
61
+ if (schema.maxLength !== undefined && value.length > schema.maxLength) {
62
+ violations.push({
63
+ path,
64
+ message: `string length ${value.length} exceeds maxLength ${schema.maxLength}`,
65
+ schema_path: `${schemaPath}.maxLength`,
66
+ });
67
+ }
68
+ if (schema.pattern !== undefined) {
69
+ try {
70
+ const re = new RegExp(schema.pattern);
71
+ if (!re.test(value)) {
72
+ violations.push({
73
+ path,
74
+ message: `string does not match pattern /${schema.pattern}/`,
75
+ schema_path: `${schemaPath}.pattern`,
76
+ });
77
+ }
78
+ }
79
+ catch {
80
+ violations.push({
81
+ path,
82
+ message: `pattern /${schema.pattern}/ is not a valid regular expression`,
83
+ schema_path: `${schemaPath}.pattern`,
84
+ });
85
+ }
86
+ }
87
+ }
88
+ function checkArrayConstraints(value, schema, path, schemaPath, depth, violations) {
89
+ if (schema.minItems !== undefined && value.length < schema.minItems) {
90
+ violations.push({
91
+ path,
92
+ message: `array length ${value.length} is less than minItems ${schema.minItems}`,
93
+ schema_path: `${schemaPath}.minItems`,
94
+ });
95
+ }
96
+ if (schema.maxItems !== undefined && value.length > schema.maxItems) {
97
+ violations.push({
98
+ path,
99
+ message: `array length ${value.length} exceeds maxItems ${schema.maxItems}`,
100
+ schema_path: `${schemaPath}.maxItems`,
101
+ });
102
+ }
103
+ if (schema.items !== undefined) {
104
+ for (let i = 0; i < value.length; i++) {
105
+ violations.push(...validateAgainstSchema(value[i], schema.items, `${path}[${i}]`, `${schemaPath}.items`, depth + 1));
106
+ }
107
+ }
108
+ }
109
+ function checkObjectConstraints(value, schema, path, schemaPath, depth, violations) {
110
+ if (schema.required !== undefined) {
111
+ for (const key of schema.required) {
112
+ if (!(key in value)) {
113
+ violations.push({
114
+ path,
115
+ message: `missing required property '${key}'`,
116
+ schema_path: `${schemaPath}.required`,
117
+ });
118
+ }
119
+ }
120
+ }
121
+ if (schema.properties !== undefined) {
122
+ for (const [key, childSchema] of Object.entries(schema.properties)) {
123
+ if (key in value) {
124
+ violations.push(...validateAgainstSchema(value[key], childSchema, `${path}.${key}`, `${schemaPath}.properties.${key}`, depth + 1));
125
+ }
126
+ }
127
+ }
128
+ if (schema.additionalProperties === false && schema.properties !== undefined) {
129
+ const allowed = new Set(Object.keys(schema.properties));
130
+ for (const key of Object.keys(value)) {
131
+ if (!allowed.has(key)) {
132
+ violations.push({
133
+ path,
134
+ message: `additional property '${key}' is not allowed`,
135
+ schema_path: `${schemaPath}.additionalProperties`,
136
+ });
137
+ }
138
+ }
139
+ }
140
+ else if (typeof schema.additionalProperties === 'object' &&
141
+ schema.additionalProperties !== null) {
142
+ const allowed = new Set(Object.keys(schema.properties ?? {}));
143
+ for (const key of Object.keys(value)) {
144
+ if (!allowed.has(key)) {
145
+ violations.push(...validateAgainstSchema(value[key], schema.additionalProperties, `${path}.${key}`, `${schemaPath}.additionalProperties`, depth + 1));
146
+ }
147
+ }
148
+ }
149
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * M5 — Stage output schema types and meta-validation.
3
+ *
4
+ * Per-stage `output_schema` block constrains the executor's string output.
5
+ * Companion field `output_retry` (none|single|loop) decides what happens
6
+ * when validation fails. The runtime validator lives in
7
+ * `./output-schema-validate.ts`; this file owns the type definitions and
8
+ * the meta-validation step (catches `$ref`/etc. on parse).
9
+ *
10
+ * Supported keywords (subset):
11
+ * type — string | number | integer | boolean | array | object | null
12
+ * properties — Record<string, JsonSchema> for object validation
13
+ * required — string[] of required keys
14
+ * additionalProperties — boolean | JsonSchema (default true)
15
+ * enum — exact value match
16
+ * items — JsonSchema for array element validation
17
+ * minItems / maxItems — array length bounds
18
+ * minLength / maxLength — string length bounds
19
+ * pattern — regex string (matches whole value)
20
+ * format — informational only; not validated
21
+ *
22
+ * NOT supported (fail-fast on schema parse):
23
+ * $ref, definitions, $defs, allOf, anyOf, oneOf, not, dependencies, propertyNames
24
+ */
25
+ export type JsonSchemaType = 'string' | 'number' | 'integer' | 'boolean' | 'array' | 'object' | 'null';
26
+ export interface JsonSchema {
27
+ type?: JsonSchemaType | JsonSchemaType[];
28
+ properties?: Record<string, JsonSchema>;
29
+ required?: string[];
30
+ additionalProperties?: boolean | JsonSchema;
31
+ enum?: unknown[];
32
+ items?: JsonSchema;
33
+ minItems?: number;
34
+ maxItems?: number;
35
+ minLength?: number;
36
+ maxLength?: number;
37
+ pattern?: string;
38
+ format?: string;
39
+ }
40
+ export interface OutputValidationViolation {
41
+ /** JSON pointer into the value, e.g. "$", "$.items[0].name". */
42
+ path: string;
43
+ /** Human-readable explanation of the violation. */
44
+ message: string;
45
+ /** JSON pointer into the schema, e.g. "$.required", "$.properties.name.type". */
46
+ schema_path: string;
47
+ }
48
+ export interface OutputValidationResult {
49
+ ok: boolean;
50
+ violations: OutputValidationViolation[];
51
+ }
52
+ /** Max recursion depth for nested object/array schemas. */
53
+ export declare const MAX_VALIDATION_DEPTH = 32;
54
+ /**
55
+ * Validate the schema definition itself (meta-validation). Returns a
56
+ * non-empty violations list when the schema declares unsupported
57
+ * keywords (e.g. `$ref`) or is malformed. Schema is allowed to be
58
+ * `undefined`/`null` → returns `{ok: true}` so callers can use it as a
59
+ * permissive pre-check before wiring it into runtime validation.
60
+ */
61
+ export declare function validateJsonSchema(raw: unknown): OutputValidationResult;
62
+ /** Shared helpers used by output-schema-validate.ts. */
63
+ export declare function jsonTypeOf(value: unknown): JsonSchemaType;
64
+ export declare function typeMatches(expected: JsonSchemaType, actual: JsonSchemaType, _value: unknown): boolean;
65
+ export declare function deepEqual(a: unknown, b: unknown): boolean;
66
+ export declare function isPlainObject(value: unknown): value is Record<string, unknown>;
@@ -0,0 +1,141 @@
1
+ /**
2
+ * M5 — Stage output schema types and meta-validation.
3
+ *
4
+ * Per-stage `output_schema` block constrains the executor's string output.
5
+ * Companion field `output_retry` (none|single|loop) decides what happens
6
+ * when validation fails. The runtime validator lives in
7
+ * `./output-schema-validate.ts`; this file owns the type definitions and
8
+ * the meta-validation step (catches `$ref`/etc. on parse).
9
+ *
10
+ * Supported keywords (subset):
11
+ * type — string | number | integer | boolean | array | object | null
12
+ * properties — Record<string, JsonSchema> for object validation
13
+ * required — string[] of required keys
14
+ * additionalProperties — boolean | JsonSchema (default true)
15
+ * enum — exact value match
16
+ * items — JsonSchema for array element validation
17
+ * minItems / maxItems — array length bounds
18
+ * minLength / maxLength — string length bounds
19
+ * pattern — regex string (matches whole value)
20
+ * format — informational only; not validated
21
+ *
22
+ * NOT supported (fail-fast on schema parse):
23
+ * $ref, definitions, $defs, allOf, anyOf, oneOf, not, dependencies, propertyNames
24
+ */
25
+ /** Max recursion depth for nested object/array schemas. */
26
+ export const MAX_VALIDATION_DEPTH = 32;
27
+ const UNSUPPORTED_KEYWORDS = new Set([
28
+ '$ref', 'definitions', '$defs', 'allOf', 'anyOf', 'oneOf',
29
+ 'not', 'dependencies', 'propertyNames',
30
+ ]);
31
+ /**
32
+ * Validate the schema definition itself (meta-validation). Returns a
33
+ * non-empty violations list when the schema declares unsupported
34
+ * keywords (e.g. `$ref`) or is malformed. Schema is allowed to be
35
+ * `undefined`/`null` → returns `{ok: true}` so callers can use it as a
36
+ * permissive pre-check before wiring it into runtime validation.
37
+ */
38
+ export function validateJsonSchema(raw) {
39
+ const violations = [];
40
+ walkSchemaCheck(raw, '$', violations);
41
+ return { ok: violations.length === 0, violations };
42
+ }
43
+ function walkSchemaCheck(schema, schemaPath, violations) {
44
+ if (schema === undefined || schema === null)
45
+ return;
46
+ if (typeof schema !== 'object' || Array.isArray(schema)) {
47
+ violations.push({
48
+ path: '$',
49
+ message: `schema at ${schemaPath} must be an object`,
50
+ schema_path: schemaPath,
51
+ });
52
+ return;
53
+ }
54
+ const obj = schema;
55
+ for (const k of Object.keys(obj)) {
56
+ if (UNSUPPORTED_KEYWORDS.has(k)) {
57
+ violations.push({
58
+ path: '$',
59
+ message: `keyword '${k}' is not supported in the M5 subset validator`,
60
+ schema_path: `${schemaPath}.${k}`,
61
+ });
62
+ }
63
+ }
64
+ if (obj['properties'] !== undefined) {
65
+ const props = obj['properties'];
66
+ if (typeof props !== 'object' || props === null || Array.isArray(props)) {
67
+ violations.push({
68
+ path: '$',
69
+ message: 'properties must be an object',
70
+ schema_path: `${schemaPath}.properties`,
71
+ });
72
+ }
73
+ else {
74
+ for (const [key, child] of Object.entries(props)) {
75
+ walkSchemaCheck(child, `${schemaPath}.properties.${key}`, violations);
76
+ }
77
+ }
78
+ }
79
+ if (obj['items'] !== undefined) {
80
+ walkSchemaCheck(obj['items'], `${schemaPath}.items`, violations);
81
+ }
82
+ if (obj['additionalProperties'] !== undefined && typeof obj['additionalProperties'] === 'object') {
83
+ walkSchemaCheck(obj['additionalProperties'], `${schemaPath}.additionalProperties`, violations);
84
+ }
85
+ }
86
+ /** Shared helpers used by output-schema-validate.ts. */
87
+ export function jsonTypeOf(value) {
88
+ if (value === null)
89
+ return 'null';
90
+ if (Array.isArray(value))
91
+ return 'array';
92
+ if (typeof value === 'number') {
93
+ return Number.isInteger(value) ? 'integer' : 'number';
94
+ }
95
+ if (typeof value === 'string')
96
+ return 'string';
97
+ if (typeof value === 'boolean')
98
+ return 'boolean';
99
+ if (typeof value === 'object')
100
+ return 'object';
101
+ return 'null';
102
+ }
103
+ export function typeMatches(expected, actual, _value) {
104
+ if (expected === 'integer' && actual === 'integer')
105
+ return true;
106
+ if (expected === 'number' && (actual === 'number' || actual === 'integer'))
107
+ return true;
108
+ return expected === actual;
109
+ }
110
+ export function deepEqual(a, b) {
111
+ if (a === b)
112
+ return true;
113
+ if (typeof a !== typeof b)
114
+ return false;
115
+ if (a === null || b === null)
116
+ return a === b;
117
+ if (Array.isArray(a) && Array.isArray(b)) {
118
+ if (a.length !== b.length)
119
+ return false;
120
+ for (let i = 0; i < a.length; i++) {
121
+ if (!deepEqual(a[i], b[i]))
122
+ return false;
123
+ }
124
+ return true;
125
+ }
126
+ if (typeof a === 'object' && typeof b === 'object') {
127
+ const ak = Object.keys(a);
128
+ const bk = Object.keys(b);
129
+ if (ak.length !== bk.length)
130
+ return false;
131
+ for (const k of ak) {
132
+ if (!deepEqual(a[k], b[k]))
133
+ return false;
134
+ }
135
+ return true;
136
+ }
137
+ return false;
138
+ }
139
+ export function isPlainObject(value) {
140
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
141
+ }
@@ -32,6 +32,21 @@ export interface PipelineRefContext {
32
32
  inputs: Record<string, unknown>;
33
33
  previousOutputs: Record<string, string>;
34
34
  }
35
+ export interface DoubleBraceContext {
36
+ /** The stage's own argument block. Highest precedence for bare names. */
37
+ stageInputs: Record<string, unknown> | null;
38
+ /** Pipeline-level inputs, visible to every stage. */
39
+ pipelineInputs: Record<string, unknown>;
40
+ /** Prior stage outputs, keyed by stage id. */
41
+ previousOutputs?: Record<string, string>;
42
+ /** Reports an unresolved ref or a shadowed input. Optional. */
43
+ onWarning?: (message: string) => void;
44
+ /** @internal names whose resolution fell through to the pipeline scope. */
45
+ viaPipeline?: Set<string>;
46
+ /** @internal names currently being resolved — the cycle guard. */
47
+ visiting?: Set<string>;
48
+ }
49
+ export declare function resolveDoubleBraceRefs(value: unknown, ctx: DoubleBraceContext): unknown;
35
50
  export declare function resolveInputRefs(value: unknown, ctx: PipelineRefContext): unknown;
36
51
  /**
37
52
  * Substitute built-in special keys (\$today, \$now, \$year, \$month, \$weekday)