@commonlyai/cli 0.1.267 → 0.1.269

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.267",
3
+ "version": "0.1.269",
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,
@@ -130,6 +131,7 @@ import {
130
131
  refusedItemRef,
131
132
  sanitizeHandoffAgent,
132
133
  } from '../lib/content-refusal.js';
134
+ import { CANT_ANSWER_NOTICE_WINDOW_MS, cantAnswerNotice } from '../lib/turn-failure-notice.js';
133
135
  import {
134
136
  ADDRESSED_EVENT_TYPES,
135
137
  CASCADE_DEFAULTS,
@@ -232,10 +234,18 @@ export const runtimeAdapterForInstallation = ({ installations, podId, instanceId
232
234
  return adapter || null;
233
235
  };
234
236
 
235
- /** 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
+ */
236
245
  export const adapterRequiresServerBinding = (adapterName) => {
237
246
  const adapter = String(adapterName || '').trim().toLowerCase();
238
- 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));
239
249
  };
240
250
 
241
251
  const serverRuntimeAdapterProjectionState = (installations) => {
@@ -742,6 +752,12 @@ const PROMPT_EVENT_TYPES = new Set([
742
752
  // event that exists to introduce the seat rather than to answer anyone, so it
743
753
  // is the only one worth holding back.
744
754
  const DEFERRABLE_SOLO_EVENT_TYPES = new Set(['first_contact']);
755
+ // Someone asked this seat for an answer: by type, by the server's stamp, or by
756
+ // replying to it. A batch turn carries the same answer for its items.
757
+ const someoneIsWaiting = (event) => ADDRESSED_EVENT_TYPES.has(event.type)
758
+ || event.payload?.addressed === true
759
+ || event.payload?.repliesToYourMessage === true
760
+ || event.payload?.someoneWaiting === true;
745
761
 
746
762
  // How long a fresh seat's greeting waits for a person before it runs alone.
747
763
  // One poll lost the race on the 0.1.257 walk (2026-11-05): the mention landed
@@ -2369,6 +2385,48 @@ export const performRun = ({
2369
2385
  }
2370
2386
  };
2371
2387
 
2388
+ // A failure only a person can fix, or only time can, leaves a mention
2389
+ // unanswered for as long as it lasts, so each pod with someone waiting is told
2390
+ // why, at most once per cause per pod per hour (persisted, so a restart does
2391
+ // not re-post). A later pod the failed turn stopped before reaching is told
2392
+ // too: a key or an allowance fails every pod alike, and its own turn could be
2393
+ // 45 minutes away. A notice that fails to post is logged and tried at the next
2394
+ // failure; the retry goes ahead either way.
2395
+ const noticeCantAnswer = async (error, waitingEvents) => {
2396
+ const notice = cantAnswerNotice(error);
2397
+ if (!notice || modelUnavailableFailure(error)) return;
2398
+ const waitingPods = new Set(waitingEvents
2399
+ .filter(someoneIsWaiting)
2400
+ .map((event) => event.podId || podId)
2401
+ .filter(Boolean));
2402
+ for (const waitingPod of waitingPods) {
2403
+ const key = `cant-answer:${notice.cause}:${waitingPod}`;
2404
+ try {
2405
+ // eslint-disable-next-line no-continue
2406
+ if (!noticeDue(agentName, key, CANT_ANSWER_NOTICE_WINDOW_MS)) continue;
2407
+ // eslint-disable-next-line no-await-in-loop
2408
+ const delivery = await deliverChatReply({
2409
+ client,
2410
+ podId: waitingPod,
2411
+ text: notice.text,
2412
+ limit: chatCharLimit,
2413
+ maxChunks: maxChatChunks,
2414
+ uploadName: `${agentName}-cant-answer.md`,
2415
+ log: (line) => log(`[inbox.batch] ${line}`),
2416
+ });
2417
+ if (delivery.skipped || delivery.refused) {
2418
+ log(`[inbox.batch] pod ${waitingPod} was not told why this agent can't answer: `
2419
+ + `${delivery.reason || 'the notice was not posted'}`);
2420
+ } else {
2421
+ recordNotice(agentName, key);
2422
+ log(`[inbox.batch] told pod ${waitingPod} why this agent can't answer (${notice.cause})`);
2423
+ }
2424
+ } catch (noticeError) {
2425
+ log(`[inbox.batch] pod ${waitingPod} was not told why this agent can't answer: ${noticeError.message}`);
2426
+ }
2427
+ }
2428
+ };
2429
+
2372
2430
  const runTurnBody = async ({
2373
2431
  event, eventPodId, prompt, preSpawnIds, snapshotMessages, claimKeeper, trigger, turn,
2374
2432
  }) => {
@@ -2963,6 +3021,8 @@ export const performRun = ({
2963
3021
  // any other wake it is terminal. The free-text detail stays in the seat
2964
3022
  // log and the event ack; the kernel records the class.
2965
3023
  if (!delivered && upstream) {
3024
+ // pi exits 0 on a refused route, so no failure reaches the retry path.
3025
+ await noticeCantAnswer(new Error(describeUpstreamRefusal(upstream)), [event]);
2966
3026
  return {
2967
3027
  outcome: 'no_action',
2968
3028
  refused: {
@@ -3590,6 +3650,7 @@ export const performRun = ({
3590
3650
  ...actionEntries[0].event.payload,
3591
3651
  batchEventIds: entries.filter((entry) => !entry.pastCap).map((entry) => String(entry.event._id)),
3592
3652
  hasHeartbeat: entries.some((entry) => !entry.pastCap && entry.event.type === 'heartbeat'),
3653
+ someoneWaiting: entries.some((entry) => !entry.pastCap && someoneIsWaiting(entry.event)),
3593
3654
  },
3594
3655
  };
3595
3656
  // One item, run as its own turn. Used only after the provider refused a
@@ -3606,6 +3667,7 @@ export const performRun = ({
3606
3667
  ...entry.event.payload,
3607
3668
  batchEventIds: [String(entry.event._id)],
3608
3669
  hasHeartbeat: entry.event.type === 'heartbeat',
3670
+ someoneWaiting: someoneIsWaiting(entry.event),
3609
3671
  },
3610
3672
  },
3611
3673
  eventPodId,
@@ -3959,6 +4021,7 @@ export const performRun = ({
3959
4021
  });
3960
4022
  if (onError) onError(wrapped);
3961
4023
  else log(`[inbox.batch] ${wrapped.message}`);
4024
+ await noticeCantAnswer(err, [...failedEvents, ...untriedAfter(groupIndex)]);
3962
4025
  };
3963
4026
  let batch;
3964
4027
  try {
@@ -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,
@@ -103,6 +103,12 @@ const CONTENT_REFUSED_RE = /(?:flagged for possible cybersecurity risk|this cont
103
103
  // adjacent `.`+digit is rare enough in provider copy to accept. The test below
104
104
  // pins what the pattern ACTUALLY has — a space after the period ends the match —
105
105
  // rather than the stronger property it does not have.
106
+ // The gateway's two budget refusals. A key over its budget answers 422 with this
107
+ // exact text (walked on a real key, 2026-11-06); a model group over its monthly
108
+ // pool answers 429 "crossed budget" (our gateway config). Case-sensitive, so a
109
+ // "thinking budget has been exceeded" stays out. Unmatched, the 422 is RUNTIME
110
+ // and the seat respawns every few seconds against a key that stays refused.
111
+ export const GATEWAY_BUDGET_RE = /Budget has been exceeded!|crossed budget/;
106
112
  const QUOTA_RE = /(?:quota|usage limit|session limit|weekly limit|credit balance|out of credits|billing|insufficient[_ -]?quota|resource exhausted|spending limit)/i;
107
113
  const QUOTA_POSSESSIVE_RE = /you'?ve (?:hit|reached) your (?!rate[ -]?limit)(?:[^.\n]|\.(?=\d)){0,40}?limit/i;
108
114
  // The status code is not a throttle wording: "429: You've reached your Fable 5
@@ -139,7 +145,7 @@ export const classifySpawnFailure = (error) => {
139
145
  // Provider APIs commonly report an exhausted account quota as HTTP 429.
140
146
  // Prefer the more specific body/message over the generic status code so a
141
147
  // hard quota failure gets the long cooldown rather than a one-minute probe.
142
- if (QUOTA_RE.test(text)) return SPAWN_FAILURE_CLASS.QUOTA;
148
+ if (QUOTA_RE.test(text) || GATEWAY_BUDGET_RE.test(text)) return SPAWN_FAILURE_CLASS.QUOTA;
143
149
  // The possessive shape is deliberately loose about what sits between "your"
144
150
  // and "limit", and its `(?!rate[ -]?limit)` lookahead only guards the word
145
151
  // IMMEDIATELY after "your" — so "you've hit your API rate limit" walked past
@@ -0,0 +1,73 @@
1
+ /**
2
+ * A seat that can't run a turn goes quiet (2026-11-06).
3
+ *
4
+ * The turn fails, the run loop opens the circuit and retries in 15 minutes, and
5
+ * the only trace is a line in a terminal the person in the pod may not own.
6
+ * They see their @mention go unanswered, with no reason. The wrapper, not the
7
+ * model, posts one plain line instead, since no model turn can run. It names
8
+ * the cause and who can fix it. It never quotes the error text, which is vendor
9
+ * output and can carry key material.
10
+ *
11
+ * The failure classes in spawn-retry.js are too loose for this. They only pick a
12
+ * backoff, so a stray "401" or "billing" in a stack trace costs a slower retry.
13
+ * Here the match becomes a statement to a person, so each line below fires only
14
+ * on a wording a seat has logged, a walk has produced, or the wrapper or our own
15
+ * gateway config writes. A failure that matches none of them posts nothing,
16
+ * which is what it did before.
17
+ */
18
+ import { PUBLIC_MCP_NOT_READY_CODE, PUBLIC_TOOL_FAILED_CODE } from './public-tool-error.js';
19
+ import { classifySpawnFailure, GATEWAY_BUDGET_RE, SPAWN_FAILURE_CLASS } from './spawn-retry.js';
20
+
21
+ /** How long one cause stays posted in a pod before the seat may post it again. */
22
+ export const CANT_ANSWER_NOTICE_WINDOW_MS = 60 * 60 * 1000;
23
+
24
+ const LOGIN_FAILED_WORDINGS = [
25
+ // Not `(upstream 401)` alone: adapterFailure writes that for any "status 401"
26
+ // in a tail, including a tool's stderr. A failed Codex turn is its own report.
27
+ /^codex turn failed \(upstream 401\)/,
28
+ /\bupstream refused 401\b/, // the same refusal, read from pi's stream
29
+ /^\w+ exited(?: with code)? \d+: 401\b/, // pi's text, which names no upstream
30
+ /workspace routing discovery unauthorized/,
31
+ /(?:^|: | \| )Not logged in · Please run \/login/,
32
+ /API Error: 400 This API key is not scoped to a workspace/,
33
+ // The wrapper's own refusals of a Claude login (adapters/claude.js).
34
+ /the Claude login on this machine expires in/,
35
+ /refusing a Claude login/,
36
+ ];
37
+ const WONT_START_WORDINGS = [
38
+ /^spawn \S+ ENOENT/,
39
+ /^\w+ adapter: \S+ (?:is not set|is missing)/, // the seat has no provider key
40
+ ];
41
+ // Not the whole of QUOTA_RE, which also holds "billing" and "quota" for backoff.
42
+ const OUT_OF_ALLOWANCE_WORDINGS = [
43
+ /(?:^|: | \| )you['’]?ve (?:hit|reached) your [^\n]{0,40}?limit/i,
44
+ /\bout of credits\b/i,
45
+ GATEWAY_BUDGET_RE,
46
+ ];
47
+
48
+ const AGAIN = 'After that, send your message again if I still haven’t answered.';
49
+
50
+ export const LOGIN_NOTICE = 'I can’t answer right now: the key or login on the computer I run on isn’t working. '
51
+ + `Whoever runs me needs to fix it and start me again. ${AGAIN}`;
52
+ export const WONT_START_NOTICE = 'I can’t answer right now: the tool I run on wouldn’t start on my computer. '
53
+ + `Whoever runs me needs to fix that and start me again. ${AGAIN}`;
54
+ export const OUT_OF_ALLOWANCE_NOTICE = 'I can’t answer right now: the AI account I run on has used up its allowance. '
55
+ + `It needs to reset, or whoever runs me needs to add more. ${AGAIN}`;
56
+
57
+ const matches = (wordings, text) => wordings.some((wording) => wording.test(text));
58
+
59
+ /** The cause a pod should hear about, and its line, or null when it should hear nothing. */
60
+ export const cantAnswerNotice = (error) => {
61
+ // A public seat's withheld turn quotes a TOOL's error, not its own provider's.
62
+ if (error?.code === PUBLIC_TOOL_FAILED_CODE || error?.code === PUBLIC_MCP_NOT_READY_CODE) return null;
63
+ // A crashed claude turn keeps assistant and tool JSON lines in its tail, and
64
+ // those are the model's words, or a tool's.
65
+ const text = String(error?.message ?? '').split(/(?:^|: | \| |\n)\{"type":/)[0];
66
+ // Before the allowance check: a 401 is settled, whatever else its body says.
67
+ if (matches(LOGIN_FAILED_WORDINGS, text)) return { cause: 'login', text: LOGIN_NOTICE };
68
+ if (matches(WONT_START_WORDINGS, text)) return { cause: 'wont-start', text: WONT_START_NOTICE };
69
+ if (classifySpawnFailure(error) === SPAWN_FAILURE_CLASS.QUOTA && matches(OUT_OF_ALLOWANCE_WORDINGS, text)) {
70
+ return { cause: 'out-of-allowance', text: OUT_OF_ALLOWANCE_NOTICE };
71
+ }
72
+ return null;
73
+ };