@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
@@ -28,6 +28,161 @@
28
28
  * Strings get the regex substitution. Numbers, booleans, null return
29
29
  * unchanged.
30
30
  */
31
+ /* ------------------------------------------------------------------------- *
32
+ * `{{ }}` double-brace interpolation
33
+ *
34
+ * The third pattern in the documented trio (PIPELINE.md "Pre-existing
35
+ * interpolation patterns", specs §12): `{{var}}`, stage-input interpolation.
36
+ * It was documented from the start and never implemented — `$input.X` and
37
+ * `${stages.X.outputs.Y}` were built, this one was skipped, and no test
38
+ * covered it, so the gap survived. The 2019s avoided it entirely: stage input
39
+ * blocks never had `{{ }}` in them, so LLM stages masked the hole by
40
+ * receiving every input and every prior stage output as separate context
41
+ * blocks and reading from there instead. Tool skills get no such blocks and
42
+ * no model to guess with, so a literal `{{image_url}}` reached
43
+ * `image_describe` and the stage died on the literal.
44
+ *
45
+ * Accepted resolution order (2026-10-13):
46
+ * - `{{name}}` → stage input, then pipeline input. Stage wins.
47
+ * - `{{ inputs.X }}` → pipeline input, addressed explicitly
48
+ * - `{{stages.X.outputs}}` → prior stage output
49
+ * - unknown → left literal + a warning, never thrown
50
+ *
51
+ * Stage-wins shadowing is only half a decision: a silently shadowed pipeline
52
+ * input is exactly the kind of thing an author cannot debug from the output,
53
+ * so every collision is reported rather than quietly applied.
54
+ *
55
+ * Extends specs §12/§16, which define stage-output refs only as
56
+ * `${stages.X.outputs.Y}`. The canonical pipeline set writes the double-brace
57
+ * form instead, so both are honoured; that is a superset of the contract, not
58
+ * a contradiction of it.
59
+ * ------------------------------------------------------------------------- */
60
+ const DOUBLE_BRACE_PATTERN = /\{\{\s*([^{}]+?)\s*\}\}/g;
61
+ const DOUBLE_BRACE_WHOLE_PATTERN = /^\{\{\s*([^{}]+?)\s*\}\}$/;
62
+ const PIPELINE_SCOPED_RE = /^inputs\.([A-Za-z_][A-Za-z0-9_]*)$/;
63
+ const STAGE_OUTPUT_RE = /^stages\.([A-Za-z_][A-Za-z0-9_-]*)(?:\.outputs?)(?:\.([A-Za-z_][A-Za-z0-9_-]*))?$/;
64
+ const BARE_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
65
+ function report(ctx, message) {
66
+ if (ctx.onWarning)
67
+ ctx.onWarning(message);
68
+ else
69
+ console.warn(`[refs] ${message}`);
70
+ }
71
+ function lookupDoubleBrace(expression, ctx) {
72
+ // `{{ inputs.X }}` — the pipeline address, spelled out so it cannot be
73
+ // mistaken for a stage argument of the same name.
74
+ const scoped = PIPELINE_SCOPED_RE.exec(expression);
75
+ if (scoped) {
76
+ const key = scoped[1];
77
+ if (Object.prototype.hasOwnProperty.call(ctx.pipelineInputs, key)) {
78
+ return { found: true, value: ctx.pipelineInputs[key] };
79
+ }
80
+ report(ctx, `{{ ${expression} }} refers to a pipeline input that does not exist; left literal.`);
81
+ return { found: false, value: undefined };
82
+ }
83
+ // `{{ stages.X.outputs }}` / `{{ stages.X.outputs.Y }}`
84
+ const stageRef = STAGE_OUTPUT_RE.exec(expression);
85
+ if (stageRef) {
86
+ const stageId = stageRef[1];
87
+ const outputs = ctx.previousOutputs ?? {};
88
+ if (Object.prototype.hasOwnProperty.call(outputs, stageId)) {
89
+ return { found: true, value: outputs[stageId] ?? '' };
90
+ }
91
+ report(ctx, `{{ ${expression} }} refers to stage '${stageId}', which has not produced output yet; left literal.`);
92
+ return { found: false, value: undefined };
93
+ }
94
+ // `{{name}}` — stage argument first, pipeline input second.
95
+ if (!BARE_NAME_RE.test(expression)) {
96
+ report(ctx, `{{ ${expression} }} is not a recognised reference form; left literal.`);
97
+ return { found: false, value: undefined };
98
+ }
99
+ const stageInputs = ctx.stageInputs;
100
+ const inPipeline = Object.prototype.hasOwnProperty.call(ctx.pipelineInputs, expression);
101
+ if (stageInputs !== null && Object.prototype.hasOwnProperty.call(stageInputs, expression)) {
102
+ const resolved = resolveStageArgument(expression, ctx);
103
+ if (resolved.found) {
104
+ // Report shadowing only when the stage really carries its own value. An
105
+ // argument like `image_url: "{{image_url}}"` forwards to the pipeline, so
106
+ // calling that a collision would be noise — and it would be noise on
107
+ // every reference, which trains the author to ignore the warning.
108
+ if (inPipeline && !ctx.viaPipeline?.has(expression)) {
109
+ report(ctx, `{{ ${expression} }} is declared both as a stage argument and as a pipeline input; ` +
110
+ 'the stage argument wins. Rename one of them to make the intent explicit.');
111
+ }
112
+ return resolved;
113
+ }
114
+ }
115
+ if (inPipeline) {
116
+ ctx.viaPipeline?.add(expression);
117
+ return { found: true, value: ctx.pipelineInputs[expression] };
118
+ }
119
+ report(ctx, `{{ ${expression} }} does not match any stage argument or pipeline input; left literal.`);
120
+ return { found: false, value: undefined };
121
+ }
122
+ /**
123
+ * Resolve a stage argument as a value in its own right.
124
+ *
125
+ * A stage argument may itself be a template — every canonical spec writes
126
+ * `image_url: "{{image_url}}"`, naming the argument after the very ref it
127
+ * carries. Handing that raw string back as the value of `{{image_url}}`
128
+ * satisfies the lookup with the template itself, so the tool skill receives
129
+ * the literal and rejects it. So an argument is resolved in the same scope as
130
+ * anything else, with the name it is resolving marked as in-flight: reaching it
131
+ * again means the definitions are circular, which yields "not found" and lets
132
+ * the pipeline scope answer instead of spinning.
133
+ */
134
+ function resolveStageArgument(name, ctx) {
135
+ const stageInputs = ctx.stageInputs;
136
+ if (stageInputs === null || !Object.prototype.hasOwnProperty.call(stageInputs, name)) {
137
+ return { found: false, value: undefined };
138
+ }
139
+ const visiting = ctx.visiting ?? new Set();
140
+ if (visiting.has(name))
141
+ return { found: false, value: undefined };
142
+ const nested = new Set(visiting);
143
+ nested.add(name);
144
+ return { found: true, value: resolveDoubleBraceRefs(stageInputs[name], { ...ctx, visiting: nested }) };
145
+ }
146
+ function resolveDoubleBraceString(text, ctx) {
147
+ // A string that is nothing but one reference yields the native value, so an
148
+ // array argument stays an array. Same rule the $-forms follow — tool skills
149
+ // need native types, and JSON.stringify at the YAML layer is not available.
150
+ const whole = DOUBLE_BRACE_WHOLE_PATTERN.exec(text);
151
+ if (whole) {
152
+ const resolved = lookupDoubleBrace(whole[1], ctx);
153
+ return resolved.found ? resolved.value : text;
154
+ }
155
+ DOUBLE_BRACE_PATTERN.lastIndex = 0;
156
+ let touched = false;
157
+ const out = text.replace(DOUBLE_BRACE_PATTERN, (match, expression) => {
158
+ const resolved = lookupDoubleBrace(expression, ctx);
159
+ if (!resolved.found)
160
+ return match;
161
+ touched = true;
162
+ return typeof resolved.value === 'string' ? resolved.value : JSON.stringify(resolved.value);
163
+ });
164
+ return touched ? out : text;
165
+ }
166
+ export function resolveDoubleBraceRefs(value, ctx) {
167
+ // The two sets are per-resolution-run state. Seeding them here means every
168
+ // caller gets a correct cycle guard and shadowing report without having to
169
+ // know they exist, while nested calls inherit the same instances.
170
+ const root = ctx.visiting && ctx.viaPipeline
171
+ ? ctx
172
+ : { ...ctx, visiting: ctx.visiting ?? new Set(), viaPipeline: ctx.viaPipeline ?? new Set() };
173
+ if (typeof value === 'string')
174
+ return resolveDoubleBraceString(value, root);
175
+ if (Array.isArray(value))
176
+ return value.map((v) => resolveDoubleBraceRefs(v, root));
177
+ if (value && typeof value === 'object') {
178
+ const out = {};
179
+ for (const [k, v] of Object.entries(value)) {
180
+ out[k] = resolveDoubleBraceRefs(v, root);
181
+ }
182
+ return out;
183
+ }
184
+ return value;
185
+ }
31
186
  const INPUT_REF_PATTERN = /\$\{\s*input\.([A-Za-z_][A-Za-z0-9_]*)\s*\}|\$input\.([A-Za-z_][A-Za-z0-9_]*)/g;
32
187
  const STAGE_OUTPUT_REF_PATTERN = /\$\{\s*stages\.([A-Za-z_][A-Za-z0-9_.-]*)\.output\s*\}|\$stages\.([A-Za-z_][A-Za-z0-9_.-]*)\.output/g;
33
188
  const SPECIAL_KEYS = {
@@ -47,6 +47,8 @@ export interface ProviderSpec {
47
47
  readonly supportedModels: readonly string[];
48
48
  readonly baseUrl?: string;
49
49
  readonly apiKeyEnvVar?: string;
50
+ /** M1 NEW — models that accept multimodal (image/audio/video) inputs. */
51
+ readonly visionCapableModels?: readonly string[];
50
52
  }
51
53
  export declare const PROVIDER_REGISTRY: Readonly<Record<Provider, ProviderSpec>>;
52
54
  /**
@@ -86,6 +88,25 @@ export declare function validateProviderModel(providerName: string, modelName: s
86
88
  };
87
89
  /** All provider specs, in registry-insertion order. */
88
90
  export declare function listProviders(): ProviderSpec[];
91
+ /**
92
+ * M1 NEW — Is this (provider, model) combination capable of accepting
93
+ * multimodal input? Pure check; throws nothing. Unknown provider or
94
+ * provider without visionCapableModels → false.
95
+ */
96
+ export declare function isVisionCapable(providerName: Provider, modelName: string): boolean;
97
+ /**
98
+ * M1 NEW — Throw {@link MultimodalModelUnsupportedError} when (provider,
99
+ * model) does not accept multimodal input. Returns silently when the
100
+ * model is vision-capable. Use at trust boundaries (stage executor) to
101
+ * fail fast with a clear message.
102
+ */
103
+ export declare function assertMultimodalSupported(providerName: Provider, modelName: string): void;
104
+ /**
105
+ * M1 NEW — Return the vision-capable models for a provider (empty array
106
+ * if the provider is text-only or unknown). Used by error messages and
107
+ * CLI discovery.
108
+ */
109
+ export declare function listVisionCapableModels(providerName: Provider): readonly string[];
89
110
  /**
90
111
  * Models the provider supports (or `['*']` for gateways).
91
112
  * Returns the same readonly tuple as `spec.supportedModels` —
@@ -102,7 +123,7 @@ export interface R6StageInput {
102
123
  readonly provider?: string;
103
124
  readonly model?: string;
104
125
  readonly uses?: unknown;
105
- readonly prompt?: string;
126
+ readonly prompt?: string | readonly unknown[];
106
127
  }
107
128
  export interface R6SpecInput {
108
129
  readonly stages?: readonly R6StageInput[];
@@ -34,12 +34,15 @@ export const PROVIDER_REGISTRY = {
34
34
  name: 'openai',
35
35
  displayName: 'OpenAI',
36
36
  supportedModels: [
37
+ 'gpt-4',
38
+ 'gpt-4-turbo',
37
39
  'gpt-4o',
38
40
  'gpt-4o-mini',
39
41
  'o1-preview',
40
42
  'o1-mini',
41
43
  'gpt-3.5-turbo',
42
44
  ],
45
+ visionCapableModels: ['gpt-4-turbo', 'gpt-4o', 'gpt-4o-mini'],
43
46
  baseUrl: 'https://api.openai.com/v1',
44
47
  apiKeyEnvVar: 'OPENAI_API_KEY',
45
48
  },
@@ -50,6 +53,15 @@ export const PROVIDER_REGISTRY = {
50
53
  'claude-3-5-sonnet-20241022',
51
54
  'claude-3-5-haiku-20241022',
52
55
  'claude-3-opus-20240229',
56
+ 'claude-3-sonnet-20240229',
57
+ 'claude-3-haiku-20240307',
58
+ ],
59
+ visionCapableModels: [
60
+ 'claude-3-5-sonnet-20241022',
61
+ 'claude-3-5-haiku-20241022',
62
+ 'claude-3-opus-20240229',
63
+ 'claude-3-sonnet-20240229',
64
+ 'claude-3-haiku-20240307',
53
65
  ],
54
66
  baseUrl: 'https://api.anthropic.com/v1',
55
67
  apiKeyEnvVar: 'ANTHROPIC_API_KEY',
@@ -62,6 +74,7 @@ export const PROVIDER_REGISTRY = {
62
74
  'MiniMax-M2.7',
63
75
  'MiniMax-M1',
64
76
  ],
77
+ visionCapableModels: ['MiniMax-M3'],
65
78
  baseUrl: 'https://api.minimax.io/anthropic/v1',
66
79
  apiKeyEnvVar: 'MINIMAX_API_KEY',
67
80
  },
@@ -70,6 +83,13 @@ export const PROVIDER_REGISTRY = {
70
83
  displayName: 'OpenRouter',
71
84
  // OpenRouter is a multi-model gateway — it routes anything.
72
85
  supportedModels: ['*'],
86
+ // Conservative explicit list — adding new vision models is a code change.
87
+ visionCapableModels: [
88
+ 'openai/gpt-4o',
89
+ 'openai/gpt-4-turbo',
90
+ 'anthropic/claude-3.5-sonnet',
91
+ 'anthropic/claude-3-opus',
92
+ ],
73
93
  baseUrl: 'https://openrouter.ai/api/v1',
74
94
  apiKeyEnvVar: 'OPENROUTER_API_KEY',
75
95
  },
@@ -146,6 +166,40 @@ export function validateProviderModel(providerName, modelName) {
146
166
  export function listProviders() {
147
167
  return Object.values(PROVIDER_REGISTRY);
148
168
  }
169
+ /**
170
+ * M1 NEW — Is this (provider, model) combination capable of accepting
171
+ * multimodal input? Pure check; throws nothing. Unknown provider or
172
+ * provider without visionCapableModels → false.
173
+ */
174
+ export function isVisionCapable(providerName, modelName) {
175
+ const spec = PROVIDER_REGISTRY[providerName];
176
+ if (!spec)
177
+ return false;
178
+ const vision = spec.visionCapableModels ?? [];
179
+ return vision.includes(modelName);
180
+ }
181
+ /**
182
+ * M1 NEW — Throw {@link MultimodalModelUnsupportedError} when (provider,
183
+ * model) does not accept multimodal input. Returns silently when the
184
+ * model is vision-capable. Use at trust boundaries (stage executor) to
185
+ * fail fast with a clear message.
186
+ */
187
+ export function assertMultimodalSupported(providerName, modelName) {
188
+ if (isVisionCapable(providerName, modelName))
189
+ return;
190
+ const spec = PROVIDER_REGISTRY[providerName];
191
+ const vision = spec?.visionCapableModels ?? [];
192
+ throw new MultimodalModelUnsupportedError(providerName, modelName, vision);
193
+ }
194
+ /**
195
+ * M1 NEW — Return the vision-capable models for a provider (empty array
196
+ * if the provider is text-only or unknown). Used by error messages and
197
+ * CLI discovery.
198
+ */
199
+ export function listVisionCapableModels(providerName) {
200
+ const spec = PROVIDER_REGISTRY[providerName];
201
+ return spec?.visionCapableModels ?? [];
202
+ }
149
203
  /**
150
204
  * Models the provider supports (or `['*']` for gateways).
151
205
  * Returns the same readonly tuple as `spec.supportedModels` —
@@ -178,7 +232,9 @@ export function validateR6Spec(spec) {
178
232
  for (const stage of stages) {
179
233
  const isUsesStage = stage.uses !== undefined && stage.uses !== null;
180
234
  const hasModel = typeof stage.model === 'string' && stage.model.length > 0;
181
- const hasPrompt = typeof stage.prompt === 'string' && stage.prompt.length > 0;
235
+ const hasStringPrompt = typeof stage.prompt === 'string' && stage.prompt.length > 0;
236
+ const hasMultimodalPrompt = Array.isArray(stage.prompt) && stage.prompt.length > 0;
237
+ const hasPrompt = hasStringPrompt || hasMultimodalPrompt;
182
238
  const isLlmStage = hasModel || (hasPrompt && !isUsesStage);
183
239
  if (!isLlmStage)
184
240
  continue;
@@ -221,7 +277,10 @@ export function migrateProviderField(spec, defaultProvider = 'minimax') {
221
277
  const uses = stage['uses'];
222
278
  const hasUses = uses !== undefined && uses !== null;
223
279
  const hasModel = typeof stage['model'] === 'string' && stage['model'].length > 0;
224
- const hasPrompt = typeof stage['prompt'] === 'string' && stage['prompt'].length > 0;
280
+ const promptVal = stage['prompt'];
281
+ const hasStringPrompt = typeof promptVal === 'string' && promptVal.length > 0;
282
+ const hasMultimodalPrompt = Array.isArray(promptVal) && promptVal.length > 0;
283
+ const hasPrompt = hasStringPrompt || hasMultimodalPrompt;
225
284
  const isLlmStage = hasModel || (hasPrompt && !hasUses);
226
285
  if (!isLlmStage)
227
286
  return stage;
@@ -264,6 +323,7 @@ export class ProviderModelMismatchError extends Error {
264
323
  this.availableModels = availableModels;
265
324
  }
266
325
  }
326
+ import { MultimodalModelUnsupportedError } from './multimodal.js';
267
327
  /**
268
328
  * Thrown when a stage declares `provider: X` but X is not in the
269
329
  * registry passed to the executor.
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Anthropic Claude 3 provider — claude-3-opus / sonnet / haiku.
3
+ *
4
+ * Endpoint: https://api.anthropic.com/v1/messages (via @anthropic-ai/sdk)
5
+ * Auth: ANTHROPIC_API_KEY env var (or apiKey in constructor opts)
6
+ *
7
+ * Follows the MiniMaxProvider pattern (adapters/minimax.ts): MiniMax wraps
8
+ * an Anthropic-compatible endpoint, so the SDK usage, system-prompt
9
+ * handling (top-level `system`, never role:system in messages), and
10
+ * multimodal conversion (toAnthropicContent) are shared.
11
+ */
12
+ import type { LLMProvider, GenerateOptions, GenerateResult } from '../types.js';
13
+ import { z } from 'zod';
14
+ export interface AnthropicProviderOptions {
15
+ apiKey?: string;
16
+ baseURL?: string;
17
+ }
18
+ export declare class AnthropicProvider implements LLMProvider {
19
+ readonly name = "anthropic";
20
+ readonly models: readonly ["claude-3-opus-20240229", "claude-3-sonnet-20240229", "claude-3-haiku-20240307"];
21
+ readonly simpleModel = "claude-3-sonnet-20240229";
22
+ readonly complexModel = "claude-3-opus-20240229";
23
+ private client;
24
+ supports(model: string): boolean;
25
+ constructor(opts?: AnthropicProviderOptions);
26
+ generateText(prompt: string, opts?: GenerateOptions): Promise<GenerateResult>;
27
+ generateJson<T>(prompt: string, schema: z.ZodSchema<T>, opts?: GenerateOptions): Promise<T>;
28
+ }
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Anthropic Claude 3 provider — claude-3-opus / sonnet / haiku.
3
+ *
4
+ * Endpoint: https://api.anthropic.com/v1/messages (via @anthropic-ai/sdk)
5
+ * Auth: ANTHROPIC_API_KEY env var (or apiKey in constructor opts)
6
+ *
7
+ * Follows the MiniMaxProvider pattern (adapters/minimax.ts): MiniMax wraps
8
+ * an Anthropic-compatible endpoint, so the SDK usage, system-prompt
9
+ * handling (top-level `system`, never role:system in messages), and
10
+ * multimodal conversion (toAnthropicContent) are shared.
11
+ */
12
+ import Anthropic from '@anthropic-ai/sdk';
13
+ import { toAnthropicContent, } from '../adapters/multimodal-convert.js';
14
+ import { parseJsonLenient } from '../validate-inputs.js';
15
+ const DEFAULT_BASE_URL = 'https://api.anthropic.com';
16
+ export class AnthropicProvider {
17
+ name = 'anthropic';
18
+ models = [
19
+ 'claude-3-opus-20240229',
20
+ 'claude-3-sonnet-20240229',
21
+ 'claude-3-haiku-20240307',
22
+ ];
23
+ simpleModel = 'claude-3-sonnet-20240229';
24
+ complexModel = 'claude-3-opus-20240229';
25
+ client;
26
+ supports(model) {
27
+ return this.models.includes(model);
28
+ }
29
+ constructor(opts = {}) {
30
+ const procEnv = typeof process !== 'undefined' ? process.env : undefined;
31
+ const apiKey = opts.apiKey || procEnv?.ANTHROPIC_API_KEY;
32
+ if (!apiKey) {
33
+ throw new Error('AnthropicProvider: apiKey missing. Pass via opts.apiKey or set ANTHROPIC_API_KEY env var.');
34
+ }
35
+ this.client = new Anthropic({
36
+ apiKey,
37
+ baseURL: opts.baseURL || procEnv?.ANTHROPIC_BASE_URL || DEFAULT_BASE_URL,
38
+ });
39
+ }
40
+ async generateText(prompt, opts = {}) {
41
+ const model = opts.model ?? (opts.complexity === 'complex' ? this.complexModel : this.simpleModel);
42
+ const { messages, systemParts } = buildAnthropicMessages(opts.messages, prompt);
43
+ const system = joinSystem(opts.system, systemParts);
44
+ const response = await this.client.messages.create({
45
+ model,
46
+ max_tokens: opts.maxTokens ?? 2048,
47
+ temperature: opts.temperature ?? 0.7,
48
+ ...(opts.topP !== undefined ? { top_p: opts.topP } : {}),
49
+ ...(system !== undefined ? { system } : {}),
50
+ ...(opts.stopSequences ? { stop_sequences: opts.stopSequences } : {}),
51
+ messages: messages,
52
+ });
53
+ const text = response.content
54
+ .filter((block) => block.type === 'text')
55
+ .map((block) => block.text)
56
+ .join('');
57
+ const usage = {
58
+ inputTokens: response.usage.input_tokens,
59
+ outputTokens: response.usage.output_tokens,
60
+ };
61
+ return { text, usage };
62
+ }
63
+ async generateJson(prompt, schema, opts = {}) {
64
+ const jsonPrompt = `${prompt}\n\nRespond ONLY with valid JSON. No markdown, no prose, no code fences.`;
65
+ const { text } = await this.generateText(jsonPrompt, {
66
+ ...opts,
67
+ system: opts.system ?? 'You are a JSON generator. Output only valid JSON, nothing else.',
68
+ });
69
+ const parsed = parseJsonLenient(text);
70
+ return schema.parse(parsed);
71
+ }
72
+ }
73
+ /**
74
+ * Build the `messages` payload for `client.messages.create`. When multimodal
75
+ * messages are supplied we convert each to Anthropic content blocks; otherwise
76
+ * we fall back to wrapping the legacy string `prompt` as a single user turn.
77
+ *
78
+ * Anthropic API does NOT accept `role:'system'` on messages — system prompts
79
+ * are a top-level parameter. We extract any system-role messages and return
80
+ * them as `systemParts` for the caller to merge into the `system` field.
81
+ */
82
+ function buildAnthropicMessages(messages, fallbackPrompt) {
83
+ if (!messages || messages.length === 0) {
84
+ return { messages: [{ role: 'user', content: fallbackPrompt }], systemParts: [] };
85
+ }
86
+ const systemParts = [];
87
+ const out = [];
88
+ for (const msg of messages) {
89
+ if (msg.role === 'system') {
90
+ systemParts.push(typeof msg.content === 'string' ? msg.content : textFromParts(msg.content));
91
+ continue;
92
+ }
93
+ const role = msg.role === 'assistant' ? 'assistant' : 'user';
94
+ if (typeof msg.content === 'string') {
95
+ out.push({ role, content: msg.content });
96
+ }
97
+ else {
98
+ out.push({ role, content: toAnthropicContent(msg.content) });
99
+ }
100
+ }
101
+ if (out.length === 0) {
102
+ out.push({ role: 'user', content: '' });
103
+ }
104
+ return { messages: out, systemParts };
105
+ }
106
+ function textFromParts(parts) {
107
+ return parts
108
+ .filter((p) => p.type === 'text' && typeof p.text === 'string')
109
+ .map((p) => p.text)
110
+ .join('\n');
111
+ }
112
+ function joinSystem(existing, parts) {
113
+ const filtered = parts.filter((s) => s.length > 0);
114
+ if (filtered.length === 0)
115
+ return existing;
116
+ const joined = filtered.join('\n\n');
117
+ return existing && existing.length > 0 ? `${existing}\n\n${joined}` : joined;
118
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * OpenAI chat completions provider — gpt-4 / gpt-4-turbo / gpt-3.5-turbo.
3
+ *
4
+ * Endpoint: https://api.openai.com/v1/chat/completions (via openai SDK)
5
+ * Auth: OPENAI_API_KEY env var (or apiKey in constructor opts)
6
+ *
7
+ * Follows the OpenRouterProvider pattern (adapters/openrouter.ts):
8
+ * OpenAI-compatible chat.completions API, messages passed through verbatim.
9
+ * Multimodal messages (image/audio/video parts) are forwarded unchanged —
10
+ * the OpenAI API accepts image_url parts natively.
11
+ */
12
+ import type { LLMProvider, GenerateOptions, GenerateResult } from '../types.js';
13
+ import { z } from 'zod';
14
+ export interface OpenAIChatProviderOptions {
15
+ apiKey?: string;
16
+ baseURL?: string;
17
+ }
18
+ export declare class OpenAIChatProvider implements LLMProvider {
19
+ readonly name = "openai";
20
+ readonly models: readonly ["gpt-4", "gpt-4-turbo", "gpt-3.5-turbo"];
21
+ readonly simpleModel = "gpt-4";
22
+ readonly complexModel = "gpt-4-turbo";
23
+ private client;
24
+ supports(model: string): boolean;
25
+ constructor(opts?: OpenAIChatProviderOptions);
26
+ generateText(prompt: string, opts?: GenerateOptions): Promise<GenerateResult>;
27
+ generateJson<T>(prompt: string, schema: z.ZodSchema<T>, opts?: GenerateOptions): Promise<T>;
28
+ }
@@ -0,0 +1,106 @@
1
+ /**
2
+ * OpenAI chat completions provider — gpt-4 / gpt-4-turbo / gpt-3.5-turbo.
3
+ *
4
+ * Endpoint: https://api.openai.com/v1/chat/completions (via openai SDK)
5
+ * Auth: OPENAI_API_KEY env var (or apiKey in constructor opts)
6
+ *
7
+ * Follows the OpenRouterProvider pattern (adapters/openrouter.ts):
8
+ * OpenAI-compatible chat.completions API, messages passed through verbatim.
9
+ * Multimodal messages (image/audio/video parts) are forwarded unchanged —
10
+ * the OpenAI API accepts image_url parts natively.
11
+ */
12
+ import OpenAI from 'openai';
13
+ import { parseJsonLenient } from '../validate-inputs.js';
14
+ const DEFAULT_BASE_URL = 'https://api.openai.com/v1';
15
+ export class OpenAIChatProvider {
16
+ name = 'openai';
17
+ models = ['gpt-4', 'gpt-4-turbo', 'gpt-3.5-turbo'];
18
+ simpleModel = 'gpt-4';
19
+ complexModel = 'gpt-4-turbo';
20
+ client;
21
+ supports(model) {
22
+ return this.models.includes(model);
23
+ }
24
+ constructor(opts = {}) {
25
+ const procEnv = typeof process !== 'undefined' ? process.env : undefined;
26
+ const apiKey = opts.apiKey || procEnv?.OPENAI_API_KEY;
27
+ if (!apiKey) {
28
+ throw new Error('OpenAIChatProvider: apiKey missing. Pass via opts.apiKey or set OPENAI_API_KEY env var.');
29
+ }
30
+ this.client = new OpenAI({
31
+ apiKey,
32
+ baseURL: opts.baseURL || procEnv?.OPENAI_BASE_URL || DEFAULT_BASE_URL,
33
+ });
34
+ }
35
+ async generateText(prompt, opts = {}) {
36
+ const model = opts.model ?? (opts.complexity === 'complex' ? this.complexModel : this.simpleModel);
37
+ const messages = buildOpenAIMessages(opts.messages, prompt, opts.system);
38
+ const response = await this.client.chat.completions.create({
39
+ model,
40
+ max_tokens: opts.maxTokens ?? 2048,
41
+ temperature: opts.temperature ?? 0.7,
42
+ ...(opts.topP !== undefined ? { top_p: opts.topP } : {}),
43
+ messages: messages,
44
+ ...(opts.stopSequences ? { stop: opts.stopSequences } : {}),
45
+ });
46
+ const text = response.choices[0]?.message?.content ?? '';
47
+ const usage = {
48
+ inputTokens: response.usage?.prompt_tokens ?? 0,
49
+ outputTokens: response.usage?.completion_tokens ?? 0,
50
+ };
51
+ return { text, usage };
52
+ }
53
+ async generateJson(prompt, schema, opts = {}) {
54
+ const jsonPrompt = `${prompt}\n\nRespond ONLY with valid JSON. No markdown, no prose, no code fences.`;
55
+ const { text } = await this.generateText(jsonPrompt, {
56
+ ...opts,
57
+ system: opts.system ?? 'You are a JSON generator. Output only valid JSON, nothing else.',
58
+ });
59
+ const parsed = parseJsonLenient(text);
60
+ return schema.parse(parsed);
61
+ }
62
+ }
63
+ function buildOpenAIMessages(messages, fallbackPrompt, system) {
64
+ if (!messages || messages.length === 0) {
65
+ const out = [];
66
+ if (system)
67
+ out.push({ role: 'system', content: system });
68
+ out.push({ role: 'user', content: fallbackPrompt });
69
+ return out;
70
+ }
71
+ const out = [];
72
+ if (system)
73
+ out.push({ role: 'system', content: system });
74
+ for (const msg of messages) {
75
+ if (msg.role === 'system') {
76
+ const sysContent = typeof msg.content === 'string' ? msg.content : textFromParts(msg.content);
77
+ out.push({ role: 'system', content: sysContent });
78
+ continue;
79
+ }
80
+ const role = msg.role === 'assistant' ? 'assistant' : 'user';
81
+ if (typeof msg.content === 'string') {
82
+ out.push({ role, content: msg.content });
83
+ }
84
+ else {
85
+ out.push({ role, content: msg.content.map(toOpenAIPart) });
86
+ }
87
+ }
88
+ return out;
89
+ }
90
+ function toOpenAIPart(part) {
91
+ if (part.type === 'text')
92
+ return { type: 'text', text: part.text };
93
+ if (part.type === 'image_url') {
94
+ return { type: 'image_url', image_url: part.image_url };
95
+ }
96
+ if (part.type === 'audio_url') {
97
+ return { type: 'audio_url', audio_url: part.audio_url };
98
+ }
99
+ return { type: 'video_url', video_url: part.video_url };
100
+ }
101
+ function textFromParts(parts) {
102
+ return parts
103
+ .filter((p) => p.type === 'text')
104
+ .map((p) => (p.type === 'text' ? p.text : ''))
105
+ .join('\n');
106
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * OpenAI DALL-E 3 provider — text-to-image.
3
+ * Used by image_generate tool skill.
4
+ *
5
+ * Env: OPENAI_API_KEY
6
+ * Cost: $0.040/image (1024x1024 standard), $0.080 (hd)
7
+ * Sizes: 1024x1024, 1024x1792, 1792x1024
8
+ */
9
+ import { ToolSkillResult } from './types.js';
10
+ export type DallESize = '1024x1024' | '1024x1792' | '1792x1024';
11
+ export type DallEQuality = 'standard' | 'hd';
12
+ export interface OpenAIDallEInput {
13
+ prompt: string;
14
+ size?: DallESize;
15
+ quality?: DallEQuality;
16
+ n?: number;
17
+ }
18
+ export declare const MAX_N = 4;
19
+ export declare function openaiDallEGenerate(input: OpenAIDallEInput): Promise<ToolSkillResult>;
@@ -0,0 +1,41 @@
1
+ /**
2
+ * OpenAI DALL-E 3 provider — text-to-image.
3
+ * Used by image_generate tool skill.
4
+ *
5
+ * Env: OPENAI_API_KEY
6
+ * Cost: $0.040/image (1024x1024 standard), $0.080 (hd)
7
+ * Sizes: 1024x1024, 1024x1792, 1792x1024
8
+ */
9
+ import { ProviderError, requireEnv } from './types.js';
10
+ export const MAX_N = 4;
11
+ export async function openaiDallEGenerate(input) {
12
+ const apiKey = requireEnv('OPENAI_API_KEY');
13
+ const n = Math.min(input.n ?? 1, MAX_N);
14
+ if (n < 1)
15
+ throw new ProviderError('n must be >= 1', 'openai-dalle', 400);
16
+ const res = await fetch('https://api.openai.com/v1/images/generations', {
17
+ method: 'POST',
18
+ headers: {
19
+ Authorization: `Bearer ${apiKey}`,
20
+ 'Content-Type': 'application/json',
21
+ },
22
+ body: JSON.stringify({
23
+ model: 'dall-e-3',
24
+ prompt: input.prompt,
25
+ size: input.size ?? '1024x1024',
26
+ quality: input.quality ?? 'standard',
27
+ n,
28
+ }),
29
+ });
30
+ if (!res.ok) {
31
+ const errText = await res.text();
32
+ throw new ProviderError(`openai-dalle error ${res.status}: ${errText.slice(0, 500)}`, 'openai-dalle', res.status);
33
+ }
34
+ const data = (await res.json());
35
+ const images = data.data.map((img) => ({ url: img.url, revised_prompt: img.revised_prompt }));
36
+ return {
37
+ text: JSON.stringify({ images, ok: true }),
38
+ usage: { inputTokens: 0, outputTokens: 0 },
39
+ meta: { provider: 'openai', model: 'dall-e-3', size: input.size ?? '1024x1024', count: images.length },
40
+ };
41
+ }