@capybara-hq/device 0.1.0-rc.14 → 0.1.0-rc.16
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 +101 -157
- package/dist/api.d.ts +2 -2
- package/dist/args.d.ts +2 -8
- package/dist/args.js +2 -25
- package/dist/cli.d.ts +2 -11
- package/dist/cli.js +6 -61
- package/dist/client.d.ts +8 -45
- package/dist/client.js +25 -424
- package/dist/command-log.d.ts +14 -4
- package/dist/command-log.js +37 -1
- package/dist/commands/ceiling.d.ts +0 -2
- package/dist/commands/ceiling.js +3 -4
- package/dist/commands/login.d.ts +25 -1
- package/dist/commands/login.js +75 -61
- package/dist/commands/policy.d.ts +6 -8
- package/dist/commands/policy.js +30 -49
- package/dist/commands/start.d.ts +2 -17
- package/dist/commands/start.js +13 -53
- package/dist/exec/docker-operations.d.ts +2 -2
- package/dist/exec/docker-operations.js +4 -2
- package/dist/exec/docker.d.ts +37 -122
- package/dist/exec/docker.js +72 -717
- package/dist/exec/instance-binding.d.ts +4 -4
- package/dist/exec/linux-agent.js +30 -0
- package/dist/exec/linux-operation-backend.d.ts +5 -0
- package/dist/exec/linux-operation-backend.js +3 -1
- package/dist/exec/linux-operation-worker.d.ts +9 -0
- package/dist/exec/linux-operation-worker.js +11 -2
- package/dist/exec/mac-read-policy.d.ts +58 -0
- package/dist/exec/mac-read-policy.js +104 -0
- package/dist/exec/mac-self-check.d.ts +6 -3
- package/dist/exec/mac-self-check.js +28 -5
- package/dist/exec/operation-worker.d.ts +21 -2
- package/dist/exec/operation-worker.js +164 -43
- package/dist/exec/sandbox-check.d.ts +10 -0
- package/dist/exec/sandbox-check.js +18 -0
- package/dist/exec/sandbox-messages.d.ts +3 -11
- package/dist/exec/sandbox-messages.js +3 -18
- package/dist/exec/shared.d.ts +24 -47
- package/dist/exec/shared.js +53 -165
- package/dist/exec/types.d.ts +2 -66
- package/dist/exec/types.js +1 -1
- package/dist/node_modules/@anthropic-ai/sandbox-runtime/CAPYBARA-MODIFICATIONS.patch +71 -12
- package/dist/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/macos-sandbox-utils.js +18 -4
- package/dist/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/sandbox-config.js +6 -0
- package/dist/node_modules/@anthropic-ai/sandbox-runtime/dist/sandbox/sandbox-manager.js +4 -0
- package/dist/node_modules/@capybara-hq/plugin-sdk/agent-docs/concepts.md +9 -4
- package/dist/node_modules/@capybara-hq/plugin-sdk/agent-docs/extension-points/channel.md +1 -1
- package/dist/node_modules/@capybara-hq/plugin-sdk/agent-docs/extension-points/file-preview.md +2 -0
- package/dist/node_modules/@capybara-hq/plugin-sdk/agent-docs/extension-points/sandbox.md +1 -1
- package/dist/node_modules/@capybara-hq/plugin-sdk/agent-docs/plugin-format.md +1 -1
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/cards.d.ts +11 -0
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/cards.js +1 -1
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/channel.d.ts +37 -0
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/ctx.d.ts +47 -3
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/device-denied-paths.d.ts +14 -0
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/device-denied-paths.js +41 -0
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/device-protocol.d.ts +140 -20
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/device-protocol.js +419 -14
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/file-preview.d.ts +22 -5
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/hooks.d.ts +77 -13
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/http-access.d.ts +10 -0
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/index.d.ts +2 -2
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/index.js +2 -3
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/model.d.ts +89 -5
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/model.js +103 -0
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/permissions.d.ts +3 -2
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/permissions.js +2 -2
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/sandbox-operation.d.ts +4 -0
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/ui-parts.d.ts +1 -1
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/ui-parts.js +11 -0
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/ui.d.ts +25 -6
- package/dist/node_modules/@capybara-hq/plugin-sdk/package.json +1 -1
- package/dist/owner-report.d.ts +2 -2
- package/dist/owner-report.js +2 -2
- package/dist/policy-store.d.ts +6 -10
- package/dist/policy-store.js +9 -23
- package/dist/policy.d.ts +3 -32
- package/dist/policy.js +4 -74
- package/dist/runtime-manifest.json +1 -1
- package/dist/server-ops.d.ts +18 -46
- package/dist/server-ops.js +134 -269
- package/dist/staged-connect.js +44 -7
- package/dist/staged-device.d.ts +4 -4
- package/dist/staged-device.js +3 -0
- package/dist/staged-session.d.ts +5 -5
- package/dist/staged-session.js +4 -4
- package/dist/state.js +3 -2
- package/package.json +2 -2
- package/dist/commands/mode.d.ts +0 -69
- package/dist/commands/mode.js +0 -133
- package/dist/exec/fs-helper.d.ts +0 -21
- package/dist/exec/fs-helper.js +0 -171
- package/dist/exec/host.d.ts +0 -61
- package/dist/exec/host.js +0 -203
- package/dist/exec/listing.d.ts +0 -35
- package/dist/exec/listing.js +0 -157
- package/dist/exec/os.d.ts +0 -162
- package/dist/exec/os.js +0 -616
- package/dist/exec/procs.d.ts +0 -11
- package/dist/exec/procs.js +0 -67
- package/dist/exec/reap.d.ts +0 -41
- package/dist/exec/reap.js +0 -89
- package/dist/exec/switch.d.ts +0 -107
- package/dist/exec/switch.js +0 -204
- package/dist/network.d.ts +0 -45
- package/dist/network.js +0 -154
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/device-protocol-v3.d.ts +0 -117
- package/dist/node_modules/@capybara-hq/plugin-sdk/dist/device-protocol-v3.js +0 -409
|
@@ -1,14 +1,17 @@
|
|
|
1
1
|
import { fork, spawn, spawnSync } from "node:child_process";
|
|
2
2
|
import { randomUUID } from "node:crypto";
|
|
3
|
-
import { constants } from "node:fs";
|
|
4
|
-
import { open, realpath, stat } from "node:fs/promises";
|
|
5
|
-
import {
|
|
3
|
+
import { constants, realpathSync } from "node:fs";
|
|
4
|
+
import { mkdtemp, open, readdir, realpath, rm, stat } from "node:fs/promises";
|
|
5
|
+
import { homedir, tmpdir } from "node:os";
|
|
6
|
+
import { basename, dirname, join } from "node:path";
|
|
6
7
|
import { SANDBOX_GIT_DENIED_INTERNALS, SANDBOX_MANDATORY_WRITE_DENIES, SandboxPermissionUnsupportedError, SandboxScopeDeniedError, } from "@capybara-hq/plugin-sdk";
|
|
7
8
|
import { implicitWritePaths } from "../policy.js";
|
|
9
|
+
import { macReadAllows } from "./mac-read-policy.js";
|
|
8
10
|
import { macWriteRegexRules, macWriteRootSpellings } from "./mac-write-policy.js";
|
|
9
11
|
import { runNativeHelper, } from "./native-helper-client.js";
|
|
12
|
+
import { withCanonicalForms } from "./operation-types.js";
|
|
10
13
|
import { acquireSealedRuntime, stagePrivateSource, stageRuntimeSource, } from "./runtime-source.js";
|
|
11
|
-
import { ENV_NAME_RE, OutputCap, shellQuote } from "./shared.js";
|
|
14
|
+
import { ENV_NAME_RE, OutputCap, restrictedToolHomes, shellQuote } from "./shared.js";
|
|
12
15
|
/** Coalesce an active owned cancellation; a failed attempt never becomes a cached outcome. */
|
|
13
16
|
export function createCancellationAttempt(attempt) {
|
|
14
17
|
let pending;
|
|
@@ -51,7 +54,7 @@ export function mandatoryDenyPatterns(root) {
|
|
|
51
54
|
* `.git/modules`) under each write root, descriptor-relative and never following a link, after a
|
|
52
55
|
* restricted command ended. Anything not empty, missing or not a directory is left alone.
|
|
53
56
|
*/
|
|
54
|
-
const REMOVE_EMPTY_SEQUENCERS =
|
|
57
|
+
const REMOVE_EMPTY_SEQUENCERS = `
|
|
55
58
|
import json, os, stat, sys
|
|
56
59
|
FLAGS = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC
|
|
57
60
|
budget = [4000]
|
|
@@ -113,11 +116,21 @@ function removeEmptySequencers(roots, pythonPath, onDiagnostic) {
|
|
|
113
116
|
}
|
|
114
117
|
/** The JVM proxy agent the sandbox runtime points sandboxed JVMs at, inside its package. */
|
|
115
118
|
export const JAVA_PROXY_AGENT_JAR = "vendor/java-proxy-agent/srt-proxy-agent.jar";
|
|
116
|
-
/**
|
|
119
|
+
/**
|
|
120
|
+
* The fixed private worker bootstrap (a runtime-manifest helper entry). A kill (cancel, timeout,
|
|
121
|
+
* stop) first stops the launched command's descendant tree by parent pid (`stopTree`: top down,
|
|
122
|
+
* each process stopped before its children are read, so a pid is never reused under it), then
|
|
123
|
+
* kills that tree and the owned groups. Once the launched process has exited and its group is
|
|
124
|
+
* gone, `settle` closes the stdio pipes after a short bounded grace, so a process that escaped
|
|
125
|
+
* (one reparented to launchd before the walk) cannot hold the call or the worker open.
|
|
126
|
+
* Darwin answers a group signal with EPERM (not ESRCH) while the group holds only dead members
|
|
127
|
+
* (zombies not yet reaped, or processes exiting), so `signalGroup` counts EPERM as gone when a
|
|
128
|
+
* process snapshot shows no live member of the group; EPERM with a live member still fails.
|
|
129
|
+
*/
|
|
117
130
|
export const WORKER = `import {pathToFileURL} from 'node:url';
|
|
118
|
-
import {spawn} from 'node:child_process';
|
|
131
|
+
import {spawn,spawnSync} from 'node:child_process';
|
|
119
132
|
import {randomUUID} from 'node:crypto';
|
|
120
|
-
let manager,initialized=false,wrapped=false,closing=false,full=false,child,childClosed,timer,timedOut=false,killed=false;
|
|
133
|
+
let manager,initialized=false,wrapped=false,closing=false,full=false,child,childClosed,timer,timedOut=false,killed=false,exited=false,forced=false,settling=false,settleTimer;
|
|
121
134
|
const owned=new Map(),signaled=new Set();
|
|
122
135
|
let credit,sequence=0,outputFailed=false,outputDone=Promise.resolve();
|
|
123
136
|
async function collect(stream){
|
|
@@ -129,15 +142,50 @@ async function collect(stream){
|
|
|
129
142
|
send({event:'output-flow',frameBytes:data.length,bufferedBytes,producerLimit:262144});
|
|
130
143
|
await new Promise((resolve,reject)=>{credit={seq,resolve,reject};send({event:'output',stream:'stdout',seq,data:data.toString('base64')});});
|
|
131
144
|
}
|
|
132
|
-
}}catch(error){const alreadyFailed=outputFailed;outputFailed=true;stream.resume();if(!alreadyFailed)send({event:'error',message:'Managed producer failed'});}
|
|
145
|
+
}}catch(error){if(forced)return;const alreadyFailed=outputFailed;outputFailed=true;stream.resume();if(!alreadyFailed)send({event:'error',message:'Managed producer failed'});}
|
|
133
146
|
}
|
|
134
147
|
const send=value=>{if(process.connected)process.send(value,()=>{});};
|
|
135
|
-
function
|
|
148
|
+
function stopTree(){
|
|
149
|
+
if(!child?.pid||child.exitCode!==null||child.signalCode!==null)return [];
|
|
150
|
+
try{process.kill(child.pid,'SIGSTOP');}catch{return [];}
|
|
151
|
+
const tree=new Set([child.pid]);
|
|
152
|
+
for(let round=0;round<64;round++){
|
|
153
|
+
const ps=spawnSync('/bin/ps',['-axo','pid=,ppid='],{encoding:'utf8',timeout:5000});
|
|
154
|
+
if(ps.status!==0){send({event:'diagnostic',text:'Descendant snapshot failed'});break;}
|
|
155
|
+
const found=[];
|
|
156
|
+
for(const line of ps.stdout.split('\\n')){const [pid,ppid]=line.trim().split(/\\s+/).map(Number);if(pid>1&&tree.has(ppid)&&!tree.has(pid))found.push(pid);}
|
|
157
|
+
if(!found.length)break;
|
|
158
|
+
for(const pid of found)try{process.kill(pid,'SIGSTOP');tree.add(pid);}catch{}
|
|
159
|
+
}
|
|
160
|
+
return [...tree];
|
|
161
|
+
}
|
|
162
|
+
function deadGroup(pgid){
|
|
163
|
+
const ps=spawnSync('/bin/ps',['-axo','pgid=,stat='],{encoding:'utf8',timeout:5000});
|
|
164
|
+
if(ps.status!==0)return false;
|
|
165
|
+
for(const line of ps.stdout.split('\\n')){const [group,stat='']=line.trim().split(/\\s+/);if(Number(group)===pgid&&!stat.startsWith('Z')&&!stat.includes('E'))return false;}
|
|
166
|
+
return true;
|
|
167
|
+
}
|
|
168
|
+
function signalGroup(pgid,signal){try{process.kill(-pgid,signal);return true;}catch(error){if(error.code==='ESRCH'||(error.code==='EPERM'&&deadGroup(pgid)))return false;throw error;}}
|
|
169
|
+
function signalOwned(signal='SIGKILL'){if(signal==='SIGKILL')for(const pid of stopTree())try{process.kill(pid,'SIGKILL');}catch{}for(const pid of owned.keys()){if(signaled.has(pid))continue;if(!signalGroup(pid,signal)||signal==='SIGKILL')signaled.add(pid);}}
|
|
170
|
+
function settle(){
|
|
171
|
+
if(!child||settling||!exited||!(killed||timedOut||closing))return;settling=true;
|
|
172
|
+
const started=Date.now();let goneAt=0;
|
|
173
|
+
const tick=()=>{
|
|
174
|
+
let gone=false;try{gone=!signalGroup(child.pid,0);}catch{}
|
|
175
|
+
const now=Date.now();if(gone&&!goneAt)goneAt=now;
|
|
176
|
+
if((goneAt&&now-goneAt>=250)||now-started>=5000){
|
|
177
|
+
forced=true;if(credit){const pending=credit;credit=undefined;pending.reject(Error('Owned output closed after cancellation'));}
|
|
178
|
+
child.stdout.destroy();child.stderr.destroy();return;
|
|
179
|
+
}
|
|
180
|
+
settleTimer=setTimeout(tick,50);
|
|
181
|
+
};
|
|
182
|
+
settleTimer=setTimeout(tick,50);
|
|
183
|
+
}
|
|
136
184
|
async function stop(){
|
|
137
185
|
if(closing)return;closing=true;
|
|
138
186
|
if(credit){outputFailed=true;const pending=credit;credit=undefined;pending.reject(Error('Owned output channel closed'));child?.stdout.resume();}
|
|
139
187
|
try{signalOwned();}catch(error){closing=false;send({event:'error',message:'Owned cancellation remains pending: '+error.code});return;}
|
|
140
|
-
await childClosed;owned.clear();await manager?.reset();process.disconnect?.();
|
|
188
|
+
settle();await childClosed;owned.clear();await manager?.reset();process.disconnect?.();
|
|
141
189
|
}
|
|
142
190
|
process.on('disconnect',stop);process.on('SIGTERM',stop);
|
|
143
191
|
process.on('message',async message=>{try{
|
|
@@ -155,17 +203,17 @@ process.on('message',async message=>{try{
|
|
|
155
203
|
child=spawn('/bin/bash',['-c',message.script],{cwd:message.cwd,env:message.env,detached:true,stdio:['ignore','pipe','pipe']});
|
|
156
204
|
const identity={pid:child.pid,token:randomUUID()};if(!identity.pid)throw Error('Missing trusted launch identity');
|
|
157
205
|
owned.set(identity.pid,identity.token);
|
|
158
|
-
childClosed=new Promise(resolve=>child.once('close',async code=>{clearTimeout(timer);await outputDone;send({event:'completed',code,timedOut,killed,outputFailed});resolve();}));
|
|
206
|
+
childClosed=new Promise(resolve=>child.once('close',async code=>{clearTimeout(timer);clearTimeout(settleTimer);await outputDone;send({event:'completed',code,timedOut,killed,outputFailed});resolve();}));
|
|
159
207
|
child.once('error',error=>send({event:'error',message:String(error)}));
|
|
160
|
-
child.once('exit',code=>{send({event:'process-exit',code,timedOut,killed});try{signalOwned();}catch(error){send({event:'error',message:'Owned group cleanup pending: '+error.code});}});
|
|
208
|
+
child.once('exit',code=>{exited=true;send({event:'process-exit',code,timedOut,killed});try{signalOwned();}catch(error){send({event:'error',message:'Owned group cleanup pending: '+error.code});}settle();});
|
|
161
209
|
if(message.managed){
|
|
162
210
|
if(child.stdout.readableHighWaterMark>65536)throw Error('Unbounded managed producer buffer');
|
|
163
211
|
outputDone=collect(child.stdout);let diagnosticBytes=0;child.stderr.on('data',bytes=>{diagnosticBytes+=bytes.length;if(diagnosticBytes<=65536)send({event:'diagnostic',text:bytes.toString()});});
|
|
164
212
|
}else for(const stream of ['stdout','stderr'])child[stream].on('data',bytes=>{child[stream].pause();if(!process.connected){child[stream].resume();return;}process.send({event:'output',stream,data:bytes.toString('base64')},()=>child[stream].resume());});
|
|
165
|
-
timer=setTimeout(()=>{timedOut=true;try{signalOwned();}catch(error){send({event:'error',message:'Owned timeout cancellation pending: '+error.code});}},message.timeoutMs);
|
|
213
|
+
timer=setTimeout(()=>{timedOut=true;try{signalOwned();}catch(error){send({event:'error',message:'Owned timeout cancellation pending: '+error.code});}settle();},message.timeoutMs);
|
|
166
214
|
send({event:'launched',...identity});
|
|
167
215
|
}else if(message.type==='cancel'){
|
|
168
|
-
killed=true;try{if(message.graceMs>0&&child){signalOwned('SIGTERM');const force=setTimeout(()=>{try{signalOwned();}catch(error){send({event:'error',message:'Owned graceful cancellation pending: '+error.code});}},message.graceMs);childClosed.finally(()=>clearTimeout(force));}else signalOwned();send({event:'cancelled',ok:true});}catch(error){send({event:'cancelled',ok:false,message:'Owned cancellation pending: '+error.code});}
|
|
216
|
+
killed=true;try{if(message.graceMs>0&&child){signalOwned('SIGTERM');const force=setTimeout(()=>{try{signalOwned();}catch(error){send({event:'error',message:'Owned graceful cancellation pending: '+error.code});}},message.graceMs);childClosed.finally(()=>clearTimeout(force));}else signalOwned();send({event:'cancelled',ok:true});}catch(error){send({event:'cancelled',ok:false,message:'Owned cancellation pending: '+error.code});}settle();
|
|
169
217
|
}else if(message.type==='register'){
|
|
170
218
|
if(!Number.isSafeInteger(message.pid)||message.pid<=1||typeof message.token!=='string')throw Error('Invalid trusted launch identity');
|
|
171
219
|
owned.set(message.pid,message.token);send({event:'registered'});
|
|
@@ -214,18 +262,49 @@ function message(child, event) {
|
|
|
214
262
|
child.once("error", error);
|
|
215
263
|
});
|
|
216
264
|
}
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
265
|
+
let userTempDir = null;
|
|
266
|
+
/** The canonical `DARWIN_USER_TEMP_DIR` of this user, looked up once; undefined when unknown. */
|
|
267
|
+
function macUserTempDir() {
|
|
268
|
+
if (userTempDir !== null)
|
|
269
|
+
return userTempDir;
|
|
270
|
+
try {
|
|
271
|
+
const out = spawnSync("/usr/bin/getconf", ["DARWIN_USER_TEMP_DIR"], {
|
|
272
|
+
encoding: "utf8",
|
|
273
|
+
timeout: 5000,
|
|
274
|
+
});
|
|
275
|
+
const dir = out.status === 0 ? out.stdout.trim() : "";
|
|
276
|
+
userTempDir = dir ? realpathSync(dir) : undefined;
|
|
277
|
+
}
|
|
278
|
+
catch {
|
|
279
|
+
userTempDir = undefined;
|
|
280
|
+
}
|
|
281
|
+
return userTempDir;
|
|
282
|
+
}
|
|
283
|
+
const PRIVATE_TMP_PREFIX = "capybara-op-";
|
|
284
|
+
/**
|
|
285
|
+
* Removes the private temporary directories of device processes that are gone (named with the
|
|
286
|
+
* owning process id; this process removes its own when each operation ends). Best effort.
|
|
287
|
+
*/
|
|
288
|
+
async function sweepPrivateTemps(base) {
|
|
289
|
+
try {
|
|
290
|
+
for (const name of await readdir(base)) {
|
|
291
|
+
const pid = Number(/^capybara-op-(\d+)-[^/]+$/.exec(name)?.[1]);
|
|
292
|
+
if (!pid || pid === process.pid)
|
|
293
|
+
continue;
|
|
294
|
+
try {
|
|
295
|
+
process.kill(pid, 0);
|
|
296
|
+
continue;
|
|
297
|
+
}
|
|
298
|
+
catch (error) {
|
|
299
|
+
if (error.code !== "ESRCH")
|
|
300
|
+
continue;
|
|
301
|
+
}
|
|
302
|
+
await rm(join(base, name), { recursive: true, force: true });
|
|
226
303
|
}
|
|
227
304
|
}
|
|
228
|
-
|
|
305
|
+
catch {
|
|
306
|
+
// a failed sweep only leaves empty scratch directories behind
|
|
307
|
+
}
|
|
229
308
|
}
|
|
230
309
|
/** A separate process owns each immutable SRT manager; Full never enters that process. */
|
|
231
310
|
export async function startMacOperationWorker(request, signal) {
|
|
@@ -290,6 +369,7 @@ export async function startMacOperationWorker(request, signal) {
|
|
|
290
369
|
if (signal.aborted)
|
|
291
370
|
abort();
|
|
292
371
|
let sealed;
|
|
372
|
+
let privateTmp;
|
|
293
373
|
const completion = (async () => {
|
|
294
374
|
try {
|
|
295
375
|
// Restricted workers import only the sealed private copy of the verified runtime closure
|
|
@@ -339,6 +419,23 @@ export async function startMacOperationWorker(request, signal) {
|
|
|
339
419
|
roots.push({ path: canonical, fd: file.fd, access, components });
|
|
340
420
|
}
|
|
341
421
|
}
|
|
422
|
+
// Version managers (asdf, nvm, pyenv, ...) read their data under the real home, while HOME
|
|
423
|
+
// is the working directory: this trusted process has the real home and the device's own
|
|
424
|
+
// environment (the forked worker runs with a reduced one), so it picks the variables and
|
|
425
|
+
// grants their directories read only. Full access inherits this process's environment.
|
|
426
|
+
const toolHomes = request.kind === "exec" && !request.grant.full
|
|
427
|
+
? restrictedToolHomes(request.toolHome?.home ?? homedir(), request.toolHome?.env ?? process.env, request.grant.deniedReadRoots)
|
|
428
|
+
: undefined;
|
|
429
|
+
// A restricted command's own temporary directory (TMPDIR, TMP, TEMP): created empty for
|
|
430
|
+
// this operation alone, private (0700) under the user's temporary directory, writable and
|
|
431
|
+
// readable only inside the sandbox's grant, and removed once the operation's processes are
|
|
432
|
+
// gone (a crashed device leaves it behind: the next launch removes it). The runtime's default (`/tmp/claude`) is shared by every command, so it is denied
|
|
433
|
+
// (implicitWritePaths), and the user's temporary directory itself stays out of reach.
|
|
434
|
+
if (request.kind === "exec" && !request.grant.full) {
|
|
435
|
+
const base = macUserTempDir() ?? (await realpath(tmpdir()));
|
|
436
|
+
await sweepPrivateTemps(base);
|
|
437
|
+
privateTmp = await mkdtemp(join(base, `${PRIVATE_TMP_PREFIX}${process.pid}-`));
|
|
438
|
+
}
|
|
342
439
|
let wrap = async (script) => script;
|
|
343
440
|
{
|
|
344
441
|
const source = await stagePrivateSource(request.stateDir, "mac-worker.mjs", WORKER);
|
|
@@ -350,26 +447,36 @@ export async function startMacOperationWorker(request, signal) {
|
|
|
350
447
|
const runtimeRoots = roots.length
|
|
351
448
|
? roots.map((r) => r.path)
|
|
352
449
|
: [...request.grant.readRoots, ...request.grant.writeRoots];
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
450
|
+
// Every read is denied from `/` down; only the grant, the system roots, the staged
|
|
451
|
+
// helper and agent and the tool homes come back (mac-read-policy.ts). Ancestors get no
|
|
452
|
+
// read rule: directory metadata is all traversal needs, and a subtree rule on one would
|
|
453
|
+
// expose everything beneath it.
|
|
454
|
+
// A native root pinned at an existing ancestor names the missing directories between
|
|
455
|
+
// them: the fixed helper opens each one it creates or meets, so those are read exactly.
|
|
456
|
+
const pinnedComponents = roots.flatMap((r) => {
|
|
457
|
+
const dirs = [];
|
|
458
|
+
for (let i = 1, p = dirname(r.path); i < (r.components?.length ?? 0); i++, p = dirname(p))
|
|
459
|
+
dirs.push(p);
|
|
460
|
+
return dirs;
|
|
461
|
+
});
|
|
462
|
+
const reads = macReadAllows({
|
|
463
|
+
roots: [
|
|
365
464
|
...runtimeRoots,
|
|
465
|
+
...(privateTmp ? [privateTmp] : []),
|
|
466
|
+
...(toolHomes?.readRoots ?? []),
|
|
467
|
+
],
|
|
468
|
+
exact: [
|
|
469
|
+
...pinnedComponents,
|
|
366
470
|
...(helper ? [helper] : []),
|
|
367
471
|
...(javaAgent ? [javaAgent] : []),
|
|
368
|
-
|
|
369
|
-
|
|
472
|
+
...(toolHomes?.readFiles ?? []),
|
|
473
|
+
],
|
|
474
|
+
deniedReadRoots: request.grant.deniedReadRoots,
|
|
475
|
+
userTempDir: macUserTempDir(),
|
|
476
|
+
});
|
|
370
477
|
const writeRoots = request.kind === "native"
|
|
371
478
|
? roots.filter((r) => r.access === "write").map((r) => r.path)
|
|
372
|
-
: [...request.grant.writeRoots];
|
|
479
|
+
: [...request.grant.writeRoots, ...(privateTmp ? [privateTmp] : [])];
|
|
373
480
|
// Only the fixed native helper may establish missing ancestor directories. Its
|
|
374
481
|
// descriptor prelude creates exact components and passes only the final narrow
|
|
375
482
|
// root to NativeFiles. SRT needs this transient subtree write exception because
|
|
@@ -393,13 +500,20 @@ export async function startMacOperationWorker(request, signal) {
|
|
|
393
500
|
const config = {
|
|
394
501
|
filesystem: {
|
|
395
502
|
denyRead: ["/", ...request.grant.deniedReadRoots],
|
|
396
|
-
allowRead:
|
|
503
|
+
allowRead: reads.allowRead,
|
|
504
|
+
// patched runtime: exact `(literal …)` read allows, never the subtree below them
|
|
505
|
+
allowReadExact: reads.allowReadExact,
|
|
397
506
|
allowWrite: [
|
|
398
507
|
...writeRoots,
|
|
399
508
|
...establishmentRoots.map((path) => ({ path, literal: true })),
|
|
400
509
|
],
|
|
401
510
|
denyWrite: [
|
|
402
511
|
...implicitWritePaths(),
|
|
512
|
+
// The owner-denied roots (the secret paths, the device's state directory) are
|
|
513
|
+
// unwritable too: a write root may contain one (a project bound at the home, an
|
|
514
|
+
// approved `cd ~`), and the runtime turns each deny into write, move and creation
|
|
515
|
+
// denies on the path and moves of its ancestors.
|
|
516
|
+
...withCanonicalForms(request.grant.deniedReadRoots),
|
|
403
517
|
// Per-root deny entries pin every ancestor against creation in SRT.
|
|
404
518
|
// The fixed helper has no rename API; retain global Git content denies
|
|
405
519
|
// while it establishes a missing root without those ancestor pins.
|
|
@@ -498,15 +612,20 @@ export async function startMacOperationWorker(request, signal) {
|
|
|
498
612
|
if (!ENV_NAME_RE.test(key))
|
|
499
613
|
throw new Error("Invalid environment variable name");
|
|
500
614
|
const outerEnv = {
|
|
615
|
+
...toolHomes?.env,
|
|
501
616
|
PATH: process.env.PATH,
|
|
502
617
|
LANG: process.env.LANG,
|
|
503
618
|
HOME: args.cwd ?? "/",
|
|
504
|
-
TMPDIR: request.grant.writeRoots[0] ?? "/tmp",
|
|
619
|
+
TMPDIR: privateTmp ?? request.grant.writeRoots[0] ?? "/tmp",
|
|
505
620
|
};
|
|
621
|
+
// the runtime's wrapper sets its own TMPDIR after this environment: set ours inside it
|
|
622
|
+
const temp = privateTmp
|
|
623
|
+
? `export TMPDIR=${shellQuote(privateTmp)} TMP=${shellQuote(privateTmp)} TEMP=${shellQuote(privateTmp)}; `
|
|
624
|
+
: "";
|
|
506
625
|
const exports = Object.entries(args.env ?? {})
|
|
507
626
|
.map(([key, value]) => `export ${key}=${shellQuote(value)}`)
|
|
508
627
|
.join("; ");
|
|
509
|
-
const script = await wrap(`${!request.grant.full && exports ? `${exports}; ` : ""}exec /bin/bash -c ${shellQuote(args.command)}${request.managedOutput ? " 2>&1" : ""}`);
|
|
628
|
+
const script = await wrap(`${temp}${!request.grant.full && exports ? `${exports}; ` : ""}exec /bin/bash -c ${shellQuote(args.command)}${request.managedOutput ? " 2>&1" : ""}`);
|
|
510
629
|
await request.beforeLaunch();
|
|
511
630
|
controller.signal.throwIfAborted();
|
|
512
631
|
const cap = new OutputCap(args.maxOutputBytes);
|
|
@@ -622,6 +741,8 @@ export async function startMacOperationWorker(request, signal) {
|
|
|
622
741
|
// by the command; once the command is gone, the trusted worker removes it where empty
|
|
623
742
|
if (request.kind === "exec" && !request.grant.full && execStarted)
|
|
624
743
|
removeEmptySequencers(request.grant.writeRoots, request.pythonPath, request.onDiagnostic);
|
|
744
|
+
if (privateTmp)
|
|
745
|
+
await rm(privateTmp, { recursive: true, force: true }).catch((error) => request.onDiagnostic?.(`Private temporary directory: ${error.message}`));
|
|
625
746
|
}
|
|
626
747
|
})();
|
|
627
748
|
void completion.catch(() => { });
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whether the OS sandbox's dependencies are present here, and why not (`login` says what to
|
|
3
|
+
* install). Loaded on demand: only `login` asks.
|
|
4
|
+
*/
|
|
5
|
+
export declare function sandboxAvailability(): {
|
|
6
|
+
ok: true;
|
|
7
|
+
} | {
|
|
8
|
+
ok: false;
|
|
9
|
+
reason: string;
|
|
10
|
+
};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { SandboxManager } from "@anthropic-ai/sandbox-runtime";
|
|
2
|
+
/**
|
|
3
|
+
* Whether the OS sandbox's dependencies are present here, and why not (`login` says what to
|
|
4
|
+
* install). Loaded on demand: only `login` asks.
|
|
5
|
+
*/
|
|
6
|
+
export function sandboxAvailability() {
|
|
7
|
+
if (!SandboxManager.isSupportedPlatform()) {
|
|
8
|
+
return { ok: false, reason: `the OS sandbox does not support ${process.platform}` };
|
|
9
|
+
}
|
|
10
|
+
const deps = SandboxManager.checkDependencies();
|
|
11
|
+
if (deps.errors.length > 0) {
|
|
12
|
+
return {
|
|
13
|
+
ok: false,
|
|
14
|
+
reason: `the OS sandbox is missing dependencies: ${deps.errors.join("; ")}`,
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
return { ok: true };
|
|
18
|
+
}
|
|
@@ -1,14 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The
|
|
3
|
-
*
|
|
4
|
-
* `mode` command can use them without loading the sandbox runtime.
|
|
2
|
+
* The text of an unavailable OS sandbox. A pure string, so `login` can use it without loading the
|
|
3
|
+
* sandbox runtime.
|
|
5
4
|
*/
|
|
6
|
-
/** How to fix an unavailable OS sandbox
|
|
5
|
+
/** How to fix an unavailable OS sandbox. */
|
|
7
6
|
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;
|
|
@@ -1,21 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The
|
|
3
|
-
*
|
|
4
|
-
* `mode` command can use them without loading the sandbox runtime.
|
|
2
|
+
* The text of an unavailable OS sandbox. A pure string, so `login` can use it without loading the
|
|
3
|
+
* sandbox runtime.
|
|
5
4
|
*/
|
|
6
|
-
/** How to fix an unavailable OS sandbox
|
|
5
|
+
/** How to fix an unavailable OS sandbox. */
|
|
7
6
|
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
|
-
}
|
package/dist/exec/shared.d.ts
CHANGED
|
@@ -1,10 +1,4 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import type { SandboxMode } from "../state.js";
|
|
3
|
-
import { DeviceOpError } from "./types.js";
|
|
4
|
-
/** The file that marks a directory as a device directory this program has used. */
|
|
5
|
-
export declare const ROOT_MARKER = ".capybara-device";
|
|
6
|
-
/** How long a finished command's output pipes may stay open (held by a background child). */
|
|
7
|
-
export declare const PIPE_GRACE_MS = 200;
|
|
1
|
+
import type { SandboxRoots } from "@capybara-hq/plugin-sdk";
|
|
8
2
|
export declare const ENV_NAME_RE: RegExp;
|
|
9
3
|
/** The roots of a device directory: `<dir>/workspace`, `<dir>/skills`, `<dir>/tmp`. */
|
|
10
4
|
export declare function osRoots(dir: string): SandboxRoots;
|
|
@@ -15,6 +9,14 @@ export declare function osRoots(dir: string): SandboxRoots;
|
|
|
15
9
|
* sets them.
|
|
16
10
|
*/
|
|
17
11
|
export declare const TOOL_HOME_DIRS: readonly (readonly [string, string])[];
|
|
12
|
+
/**
|
|
13
|
+
* Single files in the home that hold a version manager's global pins, granted read only next to
|
|
14
|
+
* {@link TOOL_HOME_DIRS}: asdf's global `.tool-versions` (mise reads it too). The other managers
|
|
15
|
+
* keep their global version inside their data directory (pyenv and rbenv `version`, nvm
|
|
16
|
+
* `alias/default`, rustup `settings.toml`, mise `config.toml`); a per-project file such as
|
|
17
|
+
* `.nvmrc` is not global. Never a dotfile that could hold a secret.
|
|
18
|
+
*/
|
|
19
|
+
export declare const TOOL_HOME_FILES: readonly string[];
|
|
18
20
|
/**
|
|
19
21
|
* The version manager variables of an OS-sandboxed command ({@link TOOL_HOME_DIRS}): a variable
|
|
20
22
|
* the device's environment `env` sets to an absolute path is passed on; an unset one points at its
|
|
@@ -24,15 +26,27 @@ export declare const TOOL_HOME_DIRS: readonly (readonly [string, string])[];
|
|
|
24
26
|
* home.
|
|
25
27
|
*/
|
|
26
28
|
export declare function toolHomeEnv(home: string, env?: Record<string, string | undefined>): Record<string, string>;
|
|
29
|
+
/**
|
|
30
|
+
* What a restricted exec on the host gets for its version managers: the {@link toolHomeEnv}
|
|
31
|
+
* variables of the device process (its real `home` and its own environment `env`), the canonical
|
|
32
|
+
* directories they name as read-only roots, and the global pin files ({@link TOOL_HOME_FILES})
|
|
33
|
+
* that exist as regular files, canonical, as read-only files. A directory is left out when it does
|
|
34
|
+
* not exist, is `/`, lies at or under an owner-denied path, or contains one (Landlock cannot hide
|
|
35
|
+
* a denied path inside a granted root); a file is left out when it, or the target of a link it
|
|
36
|
+
* is, lies at or under one. Nothing here is ever made writable. A command in the device's
|
|
37
|
+
* container uses none of this: its home is the image's.
|
|
38
|
+
*/
|
|
39
|
+
export declare function restrictedToolHomes(home: string, env: Record<string, string | undefined>, deniedReadRoots: readonly string[]): {
|
|
40
|
+
env: Record<string, string>;
|
|
41
|
+
readRoots: string[];
|
|
42
|
+
readFiles: string[];
|
|
43
|
+
};
|
|
27
44
|
/**
|
|
28
45
|
* The longest prefix of `b` that does not end inside a UTF-8 sequence (a cut buffer's tail is
|
|
29
46
|
* dropped instead of decoding to U+FFFD).
|
|
30
47
|
*/
|
|
31
48
|
export declare function utf8Prefix(b: Buffer): Buffer;
|
|
32
49
|
export declare function shellQuote(s: string): string;
|
|
33
|
-
export declare function isUnder(p: string, root: string): boolean;
|
|
34
|
-
export declare function policyError(message: string): DeviceOpError;
|
|
35
|
-
export declare function isMissing(e: unknown): boolean;
|
|
36
50
|
/** Captures stdout and stderr up to a combined byte budget; the rest is drained and dropped. */
|
|
37
51
|
export declare class OutputCap {
|
|
38
52
|
private readonly max;
|
|
@@ -61,40 +75,3 @@ export declare class RootGuard {
|
|
|
61
75
|
constructor(dir: string, roots: SandboxRoots);
|
|
62
76
|
ensure(): "ok" | "gone";
|
|
63
77
|
}
|
|
64
|
-
/**
|
|
65
|
-
* Host-side file access. In sandbox mode `path`s are confined to the three roots (real paths,
|
|
66
|
-
* symlinks resolved, refused when they leave a root); in auto mode any clean absolute path is
|
|
67
|
-
* accepted (shape checks only: absolute, no `..` segments, no control characters). Used for the
|
|
68
|
-
* skills root (commands can only read it, so nothing can race it) and by the host executor.
|
|
69
|
-
*/
|
|
70
|
-
export declare class HostFiles {
|
|
71
|
-
private readonly roots;
|
|
72
|
-
private readonly mode;
|
|
73
|
-
constructor(roots: SandboxRoots, mode: SandboxMode);
|
|
74
|
-
/**
|
|
75
|
-
* `path` made absolute and normalized; in sandbox mode refused unless it is lexically under a
|
|
76
|
-
* root, in auto mode accepted when its shape is clean.
|
|
77
|
-
*/
|
|
78
|
-
lexical(path: string): string;
|
|
79
|
-
/**
|
|
80
|
-
* The real path of an existing `path` (null when missing); in sandbox mode refused unless under
|
|
81
|
-
* a root after resolving links.
|
|
82
|
-
*/
|
|
83
|
-
existing(path: string): Promise<string | null>;
|
|
84
|
-
/**
|
|
85
|
-
* The real path of an existing `path` (symlinks resolved); in sandbox mode refused unless under
|
|
86
|
-
* a root.
|
|
87
|
-
*/
|
|
88
|
-
inside(path: string, what: string): Promise<string>;
|
|
89
|
-
private checkReal;
|
|
90
|
-
private rootList;
|
|
91
|
-
read(path: string, maxBytes: number): Promise<{
|
|
92
|
-
data: Uint8Array;
|
|
93
|
-
truncated: boolean;
|
|
94
|
-
} | null>;
|
|
95
|
-
stat(path: string): Promise<{
|
|
96
|
-
size: number;
|
|
97
|
-
isDir: boolean;
|
|
98
|
-
} | null>;
|
|
99
|
-
write(path: string, data: Uint8Array): Promise<void>;
|
|
100
|
-
}
|