@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.
Files changed (43) hide show
  1. package/README.md +94 -0
  2. package/bin/webhook.mjs +11 -0
  3. package/dist/adapters/minimax.d.ts +31 -0
  4. package/dist/adapters/minimax.js +69 -0
  5. package/dist/adapters/openrouter.d.ts +29 -0
  6. package/dist/adapters/openrouter.js +71 -0
  7. package/dist/checkpoints.d.ts +142 -0
  8. package/dist/checkpoints.js +192 -0
  9. package/dist/composition.d.ts +90 -0
  10. package/dist/composition.js +108 -0
  11. package/dist/content-hash.d.ts +7 -0
  12. package/dist/content-hash.js +17 -0
  13. package/dist/fallback.d.ts +31 -0
  14. package/dist/fallback.js +76 -0
  15. package/dist/index.d.ts +64 -0
  16. package/dist/index.js +61 -0
  17. package/dist/model-resolver.d.ts +136 -0
  18. package/dist/model-resolver.js +36 -0
  19. package/dist/parallel.d.ts +26 -0
  20. package/dist/parallel.js +83 -0
  21. package/dist/pricing.d.ts +57 -0
  22. package/dist/pricing.js +135 -0
  23. package/dist/provider-registry.d.ts +190 -0
  24. package/dist/provider-registry.js +333 -0
  25. package/dist/resolve-vars.d.ts +91 -0
  26. package/dist/resolve-vars.js +203 -0
  27. package/dist/retry.d.ts +40 -0
  28. package/dist/retry.js +61 -0
  29. package/dist/runtime-constraints.d.ts +39 -0
  30. package/dist/runtime-constraints.js +60 -0
  31. package/dist/stage-output-refs.d.ts +79 -0
  32. package/dist/stage-output-refs.js +107 -0
  33. package/dist/stages.d.ts +247 -0
  34. package/dist/stages.js +633 -0
  35. package/dist/streaming-events.d.ts +118 -0
  36. package/dist/streaming-events.js +132 -0
  37. package/dist/types.d.ts +138 -0
  38. package/dist/types.js +54 -0
  39. package/dist/webhook.d.ts +30 -0
  40. package/dist/webhook.js +160 -0
  41. package/dist/when.d.ts +55 -0
  42. package/dist/when.js +165 -0
  43. package/package.json +42 -0
package/dist/retry.js ADDED
@@ -0,0 +1,61 @@
1
+ /**
2
+ * R10.1 — Retry config primitive per ADR Q3.
3
+ *
4
+ * Same-provider retries on transient errors. Distinct from `run_if:`
5
+ * which is a compensation gate (different provider/model).
6
+ *
7
+ * GitHub Actions splits `continue-on-error` (retry decoration) from
8
+ * `if: failure()` (compensation gate) — same separation here.
9
+ * Conflating them yields confusing YAML where fallback chains,
10
+ * retry counters, and trigger conditions all live in one block.
11
+ */
12
+ export const DEFAULT_RETRY = {
13
+ attempts: 3,
14
+ backoff: 'exponential',
15
+ initial_ms: 1000,
16
+ };
17
+ export const DEFAULT_RETRYABLE_STATUSES = [429, 503];
18
+ export function isRetryableStatus(status, config = {}) {
19
+ const retryable = config.retryable_status ?? [...DEFAULT_RETRYABLE_STATUSES];
20
+ return retryable.includes(status);
21
+ }
22
+ export function computeBackoffMs(attempt, config = {}) {
23
+ const base = config.initial_ms ?? DEFAULT_RETRY.initial_ms;
24
+ const strategy = config.backoff ?? DEFAULT_RETRY.backoff;
25
+ switch (strategy) {
26
+ case 'fixed':
27
+ return base;
28
+ case 'linear':
29
+ return base * attempt;
30
+ case 'exponential':
31
+ return base * Math.pow(2, attempt - 1);
32
+ }
33
+ }
34
+ export class RetryExhaustedError extends Error {
35
+ stageId;
36
+ attempts;
37
+ lastError;
38
+ constructor(stageId, attempts, lastError) {
39
+ super(`Stage '${stageId}': retry exhausted after ${attempts} attempts — last error: ${lastError}`);
40
+ this.name = 'RETRY_EXHAUSTED';
41
+ this.stageId = stageId;
42
+ this.attempts = attempts;
43
+ this.lastError = lastError;
44
+ }
45
+ }
46
+ export class RetryAttemptError extends Error {
47
+ stageId;
48
+ attempt;
49
+ status;
50
+ retryable;
51
+ nextBackoffMs;
52
+ constructor(stageId, attempt, status, nextBackoffMs) {
53
+ super(`Stage '${stageId}': attempt ${attempt} failed with retryable status ${status} (retry in ${nextBackoffMs}ms)`);
54
+ this.name = 'RETRY_ATTEMPT';
55
+ this.stageId = stageId;
56
+ this.attempt = attempt;
57
+ this.status = status;
58
+ this.retryable = true;
59
+ this.nextBackoffMs = nextBackoffMs;
60
+ }
61
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Runtime constraints — ADR Q9. Validates a stage against a constraints spec
3
+ * (network policy, allowed providers, required skills, max runtime/cost).
4
+ *
5
+ * Errors are SURFACE conditions (stage cannot run). Warnings are ADVISORIES
6
+ * (will run but might exceed budget).
7
+ */
8
+ export type NetworkConstraint = 'required' | 'optional' | 'forbidden';
9
+ export interface RequiredSkill {
10
+ readonly id: string;
11
+ readonly min_version: string;
12
+ }
13
+ export interface RuntimeConstraints {
14
+ readonly network?: NetworkConstraint;
15
+ readonly max_runtime_ms?: number;
16
+ readonly max_cost_micro_usdc?: number;
17
+ readonly allowed_providers?: readonly string[];
18
+ readonly required_skills?: readonly RequiredSkill[];
19
+ }
20
+ export interface ConstraintContext {
21
+ readonly providersAvailable: ReadonlySet<string>;
22
+ readonly skillsAvailable: ReadonlySet<string>;
23
+ }
24
+ export interface ConstraintWarning {
25
+ readonly stageId: string;
26
+ readonly kind: 'max_runtime_ms' | 'max_cost_micro_usdc';
27
+ readonly limit: number;
28
+ }
29
+ export interface StageLikeForConstraints {
30
+ readonly id: string;
31
+ readonly provider?: string;
32
+ readonly uses?: string | string[];
33
+ readonly system?: string;
34
+ readonly prompt?: string;
35
+ }
36
+ export declare function defaultRuntimeConstraints(): RuntimeConstraints;
37
+ export declare function mergeRuntimeConstraints(a: RuntimeConstraints, b: RuntimeConstraints): RuntimeConstraints;
38
+ export declare function validateRuntimeConstraints(stage: StageLikeForConstraints, constraints: RuntimeConstraints, ctx: ConstraintContext): string[];
39
+ export declare function collectRuntimeWarnings(stage: StageLikeForConstraints, constraints: RuntimeConstraints): ConstraintWarning[];
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Runtime constraints — ADR Q9. Validates a stage against a constraints spec
3
+ * (network policy, allowed providers, required skills, max runtime/cost).
4
+ *
5
+ * Errors are SURFACE conditions (stage cannot run). Warnings are ADVISORIES
6
+ * (will run but might exceed budget).
7
+ */
8
+ export function defaultRuntimeConstraints() {
9
+ return { network: 'optional' };
10
+ }
11
+ export function mergeRuntimeConstraints(a, b) {
12
+ return {
13
+ network: b.network ?? a.network,
14
+ max_runtime_ms: b.max_runtime_ms ?? a.max_runtime_ms,
15
+ max_cost_micro_usdc: b.max_cost_micro_usdc ?? a.max_cost_micro_usdc,
16
+ allowed_providers: b.allowed_providers ?? a.allowed_providers,
17
+ required_skills: b.required_skills ?? a.required_skills,
18
+ };
19
+ }
20
+ export function validateRuntimeConstraints(stage, constraints, ctx) {
21
+ const errors = [];
22
+ if (constraints.allowed_providers) {
23
+ if (stage.provider && !constraints.allowed_providers.includes(stage.provider)) {
24
+ errors.push(`Stage '${stage.id}' uses provider '${stage.provider}' which is not in the allowed_providers list [${constraints.allowed_providers.join(', ')}]`);
25
+ }
26
+ }
27
+ if (constraints.network === 'forbidden') {
28
+ const uses = Array.isArray(stage.uses) ? stage.uses : stage.uses ? [stage.uses] : [];
29
+ const usesAny = uses.length > 0;
30
+ if (usesAny) {
31
+ errors.push(`Stage '${stage.id}' has uses: but the pipeline declares network: forbidden`);
32
+ }
33
+ }
34
+ if (constraints.network === 'required') {
35
+ const uses = Array.isArray(stage.uses) ? stage.uses : stage.uses ? [stage.uses] : [];
36
+ const usesAny = uses.length > 0;
37
+ const hasPrompt = !!stage.prompt && stage.prompt.length > 0;
38
+ if (!usesAny && !hasPrompt) {
39
+ errors.push(`Stage '${stage.id}' declares network: required but has neither uses: nor a prompt to act on`);
40
+ }
41
+ }
42
+ if (constraints.required_skills) {
43
+ for (const req of constraints.required_skills) {
44
+ if (!ctx.skillsAvailable.has(req.id)) {
45
+ errors.push(`Stage '${stage.id}' requires skill '${req.id}' (>= ${req.min_version}) but marketplace reports it unavailable`);
46
+ }
47
+ }
48
+ }
49
+ return errors;
50
+ }
51
+ export function collectRuntimeWarnings(stage, constraints) {
52
+ const warnings = [];
53
+ if (constraints.max_runtime_ms !== undefined) {
54
+ warnings.push({ stageId: stage.id, kind: 'max_runtime_ms', limit: constraints.max_runtime_ms });
55
+ }
56
+ if (constraints.max_cost_micro_usdc !== undefined) {
57
+ warnings.push({ stageId: stage.id, kind: 'max_cost_micro_usdc', limit: constraints.max_cost_micro_usdc });
58
+ }
59
+ return warnings;
60
+ }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Stage output refs resolution (`${stages.X.outputs.Y}`).
3
+ *
4
+ * v0.3 NEW (R10.8, ADR Q5 reference). Lets stages reference outputs of
5
+ * previously-executed stages inside string fields (`prompt`, `system`,
6
+ * `input`). Reuses the same `${...}` shell-style syntax as R7 env vars
7
+ * (resolve-vars.ts) so authors have a single interpolation language.
8
+ *
9
+ * Two flavors:
10
+ * 1. `tryParseStageOutputRef` — return null OR `{stageId,outputKey}`
11
+ * when the ENTIRE template is a single ref. Used by when DSL
12
+ * (makeWhenResolve) to detect `when: "${stages.X.outputs.Y} == 'X'"`
13
+ * — a stage output driving a downstream branch. Symmetric with
14
+ * the existing `inputs.X` parsing in makeWhenResolve.
15
+ * 2. `resolveStageOutputRefs` — substitute ALL refs in an arbitrary
16
+ * string against an outputs map. Used inline by executeStage on
17
+ * prompt/system/input right before provider.generateText, so the
18
+ * LLM sees concrete strings, not unrendered `${...}`.
19
+ *
20
+ * Stages referenced via this mechanism MUST already have completed
21
+ * (their `outputs[id]` populated). At integration time we add `event`
22
+ * semantics: ref pointing at a not-yet-executed sibling is a pipeline
23
+ * authoring error — resolved against `outputs` map, so unmet refs throw.
24
+ *
25
+ * Failure modes:
26
+ * - Empty template (`''`) → '' (not an error, intentional passthrough).
27
+ * - Template is not a stage ref OR does not contain any stage refs →
28
+ * returned verbatim by resolveStageOutputRefs (no-op substitution).
29
+ * - tryParseStageOutputRef on a template that has stage refs mixed with
30
+ * other text → returns null (mixed templates don't fit when DSL
31
+ * semantics; they require inline resolution).
32
+ */
33
+ /**
34
+ * Thrown when an inline `${stages.X.outputs.Y}` reference cannot be
35
+ * resolved. Carries ref info for structured logging.
36
+ */
37
+ export declare class UnresolvedStageOutputRefError extends Error {
38
+ readonly stageId: string;
39
+ readonly outputKey: string;
40
+ constructor(stageId: string, outputKey: string);
41
+ }
42
+ export interface ParsedStageOutputRef {
43
+ stageId: string;
44
+ outputKey: string;
45
+ }
46
+ /**
47
+ * If `template` is EXACTLY a single `${stages.X.outputs.Y}` reference,
48
+ * return the parsed `{stageId, outputKey}`. Otherwise return null.
49
+ *
50
+ * Pure — no I/O, no resolution.
51
+ *
52
+ * Examples:
53
+ * tryParseStageOutputRef("${stages.gather.outputs.diff}") → { stageId: 'gather', outputKey: 'diff' }
54
+ * tryParseStageOutputRef("${stages.gather.outputs.diff} is the PR diff") → null (mixed)
55
+ * tryParseStageOutputRef("plain string") → null
56
+ * tryParseStageOutputRef("") → null
57
+ */
58
+ export declare function tryParseStageOutputRef(template: string): ParsedStageOutputRef | null;
59
+ /**
60
+ * Substitute all `${stages.X.outputs.Y}` occurrences in `text` against
61
+ * the provided `outputs` map. Pure — no I/O, no provider calls.
62
+ *
63
+ * Behavior matrix:
64
+ * - Empty text → '' (passthrough).
65
+ * - Text without stage refs → returned verbatim (passthrough).
66
+ * - Ref to a stage PRESENT in outputs → resolved to its string
67
+ * (may be '' if that stage itself was when-skipped — intentional,
68
+ * matches `outputs[id] = ''` sentinel from R10.2.b).
69
+ * - Ref to a stage MISSING from outputs → throws
70
+ * `UnresolvedStageOutputRefError` (the pipeline author wired a
71
+ * forward-looking reference to a stage that hasn't run yet — fail
72
+ * fast).
73
+ *
74
+ * NOT used to expand env vars — that's `expandPipelineText` in
75
+ * resolve-vars.ts (R7). Composition is layered: env-var expansion
76
+ * happens first at YAML load time, stage refs happen per-stage at
77
+ * execution time.
78
+ */
79
+ export declare function resolveStageOutputRefs(text: string, outputs: Record<string, string>): string;
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Stage output refs resolution (`${stages.X.outputs.Y}`).
3
+ *
4
+ * v0.3 NEW (R10.8, ADR Q5 reference). Lets stages reference outputs of
5
+ * previously-executed stages inside string fields (`prompt`, `system`,
6
+ * `input`). Reuses the same `${...}` shell-style syntax as R7 env vars
7
+ * (resolve-vars.ts) so authors have a single interpolation language.
8
+ *
9
+ * Two flavors:
10
+ * 1. `tryParseStageOutputRef` — return null OR `{stageId,outputKey}`
11
+ * when the ENTIRE template is a single ref. Used by when DSL
12
+ * (makeWhenResolve) to detect `when: "${stages.X.outputs.Y} == 'X'"`
13
+ * — a stage output driving a downstream branch. Symmetric with
14
+ * the existing `inputs.X` parsing in makeWhenResolve.
15
+ * 2. `resolveStageOutputRefs` — substitute ALL refs in an arbitrary
16
+ * string against an outputs map. Used inline by executeStage on
17
+ * prompt/system/input right before provider.generateText, so the
18
+ * LLM sees concrete strings, not unrendered `${...}`.
19
+ *
20
+ * Stages referenced via this mechanism MUST already have completed
21
+ * (their `outputs[id]` populated). At integration time we add `event`
22
+ * semantics: ref pointing at a not-yet-executed sibling is a pipeline
23
+ * authoring error — resolved against `outputs` map, so unmet refs throw.
24
+ *
25
+ * Failure modes:
26
+ * - Empty template (`''`) → '' (not an error, intentional passthrough).
27
+ * - Template is not a stage ref OR does not contain any stage refs →
28
+ * returned verbatim by resolveStageOutputRefs (no-op substitution).
29
+ * - tryParseStageOutputRef on a template that has stage refs mixed with
30
+ * other text → returns null (mixed templates don't fit when DSL
31
+ * semantics; they require inline resolution).
32
+ */
33
+ const STAGE_REF_PATTERN = /\$\{stages\.([A-Za-z_][A-Za-z0-9_.-]*?)\.outputs\.([A-Za-z_][A-Za-z0-9_-]*)\}/g;
34
+ /**
35
+ * Thrown when an inline `${stages.X.outputs.Y}` reference cannot be
36
+ * resolved. Carries ref info for structured logging.
37
+ */
38
+ export class UnresolvedStageOutputRefError extends Error {
39
+ stageId;
40
+ outputKey;
41
+ constructor(stageId, outputKey) {
42
+ super(`Unresolved stage output reference: stages.${stageId}.outputs.${outputKey}`);
43
+ this.name = 'UNRESOLVED_STAGE_OUTPUT_REF';
44
+ this.stageId = stageId;
45
+ this.outputKey = outputKey;
46
+ }
47
+ }
48
+ /**
49
+ * If `template` is EXACTLY a single `${stages.X.outputs.Y}` reference,
50
+ * return the parsed `{stageId, outputKey}`. Otherwise return null.
51
+ *
52
+ * Pure — no I/O, no resolution.
53
+ *
54
+ * Examples:
55
+ * tryParseStageOutputRef("${stages.gather.outputs.diff}") → { stageId: 'gather', outputKey: 'diff' }
56
+ * tryParseStageOutputRef("${stages.gather.outputs.diff} is the PR diff") → null (mixed)
57
+ * tryParseStageOutputRef("plain string") → null
58
+ * tryParseStageOutputRef("") → null
59
+ */
60
+ export function tryParseStageOutputRef(template) {
61
+ const trimmed = template.trim();
62
+ if (trimmed.length === 0)
63
+ return null;
64
+ // Count occurrences via matchAll (no lastIndex bookkeeping bugs) and
65
+ // require EXACTLY ONE ref that occupies the entire trimmed string.
66
+ const matches = [...trimmed.matchAll(STAGE_REF_PATTERN)];
67
+ if (matches.length !== 1)
68
+ return null;
69
+ const first = matches[0];
70
+ if (first[0] !== trimmed)
71
+ return null;
72
+ return {
73
+ stageId: first[1],
74
+ outputKey: first[2],
75
+ };
76
+ }
77
+ /**
78
+ * Substitute all `${stages.X.outputs.Y}` occurrences in `text` against
79
+ * the provided `outputs` map. Pure — no I/O, no provider calls.
80
+ *
81
+ * Behavior matrix:
82
+ * - Empty text → '' (passthrough).
83
+ * - Text without stage refs → returned verbatim (passthrough).
84
+ * - Ref to a stage PRESENT in outputs → resolved to its string
85
+ * (may be '' if that stage itself was when-skipped — intentional,
86
+ * matches `outputs[id] = ''` sentinel from R10.2.b).
87
+ * - Ref to a stage MISSING from outputs → throws
88
+ * `UnresolvedStageOutputRefError` (the pipeline author wired a
89
+ * forward-looking reference to a stage that hasn't run yet — fail
90
+ * fast).
91
+ *
92
+ * NOT used to expand env vars — that's `expandPipelineText` in
93
+ * resolve-vars.ts (R7). Composition is layered: env-var expansion
94
+ * happens first at YAML load time, stage refs happen per-stage at
95
+ * execution time.
96
+ */
97
+ export function resolveStageOutputRefs(text, outputs) {
98
+ if (text.length === 0)
99
+ return text;
100
+ STAGE_REF_PATTERN.lastIndex = 0;
101
+ return text.replace(STAGE_REF_PATTERN, (_match, stageId, outputKey) => {
102
+ if (Object.prototype.hasOwnProperty.call(outputs, stageId)) {
103
+ return outputs[stageId] ?? '';
104
+ }
105
+ throw new UnresolvedStageOutputRefError(stageId, outputKey);
106
+ });
107
+ }
@@ -0,0 +1,247 @@
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 type { LLMProvider, TokenUsage, OutputFormat } from './types.js';
16
+ import type { LLMProviderRegistry } from './provider-registry.js';
17
+ import type { PricingResolver } from './pricing.js';
18
+ import { createModelResolver, type ModelResolver, type PipelineLike, type PipelineStageLike, type SkillLike } from './model-resolver.js';
19
+ import { type PipelineEventSink } from './streaming-events.js';
20
+ import { type RuntimeConstraints } from './runtime-constraints.js';
21
+ import { type PipelineFetcher, type CompositionConfig } from './composition.js';
22
+ export interface ResolvedUse {
23
+ id: string;
24
+ version: string | null;
25
+ }
26
+ export interface SkillInvocationDetail {
27
+ stage_id: string;
28
+ skill_id: string;
29
+ requested_version: string | null;
30
+ actual_version: string;
31
+ version_pin: 'strict' | 'loose';
32
+ content_hash: string;
33
+ fetched_at: string;
34
+ ok: boolean;
35
+ error?: string;
36
+ }
37
+ export interface MCPDetail {
38
+ declared_servers: string[];
39
+ declared_tools: string[];
40
+ validated_servers: string[];
41
+ validated_tools: string[];
42
+ }
43
+ export interface NestedCallRecord {
44
+ step_id: string;
45
+ skill_id: string;
46
+ duration_ms: number;
47
+ ok: boolean;
48
+ }
49
+ export interface StageExecutionResult {
50
+ output: string;
51
+ costMicroUsdc: number;
52
+ usage: TokenUsage;
53
+ nestedCalls: NestedCallRecord[];
54
+ modelUsed: string;
55
+ usesDetails?: SkillInvocationDetail[];
56
+ mcp?: MCPDetail;
57
+ working_dir?: string;
58
+ working_dir_ignored_on_server?: boolean;
59
+ }
60
+ export interface MCPValidationResult {
61
+ valid: boolean;
62
+ validated_servers: string[];
63
+ validated_tools: string[];
64
+ unknown_servers: string[];
65
+ unknown_tools: string[];
66
+ }
67
+ export interface StageExecutorDeps {
68
+ provider: LLMProvider;
69
+ /**
70
+ * Optional. Invoked per-stage when the stage declares `provider:`
71
+ * (R6.2). Falls back to top-level `provider` field if absent;
72
+ * R6.4+R6.6 will make the registry path the default.
73
+ */
74
+ registry?: LLMProviderRegistry;
75
+ pricing: PricingResolver;
76
+ modelResolver: ModelResolver;
77
+ fetchSkill: (skillId: string) => Promise<SkillLike | null>;
78
+ /**
79
+ * Optional pipeline fetcher for composition refs (R10.7.b, ADR Q10).
80
+ * When supplied, runPipelineV2 walks the spec once before the loop and
81
+ * expands any stage declaring `uses: "pipeline:NAME@VERSION"` by
82
+ * calling this fetcher and inlining the resolved pipeline's stages
83
+ * with parent.id prefix. Recursion capped at MAX_COMPOSITION_DEPTH (4).
84
+ */
85
+ fetchPipeline?: PipelineFetcher;
86
+ /**
87
+ * Optional. Invoked when stage declares `mcp_servers` / `mcp_tools`.
88
+ * If it returns `unknown_*`, executor throws `StageMCPConfigError`.
89
+ * If omitted, declared values are accepted verbatim (forward-compat for
90
+ * v0.2 specs that will only execute MCP tool calls in v0.3).
91
+ */
92
+ validateMCPRefs?: (declaredServers: string[], declaredTools: string[]) => MCPValidationResult;
93
+ getCurrentAgentId: () => string;
94
+ getPipelineAuthorId: () => string;
95
+ isLocal: boolean;
96
+ /**
97
+ * Optional event sink for retry-time emissions (v0.3 ADR Q11). When
98
+ * present, `runWithRetry` emits a `stage.retry` event for each
99
+ * retryable failure that triggers another attempt. Threaded through
100
+ * from `RunPipelineOptions.eventSink` by `runPipelineV2`.
101
+ */
102
+ eventSink?: PipelineEventSink;
103
+ }
104
+ export interface RetryContext {
105
+ stageId: string;
106
+ eventSink?: PipelineEventSink;
107
+ }
108
+ export interface StageContext {
109
+ inputs: Record<string, unknown>;
110
+ previousOutputs: Record<string, string>;
111
+ }
112
+ export declare function makeWhenResolve(inputs: Record<string, unknown>, outputs: Record<string, string>): (template: string) => string;
113
+ export declare function parseUsesEntry(raw: string): ResolvedUse;
114
+ export declare function parseUsesList(stage: PipelineStageLike): ResolvedUse[];
115
+ export declare function validateOutputFormat(text: string, outputFormat: OutputFormat | undefined, requiredFields: string[] | undefined): void;
116
+ export declare class StageNotFoundError extends Error {
117
+ constructor(message: string);
118
+ }
119
+ export declare class StageForbiddenError extends Error {
120
+ constructor(message: string);
121
+ }
122
+ export declare class StageBadConfigError extends Error {
123
+ constructor(message: string);
124
+ }
125
+ export declare function executeStage(stage: PipelineStageLike, pipeline: PipelineLike | undefined, ctx: StageContext, deps: StageExecutorDeps): Promise<StageExecutionResult>;
126
+ export interface RunPipelineOptions {
127
+ spec: {
128
+ name?: string;
129
+ version?: string;
130
+ stages: PipelineStageLike[];
131
+ defaults?: {
132
+ model?: string;
133
+ };
134
+ /**
135
+ * Per-pipeline composition overrides (v0.3 ADR Q4). `max_depth` caps
136
+ * the recursion depth of inline `uses: "pipeline:NAME@VERSION"`
137
+ * references — defaults to `MAX_COMPOSITION_DEPTH` (4) when unset.
138
+ */
139
+ composition?: CompositionConfig;
140
+ };
141
+ inputs: Record<string, unknown>;
142
+ deps: StageExecutorDeps;
143
+ hooks?: {
144
+ onStageStart?: (stageId: string) => void;
145
+ onStageComplete?: (stageId: string, ms: number, output: string) => void;
146
+ };
147
+ /**
148
+ * Optional event sink for streaming lifecycle events (ADR Q4).
149
+ * Stage hooks above are still emitted regardless; the sink is
150
+ * additive and targetable by external integrations (dashboards,
151
+ * webhooks, log aggregators).
152
+ */
153
+ eventSink?: PipelineEventSink;
154
+ /**
155
+ * Optional runtime constraints (ADR Q9). Validation errors throw
156
+ * before the stage executes; warnings surface as constraint_warning
157
+ * events on the sink but do not block execution.
158
+ */
159
+ constraints?: RuntimeConstraints;
160
+ /**
161
+ * Optional DAG-parallel execution (R10.5.b, ADR Q7). When `true`,
162
+ * stages with no inter-dependencies run concurrently via
163
+ * Promise.allSettled; sibling failures short-circuit the batch
164
+ * (pipeline.failed + throw) while preserving any sibling output
165
+ * that did complete. Default false = sequential, preserving v0.2
166
+ * runtime semantics for callers that didn't opt in.
167
+ */
168
+ parallel?: boolean;
169
+ /**
170
+ * Optional checkpoint storage (R10.4, ADR Q6). When supplied,
171
+ * runPipelineV2 snapshots state before each execution group and
172
+ * can resume a previously-snapshotted run by passing the same
173
+ * `runId`. Resumed runs skip already-completed stages (use
174
+ * snapshotted outputs verbatim) and continue executing pending
175
+ * stages. Throws CheckpointSchemaMismatchError on stale snapshots.
176
+ * Pass null/undefined to disable checkpointing entirely
177
+ * (default).
178
+ */
179
+ checkpointStorage?: import('./checkpoints.js').CheckpointStorage;
180
+ /**
181
+ * Required when `checkpointStorage` is supplied. Identifies the
182
+ * pipeline run; on resume, load the existing snapshot via this id.
183
+ * If absent on a checkpointed run, a UUID is generated and the
184
+ * pipeline is NOT resumable.
185
+ */
186
+ runId?: string;
187
+ /**
188
+ * If true, the `runId` returned from a previous runPipelineV2 call
189
+ * (now in `outputs`/`stageTimings` metadata) is used to load any
190
+ * existing checkpoint at start. Default false — pipeline always
191
+ * starts fresh.
192
+ */
193
+ resume?: boolean;
194
+ /**
195
+ * Optional per-stage provider resolver (Phase 6 server refactor).
196
+ * When supplied, invoked with the resolved stage model name
197
+ * (`stage.model ?? spec.defaults?.model ?? 'MiniMax-M3'`) to
198
+ * produce a provider for that specific stage. Allows callers
199
+ * (e.g., the server route) that route models to different
200
+ * providers based on the model name (claude/gpt/mistral/llama →
201
+ * OpenRouter, default → MiniMax) to use runPipelineV2 without
202
+ * losing per-stage provider selection. Falls back to `deps.provider`
203
+ * when omitted (default — same v0.2 semantics).
204
+ */
205
+ providerResolver?: (model: string) => LLMProvider;
206
+ }
207
+ export interface RunPipelineResult {
208
+ outputs: Record<string, string>;
209
+ stageTimings: Array<{
210
+ id: string;
211
+ ms: number;
212
+ costMicroUsdc: number;
213
+ model: string;
214
+ skillIds?: string[];
215
+ }>;
216
+ totalCostMicroUsdc: number;
217
+ /** v0.2 NEW: per-stage skill load provenance. */
218
+ stageProvenance?: Record<string, {
219
+ uses_details: SkillInvocationDetail[];
220
+ mcp?: MCPDetail;
221
+ working_dir?: string;
222
+ working_dir_ignored_on_server?: boolean;
223
+ }>;
224
+ /**
225
+ * Phase 6 NEW: flattened per-skill invocation records from every
226
+ * stage. Each entry has the same shape as
227
+ * `StageExecutionResult.nestedCalls` (`{step_id, skill_id,
228
+ * duration_ms, ok}`). Order: in document order across stages.
229
+ * Useful for callers that want step-level provenance without
230
+ * walking `stageProvenance` (e.g., the server route exposes this
231
+ * directly in `provenance.nested_calls`).
232
+ */
233
+ nestedCalls?: NestedCallRecord[];
234
+ /**
235
+ * R10.4 NEW: when checkpointStorage was supplied, the run_id used
236
+ * (either passed in or generated). Save this alongside any other
237
+ * pipeline metadata so a resume can pass it back.
238
+ */
239
+ runId?: string;
240
+ /**
241
+ * R10.4 NEW: count of stages skipped on resume because their
242
+ * output was already in the loaded checkpoint. 0 for fresh runs.
243
+ */
244
+ resumedFromCheckpoint?: number;
245
+ }
246
+ export declare function runPipelineV2(opts: RunPipelineOptions): Promise<RunPipelineResult>;
247
+ export { createModelResolver };