@songsid/agend 2.1.2-beta.4 → 2.1.2-beta.41

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 (166) hide show
  1. package/dist/access-path.js +15 -6
  2. package/dist/access-path.js.map +1 -1
  3. package/dist/agent-cli-instructions.md +1 -0
  4. package/dist/agent-cli.js +14 -0
  5. package/dist/agent-cli.js.map +1 -1
  6. package/dist/agent-endpoint.d.ts +2 -0
  7. package/dist/agent-endpoint.js +25 -1
  8. package/dist/agent-endpoint.js.map +1 -1
  9. package/dist/backend/antigravity.d.ts +20 -0
  10. package/dist/backend/antigravity.js +51 -4
  11. package/dist/backend/antigravity.js.map +1 -1
  12. package/dist/backend/claude-code.d.ts +59 -0
  13. package/dist/backend/claude-code.js +67 -1
  14. package/dist/backend/claude-code.js.map +1 -1
  15. package/dist/backend/codex.d.ts +27 -0
  16. package/dist/backend/codex.js +93 -0
  17. package/dist/backend/codex.js.map +1 -1
  18. package/dist/backend/grok.d.ts +25 -0
  19. package/dist/backend/grok.js +51 -0
  20. package/dist/backend/grok.js.map +1 -1
  21. package/dist/backend/kiro.d.ts +22 -0
  22. package/dist/backend/kiro.js +79 -1
  23. package/dist/backend/kiro.js.map +1 -1
  24. package/dist/backend/types.d.ts +58 -0
  25. package/dist/backend/types.js +13 -1
  26. package/dist/backend/types.js.map +1 -1
  27. package/dist/channel/adapters/discord.d.ts +15 -0
  28. package/dist/channel/adapters/discord.js +100 -2
  29. package/dist/channel/adapters/discord.js.map +1 -1
  30. package/dist/channel/adapters/telegram.d.ts +21 -0
  31. package/dist/channel/adapters/telegram.js +86 -0
  32. package/dist/channel/adapters/telegram.js.map +1 -1
  33. package/dist/channel/ipc-bridge.d.ts +9 -1
  34. package/dist/channel/ipc-bridge.js +12 -3
  35. package/dist/channel/ipc-bridge.js.map +1 -1
  36. package/dist/channel/ipc-timeouts.d.ts +46 -0
  37. package/dist/channel/ipc-timeouts.js +65 -0
  38. package/dist/channel/ipc-timeouts.js.map +1 -0
  39. package/dist/channel/mcp-server.js +30 -14
  40. package/dist/channel/mcp-server.js.map +1 -1
  41. package/dist/channel/mcp-tools.js +30 -1
  42. package/dist/channel/mcp-tools.js.map +1 -1
  43. package/dist/channel/reconnect-backoff.d.ts +17 -0
  44. package/dist/channel/reconnect-backoff.js +21 -0
  45. package/dist/channel/reconnect-backoff.js.map +1 -0
  46. package/dist/channel/types.d.ts +29 -0
  47. package/dist/classic-channel-manager.js +1 -5
  48. package/dist/classic-channel-manager.js.map +1 -1
  49. package/dist/cli.js +227 -87
  50. package/dist/cli.js.map +1 -1
  51. package/dist/completion.d.ts +27 -0
  52. package/dist/completion.js +121 -0
  53. package/dist/completion.js.map +1 -0
  54. package/dist/config-validator.js +21 -0
  55. package/dist/config-validator.js.map +1 -1
  56. package/dist/config.js +1 -0
  57. package/dist/config.js.map +1 -1
  58. package/dist/cost-guard.d.ts +3 -1
  59. package/dist/cost-guard.js +3 -1
  60. package/dist/cost-guard.js.map +1 -1
  61. package/dist/daemon.d.ts +282 -14
  62. package/dist/daemon.js +1062 -311
  63. package/dist/daemon.js.map +1 -1
  64. package/dist/event-log.d.ts +31 -0
  65. package/dist/event-log.js +96 -0
  66. package/dist/event-log.js.map +1 -1
  67. package/dist/fleet-context.d.ts +9 -0
  68. package/dist/fleet-lock.d.ts +28 -0
  69. package/dist/fleet-lock.js +130 -0
  70. package/dist/fleet-lock.js.map +1 -0
  71. package/dist/fleet-manager.d.ts +315 -2
  72. package/dist/fleet-manager.js +1414 -108
  73. package/dist/fleet-manager.js.map +1 -1
  74. package/dist/general-knowledge/skills/cross-instance-messaging/SKILL.md +22 -0
  75. package/dist/general-knowledge/skills/model-discovery/SKILL.md +14 -23
  76. package/dist/general-knowledge/skills/session-management/SKILL.md +15 -34
  77. package/dist/hang-detector.d.ts +19 -13
  78. package/dist/hang-detector.js +19 -49
  79. package/dist/hang-detector.js.map +1 -1
  80. package/dist/instance-lifecycle.d.ts +52 -3
  81. package/dist/instance-lifecycle.js +194 -48
  82. package/dist/instance-lifecycle.js.map +1 -1
  83. package/dist/instructions.d.ts +5 -0
  84. package/dist/instructions.js +9 -11
  85. package/dist/instructions.js.map +1 -1
  86. package/dist/locale.js +5 -1
  87. package/dist/locale.js.map +1 -1
  88. package/dist/logger.js +14 -0
  89. package/dist/logger.js.map +1 -1
  90. package/dist/mcp-liveness.d.ts +21 -0
  91. package/dist/mcp-liveness.js +27 -0
  92. package/dist/mcp-liveness.js.map +1 -0
  93. package/dist/outbound-handlers.d.ts +16 -0
  94. package/dist/outbound-handlers.js +151 -27
  95. package/dist/outbound-handlers.js.map +1 -1
  96. package/dist/outbound-schemas.d.ts +11 -3
  97. package/dist/outbound-schemas.js +16 -2
  98. package/dist/outbound-schemas.js.map +1 -1
  99. package/dist/pane-write-lock.d.ts +48 -0
  100. package/dist/pane-write-lock.js +73 -0
  101. package/dist/pane-write-lock.js.map +1 -0
  102. package/dist/process-memory.d.ts +31 -0
  103. package/dist/process-memory.js +79 -0
  104. package/dist/process-memory.js.map +1 -0
  105. package/dist/quickstart.js +17 -16
  106. package/dist/quickstart.js.map +1 -1
  107. package/dist/reply-dedup.d.ts +41 -0
  108. package/dist/reply-dedup.js +0 -0
  109. package/dist/reply-dedup.js.map +1 -0
  110. package/dist/scheduler/db.js +3 -0
  111. package/dist/scheduler/db.js.map +1 -1
  112. package/dist/sd-notify.d.ts +27 -0
  113. package/dist/sd-notify.js +33 -1
  114. package/dist/sd-notify.js.map +1 -1
  115. package/dist/secret-file.d.ts +33 -0
  116. package/dist/secret-file.js +36 -0
  117. package/dist/secret-file.js.map +1 -0
  118. package/dist/service-installer.d.ts +16 -0
  119. package/dist/service-installer.js +56 -1
  120. package/dist/service-installer.js.map +1 -1
  121. package/dist/setup-wizard.js +9 -7
  122. package/dist/setup-wizard.js.map +1 -1
  123. package/dist/tmux-control.d.ts +58 -5
  124. package/dist/tmux-control.js +102 -14
  125. package/dist/tmux-control.js.map +1 -1
  126. package/dist/tmux-manager.d.ts +31 -1
  127. package/dist/tmux-manager.js +40 -11
  128. package/dist/tmux-manager.js.map +1 -1
  129. package/dist/topic-commands.d.ts +49 -9
  130. package/dist/topic-commands.js +267 -105
  131. package/dist/topic-commands.js.map +1 -1
  132. package/dist/tui-glyphs.d.ts +5 -1
  133. package/dist/tui-glyphs.js +6 -2
  134. package/dist/tui-glyphs.js.map +1 -1
  135. package/dist/types.d.ts +12 -2
  136. package/dist/ui/view.html +123 -2
  137. package/dist/update-marker.d.ts +15 -0
  138. package/dist/update-marker.js +69 -0
  139. package/dist/update-marker.js.map +1 -0
  140. package/dist/usage/format-rich.d.ts +11 -0
  141. package/dist/usage/format-rich.js +121 -0
  142. package/dist/usage/format-rich.js.map +1 -0
  143. package/dist/usage/provider-alerts.d.ts +33 -0
  144. package/dist/usage/provider-alerts.js +57 -0
  145. package/dist/usage/provider-alerts.js.map +1 -0
  146. package/dist/usage/providers.d.ts +130 -0
  147. package/dist/usage/providers.js +1063 -0
  148. package/dist/usage/providers.js.map +1 -0
  149. package/dist/usage/statusline-usage.d.ts +20 -0
  150. package/dist/usage/statusline-usage.js +120 -0
  151. package/dist/usage/statusline-usage.js.map +1 -0
  152. package/dist/usage/usage-api.d.ts +50 -0
  153. package/dist/usage/usage-api.js +197 -0
  154. package/dist/usage/usage-api.js.map +1 -0
  155. package/dist/view-api.d.ts +3 -0
  156. package/dist/view-api.js +11 -2
  157. package/dist/view-api.js.map +1 -1
  158. package/dist/web-api.js +5 -2
  159. package/dist/web-api.js.map +1 -1
  160. package/package.json +4 -1
  161. package/dist/channel/tool-tracker.d.ts +0 -13
  162. package/dist/channel/tool-tracker.js +0 -58
  163. package/dist/channel/tool-tracker.js.map +0 -1
  164. package/dist/daemon-entry.d.ts +0 -1
  165. package/dist/daemon-entry.js +0 -30
  166. package/dist/daemon-entry.js.map +0 -1
package/dist/daemon.js CHANGED
@@ -1,18 +1,23 @@
1
1
  import { join, dirname, basename, resolve } from "node:path";
2
- import { mkdirSync, writeFileSync, readFileSync, existsSync, unlinkSync, rmSync, appendFileSync, statSync, chmodSync, renameSync } from "node:fs";
2
+ import { mkdirSync, writeFileSync, readFileSync, existsSync, unlinkSync, rmSync, appendFileSync, statSync, renameSync } from "node:fs";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import { createHash, randomBytes } from "node:crypto";
5
5
  import { EventEmitter } from "node:events";
6
+ import { rotateLogIfNeeded } from "./logger.js";
7
+ import { mcpServerState } from "./mcp-liveness.js";
6
8
  import { clearPausedMarker, writePausedMarker } from "./pause-marker.js";
7
9
  import { TmuxManager, resolveTmuxLogicalSize } from "./tmux-manager.js";
8
10
  import { TranscriptMonitor } from "./transcript-monitor.js";
9
11
  import { ContextGuardian } from "./context-guardian.js";
10
12
  import { IpcServer } from "./channel/ipc-bridge.js";
13
+ import { daemonBudgetMs } from "./channel/ipc-timeouts.js";
11
14
  import { MessageBus } from "./channel/message-bus.js";
12
15
  import { shellQuote } from "./backend/types.js";
13
16
  import { getTmuxSession } from "./config.js";
14
17
  import { routeToolCall } from "./channel/tool-router.js";
15
18
  import { HangDetector } from "./hang-detector.js";
19
+ import { writeSecretFile } from "./secret-file.js";
20
+ import { PaneWriteLock } from "./pane-write-lock.js";
16
21
  import { buildFleetInstructions } from "./instructions.js";
17
22
  const __filename = fileURLToPath(import.meta.url);
18
23
  const __dirname = dirname(__filename);
@@ -37,9 +42,54 @@ export function buildInstructionReloadNotice(binaryName, instanceName, instanceD
37
42
  export const DEFAULT_STUCK_TIMEOUT_MS = 10 * 60_000;
38
43
  export const DEFAULT_STATE_IDLE_DEBOUNCE_MS = 2_000;
39
44
  export const DEFAULT_STATE_SAFETY_SWEEP_MS = 60_000;
40
- /** @deprecated State detection is event-driven; this now aliases the safety sweep. */
41
- export const DEFAULT_STATE_POLL_INTERVAL_MS = DEFAULT_STATE_SAFETY_SWEEP_MS;
42
45
  const LAST_INBOUND_FILE = "last-inbound-at";
46
+ /** Minimum gap between "health check is failing" notifications for one instance. */
47
+ const HEALTH_ERROR_NOTIFY_INTERVAL_MS = 10 * 60_000;
48
+ /**
49
+ * Whether two working directories belong to the same project, so a fleet-scoped
50
+ * decision recorded in one reaches the other. Covers the worktree/checkout
51
+ * layout AgEnD fleets actually use — `AgEnD`, `AgEnD-dev1`, `AgEnD-dev2`,
52
+ * `AgEnD-reviewer`, `AgEnD-main` are one project; `DouPo_Server` is not.
53
+ * Nesting counts too (a subdirectory of a project belongs to it).
54
+ */
55
+ export function sameProjectFamily(a, b) {
56
+ const norm = (p) => p.replace(/\/+$/, "");
57
+ const x = norm(a), y = norm(b);
58
+ if (x === y)
59
+ return true;
60
+ if (x.startsWith(y + "/") || y.startsWith(x + "/"))
61
+ return true;
62
+ // Strip a trailing worktree/role suffix: "AgEnD-dev2" → "agend".
63
+ const family = (p) => {
64
+ const base = p.slice(p.lastIndexOf("/") + 1).toLowerCase();
65
+ return base.replace(/[-_](dev\d*|main|reviewer|tester|leader|sol|codex|worktree|wt\d*)$/i, "");
66
+ };
67
+ const fx = family(x), fy = family(y);
68
+ return fx.length > 0 && fx === fy;
69
+ }
70
+ /**
71
+ * Pick the decisions worth injecting into one instance's system prompt.
72
+ *
73
+ * `scope: "fleet"` previously bypassed the project check outright, so every
74
+ * instance carried every other project's playbook — measured at 8 of 14 here,
75
+ * resent on every API call. A fleet decision must now also be relevant: global
76
+ * (no project_root), the same project, or the same project family.
77
+ *
78
+ * `isDispatcher` (a general) opts out of that narrowing on purpose: it routes
79
+ * work across all projects, so cross-project rules ("X 文件操作由 Y 負責") are
80
+ * precisely what it must know. Narrowing a general would cause misrouting.
81
+ */
82
+ export function selectRelevantDecisions(all, workDir, isDispatcher = false) {
83
+ return all.filter(d => {
84
+ if (d.project_root === workDir)
85
+ return true; // own project, any scope
86
+ if (d.scope !== "fleet")
87
+ return false; // project-scoped, elsewhere
88
+ if (!d.project_root)
89
+ return true; // truly global
90
+ return isDispatcher || sameProjectFamily(d.project_root, workDir);
91
+ });
92
+ }
43
93
  /** Read the last real channel inbound timestamp persisted across daemon restarts. */
44
94
  export function readLastInboundAt(instanceDir, now = Date.now()) {
45
95
  try {
@@ -58,6 +108,40 @@ export function writeLastInboundAt(instanceDir, timestamp) {
58
108
  writeFileSync(temp, String(timestamp));
59
109
  renameSync(temp, target);
60
110
  }
111
+ /**
112
+ * Render the handoff/routing metadata that rides along with an inbound message
113
+ * into the block actually pasted into the agent's pane.
114
+ *
115
+ * These fields were all populated by the sender (outbound-handlers builds them
116
+ * into `ipcMeta`) and delivered over IPC, but never rendered — so the receiving
117
+ * agent could not see them, and several documented flows could not work:
118
+ *
119
+ * - `report_result` requires a `correlation_id` the agent had no way to know, so
120
+ * the "correlation_id not recognized" warning fired on essentially every call.
121
+ * - Delegation cancel buttons are retired by correlation id, so they never retired.
122
+ * - `react`, `edit_message` and `reply.reply_to` need `message_id`, which the tool
123
+ * descriptions tell the agent to take "from the inbound block".
124
+ * - `download_attachment` needs `attachment_file_id`.
125
+ * - `requires_reply` was invisible, so a delegated task looked like an FYI.
126
+ *
127
+ * Only non-empty fields are emitted, so a plain user message gains at most a
128
+ * message_id line.
129
+ */
130
+ export function renderHandoffMetadata(meta) {
131
+ const rows = [];
132
+ const add = (label, value) => {
133
+ if (value && value.trim())
134
+ rows.push(`${label}: ${value.trim()}`);
135
+ };
136
+ add("message_id", meta.message_id);
137
+ add("correlation_id", meta.correlation_id);
138
+ add("request_kind", meta.request_kind);
139
+ add("task_summary", meta.task_summary);
140
+ add("working_directory", meta.working_directory);
141
+ add("branch", meta.branch);
142
+ add("attachment_file_id", meta.attachment_file_id);
143
+ return rows.length ? `\n(${rows.join(" | ")})` : "";
144
+ }
61
145
  /** Headless inactivity timer used by the daemon and unit tests. */
62
146
  export class AutoPauseController {
63
147
  thresholdMs;
@@ -102,37 +186,111 @@ export class AutoPauseController {
102
186
  * Pane motion wins over a ready match because several backends keep their ready
103
187
  * marker in a persistent header/footer while generating. A stable ready pane is
104
188
  * idle; changing content is working; stable non-ready content eventually sticks.
189
+ *
190
+ * ## Why an optional busy pattern exists
191
+ *
192
+ * "Motion wins" degrades badly when a backend's ready marker is *always* on
193
+ * screen. `stuck` requires `!ready`, so for such a backend the state can only ever
194
+ * be idle or working — the stuck edge, and with it `handleStuckTransition` and the
195
+ * hang notification, is unreachable. A frozen CLI is then reported as idle, which
196
+ * also clears pending work: the message the user sent is quietly booked as done.
197
+ *
198
+ * claude-code was exactly this case (see ClaudeCodeBackend.getReadyPattern). A
199
+ * backend that can point at a marker meaning "generating right now" supplies
200
+ * `getBusyPattern()`, and that match vetoes ready regardless of what the ready
201
+ * pattern says.
105
202
  */
203
+ /**
204
+ * A shell command reduced to the part that is safe to show: the program, and a
205
+ * subcommand when there is one.
206
+ *
207
+ * curl -H "Bearer sk-ant-…" https://api.com → curl
208
+ * npm test --env=API_KEY=xxx → npm test
209
+ * git push origin main → git push
210
+ *
211
+ * Arguments are dropped wholesale rather than filtered, because there is no
212
+ * reliable way to tell a secret from an ordinary argument: tokens, bearer
213
+ * headers, connection strings and `--password=` values all look like text. The
214
+ * progress line is posted to a chat channel and, for a public one, so is
215
+ * anything in it — so the rule is "never the arguments", not "not the arguments
216
+ * that look dangerous".
217
+ *
218
+ * A second token is kept only when it is a bare word (`push`, `test`), which is
219
+ * what a subcommand looks like and what a flag, path, URL, assignment or quoted
220
+ * string does not. Everything after it goes, including `git push ORIGIN MAIN`.
221
+ */
222
+ export function shellCommandLabel(command) {
223
+ // First line only: heredocs and multi-line scripts carry the payload.
224
+ const tokens = (command.split("\n")[0] ?? "").trim().split(/\s+/).filter(Boolean);
225
+ // `FOO=bar cmd …` — leading assignments are env, and their values are exactly
226
+ // the kind of thing being protected here.
227
+ while (tokens.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[0]))
228
+ tokens.shift();
229
+ const program = tokens[0];
230
+ if (!program)
231
+ return "";
232
+ const isBareWord = (t) => !!t && /^[A-Za-z][A-Za-z0-9_-]*$/.test(t);
233
+ const label = isBareWord(tokens[1]) ? `${program} ${tokens[1]}` : program;
234
+ return label.length > 40 ? `${label.slice(0, 39)}…` : label;
235
+ }
106
236
  export class PaneStateMachine {
107
237
  stuckTimeoutMs;
108
238
  readyPattern;
239
+ busyPattern;
109
240
  lastPaneHash = null;
110
241
  lastPaneChangeAt;
111
242
  lastObservedAt;
112
243
  stateChangedAt;
113
244
  currentState = "idle";
114
- constructor(readyPattern, stuckTimeoutMs = DEFAULT_STUCK_TIMEOUT_MS, now = Date.now()) {
245
+ constructor(readyPattern, stuckTimeoutMs = DEFAULT_STUCK_TIMEOUT_MS, now = Date.now(), busyPattern) {
115
246
  this.stuckTimeoutMs = stuckTimeoutMs;
116
247
  // Stateful g/y regexes mutate lastIndex and can alternate true/false across
117
248
  // polls. State detection must be deterministic for identical pane content.
118
249
  this.readyPattern = new RegExp(readyPattern.source, readyPattern.flags.replace(/[gy]/g, ""));
250
+ this.busyPattern = busyPattern
251
+ ? new RegExp(busyPattern.source, busyPattern.flags.replace(/[gy]/g, ""))
252
+ : null;
119
253
  this.lastPaneChangeAt = now;
120
254
  this.lastObservedAt = now;
121
255
  this.stateChangedAt = now;
122
256
  }
123
- observe(pane, now = Date.now()) {
257
+ /** Ready, unless the backend can positively see that it is still generating. */
258
+ isReady(pane) {
259
+ if (this.busyPattern?.test(pane))
260
+ return false;
261
+ return this.readyPattern.test(pane);
262
+ }
263
+ /**
264
+ * @param now when this observation is being evaluated — drives the idle and
265
+ * stuck decisions.
266
+ * @param opts.changeAt when the content is believed to have changed, if that
267
+ * is earlier than `now` (the tmux output timestamp). Only the elapsed-time
268
+ * clock uses it; defaults to `now`.
269
+ * @param opts.settled the caller knows no output has arrived for the debounce
270
+ * window, so "the content differs from the last capture" says nothing about
271
+ * whether the CLI is still generating — decide on the patterns instead.
272
+ *
273
+ * Captures are event-driven, not periodic: the one taken 2s after output
274
+ * stops is compared against a capture that may be a minute old, so it
275
+ * *always* differs. Without this flag that difference reads as "still
276
+ * working" and a finished turn would not be seen as idle until the next 60s
277
+ * safety sweep. Output timestamps are the honest liveness signal here, and
278
+ * the caller has them.
279
+ */
280
+ observe(pane, now = Date.now(), opts = {}) {
281
+ const { settled = false, changeAt = now } = opts;
124
282
  const paneHash = createHash("sha256").update(pane).digest("hex");
125
283
  const firstObservation = this.lastPaneHash === null;
126
284
  const paneChanged = this.lastPaneHash !== paneHash;
127
285
  if (paneChanged) {
128
286
  this.lastPaneHash = paneHash;
129
- this.lastPaneChangeAt = now;
287
+ this.lastPaneChangeAt = changeAt;
130
288
  }
131
289
  this.lastObservedAt = now;
132
- const ready = this.readyPattern.test(pane);
290
+ const ready = this.isReady(pane);
133
291
  const nextState = firstObservation
134
292
  ? ready ? "idle" : "working"
135
- : paneChanged
293
+ : paneChanged && !settled
136
294
  ? "working"
137
295
  : ready
138
296
  ? "idle"
@@ -193,6 +351,23 @@ export class PendingWorkTracker {
193
351
  const NORMAL_ENTER_SETTLE_MS = 500;
194
352
  const FIRST_ENTER_SETTLE_MS = 1_750;
195
353
  const FIRST_DELIVERY_WINDOW_MS = 5_000;
354
+ /** After busy native-queue paste+Enter, wait before checking the pane for silent loss. */
355
+ const NATIVE_QUEUE_PASTE_VERIFY_MS = 2_000;
356
+ /** Enter-confirmation poll: 10 × 200ms ≈ 2s of observed silence before giving up. */
357
+ const CONFIRM_BUSY_POLLS = 10;
358
+ const CONFIRM_BUSY_POLL_MS = 200;
359
+ /**
360
+ * Ceiling on the whole confirmation, including time re-earned after a control-mode
361
+ * reconnect. Without it a reconnect loop could restart the poll indefinitely and
362
+ * hold the pane write lock along with it.
363
+ */
364
+ const CONFIRM_BUSY_MAX_WAIT_MS = 10_000;
365
+ /**
366
+ * How long a delivery waits for an in-flight spawn. Comfortably past the default
367
+ * 25s startup timeout plus dialog dismissal; past it we fall back to the old
368
+ * behaviour rather than holding a message indefinitely.
369
+ */
370
+ const SPAWN_SETTLE_MAX_WAIT_MS = 60_000;
196
371
  /**
197
372
  * One-shot timing gate for the first paste after a CLI reaches its ready
198
373
  * prompt. Recent tmux versions expose a short interval where the prompt is
@@ -237,6 +412,68 @@ export function sanitizePaneTail(pane, lineCount = 5) {
237
412
  .replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, "")
238
413
  .slice(0, 200));
239
414
  }
415
+ const INTERACTIVE_PROMPT_PATTERNS = [
416
+ { kind: "sudo_password", pattern: /^\s*\[sudo\]\s+password\s+for\s+[^:\n]+:\s*$/im },
417
+ // macOS sudo and several package installers use this exact no-echo prompt.
418
+ // Tail-only + stability gating is what makes the otherwise-generic word safe.
419
+ { kind: "password", pattern: /^\s*(?:Password|Passphrase):\s*$/im },
420
+ { kind: "confirmation", pattern: /^[^\n]{0,180}(?:\([Yy]\/[Nn]\)|\[[Yy]\/[Nn]\]|\((?:yes|no)\/(?:yes|no)\))\s*:?\s*$/im },
421
+ { kind: "confirmation", pattern: /^\s*Are you sure[^\n]{0,160}\((?:yes\/no)(?:\/\[[^\]]+\])?\)\??\s*$/im },
422
+ { kind: "press_enter", pattern: /^\s*(?:Please\s+)?Press (?:the )?Enter(?: key)?(?: to [^\n]{0,120})?[.:…]?\s*$/im },
423
+ ];
424
+ /**
425
+ * Detect terminal prompts that require a human, but only after the pane tail is
426
+ * unchanged and no control-mode output has arrived for the full grace period.
427
+ * This prevents prose such as "the installer asks [Y/n]" from notifying while
428
+ * an agent is still writing it.
429
+ */
430
+ export class InteractivePromptDetector {
431
+ stableMs;
432
+ signature = null;
433
+ stableSince = 0;
434
+ lastOutputAt = 0;
435
+ notifiedSignature = null;
436
+ constructor(stableMs = 10_000) {
437
+ this.stableMs = stableMs;
438
+ }
439
+ observe(pane, now = Date.now(), outputAt = 0) {
440
+ const tail = sanitizePaneTail(pane, 5);
441
+ const tailText = tail.join("\n");
442
+ let matched = null;
443
+ for (const candidate of INTERACTIVE_PROMPT_PATTERNS) {
444
+ const match = tailText.match(candidate.pattern);
445
+ if (!match)
446
+ continue;
447
+ matched = { kind: candidate.kind, prompt: match[0].trim().slice(0, 200) };
448
+ break;
449
+ }
450
+ if (!matched) {
451
+ this.reset();
452
+ this.lastOutputAt = outputAt;
453
+ return null;
454
+ }
455
+ const signature = `${matched.kind}:${tailText}`;
456
+ const outputMoved = outputAt > this.lastOutputAt;
457
+ if (signature !== this.signature || outputMoved) {
458
+ this.signature = signature;
459
+ this.stableSince = now;
460
+ this.lastOutputAt = outputAt;
461
+ if (signature !== this.notifiedSignature)
462
+ this.notifiedSignature = null;
463
+ return null;
464
+ }
465
+ this.lastOutputAt = outputAt;
466
+ if (this.notifiedSignature === signature || now - this.stableSince < this.stableMs)
467
+ return null;
468
+ this.notifiedSignature = signature;
469
+ return matched;
470
+ }
471
+ reset() {
472
+ this.signature = null;
473
+ this.stableSince = 0;
474
+ this.notifiedSignature = null;
475
+ }
476
+ }
240
477
  export class Daemon extends EventEmitter {
241
478
  name;
242
479
  config;
@@ -244,13 +481,13 @@ export class Daemon extends EventEmitter {
244
481
  topicMode;
245
482
  backend;
246
483
  controlClient;
484
+ runtimeIdentity;
247
485
  logger;
248
486
  tmuxSessionName;
249
487
  tmux = null;
250
488
  ipcServer = null;
251
489
  messageBus;
252
490
  transcriptMonitor = null;
253
- toolTracker = null;
254
491
  guardian = null;
255
492
  adapter = null;
256
493
  pendingIpcRequests = new Map();
@@ -261,6 +498,8 @@ export class Daemon extends EventEmitter {
261
498
  // Pending ack: react 🫡 on first transcript activity after receiving a message
262
499
  pendingAckMessage = null;
263
500
  // Tool status tracking for channel adapter
501
+ /** Last activity published to the fleet manager; null when nothing is running. */
502
+ currentActivity = null;
264
503
  toolStatusMessageId = null;
265
504
  toolStatusLines = [];
266
505
  toolStatusDebounce = null;
@@ -276,9 +515,19 @@ export class Daemon extends EventEmitter {
276
515
  lastSpawnAt = 0;
277
516
  crashTimestamps = [];
278
517
  healthCheckPaused = false;
518
+ lastHealthErrorNotifyAt = 0;
279
519
  /** CLI pane availability, independent from the daemon process and tri-state. */
280
520
  processStatus = "running";
281
521
  spawning = false;
522
+ /**
523
+ * Resolves when the in-flight spawn finishes; null when none is running.
524
+ *
525
+ * `spawning` alone can only be polled. Delivery needs to *wait*, and a boolean
526
+ * poll would either busy-loop or race the flag being cleared.
527
+ */
528
+ spawnSettled = null;
529
+ resolveSpawnSettled = null;
530
+ spawnDepth = 0;
282
531
  skipResume = false;
283
532
  backgroundSessionRecoveryAttempted = false;
284
533
  /** Whether the last spawn started a fresh session (not resumed). */
@@ -301,10 +550,18 @@ export class Daemon extends EventEmitter {
301
550
  instanceStateIdleDebounceMs = DEFAULT_STATE_IDLE_DEBOUNCE_MS;
302
551
  instanceStateStuckTimeoutMs = DEFAULT_STUCK_TIMEOUT_MS;
303
552
  instanceStateReadyPattern = null;
553
+ instanceStateBusyPattern = null;
304
554
  instanceStateMonitorActive = false;
305
555
  statePollInFlight = false;
306
556
  autoPauseController;
307
557
  pauseRequested = false;
558
+ /**
559
+ * Sticky "pause as soon as possible" (auth failure). Unlike pauseRequested —
560
+ * which the state monitor clears whenever the pane is not idle — this survives
561
+ * busy/stuck states, because an auth error fires mid-turn and a plain pause()
562
+ * would silently no-op exactly when we most need to stop feeding the CLI.
563
+ */
564
+ pausePending = false;
308
565
  pauseWakeState = "active";
309
566
  pauseWakeTransition = null;
310
567
  // Model failover: override model on next spawn when rate-limited
@@ -314,7 +571,13 @@ export class Daemon extends EventEmitter {
314
571
  recentEvents = [];
315
572
  recentToolActivity = [];
316
573
  snapshotConsumed = false;
574
+ /** Orders inbound channel messages against each other (queue-depth accounting
575
+ * and ⏳/👀/✅ reactions live here). It does NOT cover the other writers that
576
+ * reach the pane — {@link paneWriteLock} does. */
317
577
  pasteLock = Promise.resolve();
578
+ /** Mutual exclusion for *every* write into the pane, whichever subsystem it
579
+ * comes from. See PaneWriteLock for why interleaving is destructive. */
580
+ paneWriteLock = new PaneWriteLock();
318
581
  pendingInstructionsUpdate;
319
582
  pendingInstructionsNotice = false;
320
583
  // Whether the warmup steering-reload notice should be injected after spawn.
@@ -327,6 +590,11 @@ export class Daemon extends EventEmitter {
327
590
  firstDeliveryDelay = new FirstDeliveryDelay();
328
591
  // PTY error pattern monitoring
329
592
  errorMonitorTimer = null;
593
+ interactivePromptDetector = new InteractivePromptDetector();
594
+ /** Same 5-min gate the error monitor uses, so a dead MCP server alerts once. */
595
+ static MCP_DEATH_COOLDOWN_MS = 5 * 60_000;
596
+ lastMcpDeathNotifiedAt = 0;
597
+ mcpDeathNotifiedForPid = null;
330
598
  /** Prevent in-flight monitor callbacks from re-arming after a pause. */
331
599
  runtimeMonitorsFrozen = false;
332
600
  errorWaitingForRecovery = false; // true = error detected, waiting for ready pattern
@@ -371,7 +639,7 @@ export class Daemon extends EventEmitter {
371
639
  this.errorRecoveryDeadlineAt = 0;
372
640
  this.activeErrorPatternKey = null;
373
641
  }
374
- constructor(name, config, instanceDir, topicMode = false, backend, controlClient, rootLogger) {
642
+ constructor(name, config, instanceDir, topicMode = false, backend, controlClient, rootLogger, runtimeIdentity) {
375
643
  super();
376
644
  this.name = name;
377
645
  this.config = config;
@@ -379,8 +647,14 @@ export class Daemon extends EventEmitter {
379
647
  this.topicMode = topicMode;
380
648
  this.backend = backend;
381
649
  this.controlClient = controlClient;
650
+ this.runtimeIdentity = runtimeIdentity;
382
651
  if (!rootLogger)
383
652
  throw new Error("Daemon requires a shared root logger");
653
+ this.runtimeIdentity ??= {
654
+ kind: "fleet-topic",
655
+ backend: config.backend ?? backend?.binaryName ?? "unknown",
656
+ model: config.model ?? "default",
657
+ };
384
658
  this.logger = rootLogger.child({ instance: name }, { level: config.log_level });
385
659
  this.tmuxSessionName = getTmuxSession();
386
660
  this.messageBus = new MessageBus();
@@ -447,9 +721,6 @@ export class Daemon extends EventEmitter {
447
721
  if ((type === "fleet_schedule_response" || type === "fleet_outbound_response" || type === "fleet_decision_response" || type === "fleet_task_response" || type === "fleet_display_name_response" || type === "fleet_description_response") && msg.fleetRequestId) {
448
722
  key = String(msg.fleetRequestId);
449
723
  }
450
- else if (type === "fleet_outbound_response" && msg.requestId != null) {
451
- key = `fleet_out_${msg.requestId}`;
452
- }
453
724
  if (key && this.pendingIpcRequests.has(key)) {
454
725
  const handler = this.pendingIpcRequests.get(key);
455
726
  this.pendingIpcRequests.delete(key);
@@ -600,7 +871,12 @@ export class Daemon extends EventEmitter {
600
871
  else {
601
872
  await new Promise(r => setTimeout(r, 5000));
602
873
  }
603
- await this.tmux?.pasteText(buildInstructionReloadNotice(this.backend?.binaryName ?? "unknown", this.name, this.instanceDir));
874
+ // This path only runs when pasteQueueDepth > 0 — i.e. exactly when a real
875
+ // delivery is already in flight or queued. Without the lock the notice and
876
+ // that delivery race into the same pane.
877
+ await this.paneWriteLock.run(async () => {
878
+ await this.tmux?.pasteText(buildInstructionReloadNotice(this.backend?.binaryName ?? "unknown", this.name, this.instanceDir), this.systemPasteOptions());
879
+ });
604
880
  // Record the value the agent has now been told about so the next
605
881
  // unchanged restart skips the reload.
606
882
  try {
@@ -612,8 +888,12 @@ export class Daemon extends EventEmitter {
612
888
  catch { /* non-fatal */ }
613
889
  })();
614
890
  if (!this.config.lightweight) {
615
- // 3. Pipe-pane for prompt detection
891
+ // 3. Pipe-pane for prompt detection. Rotate first so a ballooned log from a
892
+ // previous stuck splash (hundreds of MB of ANSI frames) is truncated before
893
+ // we attach — pipe-pane uses `cat >>` on the same inode, so copytruncate
894
+ // keeps the writer attached after size resets.
616
895
  const outputLog = join(this.instanceDir, "output.log");
896
+ rotateLogIfNeeded(outputLog);
617
897
  await this.tmux.pipeOutput(outputLog).catch(() => { });
618
898
  // 4. Transcript monitor
619
899
  this.transcriptMonitor = new TranscriptMonitor(this.instanceDir, this.logger);
@@ -629,27 +909,31 @@ export class Daemon extends EventEmitter {
629
909
  this.transcriptMonitor.on("tool_use", (name, input) => {
630
910
  this.logger.debug({ tool: name }, "Tool use");
631
911
  ackIfPending();
632
- this.hangDetector?.recordActivity();
633
912
  this.recordRecentEvent({ type: "tool_use", name, preview: this.summarizeTool(name, input) });
634
913
  this.recordRecentToolActivity(this.summarizeTool(name, input));
914
+ this.publishActivity(this.summarizeTool(name, input));
635
915
  });
636
916
  this.transcriptMonitor.on("tool_result", (name, _output) => {
637
- this.hangDetector?.recordActivity();
638
917
  this.recordRecentEvent({ type: "tool_result", name });
918
+ // The tool finished; whatever comes next has not started yet. Better to
919
+ // show only elapsed time than to leave a stale "Bash: npm test" on screen.
920
+ this.publishActivity(null);
639
921
  });
640
922
  this.transcriptMonitor.on("assistant_text", (text) => {
641
923
  this.logger.debug({ text: text.slice(0, 200) }, "Claude response");
642
924
  ackIfPending();
643
- this.hangDetector?.recordActivity();
644
925
  this.recordRecentEvent({ type: "assistant_text", preview: text.slice(0, 100) });
645
926
  });
646
927
  this.transcriptMonitor.startPolling();
647
- // HangDetector remains the fleet-manager notification event bridge. Its
648
- // legacy silence timer is intentionally not started: pane state transitions
649
- // below are now the sole source of hang events.
928
+ // HangDetector is the notification bridge to the fleet manager; pane state
929
+ // transitions below are the sole source of hang events (see hang-detector.ts).
930
+ // `hang_detector.enabled: false` opts out of the notification entirely.
931
+ // NOTE: `hang_detector.timeout_minutes` is NOT read here — the stuck timeout
932
+ // the pane monitor actually uses is resolved separately below. The two have
933
+ // long been separate; documented rather than silently ignored.
650
934
  const hangConfig = this.config.hang_detector;
651
935
  if (hangConfig?.enabled !== false) {
652
- this.hangDetector = new HangDetector(hangConfig?.timeout_minutes ?? 10);
936
+ this.hangDetector = new HangDetector();
653
937
  }
654
938
  // 8. Context guardian
655
939
  const statusFile = join(this.instanceDir, "statusline.json");
@@ -657,7 +941,6 @@ export class Daemon extends EventEmitter {
657
941
  this.guardian.startWatching();
658
942
  this.guardian.on("status_update", () => {
659
943
  this.saveSessionId();
660
- this.hangDetector?.recordStatuslineUpdate();
661
944
  });
662
945
  // Context rotation removed: all CLI backends have built-in auto-compact.
663
946
  // Crash recovery (health check + respawn with snapshot) is retained below.
@@ -677,6 +960,40 @@ export class Daemon extends EventEmitter {
677
960
  this.startInstanceStateMonitor();
678
961
  this.logger.info(`${this.name} ready`);
679
962
  }
963
+ /**
964
+ * Detect a CRASHED MCP server and report it once.
965
+ *
966
+ * The MCP server writes its pid to channel.mcp.pid at startup and unlinks it on
967
+ * a clean exit, so "file present + pid dead" specifically means it died without
968
+ * cleaning up (crash / OOM / SIGKILL). A missing file is either "not started
969
+ * yet" or "exited cleanly" — neither is an incident, and an orphan exit implies
970
+ * the CLI itself died, which the crash detector already covers.
971
+ *
972
+ * The daemon deliberately does NOT try to respawn it: MCP is a stdio protocol
973
+ * where the CLI spawns the server and owns its pipes, so a daemon-spawned
974
+ * process would have no client reading it. Only the CLI can restore its own
975
+ * tools — hence notify, and let the operator decide about restarting.
976
+ */
977
+ checkMcpServerAlive() {
978
+ if (this.isPaused)
979
+ return;
980
+ const status = mcpServerState(this.instanceDir);
981
+ if (status.state === "unknown")
982
+ return;
983
+ if (status.state === "alive") {
984
+ this.mcpDeathNotifiedForPid = null; // the CLI respawned it — re-arm
985
+ return;
986
+ }
987
+ // Dead: report once per pid, and at most once per cooldown window.
988
+ if (this.mcpDeathNotifiedForPid === status.pid)
989
+ return;
990
+ if (Date.now() - this.lastMcpDeathNotifiedAt < Daemon.MCP_DEATH_COOLDOWN_MS)
991
+ return;
992
+ this.mcpDeathNotifiedForPid = status.pid;
993
+ this.lastMcpDeathNotifiedAt = Date.now();
994
+ this.logger.error({ pid: status.pid }, "MCP server process is gone — instance has no agend tools");
995
+ this.emit("mcp_died", { name: this.name, pid: status.pid });
996
+ }
680
997
  startHealthCheck() {
681
998
  if (this.runtimeMonitorsFrozen || this.healthCheckTimer)
682
999
  return;
@@ -692,249 +1009,285 @@ export class Daemon extends EventEmitter {
692
1009
  this.healthCheckTimer = null;
693
1010
  if (this.runtimeMonitorsFrozen)
694
1011
  return;
695
- // Instance directory removed externally (e.g. `rm -rf ~/.agend/instances/<name>`).
696
- // Stop the loop permanently otherwise every tick triggers a respawn, whose
697
- // writeRotationSnapshot fails with ENOENT and gets caught as "Failed to respawn",
698
- // spamming errors every ~30s forever.
699
- if (!existsSync(this.instanceDir)) {
700
- this.logger.warn({ instanceDir: this.instanceDir }, "Instance directory missing — stopping health check");
701
- this.healthCheckPaused = true;
702
- this.healthCheckTimer = null;
703
- return;
704
- }
705
- if (!this.tmux || this.spawning || this.healthCheckPaused || Daemon.tmuxServerPaused) {
706
- scheduleNext();
707
- return;
708
- }
709
- // Human-readable backend label for logs (e.g. "claude", "kiro-cli")
710
- const cliLabel = this.backend?.binaryName ?? "CLI";
711
- let paneStatus = await this.tmux.getPaneStatus();
712
- // Auto-pause intentionally exits the pane process. A health tick that
713
- // began just before pause must not classify that exit as a crash.
714
- if (this.isPaused || this.pauseWakeState === "waking") {
715
- scheduleNext();
716
- return;
717
- }
718
- if (paneStatus?.alive) {
719
- scheduleNext();
720
- return;
721
- }
722
- // A null status is ambiguous: it can be a transient `tmux list-panes`
723
- // failure (e.g. tmux busy during a fleet-restart storm) rather than a
724
- // real exit. Re-confirm once after a short delay before treating it as
725
- // a crash. A non-null {alive:false} is a definite dead pane (real exit)
726
- // and needs no recheck.
727
- if (paneStatus === null) {
728
- await new Promise(r => setTimeout(r, 1500));
729
- paneStatus = await this.tmux.getPaneStatus();
1012
+ // The whole tick is guarded: an unguarded throw in here (a tmux hiccup,
1013
+ // ENOSPC on the crash-history write) became an unhandled rejection, which
1014
+ // the CLI turned into stopAll() + exit(1) for the ENTIRE fleet, and it also
1015
+ // ended this instance's health loop because scheduleNext() sat after the
1016
+ // throwing code. Catch, log, and keep checking.
1017
+ try {
1018
+ // Instance directory removed externally (e.g. `rm -rf ~/.agend/instances/<name>`).
1019
+ // Stop the loop permanently — otherwise every tick triggers a respawn, whose
1020
+ // writeRotationSnapshot fails with ENOENT and gets caught as "Failed to respawn",
1021
+ // spamming errors every ~30s forever.
1022
+ if (!existsSync(this.instanceDir)) {
1023
+ this.logger.warn({ instanceDir: this.instanceDir }, "Instance directory missing — stopping health check");
1024
+ this.healthCheckPaused = true;
1025
+ this.healthCheckTimer = null;
1026
+ this.emitSupervisionEnded("instance directory was removed from disk", "Recreate the instance, or delete it from fleet.yaml.");
1027
+ return;
1028
+ }
1029
+ if (!this.tmux || this.spawning || this.healthCheckPaused || Daemon.tmuxServerPaused) {
1030
+ scheduleNext();
1031
+ return;
1032
+ }
1033
+ // The CLI owns the MCP server process, so the daemon can only observe it.
1034
+ this.checkMcpServerAlive();
1035
+ // Human-readable backend label for logs (e.g. "claude", "kiro-cli")
1036
+ const cliLabel = this.backend?.binaryName ?? "CLI";
1037
+ let paneStatus = await this.tmux.getPaneStatus();
1038
+ // Auto-pause intentionally exits the pane process. A health tick that
1039
+ // began just before pause must not classify that exit as a crash.
1040
+ if (this.isPaused || this.pauseWakeState === "waking") {
1041
+ scheduleNext();
1042
+ return;
1043
+ }
730
1044
  if (paneStatus?.alive) {
731
- this.logger.debug(`[health] ${cliLabel} pane reported gone then alive on recheck transient query failure, ignoring`);
1045
+ // Instance output.log is fed by tmux pipe-pane and was previously never
1046
+ // rotated (only fleet.log / daemon.log were). Cap growth every tick.
1047
+ if (!this.config.lightweight) {
1048
+ rotateLogIfNeeded(join(this.instanceDir, "output.log"));
1049
+ }
732
1050
  scheduleNext();
733
1051
  return;
734
1052
  }
735
- }
736
- // paneStatus === null → window gone entirely (e.g. tmux server crash)
737
- // paneStatus.alive === false pane dead, exit code available
738
- const exitCode = paneStatus?.exitCode;
739
- this.logger.debug({ exitCode }, `[health] pane exited with code: ${exitCode}`);
740
- // Normal exit (e.g. user Ctrl+C or /exit) — no crash, no respawn
741
- if (paneStatus && exitCode === 0) {
742
- this.setProcessStatus("stopped");
743
- this.logger.info("CLI exited normally (code 0) — pausing health check");
744
- await this.tmux.killWindow();
745
- this.healthCheckPaused = true;
746
- return;
747
- }
748
- this.setProcessStatus("crashed");
749
- // Distinguish tmux server crash from single window crash.
750
- // nullReason records *why* getPaneStatus returned null (for diagnosing
751
- // whether this was a real window loss or a transient query failure).
752
- let crashType = "window";
753
- let nullReason;
754
- if (!paneStatus) {
755
- const serverAlive = await TmuxManager.sessionExists(this.tmuxSessionName);
756
- if (!serverAlive) {
757
- crashType = "server";
758
- nullReason = "server_gone";
759
- this.logger.error(`tmux server died — all ${cliLabel} windows lost`);
760
- // Fleet-level circuit breaker: pause all instances on repeated tmux server crashes
761
- Daemon.tmuxServerCrashTimestamps.push(Date.now());
762
- const cutoff = Date.now() - 5 * 60_000;
763
- Daemon.tmuxServerCrashTimestamps = Daemon.tmuxServerCrashTimestamps.filter(t => t > cutoff);
764
- if (Daemon.tmuxServerCrashTimestamps.length >= 2 && !Daemon.tmuxServerPaused) {
765
- Daemon.tmuxServerPaused = true;
766
- this.logger.error("Fleet-level tmux server circuit breaker triggered — pausing all respawns for 30s");
767
- this.emit("tmux_server_crash", this.name);
768
- if (!Daemon.tmuxServerRecoveryTimer) {
769
- Daemon.tmuxServerRecoveryTimer = setTimeout(() => {
770
- Daemon.tmuxServerRecoveryTimer = null;
771
- Daemon.tmuxServerPaused = false;
772
- }, 30_000);
773
- }
1053
+ // A null status is ambiguous: it can be a transient `tmux list-panes`
1054
+ // failure (e.g. tmux busy during a fleet-restart storm) rather than a
1055
+ // real exit. Re-confirm once after a short delay before treating it as
1056
+ // a crash. A non-null {alive:false} is a definite dead pane (real exit)
1057
+ // and needs no recheck.
1058
+ if (paneStatus === null) {
1059
+ await new Promise(r => setTimeout(r, 1500));
1060
+ paneStatus = await this.tmux.getPaneStatus();
1061
+ if (paneStatus?.alive) {
1062
+ this.logger.debug(`[health] ${cliLabel} pane reported gone then alive on recheck — transient query failure, ignoring`);
774
1063
  scheduleNext();
775
1064
  return;
776
1065
  }
777
- await new Promise(r => setTimeout(r, 2_000)); // let session stabilize
778
1066
  }
779
- else {
780
- // null but server alive: window-level disappearance. Probe whether
781
- // the window truly no longer exists vs a transient query glitch.
782
- nullReason = "no_window";
783
- try {
784
- const windows = await TmuxManager.listWindows(this.tmuxSessionName);
785
- if (windows.some(w => w.name === this.name))
786
- nullReason = "window_present_query_glitch";
1067
+ // paneStatus === null → window gone entirely (e.g. tmux server crash)
1068
+ // paneStatus.alive === false pane dead, exit code available
1069
+ const exitCode = paneStatus?.exitCode;
1070
+ this.logger.debug({ exitCode }, `[health] pane exited with code: ${exitCode}`);
1071
+ // Normal exit (e.g. user Ctrl+C or /exit) — no crash, no respawn
1072
+ if (paneStatus && exitCode === 0) {
1073
+ this.setProcessStatus("stopped");
1074
+ this.logger.info("CLI exited normally (code 0) — pausing health check");
1075
+ await this.tmux.killWindow();
1076
+ this.healthCheckPaused = true;
1077
+ this.emitSupervisionEnded("the CLI exited normally (code 0)", "Nothing crashed — start it again when you need it.");
1078
+ return;
1079
+ }
1080
+ this.setProcessStatus("crashed");
1081
+ // Distinguish tmux server crash from single window crash.
1082
+ // nullReason records *why* getPaneStatus returned null (for diagnosing
1083
+ // whether this was a real window loss or a transient query failure).
1084
+ let crashType = "window";
1085
+ let nullReason;
1086
+ if (!paneStatus) {
1087
+ const serverAlive = await TmuxManager.sessionExists(this.tmuxSessionName);
1088
+ if (!serverAlive) {
1089
+ crashType = "server";
1090
+ nullReason = "server_gone";
1091
+ this.logger.error(`tmux server died — all ${cliLabel} windows lost`);
1092
+ // Fleet-level circuit breaker: pause all instances on repeated tmux server crashes
1093
+ Daemon.tmuxServerCrashTimestamps.push(Date.now());
1094
+ const cutoff = Date.now() - 5 * 60_000;
1095
+ Daemon.tmuxServerCrashTimestamps = Daemon.tmuxServerCrashTimestamps.filter(t => t > cutoff);
1096
+ if (Daemon.tmuxServerCrashTimestamps.length >= 2 && !Daemon.tmuxServerPaused) {
1097
+ Daemon.tmuxServerPaused = true;
1098
+ this.logger.error("Fleet-level tmux server circuit breaker triggered — pausing all respawns for 30s");
1099
+ this.emit("tmux_server_crash", this.name);
1100
+ if (!Daemon.tmuxServerRecoveryTimer) {
1101
+ Daemon.tmuxServerRecoveryTimer = setTimeout(() => {
1102
+ Daemon.tmuxServerRecoveryTimer = null;
1103
+ Daemon.tmuxServerPaused = false;
1104
+ }, 30_000);
1105
+ }
1106
+ scheduleNext();
1107
+ return;
1108
+ }
1109
+ await new Promise(r => setTimeout(r, 2_000)); // let session stabilize
787
1110
  }
788
- catch {
789
- nullReason = "query_error";
1111
+ else {
1112
+ // null but server alive: window-level disappearance. Probe whether
1113
+ // the window truly no longer exists vs a transient query glitch.
1114
+ nullReason = "no_window";
1115
+ try {
1116
+ const windows = await TmuxManager.listWindows(this.tmuxSessionName);
1117
+ if (windows.some(w => w.name === this.name))
1118
+ nullReason = "window_present_query_glitch";
1119
+ }
1120
+ catch {
1121
+ nullReason = "query_error";
1122
+ }
1123
+ this.logger.warn({ exitCode, nullReason }, `${cliLabel} window not found (tmux server alive)`);
790
1124
  }
791
- this.logger.warn({ exitCode, nullReason }, `${cliLabel} window not found (tmux server alive)`);
792
1125
  }
793
- }
794
- else {
795
- this.logger.warn({ exitCode }, `${cliLabel} process exited`);
796
- }
797
- // Capture last output before killing. Best-effort even when the pane is
798
- // gone (paneStatus null) gives the crash record something to diagnose
799
- // from instead of an empty lastOutput.
800
- let lastOutput;
801
- try {
802
- const raw = await this.tmux.capturePaneWithHistory(50);
803
- // Strip ANSI escape codes for readability
804
- const cleaned = raw.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, "");
805
- lastOutput = cleaned.trimEnd() || undefined;
806
- }
807
- catch { /* best effort pane may already be gone */ }
808
- // Kill the dead window (remain-on-exit keeps it around) before respawn
809
- if (paneStatus) {
810
- await this.tmux.killWindow();
811
- }
812
- // Detect claude-code background session conflict recover without counting as crash
813
- if (lastOutput && (lastOutput.includes("background agent") || lastOutput.includes("Session is currently running"))) {
814
- if (!this.backgroundSessionRecoveryAttempted) {
815
- this.backgroundSessionRecoveryAttempted = true;
816
- this.logger.warn("Detected lingering background agent session — starting fresh (no resume)");
817
- const sidFile = join(this.instanceDir, "session-id");
1126
+ else {
1127
+ this.logger.warn({ exitCode }, `${cliLabel} process exited`);
1128
+ }
1129
+ // Capture last output before killing. Best-effort even when the pane is
1130
+ // gone (paneStatus null) gives the crash record something to diagnose
1131
+ // from instead of an empty lastOutput.
1132
+ let lastOutput;
1133
+ try {
1134
+ const raw = await this.tmux.capturePaneWithHistory(50);
1135
+ // Strip ANSI escape codes for readability
1136
+ const cleaned = raw.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, "");
1137
+ lastOutput = cleaned.trimEnd() || undefined;
1138
+ }
1139
+ catch { /* best effort — pane may already be gone */ }
1140
+ // Kill the dead window (remain-on-exit keeps it around) before respawn
1141
+ if (paneStatus) {
1142
+ await this.tmux.killWindow();
1143
+ }
1144
+ // Detect claude-code background session conflict — recover without counting as crash
1145
+ if (lastOutput && (lastOutput.includes("background agent") || lastOutput.includes("Session is currently running"))) {
1146
+ if (!this.backgroundSessionRecoveryAttempted) {
1147
+ this.backgroundSessionRecoveryAttempted = true;
1148
+ this.logger.warn("Detected lingering background agent session — starting fresh (no resume)");
1149
+ const sidFile = join(this.instanceDir, "session-id");
1150
+ try {
1151
+ unlinkSync(sidFile);
1152
+ }
1153
+ catch { }
1154
+ this.skipResume = true;
1155
+ await new Promise(r => setTimeout(r, 2_000));
1156
+ try {
1157
+ await this.spawnClaudeWindow();
1158
+ this.setProcessStatus("running");
1159
+ this.logger.info("Recovered from background session conflict");
1160
+ this.emit("crash_respawn", this.name);
1161
+ }
1162
+ catch (err) {
1163
+ this.logger.error({ err: err.message }, "Recovery from background session conflict failed");
1164
+ }
1165
+ return; // Don't count as crash
1166
+ }
1167
+ // Already attempted recovery — fall through to normal crash handling
1168
+ }
1169
+ // Detect a --continue/--resume failure (no conversation to resume). The
1170
+ // session-id file persists across the crash, so a blind respawn would add
1171
+ // --continue again and crash in the same way → loop. Clear the session id
1172
+ // and skip resume so the next spawn starts fresh. (skipResume also stops
1173
+ // saveSessionId below from resurrecting the id from statusline.json.)
1174
+ if (lastOutput && /no conversation found|no conversation to (continue|resume)|no previous (session|conversation)|--continue/i.test(lastOutput)) {
1175
+ this.logger.warn("Detected --continue/resume failure — clearing session-id; next spawn starts fresh");
818
1176
  try {
819
- unlinkSync(sidFile);
1177
+ unlinkSync(join(this.instanceDir, "session-id"));
820
1178
  }
821
- catch { }
1179
+ catch { /* may not exist */ }
822
1180
  this.skipResume = true;
823
- await new Promise(r => setTimeout(r, 2_000));
1181
+ }
1182
+ // Append to crash history
1183
+ this.appendCrashHistory({ exitCode, lastOutput, crashType, reason: nullReason });
1184
+ if (max_retries <= 0) {
1185
+ this.healthCheckPaused = true;
1186
+ this.logger.warn(`${cliLabel} window died — automatic restart is disabled`);
1187
+ this.emitSupervisionEnded("the CLI died and automatic restart is disabled (restart_policy.max_retries is 0)", "Start it manually, or raise max_retries in fleet.yaml.");
1188
+ return;
1189
+ }
1190
+ // Detect rapid crash: sliding window — 3+ crashes in 5 minutes
1191
+ this.crashTimestamps.push(Date.now());
1192
+ const crashWindowMs = 5 * 60_000;
1193
+ this.crashTimestamps = this.crashTimestamps.filter(t => t > Date.now() - crashWindowMs);
1194
+ if (this.crashTimestamps.length >= 3) {
1195
+ this.healthCheckPaused = true;
1196
+ this.logger.error({ crashesInWindow: this.crashTimestamps.length }, "3+ crashes in 5 minutes — pausing respawn");
1197
+ // P1: Persist crash state so next process restart skips resume
824
1198
  try {
825
- await this.spawnClaudeWindow();
826
- this.setProcessStatus("running");
827
- this.logger.info("Recovered from background session conflict");
828
- this.emit("crash_respawn", this.name);
829
- }
830
- catch (err) {
831
- this.logger.error({ err: err.message }, "Recovery from background session conflict failed");
1199
+ writeFileSync(join(this.instanceDir, "crash-state.json"), JSON.stringify({
1200
+ crashesInWindow: this.crashTimestamps.length,
1201
+ lastCrashAt: Date.now(),
1202
+ resumeDisabled: true,
1203
+ }));
832
1204
  }
833
- return; // Don't count as crash
1205
+ catch { /* best effort */ }
1206
+ this.emit("crash_loop", this.name);
1207
+ return; // don't schedule next — paused
834
1208
  }
835
- // Already attempted recovery fall through to normal crash handling
836
- }
837
- // Detect a --continue/--resume failure (no conversation to resume). The
838
- // session-id file persists across the crash, so a blind respawn would add
839
- // --continue again and crash in the same way → loop. Clear the session id
840
- // and skip resume so the next spawn starts fresh. (skipResume also stops
841
- // saveSessionId below from resurrecting the id from statusline.json.)
842
- if (lastOutput && /no conversation found|no conversation to (continue|resume)|no previous (session|conversation)|--continue/i.test(lastOutput)) {
843
- this.logger.warn("Detected --continue/resume failure — clearing session-id; next spawn starts fresh");
844
- try {
845
- unlinkSync(join(this.instanceDir, "session-id"));
1209
+ // Reset crash count if enough time has passed
1210
+ if (reset_after > 0 && Date.now() - this.lastCrashAt > reset_after) {
1211
+ this.crashCount = 0;
846
1212
  }
847
- catch { /* may not exist */ }
848
- this.skipResume = true;
849
- }
850
- // Append to crash history
851
- this.appendCrashHistory({ exitCode, lastOutput, crashType, reason: nullReason });
852
- if (max_retries <= 0) {
853
- this.healthCheckPaused = true;
854
- this.logger.warn(`${cliLabel} window died — automatic restart is disabled`);
855
- return;
856
- }
857
- // Detect rapid crash: sliding window — 3+ crashes in 5 minutes
858
- this.crashTimestamps.push(Date.now());
859
- const crashWindowMs = 5 * 60_000;
860
- this.crashTimestamps = this.crashTimestamps.filter(t => t > Date.now() - crashWindowMs);
861
- if (this.crashTimestamps.length >= 3) {
862
- this.healthCheckPaused = true;
863
- this.logger.error({ crashesInWindow: this.crashTimestamps.length }, "3+ crashes in 5 minutes — pausing respawn");
864
- // P1: Persist crash state so next process restart skips resume
865
- try {
866
- writeFileSync(join(this.instanceDir, "crash-state.json"), JSON.stringify({
867
- crashesInWindow: this.crashTimestamps.length,
868
- lastCrashAt: Date.now(),
869
- resumeDisabled: true,
870
- }));
1213
+ this.crashCount++;
1214
+ this.lastCrashAt = Date.now();
1215
+ if (this.crashCount > max_retries) {
1216
+ this.logger.error({ crashCount: this.crashCount, maxRetries: max_retries }, "Max crash retries exceeded — not respawning");
1217
+ this.healthCheckPaused = true;
1218
+ this.emitSupervisionEnded(`it crashed ${this.crashCount} times, exceeding restart_policy.max_retries (${max_retries})`, "Check the logs for the cause, then restart it.");
1219
+ return; // don't schedule next — given up
871
1220
  }
872
- catch { /* best effort */ }
873
- this.emit("crash_loop", this.name);
874
- return; // don't schedule next paused
875
- }
876
- // Reset crash count if enough time has passed
877
- if (reset_after > 0 && Date.now() - this.lastCrashAt > reset_after) {
878
- this.crashCount = 0;
879
- }
880
- this.crashCount++;
881
- this.lastCrashAt = Date.now();
882
- if (this.crashCount > max_retries) {
883
- this.logger.error({ crashCount: this.crashCount, maxRetries: max_retries }, "Max crash retries exceeded — not respawning");
884
- return; // don't schedule next — given up
885
- }
886
- // Calculate backoff delay
887
- const delay = backoff === "exponential"
888
- ? Math.min(1000 * Math.pow(2, this.crashCount - 1), 60_000)
889
- : 1000 * this.crashCount;
890
- this.logger.warn({ crashCount: this.crashCount, delay }, `${cliLabel} window died — respawning after backoff`);
891
- await new Promise(r => setTimeout(r, delay));
892
- try {
893
- this.saveSessionId();
894
- this.transcriptMonitor?.resetOffset();
895
- // Kill orphan MCP server from the crashed CLI session.
896
- // MCP server writes its PID to channel.mcp.pid on startup.
897
- try {
898
- const pidFile = join(this.instanceDir, "channel.mcp.pid");
899
- const pid = parseInt(readFileSync(pidFile, "utf-8").trim(), 10);
900
- process.kill(pid, "SIGTERM");
901
- this.logger.info({ pid }, "Killed orphan MCP server");
902
- }
903
- catch { /* no pid file or process already dead */ }
904
- // Kill any same-name windows before respawn to prevent orphans.
905
- // Wrapped in try-catch: if tmux server is dead, listWindows throws —
906
- // must not block spawnClaudeWindow (which calls ensureSession).
1221
+ // Calculate backoff delay
1222
+ const delay = backoff === "exponential"
1223
+ ? Math.min(1000 * Math.pow(2, this.crashCount - 1), 60_000)
1224
+ : 1000 * this.crashCount;
1225
+ this.logger.warn({ crashCount: this.crashCount, delay }, `${cliLabel} window died — respawning after backoff`);
1226
+ await new Promise(r => setTimeout(r, delay));
907
1227
  try {
908
- const windows = await TmuxManager.listWindows(this.tmuxSessionName);
909
- for (const w of windows) {
910
- if (w.name === this.name) {
911
- const tm = new TmuxManager(this.tmuxSessionName, w.id);
912
- await tm.killWindow();
913
- }
1228
+ this.saveSessionId();
1229
+ this.transcriptMonitor?.resetOffset();
1230
+ // Kill orphan MCP server from the crashed CLI session.
1231
+ // MCP server writes its PID to channel.mcp.pid on startup.
1232
+ try {
1233
+ const pidFile = join(this.instanceDir, "channel.mcp.pid");
1234
+ const pid = parseInt(readFileSync(pidFile, "utf-8").trim(), 10);
1235
+ process.kill(pid, "SIGTERM");
1236
+ this.logger.info({ pid }, "Killed orphan MCP server");
914
1237
  }
915
- }
916
- catch { /* tmux server may be dead ensureSession in trySpawn will recover */ }
917
- // Write snapshot before spawn consumed only if resume fails
918
- this.writeRotationSnapshot("crash");
919
- // Try --resume first; spawnClaudeWindow falls back to fresh session if resume fails
920
- const resumed = await this.spawnClaudeWindow();
921
- if (!resumed) {
922
- // Resume failed → fresh session → inject snapshot for context
923
- await this.injectSnapshotMessage();
924
- }
925
- else {
926
- // Clean up stale snapshot — resume restored full context
1238
+ catch { /* no pid file or process already dead */ }
1239
+ // Kill any same-name windows before respawn to prevent orphans.
1240
+ // Wrapped in try-catch: if tmux server is dead, listWindows throws —
1241
+ // must not block spawnClaudeWindow (which calls ensureSession).
927
1242
  try {
928
- unlinkSync(join(this.instanceDir, "rotation-state.json"));
1243
+ const windows = await TmuxManager.listWindows(this.tmuxSessionName);
1244
+ for (const w of windows) {
1245
+ if (w.name === this.name) {
1246
+ const tm = new TmuxManager(this.tmuxSessionName, w.id);
1247
+ await tm.killWindow();
1248
+ }
1249
+ }
929
1250
  }
930
- catch { /* may not exist */ }
1251
+ catch { /* tmux server may be dead — ensureSession in trySpawn will recover */ }
1252
+ // Write snapshot before spawn — consumed only if resume fails
1253
+ this.writeRotationSnapshot("crash");
1254
+ // Try --resume first; spawnClaudeWindow falls back to fresh session if resume fails
1255
+ const resumed = await this.spawnClaudeWindow();
1256
+ if (!resumed) {
1257
+ // Resume failed → fresh session → inject snapshot for context
1258
+ await this.injectSnapshotMessage();
1259
+ }
1260
+ else {
1261
+ // Clean up stale snapshot — resume restored full context
1262
+ try {
1263
+ unlinkSync(join(this.instanceDir, "rotation-state.json"));
1264
+ }
1265
+ catch { /* may not exist */ }
1266
+ }
1267
+ this.setProcessStatus("running");
1268
+ this.logger.info({ resumed }, `Respawned ${cliLabel} window after crash`);
1269
+ this.emit("crash_respawn", this.name);
1270
+ }
1271
+ catch (err) {
1272
+ this.logger.error({ err }, `Failed to respawn ${cliLabel} window`);
931
1273
  }
932
- this.setProcessStatus("running");
933
- this.logger.info({ resumed }, `Respawned ${cliLabel} window after crash`);
934
- this.emit("crash_respawn", this.name);
935
1274
  }
936
1275
  catch (err) {
937
- this.logger.error({ err }, `Failed to respawn ${cliLabel} window`);
1276
+ this.logger.error({ err }, "Health check tick failed — continuing");
1277
+ // Surface it to the operator, not just the log — a health check that
1278
+ // keeps throwing means this instance is no longer being supervised.
1279
+ // Throttled: the tick repeats every ~30s, so an unnotified persistent
1280
+ // fault would otherwise post twice a minute forever.
1281
+ const now = Date.now();
1282
+ if (now - this.lastHealthErrorNotifyAt > HEALTH_ERROR_NOTIFY_INTERVAL_MS) {
1283
+ this.lastHealthErrorNotifyAt = now;
1284
+ this.emit("health_check_error", {
1285
+ name: this.name,
1286
+ message: err instanceof Error ? err.message : String(err),
1287
+ });
1288
+ }
1289
+ scheduleNext();
1290
+ return;
938
1291
  }
939
1292
  scheduleNext();
940
1293
  }, healthCheckIntervalMs);
@@ -946,6 +1299,21 @@ export class Daemon extends EventEmitter {
946
1299
  * A dead remain-on-exit pane still contains the old ready prompt, so allowing
947
1300
  * the pane monitor to capture it would re-create a false idle state.
948
1301
  */
1302
+ /**
1303
+ * Announce that this instance is no longer being supervised.
1304
+ *
1305
+ * Four health-check exits set `healthCheckPaused = true` and returned without
1306
+ * telling anyone: a clean CLI exit, `max_retries <= 0`, crash retries exhausted,
1307
+ * and the instance directory being deleted. Only the crash-LOOP case emitted an
1308
+ * event, so a fleet could quietly contain a dead instance that still looked fine
1309
+ * on the dashboard — while messages routed to it queued or failed with a bare ❌.
1310
+ *
1311
+ * `crash_loop` already had this treatment; this is the same bridge for the other
1312
+ * four, carrying a human-readable cause and the operator's next step.
1313
+ */
1314
+ emitSupervisionEnded(reason, remedy) {
1315
+ this.emit("supervision_ended", { name: this.name, reason, remedy });
1316
+ }
949
1317
  setProcessStatus(status) {
950
1318
  if (this.processStatus === status)
951
1319
  return;
@@ -984,13 +1352,12 @@ export class Daemon extends EventEmitter {
984
1352
  return;
985
1353
  const patterns = this.backend?.getErrorPatterns?.() ?? [];
986
1354
  const dialogs = this.backend?.getRuntimeDialogs?.() ?? [];
987
- if (!patterns.length && !dialogs.length)
988
- return;
989
1355
  if (!this.tmux)
990
1356
  return;
991
1357
  if (!this.backend)
992
1358
  return; // lightweight mode has no backend
993
1359
  const readyPattern = this.backend.getReadyPattern();
1360
+ const busyPattern = this.backend.getBusyPattern?.() ?? null;
994
1361
  this.errorMonitorTimer = setInterval(async () => {
995
1362
  if (!this.tmux || this.spawning)
996
1363
  return;
@@ -999,24 +1366,41 @@ export class Daemon extends EventEmitter {
999
1366
  if (!alive)
1000
1367
  return;
1001
1368
  const pane = await this.tmux.capturePane();
1369
+ const interactivePrompt = this.interactivePromptDetector.observe(pane, Date.now(), this.instanceStateLastOutputAt);
1370
+ if (interactivePrompt) {
1371
+ this.logger.warn(interactivePrompt, "Interactive terminal prompt is waiting for human input");
1372
+ this.emit("interactive_prompt", { name: this.name, ...interactivePrompt });
1373
+ // A prompt is not an error and must not enter the PTY recovery gate.
1374
+ // Continue scanning real errors in this same snapshot.
1375
+ }
1002
1376
  // Auto-dismiss runtime dialogs (e.g. Codex rate limit model switch)
1003
1377
  for (const dialog of dialogs) {
1004
1378
  if (!dialog.pattern.test(pane))
1005
1379
  continue;
1006
- this.logger.info(`Auto-dismissing runtime dialog: ${dialog.description}`);
1007
- const SPECIAL_KEYS = new Set(["Up", "Down", "Enter", "Escape", "Right", "Left"]);
1008
- for (const key of dialog.keys) {
1009
- if (SPECIAL_KEYS.has(key)) {
1010
- await this.tmux.sendSpecialKey(key);
1011
- }
1012
- else {
1013
- await this.tmux.pasteText(key);
1380
+ // These keys go straight into the pane. Sent while a message delivery is
1381
+ // mid-transaction, an `Escape` wipes the pasted text and an `Enter`
1382
+ // submits it half-composed — the user sees a message that vanished. Skip
1383
+ // (not queue) when the pane is busy: this poller runs every 5s, and the
1384
+ // dialog will still be on screen next tick.
1385
+ const dismissed = await this.paneWriteLock.tryRun(async () => {
1386
+ this.logger.info(`Auto-dismissing runtime dialog: ${dialog.description}`);
1387
+ const SPECIAL_KEYS = new Set(["Up", "Down", "Enter", "Escape", "Right", "Left"]);
1388
+ for (const key of dialog.keys) {
1389
+ if (SPECIAL_KEYS.has(key)) {
1390
+ await this.tmux.sendSpecialKey(key);
1391
+ }
1392
+ else {
1393
+ await this.tmux.pasteText(key, this.systemPasteOptions());
1394
+ }
1395
+ await new Promise(r => setTimeout(r, 200));
1014
1396
  }
1015
- await new Promise(r => setTimeout(r, 200));
1397
+ });
1398
+ if (!dismissed) {
1399
+ this.logger.debug({ dialog: dialog.description }, "Dialog dismissal deferred — pane write in flight");
1016
1400
  }
1017
- return; // Dialog dismissed, skip error checks this cycle
1401
+ return; // Dialog handled (or deliberately deferred): skip error checks this cycle
1018
1402
  }
1019
- this.evaluateErrorPatterns(pane, patterns, readyPattern);
1403
+ this.evaluateErrorPatterns(pane, patterns, readyPattern, Date.now(), busyPattern);
1020
1404
  }
1021
1405
  catch {
1022
1406
  // capturePane can fail if window is transitioning — ignore
@@ -1024,7 +1408,7 @@ export class Daemon extends EventEmitter {
1024
1408
  }, 5_000); // Check every 5 seconds (runtime dialogs need fast response)
1025
1409
  }
1026
1410
  /** Evaluate one pane snapshot. Kept synchronous so state-machine edges are unit-testable. */
1027
- evaluateErrorPatterns(pane, patterns, readyPattern, now = Date.now()) {
1411
+ evaluateErrorPatterns(pane, patterns, readyPattern, now = Date.now(), busyPattern = null) {
1028
1412
  // Count occurrences across the WHOLE pane (not just text after the last
1029
1413
  // ready prompt). Clone with `g` so stateful backend regexes cannot leak
1030
1414
  // lastIndex between monitor cycles.
@@ -1032,10 +1416,15 @@ export class Daemon extends EventEmitter {
1032
1416
  const flags = pattern.flags.includes("g") ? pattern.flags : pattern.flags + "g";
1033
1417
  return (pane.match(new RegExp(pattern.source, flags)) || []).length;
1034
1418
  };
1419
+ // Same veto as the state machine: a backend whose ready marker is permanently
1420
+ // on screen would otherwise "recover" on the very first tick after the error,
1421
+ // rebaselining the occurrence count while the error is still displayed — one
1422
+ // notification, a false recovery log, then silence.
1423
+ const looksReady = () => !busyPattern?.test(pane) && readyPattern.test(pane);
1035
1424
  // State: waiting for recovery. A missing/outdated ready pattern must not
1036
1425
  // suppress every future error forever, so the gate has a hard deadline.
1037
1426
  if (this.errorWaitingForRecovery) {
1038
- if (readyPattern.test(pane)) {
1427
+ if (looksReady()) {
1039
1428
  const downtime = Math.round((now - this.errorDetectedAt) / 1000);
1040
1429
  const active = patterns.find(ep => Daemon.errorPatternKey(ep) === this.activeErrorPatternKey);
1041
1430
  if (active) {
@@ -1134,6 +1523,12 @@ export class Daemon extends EventEmitter {
1134
1523
  * Interrupt the CLI's current generation (cancel button / `/cancel`).
1135
1524
  * Direct tmux key event (not a paste) so it registers as the interrupt key.
1136
1525
  * kiro-cli interrupts on Ctrl+C; the others (claude-code, codex, …) on Escape.
1526
+ *
1527
+ * Deliberately NOT taken through `paneWriteLock`. Cancel is the user's way out
1528
+ * of a pane that is busy or wedged — queueing it behind the very delivery chain
1529
+ * it exists to unblock would make the button useless exactly when it is needed.
1530
+ * The cost is accepted: an Escape landing between a paste and its Enter discards
1531
+ * that message, which is what the user asked for anyway.
1137
1532
  */
1138
1533
  async sendEscape() {
1139
1534
  const cancelKey = this.backend?.getCancelKey() ?? "Escape";
@@ -1171,7 +1566,6 @@ export class Daemon extends EventEmitter {
1171
1566
  this.toolStatusDebounce = null;
1172
1567
  }
1173
1568
  this.pendingIpcRequests.clear();
1174
- this.hangDetector?.stop();
1175
1569
  if (this.adapter)
1176
1570
  await this.adapter.stop();
1177
1571
  // Notify MCP servers of graceful shutdown (prevents reconnect attempts)
@@ -1198,7 +1592,12 @@ export class Daemon extends EventEmitter {
1198
1592
  if (!killed)
1199
1593
  this.logger.warn("CLI did not exit gracefully within 3s, force killing window");
1200
1594
  // Always kill window — remain-on-exit keeps dead panes around after CLI exits
1595
+ const stoppedWindowId = this.tmux.getWindowId();
1201
1596
  await this.tmux.killWindow();
1597
+ // The control client is shared across the fleet and outlives this daemon, so
1598
+ // a registration left behind here is re-resolved on every reconnect forever.
1599
+ if (stoppedWindowId)
1600
+ this.controlClient?.unregisterWindow(stoppedWindowId);
1202
1601
  const windowIdFile = join(this.instanceDir, "window-id");
1203
1602
  try {
1204
1603
  unlinkSync(windowIdFile);
@@ -1241,6 +1640,16 @@ export class Daemon extends EventEmitter {
1241
1640
  };
1242
1641
  }
1243
1642
  /** Gracefully stop the CLI while keeping its remain-on-exit tmux window. */
1643
+ /**
1644
+ * Mark the instance to pause as soon as its pane is idle. Used for auth
1645
+ * failures: pause() alone no-ops while the CLI is busy/stuck, which is the
1646
+ * usual state when the error surfaces. Cleared by a successful pause or wake.
1647
+ */
1648
+ requestPauseWhenIdle() {
1649
+ if (this.pauseWakeState === "paused")
1650
+ return;
1651
+ this.pausePending = true;
1652
+ }
1244
1653
  async pause() {
1245
1654
  if (this.pauseWakeState === "paused")
1246
1655
  return;
@@ -1310,6 +1719,9 @@ export class Daemon extends EventEmitter {
1310
1719
  }
1311
1720
  /** Respawn the CLI in the preserved window and block until its prompt is ready. */
1312
1721
  async wake(timeoutMs = 30_000) {
1722
+ // An explicit wake (e.g. after the user re-logs in) cancels a deferred
1723
+ // auth pause — otherwise the instance would pause again the moment it idles.
1724
+ this.pausePending = false;
1313
1725
  if (this.pauseWakeState === "active")
1314
1726
  return;
1315
1727
  if (this.pauseWakeState === "pausing")
@@ -1321,7 +1733,7 @@ export class Daemon extends EventEmitter {
1321
1733
  return;
1322
1734
  }
1323
1735
  this.pauseWakeState = "waking";
1324
- this.spawning = true;
1736
+ this.beginSpawn();
1325
1737
  const transition = this.autoPauseController.wakeOnDeliver(async () => {
1326
1738
  let timeout;
1327
1739
  try {
@@ -1362,7 +1774,7 @@ export class Daemon extends EventEmitter {
1362
1774
  throw err;
1363
1775
  }
1364
1776
  finally {
1365
- this.spawning = false;
1777
+ this.endSpawn();
1366
1778
  if (this.pauseWakeTransition === transition)
1367
1779
  this.pauseWakeTransition = null;
1368
1780
  }
@@ -1374,6 +1786,10 @@ export class Daemon extends EventEmitter {
1374
1786
  // observations between enqueue and paste must not clear a newer inbound.
1375
1787
  if (snapshot.state === "idle" && previous !== "idle") {
1376
1788
  this.pendingWork.recordIdle(snapshot.observedAt);
1789
+ // The turn is over. A transcript can end on a tool_use with no matching
1790
+ // tool_result (interrupted, crashed, cancelled), which would otherwise leave
1791
+ // the last tool pinned to the progress line for the rest of the session.
1792
+ this.publishActivity(null);
1377
1793
  }
1378
1794
  if (snapshot.state !== previous) {
1379
1795
  this.logger.info({
@@ -1389,6 +1805,12 @@ export class Daemon extends EventEmitter {
1389
1805
  }
1390
1806
  if (snapshot.state !== "idle")
1391
1807
  this.pauseRequested = false;
1808
+ // A pause deferred by an auth failure: retry the moment the pane settles.
1809
+ if (this.pausePending && snapshot.state === "idle" && this.pasteQueueDepth === 0) {
1810
+ this.pausePending = false;
1811
+ this.emit("auto_pause_requested", { name: this.name, idleSince: snapshot.stateChangedAt });
1812
+ return;
1813
+ }
1392
1814
  if (!this.pauseRequested && this.pasteQueueDepth === 0 && this.autoPauseController.observe(snapshot.state)) {
1393
1815
  this.pauseRequested = true;
1394
1816
  this.emit("auto_pause_requested", { name: this.name, idleSince: snapshot.stateChangedAt });
@@ -1455,9 +1877,29 @@ export class Daemon extends EventEmitter {
1455
1877
  || (this.instanceStateLastOutputAt > 0 && this.instanceStateLastOutputAt >= captureStartedAt))
1456
1878
  return;
1457
1879
  const observedChangeAt = expectedOutputAt || captureStartedAt;
1458
- this.instanceStateMachine.observe(pane, observedChangeAt);
1459
- const snapshot = this.instanceStateMachine.observe(pane, Date.now());
1880
+ // One observation per capture. This used to call observe() twice with the
1881
+ // same pane: the second call always saw an unchanged pane, so the
1882
+ // "content moved → still working" branch could never fire and the state
1883
+ // came down to the busy/ready patterns alone. That is why a single
1884
+ // mismatched spinner frame was enough to report idle mid-turn.
1885
+ const settled = this.instanceStateLastOutputAt === 0
1886
+ || captureStartedAt - this.instanceStateLastOutputAt >= this.instanceStateIdleDebounceMs;
1887
+ // The two times are genuinely different and both matter: the content
1888
+ // changed when tmux reported output (observedChangeAt), but idle/stuck are
1889
+ // decisions about *now*. The old double-observe expressed that by calling
1890
+ // observe twice, which silently disabled the "content moved" branch.
1891
+ const snapshot = this.instanceStateMachine.observe(pane, Date.now(), {
1892
+ settled,
1893
+ changeAt: observedChangeAt,
1894
+ });
1460
1895
  this.applyInstanceStateSnapshot(snapshot, pane);
1896
+ // Backends without a transcript feed can still say what they are doing, if
1897
+ // their TUI names it. Free-riding on a capture that already happened: no
1898
+ // extra tmux call. Cadence is the capture cadence (idle debounce + the 60s
1899
+ // safety sweep), which matches the progress ticker's own 60s interval.
1900
+ if (this.backend?.getPaneActivity) {
1901
+ this.publishActivity(snapshot.state === "idle" ? null : this.backend.getPaneActivity(pane));
1902
+ }
1461
1903
  if (snapshot.state === "idle") {
1462
1904
  this.clearInstanceStateStuckTimer();
1463
1905
  }
@@ -1512,7 +1954,8 @@ export class Daemon extends EventEmitter {
1512
1954
  ? rawConfig.idle_debounce_ms
1513
1955
  : DEFAULT_STATE_IDLE_DEBOUNCE_MS;
1514
1956
  this.instanceStateReadyPattern = this.backend.getReadyPattern();
1515
- this.instanceStateMachine = new PaneStateMachine(this.instanceStateReadyPattern, this.instanceStateStuckTimeoutMs);
1957
+ this.instanceStateBusyPattern = this.backend.getBusyPattern?.() ?? null;
1958
+ this.instanceStateMachine = new PaneStateMachine(this.instanceStateReadyPattern, this.instanceStateStuckTimeoutMs, Date.now(), this.instanceStateBusyPattern);
1516
1959
  this.instanceStateLastOutputAt = 0;
1517
1960
  this.instanceStateMonitorActive = true;
1518
1961
  if (this.controlClient) {
@@ -1553,6 +1996,12 @@ export class Daemon extends EventEmitter {
1553
1996
  paneTail: sanitizePaneTail(pane),
1554
1997
  readyPattern: readyPattern.toString(),
1555
1998
  readyMatched: deterministicReadyPattern.test(pane),
1999
+ // A pane that is stuck *while* the ready marker matches means the busy
2000
+ // pattern is what held it back — worth seeing when tuning either regex.
2001
+ busyPattern: this.instanceStateBusyPattern?.toString(),
2002
+ busyMatched: this.instanceStateBusyPattern
2003
+ ? new RegExp(this.instanceStateBusyPattern.source, this.instanceStateBusyPattern.flags.replace(/[gy]/g, "")).test(pane)
2004
+ : undefined,
1556
2005
  unchangedForMs: snapshot.unchangedForMs,
1557
2006
  pendingWork: this.pendingWork.hasPendingWork(),
1558
2007
  };
@@ -1574,6 +2023,7 @@ export class Daemon extends EventEmitter {
1574
2023
  clearInterval(this.errorMonitorTimer);
1575
2024
  this.errorMonitorTimer = null;
1576
2025
  }
2026
+ this.interactivePromptDetector.reset();
1577
2027
  this.stopInstanceStateMonitor();
1578
2028
  this.transcriptMonitor?.stop();
1579
2029
  this.guardian?.stop();
@@ -1595,6 +2045,40 @@ export class Daemon extends EventEmitter {
1595
2045
  return this.messageBus;
1596
2046
  }
1597
2047
  // ── Tool status tracking ──────────────────────────────────────
2048
+ /**
2049
+ * Tell the fleet manager what this instance is doing right now, for the live
2050
+ * progress line on the cancel button.
2051
+ *
2052
+ * Purely cosmetic — nothing decides anything from it, so it is fine that only
2053
+ * backends with a transcript feed report at all (claude-code today). For the
2054
+ * rest the progress line keeps showing just elapsed time.
2055
+ *
2056
+ * Repeats are dropped: the ticker only edits the channel message when the text
2057
+ * changes, and a stream of identical broadcasts would defeat that.
2058
+ */
2059
+ publishActivity(activity) {
2060
+ const next = activity && activity.trim() ? activity.trim() : null;
2061
+ if (next === this.currentActivity)
2062
+ return;
2063
+ this.currentActivity = next;
2064
+ this.ipcServer?.broadcast({
2065
+ type: "instance_activity",
2066
+ instanceName: this.name,
2067
+ activity: next,
2068
+ });
2069
+ }
2070
+ /**
2071
+ * Options for every system-initiated paste (startup notice, session snapshot,
2072
+ * runtime-dialog keys).
2073
+ *
2074
+ * One place, so the three call sites cannot drift apart on it. Backends with a
2075
+ * native input queue do not get the retry Enter: on those, a second bare Enter
2076
+ * is not the no-op the retry assumed but a queue mutation — the same reason
2077
+ * `deliverMessage` refuses to probe for busy with one.
2078
+ */
2079
+ systemPasteOptions() {
2080
+ return { retryEnter: this.backend?.supportsQueuedInput?.() !== true };
2081
+ }
1598
2082
  summarizeTool(name, input) {
1599
2083
  const inp = input;
1600
2084
  if (!inp)
@@ -1605,8 +2089,9 @@ export class Daemon extends EventEmitter {
1605
2089
  return `Edit ${inp.file_path ?? ""}`;
1606
2090
  if (name === "Write")
1607
2091
  return `Write ${inp.file_path ?? ""}`;
2092
+ // Command name only — never the arguments. See shellCommandLabel.
1608
2093
  if (name === "Bash")
1609
- return `$ ${String(inp.command ?? "").slice(0, 50)}`;
2094
+ return `$ ${shellCommandLabel(String(inp.command ?? ""))}`;
1610
2095
  if (name === "Glob")
1611
2096
  return `Glob ${inp.pattern ?? ""}`;
1612
2097
  if (name === "Grep")
@@ -1684,7 +2169,6 @@ export class Daemon extends EventEmitter {
1684
2169
  writeFileSync(join(this.instanceDir, "prev-instructions"), this.pendingInstructionsUpdate);
1685
2170
  this.pendingInstructionsUpdate = undefined;
1686
2171
  }
1687
- this.hangDetector?.recordInbound();
1688
2172
  this.pendingWork.recordInbound();
1689
2173
  // v3: record user messages for rotation snapshot
1690
2174
  this.recordRecentUserMessage(content, meta);
@@ -1707,12 +2191,26 @@ export class Daemon extends EventEmitter {
1707
2191
  // #77: show the sender's display name for readability, keeping the machine
1708
2192
  // instance name in parens so the recipient's send_to_instance target is valid.
1709
2193
  const fromLabel = meta.from_display ? `${meta.from_display} (${fromInstance})` : fromInstance;
1710
- formatted = `[from:${fromLabel}] ${content}\n(If you need to reply, use send_to_instance tool, NOT direct text. If there is nothing to add, you may stay silent.)`;
2194
+ formatted = `[from:${fromLabel}] ${content}`;
2195
+ formatted += renderHandoffMetadata(meta);
2196
+ // A delegated task that requires a reply must not read like a chatty FYI —
2197
+ // the "you may stay silent" line is for the latter only.
2198
+ formatted += meta.requires_reply === "true"
2199
+ ? "\n(A reply IS required: use report_result with the correlation_id above — or send_to_instance. Not direct text.)"
2200
+ : "\n(If you need to reply, use send_to_instance tool, NOT direct text. If there is nothing to add, you may stay silent.)";
1711
2201
  }
1712
2202
  else {
1713
2203
  const via = meta.source ? ` via ${meta.source}` : "";
1714
2204
  const idTag = meta.user_id ? `, id:${meta.user_id}` : "";
1715
- formatted = `[user:${user}${via}${idTag}] ${content}\n(Reply using the reply tool — do NOT respond with direct text)`;
2205
+ formatted = `[user:${user}${via}${idTag}] ${content}`;
2206
+ // Reactions queued since the last real message (#432). One leading line of
2207
+ // context, present only when something is pending — a reaction no longer
2208
+ // costs a turn of its own.
2209
+ if (meta.pending_reactions) {
2210
+ formatted = `[Recent reactions: ${meta.pending_reactions}]\n${formatted}`;
2211
+ }
2212
+ formatted += renderHandoffMetadata(meta);
2213
+ formatted += "\n(Reply using the reply tool — do NOT respond with direct text)";
1716
2214
  }
1717
2215
  if (meta.reply_to_text) {
1718
2216
  formatted += `\n(reply_to: "${meta.reply_to_text}")`;
@@ -1755,18 +2253,19 @@ export class Daemon extends EventEmitter {
1755
2253
  }
1756
2254
  /**
1757
2255
  * Deliver a single message and drive its status reactions:
1758
- * ⏳ message_queued — CLI busy; queued, waiting for idle
2256
+ * ⏳ message_queued — CLI busy; queued locally or by the backend
1759
2257
  * 👀 message_delivered — pasted + Enter sent; agent now has it
1760
- * ✅ message_confirmed — idle→busy transition observed; agent is processing
2258
+ * ✅ message_confirmed — processing observed, or native queue handoff succeeded
1761
2259
  * ❌ message_failed — tmux window gone, paste retries exhausted
1762
2260
  * Returns true once the message is in the CLI, false only on real delivery failure.
1763
2261
  *
1764
2262
  * Bug A (silent message loss): paste failures retry with backoff (window recovery)
1765
2263
  * and emit `message_failed` if all attempts fail.
1766
- * Busy handling (UX): we never force-paste into a busy CLI and never give up on a
1767
- * busy one — we show ⏳ and wait for idle indefinitely (a genuinely hung CLI is the
1768
- * hang detector's job; a user who can't wait presses Cancel → Escape → idle). The
1769
- * pasteLock is serial, so later messages naturally queue behind this wait.
2264
+ * Busy handling (UX): backends without a native input queue show and wait for
2265
+ * idle indefinitely (a genuinely hung CLI is the hang detector's job). Backends
2266
+ * that explicitly support queued input receive one complete paste+Enter transaction
2267
+ * immediately and own the application-level queue themselves. The pasteLock remains
2268
+ * serial in both cases so separate PTY writes can never overlap.
1770
2269
  */
1771
2270
  async deliverMessage(formatted, status) {
1772
2271
  // Sanitize unclosed code fences — they cause CLI to wait for closure on Enter
@@ -1775,14 +2274,50 @@ export class Daemon extends EventEmitter {
1775
2274
  // Odd number of fences = unclosed. Remove all code fences from the message.
1776
2275
  formatted = formatted.replace(/```/g, "");
1777
2276
  }
2277
+ // Before anything reads the window id: a spawn in progress is about to change it.
2278
+ await this.waitForSpawnToSettle();
1778
2279
  let windowId = this.getWindowId();
1779
- // If the CLI is busy, show ⏳ and wait for it to go idle — no timeout, no force.
2280
+ const supportsQueuedInput = this.backend?.supportsQueuedInput?.() === true;
2281
+ let handingOffToNativeQueue = false;
2282
+ // If the CLI is busy, either hand the complete submission to its native input
2283
+ // queue or wait for idle. Native queue support is an explicit backend capability:
2284
+ // normal Enter input has steering/interrupt semantics in several other CLIs.
1780
2285
  if (windowId && this.controlClient && !this.controlClient.isIdle(windowId)) {
1781
2286
  if (status)
1782
2287
  this.emit("message_queued", status);
1783
- this.logger.debug("CLI busy — queuing message until idle");
1784
- await this.controlClient.waitUntilIdle(windowId);
2288
+ if (supportsQueuedInput) {
2289
+ handingOffToNativeQueue = true;
2290
+ this.logger.debug("CLI busy — handing message to backend-native input queue");
2291
+ }
2292
+ else {
2293
+ this.logger.debug("CLI busy — queuing message until idle");
2294
+ const becameIdle = await this.controlClient.waitUntilIdle(windowId);
2295
+ if (!becameIdle) {
2296
+ // The pane never freed up. Report the failure instead of pasting into a
2297
+ // wedged CLI (where the text would sit unsubmitted and the next message
2298
+ // would land on top of it) — and instead of holding the queue silently.
2299
+ this.logger.error("Pane still busy after the idle wait — reporting delivery failure");
2300
+ if (status)
2301
+ this.emit("message_failed", status); // ❌
2302
+ return false;
2303
+ }
2304
+ }
1785
2305
  }
2306
+ // Everything above is *waiting*; everything below *writes*. Only the write is
2307
+ // held under the pane lock — holding it across the idle wait (up to 30 min)
2308
+ // would starve the runtime-dialog dismisser, which is often the very thing
2309
+ // that would let the pane go idle again.
2310
+ return this.paneWriteLock.run(() => this.writeMessageToPane(formatted, windowId, handingOffToNativeQueue, status));
2311
+ }
2312
+ /**
2313
+ * The write half of a delivery: paste → Enter → confirm, with retries.
2314
+ *
2315
+ * Always called under {@link paneWriteLock}. Split out from `deliverMessage`
2316
+ * precisely so the lock's scope is visible at the call site rather than being
2317
+ * an invariant maintained by comments.
2318
+ */
2319
+ async writeMessageToPane(formatted, initialWindowId, handingOffToNativeQueue, status) {
2320
+ let windowId = initialWindowId;
1786
2321
  // Bug A: paste with backoff. Transient failures are usually a stale window id
1787
2322
  // after a crash/respawn — recover by name and retry (max 3 attempts, 2s apart).
1788
2323
  const maxAttempts = 3;
@@ -1807,9 +2342,56 @@ export class Daemon extends EventEmitter {
1807
2342
  await this.tmux.sendSpecialKey("Enter");
1808
2343
  if (status)
1809
2344
  this.emit("message_delivered", status); // 👀
1810
- // Confirm the CLI accepted the message by transitioning idle→busy (new output
1811
- // after Enter). If still idle after ~2s the Enter was likely swallowed while
1812
- // the TUI was redrawing re-send Enter once and re-check.
2345
+ // Busy queue-capable CLIs (codex) may accept paste without an idle→busy
2346
+ // transition. Do NOT probe for busy a second bare Enter can mutate the
2347
+ // queue. Instead verify the paste actually landed in the pane (TUI redraw
2348
+ // can silently swallow it). Idle submissions keep the swallowed-Enter path.
2349
+ if (handingOffToNativeQueue) {
2350
+ await new Promise(r => setTimeout(r, NATIVE_QUEUE_PASTE_VERIFY_MS));
2351
+ if (await this.nativeQueuePasteVisible(formatted)) {
2352
+ if (status)
2353
+ this.emit("message_confirmed", status); // ✅ native queue accepted
2354
+ return true;
2355
+ }
2356
+ // Silent loss: fall back once to the normal idle-gated path.
2357
+ this.logger.warn("Native-queue paste not visible in pane — retrying via idle-gated delivery");
2358
+ if (windowId && this.controlClient) {
2359
+ await this.controlClient.waitUntilIdle(windowId);
2360
+ }
2361
+ const repasted = await this.tmux.pasteBuffer(formatted);
2362
+ if (!repasted) {
2363
+ this.logger.error("Idle-gated redelivery paste failed after native-queue silent loss");
2364
+ if (status)
2365
+ this.emit("message_failed", status); // ❌
2366
+ return false;
2367
+ }
2368
+ await new Promise(r => setTimeout(r, NORMAL_ENTER_SETTLE_MS));
2369
+ const retryAt = Date.now();
2370
+ await this.tmux.sendSpecialKey("Enter");
2371
+ if (windowId && this.controlClient) {
2372
+ let becameBusy = await this.confirmBusyAfterEnter(windowId, retryAt);
2373
+ if (!becameBusy) {
2374
+ this.logger.warn("No idle→busy after idle-gated redelivery — re-sending Enter once");
2375
+ const retry2At = Date.now();
2376
+ await this.tmux.sendSpecialKey("Enter");
2377
+ becameBusy = await this.confirmBusyAfterEnter(windowId, retry2At);
2378
+ }
2379
+ if (becameBusy) {
2380
+ if (status)
2381
+ this.emit("message_confirmed", status); // ✅
2382
+ return true;
2383
+ }
2384
+ }
2385
+ else if (await this.nativeQueuePasteVisible(formatted)) {
2386
+ if (status)
2387
+ this.emit("message_confirmed", status); // ✅
2388
+ return true;
2389
+ }
2390
+ this.logger.error("Idle-gated redelivery also failed after native-queue silent loss");
2391
+ if (status)
2392
+ this.emit("message_failed", status); // ❌
2393
+ return false;
2394
+ }
1813
2395
  if (windowId && this.controlClient) {
1814
2396
  let becameBusy = await this.confirmBusyAfterEnter(windowId, enterAt);
1815
2397
  if (!becameBusy) {
@@ -1818,8 +2400,20 @@ export class Daemon extends EventEmitter {
1818
2400
  await this.tmux.sendSpecialKey("Enter");
1819
2401
  becameBusy = await this.confirmBusyAfterEnter(windowId, retryAt);
1820
2402
  }
1821
- if (becameBusy && status)
1822
- this.emit("message_confirmed", status); // ✅
2403
+ if (becameBusy) {
2404
+ if (status)
2405
+ this.emit("message_confirmed", status); // ✅
2406
+ }
2407
+ else {
2408
+ // Both Enters were swallowed: the text is sitting UNSUBMITTED in the
2409
+ // CLI's input box. This used to return true, so the reaction stayed at 👀
2410
+ // forever and the next delivery pasted on top — submitting two messages
2411
+ // as one. Say so instead.
2412
+ this.logger.error("Message pasted but never submitted (no idle→busy after two Enters)");
2413
+ if (status)
2414
+ this.emit("message_failed", status); // ❌
2415
+ return false;
2416
+ }
1823
2417
  }
1824
2418
  else {
1825
2419
  // No control client to observe output: fall back to the legacy double-Enter.
@@ -1835,8 +2429,36 @@ export class Daemon extends EventEmitter {
1835
2429
  this.emit("message_failed", status); // ❌
1836
2430
  return false;
1837
2431
  }
2432
+ /**
2433
+ * True when a busy native-queue paste appears to have landed: Codex shows a
2434
+ * `↳` queue marker, or a distinctive slice of the pasted text is on screen.
2435
+ * Used only to detect silent paste loss — not as a general ready check.
2436
+ */
2437
+ async nativeQueuePasteVisible(formatted) {
2438
+ if (!this.tmux)
2439
+ return false;
2440
+ try {
2441
+ const pane = await this.tmux.capturePane();
2442
+ if (pane.includes("↳"))
2443
+ return true;
2444
+ for (const line of formatted.split(/\r?\n/)) {
2445
+ const t = line.trim();
2446
+ if (t.length >= 8 && pane.includes(t))
2447
+ return true;
2448
+ }
2449
+ const compact = formatted.replace(/\s+/g, " ").trim();
2450
+ if (compact.length >= 8 && pane.includes(compact.slice(0, Math.min(80, compact.length)))) {
2451
+ return true;
2452
+ }
2453
+ return false;
2454
+ }
2455
+ catch {
2456
+ return false;
2457
+ }
2458
+ }
1838
2459
  /** Re-resolve this instance's tmux window by name (stale id after crash/respawn). */
1839
2460
  async recoverWindow() {
2461
+ const previousWindowId = this.tmux?.getWindowId();
1840
2462
  try {
1841
2463
  const windows = await TmuxManager.listWindows(this.tmuxSessionName);
1842
2464
  const match = windows.find(w => w.name === this.name);
@@ -1844,6 +2466,12 @@ export class Daemon extends EventEmitter {
1844
2466
  return undefined;
1845
2467
  this.tmux = new TmuxManager(this.tmuxSessionName, match.id, resolveTmuxLogicalSize(this.config.terminal));
1846
2468
  writeFileSync(join(this.instanceDir, "window-id"), match.id);
2469
+ // The window we were talking to is gone; leaving it registered means the
2470
+ // control client re-resolves a dead id — one tmux subprocess — on every
2471
+ // reconnect, for the life of the fleet process.
2472
+ if (previousWindowId && previousWindowId !== match.id) {
2473
+ this.controlClient?.unregisterWindow(previousWindowId);
2474
+ }
1847
2475
  await this.controlClient?.registerWindow(match.id);
1848
2476
  this.bindInstanceStateOutputListener(match.id);
1849
2477
  this.logger.info({ windowId: match.id }, "Recovered window ID for message delivery");
@@ -1854,12 +2482,38 @@ export class Daemon extends EventEmitter {
1854
2482
  return undefined;
1855
2483
  }
1856
2484
  }
1857
- /** Poll up to ~2s (200ms × 10) for the pane to emit output after `since`. */
2485
+ /**
2486
+ * Poll up to ~2s (200ms × 10) for the pane to emit output after `since`.
2487
+ *
2488
+ * A `false` here is not "no output" — it is read as **"the message was pasted but
2489
+ * never submitted"**, which re-sends Enter and then reports ❌ to the user. So a
2490
+ * false negative costs a possible double submit and a failure notice for a
2491
+ * message that actually arrived.
2492
+ *
2493
+ * That is exactly what a control-mode reconnect used to produce. `connect()`
2494
+ * drops every output timestamp, so `hasOutputSince` answers `false` for a pane
2495
+ * that did react — the evidence was thrown away, not absent. Blind time is
2496
+ * therefore not counted against the budget: after a reset the poll restarts from
2497
+ * the moment observation resumed. A hard wall-clock cap keeps a reconnect loop
2498
+ * from extending this forever.
2499
+ */
1858
2500
  async confirmBusyAfterEnter(windowId, since) {
1859
- for (let i = 0; i < 10; i++) {
1860
- await new Promise(r => setTimeout(r, 200));
1861
- if (this.controlClient.hasOutputSince(windowId, since))
2501
+ const client = this.controlClient;
2502
+ const hardDeadline = Date.now() + CONFIRM_BUSY_MAX_WAIT_MS;
2503
+ let observedFrom = since;
2504
+ let polls = 0;
2505
+ while (polls < CONFIRM_BUSY_POLLS) {
2506
+ await new Promise(r => setTimeout(r, CONFIRM_BUSY_POLL_MS));
2507
+ if (client.hasOutputSince(windowId, observedFrom))
1862
2508
  return true;
2509
+ const resetAt = client.getObservationResetAt();
2510
+ if (resetAt > observedFrom && Date.now() < hardDeadline) {
2511
+ this.logger.debug({ windowId, resetAt }, "Control mode reconnected mid-confirmation — restarting the Enter check from when we could see again");
2512
+ observedFrom = resetAt;
2513
+ polls = 0;
2514
+ continue;
2515
+ }
2516
+ polls++;
1863
2517
  }
1864
2518
  return false;
1865
2519
  }
@@ -1930,8 +2584,8 @@ export class Daemon extends EventEmitter {
1930
2584
  });
1931
2585
  const timeout = setTimeout(() => {
1932
2586
  this.pendingIpcRequests.delete(fleetReqId);
1933
- respond(null, "Task operation timed out after 30s");
1934
- }, 30_000);
2587
+ respond(null, `Task operation timed out after ${daemonBudgetMs(tool) / 1000}s`);
2588
+ }, daemonBudgetMs(tool));
1935
2589
  this.pendingIpcRequests.set(fleetReqId, (respMsg) => {
1936
2590
  clearTimeout(timeout);
1937
2591
  respond(respMsg.result, respMsg.error);
@@ -1953,8 +2607,8 @@ export class Daemon extends EventEmitter {
1953
2607
  });
1954
2608
  const timeout = setTimeout(() => {
1955
2609
  this.pendingIpcRequests.delete(fleetReqId);
1956
- respond(null, "Decision operation timed out after 30s");
1957
- }, 30_000);
2610
+ respond(null, `Decision operation timed out after ${daemonBudgetMs(tool) / 1000}s`);
2611
+ }, daemonBudgetMs(tool));
1958
2612
  this.pendingIpcRequests.set(fleetReqId, (respMsg) => {
1959
2613
  clearTimeout(timeout);
1960
2614
  respond(respMsg.result, respMsg.error);
@@ -1980,8 +2634,8 @@ export class Daemon extends EventEmitter {
1980
2634
  // Wait for fleet_schedule_response via pending request map
1981
2635
  const timeout = setTimeout(() => {
1982
2636
  this.pendingIpcRequests.delete(fleetReqId);
1983
- respond(null, "Schedule operation timed out after 30s");
1984
- }, 30_000);
2637
+ respond(null, `Schedule operation timed out after ${daemonBudgetMs(tool) / 1000}s`);
2638
+ }, daemonBudgetMs(tool));
1985
2639
  this.pendingIpcRequests.set(fleetReqId, (respMsg) => {
1986
2640
  clearTimeout(timeout);
1987
2641
  respond(respMsg.result, respMsg.error);
@@ -2002,7 +2656,9 @@ export class Daemon extends EventEmitter {
2002
2656
  fleetRequestId: fleetReqId,
2003
2657
  senderSessionName,
2004
2658
  });
2005
- const crossTimeoutMs = (tool === "start_instance" || tool === "create_instance" || tool === "replace_instance") ? 60_000 : 30_000;
2659
+ // Shared table, so delete_instance and the deployment tools get the same
2660
+ // budget here as the MCP client expects (the ad-hoc list omitted them).
2661
+ const crossTimeoutMs = daemonBudgetMs(tool);
2006
2662
  const timeout = setTimeout(() => {
2007
2663
  this.pendingIpcRequests.delete(fleetReqId);
2008
2664
  respond(null, `Cross-instance operation timed out after ${crossTimeoutMs / 1000}s`);
@@ -2045,8 +2701,8 @@ export class Daemon extends EventEmitter {
2045
2701
  this.ipcServer?.broadcast({ type: "fleet_outbound", tool, args, fleetRequestId: fleetReqId });
2046
2702
  const timeout = setTimeout(() => {
2047
2703
  this.pendingIpcRequests.delete(outboundKey);
2048
- respond(null, "Fleet outbound timed out after 30s");
2049
- }, 30_000);
2704
+ respond(null, `Fleet outbound timed out after ${daemonBudgetMs(tool) / 1000}s`);
2705
+ }, daemonBudgetMs(tool));
2050
2706
  this.pendingIpcRequests.set(outboundKey, (respMsg) => {
2051
2707
  clearTimeout(timeout);
2052
2708
  respond(respMsg.result, respMsg.error);
@@ -2110,7 +2766,14 @@ export class Daemon extends EventEmitter {
2110
2766
  try {
2111
2767
  const all = JSON.parse(process.env.AGEND_DECISIONS);
2112
2768
  const workDir = this.config.working_directory;
2113
- decisions = all.filter(d => d.scope === "fleet" || d.project_root === workDir);
2769
+ // `scope: "fleet"` used to bypass the project check entirely, so a
2770
+ // single-project worker inherited every other project's playbook (8 of
2771
+ // 14 injected here were foreign) — resent on every API call. Now a
2772
+ // fleet decision must also be RELEVANT: global (no project_root), the
2773
+ // same project, or the same project family (worktrees/checkouts of one
2774
+ // repo). A general is exempt: it dispatches across all projects, so
2775
+ // cross-project routing rules are exactly what it needs.
2776
+ decisions = selectRelevantDecisions(all, workDir, this.config.general_topic === true);
2114
2777
  // Stable ordering so identical decision sets always build byte-identical
2115
2778
  // instructions — otherwise source ordering jitter flips the warmup hash.
2116
2779
  decisions.sort((a, b) => a.title.localeCompare(b.title));
@@ -2124,9 +2787,18 @@ export class Daemon extends EventEmitter {
2124
2787
  AGEND_SOCKET_PATH: sockPath,
2125
2788
  AGEND_INSTANCE_NAME: this.name,
2126
2789
  AGEND_WORKING_DIR: this.config.working_directory,
2790
+ AGEND_INSTANCE_KIND: this.runtimeIdentity?.kind ?? "fleet-topic",
2791
+ AGEND_BACKEND: this.runtimeIdentity?.backend ?? this.config.backend ?? this.backend?.binaryName ?? "unknown",
2792
+ AGEND_MODEL: this.runtimeIdentity?.model ?? this.config.model ?? "default",
2127
2793
  };
2128
- if (this.config.tool_set)
2129
- mcpEnv.AGEND_TOOL_SET = this.config.tool_set;
2794
+ // A general is a dispatcher, not a worker: default it to the `general` tool
2795
+ // profile instead of `full`. Every tool's schema is resent on every API call,
2796
+ // so full (44 tools) costs a general ~22k chars per turn — the single largest
2797
+ // slice of its prompt. Explicit config still wins.
2798
+ const defaultToolSet = this.config.general_topic ? "general" : undefined;
2799
+ const toolSet = this.config.tool_set ?? defaultToolSet;
2800
+ if (toolSet)
2801
+ mcpEnv.AGEND_TOOL_SET = toolSet;
2130
2802
  if (this.config.display_name)
2131
2803
  mcpEnv.AGEND_DISPLAY_NAME = this.config.display_name;
2132
2804
  if (this.config.description)
@@ -2159,6 +2831,7 @@ export class Daemon extends EventEmitter {
2159
2831
  instructions = buildFleetInstructions({
2160
2832
  instanceName: this.name,
2161
2833
  workingDirectory: this.config.working_directory,
2834
+ runtimeIdentity: this.runtimeIdentity,
2162
2835
  displayName: this.config.display_name,
2163
2836
  description: this.config.description,
2164
2837
  customPrompt: resolvedCustomPrompt,
@@ -2171,6 +2844,7 @@ export class Daemon extends EventEmitter {
2171
2844
  instructions = buildFleetInstructions({
2172
2845
  instanceName: this.name,
2173
2846
  workingDirectory: this.config.working_directory,
2847
+ runtimeIdentity: this.runtimeIdentity,
2174
2848
  displayName: this.config.display_name,
2175
2849
  description: this.config.description,
2176
2850
  customPrompt: resolvedCustomPrompt,
@@ -2192,6 +2866,7 @@ export class Daemon extends EventEmitter {
2192
2866
  },
2193
2867
  skipPermissions: this.config.skipPermissions,
2194
2868
  model: this.modelOverride ?? this.config.model,
2869
+ effort: this.config.effort,
2195
2870
  kiroUi: this.config.kiro_ui,
2196
2871
  skipResume: this.skipResume,
2197
2872
  instructions,
@@ -2217,7 +2892,9 @@ export class Daemon extends EventEmitter {
2217
2892
  // Small delay to let the CLI fully render its ready prompt
2218
2893
  await new Promise(r => setTimeout(r, 1_000));
2219
2894
  try {
2220
- await this.tmux.pasteText(`[system:session-snapshot]\n${snapshot}\n\nThis is a background context restore do NOT reply to or acknowledge this message. Simply resume normal operation when the next user or instance message arrives.`);
2895
+ // Messages can arrive during a restart and be queued on pasteLock before the
2896
+ // snapshot lands; both write to the pane, so both go through the same lock.
2897
+ await this.paneWriteLock.run(() => this.tmux.pasteText(`[system:session-snapshot]\n${snapshot}\n\nThis is a background context restore — do NOT reply to or acknowledge this message. Simply resume normal operation when the next user or instance message arrives.`, this.systemPasteOptions()));
2221
2898
  this.logger.info("Injected session snapshot as first message");
2222
2899
  this.emit("snapshot_injected", this.name);
2223
2900
  }
@@ -2226,9 +2903,69 @@ export class Daemon extends EventEmitter {
2226
2903
  this.emit("snapshot_failed", this.name);
2227
2904
  }
2228
2905
  }
2906
+ /**
2907
+ * Depth, not a flag: the wake path marks a spawn and then calls trySpawn, which
2908
+ * marks another. With a plain boolean the inner one's completion would clear the
2909
+ * latch while the outer spawn was still dismissing dialogs, releasing delivery
2910
+ * into exactly the window this exists to close.
2911
+ */
2912
+ beginSpawn() {
2913
+ this.spawnDepth++;
2914
+ this.spawning = true;
2915
+ if (!this.spawnSettled) {
2916
+ this.spawnSettled = new Promise(resolve => { this.resolveSpawnSettled = resolve; });
2917
+ }
2918
+ }
2919
+ endSpawn() {
2920
+ this.spawnDepth = Math.max(0, this.spawnDepth - 1);
2921
+ if (this.spawnDepth > 0)
2922
+ return; // an enclosing spawn is still running
2923
+ this.spawning = false;
2924
+ const resolve = this.resolveSpawnSettled;
2925
+ this.spawnSettled = null;
2926
+ this.resolveSpawnSettled = null;
2927
+ resolve?.();
2928
+ }
2929
+ /**
2930
+ * Hold until the CLI has finished starting up.
2931
+ *
2932
+ * Startup is not a quiet period: `dismissDialogsUntilReady` is clicking through
2933
+ * trust prompts and session pickers. A pane showing a modal dialog produces no
2934
+ * output, so `waitUntilIdle` reports it idle and a queued message gets pasted
2935
+ * *into the dialog* — where the text is discarded and the Enter picks a menu
2936
+ * item. The paste and the Enter both "succeed", so this loses the message
2937
+ * without even a ❌.
2938
+ *
2939
+ * The pane write lock (#414) does not cover this: it serialises each key
2940
+ * sequence, but it is released between one dialog and the next.
2941
+ *
2942
+ * Bounded, and called BEFORE the pane lock is taken — waiting on the spawn while
2943
+ * holding the lock the spawn itself needs would deadlock.
2944
+ */
2945
+ async waitForSpawnToSettle() {
2946
+ const settled = this.spawnSettled;
2947
+ if (!settled)
2948
+ return;
2949
+ this.logger.debug("Holding delivery until the CLI has finished starting up");
2950
+ let timer;
2951
+ const cap = new Promise(resolve => {
2952
+ timer = setTimeout(resolve, SPAWN_SETTLE_MAX_WAIT_MS);
2953
+ timer.unref?.();
2954
+ });
2955
+ try {
2956
+ await Promise.race([settled, cap]);
2957
+ }
2958
+ finally {
2959
+ if (timer)
2960
+ clearTimeout(timer);
2961
+ }
2962
+ if (this.spawning) {
2963
+ this.logger.warn("CLI still starting after the delivery hold — delivering anyway");
2964
+ }
2965
+ }
2229
2966
  /** Spawn a CLI window. Returns true if --resume was used successfully. */
2230
2967
  async spawnClaudeWindow() {
2231
- this.spawning = true;
2968
+ this.beginSpawn();
2232
2969
  let resumedSuccessfully = false;
2233
2970
  try {
2234
2971
  this.toolStatusLines = [];
@@ -2265,7 +3002,7 @@ export class Daemon extends EventEmitter {
2265
3002
  this.backgroundSessionRecoveryAttempted = false;
2266
3003
  }
2267
3004
  finally {
2268
- this.spawning = false;
3005
+ this.endSpawn();
2269
3006
  }
2270
3007
  return resumedSuccessfully;
2271
3008
  }
@@ -2336,11 +3073,13 @@ export class Daemon extends EventEmitter {
2336
3073
  // the global web token) from impersonating instances.
2337
3074
  const agentTokenPath = join(this.instanceDir, "agent.token");
2338
3075
  const agentToken = randomBytes(32).toString("hex");
2339
- writeFileSync(agentTokenPath, agentToken, { mode: 0o600 });
2340
- try {
2341
- chmodSync(agentTokenPath, 0o600);
3076
+ const tokenWrite = writeSecretFile(agentTokenPath, agentToken);
3077
+ if (!tokenWrite.ok) {
3078
+ // Do not fail the spawn over it — an instance that cannot start is worse
3079
+ // than one whose token is readable. But say so, loudly: the whole point of
3080
+ // this token is that other local processes cannot use it.
3081
+ this.logger.error({ path: agentTokenPath, mode: tokenWrite.mode?.toString(8), reason: tokenWrite.reason }, "Agent token file is not owner-only — other local users can impersonate this instance");
2342
3082
  }
2343
- catch { }
2344
3083
  // AGEND_HOME points the child's agent-cli at the same data dir the daemon
2345
3084
  // is using, so it can locate <instanceDir>/agent.token.
2346
3085
  const agendHome = join(this.instanceDir, "..", "..");
@@ -2358,7 +3097,12 @@ export class Daemon extends EventEmitter {
2358
3097
  windowId = this.tmux.getWindowId();
2359
3098
  }
2360
3099
  else {
3100
+ // A crash respawn makes a brand new window. The dead one stays registered
3101
+ // unless we say so — the respawn branch above already does.
3102
+ const retired = this.tmux.getWindowId();
2361
3103
  windowId = await this.tmux.createWindow(cmd, resolvedCwd, this.name);
3104
+ if (retired && retired !== windowId)
3105
+ this.controlClient?.unregisterWindow(retired);
2362
3106
  }
2363
3107
  writeFileSync(join(this.instanceDir, "window-id"), windowId);
2364
3108
  // Enable remain-on-exit to capture exit codes on crash
@@ -2366,7 +3110,9 @@ export class Daemon extends EventEmitter {
2366
3110
  this.logger.warn({ err }, "Failed to set remain-on-exit — exit codes will not be captured");
2367
3111
  });
2368
3112
  if (reuseWindow && !this.config.lightweight) {
2369
- await this.tmux.pipeOutput(join(this.instanceDir, "output.log")).catch(err => {
3113
+ const outputLog = join(this.instanceDir, "output.log");
3114
+ rotateLogIfNeeded(outputLog);
3115
+ await this.tmux.pipeOutput(outputLog).catch(err => {
2370
3116
  this.logger.warn({ err }, "Failed to restore pipe-pane after wake");
2371
3117
  });
2372
3118
  }
@@ -2422,15 +3168,20 @@ export class Daemon extends EventEmitter {
2422
3168
  for (const dialog of startupDialogs) {
2423
3169
  if (dialog.pattern.test(pane)) {
2424
3170
  this.logger.debug(`Dismissing startup dialog: ${dialog.description}`);
2425
- for (const key of dialog.keys) {
2426
- if (key === "Up" || key === "Down" || key === "Enter" || key === "Escape") {
2427
- await this.tmux.sendSpecialKey(key);
3171
+ // Restart is exactly when inbound messages pile up, and nothing gates
3172
+ // delivery on `spawning`. Take the pane lock for the key sequence so a
3173
+ // queued message cannot be pasted into a half-dismissed trust dialog.
3174
+ await this.paneWriteLock.run(async () => {
3175
+ for (const key of dialog.keys) {
3176
+ if (key === "Up" || key === "Down" || key === "Enter" || key === "Escape") {
3177
+ await this.tmux.sendSpecialKey(key);
3178
+ }
3179
+ else {
3180
+ await this.tmux.sendKeys(key);
3181
+ }
3182
+ await new Promise(r => setTimeout(r, 200));
2428
3183
  }
2429
- else {
2430
- await this.tmux.sendKeys(key);
2431
- }
2432
- await new Promise(r => setTimeout(r, 200));
2433
- }
3184
+ });
2434
3185
  // Wait for next screen to render
2435
3186
  if (this.controlClient) {
2436
3187
  const wid = readFileSync(join(this.instanceDir, "window-id"), "utf-8").trim();