@songsid/agend 2.1.2-beta.5 → 2.1.2-beta.50
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 +26 -0
- package/dist/backend/codex.js +100 -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 +23 -0
- package/dist/backend/kiro.js +120 -2
- 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 +120 -8
- 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 +242 -91
- 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 +2 -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 +302 -8
- package/dist/daemon.js +1165 -312
- 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 +14 -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 +347 -6
- package/dist/fleet-manager.js +1794 -215
- package/dist/fleet-manager.js.map +1 -1
- package/dist/general-instance.d.ts +9 -0
- package/dist/general-instance.js +11 -0
- package/dist/general-instance.js.map +1 -0
- 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 +60 -3
- package/dist/instance-lifecycle.js +237 -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 +7 -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 +18 -0
- package/dist/outbound-handlers.js +215 -35
- 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/restart-progress.d.ts +34 -0
- package/dist/restart-progress.js +87 -0
- package/dist/restart-progress.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 +28 -0
- package/dist/service-installer.js +72 -1
- package/dist/service-installer.js.map +1 -1
- package/dist/settings-api.js +5 -3
- package/dist/settings-api.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 +279 -110
- 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 +19 -2
- package/dist/ui/settings.html +1 -1
- 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 +7 -3
- package/dist/web-api.js.map +1 -1
- package/dist/web-auth.d.ts +6 -0
- package/dist/web-auth.js +54 -0
- package/dist/web-auth.js.map +1 -0
- 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/fleet-manager.js
CHANGED
|
@@ -4,7 +4,10 @@ import { createServer } from "node:http";
|
|
|
4
4
|
import { join, dirname, basename } from "node:path";
|
|
5
5
|
import { fileURLToPath } from "node:url";
|
|
6
6
|
import { getAgendHome, ensureWorkspaceGit } from "./paths.js";
|
|
7
|
-
import {
|
|
7
|
+
import { clearUpdateMarker, isUpdateInProgress } from "./update-marker.js";
|
|
8
|
+
import { sdNotify, sdNotifyBlocking } from "./sd-notify.js";
|
|
9
|
+
import { readFleetMemory } from "./process-memory.js";
|
|
10
|
+
import { ReplyDeduper } from "./reply-dedup.js";
|
|
8
11
|
import { isScalar, parseDocument } from "yaml";
|
|
9
12
|
const __filename = fileURLToPath(import.meta.url);
|
|
10
13
|
const __dirname = dirname(__filename);
|
|
@@ -21,12 +24,12 @@ import { IpcClient } from "./channel/ipc-bridge.js";
|
|
|
21
24
|
import { createAdapter } from "./channel/factory.js";
|
|
22
25
|
import { createBackend } from "./backend/factory.js";
|
|
23
26
|
import { isModelCompatible } from "./backend/types.js";
|
|
24
|
-
import { createLogger } from "./logger.js";
|
|
27
|
+
import { createLogger, rotateLogIfNeeded } from "./logger.js";
|
|
25
28
|
import { processAttachments } from "./channel/attachment-handler.js";
|
|
26
29
|
import { routeToolCall } from "./channel/tool-router.js";
|
|
27
30
|
import { Scheduler } from "./scheduler/index.js";
|
|
28
31
|
import { DEFAULT_SCHEDULER_CONFIG } from "./scheduler/index.js";
|
|
29
|
-
import { TopicCommands, saveCommandForBackend, parseSaveFilename, parsePauseWakeCommand, SAVE_FILENAME_RE, SAVE_UNSUPPORTED_MSG } from "./topic-commands.js";
|
|
32
|
+
import { TopicCommands, saveCommandForBackend, parseSaveFilename, parsePauseWakeCommand, SAVE_FILENAME_RE, SAVE_UNSUPPORTED_MSG, resolveInstanceContext, forgetInstanceContext } from "./topic-commands.js";
|
|
30
33
|
import { DailySummary } from "./daily-summary.js";
|
|
31
34
|
import { WebhookEmitter } from "./webhook-emitter.js";
|
|
32
35
|
import { TmuxControlClient } from "./tmux-control.js";
|
|
@@ -38,6 +41,7 @@ import { StatuslineWatcher } from "./statusline-watcher.js";
|
|
|
38
41
|
import { outboundHandlers } from "./outbound-handlers.js";
|
|
39
42
|
import { handleWebRequest, broadcastSseEvent } from "./web-api.js";
|
|
40
43
|
import { handleViewRequest, isViewPath } from "./view-api.js";
|
|
44
|
+
import { handleUsageRequest, isUsagePath } from "./usage/usage-api.js";
|
|
41
45
|
import { handleSettingsRequest } from "./settings-api.js";
|
|
42
46
|
import { setLocale, detectLocale, t } from "./locale.js";
|
|
43
47
|
import { handleAgentRequest } from "./agent-endpoint.js";
|
|
@@ -45,6 +49,10 @@ import { ClassicChannelManager, getClassicBackendChoices, isSelectableClassicBac
|
|
|
45
49
|
import { validateFleetConfig } from "./config-validator.js";
|
|
46
50
|
import { readLastInboundAt } from "./daemon.js";
|
|
47
51
|
import { clearPausedMarker } from "./pause-marker.js";
|
|
52
|
+
import { releaseProcessFleetLock } from "./fleet-lock.js";
|
|
53
|
+
import { GENERAL_PAUSE_ERROR, isGeneralInstance } from "./general-instance.js";
|
|
54
|
+
import { loadOrCreateWebToken, WEB_TOKEN_INVALID_MESSAGE } from "./web-auth.js";
|
|
55
|
+
import { RestartProgress } from "./restart-progress.js";
|
|
48
56
|
import { getTmuxSession } from "./config.js";
|
|
49
57
|
export function resolveReplyThreadId(argsThreadId, instanceConfig) {
|
|
50
58
|
if (typeof argsThreadId === "string" && argsThreadId.length > 0) {
|
|
@@ -83,9 +91,80 @@ const CANCEL_BTN_MAX_RETRIES = 3;
|
|
|
83
91
|
* buttons no clear trigger reached (e.g. a scheduled/HTTP turn that never called
|
|
84
92
|
* reply). 5min (not the old 2s idle-watch) so Thinking isn't misread as idle. */
|
|
85
93
|
const CANCEL_BTN_IDLE_CHECK_INTERVAL_MS = 5 * 60_000;
|
|
94
|
+
/**
|
|
95
|
+
* A queued turn can produce a very short idle edge while the CLI hands off to
|
|
96
|
+
* the next message. Do not retire the cancel button until that edge remains
|
|
97
|
+
* idle for this long; a working/stuck report during the grace cancels it.
|
|
98
|
+
*/
|
|
99
|
+
const CANCEL_BTN_IDLE_RETIRE_GRACE_MS = 2_000;
|
|
100
|
+
/**
|
|
101
|
+
* How long after a reply an instance gets to resume working before its cancel
|
|
102
|
+
* button is retired. A short turn ends with a reply and never works again → the
|
|
103
|
+
* button disappears ~2 minutes after the answer. A multi-step run replies
|
|
104
|
+
* mid-flight and keeps going → the grace check sees "working" and leaves the
|
|
105
|
+
* button alone (the idle edge retires it when the run really ends).
|
|
106
|
+
*/
|
|
107
|
+
const REPLY_RETIRE_GRACE_MS = 2 * 60_000;
|
|
108
|
+
/**
|
|
109
|
+
* The daemon only broadcasts execution state on TRANSITIONS, so a long
|
|
110
|
+
* single-state run sends nothing for hours. The idle backstop therefore pokes a
|
|
111
|
+
* query each tick; a live daemon answers within milliseconds and refreshes the
|
|
112
|
+
* cache. When nothing has refreshed it for this long despite those pokes, the
|
|
113
|
+
* reporting chain (daemon, IPC, or state monitor) is dead and a "working" state
|
|
114
|
+
* from 30 minutes ago proves nothing — the button may be retired.
|
|
115
|
+
*/
|
|
116
|
+
const STATE_REPORT_STALE_MS = 30 * 60_000;
|
|
117
|
+
/**
|
|
118
|
+
* Unconditional ceiling on a cancel button's life. Deliberately far beyond any
|
|
119
|
+
* legitimate run (multi-hour tasks are normal on this fleet): everything below
|
|
120
|
+
* this is decided by real state; a button that somehow survives a full day is
|
|
121
|
+
* wreckage, stuck or not.
|
|
122
|
+
*/
|
|
123
|
+
const CANCEL_BTN_MAX_LIFETIME_MS = 24 * 60 * 60_000;
|
|
124
|
+
/** A click on a button the fleet no longer tracks may fire at most this often. */
|
|
125
|
+
const STALE_CANCEL_CLICK_COOLDOWN_MS = 10_000;
|
|
126
|
+
/** Orphaned-button ledger, swept at startup. Lives in the fleet data dir. */
|
|
127
|
+
const CANCEL_BTN_LEDGER_FILE = "cancel-buttons.json";
|
|
128
|
+
/**
|
|
129
|
+
* How often the cancel button's text is refreshed with elapsed working time.
|
|
130
|
+
*
|
|
131
|
+
* One edit per working instance per interval — at 60s that is trivial for both
|
|
132
|
+
* platforms' rate limits, and it reads as a live counter rather than a stale
|
|
133
|
+
* snapshot. Nothing new is posted, so the channel is never spammed: there is
|
|
134
|
+
* exactly one progress message per turn, and it is the cancel button itself.
|
|
135
|
+
*/
|
|
136
|
+
const PROGRESS_UPDATE_INTERVAL_MS = 60_000;
|
|
137
|
+
/** Elapsed time is only shown once work has clearly outlasted a quick answer. */
|
|
138
|
+
/**
|
|
139
|
+
* Default delay before the button starts showing elapsed time. Configurable via
|
|
140
|
+
* `defaults.progress_min_elapsed` (seconds) in fleet.yaml. 30s is the balance
|
|
141
|
+
* point: most quick answers finish inside it (no churn for ordinary turns),
|
|
142
|
+
* while anything real shows signs of life well before the old two minutes.
|
|
143
|
+
*/
|
|
144
|
+
const PROGRESS_MIN_ELAPSED_MS = 30_000;
|
|
145
|
+
/** How much of a tool summary the progress line will show before eliding. */
|
|
146
|
+
const PROGRESS_ACTIVITY_MAX_CHARS = 48;
|
|
147
|
+
/**
|
|
148
|
+
* Emoji AgEnD itself stamps on messages as the delivery-status ladder
|
|
149
|
+
* (⏳ queued, 👀 delivered, ✅ confirmed, ❌ failed). These are machine
|
|
150
|
+
* indicators, not opinions, so they never enter the reactions queue — from
|
|
151
|
+
* anyone. This exact-emoji filter is the ONLY bot filtering left: bot-to-bot
|
|
152
|
+
* reactions are otherwise delivered on purpose (agents signal each other), and
|
|
153
|
+
* 🫡 passes too — it reads as a deliberate acknowledgement, not plumbing.
|
|
154
|
+
*/
|
|
155
|
+
const DELIVERY_STATUS_EMOJIS = new Set(["👀", "⏳", "✅", "❌"]);
|
|
156
|
+
/**
|
|
157
|
+
* How long a delivery waits out a disconnected instance IPC before giving up.
|
|
158
|
+
*
|
|
159
|
+
* Sized for a daemon restart (socket close → respawn → CLI ready), which is the
|
|
160
|
+
* event this exists for. Past it the delivery fails loudly as it always did.
|
|
161
|
+
*/
|
|
162
|
+
const IPC_RECONNECT_GRACE_MS = 30_000;
|
|
163
|
+
const IPC_RECONNECT_POLL_MS = 250;
|
|
86
164
|
const CLASSIC_BACKEND_SELECTION_TIMEOUT_MS = 60_000;
|
|
87
165
|
const CLASSIC_BACKEND_CALLBACK_PREFIX = "classic-backend:";
|
|
88
166
|
const MODEL_SELECT_CALLBACK_PREFIX = "model-select:";
|
|
167
|
+
const EFFORT_SELECT_CALLBACK_PREFIX = "effort-select:";
|
|
89
168
|
const CLI_ENV_TTL_MS = 24 * 60 * 60 * 1000; // /model reads cached CLI env within 24h
|
|
90
169
|
export class FleetManager {
|
|
91
170
|
dataDir;
|
|
@@ -93,7 +172,7 @@ export class FleetManager {
|
|
|
93
172
|
static sighupHandlerInstalled = false;
|
|
94
173
|
children = new Map();
|
|
95
174
|
lifecycle;
|
|
96
|
-
/**
|
|
175
|
+
/** Live view of lifecycle.daemons — used throughout; not deprecated. */
|
|
97
176
|
get daemons() { return this.lifecycle.daemons; }
|
|
98
177
|
fleetConfig = null;
|
|
99
178
|
rawFleetConfig = {};
|
|
@@ -108,8 +187,11 @@ export class FleetManager {
|
|
|
108
187
|
// same guild both receive every message). Bounded FIFO of recent message keys.
|
|
109
188
|
recentMessageIds = new Set();
|
|
110
189
|
accessManager = null;
|
|
111
|
-
/** Primary world (
|
|
112
|
-
get primaryWorld() {
|
|
190
|
+
/** Primary world (channels[0]), independent of concurrent adapter startup order. */
|
|
191
|
+
get primaryWorld() {
|
|
192
|
+
const adapterId = this.getPrimaryAdapterId();
|
|
193
|
+
return adapterId ? this.worlds.get(adapterId) : undefined;
|
|
194
|
+
}
|
|
113
195
|
routing = new RoutingEngine();
|
|
114
196
|
get routingTable() { return this.routing.map; }
|
|
115
197
|
instanceIpcClients = new Map();
|
|
@@ -151,6 +233,16 @@ export class FleetManager {
|
|
|
151
233
|
// reply, on cancel, or when a newer button supersedes it for the same
|
|
152
234
|
// instance. Per-button tracking means a failed delete never strands a button.
|
|
153
235
|
cancelButtons = new Map();
|
|
236
|
+
/** Pending idle-edge retirement, one timer per instance. */
|
|
237
|
+
cancelButtonIdleRetireTimers = new Map();
|
|
238
|
+
/** Duplicate-reply suppression across both the MCP and HTTP reply paths. */
|
|
239
|
+
replyDeduper = new ReplyDeduper();
|
|
240
|
+
/** instanceName → what it is doing right now, when the backend can tell us. */
|
|
241
|
+
instanceActivity = new Map();
|
|
242
|
+
/** instanceName → tail of deliveries waiting for its IPC to come back. */
|
|
243
|
+
ipcWaitTails = new Map();
|
|
244
|
+
/** instanceName → restart currently executing; concurrent callers join it. */
|
|
245
|
+
restartsInFlight = new Map();
|
|
154
246
|
// Last user message delivered to each instance — used to react ✅ on completion.
|
|
155
247
|
lastInboundMsg = new Map();
|
|
156
248
|
topicArchiver;
|
|
@@ -158,11 +250,17 @@ export class FleetManager {
|
|
|
158
250
|
classicChannels = null;
|
|
159
251
|
pendingClassicStarts = new Map();
|
|
160
252
|
/** In-flight /model selections, keyed by nonce (see handleModelSelection). */
|
|
253
|
+
/** In-flight /effort selections, same coordinator shape as pendingModelSelects. */
|
|
254
|
+
pendingEffortSelects = new Map();
|
|
161
255
|
pendingModelSelects = new Map();
|
|
162
256
|
// Model failover state
|
|
163
257
|
failoverActive = new Map(); // instance → current failover model
|
|
164
258
|
// IPC reconnect: tracks instances being intentionally stopped (skip reconnect)
|
|
259
|
+
/** instance → when a click with no live button entry last fired a cancel. */
|
|
260
|
+
staleCancelClickAt = new Map();
|
|
165
261
|
ipcStoppingInstances = new Set();
|
|
262
|
+
/** Set the moment a graceful stop begins — see isPlannedRestart(). */
|
|
263
|
+
shuttingDown = false;
|
|
166
264
|
/** Coalesce concurrent connection attempts for the same daemon socket. */
|
|
167
265
|
ipcConnectInFlight = new Map();
|
|
168
266
|
/** At most one reconnect/backoff loop may exist per instance. */
|
|
@@ -176,6 +274,10 @@ export class FleetManager {
|
|
|
176
274
|
healthServer = null;
|
|
177
275
|
healthPortRetried = false;
|
|
178
276
|
updateCheckTimer = null;
|
|
277
|
+
eventLogPruneTimer = null;
|
|
278
|
+
logRotateTimer = null;
|
|
279
|
+
/** Days of event/activity history to keep. */
|
|
280
|
+
static EVENT_LOG_RETENTION_DAYS = 30;
|
|
179
281
|
watchdogTimer = null;
|
|
180
282
|
startedAt = 0;
|
|
181
283
|
// Mirror topic: buffer cross-instance messages, flush every 3s
|
|
@@ -185,6 +287,7 @@ export class FleetManager {
|
|
|
185
287
|
sseClients = new Set();
|
|
186
288
|
webToken = null;
|
|
187
289
|
viewToken = null;
|
|
290
|
+
healthServerListening = false;
|
|
188
291
|
constructor(dataDir) {
|
|
189
292
|
this.dataDir = dataDir;
|
|
190
293
|
FleetManager.signalTarget = this;
|
|
@@ -214,7 +317,13 @@ export class FleetManager {
|
|
|
214
317
|
}
|
|
215
318
|
this.reloadPending = false;
|
|
216
319
|
this.reconcileInFlight = this.reconcileInstances()
|
|
217
|
-
.catch(err =>
|
|
320
|
+
.catch(err => {
|
|
321
|
+
// Almost always a YAML parse error. Log-only meant the user edited
|
|
322
|
+
// fleet.yaml, sent SIGHUP, and got no reaction and no explanation.
|
|
323
|
+
this.logger.error({ err }, "SIGHUP config reload failed");
|
|
324
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
325
|
+
this.notifyFleetError(`⚠️ fleet.yaml reload FAILED — ${message}\nThe previous configuration is still running.`);
|
|
326
|
+
})
|
|
218
327
|
.finally(() => {
|
|
219
328
|
this.reconcileInFlight = null;
|
|
220
329
|
if (this.reloadPending && this.startupComplete) {
|
|
@@ -222,16 +331,55 @@ export class FleetManager {
|
|
|
222
331
|
}
|
|
223
332
|
});
|
|
224
333
|
}
|
|
334
|
+
/**
|
|
335
|
+
* Is the fleet going down (or coming back up) on purpose?
|
|
336
|
+
*
|
|
337
|
+
* Instances dying during a planned restart is the restart working, not an
|
|
338
|
+
* incident — but the code that notices a dead pane or a dead MCP server
|
|
339
|
+
* cannot tell the difference on its own. Two sources, because the noise
|
|
340
|
+
* starts before this process is even told to stop: `agend update` replaces
|
|
341
|
+
* the package on disk while this daemon is still running and still watching.
|
|
342
|
+
*/
|
|
343
|
+
isPlannedRestart() {
|
|
344
|
+
return this.shuttingDown || isUpdateInProgress(this.dataDir);
|
|
345
|
+
}
|
|
225
346
|
finishStartup() {
|
|
226
347
|
this.startupComplete = true;
|
|
348
|
+
// We are the post-update fleet: the update is over by definition. Clearing
|
|
349
|
+
// it here (rather than in the update command, which exits before the new
|
|
350
|
+
// fleet is up) is what keeps the quiet window from outliving the restart.
|
|
351
|
+
clearUpdateMarker(this.dataDir);
|
|
227
352
|
if (this.reloadPending)
|
|
228
353
|
this.scheduleReconcile();
|
|
354
|
+
void this.sweepOrphanedCancelButtons();
|
|
229
355
|
}
|
|
230
356
|
// ── ArchiverContext bridge ────────────────────────────────────────────
|
|
231
357
|
lastActivityMs(name) {
|
|
232
358
|
return this.lastActivity.get(name) ?? 0;
|
|
233
359
|
}
|
|
360
|
+
/**
|
|
361
|
+
* Is the instance between turns?
|
|
362
|
+
*
|
|
363
|
+
* Prefers the daemon's pane state machine (debounced, busy-pattern aware) over
|
|
364
|
+
* the control client's raw 2-second output-silence heuristic. The raw heuristic
|
|
365
|
+
* reads every >2s output lull as idle — and long silent tools (a build, a test
|
|
366
|
+
* run) or an LLM pause produce those constantly mid-turn. That misreading is
|
|
367
|
+
* what retired cancel buttons in the middle of long work (the 5-minute backstop
|
|
368
|
+
* fired during a lull) and froze their progress text (ticker skipped "idle"
|
|
369
|
+
* ticks). The silence heuristic remains only as the fallback for instances
|
|
370
|
+
* whose daemon has not reported a state yet.
|
|
371
|
+
*/
|
|
234
372
|
getInstanceIdle(name) {
|
|
373
|
+
// A daemon that is not running cannot be mid-turn. This is what a stale
|
|
374
|
+
// "working" cache after a hard daemon kill (SIGKILL/OOM — no IPC crash
|
|
375
|
+
// report ever arrives) must not override.
|
|
376
|
+
if (this.getInstanceStatus(name) !== "running")
|
|
377
|
+
return true;
|
|
378
|
+
const state = this.getInstanceExecutionState(name);
|
|
379
|
+
if (state === "working" || state === "stuck")
|
|
380
|
+
return false;
|
|
381
|
+
if (state === "idle")
|
|
382
|
+
return true;
|
|
235
383
|
try {
|
|
236
384
|
const widFile = join(this.getInstanceDir(name), "window-id");
|
|
237
385
|
if (!existsSync(widFile))
|
|
@@ -243,6 +391,18 @@ export class FleetManager {
|
|
|
243
391
|
return true;
|
|
244
392
|
}
|
|
245
393
|
}
|
|
394
|
+
/**
|
|
395
|
+
* True when the instance claims working/stuck but nothing has refreshed that
|
|
396
|
+
* claim for STATE_REPORT_STALE_MS despite the backstop's per-tick queries.
|
|
397
|
+
* Measures the CACHE's age, not the button's — a healthy multi-hour run
|
|
398
|
+
* answers every query and never trips this.
|
|
399
|
+
*/
|
|
400
|
+
stateReportDead(name) {
|
|
401
|
+
const cached = this.instanceStateCache.get(name);
|
|
402
|
+
if (!cached)
|
|
403
|
+
return false; // no claim to distrust — getInstanceIdle owns this case
|
|
404
|
+
return Date.now() - cached.receivedAt > STATE_REPORT_STALE_MS;
|
|
405
|
+
}
|
|
246
406
|
// ── LifecycleContext bridge methods ──────────────────────────────────────
|
|
247
407
|
webhookEmit(event, name, data) {
|
|
248
408
|
this.webhookEmitter?.emit(event, name, data);
|
|
@@ -304,10 +464,20 @@ export class FleetManager {
|
|
|
304
464
|
if (!this.classicChannels)
|
|
305
465
|
return;
|
|
306
466
|
const channels = this.classicChannels.getAll();
|
|
467
|
+
// Classic's persisted adapter is authoritative. Legacy adapter-less rows
|
|
468
|
+
// deterministically belong to channels[0], never to whichever bot happens
|
|
469
|
+
// to deliver the first message after startup/reconnect.
|
|
470
|
+
for (const ch of channels) {
|
|
471
|
+
const adapterId = ch.adapterId ?? this.getPrimaryAdapterId();
|
|
472
|
+
if (adapterId)
|
|
473
|
+
this.instanceWorldBinding.set(ch.instanceName, adapterId);
|
|
474
|
+
}
|
|
307
475
|
// Always update adapter openChannels (including empty — clears stale entries on /stop)
|
|
308
476
|
for (const [adapterId, w] of this.worlds) {
|
|
309
477
|
if (typeof w.adapter?.setOpenChannels === "function") {
|
|
310
|
-
const owned = channels
|
|
478
|
+
const owned = channels
|
|
479
|
+
.filter(ch => (ch.adapterId ?? this.getPrimaryAdapterId()) === adapterId)
|
|
480
|
+
.map(ch => ch.channelId);
|
|
311
481
|
w.adapter.setOpenChannels(owned);
|
|
312
482
|
}
|
|
313
483
|
}
|
|
@@ -385,58 +555,113 @@ export class FleetManager {
|
|
|
385
555
|
}
|
|
386
556
|
/** Get the adapter bound to an instance, falling back to primary adapter */
|
|
387
557
|
getAdapterForInstance(name) {
|
|
388
|
-
const worldId = this.
|
|
558
|
+
const worldId = this.getInstanceAdapterId(name);
|
|
389
559
|
if (worldId)
|
|
390
560
|
return this.worlds.get(worldId)?.adapter ?? this.adapter;
|
|
391
561
|
return this.adapter;
|
|
392
562
|
}
|
|
393
563
|
/** Get the world for an instance */
|
|
394
564
|
getWorldForInstance(name) {
|
|
395
|
-
const worldId = this.
|
|
396
|
-
return worldId ? this.worlds.get(worldId) :
|
|
565
|
+
const worldId = this.getInstanceAdapterId(name);
|
|
566
|
+
return worldId ? this.worlds.get(worldId) : undefined;
|
|
397
567
|
}
|
|
398
568
|
/** Get channel config for a specific adapter (by id), falling back to primary */
|
|
399
569
|
getChannelConfig(adapterId) {
|
|
570
|
+
const channels = this.fleetConfig?.channels
|
|
571
|
+
?? (this.fleetConfig?.channel ? [this.fleetConfig.channel] : []);
|
|
400
572
|
if (adapterId) {
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
573
|
+
return channels.find(ch => (ch.id ?? ch.type) === adapterId)
|
|
574
|
+
?? this.worlds.get(adapterId)?.channelConfig
|
|
575
|
+
?? channels[0];
|
|
404
576
|
}
|
|
405
|
-
return
|
|
577
|
+
return channels[0];
|
|
406
578
|
}
|
|
407
579
|
/** Get the group_id for an instance's bound adapter */
|
|
408
580
|
getGroupIdForInstance(name) {
|
|
409
|
-
const
|
|
410
|
-
|
|
581
|
+
const adapterId = this.getInstanceAdapterId(name);
|
|
582
|
+
const world = adapterId ? this.worlds.get(adapterId) : undefined;
|
|
583
|
+
return world?.groupId ?? String(this.getChannelConfig(adapterId)?.group_id ?? "");
|
|
584
|
+
}
|
|
585
|
+
/** Configured primary adapter id. Never infer this from Map insertion order. */
|
|
586
|
+
getPrimaryAdapterId() {
|
|
587
|
+
const primary = this.fleetConfig?.channels?.[0] ?? this.fleetConfig?.channel;
|
|
588
|
+
if (primary)
|
|
589
|
+
return primary.id ?? primary.type;
|
|
590
|
+
// Defensive compatibility for callers/tests that provide a live world but
|
|
591
|
+
// no channel config. Real multi-adapter fleets always have channels[].
|
|
592
|
+
return this.worlds.keys().next().value;
|
|
593
|
+
}
|
|
594
|
+
/** Warn when a coordinator's adapter identity is ambiguous to the operator. */
|
|
595
|
+
warnUnboundGeneralChannelIds(fleet) {
|
|
596
|
+
const channels = fleet.channels ?? (fleet.channel ? [fleet.channel] : []);
|
|
597
|
+
if (channels.length <= 1)
|
|
598
|
+
return;
|
|
599
|
+
const adapterIds = channels.map(ch => ch.id ?? ch.type);
|
|
600
|
+
for (const [name, config] of Object.entries(fleet.instances)) {
|
|
601
|
+
if (!config.general_topic || config.channel_id)
|
|
602
|
+
continue;
|
|
603
|
+
this.logger.warn({
|
|
604
|
+
instance: name,
|
|
605
|
+
defaultAdapter: adapterIds[0],
|
|
606
|
+
availableAdapters: adapterIds,
|
|
607
|
+
}, "General instance has no channel_id in a multi-channel fleet; defaulting to the first adapter. Set channel_id explicitly.");
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
/**
|
|
611
|
+
* Resolve the authoritative adapter identity for an instance.
|
|
612
|
+
* Fleet instances without channel_id and legacy Classic entries both belong
|
|
613
|
+
* to channels[0]. Runtime bindings remain available for external sessions.
|
|
614
|
+
*/
|
|
615
|
+
getInstanceAdapterId(name) {
|
|
616
|
+
const cfg = this.fleetConfig?.instances[name];
|
|
617
|
+
if (cfg)
|
|
618
|
+
return cfg.channel_id ?? this.getPrimaryAdapterId();
|
|
619
|
+
if (this.classicChannels?.getChannelIdByInstance(name) !== undefined) {
|
|
620
|
+
return this.classicChannels.getAdapterIdByInstance(name) ?? this.getPrimaryAdapterId();
|
|
621
|
+
}
|
|
622
|
+
return this.instanceWorldBinding.get(name) ?? this.getPrimaryAdapterId();
|
|
411
623
|
}
|
|
412
624
|
/**
|
|
413
625
|
* Bind an instance to a specific world (the bot that answers for it).
|
|
414
626
|
* fromInbound=true (binding inferred from which adapter received a message)
|
|
415
|
-
* must not override a configured identity
|
|
416
|
-
*
|
|
417
|
-
*
|
|
627
|
+
* must not override a configured identity. Fleet instances use channel_id or
|
|
628
|
+
* channels[0]; Classic instances use their persisted adapter (or channels[0]
|
|
629
|
+
* for a legacy entry). Only external sessions may bind from inbound traffic.
|
|
418
630
|
*/
|
|
419
631
|
bindInstanceAdapter(name, adapterId, fromInbound = false) {
|
|
420
|
-
const cfg = this.fleetConfig?.instances[name];
|
|
421
632
|
if (fromInbound) {
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
return;
|
|
428
|
-
if (cfg && !cfg.channel_id)
|
|
429
|
-
return; // fleet instance without explicit binding → use primary
|
|
430
|
-
// Classic instance: don't override an existing binding (authoritative from /start)
|
|
431
|
-
if (this.classicChannels?.getChannelIdByInstance(name) !== undefined && this.instanceWorldBinding.has(name))
|
|
633
|
+
const configuredId = this.getInstanceAdapterId(name);
|
|
634
|
+
if (this.fleetConfig?.instances[name]
|
|
635
|
+
|| this.classicChannels?.getChannelIdByInstance(name) !== undefined) {
|
|
636
|
+
if (configuredId)
|
|
637
|
+
this.instanceWorldBinding.set(name, configuredId);
|
|
432
638
|
return;
|
|
639
|
+
}
|
|
433
640
|
}
|
|
434
641
|
this.instanceWorldBinding.set(name, adapterId);
|
|
435
642
|
}
|
|
436
643
|
getInstanceStatus(name) {
|
|
437
644
|
if (this.lifecycle.isPaused(name))
|
|
438
645
|
return "paused";
|
|
646
|
+
const daemon = this.lifecycle.daemons.get(name);
|
|
439
647
|
const processStatus = this.instanceProcessStatus.get(name);
|
|
648
|
+
// IPC can be disconnected during a respawn, so the event which announces
|
|
649
|
+
// the new live pane may be missed. The in-process daemon is authoritative
|
|
650
|
+
// in that case; do not leave a stale `crashed` cache masking an instance
|
|
651
|
+
// that has already recovered and can answer messages.
|
|
652
|
+
const daemonStatus = daemon?.getProcessStatus?.();
|
|
653
|
+
if (daemonStatus === "running") {
|
|
654
|
+
if (processStatus)
|
|
655
|
+
this.instanceProcessStatus.delete(name);
|
|
656
|
+
// A recovered in-process daemon is also the authority for clearing a
|
|
657
|
+
// marker left by a crash-loop/reconnect race. This keeps standalone
|
|
658
|
+
// `agend ls` from seeing the old marker after the next API outage.
|
|
659
|
+
try {
|
|
660
|
+
unlinkSync(join(this.getInstanceDir(name), "crash-state.json"));
|
|
661
|
+
}
|
|
662
|
+
catch { /* absent */ }
|
|
663
|
+
return "running";
|
|
664
|
+
}
|
|
440
665
|
if (processStatus)
|
|
441
666
|
return processStatus;
|
|
442
667
|
const pidPath = join(this.getInstanceDir(name), "daemon.pid");
|
|
@@ -454,6 +679,10 @@ export class FleetManager {
|
|
|
454
679
|
getInstanceExecutionState(name) {
|
|
455
680
|
if (this.lifecycle.isPaused(name))
|
|
456
681
|
return null;
|
|
682
|
+
// Process status wins over a stale pane snapshot. A dead remain-on-exit pane
|
|
683
|
+
// can still contain the old ready marker and must never surface as Idle.
|
|
684
|
+
if (this.instanceProcessStatus.has(name))
|
|
685
|
+
return null;
|
|
457
686
|
return this.instanceStateCache.get(name)?.state ?? null;
|
|
458
687
|
}
|
|
459
688
|
isClassicInstance(name) {
|
|
@@ -471,22 +700,61 @@ export class FleetManager {
|
|
|
471
700
|
unchangedForMs: numberOr(msg.unchangedForMs, previous?.unchangedForMs ?? 0),
|
|
472
701
|
observedAt: numberOr(msg.observedAt, now),
|
|
473
702
|
stateChangedAt: numberOr(msg.stateChangedAt, previous?.state === state ? previous.stateChangedAt : now),
|
|
703
|
+
// Fleet-manager receipt time, NOT the daemon's observation time: staleness
|
|
704
|
+
// asks "is anyone still reporting", which only the receiver can date.
|
|
705
|
+
receivedAt: now,
|
|
474
706
|
});
|
|
475
707
|
for (const check of this.instanceIdleWaiters.get(name) ?? [])
|
|
476
708
|
check();
|
|
477
709
|
// warm_cap: a fresh transition into idle may free this instance for eviction,
|
|
478
710
|
// or (more usefully) reveal that the fleet is now over cap. Only fire on the
|
|
479
711
|
// edge into idle, not on every idle heartbeat.
|
|
480
|
-
if (state === "idle" && previous?.state !== "idle")
|
|
712
|
+
if (state === "idle" && previous?.state !== "idle") {
|
|
481
713
|
this.enforceWarmCap();
|
|
714
|
+
// A queued message may turn this edge back into working almost
|
|
715
|
+
// immediately. Give that handoff a short grace before retiring the button.
|
|
716
|
+
this.scheduleIdleButtonRetirement(name);
|
|
717
|
+
}
|
|
718
|
+
else if (state !== "idle") {
|
|
719
|
+
this.cancelIdleButtonRetirement(name);
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
cancelIdleButtonRetirement(name) {
|
|
723
|
+
const timer = this.cancelButtonIdleRetireTimers.get(name);
|
|
724
|
+
if (!timer)
|
|
725
|
+
return;
|
|
726
|
+
clearTimeout(timer);
|
|
727
|
+
this.cancelButtonIdleRetireTimers.delete(name);
|
|
728
|
+
}
|
|
729
|
+
scheduleIdleButtonRetirement(name) {
|
|
730
|
+
this.cancelIdleButtonRetirement(name);
|
|
731
|
+
const timer = setTimeout(() => {
|
|
732
|
+
// Ignore a superseded timer even if it was already queued to run.
|
|
733
|
+
if (this.cancelButtonIdleRetireTimers.get(name) !== timer)
|
|
734
|
+
return;
|
|
735
|
+
this.cancelButtonIdleRetireTimers.delete(name);
|
|
736
|
+
if (this.getInstanceExecutionState(name) === "idle") {
|
|
737
|
+
this.retireInstanceButtons(name);
|
|
738
|
+
}
|
|
739
|
+
}, CANCEL_BTN_IDLE_RETIRE_GRACE_MS);
|
|
740
|
+
timer.unref?.();
|
|
741
|
+
this.cancelButtonIdleRetireTimers.set(name, timer);
|
|
482
742
|
}
|
|
483
743
|
cacheInstanceProcessStatus(name, status) {
|
|
484
744
|
if (status === "running") {
|
|
485
745
|
this.instanceProcessStatus.delete(name);
|
|
746
|
+
// A prior crash-loop marker is one-shot. Successful respawn is the
|
|
747
|
+
// authoritative recovery signal even when the marker outlived an IPC
|
|
748
|
+
// disconnect and was not consumed by a new Daemon constructor.
|
|
749
|
+
try {
|
|
750
|
+
unlinkSync(join(this.getInstanceDir(name), "crash-state.json"));
|
|
751
|
+
}
|
|
752
|
+
catch { /* absent */ }
|
|
486
753
|
return;
|
|
487
754
|
}
|
|
488
755
|
if (status !== "crashed" && status !== "stopped")
|
|
489
756
|
return;
|
|
757
|
+
this.cancelIdleButtonRetirement(name);
|
|
490
758
|
this.instanceProcessStatus.set(name, status);
|
|
491
759
|
// Never display the last ready prompt as current execution state after its
|
|
492
760
|
// owning CLI process has exited.
|
|
@@ -517,7 +785,7 @@ export class FleetManager {
|
|
|
517
785
|
const victims = selectLruEvictions(warm, cap, {
|
|
518
786
|
exclude,
|
|
519
787
|
isEvicting: name => this.warmCapEvicting.has(name),
|
|
520
|
-
isGeneral: name => this.fleetConfig
|
|
788
|
+
isGeneral: name => isGeneralInstance(this.fleetConfig, name),
|
|
521
789
|
isIdle: name => this.getInstanceExecutionState(name) === "idle",
|
|
522
790
|
lastInboundAt: name => readLastInboundAt(this.getInstanceDir(name)) ?? 0,
|
|
523
791
|
});
|
|
@@ -583,12 +851,70 @@ export class FleetManager {
|
|
|
583
851
|
if (!idle) {
|
|
584
852
|
this.logger.warn({ instanceName, timeoutMs }, "Idle gate timed out; forcing delivery");
|
|
585
853
|
}
|
|
586
|
-
|
|
587
|
-
if (!ipc?.connected)
|
|
588
|
-
throw new Error(`Instance '${instanceName}' IPC is unavailable`);
|
|
589
|
-
ipc.send(payload);
|
|
854
|
+
await this.sendWhenConnected(instanceName, payload);
|
|
590
855
|
this.lastDeliveryAt.set(instanceName, Date.now());
|
|
591
856
|
}
|
|
857
|
+
/**
|
|
858
|
+
* Hand a payload to an instance's IPC, waiting out a *transient* disconnect.
|
|
859
|
+
*
|
|
860
|
+
* A daemon that is restarting — `/restart`, crash recovery, a model switch —
|
|
861
|
+
* drops its socket for a few seconds. Any message arriving in that window used
|
|
862
|
+
* to fail instantly: the caller logged a warning, put ❌ on the user's message,
|
|
863
|
+
* and the message was gone. The user had to notice the ❌ and retype it. That is
|
|
864
|
+
* the "instance 訊息不容易掉" goal failing on the most predictable event there is.
|
|
865
|
+
*
|
|
866
|
+
* The wait is bounded. If the instance is genuinely down, this still throws and
|
|
867
|
+
* the ❌ still appears — just for a real failure rather than a restart.
|
|
868
|
+
*
|
|
869
|
+
* Ordering is preserved by serialising behind any waiter already queued for this
|
|
870
|
+
* instance, *including* when the socket happens to be up: otherwise a message
|
|
871
|
+
* arriving after the reconnect could overtake one that has been waiting for it.
|
|
872
|
+
*/
|
|
873
|
+
async sendWhenConnected(instanceName, payload) {
|
|
874
|
+
const queued = this.ipcWaitTails.get(instanceName);
|
|
875
|
+
if (!queued) {
|
|
876
|
+
const ipc = this.instanceIpcClients.get(instanceName);
|
|
877
|
+
if (ipc?.connected && ipc.send(payload))
|
|
878
|
+
return;
|
|
879
|
+
}
|
|
880
|
+
const attempt = (queued ?? Promise.resolve())
|
|
881
|
+
.catch(() => { })
|
|
882
|
+
.then(() => this.sendAfterIpcReturns(instanceName, payload));
|
|
883
|
+
// The chain stores a settled-either-way promise so one failed delivery cannot
|
|
884
|
+
// wedge every later one, and so `queued` above is safe to await unguarded.
|
|
885
|
+
const tail = attempt.catch(() => { });
|
|
886
|
+
this.ipcWaitTails.set(instanceName, tail);
|
|
887
|
+
try {
|
|
888
|
+
await attempt;
|
|
889
|
+
}
|
|
890
|
+
finally {
|
|
891
|
+
// Only the last waiter clears the chain; while a queue is still draining the
|
|
892
|
+
// map must keep pointing at it or ordering is lost.
|
|
893
|
+
if (this.ipcWaitTails.get(instanceName) === tail) {
|
|
894
|
+
this.ipcWaitTails.delete(instanceName);
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
/** Poll for the instance's IPC to come back, then send. Throws if it does not. */
|
|
899
|
+
async sendAfterIpcReturns(instanceName, payload) {
|
|
900
|
+
const deadline = Date.now() + IPC_RECONNECT_GRACE_MS;
|
|
901
|
+
let warned = false;
|
|
902
|
+
for (;;) {
|
|
903
|
+
// Re-read every round: a reconnect replaces the IpcClient object entirely,
|
|
904
|
+
// so a cached reference would stay dead forever.
|
|
905
|
+
const ipc = this.instanceIpcClients.get(instanceName);
|
|
906
|
+
if (ipc?.connected && ipc.send(payload))
|
|
907
|
+
return;
|
|
908
|
+
if (Date.now() >= deadline) {
|
|
909
|
+
throw new Error(`Instance '${instanceName}' IPC is unavailable`);
|
|
910
|
+
}
|
|
911
|
+
if (!warned) {
|
|
912
|
+
warned = true;
|
|
913
|
+
this.logger.info({ instanceName }, "Instance IPC is down — holding delivery until it reconnects");
|
|
914
|
+
}
|
|
915
|
+
await new Promise(resolve => setTimeout(resolve, IPC_RECONNECT_POLL_MS));
|
|
916
|
+
}
|
|
917
|
+
}
|
|
592
918
|
/** Single delivery facade: wake paused CLIs and serialize non-user work behind idle. */
|
|
593
919
|
async deliverToInstance(instanceName, payload, options = {}) {
|
|
594
920
|
const meta = payload.meta && typeof payload.meta === "object"
|
|
@@ -604,10 +930,7 @@ export class FleetManager {
|
|
|
604
930
|
await this.lifecycle.wake(instanceName, 30_000);
|
|
605
931
|
this.enforceWarmCap(instanceName); // woke one → evict a different LRU idle if over cap
|
|
606
932
|
}
|
|
607
|
-
|
|
608
|
-
if (!ipc?.connected)
|
|
609
|
-
throw new Error(`Instance '${instanceName}' IPC is unavailable`);
|
|
610
|
-
ipc.send(payload);
|
|
933
|
+
await this.sendWhenConnected(instanceName, payload);
|
|
611
934
|
// A cross-instance item arriving before the daemon observes this turn as
|
|
612
935
|
// working must not trust the stale idle snapshot from before the send.
|
|
613
936
|
this.lastDeliveryAt.set(instanceName, Date.now());
|
|
@@ -636,6 +959,9 @@ export class FleetManager {
|
|
|
636
959
|
this.enforceWarmCap(name); // manual wake still respects the fleet warm cap
|
|
637
960
|
return "awake";
|
|
638
961
|
}
|
|
962
|
+
if (isGeneralInstance(this.fleetConfig, name)) {
|
|
963
|
+
throw new Error(GENERAL_PAUSE_ERROR);
|
|
964
|
+
}
|
|
639
965
|
await this.lifecycle.pause(name);
|
|
640
966
|
return this.lifecycle.isPaused(name) ? "paused" : "not_idle";
|
|
641
967
|
}
|
|
@@ -655,11 +981,41 @@ export class FleetManager {
|
|
|
655
981
|
await new Promise(resolve => setTimeout(resolve, 250));
|
|
656
982
|
await this.startClassicInstance(instanceName, this.classicChannels.getBackendByInstance(instanceName, this.fleetConfig?.defaults?.backend), this.classicChannels.getPreTaskCommand(channel.channelId, channel.adapterId), this.classicChannels.getModel(channel.channelId, channel.adapterId, this.fleetConfig?.defaults?.model), this.classicChannels.getAutoPauseAfter(channel.channelId, channel.adapterId, this.fleetConfig?.defaults?.auto_pause_after));
|
|
657
983
|
}
|
|
658
|
-
async startInstance(name, config, topicMode
|
|
984
|
+
async startInstance(name, config, topicMode, kind = "fleet-topic",
|
|
985
|
+
/**
|
|
986
|
+
* Explicit starts (CLI/API) may resume a paused or failed daemon. Startup
|
|
987
|
+
* and reconcile calls leave this false so a persisted pause remains paused
|
|
988
|
+
* across a fleet restart.
|
|
989
|
+
*/
|
|
990
|
+
resumePaused = false) {
|
|
991
|
+
if (resumePaused && this.lifecycle.isPaused(name)) {
|
|
992
|
+
await this.lifecycle.wake(name, 30_000);
|
|
993
|
+
// A successful wake clears the persisted pause marker and produces a
|
|
994
|
+
// fresh instance_state snapshot. Drop any stale process error left by a
|
|
995
|
+
// pre-pause crash so /api/fleet and `agend ls` converge on running.
|
|
996
|
+
this.instanceProcessStatus.delete(name);
|
|
997
|
+
return;
|
|
998
|
+
}
|
|
659
999
|
if (this.lifecycle.isPaused(name)) {
|
|
660
1000
|
this.logger.info({ name }, "Persisted paused instance — skipping startup");
|
|
661
1001
|
return;
|
|
662
1002
|
}
|
|
1003
|
+
if (this.lifecycle.daemons.has(name)) {
|
|
1004
|
+
// A crash-loop daemon remains in the lifecycle map so its health monitor
|
|
1005
|
+
// can expose the failure. The old start path treated that object as
|
|
1006
|
+
// already running and merely deleted the process-status cache, leaving a
|
|
1007
|
+
// dead pane (and crash marker) behind. An explicit start is a recovery
|
|
1008
|
+
// request: tear down the failed daemon and build a fresh one.
|
|
1009
|
+
if (resumePaused) {
|
|
1010
|
+
const status = this.getInstanceStatus(name);
|
|
1011
|
+
if (status === "crashed" || status === "stopped") {
|
|
1012
|
+
await this.restartSingleInstance(name);
|
|
1013
|
+
return;
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1016
|
+
this.logger.info({ name }, "Instance already running, skipping");
|
|
1017
|
+
return;
|
|
1018
|
+
}
|
|
663
1019
|
if (config.general_topic) {
|
|
664
1020
|
// antigravity (agy) does not read MCP instructions — fleet context and
|
|
665
1021
|
// routing instructions are not injected, so it cannot act as a dispatcher.
|
|
@@ -670,8 +1026,19 @@ export class FleetManager {
|
|
|
670
1026
|
}
|
|
671
1027
|
this.ensureGeneralInstructions(config.working_directory, config.backend);
|
|
672
1028
|
}
|
|
1029
|
+
await this.lifecycle.start(name, config, topicMode, {
|
|
1030
|
+
kind,
|
|
1031
|
+
backend: config.backend ?? this.fleetConfig?.defaults?.backend ?? "claude-code",
|
|
1032
|
+
model: this.resolveInstanceModel(name).display,
|
|
1033
|
+
});
|
|
1034
|
+
// Only clear a stale process status after a real start succeeded. Clearing
|
|
1035
|
+
// it before lifecycle.start() can turn a crash-loop daemon's dead pane into
|
|
1036
|
+
// a falsely running instance when lifecycle.start() returns early.
|
|
673
1037
|
this.instanceProcessStatus.delete(name);
|
|
674
|
-
|
|
1038
|
+
try {
|
|
1039
|
+
unlinkSync(join(this.getInstanceDir(name), "crash-state.json"));
|
|
1040
|
+
}
|
|
1041
|
+
catch { /* consumed or absent */ }
|
|
675
1042
|
// Auto-connect IPC — daemon.start() ensures socket is ready before resolving
|
|
676
1043
|
await this.connectIpcToInstance(name);
|
|
677
1044
|
}
|
|
@@ -695,7 +1062,18 @@ export class FleetManager {
|
|
|
695
1062
|
* to avoid config file races. Stagger delay is group-to-group, not instance-to-instance.
|
|
696
1063
|
* TODO: per-instance startup timeout (existing issue, not introduced here)
|
|
697
1064
|
*/
|
|
698
|
-
async startInstancesWithConcurrency(entries, topicMode) {
|
|
1065
|
+
async startInstancesWithConcurrency(entries, topicMode, onReady) {
|
|
1066
|
+
// Persisted pauses are intentionally preserved across fleet restarts. Filter
|
|
1067
|
+
// them before grouping/staggering: startInstance() retains its own guard as
|
|
1068
|
+
// a final backstop, but putting a no-op entry in this queue still consumes a
|
|
1069
|
+
// full stagger slot for every distinct working directory.
|
|
1070
|
+
const runnableEntries = entries.filter(([name]) => !this.lifecycle.isPaused(name));
|
|
1071
|
+
const pausedCount = entries.length - runnableEntries.length;
|
|
1072
|
+
if (pausedCount > 0) {
|
|
1073
|
+
this.logger.info({ pausedCount }, "Paused instances excluded from startup queue");
|
|
1074
|
+
}
|
|
1075
|
+
if (runnableEntries.length === 0)
|
|
1076
|
+
return;
|
|
699
1077
|
const raw = this.fleetConfig?.defaults?.startup;
|
|
700
1078
|
const explicitConcurrency = raw?.concurrency;
|
|
701
1079
|
const staggerMs = Math.max(0, Math.min(30_000, raw?.stagger_delay_ms ?? 500));
|
|
@@ -710,10 +1088,10 @@ export class FleetManager {
|
|
|
710
1088
|
else {
|
|
711
1089
|
const freeMemMB = Math.round(freemem() / (1024 * 1024));
|
|
712
1090
|
concurrency = Math.max(2, Math.min(10, Math.floor(freeMemMB / ESTIMATED_MB_PER_INSTANCE)));
|
|
713
|
-
this.logger.info({ concurrency, freeMemMB: freeMemMB, totalInstances:
|
|
1091
|
+
this.logger.info({ concurrency, freeMemMB: freeMemMB, totalInstances: runnableEntries.length }, "Adaptive startup concurrency");
|
|
714
1092
|
}
|
|
715
1093
|
const byWorkDir = new Map();
|
|
716
|
-
for (const [name, config] of
|
|
1094
|
+
for (const [name, config] of runnableEntries) {
|
|
717
1095
|
const dir = config.working_directory;
|
|
718
1096
|
if (!byWorkDir.has(dir))
|
|
719
1097
|
byWorkDir.set(dir, []);
|
|
@@ -756,7 +1134,14 @@ export class FleetManager {
|
|
|
756
1134
|
lastStartAt = Date.now();
|
|
757
1135
|
(async () => {
|
|
758
1136
|
for (const [name, config] of group) {
|
|
759
|
-
|
|
1137
|
+
try {
|
|
1138
|
+
await this.startInstance(name, config, topicMode);
|
|
1139
|
+
if (this.daemons.has(name))
|
|
1140
|
+
onReady?.(name);
|
|
1141
|
+
}
|
|
1142
|
+
catch (err) {
|
|
1143
|
+
this.logger.error({ err, name }, "Failed to start instance");
|
|
1144
|
+
}
|
|
760
1145
|
}
|
|
761
1146
|
})().finally(() => {
|
|
762
1147
|
running--;
|
|
@@ -770,8 +1155,37 @@ export class FleetManager {
|
|
|
770
1155
|
startNext();
|
|
771
1156
|
});
|
|
772
1157
|
}
|
|
1158
|
+
runnableStartupCount(fleet, includeClassic) {
|
|
1159
|
+
const names = new Set(Object.keys(fleet.instances));
|
|
1160
|
+
if (includeClassic) {
|
|
1161
|
+
for (const channel of this.classicChannels?.getAll() ?? [])
|
|
1162
|
+
names.add(channel.instanceName);
|
|
1163
|
+
}
|
|
1164
|
+
let count = 0;
|
|
1165
|
+
for (const name of names) {
|
|
1166
|
+
if (!this.lifecycle.isPaused(name))
|
|
1167
|
+
count++;
|
|
1168
|
+
}
|
|
1169
|
+
return count;
|
|
1170
|
+
}
|
|
1171
|
+
restartProgressTarget() {
|
|
1172
|
+
const generalName = this.findGeneralInstance();
|
|
1173
|
+
if (!generalName)
|
|
1174
|
+
return null;
|
|
1175
|
+
const adapter = this.getAdapterForInstance(generalName);
|
|
1176
|
+
const chatId = this.getGroupIdForInstance(generalName);
|
|
1177
|
+
if (!adapter || !chatId)
|
|
1178
|
+
return null;
|
|
1179
|
+
const topicId = this.fleetConfig?.instances[generalName]?.topic_id;
|
|
1180
|
+
return {
|
|
1181
|
+
adapter,
|
|
1182
|
+
chatId,
|
|
1183
|
+
threadId: topicId != null ? String(topicId) : undefined,
|
|
1184
|
+
};
|
|
1185
|
+
}
|
|
773
1186
|
async stopInstance(name) {
|
|
774
1187
|
this.failoverActive.delete(name);
|
|
1188
|
+
this.cancelIdleButtonRetirement(name);
|
|
775
1189
|
this.instanceStateCache.delete(name);
|
|
776
1190
|
this.instanceProcessStatus.delete(name);
|
|
777
1191
|
this.lastDeliveryAt.delete(name);
|
|
@@ -779,6 +1193,21 @@ export class FleetManager {
|
|
|
779
1193
|
}
|
|
780
1194
|
/** Restart a single instance, reloading fleet.yaml first to pick up config changes. */
|
|
781
1195
|
async restartSingleInstance(name, opts) {
|
|
1196
|
+
// One restart at a time per instance. Multiple sources can ask concurrently
|
|
1197
|
+
// (MCP revival, /restart, pty_error, model failover); a second stop/start
|
|
1198
|
+
// interleaved with the first tears down the window the first just created.
|
|
1199
|
+
// Later callers join the in-flight restart instead — its opts win.
|
|
1200
|
+
const inFlight = this.restartsInFlight.get(name);
|
|
1201
|
+
if (inFlight) {
|
|
1202
|
+
this.logger.info({ name }, "restartSingleInstance: joining the restart already in flight");
|
|
1203
|
+
return inFlight;
|
|
1204
|
+
}
|
|
1205
|
+
const run = this.doRestartSingleInstance(name, opts)
|
|
1206
|
+
.finally(() => this.restartsInFlight.delete(name));
|
|
1207
|
+
this.restartsInFlight.set(name, run);
|
|
1208
|
+
return run;
|
|
1209
|
+
}
|
|
1210
|
+
async doRestartSingleInstance(name, opts) {
|
|
782
1211
|
if (this.configPath) {
|
|
783
1212
|
this.loadConfig(this.configPath);
|
|
784
1213
|
this.routing.rebuild(this.fleetConfig);
|
|
@@ -834,7 +1263,10 @@ export class FleetManager {
|
|
|
834
1263
|
const eqIdx = trimmed.indexOf("=");
|
|
835
1264
|
if (eqIdx < 0)
|
|
836
1265
|
continue;
|
|
837
|
-
|
|
1266
|
+
// Accept `export KEY=value` — the shell-style form people paste from their
|
|
1267
|
+
// .bashrc. Without this the variable landed in process.env under the key
|
|
1268
|
+
// "export KEY" and silently did nothing.
|
|
1269
|
+
const key = trimmed.slice(0, eqIdx).replace(/^export\s+/, "").trim();
|
|
838
1270
|
const raw = trimmed.slice(eqIdx + 1);
|
|
839
1271
|
const value = raw.replace(/^["'](.*)["']$/, '$1');
|
|
840
1272
|
// .env file always wins over inherited shell env vars, so that
|
|
@@ -842,17 +1274,36 @@ export class FleetManager {
|
|
|
842
1274
|
process.env[key] = value;
|
|
843
1275
|
}
|
|
844
1276
|
}
|
|
1277
|
+
/** Initialize auth before any adapter can answer /dashboard. */
|
|
1278
|
+
initializeWebAuthTokens() {
|
|
1279
|
+
this.webToken = loadOrCreateWebToken(this.dataDir);
|
|
1280
|
+
this.viewToken = randomBytes(24).toString("hex");
|
|
1281
|
+
const viewTokenPath = join(this.dataDir, "view.token");
|
|
1282
|
+
writeFileSync(viewTokenPath, this.viewToken, { encoding: "utf8", mode: 0o600 });
|
|
1283
|
+
try {
|
|
1284
|
+
chmodSync(viewTokenPath, 0o600);
|
|
1285
|
+
}
|
|
1286
|
+
catch { /* best effort */ }
|
|
1287
|
+
this.healthServerListening = false;
|
|
1288
|
+
}
|
|
1289
|
+
getDashboardAccess() {
|
|
1290
|
+
return { ready: this.healthServerListening, token: this.webToken };
|
|
1291
|
+
}
|
|
845
1292
|
/** Start all instances from fleet config */
|
|
846
1293
|
async startAll(configPath) {
|
|
1294
|
+
const startupStartedAt = Date.now();
|
|
847
1295
|
FleetManager.signalTarget = this;
|
|
848
1296
|
this.startupComplete = false;
|
|
1297
|
+
// Cleared here, not at the end of doStopAll: a stop has an async tail, and
|
|
1298
|
+
// anything arriving during it is still part of the stop.
|
|
1299
|
+
this.shuttingDown = false;
|
|
849
1300
|
this.configPath = configPath;
|
|
850
1301
|
this.loadEnvFile();
|
|
851
1302
|
// Rotate fleet.log if oversized (before any logging)
|
|
852
|
-
const { rotateLogIfNeeded } = await import("./logger.js");
|
|
853
1303
|
rotateLogIfNeeded(join(this.dataDir, "fleet.log"));
|
|
854
1304
|
const fleet = this.loadConfig(configPath);
|
|
855
1305
|
setLocale(detectLocale(fleet)); // user-facing text language (fleet.yaml defaults.locale / timezone)
|
|
1306
|
+
this.initializeWebAuthTokens();
|
|
856
1307
|
const topicMode = fleet.channel?.mode === "topic" || !!fleet.channels?.some(ch => ch.mode === "topic");
|
|
857
1308
|
// Set tmux socket isolation for custom AGEND_HOME
|
|
858
1309
|
const { getTmuxSocketName: getSocket } = await import("./paths.js");
|
|
@@ -893,7 +1344,7 @@ export class FleetManager {
|
|
|
893
1344
|
}
|
|
894
1345
|
const pidPath = join(this.dataDir, "fleet.pid");
|
|
895
1346
|
writeFileSync(pidPath, String(process.pid), "utf-8");
|
|
896
|
-
this.eventLog =
|
|
1347
|
+
this.eventLog = this.openEventLog();
|
|
897
1348
|
// Initialize classic channel manager. The primary adapter (channels[0])
|
|
898
1349
|
// migrates legacy single-bot entries and names without a suffix. Classic
|
|
899
1350
|
// routing does NOT go through the routing engine (single-key, can't hold two
|
|
@@ -982,6 +1433,10 @@ export class FleetManager {
|
|
|
982
1433
|
// Rotate fleet.log daily too (besides the startup size check above), so a
|
|
983
1434
|
// long-running fleet doesn't accumulate an unbounded log.
|
|
984
1435
|
rotateLogIfNeeded(join(this.dataDir, "fleet.log"));
|
|
1436
|
+
// Instance output.log is pipe-pane (TUI ANSI). Daemon health ticks rotate a
|
|
1437
|
+
// running instance's own log; this sweep is the safety net for every other
|
|
1438
|
+
// kind. One implementation, so the two cannot cover different sets.
|
|
1439
|
+
this.rotateAllInstanceLogs();
|
|
985
1440
|
}, () => {
|
|
986
1441
|
const instances = Object.keys(this.fleetConfig?.instances ?? {});
|
|
987
1442
|
const costMap = new Map();
|
|
@@ -996,6 +1451,7 @@ export class FleetManager {
|
|
|
996
1451
|
this.rotateInboxes();
|
|
997
1452
|
// Auto-create/adopt a general dispatcher — ONLY for the primary adapter.
|
|
998
1453
|
const channelConfigs = fleet.channels ?? (fleet.channel ? [fleet.channel] : []);
|
|
1454
|
+
this.warnUnboundGeneralChannelIds(fleet);
|
|
999
1455
|
const primaryAdapterId = channelConfigs[0] ? (channelConfigs[0].id ?? channelConfigs[0].type) : undefined;
|
|
1000
1456
|
const generalInstances = Object.entries(fleet.instances).filter(([, inst]) => inst.general_topic === true);
|
|
1001
1457
|
let generalsCreated = false;
|
|
@@ -1103,10 +1559,13 @@ export class FleetManager {
|
|
|
1103
1559
|
const allEntries = Object.entries(fleet.instances);
|
|
1104
1560
|
const generals = allEntries.filter(([_, cfg]) => cfg.general_topic);
|
|
1105
1561
|
const others = allEntries.filter(([_, cfg]) => !cfg.general_topic);
|
|
1562
|
+
const startupProgress = new RestartProgress(this.runnableStartupCount(fleet, topicMode), startupStartedAt, this.logger);
|
|
1106
1563
|
if (generals.length > 0) {
|
|
1107
1564
|
for (const [name, cfg] of generals) {
|
|
1108
1565
|
try {
|
|
1109
1566
|
await this.startInstance(name, cfg, topicMode);
|
|
1567
|
+
if (this.daemons.has(name))
|
|
1568
|
+
startupProgress.markReady();
|
|
1110
1569
|
}
|
|
1111
1570
|
catch (err) {
|
|
1112
1571
|
this.logger.error({ err, name }, "Failed to start general instance");
|
|
@@ -1121,39 +1580,63 @@ export class FleetManager {
|
|
|
1121
1580
|
}
|
|
1122
1581
|
}
|
|
1123
1582
|
}
|
|
1124
|
-
//
|
|
1125
|
-
|
|
1583
|
+
// The adapter must exist before General can receive the progress message.
|
|
1584
|
+
// Start it after General is ready, in parallel with the remaining CLIs, so
|
|
1585
|
+
// progress is visible without adding adapter startup time to the critical path.
|
|
1586
|
+
let adapterStartup = null;
|
|
1587
|
+
let progressStart = Promise.resolve(false);
|
|
1588
|
+
if (topicMode && (fleet.channel || fleet.channels?.length)) {
|
|
1589
|
+
// An adapter becoming reachable during startup can receive messages; make
|
|
1590
|
+
// all existing topic ids routable before opening that inbound path.
|
|
1591
|
+
this.routing.rebuild(fleet);
|
|
1592
|
+
this.reregisterClassicChannels();
|
|
1593
|
+
adapterStartup = (async () => {
|
|
1594
|
+
try {
|
|
1595
|
+
await this.startSharedAdapter(fleet);
|
|
1596
|
+
}
|
|
1597
|
+
catch (err) {
|
|
1598
|
+
this.logger.error({ err }, "startSharedAdapter failed — fleet continues without some adapters");
|
|
1599
|
+
}
|
|
1600
|
+
})();
|
|
1601
|
+
progressStart = adapterStartup.then(() => startupProgress.start(this.restartProgressTarget()));
|
|
1602
|
+
}
|
|
1603
|
+
// The systemd watchdog answers exactly one question: is this process still
|
|
1604
|
+
// turning its event loop? Pinging from a timer proves that, and after the
|
|
1605
|
+
// blocking child-process calls were made async it is a meaningful signal —
|
|
1606
|
+
// a deadlocked or frozen fleet stops pinging and systemd restarts it.
|
|
1607
|
+
//
|
|
1608
|
+
// It deliberately does NOT gate on fleet health. "No adapter connected" or
|
|
1609
|
+
// "an instance crashed" must not kill the process: the fleet would be restarted
|
|
1610
|
+
// into the same broken state, and a user who has legitimately stopped every
|
|
1611
|
+
// instance would get a restart loop. Those conditions surface through /health
|
|
1612
|
+
// (which now returns 503) and through the General-topic notifications instead.
|
|
1126
1613
|
this.watchdogTimer = setInterval(() => sdNotify("WATCHDOG=1"), 30_000);
|
|
1614
|
+
// EventLog.prune() existed but was never called, so `events` and `activity`
|
|
1615
|
+
// grew without bound for the life of the install. Prune once at startup and
|
|
1616
|
+
// daily after that; the timer is unref'd so it never holds the loop open.
|
|
1617
|
+
this.pruneEventLog();
|
|
1618
|
+
this.eventLogPruneTimer = setInterval(() => this.pruneEventLog(), 24 * 60 * 60_000);
|
|
1619
|
+
this.eventLogPruneTimer.unref?.();
|
|
1620
|
+
// Same shape for pipe-pane logs, and for the same reason: the only sweep that
|
|
1621
|
+
// covered them lived inside the daily-summary callback, so it did not run at
|
|
1622
|
+
// all when summaries were off.
|
|
1623
|
+
this.rotateAllInstanceLogs();
|
|
1624
|
+
this.logRotateTimer = setInterval(() => this.rotateAllInstanceLogs(), 24 * 60 * 60_000);
|
|
1625
|
+
this.logRotateTimer.unref?.();
|
|
1127
1626
|
// Phase 2: Start remaining instances with staggered concurrency
|
|
1128
1627
|
if (others.length > 0) {
|
|
1129
|
-
await this.startInstancesWithConcurrency(others, topicMode);
|
|
1628
|
+
await this.startInstancesWithConcurrency(others, topicMode, () => startupProgress.markReady());
|
|
1130
1629
|
}
|
|
1131
1630
|
if (topicMode && (fleet.channel || fleet.channels?.length)) {
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
}
|
|
1138
|
-
// Bind instances to their adapter (which bot answers on their behalf).
|
|
1139
|
-
// An explicit channel_id is authoritative — this is how a persona instance
|
|
1140
|
-
// picks its bot when several share one guild. Generals without a channel_id
|
|
1141
|
-
// fall back to a name-contains-adapterId heuristic.
|
|
1142
|
-
const channelConfigsForBind = fleet.channels ?? (fleet.channel ? [fleet.channel] : []);
|
|
1631
|
+
await adapterStartup;
|
|
1632
|
+
// Bind every fleet instance deterministically. Explicit channel_id wins;
|
|
1633
|
+
// otherwise channels[0] is authoritative. Do not infer identity from
|
|
1634
|
+
// concurrent adapter startup or whichever bot receives a message first.
|
|
1635
|
+
const primaryAdapterId = this.getPrimaryAdapterId();
|
|
1143
1636
|
for (const [name, config] of Object.entries(fleet.instances)) {
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
}
|
|
1148
|
-
if (!config.general_topic)
|
|
1149
|
-
continue;
|
|
1150
|
-
for (const ch of channelConfigsForBind) {
|
|
1151
|
-
const id = ch.id ?? ch.type;
|
|
1152
|
-
if (name.includes(id)) {
|
|
1153
|
-
this.bindInstanceAdapter(name, id);
|
|
1154
|
-
break;
|
|
1155
|
-
}
|
|
1156
|
-
}
|
|
1637
|
+
const adapterId = config.channel_id ?? primaryAdapterId;
|
|
1638
|
+
if (adapterId)
|
|
1639
|
+
this.bindInstanceAdapter(name, adapterId);
|
|
1157
1640
|
}
|
|
1158
1641
|
// Guard against a stale/invalid general topic_id. An old auto-general
|
|
1159
1642
|
// could have written the TG-convention "1" for a Discord general; the DC
|
|
@@ -1163,7 +1646,7 @@ export class FleetManager {
|
|
|
1163
1646
|
for (const [name, cfg] of Object.entries(this.fleetConfig.instances)) {
|
|
1164
1647
|
if (!cfg.general_topic || cfg.topic_id == null)
|
|
1165
1648
|
continue;
|
|
1166
|
-
const adapterId = this.
|
|
1649
|
+
const adapterId = this.getInstanceAdapterId(name);
|
|
1167
1650
|
if (this.getChannelConfig(adapterId)?.type === "discord" && !/^\d{17,}$/.test(String(cfg.topic_id))) {
|
|
1168
1651
|
this.logger.warn({ name, topic_id: cfg.topic_id }, "Discord general topic_id is not a valid channel — unbinding to avoid a crash loop");
|
|
1169
1652
|
delete cfg.topic_id;
|
|
@@ -1186,18 +1669,30 @@ export class FleetManager {
|
|
|
1186
1669
|
// Start classic channel instances (parallel, concurrency 3)
|
|
1187
1670
|
if (this.classicChannels) {
|
|
1188
1671
|
const fleetBackend = this.fleetConfig?.defaults?.backend;
|
|
1189
|
-
const channels = this.classicChannels.getAll()
|
|
1672
|
+
const channels = this.classicChannels.getAll()
|
|
1673
|
+
.filter(ch => !this.lifecycle.isPaused(ch.instanceName));
|
|
1190
1674
|
const concurrency = 3;
|
|
1191
1675
|
let idx = 0;
|
|
1192
1676
|
while (idx < channels.length) {
|
|
1193
1677
|
const batch = channels.slice(idx, idx + concurrency);
|
|
1194
|
-
await Promise.allSettled(batch.map(
|
|
1678
|
+
await Promise.allSettled(batch.map(async (ch) => {
|
|
1679
|
+
try {
|
|
1680
|
+
await this.startClassicInstance(ch.instanceName, this.classicChannels.getBackendByInstance(ch.instanceName, fleetBackend), this.classicChannels.getPreTaskCommand(ch.channelId, ch.adapterId), this.classicChannels.getModel(ch.channelId, ch.adapterId, this.fleetConfig?.defaults?.model), this.classicChannels.getAutoPauseAfter(ch.channelId, ch.adapterId, this.fleetConfig?.defaults?.auto_pause_after));
|
|
1681
|
+
if (this.daemons.has(ch.instanceName))
|
|
1682
|
+
startupProgress.markReady();
|
|
1683
|
+
}
|
|
1684
|
+
catch (err) {
|
|
1685
|
+
this.logger.warn({ err, instanceName: ch.instanceName }, "Failed to start classic instance");
|
|
1686
|
+
}
|
|
1687
|
+
}));
|
|
1195
1688
|
idx += concurrency;
|
|
1196
1689
|
}
|
|
1197
1690
|
}
|
|
1198
1691
|
for (const name of Object.keys(fleet.instances)) {
|
|
1199
1692
|
this.startStatuslineWatcher(name);
|
|
1200
1693
|
}
|
|
1694
|
+
await progressStart;
|
|
1695
|
+
const progressCompleted = await startupProgress.finish();
|
|
1201
1696
|
// Notify General topic that fleet is up
|
|
1202
1697
|
const classicCount = this.classicChannels?.getAll().length ?? 0;
|
|
1203
1698
|
const total = Object.keys(fleet.instances).length + classicCount;
|
|
@@ -1210,7 +1705,7 @@ export class FleetManager {
|
|
|
1210
1705
|
const { createRequire } = await import("node:module");
|
|
1211
1706
|
const _require = createRequire(import.meta.url);
|
|
1212
1707
|
const agendVersion = _require("../package.json").version ?? "unknown";
|
|
1213
|
-
if (this.adapter && fleet.channel?.group_id) {
|
|
1708
|
+
if (!progressCompleted && this.adapter && fleet.channel?.group_id) {
|
|
1214
1709
|
let text;
|
|
1215
1710
|
if (failedNames.length === 0 && pausedNames.length === 0) {
|
|
1216
1711
|
text = t("fleet.ready", started, total, agendVersion);
|
|
@@ -1259,6 +1754,15 @@ export class FleetManager {
|
|
|
1259
1754
|
// rest of startup finishes. Replay one coalesced reload only after all
|
|
1260
1755
|
// startup-owned lifecycle work and signal handlers are in place.
|
|
1261
1756
|
this.finishStartup();
|
|
1757
|
+
// Tell systemd we are ready only now. This used to fire right after the
|
|
1758
|
+
// generals started — before adapters, classic instances, topic creation and the
|
|
1759
|
+
// health server — so `systemctl start` returned success while the fleet was
|
|
1760
|
+
// still deaf: no path existed for a user message to arrive.
|
|
1761
|
+
sdNotify("READY=1");
|
|
1762
|
+
const health = this.getFleetHealth();
|
|
1763
|
+
if (health.status !== "ok") {
|
|
1764
|
+
this.logger.warn({ health }, "Fleet started with problems — see /health");
|
|
1765
|
+
}
|
|
1262
1766
|
}
|
|
1263
1767
|
/**
|
|
1264
1768
|
* Delete inbox files older than retentionDays (by mtime). Cleans the shared
|
|
@@ -1375,6 +1879,67 @@ export class FleetManager {
|
|
|
1375
1879
|
getAdapterStates() {
|
|
1376
1880
|
return this.adapterState;
|
|
1377
1881
|
}
|
|
1882
|
+
/**
|
|
1883
|
+
* Real, checkable fleet health for `/health` and the operator.
|
|
1884
|
+
*
|
|
1885
|
+
* `status` is:
|
|
1886
|
+
* - `ok` — at least one adapter connected and every configured instance
|
|
1887
|
+
* that should be running is running
|
|
1888
|
+
* - `degraded` — reachable, but something the operator should look at (an
|
|
1889
|
+
* adapter retrying, an instance crashed or stopped)
|
|
1890
|
+
* - `down` — the fleet cannot do its job: no adapter is connected, so no
|
|
1891
|
+
* message can arrive or be answered
|
|
1892
|
+
*
|
|
1893
|
+
* Deliberately does NOT gate the systemd watchdog — see the comment at the
|
|
1894
|
+
* WATCHDOG timer for why.
|
|
1895
|
+
*/
|
|
1896
|
+
getFleetHealth() {
|
|
1897
|
+
const names = Object.keys(this.fleetConfig?.instances ?? {});
|
|
1898
|
+
const counts = { configured: names.length, running: 0, crashed: 0, paused: 0, stopped: 0 };
|
|
1899
|
+
for (const name of names) {
|
|
1900
|
+
const state = this.getInstanceStatus(name);
|
|
1901
|
+
if (state === "running")
|
|
1902
|
+
counts.running++;
|
|
1903
|
+
else if (state === "crashed")
|
|
1904
|
+
counts.crashed++;
|
|
1905
|
+
else if (state === "paused")
|
|
1906
|
+
counts.paused++;
|
|
1907
|
+
else
|
|
1908
|
+
counts.stopped++;
|
|
1909
|
+
}
|
|
1910
|
+
const states = {};
|
|
1911
|
+
let connected = 0;
|
|
1912
|
+
for (const [id, state] of this.adapterState) {
|
|
1913
|
+
states[id] = state.status;
|
|
1914
|
+
if (state.status === "connected")
|
|
1915
|
+
connected++;
|
|
1916
|
+
}
|
|
1917
|
+
const problems = [];
|
|
1918
|
+
if (this.adapterState.size > 0 && connected === 0)
|
|
1919
|
+
problems.push("no channel adapter is connected");
|
|
1920
|
+
if (counts.crashed > 0)
|
|
1921
|
+
problems.push(`${counts.crashed} instance(s) crashed`);
|
|
1922
|
+
for (const [id, state] of this.adapterState) {
|
|
1923
|
+
if (state.status !== "connected")
|
|
1924
|
+
problems.push(`adapter ${id} is ${state.status}`);
|
|
1925
|
+
}
|
|
1926
|
+
if (!this.startupComplete)
|
|
1927
|
+
problems.push("startup has not completed");
|
|
1928
|
+
// "down" is reserved for "cannot receive or answer a message at all". A fleet
|
|
1929
|
+
// with adapters configured but none connected is exactly that.
|
|
1930
|
+
const status = this.adapterState.size > 0 && connected === 0
|
|
1931
|
+
? "down"
|
|
1932
|
+
: problems.length > 0 ? "degraded" : "ok";
|
|
1933
|
+
return {
|
|
1934
|
+
status,
|
|
1935
|
+
uptime: Math.floor((Date.now() - this.startedAt) / 1000),
|
|
1936
|
+
instances: counts,
|
|
1937
|
+
adapters: { total: this.adapterState.size, connected, states },
|
|
1938
|
+
startupComplete: this.startupComplete,
|
|
1939
|
+
memory: readFleetMemory(),
|
|
1940
|
+
problems,
|
|
1941
|
+
};
|
|
1942
|
+
}
|
|
1378
1943
|
/** Start the primary adapter (backward-compatible, sets this.adapter) */
|
|
1379
1944
|
async startSingleAdapter(fleet, channelConfig) {
|
|
1380
1945
|
const botToken = process.env[channelConfig.bot_token_env];
|
|
@@ -1401,11 +1966,16 @@ export class FleetManager {
|
|
|
1401
1966
|
this.adapter.on("message", safeHandler(async (msg) => {
|
|
1402
1967
|
await this.handleInboundMessage(msg);
|
|
1403
1968
|
}, this.logger, "adapter.message"));
|
|
1969
|
+
this.adapter.on("reaction", safeHandler(async (r) => {
|
|
1970
|
+
await this.handleInboundReaction(r);
|
|
1971
|
+
}, this.logger, "adapter.reaction"));
|
|
1404
1972
|
this.adapter.on("callback_query", safeHandler(async (data) => {
|
|
1405
1973
|
if (await this.handleClassicBackendSelection(data))
|
|
1406
1974
|
return;
|
|
1407
1975
|
if (await this.handleModelSelection(data))
|
|
1408
1976
|
return;
|
|
1977
|
+
if (await this.handleEffortSelection(data))
|
|
1978
|
+
return;
|
|
1409
1979
|
if (data.callbackData.startsWith("hang:")) {
|
|
1410
1980
|
const parts = data.callbackData.split(":");
|
|
1411
1981
|
const action = parts[1];
|
|
@@ -1426,12 +1996,7 @@ export class FleetManager {
|
|
|
1426
1996
|
return;
|
|
1427
1997
|
}
|
|
1428
1998
|
if (data.callbackData.startsWith("cancel:")) {
|
|
1429
|
-
|
|
1430
|
-
// Idempotent: a button click only acts while the button is live. A
|
|
1431
|
-
// second click (entry already cleared) is a no-op — don't re-send the
|
|
1432
|
-
// interrupt key. (The /cancel command path calls cancelInstance directly.)
|
|
1433
|
-
if (this.hasCancelButton(instanceName))
|
|
1434
|
-
this.cancelInstance(instanceName);
|
|
1999
|
+
this.handleCancelClick(data.callbackData.slice("cancel:".length), this.adapter, data);
|
|
1435
2000
|
return;
|
|
1436
2001
|
}
|
|
1437
2002
|
}, this.logger, "adapter.callback_query"));
|
|
@@ -1511,6 +2076,9 @@ export class FleetManager {
|
|
|
1511
2076
|
else if (data.command === "model") {
|
|
1512
2077
|
await this.handleModelSlash(data, adapterId);
|
|
1513
2078
|
}
|
|
2079
|
+
else if (data.command === "effort") {
|
|
2080
|
+
await this.handleEffortSlash(data, adapterId);
|
|
2081
|
+
}
|
|
1514
2082
|
else if (data.command === "cancel") {
|
|
1515
2083
|
const name = this.resolveSlashTarget(data.channelId, adapterId);
|
|
1516
2084
|
if (!name) {
|
|
@@ -1575,19 +2143,29 @@ export class FleetManager {
|
|
|
1575
2143
|
await data.respond(t("not_authorized"));
|
|
1576
2144
|
return;
|
|
1577
2145
|
}
|
|
2146
|
+
await data.respond(await this.runBackendDoctor());
|
|
2147
|
+
}
|
|
2148
|
+
else if (data.command === "usage") {
|
|
2149
|
+
// Same permission level as /ctx (none). The reply is still ephemeral —
|
|
2150
|
+
// the adapter defers non-chat commands that way — so it never spams the
|
|
2151
|
+
// channel either way.
|
|
1578
2152
|
try {
|
|
1579
|
-
const {
|
|
1580
|
-
const
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
await data.respond(clean || "No output");
|
|
2153
|
+
const { getUsageSnapshot } = await import("./usage/usage-api.js");
|
|
2154
|
+
const { renderUsageMarkdown } = await import("./usage/format-rich.js");
|
|
2155
|
+
// slash_command is Discord-only; editReply renders Markdown natively.
|
|
2156
|
+
await data.respond(renderUsageMarkdown(await getUsageSnapshot()));
|
|
1584
2157
|
}
|
|
1585
2158
|
catch (err) {
|
|
1586
|
-
|
|
1587
|
-
await data.respond(output);
|
|
2159
|
+
await data.respond(`⚠️ Usage fetch failed: ${err.message}`);
|
|
1588
2160
|
}
|
|
1589
2161
|
}
|
|
1590
2162
|
else if (data.command === "status") {
|
|
2163
|
+
// Admin-gated (like the topic path): the merged table shows every
|
|
2164
|
+
// instance's cost and IPC health.
|
|
2165
|
+
if (!this.isFleetAdmin(data.userId, adapterId)) {
|
|
2166
|
+
await data.respond(t("cmd.admin_required", "/status"));
|
|
2167
|
+
return;
|
|
2168
|
+
}
|
|
1591
2169
|
const text = await this.topicCommands.getStatusText();
|
|
1592
2170
|
await data.respond(text);
|
|
1593
2171
|
}
|
|
@@ -1633,7 +2211,9 @@ export class FleetManager {
|
|
|
1633
2211
|
this.probeCliEnvs();
|
|
1634
2212
|
this.adapter.on("started", safeHandler((username, userId) => {
|
|
1635
2213
|
this.logger.info(`Bot @${username} polling started. Ensure no other service is polling this bot token.`);
|
|
1636
|
-
|
|
2214
|
+
// Concurrent startup can insert a secondary world first. Update the
|
|
2215
|
+
// configured primary world, not Map insertion order.
|
|
2216
|
+
const w = this.worlds.get(adapterId);
|
|
1637
2217
|
if (w) {
|
|
1638
2218
|
w.botUsername = username;
|
|
1639
2219
|
if (userId)
|
|
@@ -1696,11 +2276,16 @@ export class FleetManager {
|
|
|
1696
2276
|
adapter.on("message", safeHandler(async (msg) => {
|
|
1697
2277
|
await this.handleInboundMessage(msg);
|
|
1698
2278
|
}, this.logger, `adapter[${adapterId}].message`));
|
|
2279
|
+
adapter.on("reaction", safeHandler(async (r) => {
|
|
2280
|
+
await this.handleInboundReaction(r);
|
|
2281
|
+
}, this.logger, `adapter[${adapterId}].reaction`));
|
|
1699
2282
|
adapter.on("callback_query", safeHandler(async (data) => {
|
|
1700
2283
|
if (await this.handleClassicBackendSelection(data))
|
|
1701
2284
|
return;
|
|
1702
2285
|
if (await this.handleModelSelection(data))
|
|
1703
2286
|
return;
|
|
2287
|
+
if (await this.handleEffortSelection(data))
|
|
2288
|
+
return;
|
|
1704
2289
|
if (data.callbackData.startsWith("hang:")) {
|
|
1705
2290
|
const parts = data.callbackData.split(":");
|
|
1706
2291
|
const action = parts[1];
|
|
@@ -1720,10 +2305,7 @@ export class FleetManager {
|
|
|
1720
2305
|
return;
|
|
1721
2306
|
}
|
|
1722
2307
|
if (data.callbackData.startsWith("cancel:")) {
|
|
1723
|
-
|
|
1724
|
-
// Idempotent: only the first click (while the button is live) acts.
|
|
1725
|
-
if (this.hasCancelButton(instanceName))
|
|
1726
|
-
this.cancelInstance(instanceName);
|
|
2308
|
+
this.handleCancelClick(data.callbackData.slice("cancel:".length), adapter, data);
|
|
1727
2309
|
return;
|
|
1728
2310
|
}
|
|
1729
2311
|
}, this.logger, `adapter[${adapterId}].callback_query`));
|
|
@@ -1793,6 +2375,9 @@ export class FleetManager {
|
|
|
1793
2375
|
else if (data.command === "model") {
|
|
1794
2376
|
await this.handleModelSlash(data, adapterId);
|
|
1795
2377
|
}
|
|
2378
|
+
else if (data.command === "effort") {
|
|
2379
|
+
await this.handleEffortSlash(data, adapterId);
|
|
2380
|
+
}
|
|
1796
2381
|
else if (data.command === "cancel") {
|
|
1797
2382
|
const name = this.resolveSlashTarget(data.channelId, adapterId);
|
|
1798
2383
|
if (!name) {
|
|
@@ -1857,19 +2442,29 @@ export class FleetManager {
|
|
|
1857
2442
|
await data.respond(t("not_authorized"));
|
|
1858
2443
|
return;
|
|
1859
2444
|
}
|
|
2445
|
+
await data.respond(await this.runBackendDoctor());
|
|
2446
|
+
}
|
|
2447
|
+
else if (data.command === "usage") {
|
|
2448
|
+
// Same permission level as /ctx (none). The reply is still ephemeral —
|
|
2449
|
+
// the adapter defers non-chat commands that way — so it never spams the
|
|
2450
|
+
// channel either way.
|
|
1860
2451
|
try {
|
|
1861
|
-
const {
|
|
1862
|
-
const
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
await data.respond(clean || "No output");
|
|
2452
|
+
const { getUsageSnapshot } = await import("./usage/usage-api.js");
|
|
2453
|
+
const { renderUsageMarkdown } = await import("./usage/format-rich.js");
|
|
2454
|
+
// slash_command is Discord-only; editReply renders Markdown natively.
|
|
2455
|
+
await data.respond(renderUsageMarkdown(await getUsageSnapshot()));
|
|
1866
2456
|
}
|
|
1867
2457
|
catch (err) {
|
|
1868
|
-
|
|
1869
|
-
await data.respond(output);
|
|
2458
|
+
await data.respond(`⚠️ Usage fetch failed: ${err.message}`);
|
|
1870
2459
|
}
|
|
1871
2460
|
}
|
|
1872
2461
|
else if (data.command === "status") {
|
|
2462
|
+
// Admin-gated (like the topic path): the merged table shows every
|
|
2463
|
+
// instance's cost and IPC health.
|
|
2464
|
+
if (!this.isFleetAdmin(data.userId, adapterId)) {
|
|
2465
|
+
await data.respond(t("cmd.admin_required", "/status"));
|
|
2466
|
+
return;
|
|
2467
|
+
}
|
|
1873
2468
|
const text = await this.topicCommands.getStatusText();
|
|
1874
2469
|
await data.respond(text);
|
|
1875
2470
|
}
|
|
@@ -2025,6 +2620,9 @@ export class FleetManager {
|
|
|
2025
2620
|
else if (msg.type === "instance_process_state") {
|
|
2026
2621
|
this.cacheInstanceProcessStatus(name, msg.status);
|
|
2027
2622
|
}
|
|
2623
|
+
else if (msg.type === "instance_activity") {
|
|
2624
|
+
this.cacheInstanceActivity(name, msg.activity);
|
|
2625
|
+
}
|
|
2028
2626
|
else if (msg.type === "instance_state" || msg.type === "instance_state_response") {
|
|
2029
2627
|
this.cacheInstanceExecutionState(name, msg);
|
|
2030
2628
|
if (msg.type === "instance_state_response") {
|
|
@@ -2095,9 +2693,22 @@ export class FleetManager {
|
|
|
2095
2693
|
if (existsSync(windowIdPath)) {
|
|
2096
2694
|
const windowId = readFileSync(windowIdPath, "utf-8").trim();
|
|
2097
2695
|
if (windowId) {
|
|
2696
|
+
// Async with an explicit timeout: this was execSync with NO timeout at
|
|
2697
|
+
// all, so a wedged tmux server blocked the whole fleet event loop
|
|
2698
|
+
// indefinitely — while we were here to diagnose a lost connection.
|
|
2699
|
+
// A timeout is also the correct signal: an unresponsive tmux server
|
|
2700
|
+
// means we cannot verify the pane, which is treated as dead (the same
|
|
2701
|
+
// conclusion the old code reached only by throwing).
|
|
2098
2702
|
try {
|
|
2099
|
-
const {
|
|
2100
|
-
|
|
2703
|
+
const { execFile } = await import("node:child_process");
|
|
2704
|
+
const { promisify } = await import("node:util");
|
|
2705
|
+
const { getTmuxSocketName } = await import("./paths.js");
|
|
2706
|
+
// Honour socket isolation: without -L this queried the user's default
|
|
2707
|
+
// tmux server instead of the fleet's, so under a custom AGEND_HOME the
|
|
2708
|
+
// check was meaningless (it reported every pane dead).
|
|
2709
|
+
const socket = getTmuxSocketName();
|
|
2710
|
+
const args = socket ? ["-L", socket, "list-panes", "-t", windowId] : ["list-panes", "-t", windowId];
|
|
2711
|
+
await promisify(execFile)("tmux", args, { timeout: 5_000 });
|
|
2101
2712
|
}
|
|
2102
2713
|
catch {
|
|
2103
2714
|
// Pane dead — respawn
|
|
@@ -2118,6 +2729,12 @@ export class FleetManager {
|
|
|
2118
2729
|
if (this.adapterRestarting.has(id))
|
|
2119
2730
|
return;
|
|
2120
2731
|
this.adapterRestarting.add(id);
|
|
2732
|
+
// Reflect reality in adapterState throughout. This loop used to leave the state
|
|
2733
|
+
// untouched, so getAdapterStates() — and therefore /health and the dashboard —
|
|
2734
|
+
// kept reporting "connected" for an adapter that had been down for hours. An
|
|
2735
|
+
// adapter's true status was simply not knowable from inside the process.
|
|
2736
|
+
const previous = this.adapterState.get(id);
|
|
2737
|
+
this.adapterState.set(id, { status: "retrying", retryCount: 0, lastError: previous?.lastError });
|
|
2121
2738
|
try {
|
|
2122
2739
|
for (let attempt = 1;; attempt++) {
|
|
2123
2740
|
if (this.ipcStoppingInstances.has("__fleet_stopping__"))
|
|
@@ -2130,9 +2747,16 @@ export class FleetManager {
|
|
|
2130
2747
|
await adapter.stop().catch(() => { });
|
|
2131
2748
|
await adapter.start();
|
|
2132
2749
|
this.logger.info({ id, attempt }, "Adapter restarted successfully");
|
|
2750
|
+
this.adapterState.set(id, { status: "connected", retryCount: 0 });
|
|
2133
2751
|
return;
|
|
2134
2752
|
}
|
|
2135
|
-
catch {
|
|
2753
|
+
catch (err) {
|
|
2754
|
+
this.adapterState.set(id, {
|
|
2755
|
+
status: "retrying",
|
|
2756
|
+
retryCount: attempt,
|
|
2757
|
+
lastError: err?.message ?? String(err),
|
|
2758
|
+
});
|
|
2759
|
+
}
|
|
2136
2760
|
if (attempt % 10 === 0) {
|
|
2137
2761
|
this.logger.warn({ id, attempt }, "Adapter restart still failing");
|
|
2138
2762
|
}
|
|
@@ -2168,6 +2792,49 @@ export class FleetManager {
|
|
|
2168
2792
|
}
|
|
2169
2793
|
return generals[0];
|
|
2170
2794
|
}
|
|
2795
|
+
/**
|
|
2796
|
+
* A user reacted to one of the bot's messages (#408).
|
|
2797
|
+
*
|
|
2798
|
+
* A reaction is context, not a message (#432, reworking #413): it never triggers
|
|
2799
|
+
* an agent turn and never wakes anything. It is queued in the event log and rides
|
|
2800
|
+
* into the instance's NEXT real message as one compact leading line —
|
|
2801
|
+
* `[Recent reactions: 👍×2 from hanhanv]` — after which it is marked consumed.
|
|
2802
|
+
* No pending reactions → no line → zero context spent, which is the common case.
|
|
2803
|
+
*/
|
|
2804
|
+
async handleInboundReaction(r) {
|
|
2805
|
+
const instanceName = this.resolveSlashTarget(r.threadId ?? r.chatId, r.adapterId);
|
|
2806
|
+
if (!instanceName) {
|
|
2807
|
+
this.logger.debug({ emoji: r.emoji, chatId: r.chatId }, "Reaction in an unrouted channel — ignoring");
|
|
2808
|
+
return;
|
|
2809
|
+
}
|
|
2810
|
+
if (DELIVERY_STATUS_EMOJIS.has(r.emoji)) {
|
|
2811
|
+
this.logger.debug({ emoji: r.emoji, user: r.username }, "Ignoring delivery-status emoji as a reaction");
|
|
2812
|
+
return;
|
|
2813
|
+
}
|
|
2814
|
+
this.eventLog?.logActivity("reaction", r.username, `${r.emoji} ${r.action}`, instanceName);
|
|
2815
|
+
if (r.action === "add") {
|
|
2816
|
+
this.eventLog?.addReaction(instanceName, r.messageId, r.username, r.emoji);
|
|
2817
|
+
}
|
|
2818
|
+
else {
|
|
2819
|
+
// Withdrawn before anyone saw it → it never happened. See removeReaction.
|
|
2820
|
+
this.eventLog?.removeReaction(instanceName, r.messageId, r.username, r.emoji);
|
|
2821
|
+
}
|
|
2822
|
+
}
|
|
2823
|
+
/**
|
|
2824
|
+
* The queued-reaction summary for an instance's next real message, or {} when
|
|
2825
|
+
* nothing is pending (the common case must add zero context). The consume
|
|
2826
|
+
* callback is separate from the fetch so reactions are only marked once the
|
|
2827
|
+
* message actually went out — a failed delivery keeps them queued.
|
|
2828
|
+
*/
|
|
2829
|
+
pendingReactionsMeta(instanceName) {
|
|
2830
|
+
const pending = this.eventLog?.pendingReactions(instanceName);
|
|
2831
|
+
if (!pending)
|
|
2832
|
+
return { meta: {}, consume: () => { } };
|
|
2833
|
+
return {
|
|
2834
|
+
meta: { pending_reactions: pending.summary },
|
|
2835
|
+
consume: () => this.eventLog?.markReactionsConsumed(instanceName, pending.maxId),
|
|
2836
|
+
};
|
|
2837
|
+
}
|
|
2171
2838
|
async handleInboundMessage(msg) {
|
|
2172
2839
|
const threadId = msg.threadId || undefined;
|
|
2173
2840
|
this.logger.debug({ source: msg.source, chatId: msg.chatId, threadId, userId: msg.userId, isBotMessage: msg.isBotMessage, textLen: (msg.text ?? "").length, text: (msg.text ?? "").slice(0, 80) }, "handleInboundMessage entry");
|
|
@@ -2505,6 +3172,7 @@ export class FleetManager {
|
|
|
2505
3172
|
}
|
|
2506
3173
|
this.warnIfRateLimited(generalInstance, msg);
|
|
2507
3174
|
const { text, extraMeta } = await processAttachments(msg, inboundAdapter, this.logger, generalInstance);
|
|
3175
|
+
const generalReactions = this.pendingReactionsMeta(generalInstance);
|
|
2508
3176
|
try {
|
|
2509
3177
|
await this.deliverToInstance(generalInstance, {
|
|
2510
3178
|
type: "fleet_inbound",
|
|
@@ -2520,9 +3188,11 @@ export class FleetManager {
|
|
|
2520
3188
|
adapter_id: msg.adapterId,
|
|
2521
3189
|
source: msg.source,
|
|
2522
3190
|
...(msg.replyToText ? { reply_to_text: msg.replyToText } : {}),
|
|
3191
|
+
...generalReactions.meta,
|
|
2523
3192
|
...extraMeta,
|
|
2524
3193
|
},
|
|
2525
3194
|
});
|
|
3195
|
+
generalReactions.consume();
|
|
2526
3196
|
this.lastInboundUser.set(generalInstance, msg.username);
|
|
2527
3197
|
this.logger.info(`${msg.username} → ${generalInstance}: ${(text ?? "").slice(0, 100)}`);
|
|
2528
3198
|
this.eventLog?.logActivity("message", msg.username, (text ?? "").slice(0, 200), generalInstance);
|
|
@@ -2598,6 +3268,7 @@ export class FleetManager {
|
|
|
2598
3268
|
this.setTopicIcon(instanceName, "blue");
|
|
2599
3269
|
this.warnIfRateLimited(instanceName, msg);
|
|
2600
3270
|
const { text, extraMeta } = await processAttachments(msg, inboundAdapter, this.logger, instanceName);
|
|
3271
|
+
const reactions = this.pendingReactionsMeta(instanceName);
|
|
2601
3272
|
try {
|
|
2602
3273
|
await this.deliverToInstance(instanceName, {
|
|
2603
3274
|
type: "fleet_inbound",
|
|
@@ -2613,9 +3284,13 @@ export class FleetManager {
|
|
|
2613
3284
|
adapter_id: msg.adapterId,
|
|
2614
3285
|
source: msg.source,
|
|
2615
3286
|
...(msg.replyToText ? { reply_to_text: msg.replyToText } : {}),
|
|
3287
|
+
...reactions.meta,
|
|
2616
3288
|
...extraMeta,
|
|
2617
3289
|
},
|
|
2618
3290
|
});
|
|
3291
|
+
// Only after the message actually went out. A failed delivery keeps the
|
|
3292
|
+
// reactions queued for the retry / the next message.
|
|
3293
|
+
reactions.consume();
|
|
2619
3294
|
}
|
|
2620
3295
|
catch (err) {
|
|
2621
3296
|
this.logger.warn({ err: err.message, instanceName }, "Wake/delivery failed");
|
|
@@ -2690,8 +3365,21 @@ export class FleetManager {
|
|
|
2690
3365
|
: (senderSessionName ? undefined : this.fleetConfig?.instances[instanceName]);
|
|
2691
3366
|
let threadId = resolveReplyThreadId(args.thread_id, routingConfig)
|
|
2692
3367
|
?? this.classicChannels?.getChannelIdByInstance(senderInstanceName ?? instanceName);
|
|
2693
|
-
// Select adapter
|
|
2694
|
-
|
|
3368
|
+
// Select the adapter from the daemon's exact last-inbound context. Message
|
|
3369
|
+
// ids are scoped to that bot/world; routing a secondary-world id through the
|
|
3370
|
+
// primary adapter produces a 404. Instance binding remains the compatibility
|
|
3371
|
+
// fallback for older daemons and calls without a live/persisted context.
|
|
3372
|
+
const contextAdapterId = typeof msg.adapterId === "string" && msg.adapterId
|
|
3373
|
+
? msg.adapterId
|
|
3374
|
+
: undefined;
|
|
3375
|
+
const contextWorld = contextAdapterId ? this.worlds.get(contextAdapterId) : undefined;
|
|
3376
|
+
if (contextAdapterId && !contextWorld) {
|
|
3377
|
+
respond(null, `Adapter world unavailable: ${contextAdapterId}`);
|
|
3378
|
+
return;
|
|
3379
|
+
}
|
|
3380
|
+
const outAdapter = contextWorld?.adapter
|
|
3381
|
+
?? this.getAdapterForInstance(senderInstanceName ?? instanceName)
|
|
3382
|
+
?? this.adapter;
|
|
2695
3383
|
if (!outAdapter) {
|
|
2696
3384
|
respond(null, "No adapter available");
|
|
2697
3385
|
return;
|
|
@@ -2704,25 +3392,33 @@ export class FleetManager {
|
|
|
2704
3392
|
delete args.thread_id;
|
|
2705
3393
|
threadId = undefined;
|
|
2706
3394
|
}
|
|
3395
|
+
// Reply dedup: retries land here when the agent was told a send failed
|
|
3396
|
+
// (daemon budget elapsed, shell tool killed) while the adapter send was
|
|
3397
|
+
// still in flight and about to succeed. One real send, everyone gets its
|
|
3398
|
+
// outcome; a genuinely failed send clears the entry so a retry passes.
|
|
3399
|
+
if (tool === "reply") {
|
|
3400
|
+
const ticket = this.replyDeduper.begin(instanceName, String(args.text ?? ""), Array.isArray(args.files) ? args.files : []);
|
|
3401
|
+
if (ticket.duplicate) {
|
|
3402
|
+
this.logger.info({ instanceName }, "Duplicate reply suppressed — replaying the original send's outcome");
|
|
3403
|
+
ticket.subscribe(respond);
|
|
3404
|
+
return;
|
|
3405
|
+
}
|
|
3406
|
+
const original = respond;
|
|
3407
|
+
const respondAndRecord = (result, error) => {
|
|
3408
|
+
ticket.complete(result, error);
|
|
3409
|
+
original(result, error);
|
|
3410
|
+
};
|
|
3411
|
+
if (routeToolCall(outAdapter, tool, args, threadId, respondAndRecord)) {
|
|
3412
|
+
this.afterReplyRouted(instanceName, args, senderSessionName);
|
|
3413
|
+
return;
|
|
3414
|
+
}
|
|
3415
|
+
// routeToolCall knows "reply"; not handling it means the world changed.
|
|
3416
|
+
ticket.complete(null, "reply not handled");
|
|
3417
|
+
original(null, "reply not handled");
|
|
3418
|
+
return;
|
|
3419
|
+
}
|
|
2707
3420
|
// Route standard channel tools (reply, react, edit_message, download_attachment)
|
|
2708
3421
|
if (routeToolCall(outAdapter, tool, args, threadId, respond)) {
|
|
2709
|
-
if (tool === "reply") {
|
|
2710
|
-
// Agent answered — retire its pending cancel button and mark ✅ done.
|
|
2711
|
-
this.clearCancelButton(instanceName);
|
|
2712
|
-
this.reactDone(instanceName);
|
|
2713
|
-
const replyTo = this.lastInboundUser.get(instanceName) ?? "user";
|
|
2714
|
-
this.logger.info(`${instanceName} → ${replyTo}: ${(args.text ?? "").slice(0, 100)}`);
|
|
2715
|
-
this.emitSseEvent("message", {
|
|
2716
|
-
instance: instanceName, sender: senderSessionName ?? instanceName,
|
|
2717
|
-
text: (args.text ?? "").slice(0, 2000),
|
|
2718
|
-
ts: new Date().toISOString(),
|
|
2719
|
-
});
|
|
2720
|
-
// Log bot reply to classic instance chat-log
|
|
2721
|
-
const isClassic = this.classicChannels?.getChannelIdByInstance(instanceName) !== undefined;
|
|
2722
|
-
if (isClassic) {
|
|
2723
|
-
ClassicChannelManager.logMessage(instanceName, "bot", args.text ?? "", new Date());
|
|
2724
|
-
}
|
|
2725
|
-
}
|
|
2726
3422
|
return;
|
|
2727
3423
|
}
|
|
2728
3424
|
// Log tool calls for activity visualization
|
|
@@ -2737,6 +3433,35 @@ export class FleetManager {
|
|
|
2737
3433
|
respond(null, `Unknown tool: ${tool}`);
|
|
2738
3434
|
}
|
|
2739
3435
|
}
|
|
3436
|
+
/** Side effects of a routed reply: cancel-button lifecycle, logs, SSE, chat log. */
|
|
3437
|
+
afterReplyRouted(instanceName, args, senderSessionName) {
|
|
3438
|
+
// A reply is NOT proof the turn is over (#410) — but it is not proof of
|
|
3439
|
+
// more work either. Split the difference: an instance that is clearly
|
|
3440
|
+
// idle loses the button now; one that looks busy keeps it (re-posted
|
|
3441
|
+
// below the reply so it stays last in the channel), with a 2-minute
|
|
3442
|
+
// grace check — if it has NOT resumed working by then, the reply was the
|
|
3443
|
+
// end of the turn and the button goes. A multi-step run that keeps
|
|
3444
|
+
// working sails through the check and keeps its button.
|
|
3445
|
+
if (this.getInstanceIdle(instanceName)) {
|
|
3446
|
+
this.clearCancelButton(instanceName);
|
|
3447
|
+
}
|
|
3448
|
+
else {
|
|
3449
|
+
void this.sendCancelButton(instanceName).then(() => this.armReplyGrace(instanceName));
|
|
3450
|
+
}
|
|
3451
|
+
this.reactDone(instanceName);
|
|
3452
|
+
const replyTo = this.lastInboundUser.get(instanceName) ?? "user";
|
|
3453
|
+
this.logger.info(`${instanceName} → ${replyTo}: ${(args.text ?? "").slice(0, 100)}`);
|
|
3454
|
+
this.emitSseEvent("message", {
|
|
3455
|
+
instance: instanceName, sender: senderSessionName ?? instanceName,
|
|
3456
|
+
text: (args.text ?? "").slice(0, 2000),
|
|
3457
|
+
ts: new Date().toISOString(),
|
|
3458
|
+
});
|
|
3459
|
+
// Log bot reply to classic instance chat-log
|
|
3460
|
+
const isClassic = this.classicChannels?.getChannelIdByInstance(instanceName) !== undefined;
|
|
3461
|
+
if (isClassic) {
|
|
3462
|
+
ClassicChannelManager.logMessage(instanceName, "bot", args.text ?? "", new Date());
|
|
3463
|
+
}
|
|
3464
|
+
}
|
|
2740
3465
|
/** Handle tool status update from a daemon instance */
|
|
2741
3466
|
handleToolStatusFromInstance(instanceName, msg) {
|
|
2742
3467
|
const statusAdapter = this.getAdapterForInstance(instanceName) ?? this.adapter;
|
|
@@ -3274,7 +3999,12 @@ export class FleetManager {
|
|
|
3274
3999
|
// the before/after runtime diff cannot observe.
|
|
3275
4000
|
for (const patch of explicitPatches) {
|
|
3276
4001
|
if (patch.remove) {
|
|
3277
|
-
|
|
4002
|
+
// YAML's deleteIn throws when an inherited nested key has no raw parent
|
|
4003
|
+
// (or a legacy scalar occupies that parent). Removing an override which
|
|
4004
|
+
// is already absent is an idempotent no-op, not a failed Settings save.
|
|
4005
|
+
if (this.rawFleetDocument.hasIn(patch.path)) {
|
|
4006
|
+
this.rawFleetDocument.deleteIn(patch.path);
|
|
4007
|
+
}
|
|
3278
4008
|
}
|
|
3279
4009
|
else {
|
|
3280
4010
|
const before = this.rawFleetDocument.getIn(patch.path);
|
|
@@ -3300,8 +4030,11 @@ export class FleetManager {
|
|
|
3300
4030
|
this.patchFleetDocument(document, [...path, i], before[i], after[i]);
|
|
3301
4031
|
}
|
|
3302
4032
|
// Remove from the end so YAML sequence indexes do not shift underneath us.
|
|
3303
|
-
for (let i = before.length - 1; i >= after.length; i--)
|
|
3304
|
-
|
|
4033
|
+
for (let i = before.length - 1; i >= after.length; i--) {
|
|
4034
|
+
const itemPath = [...path, i];
|
|
4035
|
+
if (document.hasIn(itemPath))
|
|
4036
|
+
document.deleteIn(itemPath);
|
|
4037
|
+
}
|
|
3305
4038
|
for (let i = shared; i < after.length; i++)
|
|
3306
4039
|
document.setIn([...path, i], after[i]);
|
|
3307
4040
|
return;
|
|
@@ -3323,7 +4056,11 @@ export class FleetManager {
|
|
|
3323
4056
|
return;
|
|
3324
4057
|
}
|
|
3325
4058
|
if (after === undefined) {
|
|
3326
|
-
|
|
4059
|
+
// Effective config contains inherited objects that may not exist in the
|
|
4060
|
+
// raw YAML at all. yaml.deleteIn() is not idempotent for a missing nested
|
|
4061
|
+
// parent, so guard it explicitly.
|
|
4062
|
+
if (document.hasIn(path))
|
|
4063
|
+
document.deleteIn(path);
|
|
3327
4064
|
}
|
|
3328
4065
|
else if (path.length === 0) {
|
|
3329
4066
|
document.contents = document.createNode(after);
|
|
@@ -3339,6 +4076,9 @@ export class FleetManager {
|
|
|
3339
4076
|
}
|
|
3340
4077
|
}
|
|
3341
4078
|
async removeInstance(name) {
|
|
4079
|
+
// Drop cached pane context — the map is keyed by instance name and nothing
|
|
4080
|
+
// else evicted deleted entries, so it grew for the life of the process.
|
|
4081
|
+
forgetInstanceContext(name);
|
|
3342
4082
|
// Clean up schedules (scheduler is fleet-level, not lifecycle-level)
|
|
3343
4083
|
const config = this.fleetConfig?.instances[name];
|
|
3344
4084
|
if (this.scheduler && config?.topic_id) {
|
|
@@ -3444,11 +4184,176 @@ export class FleetManager {
|
|
|
3444
4184
|
this.collabInstances.add(instanceName);
|
|
3445
4185
|
return true;
|
|
3446
4186
|
}
|
|
4187
|
+
/**
|
|
4188
|
+
* Open the event log, tolerating a corrupt file.
|
|
4189
|
+
*
|
|
4190
|
+
* `events.db` holds history only — event rows and the activity feed. Nothing the
|
|
4191
|
+
* fleet needs to run depends on it, and every consumer already uses
|
|
4192
|
+
* `this.eventLog?.`. An unguarded `new EventLog(...)` here meant a corrupt or
|
|
4193
|
+
* unreadable history file (a truncated WAL after a hard kill, a full disk)
|
|
4194
|
+
* threw during startAll and the WHOLE FLEET FAILED TO BOOT — trading every
|
|
4195
|
+
* running agent for a file whose only job is reporting.
|
|
4196
|
+
*
|
|
4197
|
+
* So: try, move a bad file aside and retry once with a fresh one, and if even
|
|
4198
|
+
* that fails carry on without an event log.
|
|
4199
|
+
*/
|
|
4200
|
+
/**
|
|
4201
|
+
* Run `agend backend doctor` for the fleet's default backend and return its
|
|
4202
|
+
* cleaned output.
|
|
4203
|
+
*
|
|
4204
|
+
* Async on purpose: this was `execSync` with a 30s timeout, reachable by any
|
|
4205
|
+
* allowlisted user through `/doctor`. While it ran, the entire fleet event loop
|
|
4206
|
+
* was frozen — no IPC, no adapter, no message delivery, no health responses,
|
|
4207
|
+
* and critically no WATCHDOG ping, so a slow doctor could push past
|
|
4208
|
+
* WatchdogSec and have systemd SIGABRT the fleet.
|
|
4209
|
+
*/
|
|
4210
|
+
async runBackendDoctor() {
|
|
4211
|
+
const stripAnsi = (s) => s.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, "");
|
|
4212
|
+
const backend = this.fleetConfig?.defaults?.backend || "claude-code";
|
|
4213
|
+
try {
|
|
4214
|
+
const { execFile } = await import("node:child_process");
|
|
4215
|
+
const { promisify } = await import("node:util");
|
|
4216
|
+
// execFile with an argv array — no shell, so the backend name cannot be
|
|
4217
|
+
// interpreted as a command even if config is malformed.
|
|
4218
|
+
const { stdout } = await promisify(execFile)("agend", ["backend", "doctor", backend], {
|
|
4219
|
+
timeout: 30_000,
|
|
4220
|
+
encoding: "utf-8",
|
|
4221
|
+
});
|
|
4222
|
+
return stripAnsi(stdout) || "No output";
|
|
4223
|
+
}
|
|
4224
|
+
catch (err) {
|
|
4225
|
+
const e = err;
|
|
4226
|
+
return stripAnsi(e.stdout ?? e.message ?? "Doctor failed");
|
|
4227
|
+
}
|
|
4228
|
+
}
|
|
4229
|
+
/** Drop event/activity rows older than the retention window. Best-effort. */
|
|
4230
|
+
/**
|
|
4231
|
+
* Cap every instance's pipe-pane log, walking the instances **directory** rather
|
|
4232
|
+
* than the config.
|
|
4233
|
+
*
|
|
4234
|
+
* A running instance rotates its own log on each health tick, so the ones that
|
|
4235
|
+
* need this are the ones nothing else looks at:
|
|
4236
|
+
*
|
|
4237
|
+
* - deleted instances, whose directory outlives the config entry. Nothing ever
|
|
4238
|
+
* touched these again. On the machine this was found on, one held 122 MB and
|
|
4239
|
+
* another 74 MB, out of 622 MB of pipe-pane logs in total.
|
|
4240
|
+
* - classic instances, which live in classicChannels, not fleetConfig.instances,
|
|
4241
|
+
* and so were never in the old config-driven loop at all.
|
|
4242
|
+
* - stopped instances, which have no health tick running.
|
|
4243
|
+
*
|
|
4244
|
+
* pipe-pane writes raw TUI output, so a wedged splash screen can emit ANSI frames
|
|
4245
|
+
* at animation rate. Unbounded growth here fills the disk, which takes the whole
|
|
4246
|
+
* fleet down rather than one instance.
|
|
4247
|
+
*/
|
|
4248
|
+
rotateAllInstanceLogs() {
|
|
4249
|
+
const root = join(this.dataDir, "instances");
|
|
4250
|
+
let entries;
|
|
4251
|
+
try {
|
|
4252
|
+
entries = readdirSync(root, { withFileTypes: true });
|
|
4253
|
+
}
|
|
4254
|
+
catch {
|
|
4255
|
+
return; // no instances directory yet
|
|
4256
|
+
}
|
|
4257
|
+
for (const entry of entries) {
|
|
4258
|
+
if (!entry.isDirectory())
|
|
4259
|
+
continue;
|
|
4260
|
+
// rotateLogIfNeeded is already best-effort and returns early on a missing
|
|
4261
|
+
// file, so a directory without a pipe-pane log costs one stat.
|
|
4262
|
+
rotateLogIfNeeded(join(root, entry.name, "output.log"));
|
|
4263
|
+
}
|
|
4264
|
+
}
|
|
4265
|
+
pruneEventLog() {
|
|
4266
|
+
try {
|
|
4267
|
+
this.eventLog?.prune(FleetManager.EVENT_LOG_RETENTION_DAYS);
|
|
4268
|
+
}
|
|
4269
|
+
catch (err) {
|
|
4270
|
+
this.logger.warn({ err }, "Event log prune failed");
|
|
4271
|
+
}
|
|
4272
|
+
}
|
|
4273
|
+
openEventLog() {
|
|
4274
|
+
const dbPath = join(this.dataDir, "events.db");
|
|
4275
|
+
try {
|
|
4276
|
+
return new EventLog(dbPath);
|
|
4277
|
+
}
|
|
4278
|
+
catch (err) {
|
|
4279
|
+
this.logger.error({ err, dbPath }, "events.db unusable — moving it aside and starting a fresh one");
|
|
4280
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
|
|
4281
|
+
for (const suffix of ["", "-wal", "-shm"]) {
|
|
4282
|
+
try {
|
|
4283
|
+
renameSync(`${dbPath}${suffix}`, `${dbPath}${suffix}.corrupt-${stamp}`);
|
|
4284
|
+
}
|
|
4285
|
+
catch { /* may not exist */ }
|
|
4286
|
+
}
|
|
4287
|
+
try {
|
|
4288
|
+
return new EventLog(dbPath);
|
|
4289
|
+
}
|
|
4290
|
+
catch (retryErr) {
|
|
4291
|
+
// History is worth losing; a fleet that won't start is not.
|
|
4292
|
+
this.logger.error({ err: retryErr, dbPath }, "Could not open a fresh events.db — continuing without event logging");
|
|
4293
|
+
return null;
|
|
4294
|
+
}
|
|
4295
|
+
}
|
|
4296
|
+
}
|
|
4297
|
+
/**
|
|
4298
|
+
* Report a fleet-level fault (not attributable to one instance) to the General
|
|
4299
|
+
* topic, so the operator learns about it without reading daemon.log.
|
|
4300
|
+
*
|
|
4301
|
+
* Throttled per distinct message: an unhandled rejection typically comes from a
|
|
4302
|
+
* loop (a poller, a repeating timer), and one channel message per occurrence
|
|
4303
|
+
* would bury the topic — which is worse than silence. First occurrence goes out
|
|
4304
|
+
* immediately, repeats are suppressed for THROTTLE_MS and then re-sent with a
|
|
4305
|
+
* count.
|
|
4306
|
+
*
|
|
4307
|
+
* The log line is written by the caller regardless: if every adapter is down,
|
|
4308
|
+
* the only notification path is the one that is broken.
|
|
4309
|
+
*/
|
|
4310
|
+
notifyFleetError(text) {
|
|
4311
|
+
const now = Date.now();
|
|
4312
|
+
const key = text.slice(0, 200);
|
|
4313
|
+
const seen = this.fleetErrorNotices.get(key);
|
|
4314
|
+
if (seen && now - seen.at < FleetManager.FLEET_ERROR_THROTTLE_MS) {
|
|
4315
|
+
seen.suppressed++;
|
|
4316
|
+
return;
|
|
4317
|
+
}
|
|
4318
|
+
const suppressed = seen?.suppressed ?? 0;
|
|
4319
|
+
this.fleetErrorNotices.set(key, { at: now, suppressed: 0 });
|
|
4320
|
+
// Bound the map: it is keyed by message text, and a message with a varying
|
|
4321
|
+
// suffix (a path, an id) would otherwise grow it without limit.
|
|
4322
|
+
if (this.fleetErrorNotices.size > 100) {
|
|
4323
|
+
const oldest = this.fleetErrorNotices.keys().next().value;
|
|
4324
|
+
if (oldest !== undefined)
|
|
4325
|
+
this.fleetErrorNotices.delete(oldest);
|
|
4326
|
+
}
|
|
4327
|
+
const body = suppressed > 0
|
|
4328
|
+
? `${text}\n(plus ${suppressed} more in the last ${Math.round(FleetManager.FLEET_ERROR_THROTTLE_MS / 60_000)}m)`
|
|
4329
|
+
: text;
|
|
4330
|
+
// Resolved from config, NOT findGeneralInstance(): that requires a live daemon,
|
|
4331
|
+
// and a fleet-level fault is exactly when the General may be down. The topic
|
|
4332
|
+
// itself still exists, and notifyInstanceTopic only needs adapter + group +
|
|
4333
|
+
// topic_id to post into it.
|
|
4334
|
+
const general = Object.entries(this.fleetConfig?.instances ?? {})
|
|
4335
|
+
.find(([, config]) => config.general_topic === true)?.[0];
|
|
4336
|
+
if (general) {
|
|
4337
|
+
this.notifyInstanceTopic(general, body);
|
|
4338
|
+
return;
|
|
4339
|
+
}
|
|
4340
|
+
// No General instance — fall back to the primary channel's group.
|
|
4341
|
+
const channelCfg = this.getChannelConfig();
|
|
4342
|
+
const groupId = channelCfg?.group_id;
|
|
4343
|
+
if (this.adapter && groupId) {
|
|
4344
|
+
this.adapter.sendText(String(groupId), body)
|
|
4345
|
+
.catch(err => this.logger.warn({ err }, "Failed to send fleet error notification"));
|
|
4346
|
+
return;
|
|
4347
|
+
}
|
|
4348
|
+
this.logger.warn({ text: body }, "Fleet error had no notification target (no General instance, no adapter)");
|
|
4349
|
+
}
|
|
4350
|
+
static FLEET_ERROR_THROTTLE_MS = 10 * 60_000;
|
|
4351
|
+
fleetErrorNotices = new Map();
|
|
3447
4352
|
notifyInstanceTopic(instanceName, text, extraOpts) {
|
|
3448
4353
|
const adapter = this.getAdapterForInstance(instanceName) ?? this.adapter;
|
|
3449
4354
|
if (!adapter)
|
|
3450
4355
|
return;
|
|
3451
|
-
const channelCfg = this.getChannelConfig(this.
|
|
4356
|
+
const channelCfg = this.getChannelConfig(this.getInstanceAdapterId(instanceName));
|
|
3452
4357
|
const groupId = channelCfg?.group_id;
|
|
3453
4358
|
// Fleet topic instance
|
|
3454
4359
|
const threadId = this.fleetConfig?.instances[instanceName]?.topic_id;
|
|
@@ -3517,6 +4422,40 @@ export class FleetManager {
|
|
|
3517
4422
|
await data.respond(t("save.sent", cmd, target.name));
|
|
3518
4423
|
}
|
|
3519
4424
|
/** Whether the instance currently has at least one live cancel button. */
|
|
4425
|
+
/**
|
|
4426
|
+
* A click on a cancel button, whether or not the fleet still tracks it.
|
|
4427
|
+
*
|
|
4428
|
+
* The old rule was "act only while an entry is live", which made a click on a
|
|
4429
|
+
* button the fleet had forgotten a silent no-op — no cancel, no message, not
|
|
4430
|
+
* even a log line. That is indistinguishable from a broken button, and it is
|
|
4431
|
+
* what the "按鈕點了沒反應" reports were: the entry is briefly absent while a
|
|
4432
|
+
* button is being replaced, and a delete that fails leaves the message on
|
|
4433
|
+
* screen with no entry at all.
|
|
4434
|
+
*
|
|
4435
|
+
* So: honour the click if the instance is actually running, and say so plainly
|
|
4436
|
+
* if it is not. The stale-click path is rate-limited because the original
|
|
4437
|
+
* concern was real — a second click must not fire a second interrupt key at an
|
|
4438
|
+
* instance that has already started a new turn.
|
|
4439
|
+
*/
|
|
4440
|
+
handleCancelClick(instanceName, adapter, data) {
|
|
4441
|
+
if (this.hasCancelButton(instanceName)) {
|
|
4442
|
+
this.cancelInstance(instanceName);
|
|
4443
|
+
return;
|
|
4444
|
+
}
|
|
4445
|
+
const lastAt = this.staleCancelClickAt.get(instanceName) ?? 0;
|
|
4446
|
+
if (Date.now() - lastAt < STALE_CANCEL_CLICK_COOLDOWN_MS)
|
|
4447
|
+
return;
|
|
4448
|
+
this.staleCancelClickAt.set(instanceName, Date.now());
|
|
4449
|
+
// cancelInstance returns false when there is no daemon — i.e. nothing to
|
|
4450
|
+
// cancel, which is the one case where the button really is dead.
|
|
4451
|
+
if (this.cancelInstance(instanceName)) {
|
|
4452
|
+
this.logger.info({ instanceName }, "Cancel click honoured with no live button entry");
|
|
4453
|
+
return;
|
|
4454
|
+
}
|
|
4455
|
+
this.logger.info({ instanceName }, "Cancel click on an expired button — instance not running");
|
|
4456
|
+
adapter?.editMessage(data.chatId, data.messageId, t("cancel.button_stale", instanceName), data.threadId)
|
|
4457
|
+
.catch(() => { });
|
|
4458
|
+
}
|
|
3520
4459
|
hasCancelButton(instanceName) {
|
|
3521
4460
|
for (const e of this.cancelButtons.values()) {
|
|
3522
4461
|
if (e.instanceName === instanceName)
|
|
@@ -3525,15 +4464,22 @@ export class FleetManager {
|
|
|
3525
4464
|
return false;
|
|
3526
4465
|
}
|
|
3527
4466
|
async sendCancelButton(instanceName, correlationId) {
|
|
3528
|
-
//
|
|
3529
|
-
//
|
|
3530
|
-
//
|
|
3531
|
-
|
|
4467
|
+
// Post first, retire after (see the tail of this method). Retiring up front
|
|
4468
|
+
// meant that from the delete until the new message came back — a chat API
|
|
4469
|
+
// round trip, and every reply goes through here — the instance had NO live
|
|
4470
|
+
// entry, while the old button was still on screen. A click in that window
|
|
4471
|
+
// hit `hasCancelButton() === false` and was silently dropped: the reported
|
|
4472
|
+
// "按鈕失效". If notifyAlert then failed, the button was simply gone.
|
|
3532
4473
|
const adapter = this.getAdapterForInstance(instanceName) ?? this.adapter;
|
|
3533
4474
|
if (!adapter)
|
|
3534
4475
|
return;
|
|
3535
|
-
|
|
3536
|
-
|
|
4476
|
+
// Resolve the group through the world fallback (first world when unbound),
|
|
4477
|
+
// NOT through getChannelConfig(binding)?.group_id: on a fleet configured with
|
|
4478
|
+
// `channels:` worlds the primary `channel:` block is empty, so an instance
|
|
4479
|
+
// with no world binding yet (fresh restart, cross-instance delegation)
|
|
4480
|
+
// resolved group_id to undefined and the button silently never appeared.
|
|
4481
|
+
const adapterId = this.getInstanceAdapterId(instanceName);
|
|
4482
|
+
const groupId = this.getGroupIdForInstance(instanceName) || undefined;
|
|
3537
4483
|
const topicId = this.fleetConfig?.instances[instanceName]?.topic_id;
|
|
3538
4484
|
let chatId;
|
|
3539
4485
|
let threadId;
|
|
@@ -3549,8 +4495,12 @@ export class FleetManager {
|
|
|
3549
4495
|
if (!chatId && groupId)
|
|
3550
4496
|
chatId = String(groupId);
|
|
3551
4497
|
}
|
|
3552
|
-
if (!chatId)
|
|
4498
|
+
if (!chatId) {
|
|
4499
|
+
// A button that cannot be addressed must say so — this exact silence is how
|
|
4500
|
+
// "the cancel button sometimes never appears" stayed unreported-in-logs.
|
|
4501
|
+
this.logger.warn({ instanceName, topicId, groupId }, "Cannot address cancel button (no chat id resolved)");
|
|
3553
4502
|
return;
|
|
4503
|
+
}
|
|
3554
4504
|
try {
|
|
3555
4505
|
const sent = await adapter.notifyAlert(chatId, {
|
|
3556
4506
|
type: "cancel",
|
|
@@ -3558,13 +4508,6 @@ export class FleetManager {
|
|
|
3558
4508
|
message: "👀 處理中…",
|
|
3559
4509
|
choices: [{ id: `cancel:${instanceName}`, label: t("cancel.button") }],
|
|
3560
4510
|
}, threadId ? { threadId } : undefined);
|
|
3561
|
-
// A concurrent sendCancelButton for the same instance may have posted its
|
|
3562
|
-
// own button while we awaited notifyAlert. Retire any other buttons for
|
|
3563
|
-
// this instance (not the one we just posted) so only the newest shows.
|
|
3564
|
-
for (const other of this.cancelButtons.values()) {
|
|
3565
|
-
if (other.instanceName === instanceName)
|
|
3566
|
-
this.retireButton(other);
|
|
3567
|
-
}
|
|
3568
4511
|
const entry = {
|
|
3569
4512
|
instanceName,
|
|
3570
4513
|
adapterId,
|
|
@@ -3573,7 +4516,16 @@ export class FleetManager {
|
|
|
3573
4516
|
threadId: sent.threadId ?? threadId,
|
|
3574
4517
|
correlationId,
|
|
3575
4518
|
retryCount: 0,
|
|
4519
|
+
// Elapsed time is measured from when this button was posted — i.e. from
|
|
4520
|
+
// when the work was handed over — not from the pane's working transition,
|
|
4521
|
+
// which resets if the CLI blips idle mid-turn.
|
|
4522
|
+
startedAt: Date.now(),
|
|
4523
|
+
// Matches the text notifyAlert just posted, so the first 60s tick does
|
|
4524
|
+
// not re-edit identical text — which put a "(edited)" mark on Discord
|
|
4525
|
+
// with nothing visibly changed.
|
|
4526
|
+
lastProgressText: "👀 處理中…",
|
|
3576
4527
|
};
|
|
4528
|
+
this.startProgressTicker(entry);
|
|
3577
4529
|
// Idle-check backstop: every 5min, if the instance is idle, retire the
|
|
3578
4530
|
// button. Covers turns that end without hitting a clear trigger (reply /
|
|
3579
4531
|
// cancel / correlation). Cleared in discardButton when the entry is removed.
|
|
@@ -3582,18 +4534,167 @@ export class FleetManager {
|
|
|
3582
4534
|
clearInterval(entry.idleCheckTimer);
|
|
3583
4535
|
return;
|
|
3584
4536
|
}
|
|
3585
|
-
|
|
3586
|
-
this.
|
|
4537
|
+
const reason = this.getInstanceIdle(instanceName) ? "idle"
|
|
4538
|
+
: this.stateReportDead(instanceName) ? "state reports stopped"
|
|
4539
|
+
: Date.now() - (entry.startedAt ?? 0) > CANCEL_BTN_MAX_LIFETIME_MS ? "24h ceiling"
|
|
4540
|
+
: null;
|
|
4541
|
+
if (reason) {
|
|
4542
|
+
this.logger.info({ instanceName, messageId: entry.messageId, reason }, "Cancel button backstop retiring");
|
|
3587
4543
|
this.retireButton(entry);
|
|
4544
|
+
return;
|
|
3588
4545
|
}
|
|
4546
|
+
// Still looks busy. The daemon only broadcasts on transitions, so ask for
|
|
4547
|
+
// a fresh snapshot — a live daemon's answer refreshes receivedAt and keeps
|
|
4548
|
+
// the staleness check honest; a dead one's silence is the evidence.
|
|
4549
|
+
this.instanceIpcClients.get(instanceName)?.send({
|
|
4550
|
+
type: "query_instance_state", requestId: `cancel-btn-${Date.now()}`,
|
|
4551
|
+
});
|
|
3589
4552
|
}, CANCEL_BTN_IDLE_CHECK_INTERVAL_MS);
|
|
3590
4553
|
this.cancelButtons.set(sent.messageId, entry);
|
|
4554
|
+
// Only now: at most one button per instance, but never zero. Covers both
|
|
4555
|
+
// the previous turn's button and any button a concurrent
|
|
4556
|
+
// sendCancelButton posted while we were awaiting notifyAlert.
|
|
4557
|
+
for (const other of [...this.cancelButtons.values()]) {
|
|
4558
|
+
if (other.instanceName === instanceName && other.messageId !== sent.messageId) {
|
|
4559
|
+
this.retireButton(other);
|
|
4560
|
+
}
|
|
4561
|
+
}
|
|
4562
|
+
this.persistCancelButtons();
|
|
3591
4563
|
this.logger.info({ instanceName, messageId: sent.messageId }, "Cancel button sent");
|
|
3592
4564
|
}
|
|
3593
4565
|
catch (e) {
|
|
3594
4566
|
this.logger.warn({ err: e.message, instanceName }, "Failed to send cancel button");
|
|
3595
4567
|
}
|
|
3596
4568
|
}
|
|
4569
|
+
/**
|
|
4570
|
+
* The cancel button's text for a given elapsed time.
|
|
4571
|
+
*
|
|
4572
|
+
* Below the threshold it keeps the original wording, so a normal quick answer
|
|
4573
|
+
* looks exactly as it did before. Past it, the button doubles as the live
|
|
4574
|
+
* progress indicator (#409) — the channel showed nothing at all during long work,
|
|
4575
|
+
* and once the agent had replied once there was no sign it was still going.
|
|
4576
|
+
*/
|
|
4577
|
+
static progressText(elapsedMs, activity, minElapsedMs = PROGRESS_MIN_ELAPSED_MS) {
|
|
4578
|
+
if (elapsedMs < minElapsedMs)
|
|
4579
|
+
return "👀 處理中…";
|
|
4580
|
+
const totalSeconds = Math.floor(elapsedMs / 1000);
|
|
4581
|
+
const minutes = Math.floor(totalSeconds / 60);
|
|
4582
|
+
const seconds = totalSeconds % 60;
|
|
4583
|
+
const elapsed = minutes >= 60
|
|
4584
|
+
? `${Math.floor(minutes / 60)}h ${minutes % 60}m`
|
|
4585
|
+
: `${minutes}m ${String(seconds).padStart(2, "0")}s`;
|
|
4586
|
+
const detail = FleetManager.sanitizeActivity(activity);
|
|
4587
|
+
return detail
|
|
4588
|
+
? `⏳ 處理中… (已進行 ${elapsed} · ${detail})`
|
|
4589
|
+
: `⏳ 處理中… (已進行 ${elapsed})`;
|
|
4590
|
+
}
|
|
4591
|
+
/**
|
|
4592
|
+
* Make a tool summary safe to paste into a channel message.
|
|
4593
|
+
*
|
|
4594
|
+
* The text is agent-controlled (it is built from tool inputs — file paths,
|
|
4595
|
+
* shell commands), so it gets flattened to one line, capped, and stripped of
|
|
4596
|
+
* the two Discord mass-mention triggers. Neither channel renders it with a
|
|
4597
|
+
* parse mode, so no markup escaping is needed beyond that.
|
|
4598
|
+
*/
|
|
4599
|
+
static sanitizeActivity(activity) {
|
|
4600
|
+
if (!activity)
|
|
4601
|
+
return null;
|
|
4602
|
+
const flat = activity.replace(/\s+/g, " ").replace(/@(everyone|here)/g, "@$1").trim();
|
|
4603
|
+
if (!flat)
|
|
4604
|
+
return null;
|
|
4605
|
+
return flat.length > PROGRESS_ACTIVITY_MAX_CHARS
|
|
4606
|
+
? `${flat.slice(0, PROGRESS_ACTIVITY_MAX_CHARS - 1)}…`
|
|
4607
|
+
: flat;
|
|
4608
|
+
}
|
|
4609
|
+
/**
|
|
4610
|
+
* Remember what an instance is currently doing, for the progress line.
|
|
4611
|
+
*
|
|
4612
|
+
* Best-effort by design: only backends that expose a live activity feed report
|
|
4613
|
+
* anything, and the progress line simply omits the detail for the rest. It is
|
|
4614
|
+
* never used to decide anything — purely what the user is shown.
|
|
4615
|
+
*/
|
|
4616
|
+
cacheInstanceActivity(name, activity) {
|
|
4617
|
+
if (activity)
|
|
4618
|
+
this.instanceActivity.set(name, activity);
|
|
4619
|
+
else
|
|
4620
|
+
this.instanceActivity.delete(name);
|
|
4621
|
+
}
|
|
4622
|
+
/**
|
|
4623
|
+
* Refresh the button's text in place while the instance keeps working.
|
|
4624
|
+
*
|
|
4625
|
+
* Uses `editAlert`, NOT `editMessage`: on Telegram the latter omits reply_markup,
|
|
4626
|
+
* and the Bot API treats that as "clear the keyboard" — so editing with it would
|
|
4627
|
+
* delete the very cancel button this is trying to keep alive.
|
|
4628
|
+
*/
|
|
4629
|
+
/** Configured threshold before elapsed time appears, in ms. */
|
|
4630
|
+
progressMinElapsedMs() {
|
|
4631
|
+
const seconds = this.fleetConfig?.defaults
|
|
4632
|
+
?.progress_min_elapsed;
|
|
4633
|
+
if (typeof seconds === "number" && Number.isFinite(seconds) && seconds >= 0) {
|
|
4634
|
+
return seconds * 1000;
|
|
4635
|
+
}
|
|
4636
|
+
return PROGRESS_MIN_ELAPSED_MS;
|
|
4637
|
+
}
|
|
4638
|
+
startProgressTicker(entry) {
|
|
4639
|
+
const tick = () => {
|
|
4640
|
+
if (!this.cancelButtons.has(entry.messageId)) {
|
|
4641
|
+
clearInterval(entry.progressTimer);
|
|
4642
|
+
return;
|
|
4643
|
+
}
|
|
4644
|
+
const text = FleetManager.progressText(Date.now() - (entry.startedAt ?? Date.now()), this.instanceActivity.get(entry.instanceName), this.progressMinElapsedMs());
|
|
4645
|
+
if (text === entry.lastProgressText)
|
|
4646
|
+
return; // nothing changed — skip the API call
|
|
4647
|
+
const adapter = this.getAdapterForInstance(entry.instanceName) ?? this.adapter;
|
|
4648
|
+
if (!adapter?.editAlert)
|
|
4649
|
+
return;
|
|
4650
|
+
entry.lastProgressText = text;
|
|
4651
|
+
adapter.editAlert(entry.chatId, entry.messageId, {
|
|
4652
|
+
type: "cancel",
|
|
4653
|
+
instanceName: entry.instanceName,
|
|
4654
|
+
message: text,
|
|
4655
|
+
choices: [{ id: `cancel:${entry.instanceName}`, label: t("cancel.button") }],
|
|
4656
|
+
}, entry.threadId ? { threadId: entry.threadId } : undefined)
|
|
4657
|
+
.catch(err => {
|
|
4658
|
+
// A failed progress edit must never escalate: the button still works and
|
|
4659
|
+
// the next tick retries. Common causes are a deleted message or a
|
|
4660
|
+
// rate limit.
|
|
4661
|
+
this.logger.debug({ err, instanceName: entry.instanceName }, "Progress edit failed");
|
|
4662
|
+
});
|
|
4663
|
+
};
|
|
4664
|
+
entry.progressTimer = setInterval(tick, PROGRESS_UPDATE_INTERVAL_MS);
|
|
4665
|
+
entry.progressTimer.unref?.();
|
|
4666
|
+
// One extra tick right when the threshold passes, so a 30s threshold shows
|
|
4667
|
+
// time at ~30s instead of waiting for the first 60s interval. Costs at most
|
|
4668
|
+
// one additional edit per turn that lives past the threshold.
|
|
4669
|
+
const firstAt = this.progressMinElapsedMs() - (Date.now() - (entry.startedAt ?? Date.now()));
|
|
4670
|
+
if (firstAt > 0 && firstAt < PROGRESS_UPDATE_INTERVAL_MS) {
|
|
4671
|
+
const firstTick = setTimeout(tick, firstAt);
|
|
4672
|
+
firstTick.unref?.();
|
|
4673
|
+
}
|
|
4674
|
+
}
|
|
4675
|
+
/**
|
|
4676
|
+
* After a reply: give the instance REPLY_RETIRE_GRACE_MS to resume working; if
|
|
4677
|
+
* it has not, retire its button. Re-arming replaces the previous timer, so a
|
|
4678
|
+
* burst of replies ends with exactly one pending check.
|
|
4679
|
+
*/
|
|
4680
|
+
armReplyGrace(instanceName) {
|
|
4681
|
+
for (const entry of this.cancelButtons.values()) {
|
|
4682
|
+
if (entry.instanceName !== instanceName)
|
|
4683
|
+
continue;
|
|
4684
|
+
if (entry.replyGraceTimer)
|
|
4685
|
+
clearTimeout(entry.replyGraceTimer);
|
|
4686
|
+
entry.replyGraceTimer = setTimeout(() => {
|
|
4687
|
+
entry.replyGraceTimer = undefined;
|
|
4688
|
+
if (!this.cancelButtons.has(entry.messageId))
|
|
4689
|
+
return;
|
|
4690
|
+
if (!this.getInstanceIdle(instanceName))
|
|
4691
|
+
return; // resumed — a long run keeps its button
|
|
4692
|
+
this.logger.info({ instanceName, messageId: entry.messageId }, "Cancel button retired — no work resumed after reply");
|
|
4693
|
+
this.retireButton(entry);
|
|
4694
|
+
}, REPLY_RETIRE_GRACE_MS);
|
|
4695
|
+
entry.replyGraceTimer.unref?.();
|
|
4696
|
+
}
|
|
4697
|
+
}
|
|
3597
4698
|
/** Retire (delete) every cancel button belonging to an instance. */
|
|
3598
4699
|
retireInstanceButtons(instanceName) {
|
|
3599
4700
|
// Snapshot first — retireButton may delete entries from the map on success.
|
|
@@ -3625,7 +4726,70 @@ export class FleetManager {
|
|
|
3625
4726
|
clearTimeout(entry.retryTimer);
|
|
3626
4727
|
if (entry.idleCheckTimer)
|
|
3627
4728
|
clearInterval(entry.idleCheckTimer);
|
|
4729
|
+
if (entry.progressTimer)
|
|
4730
|
+
clearInterval(entry.progressTimer);
|
|
4731
|
+
if (entry.replyGraceTimer)
|
|
4732
|
+
clearTimeout(entry.replyGraceTimer);
|
|
3628
4733
|
this.cancelButtons.delete(entry.messageId);
|
|
4734
|
+
this.persistCancelButtons();
|
|
4735
|
+
}
|
|
4736
|
+
/**
|
|
4737
|
+
* Mirror the live buttons to disk. The map is memory-only, so before this a
|
|
4738
|
+
* fleet restart orphaned every button on screen: frozen "處理中…" text and a
|
|
4739
|
+
* click that did nothing, forever. The ledger is tiny (a handful of rows) and
|
|
4740
|
+
* written on every add/remove — no debounce needed at that rate.
|
|
4741
|
+
*/
|
|
4742
|
+
persistCancelButtons() {
|
|
4743
|
+
try {
|
|
4744
|
+
const rows = [...this.cancelButtons.values()].map(e => ({
|
|
4745
|
+
instanceName: e.instanceName,
|
|
4746
|
+
adapterId: e.adapterId,
|
|
4747
|
+
chatId: e.chatId,
|
|
4748
|
+
messageId: e.messageId,
|
|
4749
|
+
threadId: e.threadId,
|
|
4750
|
+
}));
|
|
4751
|
+
writeFileSync(join(this.dataDir, CANCEL_BTN_LEDGER_FILE), JSON.stringify(rows));
|
|
4752
|
+
}
|
|
4753
|
+
catch (err) {
|
|
4754
|
+
this.logger.debug({ err }, "Cancel button ledger write failed");
|
|
4755
|
+
}
|
|
4756
|
+
}
|
|
4757
|
+
/**
|
|
4758
|
+
* Delete the previous process's buttons. Runs once adapters are up: nothing
|
|
4759
|
+
* from a previous fleet process can still be mid-turn from this process's
|
|
4760
|
+
* point of view, so every ledger row is an orphan by definition.
|
|
4761
|
+
*/
|
|
4762
|
+
async sweepOrphanedCancelButtons() {
|
|
4763
|
+
const ledgerPath = join(this.dataDir, CANCEL_BTN_LEDGER_FILE);
|
|
4764
|
+
let rows;
|
|
4765
|
+
try {
|
|
4766
|
+
if (!existsSync(ledgerPath))
|
|
4767
|
+
return;
|
|
4768
|
+
rows = JSON.parse(readFileSync(ledgerPath, "utf-8"));
|
|
4769
|
+
}
|
|
4770
|
+
catch {
|
|
4771
|
+
try {
|
|
4772
|
+
unlinkSync(ledgerPath);
|
|
4773
|
+
}
|
|
4774
|
+
catch { /* corrupt ledger — drop it */ }
|
|
4775
|
+
return;
|
|
4776
|
+
}
|
|
4777
|
+
for (const row of rows) {
|
|
4778
|
+
const adapter = (row.adapterId ? this.worlds.get(row.adapterId)?.adapter : undefined)
|
|
4779
|
+
?? this.getAdapterForInstance?.(row.instanceName) ?? this.adapter;
|
|
4780
|
+
if (!adapter?.deleteMessage)
|
|
4781
|
+
continue;
|
|
4782
|
+
try {
|
|
4783
|
+
await adapter.deleteMessage(row.chatId, row.messageId, row.threadId);
|
|
4784
|
+
this.logger.info({ instanceName: row.instanceName, messageId: row.messageId }, "Swept orphaned cancel button from previous run");
|
|
4785
|
+
}
|
|
4786
|
+
catch (err) {
|
|
4787
|
+
// Best effort: the message may already be gone, or too old to delete.
|
|
4788
|
+
this.logger.debug({ err, messageId: row.messageId }, "Orphaned cancel button sweep failed");
|
|
4789
|
+
}
|
|
4790
|
+
}
|
|
4791
|
+
// The current process owns the ledger from here on.
|
|
4792
|
+
this.persistCancelButtons();
|
|
3629
4793
|
}
|
|
3630
4794
|
/** Re-attempt a failed button delete up to CANCEL_BTN_MAX_RETRIES times. */
|
|
3631
4795
|
scheduleButtonRetry(entry, err) {
|
|
@@ -3739,7 +4903,7 @@ export class FleetManager {
|
|
|
3739
4903
|
const adapter = this.getAdapterForInstance(instanceName) ?? this.adapter;
|
|
3740
4904
|
if (!adapter)
|
|
3741
4905
|
return;
|
|
3742
|
-
const channelCfg = this.getChannelConfig(this.
|
|
4906
|
+
const channelCfg = this.getChannelConfig(this.getInstanceAdapterId(instanceName));
|
|
3743
4907
|
const groupId = channelCfg?.group_id;
|
|
3744
4908
|
if (!groupId)
|
|
3745
4909
|
return;
|
|
@@ -4290,6 +5454,12 @@ When users create specialized instances, suggest these configurations:
|
|
|
4290
5454
|
meta.image_path = saves[saves.length - 1][1].split(",")[0].trim();
|
|
4291
5455
|
}
|
|
4292
5456
|
}
|
|
5457
|
+
// Classic channels queue reactions like everyone else (#432 stored them, but
|
|
5458
|
+
// this path never attached them — reactions in a ClassicBot channel went into
|
|
5459
|
+
// the DB and were never seen again). Same contract as the topic paths:
|
|
5460
|
+
// consumed only after the delivery succeeded.
|
|
5461
|
+
const reactions = this.pendingReactionsMeta(instanceName);
|
|
5462
|
+
Object.assign(meta, reactions.meta);
|
|
4293
5463
|
try {
|
|
4294
5464
|
await this.deliverToInstance(instanceName, {
|
|
4295
5465
|
type: "fleet_inbound",
|
|
@@ -4297,6 +5467,7 @@ When users create specialized instances, suggest these configurations:
|
|
|
4297
5467
|
targetSession: instanceName,
|
|
4298
5468
|
meta,
|
|
4299
5469
|
});
|
|
5470
|
+
reactions.consume();
|
|
4300
5471
|
}
|
|
4301
5472
|
catch (err) {
|
|
4302
5473
|
this.logger.warn({ err: err.message, instanceName }, "Classic wake/delivery failed");
|
|
@@ -4435,6 +5606,170 @@ When users create specialized instances, suggest these configurations:
|
|
|
4435
5606
|
return env?.models ?? [];
|
|
4436
5607
|
}
|
|
4437
5608
|
/** `/model` slash handler (admin only). No arg → DC menu; `/model <name>` → apply directly. */
|
|
5609
|
+
/** Label an effort choice, marking the one currently configured. */
|
|
5610
|
+
effortChoiceLabel(level, current) {
|
|
5611
|
+
return level === current ? `✓ ${level}` : level;
|
|
5612
|
+
}
|
|
5613
|
+
effortMenuHeader(instanceName) {
|
|
5614
|
+
const { effort, source } = this.resolveInstanceEffort(instanceName);
|
|
5615
|
+
if (!effort)
|
|
5616
|
+
return "Current effort: (CLI default)";
|
|
5617
|
+
return source === "fleet-default"
|
|
5618
|
+
? `Current effort: ${effort} (fleet default)`
|
|
5619
|
+
: `Current effort: ${effort}`;
|
|
5620
|
+
}
|
|
5621
|
+
/** `/effort` — DC Select Menu, or apply directly when a level is given. */
|
|
5622
|
+
async handleEffortSlash(data, adapterId) {
|
|
5623
|
+
if (!this.isModelAdmin(data.userId, data.channelId, adapterId)) {
|
|
5624
|
+
await data.respond(t("permission.denied"));
|
|
5625
|
+
return;
|
|
5626
|
+
}
|
|
5627
|
+
const name = this.resolveSlashTarget(data.channelId, adapterId);
|
|
5628
|
+
if (!name) {
|
|
5629
|
+
await data.respond(t("classic.no_agent"));
|
|
5630
|
+
return;
|
|
5631
|
+
}
|
|
5632
|
+
const requested = (typeof data.options?.level === "string" ? data.options.level.trim() : "")
|
|
5633
|
+
|| (data.text?.trim() ?? "");
|
|
5634
|
+
if (requested) {
|
|
5635
|
+
await data.respond(await this.applyEffort(name, requested));
|
|
5636
|
+
return;
|
|
5637
|
+
}
|
|
5638
|
+
const levels = this.effortLevelsFor(name);
|
|
5639
|
+
if (levels.length === 0) {
|
|
5640
|
+
await data.respond(`❌ ${this.backendNameForInstance(name)} has no reasoning-effort setting.`);
|
|
5641
|
+
return;
|
|
5642
|
+
}
|
|
5643
|
+
if (!data.respondChoices) {
|
|
5644
|
+
await data.respond(`Usage: /effort <${levels.join("|")}>`);
|
|
5645
|
+
return;
|
|
5646
|
+
}
|
|
5647
|
+
const current = this.resolveInstanceEffort(name).effort;
|
|
5648
|
+
const nonce = randomBytes(6).toString("hex");
|
|
5649
|
+
const choices = levels.map(l => ({
|
|
5650
|
+
id: `${EFFORT_SELECT_CALLBACK_PREFIX}${nonce}:${l}`,
|
|
5651
|
+
label: this.effortChoiceLabel(l, current),
|
|
5652
|
+
}));
|
|
5653
|
+
const timer = setTimeout(() => this.pendingEffortSelects.delete(nonce), CLASSIC_BACKEND_SELECTION_TIMEOUT_MS);
|
|
5654
|
+
timer.unref?.();
|
|
5655
|
+
this.pendingEffortSelects.set(nonce, { instanceName: name, userId: data.userId, channelId: data.channelId, timer, respond: data.respond });
|
|
5656
|
+
try {
|
|
5657
|
+
await data.respondChoices(`${this.effortMenuHeader(name)}\nSelect a new effort level:`, choices);
|
|
5658
|
+
}
|
|
5659
|
+
catch (err) {
|
|
5660
|
+
this.pendingEffortSelects.delete(nonce);
|
|
5661
|
+
clearTimeout(timer);
|
|
5662
|
+
this.logger.warn({ err, instanceName: name }, "effort menu failed");
|
|
5663
|
+
await data.respond(`Usage: /effort <${levels.join("|")}>`);
|
|
5664
|
+
}
|
|
5665
|
+
}
|
|
5666
|
+
/** TG inline-keyboard effort menu. Returns null on success, else a fallback string. */
|
|
5667
|
+
async promptEffortMenu(instanceName, userId, channelId, adapter, chatId, threadId) {
|
|
5668
|
+
const levels = this.effortLevelsFor(instanceName);
|
|
5669
|
+
if (levels.length === 0) {
|
|
5670
|
+
return `❌ ${this.backendNameForInstance(instanceName)} has no reasoning-effort setting.`;
|
|
5671
|
+
}
|
|
5672
|
+
const current = this.resolveInstanceEffort(instanceName).effort;
|
|
5673
|
+
const nonce = randomBytes(6).toString("hex");
|
|
5674
|
+
const choices = levels.map(l => ({
|
|
5675
|
+
id: `${EFFORT_SELECT_CALLBACK_PREFIX}${nonce}:${l}`,
|
|
5676
|
+
label: this.effortChoiceLabel(l, current),
|
|
5677
|
+
}));
|
|
5678
|
+
const respond = async (text) => {
|
|
5679
|
+
await adapter.sendText(chatId, text, { threadId });
|
|
5680
|
+
return undefined;
|
|
5681
|
+
};
|
|
5682
|
+
const timer = setTimeout(() => {
|
|
5683
|
+
const p = this.pendingEffortSelects.get(nonce);
|
|
5684
|
+
if (p) {
|
|
5685
|
+
this.pendingEffortSelects.delete(nonce);
|
|
5686
|
+
p.respond("⏰ Effort selection expired.").catch(() => { });
|
|
5687
|
+
}
|
|
5688
|
+
}, CLASSIC_BACKEND_SELECTION_TIMEOUT_MS);
|
|
5689
|
+
timer.unref?.();
|
|
5690
|
+
this.pendingEffortSelects.set(nonce, { instanceName, userId, channelId, timer, respond, adapter, adapterChatId: chatId, adapterThreadId: threadId });
|
|
5691
|
+
try {
|
|
5692
|
+
const menuMessageId = await adapter.promptUser(chatId, `${this.effortMenuHeader(instanceName)}\nSelect a new effort level:`, choices, { threadId });
|
|
5693
|
+
const pending = this.pendingEffortSelects.get(nonce);
|
|
5694
|
+
if (pending)
|
|
5695
|
+
pending.menuMessageId = menuMessageId;
|
|
5696
|
+
return null;
|
|
5697
|
+
}
|
|
5698
|
+
catch (err) {
|
|
5699
|
+
this.pendingEffortSelects.delete(nonce);
|
|
5700
|
+
clearTimeout(timer);
|
|
5701
|
+
this.logger.warn({ err, instanceName }, "TG effort menu failed");
|
|
5702
|
+
return `Usage: /effort <${levels.join("|")}>`;
|
|
5703
|
+
}
|
|
5704
|
+
}
|
|
5705
|
+
/** Consume an `/effort` selection callback. Mirrors handleModelSelection. */
|
|
5706
|
+
async handleEffortSelection(data) {
|
|
5707
|
+
if (!data.callbackData.startsWith(EFFORT_SELECT_CALLBACK_PREFIX))
|
|
5708
|
+
return false;
|
|
5709
|
+
const match = data.callbackData.match(/^effort-select:([0-9a-f]+):(.+)$/);
|
|
5710
|
+
if (!match)
|
|
5711
|
+
return true;
|
|
5712
|
+
const pending = this.pendingEffortSelects.get(match[1]);
|
|
5713
|
+
if (!pending)
|
|
5714
|
+
return true;
|
|
5715
|
+
if (data.userId && data.userId !== pending.userId)
|
|
5716
|
+
return true;
|
|
5717
|
+
const cbChannel = data.threadId ?? data.chatId;
|
|
5718
|
+
if (cbChannel !== pending.channelId && data.chatId !== pending.channelId)
|
|
5719
|
+
return true;
|
|
5720
|
+
this.pendingEffortSelects.delete(match[1]);
|
|
5721
|
+
clearTimeout(pending.timer);
|
|
5722
|
+
const level = match[2];
|
|
5723
|
+
const progressText = `⏳ Setting ${pending.instanceName} effort to \`${level}\`…`;
|
|
5724
|
+
let progressMsgId;
|
|
5725
|
+
if (pending.adapter && pending.adapterChatId) {
|
|
5726
|
+
const menuMessageId = pending.menuMessageId ?? data.messageId;
|
|
5727
|
+
if (menuMessageId && pending.adapter.editMessageRemoveButtons) {
|
|
5728
|
+
try {
|
|
5729
|
+
await pending.adapter.editMessageRemoveButtons(pending.adapterChatId, menuMessageId, progressText, pending.adapterThreadId);
|
|
5730
|
+
progressMsgId = menuMessageId;
|
|
5731
|
+
}
|
|
5732
|
+
catch { /* fall back to a new message */ }
|
|
5733
|
+
}
|
|
5734
|
+
if (!progressMsgId) {
|
|
5735
|
+
try {
|
|
5736
|
+
const sent = await pending.adapter.sendText(pending.adapterChatId, progressText, { threadId: pending.adapterThreadId });
|
|
5737
|
+
progressMsgId = sent.messageId;
|
|
5738
|
+
}
|
|
5739
|
+
catch { /* non-fatal */ }
|
|
5740
|
+
}
|
|
5741
|
+
}
|
|
5742
|
+
else {
|
|
5743
|
+
await pending.respond(progressText).catch(() => { });
|
|
5744
|
+
}
|
|
5745
|
+
// Background-applied and guarded for the same reason as the model path: a
|
|
5746
|
+
// restart backend respawns the instance here, and an unguarded rejection
|
|
5747
|
+
// from a menu click must not take the fleet down.
|
|
5748
|
+
void (async () => {
|
|
5749
|
+
let result;
|
|
5750
|
+
try {
|
|
5751
|
+
result = await this.applyEffort(pending.instanceName, level);
|
|
5752
|
+
}
|
|
5753
|
+
catch (err) {
|
|
5754
|
+
this.logger.error({ err, instance: pending.instanceName, level }, "Effort switch failed");
|
|
5755
|
+
result = `Effort switch to \`${level}\` failed: ${err instanceof Error ? err.message : String(err)}`;
|
|
5756
|
+
}
|
|
5757
|
+
if (pending.adapter && pending.adapterChatId) {
|
|
5758
|
+
if (progressMsgId) {
|
|
5759
|
+
pending.adapter.editMessage(pending.adapterChatId, progressMsgId, result, pending.adapterThreadId).catch(() => {
|
|
5760
|
+
pending.adapter.sendText(pending.adapterChatId, result, { threadId: pending.adapterThreadId }).catch(() => { });
|
|
5761
|
+
});
|
|
5762
|
+
}
|
|
5763
|
+
else {
|
|
5764
|
+
pending.adapter.sendText(pending.adapterChatId, result, { threadId: pending.adapterThreadId }).catch(() => { });
|
|
5765
|
+
}
|
|
5766
|
+
}
|
|
5767
|
+
else {
|
|
5768
|
+
await pending.respond(result).catch(() => { });
|
|
5769
|
+
}
|
|
5770
|
+
})();
|
|
5771
|
+
return true;
|
|
5772
|
+
}
|
|
4438
5773
|
async handleModelSlash(data, adapterId) {
|
|
4439
5774
|
if (!this.isModelAdmin(data.userId, data.channelId, adapterId)) {
|
|
4440
5775
|
await data.respond(t("permission.denied"));
|
|
@@ -4571,9 +5906,19 @@ When users create specialized instances, suggest these configurations:
|
|
|
4571
5906
|
// DC path: respond immediately with progress text
|
|
4572
5907
|
await pending.respond(progressText).catch(() => { });
|
|
4573
5908
|
}
|
|
4574
|
-
// Apply model in background — don't await here (keeps callback handler fast)
|
|
5909
|
+
// Apply model in background — don't await here (keeps callback handler fast).
|
|
5910
|
+
// Guarded: applyModel() restarts the instance, and an unguarded rejection here
|
|
5911
|
+
// meant a user picking from the /model menu could take the whole fleet down.
|
|
5912
|
+
// On failure the user gets told, rather than the click silently doing nothing.
|
|
4575
5913
|
void (async () => {
|
|
4576
|
-
|
|
5914
|
+
let result;
|
|
5915
|
+
try {
|
|
5916
|
+
result = await this.applyModel(pending.instanceName, model);
|
|
5917
|
+
}
|
|
5918
|
+
catch (err) {
|
|
5919
|
+
this.logger.error({ err, instance: pending.instanceName, model }, "Model switch failed");
|
|
5920
|
+
result = `Model switch to \`${model}\` failed: ${err instanceof Error ? err.message : String(err)}`;
|
|
5921
|
+
}
|
|
4577
5922
|
if (pending.adapter && pending.adapterChatId) {
|
|
4578
5923
|
if (progressMsgId) {
|
|
4579
5924
|
pending.adapter.editMessage(pending.adapterChatId, progressMsgId, result, pending.adapterThreadId).catch(() => {
|
|
@@ -4591,6 +5936,110 @@ When users create specialized instances, suggest these configurations:
|
|
|
4591
5936
|
return true;
|
|
4592
5937
|
}
|
|
4593
5938
|
/** Apply a model to an instance: runtime paste (claude-code) or persist + restart (others). */
|
|
5939
|
+
/** AgEnD's canonical effort ladder, low → max. Backends expose a subset. */
|
|
5940
|
+
static EFFORT_LEVELS = ["low", "medium", "high", "xhigh", "max"];
|
|
5941
|
+
/** How this instance's backend applies an effort change. */
|
|
5942
|
+
effortStrategyFor(instanceName) {
|
|
5943
|
+
try {
|
|
5944
|
+
const backend = createBackend(this.backendNameForInstance(instanceName), this.getInstanceDir(instanceName));
|
|
5945
|
+
const strategy = backend.getEffortStrategy?.() ?? "unsupported";
|
|
5946
|
+
// A backend claiming support but listing no levels is unusable either way.
|
|
5947
|
+
return strategy !== "unsupported" && (backend.getEffortLevels?.() ?? []).length > 0
|
|
5948
|
+
? strategy
|
|
5949
|
+
: "unsupported";
|
|
5950
|
+
}
|
|
5951
|
+
catch {
|
|
5952
|
+
return "unsupported";
|
|
5953
|
+
}
|
|
5954
|
+
}
|
|
5955
|
+
/** Effort levels this instance's backend actually accepts (empty = unsupported). */
|
|
5956
|
+
effortLevelsFor(instanceName) {
|
|
5957
|
+
try {
|
|
5958
|
+
const backend = createBackend(this.backendNameForInstance(instanceName), this.getInstanceDir(instanceName));
|
|
5959
|
+
if ((backend.getEffortStrategy?.() ?? "unsupported") === "unsupported")
|
|
5960
|
+
return [];
|
|
5961
|
+
return backend.getEffortLevels?.() ?? [];
|
|
5962
|
+
}
|
|
5963
|
+
catch {
|
|
5964
|
+
return [];
|
|
5965
|
+
}
|
|
5966
|
+
}
|
|
5967
|
+
/** Configured effort for an instance: per-instance, else fleet default, else none. */
|
|
5968
|
+
resolveInstanceEffort(instanceName) {
|
|
5969
|
+
const own = this.fleetConfig?.instances[instanceName]?.effort;
|
|
5970
|
+
if (own)
|
|
5971
|
+
return { effort: own, source: "instance" };
|
|
5972
|
+
const fallback = this.fleetConfig?.defaults?.effort;
|
|
5973
|
+
if (fallback)
|
|
5974
|
+
return { effort: fallback, source: "fleet-default" };
|
|
5975
|
+
return { effort: null, source: "unset" };
|
|
5976
|
+
}
|
|
5977
|
+
/**
|
|
5978
|
+
* Clamp a canonical level to the nearest one this backend supports.
|
|
5979
|
+
*
|
|
5980
|
+
* Clamping DOWN the ladder, never up: asking for `max` on a CLI that stops at
|
|
5981
|
+
* `high` should get high, not silently fall to low. The caller reports the
|
|
5982
|
+
* clamp — a user who asks for max and quietly receives high has been told the
|
|
5983
|
+
* request succeeded when it did not.
|
|
5984
|
+
*/
|
|
5985
|
+
static clampEffort(level, supported) {
|
|
5986
|
+
if (supported.includes(level))
|
|
5987
|
+
return level;
|
|
5988
|
+
const ladder = FleetManager.EFFORT_LEVELS;
|
|
5989
|
+
const wanted = ladder.indexOf(level);
|
|
5990
|
+
if (wanted < 0)
|
|
5991
|
+
return null;
|
|
5992
|
+
for (let i = wanted - 1; i >= 0; i--) {
|
|
5993
|
+
if (supported.includes(ladder[i]))
|
|
5994
|
+
return ladder[i];
|
|
5995
|
+
}
|
|
5996
|
+
return supported[0] ?? null;
|
|
5997
|
+
}
|
|
5998
|
+
/**
|
|
5999
|
+
* Apply a reasoning-effort level, mirroring applyModel's shape.
|
|
6000
|
+
*
|
|
6001
|
+
* runtime backends take `/effort <level>` in the pane and keep working;
|
|
6002
|
+
* restart backends only read it at launch, so it is persisted and the
|
|
6003
|
+
* instance respawns.
|
|
6004
|
+
*/
|
|
6005
|
+
async applyEffort(instanceName, requested) {
|
|
6006
|
+
const level = requested.trim().toLowerCase();
|
|
6007
|
+
const backendName = this.backendNameForInstance(instanceName);
|
|
6008
|
+
let strategy = "unsupported";
|
|
6009
|
+
let supported = [];
|
|
6010
|
+
try {
|
|
6011
|
+
const backend = createBackend(backendName, this.getInstanceDir(instanceName));
|
|
6012
|
+
strategy = backend.getEffortStrategy?.() ?? "unsupported";
|
|
6013
|
+
supported = backend.getEffortLevels?.() ?? [];
|
|
6014
|
+
}
|
|
6015
|
+
catch { /* treated as unsupported below */ }
|
|
6016
|
+
if (strategy === "unsupported" || supported.length === 0) {
|
|
6017
|
+
return `❌ ${backendName} has no reasoning-effort setting.`;
|
|
6018
|
+
}
|
|
6019
|
+
if (!FleetManager.EFFORT_LEVELS.includes(level)) {
|
|
6020
|
+
return `❌ Unknown effort level \`${level}\`. Use: ${FleetManager.EFFORT_LEVELS.join(", ")}.`;
|
|
6021
|
+
}
|
|
6022
|
+
const applied = FleetManager.clampEffort(level, supported);
|
|
6023
|
+
if (!applied)
|
|
6024
|
+
return `❌ ${backendName} accepts none of the canonical effort levels.`;
|
|
6025
|
+
const warn = applied === level
|
|
6026
|
+
? ""
|
|
6027
|
+
: `⚠️ Clamped to \`${applied}\` (\`${level}\` not supported by ${backendName}).\n`;
|
|
6028
|
+
// Persist either way: a runtime switch must survive the next respawn too,
|
|
6029
|
+
// or the instance silently reverts on restart.
|
|
6030
|
+
if (this.fleetConfig?.instances[instanceName]) {
|
|
6031
|
+
this.fleetConfig.instances[instanceName].effort = applied;
|
|
6032
|
+
this.saveFleetConfig();
|
|
6033
|
+
}
|
|
6034
|
+
if (strategy === "runtime") {
|
|
6035
|
+
if (!this.instanceIpcClients.get(instanceName))
|
|
6036
|
+
return `${warn}❌ ${instanceName} is not running.`;
|
|
6037
|
+
this.pasteRawToClassicInstance(instanceName, `/effort ${applied}`);
|
|
6038
|
+
return `${warn}✅ Set ${instanceName} effort to \`${applied}\` (runtime).`;
|
|
6039
|
+
}
|
|
6040
|
+
await this.restartSingleInstance(instanceName);
|
|
6041
|
+
return `${warn}✅ Set ${instanceName} effort to \`${applied}\` and restarted.`;
|
|
6042
|
+
}
|
|
4594
6043
|
async applyModel(instanceName, model) {
|
|
4595
6044
|
const backendName = this.backendNameForInstance(instanceName);
|
|
4596
6045
|
let strategy = "restart";
|
|
@@ -4603,7 +6052,7 @@ When users create specialized instances, suggest these configurations:
|
|
|
4603
6052
|
if (!this.instanceIpcClients.get(instanceName))
|
|
4604
6053
|
return `${warn}❌ ${instanceName} is not running.`;
|
|
4605
6054
|
this.pasteRawToClassicInstance(instanceName, `/model ${model}`);
|
|
4606
|
-
return `${warn}✅ Switched ${instanceName} to \`${model}\` (runtime)
|
|
6055
|
+
return `${warn}✅ Switched ${instanceName} to \`${model}\` (runtime).${this.effortSuffix(instanceName)}`;
|
|
4607
6056
|
}
|
|
4608
6057
|
// restart: persist the model so the respawned CLI launches with it.
|
|
4609
6058
|
let persisted = false;
|
|
@@ -4618,7 +6067,24 @@ When users create specialized instances, suggest these configurations:
|
|
|
4618
6067
|
if (!persisted)
|
|
4619
6068
|
return `${warn}❌ Could not set model for ${instanceName}.`;
|
|
4620
6069
|
await this.restartSingleInstance(instanceName);
|
|
4621
|
-
return `${warn}✅ Set ${instanceName} to \`${model}\` and restarted
|
|
6070
|
+
return `${warn}✅ Set ${instanceName} to \`${model}\` and restarted.${this.effortSuffix(instanceName)}`;
|
|
6071
|
+
}
|
|
6072
|
+
/**
|
|
6073
|
+
* The trailing "Current effort: …" line for a /model reply.
|
|
6074
|
+
*
|
|
6075
|
+
* Model and effort interact (a cheaper model at max effort is a different
|
|
6076
|
+
* trade than a bigger one at low), so showing the effort in force right after
|
|
6077
|
+
* a switch saves the round trip of asking. Empty when the backend has none.
|
|
6078
|
+
*/
|
|
6079
|
+
effortSuffix(instanceName) {
|
|
6080
|
+
if (this.effortLevelsFor(instanceName).length === 0)
|
|
6081
|
+
return "";
|
|
6082
|
+
const { effort, source } = this.resolveInstanceEffort(instanceName);
|
|
6083
|
+
if (!effort)
|
|
6084
|
+
return "\nCurrent effort: (CLI default)";
|
|
6085
|
+
return source === "fleet-default"
|
|
6086
|
+
? `\nCurrent effort: ${effort} (fleet default)`
|
|
6087
|
+
: `\nCurrent effort: ${effort}`;
|
|
4622
6088
|
}
|
|
4623
6089
|
/** Read recent chat log for agent context */
|
|
4624
6090
|
getRecentChatLog(instanceName, maxLines = 10) {
|
|
@@ -4811,7 +6277,7 @@ When users create specialized instances, suggest these configurations:
|
|
|
4811
6277
|
...(preTaskCommand ? { pre_task_command: preTaskCommand } : {}),
|
|
4812
6278
|
};
|
|
4813
6279
|
const topicMode = this.fleetConfig?.channel?.mode === "topic";
|
|
4814
|
-
await this.startInstance(instanceName, config, topicMode);
|
|
6280
|
+
await this.startInstance(instanceName, config, topicMode, "classic");
|
|
4815
6281
|
}
|
|
4816
6282
|
/** Handle /start slash command — register classic channel */
|
|
4817
6283
|
async handleClassicStart(channelId, channelName, userId, guildId, adapterId, backend) {
|
|
@@ -4853,11 +6319,28 @@ When users create specialized instances, suggest these configurations:
|
|
|
4853
6319
|
this.logger.info({ channelId, adapterId, instanceName: ch.instanceName }, "Classic channel stopped");
|
|
4854
6320
|
return t("classic.stopped");
|
|
4855
6321
|
}
|
|
4856
|
-
|
|
6322
|
+
/**
|
|
6323
|
+
* Idempotent while in flight: SIGINT and SIGTERM share one handler and the
|
|
6324
|
+
* uncaughtException path calls this too, so overlapping runs were possible —
|
|
6325
|
+
* each snapshotting the daemon map and calling stop() on the same daemons
|
|
6326
|
+
* concurrently. Deliberately NOT `async`, so callers receive the same promise
|
|
6327
|
+
* object rather than a fresh wrapper around it. The latch clears when the run
|
|
6328
|
+
* settles, so a later genuine stop (after a restart) still does the work.
|
|
6329
|
+
*/
|
|
6330
|
+
stopAll() {
|
|
6331
|
+
this.stopAllInFlight ??= this.doStopAll().finally(() => { this.stopAllInFlight = null; });
|
|
6332
|
+
return this.stopAllInFlight;
|
|
6333
|
+
}
|
|
6334
|
+
stopAllInFlight = null;
|
|
6335
|
+
async doStopAll() {
|
|
4857
6336
|
this.startupComplete = false;
|
|
4858
6337
|
this.reloadPending = false;
|
|
6338
|
+
// Before anything is stopped: everything that dies from here on dies
|
|
6339
|
+
// because we asked it to. Set synchronously — doStopAll runs to its first
|
|
6340
|
+
// await in the same tick as the signal handler, so no event can slip in.
|
|
6341
|
+
this.shuttingDown = true;
|
|
4859
6342
|
this.ipcStoppingInstances.add("__fleet_stopping__");
|
|
4860
|
-
|
|
6343
|
+
sdNotifyBlocking("STOPPING=1");
|
|
4861
6344
|
if (this.watchdogTimer) {
|
|
4862
6345
|
clearInterval(this.watchdogTimer);
|
|
4863
6346
|
this.watchdogTimer = null;
|
|
@@ -4877,6 +6360,29 @@ When users create specialized instances, suggest these configurations:
|
|
|
4877
6360
|
clearInterval(this.updateCheckTimer);
|
|
4878
6361
|
this.updateCheckTimer = null;
|
|
4879
6362
|
}
|
|
6363
|
+
if (this.eventLogPruneTimer) {
|
|
6364
|
+
clearInterval(this.eventLogPruneTimer);
|
|
6365
|
+
this.eventLogPruneTimer = null;
|
|
6366
|
+
}
|
|
6367
|
+
if (this.logRotateTimer) {
|
|
6368
|
+
clearInterval(this.logRotateTimer);
|
|
6369
|
+
this.logRotateTimer = null;
|
|
6370
|
+
}
|
|
6371
|
+
// Cancel-button timers were never cleared here. The idle-check interval is not
|
|
6372
|
+
// unref'd, so it held the event loop open past shutdown and kept retrying
|
|
6373
|
+
// deletes against an adapter that was already gone.
|
|
6374
|
+
for (const entry of [...this.cancelButtons.values()]) {
|
|
6375
|
+
if (entry.retryTimer)
|
|
6376
|
+
clearTimeout(entry.retryTimer);
|
|
6377
|
+
if (entry.idleCheckTimer)
|
|
6378
|
+
clearInterval(entry.idleCheckTimer);
|
|
6379
|
+
if (entry.progressTimer)
|
|
6380
|
+
clearInterval(entry.progressTimer);
|
|
6381
|
+
}
|
|
6382
|
+
this.cancelButtons.clear();
|
|
6383
|
+
for (const timer of this.cancelButtonIdleRetireTimers.values())
|
|
6384
|
+
clearTimeout(timer);
|
|
6385
|
+
this.cancelButtonIdleRetireTimers.clear();
|
|
4880
6386
|
if (this.topicCleanupTimer) {
|
|
4881
6387
|
clearInterval(this.topicCleanupTimer);
|
|
4882
6388
|
this.topicCleanupTimer = null;
|
|
@@ -4933,6 +6439,7 @@ When users create specialized instances, suggest these configurations:
|
|
|
4933
6439
|
this.controlClient?.stop();
|
|
4934
6440
|
this.controlClient = null;
|
|
4935
6441
|
if (this.healthServer) {
|
|
6442
|
+
this.healthServerListening = false;
|
|
4936
6443
|
this.healthServer.close();
|
|
4937
6444
|
this.healthServer = null;
|
|
4938
6445
|
}
|
|
@@ -4944,6 +6451,9 @@ When users create specialized instances, suggest these configurations:
|
|
|
4944
6451
|
catch (e) {
|
|
4945
6452
|
this.logger.debug({ err: e }, "Failed to remove fleet PID file");
|
|
4946
6453
|
}
|
|
6454
|
+
// The lock contains a nonce, so an older/shutting-down process can never
|
|
6455
|
+
// remove a lock acquired by a newer fleet owner.
|
|
6456
|
+
releaseProcessFleetLock();
|
|
4947
6457
|
}
|
|
4948
6458
|
/**
|
|
4949
6459
|
* Prune stale external sessions by re-querying each daemon for live sessions.
|
|
@@ -5095,6 +6605,15 @@ When users create specialized instances, suggest these configurations:
|
|
|
5095
6605
|
removedRatio,
|
|
5096
6606
|
validationErrors: validation.errors,
|
|
5097
6607
|
}, "Refusing unsafe fleet config reload; running configuration was kept");
|
|
6608
|
+
// Tell the operator. A silently ignored config edit is the most confusing
|
|
6609
|
+
// possible outcome: they change fleet.yaml, send SIGHUP, and nothing happens
|
|
6610
|
+
// with no explanation anywhere they are looking.
|
|
6611
|
+
const why = !validation.valid
|
|
6612
|
+
? `validation failed:\n${validation.errors.map(e => `• ${e.path}: ${e.message}`).join("\n")}`
|
|
6613
|
+
: unsafeEmpty
|
|
6614
|
+
? `it removed every instance (${oldCount} → 0)`
|
|
6615
|
+
: `it removed more than half the instances (${oldCount} → ${newCount})`;
|
|
6616
|
+
this.notifyFleetError(`⚠️ fleet.yaml reload REJECTED — ${why}\nThe previous configuration is still running.`);
|
|
5098
6617
|
return;
|
|
5099
6618
|
}
|
|
5100
6619
|
this.routing.rebuild(this.fleetConfig);
|
|
@@ -5178,6 +6697,10 @@ When users create specialized instances, suggest these configurations:
|
|
|
5178
6697
|
clearTimeout(timeoutHandle);
|
|
5179
6698
|
}
|
|
5180
6699
|
this.logger.info("All instances idle — restarting...");
|
|
6700
|
+
const restartStartedAt = Date.now();
|
|
6701
|
+
// Capture the live adapter/topic before General's daemon is stopped. The
|
|
6702
|
+
// channel adapter remains connected throughout an in-process restart.
|
|
6703
|
+
const progressTarget = this.restartProgressTarget();
|
|
5181
6704
|
this.clearStatuslineWatchers();
|
|
5182
6705
|
for (const [, ipc] of this.instanceIpcClients) {
|
|
5183
6706
|
await ipc.close();
|
|
@@ -5202,15 +6725,25 @@ When users create specialized instances, suggest these configurations:
|
|
|
5202
6725
|
const fleet = this.loadConfig(this.configPath);
|
|
5203
6726
|
this.fleetConfig = fleet;
|
|
5204
6727
|
const topicMode = fleet.channel?.mode === "topic" || !!fleet.channels?.some(ch => ch.mode === "topic");
|
|
6728
|
+
const restartProgress = new RestartProgress(this.runnableStartupCount(fleet, topicMode), restartStartedAt, this.logger);
|
|
5205
6729
|
// Phase 1: generals first
|
|
5206
6730
|
const restartEntries = Object.entries(fleet.instances);
|
|
5207
6731
|
const restartGenerals = restartEntries.filter(([_, cfg]) => cfg.general_topic);
|
|
5208
6732
|
const restartOthers = restartEntries.filter(([_, cfg]) => !cfg.general_topic);
|
|
5209
6733
|
for (const [name, cfg] of restartGenerals) {
|
|
5210
|
-
|
|
6734
|
+
try {
|
|
6735
|
+
await this.startInstance(name, cfg, topicMode);
|
|
6736
|
+
if (this.daemons.has(name))
|
|
6737
|
+
restartProgress.markReady();
|
|
6738
|
+
}
|
|
6739
|
+
catch (err) {
|
|
6740
|
+
this.logger.error({ err, name }, "Failed to start general instance");
|
|
6741
|
+
}
|
|
5211
6742
|
}
|
|
6743
|
+
// General is ready again; now its topic can own the live progress message.
|
|
6744
|
+
await restartProgress.start(progressTarget);
|
|
5212
6745
|
if (restartOthers.length > 0) {
|
|
5213
|
-
await this.startInstancesWithConcurrency(restartOthers, topicMode);
|
|
6746
|
+
await this.startInstancesWithConcurrency(restartOthers, topicMode, () => restartProgress.markReady());
|
|
5214
6747
|
}
|
|
5215
6748
|
if (topicMode) {
|
|
5216
6749
|
this.routing.rebuild(this.fleetConfig);
|
|
@@ -5219,12 +6752,22 @@ When users create specialized instances, suggest these configurations:
|
|
|
5219
6752
|
// Restart classic channel instances (killed during orphan cleanup)
|
|
5220
6753
|
if (this.classicChannels) {
|
|
5221
6754
|
const fleetBackend = this.fleetConfig?.defaults?.backend;
|
|
5222
|
-
const channels = this.classicChannels.getAll()
|
|
6755
|
+
const channels = this.classicChannels.getAll()
|
|
6756
|
+
.filter(ch => !this.lifecycle.isPaused(ch.instanceName));
|
|
5223
6757
|
const concurrency = 3;
|
|
5224
6758
|
let idx = 0;
|
|
5225
6759
|
while (idx < channels.length) {
|
|
5226
6760
|
const batch = channels.slice(idx, idx + concurrency);
|
|
5227
|
-
await Promise.allSettled(batch.map(
|
|
6761
|
+
await Promise.allSettled(batch.map(async (ch) => {
|
|
6762
|
+
try {
|
|
6763
|
+
await this.startClassicInstance(ch.instanceName, this.classicChannels.getBackendByInstance(ch.instanceName, fleetBackend), this.classicChannels.getPreTaskCommand(ch.channelId, ch.adapterId), this.classicChannels.getModel(ch.channelId, ch.adapterId, this.fleetConfig?.defaults?.model), this.classicChannels.getAutoPauseAfter(ch.channelId, ch.adapterId, this.fleetConfig?.defaults?.auto_pause_after));
|
|
6764
|
+
if (this.daemons.has(ch.instanceName))
|
|
6765
|
+
restartProgress.markReady();
|
|
6766
|
+
}
|
|
6767
|
+
catch (err) {
|
|
6768
|
+
this.logger.warn({ err, instanceName: ch.instanceName }, "Failed to start classic instance");
|
|
6769
|
+
}
|
|
6770
|
+
}));
|
|
5228
6771
|
idx += concurrency;
|
|
5229
6772
|
}
|
|
5230
6773
|
}
|
|
@@ -5233,6 +6776,7 @@ When users create specialized instances, suggest these configurations:
|
|
|
5233
6776
|
}
|
|
5234
6777
|
}
|
|
5235
6778
|
this.logger.info("Graceful restart complete");
|
|
6779
|
+
const progressCompleted = await restartProgress.finish();
|
|
5236
6780
|
if (groupId && this.adapter) {
|
|
5237
6781
|
const total = Object.keys(fleet.instances).length;
|
|
5238
6782
|
const started = this.daemons.size;
|
|
@@ -5253,8 +6797,10 @@ When users create specialized instances, suggest these configurations:
|
|
|
5253
6797
|
restartText = t("fleet.ready_with_failed", started, total, agendVersion2, failedNames.join(", "))
|
|
5254
6798
|
+ (pausedNames2.length > 0 ? `\n⏸ Paused: ${pausedNames2.join(", ")}` : "");
|
|
5255
6799
|
}
|
|
5256
|
-
|
|
5257
|
-
|
|
6800
|
+
if (!progressCompleted) {
|
|
6801
|
+
await this.adapter.sendText(String(groupId), restartText, notifyOpts)
|
|
6802
|
+
.catch(e => this.logger.warn({ err: e }, "Failed to post restart completion notification"));
|
|
6803
|
+
}
|
|
5258
6804
|
// Notify each instance's channel — staggered to avoid rate limit storm
|
|
5259
6805
|
const instances = Object.entries(this.fleetConfig?.instances ?? {});
|
|
5260
6806
|
this.logger.info({ count: instances.length }, "Sending restart notification to instances (staggered)");
|
|
@@ -5294,10 +6840,20 @@ When users create specialized instances, suggest these configurations:
|
|
|
5294
6840
|
// ── Update check ────────────────────────────────────────────────────
|
|
5295
6841
|
async checkForUpdates() {
|
|
5296
6842
|
try {
|
|
5297
|
-
|
|
6843
|
+
// Both npm lookups are async: as execSync they froze the fleet event loop for
|
|
6844
|
+
// up to 15s each, and on a beta build BOTH ran — 30s with no WATCHDOG ping,
|
|
6845
|
+
// past WatchdogSec's half-interval and enough for systemd to SIGABRT the fleet
|
|
6846
|
+
// for a background version check.
|
|
6847
|
+
const { execFile } = await import("node:child_process");
|
|
6848
|
+
const { promisify } = await import("node:util");
|
|
6849
|
+
const execFileP = promisify(execFile);
|
|
6850
|
+
const npmVersion = async (spec) => {
|
|
6851
|
+
const { stdout } = await execFileP("npm", ["view", spec, "version"], { timeout: 15_000 });
|
|
6852
|
+
return stdout.toString().trim();
|
|
6853
|
+
};
|
|
5298
6854
|
const pkgPath = join(dirname(fileURLToPath(import.meta.url)), "..", "package.json");
|
|
5299
6855
|
const currentVersion = JSON.parse(readFileSync(pkgPath, "utf-8")).version ?? "0.0.0";
|
|
5300
|
-
const latest =
|
|
6856
|
+
const latest = await npmVersion("@songsid/agend");
|
|
5301
6857
|
let target = latest;
|
|
5302
6858
|
if (currentVersion.includes("-beta")) {
|
|
5303
6859
|
// Beta users track the @beta channel (never fall back to @latest, which is
|
|
@@ -5305,7 +6861,7 @@ When users create specialized instances, suggest these configurations:
|
|
|
5305
6861
|
// of beta/latest is the newest.
|
|
5306
6862
|
let beta = "";
|
|
5307
6863
|
try {
|
|
5308
|
-
beta =
|
|
6864
|
+
beta = await npmVersion("@songsid/agend@beta");
|
|
5309
6865
|
}
|
|
5310
6866
|
catch { /* no beta tag */ }
|
|
5311
6867
|
target = beta || latest;
|
|
@@ -5379,28 +6935,22 @@ When users create specialized instances, suggest these configurations:
|
|
|
5379
6935
|
// ── Health HTTP endpoint ─────────────────────────────────────────────
|
|
5380
6936
|
startHealthServer(port) {
|
|
5381
6937
|
this.startedAt = Date.now();
|
|
5382
|
-
|
|
5383
|
-
this.
|
|
5384
|
-
|
|
5385
|
-
|
|
5386
|
-
|
|
5387
|
-
try {
|
|
5388
|
-
chmodSync(tokenPath, 0o600);
|
|
5389
|
-
}
|
|
5390
|
-
catch {
|
|
5391
|
-
// best-effort
|
|
5392
|
-
}
|
|
5393
|
-
// Separate read-only token for the /view page: grants terminal-view + profile
|
|
5394
|
-
// read, but never write (POSTs still require the full web token).
|
|
5395
|
-
this.viewToken = randomBytes(24).toString("hex");
|
|
5396
|
-
const viewTokenPath = join(this.dataDir, "view.token");
|
|
5397
|
-
writeFileSync(viewTokenPath, this.viewToken, { mode: 0o600 });
|
|
5398
|
-
try {
|
|
5399
|
-
chmodSync(viewTokenPath, 0o600);
|
|
5400
|
-
}
|
|
5401
|
-
catch { /* best-effort */ }
|
|
6938
|
+
this.healthServerListening = false;
|
|
6939
|
+
this.healthPortRetried = false;
|
|
6940
|
+
// Defensive for direct/unit callers; normal startup initializes these before adapters.
|
|
6941
|
+
if (!this.webToken || !this.viewToken)
|
|
6942
|
+
this.initializeWebAuthTokens();
|
|
5402
6943
|
this.healthServer = createServer((req, res) => {
|
|
5403
6944
|
res.setHeader("Content-Type", "application/json");
|
|
6945
|
+
const requestPath = new URL(req.url ?? "/", `http://localhost:${port}`).pathname;
|
|
6946
|
+
// Browsers request this automatically and AgEnD does not ship an icon.
|
|
6947
|
+
// It is neither user data nor an API route, so do not turn the harmless
|
|
6948
|
+
// probe into a noisy web-token 401 in the browser console.
|
|
6949
|
+
if (req.method === "GET" && requestPath === "/favicon.ico") {
|
|
6950
|
+
res.writeHead(204);
|
|
6951
|
+
res.end();
|
|
6952
|
+
return;
|
|
6953
|
+
}
|
|
5404
6954
|
// Public health probe — no auth required.
|
|
5405
6955
|
if (req.method === "GET" && req.url === "/health") {
|
|
5406
6956
|
// fallthrough to existing handler below
|
|
@@ -5412,6 +6962,10 @@ When users create specialized instances, suggest these configurations:
|
|
|
5412
6962
|
// /view routes accept the read-only view.token (or web.token) and do
|
|
5413
6963
|
// their own per-method auth in view-api.ts — skip the web-token gate.
|
|
5414
6964
|
}
|
|
6965
|
+
else if (isUsagePath(new URL(req.url ?? "/", `http://localhost:${port}`).pathname)) {
|
|
6966
|
+
// /api/ai-usage is read-only GET data for the /view Usage panel — open
|
|
6967
|
+
// like the other /view data routes (usage-api.ts rejects non-GET).
|
|
6968
|
+
}
|
|
5415
6969
|
else {
|
|
5416
6970
|
// All other endpoints require a valid token (query ?token= or X-Agend-Token header).
|
|
5417
6971
|
// /ui/* will also re-check in web-api.ts, which is harmless.
|
|
@@ -5421,39 +6975,39 @@ When users create specialized instances, suggest these configurations:
|
|
|
5421
6975
|
?? (typeof headerToken === "string" ? headerToken : null);
|
|
5422
6976
|
if (!this.webToken || providedToken !== this.webToken) {
|
|
5423
6977
|
res.writeHead(401);
|
|
5424
|
-
res.end(JSON.stringify({ error:
|
|
6978
|
+
res.end(JSON.stringify({ error: WEB_TOKEN_INVALID_MESSAGE }));
|
|
5425
6979
|
return;
|
|
5426
6980
|
}
|
|
5427
6981
|
}
|
|
5428
6982
|
if (req.method === "GET" && req.url === "/health") {
|
|
5429
|
-
const
|
|
5430
|
-
|
|
5431
|
-
|
|
5432
|
-
|
|
5433
|
-
|
|
5434
|
-
|
|
5435
|
-
|
|
5436
|
-
uptime: Math.floor((Date.now() - this.startedAt) / 1000),
|
|
5437
|
-
}));
|
|
6983
|
+
const health = this.getFleetHealth();
|
|
6984
|
+
// 503 when the fleet cannot do its job, so an external monitor sees it.
|
|
6985
|
+
// This used to always answer 200 "ok" with a count of CONFIGURED instances,
|
|
6986
|
+
// so every agent could be dead and every adapter down and it still looked
|
|
6987
|
+
// green.
|
|
6988
|
+
res.writeHead(health.status === "ok" ? 200 : 503);
|
|
6989
|
+
res.end(JSON.stringify(health));
|
|
5438
6990
|
return;
|
|
5439
6991
|
}
|
|
5440
6992
|
if (req.method === "GET" && req.url === "/status") {
|
|
5441
6993
|
const instances = Object.keys(this.fleetConfig?.instances ?? {}).map(name => {
|
|
5442
6994
|
const statusFile = join(this.getInstanceDir(name), "statusline.json");
|
|
5443
|
-
let context_pct = 0;
|
|
5444
6995
|
let cost = 0;
|
|
5445
6996
|
try {
|
|
5446
6997
|
const data = JSON.parse(readFileSync(statusFile, "utf-8"));
|
|
5447
|
-
context_pct = data.context_window?.used_percentage ?? 0;
|
|
5448
6998
|
cost = data.cost?.total_cost_usd ?? 0;
|
|
5449
6999
|
}
|
|
5450
7000
|
catch (err) {
|
|
5451
7001
|
this.logger.debug({ err, name }, "statusline.json read failed (/status)");
|
|
5452
7002
|
}
|
|
7003
|
+
const backend = this.fleetConfig?.instances[name]?.backend
|
|
7004
|
+
?? this.fleetConfig?.defaults?.backend
|
|
7005
|
+
?? "claude-code";
|
|
7006
|
+
const { context } = resolveInstanceContext(this.dataDir, name, backend);
|
|
5453
7007
|
return {
|
|
5454
7008
|
name,
|
|
5455
7009
|
status: this.getInstanceStatus(name),
|
|
5456
|
-
context_pct,
|
|
7010
|
+
context_pct: context ?? 0,
|
|
5457
7011
|
cost,
|
|
5458
7012
|
};
|
|
5459
7013
|
});
|
|
@@ -5559,7 +7113,7 @@ When users create specialized instances, suggest these configurations:
|
|
|
5559
7113
|
(async () => {
|
|
5560
7114
|
try {
|
|
5561
7115
|
const topicMode = this.fleetConfig?.channel?.mode === "topic";
|
|
5562
|
-
await this.startInstance(name, config, topicMode ?? false);
|
|
7116
|
+
await this.startInstance(name, config, topicMode ?? false, "fleet-topic", true);
|
|
5563
7117
|
this.emitSseEvent("status", this.getUiStatus());
|
|
5564
7118
|
res.writeHead(200);
|
|
5565
7119
|
res.end(JSON.stringify({ ok: true }));
|
|
@@ -5568,7 +7122,10 @@ When users create specialized instances, suggest these configurations:
|
|
|
5568
7122
|
res.writeHead(500);
|
|
5569
7123
|
res.end(JSON.stringify({ error: `Start failed: ${err.message}` }));
|
|
5570
7124
|
}
|
|
5571
|
-
|
|
7125
|
+
// The inner catch can itself throw (writeHead after a successful
|
|
7126
|
+
// writeHead is ERR_HTTP_HEADERS_SENT), and that rejection escapes the
|
|
7127
|
+
// IIFE. Same for the two handlers below.
|
|
7128
|
+
})().catch(err => this.logger.error({ err, name }, "HTTP start handler failed"));
|
|
5572
7129
|
return;
|
|
5573
7130
|
}
|
|
5574
7131
|
// Instance restart (immediate, no idle wait)
|
|
@@ -5589,7 +7146,7 @@ When users create specialized instances, suggest these configurations:
|
|
|
5589
7146
|
res.writeHead(status);
|
|
5590
7147
|
res.end(JSON.stringify({ error: `Restart failed: ${err.message}` }));
|
|
5591
7148
|
}
|
|
5592
|
-
})();
|
|
7149
|
+
})().catch(err => this.logger.error({ err, name }, "HTTP restart handler failed"));
|
|
5593
7150
|
return;
|
|
5594
7151
|
}
|
|
5595
7152
|
if (req.method === "POST" && req.url?.startsWith("/stop/")) {
|
|
@@ -5612,7 +7169,7 @@ When users create specialized instances, suggest these configurations:
|
|
|
5612
7169
|
res.writeHead(500);
|
|
5613
7170
|
res.end(JSON.stringify({ error: `Stop failed: ${err.message}` }));
|
|
5614
7171
|
}
|
|
5615
|
-
})();
|
|
7172
|
+
})().catch(err => this.logger.error({ err, name }, "HTTP stop handler failed"));
|
|
5616
7173
|
return;
|
|
5617
7174
|
}
|
|
5618
7175
|
// ── Agent CLI endpoint ─────
|
|
@@ -5624,6 +7181,8 @@ When users create specialized instances, suggest these configurations:
|
|
|
5624
7181
|
const url = new URL(req.url ?? "/", `http://localhost:${port}`);
|
|
5625
7182
|
if (handleViewRequest(req, res, url, this))
|
|
5626
7183
|
return;
|
|
7184
|
+
if (handleUsageRequest(req, res, url, this))
|
|
7185
|
+
return;
|
|
5627
7186
|
if (handleSettingsRequest(req, res, url, this))
|
|
5628
7187
|
return;
|
|
5629
7188
|
if (handleWebRequest(req, res, url, this))
|
|
@@ -5631,10 +7190,20 @@ When users create specialized instances, suggest these configurations:
|
|
|
5631
7190
|
res.writeHead(404);
|
|
5632
7191
|
res.end(JSON.stringify({ error: "not found" }));
|
|
5633
7192
|
});
|
|
7193
|
+
const markListening = (afterTakeover = false) => {
|
|
7194
|
+
this.healthServerListening = true;
|
|
7195
|
+
this.logger.info({ port }, afterTakeover
|
|
7196
|
+
? "Health endpoint listening (after takeover)"
|
|
7197
|
+
: "Health endpoint listening");
|
|
7198
|
+
this.logger.info({ url: `http://localhost:${port}/ui?token=${this.webToken}` }, "Web UI available");
|
|
7199
|
+
this.logger.info({ url: `http://localhost:${port}/view?token=${this.viewToken}` }, "Web View available");
|
|
7200
|
+
};
|
|
5634
7201
|
this.healthServer.on("error", (err) => {
|
|
7202
|
+
this.healthServerListening = false;
|
|
5635
7203
|
if (err.code === "EADDRINUSE") {
|
|
5636
7204
|
if (this.healthPortRetried) {
|
|
5637
|
-
this.logger.
|
|
7205
|
+
this.logger.error({ err, port }, "Health port still in use after takeover — dashboard disabled");
|
|
7206
|
+
this.notifyFleetError(`⚠️ Dashboard unavailable — health port ${port} is already in use. Stop the conflicting process or configure a different health_port.`);
|
|
5638
7207
|
return;
|
|
5639
7208
|
}
|
|
5640
7209
|
this.healthPortRetried = true;
|
|
@@ -5655,35 +7224,45 @@ When users create specialized instances, suggest these configurations:
|
|
|
5655
7224
|
setTimeout(() => {
|
|
5656
7225
|
if (!this.healthServer)
|
|
5657
7226
|
return;
|
|
5658
|
-
this.healthServer.listen(port, "127.0.0.1", () =>
|
|
5659
|
-
this.logger.info({ port }, "Health endpoint listening (after takeover)");
|
|
5660
|
-
});
|
|
7227
|
+
this.healthServer.listen(port, "127.0.0.1", () => markListening(true));
|
|
5661
7228
|
}, 1500);
|
|
5662
7229
|
return;
|
|
5663
7230
|
}
|
|
5664
7231
|
this.logger.error({ err, port }, "Health server error");
|
|
7232
|
+
this.notifyFleetError(`⚠️ Dashboard unavailable — health server failed: ${err.message}`);
|
|
5665
7233
|
});
|
|
5666
|
-
this.healthServer.listen(port, "127.0.0.1", () =>
|
|
5667
|
-
this.logger.info({ port }, "Health endpoint listening");
|
|
5668
|
-
});
|
|
5669
|
-
this.logger.info({ url: `http://localhost:${port}/ui?token=${this.webToken}` }, "Web UI available");
|
|
5670
|
-
this.logger.info({ url: `http://localhost:${port}/view?token=${this.viewToken}` }, "Web View available");
|
|
7234
|
+
this.healthServer.listen(port, "127.0.0.1", () => markListening());
|
|
5671
7235
|
}
|
|
5672
7236
|
getUiStatus() {
|
|
5673
|
-
const
|
|
7237
|
+
const fleetNames = Object.keys(this.fleetConfig?.instances ?? {});
|
|
7238
|
+
// Classic rooms live only in classicBot.yaml — /api/profiles merges them into
|
|
7239
|
+
// the View roster, but previously getUiStatus skipped them so context_pct was
|
|
7240
|
+
// always 0 (live map miss → l?.context_pct ?? 0).
|
|
7241
|
+
const classicOnly = (this.classicChannels?.getAll() ?? [])
|
|
7242
|
+
.map(ch => ch.instanceName)
|
|
7243
|
+
.filter(name => !fleetNames.includes(name));
|
|
7244
|
+
const names = [...fleetNames, ...classicOnly];
|
|
7245
|
+
const instances = names.map(name => {
|
|
5674
7246
|
const statusFile = join(this.getInstanceDir(name), "statusline.json");
|
|
5675
|
-
let context_pct = 0;
|
|
5676
7247
|
let cost = 0;
|
|
5677
7248
|
let model = "";
|
|
5678
7249
|
try {
|
|
5679
7250
|
const data = JSON.parse(readFileSync(statusFile, "utf-8"));
|
|
5680
|
-
context_pct = data.context_window?.used_percentage ?? 0;
|
|
5681
7251
|
cost = data.cost?.total_cost_usd ?? 0;
|
|
5682
7252
|
model = data.model?.display_name ?? "";
|
|
5683
7253
|
}
|
|
5684
7254
|
catch (err) {
|
|
5685
7255
|
this.logger.debug({ err, name }, "statusline.json read failed (getUiStatus)");
|
|
5686
7256
|
}
|
|
7257
|
+
// Align with /ctx: statusline for claude-code, pane scrape for kiro/grok/codex.
|
|
7258
|
+
const classic = classicOnly.includes(name);
|
|
7259
|
+
const backend = classic
|
|
7260
|
+
? this.classicChannels.getBackendByInstance(name, this.fleetConfig?.defaults?.backend)
|
|
7261
|
+
: (this.fleetConfig?.instances[name]?.backend
|
|
7262
|
+
?? this.fleetConfig?.defaults?.backend
|
|
7263
|
+
?? "claude-code");
|
|
7264
|
+
const { context } = resolveInstanceContext(this.dataDir, name, backend);
|
|
7265
|
+
const context_pct = context ?? 0;
|
|
5687
7266
|
return { name, status: this.getInstanceStatus(name), context_pct, cost, model };
|
|
5688
7267
|
});
|
|
5689
7268
|
return {
|