@integrity-labs/agt-cli 0.28.1280 → 0.28.1282

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 (29) hide show
  1. package/dist/{api-client-QEV6AB73.js → api-client-5L5TDFEN.js} +3 -3
  2. package/dist/bin/agt.js +7 -7
  3. package/dist/{chunk-47ARAO23.js → chunk-AG2YIBH2.js} +7 -1
  4. package/dist/{chunk-47ARAO23.js.map → chunk-AG2YIBH2.js.map} +1 -1
  5. package/dist/{chunk-FVW5O7NY.js → chunk-EUD5VDGR.js} +2 -2
  6. package/dist/{chunk-HHEN4FTL.js → chunk-FP4Z5C4N.js} +3 -3
  7. package/dist/{chunk-BJKY5764.js → chunk-KZ55FIP5.js} +2 -2
  8. package/dist/{chunk-TICHDHYF.js → chunk-PLL64X3Q.js} +5 -5
  9. package/dist/{chunk-5MI3GRHT.js → chunk-URE73ODK.js} +6 -3
  10. package/dist/{chunk-5MI3GRHT.js.map → chunk-URE73ODK.js.map} +1 -1
  11. package/dist/{claude-code-updater-BHSYASF3.js → claude-code-updater-C7BXV6S7.js} +3 -3
  12. package/dist/{claude-pair-runtime-27FK2QO2.js → claude-pair-runtime-7W5TM3MA.js} +3 -3
  13. package/dist/lib/manager-worker.js +356 -28
  14. package/dist/lib/manager-worker.js.map +1 -1
  15. package/dist/mcp/index.js +1 -0
  16. package/dist/{persistent-session-WBWYC4XL.js → persistent-session-C6G3R6BI.js} +4 -4
  17. package/dist/{responsiveness-probe-BLLWDXE4.js → responsiveness-probe-Q4GRRSHY.js} +4 -4
  18. package/dist/{session-auth-dead-NJR7X5T6.js → session-auth-dead-MAJHZEHU.js} +3 -3
  19. package/package.json +1 -1
  20. /package/dist/{api-client-QEV6AB73.js.map → api-client-5L5TDFEN.js.map} +0 -0
  21. /package/dist/{chunk-FVW5O7NY.js.map → chunk-EUD5VDGR.js.map} +0 -0
  22. /package/dist/{chunk-HHEN4FTL.js.map → chunk-FP4Z5C4N.js.map} +0 -0
  23. /package/dist/{chunk-BJKY5764.js.map → chunk-KZ55FIP5.js.map} +0 -0
  24. /package/dist/{chunk-TICHDHYF.js.map → chunk-PLL64X3Q.js.map} +0 -0
  25. /package/dist/{claude-code-updater-BHSYASF3.js.map → claude-code-updater-C7BXV6S7.js.map} +0 -0
  26. /package/dist/{claude-pair-runtime-27FK2QO2.js.map → claude-pair-runtime-7W5TM3MA.js.map} +0 -0
  27. /package/dist/{persistent-session-WBWYC4XL.js.map → persistent-session-C6G3R6BI.js.map} +0 -0
  28. /package/dist/{responsiveness-probe-BLLWDXE4.js.map → responsiveness-probe-Q4GRRSHY.js.map} +0 -0
  29. /package/dist/{session-auth-dead-NJR7X5T6.js.map → session-auth-dead-MAJHZEHU.js.map} +0 -0
@@ -13,9 +13,9 @@ import {
13
13
  probeClaudeInstalls,
14
14
  readsAsNativeInstall,
15
15
  shouldRunClaudeCodeUpdater
16
- } from "./chunk-BJKY5764.js";
16
+ } from "./chunk-KZ55FIP5.js";
17
17
  import "./chunk-XWVM4KPK.js";
18
- import "./chunk-47ARAO23.js";
18
+ import "./chunk-AG2YIBH2.js";
19
19
  import "./chunk-AIUIMEUS.js";
20
20
  import "./chunk-DGUM43GV.js";
21
21
  export {
@@ -34,4 +34,4 @@ export {
34
34
  readsAsNativeInstall,
35
35
  shouldRunClaudeCodeUpdater
36
36
  };
37
- //# sourceMappingURL=claude-code-updater-BHSYASF3.js.map
37
+ //# sourceMappingURL=claude-code-updater-C7BXV6S7.js.map
@@ -10,7 +10,7 @@ import {
10
10
  import {
11
11
  redactPaneFrame,
12
12
  sanitizeTerminalFrame
13
- } from "./chunk-47ARAO23.js";
13
+ } from "./chunk-AG2YIBH2.js";
14
14
  import {
15
15
  CLAUDE_CONFIG_DIR_ENV,
16
16
  claudeConfigDirFor,
@@ -323,7 +323,7 @@ async function spawnPairSession(session) {
323
323
  return { ok: true };
324
324
  } catch {
325
325
  }
326
- const { resolveClaudeBinary } = await import("./persistent-session-WBWYC4XL.js");
326
+ const { resolveClaudeBinary } = await import("./persistent-session-C6G3R6BI.js");
327
327
  const claudeBin = resolveClaudeBinary();
328
328
  const pairEnv = {
329
329
  ...process.env,
@@ -838,4 +838,4 @@ export {
838
838
  startClaudePair,
839
839
  submitClaudePairCode
840
840
  };
841
- //# sourceMappingURL=claude-pair-runtime-27FK2QO2.js.map
841
+ //# sourceMappingURL=claude-pair-runtime-7W5TM3MA.js.map
@@ -70,7 +70,7 @@ import {
70
70
  tripClass,
71
71
  writeEtcEnvironment,
72
72
  writeProfileDScript
73
- } from "../chunk-TICHDHYF.js";
73
+ } from "../chunk-PLL64X3Q.js";
74
74
  import {
75
75
  ApiError,
76
76
  adoptHostKeyInProcess,
@@ -88,7 +88,7 @@ import {
88
88
  probeHostKey,
89
89
  requireHost,
90
90
  setConfigHash
91
- } from "../chunk-HHEN4FTL.js";
91
+ } from "../chunk-FP4Z5C4N.js";
92
92
  import {
93
93
  BLOCKED_ON_PROMPT_DECISION,
94
94
  CHANNEL_SECRET_ENV_KEYS,
@@ -180,7 +180,7 @@ import {
180
180
  webFetchBaselineValue,
181
181
  webFetchRestartNeeded,
182
182
  writeEgressAllowlist
183
- } from "../chunk-5MI3GRHT.js";
183
+ } from "../chunk-URE73ODK.js";
184
184
  import {
185
185
  isAgentIdle,
186
186
  isStaleForToday,
@@ -191,7 +191,7 @@ import {
191
191
  subagentActivityAgeSeconds,
192
192
  subagentTranscriptDir,
193
193
  transcriptActivityAgeSeconds
194
- } from "../chunk-FVW5O7NY.js";
194
+ } from "../chunk-EUD5VDGR.js";
195
195
  import {
196
196
  classifyUnanswerablePane,
197
197
  focusedConfirmDialogBlock,
@@ -217,7 +217,7 @@ import {
217
217
  runSafeCleanup,
218
218
  tightestDiskStat,
219
219
  withPackageCacheLock
220
- } from "../chunk-BJKY5764.js";
220
+ } from "../chunk-KZ55FIP5.js";
221
221
  import {
222
222
  parsePsRows,
223
223
  reapOrphanChannelMcps
@@ -346,7 +346,7 @@ import {
346
346
  stabiliseResetInstant,
347
347
  sumTranscriptUsageInWindow,
348
348
  summarizeTranscriptActivity
349
- } from "../chunk-47ARAO23.js";
349
+ } from "../chunk-AG2YIBH2.js";
350
350
  import {
351
351
  CLAUDE_CONFIG_DIR_ENV,
352
352
  claudeConfigDirFor,
@@ -369,6 +369,157 @@ import {
369
369
  } from "../chunk-FIGZJ6AU.js";
370
370
  import "../chunk-DGUM43GV.js";
371
371
 
372
+ // src/lib/credit-exhaustion.ts
373
+ var CREDIT_EXHAUSTED_PATTERN = /credit balance (?:is )?too low/i;
374
+ var PANE_CREDIT_EXHAUSTED_PATTERN = /^credit balance (?:is )?too low\s*·\s*add funds\s*$/i;
375
+ var RECOVERY_REPORT_MS = 60 * 60 * 1e3;
376
+ var RESULT_LINE = /^\s+⎿\s*(.*)$/;
377
+ function isCreditExhaustedText(text) {
378
+ return typeof text === "string" && CREDIT_EXHAUSTED_PATTERN.test(text);
379
+ }
380
+ function isPaneCreditLine(line) {
381
+ return typeof line === "string" && PANE_CREDIT_EXHAUSTED_PATTERN.test(line);
382
+ }
383
+ function paneResultSighting(rawLog) {
384
+ if (typeof rawLog !== "string") return { ordinal: 0, latest: null };
385
+ const stripped = rawLog.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, "");
386
+ let ordinal = 0;
387
+ let latest = null;
388
+ for (const line of stripped.split("\n")) {
389
+ const m = RESULT_LINE.exec(line);
390
+ if (m) {
391
+ ordinal += 1;
392
+ latest = (m[1] ?? "").trim();
393
+ }
394
+ }
395
+ return { ordinal, latest };
396
+ }
397
+ function isNewPaneResult(args) {
398
+ return args.previous !== void 0 && args.ordinal !== args.previous;
399
+ }
400
+ var PROBE_INTERVAL_MS = 10 * 60 * 1e3;
401
+ var PROBE_MODEL = "claude-haiku-4-5-20251001";
402
+ var CreditExhaustionTracker = class {
403
+ hitFingerprint = null;
404
+ lastHitMs = null;
405
+ lastEvidence = null;
406
+ lastSuccessMs = null;
407
+ successFingerprint = null;
408
+ lastProbeMs = null;
409
+ serverFlagFingerprint = null;
410
+ /**
411
+ * Record a sighting on the key with fingerprint `fp`. A string that does not
412
+ * match, or an unknown key, is ignored: a verdict that cannot be bound to a
413
+ * credential is not reported.
414
+ */
415
+ noteError(source, text, fp, nowMs) {
416
+ if (!isCreditExhaustedText(text) || !isFingerprint(fp)) return false;
417
+ this.hitFingerprint = fp;
418
+ this.lastHitMs = nowMs;
419
+ this.lastEvidence = `${source}: ${String(text).replace(/\s+/g, " ").trim().slice(0, 280)}`;
420
+ return true;
421
+ }
422
+ /** A probe on the key with fingerprint `fp` SUCCEEDED. */
423
+ noteSuccess(fp, nowMs) {
424
+ if (!isFingerprint(fp)) return;
425
+ this.lastSuccessMs = nowMs;
426
+ this.successFingerprint = fp;
427
+ }
428
+ /** Is the key with fingerprint `fp` out of credit, on the evidence held? */
429
+ isExhausted(fp) {
430
+ if (!isFingerprint(fp) || this.hitFingerprint !== fp || this.lastHitMs === null) return false;
431
+ return !(this.successFingerprint === fp && this.lastSuccessMs !== null && this.lastSuccessMs > this.lastHitMs);
432
+ }
433
+ /**
434
+ * The heartbeat response's stored flag: the fingerprint of the key the API
435
+ * holds as out of credit, or null. The STORED flag is the source of truth, so
436
+ * a restarted manager (which remembers no sighting), or one whose recovery
437
+ * report lapsed undelivered, keeps probing while the API still holds the flag.
438
+ */
439
+ noteServerFlag(fp) {
440
+ this.serverFlagFingerprint = isFingerprint(fp) ? fp : null;
441
+ }
442
+ /** Does the API's stored flag name exactly this (well-formed) key? */
443
+ serverFlagMatches(fp) {
444
+ return isFingerprint(fp) && this.serverFlagFingerprint === fp;
445
+ }
446
+ /**
447
+ * Is a probe due now? Only while flagged (on this process's evidence, or the
448
+ * API's stored flag for this key), at most once per interval.
449
+ *
450
+ * CodeRabbit on 5fc19a7069: an UNKNOWN local key (`fp` null, i.e. a restarted
451
+ * manager that has not run /host/exchange yet, which on a host with no agents
452
+ * is forever) counts as flagged when the API holds a flag. The caller then
453
+ * loads the key and re-checks with the real fingerprint, so a flag about some
454
+ * OTHER key never gets that key probed.
455
+ */
456
+ probeDue(fp, nowMs) {
457
+ const serverFlagged = this.serverFlagFingerprint !== null && (fp === null || fp === void 0 || this.serverFlagFingerprint === fp);
458
+ const flagged = this.isExhausted(fp) || serverFlagged;
459
+ if (!flagged) return false;
460
+ return this.lastProbeMs === null || nowMs - this.lastProbeMs >= PROBE_INTERVAL_MS;
461
+ }
462
+ /** Mark a probe as started. No retries: the next one waits a full interval. */
463
+ noteProbeStarted(nowMs) {
464
+ this.lastProbeMs = nowMs;
465
+ }
466
+ /**
467
+ * The heartbeat's `claude_credit` field for the CURRENT key, or undefined to
468
+ * omit it. Sent only on an `api_key` host with a known key fingerprint.
469
+ *
470
+ * - Exhausted on this key: sent.
471
+ * - A probe succeeded on this key within {@link RECOVERY_REPORT_MS}: sent as
472
+ * `exhausted: false`, so the API clears the status and closes the alert.
473
+ * - Anything about a different key, or no evidence: omitted.
474
+ */
475
+ heartbeatField(mode, fp, nowMs) {
476
+ if (mode !== "api_key" || !isFingerprint(fp)) return void 0;
477
+ if (this.isExhausted(fp)) {
478
+ return {
479
+ exhausted: true,
480
+ key_fingerprint: fp,
481
+ ...this.lastEvidence ? { evidence: this.lastEvidence } : {},
482
+ ...this.lastHitMs !== null ? { observed_at: new Date(this.lastHitMs).toISOString() } : {}
483
+ };
484
+ }
485
+ if (this.successFingerprint === fp && this.lastSuccessMs !== null && nowMs - this.lastSuccessMs < RECOVERY_REPORT_MS) {
486
+ return { exhausted: false, key_fingerprint: fp };
487
+ }
488
+ return void 0;
489
+ }
490
+ };
491
+ function isFingerprint(fp) {
492
+ return typeof fp === "string" && /^[0-9a-f]{8}$/.test(fp);
493
+ }
494
+ var creditExhaustion = new CreditExhaustionTracker();
495
+ async function probeCredit(apiKey, opts = {}) {
496
+ const doFetch = opts.fetchImpl ?? fetch;
497
+ let res;
498
+ try {
499
+ res = await doFetch(opts.url ?? "https://api.anthropic.com/v1/messages", {
500
+ method: "POST",
501
+ headers: { "Content-Type": "application/json", "x-api-key": apiKey, "anthropic-version": "2023-06-01" },
502
+ body: JSON.stringify({ model: PROBE_MODEL, max_tokens: 1, messages: [{ role: "user", content: "ok" }] }),
503
+ signal: AbortSignal.timeout(opts.timeoutMs ?? 15e3)
504
+ });
505
+ } catch (err) {
506
+ return { other: err?.name ?? "fetch_failed" };
507
+ }
508
+ if (res.ok) return "ok";
509
+ let message = "";
510
+ try {
511
+ const body = await res.json();
512
+ message = typeof body?.error?.message === "string" ? body.error.message : "";
513
+ } catch {
514
+ message = "";
515
+ }
516
+ return isCreditExhaustedText(message) ? "credit_exhausted" : { other: String(res.status) };
517
+ }
518
+ function evalBackendSharesHostKey(kind) {
519
+ const k = (kind ?? "").trim().toLowerCase();
520
+ return k === "" || k === "claude-p";
521
+ }
522
+
372
523
  // src/lib/manager-restart-gate.ts
373
524
  import { execFileSync } from "child_process";
374
525
  var MANAGER_RESTART_REASON = "manager-restart";
@@ -467,6 +618,14 @@ var ConfigReloadLedger = class {
467
618
  * b4cfce82 hit). Cleared whenever the reload is re-torn-down or acked.
468
619
  */
469
620
  freshRenderAt = /* @__PURE__ */ new Map();
621
+ /**
622
+ * ENG-12141: the RENDER REVISION of that fresh render, i.e. a hash of the
623
+ * `.mcp.json` exactly as a spawn would load it (`projectMcpHash`, spawn view).
624
+ * A later fresh render with a different revision is a different config, so the
625
+ * marker moves to it; one with the same revision is the same config, so the
626
+ * earliest stays. See `noteFreshRender`.
627
+ */
628
+ freshRenderRevision = /* @__PURE__ */ new Map();
470
629
  /** What the poll does with this agent's integration-change request. Records a teardown. */
471
630
  service(agentId, requested) {
472
631
  const action = configReloadAction({ requested, pendingRequested: this.pending.get(agentId) });
@@ -474,12 +633,59 @@ var ConfigReloadLedger = class {
474
633
  this.pending.set(agentId, requested);
475
634
  this.confirmed.delete(agentId);
476
635
  this.freshRenderAt.delete(agentId);
636
+ this.freshRenderRevision.delete(agentId);
477
637
  }
478
638
  return action;
479
639
  }
480
- /** ENG-12052: a fresh render landed for the pending reload; keeps the earliest. */
481
- noteFreshRender(agentId, atMs) {
482
- if (this.pending.has(agentId) && !this.freshRenderAt.has(agentId)) this.freshRenderAt.set(agentId, atMs);
640
+ /**
641
+ * ENG-12052: a fresh render landed for the pending reload. Keeps the EARLIEST
642
+ * render of a given config.
643
+ *
644
+ * ENG-12141: `revision` is what the spawn will actually read, hashed: the
645
+ * spawn-view `.mcp.json` (`projectMcpHash`). When it differs from the revision
646
+ * the marker was set at, the rendered config CHANGED during the pending reload
647
+ * (a new `remoteMcp.url`, a tool-tier change, a server added or removed), so a
648
+ * session started from the earlier render is now stale and the marker moves to
649
+ * this render. Same revision: same config, earliest kept, so a session started
650
+ * from it is still fresh and is never restarted.
651
+ *
652
+ * INVARIANT (Sherlock, ENG-12141): anything that changes WHICH servers or tools a
653
+ * session gets must live in .mcp.json; .env holds live values only and is
654
+ * deliberately not hashed. Pinned by eng-12141-fresh-render-revision.test.ts.
655
+ *
656
+ * Why the rendered `.mcp.json` and nothing else. It is template-only: every
657
+ * writer emits `${VAR}` references and the ENG-5901 literal-secret lint refuses
658
+ * a write carrying a literal secret. So the values a reload must NOT restart
659
+ * for live outside it by construction: credentials and OAuth tokens (ENG-6918)
660
+ * in `.env.integrations` / the proxy token file, which the proxy re-reads per
661
+ * request or the hot-reload reap applies, and the Anchor `session_id`, which
662
+ * lands as `ANCHOR_BROWSER_SESSION_ID` and is read live per request. The
663
+ * values a reload MUST act on are spawn-fixed and live inside it: the server
664
+ * set, each URL (`AGT_REMOTE_MCP_URL`), and the tool tiers
665
+ * (`AGT_REMOTE_MCP_TOOL_TIERS`, read once at proxy start). No input allowlist,
666
+ * no deny list (the approach reverted on #7666).
667
+ *
668
+ * A `null`/absent revision (the file could not be read) can't be compared, so
669
+ * it keeps the earliest, which is the pre-ENG-12141 behaviour and fails safe:
670
+ * at worst it misses a rare reload, it never stops a fresh session.
671
+ */
672
+ noteFreshRender(agentId, atMs, revision = null) {
673
+ if (!this.pending.has(agentId)) return;
674
+ if (!this.freshRenderAt.has(agentId)) {
675
+ this.freshRenderAt.set(agentId, atMs);
676
+ this.freshRenderRevision.set(agentId, revision);
677
+ return;
678
+ }
679
+ const was = this.freshRenderRevision.get(agentId) ?? null;
680
+ if (revision === null) return;
681
+ if (was === null) {
682
+ this.freshRenderRevision.set(agentId, revision);
683
+ return;
684
+ }
685
+ if (revision !== was) {
686
+ this.freshRenderAt.set(agentId, atMs);
687
+ this.freshRenderRevision.set(agentId, revision);
688
+ }
483
689
  }
484
690
  /** ENG-12052: when the pending reload's first fresh render landed, or null. */
485
691
  freshRenderedAt(agentId) {
@@ -501,6 +707,7 @@ var ConfigReloadLedger = class {
501
707
  this.confirmed.delete(agentId);
502
708
  this.pending.delete(agentId);
503
709
  this.freshRenderAt.delete(agentId);
710
+ this.freshRenderRevision.delete(agentId);
504
711
  if (requestedAt) out.push({ agentId, requestedAt });
505
712
  }
506
713
  return out;
@@ -510,6 +717,7 @@ var ConfigReloadLedger = class {
510
717
  this.pending.delete(agentId);
511
718
  this.confirmed.delete(agentId);
512
719
  this.freshRenderAt.delete(agentId);
720
+ this.freshRenderRevision.delete(agentId);
513
721
  }
514
722
  };
515
723
  function stampIsOlder(a, b) {
@@ -15228,7 +15436,7 @@ function createFileMigrationReportIO(codeName, log2) {
15228
15436
  };
15229
15437
  }
15230
15438
  var managerHostPost = async (path, body) => {
15231
- const { api: api2, ApiError: ApiError3 } = await import("../api-client-QEV6AB73.js");
15439
+ const { api: api2, ApiError: ApiError3 } = await import("../api-client-5L5TDFEN.js");
15232
15440
  try {
15233
15441
  const json = await api2.post(path, body);
15234
15442
  return { status: 200, json };
@@ -17283,7 +17491,7 @@ var pendingDayRolloverReset = /* @__PURE__ */ new Set();
17283
17491
  var dayRolloverInboundHold = /* @__PURE__ */ new Map();
17284
17492
  var INBOUND_HOLD_EPISODE_GAP_MS = 12e4;
17285
17493
  async function channelInboundActivityAgeSecondsFor(codeName) {
17286
- const { newestPendingInboundActivityMtimeMs } = await import("../responsiveness-probe-BLLWDXE4.js");
17494
+ const { newestPendingInboundActivityMtimeMs } = await import("../responsiveness-probe-Q4GRRSHY.js");
17287
17495
  const newest = newestPendingInboundActivityMtimeMs(dirname11(paneLogPath(codeName)));
17288
17496
  if (newest === null) return null;
17289
17497
  return Math.max(0, Math.floor((Date.now() - newest) / 1e3));
@@ -18164,7 +18372,7 @@ var agentRestartTimezoneInputs = /* @__PURE__ */ new Map();
18164
18372
  var lastVersionCheckAt = 0;
18165
18373
  var VERSION_CHECK_INTERVAL_MS = 5 * 60 * 1e3;
18166
18374
  var lastResponsivenessProbeAt = 0;
18167
- var agtCliVersion = true ? "0.28.1280" : "dev";
18375
+ var agtCliVersion = true ? "0.28.1282" : "dev";
18168
18376
  function resolveBrewPath(execFileSync5) {
18169
18377
  try {
18170
18378
  const out = execFileSync5("which", ["brew"], { timeout: 5e3 }).toString().trim();
@@ -19968,6 +20176,103 @@ function hostFlagStore() {
19968
20176
  function shouldRenderIntegrationsSection() {
19969
20177
  return hostFlagStore().getBoolean("claude-md-integrations-section");
19970
20178
  }
20179
+ function creditContextAtStart() {
20180
+ return {
20181
+ fingerprint: creditHostKey.fingerprint,
20182
+ sharesHostKey: evalBackendSharesHostKey(hostFlagStore().getString("conversation-eval-backend"))
20183
+ };
20184
+ }
20185
+ function noteCreditFromError(source, err, atStart) {
20186
+ if (!atStart.sharesHostKey) return;
20187
+ if (atStart.fingerprint !== creditHostKey.fingerprint) return;
20188
+ const text = err instanceof Error ? err.message : typeof err === "string" ? err : null;
20189
+ if (creditExhaustion.noteError(source, text, atStart.fingerprint, Date.now())) {
20190
+ log(`[credit-exhaustion] ${source} hit "Credit balance is too low": this host's API key is out of Anthropic credit`);
20191
+ }
20192
+ }
20193
+ var creditHostKey = { key: null, fingerprint: null };
20194
+ function maybeProbeHostCredit() {
20195
+ const nowMs = Date.now();
20196
+ if (!creditExhaustion.probeDue(creditHostKey.fingerprint, nowMs)) return;
20197
+ const knownMode = getCachedClaudeAuthModeRaw();
20198
+ if (knownMode != null && knownMode !== "api_key") return;
20199
+ creditExhaustion.noteProbeStarted(nowMs);
20200
+ void (async () => {
20201
+ if (!creditHostKey.key) {
20202
+ const hostApiKey = getApiKey();
20203
+ if (!hostApiKey) {
20204
+ log("[credit-exhaustion] probe cannot run: flagged out of credit but AGT_API_KEY is not set");
20205
+ return;
20206
+ }
20207
+ try {
20208
+ const exchange = await exchangeApiKey(hostApiKey, false, { maxAgeMs: AUTH_EXCHANGE_MAX_AGE_MS });
20209
+ setCreditHostKey(exchange.anthropicApiKey ?? null, exchange.anthropicApiKeyFingerprint ?? null);
20210
+ } catch {
20211
+ log("[credit-exhaustion] probe cannot run: could not load the host API key (exchange failed); next try in one interval");
20212
+ return;
20213
+ }
20214
+ }
20215
+ const { key, fingerprint: fingerprint3 } = creditHostKey;
20216
+ if (getCachedClaudeAuthModeRaw() !== "api_key" || !key) {
20217
+ log("[credit-exhaustion] probe skipped: the host is not on an Anthropic API key");
20218
+ return;
20219
+ }
20220
+ if (!creditExhaustion.isExhausted(fingerprint3) && !creditExhaustion.serverFlagMatches(fingerprint3)) return;
20221
+ const outcome = await probeCredit(key);
20222
+ if (fingerprint3 !== creditHostKey.fingerprint) {
20223
+ log("[credit-exhaustion] probe result dropped: the host API key changed while the probe ran");
20224
+ return;
20225
+ }
20226
+ if (outcome === "ok") {
20227
+ creditExhaustion.noteSuccess(fingerprint3, Date.now());
20228
+ log("[credit-exhaustion] probe: the host API key has credit again; reporting the recovery");
20229
+ } else if (outcome === "credit_exhausted") {
20230
+ creditExhaustion.noteError("probe", "Credit balance is too low", fingerprint3, Date.now());
20231
+ log("[credit-exhaustion] probe: still out of Anthropic credit");
20232
+ } else {
20233
+ log(`[credit-exhaustion] probe inconclusive (${outcome.other}); next probe in one interval`);
20234
+ }
20235
+ })().catch(() => {
20236
+ log("[credit-exhaustion] probe failed to run; next probe in one interval");
20237
+ });
20238
+ }
20239
+ var creditPaneCheckedAt = /* @__PURE__ */ new Map();
20240
+ var creditPaneLastOrdinal = /* @__PURE__ */ new Map();
20241
+ var CREDIT_PANE_CHECK_INTERVAL_MS = 6e4;
20242
+ function setCreditHostKey(key, fingerprint3) {
20243
+ const changed = creditHostKey.fingerprint !== null && fingerprint3 !== creditHostKey.fingerprint;
20244
+ creditHostKey.key = key;
20245
+ creditHostKey.fingerprint = fingerprint3;
20246
+ if (!changed) return;
20247
+ for (const codeName of [...creditPaneLastOrdinal.keys()]) {
20248
+ try {
20249
+ creditPaneLastOrdinal.set(codeName, paneResultSighting(readFileSync39(paneLogPath(codeName), "utf-8")).ordinal);
20250
+ } catch {
20251
+ creditPaneLastOrdinal.delete(codeName);
20252
+ }
20253
+ }
20254
+ }
20255
+ function checkPaneForCreditExhaustion(codeName) {
20256
+ const nowMs = Date.now();
20257
+ const last = creditPaneCheckedAt.get(codeName);
20258
+ if (last !== void 0 && nowMs - last < CREDIT_PANE_CHECK_INTERVAL_MS) return;
20259
+ creditPaneCheckedAt.set(codeName, nowMs);
20260
+ let rawLog;
20261
+ try {
20262
+ rawLog = readFileSync39(paneLogPath(codeName), "utf-8");
20263
+ } catch {
20264
+ return;
20265
+ }
20266
+ const { ordinal, latest } = paneResultSighting(rawLog);
20267
+ const previous = creditPaneLastOrdinal.get(codeName);
20268
+ creditPaneLastOrdinal.set(codeName, ordinal);
20269
+ if (!isNewPaneResult({ ordinal, previous })) return;
20270
+ if (isPaneCreditLine(latest)) {
20271
+ if (creditExhaustion.noteError("pane", latest, creditHostKey.fingerprint, nowMs)) {
20272
+ log(`[credit-exhaustion] '${codeName}' pane: "${latest}": this host's API key is out of Anthropic credit`);
20273
+ }
20274
+ }
20275
+ }
19971
20276
  function reportManagerModelCallError(source, err, modelId) {
19972
20277
  try {
19973
20278
  if (!hostFlagStore().getBoolean("model-api-error-reporting")) return;
@@ -20178,7 +20483,7 @@ function flushRestartedAgentDiagnostics(hostId, codeNames) {
20178
20483
  if (codeNames.length === 0) return;
20179
20484
  void (async () => {
20180
20485
  try {
20181
- const { collectDiagnostics } = await import("../persistent-session-WBWYC4XL.js");
20486
+ const { collectDiagnostics } = await import("../persistent-session-C6G3R6BI.js");
20182
20487
  await api.post("/host/heartbeat", {
20183
20488
  host_id: hostId,
20184
20489
  agent_diagnostics: collectDiagnostics(codeNames, quarantineEntriesFor, claudeMdSizeFor, spawnOutcomeForDiagnostics, pidPressureFor, forwardedToolsFor, runtimeVersionFor, sessionActivityFor)
@@ -20321,7 +20626,7 @@ async function pollCycleInner() {
20321
20626
  }
20322
20627
  try {
20323
20628
  const { detectHostSecurity } = await import("../host-security-KQYYZZVW.js");
20324
- const { collectDiagnostics } = await import("../persistent-session-WBWYC4XL.js");
20629
+ const { collectDiagnostics } = await import("../persistent-session-C6G3R6BI.js");
20325
20630
  const diagCodeNames = [...agentState.persistentSessionAgents];
20326
20631
  const agentDiagnostics = diagCodeNames.length > 0 ? collectDiagnostics(diagCodeNames, quarantineEntriesFor, claudeMdSizeFor, spawnOutcomeForDiagnostics, pidPressureFor, forwardedToolsFor, runtimeVersionFor, sessionActivityFor) : void 0;
20327
20632
  let tailscaleHostname;
@@ -20439,6 +20744,9 @@ async function pollCycleInner() {
20439
20744
  detected: claudeAuth,
20440
20745
  detectionFailed: claudeAuthDetectionFailed
20441
20746
  }),
20747
+ // ENG-12162: api_key hosts only; omitted when there is nothing to say,
20748
+ // and the API reads an omitted field as no signal (never a recovery).
20749
+ claude_credit: creditExhaustion.heartbeatField(getCachedClaudeAuthModeRaw(), creditHostKey.fingerprint, Date.now()),
20442
20750
  // OMITTED rather than sent as null when it cannot be read. The API
20443
20751
  // treats absence as "no observation" and leaves the stored label
20444
20752
  // alone; sending null would let a transient unreadable config WIPE a
@@ -20542,6 +20850,9 @@ async function pollCycleInner() {
20542
20850
  if (hbResp?.maintenance_window) {
20543
20851
  cachedMaintenanceWindow = hbResp.maintenance_window;
20544
20852
  }
20853
+ if (hbResp) {
20854
+ creditExhaustion.noteServerFlag(hbResp.claude_credit_exhausted?.key_fingerprint ?? null);
20855
+ }
20545
20856
  if (hbResp && Object.prototype.hasOwnProperty.call(hbResp, "claude_code_security_floor")) {
20546
20857
  const serverFloor = hbResp.claude_code_security_floor;
20547
20858
  cachedServerSecurityFloor = typeof serverFloor === "string" ? serverFloor : null;
@@ -20614,7 +20925,7 @@ async function pollCycleInner() {
20614
20925
  }
20615
20926
  try {
20616
20927
  const desiredClaudeCodeVersion = hbResp?.desired_claude_code_version?.trim();
20617
- const { maybeUpdateClaudeCode, shouldRunClaudeCodeUpdater } = await import("../claude-code-updater-BHSYASF3.js");
20928
+ const { maybeUpdateClaudeCode, shouldRunClaudeCodeUpdater } = await import("../claude-code-updater-C7BXV6S7.js");
20618
20929
  const securityFloor = currentSecurityFloor();
20619
20930
  claudeUpdaterInFlight = true;
20620
20931
  if (desiredClaudeCodeVersion && (claudePairLoop.busy || claudePairingInProgress())) {
@@ -20649,7 +20960,7 @@ async function pollCycleInner() {
20649
20960
  collectPanelessActivityProbes,
20650
20961
  getResponsivenessIntervalMs,
20651
20962
  occupancyQualificationClassifications
20652
- } = await import("../responsiveness-probe-BLLWDXE4.js");
20963
+ } = await import("../responsiveness-probe-Q4GRRSHY.js");
20653
20964
  const probeIntervalMs = getResponsivenessIntervalMs();
20654
20965
  if (now - lastResponsivenessProbeAt > probeIntervalMs) {
20655
20966
  const probeCodeNames = [...agentState.persistentSessionAgents];
@@ -20766,7 +21077,7 @@ async function pollCycleInner() {
20766
21077
  collectResponsivenessProbes,
20767
21078
  livePendingInboundOldestAgeSeconds,
20768
21079
  parkPendingInbound
20769
- } = await import("../responsiveness-probe-BLLWDXE4.js");
21080
+ } = await import("../responsiveness-probe-Q4GRRSHY.js");
20770
21081
  const { getProjectDir: wedgeProjectDir } = await import("../scheduler-engine-5PCBGRNY.js");
20771
21082
  const wedgeNow = /* @__PURE__ */ new Date();
20772
21083
  const liveAgents = agentState.persistentSessionAgents;
@@ -21052,7 +21363,7 @@ async function pollCycleInner() {
21052
21363
  }
21053
21364
  }
21054
21365
  );
21055
- const { parkPendingInbound } = await import("../responsiveness-probe-BLLWDXE4.js");
21366
+ const { parkPendingInbound } = await import("../responsiveness-probe-Q4GRRSHY.js");
21056
21367
  const { parked, deadLettered } = parkPendingInbound(codeName, new Date(fatalNowMs));
21057
21368
  paneFatalStreak.delete(codeName);
21058
21369
  paneFatalRestarts.set(codeName, [...history, fatalNowMs]);
@@ -21083,7 +21394,7 @@ async function pollCycleInner() {
21083
21394
  TRANSCRIPT_MOUNT_ESCALATION_REFRESH_MS,
21084
21395
  bindSourceEscalations
21085
21396
  } = await import("../transcript-mount-health-OHE6IVJV.js");
21086
- const { transcriptBindSourcesFor, ensureTranscriptBindSources } = await import("../persistent-session-WBWYC4XL.js");
21397
+ const { transcriptBindSourcesFor, ensureTranscriptBindSources } = await import("../persistent-session-C6G3R6BI.js");
21087
21398
  const mountConfig = resolveTranscriptMountConfig();
21088
21399
  const liveAgents = agentState.persistentSessionAgents;
21089
21400
  for (const tracked of [
@@ -21248,7 +21559,7 @@ async function pollCycleInner() {
21248
21559
  }
21249
21560
  try {
21250
21561
  const { scrapeMcpFailedBannerCount } = await import("../pane-mcp-banner-scraper-VR5QGP3J.js");
21251
- const { probeSessionAuth } = await import("../session-auth-dead-NJR7X5T6.js");
21562
+ const { probeSessionAuth } = await import("../session-auth-dead-MAJHZEHU.js");
21252
21563
  const observations = [];
21253
21564
  const pendingCacheCommits = [];
21254
21565
  const modelApiErrorReportingOn = hostFlagStore().getBoolean("model-api-error-reporting");
@@ -21692,6 +22003,7 @@ async function pollCycleInner() {
21692
22003
  pollCycleBoardFetched = 0;
21693
22004
  pollCycleBoardGated = 0;
21694
22005
  boardTokenCache.resetStats();
22006
+ maybeProbeHostCredit();
21695
22007
  for (const agent of processOrder) {
21696
22008
  if (restartInFlight.has(agent.agent_id)) {
21697
22009
  const existing = state9.agents.find((a) => a.agentId === agent.agent_id);
@@ -22151,6 +22463,7 @@ async function processAgent(agent, agentStates, managedToolkits) {
22151
22463
  agentFrameworkCache.set(agent.code_name, agent.framework);
22152
22464
  }
22153
22465
  if (agent.framework === "claude-code" && agent.status === "active") {
22466
+ checkPaneForCreditExhaustion(agent.code_name);
22154
22467
  void maybeReportUsageBanner({
22155
22468
  api,
22156
22469
  codeName: agent.code_name,
@@ -22182,24 +22495,32 @@ async function processAgent(agent, agentStates, managedToolkits) {
22182
22495
  }
22183
22496
  if (!scorerSuppressed) {
22184
22497
  const evalBackend = resolveConversationEvalBackend();
22498
+ const evalCredit = creditContextAtStart();
22185
22499
  void maybeEvaluateConversations({
22186
22500
  api,
22187
22501
  backend: evalBackend,
22188
22502
  codeName: agent.code_name,
22189
22503
  agentId: agent.agent_id,
22190
22504
  log,
22191
- onModelCallError: (err) => reportManagerModelCallError("conversation_eval", err, evalBackend.model ?? null)
22505
+ onModelCallError: (err) => {
22506
+ noteCreditFromError("conversation_eval", err, evalCredit);
22507
+ reportManagerModelCallError("conversation_eval", err, evalBackend.model ?? null);
22508
+ }
22192
22509
  });
22193
22510
  }
22194
22511
  if (memoryExtractionEnabled() && !scorerSuppressed) {
22195
22512
  const memBackend = resolveConversationEvalBackend();
22513
+ const memCredit = creditContextAtStart();
22196
22514
  void maybeExtractMemories({
22197
22515
  api,
22198
22516
  backend: memBackend,
22199
22517
  codeName: agent.code_name,
22200
22518
  agentId: agent.agent_id,
22201
22519
  log,
22202
- onModelCallError: (err) => reportManagerModelCallError("memory_extraction", err, memBackend.model ?? null)
22520
+ onModelCallError: (err) => {
22521
+ noteCreditFromError("memory_extraction", err, memCredit);
22522
+ reportManagerModelCallError("memory_extraction", err, memBackend.model ?? null);
22523
+ }
22203
22524
  });
22204
22525
  }
22205
22526
  if (toolCallAuditEnabled()) {
@@ -23845,7 +24166,7 @@ async function processAgent(agent, agentStates, managedToolkits) {
23845
24166
  }
23846
24167
  const reloadRendered = rotationHandled && !orphanPruneFailed && !mcpWriteFailed;
23847
24168
  if (configReloads.isPending(agent.agent_id) && integrationsFresh && reloadRendered) {
23848
- configReloads.noteFreshRender(agent.agent_id, Date.now());
24169
+ configReloads.noteFreshRender(agent.agent_id, Date.now(), projectMcpHash(agent.code_name, getProjectDir(agent.code_name)));
23849
24170
  }
23850
24171
  confirmConfigReload(
23851
24172
  {
@@ -24431,7 +24752,13 @@ async function processAgent(agent, agentStates, managedToolkits) {
24431
24752
  const normalizedDetail = psResult.detail?.replace(/\s+/g, " ").trim();
24432
24753
  const detailSuffix = normalizedDetail ? ` detail=${JSON.stringify(normalizedDetail)}` : "";
24433
24754
  log(
24434
- `[persistent-session-decision] agent=${agent.code_name} decision=${psResult.decision} spawn_attempted=${psResult.spawnAttempted} session_healthy_after=${psResult.sessionHealthyAfter}${detailSuffix}`
24755
+ `[persistent-session-decision] agent=${agent.code_name} decision=${psResult.decision} spawn_attempted=${psResult.spawnAttempted} session_healthy_after=${psResult.sessionHealthyAfter}${detailSuffix}` + // ENG-12162 (AC4, as changed by Sherlock's ruling): the decision line
24756
+ // says the host key is out of credit, so a "healthy" read here can no
24757
+ // longer hide it. The decision ITSELF is left alone: rewriting it broke
24758
+ // the respawn-confirmation logic (Obi Wan 5b581c53073d, 9b95bff220e9).
24759
+ // CodeRabbit on 40a73e7d24: a restored server flag with no local hit (a
24760
+ // restarted manager, an inconclusive probe) is still out of credit.
24761
+ (creditExhaustion.isExhausted(creditHostKey.fingerprint) || creditExhaustion.serverFlagMatches(creditHostKey.fingerprint) ? " credit_exhausted=true" : "")
24435
24762
  );
24436
24763
  recordSpawnOutcome(agent.code_name, psResult);
24437
24764
  const stuck = persistentSessionStuckTracker.record({
@@ -25375,6 +25702,7 @@ async function ensurePersistentSessionUnchecked(agent, tasks, boardItems, refres
25375
25702
  claudeAuthMode = exchange.claudeAuthMode;
25376
25703
  anthropicApiKey = exchange.anthropicApiKey;
25377
25704
  anthropicApiKeyFingerprint = exchange.anthropicApiKeyFingerprint;
25705
+ setCreditHostKey(exchange.anthropicApiKey ?? null, exchange.anthropicApiKeyFingerprint ?? null);
25378
25706
  hostKind = exchange.hostKind;
25379
25707
  rawHostKey = apiKey;
25380
25708
  } catch (err) {
@@ -26317,7 +26645,7 @@ async function handleRestartDoorbell(agentId, requestedAt, restartReason) {
26317
26645
  if (!refreshData) return;
26318
26646
  const framework = refreshData.agent?.framework ?? agentFrameworkCache.get(codeName) ?? DEFAULT_FRAMEWORK;
26319
26647
  const hostId = await getHostId();
26320
- const parkForRestart = await import("../responsiveness-probe-BLLWDXE4.js").then(
26648
+ const parkForRestart = await import("../responsiveness-probe-Q4GRRSHY.js").then(
26321
26649
  (m) => m.parkPendingInbound,
26322
26650
  (err) => err
26323
26651
  );
@@ -26394,7 +26722,7 @@ async function handleRestartDoorbell(agentId, requestedAt, restartReason) {
26394
26722
  void api.post("/host/restart-ack", { host_id: hostId, agent_id: agentId, restart_requested_at: requestedAt }).catch((err) => log(`[restart-lane] ack failed for '${codeName}': ${err.message}`));
26395
26723
  void (async () => {
26396
26724
  try {
26397
- const { collectDiagnostics } = await import("../persistent-session-WBWYC4XL.js");
26725
+ const { collectDiagnostics } = await import("../persistent-session-C6G3R6BI.js");
26398
26726
  await api.post("/host/heartbeat", {
26399
26727
  host_id: hostId,
26400
26728
  agent_diagnostics: collectDiagnostics([codeName], quarantineEntriesFor, claudeMdSizeFor, spawnOutcomeForDiagnostics, pidPressureFor, forwardedToolsFor, runtimeVersionFor, sessionActivityFor)
@@ -26447,7 +26775,7 @@ async function respawnAgentAfterMcpStop(codeName, reason) {
26447
26775
  }
26448
26776
  try {
26449
26777
  const hostId = await getHostId();
26450
- const { collectDiagnostics } = await import("../persistent-session-WBWYC4XL.js");
26778
+ const { collectDiagnostics } = await import("../persistent-session-C6G3R6BI.js");
26451
26779
  await api.post("/host/heartbeat", {
26452
26780
  host_id: hostId,
26453
26781
  agent_diagnostics: collectDiagnostics([codeName], quarantineEntriesFor, claudeMdSizeFor, spawnOutcomeForDiagnostics, pidPressureFor, forwardedToolsFor, runtimeVersionFor, sessionActivityFor)
@@ -27174,7 +27502,7 @@ async function processClaudePairSessions(agents) {
27174
27502
  snapshotPairConfig,
27175
27503
  // ENG-11659: result -> report body + the manager.log line that records it.
27176
27504
  planPairStartReport
27177
- } = await import("../claude-pair-runtime-27FK2QO2.js");
27505
+ } = await import("../claude-pair-runtime-7W5TM3MA.js");
27178
27506
  const { resetClaudeSignin, describeSigninResetForLog, describeSigninResetFailure } = await import("../claude-signin-reset-6IJMMVYG.js");
27179
27507
  for (const pairId of pendingResp.cancelled_pair_ids ?? []) {
27180
27508
  log(`[claude-pair] sweeping orphan tmux session for pair ${pairId.slice(0, 8)}`);