@commonlyai/cli 0.1.266 → 0.1.267

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.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/src/commands/agent.js +154 -30
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@commonlyai/cli",
3
- "version": "0.1.266",
3
+ "version": "0.1.267",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -781,6 +781,34 @@ const DELIVERY_RENEW_INTERVAL_MS = 60_000;
781
781
  // point where spawnRetryPolicy stops treating an unknown failure as transient.
782
782
  const HELD_RETRY_MAX_FAILURES = 3;
783
783
 
784
+ // F226: a turn shows at most the batch limit, so a carried item on top of a full
785
+ // page can sit past the cap. Such an item is not acked: it keeps its lease and
786
+ // rejoins the next turn. At this many turns passed over the carry lets it go,
787
+ // the way HELD_RETRY_MAX_FAILURES does, so an ambient item under a steady stream
788
+ // of people, or anything piling up during an outage, can't be held forever. The
789
+ // server redelivers it under its cap, and may retire it with the TASK-656 line,
790
+ // which is skipped if the agent has posted in the pod since.
791
+ const PAST_CAP_MAX_CARRIES = 5;
792
+
793
+ // Who gets a slot when a batch is past the cap. 'unknown' counts as a person:
794
+ // the snapshot behind `trigger` holds 10 messages and a page holds up to 50, and
795
+ // a wrong guess costs an ambient item one turn. Within a rank the older row
796
+ // wins, and carried rows lead the page, so new arrivals can't overtake them.
797
+ const capRank = (entry) => {
798
+ const { type, payload } = entry.event;
799
+ // A reply to the seat is direct address on a broadcast's transport, as the
800
+ // claim path treats it.
801
+ const direct = ADDRESSED_EVENT_TYPES.has(type)
802
+ || ((payload?.repliesToYourMessage === true || payload?.addressed === true)
803
+ && payload?.senderIsHuman !== false);
804
+ return direct && entry.trigger !== 'agent' && entry.trigger !== 'kernel'
805
+ ? 0
806
+ : 1 + inboxPriority(entry.event);
807
+ };
808
+
809
+ // The wake whose ack settles the digest (agentEventService.acknowledge).
810
+ const holdsDigest = (event) => Boolean(event.digestSnapshotAt || event.payload?.digestRollup);
811
+
784
812
  const deliveryIdOf = (event) => {
785
813
  const deliveryId = event?.payload?.deliveryId;
786
814
  return typeof deliveryId === 'string' && deliveryId ? deliveryId : null;
@@ -1525,7 +1553,14 @@ const FINAL_TEXT_IS_POSTED = 'Your final text is posted to the pod unless it is
1525
1553
  // threadRootId set to that message, so the answer sat in a collapsed thread
1526
1554
  // under it. The kernel's mention cue teaches threadRootId as a verb but never
1527
1555
  // says which messages it is for, so each top-level mention says where its
1528
- // answer goes, beside the message it answers.
1556
+ // answer goes, beside the message it answers. replyToMessageId alone threads
1557
+ // too, because the kernel derives the root from the reply edge, so the line
1558
+ // names both. This is advice: the guarantee is the kernel's answerStaysTopLevel.
1559
+ //
1560
+ // Only for a person's message. The line sends a plain post, which the kernel
1561
+ // cannot thread back, so on a peer's mention it would put an agent exchange in
1562
+ // the channel at every hop. A missing `senderIsHuman` means no line: the kernel
1563
+ // still keeps the answer top-level for a person.
1529
1564
  //
1530
1565
  // `chat.mention` alone is not "top-level": the kernel sends a chat-thread
1531
1566
  // mention as chat.mention with `payload.threadRootId`, a 1:1 DM as chat.mention
@@ -1551,6 +1586,7 @@ export const answersInChannel = (entry) => {
1551
1586
  return entry?.event?.type === 'chat.mention' && !entry.readOnly
1552
1587
  && entry.result?.reason !== 'duplicate-delivery'
1553
1588
  && Boolean(payload.messageId)
1589
+ && payload.senderIsHuman === true
1554
1590
  && (payload.threadRootId === undefined || payload.threadRootId === null || payload.threadRootId === '')
1555
1591
  && payload.source !== 'dm' && !payload.dmKind;
1556
1592
  };
@@ -2951,20 +2987,26 @@ export const performRun = ({
2951
2987
  };
2952
2988
 
2953
2989
  // 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
2990
+ // copied bodies. A claimed item past the cap (`pastCap`, set in
2991
+ // handleEventBatch) is left out and named in the prompt, never acked as seen;
2992
+ // the next turn shows it. Additional pending
2956
2993
  // events stay in the kernel queue and are cued in the header for a later
2957
2994
  // pull, rather than being silently consumed here.
2958
2995
  const buildInboxPrompt = (entries, inboxCount = entries.length) => {
2959
2996
  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);
2997
+ const wakeEntries = entries.filter((entry) => entry.event.deliveryMode !== 'digest' && !entry.pastCap);
2998
+ const digestEntries = entries.filter((entry) => entry.event.deliveryMode === 'digest' && !entry.pastCap);
2999
+ // What the turn acts on always fits. An item already settled (a peer's, a
3000
+ // duplicate) is context, and takes only what's left.
3001
+ const context = wakeEntries.filter((entry) => entry.result);
3002
+ const contextShown = new Set(context.slice(0, Math.max(0, BODY_LIMIT - wakeEntries.length + context.length)));
3003
+ const shownEntries = wakeEntries.filter((entry) => !entry.result || contextShown.has(entry));
3004
+ const heldBack = entries.filter((entry) => entry.pastCap).length;
2963
3005
  const answersPerson = shownEntries.some(answersAPerson);
2964
3006
  const bodies = shownEntries.map((entry, index) => {
2965
3007
  const messageId = entry.event.payload?.messageId;
2966
3008
  const prefix = [
2967
- `Event ${index + 1}/${wakeEntries.length}: ${entry.event.type}`,
3009
+ `Event ${index + 1}/${shownEntries.length}: ${entry.event.type}`,
2968
3010
  messageId ? `message ${messageId}` : null,
2969
3011
  ].filter(Boolean).join(' — ');
2970
3012
  const claimContext = entry.readOnly
@@ -2994,6 +3036,10 @@ export const performRun = ({
2994
3036
  + 'Never checkpoint unfinished work. Only a successful checkpoint prevents replay after timeout. '
2995
3037
  + 'If the tool is unavailable, continue normally; completion will acknowledge the batch.',
2996
3038
  ...bodies,
3039
+ ...(heldBack > 0
3040
+ ? [`[${heldBack} more event${heldBack === 1 ? '' : 's'} in this inbox did not fit this turn. `
3041
+ + 'They are unread and still queued, and come in a later turn. Don\'t answer as if you saw them.]']
3042
+ : []),
2997
3043
  ...(digestFrame ? [digestFrame] : []),
2998
3044
  ...(omitted > 0
2999
3045
  ? [`[${omitted} more event${omitted === 1 ? '' : 's'} arrived. Their count is real; pull pod context if needed.]`]
@@ -3107,6 +3153,11 @@ export const performRun = ({
3107
3153
  let tickUnsettled = [];
3108
3154
  // eventId → consecutive local failures, for HELD_RETRY_MAX_FAILURES.
3109
3155
  const heldRetryFailures = new Map();
3156
+ // eventId → turns passed over, for PAST_CAP_MAX_CARRIES.
3157
+ const pastCapCarries = new Map();
3158
+ // The current batch's items past the cap. Kept out here because the tick needs
3159
+ // them when the turn throws, and a throw returns no entries.
3160
+ let pastCapEvents = [];
3110
3161
  let heldRenewTimer = null;
3111
3162
  const clearHeldRenewal = () => {
3112
3163
  if (heldRenewTimer !== null) clearIntervalImpl(heldRenewTimer);
@@ -3148,8 +3199,11 @@ export const performRun = ({
3148
3199
  // Decide what a failed turn's retry carries. `failedEvents` were attempted
3149
3200
  // and count toward HELD_RETRY_MAX_FAILURES; `untriedEvents` are later groups
3150
3201
  // 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 = []) => {
3202
+ // are just as claimed, so they ride along without a strike. `pastCap` events
3203
+ // were left out of a turn, which is no failure of theirs: no strike, and
3204
+ // PAST_CAP_MAX_CARRIES bounds them instead. A later group's hold in the same
3205
+ // tick adds to the carry, never replaces it.
3206
+ const holdForRetry = async (failedEvents, untriedEvents = [], pastCap = []) => {
3153
3207
  const released = [];
3154
3208
  const carry = [];
3155
3209
  const seen = new Set();
@@ -3174,6 +3228,26 @@ export const performRun = ({
3174
3228
  carry.push(event);
3175
3229
  }
3176
3230
  }
3231
+ const passedOver = [];
3232
+ for (const event of pastCap) {
3233
+ const id = String(event._id);
3234
+ if (!seen.has(id)) {
3235
+ seen.add(id);
3236
+ const carries = (pastCapCarries.get(id) || 0) + 1;
3237
+ // As above: a stop hands the item back rather than leave it to the sweep.
3238
+ if (running && carries >= PAST_CAP_MAX_CARRIES) passedOver.push(event);
3239
+ else {
3240
+ pastCapCarries.set(id, carries);
3241
+ carry.push(event);
3242
+ }
3243
+ }
3244
+ }
3245
+ if (passedOver.length) {
3246
+ log(
3247
+ `[inbox.batch] releasing ${countEvents(passedOver.length)} after ${PAST_CAP_MAX_CARRIES} turns past the prompt cap `
3248
+ + 'to the server\'s requeue (redelivered in ~10–20 min)',
3249
+ );
3250
+ }
3177
3251
  // A stopping run carries nothing and renews nothing: extending the lease
3178
3252
  // of a process on its way out only delays the replacement's redelivery.
3179
3253
  // Its carry is handed back to the server when the tick ends instead
@@ -3181,18 +3255,21 @@ export const performRun = ({
3181
3255
  if (!running) {
3182
3256
  heldRetry = [...heldRetry, ...carry];
3183
3257
  heldRetryFailures.clear();
3258
+ pastCapCarries.clear();
3184
3259
  return { held: [], released, handedBack: carry };
3185
3260
  }
3186
3261
  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);
3262
+ // The stop landed during that renewal, after the limits were applied.
3263
+ if (!running) tickUnsettled.push(...released, ...passedOver);
3189
3264
  const held = carry.filter((event) => stillHeld(event, confirmed));
3190
3265
  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);
3266
+ heldRetry = [...heldRetry, ...held];
3267
+ const heldIds = new Set(heldRetry.map((event) => String(event._id)));
3268
+ for (const counts of [heldRetryFailures, pastCapCarries]) {
3269
+ for (const id of [...counts.keys()]) {
3270
+ if (!heldIds.has(id)) counts.delete(id);
3271
+ }
3194
3272
  }
3195
- heldRetry = held;
3196
3273
  if (dropped.length) {
3197
3274
  log(
3198
3275
  `[inbox.batch] ${countEvents(dropped.length)} no longer held by this runner on the server `
@@ -3307,6 +3384,7 @@ export const performRun = ({
3307
3384
  };
3308
3385
 
3309
3386
  const handleEventBatch = async (events, inboxCount = events.length) => {
3387
+ pastCapEvents = [];
3310
3388
  const eventPodId = events[0]?.podId || podId;
3311
3389
  if (!eventPodId || events.some((event) => (event.podId || podId) !== eventPodId)) {
3312
3390
  throw new Error('Inbox batch crossed pod boundaries; refusing to mix private pod context');
@@ -3364,6 +3442,22 @@ export const performRun = ({
3364
3442
  ? new Set(preSpawn.map((message) => String(message._id || message.id)))
3365
3443
  : null;
3366
3444
  const activeEntries = entries.filter((entry) => !entry.result);
3445
+ // The server settles a digest on its holder's ack, up to the holder's
3446
+ // snapshot. A holder this turn shows settles what it shows, so every digest
3447
+ // in hand goes in its prompt, whoever else waits. With no holder shown, a
3448
+ // holder that waits takes them along, so they settle on a turn that shows
3449
+ // them. A holder with a result settles nothing here: its reason doesn't count
3450
+ // as reading a digest.
3451
+ const carryPastCap = () => {
3452
+ const isHolder = (entry) => holdsDigest(entry.event);
3453
+ const shownHolder = wakingEntries.some((entry) => !entry.pastCap && !entry.result && isHolder(entry));
3454
+ if (!shownHolder && wakingEntries.some((entry) => entry.pastCap && isHolder(entry))) {
3455
+ for (const entry of activeEntries) {
3456
+ if (entry.event.deliveryMode === 'digest') entry.pastCap = true;
3457
+ }
3458
+ }
3459
+ pastCapEvents = entries.filter((entry) => entry.pastCap).map((entry) => entry.event);
3460
+ };
3367
3461
  // Ambient digest entries provide context for this turn, but must never
3368
3462
  // determine its admission or count as the trigger that woke the seat.
3369
3463
  const wakingEntries = activeEntries.filter((entry) => entry.event.deliveryMode !== 'digest');
@@ -3395,9 +3489,18 @@ export const performRun = ({
3395
3489
  admissionEvent.event.payload,
3396
3490
  );
3397
3491
  if (!admission.allowed) {
3492
+ // An agent row refuses the page, and that shouldn't cost a row nobody
3493
+ // can place: a person's message that scrolled off the snapshot reads
3494
+ // `unknown`. It is carried, past-cap bound included, and alone in its
3495
+ // next page it can't be refused, because only 'agent' ever is. A row
3496
+ // stamped as an agent's is placed, so it stays refused, or it would walk
3497
+ // past this brake. A legacy row has no stamp, and still carries.
3398
3498
  for (const entry of wakingEntries) {
3399
- entry.result = batchAdmissionResult(entry.event, admission);
3499
+ if (entry.trigger === 'unknown' && entry.event.payload?.messageId
3500
+ && entry.event.payload?.senderIsHuman !== false) entry.pastCap = true;
3501
+ else entry.result = batchAdmissionResult(entry.event, admission);
3400
3502
  }
3503
+ carryPastCap();
3401
3504
  return { entries };
3402
3505
  }
3403
3506
  }
@@ -3414,10 +3517,9 @@ export const performRun = ({
3414
3517
  }
3415
3518
  }
3416
3519
 
3417
- for (const entry of activeEntries) {
3418
- if (entry.event.deliveryMode === 'digest') continue;
3520
+ const claimEntry = async (entry) => {
3419
3521
  const messageId = entry.event.payload?.messageId;
3420
- if (!messageId || !CLAIMABLE_EVENT_TYPES.has(entry.event.type)) continue;
3522
+ if (!messageId || !CLAIMABLE_EVENT_TYPES.has(entry.event.type)) return;
3421
3523
  const claimKeeper = createClaimKeeper(client, {
3422
3524
  messageId,
3423
3525
  podId: eventPodId,
@@ -3441,7 +3543,7 @@ export const performRun = ({
3441
3543
  // read-only so a generic broadcast cannot widen itself after CAS.
3442
3544
  if (entry.event.payload?.repliesToYourMessage === true || entry.event.payload?.addressed === true) {
3443
3545
  entry.peerFrame = peerHoldsFrame(claim.holder, messageId);
3444
- continue;
3546
+ return;
3445
3547
  }
3446
3548
  // D3a's partition: no later model judgement can widen this item's
3447
3549
  // authority after a peer won the binding CAS.
@@ -3454,9 +3556,23 @@ export const performRun = ({
3454
3556
  } else {
3455
3557
  log(`[${entry.event.type}] claim unavailable (${claim.error?.message || 'unknown error'}) — proceeding unguarded`);
3456
3558
  }
3559
+ };
3560
+
3561
+ // The cap is spent here, not when the prompt is built: a lost claim gives its
3562
+ // slot back, and an item past the cap is never claimed, because a seat that
3563
+ // isn't reading a message must not hold a peer off it.
3564
+ let slotsLeft = batchLimit;
3565
+ for (const entry of [...wakingEntries].sort((a, b) => capRank(a) - capRank(b))) {
3566
+ if (slotsLeft === 0) entry.pastCap = true;
3567
+ else {
3568
+ // eslint-disable-next-line no-await-in-loop
3569
+ await claimEntry(entry);
3570
+ if (!entry.result) slotsLeft -= 1;
3571
+ }
3457
3572
  }
3573
+ carryPastCap();
3458
3574
 
3459
- const actionEntries = wakingEntries.filter((entry) => !entry.result);
3575
+ const actionEntries = wakingEntries.filter((entry) => !entry.result && !entry.pastCap);
3460
3576
  if (actionEntries.length === 0) return { entries };
3461
3577
 
3462
3578
  const claimKeepers = actionEntries
@@ -3472,8 +3588,8 @@ export const performRun = ({
3472
3588
  type: 'inbox.batch',
3473
3589
  payload: {
3474
3590
  ...actionEntries[0].event.payload,
3475
- batchEventIds: entries.map((entry) => String(entry.event._id)),
3476
- hasHeartbeat: entries.some((entry) => entry.event.type === 'heartbeat'),
3591
+ batchEventIds: entries.filter((entry) => !entry.pastCap).map((entry) => String(entry.event._id)),
3592
+ hasHeartbeat: entries.some((entry) => !entry.pastCap && entry.event.type === 'heartbeat'),
3477
3593
  },
3478
3594
  };
3479
3595
  // One item, run as its own turn. Used only after the provider refused a
@@ -3527,7 +3643,7 @@ export const performRun = ({
3527
3643
  || (turnResult?.outcome === 'no_action'
3528
3644
  && (!turnResult?.reason || turnResult.reason === 'silent_or_empty'))) {
3529
3645
  for (const entry of activeEntries) {
3530
- if (entry.event.deliveryMode === 'digest') {
3646
+ if (entry.event.deliveryMode === 'digest' && !entry.pastCap) {
3531
3647
  entry.result = { outcome: 'no_action', reason: 'digest-read' };
3532
3648
  }
3533
3649
  }
@@ -3654,9 +3770,9 @@ export const performRun = ({
3654
3770
  let retryScheduled = false;
3655
3771
  try {
3656
3772
  // 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;
3773
+ // backend returns one pod's oldest pending batch, so the rows below belong
3774
+ // to one composite turn, and what doesn't fit its prompt is carried to the
3775
+ // next (F226). The service selects the pod before claiming any row;
3660
3776
  // do not reintroduce a mixed-pod `limit: 10` here.
3661
3777
  // TASK-317: name this CLI for the chat chip. The server keeps it as a
3662
3778
  // display-only label (runtime.reportedCli) and never as a binding.
@@ -3722,8 +3838,8 @@ export const performRun = ({
3722
3838
  eventGroups.set(key, group);
3723
3839
  }
3724
3840
  // 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.
3841
+ // cap (CodeRabbit on #3511). It goes back to the greeting hold instead
3842
+ // of the past-cap carry.
3727
3843
  for (const [key, group] of eventGroups) {
3728
3844
  const wakeCount = group.filter((event) => event.deliveryMode !== 'digest').length;
3729
3845
  if (wakeCount <= batchLimit) continue;
@@ -3809,7 +3925,11 @@ export const performRun = ({
3809
3925
  nextPollDelayMs = retry.delayMs;
3810
3926
  retryScheduled = true;
3811
3927
  tickUnsettled.push(...claimedAfter(groupIndex));
3812
- const hold = await holdForRetry(failedEvents, untriedAfter(groupIndex));
3928
+ const hold = await holdForRetry(
3929
+ failedEvents.filter((event) => !pastCapEvents.includes(event)),
3930
+ untriedAfter(groupIndex),
3931
+ pastCapEvents,
3932
+ );
3813
3933
  keepHeldLeases(retry.delayMs);
3814
3934
  const event = group[0];
3815
3935
  const wrapped = new Error(
@@ -3896,6 +4016,10 @@ export const performRun = ({
3896
4016
  // Items a stop cut off before they ran (refusal isolation checks
3897
4017
  // `running`), and any digest this batch left unread.
3898
4018
  tickUnsettled.push(...batch.entries.filter((entry) => !entry.result).map((entry) => entry.event));
4019
+ if (pastCapEvents.length) {
4020
+ await holdForRetry([], [], pastCapEvents);
4021
+ keepHeldLeases(nextPollDelayMs);
4022
+ }
3899
4023
  continue;
3900
4024
  }
3901
4025
  const [event] = group;