@agentsmarket/pipeline-runtime 0.5.13 → 0.7.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.
@@ -13,4 +13,9 @@
13
13
  * most `max` element issues, however long it is.
14
14
  */
15
15
  import { z } from 'zod';
16
- export declare function cappedArray<T extends z.ZodTypeAny>(element: T, max: number): z.ZodEffects<z.ZodArray<T>, z.ZodArray<T>['_output'], unknown>;
16
+ /**
17
+ * The return type is inferred on purpose: zod v4 dropped the exported
18
+ * `ZodEffects` type (v4's `z.preprocess` returns a pipe), and naming the
19
+ * old type here would break the build for a shape nobody reads.
20
+ */
21
+ export declare function cappedArray<T extends z.ZodTypeAny>(element: T, max: number): z.ZodPreprocess<z.ZodArray<T>, unknown>;
@@ -13,13 +13,19 @@
13
13
  * most `max` element issues, however long it is.
14
14
  */
15
15
  import { z } from 'zod';
16
+ /**
17
+ * The return type is inferred on purpose: zod v4 dropped the exported
18
+ * `ZodEffects` type (v4's `z.preprocess` returns a pipe), and naming the
19
+ * old type here would break the build for a shape nobody reads.
20
+ */
16
21
  export function cappedArray(element, max) {
17
22
  return z.preprocess((value, ctx) => {
18
23
  if (Array.isArray(value) && value.length > max) {
19
24
  ctx.addIssue({
20
25
  code: z.ZodIssueCode.too_big,
21
26
  maximum: max,
22
- type: 'array',
27
+ // v3 called this field `type`; v4 calls it `origin`.
28
+ origin: 'array',
23
29
  inclusive: true,
24
30
  message: `must contain at most ${max} item(s)`,
25
31
  });
package/dist/index.d.ts CHANGED
@@ -4,6 +4,7 @@
4
4
  * Public API: providers (MiniMax, OpenRouter), stage executor (executeStage,
5
5
  * runPipelineV2), pricing (PricingResolver), model resolver.
6
6
  */
7
+ import type { PipelineLimits } from './limits.js';
7
8
  export type { LLMProvider, GenerateOptions, GenerateResult, Complexity, ProviderRegistry, TokenUsage, OutputFormat, OutputFormatViolation, } from './types.js';
8
9
  export { resolveProvider, StageOutputFormatError, StageSkillVersionMismatchError, StageMCPConfigError, } from './types.js';
9
10
  export type { TextMessagePart, ImageMessagePart, AudioMessagePart, VideoMessagePart, MultimodalPart, MultimodalRole, MultimodalMessage, StagePrompt, } from './multimodal.js';
@@ -38,9 +39,11 @@ export type { PricingResolver, PricingEntry } from './pricing.js';
38
39
  export { OpenRouterPricingResolver, MiniMaxPricingResolver, StaticPricingResolver, CompositePricingResolver, createDefaultPricingResolver, } from './pricing.js';
39
40
  export { buildCheckpoint, restoreFromCheckpoint, R2CheckpointStorage, InMemoryCheckpointStorage, CheckpointLoadError, CheckpointSaveError, CheckpointSchemaMismatchError, CHECKPOINT_SCHEMA_VERSION, } from './checkpoints.js';
40
41
  export type { PipelineCheckpoint, CheckpointStorage, R2BucketLike, CompletedStageRecord, RestoreResult, } from './checkpoints.js';
41
- export { createModelResolver, resolveModelSync, DEFAULT_MODEL, type ModelResolver, type ModelResolverOptions, type PipelineLike, type PipelineStageLike, type SkillLike, } from './model-resolver.js';
42
+ export { createModelResolver, resolveModelSync, DEFAULT_MODEL, STAGE_FIELDS, type ModelResolver, type ModelResolverOptions, type PipelineLike, type PipelineStageLike, type SkillLike, } from './model-resolver.js';
42
43
  export { sha256Hex, computeSkillContentHash, } from './content-hash.js';
44
+ export { canonicalJson, computeHashFromValue, computeInputsHash, computeOutputsHash, } from './receipt-hash.js';
43
45
  export { executeStage, runPipelineV2, makeWhenResolve, parseUsesEntry, parseUsesList, validateOutputFormat, StageNotFoundError, StageForbiddenError, StageBadConfigError, type StageExecutorDeps, type StageContext, type StageExecutionResult, type RunPipelineOptions, type RunPipelineResult, type NestedCallRecord, type ResolvedUse, type SkillInvocationDetail, type MCPValidationResult, type MCPDetail, } from './stages.js';
46
+ export { PipelineLimitExceededError, normalizePipelineLimits, type PipelineLimits, type PipelineLimitKind, } from './limits.js';
44
47
  export { validateInputs, formatInputErrors, applyInputDefaults, type InputDecl, type InputSpec, type InputValidationError, } from './validate-inputs.js';
45
48
  export { validateMultimodalInput, type MultimodalValidationError, type MultimodalValidationResult, } from './validate-inputs.js';
46
49
  export { parseMediaUrl, detectMime, isImageMime, isAudioMime, isVideoMime, SUPPORTED_IMAGE_MIME, SUPPORTED_AUDIO_MIME, SUPPORTED_VIDEO_MIME, toAnthropicContent, type ParsedMedia, type AnthropicContentBlock, } from './adapters/multimodal-convert.js';
@@ -66,6 +69,8 @@ export interface PipelineSpec {
66
69
  name: string;
67
70
  version: string;
68
71
  stages: PipelineStageSpec[];
72
+ /** Per-pipeline resource ceilings (spec §7). */
73
+ limits?: PipelineLimits;
69
74
  }
70
75
  export interface PipelineContext {
71
76
  provider: import('./types.js').LLMProvider;
package/dist/index.js CHANGED
@@ -22,9 +22,11 @@ export { tryParsePipelineUses, resolvePipelineRef, injectNestedStages, expandCom
22
22
  export { tryParseStageOutputRef, resolveStageOutputRefs, UnresolvedStageOutputRefError, } from './stage-output-refs.js';
23
23
  export { OpenRouterPricingResolver, MiniMaxPricingResolver, StaticPricingResolver, CompositePricingResolver, createDefaultPricingResolver, } from './pricing.js';
24
24
  export { buildCheckpoint, restoreFromCheckpoint, R2CheckpointStorage, InMemoryCheckpointStorage, CheckpointLoadError, CheckpointSaveError, CheckpointSchemaMismatchError, CHECKPOINT_SCHEMA_VERSION, } from './checkpoints.js';
25
- export { createModelResolver, resolveModelSync, DEFAULT_MODEL, } from './model-resolver.js';
25
+ export { createModelResolver, resolveModelSync, DEFAULT_MODEL, STAGE_FIELDS, } from './model-resolver.js';
26
26
  export { sha256Hex, computeSkillContentHash, } from './content-hash.js';
27
+ export { canonicalJson, computeHashFromValue, computeInputsHash, computeOutputsHash, } from './receipt-hash.js';
27
28
  export { executeStage, runPipelineV2, makeWhenResolve, parseUsesEntry, parseUsesList, validateOutputFormat, StageNotFoundError, StageForbiddenError, StageBadConfigError, } from './stages.js';
29
+ export { PipelineLimitExceededError, normalizePipelineLimits, } from './limits.js';
28
30
  export { validateInputs, formatInputErrors, applyInputDefaults, } from './validate-inputs.js';
29
31
  export { validateMultimodalInput, } from './validate-inputs.js';
30
32
  export { parseMediaUrl, detectMime, isImageMime, isAudioMime, isVideoMime, SUPPORTED_IMAGE_MIME, SUPPORTED_AUDIO_MIME, SUPPORTED_VIDEO_MIME, toAnthropicContent, } from './adapters/multimodal-convert.js';
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Per-pipeline resource ceilings — the `limits:` block of the pipeline spec
3
+ * (pipeline spec §7):
4
+ *
5
+ * limits:
6
+ * total_tokens: 30000 # across all stages
7
+ * total_cost_usdc: 0.50 # across all stages
8
+ * timeout_seconds: 600 # wall-clock budget for the whole run
9
+ *
10
+ * The runner aborts the run when a stage pushes the cumulative usage past a
11
+ * ceiling, and the error names the ceiling that fired: a run that stops
12
+ * without saying which budget ran out looks exactly like a broken pipeline.
13
+ */
14
+ /** The three ceilings the spec defines. All optional — an absent block means "no ceiling". */
15
+ export interface PipelineLimits {
16
+ /** Cumulative tokens (input + output) across all stages. */
17
+ total_tokens?: number;
18
+ /** Cumulative cost across all stages, in USDC (not micro-USDC). */
19
+ total_cost_usdc?: number;
20
+ /** Wall-clock budget for the whole run, in seconds. */
21
+ timeout_seconds?: number;
22
+ }
23
+ export type PipelineLimitKind = 'total_tokens' | 'total_cost_usdc' | 'timeout_seconds';
24
+ /**
25
+ * Thrown when a run crosses one of the spec's ceilings. The server turns it
26
+ * into a `LIMIT_EXCEEDED` envelope; the CLI prints the message as is.
27
+ */
28
+ export declare class PipelineLimitExceededError extends Error {
29
+ readonly limit: PipelineLimitKind;
30
+ readonly actual: number;
31
+ readonly limitValue: number;
32
+ readonly stageId?: string;
33
+ constructor(limit: PipelineLimitKind, actual: number, limitValue: number, stageId?: string);
34
+ }
35
+ /**
36
+ * Read the `limits:` block out of a parsed spec.
37
+ *
38
+ * Tolerates a spec without one and drops fields that are not finite numbers:
39
+ * a typo in the YAML must not become a ceiling of `NaN` that every run
40
+ * trips over, nor a ceiling of `0` tokens that aborts a run before its first
41
+ * stage. A cost of `0` is kept — a zero budget is a real budget.
42
+ */
43
+ export declare function normalizePipelineLimits(raw: unknown): PipelineLimits | undefined;
package/dist/limits.js ADDED
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Per-pipeline resource ceilings — the `limits:` block of the pipeline spec
3
+ * (pipeline spec §7):
4
+ *
5
+ * limits:
6
+ * total_tokens: 30000 # across all stages
7
+ * total_cost_usdc: 0.50 # across all stages
8
+ * timeout_seconds: 600 # wall-clock budget for the whole run
9
+ *
10
+ * The runner aborts the run when a stage pushes the cumulative usage past a
11
+ * ceiling, and the error names the ceiling that fired: a run that stops
12
+ * without saying which budget ran out looks exactly like a broken pipeline.
13
+ */
14
+ /**
15
+ * Thrown when a run crosses one of the spec's ceilings. The server turns it
16
+ * into a `LIMIT_EXCEEDED` envelope; the CLI prints the message as is.
17
+ */
18
+ export class PipelineLimitExceededError extends Error {
19
+ limit;
20
+ actual;
21
+ limitValue;
22
+ stageId;
23
+ constructor(limit, actual, limitValue, stageId) {
24
+ super(`pipeline limit exceeded: ${limit} (${actual} > ${limitValue})`
25
+ + (stageId ? ` at stage '${stageId}'` : ''));
26
+ this.name = 'LIMIT_EXCEEDED';
27
+ this.limit = limit;
28
+ this.actual = actual;
29
+ this.limitValue = limitValue;
30
+ this.stageId = stageId;
31
+ }
32
+ }
33
+ /**
34
+ * Read the `limits:` block out of a parsed spec.
35
+ *
36
+ * Tolerates a spec without one and drops fields that are not finite numbers:
37
+ * a typo in the YAML must not become a ceiling of `NaN` that every run
38
+ * trips over, nor a ceiling of `0` tokens that aborts a run before its first
39
+ * stage. A cost of `0` is kept — a zero budget is a real budget.
40
+ */
41
+ export function normalizePipelineLimits(raw) {
42
+ if (!raw || typeof raw !== 'object')
43
+ return undefined;
44
+ const src = raw;
45
+ const out = {};
46
+ const tokens = Number(src.total_tokens);
47
+ if (Number.isFinite(tokens) && tokens > 0)
48
+ out.total_tokens = tokens;
49
+ const cost = Number(src.total_cost_usdc);
50
+ if (Number.isFinite(cost) && cost >= 0)
51
+ out.total_cost_usdc = cost;
52
+ const timeout = Number(src.timeout_seconds);
53
+ if (Number.isFinite(timeout) && timeout > 0)
54
+ out.timeout_seconds = timeout;
55
+ return Object.keys(out).length > 0 ? out : undefined;
56
+ }
@@ -36,6 +36,30 @@ export interface PipelineStageLike {
36
36
  * `input:` twice. Both are honoured; singular wins if both are somehow set.
37
37
  */
38
38
  inputs?: unknown;
39
+ /**
40
+ * The pipeline inputs this stage reads.
41
+ *
42
+ * Undefined — the default, and what every published spec was written
43
+ * against — means every input, which is how the runtime has always
44
+ * behaved. A list narrows the `Inputs:` block the stage's prompt is
45
+ * given: only those inputs are in it, and the rest are not sent to the
46
+ * model at all.
47
+ *
48
+ * It narrows the block only. An input the stage's own prompt names is
49
+ * kept either way — `{{code_diff}}` is substituted into the prompt, and
50
+ * `$input.code_diff`, which is not substituted in a prompt, keeps its
51
+ * input in the block. A stage cannot be given less than its prompt asks
52
+ * it to read.
53
+ */
54
+ reads?: string[];
55
+ /**
56
+ * The secret names a shell stage declares. The runtime resolves them
57
+ * against the buyer's secrets; the type did not say so, and the CLI
58
+ * validator learned the vocabulary from this interface — a field the
59
+ * runtime reads that the interface omits is a field the validator calls
60
+ * unknown.
61
+ */
62
+ secrets?: string[];
39
63
  system?: string;
40
64
  prompt?: string | readonly import('./multimodal.js').MultimodalMessage[];
41
65
  /**
@@ -192,6 +216,21 @@ export interface PipelineStageLike {
192
216
  */
193
217
  output_retry?: import('./output-errors.js').OutputValidationMode;
194
218
  }
219
+ /**
220
+ * The stage fields the runtime reads, plus `run_if`, which the CLI
221
+ * validator still checks although the runtime no longer acts on it.
222
+ *
223
+ * It is a list of names, not a schema: the runtime ignores an unknown
224
+ * field rather than refusing the spec, so a spec that carries one is
225
+ * never broken by it. The list exists so that a field which is one typo
226
+ * away from a real one is not silent — `read:` is not `reads:`, and the
227
+ * difference is a stage that quietly reads every input again.
228
+ *
229
+ * Kept next to `PipelineStageLike` on purpose: that interface is the
230
+ * authority on what a stage may carry, and a field added there should
231
+ * be added here.
232
+ */
233
+ export declare const STAGE_FIELDS: readonly string[];
195
234
  export interface PipelineLike {
196
235
  name?: string;
197
236
  version?: string;
@@ -16,6 +16,50 @@
16
16
  *
17
17
  * Cost of a stage is always based on the resolved model, regardless of who declared it.
18
18
  */
19
+ /**
20
+ * The stage fields the runtime reads, plus `run_if`, which the CLI
21
+ * validator still checks although the runtime no longer acts on it.
22
+ *
23
+ * It is a list of names, not a schema: the runtime ignores an unknown
24
+ * field rather than refusing the spec, so a spec that carries one is
25
+ * never broken by it. The list exists so that a field which is one typo
26
+ * away from a real one is not silent — `read:` is not `reads:`, and the
27
+ * difference is a stage that quietly reads every input again.
28
+ *
29
+ * Kept next to `PipelineStageLike` on purpose: that interface is the
30
+ * authority on what a stage may carry, and a field added there should
31
+ * be added here.
32
+ */
33
+ export const STAGE_FIELDS = [
34
+ 'id',
35
+ 'model',
36
+ 'system',
37
+ 'prompt',
38
+ 'provider',
39
+ 'uses',
40
+ 'uses_version',
41
+ 'input',
42
+ 'inputs',
43
+ 'reads',
44
+ 'secrets',
45
+ 'output_format',
46
+ 'fields',
47
+ 'maxTokens',
48
+ 'model_params',
49
+ 'mcp_servers',
50
+ 'mcp_tools',
51
+ 'working_dir',
52
+ 'shell',
53
+ 'loop',
54
+ 'when',
55
+ 'run_if',
56
+ 'depends_on',
57
+ 'requires',
58
+ 'needs',
59
+ 'retry',
60
+ 'output_schema',
61
+ 'output_retry',
62
+ ];
19
63
  export const DEFAULT_MODEL = 'MiniMax-M3';
20
64
  export function createModelResolver(opts = {}) {
21
65
  const hardcoded = opts.hardcodedDefault ?? DEFAULT_MODEL;
@@ -0,0 +1,31 @@
1
+ /**
2
+ * The hashes of a receipt — the binding between a spec, its inputs and its
3
+ * outputs.
4
+ *
5
+ * Why they live HERE and not in the server: the server computes them for a
6
+ * run it executes, but a peer that runs a pipeline ON ITS OWN MACHINE (the
7
+ * delegation of a contract) has to compute the same hashes — otherwise the
8
+ * receipt of one run cannot be compared with the receipt of the same run on
9
+ * the server, and neither proves anything.
10
+ *
11
+ * One implementation, one algorithm: keccak256 over canonical JSON (recursively
12
+ * sorted keys). Off-platform verifiers in ethers.js / web3.py / viem produce
13
+ * the same bytes.
14
+ *
15
+ * There is no hash of the SPEC here, and that is deliberate: the spec of a
16
+ * receipt is the PUBLISHED hash of the pipeline version that ran — the value
17
+ * the catalogue holds for it. A verifier compares it with the catalogue by
18
+ * EQUALITY, without needing the source of the pipeline; a digest of the
19
+ * source in some other form could be compared with nothing.
20
+ */
21
+ /**
22
+ * Canonical JSON: the keys of every object are sorted, so the same value
23
+ * always hashes to the same bytes.
24
+ */
25
+ export declare function canonicalJson(value: unknown): string;
26
+ /** keccak256 of canonicalised JSON of `value`. Returns 0x + 64 hex. */
27
+ export declare function computeHashFromValue(value: Record<string, unknown>): string;
28
+ /** keccak256 of canonicalised inputs. */
29
+ export declare function computeInputsHash(inputsValues: Record<string, unknown>): string;
30
+ /** keccak256 of canonicalised outputs. */
31
+ export declare function computeOutputsHash(outputsValues: Record<string, unknown>): string;
@@ -0,0 +1,58 @@
1
+ /**
2
+ * The hashes of a receipt — the binding between a spec, its inputs and its
3
+ * outputs.
4
+ *
5
+ * Why they live HERE and not in the server: the server computes them for a
6
+ * run it executes, but a peer that runs a pipeline ON ITS OWN MACHINE (the
7
+ * delegation of a contract) has to compute the same hashes — otherwise the
8
+ * receipt of one run cannot be compared with the receipt of the same run on
9
+ * the server, and neither proves anything.
10
+ *
11
+ * One implementation, one algorithm: keccak256 over canonical JSON (recursively
12
+ * sorted keys). Off-platform verifiers in ethers.js / web3.py / viem produce
13
+ * the same bytes.
14
+ *
15
+ * There is no hash of the SPEC here, and that is deliberate: the spec of a
16
+ * receipt is the PUBLISHED hash of the pipeline version that ran — the value
17
+ * the catalogue holds for it. A verifier compares it with the catalogue by
18
+ * EQUALITY, without needing the source of the pipeline; a digest of the
19
+ * source in some other form could be compared with nothing.
20
+ */
21
+ import { id } from 'ethers';
22
+ /**
23
+ * Canonical JSON: the keys of every object are sorted, so the same value
24
+ * always hashes to the same bytes.
25
+ */
26
+ export function canonicalJson(value) {
27
+ if (value === null)
28
+ return 'null';
29
+ if (typeof value === 'number')
30
+ return Number.isFinite(value) ? String(value) : 'null';
31
+ if (typeof value === 'string')
32
+ return JSON.stringify(value);
33
+ if (typeof value === 'boolean')
34
+ return String(value);
35
+ if (Array.isArray(value)) {
36
+ return '[' + value.map(canonicalJson).join(',') + ']';
37
+ }
38
+ if (typeof value === 'object') {
39
+ const obj = value;
40
+ const keys = Object.keys(obj).sort();
41
+ return '{' + keys
42
+ .map(k => JSON.stringify(k) + ':' + canonicalJson(obj[k]))
43
+ .join(',') + '}';
44
+ }
45
+ return 'null';
46
+ }
47
+ /** keccak256 of canonicalised JSON of `value`. Returns 0x + 64 hex. */
48
+ export function computeHashFromValue(value) {
49
+ return id(canonicalJson(value));
50
+ }
51
+ /** keccak256 of canonicalised inputs. */
52
+ export function computeInputsHash(inputsValues) {
53
+ return computeHashFromValue(inputsValues);
54
+ }
55
+ /** keccak256 of canonicalised outputs. */
56
+ export function computeOutputsHash(outputsValues) {
57
+ return computeHashFromValue(outputsValues);
58
+ }
package/dist/stages.d.ts CHANGED
@@ -16,6 +16,7 @@ import type { LLMProvider, TokenUsage, OutputFormat } from './types.js';
16
16
  import type { LLMProviderRegistry } from './provider-registry.js';
17
17
  import type { PricingResolver } from './pricing.js';
18
18
  import { createModelResolver, type ModelResolver, type PipelineLike, type PipelineStageLike, type SkillLike } from './model-resolver.js';
19
+ import { type PipelineLimits } from './limits.js';
19
20
  import { type PipelineEventSink } from './streaming-events.js';
20
21
  import { type RuntimeConstraints } from './runtime-constraints.js';
21
22
  import { type ShellExecutor, type ShellExecFile } from './shell-stage.js';
@@ -197,6 +198,12 @@ export interface RunPipelineOptions {
197
198
  * references — defaults to `MAX_COMPOSITION_DEPTH` (4) when unset.
198
199
  */
199
200
  composition?: CompositionConfig;
201
+ /**
202
+ * Per-pipeline resource ceilings (spec §7). When a stage pushes the
203
+ * cumulative usage past one of them the run is aborted and the error
204
+ * names the ceiling that fired.
205
+ */
206
+ limits?: PipelineLimits;
200
207
  };
201
208
  inputs: Record<string, unknown>;
202
209
  deps: StageExecutorDeps;
package/dist/stages.js CHANGED
@@ -16,6 +16,7 @@ import { StageOutputFormatError, StageSkillVersionMismatchError, StageMCPConfigE
16
16
  import { assertMultimodalSupported } from './provider-registry.js';
17
17
  import { createModelResolver, } from './model-resolver.js';
18
18
  import { computeSkillContentHash } from './content-hash.js';
19
+ import { PipelineLimitExceededError } from './limits.js';
19
20
  import { shouldSkipStage } from './when.js';
20
21
  import { resolveInputRefs, resolveDoubleBraceRefs, resolveSpecialKeys } from './pipeline-refs.js';
21
22
  import { isToolSkill, invokeToolSkill } from './tools/tool-skills.js';
@@ -44,6 +45,67 @@ function buildInputsString(inputs) {
44
45
  return '';
45
46
  return entries.map(([k, v]) => `${k}: ${JSON.stringify(v)}\n`).join('');
46
47
  }
48
+ /**
49
+ * The inputs a stage's own prompt asks for.
50
+ *
51
+ * `$input.name` is not substituted in a prompt — only in a stage's provider
52
+ * and model — so a prompt that says `$input.code_diff` gets the value from
53
+ * the `Inputs:` block and from nowhere else. A stage that declares `reads:`
54
+ * therefore keeps the inputs its prompt names: the declaration narrows what
55
+ * the stage is *given*, not what it is *told to read*.
56
+ */
57
+ const PROMPT_INPUT_REF = /\$input\.([A-Za-z_][A-Za-z0-9_]*)|\$\{\s*input\.([A-Za-z_][A-Za-z0-9_]*)\s*\}/g;
58
+ function promptInputNames(stage) {
59
+ const texts = [];
60
+ if (typeof stage.system === 'string')
61
+ texts.push(stage.system);
62
+ if (typeof stage.prompt === 'string')
63
+ texts.push(stage.prompt);
64
+ else if (stage.prompt)
65
+ texts.push(JSON.stringify(stage.prompt));
66
+ const names = new Set();
67
+ for (const text of texts) {
68
+ for (const match of text.matchAll(PROMPT_INPUT_REF)) {
69
+ names.add(match[1] ?? match[2]);
70
+ }
71
+ }
72
+ return [...names];
73
+ }
74
+ /**
75
+ * The inputs a stage is given.
76
+ *
77
+ * Every stage used to be given every pipeline input, in full, so a stage
78
+ * could not be given less to read: the diff of a review pipeline reached
79
+ * the stage that aggregates the findings, and that stage paid for it on
80
+ * every run.
81
+ *
82
+ * A stage that declares `reads:` gets only those inputs, plus the ones its
83
+ * own prompt asks for. A stage that declares nothing gets all of them —
84
+ * that default is the behaviour every published spec was written against,
85
+ * which is why this is opt-in and not a change of the default.
86
+ *
87
+ * A name that is not an input of the pipeline is ignored, not an error: a
88
+ * spec may declare a stage that reads an input the caller did not send, and
89
+ * the stage still runs. A `reads` that is not a list of names at all falls
90
+ * back to every input, which is what the stage would have read anyway.
91
+ */
92
+ function selectStageInputs(inputs, reads, stage) {
93
+ if (!Array.isArray(reads))
94
+ return inputs;
95
+ // The scan is the price of the field, and only a stage that declares it
96
+ // pays: every other stage keeps the behaviour it had.
97
+ const names = new Set(promptInputNames(stage));
98
+ for (const name of reads) {
99
+ if (typeof name === 'string')
100
+ names.add(name);
101
+ }
102
+ const picked = {};
103
+ for (const name of names) {
104
+ if (Object.prototype.hasOwnProperty.call(inputs, name))
105
+ picked[name] = inputs[name];
106
+ }
107
+ return picked;
108
+ }
47
109
  /**
48
110
  * All three documented interpolation engines, for `prompt` and `system`.
49
111
  *
@@ -455,7 +517,7 @@ correctionHint) {
455
517
  : undefined;
456
518
  const workingDirIgnoredOnServer = !!workingDir && !deps.isLocal;
457
519
  const previousContext = buildPreviousContext(ctx.previousOutputs);
458
- const inputsString = buildInputsString(ctx.inputs);
520
+ const inputsString = buildInputsString(selectStageInputs(ctx.inputs, stage.reads, stage));
459
521
  const retryCtx = deps.eventSink
460
522
  ? { stageId: stage.id, eventSink: deps.eventSink }
461
523
  : undefined;
@@ -771,11 +833,43 @@ correctionHint) {
771
833
  ...(workingDir ? { working_dir: workingDir, working_dir_ignored_on_server: workingDirIgnoredOnServer } : {}),
772
834
  };
773
835
  }
836
+ /**
837
+ * The `limits:` ceilings of the spec §7, checked against the run so far.
838
+ *
839
+ * Returns the error to abort the run with, or null while the run is still
840
+ * inside its budget. The cost counter is micro-USDC (what the runtime prices
841
+ * in) while the ceiling is USDC (what the author writes).
842
+ */
843
+ function evaluateLimits(shared, stageId) {
844
+ const limits = shared.opts.spec.limits;
845
+ if (!limits)
846
+ return null;
847
+ const tokens = shared.totalTokensRef.value;
848
+ if (typeof limits.total_tokens === 'number' && tokens > limits.total_tokens) {
849
+ return new PipelineLimitExceededError('total_tokens', tokens, limits.total_tokens, stageId);
850
+ }
851
+ const costUsdc = shared.totalCostRef.value / 1_000_000;
852
+ if (typeof limits.total_cost_usdc === 'number' && costUsdc > limits.total_cost_usdc) {
853
+ return new PipelineLimitExceededError('total_cost_usdc', costUsdc, limits.total_cost_usdc, stageId);
854
+ }
855
+ const elapsedSeconds = (Date.now() - shared.startedAtMs) / 1000;
856
+ if (typeof limits.timeout_seconds === 'number' && elapsedSeconds > limits.timeout_seconds) {
857
+ return new PipelineLimitExceededError('timeout_seconds', elapsedSeconds, limits.timeout_seconds, stageId);
858
+ }
859
+ return null;
860
+ }
774
861
  async function runOneStage(stage, shared) {
775
862
  if (!stage.id) {
776
863
  return { kind: 'failed', stageId: '<no-id>', error: new StageBadConfigError('Stage missing required field: id') };
777
864
  }
778
865
  const stageId = stage.id;
866
+ // The run may already be out of budget before this stage starts — a
867
+ // resumed run, or a stage that took longer than the whole budget allows.
868
+ const overBudget = evaluateLimits(shared, stageId);
869
+ if (overBudget) {
870
+ shared.emit(makeStageFailedEvent({ stageId, error: overBudget.message }));
871
+ return { kind: 'failed', stageId, error: overBudget };
872
+ }
779
873
  shared.opts.hooks?.onStageStart?.(stageId);
780
874
  shared.emit(makeStageStartedEvent(stageId));
781
875
  if (stage.when && shouldSkipStage(stage.when, shared.whenResolve)) {
@@ -831,6 +925,7 @@ async function runOneStage(stage, shared) {
831
925
  };
832
926
  shared.nestedCalls.push(...result.nestedCalls);
833
927
  shared.totalCostRef.value += result.costMicroUsdc;
928
+ shared.totalTokensRef.value += result.usage.inputTokens + result.usage.outputTokens;
834
929
  shared.opts.hooks?.onStageComplete?.(stageId, ms, result.output);
835
930
  shared.emit(makeStageCompletedEvent({
836
931
  stageId,
@@ -839,6 +934,13 @@ async function runOneStage(stage, shared) {
839
934
  model: result.modelUsed,
840
935
  output: result.output,
841
936
  }));
937
+ // The spec's MUST (§7): a stage that pushes the run past a ceiling
938
+ // aborts the run, and the error names the ceiling that fired. The stage
939
+ // itself succeeded, so its output and its cost stay recorded.
940
+ const limitError = evaluateLimits(shared, stageId);
941
+ if (limitError) {
942
+ return { kind: 'failed', stageId, error: limitError };
943
+ }
842
944
  return { kind: 'completed', stageId, ms, costMicroUsdc: result.costMicroUsdc };
843
945
  }
844
946
  catch (e) {
@@ -991,6 +1093,12 @@ export async function runPipelineV2(opts) {
991
1093
  // already have snapshotted outputs (so the loop below skips them).
992
1094
  const runId = opts.runId ?? (opts.checkpointStorage ? randomUUID() : undefined);
993
1095
  let startedAt = new Date().toISOString();
1096
+ /**
1097
+ * The wall-clock start the `limits.timeout_seconds` budget is measured
1098
+ * against. A resumed run keeps the ORIGINAL start: the budget covers the
1099
+ * pipeline, not the attempt.
1100
+ */
1101
+ let startedAtMs = Date.now();
994
1102
  const completedStageIds = new Set();
995
1103
  let resumedFromCheckpoint = 0;
996
1104
  if (runId && opts.checkpointStorage && opts.resume) {
@@ -998,6 +1106,9 @@ export async function runPipelineV2(opts) {
998
1106
  if (cp) {
999
1107
  const restored = restoreFromCheckpoint(cp);
1000
1108
  startedAt = cp.started_at;
1109
+ const restoredMs = Date.parse(cp.started_at);
1110
+ if (Number.isFinite(restoredMs))
1111
+ startedAtMs = restoredMs;
1001
1112
  for (const id of Object.keys(restored.restored_outputs)) {
1002
1113
  outputs[id] = restored.restored_outputs[id];
1003
1114
  completedStageIds.add(id);
@@ -1026,6 +1137,8 @@ export async function runPipelineV2(opts) {
1026
1137
  stageProvenance,
1027
1138
  nestedCalls,
1028
1139
  totalCostRef: { value: totalCostMicroUsdc },
1140
+ totalTokensRef: { value: 0 },
1141
+ startedAtMs,
1029
1142
  emit,
1030
1143
  };
1031
1144
  async function snapshotCheckpoint() {
@@ -1075,6 +1188,10 @@ export async function runPipelineV2(opts) {
1075
1188
  }
1076
1189
  const settled = await Promise.allSettled(liveStages.map((s) => runOneStage(s, shared)));
1077
1190
  const failedIds = [];
1191
+ // A budget abort is not a sibling failure — it is the run's own limit
1192
+ // firing, and the caller must see WHICH limit. The generic summary
1193
+ // below would hide it behind "2/3 parallel siblings failed".
1194
+ let limitError = null;
1078
1195
  for (let i = 0; i < settled.length; i++) {
1079
1196
  const r = settled[i];
1080
1197
  const stage = liveStages[i];
@@ -1083,6 +1200,9 @@ export async function runPipelineV2(opts) {
1083
1200
  }
1084
1201
  else if (r.status === 'fulfilled' && r.value.kind === 'failed') {
1085
1202
  failedIds.push(r.value.stageId);
1203
+ if (r.value.error instanceof PipelineLimitExceededError && !limitError) {
1204
+ limitError = r.value.error;
1205
+ }
1086
1206
  }
1087
1207
  else if (r.status === 'rejected') {
1088
1208
  const reason = r.reason instanceof Error ? r.reason.message : String(r.reason);
@@ -1091,6 +1211,15 @@ export async function runPipelineV2(opts) {
1091
1211
  }
1092
1212
  if (failedIds.length > 0) {
1093
1213
  await snapshotCheckpoint();
1214
+ if (limitError) {
1215
+ emit(makePipelineFailedEvent({
1216
+ pipelineName,
1217
+ pipelineVersion,
1218
+ totalMs: Date.now() - pipelineT0,
1219
+ error: limitError.message,
1220
+ }));
1221
+ throw limitError;
1222
+ }
1094
1223
  const summary = `pipeline failed: ${failedIds.length}/${liveStages.length} parallel siblings failed (${failedIds.join(', ')})`;
1095
1224
  emit(makePipelineFailedEvent({
1096
1225
  pipelineName,
@@ -1,100 +1,43 @@
1
1
  import { z } from 'zod';
2
- declare const AssertionSchema: z.ZodUnion<[z.ZodObject<{
2
+ declare const AssertionSchema: z.ZodUnion<readonly [z.ZodObject<{
3
3
  type: z.ZodLiteral<"equality">;
4
4
  path: z.ZodString;
5
5
  value: z.ZodUnknown;
6
- }, "strip", z.ZodTypeAny, {
7
- path: string;
8
- type: "equality";
9
- value?: unknown;
10
- }, {
11
- path: string;
12
- type: "equality";
13
- value?: unknown;
14
- }>, z.ZodObject<{
6
+ }, z.core.$strip>, z.ZodObject<{
15
7
  type: z.ZodLiteral<"contains">;
16
8
  path: z.ZodString;
17
- value: z.ZodUnion<[z.ZodString, z.ZodNumber, z.ZodBoolean]>;
18
- }, "strip", z.ZodTypeAny, {
19
- value: string | number | boolean;
20
- path: string;
21
- type: "contains";
22
- }, {
23
- value: string | number | boolean;
24
- path: string;
25
- type: "contains";
26
- }>, z.ZodObject<{
9
+ value: z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>;
10
+ }, z.core.$strip>, z.ZodObject<{
27
11
  type: z.ZodLiteral<"regex">;
28
12
  path: z.ZodString;
29
13
  pattern: z.ZodString;
30
14
  flags: z.ZodOptional<z.ZodString>;
31
- }, "strip", z.ZodTypeAny, {
32
- path: string;
33
- type: "regex";
34
- pattern: string;
35
- flags?: string | undefined;
36
- }, {
37
- path: string;
38
- type: "regex";
39
- pattern: string;
40
- flags?: string | undefined;
41
- }>, z.ZodObject<{
42
- type: z.ZodEnum<["gte", "lte", "gt", "lt"]>;
15
+ }, z.core.$strip>, z.ZodObject<{
16
+ type: z.ZodEnum<{
17
+ gte: "gte";
18
+ lte: "lte";
19
+ gt: "gt";
20
+ lt: "lt";
21
+ }>;
43
22
  path: z.ZodString;
44
23
  value: z.ZodNumber;
45
- }, "strip", z.ZodTypeAny, {
46
- value: number;
47
- path: string;
48
- type: "gte" | "lte" | "gt" | "lt";
49
- }, {
50
- value: number;
51
- path: string;
52
- type: "gte" | "lte" | "gt" | "lt";
53
- }>, z.ZodObject<{
24
+ }, z.core.$strip>, z.ZodObject<{
54
25
  type: z.ZodLiteral<"exists">;
55
26
  path: z.ZodString;
56
- }, "strip", z.ZodTypeAny, {
57
- path: string;
58
- type: "exists";
59
- }, {
60
- path: string;
61
- type: "exists";
62
- }>, z.ZodObject<{
27
+ }, z.core.$strip>, z.ZodObject<{
63
28
  type: z.ZodLiteral<"absent">;
64
29
  path: z.ZodString;
65
- }, "strip", z.ZodTypeAny, {
66
- path: string;
67
- type: "absent";
68
- }, {
69
- path: string;
70
- type: "absent";
71
- }>, z.ZodObject<{
30
+ }, z.core.$strip>, z.ZodObject<{
72
31
  type: z.ZodLiteral<"jsonpath">;
73
32
  path: z.ZodString;
74
33
  value: z.ZodUnknown;
75
- }, "strip", z.ZodTypeAny, {
76
- path: string;
77
- type: "jsonpath";
78
- value?: unknown;
79
- }, {
80
- path: string;
81
- type: "jsonpath";
82
- value?: unknown;
83
- }>, z.ZodObject<{
34
+ }, z.core.$strip>, z.ZodObject<{
84
35
  type: z.ZodLiteral<"schema">;
85
36
  path: z.ZodString;
86
37
  schema_file: z.ZodString;
87
- }, "strip", z.ZodTypeAny, {
88
- path: string;
89
- type: "schema";
90
- schema_file: string;
91
- }, {
92
- path: string;
93
- type: "schema";
94
- schema_file: string;
95
- }>]>;
38
+ }, z.core.$strip>]>;
96
39
  export type Assertion = z.infer<typeof AssertionSchema>;
97
- declare const TestSpecSchema: z.ZodEffects<z.ZodObject<{
40
+ declare const TestSpecSchema: z.ZodObject<{
98
41
  name: z.ZodString;
99
42
  description: z.ZodOptional<z.ZodString>;
100
43
  pipeline: z.ZodOptional<z.ZodString>;
@@ -102,230 +45,44 @@ declare const TestSpecSchema: z.ZodEffects<z.ZodObject<{
102
45
  inputs: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
103
46
  mock: z.ZodDefault<z.ZodBoolean>;
104
47
  expect_error: z.ZodOptional<z.ZodString>;
105
- assertions: z.ZodDefault<z.ZodEffects<z.ZodArray<z.ZodUnion<[z.ZodObject<{
48
+ assertions: z.ZodDefault<z.ZodPreprocess<z.ZodArray<z.ZodUnion<readonly [z.ZodObject<{
106
49
  type: z.ZodLiteral<"equality">;
107
50
  path: z.ZodString;
108
51
  value: z.ZodUnknown;
109
- }, "strip", z.ZodTypeAny, {
110
- path: string;
111
- type: "equality";
112
- value?: unknown;
113
- }, {
114
- path: string;
115
- type: "equality";
116
- value?: unknown;
117
- }>, z.ZodObject<{
52
+ }, z.core.$strip>, z.ZodObject<{
118
53
  type: z.ZodLiteral<"contains">;
119
54
  path: z.ZodString;
120
- value: z.ZodUnion<[z.ZodString, z.ZodNumber, z.ZodBoolean]>;
121
- }, "strip", z.ZodTypeAny, {
122
- value: string | number | boolean;
123
- path: string;
124
- type: "contains";
125
- }, {
126
- value: string | number | boolean;
127
- path: string;
128
- type: "contains";
129
- }>, z.ZodObject<{
55
+ value: z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>;
56
+ }, z.core.$strip>, z.ZodObject<{
130
57
  type: z.ZodLiteral<"regex">;
131
58
  path: z.ZodString;
132
59
  pattern: z.ZodString;
133
60
  flags: z.ZodOptional<z.ZodString>;
134
- }, "strip", z.ZodTypeAny, {
135
- path: string;
136
- type: "regex";
137
- pattern: string;
138
- flags?: string | undefined;
139
- }, {
140
- path: string;
141
- type: "regex";
142
- pattern: string;
143
- flags?: string | undefined;
144
- }>, z.ZodObject<{
145
- type: z.ZodEnum<["gte", "lte", "gt", "lt"]>;
61
+ }, z.core.$strip>, z.ZodObject<{
62
+ type: z.ZodEnum<{
63
+ gte: "gte";
64
+ lte: "lte";
65
+ gt: "gt";
66
+ lt: "lt";
67
+ }>;
146
68
  path: z.ZodString;
147
69
  value: z.ZodNumber;
148
- }, "strip", z.ZodTypeAny, {
149
- value: number;
150
- path: string;
151
- type: "gte" | "lte" | "gt" | "lt";
152
- }, {
153
- value: number;
154
- path: string;
155
- type: "gte" | "lte" | "gt" | "lt";
156
- }>, z.ZodObject<{
70
+ }, z.core.$strip>, z.ZodObject<{
157
71
  type: z.ZodLiteral<"exists">;
158
72
  path: z.ZodString;
159
- }, "strip", z.ZodTypeAny, {
160
- path: string;
161
- type: "exists";
162
- }, {
163
- path: string;
164
- type: "exists";
165
- }>, z.ZodObject<{
73
+ }, z.core.$strip>, z.ZodObject<{
166
74
  type: z.ZodLiteral<"absent">;
167
75
  path: z.ZodString;
168
- }, "strip", z.ZodTypeAny, {
169
- path: string;
170
- type: "absent";
171
- }, {
172
- path: string;
173
- type: "absent";
174
- }>, z.ZodObject<{
76
+ }, z.core.$strip>, z.ZodObject<{
175
77
  type: z.ZodLiteral<"jsonpath">;
176
78
  path: z.ZodString;
177
79
  value: z.ZodUnknown;
178
- }, "strip", z.ZodTypeAny, {
179
- path: string;
180
- type: "jsonpath";
181
- value?: unknown;
182
- }, {
183
- path: string;
184
- type: "jsonpath";
185
- value?: unknown;
186
- }>, z.ZodObject<{
80
+ }, z.core.$strip>, z.ZodObject<{
187
81
  type: z.ZodLiteral<"schema">;
188
82
  path: z.ZodString;
189
83
  schema_file: z.ZodString;
190
- }, "strip", z.ZodTypeAny, {
191
- path: string;
192
- type: "schema";
193
- schema_file: string;
194
- }, {
195
- path: string;
196
- type: "schema";
197
- schema_file: string;
198
- }>]>, "many">, ({
199
- path: string;
200
- type: "equality";
201
- value?: unknown;
202
- } | {
203
- value: string | number | boolean;
204
- path: string;
205
- type: "contains";
206
- } | {
207
- path: string;
208
- type: "regex";
209
- pattern: string;
210
- flags?: string | undefined;
211
- } | {
212
- value: number;
213
- path: string;
214
- type: "gte" | "lte" | "gt" | "lt";
215
- } | {
216
- path: string;
217
- type: "exists";
218
- } | {
219
- path: string;
220
- type: "absent";
221
- } | {
222
- path: string;
223
- type: "jsonpath";
224
- value?: unknown;
225
- } | {
226
- path: string;
227
- type: "schema";
228
- schema_file: string;
229
- })[], unknown>>;
230
- }, "strip", z.ZodTypeAny, {
231
- inputs: Record<string, unknown>;
232
- name: string;
233
- mock: boolean;
234
- assertions: ({
235
- path: string;
236
- type: "equality";
237
- value?: unknown;
238
- } | {
239
- value: string | number | boolean;
240
- path: string;
241
- type: "contains";
242
- } | {
243
- path: string;
244
- type: "regex";
245
- pattern: string;
246
- flags?: string | undefined;
247
- } | {
248
- value: number;
249
- path: string;
250
- type: "gte" | "lte" | "gt" | "lt";
251
- } | {
252
- path: string;
253
- type: "exists";
254
- } | {
255
- path: string;
256
- type: "absent";
257
- } | {
258
- path: string;
259
- type: "jsonpath";
260
- value?: unknown;
261
- } | {
262
- path: string;
263
- type: "schema";
264
- schema_file: string;
265
- })[];
266
- pipeline?: string | undefined;
267
- description?: string | undefined;
268
- stage?: string | undefined;
269
- expect_error?: string | undefined;
270
- }, {
271
- name: string;
272
- inputs?: Record<string, unknown> | undefined;
273
- pipeline?: string | undefined;
274
- description?: string | undefined;
275
- mock?: boolean | undefined;
276
- stage?: string | undefined;
277
- expect_error?: string | undefined;
278
- assertions?: unknown;
279
- }>, {
280
- inputs: Record<string, unknown>;
281
- name: string;
282
- mock: boolean;
283
- assertions: ({
284
- path: string;
285
- type: "equality";
286
- value?: unknown;
287
- } | {
288
- value: string | number | boolean;
289
- path: string;
290
- type: "contains";
291
- } | {
292
- path: string;
293
- type: "regex";
294
- pattern: string;
295
- flags?: string | undefined;
296
- } | {
297
- value: number;
298
- path: string;
299
- type: "gte" | "lte" | "gt" | "lt";
300
- } | {
301
- path: string;
302
- type: "exists";
303
- } | {
304
- path: string;
305
- type: "absent";
306
- } | {
307
- path: string;
308
- type: "jsonpath";
309
- value?: unknown;
310
- } | {
311
- path: string;
312
- type: "schema";
313
- schema_file: string;
314
- })[];
315
- pipeline?: string | undefined;
316
- description?: string | undefined;
317
- stage?: string | undefined;
318
- expect_error?: string | undefined;
319
- }, {
320
- name: string;
321
- inputs?: Record<string, unknown> | undefined;
322
- pipeline?: string | undefined;
323
- description?: string | undefined;
324
- mock?: boolean | undefined;
325
- stage?: string | undefined;
326
- expect_error?: string | undefined;
327
- assertions?: unknown;
328
- }>;
84
+ }, z.core.$strip>]>>, unknown>>;
85
+ }, z.core.$strip>;
329
86
  export type TestSpec = z.infer<typeof TestSpecSchema>;
330
87
  export declare class TestSpecParseError extends Error {
331
88
  constructor(message: string);
@@ -29,7 +29,7 @@ const TestSpecSchema = z.object({
29
29
  description: z.string().optional(),
30
30
  pipeline: z.string().optional(),
31
31
  stage: z.string().optional(),
32
- inputs: z.record(z.unknown()).default({}),
32
+ inputs: z.record(z.string(), z.unknown()).default({}),
33
33
  mock: z.boolean().default(true),
34
34
  expect_error: z.string().optional(),
35
35
  assertions: cappedArray(AssertionSchema, MAX_ASSERTIONS).default([]),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentsmarket/pipeline-runtime",
3
- "version": "0.5.13",
3
+ "version": "0.7.0",
4
4
  "description": "Runtime for executing PIPELINE.md workflows (multi-skill orchestration). Provider-agnostic (MiniMax, Claude, OpenAI).",
5
5
  "license": "MIT",
6
6
  "type": "module",