@agentsmarket/pipeline-runtime 0.1.0
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 +94 -0
- package/bin/webhook.mjs +11 -0
- package/dist/adapters/minimax.d.ts +31 -0
- package/dist/adapters/minimax.js +69 -0
- package/dist/adapters/openrouter.d.ts +29 -0
- package/dist/adapters/openrouter.js +71 -0
- package/dist/checkpoints.d.ts +142 -0
- package/dist/checkpoints.js +192 -0
- package/dist/composition.d.ts +90 -0
- package/dist/composition.js +108 -0
- package/dist/content-hash.d.ts +7 -0
- package/dist/content-hash.js +17 -0
- package/dist/fallback.d.ts +31 -0
- package/dist/fallback.js +76 -0
- package/dist/index.d.ts +64 -0
- package/dist/index.js +61 -0
- package/dist/model-resolver.d.ts +136 -0
- package/dist/model-resolver.js +36 -0
- package/dist/parallel.d.ts +26 -0
- package/dist/parallel.js +83 -0
- package/dist/pricing.d.ts +57 -0
- package/dist/pricing.js +135 -0
- package/dist/provider-registry.d.ts +190 -0
- package/dist/provider-registry.js +333 -0
- package/dist/resolve-vars.d.ts +91 -0
- package/dist/resolve-vars.js +203 -0
- package/dist/retry.d.ts +40 -0
- package/dist/retry.js +61 -0
- package/dist/runtime-constraints.d.ts +39 -0
- package/dist/runtime-constraints.js +60 -0
- package/dist/stage-output-refs.d.ts +79 -0
- package/dist/stage-output-refs.js +107 -0
- package/dist/stages.d.ts +247 -0
- package/dist/stages.js +633 -0
- package/dist/streaming-events.d.ts +118 -0
- package/dist/streaming-events.js +132 -0
- package/dist/types.d.ts +138 -0
- package/dist/types.js +54 -0
- package/dist/webhook.d.ts +30 -0
- package/dist/webhook.js +160 -0
- package/dist/when.d.ts +55 -0
- package/dist/when.js +165 -0
- package/package.json +42 -0
package/dist/stages.js
ADDED
|
@@ -0,0 +1,633 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Stage executor — extracted from server/src/index.ts so both server AND CLI
|
|
3
|
+
* can run pipeline stages with identical semantics.
|
|
4
|
+
*
|
|
5
|
+
* Stage types handled:
|
|
6
|
+
* - llm (model + prompt) — direct LLM call
|
|
7
|
+
* - uses (string) — single skill invocation
|
|
8
|
+
* - uses (string[]) — sequential array of skill invocations
|
|
9
|
+
*
|
|
10
|
+
* Future (P3+): mcp_call, human_approval, action
|
|
11
|
+
*
|
|
12
|
+
* Pure functions — takes StageExecutorDeps as parameter, no DB/global access.
|
|
13
|
+
* Both server (passes DB-backed fetchSkill) and CLI (passes HTTP fetchSkill) use this.
|
|
14
|
+
*/
|
|
15
|
+
import { StageOutputFormatError, StageSkillVersionMismatchError, StageMCPConfigError, } from './types.js';
|
|
16
|
+
import { createModelResolver, } from './model-resolver.js';
|
|
17
|
+
import { computeSkillContentHash } from './content-hash.js';
|
|
18
|
+
import { shouldSkipStage } from './when.js';
|
|
19
|
+
import { isRetryableStatus, computeBackoffMs, RetryExhaustedError, DEFAULT_RETRY, } from './retry.js';
|
|
20
|
+
import { NoopEventSink, makeStartedEvent as makePipelineStartedEvent, makeCompletedEvent as makePipelineCompletedEvent, makeFailedEvent as makePipelineFailedEvent, makeStageStartedEvent, makeStageCompletedEvent, makeStageSkippedEvent, makeStageFailedEvent, makeStageRetriedEvent, } from './streaming-events.js';
|
|
21
|
+
import { validateRuntimeConstraints, collectRuntimeWarnings, defaultRuntimeConstraints, } from './runtime-constraints.js';
|
|
22
|
+
import { resolveStageOutputRefs } from './stage-output-refs.js';
|
|
23
|
+
import { expandComposition, } from './composition.js';
|
|
24
|
+
import { groupIndependentStages, } from './parallel.js';
|
|
25
|
+
import { randomUUID } from 'node:crypto';
|
|
26
|
+
import { buildCheckpoint, restoreFromCheckpoint, } from './checkpoints.js';
|
|
27
|
+
function buildPreviousContext(outputs) {
|
|
28
|
+
const entries = Object.entries(outputs);
|
|
29
|
+
if (entries.length === 0)
|
|
30
|
+
return '';
|
|
31
|
+
const blocks = entries.map(([k, v]) => `\`\`\`\n${k}:\n${v}\n\`\`\``);
|
|
32
|
+
return `Previous stage outputs:\n${blocks.join('\n\n')}\n\n---\n\n`;
|
|
33
|
+
}
|
|
34
|
+
function buildInputsString(inputs) {
|
|
35
|
+
const entries = Object.entries(inputs);
|
|
36
|
+
if (entries.length === 0)
|
|
37
|
+
return '';
|
|
38
|
+
return entries.map(([k, v]) => `${k}: ${JSON.stringify(v)}\n`).join('');
|
|
39
|
+
}
|
|
40
|
+
export function makeWhenResolve(inputs, outputs) {
|
|
41
|
+
const stageRefRe = /^stages\.([A-Za-z_][A-Za-z0-9_]*)(?:\.outputs?(?:\.[A-Za-z_][A-Za-z0-9_]*)?)?$/;
|
|
42
|
+
const inputRefRe = /^inputs\.([A-Za-z_][A-Za-z0-9_]*)$/;
|
|
43
|
+
return (template) => {
|
|
44
|
+
const trimmed = template.trim();
|
|
45
|
+
const stageMatch = stageRefRe.exec(trimmed);
|
|
46
|
+
if (stageMatch) {
|
|
47
|
+
const stageId = stageMatch[1];
|
|
48
|
+
if (Object.prototype.hasOwnProperty.call(outputs, stageId)) {
|
|
49
|
+
return outputs[stageId] ?? '';
|
|
50
|
+
}
|
|
51
|
+
return '';
|
|
52
|
+
}
|
|
53
|
+
const inputMatch = inputRefRe.exec(trimmed);
|
|
54
|
+
if (inputMatch) {
|
|
55
|
+
const key = inputMatch[1];
|
|
56
|
+
const val = inputs[key];
|
|
57
|
+
if (val == null)
|
|
58
|
+
return '';
|
|
59
|
+
return typeof val === 'string' ? val : JSON.stringify(val);
|
|
60
|
+
}
|
|
61
|
+
return trimmed;
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
export function parseUsesEntry(raw) {
|
|
65
|
+
const trimmed = raw.trim();
|
|
66
|
+
if (!trimmed)
|
|
67
|
+
return { id: '', version: null };
|
|
68
|
+
const at = trimmed.lastIndexOf('@');
|
|
69
|
+
if (at <= 0 || at === trimmed.length - 1) {
|
|
70
|
+
return { id: trimmed, version: null };
|
|
71
|
+
}
|
|
72
|
+
return { id: trimmed.slice(0, at), version: trimmed.slice(at + 1) };
|
|
73
|
+
}
|
|
74
|
+
export function parseUsesList(stage) {
|
|
75
|
+
if (typeof stage.uses === 'string' && stage.uses.length > 0) {
|
|
76
|
+
return [parseUsesEntry(stage.uses)];
|
|
77
|
+
}
|
|
78
|
+
if (Array.isArray(stage.uses)) {
|
|
79
|
+
return stage.uses
|
|
80
|
+
.filter((s) => typeof s === 'string' && s.length > 0)
|
|
81
|
+
.map((s) => parseUsesEntry(s));
|
|
82
|
+
}
|
|
83
|
+
return [];
|
|
84
|
+
}
|
|
85
|
+
function getPath(obj, dotted) {
|
|
86
|
+
const parts = dotted.split('.');
|
|
87
|
+
let cursor = obj;
|
|
88
|
+
for (let i = 0; i < parts.length; i++) {
|
|
89
|
+
if (cursor == null)
|
|
90
|
+
return { found: false, reason: 'null at path' };
|
|
91
|
+
if (typeof cursor !== 'object') {
|
|
92
|
+
return { found: false, reason: `expected object at segment '${parts[i]}', got ${typeof cursor}` };
|
|
93
|
+
}
|
|
94
|
+
const key = parts[i];
|
|
95
|
+
if (Array.isArray(cursor)) {
|
|
96
|
+
const idx = Number(key);
|
|
97
|
+
if (!Number.isInteger(idx) || idx < 0 || idx >= cursor.length) {
|
|
98
|
+
return { found: false, reason: `array index ${key} out of bounds (length ${cursor.length})` };
|
|
99
|
+
}
|
|
100
|
+
cursor = cursor[idx];
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
const rec = cursor;
|
|
104
|
+
if (!(key in rec))
|
|
105
|
+
return { found: false, reason: `key '${key}' missing` };
|
|
106
|
+
cursor = rec[key];
|
|
107
|
+
}
|
|
108
|
+
return { found: true, reason: '' };
|
|
109
|
+
}
|
|
110
|
+
export function validateOutputFormat(text, outputFormat, requiredFields) {
|
|
111
|
+
if (outputFormat !== 'structured_json')
|
|
112
|
+
return;
|
|
113
|
+
if (!requiredFields || requiredFields.length === 0)
|
|
114
|
+
return;
|
|
115
|
+
let parsed;
|
|
116
|
+
try {
|
|
117
|
+
parsed = JSON.parse(text);
|
|
118
|
+
}
|
|
119
|
+
catch (e) {
|
|
120
|
+
throw new StageOutputFormatError([
|
|
121
|
+
{ path: '$', reason: `LLM output is not valid JSON: ${e.message}` },
|
|
122
|
+
]);
|
|
123
|
+
}
|
|
124
|
+
const violations = [];
|
|
125
|
+
for (const field of requiredFields) {
|
|
126
|
+
const { found, reason } = getPath(parsed, field);
|
|
127
|
+
if (!found)
|
|
128
|
+
violations.push({ path: field, reason });
|
|
129
|
+
}
|
|
130
|
+
if (violations.length > 0)
|
|
131
|
+
throw new StageOutputFormatError(violations);
|
|
132
|
+
}
|
|
133
|
+
function validateMCPConfig(declaredServers, declaredTools, validator) {
|
|
134
|
+
if (!declaredServers && !declaredTools)
|
|
135
|
+
return { detail: undefined, passThrough: false };
|
|
136
|
+
const servers = declaredServers ?? [];
|
|
137
|
+
const tools = declaredTools ?? [];
|
|
138
|
+
if (!validator) {
|
|
139
|
+
return {
|
|
140
|
+
detail: { declared_servers: servers, declared_tools: tools, validated_servers: servers, validated_tools: tools },
|
|
141
|
+
passThrough: true,
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
const result = validator(servers, tools);
|
|
145
|
+
if (result.unknown_servers.length > 0 || result.unknown_tools.length > 0) {
|
|
146
|
+
throw new StageMCPConfigError(result.unknown_servers, result.unknown_tools);
|
|
147
|
+
}
|
|
148
|
+
return {
|
|
149
|
+
detail: {
|
|
150
|
+
declared_servers: servers,
|
|
151
|
+
declared_tools: tools,
|
|
152
|
+
validated_servers: result.validated_servers,
|
|
153
|
+
validated_tools: result.validated_tools,
|
|
154
|
+
},
|
|
155
|
+
passThrough: false,
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
function checkSkillAccess(skill, viewerAgentId, pipelineAuthorId, isPrivate, grantedTo) {
|
|
159
|
+
if (!isPrivate)
|
|
160
|
+
return;
|
|
161
|
+
const isViewerAuthor = viewerAgentId.toLowerCase() === pipelineAuthorId.toLowerCase();
|
|
162
|
+
const isSkillAuthor = viewerAgentId.toLowerCase() === (skill.author_agent_id ?? '').toLowerCase();
|
|
163
|
+
if (isViewerAuthor || isSkillAuthor)
|
|
164
|
+
return;
|
|
165
|
+
if (grantedTo.some((a) => a.toLowerCase() === viewerAgentId.toLowerCase()))
|
|
166
|
+
return;
|
|
167
|
+
throw new StageForbiddenError(`Private skill '${skill.id}' access denied`);
|
|
168
|
+
}
|
|
169
|
+
export class StageNotFoundError extends Error {
|
|
170
|
+
constructor(message) {
|
|
171
|
+
super(message);
|
|
172
|
+
this.name = 'REFERENCED_SKILL_NOT_FOUND';
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
export class StageForbiddenError extends Error {
|
|
176
|
+
constructor(message) {
|
|
177
|
+
super(message);
|
|
178
|
+
this.name = 'REFERENCED_SKILL_FORBIDDEN';
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
export class StageBadConfigError extends Error {
|
|
182
|
+
constructor(message) {
|
|
183
|
+
super(message);
|
|
184
|
+
this.name = 'BAD_STAGE';
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
function resolveStageProvider(deps, stage, model) {
|
|
188
|
+
if (!stage.provider)
|
|
189
|
+
return deps.provider;
|
|
190
|
+
if (!deps.registry) {
|
|
191
|
+
throw new StageBadConfigError(`stage '${stage.id}': declares provider '${stage.provider}' but no registry supplied to executor`);
|
|
192
|
+
}
|
|
193
|
+
return deps.registry.resolveWithSupports(stage.provider, model);
|
|
194
|
+
}
|
|
195
|
+
async function invokeSkill(skill, input, previousContext, skillLabel, provider, retry, retryCtx) {
|
|
196
|
+
const t0 = Date.now();
|
|
197
|
+
const inputStr = JSON.stringify(input ?? {}, null, 2);
|
|
198
|
+
const fullMd = skill.full_md ?? '';
|
|
199
|
+
const description = skill.description ?? '';
|
|
200
|
+
const composedPrompt = `${previousContext}${fullMd}\n\n---\n\nInput:\n${inputStr}`;
|
|
201
|
+
const ran = await runWithRetry(() => provider.generateText(composedPrompt, {
|
|
202
|
+
system: `${skillLabel}\n${description}`,
|
|
203
|
+
complexity: 'complex',
|
|
204
|
+
maxTokens: 4096,
|
|
205
|
+
}), retry, retryCtx);
|
|
206
|
+
return { result: ran.value, durationMs: Date.now() - t0, attempts: ran.attempts };
|
|
207
|
+
}
|
|
208
|
+
function readErrorStatus(e) {
|
|
209
|
+
if (!e || typeof e !== 'object')
|
|
210
|
+
return undefined;
|
|
211
|
+
const rec = e;
|
|
212
|
+
const raw = rec.status ?? rec.statusCode ?? rec.code;
|
|
213
|
+
if (typeof raw === 'number' && Number.isFinite(raw))
|
|
214
|
+
return raw;
|
|
215
|
+
if (typeof raw === 'string') {
|
|
216
|
+
const n = Number(raw);
|
|
217
|
+
if (Number.isFinite(n))
|
|
218
|
+
return n;
|
|
219
|
+
}
|
|
220
|
+
return undefined;
|
|
221
|
+
}
|
|
222
|
+
async function sleep(ms) {
|
|
223
|
+
if (ms <= 0)
|
|
224
|
+
return;
|
|
225
|
+
await new Promise((r) => setTimeout(r, ms));
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Retry the wrapped operation on transient retryable statuses per the
|
|
229
|
+
* supplied `RetryConfig`. Wraps OpenAI/Anthropic SDK errors that surface
|
|
230
|
+
* a numeric `status`/`statusCode` field. Any other thrown value is
|
|
231
|
+
* re-thrown verbatim on the first attempt (untouched).
|
|
232
|
+
*
|
|
233
|
+
* Default config: 3 attempts, exponential backoff, 1000ms initial,
|
|
234
|
+
* retryable statuses {429, 503}. Pass `attempts: 1` to disable retry.
|
|
235
|
+
*
|
|
236
|
+
* When `retryCtx` carries an `eventSink`, a `stage.retry` event is
|
|
237
|
+
* emitted for every attempt that fails with a retryable status and
|
|
238
|
+
* triggers another try. Final-exhaustion emits `stage.failed` via the
|
|
239
|
+
* caller (not here — `runWithRetry` only signals retry decisions).
|
|
240
|
+
*/
|
|
241
|
+
async function runWithRetry(op, retry, retryCtx) {
|
|
242
|
+
const cfg = retry ?? DEFAULT_RETRY;
|
|
243
|
+
const attempts = Math.max(1, cfg.attempts ?? DEFAULT_RETRY.attempts);
|
|
244
|
+
const retryable = cfg.retryable_status ?? [...DEFAULT_RETRYABLE_STATUSES_FALLBACK];
|
|
245
|
+
let lastError;
|
|
246
|
+
let lastStatus;
|
|
247
|
+
for (let attempt = 1; attempt <= attempts; attempt++) {
|
|
248
|
+
try {
|
|
249
|
+
const value = await op();
|
|
250
|
+
return { value, attempts: attempt };
|
|
251
|
+
}
|
|
252
|
+
catch (e) {
|
|
253
|
+
lastError = e;
|
|
254
|
+
lastStatus = readErrorStatus(e);
|
|
255
|
+
if (attempt >= attempts)
|
|
256
|
+
break;
|
|
257
|
+
if (lastStatus === undefined || !isRetryableStatus(lastStatus, { retryable_status: retryable })) {
|
|
258
|
+
throw e;
|
|
259
|
+
}
|
|
260
|
+
const backoffMs = computeBackoffMs(attempt, cfg);
|
|
261
|
+
if (retryCtx?.eventSink) {
|
|
262
|
+
const errorMessage = e instanceof Error ? e.message : String(e);
|
|
263
|
+
retryCtx.eventSink.emit(makeStageRetriedEvent({
|
|
264
|
+
stageId: retryCtx.stageId,
|
|
265
|
+
attempt,
|
|
266
|
+
maxAttempts: attempts,
|
|
267
|
+
errorMessage,
|
|
268
|
+
...(lastStatus !== undefined ? { errorStatus: lastStatus } : {}),
|
|
269
|
+
nextBackoffMs: backoffMs,
|
|
270
|
+
}));
|
|
271
|
+
}
|
|
272
|
+
await sleep(backoffMs);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
const lastMessage = lastError instanceof Error ? lastError.message : String(lastError);
|
|
276
|
+
throw new RetryExhaustedError(retryCtx?.stageId ?? '<stage>', attempts, lastMessage + (lastStatus !== undefined ? ` (status ${lastStatus})` : ''));
|
|
277
|
+
}
|
|
278
|
+
// Fallback constant (kept local — retry.ts owns the canonical list).
|
|
279
|
+
const DEFAULT_RETRYABLE_STATUSES_FALLBACK = [429, 503];
|
|
280
|
+
export async function executeStage(stage, pipeline, ctx, deps) {
|
|
281
|
+
const mcpResult = validateMCPConfig(stage.mcp_servers, stage.mcp_tools, deps.validateMCPRefs);
|
|
282
|
+
const workingDir = typeof stage.working_dir === 'string' && stage.working_dir.length > 0
|
|
283
|
+
? stage.working_dir
|
|
284
|
+
: undefined;
|
|
285
|
+
const workingDirIgnoredOnServer = !!workingDir && !deps.isLocal;
|
|
286
|
+
const previousContext = buildPreviousContext(ctx.previousOutputs);
|
|
287
|
+
const inputsString = buildInputsString(ctx.inputs);
|
|
288
|
+
const retryCtx = deps.eventSink
|
|
289
|
+
? { stageId: stage.id, eventSink: deps.eventSink }
|
|
290
|
+
: undefined;
|
|
291
|
+
const usesList = parseUsesList(stage);
|
|
292
|
+
const hasUses = usesList.length > 0;
|
|
293
|
+
const hasModel = typeof stage.model === 'string' && stage.model.length > 0;
|
|
294
|
+
const hasPrompt = typeof stage.prompt === 'string' && stage.prompt.length > 0;
|
|
295
|
+
const hasSystem = typeof stage.system === 'string' && stage.system.length > 0;
|
|
296
|
+
if (!hasUses && !hasModel && !hasPrompt) {
|
|
297
|
+
throw new StageBadConfigError(`Stage '${stage.id}' requires one of: 'uses' (skill stage), 'model'+'prompt' (LLM stage), or just 'prompt' with default model`);
|
|
298
|
+
}
|
|
299
|
+
if (hasUses) {
|
|
300
|
+
let chainedInput = stage.input ?? ctx.inputs;
|
|
301
|
+
let lastResult = null;
|
|
302
|
+
const nestedCalls = [];
|
|
303
|
+
const usesDetails = [];
|
|
304
|
+
let totalCost = 0;
|
|
305
|
+
let totalUsage = { inputTokens: 0, outputTokens: 0 };
|
|
306
|
+
let resolvedModel = 'MiniMax-M3';
|
|
307
|
+
for (let i = 0; i < usesList.length; i++) {
|
|
308
|
+
const use = usesList[i];
|
|
309
|
+
const skill = await deps.fetchSkill(use.id);
|
|
310
|
+
if (!skill) {
|
|
311
|
+
throw new StageNotFoundError(`Stage '${stage.id}' references missing skill '${use.id}'`);
|
|
312
|
+
}
|
|
313
|
+
const isPrivate = skill.is_private === 1;
|
|
314
|
+
let grantedTo = [];
|
|
315
|
+
try {
|
|
316
|
+
grantedTo = JSON.parse(skill.granted_to ?? '[]');
|
|
317
|
+
}
|
|
318
|
+
catch {
|
|
319
|
+
grantedTo = [];
|
|
320
|
+
}
|
|
321
|
+
checkSkillAccess(skill, deps.getCurrentAgentId(), deps.getPipelineAuthorId(), isPrivate, grantedTo);
|
|
322
|
+
const actualVersion = (skill.version ?? '0.0.0').trim();
|
|
323
|
+
if (use.version !== null && use.version !== actualVersion) {
|
|
324
|
+
const detail = {
|
|
325
|
+
stage_id: stage.id,
|
|
326
|
+
skill_id: use.id,
|
|
327
|
+
requested_version: use.version,
|
|
328
|
+
actual_version: actualVersion,
|
|
329
|
+
version_pin: 'strict',
|
|
330
|
+
content_hash: skill.content_hash ?? '',
|
|
331
|
+
fetched_at: new Date().toISOString(),
|
|
332
|
+
ok: false,
|
|
333
|
+
error: `requested version '@${use.version}' but actual is '${actualVersion}'`,
|
|
334
|
+
};
|
|
335
|
+
usesDetails.push(detail);
|
|
336
|
+
throw new StageSkillVersionMismatchError(use.version, actualVersion);
|
|
337
|
+
}
|
|
338
|
+
const contentHash = skill.content_hash && skill.content_hash.length === 64
|
|
339
|
+
? skill.content_hash
|
|
340
|
+
: await computeSkillContentHash(skill);
|
|
341
|
+
const label = `[SKILL:${use.id} v${actualVersion} sha256:${contentHash}]\nYou MUST follow the skill instructions above exactly. If you cannot, return JSON { "error": "<reason>" }.`;
|
|
342
|
+
usesDetails.push({
|
|
343
|
+
stage_id: stage.id,
|
|
344
|
+
skill_id: use.id,
|
|
345
|
+
requested_version: use.version,
|
|
346
|
+
actual_version: actualVersion,
|
|
347
|
+
version_pin: use.version !== null ? 'strict' : 'loose',
|
|
348
|
+
content_hash: contentHash,
|
|
349
|
+
fetched_at: new Date().toISOString(),
|
|
350
|
+
ok: true,
|
|
351
|
+
});
|
|
352
|
+
const skillModel = deps.modelResolver.resolveSync(stage, pipeline, skill);
|
|
353
|
+
resolvedModel = skillModel;
|
|
354
|
+
const stageProvider = resolveStageProvider(deps, stage, skillModel);
|
|
355
|
+
const resolvedInput = typeof chainedInput === 'string'
|
|
356
|
+
? resolveStageOutputRefs(chainedInput, ctx.previousOutputs)
|
|
357
|
+
: chainedInput;
|
|
358
|
+
const { result, durationMs } = await invokeSkill(skill, resolvedInput, previousContext, label, stageProvider, stage.retry, retryCtx);
|
|
359
|
+
lastResult = result;
|
|
360
|
+
chainedInput = { input_from_previous_skill: result.text };
|
|
361
|
+
nestedCalls.push({
|
|
362
|
+
step_id: `${stage.id}:${i + 1}`,
|
|
363
|
+
skill_id: use.id,
|
|
364
|
+
duration_ms: durationMs,
|
|
365
|
+
ok: true,
|
|
366
|
+
});
|
|
367
|
+
const skillCost = await deps.pricing.resolveCostMicroUsdc(skillModel, result.usage);
|
|
368
|
+
totalCost += skillCost;
|
|
369
|
+
totalUsage = {
|
|
370
|
+
inputTokens: totalUsage.inputTokens + result.usage.inputTokens,
|
|
371
|
+
outputTokens: totalUsage.outputTokens + result.usage.outputTokens,
|
|
372
|
+
};
|
|
373
|
+
}
|
|
374
|
+
const output = lastResult?.text ?? '';
|
|
375
|
+
validateOutputFormat(output, stage.output_format, stage.fields);
|
|
376
|
+
return {
|
|
377
|
+
output,
|
|
378
|
+
costMicroUsdc: totalCost,
|
|
379
|
+
usage: totalUsage,
|
|
380
|
+
nestedCalls,
|
|
381
|
+
modelUsed: resolvedModel,
|
|
382
|
+
usesDetails,
|
|
383
|
+
mcp: mcpResult.detail,
|
|
384
|
+
...(workingDir ? { working_dir: workingDir, working_dir_ignored_on_server: workingDirIgnoredOnServer } : {}),
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
const model = deps.modelResolver.resolveSync(stage, pipeline);
|
|
388
|
+
const stageProvider = resolveStageProvider(deps, stage, model);
|
|
389
|
+
const resolvedSystem = stage.system
|
|
390
|
+
? resolveStageOutputRefs(stage.system, ctx.previousOutputs)
|
|
391
|
+
: stage.system;
|
|
392
|
+
const resolvedPrompt = resolveStageOutputRefs(stage.prompt ?? '', ctx.previousOutputs);
|
|
393
|
+
const prompt = previousContext + `Inputs:\n${inputsString}\n---\n\n${resolvedPrompt}`;
|
|
394
|
+
const ran = await runWithRetry(() => stageProvider.generateText(prompt, {
|
|
395
|
+
model,
|
|
396
|
+
system: resolvedSystem,
|
|
397
|
+
complexity: stage.model?.includes('M3') || stage.model?.includes('opus') ? 'complex' : 'simple',
|
|
398
|
+
maxTokens: 4096,
|
|
399
|
+
}), stage.retry, retryCtx);
|
|
400
|
+
const result = ran.value;
|
|
401
|
+
const costMicroUsdc = await deps.pricing.resolveCostMicroUsdc(model, result.usage);
|
|
402
|
+
validateOutputFormat(result.text, stage.output_format, stage.fields);
|
|
403
|
+
return {
|
|
404
|
+
output: result.text,
|
|
405
|
+
costMicroUsdc,
|
|
406
|
+
usage: result.usage,
|
|
407
|
+
nestedCalls: [],
|
|
408
|
+
modelUsed: model,
|
|
409
|
+
mcp: mcpResult.detail,
|
|
410
|
+
...(workingDir ? { working_dir: workingDir, working_dir_ignored_on_server: workingDirIgnoredOnServer } : {}),
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
async function runOneStage(stage, shared) {
|
|
414
|
+
if (!stage.id) {
|
|
415
|
+
return { kind: 'failed', stageId: '<no-id>', error: new StageBadConfigError('Stage missing required field: id') };
|
|
416
|
+
}
|
|
417
|
+
const stageId = stage.id;
|
|
418
|
+
shared.opts.hooks?.onStageStart?.(stageId);
|
|
419
|
+
shared.emit(makeStageStartedEvent(stageId));
|
|
420
|
+
if (stage.when && shouldSkipStage(stage.when, shared.whenResolve)) {
|
|
421
|
+
shared.outputs[stageId] = '';
|
|
422
|
+
shared.stageTimings.push({ id: stageId, ms: 0, costMicroUsdc: 0, model: 'skipped', skillIds: [] });
|
|
423
|
+
shared.stageProvenance[stageId] = { uses_details: [] };
|
|
424
|
+
shared.opts.hooks?.onStageComplete?.(stageId, 0, '');
|
|
425
|
+
shared.emit(makeStageSkippedEvent(stageId));
|
|
426
|
+
return { kind: 'skipped', stageId };
|
|
427
|
+
}
|
|
428
|
+
const errs = validateRuntimeConstraints(stage, shared.constraints, shared.constraintCtx);
|
|
429
|
+
if (errs.length > 0) {
|
|
430
|
+
const first = errs[0];
|
|
431
|
+
shared.emit(makeStageFailedEvent({ stageId, error: first }));
|
|
432
|
+
return { kind: 'failed', stageId, error: new Error(`runtime constraint violation in stage '${stageId}': ${first}`) };
|
|
433
|
+
}
|
|
434
|
+
for (const w of collectRuntimeWarnings(stage, shared.constraints)) {
|
|
435
|
+
shared.emit({ type: 'stage.started', at: new Date().toISOString(), stageId, reason: 'normal' });
|
|
436
|
+
}
|
|
437
|
+
const t0 = Date.now();
|
|
438
|
+
try {
|
|
439
|
+
const stageModel = stage.model ?? shared.opts.spec.defaults?.model ?? 'MiniMax-M3';
|
|
440
|
+
const stageDeps = shared.opts.providerResolver
|
|
441
|
+
? { ...shared.opts.deps, provider: shared.opts.providerResolver(stageModel) }
|
|
442
|
+
: shared.opts.deps;
|
|
443
|
+
const stageDepsWithSink = shared.opts.eventSink
|
|
444
|
+
? { ...stageDeps, eventSink: shared.opts.eventSink }
|
|
445
|
+
: stageDeps;
|
|
446
|
+
const result = await executeStage(stage, shared.opts.spec, { inputs: shared.opts.inputs, previousOutputs: shared.outputs }, stageDepsWithSink);
|
|
447
|
+
const ms = Date.now() - t0;
|
|
448
|
+
shared.outputs[stageId] = result.output;
|
|
449
|
+
shared.stageTimings.push({
|
|
450
|
+
id: stageId,
|
|
451
|
+
ms,
|
|
452
|
+
costMicroUsdc: result.costMicroUsdc,
|
|
453
|
+
model: result.modelUsed,
|
|
454
|
+
skillIds: result.nestedCalls.map((c) => c.skill_id),
|
|
455
|
+
});
|
|
456
|
+
shared.stageProvenance[stageId] = {
|
|
457
|
+
uses_details: result.usesDetails ?? [],
|
|
458
|
+
...(result.mcp ? { mcp: result.mcp } : {}),
|
|
459
|
+
...(result.working_dir
|
|
460
|
+
? { working_dir: result.working_dir, working_dir_ignored_on_server: !!result.working_dir_ignored_on_server }
|
|
461
|
+
: {}),
|
|
462
|
+
};
|
|
463
|
+
shared.nestedCalls.push(...result.nestedCalls);
|
|
464
|
+
shared.totalCostRef.value += result.costMicroUsdc;
|
|
465
|
+
shared.opts.hooks?.onStageComplete?.(stageId, ms, result.output);
|
|
466
|
+
shared.emit(makeStageCompletedEvent({
|
|
467
|
+
stageId,
|
|
468
|
+
ms,
|
|
469
|
+
costMicroUsdc: result.costMicroUsdc,
|
|
470
|
+
model: result.modelUsed,
|
|
471
|
+
output: result.output,
|
|
472
|
+
}));
|
|
473
|
+
return { kind: 'completed', stageId, ms, costMicroUsdc: result.costMicroUsdc };
|
|
474
|
+
}
|
|
475
|
+
catch (e) {
|
|
476
|
+
const err = e instanceof Error ? e : new Error(String(e));
|
|
477
|
+
shared.emit(makeStageFailedEvent({ stageId, error: err.message }));
|
|
478
|
+
return { kind: 'failed', stageId, error: err };
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
export async function runPipelineV2(opts) {
|
|
482
|
+
const outputs = {};
|
|
483
|
+
const stageTimings = [];
|
|
484
|
+
const stageProvenance = {};
|
|
485
|
+
const nestedCalls = [];
|
|
486
|
+
const totalCostMicroUsdc = 0;
|
|
487
|
+
const whenResolve = makeWhenResolve(opts.inputs, outputs);
|
|
488
|
+
const sink = opts.eventSink ?? new NoopEventSink();
|
|
489
|
+
const constraints = opts.constraints ?? defaultRuntimeConstraints();
|
|
490
|
+
const constraintCtx = {
|
|
491
|
+
providersAvailable: new Set([opts.deps.provider.name]),
|
|
492
|
+
skillsAvailable: new Set(),
|
|
493
|
+
};
|
|
494
|
+
const pipelineName = opts.spec.name;
|
|
495
|
+
const pipelineVersion = opts.spec.version;
|
|
496
|
+
const baseStages = opts.deps.fetchPipeline
|
|
497
|
+
? await expandComposition(opts.spec.stages.map((s) => ({ ...s })), opts.deps.fetchPipeline, 0, opts.spec.composition?.max_depth !== undefined
|
|
498
|
+
? { maxDepth: opts.spec.composition.max_depth }
|
|
499
|
+
: {})
|
|
500
|
+
: opts.spec.stages;
|
|
501
|
+
function emit(ev) { sink.emit(ev); }
|
|
502
|
+
// R10.4 checkpoint lifecycle: assign runId (or use caller's), restore
|
|
503
|
+
// any prior snapshot when `resume: true`, and remember which stage ids
|
|
504
|
+
// already have snapshotted outputs (so the loop below skips them).
|
|
505
|
+
const runId = opts.runId ?? (opts.checkpointStorage ? randomUUID() : undefined);
|
|
506
|
+
let startedAt = new Date().toISOString();
|
|
507
|
+
const completedStageIds = new Set();
|
|
508
|
+
let resumedFromCheckpoint = 0;
|
|
509
|
+
if (runId && opts.checkpointStorage && opts.resume) {
|
|
510
|
+
const cp = await opts.checkpointStorage.load(runId);
|
|
511
|
+
if (cp) {
|
|
512
|
+
const restored = restoreFromCheckpoint(cp);
|
|
513
|
+
startedAt = cp.started_at;
|
|
514
|
+
for (const id of Object.keys(restored.restored_outputs)) {
|
|
515
|
+
outputs[id] = restored.restored_outputs[id];
|
|
516
|
+
completedStageIds.add(id);
|
|
517
|
+
stageProvenance[id] = { uses_details: [] };
|
|
518
|
+
stageTimings.push({ id, ms: 0, costMicroUsdc: 0, model: 'restored', skillIds: [] });
|
|
519
|
+
}
|
|
520
|
+
resumedFromCheckpoint = Object.keys(restored.restored_outputs).length;
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
emit(makePipelineStartedEvent({
|
|
524
|
+
pipelineName,
|
|
525
|
+
pipelineVersion,
|
|
526
|
+
stageCount: baseStages.length,
|
|
527
|
+
}));
|
|
528
|
+
const pipelineT0 = Date.now();
|
|
529
|
+
const executionGroups = opts.parallel
|
|
530
|
+
? groupIndependentStages(baseStages)
|
|
531
|
+
: baseStages.map((s) => ({ parallel: false, stages: [s] }));
|
|
532
|
+
const shared = {
|
|
533
|
+
opts,
|
|
534
|
+
whenResolve,
|
|
535
|
+
constraints,
|
|
536
|
+
constraintCtx,
|
|
537
|
+
outputs,
|
|
538
|
+
stageTimings,
|
|
539
|
+
stageProvenance,
|
|
540
|
+
nestedCalls,
|
|
541
|
+
totalCostRef: { value: totalCostMicroUsdc },
|
|
542
|
+
emit,
|
|
543
|
+
};
|
|
544
|
+
async function snapshotCheckpoint() {
|
|
545
|
+
if (!opts.checkpointStorage || !runId)
|
|
546
|
+
return;
|
|
547
|
+
const completed = stageTimings
|
|
548
|
+
.filter((t) => t.model !== 'skipped' && t.model !== 'restored' && Object.prototype.hasOwnProperty.call(outputs, t.id))
|
|
549
|
+
.map((t) => ({ id: t.id, output: outputs[t.id], ms: t.ms, costMicroUsdc: t.costMicroUsdc, model: t.model }));
|
|
550
|
+
const completedIds = new Set(completed.map((c) => c.id));
|
|
551
|
+
const pending = baseStages.filter((s) => s.id !== undefined && !completedIds.has(s.id));
|
|
552
|
+
await opts.checkpointStorage.save(buildCheckpoint({
|
|
553
|
+
run_id: runId,
|
|
554
|
+
pipeline_name: pipelineName ?? '<unnamed>',
|
|
555
|
+
pipeline_version: pipelineVersion,
|
|
556
|
+
started_at: startedAt,
|
|
557
|
+
now_iso: new Date().toISOString(),
|
|
558
|
+
inputs: opts.inputs,
|
|
559
|
+
completed,
|
|
560
|
+
pending: pending,
|
|
561
|
+
}));
|
|
562
|
+
}
|
|
563
|
+
function isStageRestored(stage) {
|
|
564
|
+
return stage.id !== undefined && completedStageIds.has(stage.id);
|
|
565
|
+
}
|
|
566
|
+
for (const group of executionGroups) {
|
|
567
|
+
const liveStages = group.stages.filter((s) => !isStageRestored(s));
|
|
568
|
+
if (liveStages.length === 0)
|
|
569
|
+
continue;
|
|
570
|
+
if (liveStages.length === 1 || !opts.parallel) {
|
|
571
|
+
for (const stage of liveStages) {
|
|
572
|
+
const outcome = await runOneStage(stage, shared);
|
|
573
|
+
if (outcome.kind === 'completed' && stage.id)
|
|
574
|
+
completedStageIds.add(stage.id);
|
|
575
|
+
if (outcome.kind === 'failed') {
|
|
576
|
+
await snapshotCheckpoint();
|
|
577
|
+
emit(makePipelineFailedEvent({
|
|
578
|
+
pipelineName,
|
|
579
|
+
pipelineVersion,
|
|
580
|
+
totalMs: Date.now() - pipelineT0,
|
|
581
|
+
error: outcome.error.message,
|
|
582
|
+
}));
|
|
583
|
+
throw outcome.error;
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
await snapshotCheckpoint();
|
|
587
|
+
continue;
|
|
588
|
+
}
|
|
589
|
+
const settled = await Promise.allSettled(liveStages.map((s) => runOneStage(s, shared)));
|
|
590
|
+
const failedIds = [];
|
|
591
|
+
for (let i = 0; i < settled.length; i++) {
|
|
592
|
+
const r = settled[i];
|
|
593
|
+
const stage = liveStages[i];
|
|
594
|
+
if (r.status === 'fulfilled' && r.value.kind === 'completed' && stage.id) {
|
|
595
|
+
completedStageIds.add(stage.id);
|
|
596
|
+
}
|
|
597
|
+
else if (r.status === 'fulfilled' && r.value.kind === 'failed') {
|
|
598
|
+
failedIds.push(r.value.stageId);
|
|
599
|
+
}
|
|
600
|
+
else if (r.status === 'rejected') {
|
|
601
|
+
const reason = r.reason instanceof Error ? r.reason.message : String(r.reason);
|
|
602
|
+
failedIds.push(`<rejected: ${reason}>`);
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
if (failedIds.length > 0) {
|
|
606
|
+
await snapshotCheckpoint();
|
|
607
|
+
const summary = `pipeline failed: ${failedIds.length}/${liveStages.length} parallel siblings failed (${failedIds.join(', ')})`;
|
|
608
|
+
emit(makePipelineFailedEvent({
|
|
609
|
+
pipelineName,
|
|
610
|
+
pipelineVersion,
|
|
611
|
+
totalMs: Date.now() - pipelineT0,
|
|
612
|
+
error: summary,
|
|
613
|
+
}));
|
|
614
|
+
throw new Error(summary);
|
|
615
|
+
}
|
|
616
|
+
await snapshotCheckpoint();
|
|
617
|
+
}
|
|
618
|
+
emit(makePipelineCompletedEvent({
|
|
619
|
+
pipelineName,
|
|
620
|
+
pipelineVersion,
|
|
621
|
+
totalMs: Date.now() - pipelineT0,
|
|
622
|
+
}));
|
|
623
|
+
return {
|
|
624
|
+
outputs,
|
|
625
|
+
stageTimings,
|
|
626
|
+
totalCostMicroUsdc: shared.totalCostRef.value,
|
|
627
|
+
stageProvenance,
|
|
628
|
+
nestedCalls: shared.nestedCalls,
|
|
629
|
+
...(runId ? { runId } : {}),
|
|
630
|
+
...(resumedFromCheckpoint > 0 ? { resumedFromCheckpoint } : {}),
|
|
631
|
+
};
|
|
632
|
+
}
|
|
633
|
+
export { createModelResolver };
|