@agentsmarket/pipeline-runtime 0.6.0 → 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.
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';
@@ -40,7 +41,9 @@ export { buildCheckpoint, restoreFromCheckpoint, R2CheckpointStorage, InMemoryCh
40
41
  export type { PipelineCheckpoint, CheckpointStorage, R2BucketLike, CompletedStageRecord, RestoreResult, } from './checkpoints.js';
41
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
@@ -24,7 +24,9 @@ export { OpenRouterPricingResolver, MiniMaxPricingResolver, StaticPricingResolve
24
24
  export { buildCheckpoint, restoreFromCheckpoint, R2CheckpointStorage, InMemoryCheckpointStorage, CheckpointLoadError, CheckpointSaveError, CheckpointSchemaMismatchError, CHECKPOINT_SCHEMA_VERSION, } from './checkpoints.js';
25
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
+ }
@@ -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';
@@ -832,11 +833,43 @@ correctionHint) {
832
833
  ...(workingDir ? { working_dir: workingDir, working_dir_ignored_on_server: workingDirIgnoredOnServer } : {}),
833
834
  };
834
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
+ }
835
861
  async function runOneStage(stage, shared) {
836
862
  if (!stage.id) {
837
863
  return { kind: 'failed', stageId: '<no-id>', error: new StageBadConfigError('Stage missing required field: id') };
838
864
  }
839
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
+ }
840
873
  shared.opts.hooks?.onStageStart?.(stageId);
841
874
  shared.emit(makeStageStartedEvent(stageId));
842
875
  if (stage.when && shouldSkipStage(stage.when, shared.whenResolve)) {
@@ -892,6 +925,7 @@ async function runOneStage(stage, shared) {
892
925
  };
893
926
  shared.nestedCalls.push(...result.nestedCalls);
894
927
  shared.totalCostRef.value += result.costMicroUsdc;
928
+ shared.totalTokensRef.value += result.usage.inputTokens + result.usage.outputTokens;
895
929
  shared.opts.hooks?.onStageComplete?.(stageId, ms, result.output);
896
930
  shared.emit(makeStageCompletedEvent({
897
931
  stageId,
@@ -900,6 +934,13 @@ async function runOneStage(stage, shared) {
900
934
  model: result.modelUsed,
901
935
  output: result.output,
902
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
+ }
903
944
  return { kind: 'completed', stageId, ms, costMicroUsdc: result.costMicroUsdc };
904
945
  }
905
946
  catch (e) {
@@ -1052,6 +1093,12 @@ export async function runPipelineV2(opts) {
1052
1093
  // already have snapshotted outputs (so the loop below skips them).
1053
1094
  const runId = opts.runId ?? (opts.checkpointStorage ? randomUUID() : undefined);
1054
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();
1055
1102
  const completedStageIds = new Set();
1056
1103
  let resumedFromCheckpoint = 0;
1057
1104
  if (runId && opts.checkpointStorage && opts.resume) {
@@ -1059,6 +1106,9 @@ export async function runPipelineV2(opts) {
1059
1106
  if (cp) {
1060
1107
  const restored = restoreFromCheckpoint(cp);
1061
1108
  startedAt = cp.started_at;
1109
+ const restoredMs = Date.parse(cp.started_at);
1110
+ if (Number.isFinite(restoredMs))
1111
+ startedAtMs = restoredMs;
1062
1112
  for (const id of Object.keys(restored.restored_outputs)) {
1063
1113
  outputs[id] = restored.restored_outputs[id];
1064
1114
  completedStageIds.add(id);
@@ -1087,6 +1137,8 @@ export async function runPipelineV2(opts) {
1087
1137
  stageProvenance,
1088
1138
  nestedCalls,
1089
1139
  totalCostRef: { value: totalCostMicroUsdc },
1140
+ totalTokensRef: { value: 0 },
1141
+ startedAtMs,
1090
1142
  emit,
1091
1143
  };
1092
1144
  async function snapshotCheckpoint() {
@@ -1136,6 +1188,10 @@ export async function runPipelineV2(opts) {
1136
1188
  }
1137
1189
  const settled = await Promise.allSettled(liveStages.map((s) => runOneStage(s, shared)));
1138
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;
1139
1195
  for (let i = 0; i < settled.length; i++) {
1140
1196
  const r = settled[i];
1141
1197
  const stage = liveStages[i];
@@ -1144,6 +1200,9 @@ export async function runPipelineV2(opts) {
1144
1200
  }
1145
1201
  else if (r.status === 'fulfilled' && r.value.kind === 'failed') {
1146
1202
  failedIds.push(r.value.stageId);
1203
+ if (r.value.error instanceof PipelineLimitExceededError && !limitError) {
1204
+ limitError = r.value.error;
1205
+ }
1147
1206
  }
1148
1207
  else if (r.status === 'rejected') {
1149
1208
  const reason = r.reason instanceof Error ? r.reason.message : String(r.reason);
@@ -1152,6 +1211,15 @@ export async function runPipelineV2(opts) {
1152
1211
  }
1153
1212
  if (failedIds.length > 0) {
1154
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
+ }
1155
1223
  const summary = `pipeline failed: ${failedIds.length}/${liveStages.length} parallel siblings failed (${failedIds.join(', ')})`;
1156
1224
  emit(makePipelineFailedEvent({
1157
1225
  pipelineName,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentsmarket/pipeline-runtime",
3
- "version": "0.6.0",
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",