@integrity-labs/agt-cli 0.28.1281 → 0.28.1283

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 (35) hide show
  1. package/dist/{api-client-UW5GPDR5.js → api-client-34MRJANA.js} +3 -3
  2. package/dist/bin/agt.js +7 -7
  3. package/dist/{chunk-A26WJ7TB.js → chunk-5CUCQYZH.js} +2 -2
  4. package/dist/{chunk-XNHTH267.js → chunk-D5DY5OKR.js} +62 -11
  5. package/dist/chunk-D5DY5OKR.js.map +1 -0
  6. package/dist/{chunk-O5D6I72R.js → chunk-FFLU5VIN.js} +2 -1
  7. package/dist/chunk-FFLU5VIN.js.map +1 -0
  8. package/dist/{chunk-CCWVPE2F.js → chunk-G3CTTMOE.js} +3 -3
  9. package/dist/{chunk-SHBU7NAQ.js → chunk-L4HODIVN.js} +5 -5
  10. package/dist/{chunk-FQMFWJUD.js → chunk-QK4R5ZIT.js} +2 -2
  11. package/dist/{claude-code-updater-L3NMDSSG.js → claude-code-updater-BQFWZDEI.js} +3 -3
  12. package/dist/{claude-pair-runtime-TUVLJDJZ.js → claude-pair-runtime-L6XQTJKV.js} +3 -3
  13. package/dist/lib/manager-worker.js +348 -32
  14. package/dist/lib/manager-worker.js.map +1 -1
  15. package/dist/mcp/direct-chat-channel.js +4 -0
  16. package/dist/mcp/index.js +5 -0
  17. package/dist/mcp/origami.js +4 -0
  18. package/dist/mcp/slack-channel.js +4 -0
  19. package/dist/mcp/telegram-channel.js +4 -0
  20. package/dist/{persistent-session-LMR3WHVO.js → persistent-session-ISLJXHGH.js} +6 -4
  21. package/dist/{responsiveness-probe-FWPQTPQ5.js → responsiveness-probe-X3SNNEDY.js} +4 -4
  22. package/dist/{session-auth-dead-5PNG5ILK.js → session-auth-dead-UBNHYRAW.js} +3 -3
  23. package/package.json +1 -1
  24. package/dist/chunk-O5D6I72R.js.map +0 -1
  25. package/dist/chunk-XNHTH267.js.map +0 -1
  26. /package/dist/{api-client-UW5GPDR5.js.map → api-client-34MRJANA.js.map} +0 -0
  27. /package/dist/{chunk-A26WJ7TB.js.map → chunk-5CUCQYZH.js.map} +0 -0
  28. /package/dist/{chunk-CCWVPE2F.js.map → chunk-G3CTTMOE.js.map} +0 -0
  29. /package/dist/{chunk-SHBU7NAQ.js.map → chunk-L4HODIVN.js.map} +0 -0
  30. /package/dist/{chunk-FQMFWJUD.js.map → chunk-QK4R5ZIT.js.map} +0 -0
  31. /package/dist/{claude-code-updater-L3NMDSSG.js.map → claude-code-updater-BQFWZDEI.js.map} +0 -0
  32. /package/dist/{claude-pair-runtime-TUVLJDJZ.js.map → claude-pair-runtime-L6XQTJKV.js.map} +0 -0
  33. /package/dist/{persistent-session-LMR3WHVO.js.map → persistent-session-ISLJXHGH.js.map} +0 -0
  34. /package/dist/{responsiveness-probe-FWPQTPQ5.js.map → responsiveness-probe-X3SNNEDY.js.map} +0 -0
  35. /package/dist/{session-auth-dead-5PNG5ILK.js.map → session-auth-dead-UBNHYRAW.js.map} +0 -0
@@ -70,7 +70,7 @@ import {
70
70
  tripClass,
71
71
  writeEtcEnvironment,
72
72
  writeProfileDScript
73
- } from "../chunk-SHBU7NAQ.js";
73
+ } from "../chunk-L4HODIVN.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-CCWVPE2F.js";
91
+ } from "../chunk-G3CTTMOE.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-XNHTH267.js";
183
+ } from "../chunk-D5DY5OKR.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-FQMFWJUD.js";
194
+ } from "../chunk-QK4R5ZIT.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-A26WJ7TB.js";
220
+ } from "../chunk-5CUCQYZH.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-O5D6I72R.js";
349
+ } from "../chunk-FFLU5VIN.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";
@@ -10726,6 +10877,14 @@ var HYBRID_ACTIONABLE_STATUSES = new Set(KANBAN_NUDGE_ACTIONABLE_STATUSES);
10726
10877
  function isHybridActionable(item) {
10727
10878
  return HYBRID_ACTIONABLE_STATUSES.has(item.status) && item.source_type !== "scheduled_task" && item.assignee_type !== "human" && item.owed_reply_on_own_card !== false;
10728
10879
  }
10880
+ function selectHybridNudgeSet(items) {
10881
+ const actionable = items.filter(isHybridActionable);
10882
+ if (actionable.length > 0) return { items: actionable, backlogOnly: false };
10883
+ const backlog = items.filter(
10884
+ (item) => item.status === "backlog" && item.source_type !== "scheduled_task" && item.assignee_type !== "human" && item.owed_reply_on_own_card !== false
10885
+ );
10886
+ return { items: backlog, backlogOnly: backlog.length > 0 };
10887
+ }
10729
10888
  function resolveHybridNudgeAction(stale, allowedCount, suppressedCount) {
10730
10889
  if (stale) return "skip-stale";
10731
10890
  if (allowedCount > 0) return "nudge";
@@ -15285,7 +15444,7 @@ function createFileMigrationReportIO(codeName, log2) {
15285
15444
  };
15286
15445
  }
15287
15446
  var managerHostPost = async (path, body) => {
15288
- const { api: api2, ApiError: ApiError3 } = await import("../api-client-UW5GPDR5.js");
15447
+ const { api: api2, ApiError: ApiError3 } = await import("../api-client-34MRJANA.js");
15289
15448
  try {
15290
15449
  const json = await api2.post(path, body);
15291
15450
  return { status: 200, json };
@@ -17340,7 +17499,7 @@ var pendingDayRolloverReset = /* @__PURE__ */ new Set();
17340
17499
  var dayRolloverInboundHold = /* @__PURE__ */ new Map();
17341
17500
  var INBOUND_HOLD_EPISODE_GAP_MS = 12e4;
17342
17501
  async function channelInboundActivityAgeSecondsFor(codeName) {
17343
- const { newestPendingInboundActivityMtimeMs } = await import("../responsiveness-probe-FWPQTPQ5.js");
17502
+ const { newestPendingInboundActivityMtimeMs } = await import("../responsiveness-probe-X3SNNEDY.js");
17344
17503
  const newest = newestPendingInboundActivityMtimeMs(dirname11(paneLogPath(codeName)));
17345
17504
  if (newest === null) return null;
17346
17505
  return Math.max(0, Math.floor((Date.now() - newest) / 1e3));
@@ -18221,7 +18380,7 @@ var agentRestartTimezoneInputs = /* @__PURE__ */ new Map();
18221
18380
  var lastVersionCheckAt = 0;
18222
18381
  var VERSION_CHECK_INTERVAL_MS = 5 * 60 * 1e3;
18223
18382
  var lastResponsivenessProbeAt = 0;
18224
- var agtCliVersion = true ? "0.28.1281" : "dev";
18383
+ var agtCliVersion = true ? "0.28.1283" : "dev";
18225
18384
  function resolveBrewPath(execFileSync5) {
18226
18385
  try {
18227
18386
  const out = execFileSync5("which", ["brew"], { timeout: 5e3 }).toString().trim();
@@ -20025,6 +20184,103 @@ function hostFlagStore() {
20025
20184
  function shouldRenderIntegrationsSection() {
20026
20185
  return hostFlagStore().getBoolean("claude-md-integrations-section");
20027
20186
  }
20187
+ function creditContextAtStart() {
20188
+ return {
20189
+ fingerprint: creditHostKey.fingerprint,
20190
+ sharesHostKey: evalBackendSharesHostKey(hostFlagStore().getString("conversation-eval-backend"))
20191
+ };
20192
+ }
20193
+ function noteCreditFromError(source, err, atStart) {
20194
+ if (!atStart.sharesHostKey) return;
20195
+ if (atStart.fingerprint !== creditHostKey.fingerprint) return;
20196
+ const text = err instanceof Error ? err.message : typeof err === "string" ? err : null;
20197
+ if (creditExhaustion.noteError(source, text, atStart.fingerprint, Date.now())) {
20198
+ log(`[credit-exhaustion] ${source} hit "Credit balance is too low": this host's API key is out of Anthropic credit`);
20199
+ }
20200
+ }
20201
+ var creditHostKey = { key: null, fingerprint: null };
20202
+ function maybeProbeHostCredit() {
20203
+ const nowMs = Date.now();
20204
+ if (!creditExhaustion.probeDue(creditHostKey.fingerprint, nowMs)) return;
20205
+ const knownMode = getCachedClaudeAuthModeRaw();
20206
+ if (knownMode != null && knownMode !== "api_key") return;
20207
+ creditExhaustion.noteProbeStarted(nowMs);
20208
+ void (async () => {
20209
+ if (!creditHostKey.key) {
20210
+ const hostApiKey = getApiKey();
20211
+ if (!hostApiKey) {
20212
+ log("[credit-exhaustion] probe cannot run: flagged out of credit but AGT_API_KEY is not set");
20213
+ return;
20214
+ }
20215
+ try {
20216
+ const exchange = await exchangeApiKey(hostApiKey, false, { maxAgeMs: AUTH_EXCHANGE_MAX_AGE_MS });
20217
+ setCreditHostKey(exchange.anthropicApiKey ?? null, exchange.anthropicApiKeyFingerprint ?? null);
20218
+ } catch {
20219
+ log("[credit-exhaustion] probe cannot run: could not load the host API key (exchange failed); next try in one interval");
20220
+ return;
20221
+ }
20222
+ }
20223
+ const { key, fingerprint: fingerprint3 } = creditHostKey;
20224
+ if (getCachedClaudeAuthModeRaw() !== "api_key" || !key) {
20225
+ log("[credit-exhaustion] probe skipped: the host is not on an Anthropic API key");
20226
+ return;
20227
+ }
20228
+ if (!creditExhaustion.isExhausted(fingerprint3) && !creditExhaustion.serverFlagMatches(fingerprint3)) return;
20229
+ const outcome = await probeCredit(key);
20230
+ if (fingerprint3 !== creditHostKey.fingerprint) {
20231
+ log("[credit-exhaustion] probe result dropped: the host API key changed while the probe ran");
20232
+ return;
20233
+ }
20234
+ if (outcome === "ok") {
20235
+ creditExhaustion.noteSuccess(fingerprint3, Date.now());
20236
+ log("[credit-exhaustion] probe: the host API key has credit again; reporting the recovery");
20237
+ } else if (outcome === "credit_exhausted") {
20238
+ creditExhaustion.noteError("probe", "Credit balance is too low", fingerprint3, Date.now());
20239
+ log("[credit-exhaustion] probe: still out of Anthropic credit");
20240
+ } else {
20241
+ log(`[credit-exhaustion] probe inconclusive (${outcome.other}); next probe in one interval`);
20242
+ }
20243
+ })().catch(() => {
20244
+ log("[credit-exhaustion] probe failed to run; next probe in one interval");
20245
+ });
20246
+ }
20247
+ var creditPaneCheckedAt = /* @__PURE__ */ new Map();
20248
+ var creditPaneLastOrdinal = /* @__PURE__ */ new Map();
20249
+ var CREDIT_PANE_CHECK_INTERVAL_MS = 6e4;
20250
+ function setCreditHostKey(key, fingerprint3) {
20251
+ const changed = creditHostKey.fingerprint !== null && fingerprint3 !== creditHostKey.fingerprint;
20252
+ creditHostKey.key = key;
20253
+ creditHostKey.fingerprint = fingerprint3;
20254
+ if (!changed) return;
20255
+ for (const codeName of [...creditPaneLastOrdinal.keys()]) {
20256
+ try {
20257
+ creditPaneLastOrdinal.set(codeName, paneResultSighting(readFileSync39(paneLogPath(codeName), "utf-8")).ordinal);
20258
+ } catch {
20259
+ creditPaneLastOrdinal.delete(codeName);
20260
+ }
20261
+ }
20262
+ }
20263
+ function checkPaneForCreditExhaustion(codeName) {
20264
+ const nowMs = Date.now();
20265
+ const last = creditPaneCheckedAt.get(codeName);
20266
+ if (last !== void 0 && nowMs - last < CREDIT_PANE_CHECK_INTERVAL_MS) return;
20267
+ creditPaneCheckedAt.set(codeName, nowMs);
20268
+ let rawLog;
20269
+ try {
20270
+ rawLog = readFileSync39(paneLogPath(codeName), "utf-8");
20271
+ } catch {
20272
+ return;
20273
+ }
20274
+ const { ordinal, latest } = paneResultSighting(rawLog);
20275
+ const previous = creditPaneLastOrdinal.get(codeName);
20276
+ creditPaneLastOrdinal.set(codeName, ordinal);
20277
+ if (!isNewPaneResult({ ordinal, previous })) return;
20278
+ if (isPaneCreditLine(latest)) {
20279
+ if (creditExhaustion.noteError("pane", latest, creditHostKey.fingerprint, nowMs)) {
20280
+ log(`[credit-exhaustion] '${codeName}' pane: "${latest}": this host's API key is out of Anthropic credit`);
20281
+ }
20282
+ }
20283
+ }
20028
20284
  function reportManagerModelCallError(source, err, modelId) {
20029
20285
  try {
20030
20286
  if (!hostFlagStore().getBoolean("model-api-error-reporting")) return;
@@ -20235,7 +20491,7 @@ function flushRestartedAgentDiagnostics(hostId, codeNames) {
20235
20491
  if (codeNames.length === 0) return;
20236
20492
  void (async () => {
20237
20493
  try {
20238
- const { collectDiagnostics } = await import("../persistent-session-LMR3WHVO.js");
20494
+ const { collectDiagnostics } = await import("../persistent-session-ISLJXHGH.js");
20239
20495
  await api.post("/host/heartbeat", {
20240
20496
  host_id: hostId,
20241
20497
  agent_diagnostics: collectDiagnostics(codeNames, quarantineEntriesFor, claudeMdSizeFor, spawnOutcomeForDiagnostics, pidPressureFor, forwardedToolsFor, runtimeVersionFor, sessionActivityFor)
@@ -20378,7 +20634,7 @@ async function pollCycleInner() {
20378
20634
  }
20379
20635
  try {
20380
20636
  const { detectHostSecurity } = await import("../host-security-KQYYZZVW.js");
20381
- const { collectDiagnostics } = await import("../persistent-session-LMR3WHVO.js");
20637
+ const { collectDiagnostics } = await import("../persistent-session-ISLJXHGH.js");
20382
20638
  const diagCodeNames = [...agentState.persistentSessionAgents];
20383
20639
  const agentDiagnostics = diagCodeNames.length > 0 ? collectDiagnostics(diagCodeNames, quarantineEntriesFor, claudeMdSizeFor, spawnOutcomeForDiagnostics, pidPressureFor, forwardedToolsFor, runtimeVersionFor, sessionActivityFor) : void 0;
20384
20640
  let tailscaleHostname;
@@ -20496,6 +20752,9 @@ async function pollCycleInner() {
20496
20752
  detected: claudeAuth,
20497
20753
  detectionFailed: claudeAuthDetectionFailed
20498
20754
  }),
20755
+ // ENG-12162: api_key hosts only; omitted when there is nothing to say,
20756
+ // and the API reads an omitted field as no signal (never a recovery).
20757
+ claude_credit: creditExhaustion.heartbeatField(getCachedClaudeAuthModeRaw(), creditHostKey.fingerprint, Date.now()),
20499
20758
  // OMITTED rather than sent as null when it cannot be read. The API
20500
20759
  // treats absence as "no observation" and leaves the stored label
20501
20760
  // alone; sending null would let a transient unreadable config WIPE a
@@ -20599,6 +20858,9 @@ async function pollCycleInner() {
20599
20858
  if (hbResp?.maintenance_window) {
20600
20859
  cachedMaintenanceWindow = hbResp.maintenance_window;
20601
20860
  }
20861
+ if (hbResp) {
20862
+ creditExhaustion.noteServerFlag(hbResp.claude_credit_exhausted?.key_fingerprint ?? null);
20863
+ }
20602
20864
  if (hbResp && Object.prototype.hasOwnProperty.call(hbResp, "claude_code_security_floor")) {
20603
20865
  const serverFloor = hbResp.claude_code_security_floor;
20604
20866
  cachedServerSecurityFloor = typeof serverFloor === "string" ? serverFloor : null;
@@ -20671,7 +20933,7 @@ async function pollCycleInner() {
20671
20933
  }
20672
20934
  try {
20673
20935
  const desiredClaudeCodeVersion = hbResp?.desired_claude_code_version?.trim();
20674
- const { maybeUpdateClaudeCode, shouldRunClaudeCodeUpdater } = await import("../claude-code-updater-L3NMDSSG.js");
20936
+ const { maybeUpdateClaudeCode, shouldRunClaudeCodeUpdater } = await import("../claude-code-updater-BQFWZDEI.js");
20675
20937
  const securityFloor = currentSecurityFloor();
20676
20938
  claudeUpdaterInFlight = true;
20677
20939
  if (desiredClaudeCodeVersion && (claudePairLoop.busy || claudePairingInProgress())) {
@@ -20706,7 +20968,7 @@ async function pollCycleInner() {
20706
20968
  collectPanelessActivityProbes,
20707
20969
  getResponsivenessIntervalMs,
20708
20970
  occupancyQualificationClassifications
20709
- } = await import("../responsiveness-probe-FWPQTPQ5.js");
20971
+ } = await import("../responsiveness-probe-X3SNNEDY.js");
20710
20972
  const probeIntervalMs = getResponsivenessIntervalMs();
20711
20973
  if (now - lastResponsivenessProbeAt > probeIntervalMs) {
20712
20974
  const probeCodeNames = [...agentState.persistentSessionAgents];
@@ -20823,7 +21085,7 @@ async function pollCycleInner() {
20823
21085
  collectResponsivenessProbes,
20824
21086
  livePendingInboundOldestAgeSeconds,
20825
21087
  parkPendingInbound
20826
- } = await import("../responsiveness-probe-FWPQTPQ5.js");
21088
+ } = await import("../responsiveness-probe-X3SNNEDY.js");
20827
21089
  const { getProjectDir: wedgeProjectDir } = await import("../scheduler-engine-5PCBGRNY.js");
20828
21090
  const wedgeNow = /* @__PURE__ */ new Date();
20829
21091
  const liveAgents = agentState.persistentSessionAgents;
@@ -21109,7 +21371,7 @@ async function pollCycleInner() {
21109
21371
  }
21110
21372
  }
21111
21373
  );
21112
- const { parkPendingInbound } = await import("../responsiveness-probe-FWPQTPQ5.js");
21374
+ const { parkPendingInbound } = await import("../responsiveness-probe-X3SNNEDY.js");
21113
21375
  const { parked, deadLettered } = parkPendingInbound(codeName, new Date(fatalNowMs));
21114
21376
  paneFatalStreak.delete(codeName);
21115
21377
  paneFatalRestarts.set(codeName, [...history, fatalNowMs]);
@@ -21140,7 +21402,7 @@ async function pollCycleInner() {
21140
21402
  TRANSCRIPT_MOUNT_ESCALATION_REFRESH_MS,
21141
21403
  bindSourceEscalations
21142
21404
  } = await import("../transcript-mount-health-OHE6IVJV.js");
21143
- const { transcriptBindSourcesFor, ensureTranscriptBindSources } = await import("../persistent-session-LMR3WHVO.js");
21405
+ const { transcriptBindSourcesFor, ensureTranscriptBindSources } = await import("../persistent-session-ISLJXHGH.js");
21144
21406
  const mountConfig = resolveTranscriptMountConfig();
21145
21407
  const liveAgents = agentState.persistentSessionAgents;
21146
21408
  for (const tracked of [
@@ -21305,7 +21567,7 @@ async function pollCycleInner() {
21305
21567
  }
21306
21568
  try {
21307
21569
  const { scrapeMcpFailedBannerCount } = await import("../pane-mcp-banner-scraper-VR5QGP3J.js");
21308
- const { probeSessionAuth } = await import("../session-auth-dead-5PNG5ILK.js");
21570
+ const { probeSessionAuth } = await import("../session-auth-dead-UBNHYRAW.js");
21309
21571
  const observations = [];
21310
21572
  const pendingCacheCommits = [];
21311
21573
  const modelApiErrorReportingOn = hostFlagStore().getBoolean("model-api-error-reporting");
@@ -21749,6 +22011,7 @@ async function pollCycleInner() {
21749
22011
  pollCycleBoardFetched = 0;
21750
22012
  pollCycleBoardGated = 0;
21751
22013
  boardTokenCache.resetStats();
22014
+ maybeProbeHostCredit();
21752
22015
  for (const agent of processOrder) {
21753
22016
  if (restartInFlight.has(agent.agent_id)) {
21754
22017
  const existing = state9.agents.find((a) => a.agentId === agent.agent_id);
@@ -22208,6 +22471,7 @@ async function processAgent(agent, agentStates, managedToolkits) {
22208
22471
  agentFrameworkCache.set(agent.code_name, agent.framework);
22209
22472
  }
22210
22473
  if (agent.framework === "claude-code" && agent.status === "active") {
22474
+ checkPaneForCreditExhaustion(agent.code_name);
22211
22475
  void maybeReportUsageBanner({
22212
22476
  api,
22213
22477
  codeName: agent.code_name,
@@ -22239,24 +22503,32 @@ async function processAgent(agent, agentStates, managedToolkits) {
22239
22503
  }
22240
22504
  if (!scorerSuppressed) {
22241
22505
  const evalBackend = resolveConversationEvalBackend();
22506
+ const evalCredit = creditContextAtStart();
22242
22507
  void maybeEvaluateConversations({
22243
22508
  api,
22244
22509
  backend: evalBackend,
22245
22510
  codeName: agent.code_name,
22246
22511
  agentId: agent.agent_id,
22247
22512
  log,
22248
- onModelCallError: (err) => reportManagerModelCallError("conversation_eval", err, evalBackend.model ?? null)
22513
+ onModelCallError: (err) => {
22514
+ noteCreditFromError("conversation_eval", err, evalCredit);
22515
+ reportManagerModelCallError("conversation_eval", err, evalBackend.model ?? null);
22516
+ }
22249
22517
  });
22250
22518
  }
22251
22519
  if (memoryExtractionEnabled() && !scorerSuppressed) {
22252
22520
  const memBackend = resolveConversationEvalBackend();
22521
+ const memCredit = creditContextAtStart();
22253
22522
  void maybeExtractMemories({
22254
22523
  api,
22255
22524
  backend: memBackend,
22256
22525
  codeName: agent.code_name,
22257
22526
  agentId: agent.agent_id,
22258
22527
  log,
22259
- onModelCallError: (err) => reportManagerModelCallError("memory_extraction", err, memBackend.model ?? null)
22528
+ onModelCallError: (err) => {
22529
+ noteCreditFromError("memory_extraction", err, memCredit);
22530
+ reportManagerModelCallError("memory_extraction", err, memBackend.model ?? null);
22531
+ }
22260
22532
  });
22261
22533
  }
22262
22534
  if (toolCallAuditEnabled()) {
@@ -24422,7 +24694,7 @@ async function processAgent(agent, agentStates, managedToolkits) {
24422
24694
  else wedgeRestartsByCard.delete(agent.code_name);
24423
24695
  }
24424
24696
  const cardStates = wedgeRestartsByCard.get(agent.code_name);
24425
- const actionable = hybridBoard.filter(isHybridActionable);
24697
+ const { items: actionable, backlogOnly } = selectHybridNudgeSet(hybridBoard);
24426
24698
  const { allowed, suppressed } = cardStates ? partitionActionableByPoison(actionable, cardStates, poisonCfg) : { allowed: actionable, suppressed: [] };
24427
24699
  const nudgeAction = resolveHybridNudgeAction(
24428
24700
  hybridBoardStale,
@@ -24451,7 +24723,8 @@ async function processAgent(agent, agentStates, managedToolkits) {
24451
24723
  agent.code_name,
24452
24724
  agent.agent_id,
24453
24725
  allowed.length,
24454
- kanbanActionableSignature(allowed)
24726
+ kanbanActionableSignature(allowed),
24727
+ backlogOnly
24455
24728
  );
24456
24729
  }
24457
24730
  } else if (nudgeAction === "close-suppressed") {
@@ -24488,7 +24761,13 @@ async function processAgent(agent, agentStates, managedToolkits) {
24488
24761
  const normalizedDetail = psResult.detail?.replace(/\s+/g, " ").trim();
24489
24762
  const detailSuffix = normalizedDetail ? ` detail=${JSON.stringify(normalizedDetail)}` : "";
24490
24763
  log(
24491
- `[persistent-session-decision] agent=${agent.code_name} decision=${psResult.decision} spawn_attempted=${psResult.spawnAttempted} session_healthy_after=${psResult.sessionHealthyAfter}${detailSuffix}`
24764
+ `[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
24765
+ // says the host key is out of credit, so a "healthy" read here can no
24766
+ // longer hide it. The decision ITSELF is left alone: rewriting it broke
24767
+ // the respawn-confirmation logic (Obi Wan 5b581c53073d, 9b95bff220e9).
24768
+ // CodeRabbit on 40a73e7d24: a restored server flag with no local hit (a
24769
+ // restarted manager, an inconclusive probe) is still out of credit.
24770
+ (creditExhaustion.isExhausted(creditHostKey.fingerprint) || creditExhaustion.serverFlagMatches(creditHostKey.fingerprint) ? " credit_exhausted=true" : "")
24492
24771
  );
24493
24772
  recordSpawnOutcome(agent.code_name, psResult);
24494
24773
  const stuck = persistentSessionStuckTracker.record({
@@ -25432,6 +25711,7 @@ async function ensurePersistentSessionUnchecked(agent, tasks, boardItems, refres
25432
25711
  claudeAuthMode = exchange.claudeAuthMode;
25433
25712
  anthropicApiKey = exchange.anthropicApiKey;
25434
25713
  anthropicApiKeyFingerprint = exchange.anthropicApiKeyFingerprint;
25714
+ setCreditHostKey(exchange.anthropicApiKey ?? null, exchange.anthropicApiKeyFingerprint ?? null);
25435
25715
  hostKind = exchange.hostKind;
25436
25716
  rawHostKey = apiKey;
25437
25717
  } catch (err) {
@@ -25727,7 +26007,32 @@ async function ensurePersistentSessionUnchecked(agent, tasks, boardItems, refres
25727
26007
  log(`[persistent-session] Failed to provision review poster for '${codeName}': ${err.message}`);
25728
26008
  }
25729
26009
  if (!isSessionHealthy(codeName)) {
25730
- if (agentState.persistentSessionAgents.has(codeName)) {
26010
+ const zombie = takeZombieDetection(codeName);
26011
+ if (zombie?.kind === "migrated") {
26012
+ log(
26013
+ `[persistent-session] MIGRATED '${codeName}' host -> container: a live session started on the host path by an earlier manager was found on an isolated host; ended it so the respawn starts it in its container. Not a crash; pending inbound is kept and replays into the new session.`
26014
+ );
26015
+ lastRestartWasExternal.set(codeName, true);
26016
+ getHostId().then((hostId) => {
26017
+ if (!hostId) return;
26018
+ return api.post("/host/events", {
26019
+ host_id: hostId,
26020
+ agent_code_name: codeName,
26021
+ event_type: "manager.agent_migrated_to_container",
26022
+ payload: {
26023
+ agent_code_name: codeName,
26024
+ agent_id: agent.agent_id,
26025
+ tmux_session: zombie.tmuxSession,
26026
+ detected_at: new Date(zombie.detectedAt).toISOString(),
26027
+ from: "host",
26028
+ to: "container"
26029
+ },
26030
+ timestamp: new Date(zombie.detectedAt).toISOString()
26031
+ });
26032
+ }).catch((err) => {
26033
+ log(`[persistent-session] Failed to forward migration audit event for '${codeName}': ${err.message}`);
26034
+ });
26035
+ } else if (agentState.persistentSessionAgents.has(codeName)) {
25731
26036
  const ctx = getLastFailureContext(codeName);
25732
26037
  const recovery = prepareForRespawn(codeName);
25733
26038
  const tailSummary = !ctx.tail ? "" : KNOWN_SAFE_TAIL_SIGNATURES.has(ctx.signature) ? `; last pane output (${PANE_TAIL_PREVIEW_LINES} of ~20 lines):
@@ -25738,8 +26043,7 @@ ${truncateForLog(ctx.tail)}` : `; pane_tail_hash=sha256:${createHash21("sha256")
25738
26043
  `[persistent-session] Session for '${codeName}' is unhealthy (restart #${ctx.restartCount}${sigSummary}${recoverySummary}), will restart${tailSummary}`
25739
26044
  );
25740
26045
  }
25741
- const zombie = takeZombieDetection(codeName);
25742
- if (zombie) {
26046
+ if (zombie?.kind === "zombie") {
25743
26047
  log(
25744
26048
  `[persistent-session] ZOMBIE DETECTED for '${codeName}' \u2014 tmux session ${zombie.tmuxSession} alive but no claude process inside; killed shell, will respawn`
25745
26049
  );
@@ -26374,7 +26678,7 @@ async function handleRestartDoorbell(agentId, requestedAt, restartReason) {
26374
26678
  if (!refreshData) return;
26375
26679
  const framework = refreshData.agent?.framework ?? agentFrameworkCache.get(codeName) ?? DEFAULT_FRAMEWORK;
26376
26680
  const hostId = await getHostId();
26377
- const parkForRestart = await import("../responsiveness-probe-FWPQTPQ5.js").then(
26681
+ const parkForRestart = await import("../responsiveness-probe-X3SNNEDY.js").then(
26378
26682
  (m) => m.parkPendingInbound,
26379
26683
  (err) => err
26380
26684
  );
@@ -26451,7 +26755,7 @@ async function handleRestartDoorbell(agentId, requestedAt, restartReason) {
26451
26755
  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}`));
26452
26756
  void (async () => {
26453
26757
  try {
26454
- const { collectDiagnostics } = await import("../persistent-session-LMR3WHVO.js");
26758
+ const { collectDiagnostics } = await import("../persistent-session-ISLJXHGH.js");
26455
26759
  await api.post("/host/heartbeat", {
26456
26760
  host_id: hostId,
26457
26761
  agent_diagnostics: collectDiagnostics([codeName], quarantineEntriesFor, claudeMdSizeFor, spawnOutcomeForDiagnostics, pidPressureFor, forwardedToolsFor, runtimeVersionFor, sessionActivityFor)
@@ -26504,7 +26808,7 @@ async function respawnAgentAfterMcpStop(codeName, reason) {
26504
26808
  }
26505
26809
  try {
26506
26810
  const hostId = await getHostId();
26507
- const { collectDiagnostics } = await import("../persistent-session-LMR3WHVO.js");
26811
+ const { collectDiagnostics } = await import("../persistent-session-ISLJXHGH.js");
26508
26812
  await api.post("/host/heartbeat", {
26509
26813
  host_id: hostId,
26510
26814
  agent_diagnostics: collectDiagnostics([codeName], quarantineEntriesFor, claudeMdSizeFor, spawnOutcomeForDiagnostics, pidPressureFor, forwardedToolsFor, runtimeVersionFor, sessionActivityFor)
@@ -27046,6 +27350,18 @@ var KANBAN_HYBRID_MAX_CADENCE_MS = (() => {
27046
27350
  if (Number.isFinite(parsed) && parsed > 0) return Math.max(parsed * 1e3, KANBAN_HYBRID_FULL_CADENCE_MS);
27047
27351
  return Math.max(60 * 6e4, KANBAN_HYBRID_FULL_CADENCE_MS);
27048
27352
  })();
27353
+ var KANBAN_HYBRID_BACKLOG_FULL_CADENCE_MS = (() => {
27354
+ const raw = process.env["AGT_KANBAN_HYBRID_BACKLOG_FULL_CADENCE_SECONDS"];
27355
+ const parsed = raw ? parseInt(raw, 10) : NaN;
27356
+ if (Number.isFinite(parsed) && parsed > 0) return Math.max(parsed * 1e3, KANBAN_HYBRID_MAX_CADENCE_MS);
27357
+ return Math.max(60 * 6e4, KANBAN_HYBRID_MAX_CADENCE_MS);
27358
+ })();
27359
+ var KANBAN_HYBRID_BACKLOG_MAX_CADENCE_MS = (() => {
27360
+ const raw = process.env["AGT_KANBAN_HYBRID_BACKLOG_MAX_CADENCE_SECONDS"];
27361
+ const parsed = raw ? parseInt(raw, 10) : NaN;
27362
+ if (Number.isFinite(parsed) && parsed > 0) return Math.max(parsed * 1e3, KANBAN_HYBRID_BACKLOG_FULL_CADENCE_MS);
27363
+ return Math.max(24 * 60 * 6e4, KANBAN_HYBRID_BACKLOG_FULL_CADENCE_MS);
27364
+ })();
27049
27365
  async function injectKanbanCheckViaDirectChat(codeName, agentId, actionableCount) {
27050
27366
  if (isKanbanHybridDryRun()) {
27051
27367
  log(
@@ -27080,7 +27396,7 @@ ${formatRunMarker(run_id)}` : KANBAN_CHECK_COMMAND;
27080
27396
  );
27081
27397
  return true;
27082
27398
  }
27083
- async function maybeInjectKanbanCheck(codeName, agentId, actionableCount, signature) {
27399
+ async function maybeInjectKanbanCheck(codeName, agentId, actionableCount, signature, backlogOnly = false) {
27084
27400
  const failureGate = shouldAttemptNoticeEnqueue(
27085
27401
  getKanbanNudgeState(codeName),
27086
27402
  Date.now(),
@@ -27092,8 +27408,8 @@ async function maybeInjectKanbanCheck(codeName, agentId, actionableCount, signat
27092
27408
  signature,
27093
27409
  getKanbanNudgeState(codeName),
27094
27410
  Date.now(),
27095
- KANBAN_HYBRID_FULL_CADENCE_MS,
27096
- KANBAN_HYBRID_MAX_CADENCE_MS
27411
+ backlogOnly ? KANBAN_HYBRID_BACKLOG_FULL_CADENCE_MS : KANBAN_HYBRID_FULL_CADENCE_MS,
27412
+ backlogOnly ? KANBAN_HYBRID_BACKLOG_MAX_CADENCE_MS : KANBAN_HYBRID_MAX_CADENCE_MS
27097
27413
  )) {
27098
27414
  return;
27099
27415
  }
@@ -27231,7 +27547,7 @@ async function processClaudePairSessions(agents) {
27231
27547
  snapshotPairConfig,
27232
27548
  // ENG-11659: result -> report body + the manager.log line that records it.
27233
27549
  planPairStartReport
27234
- } = await import("../claude-pair-runtime-TUVLJDJZ.js");
27550
+ } = await import("../claude-pair-runtime-L6XQTJKV.js");
27235
27551
  const { resetClaudeSignin, describeSigninResetForLog, describeSigninResetFailure } = await import("../claude-signin-reset-6IJMMVYG.js");
27236
27552
  for (const pairId of pendingResp.cancelled_pair_ids ?? []) {
27237
27553
  log(`[claude-pair] sweeping orphan tmux session for pair ${pairId.slice(0, 8)}`);