@commonlyai/cli 0.1.266 → 0.1.268

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.266",
3
+ "version": "0.1.268",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -130,6 +130,7 @@ import {
130
130
  refusedItemRef,
131
131
  sanitizeHandoffAgent,
132
132
  } from '../lib/content-refusal.js';
133
+ import { CANT_ANSWER_NOTICE_WINDOW_MS, cantAnswerNotice } from '../lib/turn-failure-notice.js';
133
134
  import {
134
135
  ADDRESSED_EVENT_TYPES,
135
136
  CASCADE_DEFAULTS,
@@ -742,6 +743,12 @@ const PROMPT_EVENT_TYPES = new Set([
742
743
  // event that exists to introduce the seat rather than to answer anyone, so it
743
744
  // is the only one worth holding back.
744
745
  const DEFERRABLE_SOLO_EVENT_TYPES = new Set(['first_contact']);
746
+ // Someone asked this seat for an answer: by type, by the server's stamp, or by
747
+ // replying to it. A batch turn carries the same answer for its items.
748
+ const someoneIsWaiting = (event) => ADDRESSED_EVENT_TYPES.has(event.type)
749
+ || event.payload?.addressed === true
750
+ || event.payload?.repliesToYourMessage === true
751
+ || event.payload?.someoneWaiting === true;
745
752
 
746
753
  // How long a fresh seat's greeting waits for a person before it runs alone.
747
754
  // One poll lost the race on the 0.1.257 walk (2026-11-05): the mention landed
@@ -781,6 +788,34 @@ const DELIVERY_RENEW_INTERVAL_MS = 60_000;
781
788
  // point where spawnRetryPolicy stops treating an unknown failure as transient.
782
789
  const HELD_RETRY_MAX_FAILURES = 3;
783
790
 
791
+ // F226: a turn shows at most the batch limit, so a carried item on top of a full
792
+ // page can sit past the cap. Such an item is not acked: it keeps its lease and
793
+ // rejoins the next turn. At this many turns passed over the carry lets it go,
794
+ // the way HELD_RETRY_MAX_FAILURES does, so an ambient item under a steady stream
795
+ // of people, or anything piling up during an outage, can't be held forever. The
796
+ // server redelivers it under its cap, and may retire it with the TASK-656 line,
797
+ // which is skipped if the agent has posted in the pod since.
798
+ const PAST_CAP_MAX_CARRIES = 5;
799
+
800
+ // Who gets a slot when a batch is past the cap. 'unknown' counts as a person:
801
+ // the snapshot behind `trigger` holds 10 messages and a page holds up to 50, and
802
+ // a wrong guess costs an ambient item one turn. Within a rank the older row
803
+ // wins, and carried rows lead the page, so new arrivals can't overtake them.
804
+ const capRank = (entry) => {
805
+ const { type, payload } = entry.event;
806
+ // A reply to the seat is direct address on a broadcast's transport, as the
807
+ // claim path treats it.
808
+ const direct = ADDRESSED_EVENT_TYPES.has(type)
809
+ || ((payload?.repliesToYourMessage === true || payload?.addressed === true)
810
+ && payload?.senderIsHuman !== false);
811
+ return direct && entry.trigger !== 'agent' && entry.trigger !== 'kernel'
812
+ ? 0
813
+ : 1 + inboxPriority(entry.event);
814
+ };
815
+
816
+ // The wake whose ack settles the digest (agentEventService.acknowledge).
817
+ const holdsDigest = (event) => Boolean(event.digestSnapshotAt || event.payload?.digestRollup);
818
+
784
819
  const deliveryIdOf = (event) => {
785
820
  const deliveryId = event?.payload?.deliveryId;
786
821
  return typeof deliveryId === 'string' && deliveryId ? deliveryId : null;
@@ -1525,7 +1560,14 @@ const FINAL_TEXT_IS_POSTED = 'Your final text is posted to the pod unless it is
1525
1560
  // threadRootId set to that message, so the answer sat in a collapsed thread
1526
1561
  // under it. The kernel's mention cue teaches threadRootId as a verb but never
1527
1562
  // says which messages it is for, so each top-level mention says where its
1528
- // answer goes, beside the message it answers.
1563
+ // answer goes, beside the message it answers. replyToMessageId alone threads
1564
+ // too, because the kernel derives the root from the reply edge, so the line
1565
+ // names both. This is advice: the guarantee is the kernel's answerStaysTopLevel.
1566
+ //
1567
+ // Only for a person's message. The line sends a plain post, which the kernel
1568
+ // cannot thread back, so on a peer's mention it would put an agent exchange in
1569
+ // the channel at every hop. A missing `senderIsHuman` means no line: the kernel
1570
+ // still keeps the answer top-level for a person.
1529
1571
  //
1530
1572
  // `chat.mention` alone is not "top-level": the kernel sends a chat-thread
1531
1573
  // mention as chat.mention with `payload.threadRootId`, a 1:1 DM as chat.mention
@@ -1551,6 +1593,7 @@ export const answersInChannel = (entry) => {
1551
1593
  return entry?.event?.type === 'chat.mention' && !entry.readOnly
1552
1594
  && entry.result?.reason !== 'duplicate-delivery'
1553
1595
  && Boolean(payload.messageId)
1596
+ && payload.senderIsHuman === true
1554
1597
  && (payload.threadRootId === undefined || payload.threadRootId === null || payload.threadRootId === '')
1555
1598
  && payload.source !== 'dm' && !payload.dmKind;
1556
1599
  };
@@ -2333,6 +2376,48 @@ export const performRun = ({
2333
2376
  }
2334
2377
  };
2335
2378
 
2379
+ // A failure only a person can fix, or only time can, leaves a mention
2380
+ // unanswered for as long as it lasts, so each pod with someone waiting is told
2381
+ // why, at most once per cause per pod per hour (persisted, so a restart does
2382
+ // not re-post). A later pod the failed turn stopped before reaching is told
2383
+ // too: a key or an allowance fails every pod alike, and its own turn could be
2384
+ // 45 minutes away. A notice that fails to post is logged and tried at the next
2385
+ // failure; the retry goes ahead either way.
2386
+ const noticeCantAnswer = async (error, waitingEvents) => {
2387
+ const notice = cantAnswerNotice(error);
2388
+ if (!notice || modelUnavailableFailure(error)) return;
2389
+ const waitingPods = new Set(waitingEvents
2390
+ .filter(someoneIsWaiting)
2391
+ .map((event) => event.podId || podId)
2392
+ .filter(Boolean));
2393
+ for (const waitingPod of waitingPods) {
2394
+ const key = `cant-answer:${notice.cause}:${waitingPod}`;
2395
+ try {
2396
+ // eslint-disable-next-line no-continue
2397
+ if (!noticeDue(agentName, key, CANT_ANSWER_NOTICE_WINDOW_MS)) continue;
2398
+ // eslint-disable-next-line no-await-in-loop
2399
+ const delivery = await deliverChatReply({
2400
+ client,
2401
+ podId: waitingPod,
2402
+ text: notice.text,
2403
+ limit: chatCharLimit,
2404
+ maxChunks: maxChatChunks,
2405
+ uploadName: `${agentName}-cant-answer.md`,
2406
+ log: (line) => log(`[inbox.batch] ${line}`),
2407
+ });
2408
+ if (delivery.skipped || delivery.refused) {
2409
+ log(`[inbox.batch] pod ${waitingPod} was not told why this agent can't answer: `
2410
+ + `${delivery.reason || 'the notice was not posted'}`);
2411
+ } else {
2412
+ recordNotice(agentName, key);
2413
+ log(`[inbox.batch] told pod ${waitingPod} why this agent can't answer (${notice.cause})`);
2414
+ }
2415
+ } catch (noticeError) {
2416
+ log(`[inbox.batch] pod ${waitingPod} was not told why this agent can't answer: ${noticeError.message}`);
2417
+ }
2418
+ }
2419
+ };
2420
+
2336
2421
  const runTurnBody = async ({
2337
2422
  event, eventPodId, prompt, preSpawnIds, snapshotMessages, claimKeeper, trigger, turn,
2338
2423
  }) => {
@@ -2927,6 +3012,8 @@ export const performRun = ({
2927
3012
  // any other wake it is terminal. The free-text detail stays in the seat
2928
3013
  // log and the event ack; the kernel records the class.
2929
3014
  if (!delivered && upstream) {
3015
+ // pi exits 0 on a refused route, so no failure reaches the retry path.
3016
+ await noticeCantAnswer(new Error(describeUpstreamRefusal(upstream)), [event]);
2930
3017
  return {
2931
3018
  outcome: 'no_action',
2932
3019
  refused: {
@@ -2951,20 +3038,26 @@ export const performRun = ({
2951
3038
  };
2952
3039
 
2953
3040
  // ADR-024 D3: the batch header states the real inbox count even when we cap
2954
- // copied bodies. The cap is the fetched page itself: never acknowledge a
2955
- // claimed event whose body the one turn did not receive. Additional pending
3041
+ // copied bodies. A claimed item past the cap (`pastCap`, set in
3042
+ // handleEventBatch) is left out and named in the prompt, never acked as seen;
3043
+ // the next turn shows it. Additional pending
2956
3044
  // events stay in the kernel queue and are cued in the header for a later
2957
3045
  // pull, rather than being silently consumed here.
2958
3046
  const buildInboxPrompt = (entries, inboxCount = entries.length) => {
2959
3047
  const BODY_LIMIT = batchLimit;
2960
- const wakeEntries = entries.filter((entry) => entry.event.deliveryMode !== 'digest');
2961
- const digestEntries = entries.filter((entry) => entry.event.deliveryMode === 'digest');
2962
- const shownEntries = wakeEntries.slice(0, BODY_LIMIT);
3048
+ const wakeEntries = entries.filter((entry) => entry.event.deliveryMode !== 'digest' && !entry.pastCap);
3049
+ const digestEntries = entries.filter((entry) => entry.event.deliveryMode === 'digest' && !entry.pastCap);
3050
+ // What the turn acts on always fits. An item already settled (a peer's, a
3051
+ // duplicate) is context, and takes only what's left.
3052
+ const context = wakeEntries.filter((entry) => entry.result);
3053
+ const contextShown = new Set(context.slice(0, Math.max(0, BODY_LIMIT - wakeEntries.length + context.length)));
3054
+ const shownEntries = wakeEntries.filter((entry) => !entry.result || contextShown.has(entry));
3055
+ const heldBack = entries.filter((entry) => entry.pastCap).length;
2963
3056
  const answersPerson = shownEntries.some(answersAPerson);
2964
3057
  const bodies = shownEntries.map((entry, index) => {
2965
3058
  const messageId = entry.event.payload?.messageId;
2966
3059
  const prefix = [
2967
- `Event ${index + 1}/${wakeEntries.length}: ${entry.event.type}`,
3060
+ `Event ${index + 1}/${shownEntries.length}: ${entry.event.type}`,
2968
3061
  messageId ? `message ${messageId}` : null,
2969
3062
  ].filter(Boolean).join(' — ');
2970
3063
  const claimContext = entry.readOnly
@@ -2994,6 +3087,10 @@ export const performRun = ({
2994
3087
  + 'Never checkpoint unfinished work. Only a successful checkpoint prevents replay after timeout. '
2995
3088
  + 'If the tool is unavailable, continue normally; completion will acknowledge the batch.',
2996
3089
  ...bodies,
3090
+ ...(heldBack > 0
3091
+ ? [`[${heldBack} more event${heldBack === 1 ? '' : 's'} in this inbox did not fit this turn. `
3092
+ + 'They are unread and still queued, and come in a later turn. Don\'t answer as if you saw them.]']
3093
+ : []),
2997
3094
  ...(digestFrame ? [digestFrame] : []),
2998
3095
  ...(omitted > 0
2999
3096
  ? [`[${omitted} more event${omitted === 1 ? '' : 's'} arrived. Their count is real; pull pod context if needed.]`]
@@ -3107,6 +3204,11 @@ export const performRun = ({
3107
3204
  let tickUnsettled = [];
3108
3205
  // eventId → consecutive local failures, for HELD_RETRY_MAX_FAILURES.
3109
3206
  const heldRetryFailures = new Map();
3207
+ // eventId → turns passed over, for PAST_CAP_MAX_CARRIES.
3208
+ const pastCapCarries = new Map();
3209
+ // The current batch's items past the cap. Kept out here because the tick needs
3210
+ // them when the turn throws, and a throw returns no entries.
3211
+ let pastCapEvents = [];
3110
3212
  let heldRenewTimer = null;
3111
3213
  const clearHeldRenewal = () => {
3112
3214
  if (heldRenewTimer !== null) clearIntervalImpl(heldRenewTimer);
@@ -3148,8 +3250,11 @@ export const performRun = ({
3148
3250
  // Decide what a failed turn's retry carries. `failedEvents` were attempted
3149
3251
  // and count toward HELD_RETRY_MAX_FAILURES; `untriedEvents` are later groups
3150
3252
  // from the same page that the failure stopped before they ran (#782), and
3151
- // are just as claimed, so they ride along without a strike.
3152
- const holdForRetry = async (failedEvents, untriedEvents = []) => {
3253
+ // are just as claimed, so they ride along without a strike. `pastCap` events
3254
+ // were left out of a turn, which is no failure of theirs: no strike, and
3255
+ // PAST_CAP_MAX_CARRIES bounds them instead. A later group's hold in the same
3256
+ // tick adds to the carry, never replaces it.
3257
+ const holdForRetry = async (failedEvents, untriedEvents = [], pastCap = []) => {
3153
3258
  const released = [];
3154
3259
  const carry = [];
3155
3260
  const seen = new Set();
@@ -3174,6 +3279,26 @@ export const performRun = ({
3174
3279
  carry.push(event);
3175
3280
  }
3176
3281
  }
3282
+ const passedOver = [];
3283
+ for (const event of pastCap) {
3284
+ const id = String(event._id);
3285
+ if (!seen.has(id)) {
3286
+ seen.add(id);
3287
+ const carries = (pastCapCarries.get(id) || 0) + 1;
3288
+ // As above: a stop hands the item back rather than leave it to the sweep.
3289
+ if (running && carries >= PAST_CAP_MAX_CARRIES) passedOver.push(event);
3290
+ else {
3291
+ pastCapCarries.set(id, carries);
3292
+ carry.push(event);
3293
+ }
3294
+ }
3295
+ }
3296
+ if (passedOver.length) {
3297
+ log(
3298
+ `[inbox.batch] releasing ${countEvents(passedOver.length)} after ${PAST_CAP_MAX_CARRIES} turns past the prompt cap `
3299
+ + 'to the server\'s requeue (redelivered in ~10–20 min)',
3300
+ );
3301
+ }
3177
3302
  // A stopping run carries nothing and renews nothing: extending the lease
3178
3303
  // of a process on its way out only delays the replacement's redelivery.
3179
3304
  // Its carry is handed back to the server when the tick ends instead
@@ -3181,18 +3306,21 @@ export const performRun = ({
3181
3306
  if (!running) {
3182
3307
  heldRetry = [...heldRetry, ...carry];
3183
3308
  heldRetryFailures.clear();
3309
+ pastCapCarries.clear();
3184
3310
  return { held: [], released, handedBack: carry };
3185
3311
  }
3186
3312
  const confirmed = carry.length ? await renewHeldDeliveries(carry) : null;
3187
- // The stop landed during that renewal, after the limit was applied.
3188
- if (!running) tickUnsettled.push(...released);
3313
+ // The stop landed during that renewal, after the limits were applied.
3314
+ if (!running) tickUnsettled.push(...released, ...passedOver);
3189
3315
  const held = carry.filter((event) => stillHeld(event, confirmed));
3190
3316
  const dropped = carry.filter((event) => !stillHeld(event, confirmed));
3191
- const heldIds = new Set(held.map((event) => String(event._id)));
3192
- for (const id of [...heldRetryFailures.keys()]) {
3193
- if (!heldIds.has(id)) heldRetryFailures.delete(id);
3317
+ heldRetry = [...heldRetry, ...held];
3318
+ const heldIds = new Set(heldRetry.map((event) => String(event._id)));
3319
+ for (const counts of [heldRetryFailures, pastCapCarries]) {
3320
+ for (const id of [...counts.keys()]) {
3321
+ if (!heldIds.has(id)) counts.delete(id);
3322
+ }
3194
3323
  }
3195
- heldRetry = held;
3196
3324
  if (dropped.length) {
3197
3325
  log(
3198
3326
  `[inbox.batch] ${countEvents(dropped.length)} no longer held by this runner on the server `
@@ -3307,6 +3435,7 @@ export const performRun = ({
3307
3435
  };
3308
3436
 
3309
3437
  const handleEventBatch = async (events, inboxCount = events.length) => {
3438
+ pastCapEvents = [];
3310
3439
  const eventPodId = events[0]?.podId || podId;
3311
3440
  if (!eventPodId || events.some((event) => (event.podId || podId) !== eventPodId)) {
3312
3441
  throw new Error('Inbox batch crossed pod boundaries; refusing to mix private pod context');
@@ -3364,6 +3493,22 @@ export const performRun = ({
3364
3493
  ? new Set(preSpawn.map((message) => String(message._id || message.id)))
3365
3494
  : null;
3366
3495
  const activeEntries = entries.filter((entry) => !entry.result);
3496
+ // The server settles a digest on its holder's ack, up to the holder's
3497
+ // snapshot. A holder this turn shows settles what it shows, so every digest
3498
+ // in hand goes in its prompt, whoever else waits. With no holder shown, a
3499
+ // holder that waits takes them along, so they settle on a turn that shows
3500
+ // them. A holder with a result settles nothing here: its reason doesn't count
3501
+ // as reading a digest.
3502
+ const carryPastCap = () => {
3503
+ const isHolder = (entry) => holdsDigest(entry.event);
3504
+ const shownHolder = wakingEntries.some((entry) => !entry.pastCap && !entry.result && isHolder(entry));
3505
+ if (!shownHolder && wakingEntries.some((entry) => entry.pastCap && isHolder(entry))) {
3506
+ for (const entry of activeEntries) {
3507
+ if (entry.event.deliveryMode === 'digest') entry.pastCap = true;
3508
+ }
3509
+ }
3510
+ pastCapEvents = entries.filter((entry) => entry.pastCap).map((entry) => entry.event);
3511
+ };
3367
3512
  // Ambient digest entries provide context for this turn, but must never
3368
3513
  // determine its admission or count as the trigger that woke the seat.
3369
3514
  const wakingEntries = activeEntries.filter((entry) => entry.event.deliveryMode !== 'digest');
@@ -3395,9 +3540,18 @@ export const performRun = ({
3395
3540
  admissionEvent.event.payload,
3396
3541
  );
3397
3542
  if (!admission.allowed) {
3543
+ // An agent row refuses the page, and that shouldn't cost a row nobody
3544
+ // can place: a person's message that scrolled off the snapshot reads
3545
+ // `unknown`. It is carried, past-cap bound included, and alone in its
3546
+ // next page it can't be refused, because only 'agent' ever is. A row
3547
+ // stamped as an agent's is placed, so it stays refused, or it would walk
3548
+ // past this brake. A legacy row has no stamp, and still carries.
3398
3549
  for (const entry of wakingEntries) {
3399
- entry.result = batchAdmissionResult(entry.event, admission);
3550
+ if (entry.trigger === 'unknown' && entry.event.payload?.messageId
3551
+ && entry.event.payload?.senderIsHuman !== false) entry.pastCap = true;
3552
+ else entry.result = batchAdmissionResult(entry.event, admission);
3400
3553
  }
3554
+ carryPastCap();
3401
3555
  return { entries };
3402
3556
  }
3403
3557
  }
@@ -3414,10 +3568,9 @@ export const performRun = ({
3414
3568
  }
3415
3569
  }
3416
3570
 
3417
- for (const entry of activeEntries) {
3418
- if (entry.event.deliveryMode === 'digest') continue;
3571
+ const claimEntry = async (entry) => {
3419
3572
  const messageId = entry.event.payload?.messageId;
3420
- if (!messageId || !CLAIMABLE_EVENT_TYPES.has(entry.event.type)) continue;
3573
+ if (!messageId || !CLAIMABLE_EVENT_TYPES.has(entry.event.type)) return;
3421
3574
  const claimKeeper = createClaimKeeper(client, {
3422
3575
  messageId,
3423
3576
  podId: eventPodId,
@@ -3441,7 +3594,7 @@ export const performRun = ({
3441
3594
  // read-only so a generic broadcast cannot widen itself after CAS.
3442
3595
  if (entry.event.payload?.repliesToYourMessage === true || entry.event.payload?.addressed === true) {
3443
3596
  entry.peerFrame = peerHoldsFrame(claim.holder, messageId);
3444
- continue;
3597
+ return;
3445
3598
  }
3446
3599
  // D3a's partition: no later model judgement can widen this item's
3447
3600
  // authority after a peer won the binding CAS.
@@ -3454,9 +3607,23 @@ export const performRun = ({
3454
3607
  } else {
3455
3608
  log(`[${entry.event.type}] claim unavailable (${claim.error?.message || 'unknown error'}) — proceeding unguarded`);
3456
3609
  }
3610
+ };
3611
+
3612
+ // The cap is spent here, not when the prompt is built: a lost claim gives its
3613
+ // slot back, and an item past the cap is never claimed, because a seat that
3614
+ // isn't reading a message must not hold a peer off it.
3615
+ let slotsLeft = batchLimit;
3616
+ for (const entry of [...wakingEntries].sort((a, b) => capRank(a) - capRank(b))) {
3617
+ if (slotsLeft === 0) entry.pastCap = true;
3618
+ else {
3619
+ // eslint-disable-next-line no-await-in-loop
3620
+ await claimEntry(entry);
3621
+ if (!entry.result) slotsLeft -= 1;
3622
+ }
3457
3623
  }
3624
+ carryPastCap();
3458
3625
 
3459
- const actionEntries = wakingEntries.filter((entry) => !entry.result);
3626
+ const actionEntries = wakingEntries.filter((entry) => !entry.result && !entry.pastCap);
3460
3627
  if (actionEntries.length === 0) return { entries };
3461
3628
 
3462
3629
  const claimKeepers = actionEntries
@@ -3472,8 +3639,9 @@ export const performRun = ({
3472
3639
  type: 'inbox.batch',
3473
3640
  payload: {
3474
3641
  ...actionEntries[0].event.payload,
3475
- batchEventIds: entries.map((entry) => String(entry.event._id)),
3476
- hasHeartbeat: entries.some((entry) => entry.event.type === 'heartbeat'),
3642
+ batchEventIds: entries.filter((entry) => !entry.pastCap).map((entry) => String(entry.event._id)),
3643
+ hasHeartbeat: entries.some((entry) => !entry.pastCap && entry.event.type === 'heartbeat'),
3644
+ someoneWaiting: entries.some((entry) => !entry.pastCap && someoneIsWaiting(entry.event)),
3477
3645
  },
3478
3646
  };
3479
3647
  // One item, run as its own turn. Used only after the provider refused a
@@ -3490,6 +3658,7 @@ export const performRun = ({
3490
3658
  ...entry.event.payload,
3491
3659
  batchEventIds: [String(entry.event._id)],
3492
3660
  hasHeartbeat: entry.event.type === 'heartbeat',
3661
+ someoneWaiting: someoneIsWaiting(entry.event),
3493
3662
  },
3494
3663
  },
3495
3664
  eventPodId,
@@ -3527,7 +3696,7 @@ export const performRun = ({
3527
3696
  || (turnResult?.outcome === 'no_action'
3528
3697
  && (!turnResult?.reason || turnResult.reason === 'silent_or_empty'))) {
3529
3698
  for (const entry of activeEntries) {
3530
- if (entry.event.deliveryMode === 'digest') {
3699
+ if (entry.event.deliveryMode === 'digest' && !entry.pastCap) {
3531
3700
  entry.result = { outcome: 'no_action', reason: 'digest-read' };
3532
3701
  }
3533
3702
  }
@@ -3654,9 +3823,9 @@ export const performRun = ({
3654
3823
  let retryScheduled = false;
3655
3824
  try {
3656
3825
  // ADR-024 D3: this is an inbox fetch, not a stream of interrupts. The
3657
- // backend returns one pod's oldest pending batch, so every delivered row
3658
- // below reaches the SAME composite turn before it can age into the
3659
- // requeue sweep. The service selects the pod before claiming any row;
3826
+ // backend returns one pod's oldest pending batch, so the rows below belong
3827
+ // to one composite turn, and what doesn't fit its prompt is carried to the
3828
+ // next (F226). The service selects the pod before claiming any row;
3660
3829
  // do not reintroduce a mixed-pod `limit: 10` here.
3661
3830
  // TASK-317: name this CLI for the chat chip. The server keeps it as a
3662
3831
  // display-only label (runtime.reportedCli) and never as a binding.
@@ -3722,8 +3891,8 @@ export const performRun = ({
3722
3891
  eventGroups.set(key, group);
3723
3892
  }
3724
3893
  // A carried greeting must not push a full page past the prompt's body
3725
- // cap: an event past the cap gets no body yet is acked with the batch
3726
- // (CodeRabbit on #3511). Carry the greeting again instead.
3894
+ // cap (CodeRabbit on #3511). It goes back to the greeting hold instead
3895
+ // of the past-cap carry.
3727
3896
  for (const [key, group] of eventGroups) {
3728
3897
  const wakeCount = group.filter((event) => event.deliveryMode !== 'digest').length;
3729
3898
  if (wakeCount <= batchLimit) continue;
@@ -3809,7 +3978,11 @@ export const performRun = ({
3809
3978
  nextPollDelayMs = retry.delayMs;
3810
3979
  retryScheduled = true;
3811
3980
  tickUnsettled.push(...claimedAfter(groupIndex));
3812
- const hold = await holdForRetry(failedEvents, untriedAfter(groupIndex));
3981
+ const hold = await holdForRetry(
3982
+ failedEvents.filter((event) => !pastCapEvents.includes(event)),
3983
+ untriedAfter(groupIndex),
3984
+ pastCapEvents,
3985
+ );
3813
3986
  keepHeldLeases(retry.delayMs);
3814
3987
  const event = group[0];
3815
3988
  const wrapped = new Error(
@@ -3839,6 +4012,7 @@ export const performRun = ({
3839
4012
  });
3840
4013
  if (onError) onError(wrapped);
3841
4014
  else log(`[inbox.batch] ${wrapped.message}`);
4015
+ await noticeCantAnswer(err, [...failedEvents, ...untriedAfter(groupIndex)]);
3842
4016
  };
3843
4017
  let batch;
3844
4018
  try {
@@ -3896,6 +4070,10 @@ export const performRun = ({
3896
4070
  // Items a stop cut off before they ran (refusal isolation checks
3897
4071
  // `running`), and any digest this batch left unread.
3898
4072
  tickUnsettled.push(...batch.entries.filter((entry) => !entry.result).map((entry) => entry.event));
4073
+ if (pastCapEvents.length) {
4074
+ await holdForRetry([], [], pastCapEvents);
4075
+ keepHeldLeases(nextPollDelayMs);
4076
+ }
3899
4077
  continue;
3900
4078
  }
3901
4079
  const [event] = group;
@@ -103,6 +103,12 @@ const CONTENT_REFUSED_RE = /(?:flagged for possible cybersecurity risk|this cont
103
103
  // adjacent `.`+digit is rare enough in provider copy to accept. The test below
104
104
  // pins what the pattern ACTUALLY has — a space after the period ends the match —
105
105
  // rather than the stronger property it does not have.
106
+ // The gateway's two budget refusals. A key over its budget answers 422 with this
107
+ // exact text (walked on a real key, 2026-11-06); a model group over its monthly
108
+ // pool answers 429 "crossed budget" (our gateway config). Case-sensitive, so a
109
+ // "thinking budget has been exceeded" stays out. Unmatched, the 422 is RUNTIME
110
+ // and the seat respawns every few seconds against a key that stays refused.
111
+ export const GATEWAY_BUDGET_RE = /Budget has been exceeded!|crossed budget/;
106
112
  const QUOTA_RE = /(?:quota|usage limit|session limit|weekly limit|credit balance|out of credits|billing|insufficient[_ -]?quota|resource exhausted|spending limit)/i;
107
113
  const QUOTA_POSSESSIVE_RE = /you'?ve (?:hit|reached) your (?!rate[ -]?limit)(?:[^.\n]|\.(?=\d)){0,40}?limit/i;
108
114
  // The status code is not a throttle wording: "429: You've reached your Fable 5
@@ -139,7 +145,7 @@ export const classifySpawnFailure = (error) => {
139
145
  // Provider APIs commonly report an exhausted account quota as HTTP 429.
140
146
  // Prefer the more specific body/message over the generic status code so a
141
147
  // hard quota failure gets the long cooldown rather than a one-minute probe.
142
- if (QUOTA_RE.test(text)) return SPAWN_FAILURE_CLASS.QUOTA;
148
+ if (QUOTA_RE.test(text) || GATEWAY_BUDGET_RE.test(text)) return SPAWN_FAILURE_CLASS.QUOTA;
143
149
  // The possessive shape is deliberately loose about what sits between "your"
144
150
  // and "limit", and its `(?!rate[ -]?limit)` lookahead only guards the word
145
151
  // IMMEDIATELY after "your" — so "you've hit your API rate limit" walked past
@@ -0,0 +1,73 @@
1
+ /**
2
+ * A seat that can't run a turn goes quiet (2026-11-06).
3
+ *
4
+ * The turn fails, the run loop opens the circuit and retries in 15 minutes, and
5
+ * the only trace is a line in a terminal the person in the pod may not own.
6
+ * They see their @mention go unanswered, with no reason. The wrapper, not the
7
+ * model, posts one plain line instead, since no model turn can run. It names
8
+ * the cause and who can fix it. It never quotes the error text, which is vendor
9
+ * output and can carry key material.
10
+ *
11
+ * The failure classes in spawn-retry.js are too loose for this. They only pick a
12
+ * backoff, so a stray "401" or "billing" in a stack trace costs a slower retry.
13
+ * Here the match becomes a statement to a person, so each line below fires only
14
+ * on a wording a seat has logged, a walk has produced, or the wrapper or our own
15
+ * gateway config writes. A failure that matches none of them posts nothing,
16
+ * which is what it did before.
17
+ */
18
+ import { PUBLIC_MCP_NOT_READY_CODE, PUBLIC_TOOL_FAILED_CODE } from './public-tool-error.js';
19
+ import { classifySpawnFailure, GATEWAY_BUDGET_RE, SPAWN_FAILURE_CLASS } from './spawn-retry.js';
20
+
21
+ /** How long one cause stays posted in a pod before the seat may post it again. */
22
+ export const CANT_ANSWER_NOTICE_WINDOW_MS = 60 * 60 * 1000;
23
+
24
+ const LOGIN_FAILED_WORDINGS = [
25
+ // Not `(upstream 401)` alone: adapterFailure writes that for any "status 401"
26
+ // in a tail, including a tool's stderr. A failed Codex turn is its own report.
27
+ /^codex turn failed \(upstream 401\)/,
28
+ /\bupstream refused 401\b/, // the same refusal, read from pi's stream
29
+ /^\w+ exited(?: with code)? \d+: 401\b/, // pi's text, which names no upstream
30
+ /workspace routing discovery unauthorized/,
31
+ /(?:^|: | \| )Not logged in · Please run \/login/,
32
+ /API Error: 400 This API key is not scoped to a workspace/,
33
+ // The wrapper's own refusals of a Claude login (adapters/claude.js).
34
+ /the Claude login on this machine expires in/,
35
+ /refusing a Claude login/,
36
+ ];
37
+ const WONT_START_WORDINGS = [
38
+ /^spawn \S+ ENOENT/,
39
+ /^\w+ adapter: \S+ (?:is not set|is missing)/, // the seat has no provider key
40
+ ];
41
+ // Not the whole of QUOTA_RE, which also holds "billing" and "quota" for backoff.
42
+ const OUT_OF_ALLOWANCE_WORDINGS = [
43
+ /(?:^|: | \| )you['’]?ve (?:hit|reached) your [^\n]{0,40}?limit/i,
44
+ /\bout of credits\b/i,
45
+ GATEWAY_BUDGET_RE,
46
+ ];
47
+
48
+ const AGAIN = 'After that, send your message again if I still haven’t answered.';
49
+
50
+ export const LOGIN_NOTICE = 'I can’t answer right now: the key or login on the computer I run on isn’t working. '
51
+ + `Whoever runs me needs to fix it and start me again. ${AGAIN}`;
52
+ export const WONT_START_NOTICE = 'I can’t answer right now: the tool I run on wouldn’t start on my computer. '
53
+ + `Whoever runs me needs to fix that and start me again. ${AGAIN}`;
54
+ export const OUT_OF_ALLOWANCE_NOTICE = 'I can’t answer right now: the AI account I run on has used up its allowance. '
55
+ + `It needs to reset, or whoever runs me needs to add more. ${AGAIN}`;
56
+
57
+ const matches = (wordings, text) => wordings.some((wording) => wording.test(text));
58
+
59
+ /** The cause a pod should hear about, and its line, or null when it should hear nothing. */
60
+ export const cantAnswerNotice = (error) => {
61
+ // A public seat's withheld turn quotes a TOOL's error, not its own provider's.
62
+ if (error?.code === PUBLIC_TOOL_FAILED_CODE || error?.code === PUBLIC_MCP_NOT_READY_CODE) return null;
63
+ // A crashed claude turn keeps assistant and tool JSON lines in its tail, and
64
+ // those are the model's words, or a tool's.
65
+ const text = String(error?.message ?? '').split(/(?:^|: | \| |\n)\{"type":/)[0];
66
+ // Before the allowance check: a 401 is settled, whatever else its body says.
67
+ if (matches(LOGIN_FAILED_WORDINGS, text)) return { cause: 'login', text: LOGIN_NOTICE };
68
+ if (matches(WONT_START_WORDINGS, text)) return { cause: 'wont-start', text: WONT_START_NOTICE };
69
+ if (classifySpawnFailure(error) === SPAWN_FAILURE_CLASS.QUOTA && matches(OUT_OF_ALLOWANCE_WORDINGS, text)) {
70
+ return { cause: 'out-of-allowance', text: OUT_OF_ALLOWANCE_NOTICE };
71
+ }
72
+ return null;
73
+ };