@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/README.md CHANGED
@@ -91,4 +91,89 @@ Single source of truth: `PROVIDER_REGISTRY` in
91
91
 
92
92
  ## Status
93
93
 
94
- v0.3 — R6 (Provider ≠ Model) shipped. Linear + DAG stage execution. Retry, parallel branches, checkpoint.
94
+ v0.5 — file output + shell stages shipped (P5 + P4). Server surfaces
95
+ `call_price_usdc` + `preferred_model` + `capabilities` on every pipeline.
96
+
97
+ ## Output spec helpers (v0.5 — P1.1)
98
+
99
+ Pipelines declare a top-level `output:` block describing what they produce.
100
+ Two concerns: `format` (text/json/zip/files) and `delivery` (inline or
101
+ signed URL). `validateOutputSpec(raw)` returns the normalized spec or
102
+ structured errors:
103
+
104
+ ```ts
105
+ import { validateOutputSpec } from '@agentsmarket/pipeline-runtime';
106
+
107
+ const r = validateOutputSpec({
108
+ format: 'files',
109
+ files: ['*.md', 'report.json'],
110
+ delivery: 'signed_url',
111
+ expires_in: 3600,
112
+ });
113
+ // r.ok === true, r.value = { format: 'files', files: [...], delivery: 'signed_url', expires_in: 3600 }
114
+ ```
115
+
116
+ Limits: `expires_in` 60 ≤ seconds ≤ 604800 (7 days). Globs use `*` and `**`
117
+ with the standard "no slash past `**`" semantics.
118
+
119
+ ## File output collection (v0.5 — P1.2 / P5)
120
+
121
+ When a stage declares `output_format: structured_json` and includes a
122
+ `produced_files` array, `extractProducedFiles(stageOutputs, spec)` collects
123
+ the base64-encoded files and validates them against `output.files` globs:
124
+
125
+ ```ts
126
+ import { extractProducedFiles, globToRegex } from '@agentsmarket/pipeline-runtime';
127
+
128
+ const stageOutput = JSON.stringify({
129
+ summary: 'done',
130
+ produced_files: [
131
+ { name: 'report.md', content_type: 'text/markdown', content_b64: 'IyBS...' },
132
+ ],
133
+ });
134
+
135
+ const r = extractProducedFiles(
136
+ { stage1: stageOutput },
137
+ { format: 'files', files: ['*.md'], delivery: 'signed_url', expires_in: 3600 },
138
+ );
139
+ // r.files = [{ stage_id: 'stage1', name: 'report.md', size: 7, content_type: 'text/markdown', content_b64: '...' }]
140
+ // r.errors = [], r.warnings = []
141
+ ```
142
+
143
+ Limits: 10 MB/file, 50 MB total per invoke, 100 files max. Names reject
144
+ `/`, `\`, `..` (flat namespace). Bad base64 / oversized / path-traversal
145
+ return errors that abort the pipeline; unmatched globs return warnings.
146
+
147
+ Server uses this on `POST /v1/pipelines/:id/invoke` (P5) to upload files to
148
+ R2 and return HMAC-signed URLs in `output_files[]`.
149
+
150
+ ## Shell stage helpers (v0.5 — P4, CLI-only)
151
+
152
+ Stages can declare `shell: "cmd args..."` or
153
+ `shell: { cmd, args?, cwd?, timeout_ms? }`. Executed only via
154
+ `pipeline call --local`; server invokes return
155
+ `400 SHELL_UNSUPPORTED_ON_SERVER`.
156
+
157
+ ```ts
158
+ import { NodeShellExecutor, ThrowingShellExecutor } from '@agentsmarket/pipeline-runtime';
159
+
160
+ // CLI passes a real executor
161
+ const cliDeps = { isLocal: true, shellExecutor: new NodeShellExecutor(), ... };
162
+
163
+ // Server passes a throwing stub (Workers can't spawn)
164
+ const serverDeps = { isLocal: false, shellExecutor: new ThrowingShellExecutor('server cannot spawn'), ... };
165
+ ```
166
+
167
+ `NodeShellExecutor` uses `child_process.spawn(cmd, args, { shell: false, timeout })`:
168
+ no shell interpretation (no injection), SIGTERM on `timeout_ms` expiry
169
+ (maps to `ShellStageTimeoutError`), non-zero exit → `ShellStageExecError`,
170
+ stdout/stderr truncated at 1 MB each.
171
+
172
+ Limits: `timeout_ms` default 30000, max 600000 (10 min). Output cap 1 MB
173
+ per stream.
174
+
175
+ ## Status
176
+
177
+ v0.5 — file output (P5) + shell stages (P4) shipped. R6 (Provider ≠ Model)
178
+ shipped in v0.3. Linear + DAG stage execution. Retry, parallel branches,
179
+ checkpoint.
@@ -1,16 +1,23 @@
1
1
  /**
2
- * MiniMax provider — wraps MiniMax API which exposes an Anthropic-compatible endpoint.
2
+ * MiniMax provider — calls MiniMax API (Anthropic-compatible endpoint) via
3
+ * global `fetch`. Does NOT use @anthropic-ai/sdk because SDK v0.125+
4
+ * hardcodes `Authorization: Bearer` and does not honour our `x-api-key`
5
+ * requirement (MiniMax API rejects Bearer with 401).
3
6
  *
4
- * Endpoint: https://api.minimax.io/anthropic/v1/messages
5
- * Auth: MINIMAX_API_KEY env var (or apiKey in opts)
6
- *
7
- * IMPORTANT: Anthropic SDK appends '/v1/messages' to baseURL.
8
- * So baseURL must NOT include '/v1' (else we get '/v1/v1/messages' → 404).
7
+ * Endpoint: POST https://api.minimax.io/anthropic/v1/messages
8
+ * Auth: x-api-key: <MINIMAX_API_KEY> (NOT Bearer)
9
9
  *
10
10
  * Models:
11
11
  * - MiniMax-M2.7 (fast, simple tasks)
12
12
  * - MiniMax-M2.7-highspeed (fastest, simplest)
13
- * - MiniMax-M3 (slower, more capable, complex tasks)
13
+ * - MiniMax-M3 (slower, more capable, complex tasks — vision-capable)
14
+ *
15
+ * M1 — multimodal (image/audio/video) supported via `opts.messages`. Each
16
+ * MultimodalMessage is converted to Anthropic-style content blocks
17
+ * (image for `image_url`, document for `audio_url`/`video_url`). The
18
+ * vision-capable check is the executor's responsibility (see
19
+ * `assertMultimodalSupported` in provider-registry.ts); this adapter only
20
+ * shapes the request body.
14
21
  */
15
22
  import type { LLMProvider, GenerateOptions, GenerateResult } from '../types.js';
16
23
  import { z } from 'zod';
@@ -23,7 +30,8 @@ export declare class MiniMaxProvider implements LLMProvider {
23
30
  readonly models: readonly ["MiniMax-M2.7", "MiniMax-M2.7-highspeed", "MiniMax-M3"];
24
31
  readonly simpleModel = "MiniMax-M2.7";
25
32
  readonly complexModel = "MiniMax-M3";
26
- private client;
33
+ private readonly apiKey;
34
+ private readonly baseURL;
27
35
  supports(model: string): boolean;
28
36
  constructor(opts?: MiniMaxProviderOptions);
29
37
  generateText(prompt: string, opts?: GenerateOptions): Promise<GenerateResult>;
@@ -1,70 +1,149 @@
1
1
  /**
2
- * MiniMax provider — wraps MiniMax API which exposes an Anthropic-compatible endpoint.
2
+ * MiniMax provider — calls MiniMax API (Anthropic-compatible endpoint) via
3
+ * global `fetch`. Does NOT use @anthropic-ai/sdk because SDK v0.125+
4
+ * hardcodes `Authorization: Bearer` and does not honour our `x-api-key`
5
+ * requirement (MiniMax API rejects Bearer with 401).
3
6
  *
4
- * Endpoint: https://api.minimax.io/anthropic/v1/messages
5
- * Auth: MINIMAX_API_KEY env var (or apiKey in opts)
6
- *
7
- * IMPORTANT: Anthropic SDK appends '/v1/messages' to baseURL.
8
- * So baseURL must NOT include '/v1' (else we get '/v1/v1/messages' → 404).
7
+ * Endpoint: POST https://api.minimax.io/anthropic/v1/messages
8
+ * Auth: x-api-key: <MINIMAX_API_KEY> (NOT Bearer)
9
9
  *
10
10
  * Models:
11
11
  * - MiniMax-M2.7 (fast, simple tasks)
12
12
  * - MiniMax-M2.7-highspeed (fastest, simplest)
13
- * - MiniMax-M3 (slower, more capable, complex tasks)
13
+ * - MiniMax-M3 (slower, more capable, complex tasks — vision-capable)
14
+ *
15
+ * M1 — multimodal (image/audio/video) supported via `opts.messages`. Each
16
+ * MultimodalMessage is converted to Anthropic-style content blocks
17
+ * (image for `image_url`, document for `audio_url`/`video_url`). The
18
+ * vision-capable check is the executor's responsibility (see
19
+ * `assertMultimodalSupported` in provider-registry.ts); this adapter only
20
+ * shapes the request body.
14
21
  */
15
- import Anthropic from '@anthropic-ai/sdk';
16
- // SDK appends '/v1/messages' → baseURL must NOT end with /v1
22
+ import { toAnthropicContent, } from './multimodal-convert.js';
23
+ import { parseJsonLenient } from '../validate-inputs.js';
17
24
  const DEFAULT_BASE_URL = 'https://api.minimax.io/anthropic';
18
25
  export class MiniMaxProvider {
19
26
  name = 'minimax';
20
27
  models = ['MiniMax-M2.7', 'MiniMax-M2.7-highspeed', 'MiniMax-M3'];
21
28
  simpleModel = 'MiniMax-M2.7';
22
29
  complexModel = 'MiniMax-M3';
23
- client;
30
+ apiKey;
31
+ baseURL;
24
32
  supports(model) {
25
33
  return this.models.includes(model);
26
34
  }
27
35
  constructor(opts = {}) {
28
- // Workers runtime doesn't have `process` — guard access
29
36
  const procEnv = typeof process !== 'undefined' ? process.env : undefined;
30
37
  const apiKey = opts.apiKey || procEnv?.MINIMAX_API_KEY;
31
38
  if (!apiKey) {
32
39
  throw new Error('MiniMaxProvider: apiKey missing. Pass via opts.apiKey or set MINIMAX_API_KEY env var.');
33
40
  }
34
- this.client = new Anthropic({
35
- apiKey,
36
- baseURL: opts.baseURL || procEnv?.MINIMAX_BASE_URL || DEFAULT_BASE_URL,
37
- });
41
+ this.apiKey = apiKey;
42
+ this.baseURL = opts.baseURL || procEnv?.MINIMAX_BASE_URL || DEFAULT_BASE_URL;
38
43
  }
39
44
  async generateText(prompt, opts = {}) {
40
45
  const model = opts.model ?? (opts.complexity === 'complex' ? this.complexModel : this.simpleModel);
41
- const response = await this.client.messages.create({
46
+ const { messages, systemParts } = buildAnthropicMessages(opts.messages, prompt);
47
+ const system = joinSystem(opts.system, systemParts);
48
+ const body = {
42
49
  model,
43
50
  max_tokens: opts.maxTokens ?? 2048,
44
51
  temperature: opts.temperature ?? 0.7,
45
52
  ...(opts.topP !== undefined ? { top_p: opts.topP } : {}),
46
- system: opts.system,
53
+ ...(system !== undefined ? { system } : {}),
47
54
  ...(opts.stopSequences ? { stop_sequences: opts.stopSequences } : {}),
48
- messages: [{ role: 'user', content: prompt }],
55
+ messages,
56
+ };
57
+ const response = await fetch(`${this.baseURL}/v1/messages`, {
58
+ method: 'POST',
59
+ headers: {
60
+ 'content-type': 'application/json',
61
+ 'x-api-key': this.apiKey,
62
+ 'anthropic-version': '2023-06-01',
63
+ },
64
+ body: JSON.stringify(body),
65
+ }).catch((e) => {
66
+ console.error(`[MiniMax fetch] ERROR: ${e instanceof Error ? e.message : e}`);
67
+ throw e;
49
68
  });
50
- const text = response.content
51
- .filter((block) => block.type === 'text')
52
- .map((block) => block.text)
69
+ if (!response.ok) {
70
+ const errText = await response.text();
71
+ console.error(`[MiniMax fetch] ${response.status} keyLen=${this.apiKey.length} url=${this.baseURL}/v1/messages`);
72
+ console.error(`[MiniMax fetch] body:`, errText);
73
+ throw new Error(`MiniMax API ${response.status}: ${errText}`);
74
+ }
75
+ if (!response.ok) {
76
+ const errText = await response.text();
77
+ throw new Error(`MiniMax API ${response.status}: ${errText}`);
78
+ }
79
+ const data = (await response.json());
80
+ const text = (data.content ?? [])
81
+ .filter((b) => b.type === 'text' && typeof b.text === 'string')
82
+ .map((b) => b.text)
53
83
  .join('');
54
84
  const usage = {
55
- inputTokens: response.usage.input_tokens,
56
- outputTokens: response.usage.output_tokens,
85
+ inputTokens: data.usage?.input_tokens ?? 0,
86
+ outputTokens: data.usage?.output_tokens ?? 0,
57
87
  };
58
88
  return { text, usage };
59
89
  }
60
90
  async generateJson(prompt, schema, opts = {}) {
61
- const jsonPrompt = `${prompt}\\n\\nRespond ONLY with valid JSON. No markdown, no prose, no code fences.`;
91
+ const jsonPrompt = `${prompt}\n\nRespond ONLY with valid JSON. No markdown, no prose, no code fences.`;
62
92
  const { text } = await this.generateText(jsonPrompt, {
63
93
  ...opts,
64
94
  system: opts.system ?? 'You are a JSON generator. Output only valid JSON, nothing else.',
65
95
  });
66
- const cleaned = text.replace(/^```json\s*/i, '').replace(/```\s*$/, '').trim();
67
- const parsed = JSON.parse(cleaned);
96
+ const parsed = parseJsonLenient(text);
68
97
  return schema.parse(parsed);
69
98
  }
70
99
  }
100
+ /**
101
+ * Build the `messages` payload. When multimodal messages are supplied we
102
+ * convert each to content blocks; otherwise we fall back to wrapping the
103
+ * legacy string `prompt` as a single user turn.
104
+ *
105
+ * MiniMax API does NOT accept `role:'system'` on messages — system prompts
106
+ * are a top-level parameter. We extract any system-role messages and return
107
+ * them as `systemParts` for the caller to merge into the `system` field.
108
+ */
109
+ function buildAnthropicMessages(messages, fallbackPrompt) {
110
+ const systemParts = [];
111
+ const out = [];
112
+ if (!messages || messages.length === 0) {
113
+ out.push({ role: 'user', content: fallbackPrompt });
114
+ return { messages: out, systemParts };
115
+ }
116
+ for (const msg of messages) {
117
+ if (msg.role === 'system') {
118
+ systemParts.push(typeof msg.content === 'string' ? msg.content : textFromParts(msg.content));
119
+ continue;
120
+ }
121
+ const role = msg.role === 'assistant' ? 'assistant' : 'user';
122
+ if (typeof msg.content === 'string') {
123
+ out.push({ role, content: msg.content });
124
+ }
125
+ else {
126
+ out.push({ role, content: toAnthropicContent(msg.content) });
127
+ }
128
+ }
129
+ if (out.length === 0) {
130
+ out.push({ role: 'user', content: '' });
131
+ }
132
+ return { messages: out, systemParts };
133
+ }
134
+ function textFromParts(parts) {
135
+ return parts
136
+ .filter((p) => p.type === 'text' && typeof p.text === 'string')
137
+ .map((p) => p.text)
138
+ .join('');
139
+ }
140
+ function joinSystem(system, parts) {
141
+ const filtered = parts.filter((p) => p.length > 0);
142
+ if (system && filtered.length > 0)
143
+ return `${system}\n\n${filtered.join('\n\n')}`;
144
+ if (system)
145
+ return system;
146
+ if (filtered.length > 0)
147
+ return filtered.join('\n\n');
148
+ return undefined;
149
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Multimodal content conversion — maps our standard MultimodalMessage /
3
+ * MultimodalPart shapes to provider-native request bodies.
4
+ *
5
+ * Anthropic's content-block schema is structurally different from OpenAI's
6
+ * chat.completions messages (image uses `{type:'image', source:{...}}` not
7
+ * `{type:'image_url', image_url:{...}}`; audio/video arrive as document
8
+ * blocks with explicit `media_type`).
9
+ *
10
+ * OpenAI-shaped providers (OpenRouter, anything OpenAI-compatible) do NOT
11
+ * call this module — they pass messages through unchanged.
12
+ */
13
+ import type { MultimodalMessage } from '../multimodal.js';
14
+ export declare const SUPPORTED_IMAGE_MIME: Set<string>;
15
+ export declare const SUPPORTED_AUDIO_MIME: Set<string>;
16
+ export declare const SUPPORTED_VIDEO_MIME: Set<string>;
17
+ export type ParsedMedia = {
18
+ readonly kind: 'url';
19
+ readonly url: string;
20
+ } | {
21
+ readonly kind: 'data';
22
+ readonly mediaType: string;
23
+ readonly base64: string;
24
+ };
25
+ export declare function parseMediaUrl(url: string): ParsedMedia;
26
+ export declare function detectMime(url: string): string | null;
27
+ export declare function isImageMime(mime: string): boolean;
28
+ export declare function isAudioMime(mime: string): boolean;
29
+ export declare function isVideoMime(mime: string): boolean;
30
+ export type AnthropicContentBlock = {
31
+ readonly type: 'text';
32
+ readonly text: string;
33
+ } | {
34
+ readonly type: 'image';
35
+ readonly source: {
36
+ readonly type: 'base64';
37
+ readonly media_type: string;
38
+ readonly data: string;
39
+ } | {
40
+ readonly type: 'url';
41
+ readonly url: string;
42
+ };
43
+ } | {
44
+ readonly type: 'document';
45
+ readonly source: {
46
+ readonly type: 'base64';
47
+ readonly media_type: string;
48
+ readonly data: string;
49
+ } | {
50
+ readonly type: 'url';
51
+ readonly url: string;
52
+ };
53
+ };
54
+ export declare function toAnthropicContent(content: MultimodalMessage['content']): readonly AnthropicContentBlock[];
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Multimodal content conversion — maps our standard MultimodalMessage /
3
+ * MultimodalPart shapes to provider-native request bodies.
4
+ *
5
+ * Anthropic's content-block schema is structurally different from OpenAI's
6
+ * chat.completions messages (image uses `{type:'image', source:{...}}` not
7
+ * `{type:'image_url', image_url:{...}}`; audio/video arrive as document
8
+ * blocks with explicit `media_type`).
9
+ *
10
+ * OpenAI-shaped providers (OpenRouter, anything OpenAI-compatible) do NOT
11
+ * call this module — they pass messages through unchanged.
12
+ */
13
+ const DATA_URI_RE = /^data:([^;,]+)(?:;base64)?,(.*)$/s;
14
+ export const SUPPORTED_IMAGE_MIME = new Set([
15
+ 'image/png',
16
+ 'image/jpeg',
17
+ 'image/jpg',
18
+ 'image/gif',
19
+ 'image/webp',
20
+ ]);
21
+ export const SUPPORTED_AUDIO_MIME = new Set([
22
+ 'audio/mp3',
23
+ 'audio/mpeg',
24
+ 'audio/wav',
25
+ 'audio/x-wav',
26
+ 'audio/ogg',
27
+ 'audio/webm',
28
+ ]);
29
+ export const SUPPORTED_VIDEO_MIME = new Set([
30
+ 'video/mp4',
31
+ 'video/webm',
32
+ 'video/quicktime',
33
+ ]);
34
+ export function parseMediaUrl(url) {
35
+ if (typeof url !== 'string' || url.length === 0) {
36
+ throw new Error('Multimodal part url is empty');
37
+ }
38
+ if (url.startsWith('data:')) {
39
+ const match = DATA_URI_RE.exec(url);
40
+ if (!match) {
41
+ throw new Error(`Invalid data URI: ${url.slice(0, 40)}...`);
42
+ }
43
+ const mediaType = match[1] ?? '';
44
+ const body = match[2] ?? '';
45
+ return { kind: 'data', mediaType, base64: body };
46
+ }
47
+ if (url.startsWith('https://') || url.startsWith('http://')) {
48
+ return { kind: 'url', url };
49
+ }
50
+ throw new Error(`Unsupported multimodal URL scheme: ${url.slice(0, 24)}`);
51
+ }
52
+ export function detectMime(url) {
53
+ if (url.startsWith('data:')) {
54
+ const match = DATA_URI_RE.exec(url);
55
+ return match ? (match[1] ?? null) : null;
56
+ }
57
+ const ext = url.split('?')[0]?.split('.').pop()?.toLowerCase() ?? '';
58
+ switch (ext) {
59
+ case 'png': return 'image/png';
60
+ case 'jpg':
61
+ case 'jpeg': return 'image/jpeg';
62
+ case 'gif': return 'image/gif';
63
+ case 'webp': return 'image/webp';
64
+ case 'mp3': return 'audio/mpeg';
65
+ case 'wav': return 'audio/wav';
66
+ case 'ogg': return 'audio/ogg';
67
+ case 'mp4': return 'video/mp4';
68
+ case 'webm': return 'video/webm';
69
+ case 'mov': return 'video/quicktime';
70
+ default: return null;
71
+ }
72
+ }
73
+ export function isImageMime(mime) {
74
+ return SUPPORTED_IMAGE_MIME.has(mime);
75
+ }
76
+ export function isAudioMime(mime) {
77
+ return SUPPORTED_AUDIO_MIME.has(mime);
78
+ }
79
+ export function isVideoMime(mime) {
80
+ return SUPPORTED_VIDEO_MIME.has(mime);
81
+ }
82
+ export function toAnthropicContent(content) {
83
+ if (typeof content === 'string') {
84
+ return [{ type: 'text', text: content }];
85
+ }
86
+ return content.map(toAnthropicBlock);
87
+ }
88
+ function toAnthropicBlock(part) {
89
+ if (part.type === 'text') {
90
+ return { type: 'text', text: part.text };
91
+ }
92
+ const url = part.type === 'image_url'
93
+ ? part.image_url.url
94
+ : part.type === 'audio_url'
95
+ ? part.audio_url.url
96
+ : part.video_url.url;
97
+ const parsed = parseMediaUrl(url);
98
+ const source = parsed.kind === 'data'
99
+ ? { type: 'base64', media_type: parsed.mediaType, data: parsed.base64 }
100
+ : { type: 'url', url: parsed.url };
101
+ if (part.type === 'image_url') {
102
+ return { type: 'image', source };
103
+ }
104
+ return { type: 'document', source };
105
+ }
@@ -9,6 +9,11 @@
9
9
  *
10
10
  * Model routing — pass model name in pipeline stage (e.g. "anthropic/claude-3.5-sonnet").
11
11
  * Marketplace executes each stage with the named model; OpenRouter routes to provider.
12
+ *
13
+ * M1 — multimodal (image/audio/video) supported via `opts.messages`. The
14
+ * OpenRouter/OpenAI-compatible chat.completions API accepts our
15
+ * MultimodalMessage shape verbatim (image_url / audio_url / video_url),
16
+ * so we pass messages through unchanged.
12
17
  */
13
18
  import type { LLMProvider, GenerateOptions, GenerateResult } from '../types.js';
14
19
  import { z } from 'zod';
@@ -9,8 +9,14 @@
9
9
  *
10
10
  * Model routing — pass model name in pipeline stage (e.g. "anthropic/claude-3.5-sonnet").
11
11
  * Marketplace executes each stage with the named model; OpenRouter routes to provider.
12
+ *
13
+ * M1 — multimodal (image/audio/video) supported via `opts.messages`. The
14
+ * OpenRouter/OpenAI-compatible chat.completions API accepts our
15
+ * MultimodalMessage shape verbatim (image_url / audio_url / video_url),
16
+ * so we pass messages through unchanged.
12
17
  */
13
18
  import OpenAI from 'openai';
19
+ import { parseJsonLenient } from '../validate-inputs.js';
14
20
  const DEFAULT_BASE_URL = 'https://openrouter.ai/api/v1';
15
21
  export class OpenRouterProvider {
16
22
  name = 'openrouter';
@@ -41,6 +47,7 @@ export class OpenRouterProvider {
41
47
  }
42
48
  async generateText(prompt, opts = {}) {
43
49
  const model = opts.model || (opts.complexity === 'complex' ? this.complexModel : this.simpleModel);
50
+ const messages = buildOpenAIMessages(opts.messages, prompt, opts.system);
44
51
  const response = await this.client.chat.completions.create({
45
52
  model,
46
53
  max_tokens: opts.maxTokens ?? 2048,
@@ -51,10 +58,7 @@ export class OpenRouterProvider {
51
58
  ...(opts.responseFormat !== undefined
52
59
  ? { response_format: { type: opts.responseFormat } }
53
60
  : {}),
54
- messages: [
55
- ...(opts.system ? [{ role: 'system', content: opts.system }] : []),
56
- { role: 'user', content: prompt },
57
- ],
61
+ messages: messages,
58
62
  ...(opts.stopSequences ? { stop: opts.stopSequences } : {}),
59
63
  ...(opts.providerParams ?? {}),
60
64
  });
@@ -71,8 +75,51 @@ export class OpenRouterProvider {
71
75
  ...opts,
72
76
  system: opts.system ?? 'You are a JSON generator. Output only valid JSON, nothing else.',
73
77
  });
74
- const cleaned = text.replace(/^```json\s*/i, '').replace(/```\s*$/, '').trim();
75
- const parsed = JSON.parse(cleaned);
78
+ const parsed = parseJsonLenient(text);
76
79
  return schema.parse(parsed);
77
80
  }
78
81
  }
82
+ function buildOpenAIMessages(messages, fallbackPrompt, system) {
83
+ if (!messages || messages.length === 0) {
84
+ const out = [];
85
+ if (system)
86
+ out.push({ role: 'system', content: system });
87
+ out.push({ role: 'user', content: fallbackPrompt });
88
+ return out;
89
+ }
90
+ const out = [];
91
+ if (system)
92
+ out.push({ role: 'system', content: system });
93
+ for (const msg of messages) {
94
+ if (msg.role === 'system') {
95
+ const sysContent = typeof msg.content === 'string' ? msg.content : textFromParts(msg.content);
96
+ out.push({ role: 'system', content: sysContent });
97
+ continue;
98
+ }
99
+ const role = msg.role === 'assistant' ? 'assistant' : 'user';
100
+ if (typeof msg.content === 'string') {
101
+ out.push({ role, content: msg.content });
102
+ }
103
+ else {
104
+ out.push({ role, content: msg.content.map(toOpenAIPart) });
105
+ }
106
+ }
107
+ return out;
108
+ }
109
+ function toOpenAIPart(part) {
110
+ if (part.type === 'text')
111
+ return { type: 'text', text: part.text };
112
+ if (part.type === 'image_url') {
113
+ return { type: 'image_url', image_url: part.image_url };
114
+ }
115
+ if (part.type === 'audio_url') {
116
+ return { type: 'audio_url', audio_url: part.audio_url };
117
+ }
118
+ return { type: 'video_url', video_url: part.video_url };
119
+ }
120
+ function textFromParts(parts) {
121
+ return parts
122
+ .filter((p) => p.type === 'text')
123
+ .map((p) => (p.type === 'text' ? p.text : ''))
124
+ .join('\n');
125
+ }
package/dist/index.d.ts CHANGED
@@ -6,19 +6,25 @@
6
6
  */
7
7
  export type { LLMProvider, GenerateOptions, GenerateResult, Complexity, ProviderRegistry, TokenUsage, OutputFormat, OutputFormatViolation, } from './types.js';
8
8
  export { resolveProvider, StageOutputFormatError, StageSkillVersionMismatchError, StageMCPConfigError, } from './types.js';
9
+ export type { TextMessagePart, ImageMessagePart, AudioMessagePart, VideoMessagePart, MultimodalPart, MultimodalRole, MultimodalMessage, StagePrompt, } from './multimodal.js';
10
+ export { MultimodalModelUnsupportedError } from './multimodal.js';
9
11
  export { MiniMaxProvider } from './adapters/minimax.js';
10
12
  export type { MiniMaxProviderOptions } from './adapters/minimax.js';
11
13
  export { OpenRouterProvider } from './adapters/openrouter.js';
12
14
  export type { OpenRouterProviderOptions } from './adapters/openrouter.js';
15
+ export { OpenAIChatProvider } from './providers/openai-chat.js';
16
+ export type { OpenAIChatProviderOptions } from './providers/openai-chat.js';
17
+ export { AnthropicProvider } from './providers/anthropic.js';
18
+ export type { AnthropicProviderOptions } from './providers/anthropic.js';
13
19
  export { FallbackProvider, createFallbackProvider } from './fallback.js';
14
- export { PROVIDER_REGISTRY, getProvider, validateProviderName, supportsModel, validateProviderModel, listProviders, listSupportedModels, validateR6Spec, migrateProviderField, ProviderSpecNotFoundError, ProviderModelMismatchError, LLMProviderRegistry, ProviderMismatchError, UnknownProviderError, type Provider, type ProviderSpec, type R6StageInput, type R6SpecInput, type R6ValidationResult, } from './provider-registry.js';
20
+ export { PROVIDER_REGISTRY, getProvider, validateProviderName, supportsModel, validateProviderModel, listProviders, listSupportedModels, listVisionCapableModels, isVisionCapable, assertMultimodalSupported, validateR6Spec, migrateProviderField, ProviderSpecNotFoundError, ProviderModelMismatchError, LLMProviderRegistry, ProviderMismatchError, UnknownProviderError, type Provider, type ProviderSpec, type R6StageInput, type R6SpecInput, type R6ValidationResult, } from './provider-registry.js';
15
21
  export { expandPipelineText, resolveEnvVars, resolveEnvVarsInObject, loadPipelineYaml, parseVariableSpec, MissingEnvVarError, } from './resolve-vars.js';
16
22
  export type { EnvLike } from './resolve-vars.js';
17
23
  export { isRetryableStatus, computeBackoffMs, RetryExhaustedError, RetryAttemptError, DEFAULT_RETRY, DEFAULT_RETRYABLE_STATUSES, } from './retry.js';
18
24
  export type { RetryConfig, RetryBackoff } from './retry.js';
19
25
  export { parseComparison, parseWhenLiteral, evaluateComparison, evaluateWhen, shouldSkipStage, validateWhenShape, WhenParseError, } from './when.js';
20
26
  export type { WhenCondition, WhenCompareOp, ParsedComparison } from './when.js';
21
- export { NoopEventSink, CallbackEventSink, createDefaultSink, makeStageRetriedEvent, } from './streaming-events.js';
27
+ export { NoopEventSink, CallbackEventSink, createDefaultSink, makeStageRetriedEvent, makeStageWarnedEvent, } from './streaming-events.js';
22
28
  export type { PipelineEvent, PipelineEventType, PipelineEventSink, StageStartedEvent, StageCompletedEvent, StageFailedEvent, StageSkippedEvent, StageRetriedEvent, PipelineStartedEvent, PipelineCompletedEvent, PipelineFailedEvent, } from './streaming-events.js';
23
29
  export { validateRuntimeConstraints, collectRuntimeWarnings, defaultRuntimeConstraints, mergeRuntimeConstraints, } from './runtime-constraints.js';
24
30
  export type { NetworkConstraint, RequiredSkill, RuntimeConstraints, ConstraintContext, ConstraintWarning, StageLikeForConstraints, } from './runtime-constraints.js';
@@ -36,9 +42,15 @@ export { createModelResolver, resolveModelSync, DEFAULT_MODEL, type ModelResolve
36
42
  export { sha256Hex, computeSkillContentHash, } from './content-hash.js';
37
43
  export { executeStage, runPipelineV2, makeWhenResolve, parseUsesEntry, parseUsesList, validateOutputFormat, StageNotFoundError, StageForbiddenError, StageBadConfigError, type StageExecutorDeps, type StageContext, type StageExecutionResult, type RunPipelineOptions, type RunPipelineResult, type NestedCallRecord, type ResolvedUse, type SkillInvocationDetail, type MCPValidationResult, type MCPDetail, } from './stages.js';
38
44
  export { validateInputs, formatInputErrors, type InputDecl, type InputSpec, type InputValidationError, } from './validate-inputs.js';
39
- export { resolveInputRefs, resolveSpecialKeys, type PipelineRefContext, } from './pipeline-refs.js';
45
+ export { validateMultimodalInput, type MultimodalValidationError, type MultimodalValidationResult, } from './validate-inputs.js';
46
+ export { parseMediaUrl, detectMime, isImageMime, isAudioMime, isVideoMime, SUPPORTED_IMAGE_MIME, SUPPORTED_AUDIO_MIME, SUPPORTED_VIDEO_MIME, toAnthropicContent, type ParsedMedia, type AnthropicContentBlock, } from './adapters/multimodal-convert.js';
47
+ export { resolveInputRefs, resolveSpecialKeys, resolveDoubleBraceRefs, type PipelineRefContext, type DoubleBraceContext, } from './pipeline-refs.js';
40
48
  export { isToolSkill, invokeToolSkill, type ToolSkillContext, type ToolSkillResult, type ToolSkillHandler, } from './tools/tool-skills.js';
41
49
  export { validateOutputSpec, DEFAULT_OUTPUT_FORMAT, DEFAULT_OUTPUT_DELIVERY, DEFAULT_OUTPUT_EXPIRES_IN, MIN_OUTPUT_EXPIRES_IN, MAX_OUTPUT_EXPIRES_IN, type PipelineOutputSpec, type PipelineOutputDelivery, type PipelineOutputFormat, type PipelineOutputSpecError, } from './output-spec.js';
50
+ export { validateJsonSchema, MAX_VALIDATION_DEPTH, type JsonSchema, type JsonSchemaType, type OutputValidationViolation, type OutputValidationResult, } from './output-schema.js';
51
+ export { validateAgainstSchema } from './output-schema-validate.js';
52
+ export { OutputValidationError, OUTPUT_VALIDATION_RETRY_ATTEMPTS, isOutputValidationMode, type OutputValidationMode, } from './output-errors.js';
53
+ export { validateOutput, type ValidateOutputOptions, type ValidateOutputResult, } from './validate-inputs.js';
42
54
  export { analyzeCapabilities, type PipelineCapabilities, type NetworkCapability, type PipelineSpecLikeForCaps, type PipelineStageLikeForCaps, } from './capabilities.js';
43
55
  export { extractProducedFiles, globToRegex, MAX_FILE_BYTES, MAX_TOTAL_BYTES, MAX_FILES, type ProducedFile, type ExtractResult, } from './file-output.js';
44
56
  export { normalizeShellStage, ThrowingShellExecutor, NodeShellExecutor, ShellStageUnsupportedError, ShellStageExecError, ShellStageTimeoutError, SHELL_DEFAULT_TIMEOUT_MS, SHELL_MAX_TIMEOUT_MS, SHELL_MAX_OUTPUT_BYTES, type ShellStageSpec, type ShellExecutor, type ShellExecOptions, type ShellExecResult, } from './shell-stage.js';
@@ -62,7 +74,7 @@ export interface PipelineContext {
62
74
  export interface PipelineHooks {
63
75
  onStageStart?: (stageId: string) => void;
64
76
  onStageComplete?: (stageId: string, ms: number, output: string) => void;
65
- onLlmResponse?: (stageId: string, rawText: string, model: string) => void;
77
+ onLlmResponse?: (stageId: string, rawText: string, model: string) => void | Promise<void>;
66
78
  }
67
79
  import type { LLMProvider } from './types.js';
68
80
  export declare function runStage(stage: PipelineStageSpec, ctx: PipelineContext): Promise<string>;
@@ -70,3 +82,7 @@ export declare function runPipeline(spec: PipelineSpec, inputs: Record<string, u
70
82
  provider: LLMProvider;
71
83
  hooks?: PipelineHooks;
72
84
  }): Promise<Record<string, string>>;
85
+ export { LOOP_SCHEMA_VERSION, DEFAULT_MAX_ITERATIONS, ABSOLUTE_MAX_ITERATIONS, LoopConfigError, LoopMaxIterationsExceededError, parseExitExpression, evaluateExitExpression, executeLoop, type LoopOperator, type LoopExitExpression, type LoopSpec, type LoopIteration, type LoopTrace, type RunBodyStage, type LoopExecutionOptions, } from './loop.js';
86
+ export { MEMORY_SCHEMA_VERSION, MAX_MEMORY_VALUE_BYTES, InMemoryMemoryStore, R2MemoryStore, createMemoryStore, type MemoryScope, type MemoryPartition, type MemoryEntry, type MemoryStore, type MemoryR2Like, } from './memory.js';
87
+ export { parseTestSpec, loadTestSpecFile, TestSpecParseError, runAssertion, getPath, runSingleTest, runTestSuite, mockValueForField, buildMockProvider, extractStage, StageNotFoundInSpecError, renderText, renderJson, renderJunit, computeCoverage, renderCoverageText, loadCoverageForPipeline, discoverTestFiles, runConformanceDir, } from './testing/index.js';
88
+ export type { TestSpec, Assertion, AssertionResult, AssertionContext, SingleTestResult, RunTestOptions, RunSuiteOptions, ExtractedStage, CoverageReport, } from './testing/index.js';