@integrity-labs/agt-cli 0.28.1289 → 0.28.1291

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-LVYFYF3Z.js → api-client-6L3L4HKS.js} +3 -3
  2. package/dist/bin/agt.js +7 -7
  3. package/dist/{chunk-X7ZRYILH.js → chunk-3NCSZIK4.js} +2 -2
  4. package/dist/{chunk-JNEXXGKW.js → chunk-G4T3PGWR.js} +3 -3
  5. package/dist/{chunk-FRNONFQA.js → chunk-IPWGWDON.js} +2 -2
  6. package/dist/{chunk-DITI25ZO.js → chunk-LAJEUIP7.js} +35 -3
  7. package/dist/chunk-LAJEUIP7.js.map +1 -0
  8. package/dist/{chunk-WIU4M5EF.js → chunk-QSIKMH7L.js} +3 -3
  9. package/dist/{chunk-OJWLTVBR.js → chunk-RPZSSKF7.js} +5 -5
  10. package/dist/{claude-code-updater-6NRYKDKS.js → claude-code-updater-NBWLPWZU.js} +3 -3
  11. package/dist/{claude-pair-runtime-PMGEAT3Z.js → claude-pair-runtime-3RJNQ3XJ.js} +3 -3
  12. package/dist/lib/manager-worker.js +330 -57
  13. package/dist/lib/manager-worker.js.map +1 -1
  14. package/dist/mcp/direct-chat-channel.js +34 -2
  15. package/dist/mcp/index.js +34 -2
  16. package/dist/mcp/origami.js +34 -2
  17. package/dist/mcp/slack-channel.js +34 -2
  18. package/dist/mcp/telegram-channel.js +34 -2
  19. package/dist/mcp/xero.js +44 -11
  20. package/dist/{persistent-session-XYZN6NSP.js → persistent-session-Q5FJJAFR.js} +4 -4
  21. package/dist/{responsiveness-probe-NIH64ZZE.js → responsiveness-probe-EYIQ2RPD.js} +4 -4
  22. package/dist/{session-auth-dead-IBUKQXBO.js → session-auth-dead-TYDPUWCV.js} +3 -3
  23. package/package.json +1 -1
  24. package/dist/chunk-DITI25ZO.js.map +0 -1
  25. /package/dist/{api-client-LVYFYF3Z.js.map → api-client-6L3L4HKS.js.map} +0 -0
  26. /package/dist/{chunk-X7ZRYILH.js.map → chunk-3NCSZIK4.js.map} +0 -0
  27. /package/dist/{chunk-JNEXXGKW.js.map → chunk-G4T3PGWR.js.map} +0 -0
  28. /package/dist/{chunk-FRNONFQA.js.map → chunk-IPWGWDON.js.map} +0 -0
  29. /package/dist/{chunk-WIU4M5EF.js.map → chunk-QSIKMH7L.js.map} +0 -0
  30. /package/dist/{chunk-OJWLTVBR.js.map → chunk-RPZSSKF7.js.map} +0 -0
  31. /package/dist/{claude-code-updater-6NRYKDKS.js.map → claude-code-updater-NBWLPWZU.js.map} +0 -0
  32. /package/dist/{claude-pair-runtime-PMGEAT3Z.js.map → claude-pair-runtime-3RJNQ3XJ.js.map} +0 -0
  33. /package/dist/{persistent-session-XYZN6NSP.js.map → persistent-session-Q5FJJAFR.js.map} +0 -0
  34. /package/dist/{responsiveness-probe-NIH64ZZE.js.map → responsiveness-probe-EYIQ2RPD.js.map} +0 -0
  35. /package/dist/{session-auth-dead-IBUKQXBO.js.map → session-auth-dead-TYDPUWCV.js.map} +0 -0
@@ -70,7 +70,7 @@ import {
70
70
  tripClass,
71
71
  writeEtcEnvironment,
72
72
  writeProfileDScript
73
- } from "../chunk-OJWLTVBR.js";
73
+ } from "../chunk-RPZSSKF7.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-JNEXXGKW.js";
91
+ } from "../chunk-G4T3PGWR.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-WIU4M5EF.js";
183
+ } from "../chunk-QSIKMH7L.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-X7ZRYILH.js";
194
+ } from "../chunk-3NCSZIK4.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-FRNONFQA.js";
220
+ } from "../chunk-IPWGWDON.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-DITI25ZO.js";
349
+ } from "../chunk-LAJEUIP7.js";
350
350
  import {
351
351
  CLAUDE_CONFIG_DIR_ENV,
352
352
  claudeConfigDirFor,
@@ -4698,6 +4698,128 @@ function isDirectChatMessageExpired(createdAt, nowMs, maxAgeMs) {
4698
4698
  return nowMs - created > maxAgeMs;
4699
4699
  }
4700
4700
 
4701
+ // src/lib/direct-chat-poll-coalescer.ts
4702
+ function createPollCoalescer(opts) {
4703
+ const states = /* @__PURE__ */ new Map();
4704
+ return {
4705
+ stats: (key) => {
4706
+ const s = states.get(key);
4707
+ return s ? { running: s.running, pending: s.pending } : void 0;
4708
+ },
4709
+ kick: (key, run) => {
4710
+ const existing = states.get(key);
4711
+ const state10 = existing ?? { running: false, pending: false, run };
4712
+ if (!existing) states.set(key, state10);
4713
+ state10.run = run;
4714
+ if (state10.running) {
4715
+ state10.pending = true;
4716
+ return;
4717
+ }
4718
+ state10.running = true;
4719
+ void (async () => {
4720
+ try {
4721
+ do {
4722
+ state10.pending = false;
4723
+ try {
4724
+ await state10.run();
4725
+ } catch (err) {
4726
+ opts.onError(key, err);
4727
+ }
4728
+ } while (state10.pending);
4729
+ } finally {
4730
+ state10.running = false;
4731
+ }
4732
+ })();
4733
+ }
4734
+ };
4735
+ }
4736
+
4737
+ // src/lib/direct-chat-delivered-ledger.ts
4738
+ var DELIVERED_LEDGER_MAX = 2e3;
4739
+ function createDeliveredLedger(max = DELIVERED_LEDGER_MAX) {
4740
+ const seen = /* @__PURE__ */ new Set();
4741
+ return {
4742
+ has: (id) => seen.has(id),
4743
+ mark: (id) => {
4744
+ if (seen.has(id)) return;
4745
+ seen.add(id);
4746
+ while (seen.size > max) {
4747
+ const oldest = seen.values().next();
4748
+ if (oldest.done === true) break;
4749
+ seen.delete(oldest.value);
4750
+ }
4751
+ },
4752
+ size: () => seen.size
4753
+ };
4754
+ }
4755
+
4756
+ // src/lib/agent-status-ledger.ts
4757
+ function createAgentStatusLedger() {
4758
+ let seen = /* @__PURE__ */ new Map();
4759
+ return {
4760
+ note: (agentStates) => {
4761
+ const next = /* @__PURE__ */ new Map();
4762
+ for (const a of agentStates) next.set(a.agentId, a.status);
4763
+ seen = next;
4764
+ },
4765
+ get: (agentId) => seen.get(agentId),
4766
+ forget: (agentId) => {
4767
+ seen.delete(agentId);
4768
+ },
4769
+ size: () => seen.size
4770
+ };
4771
+ }
4772
+
4773
+ // src/lib/direct-chat-route.ts
4774
+ function routeDirectChatMessage(input) {
4775
+ const { framework, railEnabled, dockerIsolated, hasBody, ringFailed } = input;
4776
+ if (framework === "opencode") {
4777
+ return hasBody ? { kind: "inject" } : { kind: "kick" };
4778
+ }
4779
+ if (!railEnabled) {
4780
+ return hasBody ? { kind: "inject" } : { kind: "kick" };
4781
+ }
4782
+ if (hasBody) {
4783
+ return { kind: "inject" };
4784
+ }
4785
+ if (!ringFailed) {
4786
+ return { kind: "ring" };
4787
+ }
4788
+ return {
4789
+ kind: "leave-pending",
4790
+ why: dockerIsolated ? "doorbell ring failed for an isolated agent; its in-session safety-net poll will claim it, keeping the queue cursor and delivery record (ENG-10688)" : "doorbell ring failed for a flag-rail agent; the manager must not claim for it, and its in-session safety-net poll runs regardless of the ring (ENG-11719)"
4791
+ };
4792
+ }
4793
+ function mayManagerPoll(input) {
4794
+ if (input.framework === "opencode") return true;
4795
+ return !input.railEnabled;
4796
+ }
4797
+ var REKICK_MIN_MS = 250;
4798
+ var REKICK_MAX_MS = 3e4;
4799
+ var REKICK_CHAIN_MAX_MS = 15e4;
4800
+ function nextDirectChatPoll(input) {
4801
+ const { retryAfterMs, claimed, chainElapsedMs, failed } = input;
4802
+ const spent = chainElapsedMs >= REKICK_CHAIN_MAX_MS;
4803
+ if (failed === true) {
4804
+ if (spent) return { kind: "bound-reached" };
4805
+ const step = Math.max(0, Math.floor(chainElapsedMs / REKICK_MIN_MS));
4806
+ const backoff = Math.min(REKICK_MAX_MS, REKICK_MIN_MS * 2 ** Math.min(step, 10));
4807
+ return { kind: "again", delayMs: backoff, reason: "failed" };
4808
+ }
4809
+ let candidate = null;
4810
+ if (typeof retryAfterMs === "number" && Number.isFinite(retryAfterMs) && retryAfterMs > 0) {
4811
+ candidate = {
4812
+ delayMs: Math.max(REKICK_MIN_MS, Math.min(REKICK_MAX_MS, retryAfterMs)),
4813
+ reason: "held"
4814
+ };
4815
+ } else if (claimed > 0) {
4816
+ candidate = { delayMs: REKICK_MIN_MS, reason: "full-page" };
4817
+ }
4818
+ if (candidate === null) return { kind: "done" };
4819
+ if (spent) return { kind: "bound-reached" };
4820
+ return { kind: "again", delayMs: candidate.delayMs, reason: candidate.reason };
4821
+ }
4822
+
4701
4823
  // src/lib/review-poster-asset.ts
4702
4824
  import { copyFileSync as copyFileSync2, chmodSync, existsSync as existsSync2, mkdirSync as mkdirSync5, readFileSync as readFileSync11 } from "fs";
4703
4825
  import { dirname as dirname5, join as join11 } from "path";
@@ -15444,7 +15566,7 @@ function createFileMigrationReportIO(codeName, log2) {
15444
15566
  };
15445
15567
  }
15446
15568
  var managerHostPost = async (path, body) => {
15447
- const { api: api2, ApiError: ApiError3 } = await import("../api-client-LVYFYF3Z.js");
15569
+ const { api: api2, ApiError: ApiError3 } = await import("../api-client-6L3L4HKS.js");
15448
15570
  try {
15449
15571
  const json = await api2.post(path, body);
15450
15572
  return { status: 200, json };
@@ -16153,8 +16275,17 @@ function ensureClient(config2) {
16153
16275
  client.realtime.setAuth(config2.token);
16154
16276
  return client;
16155
16277
  }
16278
+ function projectDirectChatDoorbell(row) {
16279
+ if (row["status"] !== "pending") return null;
16280
+ return {
16281
+ id: String(row["id"]),
16282
+ agent_id: String(row["agent_id"]),
16283
+ session_id: String(row["session_id"]),
16284
+ status: String(row["status"])
16285
+ };
16286
+ }
16156
16287
  function startRealtimeChat(config2) {
16157
- const { agentIds, onMessage, onStatusChange, log: log2 } = config2;
16288
+ const { agentIds, onDoorbell, onStatusChange, log: log2 } = config2;
16158
16289
  if (agentIds.length === 0) return;
16159
16290
  const sb = ensureClient(config2);
16160
16291
  const filterStr = agentIds.length === 1 ? `agent_id=eq.${agentIds[0]}` : `agent_id=in.(${agentIds.join(",")})`;
@@ -16164,10 +16295,10 @@ function startRealtimeChat(config2) {
16164
16295
  table: "direct_chat_messages",
16165
16296
  filter: filterStr
16166
16297
  }, (payload) => {
16167
- const msg = payload.new;
16168
- if (msg.status !== "pending") return;
16169
- log2(`[realtime] Chat message for agent ${msg.agent_id}: id=${msg.id}`);
16170
- onMessage(msg);
16298
+ const doorbell = projectDirectChatDoorbell(payload.new);
16299
+ if (!doorbell) return;
16300
+ log2(`[realtime] Chat doorbell for agent ${doorbell.agent_id}: id=${doorbell.id}`);
16301
+ onDoorbell(doorbell);
16171
16302
  }).subscribe((status) => {
16172
16303
  if (status === "SUBSCRIBED") {
16173
16304
  connected = true;
@@ -17499,7 +17630,7 @@ var pendingDayRolloverReset = /* @__PURE__ */ new Set();
17499
17630
  var dayRolloverInboundHold = /* @__PURE__ */ new Map();
17500
17631
  var INBOUND_HOLD_EPISODE_GAP_MS = 12e4;
17501
17632
  async function channelInboundActivityAgeSecondsFor(codeName) {
17502
- const { newestPendingInboundActivityMtimeMs } = await import("../responsiveness-probe-NIH64ZZE.js");
17633
+ const { newestPendingInboundActivityMtimeMs } = await import("../responsiveness-probe-EYIQ2RPD.js");
17503
17634
  const newest = newestPendingInboundActivityMtimeMs(dirname11(paneLogPath(codeName)));
17504
17635
  if (newest === null) return null;
17505
17636
  return Math.max(0, Math.floor((Date.now() - newest) / 1e3));
@@ -18325,6 +18456,8 @@ function resolveAgentFramework(codeName) {
18325
18456
  function clearAgentCaches(agentId, codeName) {
18326
18457
  const channelCacheMutated = clearAgentState(agentId, codeName);
18327
18458
  agentChannelTokens.delete(codeName);
18459
+ directChatChainStart.delete(agentId);
18460
+ agentStatusLedger.forget(agentId);
18328
18461
  blockedPromptCost.forget(codeName);
18329
18462
  pendingRecoveryCost.delete(codeName);
18330
18463
  lastRefreshPayload.delete(agentId);
@@ -18380,7 +18513,7 @@ var agentRestartTimezoneInputs = /* @__PURE__ */ new Map();
18380
18513
  var lastVersionCheckAt = 0;
18381
18514
  var VERSION_CHECK_INTERVAL_MS = 5 * 60 * 1e3;
18382
18515
  var lastResponsivenessProbeAt = 0;
18383
- var agtCliVersion = true ? "0.28.1289" : "dev";
18516
+ var agtCliVersion = true ? "0.28.1291" : "dev";
18384
18517
  function resolveBrewPath(execFileSync5) {
18385
18518
  try {
18386
18519
  const out = execFileSync5("which", ["brew"], { timeout: 5e3 }).toString().trim();
@@ -20491,7 +20624,7 @@ function flushRestartedAgentDiagnostics(hostId, codeNames) {
20491
20624
  if (codeNames.length === 0) return;
20492
20625
  void (async () => {
20493
20626
  try {
20494
- const { collectDiagnostics } = await import("../persistent-session-XYZN6NSP.js");
20627
+ const { collectDiagnostics } = await import("../persistent-session-Q5FJJAFR.js");
20495
20628
  await api.post("/host/heartbeat", {
20496
20629
  host_id: hostId,
20497
20630
  agent_diagnostics: collectDiagnostics(codeNames, quarantineEntriesFor, claudeMdSizeFor, spawnOutcomeForDiagnostics, pidPressureFor, forwardedToolsFor, runtimeVersionFor, sessionActivityFor)
@@ -20634,7 +20767,7 @@ async function pollCycleInner() {
20634
20767
  }
20635
20768
  try {
20636
20769
  const { detectHostSecurity } = await import("../host-security-KQYYZZVW.js");
20637
- const { collectDiagnostics } = await import("../persistent-session-XYZN6NSP.js");
20770
+ const { collectDiagnostics } = await import("../persistent-session-Q5FJJAFR.js");
20638
20771
  const diagCodeNames = [...agentState.persistentSessionAgents];
20639
20772
  const agentDiagnostics = diagCodeNames.length > 0 ? collectDiagnostics(diagCodeNames, quarantineEntriesFor, claudeMdSizeFor, spawnOutcomeForDiagnostics, pidPressureFor, forwardedToolsFor, runtimeVersionFor, sessionActivityFor) : void 0;
20640
20773
  let tailscaleHostname;
@@ -20933,7 +21066,7 @@ async function pollCycleInner() {
20933
21066
  }
20934
21067
  try {
20935
21068
  const desiredClaudeCodeVersion = hbResp?.desired_claude_code_version?.trim();
20936
- const { maybeUpdateClaudeCode, shouldRunClaudeCodeUpdater } = await import("../claude-code-updater-6NRYKDKS.js");
21069
+ const { maybeUpdateClaudeCode, shouldRunClaudeCodeUpdater } = await import("../claude-code-updater-NBWLPWZU.js");
20937
21070
  const securityFloor = currentSecurityFloor();
20938
21071
  claudeUpdaterInFlight = true;
20939
21072
  if (desiredClaudeCodeVersion && (claudePairLoop.busy || claudePairingInProgress())) {
@@ -20968,7 +21101,7 @@ async function pollCycleInner() {
20968
21101
  collectPanelessActivityProbes,
20969
21102
  getResponsivenessIntervalMs,
20970
21103
  occupancyQualificationClassifications
20971
- } = await import("../responsiveness-probe-NIH64ZZE.js");
21104
+ } = await import("../responsiveness-probe-EYIQ2RPD.js");
20972
21105
  const probeIntervalMs = getResponsivenessIntervalMs();
20973
21106
  if (now - lastResponsivenessProbeAt > probeIntervalMs) {
20974
21107
  const probeCodeNames = [...agentState.persistentSessionAgents];
@@ -21085,7 +21218,7 @@ async function pollCycleInner() {
21085
21218
  collectResponsivenessProbes,
21086
21219
  livePendingInboundOldestAgeSeconds,
21087
21220
  parkPendingInbound
21088
- } = await import("../responsiveness-probe-NIH64ZZE.js");
21221
+ } = await import("../responsiveness-probe-EYIQ2RPD.js");
21089
21222
  const { getProjectDir: wedgeProjectDir } = await import("../scheduler-engine-5PCBGRNY.js");
21090
21223
  const wedgeNow = /* @__PURE__ */ new Date();
21091
21224
  const liveAgents = agentState.persistentSessionAgents;
@@ -21371,7 +21504,7 @@ async function pollCycleInner() {
21371
21504
  }
21372
21505
  }
21373
21506
  );
21374
- const { parkPendingInbound } = await import("../responsiveness-probe-NIH64ZZE.js");
21507
+ const { parkPendingInbound } = await import("../responsiveness-probe-EYIQ2RPD.js");
21375
21508
  const { parked, deadLettered } = parkPendingInbound(codeName, new Date(fatalNowMs));
21376
21509
  paneFatalStreak.delete(codeName);
21377
21510
  paneFatalRestarts.set(codeName, [...history, fatalNowMs]);
@@ -21402,7 +21535,7 @@ async function pollCycleInner() {
21402
21535
  TRANSCRIPT_MOUNT_ESCALATION_REFRESH_MS,
21403
21536
  bindSourceEscalations
21404
21537
  } = await import("../transcript-mount-health-OHE6IVJV.js");
21405
- const { transcriptBindSourcesFor, ensureTranscriptBindSources } = await import("../persistent-session-XYZN6NSP.js");
21538
+ const { transcriptBindSourcesFor, ensureTranscriptBindSources } = await import("../persistent-session-Q5FJJAFR.js");
21406
21539
  const mountConfig = resolveTranscriptMountConfig();
21407
21540
  const liveAgents = agentState.persistentSessionAgents;
21408
21541
  for (const tracked of [
@@ -21567,7 +21700,7 @@ async function pollCycleInner() {
21567
21700
  }
21568
21701
  try {
21569
21702
  const { scrapeMcpFailedBannerCount } = await import("../pane-mcp-banner-scraper-VR5QGP3J.js");
21570
- const { probeSessionAuth } = await import("../session-auth-dead-IBUKQXBO.js");
21703
+ const { probeSessionAuth } = await import("../session-auth-dead-TYDPUWCV.js");
21571
21704
  const observations = [];
21572
21705
  const pendingCacheCommits = [];
21573
21706
  const modelApiErrorReportingOn = hostFlagStore().getBoolean("model-api-error-reporting");
@@ -22294,6 +22427,7 @@ async function pollCycleInner() {
22294
22427
  });
22295
22428
  }
22296
22429
  }
22430
+ noteAgentStatuses(agentStates);
22297
22431
  ensureRealtimeStarted(agentStates);
22298
22432
  ensureRealtimeDriftStarted(agentStates);
22299
22433
  ensureRealtimeAssignStarted(agentStates);
@@ -26524,20 +26658,19 @@ function ensureRealtimeStarted(agentStates) {
26524
26658
  supabaseAnonKey: exchange.supabaseAnonKey,
26525
26659
  token: exchange.token,
26526
26660
  agentIds: activeAgentIds,
26527
- onMessage: (msg) => {
26661
+ onDoorbell: (msg) => {
26528
26662
  const agent = agentStates.find((a) => a.agentId === msg.agent_id);
26529
26663
  if (!agent) return;
26530
- if (directChatInFlight.has(msg.id)) return;
26531
- directChatInFlight.add(msg.id);
26664
+ if (directChatDoorbellInFlight.has(msg.id)) return;
26665
+ directChatDoorbellInFlight.add(msg.id);
26532
26666
  void dispatchDirectChatMessage({
26533
26667
  id: msg.id,
26534
26668
  codeName: agent.codeName,
26535
26669
  process: () => processDirectChatMessage(agent, {
26536
26670
  id: msg.id,
26537
- session_id: msg.session_id,
26538
- content: msg.content
26671
+ session_id: msg.session_id
26539
26672
  }),
26540
- inFlight: directChatInFlight,
26673
+ inFlight: directChatDoorbellInFlight,
26541
26674
  log
26542
26675
  });
26543
26676
  },
@@ -26678,7 +26811,7 @@ async function handleRestartDoorbell(agentId, requestedAt, restartReason) {
26678
26811
  if (!refreshData) return;
26679
26812
  const framework = refreshData.agent?.framework ?? agentFrameworkCache.get(codeName) ?? DEFAULT_FRAMEWORK;
26680
26813
  const hostId = await getHostId();
26681
- const parkForRestart = await import("../responsiveness-probe-NIH64ZZE.js").then(
26814
+ const parkForRestart = await import("../responsiveness-probe-EYIQ2RPD.js").then(
26682
26815
  (m) => m.parkPendingInbound,
26683
26816
  (err) => err
26684
26817
  );
@@ -26755,7 +26888,7 @@ async function handleRestartDoorbell(agentId, requestedAt, restartReason) {
26755
26888
  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}`));
26756
26889
  void (async () => {
26757
26890
  try {
26758
- const { collectDiagnostics } = await import("../persistent-session-XYZN6NSP.js");
26891
+ const { collectDiagnostics } = await import("../persistent-session-Q5FJJAFR.js");
26759
26892
  await api.post("/host/heartbeat", {
26760
26893
  host_id: hostId,
26761
26894
  agent_diagnostics: collectDiagnostics([codeName], quarantineEntriesFor, claudeMdSizeFor, spawnOutcomeForDiagnostics, pidPressureFor, forwardedToolsFor, runtimeVersionFor, sessionActivityFor)
@@ -26808,7 +26941,7 @@ async function respawnAgentAfterMcpStop(codeName, reason) {
26808
26941
  }
26809
26942
  try {
26810
26943
  const hostId = await getHostId();
26811
- const { collectDiagnostics } = await import("../persistent-session-XYZN6NSP.js");
26944
+ const { collectDiagnostics } = await import("../persistent-session-Q5FJJAFR.js");
26812
26945
  await api.post("/host/heartbeat", {
26813
26946
  host_id: hostId,
26814
26947
  agent_diagnostics: collectDiagnostics([codeName], quarantineEntriesFor, claudeMdSizeFor, spawnOutcomeForDiagnostics, pidPressureFor, forwardedToolsFor, runtimeVersionFor, sessionActivityFor)
@@ -27063,6 +27196,16 @@ function triggerEarlyPoll(reason, agentId) {
27063
27196
  }, 0);
27064
27197
  }
27065
27198
  var directChatInFlight = /* @__PURE__ */ new Set();
27199
+ var directChatDoorbellInFlight = /* @__PURE__ */ new Set();
27200
+ function usesDoorbellRail(agent) {
27201
+ return hostFlagStore().getBoolean("direct-chat-doorbell") || effectiveIsolationMode(agent.codeName) === "docker";
27202
+ }
27203
+ var directChatPollCoalescer = createPollCoalescer({
27204
+ onError: (agentId, err) => log(`[direct-chat] ENG-12293: doorbell kick failed for agent ${agentId}: ${describeRejection(err)}`)
27205
+ });
27206
+ function kickDirectChatPoll(agent) {
27207
+ directChatPollCoalescer.kick(agent.agentId, () => pollDirectChatForAgent(agent));
27208
+ }
27066
27209
  function describeRejection(err) {
27067
27210
  try {
27068
27211
  if (err instanceof Error) return typeof err.message === "string" ? err.message : "Error with no message";
@@ -27082,30 +27225,119 @@ async function dispatchDirectChatMessage(args) {
27082
27225
  );
27083
27226
  } finally {
27084
27227
  args.inFlight.delete(args.id);
27228
+ args.onSettled?.();
27085
27229
  }
27086
27230
  }
27231
+ function pollableForManagerDelivery(agent) {
27232
+ if (agent.status !== "active") return false;
27233
+ const fw = agentFrameworkCache.get(agent.codeName) ?? DEFAULT_FRAMEWORK;
27234
+ return mayManagerPoll({ framework: fw, railEnabled: usesDoorbellRail(agent) });
27235
+ }
27087
27236
  async function pollDirectChatMessages(agentStates) {
27088
27237
  for (const agent of agentStates) {
27089
- if (agent.status !== "active") continue;
27090
- try {
27091
- const data = await api.post("/host/direct-chat/poll", { agent_id: agent.agentId });
27092
- for (const msg of data.messages) {
27093
- if (directChatInFlight.has(msg.id)) continue;
27094
- directChatInFlight.add(msg.id);
27095
- void dispatchDirectChatMessage({
27096
- id: msg.id,
27097
- codeName: agent.codeName,
27098
- process: () => processDirectChatMessage(agent, msg),
27099
- inFlight: directChatInFlight,
27100
- log
27101
- });
27238
+ await pollDirectChatForAgent(agent);
27239
+ }
27240
+ }
27241
+ var directChatDelivered = createDeliveredLedger();
27242
+ var UNDELIVERED_RETRY_MS = 11 * 60 * 1e3;
27243
+ function scheduleUndeliveredRetry(agent, messageId) {
27244
+ if (directChatDelivered.has(messageId)) return;
27245
+ log(
27246
+ `[direct-chat] ENG-12293: msg=${messageId} for '${agent.codeName}' settled WITHOUT delivery \u2014 one more claim in ${UNDELIVERED_RETRY_MS / 6e4}m, after the stale-processing sweep makes it claimable again`
27247
+ );
27248
+ setTimeout(() => {
27249
+ if (directChatDelivered.has(messageId)) return;
27250
+ if (!stillPollableForManagerDelivery(agent)) {
27251
+ directChatChainStart.delete(agent.agentId);
27252
+ log(
27253
+ `[direct-chat] ENG-12293: dropping the undelivered retry for msg=${messageId} \u2014 '${agent.codeName}' is no longer pollable (status=${agentStatusLedger.get(agent.agentId) ?? "off-roster"})`
27254
+ );
27255
+ return;
27256
+ }
27257
+ kickDirectChatPoll(agent);
27258
+ }, UNDELIVERED_RETRY_MS).unref?.();
27259
+ }
27260
+ var agentStatusLedger = createAgentStatusLedger();
27261
+ function noteAgentStatuses(agentStates) {
27262
+ agentStatusLedger.note(agentStates);
27263
+ }
27264
+ function stillPollableForManagerDelivery(agent) {
27265
+ const current = agentStatusLedger.get(agent.agentId);
27266
+ if (current !== "active") return false;
27267
+ return pollableForManagerDelivery({ ...agent, status: current });
27268
+ }
27269
+ var directChatChainStart = /* @__PURE__ */ new Map();
27270
+ async function pollDirectChatForAgent(agent) {
27271
+ if (!pollableForManagerDelivery(agent)) {
27272
+ directChatChainStart.delete(agent.agentId);
27273
+ return;
27274
+ }
27275
+ const chainStartedAt = directChatChainStart.get(agent.agentId) ?? Date.now();
27276
+ directChatChainStart.set(agent.agentId, chainStartedAt);
27277
+ try {
27278
+ const data = await api.post("/host/direct-chat/poll", { agent_id: agent.agentId });
27279
+ for (const msg of data.messages) {
27280
+ if (directChatInFlight.has(msg.id)) continue;
27281
+ directChatInFlight.add(msg.id);
27282
+ void dispatchDirectChatMessage({
27283
+ id: msg.id,
27284
+ codeName: agent.codeName,
27285
+ process: () => processDirectChatMessage(agent, msg),
27286
+ inFlight: directChatInFlight,
27287
+ log,
27288
+ onSettled: () => scheduleUndeliveredRetry(agent, msg.id)
27289
+ });
27290
+ }
27291
+ const next = nextDirectChatPoll({
27292
+ retryAfterMs: data.retry_after_ms,
27293
+ claimed: data.messages.length,
27294
+ chainElapsedMs: Date.now() - chainStartedAt
27295
+ });
27296
+ if (next.kind === "done") {
27297
+ directChatChainStart.delete(agent.agentId);
27298
+ return;
27299
+ }
27300
+ if (next.kind === "bound-reached") {
27301
+ directChatChainStart.delete(agent.agentId);
27302
+ log(
27303
+ `[direct-chat] ENG-12293: re-kick chain for '${agent.codeName}' hit ${REKICK_CHAIN_MAX_MS}ms with more still to collect \u2014 pausing this chain and starting a fresh one in ${REKICK_CHAIN_MAX_MS}ms`
27304
+ );
27305
+ setTimeout(() => {
27306
+ if (!stillPollableForManagerDelivery(agent)) {
27307
+ directChatChainStart.delete(agent.agentId);
27308
+ return;
27309
+ }
27310
+ kickDirectChatPoll(agent);
27311
+ }, REKICK_CHAIN_MAX_MS).unref?.();
27312
+ return;
27313
+ }
27314
+ setTimeout(() => kickDirectChatPoll(agent), next.delayMs).unref?.();
27315
+ } catch (err) {
27316
+ log(`Direct chat poll failed for '${agent.codeName}': ${err.message}`);
27317
+ const after = nextDirectChatPoll({
27318
+ failed: true,
27319
+ claimed: 0,
27320
+ chainElapsedMs: Date.now() - chainStartedAt
27321
+ });
27322
+ if (after.kind !== "again") {
27323
+ directChatChainStart.delete(agent.agentId);
27324
+ if (after.kind === "bound-reached") {
27325
+ log(
27326
+ `[direct-chat] ENG-12293: giving up the retry chain for '${agent.codeName}' after ${REKICK_CHAIN_MAX_MS}ms of failures; the next message or a socket drop resumes it`
27327
+ );
27102
27328
  }
27103
- } catch (err) {
27104
- log(`Direct chat poll failed for '${agent.codeName}': ${err.message}`);
27329
+ return;
27105
27330
  }
27331
+ setTimeout(() => kickDirectChatPoll(agent), after.delayMs).unref?.();
27106
27332
  }
27107
27333
  }
27108
27334
  async function processDirectChatMessageOpencode(agent, msg) {
27335
+ if (directChatDelivered.has(msg.id)) {
27336
+ log(
27337
+ `[direct-chat] ENG-12293: msg=${msg.id} was already answered by '${agent.codeName}' \u2014 not re-injecting (the stale-processing reaper requeued it)`
27338
+ );
27339
+ return;
27340
+ }
27109
27341
  if (!isOpencodeSessionHealthy(agent.codeName)) {
27110
27342
  log(`[direct-chat] opencode server not running for '${agent.codeName}' (msg=${msg.id}) \u2014 leaving for redelivery`);
27111
27343
  return;
@@ -27166,6 +27398,7 @@ async function processDirectChatMessageOpencode(agent, msg) {
27166
27398
  })
27167
27399
  );
27168
27400
  }
27401
+ directChatDelivered.mark(msg.id);
27169
27402
  log(`[direct-chat] opencode replied for '${agent.codeName}' (msg=${msg.id}, ${result.reply.length} chars)`);
27170
27403
  } catch (err) {
27171
27404
  if (!recorded) {
@@ -27189,7 +27422,9 @@ async function processDirectChatMessageOpencode(agent, msg) {
27189
27422
  async function processDirectChatMessage(agent, msg) {
27190
27423
  noteInbound(agent.codeName);
27191
27424
  const fw = agentFrameworkCache.get(agent.codeName) ?? DEFAULT_FRAMEWORK;
27192
- log(`[direct-chat] Processing message for '${agent.codeName}' (fw=${fw}): id=${msg.id} len=${msg.content.length}`);
27425
+ log(
27426
+ `[direct-chat] Processing message for '${agent.codeName}' (fw=${fw}): id=${msg.id} ` + (msg.content === void 0 ? "body=doorbell (ENG-12293)" : `len=${msg.content.length}`)
27427
+ );
27193
27428
  if (isDirectChatMessageExpired(msg.created_at, Date.now(), directChatMaxAgeMs())) {
27194
27429
  log(`[direct-chat] Expired backlog message for '${agent.codeName}' (msg=${msg.id}, created_at=${msg.created_at}) \u2014 draining without delivery`);
27195
27430
  try {
@@ -27208,7 +27443,18 @@ async function processDirectChatMessage(agent, msg) {
27208
27443
  return;
27209
27444
  }
27210
27445
  if (fw === "opencode") {
27211
- await processDirectChatMessageOpencode(agent, msg);
27446
+ const ocRoute = routeDirectChatMessage({
27447
+ framework: "opencode",
27448
+ railEnabled: usesDoorbellRail(agent),
27449
+ dockerIsolated: effectiveIsolationMode(agent.codeName) === "docker",
27450
+ hasBody: msg.content !== void 0,
27451
+ ringFailed: false
27452
+ });
27453
+ if (ocRoute.kind === "kick") {
27454
+ kickDirectChatPoll(agent);
27455
+ return;
27456
+ }
27457
+ await processDirectChatMessageOpencode(agent, { ...msg, content: msg.content });
27212
27458
  return;
27213
27459
  }
27214
27460
  if (performLazyDayRolloverReset(agent.codeName, cachedAgentTimezoneFor(agent.codeName))) {
@@ -27241,8 +27487,16 @@ async function processDirectChatMessage(agent, msg) {
27241
27487
  }
27242
27488
  }
27243
27489
  if (!blockedOnPrompt && isSessionHealthy(agent.codeName)) {
27244
- const useDoorbell = hostFlagStore().getBoolean("direct-chat-doorbell") || effectiveIsolationMode(agent.codeName) === "docker";
27245
- if (useDoorbell) {
27490
+ const dockerIsolated = effectiveIsolationMode(agent.codeName) === "docker";
27491
+ const railEnabled = usesDoorbellRail(agent);
27492
+ let route = routeDirectChatMessage({
27493
+ framework: fw,
27494
+ railEnabled,
27495
+ dockerIsolated,
27496
+ hasBody: msg.content !== void 0,
27497
+ ringFailed: false
27498
+ });
27499
+ if (route.kind === "ring") {
27246
27500
  try {
27247
27501
  const doorbell = directChatDoorbellPath(agent.agentId, homedir17());
27248
27502
  mkdirSync18(dirname11(doorbell), { recursive: true });
@@ -27250,16 +27504,34 @@ async function processDirectChatMessage(agent, msg) {
27250
27504
  log(`[direct-chat] Doorbell rung for '${agent.codeName}' (msg=${msg.id}) \u2014 in-session MCP will pull via the cursor`);
27251
27505
  return;
27252
27506
  } catch (err) {
27253
- if (effectiveIsolationMode(agent.codeName) === "docker") {
27254
- log(`[direct-chat] Doorbell ring failed for isolated '${agent.codeName}' (msg=${msg.id}): ${err.message} \u2014 leaving pending for the in-session safety-net poll`);
27255
- return;
27256
- }
27257
- log(`[direct-chat] Doorbell ring failed for '${agent.codeName}' (msg=${msg.id}): ${err.message} \u2014 falling back to send-keys inject`);
27507
+ log(`[direct-chat] Doorbell ring failed for '${agent.codeName}' (msg=${msg.id}): ${err.message}`);
27508
+ route = routeDirectChatMessage({
27509
+ framework: fw,
27510
+ railEnabled,
27511
+ dockerIsolated,
27512
+ hasBody: msg.content !== void 0,
27513
+ ringFailed: true
27514
+ });
27258
27515
  }
27259
27516
  }
27517
+ if (route.kind === "leave-pending") {
27518
+ log(`[direct-chat] Leaving msg=${msg.id} pending for '${agent.codeName}': ${route.why}`);
27519
+ return;
27520
+ }
27521
+ if (route.kind === "kick") {
27522
+ kickDirectChatPoll(agent);
27523
+ return;
27524
+ }
27525
+ if (directChatDelivered.has(msg.id)) {
27526
+ log(
27527
+ `[direct-chat] ENG-12293: msg=${msg.id} was already delivered to '${agent.codeName}' \u2014 not injecting again (the stale-processing reaper requeued it mid-turn); the agent's reply still closes it`
27528
+ );
27529
+ return;
27530
+ }
27531
+ const messageBody = msg.content;
27260
27532
  const escapeXml = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&apos;");
27261
27533
  const channelEnvelope = `<channel source="direct-chat" session_id="${escapeXml(msg.session_id)}" user="webapp" ${laneTagFragment("conversational", true)}>
27262
- ${escapeXml(msg.content)}
27534
+ ${escapeXml(messageBody)}
27263
27535
  </channel>`;
27264
27536
  const delivered = await injectMessage(
27265
27537
  agent.codeName,
@@ -27269,6 +27541,7 @@ ${escapeXml(msg.content)}
27269
27541
  log
27270
27542
  );
27271
27543
  if (delivered) {
27544
+ directChatDelivered.mark(msg.id);
27272
27545
  log(`[direct-chat] Injected into persistent session for '${agent.codeName}' (msg=${msg.id}); agent will reply via direct_chat.reply tool`);
27273
27546
  return;
27274
27547
  }
@@ -27547,7 +27820,7 @@ async function processClaudePairSessions(agents) {
27547
27820
  snapshotPairConfig,
27548
27821
  // ENG-11659: result -> report body + the manager.log line that records it.
27549
27822
  planPairStartReport
27550
- } = await import("../claude-pair-runtime-PMGEAT3Z.js");
27823
+ } = await import("../claude-pair-runtime-3RJNQ3XJ.js");
27551
27824
  const { resetClaudeSignin, describeSigninResetForLog, describeSigninResetFailure } = await import("../claude-signin-reset-6IJMMVYG.js");
27552
27825
  for (const pairId of pendingResp.cancelled_pair_ids ?? []) {
27553
27826
  log(`[claude-pair] sweeping orphan tmux session for pair ${pairId.slice(0, 8)}`);