@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.
- package/README.md +86 -1
- package/dist/adapters/minimax.d.ts +16 -8
- package/dist/adapters/minimax.js +105 -26
- package/dist/adapters/multimodal-convert.d.ts +54 -0
- package/dist/adapters/multimodal-convert.js +105 -0
- package/dist/adapters/openrouter.d.ts +5 -0
- package/dist/adapters/openrouter.js +53 -6
- package/dist/index.d.ts +20 -4
- package/dist/index.js +15 -3
- package/dist/loop.d.ts +90 -0
- package/dist/loop.js +200 -0
- package/dist/memory.d.ts +73 -0
- package/dist/memory.js +119 -0
- package/dist/model-resolver.d.ts +52 -1
- package/dist/multimodal.d.ts +43 -0
- package/dist/multimodal.js +23 -0
- package/dist/output-errors.d.ts +93 -0
- package/dist/output-errors.js +128 -0
- package/dist/output-schema-validate.d.ts +10 -0
- package/dist/output-schema-validate.js +149 -0
- package/dist/output-schema.d.ts +66 -0
- package/dist/output-schema.js +141 -0
- package/dist/pipeline-refs.d.ts +15 -0
- package/dist/pipeline-refs.js +155 -0
- package/dist/provider-registry.d.ts +22 -1
- package/dist/provider-registry.js +62 -2
- package/dist/providers/anthropic.d.ts +28 -0
- package/dist/providers/anthropic.js +118 -0
- package/dist/providers/openai-chat.d.ts +28 -0
- package/dist/providers/openai-chat.js +106 -0
- package/dist/providers/openai-dalle.d.ts +19 -0
- package/dist/providers/openai-dalle.js +41 -0
- package/dist/providers/openai-tts.d.ts +19 -0
- package/dist/providers/openai-tts.js +46 -0
- package/dist/providers/openai-vision.d.ts +15 -0
- package/dist/providers/openai-vision.js +43 -0
- package/dist/providers/openai-whisper.d.ts +16 -0
- package/dist/providers/openai-whisper.js +43 -0
- package/dist/providers/replicate.d.ts +19 -0
- package/dist/providers/replicate.js +61 -0
- package/dist/providers/types.d.ts +23 -0
- package/dist/providers/types.js +31 -0
- package/dist/runtime-constraints.d.ts +2 -1
- package/dist/stages.d.ts +14 -2
- package/dist/stages.js +339 -34
- package/dist/streaming-events.d.ts +17 -2
- package/dist/streaming-events.js +12 -0
- package/dist/testing/assertions.d.ts +17 -0
- package/dist/testing/assertions.js +149 -0
- package/dist/testing/conformance.d.ts +3 -0
- package/dist/testing/conformance.js +28 -0
- package/dist/testing/coverage.d.ts +11 -0
- package/dist/testing/coverage.js +35 -0
- package/dist/testing/index.d.ts +9 -0
- package/dist/testing/index.js +9 -0
- package/dist/testing/reporters/json.d.ts +5 -0
- package/dist/testing/reporters/json.js +23 -0
- package/dist/testing/reporters/junit.d.ts +5 -0
- package/dist/testing/reporters/junit.js +31 -0
- package/dist/testing/reporters/text.d.ts +5 -0
- package/dist/testing/reporters/text.js +36 -0
- package/dist/testing/runner.d.ts +25 -0
- package/dist/testing/runner.js +222 -0
- package/dist/testing/spec-parser.d.ts +366 -0
- package/dist/testing/spec-parser.js +60 -0
- package/dist/testing/stage-extractor.d.ts +16 -0
- package/dist/testing/stage-extractor.js +25 -0
- package/dist/tools/audio-transcribe.d.ts +11 -0
- package/dist/tools/audio-transcribe.js +45 -0
- package/dist/tools/image-describe.d.ts +12 -0
- package/dist/tools/image-describe.js +47 -0
- package/dist/tools/image-generate.d.ts +12 -0
- package/dist/tools/image-generate.js +47 -0
- package/dist/tools/memory-recall.d.ts +13 -0
- package/dist/tools/memory-recall.js +63 -0
- package/dist/tools/memory-shared.d.ts +8 -0
- package/dist/tools/memory-shared.js +8 -0
- package/dist/tools/memory-store.d.ts +14 -0
- package/dist/tools/memory-store.js +68 -0
- package/dist/tools/tool-skills.js +14 -0
- package/dist/tools/tts-synthesize.d.ts +12 -0
- package/dist/tools/tts-synthesize.js +50 -0
- package/dist/tools/video-generate.d.ts +12 -0
- package/dist/tools/video-generate.js +47 -0
- package/dist/types.d.ts +8 -0
- package/dist/validate-inputs.d.ts +115 -0
- package/dist/validate-inputs.js +273 -0
- package/package.json +3 -3
package/dist/stages.js
CHANGED
|
@@ -13,14 +13,18 @@
|
|
|
13
13
|
* Both server (passes DB-backed fetchSkill) and CLI (passes HTTP fetchSkill) use this.
|
|
14
14
|
*/
|
|
15
15
|
import { StageOutputFormatError, StageSkillVersionMismatchError, StageMCPConfigError, } from './types.js';
|
|
16
|
+
import { assertMultimodalSupported } from './provider-registry.js';
|
|
16
17
|
import { createModelResolver, } from './model-resolver.js';
|
|
17
18
|
import { computeSkillContentHash } from './content-hash.js';
|
|
18
19
|
import { shouldSkipStage } from './when.js';
|
|
19
|
-
import { resolveInputRefs, resolveSpecialKeys } from './pipeline-refs.js';
|
|
20
|
+
import { resolveInputRefs, resolveDoubleBraceRefs, resolveSpecialKeys } from './pipeline-refs.js';
|
|
20
21
|
import { isToolSkill, invokeToolSkill } from './tools/tool-skills.js';
|
|
21
22
|
import { isRetryableStatus, computeBackoffMs, RetryExhaustedError, DEFAULT_RETRY, } from './retry.js';
|
|
22
|
-
import { NoopEventSink, makeStartedEvent as makePipelineStartedEvent, makeCompletedEvent as makePipelineCompletedEvent, makeFailedEvent as makePipelineFailedEvent, makeStageStartedEvent, makeStageCompletedEvent, makeStageSkippedEvent, makeStageFailedEvent, makeStageRetriedEvent, } from './streaming-events.js';
|
|
23
|
+
import { NoopEventSink, makeStartedEvent as makePipelineStartedEvent, makeCompletedEvent as makePipelineCompletedEvent, makeFailedEvent as makePipelineFailedEvent, makeStageStartedEvent, makeStageCompletedEvent, makeStageSkippedEvent, makeStageFailedEvent, makeStageRetriedEvent, makeStageWarnedEvent, } from './streaming-events.js';
|
|
23
24
|
import { validateRuntimeConstraints, collectRuntimeWarnings, defaultRuntimeConstraints, } from './runtime-constraints.js';
|
|
25
|
+
import { validateJsonSchema } from './output-schema.js';
|
|
26
|
+
import { validateOutput, parseJsonLenient } from './validate-inputs.js';
|
|
27
|
+
import { OutputValidationError, OUTPUT_VALIDATION_RETRY_ATTEMPTS, isOutputValidationMode, truncateRawOutput, formatTruncatedRawOutput, } from './output-errors.js';
|
|
24
28
|
import { resolveStageOutputRefs } from './stage-output-refs.js';
|
|
25
29
|
import { normalizeShellStage, ShellStageUnsupportedError, ShellStageExecError, ShellStageTimeoutError, SHELL_DEFAULT_TIMEOUT_MS, } from './shell-stage.js';
|
|
26
30
|
import { expandComposition, } from './composition.js';
|
|
@@ -40,6 +44,55 @@ function buildInputsString(inputs) {
|
|
|
40
44
|
return '';
|
|
41
45
|
return entries.map(([k, v]) => `${k}: ${JSON.stringify(v)}\n`).join('');
|
|
42
46
|
}
|
|
47
|
+
/**
|
|
48
|
+
* All three documented interpolation engines, for `prompt` and `system`.
|
|
49
|
+
*
|
|
50
|
+
* Double-brace runs first so a substituted value that itself carries a
|
|
51
|
+
* stage-output or `${today}` reference is still resolved. `{{ }}` sees
|
|
52
|
+
* pipeline inputs and prior stage outputs only — a prompt has no stage
|
|
53
|
+
* argument block, which is the same scope the $-forms give it.
|
|
54
|
+
*
|
|
55
|
+
* Prompts used to keep their literals deliberately: the executor hands the
|
|
56
|
+
* model every input and every prior output as separate `Inputs:` and
|
|
57
|
+
* `Previous stage outputs:` blocks, so a model reads the values from there and
|
|
58
|
+
* a literal in the prompt was harmless noise. That is a sound argument, and it
|
|
59
|
+
* was the reason the scope was narrowed in the first place — but it left
|
|
60
|
+
* PIPELINE.md and specs §12 promising substitution in prompts that never
|
|
61
|
+
* happened, with all 21 canonical specs written against it. Accepted
|
|
62
|
+
* 2026-10-13, deliberately as its own commit: unlike a tool skill's arguments,
|
|
63
|
+
* this changes the text sent to the model for every pipeline at once, so it
|
|
64
|
+
* has to be revertible on its own.
|
|
65
|
+
*/
|
|
66
|
+
function resolvePromptRefs(value, inputs, previousOutputs, onWarning) {
|
|
67
|
+
if (typeof value === 'string') {
|
|
68
|
+
const braced = resolveDoubleBraceRefs(value, {
|
|
69
|
+
stageInputs: null,
|
|
70
|
+
pipelineInputs: inputs,
|
|
71
|
+
previousOutputs,
|
|
72
|
+
// `{{ }}` is documented for pipeline inputs and prior stage outputs
|
|
73
|
+
// only, so `{{date}}` or any other unbound name resolves to itself and
|
|
74
|
+
// stays literal. That is deliberate — guessing the author's intent
|
|
75
|
+
// would silently rewrite their prompt. But a literal that was meant to
|
|
76
|
+
// be a reference is a defect in the pipeline, and without a sink it
|
|
77
|
+
// reached nobody: report() fell back to console.warn, which in a
|
|
78
|
+
// Worker means the logs the author never reads.
|
|
79
|
+
onWarning,
|
|
80
|
+
});
|
|
81
|
+
const asText = typeof braced === 'string' ? braced : String(braced);
|
|
82
|
+
return resolveSpecialKeys(resolveStageOutputRefs(asText, previousOutputs));
|
|
83
|
+
}
|
|
84
|
+
if (Array.isArray(value)) {
|
|
85
|
+
return value.map((v) => resolvePromptRefs(v, inputs, previousOutputs));
|
|
86
|
+
}
|
|
87
|
+
if (value && typeof value === 'object') {
|
|
88
|
+
const out = {};
|
|
89
|
+
for (const [k, v] of Object.entries(value)) {
|
|
90
|
+
out[k] = resolvePromptRefs(v, inputs, previousOutputs);
|
|
91
|
+
}
|
|
92
|
+
return out;
|
|
93
|
+
}
|
|
94
|
+
return value;
|
|
95
|
+
}
|
|
43
96
|
export function makeWhenResolve(inputs, outputs) {
|
|
44
97
|
const stageRefRe = /^stages\.([A-Za-z_][A-Za-z0-9_]*)(?:\.outputs?(?:\.[A-Za-z_][A-Za-z0-9_]*)?)?$/;
|
|
45
98
|
const inputRefRe = /^inputs\.([A-Za-z_][A-Za-z0-9_]*)$/;
|
|
@@ -69,10 +122,17 @@ export function parseUsesEntry(raw) {
|
|
|
69
122
|
if (!trimmed)
|
|
70
123
|
return { id: '', version: null };
|
|
71
124
|
const at = trimmed.lastIndexOf('@');
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
125
|
+
const rawId = at <= 0 || at === trimmed.length - 1 ? trimmed : trimmed.slice(0, at);
|
|
126
|
+
// `tool:<name>` is the documented way to declare a runtime-native tool skill,
|
|
127
|
+
// but nothing ever stripped the prefix — the id stayed `tool:image_describe`,
|
|
128
|
+
// which is neither a marketplace skill nor a key in TOOL_SKILLS, so every
|
|
129
|
+
// stage using it died as "references missing skill". Both spellings must
|
|
130
|
+
// reach invokeToolSkill under the bare name. Only strip when what follows is
|
|
131
|
+
// really a tool skill: an unknown `tool:` prefix should keep failing loudly
|
|
132
|
+
// rather than being silently downgraded to a bare skill that also isn't there.
|
|
133
|
+
const id = rawId.startsWith('tool:') && isToolSkill(rawId.slice(5)) ? rawId.slice(5) : rawId;
|
|
134
|
+
const version = at <= 0 || at === trimmed.length - 1 ? null : trimmed.slice(at + 1);
|
|
135
|
+
return { id, version };
|
|
76
136
|
}
|
|
77
137
|
export function parseUsesList(stage) {
|
|
78
138
|
if (typeof stage.uses === 'string' && stage.uses.length > 0) {
|
|
@@ -130,7 +190,7 @@ export function validateOutputFormat(text, outputFormat, requiredFields) {
|
|
|
130
190
|
return;
|
|
131
191
|
let parsed;
|
|
132
192
|
try {
|
|
133
|
-
parsed =
|
|
193
|
+
parsed = parseJsonLenient(text);
|
|
134
194
|
}
|
|
135
195
|
catch (e) {
|
|
136
196
|
throw new StageOutputFormatError([
|
|
@@ -214,7 +274,38 @@ function resolveStageProvider(deps, stage, model) {
|
|
|
214
274
|
}
|
|
215
275
|
return deps.registry.resolveWithSupports(stage.provider, model);
|
|
216
276
|
}
|
|
217
|
-
|
|
277
|
+
/**
|
|
278
|
+
* Price one model call, tolerating a model whose price cannot be resolved.
|
|
279
|
+
*
|
|
280
|
+
* Whether a failed lookup is fatal depends on who is paying. Locally the buyer
|
|
281
|
+
* spends their own key — or runs a local model that has no price at all — so a
|
|
282
|
+
* missing price is informational and must not take the run down. On the server
|
|
283
|
+
* we pay from our own key, so an unpriced model is a real loss and stays fatal.
|
|
284
|
+
*
|
|
285
|
+
* This was not hypothetical: the resolver's static table holds exactly two
|
|
286
|
+
* model names, everything else falls through to OpenRouter, which matches on the
|
|
287
|
+
* full namespaced id. So a bare `gpt-4`, or any local model like `llama3`, threw
|
|
288
|
+
* *after* the model had answered and took the whole run down with it. All 24
|
|
289
|
+
* model references across the six canonical pipelines are `MiniMax-M3`, so no
|
|
290
|
+
* shipped pipeline ever reached it.
|
|
291
|
+
*/
|
|
292
|
+
async function priceStageCost(deps, stageId, model, usage) {
|
|
293
|
+
try {
|
|
294
|
+
return await deps.pricing.resolveCostMicroUsdc(model, usage);
|
|
295
|
+
}
|
|
296
|
+
catch (err) {
|
|
297
|
+
if (!deps.isLocal)
|
|
298
|
+
throw err;
|
|
299
|
+
deps.eventSink?.emit(makeStageWarnedEvent({
|
|
300
|
+
stageId,
|
|
301
|
+
message: `no price resolved for model '${model}' — counting this stage as $0. ` +
|
|
302
|
+
'Locally nothing is billed, so this does not change what you pay; the ' +
|
|
303
|
+
'same run against the server would be refused.',
|
|
304
|
+
}));
|
|
305
|
+
return 0;
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
async function invokeSkill(skill, input, previousContext, skillLabel, provider, retry, retryCtx, outputFormat, maxTokens) {
|
|
218
309
|
const t0 = Date.now();
|
|
219
310
|
const inputStr = JSON.stringify(input ?? {}, null, 2);
|
|
220
311
|
const fullMd = skill.full_md ?? '';
|
|
@@ -223,7 +314,11 @@ async function invokeSkill(skill, input, previousContext, skillLabel, provider,
|
|
|
223
314
|
const ran = await runWithRetry(() => provider.generateText(composedPrompt, {
|
|
224
315
|
system: `${skillLabel}\n${description}`,
|
|
225
316
|
complexity: 'complex',
|
|
226
|
-
|
|
317
|
+
// Same reasoning-budget trap as the direct stage paths: a skill invoked
|
|
318
|
+
// from a stage has no way to declare its own budget, so it inherited the
|
|
319
|
+
// hardcoded 4096 and a reasoning model could spend all of it thinking,
|
|
320
|
+
// returning no text while the stage went on to validate it as JSON.
|
|
321
|
+
maxTokens: Number.isFinite(maxTokens) ? maxTokens : 4096,
|
|
227
322
|
...(outputFormat ? { outputFormat } : {}),
|
|
228
323
|
}), retry, retryCtx);
|
|
229
324
|
return { result: ran.value, durationMs: Date.now() - t0, attempts: ran.attempts };
|
|
@@ -300,7 +395,14 @@ async function runWithRetry(op, retry, retryCtx) {
|
|
|
300
395
|
}
|
|
301
396
|
// Fallback constant (kept local — retry.ts owns the canonical list).
|
|
302
397
|
const DEFAULT_RETRYABLE_STATUSES_FALLBACK = [429, 503];
|
|
303
|
-
export async function executeStage(stage, pipeline, ctx, deps
|
|
398
|
+
export async function executeStage(stage, pipeline, ctx, deps,
|
|
399
|
+
/**
|
|
400
|
+
* Appended to the prompt on a validation retry. `output_retry` used to
|
|
401
|
+
* re-run the stage with byte-identical input, which only pays off when the
|
|
402
|
+
* failure was a one-off transport glitch; a stage whose output shape is
|
|
403
|
+
* wrong re-rolls the same wrong shape. See runStageWithOutputValidation.
|
|
404
|
+
*/
|
|
405
|
+
correctionHint) {
|
|
304
406
|
const mcpResult = validateMCPConfig(stage.mcp_servers, stage.mcp_tools, deps.validateMCPRefs);
|
|
305
407
|
const workingDir = typeof stage.working_dir === 'string' && stage.working_dir.length > 0
|
|
306
408
|
? stage.working_dir
|
|
@@ -314,11 +416,14 @@ export async function executeStage(stage, pipeline, ctx, deps) {
|
|
|
314
416
|
const usesList = parseUsesList(stage);
|
|
315
417
|
const hasUses = usesList.length > 0;
|
|
316
418
|
const hasModel = typeof stage.model === 'string' && stage.model.length > 0;
|
|
317
|
-
const
|
|
419
|
+
const hasStringPrompt = typeof stage.prompt === 'string' && stage.prompt.length > 0;
|
|
420
|
+
const hasMultimodalPrompt = Array.isArray(stage.prompt) && stage.prompt.length > 0;
|
|
421
|
+
const hasPrompt = hasStringPrompt || hasMultimodalPrompt;
|
|
318
422
|
const hasSystem = typeof stage.system === 'string' && stage.system.length > 0;
|
|
319
423
|
const hasShell = stage.shell !== undefined && stage.shell !== null;
|
|
320
|
-
|
|
321
|
-
|
|
424
|
+
const hasLoop = stage.loop !== undefined && stage.loop !== null;
|
|
425
|
+
if (!hasShell && !hasUses && !hasModel && !hasPrompt && !hasLoop) {
|
|
426
|
+
throw new StageBadConfigError(`Stage '${stage.id}' requires one of: 'shell' (shell stage, CLI --local only), 'uses' (skill stage), 'model'+'prompt' (LLM stage), 'loop' (M6.2 iterative executor), or just 'prompt' with default model`);
|
|
322
427
|
}
|
|
323
428
|
if (hasShell) {
|
|
324
429
|
if (!deps.shellExecutor) {
|
|
@@ -369,7 +474,15 @@ export async function executeStage(stage, pipeline, ctx, deps) {
|
|
|
369
474
|
}
|
|
370
475
|
}
|
|
371
476
|
if (hasUses) {
|
|
372
|
-
|
|
477
|
+
// `inputs:` (plural) is how 16 of the 18 stage blocks in the canonical set
|
|
478
|
+
// declare per-stage arguments, and `input:` (singular) is how the runtime
|
|
479
|
+
// has always read them. Nothing ever reconciled the two, so every stage
|
|
480
|
+
// written the plural way silently received the *pipeline's* inputs instead
|
|
481
|
+
// of its own — image-captioner's store_caption asks memory_store for a
|
|
482
|
+
// pipeline_id it never got, and the handler reported "pipeline_id is
|
|
483
|
+
// required" for an input that was sitting right there in the YAML.
|
|
484
|
+
const stageInputs = stage.inputs;
|
|
485
|
+
let chainedInput = stage.input ?? stageInputs ?? ctx.inputs;
|
|
373
486
|
let lastResult = null;
|
|
374
487
|
const nestedCalls = [];
|
|
375
488
|
const usesDetails = [];
|
|
@@ -424,16 +537,27 @@ export async function executeStage(stage, pipeline, ctx, deps) {
|
|
|
424
537
|
const skillModel = deps.modelResolver.resolveSync(stage, pipeline, skill);
|
|
425
538
|
resolvedModel = skillModel;
|
|
426
539
|
const stageProvider = resolveStageProvider(deps, stage, skillModel);
|
|
540
|
+
const stageInputsScope = (typeof chainedInput === 'object' && chainedInput !== null && !Array.isArray(chainedInput))
|
|
541
|
+
? chainedInput
|
|
542
|
+
: null;
|
|
427
543
|
const resolvedInput = typeof chainedInput === 'string'
|
|
428
544
|
? resolveStageOutputRefs(chainedInput, ctx.previousOutputs)
|
|
429
|
-
|
|
545
|
+
// `{{ }}` first, then the `$`-forms. Both are spec'd as supported and
|
|
546
|
+
// the canonical specs use the double-brace spelling for stage arguments
|
|
547
|
+
// (see resolveDoubleBraceRefs); tool skills get no context blocks and
|
|
548
|
+
// no model to guess with, so a literal reaching them fails the stage.
|
|
549
|
+
: resolveInputRefs(resolveDoubleBraceRefs(chainedInput, {
|
|
550
|
+
stageInputs: stageInputsScope,
|
|
551
|
+
pipelineInputs: ctx.inputs,
|
|
552
|
+
previousOutputs: ctx.previousOutputs,
|
|
553
|
+
}), { inputs: ctx.inputs, previousOutputs: ctx.previousOutputs });
|
|
430
554
|
if (isToolSkill(use.id)) {
|
|
431
555
|
const toolT0 = Date.now();
|
|
432
556
|
const toolResult = await invokeToolSkill(use.id, resolvedInput, {
|
|
433
557
|
agentId: deps.getCurrentAgentId(),
|
|
434
558
|
});
|
|
435
559
|
const toolDurationMs = Date.now() - toolT0;
|
|
436
|
-
deps.onLlmResponse?.(`${stage.id}:${use.id}`, toolResult.text, 'tool');
|
|
560
|
+
await deps.onLlmResponse?.(`${stage.id}:${use.id}`, toolResult.text, 'tool');
|
|
437
561
|
lastResult = {
|
|
438
562
|
text: toolResult.text,
|
|
439
563
|
usage: toolResult.usage,
|
|
@@ -447,8 +571,8 @@ export async function executeStage(stage, pipeline, ctx, deps) {
|
|
|
447
571
|
});
|
|
448
572
|
continue;
|
|
449
573
|
}
|
|
450
|
-
const { result, durationMs } = await invokeSkill(skill, resolvedInput, previousContext, label, stageProvider, stage.retry, retryCtx, stage.output_format);
|
|
451
|
-
deps.onLlmResponse?.(`${stage.id}:${use.id}`, result.text, skillModel);
|
|
574
|
+
const { result, durationMs } = await invokeSkill(skill, resolvedInput, previousContext, label, stageProvider, stage.retry, retryCtx, stage.output_format, stage.maxTokens);
|
|
575
|
+
await deps.onLlmResponse?.(`${stage.id}:${use.id}`, result.text, skillModel);
|
|
452
576
|
lastResult = result;
|
|
453
577
|
chainedInput = { input_from_previous_skill: result.text };
|
|
454
578
|
nestedCalls.push({
|
|
@@ -457,7 +581,7 @@ export async function executeStage(stage, pipeline, ctx, deps) {
|
|
|
457
581
|
duration_ms: durationMs,
|
|
458
582
|
ok: true,
|
|
459
583
|
});
|
|
460
|
-
const skillCost = await deps.
|
|
584
|
+
const skillCost = await priceStageCost(deps, use.id, skillModel, result.usage);
|
|
461
585
|
totalCost += skillCost;
|
|
462
586
|
totalUsage = {
|
|
463
587
|
inputTokens: totalUsage.inputTokens + result.usage.inputTokens,
|
|
@@ -477,25 +601,85 @@ export async function executeStage(stage, pipeline, ctx, deps) {
|
|
|
477
601
|
...(workingDir ? { working_dir: workingDir, working_dir_ignored_on_server: workingDirIgnoredOnServer } : {}),
|
|
478
602
|
};
|
|
479
603
|
}
|
|
604
|
+
// Unresolved `{{ }}` references become `stage.warned` events rather than
|
|
605
|
+
// console output. A Worker's stdout goes to Cloudflare logs, which the
|
|
606
|
+
// pipeline's author never opens — so a literal that was meant to be a
|
|
607
|
+
// reference shipped in the deliverable with nothing anywhere to say so.
|
|
608
|
+
// Warnings only: the pipeline still runs, because refusing would turn a
|
|
609
|
+
// cosmetic authoring problem into a failed run the buyer paid for.
|
|
610
|
+
const onWarning = deps.eventSink
|
|
611
|
+
? (message) => {
|
|
612
|
+
deps.eventSink.emit(makeStageWarnedEvent({ stageId: stage.id, message }));
|
|
613
|
+
}
|
|
614
|
+
: undefined;
|
|
480
615
|
const model = deps.modelResolver.resolveSync(stage, pipeline);
|
|
481
616
|
const stageProvider = resolveStageProvider(deps, stage, model);
|
|
482
617
|
const resolvedSystem = stage.system
|
|
483
|
-
?
|
|
618
|
+
? resolvePromptRefs(stage.system, ctx.inputs, ctx.previousOutputs, onWarning)
|
|
484
619
|
: stage.system;
|
|
485
|
-
const
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
}
|
|
620
|
+
const stageProviderName = (stage.provider ?? stageProvider.name);
|
|
621
|
+
// M1 — multimodal prompt path. When stage.prompt is an array of
|
|
622
|
+
// MultimodalMessage, route through opts.messages and prepend a
|
|
623
|
+
// synthetic user message carrying the prior context + inputs.
|
|
624
|
+
// Text-only callers keep the legacy single-string path unchanged.
|
|
625
|
+
const rawPrompt = stage.prompt;
|
|
626
|
+
const isMultimodal = Array.isArray(rawPrompt);
|
|
627
|
+
if (isMultimodal) {
|
|
628
|
+
assertMultimodalSupported(stageProviderName, model);
|
|
629
|
+
}
|
|
630
|
+
const ctxPrefix = previousContext.length > 0 || inputsString.length > 0
|
|
631
|
+
? `${previousContext}Inputs:\n${inputsString}\n---\n\n`
|
|
632
|
+
: '';
|
|
633
|
+
// Resolved here rather than inside generateText so a nested
|
|
634
|
+
// image_url.url and a text part are interpolated by the same walk.
|
|
635
|
+
const resolvedPromptMessages = isMultimodal
|
|
636
|
+
? resolvePromptRefs(rawPrompt, ctx.inputs, ctx.previousOutputs)
|
|
637
|
+
: null;
|
|
638
|
+
const ran = await runWithRetry(() => isMultimodal
|
|
639
|
+
? stageProvider.generateText('', {
|
|
640
|
+
model,
|
|
641
|
+
system: resolvedSystem,
|
|
642
|
+
complexity: stage.model?.includes('M3') || stage.model?.includes('opus') ? 'complex' : 'simple',
|
|
643
|
+
maxTokens: Number.isFinite(stage.maxTokens) ? stage.maxTokens : 4096,
|
|
644
|
+
fields: stage.fields,
|
|
645
|
+
outputFormat: stage.output_format,
|
|
646
|
+
messages: correctionHint
|
|
647
|
+
? [
|
|
648
|
+
...(ctxPrefix.length > 0 ? [{ role: 'user', content: ctxPrefix }] : []),
|
|
649
|
+
{ role: 'user', content: correctionHint },
|
|
650
|
+
...(resolvedPromptMessages ?? []),
|
|
651
|
+
]
|
|
652
|
+
: ctxPrefix.length > 0
|
|
653
|
+
? [
|
|
654
|
+
{ role: 'user', content: ctxPrefix },
|
|
655
|
+
...(resolvedPromptMessages ?? []),
|
|
656
|
+
]
|
|
657
|
+
: (resolvedPromptMessages ?? []),
|
|
658
|
+
})
|
|
659
|
+
: (() => {
|
|
660
|
+
const stringPrompt = typeof stage.prompt === 'string' ? stage.prompt : '';
|
|
661
|
+
const resolvedPrompt = resolvePromptRefs(stringPrompt, ctx.inputs, ctx.previousOutputs, onWarning);
|
|
662
|
+
const prompt = `${previousContext}Inputs:\n${inputsString}\n---\n\n${correctionHint ? `${correctionHint}\n\n` : ''}${resolvedPrompt}`;
|
|
663
|
+
return stageProvider.generateText(prompt, {
|
|
664
|
+
model,
|
|
665
|
+
system: resolvedSystem,
|
|
666
|
+
complexity: stage.model?.includes('M3') || stage.model?.includes('opus') ? 'complex' : 'simple',
|
|
667
|
+
maxTokens: Number.isFinite(stage.maxTokens) ? stage.maxTokens : 4096,
|
|
668
|
+
fields: stage.fields,
|
|
669
|
+
outputFormat: stage.output_format,
|
|
670
|
+
});
|
|
671
|
+
})(), stage.retry, retryCtx);
|
|
495
672
|
const result = ran.value;
|
|
496
|
-
const costMicroUsdc = await deps.
|
|
497
|
-
deps.onLlmResponse?.(stage.id, result.text, model);
|
|
498
|
-
|
|
673
|
+
const costMicroUsdc = await priceStageCost(deps, stage.id, model, result.usage);
|
|
674
|
+
await deps.onLlmResponse?.(stage.id, result.text, model);
|
|
675
|
+
// When output_schema is present this stage runs under
|
|
676
|
+
// runStageWithOutputValidation, which performs this check inside its retry
|
|
677
|
+
// loop so output_retry can recover a wrong-shaped answer. Throwing here
|
|
678
|
+
// would pre-empt that loop, so the check is skipped for exactly that case
|
|
679
|
+
// and nothing else.
|
|
680
|
+
if (!stage.output_schema) {
|
|
681
|
+
validateOutputFormat(result.text, stage.output_format, stage.fields);
|
|
682
|
+
}
|
|
499
683
|
return {
|
|
500
684
|
output: result.text,
|
|
501
685
|
costMicroUsdc,
|
|
@@ -530,6 +714,9 @@ async function runOneStage(stage, shared) {
|
|
|
530
714
|
for (const w of collectRuntimeWarnings(stage, shared.constraints)) {
|
|
531
715
|
shared.emit({ type: 'stage.started', at: new Date().toISOString(), stageId, reason: 'normal' });
|
|
532
716
|
}
|
|
717
|
+
for (const w of collectRuntimeWarnings(stage, shared.constraints)) {
|
|
718
|
+
shared.emit({ type: 'stage.started', at: new Date().toISOString(), stageId, reason: 'normal' });
|
|
719
|
+
}
|
|
533
720
|
const t0 = Date.now();
|
|
534
721
|
try {
|
|
535
722
|
const stageModel = stage.model ?? shared.opts.spec.defaults?.model ?? 'MiniMax-M3';
|
|
@@ -539,7 +726,7 @@ async function runOneStage(stage, shared) {
|
|
|
539
726
|
const stageDepsWithSink = shared.opts.eventSink
|
|
540
727
|
? { ...stageDeps, eventSink: shared.opts.eventSink }
|
|
541
728
|
: stageDeps;
|
|
542
|
-
const result = await
|
|
729
|
+
const result = await runStageWithOutputValidation(stage, shared.opts.spec, { inputs: shared.opts.inputs, previousOutputs: shared.outputs }, stageDepsWithSink);
|
|
543
730
|
const ms = Date.now() - t0;
|
|
544
731
|
shared.outputs[stageId] = result.output;
|
|
545
732
|
shared.stageTimings.push({
|
|
@@ -574,6 +761,124 @@ async function runOneStage(stage, shared) {
|
|
|
574
761
|
return { kind: 'failed', stageId, error: err };
|
|
575
762
|
}
|
|
576
763
|
}
|
|
764
|
+
/**
|
|
765
|
+
* M5 — wraps `executeStage` with optional JSON Schema output validation.
|
|
766
|
+
*
|
|
767
|
+
* Behavior by `output_retry` mode:
|
|
768
|
+
* - 'none' — single attempt; fail-fast on validation error
|
|
769
|
+
* - 'single' — at most 2 attempts (initial + 1 retry)
|
|
770
|
+
* - 'loop' — at most 3 attempts (initial + 2 retries)
|
|
771
|
+
*
|
|
772
|
+
* Independent of HTTP-status `retry:` (which is handled inside
|
|
773
|
+
* `runWithRetry` per call). Output validation retries invoke the entire
|
|
774
|
+
* stage body again (LLM call + output) — this is the M5 contract.
|
|
775
|
+
*/
|
|
776
|
+
async function runStageWithOutputValidation(stage, pipeline, ctx, deps) {
|
|
777
|
+
const schema = stage.output_schema;
|
|
778
|
+
// Default was `none` (a single attempt) until M38. `single` is now the
|
|
779
|
+
// default: the correction hint below makes a retry far more likely to
|
|
780
|
+
// succeed than a blind re-roll, and the cost is only incurred on a stage
|
|
781
|
+
// that would otherwise have failed outright.
|
|
782
|
+
//
|
|
783
|
+
// An author who wants one attempt still says so — `output_retry: 'none'`
|
|
784
|
+
// is explicit and unchanged. This changes only the unset case.
|
|
785
|
+
const mode = isOutputValidationMode(stage.output_retry)
|
|
786
|
+
? stage.output_retry
|
|
787
|
+
: 'single';
|
|
788
|
+
if (!schema) {
|
|
789
|
+
// No schema means no retry loop, so output_format is enforced inside
|
|
790
|
+
// executeStage as before.
|
|
791
|
+
return executeStage(stage, pipeline, ctx, deps);
|
|
792
|
+
}
|
|
793
|
+
const schemaCheck = validateJsonSchema(schema);
|
|
794
|
+
if (!schemaCheck.ok) {
|
|
795
|
+
throw new OutputValidationError(stage.id, 1, schemaCheck.violations);
|
|
796
|
+
}
|
|
797
|
+
const mode2 = mode;
|
|
798
|
+
const maxAttempts = OUTPUT_VALIDATION_RETRY_ATTEMPTS[mode2];
|
|
799
|
+
let lastViolations = [];
|
|
800
|
+
// M-diagnostics: capture the raw model output from each attempt so a
|
|
801
|
+
// final-attempt `OutputValidationError` can carry what the LLM actually
|
|
802
|
+
// produced, not just a parser-derived summary. Without this, operators
|
|
803
|
+
// faced with `$: expected type object, got string` were forced to
|
|
804
|
+
// deduce whether the model emitted JSON, a JSON-in-quotes string, or
|
|
805
|
+
// a prose block — exactly the diagnostic we now pin next to
|
|
806
|
+
// `failure_reason` via the server route.
|
|
807
|
+
let lastRawOutput;
|
|
808
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
809
|
+
const result = await executeStage(stage, pipeline, ctx, deps, attempt > 1 ? correctionHint(stage.id, schema, lastViolations) : undefined);
|
|
810
|
+
lastRawOutput = result.output;
|
|
811
|
+
// output_format first: it is the stricter check, and it used to throw from
|
|
812
|
+
// inside executeStage — before this loop — which pre-empted output_retry
|
|
813
|
+
// entirely. That is why a prose answer to a structured_json stage failed
|
|
814
|
+
// on the first attempt with no correction ever offered, while a schema
|
|
815
|
+
// mismatch (a softer failure) did retry.
|
|
816
|
+
try {
|
|
817
|
+
validateOutputFormat(result.output, stage.output_format, stage.fields);
|
|
818
|
+
}
|
|
819
|
+
catch (formatErr) {
|
|
820
|
+
if (attempt >= maxAttempts) {
|
|
821
|
+
// Wrap the stricter output_format failure into OutputValidationError
|
|
822
|
+
// so the server route treats it the same as a schema mismatch:
|
|
823
|
+
// one error class, one diagnostic payload, one persisted `output_json`.
|
|
824
|
+
// validateOutputFormat throws StageOutputFormatError with violations
|
|
825
|
+
// shaped differently than OutputValidationViolation, so we re-shape.
|
|
826
|
+
const message = formatErr instanceof Error ? formatErr.message : String(formatErr);
|
|
827
|
+
const truncated = truncateRawOutput(result.output);
|
|
828
|
+
throw new OutputValidationError(stage.id, attempt, [{ path: '$', message, schema_path: '$' }], formatTruncatedRawOutput(truncated), truncated.truncatedChars);
|
|
829
|
+
}
|
|
830
|
+
lastViolations = [{
|
|
831
|
+
path: '$',
|
|
832
|
+
message: formatErr instanceof Error ? formatErr.message : String(formatErr),
|
|
833
|
+
schema_path: '$',
|
|
834
|
+
}];
|
|
835
|
+
continue;
|
|
836
|
+
}
|
|
837
|
+
const validation = validateOutput(result.output, schema);
|
|
838
|
+
if (validation.ok) {
|
|
839
|
+
return result;
|
|
840
|
+
}
|
|
841
|
+
lastViolations = validation.violations;
|
|
842
|
+
if (attempt >= maxAttempts) {
|
|
843
|
+
const truncated = truncateRawOutput(result.output);
|
|
844
|
+
throw new OutputValidationError(stage.id, attempt, lastViolations, formatTruncatedRawOutput(truncated), truncated.truncatedChars);
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
// Unreachable in practice — the loop always `throw`s on the final
|
|
848
|
+
// attempt — but TypeScript needs a terminator and we keep it
|
|
849
|
+
// symmetric: attach whatever the most recent attempt produced.
|
|
850
|
+
const truncated = lastRawOutput !== undefined ? truncateRawOutput(lastRawOutput) : undefined;
|
|
851
|
+
throw new OutputValidationError(stage.id, maxAttempts, lastViolations, truncated ? formatTruncatedRawOutput(truncated) : undefined, truncated?.truncatedChars);
|
|
852
|
+
}
|
|
853
|
+
/**
|
|
854
|
+
* Tell the model exactly what its previous answer got wrong.
|
|
855
|
+
*
|
|
856
|
+
* `output_retry` re-ran the stage with byte-identical input, so it only helped
|
|
857
|
+
* when the failure was a transient glitch; a stage that answers in prose when
|
|
858
|
+
* the schema wants an object just produces prose again. Feeding the violations
|
|
859
|
+
* back turns the retry into a correction, which is the whole point of having a
|
|
860
|
+
* retry mode at all.
|
|
861
|
+
*
|
|
862
|
+
* The schema is echoed because the model is not shown it — validation happens
|
|
863
|
+
* after the call returns, so "expected type object, got string" is the first
|
|
864
|
+
* time it hears about the shape it was supposed to produce.
|
|
865
|
+
*/
|
|
866
|
+
function correctionHint(stageId, schema, violations) {
|
|
867
|
+
const lines = violations
|
|
868
|
+
.slice(0, 8)
|
|
869
|
+
.map((v) => `- ${v.path || '$'}: ${v.message}`)
|
|
870
|
+
.join('\n');
|
|
871
|
+
return [
|
|
872
|
+
`Your previous answer for stage "${stageId}" was rejected by output validation:`,
|
|
873
|
+
lines,
|
|
874
|
+
'',
|
|
875
|
+
'Reply again with ONLY a JSON value matching this schema. No prose, no explanation,',
|
|
876
|
+
'no markdown code fences — the first character must be { or [ and the last } or ].',
|
|
877
|
+
'',
|
|
878
|
+
'Schema:',
|
|
879
|
+
JSON.stringify(schema, null, 2),
|
|
880
|
+
].join('\n');
|
|
881
|
+
}
|
|
577
882
|
export async function runPipelineV2(opts) {
|
|
578
883
|
const outputs = {};
|
|
579
884
|
const stageTimings = [];
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
* Default no-op sink is fine for plain CLI usage. Replace with a richer sink
|
|
9
9
|
* when integrating into a UI / webhook / log aggregator.
|
|
10
10
|
*/
|
|
11
|
-
export type PipelineEventType = 'pipeline.started' | 'pipeline.completed' | 'pipeline.failed' | 'stage.started' | 'stage.completed' | 'stage.failed' | 'stage.skipped' | 'stage.retry';
|
|
11
|
+
export type PipelineEventType = 'pipeline.started' | 'pipeline.completed' | 'pipeline.failed' | 'stage.started' | 'stage.completed' | 'stage.failed' | 'stage.skipped' | 'stage.warned' | 'stage.retry';
|
|
12
12
|
interface PipelineEventBase {
|
|
13
13
|
readonly type: PipelineEventType;
|
|
14
14
|
readonly at: string;
|
|
@@ -22,7 +22,7 @@ export interface PipelineLifecycleEvent extends PipelineEventBase {
|
|
|
22
22
|
readonly error?: string;
|
|
23
23
|
}
|
|
24
24
|
export interface StageLifecycleEvent extends PipelineEventBase {
|
|
25
|
-
readonly type: 'stage.started' | 'stage.completed' | 'stage.failed' | 'stage.skipped';
|
|
25
|
+
readonly type: 'stage.started' | 'stage.completed' | 'stage.failed' | 'stage.skipped' | 'stage.warned';
|
|
26
26
|
readonly stageId: string;
|
|
27
27
|
readonly ms?: number;
|
|
28
28
|
readonly costMicroUsdc?: number;
|
|
@@ -30,6 +30,8 @@ export interface StageLifecycleEvent extends PipelineEventBase {
|
|
|
30
30
|
readonly reason?: 'when-false' | 'error' | 'normal';
|
|
31
31
|
readonly error?: string;
|
|
32
32
|
readonly output?: string;
|
|
33
|
+
/** Set on `stage.warned` — the non-fatal problem, verbatim. */
|
|
34
|
+
readonly message?: string;
|
|
33
35
|
}
|
|
34
36
|
/**
|
|
35
37
|
* Emitted once per retry attempt by `runWithRetry` whenever a retryable
|
|
@@ -107,6 +109,19 @@ export declare function makeStageFailedEvent(args: {
|
|
|
107
109
|
stageId: string;
|
|
108
110
|
error: string;
|
|
109
111
|
}): StageLifecycleEvent;
|
|
112
|
+
/**
|
|
113
|
+
* A non-fatal problem worth telling the author about.
|
|
114
|
+
*
|
|
115
|
+
* For unresolved `{{ }}` references: `{{ }}` resolves only pipeline inputs and
|
|
116
|
+
* prior stage outputs, so anything else in that shape stays literal and would
|
|
117
|
+
* otherwise ship inside the deliverable with no signal anywhere. The pipeline
|
|
118
|
+
* still runs — a literal prompt is the author's business, and failing a run the
|
|
119
|
+
* buyer has already paid for would be a worse outcome than the warning.
|
|
120
|
+
*/
|
|
121
|
+
export declare function makeStageWarnedEvent(args: {
|
|
122
|
+
stageId: string;
|
|
123
|
+
message: string;
|
|
124
|
+
}): StageLifecycleEvent;
|
|
110
125
|
export declare function makeStageRetriedEvent(args: {
|
|
111
126
|
stageId: string;
|
|
112
127
|
attempt: number;
|
package/dist/streaming-events.js
CHANGED
|
@@ -118,6 +118,18 @@ export function makeStageSkippedEvent(stageId) {
|
|
|
118
118
|
export function makeStageFailedEvent(args) {
|
|
119
119
|
return { type: 'stage.failed', at: nowIso(), stageId: args.stageId, error: args.error, reason: 'error' };
|
|
120
120
|
}
|
|
121
|
+
/**
|
|
122
|
+
* A non-fatal problem worth telling the author about.
|
|
123
|
+
*
|
|
124
|
+
* For unresolved `{{ }}` references: `{{ }}` resolves only pipeline inputs and
|
|
125
|
+
* prior stage outputs, so anything else in that shape stays literal and would
|
|
126
|
+
* otherwise ship inside the deliverable with no signal anywhere. The pipeline
|
|
127
|
+
* still runs — a literal prompt is the author's business, and failing a run the
|
|
128
|
+
* buyer has already paid for would be a worse outcome than the warning.
|
|
129
|
+
*/
|
|
130
|
+
export function makeStageWarnedEvent(args) {
|
|
131
|
+
return { type: 'stage.warned', at: nowIso(), stageId: args.stageId, message: args.message };
|
|
132
|
+
}
|
|
121
133
|
export function makeStageRetriedEvent(args) {
|
|
122
134
|
return {
|
|
123
135
|
type: 'stage.retry',
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { Assertion } from './spec-parser.js';
|
|
2
|
+
export interface AssertionResult {
|
|
3
|
+
passed: boolean;
|
|
4
|
+
message: string;
|
|
5
|
+
expected?: unknown;
|
|
6
|
+
actual?: unknown;
|
|
7
|
+
duration_ms: number;
|
|
8
|
+
}
|
|
9
|
+
export interface AssertionContext {
|
|
10
|
+
baseDir?: string;
|
|
11
|
+
}
|
|
12
|
+
/** Traverse dot path with [n] array indices. Returns {found, value}. */
|
|
13
|
+
export declare function getPath(root: unknown, dotPath: string): {
|
|
14
|
+
found: boolean;
|
|
15
|
+
value?: unknown;
|
|
16
|
+
};
|
|
17
|
+
export declare function runAssertion(output: unknown, assertion: Assertion, ctx?: AssertionContext): AssertionResult;
|