@commonlyai/cli 0.1.345 → 0.1.346

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.345",
3
+ "version": "0.1.346",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -92,7 +92,10 @@ import {
92
92
  publicClaudeStateRoot,
93
93
  wrapArgvWithSeatbelt,
94
94
  } from '../sandbox/seatbelt.js';
95
- import { CREDENTIAL_FILE_VAR, CREDENTIAL_KEY, writeCredentialFile } from '../credential-file.js';
95
+ import {
96
+ CREDENTIAL_FILE_VAR, CREDENTIAL_KEY, armCredentialRelease, restoreCredentialFile, writeCredentialFile,
97
+ } from '../credential-file.js';
98
+ import { MCP_READY_FILE_ENV, commonlyMcpReadyFile } from '../mcp-ready.js';
96
99
  import { supportedGitHooks } from '../commit-attribution.js';
97
100
  import { workspaceGitAttachment, workspaceGitEnabled } from '../workspace-git.js';
98
101
  import { deliverSeatCredential, withholdRuntimeCredential } from '../mcp-credential-delivery.js';
@@ -1164,6 +1167,10 @@ const buildMcpConfig = (mcpServers, ctx = {}) => {
1164
1167
  label: 'claude',
1165
1168
  }).env;
1166
1169
  }
1170
+ // F460: on a public seat our server names the file it writes once it has
1171
+ // read the credential (a path, not a secret). An older warm build refuses.
1172
+ const readyPath = spawnCommand ? commonlyMcpReadyFile(server, spawnCommand, ctx, { env: entry.env }) : null;
1173
+ if (readyPath) entry.env = { ...(entry.env || {}), [MCP_READY_FILE_ENV]: readyPath };
1167
1174
  const headerHelper = ctx.dynamicHeaderHelpers?.get(server.name);
1168
1175
  if (server.headers) {
1169
1176
  const headers = { ...server.headers };
@@ -1228,7 +1235,12 @@ const createMcpConfig = async (mcpServers, ctx = {}) => {
1228
1235
  + `inherits it. Put the credential on the entry's env to get the file channel.`,
1229
1236
  );
1230
1237
  }
1231
- return { dir, file, credential, expansionEnv, unavailableMcp, mcpReadDirectories };
1238
+ return {
1239
+ dir, file, credential, expansionEnv, unavailableMcp, mcpReadDirectories,
1240
+ // A headersHelper reads the credential on every HTTP (re)connect, so a
1241
+ // turn that has one keeps the file (F460's named residual).
1242
+ headerHelpers: dynamicHeaderHelpers.size,
1243
+ };
1232
1244
  } catch (err) {
1233
1245
  try { await rm(dir, { recursive: true, force: true }); } catch { /* ignore */ }
1234
1246
  throw err;
@@ -1720,6 +1732,30 @@ export default {
1720
1732
 
1721
1733
  let mcpConfig = null;
1722
1734
  let publicClaudeState = null;
1735
+ // F460: a public seat's credential goes once every MCP reader has it.
1736
+ let readyFileDir = null;
1737
+ let ownReadyDir = null;
1738
+ const readyFiles = [];
1739
+ let credentialRelease = null;
1740
+ let releaseFailure = null;
1741
+ let claudeChild = null;
1742
+ const spawnImpl = (...spawnCall) => {
1743
+ claudeChild = (ctx._spawnImpl || childSpawn)(...spawnCall);
1744
+ return claudeChild;
1745
+ };
1746
+ const armRelease = () => {
1747
+ if (!readyFileDir || !mcpConfig?.credential || mcpConfig.headerHelpers > 0) return;
1748
+ credentialRelease = armCredentialRelease(mcpConfig.credential, {
1749
+ readyFiles: readyFiles.map(({ path }) => path),
1750
+ label: 'public Claude seat',
1751
+ // eslint-disable-next-line no-console
1752
+ warn: (text) => console.warn(`[claude] ${text}`),
1753
+ onFailure: (failure) => { releaseFailure = failure; claudeChild?.kill?.('SIGKILL'); },
1754
+ ...ctx._credentialRelease,
1755
+ });
1756
+ // A delete that failed at arm time ends the turn before Claude starts.
1757
+ if (credentialRelease.error) throw credentialRelease.error;
1758
+ };
1723
1759
  let providerProxy = null;
1724
1760
  // A login seat's gateway, when the host names one: config, not a secret.
1725
1761
  let publicLoginBaseUrl = null;
@@ -1852,7 +1888,21 @@ export default {
1852
1888
  }
1853
1889
  if (ctx.environment && ctx.cwd) ctx.onSkillsLinked?.(skillMount);
1854
1890
  if (Array.isArray(ctx.environment?.mcp) && ctx.environment.mcp.length > 0) {
1891
+ // F460: the jail writes the seat's state folder, so a public seat's MCP
1892
+ // servers write their ready files there (named per spawn, removed after).
1893
+ if (ctx.environment?.sandbox?.trust === 'public' && publicClaudeState?.statePath) {
1894
+ readyFileDir = join(publicClaudeState.statePath, 'mcp-ready');
1895
+ await mkdir(readyFileDir, { recursive: true, mode: 0o700 });
1896
+ } else if (ctx.environment?.sandbox?.trust === 'public') {
1897
+ // A policy-only host (D245) prepares no state folder and runs the MCP
1898
+ // children unjailed, so a folder of this turn's own serves.
1899
+ ownReadyDir = await mkdtemp(join(tmpdir(), 'commonly-claude-ready-'));
1900
+ await chmod(ownReadyDir, 0o700);
1901
+ readyFileDir = ownReadyDir;
1902
+ }
1855
1903
  mcpConfig = await createMcpConfig(ctx.environment.mcp, {
1904
+ readyFileDir,
1905
+ readyFiles,
1856
1906
  runtimeToken: ctx.runtimeToken,
1857
1907
  instanceUrl: ctx.instanceUrl,
1858
1908
  agentName: ctx.agentName,
@@ -1885,6 +1935,7 @@ export default {
1885
1935
  claudeEnv,
1886
1936
  };
1887
1937
  const { cmd, args, env, childHome } = await prepareArgv(baseArgs, spawnCtx);
1938
+ armRelease();
1888
1939
  const stdout = await runClaude({
1889
1940
  cmd,
1890
1941
  args,
@@ -1896,7 +1947,7 @@ export default {
1896
1947
  // and its provider key is not an env var here, so the seat credential is
1897
1948
  // the value a tail can echo back.
1898
1949
  credentials: turnCredentials(spawnCtx),
1899
- spawnImpl: ctx._spawnImpl, onSpawn: ctx.onSpawn, controls: controlsFromArguments(modelArgs, { modelFlag: '--model', effortFlag: '--effort' }), // test seam only — do not use in production
1950
+ spawnImpl, onSpawn: ctx.onSpawn, controls: controlsFromArguments(modelArgs, { modelFlag: '--model', effortFlag: '--effort' }),
1900
1951
  ownGroup: wantsOwnProcessGroup(ctx),
1901
1952
  transcriptPath: claudeTranscriptPath({
1902
1953
  cwd: physicalPath(ctx.cwd), sessionId, configDir: claudeConfigDirFor({ ...env, HOME: childHome || env?.HOME }),
@@ -1909,6 +1960,7 @@ export default {
1909
1960
  commandResolution: ctx._commandResolution, // test seam only
1910
1961
  confined: reapEverything,
1911
1962
  });
1963
+ if (releaseFailure) throw releaseFailure;
1912
1964
  // TASK-440: the context this turn left, read from the transcript the
1913
1965
  // child wrote under its own env (an isolated HOME for public seats).
1914
1966
  const contextTokens = claudeContextTokens({
@@ -1922,6 +1974,8 @@ export default {
1922
1974
  stats: claudeRunStats(stdout),
1923
1975
  };
1924
1976
  } catch (err) {
1977
+ // F460: a credential that could not be deleted ends the turn; no retry.
1978
+ if (releaseFailure) throw releaseFailure;
1925
1979
  // A public seat's refusal is not a session-store failure, whatever its
1926
1980
  // message happens to contain: it must reach the run loop, never the
1927
1981
  // fresh-session retry below (#2247).
@@ -1963,7 +2017,16 @@ export default {
1963
2017
  if ((publicNativeSandbox || publicBwrapSandbox) && ctx.commitAttributionEnv) {
1964
2018
  Object.assign(retryCtx.claudeEnv, ctx.commitAttributionEnv);
1965
2019
  }
2020
+ // F460: the first run may have released the credential once its
2021
+ // servers had it. The retry's servers read it from the same path, so it
2022
+ // is written there again and released again once they are ready.
2023
+ if (credentialRelease) {
2024
+ credentialRelease.stop();
2025
+ await Promise.all(readyFiles.map(({ path }) => rm(path, { force: true })));
2026
+ restoreCredentialFile(mcpConfig.credential, ctx.runtimeToken);
2027
+ }
1966
2028
  const retry = await prepareArgv(retryBase, retryCtx);
2029
+ if (credentialRelease) armRelease();
1967
2030
  const stdout = await runClaude({
1968
2031
  cmd: retry.cmd,
1969
2032
  args: retry.args,
@@ -1971,7 +2034,7 @@ export default {
1971
2034
  env: retry.env,
1972
2035
  timeoutMs: ctx.timeoutMs || DEFAULT_TIMEOUT_MS,
1973
2036
  credentials: turnCredentials(retryCtx),
1974
- spawnImpl: ctx._spawnImpl, onSpawn: ctx.onSpawn, controls: controlsFromArguments(modelArgs, { modelFlag: '--model', effortFlag: '--effort' }),
2037
+ spawnImpl, onSpawn: ctx.onSpawn, controls: controlsFromArguments(modelArgs, { modelFlag: '--model', effortFlag: '--effort' }),
1975
2038
  ownGroup: wantsOwnProcessGroup(ctx),
1976
2039
  transcriptPath: claudeTranscriptPath({
1977
2040
  cwd: physicalPath(ctx.cwd), sessionId: freshId,
@@ -1984,7 +2047,8 @@ export default {
1984
2047
  turnReap: ctx._turnReap,
1985
2048
  commandResolution: ctx._commandResolution, // test seam only
1986
2049
  confined: reapEverything,
1987
- });
2050
+ }).catch((retryErr) => { throw releaseFailure || retryErr; });
2051
+ if (releaseFailure) throw releaseFailure;
1988
2052
  const contextTokens = claudeContextTokens({
1989
2053
  cwd: physicalPath(ctx.cwd), sessionId: freshId,
1990
2054
  configDir: claudeConfigDirFor({ ...retry.env, HOME: retry.childHome || retry.env?.HOME }),
@@ -2009,6 +2073,9 @@ export default {
2009
2073
  }
2010
2074
  throw err;
2011
2075
  } finally {
2076
+ credentialRelease?.stop();
2077
+ await Promise.all(readyFiles.map(({ path }) => rm(path, { force: true }).catch(() => {})));
2078
+ if (ownReadyDir) await rm(ownReadyDir, { recursive: true, force: true }).catch(() => {});
2012
2079
  if (mcpConfig?.dir) {
2013
2080
  try { await rm(mcpConfig.dir, { recursive: true, force: true }); } catch { /* ignore */ }
2014
2081
  }
@@ -17,8 +17,11 @@
17
17
  * `${COMMONLY_AGENT_TOKEN}`;
18
18
  * - COMMONLY_TOKEN_FILE: the path of this spawn's 0600 credential file, the
19
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.
20
+ * The token is read from that file once, at start, and kept in this process's
21
+ * memory and the request header only. On a public seat the file is deleted as
22
+ * soon as its readers have it (F460): this bridge then writes
23
+ * COMMONLY_MCP_READY_FILE, as the commonly MCP server does, on the host's first
24
+ * tools/list.
22
25
  *
23
26
  * It is a pass-through: each JSON-RPC line from codex is POSTed as it is, and
24
27
  * every message in the answer (plain JSON or an event stream) is written back
@@ -32,7 +35,8 @@
32
35
  * pieces it shares with the rest of the CLI are restated here, and a test pins
33
36
  * the import list.
34
37
  */
35
- import { readFileSync, realpathSync } from 'node:fs';
38
+ import { readFileSync, realpathSync, writeFileSync } from 'node:fs';
39
+ import { isAbsolute } from 'node:path';
36
40
  import { createInterface } from 'node:readline';
37
41
  import { fileURLToPath } from 'node:url';
38
42
 
@@ -44,6 +48,8 @@ export const TOKEN_PLACEHOLDER = '${COMMONLY_AGENT_TOKEN}';
44
48
 
45
49
  // The same name as credential-file.js CREDENTIAL_FILE_VAR (a test pins it).
46
50
  export const CREDENTIAL_FILE_VAR = 'COMMONLY_TOKEN_FILE';
51
+ // The same name as commonly-mcp's READY_FILE_ENV (a test pins it).
52
+ export const READY_FILE_VAR = 'COMMONLY_MCP_READY_FILE';
47
53
 
48
54
  const MAX_ERROR_TEXT = 2048;
49
55
 
@@ -71,17 +77,23 @@ export const createBrokerBridge = ({
71
77
  url,
72
78
  headerTemplates = {},
73
79
  tokenFile,
80
+ readyFile = null,
74
81
  fetchImpl = globalThis.fetch,
75
82
  write,
83
+ writeReady = writeFileSync,
84
+ warn = (text) => process.stderr.write(`[commonly-broker-bridge] ${text}\n`),
76
85
  timeoutMs = 120_000,
77
86
  }) => {
78
87
  let sessionId = null;
79
88
  let protocolVersion = null;
80
89
  let lastToken = null;
90
+ let readyWritten = !readyFile;
81
91
  // Nothing the bridge writes back may hold the token, whatever produced it.
82
92
  const scrub = (text) => (lastToken ? String(text).split(lastToken).join('[token]') : String(text));
83
93
 
94
+ // Once: the file is deleted after its readers have it (F460).
84
95
  const readToken = () => {
96
+ if (lastToken) return lastToken;
85
97
  if (!tokenFile) throw new Error(`no credential file (${CREDENTIAL_FILE_VAR} is unset)`);
86
98
  let token;
87
99
  try {
@@ -94,9 +106,37 @@ export const createBrokerBridge = ({
94
106
  return token;
95
107
  };
96
108
 
109
+ const needsToken = () => Object.values(headerTemplates).some((v) => String(v).includes(TOKEN_PLACEHOLDER));
110
+ // Read at start, before the host asks for anything, so a file deleted at the
111
+ // ready deadline finds the token already held. A file that cannot be read
112
+ // now is reported on the first request instead.
113
+ const prime = () => {
114
+ if (!needsToken()) return true;
115
+ try {
116
+ readToken();
117
+ return true;
118
+ } catch {
119
+ return false;
120
+ }
121
+ };
122
+ // Exclusive, 0600, holds nothing secret; written once the token is held.
123
+ const markReady = () => {
124
+ if (readyWritten) return;
125
+ readyWritten = true;
126
+ if (!isAbsolute(readyFile)) {
127
+ warn(`${READY_FILE_VAR} is not an absolute path; not writing it`);
128
+ return;
129
+ }
130
+ try {
131
+ writeReady(readyFile, 'ready\n', { flag: 'wx', mode: 0o600 });
132
+ } catch (error) {
133
+ warn(`could not write the ready file: ${error?.code || error?.message || error}`);
134
+ }
135
+ };
136
+
97
137
  const headers = () => {
98
138
  const templates = Object.entries(headerTemplates);
99
- const token = templates.some(([, v]) => String(v).includes(TOKEN_PLACEHOLDER)) ? readToken() : null;
139
+ const token = needsToken() ? readToken() : null;
100
140
  return {
101
141
  'content-type': 'application/json',
102
142
  accept: 'application/json, text/event-stream',
@@ -190,6 +230,7 @@ export const createBrokerBridge = ({
190
230
  }
191
231
  write(JSON.stringify(answer));
192
232
  if (isRequest && answer?.id === id && ('result' in answer || 'error' in answer)) answered = true;
233
+ if (answered && message?.method === 'tools/list' && 'result' in answer && (lastToken || !needsToken())) markReady();
193
234
  return answered;
194
235
  };
195
236
  let res;
@@ -211,7 +252,7 @@ export const createBrokerBridge = ({
211
252
  }
212
253
  };
213
254
 
214
- return { handleLine };
255
+ return { handleLine, prime };
215
256
  };
216
257
 
217
258
  const isMain = () => {
@@ -239,9 +280,11 @@ if (isMain()) {
239
280
  url,
240
281
  headerTemplates,
241
282
  tokenFile: process.env[CREDENTIAL_FILE_VAR],
283
+ readyFile: process.env[READY_FILE_VAR] || null,
242
284
  // A closed stdout (codex gone) must not become an unhandled rejection.
243
285
  write: (line) => { try { process.stdout.write(`${line}\n`); } catch { /* codex has gone */ } },
244
286
  });
287
+ bridge.prime();
245
288
  const pending = new Set();
246
289
  const lines = createInterface({ input: process.stdin });
247
290
  lines.on('line', (line) => {
@@ -72,7 +72,8 @@ import {
72
72
  join,
73
73
  resolve as pathResolve,
74
74
  } from 'path';
75
- import { CREDENTIAL_KEY, writeCredentialFile } from '../credential-file.js';
75
+ import { CREDENTIAL_KEY, armCredentialRelease, writeCredentialFile } from '../credential-file.js';
76
+ import { MCP_READY_FILE_ENV, bridgeReadyFile, commonlyMcpReadyFile } from '../mcp-ready.js';
76
77
  import { isOurGrantBroker } from '../grant-broker-guard.js';
77
78
  import { BRIDGE_PATH } from './codex-broker-bridge.mjs';
78
79
  import { brokerBridgeEntry } from './broker-bridge-entry.js';
@@ -178,6 +179,9 @@ const bridgeGrantBroker = (server, ctx) => {
178
179
  console.warn(`[codex] grant broker ${server.name}: ${entry.skip}, so it is not wired for this spawn.`);
179
180
  return null;
180
181
  }
182
+ // F460: the bridge reads the credential once and says so in its ready file.
183
+ const readyPath = bridgeReadyFile(server, ctx);
184
+ if (readyPath) entry.env = { ...entry.env, [MCP_READY_FILE_ENV]: readyPath };
181
185
  return [
182
186
  '-c', `mcp_servers.${server.name}.command=${toml(entry.command)}`,
183
187
  // The broker parks every write for the owner's approval itself, so codex
@@ -226,7 +230,7 @@ const buildMcpOverrideArgs = (mcpServers, ctx = {}) => {
226
230
  // one path by which the value ends up in codex's own environment and from
227
231
  // there in every MCP child it spawns (TASK-083, measured on a live codex
228
232
  // seat before the change).
229
- const declaredEnv = deliverSeatCredential({ ...server, command: spawnCommand }, {
233
+ let declaredEnv = deliverSeatCredential({ ...server, command: spawnCommand }, {
230
234
  credentialFile: ctx.credentialFile,
231
235
  label: 'codex',
232
236
  }).env;
@@ -260,6 +264,12 @@ const buildMcpOverrideArgs = (mcpServers, ctx = {}) => {
260
264
  );
261
265
  continue;
262
266
  }
267
+ // F460: on a public seat our server names the file it writes once it has
268
+ // read the credential (a path, not a secret). An older warm build refuses,
269
+ // and so does another server handed the credential path. Named only for an
270
+ // entry that is wired, so a skipped one is never waited for.
271
+ const readyPath = commonlyMcpReadyFile(server, spawnCommand, ctx, { env: declaredEnv });
272
+ if (readyPath) declaredEnv = { ...declaredEnv, [MCP_READY_FILE_ENV]: readyPath };
263
273
  flags.push('-c', `mcp_servers.${server.name}.command=${toml(command)}`);
264
274
  const versionDir = ctx.publicSeat && selectedMcpVersionDir(spawnCommand);
265
275
  if (versionDir) mcpReadDirectories.push(versionDir);
@@ -1537,6 +1547,8 @@ export default {
1537
1547
  });
1538
1548
 
1539
1549
  let providerProxy = null;
1550
+ const readyFiles = [];
1551
+ let credentialRelease = null;
1540
1552
  try {
1541
1553
  // A public seat can't run git from its shell on macOS: Homebrew's git is
1542
1554
  // outside the profile and /usr/bin/git is an xcrun shim that fails there.
@@ -1577,10 +1589,16 @@ export default {
1577
1589
  ...(workspaceGit ? [workspaceGit] : []),
1578
1590
  ];
1579
1591
  }
1592
+ // F460: a public seat's MCP servers name their ready files here; codex
1593
+ // starts them outside the seat's permission profile, beside the credential.
1594
+ const readyFileDir = sandbox?.trust === 'public' && credential ? join(dir, 'mcp-ready') : null;
1595
+ if (readyFileDir) await mkdir(readyFileDir, { recursive: true, mode: 0o700 });
1580
1596
  const mcp = buildMcpOverrideArgs(seatMcp, {
1581
1597
  runtimeToken: ctx.runtimeToken,
1582
1598
  instanceUrl: ctx.instanceUrl,
1583
1599
  credentialFile: credential?.path || null,
1600
+ readyFileDir,
1601
+ readyFiles,
1584
1602
  publicSeat: sandbox?.trust === 'public',
1585
1603
  ownerWoken: ctx.ownerWoken,
1586
1604
  commandResolution: { env: ctx.env || process.env, ...ctx._commandResolution },
@@ -1743,7 +1761,27 @@ export default {
1743
1761
  if (ctx.signal?.aborted) {
1744
1762
  throw ctx.signal.reason || new Error('codex spawn cancelled before the process started');
1745
1763
  }
1746
- const { threadId, turnCompleted } = await runCodex({
1764
+ // F460: on a public seat the credential goes once every MCP reader has it
1765
+ // (their ready files), or at the deadline. A delete that fails ends the turn.
1766
+ let releaseFailure = null;
1767
+ let child = null;
1768
+ const spawnImpl = (...spawnArgs) => {
1769
+ child = (ctx._spawnImpl || childSpawn)(...spawnArgs);
1770
+ return child;
1771
+ };
1772
+ if (readyFileDir) {
1773
+ credentialRelease = armCredentialRelease(credential, {
1774
+ readyFiles: readyFiles.map(({ path }) => path),
1775
+ label: 'public codex seat',
1776
+ warn: (text) => process.stderr.write(`[codex] ${text}\n`),
1777
+ onFailure: (err) => { releaseFailure = err; child?.kill?.('SIGKILL'); },
1778
+ ...ctx._credentialRelease,
1779
+ });
1780
+ // A delete that failed at arm time (every reader already ready) ends
1781
+ // the turn before Codex starts.
1782
+ if (credentialRelease.error) throw credentialRelease.error;
1783
+ }
1784
+ const ran = await runCodex({
1747
1785
  args,
1748
1786
  cwd: ctx.cwd,
1749
1787
  env: childEnv,
@@ -1755,7 +1793,7 @@ export default {
1755
1793
  // nothing left to compare a tail against.
1756
1794
  // The per-turn proxy token is one too: codex was handed it in place of the key.
1757
1795
  credentials: [...spawnCredentials(ctx, CODEX_PROVIDER_KEY_ENVS), route?.key, providerProxy?.token].filter(Boolean),
1758
- spawnImpl: ctx._spawnImpl, onSpawn: ctx.onSpawn, controls: controlsFromArguments(args.slice(args.indexOf('exec') + (args[args.indexOf('exec') + 1] === 'resume' ? 3 : 1), -1), { modelFlag: '--model', valueFlags: ['-c', '-o', '--permission-profile'], codex: true }), // test seam only — do not use in production
1796
+ spawnImpl, onSpawn: ctx.onSpawn, controls: controlsFromArguments(args.slice(args.indexOf('exec') + (args[args.indexOf('exec') + 1] === 'resume' ? 3 : 1), -1), { modelFlag: '--model', valueFlags: ['-c', '-o', '--permission-profile'], codex: true }), // test seam only — do not use in production
1759
1797
  ownGroup: wantsOwnProcessGroup(ctx),
1760
1798
  turnReap: ctx._turnReap,
1761
1799
  // A public seat keeps nothing a turn leaves running, whatever the turn
@@ -1763,7 +1801,9 @@ export default {
1763
1801
  // exactly when trust is `public`; workspace trust is refused above.
1764
1802
  confined: publicSandboxMode !== null,
1765
1803
  commandResolution: ctx._commandResolution, // test seam only
1766
- });
1804
+ }).catch((err) => { throw releaseFailure || err; });
1805
+ if (releaseFailure) throw releaseFailure;
1806
+ const { threadId, turnCompleted } = ran;
1767
1807
 
1768
1808
  let text = '';
1769
1809
  try {
@@ -1801,6 +1841,7 @@ export default {
1801
1841
  text, newSessionId, contextTokens, ...(Object.keys(stats).length ? { stats } : {}),
1802
1842
  };
1803
1843
  } finally {
1844
+ credentialRelease?.stop();
1804
1845
  try { await providerProxy?.close(); } catch { /* ignore */ }
1805
1846
  try { await rm(dir, { recursive: true, force: true }); } catch { /* ignore */ }
1806
1847
  }
@@ -9,7 +9,8 @@ import { StringDecoder } from 'node:string_decoder';
9
9
  import { buildMemoryPreamble } from '../memory-bridge.js';
10
10
  import { OWNER_WOKEN_MEMORY_TOOLS } from '../public-withheld-tools.js';
11
11
  import { effectiveSandboxTrust, refuseWorkspaceTrust, validateEnvironmentSpec } from '../environment.js';
12
- import { writeCredentialFile } from '../credential-file.js';
12
+ import { armCredentialRelease, writeCredentialFile } from '../credential-file.js';
13
+ import { MCP_READY_FILE_ENV, bridgeReadyFile, commonlyMcpReadyFile } from '../mcp-ready.js';
13
14
  import { deliverSeatCredential, withholdRuntimeCredential } from '../mcp-credential-delivery.js';
14
15
  import { prepareMcpSpawn, selectedMcpVersionDir } from '../mcp-home.js';
15
16
  import { describeMcpCommand } from '../mcp-server-version.js';
@@ -130,7 +131,11 @@ export const bridgedGooseExtension = (server, ctx) => {
130
131
  console.warn(`[goose] grant broker ${server.name}: ${entry.skip}, so it is not wired for this spawn.`);
131
132
  return null;
132
133
  }
133
- return { type: 'stdio', name: server.name, cmd: entry.command, args: entry.args, envs: entry.env };
134
+ const readyPath = bridgeReadyFile(server, ctx);
135
+ return {
136
+ type: 'stdio', name: server.name, cmd: entry.command, args: entry.args,
137
+ envs: readyPath ? { ...entry.env, [MCP_READY_FILE_ENV]: readyPath } : entry.env,
138
+ };
134
139
  };
135
140
 
136
141
  /** The flag contains paths and URLs only. Literal MCP secrets cannot ride argv. */
@@ -202,9 +207,15 @@ export const extensionArgs = (servers, ctx) => {
202
207
  });
203
208
  const commandWords = command.map((part) => gooseWord(substitute(part, ctx)));
204
209
  if (ctx.publicSeat) {
210
+ // F460: our server names the file it writes once it has read the
211
+ // credential (a path, not a secret). An older warm build refuses.
212
+ const readyPath = commonlyMcpReadyFile(server, command, ctx, { env: delivery.env });
205
213
  ctx.publicExtensions.push({ type: 'stdio', name: server.name, cmd: command[0],
206
214
  args: command.slice(1).map((part) => substitute(part, ctx)),
207
- envs: Object.fromEntries(Object.entries(delivery.env).map(([name, value]) => [name, substitute(value, ctx)])),
215
+ envs: {
216
+ ...Object.fromEntries(Object.entries(delivery.env).map(([name, value]) => [name, substitute(value, ctx)])),
217
+ ...(readyPath ? { [MCP_READY_FILE_ENV]: readyPath } : {}),
218
+ },
208
219
  available_tools: publicGooseTools(ctx),
209
220
  });
210
221
  } else {
@@ -359,10 +370,16 @@ export default {
359
370
  const tempDir = await mkdtemp(join(tmpdir(), 'commonly-goose-'));
360
371
  const home = await mkdtemp(join(tmpdir(), 'commonly-goose-home-'));
361
372
  let proxy;
373
+ let credentialRelease = null;
362
374
  try {
363
375
  const credential = writeCredentialFile(ctx.runtimeToken, {
364
376
  root: tempDir, agentName: ctx.agentName || 'agent',
365
377
  });
378
+ // F460: the jail writes only the seat's home, so a public seat's MCP
379
+ // servers write their ready files there.
380
+ const readyFileDir = isPublic && credential ? join(home, 'mcp-ready') : null;
381
+ if (readyFileDir) await mkdir(readyFileDir, { recursive: true, mode: 0o700 });
382
+ const readyFiles = [];
366
383
  // No tokenFile: nothing here reads one, so the token is never on disk.
367
384
  if (isPublic) proxy = await startProviderProxy({
368
385
  provider: configured, keyFile, adapterLabel: 'Goose', pinnedModel: model,
@@ -387,6 +404,7 @@ export default {
387
404
  credentialFile: credential?.path || '', instanceUrl: ctx.instanceUrl || '',
388
405
  runtimeToken: ctx.runtimeToken || '',
389
406
  publicSeat: isPublic, ownerWoken: ctx.ownerWoken, mcpReadDirectories, publicExtensions, brokerExtensions,
407
+ readyFileDir, readyFiles,
390
408
  }),
391
409
  ...(!isPublic ? ['-t', buildMemoryPreamble(prompt, ctx.memoryLongTerm, { freshSession: true })] : []),
392
410
  ];
@@ -446,14 +464,35 @@ export default {
446
464
  });
447
465
  }
448
466
  }
467
+ // F460: on a public seat the credential goes once every MCP reader has it
468
+ // (their ready files), or at the deadline. A delete that fails ends the turn.
469
+ let releaseFailure = null;
470
+ let child = null;
471
+ const spawnImpl = (...spawnArgs) => {
472
+ child = (ctx._spawnImpl || childSpawn)(...spawnArgs);
473
+ return child;
474
+ };
475
+ if (readyFileDir) {
476
+ credentialRelease = armCredentialRelease(credential, {
477
+ readyFiles: readyFiles.map(({ path }) => path),
478
+ label: 'public Goose seat',
479
+ // eslint-disable-next-line no-console
480
+ warn: (text) => console.warn(`[goose] ${text}`),
481
+ onFailure: (err) => { releaseFailure = err; child?.kill?.('SIGKILL'); },
482
+ ...ctx._credentialRelease,
483
+ });
484
+ if (credentialRelease.error) throw credentialRelease.error;
485
+ }
449
486
  const text = await runGoose({
450
487
  binary: executable, args: spawnArgs, cwd: ctx.cwd, env, timeoutMs,
451
488
  credentials: [...spawnCredentials(ctx, [DEFAULT_PROVIDER_KEY]), key, env.OPENAI_API_KEY],
452
489
  optionalExtensions: brokerExtensions,
453
- spawnImpl: ctx._spawnImpl,
454
- });
490
+ spawnImpl,
491
+ }).catch((err) => { throw releaseFailure || err; });
492
+ if (releaseFailure) throw releaseFailure;
455
493
  return { text, newSessionId: null };
456
494
  } finally {
495
+ credentialRelease?.stop();
457
496
  try { await proxy?.close(); } finally {
458
497
  await Promise.all([tempDir, home].map((path) => rm(path, { recursive: true, force: true })));
459
498
  }
@@ -23,7 +23,7 @@ import { observeSpawn, controlsFromArguments } from '../runtime-observation.js';
23
23
  import { requireSeatModel, seatModelRequired } from './seat-model.js';
24
24
  import { isPatchAfterNewestTested } from './tested-version.js';
25
25
  import { spawn as childSpawn, spawnSync } from 'child_process';
26
- import { createHash, randomUUID } from 'crypto';
26
+ import { createHash } from 'crypto';
27
27
  import {
28
28
  existsSync, lstatSync, readdirSync, readlinkSync, realpathSync, rmSync, statSync,
29
29
  } from 'fs';
@@ -43,10 +43,10 @@ import { fileURLToPath } from 'url';
43
43
  import {
44
44
  basename, dirname, isAbsolute, join, relative, resolve as pathResolve,
45
45
  } from 'path';
46
- import { writeCredentialFile } from '../credential-file.js';
46
+ import { armCredentialRelease, writeCredentialFile } from '../credential-file.js';
47
47
  import { deliverSeatCredential, withholdRuntimeCredential } from '../mcp-credential-delivery.js';
48
48
  import {
49
- prepareMcpSpawn, publicMcpUnavailableError, selectedMcpVersionDir, selectedMcpWritesReadyFile,
49
+ prepareMcpSpawn, publicMcpUnavailableError, selectedMcpVersionDir,
50
50
  } from '../mcp-home.js';
51
51
  import { buildMemoryPreamble } from '../memory-bridge.js';
52
52
  import {
@@ -61,6 +61,7 @@ import { wrapArgvWithSeatbelt } from '../sandbox/seatbelt.js';
61
61
  import { resolvePublicSandboxMode } from '../sandbox/mode.js';
62
62
  import { resolveProviderKeyFile, startProviderProxy } from '../provider-proxy.js';
63
63
  import { isShippedCommonlyMcpCommand } from '../declared-mcp-guard.js';
64
+ import { MCP_READY_FILE_ENV, commonlyMcpReadyFile } from '../mcp-ready.js';
64
65
  import { isAnswerableToolError, PUBLIC_MCP_NOT_READY_CODE, PUBLIC_TOOL_FAILED_CODE } from '../public-tool-error.js';
65
66
  import { startInstanceProxy } from '../instance-proxy.js';
66
67
  import { publicSeatWithheldTools } from '../public-withheld-tools.js';
@@ -717,14 +718,12 @@ const buildMcpConfig = (servers, ctx = {}) => {
717
718
  console.warn(`[opencode] skipping MCP server ${server.name}: its credential declaration has no file-backed delivery`);
718
719
  continue;
719
720
  }
720
- // F421: the shipped Commonly server of a public seat names its ready file,
721
- // when the warm build it runs writes one (selectedMcpWritesReadyFile).
722
- if (ctx.readyFileDir && isShippedCommonlyMcpCommand(server.command)
723
- && (ctx.mcpWritesReadyFile || selectedMcpWritesReadyFile)(command)) {
724
- const readyPath = join(ctx.readyFileDir, randomUUID());
725
- env[MCP_READY_FILE_ENV] = readyPath;
726
- ctx.readyFiles?.push({ name: server.name, path: readyPath });
727
- }
721
+ // F421: the shipped Commonly server of a public seat names its ready file.
722
+ // F460: a warm build that writes none is refused on a public seat.
723
+ const readyPath = ctx.readyFiles
724
+ ? commonlyMcpReadyFile(server, command, ctx, { writesReadyFile: ctx.mcpWritesReadyFile, env })
725
+ : null;
726
+ if (readyPath) env[MCP_READY_FILE_ENV] = readyPath;
728
727
  mcp[server.name] = {
729
728
  type: 'local',
730
729
  command: command.map((part) => substitutePublicPlaceholders(part, ctx)),
@@ -975,7 +974,7 @@ export { PUBLIC_TOOL_FAILED_CODE };
975
974
  // data home: Seatbelt's statePath, bwrap's write-outside). A turn whose file is
976
975
  // missing never had the server, so its reply is withheld and the run loop tells
977
976
  // the waiting pod why (turn-failure-notice.js) and retries.
978
- export const MCP_READY_FILE_ENV = 'COMMONLY_MCP_READY_FILE';
977
+ export { MCP_READY_FILE_ENV };
979
978
 
980
979
  export const missingReadyFile = (readyFiles, exists = existsSync) => (
981
980
  (readyFiles || []).find(({ path }) => !exists(path)) || null
@@ -1410,6 +1409,7 @@ export default {
1410
1409
  let readyFileDir = null;
1411
1410
  const readyFiles = [];
1412
1411
  let providerProxy = null;
1412
+ let credentialRelease = null;
1413
1413
  let instanceProxy = null;
1414
1414
  try {
1415
1415
  openCodeHome = await prepareOpenCodeDataHome(ctx, { publicSeat: isPublic });
@@ -1460,13 +1460,6 @@ export default {
1460
1460
  bearerFileServers,
1461
1461
  });
1462
1462
  if (unavailableMcp.length) throw publicMcpUnavailableError(unavailableMcp);
1463
- // A remote server that holds this spawn's credential file can spend
1464
- // whatever the credential reaches, a connector grant included. The broker
1465
- // entry that reaches the adapter has passed the daemon's withhold
1466
- // (grant-broker-guard.js), but buildMcpConfig hands the file to any http
1467
- // entry declaring `Bearer ${COMMONLY_AGENT_TOKEN}`, whatever its URL, so
1468
- // the walk's fail-closed rule keys on what was written (CodeRabbit #3487).
1469
- const carriesGrant = bearerFileServers.length > 0;
1470
1463
  const config = {
1471
1464
  permission: isPublic
1472
1465
  ? publicPermissions(sandboxMode, Object.keys(mcp), ctx)
@@ -1582,6 +1575,27 @@ export default {
1582
1575
  [cmd, ...spawnArgs] = wrapped;
1583
1576
  }
1584
1577
  const credentials = [...spawnCredentials(ctx, sourceAuthEnvNames(sourceEnv)), ctx.providerKey].filter(Boolean);
1578
+ // F460: a public seat's credential goes at OpenCode's first step, once
1579
+ // its ready files exist, or at the deadline, whichever comes first.
1580
+ let releaseFailure = null;
1581
+ let child = null;
1582
+ const spawnImpl = (...spawnCall) => {
1583
+ child = (ctx._spawnImpl || childSpawn)(...spawnCall);
1584
+ return child;
1585
+ };
1586
+ if (isPublic && credential) {
1587
+ credentialRelease = armCredentialRelease(credential, {
1588
+ readyFiles: readyFiles.map(({ path }) => path),
1589
+ ownTrigger: true,
1590
+ label: 'public OpenCode seat',
1591
+ // eslint-disable-next-line no-console
1592
+ warn: (text) => console.warn(`[opencode] ${text}`),
1593
+ onFailure: (err) => { releaseFailure = err; child?.kill?.('SIGKILL'); },
1594
+ fs: { rmSync: ctx._rmSync || rmSync, existsSync: ctx._existsSync || existsSync },
1595
+ ...ctx._credentialRelease,
1596
+ });
1597
+ if (credentialRelease.error) throw credentialRelease.error;
1598
+ }
1585
1599
  const result = await runOpenCode({
1586
1600
  cmd,
1587
1601
  args: spawnArgs,
@@ -1589,10 +1603,9 @@ export default {
1589
1603
  env: childEnv,
1590
1604
  timeoutMs: ctx.timeoutMs || DEFAULT_TIMEOUT_MS,
1591
1605
  credentials,
1592
- spawnImpl: ctx._spawnImpl, onSpawn: ctx.onSpawn, controls: controlsFromArguments(args.slice(0, -1), { modelFlag: '-m', effortFlag: '--variant', valueFlags: ['-s', '--dir', '--title', '--format'] }),
1593
- // CodeRabbit #3487: the walk cannot prove a whole node_modules tree
1594
- // free of a deep link to the temp root, so a credential handed to a
1595
- // remote server stops existing once OpenCode has read it. Measured in
1606
+ spawnImpl, onSpawn: ctx.onSpawn, controls: controlsFromArguments(args.slice(0, -1), { modelFlag: '-m', effortFlag: '--variant', valueFlags: ['-s', '--dir', '--title', '--format'] }),
1607
+ // CodeRabbit #3487, F460: a public seat's credential stops existing
1608
+ // once OpenCode has read it, grant or not. Measured in
1596
1609
  // the 1.19.4 binary: {file:} is expanded once, over the config text at
1597
1610
  // load; every MCP connect (a reconnect included) takes its headers from
1598
1611
  // that cached config; and `run` emits step_start only after tools are
@@ -1600,21 +1613,16 @@ export default {
1600
1613
  // COMMONLY_TOKEN_FILE at startup), has connected. A config reload after
1601
1614
  // this point would fail on the missing file, closed, not open.
1602
1615
  // A delete that fails leaves the credential readable, so the turn ends
1603
- // rather than run on with it (`force` already ignores a missing file).
1604
- onFirstStep: isPublic && carriesGrant && credential
1616
+ // rather than run on with it. The ready files and the deadline (F460)
1617
+ // cover a turn that never reaches its first step.
1618
+ onFirstStep: credentialRelease
1605
1619
  ? () => {
1606
- try {
1607
- (ctx._rmSync || rmSync)(credential.path, { force: true });
1608
- } catch (err) {
1609
- throw new Error(
1610
- `public OpenCode seat could not delete its connector credential (${credential.path}) once OpenCode `
1611
- + `had loaded its config: ${err?.message || err}; the turn was stopped so the credential does not `
1612
- + 'stay readable to its tools',
1613
- );
1614
- }
1620
+ const failure = credentialRelease.release('stream');
1621
+ if (failure) throw failure;
1615
1622
  }
1616
1623
  : undefined,
1617
- });
1624
+ }).catch((err) => { throw releaseFailure || err; });
1625
+ if (releaseFailure) throw releaseFailure;
1618
1626
  if (isPublic) {
1619
1627
  const notReady = missingReadyFile(readyFiles, ctx._existsSync);
1620
1628
  if (notReady) throw publicMcpNotReadyError(notReady.name);
@@ -1627,6 +1635,7 @@ export default {
1627
1635
  ...(result.usage ? { usage: result.usage } : {}),
1628
1636
  };
1629
1637
  } finally {
1638
+ credentialRelease?.stop();
1630
1639
  try { await instanceProxy?.close(); } catch { /* ignore */ }
1631
1640
  try { await providerProxy?.close(); } catch { /* ignore */ }
1632
1641
  try { await rm(tempDir, { recursive: true, force: true }); } catch { /* ignore */ }
@@ -4,13 +4,16 @@ import { isPatchAfterNewestTested, probeVersion } from './tested-version.js';
4
4
  import * as childProcess from 'child_process';
5
5
  import { spawn as childSpawn, spawnSync } from 'child_process';
6
6
  import { lstatSync, realpathSync } from 'fs';
7
- import { chmod, mkdtemp, readFile, rm, writeFile } from 'fs/promises';
7
+ import {
8
+ chmod, mkdir, mkdtemp, readFile, rm, writeFile,
9
+ } from 'fs/promises';
8
10
  import { tmpdir } from 'os';
9
11
  import { basename, dirname, isAbsolute, join } from 'path';
10
12
  import { buildMemoryPreamble } from '../memory-bridge.js';
11
13
  import { deliverSeatCredential } from '../mcp-credential-delivery.js';
12
14
  import { prepareMcpSpawn, publicMcpUnavailableError, selectedMcpVersionDir } from '../mcp-home.js';
13
- import { writeCredentialFile } from '../credential-file.js';
15
+ import { armCredentialRelease, writeCredentialFile } from '../credential-file.js';
16
+ import { MCP_READY_FILE_ENV, bridgeReadyFile, commonlyMcpReadyFile } from '../mcp-ready.js';
14
17
  import { normalizeSandboxTrust, refuseWorkspaceTrust, validateEnvironmentSpec } from '../environment.js';
15
18
  import { resolvePublicSandboxMode } from '../sandbox/mode.js';
16
19
  import { detectBwrap, wrapArgvWithBwrap } from '../sandbox/bwrap.js';
@@ -158,6 +161,10 @@ export const buildQwenMcpConfig = (servers, ctx) => {
158
161
  const args = command.slice(1).map((part) => substitute(part, ctx));
159
162
  const env = Object.fromEntries(Object.entries(delivery.env)
160
163
  .map(([name, value]) => [name, substitute(value, ctx)]));
164
+ // F460: on a public seat our server names the file it writes once it has
165
+ // read the credential (a path, not a secret). An older warm build refuses.
166
+ const readyPath = commonlyMcpReadyFile(server, command, ctx, { env });
167
+ if (readyPath) env[MCP_READY_FILE_ENV] = readyPath;
161
168
  const serialized = JSON.stringify({ command: command[0], args, env });
162
169
  if (serialized.includes('${COMMONLY_AGENT_TOKEN}')
163
170
  || (ctx.runtimeToken && serialized.includes(ctx.runtimeToken))) {
@@ -188,7 +195,12 @@ export const buildQwenMcpConfig = (servers, ctx) => {
188
195
  console.warn(`[qwen] grant broker ${server.name}: ${entry.skip}, so it is not wired for this spawn.`);
189
196
  continue;
190
197
  }
191
- mcpServers[server.name] = { command: entry.command, args: entry.args, env: entry.env };
198
+ const readyPath = bridgeReadyFile(server, ctx);
199
+ mcpServers[server.name] = {
200
+ command: entry.command,
201
+ args: entry.args,
202
+ env: readyPath ? { ...entry.env, [MCP_READY_FILE_ENV]: readyPath } : entry.env,
203
+ };
192
204
  ctx.mcpReadDirectories?.push(entry.readPath);
193
205
  ctx.bridgedBrokers?.push(server.name);
194
206
  continue;
@@ -354,10 +366,16 @@ export default {
354
366
  const settingsPath = join(tempDir, 'settings.json');
355
367
  const mcpPath = join(tempDir, 'mcp.json');
356
368
  let proxy;
369
+ let credentialRelease = null;
357
370
  try {
358
371
  const credential = writeCredentialFile(ctx.runtimeToken, {
359
372
  agentName: ctx.agentName || 'agent', root: tempDir,
360
373
  });
374
+ // F460: the jail writes only the seat's home, so a public seat's MCP
375
+ // servers write their ready files there.
376
+ const readyFileDir = isPublic && credential ? join(home, 'mcp-ready') : null;
377
+ if (readyFileDir) await mkdir(readyFileDir, { recursive: true, mode: 0o700 });
378
+ const readyFiles = [];
361
379
  proxy = await startProviderProxy({
362
380
  provider, keyFile, tokenFile: join(tempDir, 'provider-proxy-token'), adapterLabel: 'Qwen',
363
381
  });
@@ -377,6 +395,8 @@ export default {
377
395
  unavailableMcp,
378
396
  mcpReadDirectories,
379
397
  bridgedBrokers,
398
+ readyFileDir,
399
+ readyFiles,
380
400
  });
381
401
  if (unavailableMcp.length) throw publicMcpUnavailableError(unavailableMcp);
382
402
  await Promise.all([
@@ -457,13 +477,34 @@ export default {
457
477
  const requestedTimeout = Number(ctx.timeoutMs);
458
478
  const timeoutMs = Number.isFinite(requestedTimeout) && requestedTimeout > 0
459
479
  ? Math.min(requestedTimeout, DEFAULT_TIMEOUT_MS) : DEFAULT_TIMEOUT_MS;
480
+ // F460: on a public seat the credential goes once every MCP reader has it
481
+ // (their ready files), or at the deadline. A delete that fails ends the turn.
482
+ let releaseFailure = null;
483
+ let child = null;
484
+ const spawnImpl = (...spawnArgs) => {
485
+ child = (ctx._spawnImpl || childSpawn)(...spawnArgs);
486
+ return child;
487
+ };
488
+ if (readyFileDir) {
489
+ credentialRelease = armCredentialRelease(credential, {
490
+ readyFiles: readyFiles.map(({ path }) => path),
491
+ label: 'public Qwen seat',
492
+ // eslint-disable-next-line no-console
493
+ warn: (text) => console.warn(`[qwen] ${text}`),
494
+ onFailure: (err) => { releaseFailure = err; child?.kill?.('SIGKILL'); },
495
+ ...ctx._credentialRelease,
496
+ });
497
+ if (credentialRelease.error) throw credentialRelease.error;
498
+ }
460
499
  const result = await runQwen({
461
500
  cmd, args: spawnArgs, cwd: ctx.cwd, env, timeoutMs,
462
- spawnImpl: ctx._spawnImpl,
501
+ spawnImpl,
463
502
  credentials: [...spawnCredentials(ctx, []), proxyWithBearer.bearer],
464
- });
503
+ }).catch((err) => { throw releaseFailure || err; });
504
+ if (releaseFailure) throw releaseFailure;
465
505
  return { text: result.text, newSessionId: null };
466
506
  } finally {
507
+ credentialRelease?.stop();
467
508
  try { await proxy?.close(); } catch { /* best effort */ }
468
509
  await Promise.all([tempDir, home].map((path) => rm(path, { recursive: true, force: true })));
469
510
  }
@@ -24,7 +24,9 @@
24
24
  * fd, then file, then environment — by declaration, and refuses to fall through
25
25
  * from a declared source that cannot be read.
26
26
  */
27
- import { chmodSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
27
+ import {
28
+ chmodSync, existsSync, mkdirSync, rmSync, writeFileSync,
29
+ } from 'node:fs';
28
30
  import { dirname, join } from 'node:path';
29
31
  import { randomBytes } from 'node:crypto';
30
32
 
@@ -79,6 +81,26 @@ export const writeCredentialFile = (token, {
79
81
  return { path, dir };
80
82
  };
81
83
 
84
+ /**
85
+ * Writes the token again at the path an earlier writeCredentialFile chose, for
86
+ * a retry whose config already names that path (F460: the first run released
87
+ * it once its readers had it).
88
+ */
89
+ export const restoreCredentialFile = (written, token, {
90
+ fs = {
91
+ mkdirSync, writeFileSync, chmodSync, rmSync,
92
+ },
93
+ } = {}) => {
94
+ const value = typeof token === 'string' ? token.trim() : '';
95
+ if (!written?.path || !written?.dir || !value) return false;
96
+ fs.mkdirSync(written.dir, { recursive: true, mode: 0o700 });
97
+ // Exclusive create: whatever sits at the path is removed, never written through.
98
+ fs.rmSync(written.path, { force: true });
99
+ fs.writeFileSync(written.path, value, { mode: 0o600, flag: 'wx' });
100
+ fs.chmodSync(written.path, 0o600);
101
+ return true;
102
+ };
103
+
82
104
  /** Best-effort removal once the spawn that owns the file has ended. */
83
105
  export const removeCredentialFile = (written, { fs = { rmSync } } = {}) => {
84
106
  const dir = typeof written === 'string' ? dirname(written) : written?.dir;
@@ -90,3 +112,97 @@ export const removeCredentialFile = (written, { fs = { rmSync } } = {}) => {
90
112
  return false;
91
113
  }
92
114
  };
115
+
116
+ /** How long a public seat waits for its MCP servers' ready files (F460). */
117
+ export const READY_DEADLINE_MS = 30_000;
118
+
119
+ /**
120
+ * F460. Delete this spawn's credential as soon as every process that reads it
121
+ * has read it, so nothing the model does later in the turn (a tool, a link the
122
+ * walk missed) can reach it. pi has done this since F146; this is the one
123
+ * shared version.
124
+ *
125
+ * Two triggers, either of which may fire first:
126
+ * - `release('stream')`, called by the adapter on an output event measured to
127
+ * come after every read (pi's first event, OpenCode's step_start);
128
+ * - `readyFiles`: each Commonly MCP server writes its ready file on the host's
129
+ * first `tools/list`, after it read the credential at start, and the broker
130
+ * bridge does the same. Once every listed file exists, the credential goes.
131
+ * With a deadline: a server that never gets ready costs a degraded turn,
132
+ * never a credential left readable for the whole turn.
133
+ *
134
+ * A delete that fails stops the turn: `onFailure(error)` kills the child, and
135
+ * the error (the path, never the value) is the turn's result. `stop()` belongs
136
+ * in the spawn's `finally`, beside `removeCredentialFile`.
137
+ */
138
+ export const armCredentialRelease = (credential, {
139
+ readyFiles = null,
140
+ // An adapter with a trigger of its own (OpenCode's first step) calls
141
+ // release() itself; an empty list then waits for it, or the deadline.
142
+ ownTrigger = false,
143
+ deadlineMs = READY_DEADLINE_MS,
144
+ pollMs = 100,
145
+ label = 'this seat',
146
+ onFailure = () => {},
147
+ warn = () => {},
148
+ fs = { rmSync, existsSync },
149
+ timers = {
150
+ setTimeout, clearTimeout, setInterval, clearInterval,
151
+ },
152
+ } = {}) => {
153
+ let armed = Boolean(credential?.dir);
154
+ let reason = null;
155
+ let error = null;
156
+ let poll = null;
157
+ let deadline = null;
158
+ const stop = () => {
159
+ if (poll !== null) timers.clearInterval(poll);
160
+ if (deadline !== null) timers.clearTimeout(deadline);
161
+ poll = null;
162
+ deadline = null;
163
+ };
164
+ const release = (why) => {
165
+ if (!armed) return error;
166
+ armed = false;
167
+ reason = why;
168
+ stop();
169
+ try {
170
+ fs.rmSync(credential.dir, { recursive: true, force: true });
171
+ } catch (err) {
172
+ error = new Error(
173
+ `${label} could not delete its runtime credential (${credential.path}) once its readers had it: `
174
+ + `${err?.code || err?.message || err}; the turn was stopped so the credential does not stay readable to its tools`,
175
+ );
176
+ onFailure(error);
177
+ }
178
+ return error;
179
+ };
180
+ if (armed && Array.isArray(readyFiles)) {
181
+ const waits = ownTrigger && !readyFiles.length;
182
+ const allReady = () => !waits && readyFiles.every((path) => fs.existsSync(path));
183
+ if (allReady()) {
184
+ release('ready');
185
+ } else {
186
+ if (!waits) {
187
+ poll = timers.setInterval(() => { if (allReady()) release('ready'); }, pollMs);
188
+ poll?.unref?.();
189
+ }
190
+ deadline = timers.setTimeout(() => {
191
+ const missing = readyFiles.filter((path) => !fs.existsSync(path));
192
+ warn(
193
+ `${label}: MCP servers not ready after ${Math.round(deadlineMs / 1000)}s `
194
+ + `(${missing.length ? missing.join(', ') : 'its runtime never reported them started'}); `
195
+ + 'the runtime credential was deleted anyway, so tools that still need it will fail this turn',
196
+ );
197
+ release('deadline');
198
+ }, deadlineMs);
199
+ deadline?.unref?.();
200
+ }
201
+ }
202
+ return {
203
+ release,
204
+ stop,
205
+ get reason() { return reason; },
206
+ get error() { return error; },
207
+ };
208
+ };
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Ready files for a public seat's MCP servers (F421, F460).
3
+ *
4
+ * The Commonly MCP server reads the seat credential once, at start, and
5
+ * creates the file named in COMMONLY_MCP_READY_FILE on its host's first
6
+ * `tools/list` (commonly-mcp/src/ready-file.js); the grant-broker bridge does
7
+ * the same (codex-broker-bridge.mjs). So once every ready file a spawn named
8
+ * exists, nothing in that spawn still needs the credential file, and
9
+ * `armCredentialRelease` (credential-file.js) deletes it.
10
+ *
11
+ * A seat names files only when the spawn has a ready folder, which the adapter
12
+ * creates for a public seat alone. A public seat whose Commonly server can't
13
+ * be shown to write one is refused: a warm build from before ready files, or
14
+ * our package run from a path outside the host-prepared MCP home (a checkout).
15
+ * Without the file its credential would stay readable to the deadline on every
16
+ * turn, or, named by nothing, be gone before that server read it.
17
+ */
18
+ import { randomUUID } from 'node:crypto';
19
+ import { join } from 'node:path';
20
+ import { CREDENTIAL_FILE_VAR } from './credential-file.js';
21
+ import { isShippedCommonlyMcpCommand } from './declared-mcp-guard.js';
22
+ import { selectedMcpWritesReadyFile } from './mcp-home.js';
23
+ import { describeMcpCommand } from './mcp-server-version.js';
24
+
25
+ export const MCP_READY_FILE_ENV = 'COMMONLY_MCP_READY_FILE';
26
+
27
+ const nameReadyFile = (name, ctx) => {
28
+ const path = join(ctx.readyFileDir, randomUUID());
29
+ ctx.readyFiles.push({ name, path });
30
+ return path;
31
+ };
32
+
33
+ export const publicMcpOutdatedError = (name) => new Error(
34
+ `public seats need a Commonly MCP server that reports when it has started, and the one this seat runs for `
35
+ + `${name} does not (a build from before that, or one run from outside the host-prepared MCP home); `
36
+ + 'update @commonlyai/mcp',
37
+ );
38
+
39
+ export const publicMcpUnreportedReaderError = (name) => new Error(
40
+ `public seats hand the runtime credential only to the Commonly MCP server, which reports when it has read it; `
41
+ + `${name} is another server declaring ${CREDENTIAL_FILE_VAR}, so it would lose the credential before reading it. `
42
+ + 'Remove that declaration, or run this server on a private seat',
43
+ );
44
+
45
+ /**
46
+ * The ready file for `server` (as declared), run as `spawnCommand` (the warm
47
+ * build it resolved to), or null when this spawn names none for it.
48
+ */
49
+ export const commonlyMcpReadyFile = (server, spawnCommand, ctx, {
50
+ writesReadyFile = selectedMcpWritesReadyFile,
51
+ describe = describeMcpCommand,
52
+ env = null,
53
+ } = {}) => {
54
+ if (!ctx?.readyFileDir) return null;
55
+ const ours = isShippedCommonlyMcpCommand(server?.command) || Boolean(describe(spawnCommand)?.isCommonly);
56
+ if (!ours) {
57
+ // `env` is the entry's environment after credential delivery: a server that
58
+ // is not ours but was handed the credential path names no ready file, so
59
+ // the release would not wait for it.
60
+ if (env && String(env[CREDENTIAL_FILE_VAR] ?? '').trim()) throw publicMcpUnreportedReaderError(server?.name);
61
+ return null;
62
+ }
63
+ if (!writesReadyFile(spawnCommand)) throw publicMcpOutdatedError(server.name);
64
+ return nameReadyFile(server.name, ctx);
65
+ };
66
+
67
+ /** The broker bridge ships with this CLI, so it always writes one. */
68
+ export const bridgeReadyFile = (server, ctx) => (ctx?.readyFileDir ? nameReadyFile(server.name, ctx) : null);