@commonlyai/cli 0.1.276 → 0.1.278

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.276",
3
+ "version": "0.1.278",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -116,7 +116,7 @@ Good reasons to ping someone (proactively — this is normal, not exceptional):
116
116
  How to reach out:
117
117
  - **`commonly_request_decision(...)`** for a genuine advisory fork where a
118
118
  human must choose among 2–4 concrete options. Mark one recommended and add
119
- context; when a specific person should rule, address them with `@human` in
119
+ context; when a specific person should rule, address them by their real `@handle` in
120
120
  the question (pod-wide choices need no invented target). The tool posts the
121
121
  interactive card; its later ruling arrives as a `decision.ruled` event. Do not duplicate it as
122
122
  a chat ask, and do not treat it as permission for a privileged action.
@@ -0,0 +1,76 @@
1
+ /**
2
+ * The stdio server a harness runs to reach the grant broker (F175b, F175d).
3
+ *
4
+ * Codex, Qwen and Goose can't hold the broker's bearer token in an HTTP entry
5
+ * without putting it somewhere the rule forbids: Codex reads it from an env
6
+ * var, Qwen sends `--mcp-config` headers literally, and Goose fills a header
7
+ * from its own environment or a literal in the recipe (measured on Qwen 0.26.2
8
+ * and Goose 1.54.0). So each runs our bridge (codex-broker-bridge.mjs), told
9
+ * the broker's url, its headers as templates and the path of this spawn's
10
+ * credential file. None of those is a secret. The token stays in that one file,
11
+ * and the bridge reads it for each request.
12
+ *
13
+ * Whether a seat may hold the broker at all was decided before the adapter
14
+ * (grant-broker-guard.js). This decides whether THIS entry can be wired, and a
15
+ * command the entry declares is never run.
16
+ */
17
+ import {
18
+ BRIDGE_HEADERS_VAR, BRIDGE_PATH, BRIDGE_URL_VAR, CREDENTIAL_FILE_VAR,
19
+ } from './codex-broker-bridge.mjs';
20
+
21
+ // A server name becomes a config key or a tool-name prefix.
22
+ export const SERVER_NAME = /^[A-Za-z0-9_-]+$/;
23
+ // What fetch accepts in a header: Latin-1, no CR, LF or NUL.
24
+ // eslint-disable-next-line no-control-regex
25
+ const HEADER_TEXT = /^[^\r\n\0Ā-￿]*$/;
26
+ const INSTANCE_PLACEHOLDER = /\$\{(?:COMMONLY_API_URL|COMMONLY_INSTANCE_URL)\}/g;
27
+
28
+ /**
29
+ * `{ command, args, env, readPath }`, or `{ skip }` with why it can't be wired.
30
+ * `readPath` is the one file a jailed seat must be able to read: the bridge
31
+ * imports node builtins only.
32
+ */
33
+ export const brokerBridgeEntry = (server, { instanceUrl, credentialFile, runtimeToken } = {}) => {
34
+ if (!SERVER_NAME.test(server?.name || '')) return { skip: 'its name is not a plain config key' };
35
+ if (!credentialFile) return { skip: 'there is no seat credential to read' };
36
+ // Resolve the instance placeholders only: the token placeholder stays in the
37
+ // header template and is filled by the bridge from the file.
38
+ const resolve = (value) => String(value).replace(INSTANCE_PLACEHOLDER, (whole) => instanceUrl || whole);
39
+ const resolvedUrl = resolve(server.url);
40
+ const headers = Object.fromEntries(Object.entries(server.headers || {})
41
+ .map(([name, value]) => [String(name), resolve(String(value))]));
42
+ const carriesToken = (value) => !!runtimeToken && value.includes(runtimeToken);
43
+ if (carriesToken(resolvedUrl)
44
+ || Object.entries(headers).some(([name, value]) => carriesToken(name) || carriesToken(value))) {
45
+ return { skip: 'the entry holds the seat token as a literal, which would ride a config' };
46
+ }
47
+ if (resolvedUrl.includes('${')) return { skip: 'its url holds a placeholder this host cannot resolve' };
48
+ // A header fetch would reject quotes its value in the error, and that value
49
+ // holds the token once the bridge fills it, so such an entry is not wired.
50
+ if (Object.entries(headers).some(([name, value]) => !HEADER_TEXT.test(name) || !HEADER_TEXT.test(value))) {
51
+ return { skip: 'a header holds a control or non-Latin-1 character' };
52
+ }
53
+ // The url the guard judged (isOurGrantBroker) is normalised: resolved against
54
+ // the instance, with doubled slashes collapsed. The bridge fetches that same
55
+ // url, on the instance's own origin, or nothing.
56
+ let url;
57
+ try {
58
+ const instance = new URL(instanceUrl);
59
+ const parsed = new URL(resolvedUrl, instance);
60
+ if (parsed.origin !== instance.origin) return { skip: 'its url is not on this instance' };
61
+ parsed.pathname = parsed.pathname.replace(/\/{2,}/g, '/');
62
+ url = parsed.href;
63
+ } catch {
64
+ return { skip: 'its url does not resolve against this instance' };
65
+ }
66
+ return {
67
+ command: process.execPath,
68
+ args: [BRIDGE_PATH],
69
+ env: {
70
+ [BRIDGE_URL_VAR]: url,
71
+ [BRIDGE_HEADERS_VAR]: JSON.stringify(headers),
72
+ [CREDENTIAL_FILE_VAR]: credentialFile,
73
+ },
74
+ readPath: BRIDGE_PATH,
75
+ };
76
+ };
@@ -788,28 +788,28 @@ const parseEvent = (line) => {
788
788
  }
789
789
  };
790
790
 
791
- // The reply is the `result` event's text. A turn that reaches no result event
792
- // (killed mid-stream, exit 0) gets the text of its assistant events, never the
793
- // raw NDJSON. Output with no JSON lines at all is plain text and returned as it
794
- // arrived. A result flagged `is_error` is a failed turn, whatever its exit code,
795
- // so it is raised here, outside the parse guard, and never returned as a reply.
791
+ const STOPPED_TURN = 'the turn stopped before it finished';
792
+
793
+ // The reply is the `result` event's text. A turn with no result event stopped
794
+ // before it finished: SIGINT exits 0 without printing one (claude 2.1.318), with
795
+ // or without assistant text, and before startup it prints nothing at all. That
796
+ // text isn't an answer, since each assistant event may be an interim message on
797
+ // the way to a tool, and empty text would read as a turn with nothing to say.
798
+ // Other output with no JSON lines is plain text and returned as it arrived. A
799
+ // result flagged `is_error` is a failed turn, whatever its exit code, so it is
800
+ // raised here, outside the parse guard, and never returned as a reply.
796
801
  export const claudeResultText = (stdout, { credentials = [] } = {}) => {
797
802
  const text = String(stdout || '');
798
803
  const events = text.split('\n').map(parseEvent);
799
- if (!events.some(Boolean)) return text.trim();
804
+ if (text.trim() && !events.some(Boolean)) return text.trim();
800
805
  for (let i = events.length - 1; i >= 0; i -= 1) {
801
806
  if (events[i]?.type !== 'result') continue;
802
807
  const reply = String(events[i].result ?? '').trim();
803
- if (events[i].is_error === true) throw adapterFailure('claude', reply, { credentials });
808
+ // An interrupted request reports error_during_execution with empty text.
809
+ if (events[i].is_error === true) throw adapterFailure('claude', reply || STOPPED_TURN, { credentials });
804
810
  return reply;
805
811
  }
806
- return events
807
- .filter((event) => event?.type === 'assistant')
808
- .flatMap((event) => event.message?.content || [])
809
- .filter((block) => block?.type === 'text')
810
- .map((block) => block.text)
811
- .join('')
812
- .trim();
812
+ throw adapterFailure('claude', STOPPED_TURN, { credentials });
813
813
  };
814
814
 
815
815
  // TASK-256: what a public seat's own stream says about its Commonly MCP server.
@@ -71,9 +71,10 @@ import {
71
71
  join,
72
72
  resolve as pathResolve,
73
73
  } from 'path';
74
- import { CREDENTIAL_FILE_VAR, CREDENTIAL_KEY, writeCredentialFile } from '../credential-file.js';
74
+ import { CREDENTIAL_KEY, writeCredentialFile } from '../credential-file.js';
75
75
  import { isOurGrantBroker } from '../grant-broker-guard.js';
76
- import { BRIDGE_HEADERS_VAR, BRIDGE_PATH, BRIDGE_URL_VAR } from './codex-broker-bridge.mjs';
76
+ import { BRIDGE_PATH } from './codex-broker-bridge.mjs';
77
+ import { brokerBridgeEntry } from './broker-bridge-entry.js';
77
78
  import { supportedGitHooks } from '../commit-attribution.js';
78
79
  import { deliverSeatCredential, withholdRuntimeCredential } from '../mcp-credential-delivery.js';
79
80
  import { prepareMcpSpawn, publicMcpUnavailableError, selectedMcpVersionDir } from '../mcp-home.js';
@@ -159,69 +160,25 @@ const substitutePlaceholders = (value, ctx) => {
159
160
  const toml = (s) => JSON.stringify(String(s));
160
161
 
161
162
  const HTTP_TRANSPORTS = new Set(['http', 'streamable-http']);
162
- // A server name becomes a TOML key path, so it must not hold a dot.
163
- const SERVER_NAME = /^[A-Za-z0-9_-]+$/;
164
- // What fetch accepts in a header: Latin-1, no CR, LF or NUL.
165
- // eslint-disable-next-line no-control-regex
166
- const HEADER_TEXT = /^[^\r\n\0\u0100-\uffff]*$/;
167
163
 
168
164
  // F175b: the grant broker is a Streamable HTTP server and codex runs stdio
169
165
  // servers here, so the broker is wired as OUR stdio bridge
170
- // (codex-broker-bridge.mjs) with the broker's url, its headers as templates and
171
- // this spawn's credential-file path, none of them a secret. The command the
172
- // entry declares, if any, is never run. Whether this seat may hold the broker
173
- // at all was decided before the adapter (grant-broker-guard.js), which
174
- // withholds it from a seat that is not confined.
166
+ // (broker-bridge-entry.js). Whether this seat may hold the broker at all was
167
+ // decided before the adapter (grant-broker-guard.js).
175
168
  const bridgeGrantBroker = (server, ctx) => {
176
- const skip = (why) => {
169
+ const entry = brokerBridgeEntry(server, ctx);
170
+ if (entry.skip) {
177
171
  // eslint-disable-next-line no-console
178
- console.warn(`[codex] grant broker ${server.name}: ${why}, so it is not wired for this spawn.`);
172
+ console.warn(`[codex] grant broker ${server.name}: ${entry.skip}, so it is not wired for this spawn.`);
179
173
  return null;
180
- };
181
- if (!SERVER_NAME.test(server.name)) return skip('its name is not a plain config key');
182
- if (!ctx.credentialFile) return skip('there is no seat credential to read');
183
- // Resolve the instance placeholders only: the token placeholder stays in the
184
- // header template and is filled by the bridge from the file.
185
- const resolve = (value) => substitutePlaceholders(value, { instanceUrl: ctx.instanceUrl });
186
- const resolvedUrl = resolve(server.url);
187
- const headers = Object.fromEntries(Object.entries(server.headers || {})
188
- .map(([name, value]) => [String(name), resolve(String(value))]));
189
- const carriesToken = (value) => !!ctx.runtimeToken && value.includes(ctx.runtimeToken);
190
- if (carriesToken(resolvedUrl)
191
- || Object.entries(headers).some(([name, value]) => carriesToken(name) || carriesToken(value))) {
192
- return skip('the entry holds the seat token as a literal, which would ride argv');
193
- }
194
- if (resolvedUrl.includes('${')) return skip('its url holds a placeholder this host cannot resolve');
195
- // A header fetch would reject quotes its value in the error, and that value
196
- // holds the token once the bridge fills it, so such an entry is not wired.
197
- if (Object.entries(headers).some(([name, value]) => !HEADER_TEXT.test(name) || !HEADER_TEXT.test(value))) {
198
- return skip('a header holds a control or non-Latin-1 character');
199
174
  }
200
- // The url the guard judged (isOurGrantBroker) is normalised: resolved against
201
- // the instance, with doubled slashes collapsed. The bridge fetches that same
202
- // url, on the instance's own origin, or nothing.
203
- let url;
204
- try {
205
- const instance = new URL(ctx.instanceUrl);
206
- const parsed = new URL(resolvedUrl, instance);
207
- if (parsed.origin !== instance.origin) return skip('its url is not on this instance');
208
- parsed.pathname = parsed.pathname.replace(/\/{2,}/g, '/');
209
- url = parsed.href;
210
- } catch {
211
- return skip('its url does not resolve against this instance');
212
- }
213
- const env = [
214
- [BRIDGE_URL_VAR, url],
215
- [BRIDGE_HEADERS_VAR, JSON.stringify(headers)],
216
- [CREDENTIAL_FILE_VAR, ctx.credentialFile],
217
- ];
218
175
  return [
219
- '-c', `mcp_servers.${server.name}.command=${toml(process.execPath)}`,
176
+ '-c', `mcp_servers.${server.name}.command=${toml(entry.command)}`,
220
177
  // The broker parks every write for the owner's approval itself, so codex
221
178
  // approving the call is the same boundary the stdio servers get below.
222
179
  '-c', `mcp_servers.${server.name}.default_tools_approval_mode="approve"`,
223
- '-c', `mcp_servers.${server.name}.args=[${toml(BRIDGE_PATH)}]`,
224
- '-c', `mcp_servers.${server.name}.env={${env.map(([key, value]) => `${key} = ${toml(value)}`).join(', ')}}`,
180
+ '-c', `mcp_servers.${server.name}.args=[${entry.args.map(toml).join(', ')}]`,
181
+ '-c', `mcp_servers.${server.name}.env={${Object.entries(entry.env).map(([key, value]) => `${key} = ${toml(value)}`).join(', ')}}`,
225
182
  ];
226
183
  };
227
184
 
@@ -18,6 +18,9 @@ import { detectBwrap, wrapArgvWithBwrap } from '../sandbox/bwrap.js';
18
18
  import { wrapArgvWithSeatbelt } from '../sandbox/seatbelt.js';
19
19
  import { refuseWorkspaceHoldingTurnDirs } from '../sandbox/turn-dir.js';
20
20
  import { adapterFailure, spawnCredentials } from '../upstream-refusal.js';
21
+ import { isOurGrantBroker } from '../grant-broker-guard.js';
22
+ import { brokerBridgeEntry } from './broker-bridge-entry.js';
23
+ import { BRIDGE_PATH } from './codex-broker-bridge.mjs';
21
24
 
22
25
  // A version enters this list only after a real headless turn with that binary.
23
26
  export const TESTED_GOOSE_VERSIONS = Object.freeze(['1.54.0']);
@@ -95,13 +98,37 @@ const substitute = (value, ctx) => String(value).replace(PLACEHOLDER_RE, (whole,
95
98
  COMMONLY_INSTANCE_URL: ctx.instanceUrl,
96
99
  }[name] || whole));
97
100
 
101
+ /**
102
+ * F175d: the grant broker as a recipe extension running our stdio bridge, or
103
+ * null when this entry can't be wired. Goose fills an HTTP header from its own
104
+ * environment or a literal in the recipe, and neither keeps the token to the
105
+ * credential file. No `available_tools`: the broker lists only what the grant
106
+ * holds, and re-checks the grant and this seat on every call.
107
+ */
108
+ export const bridgedGooseExtension = (server, ctx) => {
109
+ const entry = brokerBridgeEntry(server, ctx);
110
+ if (entry.skip) {
111
+ // eslint-disable-next-line no-console
112
+ console.warn(`[goose] grant broker ${server.name}: ${entry.skip}, so it is not wired for this spawn.`);
113
+ return null;
114
+ }
115
+ return { type: 'stdio', name: server.name, cmd: entry.command, args: entry.args, envs: entry.env };
116
+ };
117
+
98
118
  /** The flag contains paths and URLs only. Literal MCP secrets cannot ride argv. */
99
119
  export const extensionArgs = (servers, ctx) => {
100
120
  const args = [];
101
- if (ctx.publicSeat && (!Array.isArray(servers) || servers.length !== 1)) {
121
+ // A broker is the one extra a public seat may hold. A private seat has no
122
+ // jail, so the guard withholds its broker, and an entry that reaches here
123
+ // anyway meets the HTTP refusal below.
124
+ const declared = Array.isArray(servers) ? servers : [];
125
+ const brokers = ctx.publicSeat
126
+ ? declared.filter((server) => isOurGrantBroker(server, { instanceUrl: ctx.instanceUrl })) : [];
127
+ const others = declared.filter((server) => !brokers.includes(server));
128
+ if (ctx.publicSeat && others.length !== 1) {
102
129
  throw new Error('goose adapter: public seats require only the Commonly MCP extension');
103
130
  }
104
- for (const server of servers || []) {
131
+ for (const server of others) {
105
132
  if (ctx.publicSeat && (server.name !== 'commonly' || (server.transport || 'stdio') !== 'stdio'
106
133
  || !describeMcpCommand(server.command)?.isCommonly)) {
107
134
  throw new Error('goose adapter: public seats require only the Commonly stdio MCP extension');
@@ -164,6 +191,14 @@ export const extensionArgs = (servers, ctx) => {
164
191
  args.push('--with-extension', `${server.name}:${[...env, ...commandWords].join(' ')}`);
165
192
  }
166
193
  }
194
+ for (const server of brokers) {
195
+ const extension = bridgedGooseExtension(server, ctx);
196
+ if (extension) {
197
+ ctx.publicExtensions.push(extension);
198
+ ctx.brokerExtensions?.add(extension.name);
199
+ ctx.mcpReadDirectories?.push(BRIDGE_PATH);
200
+ }
201
+ }
167
202
  return args;
168
203
  };
169
204
 
@@ -186,7 +221,9 @@ export const readGooseStream = (stdout) => {
186
221
  return { text, error, complete };
187
222
  };
188
223
 
189
- const runGoose = ({ binary, args, cwd, env, timeoutMs, credentials, spawnImpl = childSpawn }) => new Promise((resolve, reject) => {
224
+ const runGoose = ({
225
+ binary, args, cwd, env, timeoutMs, credentials, optionalExtensions = new Set(), spawnImpl = childSpawn,
226
+ }) => new Promise((resolve, reject) => {
190
227
  const child = spawnImpl(binary, args, { cwd, env, stdio: ['ignore', 'pipe', 'pipe'] });
191
228
  let stdout = '';
192
229
  const stdoutDecoder = new StringDecoder('utf8');
@@ -221,7 +258,10 @@ const runGoose = ({ binary, args, cwd, env, timeoutMs, credentials, spawnImpl =
221
258
  });
222
259
  child.stderr?.on('data', (chunk) => {
223
260
  const received = chunk.toString();
224
- extensionFailure ||= (stderr + received).match(/Failed to start extension '[^']+'[^\n]*/)?.[0] || null;
261
+ // A broker that won't start (a grant refused at the door, the instance
262
+ // down) costs that grant, not the turn: the seat still answers the pod.
263
+ extensionFailure ||= [...(stderr + received).matchAll(/Failed to start extension '([^']+)'[^\n]*/g)]
264
+ .find((failure) => !optionalExtensions.has(failure[1]))?.[0] || null;
225
265
  stderr = (stderr + received).slice(-8192);
226
266
  });
227
267
  child.on('error', (error) => finish(error));
@@ -309,6 +349,7 @@ export default {
309
349
  });
310
350
  const mcpReadDirectories = [];
311
351
  const publicExtensions = [];
352
+ const brokerExtensions = new Set();
312
353
  // Node's compiled-in OpenSSL config can sit outside the permitted tree
313
354
  // (including hostedtoolcache on CI). Use our empty config, retaining
314
355
  // Node's bundled TLS roots, instead of granting host configuration reads.
@@ -325,7 +366,7 @@ export default {
325
366
  ...extensionArgs(ctx.environment?.mcp, {
326
367
  credentialFile: credential?.path || '', instanceUrl: ctx.instanceUrl || '',
327
368
  runtimeToken: ctx.runtimeToken || '',
328
- publicSeat: isPublic, mcpReadDirectories, publicExtensions,
369
+ publicSeat: isPublic, mcpReadDirectories, publicExtensions, brokerExtensions,
329
370
  }),
330
371
  ...(!isPublic ? ['-t', buildMemoryPreamble(prompt, ctx.memoryLongTerm, { freshSession: true })] : []),
331
372
  ];
@@ -387,6 +428,7 @@ export default {
387
428
  const text = await runGoose({
388
429
  binary: executable, args: spawnArgs, cwd: ctx.cwd, env, timeoutMs,
389
430
  credentials: [...spawnCredentials(ctx, [DEFAULT_PROVIDER_KEY]), key, env.OPENAI_API_KEY],
431
+ optionalExtensions: brokerExtensions,
390
432
  spawnImpl: ctx._spawnImpl,
391
433
  });
392
434
  return { text, newSessionId: null };
@@ -52,6 +52,7 @@ import { homedir } from 'os';
52
52
  import { dirname, isAbsolute, join } from 'path';
53
53
  import { fileURLToPath } from 'url';
54
54
  import {
55
+ adapterFailure,
55
56
  readUpstreamRefusal,
56
57
  spawnCredentials,
57
58
  } from '../upstream-refusal.js';
@@ -450,10 +451,18 @@ export const buildArgs = ({
450
451
  prompt,
451
452
  ];
452
453
 
453
- /** The reply is the last assistant `message_end`'s text parts; tool calls are not text. */
454
+ /**
455
+ * The reply is the last assistant `message_end`'s text parts; tool calls are not
456
+ * text. `finished` means pi ended the turn on an answer: `agent_end`, not retried,
457
+ * after an assistant message that stopped with `stop`. An overflow's `agent_end`
458
+ * says `willRetry: false` and then pi compacts and continues, so `agent_end` after
459
+ * an `error` or `length` stop doesn't count; the continuation's message decides.
460
+ */
454
461
  export const extractReply = (stdout) => {
455
462
  let text = '';
456
463
  let sawAssistant = false;
464
+ let finished = false;
465
+ let lastStop = null;
457
466
  const errors = [];
458
467
  for (const line of String(stdout).split('\n')) {
459
468
  if (!line.trim()) continue;
@@ -462,10 +471,33 @@ export const extractReply = (stdout) => {
462
471
  if (event?.type === 'message_end' && event.message?.role === 'assistant') {
463
472
  const parts = (event.message.content || []).filter((c) => c?.type === 'text').map((c) => c.text || '');
464
473
  if (parts.length) { text = parts.join('\n').trim(); sawAssistant = true; }
474
+ lastStop = event.message.stopReason;
475
+ finished = false;
465
476
  }
477
+ if (event?.type === 'agent_end') finished = event.willRetry !== true && lastStop === 'stop';
466
478
  if (event?.type === 'error') errors.push(String(event.message || event.error || 'error'));
467
479
  }
468
- return { text, sawAssistant, errors };
480
+ return { text, sawAssistant, finished, errors };
481
+ };
482
+
483
+ // A turn that printed an interim message and then ended without finishing. A
484
+ // crash keeps its cause, so a quota line in stderr or a refusal on the stream
485
+ // still classifies. A signal (143, 129, or a null code) has neither: stderr then
486
+ // holds pi's startup warnings, and a refusal on the stream may be one pi was
487
+ // recovering from, like an overflow's 400.
488
+ const stoppedTurnFailure = (reply, {
489
+ code, signal, stderr, credentials,
490
+ }) => {
491
+ const killed = Boolean(signal) || code === 143 || code === 129;
492
+ const upstream = killed ? null : reply.upstream;
493
+ const failure = adapterFailure(
494
+ 'pi',
495
+ reply.errors.join(' | ') || (killed ? '' : stderr.trim().slice(-600)) || upstream?.detail
496
+ || 'the turn stopped before it finished',
497
+ { credentials, exitCode: code, limit: 600 },
498
+ );
499
+ if (upstream) failure.status ??= upstream.status;
500
+ return failure;
469
501
  };
470
502
 
471
503
  /**
@@ -538,7 +570,7 @@ const runPi = ({
538
570
  });
539
571
  proc.stderr.on('data', (chunk) => { stderr += chunk.toString(); });
540
572
  proc.on('error', (err) => { clearTimeout(timer); reject(err); });
541
- proc.on('close', (code) => {
573
+ proc.on('close', (code, signal) => {
542
574
  clearTimeout(timer);
543
575
  if (hookError) return reject(hookError);
544
576
  if (timedOut) return reject(new Error(`pi timed out after ${timeoutMs}ms`));
@@ -548,7 +580,16 @@ const runPi = ({
548
580
  // on the stream rather than on the exit code (TASK-096, measured 2026-09-22).
549
581
  const upstream = readUpstreamRefusal(stdout, { credentials });
550
582
  if (upstream) reply.upstream = upstream;
551
- if (code !== 0 && !reply.sawAssistant) {
583
+ // Without `finished`, the text pi printed was an interim message, so posting
584
+ // it would answer with half a turn and acknowledge what it held. An error
585
+ // event fails the turn even after `finished`, which could otherwise read as
586
+ // silent. A tool-only turn that finished stays silent, whatever the exit.
587
+ if (code !== 0 && (!reply.finished || reply.errors.length)) {
588
+ if (reply.sawAssistant) {
589
+ return reject(stoppedTurnFailure(reply, {
590
+ code, signal, stderr, credentials,
591
+ }));
592
+ }
552
593
  const tail = (reply.errors.join(' | ') || stderr).trim().slice(-600);
553
594
  return reject(new Error(`pi exited ${code}: ${tail}`));
554
595
  }
@@ -19,9 +19,18 @@ import { refuseWorkspaceHoldingTurnDirs } from '../sandbox/turn-dir.js';
19
19
  import { resolveProviderKeyFile, startProviderProxy } from '../provider-proxy.js';
20
20
  import { adapterFailure, spawnCredentials } from '../upstream-refusal.js';
21
21
  import { PUBLIC_SEAT_WITHHELD_TOOLS } from '../public-withheld-tools.js';
22
+ import { isOurGrantBroker } from '../grant-broker-guard.js';
23
+ import { brokerBridgeEntry } from './broker-bridge-entry.js';
24
+ import { describeMcpCommand } from '../mcp-server-version.js';
22
25
 
23
26
  // Add a version only with a passing real clean-box sandbox smoke that names it.
24
27
  const TESTED_QWEN_VERSIONS = Object.freeze(['0.25.1', '0.26.2']);
28
+ // What keeps a broker-holding seat off its credential is a list of denied
29
+ // built-ins, so a version with a file-reading tool the list doesn't name could
30
+ // reach it. A broker rides only a version that passed the grant proof
31
+ // (qwen.grant-broker.public-smoke.test.mjs), compared exactly: no later patch
32
+ // and no host override. Narrower than TESTED_QWEN_VERSIONS on purpose.
33
+ export const GRANT_TESTED_QWEN_VERSIONS = Object.freeze(['0.26.2']);
25
34
  const ALLOW_UNTESTED_QWEN_VERSION_ENV = 'COMMONLY_QWEN_ALLOW_UNTESTED_VERSION';
26
35
  const DEFAULT_TIMEOUT_MS = 15 * 60 * 1000;
27
36
  const TERMINATION_GRACE_MS = 5000;
@@ -93,6 +102,34 @@ const substitute = (value, ctx) => String(value).replace(/\$\{(COMMONLY_[A-Z_]+)
93
102
  COMMONLY_INSTANCE_URL: ctx.instanceUrl,
94
103
  }[name] || whole));
95
104
 
105
+ const isCommonlyStdio = (server) => server?.name === 'commonly'
106
+ && (server.transport || 'stdio') === 'stdio'
107
+ && Boolean(describeMcpCommand(server.command)?.isCommonly);
108
+
109
+ /**
110
+ * The turn's servers. A public seat holds a broker only on a proven version,
111
+ * with the Commonly server as its one other entry, as Goose requires: a second
112
+ * server could read the credential file from the jail, or replace an entry by
113
+ * name and inherit its tool approval. Otherwise the broker goes and the turn runs.
114
+ */
115
+ export const withoutUnprovenBroker = (servers, { version, isPublic, instanceUrl }) => {
116
+ if (!isPublic || !Array.isArray(servers)) return servers;
117
+ const brokers = servers.filter((server) => isOurGrantBroker(server, { instanceUrl }));
118
+ if (!brokers.length) return servers;
119
+ const others = servers.filter((server) => !brokers.includes(server));
120
+ const proven = GRANT_TESTED_QWEN_VERSIONS.includes(version);
121
+ const alone = others.every(isCommonlyStdio);
122
+ if (proven && alone) return servers;
123
+ const why = proven
124
+ ? 'another MCP server is declared beside it'
125
+ : `not on Qwen ${version || 'unknown'}, which hasn't passed the grant proof (${GRANT_TESTED_QWEN_VERSIONS.join(', ')})`;
126
+ for (const broker of brokers) {
127
+ // eslint-disable-next-line no-console
128
+ console.warn(`[qwen] grant broker ${broker.name}: ${why}, so this turn runs without it.`);
129
+ }
130
+ return others;
131
+ };
132
+
96
133
  export const buildQwenMcpConfig = (servers, ctx) => {
97
134
  const mcpServers = {};
98
135
  for (const server of servers || []) {
@@ -122,6 +159,9 @@ export const buildQwenMcpConfig = (servers, ctx) => {
122
159
  mcpServers[server.name] = {
123
160
  command: command[0], args, env,
124
161
  ...(server.cwd ? { cwd: server.cwd } : {}),
162
+ // `--exclude-tools` refuses these at the call and still lists them for
163
+ // the model (measured on 0.26.2), so the server entry drops them too.
164
+ ...(ctx.publicSeat ? { excludeTools: [...PUBLIC_SEAT_WITHHELD_TOOLS] } : {}),
125
165
  };
126
166
  const versionDir = ctx.publicSeat && selectedMcpVersionDir(command);
127
167
  if (versionDir) ctx.mcpReadDirectories?.push(versionDir);
@@ -130,6 +170,22 @@ export const buildQwenMcpConfig = (servers, ctx) => {
130
170
  if (transport !== 'http' || typeof server.url !== 'string') {
131
171
  throw new Error(`Qwen MCP server ${server.name} has unsupported transport`);
132
172
  }
173
+ // F175d: Qwen sends these headers literally (no `${VAR}`, no file), so the
174
+ // broker runs behind the stdio bridge. Public seats only: a private seat
175
+ // has no jail, so the guard withholds its broker, and an entry that reaches
176
+ // here anyway falls through to the refusal below.
177
+ if (ctx.publicSeat && isOurGrantBroker(server, { instanceUrl: ctx.instanceUrl })) {
178
+ const entry = brokerBridgeEntry(server, ctx);
179
+ if (entry.skip) {
180
+ // eslint-disable-next-line no-console
181
+ console.warn(`[qwen] grant broker ${server.name}: ${entry.skip}, so it is not wired for this spawn.`);
182
+ continue;
183
+ }
184
+ mcpServers[server.name] = { command: entry.command, args: entry.args, env: entry.env };
185
+ ctx.mcpReadDirectories?.push(entry.readPath);
186
+ ctx.bridgedBrokers?.push(server.name);
187
+ continue;
188
+ }
133
189
  const httpUrl = substitute(server.url, ctx);
134
190
  const headers = Object.fromEntries(Object.entries(server.headers || {})
135
191
  .map(([name, value]) => [name, substitute(value, ctx)]));
@@ -301,13 +357,18 @@ export default {
301
357
  const proxyWithBearer = { ...proxy, bearer: (await readFile(proxy.tokenFile, 'utf8')).trim() };
302
358
  const unavailableMcp = [];
303
359
  const mcpReadDirectories = [];
304
- const mcp = buildQwenMcpConfig(ctx.environment?.mcp, {
360
+ const bridgedBrokers = [];
361
+ const turnServers = withoutUnprovenBroker(ctx.environment?.mcp, {
362
+ version, isPublic, instanceUrl: ctx.instanceUrl || '',
363
+ });
364
+ const mcp = buildQwenMcpConfig(turnServers, {
305
365
  credentialFile: credential?.path || '',
306
366
  instanceUrl: ctx.instanceUrl || '',
307
367
  runtimeToken: ctx.runtimeToken || '',
308
368
  publicSeat: isPublic,
309
369
  unavailableMcp,
310
370
  mcpReadDirectories,
371
+ bridgedBrokers,
311
372
  });
312
373
  if (unavailableMcp.length) throw publicMcpUnavailableError(unavailableMcp);
313
374
  await Promise.all([
@@ -325,6 +386,9 @@ export default {
325
386
  // F118: a public seat reads its memory but is not offered a write.
326
387
  memoryReadOnly: isPublic,
327
388
  });
389
+ const allowedTools = [
390
+ ...(Object.hasOwn(mcp.mcpServers, 'commonly') ? ['commonly'] : []), ...bridgedBrokers,
391
+ ].map((name) => `mcp__${name}__*`);
328
392
  const args = [
329
393
  '--bare', '--safe-mode', '--auth-type', 'openai', '-m', seatModel,
330
394
  '--mcp-config', mcpPath, '--exclude-tools', [
@@ -336,17 +400,20 @@ export default {
336
400
  // without it a public seat's commonly_post_message was declined
337
401
  // (D247 walk, 11-04). Public parity with Claude's --allowedTools
338
402
  // mcp__commonly__*; the withheld tools stay in --exclude-tools above.
339
- ...(Object.hasOwn(mcp.mcpServers, 'commonly')
340
- ? ['--allowed-tools', 'mcp__commonly__*'] : []),
403
+ // The broker parks every write for the owner itself (F175d).
404
+ ...(allowedTools.length ? ['--allowed-tools', allowedTools.join(',')] : []),
341
405
  '-o', 'stream-json', '-p', fullPrompt,
342
406
  ];
343
407
  let cmd = executable;
344
408
  let spawnArgs = args;
345
409
  if (isPublic && mode === 'bwrap') {
346
410
  if (!isAbsolute(executable)) throw new Error('public Qwen seats require an absolute qwen executable path');
411
+ // bwrap binds a symlink's target at the link's path, so npm's `.bin/qwen`
412
+ // would lose the `./cli.js` beside it. The real entry keeps its package.
413
+ const bwrapEntry = symlinkedBinary ? realpathSync(executable) : executable;
347
414
  const bwrap = (ctx._detectBwrap || detectBwrap)();
348
415
  if (!bwrap.available) throw new Error(`public Qwen seats require bwrap: ${bwrap.error}`);
349
- [cmd, ...spawnArgs] = (ctx._wrapArgvWithBwrap || wrapArgvWithBwrap)([executable, ...args], {
416
+ [cmd, ...spawnArgs] = (ctx._wrapArgvWithBwrap || wrapArgvWithBwrap)([bwrapEntry, ...args], {
350
417
  ...ctx.environment,
351
418
  sandbox: {
352
419
  ...sandbox,
@@ -360,7 +427,7 @@ export default {
360
427
  }, {
361
428
  workspacePath: ctx.cwd,
362
429
  homePath: home,
363
- readOnlyPaths: [tempDir, executable, packageDir, process.execPath, ...mcpReadDirectories].filter(Boolean),
430
+ readOnlyPaths: [tempDir, bwrapEntry, packageDir, process.execPath, ...mcpReadDirectories].filter(Boolean),
364
431
  });
365
432
  } else if (isPublic) {
366
433
  if ((ctx._platform || process.platform) !== 'darwin') {
@@ -56,19 +56,29 @@ export const ADAPTERS_WITH_SANDBOX_ENFORCEMENT = new Set([...ADAPTERS_WITH_DEFAU
56
56
  // the per-spawn credential out of its own tools' reach (OpenCode: F175a, its
57
57
  // external_directory deny with the credential outside --dir; pi: F175c, a
58
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
59
+ // has loaded its extensions; Qwen and Goose: F175d, a public turn that offers no
60
+ // file or shell tool, with the broker behind the stdio bridge so the token
61
+ // stays in one file). Narrower than the sandbox sets above on purpose, and
62
+ // mirrored by the server's CONFINING_ADAPTERS
61
63
  // (backend/services/grantBrokerConfinement.ts).
62
- export const ADAPTERS_WITH_GRANT_BROKER = new Set(['claude', 'codex', 'opencode', 'pi']);
64
+ export const ADAPTERS_WITH_GRANT_BROKER = new Set(['claude', 'codex', 'opencode', 'pi', 'qwen', 'goose']);
63
65
 
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.
66
+ // The modes a jail enforces, by host: what an adapter's spawn turns into
67
+ // Seatbelt on macOS and bubblewrap on Linux.
68
+ const SEATBELT_MODES = new Set(['workspace', 'read-only']);
69
+ const BWRAP_MODES = new Set(['bwrap']);
70
+
71
+ // F175c, F175d: adapters in the set above that hold a grant ONLY on a confined
72
+ // public seat, in the modes each host's jail enforces; a host with no entry has
73
+ // no jail for it. Each runs a private seat with no sandbox at all, so a private
74
+ // seat is never confined. pi confines in macOS Seatbelt alone
75
+ // (adapters/pi.js assertSandboxSupported). Naming the agent on the grant (F94)
76
+ // does not lift this, unlike the sandbox refusals of Claude, Codex and OpenCode.
77
+ // Mirrored by the server's PUBLIC_ONLY_GRANT_ADAPTERS.
70
78
  export const ADAPTERS_WITH_PUBLIC_ONLY_GRANT = new Map([
71
- ['pi', Object.freeze({ platforms: new Set(['darwin']), modes: new Set(['workspace', 'read-only']) })],
79
+ ['pi', Object.freeze({ darwin: SEATBELT_MODES })],
80
+ ['qwen', Object.freeze({ darwin: SEATBELT_MODES, linux: BWRAP_MODES })],
81
+ ['goose', Object.freeze({ darwin: SEATBELT_MODES, linux: BWRAP_MODES })],
72
82
  ]);
73
83
 
74
84
  /**
@@ -95,8 +105,7 @@ export const ADAPTERS_WITH_PUBLIC_ONLY_GRANT = new Map([
95
105
  * Claude, codex, opencode and qwen receive this default block
96
106
  * (ADAPTERS_WITH_DEFAULT_SANDBOX). Goose and pi support explicitly configured
97
107
  * public confinement, but are not defaulted into it (see the set's comment).
98
- * Grant-broker eligibility is
99
- * narrower until the server admits OpenCode after its confinement proof.
108
+ * Grant-broker eligibility is its own list (ADAPTERS_WITH_GRANT_BROKER).
100
109
  */
101
110
  export const COMMONLY_DEFAULT_SANDBOX = Object.freeze({ trust: 'public' });
102
111
 
@@ -37,7 +37,7 @@ export const CLAIMABLE_EVENT_TYPES = new Set([
37
37
  // whether the work genuinely cannot continue without a human ruling.
38
38
  export const DECISION_FORK_FRAME = [
39
39
  '[Decision forks]',
40
- 'If you are blocked on a genuine fork that needs a human choice, use your runtime\'s decision-card tool (MCP: commonly_request_decision); include @human when a specific person should rule, and do not duplicate the card with a prose @ask.',
40
+ 'If you are blocked on a genuine fork that needs a human choice, use your runtime\'s decision-card tool (MCP: commonly_request_decision); include that person\'s real @handle when a specific person should rule, and do not duplicate the card with a prose @ask.',
41
41
  'Use it only when you cannot safely continue before a ruling. Give 2–4 concrete options and mark one recommendation.',
42
42
  'Use ordinary pod messages for status, factual questions, and coordination that do not require a human choice.',
43
43
  ].join('\n');
@@ -18,10 +18,11 @@
18
18
  *
19
19
  * THE ADAPTER IS THE HOST-INDEPENDENT FACT, but sandbox support and broker
20
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.
21
+ * broker (claude, codex, OpenCode since F175a, pi since F175c, Qwen and Goose
22
+ * since F175d). pi, Qwen and Goose are admitted on a narrower rule
23
+ * (ADAPTERS_WITH_PUBLIC_ONLY_GRANT): a public seat in a jail this host has (for
24
+ * pi, macOS Seatbelt only), and every other declaration is
25
+ * `adapter_confines_public_only`, which a named grant (F94) does not lift.
25
26
  *
26
27
  * ONE REASON THE SERVER DOES NOT HAVE: `sandbox_absent`. The server must ALLOW
27
28
  * an absent block (a daemon-provisioned seat's baseline is derived here and is
@@ -174,9 +175,9 @@ export const declaresGrantBroker = (environment, opts) => (
174
175
 
175
176
  /**
176
177
  * 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.
178
+ * list. pi, Qwen and Goose hold a grant only on a public seat in a jail, so
179
+ * every declaration of theirs short of that is this reason, not a sandbox
180
+ * reason a consent could waive. Same literal as the server's.
180
181
  */
181
182
  export const PUBLIC_ONLY_REASON = 'adapter_confines_public_only';
182
183
 
@@ -186,9 +187,10 @@ const publicOnlyReason = (environment, rule, platform) => {
186
187
  if (sandbox.mode === 'none' || effectiveSandboxTrust(sandbox.trust) !== 'public') return PUBLIC_ONLY_REASON;
187
188
  // D245: a public declaration on native Windows reads the same for every adapter.
188
189
  if (platform === 'win32') return 'sandbox_mode_unenforceable';
189
- if (!rule.platforms.has(platform)) return PUBLIC_ONLY_REASON;
190
+ const modes = Object.hasOwn(rule, platform) ? rule[platform] : null;
191
+ if (!modes) return PUBLIC_ONLY_REASON;
190
192
  const mode = resolvePublicSandboxMode(sandbox, platform);
191
- return typeof mode === 'string' && rule.modes.has(mode) ? null : PUBLIC_ONLY_REASON;
193
+ return typeof mode === 'string' && modes.has(mode) ? null : PUBLIC_ONLY_REASON;
192
194
  };
193
195
 
194
196
  /**
@@ -229,9 +231,11 @@ const detailFor = (reason, adapter, environment, platform = process.platform) =>
229
231
  + ` run the agent on macOS or Linux to use grants, ${drop}`;
230
232
  }
231
233
  if (reason === PUBLIC_ONLY_REASON) {
234
+ const jails = Object.keys(ADAPTERS_WITH_PUBLIC_ONLY_GRANT.get(adapter) || {});
235
+ const macOnly = jails.length === 1 && jails[0] === 'darwin';
232
236
  return `the seat runs the '${adapter}' adapter, which carries a grant only on a public seat confined by the`
233
- + " macOS sandbox; declare sandbox.trust 'public' and run it on a Mac, or move it to an adapter that confines"
234
- + ` this host, ${drop} (naming the agent on the grant does not lift this)`;
237
+ + `${macOnly ? ' macOS' : ''} sandbox; declare sandbox.trust 'public'${macOnly ? ' and run it on a Mac' : ''},`
238
+ + ` or move it to an adapter that confines this host, ${drop} (naming the agent on the grant does not lift this)`;
235
239
  }
236
240
  if (reason === 'adapter_cannot_confine') {
237
241
  return `the seat runs the '${adapter || 'unresolved'}' adapter, which is not approved to receive the grant broker;`