@songsid/agend 2.1.2-beta.4 → 2.1.2-beta.40
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.
- package/dist/access-path.js +15 -6
- package/dist/access-path.js.map +1 -1
- package/dist/agent-cli-instructions.md +1 -0
- package/dist/agent-cli.js +14 -0
- package/dist/agent-cli.js.map +1 -1
- package/dist/agent-endpoint.d.ts +2 -0
- package/dist/agent-endpoint.js +25 -1
- package/dist/agent-endpoint.js.map +1 -1
- package/dist/backend/antigravity.d.ts +20 -0
- package/dist/backend/antigravity.js +51 -4
- package/dist/backend/antigravity.js.map +1 -1
- package/dist/backend/claude-code.d.ts +59 -0
- package/dist/backend/claude-code.js +67 -1
- package/dist/backend/claude-code.js.map +1 -1
- package/dist/backend/codex.d.ts +27 -0
- package/dist/backend/codex.js +93 -0
- package/dist/backend/codex.js.map +1 -1
- package/dist/backend/grok.d.ts +25 -0
- package/dist/backend/grok.js +51 -0
- package/dist/backend/grok.js.map +1 -1
- package/dist/backend/kiro.d.ts +22 -0
- package/dist/backend/kiro.js +79 -1
- package/dist/backend/kiro.js.map +1 -1
- package/dist/backend/types.d.ts +58 -0
- package/dist/backend/types.js +13 -1
- package/dist/backend/types.js.map +1 -1
- package/dist/channel/adapters/discord.d.ts +15 -0
- package/dist/channel/adapters/discord.js +100 -2
- package/dist/channel/adapters/discord.js.map +1 -1
- package/dist/channel/adapters/telegram.d.ts +21 -0
- package/dist/channel/adapters/telegram.js +86 -0
- package/dist/channel/adapters/telegram.js.map +1 -1
- package/dist/channel/ipc-bridge.d.ts +9 -1
- package/dist/channel/ipc-bridge.js +12 -3
- package/dist/channel/ipc-bridge.js.map +1 -1
- package/dist/channel/ipc-timeouts.d.ts +46 -0
- package/dist/channel/ipc-timeouts.js +65 -0
- package/dist/channel/ipc-timeouts.js.map +1 -0
- package/dist/channel/mcp-server.js +30 -14
- package/dist/channel/mcp-server.js.map +1 -1
- package/dist/channel/mcp-tools.js +30 -1
- package/dist/channel/mcp-tools.js.map +1 -1
- package/dist/channel/reconnect-backoff.d.ts +17 -0
- package/dist/channel/reconnect-backoff.js +21 -0
- package/dist/channel/reconnect-backoff.js.map +1 -0
- package/dist/channel/types.d.ts +29 -0
- package/dist/classic-channel-manager.js +1 -5
- package/dist/classic-channel-manager.js.map +1 -1
- package/dist/cli.js +204 -82
- package/dist/cli.js.map +1 -1
- package/dist/completion.d.ts +27 -0
- package/dist/completion.js +121 -0
- package/dist/completion.js.map +1 -0
- package/dist/config-validator.js +21 -0
- package/dist/config-validator.js.map +1 -1
- package/dist/config.js +1 -0
- package/dist/config.js.map +1 -1
- package/dist/cost-guard.d.ts +3 -1
- package/dist/cost-guard.js +3 -1
- package/dist/cost-guard.js.map +1 -1
- package/dist/daemon.d.ts +260 -14
- package/dist/daemon.js +991 -309
- package/dist/daemon.js.map +1 -1
- package/dist/event-log.d.ts +31 -0
- package/dist/event-log.js +96 -0
- package/dist/event-log.js.map +1 -1
- package/dist/fleet-context.d.ts +9 -0
- package/dist/fleet-lock.d.ts +28 -0
- package/dist/fleet-lock.js +130 -0
- package/dist/fleet-lock.js.map +1 -0
- package/dist/fleet-manager.d.ts +315 -2
- package/dist/fleet-manager.js +1410 -108
- package/dist/fleet-manager.js.map +1 -1
- package/dist/general-knowledge/skills/cross-instance-messaging/SKILL.md +22 -0
- package/dist/general-knowledge/skills/model-discovery/SKILL.md +14 -23
- package/dist/general-knowledge/skills/session-management/SKILL.md +15 -34
- package/dist/hang-detector.d.ts +19 -13
- package/dist/hang-detector.js +19 -49
- package/dist/hang-detector.js.map +1 -1
- package/dist/instance-lifecycle.d.ts +44 -3
- package/dist/instance-lifecycle.js +165 -48
- package/dist/instance-lifecycle.js.map +1 -1
- package/dist/instructions.d.ts +5 -0
- package/dist/instructions.js +9 -11
- package/dist/instructions.js.map +1 -1
- package/dist/locale.js +5 -1
- package/dist/locale.js.map +1 -1
- package/dist/logger.js +14 -0
- package/dist/logger.js.map +1 -1
- package/dist/mcp-liveness.d.ts +21 -0
- package/dist/mcp-liveness.js +27 -0
- package/dist/mcp-liveness.js.map +1 -0
- package/dist/outbound-handlers.d.ts +16 -0
- package/dist/outbound-handlers.js +151 -27
- package/dist/outbound-handlers.js.map +1 -1
- package/dist/outbound-schemas.d.ts +11 -3
- package/dist/outbound-schemas.js +16 -2
- package/dist/outbound-schemas.js.map +1 -1
- package/dist/pane-write-lock.d.ts +48 -0
- package/dist/pane-write-lock.js +73 -0
- package/dist/pane-write-lock.js.map +1 -0
- package/dist/process-memory.d.ts +31 -0
- package/dist/process-memory.js +79 -0
- package/dist/process-memory.js.map +1 -0
- package/dist/quickstart.js +17 -16
- package/dist/quickstart.js.map +1 -1
- package/dist/reply-dedup.d.ts +41 -0
- package/dist/reply-dedup.js +0 -0
- package/dist/reply-dedup.js.map +1 -0
- package/dist/scheduler/db.js +3 -0
- package/dist/scheduler/db.js.map +1 -1
- package/dist/sd-notify.d.ts +27 -0
- package/dist/sd-notify.js +33 -1
- package/dist/sd-notify.js.map +1 -1
- package/dist/secret-file.d.ts +33 -0
- package/dist/secret-file.js +36 -0
- package/dist/secret-file.js.map +1 -0
- package/dist/service-installer.d.ts +16 -0
- package/dist/service-installer.js +56 -1
- package/dist/service-installer.js.map +1 -1
- package/dist/setup-wizard.js +9 -7
- package/dist/setup-wizard.js.map +1 -1
- package/dist/tmux-control.d.ts +58 -5
- package/dist/tmux-control.js +102 -14
- package/dist/tmux-control.js.map +1 -1
- package/dist/tmux-manager.d.ts +31 -1
- package/dist/tmux-manager.js +40 -11
- package/dist/tmux-manager.js.map +1 -1
- package/dist/topic-commands.d.ts +49 -9
- package/dist/topic-commands.js +267 -105
- package/dist/topic-commands.js.map +1 -1
- package/dist/tui-glyphs.d.ts +5 -1
- package/dist/tui-glyphs.js +6 -2
- package/dist/tui-glyphs.js.map +1 -1
- package/dist/types.d.ts +12 -2
- package/dist/ui/view.html +123 -2
- package/dist/update-marker.d.ts +15 -0
- package/dist/update-marker.js +69 -0
- package/dist/update-marker.js.map +1 -0
- package/dist/usage/format-rich.d.ts +11 -0
- package/dist/usage/format-rich.js +121 -0
- package/dist/usage/format-rich.js.map +1 -0
- package/dist/usage/provider-alerts.d.ts +33 -0
- package/dist/usage/provider-alerts.js +57 -0
- package/dist/usage/provider-alerts.js.map +1 -0
- package/dist/usage/providers.d.ts +130 -0
- package/dist/usage/providers.js +1063 -0
- package/dist/usage/providers.js.map +1 -0
- package/dist/usage/statusline-usage.d.ts +20 -0
- package/dist/usage/statusline-usage.js +120 -0
- package/dist/usage/statusline-usage.js.map +1 -0
- package/dist/usage/usage-api.d.ts +50 -0
- package/dist/usage/usage-api.js +197 -0
- package/dist/usage/usage-api.js.map +1 -0
- package/dist/view-api.d.ts +3 -0
- package/dist/view-api.js +11 -2
- package/dist/view-api.js.map +1 -1
- package/dist/web-api.js +5 -2
- package/dist/web-api.js.map +1 -1
- package/package.json +4 -1
- package/dist/channel/tool-tracker.d.ts +0 -13
- package/dist/channel/tool-tracker.js +0 -58
- package/dist/channel/tool-tracker.js.map +0 -1
- package/dist/daemon-entry.d.ts +0 -1
- package/dist/daemon-entry.js +0 -30
- 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,
|
|
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.
|
|
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`.
|
|
105
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
|
-
|
|
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 =
|
|
287
|
+
this.lastPaneChangeAt = changeAt;
|
|
130
288
|
}
|
|
131
289
|
this.lastObservedAt = now;
|
|
132
|
-
const ready = this.
|
|
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
|
|
@@ -244,13 +419,13 @@ export class Daemon extends EventEmitter {
|
|
|
244
419
|
topicMode;
|
|
245
420
|
backend;
|
|
246
421
|
controlClient;
|
|
422
|
+
runtimeIdentity;
|
|
247
423
|
logger;
|
|
248
424
|
tmuxSessionName;
|
|
249
425
|
tmux = null;
|
|
250
426
|
ipcServer = null;
|
|
251
427
|
messageBus;
|
|
252
428
|
transcriptMonitor = null;
|
|
253
|
-
toolTracker = null;
|
|
254
429
|
guardian = null;
|
|
255
430
|
adapter = null;
|
|
256
431
|
pendingIpcRequests = new Map();
|
|
@@ -261,6 +436,8 @@ export class Daemon extends EventEmitter {
|
|
|
261
436
|
// Pending ack: react 🫡 on first transcript activity after receiving a message
|
|
262
437
|
pendingAckMessage = null;
|
|
263
438
|
// Tool status tracking for channel adapter
|
|
439
|
+
/** Last activity published to the fleet manager; null when nothing is running. */
|
|
440
|
+
currentActivity = null;
|
|
264
441
|
toolStatusMessageId = null;
|
|
265
442
|
toolStatusLines = [];
|
|
266
443
|
toolStatusDebounce = null;
|
|
@@ -276,9 +453,19 @@ export class Daemon extends EventEmitter {
|
|
|
276
453
|
lastSpawnAt = 0;
|
|
277
454
|
crashTimestamps = [];
|
|
278
455
|
healthCheckPaused = false;
|
|
456
|
+
lastHealthErrorNotifyAt = 0;
|
|
279
457
|
/** CLI pane availability, independent from the daemon process and tri-state. */
|
|
280
458
|
processStatus = "running";
|
|
281
459
|
spawning = false;
|
|
460
|
+
/**
|
|
461
|
+
* Resolves when the in-flight spawn finishes; null when none is running.
|
|
462
|
+
*
|
|
463
|
+
* `spawning` alone can only be polled. Delivery needs to *wait*, and a boolean
|
|
464
|
+
* poll would either busy-loop or race the flag being cleared.
|
|
465
|
+
*/
|
|
466
|
+
spawnSettled = null;
|
|
467
|
+
resolveSpawnSettled = null;
|
|
468
|
+
spawnDepth = 0;
|
|
282
469
|
skipResume = false;
|
|
283
470
|
backgroundSessionRecoveryAttempted = false;
|
|
284
471
|
/** Whether the last spawn started a fresh session (not resumed). */
|
|
@@ -301,10 +488,18 @@ export class Daemon extends EventEmitter {
|
|
|
301
488
|
instanceStateIdleDebounceMs = DEFAULT_STATE_IDLE_DEBOUNCE_MS;
|
|
302
489
|
instanceStateStuckTimeoutMs = DEFAULT_STUCK_TIMEOUT_MS;
|
|
303
490
|
instanceStateReadyPattern = null;
|
|
491
|
+
instanceStateBusyPattern = null;
|
|
304
492
|
instanceStateMonitorActive = false;
|
|
305
493
|
statePollInFlight = false;
|
|
306
494
|
autoPauseController;
|
|
307
495
|
pauseRequested = false;
|
|
496
|
+
/**
|
|
497
|
+
* Sticky "pause as soon as possible" (auth failure). Unlike pauseRequested —
|
|
498
|
+
* which the state monitor clears whenever the pane is not idle — this survives
|
|
499
|
+
* busy/stuck states, because an auth error fires mid-turn and a plain pause()
|
|
500
|
+
* would silently no-op exactly when we most need to stop feeding the CLI.
|
|
501
|
+
*/
|
|
502
|
+
pausePending = false;
|
|
308
503
|
pauseWakeState = "active";
|
|
309
504
|
pauseWakeTransition = null;
|
|
310
505
|
// Model failover: override model on next spawn when rate-limited
|
|
@@ -314,7 +509,13 @@ export class Daemon extends EventEmitter {
|
|
|
314
509
|
recentEvents = [];
|
|
315
510
|
recentToolActivity = [];
|
|
316
511
|
snapshotConsumed = false;
|
|
512
|
+
/** Orders inbound channel messages against each other (queue-depth accounting
|
|
513
|
+
* and ⏳/👀/✅ reactions live here). It does NOT cover the other writers that
|
|
514
|
+
* reach the pane — {@link paneWriteLock} does. */
|
|
317
515
|
pasteLock = Promise.resolve();
|
|
516
|
+
/** Mutual exclusion for *every* write into the pane, whichever subsystem it
|
|
517
|
+
* comes from. See PaneWriteLock for why interleaving is destructive. */
|
|
518
|
+
paneWriteLock = new PaneWriteLock();
|
|
318
519
|
pendingInstructionsUpdate;
|
|
319
520
|
pendingInstructionsNotice = false;
|
|
320
521
|
// Whether the warmup steering-reload notice should be injected after spawn.
|
|
@@ -327,6 +528,10 @@ export class Daemon extends EventEmitter {
|
|
|
327
528
|
firstDeliveryDelay = new FirstDeliveryDelay();
|
|
328
529
|
// PTY error pattern monitoring
|
|
329
530
|
errorMonitorTimer = null;
|
|
531
|
+
/** Same 5-min gate the error monitor uses, so a dead MCP server alerts once. */
|
|
532
|
+
static MCP_DEATH_COOLDOWN_MS = 5 * 60_000;
|
|
533
|
+
lastMcpDeathNotifiedAt = 0;
|
|
534
|
+
mcpDeathNotifiedForPid = null;
|
|
330
535
|
/** Prevent in-flight monitor callbacks from re-arming after a pause. */
|
|
331
536
|
runtimeMonitorsFrozen = false;
|
|
332
537
|
errorWaitingForRecovery = false; // true = error detected, waiting for ready pattern
|
|
@@ -371,7 +576,7 @@ export class Daemon extends EventEmitter {
|
|
|
371
576
|
this.errorRecoveryDeadlineAt = 0;
|
|
372
577
|
this.activeErrorPatternKey = null;
|
|
373
578
|
}
|
|
374
|
-
constructor(name, config, instanceDir, topicMode = false, backend, controlClient, rootLogger) {
|
|
579
|
+
constructor(name, config, instanceDir, topicMode = false, backend, controlClient, rootLogger, runtimeIdentity) {
|
|
375
580
|
super();
|
|
376
581
|
this.name = name;
|
|
377
582
|
this.config = config;
|
|
@@ -379,8 +584,14 @@ export class Daemon extends EventEmitter {
|
|
|
379
584
|
this.topicMode = topicMode;
|
|
380
585
|
this.backend = backend;
|
|
381
586
|
this.controlClient = controlClient;
|
|
587
|
+
this.runtimeIdentity = runtimeIdentity;
|
|
382
588
|
if (!rootLogger)
|
|
383
589
|
throw new Error("Daemon requires a shared root logger");
|
|
590
|
+
this.runtimeIdentity ??= {
|
|
591
|
+
kind: "fleet-topic",
|
|
592
|
+
backend: config.backend ?? backend?.binaryName ?? "unknown",
|
|
593
|
+
model: config.model ?? "default",
|
|
594
|
+
};
|
|
384
595
|
this.logger = rootLogger.child({ instance: name }, { level: config.log_level });
|
|
385
596
|
this.tmuxSessionName = getTmuxSession();
|
|
386
597
|
this.messageBus = new MessageBus();
|
|
@@ -447,9 +658,6 @@ export class Daemon extends EventEmitter {
|
|
|
447
658
|
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
659
|
key = String(msg.fleetRequestId);
|
|
449
660
|
}
|
|
450
|
-
else if (type === "fleet_outbound_response" && msg.requestId != null) {
|
|
451
|
-
key = `fleet_out_${msg.requestId}`;
|
|
452
|
-
}
|
|
453
661
|
if (key && this.pendingIpcRequests.has(key)) {
|
|
454
662
|
const handler = this.pendingIpcRequests.get(key);
|
|
455
663
|
this.pendingIpcRequests.delete(key);
|
|
@@ -600,7 +808,12 @@ export class Daemon extends EventEmitter {
|
|
|
600
808
|
else {
|
|
601
809
|
await new Promise(r => setTimeout(r, 5000));
|
|
602
810
|
}
|
|
603
|
-
|
|
811
|
+
// This path only runs when pasteQueueDepth > 0 — i.e. exactly when a real
|
|
812
|
+
// delivery is already in flight or queued. Without the lock the notice and
|
|
813
|
+
// that delivery race into the same pane.
|
|
814
|
+
await this.paneWriteLock.run(async () => {
|
|
815
|
+
await this.tmux?.pasteText(buildInstructionReloadNotice(this.backend?.binaryName ?? "unknown", this.name, this.instanceDir), this.systemPasteOptions());
|
|
816
|
+
});
|
|
604
817
|
// Record the value the agent has now been told about so the next
|
|
605
818
|
// unchanged restart skips the reload.
|
|
606
819
|
try {
|
|
@@ -612,8 +825,12 @@ export class Daemon extends EventEmitter {
|
|
|
612
825
|
catch { /* non-fatal */ }
|
|
613
826
|
})();
|
|
614
827
|
if (!this.config.lightweight) {
|
|
615
|
-
// 3. Pipe-pane for prompt detection
|
|
828
|
+
// 3. Pipe-pane for prompt detection. Rotate first so a ballooned log from a
|
|
829
|
+
// previous stuck splash (hundreds of MB of ANSI frames) is truncated before
|
|
830
|
+
// we attach — pipe-pane uses `cat >>` on the same inode, so copytruncate
|
|
831
|
+
// keeps the writer attached after size resets.
|
|
616
832
|
const outputLog = join(this.instanceDir, "output.log");
|
|
833
|
+
rotateLogIfNeeded(outputLog);
|
|
617
834
|
await this.tmux.pipeOutput(outputLog).catch(() => { });
|
|
618
835
|
// 4. Transcript monitor
|
|
619
836
|
this.transcriptMonitor = new TranscriptMonitor(this.instanceDir, this.logger);
|
|
@@ -629,27 +846,31 @@ export class Daemon extends EventEmitter {
|
|
|
629
846
|
this.transcriptMonitor.on("tool_use", (name, input) => {
|
|
630
847
|
this.logger.debug({ tool: name }, "Tool use");
|
|
631
848
|
ackIfPending();
|
|
632
|
-
this.hangDetector?.recordActivity();
|
|
633
849
|
this.recordRecentEvent({ type: "tool_use", name, preview: this.summarizeTool(name, input) });
|
|
634
850
|
this.recordRecentToolActivity(this.summarizeTool(name, input));
|
|
851
|
+
this.publishActivity(this.summarizeTool(name, input));
|
|
635
852
|
});
|
|
636
853
|
this.transcriptMonitor.on("tool_result", (name, _output) => {
|
|
637
|
-
this.hangDetector?.recordActivity();
|
|
638
854
|
this.recordRecentEvent({ type: "tool_result", name });
|
|
855
|
+
// The tool finished; whatever comes next has not started yet. Better to
|
|
856
|
+
// show only elapsed time than to leave a stale "Bash: npm test" on screen.
|
|
857
|
+
this.publishActivity(null);
|
|
639
858
|
});
|
|
640
859
|
this.transcriptMonitor.on("assistant_text", (text) => {
|
|
641
860
|
this.logger.debug({ text: text.slice(0, 200) }, "Claude response");
|
|
642
861
|
ackIfPending();
|
|
643
|
-
this.hangDetector?.recordActivity();
|
|
644
862
|
this.recordRecentEvent({ type: "assistant_text", preview: text.slice(0, 100) });
|
|
645
863
|
});
|
|
646
864
|
this.transcriptMonitor.startPolling();
|
|
647
|
-
// HangDetector
|
|
648
|
-
//
|
|
649
|
-
//
|
|
865
|
+
// HangDetector is the notification bridge to the fleet manager; pane state
|
|
866
|
+
// transitions below are the sole source of hang events (see hang-detector.ts).
|
|
867
|
+
// `hang_detector.enabled: false` opts out of the notification entirely.
|
|
868
|
+
// NOTE: `hang_detector.timeout_minutes` is NOT read here — the stuck timeout
|
|
869
|
+
// the pane monitor actually uses is resolved separately below. The two have
|
|
870
|
+
// long been separate; documented rather than silently ignored.
|
|
650
871
|
const hangConfig = this.config.hang_detector;
|
|
651
872
|
if (hangConfig?.enabled !== false) {
|
|
652
|
-
this.hangDetector = new HangDetector(
|
|
873
|
+
this.hangDetector = new HangDetector();
|
|
653
874
|
}
|
|
654
875
|
// 8. Context guardian
|
|
655
876
|
const statusFile = join(this.instanceDir, "statusline.json");
|
|
@@ -657,7 +878,6 @@ export class Daemon extends EventEmitter {
|
|
|
657
878
|
this.guardian.startWatching();
|
|
658
879
|
this.guardian.on("status_update", () => {
|
|
659
880
|
this.saveSessionId();
|
|
660
|
-
this.hangDetector?.recordStatuslineUpdate();
|
|
661
881
|
});
|
|
662
882
|
// Context rotation removed: all CLI backends have built-in auto-compact.
|
|
663
883
|
// Crash recovery (health check + respawn with snapshot) is retained below.
|
|
@@ -677,6 +897,40 @@ export class Daemon extends EventEmitter {
|
|
|
677
897
|
this.startInstanceStateMonitor();
|
|
678
898
|
this.logger.info(`${this.name} ready`);
|
|
679
899
|
}
|
|
900
|
+
/**
|
|
901
|
+
* Detect a CRASHED MCP server and report it once.
|
|
902
|
+
*
|
|
903
|
+
* The MCP server writes its pid to channel.mcp.pid at startup and unlinks it on
|
|
904
|
+
* a clean exit, so "file present + pid dead" specifically means it died without
|
|
905
|
+
* cleaning up (crash / OOM / SIGKILL). A missing file is either "not started
|
|
906
|
+
* yet" or "exited cleanly" — neither is an incident, and an orphan exit implies
|
|
907
|
+
* the CLI itself died, which the crash detector already covers.
|
|
908
|
+
*
|
|
909
|
+
* The daemon deliberately does NOT try to respawn it: MCP is a stdio protocol
|
|
910
|
+
* where the CLI spawns the server and owns its pipes, so a daemon-spawned
|
|
911
|
+
* process would have no client reading it. Only the CLI can restore its own
|
|
912
|
+
* tools — hence notify, and let the operator decide about restarting.
|
|
913
|
+
*/
|
|
914
|
+
checkMcpServerAlive() {
|
|
915
|
+
if (this.isPaused)
|
|
916
|
+
return;
|
|
917
|
+
const status = mcpServerState(this.instanceDir);
|
|
918
|
+
if (status.state === "unknown")
|
|
919
|
+
return;
|
|
920
|
+
if (status.state === "alive") {
|
|
921
|
+
this.mcpDeathNotifiedForPid = null; // the CLI respawned it — re-arm
|
|
922
|
+
return;
|
|
923
|
+
}
|
|
924
|
+
// Dead: report once per pid, and at most once per cooldown window.
|
|
925
|
+
if (this.mcpDeathNotifiedForPid === status.pid)
|
|
926
|
+
return;
|
|
927
|
+
if (Date.now() - this.lastMcpDeathNotifiedAt < Daemon.MCP_DEATH_COOLDOWN_MS)
|
|
928
|
+
return;
|
|
929
|
+
this.mcpDeathNotifiedForPid = status.pid;
|
|
930
|
+
this.lastMcpDeathNotifiedAt = Date.now();
|
|
931
|
+
this.logger.error({ pid: status.pid }, "MCP server process is gone — instance has no agend tools");
|
|
932
|
+
this.emit("mcp_died", { name: this.name, pid: status.pid });
|
|
933
|
+
}
|
|
680
934
|
startHealthCheck() {
|
|
681
935
|
if (this.runtimeMonitorsFrozen || this.healthCheckTimer)
|
|
682
936
|
return;
|
|
@@ -692,249 +946,285 @@ export class Daemon extends EventEmitter {
|
|
|
692
946
|
this.healthCheckTimer = null;
|
|
693
947
|
if (this.runtimeMonitorsFrozen)
|
|
694
948
|
return;
|
|
695
|
-
//
|
|
696
|
-
//
|
|
697
|
-
//
|
|
698
|
-
//
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
if (paneStatus === null) {
|
|
728
|
-
await new Promise(r => setTimeout(r, 1500));
|
|
729
|
-
paneStatus = await this.tmux.getPaneStatus();
|
|
949
|
+
// The whole tick is guarded: an unguarded throw in here (a tmux hiccup,
|
|
950
|
+
// ENOSPC on the crash-history write) became an unhandled rejection, which
|
|
951
|
+
// the CLI turned into stopAll() + exit(1) for the ENTIRE fleet, and it also
|
|
952
|
+
// ended this instance's health loop because scheduleNext() sat after the
|
|
953
|
+
// throwing code. Catch, log, and keep checking.
|
|
954
|
+
try {
|
|
955
|
+
// Instance directory removed externally (e.g. `rm -rf ~/.agend/instances/<name>`).
|
|
956
|
+
// Stop the loop permanently — otherwise every tick triggers a respawn, whose
|
|
957
|
+
// writeRotationSnapshot fails with ENOENT and gets caught as "Failed to respawn",
|
|
958
|
+
// spamming errors every ~30s forever.
|
|
959
|
+
if (!existsSync(this.instanceDir)) {
|
|
960
|
+
this.logger.warn({ instanceDir: this.instanceDir }, "Instance directory missing — stopping health check");
|
|
961
|
+
this.healthCheckPaused = true;
|
|
962
|
+
this.healthCheckTimer = null;
|
|
963
|
+
this.emitSupervisionEnded("instance directory was removed from disk", "Recreate the instance, or delete it from fleet.yaml.");
|
|
964
|
+
return;
|
|
965
|
+
}
|
|
966
|
+
if (!this.tmux || this.spawning || this.healthCheckPaused || Daemon.tmuxServerPaused) {
|
|
967
|
+
scheduleNext();
|
|
968
|
+
return;
|
|
969
|
+
}
|
|
970
|
+
// The CLI owns the MCP server process, so the daemon can only observe it.
|
|
971
|
+
this.checkMcpServerAlive();
|
|
972
|
+
// Human-readable backend label for logs (e.g. "claude", "kiro-cli")
|
|
973
|
+
const cliLabel = this.backend?.binaryName ?? "CLI";
|
|
974
|
+
let paneStatus = await this.tmux.getPaneStatus();
|
|
975
|
+
// Auto-pause intentionally exits the pane process. A health tick that
|
|
976
|
+
// began just before pause must not classify that exit as a crash.
|
|
977
|
+
if (this.isPaused || this.pauseWakeState === "waking") {
|
|
978
|
+
scheduleNext();
|
|
979
|
+
return;
|
|
980
|
+
}
|
|
730
981
|
if (paneStatus?.alive) {
|
|
731
|
-
|
|
982
|
+
// Instance output.log is fed by tmux pipe-pane and was previously never
|
|
983
|
+
// rotated (only fleet.log / daemon.log were). Cap growth every tick.
|
|
984
|
+
if (!this.config.lightweight) {
|
|
985
|
+
rotateLogIfNeeded(join(this.instanceDir, "output.log"));
|
|
986
|
+
}
|
|
732
987
|
scheduleNext();
|
|
733
988
|
return;
|
|
734
989
|
}
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
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
|
-
}
|
|
990
|
+
// A null status is ambiguous: it can be a transient `tmux list-panes`
|
|
991
|
+
// failure (e.g. tmux busy during a fleet-restart storm) rather than a
|
|
992
|
+
// real exit. Re-confirm once after a short delay before treating it as
|
|
993
|
+
// a crash. A non-null {alive:false} is a definite dead pane (real exit)
|
|
994
|
+
// and needs no recheck.
|
|
995
|
+
if (paneStatus === null) {
|
|
996
|
+
await new Promise(r => setTimeout(r, 1500));
|
|
997
|
+
paneStatus = await this.tmux.getPaneStatus();
|
|
998
|
+
if (paneStatus?.alive) {
|
|
999
|
+
this.logger.debug(`[health] ${cliLabel} pane reported gone then alive on recheck — transient query failure, ignoring`);
|
|
774
1000
|
scheduleNext();
|
|
775
1001
|
return;
|
|
776
1002
|
}
|
|
777
|
-
await new Promise(r => setTimeout(r, 2_000)); // let session stabilize
|
|
778
1003
|
}
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
1004
|
+
// paneStatus === null → window gone entirely (e.g. tmux server crash)
|
|
1005
|
+
// paneStatus.alive === false → pane dead, exit code available
|
|
1006
|
+
const exitCode = paneStatus?.exitCode;
|
|
1007
|
+
this.logger.debug({ exitCode }, `[health] pane exited with code: ${exitCode}`);
|
|
1008
|
+
// Normal exit (e.g. user Ctrl+C or /exit) — no crash, no respawn
|
|
1009
|
+
if (paneStatus && exitCode === 0) {
|
|
1010
|
+
this.setProcessStatus("stopped");
|
|
1011
|
+
this.logger.info("CLI exited normally (code 0) — pausing health check");
|
|
1012
|
+
await this.tmux.killWindow();
|
|
1013
|
+
this.healthCheckPaused = true;
|
|
1014
|
+
this.emitSupervisionEnded("the CLI exited normally (code 0)", "Nothing crashed — start it again when you need it.");
|
|
1015
|
+
return;
|
|
1016
|
+
}
|
|
1017
|
+
this.setProcessStatus("crashed");
|
|
1018
|
+
// Distinguish tmux server crash from single window crash.
|
|
1019
|
+
// nullReason records *why* getPaneStatus returned null (for diagnosing
|
|
1020
|
+
// whether this was a real window loss or a transient query failure).
|
|
1021
|
+
let crashType = "window";
|
|
1022
|
+
let nullReason;
|
|
1023
|
+
if (!paneStatus) {
|
|
1024
|
+
const serverAlive = await TmuxManager.sessionExists(this.tmuxSessionName);
|
|
1025
|
+
if (!serverAlive) {
|
|
1026
|
+
crashType = "server";
|
|
1027
|
+
nullReason = "server_gone";
|
|
1028
|
+
this.logger.error(`tmux server died — all ${cliLabel} windows lost`);
|
|
1029
|
+
// Fleet-level circuit breaker: pause all instances on repeated tmux server crashes
|
|
1030
|
+
Daemon.tmuxServerCrashTimestamps.push(Date.now());
|
|
1031
|
+
const cutoff = Date.now() - 5 * 60_000;
|
|
1032
|
+
Daemon.tmuxServerCrashTimestamps = Daemon.tmuxServerCrashTimestamps.filter(t => t > cutoff);
|
|
1033
|
+
if (Daemon.tmuxServerCrashTimestamps.length >= 2 && !Daemon.tmuxServerPaused) {
|
|
1034
|
+
Daemon.tmuxServerPaused = true;
|
|
1035
|
+
this.logger.error("Fleet-level tmux server circuit breaker triggered — pausing all respawns for 30s");
|
|
1036
|
+
this.emit("tmux_server_crash", this.name);
|
|
1037
|
+
if (!Daemon.tmuxServerRecoveryTimer) {
|
|
1038
|
+
Daemon.tmuxServerRecoveryTimer = setTimeout(() => {
|
|
1039
|
+
Daemon.tmuxServerRecoveryTimer = null;
|
|
1040
|
+
Daemon.tmuxServerPaused = false;
|
|
1041
|
+
}, 30_000);
|
|
1042
|
+
}
|
|
1043
|
+
scheduleNext();
|
|
1044
|
+
return;
|
|
1045
|
+
}
|
|
1046
|
+
await new Promise(r => setTimeout(r, 2_000)); // let session stabilize
|
|
787
1047
|
}
|
|
788
|
-
|
|
789
|
-
|
|
1048
|
+
else {
|
|
1049
|
+
// null but server alive: window-level disappearance. Probe whether
|
|
1050
|
+
// the window truly no longer exists vs a transient query glitch.
|
|
1051
|
+
nullReason = "no_window";
|
|
1052
|
+
try {
|
|
1053
|
+
const windows = await TmuxManager.listWindows(this.tmuxSessionName);
|
|
1054
|
+
if (windows.some(w => w.name === this.name))
|
|
1055
|
+
nullReason = "window_present_query_glitch";
|
|
1056
|
+
}
|
|
1057
|
+
catch {
|
|
1058
|
+
nullReason = "query_error";
|
|
1059
|
+
}
|
|
1060
|
+
this.logger.warn({ exitCode, nullReason }, `${cliLabel} window not found (tmux server alive)`);
|
|
790
1061
|
}
|
|
791
|
-
this.logger.warn({ exitCode, nullReason }, `${cliLabel} window not found (tmux server alive)`);
|
|
792
1062
|
}
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
1063
|
+
else {
|
|
1064
|
+
this.logger.warn({ exitCode }, `${cliLabel} process exited`);
|
|
1065
|
+
}
|
|
1066
|
+
// Capture last output before killing. Best-effort even when the pane is
|
|
1067
|
+
// gone (paneStatus null) — gives the crash record something to diagnose
|
|
1068
|
+
// from instead of an empty lastOutput.
|
|
1069
|
+
let lastOutput;
|
|
1070
|
+
try {
|
|
1071
|
+
const raw = await this.tmux.capturePaneWithHistory(50);
|
|
1072
|
+
// Strip ANSI escape codes for readability
|
|
1073
|
+
const cleaned = raw.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, "");
|
|
1074
|
+
lastOutput = cleaned.trimEnd() || undefined;
|
|
1075
|
+
}
|
|
1076
|
+
catch { /* best effort — pane may already be gone */ }
|
|
1077
|
+
// Kill the dead window (remain-on-exit keeps it around) before respawn
|
|
1078
|
+
if (paneStatus) {
|
|
1079
|
+
await this.tmux.killWindow();
|
|
1080
|
+
}
|
|
1081
|
+
// Detect claude-code background session conflict — recover without counting as crash
|
|
1082
|
+
if (lastOutput && (lastOutput.includes("background agent") || lastOutput.includes("Session is currently running"))) {
|
|
1083
|
+
if (!this.backgroundSessionRecoveryAttempted) {
|
|
1084
|
+
this.backgroundSessionRecoveryAttempted = true;
|
|
1085
|
+
this.logger.warn("Detected lingering background agent session — starting fresh (no resume)");
|
|
1086
|
+
const sidFile = join(this.instanceDir, "session-id");
|
|
1087
|
+
try {
|
|
1088
|
+
unlinkSync(sidFile);
|
|
1089
|
+
}
|
|
1090
|
+
catch { }
|
|
1091
|
+
this.skipResume = true;
|
|
1092
|
+
await new Promise(r => setTimeout(r, 2_000));
|
|
1093
|
+
try {
|
|
1094
|
+
await this.spawnClaudeWindow();
|
|
1095
|
+
this.setProcessStatus("running");
|
|
1096
|
+
this.logger.info("Recovered from background session conflict");
|
|
1097
|
+
this.emit("crash_respawn", this.name);
|
|
1098
|
+
}
|
|
1099
|
+
catch (err) {
|
|
1100
|
+
this.logger.error({ err: err.message }, "Recovery from background session conflict failed");
|
|
1101
|
+
}
|
|
1102
|
+
return; // Don't count as crash
|
|
1103
|
+
}
|
|
1104
|
+
// Already attempted recovery — fall through to normal crash handling
|
|
1105
|
+
}
|
|
1106
|
+
// Detect a --continue/--resume failure (no conversation to resume). The
|
|
1107
|
+
// session-id file persists across the crash, so a blind respawn would add
|
|
1108
|
+
// --continue again and crash in the same way → loop. Clear the session id
|
|
1109
|
+
// and skip resume so the next spawn starts fresh. (skipResume also stops
|
|
1110
|
+
// saveSessionId below from resurrecting the id from statusline.json.)
|
|
1111
|
+
if (lastOutput && /no conversation found|no conversation to (continue|resume)|no previous (session|conversation)|--continue/i.test(lastOutput)) {
|
|
1112
|
+
this.logger.warn("Detected --continue/resume failure — clearing session-id; next spawn starts fresh");
|
|
818
1113
|
try {
|
|
819
|
-
unlinkSync(
|
|
1114
|
+
unlinkSync(join(this.instanceDir, "session-id"));
|
|
820
1115
|
}
|
|
821
|
-
catch { }
|
|
1116
|
+
catch { /* may not exist */ }
|
|
822
1117
|
this.skipResume = true;
|
|
823
|
-
|
|
1118
|
+
}
|
|
1119
|
+
// Append to crash history
|
|
1120
|
+
this.appendCrashHistory({ exitCode, lastOutput, crashType, reason: nullReason });
|
|
1121
|
+
if (max_retries <= 0) {
|
|
1122
|
+
this.healthCheckPaused = true;
|
|
1123
|
+
this.logger.warn(`${cliLabel} window died — automatic restart is disabled`);
|
|
1124
|
+
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.");
|
|
1125
|
+
return;
|
|
1126
|
+
}
|
|
1127
|
+
// Detect rapid crash: sliding window — 3+ crashes in 5 minutes
|
|
1128
|
+
this.crashTimestamps.push(Date.now());
|
|
1129
|
+
const crashWindowMs = 5 * 60_000;
|
|
1130
|
+
this.crashTimestamps = this.crashTimestamps.filter(t => t > Date.now() - crashWindowMs);
|
|
1131
|
+
if (this.crashTimestamps.length >= 3) {
|
|
1132
|
+
this.healthCheckPaused = true;
|
|
1133
|
+
this.logger.error({ crashesInWindow: this.crashTimestamps.length }, "3+ crashes in 5 minutes — pausing respawn");
|
|
1134
|
+
// P1: Persist crash state so next process restart skips resume
|
|
824
1135
|
try {
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
1136
|
+
writeFileSync(join(this.instanceDir, "crash-state.json"), JSON.stringify({
|
|
1137
|
+
crashesInWindow: this.crashTimestamps.length,
|
|
1138
|
+
lastCrashAt: Date.now(),
|
|
1139
|
+
resumeDisabled: true,
|
|
1140
|
+
}));
|
|
829
1141
|
}
|
|
830
|
-
catch
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
return; // Don't count as crash
|
|
834
|
-
}
|
|
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"));
|
|
1142
|
+
catch { /* best effort */ }
|
|
1143
|
+
this.emit("crash_loop", this.name);
|
|
1144
|
+
return; // don't schedule next — paused
|
|
846
1145
|
}
|
|
847
|
-
|
|
848
|
-
this.
|
|
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
|
-
}));
|
|
1146
|
+
// Reset crash count if enough time has passed
|
|
1147
|
+
if (reset_after > 0 && Date.now() - this.lastCrashAt > reset_after) {
|
|
1148
|
+
this.crashCount = 0;
|
|
871
1149
|
}
|
|
872
|
-
|
|
873
|
-
this.
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
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");
|
|
1150
|
+
this.crashCount++;
|
|
1151
|
+
this.lastCrashAt = Date.now();
|
|
1152
|
+
if (this.crashCount > max_retries) {
|
|
1153
|
+
this.logger.error({ crashCount: this.crashCount, maxRetries: max_retries }, "Max crash retries exceeded — not respawning");
|
|
1154
|
+
this.healthCheckPaused = true;
|
|
1155
|
+
this.emitSupervisionEnded(`it crashed ${this.crashCount} times, exceeding restart_policy.max_retries (${max_retries})`, "Check the logs for the cause, then restart it.");
|
|
1156
|
+
return; // don't schedule next — given up
|
|
902
1157
|
}
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
1158
|
+
// Calculate backoff delay
|
|
1159
|
+
const delay = backoff === "exponential"
|
|
1160
|
+
? Math.min(1000 * Math.pow(2, this.crashCount - 1), 60_000)
|
|
1161
|
+
: 1000 * this.crashCount;
|
|
1162
|
+
this.logger.warn({ crashCount: this.crashCount, delay }, `${cliLabel} window died — respawning after backoff`);
|
|
1163
|
+
await new Promise(r => setTimeout(r, delay));
|
|
907
1164
|
try {
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
1165
|
+
this.saveSessionId();
|
|
1166
|
+
this.transcriptMonitor?.resetOffset();
|
|
1167
|
+
// Kill orphan MCP server from the crashed CLI session.
|
|
1168
|
+
// MCP server writes its PID to channel.mcp.pid on startup.
|
|
1169
|
+
try {
|
|
1170
|
+
const pidFile = join(this.instanceDir, "channel.mcp.pid");
|
|
1171
|
+
const pid = parseInt(readFileSync(pidFile, "utf-8").trim(), 10);
|
|
1172
|
+
process.kill(pid, "SIGTERM");
|
|
1173
|
+
this.logger.info({ pid }, "Killed orphan MCP server");
|
|
914
1174
|
}
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
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
|
|
1175
|
+
catch { /* no pid file or process already dead */ }
|
|
1176
|
+
// Kill any same-name windows before respawn to prevent orphans.
|
|
1177
|
+
// Wrapped in try-catch: if tmux server is dead, listWindows throws —
|
|
1178
|
+
// must not block spawnClaudeWindow (which calls ensureSession).
|
|
927
1179
|
try {
|
|
928
|
-
|
|
1180
|
+
const windows = await TmuxManager.listWindows(this.tmuxSessionName);
|
|
1181
|
+
for (const w of windows) {
|
|
1182
|
+
if (w.name === this.name) {
|
|
1183
|
+
const tm = new TmuxManager(this.tmuxSessionName, w.id);
|
|
1184
|
+
await tm.killWindow();
|
|
1185
|
+
}
|
|
1186
|
+
}
|
|
929
1187
|
}
|
|
930
|
-
catch { /* may
|
|
1188
|
+
catch { /* tmux server may be dead — ensureSession in trySpawn will recover */ }
|
|
1189
|
+
// Write snapshot before spawn — consumed only if resume fails
|
|
1190
|
+
this.writeRotationSnapshot("crash");
|
|
1191
|
+
// Try --resume first; spawnClaudeWindow falls back to fresh session if resume fails
|
|
1192
|
+
const resumed = await this.spawnClaudeWindow();
|
|
1193
|
+
if (!resumed) {
|
|
1194
|
+
// Resume failed → fresh session → inject snapshot for context
|
|
1195
|
+
await this.injectSnapshotMessage();
|
|
1196
|
+
}
|
|
1197
|
+
else {
|
|
1198
|
+
// Clean up stale snapshot — resume restored full context
|
|
1199
|
+
try {
|
|
1200
|
+
unlinkSync(join(this.instanceDir, "rotation-state.json"));
|
|
1201
|
+
}
|
|
1202
|
+
catch { /* may not exist */ }
|
|
1203
|
+
}
|
|
1204
|
+
this.setProcessStatus("running");
|
|
1205
|
+
this.logger.info({ resumed }, `Respawned ${cliLabel} window after crash`);
|
|
1206
|
+
this.emit("crash_respawn", this.name);
|
|
1207
|
+
}
|
|
1208
|
+
catch (err) {
|
|
1209
|
+
this.logger.error({ err }, `Failed to respawn ${cliLabel} window`);
|
|
931
1210
|
}
|
|
932
|
-
this.setProcessStatus("running");
|
|
933
|
-
this.logger.info({ resumed }, `Respawned ${cliLabel} window after crash`);
|
|
934
|
-
this.emit("crash_respawn", this.name);
|
|
935
1211
|
}
|
|
936
1212
|
catch (err) {
|
|
937
|
-
this.logger.error({ err },
|
|
1213
|
+
this.logger.error({ err }, "Health check tick failed — continuing");
|
|
1214
|
+
// Surface it to the operator, not just the log — a health check that
|
|
1215
|
+
// keeps throwing means this instance is no longer being supervised.
|
|
1216
|
+
// Throttled: the tick repeats every ~30s, so an unnotified persistent
|
|
1217
|
+
// fault would otherwise post twice a minute forever.
|
|
1218
|
+
const now = Date.now();
|
|
1219
|
+
if (now - this.lastHealthErrorNotifyAt > HEALTH_ERROR_NOTIFY_INTERVAL_MS) {
|
|
1220
|
+
this.lastHealthErrorNotifyAt = now;
|
|
1221
|
+
this.emit("health_check_error", {
|
|
1222
|
+
name: this.name,
|
|
1223
|
+
message: err instanceof Error ? err.message : String(err),
|
|
1224
|
+
});
|
|
1225
|
+
}
|
|
1226
|
+
scheduleNext();
|
|
1227
|
+
return;
|
|
938
1228
|
}
|
|
939
1229
|
scheduleNext();
|
|
940
1230
|
}, healthCheckIntervalMs);
|
|
@@ -946,6 +1236,21 @@ export class Daemon extends EventEmitter {
|
|
|
946
1236
|
* A dead remain-on-exit pane still contains the old ready prompt, so allowing
|
|
947
1237
|
* the pane monitor to capture it would re-create a false idle state.
|
|
948
1238
|
*/
|
|
1239
|
+
/**
|
|
1240
|
+
* Announce that this instance is no longer being supervised.
|
|
1241
|
+
*
|
|
1242
|
+
* Four health-check exits set `healthCheckPaused = true` and returned without
|
|
1243
|
+
* telling anyone: a clean CLI exit, `max_retries <= 0`, crash retries exhausted,
|
|
1244
|
+
* and the instance directory being deleted. Only the crash-LOOP case emitted an
|
|
1245
|
+
* event, so a fleet could quietly contain a dead instance that still looked fine
|
|
1246
|
+
* on the dashboard — while messages routed to it queued or failed with a bare ❌.
|
|
1247
|
+
*
|
|
1248
|
+
* `crash_loop` already had this treatment; this is the same bridge for the other
|
|
1249
|
+
* four, carrying a human-readable cause and the operator's next step.
|
|
1250
|
+
*/
|
|
1251
|
+
emitSupervisionEnded(reason, remedy) {
|
|
1252
|
+
this.emit("supervision_ended", { name: this.name, reason, remedy });
|
|
1253
|
+
}
|
|
949
1254
|
setProcessStatus(status) {
|
|
950
1255
|
if (this.processStatus === status)
|
|
951
1256
|
return;
|
|
@@ -991,6 +1296,7 @@ export class Daemon extends EventEmitter {
|
|
|
991
1296
|
if (!this.backend)
|
|
992
1297
|
return; // lightweight mode has no backend
|
|
993
1298
|
const readyPattern = this.backend.getReadyPattern();
|
|
1299
|
+
const busyPattern = this.backend.getBusyPattern?.() ?? null;
|
|
994
1300
|
this.errorMonitorTimer = setInterval(async () => {
|
|
995
1301
|
if (!this.tmux || this.spawning)
|
|
996
1302
|
return;
|
|
@@ -1003,20 +1309,30 @@ export class Daemon extends EventEmitter {
|
|
|
1003
1309
|
for (const dialog of dialogs) {
|
|
1004
1310
|
if (!dialog.pattern.test(pane))
|
|
1005
1311
|
continue;
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1312
|
+
// These keys go straight into the pane. Sent while a message delivery is
|
|
1313
|
+
// mid-transaction, an `Escape` wipes the pasted text and an `Enter`
|
|
1314
|
+
// submits it half-composed — the user sees a message that vanished. Skip
|
|
1315
|
+
// (not queue) when the pane is busy: this poller runs every 5s, and the
|
|
1316
|
+
// dialog will still be on screen next tick.
|
|
1317
|
+
const dismissed = await this.paneWriteLock.tryRun(async () => {
|
|
1318
|
+
this.logger.info(`Auto-dismissing runtime dialog: ${dialog.description}`);
|
|
1319
|
+
const SPECIAL_KEYS = new Set(["Up", "Down", "Enter", "Escape", "Right", "Left"]);
|
|
1320
|
+
for (const key of dialog.keys) {
|
|
1321
|
+
if (SPECIAL_KEYS.has(key)) {
|
|
1322
|
+
await this.tmux.sendSpecialKey(key);
|
|
1323
|
+
}
|
|
1324
|
+
else {
|
|
1325
|
+
await this.tmux.pasteText(key, this.systemPasteOptions());
|
|
1326
|
+
}
|
|
1327
|
+
await new Promise(r => setTimeout(r, 200));
|
|
1014
1328
|
}
|
|
1015
|
-
|
|
1329
|
+
});
|
|
1330
|
+
if (!dismissed) {
|
|
1331
|
+
this.logger.debug({ dialog: dialog.description }, "Dialog dismissal deferred — pane write in flight");
|
|
1016
1332
|
}
|
|
1017
|
-
return; // Dialog
|
|
1333
|
+
return; // Dialog handled (or deliberately deferred): skip error checks this cycle
|
|
1018
1334
|
}
|
|
1019
|
-
this.evaluateErrorPatterns(pane, patterns, readyPattern);
|
|
1335
|
+
this.evaluateErrorPatterns(pane, patterns, readyPattern, Date.now(), busyPattern);
|
|
1020
1336
|
}
|
|
1021
1337
|
catch {
|
|
1022
1338
|
// capturePane can fail if window is transitioning — ignore
|
|
@@ -1024,7 +1340,7 @@ export class Daemon extends EventEmitter {
|
|
|
1024
1340
|
}, 5_000); // Check every 5 seconds (runtime dialogs need fast response)
|
|
1025
1341
|
}
|
|
1026
1342
|
/** Evaluate one pane snapshot. Kept synchronous so state-machine edges are unit-testable. */
|
|
1027
|
-
evaluateErrorPatterns(pane, patterns, readyPattern, now = Date.now()) {
|
|
1343
|
+
evaluateErrorPatterns(pane, patterns, readyPattern, now = Date.now(), busyPattern = null) {
|
|
1028
1344
|
// Count occurrences across the WHOLE pane (not just text after the last
|
|
1029
1345
|
// ready prompt). Clone with `g` so stateful backend regexes cannot leak
|
|
1030
1346
|
// lastIndex between monitor cycles.
|
|
@@ -1032,10 +1348,15 @@ export class Daemon extends EventEmitter {
|
|
|
1032
1348
|
const flags = pattern.flags.includes("g") ? pattern.flags : pattern.flags + "g";
|
|
1033
1349
|
return (pane.match(new RegExp(pattern.source, flags)) || []).length;
|
|
1034
1350
|
};
|
|
1351
|
+
// Same veto as the state machine: a backend whose ready marker is permanently
|
|
1352
|
+
// on screen would otherwise "recover" on the very first tick after the error,
|
|
1353
|
+
// rebaselining the occurrence count while the error is still displayed — one
|
|
1354
|
+
// notification, a false recovery log, then silence.
|
|
1355
|
+
const looksReady = () => !busyPattern?.test(pane) && readyPattern.test(pane);
|
|
1035
1356
|
// State: waiting for recovery. A missing/outdated ready pattern must not
|
|
1036
1357
|
// suppress every future error forever, so the gate has a hard deadline.
|
|
1037
1358
|
if (this.errorWaitingForRecovery) {
|
|
1038
|
-
if (
|
|
1359
|
+
if (looksReady()) {
|
|
1039
1360
|
const downtime = Math.round((now - this.errorDetectedAt) / 1000);
|
|
1040
1361
|
const active = patterns.find(ep => Daemon.errorPatternKey(ep) === this.activeErrorPatternKey);
|
|
1041
1362
|
if (active) {
|
|
@@ -1134,6 +1455,12 @@ export class Daemon extends EventEmitter {
|
|
|
1134
1455
|
* Interrupt the CLI's current generation (cancel button / `/cancel`).
|
|
1135
1456
|
* Direct tmux key event (not a paste) so it registers as the interrupt key.
|
|
1136
1457
|
* kiro-cli interrupts on Ctrl+C; the others (claude-code, codex, …) on Escape.
|
|
1458
|
+
*
|
|
1459
|
+
* Deliberately NOT taken through `paneWriteLock`. Cancel is the user's way out
|
|
1460
|
+
* of a pane that is busy or wedged — queueing it behind the very delivery chain
|
|
1461
|
+
* it exists to unblock would make the button useless exactly when it is needed.
|
|
1462
|
+
* The cost is accepted: an Escape landing between a paste and its Enter discards
|
|
1463
|
+
* that message, which is what the user asked for anyway.
|
|
1137
1464
|
*/
|
|
1138
1465
|
async sendEscape() {
|
|
1139
1466
|
const cancelKey = this.backend?.getCancelKey() ?? "Escape";
|
|
@@ -1171,7 +1498,6 @@ export class Daemon extends EventEmitter {
|
|
|
1171
1498
|
this.toolStatusDebounce = null;
|
|
1172
1499
|
}
|
|
1173
1500
|
this.pendingIpcRequests.clear();
|
|
1174
|
-
this.hangDetector?.stop();
|
|
1175
1501
|
if (this.adapter)
|
|
1176
1502
|
await this.adapter.stop();
|
|
1177
1503
|
// Notify MCP servers of graceful shutdown (prevents reconnect attempts)
|
|
@@ -1198,7 +1524,12 @@ export class Daemon extends EventEmitter {
|
|
|
1198
1524
|
if (!killed)
|
|
1199
1525
|
this.logger.warn("CLI did not exit gracefully within 3s, force killing window");
|
|
1200
1526
|
// Always kill window — remain-on-exit keeps dead panes around after CLI exits
|
|
1527
|
+
const stoppedWindowId = this.tmux.getWindowId();
|
|
1201
1528
|
await this.tmux.killWindow();
|
|
1529
|
+
// The control client is shared across the fleet and outlives this daemon, so
|
|
1530
|
+
// a registration left behind here is re-resolved on every reconnect forever.
|
|
1531
|
+
if (stoppedWindowId)
|
|
1532
|
+
this.controlClient?.unregisterWindow(stoppedWindowId);
|
|
1202
1533
|
const windowIdFile = join(this.instanceDir, "window-id");
|
|
1203
1534
|
try {
|
|
1204
1535
|
unlinkSync(windowIdFile);
|
|
@@ -1241,6 +1572,16 @@ export class Daemon extends EventEmitter {
|
|
|
1241
1572
|
};
|
|
1242
1573
|
}
|
|
1243
1574
|
/** Gracefully stop the CLI while keeping its remain-on-exit tmux window. */
|
|
1575
|
+
/**
|
|
1576
|
+
* Mark the instance to pause as soon as its pane is idle. Used for auth
|
|
1577
|
+
* failures: pause() alone no-ops while the CLI is busy/stuck, which is the
|
|
1578
|
+
* usual state when the error surfaces. Cleared by a successful pause or wake.
|
|
1579
|
+
*/
|
|
1580
|
+
requestPauseWhenIdle() {
|
|
1581
|
+
if (this.pauseWakeState === "paused")
|
|
1582
|
+
return;
|
|
1583
|
+
this.pausePending = true;
|
|
1584
|
+
}
|
|
1244
1585
|
async pause() {
|
|
1245
1586
|
if (this.pauseWakeState === "paused")
|
|
1246
1587
|
return;
|
|
@@ -1310,6 +1651,9 @@ export class Daemon extends EventEmitter {
|
|
|
1310
1651
|
}
|
|
1311
1652
|
/** Respawn the CLI in the preserved window and block until its prompt is ready. */
|
|
1312
1653
|
async wake(timeoutMs = 30_000) {
|
|
1654
|
+
// An explicit wake (e.g. after the user re-logs in) cancels a deferred
|
|
1655
|
+
// auth pause — otherwise the instance would pause again the moment it idles.
|
|
1656
|
+
this.pausePending = false;
|
|
1313
1657
|
if (this.pauseWakeState === "active")
|
|
1314
1658
|
return;
|
|
1315
1659
|
if (this.pauseWakeState === "pausing")
|
|
@@ -1321,7 +1665,7 @@ export class Daemon extends EventEmitter {
|
|
|
1321
1665
|
return;
|
|
1322
1666
|
}
|
|
1323
1667
|
this.pauseWakeState = "waking";
|
|
1324
|
-
this.
|
|
1668
|
+
this.beginSpawn();
|
|
1325
1669
|
const transition = this.autoPauseController.wakeOnDeliver(async () => {
|
|
1326
1670
|
let timeout;
|
|
1327
1671
|
try {
|
|
@@ -1362,7 +1706,7 @@ export class Daemon extends EventEmitter {
|
|
|
1362
1706
|
throw err;
|
|
1363
1707
|
}
|
|
1364
1708
|
finally {
|
|
1365
|
-
this.
|
|
1709
|
+
this.endSpawn();
|
|
1366
1710
|
if (this.pauseWakeTransition === transition)
|
|
1367
1711
|
this.pauseWakeTransition = null;
|
|
1368
1712
|
}
|
|
@@ -1374,6 +1718,10 @@ export class Daemon extends EventEmitter {
|
|
|
1374
1718
|
// observations between enqueue and paste must not clear a newer inbound.
|
|
1375
1719
|
if (snapshot.state === "idle" && previous !== "idle") {
|
|
1376
1720
|
this.pendingWork.recordIdle(snapshot.observedAt);
|
|
1721
|
+
// The turn is over. A transcript can end on a tool_use with no matching
|
|
1722
|
+
// tool_result (interrupted, crashed, cancelled), which would otherwise leave
|
|
1723
|
+
// the last tool pinned to the progress line for the rest of the session.
|
|
1724
|
+
this.publishActivity(null);
|
|
1377
1725
|
}
|
|
1378
1726
|
if (snapshot.state !== previous) {
|
|
1379
1727
|
this.logger.info({
|
|
@@ -1389,6 +1737,12 @@ export class Daemon extends EventEmitter {
|
|
|
1389
1737
|
}
|
|
1390
1738
|
if (snapshot.state !== "idle")
|
|
1391
1739
|
this.pauseRequested = false;
|
|
1740
|
+
// A pause deferred by an auth failure: retry the moment the pane settles.
|
|
1741
|
+
if (this.pausePending && snapshot.state === "idle" && this.pasteQueueDepth === 0) {
|
|
1742
|
+
this.pausePending = false;
|
|
1743
|
+
this.emit("auto_pause_requested", { name: this.name, idleSince: snapshot.stateChangedAt });
|
|
1744
|
+
return;
|
|
1745
|
+
}
|
|
1392
1746
|
if (!this.pauseRequested && this.pasteQueueDepth === 0 && this.autoPauseController.observe(snapshot.state)) {
|
|
1393
1747
|
this.pauseRequested = true;
|
|
1394
1748
|
this.emit("auto_pause_requested", { name: this.name, idleSince: snapshot.stateChangedAt });
|
|
@@ -1455,9 +1809,29 @@ export class Daemon extends EventEmitter {
|
|
|
1455
1809
|
|| (this.instanceStateLastOutputAt > 0 && this.instanceStateLastOutputAt >= captureStartedAt))
|
|
1456
1810
|
return;
|
|
1457
1811
|
const observedChangeAt = expectedOutputAt || captureStartedAt;
|
|
1458
|
-
|
|
1459
|
-
|
|
1812
|
+
// One observation per capture. This used to call observe() twice with the
|
|
1813
|
+
// same pane: the second call always saw an unchanged pane, so the
|
|
1814
|
+
// "content moved → still working" branch could never fire and the state
|
|
1815
|
+
// came down to the busy/ready patterns alone. That is why a single
|
|
1816
|
+
// mismatched spinner frame was enough to report idle mid-turn.
|
|
1817
|
+
const settled = this.instanceStateLastOutputAt === 0
|
|
1818
|
+
|| captureStartedAt - this.instanceStateLastOutputAt >= this.instanceStateIdleDebounceMs;
|
|
1819
|
+
// The two times are genuinely different and both matter: the content
|
|
1820
|
+
// changed when tmux reported output (observedChangeAt), but idle/stuck are
|
|
1821
|
+
// decisions about *now*. The old double-observe expressed that by calling
|
|
1822
|
+
// observe twice, which silently disabled the "content moved" branch.
|
|
1823
|
+
const snapshot = this.instanceStateMachine.observe(pane, Date.now(), {
|
|
1824
|
+
settled,
|
|
1825
|
+
changeAt: observedChangeAt,
|
|
1826
|
+
});
|
|
1460
1827
|
this.applyInstanceStateSnapshot(snapshot, pane);
|
|
1828
|
+
// Backends without a transcript feed can still say what they are doing, if
|
|
1829
|
+
// their TUI names it. Free-riding on a capture that already happened: no
|
|
1830
|
+
// extra tmux call. Cadence is the capture cadence (idle debounce + the 60s
|
|
1831
|
+
// safety sweep), which matches the progress ticker's own 60s interval.
|
|
1832
|
+
if (this.backend?.getPaneActivity) {
|
|
1833
|
+
this.publishActivity(snapshot.state === "idle" ? null : this.backend.getPaneActivity(pane));
|
|
1834
|
+
}
|
|
1461
1835
|
if (snapshot.state === "idle") {
|
|
1462
1836
|
this.clearInstanceStateStuckTimer();
|
|
1463
1837
|
}
|
|
@@ -1512,7 +1886,8 @@ export class Daemon extends EventEmitter {
|
|
|
1512
1886
|
? rawConfig.idle_debounce_ms
|
|
1513
1887
|
: DEFAULT_STATE_IDLE_DEBOUNCE_MS;
|
|
1514
1888
|
this.instanceStateReadyPattern = this.backend.getReadyPattern();
|
|
1515
|
-
this.
|
|
1889
|
+
this.instanceStateBusyPattern = this.backend.getBusyPattern?.() ?? null;
|
|
1890
|
+
this.instanceStateMachine = new PaneStateMachine(this.instanceStateReadyPattern, this.instanceStateStuckTimeoutMs, Date.now(), this.instanceStateBusyPattern);
|
|
1516
1891
|
this.instanceStateLastOutputAt = 0;
|
|
1517
1892
|
this.instanceStateMonitorActive = true;
|
|
1518
1893
|
if (this.controlClient) {
|
|
@@ -1553,6 +1928,12 @@ export class Daemon extends EventEmitter {
|
|
|
1553
1928
|
paneTail: sanitizePaneTail(pane),
|
|
1554
1929
|
readyPattern: readyPattern.toString(),
|
|
1555
1930
|
readyMatched: deterministicReadyPattern.test(pane),
|
|
1931
|
+
// A pane that is stuck *while* the ready marker matches means the busy
|
|
1932
|
+
// pattern is what held it back — worth seeing when tuning either regex.
|
|
1933
|
+
busyPattern: this.instanceStateBusyPattern?.toString(),
|
|
1934
|
+
busyMatched: this.instanceStateBusyPattern
|
|
1935
|
+
? new RegExp(this.instanceStateBusyPattern.source, this.instanceStateBusyPattern.flags.replace(/[gy]/g, "")).test(pane)
|
|
1936
|
+
: undefined,
|
|
1556
1937
|
unchangedForMs: snapshot.unchangedForMs,
|
|
1557
1938
|
pendingWork: this.pendingWork.hasPendingWork(),
|
|
1558
1939
|
};
|
|
@@ -1595,6 +1976,40 @@ export class Daemon extends EventEmitter {
|
|
|
1595
1976
|
return this.messageBus;
|
|
1596
1977
|
}
|
|
1597
1978
|
// ── Tool status tracking ──────────────────────────────────────
|
|
1979
|
+
/**
|
|
1980
|
+
* Tell the fleet manager what this instance is doing right now, for the live
|
|
1981
|
+
* progress line on the cancel button.
|
|
1982
|
+
*
|
|
1983
|
+
* Purely cosmetic — nothing decides anything from it, so it is fine that only
|
|
1984
|
+
* backends with a transcript feed report at all (claude-code today). For the
|
|
1985
|
+
* rest the progress line keeps showing just elapsed time.
|
|
1986
|
+
*
|
|
1987
|
+
* Repeats are dropped: the ticker only edits the channel message when the text
|
|
1988
|
+
* changes, and a stream of identical broadcasts would defeat that.
|
|
1989
|
+
*/
|
|
1990
|
+
publishActivity(activity) {
|
|
1991
|
+
const next = activity && activity.trim() ? activity.trim() : null;
|
|
1992
|
+
if (next === this.currentActivity)
|
|
1993
|
+
return;
|
|
1994
|
+
this.currentActivity = next;
|
|
1995
|
+
this.ipcServer?.broadcast({
|
|
1996
|
+
type: "instance_activity",
|
|
1997
|
+
instanceName: this.name,
|
|
1998
|
+
activity: next,
|
|
1999
|
+
});
|
|
2000
|
+
}
|
|
2001
|
+
/**
|
|
2002
|
+
* Options for every system-initiated paste (startup notice, session snapshot,
|
|
2003
|
+
* runtime-dialog keys).
|
|
2004
|
+
*
|
|
2005
|
+
* One place, so the three call sites cannot drift apart on it. Backends with a
|
|
2006
|
+
* native input queue do not get the retry Enter: on those, a second bare Enter
|
|
2007
|
+
* is not the no-op the retry assumed but a queue mutation — the same reason
|
|
2008
|
+
* `deliverMessage` refuses to probe for busy with one.
|
|
2009
|
+
*/
|
|
2010
|
+
systemPasteOptions() {
|
|
2011
|
+
return { retryEnter: this.backend?.supportsQueuedInput?.() !== true };
|
|
2012
|
+
}
|
|
1598
2013
|
summarizeTool(name, input) {
|
|
1599
2014
|
const inp = input;
|
|
1600
2015
|
if (!inp)
|
|
@@ -1605,8 +2020,9 @@ export class Daemon extends EventEmitter {
|
|
|
1605
2020
|
return `Edit ${inp.file_path ?? ""}`;
|
|
1606
2021
|
if (name === "Write")
|
|
1607
2022
|
return `Write ${inp.file_path ?? ""}`;
|
|
2023
|
+
// Command name only — never the arguments. See shellCommandLabel.
|
|
1608
2024
|
if (name === "Bash")
|
|
1609
|
-
return `$ ${String(inp.command ?? "")
|
|
2025
|
+
return `$ ${shellCommandLabel(String(inp.command ?? ""))}`;
|
|
1610
2026
|
if (name === "Glob")
|
|
1611
2027
|
return `Glob ${inp.pattern ?? ""}`;
|
|
1612
2028
|
if (name === "Grep")
|
|
@@ -1684,7 +2100,6 @@ export class Daemon extends EventEmitter {
|
|
|
1684
2100
|
writeFileSync(join(this.instanceDir, "prev-instructions"), this.pendingInstructionsUpdate);
|
|
1685
2101
|
this.pendingInstructionsUpdate = undefined;
|
|
1686
2102
|
}
|
|
1687
|
-
this.hangDetector?.recordInbound();
|
|
1688
2103
|
this.pendingWork.recordInbound();
|
|
1689
2104
|
// v3: record user messages for rotation snapshot
|
|
1690
2105
|
this.recordRecentUserMessage(content, meta);
|
|
@@ -1707,12 +2122,26 @@ export class Daemon extends EventEmitter {
|
|
|
1707
2122
|
// #77: show the sender's display name for readability, keeping the machine
|
|
1708
2123
|
// instance name in parens so the recipient's send_to_instance target is valid.
|
|
1709
2124
|
const fromLabel = meta.from_display ? `${meta.from_display} (${fromInstance})` : fromInstance;
|
|
1710
|
-
formatted = `[from:${fromLabel}] ${content}
|
|
2125
|
+
formatted = `[from:${fromLabel}] ${content}`;
|
|
2126
|
+
formatted += renderHandoffMetadata(meta);
|
|
2127
|
+
// A delegated task that requires a reply must not read like a chatty FYI —
|
|
2128
|
+
// the "you may stay silent" line is for the latter only.
|
|
2129
|
+
formatted += meta.requires_reply === "true"
|
|
2130
|
+
? "\n(A reply IS required: use report_result with the correlation_id above — or send_to_instance. Not direct text.)"
|
|
2131
|
+
: "\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
2132
|
}
|
|
1712
2133
|
else {
|
|
1713
2134
|
const via = meta.source ? ` via ${meta.source}` : "";
|
|
1714
2135
|
const idTag = meta.user_id ? `, id:${meta.user_id}` : "";
|
|
1715
|
-
formatted = `[user:${user}${via}${idTag}] ${content}
|
|
2136
|
+
formatted = `[user:${user}${via}${idTag}] ${content}`;
|
|
2137
|
+
// Reactions queued since the last real message (#432). One leading line of
|
|
2138
|
+
// context, present only when something is pending — a reaction no longer
|
|
2139
|
+
// costs a turn of its own.
|
|
2140
|
+
if (meta.pending_reactions) {
|
|
2141
|
+
formatted = `[Recent reactions: ${meta.pending_reactions}]\n${formatted}`;
|
|
2142
|
+
}
|
|
2143
|
+
formatted += renderHandoffMetadata(meta);
|
|
2144
|
+
formatted += "\n(Reply using the reply tool — do NOT respond with direct text)";
|
|
1716
2145
|
}
|
|
1717
2146
|
if (meta.reply_to_text) {
|
|
1718
2147
|
formatted += `\n(reply_to: "${meta.reply_to_text}")`;
|
|
@@ -1755,18 +2184,19 @@ export class Daemon extends EventEmitter {
|
|
|
1755
2184
|
}
|
|
1756
2185
|
/**
|
|
1757
2186
|
* Deliver a single message and drive its status reactions:
|
|
1758
|
-
* ⏳ message_queued — CLI busy; queued
|
|
2187
|
+
* ⏳ message_queued — CLI busy; queued locally or by the backend
|
|
1759
2188
|
* 👀 message_delivered — pasted + Enter sent; agent now has it
|
|
1760
|
-
* ✅ message_confirmed —
|
|
2189
|
+
* ✅ message_confirmed — processing observed, or native queue handoff succeeded
|
|
1761
2190
|
* ❌ message_failed — tmux window gone, paste retries exhausted
|
|
1762
2191
|
* Returns true once the message is in the CLI, false only on real delivery failure.
|
|
1763
2192
|
*
|
|
1764
2193
|
* Bug A (silent message loss): paste failures retry with backoff (window recovery)
|
|
1765
2194
|
* and emit `message_failed` if all attempts fail.
|
|
1766
|
-
* Busy handling (UX):
|
|
1767
|
-
*
|
|
1768
|
-
*
|
|
1769
|
-
*
|
|
2195
|
+
* Busy handling (UX): backends without a native input queue show ⏳ and wait for
|
|
2196
|
+
* idle indefinitely (a genuinely hung CLI is the hang detector's job). Backends
|
|
2197
|
+
* that explicitly support queued input receive one complete paste+Enter transaction
|
|
2198
|
+
* immediately and own the application-level queue themselves. The pasteLock remains
|
|
2199
|
+
* serial in both cases so separate PTY writes can never overlap.
|
|
1770
2200
|
*/
|
|
1771
2201
|
async deliverMessage(formatted, status) {
|
|
1772
2202
|
// Sanitize unclosed code fences — they cause CLI to wait for closure on Enter
|
|
@@ -1775,14 +2205,50 @@ export class Daemon extends EventEmitter {
|
|
|
1775
2205
|
// Odd number of fences = unclosed. Remove all code fences from the message.
|
|
1776
2206
|
formatted = formatted.replace(/```/g, "");
|
|
1777
2207
|
}
|
|
2208
|
+
// Before anything reads the window id: a spawn in progress is about to change it.
|
|
2209
|
+
await this.waitForSpawnToSettle();
|
|
1778
2210
|
let windowId = this.getWindowId();
|
|
1779
|
-
|
|
2211
|
+
const supportsQueuedInput = this.backend?.supportsQueuedInput?.() === true;
|
|
2212
|
+
let handingOffToNativeQueue = false;
|
|
2213
|
+
// If the CLI is busy, either hand the complete submission to its native input
|
|
2214
|
+
// queue or wait for idle. Native queue support is an explicit backend capability:
|
|
2215
|
+
// normal Enter input has steering/interrupt semantics in several other CLIs.
|
|
1780
2216
|
if (windowId && this.controlClient && !this.controlClient.isIdle(windowId)) {
|
|
1781
2217
|
if (status)
|
|
1782
2218
|
this.emit("message_queued", status);
|
|
1783
|
-
|
|
1784
|
-
|
|
2219
|
+
if (supportsQueuedInput) {
|
|
2220
|
+
handingOffToNativeQueue = true;
|
|
2221
|
+
this.logger.debug("CLI busy — handing message to backend-native input queue");
|
|
2222
|
+
}
|
|
2223
|
+
else {
|
|
2224
|
+
this.logger.debug("CLI busy — queuing message until idle");
|
|
2225
|
+
const becameIdle = await this.controlClient.waitUntilIdle(windowId);
|
|
2226
|
+
if (!becameIdle) {
|
|
2227
|
+
// The pane never freed up. Report the failure instead of pasting into a
|
|
2228
|
+
// wedged CLI (where the text would sit unsubmitted and the next message
|
|
2229
|
+
// would land on top of it) — and instead of holding the queue silently.
|
|
2230
|
+
this.logger.error("Pane still busy after the idle wait — reporting delivery failure");
|
|
2231
|
+
if (status)
|
|
2232
|
+
this.emit("message_failed", status); // ❌
|
|
2233
|
+
return false;
|
|
2234
|
+
}
|
|
2235
|
+
}
|
|
1785
2236
|
}
|
|
2237
|
+
// Everything above is *waiting*; everything below *writes*. Only the write is
|
|
2238
|
+
// held under the pane lock — holding it across the idle wait (up to 30 min)
|
|
2239
|
+
// would starve the runtime-dialog dismisser, which is often the very thing
|
|
2240
|
+
// that would let the pane go idle again.
|
|
2241
|
+
return this.paneWriteLock.run(() => this.writeMessageToPane(formatted, windowId, handingOffToNativeQueue, status));
|
|
2242
|
+
}
|
|
2243
|
+
/**
|
|
2244
|
+
* The write half of a delivery: paste → Enter → confirm, with retries.
|
|
2245
|
+
*
|
|
2246
|
+
* Always called under {@link paneWriteLock}. Split out from `deliverMessage`
|
|
2247
|
+
* precisely so the lock's scope is visible at the call site rather than being
|
|
2248
|
+
* an invariant maintained by comments.
|
|
2249
|
+
*/
|
|
2250
|
+
async writeMessageToPane(formatted, initialWindowId, handingOffToNativeQueue, status) {
|
|
2251
|
+
let windowId = initialWindowId;
|
|
1786
2252
|
// Bug A: paste with backoff. Transient failures are usually a stale window id
|
|
1787
2253
|
// after a crash/respawn — recover by name and retry (max 3 attempts, 2s apart).
|
|
1788
2254
|
const maxAttempts = 3;
|
|
@@ -1807,9 +2273,56 @@ export class Daemon extends EventEmitter {
|
|
|
1807
2273
|
await this.tmux.sendSpecialKey("Enter");
|
|
1808
2274
|
if (status)
|
|
1809
2275
|
this.emit("message_delivered", status); // 👀
|
|
1810
|
-
//
|
|
1811
|
-
//
|
|
1812
|
-
// the
|
|
2276
|
+
// Busy queue-capable CLIs (codex) may accept paste without an idle→busy
|
|
2277
|
+
// transition. Do NOT probe for busy — a second bare Enter can mutate the
|
|
2278
|
+
// queue. Instead verify the paste actually landed in the pane (TUI redraw
|
|
2279
|
+
// can silently swallow it). Idle submissions keep the swallowed-Enter path.
|
|
2280
|
+
if (handingOffToNativeQueue) {
|
|
2281
|
+
await new Promise(r => setTimeout(r, NATIVE_QUEUE_PASTE_VERIFY_MS));
|
|
2282
|
+
if (await this.nativeQueuePasteVisible(formatted)) {
|
|
2283
|
+
if (status)
|
|
2284
|
+
this.emit("message_confirmed", status); // ✅ native queue accepted
|
|
2285
|
+
return true;
|
|
2286
|
+
}
|
|
2287
|
+
// Silent loss: fall back once to the normal idle-gated path.
|
|
2288
|
+
this.logger.warn("Native-queue paste not visible in pane — retrying via idle-gated delivery");
|
|
2289
|
+
if (windowId && this.controlClient) {
|
|
2290
|
+
await this.controlClient.waitUntilIdle(windowId);
|
|
2291
|
+
}
|
|
2292
|
+
const repasted = await this.tmux.pasteBuffer(formatted);
|
|
2293
|
+
if (!repasted) {
|
|
2294
|
+
this.logger.error("Idle-gated redelivery paste failed after native-queue silent loss");
|
|
2295
|
+
if (status)
|
|
2296
|
+
this.emit("message_failed", status); // ❌
|
|
2297
|
+
return false;
|
|
2298
|
+
}
|
|
2299
|
+
await new Promise(r => setTimeout(r, NORMAL_ENTER_SETTLE_MS));
|
|
2300
|
+
const retryAt = Date.now();
|
|
2301
|
+
await this.tmux.sendSpecialKey("Enter");
|
|
2302
|
+
if (windowId && this.controlClient) {
|
|
2303
|
+
let becameBusy = await this.confirmBusyAfterEnter(windowId, retryAt);
|
|
2304
|
+
if (!becameBusy) {
|
|
2305
|
+
this.logger.warn("No idle→busy after idle-gated redelivery — re-sending Enter once");
|
|
2306
|
+
const retry2At = Date.now();
|
|
2307
|
+
await this.tmux.sendSpecialKey("Enter");
|
|
2308
|
+
becameBusy = await this.confirmBusyAfterEnter(windowId, retry2At);
|
|
2309
|
+
}
|
|
2310
|
+
if (becameBusy) {
|
|
2311
|
+
if (status)
|
|
2312
|
+
this.emit("message_confirmed", status); // ✅
|
|
2313
|
+
return true;
|
|
2314
|
+
}
|
|
2315
|
+
}
|
|
2316
|
+
else if (await this.nativeQueuePasteVisible(formatted)) {
|
|
2317
|
+
if (status)
|
|
2318
|
+
this.emit("message_confirmed", status); // ✅
|
|
2319
|
+
return true;
|
|
2320
|
+
}
|
|
2321
|
+
this.logger.error("Idle-gated redelivery also failed after native-queue silent loss");
|
|
2322
|
+
if (status)
|
|
2323
|
+
this.emit("message_failed", status); // ❌
|
|
2324
|
+
return false;
|
|
2325
|
+
}
|
|
1813
2326
|
if (windowId && this.controlClient) {
|
|
1814
2327
|
let becameBusy = await this.confirmBusyAfterEnter(windowId, enterAt);
|
|
1815
2328
|
if (!becameBusy) {
|
|
@@ -1818,8 +2331,20 @@ export class Daemon extends EventEmitter {
|
|
|
1818
2331
|
await this.tmux.sendSpecialKey("Enter");
|
|
1819
2332
|
becameBusy = await this.confirmBusyAfterEnter(windowId, retryAt);
|
|
1820
2333
|
}
|
|
1821
|
-
if (becameBusy
|
|
1822
|
-
|
|
2334
|
+
if (becameBusy) {
|
|
2335
|
+
if (status)
|
|
2336
|
+
this.emit("message_confirmed", status); // ✅
|
|
2337
|
+
}
|
|
2338
|
+
else {
|
|
2339
|
+
// Both Enters were swallowed: the text is sitting UNSUBMITTED in the
|
|
2340
|
+
// CLI's input box. This used to return true, so the reaction stayed at 👀
|
|
2341
|
+
// forever and the next delivery pasted on top — submitting two messages
|
|
2342
|
+
// as one. Say so instead.
|
|
2343
|
+
this.logger.error("Message pasted but never submitted (no idle→busy after two Enters)");
|
|
2344
|
+
if (status)
|
|
2345
|
+
this.emit("message_failed", status); // ❌
|
|
2346
|
+
return false;
|
|
2347
|
+
}
|
|
1823
2348
|
}
|
|
1824
2349
|
else {
|
|
1825
2350
|
// No control client to observe output: fall back to the legacy double-Enter.
|
|
@@ -1835,8 +2360,36 @@ export class Daemon extends EventEmitter {
|
|
|
1835
2360
|
this.emit("message_failed", status); // ❌
|
|
1836
2361
|
return false;
|
|
1837
2362
|
}
|
|
2363
|
+
/**
|
|
2364
|
+
* True when a busy native-queue paste appears to have landed: Codex shows a
|
|
2365
|
+
* `↳` queue marker, or a distinctive slice of the pasted text is on screen.
|
|
2366
|
+
* Used only to detect silent paste loss — not as a general ready check.
|
|
2367
|
+
*/
|
|
2368
|
+
async nativeQueuePasteVisible(formatted) {
|
|
2369
|
+
if (!this.tmux)
|
|
2370
|
+
return false;
|
|
2371
|
+
try {
|
|
2372
|
+
const pane = await this.tmux.capturePane();
|
|
2373
|
+
if (pane.includes("↳"))
|
|
2374
|
+
return true;
|
|
2375
|
+
for (const line of formatted.split(/\r?\n/)) {
|
|
2376
|
+
const t = line.trim();
|
|
2377
|
+
if (t.length >= 8 && pane.includes(t))
|
|
2378
|
+
return true;
|
|
2379
|
+
}
|
|
2380
|
+
const compact = formatted.replace(/\s+/g, " ").trim();
|
|
2381
|
+
if (compact.length >= 8 && pane.includes(compact.slice(0, Math.min(80, compact.length)))) {
|
|
2382
|
+
return true;
|
|
2383
|
+
}
|
|
2384
|
+
return false;
|
|
2385
|
+
}
|
|
2386
|
+
catch {
|
|
2387
|
+
return false;
|
|
2388
|
+
}
|
|
2389
|
+
}
|
|
1838
2390
|
/** Re-resolve this instance's tmux window by name (stale id after crash/respawn). */
|
|
1839
2391
|
async recoverWindow() {
|
|
2392
|
+
const previousWindowId = this.tmux?.getWindowId();
|
|
1840
2393
|
try {
|
|
1841
2394
|
const windows = await TmuxManager.listWindows(this.tmuxSessionName);
|
|
1842
2395
|
const match = windows.find(w => w.name === this.name);
|
|
@@ -1844,6 +2397,12 @@ export class Daemon extends EventEmitter {
|
|
|
1844
2397
|
return undefined;
|
|
1845
2398
|
this.tmux = new TmuxManager(this.tmuxSessionName, match.id, resolveTmuxLogicalSize(this.config.terminal));
|
|
1846
2399
|
writeFileSync(join(this.instanceDir, "window-id"), match.id);
|
|
2400
|
+
// The window we were talking to is gone; leaving it registered means the
|
|
2401
|
+
// control client re-resolves a dead id — one tmux subprocess — on every
|
|
2402
|
+
// reconnect, for the life of the fleet process.
|
|
2403
|
+
if (previousWindowId && previousWindowId !== match.id) {
|
|
2404
|
+
this.controlClient?.unregisterWindow(previousWindowId);
|
|
2405
|
+
}
|
|
1847
2406
|
await this.controlClient?.registerWindow(match.id);
|
|
1848
2407
|
this.bindInstanceStateOutputListener(match.id);
|
|
1849
2408
|
this.logger.info({ windowId: match.id }, "Recovered window ID for message delivery");
|
|
@@ -1854,12 +2413,38 @@ export class Daemon extends EventEmitter {
|
|
|
1854
2413
|
return undefined;
|
|
1855
2414
|
}
|
|
1856
2415
|
}
|
|
1857
|
-
/**
|
|
2416
|
+
/**
|
|
2417
|
+
* Poll up to ~2s (200ms × 10) for the pane to emit output after `since`.
|
|
2418
|
+
*
|
|
2419
|
+
* A `false` here is not "no output" — it is read as **"the message was pasted but
|
|
2420
|
+
* never submitted"**, which re-sends Enter and then reports ❌ to the user. So a
|
|
2421
|
+
* false negative costs a possible double submit and a failure notice for a
|
|
2422
|
+
* message that actually arrived.
|
|
2423
|
+
*
|
|
2424
|
+
* That is exactly what a control-mode reconnect used to produce. `connect()`
|
|
2425
|
+
* drops every output timestamp, so `hasOutputSince` answers `false` for a pane
|
|
2426
|
+
* that did react — the evidence was thrown away, not absent. Blind time is
|
|
2427
|
+
* therefore not counted against the budget: after a reset the poll restarts from
|
|
2428
|
+
* the moment observation resumed. A hard wall-clock cap keeps a reconnect loop
|
|
2429
|
+
* from extending this forever.
|
|
2430
|
+
*/
|
|
1858
2431
|
async confirmBusyAfterEnter(windowId, since) {
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
2432
|
+
const client = this.controlClient;
|
|
2433
|
+
const hardDeadline = Date.now() + CONFIRM_BUSY_MAX_WAIT_MS;
|
|
2434
|
+
let observedFrom = since;
|
|
2435
|
+
let polls = 0;
|
|
2436
|
+
while (polls < CONFIRM_BUSY_POLLS) {
|
|
2437
|
+
await new Promise(r => setTimeout(r, CONFIRM_BUSY_POLL_MS));
|
|
2438
|
+
if (client.hasOutputSince(windowId, observedFrom))
|
|
1862
2439
|
return true;
|
|
2440
|
+
const resetAt = client.getObservationResetAt();
|
|
2441
|
+
if (resetAt > observedFrom && Date.now() < hardDeadline) {
|
|
2442
|
+
this.logger.debug({ windowId, resetAt }, "Control mode reconnected mid-confirmation — restarting the Enter check from when we could see again");
|
|
2443
|
+
observedFrom = resetAt;
|
|
2444
|
+
polls = 0;
|
|
2445
|
+
continue;
|
|
2446
|
+
}
|
|
2447
|
+
polls++;
|
|
1863
2448
|
}
|
|
1864
2449
|
return false;
|
|
1865
2450
|
}
|
|
@@ -1930,8 +2515,8 @@ export class Daemon extends EventEmitter {
|
|
|
1930
2515
|
});
|
|
1931
2516
|
const timeout = setTimeout(() => {
|
|
1932
2517
|
this.pendingIpcRequests.delete(fleetReqId);
|
|
1933
|
-
respond(null,
|
|
1934
|
-
},
|
|
2518
|
+
respond(null, `Task operation timed out after ${daemonBudgetMs(tool) / 1000}s`);
|
|
2519
|
+
}, daemonBudgetMs(tool));
|
|
1935
2520
|
this.pendingIpcRequests.set(fleetReqId, (respMsg) => {
|
|
1936
2521
|
clearTimeout(timeout);
|
|
1937
2522
|
respond(respMsg.result, respMsg.error);
|
|
@@ -1953,8 +2538,8 @@ export class Daemon extends EventEmitter {
|
|
|
1953
2538
|
});
|
|
1954
2539
|
const timeout = setTimeout(() => {
|
|
1955
2540
|
this.pendingIpcRequests.delete(fleetReqId);
|
|
1956
|
-
respond(null,
|
|
1957
|
-
},
|
|
2541
|
+
respond(null, `Decision operation timed out after ${daemonBudgetMs(tool) / 1000}s`);
|
|
2542
|
+
}, daemonBudgetMs(tool));
|
|
1958
2543
|
this.pendingIpcRequests.set(fleetReqId, (respMsg) => {
|
|
1959
2544
|
clearTimeout(timeout);
|
|
1960
2545
|
respond(respMsg.result, respMsg.error);
|
|
@@ -1980,8 +2565,8 @@ export class Daemon extends EventEmitter {
|
|
|
1980
2565
|
// Wait for fleet_schedule_response via pending request map
|
|
1981
2566
|
const timeout = setTimeout(() => {
|
|
1982
2567
|
this.pendingIpcRequests.delete(fleetReqId);
|
|
1983
|
-
respond(null,
|
|
1984
|
-
},
|
|
2568
|
+
respond(null, `Schedule operation timed out after ${daemonBudgetMs(tool) / 1000}s`);
|
|
2569
|
+
}, daemonBudgetMs(tool));
|
|
1985
2570
|
this.pendingIpcRequests.set(fleetReqId, (respMsg) => {
|
|
1986
2571
|
clearTimeout(timeout);
|
|
1987
2572
|
respond(respMsg.result, respMsg.error);
|
|
@@ -2002,7 +2587,9 @@ export class Daemon extends EventEmitter {
|
|
|
2002
2587
|
fleetRequestId: fleetReqId,
|
|
2003
2588
|
senderSessionName,
|
|
2004
2589
|
});
|
|
2005
|
-
|
|
2590
|
+
// Shared table, so delete_instance and the deployment tools get the same
|
|
2591
|
+
// budget here as the MCP client expects (the ad-hoc list omitted them).
|
|
2592
|
+
const crossTimeoutMs = daemonBudgetMs(tool);
|
|
2006
2593
|
const timeout = setTimeout(() => {
|
|
2007
2594
|
this.pendingIpcRequests.delete(fleetReqId);
|
|
2008
2595
|
respond(null, `Cross-instance operation timed out after ${crossTimeoutMs / 1000}s`);
|
|
@@ -2045,8 +2632,8 @@ export class Daemon extends EventEmitter {
|
|
|
2045
2632
|
this.ipcServer?.broadcast({ type: "fleet_outbound", tool, args, fleetRequestId: fleetReqId });
|
|
2046
2633
|
const timeout = setTimeout(() => {
|
|
2047
2634
|
this.pendingIpcRequests.delete(outboundKey);
|
|
2048
|
-
respond(null,
|
|
2049
|
-
},
|
|
2635
|
+
respond(null, `Fleet outbound timed out after ${daemonBudgetMs(tool) / 1000}s`);
|
|
2636
|
+
}, daemonBudgetMs(tool));
|
|
2050
2637
|
this.pendingIpcRequests.set(outboundKey, (respMsg) => {
|
|
2051
2638
|
clearTimeout(timeout);
|
|
2052
2639
|
respond(respMsg.result, respMsg.error);
|
|
@@ -2110,7 +2697,14 @@ export class Daemon extends EventEmitter {
|
|
|
2110
2697
|
try {
|
|
2111
2698
|
const all = JSON.parse(process.env.AGEND_DECISIONS);
|
|
2112
2699
|
const workDir = this.config.working_directory;
|
|
2113
|
-
|
|
2700
|
+
// `scope: "fleet"` used to bypass the project check entirely, so a
|
|
2701
|
+
// single-project worker inherited every other project's playbook (8 of
|
|
2702
|
+
// 14 injected here were foreign) — resent on every API call. Now a
|
|
2703
|
+
// fleet decision must also be RELEVANT: global (no project_root), the
|
|
2704
|
+
// same project, or the same project family (worktrees/checkouts of one
|
|
2705
|
+
// repo). A general is exempt: it dispatches across all projects, so
|
|
2706
|
+
// cross-project routing rules are exactly what it needs.
|
|
2707
|
+
decisions = selectRelevantDecisions(all, workDir, this.config.general_topic === true);
|
|
2114
2708
|
// Stable ordering so identical decision sets always build byte-identical
|
|
2115
2709
|
// instructions — otherwise source ordering jitter flips the warmup hash.
|
|
2116
2710
|
decisions.sort((a, b) => a.title.localeCompare(b.title));
|
|
@@ -2124,9 +2718,18 @@ export class Daemon extends EventEmitter {
|
|
|
2124
2718
|
AGEND_SOCKET_PATH: sockPath,
|
|
2125
2719
|
AGEND_INSTANCE_NAME: this.name,
|
|
2126
2720
|
AGEND_WORKING_DIR: this.config.working_directory,
|
|
2721
|
+
AGEND_INSTANCE_KIND: this.runtimeIdentity?.kind ?? "fleet-topic",
|
|
2722
|
+
AGEND_BACKEND: this.runtimeIdentity?.backend ?? this.config.backend ?? this.backend?.binaryName ?? "unknown",
|
|
2723
|
+
AGEND_MODEL: this.runtimeIdentity?.model ?? this.config.model ?? "default",
|
|
2127
2724
|
};
|
|
2128
|
-
|
|
2129
|
-
|
|
2725
|
+
// A general is a dispatcher, not a worker: default it to the `general` tool
|
|
2726
|
+
// profile instead of `full`. Every tool's schema is resent on every API call,
|
|
2727
|
+
// so full (44 tools) costs a general ~22k chars per turn — the single largest
|
|
2728
|
+
// slice of its prompt. Explicit config still wins.
|
|
2729
|
+
const defaultToolSet = this.config.general_topic ? "general" : undefined;
|
|
2730
|
+
const toolSet = this.config.tool_set ?? defaultToolSet;
|
|
2731
|
+
if (toolSet)
|
|
2732
|
+
mcpEnv.AGEND_TOOL_SET = toolSet;
|
|
2130
2733
|
if (this.config.display_name)
|
|
2131
2734
|
mcpEnv.AGEND_DISPLAY_NAME = this.config.display_name;
|
|
2132
2735
|
if (this.config.description)
|
|
@@ -2159,6 +2762,7 @@ export class Daemon extends EventEmitter {
|
|
|
2159
2762
|
instructions = buildFleetInstructions({
|
|
2160
2763
|
instanceName: this.name,
|
|
2161
2764
|
workingDirectory: this.config.working_directory,
|
|
2765
|
+
runtimeIdentity: this.runtimeIdentity,
|
|
2162
2766
|
displayName: this.config.display_name,
|
|
2163
2767
|
description: this.config.description,
|
|
2164
2768
|
customPrompt: resolvedCustomPrompt,
|
|
@@ -2171,6 +2775,7 @@ export class Daemon extends EventEmitter {
|
|
|
2171
2775
|
instructions = buildFleetInstructions({
|
|
2172
2776
|
instanceName: this.name,
|
|
2173
2777
|
workingDirectory: this.config.working_directory,
|
|
2778
|
+
runtimeIdentity: this.runtimeIdentity,
|
|
2174
2779
|
displayName: this.config.display_name,
|
|
2175
2780
|
description: this.config.description,
|
|
2176
2781
|
customPrompt: resolvedCustomPrompt,
|
|
@@ -2192,6 +2797,7 @@ export class Daemon extends EventEmitter {
|
|
|
2192
2797
|
},
|
|
2193
2798
|
skipPermissions: this.config.skipPermissions,
|
|
2194
2799
|
model: this.modelOverride ?? this.config.model,
|
|
2800
|
+
effort: this.config.effort,
|
|
2195
2801
|
kiroUi: this.config.kiro_ui,
|
|
2196
2802
|
skipResume: this.skipResume,
|
|
2197
2803
|
instructions,
|
|
@@ -2217,7 +2823,9 @@ export class Daemon extends EventEmitter {
|
|
|
2217
2823
|
// Small delay to let the CLI fully render its ready prompt
|
|
2218
2824
|
await new Promise(r => setTimeout(r, 1_000));
|
|
2219
2825
|
try {
|
|
2220
|
-
|
|
2826
|
+
// Messages can arrive during a restart and be queued on pasteLock before the
|
|
2827
|
+
// snapshot lands; both write to the pane, so both go through the same lock.
|
|
2828
|
+
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
2829
|
this.logger.info("Injected session snapshot as first message");
|
|
2222
2830
|
this.emit("snapshot_injected", this.name);
|
|
2223
2831
|
}
|
|
@@ -2226,9 +2834,69 @@ export class Daemon extends EventEmitter {
|
|
|
2226
2834
|
this.emit("snapshot_failed", this.name);
|
|
2227
2835
|
}
|
|
2228
2836
|
}
|
|
2837
|
+
/**
|
|
2838
|
+
* Depth, not a flag: the wake path marks a spawn and then calls trySpawn, which
|
|
2839
|
+
* marks another. With a plain boolean the inner one's completion would clear the
|
|
2840
|
+
* latch while the outer spawn was still dismissing dialogs, releasing delivery
|
|
2841
|
+
* into exactly the window this exists to close.
|
|
2842
|
+
*/
|
|
2843
|
+
beginSpawn() {
|
|
2844
|
+
this.spawnDepth++;
|
|
2845
|
+
this.spawning = true;
|
|
2846
|
+
if (!this.spawnSettled) {
|
|
2847
|
+
this.spawnSettled = new Promise(resolve => { this.resolveSpawnSettled = resolve; });
|
|
2848
|
+
}
|
|
2849
|
+
}
|
|
2850
|
+
endSpawn() {
|
|
2851
|
+
this.spawnDepth = Math.max(0, this.spawnDepth - 1);
|
|
2852
|
+
if (this.spawnDepth > 0)
|
|
2853
|
+
return; // an enclosing spawn is still running
|
|
2854
|
+
this.spawning = false;
|
|
2855
|
+
const resolve = this.resolveSpawnSettled;
|
|
2856
|
+
this.spawnSettled = null;
|
|
2857
|
+
this.resolveSpawnSettled = null;
|
|
2858
|
+
resolve?.();
|
|
2859
|
+
}
|
|
2860
|
+
/**
|
|
2861
|
+
* Hold until the CLI has finished starting up.
|
|
2862
|
+
*
|
|
2863
|
+
* Startup is not a quiet period: `dismissDialogsUntilReady` is clicking through
|
|
2864
|
+
* trust prompts and session pickers. A pane showing a modal dialog produces no
|
|
2865
|
+
* output, so `waitUntilIdle` reports it idle and a queued message gets pasted
|
|
2866
|
+
* *into the dialog* — where the text is discarded and the Enter picks a menu
|
|
2867
|
+
* item. The paste and the Enter both "succeed", so this loses the message
|
|
2868
|
+
* without even a ❌.
|
|
2869
|
+
*
|
|
2870
|
+
* The pane write lock (#414) does not cover this: it serialises each key
|
|
2871
|
+
* sequence, but it is released between one dialog and the next.
|
|
2872
|
+
*
|
|
2873
|
+
* Bounded, and called BEFORE the pane lock is taken — waiting on the spawn while
|
|
2874
|
+
* holding the lock the spawn itself needs would deadlock.
|
|
2875
|
+
*/
|
|
2876
|
+
async waitForSpawnToSettle() {
|
|
2877
|
+
const settled = this.spawnSettled;
|
|
2878
|
+
if (!settled)
|
|
2879
|
+
return;
|
|
2880
|
+
this.logger.debug("Holding delivery until the CLI has finished starting up");
|
|
2881
|
+
let timer;
|
|
2882
|
+
const cap = new Promise(resolve => {
|
|
2883
|
+
timer = setTimeout(resolve, SPAWN_SETTLE_MAX_WAIT_MS);
|
|
2884
|
+
timer.unref?.();
|
|
2885
|
+
});
|
|
2886
|
+
try {
|
|
2887
|
+
await Promise.race([settled, cap]);
|
|
2888
|
+
}
|
|
2889
|
+
finally {
|
|
2890
|
+
if (timer)
|
|
2891
|
+
clearTimeout(timer);
|
|
2892
|
+
}
|
|
2893
|
+
if (this.spawning) {
|
|
2894
|
+
this.logger.warn("CLI still starting after the delivery hold — delivering anyway");
|
|
2895
|
+
}
|
|
2896
|
+
}
|
|
2229
2897
|
/** Spawn a CLI window. Returns true if --resume was used successfully. */
|
|
2230
2898
|
async spawnClaudeWindow() {
|
|
2231
|
-
this.
|
|
2899
|
+
this.beginSpawn();
|
|
2232
2900
|
let resumedSuccessfully = false;
|
|
2233
2901
|
try {
|
|
2234
2902
|
this.toolStatusLines = [];
|
|
@@ -2265,7 +2933,7 @@ export class Daemon extends EventEmitter {
|
|
|
2265
2933
|
this.backgroundSessionRecoveryAttempted = false;
|
|
2266
2934
|
}
|
|
2267
2935
|
finally {
|
|
2268
|
-
this.
|
|
2936
|
+
this.endSpawn();
|
|
2269
2937
|
}
|
|
2270
2938
|
return resumedSuccessfully;
|
|
2271
2939
|
}
|
|
@@ -2336,11 +3004,13 @@ export class Daemon extends EventEmitter {
|
|
|
2336
3004
|
// the global web token) from impersonating instances.
|
|
2337
3005
|
const agentTokenPath = join(this.instanceDir, "agent.token");
|
|
2338
3006
|
const agentToken = randomBytes(32).toString("hex");
|
|
2339
|
-
|
|
2340
|
-
|
|
2341
|
-
|
|
3007
|
+
const tokenWrite = writeSecretFile(agentTokenPath, agentToken);
|
|
3008
|
+
if (!tokenWrite.ok) {
|
|
3009
|
+
// Do not fail the spawn over it — an instance that cannot start is worse
|
|
3010
|
+
// than one whose token is readable. But say so, loudly: the whole point of
|
|
3011
|
+
// this token is that other local processes cannot use it.
|
|
3012
|
+
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
3013
|
}
|
|
2343
|
-
catch { }
|
|
2344
3014
|
// AGEND_HOME points the child's agent-cli at the same data dir the daemon
|
|
2345
3015
|
// is using, so it can locate <instanceDir>/agent.token.
|
|
2346
3016
|
const agendHome = join(this.instanceDir, "..", "..");
|
|
@@ -2358,7 +3028,12 @@ export class Daemon extends EventEmitter {
|
|
|
2358
3028
|
windowId = this.tmux.getWindowId();
|
|
2359
3029
|
}
|
|
2360
3030
|
else {
|
|
3031
|
+
// A crash respawn makes a brand new window. The dead one stays registered
|
|
3032
|
+
// unless we say so — the respawn branch above already does.
|
|
3033
|
+
const retired = this.tmux.getWindowId();
|
|
2361
3034
|
windowId = await this.tmux.createWindow(cmd, resolvedCwd, this.name);
|
|
3035
|
+
if (retired && retired !== windowId)
|
|
3036
|
+
this.controlClient?.unregisterWindow(retired);
|
|
2362
3037
|
}
|
|
2363
3038
|
writeFileSync(join(this.instanceDir, "window-id"), windowId);
|
|
2364
3039
|
// Enable remain-on-exit to capture exit codes on crash
|
|
@@ -2366,7 +3041,9 @@ export class Daemon extends EventEmitter {
|
|
|
2366
3041
|
this.logger.warn({ err }, "Failed to set remain-on-exit — exit codes will not be captured");
|
|
2367
3042
|
});
|
|
2368
3043
|
if (reuseWindow && !this.config.lightweight) {
|
|
2369
|
-
|
|
3044
|
+
const outputLog = join(this.instanceDir, "output.log");
|
|
3045
|
+
rotateLogIfNeeded(outputLog);
|
|
3046
|
+
await this.tmux.pipeOutput(outputLog).catch(err => {
|
|
2370
3047
|
this.logger.warn({ err }, "Failed to restore pipe-pane after wake");
|
|
2371
3048
|
});
|
|
2372
3049
|
}
|
|
@@ -2422,15 +3099,20 @@ export class Daemon extends EventEmitter {
|
|
|
2422
3099
|
for (const dialog of startupDialogs) {
|
|
2423
3100
|
if (dialog.pattern.test(pane)) {
|
|
2424
3101
|
this.logger.debug(`Dismissing startup dialog: ${dialog.description}`);
|
|
2425
|
-
|
|
2426
|
-
|
|
2427
|
-
|
|
3102
|
+
// Restart is exactly when inbound messages pile up, and nothing gates
|
|
3103
|
+
// delivery on `spawning`. Take the pane lock for the key sequence so a
|
|
3104
|
+
// queued message cannot be pasted into a half-dismissed trust dialog.
|
|
3105
|
+
await this.paneWriteLock.run(async () => {
|
|
3106
|
+
for (const key of dialog.keys) {
|
|
3107
|
+
if (key === "Up" || key === "Down" || key === "Enter" || key === "Escape") {
|
|
3108
|
+
await this.tmux.sendSpecialKey(key);
|
|
3109
|
+
}
|
|
3110
|
+
else {
|
|
3111
|
+
await this.tmux.sendKeys(key);
|
|
3112
|
+
}
|
|
3113
|
+
await new Promise(r => setTimeout(r, 200));
|
|
2428
3114
|
}
|
|
2429
|
-
|
|
2430
|
-
await this.tmux.sendKeys(key);
|
|
2431
|
-
}
|
|
2432
|
-
await new Promise(r => setTimeout(r, 200));
|
|
2433
|
-
}
|
|
3115
|
+
});
|
|
2434
3116
|
// Wait for next screen to render
|
|
2435
3117
|
if (this.controlClient) {
|
|
2436
3118
|
const wid = readFileSync(join(this.instanceDir, "window-id"), "utf-8").trim();
|