@commonlyai/cli 0.1.253 → 0.1.255

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.253",
3
+ "version": "0.1.255",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -81,7 +81,7 @@ import {
81
81
  withDefaultMcpServer,
82
82
  withDefaultSandbox,
83
83
  } from '../lib/default-environment.js';
84
- import { withholdGrantBroker } from '../lib/grant-broker-guard.js';
84
+ import { mergeGrantBrokers, withholdGrantBroker } from '../lib/grant-broker-guard.js';
85
85
  import {
86
86
  FOCUS_FRAME_MAX_CODE_POINTS,
87
87
  formatPodFocusFrame,
@@ -1667,6 +1667,9 @@ export const performRun = ({
1667
1667
  // saved on the server before each turn. Off for daemon seats, whose daemon
1668
1668
  // projects the same values into `environment`.
1669
1669
  readSavedControls = false,
1670
+ // F150: a seat with no daemon reads its live grant brokers before each turn.
1671
+ // Off for daemon seats, whose daemon merges /assigned's into the record.
1672
+ readGrantBrokers = false,
1670
1673
  resolveOwnProviderKey = null,
1671
1674
  runtimeReportClient = null,
1672
1675
  refusalHandoff = null,
@@ -1744,26 +1747,60 @@ export const performRun = ({
1744
1747
  return spawnPolicyPromise;
1745
1748
  };
1746
1749
 
1747
- // THE SEAT'S OWN RECORD IS THE ONLY DECLARATION THERE IS. The broker reaches a
1748
- // seat as an injected MCP entry written by hand into its environment — no
1749
- // server projection puts it there (`GRANT_BROKER_URL` is imported by one
1750
- // route, the daemon assignment, and that one already refuses). So a seat run
1751
- // by `commonly agent run` under launchd spawns the entry verbatim, and the
1752
- // confinement it promises is declared in a different field (`sandbox`), which
1753
- // can disagree. The daemon half of this refusal already runs
1754
- // (`daemon-supervisor.js`); this is the same predicate at the only other site
1755
- // that can see the record — same code, so one refusal with two emitters.
1750
+ // THE BROKER REACHES A SEAT AS AN INJECTED MCP ENTRY, and the confinement it
1751
+ // promises is declared in a different field (`sandbox`), which can disagree.
1752
+ // Two sources put the entry there. Under the daemon, its work list
1753
+ // (`/api/agent-binding/assigned`) merges the seat's live grants into the
1754
+ // record before this process starts. Without a daemon (`readGrantBrokers`),
1755
+ // this loop reads `/api/agents/runtime/grant-brokers` itself, before every
1756
+ // turn, and merges the same projection the same way (`mergeGrantBrokers`)
1757
+ // (F150). Either way the entry is then judged HERE by `withholdGrantBroker`,
1758
+ // the same predicate the daemon runs: one refusal with two emitters, so the
1759
+ // server's answer can add a broker and the seat's own guard can still
1760
+ // withhold it (pi, an absent sandbox the grant does not name).
1756
1761
  //
1757
- // IN MEMORY, RECORD UNTOUCHED: the withheld environment is what
1758
- // the adapter spawns with, and the stored record keeps its broker, so the
1759
- // daemon stays the layer that judges a host it knows. Applied once for the
1760
- // run rather than per turn: `agent run` reads its record once at boot.
1761
- const requestedSeatEnvironment = withholdGrantBroker(environment, adapter?.name, {
1762
- instanceUrl,
1763
- onRefuse: (refusal, names) => log(
1764
- `${refusal.code} (${refusal.reason}) — withholding ${names.join(', ')}: ${refusal.detail}`,
1765
- ),
1766
- });
1762
+ // IN MEMORY, RECORD UNTOUCHED: the withheld environment is what the adapter
1763
+ // spawns with, and the stored record keeps its own entries, so the daemon
1764
+ // stays the layer that judges a host it knows.
1765
+ //
1766
+ // Read per turn, not once at boot: a grant is revoked or expires while a seat
1767
+ // runs, and one GET beside the per-turn reads already made here is cheap; the
1768
+ // daemon re-reads /assigned every 30s and restarts the seat, which is coarser.
1769
+ // A failed read keeps the last answer: a stale entry reaches nothing, because
1770
+ // the broker re-reads the grant and refuses a revoked or expired one on every
1771
+ // call (`toolBrokerService` → `assertGrantUsable`).
1772
+ let lastRefusalKey = null;
1773
+ const guardedEnvironment = (grantBrokers) => withholdGrantBroker(
1774
+ mergeGrantBrokers(environment, grantBrokers), adapter?.name, {
1775
+ instanceUrl,
1776
+ onRefuse: (refusal, names) => {
1777
+ // Said once per change, not once per turn.
1778
+ const key = `${refusal.reason}:${names.join(',')}`;
1779
+ if (key === lastRefusalKey) return;
1780
+ lastRefusalKey = key;
1781
+ log(`${refusal.code} (${refusal.reason}) — withholding ${names.join(', ')}: ${refusal.detail}`);
1782
+ },
1783
+ },
1784
+ );
1785
+ let lastGrantBrokers = [];
1786
+ let lastServerGrantRefusal = null;
1787
+ let requestedSeatEnvironment = guardedEnvironment(lastGrantBrokers);
1788
+ const refreshGrantBrokers = async () => {
1789
+ if (!readGrantBrokers) return;
1790
+ try {
1791
+ const projection = await client.get('/api/agents/runtime/grant-brokers', { adapter: adapter?.name }, {
1792
+ signal: AbortSignal.timeout(5000),
1793
+ });
1794
+ lastGrantBrokers = Array.isArray(projection?.servers) ? projection.servers : [];
1795
+ const refusal = projection?.refusal || null;
1796
+ const refusalKey = refusal ? `${refusal.reason}` : null;
1797
+ if (refusal && refusalKey !== lastServerGrantRefusal) {
1798
+ log(`${refusal.code} (${refusal.reason}) — a live grant was withheld by the server: ${refusal.detail}`);
1799
+ }
1800
+ lastServerGrantRefusal = refusalKey;
1801
+ } catch { /* keep the last answer; the broker refuses a revoked grant on every call */ }
1802
+ requestedSeatEnvironment = guardedEnvironment(lastGrantBrokers);
1803
+ };
1767
1804
  // Without native effort inventory a machine runner cannot promise that a
1768
1805
  // stored effort is supported. Preserve the record and use harness default.
1769
1806
  // Standalone CLI behavior remains under the operator's control.
@@ -1860,6 +1897,7 @@ export const performRun = ({
1860
1897
  let savedControlsNoticeShown = false;
1861
1898
  const refreshSeatEnvironment = async () => {
1862
1899
  const inventory = await runtimeInventoryPromise;
1900
+ await refreshGrantBrokers();
1863
1901
  let desiredEnvironment = requestedSeatEnvironment;
1864
1902
  if (readSavedControls) {
1865
1903
  try {
@@ -1871,11 +1909,15 @@ export const performRun = ({
1871
1909
  ...(identity && 'runtimeSourcePodId' in identity ? { runtimeSourcePodId: identity.runtimeSourcePodId } : {}),
1872
1910
  });
1873
1911
  } catch { /* keep the last controls read; a failed read changes nothing */ }
1874
- desiredEnvironment = withSavedRuntimeControls(requestedSeatEnvironment, lastSavedControls);
1912
+ // Keyed on the RECORD's environment, not the merged one: grant brokers
1913
+ // (F150) can give a record with none an `mcp` list, and that must not
1914
+ // turn on saved controls the notice below says don't apply.
1915
+ desiredEnvironment = environment
1916
+ ? withSavedRuntimeControls(requestedSeatEnvironment, lastSavedControls) : requestedSeatEnvironment;
1875
1917
  // A record with no environment (from before attach wrote one) isn't
1876
1918
  // given one silently. `agent config` writes one to the record, and from
1877
1919
  // then on saved controls apply. Say so once, with the command.
1878
- if (!requestedSeatEnvironment && lastSavedControls && !savedControlsNoticeShown) {
1920
+ if (!environment && lastSavedControls && !savedControlsNoticeShown) {
1879
1921
  savedControlsNoticeShown = true;
1880
1922
  const flag = (name, value) => (value && /^[A-Za-z0-9._:/-]+$/.test(value) ? ` --${name} ${value}` : '');
1881
1923
  const flags = `${flag('model', lastSavedControls.model)}${flag('effort', lastSavedControls.effort)}` || ' --model <model>';
@@ -4490,6 +4532,7 @@ Docs:
4490
4532
  machineId: record.machineId, agentName: record.agentName, instanceId: record.instanceId }),
4491
4533
  reportRuntime: Boolean(record.machineId || process.env.COMMONLY_MANAGED_RUNNER === '1'),
4492
4534
  readSavedControls: !record.machineId && process.env.COMMONLY_MANAGED_RUNNER !== '1',
4535
+ readGrantBrokers: !record.machineId && process.env.COMMONLY_MANAGED_RUNNER !== '1',
4493
4536
  spawnCredentialTtlSeconds: resolveSpawnTtlSeconds(process.env),
4494
4537
  refusalHandoff: opts.refusalHandoff || null,
4495
4538
  log: (line) => console.log(`${stamp()} [${name}] ${line}`),
@@ -0,0 +1,255 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * The grant broker, as a stdio MCP server codex can run (F175b).
4
+ *
5
+ * codex is admitted for the grant broker (ADAPTERS_WITH_GRANT_BROKER), but the
6
+ * broker is a Streamable HTTP server (`grantBrokerServer`) and codex.js wires
7
+ * stdio servers only, so a granted codex seat used to receive the entry and
8
+ * drop it. codex's own url transport is no way round that: it reads a bearer
9
+ * token from an environment variable (`bearer_token_env_var`), which would put
10
+ * the token back in codex's environment and in every MCP child it spawns, the
11
+ * thing TASK-083 took out.
12
+ *
13
+ * So codex runs this file, and this file speaks HTTP to the broker. It holds no
14
+ * token of its own. It is told three things, none of them a secret:
15
+ * - COMMONLY_BROKER_URL: the broker url, already resolved to this instance;
16
+ * - COMMONLY_BROKER_HEADERS: the declared headers as TEMPLATES, still holding
17
+ * `${COMMONLY_AGENT_TOKEN}`;
18
+ * - COMMONLY_TOKEN_FILE: the path of this spawn's 0600 credential file, the
19
+ * same file the commonly MCP server reads.
20
+ * The token is read from that file on every request (as claude's headersHelper
21
+ * does), so it exists only in this process's memory and in the request header.
22
+ *
23
+ * It is a pass-through: each JSON-RPC line from codex is POSTed as it is, and
24
+ * every message in the answer (plain JSON or an event stream) is written back
25
+ * as a line. The broker is stateless, but a session id and the negotiated
26
+ * protocol version are carried the way the spec asks, so a stateful server
27
+ * would work too.
28
+ *
29
+ * It imports node builtins only. On a public seat codex runs it under the
30
+ * seat's permission profile, which is granted read on THIS file alone; an
31
+ * import from elsewhere in the CLI would need a wider grant. So the two small
32
+ * pieces it shares with the rest of the CLI are restated here, and a test pins
33
+ * the import list.
34
+ */
35
+ import { readFileSync, realpathSync } from 'node:fs';
36
+ import { createInterface } from 'node:readline';
37
+ import { fileURLToPath } from 'node:url';
38
+
39
+
40
+ export const BRIDGE_PATH = fileURLToPath(import.meta.url);
41
+ export const BRIDGE_URL_VAR = 'COMMONLY_BROKER_URL';
42
+ export const BRIDGE_HEADERS_VAR = 'COMMONLY_BROKER_HEADERS';
43
+ export const TOKEN_PLACEHOLDER = '${COMMONLY_AGENT_TOKEN}';
44
+
45
+ // The same name as credential-file.js CREDENTIAL_FILE_VAR (a test pins it).
46
+ export const CREDENTIAL_FILE_VAR = 'COMMONLY_TOKEN_FILE';
47
+
48
+ const MAX_ERROR_TEXT = 2048;
49
+
50
+ // Streamable HTTP answers a POST with one JSON object or with an event stream
51
+ // of `data:` payloads. Same reading as pi-mcp-client.mjs parseMessages: the body
52
+ // decides before the header does.
53
+ const ssePayloads = (text) => text.split(/\r?\n\r?\n/)
54
+ .map((block) => block.split(/\r?\n/)
55
+ .filter((line) => line.startsWith('data:'))
56
+ .map((line) => line.slice(5).trimStart())
57
+ .join('\n'))
58
+ .filter(Boolean);
59
+
60
+ const parseMessages = (text, contentType) => {
61
+ const body = text.trim();
62
+ if (!body) return [];
63
+ if (contentType.includes('text/event-stream')) return ssePayloads(body);
64
+ if (body.startsWith('{') || body.startsWith('[')) return [body];
65
+ return ssePayloads(body);
66
+ };
67
+
68
+ const rpcError = (id, code, message) => ({ jsonrpc: '2.0', id: id ?? null, error: { code, message } });
69
+
70
+ export const createBrokerBridge = ({
71
+ url,
72
+ headerTemplates = {},
73
+ tokenFile,
74
+ fetchImpl = globalThis.fetch,
75
+ write,
76
+ timeoutMs = 120_000,
77
+ }) => {
78
+ let sessionId = null;
79
+ let protocolVersion = null;
80
+ let lastToken = null;
81
+ // Nothing the bridge writes back may hold the token, whatever produced it.
82
+ const scrub = (text) => (lastToken ? String(text).split(lastToken).join('[token]') : String(text));
83
+
84
+ const readToken = () => {
85
+ if (!tokenFile) throw new Error(`no credential file (${CREDENTIAL_FILE_VAR} is unset)`);
86
+ let token;
87
+ try {
88
+ token = readFileSync(tokenFile, 'utf8').trim();
89
+ } catch (error) {
90
+ throw new Error(`cannot read the credential file: ${error?.code || error?.message || error}`);
91
+ }
92
+ if (!token) throw new Error('the credential file is empty');
93
+ lastToken = token;
94
+ return token;
95
+ };
96
+
97
+ const headers = () => {
98
+ const templates = Object.entries(headerTemplates);
99
+ const token = templates.some(([, v]) => String(v).includes(TOKEN_PLACEHOLDER)) ? readToken() : null;
100
+ return {
101
+ 'content-type': 'application/json',
102
+ accept: 'application/json, text/event-stream',
103
+ ...Object.fromEntries(templates.map(([k, v]) => [k, String(v).split(TOKEN_PLACEHOLDER).join(token)])),
104
+ ...(sessionId ? { 'mcp-session-id': sessionId } : {}),
105
+ ...(protocolVersion ? { 'mcp-protocol-version': protocolVersion } : {}),
106
+ };
107
+ };
108
+
109
+ // One exchange: POST the line, then hand each JSON-RPC message in the answer
110
+ // to `onMessage` as it arrives. An event stream is read event by event, so a
111
+ // notification sent before the response reaches codex then, and reading stops
112
+ // once `onMessage` says the request is answered, whether or not the server
113
+ // closes the stream. The timer covers the whole exchange, body included: a
114
+ // stream that never answers still ends in an error, not a wait forever.
115
+ const exchange = async (body, onMessage) => {
116
+ const controller = new AbortController();
117
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
118
+ try {
119
+ const res = await fetchImpl(url, {
120
+ method: 'POST',
121
+ headers: headers(),
122
+ body,
123
+ signal: controller.signal,
124
+ // The request carries the seat token, so no redirect is followed: a
125
+ // redirect may point at another origin (same rule as connectHttpMcp).
126
+ redirect: 'error',
127
+ });
128
+ const contentType = res.headers?.get?.('content-type') || '';
129
+ const reader = res.ok && contentType.includes('text/event-stream') ? res.body?.getReader?.() : null;
130
+ if (!reader) return { res, text: await res.text() };
131
+ // Not every fetch errors a body it has already handed over when the
132
+ // signal fires, so the timeout ends the read itself.
133
+ const stopReading = () => reader.cancel().catch(() => {});
134
+ controller.signal.addEventListener('abort', stopReading, { once: true });
135
+ const decoder = new TextDecoder();
136
+ let buffered = '';
137
+ const drain = (final) => {
138
+ const blocks = buffered.split(/\r?\n\r?\n/);
139
+ buffered = final ? '' : blocks.pop();
140
+ return blocks.flatMap((block) => ssePayloads(`${block}\n\n`)).some((raw) => onMessage(raw));
141
+ };
142
+ for (;;) {
143
+ // eslint-disable-next-line no-await-in-loop
144
+ const { value, done } = await reader.read();
145
+ if (done) {
146
+ buffered += decoder.decode();
147
+ drain(true);
148
+ break;
149
+ }
150
+ buffered += decoder.decode(value, { stream: true });
151
+ if (drain(false)) {
152
+ stopReading();
153
+ break;
154
+ }
155
+ }
156
+ if (controller.signal.aborted) throw Object.assign(new Error('aborted'), { name: 'AbortError' });
157
+ return { res, text: null };
158
+ } finally {
159
+ clearTimeout(timer);
160
+ }
161
+ };
162
+
163
+ const handleLine = async (line) => {
164
+ if (!line.trim()) return;
165
+ let message;
166
+ try {
167
+ message = JSON.parse(line);
168
+ } catch {
169
+ write(JSON.stringify(rpcError(null, -32700, 'parse error')));
170
+ return;
171
+ }
172
+ const id = message?.id;
173
+ const isRequest = id !== undefined && id !== null && typeof message?.method === 'string';
174
+ let answered = false;
175
+ const fail = (text) => {
176
+ if (isRequest && !answered) write(JSON.stringify(rpcError(id, -32000, `grant broker: ${scrub(text)}`)));
177
+ else process.stderr.write(`[commonly-broker-bridge] ${scrub(text)}\n`);
178
+ };
179
+ // Writes one message back to codex; true once this request is answered.
180
+ const forward = (raw) => {
181
+ let answer;
182
+ try {
183
+ answer = JSON.parse(raw);
184
+ } catch {
185
+ return false;
186
+ }
187
+ if (message?.method === 'initialize' && answer?.id === id
188
+ && typeof answer?.result?.protocolVersion === 'string') {
189
+ protocolVersion = answer.result.protocolVersion;
190
+ }
191
+ write(JSON.stringify(answer));
192
+ if (isRequest && answer?.id === id && ('result' in answer || 'error' in answer)) answered = true;
193
+ return answered;
194
+ };
195
+ let res;
196
+ let text;
197
+ try {
198
+ ({ res, text } = await exchange(line, forward));
199
+ } catch (error) {
200
+ fail(error?.name === 'AbortError' ? `timed out after ${timeoutMs}ms` : (error?.message || String(error)));
201
+ return;
202
+ }
203
+ const header = res.headers?.get?.('mcp-session-id');
204
+ if (header && !sessionId) sessionId = header;
205
+ if (!res.ok) {
206
+ fail(`HTTP ${res.status}${text ? `: ${text.slice(0, MAX_ERROR_TEXT)}` : ''}`);
207
+ return;
208
+ }
209
+ if (text !== null) {
210
+ for (const raw of parseMessages(text || '', res.headers?.get?.('content-type') || '')) forward(raw);
211
+ }
212
+ };
213
+
214
+ return { handleLine };
215
+ };
216
+
217
+ const isMain = () => {
218
+ try {
219
+ return realpathSync(process.argv[1] || '') === realpathSync(BRIDGE_PATH);
220
+ } catch {
221
+ return false;
222
+ }
223
+ };
224
+
225
+ if (isMain()) {
226
+ const url = process.env[BRIDGE_URL_VAR];
227
+ let headerTemplates = {};
228
+ try {
229
+ headerTemplates = JSON.parse(process.env[BRIDGE_HEADERS_VAR] || '{}');
230
+ } catch {
231
+ process.stderr.write(`[commonly-broker-bridge] ${BRIDGE_HEADERS_VAR} is not JSON\n`);
232
+ process.exit(1);
233
+ }
234
+ if (!url) {
235
+ process.stderr.write(`[commonly-broker-bridge] ${BRIDGE_URL_VAR} is unset\n`);
236
+ process.exit(1);
237
+ }
238
+ const bridge = createBrokerBridge({
239
+ url,
240
+ headerTemplates,
241
+ tokenFile: process.env[CREDENTIAL_FILE_VAR],
242
+ // A closed stdout (codex gone) must not become an unhandled rejection.
243
+ write: (line) => { try { process.stdout.write(`${line}\n`); } catch { /* codex has gone */ } },
244
+ });
245
+ const pending = new Set();
246
+ const lines = createInterface({ input: process.stdin });
247
+ lines.on('line', (line) => {
248
+ const task = bridge.handleLine(line).finally(() => pending.delete(task));
249
+ pending.add(task);
250
+ });
251
+ lines.on('close', async () => {
252
+ await Promise.allSettled([...pending]);
253
+ process.exit(0);
254
+ });
255
+ }
@@ -70,7 +70,9 @@ import {
70
70
  resolve as pathResolve,
71
71
  sep,
72
72
  } from 'path';
73
- import { CREDENTIAL_KEY, writeCredentialFile } from '../credential-file.js';
73
+ import { CREDENTIAL_FILE_VAR, CREDENTIAL_KEY, writeCredentialFile } from '../credential-file.js';
74
+ import { isOurGrantBroker } from '../grant-broker-guard.js';
75
+ import { BRIDGE_HEADERS_VAR, BRIDGE_PATH, BRIDGE_URL_VAR } from './codex-broker-bridge.mjs';
74
76
  import { supportedGitHooks } from '../commit-attribution.js';
75
77
  import { deliverSeatCredential, withholdRuntimeCredential } from '../mcp-credential-delivery.js';
76
78
  import { prepareMcpSpawn, publicMcpUnavailableError, selectedMcpVersionDir } from '../mcp-home.js';
@@ -119,7 +121,8 @@ const buildPrompt = buildMemoryPreamble;
119
121
  //
120
122
  // Codex-specific constraints:
121
123
  // - stdio/command servers only (no url transport here); url-only entries
122
- // are skipped rather than half-wired.
124
+ // are skipped rather than half-wired. The one exception is our grant
125
+ // broker, which runs behind a stdio bridge (bridgeGrantBroker, F175b).
123
126
  // - Only entries that DECLARE stdio (or name no transport) are emitted, even
124
127
  // when they also carry a `command`. `auditDeclaredMcp` classifies by
125
128
  // `transport` and never judges the command of an entry that declared an
@@ -153,6 +156,73 @@ const substitutePlaceholders = (value, ctx) => {
153
156
  // JSON.stringify doubles as the TOML quoter for command/args/env values.
154
157
  const toml = (s) => JSON.stringify(String(s));
155
158
 
159
+ const HTTP_TRANSPORTS = new Set(['http', 'streamable-http']);
160
+ // A server name becomes a TOML key path, so it must not hold a dot.
161
+ const SERVER_NAME = /^[A-Za-z0-9_-]+$/;
162
+ // What fetch accepts in a header: Latin-1, no CR, LF or NUL.
163
+ // eslint-disable-next-line no-control-regex
164
+ const HEADER_TEXT = /^[^\r\n\0\u0100-\uffff]*$/;
165
+
166
+ // F175b: the grant broker is a Streamable HTTP server and codex runs stdio
167
+ // servers here, so the broker is wired as OUR stdio bridge
168
+ // (codex-broker-bridge.mjs) with the broker's url, its headers as templates and
169
+ // this spawn's credential-file path, none of them a secret. The command the
170
+ // entry declares, if any, is never run. Whether this seat may hold the broker
171
+ // at all was decided before the adapter (grant-broker-guard.js), which
172
+ // withholds it from a seat that is not confined.
173
+ const bridgeGrantBroker = (server, ctx) => {
174
+ const skip = (why) => {
175
+ // eslint-disable-next-line no-console
176
+ console.warn(`[codex] grant broker ${server.name}: ${why}, so it is not wired for this spawn.`);
177
+ return null;
178
+ };
179
+ if (!SERVER_NAME.test(server.name)) return skip('its name is not a plain config key');
180
+ if (!ctx.credentialFile) return skip('there is no seat credential to read');
181
+ // Resolve the instance placeholders only: the token placeholder stays in the
182
+ // header template and is filled by the bridge from the file.
183
+ const resolve = (value) => substitutePlaceholders(value, { instanceUrl: ctx.instanceUrl });
184
+ const resolvedUrl = resolve(server.url);
185
+ const headers = Object.fromEntries(Object.entries(server.headers || {})
186
+ .map(([name, value]) => [String(name), resolve(String(value))]));
187
+ const carriesToken = (value) => !!ctx.runtimeToken && value.includes(ctx.runtimeToken);
188
+ if (carriesToken(resolvedUrl)
189
+ || Object.entries(headers).some(([name, value]) => carriesToken(name) || carriesToken(value))) {
190
+ return skip('the entry holds the seat token as a literal, which would ride argv');
191
+ }
192
+ if (resolvedUrl.includes('${')) return skip('its url holds a placeholder this host cannot resolve');
193
+ // A header fetch would reject quotes its value in the error, and that value
194
+ // holds the token once the bridge fills it, so such an entry is not wired.
195
+ if (Object.entries(headers).some(([name, value]) => !HEADER_TEXT.test(name) || !HEADER_TEXT.test(value))) {
196
+ return skip('a header holds a control or non-Latin-1 character');
197
+ }
198
+ // The url the guard judged (isOurGrantBroker) is normalised: resolved against
199
+ // the instance, with doubled slashes collapsed. The bridge fetches that same
200
+ // url, on the instance's own origin, or nothing.
201
+ let url;
202
+ try {
203
+ const instance = new URL(ctx.instanceUrl);
204
+ const parsed = new URL(resolvedUrl, instance);
205
+ if (parsed.origin !== instance.origin) return skip('its url is not on this instance');
206
+ parsed.pathname = parsed.pathname.replace(/\/{2,}/g, '/');
207
+ url = parsed.href;
208
+ } catch {
209
+ return skip('its url does not resolve against this instance');
210
+ }
211
+ const env = [
212
+ [BRIDGE_URL_VAR, url],
213
+ [BRIDGE_HEADERS_VAR, JSON.stringify(headers)],
214
+ [CREDENTIAL_FILE_VAR, ctx.credentialFile],
215
+ ];
216
+ return [
217
+ '-c', `mcp_servers.${server.name}.command=${toml(process.execPath)}`,
218
+ // The broker parks every write for the owner's approval itself, so codex
219
+ // approving the call is the same boundary the stdio servers get below.
220
+ '-c', `mcp_servers.${server.name}.default_tools_approval_mode="approve"`,
221
+ '-c', `mcp_servers.${server.name}.args=[${toml(BRIDGE_PATH)}]`,
222
+ '-c', `mcp_servers.${server.name}.env={${env.map(([key, value]) => `${key} = ${toml(value)}`).join(', ')}}`,
223
+ ];
224
+ };
225
+
156
226
  const buildMcpOverrideArgs = (mcpServers, ctx = {}) => {
157
227
  const flags = [];
158
228
  const forwardedEnv = {};
@@ -160,6 +230,17 @@ const buildMcpOverrideArgs = (mcpServers, ctx = {}) => {
160
230
  const mcpReadDirectories = [];
161
231
  for (const server of mcpServers || []) {
162
232
  const transport = typeof server?.transport === 'string' ? server.transport.trim().toLowerCase() : 'stdio';
233
+ if (server?.name && HTTP_TRANSPORTS.has(transport)
234
+ && isOurGrantBroker(server, { instanceUrl: ctx.instanceUrl })) {
235
+ const bridged = bridgeGrantBroker(server, ctx);
236
+ if (bridged) {
237
+ flags.push(...bridged);
238
+ // A public seat's MCP children run under its permission profile; the
239
+ // bridge imports node builtins only, so the file is all it reads.
240
+ if (ctx.publicSeat) mcpReadDirectories.push(BRIDGE_PATH);
241
+ }
242
+ continue;
243
+ }
163
244
  if (!server?.name || transport !== 'stdio'
164
245
  || !Array.isArray(server.command) || !server.command.length) continue;
165
246
  // TASK-174: the command that will EXECUTE — the warmed build from the seat's
@@ -268,6 +268,34 @@ export const withholdGrantBroker = (environment, adapter, {
268
268
  return { ...environment, mcp: kept };
269
269
  };
270
270
 
271
+ /**
272
+ * Merge the server's grant-broker entries into a seat environment, the way the
273
+ * daemon's work list does it (`GET /api/agent-binding/assigned` in
274
+ * `backend/routes/agentBinding.ts`): an existing entry with a broker's name is
275
+ * replaced, the brokers are appended, and a seat with no environment gets one
276
+ * holding only them. Used by `agent run` without a daemon (F150), whose
277
+ * `GET /api/agents/runtime/grant-brokers` returns the same per-seat projection.
278
+ *
279
+ * Merge only. The caller runs `withholdGrantBroker` on the result, so the
280
+ * client-side refusal still applies to whatever the server sent.
281
+ * Identity is preserved when there is nothing to merge.
282
+ */
283
+ export const mergeGrantBrokers = (environment, servers) => {
284
+ const brokers = Array.isArray(servers)
285
+ ? servers.filter((server) => server && typeof server === 'object' && !Array.isArray(server))
286
+ : [];
287
+ if (!brokers.length) return environment;
288
+ if (!environment) return { mcp: brokers };
289
+ const existing = Array.isArray(environment.mcp) ? environment.mcp : [];
290
+ return {
291
+ ...environment,
292
+ mcp: [
293
+ ...existing.filter((server) => !brokers.some((broker) => broker.name === server?.name)),
294
+ ...brokers,
295
+ ],
296
+ };
297
+ };
298
+
271
299
  export default {
272
300
  GRANT_BROKER_REFUSAL_CODE,
273
301
  ENFORCING_MODES,
@@ -275,4 +303,5 @@ export default {
275
303
  declaresGrantBroker,
276
304
  confinementReason,
277
305
  withholdGrantBroker,
306
+ mergeGrantBrokers,
278
307
  };