@cohortapp/agent-sdk 2.18.23 → 2.18.24

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.
@@ -345,6 +345,29 @@ export function fallbackNotice(o = {}) {
345
345
  // colleague tells them, so a notice may only assert what it saw.
346
346
  return `${about} was cut off part-way — the session running it stopped and a new one took over. I've picked it back up from where it stopped.`;
347
347
  }
348
+ // Gated on a retry actually being pending, not on the flag alone. A closed
349
+ // obligation really HAS stopped, so the final notice's "I've stopped trying"
350
+ // is true and must survive a caller that passes `paused` through both paths —
351
+ // the composer already narrows it, but this template is exported and is not
352
+ // entitled to assume its callers do.
353
+ if (o.paused && (o.willRetry || o.kind === "failure:retrying")) {
354
+ // A SPENT USAGE WINDOW IS NOT A BREAKAGE AND THE RETRY IS NOT RUNNING.
355
+ //
356
+ // The retrying line below asserts two things that are both false of a
357
+ // capped seat: that something "broke" (nothing did — a quota ran out on
358
+ // schedule) and that the work is running "now" (the rate-guard breaker is
359
+ // holding the spawn until the window resets). This branch exists because
360
+ // that fallback is not a rare path for THIS cause: the written notice is
361
+ // produced by spawning the same CLI that is capped, so when a seat is out
362
+ // of allowance the generator fails and this template is what the room
363
+ // actually reads. Every one of the ten notices measured on seat A028 on
364
+ // 2026-09-30 came through here.
365
+ //
366
+ // It promises only what the machinery does: one more attempt (RETRY_MAX),
367
+ // then a final notice either way. It does not promise to keep trying until
368
+ // the window reopens, because `sweepObligations` does not.
369
+ return `${about} hasn't gone through yet — ${cause}. I'll try again shortly and come back to you either way.`;
370
+ }
348
371
  if (o.willRetry || o.kind === "failure:retrying") {
349
372
  return `${about} broke before it finished: ${cause}. I'm running it again now.`;
350
373
  }
@@ -275,17 +275,93 @@ export const RATE_USAGE_LIMIT_HOLD_MS = num(process.env.RATE_USAGE_LIMIT_HOLD_MS
275
275
  */
276
276
  export function parseResetAt(text, deps) {
277
277
  if (!text || typeof text !== "string") return null;
278
- const m = /(?:reset|resets|resets at|resets in|try again at|available again at)\s+(\d{1,2})(?::(\d{2}))?\s*([ap])\.?\s?m\.?/i.exec(text);
278
+ // Lead-ins the providers actually use. "reset at" was missing and is the
279
+ // canonical Claude Code phrasing ("Your limit will reset at 3pm (UTC)") —
280
+ // the old alternation had `reset` and `resets at` but not `reset at`, so the
281
+ // one message this parser exists to read was the one it could not.
282
+ const m =
283
+ /(?:reset|resets|try again|available again|back)(?:\s+(?:at|in))?\s+(\d{1,2})(?::(\d{2}))?\s*([ap])\.?\s?m\.?/i.exec(text);
279
284
  if (!m) return null;
280
285
  const nowMs = clock(deps)();
281
286
  let hr = parseInt(m[1], 10) % 12;
282
287
  if (/p/i.test(m[3])) hr += 12;
283
288
  const min = m[2] ? parseInt(m[2], 10) : 0;
289
+
290
+ // THE STATED ZONE WINS OVER THE SEAT'S OWN.
291
+ //
292
+ // This used to resolve the wall clock in the daemon's local zone always, on
293
+ // the reasoning that a seat reads a message written for its own timezone.
294
+ // That is not true of either real message: Claude Code stamps "(UTC)", and
295
+ // this file's OWN test corpus carries "resets 9:40pm (Australia/Sydney)".
296
+ // Against a Gulf seat those are 4 and 6 hours of error, and the error is not
297
+ // cosmetic — `recordUsageLimit` holds the breaker until this instant, so
298
+ // reading it too early reopens into a still-spent window (a storm) and too
299
+ // late leaves the seat dark for hours after its quota returned. Both were
300
+ // observed shapes on this fleet.
301
+ const zone = statedZone(text);
302
+ const t = zone ? epochInZone(nowMs, hr, min, zone) : epochLocal(nowMs, hr, min);
303
+ if (t == null) return null;
304
+ return t <= nowMs ? t + 24 * 60 * 60 * 1000 : t;
305
+ }
306
+
307
+ /** The wall clock `hr:min` today, in the daemon's own zone. */
308
+ function epochLocal(nowMs, hr, min) {
284
309
  const cand = new Date(nowMs);
285
310
  cand.setHours(hr, min, 0, 0);
286
- let t = cand.getTime();
287
- if (t <= nowMs) t += 24 * 60 * 60 * 1000; // already past today → next occurrence
288
- return t;
311
+ return cand.getTime();
312
+ }
313
+
314
+ /**
315
+ * A timezone named in the message — "(UTC)", "(GMT)", a trailing "UTC", or an
316
+ * IANA "Area/City" in parentheses. null when the message names none, which is
317
+ * the case that keeps the old local-zone behaviour exactly as it was.
318
+ */
319
+ function statedZone(text) {
320
+ const paren = /\(([A-Za-z]+(?:\/[A-Za-z_+-]+)+)\)/.exec(text);
321
+ if (paren) return paren[1];
322
+ if (/\b(?:UTC|GMT)\b/i.test(text)) return "UTC";
323
+ return null;
324
+ }
325
+
326
+ /**
327
+ * The epoch ms of `hr:min` on the zone's CURRENT day, for an arbitrary IANA
328
+ * zone. Two passes because a zone's offset depends on the instant being
329
+ * resolved: the first guess picks an offset, the second re-resolves with it,
330
+ * which converges across a DST boundary where a single pass lands an hour out.
331
+ * Returns null for an unusable zone name rather than throwing — a malformed
332
+ * zone must degrade to "no reset time known", never take the daemon down.
333
+ */
334
+ function epochInZone(nowMs, hr, min, zone) {
335
+ try {
336
+ const parts = zoneParts(nowMs, zone);
337
+ let guess = Date.UTC(parts.year, parts.month - 1, parts.day, hr, min, 0, 0);
338
+ for (let i = 0; i < 2; i += 1) {
339
+ guess = Date.UTC(parts.year, parts.month - 1, parts.day, hr, min, 0, 0) - zoneOffsetMs(guess, zone);
340
+ }
341
+ return guess;
342
+ } catch {
343
+ return null;
344
+ }
345
+ }
346
+
347
+ /** The calendar date it currently is in `zone`. Throws on a bad zone name. */
348
+ function zoneParts(epochMs, zone) {
349
+ const f = new Intl.DateTimeFormat("en-US", {
350
+ timeZone: zone, hour12: false,
351
+ year: "numeric", month: "2-digit", day: "2-digit",
352
+ hour: "2-digit", minute: "2-digit", second: "2-digit",
353
+ });
354
+ const got = {};
355
+ for (const p of f.formatToParts(new Date(epochMs))) {
356
+ if (p.type !== "literal") got[p.type] = parseInt(p.value, 10);
357
+ }
358
+ return { year: got.year, month: got.month, day: got.day, hour: got.hour % 24, minute: got.minute, second: got.second };
359
+ }
360
+
361
+ /** `zone`'s UTC offset in ms at a given instant. */
362
+ function zoneOffsetMs(epochMs, zone) {
363
+ const p = zoneParts(epochMs, zone);
364
+ return Date.UTC(p.year, p.month - 1, p.day, p.hour, p.minute, p.second) - epochMs;
289
365
  }
290
366
 
291
367
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cohortapp/agent-sdk",
3
- "version": "2.18.23",
3
+ "version": "2.18.24",
4
4
  "description": "Cohort Agent SDK — autonomous AI colleague runtime. Deploy senior AI colleagues on dedicated Mac minis, wired to the Cohort operating surface.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -110,6 +110,7 @@ import {
110
110
  batchQuietMs,
111
111
  batchMaxSpanMs,
112
112
  } from "../../lib/assurance/batch.mjs";
113
+ import { classifyUsageLimit } from "../../lib/rate-guard.mjs";
113
114
 
114
115
  // ── Board mirror seams ───────────────────────────────────────────────────────
115
116
  // Imported lazily so a board module problem can never stop the daemon booting,
@@ -1118,6 +1119,11 @@ export function composeFailure(rec, o = {}) {
1118
1119
  cause: f.human || "the working session ended unexpectedly",
1119
1120
  topic: o.topic != null ? o.topic : noticeTopic(rec),
1120
1121
  willRetry: !!o.willRetry,
1122
+ // `paused` is set by the CLASSIFIER, not matched on a label here. The
1123
+ // composer has no business knowing which causes mean "held, not broken" —
1124
+ // classifyFailure already decided, and keeping that judgement in one place
1125
+ // is why a new held cause needs no edit to this file.
1126
+ paused: !!f.paused && !!o.willRetry,
1121
1127
  });
1122
1128
  }
1123
1129
 
@@ -1351,6 +1357,32 @@ export function composeInterrupted() {
1351
1357
  * @param {string} [o.stage]
1352
1358
  * @returns {{transient:boolean, label:string, human:string}}
1353
1359
  */
1360
+ /**
1361
+ * The cause clause for a spent usage window.
1362
+ *
1363
+ * Names the reset when `rate-guard` could parse one out of the provider's own
1364
+ * message, and says only "when the window resets" when it could not — the same
1365
+ * rule the rest of this file follows: assert what was observed, never a guess.
1366
+ * A wrong clock time is worse than no clock time, because a colleague plans
1367
+ * around it.
1368
+ *
1369
+ * @param {number|null} resetAt epoch ms, or null when unparseable
1370
+ */
1371
+ function usageCapHuman(resetAt) {
1372
+ if (typeof resetAt === "number" && Number.isFinite(resetAt)) {
1373
+ // "7:00pm", not "7:00 PM" — this lands mid-sentence in a message to a
1374
+ // colleague, and the locale default's caps read like a log line.
1375
+ const when = new Date(resetAt)
1376
+ .toLocaleTimeString("en-GB", { hour: "numeric", minute: "2-digit", hour12: true })
1377
+ .replace(/\s*([ap])\.?m\.?/i, (_, ap) => `${ap.toLowerCase()}m`);
1378
+ // Comma, not an em-dash: this clause is interpolated INTO a sentence that
1379
+ // already carries one ("… hasn't gone through yet — <cause>."), and two
1380
+ // dashes in one line read like a transcript rather than a colleague.
1381
+ return `I've used up my usage allowance for now, and it resets at ${when}`;
1382
+ }
1383
+ return "I've used up my usage allowance for now, and it comes back when the window resets";
1384
+ }
1385
+
1354
1386
  export function classifyFailure(o = {}) {
1355
1387
  const err = String(o.error || "");
1356
1388
  const code = o.code;
@@ -1365,6 +1397,42 @@ export function classifyFailure(o = {}) {
1365
1397
  if (/budget|spend cap|daily budget|essential-only/i.test(err)) {
1366
1398
  return { transient: false, label: "budget_refused", human: "I've hit my spend cap for today, so I can't run the work that would answer this" };
1367
1399
  }
1400
+ // A SPENT USAGE WINDOW IS NOT "AN ERROR", AND THE LAYER ALREADY KNOWS IT.
1401
+ //
1402
+ // `lib/rate-guard.mjs` recognises a spent usage window and the dispatcher
1403
+ // holds the breaker until it resets (dispatcher.mjs, two call sites). That
1404
+ // half worked. What did not is that THIS function — the one that decides what
1405
+ // a room is told — never asked. So a capped seat fell through to the generic
1406
+ // `exit_${code}` branch and told ten separate askers "the working session
1407
+ // ended with an error. I'm running it again now", ten times on 2026-09-30,
1408
+ // while the truth was a single fact with a known end time.
1409
+ //
1410
+ // Measured on seat A028 that day: ten asks, each one capped, each one told a
1411
+ // bare error. The owner read the room and diagnosed the cap by eye
1412
+ // ("looks like Jacob has hit his limit") — which is the tell that the notice
1413
+ // was withholding what the machine already had.
1414
+ //
1415
+ // PRECEDENCE, both directions, because USAGE_LIMIT_RE matches the bare words
1416
+ // "limit reached" and would otherwise steal two neighbours:
1417
+ // - AFTER the 429 branch: "rate limit reached" carries both signatures, and
1418
+ // a 429 is a recoverable provider blip that SHOULD be retried with
1419
+ // backoff, whereas a spent window must not be hammered.
1420
+ // - AFTER budget_refused: a local spend cap phrased "daily budget limit
1421
+ // reached" would land here and become transient — turning a refusal that
1422
+ // holds for the rest of the day into a retry. Those messages are ours and
1423
+ // their wording is known, so the narrow check goes first.
1424
+ // First match wins, so both neighbours keep precedence over this one.
1425
+ //
1426
+ // `transient` stays TRUE, and that is not an oversight. `sweepObligations`
1427
+ // reads it as "retry once more" (RETRY_MAX=1); false would send the ask
1428
+ // straight to `closeObligation({outcome:"failed"})` and the work would be
1429
+ // abandoned rather than picked up when the window reopens. The retry itself
1430
+ // is already cheap — the breaker refuses the spawn while the hold stands.
1431
+ // The defect being fixed here is the sentence, not the retry policy.
1432
+ const cap = classifyUsageLimit(err, o.deps);
1433
+ if (cap.isLimit) {
1434
+ return { transient: true, label: "usage_capped", paused: true, human: usageCapHuman(cap.resetAt) };
1435
+ }
1368
1436
  if (/out of memory|ENOMEM|low free memory/i.test(err)) {
1369
1437
  return { transient: true, label: "resource_starved", human: "my machine ran out of memory partway through" };
1370
1438
  }