@niwa-labs/sandbox 0.0.0-stage → 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +21 -2
- package/package.json +15 -4
- package/src/access.ts +642 -0
- package/src/index.ts +68 -0
- package/src/launch.ts +403 -0
- package/src/nono.ts +349 -0
- package/src/paths.ts +31 -0
- package/src/profile.ts +140 -0
- package/src/profiles.ts +62 -0
- package/src/sandbox.ts +124 -0
- package/src/spawn.ts +147 -0
- package/src/spec.ts +60 -0
- package/src/srt.ts +187 -0
- package/test/access.test.ts +367 -0
- package/test/box-process.test.ts +327 -0
- package/test/launcher-env.test.ts +144 -0
- package/test/live.test.ts +259 -0
- package/test/manifest.test.ts +231 -0
- package/tsconfig.json +6 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The sandbox module: `Sandbox { name, class, available, manifest,
|
|
3
|
+
* launch }` over the `BoxSpec`. The process class is built (srt, nono); microVMs are not.
|
|
4
|
+
*
|
|
5
|
+
* The `spawnAgent` funnel (`launch.ts`) is here too: the one place an agent process is born, boxed
|
|
6
|
+
* or not.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export { BoxPathSchema, BoxSpecSchema, EnvNameSchema, NetHostSchema, boxSpec } from "./spec.ts";
|
|
10
|
+
export type { BoxPath, BoxSpec, BoxSpecInput, EnvName, NetHost } from "./spec.ts";
|
|
11
|
+
export { BoxRefused, SandboxUnavailable, requireSandbox } from "./sandbox.ts";
|
|
12
|
+
export type { BoxPolicy, BoxRefusal, LaunchedBox, Sandbox, SandboxClass, SandboxManifest, SandboxName } from "./sandbox.ts";
|
|
13
|
+
export {
|
|
14
|
+
ALWAYS_CLOSED,
|
|
15
|
+
AccessItemSchema,
|
|
16
|
+
BoxAccessSchema,
|
|
17
|
+
BoxManifestSchema,
|
|
18
|
+
BoxPolicySchema,
|
|
19
|
+
admit,
|
|
20
|
+
boxManifest,
|
|
21
|
+
itemOf,
|
|
22
|
+
itemText,
|
|
23
|
+
placeTarget,
|
|
24
|
+
repositoryOf,
|
|
25
|
+
sandbox,
|
|
26
|
+
planSpec,
|
|
27
|
+
} from "./access.ts";
|
|
28
|
+
export type {
|
|
29
|
+
AccessItem,
|
|
30
|
+
AccessItemInput,
|
|
31
|
+
BoxAccess,
|
|
32
|
+
BoxAccessInput,
|
|
33
|
+
BoxManifest,
|
|
34
|
+
BoxPlan,
|
|
35
|
+
BoxProfiles,
|
|
36
|
+
Origin,
|
|
37
|
+
PathNeed,
|
|
38
|
+
PlanInput,
|
|
39
|
+
ProfileName,
|
|
40
|
+
SandboxHost,
|
|
41
|
+
SandboxOptions,
|
|
42
|
+
Skipped,
|
|
43
|
+
} from "./access.ts";
|
|
44
|
+
export { programPaths, realPlace, resolveProfile } from "./profile.ts";
|
|
45
|
+
export type { BoxProfile, ProfileContext, ProfilePaths, ResolvedProfile } from "./profile.ts";
|
|
46
|
+
export { srt } from "./srt.ts";
|
|
47
|
+
export type { SrtManifest, SrtOptions, SrtSettings } from "./srt.ts";
|
|
48
|
+
export { nono } from "./nono.ts";
|
|
49
|
+
export type { NonoManifest, NonoOptions, NonoProfile } from "./nono.ts";
|
|
50
|
+
export {
|
|
51
|
+
LIVE_PROCESS_REFUSAL,
|
|
52
|
+
homePath,
|
|
53
|
+
onBoxManifest,
|
|
54
|
+
onSpawn,
|
|
55
|
+
requireBox,
|
|
56
|
+
sandboxOf,
|
|
57
|
+
spawnAgent,
|
|
58
|
+
spawnAgentNow,
|
|
59
|
+
useSandbox,
|
|
60
|
+
} from "./launch.ts";
|
|
61
|
+
export type {
|
|
62
|
+
AgentLaunch,
|
|
63
|
+
AgentProcess,
|
|
64
|
+
BoxRecord,
|
|
65
|
+
BoxRequest,
|
|
66
|
+
BoxSandboxName,
|
|
67
|
+
SpawnEvent,
|
|
68
|
+
} from "./launch.ts";
|
package/src/launch.ts
ADDED
|
@@ -0,0 +1,403 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `spawnAgent` funnel: the one place an agent process is born.
|
|
3
|
+
*
|
|
4
|
+
* Every harness starts its process here. The funnel builds the environment (the inherited one plus
|
|
5
|
+
* the session's additions), and when the launch asks for a box it takes the box's sandbox, records
|
|
6
|
+
* the manifest, and launches through the sandbox. What the harness needs inside the box is in the
|
|
7
|
+
* spec already: its profile was resolved with the rest of the box. A sandbox that is required and unavailable stops the start: the error is
|
|
8
|
+
* `SandboxUnavailable` and no process exists.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { spawn } from "node:child_process";
|
|
12
|
+
import type { ChildProcessByStdio } from "node:child_process";
|
|
13
|
+
import { EventEmitter } from "node:events";
|
|
14
|
+
import { homedir } from "node:os";
|
|
15
|
+
import { join } from "node:path";
|
|
16
|
+
import { PassThrough } from "node:stream";
|
|
17
|
+
import type { Readable, Writable } from "node:stream";
|
|
18
|
+
|
|
19
|
+
import { nono } from "./nono.ts";
|
|
20
|
+
import { requireSandbox } from "./sandbox.ts";
|
|
21
|
+
import type { LaunchedBox, Sandbox, SandboxManifest, SandboxName } from "./sandbox.ts";
|
|
22
|
+
import { boxSpec } from "./spec.ts";
|
|
23
|
+
import type { BoxSpec, BoxSpecInput } from "./spec.ts";
|
|
24
|
+
import { srt } from "./srt.ts";
|
|
25
|
+
|
|
26
|
+
/** The sandboxes a launch may name: the process class. */
|
|
27
|
+
export type BoxSandboxName = "srt" | "nono";
|
|
28
|
+
|
|
29
|
+
/** A box a session must run in: the sandbox and what it may reach. */
|
|
30
|
+
export interface BoxRequest {
|
|
31
|
+
/** The sandbox by its name, or the sandbox itself for a host that made its own. */
|
|
32
|
+
readonly sandbox: BoxSandboxName | Sandbox;
|
|
33
|
+
readonly spec: BoxSpecInput;
|
|
34
|
+
/** Whoever asked for the box, so the manifest of its launch can be told from another's: it goes on to the record. */
|
|
35
|
+
readonly mark?: string;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Why a resume that reuses a running process cannot take new tools or a new box. */
|
|
39
|
+
export const LIVE_PROCESS_REFUSAL = "a running session keeps the tools and the box its process was born with";
|
|
40
|
+
|
|
41
|
+
/** A path under the user's home directory, absolute. */
|
|
42
|
+
export function homePath(...parts: readonly string[]): string {
|
|
43
|
+
return join(homedir(), ...parts);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface AgentLaunch {
|
|
47
|
+
/** The harness instance that starts the process, for the records. */
|
|
48
|
+
readonly harness: string;
|
|
49
|
+
readonly program: string;
|
|
50
|
+
readonly args: readonly string[];
|
|
51
|
+
readonly cwd?: string;
|
|
52
|
+
/** Added to the inherited environment: the session's `NIWA_ID` and what the harness sets for itself. */
|
|
53
|
+
readonly env?: Readonly<Record<string, string>>;
|
|
54
|
+
/** Names removed from the inherited environment before the additions go on. */
|
|
55
|
+
readonly unset?: readonly string[];
|
|
56
|
+
/** The process leads its own process group, so a stop reaches everything it started. */
|
|
57
|
+
readonly detached?: boolean;
|
|
58
|
+
/** Run inside a sandbox. */
|
|
59
|
+
readonly box?: BoxRequest;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* The part of a child process the harnesses use. A node `ChildProcess` started with pipes is one;
|
|
64
|
+
* so is the process of a boxed launch.
|
|
65
|
+
*/
|
|
66
|
+
export interface AgentProcess {
|
|
67
|
+
readonly pid?: number | undefined;
|
|
68
|
+
readonly stdin: Writable;
|
|
69
|
+
readonly stdout: Readable;
|
|
70
|
+
readonly stderr: Readable;
|
|
71
|
+
readonly exitCode: number | null;
|
|
72
|
+
readonly signalCode: NodeJS.Signals | null;
|
|
73
|
+
readonly killed: boolean;
|
|
74
|
+
kill(signal?: NodeJS.Signals | number): boolean;
|
|
75
|
+
on(event: "close" | "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;
|
|
76
|
+
on(event: "error", listener: (error: Error) => void): this;
|
|
77
|
+
once(event: "close" | "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;
|
|
78
|
+
once(event: "error", listener: (error: Error) => void): this;
|
|
79
|
+
off(event: "close" | "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this;
|
|
80
|
+
off(event: "error", listener: (error: Error) => void): this;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** One process, as the funnel started it. */
|
|
84
|
+
export interface SpawnEvent {
|
|
85
|
+
readonly harness: string;
|
|
86
|
+
/** The program and its arguments, as they were run: inside the wrapper's own argv when boxed. */
|
|
87
|
+
readonly argv: readonly string[];
|
|
88
|
+
readonly cwd: string | undefined;
|
|
89
|
+
/** The additions to the environment, not the whole of it. */
|
|
90
|
+
readonly env: Readonly<Record<string, string>>;
|
|
91
|
+
readonly sandbox: SandboxName | undefined;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** The manifest of a box, as it will be given to the sandbox. */
|
|
95
|
+
export interface BoxRecord {
|
|
96
|
+
readonly harness: string;
|
|
97
|
+
/** The mark of the request, when it had one. */
|
|
98
|
+
readonly mark?: string;
|
|
99
|
+
readonly sandbox: SandboxName;
|
|
100
|
+
/** The spec, with the environment the process is started with. */
|
|
101
|
+
readonly spec: BoxSpec;
|
|
102
|
+
readonly manifest: SandboxManifest;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const spawnListeners = new Set<(event: SpawnEvent) => void>();
|
|
106
|
+
const boxListeners = new Set<(record: BoxRecord) => void | Promise<void>>();
|
|
107
|
+
|
|
108
|
+
/** Hears every process the funnel starts, as it starts. Returns the unsubscribe. */
|
|
109
|
+
export function onSpawn(listener: (event: SpawnEvent) => void): () => void {
|
|
110
|
+
spawnListeners.add(listener);
|
|
111
|
+
return () => void spawnListeners.delete(listener);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Hears the manifest of every box before its process is started, and is waited for: a record that
|
|
116
|
+
* cannot be made stops the launch. Returns the unsubscribe.
|
|
117
|
+
*/
|
|
118
|
+
export function onBoxManifest(listener: (record: BoxRecord) => void | Promise<void>): () => void {
|
|
119
|
+
boxListeners.add(listener);
|
|
120
|
+
return () => void boxListeners.delete(listener);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const sandboxes = new Map<BoxSandboxName, Sandbox>();
|
|
124
|
+
|
|
125
|
+
/** The sandbox a request names: the one it holds, or the one the funnel keeps under its name. */
|
|
126
|
+
export function sandboxOf(named: BoxSandboxName | Sandbox): Sandbox {
|
|
127
|
+
if (typeof named !== "string") return named;
|
|
128
|
+
const name = named;
|
|
129
|
+
let found = sandboxes.get(name);
|
|
130
|
+
if (found === undefined) {
|
|
131
|
+
found = name === "srt" ? srt() : nono();
|
|
132
|
+
sandboxes.set(name, found);
|
|
133
|
+
}
|
|
134
|
+
return found;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Replaces the sandbox the funnel uses under a name, for a host that knows where its binary is. Returns the restore. */
|
|
138
|
+
export function useSandbox(name: BoxSandboxName, sandbox: Sandbox): () => void {
|
|
139
|
+
const before = sandboxes.get(name);
|
|
140
|
+
sandboxes.set(name, sandbox);
|
|
141
|
+
return () => {
|
|
142
|
+
if (before === undefined) sandboxes.delete(name);
|
|
143
|
+
else sandboxes.set(name, before);
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Refuses a start whose box cannot run here: `SandboxUnavailable`, before any process exists. */
|
|
148
|
+
export async function requireBox(box: BoxRequest | undefined): Promise<void> {
|
|
149
|
+
if (box !== undefined) await requireSandbox(sandboxOf(box.sandbox));
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function inherited(unset: readonly string[]): Record<string, string> {
|
|
153
|
+
const env: Record<string, string> = {};
|
|
154
|
+
for (const [name, value] of Object.entries(process.env)) {
|
|
155
|
+
if (value !== undefined && !unset.includes(name)) env[name] = value;
|
|
156
|
+
}
|
|
157
|
+
return env;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* The spec a box is given: the request's, with the environment of the launch. The environment is
|
|
162
|
+
* only what is listed: `HOME` and `PATH` so the harness can find itself, then the spec's own, then
|
|
163
|
+
* the session's additions.
|
|
164
|
+
*/
|
|
165
|
+
function boxedSpec(launch: AgentLaunch, box: BoxRequest): BoxSpec {
|
|
166
|
+
const given = boxSpec(box.spec);
|
|
167
|
+
return boxSpec({
|
|
168
|
+
...given,
|
|
169
|
+
cwd: launch.cwd ?? given.cwd,
|
|
170
|
+
env: { HOME: homedir(), PATH: process.env["PATH"] ?? "/usr/bin:/bin", ...given.env, ...launch.env },
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** How a boxed process ended, as it is told to those who listen. */
|
|
175
|
+
interface Outcome {
|
|
176
|
+
readonly code: number | null;
|
|
177
|
+
readonly signal: NodeJS.Signals | null;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
type EndListener = (code: number | null, signal: NodeJS.Signals | null) => void;
|
|
181
|
+
type Listener = Parameters<EventEmitter["on"]>[1];
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* The process of a boxed launch, in the shape of a child process: streams, an exit, a kill.
|
|
185
|
+
*
|
|
186
|
+
* The end of a box can come before the one who started it holds the process. Such a late listener
|
|
187
|
+
* for `exit`, `close` or the `error` of a failed clean-up is told what happened, as soon as it is registered, rather than waiting for an
|
|
188
|
+
* event that will not come again.
|
|
189
|
+
*/
|
|
190
|
+
class BoxedProcess extends EventEmitter implements AgentProcess {
|
|
191
|
+
readonly stdin = new PassThrough();
|
|
192
|
+
readonly stdout = new PassThrough();
|
|
193
|
+
readonly stderr = new PassThrough();
|
|
194
|
+
exitCode: number | null = null;
|
|
195
|
+
signalCode: NodeJS.Signals | null = null;
|
|
196
|
+
killed = false;
|
|
197
|
+
#box: LaunchedBox | undefined;
|
|
198
|
+
/** A signal sent before the box was there: it is delivered the moment the box is. */
|
|
199
|
+
#unsent: NodeJS.Signals | number | undefined;
|
|
200
|
+
#exited: Outcome | undefined;
|
|
201
|
+
#closed: Outcome | undefined;
|
|
202
|
+
#failure: Error | undefined;
|
|
203
|
+
|
|
204
|
+
get pid(): number | undefined {
|
|
205
|
+
return this.#box?.pid;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
kill(signal?: NodeJS.Signals | number): boolean {
|
|
209
|
+
this.killed = true;
|
|
210
|
+
if (this.#box === undefined) this.#unsent = signal ?? "SIGTERM";
|
|
211
|
+
else this.#box.kill(signal);
|
|
212
|
+
return true;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
override on(event: "close" | "exit", listener: EndListener): this;
|
|
216
|
+
override on(event: "error", listener: (error: Error) => void): this;
|
|
217
|
+
override on(event: string | symbol, listener: Listener): this;
|
|
218
|
+
override on(event: string | symbol, listener: Listener): this {
|
|
219
|
+
return this.#told(event, listener) ? this : super.on(event, listener);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
override once(event: "close" | "exit", listener: EndListener): this;
|
|
223
|
+
override once(event: "error", listener: (error: Error) => void): this;
|
|
224
|
+
override once(event: string | symbol, listener: Listener): this;
|
|
225
|
+
override once(event: string | symbol, listener: Listener): this {
|
|
226
|
+
return this.#told(event, listener) ? this : super.once(event, listener);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** Tells a listener of an end that has happened already; false when the end is still to come. */
|
|
230
|
+
#told(event: string | symbol, listener: Listener): boolean {
|
|
231
|
+
const failure = this.#failure;
|
|
232
|
+
if (event === "error" && failure !== undefined) {
|
|
233
|
+
setImmediate(() => (listener as (error: Error) => void)(failure));
|
|
234
|
+
return true;
|
|
235
|
+
}
|
|
236
|
+
const outcome = event === "exit" ? this.#exited : event === "close" ? this.#closed : undefined;
|
|
237
|
+
if (outcome === undefined) return false;
|
|
238
|
+
setImmediate(() => (listener as EndListener)(outcome.code, outcome.signal));
|
|
239
|
+
return true;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
attach(box: LaunchedBox): void {
|
|
243
|
+
this.#box = box;
|
|
244
|
+
if (this.#unsent !== undefined) box.kill(this.#unsent);
|
|
245
|
+
this.stdin.on("data", (chunk: Buffer) => box.stdin.write(chunk));
|
|
246
|
+
this.stdin.on("end", () => box.stdin.end());
|
|
247
|
+
const drained = Promise.all([pump(box.stdout, this.stdout), pump(box.stderr, this.stderr)]).then(() => undefined, () => undefined);
|
|
248
|
+
void box.exited.then(
|
|
249
|
+
async (code) => this.#end(code, (await box.signaled) ?? null, undefined, drained),
|
|
250
|
+
(error: unknown) => this.#end(null, null, error, drained),
|
|
251
|
+
);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* The box is gone, by a code or by the signal that ended it. A clean-up that failed leaves the process ended without a code: the exit is
|
|
256
|
+
* told with `null`, and the failure goes to whoever listens for `error`. An error nobody is
|
|
257
|
+
* listening for is not thrown.
|
|
258
|
+
*/
|
|
259
|
+
async #end(code: number | null, signal: NodeJS.Signals | null, failure: unknown, drained: Promise<void>): Promise<void> {
|
|
260
|
+
// As a child process tells it: a process ended by a signal has no exit code, whatever status it left.
|
|
261
|
+
const outcome: Outcome = signal === null ? { code, signal } : { code: null, signal };
|
|
262
|
+
this.exitCode = outcome.code;
|
|
263
|
+
this.signalCode = outcome.signal;
|
|
264
|
+
this.#exited = outcome;
|
|
265
|
+
if (failure !== undefined) this.#failure = failure instanceof Error ? failure : new Error(String(failure));
|
|
266
|
+
this.emit("exit", outcome.code, outcome.signal);
|
|
267
|
+
if (this.#failure !== undefined && this.listenerCount("error") > 0) this.emit("error", this.#failure);
|
|
268
|
+
await drained;
|
|
269
|
+
this.#closed = outcome;
|
|
270
|
+
this.emit("close", outcome.code, outcome.signal);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** The launch failed after the process was handed out; whoever holds it hears of it once it can listen. */
|
|
274
|
+
fail(error: unknown): void {
|
|
275
|
+
const failure = error instanceof Error ? error : new Error(String(error));
|
|
276
|
+
// Kept before anyone is told, so a listener that comes later is told the same.
|
|
277
|
+
this.#failure = failure;
|
|
278
|
+
this.#closed = { code: null, signal: null };
|
|
279
|
+
this.stdout.end();
|
|
280
|
+
this.stderr.end();
|
|
281
|
+
setImmediate(() => {
|
|
282
|
+
if (this.listenerCount("error") > 0) this.emit("error", failure);
|
|
283
|
+
this.emit("close", null, null);
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** Resolves when the stream can take more, or can take nothing more. */
|
|
289
|
+
function drained(stream: PassThrough): Promise<void> {
|
|
290
|
+
// The reader that went away has no `drain` or `close` still to come.
|
|
291
|
+
if (stream.destroyed) return Promise.resolve();
|
|
292
|
+
return new Promise((resolve) => {
|
|
293
|
+
const done = () => {
|
|
294
|
+
stream.off("drain", done);
|
|
295
|
+
stream.off("close", done);
|
|
296
|
+
stream.off("error", done);
|
|
297
|
+
resolve();
|
|
298
|
+
};
|
|
299
|
+
stream.once("drain", done);
|
|
300
|
+
stream.once("close", done);
|
|
301
|
+
stream.once("error", done);
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/** Copies a box's output to a stream at the pace of its reader: nothing is read while the stream is full. */
|
|
306
|
+
async function pump(from: ReadableStream<Uint8Array>, to: PassThrough): Promise<void> {
|
|
307
|
+
const reader = from.getReader();
|
|
308
|
+
try {
|
|
309
|
+
for (;;) {
|
|
310
|
+
const { done, value } = await reader.read();
|
|
311
|
+
if (done) break;
|
|
312
|
+
if (to.destroyed) {
|
|
313
|
+
await reader.cancel();
|
|
314
|
+
break;
|
|
315
|
+
}
|
|
316
|
+
if (!to.write(value)) await drained(to);
|
|
317
|
+
if (to.destroyed) {
|
|
318
|
+
await reader.cancel();
|
|
319
|
+
break;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
} finally {
|
|
323
|
+
to.end();
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
function announce(launch: AgentLaunch, argv: readonly string[], sandbox: SandboxName | undefined): void {
|
|
328
|
+
const event: SpawnEvent = { harness: launch.harness, argv, cwd: launch.cwd, env: launch.env ?? {}, sandbox };
|
|
329
|
+
for (const listener of spawnListeners) listener(event);
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/** The spec with its environment, the manifest made from it, and the listeners told: all before anything starts. */
|
|
333
|
+
async function admitBox(launch: AgentLaunch, request: BoxRequest): Promise<{ sandbox: Sandbox; spec: BoxSpec }> {
|
|
334
|
+
const sandbox = sandboxOf(request.sandbox);
|
|
335
|
+
const spec = boxedSpec(launch, request);
|
|
336
|
+
const record: BoxRecord = {
|
|
337
|
+
harness: launch.harness,
|
|
338
|
+
...(request.mark === undefined ? {} : { mark: request.mark }),
|
|
339
|
+
sandbox: sandbox.name,
|
|
340
|
+
spec,
|
|
341
|
+
manifest: sandbox.manifest(spec),
|
|
342
|
+
};
|
|
343
|
+
for (const listener of boxListeners) await listener(record);
|
|
344
|
+
return { sandbox, spec };
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
function argvOf(launch: AgentLaunch): string[] {
|
|
348
|
+
return [launch.program, ...launch.args];
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
function spawnPlain(launch: AgentLaunch): PipedProcess {
|
|
352
|
+
announce(launch, argvOf(launch), undefined);
|
|
353
|
+
return spawn(launch.program, [...launch.args], {
|
|
354
|
+
cwd: launch.cwd,
|
|
355
|
+
env: { ...inherited(launch.unset ?? []), ...launch.env },
|
|
356
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
357
|
+
detached: launch.detached ?? false,
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/** A child process started with pipes. */
|
|
362
|
+
type PipedProcess = ChildProcessByStdio<Writable, Readable, Readable>;
|
|
363
|
+
|
|
364
|
+
/** The process once it is running, or the error that kept it from running: the program is not there, or may not be run. */
|
|
365
|
+
function spawned(child: PipedProcess): Promise<PipedProcess> {
|
|
366
|
+
return new Promise((resolve, reject) => {
|
|
367
|
+
child.once("spawn", () => {
|
|
368
|
+
child.off("error", reject);
|
|
369
|
+
resolve(child);
|
|
370
|
+
});
|
|
371
|
+
child.once("error", reject);
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/** The funnel: every agent process is started here. Any refusal is typed and comes before the process. */
|
|
376
|
+
export async function spawnAgent(launch: AgentLaunch): Promise<AgentProcess> {
|
|
377
|
+
if (launch.box === undefined) return await spawned(spawnPlain(launch));
|
|
378
|
+
await requireBox(launch.box);
|
|
379
|
+
const { sandbox, spec } = await admitBox(launch, launch.box);
|
|
380
|
+
announce(launch, argvOf(launch), sandbox.name);
|
|
381
|
+
const child = new BoxedProcess();
|
|
382
|
+
child.attach(await sandbox.launch(spec, argvOf(launch), { detached: launch.detached ?? false }));
|
|
383
|
+
return child;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/**
|
|
387
|
+
* Starts the process of a launch and returns it at once, for a host that must have it in hand
|
|
388
|
+
* synchronously: the Claude SDK's spawn hook. A boxed launch is admitted and launched behind the
|
|
389
|
+
* returned process, and a failure reaches it as an `error`; the caller has passed `requireBox`
|
|
390
|
+
* first, so the usual refusal is typed and came before.
|
|
391
|
+
*/
|
|
392
|
+
export function spawnAgentNow(launch: AgentLaunch): AgentProcess {
|
|
393
|
+
const request = launch.box;
|
|
394
|
+
if (request === undefined) return spawnPlain(launch);
|
|
395
|
+
const child = new BoxedProcess();
|
|
396
|
+
void admitBox(launch, request)
|
|
397
|
+
.then(({ sandbox, spec }) => {
|
|
398
|
+
announce(launch, argvOf(launch), sandbox.name);
|
|
399
|
+
return sandbox.launch(spec, argvOf(launch), { detached: launch.detached ?? false });
|
|
400
|
+
})
|
|
401
|
+
.then((box) => child.attach(box), (error: unknown) => child.fail(error));
|
|
402
|
+
return child;
|
|
403
|
+
}
|