@commonlyai/cli 0.1.243 → 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.243",
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",
@@ -60,6 +60,7 @@ import { detectMemorySources, composeImport, importMemory } from '../lib/memory-
60
60
  import { detectSkills, importSkills, parseSkillMeta } from '../lib/skills-import.js';
61
61
  import { compileServerSkills } from '../lib/server-skills.js';
62
62
  import {
63
+ effectiveSandboxTrust,
63
64
  environmentForServer,
64
65
  normalizeSandboxTrust,
65
66
  parseEnvironmentFile,
@@ -2200,6 +2201,12 @@ export const performRun = ({
2200
2201
  // The adapter also denies the memory tools for it (memoryWithheld).
2201
2202
  const memoryWithheld = Boolean(placement.reason);
2202
2203
  const memoryLongTerm = memoryWithheld ? undefined : await readLongTerm(client, { onError });
2204
+ // F118: a public seat reads its memory but never writes it. Its summary is
2205
+ // its own output, which a stranger in the pod can steer, so the wrapper does
2206
+ // not sync it back; the adapters withhold the memory-write tools the same
2207
+ // way. A workspace seat's public turn is covered by memoryWithheld too.
2208
+ const memoryWriteWithheld = memoryWithheld
2209
+ || effectiveSandboxTrust(placement.environment?.sandbox?.trust) === 'public';
2203
2210
 
2204
2211
  // TASK-129: focus is a turn-start read, not an enqueue-time
2205
2212
  // snapshot. Read through the authorized runtime context route immediately
@@ -2675,7 +2682,7 @@ export const performRun = ({
2675
2682
  }
2676
2683
  }
2677
2684
  turn.finish(turnOutcome);
2678
- if (result.memorySummary && !memoryWithheld) {
2685
+ if (result.memorySummary && !memoryWriteWithheld) {
2679
2686
  try {
2680
2687
  await syncBack(client, { summary: result.memorySummary });
2681
2688
  log(`[${event.type}] memory synced (${Buffer.byteLength(result.memorySummary)} bytes)`);
@@ -101,7 +101,7 @@ import { BACKGROUND_PROCESS_CUE, buildMemoryPreamble, ROW_SLICING_CUE } from '..
101
101
  import { claudeConfigDirFor, claudeContextTokens, claudeTranscriptPath } from '../session-recycle.js';
102
102
  import { skillsAsText } from '../skill-prompt.js';
103
103
  import { adapterFailure, redactKnownCredentials, spawnCredentials } from '../upstream-refusal.js';
104
- import { PUBLIC_WITHHELD_TOOLS } from '../public-withheld-tools.js';
104
+ import { PUBLIC_ONLY_WITHHELD_TOOLS, PUBLIC_WITHHELD_TOOLS } from '../public-withheld-tools.js';
105
105
  import { isShippedCommonlyMcpCommand } from '../declared-mcp-guard.js';
106
106
  import { isAnswerableToolError, PUBLIC_MCP_NOT_READY_CODE, PUBLIC_TOOL_FAILED_CODE } from '../public-tool-error.js';
107
107
  import { resolveLaunch, resolveMcpCommand, resolveWindowsCommandWithReason } from '../windows-command.js';
@@ -596,9 +596,17 @@ const buildPublicClaudePolicyArgs = (mcpToolPatterns, {
596
596
  ? MEMORY_TOOLS.flatMap((tool) => mcpToolPatterns.map((pattern) => pattern.replace(/\*$/, tool)))
597
597
  : [];
598
598
  // Nor, on any confined trust, the tools no public seat is offered
599
- // (public-withheld-tools.js).
600
- const withheldDenies = PUBLIC_WITHHELD_TOOLS
599
+ // (public-withheld-tools.js). A public seat also loses self-install and every
600
+ // memory write (F118). Only a workspace seat is called with its trust at
601
+ // every call site; the public ones pass none, so "not workspace" is public.
602
+ const withheldTools = trust === 'workspace'
603
+ ? PUBLIC_WITHHELD_TOOLS
604
+ : [...PUBLIC_WITHHELD_TOOLS, ...PUBLIC_ONLY_WITHHELD_TOOLS];
605
+ const withheldDenies = withheldTools
601
606
  .flatMap((tool) => mcpToolPatterns.map((pattern) => pattern.replace(/\*$/, tool)));
607
+ // A tool can be denied for two reasons (a withheld turn's memory write is
608
+ // also a public seat's); each deny is written once.
609
+ const toolDenies = [...new Set([...workspaceDenies, ...memoryDenies, ...withheldDenies])];
602
610
  return [
603
611
  // HOME points at an isolated, sanitized state directory. Ignore settings
604
612
  // from user/project/local sources and disable slash-command extensions;
@@ -610,7 +618,7 @@ const buildPublicClaudePolicyArgs = (mcpToolPatterns, {
610
618
  '--permission-mode', 'dontAsk',
611
619
  '--allowedTools', 'Read(./**)', ...granted, ...mcpToolPatterns,
612
620
  '--disallowedTools', ...PUBLIC_DENIED_TOOLS.filter((tool) => !granted.some((g) => g === tool || g.startsWith(`${tool}(`))),
613
- ...deniedReads, ...workspaceDenies, ...memoryDenies, ...withheldDenies,
621
+ ...deniedReads, ...toolDenies,
614
622
  ];
615
623
  };
616
624
 
@@ -1501,10 +1509,13 @@ export default {
1501
1509
  // there is a signal, not a leak.
1502
1510
  const witnessedMcp = ctx.environment?.sandbox?.trust === 'public' ? ctx.environment?.mcp : null;
1503
1511
  const workCues = publicTrust ? [] : WORK_CUES;
1512
+ // F118: a public seat reads its memory but is not offered a write.
1513
+ const memoryReadOnly = ctx.environment?.sandbox?.trust === 'public';
1504
1514
  const fullPrompt = buildPrompt(prompt, ctx.memoryLongTerm, {
1505
1515
  freshSession: !isResume,
1506
1516
  workCues,
1507
1517
  memoryWithheld: ctx.memoryWithheld === true,
1518
+ memoryReadOnly,
1508
1519
  });
1509
1520
  const sessionFlag = isResume ? '--resume' : '--session-id';
1510
1521
  // Model pin from the ADR-008 environment spec. Absent it, claude picks its
@@ -1729,6 +1740,7 @@ export default {
1729
1740
  freshSession: true,
1730
1741
  workCues,
1731
1742
  memoryWithheld: ctx.memoryWithheld === true,
1743
+ memoryReadOnly,
1732
1744
  });
1733
1745
  const retryBase = ['-p', freshPrompt,
1734
1746
  ...STREAM_ARGS, '--session-id', freshId, ...modelArgs];
@@ -78,7 +78,7 @@ import { BACKGROUND_PROCESS_CUE, buildMemoryPreamble, ROW_SLICING_CUE } from '..
78
78
  import { resolveSkillSource, skillsAsText } from '../skill-prompt.js';
79
79
  import { isLegacySandboxTrust, normalizeSandboxTrust, refuseWorkspaceTrust } from '../environment.js';
80
80
  import { adapterFailure, spawnCredentials } from '../upstream-refusal.js';
81
- import { PUBLIC_WITHHELD_TOOLS } from '../public-withheld-tools.js';
81
+ import { PUBLIC_SEAT_WITHHELD_TOOLS } from '../public-withheld-tools.js';
82
82
  import { resolveLaunch, resolveMcpCommand, resolveWindowsCommandWithReason } from '../windows-command.js';
83
83
 
84
84
  // Default timeout for a single codex spawn (exec mode).
@@ -227,9 +227,10 @@ const buildMcpOverrideArgs = (mcpServers, ctx = {}) => {
227
227
  '-c',
228
228
  `mcp_servers.${server.name}.default_tools_approval_mode="approve"`,
229
229
  );
230
- // ...except the tools no public seat is offered (public-withheld-tools.js).
230
+ // ...except the tools no public seat is offered (public-withheld-tools.js),
231
+ // self-install and the memory writes included (F118).
231
232
  if (ctx.publicSeat) {
232
- flags.push('-c', `mcp_servers.${server.name}.disabled_tools=[${PUBLIC_WITHHELD_TOOLS.map(toml).join(',')}]`);
233
+ flags.push('-c', `mcp_servers.${server.name}.disabled_tools=[${PUBLIC_SEAT_WITHHELD_TOOLS.map(toml).join(',')}]`);
233
234
  }
234
235
  if (rest.length) {
235
236
  flags.push('-c', `mcp_servers.${server.name}.args=[${rest.map(toml).join(',')}]`);
@@ -853,6 +854,8 @@ export default {
853
854
  const fullPrompt = buildPrompt(prompt, ctx.memoryLongTerm, {
854
855
  freshSession: !ctx.sessionId,
855
856
  workCues: sandbox?.trust === 'public' ? [] : [ROW_SLICING_CUE, BACKGROUND_PROCESS_CUE],
857
+ // F118: a public seat reads its memory but is not offered a write.
858
+ memoryReadOnly: sandbox?.trust === 'public',
856
859
  });
857
860
 
858
861
  // Per-spawn temp dir for --output-last-message. Cleaned up in `finally`
@@ -42,6 +42,8 @@ const templateLiteral = (value) => {
42
42
  // attach_file reads this process's filesystem, including its credential file.
43
43
  // catch_up is left out too: it moves the read cursor past history unread, so a
44
44
  // public seat past 50 unseen falls back to continueAnyway, which it keeps.
45
+ // Self-install and the memory writes (log_cycle included) are left out on every
46
+ // public seat (F118, PUBLIC_ONLY_WITHHELD_TOOLS); reading memory stays.
45
47
  export const PUBLIC_GOOSE_TOOLS = Object.freeze([
46
48
  'commonly_get_started', 'commonly_post_message', 'commonly_claim_message',
47
49
  'commonly_release_claim', 'commonly_get_messages', 'commonly_get_context',
@@ -49,8 +51,7 @@ export const PUBLIC_GOOSE_TOOLS = Object.freeze([
49
51
  'commonly_get_posts', 'commonly_post_thread_comment', 'commonly_get_tasks',
50
52
  'commonly_create_task', 'commonly_claim_task', 'commonly_watch_task',
51
53
  'commonly_complete_task', 'commonly_update_task', 'commonly_create_pod',
52
- 'commonly_list_pods', 'commonly_self_install_into_pod', 'commonly_read_agent_memory',
53
- 'commonly_write_agent_memory', 'commonly_save_my_memory', 'commonly_log_cycle',
54
+ 'commonly_list_pods', 'commonly_read_agent_memory',
54
55
  'commonly_dm_agent', 'commonly_ask_agent', 'commonly_request_decision',
55
56
  'commonly_respond_to_ask', 'commonly_react_to_message',
56
57
  ]);
@@ -324,7 +325,8 @@ export default {
324
325
  extensions: publicExtensions.map((extension) => ({ ...extension,
325
326
  envs: { ...extension.envs, OPENSSL_CONF: opensslConfig },
326
327
  })),
327
- prompt: buildMemoryPreamble(prompt, ctx.memoryLongTerm, { freshSession: true }),
328
+ // F118: a public seat reads its memory but is not offered a write.
329
+ prompt: buildMemoryPreamble(prompt, ctx.memoryLongTerm, { freshSession: true, memoryReadOnly: true }),
328
330
  })), { mode: 0o600 });
329
331
  const env = {
330
332
  ...safeEnv(sourceEnv),
@@ -59,7 +59,7 @@ import { resolveProviderKeyFile, startProviderProxy } from '../provider-proxy.js
59
59
  import { isShippedCommonlyMcpCommand } from '../declared-mcp-guard.js';
60
60
  import { isAnswerableToolError, PUBLIC_TOOL_FAILED_CODE } from '../public-tool-error.js';
61
61
  import { startInstanceProxy } from '../instance-proxy.js';
62
- import { PUBLIC_WITHHELD_TOOLS } from '../public-withheld-tools.js';
62
+ import { PUBLIC_SEAT_WITHHELD_TOOLS } from '../public-withheld-tools.js';
63
63
 
64
64
  const DEFAULT_TIMEOUT_MS = 15 * 60 * 1000;
65
65
  const ISOLATED_PROXY_PORT = 8765;
@@ -249,8 +249,8 @@ const publicPermissions = (mode, mcpNames) => {
249
249
  lsp: 'allow',
250
250
  ...Object.fromEntries(mcpNames.map((name) => [`${permissionMcpName(name)}_*`, 'allow'])),
251
251
  // After the wildcard allow, since the last matching rule wins
252
- // (public-withheld-tools.js).
253
- ...Object.fromEntries(mcpNames.flatMap((name) => PUBLIC_WITHHELD_TOOLS
252
+ // (public-withheld-tools.js; self-install and memory writes, F118).
253
+ ...Object.fromEntries(mcpNames.flatMap((name) => PUBLIC_SEAT_WITHHELD_TOOLS
254
254
  .map((tool) => [`${permissionMcpName(name)}_${tool}`, 'deny']))),
255
255
  };
256
256
  };
@@ -749,6 +749,8 @@ export default {
749
749
 
750
750
  const fullPrompt = buildMemoryPreamble(prompt, ctx.memoryLongTerm, {
751
751
  freshSession: !ctx.sessionId,
752
+ // F118: a public seat reads its memory but is not offered a write.
753
+ memoryReadOnly: isPublic,
752
754
  });
753
755
  const tempDir = await mkdtemp(join(tmpdir(), 'commonly-opencode-'));
754
756
  await chmod(tempDir, 0o700);
@@ -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
  };
@@ -16,7 +16,7 @@ import { detectBwrap, wrapArgvWithBwrap } from '../sandbox/bwrap.js';
16
16
  import { wrapArgvWithSeatbelt } from '../sandbox/seatbelt.js';
17
17
  import { resolveProviderKeyFile, startProviderProxy } from '../provider-proxy.js';
18
18
  import { adapterFailure, spawnCredentials } from '../upstream-refusal.js';
19
- import { PUBLIC_WITHHELD_TOOLS } from '../public-withheld-tools.js';
19
+ import { PUBLIC_SEAT_WITHHELD_TOOLS } from '../public-withheld-tools.js';
20
20
 
21
21
  // Add a version only with a passing real clean-box sandbox smoke that names it.
22
22
  const TESTED_QWEN_VERSIONS = Object.freeze(['0.25.1', '0.26.2']);
@@ -41,8 +41,8 @@ const EXCLUDED_TOOLS = [
41
41
  const PUBLIC_READ_TOOLS = [
42
42
  'read_file', 'grep_search', 'search_file_content', 'glob', 'list_directory', 'lsp',
43
43
  // Both spellings of a Commonly MCP tool, as with the aliases above
44
- // (public-withheld-tools.js).
45
- ...PUBLIC_WITHHELD_TOOLS.flatMap((tool) => [tool, `mcp__commonly__${tool}`]),
44
+ // (public-withheld-tools.js; self-install and memory writes, F118).
45
+ ...PUBLIC_SEAT_WITHHELD_TOOLS.flatMap((tool) => [tool, `mcp__commonly__${tool}`]),
46
46
  ];
47
47
 
48
48
  const parseVersion = (output) => {
@@ -315,6 +315,8 @@ export default {
315
315
  // be resumed. The kernel memory preamble supplies continuity instead.
316
316
  const fullPrompt = buildMemoryPreamble(prompt, ctx.memoryLongTerm, {
317
317
  freshSession: true,
318
+ // F118: a public seat reads its memory but is not offered a write.
319
+ memoryReadOnly: isPublic,
318
320
  });
319
321
  const args = [
320
322
  '--bare', '--safe-mode', '--auth-type', 'openai', '-m', seatModel,
@@ -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
 
@@ -65,11 +65,15 @@ export const BACKGROUND_PROCESS_CUE = 'Background processes: anything you start
65
65
  * the memory cues and under the same once-per-session rule. An adapter passes
66
66
  * only the habits its CLI can act on; passing none leaves the preamble as it
67
67
  * was.
68
+ *
69
+ * `memoryReadOnly` is a public seat (F118): it reads its memory and is shown
70
+ * the long_term it read, but it is not offered the save tool, so no cue names
71
+ * one. `memoryWithheld` wins over it: that turn reads nothing either.
68
72
  */
69
73
  export const buildMemoryPreamble = (
70
74
  prompt,
71
75
  memoryLongTerm,
72
- { freshSession = false, workCues = [], memoryWithheld = false } = {},
76
+ { freshSession = false, workCues = [], memoryWithheld = false, memoryReadOnly = false } = {},
73
77
  ) => {
74
78
  // `null` is the UNREADABLE signal, and it is deliberately not the same value
75
79
  // as `''`. Telling a seat whose token was revoked that "nothing has ever been
@@ -91,6 +95,11 @@ export const buildMemoryPreamble = (
91
95
  + `state you may already hold.)`;
92
96
  } else if (memoryLongTerm) {
93
97
  context = `=== Context (your persistent memory) ===\n${memoryLongTerm}`;
98
+ } else if (memoryReadOnly) {
99
+ // F118: a public seat is not offered the save tool, so the cue that
100
+ // teaches it would name a tool the seat cannot call.
101
+ context = `=== Context (your persistent memory) ===\n`
102
+ + `(empty — nothing has ever been saved here)`;
94
103
  } else {
95
104
  context = `=== Context (your persistent memory) ===\n`
96
105
  + `(empty — nothing has ever been saved here)\n`
@@ -114,6 +123,8 @@ export const buildMemoryPreamble = (
114
123
  let sessionEndCue = '=== Before this session ends ===\n';
115
124
  if (memoryWithheld) {
116
125
  sessionEndCue += 'Memory is withheld this turn, so there is nothing to save.';
126
+ } else if (memoryReadOnly) {
127
+ sessionEndCue += 'Memory is read-only on this public seat, so there is nothing to save.';
117
128
  } else if (memoryLongTerm === null) {
118
129
  sessionEndCue += 'Memory was unreadable on this fresh session. Do not treat it as empty or '
119
130
  + 'write a replacement based on this cue.';
@@ -5,3 +5,25 @@
5
5
  // commonly_catch_up moves the read cursor past history unread; a wrapper seat
6
6
  // already catches up before each turn, so no seat on this list needs the tool.
7
7
  export const PUBLIC_WITHHELD_TOOLS = Object.freeze(['commonly_attach_file', 'commonly_catch_up']);
8
+
9
+ // F118 (Cofounder ruling, 11-04): public agents start from nothing and earn
10
+ // capabilities. A public seat answers strangers, so an injected message must
11
+ // not be able to spread the agent into other pods or rewrite its memory.
12
+ // Withheld on public trust only: a Claude workspace seat keeps its memory
13
+ // writes, and denies self-install itself (claude.js, workspaceDenies).
14
+ // commonly_log_cycle is a memory write too: it appends to the agent's
15
+ // `cycles[]` through POST /api/agents/runtime/memory/sync. Reading memory
16
+ // (commonly_read_agent_memory, and the long_term the wrapper puts in the
17
+ // prompt) stays offered.
18
+ export const PUBLIC_ONLY_WITHHELD_TOOLS = Object.freeze([
19
+ 'commonly_self_install_into_pod',
20
+ 'commonly_write_agent_memory',
21
+ 'commonly_save_my_memory',
22
+ 'commonly_log_cycle',
23
+ ]);
24
+
25
+ // Everything a public seat is not offered. Codex, OpenCode, Qwen and Goose
26
+ // confine on public trust only, so this is the whole list for them.
27
+ export const PUBLIC_SEAT_WITHHELD_TOOLS = Object.freeze([
28
+ ...PUBLIC_WITHHELD_TOOLS, ...PUBLIC_ONLY_WITHHELD_TOOLS,
29
+ ]);
@@ -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