@commonlyai/cli 0.1.104 → 0.1.106

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.104",
3
+ "version": "0.1.106",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -51,7 +51,9 @@ import {
51
51
  ADAPTERS_WITH_GRANT_BROKER,
52
52
  ADAPTERS_WITH_DEFAULT_SANDBOX,
53
53
  defaultMcpServers,
54
+ seatBaseline,
54
55
  withDefaultMcpServer,
56
+ withDefaultSandbox,
55
57
  } from '../lib/default-environment.js';
56
58
  import { withholdGrantBroker } from '../lib/grant-broker-guard.js';
57
59
  import {
@@ -63,6 +65,8 @@ import { claimReleaseFor, ackResultFor } from '../lib/claim-outcome.js';
63
65
  import { prepareCommitAttribution } from '../lib/commit-attribution.js';
64
66
  import { detectBwrap } from '../lib/sandbox/bwrap.js';
65
67
  import { resolvePublicSandboxMode } from '../lib/sandbox/mode.js';
68
+ import { hostSandboxRefusal, windowsSandboxMessage } from '../lib/sandbox/host-check.js';
69
+ import { prepareMcpBeforeFirstPoll } from '../lib/mcp-first-run.js';
66
70
  import { detectSeatbelt } from '../lib/sandbox/seatbelt.js';
67
71
  import { describeUpstreamRefusal } from '../lib/upstream-refusal.js';
68
72
  import {
@@ -77,6 +81,14 @@ import {
77
81
  spawnRetryJitter,
78
82
  spawnRetryPolicy,
79
83
  } from '../lib/spawn-retry.js';
84
+ import {
85
+ CONTENT_REFUSED_REASON,
86
+ composeRefusalHandoff,
87
+ contentRefusedResult,
88
+ isContentRefusal,
89
+ refusedItemRef,
90
+ sanitizeHandoffAgent,
91
+ } from '../lib/content-refusal.js';
80
92
  import {
81
93
  ADDRESSED_EVENT_TYPES,
82
94
  CASCADE_DEFAULTS,
@@ -140,6 +152,19 @@ export const deleteAgentToken = (name) => {
140
152
  // OpenCode is opt-in: unlike the established wrappers it must not be selected
141
153
  // just because its binary happens to be installed on the operator's machine.
142
154
  export const BOOTSTRAP_ADAPTER_DETECT_ORDER = ['claude', 'codex', 'pi'];
155
+ export const NO_AGENT_CLI_CODE = 'no_agent_cli';
156
+
157
+ /**
158
+ * A saved Connect-page seat from before bootstrap applied the default sandbox:
159
+ * an adapter that takes one, no workspace, and an environment with nothing
160
+ * enforced. Such a record is told how to pick the default up; it is not
161
+ * rewritten here (Cofounder, 2026-10-16: none were found outside our own tests).
162
+ */
163
+ export const savedSeatLacksDefaultSandbox = (record) => Boolean(record)
164
+ && ADAPTERS_WITH_DEFAULT_SANDBOX.has(record.adapter)
165
+ && !record.workspacePath
166
+ && record.environment !== null && typeof record.environment === 'object'
167
+ && withDefaultSandbox(record.environment) !== record.environment;
143
168
 
144
169
  /** Return the adapter binding resolved for this exact installation by the server. */
145
170
  export const runtimeAdapterForInstallation = ({ installations, podId, instanceId } = {}) => {
@@ -311,16 +336,26 @@ export const bootstrapAgentRecordFromEnv = async ({
311
336
  throw new Error(`Adapter '${adapterOverride}' not found on PATH.`);
312
337
  }
313
338
  } else {
339
+ const missing = [];
314
340
  for (const candidate of BOOTSTRAP_ADAPTER_DETECT_ORDER) {
315
341
  const adapter = adapterRegistry.getAdapter(candidate);
316
342
  // eslint-disable-next-line no-await-in-loop
317
343
  if (adapter && await adapter.detect()) { adapterName = candidate; break; }
344
+ missing.push(candidate);
318
345
  }
319
346
  if (!adapterName) {
320
- throw new Error(
347
+ const err = new Error(
321
348
  `No supported agent CLI found on PATH (looked for: ${BOOTSTRAP_ADAPTER_DETECT_ORDER.join(', ')}). `
322
349
  + 'Install one, or pass --adapter <name>.',
323
350
  );
351
+ err.code = NO_AGENT_CLI_CODE;
352
+ throw err;
353
+ }
354
+ // The page's command names the person's own CLI; running a different one
355
+ // without saying so is how a Claude Code user ended up with a Codex agent.
356
+ if (missing.length > 0) {
357
+ log(`${missing.join(', ')} not found on PATH, so this agent runs with ${adapterName}. `
358
+ + 'To choose, pass --adapter <name>.');
324
359
  }
325
360
  }
326
361
 
@@ -348,7 +383,9 @@ export const bootstrapAgentRecordFromEnv = async ({
348
383
  instanceUrl,
349
384
  runtimeToken,
350
385
  adapter: adapterName,
351
- environment: buildDefaultEnvironment(adapterName),
386
+ // The daemon's baseline for a seat nobody wrote a spec for, sandbox
387
+ // included: this record is derived from nothing the person declared.
388
+ environment: seatBaseline(buildDefaultEnvironment(adapterName), adapterName, { sandbox: true }),
352
389
  workspacePath: null,
353
390
  };
354
391
  };
@@ -1112,11 +1149,18 @@ export const performRun = ({
1112
1149
  spawnCredentialLeaseFactory = createSpawnCredentialLease,
1113
1150
  revokeOrphansImpl = revokeOrphanedSpawnCredentials,
1114
1151
  sleepImpl = (ms) => new Promise((resolve) => { setTimeout(resolve, ms); }),
1152
+ // The agent to @mention when the model provider refuses a request's content
1153
+ // (lib/content-refusal.js). Null: the refusal notice names no one.
1154
+ refusalHandoff = null,
1115
1155
  }) => {
1116
1156
  if (environment?.provider !== undefined && !adapter?.supportsProvider) {
1117
1157
  throw new Error('environment.provider requires a provider-capable adapter');
1118
1158
  }
1119
1159
  const client = createClient({ instance: instanceUrl, token });
1160
+ const handoffAgent = sanitizeHandoffAgent(refusalHandoff);
1161
+ if (refusalHandoff && !handoffAgent) {
1162
+ log(`--refusal-handoff ignored: '${String(refusalHandoff).slice(0, 64)}' is not an agent handle`);
1163
+ }
1120
1164
 
1121
1165
  // THE BOOT SWEEP IS THE SECOND NET, AND IT HAPPENS ONCE PER PROCESS. A seat
1122
1166
  // that dies mid-turn (kill, crash, reboot) leaves its child credential live
@@ -1908,6 +1952,53 @@ export const performRun = ({
1908
1952
  // claim is not discarded: it remains in the model's context with the same
1909
1953
  // peer frame the single-event path already uses, but is explicitly read-only.
1910
1954
  // Advisory losses retain their existing peer-aware behaviour.
1955
+ // A refused item is acked, never retried (lib/content-refusal.js). Every one
1956
+ // is logged by event id alone. One addressed to this seat also gets a pod
1957
+ // notice the WRAPPER writes, since the model never read it: identifiers
1958
+ // only, and the hand-off agent @mentioned outside a DM. A refused broadcast
1959
+ // gets no notice: its claim releases as `upstream-refused`, and the kernel
1960
+ // hands a human's message to another listener. A notice that fails to post
1961
+ // is logged; the ack still happens, because retrying would only re-send the
1962
+ // refused content.
1963
+ const postRefusalNotice = async (refusedEntries, eventPodId) => {
1964
+ for (const entry of refusedEntries) {
1965
+ log(`[${entry.event.type}] the model provider refused the content of event ${entry.event._id} (content_refused) — acked as refused, not retried`);
1966
+ }
1967
+ const addressed = refusedEntries.filter((entry) => ADDRESSED_EVENT_TYPES.has(entry.event.type));
1968
+ if (addressed.length === 0) return;
1969
+ const mention = Boolean(handoffAgent) && !addressed.some((entry) => entry.event.type === 'dm.message');
1970
+ const text = composeRefusalHandoff({
1971
+ items: addressed.map((entry) => refusedItemRef(entry.event)),
1972
+ handoff: handoffAgent,
1973
+ mention,
1974
+ });
1975
+ let posted = false;
1976
+ try {
1977
+ const delivery = await deliverChatReply({
1978
+ client,
1979
+ podId: eventPodId,
1980
+ text,
1981
+ limit: chatCharLimit,
1982
+ maxChunks: maxChatChunks,
1983
+ uploadName: `${agentName}-refusal-${addressed[0].event._id}.md`,
1984
+ log: (line) => log(`[inbox.batch] ${line}`),
1985
+ });
1986
+ posted = !delivery.skipped && !delivery.refused;
1987
+ log(posted
1988
+ ? `[inbox.batch] refusal notice posted${mention ? `, handed off to @${handoffAgent}` : ''}`
1989
+ : `[inbox.batch] refusal notice not delivered (${delivery.reason})`);
1990
+ } catch (err) {
1991
+ log(`[inbox.batch] refusal notice failed: ${err.message}`);
1992
+ }
1993
+ for (const entry of addressed) {
1994
+ entry.result.details = {
1995
+ ...entry.result.details,
1996
+ handoff: mention ? handoffAgent : null,
1997
+ noticePosted: posted,
1998
+ };
1999
+ }
2000
+ };
2001
+
1911
2002
  const processEventBatch = async (events, inboxCount = events.length) => {
1912
2003
  const eventPodId = events[0]?.podId || podId;
1913
2004
  if (!eventPodId || events.some((event) => (event.podId || podId) !== eventPodId)) {
@@ -2059,19 +2150,76 @@ export const performRun = ({
2059
2150
  hasHeartbeat: entries.some((entry) => entry.event.type === 'heartbeat'),
2060
2151
  },
2061
2152
  };
2062
- let turnResult;
2063
- try {
2064
- turnResult = await runTurn({
2065
- event: batchEvent,
2153
+ // One item, run as its own turn. Used only after the provider refused a
2154
+ // batch's content: a composite turn cannot say WHICH item was refused, and
2155
+ // refusing them all would swallow the ordinary items with the flagged one.
2156
+ const isolatedTurn = async (entry) => {
2157
+ const before = await snapshotMessages();
2158
+ return runTurn({
2159
+ event: {
2160
+ ...entry.event,
2161
+ _id: `batch-${entry.event._id}`,
2162
+ type: 'inbox.batch',
2163
+ payload: {
2164
+ ...entry.event.payload,
2165
+ batchEventIds: [String(entry.event._id)],
2166
+ hasHeartbeat: entry.event.type === 'heartbeat',
2167
+ },
2168
+ },
2066
2169
  eventPodId,
2067
- prompt: buildInboxPrompt(entries, inboxCount),
2068
- preSpawnIds,
2170
+ prompt: buildInboxPrompt([entry], 1),
2171
+ preSpawnIds: before ? new Set(before.map((message) => String(message._id || message.id))) : null,
2069
2172
  snapshotMessages,
2070
- claimKeeper: compositeClaimKeeper,
2173
+ claimKeeper: entry.claimKeeper,
2071
2174
  trigger,
2072
2175
  });
2073
- for (const entry of actionEntries) entry.result = turnResult;
2074
- return { entries };
2176
+ };
2177
+
2178
+ let turnResult;
2179
+ let deferredError = null;
2180
+ try {
2181
+ try {
2182
+ turnResult = await runTurn({
2183
+ event: batchEvent,
2184
+ eventPodId,
2185
+ prompt: buildInboxPrompt(entries, inboxCount),
2186
+ preSpawnIds,
2187
+ snapshotMessages,
2188
+ claimKeeper: compositeClaimKeeper,
2189
+ trigger,
2190
+ });
2191
+ for (const entry of actionEntries) entry.result = turnResult;
2192
+ } catch (err) {
2193
+ if (!isContentRefusal(err)) throw err;
2194
+ if (actionEntries.length === 1) {
2195
+ actionEntries[0].result = contentRefusedResult();
2196
+ } else {
2197
+ log(
2198
+ `[inbox.batch] the model provider refused this batch's content (content_refused); `
2199
+ + `running its ${actionEntries.length} items one at a time so only a refused item is refused`,
2200
+ );
2201
+ for (const entry of actionEntries) {
2202
+ if (!running) break;
2203
+ try {
2204
+ // eslint-disable-next-line no-await-in-loop
2205
+ entry.result = await isolatedTurn(entry);
2206
+ } catch (itemErr) {
2207
+ // Any other failure stops here and leaves this item and the rest
2208
+ // unacked for redelivery; the tick applies the retry policy.
2209
+ if (!isContentRefusal(itemErr)) {
2210
+ deferredError = itemErr;
2211
+ break;
2212
+ }
2213
+ entry.result = contentRefusedResult();
2214
+ }
2215
+ }
2216
+ }
2217
+ await postRefusalNotice(
2218
+ actionEntries.filter((entry) => entry.result?.reason === CONTENT_REFUSED_REASON),
2219
+ eventPodId,
2220
+ );
2221
+ }
2222
+ return deferredError ? { entries, deferredError } : { entries };
2075
2223
  } finally {
2076
2224
  await Promise.all(actionEntries
2077
2225
  .filter((entry) => entry.claimKeeper)
@@ -2080,8 +2228,9 @@ export const performRun = ({
2080
2228
  // broadcast may be handed to one remaining listener, a refusal
2081
2229
  // closes with its reason, and every other completed batch item
2082
2230
  // closes normally. Same decision point as the single-event path.
2083
- // Same decision point as the single-event path.
2084
- const release = claimReleaseFor(entry.event, turnResult);
2231
+ // An item left without a result (a failure during isolation)
2232
+ // releases with no outcome, for redelivery, as a thrown turn does.
2233
+ const release = claimReleaseFor(entry.event, entry.result || turnResult);
2085
2234
  await entry.claimKeeper.release(release.outcome, {
2086
2235
  reason: release.reason, status: release.status,
2087
2236
  });
@@ -2120,10 +2269,9 @@ export const performRun = ({
2120
2269
  for (const group of eventGroups.values()) {
2121
2270
  if (!running) break;
2122
2271
  if ((group[0].podId || podId) && !PRIVATE_RESPONSE_EVENT_TYPES.has(group[0].type)) {
2123
- let batch;
2124
- try {
2125
- batch = await processEventBatch(group, inboxCount);
2126
- } catch (err) {
2272
+ // One failure report for a batch whose items stay unacked, whether
2273
+ // the composite turn threw or an isolated item did after a refusal.
2274
+ const scheduleBatchRetry = (err, unackedCount) => {
2127
2275
  consecutiveSpawnFailures += 1;
2128
2276
  const retry = spawnRetryPolicy({
2129
2277
  error: err,
@@ -2135,7 +2283,7 @@ export const performRun = ({
2135
2283
  const event = group[0];
2136
2284
  const wrapped = new Error(
2137
2285
  `inbox batch processing failed (${retry.failureClass}; ${consecutiveSpawnFailures} consecutive) `
2138
- + `— ${group.length} events remain unacked; ${retry.circuitOpen ? 'circuit open' : 'retry scheduled'}, `
2286
+ + `— ${unackedCount} events remain unacked; ${retry.circuitOpen ? 'circuit open' : 'retry scheduled'}, `
2139
2287
  + `next probe in ${formatRetryDelay(retry.delayMs)}: ${err.message}`,
2140
2288
  { cause: err },
2141
2289
  );
@@ -2159,6 +2307,12 @@ export const performRun = ({
2159
2307
  });
2160
2308
  if (onError) onError(wrapped);
2161
2309
  else log(`[inbox.batch] ${wrapped.message}`);
2310
+ };
2311
+ let batch;
2312
+ try {
2313
+ batch = await processEventBatch(group, inboxCount);
2314
+ } catch (err) {
2315
+ scheduleBatchRetry(err, group.length);
2162
2316
  break;
2163
2317
  }
2164
2318
  const batchSpawned = batch.entries.some((entry) => (
@@ -2168,6 +2322,9 @@ export const performRun = ({
2168
2322
  if (batchSpawned) consecutiveSpawnFailures = 0;
2169
2323
  for (const entry of batch.entries) {
2170
2324
  const event = entry.event;
2325
+ // No result: an item a failure during refusal isolation never
2326
+ // reached. Unacked, the kernel redelivers it.
2327
+ if (!entry.result) continue;
2171
2328
  if (entry.result?.reason !== 'duplicate-delivery') {
2172
2329
  recordHandledEvent(agentName, event._id);
2173
2330
  }
@@ -2187,6 +2344,10 @@ export const performRun = ({
2187
2344
  onError?.(new Error(`Ack failed for ${event._id}: ${ackErr.message}`));
2188
2345
  }
2189
2346
  }
2347
+ if (batch.deferredError) {
2348
+ scheduleBatchRetry(batch.deferredError, batch.entries.filter((entry) => !entry.result).length);
2349
+ break;
2350
+ }
2190
2351
  continue;
2191
2352
  }
2192
2353
  const [event] = group;
@@ -2199,65 +2360,72 @@ export const performRun = ({
2199
2360
  try {
2200
2361
  result = await processEvent(event);
2201
2362
  } catch (err) {
2202
- // Do not record or ack: the kernel must retain the event for
2203
- // at-least-once delivery. Stop this fetched batch immediately —
2204
- // continuing could launch every one of the 10 returned events
2205
- // into the same provider outage before the next poll (#782).
2206
- consecutiveSpawnFailures += 1;
2207
- const retry = spawnRetryPolicy({
2208
- error: err,
2209
- consecutiveFailures: consecutiveSpawnFailures,
2210
- intervalMs,
2211
- jitterRatio: spawnJitterRatio,
2212
- });
2213
- nextPollDelayMs = retry.delayMs;
2214
- const retryIn = formatRetryDelay(retry.delayMs);
2215
- const state = retry.circuitOpen ? 'circuit open' : 'retry scheduled';
2216
- const wrapped = new Error(
2217
- `${event.type} processing failed (${retry.failureClass}; `
2218
- + `${consecutiveSpawnFailures} consecutive) — event ${event._id} remains unacked; `
2219
- + `${state}, next probe in ${retryIn}: ${err.message}`,
2220
- { cause: err },
2221
- );
2222
- Object.assign(wrapped, {
2223
- code: 'agent_spawn_retry_scheduled',
2224
- failureClass: retry.failureClass,
2225
- consecutiveFailures: consecutiveSpawnFailures,
2226
- retryAfterMs: retry.delayMs,
2227
- circuitOpen: retry.circuitOpen,
2228
- eventId: event._id,
2229
- ...(isPodFocusDiagnostic(err) ? {
2230
- focusDiagnostic: {
2231
- errorCode: err.code,
2232
- eventIds: err.eventId || event._id,
2233
- podId: err.podId || event.podId || podId || null,
2234
- focusRevision: err.focusRevision ?? null,
2235
- measuredCodePoints: err.measuredCodePoints ?? null,
2236
- allowedCodePoints: err.allowedCodePoints ?? FOCUS_FRAME_MAX_CODE_POINTS,
2237
- },
2238
- } : {}),
2239
- });
2240
- // ONE emission, not two. `wrapped.message` already opens with the
2241
- // event type, so the log copy added a second prefix and a second
2242
- // line of identical text into the same merged stream — enough that
2243
- // `grep -c 'session limit'` returned 8 for 4 failures, and a reader
2244
- // counting hits per event id saw 2 and inferred two deliveries.
2245
- // On 2026-08-18 that count pointed at the wrong cause for #993:
2246
- // two deliveries per event puts `attempts` at 2 and the requeue cap
2247
- // one step away. It did not decide anything — the cap was ruled out
2248
- // from the DB, where a capped event would have left a `failed` row
2249
- // and none existed — but it corroborated the wrong theory, and the
2250
- // doubling had to be spotted by hand before the count could be
2251
- // discounted. A log that inflates is worse than one that is silent,
2252
- // because it argues.
2253
- //
2254
- // Routed to the error channel when a caller provides one, and to
2255
- // the log when it doesn't, so neither contract loses the failure:
2256
- // an embedder that passes no `onError` still sees it, and `agent
2257
- // run` — which always passes one — stops printing it twice.
2258
- if (onError) onError(wrapped);
2259
- else log(`[${event.type}] ${wrapped.message}`);
2260
- break;
2363
+ if (isContentRefusal(err)) {
2364
+ // A refused private item is acked without a pod notice: it has no
2365
+ // pod to post into, and its sender's ask expires on its own.
2366
+ result = contentRefusedResult();
2367
+ log(`[${event.type}] the model provider refused the content of event ${event._id} (content_refused) — acked as refused, not retried`);
2368
+ } else {
2369
+ // Do not record or ack: the kernel must retain the event for
2370
+ // at-least-once delivery. Stop this fetched batch immediately —
2371
+ // continuing could launch every one of the 10 returned events
2372
+ // into the same provider outage before the next poll (#782).
2373
+ consecutiveSpawnFailures += 1;
2374
+ const retry = spawnRetryPolicy({
2375
+ error: err,
2376
+ consecutiveFailures: consecutiveSpawnFailures,
2377
+ intervalMs,
2378
+ jitterRatio: spawnJitterRatio,
2379
+ });
2380
+ nextPollDelayMs = retry.delayMs;
2381
+ const retryIn = formatRetryDelay(retry.delayMs);
2382
+ const state = retry.circuitOpen ? 'circuit open' : 'retry scheduled';
2383
+ const wrapped = new Error(
2384
+ `${event.type} processing failed (${retry.failureClass}; `
2385
+ + `${consecutiveSpawnFailures} consecutive) — event ${event._id} remains unacked; `
2386
+ + `${state}, next probe in ${retryIn}: ${err.message}`,
2387
+ { cause: err },
2388
+ );
2389
+ Object.assign(wrapped, {
2390
+ code: 'agent_spawn_retry_scheduled',
2391
+ failureClass: retry.failureClass,
2392
+ consecutiveFailures: consecutiveSpawnFailures,
2393
+ retryAfterMs: retry.delayMs,
2394
+ circuitOpen: retry.circuitOpen,
2395
+ eventId: event._id,
2396
+ ...(isPodFocusDiagnostic(err) ? {
2397
+ focusDiagnostic: {
2398
+ errorCode: err.code,
2399
+ eventIds: err.eventId || event._id,
2400
+ podId: err.podId || event.podId || podId || null,
2401
+ focusRevision: err.focusRevision ?? null,
2402
+ measuredCodePoints: err.measuredCodePoints ?? null,
2403
+ allowedCodePoints: err.allowedCodePoints ?? FOCUS_FRAME_MAX_CODE_POINTS,
2404
+ },
2405
+ } : {}),
2406
+ });
2407
+ // ONE emission, not two. `wrapped.message` already opens with the
2408
+ // event type, so the log copy added a second prefix and a second
2409
+ // line of identical text into the same merged stream — enough that
2410
+ // `grep -c 'session limit'` returned 8 for 4 failures, and a reader
2411
+ // counting hits per event id saw 2 and inferred two deliveries.
2412
+ // On 2026-08-18 that count pointed at the wrong cause for #993:
2413
+ // two deliveries per event puts `attempts` at 2 and the requeue cap
2414
+ // one step away. It did not decide anything — the cap was ruled out
2415
+ // from the DB, where a capped event would have left a `failed` row
2416
+ // and none existed — but it corroborated the wrong theory, and the
2417
+ // doubling had to be spotted by hand before the count could be
2418
+ // discounted. A log that inflates is worse than one that is silent,
2419
+ // because it argues.
2420
+ //
2421
+ // Routed to the error channel when a caller provides one, and to
2422
+ // the log when it doesn't, so neither contract loses the failure:
2423
+ // an embedder that passes no `onError` still sees it, and `agent
2424
+ // run` — which always passes one — stops printing it twice.
2425
+ if (onError) onError(wrapped);
2426
+ else log(`[${event.type}] ${wrapped.message}`);
2427
+ break;
2428
+ }
2261
2429
  }
2262
2430
  // Only a completed model turn proves the local runtime and delivery
2263
2431
  // path recovered. A malformed/no-destination event is still acked,
@@ -2904,8 +3072,10 @@ Docs:
2904
3072
  .option('--cascade-cap <n>', `Consecutive agent-triggered turns allowed per pod (env ${CASCADE_ENV_VARS.cap}, default ${CASCADE_DEFAULTS.cap})`)
2905
3073
  .option('--cascade-grace <n>', `Extra turns allowed when this seat was directly addressed; 0 disables the grace (env ${CASCADE_ENV_VARS.addressedGrace}, default ${CASCADE_DEFAULTS.addressedGrace})`)
2906
3074
  .option('--cascade-reset <ms>', `Silence window that clears the streak (env ${CASCADE_ENV_VARS.resetMs}, default ${CASCADE_DEFAULTS.resetMs})`)
3075
+ .option('--refusal-handoff <agent>', 'Agent to @mention when the model provider refuses a request\'s content; the request is acked as refused, never retried')
2907
3076
  .action(async (name, opts) => {
2908
3077
  let record = loadAgentToken(name);
3078
+ let bootstrapped = false;
2909
3079
  if (!record) {
2910
3080
  // First run on this machine: the BYO connect page hands out env vars,
2911
3081
  // not a token file — bootstrap the record from them (#913).
@@ -2917,12 +3087,14 @@ Docs:
2917
3087
  });
2918
3088
  } catch (err) {
2919
3089
  console.error(`${stamp()} [${name}] ${err.message}`);
3090
+ // A Claude Code installed with npm is a .cmd shim Node cannot spawn,
3091
+ // so on Windows this is usually "installed but not runnable here".
3092
+ if (err.code === NO_AGENT_CLI_CODE && process.platform === 'win32') {
3093
+ console.error(windowsSandboxMessage('claude'));
3094
+ }
2920
3095
  process.exit(1);
2921
3096
  }
2922
- if (record) {
2923
- saveAgentToken(record.agentName, record);
2924
- console.log(`${stamp()} [${name}] bootstrapped ${tokenFile(record.agentName)} from COMMONLY_AGENT_TOKEN (adapter: ${record.adapter})`);
2925
- } else {
3097
+ if (!record) {
2926
3098
  console.error(
2927
3099
  `No token for '${name}'. Either export COMMONLY_API_URL + COMMONLY_AGENT_TOKEN`
2928
3100
  + ` (shown on the Connect your own agent page) and re-run, or:`
@@ -2930,6 +3102,24 @@ Docs:
2930
3102
  );
2931
3103
  process.exit(1);
2932
3104
  }
3105
+ bootstrapped = true;
3106
+ }
3107
+
3108
+ // Every turn of a seat this host cannot confine would fail, so say so
3109
+ // once, before a token file is written or a poll is made.
3110
+ const hostRefusal = hostSandboxRefusal({ environment: record.environment, adapterName: record.adapter });
3111
+ if (hostRefusal) {
3112
+ console.error(`${stamp()} [${name}] ${hostRefusal}`);
3113
+ process.exit(1);
3114
+ }
3115
+ if (bootstrapped) {
3116
+ saveAgentToken(record.agentName, record);
3117
+ console.log(`${stamp()} [${name}] bootstrapped ${tokenFile(record.agentName)} from COMMONLY_AGENT_TOKEN (adapter: ${record.adapter})`);
3118
+ } else if (savedSeatLacksDefaultSandbox(record)) {
3119
+ console.warn(
3120
+ `${stamp()} [${name}] this agent's saved settings predate the default sandbox. To pick it up, reconnect: `
3121
+ + `commonly agent detach ${name} --force, then run a fresh command from the Connect page.`,
3122
+ );
2933
3123
  }
2934
3124
 
2935
3125
  const adapterRequest = checkRunAdapterRequest({
@@ -2977,6 +3167,11 @@ Docs:
2977
3167
  // Unstamped, it took `ps -o lstart` to establish when nine seats came
2978
3168
  // back on 2026-08-18, and that only worked because the processes were
2979
3169
  // still alive — after the next restart that route is gone too.
3170
+ await prepareMcpBeforeFirstPoll({
3171
+ environment: record.environment,
3172
+ log: (line) => console.log(`${stamp()} [${name}] ${line}`),
3173
+ });
3174
+
2980
3175
  console.log(`${stamp()} [${name}] polling ${record.instanceUrl} for events (ctrl+c to stop)`);
2981
3176
  console.log(`${stamp()} [${name}] foreground mode; to background and keep it across logins, run: commonly daemon install`);
2982
3177
 
@@ -2996,6 +3191,7 @@ Docs:
2996
3191
  // server's published default, which is the only lifetime we can justify
2997
3192
  // without an operator saying otherwise.
2998
3193
  spawnCredentialTtlSeconds: resolveSpawnTtlSeconds(process.env),
3194
+ refusalHandoff: opts.refusalHandoff || null,
2999
3195
  log: (line) => console.log(`${stamp()} [${name}] ${line}`),
3000
3196
  // Both sinks are stamped, and both must be — but not for the reason
3001
3197
  // this comment gave until now, which its own PR falsified.
@@ -0,0 +1,89 @@
1
+ /**
2
+ * A model provider that refuses a request's CONTENT (2026-10-16).
3
+ *
4
+ * A security-gate seat on codex was asked to review a PR whose request carried
5
+ * SSRF, exfiltration and ReDoS test cases. The provider refused every turn
6
+ * ("flagged for possible cybersecurity risk"). The run loop classed that as a
7
+ * transient runtime failure, so it never acked and re-sent the same content on
8
+ * backoff, five refusals in 52 minutes on a login every codex seat shares. The
9
+ * seat handled nothing else until the kernel's requeue cap retired the event.
10
+ *
11
+ * A content refusal is deterministic: the same content is refused again. So it
12
+ * is acked once, as refused, and never retried. A refused request addressed to
13
+ * the seat is not dropped silently either: the wrapper, not the model, posts one
14
+ * line naming the request (PR, head, message id, sender) and, when the seat is
15
+ * run with `--refusal-handoff <agent>`, @mentions that agent to take it. The
16
+ * line repeats nothing else from the request: the flagged text stays out of
17
+ * the pod.
18
+ */
19
+ import { classifySpawnFailure, SPAWN_FAILURE_CLASS } from './spawn-retry.js';
20
+
21
+ /** The ack reason, so the event ledger counts refusals by name. */
22
+ export const CONTENT_REFUSED_REASON = 'provider-refused';
23
+
24
+ export const isContentRefusal = (error) => (
25
+ classifySpawnFailure(error) === SPAWN_FAILURE_CLASS.CONTENT_REFUSED
26
+ );
27
+
28
+ /**
29
+ * The turn result for a refused item. `refused` releases its claim as
30
+ * `upstream-refused` (claim-outcome.js): on a human broadcast the kernel hands
31
+ * the message to one remaining listener, as it does for any upstream refusal.
32
+ * `outcome: 'error'` is terminal on the kernel side; the event is acked, not
33
+ * requeued.
34
+ */
35
+ export const contentRefusedResult = () => ({
36
+ outcome: 'error',
37
+ refused: { reason: 'upstream-refused' },
38
+ reason: CONTENT_REFUSED_REASON,
39
+ details: { failureClass: SPAWN_FAILURE_CLASS.CONTENT_REFUSED },
40
+ });
41
+
42
+ // A full 40-hex commit id. Shorter hex runs are not taken: the server's pod
43
+ // context frame carries 24-hex pod ids, and a short match would name one as
44
+ // the head.
45
+ const FULL_SHA_RE = /\b[0-9a-f]{40}\b/g;
46
+ const PR_REF_RE = /#\d{2,6}\b/;
47
+ const MAX_HEADS = 3;
48
+
49
+ /** An agent handle as the server resolves mentions; anything else is dropped. */
50
+ export const sanitizeHandoffAgent = (value) => {
51
+ const name = String(value ?? '').trim().replace(/^@/, '');
52
+ return /^[a-z0-9][a-z0-9._-]{0,63}$/i.test(name) ? name : null;
53
+ };
54
+
55
+ /**
56
+ * What the notice may name about a refused request: identifiers only. The PR is
57
+ * the first `#N`; the heads are every distinct full commit id (a request that
58
+ * names two is reported with both, rather than guessing which one is current).
59
+ */
60
+ export const refusedItemRef = (event) => {
61
+ const payload = event?.payload || {};
62
+ const content = String(payload.content || '');
63
+ const pr = content.match(PR_REF_RE)?.[0] || null;
64
+ const heads = [...new Set(content.match(FULL_SHA_RE) || [])].slice(0, MAX_HEADS);
65
+ const rawMessageId = String(payload.messageId ?? '');
66
+ const messageId = /^[A-Za-z0-9]{1,40}$/.test(rawMessageId) ? rawMessageId : null;
67
+ const from = String(payload.username || '').replace(/[^A-Za-z0-9._-]/g, '').slice(0, 40) || null;
68
+ return { pr, heads, messageId, from };
69
+ };
70
+
71
+ const describeItem = ({ pr, heads, messageId, from }) => {
72
+ const subject = pr ? `${pr}${heads.length ? ` at ${heads.map((head) => `\`${head}\``).join(' or ')}` : ' (no head named)'}` : 'a request';
73
+ const source = [messageId ? `message ${messageId}` : null, from ? `from ${from}` : null]
74
+ .filter(Boolean).join(' ');
75
+ return source ? `${subject} (${source})` : subject;
76
+ };
77
+
78
+ /**
79
+ * The one line the wrapper posts. `mention` is false in a DM, where @mentioning
80
+ * a third agent would pull it toward a 1:1 conversation it cannot join.
81
+ */
82
+ export const composeRefusalHandoff = ({ items, handoff = null, mention = true }) => {
83
+ const agent = sanitizeHandoffAgent(handoff);
84
+ const one = items.length === 1;
85
+ const what = one ? describeItem(items[0]) : `${items.length} requests: ${items.map(describeItem).join('; ')}`;
86
+ const lead = `The model provider refused the content of ${what}, so I could not read ${one ? 'it' : 'them'} and will not retry ${one ? 'it' : 'them'}.`;
87
+ if (agent && mention) return `${lead} @${agent}, please take ${one ? 'it' : 'them'}.`;
88
+ return `${lead} ${one ? 'It needs' : 'They need'} another reader.`;
89
+ };
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Prepare the commonly MCP build before a public seat's first poll.
3
+ *
4
+ * A public seat runs its MCP server only from a host-prepared build (TASK-273),
5
+ * and the first spawn on an empty home only STARTS preparing one, then refuses
6
+ * its turn. On a fresh machine that refused turn was the person's first
7
+ * @mention, and it waited out the kernel's requeue, about ten minutes (BYO
8
+ * walk, 2026-10-16). `agent run` prepares the build once, before it polls.
9
+ */
10
+
11
+ import { normalizeSandboxTrust } from './environment.js';
12
+ import { COMMONLY_MCP_SERVER_NAME } from './default-environment.js';
13
+ import { WARM_RESULTS, planMcpSpawn, resolveHomeDir } from './mcp-home.js';
14
+ import { warmMcpHome } from './mcp-warm-child.mjs';
15
+
16
+ /** The warm's result when it ran, or null when this seat needed none. */
17
+ export const prepareMcpBeforeFirstPoll = async ({
18
+ environment,
19
+ home,
20
+ plan = planMcpSpawn,
21
+ warm = warmMcpHome,
22
+ log = () => {},
23
+ } = {}) => {
24
+ if (normalizeSandboxTrust(environment?.sandbox)?.trust !== 'public') return null;
25
+ const server = Array.isArray(environment?.mcp)
26
+ ? environment.mcp.find((entry) => entry?.name === COMMONLY_MCP_SERVER_NAME)
27
+ : null;
28
+ if (!Array.isArray(server?.command)) return null;
29
+ if (plan(server.command, { home }).reason !== 'home-empty') return null;
30
+
31
+ log("preparing Commonly's tools on this machine (first run only)...");
32
+ const result = await warm(resolveHomeDir(home), { now: Date.now() });
33
+ if (result === WARM_RESULTS.ADVANCED || result === WARM_RESULTS.CURRENT) {
34
+ log("Commonly's tools are ready");
35
+ } else {
36
+ log(`could not prepare Commonly's tools yet (${result}); the first turn will try again`);
37
+ }
38
+ return result;
39
+ };
40
+
41
+ export default { prepareMcpBeforeFirstPoll };
@@ -31,7 +31,10 @@ const expandHome = (p) => {
31
31
  return p;
32
32
  };
33
33
 
34
- const MACOS_MESSAGE = 'bwrap is Linux-only; use sandbox.mode: none in Phase 1 or wait for sandbox-exec adapter';
34
+ // Never advise `sandbox.mode: none` here: a public seat refuses it, and the
35
+ // mechanisms that do exist are named instead.
36
+ const MACOS_MESSAGE = 'bwrap is Linux-only. On macOS a public seat runs under Seatbelt '
37
+ + '(sandbox.mode workspace or read-only); Windows has no supported sandbox yet, so use WSL 2.';
35
38
 
36
39
  const DEFAULT_RO_BINDS = [
37
40
  '/etc/ssl/certs',
@@ -53,7 +56,8 @@ export const detectBwrap = () => {
53
56
  if (res.error || res.status !== 0) {
54
57
  return {
55
58
  available: false,
56
- error: 'bwrap not found on PATH. Install bubblewrap: `apt install bubblewrap` (Debian/Ubuntu) or `dnf install bubblewrap` (Fedora).',
59
+ error: 'bwrap not found on PATH. Install bubblewrap: `sudo apt install bubblewrap` (Debian/Ubuntu, WSL), '
60
+ + '`sudo dnf install bubblewrap` (Fedora) or `sudo pacman -S bubblewrap` (Arch).',
57
61
  };
58
62
  }
59
63
  return { available: true, path: 'bwrap' };
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Can THIS host confine the seat it is about to run? Asked once, before the
3
+ * first poll.
4
+ *
5
+ * A public seat's sandbox is resolved per host (mode.js): Seatbelt on macOS,
6
+ * bubblewrap elsewhere. `agent attach --env` checks that mechanism up front;
7
+ * `agent run` did not, so a public seat on a host without it (native Windows,
8
+ * or Linux without bubblewrap) would start, poll, and fail every turn while
9
+ * the pod saw nothing.
10
+ *
11
+ * Only the adapters that run inside these mechanisms are checked. Codex
12
+ * confines with its own permission profiles (mode.js), and pi refuses a
13
+ * declared sandbox itself (default-environment.js).
14
+ */
15
+
16
+ import { normalizeSandboxTrust } from '../environment.js';
17
+ import { resolvePublicSandboxMode } from './mode.js';
18
+ import { detectBwrap as defaultDetectBwrap } from './bwrap.js';
19
+ import { detectSeatbelt as defaultDetectSeatbelt } from './seatbelt.js';
20
+
21
+ const SEATBELT_MODES = new Set(['workspace', 'read-only']);
22
+
23
+ const ADAPTER_LABELS = { claude: 'Claude Code', opencode: 'OpenCode', qwen: 'Qwen Code' };
24
+
25
+ const HOSTED_LINE = ' - A hosted agent: choose "Run it here" on the Connect page. Nothing runs on this machine.';
26
+
27
+ /** What a person on native Windows can do instead. */
28
+ export const windowsSandboxMessage = (adapterName) => {
29
+ const label = ADAPTER_LABELS[adapterName] || adapterName;
30
+ // WSL is offered only where the Linux sandbox can run the CLI: not Claude
31
+ // Code (see linuxClaudeMessage).
32
+ return [
33
+ `Commonly runs a connected ${label} inside a sandbox, and has no sandbox for Windows yet,`,
34
+ 'so this agent cannot listen for @mentions from native Windows. Instead:',
35
+ ...(adapterName === 'claude'
36
+ ? [' - Use Commonly from your own Claude Code sessions: the Connect page shows a PowerShell `claude mcp add` command.']
37
+ : [` - WSL 2 (Ubuntu): install Node and ${label} inside WSL, run \`sudo apt install bubblewrap\`,`
38
+ + ' then run these same commands there.']),
39
+ HOSTED_LINE,
40
+ ].join('\n');
41
+ };
42
+
43
+ /**
44
+ * Claude Code on Linux (WSL included). The bubblewrap namespace binds the
45
+ * system binary folders only, and Claude Code installs under the person's
46
+ * home or /usr/local, so a confined spawn could not even start it; its login
47
+ * and settings live under that home too (Ubuntu run, 2026-10-16). Until the
48
+ * namespace carries what Claude needs, the seat stops here with its options.
49
+ */
50
+ export const linuxClaudeMessage = () => [
51
+ 'Commonly runs a connected Claude Code inside a sandbox, and on Linux (WSL included) that sandbox',
52
+ 'cannot run Claude Code yet, so this agent cannot listen for @mentions here. Instead:',
53
+ ' - Use Commonly from your own Claude Code sessions: the Connect page shows a `claude mcp add` command.',
54
+ HOSTED_LINE,
55
+ ].join('\n');
56
+
57
+ /** Why this host cannot confine the seat, or null when it can (or the seat declares no sandbox). */
58
+ export const hostSandboxRefusal = ({
59
+ environment,
60
+ adapterName,
61
+ platform = process.platform,
62
+ detectBwrap = defaultDetectBwrap,
63
+ detectSeatbelt = defaultDetectSeatbelt,
64
+ } = {}) => {
65
+ if (!Object.prototype.hasOwnProperty.call(ADAPTER_LABELS, adapterName)) return null;
66
+ const sandbox = normalizeSandboxTrust(environment?.sandbox);
67
+ if (!sandbox || typeof sandbox !== 'object') return null;
68
+ const mode = sandbox.mode ?? (sandbox.trust === 'public' ? resolvePublicSandboxMode(sandbox, platform) : undefined);
69
+ if (mode !== 'bwrap' && !SEATBELT_MODES.has(mode)) return null;
70
+
71
+ if (platform === 'win32') return windowsSandboxMessage(adapterName);
72
+ if (mode === 'bwrap' && adapterName === 'claude') return linuxClaudeMessage();
73
+ if (mode === 'bwrap') {
74
+ const bwrap = detectBwrap();
75
+ return bwrap.available ? null : `This seat runs in a bubblewrap sandbox, which is not available here. ${bwrap.error}`;
76
+ }
77
+ const seatbelt = detectSeatbelt();
78
+ return seatbelt.available
79
+ ? null
80
+ : `This seat runs in a macOS Seatbelt sandbox (sandbox.mode=${mode}), which is not available here. ${seatbelt.error}`;
81
+ };
82
+
83
+ export default { hostSandboxRefusal, linuxClaudeMessage, windowsSandboxMessage };
@@ -8,6 +8,10 @@
8
8
  */
9
9
 
10
10
  export const SPAWN_FAILURE_CLASS = Object.freeze({
11
+ // The provider refused the request's CONTENT. Re-sending the same content
12
+ // can only be refused again, so this class is never retried: the run loop
13
+ // acks the event as refused instead (lib/content-refusal.js).
14
+ CONTENT_REFUSED: 'content_refused',
11
15
  QUOTA: 'quota',
12
16
  RATE_LIMIT: 'rate_limit',
13
17
  CONFIGURATION: 'configuration',
@@ -49,6 +53,15 @@ export const SPAWN_RETRY_JITTER_MAX_RATIO = 0.2;
49
53
  // Deliberately NOT loosened to a bare `limit`: QUOTA is tested before
50
54
  // RATE_LIMIT, so that would swallow every "rate limit" error into the 15-minute
51
55
  // cooldown. Add exact wordings, not looser ones.
56
+ // Measured 2026-10-16 from a codex seat (gpt-6-astra over the ChatGPT login),
57
+ // on a security-gate request carrying SSRF/exfil/ReDoS test cases: "codex turn
58
+ // failed: This content was flagged for possible cybersecurity risk. If this
59
+ // seems wrong, try rephrasing your request. If you're doing authorized security
60
+ // work … apply for Daybreak access …". Classed as `runtime`, it was re-sent on
61
+ // backoff 5 times in 52 minutes, every one refused, and the seat handled
62
+ // nothing else until the kernel retired the event. Only the refusal wordings
63
+ // themselves are matched, so an ordinary failure that mentions a flag is not.
64
+ const CONTENT_REFUSED_RE = /(?:flagged for possible cybersecurity risk|this content was flagged|content[_ ]policy[_ ]violation|cyber[_ ]policy)/i;
52
65
  const QUOTA_RE = /(?:quota|usage limit|session limit|credit balance|out of credits|billing|insufficient[_ -]?quota|resource exhausted|spending limit)/i;
53
66
  const RATE_LIMIT_RE = /(?:rate[ -]?limit|too many requests|\b429\b|overloaded|capacity)/i;
54
67
  const CONFIGURATION_RE = /(?:ENOENT|command not found|not on PATH|login required|not logged in|invalid api key|authentication failed|unauthori[sz]ed|forbidden|\b40[13]\b)/i;
@@ -65,6 +78,9 @@ const errorText = (error) => [
65
78
 
66
79
  export const classifySpawnFailure = (error) => {
67
80
  const text = errorText(error);
81
+ // First: the refusal text carries none of the words below today, but a
82
+ // refusal must never be read as a transient condition and retried.
83
+ if (CONTENT_REFUSED_RE.test(text)) return SPAWN_FAILURE_CLASS.CONTENT_REFUSED;
68
84
  // Provider APIs commonly report an exhausted account quota as HTTP 429.
69
85
  // Prefer the more specific body/message over the generic status code so a
70
86
  // hard quota failure gets the long cooldown rather than a one-minute probe.