@commonlyai/cli 0.1.349 → 0.1.351

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.349",
3
+ "version": "0.1.351",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -1014,6 +1014,12 @@ const HELD_RETRY_MAX_FAILURES = 3;
1014
1014
  // server redelivers it under its cap, and may retire it with the TASK-656 line,
1015
1015
  // which is skipped if the agent has posted in the pod since.
1016
1016
  const PAST_CAP_MAX_CARRIES = 5;
1017
+ // F236: how often a seat waiting out an open circuit checks its inbox, so a pod
1018
+ // that first asks during the wait is told why within about a minute instead of
1019
+ // at the probe (up to ~16 minutes). The check runs no turn: the circuit's delay
1020
+ // is unchanged, and the can't-answer limit (once per cause per pod per hour)
1021
+ // still decides who hears it.
1022
+ const CIRCUIT_NOTICE_CHECK_MS = 60 * 1000;
1017
1023
 
1018
1024
  // Who gets a slot when a batch is past the cap. 'unknown' counts as a person:
1019
1025
  // only a row the snapshot and the kernel's stamp both can't place reads so, and
@@ -4470,7 +4476,7 @@ export const performRun = ({
4470
4476
  tickTimer = null;
4471
4477
  if (!running) return;
4472
4478
  tickInFlight = true;
4473
- try { await runTick(); } finally {
4479
+ try { await (circuitNotice ? runCircuitNoticeCheck() : runTick()); } finally {
4474
4480
  tickInFlight = false;
4475
4481
  if (!running) {
4476
4482
  try { await handBackCarryOnStop(); } finally { resolveStopped(); }
@@ -4478,8 +4484,12 @@ export const performRun = ({
4478
4484
  }
4479
4485
  };
4480
4486
 
4487
+ // F236: set when a retry opens the circuit for a failure a person can be
4488
+ // told about; `remainingMs` is what is left of the wait after the next check.
4489
+ let circuitNotice = null;
4481
4490
  const runTick = async () => {
4482
4491
  tickUnsettled = [];
4492
+ circuitNotice = null;
4483
4493
  let nextPollDelayMs = intervalMs;
4484
4494
  let completedModelTurn = false;
4485
4495
  let retryScheduled = false;
@@ -4659,6 +4669,9 @@ export const performRun = ({
4659
4669
  });
4660
4670
  nextPollDelayMs = retry.delayMs;
4661
4671
  retryScheduled = true;
4672
+ circuitNotice = retry.circuitOpen && cantAnswerNotice(err) && !modelUnavailableFailure(err)
4673
+ ? { error: err, remainingMs: retry.delayMs }
4674
+ : null;
4662
4675
  tickUnsettled.push(...claimedAfter(groupIndex));
4663
4676
  const attempted = failedEvents.filter((event) => !pastCapEvents.includes(event));
4664
4677
  await noteFailedTurnPart(attempted);
@@ -4933,7 +4946,55 @@ export const performRun = ({
4933
4946
  // names it, and a sibling's completed turn must not shorten the backoff.
4934
4947
  // A wait the loop schedules itself always ends, so it is not a stall.
4935
4948
  pollLiveness.pause();
4936
- if (running) tickTimer = setTimeoutImpl(tick, completedModelTurn && !retryScheduled ? 3000 : nextPollDelayMs);
4949
+ const waitMs = completedModelTurn && !retryScheduled ? 3000 : nextPollDelayMs;
4950
+ const checkMs = Math.max(CIRCUIT_NOTICE_CHECK_MS, intervalMs);
4951
+ if (circuitNotice && waitMs > checkMs) circuitNotice.remainingMs = waitMs - checkMs;
4952
+ else circuitNotice = null;
4953
+ if (running) tickTimer = setTimeoutImpl(tick, circuitNotice ? checkMs : waitMs);
4954
+ };
4955
+
4956
+ // F236: one check during a circuit wait. What it claims joins the carry, so
4957
+ // the probe runs it, a stop hands it back, and its leases are renewed; each
4958
+ // newly waiting pod is told why. No turn runs here.
4959
+ const runCircuitNoticeCheck = async () => {
4960
+ const wait = circuitNotice;
4961
+ try {
4962
+ pollLiveness.arm();
4963
+ const carriedCount = [...heldRetry, ...heldGreeting]
4964
+ .filter((event) => event.deliveryMode !== 'digest').length;
4965
+ const page = await client.get('/api/agents/runtime/events', {
4966
+ agentName, instanceId, limit: Math.max(1, batchLimit - carriedCount),
4967
+ ...(adapter?.name ? { reportedCli: adapter.name } : {}),
4968
+ });
4969
+ pollLiveness.arm();
4970
+ if (pollStalled) return;
4971
+ const fetched = page?.events || [];
4972
+ // A carried id comes back only after the server requeued it, so the
4973
+ // fetched copy holds the live deliveryId and the carried one's is dead.
4974
+ // The fetched copy wins, as in runTick: otherwise the probe, which can no
4975
+ // longer fetch it, would ack a stale nonce and stop the run.
4976
+ const fetchedById = new Map(fetched.map((event) => [String(event._id), event]));
4977
+ // Reassigned only when a copy changes, so the renewal's `heldRetry !== carry`
4978
+ // guard skips its pruning only when there was something to replace.
4979
+ const refetched = (carry) => carry.some((event) => fetchedById.has(String(event._id)));
4980
+ const refreshCarry = (carry) => carry.map((event) => fetchedById.get(String(event._id)) || event);
4981
+ if (refetched(heldRetry)) heldRetry = refreshCarry(heldRetry);
4982
+ if (refetched(heldGreeting)) heldGreeting = refreshCarry(heldGreeting);
4983
+ const carriedIds = new Set([...heldRetry, ...heldGreeting].map((event) => String(event._id)));
4984
+ const fresh = fetched.filter((event) => !carriedIds.has(String(event._id)));
4985
+ if (fetched.length) idleHeartbeat.busy();
4986
+ if (fresh.length) await holdForRetry([], fresh);
4987
+ if (fetched.length) keepHeldLeases(wait.remainingMs);
4988
+ if (fresh.length) await noticeCantAnswer(wait.error, fresh);
4989
+ } catch (error) {
4990
+ log(`[inbox.batch] inbox check during the circuit wait failed: ${error.message}`);
4991
+ }
4992
+ pollLiveness.pause();
4993
+ const checkMs = Math.max(CIRCUIT_NOTICE_CHECK_MS, intervalMs);
4994
+ const stepMs = Math.min(checkMs, wait.remainingMs);
4995
+ wait.remainingMs -= stepMs;
4996
+ if (wait.remainingMs <= 0) circuitNotice = null;
4997
+ if (running) tickTimer = setTimeoutImpl(tick, stepMs);
4937
4998
  };
4938
4999
 
4939
5000
  tick();
@@ -55,7 +55,9 @@ import { describeTurnReap, markTurn, turnReapEnabled } from '@commonlyai/seats/t
55
55
  import { requireSeatModel, seatModelRequired } from './seat-model.js';
56
56
  import { claudeRunStats } from '../reply-receipt.js';
57
57
  import { spawn as childSpawn, spawnSync } from 'child_process';
58
- import { createHash, randomUUID } from 'crypto';
58
+ import {
59
+ createHash, randomBytes, randomUUID, timingSafeEqual,
60
+ } from 'crypto';
59
61
  import { accessSync, constants, realpathSync } from 'fs';
60
62
  import {
61
63
  chmod,
@@ -73,6 +75,7 @@ import {
73
75
  unlink,
74
76
  writeFile,
75
77
  } from 'fs/promises';
78
+ import { createServer } from 'net';
76
79
  import { homedir, tmpdir } from 'os';
77
80
  import {
78
81
  delimiter, dirname, isAbsolute, join,
@@ -140,12 +143,33 @@ const RUNTIME_CREDENTIAL_PLACEHOLDER = '${COMMONLY_AGENT_TOKEN}';
140
143
 
141
144
  const QUOTE_SHELL_ARGUMENT = (value) => `'${String(value).replaceAll("'", "'\\''")}'`;
142
145
 
146
+ // The helper takes the token from one of two places. With a socket path and a
147
+ // key file as its second and third arguments (a public seat, F461), it sends
148
+ // the key and the adapter, which holds the token in memory for the turn,
149
+ // answers with the token; the credential file can then go once the stdio
150
+ // servers have read it. Otherwise it reads the per-spawn file.
143
151
  const HEADER_TOKEN_HELPER_SOURCE = `import { readFileSync } from 'node:fs';
144
-
145
- const credentialFile = process.env.${CREDENTIAL_FILE_VAR};
146
- if (!credentialFile) throw new Error('missing ${CREDENTIAL_FILE_VAR}');
147
- const token = readFileSync(credentialFile, 'utf8').trim();
148
- if (!token) throw new Error('empty ${CREDENTIAL_FILE_VAR}');
152
+ import { createConnection } from 'node:net';
153
+
154
+ const fromChannel = (path, key) => new Promise((resolve, reject) => {
155
+ const chunks = [];
156
+ const socket = createConnection({ path }, () => socket.write(key + '\\n'));
157
+ socket.setTimeout(10000, () => socket.destroy(new Error('the header credential channel did not answer')));
158
+ socket.on('data', (chunk) => chunks.push(chunk));
159
+ socket.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
160
+ socket.on('error', reject);
161
+ });
162
+ const channel = process.argv[3];
163
+ let token;
164
+ if (channel) {
165
+ token = (await fromChannel(channel, readFileSync(process.argv[4], 'utf8').trim())).trim();
166
+ if (!token) throw new Error('the header credential channel sent nothing');
167
+ } else {
168
+ const credentialFile = process.env.${CREDENTIAL_FILE_VAR};
169
+ if (!credentialFile) throw new Error('missing ${CREDENTIAL_FILE_VAR}');
170
+ token = readFileSync(credentialFile, 'utf8').trim();
171
+ if (!token) throw new Error('empty ${CREDENTIAL_FILE_VAR}');
172
+ }
149
173
  const templates = JSON.parse(readFileSync(process.argv[2], 'utf8'));
150
174
  const headers = Object.fromEntries(
151
175
  Object.entries(templates).map(([name, parts]) => [name, parts.join(token)]),
@@ -1100,10 +1124,86 @@ const writePrivateFile = async (path, contents) => {
1100
1124
  await chmod(path, 0o600);
1101
1125
  };
1102
1126
 
1127
+ // F461. The longest socket path the platform takes (sun_path: 104 bytes on
1128
+ // macOS with its terminator; Linux allows 108).
1129
+ const MAX_SOCKET_PATH = 103;
1130
+
1131
+ // F461. A public seat's header helper asks this process for the token over a
1132
+ // Unix socket in the spawn's own folder (0700, the socket 0600), so the
1133
+ // credential file no longer has to outlive the stdio servers' first read. The
1134
+ // token stays in this process's memory.
1135
+ //
1136
+ // The socket answers only a client that first sends this turn's key, a 256-bit
1137
+ // random value in a 0600 file beside it. A Unix connect is not a file read: on
1138
+ // macOS another seat's Seatbelt jail, denied this folder, can still connect to
1139
+ // a socket whose path it learns (measured), because a seat's network is open.
1140
+ // The key keeps the boundary where the file had it, at who can read this
1141
+ // folder. Claude's Read tool cannot open a socket, so reading the key alone
1142
+ // gets it nothing.
1143
+ //
1144
+ // Windows keeps the file: a named pipe's default ACL grants read to Everyone. A
1145
+ // path too long for a socket, or a socket that cannot be set up, keeps the file
1146
+ // too, with a warning.
1147
+ const CHANNEL_IDLE_MS = 10_000;
1148
+ export const startHeaderCredentialChannel = async (dir, token, { platform = process.platform, warn } = {}) => {
1149
+ const value = typeof token === 'string' ? token.trim() : '';
1150
+ if (!value || platform === 'win32') return null;
1151
+ const path = join(dir, 'headers.sock');
1152
+ const keyPath = join(dir, 'headers.key');
1153
+ if (Buffer.byteLength(path) > MAX_SOCKET_PATH) {
1154
+ warn?.(`the header credential socket path is too long (${path}), so this turn keeps its credential file for its HTTP servers`);
1155
+ return null;
1156
+ }
1157
+ const key = randomBytes(32).toString('hex');
1158
+ const expected = Buffer.from(key);
1159
+ const sockets = new Set();
1160
+ const server = createServer((socket) => {
1161
+ sockets.add(socket);
1162
+ socket.on('close', () => sockets.delete(socket));
1163
+ socket.on('error', () => {});
1164
+ socket.setTimeout(CHANNEL_IDLE_MS, () => socket.destroy());
1165
+ socket.setEncoding('utf8');
1166
+ let received = '';
1167
+ socket.on('data', (chunk) => {
1168
+ received += chunk;
1169
+ const newline = received.indexOf('\n');
1170
+ if (newline === -1) {
1171
+ if (received.length > key.length) socket.destroy();
1172
+ return;
1173
+ }
1174
+ const sent = Buffer.from(received.slice(0, newline));
1175
+ socket.removeAllListeners('data');
1176
+ if (sent.length === expected.length && timingSafeEqual(sent, expected)) socket.end(value);
1177
+ else socket.destroy();
1178
+ });
1179
+ });
1180
+ // Ends every open connection too: server.close() alone waits for them.
1181
+ const close = () => new Promise((resolve) => {
1182
+ for (const socket of sockets) socket.destroy();
1183
+ server.close(() => resolve());
1184
+ });
1185
+ try {
1186
+ await writePrivateFile(keyPath, key);
1187
+ await new Promise((resolve, reject) => {
1188
+ server.once('error', reject);
1189
+ server.listen(path, () => { server.off('error', reject); resolve(); });
1190
+ });
1191
+ server.unref();
1192
+ await chmod(path, 0o600);
1193
+ } catch (err) {
1194
+ if (server.listening) await close();
1195
+ await rm(keyPath, { force: true }).catch(() => {});
1196
+ warn?.(`the header credential socket could not be set up (${err?.code || err?.message || err}), so this turn keeps its credential file for its HTTP servers`);
1197
+ return null;
1198
+ }
1199
+ return { path, keyPath, close };
1200
+ };
1201
+
1103
1202
  // Claude's headersHelper is invoked when an HTTP connection is established and
1104
1203
  // again after an authentication retry. Keep the token out of its config and
1105
- // environment: the helper reads the current per-spawn file on every invocation.
1106
- const createTokenHeaderHelpers = async (mcpServers, dir) => {
1204
+ // environment: the helper asks the channel above when there is one, and reads
1205
+ // the current per-spawn file otherwise, on every invocation.
1206
+ const createTokenHeaderHelpers = async (mcpServers, dir, channel = null) => {
1107
1207
  const servers = mcpServers
1108
1208
  .map((server, index) => ({ server, index, templates: getTokenHeaderTemplates(server) }))
1109
1209
  .filter((item) => item.templates);
@@ -1120,6 +1220,7 @@ const createTokenHeaderHelpers = async (mcpServers, dir) => {
1120
1220
  QUOTE_SHELL_ARGUMENT(process.execPath),
1121
1221
  QUOTE_SHELL_ARGUMENT(scriptPath),
1122
1222
  QUOTE_SHELL_ARGUMENT(templatesPath),
1223
+ ...(channel ? [QUOTE_SHELL_ARGUMENT(channel.path), QUOTE_SHELL_ARGUMENT(channel.keyPath)] : []),
1123
1224
  ].join(' '),
1124
1225
  headerNames: Object.keys(templates),
1125
1226
  });
@@ -1194,6 +1295,7 @@ const createMcpConfig = async (mcpServers, ctx = {}) => {
1194
1295
  const dir = await mkdtemp(join(tmpdir(), 'commonly-claude-mcp-'));
1195
1296
  const file = join(dir, 'mcp-config.json');
1196
1297
  let credential = null;
1298
+ let headerChannel = null;
1197
1299
  try {
1198
1300
  await chmod(dir, 0o700);
1199
1301
  // Written BEFORE the config, because the config may only reference it. It
@@ -1201,8 +1303,19 @@ const createMcpConfig = async (mcpServers, ctx = {}) => {
1201
1303
  // config — no second lifecycle to get wrong — and so it is inside the one
1202
1304
  // non-workspace path the Seatbelt profile admits.
1203
1305
  credential = writeCredentialFile(ctx.runtimeToken, { agentName: ctx.agentName || 'agent', root: dir });
1306
+ // F461: only a seat that will release its credential (a public one, which
1307
+ // names a ready-file folder) needs the token from somewhere else.
1308
+ const wantsChannel = Boolean(credential?.path && ctx.readyFileDir)
1309
+ && mcpServers.some((server) => getTokenHeaderTemplates(server));
1310
+ if (wantsChannel) {
1311
+ headerChannel = await startHeaderCredentialChannel(dir, ctx.runtimeToken, {
1312
+ platform: ctx.platform,
1313
+ // eslint-disable-next-line no-console
1314
+ warn: (text) => console.warn(`[claude] ${text}`),
1315
+ });
1316
+ }
1204
1317
  const dynamicHeaderHelpers = credential?.path
1205
- ? await createTokenHeaderHelpers(mcpServers, dir)
1318
+ ? await createTokenHeaderHelpers(mcpServers, dir, headerChannel)
1206
1319
  : new Map();
1207
1320
  const unavailableMcp = [];
1208
1321
  const mcpReadDirectories = [];
@@ -1224,7 +1337,7 @@ const createMcpConfig = async (mcpServers, ctx = {}) => {
1224
1337
  const expansionEnv = buildMcpExpansionEnv(config, {
1225
1338
  ...ctx,
1226
1339
  credentialFile: credential?.path || null,
1227
- headersHelperUsesCredentialFile: dynamicHeaderHelpers.size > 0,
1340
+ headersHelperUsesCredentialFile: dynamicHeaderHelpers.size > 0 && !headerChannel,
1228
1341
  });
1229
1342
  if (expansionEnv[CREDENTIAL_KEY]) {
1230
1343
  // eslint-disable-next-line no-console
@@ -1236,12 +1349,13 @@ const createMcpConfig = async (mcpServers, ctx = {}) => {
1236
1349
  );
1237
1350
  }
1238
1351
  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,
1352
+ dir, file, credential, expansionEnv, unavailableMcp, mcpReadDirectories, headerChannel,
1353
+ // A headersHelper that reads the file on every HTTP (re)connect keeps it
1354
+ // for the turn. One on the channel (F461) does not.
1355
+ helpersReadCredentialFile: dynamicHeaderHelpers.size > 0 && !headerChannel,
1243
1356
  };
1244
1357
  } catch (err) {
1358
+ try { await headerChannel?.close(); } catch { /* ignore */ }
1245
1359
  try { await rm(dir, { recursive: true, force: true }); } catch { /* ignore */ }
1246
1360
  throw err;
1247
1361
  }
@@ -1744,7 +1858,7 @@ export default {
1744
1858
  return claudeChild;
1745
1859
  };
1746
1860
  const armRelease = () => {
1747
- if (!readyFileDir || !mcpConfig?.credential || mcpConfig.headerHelpers > 0) return;
1861
+ if (!readyFileDir || !mcpConfig?.credential || mcpConfig.helpersReadCredentialFile) return;
1748
1862
  credentialRelease = armCredentialRelease(mcpConfig.credential, {
1749
1863
  readyFiles: readyFiles.map(({ path }) => path),
1750
1864
  label: 'public Claude seat',
@@ -1907,6 +2021,7 @@ export default {
1907
2021
  instanceUrl: ctx.instanceUrl,
1908
2022
  agentName: ctx.agentName,
1909
2023
  publicSeat: publicTrust,
2024
+ platform: ctx._platform || process.platform,
1910
2025
  commandResolution: { env: withClaudePath(ctx.env), ...ctx._commandResolution },
1911
2026
  });
1912
2027
  }
@@ -2076,6 +2191,7 @@ export default {
2076
2191
  credentialRelease?.stop();
2077
2192
  await Promise.all(readyFiles.map(({ path }) => rm(path, { force: true }).catch(() => {})));
2078
2193
  if (ownReadyDir) await rm(ownReadyDir, { recursive: true, force: true }).catch(() => {});
2194
+ try { await mcpConfig?.headerChannel?.close(); } catch { /* ignore */ }
2079
2195
  if (mcpConfig?.dir) {
2080
2196
  try { await rm(mcpConfig.dir, { recursive: true, force: true }); } catch { /* ignore */ }
2081
2197
  }