@commonlyai/cli 0.1.265 → 0.1.266

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 +157 -17
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@commonlyai/cli",
3
- "version": "0.1.265",
3
+ "version": "0.1.266",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -1174,11 +1174,20 @@ export const resolveAttachSandbox = ({
1174
1174
  // used to fail closed on, refusing `internal` beside `mode: 'workspace'`. It is
1175
1175
  // pure — a mode and an adapter name — so it belongs with the derivation, and
1176
1176
  // its witnesses live beside it.
1177
- if ((mode === 'workspace' || mode === 'read-only')
1178
- && (!confined || !ADAPTERS_WITH_SANDBOX_ENFORCEMENT.has(adapterName))) {
1179
- throw new Error(
1180
- `sandbox.mode=${mode} requires public trust and an adapter with sandbox enforcement`,
1181
- );
1177
+ // Two different things can be missing, so the refusal names the one that is:
1178
+ // the D247 walk read "requires public trust" on a seat whose trust WAS public.
1179
+ if (mode === 'workspace' || mode === 'read-only') {
1180
+ if (!confined) {
1181
+ throw new Error(
1182
+ `sandbox.mode=${mode} needs sandbox.trust=public. Add it, or remove sandbox.mode to run without a sandbox.`,
1183
+ );
1184
+ }
1185
+ if (!ADAPTERS_WITH_SANDBOX_ENFORCEMENT.has(adapterName)) {
1186
+ throw new Error(
1187
+ `The ${adapterName || 'selected'} adapter can't enforce sandbox.mode=${mode}. `
1188
+ + `On macOS, these adapters can: ${[...ADAPTERS_WITH_SANDBOX_ENFORCEMENT].sort().join(', ')}.`,
1189
+ );
1190
+ }
1182
1191
  }
1183
1192
  return { mode, trust };
1184
1193
  };
@@ -1702,6 +1711,7 @@ export const performRun = ({
1702
1711
  log = () => {},
1703
1712
  onError,
1704
1713
  setTimeoutImpl = setTimeout,
1714
+ clearTimeoutImpl = clearTimeout,
1705
1715
  setIntervalImpl = setInterval,
1706
1716
  clearIntervalImpl = clearInterval,
1707
1717
  // The host's bubblewrap probe, for a turn placed public; tests pin it.
@@ -3089,6 +3099,12 @@ export const performRun = ({
3089
3099
  // 2026-10-25): a scheduled retry either fires, re-running the held events,
3090
3100
  // or releases them; it never leaves a live process idle on unacked work.
3091
3101
  let heldRetry = [];
3102
+ // Claimed events the latest tick neither acked nor carried: a digest left
3103
+ // unread, or a later group a failure or a stale ack skipped. A running seat
3104
+ // leaves these to the requeue as it always has. A stop hands them back on
3105
+ // every planned exit from the tick; an unexpected throw leaves the page to
3106
+ // the requeue. One list, so a new exit has one thing to add to (F189).
3107
+ let tickUnsettled = [];
3092
3108
  // eventId → consecutive local failures, for HELD_RETRY_MAX_FAILURES.
3093
3109
  const heldRetryFailures = new Map();
3094
3110
  let heldRenewTimer = null;
@@ -3142,7 +3158,9 @@ export const performRun = ({
3142
3158
  if (!seen.has(id)) {
3143
3159
  seen.add(id);
3144
3160
  const failures = (heldRetryFailures.get(id) || 0) + 1;
3145
- if (failures >= HELD_RETRY_MAX_FAILURES) released.push(event);
3161
+ // A stop wins over the local limit: the sweep would make this event
3162
+ // wait 10–20 minutes, and the server's ceiling bounds a hand-back.
3163
+ if (running && failures >= HELD_RETRY_MAX_FAILURES) released.push(event);
3146
3164
  else {
3147
3165
  heldRetryFailures.set(id, failures);
3148
3166
  carry.push(event);
@@ -3158,9 +3176,18 @@ export const performRun = ({
3158
3176
  }
3159
3177
  // A stopping run carries nothing and renews nothing: extending the lease
3160
3178
  // of a process on its way out only delays the replacement's redelivery.
3161
- const confirmed = running && carry.length ? await renewHeldDeliveries(carry) : null;
3162
- const held = running ? carry.filter((event) => stillHeld(event, confirmed)) : [];
3163
- const dropped = running ? carry.filter((event) => !stillHeld(event, confirmed)) : [];
3179
+ // Its carry is handed back to the server when the tick ends instead
3180
+ // (F189), so the next run answers it on its first poll.
3181
+ if (!running) {
3182
+ heldRetry = [...heldRetry, ...carry];
3183
+ heldRetryFailures.clear();
3184
+ return { held: [], released, handedBack: carry };
3185
+ }
3186
+ 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);
3189
+ const held = carry.filter((event) => stillHeld(event, confirmed));
3190
+ const dropped = carry.filter((event) => !stillHeld(event, confirmed));
3164
3191
  const heldIds = new Set(held.map((event) => String(event._id)));
3165
3192
  for (const id of [...heldRetryFailures.keys()]) {
3166
3193
  if (!heldIds.has(id)) heldRetryFailures.delete(id);
@@ -3172,7 +3199,65 @@ export const performRun = ({
3172
3199
  + '(checkpointed, requeued or retired) — not retried',
3173
3200
  );
3174
3201
  }
3175
- return { held, released };
3202
+ return { held, released, handedBack: [] };
3203
+ };
3204
+
3205
+ // F189/F182: hand claimed events this run will never run back to the
3206
+ // server as pending, so the next run claims them on its first poll. Without
3207
+ // this they stay `delivered` to a dead process until the requeue sweep
3208
+ // (10–20 min, one attempt spent per lap): a walk on 2026-11-05 restarted a
3209
+ // circuit-open seat five times and each restart's mention waited on that
3210
+ // sweep. Nonce-bound on the server, so nothing a replacement holds can be
3211
+ // released, and an event this run released can no longer be acked by it.
3212
+ // The server refuses an event at its redelivery ceiling (`atCeiling`); it
3213
+ // stays delivered and the requeue retires it, which bounds a poison event.
3214
+ // Best effort: an older server without the route, or a failed request,
3215
+ // leaves them to the requeue as before, and says so.
3216
+ const handBackDeliveries = async (events, why) => {
3217
+ const seen = new Set();
3218
+ const deliveries = [];
3219
+ for (const event of events) {
3220
+ const id = String(event._id);
3221
+ if (deliveryIdOf(event) && !seen.has(id)) {
3222
+ seen.add(id);
3223
+ deliveries.push({ eventId: id, deliveryId: deliveryIdOf(event) });
3224
+ }
3225
+ }
3226
+ if (deliveries.length === 0) return [];
3227
+ const released = [];
3228
+ const atCeiling = [];
3229
+ try {
3230
+ for (let offset = 0; offset < deliveries.length; offset += 50) {
3231
+ // eslint-disable-next-line no-await-in-loop
3232
+ const response = await client.post('/api/agents/runtime/events/release', {
3233
+ events: deliveries.slice(offset, offset + 50),
3234
+ });
3235
+ if (Array.isArray(response?.released)) released.push(...response.released.map(String));
3236
+ if (Array.isArray(response?.atCeiling)) atCeiling.push(...response.atCeiling.map(String));
3237
+ }
3238
+ } catch (error) {
3239
+ log(
3240
+ `[inbox.batch] could not hand back ${countEvents(deliveries.length - released.length)} on ${why} `
3241
+ + `(${error.message}) — the server's requeue redelivers them in ~10–20 min`,
3242
+ );
3243
+ return released;
3244
+ }
3245
+ log(`[inbox.batch] handed back ${countEvents(released.length)} held on ${why}, for the next run to answer`);
3246
+ if (atCeiling.length) {
3247
+ log(`[inbox.batch] ${countEvents(atCeiling.length)} left to the requeue (at the redelivery ceiling)`);
3248
+ }
3249
+ return released;
3250
+ };
3251
+ // Everything a stopped run still carries. Taken once: the arrays are emptied
3252
+ // before the request, so a second caller finds nothing to send.
3253
+ const handBackCarryOnStop = () => {
3254
+ const carry = [...heldRetry, ...heldGreeting, ...tickUnsettled];
3255
+ heldRetry = [];
3256
+ heldGreeting = [];
3257
+ tickUnsettled = [];
3258
+ heldRetryFailures.clear();
3259
+ clearHeldRenewal();
3260
+ return carry.length ? handBackDeliveries(carry, 'stop') : Promise.resolve([]);
3176
3261
  };
3177
3262
 
3178
3263
  // Keep a long wait's leases alive. A wait shorter than one renewal interval
@@ -3202,9 +3287,13 @@ export const performRun = ({
3202
3287
  };
3203
3288
 
3204
3289
  // What the retry will actually do, for the failure report.
3205
- const describeHold = ({ held, released }, retry) => {
3290
+ const describeHold = ({ held, released, handedBack = [] }, retry) => {
3206
3291
  const parts = [];
3207
3292
  if (retry.circuitOpen) parts.push('circuit open');
3293
+ if (handedBack.length) {
3294
+ return [...parts, `stopping: handing ${countEvents(handedBack.length)} back to the server for the next run`]
3295
+ .join('; ');
3296
+ }
3208
3297
  if (released.length) {
3209
3298
  parts.push(
3210
3299
  `releasing ${countEvents(released.length)} after ${HELD_RETRY_MAX_FAILURES} failed attempts `
@@ -3537,8 +3626,29 @@ export const performRun = ({
3537
3626
  try { return await turn(); } finally { pollLiveness.arm(); }
3538
3627
  };
3539
3628
 
3629
+ // The scheduled next tick, so stop() can cancel it: a stopped run idling in
3630
+ // a 15-minute circuit wait otherwise stays alive until the timer fires,
3631
+ // which is why a walk on 2026-11-05 needed repeated signals to end it.
3632
+ let tickTimer = null;
3633
+ let tickInFlight = false;
3634
+ // stop() returns this: it resolves once the hand-back has answered, whether
3635
+ // the idle stop or the in-flight tick's end performs it.
3636
+ let stopped = null;
3637
+ let resolveStopped = () => {};
3540
3638
  const tick = async () => {
3639
+ tickTimer = null;
3541
3640
  if (!running) return;
3641
+ tickInFlight = true;
3642
+ try { await runTick(); } finally {
3643
+ tickInFlight = false;
3644
+ if (!running) {
3645
+ try { await handBackCarryOnStop(); } finally { resolveStopped(); }
3646
+ }
3647
+ }
3648
+ };
3649
+
3650
+ const runTick = async () => {
3651
+ tickUnsettled = [];
3542
3652
  let nextPollDelayMs = intervalMs;
3543
3653
  let completedModelTurn = false;
3544
3654
  let retryScheduled = false;
@@ -3567,8 +3677,9 @@ export const performRun = ({
3567
3677
  });
3568
3678
  pollLiveness.arm();
3569
3679
  // A stall fired while this request hung: the loop has already given up on
3570
- // it. A plain stop() falls through instead, to the group loop's own
3571
- // `running` check, which leaves the page's rows to requeue as it always has.
3680
+ // it, and `agent run` exits in onStall, so its page is left to the requeue.
3681
+ // A plain stop() falls through instead, to the group loop's own `running`
3682
+ // check, which hands the page back.
3572
3683
  if (pollStalled) return;
3573
3684
  const { events = [], inboxCount } = page;
3574
3685
  consecutiveAuthErrors = 0;
@@ -3626,18 +3737,30 @@ export const performRun = ({
3626
3737
  // The greeting window is counted once per poll, however many pods'
3627
3738
  // greetings this page carries (gate review of #3511).
3628
3739
  let greetingCarriedThisPoll = false;
3629
- // The claimed events a failure at `groupIndex` stops before they run.
3630
- // A digest-only group was never claimed, so it is not carried.
3740
+ // The events a failure at `groupIndex` stops before they run. A later
3741
+ // digest-only group never starts a turn of its own, so a retry does not
3742
+ // carry it.
3631
3743
  const untriedAfter = (groupIndex) => groups.slice(groupIndex + 1)
3632
3744
  .filter((later) => !later.every((event) => event.deliveryMode === 'digest'))
3633
3745
  .flat();
3746
+ // Every later group a stop must hand back. The server claims a digest
3747
+ // alongside a wake on the same page, and a private wake groups apart
3748
+ // from it, so a digest-only group here can be `delivered` to this run.
3749
+ const claimedAfter = (groupIndex) => groups.slice(groupIndex + 1).flat();
3634
3750
  for (let groupIndex = 0; groupIndex < groups.length; groupIndex += 1) {
3635
3751
  const group = groups[groupIndex];
3636
- if (!running) break;
3752
+ if (!running) {
3753
+ // Claimed by this tick's poll (or carried into it) and never run:
3754
+ // a stop that arrived mid-poll or mid-page (F182). Handed back when
3755
+ // the tick ends.
3756
+ heldRetry = [...heldRetry, ...group, ...claimedAfter(groupIndex)];
3757
+ break;
3758
+ }
3637
3759
  // A current kernel never claims a digest-only page. Guard a mixed
3638
3760
  // version rollout too: an ambient batch must not start a model turn.
3639
3761
  if (group.every((event) => event.deliveryMode === 'digest')) {
3640
3762
  log(`[inbox.batch] digest-only page (${group.length}) — no spawn or ack`);
3763
+ tickUnsettled.push(...group);
3641
3764
  continue;
3642
3765
  }
3643
3766
  if ((group[0].podId || podId) && !PRIVATE_RESPONSE_EVENT_TYPES.has(group[0].type)) {
@@ -3685,6 +3808,7 @@ export const performRun = ({
3685
3808
  });
3686
3809
  nextPollDelayMs = retry.delayMs;
3687
3810
  retryScheduled = true;
3811
+ tickUnsettled.push(...claimedAfter(groupIndex));
3688
3812
  const hold = await holdForRetry(failedEvents, untriedAfter(groupIndex));
3689
3813
  keepHeldLeases(retry.delayMs);
3690
3814
  const event = group[0];
@@ -3769,6 +3893,9 @@ export const performRun = ({
3769
3893
  );
3770
3894
  break;
3771
3895
  }
3896
+ // Items a stop cut off before they ran (refusal isolation checks
3897
+ // `running`), and any digest this batch left unread.
3898
+ tickUnsettled.push(...batch.entries.filter((entry) => !entry.result).map((entry) => entry.event));
3772
3899
  continue;
3773
3900
  }
3774
3901
  const [event] = group;
@@ -3802,6 +3929,7 @@ export const performRun = ({
3802
3929
  retryScheduled = true;
3803
3930
  // Carried to the retry like a failed batch: the event is claimed,
3804
3931
  // so the next poll would not return it.
3932
+ tickUnsettled.push(...claimedAfter(groupIndex));
3805
3933
  // eslint-disable-next-line no-await-in-loop
3806
3934
  const hold = await holdForRetry([event], untriedAfter(groupIndex));
3807
3935
  keepHeldLeases(retry.delayMs);
@@ -3877,6 +4005,7 @@ export const performRun = ({
3877
4005
  if (terminalError) {
3878
4006
  running = false;
3879
4007
  onError?.(terminalError);
4008
+ tickUnsettled.push(...claimedAfter(groupIndex));
3880
4009
  return;
3881
4010
  }
3882
4011
  onError?.(new Error(`Ack failed for ${event._id}: ${ackErr.message}`));
@@ -3929,15 +4058,26 @@ export const performRun = ({
3929
4058
  // names it, and a sibling's completed turn must not shorten the backoff.
3930
4059
  // A wait the loop schedules itself always ends, so it is not a stall.
3931
4060
  pollLiveness.pause();
3932
- if (running) setTimeoutImpl(tick, completedModelTurn && !retryScheduled ? 3000 : nextPollDelayMs);
4061
+ if (running) tickTimer = setTimeoutImpl(tick, completedModelTurn && !retryScheduled ? 3000 : nextPollDelayMs);
3933
4062
  };
3934
4063
 
3935
4064
  tick();
3936
4065
  return {
4066
+ // Resolves once anything held has been handed back. A tick in flight hands
4067
+ // back its own carry when it ends; an idle run does it here. A second
4068
+ // stop() returns the same promise.
3937
4069
  stop: () => {
4070
+ if (stopped) return stopped;
4071
+ stopped = new Promise((resolve) => { resolveStopped = resolve; });
3938
4072
  running = false;
3939
4073
  pollLiveness.stop();
3940
4074
  clearHeldRenewal();
4075
+ if (tickTimer !== null) {
4076
+ clearTimeoutImpl(tickTimer);
4077
+ tickTimer = null;
4078
+ }
4079
+ if (!tickInFlight) handBackCarryOnStop().finally(() => resolveStopped());
4080
+ return stopped;
3941
4081
  },
3942
4082
  };
3943
4083
  };