@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
package/dist/index.js CHANGED
@@ -5,14 +5,17 @@
5
5
  * runPipelineV2), pricing (PricingResolver), model resolver.
6
6
  */
7
7
  export { resolveProvider, StageOutputFormatError, StageSkillVersionMismatchError, StageMCPConfigError, } from './types.js';
8
+ export { MultimodalModelUnsupportedError } from './multimodal.js';
8
9
  export { MiniMaxProvider } from './adapters/minimax.js';
9
10
  export { OpenRouterProvider } from './adapters/openrouter.js';
11
+ export { OpenAIChatProvider } from './providers/openai-chat.js';
12
+ export { AnthropicProvider } from './providers/anthropic.js';
10
13
  export { FallbackProvider, createFallbackProvider } from './fallback.js';
11
- export { PROVIDER_REGISTRY, getProvider, validateProviderName, supportsModel, validateProviderModel, listProviders, listSupportedModels, validateR6Spec, migrateProviderField, ProviderSpecNotFoundError, ProviderModelMismatchError, LLMProviderRegistry, ProviderMismatchError, UnknownProviderError, } from './provider-registry.js';
14
+ export { PROVIDER_REGISTRY, getProvider, validateProviderName, supportsModel, validateProviderModel, listProviders, listSupportedModels, listVisionCapableModels, isVisionCapable, assertMultimodalSupported, validateR6Spec, migrateProviderField, ProviderSpecNotFoundError, ProviderModelMismatchError, LLMProviderRegistry, ProviderMismatchError, UnknownProviderError, } from './provider-registry.js';
12
15
  export { expandPipelineText, resolveEnvVars, resolveEnvVarsInObject, loadPipelineYaml, parseVariableSpec, MissingEnvVarError, } from './resolve-vars.js';
13
16
  export { isRetryableStatus, computeBackoffMs, RetryExhaustedError, RetryAttemptError, DEFAULT_RETRY, DEFAULT_RETRYABLE_STATUSES, } from './retry.js';
14
17
  export { parseComparison, parseWhenLiteral, evaluateComparison, evaluateWhen, shouldSkipStage, validateWhenShape, WhenParseError, } from './when.js';
15
- export { NoopEventSink, CallbackEventSink, createDefaultSink, makeStageRetriedEvent, } from './streaming-events.js';
18
+ export { NoopEventSink, CallbackEventSink, createDefaultSink, makeStageRetriedEvent, makeStageWarnedEvent, } from './streaming-events.js';
16
19
  export { validateRuntimeConstraints, collectRuntimeWarnings, defaultRuntimeConstraints, mergeRuntimeConstraints, } from './runtime-constraints.js';
17
20
  export { groupIndependentStages, topologicalSort, extractDepIds, CyclicDependencyError, } from './parallel.js';
18
21
  export { tryParsePipelineUses, resolvePipelineRef, injectNestedStages, expandComposition, COMPOSITION_USES_PREFIX, MAX_COMPOSITION_DEPTH, CompositionDepthError, PipelineFetchError, } from './composition.js';
@@ -23,9 +26,15 @@ export { createModelResolver, resolveModelSync, DEFAULT_MODEL, } from './model-r
23
26
  export { sha256Hex, computeSkillContentHash, } from './content-hash.js';
24
27
  export { executeStage, runPipelineV2, makeWhenResolve, parseUsesEntry, parseUsesList, validateOutputFormat, StageNotFoundError, StageForbiddenError, StageBadConfigError, } from './stages.js';
25
28
  export { validateInputs, formatInputErrors, } from './validate-inputs.js';
26
- export { resolveInputRefs, resolveSpecialKeys, } from './pipeline-refs.js';
29
+ export { validateMultimodalInput, } from './validate-inputs.js';
30
+ export { parseMediaUrl, detectMime, isImageMime, isAudioMime, isVideoMime, SUPPORTED_IMAGE_MIME, SUPPORTED_AUDIO_MIME, SUPPORTED_VIDEO_MIME, toAnthropicContent, } from './adapters/multimodal-convert.js';
31
+ export { resolveInputRefs, resolveSpecialKeys, resolveDoubleBraceRefs, } from './pipeline-refs.js';
27
32
  export { isToolSkill, invokeToolSkill, } from './tools/tool-skills.js';
28
33
  export { validateOutputSpec, DEFAULT_OUTPUT_FORMAT, DEFAULT_OUTPUT_DELIVERY, DEFAULT_OUTPUT_EXPIRES_IN, MIN_OUTPUT_EXPIRES_IN, MAX_OUTPUT_EXPIRES_IN, } from './output-spec.js';
34
+ export { validateJsonSchema, MAX_VALIDATION_DEPTH, } from './output-schema.js';
35
+ export { validateAgainstSchema } from './output-schema-validate.js';
36
+ export { OutputValidationError, OUTPUT_VALIDATION_RETRY_ATTEMPTS, isOutputValidationMode, } from './output-errors.js';
37
+ export { validateOutput, } from './validate-inputs.js';
29
38
  export { analyzeCapabilities, } from './capabilities.js';
30
39
  export { extractProducedFiles, globToRegex, MAX_FILE_BYTES, MAX_TOTAL_BYTES, MAX_FILES, } from './file-output.js';
31
40
  export { normalizeShellStage, ThrowingShellExecutor, NodeShellExecutor, ShellStageUnsupportedError, ShellStageExecError, ShellStageTimeoutError, SHELL_DEFAULT_TIMEOUT_MS, SHELL_MAX_TIMEOUT_MS, SHELL_MAX_OUTPUT_BYTES, } from './shell-stage.js';
@@ -66,3 +75,6 @@ export async function runPipeline(spec, inputs, opts) {
66
75
  }
67
76
  return outputs;
68
77
  }
78
+ export { LOOP_SCHEMA_VERSION, DEFAULT_MAX_ITERATIONS, ABSOLUTE_MAX_ITERATIONS, LoopConfigError, LoopMaxIterationsExceededError, parseExitExpression, evaluateExitExpression, executeLoop, } from './loop.js';
79
+ export { MEMORY_SCHEMA_VERSION, MAX_MEMORY_VALUE_BYTES, InMemoryMemoryStore, R2MemoryStore, createMemoryStore, } from './memory.js';
80
+ export { parseTestSpec, loadTestSpecFile, TestSpecParseError, runAssertion, getPath, runSingleTest, runTestSuite, mockValueForField, buildMockProvider, extractStage, StageNotFoundInSpecError, renderText, renderJson, renderJunit, computeCoverage, renderCoverageText, loadCoverageForPipeline, discoverTestFiles, runConformanceDir, } from './testing/index.js';
package/dist/loop.d.ts ADDED
@@ -0,0 +1,90 @@
1
+ /**
2
+ * M6.2 — Loop executor for pipeline stages (2026-09-25).
3
+ *
4
+ * Executes a `loop:` block that contains nested body stages. The loop
5
+ * runs body stages up to `max_iterations` times, evaluating `exit_when`
6
+ * after each iteration. Iteration state (counter + previous outputs) is
7
+ * persisted via the memory primitives (M6.1) so callers can introspect.
8
+ *
9
+ * Expression grammar (deliberately small for safety — no eval):
10
+ * `outputs.KEY OP VALUE`
11
+ * where OP is one of: `>=`, `<=`, `==`, `!=`, `>`, `<`
12
+ * VALUE may be a number, boolean, or quoted string.
13
+ *
14
+ * Example:
15
+ * loop:
16
+ * max_iterations: 5
17
+ * exit_when: "outputs.quality_score >= 0.9"
18
+ * body:
19
+ * - id: generate
20
+ * provider: minimax
21
+ * model: MiniMax-M3
22
+ * prompt: "..."
23
+ * - id: score
24
+ * provider: minimax
25
+ * model: MiniMax-M3
26
+ * output_schema: { ... }
27
+ */
28
+ import type { MemoryStore } from './memory.js';
29
+ export declare const LOOP_SCHEMA_VERSION = 1;
30
+ export declare const DEFAULT_MAX_ITERATIONS = 3;
31
+ export declare const ABSOLUTE_MAX_ITERATIONS = 10;
32
+ export type LoopOperator = '>=' | '<=' | '==' | '!=' | '>' | '<';
33
+ export interface LoopExitExpression {
34
+ outputs_key: string;
35
+ operator: LoopOperator;
36
+ value: number | boolean | string;
37
+ }
38
+ export interface LoopSpec {
39
+ max_iterations?: number;
40
+ exit_when?: LoopExitExpression;
41
+ body: ReadonlyArray<Record<string, unknown>>;
42
+ }
43
+ export interface LoopIteration {
44
+ iteration: number;
45
+ outputs: Record<string, unknown>;
46
+ cost_micro_usdc: number;
47
+ duration_ms: number;
48
+ exit_evaluated: boolean | null;
49
+ exited: boolean | null;
50
+ }
51
+ export interface LoopTrace {
52
+ schema_version: typeof LOOP_SCHEMA_VERSION;
53
+ loop_id: string;
54
+ pipeline_id: string;
55
+ max_iterations: number;
56
+ total_iterations: number;
57
+ exited_by: 'exit_when' | 'max_iterations' | 'error';
58
+ final_outputs: Record<string, unknown>;
59
+ total_cost_micro_usdc: number;
60
+ iterations: LoopIteration[];
61
+ }
62
+ export declare class LoopConfigError extends Error {
63
+ constructor(message: string);
64
+ }
65
+ export declare class LoopMaxIterationsExceededError extends Error {
66
+ readonly loop_id: string;
67
+ readonly max: number;
68
+ constructor(loop_id: string, max: number);
69
+ }
70
+ export declare function parseExitExpression(expr: string): LoopExitExpression;
71
+ export declare function evaluateExitExpression(outputs: Record<string, unknown>, expr: LoopExitExpression): boolean;
72
+ export interface LoopExecutor {
73
+ trace: LoopTrace;
74
+ }
75
+ export interface RunBodyStage {
76
+ (bodyStage: Record<string, unknown>, iteration: number, previousOutputs: Record<string, unknown>): Promise<{
77
+ outputs: Record<string, unknown>;
78
+ cost_micro_usdc: number;
79
+ duration_ms: number;
80
+ }>;
81
+ }
82
+ export interface LoopExecutionOptions {
83
+ loop_id: string;
84
+ pipeline_id: string;
85
+ spec: LoopSpec;
86
+ memory: MemoryStore | null;
87
+ runBodyStage: RunBodyStage;
88
+ iteration_inputs_for?: (iteration: number, prev: Record<string, unknown>) => Record<string, unknown>;
89
+ }
90
+ export declare function executeLoop(opts: LoopExecutionOptions): Promise<LoopExecutor>;
package/dist/loop.js ADDED
@@ -0,0 +1,200 @@
1
+ /**
2
+ * M6.2 — Loop executor for pipeline stages (2026-09-25).
3
+ *
4
+ * Executes a `loop:` block that contains nested body stages. The loop
5
+ * runs body stages up to `max_iterations` times, evaluating `exit_when`
6
+ * after each iteration. Iteration state (counter + previous outputs) is
7
+ * persisted via the memory primitives (M6.1) so callers can introspect.
8
+ *
9
+ * Expression grammar (deliberately small for safety — no eval):
10
+ * `outputs.KEY OP VALUE`
11
+ * where OP is one of: `>=`, `<=`, `==`, `!=`, `>`, `<`
12
+ * VALUE may be a number, boolean, or quoted string.
13
+ *
14
+ * Example:
15
+ * loop:
16
+ * max_iterations: 5
17
+ * exit_when: "outputs.quality_score >= 0.9"
18
+ * body:
19
+ * - id: generate
20
+ * provider: minimax
21
+ * model: MiniMax-M3
22
+ * prompt: "..."
23
+ * - id: score
24
+ * provider: minimax
25
+ * model: MiniMax-M3
26
+ * output_schema: { ... }
27
+ */
28
+ export const LOOP_SCHEMA_VERSION = 1;
29
+ export const DEFAULT_MAX_ITERATIONS = 3;
30
+ export const ABSOLUTE_MAX_ITERATIONS = 10;
31
+ export class LoopConfigError extends Error {
32
+ constructor(message) {
33
+ super(message);
34
+ this.name = 'LOOP_CONFIG_ERROR';
35
+ }
36
+ }
37
+ export class LoopMaxIterationsExceededError extends Error {
38
+ loop_id;
39
+ max;
40
+ constructor(loop_id, max) {
41
+ super(`Loop '${loop_id}' exceeded max_iterations=${max}`);
42
+ this.loop_id = loop_id;
43
+ this.max = max;
44
+ this.name = 'LOOP_MAX_ITERATIONS_EXCEEDED';
45
+ }
46
+ }
47
+ const OP_PATTERN = /^(>=|<=|==|!=|>|<)$/;
48
+ const EXPR_PATTERN = /^outputs\.([A-Za-z_][A-Za-z0-9_]*)\s*(>=|<=|==|!=|>|<)\s*(.+)$/;
49
+ export function parseExitExpression(expr) {
50
+ const match = EXPR_PATTERN.exec(expr.trim());
51
+ if (!match || !match[1] || !match[2] || match[3] === undefined) {
52
+ throw new LoopConfigError(`Invalid exit_when expression: '${expr}'. Expected: outputs.KEY OP VALUE (e.g., outputs.quality_score >= 0.9)`);
53
+ }
54
+ const [, outputsKey, op, rawValue] = match;
55
+ if (!outputsKey || !op || rawValue === undefined) {
56
+ throw new LoopConfigError(`Invalid exit_when expression: '${expr}'`);
57
+ }
58
+ if (!OP_PATTERN.test(op)) {
59
+ throw new LoopConfigError(`Invalid operator in exit_when: '${op}'`);
60
+ }
61
+ const value = parseLiteral(rawValue.trim());
62
+ return {
63
+ outputs_key: outputsKey,
64
+ operator: op,
65
+ value,
66
+ };
67
+ }
68
+ function parseLiteral(raw) {
69
+ if (raw === 'true')
70
+ return true;
71
+ if (raw === 'false')
72
+ return false;
73
+ if (raw === 'null')
74
+ return null;
75
+ const num = Number(raw);
76
+ if (Number.isFinite(num) && raw !== '')
77
+ return num;
78
+ if (raw.startsWith('"') && raw.endsWith('"'))
79
+ return raw.slice(1, -1);
80
+ if (raw.startsWith("'") && raw.endsWith("'"))
81
+ return raw.slice(1, -1);
82
+ return raw;
83
+ }
84
+ export function evaluateExitExpression(outputs, expr) {
85
+ const lhs = outputs[expr.outputs_key];
86
+ const rhs = expr.value;
87
+ switch (expr.operator) {
88
+ case '>=': return compare(lhs, rhs) >= 0;
89
+ case '<=': return compare(lhs, rhs) <= 0;
90
+ case '==': return looseEq(lhs, rhs);
91
+ case '!=': return !looseEq(lhs, rhs);
92
+ case '>': return compare(lhs, rhs) > 0;
93
+ case '<': return compare(lhs, rhs) < 0;
94
+ }
95
+ }
96
+ function looseEq(a, b) {
97
+ if (a === b)
98
+ return true;
99
+ if (typeof a === 'number' && typeof b === 'number')
100
+ return a === b;
101
+ if (typeof a === 'string' && typeof b === 'string')
102
+ return a === b;
103
+ if (typeof a === 'boolean' && typeof b === 'boolean')
104
+ return a === b;
105
+ return String(a) === String(b);
106
+ }
107
+ function compare(a, b) {
108
+ const na = typeof a === 'number' ? a : Number(a);
109
+ const nb = typeof b === 'number' ? b : Number(b);
110
+ if (Number.isNaN(na) || Number.isNaN(nb)) {
111
+ return -1;
112
+ }
113
+ return na - nb;
114
+ }
115
+ function flattenOutputs(iterOutputs) {
116
+ const flat = {};
117
+ for (const [stageId, stageOutput] of Object.entries(iterOutputs)) {
118
+ if (stageOutput !== null && typeof stageOutput === 'object' && !Array.isArray(stageOutput)) {
119
+ for (const [key, value] of Object.entries(stageOutput)) {
120
+ flat[key] = value;
121
+ flat[`${stageId}.${key}`] = value;
122
+ }
123
+ }
124
+ else {
125
+ flat[stageId] = stageOutput;
126
+ }
127
+ }
128
+ return flat;
129
+ }
130
+ export async function executeLoop(opts) {
131
+ const max = Math.min(Math.max(opts.spec.max_iterations ?? DEFAULT_MAX_ITERATIONS, 1), ABSOLUTE_MAX_ITERATIONS);
132
+ const expr = opts.spec.exit_when
133
+ ? typeof opts.spec.exit_when === 'string'
134
+ ? parseExitExpression(opts.spec.exit_when)
135
+ : opts.spec.exit_when
136
+ : null;
137
+ if (!Array.isArray(opts.spec.body) || opts.spec.body.length === 0) {
138
+ throw new LoopConfigError(`Loop '${opts.loop_id}' must have a non-empty body`);
139
+ }
140
+ const iterations = [];
141
+ let prevOutputs = {};
142
+ let totalCost = 0;
143
+ let exited = false;
144
+ let exitedBy = 'max_iterations';
145
+ for (let i = 1; i <= max; i++) {
146
+ const bodyStages = opts.spec.body;
147
+ const iterOutputs = {};
148
+ let iterCost = 0;
149
+ const start = Date.now();
150
+ for (const bodyStage of bodyStages) {
151
+ const stageId = typeof bodyStage['id'] === 'string' ? bodyStage['id'] : `stage_${i}`;
152
+ const result = await opts.runBodyStage(bodyStage, i, prevOutputs);
153
+ iterOutputs[stageId] = result.outputs;
154
+ iterCost += result.cost_micro_usdc;
155
+ }
156
+ const iterDuration = Date.now() - start;
157
+ totalCost += iterCost;
158
+ let exitEval = null;
159
+ if (expr) {
160
+ const flat = flattenOutputs(iterOutputs);
161
+ exitEval = evaluateExitExpression(flat, expr);
162
+ }
163
+ const iteration = {
164
+ iteration: i,
165
+ outputs: iterOutputs,
166
+ cost_micro_usdc: iterCost,
167
+ duration_ms: iterDuration,
168
+ exit_evaluated: exitEval,
169
+ exited: exitEval === true,
170
+ };
171
+ iterations.push(iteration);
172
+ if (opts.memory) {
173
+ await opts.memory.set({ pipeline_id: opts.pipeline_id, partition: 'loop_state', scope: 'pipeline' }, `${opts.loop_id}:iteration_${i}`, iteration, 86400);
174
+ }
175
+ if (exitEval === true) {
176
+ exited = true;
177
+ exitedBy = 'exit_when';
178
+ prevOutputs = iterOutputs;
179
+ break;
180
+ }
181
+ prevOutputs = iterOutputs;
182
+ }
183
+ if (!exited && exitedBy === 'max_iterations') {
184
+ if (iterations.length >= max) {
185
+ throw new LoopMaxIterationsExceededError(opts.loop_id, max);
186
+ }
187
+ }
188
+ const trace = {
189
+ schema_version: LOOP_SCHEMA_VERSION,
190
+ loop_id: opts.loop_id,
191
+ pipeline_id: opts.pipeline_id,
192
+ max_iterations: max,
193
+ total_iterations: iterations.length,
194
+ exited_by: exitedBy,
195
+ final_outputs: prevOutputs,
196
+ total_cost_micro_usdc: totalCost,
197
+ iterations,
198
+ };
199
+ return { trace };
200
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Pipeline memory — M6.1 (2026-09-25).
3
+ *
4
+ * Persistent key-value state for pipelines, backed by R2 (production) or
5
+ * in-memory map (dev/test). Lets pipelines accumulate context across stages
6
+ * (e.g., multi-turn research, iterative refinement) without re-fetching.
7
+ *
8
+ * Storage is pluggable: production uses the existing CHECKPOINTS R2 binding
9
+ * with `memory/` key prefix (avoids new wrangler.toml binding), tests use
10
+ * InMemoryMemoryStore. Pass `createMemoryStore('mock')` to disable persistence.
11
+ *
12
+ * Key format: `memory/<pipeline_id>/<partition>/<key>` (R2) or in-memory Map.
13
+ * Values are JSON-serialized. TTL stored as R2 custom metadata; lazy expiry
14
+ * on read (no background GC needed for short TTL).
15
+ */
16
+ export declare const MEMORY_SCHEMA_VERSION = 1;
17
+ export declare const MAX_MEMORY_VALUE_BYTES = 1048576;
18
+ export type MemoryScope = 'pipeline' | 'stage' | 'global';
19
+ export interface MemoryPartition {
20
+ pipeline_id: string;
21
+ partition: string;
22
+ scope: MemoryScope;
23
+ ttl_seconds?: number;
24
+ }
25
+ export interface MemoryEntry {
26
+ key: string;
27
+ value: unknown;
28
+ stored_at: string;
29
+ expires_at: string | null;
30
+ }
31
+ export interface MemoryStore {
32
+ get(partition: MemoryPartition, key: string): Promise<unknown | null>;
33
+ set(partition: MemoryPartition, key: string, value: unknown, ttl_seconds?: number): Promise<void>;
34
+ delete(partition: MemoryPartition, key: string): Promise<void>;
35
+ list(partition: MemoryPartition, prefix?: string): Promise<string[]>;
36
+ }
37
+ export interface MemoryR2Like {
38
+ get(key: string): Promise<{
39
+ body: ReadableStream | null;
40
+ customMetadata?: Record<string, string>;
41
+ } | null>;
42
+ put(key: string, value: ReadableStream | string | ArrayBuffer, options?: {
43
+ customMetadata?: Record<string, string>;
44
+ }): Promise<void>;
45
+ delete(key: string): Promise<void>;
46
+ list(options?: {
47
+ prefix?: string;
48
+ }): Promise<{
49
+ objects: Array<{
50
+ key: string;
51
+ }>;
52
+ }>;
53
+ }
54
+ export declare class InMemoryMemoryStore implements MemoryStore {
55
+ private readonly map;
56
+ private makeKey;
57
+ private isExpired;
58
+ get(partition: MemoryPartition, key: string): Promise<unknown | null>;
59
+ set(partition: MemoryPartition, key: string, value: unknown, ttl_seconds?: number): Promise<void>;
60
+ delete(partition: MemoryPartition, key: string): Promise<void>;
61
+ list(partition: MemoryPartition, prefix?: string): Promise<string[]>;
62
+ }
63
+ export declare function createMemoryStore(backend: 'r2' | 'mock', r2?: MemoryR2Like | null): MemoryStore;
64
+ export declare class R2MemoryStore implements MemoryStore {
65
+ private readonly r2;
66
+ constructor(r2: MemoryR2Like);
67
+ private makeKey;
68
+ private isExpired;
69
+ get(partition: MemoryPartition, key: string): Promise<unknown | null>;
70
+ set(partition: MemoryPartition, key: string, value: unknown, ttl_seconds?: number): Promise<void>;
71
+ delete(partition: MemoryPartition, key: string): Promise<void>;
72
+ list(partition: MemoryPartition, prefix?: string): Promise<string[]>;
73
+ }
package/dist/memory.js ADDED
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Pipeline memory — M6.1 (2026-09-25).
3
+ *
4
+ * Persistent key-value state for pipelines, backed by R2 (production) or
5
+ * in-memory map (dev/test). Lets pipelines accumulate context across stages
6
+ * (e.g., multi-turn research, iterative refinement) without re-fetching.
7
+ *
8
+ * Storage is pluggable: production uses the existing CHECKPOINTS R2 binding
9
+ * with `memory/` key prefix (avoids new wrangler.toml binding), tests use
10
+ * InMemoryMemoryStore. Pass `createMemoryStore('mock')` to disable persistence.
11
+ *
12
+ * Key format: `memory/<pipeline_id>/<partition>/<key>` (R2) or in-memory Map.
13
+ * Values are JSON-serialized. TTL stored as R2 custom metadata; lazy expiry
14
+ * on read (no background GC needed for short TTL).
15
+ */
16
+ export const MEMORY_SCHEMA_VERSION = 1;
17
+ export const MAX_MEMORY_VALUE_BYTES = 1_048_576;
18
+ export class InMemoryMemoryStore {
19
+ map = new Map();
20
+ makeKey(partition, key) {
21
+ return `${partition.pipeline_id}::${partition.partition}::${key}`;
22
+ }
23
+ isExpired(expires_at) {
24
+ return expires_at !== null && expires_at < Date.now();
25
+ }
26
+ async get(partition, key) {
27
+ const k = this.makeKey(partition, key);
28
+ const entry = this.map.get(k);
29
+ if (!entry)
30
+ return null;
31
+ if (this.isExpired(entry.expires_at)) {
32
+ this.map.delete(k);
33
+ return null;
34
+ }
35
+ return entry.value;
36
+ }
37
+ async set(partition, key, value, ttl_seconds) {
38
+ if (JSON.stringify(value).length > MAX_MEMORY_VALUE_BYTES) {
39
+ throw new Error(`memory value too large (max ${MAX_MEMORY_VALUE_BYTES} bytes)`);
40
+ }
41
+ const k = this.makeKey(partition, key);
42
+ const expires_at = ttl_seconds ?? partition.ttl_seconds ?? null;
43
+ const expires_ms = expires_at !== null && expires_at !== undefined ? Date.now() + expires_at * 1000 : null;
44
+ this.map.set(k, { value, expires_at: expires_ms });
45
+ }
46
+ async delete(partition, key) {
47
+ this.map.delete(this.makeKey(partition, key));
48
+ }
49
+ async list(partition, prefix) {
50
+ const fullPrefix = this.makeKey(partition, prefix ?? '');
51
+ const keys = [];
52
+ for (const k of this.map.keys()) {
53
+ if (k.startsWith(fullPrefix)) {
54
+ keys.push(k.split('::').slice(2).join('::'));
55
+ }
56
+ }
57
+ return keys;
58
+ }
59
+ }
60
+ export function createMemoryStore(backend, r2) {
61
+ if (backend === 'mock' || !r2) {
62
+ return new InMemoryMemoryStore();
63
+ }
64
+ return new R2MemoryStore(r2);
65
+ }
66
+ export class R2MemoryStore {
67
+ r2;
68
+ constructor(r2) {
69
+ this.r2 = r2;
70
+ }
71
+ makeKey(partition, key) {
72
+ return `memory/${partition.pipeline_id}/${partition.partition}/${key}`;
73
+ }
74
+ isExpired(expires_at) {
75
+ if (!expires_at)
76
+ return false;
77
+ return Date.parse(expires_at) < Date.now();
78
+ }
79
+ async get(partition, key) {
80
+ const r2key = this.makeKey(partition, key);
81
+ const obj = await this.r2.get(r2key);
82
+ if (!obj || !obj.body)
83
+ return null;
84
+ const meta = obj.customMetadata ?? {};
85
+ if (this.isExpired(meta['expires_at'])) {
86
+ await this.r2.delete(r2key);
87
+ return null;
88
+ }
89
+ const text = await new Response(obj.body).text();
90
+ return JSON.parse(text);
91
+ }
92
+ async set(partition, key, value, ttl_seconds) {
93
+ const serialized = JSON.stringify(value);
94
+ if (serialized.length > MAX_MEMORY_VALUE_BYTES) {
95
+ throw new Error(`memory value too large (max ${MAX_MEMORY_VALUE_BYTES} bytes)`);
96
+ }
97
+ const ttl = ttl_seconds ?? partition.ttl_seconds ?? null;
98
+ const expires_at = ttl !== null && ttl !== undefined
99
+ ? new Date(Date.now() + ttl * 1000).toISOString()
100
+ : null;
101
+ const r2key = this.makeKey(partition, key);
102
+ await this.r2.put(r2key, serialized, {
103
+ customMetadata: {
104
+ schema_version: String(MEMORY_SCHEMA_VERSION),
105
+ stored_at: new Date().toISOString(),
106
+ expires_at: expires_at ?? '',
107
+ scope: partition.scope,
108
+ },
109
+ });
110
+ }
111
+ async delete(partition, key) {
112
+ await this.r2.delete(this.makeKey(partition, key));
113
+ }
114
+ async list(partition, prefix) {
115
+ const fullPrefix = this.makeKey(partition, prefix ?? '');
116
+ const listed = await this.r2.list({ prefix: fullPrefix });
117
+ return listed.objects.map((o) => o.key.split('/').slice(3).join('/'));
118
+ }
119
+ }
@@ -28,9 +28,16 @@ export interface PipelineStageLike {
28
28
  uses?: string | string[];
29
29
  /** @deprecated Explicit list instead of inline. */
30
30
  uses_version?: string;
31
+ /** Per-stage arguments. Singular is the historical spelling. */
31
32
  input?: unknown;
33
+ /**
34
+ * Alias for `input`, and the dominant spelling in practice: the canonical
35
+ * pipeline set declares stage arguments as `inputs:` 16 times against
36
+ * `input:` twice. Both are honoured; singular wins if both are somehow set.
37
+ */
38
+ inputs?: unknown;
32
39
  system?: string;
33
- prompt?: string;
40
+ prompt?: string | readonly import('./multimodal.js').MultimodalMessage[];
34
41
  /**
35
42
  * Output format constraint for post-LLM validation.
36
43
  * Default: 'text' (no validation).
@@ -42,6 +49,15 @@ export interface PipelineStageLike {
42
49
  * Triggers `StageOutputFormatError` if any are missing in LLM output.
43
50
  */
44
51
  fields?: string[];
52
+ /**
53
+ * Output token budget for this stage. Default: 4096.
54
+ *
55
+ * Reasoning models count their thinking against this same budget, so a stage
56
+ * that emits long JSON on a large input needs room for both the reasoning and
57
+ * the answer — MiniMax M-series otherwise spends the whole budget thinking and
58
+ * returns no text at all. Raise it per stage rather than globally.
59
+ */
60
+ maxTokens?: number;
45
61
  /**
46
62
  * MCP server names available to this stage. v0.2 NEW (forward-compat).
47
63
  * Validated against executor's MCP registry, not yet executed.
@@ -73,6 +89,20 @@ export interface PipelineStageLike {
73
89
  cwd?: string;
74
90
  timeout_ms?: number;
75
91
  };
92
+ /**
93
+ * M6.2 NEW — iterative loop executor. Wraps body stages that run
94
+ * repeatedly until `exit_when` expression evaluates truthy OR
95
+ * `max_iterations` is reached. Mutually exclusive with `uses` / `model`+`prompt`.
96
+ */
97
+ loop?: {
98
+ max_iterations?: number;
99
+ exit_when?: string | {
100
+ outputs_key: string;
101
+ operator: '>=' | '<=' | '==' | '!=' | '>' | '<';
102
+ value: number | boolean | string;
103
+ };
104
+ body: ReadonlyArray<Record<string, unknown>>;
105
+ };
76
106
  /**
77
107
  * Provider name (e.g. "minimax", "openrouter"). v0.3 NEW (optional in
78
108
  * v0.3 transition; required once pickProvider auto-dispatch is removed).
@@ -119,6 +149,27 @@ export interface PipelineStageLike {
119
149
  * Callers wanting zero-retry semantics pass `attempts: 1`.
120
150
  */
121
151
  retry?: import('./retry.js').RetryConfig;
152
+ /**
153
+ * M5 — Optional JSON Schema (draft-07 subset) the executor's output
154
+ * must satisfy. When set, the runtime validates the stage result
155
+ * AFTER the executor returns and BEFORE the next stage runs. Backward
156
+ * compatible: omission = no validation (v0.7 behavior). See
157
+ * PIPELINE.md §"Stage output validation (M5)" for the full contract
158
+ * + supported subset. Failed validation triggers `output_retry`
159
+ * semantics and ultimately surfaces as HTTP 500
160
+ * `OUTPUT_VALIDATION_FAILED`.
161
+ */
162
+ output_schema?: import('./output-schema.js').JsonSchema;
163
+ /**
164
+ * M5 — Retry mode for output validation failures:
165
+ * - 'none' (default — fail-fast on first failure; backward compat)
166
+ * - 'single' (1 retry after validation failure → 2 total attempts)
167
+ * - 'loop' (up to 3 total attempts before failing)
168
+ *
169
+ * Independent of `retry:` (which handles HTTP status retries). Has no
170
+ * effect when `output_schema` is omitted.
171
+ */
172
+ output_retry?: import('./output-errors.js').OutputValidationMode;
122
173
  }
123
174
  export interface PipelineLike {
124
175
  name?: string;
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Multimodal content types — M1 NEW (image / audio / video LLM inputs).
3
+ *
4
+ * Shape mirrors the OpenAI chat.completions messages format so OpenRouter
5
+ * passes messages through unchanged; MiniMax (Anthropic-compatible) has a
6
+ * dedicated converter in adapters/multimodal-convert.ts.
7
+ */
8
+ export interface TextMessagePart {
9
+ readonly type: 'text';
10
+ readonly text: string;
11
+ }
12
+ export interface ImageMessagePart {
13
+ readonly type: 'image_url';
14
+ readonly image_url: {
15
+ readonly url: string;
16
+ readonly detail?: 'low' | 'high' | 'auto';
17
+ };
18
+ }
19
+ export interface AudioMessagePart {
20
+ readonly type: 'audio_url';
21
+ readonly audio_url: {
22
+ readonly url: string;
23
+ };
24
+ }
25
+ export interface VideoMessagePart {
26
+ readonly type: 'video_url';
27
+ readonly video_url: {
28
+ readonly url: string;
29
+ };
30
+ }
31
+ export type MultimodalPart = TextMessagePart | ImageMessagePart | AudioMessagePart | VideoMessagePart;
32
+ export type MultimodalRole = 'user' | 'assistant' | 'system';
33
+ export interface MultimodalMessage {
34
+ readonly role: MultimodalRole;
35
+ readonly content: string | readonly MultimodalPart[];
36
+ }
37
+ export type StagePrompt = string | readonly MultimodalMessage[];
38
+ export declare class MultimodalModelUnsupportedError extends Error {
39
+ readonly providerName: string;
40
+ readonly modelName: string;
41
+ readonly visionCapableModels: readonly string[];
42
+ constructor(providerName: string, modelName: string, visionCapableModels: readonly string[]);
43
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Multimodal content types — M1 NEW (image / audio / video LLM inputs).
3
+ *
4
+ * Shape mirrors the OpenAI chat.completions messages format so OpenRouter
5
+ * passes messages through unchanged; MiniMax (Anthropic-compatible) has a
6
+ * dedicated converter in adapters/multimodal-convert.ts.
7
+ */
8
+ export class MultimodalModelUnsupportedError extends Error {
9
+ providerName;
10
+ modelName;
11
+ visionCapableModels;
12
+ constructor(providerName, modelName, visionCapableModels) {
13
+ const avail = visionCapableModels.length > 0
14
+ ? visionCapableModels.join(', ')
15
+ : '(none registered for this provider)';
16
+ super(`Model '${modelName}' on provider '${providerName}' does not support multimodal ` +
17
+ `inputs (image/audio/video). Vision-capable models for ${providerName}: ${avail}`);
18
+ this.name = 'MULTIMODAL_MODEL_UNSUPPORTED';
19
+ this.providerName = providerName;
20
+ this.modelName = modelName;
21
+ this.visionCapableModels = visionCapableModels;
22
+ }
23
+ }