@integrity-labs/agt-cli 0.28.1290 → 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.
@@ -15,7 +15,7 @@ import {
15
15
  mintRotatedHostKey,
16
16
  probeHostKey,
17
17
  setConfigHash
18
- } from "./chunk-XDMJSKLQ.js";
18
+ } from "./chunk-G4T3PGWR.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-6L3L4HKS.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-RPZSSKF7.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-G4T3PGWR.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.1291" : "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.1291" : "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.1291" : "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-G4T3PGWR.js.map
@@ -2,7 +2,7 @@ import {
2
2
  exchangeApiKey,
3
3
  getApiKey,
4
4
  getHost
5
- } from "./chunk-XDMJSKLQ.js";
5
+ } from "./chunk-G4T3PGWR.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-RPZSSKF7.js.map
@@ -70,7 +70,7 @@ import {
70
70
  tripClass,
71
71
  writeEtcEnvironment,
72
72
  writeProfileDScript
73
- } from "../chunk-6YJL5HCY.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-XDMJSKLQ.js";
91
+ } from "../chunk-G4T3PGWR.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-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;
@@ -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.1290" : "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();
@@ -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
  },
@@ -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
  }