@botbuddy/cli 1.47.1 → 1.48.0

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": "@botbuddy/cli",
3
- "version": "1.47.1",
3
+ "version": "1.48.0",
4
4
  "description": "BotBuddy — Swarm coordination CLI for multi-agent workflows",
5
5
  "type": "module",
6
6
  "bin": {
package/src/wait-core.mjs CHANGED
@@ -31,6 +31,10 @@ export const EXIT = Object.freeze({
31
31
  // BOT-2330: an exact managed-allocation cleanup failed. The waiter must not
32
32
  // report a successful terminal match when the signed Helper outcome failed.
33
33
  MANAGED_ALLOCATION_FAILED: 10,
34
+ // BOT-2360: the server ended this wait while the client was still parked on it — the
35
+ // liveness reaper abandoned it, it was cancelled, or its row is gone. The relay
36
+ // refuses the stream with a typed `wait_abandoned` error frame; re-arm from next_cursor.
37
+ ABANDONED: 11,
34
38
  });
35
39
 
36
40
  // BOT-2013: the uuid spellings Postgres accepts for a lease id (uuid_in), mirrored by the SQL
@@ -1756,6 +1760,20 @@ export async function runWaitLoop({
1756
1760
  if (parsed.error === "unauthorized" || parsed.error === "forbidden") {
1757
1761
  return finalize("error", { exitCode: EXIT.AUTH, error: parsed.error });
1758
1762
  }
1763
+ // BOT-2360: the relay refuses a stream bound to a wait the server already ended
1764
+ // (prod a0cd7b11 parked 54 min on one). Never reconnect to it: exit typed, with the
1765
+ // confirmed cursor so a re-arm replays everything after it.
1766
+ if (parsed.error === "wait_abandoned") {
1767
+ return finalize("abandoned", {
1768
+ exitCode: EXIT.ABANDONED,
1769
+ error: "wait_abandoned",
1770
+ state: {
1771
+ wait_session_id: typeof parsed.wait_session_id === "string" ? parsed.wait_session_id : waitSessionId ?? null,
1772
+ status: typeof parsed.status === "string" ? parsed.status : null,
1773
+ reason: typeof parsed.reason === "string" ? parsed.reason : null,
1774
+ },
1775
+ });
1776
+ }
1759
1777
  return finalize("error", { exitCode: EXIT.INTERNAL, error: parsed.error || "stream_error" });
1760
1778
  }
1761
1779
 
package/src/wait.mjs CHANGED
@@ -180,7 +180,12 @@ OUTPUT
180
180
  8 superseded (wait replaced server-side) · 9 lease lost (a
181
181
  lease:id= wait whose lease was reaped before it was granted;
182
182
  receipt outcome lease_lost + reap_reason — request a new
183
- lease). If the receipt has
183
+ lease) · 10 managed-allocation cleanup failed (BOT-2330)
184
+ · 11 abandoned (the server ended this wait while it
185
+ was parked — reaped after 180 s without a live stream,
186
+ or cancelled; receipt outcome abandoned +
187
+ state.status/reason — re-arm with --since <next_cursor>).
188
+ If the receipt has
184
189
  reacquire_lock (claim=true), acquire_lock again FIRST and re-run
185
190
  only on a queued/busy result (granted = you hold it — just resume);
186
191
  otherwise re-run from the receipt's next_cursor. docs/agent-wait.md.
@@ -548,11 +553,28 @@ export function leaseLostNotice(receipt) {
548
553
  `(reap_reason=${st.reap_reason ?? "unknown"}) — request a new lease (exit ${EXIT.LEASE_LOST})`;
549
554
  }
550
555
 
556
+ /**
557
+ * BOT-2360: the one stderr line for an `abandoned` receipt (null for any other outcome). The
558
+ * server ended this wait (its liveness reaper or a cancel) while the client was
559
+ * still parked; re-arming from next_cursor replays everything after the last frame consumed.
560
+ */
561
+ export function waitAbandonedNotice(receipt) {
562
+ if (receipt?.outcome !== "abandoned") return null;
563
+ const st = receipt.state ?? {};
564
+ const since = receipt.next_cursor != null ? ` --since ${receipt.next_cursor}` : "";
565
+ return `bb-wait: wait ${st.wait_session_id ?? "?"} was ended server-side (status=${st.status ?? "abandoned"}, ` +
566
+ `reason=${st.reason ?? "unknown"}) — re-arm the same conditions with${since || " a fresh wait"} (exit ${EXIT.ABANDONED})`;
567
+ }
568
+
551
569
  function writeLeaseLostNotice(receipt) {
552
- const notice = leaseLostNotice(receipt);
570
+ const notice = leaseLostNotice(receipt) ?? waitAbandonedNotice(receipt);
553
571
  if (notice) process.stderr.write(`${notice}\n`);
554
572
  }
555
573
 
574
+ // BOT-1228 / BOT-2360: outcomes whose wait_session the server already ended. The client
575
+ // never finalizes them (finalize_wait_session only transitions from active).
576
+ const SERVER_ENDED_OUTCOMES = new Set(["superseded", "abandoned"]);
577
+
556
578
  // Record the terminal outcome. Best-effort AND bounded: the receipt has already
557
579
  // been written to stdout before this runs, so a slow/failing finalize must never
558
580
  // delay the agent's wake or change the exit path. A short abort timeout caps how
@@ -596,7 +618,7 @@ async function finalizeWait(opts, waitSessionId, receipt, timeoutMs = 5000) {
596
618
  // A real SSE connection to the relay's spine tail. Returns an async iterable of
597
619
  // parsed frames. Server emits `id: <seq>` per signal and replays `seq > since`
598
620
  // on connect, so a reconnect never loses an event.
599
- function makeConnect(opts) {
621
+ export function makeConnect(opts) {
600
622
  // BOT-1649: mirror the relay's keepalive expiry roll into the 0600 cache. The
601
623
  // server bumps session_token_expires_at on connect and every keepalive, but
602
624
  // the cache keeps its register-time deadline — so a wait near the 8 h cap goes
@@ -633,16 +655,25 @@ function makeConnect(opts) {
633
655
  // signal tears the stalled socket down immediately, then the read rejects and
634
656
  // the stream ends so runWaitLoop reconnects.
635
657
  const ac = new AbortController();
636
- const res = await fetch(url, {
637
- headers: {
638
- Authorization: `Bearer ${opts.token}`,
639
- "x-agent-api-key": opts.token || "",
640
- Accept: "text/event-stream",
641
- // BOT-741: never let a proxy gzip-buffer an SSE stream.
642
- "Accept-Encoding": "identity",
643
- },
644
- signal: ac.signal,
645
- });
658
+ // BOT-2360: bound the wait for response headers. Unbounded, a connect that hangs on a
659
+ // loaded host or a stuck proxy sits silent past the wait reaper's grace (undici's own
660
+ // headers timeout is 300 s); bounded, the worst silent reconnect stays inside it.
661
+ const connectTimer = setTimeout(() => ac.abort(new Error("relay connect timed out")), waitConnectTimeoutMs());
662
+ let res;
663
+ try {
664
+ res = await fetch(url, {
665
+ headers: {
666
+ Authorization: `Bearer ${opts.token}`,
667
+ "x-agent-api-key": opts.token || "",
668
+ Accept: "text/event-stream",
669
+ // BOT-741: never let a proxy gzip-buffer an SSE stream.
670
+ "Accept-Encoding": "identity",
671
+ },
672
+ signal: ac.signal,
673
+ });
674
+ } finally {
675
+ clearTimeout(connectTimer);
676
+ }
646
677
  if (res.status === 401) return errorStream("unauthorized");
647
678
  if (res.status === 403) return errorStream("forbidden");
648
679
  if (!res.ok || !res.body) throw new Error(`relay responded ${res.status}`);
@@ -655,7 +686,7 @@ function makeConnect(opts) {
655
686
  // runs the global bb_wait_linear_feed_lagging RPC) whether the Linear ingest
656
687
  // feed is stale. Any failure -> false (non-fatal: the wait keeps its last known
657
688
  // degraded state rather than flapping on a probe blip).
658
- const FEED_LAG_PROBE_TIMEOUT_MS = 10_000;
689
+ export const FEED_LAG_PROBE_TIMEOUT_MS = 10_000;
659
690
 
660
691
  function makeFeedLagProbe(opts) {
661
692
  // `issues` = the armed `linear` conditions' target ticket keys. The relay
@@ -715,9 +746,20 @@ function makeFeedLagProbe(opts) {
715
746
  // runWaitLoop reconnects from the cursor, which re-bumps wait_sessions.last_seen_at
716
747
  // (and, with --heartbeat, agents.last_heartbeat) before the reaper's grace.
717
748
  // 70s ≈ 2.3 missed keepalives — long enough to never false-trip on jitter, short
718
- // enough that the reconnect lands inside the 90s last_seen reap window.
749
+ // enough that the reconnect lands inside the 180 s last_seen reap window (BOT-2360).
719
750
  export const DEFAULT_SSE_IDLE_TIMEOUT_MS = 70_000;
720
751
 
752
+ // BOT-2360: the longest a (re)connect may wait for the relay's response headers. With the
753
+ // idle watchdog (70 s), the backoff cap (15 s) and the feed-lag probe (10 s) it bounds a
754
+ // healthy client's worst silent gap at 125 s, under the 180 s wait-reaper grace with 55 s
755
+ // to spare (asserted in bot2360-abandoned-wait.test.mjs against the registered cron job).
756
+ export const WAIT_CONNECT_TIMEOUT_MS = 30_000;
757
+
758
+ function waitConnectTimeoutMs() {
759
+ const raw = Number(process.env.BOTBUDDY_WAIT_CONNECT_TIMEOUT_MS);
760
+ return Number.isFinite(raw) && raw > 0 ? raw : WAIT_CONNECT_TIMEOUT_MS;
761
+ }
762
+
721
763
  function sseIdleTimeoutMs() {
722
764
  const raw = Number(process.env.BOTBUDDY_WAIT_IDLE_TIMEOUT_MS);
723
765
  return Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_SSE_IDLE_TIMEOUT_MS;
@@ -1194,7 +1236,7 @@ async function deliverTerminalFinalization(checkpoint) {
1194
1236
  async function flushPendingFinalization(store, checkpoint) {
1195
1237
  if (!checkpoint.cloud_wait_session_id || !checkpoint.terminal_receipt ||
1196
1238
  (checkpoint.cloud_finalize_pending === false && checkpoint.cloud_finalized_at)) return checkpoint;
1197
- if (checkpoint.terminal_receipt.outcome === "superseded") {
1239
+ if (SERVER_ENDED_OUTCOMES.has(checkpoint.terminal_receipt.outcome)) {
1198
1240
  return store.update(checkpoint.local_wait_id, {
1199
1241
  cloud_finalize_pending: false,
1200
1242
  cloud_finalized_at: new Date().toISOString(),
@@ -1296,6 +1338,7 @@ function exitForRecoveredOutcome(receipt) {
1296
1338
  if (receipt?.outcome === "cancelled") return EXIT.MATCHED;
1297
1339
  if (receipt?.outcome === "timeout") return EXIT.TIMEOUT;
1298
1340
  if (receipt?.outcome === "superseded") return EXIT.SUPERSEDED;
1341
+ if (receipt?.outcome === "abandoned") return EXIT.ABANDONED;
1299
1342
  if (receipt?.error === "cursor_expired") return EXIT.CURSOR_EXPIRED;
1300
1343
  if (receipt?.error === "unauthorized" || receipt?.error === "forbidden") return EXIT.AUTH;
1301
1344
  return EXIT.BACKEND;
@@ -2095,7 +2138,7 @@ export async function runWait(argv, { recoveryLocalWaitId = null } = {}) {
2095
2138
  terminal_receipt: terminalReceipt,
2096
2139
  exit_code: state.exitCode,
2097
2140
  safe_cursor: terminalReceipt.next_cursor ?? state.cursor ?? checkpoint.safe_cursor,
2098
- cloud_finalize_pending: Boolean(waitSessionId && terminalReceipt.outcome !== "superseded"),
2141
+ cloud_finalize_pending: Boolean(waitSessionId && !SERVER_ENDED_OUTCOMES.has(terminalReceipt.outcome)),
2099
2142
  });
2100
2143
  terminalPersistedFromFrame = true;
2101
2144
  return;
@@ -2125,7 +2168,7 @@ export async function runWait(argv, { recoveryLocalWaitId = null } = {}) {
2125
2168
  terminal_receipt: terminalReceipt,
2126
2169
  exit_code: exitCode,
2127
2170
  safe_cursor: terminalReceipt.next_cursor ?? checkpoint.safe_cursor ?? null,
2128
- cloud_finalize_pending: Boolean(waitSessionId && terminalReceipt.outcome !== "superseded"),
2171
+ cloud_finalize_pending: Boolean(waitSessionId && !SERVER_ENDED_OUTCOMES.has(terminalReceipt.outcome)),
2129
2172
  });
2130
2173
  }
2131
2174
  emitReceipt(terminalReceipt, { versioned: true });
@@ -2134,7 +2177,8 @@ export async function runWait(argv, { recoveryLocalWaitId = null } = {}) {
2134
2177
  // ended_at/updated_at stamped). Skip the client finalize: the row is already
2135
2178
  // terminal (finalize_wait_session only transitions from active, so it'd be a
2136
2179
  // no-op) and `superseded` isn't a wait_session_status enum value anyway.
2137
- if (waitSessionId && receipt.outcome !== "superseded") {
2180
+ // BOT-2360: likewise `abandoned` — the relay refused the stream because the row is ended.
2181
+ if (waitSessionId && !SERVER_ENDED_OUTCOMES.has(receipt.outcome)) {
2138
2182
  const finalized = await finalizeWait(opts, waitSessionId, terminalReceipt);
2139
2183
  try {
2140
2184
  checkpoint = await store.update(checkpoint.local_wait_id, finalized.delivered