@commonlyai/cli 0.1.104 → 0.1.105

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.105",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -77,6 +77,14 @@ import {
77
77
  spawnRetryJitter,
78
78
  spawnRetryPolicy,
79
79
  } from '../lib/spawn-retry.js';
80
+ import {
81
+ CONTENT_REFUSED_REASON,
82
+ composeRefusalHandoff,
83
+ contentRefusedResult,
84
+ isContentRefusal,
85
+ refusedItemRef,
86
+ sanitizeHandoffAgent,
87
+ } from '../lib/content-refusal.js';
80
88
  import {
81
89
  ADDRESSED_EVENT_TYPES,
82
90
  CASCADE_DEFAULTS,
@@ -1112,11 +1120,18 @@ export const performRun = ({
1112
1120
  spawnCredentialLeaseFactory = createSpawnCredentialLease,
1113
1121
  revokeOrphansImpl = revokeOrphanedSpawnCredentials,
1114
1122
  sleepImpl = (ms) => new Promise((resolve) => { setTimeout(resolve, ms); }),
1123
+ // The agent to @mention when the model provider refuses a request's content
1124
+ // (lib/content-refusal.js). Null: the refusal notice names no one.
1125
+ refusalHandoff = null,
1115
1126
  }) => {
1116
1127
  if (environment?.provider !== undefined && !adapter?.supportsProvider) {
1117
1128
  throw new Error('environment.provider requires a provider-capable adapter');
1118
1129
  }
1119
1130
  const client = createClient({ instance: instanceUrl, token });
1131
+ const handoffAgent = sanitizeHandoffAgent(refusalHandoff);
1132
+ if (refusalHandoff && !handoffAgent) {
1133
+ log(`--refusal-handoff ignored: '${String(refusalHandoff).slice(0, 64)}' is not an agent handle`);
1134
+ }
1120
1135
 
1121
1136
  // THE BOOT SWEEP IS THE SECOND NET, AND IT HAPPENS ONCE PER PROCESS. A seat
1122
1137
  // that dies mid-turn (kill, crash, reboot) leaves its child credential live
@@ -1908,6 +1923,53 @@ export const performRun = ({
1908
1923
  // claim is not discarded: it remains in the model's context with the same
1909
1924
  // peer frame the single-event path already uses, but is explicitly read-only.
1910
1925
  // Advisory losses retain their existing peer-aware behaviour.
1926
+ // A refused item is acked, never retried (lib/content-refusal.js). Every one
1927
+ // is logged by event id alone. One addressed to this seat also gets a pod
1928
+ // notice the WRAPPER writes, since the model never read it: identifiers
1929
+ // only, and the hand-off agent @mentioned outside a DM. A refused broadcast
1930
+ // gets no notice: its claim releases as `upstream-refused`, and the kernel
1931
+ // hands a human's message to another listener. A notice that fails to post
1932
+ // is logged; the ack still happens, because retrying would only re-send the
1933
+ // refused content.
1934
+ const postRefusalNotice = async (refusedEntries, eventPodId) => {
1935
+ for (const entry of refusedEntries) {
1936
+ log(`[${entry.event.type}] the model provider refused the content of event ${entry.event._id} (content_refused) — acked as refused, not retried`);
1937
+ }
1938
+ const addressed = refusedEntries.filter((entry) => ADDRESSED_EVENT_TYPES.has(entry.event.type));
1939
+ if (addressed.length === 0) return;
1940
+ const mention = Boolean(handoffAgent) && !addressed.some((entry) => entry.event.type === 'dm.message');
1941
+ const text = composeRefusalHandoff({
1942
+ items: addressed.map((entry) => refusedItemRef(entry.event)),
1943
+ handoff: handoffAgent,
1944
+ mention,
1945
+ });
1946
+ let posted = false;
1947
+ try {
1948
+ const delivery = await deliverChatReply({
1949
+ client,
1950
+ podId: eventPodId,
1951
+ text,
1952
+ limit: chatCharLimit,
1953
+ maxChunks: maxChatChunks,
1954
+ uploadName: `${agentName}-refusal-${addressed[0].event._id}.md`,
1955
+ log: (line) => log(`[inbox.batch] ${line}`),
1956
+ });
1957
+ posted = !delivery.skipped && !delivery.refused;
1958
+ log(posted
1959
+ ? `[inbox.batch] refusal notice posted${mention ? `, handed off to @${handoffAgent}` : ''}`
1960
+ : `[inbox.batch] refusal notice not delivered (${delivery.reason})`);
1961
+ } catch (err) {
1962
+ log(`[inbox.batch] refusal notice failed: ${err.message}`);
1963
+ }
1964
+ for (const entry of addressed) {
1965
+ entry.result.details = {
1966
+ ...entry.result.details,
1967
+ handoff: mention ? handoffAgent : null,
1968
+ noticePosted: posted,
1969
+ };
1970
+ }
1971
+ };
1972
+
1911
1973
  const processEventBatch = async (events, inboxCount = events.length) => {
1912
1974
  const eventPodId = events[0]?.podId || podId;
1913
1975
  if (!eventPodId || events.some((event) => (event.podId || podId) !== eventPodId)) {
@@ -2059,19 +2121,76 @@ export const performRun = ({
2059
2121
  hasHeartbeat: entries.some((entry) => entry.event.type === 'heartbeat'),
2060
2122
  },
2061
2123
  };
2062
- let turnResult;
2063
- try {
2064
- turnResult = await runTurn({
2065
- event: batchEvent,
2124
+ // One item, run as its own turn. Used only after the provider refused a
2125
+ // batch's content: a composite turn cannot say WHICH item was refused, and
2126
+ // refusing them all would swallow the ordinary items with the flagged one.
2127
+ const isolatedTurn = async (entry) => {
2128
+ const before = await snapshotMessages();
2129
+ return runTurn({
2130
+ event: {
2131
+ ...entry.event,
2132
+ _id: `batch-${entry.event._id}`,
2133
+ type: 'inbox.batch',
2134
+ payload: {
2135
+ ...entry.event.payload,
2136
+ batchEventIds: [String(entry.event._id)],
2137
+ hasHeartbeat: entry.event.type === 'heartbeat',
2138
+ },
2139
+ },
2066
2140
  eventPodId,
2067
- prompt: buildInboxPrompt(entries, inboxCount),
2068
- preSpawnIds,
2141
+ prompt: buildInboxPrompt([entry], 1),
2142
+ preSpawnIds: before ? new Set(before.map((message) => String(message._id || message.id))) : null,
2069
2143
  snapshotMessages,
2070
- claimKeeper: compositeClaimKeeper,
2144
+ claimKeeper: entry.claimKeeper,
2071
2145
  trigger,
2072
2146
  });
2073
- for (const entry of actionEntries) entry.result = turnResult;
2074
- return { entries };
2147
+ };
2148
+
2149
+ let turnResult;
2150
+ let deferredError = null;
2151
+ try {
2152
+ try {
2153
+ turnResult = await runTurn({
2154
+ event: batchEvent,
2155
+ eventPodId,
2156
+ prompt: buildInboxPrompt(entries, inboxCount),
2157
+ preSpawnIds,
2158
+ snapshotMessages,
2159
+ claimKeeper: compositeClaimKeeper,
2160
+ trigger,
2161
+ });
2162
+ for (const entry of actionEntries) entry.result = turnResult;
2163
+ } catch (err) {
2164
+ if (!isContentRefusal(err)) throw err;
2165
+ if (actionEntries.length === 1) {
2166
+ actionEntries[0].result = contentRefusedResult();
2167
+ } else {
2168
+ log(
2169
+ `[inbox.batch] the model provider refused this batch's content (content_refused); `
2170
+ + `running its ${actionEntries.length} items one at a time so only a refused item is refused`,
2171
+ );
2172
+ for (const entry of actionEntries) {
2173
+ if (!running) break;
2174
+ try {
2175
+ // eslint-disable-next-line no-await-in-loop
2176
+ entry.result = await isolatedTurn(entry);
2177
+ } catch (itemErr) {
2178
+ // Any other failure stops here and leaves this item and the rest
2179
+ // unacked for redelivery; the tick applies the retry policy.
2180
+ if (!isContentRefusal(itemErr)) {
2181
+ deferredError = itemErr;
2182
+ break;
2183
+ }
2184
+ entry.result = contentRefusedResult();
2185
+ }
2186
+ }
2187
+ }
2188
+ await postRefusalNotice(
2189
+ actionEntries.filter((entry) => entry.result?.reason === CONTENT_REFUSED_REASON),
2190
+ eventPodId,
2191
+ );
2192
+ }
2193
+ return deferredError ? { entries, deferredError } : { entries };
2075
2194
  } finally {
2076
2195
  await Promise.all(actionEntries
2077
2196
  .filter((entry) => entry.claimKeeper)
@@ -2080,8 +2199,9 @@ export const performRun = ({
2080
2199
  // broadcast may be handed to one remaining listener, a refusal
2081
2200
  // closes with its reason, and every other completed batch item
2082
2201
  // 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);
2202
+ // An item left without a result (a failure during isolation)
2203
+ // releases with no outcome, for redelivery, as a thrown turn does.
2204
+ const release = claimReleaseFor(entry.event, entry.result || turnResult);
2085
2205
  await entry.claimKeeper.release(release.outcome, {
2086
2206
  reason: release.reason, status: release.status,
2087
2207
  });
@@ -2120,10 +2240,9 @@ export const performRun = ({
2120
2240
  for (const group of eventGroups.values()) {
2121
2241
  if (!running) break;
2122
2242
  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) {
2243
+ // One failure report for a batch whose items stay unacked, whether
2244
+ // the composite turn threw or an isolated item did after a refusal.
2245
+ const scheduleBatchRetry = (err, unackedCount) => {
2127
2246
  consecutiveSpawnFailures += 1;
2128
2247
  const retry = spawnRetryPolicy({
2129
2248
  error: err,
@@ -2135,7 +2254,7 @@ export const performRun = ({
2135
2254
  const event = group[0];
2136
2255
  const wrapped = new Error(
2137
2256
  `inbox batch processing failed (${retry.failureClass}; ${consecutiveSpawnFailures} consecutive) `
2138
- + `— ${group.length} events remain unacked; ${retry.circuitOpen ? 'circuit open' : 'retry scheduled'}, `
2257
+ + `— ${unackedCount} events remain unacked; ${retry.circuitOpen ? 'circuit open' : 'retry scheduled'}, `
2139
2258
  + `next probe in ${formatRetryDelay(retry.delayMs)}: ${err.message}`,
2140
2259
  { cause: err },
2141
2260
  );
@@ -2159,6 +2278,12 @@ export const performRun = ({
2159
2278
  });
2160
2279
  if (onError) onError(wrapped);
2161
2280
  else log(`[inbox.batch] ${wrapped.message}`);
2281
+ };
2282
+ let batch;
2283
+ try {
2284
+ batch = await processEventBatch(group, inboxCount);
2285
+ } catch (err) {
2286
+ scheduleBatchRetry(err, group.length);
2162
2287
  break;
2163
2288
  }
2164
2289
  const batchSpawned = batch.entries.some((entry) => (
@@ -2168,6 +2293,9 @@ export const performRun = ({
2168
2293
  if (batchSpawned) consecutiveSpawnFailures = 0;
2169
2294
  for (const entry of batch.entries) {
2170
2295
  const event = entry.event;
2296
+ // No result: an item a failure during refusal isolation never
2297
+ // reached. Unacked, the kernel redelivers it.
2298
+ if (!entry.result) continue;
2171
2299
  if (entry.result?.reason !== 'duplicate-delivery') {
2172
2300
  recordHandledEvent(agentName, event._id);
2173
2301
  }
@@ -2187,6 +2315,10 @@ export const performRun = ({
2187
2315
  onError?.(new Error(`Ack failed for ${event._id}: ${ackErr.message}`));
2188
2316
  }
2189
2317
  }
2318
+ if (batch.deferredError) {
2319
+ scheduleBatchRetry(batch.deferredError, batch.entries.filter((entry) => !entry.result).length);
2320
+ break;
2321
+ }
2190
2322
  continue;
2191
2323
  }
2192
2324
  const [event] = group;
@@ -2199,65 +2331,72 @@ export const performRun = ({
2199
2331
  try {
2200
2332
  result = await processEvent(event);
2201
2333
  } 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;
2334
+ if (isContentRefusal(err)) {
2335
+ // A refused private item is acked without a pod notice: it has no
2336
+ // pod to post into, and its sender's ask expires on its own.
2337
+ result = contentRefusedResult();
2338
+ log(`[${event.type}] the model provider refused the content of event ${event._id} (content_refused) — acked as refused, not retried`);
2339
+ } else {
2340
+ // Do not record or ack: the kernel must retain the event for
2341
+ // at-least-once delivery. Stop this fetched batch immediately —
2342
+ // continuing could launch every one of the 10 returned events
2343
+ // into the same provider outage before the next poll (#782).
2344
+ consecutiveSpawnFailures += 1;
2345
+ const retry = spawnRetryPolicy({
2346
+ error: err,
2347
+ consecutiveFailures: consecutiveSpawnFailures,
2348
+ intervalMs,
2349
+ jitterRatio: spawnJitterRatio,
2350
+ });
2351
+ nextPollDelayMs = retry.delayMs;
2352
+ const retryIn = formatRetryDelay(retry.delayMs);
2353
+ const state = retry.circuitOpen ? 'circuit open' : 'retry scheduled';
2354
+ const wrapped = new Error(
2355
+ `${event.type} processing failed (${retry.failureClass}; `
2356
+ + `${consecutiveSpawnFailures} consecutive) — event ${event._id} remains unacked; `
2357
+ + `${state}, next probe in ${retryIn}: ${err.message}`,
2358
+ { cause: err },
2359
+ );
2360
+ Object.assign(wrapped, {
2361
+ code: 'agent_spawn_retry_scheduled',
2362
+ failureClass: retry.failureClass,
2363
+ consecutiveFailures: consecutiveSpawnFailures,
2364
+ retryAfterMs: retry.delayMs,
2365
+ circuitOpen: retry.circuitOpen,
2366
+ eventId: event._id,
2367
+ ...(isPodFocusDiagnostic(err) ? {
2368
+ focusDiagnostic: {
2369
+ errorCode: err.code,
2370
+ eventIds: err.eventId || event._id,
2371
+ podId: err.podId || event.podId || podId || null,
2372
+ focusRevision: err.focusRevision ?? null,
2373
+ measuredCodePoints: err.measuredCodePoints ?? null,
2374
+ allowedCodePoints: err.allowedCodePoints ?? FOCUS_FRAME_MAX_CODE_POINTS,
2375
+ },
2376
+ } : {}),
2377
+ });
2378
+ // ONE emission, not two. `wrapped.message` already opens with the
2379
+ // event type, so the log copy added a second prefix and a second
2380
+ // line of identical text into the same merged stream — enough that
2381
+ // `grep -c 'session limit'` returned 8 for 4 failures, and a reader
2382
+ // counting hits per event id saw 2 and inferred two deliveries.
2383
+ // On 2026-08-18 that count pointed at the wrong cause for #993:
2384
+ // two deliveries per event puts `attempts` at 2 and the requeue cap
2385
+ // one step away. It did not decide anything — the cap was ruled out
2386
+ // from the DB, where a capped event would have left a `failed` row
2387
+ // and none existed — but it corroborated the wrong theory, and the
2388
+ // doubling had to be spotted by hand before the count could be
2389
+ // discounted. A log that inflates is worse than one that is silent,
2390
+ // because it argues.
2391
+ //
2392
+ // Routed to the error channel when a caller provides one, and to
2393
+ // the log when it doesn't, so neither contract loses the failure:
2394
+ // an embedder that passes no `onError` still sees it, and `agent
2395
+ // run` — which always passes one — stops printing it twice.
2396
+ if (onError) onError(wrapped);
2397
+ else log(`[${event.type}] ${wrapped.message}`);
2398
+ break;
2399
+ }
2261
2400
  }
2262
2401
  // Only a completed model turn proves the local runtime and delivery
2263
2402
  // path recovered. A malformed/no-destination event is still acked,
@@ -2904,6 +3043,7 @@ Docs:
2904
3043
  .option('--cascade-cap <n>', `Consecutive agent-triggered turns allowed per pod (env ${CASCADE_ENV_VARS.cap}, default ${CASCADE_DEFAULTS.cap})`)
2905
3044
  .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
3045
  .option('--cascade-reset <ms>', `Silence window that clears the streak (env ${CASCADE_ENV_VARS.resetMs}, default ${CASCADE_DEFAULTS.resetMs})`)
3046
+ .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
3047
  .action(async (name, opts) => {
2908
3048
  let record = loadAgentToken(name);
2909
3049
  if (!record) {
@@ -2996,6 +3136,7 @@ Docs:
2996
3136
  // server's published default, which is the only lifetime we can justify
2997
3137
  // without an operator saying otherwise.
2998
3138
  spawnCredentialTtlSeconds: resolveSpawnTtlSeconds(process.env),
3139
+ refusalHandoff: opts.refusalHandoff || null,
2999
3140
  log: (line) => console.log(`${stamp()} [${name}] ${line}`),
3000
3141
  // Both sinks are stamped, and both must be — but not for the reason
3001
3142
  // 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
+ };
@@ -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.