@integrity-labs/agt-cli 0.28.1290 → 0.28.1292

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.
@@ -15,7 +15,7 @@ import {
15
15
  mintRotatedHostKey,
16
16
  probeHostKey,
17
17
  setConfigHash
18
- } from "./chunk-XDMJSKLQ.js";
18
+ } from "./chunk-CNDXVFNT.js";
19
19
  import "./chunk-LAJEUIP7.js";
20
20
  import "./chunk-DGUM43GV.js";
21
21
  export {
@@ -36,4 +36,4 @@ export {
36
36
  probeHostKey,
37
37
  setConfigHash
38
38
  };
39
- //# sourceMappingURL=api-client-G5MBBP5G.js.map
39
+ //# sourceMappingURL=api-client-KSSMYKP7.js.map
package/dist/bin/agt.js CHANGED
@@ -31,7 +31,7 @@ import {
31
31
  success,
32
32
  table,
33
33
  warn
34
- } from "../chunk-6YJL5HCY.js";
34
+ } from "../chunk-Q5Y5WO2A.js";
35
35
  import {
36
36
  ApiError,
37
37
  PROD_AGT_HOST,
@@ -42,7 +42,7 @@ import {
42
42
  getHost,
43
43
  getHostId,
44
44
  setActiveTeam
45
- } from "../chunk-XDMJSKLQ.js";
45
+ } from "../chunk-CNDXVFNT.js";
46
46
  import {
47
47
  getProjectDir,
48
48
  isSessionResumeDisabled,
@@ -5207,7 +5207,7 @@ import { execFileSync, execSync } from "child_process";
5207
5207
  import { existsSync as existsSync10, realpathSync as realpathSync2 } from "fs";
5208
5208
  import chalk17 from "chalk";
5209
5209
  import ora15 from "ora";
5210
- var cliVersion = true ? "0.28.1290" : "dev";
5210
+ var cliVersion = true ? "0.28.1292" : "dev";
5211
5211
  async function fetchLatestVersion() {
5212
5212
  const host2 = getHost();
5213
5213
  if (!host2) return null;
@@ -6467,7 +6467,7 @@ function handleError(err) {
6467
6467
  }
6468
6468
 
6469
6469
  // src/bin/agt.ts
6470
- var cliVersion2 = true ? "0.28.1290" : "dev";
6470
+ var cliVersion2 = true ? "0.28.1292" : "dev";
6471
6471
  var program = new Command();
6472
6472
  program.name("agt").description("Augmented CLI \u2014 agent provisioning and management").version(cliVersion2).option("--json", "Emit machine-readable JSON output (suppress spinners and colors)").option("--skip-update-check", "Skip the automatic update check on startup");
6473
6473
  program.hook("preAction", async (thisCommand, actionCommand) => {
@@ -103,7 +103,7 @@ function exchangeFailureKind(err) {
103
103
  }
104
104
 
105
105
  // src/lib/api-client.ts
106
- var agtCliVersion = true ? "0.28.1290" : "dev";
106
+ var agtCliVersion = true ? "0.28.1292" : "dev";
107
107
  var lastConfigHash = null;
108
108
  function setConfigHash(hash) {
109
109
  lastConfigHash = hash && hash.length > 0 ? hash : null;
@@ -468,4 +468,4 @@ export {
468
468
  api,
469
469
  getHostId
470
470
  };
471
- //# sourceMappingURL=chunk-XDMJSKLQ.js.map
471
+ //# sourceMappingURL=chunk-CNDXVFNT.js.map
@@ -2,7 +2,7 @@ import {
2
2
  exchangeApiKey,
3
3
  getApiKey,
4
4
  getHost
5
- } from "./chunk-XDMJSKLQ.js";
5
+ } from "./chunk-CNDXVFNT.js";
6
6
  import {
7
7
  LATE_BOUND_VARS,
8
8
  PLATFORM_DENY_PERMISSIONS,
@@ -13853,4 +13853,4 @@ export {
13853
13853
  managerInstallSystemUnitCommand,
13854
13854
  managerUninstallSystemUnitCommand
13855
13855
  };
13856
- //# sourceMappingURL=chunk-6YJL5HCY.js.map
13856
+ //# sourceMappingURL=chunk-Q5Y5WO2A.js.map
@@ -70,7 +70,7 @@ import {
70
70
  tripClass,
71
71
  writeEtcEnvironment,
72
72
  writeProfileDScript
73
- } from "../chunk-6YJL5HCY.js";
73
+ } from "../chunk-Q5Y5WO2A.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-XDMJSKLQ.js";
91
+ } from "../chunk-CNDXVFNT.js";
92
92
  import {
93
93
  BLOCKED_ON_PROMPT_DECISION,
94
94
  CHANNEL_SECRET_ENV_KEYS,
@@ -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-G5MBBP5G.js");
15569
+ const { api: api2, ApiError: ApiError3 } = await import("../api-client-KSSMYKP7.js");
15448
15570
  try {
15449
15571
  const json = await api2.post(path, body);
15450
15572
  return { status: 200, json };
@@ -16082,6 +16204,29 @@ var PersistentSessionStuckTracker = class {
16082
16204
  }
16083
16205
  };
16084
16206
 
16207
+ // src/lib/heartbeat-diagnostics-code-names.ts
16208
+ function heartbeatDiagnosticsCodeNames(persistentSessionAgents, spawnOutcomeCodeNames) {
16209
+ const out = /* @__PURE__ */ new Set();
16210
+ for (const codeName of persistentSessionAgents) if (codeName) out.add(codeName);
16211
+ for (const codeName of spawnOutcomeCodeNames) if (codeName) out.add(codeName);
16212
+ return [...out];
16213
+ }
16214
+ var SpawnOutcomeRoster = class {
16215
+ recorded = /* @__PURE__ */ new Set();
16216
+ record(codeName) {
16217
+ if (codeName) this.recorded.add(codeName);
16218
+ }
16219
+ /** Every name recorded since the previous drain, then empty. */
16220
+ drain() {
16221
+ const out = [...this.recorded];
16222
+ this.recorded.clear();
16223
+ return out;
16224
+ }
16225
+ };
16226
+ function spawnOutcomeIfRecorded(outcomeFor, recordedSinceHeartbeat) {
16227
+ return (codeName) => recordedSinceHeartbeat.has(codeName) ? outcomeFor(codeName) : void 0;
16228
+ }
16229
+
16085
16230
  // src/lib/transient-api-error-log.ts
16086
16231
  var CODE_KIND = {
16087
16232
  "429": "rate_limit",
@@ -16153,8 +16298,17 @@ function ensureClient(config2) {
16153
16298
  client.realtime.setAuth(config2.token);
16154
16299
  return client;
16155
16300
  }
16301
+ function projectDirectChatDoorbell(row) {
16302
+ if (row["status"] !== "pending") return null;
16303
+ return {
16304
+ id: String(row["id"]),
16305
+ agent_id: String(row["agent_id"]),
16306
+ session_id: String(row["session_id"]),
16307
+ status: String(row["status"])
16308
+ };
16309
+ }
16156
16310
  function startRealtimeChat(config2) {
16157
- const { agentIds, onMessage, onStatusChange, log: log2 } = config2;
16311
+ const { agentIds, onDoorbell, onStatusChange, log: log2 } = config2;
16158
16312
  if (agentIds.length === 0) return;
16159
16313
  const sb = ensureClient(config2);
16160
16314
  const filterStr = agentIds.length === 1 ? `agent_id=eq.${agentIds[0]}` : `agent_id=in.(${agentIds.join(",")})`;
@@ -16164,10 +16318,10 @@ function startRealtimeChat(config2) {
16164
16318
  table: "direct_chat_messages",
16165
16319
  filter: filterStr
16166
16320
  }, (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);
16321
+ const doorbell = projectDirectChatDoorbell(payload.new);
16322
+ if (!doorbell) return;
16323
+ log2(`[realtime] Chat doorbell for agent ${doorbell.agent_id}: id=${doorbell.id}`);
16324
+ onDoorbell(doorbell);
16171
16325
  }).subscribe((status) => {
16172
16326
  if (status === "SUBSCRIBED") {
16173
16327
  connected = true;
@@ -17383,12 +17537,14 @@ function cancelPendingSessionRestart(codeName) {
17383
17537
  log(`[hot-reload] Cancelled pending restart timer for '${codeName}' (another teardown path is handling it)`);
17384
17538
  }
17385
17539
  var lastSpawnOutcomeByAgent = /* @__PURE__ */ new Map();
17540
+ var spawnOutcomesSinceHeartbeat = new SpawnOutcomeRoster();
17386
17541
  var lastSpawnDecisionByAgent = /* @__PURE__ */ new Map();
17387
17542
  function recordSpawnOutcome(codeName, result) {
17388
17543
  lastSpawnOutcomeByAgent.set(codeName, {
17389
17544
  spawnAttempted: result.spawnAttempted,
17390
17545
  sessionHealthyAfter: result.sessionHealthyAfter
17391
17546
  });
17547
+ spawnOutcomesSinceHeartbeat.record(codeName);
17392
17548
  if (result.decision) lastSpawnDecisionByAgent.set(codeName, result.decision);
17393
17549
  }
17394
17550
  function spawnOutcomeForDiagnostics(codeName) {
@@ -18325,6 +18481,8 @@ function resolveAgentFramework(codeName) {
18325
18481
  function clearAgentCaches(agentId, codeName) {
18326
18482
  const channelCacheMutated = clearAgentState(agentId, codeName);
18327
18483
  agentChannelTokens.delete(codeName);
18484
+ directChatChainStart.delete(agentId);
18485
+ agentStatusLedger.forget(agentId);
18328
18486
  blockedPromptCost.forget(codeName);
18329
18487
  pendingRecoveryCost.delete(codeName);
18330
18488
  lastRefreshPayload.delete(agentId);
@@ -18380,7 +18538,7 @@ var agentRestartTimezoneInputs = /* @__PURE__ */ new Map();
18380
18538
  var lastVersionCheckAt = 0;
18381
18539
  var VERSION_CHECK_INTERVAL_MS = 5 * 60 * 1e3;
18382
18540
  var lastResponsivenessProbeAt = 0;
18383
- var agtCliVersion = true ? "0.28.1290" : "dev";
18541
+ var agtCliVersion = true ? "0.28.1292" : "dev";
18384
18542
  function resolveBrewPath(execFileSync5) {
18385
18543
  try {
18386
18544
  const out = execFileSync5("which", ["brew"], { timeout: 5e3 }).toString().trim();
@@ -20635,8 +20793,10 @@ async function pollCycleInner() {
20635
20793
  try {
20636
20794
  const { detectHostSecurity } = await import("../host-security-KQYYZZVW.js");
20637
20795
  const { collectDiagnostics } = await import("../persistent-session-Q5FJJAFR.js");
20638
- const diagCodeNames = [...agentState.persistentSessionAgents];
20639
- const agentDiagnostics = diagCodeNames.length > 0 ? collectDiagnostics(diagCodeNames, quarantineEntriesFor, claudeMdSizeFor, spawnOutcomeForDiagnostics, pidPressureFor, forwardedToolsFor, runtimeVersionFor, sessionActivityFor) : void 0;
20796
+ const recordedSinceHeartbeat = new Set(spawnOutcomesSinceHeartbeat.drain());
20797
+ const diagCodeNames = heartbeatDiagnosticsCodeNames(agentState.persistentSessionAgents, recordedSinceHeartbeat);
20798
+ const heartbeatSpawnOutcomeFor = spawnOutcomeIfRecorded(spawnOutcomeForDiagnostics, recordedSinceHeartbeat);
20799
+ const agentDiagnostics = diagCodeNames.length > 0 ? collectDiagnostics(diagCodeNames, quarantineEntriesFor, claudeMdSizeFor, heartbeatSpawnOutcomeFor, pidPressureFor, forwardedToolsFor, runtimeVersionFor, sessionActivityFor) : void 0;
20640
20800
  let tailscaleHostname;
20641
20801
  try {
20642
20802
  const { execSync: es } = await import("child_process");
@@ -22294,6 +22454,7 @@ async function pollCycleInner() {
22294
22454
  });
22295
22455
  }
22296
22456
  }
22457
+ noteAgentStatuses(agentStates);
22297
22458
  ensureRealtimeStarted(agentStates);
22298
22459
  ensureRealtimeDriftStarted(agentStates);
22299
22460
  ensureRealtimeAssignStarted(agentStates);
@@ -26524,20 +26685,19 @@ function ensureRealtimeStarted(agentStates) {
26524
26685
  supabaseAnonKey: exchange.supabaseAnonKey,
26525
26686
  token: exchange.token,
26526
26687
  agentIds: activeAgentIds,
26527
- onMessage: (msg) => {
26688
+ onDoorbell: (msg) => {
26528
26689
  const agent = agentStates.find((a) => a.agentId === msg.agent_id);
26529
26690
  if (!agent) return;
26530
- if (directChatInFlight.has(msg.id)) return;
26531
- directChatInFlight.add(msg.id);
26691
+ if (directChatDoorbellInFlight.has(msg.id)) return;
26692
+ directChatDoorbellInFlight.add(msg.id);
26532
26693
  void dispatchDirectChatMessage({
26533
26694
  id: msg.id,
26534
26695
  codeName: agent.codeName,
26535
26696
  process: () => processDirectChatMessage(agent, {
26536
26697
  id: msg.id,
26537
- session_id: msg.session_id,
26538
- content: msg.content
26698
+ session_id: msg.session_id
26539
26699
  }),
26540
- inFlight: directChatInFlight,
26700
+ inFlight: directChatDoorbellInFlight,
26541
26701
  log
26542
26702
  });
26543
26703
  },
@@ -27063,6 +27223,16 @@ function triggerEarlyPoll(reason, agentId) {
27063
27223
  }, 0);
27064
27224
  }
27065
27225
  var directChatInFlight = /* @__PURE__ */ new Set();
27226
+ var directChatDoorbellInFlight = /* @__PURE__ */ new Set();
27227
+ function usesDoorbellRail(agent) {
27228
+ return hostFlagStore().getBoolean("direct-chat-doorbell") || effectiveIsolationMode(agent.codeName) === "docker";
27229
+ }
27230
+ var directChatPollCoalescer = createPollCoalescer({
27231
+ onError: (agentId, err) => log(`[direct-chat] ENG-12293: doorbell kick failed for agent ${agentId}: ${describeRejection(err)}`)
27232
+ });
27233
+ function kickDirectChatPoll(agent) {
27234
+ directChatPollCoalescer.kick(agent.agentId, () => pollDirectChatForAgent(agent));
27235
+ }
27066
27236
  function describeRejection(err) {
27067
27237
  try {
27068
27238
  if (err instanceof Error) return typeof err.message === "string" ? err.message : "Error with no message";
@@ -27082,30 +27252,119 @@ async function dispatchDirectChatMessage(args) {
27082
27252
  );
27083
27253
  } finally {
27084
27254
  args.inFlight.delete(args.id);
27255
+ args.onSettled?.();
27085
27256
  }
27086
27257
  }
27258
+ function pollableForManagerDelivery(agent) {
27259
+ if (agent.status !== "active") return false;
27260
+ const fw = agentFrameworkCache.get(agent.codeName) ?? DEFAULT_FRAMEWORK;
27261
+ return mayManagerPoll({ framework: fw, railEnabled: usesDoorbellRail(agent) });
27262
+ }
27087
27263
  async function pollDirectChatMessages(agentStates) {
27088
27264
  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
- });
27265
+ await pollDirectChatForAgent(agent);
27266
+ }
27267
+ }
27268
+ var directChatDelivered = createDeliveredLedger();
27269
+ var UNDELIVERED_RETRY_MS = 11 * 60 * 1e3;
27270
+ function scheduleUndeliveredRetry(agent, messageId) {
27271
+ if (directChatDelivered.has(messageId)) return;
27272
+ log(
27273
+ `[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`
27274
+ );
27275
+ setTimeout(() => {
27276
+ if (directChatDelivered.has(messageId)) return;
27277
+ if (!stillPollableForManagerDelivery(agent)) {
27278
+ directChatChainStart.delete(agent.agentId);
27279
+ log(
27280
+ `[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"})`
27281
+ );
27282
+ return;
27283
+ }
27284
+ kickDirectChatPoll(agent);
27285
+ }, UNDELIVERED_RETRY_MS).unref?.();
27286
+ }
27287
+ var agentStatusLedger = createAgentStatusLedger();
27288
+ function noteAgentStatuses(agentStates) {
27289
+ agentStatusLedger.note(agentStates);
27290
+ }
27291
+ function stillPollableForManagerDelivery(agent) {
27292
+ const current = agentStatusLedger.get(agent.agentId);
27293
+ if (current !== "active") return false;
27294
+ return pollableForManagerDelivery({ ...agent, status: current });
27295
+ }
27296
+ var directChatChainStart = /* @__PURE__ */ new Map();
27297
+ async function pollDirectChatForAgent(agent) {
27298
+ if (!pollableForManagerDelivery(agent)) {
27299
+ directChatChainStart.delete(agent.agentId);
27300
+ return;
27301
+ }
27302
+ const chainStartedAt = directChatChainStart.get(agent.agentId) ?? Date.now();
27303
+ directChatChainStart.set(agent.agentId, chainStartedAt);
27304
+ try {
27305
+ const data = await api.post("/host/direct-chat/poll", { agent_id: agent.agentId });
27306
+ for (const msg of data.messages) {
27307
+ if (directChatInFlight.has(msg.id)) continue;
27308
+ directChatInFlight.add(msg.id);
27309
+ void dispatchDirectChatMessage({
27310
+ id: msg.id,
27311
+ codeName: agent.codeName,
27312
+ process: () => processDirectChatMessage(agent, msg),
27313
+ inFlight: directChatInFlight,
27314
+ log,
27315
+ onSettled: () => scheduleUndeliveredRetry(agent, msg.id)
27316
+ });
27317
+ }
27318
+ const next = nextDirectChatPoll({
27319
+ retryAfterMs: data.retry_after_ms,
27320
+ claimed: data.messages.length,
27321
+ chainElapsedMs: Date.now() - chainStartedAt
27322
+ });
27323
+ if (next.kind === "done") {
27324
+ directChatChainStart.delete(agent.agentId);
27325
+ return;
27326
+ }
27327
+ if (next.kind === "bound-reached") {
27328
+ directChatChainStart.delete(agent.agentId);
27329
+ log(
27330
+ `[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`
27331
+ );
27332
+ setTimeout(() => {
27333
+ if (!stillPollableForManagerDelivery(agent)) {
27334
+ directChatChainStart.delete(agent.agentId);
27335
+ return;
27336
+ }
27337
+ kickDirectChatPoll(agent);
27338
+ }, REKICK_CHAIN_MAX_MS).unref?.();
27339
+ return;
27340
+ }
27341
+ setTimeout(() => kickDirectChatPoll(agent), next.delayMs).unref?.();
27342
+ } catch (err) {
27343
+ log(`Direct chat poll failed for '${agent.codeName}': ${err.message}`);
27344
+ const after = nextDirectChatPoll({
27345
+ failed: true,
27346
+ claimed: 0,
27347
+ chainElapsedMs: Date.now() - chainStartedAt
27348
+ });
27349
+ if (after.kind !== "again") {
27350
+ directChatChainStart.delete(agent.agentId);
27351
+ if (after.kind === "bound-reached") {
27352
+ log(
27353
+ `[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`
27354
+ );
27102
27355
  }
27103
- } catch (err) {
27104
- log(`Direct chat poll failed for '${agent.codeName}': ${err.message}`);
27356
+ return;
27105
27357
  }
27358
+ setTimeout(() => kickDirectChatPoll(agent), after.delayMs).unref?.();
27106
27359
  }
27107
27360
  }
27108
27361
  async function processDirectChatMessageOpencode(agent, msg) {
27362
+ if (directChatDelivered.has(msg.id)) {
27363
+ log(
27364
+ `[direct-chat] ENG-12293: msg=${msg.id} was already answered by '${agent.codeName}' \u2014 not re-injecting (the stale-processing reaper requeued it)`
27365
+ );
27366
+ return;
27367
+ }
27109
27368
  if (!isOpencodeSessionHealthy(agent.codeName)) {
27110
27369
  log(`[direct-chat] opencode server not running for '${agent.codeName}' (msg=${msg.id}) \u2014 leaving for redelivery`);
27111
27370
  return;
@@ -27166,6 +27425,7 @@ async function processDirectChatMessageOpencode(agent, msg) {
27166
27425
  })
27167
27426
  );
27168
27427
  }
27428
+ directChatDelivered.mark(msg.id);
27169
27429
  log(`[direct-chat] opencode replied for '${agent.codeName}' (msg=${msg.id}, ${result.reply.length} chars)`);
27170
27430
  } catch (err) {
27171
27431
  if (!recorded) {
@@ -27189,7 +27449,9 @@ async function processDirectChatMessageOpencode(agent, msg) {
27189
27449
  async function processDirectChatMessage(agent, msg) {
27190
27450
  noteInbound(agent.codeName);
27191
27451
  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}`);
27452
+ log(
27453
+ `[direct-chat] Processing message for '${agent.codeName}' (fw=${fw}): id=${msg.id} ` + (msg.content === void 0 ? "body=doorbell (ENG-12293)" : `len=${msg.content.length}`)
27454
+ );
27193
27455
  if (isDirectChatMessageExpired(msg.created_at, Date.now(), directChatMaxAgeMs())) {
27194
27456
  log(`[direct-chat] Expired backlog message for '${agent.codeName}' (msg=${msg.id}, created_at=${msg.created_at}) \u2014 draining without delivery`);
27195
27457
  try {
@@ -27208,7 +27470,18 @@ async function processDirectChatMessage(agent, msg) {
27208
27470
  return;
27209
27471
  }
27210
27472
  if (fw === "opencode") {
27211
- await processDirectChatMessageOpencode(agent, msg);
27473
+ const ocRoute = routeDirectChatMessage({
27474
+ framework: "opencode",
27475
+ railEnabled: usesDoorbellRail(agent),
27476
+ dockerIsolated: effectiveIsolationMode(agent.codeName) === "docker",
27477
+ hasBody: msg.content !== void 0,
27478
+ ringFailed: false
27479
+ });
27480
+ if (ocRoute.kind === "kick") {
27481
+ kickDirectChatPoll(agent);
27482
+ return;
27483
+ }
27484
+ await processDirectChatMessageOpencode(agent, { ...msg, content: msg.content });
27212
27485
  return;
27213
27486
  }
27214
27487
  if (performLazyDayRolloverReset(agent.codeName, cachedAgentTimezoneFor(agent.codeName))) {
@@ -27241,8 +27514,16 @@ async function processDirectChatMessage(agent, msg) {
27241
27514
  }
27242
27515
  }
27243
27516
  if (!blockedOnPrompt && isSessionHealthy(agent.codeName)) {
27244
- const useDoorbell = hostFlagStore().getBoolean("direct-chat-doorbell") || effectiveIsolationMode(agent.codeName) === "docker";
27245
- if (useDoorbell) {
27517
+ const dockerIsolated = effectiveIsolationMode(agent.codeName) === "docker";
27518
+ const railEnabled = usesDoorbellRail(agent);
27519
+ let route = routeDirectChatMessage({
27520
+ framework: fw,
27521
+ railEnabled,
27522
+ dockerIsolated,
27523
+ hasBody: msg.content !== void 0,
27524
+ ringFailed: false
27525
+ });
27526
+ if (route.kind === "ring") {
27246
27527
  try {
27247
27528
  const doorbell = directChatDoorbellPath(agent.agentId, homedir17());
27248
27529
  mkdirSync18(dirname11(doorbell), { recursive: true });
@@ -27250,16 +27531,34 @@ async function processDirectChatMessage(agent, msg) {
27250
27531
  log(`[direct-chat] Doorbell rung for '${agent.codeName}' (msg=${msg.id}) \u2014 in-session MCP will pull via the cursor`);
27251
27532
  return;
27252
27533
  } 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`);
27534
+ log(`[direct-chat] Doorbell ring failed for '${agent.codeName}' (msg=${msg.id}): ${err.message}`);
27535
+ route = routeDirectChatMessage({
27536
+ framework: fw,
27537
+ railEnabled,
27538
+ dockerIsolated,
27539
+ hasBody: msg.content !== void 0,
27540
+ ringFailed: true
27541
+ });
27258
27542
  }
27259
27543
  }
27544
+ if (route.kind === "leave-pending") {
27545
+ log(`[direct-chat] Leaving msg=${msg.id} pending for '${agent.codeName}': ${route.why}`);
27546
+ return;
27547
+ }
27548
+ if (route.kind === "kick") {
27549
+ kickDirectChatPoll(agent);
27550
+ return;
27551
+ }
27552
+ if (directChatDelivered.has(msg.id)) {
27553
+ log(
27554
+ `[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`
27555
+ );
27556
+ return;
27557
+ }
27558
+ const messageBody = msg.content;
27260
27559
  const escapeXml = (value) => value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&apos;");
27261
27560
  const channelEnvelope = `<channel source="direct-chat" session_id="${escapeXml(msg.session_id)}" user="webapp" ${laneTagFragment("conversational", true)}>
27262
- ${escapeXml(msg.content)}
27561
+ ${escapeXml(messageBody)}
27263
27562
  </channel>`;
27264
27563
  const delivered = await injectMessage(
27265
27564
  agent.codeName,
@@ -27269,6 +27568,7 @@ ${escapeXml(msg.content)}
27269
27568
  log
27270
27569
  );
27271
27570
  if (delivered) {
27571
+ directChatDelivered.mark(msg.id);
27272
27572
  log(`[direct-chat] Injected into persistent session for '${agent.codeName}' (msg=${msg.id}); agent will reply via direct_chat.reply tool`);
27273
27573
  return;
27274
27574
  }