@capybara-hq/device 0.1.0-rc.0 → 0.1.0-rc.10
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 +187 -44
- package/dist/api.d.ts +6 -1
- package/dist/args.d.ts +14 -3
- package/dist/args.js +74 -10
- package/dist/cli.d.ts +14 -2
- package/dist/cli.js +59 -10
- package/dist/client.d.ts +14 -3
- package/dist/client.js +92 -18
- package/dist/command-log.d.ts +8 -0
- package/dist/commands/drain.d.ts +13 -0
- package/dist/commands/drain.js +28 -0
- package/dist/commands/login.js +68 -11
- package/dist/commands/mode.d.ts +52 -0
- package/dist/commands/mode.js +108 -0
- package/dist/commands/policy.d.ts +13 -4
- package/dist/commands/policy.js +162 -33
- package/dist/commands/service.d.ts +18 -3
- package/dist/commands/service.js +175 -9
- package/dist/commands/start.d.ts +14 -3
- package/dist/commands/start.js +37 -5
- package/dist/commands/status.js +12 -4
- package/dist/commands/stop.d.ts +9 -2
- package/dist/commands/stop.js +13 -2
- package/dist/exec/docker.d.ts +41 -13
- package/dist/exec/docker.js +123 -57
- package/dist/exec/fs-helper.d.ts +13 -8
- package/dist/exec/fs-helper.js +31 -13
- package/dist/exec/groups.d.ts +42 -0
- package/dist/exec/groups.js +100 -0
- package/dist/exec/host.d.ts +53 -0
- package/dist/exec/host.js +183 -0
- package/dist/exec/os.d.ts +85 -15
- package/dist/exec/os.js +208 -36
- package/dist/exec/reap.d.ts +41 -0
- package/dist/exec/reap.js +89 -0
- package/dist/exec/sandbox-messages.d.ts +14 -0
- package/dist/exec/sandbox-messages.js +21 -0
- package/dist/exec/shared.d.ts +42 -13
- package/dist/exec/shared.js +94 -16
- package/dist/exec/switch.d.ts +91 -0
- package/dist/exec/switch.js +164 -0
- package/dist/exec/types.d.ts +28 -4
- package/dist/index.d.ts +1 -1
- package/dist/network.d.ts +45 -0
- package/dist/network.js +154 -0
- package/dist/pid.d.ts +13 -1
- package/dist/pid.js +54 -7
- package/dist/policy-ops.d.ts +47 -0
- package/dist/policy-ops.js +90 -0
- package/dist/policy-store.d.ts +43 -0
- package/dist/policy-store.js +94 -0
- package/dist/policy.d.ts +36 -16
- package/dist/policy.js +77 -19
- package/dist/public-suffix.d.ts +6 -0
- package/dist/public-suffix.js +79 -0
- package/dist/server-ops.d.ts +46 -7
- package/dist/server-ops.js +285 -29
- package/dist/service/installed.d.ts +5 -0
- package/dist/service/installed.js +14 -0
- package/dist/service/launchd.d.ts +11 -1
- package/dist/service/launchd.js +14 -5
- package/dist/state.d.ts +50 -6
- package/dist/state.js +195 -16
- package/package.json +3 -3
package/dist/exec/os.js
CHANGED
|
@@ -1,13 +1,17 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
2
|
import { createHash, randomBytes } from "node:crypto";
|
|
3
3
|
import { existsSync, realpathSync } from "node:fs";
|
|
4
|
-
import { constants as osConstants } from "node:os";
|
|
4
|
+
import { homedir, constants as osConstants } from "node:os";
|
|
5
5
|
import { resolve } from "node:path";
|
|
6
|
-
import { SandboxManager } from "@anthropic-ai/sandbox-runtime";
|
|
7
|
-
import {
|
|
6
|
+
import { SandboxManager, } from "@anthropic-ai/sandbox-runtime";
|
|
7
|
+
import { isBackgroundLaunch, } from "@capybara-hq/plugin-sdk";
|
|
8
|
+
import { blockedHosts, denyReason, networkTrailer } from "../network.js";
|
|
9
|
+
import { effectiveEgress, grantedHosts, srtConfig } from "../policy.js";
|
|
8
10
|
import { FS_HELPER_SCRIPT } from "./fs-helper.js";
|
|
9
11
|
import { EXEC_MARKER, killMarked } from "./procs.js";
|
|
10
|
-
import {
|
|
12
|
+
import { Reaper } from "./reap.js";
|
|
13
|
+
import { sandboxUnavailableMessage } from "./sandbox-messages.js";
|
|
14
|
+
import { ENV_NAME_RE, HostFiles, isUnder, OutputCap, osRoots, PIPE_GRACE_MS, policyError, RootGuard, shellQuote, toolHomeEnv, } from "./shared.js";
|
|
11
15
|
import { DeviceOpError } from "./types.js";
|
|
12
16
|
export { osRoots, ROOT_MARKER, utf8Prefix } from "./shared.js";
|
|
13
17
|
/** A file operation in the sandboxed helper that takes longer than this is killed. */
|
|
@@ -36,6 +40,8 @@ export function sandboxAvailability() {
|
|
|
36
40
|
}
|
|
37
41
|
return { ok: true };
|
|
38
42
|
}
|
|
43
|
+
/** How to fix an unavailable OS sandbox (shared by the command refusal and the mode switch). */
|
|
44
|
+
export { SANDBOX_INSTALL_HINT, sandboxUnavailableMessage, sandboxUnavailableSwitchRefusal, } from "./sandbox-messages.js";
|
|
39
45
|
/** Sends SIGKILL to a process group; false when the group no longer exists. */
|
|
40
46
|
function killGroupId(pgid, signal = "SIGKILL") {
|
|
41
47
|
try {
|
|
@@ -56,47 +62,117 @@ function pidAlive(pid) {
|
|
|
56
62
|
}
|
|
57
63
|
}
|
|
58
64
|
/**
|
|
59
|
-
* Runs every command inside `@anthropic-ai/sandbox-runtime` (macOS Seatbelt, Linux bubblewrap)
|
|
60
|
-
* writes only under the workspace and tmp roots, the secret
|
|
61
|
-
*
|
|
62
|
-
*
|
|
63
|
-
* {@link createOsExecutor}; the constructor alone
|
|
65
|
+
* Runs every command inside `@anthropic-ai/sandbox-runtime` (macOS Seatbelt, Linux bubblewrap),
|
|
66
|
+
* today's strict profile (spec §4.4): writes only under the workspace and tmp roots, the secret
|
|
67
|
+
* paths unreadable, no local binding or unix sockets, network only to the intersection of the
|
|
68
|
+
* device's allowlist and the kernel's. File operations in the workspace, tmp and skills roots run
|
|
69
|
+
* in a sandboxed helper too. Construct it with {@link createOsExecutor}; the constructor alone
|
|
70
|
+
* serves only `ensureRoot`.
|
|
64
71
|
*/
|
|
65
72
|
export class OsExecutor {
|
|
66
73
|
opts;
|
|
67
74
|
mode = "os";
|
|
68
75
|
roots;
|
|
69
76
|
dir;
|
|
70
|
-
/** Marks every process of this
|
|
77
|
+
/** Marks every process of this device's commands: `<dirKey>.<tag>.<exec id>`. */
|
|
71
78
|
dirKey;
|
|
72
79
|
groups = new Set();
|
|
73
80
|
pruneTimer;
|
|
81
|
+
/** Kills what a foreground exec left running once it ends. */
|
|
82
|
+
reaper;
|
|
74
83
|
guard;
|
|
75
84
|
files;
|
|
76
|
-
|
|
85
|
+
/**
|
|
86
|
+
* The network limits of the latest command. The ask callback has no command id; a device belongs
|
|
87
|
+
* to one organization, so these stand for its allowlist when it explains a refusal.
|
|
88
|
+
*/
|
|
89
|
+
lastLimits;
|
|
90
|
+
/** The configuration the sandbox runs with now, as JSON (see {@link applyConfig}). */
|
|
91
|
+
installed;
|
|
92
|
+
/**
|
|
93
|
+
* Background tasks launched on macOS that still run, by the command id of their launch, with
|
|
94
|
+
* the task's process group id (its sid). A task keeps its launch's network permissions (the
|
|
95
|
+
* per-command list) until its group is gone: it uses the launch's proxy credentials long after
|
|
96
|
+
* the launch returned. Checked on the prune tick.
|
|
97
|
+
*/
|
|
98
|
+
backgroundNet = new Map();
|
|
99
|
+
/** Whether the OS sandbox can run here; false means sandbox-mode operations are refused. */
|
|
100
|
+
available;
|
|
101
|
+
/** Why the OS sandbox is unavailable (when {@link available} is false). */
|
|
102
|
+
unavailableReason;
|
|
103
|
+
constructor(opts, state = {}) {
|
|
77
104
|
this.opts = opts;
|
|
105
|
+
this.available = state.unavailable === undefined;
|
|
106
|
+
this.unavailableReason = state.unavailable;
|
|
107
|
+
this.reaper = new Reaper(opts.reaper);
|
|
78
108
|
const dir = resolve(opts.dir);
|
|
79
109
|
// The roots are reported as real paths, so what commands print matches what the kernel sends.
|
|
80
110
|
this.dir = existsSync(dir) ? realpathSync(dir) : dir;
|
|
81
111
|
this.roots = osRoots(this.dir);
|
|
82
112
|
this.guard = new RootGuard(this.dir, this.roots);
|
|
83
|
-
this.files = new HostFiles(this.roots);
|
|
113
|
+
this.files = new HostFiles(this.roots, "sandbox");
|
|
84
114
|
this.dirKey = createHash("sha256").update(this.dir).digest("hex").slice(0, 16);
|
|
85
115
|
}
|
|
86
|
-
/**
|
|
116
|
+
/** Throws the actionable refusal when the OS sandbox is unavailable. */
|
|
117
|
+
requireSandbox() {
|
|
118
|
+
if (!this.available) {
|
|
119
|
+
throw new DeviceOpError("error", sandboxUnavailableMessage(this.unavailableReason ?? ""));
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
/** The sandbox configuration (no domains: those are per command). */
|
|
87
123
|
config() {
|
|
88
|
-
return srtConfig(this.
|
|
124
|
+
return srtConfig(this.roots, [], {
|
|
89
125
|
...(this.opts.home !== undefined && { home: this.opts.home }),
|
|
90
126
|
...(this.opts.denyRead !== undefined && { denyRead: this.opts.denyRead }),
|
|
91
127
|
});
|
|
92
128
|
}
|
|
129
|
+
/**
|
|
130
|
+
* Installs {@link config} when it changed, so a policy change applies at the next command
|
|
131
|
+
* without a restart. The runtime reads its global configuration at each wrap.
|
|
132
|
+
*/
|
|
133
|
+
applyConfig() {
|
|
134
|
+
const config = this.config();
|
|
135
|
+
const json = JSON.stringify(config);
|
|
136
|
+
if (json === this.installed)
|
|
137
|
+
return;
|
|
138
|
+
if (this.installed !== undefined)
|
|
139
|
+
SandboxManager.updateConfig(config);
|
|
140
|
+
this.installed = json;
|
|
141
|
+
}
|
|
142
|
+
/** Records the configuration the sandbox was initialized with. */
|
|
143
|
+
markInstalled(config) {
|
|
144
|
+
this.installed = JSON.stringify(config);
|
|
145
|
+
}
|
|
93
146
|
async ensureRoot() {
|
|
94
147
|
return this.guard.ensure();
|
|
95
148
|
}
|
|
96
|
-
/**
|
|
149
|
+
/**
|
|
150
|
+
* The sandbox's ask callback, reached only for a host no list allows: it refuses, with a reason
|
|
151
|
+
* clients that print the proxy's status phrase show (spec §9.1). Sandbox mode has no
|
|
152
|
+
* "any host" state (auto mode runs without the OS sandbox and has the machine's network), so
|
|
153
|
+
* this never allows.
|
|
154
|
+
*/
|
|
155
|
+
askCallback = async ({ host }) => {
|
|
156
|
+
return { allow: false, reason: denyReason(host, this.lastLimits, this.opts.policy()) };
|
|
157
|
+
};
|
|
158
|
+
/** The classified network refusals of one command (read before it unregisters). */
|
|
159
|
+
blockedFor(commandId, limits, policy) {
|
|
160
|
+
const lines = SandboxManager.getSandboxViolationStore()
|
|
161
|
+
.getViolationsForCommand(commandId)
|
|
162
|
+
.map((v) => v.line);
|
|
163
|
+
return blockedHosts(lines, limits, policy);
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* The marker value of a tag's processes. An exec's processes carry `<this>.<exec id>` (see
|
|
167
|
+
* {@link execMarker}); {@link killTagged} matches both.
|
|
168
|
+
*/
|
|
97
169
|
markerOf(tag) {
|
|
98
170
|
return `${this.dirKey}.${tag}`;
|
|
99
171
|
}
|
|
172
|
+
/** The marker value of one exec's processes: its tag's plus an id of its own (no dots in a tag). */
|
|
173
|
+
execMarker(tag) {
|
|
174
|
+
return `${this.markerOf(tag)}.${randomBytes(8).toString("hex")}`;
|
|
175
|
+
}
|
|
100
176
|
/**
|
|
101
177
|
* Wraps `script` (run by bash inside the sandbox, after the request's `env` and TMPDIR are
|
|
102
178
|
* exported) and spawns it as the leader of a new process group.
|
|
@@ -111,16 +187,20 @@ export class OsExecutor {
|
|
|
111
187
|
TERM: "dumb",
|
|
112
188
|
HOME: this.roots.workspace,
|
|
113
189
|
...(process.env.USER !== undefined && { USER: process.env.USER }),
|
|
190
|
+
// Version managers (asdf, nvm, pyenv, ...) read their data under the real home: HOME is the
|
|
191
|
+
// workspace here. Read only; the request's values win.
|
|
192
|
+
...toolHomeEnv(this.opts.home ?? homedir()),
|
|
114
193
|
...o.env,
|
|
115
|
-
// The runtime points TMPDIR at its own /tmp/claude (denied by the config): use
|
|
194
|
+
// The runtime points TMPDIR at its own /tmp/claude (denied by the config): use ours.
|
|
116
195
|
TMPDIR: this.roots.tmp,
|
|
117
|
-
[EXEC_MARKER]:
|
|
196
|
+
[EXEC_MARKER]: o.marker,
|
|
118
197
|
};
|
|
119
198
|
for (const [k, v] of Object.entries(inner)) {
|
|
120
199
|
if (!ENV_NAME_RE.test(k))
|
|
121
200
|
throw policyError(`invalid environment variable name ${JSON.stringify(k)}`);
|
|
122
201
|
exports.push(`export ${k}=${shellQuote(v)}`);
|
|
123
202
|
}
|
|
203
|
+
this.applyConfig();
|
|
124
204
|
const commandId = randomBytes(16).toString("base64url");
|
|
125
205
|
const wrapped = await SandboxManager.wrapWithSandbox(`${exports.join("\n")}\n${script}`, "/bin/bash", undefined, o.signal, { commandId, commandText: script });
|
|
126
206
|
// The kernel may have cancelled while the wrap was prepared.
|
|
@@ -145,16 +225,40 @@ export class OsExecutor {
|
|
|
145
225
|
}
|
|
146
226
|
return { child, commandId };
|
|
147
227
|
}
|
|
228
|
+
/** Drops a command's network permissions (its per-command list). */
|
|
229
|
+
releaseNet(commandId) {
|
|
230
|
+
this.backgroundNet.delete(commandId);
|
|
231
|
+
SandboxManager.unregisterCommandNetworkLists(commandId);
|
|
232
|
+
}
|
|
233
|
+
/** Keeps a launched background task's network permissions while its group `sid` lives. */
|
|
234
|
+
keepBackgroundNet(commandId, sid) {
|
|
235
|
+
if (!killGroupId(sid, 0)) {
|
|
236
|
+
this.releaseNet(commandId);
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
this.backgroundNet.set(commandId, sid);
|
|
240
|
+
this.startPruning();
|
|
241
|
+
}
|
|
242
|
+
/** Releases the network permissions of background tasks whose group is gone (all: `all`). */
|
|
243
|
+
pruneBackgroundNet(all = false) {
|
|
244
|
+
for (const [commandId, sid] of [...this.backgroundNet]) {
|
|
245
|
+
if (all || !killGroupId(sid, 0))
|
|
246
|
+
this.releaseNet(commandId);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
startPruning() {
|
|
250
|
+
if (this.pruneTimer === undefined) {
|
|
251
|
+
this.pruneTimer = setInterval(() => this.prune(), PRUNE_INTERVAL_MS);
|
|
252
|
+
this.pruneTimer.unref();
|
|
253
|
+
}
|
|
254
|
+
}
|
|
148
255
|
/** Tracks a spawned command's process group; returns the entry. */
|
|
149
256
|
track(tag, child) {
|
|
150
257
|
if (child.pid === undefined)
|
|
151
258
|
return undefined;
|
|
152
259
|
const g = { tag, pgid: child.pid, exited: false };
|
|
153
260
|
this.groups.add(g);
|
|
154
|
-
|
|
155
|
-
this.pruneTimer = setInterval(() => this.prune(), PRUNE_INTERVAL_MS);
|
|
156
|
-
this.pruneTimer.unref();
|
|
157
|
-
}
|
|
261
|
+
this.startPruning();
|
|
158
262
|
return g;
|
|
159
263
|
}
|
|
160
264
|
/** Forgets finished groups with no members left (or whose id was taken by another process). */
|
|
@@ -167,7 +271,8 @@ export class OsExecutor {
|
|
|
167
271
|
if (pidAlive(g.pgid) || !killGroupId(g.pgid, 0))
|
|
168
272
|
this.groups.delete(g);
|
|
169
273
|
}
|
|
170
|
-
|
|
274
|
+
this.pruneBackgroundNet();
|
|
275
|
+
if (this.groups.size === 0 && this.backgroundNet.size === 0 && this.pruneTimer !== undefined) {
|
|
171
276
|
clearInterval(this.pruneTimer);
|
|
172
277
|
this.pruneTimer = undefined;
|
|
173
278
|
}
|
|
@@ -184,12 +289,25 @@ export class OsExecutor {
|
|
|
184
289
|
}
|
|
185
290
|
async exec(args, signal) {
|
|
186
291
|
signal.throwIfAborted();
|
|
292
|
+
this.requireSandbox();
|
|
187
293
|
const cwd = await this.files.inside(args.cwd ?? this.roots.workspace, "cwd");
|
|
294
|
+
// Read once: the command's lists and the explanation of its refusals use the same policy.
|
|
295
|
+
const policy = this.opts.policy();
|
|
296
|
+
this.lastLimits = args.limits;
|
|
297
|
+
// A granted host the command still could not reach is not the device's doing.
|
|
298
|
+
const judged = {
|
|
299
|
+
...policy,
|
|
300
|
+
allowedDomains: [...policy.allowedDomains, ...grantedHosts(args.limits, args.grants)],
|
|
301
|
+
};
|
|
302
|
+
const egress = effectiveEgress(policy, args.limits, args.grants);
|
|
303
|
+
const marker = this.execMarker(args.tag);
|
|
304
|
+
// A background task launch detaches the task on purpose: what it leaves running stays.
|
|
305
|
+
const reap = !isBackgroundLaunch(args.command);
|
|
188
306
|
const { child, commandId } = await this.spawnSandboxed(args.command, {
|
|
189
307
|
cwd,
|
|
190
308
|
...(args.env !== undefined && { env: args.env }),
|
|
191
|
-
|
|
192
|
-
egress
|
|
309
|
+
marker,
|
|
310
|
+
egress,
|
|
193
311
|
signal,
|
|
194
312
|
});
|
|
195
313
|
return new Promise((resolvePromise, reject) => {
|
|
@@ -218,7 +336,7 @@ export class OsExecutor {
|
|
|
218
336
|
}, args.timeoutMs);
|
|
219
337
|
const onAbort = () => kill();
|
|
220
338
|
signal.addEventListener("abort", onAbort, { once: true });
|
|
221
|
-
const cleanup = () => {
|
|
339
|
+
const cleanup = (keepFor) => {
|
|
222
340
|
clearTimeout(timer);
|
|
223
341
|
if (grace)
|
|
224
342
|
clearTimeout(grace);
|
|
@@ -227,14 +345,28 @@ export class OsExecutor {
|
|
|
227
345
|
group.exited = true;
|
|
228
346
|
group.onKill = undefined;
|
|
229
347
|
}
|
|
230
|
-
|
|
348
|
+
if (keepFor !== undefined)
|
|
349
|
+
this.keepBackgroundNet(commandId, keepFor);
|
|
350
|
+
else
|
|
351
|
+
this.releaseNet(commandId);
|
|
231
352
|
SandboxManager.cleanupAfterCommand();
|
|
232
353
|
};
|
|
233
354
|
const finish = () => {
|
|
234
355
|
if (settled || exit === undefined)
|
|
235
356
|
return;
|
|
236
357
|
settled = true;
|
|
237
|
-
cleanup
|
|
358
|
+
// Before cleanup: the violations are looked up by the command's id.
|
|
359
|
+
let blocked = [];
|
|
360
|
+
try {
|
|
361
|
+
blocked = this.blockedFor(commandId, args.limits, judged);
|
|
362
|
+
}
|
|
363
|
+
catch {
|
|
364
|
+
// The explanation is best effort: the command's result always comes back.
|
|
365
|
+
}
|
|
366
|
+
const trailer = networkTrailer(blocked);
|
|
367
|
+
cleanup(reap || killed || timedOut || exit.code !== 0
|
|
368
|
+
? undefined
|
|
369
|
+
: launchedGroup(cap.text("stdout")));
|
|
238
370
|
child.stdout?.destroy();
|
|
239
371
|
child.stderr?.destroy();
|
|
240
372
|
let exitCode = exit.code;
|
|
@@ -243,12 +375,17 @@ export class OsExecutor {
|
|
|
243
375
|
else if (exitCode === null && exit.sig !== null) {
|
|
244
376
|
exitCode = 128 + (osConstants.signals[exit.sig] ?? 0);
|
|
245
377
|
}
|
|
378
|
+
let stderr = cap.text("stderr");
|
|
379
|
+
if (trailer !== "") {
|
|
380
|
+
stderr += `${stderr === "" || stderr.endsWith("\n") ? "" : "\n"}${trailer}`;
|
|
381
|
+
}
|
|
246
382
|
resolvePromise({
|
|
247
383
|
exitCode,
|
|
248
384
|
stdout: cap.text("stdout"),
|
|
249
|
-
stderr
|
|
385
|
+
stderr,
|
|
250
386
|
truncated: cap.truncated,
|
|
251
387
|
timedOut,
|
|
388
|
+
...(blocked.length > 0 && { network: { blocked } }),
|
|
252
389
|
});
|
|
253
390
|
};
|
|
254
391
|
child.stdout?.on("data", (b) => cap.push("stdout", b));
|
|
@@ -266,6 +403,11 @@ export class OsExecutor {
|
|
|
266
403
|
exit = { code, sig };
|
|
267
404
|
if (group)
|
|
268
405
|
group.exited = true;
|
|
406
|
+
// The call is over (exit, timeout or abort): nothing it started may outlive it, because no
|
|
407
|
+
// later command can stop it (the sandbox lets no command signal another's processes).
|
|
408
|
+
// Its group goes before the result; processes that left the group soon after.
|
|
409
|
+
if (group && reap)
|
|
410
|
+
void this.reaper.reap(group.pgid, marker);
|
|
269
411
|
// A background child may hold the pipes open; do not wait for it past a short grace.
|
|
270
412
|
grace = setTimeout(finish, PIPE_GRACE_MS);
|
|
271
413
|
});
|
|
@@ -278,6 +420,7 @@ export class OsExecutor {
|
|
|
278
420
|
process.execPath,
|
|
279
421
|
"-e",
|
|
280
422
|
FS_HELPER_SCRIPT,
|
|
423
|
+
"sandbox",
|
|
281
424
|
op,
|
|
282
425
|
path,
|
|
283
426
|
String(maxBytes),
|
|
@@ -288,7 +431,7 @@ export class OsExecutor {
|
|
|
288
431
|
.join(" ");
|
|
289
432
|
const { child, commandId } = await this.spawnSandboxed(script, {
|
|
290
433
|
cwd: this.roots.workspace,
|
|
291
|
-
|
|
434
|
+
marker: this.markerOf("fs-helper"),
|
|
292
435
|
egress: [],
|
|
293
436
|
stdin: data !== undefined,
|
|
294
437
|
});
|
|
@@ -335,6 +478,7 @@ export class OsExecutor {
|
|
|
335
478
|
return res.r ?? null;
|
|
336
479
|
}
|
|
337
480
|
async readFile(path, maxBytes) {
|
|
481
|
+
this.requireSandbox();
|
|
338
482
|
const p = this.files.lexical(path);
|
|
339
483
|
if (isUnder(p, this.roots.skills))
|
|
340
484
|
return this.files.read(path, maxBytes);
|
|
@@ -342,12 +486,14 @@ export class OsExecutor {
|
|
|
342
486
|
return r === null ? null : { data: Buffer.from(r.b64, "base64"), truncated: r.truncated };
|
|
343
487
|
}
|
|
344
488
|
async writeFile(path, data) {
|
|
489
|
+
this.requireSandbox();
|
|
345
490
|
const p = this.files.lexical(path);
|
|
346
491
|
if (isUnder(p, this.roots.skills))
|
|
347
492
|
return this.files.write(path, data);
|
|
348
493
|
await this.helper("write", p, 0, data);
|
|
349
494
|
}
|
|
350
495
|
async stat(path) {
|
|
496
|
+
this.requireSandbox();
|
|
351
497
|
const p = this.files.lexical(path);
|
|
352
498
|
if (isUnder(p, this.roots.skills)) {
|
|
353
499
|
return this.files.stat(path);
|
|
@@ -360,14 +506,20 @@ export class OsExecutor {
|
|
|
360
506
|
if (want.has(g.tag))
|
|
361
507
|
this.killGroup(g);
|
|
362
508
|
const values = new Set(tags.map((t) => this.markerOf(t)));
|
|
363
|
-
|
|
509
|
+
// `<dirKey>.<tag>` or an exec's `<dirKey>.<tag>.<id>`: a tag has no dot, so `ab` never
|
|
510
|
+
// matches `ab-cd`'s processes.
|
|
511
|
+
await killMarked((v) => {
|
|
512
|
+
const dot = v.indexOf(".", this.dirKey.length + 1);
|
|
513
|
+
return values.has(dot < 0 ? v : v.slice(0, dot));
|
|
514
|
+
});
|
|
364
515
|
}
|
|
365
516
|
async killAll() {
|
|
366
517
|
for (const g of [...this.groups])
|
|
367
518
|
this.killGroup(g);
|
|
368
519
|
await this.killLeftovers();
|
|
520
|
+
this.pruneBackgroundNet(true);
|
|
369
521
|
}
|
|
370
|
-
/** Kills every process carrying this
|
|
522
|
+
/** Kills every process carrying this device's marker (also a previous run's). */
|
|
371
523
|
async killLeftovers() {
|
|
372
524
|
const prefix = `${this.dirKey}.`;
|
|
373
525
|
await killMarked((v) => v.startsWith(prefix));
|
|
@@ -378,21 +530,41 @@ export class OsExecutor {
|
|
|
378
530
|
if (this.pruneTimer !== undefined)
|
|
379
531
|
clearInterval(this.pruneTimer);
|
|
380
532
|
this.pruneTimer = undefined;
|
|
381
|
-
|
|
533
|
+
if (this.available)
|
|
534
|
+
await SandboxManager.reset();
|
|
382
535
|
}
|
|
383
536
|
}
|
|
537
|
+
/**
|
|
538
|
+
* The process group id a background task launch printed as its last line (the task's sid), on
|
|
539
|
+
* macOS only: there the sandbox shares the host's process ids, so the device can watch the group.
|
|
540
|
+
* Elsewhere (Linux: bwrap's own pid namespace) undefined, and the launch's permissions end with it.
|
|
541
|
+
*/
|
|
542
|
+
export function launchedGroup(stdout, platform = process.platform) {
|
|
543
|
+
if (platform !== "darwin")
|
|
544
|
+
return undefined;
|
|
545
|
+
const last = stdout.trimEnd().split("\n").pop()?.trim() ?? "";
|
|
546
|
+
return /^[1-9][0-9]*$/.test(last) ? Number(last) : undefined;
|
|
547
|
+
}
|
|
384
548
|
/**
|
|
385
549
|
* The OS sandbox executor: checks the platform and dependencies, starts the sandbox's proxies
|
|
386
|
-
* once for this process, and kills what a previous run of this
|
|
550
|
+
* once for this process, and kills what a previous run of this device left running.
|
|
387
551
|
* Network is denied unless a command's own list allows it.
|
|
552
|
+
*
|
|
553
|
+
* When the OS sandbox is unavailable (an unsupported platform or missing dependencies) this still
|
|
554
|
+
* returns an executor, marked unavailable, so `start` keeps serving: auto mode works, and every
|
|
555
|
+
* sandbox-mode command or file operation is refused with the actionable reason
|
|
556
|
+
* ({@link sandboxUnavailableMessage}) instead of running unsandboxed or stopping the device.
|
|
388
557
|
*/
|
|
389
558
|
export async function createOsExecutor(opts) {
|
|
390
559
|
const available = sandboxAvailability();
|
|
391
560
|
if (!available.ok)
|
|
392
|
-
|
|
561
|
+
return new OsExecutor(opts, { unavailable: available.reason });
|
|
393
562
|
const executor = new OsExecutor(opts);
|
|
394
|
-
//
|
|
395
|
-
|
|
563
|
+
// The ask callback never allows: a destination outside the lists is refused, with a reason
|
|
564
|
+
// when this runtime carries one (an older runtime would read any answer object as an allow).
|
|
565
|
+
const config = executor.config();
|
|
566
|
+
await SandboxManager.initialize(config, SandboxManager.askCallbackDenyReason === true ? executor.askCallback : undefined);
|
|
567
|
+
executor.markInstalled(config);
|
|
396
568
|
await executor.killLeftovers();
|
|
397
569
|
return executor;
|
|
398
570
|
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/** The most scans one batch of reaps makes while it still finds processes. */
|
|
2
|
+
export declare const REAP_ROUNDS = 3;
|
|
3
|
+
export interface ReaperDeps {
|
|
4
|
+
/** SIGKILLs a process group; false when it no longer exists. */
|
|
5
|
+
killGroup: (pgid: number) => boolean;
|
|
6
|
+
/** The pids of this user's processes whose marker value `match` accepts (see `procs.ts`). */
|
|
7
|
+
findMarked: (match: (value: string) => boolean) => Promise<number[]>;
|
|
8
|
+
/** SIGKILLs one process and the process group it leads, if any. */
|
|
9
|
+
killPid: (pid: number) => void;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Kills what a foreground exec left running once it ended (normal exit, timeout or abort). Inside
|
|
13
|
+
* the OS sandbox a command can neither list nor signal the processes another command started, so
|
|
14
|
+
* a `sleep 300 &` or `nohup server &` left behind could otherwise be stopped by nobody.
|
|
15
|
+
*
|
|
16
|
+
* The exec's process group goes at once (a `&` or `nohup` child stays in it). A process that left
|
|
17
|
+
* the group (`setsid`, a detached spawn) is found by the exec's own marker value, which every
|
|
18
|
+
* process it starts inherits; listing processes is slow on macOS (`ps -E`), so that part runs
|
|
19
|
+
* after the result and reaps that arrive meanwhile share one scan. On macOS `ps -E` hides the
|
|
20
|
+
* environment of Apple platform binaries, so it is best effort there (the group covers the rest).
|
|
21
|
+
* Background task launches are not reaped at all (`isBackgroundLaunch`): they detach on purpose.
|
|
22
|
+
*/
|
|
23
|
+
export declare class Reaper {
|
|
24
|
+
private readonly deps;
|
|
25
|
+
/** Markers whose processes the next scan kills. */
|
|
26
|
+
private readonly pending;
|
|
27
|
+
/** The queued scan (not started yet), which every new reap joins. */
|
|
28
|
+
private next;
|
|
29
|
+
/** The scan in progress. */
|
|
30
|
+
private running;
|
|
31
|
+
constructor(deps?: Partial<ReaperDeps>);
|
|
32
|
+
/**
|
|
33
|
+
* SIGKILLs the process group `pgid` now and, soon after, every process carrying the marker
|
|
34
|
+
* value `marker` exactly (none when empty). Resolves once that scan is done; never rejects.
|
|
35
|
+
*/
|
|
36
|
+
reap(pgid: number, marker: string): Promise<void>;
|
|
37
|
+
private schedule;
|
|
38
|
+
/** Waits for the scan in progress, then scans every marker pending by then. */
|
|
39
|
+
private runQueued;
|
|
40
|
+
private scan;
|
|
41
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { killGroupId } from "./groups.js";
|
|
2
|
+
import { findMarked } from "./procs.js";
|
|
3
|
+
/** The most scans one batch of reaps makes while it still finds processes. */
|
|
4
|
+
export const REAP_ROUNDS = 3;
|
|
5
|
+
function killPid(pid) {
|
|
6
|
+
// A live process's pid is a group id only when it leads that group: then the group goes too.
|
|
7
|
+
killGroupId(pid);
|
|
8
|
+
try {
|
|
9
|
+
process.kill(pid, "SIGKILL");
|
|
10
|
+
}
|
|
11
|
+
catch {
|
|
12
|
+
// Already gone.
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
const DEFAULT_DEPS = { killGroup: (pgid) => killGroupId(pgid), findMarked, killPid };
|
|
16
|
+
/**
|
|
17
|
+
* Kills what a foreground exec left running once it ended (normal exit, timeout or abort). Inside
|
|
18
|
+
* the OS sandbox a command can neither list nor signal the processes another command started, so
|
|
19
|
+
* a `sleep 300 &` or `nohup server &` left behind could otherwise be stopped by nobody.
|
|
20
|
+
*
|
|
21
|
+
* The exec's process group goes at once (a `&` or `nohup` child stays in it). A process that left
|
|
22
|
+
* the group (`setsid`, a detached spawn) is found by the exec's own marker value, which every
|
|
23
|
+
* process it starts inherits; listing processes is slow on macOS (`ps -E`), so that part runs
|
|
24
|
+
* after the result and reaps that arrive meanwhile share one scan. On macOS `ps -E` hides the
|
|
25
|
+
* environment of Apple platform binaries, so it is best effort there (the group covers the rest).
|
|
26
|
+
* Background task launches are not reaped at all (`isBackgroundLaunch`): they detach on purpose.
|
|
27
|
+
*/
|
|
28
|
+
export class Reaper {
|
|
29
|
+
deps;
|
|
30
|
+
/** Markers whose processes the next scan kills. */
|
|
31
|
+
pending = new Set();
|
|
32
|
+
/** The queued scan (not started yet), which every new reap joins. */
|
|
33
|
+
next;
|
|
34
|
+
/** The scan in progress. */
|
|
35
|
+
running;
|
|
36
|
+
constructor(deps = {}) {
|
|
37
|
+
this.deps = { ...DEFAULT_DEPS, ...deps };
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* SIGKILLs the process group `pgid` now and, soon after, every process carrying the marker
|
|
41
|
+
* value `marker` exactly (none when empty). Resolves once that scan is done; never rejects.
|
|
42
|
+
*/
|
|
43
|
+
reap(pgid, marker) {
|
|
44
|
+
this.deps.killGroup(pgid);
|
|
45
|
+
if (marker === "")
|
|
46
|
+
return Promise.resolve();
|
|
47
|
+
this.pending.add(marker);
|
|
48
|
+
return this.schedule();
|
|
49
|
+
}
|
|
50
|
+
schedule() {
|
|
51
|
+
if (this.next !== undefined)
|
|
52
|
+
return this.next;
|
|
53
|
+
const queued = this.runQueued();
|
|
54
|
+
this.next = queued;
|
|
55
|
+
return queued;
|
|
56
|
+
}
|
|
57
|
+
/** Waits for the scan in progress, then scans every marker pending by then. */
|
|
58
|
+
async runQueued() {
|
|
59
|
+
// Always yields first, so `schedule` has set `this.next` before it is cleared here.
|
|
60
|
+
await (this.running ?? Promise.resolve()).catch(() => { });
|
|
61
|
+
this.next = undefined;
|
|
62
|
+
const markers = new Set(this.pending);
|
|
63
|
+
this.pending.clear();
|
|
64
|
+
const scan = this.scan(markers);
|
|
65
|
+
this.running = scan;
|
|
66
|
+
try {
|
|
67
|
+
await scan;
|
|
68
|
+
}
|
|
69
|
+
finally {
|
|
70
|
+
if (this.running === scan)
|
|
71
|
+
this.running = undefined;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
async scan(markers) {
|
|
75
|
+
for (let round = 0; round < REAP_ROUNDS; round++) {
|
|
76
|
+
let pids;
|
|
77
|
+
try {
|
|
78
|
+
pids = await this.deps.findMarked((v) => markers.has(v));
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
if (pids.length === 0)
|
|
84
|
+
return;
|
|
85
|
+
for (const pid of pids)
|
|
86
|
+
this.deps.killPid(pid);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The texts of an unavailable OS sandbox (spec 2026-11-14 direction): sandbox mode must refuse a
|
|
3
|
+
* command with a clear, actionable reason while auto mode keeps working. Pure strings, so the
|
|
4
|
+
* `mode` command can use them without loading the sandbox runtime.
|
|
5
|
+
*/
|
|
6
|
+
/** How to fix an unavailable OS sandbox (shared by the command refusal and the mode switch). */
|
|
7
|
+
export declare const SANDBOX_INSTALL_HINT = "install the sandbox dependencies (bubblewrap and socat on Linux) and restart capybara-device";
|
|
8
|
+
/**
|
|
9
|
+
* The refusal of every sandbox-mode operation when the OS sandbox is unavailable (device protocol
|
|
10
|
+
* error kind `error`): actionable, and never a silent fallback to running unsandboxed.
|
|
11
|
+
*/
|
|
12
|
+
export declare function sandboxUnavailableMessage(reason: string): string;
|
|
13
|
+
/** The refusal of `capybara-device mode sandbox` when the OS sandbox is unavailable. */
|
|
14
|
+
export declare function sandboxUnavailableSwitchRefusal(reason: string): string;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The texts of an unavailable OS sandbox (spec 2026-11-14 direction): sandbox mode must refuse a
|
|
3
|
+
* command with a clear, actionable reason while auto mode keeps working. Pure strings, so the
|
|
4
|
+
* `mode` command can use them without loading the sandbox runtime.
|
|
5
|
+
*/
|
|
6
|
+
/** How to fix an unavailable OS sandbox (shared by the command refusal and the mode switch). */
|
|
7
|
+
export const SANDBOX_INSTALL_HINT = "install the sandbox dependencies (bubblewrap and socat on Linux) and restart capybara-device";
|
|
8
|
+
/**
|
|
9
|
+
* The refusal of every sandbox-mode operation when the OS sandbox is unavailable (device protocol
|
|
10
|
+
* error kind `error`): actionable, and never a silent fallback to running unsandboxed.
|
|
11
|
+
*/
|
|
12
|
+
export function sandboxUnavailableMessage(reason) {
|
|
13
|
+
return (`The OS sandbox is unavailable on this machine (${reason}), so commands cannot run in sandbox ` +
|
|
14
|
+
"mode. Run `capybara-device mode auto` on this machine to use auto mode, or " +
|
|
15
|
+
`${SANDBOX_INSTALL_HINT}.`);
|
|
16
|
+
}
|
|
17
|
+
/** The refusal of `capybara-device mode sandbox` when the OS sandbox is unavailable. */
|
|
18
|
+
export function sandboxUnavailableSwitchRefusal(reason) {
|
|
19
|
+
return (`Nothing changed: the OS sandbox is unavailable on this machine (${reason}), so sandbox mode ` +
|
|
20
|
+
`could not run commands. Stay in auto mode, or ${SANDBOX_INSTALL_HINT} and try again.`);
|
|
21
|
+
}
|