@agentsmarket/pipeline-runtime 0.5.6 → 0.5.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -165,12 +165,44 @@ const serverDeps = { isLocal: false, shellExecutor: new ThrowingShellExecutor('s
165
165
  ```
166
166
 
167
167
  `NodeShellExecutor` uses `child_process.spawn(cmd, args, { shell: false, timeout })`:
168
- no shell interpretation (no injection), SIGTERM on `timeout_ms` expiry
169
- (maps to `ShellStageTimeoutError`), non-zero exit → `ShellStageExecError`,
170
- stdout/stderr truncated at 1 MB each.
168
+ SIGTERM on `timeout_ms` expiry (maps to `ShellStageTimeoutError`), non-zero
169
+ exit → `ShellStageExecError`, stdout/stderr truncated at 1 MB each.
170
+
171
+ **Two forms, two different things:**
172
+
173
+ | form | what it is | how it runs |
174
+ |---|---|---|
175
+ | `shell: "npm test && npm run lint"` | a **command line** | `/bin/sh -c "npm test && npm run lint"` — `&&`, `\|`, `>`, `;` and quotes work as written |
176
+ | `shell: { cmd: "npm", args: ["test"] }` | an **exact argv** | `spawn(cmd, args, { shell: false })` — nothing is interpreted, nothing is re-quoted |
177
+
178
+ The string form is a real shell because the stage is called `shell:` — a line
179
+ that auto-splits into an argv would make `&&` an ordinary argument and quotes
180
+ literal. The translation happens once, in `normalizeShellStage`, so every
181
+ executor (local Node, remote sandbox) runs the exact same argv. The object
182
+ form stays shell-free: it is the form to use when the program must receive
183
+ precisely these arguments.
184
+
185
+ ```yaml
186
+ stages:
187
+ - id: lint-and-test
188
+ shell: "npm run lint && npm test"
189
+ - id: pytest
190
+ shell:
191
+ cmd: pytest
192
+ args: ["-x", "tests/"]
193
+ cwd: ./backend
194
+ timeout_ms: 120000
195
+ ```
171
196
 
172
197
  Limits: `timeout_ms` default 30000, max 600000 (10 min). Output cap 1 MB
173
- per stream.
198
+ per stream. The string form runs under POSIX `/bin/sh` (`SHELL_BIN`).
199
+
200
+ **One collision to know about:** `${VAR}` is substituted by the runtime
201
+ (v0.3 env-var substitution) before the YAML is parsed, so `${VAR}` inside a
202
+ shell line is resolved from the run's environment — not by the shell. That is
203
+ what you want for `shell: "curl -H 'Bearer ${API_KEY}' …"`, but a shell
204
+ construct that wants `${...}` for itself (a positional parameter, `${1}`)
205
+ never reaches the shell.
174
206
 
175
207
  ## Status
176
208
 
@@ -0,0 +1,66 @@
1
+ /**
2
+ * P4 — the HTTP shell executor: the server's way of running a command.
3
+ *
4
+ * The runtime asks "who runs this?" and the executor answers. Locally that is
5
+ * `NodeShellExecutor` (a child process on the machine). On the server the
6
+ * Worker has no processes, so the command goes to a sandbox service over
7
+ * HTTP and comes back as stdout/stderr/exit code.
8
+ *
9
+ * Why HTTP and not a binding: the sandbox is a separate process boundary. It
10
+ * holds no marketplace secret, it can be killed as a unit, and it can live on
11
+ * a different machine than the API. The protocol is deliberately small:
12
+ *
13
+ * POST /exec
14
+ * { "cmd": "python3", "args": ["verify.py"], "cwd": "/work",
15
+ * "env": {}, "files": [], "timeout_ms": 60000 }
16
+ *
17
+ * → { "stdout": "...", "stderr": "...", "exit_code": 0,
18
+ * "wall_ms": 812, "timed_out": false }
19
+ *
20
+ * The command is spawned WITHOUT a shell (`shell: false`), so the argv the
21
+ * runtime produced is the argv the sandbox runs. The runtime translates the
22
+ * string form into `/bin/sh -c <line>` before it gets here, which means the
23
+ * sandbox needs no idea that a "shell stage" exists — it runs argv.
24
+ *
25
+ * The sandbox is a trust boundary, not a convenience: it must not be able to
26
+ * reach the API, the database or the metadata service, and it must not see
27
+ * our keys. Those are properties of the sandbox's container, not of this
28
+ * client — this client only refuses to send anything the runtime did not
29
+ * ask for.
30
+ */
31
+ import { type ShellExecOptions, type ShellExecResult, type ShellExecutor, type ShellStageSpec } from './shell-stage.js';
32
+ /** The body the sandbox accepts. */
33
+ export interface SandboxExecRequest {
34
+ cmd: string;
35
+ args: string[];
36
+ cwd: string;
37
+ env?: Record<string, string>;
38
+ files?: Array<{
39
+ path: string;
40
+ content_b64: string;
41
+ }>;
42
+ timeout_ms: number;
43
+ }
44
+ /** The body the sandbox returns. */
45
+ export interface SandboxExecResponse {
46
+ stdout: string;
47
+ stderr: string;
48
+ exit_code: number;
49
+ wall_ms?: number;
50
+ timed_out?: boolean;
51
+ }
52
+ export interface HttpShellExecutorOptions {
53
+ /** Base URL of the sandbox service, e.g. https://sandbox.agentsmarket.world */
54
+ url: string;
55
+ /** Shared secret for the sandbox. Sent as a bearer token; never a pipeline value. */
56
+ token?: string;
57
+ /** Injectable for tests. Defaults to the global fetch. */
58
+ fetchImpl?: typeof fetch;
59
+ /** Milliseconds to wait for the sandbox before giving up on it. */
60
+ requestTimeoutMs?: number;
61
+ }
62
+ export declare class HttpShellExecutor implements ShellExecutor {
63
+ private readonly options;
64
+ constructor(options: HttpShellExecutorOptions);
65
+ exec(spec: ShellStageSpec, opts: ShellExecOptions): Promise<ShellExecResult>;
66
+ }
@@ -0,0 +1,99 @@
1
+ /**
2
+ * P4 — the HTTP shell executor: the server's way of running a command.
3
+ *
4
+ * The runtime asks "who runs this?" and the executor answers. Locally that is
5
+ * `NodeShellExecutor` (a child process on the machine). On the server the
6
+ * Worker has no processes, so the command goes to a sandbox service over
7
+ * HTTP and comes back as stdout/stderr/exit code.
8
+ *
9
+ * Why HTTP and not a binding: the sandbox is a separate process boundary. It
10
+ * holds no marketplace secret, it can be killed as a unit, and it can live on
11
+ * a different machine than the API. The protocol is deliberately small:
12
+ *
13
+ * POST /exec
14
+ * { "cmd": "python3", "args": ["verify.py"], "cwd": "/work",
15
+ * "env": {}, "files": [], "timeout_ms": 60000 }
16
+ *
17
+ * → { "stdout": "...", "stderr": "...", "exit_code": 0,
18
+ * "wall_ms": 812, "timed_out": false }
19
+ *
20
+ * The command is spawned WITHOUT a shell (`shell: false`), so the argv the
21
+ * runtime produced is the argv the sandbox runs. The runtime translates the
22
+ * string form into `/bin/sh -c <line>` before it gets here, which means the
23
+ * sandbox needs no idea that a "shell stage" exists — it runs argv.
24
+ *
25
+ * The sandbox is a trust boundary, not a convenience: it must not be able to
26
+ * reach the API, the database or the metadata service, and it must not see
27
+ * our keys. Those are properties of the sandbox's container, not of this
28
+ * client — this client only refuses to send anything the runtime did not
29
+ * ask for.
30
+ */
31
+ import { ShellStageExecError, ShellStageTimeoutError, ShellStageUnsupportedError, } from './shell-stage.js';
32
+ export class HttpShellExecutor {
33
+ options;
34
+ constructor(options) {
35
+ this.options = options;
36
+ }
37
+ async exec(spec, opts) {
38
+ const fetchImpl = this.options.fetchImpl ?? globalThis.fetch;
39
+ if (typeof fetchImpl !== 'function') {
40
+ throw new ShellStageUnsupportedError('<shell>', 'no fetch implementation is available');
41
+ }
42
+ const body = {
43
+ cmd: spec.cmd,
44
+ args: spec.args ?? [],
45
+ cwd: opts.cwd,
46
+ // Sent as exactly what the runtime resolved for this stage — the
47
+ // sandbox builds PATH/HOME/LANG itself and adds nothing else, so this
48
+ // object IS the stage's universe. It used to be omitted entirely,
49
+ // which meant a stage handed a granted secret still ran without it.
50
+ env: { ...(opts.env ?? {}) },
51
+ // The author's bundle, written into the working directory before the
52
+ // command starts. Omitted when the pipeline ships no files — the
53
+ // sandbox treats a missing list as "nothing to write".
54
+ ...(opts.files && opts.files.length > 0 ? { files: opts.files } : {}),
55
+ timeout_ms: opts.timeoutMs,
56
+ };
57
+ const controller = new AbortController();
58
+ const requestTimeout = this.options.requestTimeoutMs ?? opts.timeoutMs + 5_000;
59
+ const timer = setTimeout(() => controller.abort(), requestTimeout);
60
+ const t0 = Date.now();
61
+ let response;
62
+ try {
63
+ response = await fetchImpl(`${this.options.url.replace(/\/$/, '')}/exec`, {
64
+ method: 'POST',
65
+ headers: {
66
+ 'content-type': 'application/json',
67
+ ...(this.options.token ? { authorization: `Bearer ${this.options.token}` } : {}),
68
+ },
69
+ body: JSON.stringify(body),
70
+ signal: controller.signal,
71
+ });
72
+ }
73
+ catch (e) {
74
+ clearTimeout(timer);
75
+ throw new ShellStageUnsupportedError('<shell>', `the sandbox at ${this.options.url} is unreachable (${e instanceof Error ? e.message : String(e)})`);
76
+ }
77
+ clearTimeout(timer);
78
+ if (!response.ok) {
79
+ const text = await response.text().catch(() => '');
80
+ throw new ShellStageUnsupportedError('<shell>', `the sandbox at ${this.options.url} answered HTTP ${response.status}${text ? `: ${text.slice(0, 200)}` : ''}`);
81
+ }
82
+ const payload = (await response.json());
83
+ const durationMs = payload.wall_ms ?? Date.now() - t0;
84
+ if (payload.timed_out) {
85
+ throw new ShellStageTimeoutError('<shell>', opts.timeoutMs);
86
+ }
87
+ if (payload.exit_code !== 0) {
88
+ throw new ShellStageExecError('<shell>', payload.exit_code, payload.stderr || payload.stdout);
89
+ }
90
+ return {
91
+ stdout: payload.stdout ?? '',
92
+ stderr: payload.stderr ?? '',
93
+ exitCode: payload.exit_code,
94
+ durationMs,
95
+ cmd: spec.cmd,
96
+ args: spec.args ?? [],
97
+ };
98
+ }
99
+ }
package/dist/index.d.ts CHANGED
@@ -53,7 +53,8 @@ export { OutputValidationError, OUTPUT_VALIDATION_RETRY_ATTEMPTS, isOutputValida
53
53
  export { validateOutput, type ValidateOutputOptions, type ValidateOutputResult, } from './validate-inputs.js';
54
54
  export { analyzeCapabilities, type PipelineCapabilities, type NetworkCapability, type PipelineSpecLikeForCaps, type PipelineStageLikeForCaps, } from './capabilities.js';
55
55
  export { extractProducedFiles, globToRegex, MAX_FILE_BYTES, MAX_TOTAL_BYTES, MAX_FILES, type ProducedFile, type ExtractResult, } from './file-output.js';
56
- export { normalizeShellStage, ThrowingShellExecutor, NodeShellExecutor, ShellStageUnsupportedError, ShellStageExecError, ShellStageTimeoutError, SHELL_DEFAULT_TIMEOUT_MS, SHELL_MAX_TIMEOUT_MS, SHELL_MAX_OUTPUT_BYTES, type ShellStageSpec, type ShellExecutor, type ShellExecOptions, type ShellExecResult, } from './shell-stage.js';
56
+ export { HttpShellExecutor, type HttpShellExecutorOptions, type SandboxExecRequest, type SandboxExecResponse, } from './http-shell-executor.js';
57
+ export { normalizeShellStage, ThrowingShellExecutor, NodeShellExecutor, ShellStageUnsupportedError, ShellStageExecError, ShellStageTimeoutError, SHELL_DEFAULT_TIMEOUT_MS, SHELL_MAX_TIMEOUT_MS, SHELL_MAX_OUTPUT_BYTES, SHELL_BIN, validateShellStageSecretUsage, type ShellStageSpec, type ShellExecutor, type ShellExecOptions, type ShellExecResult, } from './shell-stage.js';
57
58
  export interface PipelineStageSpec {
58
59
  id: string;
59
60
  model: string;
package/dist/index.js CHANGED
@@ -37,7 +37,8 @@ export { OutputValidationError, OUTPUT_VALIDATION_RETRY_ATTEMPTS, isOutputValida
37
37
  export { validateOutput, } from './validate-inputs.js';
38
38
  export { analyzeCapabilities, } from './capabilities.js';
39
39
  export { extractProducedFiles, globToRegex, MAX_FILE_BYTES, MAX_TOTAL_BYTES, MAX_FILES, } from './file-output.js';
40
- export { normalizeShellStage, ThrowingShellExecutor, NodeShellExecutor, ShellStageUnsupportedError, ShellStageExecError, ShellStageTimeoutError, SHELL_DEFAULT_TIMEOUT_MS, SHELL_MAX_TIMEOUT_MS, SHELL_MAX_OUTPUT_BYTES, } from './shell-stage.js';
40
+ export { HttpShellExecutor, } from './http-shell-executor.js';
41
+ export { normalizeShellStage, ThrowingShellExecutor, NodeShellExecutor, ShellStageUnsupportedError, ShellStageExecError, ShellStageTimeoutError, SHELL_DEFAULT_TIMEOUT_MS, SHELL_MAX_TIMEOUT_MS, SHELL_MAX_OUTPUT_BYTES, SHELL_BIN, validateShellStageSecretUsage, } from './shell-stage.js';
41
42
  export async function runStage(stage, ctx) {
42
43
  const vars = [];
43
44
  for (const [key, val] of Object.entries(ctx.outputs)) {
@@ -13,8 +13,12 @@
13
13
  * change here.
14
14
  *
15
15
  * **Execution model:**
16
- * - `spawn(cmd, args, { shell: false })` — no shell interpretation, args
17
- * are passed verbatim to the OS as argv. Prevents shell injection.
16
+ * - The STRING form is a command LINE, not an argv. It is translated once,
17
+ * in `normalizeShellStage`, into `/bin/sh -c <line>` — so `&&`, `|`, `>`
18
+ * and quotes behave the way the author wrote them, and every executor
19
+ * (local Node, remote sandbox) runs the exact same argv.
20
+ * - The OBJECT form is an exact argv: `spawn(cmd, args, { shell: false })`,
21
+ * no shell interpretation, nothing re-quoted.
18
22
  * - `timeout` option sends SIGTERM after `timeout_ms`; the executor
19
23
  * maps that to `ShellStageTimeoutError`.
20
24
  * - Non-zero exit code → `ShellStageExecError` with stderr in message.
@@ -26,8 +30,8 @@
26
30
  * never touch the binding (the server uses a throwing stub).
27
31
  *
28
32
  * Stage schema (two forms):
29
- * shell: "npm test" # shorthand: auto-split
30
- * shell: # explicit form
33
+ * shell: "npm test && npm run lint" # shorthand: a shell line
34
+ * shell: # explicit form: exact argv
31
35
  * cmd: "npm"
32
36
  * args: ["test"]
33
37
  * cwd: "./my-project"
@@ -42,10 +46,68 @@ export interface ShellStageSpec {
42
46
  export declare const SHELL_DEFAULT_TIMEOUT_MS = 30000;
43
47
  export declare const SHELL_MAX_OUTPUT_BYTES: number;
44
48
  export declare const SHELL_MAX_TIMEOUT_MS = 600000;
49
+ /**
50
+ * The shell that runs the STRING form of a shell stage.
51
+ *
52
+ * A string is a command line, not an argv — without a shell `&&` would be an
53
+ * argument and quotes would be literal. POSIX `/bin/sh`; the stage's `cwd`
54
+ * and the runner's environment apply as usual.
55
+ */
56
+ export declare const SHELL_BIN = "/bin/sh";
45
57
  export declare function normalizeShellStage(raw: unknown): ShellStageSpec | null;
58
+ /**
59
+ * The exact-argv form does not expand `$NAME` — and a secret can only reach
60
+ * a program through the environment.
61
+ *
62
+ * A shell stage has two forms and they deliver a secret differently:
63
+ *
64
+ * the STRING form → `/bin/sh -c <line>`, so the shell expands `$TOKEN`
65
+ * from the stage's environment;
66
+ * the OBJECT form → an exact argv, spawned without a shell, so `$TOKEN`
67
+ * is a literal string and `${TOKEN}` is refused at
68
+ * publish time (a secret's value never belongs in the
69
+ * text of a spec — the owner's rule §8.1).
70
+ *
71
+ * In the object form the secret still arrives: the runtime resolves the
72
+ * names the stage declared against the buyer's grants and passes them as
73
+ * that stage's environment, so the program reads `os.environ['TOKEN']` (or
74
+ * `process.env.TOKEN`). What does NOT work is the author writing `$TOKEN`
75
+ * inside `args` and expecting the value there — it would reach the program
76
+ * as the four characters `$TOKEN`.
77
+ *
78
+ * This check turns that silent mistake into an error at publish time, where
79
+ * the author is still looking at the spec. The string form is left alone:
80
+ * there the shell does the expanding, which is the whole point of it.
81
+ */
82
+ export declare function validateShellStageSecretUsage(stage: unknown): string | null;
46
83
  export interface ShellExecOptions {
47
84
  cwd: string;
48
85
  timeoutMs: number;
86
+ /**
87
+ * Variables this stage is allowed to see.
88
+ *
89
+ * The runtime resolves a stage's declared `secrets:` against the buyer's
90
+ * granted set and passes only those values here. A stage that declares
91
+ * nothing gets an empty object — the executor's job is to run the command in
92
+ * exactly this environment, so whatever the host process happens to hold must
93
+ * not leak in by default.
94
+ */
95
+ env?: Record<string, string>;
96
+ /**
97
+ * The author's bundle — the files that ship with the pipeline — to be
98
+ * written into the working directory before the command runs.
99
+ *
100
+ * Without this a stage that runs `node scripts/verify.js` finds no
101
+ * `scripts/`: the pipeline's files were stored with the pipeline but never
102
+ * travelled to the process that runs them. The content is base64 because
103
+ * a bundle entry is binary as often as it is text.
104
+ */
105
+ files?: ShellExecFile[];
106
+ }
107
+ /** One file of the author's bundle, on its way to the working directory. */
108
+ export interface ShellExecFile {
109
+ path: string;
110
+ content_b64: string;
49
111
  }
50
112
  export interface ShellExecResult {
51
113
  stdout: string;
@@ -13,8 +13,12 @@
13
13
  * change here.
14
14
  *
15
15
  * **Execution model:**
16
- * - `spawn(cmd, args, { shell: false })` — no shell interpretation, args
17
- * are passed verbatim to the OS as argv. Prevents shell injection.
16
+ * - The STRING form is a command LINE, not an argv. It is translated once,
17
+ * in `normalizeShellStage`, into `/bin/sh -c <line>` — so `&&`, `|`, `>`
18
+ * and quotes behave the way the author wrote them, and every executor
19
+ * (local Node, remote sandbox) runs the exact same argv.
20
+ * - The OBJECT form is an exact argv: `spawn(cmd, args, { shell: false })`,
21
+ * no shell interpretation, nothing re-quoted.
18
22
  * - `timeout` option sends SIGTERM after `timeout_ms`; the executor
19
23
  * maps that to `ShellStageTimeoutError`.
20
24
  * - Non-zero exit code → `ShellStageExecError` with stderr in message.
@@ -26,8 +30,8 @@
26
30
  * never touch the binding (the server uses a throwing stub).
27
31
  *
28
32
  * Stage schema (two forms):
29
- * shell: "npm test" # shorthand: auto-split
30
- * shell: # explicit form
33
+ * shell: "npm test && npm run lint" # shorthand: a shell line
34
+ * shell: # explicit form: exact argv
31
35
  * cmd: "npm"
32
36
  * args: ["test"]
33
37
  * cwd: "./my-project"
@@ -36,13 +40,23 @@
36
40
  export const SHELL_DEFAULT_TIMEOUT_MS = 30_000;
37
41
  export const SHELL_MAX_OUTPUT_BYTES = 1024 * 1024;
38
42
  export const SHELL_MAX_TIMEOUT_MS = 600_000;
43
+ /**
44
+ * The shell that runs the STRING form of a shell stage.
45
+ *
46
+ * A string is a command line, not an argv — without a shell `&&` would be an
47
+ * argument and quotes would be literal. POSIX `/bin/sh`; the stage's `cwd`
48
+ * and the runner's environment apply as usual.
49
+ */
50
+ export const SHELL_BIN = '/bin/sh';
39
51
  export function normalizeShellStage(raw) {
40
52
  if (typeof raw === 'string') {
41
53
  const trimmed = raw.trim();
42
54
  if (trimmed.length === 0)
43
55
  return null;
44
- const parts = trimmed.split(/\s+/);
45
- return { cmd: parts[0], args: parts.slice(1) };
56
+ // Translated HERE, once, so every executor runs the same argv: the local
57
+ // Node executor and a remote sandbox must not disagree about what the
58
+ // author's `&&` means.
59
+ return { cmd: SHELL_BIN, args: ['-c', trimmed] };
46
60
  }
47
61
  if (!raw || typeof raw !== 'object')
48
62
  return null;
@@ -62,6 +76,68 @@ export function normalizeShellStage(raw) {
62
76
  }
63
77
  return spec;
64
78
  }
79
+ /**
80
+ * The exact-argv form does not expand `$NAME` — and a secret can only reach
81
+ * a program through the environment.
82
+ *
83
+ * A shell stage has two forms and they deliver a secret differently:
84
+ *
85
+ * the STRING form → `/bin/sh -c <line>`, so the shell expands `$TOKEN`
86
+ * from the stage's environment;
87
+ * the OBJECT form → an exact argv, spawned without a shell, so `$TOKEN`
88
+ * is a literal string and `${TOKEN}` is refused at
89
+ * publish time (a secret's value never belongs in the
90
+ * text of a spec — the owner's rule §8.1).
91
+ *
92
+ * In the object form the secret still arrives: the runtime resolves the
93
+ * names the stage declared against the buyer's grants and passes them as
94
+ * that stage's environment, so the program reads `os.environ['TOKEN']` (or
95
+ * `process.env.TOKEN`). What does NOT work is the author writing `$TOKEN`
96
+ * inside `args` and expecting the value there — it would reach the program
97
+ * as the four characters `$TOKEN`.
98
+ *
99
+ * This check turns that silent mistake into an error at publish time, where
100
+ * the author is still looking at the spec. The string form is left alone:
101
+ * there the shell does the expanding, which is the whole point of it.
102
+ */
103
+ export function validateShellStageSecretUsage(stage) {
104
+ if (!stage || typeof stage !== 'object')
105
+ return null;
106
+ const s = stage;
107
+ // Only the object form: the string form goes through a shell.
108
+ if (!s.shell || typeof s.shell !== 'object' || Array.isArray(s.shell))
109
+ return null;
110
+ const shell = s.shell;
111
+ const declared = Array.isArray(s.secrets)
112
+ ? s.secrets.filter((n) => typeof n === 'string')
113
+ : [];
114
+ if (declared.length === 0)
115
+ return null;
116
+ const texts = [];
117
+ if (typeof shell.cmd === 'string')
118
+ texts.push(shell.cmd);
119
+ if (Array.isArray(shell.args)) {
120
+ for (const a of shell.args)
121
+ if (typeof a === 'string')
122
+ texts.push(a);
123
+ }
124
+ if (texts.length === 0)
125
+ return null;
126
+ const label = typeof s.id === 'string' && s.id.length > 0 ? `Stage '${s.id}'` : 'Stage';
127
+ for (const name of declared) {
128
+ // `$NAME` or `${NAME}` — both are the author's intent to put the value
129
+ // into the argument, and neither can work here.
130
+ const re = new RegExp(`\\$\\{?${name}\\b`);
131
+ if (!texts.some((t) => re.test(t)))
132
+ continue;
133
+ return (`${label}: the exact-argv form ({cmd, args}) does not expand $${name}, and a secret's ` +
134
+ `value never belongs in the text of a spec. The secret reaches the program as the ` +
135
+ `environment variable ${name}: declare it in this stage's \`secrets:\` and read it from ` +
136
+ `the environment (os.environ['${name}']). To let a shell expand $${name} itself, use the ` +
137
+ `string form (\`shell: "…$$\{${name}\}…"\`), which runs through /bin/sh.`);
138
+ }
139
+ return null;
140
+ }
65
141
  export class ShellStageUnsupportedError extends Error {
66
142
  stageId;
67
143
  reason;
package/dist/stages.d.ts CHANGED
@@ -18,7 +18,7 @@ import type { PricingResolver } from './pricing.js';
18
18
  import { createModelResolver, type ModelResolver, type PipelineLike, type PipelineStageLike, type SkillLike } from './model-resolver.js';
19
19
  import { type PipelineEventSink } from './streaming-events.js';
20
20
  import { type RuntimeConstraints } from './runtime-constraints.js';
21
- import { type ShellExecutor } from './shell-stage.js';
21
+ import { type ShellExecutor, type ShellExecFile } from './shell-stage.js';
22
22
  import { type PipelineFetcher, type CompositionConfig } from './composition.js';
23
23
  export interface ResolvedUse {
24
24
  id: string;
@@ -129,6 +129,30 @@ export interface StageExecutorDeps {
129
129
  * When absent, stages declaring `shell:` throw `ShellStageUnsupportedError`.
130
130
  */
131
131
  shellExecutor?: ShellExecutor;
132
+ /**
133
+ * Values of the secrets granted for this run, by name.
134
+ *
135
+ * A shell stage receives only the names it declared in its own `secrets:`
136
+ * list, resolved out of this map. The host's own environment is never a
137
+ * source — the caller builds this from the buyer's grants, so a stage
138
+ * cannot read the platform's bindings by naming them.
139
+ */
140
+ grantedSecrets?: Record<string, string>;
141
+ /**
142
+ * The author's bundle, by path — written into the working directory before
143
+ * the command runs, so a stage can call the script that ships with the
144
+ * pipeline. Empty/absent for a pipeline that ships no files.
145
+ */
146
+ stageFiles?: ShellExecFile[];
147
+ /**
148
+ * The working directory for stages that do not name one.
149
+ *
150
+ * The server sets a per-run directory: the sandbox container has one
151
+ * filesystem, and two runs writing the same file name into the same place
152
+ * would race. Left undefined locally, where the caller's own directory is
153
+ * the right answer.
154
+ */
155
+ shellWorkdir?: string;
132
156
  }
133
157
  export interface RetryContext {
134
158
  stageId: string;
package/dist/stages.js CHANGED
@@ -484,10 +484,33 @@ correctionHint) {
484
484
  throw new StageBadConfigError(`Stage '${stage.id}' has a malformed 'shell' spec (expected string or { cmd, args?, cwd?, timeout_ms? })`);
485
485
  }
486
486
  const shellT0 = Date.now();
487
+ // Only the names THIS stage declared, and only those the host actually
488
+ // granted. The sandbox executor runs the command in exactly this
489
+ // environment — nothing crosses the boundary but what is listed here.
490
+ // The local executor merges it over the caller's own shell env, because
491
+ // that is where a local run's variables come from (the CLI substitutes
492
+ // ${VAR} from the same place).
493
+ const stageEnv = {};
494
+ const declaredRaw = stage.secrets;
495
+ const declared = Array.isArray(declaredRaw)
496
+ ? declaredRaw.filter((n) => typeof n === 'string')
497
+ : [];
498
+ for (const name of declared) {
499
+ const v = deps.grantedSecrets?.[name];
500
+ if (typeof v === 'string' && v.length > 0)
501
+ stageEnv[name] = v;
502
+ }
487
503
  try {
488
504
  const result = await deps.shellExecutor.exec(spec, {
489
- cwd: spec.cwd ?? process.cwd(),
505
+ // The host's working directory when the author did not pick one: on
506
+ // the server that is a per-run directory (a Worker has no meaningful
507
+ // cwd of its own, and '/' is not writable inside the sandbox).
508
+ cwd: spec.cwd ?? deps.shellWorkdir ?? process.cwd(),
490
509
  timeoutMs: spec.timeout_ms ?? SHELL_DEFAULT_TIMEOUT_MS,
510
+ env: stageEnv,
511
+ // The author's bundle, written into the working directory before the
512
+ // command starts. Absent for a pipeline that ships no files.
513
+ files: deps.stageFiles,
491
514
  });
492
515
  const output = JSON.stringify({
493
516
  cmd: spec.cmd,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentsmarket/pipeline-runtime",
3
- "version": "0.5.6",
3
+ "version": "0.5.8",
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",