@agentsmarket/pipeline-runtime 0.5.1 → 0.5.3

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.
package/dist/index.d.ts CHANGED
@@ -17,7 +17,7 @@ export type { OpenAIChatProviderOptions } from './providers/openai-chat.js';
17
17
  export { AnthropicProvider } from './providers/anthropic.js';
18
18
  export type { AnthropicProviderOptions } from './providers/anthropic.js';
19
19
  export { FallbackProvider, createFallbackProvider } from './fallback.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';
20
+ export { PROVIDER_REGISTRY, getProvider, validateProviderName, supportsModel, validateProviderModel, listProviders, listSupportedModels, listVisionCapableModels, isVisionCapable, assertMultimodalSupported, validateR6Spec, R6_PROVIDER_REQUIRED, migrateProviderField, ProviderSpecNotFoundError, ProviderModelMismatchError, LLMProviderRegistry, ProviderMismatchError, UnknownProviderError, type Provider, type ProviderSpec, type R6StageInput, type R6SpecInput, type R6ValidationResult, } from './provider-registry.js';
21
21
  export { expandPipelineText, resolveEnvVars, resolveEnvVarsInObject, loadPipelineYaml, parseVariableSpec, MissingEnvVarError, } from './resolve-vars.js';
22
22
  export type { EnvLike } from './resolve-vars.js';
23
23
  export { isRetryableStatus, computeBackoffMs, RetryExhaustedError, RetryAttemptError, DEFAULT_RETRY, DEFAULT_RETRYABLE_STATUSES, } from './retry.js';
@@ -44,7 +44,7 @@ export { executeStage, runPipelineV2, makeWhenResolve, parseUsesEntry, parseUses
44
44
  export { validateInputs, formatInputErrors, type InputDecl, type InputSpec, type InputValidationError, } from './validate-inputs.js';
45
45
  export { validateMultimodalInput, type MultimodalValidationError, type MultimodalValidationResult, } from './validate-inputs.js';
46
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';
47
+ export { resolveInputRefs, containsInputRef, resolveSpecialKeys, resolveDoubleBraceRefs, type PipelineRefContext, type DoubleBraceContext, } from './pipeline-refs.js';
48
48
  export { isToolSkill, invokeToolSkill, type ToolSkillContext, type ToolSkillResult, type ToolSkillHandler, } from './tools/tool-skills.js';
49
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
50
  export { validateJsonSchema, MAX_VALIDATION_DEPTH, type JsonSchema, type JsonSchemaType, type OutputValidationViolation, type OutputValidationResult, } from './output-schema.js';
package/dist/index.js CHANGED
@@ -11,7 +11,7 @@ export { OpenRouterProvider } from './adapters/openrouter.js';
11
11
  export { OpenAIChatProvider } from './providers/openai-chat.js';
12
12
  export { AnthropicProvider } from './providers/anthropic.js';
13
13
  export { FallbackProvider, createFallbackProvider } from './fallback.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';
14
+ export { PROVIDER_REGISTRY, getProvider, validateProviderName, supportsModel, validateProviderModel, listProviders, listSupportedModels, listVisionCapableModels, isVisionCapable, assertMultimodalSupported, validateR6Spec, R6_PROVIDER_REQUIRED, migrateProviderField, ProviderSpecNotFoundError, ProviderModelMismatchError, LLMProviderRegistry, ProviderMismatchError, UnknownProviderError, } from './provider-registry.js';
15
15
  export { expandPipelineText, resolveEnvVars, resolveEnvVarsInObject, loadPipelineYaml, parseVariableSpec, MissingEnvVarError, } from './resolve-vars.js';
16
16
  export { isRetryableStatus, computeBackoffMs, RetryExhaustedError, RetryAttemptError, DEFAULT_RETRY, DEFAULT_RETRYABLE_STATUSES, } from './retry.js';
17
17
  export { parseComparison, parseWhenLiteral, evaluateComparison, evaluateWhen, shouldSkipStage, validateWhenShape, WhenParseError, } from './when.js';
@@ -28,7 +28,7 @@ export { executeStage, runPipelineV2, makeWhenResolve, parseUsesEntry, parseUses
28
28
  export { validateInputs, formatInputErrors, } from './validate-inputs.js';
29
29
  export { validateMultimodalInput, } from './validate-inputs.js';
30
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';
31
+ export { resolveInputRefs, containsInputRef, resolveSpecialKeys, resolveDoubleBraceRefs, } from './pipeline-refs.js';
32
32
  export { isToolSkill, invokeToolSkill, } from './tools/tool-skills.js';
33
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
34
  export { validateJsonSchema, MAX_VALIDATION_DEPTH, } from './output-schema.js';
@@ -47,6 +47,18 @@ export interface DoubleBraceContext {
47
47
  visiting?: Set<string>;
48
48
  }
49
49
  export declare function resolveDoubleBraceRefs(value: unknown, ctx: DoubleBraceContext): unknown;
50
+ /**
51
+ * Whether a value carries an input reference (`$input.X` / `${input.X}`).
52
+ *
53
+ * Callers that must inspect a value BEFORE inputs are known use this to tell
54
+ * "this is a literal" from "this will be substituted later". Spec validation is
55
+ * the case that matters: `provider: ${input.provider}` cannot be checked against
56
+ * the provider registry at that point, because the actual value is not known yet.
57
+ *
58
+ * Lives here so the ref syntax has one definition — a second copy of the pattern
59
+ * in a consumer would drift the moment either side gains a form.
60
+ */
61
+ export declare function containsInputRef(value: unknown): boolean;
50
62
  export declare function resolveInputRefs(value: unknown, ctx: PipelineRefContext): unknown;
51
63
  /**
52
64
  * Substitute built-in special keys (\$today, \$now, \$year, \$month, \$weekday)
@@ -183,7 +183,28 @@ export function resolveDoubleBraceRefs(value, ctx) {
183
183
  }
184
184
  return value;
185
185
  }
186
- const INPUT_REF_PATTERN = /\$\{\s*input\.([A-Za-z_][A-Za-z0-9_]*)\s*\}|\$input\.([A-Za-z_][A-Za-z0-9_]*)/g;
186
+ /**
187
+ * Whether a value carries an input reference (`$input.X` / `${input.X}`).
188
+ *
189
+ * Callers that must inspect a value BEFORE inputs are known use this to tell
190
+ * "this is a literal" from "this will be substituted later". Spec validation is
191
+ * the case that matters: `provider: ${input.provider}` cannot be checked against
192
+ * the provider registry at that point, because the actual value is not known yet.
193
+ *
194
+ * Lives here so the ref syntax has one definition — a second copy of the pattern
195
+ * in a consumer would drift the moment either side gains a form.
196
+ */
197
+ export function containsInputRef(value) {
198
+ return typeof value === 'string' && INPUT_REF_PROBE.test(value);
199
+ }
200
+ // One definition of the ref syntax, two regexes over it. Substitution needs the
201
+ // global flag; the predicate must NOT have it — a global regex carries
202
+ // `lastIndex` between `.test()` calls, so `containsInputRef` answered
203
+ // true/false/true for the same string and every second stage that used
204
+ // `${input.provider}` was validated as a literal.
205
+ const INPUT_REF_SRC = String.raw `\$\{\s*input\.([A-Za-z_][A-Za-z0-9_]*)\s*\}|\$input\.([A-Za-z_][A-Za-z0-9_]*)`;
206
+ const INPUT_REF_PATTERN = new RegExp(INPUT_REF_SRC, 'g');
207
+ const INPUT_REF_PROBE = new RegExp(INPUT_REF_SRC);
187
208
  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;
188
209
  const SPECIAL_KEYS = {
189
210
  today: () => new Date().toISOString().slice(0, 10),
@@ -153,6 +153,15 @@ export interface R6ValidationResult {
153
153
  * 3. The stage's effective model = `stage.model ?? spec.defaults?.model ?? 'MiniMax-M3'`.
154
154
  * Stages using `uses:` (skill invocation) skip the gate entirely.
155
155
  */
156
+ /**
157
+ * The R6 remedy text, in one place.
158
+ *
159
+ * It used to name only `provider: minimax`, and that is how all six canonical
160
+ * pipelines came to hardcode it — the message was followed literally. Since a
161
+ * stage can now take its provider from a pipeline input, the message has to say
162
+ * so, otherwise the same trap is re-set for the next author.
163
+ */
164
+ export declare const R6_PROVIDER_REQUIRED: string;
156
165
  export declare function validateR6Spec(spec: R6SpecInput): R6ValidationResult;
157
166
  /**
158
167
  * One-shot migration: adds `provider: minimax` to every LLM stage
@@ -226,6 +226,17 @@ export function listSupportedModels(providerName) {
226
226
  * 3. The stage's effective model = `stage.model ?? spec.defaults?.model ?? 'MiniMax-M3'`.
227
227
  * Stages using `uses:` (skill invocation) skip the gate entirely.
228
228
  */
229
+ /**
230
+ * The R6 remedy text, in one place.
231
+ *
232
+ * It used to name only `provider: minimax`, and that is how all six canonical
233
+ * pipelines came to hardcode it — the message was followed literally. Since a
234
+ * stage can now take its provider from a pipeline input, the message has to say
235
+ * so, otherwise the same trap is re-set for the next author.
236
+ */
237
+ export const R6_PROVIDER_REQUIRED = `R6 requires explicit 'provider:' field (auto-dispatch by model name removed). ` +
238
+ `Add 'provider: minimax' (or openrouter/openai/anthropic/replicate), or pick it ` +
239
+ `per run with provider: \${input.provider} and a declared default under inputs:.`;
229
240
  export function validateR6Spec(spec) {
230
241
  const errors = [];
231
242
  const stages = spec.stages ?? [];
@@ -240,14 +251,18 @@ export function validateR6Spec(spec) {
240
251
  continue;
241
252
  const stageLabel = `Stage '${stage.id ?? '<no-id>'}'`;
242
253
  if (typeof stage.provider !== 'string' || stage.provider.length === 0) {
243
- errors.push(`${stageLabel}: R6 requires explicit 'provider:' field ` +
244
- `(auto-dispatch by model name removed). Add 'provider: minimax' ` +
245
- `(or openrouter/openai/anthropic/replicate).`);
254
+ errors.push(`${stageLabel}: ${R6_PROVIDER_REQUIRED}`);
246
255
  continue;
247
256
  }
248
257
  const effectiveModel = hasModel
249
258
  ? stage.model
250
259
  : (spec.defaults?.model ?? 'MiniMax-M3');
260
+ // A provider or model that will be substituted from pipeline inputs has no
261
+ // value yet at spec-validation time — this function only sees the spec. The
262
+ // runtime resolves both fields before dispatch and rejects an unknown
263
+ // provider there, against the real value.
264
+ if (containsInputRef(stage.provider) || containsInputRef(effectiveModel))
265
+ continue;
251
266
  try {
252
267
  validateProviderModel(stage.provider, effectiveModel);
253
268
  }
@@ -324,6 +339,7 @@ export class ProviderModelMismatchError extends Error {
324
339
  }
325
340
  }
326
341
  import { MultimodalModelUnsupportedError } from './multimodal.js';
342
+ import { containsInputRef } from './pipeline-refs.js';
327
343
  /**
328
344
  * Thrown when a stage declares `provider: X` but X is not in the
329
345
  * registry passed to the executor.
package/dist/stages.js CHANGED
@@ -260,6 +260,26 @@ export class StageBadConfigError extends Error {
260
260
  this.name = 'BAD_STAGE';
261
261
  }
262
262
  }
263
+ /**
264
+ * Substitute `${input.X}` / `$input.X` references in `stage.provider` and
265
+ * `stage.model` before they reach the resolver. Same walking strategy that
266
+ * already runs over `chainedInput` (stage arguments) at line ~830; literals
267
+ * pass through unchanged and unresolved references stay as their text form
268
+ * (matching resolveInputRefs:266 — pipeline-refs.ts).
269
+ *
270
+ * Returns a shallow clone when at least one field actually changes; returns
271
+ * the same `stage` object otherwise so we don't allocate per-call.
272
+ */
273
+ function resolveStageMetaRefs(stage, inputs) {
274
+ const resolvedProvider = resolveInputRefs(stage.provider, { inputs, previousOutputs: {} });
275
+ const resolvedModelRaw = resolveInputRefs(stage.model, { inputs, previousOutputs: {} });
276
+ const resolvedModel = typeof resolvedModelRaw === 'string' ? resolvedModelRaw : stage.model;
277
+ const providerChanged = typeof resolvedProvider === 'string' && resolvedProvider !== stage.provider;
278
+ const modelChanged = typeof stage.model === 'string' && resolvedModel !== stage.model;
279
+ if (!providerChanged && !modelChanged)
280
+ return stage;
281
+ return { ...stage, provider: resolvedProvider, model: resolvedModel };
282
+ }
263
283
  function resolveStageProvider(deps, stage, model) {
264
284
  // F12: --mock must override explicit per-stage `provider:` declarations,
265
285
  // otherwise canonical seeded pipelines (which all declare
@@ -274,7 +294,38 @@ function resolveStageProvider(deps, stage, model) {
274
294
  }
275
295
  return deps.registry.resolveWithSupports(stage.provider, model);
276
296
  }
277
- async function invokeSkill(skill, input, previousContext, skillLabel, provider, retry, retryCtx, outputFormat) {
297
+ /**
298
+ * Price one model call, tolerating a model whose price cannot be resolved.
299
+ *
300
+ * Whether a failed lookup is fatal depends on who is paying. Locally the buyer
301
+ * spends their own key — or runs a local model that has no price at all — so a
302
+ * missing price is informational and must not take the run down. On the server
303
+ * we pay from our own key, so an unpriced model is a real loss and stays fatal.
304
+ *
305
+ * This was not hypothetical: the resolver's static table holds exactly two
306
+ * model names, everything else falls through to OpenRouter, which matches on the
307
+ * full namespaced id. So a bare `gpt-4`, or any local model like `llama3`, threw
308
+ * *after* the model had answered and took the whole run down with it. All 24
309
+ * model references across the six canonical pipelines are `MiniMax-M3`, so no
310
+ * shipped pipeline ever reached it.
311
+ */
312
+ async function priceStageCost(deps, stageId, model, usage) {
313
+ try {
314
+ return await deps.pricing.resolveCostMicroUsdc(model, usage);
315
+ }
316
+ catch (err) {
317
+ if (!deps.isLocal)
318
+ throw err;
319
+ deps.eventSink?.emit(makeStageWarnedEvent({
320
+ stageId,
321
+ message: `no price resolved for model '${model}' — counting this stage as $0. ` +
322
+ 'Locally nothing is billed, so this does not change what you pay; the ' +
323
+ 'same run against the server would be refused.',
324
+ }));
325
+ return 0;
326
+ }
327
+ }
328
+ async function invokeSkill(skill, input, previousContext, skillLabel, provider, retry, retryCtx, outputFormat, maxTokens) {
278
329
  const t0 = Date.now();
279
330
  const inputStr = JSON.stringify(input ?? {}, null, 2);
280
331
  const fullMd = skill.full_md ?? '';
@@ -283,7 +334,11 @@ async function invokeSkill(skill, input, previousContext, skillLabel, provider,
283
334
  const ran = await runWithRetry(() => provider.generateText(composedPrompt, {
284
335
  system: `${skillLabel}\n${description}`,
285
336
  complexity: 'complex',
286
- maxTokens: 4096,
337
+ // Same reasoning-budget trap as the direct stage paths: a skill invoked
338
+ // from a stage has no way to declare its own budget, so it inherited the
339
+ // hardcoded 4096 and a reasoning model could spend all of it thinking,
340
+ // returning no text while the stage went on to validate it as JSON.
341
+ maxTokens: Number.isFinite(maxTokens) ? maxTokens : 4096,
287
342
  ...(outputFormat ? { outputFormat } : {}),
288
343
  }), retry, retryCtx);
289
344
  return { result: ran.value, durationMs: Date.now() - t0, attempts: ran.attempts };
@@ -536,7 +591,7 @@ correctionHint) {
536
591
  });
537
592
  continue;
538
593
  }
539
- const { result, durationMs } = await invokeSkill(skill, resolvedInput, previousContext, label, stageProvider, stage.retry, retryCtx, stage.output_format);
594
+ const { result, durationMs } = await invokeSkill(skill, resolvedInput, previousContext, label, stageProvider, stage.retry, retryCtx, stage.output_format, stage.maxTokens);
540
595
  await deps.onLlmResponse?.(`${stage.id}:${use.id}`, result.text, skillModel);
541
596
  lastResult = result;
542
597
  chainedInput = { input_from_previous_skill: result.text };
@@ -546,7 +601,7 @@ correctionHint) {
546
601
  duration_ms: durationMs,
547
602
  ok: true,
548
603
  });
549
- const skillCost = await deps.pricing.resolveCostMicroUsdc(skillModel, result.usage);
604
+ const skillCost = await priceStageCost(deps, use.id, skillModel, result.usage);
550
605
  totalCost += skillCost;
551
606
  totalUsage = {
552
607
  inputTokens: totalUsage.inputTokens + result.usage.inputTokens,
@@ -605,7 +660,7 @@ correctionHint) {
605
660
  model,
606
661
  system: resolvedSystem,
607
662
  complexity: stage.model?.includes('M3') || stage.model?.includes('opus') ? 'complex' : 'simple',
608
- maxTokens: typeof stage.maxTokens === 'number' ? stage.maxTokens : 4096,
663
+ maxTokens: Number.isFinite(stage.maxTokens) ? stage.maxTokens : 4096,
609
664
  fields: stage.fields,
610
665
  outputFormat: stage.output_format,
611
666
  messages: correctionHint
@@ -629,13 +684,13 @@ correctionHint) {
629
684
  model,
630
685
  system: resolvedSystem,
631
686
  complexity: stage.model?.includes('M3') || stage.model?.includes('opus') ? 'complex' : 'simple',
632
- maxTokens: typeof stage.maxTokens === 'number' ? stage.maxTokens : 4096,
687
+ maxTokens: Number.isFinite(stage.maxTokens) ? stage.maxTokens : 4096,
633
688
  fields: stage.fields,
634
689
  outputFormat: stage.output_format,
635
690
  });
636
691
  })(), stage.retry, retryCtx);
637
692
  const result = ran.value;
638
- const costMicroUsdc = await deps.pricing.resolveCostMicroUsdc(model, result.usage);
693
+ const costMicroUsdc = await priceStageCost(deps, stage.id, model, result.usage);
639
694
  await deps.onLlmResponse?.(stage.id, result.text, model);
640
695
  // When output_schema is present this stage runs under
641
696
  // runStageWithOutputValidation, which performs this check inside its retry
@@ -682,16 +737,21 @@ async function runOneStage(stage, shared) {
682
737
  for (const w of collectRuntimeWarnings(stage, shared.constraints)) {
683
738
  shared.emit({ type: 'stage.started', at: new Date().toISOString(), stageId, reason: 'normal' });
684
739
  }
740
+ // Substitute `${input.X}` references in provider/model before the resolver
741
+ // sees them. Without this a stage like `provider: ${input.provider}` reaches
742
+ // the registry with the verbatim string and throws
743
+ // `Provider '${input.provider}' is not registered`. Literals pass through.
744
+ const effectiveStage = resolveStageMetaRefs(stage, shared.opts.inputs);
685
745
  const t0 = Date.now();
686
746
  try {
687
- const stageModel = stage.model ?? shared.opts.spec.defaults?.model ?? 'MiniMax-M3';
747
+ const stageModel = effectiveStage.model ?? shared.opts.spec.defaults?.model ?? 'MiniMax-M3';
688
748
  const stageDeps = shared.opts.providerResolver
689
749
  ? { ...shared.opts.deps, provider: shared.opts.providerResolver(stageModel) }
690
750
  : shared.opts.deps;
691
751
  const stageDepsWithSink = shared.opts.eventSink
692
752
  ? { ...stageDeps, eventSink: shared.opts.eventSink }
693
753
  : stageDeps;
694
- const result = await runStageWithOutputValidation(stage, shared.opts.spec, { inputs: shared.opts.inputs, previousOutputs: shared.outputs }, stageDepsWithSink);
754
+ const result = await runStageWithOutputValidation(effectiveStage, shared.opts.spec, { inputs: shared.opts.inputs, previousOutputs: shared.outputs }, stageDepsWithSink);
695
755
  const ms = Date.now() - t0;
696
756
  shared.outputs[stageId] = result.output;
697
757
  shared.stageTimings.push({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentsmarket/pipeline-runtime",
3
- "version": "0.5.1",
3
+ "version": "0.5.3",
4
4
  "description": "Runtime for executing PIPELINE.md workflows (multi-skill orchestration). Provider-agnostic (MiniMax, Claude, OpenAI).",
5
5
  "license": "MIT",
6
6
  "type": "module",