@commonlyai/cli 0.1.244 → 0.1.245

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.245",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -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,40 @@
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';
36
45
  import { spawn as childSpawn, spawnSync } from 'child_process';
37
46
  import { createHash, randomUUID } from 'crypto';
47
+ import { accessSync, constants as fsConstants, existsSync, readFileSync, realpathSync } from 'fs';
38
48
  import { mkdir, readdir, writeFile } from 'fs/promises';
39
49
  import { homedir } from 'os';
40
- import { dirname, join } from 'path';
50
+ import { delimiter, dirname, isAbsolute, join } from 'path';
41
51
  import { fileURLToPath } from 'url';
42
52
  import {
43
53
  readUpstreamRefusal,
44
54
  spawnCredentials,
45
55
  } from '../upstream-refusal.js';
46
56
  import { buildMemoryPreamble } from '../memory-bridge.js';
47
- import { effectiveSandboxTrust, refuseWorkspaceTrust } from '../environment.js';
57
+ import { effectiveSandboxTrust, normalizeSandboxTrust, refuseWorkspaceTrust } from '../environment.js';
48
58
  import { GRANT_BROKER_REFUSAL, isGrantBrokerUrl } from './pi-mcp-client.mjs';
49
59
  import { deliverSeatCredential, withholdRuntimeCredential } from '../mcp-credential-delivery.js';
50
- import { prepareMcpSpawn } from '../mcp-home.js';
60
+ import { prepareMcpSpawn, publicMcpUnavailableError, selectedMcpVersionDir } from '../mcp-home.js';
51
61
  import { removeCredentialFile, writeCredentialFile } from '../credential-file.js';
62
+ import { resolvePublicSandboxMode } from '../sandbox/mode.js';
63
+ import { wrapArgvWithSeatbelt } from '../sandbox/seatbelt.js';
64
+ import { startProviderProxy } from '../provider-proxy.js';
65
+ import { PUBLIC_SEAT_WITHHELD_TOOLS } from '../public-withheld-tools.js';
52
66
 
53
67
  const DEFAULT_TIMEOUT_MS = (() => {
54
68
  const fallback = 15 * 60 * 1000;
@@ -71,8 +85,37 @@ export const DEFAULT_PROVIDER = Object.freeze({
71
85
  const THINKING = { none: 'off', off: 'off', minimal: 'minimal', low: 'low', medium: 'medium', high: 'high', xhigh: 'xhigh', max: 'max' };
72
86
  export const thinkingFor = (effort) => (effort ? THINKING[String(effort).toLowerCase()] || null : null);
73
87
 
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');
88
+ const ADAPTERS_DIR = dirname(fileURLToPath(import.meta.url));
89
+ const BRIDGE_PATH = join(ADAPTERS_DIR, 'pi-commonly-mcp.mjs');
90
+ const SHELL_ENV_PATH = join(ADAPTERS_DIR, 'pi-shell-env.mjs');
91
+ // The bridge imports siblings from the CLI's lib dir (credential-file.js,
92
+ // mcp-server-version.js), so a jailed pi must be able to read that tree. It
93
+ // holds code only.
94
+ const EXTENSION_CODE_ROOT = dirname(ADAPTERS_DIR);
95
+
96
+ // A public seat runs only a pi version whose tool flags were checked against a
97
+ // real headless turn under Seatbelt: `--no-builtin-tools`, `--exclude-tools`
98
+ // (which removes a tool from pi's registry, extension tools included, not only
99
+ // from the active set) and `--no-approve`. Add a version only with that smoke.
100
+ export const TESTED_PI_VERSIONS = Object.freeze(['0.84.1']);
101
+ const PI_PACKAGE = '@earendil-works/pi-coding-agent';
102
+
103
+ // pi's built-in tools (`allToolNames`, core/tools/index.js in 0.84). A public
104
+ // seat gets none of them: no shell, and no file reads either, because the jail
105
+ // has to admit the seat home that holds this turn's credential file (the bridge
106
+ // reads it), so a read tool could hand that file to the room. Every public
107
+ // adapter denies its shell; Qwen denies its read tools for this same reason,
108
+ // and Goose loads no built-in at all.
109
+ export const PI_BUILTIN_TOOLS = Object.freeze(['read', 'bash', 'edit', 'write', 'grep', 'find', 'ls']);
110
+ export const PUBLIC_EXCLUDED_TOOLS = Object.freeze([...PI_BUILTIN_TOOLS, ...PUBLIC_SEAT_WITHHELD_TOOLS]);
111
+
112
+ // What a public pi inherits from the launcher's environment. Everything else
113
+ // (operator variables, the real provider key, the seat token) stays out.
114
+ const PUBLIC_SAFE_ENV = /^(?:PATH|LANG|LC_[A-Z_]+|TERM|USER|LOGNAME|NO_COLOR|CI|SSL_CERT_FILE|SSL_CERT_DIR)$/;
115
+ const safeEnv = (env) => Object.fromEntries(Object.entries(env).filter(([name]) => PUBLIC_SAFE_ENV.test(name)));
116
+
117
+ // The one provider API the loopback proxy carries for pi.
118
+ const PUBLIC_PROVIDER_API = 'openai-completions';
76
119
 
77
120
  // Same substitution contract as claude.js / codex.js: ${COMMONLY_*}
78
121
  // placeholders in the declared MCP env are the wrapper's per-(agent, pod)
@@ -151,8 +194,8 @@ const originOf = (value) => {
151
194
  * the guard both admit) is refused rather than reinterpreted as one it can.
152
195
  *
153
196
  * 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),
197
+ * the one http entry that carries authority rather than data, and pi is not
198
+ * approved to confine it. The ruling for TASK-063 (`isGrantBrokerUrl` in pi-mcp-client.mjs),
156
199
  * the daemon-side half of the same refusal the server makes at the projection —
157
200
  * this is the half that holds on deploy skew, when the row names no adapter for
158
201
  * the server to key on, and in any backend older than the refusal.
@@ -179,21 +222,24 @@ export const resolveMcpServers = (mcpServers, ctx = {}) => {
179
222
  continue;
180
223
  }
181
224
  // 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
225
+ // than data: a granted seat acts on external systems as the granter. pi is
226
+ // not admitted to grant-broker confinement (ADAPTERS_WITH_GRANT_BROKER is
227
+ // claude and codex; a public pi's Seatbelt jail, F113b, has not been
228
+ // reviewed for that), so the reach is refused here as well as at the
229
+ // server's projection — this
185
230
  // layer is what holds when the backend predates that refusal, when the
186
231
  // row names no adapter for the server to key on, or when a deploy leaves
187
232
  // the two on different clocks.
188
233
  if (isGrantBrokerUrl(url)) {
189
234
  // 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`);
235
+ 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
236
  continue;
192
237
  }
193
238
  carried.push({
194
239
  name: server.name,
195
240
  url,
196
241
  headers: Object.fromEntries(Object.entries(server.headers || {}).map(([k, v]) => [k, substitutePlaceholders(v, ctx)])),
242
+ ...(ctx.publicSeat ? { withheldTools: [...PUBLIC_SEAT_WITHHELD_TOOLS] } : {}),
197
243
  });
198
244
  continue;
199
245
  }
@@ -211,7 +257,18 @@ export const resolveMcpServers = (mcpServers, ctx = {}) => {
211
257
  // TASK-174: what will EXECUTE — the warmed build from the seat's MCP home
212
258
  // when there is one — and the credential channel is decided on that same
213
259
  // command, so the two can never disagree about which release runs.
214
- const spawnCommand = prepareMcpSpawn(server.command, { apiUrl: ctx.instanceUrl });
260
+ const spawnCommand = prepareMcpSpawn(server.command, { apiUrl: ctx.instanceUrl, publicSeat: Boolean(ctx.publicSeat) });
261
+ // A public seat never runs a package runner (npx) from inside the jail; the
262
+ // host-prepared build is the only stdio Commonly server it may start, and
263
+ // that build's tree has to be readable inside the profile.
264
+ if (!spawnCommand) {
265
+ ctx.unavailableMcp?.push(server.name);
266
+ continue;
267
+ }
268
+ if (ctx.publicSeat) {
269
+ const versionDir = selectedMcpVersionDir(spawnCommand);
270
+ if (versionDir) ctx.mcpReadDirectories?.push(versionDir);
271
+ }
215
272
  carried.push({
216
273
  name: server.name,
217
274
  command: spawnCommand.map((a) => substitutePlaceholders(a, ctx)),
@@ -223,6 +280,7 @@ export const resolveMcpServers = (mcpServers, ctx = {}) => {
223
280
  label: 'pi',
224
281
  }).env,
225
282
  ).map(([k, v]) => [k, substitutePlaceholders(v, ctx)])),
283
+ ...(ctx.publicSeat ? { withheldTools: [...PUBLIC_SEAT_WITHHELD_TOOLS] } : {}),
226
284
  });
227
285
  continue;
228
286
  }
@@ -264,11 +322,21 @@ export const buildModelsJson = (provider, model) => ({
264
322
  },
265
323
  });
266
324
 
267
- /** Per-seat pi home: `~/.commonly/pi-homes/<hash(agent)>`. Never the operator's ~/.pi. */
268
- export const seatHome = (ctx) => {
325
+ /**
326
+ * Per-seat pi home: `~/.commonly/pi-homes/<hash(agent)>`. Never the operator's ~/.pi.
327
+ *
328
+ * A public turn gets its own sibling, `<hash>-public`. The home holds the
329
+ * seat's sessions, so a shared one let a seat switched from private to public
330
+ * resume a session full of private history: the wrapper hands back the id it
331
+ * persisted, and `sessionExists` found it. In a separate home that id is not
332
+ * found and the public turn starts fresh; and the Seatbelt profile admits only
333
+ * the public home, so the private one is not readable from inside either.
334
+ */
335
+ export const seatHome = (ctx, { publicSeat = false } = {}) => {
269
336
  const identity = ctx.agentName || ctx.cwd || 'anonymous';
270
337
  const hash = createHash('sha256').update(identity).digest('hex').slice(0, 20);
271
- return ctx._piHome || join(homedir(), '.commonly', 'pi-homes', hash);
338
+ const base = ctx._piHome || join(homedir(), '.commonly', 'pi-homes', hash);
339
+ return publicSeat ? `${base}-public` : base;
272
340
  };
273
341
 
274
342
  /**
@@ -290,32 +358,81 @@ export const sessionExists = async (sessionDir, sessionId) => {
290
358
  };
291
359
 
292
360
  /**
293
- * Fail closed: pi cannot enforce `environment.sandbox`, so a seat that declares
294
- * one does not start.
361
+ * What pi can enforce: a public seat, confined by Seatbelt on macOS (F113b),
362
+ * and nothing else.
295
363
  *
296
364
  * 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.
365
+ * raw. A stored `internal` means `public` and every other gate in this package
366
+ * resolves it that way: the attach path (`agent.js`), the mode resolver
367
+ * (`sandbox/mode.js`) and the grant-broker guard. Reading it raw here once made
368
+ * this gate the one site that failed OPEN (TASK-114).
369
+ *
370
+ * Seatbelt only. pi has no bwrap path yet, so a public seat off macOS, or one
371
+ * that names `bwrap`, is refused rather than run unconfined. A non-public seat
372
+ * that declares a mode is refused too: nothing would enforce it.
305
373
  */
306
- export const assertNoSandboxDeclared = (environment = {}) => {
374
+ export const assertSandboxSupported = (environment = {}, platform = process.platform) => {
307
375
  const sandbox = environment?.sandbox || {};
308
376
  refuseWorkspaceTrust(sandbox, 'pi');
309
377
  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');
378
+ const mode = resolvePublicSandboxMode(sandbox, platform);
379
+ if (!['workspace', 'read-only', 'bwrap'].includes(mode)) {
380
+ throw new Error('pi adapter: public seats require an enforced sandbox');
381
+ }
382
+ if (platform !== 'darwin' || mode === 'bwrap') {
383
+ 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');
384
+ }
385
+ if (sandbox.filesystem?.['read-outside']?.length) {
386
+ throw new Error('pi adapter: public seats do not allow sandbox.filesystem.read-outside');
387
+ }
388
+ if (sandbox.network?.policy === 'restricted') {
389
+ throw new Error('pi adapter: public seats do not support restricted networking');
390
+ }
391
+ return;
311
392
  }
312
393
  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`);
394
+ 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`);
395
+ }
396
+ };
397
+
398
+ /** The first executable `name` on PATH, absolute, or null. No shell involved. */
399
+ export const resolveOnPath = (name, pathValue) => {
400
+ for (const dir of String(pathValue || '').split(delimiter)) {
401
+ if (!dir || !isAbsolute(dir)) continue;
402
+ const candidate = join(dir, name);
403
+ try {
404
+ accessSync(candidate, fsConstants.X_OK);
405
+ return candidate;
406
+ } catch { /* next */ }
407
+ }
408
+ return null;
409
+ };
410
+
411
+ /**
412
+ * pi's install tree: the nearest directory above the real entry file whose
413
+ * package.json names pi. Its `node_modules` and dist are what a jailed pi loads,
414
+ * and nothing else under that prefix needs to be readable.
415
+ */
416
+ export const piPackageRoot = (binary) => {
417
+ let dir;
418
+ try { dir = dirname(realpathSync(binary)); } catch { return null; }
419
+ for (;;) {
420
+ const manifest = join(dir, 'package.json');
421
+ if (existsSync(manifest)) {
422
+ try {
423
+ if (JSON.parse(readFileSync(manifest, 'utf8')).name === PI_PACKAGE) return dir;
424
+ } catch { /* keep walking */ }
425
+ }
426
+ const parent = dirname(dir);
427
+ if (parent === dir) return null;
428
+ dir = parent;
314
429
  }
315
430
  };
316
431
 
432
+ const versionOf = (value) => String(value || '').trim().match(/\b(\d+\.\d+\.\d+)\b/)?.[1] || null;
433
+
317
434
  export const buildArgs = ({
318
- prompt, provider, model, thinking, sessionId, isResume, sessionDir, bridge,
435
+ prompt, provider, model, thinking, sessionId, isResume, sessionDir, bridge, publicSeat = false,
319
436
  }) => [
320
437
  '-p',
321
438
  '--mode', 'json',
@@ -323,6 +440,10 @@ export const buildArgs = ({
323
440
  '--no-skills',
324
441
  '--no-prompt-templates',
325
442
  '--no-themes',
443
+ // A public seat: no built-in tool (no shell, no file access), the withheld
444
+ // Commonly tools removed from the registry, and no project-local pi files
445
+ // from the workspace trusted for this run.
446
+ ...(publicSeat ? ['--no-builtin-tools', '--exclude-tools', PUBLIC_EXCLUDED_TOOLS.join(','), '--no-approve'] : []),
326
447
  '--provider', provider,
327
448
  '--model', model,
328
449
  ...(thinking ? ['--thinking', thinking] : []),
@@ -350,14 +471,14 @@ export const extractReply = (stdout) => {
350
471
  return { text, sawAssistant, errors };
351
472
  };
352
473
 
353
- const runPi = ({ args, cwd, env, payload, timeoutMs, credentials = [], spawnImpl = childSpawn }) => new Promise((resolve, reject) => {
474
+ const runPi = ({ command = 'pi', args, cwd, env, payload, timeoutMs, credentials = [], spawnImpl = childSpawn }) => new Promise((resolve, reject) => {
354
475
  let stdout = '';
355
476
  let stderr = '';
356
477
  let timedOut = false;
357
478
  // fd 3 carries the MCP server list, so the 4th pipe exists exactly when there
358
479
  // is a list to hand over. The bridge reads it at extension load (takeServers).
359
480
  const withList = typeof payload === 'string';
360
- const proc = spawnImpl('pi', args, { cwd, env, stdio: withList ? ['ignore', 'pipe', 'pipe', 'pipe'] : ['ignore', 'pipe', 'pipe'] });
481
+ const proc = spawnImpl(command, args, { cwd, env, stdio: withList ? ['ignore', 'pipe', 'pipe', 'pipe'] : ['ignore', 'pipe', 'pipe'] });
361
482
  if (withList) {
362
483
  const channel = proc.stdio && proc.stdio[3];
363
484
  // A missing pipe is an invariant break, not a degraded mode: the bridge would
@@ -401,6 +522,12 @@ export default {
401
522
  // daemon level.
402
523
  providerKeyEnv: DEFAULT_PROVIDER.apiKeyEnv,
403
524
 
525
+ // Attach runs this before anything is published, so a public pi seat this
526
+ // host cannot confine is refused there rather than at its first turn.
527
+ async validateEnvironment(environment) {
528
+ assertSandboxSupported(environment);
529
+ },
530
+
404
531
  async detect() {
405
532
  const res = spawnSync('pi', ['--version'], { encoding: 'utf8' });
406
533
  if (res.error || res.status !== 0) return null;
@@ -411,10 +538,12 @@ export default {
411
538
 
412
539
  async spawn(prompt, ctx = {}) {
413
540
  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);
541
+ const platform = ctx._platform || process.platform;
542
+ // A public seat is confined by Seatbelt below; every sandbox declaration pi
543
+ // cannot honour on this host is refused here, before anything starts.
544
+ assertSandboxSupported(ctx.environment, platform);
545
+ const sandbox = normalizeSandboxTrust(ctx.environment?.sandbox);
546
+ const isPublic = effectiveSandboxTrust(sandbox?.trust) === 'public';
418
547
  const provider = resolveProvider(ctx.environment);
419
548
  const model = seatModel;
420
549
  const thinking = thinkingFor(ctx.environment?.effort);
@@ -422,6 +551,36 @@ export default {
422
551
  if (!baseEnv[provider.apiKeyEnv]) {
423
552
  throw new Error(`pi adapter: ${provider.apiKeyEnv} is not set — the seat's environment must carry the provider key (LiteLLM virtual key)`);
424
553
  }
554
+
555
+ // What a public turn runs inside the jail: the absolute pi entry, the
556
+ // package tree it loads, and the node its shebang resolves to.
557
+ let binary = 'pi';
558
+ let packageRoot = null;
559
+ let nodePath = null;
560
+ if (isPublic) {
561
+ if (provider.api !== PUBLIC_PROVIDER_API) {
562
+ 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}`);
563
+ }
564
+ if (!ctx.cwd || !isAbsolute(ctx.cwd)) {
565
+ throw new Error('pi adapter: a public seat needs an absolute workspace path');
566
+ }
567
+ binary = ctx._binaryPath || resolveOnPath('pi', baseEnv.PATH);
568
+ if (!binary || !isAbsolute(binary)) {
569
+ throw new Error('pi adapter: a public seat needs an absolute pi executable on PATH');
570
+ }
571
+ packageRoot = piPackageRoot(binary);
572
+ if (!packageRoot) {
573
+ throw new Error(`pi adapter: no ${PI_PACKAGE} package found behind ${binary}, so the sandbox cannot admit pi's code`);
574
+ }
575
+ const version = ctx._version || versionOf(spawnSync(binary, ['--version'], {
576
+ encoding: 'utf8', timeout: 30000, env: safeEnv(baseEnv),
577
+ })?.stdout);
578
+ if (!TESTED_PI_VERSIONS.includes(version)) {
579
+ throw new Error(`pi adapter: public seats refuse untested pi version ${version || 'unknown'}; smoke-tested: ${TESTED_PI_VERSIONS.join(', ')}`);
580
+ }
581
+ nodePath = resolveOnPath('node', baseEnv.PATH);
582
+ }
583
+
425
584
  // The values this spawn is handed, for the refusal log's exact-match check:
426
585
  // the provider key the route authenticates with, and the seat credential the
427
586
  // bridge carries. Snapshot them HERE — `withholdRuntimeCredential` removes
@@ -430,33 +589,70 @@ export default {
430
589
  const credentials = spawnCredentials(ctx, [provider.apiKeyEnv]);
431
590
 
432
591
  // Per-seat pi home: models.json holds the provider by env reference.
433
- const home = seatHome(ctx);
592
+ const home = seatHome(ctx, { publicSeat: isPublic });
434
593
  const agentDir = join(home, 'agent');
435
594
  const sessionDir = join(home, 'sessions');
436
595
  await mkdir(agentDir, { recursive: true, mode: 0o700 });
437
596
  await mkdir(sessionDir, { recursive: true, mode: 0o700 });
597
+ if (isPublic) await mkdir(join(home, 'tmp'), { recursive: true, mode: 0o700 });
438
598
 
439
599
  // Resume only what pi wrote; anything else (a codex thread id from before
440
600
  // the switch, a wiped home) starts fresh under a new id.
441
601
  const isResume = await sessionExists(sessionDir, ctx.sessionId);
442
602
  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 });
603
+ // F118: a public seat reads its memory but is not offered the save tool,
604
+ // so its preamble names none.
605
+ const fullPrompt = buildMemoryPreamble(prompt, ctx.memoryLongTerm, {
606
+ freshSession: !isResume, memoryReadOnly: isPublic,
607
+ });
445
608
 
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.
609
+ // One credential file per spawn, inside this seat's own 0700 home: the
610
+ // narrowest place the bridge can still read. On a public seat that home is
611
+ // the jail's state directory, which is why pi gets no read tool there. The
612
+ // value the server receives still travels on fd 3 (pi-mcp-client's fd
613
+ // channel); the file is where the launcher puts it.
450
614
  const credential = writeCredentialFile(ctx.runtimeToken, {
451
615
  agentName: ctx.agentName || 'agent',
452
616
  root: join(home, 'credentials'),
453
617
  });
618
+ let proxy = null;
454
619
  try {
620
+ // A public pi never holds the provider key: it talks to a loopback proxy
621
+ // with a per-turn token, and the proxy, in this process, adds the key and
622
+ // pins the model (the same shape as Goose and Qwen).
623
+ if (isPublic) {
624
+ proxy = await (ctx._startProviderProxy || startProviderProxy)({
625
+ provider: { baseURL: provider.baseUrl },
626
+ keyMaterial: baseEnv[provider.apiKeyEnv],
627
+ adapterLabel: 'pi',
628
+ pinnedModel: model,
629
+ });
630
+ }
631
+ await writeFile(join(agentDir, 'models.json'), `${JSON.stringify(buildModelsJson(
632
+ proxy ? { ...provider, baseUrl: proxy.baseURL } : provider, model,
633
+ ), null, 2)}\n`, { mode: 0o600 });
634
+
635
+ const unavailableMcp = [];
636
+ const mcpReadDirectories = [];
455
637
  const servers = resolveMcpServers(ctx.environment?.mcp, {
456
638
  ...ctx,
457
639
  credentialFile: credential?.path || null,
640
+ publicSeat: isPublic,
641
+ unavailableMcp,
642
+ mcpReadDirectories,
458
643
  });
459
- const childEnv = {
644
+ if (unavailableMcp.length) throw publicMcpUnavailableError(unavailableMcp);
645
+ const childEnv = isPublic ? {
646
+ // A scrubbed environment: nothing of the operator's crosses into the
647
+ // jail, and the provider variable holds the proxy's token, not the key.
648
+ ...safeEnv(baseEnv),
649
+ HOME: home,
650
+ TMPDIR: join(home, 'tmp'),
651
+ PI_CODING_AGENT_DIR: agentDir,
652
+ PI_SKIP_VERSION_CHECK: '1',
653
+ PI_OFFLINE: '1',
654
+ [provider.apiKeyEnv]: proxy.token,
655
+ } : {
460
656
  ...baseEnv,
461
657
  PI_CODING_AGENT_DIR: agentDir,
462
658
  PI_SKIP_VERSION_CHECK: '1',
@@ -477,17 +673,42 @@ export default {
477
673
  const args = buildArgs({
478
674
  prompt: fullPrompt, provider: provider.name, model, thinking, sessionId, isResume, sessionDir,
479
675
  bridge: servers.length ? (ctx._bridgePath || BRIDGE_PATH) : null,
676
+ publicSeat: isPublic,
480
677
  });
481
- // Shell isolation must not depend on whether this turn declares MCP.
482
- args.splice(args.length - 1, 0, '-e', SHELL_ENV_PATH);
678
+ // Shell isolation must not depend on whether this turn declares MCP. A
679
+ // public turn has no shell at all, so it loads no shell extension (that
680
+ // extension registers a `bash` tool of its own).
681
+ if (!isPublic) args.splice(args.length - 1, 0, '-e', SHELL_ENV_PATH);
682
+
683
+ // The public jail wraps pi itself. The bridge is an in-process pi
684
+ // extension, so every MCP server it starts is a child of the jailed
685
+ // process, and a Seatbelt profile is inherited across fork and exec: there
686
+ // is no second spawn here, and nothing pi launches runs outside it.
687
+ let command = 'pi';
688
+ let spawnArgs = args;
689
+ if (isPublic) {
690
+ [command, ...spawnArgs] = (ctx._wrapArgvWithSeatbelt || wrapArgvWithSeatbelt)([binary, ...args], {
691
+ workspacePath: ctx.cwd,
692
+ workspaceAccess: resolvePublicSandboxMode(sandbox, platform) === 'read-only' ? 'read' : 'write',
693
+ executablePath: binary,
694
+ executablePaths: nodePath ? [nodePath] : [],
695
+ statePath: home,
696
+ loopbackNetworkPorts: [proxy.port],
697
+ readOnlyDirectories: [packageRoot, EXTENSION_CODE_ROOT, ...mcpReadDirectories],
698
+ // The jailed pi holds the seat token in memory (the bridge reads it),
699
+ // so nothing it starts may inspect it.
700
+ processInfo: 'self',
701
+ });
702
+ }
483
703
 
484
704
  const reply = await runPi({
485
- args,
705
+ command,
706
+ args: spawnArgs,
486
707
  cwd: ctx.cwd,
487
708
  env: childEnv,
488
709
  payload: servers.length ? JSON.stringify(servers) : undefined,
489
710
  timeoutMs: ctx.timeoutMs || DEFAULT_TIMEOUT_MS,
490
- credentials,
711
+ credentials: proxy ? [...credentials, proxy.token] : credentials,
491
712
  spawnImpl: ctx._spawnImpl, // test seam only — do not use in production
492
713
  });
493
714
  // Empty text with a clean exit is a silent turn; the run loop treats it
@@ -499,6 +720,7 @@ export default {
499
720
  // turn ends, and a token file that outlives its turn is a token file that
500
721
  // sits in a home for the next one.
501
722
  removeCredentialFile(credential);
723
+ try { await proxy?.close(); } catch { /* best effort */ }
502
724
  }
503
725
  },
504
726
  };
@@ -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