@commonlyai/cli 0.1.327 → 0.1.329

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.327",
3
+ "version": "0.1.329",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -114,19 +114,22 @@ const watchDaemonStatus = async () => {
114
114
  const seats = (loadDaemonState()?.seats || []).map((seat) => ({
115
115
  ...seat,
116
116
  // The supervisor stamps spawn time; the session store holds real turns.
117
- lastTurnAt: readSessionLastTurn(seat.agentName),
117
+ lastTurnAt: readSessionLastTurn(seat.recordKey || seat.agentName),
118
118
  }));
119
+ // Keyed by the local record, so two instances of one agent never read
120
+ // each other's log, last turn or pod (F427).
119
121
  const logTails = {};
120
122
  for (const seat of seats) {
121
- const tail = readLogTail(daemonSeatLogPath(seat.agentName), 3);
122
- logTails[seat.agentName] = tail ? tail.split('\n') : [];
123
+ const key = seat.recordKey || seat.agentName;
124
+ const tail = readLogTail(daemonSeatLogPath(key), 3);
125
+ logTails[key] = tail ? tail.split('\n') : [];
123
126
  }
124
127
  let states = null;
125
128
  let stateNote = '';
126
129
  if (!getToken(record.instanceUrl)) {
127
130
  stateNote = `Not logged in: showing local process state only. Run: commonly login --instance ${record.instanceUrl}`;
128
131
  } else {
129
- const podIds = [...new Set(seats.map((seat) => loadAgentToken(seat.agentName)?.podId).filter(Boolean))];
132
+ const podIds = [...new Set(seats.map((seat) => loadAgentToken(seat.recordKey || seat.agentName)?.podId).filter(Boolean))];
130
133
  try {
131
134
  states = await reachFor(podIds);
132
135
  } catch (error) {
@@ -746,12 +749,14 @@ Examples:
746
749
  // One child per agent, logging to its own file. The child is the
747
750
  // ordinary `commonly agent run <name>` — the daemon is its
748
751
  // supervisor, never its replacement (D6).
749
- spawnChild: (agentName) => {
750
- warnMissingSeatKey(agentName);
751
- const seatLog = daemonSeatLogPath(agentName);
752
+ // `recordKey` is the local record: `<name>`, or `<name>@<id>` for
753
+ // another instance, which `agent run` resolves the same way (F427).
754
+ spawnChild: (recordKey) => {
755
+ warnMissingSeatKey(recordKey);
756
+ const seatLog = daemonSeatLogPath(recordKey);
752
757
  const out = openSync(seatLog, 'a', 0o600);
753
758
  chmodSync(seatLog, 0o600);
754
- return spawn(process.execPath, [process.argv[1], 'agent', 'run', agentName], {
759
+ return spawn(process.execPath, [process.argv[1], 'agent', 'run', recordKey], {
755
760
  stdio: ['ignore', out, out],
756
761
  // Windows: never flash a console window per seat (no-op elsewhere).
757
762
  windowsHide: true,
@@ -776,7 +781,7 @@ Examples:
776
781
  updatedAt: new Date().toISOString(),
777
782
  seats: seats.map((seat) => ({
778
783
  ...seat,
779
- lastTurnAt: getLastTurn(seat.agentName) || seat.lastTurnAt,
784
+ lastTurnAt: getLastTurn(seat.recordKey || seat.agentName) || seat.lastTurnAt,
780
785
  })),
781
786
  }),
782
787
  });
@@ -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 } from 'crypto';
26
+ import { createHash, randomUUID } from 'crypto';
27
27
  import { existsSync, readdirSync, realpathSync, rmSync } from 'fs';
28
28
  import {
29
29
  chmod,
@@ -43,7 +43,9 @@ import {
43
43
  } from 'path';
44
44
  import { writeCredentialFile } from '../credential-file.js';
45
45
  import { deliverSeatCredential, withholdRuntimeCredential } from '../mcp-credential-delivery.js';
46
- import { prepareMcpSpawn, publicMcpUnavailableError, selectedMcpVersionDir } from '../mcp-home.js';
46
+ import {
47
+ prepareMcpSpawn, publicMcpUnavailableError, selectedMcpVersionDir, selectedMcpWritesReadyFile,
48
+ } from '../mcp-home.js';
47
49
  import { buildMemoryPreamble } from '../memory-bridge.js';
48
50
  import {
49
51
  isLegacySandboxTrust,
@@ -57,7 +59,7 @@ import { wrapArgvWithSeatbelt } from '../sandbox/seatbelt.js';
57
59
  import { resolvePublicSandboxMode } from '../sandbox/mode.js';
58
60
  import { resolveProviderKeyFile, startProviderProxy } from '../provider-proxy.js';
59
61
  import { isShippedCommonlyMcpCommand } from '../declared-mcp-guard.js';
60
- import { isAnswerableToolError, PUBLIC_TOOL_FAILED_CODE } from '../public-tool-error.js';
62
+ import { isAnswerableToolError, PUBLIC_MCP_NOT_READY_CODE, PUBLIC_TOOL_FAILED_CODE } from '../public-tool-error.js';
61
63
  import { startInstanceProxy } from '../instance-proxy.js';
62
64
  import { publicSeatWithheldTools } from '../public-withheld-tools.js';
63
65
 
@@ -567,6 +569,14 @@ const buildMcpConfig = (servers, ctx = {}) => {
567
569
  console.warn(`[opencode] skipping MCP server ${server.name}: its credential declaration has no file-backed delivery`);
568
570
  continue;
569
571
  }
572
+ // F421: the shipped Commonly server of a public seat names its ready file,
573
+ // when the warm build it runs writes one (selectedMcpWritesReadyFile).
574
+ if (ctx.readyFileDir && isShippedCommonlyMcpCommand(server.command)
575
+ && (ctx.mcpWritesReadyFile || selectedMcpWritesReadyFile)(command)) {
576
+ const readyPath = join(ctx.readyFileDir, randomUUID());
577
+ env[MCP_READY_FILE_ENV] = readyPath;
578
+ ctx.readyFiles?.push({ name: server.name, path: readyPath });
579
+ }
570
580
  mcp[server.name] = {
571
581
  type: 'local',
572
582
  command: command.map((part) => substitutePublicPlaceholders(part, ctx)),
@@ -807,6 +817,31 @@ const makeEventParser = () => {
807
817
  // started, so each catches what the other cannot.
808
818
  export { PUBLIC_TOOL_FAILED_CODE };
809
819
 
820
+ // F421. OpenCode's stream says nothing about its MCP servers. When the Commonly
821
+ // server fails to start, OpenCode 1.19.0 logs one WARN line ("server
822
+ // unavailable … status=failed"), runs the model without the Commonly tools, and
823
+ // exits 0, so the reply would be an answer written without reading the pod
824
+ // (measured with a stub provider on 2026-11-11). The server creates the file
825
+ // this adapter names in COMMONLY_MCP_READY_FILE once OpenCode asks for its
826
+ // tools (tools/list, sent only after initialize succeeded), inside the folder the sandbox lets the seat write (OpenCode's own
827
+ // data home: Seatbelt's statePath, bwrap's write-outside). A turn whose file is
828
+ // missing never had the server, so its reply is withheld and the run loop tells
829
+ // the waiting pod why (turn-failure-notice.js) and retries.
830
+ export const MCP_READY_FILE_ENV = 'COMMONLY_MCP_READY_FILE';
831
+
832
+ export const missingReadyFile = (readyFiles, exists = existsSync) => (
833
+ (readyFiles || []).find(({ path }) => !exists(path)) || null
834
+ );
835
+
836
+ const publicMcpNotReadyError = (name) => {
837
+ const failure = new Error(
838
+ `public seat withheld this turn's reply: Commonly MCP server ${name} never reported ready (no ready file), `
839
+ + 'so the model ran without its Commonly tools; the CLI posted no reply for it and does not ack the event',
840
+ );
841
+ failure.code = PUBLIC_MCP_NOT_READY_CODE;
842
+ return failure;
843
+ };
844
+
810
845
  export const publicToolFailure = (toolErrors, mcpServers) => {
811
846
  const prefixes = (Array.isArray(mcpServers) ? mcpServers : [])
812
847
  .filter((server) => server?.name && isShippedCommonlyMcpCommand(server.command))
@@ -1217,6 +1252,8 @@ export default {
1217
1252
  root: tempDir,
1218
1253
  });
1219
1254
  let openCodeHome = null;
1255
+ let readyFileDir = null;
1256
+ const readyFiles = [];
1220
1257
  let providerProxy = null;
1221
1258
  let instanceProxy = null;
1222
1259
  try {
@@ -1242,6 +1279,7 @@ export default {
1242
1279
  });
1243
1280
  }
1244
1281
  const stateHome = isPublic ? join(openCodeHome.root, 'state') : null;
1282
+ readyFileDir = isPublic ? join(openCodeHome.root, 'mcp-ready') : null;
1245
1283
  const cacheHome = isPublic ? join(openCodeHome.root, 'cache') : null;
1246
1284
  const tempWork = isPublic ? join(openCodeHome.root, 'tmp') : join(tempDir, 'tmp');
1247
1285
  await Promise.all([
@@ -1252,7 +1290,11 @@ export default {
1252
1290
  const unavailableMcp = [];
1253
1291
  const mcpReadDirectories = [];
1254
1292
  const bearerFileServers = [];
1293
+ if (readyFileDir) await mkdir(readyFileDir, { recursive: true, mode: 0o700 });
1255
1294
  const mcp = buildMcpConfig(ctx.environment?.mcp, {
1295
+ readyFileDir,
1296
+ readyFiles,
1297
+ mcpWritesReadyFile: ctx._mcpWritesReadyFile,
1256
1298
  runtimeToken: ctx.runtimeToken,
1257
1299
  instanceUrl: instanceProxy
1258
1300
  ? `http://127.0.0.1:${ISOLATED_INSTANCE_PORT}` : ctx.instanceUrl,
@@ -1419,6 +1461,8 @@ export default {
1419
1461
  : undefined,
1420
1462
  });
1421
1463
  if (isPublic) {
1464
+ const notReady = missingReadyFile(readyFiles, ctx._existsSync);
1465
+ if (notReady) throw publicMcpNotReadyError(notReady.name);
1422
1466
  const failure = publicToolFailure(result.toolErrors, ctx.environment?.mcp);
1423
1467
  if (failure) throw publicToolFailedError(failure);
1424
1468
  }
@@ -1431,6 +1475,9 @@ export default {
1431
1475
  try { await instanceProxy?.close(); } catch { /* ignore */ }
1432
1476
  try { await providerProxy?.close(); } catch { /* ignore */ }
1433
1477
  try { await rm(tempDir, { recursive: true, force: true }); } catch { /* ignore */ }
1478
+ for (const { path } of readyFiles) {
1479
+ try { await rm(path, { force: true }); } catch { /* ignore */ }
1480
+ }
1434
1481
  }
1435
1482
  },
1436
1483
  };
@@ -26,6 +26,9 @@ const fixedLastError = (value) => {
26
26
  const seatState = (seat = {}) => ({
27
27
  agentName: seat.agentName,
28
28
  instanceId: seat.instanceId,
29
+ // The local record the seat runs from (`<name>` or `<name>@<id>`, F427):
30
+ // a file name, not a secret. Status reads its log and last turn by it.
31
+ recordKey: typeof seat.recordKey === 'string' ? seat.recordKey : null,
29
32
  state: seat.state,
30
33
  restarts: seat.restarts,
31
34
  adapter: seat.adapter || null,
@@ -59,6 +59,32 @@ export const backoffMs = (restarts) => Math.min(
59
59
 
60
60
  const identityKey = (agentName, instanceId) => `${agentName} ${instanceId || 'default'}`;
61
61
 
62
+ // An instance id becomes part of a local file name.
63
+ const INSTANCE_ID_PATTERN = /^[A-Za-z0-9._-]{1,64}$/;
64
+ const isDefaultInstance = (instanceId) => String(instanceId || 'default').toLowerCase() === 'default';
65
+ // Instance ids compare case-insensitively, as `agent run` and the server do.
66
+ const sameInstance = (a, b) => String(a || 'default').toLowerCase() === String(b || 'default').toLowerCase();
67
+
68
+ /**
69
+ * The local token record a seat lives in, as `agent run <key>` resolves it
70
+ * (F306, F427): the default instance is `<name>`, another is `<name>@<id>`,
71
+ * except a key an older CLI saved for that instance under the bare name, which
72
+ * is used where it is. So a second instance placed on a computer that already
73
+ * runs the default gets its own record, and neither overwrites the other.
74
+ * Null for an instance id that can't be a file name.
75
+ */
76
+ export const recordKeyFor = (row, loadToken) => {
77
+ const { agentName } = row;
78
+ const instanceId = row.instanceId || 'default';
79
+ if (isDefaultInstance(instanceId)) return agentName;
80
+ if (!INSTANCE_ID_PATTERN.test(instanceId)) return null;
81
+ const scoped = `${agentName}@${instanceId}`;
82
+ if (loadToken(scoped)) return scoped;
83
+ const legacy = loadToken(agentName);
84
+ if (legacy && sameInstance(legacy.instanceId, instanceId)) return agentName;
85
+ return scoped;
86
+ };
87
+
62
88
  export const createDaemonSupervisor = ({
63
89
  record,
64
90
  client,
@@ -104,7 +130,10 @@ export const createDaemonSupervisor = ({
104
130
 
105
131
  const persist = () => {
106
132
  try {
107
- persistState(agentStates());
133
+ // The local record key too, for this host's own readouts (the last turn
134
+ // is kept per record); the heartbeat reports agentStates() without it.
135
+ const keys = Array.from(seats.values()).map((s) => s.recordKey || s.agentName);
136
+ persistState(agentStates().map((state, i) => ({ ...state, recordKey: keys[i] })));
108
137
  } catch (error) {
109
138
  // A diagnostic state file must never take the daemon down. The log is
110
139
  // still useful, and the next state transition retries the write.
@@ -139,13 +168,13 @@ export const createDaemonSupervisor = ({
139
168
  return;
140
169
  }
141
170
  recentStarts.push(at);
142
- seat.child = spawnChild(seat.agentName);
171
+ seat.child = spawnChild(seat.recordKey || seat.agentName);
143
172
  seat.state = 'running';
144
173
  seat.pid = Number.isInteger(seat.child?.pid) ? seat.child.pid : null;
145
174
  seat.lastTurnAt = new Date().toISOString();
146
175
  seat.lastError = null;
147
176
  persist();
148
- log(`[${seat.agentName}] supervising (restarts so far: ${seat.restarts})`);
177
+ log(`[${seat.recordKey || seat.agentName}] supervising (restarts so far: ${seat.restarts})`);
149
178
  seat.child.on('exit', (code) => {
150
179
  seat.child = null;
151
180
  seat.pid = null;
@@ -158,7 +187,7 @@ export const createDaemonSupervisor = ({
158
187
  seat.lastError = code === 0 ? null : `child exited with code ${code}`;
159
188
  seat.restarts += 1;
160
189
  const delay = backoffMs(seat.restarts - 1);
161
- log(`[${seat.agentName}] exited (code ${code}) — respawn in ${Math.round(delay / 1000)}s`);
190
+ log(`[${seat.recordKey || seat.agentName}] exited (code ${code}) — respawn in ${Math.round(delay / 1000)}s`);
162
191
  seat.backoffTimer = setTimeoutFn(() => {
163
192
  seat.backoffTimer = null;
164
193
  startChild(seat);
@@ -178,7 +207,7 @@ export const createDaemonSupervisor = ({
178
207
  seat.backoffTimer = null;
179
208
  }
180
209
  if (seat.child) {
181
- log(`[${seat.agentName}] no longer assigned here — stopping`);
210
+ log(`[${seat.recordKey || seat.agentName}] no longer assigned here — stopping`);
182
211
  seat.child.kill('SIGTERM');
183
212
  } else {
184
213
  seat.state = 'stopped';
@@ -236,7 +265,7 @@ export const createDaemonSupervisor = ({
236
265
  // that refusal is answered with rotate:true — loudly.
237
266
  // Returns 'ready' | 'changed' (record updated — the seat must restart to
238
267
  // load it) | false.
239
- const ensureToken = async (row) => {
268
+ const ensureToken = async (row, recordKey) => {
240
269
  // One derive for this seat, so the broker refusal cannot be applied at three
241
270
  // of four sites: `seatBaseline` is where an environment becomes the one the
242
271
  // seat RUNS under, and `withholdGrantBroker` asks the same question the
@@ -253,18 +282,19 @@ export const createDaemonSupervisor = ({
253
282
  {
254
283
  instanceUrl: record.instanceUrl,
255
284
  onRefuse: (refusal, names) => log(
256
- `[${row.agentName}] ${refusal.code} (${refusal.reason}) — withholding ${names.join(', ')}: ${refusal.detail}`,
285
+ `[${recordKey}] ${refusal.code} (${refusal.reason}) — withholding ${names.join(', ')}: ${refusal.detail}`,
257
286
  ),
258
287
  },
259
288
  );
260
289
 
261
- const existing = loadToken(row.agentName);
290
+ const existing = loadToken(recordKey);
262
291
  if (existing) {
263
- // Local records are still keyed by agent name. Never rotate or launch
264
- // another instance through a same-name record: that would overwrite a
265
- // different seat's bearer until instance-scoped local records land.
266
- if ((existing.instanceId || 'default') !== (row.instanceId || 'default')) {
267
- log(`[${row.agentName}] local token belongs to instance '${existing.instanceId || 'default'}'; refusing '${row.instanceId || 'default'}'`);
292
+ // recordKeyFor gives each instance its own record; a record that still
293
+ // names another instance (written by hand, or the bare name holding a
294
+ // non-default instance when the default is placed) is never rotated or
295
+ // launched as this one, which would overwrite that seat's bearer.
296
+ if (!sameInstance(existing.instanceId, row.instanceId)) {
297
+ log(`[${recordKey}] local token belongs to instance '${existing.instanceId || 'default'}'; refusing '${row.instanceId || 'default'}'`);
268
298
  return false;
269
299
  }
270
300
  // A human owner can request a fresh key from Settings after revocation.
@@ -279,15 +309,15 @@ export const createDaemonSupervisor = ({
279
309
  agentName: row.agentName, instanceId: row.instanceId, rotate: true,
280
310
  });
281
311
  if (!minted?.token) throw new Error('mint returned no token');
282
- saveToken(row.agentName, {
312
+ saveToken(recordKey, {
283
313
  ...existing,
284
314
  runtimeToken: minted.token,
285
315
  reconnectRequestAppliedAt: row.reconnectRequestedAt,
286
316
  });
287
- log(`[${row.agentName}] owner-requested key rotation applied; restarting the seat`);
317
+ log(`[${recordKey}] owner-requested key rotation applied; restarting the seat`);
288
318
  return 'changed';
289
319
  } catch (error) {
290
- log(`[${row.agentName}] owner-requested key rotation failed: ${error.message}`);
320
+ log(`[${recordKey}] owner-requested key rotation failed: ${error.message}`);
291
321
  return false;
292
322
  }
293
323
  }
@@ -311,7 +341,7 @@ export const createDaemonSupervisor = ({
311
341
  // versa). Keep the existing child/token untouched until the exact
312
342
  // requested adapter is detected locally.
313
343
  if (detectedAdapter !== declaredAdapter) {
314
- log(`[${row.agentName}] requested adapter '${declaredAdapter}' is not available on this machine — keeping the current seat`);
344
+ log(`[${recordKey}] requested adapter '${declaredAdapter}' is not available on this machine — keeping the current seat`);
315
345
  return false;
316
346
  }
317
347
  nextAdapter = declaredAdapter;
@@ -324,7 +354,7 @@ export const createDaemonSupervisor = ({
324
354
  // adapter that needs a server binding (opencode) refuses to run under
325
355
  // the server's new one, so starting it would only crash-loop. The
326
356
  // owner sets the adapter back, or moves the provider to one it speaks.
327
- log(`[${row.agentName}] host-local provider: ${providerRefused} — keeping the current record and not starting it; `
357
+ log(`[${recordKey}] host-local provider: ${providerRefused} — keeping the current record and not starting it; `
328
358
  + `set the adapter back to ${existing.adapter || 'the previous one'} in Commonly, or change the provider`);
329
359
  return false;
330
360
  }
@@ -363,7 +393,7 @@ export const createDaemonSupervisor = ({
363
393
  if (adapterChanged
364
394
  || !isDeepStrictEqual(existing.environment || null, nextEnvironment)
365
395
  || (workspacePath && existing.workspacePath !== workspacePath)) {
366
- saveToken(row.agentName, nextRecord);
396
+ saveToken(recordKey, nextRecord);
367
397
  log('runtime config changed — restarting the seat to load it');
368
398
  return 'changed';
369
399
  }
@@ -374,7 +404,7 @@ export const createDaemonSupervisor = ({
374
404
  const nextEnvironment = derive(existing.environment, nextAdapter, {
375
405
  sandbox: !existing.environment,
376
406
  });
377
- saveToken(row.agentName, {
407
+ saveToken(recordKey, {
378
408
  ...existing,
379
409
  adapter: nextAdapter,
380
410
  ...(nextEnvironment ? { environment: nextEnvironment } : {}),
@@ -394,7 +424,7 @@ export const createDaemonSupervisor = ({
394
424
  sandbox: !existing.environment,
395
425
  });
396
426
  if (!isDeepStrictEqual(existing.environment || null, nextEnvironment || null)) {
397
- saveToken(row.agentName, { ...existing, environment: nextEnvironment });
427
+ saveToken(recordKey, { ...existing, environment: nextEnvironment });
398
428
  log('record predates the commonly MCP baseline — restarting the seat to load it');
399
429
  return 'changed';
400
430
  }
@@ -409,7 +439,7 @@ export const createDaemonSupervisor = ({
409
439
  if (requestedAdapter) {
410
440
  adapter = await resolveAdapter(row.runtime || null);
411
441
  if (adapter !== requestedAdapter) {
412
- log(`[${row.agentName}] requested adapter '${requestedAdapter}' is not available on this machine — skipping token mint`);
442
+ log(`[${recordKey}] requested adapter '${requestedAdapter}' is not available on this machine — skipping token mint`);
413
443
  return false;
414
444
  }
415
445
  }
@@ -421,25 +451,25 @@ export const createDaemonSupervisor = ({
421
451
  minted = await client.post('/api/agent-binding/runtime-token', body);
422
452
  } catch (error) {
423
453
  if (error?.status === 409 && error?.body?.code === 'token_exists') {
424
- log(`[${row.agentName}] a runtime token exists elsewhere — rotating it to this machine (the old token stops working)`);
454
+ log(`[${recordKey}] a runtime token exists elsewhere — rotating it to this machine (the old token stops working)`);
425
455
  try {
426
456
  minted = await client.post('/api/agent-binding/runtime-token', { ...body, rotate: true });
427
457
  } catch (rotateError) {
428
- log(`[${row.agentName}] token rotation failed: ${rotateError.message}`);
458
+ log(`[${recordKey}] token rotation failed: ${rotateError.message}`);
429
459
  return false;
430
460
  }
431
461
  } else {
432
- log(`[${row.agentName}] token mint failed: ${error.message}`);
462
+ log(`[${recordKey}] token mint failed: ${error.message}`);
433
463
  return false;
434
464
  }
435
465
  }
436
466
  if (!minted?.token) {
437
- log(`[${row.agentName}] mint returned no token — skipping`);
467
+ log(`[${recordKey}] mint returned no token — skipping`);
438
468
  return false;
439
469
  }
440
470
  if (!adapter) adapter = await resolveAdapter(row.runtime || null);
441
471
  if (!adapter) {
442
- log(`[${row.agentName}] no usable CLI adapter on this machine — install claude, codex, opencode, qwen, or dsh, or attach manually`);
472
+ log(`[${recordKey}] no usable CLI adapter on this machine — install claude, codex, opencode, qwen, or dsh, or attach manually`);
443
473
  return false;
444
474
  }
445
475
  const environment = environmentFor(row);
@@ -453,7 +483,7 @@ export const createDaemonSupervisor = ({
453
483
  adapter,
454
484
  { sandbox: true },
455
485
  );
456
- saveToken(row.agentName, {
486
+ saveToken(recordKey, {
457
487
  agentName: row.agentName,
458
488
  instanceId: row.instanceId,
459
489
  runtimeToken: minted.token,
@@ -467,7 +497,7 @@ export const createDaemonSupervisor = ({
467
497
  return workspacePath ? { workspacePath } : {};
468
498
  })() : {}),
469
499
  });
470
- log(`[${row.agentName}] provisioned runtime token (adapter: ${adapter}${environment?.value?.model ? `, model: ${environment.value.model}` : ''})`);
500
+ log(`[${recordKey}] provisioned runtime token (adapter: ${adapter}${environment?.value?.model ? `, model: ${environment.value.model}` : ''})`);
471
501
  return 'ready';
472
502
  };
473
503
 
@@ -527,8 +557,14 @@ export const createDaemonSupervisor = ({
527
557
  seats.set(key, seat);
528
558
  }
529
559
  seat.desired = true;
560
+ const recordKey = recordKeyFor(row, loadToken);
561
+ if (!recordKey) {
562
+ log(`[${row.agentName}] instance id '${row.instanceId}' is not a plain id (letters, digits, '.', '_' or '-'); not starting it`);
563
+ continue;
564
+ }
565
+ seat.recordKey = recordKey;
530
566
  // eslint-disable-next-line no-await-in-loop
531
- const ready = await ensureToken(row);
567
+ const ready = await ensureToken(row, recordKey);
532
568
  // Report what the seat actually RUNS, which is the record: `agent run`
533
569
  // reads it once at boot, and ensureToken above may have just rewritten it
534
570
  // (a mint, or a config change). Reading it AFTER ensureToken is the point
@@ -543,7 +579,7 @@ export const createDaemonSupervisor = ({
543
579
  // the TASK-065 measurement). ensureToken also REFUSES a change it cannot
544
580
  // apply — a requested adapter this machine does not have — so the record
545
581
  // is the honest answer there too: it names the adapter that kept running.
546
- const current = loadToken(row.agentName);
582
+ const current = loadToken(recordKey);
547
583
  seat.adapter = current ? (current.adapter || null) : (row.runtime?.adapter || null);
548
584
  seat.model = current ? (current.environment?.model || null) : (row.runtime?.model || null);
549
585
  seat.effort = current ? (current.environment?.effort || null) : (row.runtime?.effort || null);
@@ -82,7 +82,7 @@ const agentBlock = (seat, { now, width, color, logTail, states }) => {
82
82
  const dim = (text) => (color ? `${ANSI.dim}${text}${ANSI.reset}` : text);
83
83
  const bold = (text) => (color ? `${ANSI.bold}${text}${ANSI.reset}` : text);
84
84
  const lines = [
85
- `${bold(clip(seat.agentName || 'unknown', width))} ${agentStateLabel(seat, states)} last turn ${relative(seat.lastTurnAt, now)}`,
85
+ `${bold(clip(seat.recordKey || seat.agentName || 'unknown', width))} ${agentStateLabel(seat, states)} last turn ${relative(seat.lastTurnAt, now)}`,
86
86
  ];
87
87
  if (seat.lastError) lines.push(clip(` error: ${seat.lastError}`, width));
88
88
  for (const line of logTail || []) lines.push(dim(` ${safeLogLine(line, Math.max(10, width - 2))}`));
@@ -90,7 +90,7 @@ const agentBlock = (seat, { now, width, color, logTail, states }) => {
90
90
  };
91
91
 
92
92
  // Inputs: `machine` { name, status, lastSeenAt }, `seats` (from the daemon state
93
- // file), `logTails` { [agentName]: string[] }, `states` (Map from
93
+ // file), `logTails` { [recordKey || agentName]: string[] }, `states` (Map from
94
94
  // loadReachByAgent, or null), `stateNote` (why states is null), `now` (ms),
95
95
  // `width` (columns).
96
96
  export const renderDaemonWatch = ({
@@ -108,7 +108,7 @@ export const renderDaemonWatch = ({
108
108
  return out.join('\n');
109
109
  }
110
110
  for (const seat of seats) {
111
- out.push(...agentBlock(seat, { now, width, color, logTail: logTails[seat.agentName] || [], states }));
111
+ out.push(...agentBlock(seat, { now, width, color, logTail: logTails[seat.recordKey || seat.agentName] || [], states }));
112
112
  out.push('');
113
113
  }
114
114
  return out.join('\n').replace(/\n+$/, '');
@@ -350,6 +350,30 @@ export const selectedMcpVersionDir = (command, home = mcpHomeDir()) => {
350
350
  return versionDirFor(home, version);
351
351
  };
352
352
 
353
+ /**
354
+ * Whether the warm build this spawn runs writes the ready file (F421).
355
+ *
356
+ * A public OpenCode seat's stream reports nothing about its MCP servers, so the
357
+ * adapter names a file the Commonly server creates once its host reaches it
358
+ * (commonly-mcp/src/ready-file.js) and withholds a turn that ends without it.
359
+ * Only a release that says so in its package.json (`commonly.readyFile`) is
360
+ * asked: a build from before the file existed would leave every turn withheld.
361
+ * Anything this cannot read or verify answers false, which keeps the turn as it
362
+ * was before F421.
363
+ */
364
+ export const selectedMcpWritesReadyFile = (command, home = mcpHomeDir(), { readFile = defaultRead } = {}) => {
365
+ if (!selectedMcpVersionDir(command, home)) return false;
366
+ const version = relative(home, command[1]).split(sep)[0];
367
+ const raw = readFile(join(packageDirFor(home, version), 'package.json'));
368
+ if (typeof raw !== 'string') return false;
369
+ try {
370
+ const pkg = JSON.parse(raw);
371
+ return pkg?.name === MCP_PACKAGE && pkg?.commonly?.readyFile === true;
372
+ } catch {
373
+ return false;
374
+ }
375
+ };
376
+
353
377
  /**
354
378
  * The bin of an npm PREFIX dir, which is the shape the warm installs into:
355
379
  * `npm install --prefix <dir>` leaves `<dir>/node_modules/...`, with no version
@@ -88,6 +88,12 @@ export const OUT_OF_ALLOWANCE_NOTICE = 'I can’t answer right now: the AI accou
88
88
  // (CUT_OFF_LINE in agentMessageService.ts, pinned by a test).
89
89
  export const CUT_OFF_NOTICE = 'I got cut off before I could finish that, so please ask me again if anything is missing.';
90
90
 
91
+ // F421: a public seat whose Commonly tools never came up. Its model would have
92
+ // answered without reading the pod, so the wrapper withholds that answer and
93
+ // says this instead; the event stays unacked and is answered once the tools work.
94
+ export const TOOLS_UNAVAILABLE_NOTICE = 'I can’t answer right now: the tools I use to read and post here '
95
+ + `aren’t working on my computer. Whoever runs me needs to fix that. ${AGAIN}`;
96
+
91
97
  export const codexVersionNotice = (required) => 'I can’t answer right now: the computer I run on needs '
92
98
  + `Codex ${required} or newer. Whoever runs me needs to upgrade it and start me again. ${AGAIN}`;
93
99
 
@@ -96,7 +102,11 @@ const matches = (wordings, text) => wordings.some((wording) => wording.test(text
96
102
  /** The cause a pod should hear about, and its line, or null when it should hear nothing. */
97
103
  export const cantAnswerNotice = (error) => {
98
104
  // A public seat's withheld turn quotes a TOOL's error, not its own provider's.
99
- if (error?.code === PUBLIC_TOOL_FAILED_CODE || error?.code === PUBLIC_MCP_NOT_READY_CODE) return null;
105
+ // A tool that failed mid-turn usually means Commonly itself was unreachable,
106
+ // so a line could not reach the pod either; it stays silent and retries.
107
+ if (error?.code === PUBLIC_TOOL_FAILED_CODE) return null;
108
+ // Tools that never started leave the API reachable, and a stranger waiting.
109
+ if (error?.code === PUBLIC_MCP_NOT_READY_CODE) return { cause: 'tools-unavailable', text: TOOLS_UNAVAILABLE_NOTICE };
100
110
  if (error?.code === PUBLIC_CODEX_VERSION_CODE) {
101
111
  return { cause: 'codex-version', text: codexVersionNotice(error.requiredVersion) };
102
112
  }