@agentsmarket/pipeline-runtime 0.6.0 → 0.8.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.
@@ -60,12 +60,90 @@ export class PipelineFetchError extends Error {
60
60
  this.version = version;
61
61
  }
62
62
  }
63
- function prefixChildStages(stages, prefix) {
64
- return stages.map((s) => ({
65
- ...s,
66
- id: `${prefix}.${s.id}`,
67
- depends_on: s.depends_on?.map((d) => (d.includes('.') ? d : `${prefix}.${d}`)),
68
- }));
63
+ function prefixChildStages(stages, prefix, parentDependsOn = [], parentWhen) {
64
+ const childIds = new Set(stages.map((s) => s.id));
65
+ return stages.map((s) => {
66
+ // The child's own dependencies are the child's own stages: they are
67
+ // renamed with the prefix too. A dependency that already carries a dot
68
+ // names a stage of the child's own child ('x.g'), which is renamed the
69
+ // same way — prefixing it once is what makes it point at the stage that
70
+ // actually exists.
71
+ const own = (s.depends_on ?? []).map((d) => `${prefix}.${d}`);
72
+ // The stage the child replaces had dependencies of its own — the parent
73
+ // stage it read from. They are inherited by the child's stages, or the
74
+ // child would run before the stage whose output it reads.
75
+ const deps = [...parentDependsOn, ...own];
76
+ // The child's own gate is rewritten with the rest of the child's text —
77
+ // a gate on the child's own stage has to name the inlined stage.
78
+ const rewritten = rewriteChildRefs(s, prefix, childIds);
79
+ const when = combineWhen(parentWhen, rewritten.when);
80
+ return {
81
+ ...rewritten,
82
+ id: `${prefix}.${s.id}`,
83
+ depends_on: deps.length > 0 ? deps : undefined,
84
+ // The gate the parent put on the piece travels with it: a stage the
85
+ // parent skipped must not be run by the child either. When the child
86
+ // gates itself as well, both gates apply.
87
+ ...(when !== undefined ? { when } : {}),
88
+ };
89
+ });
90
+ }
91
+ /**
92
+ * The condition that applies to a stage: the parent's gate AND the child's.
93
+ *
94
+ * The parent's gate is a condition about the PARENT's stages (the piece runs
95
+ * only when the lead qualified), so it is inherited verbatim — its stage ids
96
+ * still exist in the composed pipeline.
97
+ */
98
+ function combineWhen(parentWhen, childWhen) {
99
+ const hasParent = parentWhen !== undefined && parentWhen !== null;
100
+ const hasChild = childWhen !== undefined && childWhen !== null;
101
+ if (!hasParent)
102
+ return childWhen;
103
+ if (!hasChild)
104
+ return parentWhen;
105
+ return { all: [parentWhen, childWhen] };
106
+ }
107
+ /**
108
+ * A reference to a stage's output inside a child's own text.
109
+ *
110
+ * `stages.<id>.outputs.<key>` — the id may carry dots, because a composed
111
+ * child's stage is named `<parentStage>.<childStage>`.
112
+ */
113
+ const CHILD_REF_PATTERN = /stages\.([A-Za-z_][A-Za-z0-9_.-]*?)\.outputs\.([A-Za-z_][A-Za-z0-9_-]*)/g;
114
+ /**
115
+ * Rewrite the child's references to its OWN stages when the child is inlined.
116
+ *
117
+ * A child that reads its own earlier stage (`when: "stages.extract.outputs.
118
+ * qualified == true"`, `{{stages.extract.outputs.name}}`) breaks when it is
119
+ * inlined: the reference still says `stages.extract`, while the inlined stage
120
+ * is `parent.extract`, and the reference resolves to nothing. So a
121
+ * multi-stage child could not be composed at all.
122
+ *
123
+ * Only the child's OWN stage ids are rewritten. A reference to a stage the
124
+ * child does not own — the parent's extraction stage, say — is left alone:
125
+ * that stage keeps its id in the composed pipeline, and the reference must
126
+ * keep pointing at it.
127
+ */
128
+ function rewriteChildRefs(value, prefix, childIds) {
129
+ if (typeof value === 'string') {
130
+ CHILD_REF_PATTERN.lastIndex = 0;
131
+ return value.replace(CHILD_REF_PATTERN, (match, stageId, outputKey) => {
132
+ if (!childIds.has(stageId))
133
+ return match;
134
+ return `stages.${prefix}.${stageId}.outputs.${outputKey}`;
135
+ });
136
+ }
137
+ if (Array.isArray(value))
138
+ return value.map((v) => rewriteChildRefs(v, prefix, childIds));
139
+ if (value && typeof value === 'object') {
140
+ const out = {};
141
+ for (const [k, v] of Object.entries(value)) {
142
+ out[k] = rewriteChildRefs(v, prefix, childIds);
143
+ }
144
+ return out;
145
+ }
146
+ return value;
69
147
  }
70
148
  /**
71
149
  * Expand a stage list by inlining any stage whose `uses:` references another
@@ -97,7 +175,7 @@ export async function expandComposition(stages, fetcher, depth = 0, options = {}
97
175
  if (!child)
98
176
  throw new PipelineFetchError(ref.id, ref.version);
99
177
  const childStages = await expandComposition(child.stages.map((s) => ({ ...s })), fetcher, depth + 1, { maxDepth });
100
- const renamed = prefixChildStages(childStages, stage.id);
178
+ const renamed = prefixChildStages(childStages, stage.id, stage.depends_on ?? [], stage.when);
101
179
  expanded.push(...renamed);
102
180
  continue;
103
181
  }
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,12 +41,15 @@ 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';
47
50
  export { resolveInputRefs, containsInputRef, inputRefName, resolveSpecialKeys, resolveDoubleBraceRefs, type PipelineRefContext, type DoubleBraceContext, } from './pipeline-refs.js';
48
- export { isToolSkill, invokeToolSkill, type ToolSkillContext, type ToolSkillResult, type ToolSkillHandler, } from './tools/tool-skills.js';
51
+ export { isToolSkill, invokeToolSkill, type ToolSkillContext, type ToolSkillResult, type ToolSkillHandler, type ToolSkillRegistry, } from './tools/tool-skills.js';
52
+ export { httpRequestHandler, hostAllowed, redact, resolveEnvRefs, validateHttpStageSecretUsage, HTTP_ALLOWED_HOSTS, HTTP_STAGE_ALLOWED_SECRETS, } from './tools/http-request.js';
49
53
  export { validateOutputSpec, DEFAULT_OUTPUT_FORMAT, DEFAULT_OUTPUT_DELIVERY, DEFAULT_OUTPUT_EXPIRES_IN, MIN_OUTPUT_EXPIRES_IN, MAX_OUTPUT_EXPIRES_IN, type PipelineOutputSpec, type PipelineOutputDelivery, type PipelineOutputFormat, type PipelineOutputSpecError, } from './output-spec.js';
50
54
  export { validateJsonSchema, MAX_VALIDATION_DEPTH, type JsonSchema, type JsonSchemaType, type OutputValidationViolation, type OutputValidationResult, } from './output-schema.js';
51
55
  export { validateAgainstSchema } from './output-schema-validate.js';
@@ -66,6 +70,8 @@ export interface PipelineSpec {
66
70
  name: string;
67
71
  version: string;
68
72
  stages: PipelineStageSpec[];
73
+ /** Per-pipeline resource ceilings (spec §7). */
74
+ limits?: PipelineLimits;
69
75
  }
70
76
  export interface PipelineContext {
71
77
  provider: import('./types.js').LLMProvider;
package/dist/index.js CHANGED
@@ -24,12 +24,15 @@ 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';
31
33
  export { resolveInputRefs, containsInputRef, inputRefName, resolveSpecialKeys, resolveDoubleBraceRefs, } from './pipeline-refs.js';
32
34
  export { isToolSkill, invokeToolSkill, } from './tools/tool-skills.js';
35
+ export { httpRequestHandler, hostAllowed, redact, resolveEnvRefs, validateHttpStageSecretUsage, HTTP_ALLOWED_HOSTS, HTTP_STAGE_ALLOWED_SECRETS, } from './tools/http-request.js';
33
36
  export { validateOutputSpec, DEFAULT_OUTPUT_FORMAT, DEFAULT_OUTPUT_DELIVERY, DEFAULT_OUTPUT_EXPIRES_IN, MIN_OUTPUT_EXPIRES_IN, MAX_OUTPUT_EXPIRES_IN, } from './output-spec.js';
34
37
  export { validateJsonSchema, MAX_VALIDATION_DEPTH, } from './output-schema.js';
35
38
  export { validateAgainstSchema } from './output-schema-validate.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
+ }
@@ -28,6 +28,7 @@
28
28
  * Strings get the regex substitution. Numbers, booleans, null return
29
29
  * unchanged.
30
30
  */
31
+ import { extractOutputField } from './stage-output-refs.js';
31
32
  /* ------------------------------------------------------------------------- *
32
33
  * `{{ }}` double-brace interpolation
33
34
  *
@@ -60,7 +61,10 @@
60
61
  const DOUBLE_BRACE_PATTERN = /\{\{\s*([^{}]+?)\s*\}\}/g;
61
62
  const DOUBLE_BRACE_WHOLE_PATTERN = /^\{\{\s*([^{}]+?)\s*\}\}$/;
62
63
  const PIPELINE_SCOPED_RE = /^inputs\.([A-Za-z_][A-Za-z0-9_]*)$/;
63
- const STAGE_OUTPUT_RE = /^stages\.([A-Za-z_][A-Za-z0-9_-]*)(?:\.outputs?)(?:\.([A-Za-z_][A-Za-z0-9_-]*))?$/;
64
+ // The stage id may carry dots: a composed child's stage is named
65
+ // `<parentStage>.<childStage>`. The id group is lazy so that
66
+ // `stages.a.outputs.b` reads as stage `a`, field `b`.
67
+ const STAGE_OUTPUT_RE = /^stages\.([A-Za-z_][A-Za-z0-9_.-]*?)(?:\.outputs?)(?:\.([A-Za-z_][A-Za-z0-9_-]*))?$/;
64
68
  const BARE_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
65
69
  function report(ctx, message) {
66
70
  if (ctx.onWarning)
@@ -84,9 +88,15 @@ function lookupDoubleBrace(expression, ctx) {
84
88
  const stageRef = STAGE_OUTPUT_RE.exec(expression);
85
89
  if (stageRef) {
86
90
  const stageId = stageRef[1];
91
+ const field = stageRef[2];
87
92
  const outputs = ctx.previousOutputs ?? {};
88
93
  if (Object.prototype.hasOwnProperty.call(outputs, stageId)) {
89
- return { found: true, value: outputs[stageId] ?? '' };
94
+ const whole = outputs[stageId] ?? '';
95
+ // `.Y` names a field of a structured output; without it the whole
96
+ // document is what the reference means.
97
+ if (field)
98
+ return { found: true, value: extractOutputField(whole, field) ?? whole };
99
+ return { found: true, value: whole };
90
100
  }
91
101
  report(ctx, `{{ ${expression} }} refers to stage '${stageId}', which has not produced output yet; left literal.`);
92
102
  return { found: false, value: undefined };
package/dist/pricing.js CHANGED
@@ -15,6 +15,10 @@ const MINIMAX_PRICING = {
15
15
  'MiniMax-M2.7': { input: 0.20, output: 0.80 },
16
16
  'MiniMax-M2.7-highspeed': { input: 0.10, output: 0.40 },
17
17
  'MiniMax-M3': { input: 2.00, output: 8.00 },
18
+ // The official price of the flash model (MiniMax pricing page, 22.11.2026):
19
+ // $0.15 / M input, $0.60 / M output. It is what MiniMax charges US, so a
20
+ // run priced at this table costs the platform exactly what it pays.
21
+ 'MiniMax-M3.1-Flash': { input: 0.15, output: 0.60 },
18
22
  };
19
23
  export class OpenRouterPricingResolver {
20
24
  opts;
@@ -71,6 +71,7 @@ export const PROVIDER_REGISTRY = {
71
71
  displayName: 'MiniMax',
72
72
  supportedModels: [
73
73
  'MiniMax-M3',
74
+ 'MiniMax-M3.1-Flash',
74
75
  'MiniMax-M2.7',
75
76
  'MiniMax-M2.7-highspeed',
76
77
  'MiniMax-M1',
@@ -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
+ }
@@ -77,3 +77,18 @@ export declare function tryParseStageOutputRef(template: string): ParsedStageOut
77
77
  * execution time.
78
78
  */
79
79
  export declare function resolveStageOutputRefs(text: string, outputs: Record<string, string>): string;
80
+ /**
81
+ * A named field of a stage output, when the output is a JSON object.
82
+ *
83
+ * A stage with `output_schema` stores the model's JSON text, so
84
+ * `stages.extract.outputs.qualified` has to mean "the `qualified` field of
85
+ * that JSON". Without this, every reference to a structured stage returned the
86
+ * whole document — which made `when: "stages.x.outputs.qualified == true"`
87
+ * compare a JSON blob against a literal and always fail, and made a CRM write
88
+ * impossible to fill with an extracted field.
89
+ *
90
+ * Returns undefined when the output is not a JSON object or has no such
91
+ * field. The caller then falls back to the whole output, which is what the
92
+ * runtime has always done — a missing field is never a silent empty string.
93
+ */
94
+ export declare function extractOutputField(outputText: string, field: string): string | undefined;
@@ -100,8 +100,48 @@ export function resolveStageOutputRefs(text, outputs) {
100
100
  STAGE_REF_PATTERN.lastIndex = 0;
101
101
  return text.replace(STAGE_REF_PATTERN, (_match, stageId, outputKey) => {
102
102
  if (Object.prototype.hasOwnProperty.call(outputs, stageId)) {
103
- return outputs[stageId] ?? '';
103
+ const whole = outputs[stageId] ?? '';
104
+ // `stages.X.outputs.Y` names a FIELD of a structured output, not the
105
+ // whole document: a stage that returned JSON has fields, and a caller
106
+ // that asks for one of them means that one.
107
+ return extractOutputField(whole, outputKey) ?? whole;
104
108
  }
105
109
  throw new UnresolvedStageOutputRefError(stageId, outputKey);
106
110
  });
107
111
  }
112
+ /**
113
+ * A named field of a stage output, when the output is a JSON object.
114
+ *
115
+ * A stage with `output_schema` stores the model's JSON text, so
116
+ * `stages.extract.outputs.qualified` has to mean "the `qualified` field of
117
+ * that JSON". Without this, every reference to a structured stage returned the
118
+ * whole document — which made `when: "stages.x.outputs.qualified == true"`
119
+ * compare a JSON blob against a literal and always fail, and made a CRM write
120
+ * impossible to fill with an extracted field.
121
+ *
122
+ * Returns undefined when the output is not a JSON object or has no such
123
+ * field. The caller then falls back to the whole output, which is what the
124
+ * runtime has always done — a missing field is never a silent empty string.
125
+ */
126
+ export function extractOutputField(outputText, field) {
127
+ const trimmed = outputText.trim();
128
+ if (!trimmed.startsWith('{'))
129
+ return undefined;
130
+ let parsed;
131
+ try {
132
+ parsed = JSON.parse(trimmed);
133
+ }
134
+ catch {
135
+ return undefined;
136
+ }
137
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
138
+ return undefined;
139
+ const value = parsed[field];
140
+ if (value === undefined || value === null)
141
+ return undefined;
142
+ if (typeof value === 'string')
143
+ return value;
144
+ if (typeof value === 'number' || typeof value === 'boolean')
145
+ return String(value);
146
+ return JSON.stringify(value);
147
+ }
package/dist/stages.d.ts CHANGED
@@ -16,6 +16,8 @@ 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';
20
+ import { type ToolSkillRegistry } from './tools/tool-skills.js';
19
21
  import { type PipelineEventSink } from './streaming-events.js';
20
22
  import { type RuntimeConstraints } from './runtime-constraints.js';
21
23
  import { type ShellExecutor, type ShellExecFile } from './shell-stage.js';
@@ -138,6 +140,17 @@ export interface StageExecutorDeps {
138
140
  * cannot read the platform's bindings by naming them.
139
141
  */
140
142
  grantedSecrets?: Record<string, string>;
143
+ /**
144
+ * Tool skills the host provides, by name.
145
+ *
146
+ * The runtime ships its own (web_fetch, http_request, image_describe…); a
147
+ * host that owns resources the runtime knows nothing about adds its own
148
+ * here. The server adds the connectors: they spend a BUYER's credential on
149
+ * the buyer's behalf, so they live where the credential is — in the
150
+ * platform's key store — and not in the runtime. A stage names one with
151
+ * `uses: tool:<name>`, exactly like a built-in.
152
+ */
153
+ toolSkills?: ToolSkillRegistry;
141
154
  /**
142
155
  * The author's bundle, by path — written into the working directory before
143
156
  * the command runs, so a stage can call the script that ships with the
@@ -163,8 +176,8 @@ export interface StageContext {
163
176
  previousOutputs: Record<string, string>;
164
177
  }
165
178
  export declare function makeWhenResolve(inputs: Record<string, unknown>, outputs: Record<string, string>): (template: string) => string;
166
- export declare function parseUsesEntry(raw: string): ResolvedUse;
167
- export declare function parseUsesList(stage: PipelineStageLike): ResolvedUse[];
179
+ export declare function parseUsesEntry(raw: string, extraTools?: ToolSkillRegistry): ResolvedUse;
180
+ export declare function parseUsesList(stage: PipelineStageLike, extraTools?: ToolSkillRegistry): ResolvedUse[];
168
181
  export declare function validateOutputFormat(text: string, outputFormat: OutputFormat | undefined, requiredFields: string[] | undefined): void;
169
182
  export declare class StageNotFoundError extends Error {
170
183
  constructor(message: string);
@@ -197,6 +210,12 @@ export interface RunPipelineOptions {
197
210
  * references — defaults to `MAX_COMPOSITION_DEPTH` (4) when unset.
198
211
  */
199
212
  composition?: CompositionConfig;
213
+ /**
214
+ * Per-pipeline resource ceilings (spec §7). When a stage pushes the
215
+ * cumulative usage past one of them the run is aborted and the error
216
+ * names the ceiling that fired.
217
+ */
218
+ limits?: PipelineLimits;
200
219
  };
201
220
  inputs: Record<string, unknown>;
202
221
  deps: StageExecutorDeps;
package/dist/stages.js CHANGED
@@ -16,9 +16,12 @@ 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';
22
+ import { extractOutputField } from './stage-output-refs.js';
21
23
  import { isToolSkill, invokeToolSkill } from './tools/tool-skills.js';
24
+ import { HTTP_STAGE_ALLOWED_SECRETS } from './tools/http-request.js';
22
25
  import { isRetryableStatus, computeBackoffMs, RetryExhaustedError, DEFAULT_RETRY, } from './retry.js';
23
26
  import { NoopEventSink, makeStartedEvent as makePipelineStartedEvent, makeCompletedEvent as makePipelineCompletedEvent, makeFailedEvent as makePipelineFailedEvent, makeStageStartedEvent, makeStageCompletedEvent, makeStageSkippedEvent, makeStageFailedEvent, makeStageRetriedEvent, makeStageWarnedEvent, } from './streaming-events.js';
24
27
  import { validateRuntimeConstraints, collectRuntimeWarnings, defaultRuntimeConstraints, } from './runtime-constraints.js';
@@ -31,6 +34,53 @@ import { expandComposition, } from './composition.js';
31
34
  import { groupIndependentStages, } from './parallel.js';
32
35
  import { randomUUID } from 'node:crypto';
33
36
  import { buildCheckpoint, restoreFromCheckpoint, } from './checkpoints.js';
37
+ /**
38
+ * The secrets THIS stage declared, resolved out of the run's grants.
39
+ *
40
+ * Only the names the stage listed in its own `secrets:` are visible, and only
41
+ * the values the host actually granted. The host's own environment is never a
42
+ * source — a stage cannot read the platform's bindings by naming them.
43
+ */
44
+ function collectStageEnv(stage, grantedSecrets) {
45
+ const declaredRaw = stage.secrets;
46
+ const declared = Array.isArray(declaredRaw)
47
+ ? declaredRaw.filter((n) => typeof n === 'string')
48
+ : [];
49
+ const env = {};
50
+ for (const name of declared) {
51
+ const v = grantedSecrets?.[name];
52
+ if (typeof v === 'string' && v.length > 0)
53
+ env[name] = v;
54
+ }
55
+ return env;
56
+ }
57
+ /**
58
+ * The env a TOOL stage may see.
59
+ *
60
+ * A credential must not reach a stage. The stage chooses the URL and the body
61
+ * of a request, so a credential in its hands can be stored by the buyer's own
62
+ * service and handed back — and the next stage, an LLM of the author's
63
+ * choosing, carries it out. The allowlist is not a credential: it says WHERE
64
+ * the stage may go, not what it may spend.
65
+ *
66
+ * The publish gate says the same (`validateHttpStageSecretUsage`), but this
67
+ * is the backstop for a spec published before the gate existed, and for a
68
+ * fork (a fork copies the source's spec verbatim): the stage fails instead
69
+ * of the value being handed over.
70
+ *
71
+ * The connectors are unaffected: they resolve the buyer's credential from
72
+ * the grant store themselves, which is the point of them.
73
+ */
74
+ function toolStageEnv(stage, grantedSecrets) {
75
+ const env = collectStageEnv(stage, grantedSecrets);
76
+ const bad = Object.keys(env).filter((n) => !HTTP_STAGE_ALLOWED_SECRETS.includes(n));
77
+ if (bad.length === 0)
78
+ return env;
79
+ const names = bad.map((n) => `'${n}'`).join(', ');
80
+ throw new Error(`stage '${stage.id}': the secret${bad.length > 1 ? 's' : ''} ${names} cannot be handed to a stage — ` +
81
+ 'a stage that holds a credential can put it into a request body and carry it away. Use a connector: ' +
82
+ 'the platform spends the buyer\'s credential itself, and the stage only sees the result.');
83
+ }
34
84
  function buildPreviousContext(outputs) {
35
85
  const entries = Object.entries(outputs);
36
86
  if (entries.length === 0)
@@ -155,7 +205,11 @@ function resolvePromptRefs(value, inputs, previousOutputs, onWarning) {
155
205
  return value;
156
206
  }
157
207
  export function makeWhenResolve(inputs, outputs) {
158
- const stageRefRe = /^stages\.([A-Za-z_][A-Za-z0-9_]*)(?:\.outputs?(?:\.[A-Za-z_][A-Za-z0-9_]*)?)?$/;
208
+ // The stage id may carry dots: a composed child's stage is named
209
+ // `<parentStage>.<childStage>`, and its `when:` must still resolve after
210
+ // the inlining. The id group is lazy so that `stages.a.outputs.b` reads as
211
+ // stage `a`, field `b` — not as stage `a.outputs.b`.
212
+ const stageRefRe = /^stages\.([A-Za-z_][A-Za-z0-9_.-]*?)(?:\.outputs?(?:\.([A-Za-z_][A-Za-z0-9_]*))?)?$/;
159
213
  const inputRefRe = /^inputs\.([A-Za-z_][A-Za-z0-9_]*)$/;
160
214
  return (template) => {
161
215
  const trimmed = template.trim();
@@ -163,7 +217,14 @@ export function makeWhenResolve(inputs, outputs) {
163
217
  if (stageMatch) {
164
218
  const stageId = stageMatch[1];
165
219
  if (Object.prototype.hasOwnProperty.call(outputs, stageId)) {
166
- return outputs[stageId] ?? '';
220
+ const whole = outputs[stageId] ?? '';
221
+ // `.outputs.Y` names a field of a structured output — without this a
222
+ // `when:` on a structured field compared the whole JSON document to a
223
+ // literal and never matched.
224
+ const field = stageMatch[2];
225
+ if (field)
226
+ return extractOutputField(whole, field) ?? whole;
227
+ return whole;
167
228
  }
168
229
  return '';
169
230
  }
@@ -178,7 +239,7 @@ export function makeWhenResolve(inputs, outputs) {
178
239
  return trimmed;
179
240
  };
180
241
  }
181
- export function parseUsesEntry(raw) {
242
+ export function parseUsesEntry(raw, extraTools) {
182
243
  const trimmed = raw.trim();
183
244
  if (!trimmed)
184
245
  return { id: '', version: null };
@@ -191,18 +252,18 @@ export function parseUsesEntry(raw) {
191
252
  // reach invokeToolSkill under the bare name. Only strip when what follows is
192
253
  // really a tool skill: an unknown `tool:` prefix should keep failing loudly
193
254
  // rather than being silently downgraded to a bare skill that also isn't there.
194
- const id = rawId.startsWith('tool:') && isToolSkill(rawId.slice(5)) ? rawId.slice(5) : rawId;
255
+ const id = rawId.startsWith('tool:') && isToolSkill(rawId.slice(5), extraTools) ? rawId.slice(5) : rawId;
195
256
  const version = at <= 0 || at === trimmed.length - 1 ? null : trimmed.slice(at + 1);
196
257
  return { id, version };
197
258
  }
198
- export function parseUsesList(stage) {
259
+ export function parseUsesList(stage, extraTools) {
199
260
  if (typeof stage.uses === 'string' && stage.uses.length > 0) {
200
- return [parseUsesEntry(stage.uses)];
261
+ return [parseUsesEntry(stage.uses, extraTools)];
201
262
  }
202
263
  if (Array.isArray(stage.uses)) {
203
264
  return stage.uses
204
265
  .filter((s) => typeof s === 'string' && s.length > 0)
205
- .map((s) => parseUsesEntry(s));
266
+ .map((s) => parseUsesEntry(s, extraTools));
206
267
  }
207
268
  return [];
208
269
  }
@@ -520,7 +581,7 @@ correctionHint) {
520
581
  const retryCtx = deps.eventSink
521
582
  ? { stageId: stage.id, eventSink: deps.eventSink }
522
583
  : undefined;
523
- const usesList = parseUsesList(stage);
584
+ const usesList = parseUsesList(stage, deps.toolSkills);
524
585
  const hasUses = usesList.length > 0;
525
586
  const hasModel = typeof stage.model === 'string' && stage.model.length > 0;
526
587
  const hasStringPrompt = typeof stage.prompt === 'string' && stage.prompt.length > 0;
@@ -551,16 +612,7 @@ correctionHint) {
551
612
  // The local executor merges it over the caller's own shell env, because
552
613
  // that is where a local run's variables come from (the CLI substitutes
553
614
  // ${VAR} from the same place).
554
- const stageEnv = {};
555
- const declaredRaw = stage.secrets;
556
- const declared = Array.isArray(declaredRaw)
557
- ? declaredRaw.filter((n) => typeof n === 'string')
558
- : [];
559
- for (const name of declared) {
560
- const v = deps.grantedSecrets?.[name];
561
- if (typeof v === 'string' && v.length > 0)
562
- stageEnv[name] = v;
563
- }
615
+ const stageEnv = collectStageEnv(stage, deps.grantedSecrets);
564
616
  try {
565
617
  const result = await deps.shellExecutor.exec(spec, {
566
618
  // The host's working directory when the author did not pick one: on
@@ -689,11 +741,15 @@ correctionHint) {
689
741
  pipelineInputs: ctx.inputs,
690
742
  previousOutputs: ctx.previousOutputs,
691
743
  }), { inputs: ctx.inputs, previousOutputs: ctx.previousOutputs });
692
- if (isToolSkill(use.id)) {
744
+ if (isToolSkill(use.id, deps.toolSkills)) {
693
745
  const toolT0 = Date.now();
694
746
  const toolResult = await invokeToolSkill(use.id, resolvedInput, {
695
747
  agentId: deps.getCurrentAgentId(),
696
- });
748
+ // A tool stage sees the allowlist — where it may go — and nothing
749
+ // else. A credential is spent by the platform (the connectors), never
750
+ // handed to a stage that chooses its own URL and body.
751
+ env: toolStageEnv(stage, deps.grantedSecrets),
752
+ }, deps.toolSkills);
697
753
  const toolDurationMs = Date.now() - toolT0;
698
754
  await deps.onLlmResponse?.(`${stage.id}:${use.id}`, toolResult.text, 'tool');
699
755
  lastResult = {
@@ -832,11 +888,43 @@ correctionHint) {
832
888
  ...(workingDir ? { working_dir: workingDir, working_dir_ignored_on_server: workingDirIgnoredOnServer } : {}),
833
889
  };
834
890
  }
891
+ /**
892
+ * The `limits:` ceilings of the spec §7, checked against the run so far.
893
+ *
894
+ * Returns the error to abort the run with, or null while the run is still
895
+ * inside its budget. The cost counter is micro-USDC (what the runtime prices
896
+ * in) while the ceiling is USDC (what the author writes).
897
+ */
898
+ function evaluateLimits(shared, stageId) {
899
+ const limits = shared.opts.spec.limits;
900
+ if (!limits)
901
+ return null;
902
+ const tokens = shared.totalTokensRef.value;
903
+ if (typeof limits.total_tokens === 'number' && tokens > limits.total_tokens) {
904
+ return new PipelineLimitExceededError('total_tokens', tokens, limits.total_tokens, stageId);
905
+ }
906
+ const costUsdc = shared.totalCostRef.value / 1_000_000;
907
+ if (typeof limits.total_cost_usdc === 'number' && costUsdc > limits.total_cost_usdc) {
908
+ return new PipelineLimitExceededError('total_cost_usdc', costUsdc, limits.total_cost_usdc, stageId);
909
+ }
910
+ const elapsedSeconds = (Date.now() - shared.startedAtMs) / 1000;
911
+ if (typeof limits.timeout_seconds === 'number' && elapsedSeconds > limits.timeout_seconds) {
912
+ return new PipelineLimitExceededError('timeout_seconds', elapsedSeconds, limits.timeout_seconds, stageId);
913
+ }
914
+ return null;
915
+ }
835
916
  async function runOneStage(stage, shared) {
836
917
  if (!stage.id) {
837
918
  return { kind: 'failed', stageId: '<no-id>', error: new StageBadConfigError('Stage missing required field: id') };
838
919
  }
839
920
  const stageId = stage.id;
921
+ // The run may already be out of budget before this stage starts — a
922
+ // resumed run, or a stage that took longer than the whole budget allows.
923
+ const overBudget = evaluateLimits(shared, stageId);
924
+ if (overBudget) {
925
+ shared.emit(makeStageFailedEvent({ stageId, error: overBudget.message }));
926
+ return { kind: 'failed', stageId, error: overBudget };
927
+ }
840
928
  shared.opts.hooks?.onStageStart?.(stageId);
841
929
  shared.emit(makeStageStartedEvent(stageId));
842
930
  if (stage.when && shouldSkipStage(stage.when, shared.whenResolve)) {
@@ -892,6 +980,7 @@ async function runOneStage(stage, shared) {
892
980
  };
893
981
  shared.nestedCalls.push(...result.nestedCalls);
894
982
  shared.totalCostRef.value += result.costMicroUsdc;
983
+ shared.totalTokensRef.value += result.usage.inputTokens + result.usage.outputTokens;
895
984
  shared.opts.hooks?.onStageComplete?.(stageId, ms, result.output);
896
985
  shared.emit(makeStageCompletedEvent({
897
986
  stageId,
@@ -900,6 +989,13 @@ async function runOneStage(stage, shared) {
900
989
  model: result.modelUsed,
901
990
  output: result.output,
902
991
  }));
992
+ // The spec's MUST (§7): a stage that pushes the run past a ceiling
993
+ // aborts the run, and the error names the ceiling that fired. The stage
994
+ // itself succeeded, so its output and its cost stay recorded.
995
+ const limitError = evaluateLimits(shared, stageId);
996
+ if (limitError) {
997
+ return { kind: 'failed', stageId, error: limitError };
998
+ }
903
999
  return { kind: 'completed', stageId, ms, costMicroUsdc: result.costMicroUsdc };
904
1000
  }
905
1001
  catch (e) {
@@ -1052,6 +1148,12 @@ export async function runPipelineV2(opts) {
1052
1148
  // already have snapshotted outputs (so the loop below skips them).
1053
1149
  const runId = opts.runId ?? (opts.checkpointStorage ? randomUUID() : undefined);
1054
1150
  let startedAt = new Date().toISOString();
1151
+ /**
1152
+ * The wall-clock start the `limits.timeout_seconds` budget is measured
1153
+ * against. A resumed run keeps the ORIGINAL start: the budget covers the
1154
+ * pipeline, not the attempt.
1155
+ */
1156
+ let startedAtMs = Date.now();
1055
1157
  const completedStageIds = new Set();
1056
1158
  let resumedFromCheckpoint = 0;
1057
1159
  if (runId && opts.checkpointStorage && opts.resume) {
@@ -1059,6 +1161,9 @@ export async function runPipelineV2(opts) {
1059
1161
  if (cp) {
1060
1162
  const restored = restoreFromCheckpoint(cp);
1061
1163
  startedAt = cp.started_at;
1164
+ const restoredMs = Date.parse(cp.started_at);
1165
+ if (Number.isFinite(restoredMs))
1166
+ startedAtMs = restoredMs;
1062
1167
  for (const id of Object.keys(restored.restored_outputs)) {
1063
1168
  outputs[id] = restored.restored_outputs[id];
1064
1169
  completedStageIds.add(id);
@@ -1087,6 +1192,8 @@ export async function runPipelineV2(opts) {
1087
1192
  stageProvenance,
1088
1193
  nestedCalls,
1089
1194
  totalCostRef: { value: totalCostMicroUsdc },
1195
+ totalTokensRef: { value: 0 },
1196
+ startedAtMs,
1090
1197
  emit,
1091
1198
  };
1092
1199
  async function snapshotCheckpoint() {
@@ -1136,6 +1243,10 @@ export async function runPipelineV2(opts) {
1136
1243
  }
1137
1244
  const settled = await Promise.allSettled(liveStages.map((s) => runOneStage(s, shared)));
1138
1245
  const failedIds = [];
1246
+ // A budget abort is not a sibling failure — it is the run's own limit
1247
+ // firing, and the caller must see WHICH limit. The generic summary
1248
+ // below would hide it behind "2/3 parallel siblings failed".
1249
+ let limitError = null;
1139
1250
  for (let i = 0; i < settled.length; i++) {
1140
1251
  const r = settled[i];
1141
1252
  const stage = liveStages[i];
@@ -1144,6 +1255,9 @@ export async function runPipelineV2(opts) {
1144
1255
  }
1145
1256
  else if (r.status === 'fulfilled' && r.value.kind === 'failed') {
1146
1257
  failedIds.push(r.value.stageId);
1258
+ if (r.value.error instanceof PipelineLimitExceededError && !limitError) {
1259
+ limitError = r.value.error;
1260
+ }
1147
1261
  }
1148
1262
  else if (r.status === 'rejected') {
1149
1263
  const reason = r.reason instanceof Error ? r.reason.message : String(r.reason);
@@ -1152,6 +1266,15 @@ export async function runPipelineV2(opts) {
1152
1266
  }
1153
1267
  if (failedIds.length > 0) {
1154
1268
  await snapshotCheckpoint();
1269
+ if (limitError) {
1270
+ emit(makePipelineFailedEvent({
1271
+ pipelineName,
1272
+ pipelineVersion,
1273
+ totalMs: Date.now() - pipelineT0,
1274
+ error: limitError.message,
1275
+ }));
1276
+ throw limitError;
1277
+ }
1155
1278
  const summary = `pipeline failed: ${failedIds.length}/${liveStages.length} parallel siblings failed (${failedIds.join(', ')})`;
1156
1279
  emit(makePipelineFailedEvent({
1157
1280
  pipelineName,
@@ -0,0 +1,71 @@
1
+ /**
2
+ * tool:http_request — an HTTP request made by a pipeline stage.
3
+ *
4
+ * Why it exists: the platform could not talk to a third-party API. `web_fetch`
5
+ * is GET-only, with no headers and no body; `shell:` is refused on the server;
6
+ * a skill's own executor never receives the buyer's secrets. Telegram's Bot API
7
+ * and Bitrix24's REST are both POST + auth, so without this tool a pipeline
8
+ * cannot write a lead into a CRM or answer a chat.
9
+ *
10
+ * Three rules make it safe to hand a buyer's token to a stranger's pipeline:
11
+ *
12
+ * 1. **The host must be in the buyer's own allowlist.** The list is the
13
+ * secret `HTTP_ALLOWED_HOSTS` — a value the buyer grants and the pipeline
14
+ * author cannot widen, because the author cannot write into the grant.
15
+ * No allowlist means no request: a stage that does not name the secret
16
+ * cannot reach the network at all.
17
+ * 2. **Only declared secrets are visible**, and only as `$env.NAME`
18
+ * placeholders the runtime substitutes at request time. The author writes
19
+ * the placeholder, never the value; an unknown name is an error, not an
20
+ * empty string.
21
+ * 3. **Nothing carrying a secret value comes back out** — not the URL, not
22
+ * the response body. A Telegram bot token sits in the URL path, so an
23
+ * echoed URL is a leaked token.
24
+ */
25
+ import type { ToolSkillContext, ToolSkillResult } from './tool-skills.js';
26
+ /** The secret that holds the buyer's allowlist of hosts this stage may reach. */
27
+ export declare const HTTP_ALLOWED_HOSTS = "HTTP_ALLOWED_HOSTS";
28
+ /**
29
+ * The secrets an HTTP stage may hold.
30
+ *
31
+ * `HTTP_ALLOWED_HOSTS` is a policy — which hosts the buyer's pipeline may
32
+ * reach — not a credential: it says where the stage may go, not what it may
33
+ * spend. Every other name is a credential, and a credential in an HTTP stage
34
+ * is a credential in the AUTHOR's hands: the stage chooses the URL and the
35
+ * body, so it can ask the buyer's own service to STORE the value (a lead
36
+ * comment) and hand it back (read the lead again) — and the next stage, an
37
+ * LLM of the author's choosing, carries it out. The allowlist does not stop
38
+ * that: every call stays on a host the buyer allowed.
39
+ *
40
+ * So an HTTP stage may hold the allowlist and nothing else. To spend a
41
+ * credential, use a connector: the platform performs the call with the buyer's
42
+ * own credential and the pipeline only ever sees the result.
43
+ */
44
+ export declare const HTTP_STAGE_ALLOWED_SECRETS: readonly string[];
45
+ /**
46
+ * The publish-time check: an HTTP stage may not hold a credential.
47
+ *
48
+ * Refused here, where the author can still see the spec — the same place the
49
+ * shell stage's argv is refused. A pipeline that published with a credential
50
+ * in an HTTP stage is a pipeline whose buyer is one request body away from
51
+ * handing the token to the author.
52
+ */
53
+ export declare function validateHttpStageSecretUsage(stage: unknown): string | null;
54
+ export declare function httpRequestHandler(input: unknown, ctx: ToolSkillContext): Promise<ToolSkillResult>;
55
+ /**
56
+ * Whether a host is covered by the allowlist.
57
+ *
58
+ * An entry matches the host itself and its subdomains — `example.com` covers
59
+ * `api.example.com` — so a buyer can allow one domain without listing every
60
+ * service inside it.
61
+ */
62
+ export declare function hostAllowed(host: string, allowRaw: string): boolean;
63
+ /**
64
+ * Substitute `$env.NAME` with the granted secret.
65
+ *
66
+ * An unknown name is an error: a stage that asks for a secret it was not
67
+ * granted must fail loudly, not send an empty token to the third party.
68
+ */
69
+ export declare function resolveEnvRefs(value: unknown, env: Record<string, string>): unknown;
70
+ /** Replace every granted secret value with a placeholder. */
71
+ export declare function redact(text: string, env: Record<string, string>): string;
@@ -0,0 +1,245 @@
1
+ /**
2
+ * tool:http_request — an HTTP request made by a pipeline stage.
3
+ *
4
+ * Why it exists: the platform could not talk to a third-party API. `web_fetch`
5
+ * is GET-only, with no headers and no body; `shell:` is refused on the server;
6
+ * a skill's own executor never receives the buyer's secrets. Telegram's Bot API
7
+ * and Bitrix24's REST are both POST + auth, so without this tool a pipeline
8
+ * cannot write a lead into a CRM or answer a chat.
9
+ *
10
+ * Three rules make it safe to hand a buyer's token to a stranger's pipeline:
11
+ *
12
+ * 1. **The host must be in the buyer's own allowlist.** The list is the
13
+ * secret `HTTP_ALLOWED_HOSTS` — a value the buyer grants and the pipeline
14
+ * author cannot widen, because the author cannot write into the grant.
15
+ * No allowlist means no request: a stage that does not name the secret
16
+ * cannot reach the network at all.
17
+ * 2. **Only declared secrets are visible**, and only as `$env.NAME`
18
+ * placeholders the runtime substitutes at request time. The author writes
19
+ * the placeholder, never the value; an unknown name is an error, not an
20
+ * empty string.
21
+ * 3. **Nothing carrying a secret value comes back out** — not the URL, not
22
+ * the response body. A Telegram bot token sits in the URL path, so an
23
+ * echoed URL is a leaked token.
24
+ */
25
+ /** The secret that holds the buyer's allowlist of hosts this stage may reach. */
26
+ export const HTTP_ALLOWED_HOSTS = 'HTTP_ALLOWED_HOSTS';
27
+ const METHODS = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD']);
28
+ const DEFAULT_TIMEOUT_MS = 15_000;
29
+ const MAX_TIMEOUT_MS = 60_000;
30
+ const MAX_RESPONSE_CHARS = 20_000;
31
+ const ENV_REF = /\$env\.([A-Za-z_][A-Za-z0-9_]*)/g;
32
+ const LOOPBACK = new Set(['127.0.0.1', 'localhost', '::1', '[::1]']);
33
+ /**
34
+ * The secrets an HTTP stage may hold.
35
+ *
36
+ * `HTTP_ALLOWED_HOSTS` is a policy — which hosts the buyer's pipeline may
37
+ * reach — not a credential: it says where the stage may go, not what it may
38
+ * spend. Every other name is a credential, and a credential in an HTTP stage
39
+ * is a credential in the AUTHOR's hands: the stage chooses the URL and the
40
+ * body, so it can ask the buyer's own service to STORE the value (a lead
41
+ * comment) and hand it back (read the lead again) — and the next stage, an
42
+ * LLM of the author's choosing, carries it out. The allowlist does not stop
43
+ * that: every call stays on a host the buyer allowed.
44
+ *
45
+ * So an HTTP stage may hold the allowlist and nothing else. To spend a
46
+ * credential, use a connector: the platform performs the call with the buyer's
47
+ * own credential and the pipeline only ever sees the result.
48
+ */
49
+ export const HTTP_STAGE_ALLOWED_SECRETS = [HTTP_ALLOWED_HOSTS];
50
+ /**
51
+ * The publish-time check: an HTTP stage may not hold a credential.
52
+ *
53
+ * Refused here, where the author can still see the spec — the same place the
54
+ * shell stage's argv is refused. A pipeline that published with a credential
55
+ * in an HTTP stage is a pipeline whose buyer is one request body away from
56
+ * handing the token to the author.
57
+ */
58
+ export function validateHttpStageSecretUsage(stage) {
59
+ if (!stage || typeof stage !== 'object')
60
+ return null;
61
+ const s = stage;
62
+ const uses = Array.isArray(s.uses) ? s.uses : [s.uses];
63
+ const isHttp = uses.some((u) => typeof u === 'string' && u.trim().replace(/^tool:/, '') === 'http_request');
64
+ if (!isHttp)
65
+ return null;
66
+ const declared = Array.isArray(s.secrets)
67
+ ? s.secrets.filter((n) => typeof n === 'string')
68
+ : [];
69
+ const bad = declared.filter((n) => !HTTP_STAGE_ALLOWED_SECRETS.includes(n));
70
+ if (bad.length === 0)
71
+ return null;
72
+ const label = typeof s.id === 'string' && s.id.length > 0 ? `Stage '${s.id}'` : 'Stage';
73
+ const names = bad.map((n) => `'${n}'`).join(', ');
74
+ return (`${label}: the secret${bad.length > 1 ? 's' : ''} ${names} cannot be used with tool:http_request — ` +
75
+ 'a credential in an HTTP stage reaches the author: the stage chooses the URL and the body, so it can ' +
76
+ 'have the buyer\'s own service store the value and hand it back, and the next stage (an LLM of the ' +
77
+ 'author\'s choosing) carries it out. The allowlist does not stop that — every call stays on a host the ' +
78
+ 'buyer allowed. Use a connector instead: the platform spends the buyer\'s credential itself, and the ' +
79
+ 'stage only sees the result.');
80
+ }
81
+ export async function httpRequestHandler(input, ctx) {
82
+ const env = ctx.env ?? {};
83
+ const req = parseInput(input);
84
+ const allowRaw = env[HTTP_ALLOWED_HOSTS];
85
+ if (!allowRaw || !allowRaw.trim()) {
86
+ throw new Error(`tool:http_request requires the ${HTTP_ALLOWED_HOSTS} secret — a stage without it cannot reach the network`);
87
+ }
88
+ const url = resolveEnvRefs(req.url, env);
89
+ let parsed;
90
+ try {
91
+ parsed = new URL(url);
92
+ }
93
+ catch {
94
+ throw new Error(`tool:http_request: '${redact(url, env)}' is not a valid URL`);
95
+ }
96
+ if (parsed.protocol !== 'https:' && !(parsed.protocol === 'http:' && LOOPBACK.has(parsed.hostname))) {
97
+ throw new Error(`tool:http_request requires https (http is allowed for loopback hosts only): ${redact(url, env)}`);
98
+ }
99
+ if (!hostAllowed(parsed.hostname, allowRaw)) {
100
+ throw new Error(`tool:http_request: host '${parsed.hostname}' is not in the ${HTTP_ALLOWED_HOSTS} allowlist`);
101
+ }
102
+ const headers = {};
103
+ for (const [k, v] of Object.entries(req.headers)) {
104
+ headers[k] = resolveEnvRefs(v, env);
105
+ }
106
+ const init = { method: req.method, headers };
107
+ if (req.body !== undefined && req.body !== null) {
108
+ init.body = typeof req.body === 'string' ? req.body : JSON.stringify(req.body);
109
+ if (!Object.keys(headers).some((h) => h.toLowerCase() === 'content-type')) {
110
+ headers['content-type'] = 'application/json';
111
+ }
112
+ }
113
+ const controller = new AbortController();
114
+ const timer = setTimeout(() => controller.abort(), req.timeout_ms);
115
+ const onAbort = () => controller.abort();
116
+ ctx.signal?.addEventListener('abort', onAbort);
117
+ let response;
118
+ try {
119
+ response = await fetch(parsed.toString(), { ...init, signal: controller.signal });
120
+ }
121
+ catch (e) {
122
+ const reason = e instanceof Error ? e.message : String(e);
123
+ throw new Error(`tool:http_request failed: ${reason}`);
124
+ }
125
+ finally {
126
+ clearTimeout(timer);
127
+ ctx.signal?.removeEventListener('abort', onAbort);
128
+ }
129
+ const raw = await response.text();
130
+ const truncated = raw.length > MAX_RESPONSE_CHARS;
131
+ const body = redact(truncated ? raw.slice(0, MAX_RESPONSE_CHARS) : raw, env);
132
+ return {
133
+ text: JSON.stringify({
134
+ ok: response.ok,
135
+ status: response.status,
136
+ body,
137
+ truncated,
138
+ }),
139
+ usage: { inputTokens: 0, outputTokens: 0 },
140
+ meta: {
141
+ tool: 'http_request',
142
+ method: req.method,
143
+ url: redact(parsed.toString(), env),
144
+ status: response.status,
145
+ ok: response.ok,
146
+ truncated,
147
+ },
148
+ };
149
+ }
150
+ /**
151
+ * Whether a host is covered by the allowlist.
152
+ *
153
+ * An entry matches the host itself and its subdomains — `example.com` covers
154
+ * `api.example.com` — so a buyer can allow one domain without listing every
155
+ * service inside it.
156
+ */
157
+ export function hostAllowed(host, allowRaw) {
158
+ const hostLc = host.toLowerCase();
159
+ for (const raw of allowRaw.split(/[,\s]+/)) {
160
+ const entry = raw.trim().toLowerCase();
161
+ if (!entry)
162
+ continue;
163
+ if (entry === hostLc)
164
+ return true;
165
+ if (entry.startsWith('.')) {
166
+ if (hostLc.endsWith(entry) || hostLc === entry.slice(1))
167
+ return true;
168
+ }
169
+ else if (hostLc.endsWith(`.${entry}`)) {
170
+ return true;
171
+ }
172
+ }
173
+ return false;
174
+ }
175
+ /**
176
+ * Substitute `$env.NAME` with the granted secret.
177
+ *
178
+ * An unknown name is an error: a stage that asks for a secret it was not
179
+ * granted must fail loudly, not send an empty token to the third party.
180
+ */
181
+ export function resolveEnvRefs(value, env) {
182
+ if (typeof value === 'string') {
183
+ return value.replace(ENV_REF, (match, name) => {
184
+ const v = env[name];
185
+ if (v === undefined) {
186
+ throw new Error(`tool:http_request: secret '${name}' was not granted to this stage`);
187
+ }
188
+ return v;
189
+ });
190
+ }
191
+ if (Array.isArray(value))
192
+ return value.map((v) => resolveEnvRefs(v, env));
193
+ if (value && typeof value === 'object') {
194
+ const out = {};
195
+ for (const [k, v] of Object.entries(value)) {
196
+ out[k] = resolveEnvRefs(v, env);
197
+ }
198
+ return out;
199
+ }
200
+ return value;
201
+ }
202
+ /** Replace every granted secret value with a placeholder. */
203
+ export function redact(text, env) {
204
+ let out = text;
205
+ for (const [name, value] of Object.entries(env)) {
206
+ if (name === HTTP_ALLOWED_HOSTS)
207
+ continue;
208
+ if (typeof value !== 'string' || value.length < 8)
209
+ continue;
210
+ out = out.split(value).join(`$${name}`);
211
+ }
212
+ return out;
213
+ }
214
+ function parseInput(input) {
215
+ if (!input || typeof input !== 'object' || Array.isArray(input)) {
216
+ throw new Error('tool:http_request requires an input object');
217
+ }
218
+ const obj = input;
219
+ const url = obj.url;
220
+ if (typeof url !== 'string' || url.length === 0) {
221
+ throw new Error("tool:http_request requires `url: string`");
222
+ }
223
+ const methodRaw = typeof obj.method === 'string' ? obj.method.toUpperCase() : 'GET';
224
+ if (!METHODS.has(methodRaw)) {
225
+ throw new Error(`tool:http_request: unsupported method '${methodRaw}'`);
226
+ }
227
+ const headers = {};
228
+ const headersRaw = obj.headers;
229
+ if (headersRaw !== undefined && headersRaw !== null) {
230
+ if (typeof headersRaw !== 'object' || Array.isArray(headersRaw)) {
231
+ throw new Error("tool:http_request requires `headers` to be an object");
232
+ }
233
+ for (const [k, v] of Object.entries(headersRaw)) {
234
+ if (typeof v !== 'string') {
235
+ throw new Error(`tool:http_request: header '${k}' must be a string`);
236
+ }
237
+ headers[k] = v;
238
+ }
239
+ }
240
+ const timeoutRaw = obj.timeout_ms;
241
+ const timeout = typeof timeoutRaw === 'number' && timeoutRaw > 0
242
+ ? Math.min(timeoutRaw, MAX_TIMEOUT_MS)
243
+ : DEFAULT_TIMEOUT_MS;
244
+ return { method: methodRaw, url, headers, body: obj.body, timeout_ms: timeout };
245
+ }
@@ -20,6 +20,15 @@ export interface ToolSkillContext {
20
20
  agentId: string;
21
21
  /** Abort signal — for cancellation on pipeline timeout. */
22
22
  signal?: AbortSignal;
23
+ /**
24
+ * The secrets THIS stage declared, by name.
25
+ *
26
+ * A stage sees only what it listed in its own `secrets:` — the same rule the
27
+ * shell stage follows. `tool:http_request` reads its allowlist and its
28
+ * tokens from here, so a pipeline author never sees a value, only the
29
+ * `$env.NAME` placeholder the runtime substitutes.
30
+ */
31
+ env?: Record<string, string>;
23
32
  }
24
33
  export interface ToolSkillResult {
25
34
  /** String output that becomes the stage's final output (same shape as LLM skill returns). */
@@ -33,5 +42,16 @@ export interface ToolSkillResult {
33
42
  meta?: Record<string, unknown>;
34
43
  }
35
44
  export type ToolSkillHandler = (input: unknown, ctx: ToolSkillContext) => Promise<ToolSkillResult>;
36
- export declare function isToolSkill(skillId: string): boolean;
37
- export declare function invokeToolSkill(skillId: string, input: unknown, ctx: ToolSkillContext): Promise<ToolSkillResult>;
45
+ /**
46
+ * Extra tool skills, provided by the host.
47
+ *
48
+ * The built-in handlers above are the runtime's own. A host that owns
49
+ * resources the runtime knows nothing about can add handlers of its own — the
50
+ * server adds the connectors, which spend a BUYER's credential (a Telegram
51
+ * bot token, a CRM code) on the buyer's behalf. Those must not live in the
52
+ * runtime: the runtime has no database and no key store, and the whole point
53
+ * of a connector is that the credential never reaches the pipeline.
54
+ */
55
+ export type ToolSkillRegistry = Record<string, ToolSkillHandler>;
56
+ export declare function isToolSkill(skillId: string, extra?: ToolSkillRegistry): boolean;
57
+ export declare function invokeToolSkill(skillId: string, input: unknown, ctx: ToolSkillContext, extra?: ToolSkillRegistry): Promise<ToolSkillResult>;
@@ -22,8 +22,10 @@ import { imageGenerateHandler } from './image-generate.js';
22
22
  import { videoGenerateHandler } from './video-generate.js';
23
23
  import { memoryRecallHandler } from './memory-recall.js';
24
24
  import { memoryStoreHandler } from './memory-store.js';
25
+ import { httpRequestHandler } from './http-request.js';
25
26
  const TOOL_SKILLS = {
26
27
  web_fetch: webFetchHandler,
28
+ http_request: httpRequestHandler,
27
29
  image_describe: imageDescribeHandler,
28
30
  audio_transcribe: audioTranscribeHandler,
29
31
  tts_synthesize: ttsSynthesizeHandler,
@@ -32,11 +34,11 @@ const TOOL_SKILLS = {
32
34
  memory_recall: memoryRecallHandler,
33
35
  memory_store: memoryStoreHandler,
34
36
  };
35
- export function isToolSkill(skillId) {
36
- return skillId in TOOL_SKILLS;
37
+ export function isToolSkill(skillId, extra) {
38
+ return skillId in TOOL_SKILLS || (extra ? skillId in extra : false);
37
39
  }
38
- export async function invokeToolSkill(skillId, input, ctx) {
39
- const handler = TOOL_SKILLS[skillId];
40
+ export async function invokeToolSkill(skillId, input, ctx, extra) {
41
+ const handler = (extra && extra[skillId]) || TOOL_SKILLS[skillId];
40
42
  if (!handler) {
41
43
  throw new Error(`Tool skill '${skillId}' is registered but has no handler`);
42
44
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentsmarket/pipeline-runtime",
3
- "version": "0.6.0",
3
+ "version": "0.8.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",
@@ -9,6 +9,14 @@
9
9
  "dist",
10
10
  "README.md"
11
11
  ],
12
+ "scripts": {
13
+ "build": "tsc",
14
+ "test": "vitest run",
15
+ "test:coverage": "vitest run --coverage",
16
+ "dev": "tsx src/index.ts",
17
+ "lint": "tsc --noEmit",
18
+ "typecheck": "tsc --noEmit -p tsconfig.json"
19
+ },
12
20
  "dependencies": {
13
21
  "@anthropic-ai/sdk": "^0.137.0",
14
22
  "@hono/node-server": "^2.1.5",
@@ -34,13 +42,5 @@
34
42
  "publishConfig": {
35
43
  "access": "public"
36
44
  },
37
- "types": "./dist/index.d.ts",
38
- "scripts": {
39
- "build": "tsc",
40
- "test": "vitest run",
41
- "test:coverage": "vitest run --coverage",
42
- "dev": "tsx src/index.ts",
43
- "lint": "tsc --noEmit",
44
- "typecheck": "tsc --noEmit -p tsconfig.json"
45
- }
46
- }
45
+ "types": "./dist/index.d.ts"
46
+ }
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 agentsmarket.world contributors
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.