@commonlyai/cli 0.1.268 → 0.1.270

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.268",
3
+ "version": "0.1.270",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -81,6 +81,7 @@ import { firstRunWorkspace, podIsConfirmedPrivate, workspaceTurnPlacement } from
81
81
  import {
82
82
  ADAPTERS_WITH_DEFAULT_MCP,
83
83
  ADAPTERS_WITH_GRANT_BROKER,
84
+ ADAPTERS_WITH_PUBLIC_ONLY_GRANT,
84
85
  ADAPTERS_WITH_DEFAULT_SANDBOX,
85
86
  ADAPTERS_WITH_SANDBOX_ENFORCEMENT,
86
87
  defaultMcpServers,
@@ -233,10 +234,18 @@ export const runtimeAdapterForInstallation = ({ installations, podId, instanceId
233
234
  return adapter || null;
234
235
  };
235
236
 
236
- /** Non-broker adapters need a server-resolved binding on env-token seats. */
237
+ /**
238
+ * Non-broker adapters need a server-resolved binding on env-token seats. So do
239
+ * the broker adapters that hold a grant only when public (pi, F175c): the
240
+ * broker's per-call check judges the seat by its ROW, and a row that names no
241
+ * adapter reads as daemon-decided there, where naming (F94) lifts a sandbox
242
+ * refusal that pi must never have lifted. The binding is what puts `pi` on the
243
+ * row.
244
+ */
237
245
  export const adapterRequiresServerBinding = (adapterName) => {
238
246
  const adapter = String(adapterName || '').trim().toLowerCase();
239
- return Boolean(adapter) && adapter !== 'stub' && !ADAPTERS_WITH_GRANT_BROKER.has(adapter);
247
+ return Boolean(adapter) && adapter !== 'stub'
248
+ && (!ADAPTERS_WITH_GRANT_BROKER.has(adapter) || ADAPTERS_WITH_PUBLIC_ONLY_GRANT.has(adapter));
240
249
  };
241
250
 
242
251
  const serverRuntimeAdapterProjectionState = (installations) => {
@@ -1544,6 +1553,16 @@ export const runMemoryImport = async ({
1544
1553
 
1545
1554
  // ── run: local-CLI wrapper loop (ADR-005) ────────────────────────────────────
1546
1555
 
1556
+ // D247 walk, 11-04: a Qwen seat whose post tool was declined told the pod about
1557
+ // checkpoints, first_contact and re-serving. The model wrote that, not the
1558
+ // wrapper, so the fix is an instruction and not a filter on its text: a filter
1559
+ // would also eat a pod that is discussing these words. It speaks only to a
1560
+ // request it can't meet, so it gives a heartbeat no reason to post. Every closing
1561
+ // line carries it, and it says where the note goes once the agent has posted.
1562
+ const FAILURE_IN_PLAIN_WORDS = 'If you can\'t do what someone asked of you, don\'t go silent: say in plain words what didn\'t work and what they can do next, '
1563
+ + 'without event types, checkpoints, deliveries, retries or other runtime terms unless they asked about them. '
1564
+ + 'If you already posted in this turn, post the failure note through the tool as well: final text after a tool post is dropped.';
1565
+
1547
1566
  // TASK-293, and the rule AX entry 43 earned: a frame that says "otherwise
1548
1567
  // return NO_REPLY" must also say what the otherwise costs. Silence here is an
1549
1568
  // exact match (`silentReply` in runTurn), so a seat that checkpointed and then
@@ -1553,7 +1572,8 @@ export const runMemoryImport = async ({
1553
1572
  // is. Every prompt whose final text the wrapper posts to the pod carries it.
1554
1573
  // agent.ask does not: its final text goes only to the asking agent.
1555
1574
  const FINAL_TEXT_IS_POSTED = 'Your final text is posted to the pod unless it is exactly NO_REPLY. '
1556
- + 'If you did nothing, or already posted through a tool, end with NO_REPLY alone, with no summary.';
1575
+ + 'If you did nothing, or already posted through a tool, end with NO_REPLY alone, with no summary. '
1576
+ + FAILURE_IN_PLAIN_WORDS;
1557
1577
 
1558
1578
  // Prod walk, 2026-11-05: a person @mentioned a Claude Code seat with a
1559
1579
  // top-level message, and the seat answered through commonly_post_message with
@@ -1610,7 +1630,8 @@ export const answersInChannel = (entry) => {
1610
1630
  const PERSON_ADDRESSED = '[A person addressed this to you directly: answer them in this turn, even if the answer '
1611
1631
  + 'is short, is that you can\'t help, or repeats what another agent said. Do not leave them without a reply.]';
1612
1632
  const FINAL_TEXT_ANSWERS_A_PERSON = 'Your final text is posted to the pod unless it is exactly NO_REPLY. '
1613
- + 'Use NO_REPLY alone only after you posted your answer through a tool, with no summary.';
1633
+ + 'Use NO_REPLY alone only after you posted your answer through a tool, with no summary. '
1634
+ + FAILURE_IN_PLAIN_WORDS;
1614
1635
 
1615
1636
  export const answersAPerson = (entry) => (
1616
1637
  entry?.trigger === 'human' && ADDRESSED_EVENT_TYPES.has(entry.event?.type) && !entry.peerFrame
@@ -19,7 +19,7 @@
19
19
 
20
20
  import { Type } from 'typebox';
21
21
  import {
22
- connectMcp, registrableTools, takeServers, toPiResult,
22
+ connectMcp, registrableTools, removeSpawnCredential, takeServers, toPiResult,
23
23
  } from './pi-mcp-client.mjs';
24
24
 
25
25
  export default async function commonlyMcpBridge(pi) {
@@ -34,30 +34,38 @@ export default async function commonlyMcpBridge(pi) {
34
34
  process.stderr.write('[commonly-pi-bridge] no server list on fd 3 — this seat has no commonly_* tools\n');
35
35
  }
36
36
  const clients = [];
37
- for (const server of servers) {
38
- const client = connectMcp(server);
39
- clients.push(client);
40
- try {
41
- await client.initialize();
42
- // A public seat's entries name the tools it is not offered.
43
- const tools = registrableTools(await client.listTools(), server);
44
- for (const tool of tools) {
45
- pi.registerTool({
46
- name: tool.name,
47
- label: tool.name,
48
- description: tool.description || tool.name,
49
- // The server's JSON schema, passed through: pi validates against it as-is.
50
- parameters: Type.Unsafe(tool.inputSchema || { type: 'object', properties: {} }),
51
- async execute(_toolCallId, params) {
52
- return toPiResult(await client.callTool(tool.name, params));
53
- },
54
- });
55
- }
56
- } catch (error) {
57
- process.stderr.write(`[commonly-pi-bridge] ${server.name}: ${error.message}\n`);
58
- }
59
- }
37
+ // Armed before the loop: a failed credential delete below exits the process,
38
+ // and that must not leave a started server running.
60
39
  const shutdown = () => { for (const client of clients) client.close(); };
61
40
  process.on('exit', shutdown);
62
41
  if (typeof pi.on === 'function') pi.on('session_shutdown', shutdown);
42
+ try {
43
+ for (const server of servers) {
44
+ const client = connectMcp(server);
45
+ clients.push(client);
46
+ try {
47
+ await client.initialize();
48
+ // A public seat's entries name the tools it is not offered.
49
+ const tools = registrableTools(await client.listTools(), server);
50
+ for (const tool of tools) {
51
+ pi.registerTool({
52
+ name: tool.name,
53
+ label: tool.name,
54
+ description: tool.description || tool.name,
55
+ // The server's JSON schema, passed through: pi validates against it as-is.
56
+ parameters: Type.Unsafe(tool.inputSchema || { type: 'object', properties: {} }),
57
+ async execute(_toolCallId, params) {
58
+ return toPiResult(await client.callTool(tool.name, params));
59
+ },
60
+ });
61
+ }
62
+ } catch (error) {
63
+ process.stderr.write(`[commonly-pi-bridge] ${server.name}: ${error.message}\n`);
64
+ }
65
+ }
66
+ } finally {
67
+ // Every server has read the credential by now, and pi has not created the
68
+ // session: it awaits this factory first. See removeSpawnCredential.
69
+ removeSpawnCredential(servers);
70
+ }
63
71
  }
@@ -18,7 +18,8 @@
18
18
  */
19
19
 
20
20
  import { spawn } from 'node:child_process';
21
- import { closeSync, readFileSync } from 'node:fs';
21
+ import { closeSync, readFileSync, rmSync } from 'node:fs';
22
+ import { isAbsolute } from 'node:path';
22
23
  import {
23
24
  MCP_PACKAGE, PIPE_READER_VERSION, describeMcpCommand, versionOlderThan,
24
25
  } from '../mcp-server-version.js';
@@ -26,29 +27,36 @@ import {
26
27
  import { CREDENTIAL_FILE_VAR, CREDENTIAL_KEY } from '../credential-file.js';
27
28
 
28
29
  /**
29
- * The grant broker's path. wren's ruling for the daemon-side half of TASK-063:
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
- * too), and not an older backend that still projects it, which is this layer's
34
- * job. Keyed on the PATH and not on the entry's `name`, because the name is
35
- * whatever the declaration says while the path is the broker's. A url that does
36
- * not parse is not this predicate's business — the origin rule in
37
- * `pi.js resolveMcpServers` refuses those before they are carried.
30
+ * The grant broker's path. Keyed on the PATH and not on the entry's `name`,
31
+ * because the name is whatever the declaration says while the path is the
32
+ * broker's. A url that does not parse is not this predicate's business — the
33
+ * origin rule in `pi.js resolveMcpServers` refuses those before they are
34
+ * carried.
35
+ *
36
+ * F175c: a pi turn carries the broker only when it is confined, which for pi
37
+ * means a public seat in the macOS Seatbelt jail (F113b). Every other pi turn
38
+ * refuses it here as well as at the server's projection and in the daemon's
39
+ * guard — this layer is what holds on deploy skew, when the row names no
40
+ * adapter for the server to key on, and in a backend older than the rule.
38
41
  */
39
42
  export const GRANT_BROKER_PATH = '/api/mcp/grants/';
40
43
 
41
44
  /**
42
- * The reason string BOTH halves of this refusal use, verbatim from the server's
43
- * typed refusal (`backend/services/grantBrokerConfinement.ts`: code
44
- * `grant_broker_unconfined`, reason `adapter_cannot_confine`). wren's ruling
45
- * (69829): "Same reason string on both halves" — so a daemon log line and the
46
- * server's `grantBrokerRefusal` field can be read side by side, and neither
47
- * layer grows a vocabulary the other one does not have. Mirrored rather than
48
- * imported: this package does not depend on the backend, so the literal is
49
- * pinned by a test instead.
45
+ * The reason strings BOTH halves of this refusal use, verbatim from the
46
+ * server's typed refusal (`backend/services/grantBrokerConfinement.ts`: code
47
+ * `grant_broker_unconfined`). wren's ruling (69829): "Same reason string on
48
+ * both halves" — so a daemon log line and the server's `grantBrokerRefusal`
49
+ * field can be read side by side, and neither layer grows a vocabulary the
50
+ * other one does not have. Mirrored rather than imported: this package does not
51
+ * depend on the backend, so the literals are pinned by a test instead.
52
+ *
53
+ * `adapter_cannot_confine` is the adapter-wide refusal the other unproven
54
+ * adapters get. pi's own is `adapter_confines_public_only` (F175c): pi carries a
55
+ * grant on a public macOS seat and refuses it on every other one, and naming the
56
+ * agent on the grant (F94) does not lift it.
50
57
  */
51
58
  export const GRANT_BROKER_REFUSAL = 'grant_broker_unconfined: adapter_cannot_confine';
59
+ export const GRANT_BROKER_PUBLIC_ONLY_REFUSAL = 'grant_broker_unconfined: adapter_confines_public_only';
52
60
 
53
61
  /**
54
62
  * Is this url the instance's grant broker? Path-keyed, and the comparison is
@@ -549,6 +557,47 @@ export const isHttpServer = (s) => typeof s?.url === 'string' && s.url.length >
549
557
  * pi at all; pi's own `--exclude-tools` removes the same names as a second
550
558
  * layer.
551
559
  */
560
+ /**
561
+ * Delete this spawn's credential directory from inside pi, before the session
562
+ * exists (F175c). The factory that calls this is awaited before pi creates the
563
+ * session, so the delete precedes every prompt by construction, which the
564
+ * parent's delete at pi's first JSON line cannot promise: that one runs on the
565
+ * parent's event loop, and a locally declared stdio server on a public seat
566
+ * could read the file for a prompt in the gap.
567
+ *
568
+ * The directory comes on the fd 3 list, on the broker entry, because the list is
569
+ * written by the adapter alone and consumed by the read. It is honoured only on
570
+ * a confined broker entry, and it is not an environment variable: a private pi
571
+ * turn passes the launcher's environment through, and an ambient value must
572
+ * never be able to name a directory to delete.
573
+ *
574
+ * pi logs a factory that throws and carries on without it, so a throw here would
575
+ * reach the prompt with the file on disk. A failed delete stops the process
576
+ * instead, and the adapter reports the line below as the turn's error.
577
+ */
578
+ export const removeSpawnCredential = (servers, {
579
+ rm = rmSync,
580
+ exit = process.exit,
581
+ write = (line) => process.stderr.write(line),
582
+ } = {}) => {
583
+ const dirs = new Set((Array.isArray(servers) ? servers : [])
584
+ .filter((s) => s?.confined === true && isHttpServer(s) && isGrantBrokerUrl(s.url)
585
+ && s.credentialDir !== undefined)
586
+ .map((s) => s.credentialDir));
587
+ for (const dir of dirs) {
588
+ try {
589
+ if (typeof dir !== 'string' || !isAbsolute(dir)) throw new Error('the path is not absolute');
590
+ rm(dir, { recursive: true, force: true });
591
+ } catch (error) {
592
+ write(`[commonly-pi-bridge] could not delete this turn's connector credential (${dir}): `
593
+ + `${error?.message || error}; stopping before any prompt runs\n`);
594
+ exit(1);
595
+ return false;
596
+ }
597
+ }
598
+ return true;
599
+ };
600
+
552
601
  export const registrableTools = (tools, server) => {
553
602
  const withheld = new Set(Array.isArray(server?.withheldTools) ? server.withheldTools : []);
554
603
  return withheld.size ? tools.filter((tool) => !withheld.has(tool?.name)) : tools;
@@ -557,12 +606,12 @@ export const registrableTools = (tools, server) => {
557
606
  export const readServers = (raw) => {
558
607
  if (!raw) return [];
559
608
  try {
560
- // The broker is dropped here as well as in pi.js (same reason string, see
561
- // GRANT_BROKER_REFUSAL): this is the last layer before a client is started,
562
- // and the two filters have to agree or a server reaches the bridge as an
563
- // entry the adapter would not have carried.
609
+ // A broker entry is kept only with the adapter's `confined: true` mark,
610
+ // which pi.js sets on a public turn alone (the same reason string, see
611
+ // GRANT_BROKER_PUBLIC_ONLY_REFUSAL): this is the last layer before a client
612
+ // is started, and the two filters have to agree or a server reaches the
613
+ // bridge as an entry the adapter would not have carried.
564
614
  return JSON.parse(raw).filter((s) => s?.name
565
- && (isStdioServer(s) || (isHttpServer(s) && !isGrantBrokerUrl(s.url))));
615
+ && (isStdioServer(s) || (isHttpServer(s) && (!isGrantBrokerUrl(s.url) || s.confined === true))));
566
616
  } catch { return []; }
567
617
  };
568
-
@@ -46,7 +46,7 @@ import { probeVersion } from './tested-version.js';
46
46
  import { resolveOnPath } from '../resolve-on-path.js';
47
47
  import { spawn as childSpawn, spawnSync } from 'child_process';
48
48
  import { createHash, randomUUID } from 'crypto';
49
- import { existsSync, readFileSync, realpathSync } from 'fs';
49
+ import { existsSync, readFileSync, realpathSync, rmSync } from 'fs';
50
50
  import { mkdir, readdir, writeFile } from 'fs/promises';
51
51
  import { homedir } from 'os';
52
52
  import { dirname, isAbsolute, join } from 'path';
@@ -57,7 +57,7 @@ import {
57
57
  } from '../upstream-refusal.js';
58
58
  import { buildMemoryPreamble } from '../memory-bridge.js';
59
59
  import { effectiveSandboxTrust, normalizeSandboxTrust, refuseWorkspaceTrust } from '../environment.js';
60
- import { GRANT_BROKER_REFUSAL, isGrantBrokerUrl } from './pi-mcp-client.mjs';
60
+ import { GRANT_BROKER_PUBLIC_ONLY_REFUSAL, isGrantBrokerUrl } from './pi-mcp-client.mjs';
61
61
  import { deliverSeatCredential, withholdRuntimeCredential } from '../mcp-credential-delivery.js';
62
62
  import { prepareMcpSpawn, publicMcpUnavailableError, selectedMcpVersionDir } from '../mcp-home.js';
63
63
  import { removeCredentialFile, writeCredentialFile } from '../credential-file.js';
@@ -195,12 +195,19 @@ const originOf = (value) => {
195
195
  * refused here as well. A transport pi cannot speak (`sse`, which the schema and
196
196
  * the guard both admit) is refused rather than reinterpreted as one it can.
197
197
  *
198
- * The grant broker is refused outright, by PATH rather than by entry name: it is
199
- * the one http entry that carries authority rather than data, and pi is not
200
- * approved to confine it. The ruling for TASK-063 (`isGrantBrokerUrl` in pi-mcp-client.mjs),
201
- * the daemon-side half of the same refusal the server makes at the projection —
202
- * this is the half that holds on deploy skew, when the row names no adapter for
203
- * the server to key on, and in any backend older than the refusal.
198
+ * The grant broker is carried only on a public turn (F175c), keyed by PATH
199
+ * rather than entry name (`isGrantBrokerUrl` in pi-mcp-client.mjs). It is the
200
+ * one http entry that carries authority rather than data, and a public turn is
201
+ * the only pi turn that is confined: Seatbelt on macOS (`assertSandboxSupported`
202
+ * refuses a public turn anywhere else before this runs), with no built-in tool,
203
+ * so the model cannot open a file at all. A carried broker is marked
204
+ * `confined: true` for the bridge's own filter, and its name is reported on
205
+ * `ctx.grantBrokers` so the spawn can end the credential file's life early. It
206
+ * also names `ctx.credentialDir`, as a path, for the bridge to delete from
207
+ * inside pi (`removeSpawnCredential`).
208
+ * Every other pi turn refuses it, a broker the server flagged as named (F94)
209
+ * included: this is the daemon-side half of the server's
210
+ * `adapter_confines_public_only`, and the half that holds on deploy skew.
204
211
  *
205
212
  * The stdio half does NOT have that property and must not be read as if it did:
206
213
  * a declared stdio command is executed with no allowlist check, here and in both
@@ -223,25 +230,23 @@ export const resolveMcpServers = (mcpServers, ctx = {}) => {
223
230
  console.warn(`[pi] declared MCP server '${server.name}' points at ${origin || '(unparseable)'}, not this instance (${instanceOrigin || 'unknown'}) — not starting it`);
224
231
  continue;
225
232
  }
226
- // The grant broker is the one http entry that carries AUTHORITY rather
227
- // than data: a granted seat acts on external systems as the granter. pi is
228
- // not admitted to grant-broker confinement (it is not in
229
- // ADAPTERS_WITH_GRANT_BROKER; a public pi's Seatbelt jail, F113b, has not been
230
- // reviewed for that), so the reach is refused here as well as at the
231
- // server's projection — this
232
- // layer is what holds when the backend predates that refusal, when the
233
- // row names no adapter for the server to key on, or when a deploy leaves
234
- // the two on different clocks.
235
- if (isGrantBrokerUrl(url)) {
233
+ // The grant broker carries AUTHORITY rather than data: a granted seat acts
234
+ // on external systems as the granter. Only a confined (public) pi turn
235
+ // may hold it; see the header above.
236
+ const grantBroker = isGrantBrokerUrl(url);
237
+ if (grantBroker && !ctx.publicSeat) {
236
238
  // eslint-disable-next-line no-console
237
- 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`);
239
+ console.warn(`[pi] ${GRANT_BROKER_PUBLIC_ONLY_REFUSAL} — refusing the grant broker '${server.name}': pi carries a granter's authority only on a public seat confined by the macOS sandbox, and this seat is not one — declare sandbox.trust 'public' on a Mac, or remove the grant`);
238
240
  continue;
239
241
  }
242
+ if (grantBroker) ctx.grantBrokers?.push(server.name);
240
243
  carried.push({
241
244
  name: server.name,
242
245
  url,
243
246
  headers: Object.fromEntries(Object.entries(server.headers || {}).map(([k, v]) => [k, substitutePlaceholders(v, ctx)])),
244
247
  ...(ctx.publicSeat ? { withheldTools: [...PUBLIC_SEAT_WITHHELD_TOOLS] } : {}),
248
+ ...(grantBroker ? { confined: true } : {}),
249
+ ...(grantBroker && ctx.credentialDir ? { credentialDir: ctx.credentialDir } : {}),
245
250
  });
246
251
  continue;
247
252
  }
@@ -463,10 +468,44 @@ export const extractReply = (stdout) => {
463
468
  return { text, sawAssistant, errors };
464
469
  };
465
470
 
466
- const runPi = ({ command = 'pi', args, cwd, env, payload, timeoutMs, credentials = [], spawnImpl = childSpawn }) => new Promise((resolve, reject) => {
471
+ /**
472
+ * The first whole NDJSON line pi prints, as a callback. In json mode pi writes
473
+ * its session header before it binds the session and sends the prompt, and only
474
+ * after every extension factory has returned (main.js builds the runtime, which
475
+ * loads and awaits each `-e` extension, then print-mode.js writes the header;
476
+ * pi 0.84.1). So the bridge has read the server list and every credential it
477
+ * needed by the time this fires, and the model has not been called yet. Any
478
+ * line that parses with a string `type` counts: a resumed session's header and
479
+ * `agent_start` both come after the extensions too.
480
+ */
481
+ const firstEventWatcher = (onFirstEvent) => {
482
+ let buffer = '';
483
+ let fired = !onFirstEvent;
484
+ return (chunk) => {
485
+ if (fired) return;
486
+ buffer += chunk;
487
+ let nl;
488
+ while (!fired && (nl = buffer.indexOf('\n')) !== -1) {
489
+ const raw = buffer.slice(0, nl);
490
+ buffer = buffer.slice(nl + 1);
491
+ let event;
492
+ try { event = JSON.parse(raw); } catch { continue; }
493
+ if (event && typeof event.type === 'string') {
494
+ fired = true;
495
+ buffer = '';
496
+ onFirstEvent();
497
+ }
498
+ }
499
+ };
500
+ };
501
+
502
+ const runPi = ({
503
+ command = 'pi', args, cwd, env, payload, timeoutMs, credentials = [], spawnImpl = childSpawn, onFirstEvent,
504
+ }) => new Promise((resolve, reject) => {
467
505
  let stdout = '';
468
506
  let stderr = '';
469
507
  let timedOut = false;
508
+ let hookError = null;
470
509
  // fd 3 carries the MCP server list, so the 4th pipe exists exactly when there
471
510
  // is a list to hand over. The bridge reads it at extension load (takeServers).
472
511
  const withList = typeof payload === 'string';
@@ -482,11 +521,26 @@ const runPi = ({ command = 'pi', args, cwd, env, payload, timeoutMs, credentials
482
521
  channel.end(payload);
483
522
  }
484
523
  const timer = setTimeout(() => { timedOut = true; proc.kill('SIGTERM'); }, timeoutMs);
485
- proc.stdout.on('data', (chunk) => { stdout += chunk.toString(); });
524
+ const watch = firstEventWatcher(onFirstEvent);
525
+ proc.stdout.on('data', (chunk) => {
526
+ const text = chunk.toString();
527
+ stdout += text;
528
+ // Synchronous, in the tick the line is parsed. A hook that throws ends the
529
+ // turn: pi is killed and the error is the turn's result.
530
+ try {
531
+ watch(text);
532
+ } catch (err) {
533
+ if (!hookError) {
534
+ hookError = err;
535
+ proc.kill('SIGKILL');
536
+ }
537
+ }
538
+ });
486
539
  proc.stderr.on('data', (chunk) => { stderr += chunk.toString(); });
487
540
  proc.on('error', (err) => { clearTimeout(timer); reject(err); });
488
541
  proc.on('close', (code) => {
489
542
  clearTimeout(timer);
543
+ if (hookError) return reject(hookError);
490
544
  if (timedOut) return reject(new Error(`pi timed out after ${timeoutMs}ms`));
491
545
  const reply = extractReply(stdout);
492
546
  // A refused model route is NOT an error event: pi retries the ladder itself
@@ -628,12 +682,15 @@ export default {
628
682
 
629
683
  const unavailableMcp = [];
630
684
  const mcpReadDirectories = [];
685
+ const grantBrokers = [];
631
686
  const servers = resolveMcpServers(ctx.environment?.mcp, {
632
687
  ...ctx,
633
688
  credentialFile: credential?.path || null,
689
+ credentialDir: credential?.dir || null,
634
690
  publicSeat: isPublic,
635
691
  unavailableMcp,
636
692
  mcpReadDirectories,
693
+ grantBrokers,
637
694
  });
638
695
  if (unavailableMcp.length) throw publicMcpUnavailableError(unavailableMcp);
639
696
  const childEnv = isPublic ? {
@@ -706,6 +763,28 @@ export default {
706
763
  timeoutMs: ctx.timeoutMs || DEFAULT_TIMEOUT_MS,
707
764
  credentials: proxy ? [...credentials, proxy.token] : credentials,
708
765
  spawnImpl: ctx._spawnImpl, // test seam only — do not use in production
766
+ // F175c: a turn holding a grant broker keeps its credential file only
767
+ // until pi has loaded its extensions. The first layer is inside pi: the
768
+ // bridge deletes the directory before its factory returns, which pi
769
+ // awaits before it creates the session (removeSpawnCredential), and
770
+ // stops pi if it cannot. This is the second layer, at pi's first JSON
771
+ // line (firstEventWatcher). It is async to pi, so it cannot be the one
772
+ // that closes the file before a prompt; it normally finds the file gone,
773
+ // and `force` tolerates that. It covers a turn whose bridge never ran. A
774
+ // delete that does fail here still ends the turn.
775
+ onFirstEvent: isPublic && grantBrokers.length && credential
776
+ ? () => {
777
+ try {
778
+ (ctx._rmSync || rmSync)(credential.dir, { recursive: true, force: true });
779
+ } catch (err) {
780
+ throw new Error(
781
+ `pi adapter: a public pi seat could not delete its connector credential (${credential.path}) once pi `
782
+ + `had loaded its extensions: ${err?.message || err}; the turn was stopped so the credential does not `
783
+ + 'stay readable during it',
784
+ );
785
+ }
786
+ }
787
+ : undefined,
709
788
  });
710
789
  // Empty text with a clean exit is a silent turn; the run loop treats it
711
790
  // as NO_REPLY-shaped and re-delivers on its own rules. Empty text that
@@ -54,10 +54,22 @@ export const ADAPTERS_WITH_SANDBOX_ENFORCEMENT = new Set([...ADAPTERS_WITH_DEFAU
54
54
 
55
55
  // Adapters that may receive a room grant: each confines a public seat AND keeps
56
56
  // the per-spawn credential out of its own tools' reach (OpenCode: F175a, its
57
- // external_directory deny with the credential outside --dir). Narrower than the
58
- // sandbox sets above on purpose, and mirrored by the server's
59
- // CONFINING_ADAPTERS (backend/services/grantBrokerConfinement.ts).
60
- export const ADAPTERS_WITH_GRANT_BROKER = new Set(['claude', 'codex', 'opencode']);
57
+ // external_directory deny with the credential outside --dir; pi: F175c, a
58
+ // public turn with no built-in tool, and the credential file deleted once pi
59
+ // has loaded its extensions). Narrower than the sandbox sets above on purpose,
60
+ // and mirrored by the server's CONFINING_ADAPTERS
61
+ // (backend/services/grantBrokerConfinement.ts).
62
+ export const ADAPTERS_WITH_GRANT_BROKER = new Set(['claude', 'codex', 'opencode', 'pi']);
63
+
64
+ // F175c: adapters in the set above that hold a grant ONLY on a confined public
65
+ // seat, and only in the modes and on the hosts listed. pi confines in macOS
66
+ // Seatbelt alone (adapters/pi.js assertSandboxSupported) and is never handed a
67
+ // default sandbox, so a pi seat that declares nothing runs unconfined. Naming
68
+ // the agent on the grant (F94) does not lift this, unlike the sandbox refusals
69
+ // of the other three. Mirrored by the server's PUBLIC_ONLY_GRANT_ADAPTERS.
70
+ export const ADAPTERS_WITH_PUBLIC_ONLY_GRANT = new Map([
71
+ ['pi', Object.freeze({ platforms: new Set(['darwin']), modes: new Set(['workspace', 'read-only']) })],
72
+ ]);
61
73
 
62
74
  /**
63
75
  * The sandbox an unconfigured seat gets.
@@ -17,10 +17,11 @@
17
17
  * hand-written token file). Both halves emit the same `code`.
18
18
  *
19
19
  * THE ADAPTER IS THE HOST-INDEPENDENT FACT, but sandbox support and broker
20
- * admission are separate. OpenCode enforces a public sandbox locally; until
21
- * the server allowlist admits its proven modes, only `claude` and `codex` may
22
- * receive the grant broker. `pi` is also withheld because it refuses a declared
23
- * sandbox rather than honouring it.
20
+ * admission are separate: only ADAPTERS_WITH_GRANT_BROKER may receive the grant
21
+ * broker (claude, codex, OpenCode since F175a, pi since F175c). pi is admitted
22
+ * on a narrower rule (ADAPTERS_WITH_PUBLIC_ONLY_GRANT): a public seat in macOS
23
+ * Seatbelt only, and every other pi declaration is `adapter_confines_public_only`,
24
+ * which a named grant (F94) does not lift.
24
25
  *
25
26
  * ONE REASON THE SERVER DOES NOT HAVE: `sandbox_absent`. The server must ALLOW
26
27
  * an absent block (a daemon-provisioned seat's baseline is derived here and is
@@ -73,7 +74,7 @@
73
74
  * a foreign server cannot be drawn in by its spelling.
74
75
  */
75
76
  import { isGrantBrokerUrl } from './adapters/pi-mcp-client.mjs';
76
- import { ADAPTERS_WITH_GRANT_BROKER } from './default-environment.js';
77
+ import { ADAPTERS_WITH_GRANT_BROKER, ADAPTERS_WITH_PUBLIC_ONLY_GRANT } from './default-environment.js';
77
78
  import { effectiveSandboxTrust } from './environment.js';
78
79
  import { PUBLIC_SANDBOX_MODES, resolvePublicSandboxMode } from './sandbox/mode.js';
79
80
 
@@ -171,6 +172,25 @@ export const declaresGrantBroker = (environment, opts) => (
171
172
  Array.isArray(environment?.mcp) && environment.mcp.some((server) => isOurGrantBroker(server, opts))
172
173
  );
173
174
 
175
+ /**
176
+ * F175c: the one reason naming (F94) does not lift for an adapter on the grant
177
+ * list. pi holds a grant only on a public seat confined by macOS Seatbelt, so
178
+ * every pi declaration short of that is this reason, not a sandbox reason a
179
+ * consent could waive. Same literal as the server's.
180
+ */
181
+ export const PUBLIC_ONLY_REASON = 'adapter_confines_public_only';
182
+
183
+ const publicOnlyReason = (environment, rule, platform) => {
184
+ const sandbox = environment?.sandbox;
185
+ if (sandbox === null || typeof sandbox !== 'object' || Array.isArray(sandbox)) return PUBLIC_ONLY_REASON;
186
+ if (sandbox.mode === 'none' || effectiveSandboxTrust(sandbox.trust) !== 'public') return PUBLIC_ONLY_REASON;
187
+ // D245: a public declaration on native Windows reads the same for every adapter.
188
+ if (platform === 'win32') return 'sandbox_mode_unenforceable';
189
+ if (!rule.platforms.has(platform)) return PUBLIC_ONLY_REASON;
190
+ const mode = resolvePublicSandboxMode(sandbox, platform);
191
+ return typeof mode === 'string' && rule.modes.has(mode) ? null : PUBLIC_ONLY_REASON;
192
+ };
193
+
174
194
  /**
175
195
  * Why this daemon cannot confine a seat running `adapter` with this
176
196
  * environment — or `null` when confinement is enforced and the broker may ride.
@@ -178,6 +198,8 @@ export const declaresGrantBroker = (environment, opts) => (
178
198
  */
179
199
  export const confinementReason = (environment, adapter, platform = process.platform) => {
180
200
  if (!ADAPTERS_WITH_GRANT_BROKER.has(adapter)) return 'adapter_cannot_confine';
201
+ const publicOnly = ADAPTERS_WITH_PUBLIC_ONLY_GRANT.get(adapter);
202
+ if (publicOnly) return publicOnlyReason(environment, publicOnly, platform);
181
203
 
182
204
  const sandbox = environment?.sandbox;
183
205
  if (sandbox === null || typeof sandbox !== 'object' || Array.isArray(sandbox)) return 'sandbox_absent';
@@ -205,6 +227,11 @@ const detailFor = (reason, adapter, environment, platform = process.platform) =>
205
227
  return 'native Windows has no sandbox Commonly can enforce, so no agent on this computer gets connector grants;'
206
228
  + ` run the agent on macOS or Linux to use grants, ${drop}`;
207
229
  }
230
+ if (reason === PUBLIC_ONLY_REASON) {
231
+ return `the seat runs the '${adapter}' adapter, which carries a grant only on a public seat confined by the`
232
+ + " macOS sandbox; declare sandbox.trust 'public' and run it on a Mac, or move it to an adapter that confines"
233
+ + ` this host, ${drop} (naming the agent on the grant does not lift this)`;
234
+ }
208
235
  if (reason === 'adapter_cannot_confine') {
209
236
  return `the seat runs the '${adapter || 'unresolved'}' adapter, which is not approved to receive the grant broker;`
210
237
  + ` move this seat to the ${brokerAdapterList()} adapter, ${drop}`;
@@ -254,7 +281,7 @@ export const withholdGrantBroker = (environment, adapter, {
254
281
  // only; the broker checks the naming on every call. Never on native Windows,
255
282
  // and never for an adapter not approved for the broker.
256
283
  const rides = (server) => server?.byoNamed === true
257
- && reason !== 'adapter_cannot_confine' && platform !== 'win32';
284
+ && reason !== 'adapter_cannot_confine' && reason !== PUBLIC_ONLY_REASON && platform !== 'win32';
258
285
  const isWithheld = (server) => isOurGrantBroker(server, { instanceUrl }) && !rides(server);
259
286
  if (!environment.mcp.some(isWithheld)) return environment;
260
287
 
@@ -303,6 +330,7 @@ export const mergeGrantBrokers = (environment, servers) => {
303
330
 
304
331
  export default {
305
332
  GRANT_BROKER_REFUSAL_CODE,
333
+ PUBLIC_ONLY_REASON,
306
334
  ENFORCING_MODES,
307
335
  isOurGrantBroker,
308
336
  declaresGrantBroker,