barebox 0.2.0 → 0.4.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/src/run.js ADDED
@@ -0,0 +1,232 @@
1
+ // run.js — one-call sandboxed run (M2.5 integration seam).
2
+ //
3
+ // `run()` wraps the low-level parts (`createProxy` + `addAgent` + `launch`,
4
+ // which stay public): one agent, one sandbox, one audit log, exit code out.
5
+ // The caller never touches sockets, ask files, or the hold queue.
6
+ //
7
+ // What `mode` does TODAY (letters are M3's job): the proxy sees requests,
8
+ // not intent, so until the rwxmap + bareguard letter pipeline lands there is
9
+ // no per-letter policy — only this interim hold rule:
10
+ // - the card/payment FLOOR holds in every mode, including `trust`: a
11
+ // request whose path names a payment destination (`/checkout`,
12
+ // `/payment`, `/orders`, `/purchase`). The card-in-body half of the
13
+ // floor is NOT enforced here: the decide seam sees method/URL/headers
14
+ // but never the body, so body inspection waits for M3's in-proxy rules.
15
+ // Known payment DOMAINS are likewise M3 (they need rwxmap).
16
+ // - `ask`/`auto` additionally park every non-GET/HEAD request (the PRD's
17
+ // "unsure? tag it x" default: GET/HEAD = r, anything else = x). The two
18
+ // modes behave identically until M3's `askOn` letters separate them.
19
+ // - `trust` forwards everything else, logged.
20
+ //
21
+ // A passed `onAsk` answers parked requests with no files involved; when it is
22
+ // absent the file checkpoint runs (`<runtime>/asks` + `<runtime>/answers`,
23
+ // answered from a second terminal with `sbx pending/approve/deny`).
24
+ //
25
+ // `asks` is the collected ask records in park order: the queue reports
26
+ // every park and decision through `onEvent`, so no log is re-parsed and no
27
+ // wrapper re-collects. `audit` is the JSONL audit log path, kept after
28
+ // return — the caller owns the runtime dir (including temp-dir cleanup).
29
+ import fs from 'node:fs';
30
+ import { createProxy } from './proxy.js';
31
+ import { createRuntime, runtimePaths } from './runtime.js';
32
+ import { launch } from './launcher.js';
33
+ import { diffOverlay } from './overlay.js';
34
+
35
+ /** Payment-destination path fragments: the URL-visible half of the floor (PRD section 2). */
36
+ const FLOOR_PATHS = ['/checkout', '/payment', '/orders', '/purchase'];
37
+
38
+ /**
39
+ * The card/payment floor, URL-visible half: park payment destinations in
40
+ * every mode. Returns the hold reason, or null to leave the mode rule alone.
41
+ *
42
+ * @param {{ url: string }} req request, as seen by the decide seam
43
+ * @returns {string|null} hold reason, or null
44
+ */
45
+ function floorReason(req) {
46
+ let pathname;
47
+ try {
48
+ pathname = new URL(req.url).pathname.toLowerCase();
49
+ } catch {
50
+ return null;
51
+ }
52
+ for (const fp of FLOOR_PATHS) {
53
+ if (pathname.includes(fp)) return `payment destination (floor): ${fp}`;
54
+ }
55
+ return null;
56
+ }
57
+
58
+ /**
59
+ * The interim x-rule (PRD "everything else"): GET/HEAD forward, any other
60
+ * method parks. Stands in for M3's letters.
61
+ *
62
+ * @param {{ method: string }} req request, as seen by the decide seam
63
+ * @returns {string|null} hold reason, or null
64
+ */
65
+ function methodReason(req) {
66
+ const m = String(req.method || '').toUpperCase();
67
+ return (m === 'GET' || m === 'HEAD') ? null : `method ${m || '?'} is not GET/HEAD (interim x-rule)`;
68
+ }
69
+
70
+ /**
71
+ * Build the hold decision for a mode. Pure: unit-testable without a sandbox.
72
+ *
73
+ * @param {string} mode `ask` | `auto` | `trust`
74
+ * @returns {import('./holds.js').ShouldHold} decision function for the hold queue
75
+ */
76
+ export function shouldHoldForMode(mode) {
77
+ if (mode !== 'ask' && mode !== 'auto' && mode !== 'trust') {
78
+ throw new Error(`run: mode must be ask|auto|trust, got ${JSON.stringify(mode)}`);
79
+ }
80
+ return (req) => floorReason(req)
81
+ ?? (mode === 'trust' ? null : methodReason(req));
82
+ }
83
+
84
+ /**
85
+ * A collected ask record: the parked ask plus how it was decided.
86
+ *
87
+ * @typedef {object} AskRecord
88
+ * @property {string} id hold id (`h<n>`)
89
+ * @property {string} agent agent name (its socket)
90
+ * @property {string} method HTTP method
91
+ * @property {string} url full URL
92
+ * @property {string} rule hold-reason string
93
+ * @property {string} letter always `'x'` until M3 owns letters
94
+ * @property {string} [bodyPreview] request body preview
95
+ * @property {boolean} [truncated] body preview truncation flag
96
+ * @property {string|null} [expiresAt] ISO-8601 UTC deadline, or null
97
+ * @property {string} [decision] `'allow'` | `'deny'`, once decided
98
+ * @property {string} [reason] decision reason, once decided
99
+ */
100
+
101
+ /**
102
+ * Options for {@link run}.
103
+ *
104
+ * @typedef {object} RunOptions
105
+ * @property {string} proj project directory, bound read-only inside the sandbox
106
+ * @property {string[]} command argv to run inside, for example `["bash", "-c", "echo hi"]`
107
+ * @property {string} [mode] `ask` | `auto` (default) | `trust`; see the mode comment at the top of this file
108
+ * @property {import('./holds.js').OnAsk} [onAsk] ask seam; when present no files are involved, otherwise the file checkpoint runs
109
+ * @property {import('./holds.js').OnEvent} [onEvent] event callback: `{ type: 'ask' }` on park, `{ type: 'decided' }` on settle or abandon (also feeds `asks`)
110
+ * @property {string} [runtime] runtime dir (created when absent: a short `sbx-*` temp dir, keeping unix socket paths under the ~108-char limit)
111
+ * @property {string} [agent] agent name (default `'agent'`)
112
+ * @property {number|string} [timeoutMs] hold deadline in ms, or `'never'` (default 120000)
113
+ * @property {object} [unsafeTestOnly] TEST-ONLY escape hatch, forwarded to the proxy (see `createProxy`): everything under it weakens the sandbox wall
114
+ * @property {NodeJS.WritableStream} [stdout] where the agent's stdout goes (default process.stdout)
115
+ * @property {NodeJS.WritableStream} [stderr] where the agent's stderr goes (default process.stderr)
116
+ * @property {boolean} [overlay] when true, mount a per-run overlay upper over the project (M4 tracing paper) instead of binding it read-only; the result's `diff` lists the run's changes for commit/rollback
117
+ * @property {string[]} [overlayIgnore] path segments invisible to the overlay (default `node_modules`; see overlay.js Q3)
118
+ */
119
+
120
+ /**
121
+ * Run one sandboxed agent start-to-finish in a single call.
122
+ *
123
+ * @param {object} opts
124
+ * @param {string} opts.proj project directory, bound read-only inside the sandbox
125
+ * @param {string[]} opts.command argv to run inside, for example `["bash", "-c", "echo hi"]`
126
+ * @param {string} [opts.mode] `ask` | `auto` (default) | `trust`; see the mode comment at the top of this file
127
+ * @param {import('./holds.js').OnAsk|null} [opts.onAsk] ask seam; when present no files are involved, otherwise the file checkpoint runs
128
+ * @param {import('./holds.js').OnEvent|null} [opts.onEvent] event callback: `{ type: 'ask' }` on park, `{ type: 'decided' }` on settle or abandon (also feeds `asks`)
129
+ * @param {string|null} [opts.runtime] runtime dir (created when absent: a short `sbx-*` temp dir, keeping unix socket paths under the ~108-char limit)
130
+ * @param {string} [opts.agent] agent name (default `'agent'`)
131
+ * @param {number|string} [opts.timeoutMs] hold deadline in ms, or `'never'` (default 120000)
132
+ * @param {object|null} [opts.unsafeTestOnly] TEST-ONLY escape hatch, forwarded to the proxy (see `createProxy`)
133
+ * @param {NodeJS.WritableStream|null} [opts.stdout] where the agent's stdout goes (default process.stdout)
134
+ * @param {NodeJS.WritableStream|null} [opts.stderr] where the agent's stderr goes (default process.stderr)
135
+ * @param {boolean} [opts.overlay] when true, mount a per-run overlay upper over the project instead of binding it read-only; the result's `diff` lists the run's changes for commit/rollback
136
+ * @param {string[]} [opts.overlayIgnore] path segments invisible to the overlay (default `node_modules`; see overlay.js Q3)
137
+ * @returns {Promise<{ exit: number, asks: AskRecord[], audit: string, diff: import('./overlay.js').OverlayChange[], runtime: string }>} the agent process exit code, the collected ask records, the JSONL audit log path, the run's overlay diff (M4), and the runtime dir addressing it
138
+ * @when Reach for this to HARNESS-ONLY run one sandboxed agent start-to-finish in a single call: it starts the proxy, sandboxes the command, answers holds, and returns the exit code with the ask and audit trail (plus the overlay diff once M4 exists).
139
+ * @fails Rejects on a missing/unreadable `proj`, an empty `command`, a bad `mode`, a misshapen `onAsk`, a proxy that never becomes ready, a `launch` that throws (uncommitted overlay changes, a runtime inside the project — the proxy is closed first), or an overlay diff that cannot be read. The agent's own nonzero exit is returned as `exit`, never thrown.
140
+ * @example
141
+ * import { run } from "barebox";
142
+ * const { exit, asks, audit } = await run({ proj: "/tmp/proj", command: ["bash", "-c", "echo hi"] });
143
+ */
144
+ export async function run({ proj, command, mode = 'auto', onAsk = null,
145
+ onEvent = null, runtime = null, agent = 'agent', timeoutMs,
146
+ unsafeTestOnly = null, stdout = null, stderr = null,
147
+ overlay = false, overlayIgnore }) {
148
+ if (typeof proj !== 'string' || !proj) throw new Error('run: proj must be a non-empty string');
149
+ if (!fs.existsSync(proj)) throw new Error(`run: proj does not exist: ${proj}`);
150
+ if (!Array.isArray(command) || !command.length) {
151
+ throw new Error('run: command must be a non-empty argv array');
152
+ }
153
+ if (onAsk != null && typeof onAsk !== 'function') {
154
+ throw new Error('run: onAsk must be a function');
155
+ }
156
+ // Mode first: bad input throws before any runtime dir is created.
157
+ const decide = shouldHoldForMode(mode);
158
+ // Short temp dir: agent socket paths inherit it and cap at ~108 chars.
159
+ const rt = runtime ?? createRuntime();
160
+ const audit = runtimePaths(rt).audit;
161
+
162
+ // Outcomes are reported, never reconstructed: the queue's `onEvent`
163
+ // builds the ask records in park order, for both channels alike.
164
+ /** @type {Map<string, AskRecord>} */
165
+ const seen = new Map();
166
+ /** @param {import('./holds.js').HoldEvent} e */
167
+ const recordEvent = (e) => {
168
+ if (e.type === 'ask') {
169
+ seen.set(e.ask.id, { ...e.ask });
170
+ } else if (e.type === 'decided') {
171
+ const prev = seen.get(e.id);
172
+ if (prev) seen.set(e.id, { ...prev, decision: e.decision, reason: e.reason });
173
+ }
174
+ };
175
+ const holdOnEvent = onEvent
176
+ ? (/** @type {import('./holds.js').HoldEvent} */ e) => { recordEvent(e); onEvent(e); }
177
+ : recordEvent;
178
+
179
+ const proxy = createProxy({
180
+ runtime: rt, logFile: audit, unsafeTestOnly,
181
+ hold: { shouldHold: decide, onAsk, timeoutMs, onEvent: holdOnEvent },
182
+ });
183
+ try {
184
+ await proxy.ready;
185
+ } catch (e) {
186
+ await proxy.close().catch(() => {});
187
+ throw e;
188
+ }
189
+ /** @type {string|undefined} */
190
+ let sock;
191
+ // `addAgent` and `launch` run INSIDE the try: a synchronous throw there
192
+ // (a broken socket folder, uncommitted overlay changes, a runtime inside
193
+ // the project) must still close the proxy — otherwise its listening
194
+ // sockets keep this process alive forever.
195
+ /** @type {number} */
196
+ let exit;
197
+ try {
198
+ sock = proxy.addAgent(agent);
199
+ const child = launch({
200
+ runtime: rt, agent, proj, command,
201
+ socket: sock, caFile: proxy.caFile,
202
+ overlay, overlayIgnore,
203
+ });
204
+ const out = stdout ?? process.stdout;
205
+ const err = stderr ?? process.stderr;
206
+ child.stdout?.on('data', (c) => { try { out.write(c); } catch {} });
207
+ child.stderr?.on('data', (c) => { try { err.write(c); } catch {} });
208
+ exit = await new Promise((resolve, reject) => {
209
+ child.on('error', reject);
210
+ child.on('close', (code) => resolve(code ?? 1));
211
+ });
212
+ } finally {
213
+ // The sandbox is gone: end the agent's holds as client gone now, not
214
+ // as 'proxy closing' if close() beats the sockets' async 'close'.
215
+ if (sock) proxy.removeAgent(agent);
216
+ await proxy.close();
217
+ }
218
+ // M2.5 item 4: the result carries the M4 diff. Without overlay there is no
219
+ // upper, so nothing to review — an empty diff, never null.
220
+ /** @type {import('./overlay.js').OverlayChange[]} */
221
+ let diff = [];
222
+ if (overlay) {
223
+ try {
224
+ diff = diffOverlay({ runtime: rt, agent });
225
+ } catch (e) {
226
+ const err = /** @type {Error & {exit?: number}} */ (e instanceof Error ? e : new Error(String(e)));
227
+ err.exit = exit;
228
+ throw new Error(`run: overlay diff failed after exit ${exit}: ${err.message}`);
229
+ }
230
+ }
231
+ return { exit, asks: [...seen.values()], audit, diff, runtime: rt };
232
+ }
package/src/runtime.js ADDED
@@ -0,0 +1,295 @@
1
+ // runtime.js — the single writer of the runtime folder layout.
2
+ //
3
+ // Every path both sides agree on lives here: the proxy socket, the hold
4
+ // queue's ask/answer files, the certificates dir, the CA bundle, the audit
5
+ // log, and the overlay record. Import layout from here; no other module
6
+ // names these paths. (The sandbox launcher used to import them from the
7
+ // TLS proxy just to get a filename.)
8
+ import crypto from 'node:crypto';
9
+ import fs from 'node:fs';
10
+ import net from 'node:net';
11
+ import os from 'node:os';
12
+ import path from 'node:path';
13
+ import { stripVTControlCharacters } from 'node:util';
14
+
15
+ export const AGENT_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;
16
+ // Linux sun_path: 108 bytes including the NUL.
17
+ const MAX_SOCK_PATH = 107;
18
+
19
+ /**
20
+ * Check an agent name before it reaches the filesystem.
21
+ *
22
+ * @param {string} name agent name
23
+ * @returns {void} throws on `../` and friends
24
+ */
25
+ export function assertAgentName(name) {
26
+ if (!AGENT_RE.test(name || '')) {
27
+ throw new Error(`bad agent name ${JSON.stringify(name)}: must match ${AGENT_RE}`);
28
+ }
29
+ }
30
+
31
+ /**
32
+ * Resolve symlinks through the nearest existing ancestor: socket paths may
33
+ * not exist yet, so `realpathSync` on the full path would throw. Walks up
34
+ * to the first existing ancestor, resolves that, then re-attaches the rest.
35
+ *
36
+ * @param {string} p any path, existing or not
37
+ * @returns {string} the real (symlink-free) spelling of `p`
38
+ */
39
+ export function realPathOf(p) {
40
+ const abs = path.resolve(p);
41
+ let cur = abs;
42
+ /** @type {string[]} */
43
+ const rest = [];
44
+ while (!fs.existsSync(cur)) {
45
+ const parent = path.dirname(cur);
46
+ if (parent === cur) break;
47
+ rest.unshift(path.basename(cur));
48
+ cur = parent;
49
+ }
50
+ const real = fs.realpathSync(cur);
51
+ return rest.length ? path.join(real, ...rest) : real;
52
+ }
53
+
54
+ /**
55
+ * True when `p` is `base` or lives under it, compared as real (symlink-free)
56
+ * paths, so a symlinked spelling cannot smuggle a path out.
57
+ *
58
+ * @param {string} base container path
59
+ * @param {string} p path to test
60
+ * @returns {boolean} containment on real paths
61
+ */
62
+ export function isInside(base, p) {
63
+ const realB = realPathOf(base);
64
+ const realP = realPathOf(p);
65
+ if (realP === realB) return true;
66
+ const prefix = realB.endsWith(path.sep) ? realB : realB + path.sep;
67
+ return realP.startsWith(prefix);
68
+ }
69
+
70
+ /**
71
+ * Create a short-lived runtime dir: a short `sbx-` temp dir, keeping unix
72
+ * socket paths under the ~108-char limit.
73
+ *
74
+ * @returns {string} the new runtime dir
75
+ */
76
+ export function createRuntime() {
77
+ return fs.mkdtempSync(path.join(os.tmpdir(), 'sbx-'));
78
+ }
79
+
80
+ /**
81
+ * Create a temp dir inside the runtime tree: `mkdtemp` is a runtime-layout
82
+ * writer, so it lives here, not in `overlay.js`. Used for the merged-view
83
+ * mount (`merged`) and the walker manifest dir (`walk`).
84
+ *
85
+ * @param {string} scratch overlay record dir (`overlay/<agent>`)
86
+ * @param {string} prefix dir prefix (`merged`, `walk`)
87
+ * @returns {string} the new dir
88
+ */
89
+ export function runtimeTempDir(scratch, prefix) {
90
+ return fs.mkdtempSync(path.join(scratch, `${prefix}-`));
91
+ }
92
+
93
+ /**
94
+ * Make a runtime dir owner-only whatever the umask: `mode` is masked by
95
+ * the umask and doesn't apply to an existing dir, hence the `chmod`. An
96
+ * existing dir you own is tightened to 0700; one you don't own (`/tmp`,
97
+ * root-owned, shared) is refused, since it can't be made private.
98
+ *
99
+ * @param {string} dir dir to create or fix up
100
+ * @returns {void}
101
+ * @throws {Error} when the dir exists and is owned by another uid
102
+ */
103
+ export function ensurePrivateDir(dir) {
104
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
105
+ const owner = fs.statSync(dir).uid;
106
+ const me = /** @type {number} */ (process.getuid?.());
107
+ if (owner !== me) {
108
+ throw new Error(`runtime dir ${dir} is owned by uid ${owner}, not you (uid ${me}): use a dir of your own, e.g. ${path.join(dir, 'sbx')}`);
109
+ }
110
+ fs.chmodSync(dir, 0o700);
111
+ }
112
+
113
+ /** @param {string} owner owner file path @returns {unknown} the pid it names, or 'unknown' when missing, empty or garbage */
114
+ function pidOf(owner) {
115
+ try {
116
+ return JSON.parse(fs.readFileSync(owner, 'utf8'))?.pid ?? 'unknown';
117
+ } catch {
118
+ return 'unknown';
119
+ }
120
+ }
121
+
122
+ /** @param {unknown} pid @returns {boolean} true when a process with that pid is alive */
123
+ function isPidAlive(pid) {
124
+ if (typeof pid !== 'number') return false;
125
+ try {
126
+ process.kill(pid, 0);
127
+ return true;
128
+ } catch (e) {
129
+ return /** @type {{code?: string}} */ (e)?.code === 'EPERM';
130
+ }
131
+ }
132
+
133
+ /** @param {string} runtime runtime dir @param {unknown} pid the holder @returns {Error} the one in-use error */
134
+ function inUseError(runtime, pid) {
135
+ return new Error(
136
+ `runtime ${runtime} is in use by pid ${String(pid)} (one proxy per runtime: use another SBX_RUNTIME, or leave it unset for a fresh one)`);
137
+ }
138
+
139
+ /**
140
+ * The abstract-socket name of a runtime's claim lock. Hashes the real path,
141
+ * device and inode, so a symlinked path finds the same lock and a recreated
142
+ * dir gets a new one.
143
+ *
144
+ * @param {string} runtime runtime dir
145
+ * @returns {string} the abstract socket name
146
+ */
147
+ export function lockName(runtime) {
148
+ const real = fs.realpathSync(runtime);
149
+ const st = fs.statSync(real);
150
+ return '\0barebox-' + crypto.createHash('sha256')
151
+ .update(`${real}\0${st.dev}\0${st.ino}`).digest('hex').slice(0, 32);
152
+ }
153
+
154
+ /**
155
+ * True when a live proxy owns the runtime: something answers on its lock.
156
+ * Never binds, so it can never steal the claim from a proxy that's starting.
157
+ * A runtime that doesn't exist is not live.
158
+ *
159
+ * @param {string} runtime runtime dir
160
+ * @returns {Promise<boolean>} whether the lock connects
161
+ */
162
+ export function runtimeLive(runtime) {
163
+ let name;
164
+ try {
165
+ name = lockName(runtime);
166
+ } catch {
167
+ return Promise.resolve(false);
168
+ }
169
+ return new Promise((resolve) => {
170
+ const sock = net.connect(name);
171
+ sock.on('connect', () => { sock.destroy(); resolve(true); });
172
+ sock.on('error', () => resolve(false));
173
+ });
174
+ }
175
+
176
+ /**
177
+ * Claim one runtime for one live proxy: the single enforcer of "one proxy
178
+ * owns a runtime". The claim is an abstract unix socket the proxy binds for
179
+ * as long as it lives (Linux). The kernel frees it when the process dies,
180
+ * SIGKILL included, so a claim is never stale: nothing is judged, taken
181
+ * over or deleted by hand. The name hashes the real path, device and inode,
182
+ * so a symlinked path finds the same lock and a recreated dir gets a new one.
183
+ * The bind result is synchronous (`server.listening` right after `listen`),
184
+ * so a second claim, in this process or another, throws before the caller
185
+ * touches the runtime. The lock is `unref`'d: it never keeps a process alive.
186
+ * The owner file `{"pid"}` is written by the lock holder only, to name it in
187
+ * the in-use message.
188
+ *
189
+ * @param {string} runtime runtime dir to claim
190
+ * @returns {() => void} `release()`: unlinks the owner file only when it holds our pid, then closes the lock; idempotent per claim
191
+ */
192
+ export function claimRuntime(runtime) {
193
+ ensurePrivateDir(runtime);
194
+ const real = fs.realpathSync(runtime);
195
+ const owner = runtimePaths(real).owner;
196
+ const name = lockName(runtime);
197
+ const server = net.createServer((c) => c.destroy());
198
+ server.on('error', () => {});
199
+ server.listen(name);
200
+ if (!server.listening) {
201
+ const pid = pidOf(owner);
202
+ if (isPidAlive(pid)) throw inUseError(runtime, pid);
203
+ throw new Error(`runtime ${runtime} could not be locked: no live owner is recorded (another proxy may be starting, or this process cannot bind unix sockets)`);
204
+ }
205
+ server.unref();
206
+ const tmp = `${owner}.tmp-${crypto.randomBytes(8).toString('hex')}`;
207
+ try {
208
+ fs.writeFileSync(tmp, JSON.stringify({ pid: process.pid }), { flag: 'wx', mode: 0o600 });
209
+ fs.renameSync(tmp, owner);
210
+ } catch (e) {
211
+ server.close();
212
+ throw e;
213
+ } finally {
214
+ try { fs.unlinkSync(tmp); } catch {}
215
+ }
216
+ let released = false;
217
+ return () => {
218
+ if (released) return;
219
+ released = true;
220
+ if (pidOf(owner) === process.pid) {
221
+ try { fs.unlinkSync(owner); } catch {}
222
+ }
223
+ server.close();
224
+ };
225
+ }
226
+
227
+ /**
228
+ * Strip terminal control before printing agent-controlled bytes (ask URLs,
229
+ * rules, body previews, overlay paths): an escape sequence smuggled into a
230
+ * preview could otherwise rewrite the approver's terminal line before
231
+ * approval, and bidi controls in an agent-chosen filename could flip how a
232
+ * reviewed path reads.
233
+ *
234
+ * @param {unknown} s value to print
235
+ * @returns {string} printable text with no VT sequences, C0/C1 controls, or bidi controls
236
+ */
237
+ export function safe(s) {
238
+ return stripVTControlCharacters(String(s ?? ''))
239
+ .replace(/[\x00-\x1f\x7f]/g, '')
240
+ .replace(/[\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, '');
241
+ }
242
+
243
+ /**
244
+ * Quote a path for pasting into a shell: safe spellings come back
245
+ * unchanged, anything else is single-quoted with `'` escaped.
246
+ *
247
+ * @param {string} s path to quote
248
+ * @returns {string} shell-safe spelling
249
+ */
250
+ export function shellQuote(s) {
251
+ if (/^[A-Za-z0-9_\/.,:@%+=-]+$/.test(s)) return s;
252
+ return `'` + s.replace(/'/g, `'\\''`) + `'`;
253
+ }
254
+
255
+ /**
256
+ * Every path in a runtime dir. The one place that names them.
257
+ *
258
+ * @param {string} runtime runtime dir
259
+ * @returns {{ socket: (agent: string) => string, asksDir: string, answersDir: string, askFile: (id: string) => string, answerFile: (id: string) => string, certsDir: string, caBundle: string, audit: string, owner: string, overlay: (agent: string) => { base: string, upper: string, work: string, manifest: string } }} layout
260
+ */
261
+ export function runtimePaths(runtime) {
262
+ const asksDir = path.join(runtime, 'asks');
263
+ const answersDir = path.join(runtime, 'answers');
264
+ return {
265
+ owner: path.join(runtime, 'owner'),
266
+ asksDir,
267
+ answersDir,
268
+ askFile: (id) => path.join(asksDir, `${id}.json`),
269
+ answerFile: (id) => path.join(answersDir, `${id}.json`),
270
+ /**
271
+ * The one path both sides agree on: the proxy listens here, the
272
+ * launcher binds it into the sandbox.
273
+ */
274
+ socket: (agent) => {
275
+ assertAgentName(agent);
276
+ const p = path.join(runtime, 'socks', `${agent}.sock`);
277
+ if (p.length > MAX_SOCK_PATH) {
278
+ throw new Error(`agent socket path too long (${p.length} > ${MAX_SOCK_PATH}): ${p}`);
279
+ }
280
+ return p;
281
+ },
282
+ certsDir: path.join(runtime, 'certs'),
283
+ caBundle: path.join(runtime, 'ca-bundle.pem'),
284
+ audit: path.join(runtime, 'audit.jsonl'),
285
+ overlay: (agent) => {
286
+ const base = path.join(runtime, 'overlay', agent);
287
+ return {
288
+ base,
289
+ upper: path.join(base, 'upper'),
290
+ work: path.join(base, 'work'),
291
+ manifest: path.join(base, 'manifest.json'),
292
+ };
293
+ },
294
+ };
295
+ }