@commonlyai/cli 0.1.244 → 0.1.246

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@commonlyai/cli",
3
- "version": "0.1.244",
3
+ "version": "0.1.246",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -1,5 +1,6 @@
1
1
  /** Goose 1.54.0 wrapper. Public seats expose only the Commonly MCP extension. */
2
2
  import { requireSeatModel } from './seat-model.js';
3
+ import { probeVersion } from './tested-version.js';
3
4
  import { spawn as childSpawn, spawnSync } from 'node:child_process';
4
5
  import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
5
6
  import { tmpdir } from 'node:os';
@@ -278,9 +279,12 @@ export default {
278
279
  : 'goose');
279
280
  if (isPublic && !isAbsolute(binary)) throw new Error('goose adapter: public seats require an absolute Goose executable');
280
281
  // A cold first launch can take several seconds while macOS scans the binary.
281
- const version = ctx._version || versionOf(spawnSync(binary, ['--version'], {
282
- encoding: 'utf8', timeout: 30000, env: safeEnv(sourceEnv),
283
- }).stdout);
282
+ // Async and cached per binary (tested-version.js probeVersion): a
283
+ // synchronous probe stalled every other seat's provider proxy on the
284
+ // daemon's loop for as long as this cold start took.
285
+ const version = ctx._version || await probeVersion(binary, {
286
+ env: safeEnv(sourceEnv), timeoutMs: 30000, parse: versionOf,
287
+ });
284
288
  if (!TESTED_GOOSE_VERSIONS.includes(version)) {
285
289
  if (isPublic) throw new Error(`goose adapter: public seats refuse untested version ${version || 'unknown'}`);
286
290
  // eslint-disable-next-line no-console
@@ -18,7 +18,9 @@
18
18
  */
19
19
 
20
20
  import { Type } from 'typebox';
21
- import { connectMcp, takeServers, toPiResult } from './pi-mcp-client.mjs';
21
+ import {
22
+ connectMcp, registrableTools, takeServers, toPiResult,
23
+ } from './pi-mcp-client.mjs';
22
24
 
23
25
  export default async function commonlyMcpBridge(pi) {
24
26
  // Read once and consume: the read drains the pipe, so the list (which carries
@@ -37,7 +39,8 @@ export default async function commonlyMcpBridge(pi) {
37
39
  clients.push(client);
38
40
  try {
39
41
  await client.initialize();
40
- const tools = await client.listTools();
42
+ // A public seat's entries name the tools it is not offered.
43
+ const tools = registrableTools(await client.listTools(), server);
41
44
  for (const tool of tools) {
42
45
  pi.registerTool({
43
46
  name: tool.name,
@@ -27,9 +27,9 @@ import { CREDENTIAL_FILE_VAR, CREDENTIAL_KEY } from '../credential-file.js';
27
27
 
28
28
  /**
29
29
  * The grant broker's path. wren's ruling for the daemon-side half of TASK-063:
30
- * pi confines on no host — `pi.js assertNoSandboxDeclared` refuses a DECLARED
31
- * sandbox and nothing ever derives one — so a grant broker must not reach a pi
32
- * seat by ANY route: not the server's projection (the backend refuses it there
30
+ * pi is not approved to confine a granter's authority (a public pi runs in
31
+ * Seatbelt since F113b, but grant-broker confinement is claude and codex only),
32
+ * so a grant broker must not reach a pi seat by ANY route: not the server's projection (the backend refuses it there
33
33
  * too), and not an older backend that still projects it, which is this layer's
34
34
  * job. Keyed on the PATH and not on the entry's `name`, because the name is
35
35
  * whatever the declaration says while the path is the broker's. A url that does
@@ -542,6 +542,18 @@ export const isStdioServer = (s) => Array.isArray(s?.command) && s.command.lengt
542
542
  export const isHttpServer = (s) => typeof s?.url === 'string' && s.url.length > 0
543
543
  && !(Array.isArray(s?.command) && s.command.length > 0);
544
544
 
545
+ /**
546
+ * The tools the bridge may register for one server: all of them, minus the
547
+ * entry's `withheldTools`. pi.js sets that list on a public seat
548
+ * (PUBLIC_SEAT_WITHHELD_TOOLS), so a withheld Commonly tool is never registered with
549
+ * pi at all; pi's own `--exclude-tools` removes the same names as a second
550
+ * layer.
551
+ */
552
+ export const registrableTools = (tools, server) => {
553
+ const withheld = new Set(Array.isArray(server?.withheldTools) ? server.withheldTools : []);
554
+ return withheld.size ? tools.filter((tool) => !withheld.has(tool?.name)) : tools;
555
+ };
556
+
545
557
  export const readServers = (raw) => {
546
558
  if (!raw) return [];
547
559
  try {
@@ -29,26 +29,41 @@
29
29
  * registers each tool. The token rides through the child env, never argv
30
30
  * (same rule as codex.js).
31
31
  *
32
+ * A public seat (F113b) runs the same pi as
33
+ * sandbox-exec -p <profile> <abs pi> … --no-builtin-tools
34
+ * --exclude-tools <pi built-ins + PUBLIC_SEAT_WITHHELD_TOOLS> --no-approve …
35
+ * with a scrubbed environment and the provider behind a loopback proxy. pi's
36
+ * MCP servers start inside the jailed pi (the bridge is in-process), so they
37
+ * inherit the profile. Confinement is an explicit `sandbox.trust: 'public'`,
38
+ * never a derived default: a derived one would strip the shell from every
39
+ * private fleet pi seat (default-environment.js).
40
+ *
32
41
  * Contract (see stub.js): detect() and spawn(prompt, ctx) → { text, newSessionId }.
33
42
  */
34
43
 
35
44
  import { requireSeatModel } from './seat-model.js';
45
+ import { probeVersion } from './tested-version.js';
36
46
  import { spawn as childSpawn, spawnSync } from 'child_process';
37
47
  import { createHash, randomUUID } from 'crypto';
48
+ import { accessSync, constants as fsConstants, existsSync, readFileSync, realpathSync } from 'fs';
38
49
  import { mkdir, readdir, writeFile } from 'fs/promises';
39
50
  import { homedir } from 'os';
40
- import { dirname, join } from 'path';
51
+ import { delimiter, dirname, isAbsolute, join } from 'path';
41
52
  import { fileURLToPath } from 'url';
42
53
  import {
43
54
  readUpstreamRefusal,
44
55
  spawnCredentials,
45
56
  } from '../upstream-refusal.js';
46
57
  import { buildMemoryPreamble } from '../memory-bridge.js';
47
- import { effectiveSandboxTrust, refuseWorkspaceTrust } from '../environment.js';
58
+ import { effectiveSandboxTrust, normalizeSandboxTrust, refuseWorkspaceTrust } from '../environment.js';
48
59
  import { GRANT_BROKER_REFUSAL, isGrantBrokerUrl } from './pi-mcp-client.mjs';
49
60
  import { deliverSeatCredential, withholdRuntimeCredential } from '../mcp-credential-delivery.js';
50
- import { prepareMcpSpawn } from '../mcp-home.js';
61
+ import { prepareMcpSpawn, publicMcpUnavailableError, selectedMcpVersionDir } from '../mcp-home.js';
51
62
  import { removeCredentialFile, writeCredentialFile } from '../credential-file.js';
63
+ import { resolvePublicSandboxMode } from '../sandbox/mode.js';
64
+ import { wrapArgvWithSeatbelt } from '../sandbox/seatbelt.js';
65
+ import { startProviderProxy } from '../provider-proxy.js';
66
+ import { PUBLIC_SEAT_WITHHELD_TOOLS } from '../public-withheld-tools.js';
52
67
 
53
68
  const DEFAULT_TIMEOUT_MS = (() => {
54
69
  const fallback = 15 * 60 * 1000;
@@ -71,8 +86,37 @@ export const DEFAULT_PROVIDER = Object.freeze({
71
86
  const THINKING = { none: 'off', off: 'off', minimal: 'minimal', low: 'low', medium: 'medium', high: 'high', xhigh: 'xhigh', max: 'max' };
72
87
  export const thinkingFor = (effort) => (effort ? THINKING[String(effort).toLowerCase()] || null : null);
73
88
 
74
- const BRIDGE_PATH = join(dirname(fileURLToPath(import.meta.url)), 'pi-commonly-mcp.mjs');
75
- const SHELL_ENV_PATH = join(dirname(fileURLToPath(import.meta.url)), 'pi-shell-env.mjs');
89
+ const ADAPTERS_DIR = dirname(fileURLToPath(import.meta.url));
90
+ const BRIDGE_PATH = join(ADAPTERS_DIR, 'pi-commonly-mcp.mjs');
91
+ const SHELL_ENV_PATH = join(ADAPTERS_DIR, 'pi-shell-env.mjs');
92
+ // The bridge imports siblings from the CLI's lib dir (credential-file.js,
93
+ // mcp-server-version.js), so a jailed pi must be able to read that tree. It
94
+ // holds code only.
95
+ const EXTENSION_CODE_ROOT = dirname(ADAPTERS_DIR);
96
+
97
+ // A public seat runs only a pi version whose tool flags were checked against a
98
+ // real headless turn under Seatbelt: `--no-builtin-tools`, `--exclude-tools`
99
+ // (which removes a tool from pi's registry, extension tools included, not only
100
+ // from the active set) and `--no-approve`. Add a version only with that smoke.
101
+ export const TESTED_PI_VERSIONS = Object.freeze(['0.84.1']);
102
+ const PI_PACKAGE = '@earendil-works/pi-coding-agent';
103
+
104
+ // pi's built-in tools (`allToolNames`, core/tools/index.js in 0.84). A public
105
+ // seat gets none of them: no shell, and no file reads either, because the jail
106
+ // has to admit the seat home that holds this turn's credential file (the bridge
107
+ // reads it), so a read tool could hand that file to the room. Every public
108
+ // adapter denies its shell; Qwen denies its read tools for this same reason,
109
+ // and Goose loads no built-in at all.
110
+ export const PI_BUILTIN_TOOLS = Object.freeze(['read', 'bash', 'edit', 'write', 'grep', 'find', 'ls']);
111
+ export const PUBLIC_EXCLUDED_TOOLS = Object.freeze([...PI_BUILTIN_TOOLS, ...PUBLIC_SEAT_WITHHELD_TOOLS]);
112
+
113
+ // What a public pi inherits from the launcher's environment. Everything else
114
+ // (operator variables, the real provider key, the seat token) stays out.
115
+ const PUBLIC_SAFE_ENV = /^(?:PATH|LANG|LC_[A-Z_]+|TERM|USER|LOGNAME|NO_COLOR|CI|SSL_CERT_FILE|SSL_CERT_DIR)$/;
116
+ const safeEnv = (env) => Object.fromEntries(Object.entries(env).filter(([name]) => PUBLIC_SAFE_ENV.test(name)));
117
+
118
+ // The one provider API the loopback proxy carries for pi.
119
+ const PUBLIC_PROVIDER_API = 'openai-completions';
76
120
 
77
121
  // Same substitution contract as claude.js / codex.js: ${COMMONLY_*}
78
122
  // placeholders in the declared MCP env are the wrapper's per-(agent, pod)
@@ -151,8 +195,8 @@ const originOf = (value) => {
151
195
  * the guard both admit) is refused rather than reinterpreted as one it can.
152
196
  *
153
197
  * The grant broker is refused outright, by PATH rather than by entry name: it is
154
- * the one http entry that carries authority rather than data, and pi confines on
155
- * no host. The ruling for TASK-063 (`isGrantBrokerUrl` in pi-mcp-client.mjs),
198
+ * the one http entry that carries authority rather than data, and pi is not
199
+ * approved to confine it. The ruling for TASK-063 (`isGrantBrokerUrl` in pi-mcp-client.mjs),
156
200
  * the daemon-side half of the same refusal the server makes at the projection —
157
201
  * this is the half that holds on deploy skew, when the row names no adapter for
158
202
  * the server to key on, and in any backend older than the refusal.
@@ -179,21 +223,24 @@ export const resolveMcpServers = (mcpServers, ctx = {}) => {
179
223
  continue;
180
224
  }
181
225
  // The grant broker is the one http entry that carries AUTHORITY rather
182
- // than data: a granted seat acts on external systems as the granter. A pi
183
- // seat cannot be confined on any host (see assertNoSandboxDeclared), so
184
- // the reach is refused here as well as at the server's projection — this
226
+ // than data: a granted seat acts on external systems as the granter. pi is
227
+ // not admitted to grant-broker confinement (ADAPTERS_WITH_GRANT_BROKER is
228
+ // claude and codex; a public pi's Seatbelt jail, F113b, has not been
229
+ // reviewed for that), so the reach is refused here as well as at the
230
+ // server's projection — this
185
231
  // layer is what holds when the backend predates that refusal, when the
186
232
  // row names no adapter for the server to key on, or when a deploy leaves
187
233
  // the two on different clocks.
188
234
  if (isGrantBrokerUrl(url)) {
189
235
  // eslint-disable-next-line no-console
190
- console.warn(`[pi] ${GRANT_BROKER_REFUSAL} — refusing the grant broker '${server.name}': pi has no enforced sandbox, so this seat must not act with a granter's authority — move the seat to the claude or codex adapter, or remove the grant`);
236
+ console.warn(`[pi] ${GRANT_BROKER_REFUSAL} — refusing the grant broker '${server.name}': pi is not approved to confine a granter's authority, so this seat must not act with it — move the seat to the claude or codex adapter, or remove the grant`);
191
237
  continue;
192
238
  }
193
239
  carried.push({
194
240
  name: server.name,
195
241
  url,
196
242
  headers: Object.fromEntries(Object.entries(server.headers || {}).map(([k, v]) => [k, substitutePlaceholders(v, ctx)])),
243
+ ...(ctx.publicSeat ? { withheldTools: [...PUBLIC_SEAT_WITHHELD_TOOLS] } : {}),
197
244
  });
198
245
  continue;
199
246
  }
@@ -211,7 +258,18 @@ export const resolveMcpServers = (mcpServers, ctx = {}) => {
211
258
  // TASK-174: what will EXECUTE — the warmed build from the seat's MCP home
212
259
  // when there is one — and the credential channel is decided on that same
213
260
  // command, so the two can never disagree about which release runs.
214
- const spawnCommand = prepareMcpSpawn(server.command, { apiUrl: ctx.instanceUrl });
261
+ const spawnCommand = prepareMcpSpawn(server.command, { apiUrl: ctx.instanceUrl, publicSeat: Boolean(ctx.publicSeat) });
262
+ // A public seat never runs a package runner (npx) from inside the jail; the
263
+ // host-prepared build is the only stdio Commonly server it may start, and
264
+ // that build's tree has to be readable inside the profile.
265
+ if (!spawnCommand) {
266
+ ctx.unavailableMcp?.push(server.name);
267
+ continue;
268
+ }
269
+ if (ctx.publicSeat) {
270
+ const versionDir = selectedMcpVersionDir(spawnCommand);
271
+ if (versionDir) ctx.mcpReadDirectories?.push(versionDir);
272
+ }
215
273
  carried.push({
216
274
  name: server.name,
217
275
  command: spawnCommand.map((a) => substitutePlaceholders(a, ctx)),
@@ -223,6 +281,7 @@ export const resolveMcpServers = (mcpServers, ctx = {}) => {
223
281
  label: 'pi',
224
282
  }).env,
225
283
  ).map(([k, v]) => [k, substitutePlaceholders(v, ctx)])),
284
+ ...(ctx.publicSeat ? { withheldTools: [...PUBLIC_SEAT_WITHHELD_TOOLS] } : {}),
226
285
  });
227
286
  continue;
228
287
  }
@@ -264,11 +323,21 @@ export const buildModelsJson = (provider, model) => ({
264
323
  },
265
324
  });
266
325
 
267
- /** Per-seat pi home: `~/.commonly/pi-homes/<hash(agent)>`. Never the operator's ~/.pi. */
268
- export const seatHome = (ctx) => {
326
+ /**
327
+ * Per-seat pi home: `~/.commonly/pi-homes/<hash(agent)>`. Never the operator's ~/.pi.
328
+ *
329
+ * A public turn gets its own sibling, `<hash>-public`. The home holds the
330
+ * seat's sessions, so a shared one let a seat switched from private to public
331
+ * resume a session full of private history: the wrapper hands back the id it
332
+ * persisted, and `sessionExists` found it. In a separate home that id is not
333
+ * found and the public turn starts fresh; and the Seatbelt profile admits only
334
+ * the public home, so the private one is not readable from inside either.
335
+ */
336
+ export const seatHome = (ctx, { publicSeat = false } = {}) => {
269
337
  const identity = ctx.agentName || ctx.cwd || 'anonymous';
270
338
  const hash = createHash('sha256').update(identity).digest('hex').slice(0, 20);
271
- return ctx._piHome || join(homedir(), '.commonly', 'pi-homes', hash);
339
+ const base = ctx._piHome || join(homedir(), '.commonly', 'pi-homes', hash);
340
+ return publicSeat ? `${base}-public` : base;
272
341
  };
273
342
 
274
343
  /**
@@ -290,32 +359,81 @@ export const sessionExists = async (sessionDir, sessionId) => {
290
359
  };
291
360
 
292
361
  /**
293
- * Fail closed: pi cannot enforce `environment.sandbox`, so a seat that declares
294
- * one does not start.
362
+ * What pi can enforce: a public seat, confined by Seatbelt on macOS (F113b),
363
+ * and nothing else.
295
364
  *
296
365
  * The trust is read THROUGH the legacy table (`effectiveSandboxTrust`), not
297
- * raw. A stored `internal` means `public` and every
298
- * other gate in this package resolves it that way: the attach path
299
- * (`agent.js`), the mode resolver (`sandbox/mode.js`) and the grant-broker
300
- * guard. Reading it raw here made this gate the one site that failed OPEN — a
301
- * legacy record passed both checks and the seat started unconfined, which is
302
- * the exact outcome that was refused for the record it was migrated from.
303
- * The mode clause needs no mapping: `internal` and the derived mode are
304
- * independent, and a public-meaning record is refused before the mode is read.
366
+ * raw. A stored `internal` means `public` and every other gate in this package
367
+ * resolves it that way: the attach path (`agent.js`), the mode resolver
368
+ * (`sandbox/mode.js`) and the grant-broker guard. Reading it raw here once made
369
+ * this gate the one site that failed OPEN (TASK-114).
370
+ *
371
+ * Seatbelt only. pi has no bwrap path yet, so a public seat off macOS, or one
372
+ * that names `bwrap`, is refused rather than run unconfined. A non-public seat
373
+ * that declares a mode is refused too: nothing would enforce it.
305
374
  */
306
- export const assertNoSandboxDeclared = (environment = {}) => {
375
+ export const assertSandboxSupported = (environment = {}, platform = process.platform) => {
307
376
  const sandbox = environment?.sandbox || {};
308
377
  refuseWorkspaceTrust(sandbox, 'pi');
309
378
  if (effectiveSandboxTrust(sandbox.trust) === 'public') {
310
- throw new Error('pi adapter: public-trust seats are not supported — pi has no enforced sandbox; do not attach a pi seat to a stranger-readable pod');
379
+ const mode = resolvePublicSandboxMode(sandbox, platform);
380
+ if (!['workspace', 'read-only', 'bwrap'].includes(mode)) {
381
+ throw new Error('pi adapter: public seats require an enforced sandbox');
382
+ }
383
+ if (platform !== 'darwin' || mode === 'bwrap') {
384
+ throw new Error('pi adapter: public seats run only in the macOS Seatbelt sandbox; pi has no bwrap path yet, so this seat cannot run confined here');
385
+ }
386
+ if (sandbox.filesystem?.['read-outside']?.length) {
387
+ throw new Error('pi adapter: public seats do not allow sandbox.filesystem.read-outside');
388
+ }
389
+ if (sandbox.network?.policy === 'restricted') {
390
+ throw new Error('pi adapter: public seats do not support restricted networking');
391
+ }
392
+ return;
311
393
  }
312
394
  if (sandbox.mode && sandbox.mode !== 'none') {
313
- throw new Error(`pi adapter: sandbox.mode=${sandbox.mode} cannot be enforced by pi; remove it or use the claude/codex adapter`);
395
+ throw new Error(`pi adapter: sandbox.mode=${sandbox.mode} cannot be enforced by pi without public trust; declare sandbox.trust 'public' or remove the mode`);
314
396
  }
315
397
  };
316
398
 
399
+ /** The first executable `name` on PATH, absolute, or null. No shell involved. */
400
+ export const resolveOnPath = (name, pathValue) => {
401
+ for (const dir of String(pathValue || '').split(delimiter)) {
402
+ if (!dir || !isAbsolute(dir)) continue;
403
+ const candidate = join(dir, name);
404
+ try {
405
+ accessSync(candidate, fsConstants.X_OK);
406
+ return candidate;
407
+ } catch { /* next */ }
408
+ }
409
+ return null;
410
+ };
411
+
412
+ /**
413
+ * pi's install tree: the nearest directory above the real entry file whose
414
+ * package.json names pi. Its `node_modules` and dist are what a jailed pi loads,
415
+ * and nothing else under that prefix needs to be readable.
416
+ */
417
+ export const piPackageRoot = (binary) => {
418
+ let dir;
419
+ try { dir = dirname(realpathSync(binary)); } catch { return null; }
420
+ for (;;) {
421
+ const manifest = join(dir, 'package.json');
422
+ if (existsSync(manifest)) {
423
+ try {
424
+ if (JSON.parse(readFileSync(manifest, 'utf8')).name === PI_PACKAGE) return dir;
425
+ } catch { /* keep walking */ }
426
+ }
427
+ const parent = dirname(dir);
428
+ if (parent === dir) return null;
429
+ dir = parent;
430
+ }
431
+ };
432
+
433
+ const versionOf = (value) => String(value || '').trim().match(/\b(\d+\.\d+\.\d+)\b/)?.[1] || null;
434
+
317
435
  export const buildArgs = ({
318
- prompt, provider, model, thinking, sessionId, isResume, sessionDir, bridge,
436
+ prompt, provider, model, thinking, sessionId, isResume, sessionDir, bridge, publicSeat = false,
319
437
  }) => [
320
438
  '-p',
321
439
  '--mode', 'json',
@@ -323,6 +441,10 @@ export const buildArgs = ({
323
441
  '--no-skills',
324
442
  '--no-prompt-templates',
325
443
  '--no-themes',
444
+ // A public seat: no built-in tool (no shell, no file access), the withheld
445
+ // Commonly tools removed from the registry, and no project-local pi files
446
+ // from the workspace trusted for this run.
447
+ ...(publicSeat ? ['--no-builtin-tools', '--exclude-tools', PUBLIC_EXCLUDED_TOOLS.join(','), '--no-approve'] : []),
326
448
  '--provider', provider,
327
449
  '--model', model,
328
450
  ...(thinking ? ['--thinking', thinking] : []),
@@ -350,14 +472,14 @@ export const extractReply = (stdout) => {
350
472
  return { text, sawAssistant, errors };
351
473
  };
352
474
 
353
- const runPi = ({ args, cwd, env, payload, timeoutMs, credentials = [], spawnImpl = childSpawn }) => new Promise((resolve, reject) => {
475
+ const runPi = ({ command = 'pi', args, cwd, env, payload, timeoutMs, credentials = [], spawnImpl = childSpawn }) => new Promise((resolve, reject) => {
354
476
  let stdout = '';
355
477
  let stderr = '';
356
478
  let timedOut = false;
357
479
  // fd 3 carries the MCP server list, so the 4th pipe exists exactly when there
358
480
  // is a list to hand over. The bridge reads it at extension load (takeServers).
359
481
  const withList = typeof payload === 'string';
360
- const proc = spawnImpl('pi', args, { cwd, env, stdio: withList ? ['ignore', 'pipe', 'pipe', 'pipe'] : ['ignore', 'pipe', 'pipe'] });
482
+ const proc = spawnImpl(command, args, { cwd, env, stdio: withList ? ['ignore', 'pipe', 'pipe', 'pipe'] : ['ignore', 'pipe', 'pipe'] });
361
483
  if (withList) {
362
484
  const channel = proc.stdio && proc.stdio[3];
363
485
  // A missing pipe is an invariant break, not a degraded mode: the bridge would
@@ -401,6 +523,12 @@ export default {
401
523
  // daemon level.
402
524
  providerKeyEnv: DEFAULT_PROVIDER.apiKeyEnv,
403
525
 
526
+ // Attach runs this before anything is published, so a public pi seat this
527
+ // host cannot confine is refused there rather than at its first turn.
528
+ async validateEnvironment(environment) {
529
+ assertSandboxSupported(environment);
530
+ },
531
+
404
532
  async detect() {
405
533
  const res = spawnSync('pi', ['--version'], { encoding: 'utf8' });
406
534
  if (res.error || res.status !== 0) return null;
@@ -411,10 +539,12 @@ export default {
411
539
 
412
540
  async spawn(prompt, ctx = {}) {
413
541
  const seatModel = requireSeatModel(ctx.environment, 'pi', true);
414
- // pi has no enforced sandbox. claude.js and codex.js refuse a public-trust
415
- // seat they cannot confine; so does this adapter, and it refuses any declared
416
- // sandbox mode rather than run unconfined under a spec that promised one.
417
- assertNoSandboxDeclared(ctx.environment);
542
+ const platform = ctx._platform || process.platform;
543
+ // A public seat is confined by Seatbelt below; every sandbox declaration pi
544
+ // cannot honour on this host is refused here, before anything starts.
545
+ assertSandboxSupported(ctx.environment, platform);
546
+ const sandbox = normalizeSandboxTrust(ctx.environment?.sandbox);
547
+ const isPublic = effectiveSandboxTrust(sandbox?.trust) === 'public';
418
548
  const provider = resolveProvider(ctx.environment);
419
549
  const model = seatModel;
420
550
  const thinking = thinkingFor(ctx.environment?.effort);
@@ -422,6 +552,38 @@ export default {
422
552
  if (!baseEnv[provider.apiKeyEnv]) {
423
553
  throw new Error(`pi adapter: ${provider.apiKeyEnv} is not set — the seat's environment must carry the provider key (LiteLLM virtual key)`);
424
554
  }
555
+
556
+ // What a public turn runs inside the jail: the absolute pi entry, the
557
+ // package tree it loads, and the node its shebang resolves to.
558
+ let binary = 'pi';
559
+ let packageRoot = null;
560
+ let nodePath = null;
561
+ if (isPublic) {
562
+ if (provider.api !== PUBLIC_PROVIDER_API) {
563
+ throw new Error(`pi adapter: a public seat reaches its provider through a loopback proxy that carries the ${PUBLIC_PROVIDER_API} API only, not ${provider.api}`);
564
+ }
565
+ if (!ctx.cwd || !isAbsolute(ctx.cwd)) {
566
+ throw new Error('pi adapter: a public seat needs an absolute workspace path');
567
+ }
568
+ binary = ctx._binaryPath || resolveOnPath('pi', baseEnv.PATH);
569
+ if (!binary || !isAbsolute(binary)) {
570
+ throw new Error('pi adapter: a public seat needs an absolute pi executable on PATH');
571
+ }
572
+ packageRoot = piPackageRoot(binary);
573
+ if (!packageRoot) {
574
+ throw new Error(`pi adapter: no ${PI_PACKAGE} package found behind ${binary}, so the sandbox cannot admit pi's code`);
575
+ }
576
+ // Async and cached per binary (tested-version.js): a synchronous probe
577
+ // stalled every other seat's proxy on the daemon's loop.
578
+ const version = ctx._version || await probeVersion(binary, {
579
+ env: safeEnv(baseEnv), timeoutMs: 30000, parse: versionOf,
580
+ });
581
+ if (!TESTED_PI_VERSIONS.includes(version)) {
582
+ throw new Error(`pi adapter: public seats refuse untested pi version ${version || 'unknown'}; smoke-tested: ${TESTED_PI_VERSIONS.join(', ')}`);
583
+ }
584
+ nodePath = resolveOnPath('node', baseEnv.PATH);
585
+ }
586
+
425
587
  // The values this spawn is handed, for the refusal log's exact-match check:
426
588
  // the provider key the route authenticates with, and the seat credential the
427
589
  // bridge carries. Snapshot them HERE — `withholdRuntimeCredential` removes
@@ -430,33 +592,70 @@ export default {
430
592
  const credentials = spawnCredentials(ctx, [provider.apiKeyEnv]);
431
593
 
432
594
  // Per-seat pi home: models.json holds the provider by env reference.
433
- const home = seatHome(ctx);
595
+ const home = seatHome(ctx, { publicSeat: isPublic });
434
596
  const agentDir = join(home, 'agent');
435
597
  const sessionDir = join(home, 'sessions');
436
598
  await mkdir(agentDir, { recursive: true, mode: 0o700 });
437
599
  await mkdir(sessionDir, { recursive: true, mode: 0o700 });
600
+ if (isPublic) await mkdir(join(home, 'tmp'), { recursive: true, mode: 0o700 });
438
601
 
439
602
  // Resume only what pi wrote; anything else (a codex thread id from before
440
603
  // the switch, a wiped home) starts fresh under a new id.
441
604
  const isResume = await sessionExists(sessionDir, ctx.sessionId);
442
605
  const sessionId = isResume ? ctx.sessionId : randomUUID();
443
- const fullPrompt = buildMemoryPreamble(prompt, ctx.memoryLongTerm, { freshSession: !isResume });
444
- await writeFile(join(agentDir, 'models.json'), `${JSON.stringify(buildModelsJson(provider, model), null, 2)}\n`, { mode: 0o600 });
606
+ // F118: a public seat reads its memory but is not offered the save tool,
607
+ // so its preamble names none.
608
+ const fullPrompt = buildMemoryPreamble(prompt, ctx.memoryLongTerm, {
609
+ freshSession: !isResume, memoryReadOnly: isPublic,
610
+ });
445
611
 
446
- // One credential file per spawn, inside this seat's own 0700 home — pi has no
447
- // enforced sandbox, so the seat's home is the narrowest place that is still
448
- // readable by the bridge. The value the server receives still travels on fd 3
449
- // (pi-mcp-client's fd channel); the file is where the launcher puts it.
612
+ // One credential file per spawn, inside this seat's own 0700 home: the
613
+ // narrowest place the bridge can still read. On a public seat that home is
614
+ // the jail's state directory, which is why pi gets no read tool there. The
615
+ // value the server receives still travels on fd 3 (pi-mcp-client's fd
616
+ // channel); the file is where the launcher puts it.
450
617
  const credential = writeCredentialFile(ctx.runtimeToken, {
451
618
  agentName: ctx.agentName || 'agent',
452
619
  root: join(home, 'credentials'),
453
620
  });
621
+ let proxy = null;
454
622
  try {
623
+ // A public pi never holds the provider key: it talks to a loopback proxy
624
+ // with a per-turn token, and the proxy, in this process, adds the key and
625
+ // pins the model (the same shape as Goose and Qwen).
626
+ if (isPublic) {
627
+ proxy = await (ctx._startProviderProxy || startProviderProxy)({
628
+ provider: { baseURL: provider.baseUrl },
629
+ keyMaterial: baseEnv[provider.apiKeyEnv],
630
+ adapterLabel: 'pi',
631
+ pinnedModel: model,
632
+ });
633
+ }
634
+ await writeFile(join(agentDir, 'models.json'), `${JSON.stringify(buildModelsJson(
635
+ proxy ? { ...provider, baseUrl: proxy.baseURL } : provider, model,
636
+ ), null, 2)}\n`, { mode: 0o600 });
637
+
638
+ const unavailableMcp = [];
639
+ const mcpReadDirectories = [];
455
640
  const servers = resolveMcpServers(ctx.environment?.mcp, {
456
641
  ...ctx,
457
642
  credentialFile: credential?.path || null,
643
+ publicSeat: isPublic,
644
+ unavailableMcp,
645
+ mcpReadDirectories,
458
646
  });
459
- const childEnv = {
647
+ if (unavailableMcp.length) throw publicMcpUnavailableError(unavailableMcp);
648
+ const childEnv = isPublic ? {
649
+ // A scrubbed environment: nothing of the operator's crosses into the
650
+ // jail, and the provider variable holds the proxy's token, not the key.
651
+ ...safeEnv(baseEnv),
652
+ HOME: home,
653
+ TMPDIR: join(home, 'tmp'),
654
+ PI_CODING_AGENT_DIR: agentDir,
655
+ PI_SKIP_VERSION_CHECK: '1',
656
+ PI_OFFLINE: '1',
657
+ [provider.apiKeyEnv]: proxy.token,
658
+ } : {
460
659
  ...baseEnv,
461
660
  PI_CODING_AGENT_DIR: agentDir,
462
661
  PI_SKIP_VERSION_CHECK: '1',
@@ -477,17 +676,42 @@ export default {
477
676
  const args = buildArgs({
478
677
  prompt: fullPrompt, provider: provider.name, model, thinking, sessionId, isResume, sessionDir,
479
678
  bridge: servers.length ? (ctx._bridgePath || BRIDGE_PATH) : null,
679
+ publicSeat: isPublic,
480
680
  });
481
- // Shell isolation must not depend on whether this turn declares MCP.
482
- args.splice(args.length - 1, 0, '-e', SHELL_ENV_PATH);
681
+ // Shell isolation must not depend on whether this turn declares MCP. A
682
+ // public turn has no shell at all, so it loads no shell extension (that
683
+ // extension registers a `bash` tool of its own).
684
+ if (!isPublic) args.splice(args.length - 1, 0, '-e', SHELL_ENV_PATH);
685
+
686
+ // The public jail wraps pi itself. The bridge is an in-process pi
687
+ // extension, so every MCP server it starts is a child of the jailed
688
+ // process, and a Seatbelt profile is inherited across fork and exec: there
689
+ // is no second spawn here, and nothing pi launches runs outside it.
690
+ let command = 'pi';
691
+ let spawnArgs = args;
692
+ if (isPublic) {
693
+ [command, ...spawnArgs] = (ctx._wrapArgvWithSeatbelt || wrapArgvWithSeatbelt)([binary, ...args], {
694
+ workspacePath: ctx.cwd,
695
+ workspaceAccess: resolvePublicSandboxMode(sandbox, platform) === 'read-only' ? 'read' : 'write',
696
+ executablePath: binary,
697
+ executablePaths: nodePath ? [nodePath] : [],
698
+ statePath: home,
699
+ loopbackNetworkPorts: [proxy.port],
700
+ readOnlyDirectories: [packageRoot, EXTENSION_CODE_ROOT, ...mcpReadDirectories],
701
+ // The jailed pi holds the seat token in memory (the bridge reads it),
702
+ // so nothing it starts may inspect it.
703
+ processInfo: 'self',
704
+ });
705
+ }
483
706
 
484
707
  const reply = await runPi({
485
- args,
708
+ command,
709
+ args: spawnArgs,
486
710
  cwd: ctx.cwd,
487
711
  env: childEnv,
488
712
  payload: servers.length ? JSON.stringify(servers) : undefined,
489
713
  timeoutMs: ctx.timeoutMs || DEFAULT_TIMEOUT_MS,
490
- credentials,
714
+ credentials: proxy ? [...credentials, proxy.token] : credentials,
491
715
  spawnImpl: ctx._spawnImpl, // test seam only — do not use in production
492
716
  });
493
717
  // Empty text with a clean exit is a silent turn; the run loop treats it
@@ -499,6 +723,7 @@ export default {
499
723
  // turn ends, and a token file that outlives its turn is a token file that
500
724
  // sits in a home for the next one.
501
725
  removeCredentialFile(credential);
726
+ try { await proxy?.close(); } catch { /* best effort */ }
502
727
  }
503
728
  },
504
729
  };
@@ -1,6 +1,7 @@
1
1
  /** Qwen Code 0.25.1 and 0.26.2 wrapper. Public turns have fresh HOME, config and keys. */
2
2
  import { requireSeatModel } from './seat-model.js';
3
- import { isPatchAfterNewestTested } from './tested-version.js';
3
+ import { isPatchAfterNewestTested, probeVersion } from './tested-version.js';
4
+ import * as childProcess from 'child_process';
4
5
  import { spawn as childSpawn, spawnSync } from 'child_process';
5
6
  import { lstatSync, realpathSync } from 'fs';
6
7
  import { chmod, mkdtemp, readFile, rm, writeFile } from 'fs/promises';
@@ -50,10 +51,13 @@ const parseVersion = (output) => {
50
51
  return match ? match[1] : null;
51
52
  };
52
53
 
53
- const readVersion = (binary, env) => {
54
- const result = spawnSync(binary, ['--version'], { encoding: 'utf8', env, timeout: 5000 });
55
- return result.status === 0 && !result.error ? parseVersion(result.stdout) : null;
56
- };
54
+ // Async and cached per binary (tested-version.js probeVersion): a synchronous
55
+ // probe stalled every other seat's provider proxy on the daemon's loop. The
56
+ // namespace import is read at call time, so a suite that mocks child_process
57
+ // without execFile falls back to the real one.
58
+ const readVersion = (binary, env) => probeVersion(binary, {
59
+ env, timeoutMs: 5000, parse: parseVersion, execFileImpl: childProcess.execFile,
60
+ });
57
61
 
58
62
  const resolvedBinary = (env) => {
59
63
  const where = spawnSync('which', ['qwen'], { encoding: 'utf8', env });
@@ -75,7 +79,8 @@ const withProbeEnv = async (source, run) => {
75
79
  env.QWEN_CODE_SYSTEM_SETTINGS_PATH = settingsPath;
76
80
  env.QWEN_USAGE_STATISTICS_ENABLED = 'false';
77
81
  for (const name of PROXY_ENV) env[name] = '';
78
- return run(env);
82
+ // Awaited here, so the probe home outlives an async probe.
83
+ return await run(env);
79
84
  } finally {
80
85
  await rm(home, { recursive: true, force: true });
81
86
  }
@@ -254,9 +259,9 @@ export default {
254
259
  }
255
260
  const keyFile = await this.validateEnvironment(ctx.environment, ctx.cwd);
256
261
  const sourceEnv = ctx.env || process.env;
257
- const { binary, version } = await withProbeEnv(sourceEnv, (probeEnv) => {
262
+ const { binary, version } = await withProbeEnv(sourceEnv, async (probeEnv) => {
258
263
  const path = ctx._binaryPath || resolvedBinary(probeEnv);
259
- return { binary: path, version: readVersion(path, probeEnv) };
264
+ return { binary: path, version: await readVersion(path, probeEnv) };
260
265
  });
261
266
  if (!TESTED_QWEN_VERSIONS.includes(version)) {
262
267
  const versions = TESTED_QWEN_VERSIONS.join(', ');
@@ -1,3 +1,8 @@
1
+ // A namespace import, read at call time: suites that mock child_process with
2
+ // only spawn/spawnSync still load this module.
3
+ import * as childProcess from 'node:child_process';
4
+ import { realpathSync, statSync } from 'node:fs';
5
+
1
6
  // Public seats run only on a harness version smoke-tested in its sandbox, with
2
7
  // one tolerance: a stable patch release after the newest tested one, on that
3
8
  // same major.minor line. Harnesses ship patches every few days, and refusing
@@ -14,3 +19,36 @@ export const isPatchAfterNewestTested = (version, tested) => {
14
19
  && Number(installed[2]) === Number(newest[2])
15
20
  && Number(installed[3]) > Number(newest[3]);
16
21
  };
22
+
23
+ // The harness's own `--version`, asked without blocking the event loop and
24
+ // remembered per binary. A daemon runs every seat in one process, beside the
25
+ // loopback provider proxies of other seats' live turns, so a synchronous probe
26
+ // stalled all of them while a cold harness started (up to its timeout).
27
+ //
28
+ // The cache key is the binary's real path; its mtime decides freshness, so a
29
+ // harness upgraded in place is probed again. Only a parsed version is kept: a
30
+ // failed or unparseable probe is asked again next turn, never remembered.
31
+ const versionCache = new Map();
32
+
33
+ export const probeVersion = async (binary, {
34
+ env, timeoutMs = 30000, parse, execFileImpl = childProcess.execFile, cache = versionCache,
35
+ } = {}) => {
36
+ let key = null;
37
+ let mtimeMs = null;
38
+ try {
39
+ key = realpathSync(binary);
40
+ mtimeMs = statSync(key).mtimeMs;
41
+ } catch {
42
+ key = null;
43
+ }
44
+ const hit = key ? cache.get(key) : null;
45
+ if (hit && hit.mtimeMs === mtimeMs) return hit.version;
46
+ const stdout = await new Promise((resolve) => {
47
+ execFileImpl(binary, ['--version'], { encoding: 'utf8', env, timeout: timeoutMs }, (error, out) => {
48
+ resolve(error ? null : out);
49
+ });
50
+ });
51
+ const version = stdout === null ? null : parse(stdout);
52
+ if (version && key) cache.set(key, { mtimeMs, version });
53
+ return version;
54
+ };
@@ -31,31 +31,26 @@ import { normalizeSandboxTrust } from './environment.js';
31
31
  export const ADAPTERS_WITH_DEFAULT_MCP = new Set(['claude', 'codex', 'pi', 'opencode', 'qwen', 'dsh', 'goose']);
32
32
 
33
33
  /**
34
- * The adapters that can ENFORCE the default sandbox — a strict subset of the
35
- * ones that consume `mcp[]`.
34
+ * The adapters that take the default sandbox — a strict subset of the ones that
35
+ * consume `mcp[]`, and of the ones that enforce a sandbox (below).
36
36
  *
37
- * `pi` is absent deliberately: it cannot enforce the declared sandbox.
38
- * Goose uses Seatbelt/bwrap and exposes only its prepared Commonly MCP extension.
39
- * `pi` has no sandbox path until #1740's transport
40
- * work gives it one, and since #1727 it REFUSES TO START on a spec that
41
- * declares one: `assertNoSandboxDeclared` in adapters/pi.js throws on an
42
- * effective `trust: 'public'` (a legacy `internal` resolves to it) and on any
43
- * `mode` other than 'none'. So handing pi this
44
- * block is not a harmless no-op — it is an unspawnable seat. A pi seat gets the
45
- * `mcp[]` half only, and the residual is that such a seat runs unconfined: that
46
- * belongs to the row that owns pi confinement, not to a declaration written
47
- * here and hoped for. A derived pi seat used to be exactly this shape and would
48
- * have failed every spawn with `public-trust seats are not supported`.
37
+ * Goose and pi enforce an explicitly declared public sandbox but are not handed
38
+ * this default. Goose: a default cannot supply its required provider and model.
39
+ * pi (F113b): a public pi turn has no shell and no file tools, the same as every
40
+ * public adapter, and the daemon derives pi's environment for the private fleet
41
+ * seats that write code with exactly those tools. A derived public default would
42
+ * strip them from every one of those seats. A pi seat that takes instructions
43
+ * from strangers declares `sandbox.trust: 'public'` and is confined then.
49
44
  */
50
45
  export const ADAPTERS_WITH_DEFAULT_SANDBOX = new Set(['claude', 'codex', 'opencode', 'qwen']);
51
46
 
52
47
  // Adapters that confine a public turn themselves. This is wider than the set
53
- // above: Goose enforces Seatbelt/bwrap but is not handed the default block,
54
- // because a default cannot supply its required provider and model. The attach
55
- // gate (agent.js resolveAttachSandbox) reads this set, not the default one, or
56
- // an explicitly configured public Goose seat is refused before its adapter runs
57
- // (D247 walk, 11-04). pi stays out until it has a sandbox path.
58
- export const ADAPTERS_WITH_SANDBOX_ENFORCEMENT = new Set([...ADAPTERS_WITH_DEFAULT_SANDBOX, 'goose']);
48
+ // above: Goose enforces Seatbelt/bwrap and pi enforces Seatbelt (macOS only;
49
+ // adapters/pi.js), and neither is handed the default block (see above). The
50
+ // attach gate (agent.js resolveAttachSandbox) reads this set, not the default
51
+ // one, or an explicitly configured public Goose or pi seat is refused before its
52
+ // adapter runs (D247 walk, 11-04; F113b).
53
+ export const ADAPTERS_WITH_SANDBOX_ENFORCEMENT = new Set([...ADAPTERS_WITH_DEFAULT_SANDBOX, 'goose', 'pi']);
59
54
 
60
55
  // The server has not yet admitted OpenCode to its grant-broker confinement
61
56
  // allowlist. Keep runtime sandbox support separate from the narrower set of
@@ -84,12 +79,10 @@ export const ADAPTERS_WITH_GRANT_BROKER = new Set(['claude', 'codex']);
84
79
  * An explicit mode in a record still wins over the derived one.
85
80
  *
86
81
  * Claude, codex, opencode and qwen receive this default block
87
- * (ADAPTERS_WITH_DEFAULT_SANDBOX). Goose supports explicitly configured public
88
- * confinement, but defaults cannot supply its required provider and model.
82
+ * (ADAPTERS_WITH_DEFAULT_SANDBOX). Goose and pi support explicitly configured
83
+ * public confinement, but are not defaulted into it (see the set's comment).
89
84
  * Grant-broker eligibility is
90
85
  * narrower until the server admits OpenCode after its confinement proof.
91
- * A pi seat must never be handed this block: it fails closed on a declared
92
- * sandbox rather than run under a spec it cannot honour.
93
86
  */
94
87
  export const COMMONLY_DEFAULT_SANDBOX = Object.freeze({ trust: 'public' });
95
88
 
@@ -9,11 +9,10 @@
9
9
  * the pod saw nothing.
10
10
  *
11
11
  * Only the adapters that run inside these mechanisms are checked. Codex
12
- * confines with its own permission profiles (mode.js). pi is a scope boundary,
13
- * not a gap in this check: it refuses a declared sandbox itself, so a
14
- * Connect-page pi seat is saved without one and runs unconfined
15
- * (default-environment.js, ADAPTERS_WITH_DEFAULT_SANDBOX); confining pi
16
- * belongs to pi's own sandbox work.
12
+ * confines with its own permission profiles (mode.js). pi confines an
13
+ * explicitly public seat with Seatbelt and refuses one it cannot confine at
14
+ * attach (validateEnvironment) and at spawn (adapters/pi.js); a Connect-page pi
15
+ * seat declares no sandbox and is not checked here.
17
16
  */
18
17
 
19
18
  import { normalizeSandboxTrust } from '../environment.js';
@@ -390,6 +390,12 @@ export const buildSeatbeltProfile = ({
390
390
  // workspace seat granted write keeps its project's .git read-only, so every
391
391
  // change it makes is one `git status` shows the person (TASK-294).
392
392
  readOnlyWorkspaceEntries = [],
393
+ // Whose process information a jailed process may read: 'same-sandbox' (the
394
+ // baseline) or 'self'. 'self' stops a child from inspecting its jailed parent
395
+ // (lsof/proc_pidinfo: open files, cwd), which matters when that parent holds
396
+ // a seat credential in memory, as a public pi does. Signals are not narrowed:
397
+ // a parent must still stop the children it started.
398
+ processInfo = 'same-sandbox',
393
399
  }) => {
394
400
  for (const [path, label] of [
395
401
  [workspacePath, 'workspacePath'],
@@ -406,6 +412,9 @@ export const buildSeatbeltProfile = ({
406
412
  throw new Error('Seatbelt loopbackNetworkPorts entries must be valid TCP ports');
407
413
  }
408
414
  }
415
+ if (!['same-sandbox', 'self'].includes(processInfo)) {
416
+ throw new Error('Seatbelt processInfo must be same-sandbox or self');
417
+ }
409
418
  if (!['open', 'loopback'].includes(network)) {
410
419
  throw new Error('Seatbelt network must be open or loopback');
411
420
  }
@@ -495,6 +504,10 @@ export const buildSeatbeltProfile = ({
495
504
  `(deny file-read* file-write* ${envFilesUnder(resolvedWorkspace)})`,
496
505
  readOnlyWorkspaceRules,
497
506
  ...claudeRuntimeRules,
507
+ // Later rules win, so this narrows the baseline's same-sandbox allow.
508
+ processInfo === 'self'
509
+ ? '(deny process-info* (target same-sandbox))\n(allow process-info* (target self))'
510
+ : '',
498
511
  ].filter(Boolean).join('\n\n');
499
512
  };
500
513