@agentsmarket/pipeline-runtime 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +94 -0
  2. package/bin/webhook.mjs +11 -0
  3. package/dist/adapters/minimax.d.ts +31 -0
  4. package/dist/adapters/minimax.js +69 -0
  5. package/dist/adapters/openrouter.d.ts +29 -0
  6. package/dist/adapters/openrouter.js +71 -0
  7. package/dist/checkpoints.d.ts +142 -0
  8. package/dist/checkpoints.js +192 -0
  9. package/dist/composition.d.ts +90 -0
  10. package/dist/composition.js +108 -0
  11. package/dist/content-hash.d.ts +7 -0
  12. package/dist/content-hash.js +17 -0
  13. package/dist/fallback.d.ts +31 -0
  14. package/dist/fallback.js +76 -0
  15. package/dist/index.d.ts +64 -0
  16. package/dist/index.js +61 -0
  17. package/dist/model-resolver.d.ts +136 -0
  18. package/dist/model-resolver.js +36 -0
  19. package/dist/parallel.d.ts +26 -0
  20. package/dist/parallel.js +83 -0
  21. package/dist/pricing.d.ts +57 -0
  22. package/dist/pricing.js +135 -0
  23. package/dist/provider-registry.d.ts +190 -0
  24. package/dist/provider-registry.js +333 -0
  25. package/dist/resolve-vars.d.ts +91 -0
  26. package/dist/resolve-vars.js +203 -0
  27. package/dist/retry.d.ts +40 -0
  28. package/dist/retry.js +61 -0
  29. package/dist/runtime-constraints.d.ts +39 -0
  30. package/dist/runtime-constraints.js +60 -0
  31. package/dist/stage-output-refs.d.ts +79 -0
  32. package/dist/stage-output-refs.js +107 -0
  33. package/dist/stages.d.ts +247 -0
  34. package/dist/stages.js +633 -0
  35. package/dist/streaming-events.d.ts +118 -0
  36. package/dist/streaming-events.js +132 -0
  37. package/dist/types.d.ts +138 -0
  38. package/dist/types.js +54 -0
  39. package/dist/webhook.d.ts +30 -0
  40. package/dist/webhook.js +160 -0
  41. package/dist/when.d.ts +55 -0
  42. package/dist/when.js +165 -0
  43. package/package.json +42 -0
@@ -0,0 +1,333 @@
1
+ /**
2
+ * Provider registry — static metadata + runtime class.
3
+ *
4
+ * R6 (Pipeline v0.3) — Provider ≠ Model separation.
5
+ *
6
+ * Every pipeline stage MUST declare both `provider:` and `model:`.
7
+ * Auto-dispatch by model name (v0.2 `pickProvider`) was removed in
8
+ * R6. The `PROVIDER_REGISTRY` constant below is the single source
9
+ * of truth for *which models each provider supports*.
10
+ *
11
+ * Two-layer design:
12
+ *
13
+ * 1. Static `PROVIDER_REGISTRY` (this file) — pure data: name,
14
+ * display name, supportedModels allowlist, baseUrl, env var.
15
+ * Use for: schema validation, CLI help text, `validate()`
16
+ * command. Pure module, no I/O.
17
+ *
18
+ * 2. Runtime `LLMProviderRegistry` class (this file) — wraps the
19
+ * set of *instantiated* `LLMProvider` objects available to the
20
+ * executor (depends on env keys present). Use for: actual
21
+ * request execution. Constructed once per pipeline-run.
22
+ *
23
+ * The static registry declares 5 providers (openai, anthropic,
24
+ * minimax, openrouter, replicate). The runtime class currently
25
+ * instantiates only those with env keys configured (minimax +
26
+ * openrouter). openai/anthropic/replicate land when their SDK
27
+ * adapters ship (post-R6).
28
+ *
29
+ * TODO production: replace the static allowlists with dynamic
30
+ * /models fetches against each provider's API; cache with TTL.
31
+ */
32
+ export const PROVIDER_REGISTRY = {
33
+ openai: {
34
+ name: 'openai',
35
+ displayName: 'OpenAI',
36
+ supportedModels: [
37
+ 'gpt-4o',
38
+ 'gpt-4o-mini',
39
+ 'o1-preview',
40
+ 'o1-mini',
41
+ 'gpt-3.5-turbo',
42
+ ],
43
+ baseUrl: 'https://api.openai.com/v1',
44
+ apiKeyEnvVar: 'OPENAI_API_KEY',
45
+ },
46
+ anthropic: {
47
+ name: 'anthropic',
48
+ displayName: 'Anthropic',
49
+ supportedModels: [
50
+ 'claude-3-5-sonnet-20241022',
51
+ 'claude-3-5-haiku-20241022',
52
+ 'claude-3-opus-20240229',
53
+ ],
54
+ baseUrl: 'https://api.anthropic.com/v1',
55
+ apiKeyEnvVar: 'ANTHROPIC_API_KEY',
56
+ },
57
+ minimax: {
58
+ name: 'minimax',
59
+ displayName: 'MiniMax',
60
+ supportedModels: [
61
+ 'MiniMax-M3',
62
+ 'MiniMax-M2.7',
63
+ 'MiniMax-M1',
64
+ ],
65
+ baseUrl: 'https://api.minimax.io/anthropic/v1',
66
+ apiKeyEnvVar: 'MINIMAX_API_KEY',
67
+ },
68
+ openrouter: {
69
+ name: 'openrouter',
70
+ displayName: 'OpenRouter',
71
+ // OpenRouter is a multi-model gateway — it routes anything.
72
+ supportedModels: ['*'],
73
+ baseUrl: 'https://openrouter.ai/api/v1',
74
+ apiKeyEnvVar: 'OPENROUTER_API_KEY',
75
+ },
76
+ replicate: {
77
+ name: 'replicate',
78
+ displayName: 'Replicate',
79
+ supportedModels: [
80
+ 'black-forest-labs/flux-pro',
81
+ 'black-forest-labs/flux-schnell',
82
+ 'stability-ai/sdxl',
83
+ ],
84
+ baseUrl: 'https://api.replicate.com/v1',
85
+ apiKeyEnvVar: 'REPLICATE_API_TOKEN',
86
+ },
87
+ };
88
+ /**
89
+ * Look up a provider by name. Returns null for unknown names —
90
+ * use {@link validateProviderName} when an exception is desired.
91
+ */
92
+ export function getProvider(name) {
93
+ if (typeof name !== 'string' || name.length === 0)
94
+ return null;
95
+ const spec = PROVIDER_REGISTRY[name];
96
+ return spec ?? null;
97
+ }
98
+ /**
99
+ * Like {@link getProvider} but throws `ProviderSpecNotFoundError`
100
+ * on unknown names. Use at trust boundaries (CLI validate, server
101
+ * publish) where a misspelled provider must fail-fast with a clear
102
+ * message instead of silently returning null.
103
+ */
104
+ export function validateProviderName(name) {
105
+ const spec = getProvider(name);
106
+ if (spec === null) {
107
+ throw new ProviderSpecNotFoundError(name, listProviders().map((p) => p.name));
108
+ }
109
+ return spec.name;
110
+ }
111
+ /**
112
+ * Does the provider support this model?
113
+ *
114
+ * - exact match against `supportedModels` → true
115
+ * - provider has `'*'` in supportedModels → true (openrouter)
116
+ * - otherwise → false
117
+ *
118
+ * Pure function; safe to call from validators and tests.
119
+ */
120
+ export function supportsModel(providerName, modelName) {
121
+ const spec = PROVIDER_REGISTRY[providerName];
122
+ if (!spec)
123
+ return false;
124
+ if (spec.supportedModels.includes('*'))
125
+ return true;
126
+ return spec.supportedModels.includes(modelName);
127
+ }
128
+ /**
129
+ * Combined check: validate provider name AND model membership.
130
+ * Returns the normalized `{ provider, model }` tuple.
131
+ *
132
+ * Throws `ProviderSpecNotFoundError` (unknown provider) or
133
+ * `ProviderModelMismatchError` (provider exists but model is not
134
+ * in its allowlist) with messages that include the full supported
135
+ * model list for fast debugging.
136
+ */
137
+ export function validateProviderModel(providerName, modelName) {
138
+ const provider = validateProviderName(providerName);
139
+ if (!supportsModel(provider, modelName)) {
140
+ const available = PROVIDER_REGISTRY[provider].supportedModels;
141
+ throw new ProviderModelMismatchError(provider, modelName, available);
142
+ }
143
+ return { provider, model: modelName };
144
+ }
145
+ /** All provider specs, in registry-insertion order. */
146
+ export function listProviders() {
147
+ return Object.values(PROVIDER_REGISTRY);
148
+ }
149
+ /**
150
+ * Models the provider supports (or `['*']` for gateways).
151
+ * Returns the same readonly tuple as `spec.supportedModels` —
152
+ * consumers should treat it as read-only.
153
+ */
154
+ export function listSupportedModels(providerName) {
155
+ const spec = PROVIDER_REGISTRY[providerName];
156
+ if (!spec) {
157
+ throw new ProviderSpecNotFoundError(providerName, listProviders().map((p) => p.name));
158
+ }
159
+ return spec.supportedModels;
160
+ }
161
+ /**
162
+ * Pure validator for the R6 (Provider ≠ Model) schema rules. Used
163
+ * by both CLI (`agentsmarket validate`, `agentsmarket run` preflight)
164
+ * and server (`POST /v1/pipelines` publish gate). No env access,
165
+ * no I/O — safe to call from tests and CLI completion.
166
+ *
167
+ * Rules enforced:
168
+ * 1. Every LLM stage (model OR prompt-only) MUST declare `provider:`.
169
+ * Auto-dispatch by model name was removed in R6.
170
+ * 2. The (provider, model) pair MUST be in `PROVIDER_REGISTRY`.
171
+ * `provider.supports(model)` is the source of truth.
172
+ * 3. The stage's effective model = `stage.model ?? spec.defaults?.model ?? 'MiniMax-M3'`.
173
+ * Stages using `uses:` (skill invocation) skip the gate entirely.
174
+ */
175
+ export function validateR6Spec(spec) {
176
+ const errors = [];
177
+ const stages = spec.stages ?? [];
178
+ for (const stage of stages) {
179
+ const isUsesStage = stage.uses !== undefined && stage.uses !== null;
180
+ const hasModel = typeof stage.model === 'string' && stage.model.length > 0;
181
+ const hasPrompt = typeof stage.prompt === 'string' && stage.prompt.length > 0;
182
+ const isLlmStage = hasModel || (hasPrompt && !isUsesStage);
183
+ if (!isLlmStage)
184
+ continue;
185
+ const stageLabel = `Stage '${stage.id ?? '<no-id>'}'`;
186
+ if (typeof stage.provider !== 'string' || stage.provider.length === 0) {
187
+ errors.push(`${stageLabel}: R6 requires explicit 'provider:' field ` +
188
+ `(auto-dispatch by model name removed). Add 'provider: minimax' ` +
189
+ `(or openrouter/openai/anthropic/replicate).`);
190
+ continue;
191
+ }
192
+ const effectiveModel = hasModel
193
+ ? stage.model
194
+ : (spec.defaults?.model ?? 'MiniMax-M3');
195
+ try {
196
+ validateProviderModel(stage.provider, effectiveModel);
197
+ }
198
+ catch (e) {
199
+ const msg = e instanceof Error ? e.message : String(e);
200
+ errors.push(`${stageLabel}: ${msg}`);
201
+ }
202
+ }
203
+ return { errors };
204
+ }
205
+ /**
206
+ * One-shot migration: adds `provider: minimax` to every LLM stage
207
+ * that lacks a provider field. Legacy v0.2 pipelines relied on
208
+ * auto-dispatch; R6 requires explicit declaration. Idempotent —
209
+ * re-running on an already-migrated spec is a no-op.
210
+ *
211
+ * Returns a NEW spec object (input not mutated). Stages that already
212
+ * declare any provider (openai, anthropic, openrouter, replicate, …)
213
+ * are passed through unchanged.
214
+ */
215
+ export function migrateProviderField(spec, defaultProvider = 'minimax') {
216
+ const stages = spec.stages ?? [];
217
+ const newStages = stages.map((stage) => {
218
+ const hasProvider = typeof stage['provider'] === 'string' && stage['provider'].length > 0;
219
+ if (hasProvider)
220
+ return stage;
221
+ const uses = stage['uses'];
222
+ const hasUses = uses !== undefined && uses !== null;
223
+ const hasModel = typeof stage['model'] === 'string' && stage['model'].length > 0;
224
+ const hasPrompt = typeof stage['prompt'] === 'string' && stage['prompt'].length > 0;
225
+ const isLlmStage = hasModel || (hasPrompt && !hasUses);
226
+ if (!isLlmStage)
227
+ return stage;
228
+ return { ...stage, provider: defaultProvider };
229
+ });
230
+ return { ...spec, stages: newStages };
231
+ }
232
+ // ─────────────────────────────────────────────────────────────────────────────
233
+ // Errors (static layer)
234
+ // ─────────────────────────────────────────────────────────────────────────────
235
+ /** Thrown when a string doesn't match any registered provider. */
236
+ export class ProviderSpecNotFoundError extends Error {
237
+ providerName;
238
+ availableProviders;
239
+ constructor(providerName, availableProviders) {
240
+ const avail = availableProviders.length > 0
241
+ ? availableProviders.join(', ')
242
+ : '(none registered)';
243
+ super(`Provider '${providerName}' is not registered. ` +
244
+ `Available providers: ${avail}`);
245
+ this.name = 'PROVIDER_SPEC_NOT_FOUND';
246
+ this.providerName = providerName;
247
+ this.availableProviders = availableProviders;
248
+ }
249
+ }
250
+ /** Thrown when a (provider, model) pair is invalid for the provider. */
251
+ export class ProviderModelMismatchError extends Error {
252
+ providerName;
253
+ model;
254
+ availableModels;
255
+ constructor(providerName, model, availableModels) {
256
+ const avail = availableModels.length > 0
257
+ ? availableModels.join(', ')
258
+ : '(none registered)';
259
+ super(`Provider '${providerName}' does not support model '${model}'. ` +
260
+ `Supported models for ${providerName}: ${avail}`);
261
+ this.name = 'PROVIDER_MODEL_MISMATCH';
262
+ this.providerName = providerName;
263
+ this.model = model;
264
+ this.availableModels = availableModels;
265
+ }
266
+ }
267
+ /**
268
+ * Thrown when a stage declares `provider: X` but X is not in the
269
+ * registry passed to the executor.
270
+ */
271
+ export class UnknownProviderError extends Error {
272
+ providerName;
273
+ registeredNames;
274
+ constructor(providerName, registeredNames) {
275
+ const names = registeredNames.length > 0 ? registeredNames.join(', ') : '(none registered)';
276
+ super(`Provider '${providerName}' is not registered. ` +
277
+ `Available providers: ${names}`);
278
+ this.name = 'UNKNOWN_PROVIDER';
279
+ this.providerName = providerName;
280
+ this.registeredNames = registeredNames;
281
+ }
282
+ }
283
+ /**
284
+ * Thrown when a registered provider does not support the requested
285
+ * model. Fail-fast per ADR Q1 (R6.6 consumes this at validate time;
286
+ * runtime executor is defense-in-depth).
287
+ */
288
+ export class ProviderMismatchError extends Error {
289
+ providerName;
290
+ model;
291
+ availableModels;
292
+ constructor(providerName, model, availableModels) {
293
+ const avail = availableModels.length > 0 ? availableModels.join(', ') : '(none registered)';
294
+ super(`Provider '${providerName}' does not support model '${model}'. ` +
295
+ `Available models for this provider: ${avail}`);
296
+ this.name = 'PROVIDER_MISMATCH';
297
+ this.providerName = providerName;
298
+ this.model = model;
299
+ this.availableModels = availableModels;
300
+ }
301
+ }
302
+ export class LLMProviderRegistry {
303
+ byName;
304
+ constructor(providers) {
305
+ this.byName = new Map();
306
+ for (const p of providers) {
307
+ if (this.byName.has(p.name)) {
308
+ throw new Error(`LLMProviderRegistry: duplicate provider name '${p.name}'`);
309
+ }
310
+ this.byName.set(p.name, p);
311
+ }
312
+ }
313
+ resolve(name) {
314
+ const p = this.byName.get(name);
315
+ if (!p) {
316
+ throw new UnknownProviderError(name, Array.from(this.byName.keys()));
317
+ }
318
+ return p;
319
+ }
320
+ resolveWithSupports(name, model) {
321
+ const p = this.resolve(name);
322
+ if (!p.supports(model)) {
323
+ throw new ProviderMismatchError(name, model, p.models);
324
+ }
325
+ return p;
326
+ }
327
+ hasName(name) {
328
+ return this.byName.has(name);
329
+ }
330
+ names() {
331
+ return Array.from(this.byName.keys());
332
+ }
333
+ }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Pipeline text ${VAR} resolution + YAML parse.
3
+ *
4
+ * v0.3 NEW (R7.1 → R7.7). Two-stage: pure shell-style ${VAR} / ${VAR:-default}
5
+ * substitution from a caller-provided env (defaults to process.env), then
6
+ * yaml.load(). Keeps existing yaml.load consumers unchanged — they see the
7
+ * substituted string.
8
+ *
9
+ * 12-factor env-var convention (same as bash/zsh). No credential
10
+ * storage in v0.3 — values come from shell / CI secrets / Docker -e.
11
+ *
12
+ * TODO production: integrate with CF Workers Secrets API for runtime secret
13
+ * resolution; the current impl reads from process.env at parse time.
14
+ */
15
+ /**
16
+ * Thrown when ${VAR} appears without a default and env has no value.
17
+ * Carries the variable name (and optional file/line context) for
18
+ * structured logging / UI display.
19
+ */
20
+ export declare class MissingEnvVarError extends Error {
21
+ readonly varName: string;
22
+ readonly filePath?: string;
23
+ readonly lineNumber?: number;
24
+ constructor(varName: string, opts?: {
25
+ filePath?: string;
26
+ lineNumber?: number;
27
+ });
28
+ }
29
+ export interface EnvLike {
30
+ [key: string]: string | undefined;
31
+ }
32
+ /**
33
+ * Parse one variable spec like `${VAR}` or `${VAR:-default}` into its
34
+ * components. Returns `null` for spec strings that are not valid
35
+ * variable references (used internally by the resolver; exported for
36
+ * testability and tool-building).
37
+ *
38
+ * parseVariableSpec('${OPENAI_API_KEY}') → { name: 'OPENAI_API_KEY' }
39
+ * parseVariableSpec('${MODEL:-gpt-4o}') → { name: 'MODEL', default: 'gpt-4o' }
40
+ * parseVariableSpec('${NAME:- hello world }')→ { name: 'NAME', default: 'hello world' }
41
+ * parseVariableSpec('${EMPTY_VAR:-}') → { name: 'EMPTY_VAR', default: '' }
42
+ * parseVariableSpec('${lowercase}') → null (uppercase+underscore only)
43
+ * parseVariableSpec('not a spec') → null
44
+ */
45
+ export declare function parseVariableSpec(spec: string): {
46
+ name: string;
47
+ default?: string;
48
+ } | null;
49
+ /**
50
+ * Substitute ${VAR} and ${VAR:-default} occurrences in raw pipeline text.
51
+ *
52
+ * Pure — no I/O, no side effects. Defaults to process.env when env omitted.
53
+ *
54
+ * Edge cases:
55
+ * - `$$` (escape) → literal `$`
56
+ * - `${VAR:- default with spaces }` → default trimmed
57
+ * - `${VAR:-}` (empty default) → empty string when VAR unset
58
+ * - Nested `${${VAR}}` recurses up to 10 levels deep (DoS guard)
59
+ * - Lowercase first char (`${var}`) → not matched, left literal
60
+ */
61
+ export declare function expandPipelineText(raw: string, env?: EnvLike, opts?: {
62
+ filePath?: string;
63
+ }): string;
64
+ /**
65
+ * Public alias for `expandPipelineText`. Same semantics; the alias lives
66
+ * in the public API per the R7 spec.
67
+ */
68
+ export declare function resolveEnvVars(text: string, env?: EnvLike, opts?: {
69
+ filePath?: string;
70
+ }): string;
71
+ /**
72
+ * Recursively substitute ${VAR} / ${VAR:-default} in every string leaf of an
73
+ * already-parsed object tree (post-yaml.load). Non-string leaves are passed
74
+ * through unchanged.
75
+ *
76
+ * resolveEnvVarsInObject({ a: '${X}', b: 1, c: ['${Y:-fallback}'] }, { X: 'hi' })
77
+ * → { a: 'hi', b: 1, c: ['fallback'] }
78
+ *
79
+ * Useful when env vars land in values that come from sources other than raw
80
+ * YAML text (e.g., a JSON config loaded at runtime, or CLI inputs).
81
+ */
82
+ export declare function resolveEnvVarsInObject<T>(obj: T, env?: EnvLike): T;
83
+ /**
84
+ * Convenience: expand ${VAR} then yaml.load the substituted text.
85
+ * Returns unknown — caller casts to PipelineFileSpec / similar.
86
+ *
87
+ * Existing v0.2 / v0.3 callers (CLI run / validate, server publish) use
88
+ * this entry point; it adds the env-var preprocessing before handing the
89
+ * text off to js-yaml.
90
+ */
91
+ export declare function loadPipelineYaml(raw: string, env?: EnvLike): unknown;
@@ -0,0 +1,203 @@
1
+ /**
2
+ * Pipeline text ${VAR} resolution + YAML parse.
3
+ *
4
+ * v0.3 NEW (R7.1 → R7.7). Two-stage: pure shell-style ${VAR} / ${VAR:-default}
5
+ * substitution from a caller-provided env (defaults to process.env), then
6
+ * yaml.load(). Keeps existing yaml.load consumers unchanged — they see the
7
+ * substituted string.
8
+ *
9
+ * 12-factor env-var convention (same as bash/zsh). No credential
10
+ * storage in v0.3 — values come from shell / CI secrets / Docker -e.
11
+ *
12
+ * TODO production: integrate with CF Workers Secrets API for runtime secret
13
+ * resolution; the current impl reads from process.env at parse time.
14
+ */
15
+ import yaml from 'js-yaml';
16
+ /** Maximum recursion depth for nested ${${VAR}} patterns. */
17
+ const MAX_RECURSION_DEPTH = 10;
18
+ /**
19
+ * Thrown when ${VAR} appears without a default and env has no value.
20
+ * Carries the variable name (and optional file/line context) for
21
+ * structured logging / UI display.
22
+ */
23
+ export class MissingEnvVarError extends Error {
24
+ varName;
25
+ filePath;
26
+ lineNumber;
27
+ constructor(varName, opts = {}) {
28
+ const where = opts.filePath
29
+ ? (opts.lineNumber !== undefined
30
+ ? ` (in ${opts.filePath}:${opts.lineNumber})`
31
+ : ` (in ${opts.filePath})`)
32
+ : '';
33
+ super(`Environment variable "${varName}" is required (no default specified)${where}. Pipeline references \${${varName}}; set it via export ${varName}=... or use the syntax \${${varName}:-default_value}.`);
34
+ this.name = 'MISSING_ENV_VAR';
35
+ this.varName = varName;
36
+ this.filePath = opts.filePath;
37
+ this.lineNumber = opts.lineNumber;
38
+ }
39
+ }
40
+ /**
41
+ * Parse one variable spec like `${VAR}` or `${VAR:-default}` into its
42
+ * components. Returns `null` for spec strings that are not valid
43
+ * variable references (used internally by the resolver; exported for
44
+ * testability and tool-building).
45
+ *
46
+ * parseVariableSpec('${OPENAI_API_KEY}') → { name: 'OPENAI_API_KEY' }
47
+ * parseVariableSpec('${MODEL:-gpt-4o}') → { name: 'MODEL', default: 'gpt-4o' }
48
+ * parseVariableSpec('${NAME:- hello world }')→ { name: 'NAME', default: 'hello world' }
49
+ * parseVariableSpec('${EMPTY_VAR:-}') → { name: 'EMPTY_VAR', default: '' }
50
+ * parseVariableSpec('${lowercase}') → null (uppercase+underscore only)
51
+ * parseVariableSpec('not a spec') → null
52
+ */
53
+ export function parseVariableSpec(spec) {
54
+ if (typeof spec !== 'string')
55
+ return null;
56
+ // Match exactly one "${NAME}" or "${NAME:-default}" (whitespace tolerant inside braces).
57
+ const re = /^\$\{\s*([A-Z_][A-Z0-9_]*)\s*(?::-\s*([^}]*?)\s*)?\}$/;
58
+ const m = re.exec(spec);
59
+ if (!m)
60
+ return null;
61
+ const out = { name: m[1] };
62
+ // Capturing group 2 is undefined when no ":-" was present; explicit else branch
63
+ // distinguishes "no default" from "empty default".
64
+ if (m[2] !== undefined)
65
+ out.default = m[2];
66
+ return out;
67
+ }
68
+ /**
69
+ * Substitute ${VAR} and ${VAR:-default} occurrences in raw pipeline text.
70
+ *
71
+ * Pure — no I/O, no side effects. Defaults to process.env when env omitted.
72
+ *
73
+ * Edge cases:
74
+ * - `$$` (escape) → literal `$`
75
+ * - `${VAR:- default with spaces }` → default trimmed
76
+ * - `${VAR:-}` (empty default) → empty string when VAR unset
77
+ * - Nested `${${VAR}}` recurses up to 10 levels deep (DoS guard)
78
+ * - Lowercase first char (`${var}`) → not matched, left literal
79
+ */
80
+ export function expandPipelineText(raw, env = process.env, opts = {}) {
81
+ if (typeof raw !== 'string' || raw.length === 0)
82
+ return raw;
83
+ return substituteOnce(raw, env, 0, opts);
84
+ }
85
+ /**
86
+ * Public alias for `expandPipelineText`. Same semantics; the alias lives
87
+ * in the public API per the R7 spec.
88
+ */
89
+ export function resolveEnvVars(text, env, opts = {}) {
90
+ return expandPipelineText(text, env, opts);
91
+ }
92
+ /**
93
+ * Recursively substitute ${VAR} / ${VAR:-default} in every string leaf of an
94
+ * already-parsed object tree (post-yaml.load). Non-string leaves are passed
95
+ * through unchanged.
96
+ *
97
+ * resolveEnvVarsInObject({ a: '${X}', b: 1, c: ['${Y:-fallback}'] }, { X: 'hi' })
98
+ * → { a: 'hi', b: 1, c: ['fallback'] }
99
+ *
100
+ * Useful when env vars land in values that come from sources other than raw
101
+ * YAML text (e.g., a JSON config loaded at runtime, or CLI inputs).
102
+ */
103
+ export function resolveEnvVarsInObject(obj, env) {
104
+ return walkReplace(obj, env ?? process.env, 0, {});
105
+ }
106
+ function walkReplace(value, env, depth, opts) {
107
+ if (depth > MAX_RECURSION_DEPTH) {
108
+ throw new Error(`resolveEnvVarsInObject: object nesting exceeds MAX_RECURSION_DEPTH=${MAX_RECURSION_DEPTH}`);
109
+ }
110
+ if (value === null || value === undefined)
111
+ return value;
112
+ if (typeof value === 'string') {
113
+ return expandPipelineText(value, env, opts);
114
+ }
115
+ if (Array.isArray(value)) {
116
+ return value.map((v) => walkReplace(v, env, depth + 1, opts));
117
+ }
118
+ if (typeof value === 'object') {
119
+ const out = {};
120
+ for (const [k, v] of Object.entries(value)) {
121
+ out[k] = walkReplace(v, env, depth + 1, opts);
122
+ }
123
+ return out;
124
+ }
125
+ // numbers / booleans / bigints / symbols — pass through
126
+ return value;
127
+ }
128
+ /**
129
+ * Internal: one pass of substitution. Tracks recursion depth.
130
+ *
131
+ * Implementation notes:
132
+ * - `$$` is processed via a sentinel placeholder (a private-use-area
133
+ * Unicode code point that won't appear in normal pipeline text). The
134
+ * sentinel blocks the `${...}` regex from matching the literal
135
+ * content that should remain after `$$` escape. After the regex
136
+ * pass completes, the sentinel is replaced with `$`. This way
137
+ * `$${amount}` yields literal `${amount}` (the `{amount}` was never
138
+ * matched by the var regex) and `$$${VAR}` yields `$value` (the `$$`
139
+ * became a sentinel, the `${VAR}` legitimately substituted).
140
+ * - The regex tolerates whitespace inside the braces (`${ VAR }`) and
141
+ * accepts an optional `:-default` suffix whose default value is trimmed.
142
+ * - Lowercase / mixed-case names do NOT match — only [A-Z_][A-Z0-9_]* —
143
+ * so `${var}` and `$lowercase_var` are treated as literal text.
144
+ */
145
+ /** Sentinel used to mask $$ → $ escape so the var regex doesn't see it. */
146
+ const DOLLAR_ESCAPE_SENTINEL = '\uE000\uE001';
147
+ function substituteOnce(raw, env, depth, opts) {
148
+ if (depth > MAX_RECURSION_DEPTH) {
149
+ throw new Error(`expandPipelineText: substitution recursion exceeds MAX_RECURSION_DEPTH=${MAX_RECURSION_DEPTH}`);
150
+ }
151
+ // Phase 1: mask $$ → sentinel so the var regex won't see the leading $
152
+ // of a would-be `${...}` pattern produced by the escape.
153
+ let s = raw;
154
+ if (s.includes('$$')) {
155
+ s = s.split('$$').join(DOLLAR_ESCAPE_SENTINEL);
156
+ }
157
+ // Match a single ${...} reference. Multiline / global handled by looping.
158
+ const VAR_RE = /\$\{\s*([A-Z_][A-Z0-9_]*)\s*(?::-\s*([^}]*?)\s*)?\}/g;
159
+ let out = '';
160
+ let lastIndex = 0;
161
+ let match;
162
+ while ((match = VAR_RE.exec(s)) !== null) {
163
+ out += s.slice(lastIndex, match.index);
164
+ const name = match[1];
165
+ const fallbackRaw = match[2];
166
+ let resolved;
167
+ if (Object.prototype.hasOwnProperty.call(env, name) && env[name] !== undefined) {
168
+ resolved = env[name];
169
+ }
170
+ else if (fallbackRaw !== undefined) {
171
+ // fallback is trimmed by the regex (via \s* anchors); explicit empty string
172
+ // is preserved (matches shell `:-` semantics: an empty default is intentional).
173
+ resolved = fallbackRaw;
174
+ }
175
+ else {
176
+ throw new MissingEnvVarError(name, { filePath: opts.filePath });
177
+ }
178
+ // When the resolved value itself contains a ${...}-like sequence
179
+ // (chain of vars where one references another), recurse with depth+1.
180
+ if (resolved.indexOf('${') !== -1) {
181
+ resolved = substituteOnce(resolved, env, depth + 1, opts);
182
+ }
183
+ out += resolved;
184
+ lastIndex = match.index + match[0].length;
185
+ }
186
+ out += s.slice(lastIndex);
187
+ // Phase 2: restore sentinel → $
188
+ if (out.includes(DOLLAR_ESCAPE_SENTINEL)) {
189
+ out = out.split(DOLLAR_ESCAPE_SENTINEL).join('$');
190
+ }
191
+ return out;
192
+ }
193
+ /**
194
+ * Convenience: expand ${VAR} then yaml.load the substituted text.
195
+ * Returns unknown — caller casts to PipelineFileSpec / similar.
196
+ *
197
+ * Existing v0.2 / v0.3 callers (CLI run / validate, server publish) use
198
+ * this entry point; it adds the env-var preprocessing before handing the
199
+ * text off to js-yaml.
200
+ */
201
+ export function loadPipelineYaml(raw, env) {
202
+ return yaml.load(expandPipelineText(raw, env));
203
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * R10.1 — Retry config primitive per ADR Q3.
3
+ *
4
+ * Same-provider retries on transient errors. Distinct from `run_if:`
5
+ * which is a compensation gate (different provider/model).
6
+ *
7
+ * GitHub Actions splits `continue-on-error` (retry decoration) from
8
+ * `if: failure()` (compensation gate) — same separation here.
9
+ * Conflating them yields confusing YAML where fallback chains,
10
+ * retry counters, and trigger conditions all live in one block.
11
+ */
12
+ export type RetryBackoff = 'exponential' | 'linear' | 'fixed';
13
+ export interface RetryConfig {
14
+ /** Max attempts including the first try. Default 3. */
15
+ attempts?: number;
16
+ /** Backoff strategy between attempts. Default 'exponential'. */
17
+ backoff?: RetryBackoff;
18
+ /** HTTP status codes that should trigger a retry. Default [429, 503]. */
19
+ retryable_status?: number[];
20
+ /** Initial delay before first retry (ms). Default 1000. */
21
+ initial_ms?: number;
22
+ }
23
+ export declare const DEFAULT_RETRY: Required<Omit<RetryConfig, 'retryable_status'>>;
24
+ export declare const DEFAULT_RETRYABLE_STATUSES: readonly [429, 503];
25
+ export declare function isRetryableStatus(status: number, config?: RetryConfig): boolean;
26
+ export declare function computeBackoffMs(attempt: number, config?: RetryConfig): number;
27
+ export declare class RetryExhaustedError extends Error {
28
+ readonly stageId: string;
29
+ readonly attempts: number;
30
+ readonly lastError: string;
31
+ constructor(stageId: string, attempts: number, lastError: string);
32
+ }
33
+ export declare class RetryAttemptError extends Error {
34
+ readonly stageId: string;
35
+ readonly attempt: number;
36
+ readonly status: number;
37
+ readonly retryable: boolean;
38
+ readonly nextBackoffMs: number;
39
+ constructor(stageId: string, attempt: number, status: number, nextBackoffMs: number);
40
+ }