@agentsmarket/pipeline-runtime 0.5.0 → 0.5.1
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 +299 -29
- 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/dist/webhook.js +0 -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([
|
|
@@ -300,7 +360,14 @@ async function runWithRetry(op, retry, retryCtx) {
|
|
|
300
360
|
}
|
|
301
361
|
// Fallback constant (kept local — retry.ts owns the canonical list).
|
|
302
362
|
const DEFAULT_RETRYABLE_STATUSES_FALLBACK = [429, 503];
|
|
303
|
-
export async function executeStage(stage, pipeline, ctx, deps
|
|
363
|
+
export async function executeStage(stage, pipeline, ctx, deps,
|
|
364
|
+
/**
|
|
365
|
+
* Appended to the prompt on a validation retry. `output_retry` used to
|
|
366
|
+
* re-run the stage with byte-identical input, which only pays off when the
|
|
367
|
+
* failure was a one-off transport glitch; a stage whose output shape is
|
|
368
|
+
* wrong re-rolls the same wrong shape. See runStageWithOutputValidation.
|
|
369
|
+
*/
|
|
370
|
+
correctionHint) {
|
|
304
371
|
const mcpResult = validateMCPConfig(stage.mcp_servers, stage.mcp_tools, deps.validateMCPRefs);
|
|
305
372
|
const workingDir = typeof stage.working_dir === 'string' && stage.working_dir.length > 0
|
|
306
373
|
? stage.working_dir
|
|
@@ -314,11 +381,14 @@ export async function executeStage(stage, pipeline, ctx, deps) {
|
|
|
314
381
|
const usesList = parseUsesList(stage);
|
|
315
382
|
const hasUses = usesList.length > 0;
|
|
316
383
|
const hasModel = typeof stage.model === 'string' && stage.model.length > 0;
|
|
317
|
-
const
|
|
384
|
+
const hasStringPrompt = typeof stage.prompt === 'string' && stage.prompt.length > 0;
|
|
385
|
+
const hasMultimodalPrompt = Array.isArray(stage.prompt) && stage.prompt.length > 0;
|
|
386
|
+
const hasPrompt = hasStringPrompt || hasMultimodalPrompt;
|
|
318
387
|
const hasSystem = typeof stage.system === 'string' && stage.system.length > 0;
|
|
319
388
|
const hasShell = stage.shell !== undefined && stage.shell !== null;
|
|
320
|
-
|
|
321
|
-
|
|
389
|
+
const hasLoop = stage.loop !== undefined && stage.loop !== null;
|
|
390
|
+
if (!hasShell && !hasUses && !hasModel && !hasPrompt && !hasLoop) {
|
|
391
|
+
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
392
|
}
|
|
323
393
|
if (hasShell) {
|
|
324
394
|
if (!deps.shellExecutor) {
|
|
@@ -369,7 +439,15 @@ export async function executeStage(stage, pipeline, ctx, deps) {
|
|
|
369
439
|
}
|
|
370
440
|
}
|
|
371
441
|
if (hasUses) {
|
|
372
|
-
|
|
442
|
+
// `inputs:` (plural) is how 16 of the 18 stage blocks in the canonical set
|
|
443
|
+
// declare per-stage arguments, and `input:` (singular) is how the runtime
|
|
444
|
+
// has always read them. Nothing ever reconciled the two, so every stage
|
|
445
|
+
// written the plural way silently received the *pipeline's* inputs instead
|
|
446
|
+
// of its own — image-captioner's store_caption asks memory_store for a
|
|
447
|
+
// pipeline_id it never got, and the handler reported "pipeline_id is
|
|
448
|
+
// required" for an input that was sitting right there in the YAML.
|
|
449
|
+
const stageInputs = stage.inputs;
|
|
450
|
+
let chainedInput = stage.input ?? stageInputs ?? ctx.inputs;
|
|
373
451
|
let lastResult = null;
|
|
374
452
|
const nestedCalls = [];
|
|
375
453
|
const usesDetails = [];
|
|
@@ -424,16 +502,27 @@ export async function executeStage(stage, pipeline, ctx, deps) {
|
|
|
424
502
|
const skillModel = deps.modelResolver.resolveSync(stage, pipeline, skill);
|
|
425
503
|
resolvedModel = skillModel;
|
|
426
504
|
const stageProvider = resolveStageProvider(deps, stage, skillModel);
|
|
505
|
+
const stageInputsScope = (typeof chainedInput === 'object' && chainedInput !== null && !Array.isArray(chainedInput))
|
|
506
|
+
? chainedInput
|
|
507
|
+
: null;
|
|
427
508
|
const resolvedInput = typeof chainedInput === 'string'
|
|
428
509
|
? resolveStageOutputRefs(chainedInput, ctx.previousOutputs)
|
|
429
|
-
|
|
510
|
+
// `{{ }}` first, then the `$`-forms. Both are spec'd as supported and
|
|
511
|
+
// the canonical specs use the double-brace spelling for stage arguments
|
|
512
|
+
// (see resolveDoubleBraceRefs); tool skills get no context blocks and
|
|
513
|
+
// no model to guess with, so a literal reaching them fails the stage.
|
|
514
|
+
: resolveInputRefs(resolveDoubleBraceRefs(chainedInput, {
|
|
515
|
+
stageInputs: stageInputsScope,
|
|
516
|
+
pipelineInputs: ctx.inputs,
|
|
517
|
+
previousOutputs: ctx.previousOutputs,
|
|
518
|
+
}), { inputs: ctx.inputs, previousOutputs: ctx.previousOutputs });
|
|
430
519
|
if (isToolSkill(use.id)) {
|
|
431
520
|
const toolT0 = Date.now();
|
|
432
521
|
const toolResult = await invokeToolSkill(use.id, resolvedInput, {
|
|
433
522
|
agentId: deps.getCurrentAgentId(),
|
|
434
523
|
});
|
|
435
524
|
const toolDurationMs = Date.now() - toolT0;
|
|
436
|
-
deps.onLlmResponse?.(`${stage.id}:${use.id}`, toolResult.text, 'tool');
|
|
525
|
+
await deps.onLlmResponse?.(`${stage.id}:${use.id}`, toolResult.text, 'tool');
|
|
437
526
|
lastResult = {
|
|
438
527
|
text: toolResult.text,
|
|
439
528
|
usage: toolResult.usage,
|
|
@@ -448,7 +537,7 @@ export async function executeStage(stage, pipeline, ctx, deps) {
|
|
|
448
537
|
continue;
|
|
449
538
|
}
|
|
450
539
|
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);
|
|
540
|
+
await deps.onLlmResponse?.(`${stage.id}:${use.id}`, result.text, skillModel);
|
|
452
541
|
lastResult = result;
|
|
453
542
|
chainedInput = { input_from_previous_skill: result.text };
|
|
454
543
|
nestedCalls.push({
|
|
@@ -477,25 +566,85 @@ export async function executeStage(stage, pipeline, ctx, deps) {
|
|
|
477
566
|
...(workingDir ? { working_dir: workingDir, working_dir_ignored_on_server: workingDirIgnoredOnServer } : {}),
|
|
478
567
|
};
|
|
479
568
|
}
|
|
569
|
+
// Unresolved `{{ }}` references become `stage.warned` events rather than
|
|
570
|
+
// console output. A Worker's stdout goes to Cloudflare logs, which the
|
|
571
|
+
// pipeline's author never opens — so a literal that was meant to be a
|
|
572
|
+
// reference shipped in the deliverable with nothing anywhere to say so.
|
|
573
|
+
// Warnings only: the pipeline still runs, because refusing would turn a
|
|
574
|
+
// cosmetic authoring problem into a failed run the buyer paid for.
|
|
575
|
+
const onWarning = deps.eventSink
|
|
576
|
+
? (message) => {
|
|
577
|
+
deps.eventSink.emit(makeStageWarnedEvent({ stageId: stage.id, message }));
|
|
578
|
+
}
|
|
579
|
+
: undefined;
|
|
480
580
|
const model = deps.modelResolver.resolveSync(stage, pipeline);
|
|
481
581
|
const stageProvider = resolveStageProvider(deps, stage, model);
|
|
482
582
|
const resolvedSystem = stage.system
|
|
483
|
-
?
|
|
583
|
+
? resolvePromptRefs(stage.system, ctx.inputs, ctx.previousOutputs, onWarning)
|
|
484
584
|
: stage.system;
|
|
485
|
-
const
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
}
|
|
585
|
+
const stageProviderName = (stage.provider ?? stageProvider.name);
|
|
586
|
+
// M1 — multimodal prompt path. When stage.prompt is an array of
|
|
587
|
+
// MultimodalMessage, route through opts.messages and prepend a
|
|
588
|
+
// synthetic user message carrying the prior context + inputs.
|
|
589
|
+
// Text-only callers keep the legacy single-string path unchanged.
|
|
590
|
+
const rawPrompt = stage.prompt;
|
|
591
|
+
const isMultimodal = Array.isArray(rawPrompt);
|
|
592
|
+
if (isMultimodal) {
|
|
593
|
+
assertMultimodalSupported(stageProviderName, model);
|
|
594
|
+
}
|
|
595
|
+
const ctxPrefix = previousContext.length > 0 || inputsString.length > 0
|
|
596
|
+
? `${previousContext}Inputs:\n${inputsString}\n---\n\n`
|
|
597
|
+
: '';
|
|
598
|
+
// Resolved here rather than inside generateText so a nested
|
|
599
|
+
// image_url.url and a text part are interpolated by the same walk.
|
|
600
|
+
const resolvedPromptMessages = isMultimodal
|
|
601
|
+
? resolvePromptRefs(rawPrompt, ctx.inputs, ctx.previousOutputs)
|
|
602
|
+
: null;
|
|
603
|
+
const ran = await runWithRetry(() => isMultimodal
|
|
604
|
+
? stageProvider.generateText('', {
|
|
605
|
+
model,
|
|
606
|
+
system: resolvedSystem,
|
|
607
|
+
complexity: stage.model?.includes('M3') || stage.model?.includes('opus') ? 'complex' : 'simple',
|
|
608
|
+
maxTokens: typeof stage.maxTokens === 'number' ? stage.maxTokens : 4096,
|
|
609
|
+
fields: stage.fields,
|
|
610
|
+
outputFormat: stage.output_format,
|
|
611
|
+
messages: correctionHint
|
|
612
|
+
? [
|
|
613
|
+
...(ctxPrefix.length > 0 ? [{ role: 'user', content: ctxPrefix }] : []),
|
|
614
|
+
{ role: 'user', content: correctionHint },
|
|
615
|
+
...(resolvedPromptMessages ?? []),
|
|
616
|
+
]
|
|
617
|
+
: ctxPrefix.length > 0
|
|
618
|
+
? [
|
|
619
|
+
{ role: 'user', content: ctxPrefix },
|
|
620
|
+
...(resolvedPromptMessages ?? []),
|
|
621
|
+
]
|
|
622
|
+
: (resolvedPromptMessages ?? []),
|
|
623
|
+
})
|
|
624
|
+
: (() => {
|
|
625
|
+
const stringPrompt = typeof stage.prompt === 'string' ? stage.prompt : '';
|
|
626
|
+
const resolvedPrompt = resolvePromptRefs(stringPrompt, ctx.inputs, ctx.previousOutputs, onWarning);
|
|
627
|
+
const prompt = `${previousContext}Inputs:\n${inputsString}\n---\n\n${correctionHint ? `${correctionHint}\n\n` : ''}${resolvedPrompt}`;
|
|
628
|
+
return stageProvider.generateText(prompt, {
|
|
629
|
+
model,
|
|
630
|
+
system: resolvedSystem,
|
|
631
|
+
complexity: stage.model?.includes('M3') || stage.model?.includes('opus') ? 'complex' : 'simple',
|
|
632
|
+
maxTokens: typeof stage.maxTokens === 'number' ? stage.maxTokens : 4096,
|
|
633
|
+
fields: stage.fields,
|
|
634
|
+
outputFormat: stage.output_format,
|
|
635
|
+
});
|
|
636
|
+
})(), stage.retry, retryCtx);
|
|
495
637
|
const result = ran.value;
|
|
496
638
|
const costMicroUsdc = await deps.pricing.resolveCostMicroUsdc(model, result.usage);
|
|
497
|
-
deps.onLlmResponse?.(stage.id, result.text, model);
|
|
498
|
-
|
|
639
|
+
await deps.onLlmResponse?.(stage.id, result.text, model);
|
|
640
|
+
// When output_schema is present this stage runs under
|
|
641
|
+
// runStageWithOutputValidation, which performs this check inside its retry
|
|
642
|
+
// loop so output_retry can recover a wrong-shaped answer. Throwing here
|
|
643
|
+
// would pre-empt that loop, so the check is skipped for exactly that case
|
|
644
|
+
// and nothing else.
|
|
645
|
+
if (!stage.output_schema) {
|
|
646
|
+
validateOutputFormat(result.text, stage.output_format, stage.fields);
|
|
647
|
+
}
|
|
499
648
|
return {
|
|
500
649
|
output: result.text,
|
|
501
650
|
costMicroUsdc,
|
|
@@ -530,6 +679,9 @@ async function runOneStage(stage, shared) {
|
|
|
530
679
|
for (const w of collectRuntimeWarnings(stage, shared.constraints)) {
|
|
531
680
|
shared.emit({ type: 'stage.started', at: new Date().toISOString(), stageId, reason: 'normal' });
|
|
532
681
|
}
|
|
682
|
+
for (const w of collectRuntimeWarnings(stage, shared.constraints)) {
|
|
683
|
+
shared.emit({ type: 'stage.started', at: new Date().toISOString(), stageId, reason: 'normal' });
|
|
684
|
+
}
|
|
533
685
|
const t0 = Date.now();
|
|
534
686
|
try {
|
|
535
687
|
const stageModel = stage.model ?? shared.opts.spec.defaults?.model ?? 'MiniMax-M3';
|
|
@@ -539,7 +691,7 @@ async function runOneStage(stage, shared) {
|
|
|
539
691
|
const stageDepsWithSink = shared.opts.eventSink
|
|
540
692
|
? { ...stageDeps, eventSink: shared.opts.eventSink }
|
|
541
693
|
: stageDeps;
|
|
542
|
-
const result = await
|
|
694
|
+
const result = await runStageWithOutputValidation(stage, shared.opts.spec, { inputs: shared.opts.inputs, previousOutputs: shared.outputs }, stageDepsWithSink);
|
|
543
695
|
const ms = Date.now() - t0;
|
|
544
696
|
shared.outputs[stageId] = result.output;
|
|
545
697
|
shared.stageTimings.push({
|
|
@@ -574,6 +726,124 @@ async function runOneStage(stage, shared) {
|
|
|
574
726
|
return { kind: 'failed', stageId, error: err };
|
|
575
727
|
}
|
|
576
728
|
}
|
|
729
|
+
/**
|
|
730
|
+
* M5 — wraps `executeStage` with optional JSON Schema output validation.
|
|
731
|
+
*
|
|
732
|
+
* Behavior by `output_retry` mode:
|
|
733
|
+
* - 'none' — single attempt; fail-fast on validation error
|
|
734
|
+
* - 'single' — at most 2 attempts (initial + 1 retry)
|
|
735
|
+
* - 'loop' — at most 3 attempts (initial + 2 retries)
|
|
736
|
+
*
|
|
737
|
+
* Independent of HTTP-status `retry:` (which is handled inside
|
|
738
|
+
* `runWithRetry` per call). Output validation retries invoke the entire
|
|
739
|
+
* stage body again (LLM call + output) — this is the M5 contract.
|
|
740
|
+
*/
|
|
741
|
+
async function runStageWithOutputValidation(stage, pipeline, ctx, deps) {
|
|
742
|
+
const schema = stage.output_schema;
|
|
743
|
+
// Default was `none` (a single attempt) until M38. `single` is now the
|
|
744
|
+
// default: the correction hint below makes a retry far more likely to
|
|
745
|
+
// succeed than a blind re-roll, and the cost is only incurred on a stage
|
|
746
|
+
// that would otherwise have failed outright.
|
|
747
|
+
//
|
|
748
|
+
// An author who wants one attempt still says so — `output_retry: 'none'`
|
|
749
|
+
// is explicit and unchanged. This changes only the unset case.
|
|
750
|
+
const mode = isOutputValidationMode(stage.output_retry)
|
|
751
|
+
? stage.output_retry
|
|
752
|
+
: 'single';
|
|
753
|
+
if (!schema) {
|
|
754
|
+
// No schema means no retry loop, so output_format is enforced inside
|
|
755
|
+
// executeStage as before.
|
|
756
|
+
return executeStage(stage, pipeline, ctx, deps);
|
|
757
|
+
}
|
|
758
|
+
const schemaCheck = validateJsonSchema(schema);
|
|
759
|
+
if (!schemaCheck.ok) {
|
|
760
|
+
throw new OutputValidationError(stage.id, 1, schemaCheck.violations);
|
|
761
|
+
}
|
|
762
|
+
const mode2 = mode;
|
|
763
|
+
const maxAttempts = OUTPUT_VALIDATION_RETRY_ATTEMPTS[mode2];
|
|
764
|
+
let lastViolations = [];
|
|
765
|
+
// M-diagnostics: capture the raw model output from each attempt so a
|
|
766
|
+
// final-attempt `OutputValidationError` can carry what the LLM actually
|
|
767
|
+
// produced, not just a parser-derived summary. Without this, operators
|
|
768
|
+
// faced with `$: expected type object, got string` were forced to
|
|
769
|
+
// deduce whether the model emitted JSON, a JSON-in-quotes string, or
|
|
770
|
+
// a prose block — exactly the diagnostic we now pin next to
|
|
771
|
+
// `failure_reason` via the server route.
|
|
772
|
+
let lastRawOutput;
|
|
773
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
774
|
+
const result = await executeStage(stage, pipeline, ctx, deps, attempt > 1 ? correctionHint(stage.id, schema, lastViolations) : undefined);
|
|
775
|
+
lastRawOutput = result.output;
|
|
776
|
+
// output_format first: it is the stricter check, and it used to throw from
|
|
777
|
+
// inside executeStage — before this loop — which pre-empted output_retry
|
|
778
|
+
// entirely. That is why a prose answer to a structured_json stage failed
|
|
779
|
+
// on the first attempt with no correction ever offered, while a schema
|
|
780
|
+
// mismatch (a softer failure) did retry.
|
|
781
|
+
try {
|
|
782
|
+
validateOutputFormat(result.output, stage.output_format, stage.fields);
|
|
783
|
+
}
|
|
784
|
+
catch (formatErr) {
|
|
785
|
+
if (attempt >= maxAttempts) {
|
|
786
|
+
// Wrap the stricter output_format failure into OutputValidationError
|
|
787
|
+
// so the server route treats it the same as a schema mismatch:
|
|
788
|
+
// one error class, one diagnostic payload, one persisted `output_json`.
|
|
789
|
+
// validateOutputFormat throws StageOutputFormatError with violations
|
|
790
|
+
// shaped differently than OutputValidationViolation, so we re-shape.
|
|
791
|
+
const message = formatErr instanceof Error ? formatErr.message : String(formatErr);
|
|
792
|
+
const truncated = truncateRawOutput(result.output);
|
|
793
|
+
throw new OutputValidationError(stage.id, attempt, [{ path: '$', message, schema_path: '$' }], formatTruncatedRawOutput(truncated), truncated.truncatedChars);
|
|
794
|
+
}
|
|
795
|
+
lastViolations = [{
|
|
796
|
+
path: '$',
|
|
797
|
+
message: formatErr instanceof Error ? formatErr.message : String(formatErr),
|
|
798
|
+
schema_path: '$',
|
|
799
|
+
}];
|
|
800
|
+
continue;
|
|
801
|
+
}
|
|
802
|
+
const validation = validateOutput(result.output, schema);
|
|
803
|
+
if (validation.ok) {
|
|
804
|
+
return result;
|
|
805
|
+
}
|
|
806
|
+
lastViolations = validation.violations;
|
|
807
|
+
if (attempt >= maxAttempts) {
|
|
808
|
+
const truncated = truncateRawOutput(result.output);
|
|
809
|
+
throw new OutputValidationError(stage.id, attempt, lastViolations, formatTruncatedRawOutput(truncated), truncated.truncatedChars);
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
// Unreachable in practice — the loop always `throw`s on the final
|
|
813
|
+
// attempt — but TypeScript needs a terminator and we keep it
|
|
814
|
+
// symmetric: attach whatever the most recent attempt produced.
|
|
815
|
+
const truncated = lastRawOutput !== undefined ? truncateRawOutput(lastRawOutput) : undefined;
|
|
816
|
+
throw new OutputValidationError(stage.id, maxAttempts, lastViolations, truncated ? formatTruncatedRawOutput(truncated) : undefined, truncated?.truncatedChars);
|
|
817
|
+
}
|
|
818
|
+
/**
|
|
819
|
+
* Tell the model exactly what its previous answer got wrong.
|
|
820
|
+
*
|
|
821
|
+
* `output_retry` re-ran the stage with byte-identical input, so it only helped
|
|
822
|
+
* when the failure was a transient glitch; a stage that answers in prose when
|
|
823
|
+
* the schema wants an object just produces prose again. Feeding the violations
|
|
824
|
+
* back turns the retry into a correction, which is the whole point of having a
|
|
825
|
+
* retry mode at all.
|
|
826
|
+
*
|
|
827
|
+
* The schema is echoed because the model is not shown it — validation happens
|
|
828
|
+
* after the call returns, so "expected type object, got string" is the first
|
|
829
|
+
* time it hears about the shape it was supposed to produce.
|
|
830
|
+
*/
|
|
831
|
+
function correctionHint(stageId, schema, violations) {
|
|
832
|
+
const lines = violations
|
|
833
|
+
.slice(0, 8)
|
|
834
|
+
.map((v) => `- ${v.path || '$'}: ${v.message}`)
|
|
835
|
+
.join('\n');
|
|
836
|
+
return [
|
|
837
|
+
`Your previous answer for stage "${stageId}" was rejected by output validation:`,
|
|
838
|
+
lines,
|
|
839
|
+
'',
|
|
840
|
+
'Reply again with ONLY a JSON value matching this schema. No prose, no explanation,',
|
|
841
|
+
'no markdown code fences — the first character must be { or [ and the last } or ].',
|
|
842
|
+
'',
|
|
843
|
+
'Schema:',
|
|
844
|
+
JSON.stringify(schema, null, 2),
|
|
845
|
+
].join('\n');
|
|
846
|
+
}
|
|
577
847
|
export async function runPipelineV2(opts) {
|
|
578
848
|
const outputs = {};
|
|
579
849
|
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;
|