@commonlyai/cli 0.1.396 → 0.1.397

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.396",
3
+ "version": "0.1.397",
4
4
  "license": "Apache-2.0",
5
5
  "description": "The Commonly CLI — connect agents, manage pods, iterate fast",
6
6
  "type": "module",
@@ -68,6 +68,7 @@ import {
68
68
  import { catchUpBeforeTurn } from '../lib/pod-catch-up.js';
69
69
  import { readLongTerm, syncBack } from '../lib/memory-bridge.js';
70
70
  import { pollRetryPolicy } from '../lib/poll-retry.js';
71
+ import { clampHoldToLiveness, longPollWaitMs, wasHeld } from '../lib/long-poll.js';
71
72
  import {
72
73
  createIdleHeartbeat, createPollLiveness, formatStall, resolveIdleLineMs, resolvePollLivenessMs,
73
74
  } from '../lib/poll-liveness.js';
@@ -2275,6 +2276,10 @@ export const performRun = ({
2275
2276
  // How often a seat that keeps polling and finds nothing says so. Undefined
2276
2277
  // reads COMMONLY_IDLE_LINE_MS, then ten minutes (lib/poll-liveness.js).
2277
2278
  idleLineMs,
2279
+ // F597: the wait an empty inbox poll asks the server to hold it for
2280
+ // (lib/long-poll.js). Undefined derives it from the read timeout; 0 turns
2281
+ // the long-poll off. Tests pin a small value.
2282
+ longPollWaitMs: longPollWaitOverride,
2278
2283
  }) => {
2279
2284
  const stateKey = localKey || agentName;
2280
2285
  const supervising = superviseRuns ?? superviseRunsByDefault(adapter?.name);
@@ -4677,6 +4682,28 @@ export const performRun = ({
4677
4682
  // a 15-minute circuit wait otherwise stays alive until the timer fires,
4678
4683
  // which is why a walk on 2026-11-05 needed repeated signals to end it.
4679
4684
  let tickTimer = null;
4685
+ // F597: an idle seat's inbox poll is held by the server up to this long.
4686
+ // Never so long that the poll-liveness clock reads the hold as a wedge.
4687
+ const longPollWait = clampHoldToLiveness(
4688
+ longPollWaitOverride ?? longPollWaitMs(),
4689
+ resolvePollLivenessMs(pollLivenessMs),
4690
+ );
4691
+ // The held poll in flight, so stop() can end it instead of waiting it out.
4692
+ let holdAbort = null;
4693
+ const STOPPED_HOLD = Symbol('stopped-hold');
4694
+ const heldInboxPoll = async (holdMs) => {
4695
+ holdAbort = new AbortController();
4696
+ try {
4697
+ return await client.get('/api/agents/runtime/events', { ...inboxQuery(), waitMs: holdMs }, {
4698
+ signal: holdAbort.signal,
4699
+ });
4700
+ } catch (error) {
4701
+ if (!running && holdAbort.signal.aborted) return STOPPED_HOLD;
4702
+ throw error;
4703
+ } finally {
4704
+ holdAbort = null;
4705
+ }
4706
+ };
4680
4707
  let tickInFlight = false;
4681
4708
  // stop() returns this: it resolves once the hand-back has answered, whether
4682
4709
  // the idle stop or the in-flight tick's end performs it.
@@ -4721,14 +4748,26 @@ export const performRun = ({
4721
4748
  // Only wake events count: the server's page cap is on wakes, and a
4722
4749
  // carried digest row takes no body (CodeRabbit on #3511).
4723
4750
  // F237: a full carry in an outage claims nothing new (inboxQuery).
4724
- const page = await client.get('/api/agents/runtime/events', inboxQuery());
4751
+ // F597: with nothing carried, an empty inbox asks the server to hold the
4752
+ // poll (long-poll). A carry is never held: its retry runs on this tick.
4753
+ const holdMs = heldRetry.length || heldGreeting.length ? 0 : longPollWait;
4754
+ const pollStartedAt = Date.now();
4755
+ const page = holdMs > 0 ? await heldInboxPoll(holdMs) : await client.get('/api/agents/runtime/events', inboxQuery());
4725
4756
  pollLiveness.arm();
4726
4757
  // A stall fired while this request hung: the loop has already given up on
4727
4758
  // it, and `agent run` exits in onStall, so its page is left to the requeue.
4728
4759
  // A plain stop() falls through instead, to the group loop's own `running`
4729
4760
  // check, which hands the page back.
4730
4761
  if (pollStalled) return;
4762
+ // stop() ended a held poll: nothing was claimed, nothing to hand back.
4763
+ if (page === STOPPED_HOLD) return;
4731
4764
  const { events = [], inboxCount } = page;
4765
+ // An empty answer the server held: the next poll goes at once, since the
4766
+ // hold was the wait. One that came back fast (an older server that
4767
+ // ignores waitMs) keeps the ordinary interval, so the loop never spins.
4768
+ if (!events.length && wasHeld({ requestedMs: holdMs, elapsedMs: Date.now() - pollStartedAt })) {
4769
+ nextPollDelayMs = 0;
4770
+ }
4732
4771
  consecutiveAuthErrors = 0;
4733
4772
  consecutivePollFailures = 0;
4734
4773
  // A deployed CLI can briefly run against an older server that still
@@ -5301,6 +5340,8 @@ export const performRun = ({
5301
5340
  running = false;
5302
5341
  pollLiveness.stop();
5303
5342
  clearHeldRenewal();
5343
+ // A held poll would otherwise keep the stop waiting for up to its wait.
5344
+ holdAbort?.abort();
5304
5345
  if (tickTimer !== null) {
5305
5346
  clearTimeoutImpl(tickTimer);
5306
5347
  tickTimer = null;
package/src/lib/api.js CHANGED
@@ -7,6 +7,7 @@
7
7
 
8
8
  import { resolveInstanceUrl, getToken, resolveInstance } from './config.js';
9
9
  import { CLI } from './cli-hint.js';
10
+ import { capTimeoutMs } from './cap-timeout.js';
10
11
 
11
12
  const headers = (token, extra = {}) => ({
12
13
  'Content-Type': 'application/json',
@@ -65,17 +66,9 @@ const handleResponse = async (res, session = null) => {
65
66
  // (TASK-025) only handles a fetch that throws, so a timeout throws: it is an
66
67
  // ordinary failed request, retried with backoff, and never an ack.
67
68
  //
68
- // Reads get the base timeout; writes and uploads carry a body and a server-side
69
- // write, so they get a multiple of it. COMMONLY_CAP_TIMEOUT_MS sets the base.
70
- export const CAP_TIMEOUT_DEFAULT_MS = 30_000;
71
- const TIMEOUT_SCALE = { read: 1, write: 2, upload: 4 };
72
-
73
- export const capTimeoutMs = (kind, { baseMs, env = process.env } = {}) => {
74
- const fromEnv = Number(env.COMMONLY_CAP_TIMEOUT_MS);
75
- const base = [baseMs, fromEnv].find((value) => Number.isFinite(value) && value > 0)
76
- ?? CAP_TIMEOUT_DEFAULT_MS;
77
- return Math.min(base * (TIMEOUT_SCALE[kind] || 1), 2_147_483_647);
78
- };
69
+ // The numbers live in cap-timeout.js: reads get the base timeout, writes and
70
+ // uploads a multiple of it, and COMMONLY_CAP_TIMEOUT_MS sets the base.
71
+ export { CAP_TIMEOUT_DEFAULT_MS, capTimeoutMs } from './cap-timeout.js';
79
72
 
80
73
  // A caller's own signal (doctor, and the 5s identity and skills reads in the
81
74
  // run loop) still applies; the hard timeout is added beside it, never instead.
@@ -0,0 +1,17 @@
1
+ /**
2
+ * The CAP request timeout (TASK-338), on its own so modules that only need the
3
+ * number (the long-poll's wait, lib/long-poll.js) don't import the HTTP client.
4
+ * api.js re-exports both names; see its comment for why every request has one.
5
+ *
6
+ * Reads get the base timeout; writes and uploads carry a body and a server-side
7
+ * write, so they get a multiple of it. COMMONLY_CAP_TIMEOUT_MS sets the base.
8
+ */
9
+ export const CAP_TIMEOUT_DEFAULT_MS = 30_000;
10
+ const TIMEOUT_SCALE = { read: 1, write: 2, upload: 4 };
11
+
12
+ export const capTimeoutMs = (kind, { baseMs, env = process.env } = {}) => {
13
+ const fromEnv = Number(env.COMMONLY_CAP_TIMEOUT_MS);
14
+ const base = [baseMs, fromEnv].find((value) => Number.isFinite(value) && value > 0)
15
+ ?? CAP_TIMEOUT_DEFAULT_MS;
16
+ return Math.min(base * (TIMEOUT_SCALE[kind] || 1), 2_147_483_647);
17
+ };
@@ -0,0 +1,50 @@
1
+ /**
2
+ * F597: the events poll's long-poll (`GET /api/agents/runtime/events?waitMs=`).
3
+ *
4
+ * A current server holds an empty poll open up to `waitMs` (at most 25 s) and
5
+ * answers as soon as an event can be claimed, so an idle agent asks about once
6
+ * per 25 s instead of every ~5 s, and a new event still arrives at once.
7
+ *
8
+ * An older server ignores the parameter and answers an empty poll at once.
9
+ * The loop must then keep its normal interval, never spin: an empty answer
10
+ * that came back in well under the requested wait was not held, and is
11
+ * treated exactly like today's empty poll.
12
+ */
13
+ import { capTimeoutMs } from './cap-timeout.js';
14
+
15
+ export const LONG_POLL_MAX_WAIT_MS = 25_000;
16
+ // The hold must end, and its answer arrive, before the request's own timeout.
17
+ export const LONG_POLL_TIMEOUT_MARGIN_MS = 5_000;
18
+ // Below this the hold buys nothing over the ordinary interval.
19
+ const LONG_POLL_MIN_WAIT_MS = 1_000;
20
+
21
+ /** The wait to ask for: 0 (no long-poll) when the read timeout leaves no room. */
22
+ export const longPollWaitMs = ({ env = process.env } = {}) => {
23
+ const room = capTimeoutMs('read', { env }) - LONG_POLL_TIMEOUT_MARGIN_MS;
24
+ const wait = Math.min(LONG_POLL_MAX_WAIT_MS, room);
25
+ return wait >= LONG_POLL_MIN_WAIT_MS ? wait : 0;
26
+ };
27
+
28
+ /**
29
+ * The hold a loop may ask for under its poll-liveness limit
30
+ * (lib/poll-liveness.js): the liveness clock runs while the poll is in flight,
31
+ * so a hold near the limit would read as a wedged loop and stop the run. The
32
+ * hold ends a margin before the limit (5 s or a quarter of it, whichever is
33
+ * larger); if what is left is under LONG_POLL_MIN_LIVENESS_HOLD_MS, no hold.
34
+ */
35
+ export const LONG_POLL_MIN_LIVENESS_HOLD_MS = 3_000;
36
+ export const clampHoldToLiveness = (holdMs, livenessMs) => {
37
+ if (!(holdMs > 0)) return 0;
38
+ if (!Number.isFinite(livenessMs) || livenessMs <= 0) return holdMs;
39
+ const room = Math.floor(livenessMs - Math.max(5_000, livenessMs / 4));
40
+ return room >= LONG_POLL_MIN_LIVENESS_HOLD_MS ? Math.min(holdMs, room) : 0;
41
+ };
42
+
43
+ /**
44
+ * Whether an empty answer was a held one, so the next poll can go at once.
45
+ * Half the requested wait is the line: an old server answers in milliseconds,
46
+ * a held poll that timed out answers at about the full wait.
47
+ */
48
+ export const wasHeld = ({ requestedMs, elapsedMs }) => (
49
+ requestedMs > 0 && elapsedMs >= requestedMs / 2
50
+ );
package/src/lib/poller.js CHANGED
@@ -11,6 +11,7 @@ import { formatDigestFrame } from './digest-frame.js';
11
11
  import { EMPTY_OUTPUT } from './claim-outcome.js';
12
12
  import { createPollLiveness, formatStall, resolvePollLivenessMs } from './poll-liveness.js';
13
13
  import { CLI } from './cli-hint.js';
14
+ import { clampHoldToLiveness, longPollWaitMs as defaultLongPollWaitMs, wasHeld } from './long-poll.js';
14
15
 
15
16
  // Delivery failures that must stop a consumer rather than fall through to the
16
17
  // normal at-least-once retry path. A stale delivery belongs to a replacement
@@ -44,6 +45,9 @@ export const startPoller = ({
44
45
  pollLivenessMs, // TASK-338: see lib/poll-liveness.js
45
46
  pollLivenessCheckMs,
46
47
  onPollStalled, // ({ stalledMs }) => void; the connect command exits on it
48
+ // F597: how long an empty poll asks the server to hold it (lib/long-poll.js).
49
+ // Undefined derives it from the read timeout; 0 turns the long-poll off.
50
+ longPollWaitMs,
47
51
  }) => {
48
52
  const client = createClient({ instance: instanceUrl, token });
49
53
  let running = true;
@@ -55,6 +59,10 @@ export const startPoller = ({
55
59
  let consecutiveAuthErrors = 0;
56
60
  const MAX_AUTH_ERRORS = 3;
57
61
  let pollStalled = false;
62
+ // Never so long that the poll-liveness clock reads the hold as a wedge.
63
+ const holdMs = clampHoldToLiveness(longPollWaitMs ?? defaultLongPollWaitMs(), resolvePollLivenessMs(pollLivenessMs));
64
+ // The poll in flight, so stop() ends a held one instead of waiting it out.
65
+ let pollAbort = null;
58
66
  const pollLiveness = createPollLiveness({
59
67
  limitMs: resolvePollLivenessMs(pollLivenessMs),
60
68
  checkEveryMs: pollLivenessCheckMs,
@@ -68,21 +76,41 @@ export const startPoller = ({
68
76
  },
69
77
  });
70
78
 
79
+ let nextDelayMs = intervalMs;
71
80
  const poll = async () => {
72
81
  if (!running) return;
82
+ nextDelayMs = intervalMs;
73
83
 
74
84
  try {
75
85
  // Same clock as `agent run`: running from here to the scheduled wait,
76
86
  // paused while the local handler takes the event.
77
87
  pollLiveness.arm();
78
- const page = await client.get('/api/agents/runtime/events', {
79
- agentName,
80
- instanceId,
81
- limit: 10,
82
- });
88
+ pollAbort = new AbortController();
89
+ const pollStartedAt = Date.now();
90
+ let page;
91
+ try {
92
+ page = await client.get('/api/agents/runtime/events', {
93
+ agentName,
94
+ instanceId,
95
+ limit: 10,
96
+ ...(holdMs > 0 ? { waitMs: holdMs } : {}),
97
+ }, { signal: pollAbort.signal });
98
+ } catch (pollErr) {
99
+ // stop() ended a held poll: not a failure, and nothing was claimed.
100
+ if (!running && pollAbort.signal.aborted) return;
101
+ throw pollErr;
102
+ } finally {
103
+ pollAbort = null;
104
+ }
83
105
  pollLiveness.arm();
84
106
  if (pollStalled) return;
85
107
  const { events = [] } = page;
108
+ // An empty answer the server held (F597): poll again at once, the hold
109
+ // was the wait. A fast empty answer (an older server ignores waitMs)
110
+ // keeps the ordinary interval, so the loop never spins.
111
+ nextDelayMs = !events.length && wasHeld({ requestedMs: holdMs, elapsedMs: Date.now() - pollStartedAt })
112
+ ? 0
113
+ : intervalMs;
86
114
 
87
115
  // A digest is received context, not a webhook invocation. The runtime
88
116
  // inbox claims it only alongside a wake from the same pod.
@@ -185,7 +213,7 @@ export const startPoller = ({
185
213
  }
186
214
 
187
215
  pollLiveness.pause();
188
- if (running) setTimeout(poll, intervalMs);
216
+ if (running) setTimeout(poll, nextDelayMs);
189
217
  };
190
218
 
191
219
  // Start immediately
@@ -195,6 +223,7 @@ export const startPoller = ({
195
223
  stop: () => {
196
224
  running = false;
197
225
  pollLiveness.stop();
226
+ pollAbort?.abort();
198
227
  },
199
228
  };
200
229
  };