@songsid/agend 2.1.2-beta.3 → 2.1.2-beta.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. package/dist/access-path.js +15 -6
  2. package/dist/access-path.js.map +1 -1
  3. package/dist/agent-cli-instructions.md +1 -0
  4. package/dist/agent-cli.js +14 -0
  5. package/dist/agent-cli.js.map +1 -1
  6. package/dist/agent-endpoint.d.ts +2 -0
  7. package/dist/agent-endpoint.js +25 -1
  8. package/dist/agent-endpoint.js.map +1 -1
  9. package/dist/backend/antigravity.d.ts +20 -0
  10. package/dist/backend/antigravity.js +37 -3
  11. package/dist/backend/antigravity.js.map +1 -1
  12. package/dist/backend/claude-code.d.ts +59 -0
  13. package/dist/backend/claude-code.js +67 -1
  14. package/dist/backend/claude-code.js.map +1 -1
  15. package/dist/backend/codex.d.ts +3 -0
  16. package/dist/backend/codex.js +30 -0
  17. package/dist/backend/codex.js.map +1 -1
  18. package/dist/backend/grok.d.ts +25 -0
  19. package/dist/backend/grok.js +51 -0
  20. package/dist/backend/grok.js.map +1 -1
  21. package/dist/backend/kiro.d.ts +22 -0
  22. package/dist/backend/kiro.js +85 -3
  23. package/dist/backend/kiro.js.map +1 -1
  24. package/dist/backend/types.d.ts +58 -0
  25. package/dist/backend/types.js +13 -1
  26. package/dist/backend/types.js.map +1 -1
  27. package/dist/channel/adapters/discord.d.ts +15 -0
  28. package/dist/channel/adapters/discord.js +100 -2
  29. package/dist/channel/adapters/discord.js.map +1 -1
  30. package/dist/channel/adapters/telegram.d.ts +21 -0
  31. package/dist/channel/adapters/telegram.js +86 -0
  32. package/dist/channel/adapters/telegram.js.map +1 -1
  33. package/dist/channel/ipc-bridge.d.ts +9 -1
  34. package/dist/channel/ipc-bridge.js +12 -3
  35. package/dist/channel/ipc-bridge.js.map +1 -1
  36. package/dist/channel/ipc-timeouts.d.ts +46 -0
  37. package/dist/channel/ipc-timeouts.js +65 -0
  38. package/dist/channel/ipc-timeouts.js.map +1 -0
  39. package/dist/channel/mcp-server.js +30 -14
  40. package/dist/channel/mcp-server.js.map +1 -1
  41. package/dist/channel/mcp-tools.js +30 -1
  42. package/dist/channel/mcp-tools.js.map +1 -1
  43. package/dist/channel/reconnect-backoff.d.ts +17 -0
  44. package/dist/channel/reconnect-backoff.js +21 -0
  45. package/dist/channel/reconnect-backoff.js.map +1 -0
  46. package/dist/channel/types.d.ts +29 -0
  47. package/dist/classic-channel-manager.js +1 -5
  48. package/dist/classic-channel-manager.js.map +1 -1
  49. package/dist/cli.js +155 -63
  50. package/dist/cli.js.map +1 -1
  51. package/dist/completion.d.ts +27 -0
  52. package/dist/completion.js +121 -0
  53. package/dist/completion.js.map +1 -0
  54. package/dist/config-validator.js +21 -0
  55. package/dist/config-validator.js.map +1 -1
  56. package/dist/config.js +1 -0
  57. package/dist/config.js.map +1 -1
  58. package/dist/cost-guard.d.ts +3 -1
  59. package/dist/cost-guard.js +3 -1
  60. package/dist/cost-guard.js.map +1 -1
  61. package/dist/daemon.d.ts +240 -14
  62. package/dist/daemon.js +956 -308
  63. package/dist/daemon.js.map +1 -1
  64. package/dist/event-log.d.ts +31 -0
  65. package/dist/event-log.js +96 -0
  66. package/dist/event-log.js.map +1 -1
  67. package/dist/fleet-context.d.ts +9 -0
  68. package/dist/fleet-manager.d.ts +311 -2
  69. package/dist/fleet-manager.js +1369 -108
  70. package/dist/fleet-manager.js.map +1 -1
  71. package/dist/general-knowledge/skills/cross-instance-messaging/SKILL.md +22 -0
  72. package/dist/general-knowledge/skills/model-discovery/SKILL.md +14 -23
  73. package/dist/general-knowledge/skills/session-management/SKILL.md +15 -34
  74. package/dist/hang-detector.d.ts +19 -13
  75. package/dist/hang-detector.js +19 -49
  76. package/dist/hang-detector.js.map +1 -1
  77. package/dist/instance-lifecycle.d.ts +43 -1
  78. package/dist/instance-lifecycle.js +155 -43
  79. package/dist/instance-lifecycle.js.map +1 -1
  80. package/dist/instructions.d.ts +5 -0
  81. package/dist/instructions.js +9 -11
  82. package/dist/instructions.js.map +1 -1
  83. package/dist/locale.js +5 -1
  84. package/dist/locale.js.map +1 -1
  85. package/dist/logger.js +14 -0
  86. package/dist/logger.js.map +1 -1
  87. package/dist/mcp-liveness.d.ts +21 -0
  88. package/dist/mcp-liveness.js +27 -0
  89. package/dist/mcp-liveness.js.map +1 -0
  90. package/dist/outbound-handlers.d.ts +16 -0
  91. package/dist/outbound-handlers.js +151 -27
  92. package/dist/outbound-handlers.js.map +1 -1
  93. package/dist/outbound-schemas.d.ts +11 -3
  94. package/dist/outbound-schemas.js +16 -2
  95. package/dist/outbound-schemas.js.map +1 -1
  96. package/dist/pane-write-lock.d.ts +48 -0
  97. package/dist/pane-write-lock.js +73 -0
  98. package/dist/pane-write-lock.js.map +1 -0
  99. package/dist/process-memory.d.ts +31 -0
  100. package/dist/process-memory.js +79 -0
  101. package/dist/process-memory.js.map +1 -0
  102. package/dist/quickstart.js +17 -16
  103. package/dist/quickstart.js.map +1 -1
  104. package/dist/reply-dedup.d.ts +41 -0
  105. package/dist/reply-dedup.js +0 -0
  106. package/dist/reply-dedup.js.map +1 -0
  107. package/dist/scheduler/db.js +3 -0
  108. package/dist/scheduler/db.js.map +1 -1
  109. package/dist/sd-notify.d.ts +27 -0
  110. package/dist/sd-notify.js +33 -1
  111. package/dist/sd-notify.js.map +1 -1
  112. package/dist/secret-file.d.ts +33 -0
  113. package/dist/secret-file.js +36 -0
  114. package/dist/secret-file.js.map +1 -0
  115. package/dist/setup-wizard.js +9 -7
  116. package/dist/setup-wizard.js.map +1 -1
  117. package/dist/tmux-control.d.ts +58 -5
  118. package/dist/tmux-control.js +102 -14
  119. package/dist/tmux-control.js.map +1 -1
  120. package/dist/tmux-manager.d.ts +31 -1
  121. package/dist/tmux-manager.js +40 -11
  122. package/dist/tmux-manager.js.map +1 -1
  123. package/dist/topic-commands.d.ts +50 -10
  124. package/dist/topic-commands.js +269 -106
  125. package/dist/topic-commands.js.map +1 -1
  126. package/dist/tui-glyphs.d.ts +25 -0
  127. package/dist/tui-glyphs.js +26 -0
  128. package/dist/tui-glyphs.js.map +1 -0
  129. package/dist/types.d.ts +12 -2
  130. package/dist/ui/view.html +123 -2
  131. package/dist/update-marker.d.ts +15 -0
  132. package/dist/update-marker.js +69 -0
  133. package/dist/update-marker.js.map +1 -0
  134. package/dist/usage/format-rich.d.ts +11 -0
  135. package/dist/usage/format-rich.js +121 -0
  136. package/dist/usage/format-rich.js.map +1 -0
  137. package/dist/usage/providers.d.ts +130 -0
  138. package/dist/usage/providers.js +1030 -0
  139. package/dist/usage/providers.js.map +1 -0
  140. package/dist/usage/statusline-usage.d.ts +20 -0
  141. package/dist/usage/statusline-usage.js +120 -0
  142. package/dist/usage/statusline-usage.js.map +1 -0
  143. package/dist/usage/usage-api.d.ts +50 -0
  144. package/dist/usage/usage-api.js +167 -0
  145. package/dist/usage/usage-api.js.map +1 -0
  146. package/dist/view-api.d.ts +3 -0
  147. package/dist/view-api.js +11 -2
  148. package/dist/view-api.js.map +1 -1
  149. package/dist/web-api.js +5 -2
  150. package/dist/web-api.js.map +1 -1
  151. package/package.json +4 -1
  152. package/dist/channel/tool-tracker.d.ts +0 -13
  153. package/dist/channel/tool-tracker.js +0 -58
  154. package/dist/channel/tool-tracker.js.map +0 -1
  155. package/dist/daemon-entry.d.ts +0 -1
  156. package/dist/daemon-entry.js +0 -30
  157. package/dist/daemon-entry.js.map +0 -1
@@ -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 { sdNotify } from "./sd-notify.js";
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";
@@ -83,9 +87,74 @@ const CANCEL_BTN_MAX_RETRIES = 3;
83
87
  * buttons no clear trigger reached (e.g. a scheduled/HTTP turn that never called
84
88
  * reply). 5min (not the old 2s idle-watch) so Thinking isn't misread as idle. */
85
89
  const CANCEL_BTN_IDLE_CHECK_INTERVAL_MS = 5 * 60_000;
90
+ /**
91
+ * How long after a reply an instance gets to resume working before its cancel
92
+ * button is retired. A short turn ends with a reply and never works again → the
93
+ * button disappears ~2 minutes after the answer. A multi-step run replies
94
+ * mid-flight and keeps going → the grace check sees "working" and leaves the
95
+ * button alone (the idle edge retires it when the run really ends).
96
+ */
97
+ const REPLY_RETIRE_GRACE_MS = 2 * 60_000;
98
+ /**
99
+ * The daemon only broadcasts execution state on TRANSITIONS, so a long
100
+ * single-state run sends nothing for hours. The idle backstop therefore pokes a
101
+ * query each tick; a live daemon answers within milliseconds and refreshes the
102
+ * cache. When nothing has refreshed it for this long despite those pokes, the
103
+ * reporting chain (daemon, IPC, or state monitor) is dead and a "working" state
104
+ * from 30 minutes ago proves nothing — the button may be retired.
105
+ */
106
+ const STATE_REPORT_STALE_MS = 30 * 60_000;
107
+ /**
108
+ * Unconditional ceiling on a cancel button's life. Deliberately far beyond any
109
+ * legitimate run (multi-hour tasks are normal on this fleet): everything below
110
+ * this is decided by real state; a button that somehow survives a full day is
111
+ * wreckage, stuck or not.
112
+ */
113
+ const CANCEL_BTN_MAX_LIFETIME_MS = 24 * 60 * 60_000;
114
+ /** A click on a button the fleet no longer tracks may fire at most this often. */
115
+ const STALE_CANCEL_CLICK_COOLDOWN_MS = 10_000;
116
+ /** Orphaned-button ledger, swept at startup. Lives in the fleet data dir. */
117
+ const CANCEL_BTN_LEDGER_FILE = "cancel-buttons.json";
118
+ /**
119
+ * How often the cancel button's text is refreshed with elapsed working time.
120
+ *
121
+ * One edit per working instance per interval — at 60s that is trivial for both
122
+ * platforms' rate limits, and it reads as a live counter rather than a stale
123
+ * snapshot. Nothing new is posted, so the channel is never spammed: there is
124
+ * exactly one progress message per turn, and it is the cancel button itself.
125
+ */
126
+ const PROGRESS_UPDATE_INTERVAL_MS = 60_000;
127
+ /** Elapsed time is only shown once work has clearly outlasted a quick answer. */
128
+ /**
129
+ * Default delay before the button starts showing elapsed time. Configurable via
130
+ * `defaults.progress_min_elapsed` (seconds) in fleet.yaml. 30s is the balance
131
+ * point: most quick answers finish inside it (no churn for ordinary turns),
132
+ * while anything real shows signs of life well before the old two minutes.
133
+ */
134
+ const PROGRESS_MIN_ELAPSED_MS = 30_000;
135
+ /** How much of a tool summary the progress line will show before eliding. */
136
+ const PROGRESS_ACTIVITY_MAX_CHARS = 48;
137
+ /**
138
+ * Emoji AgEnD itself stamps on messages as the delivery-status ladder
139
+ * (⏳ queued, 👀 delivered, ✅ confirmed, ❌ failed). These are machine
140
+ * indicators, not opinions, so they never enter the reactions queue — from
141
+ * anyone. This exact-emoji filter is the ONLY bot filtering left: bot-to-bot
142
+ * reactions are otherwise delivered on purpose (agents signal each other), and
143
+ * 🫡 passes too — it reads as a deliberate acknowledgement, not plumbing.
144
+ */
145
+ const DELIVERY_STATUS_EMOJIS = new Set(["👀", "⏳", "✅", "❌"]);
146
+ /**
147
+ * How long a delivery waits out a disconnected instance IPC before giving up.
148
+ *
149
+ * Sized for a daemon restart (socket close → respawn → CLI ready), which is the
150
+ * event this exists for. Past it the delivery fails loudly as it always did.
151
+ */
152
+ const IPC_RECONNECT_GRACE_MS = 30_000;
153
+ const IPC_RECONNECT_POLL_MS = 250;
86
154
  const CLASSIC_BACKEND_SELECTION_TIMEOUT_MS = 60_000;
87
155
  const CLASSIC_BACKEND_CALLBACK_PREFIX = "classic-backend:";
88
156
  const MODEL_SELECT_CALLBACK_PREFIX = "model-select:";
157
+ const EFFORT_SELECT_CALLBACK_PREFIX = "effort-select:";
89
158
  const CLI_ENV_TTL_MS = 24 * 60 * 60 * 1000; // /model reads cached CLI env within 24h
90
159
  export class FleetManager {
91
160
  dataDir;
@@ -93,7 +162,7 @@ export class FleetManager {
93
162
  static sighupHandlerInstalled = false;
94
163
  children = new Map();
95
164
  lifecycle;
96
- /** @deprecated Use lifecycle.daemons — kept for backward compat */
165
+ /** Live view of lifecycle.daemons — used throughout; not deprecated. */
97
166
  get daemons() { return this.lifecycle.daemons; }
98
167
  fleetConfig = null;
99
168
  rawFleetConfig = {};
@@ -151,6 +220,12 @@ export class FleetManager {
151
220
  // reply, on cancel, or when a newer button supersedes it for the same
152
221
  // instance. Per-button tracking means a failed delete never strands a button.
153
222
  cancelButtons = new Map();
223
+ /** Duplicate-reply suppression across both the MCP and HTTP reply paths. */
224
+ replyDeduper = new ReplyDeduper();
225
+ /** instanceName → what it is doing right now, when the backend can tell us. */
226
+ instanceActivity = new Map();
227
+ /** instanceName → tail of deliveries waiting for its IPC to come back. */
228
+ ipcWaitTails = new Map();
154
229
  // Last user message delivered to each instance — used to react ✅ on completion.
155
230
  lastInboundMsg = new Map();
156
231
  topicArchiver;
@@ -158,11 +233,17 @@ export class FleetManager {
158
233
  classicChannels = null;
159
234
  pendingClassicStarts = new Map();
160
235
  /** In-flight /model selections, keyed by nonce (see handleModelSelection). */
236
+ /** In-flight /effort selections, same coordinator shape as pendingModelSelects. */
237
+ pendingEffortSelects = new Map();
161
238
  pendingModelSelects = new Map();
162
239
  // Model failover state
163
240
  failoverActive = new Map(); // instance → current failover model
164
241
  // IPC reconnect: tracks instances being intentionally stopped (skip reconnect)
242
+ /** instance → when a click with no live button entry last fired a cancel. */
243
+ staleCancelClickAt = new Map();
165
244
  ipcStoppingInstances = new Set();
245
+ /** Set the moment a graceful stop begins — see isPlannedRestart(). */
246
+ shuttingDown = false;
166
247
  /** Coalesce concurrent connection attempts for the same daemon socket. */
167
248
  ipcConnectInFlight = new Map();
168
249
  /** At most one reconnect/backoff loop may exist per instance. */
@@ -176,6 +257,10 @@ export class FleetManager {
176
257
  healthServer = null;
177
258
  healthPortRetried = false;
178
259
  updateCheckTimer = null;
260
+ eventLogPruneTimer = null;
261
+ logRotateTimer = null;
262
+ /** Days of event/activity history to keep. */
263
+ static EVENT_LOG_RETENTION_DAYS = 30;
179
264
  watchdogTimer = null;
180
265
  startedAt = 0;
181
266
  // Mirror topic: buffer cross-instance messages, flush every 3s
@@ -214,7 +299,13 @@ export class FleetManager {
214
299
  }
215
300
  this.reloadPending = false;
216
301
  this.reconcileInFlight = this.reconcileInstances()
217
- .catch(err => this.logger.error({ err }, "SIGHUP config reload failed"))
302
+ .catch(err => {
303
+ // Almost always a YAML parse error. Log-only meant the user edited
304
+ // fleet.yaml, sent SIGHUP, and got no reaction and no explanation.
305
+ this.logger.error({ err }, "SIGHUP config reload failed");
306
+ const message = err instanceof Error ? err.message : String(err);
307
+ this.notifyFleetError(`⚠️ fleet.yaml reload FAILED — ${message}\nThe previous configuration is still running.`);
308
+ })
218
309
  .finally(() => {
219
310
  this.reconcileInFlight = null;
220
311
  if (this.reloadPending && this.startupComplete) {
@@ -222,16 +313,55 @@ export class FleetManager {
222
313
  }
223
314
  });
224
315
  }
316
+ /**
317
+ * Is the fleet going down (or coming back up) on purpose?
318
+ *
319
+ * Instances dying during a planned restart is the restart working, not an
320
+ * incident — but the code that notices a dead pane or a dead MCP server
321
+ * cannot tell the difference on its own. Two sources, because the noise
322
+ * starts before this process is even told to stop: `agend update` replaces
323
+ * the package on disk while this daemon is still running and still watching.
324
+ */
325
+ isPlannedRestart() {
326
+ return this.shuttingDown || isUpdateInProgress(this.dataDir);
327
+ }
225
328
  finishStartup() {
226
329
  this.startupComplete = true;
330
+ // We are the post-update fleet: the update is over by definition. Clearing
331
+ // it here (rather than in the update command, which exits before the new
332
+ // fleet is up) is what keeps the quiet window from outliving the restart.
333
+ clearUpdateMarker(this.dataDir);
227
334
  if (this.reloadPending)
228
335
  this.scheduleReconcile();
336
+ void this.sweepOrphanedCancelButtons();
229
337
  }
230
338
  // ── ArchiverContext bridge ────────────────────────────────────────────
231
339
  lastActivityMs(name) {
232
340
  return this.lastActivity.get(name) ?? 0;
233
341
  }
342
+ /**
343
+ * Is the instance between turns?
344
+ *
345
+ * Prefers the daemon's pane state machine (debounced, busy-pattern aware) over
346
+ * the control client's raw 2-second output-silence heuristic. The raw heuristic
347
+ * reads every >2s output lull as idle — and long silent tools (a build, a test
348
+ * run) or an LLM pause produce those constantly mid-turn. That misreading is
349
+ * what retired cancel buttons in the middle of long work (the 5-minute backstop
350
+ * fired during a lull) and froze their progress text (ticker skipped "idle"
351
+ * ticks). The silence heuristic remains only as the fallback for instances
352
+ * whose daemon has not reported a state yet.
353
+ */
234
354
  getInstanceIdle(name) {
355
+ // A daemon that is not running cannot be mid-turn. This is what a stale
356
+ // "working" cache after a hard daemon kill (SIGKILL/OOM — no IPC crash
357
+ // report ever arrives) must not override.
358
+ if (this.getInstanceStatus(name) !== "running")
359
+ return true;
360
+ const state = this.getInstanceExecutionState(name);
361
+ if (state === "working" || state === "stuck")
362
+ return false;
363
+ if (state === "idle")
364
+ return true;
235
365
  try {
236
366
  const widFile = join(this.getInstanceDir(name), "window-id");
237
367
  if (!existsSync(widFile))
@@ -243,6 +373,18 @@ export class FleetManager {
243
373
  return true;
244
374
  }
245
375
  }
376
+ /**
377
+ * True when the instance claims working/stuck but nothing has refreshed that
378
+ * claim for STATE_REPORT_STALE_MS despite the backstop's per-tick queries.
379
+ * Measures the CACHE's age, not the button's — a healthy multi-hour run
380
+ * answers every query and never trips this.
381
+ */
382
+ stateReportDead(name) {
383
+ const cached = this.instanceStateCache.get(name);
384
+ if (!cached)
385
+ return false; // no claim to distrust — getInstanceIdle owns this case
386
+ return Date.now() - cached.receivedAt > STATE_REPORT_STALE_MS;
387
+ }
246
388
  // ── LifecycleContext bridge methods ──────────────────────────────────────
247
389
  webhookEmit(event, name, data) {
248
390
  this.webhookEmitter?.emit(event, name, data);
@@ -471,14 +613,21 @@ export class FleetManager {
471
613
  unchangedForMs: numberOr(msg.unchangedForMs, previous?.unchangedForMs ?? 0),
472
614
  observedAt: numberOr(msg.observedAt, now),
473
615
  stateChangedAt: numberOr(msg.stateChangedAt, previous?.state === state ? previous.stateChangedAt : now),
616
+ // Fleet-manager receipt time, NOT the daemon's observation time: staleness
617
+ // asks "is anyone still reporting", which only the receiver can date.
618
+ receivedAt: now,
474
619
  });
475
620
  for (const check of this.instanceIdleWaiters.get(name) ?? [])
476
621
  check();
477
622
  // warm_cap: a fresh transition into idle may free this instance for eviction,
478
623
  // or (more usefully) reveal that the fleet is now over cap. Only fire on the
479
624
  // edge into idle, not on every idle heartbeat.
480
- if (state === "idle" && previous?.state !== "idle")
625
+ if (state === "idle" && previous?.state !== "idle") {
481
626
  this.enforceWarmCap();
627
+ // The turn is genuinely over — retire the cancel/progress button now rather
628
+ // than waiting for the 5-minute idle backstop to notice.
629
+ this.retireInstanceButtons(name);
630
+ }
482
631
  }
483
632
  cacheInstanceProcessStatus(name, status) {
484
633
  if (status === "running") {
@@ -583,12 +732,70 @@ export class FleetManager {
583
732
  if (!idle) {
584
733
  this.logger.warn({ instanceName, timeoutMs }, "Idle gate timed out; forcing delivery");
585
734
  }
586
- const ipc = this.instanceIpcClients.get(instanceName);
587
- if (!ipc?.connected)
588
- throw new Error(`Instance '${instanceName}' IPC is unavailable`);
589
- ipc.send(payload);
735
+ await this.sendWhenConnected(instanceName, payload);
590
736
  this.lastDeliveryAt.set(instanceName, Date.now());
591
737
  }
738
+ /**
739
+ * Hand a payload to an instance's IPC, waiting out a *transient* disconnect.
740
+ *
741
+ * A daemon that is restarting — `/restart`, crash recovery, a model switch —
742
+ * drops its socket for a few seconds. Any message arriving in that window used
743
+ * to fail instantly: the caller logged a warning, put ❌ on the user's message,
744
+ * and the message was gone. The user had to notice the ❌ and retype it. That is
745
+ * the "instance 訊息不容易掉" goal failing on the most predictable event there is.
746
+ *
747
+ * The wait is bounded. If the instance is genuinely down, this still throws and
748
+ * the ❌ still appears — just for a real failure rather than a restart.
749
+ *
750
+ * Ordering is preserved by serialising behind any waiter already queued for this
751
+ * instance, *including* when the socket happens to be up: otherwise a message
752
+ * arriving after the reconnect could overtake one that has been waiting for it.
753
+ */
754
+ async sendWhenConnected(instanceName, payload) {
755
+ const queued = this.ipcWaitTails.get(instanceName);
756
+ if (!queued) {
757
+ const ipc = this.instanceIpcClients.get(instanceName);
758
+ if (ipc?.connected && ipc.send(payload))
759
+ return;
760
+ }
761
+ const attempt = (queued ?? Promise.resolve())
762
+ .catch(() => { })
763
+ .then(() => this.sendAfterIpcReturns(instanceName, payload));
764
+ // The chain stores a settled-either-way promise so one failed delivery cannot
765
+ // wedge every later one, and so `queued` above is safe to await unguarded.
766
+ const tail = attempt.catch(() => { });
767
+ this.ipcWaitTails.set(instanceName, tail);
768
+ try {
769
+ await attempt;
770
+ }
771
+ finally {
772
+ // Only the last waiter clears the chain; while a queue is still draining the
773
+ // map must keep pointing at it or ordering is lost.
774
+ if (this.ipcWaitTails.get(instanceName) === tail) {
775
+ this.ipcWaitTails.delete(instanceName);
776
+ }
777
+ }
778
+ }
779
+ /** Poll for the instance's IPC to come back, then send. Throws if it does not. */
780
+ async sendAfterIpcReturns(instanceName, payload) {
781
+ const deadline = Date.now() + IPC_RECONNECT_GRACE_MS;
782
+ let warned = false;
783
+ for (;;) {
784
+ // Re-read every round: a reconnect replaces the IpcClient object entirely,
785
+ // so a cached reference would stay dead forever.
786
+ const ipc = this.instanceIpcClients.get(instanceName);
787
+ if (ipc?.connected && ipc.send(payload))
788
+ return;
789
+ if (Date.now() >= deadline) {
790
+ throw new Error(`Instance '${instanceName}' IPC is unavailable`);
791
+ }
792
+ if (!warned) {
793
+ warned = true;
794
+ this.logger.info({ instanceName }, "Instance IPC is down — holding delivery until it reconnects");
795
+ }
796
+ await new Promise(resolve => setTimeout(resolve, IPC_RECONNECT_POLL_MS));
797
+ }
798
+ }
592
799
  /** Single delivery facade: wake paused CLIs and serialize non-user work behind idle. */
593
800
  async deliverToInstance(instanceName, payload, options = {}) {
594
801
  const meta = payload.meta && typeof payload.meta === "object"
@@ -604,10 +811,7 @@ export class FleetManager {
604
811
  await this.lifecycle.wake(instanceName, 30_000);
605
812
  this.enforceWarmCap(instanceName); // woke one → evict a different LRU idle if over cap
606
813
  }
607
- const ipc = this.instanceIpcClients.get(instanceName);
608
- if (!ipc?.connected)
609
- throw new Error(`Instance '${instanceName}' IPC is unavailable`);
610
- ipc.send(payload);
814
+ await this.sendWhenConnected(instanceName, payload);
611
815
  // A cross-instance item arriving before the daemon observes this turn as
612
816
  // working must not trust the stale idle snapshot from before the send.
613
817
  this.lastDeliveryAt.set(instanceName, Date.now());
@@ -655,7 +859,7 @@ export class FleetManager {
655
859
  await new Promise(resolve => setTimeout(resolve, 250));
656
860
  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
861
  }
658
- async startInstance(name, config, topicMode) {
862
+ async startInstance(name, config, topicMode, kind = "fleet-topic") {
659
863
  if (this.lifecycle.isPaused(name)) {
660
864
  this.logger.info({ name }, "Persisted paused instance — skipping startup");
661
865
  return;
@@ -671,7 +875,11 @@ export class FleetManager {
671
875
  this.ensureGeneralInstructions(config.working_directory, config.backend);
672
876
  }
673
877
  this.instanceProcessStatus.delete(name);
674
- await this.lifecycle.start(name, config, topicMode);
878
+ await this.lifecycle.start(name, config, topicMode, {
879
+ kind,
880
+ backend: config.backend ?? this.fleetConfig?.defaults?.backend ?? "claude-code",
881
+ model: this.resolveInstanceModel(name).display,
882
+ });
675
883
  // Auto-connect IPC — daemon.start() ensures socket is ready before resolving
676
884
  await this.connectIpcToInstance(name);
677
885
  }
@@ -834,7 +1042,10 @@ export class FleetManager {
834
1042
  const eqIdx = trimmed.indexOf("=");
835
1043
  if (eqIdx < 0)
836
1044
  continue;
837
- const key = trimmed.slice(0, eqIdx);
1045
+ // Accept `export KEY=value` the shell-style form people paste from their
1046
+ // .bashrc. Without this the variable landed in process.env under the key
1047
+ // "export KEY" and silently did nothing.
1048
+ const key = trimmed.slice(0, eqIdx).replace(/^export\s+/, "").trim();
838
1049
  const raw = trimmed.slice(eqIdx + 1);
839
1050
  const value = raw.replace(/^["'](.*)["']$/, '$1');
840
1051
  // .env file always wins over inherited shell env vars, so that
@@ -846,10 +1057,12 @@ export class FleetManager {
846
1057
  async startAll(configPath) {
847
1058
  FleetManager.signalTarget = this;
848
1059
  this.startupComplete = false;
1060
+ // Cleared here, not at the end of doStopAll: a stop has an async tail, and
1061
+ // anything arriving during it is still part of the stop.
1062
+ this.shuttingDown = false;
849
1063
  this.configPath = configPath;
850
1064
  this.loadEnvFile();
851
1065
  // Rotate fleet.log if oversized (before any logging)
852
- const { rotateLogIfNeeded } = await import("./logger.js");
853
1066
  rotateLogIfNeeded(join(this.dataDir, "fleet.log"));
854
1067
  const fleet = this.loadConfig(configPath);
855
1068
  setLocale(detectLocale(fleet)); // user-facing text language (fleet.yaml defaults.locale / timezone)
@@ -893,7 +1106,7 @@ export class FleetManager {
893
1106
  }
894
1107
  const pidPath = join(this.dataDir, "fleet.pid");
895
1108
  writeFileSync(pidPath, String(process.pid), "utf-8");
896
- this.eventLog = new EventLog(join(this.dataDir, "events.db"));
1109
+ this.eventLog = this.openEventLog();
897
1110
  // Initialize classic channel manager. The primary adapter (channels[0])
898
1111
  // migrates legacy single-bot entries and names without a suffix. Classic
899
1112
  // routing does NOT go through the routing engine (single-key, can't hold two
@@ -982,6 +1195,10 @@ export class FleetManager {
982
1195
  // Rotate fleet.log daily too (besides the startup size check above), so a
983
1196
  // long-running fleet doesn't accumulate an unbounded log.
984
1197
  rotateLogIfNeeded(join(this.dataDir, "fleet.log"));
1198
+ // Instance output.log is pipe-pane (TUI ANSI). Daemon health ticks rotate a
1199
+ // running instance's own log; this sweep is the safety net for every other
1200
+ // kind. One implementation, so the two cannot cover different sets.
1201
+ this.rotateAllInstanceLogs();
985
1202
  }, () => {
986
1203
  const instances = Object.keys(this.fleetConfig?.instances ?? {});
987
1204
  const costMap = new Map();
@@ -1121,9 +1338,29 @@ export class FleetManager {
1121
1338
  }
1122
1339
  }
1123
1340
  }
1124
- // Signal systemd: generals ready
1125
- sdNotify("READY=1");
1341
+ // The systemd watchdog answers exactly one question: is this process still
1342
+ // turning its event loop? Pinging from a timer proves that, and after the
1343
+ // blocking child-process calls were made async it is a meaningful signal —
1344
+ // a deadlocked or frozen fleet stops pinging and systemd restarts it.
1345
+ //
1346
+ // It deliberately does NOT gate on fleet health. "No adapter connected" or
1347
+ // "an instance crashed" must not kill the process: the fleet would be restarted
1348
+ // into the same broken state, and a user who has legitimately stopped every
1349
+ // instance would get a restart loop. Those conditions surface through /health
1350
+ // (which now returns 503) and through the General-topic notifications instead.
1126
1351
  this.watchdogTimer = setInterval(() => sdNotify("WATCHDOG=1"), 30_000);
1352
+ // EventLog.prune() existed but was never called, so `events` and `activity`
1353
+ // grew without bound for the life of the install. Prune once at startup and
1354
+ // daily after that; the timer is unref'd so it never holds the loop open.
1355
+ this.pruneEventLog();
1356
+ this.eventLogPruneTimer = setInterval(() => this.pruneEventLog(), 24 * 60 * 60_000);
1357
+ this.eventLogPruneTimer.unref?.();
1358
+ // Same shape for pipe-pane logs, and for the same reason: the only sweep that
1359
+ // covered them lived inside the daily-summary callback, so it did not run at
1360
+ // all when summaries were off.
1361
+ this.rotateAllInstanceLogs();
1362
+ this.logRotateTimer = setInterval(() => this.rotateAllInstanceLogs(), 24 * 60 * 60_000);
1363
+ this.logRotateTimer.unref?.();
1127
1364
  // Phase 2: Start remaining instances with staggered concurrency
1128
1365
  if (others.length > 0) {
1129
1366
  await this.startInstancesWithConcurrency(others, topicMode);
@@ -1259,6 +1496,15 @@ export class FleetManager {
1259
1496
  // rest of startup finishes. Replay one coalesced reload only after all
1260
1497
  // startup-owned lifecycle work and signal handlers are in place.
1261
1498
  this.finishStartup();
1499
+ // Tell systemd we are ready only now. This used to fire right after the
1500
+ // generals started — before adapters, classic instances, topic creation and the
1501
+ // health server — so `systemctl start` returned success while the fleet was
1502
+ // still deaf: no path existed for a user message to arrive.
1503
+ sdNotify("READY=1");
1504
+ const health = this.getFleetHealth();
1505
+ if (health.status !== "ok") {
1506
+ this.logger.warn({ health }, "Fleet started with problems — see /health");
1507
+ }
1262
1508
  }
1263
1509
  /**
1264
1510
  * Delete inbox files older than retentionDays (by mtime). Cleans the shared
@@ -1375,6 +1621,67 @@ export class FleetManager {
1375
1621
  getAdapterStates() {
1376
1622
  return this.adapterState;
1377
1623
  }
1624
+ /**
1625
+ * Real, checkable fleet health for `/health` and the operator.
1626
+ *
1627
+ * `status` is:
1628
+ * - `ok` — at least one adapter connected and every configured instance
1629
+ * that should be running is running
1630
+ * - `degraded` — reachable, but something the operator should look at (an
1631
+ * adapter retrying, an instance crashed or stopped)
1632
+ * - `down` — the fleet cannot do its job: no adapter is connected, so no
1633
+ * message can arrive or be answered
1634
+ *
1635
+ * Deliberately does NOT gate the systemd watchdog — see the comment at the
1636
+ * WATCHDOG timer for why.
1637
+ */
1638
+ getFleetHealth() {
1639
+ const names = Object.keys(this.fleetConfig?.instances ?? {});
1640
+ const counts = { configured: names.length, running: 0, crashed: 0, paused: 0, stopped: 0 };
1641
+ for (const name of names) {
1642
+ const state = this.getInstanceStatus(name);
1643
+ if (state === "running")
1644
+ counts.running++;
1645
+ else if (state === "crashed")
1646
+ counts.crashed++;
1647
+ else if (state === "paused")
1648
+ counts.paused++;
1649
+ else
1650
+ counts.stopped++;
1651
+ }
1652
+ const states = {};
1653
+ let connected = 0;
1654
+ for (const [id, state] of this.adapterState) {
1655
+ states[id] = state.status;
1656
+ if (state.status === "connected")
1657
+ connected++;
1658
+ }
1659
+ const problems = [];
1660
+ if (this.adapterState.size > 0 && connected === 0)
1661
+ problems.push("no channel adapter is connected");
1662
+ if (counts.crashed > 0)
1663
+ problems.push(`${counts.crashed} instance(s) crashed`);
1664
+ for (const [id, state] of this.adapterState) {
1665
+ if (state.status !== "connected")
1666
+ problems.push(`adapter ${id} is ${state.status}`);
1667
+ }
1668
+ if (!this.startupComplete)
1669
+ problems.push("startup has not completed");
1670
+ // "down" is reserved for "cannot receive or answer a message at all". A fleet
1671
+ // with adapters configured but none connected is exactly that.
1672
+ const status = this.adapterState.size > 0 && connected === 0
1673
+ ? "down"
1674
+ : problems.length > 0 ? "degraded" : "ok";
1675
+ return {
1676
+ status,
1677
+ uptime: Math.floor((Date.now() - this.startedAt) / 1000),
1678
+ instances: counts,
1679
+ adapters: { total: this.adapterState.size, connected, states },
1680
+ startupComplete: this.startupComplete,
1681
+ memory: readFleetMemory(),
1682
+ problems,
1683
+ };
1684
+ }
1378
1685
  /** Start the primary adapter (backward-compatible, sets this.adapter) */
1379
1686
  async startSingleAdapter(fleet, channelConfig) {
1380
1687
  const botToken = process.env[channelConfig.bot_token_env];
@@ -1401,11 +1708,16 @@ export class FleetManager {
1401
1708
  this.adapter.on("message", safeHandler(async (msg) => {
1402
1709
  await this.handleInboundMessage(msg);
1403
1710
  }, this.logger, "adapter.message"));
1711
+ this.adapter.on("reaction", safeHandler(async (r) => {
1712
+ await this.handleInboundReaction(r);
1713
+ }, this.logger, "adapter.reaction"));
1404
1714
  this.adapter.on("callback_query", safeHandler(async (data) => {
1405
1715
  if (await this.handleClassicBackendSelection(data))
1406
1716
  return;
1407
1717
  if (await this.handleModelSelection(data))
1408
1718
  return;
1719
+ if (await this.handleEffortSelection(data))
1720
+ return;
1409
1721
  if (data.callbackData.startsWith("hang:")) {
1410
1722
  const parts = data.callbackData.split(":");
1411
1723
  const action = parts[1];
@@ -1426,12 +1738,7 @@ export class FleetManager {
1426
1738
  return;
1427
1739
  }
1428
1740
  if (data.callbackData.startsWith("cancel:")) {
1429
- const instanceName = data.callbackData.slice("cancel:".length);
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);
1741
+ this.handleCancelClick(data.callbackData.slice("cancel:".length), this.adapter, data);
1435
1742
  return;
1436
1743
  }
1437
1744
  }, this.logger, "adapter.callback_query"));
@@ -1511,6 +1818,9 @@ export class FleetManager {
1511
1818
  else if (data.command === "model") {
1512
1819
  await this.handleModelSlash(data, adapterId);
1513
1820
  }
1821
+ else if (data.command === "effort") {
1822
+ await this.handleEffortSlash(data, adapterId);
1823
+ }
1514
1824
  else if (data.command === "cancel") {
1515
1825
  const name = this.resolveSlashTarget(data.channelId, adapterId);
1516
1826
  if (!name) {
@@ -1575,19 +1885,29 @@ export class FleetManager {
1575
1885
  await data.respond(t("not_authorized"));
1576
1886
  return;
1577
1887
  }
1888
+ await data.respond(await this.runBackendDoctor());
1889
+ }
1890
+ else if (data.command === "usage") {
1891
+ // Same permission level as /ctx (none). The reply is still ephemeral —
1892
+ // the adapter defers non-chat commands that way — so it never spams the
1893
+ // channel either way.
1578
1894
  try {
1579
- const { execSync } = await import("node:child_process");
1580
- const backend = this.fleetConfig?.defaults?.backend || "claude-code";
1581
- const result = execSync(`agend backend doctor ${backend}`, { timeout: 30_000, encoding: "utf-8" });
1582
- const clean = result.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, "");
1583
- await data.respond(clean || "No output");
1895
+ const { getUsageSnapshot } = await import("./usage/usage-api.js");
1896
+ const { renderUsageMarkdown } = await import("./usage/format-rich.js");
1897
+ // slash_command is Discord-only; editReply renders Markdown natively.
1898
+ await data.respond(renderUsageMarkdown(await getUsageSnapshot()));
1584
1899
  }
1585
1900
  catch (err) {
1586
- const output = (err.stdout ?? err.message ?? "Doctor failed").replace(/\x1b\[[0-9;]*[a-zA-Z]/g, "");
1587
- await data.respond(output);
1901
+ await data.respond(`⚠️ Usage fetch failed: ${err.message}`);
1588
1902
  }
1589
1903
  }
1590
1904
  else if (data.command === "status") {
1905
+ // Admin-gated (like the topic path): the merged table shows every
1906
+ // instance's cost and IPC health.
1907
+ if (!this.isFleetAdmin(data.userId, adapterId)) {
1908
+ await data.respond(t("cmd.admin_required", "/status"));
1909
+ return;
1910
+ }
1591
1911
  const text = await this.topicCommands.getStatusText();
1592
1912
  await data.respond(text);
1593
1913
  }
@@ -1696,11 +2016,16 @@ export class FleetManager {
1696
2016
  adapter.on("message", safeHandler(async (msg) => {
1697
2017
  await this.handleInboundMessage(msg);
1698
2018
  }, this.logger, `adapter[${adapterId}].message`));
2019
+ adapter.on("reaction", safeHandler(async (r) => {
2020
+ await this.handleInboundReaction(r);
2021
+ }, this.logger, `adapter[${adapterId}].reaction`));
1699
2022
  adapter.on("callback_query", safeHandler(async (data) => {
1700
2023
  if (await this.handleClassicBackendSelection(data))
1701
2024
  return;
1702
2025
  if (await this.handleModelSelection(data))
1703
2026
  return;
2027
+ if (await this.handleEffortSelection(data))
2028
+ return;
1704
2029
  if (data.callbackData.startsWith("hang:")) {
1705
2030
  const parts = data.callbackData.split(":");
1706
2031
  const action = parts[1];
@@ -1720,10 +2045,7 @@ export class FleetManager {
1720
2045
  return;
1721
2046
  }
1722
2047
  if (data.callbackData.startsWith("cancel:")) {
1723
- const instanceName = data.callbackData.slice("cancel:".length);
1724
- // Idempotent: only the first click (while the button is live) acts.
1725
- if (this.hasCancelButton(instanceName))
1726
- this.cancelInstance(instanceName);
2048
+ this.handleCancelClick(data.callbackData.slice("cancel:".length), adapter, data);
1727
2049
  return;
1728
2050
  }
1729
2051
  }, this.logger, `adapter[${adapterId}].callback_query`));
@@ -1793,6 +2115,9 @@ export class FleetManager {
1793
2115
  else if (data.command === "model") {
1794
2116
  await this.handleModelSlash(data, adapterId);
1795
2117
  }
2118
+ else if (data.command === "effort") {
2119
+ await this.handleEffortSlash(data, adapterId);
2120
+ }
1796
2121
  else if (data.command === "cancel") {
1797
2122
  const name = this.resolveSlashTarget(data.channelId, adapterId);
1798
2123
  if (!name) {
@@ -1857,19 +2182,29 @@ export class FleetManager {
1857
2182
  await data.respond(t("not_authorized"));
1858
2183
  return;
1859
2184
  }
2185
+ await data.respond(await this.runBackendDoctor());
2186
+ }
2187
+ else if (data.command === "usage") {
2188
+ // Same permission level as /ctx (none). The reply is still ephemeral —
2189
+ // the adapter defers non-chat commands that way — so it never spams the
2190
+ // channel either way.
1860
2191
  try {
1861
- const { execSync } = await import("node:child_process");
1862
- const backend = this.fleetConfig?.defaults?.backend || "claude-code";
1863
- const result = execSync(`agend backend doctor ${backend}`, { timeout: 30_000, encoding: "utf-8" });
1864
- const clean = result.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, "");
1865
- await data.respond(clean || "No output");
2192
+ const { getUsageSnapshot } = await import("./usage/usage-api.js");
2193
+ const { renderUsageMarkdown } = await import("./usage/format-rich.js");
2194
+ // slash_command is Discord-only; editReply renders Markdown natively.
2195
+ await data.respond(renderUsageMarkdown(await getUsageSnapshot()));
1866
2196
  }
1867
2197
  catch (err) {
1868
- const output = (err.stdout ?? err.message ?? "Doctor failed").replace(/\x1b\[[0-9;]*[a-zA-Z]/g, "");
1869
- await data.respond(output);
2198
+ await data.respond(`⚠️ Usage fetch failed: ${err.message}`);
1870
2199
  }
1871
2200
  }
1872
2201
  else if (data.command === "status") {
2202
+ // Admin-gated (like the topic path): the merged table shows every
2203
+ // instance's cost and IPC health.
2204
+ if (!this.isFleetAdmin(data.userId, adapterId)) {
2205
+ await data.respond(t("cmd.admin_required", "/status"));
2206
+ return;
2207
+ }
1873
2208
  const text = await this.topicCommands.getStatusText();
1874
2209
  await data.respond(text);
1875
2210
  }
@@ -2025,6 +2360,9 @@ export class FleetManager {
2025
2360
  else if (msg.type === "instance_process_state") {
2026
2361
  this.cacheInstanceProcessStatus(name, msg.status);
2027
2362
  }
2363
+ else if (msg.type === "instance_activity") {
2364
+ this.cacheInstanceActivity(name, msg.activity);
2365
+ }
2028
2366
  else if (msg.type === "instance_state" || msg.type === "instance_state_response") {
2029
2367
  this.cacheInstanceExecutionState(name, msg);
2030
2368
  if (msg.type === "instance_state_response") {
@@ -2095,9 +2433,22 @@ export class FleetManager {
2095
2433
  if (existsSync(windowIdPath)) {
2096
2434
  const windowId = readFileSync(windowIdPath, "utf-8").trim();
2097
2435
  if (windowId) {
2436
+ // Async with an explicit timeout: this was execSync with NO timeout at
2437
+ // all, so a wedged tmux server blocked the whole fleet event loop
2438
+ // indefinitely — while we were here to diagnose a lost connection.
2439
+ // A timeout is also the correct signal: an unresponsive tmux server
2440
+ // means we cannot verify the pane, which is treated as dead (the same
2441
+ // conclusion the old code reached only by throwing).
2098
2442
  try {
2099
- const { execSync } = await import("node:child_process");
2100
- execSync(`tmux list-panes -t "${windowId}"`, { stdio: "ignore" });
2443
+ const { execFile } = await import("node:child_process");
2444
+ const { promisify } = await import("node:util");
2445
+ const { getTmuxSocketName } = await import("./paths.js");
2446
+ // Honour socket isolation: without -L this queried the user's default
2447
+ // tmux server instead of the fleet's, so under a custom AGEND_HOME the
2448
+ // check was meaningless (it reported every pane dead).
2449
+ const socket = getTmuxSocketName();
2450
+ const args = socket ? ["-L", socket, "list-panes", "-t", windowId] : ["list-panes", "-t", windowId];
2451
+ await promisify(execFile)("tmux", args, { timeout: 5_000 });
2101
2452
  }
2102
2453
  catch {
2103
2454
  // Pane dead — respawn
@@ -2118,6 +2469,12 @@ export class FleetManager {
2118
2469
  if (this.adapterRestarting.has(id))
2119
2470
  return;
2120
2471
  this.adapterRestarting.add(id);
2472
+ // Reflect reality in adapterState throughout. This loop used to leave the state
2473
+ // untouched, so getAdapterStates() — and therefore /health and the dashboard —
2474
+ // kept reporting "connected" for an adapter that had been down for hours. An
2475
+ // adapter's true status was simply not knowable from inside the process.
2476
+ const previous = this.adapterState.get(id);
2477
+ this.adapterState.set(id, { status: "retrying", retryCount: 0, lastError: previous?.lastError });
2121
2478
  try {
2122
2479
  for (let attempt = 1;; attempt++) {
2123
2480
  if (this.ipcStoppingInstances.has("__fleet_stopping__"))
@@ -2130,9 +2487,16 @@ export class FleetManager {
2130
2487
  await adapter.stop().catch(() => { });
2131
2488
  await adapter.start();
2132
2489
  this.logger.info({ id, attempt }, "Adapter restarted successfully");
2490
+ this.adapterState.set(id, { status: "connected", retryCount: 0 });
2133
2491
  return;
2134
2492
  }
2135
- catch { /* retry */ }
2493
+ catch (err) {
2494
+ this.adapterState.set(id, {
2495
+ status: "retrying",
2496
+ retryCount: attempt,
2497
+ lastError: err?.message ?? String(err),
2498
+ });
2499
+ }
2136
2500
  if (attempt % 10 === 0) {
2137
2501
  this.logger.warn({ id, attempt }, "Adapter restart still failing");
2138
2502
  }
@@ -2168,6 +2532,49 @@ export class FleetManager {
2168
2532
  }
2169
2533
  return generals[0];
2170
2534
  }
2535
+ /**
2536
+ * A user reacted to one of the bot's messages (#408).
2537
+ *
2538
+ * A reaction is context, not a message (#432, reworking #413): it never triggers
2539
+ * an agent turn and never wakes anything. It is queued in the event log and rides
2540
+ * into the instance's NEXT real message as one compact leading line —
2541
+ * `[Recent reactions: 👍×2 from hanhanv]` — after which it is marked consumed.
2542
+ * No pending reactions → no line → zero context spent, which is the common case.
2543
+ */
2544
+ async handleInboundReaction(r) {
2545
+ const instanceName = this.resolveSlashTarget(r.threadId ?? r.chatId, r.adapterId);
2546
+ if (!instanceName) {
2547
+ this.logger.debug({ emoji: r.emoji, chatId: r.chatId }, "Reaction in an unrouted channel — ignoring");
2548
+ return;
2549
+ }
2550
+ if (DELIVERY_STATUS_EMOJIS.has(r.emoji)) {
2551
+ this.logger.debug({ emoji: r.emoji, user: r.username }, "Ignoring delivery-status emoji as a reaction");
2552
+ return;
2553
+ }
2554
+ this.eventLog?.logActivity("reaction", r.username, `${r.emoji} ${r.action}`, instanceName);
2555
+ if (r.action === "add") {
2556
+ this.eventLog?.addReaction(instanceName, r.messageId, r.username, r.emoji);
2557
+ }
2558
+ else {
2559
+ // Withdrawn before anyone saw it → it never happened. See removeReaction.
2560
+ this.eventLog?.removeReaction(instanceName, r.messageId, r.username, r.emoji);
2561
+ }
2562
+ }
2563
+ /**
2564
+ * The queued-reaction summary for an instance's next real message, or {} when
2565
+ * nothing is pending (the common case must add zero context). The consume
2566
+ * callback is separate from the fetch so reactions are only marked once the
2567
+ * message actually went out — a failed delivery keeps them queued.
2568
+ */
2569
+ pendingReactionsMeta(instanceName) {
2570
+ const pending = this.eventLog?.pendingReactions(instanceName);
2571
+ if (!pending)
2572
+ return { meta: {}, consume: () => { } };
2573
+ return {
2574
+ meta: { pending_reactions: pending.summary },
2575
+ consume: () => this.eventLog?.markReactionsConsumed(instanceName, pending.maxId),
2576
+ };
2577
+ }
2171
2578
  async handleInboundMessage(msg) {
2172
2579
  const threadId = msg.threadId || undefined;
2173
2580
  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 +2912,7 @@ export class FleetManager {
2505
2912
  }
2506
2913
  this.warnIfRateLimited(generalInstance, msg);
2507
2914
  const { text, extraMeta } = await processAttachments(msg, inboundAdapter, this.logger, generalInstance);
2915
+ const generalReactions = this.pendingReactionsMeta(generalInstance);
2508
2916
  try {
2509
2917
  await this.deliverToInstance(generalInstance, {
2510
2918
  type: "fleet_inbound",
@@ -2520,9 +2928,11 @@ export class FleetManager {
2520
2928
  adapter_id: msg.adapterId,
2521
2929
  source: msg.source,
2522
2930
  ...(msg.replyToText ? { reply_to_text: msg.replyToText } : {}),
2931
+ ...generalReactions.meta,
2523
2932
  ...extraMeta,
2524
2933
  },
2525
2934
  });
2935
+ generalReactions.consume();
2526
2936
  this.lastInboundUser.set(generalInstance, msg.username);
2527
2937
  this.logger.info(`${msg.username} → ${generalInstance}: ${(text ?? "").slice(0, 100)}`);
2528
2938
  this.eventLog?.logActivity("message", msg.username, (text ?? "").slice(0, 200), generalInstance);
@@ -2598,6 +3008,7 @@ export class FleetManager {
2598
3008
  this.setTopicIcon(instanceName, "blue");
2599
3009
  this.warnIfRateLimited(instanceName, msg);
2600
3010
  const { text, extraMeta } = await processAttachments(msg, inboundAdapter, this.logger, instanceName);
3011
+ const reactions = this.pendingReactionsMeta(instanceName);
2601
3012
  try {
2602
3013
  await this.deliverToInstance(instanceName, {
2603
3014
  type: "fleet_inbound",
@@ -2613,9 +3024,13 @@ export class FleetManager {
2613
3024
  adapter_id: msg.adapterId,
2614
3025
  source: msg.source,
2615
3026
  ...(msg.replyToText ? { reply_to_text: msg.replyToText } : {}),
3027
+ ...reactions.meta,
2616
3028
  ...extraMeta,
2617
3029
  },
2618
3030
  });
3031
+ // Only after the message actually went out. A failed delivery keeps the
3032
+ // reactions queued for the retry / the next message.
3033
+ reactions.consume();
2619
3034
  }
2620
3035
  catch (err) {
2621
3036
  this.logger.warn({ err: err.message, instanceName }, "Wake/delivery failed");
@@ -2704,25 +3119,33 @@ export class FleetManager {
2704
3119
  delete args.thread_id;
2705
3120
  threadId = undefined;
2706
3121
  }
3122
+ // Reply dedup: retries land here when the agent was told a send failed
3123
+ // (daemon budget elapsed, shell tool killed) while the adapter send was
3124
+ // still in flight and about to succeed. One real send, everyone gets its
3125
+ // outcome; a genuinely failed send clears the entry so a retry passes.
3126
+ if (tool === "reply") {
3127
+ const ticket = this.replyDeduper.begin(instanceName, String(args.text ?? ""), Array.isArray(args.files) ? args.files : []);
3128
+ if (ticket.duplicate) {
3129
+ this.logger.info({ instanceName }, "Duplicate reply suppressed — replaying the original send's outcome");
3130
+ ticket.subscribe(respond);
3131
+ return;
3132
+ }
3133
+ const original = respond;
3134
+ const respondAndRecord = (result, error) => {
3135
+ ticket.complete(result, error);
3136
+ original(result, error);
3137
+ };
3138
+ if (routeToolCall(outAdapter, tool, args, threadId, respondAndRecord)) {
3139
+ this.afterReplyRouted(instanceName, args, senderSessionName);
3140
+ return;
3141
+ }
3142
+ // routeToolCall knows "reply"; not handling it means the world changed.
3143
+ ticket.complete(null, "reply not handled");
3144
+ original(null, "reply not handled");
3145
+ return;
3146
+ }
2707
3147
  // Route standard channel tools (reply, react, edit_message, download_attachment)
2708
3148
  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
3149
  return;
2727
3150
  }
2728
3151
  // Log tool calls for activity visualization
@@ -2737,6 +3160,35 @@ export class FleetManager {
2737
3160
  respond(null, `Unknown tool: ${tool}`);
2738
3161
  }
2739
3162
  }
3163
+ /** Side effects of a routed reply: cancel-button lifecycle, logs, SSE, chat log. */
3164
+ afterReplyRouted(instanceName, args, senderSessionName) {
3165
+ // A reply is NOT proof the turn is over (#410) — but it is not proof of
3166
+ // more work either. Split the difference: an instance that is clearly
3167
+ // idle loses the button now; one that looks busy keeps it (re-posted
3168
+ // below the reply so it stays last in the channel), with a 2-minute
3169
+ // grace check — if it has NOT resumed working by then, the reply was the
3170
+ // end of the turn and the button goes. A multi-step run that keeps
3171
+ // working sails through the check and keeps its button.
3172
+ if (this.getInstanceIdle(instanceName)) {
3173
+ this.clearCancelButton(instanceName);
3174
+ }
3175
+ else {
3176
+ void this.sendCancelButton(instanceName).then(() => this.armReplyGrace(instanceName));
3177
+ }
3178
+ this.reactDone(instanceName);
3179
+ const replyTo = this.lastInboundUser.get(instanceName) ?? "user";
3180
+ this.logger.info(`${instanceName} → ${replyTo}: ${(args.text ?? "").slice(0, 100)}`);
3181
+ this.emitSseEvent("message", {
3182
+ instance: instanceName, sender: senderSessionName ?? instanceName,
3183
+ text: (args.text ?? "").slice(0, 2000),
3184
+ ts: new Date().toISOString(),
3185
+ });
3186
+ // Log bot reply to classic instance chat-log
3187
+ const isClassic = this.classicChannels?.getChannelIdByInstance(instanceName) !== undefined;
3188
+ if (isClassic) {
3189
+ ClassicChannelManager.logMessage(instanceName, "bot", args.text ?? "", new Date());
3190
+ }
3191
+ }
2740
3192
  /** Handle tool status update from a daemon instance */
2741
3193
  handleToolStatusFromInstance(instanceName, msg) {
2742
3194
  const statusAdapter = this.getAdapterForInstance(instanceName) ?? this.adapter;
@@ -3339,6 +3791,9 @@ export class FleetManager {
3339
3791
  }
3340
3792
  }
3341
3793
  async removeInstance(name) {
3794
+ // Drop cached pane context — the map is keyed by instance name and nothing
3795
+ // else evicted deleted entries, so it grew for the life of the process.
3796
+ forgetInstanceContext(name);
3342
3797
  // Clean up schedules (scheduler is fleet-level, not lifecycle-level)
3343
3798
  const config = this.fleetConfig?.instances[name];
3344
3799
  if (this.scheduler && config?.topic_id) {
@@ -3444,6 +3899,171 @@ export class FleetManager {
3444
3899
  this.collabInstances.add(instanceName);
3445
3900
  return true;
3446
3901
  }
3902
+ /**
3903
+ * Open the event log, tolerating a corrupt file.
3904
+ *
3905
+ * `events.db` holds history only — event rows and the activity feed. Nothing the
3906
+ * fleet needs to run depends on it, and every consumer already uses
3907
+ * `this.eventLog?.`. An unguarded `new EventLog(...)` here meant a corrupt or
3908
+ * unreadable history file (a truncated WAL after a hard kill, a full disk)
3909
+ * threw during startAll and the WHOLE FLEET FAILED TO BOOT — trading every
3910
+ * running agent for a file whose only job is reporting.
3911
+ *
3912
+ * So: try, move a bad file aside and retry once with a fresh one, and if even
3913
+ * that fails carry on without an event log.
3914
+ */
3915
+ /**
3916
+ * Run `agend backend doctor` for the fleet's default backend and return its
3917
+ * cleaned output.
3918
+ *
3919
+ * Async on purpose: this was `execSync` with a 30s timeout, reachable by any
3920
+ * allowlisted user through `/doctor`. While it ran, the entire fleet event loop
3921
+ * was frozen — no IPC, no adapter, no message delivery, no health responses,
3922
+ * and critically no WATCHDOG ping, so a slow doctor could push past
3923
+ * WatchdogSec and have systemd SIGABRT the fleet.
3924
+ */
3925
+ async runBackendDoctor() {
3926
+ const stripAnsi = (s) => s.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, "");
3927
+ const backend = this.fleetConfig?.defaults?.backend || "claude-code";
3928
+ try {
3929
+ const { execFile } = await import("node:child_process");
3930
+ const { promisify } = await import("node:util");
3931
+ // execFile with an argv array — no shell, so the backend name cannot be
3932
+ // interpreted as a command even if config is malformed.
3933
+ const { stdout } = await promisify(execFile)("agend", ["backend", "doctor", backend], {
3934
+ timeout: 30_000,
3935
+ encoding: "utf-8",
3936
+ });
3937
+ return stripAnsi(stdout) || "No output";
3938
+ }
3939
+ catch (err) {
3940
+ const e = err;
3941
+ return stripAnsi(e.stdout ?? e.message ?? "Doctor failed");
3942
+ }
3943
+ }
3944
+ /** Drop event/activity rows older than the retention window. Best-effort. */
3945
+ /**
3946
+ * Cap every instance's pipe-pane log, walking the instances **directory** rather
3947
+ * than the config.
3948
+ *
3949
+ * A running instance rotates its own log on each health tick, so the ones that
3950
+ * need this are the ones nothing else looks at:
3951
+ *
3952
+ * - deleted instances, whose directory outlives the config entry. Nothing ever
3953
+ * touched these again. On the machine this was found on, one held 122 MB and
3954
+ * another 74 MB, out of 622 MB of pipe-pane logs in total.
3955
+ * - classic instances, which live in classicChannels, not fleetConfig.instances,
3956
+ * and so were never in the old config-driven loop at all.
3957
+ * - stopped instances, which have no health tick running.
3958
+ *
3959
+ * pipe-pane writes raw TUI output, so a wedged splash screen can emit ANSI frames
3960
+ * at animation rate. Unbounded growth here fills the disk, which takes the whole
3961
+ * fleet down rather than one instance.
3962
+ */
3963
+ rotateAllInstanceLogs() {
3964
+ const root = join(this.dataDir, "instances");
3965
+ let entries;
3966
+ try {
3967
+ entries = readdirSync(root, { withFileTypes: true });
3968
+ }
3969
+ catch {
3970
+ return; // no instances directory yet
3971
+ }
3972
+ for (const entry of entries) {
3973
+ if (!entry.isDirectory())
3974
+ continue;
3975
+ // rotateLogIfNeeded is already best-effort and returns early on a missing
3976
+ // file, so a directory without a pipe-pane log costs one stat.
3977
+ rotateLogIfNeeded(join(root, entry.name, "output.log"));
3978
+ }
3979
+ }
3980
+ pruneEventLog() {
3981
+ try {
3982
+ this.eventLog?.prune(FleetManager.EVENT_LOG_RETENTION_DAYS);
3983
+ }
3984
+ catch (err) {
3985
+ this.logger.warn({ err }, "Event log prune failed");
3986
+ }
3987
+ }
3988
+ openEventLog() {
3989
+ const dbPath = join(this.dataDir, "events.db");
3990
+ try {
3991
+ return new EventLog(dbPath);
3992
+ }
3993
+ catch (err) {
3994
+ this.logger.error({ err, dbPath }, "events.db unusable — moving it aside and starting a fresh one");
3995
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
3996
+ for (const suffix of ["", "-wal", "-shm"]) {
3997
+ try {
3998
+ renameSync(`${dbPath}${suffix}`, `${dbPath}${suffix}.corrupt-${stamp}`);
3999
+ }
4000
+ catch { /* may not exist */ }
4001
+ }
4002
+ try {
4003
+ return new EventLog(dbPath);
4004
+ }
4005
+ catch (retryErr) {
4006
+ // History is worth losing; a fleet that won't start is not.
4007
+ this.logger.error({ err: retryErr, dbPath }, "Could not open a fresh events.db — continuing without event logging");
4008
+ return null;
4009
+ }
4010
+ }
4011
+ }
4012
+ /**
4013
+ * Report a fleet-level fault (not attributable to one instance) to the General
4014
+ * topic, so the operator learns about it without reading daemon.log.
4015
+ *
4016
+ * Throttled per distinct message: an unhandled rejection typically comes from a
4017
+ * loop (a poller, a repeating timer), and one channel message per occurrence
4018
+ * would bury the topic — which is worse than silence. First occurrence goes out
4019
+ * immediately, repeats are suppressed for THROTTLE_MS and then re-sent with a
4020
+ * count.
4021
+ *
4022
+ * The log line is written by the caller regardless: if every adapter is down,
4023
+ * the only notification path is the one that is broken.
4024
+ */
4025
+ notifyFleetError(text) {
4026
+ const now = Date.now();
4027
+ const key = text.slice(0, 200);
4028
+ const seen = this.fleetErrorNotices.get(key);
4029
+ if (seen && now - seen.at < FleetManager.FLEET_ERROR_THROTTLE_MS) {
4030
+ seen.suppressed++;
4031
+ return;
4032
+ }
4033
+ const suppressed = seen?.suppressed ?? 0;
4034
+ this.fleetErrorNotices.set(key, { at: now, suppressed: 0 });
4035
+ // Bound the map: it is keyed by message text, and a message with a varying
4036
+ // suffix (a path, an id) would otherwise grow it without limit.
4037
+ if (this.fleetErrorNotices.size > 100) {
4038
+ const oldest = this.fleetErrorNotices.keys().next().value;
4039
+ if (oldest !== undefined)
4040
+ this.fleetErrorNotices.delete(oldest);
4041
+ }
4042
+ const body = suppressed > 0
4043
+ ? `${text}\n(plus ${suppressed} more in the last ${Math.round(FleetManager.FLEET_ERROR_THROTTLE_MS / 60_000)}m)`
4044
+ : text;
4045
+ // Resolved from config, NOT findGeneralInstance(): that requires a live daemon,
4046
+ // and a fleet-level fault is exactly when the General may be down. The topic
4047
+ // itself still exists, and notifyInstanceTopic only needs adapter + group +
4048
+ // topic_id to post into it.
4049
+ const general = Object.entries(this.fleetConfig?.instances ?? {})
4050
+ .find(([, config]) => config.general_topic === true)?.[0];
4051
+ if (general) {
4052
+ this.notifyInstanceTopic(general, body);
4053
+ return;
4054
+ }
4055
+ // No General instance — fall back to the primary channel's group.
4056
+ const channelCfg = this.getChannelConfig();
4057
+ const groupId = channelCfg?.group_id;
4058
+ if (this.adapter && groupId) {
4059
+ this.adapter.sendText(String(groupId), body)
4060
+ .catch(err => this.logger.warn({ err }, "Failed to send fleet error notification"));
4061
+ return;
4062
+ }
4063
+ this.logger.warn({ text: body }, "Fleet error had no notification target (no General instance, no adapter)");
4064
+ }
4065
+ static FLEET_ERROR_THROTTLE_MS = 10 * 60_000;
4066
+ fleetErrorNotices = new Map();
3447
4067
  notifyInstanceTopic(instanceName, text, extraOpts) {
3448
4068
  const adapter = this.getAdapterForInstance(instanceName) ?? this.adapter;
3449
4069
  if (!adapter)
@@ -3517,6 +4137,40 @@ export class FleetManager {
3517
4137
  await data.respond(t("save.sent", cmd, target.name));
3518
4138
  }
3519
4139
  /** Whether the instance currently has at least one live cancel button. */
4140
+ /**
4141
+ * A click on a cancel button, whether or not the fleet still tracks it.
4142
+ *
4143
+ * The old rule was "act only while an entry is live", which made a click on a
4144
+ * button the fleet had forgotten a silent no-op — no cancel, no message, not
4145
+ * even a log line. That is indistinguishable from a broken button, and it is
4146
+ * what the "按鈕點了沒反應" reports were: the entry is briefly absent while a
4147
+ * button is being replaced, and a delete that fails leaves the message on
4148
+ * screen with no entry at all.
4149
+ *
4150
+ * So: honour the click if the instance is actually running, and say so plainly
4151
+ * if it is not. The stale-click path is rate-limited because the original
4152
+ * concern was real — a second click must not fire a second interrupt key at an
4153
+ * instance that has already started a new turn.
4154
+ */
4155
+ handleCancelClick(instanceName, adapter, data) {
4156
+ if (this.hasCancelButton(instanceName)) {
4157
+ this.cancelInstance(instanceName);
4158
+ return;
4159
+ }
4160
+ const lastAt = this.staleCancelClickAt.get(instanceName) ?? 0;
4161
+ if (Date.now() - lastAt < STALE_CANCEL_CLICK_COOLDOWN_MS)
4162
+ return;
4163
+ this.staleCancelClickAt.set(instanceName, Date.now());
4164
+ // cancelInstance returns false when there is no daemon — i.e. nothing to
4165
+ // cancel, which is the one case where the button really is dead.
4166
+ if (this.cancelInstance(instanceName)) {
4167
+ this.logger.info({ instanceName }, "Cancel click honoured with no live button entry");
4168
+ return;
4169
+ }
4170
+ this.logger.info({ instanceName }, "Cancel click on an expired button — instance not running");
4171
+ adapter?.editMessage(data.chatId, data.messageId, t("cancel.button_stale", instanceName), data.threadId)
4172
+ .catch(() => { });
4173
+ }
3520
4174
  hasCancelButton(instanceName) {
3521
4175
  for (const e of this.cancelButtons.values()) {
3522
4176
  if (e.instanceName === instanceName)
@@ -3525,15 +4179,22 @@ export class FleetManager {
3525
4179
  return false;
3526
4180
  }
3527
4181
  async sendCancelButton(instanceName, correlationId) {
3528
- // At most one button shown per instance: retire any existing ones first
3529
- // (delete + bounded retry). Each is tracked separately, so a failed delete
3530
- // here doesn't strand it it keeps retrying on its own timer.
3531
- this.retireInstanceButtons(instanceName);
4182
+ // Post first, retire after (see the tail of this method). Retiring up front
4183
+ // meant that from the delete until the new message came back a chat API
4184
+ // round trip, and every reply goes through here the instance had NO live
4185
+ // entry, while the old button was still on screen. A click in that window
4186
+ // hit `hasCancelButton() === false` and was silently dropped: the reported
4187
+ // "按鈕失效". If notifyAlert then failed, the button was simply gone.
3532
4188
  const adapter = this.getAdapterForInstance(instanceName) ?? this.adapter;
3533
4189
  if (!adapter)
3534
4190
  return;
4191
+ // Resolve the group through the world fallback (first world when unbound),
4192
+ // NOT through getChannelConfig(binding)?.group_id: on a fleet configured with
4193
+ // `channels:` worlds the primary `channel:` block is empty, so an instance
4194
+ // with no world binding yet (fresh restart, cross-instance delegation)
4195
+ // resolved group_id to undefined and the button silently never appeared.
3535
4196
  const adapterId = this.instanceWorldBinding.get(instanceName);
3536
- const groupId = this.getChannelConfig(adapterId)?.group_id;
4197
+ const groupId = this.getGroupIdForInstance(instanceName) || undefined;
3537
4198
  const topicId = this.fleetConfig?.instances[instanceName]?.topic_id;
3538
4199
  let chatId;
3539
4200
  let threadId;
@@ -3549,8 +4210,12 @@ export class FleetManager {
3549
4210
  if (!chatId && groupId)
3550
4211
  chatId = String(groupId);
3551
4212
  }
3552
- if (!chatId)
4213
+ if (!chatId) {
4214
+ // A button that cannot be addressed must say so — this exact silence is how
4215
+ // "the cancel button sometimes never appears" stayed unreported-in-logs.
4216
+ this.logger.warn({ instanceName, topicId, groupId }, "Cannot address cancel button (no chat id resolved)");
3553
4217
  return;
4218
+ }
3554
4219
  try {
3555
4220
  const sent = await adapter.notifyAlert(chatId, {
3556
4221
  type: "cancel",
@@ -3558,13 +4223,6 @@ export class FleetManager {
3558
4223
  message: "👀 處理中…",
3559
4224
  choices: [{ id: `cancel:${instanceName}`, label: t("cancel.button") }],
3560
4225
  }, 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
4226
  const entry = {
3569
4227
  instanceName,
3570
4228
  adapterId,
@@ -3573,7 +4231,16 @@ export class FleetManager {
3573
4231
  threadId: sent.threadId ?? threadId,
3574
4232
  correlationId,
3575
4233
  retryCount: 0,
4234
+ // Elapsed time is measured from when this button was posted — i.e. from
4235
+ // when the work was handed over — not from the pane's working transition,
4236
+ // which resets if the CLI blips idle mid-turn.
4237
+ startedAt: Date.now(),
4238
+ // Matches the text notifyAlert just posted, so the first 60s tick does
4239
+ // not re-edit identical text — which put a "(edited)" mark on Discord
4240
+ // with nothing visibly changed.
4241
+ lastProgressText: "👀 處理中…",
3576
4242
  };
4243
+ this.startProgressTicker(entry);
3577
4244
  // Idle-check backstop: every 5min, if the instance is idle, retire the
3578
4245
  // button. Covers turns that end without hitting a clear trigger (reply /
3579
4246
  // cancel / correlation). Cleared in discardButton when the entry is removed.
@@ -3582,18 +4249,167 @@ export class FleetManager {
3582
4249
  clearInterval(entry.idleCheckTimer);
3583
4250
  return;
3584
4251
  }
3585
- if (this.getInstanceIdle(instanceName)) {
3586
- this.logger.info({ instanceName, messageId: entry.messageId }, "Cancel button idle backstop retiring");
4252
+ const reason = this.getInstanceIdle(instanceName) ? "idle"
4253
+ : this.stateReportDead(instanceName) ? "state reports stopped"
4254
+ : Date.now() - (entry.startedAt ?? 0) > CANCEL_BTN_MAX_LIFETIME_MS ? "24h ceiling"
4255
+ : null;
4256
+ if (reason) {
4257
+ this.logger.info({ instanceName, messageId: entry.messageId, reason }, "Cancel button backstop retiring");
3587
4258
  this.retireButton(entry);
4259
+ return;
3588
4260
  }
4261
+ // Still looks busy. The daemon only broadcasts on transitions, so ask for
4262
+ // a fresh snapshot — a live daemon's answer refreshes receivedAt and keeps
4263
+ // the staleness check honest; a dead one's silence is the evidence.
4264
+ this.instanceIpcClients.get(instanceName)?.send({
4265
+ type: "query_instance_state", requestId: `cancel-btn-${Date.now()}`,
4266
+ });
3589
4267
  }, CANCEL_BTN_IDLE_CHECK_INTERVAL_MS);
3590
4268
  this.cancelButtons.set(sent.messageId, entry);
4269
+ // Only now: at most one button per instance, but never zero. Covers both
4270
+ // the previous turn's button and any button a concurrent
4271
+ // sendCancelButton posted while we were awaiting notifyAlert.
4272
+ for (const other of [...this.cancelButtons.values()]) {
4273
+ if (other.instanceName === instanceName && other.messageId !== sent.messageId) {
4274
+ this.retireButton(other);
4275
+ }
4276
+ }
4277
+ this.persistCancelButtons();
3591
4278
  this.logger.info({ instanceName, messageId: sent.messageId }, "Cancel button sent");
3592
4279
  }
3593
4280
  catch (e) {
3594
4281
  this.logger.warn({ err: e.message, instanceName }, "Failed to send cancel button");
3595
4282
  }
3596
4283
  }
4284
+ /**
4285
+ * The cancel button's text for a given elapsed time.
4286
+ *
4287
+ * Below the threshold it keeps the original wording, so a normal quick answer
4288
+ * looks exactly as it did before. Past it, the button doubles as the live
4289
+ * progress indicator (#409) — the channel showed nothing at all during long work,
4290
+ * and once the agent had replied once there was no sign it was still going.
4291
+ */
4292
+ static progressText(elapsedMs, activity, minElapsedMs = PROGRESS_MIN_ELAPSED_MS) {
4293
+ if (elapsedMs < minElapsedMs)
4294
+ return "👀 處理中…";
4295
+ const totalSeconds = Math.floor(elapsedMs / 1000);
4296
+ const minutes = Math.floor(totalSeconds / 60);
4297
+ const seconds = totalSeconds % 60;
4298
+ const elapsed = minutes >= 60
4299
+ ? `${Math.floor(minutes / 60)}h ${minutes % 60}m`
4300
+ : `${minutes}m ${String(seconds).padStart(2, "0")}s`;
4301
+ const detail = FleetManager.sanitizeActivity(activity);
4302
+ return detail
4303
+ ? `⏳ 處理中… (已進行 ${elapsed} · ${detail})`
4304
+ : `⏳ 處理中… (已進行 ${elapsed})`;
4305
+ }
4306
+ /**
4307
+ * Make a tool summary safe to paste into a channel message.
4308
+ *
4309
+ * The text is agent-controlled (it is built from tool inputs — file paths,
4310
+ * shell commands), so it gets flattened to one line, capped, and stripped of
4311
+ * the two Discord mass-mention triggers. Neither channel renders it with a
4312
+ * parse mode, so no markup escaping is needed beyond that.
4313
+ */
4314
+ static sanitizeActivity(activity) {
4315
+ if (!activity)
4316
+ return null;
4317
+ const flat = activity.replace(/\s+/g, " ").replace(/@(everyone|here)/g, "@​$1").trim();
4318
+ if (!flat)
4319
+ return null;
4320
+ return flat.length > PROGRESS_ACTIVITY_MAX_CHARS
4321
+ ? `${flat.slice(0, PROGRESS_ACTIVITY_MAX_CHARS - 1)}…`
4322
+ : flat;
4323
+ }
4324
+ /**
4325
+ * Remember what an instance is currently doing, for the progress line.
4326
+ *
4327
+ * Best-effort by design: only backends that expose a live activity feed report
4328
+ * anything, and the progress line simply omits the detail for the rest. It is
4329
+ * never used to decide anything — purely what the user is shown.
4330
+ */
4331
+ cacheInstanceActivity(name, activity) {
4332
+ if (activity)
4333
+ this.instanceActivity.set(name, activity);
4334
+ else
4335
+ this.instanceActivity.delete(name);
4336
+ }
4337
+ /**
4338
+ * Refresh the button's text in place while the instance keeps working.
4339
+ *
4340
+ * Uses `editAlert`, NOT `editMessage`: on Telegram the latter omits reply_markup,
4341
+ * and the Bot API treats that as "clear the keyboard" — so editing with it would
4342
+ * delete the very cancel button this is trying to keep alive.
4343
+ */
4344
+ /** Configured threshold before elapsed time appears, in ms. */
4345
+ progressMinElapsedMs() {
4346
+ const seconds = this.fleetConfig?.defaults
4347
+ ?.progress_min_elapsed;
4348
+ if (typeof seconds === "number" && Number.isFinite(seconds) && seconds >= 0) {
4349
+ return seconds * 1000;
4350
+ }
4351
+ return PROGRESS_MIN_ELAPSED_MS;
4352
+ }
4353
+ startProgressTicker(entry) {
4354
+ const tick = () => {
4355
+ if (!this.cancelButtons.has(entry.messageId)) {
4356
+ clearInterval(entry.progressTimer);
4357
+ return;
4358
+ }
4359
+ const text = FleetManager.progressText(Date.now() - (entry.startedAt ?? Date.now()), this.instanceActivity.get(entry.instanceName), this.progressMinElapsedMs());
4360
+ if (text === entry.lastProgressText)
4361
+ return; // nothing changed — skip the API call
4362
+ const adapter = this.getAdapterForInstance(entry.instanceName) ?? this.adapter;
4363
+ if (!adapter?.editAlert)
4364
+ return;
4365
+ entry.lastProgressText = text;
4366
+ adapter.editAlert(entry.chatId, entry.messageId, {
4367
+ type: "cancel",
4368
+ instanceName: entry.instanceName,
4369
+ message: text,
4370
+ choices: [{ id: `cancel:${entry.instanceName}`, label: t("cancel.button") }],
4371
+ }, entry.threadId ? { threadId: entry.threadId } : undefined)
4372
+ .catch(err => {
4373
+ // A failed progress edit must never escalate: the button still works and
4374
+ // the next tick retries. Common causes are a deleted message or a
4375
+ // rate limit.
4376
+ this.logger.debug({ err, instanceName: entry.instanceName }, "Progress edit failed");
4377
+ });
4378
+ };
4379
+ entry.progressTimer = setInterval(tick, PROGRESS_UPDATE_INTERVAL_MS);
4380
+ entry.progressTimer.unref?.();
4381
+ // One extra tick right when the threshold passes, so a 30s threshold shows
4382
+ // time at ~30s instead of waiting for the first 60s interval. Costs at most
4383
+ // one additional edit per turn that lives past the threshold.
4384
+ const firstAt = this.progressMinElapsedMs() - (Date.now() - (entry.startedAt ?? Date.now()));
4385
+ if (firstAt > 0 && firstAt < PROGRESS_UPDATE_INTERVAL_MS) {
4386
+ const firstTick = setTimeout(tick, firstAt);
4387
+ firstTick.unref?.();
4388
+ }
4389
+ }
4390
+ /**
4391
+ * After a reply: give the instance REPLY_RETIRE_GRACE_MS to resume working; if
4392
+ * it has not, retire its button. Re-arming replaces the previous timer, so a
4393
+ * burst of replies ends with exactly one pending check.
4394
+ */
4395
+ armReplyGrace(instanceName) {
4396
+ for (const entry of this.cancelButtons.values()) {
4397
+ if (entry.instanceName !== instanceName)
4398
+ continue;
4399
+ if (entry.replyGraceTimer)
4400
+ clearTimeout(entry.replyGraceTimer);
4401
+ entry.replyGraceTimer = setTimeout(() => {
4402
+ entry.replyGraceTimer = undefined;
4403
+ if (!this.cancelButtons.has(entry.messageId))
4404
+ return;
4405
+ if (!this.getInstanceIdle(instanceName))
4406
+ return; // resumed — a long run keeps its button
4407
+ this.logger.info({ instanceName, messageId: entry.messageId }, "Cancel button retired — no work resumed after reply");
4408
+ this.retireButton(entry);
4409
+ }, REPLY_RETIRE_GRACE_MS);
4410
+ entry.replyGraceTimer.unref?.();
4411
+ }
4412
+ }
3597
4413
  /** Retire (delete) every cancel button belonging to an instance. */
3598
4414
  retireInstanceButtons(instanceName) {
3599
4415
  // Snapshot first — retireButton may delete entries from the map on success.
@@ -3625,7 +4441,70 @@ export class FleetManager {
3625
4441
  clearTimeout(entry.retryTimer);
3626
4442
  if (entry.idleCheckTimer)
3627
4443
  clearInterval(entry.idleCheckTimer);
4444
+ if (entry.progressTimer)
4445
+ clearInterval(entry.progressTimer);
4446
+ if (entry.replyGraceTimer)
4447
+ clearTimeout(entry.replyGraceTimer);
3628
4448
  this.cancelButtons.delete(entry.messageId);
4449
+ this.persistCancelButtons();
4450
+ }
4451
+ /**
4452
+ * Mirror the live buttons to disk. The map is memory-only, so before this a
4453
+ * fleet restart orphaned every button on screen: frozen "處理中…" text and a
4454
+ * click that did nothing, forever. The ledger is tiny (a handful of rows) and
4455
+ * written on every add/remove — no debounce needed at that rate.
4456
+ */
4457
+ persistCancelButtons() {
4458
+ try {
4459
+ const rows = [...this.cancelButtons.values()].map(e => ({
4460
+ instanceName: e.instanceName,
4461
+ adapterId: e.adapterId,
4462
+ chatId: e.chatId,
4463
+ messageId: e.messageId,
4464
+ threadId: e.threadId,
4465
+ }));
4466
+ writeFileSync(join(this.dataDir, CANCEL_BTN_LEDGER_FILE), JSON.stringify(rows));
4467
+ }
4468
+ catch (err) {
4469
+ this.logger.debug({ err }, "Cancel button ledger write failed");
4470
+ }
4471
+ }
4472
+ /**
4473
+ * Delete the previous process's buttons. Runs once adapters are up: nothing
4474
+ * from a previous fleet process can still be mid-turn from this process's
4475
+ * point of view, so every ledger row is an orphan by definition.
4476
+ */
4477
+ async sweepOrphanedCancelButtons() {
4478
+ const ledgerPath = join(this.dataDir, CANCEL_BTN_LEDGER_FILE);
4479
+ let rows;
4480
+ try {
4481
+ if (!existsSync(ledgerPath))
4482
+ return;
4483
+ rows = JSON.parse(readFileSync(ledgerPath, "utf-8"));
4484
+ }
4485
+ catch {
4486
+ try {
4487
+ unlinkSync(ledgerPath);
4488
+ }
4489
+ catch { /* corrupt ledger — drop it */ }
4490
+ return;
4491
+ }
4492
+ for (const row of rows) {
4493
+ const adapter = (row.adapterId ? this.worlds.get(row.adapterId)?.adapter : undefined)
4494
+ ?? this.getAdapterForInstance?.(row.instanceName) ?? this.adapter;
4495
+ if (!adapter?.deleteMessage)
4496
+ continue;
4497
+ try {
4498
+ await adapter.deleteMessage(row.chatId, row.messageId, row.threadId);
4499
+ this.logger.info({ instanceName: row.instanceName, messageId: row.messageId }, "Swept orphaned cancel button from previous run");
4500
+ }
4501
+ catch (err) {
4502
+ // Best effort: the message may already be gone, or too old to delete.
4503
+ this.logger.debug({ err, messageId: row.messageId }, "Orphaned cancel button sweep failed");
4504
+ }
4505
+ }
4506
+ // The current process owns the ledger from here on.
4507
+ this.persistCancelButtons();
3629
4508
  }
3630
4509
  /** Re-attempt a failed button delete up to CANCEL_BTN_MAX_RETRIES times. */
3631
4510
  scheduleButtonRetry(entry, err) {
@@ -4290,6 +5169,12 @@ When users create specialized instances, suggest these configurations:
4290
5169
  meta.image_path = saves[saves.length - 1][1].split(",")[0].trim();
4291
5170
  }
4292
5171
  }
5172
+ // Classic channels queue reactions like everyone else (#432 stored them, but
5173
+ // this path never attached them — reactions in a ClassicBot channel went into
5174
+ // the DB and were never seen again). Same contract as the topic paths:
5175
+ // consumed only after the delivery succeeded.
5176
+ const reactions = this.pendingReactionsMeta(instanceName);
5177
+ Object.assign(meta, reactions.meta);
4293
5178
  try {
4294
5179
  await this.deliverToInstance(instanceName, {
4295
5180
  type: "fleet_inbound",
@@ -4297,6 +5182,7 @@ When users create specialized instances, suggest these configurations:
4297
5182
  targetSession: instanceName,
4298
5183
  meta,
4299
5184
  });
5185
+ reactions.consume();
4300
5186
  }
4301
5187
  catch (err) {
4302
5188
  this.logger.warn({ err: err.message, instanceName }, "Classic wake/delivery failed");
@@ -4435,6 +5321,170 @@ When users create specialized instances, suggest these configurations:
4435
5321
  return env?.models ?? [];
4436
5322
  }
4437
5323
  /** `/model` slash handler (admin only). No arg → DC menu; `/model <name>` → apply directly. */
5324
+ /** Label an effort choice, marking the one currently configured. */
5325
+ effortChoiceLabel(level, current) {
5326
+ return level === current ? `✓ ${level}` : level;
5327
+ }
5328
+ effortMenuHeader(instanceName) {
5329
+ const { effort, source } = this.resolveInstanceEffort(instanceName);
5330
+ if (!effort)
5331
+ return "Current effort: (CLI default)";
5332
+ return source === "fleet-default"
5333
+ ? `Current effort: ${effort} (fleet default)`
5334
+ : `Current effort: ${effort}`;
5335
+ }
5336
+ /** `/effort` — DC Select Menu, or apply directly when a level is given. */
5337
+ async handleEffortSlash(data, adapterId) {
5338
+ if (!this.isModelAdmin(data.userId, data.channelId, adapterId)) {
5339
+ await data.respond(t("permission.denied"));
5340
+ return;
5341
+ }
5342
+ const name = this.resolveSlashTarget(data.channelId, adapterId);
5343
+ if (!name) {
5344
+ await data.respond(t("classic.no_agent"));
5345
+ return;
5346
+ }
5347
+ const requested = (typeof data.options?.level === "string" ? data.options.level.trim() : "")
5348
+ || (data.text?.trim() ?? "");
5349
+ if (requested) {
5350
+ await data.respond(await this.applyEffort(name, requested));
5351
+ return;
5352
+ }
5353
+ const levels = this.effortLevelsFor(name);
5354
+ if (levels.length === 0) {
5355
+ await data.respond(`❌ ${this.backendNameForInstance(name)} has no reasoning-effort setting.`);
5356
+ return;
5357
+ }
5358
+ if (!data.respondChoices) {
5359
+ await data.respond(`Usage: /effort <${levels.join("|")}>`);
5360
+ return;
5361
+ }
5362
+ const current = this.resolveInstanceEffort(name).effort;
5363
+ const nonce = randomBytes(6).toString("hex");
5364
+ const choices = levels.map(l => ({
5365
+ id: `${EFFORT_SELECT_CALLBACK_PREFIX}${nonce}:${l}`,
5366
+ label: this.effortChoiceLabel(l, current),
5367
+ }));
5368
+ const timer = setTimeout(() => this.pendingEffortSelects.delete(nonce), CLASSIC_BACKEND_SELECTION_TIMEOUT_MS);
5369
+ timer.unref?.();
5370
+ this.pendingEffortSelects.set(nonce, { instanceName: name, userId: data.userId, channelId: data.channelId, timer, respond: data.respond });
5371
+ try {
5372
+ await data.respondChoices(`${this.effortMenuHeader(name)}\nSelect a new effort level:`, choices);
5373
+ }
5374
+ catch (err) {
5375
+ this.pendingEffortSelects.delete(nonce);
5376
+ clearTimeout(timer);
5377
+ this.logger.warn({ err, instanceName: name }, "effort menu failed");
5378
+ await data.respond(`Usage: /effort <${levels.join("|")}>`);
5379
+ }
5380
+ }
5381
+ /** TG inline-keyboard effort menu. Returns null on success, else a fallback string. */
5382
+ async promptEffortMenu(instanceName, userId, channelId, adapter, chatId, threadId) {
5383
+ const levels = this.effortLevelsFor(instanceName);
5384
+ if (levels.length === 0) {
5385
+ return `❌ ${this.backendNameForInstance(instanceName)} has no reasoning-effort setting.`;
5386
+ }
5387
+ const current = this.resolveInstanceEffort(instanceName).effort;
5388
+ const nonce = randomBytes(6).toString("hex");
5389
+ const choices = levels.map(l => ({
5390
+ id: `${EFFORT_SELECT_CALLBACK_PREFIX}${nonce}:${l}`,
5391
+ label: this.effortChoiceLabel(l, current),
5392
+ }));
5393
+ const respond = async (text) => {
5394
+ await adapter.sendText(chatId, text, { threadId });
5395
+ return undefined;
5396
+ };
5397
+ const timer = setTimeout(() => {
5398
+ const p = this.pendingEffortSelects.get(nonce);
5399
+ if (p) {
5400
+ this.pendingEffortSelects.delete(nonce);
5401
+ p.respond("⏰ Effort selection expired.").catch(() => { });
5402
+ }
5403
+ }, CLASSIC_BACKEND_SELECTION_TIMEOUT_MS);
5404
+ timer.unref?.();
5405
+ this.pendingEffortSelects.set(nonce, { instanceName, userId, channelId, timer, respond, adapter, adapterChatId: chatId, adapterThreadId: threadId });
5406
+ try {
5407
+ const menuMessageId = await adapter.promptUser(chatId, `${this.effortMenuHeader(instanceName)}\nSelect a new effort level:`, choices, { threadId });
5408
+ const pending = this.pendingEffortSelects.get(nonce);
5409
+ if (pending)
5410
+ pending.menuMessageId = menuMessageId;
5411
+ return null;
5412
+ }
5413
+ catch (err) {
5414
+ this.pendingEffortSelects.delete(nonce);
5415
+ clearTimeout(timer);
5416
+ this.logger.warn({ err, instanceName }, "TG effort menu failed");
5417
+ return `Usage: /effort <${levels.join("|")}>`;
5418
+ }
5419
+ }
5420
+ /** Consume an `/effort` selection callback. Mirrors handleModelSelection. */
5421
+ async handleEffortSelection(data) {
5422
+ if (!data.callbackData.startsWith(EFFORT_SELECT_CALLBACK_PREFIX))
5423
+ return false;
5424
+ const match = data.callbackData.match(/^effort-select:([0-9a-f]+):(.+)$/);
5425
+ if (!match)
5426
+ return true;
5427
+ const pending = this.pendingEffortSelects.get(match[1]);
5428
+ if (!pending)
5429
+ return true;
5430
+ if (data.userId && data.userId !== pending.userId)
5431
+ return true;
5432
+ const cbChannel = data.threadId ?? data.chatId;
5433
+ if (cbChannel !== pending.channelId && data.chatId !== pending.channelId)
5434
+ return true;
5435
+ this.pendingEffortSelects.delete(match[1]);
5436
+ clearTimeout(pending.timer);
5437
+ const level = match[2];
5438
+ const progressText = `⏳ Setting ${pending.instanceName} effort to \`${level}\`…`;
5439
+ let progressMsgId;
5440
+ if (pending.adapter && pending.adapterChatId) {
5441
+ const menuMessageId = pending.menuMessageId ?? data.messageId;
5442
+ if (menuMessageId && pending.adapter.editMessageRemoveButtons) {
5443
+ try {
5444
+ await pending.adapter.editMessageRemoveButtons(pending.adapterChatId, menuMessageId, progressText, pending.adapterThreadId);
5445
+ progressMsgId = menuMessageId;
5446
+ }
5447
+ catch { /* fall back to a new message */ }
5448
+ }
5449
+ if (!progressMsgId) {
5450
+ try {
5451
+ const sent = await pending.adapter.sendText(pending.adapterChatId, progressText, { threadId: pending.adapterThreadId });
5452
+ progressMsgId = sent.messageId;
5453
+ }
5454
+ catch { /* non-fatal */ }
5455
+ }
5456
+ }
5457
+ else {
5458
+ await pending.respond(progressText).catch(() => { });
5459
+ }
5460
+ // Background-applied and guarded for the same reason as the model path: a
5461
+ // restart backend respawns the instance here, and an unguarded rejection
5462
+ // from a menu click must not take the fleet down.
5463
+ void (async () => {
5464
+ let result;
5465
+ try {
5466
+ result = await this.applyEffort(pending.instanceName, level);
5467
+ }
5468
+ catch (err) {
5469
+ this.logger.error({ err, instance: pending.instanceName, level }, "Effort switch failed");
5470
+ result = `Effort switch to \`${level}\` failed: ${err instanceof Error ? err.message : String(err)}`;
5471
+ }
5472
+ if (pending.adapter && pending.adapterChatId) {
5473
+ if (progressMsgId) {
5474
+ pending.adapter.editMessage(pending.adapterChatId, progressMsgId, result, pending.adapterThreadId).catch(() => {
5475
+ pending.adapter.sendText(pending.adapterChatId, result, { threadId: pending.adapterThreadId }).catch(() => { });
5476
+ });
5477
+ }
5478
+ else {
5479
+ pending.adapter.sendText(pending.adapterChatId, result, { threadId: pending.adapterThreadId }).catch(() => { });
5480
+ }
5481
+ }
5482
+ else {
5483
+ await pending.respond(result).catch(() => { });
5484
+ }
5485
+ })();
5486
+ return true;
5487
+ }
4438
5488
  async handleModelSlash(data, adapterId) {
4439
5489
  if (!this.isModelAdmin(data.userId, data.channelId, adapterId)) {
4440
5490
  await data.respond(t("permission.denied"));
@@ -4571,9 +5621,19 @@ When users create specialized instances, suggest these configurations:
4571
5621
  // DC path: respond immediately with progress text
4572
5622
  await pending.respond(progressText).catch(() => { });
4573
5623
  }
4574
- // Apply model in background — don't await here (keeps callback handler fast)
5624
+ // Apply model in background — don't await here (keeps callback handler fast).
5625
+ // Guarded: applyModel() restarts the instance, and an unguarded rejection here
5626
+ // meant a user picking from the /model menu could take the whole fleet down.
5627
+ // On failure the user gets told, rather than the click silently doing nothing.
4575
5628
  void (async () => {
4576
- const result = await this.applyModel(pending.instanceName, model);
5629
+ let result;
5630
+ try {
5631
+ result = await this.applyModel(pending.instanceName, model);
5632
+ }
5633
+ catch (err) {
5634
+ this.logger.error({ err, instance: pending.instanceName, model }, "Model switch failed");
5635
+ result = `Model switch to \`${model}\` failed: ${err instanceof Error ? err.message : String(err)}`;
5636
+ }
4577
5637
  if (pending.adapter && pending.adapterChatId) {
4578
5638
  if (progressMsgId) {
4579
5639
  pending.adapter.editMessage(pending.adapterChatId, progressMsgId, result, pending.adapterThreadId).catch(() => {
@@ -4591,6 +5651,110 @@ When users create specialized instances, suggest these configurations:
4591
5651
  return true;
4592
5652
  }
4593
5653
  /** Apply a model to an instance: runtime paste (claude-code) or persist + restart (others). */
5654
+ /** AgEnD's canonical effort ladder, low → max. Backends expose a subset. */
5655
+ static EFFORT_LEVELS = ["low", "medium", "high", "xhigh", "max"];
5656
+ /** How this instance's backend applies an effort change. */
5657
+ effortStrategyFor(instanceName) {
5658
+ try {
5659
+ const backend = createBackend(this.backendNameForInstance(instanceName), this.getInstanceDir(instanceName));
5660
+ const strategy = backend.getEffortStrategy?.() ?? "unsupported";
5661
+ // A backend claiming support but listing no levels is unusable either way.
5662
+ return strategy !== "unsupported" && (backend.getEffortLevels?.() ?? []).length > 0
5663
+ ? strategy
5664
+ : "unsupported";
5665
+ }
5666
+ catch {
5667
+ return "unsupported";
5668
+ }
5669
+ }
5670
+ /** Effort levels this instance's backend actually accepts (empty = unsupported). */
5671
+ effortLevelsFor(instanceName) {
5672
+ try {
5673
+ const backend = createBackend(this.backendNameForInstance(instanceName), this.getInstanceDir(instanceName));
5674
+ if ((backend.getEffortStrategy?.() ?? "unsupported") === "unsupported")
5675
+ return [];
5676
+ return backend.getEffortLevels?.() ?? [];
5677
+ }
5678
+ catch {
5679
+ return [];
5680
+ }
5681
+ }
5682
+ /** Configured effort for an instance: per-instance, else fleet default, else none. */
5683
+ resolveInstanceEffort(instanceName) {
5684
+ const own = this.fleetConfig?.instances[instanceName]?.effort;
5685
+ if (own)
5686
+ return { effort: own, source: "instance" };
5687
+ const fallback = this.fleetConfig?.defaults?.effort;
5688
+ if (fallback)
5689
+ return { effort: fallback, source: "fleet-default" };
5690
+ return { effort: null, source: "unset" };
5691
+ }
5692
+ /**
5693
+ * Clamp a canonical level to the nearest one this backend supports.
5694
+ *
5695
+ * Clamping DOWN the ladder, never up: asking for `max` on a CLI that stops at
5696
+ * `high` should get high, not silently fall to low. The caller reports the
5697
+ * clamp — a user who asks for max and quietly receives high has been told the
5698
+ * request succeeded when it did not.
5699
+ */
5700
+ static clampEffort(level, supported) {
5701
+ if (supported.includes(level))
5702
+ return level;
5703
+ const ladder = FleetManager.EFFORT_LEVELS;
5704
+ const wanted = ladder.indexOf(level);
5705
+ if (wanted < 0)
5706
+ return null;
5707
+ for (let i = wanted - 1; i >= 0; i--) {
5708
+ if (supported.includes(ladder[i]))
5709
+ return ladder[i];
5710
+ }
5711
+ return supported[0] ?? null;
5712
+ }
5713
+ /**
5714
+ * Apply a reasoning-effort level, mirroring applyModel's shape.
5715
+ *
5716
+ * runtime backends take `/effort <level>` in the pane and keep working;
5717
+ * restart backends only read it at launch, so it is persisted and the
5718
+ * instance respawns.
5719
+ */
5720
+ async applyEffort(instanceName, requested) {
5721
+ const level = requested.trim().toLowerCase();
5722
+ const backendName = this.backendNameForInstance(instanceName);
5723
+ let strategy = "unsupported";
5724
+ let supported = [];
5725
+ try {
5726
+ const backend = createBackend(backendName, this.getInstanceDir(instanceName));
5727
+ strategy = backend.getEffortStrategy?.() ?? "unsupported";
5728
+ supported = backend.getEffortLevels?.() ?? [];
5729
+ }
5730
+ catch { /* treated as unsupported below */ }
5731
+ if (strategy === "unsupported" || supported.length === 0) {
5732
+ return `❌ ${backendName} has no reasoning-effort setting.`;
5733
+ }
5734
+ if (!FleetManager.EFFORT_LEVELS.includes(level)) {
5735
+ return `❌ Unknown effort level \`${level}\`. Use: ${FleetManager.EFFORT_LEVELS.join(", ")}.`;
5736
+ }
5737
+ const applied = FleetManager.clampEffort(level, supported);
5738
+ if (!applied)
5739
+ return `❌ ${backendName} accepts none of the canonical effort levels.`;
5740
+ const warn = applied === level
5741
+ ? ""
5742
+ : `⚠️ Clamped to \`${applied}\` (\`${level}\` not supported by ${backendName}).\n`;
5743
+ // Persist either way: a runtime switch must survive the next respawn too,
5744
+ // or the instance silently reverts on restart.
5745
+ if (this.fleetConfig?.instances[instanceName]) {
5746
+ this.fleetConfig.instances[instanceName].effort = applied;
5747
+ this.saveFleetConfig();
5748
+ }
5749
+ if (strategy === "runtime") {
5750
+ if (!this.instanceIpcClients.get(instanceName))
5751
+ return `${warn}❌ ${instanceName} is not running.`;
5752
+ this.pasteRawToClassicInstance(instanceName, `/effort ${applied}`);
5753
+ return `${warn}✅ Set ${instanceName} effort to \`${applied}\` (runtime).`;
5754
+ }
5755
+ await this.restartSingleInstance(instanceName);
5756
+ return `${warn}✅ Set ${instanceName} effort to \`${applied}\` and restarted.`;
5757
+ }
4594
5758
  async applyModel(instanceName, model) {
4595
5759
  const backendName = this.backendNameForInstance(instanceName);
4596
5760
  let strategy = "restart";
@@ -4603,7 +5767,7 @@ When users create specialized instances, suggest these configurations:
4603
5767
  if (!this.instanceIpcClients.get(instanceName))
4604
5768
  return `${warn}❌ ${instanceName} is not running.`;
4605
5769
  this.pasteRawToClassicInstance(instanceName, `/model ${model}`);
4606
- return `${warn}✅ Switched ${instanceName} to \`${model}\` (runtime).`;
5770
+ return `${warn}✅ Switched ${instanceName} to \`${model}\` (runtime).${this.effortSuffix(instanceName)}`;
4607
5771
  }
4608
5772
  // restart: persist the model so the respawned CLI launches with it.
4609
5773
  let persisted = false;
@@ -4618,7 +5782,24 @@ When users create specialized instances, suggest these configurations:
4618
5782
  if (!persisted)
4619
5783
  return `${warn}❌ Could not set model for ${instanceName}.`;
4620
5784
  await this.restartSingleInstance(instanceName);
4621
- return `${warn}✅ Set ${instanceName} to \`${model}\` and restarted.`;
5785
+ return `${warn}✅ Set ${instanceName} to \`${model}\` and restarted.${this.effortSuffix(instanceName)}`;
5786
+ }
5787
+ /**
5788
+ * The trailing "Current effort: …" line for a /model reply.
5789
+ *
5790
+ * Model and effort interact (a cheaper model at max effort is a different
5791
+ * trade than a bigger one at low), so showing the effort in force right after
5792
+ * a switch saves the round trip of asking. Empty when the backend has none.
5793
+ */
5794
+ effortSuffix(instanceName) {
5795
+ if (this.effortLevelsFor(instanceName).length === 0)
5796
+ return "";
5797
+ const { effort, source } = this.resolveInstanceEffort(instanceName);
5798
+ if (!effort)
5799
+ return "\nCurrent effort: (CLI default)";
5800
+ return source === "fleet-default"
5801
+ ? `\nCurrent effort: ${effort} (fleet default)`
5802
+ : `\nCurrent effort: ${effort}`;
4622
5803
  }
4623
5804
  /** Read recent chat log for agent context */
4624
5805
  getRecentChatLog(instanceName, maxLines = 10) {
@@ -4811,7 +5992,7 @@ When users create specialized instances, suggest these configurations:
4811
5992
  ...(preTaskCommand ? { pre_task_command: preTaskCommand } : {}),
4812
5993
  };
4813
5994
  const topicMode = this.fleetConfig?.channel?.mode === "topic";
4814
- await this.startInstance(instanceName, config, topicMode);
5995
+ await this.startInstance(instanceName, config, topicMode, "classic");
4815
5996
  }
4816
5997
  /** Handle /start slash command — register classic channel */
4817
5998
  async handleClassicStart(channelId, channelName, userId, guildId, adapterId, backend) {
@@ -4853,11 +6034,28 @@ When users create specialized instances, suggest these configurations:
4853
6034
  this.logger.info({ channelId, adapterId, instanceName: ch.instanceName }, "Classic channel stopped");
4854
6035
  return t("classic.stopped");
4855
6036
  }
4856
- async stopAll() {
6037
+ /**
6038
+ * Idempotent while in flight: SIGINT and SIGTERM share one handler and the
6039
+ * uncaughtException path calls this too, so overlapping runs were possible —
6040
+ * each snapshotting the daemon map and calling stop() on the same daemons
6041
+ * concurrently. Deliberately NOT `async`, so callers receive the same promise
6042
+ * object rather than a fresh wrapper around it. The latch clears when the run
6043
+ * settles, so a later genuine stop (after a restart) still does the work.
6044
+ */
6045
+ stopAll() {
6046
+ this.stopAllInFlight ??= this.doStopAll().finally(() => { this.stopAllInFlight = null; });
6047
+ return this.stopAllInFlight;
6048
+ }
6049
+ stopAllInFlight = null;
6050
+ async doStopAll() {
4857
6051
  this.startupComplete = false;
4858
6052
  this.reloadPending = false;
6053
+ // Before anything is stopped: everything that dies from here on dies
6054
+ // because we asked it to. Set synchronously — doStopAll runs to its first
6055
+ // await in the same tick as the signal handler, so no event can slip in.
6056
+ this.shuttingDown = true;
4859
6057
  this.ipcStoppingInstances.add("__fleet_stopping__");
4860
- sdNotify("STOPPING=1");
6058
+ sdNotifyBlocking("STOPPING=1");
4861
6059
  if (this.watchdogTimer) {
4862
6060
  clearInterval(this.watchdogTimer);
4863
6061
  this.watchdogTimer = null;
@@ -4877,6 +6075,26 @@ When users create specialized instances, suggest these configurations:
4877
6075
  clearInterval(this.updateCheckTimer);
4878
6076
  this.updateCheckTimer = null;
4879
6077
  }
6078
+ if (this.eventLogPruneTimer) {
6079
+ clearInterval(this.eventLogPruneTimer);
6080
+ this.eventLogPruneTimer = null;
6081
+ }
6082
+ if (this.logRotateTimer) {
6083
+ clearInterval(this.logRotateTimer);
6084
+ this.logRotateTimer = null;
6085
+ }
6086
+ // Cancel-button timers were never cleared here. The idle-check interval is not
6087
+ // unref'd, so it held the event loop open past shutdown and kept retrying
6088
+ // deletes against an adapter that was already gone.
6089
+ for (const entry of [...this.cancelButtons.values()]) {
6090
+ if (entry.retryTimer)
6091
+ clearTimeout(entry.retryTimer);
6092
+ if (entry.idleCheckTimer)
6093
+ clearInterval(entry.idleCheckTimer);
6094
+ if (entry.progressTimer)
6095
+ clearInterval(entry.progressTimer);
6096
+ }
6097
+ this.cancelButtons.clear();
4880
6098
  if (this.topicCleanupTimer) {
4881
6099
  clearInterval(this.topicCleanupTimer);
4882
6100
  this.topicCleanupTimer = null;
@@ -5095,6 +6313,15 @@ When users create specialized instances, suggest these configurations:
5095
6313
  removedRatio,
5096
6314
  validationErrors: validation.errors,
5097
6315
  }, "Refusing unsafe fleet config reload; running configuration was kept");
6316
+ // Tell the operator. A silently ignored config edit is the most confusing
6317
+ // possible outcome: they change fleet.yaml, send SIGHUP, and nothing happens
6318
+ // with no explanation anywhere they are looking.
6319
+ const why = !validation.valid
6320
+ ? `validation failed:\n${validation.errors.map(e => `• ${e.path}: ${e.message}`).join("\n")}`
6321
+ : unsafeEmpty
6322
+ ? `it removed every instance (${oldCount} → 0)`
6323
+ : `it removed more than half the instances (${oldCount} → ${newCount})`;
6324
+ this.notifyFleetError(`⚠️ fleet.yaml reload REJECTED — ${why}\nThe previous configuration is still running.`);
5098
6325
  return;
5099
6326
  }
5100
6327
  this.routing.rebuild(this.fleetConfig);
@@ -5294,10 +6521,20 @@ When users create specialized instances, suggest these configurations:
5294
6521
  // ── Update check ────────────────────────────────────────────────────
5295
6522
  async checkForUpdates() {
5296
6523
  try {
5297
- const { execSync } = await import("node:child_process");
6524
+ // Both npm lookups are async: as execSync they froze the fleet event loop for
6525
+ // up to 15s each, and on a beta build BOTH ran — 30s with no WATCHDOG ping,
6526
+ // past WatchdogSec's half-interval and enough for systemd to SIGABRT the fleet
6527
+ // for a background version check.
6528
+ const { execFile } = await import("node:child_process");
6529
+ const { promisify } = await import("node:util");
6530
+ const execFileP = promisify(execFile);
6531
+ const npmVersion = async (spec) => {
6532
+ const { stdout } = await execFileP("npm", ["view", spec, "version"], { timeout: 15_000 });
6533
+ return stdout.toString().trim();
6534
+ };
5298
6535
  const pkgPath = join(dirname(fileURLToPath(import.meta.url)), "..", "package.json");
5299
6536
  const currentVersion = JSON.parse(readFileSync(pkgPath, "utf-8")).version ?? "0.0.0";
5300
- const latest = execSync("npm view @songsid/agend version", { stdio: "pipe", timeout: 15_000 }).toString().trim();
6537
+ const latest = await npmVersion("@songsid/agend");
5301
6538
  let target = latest;
5302
6539
  if (currentVersion.includes("-beta")) {
5303
6540
  // Beta users track the @beta channel (never fall back to @latest, which is
@@ -5305,7 +6542,7 @@ When users create specialized instances, suggest these configurations:
5305
6542
  // of beta/latest is the newest.
5306
6543
  let beta = "";
5307
6544
  try {
5308
- beta = execSync("npm view @songsid/agend@beta version", { stdio: "pipe", timeout: 15_000 }).toString().trim();
6545
+ beta = await npmVersion("@songsid/agend@beta");
5309
6546
  }
5310
6547
  catch { /* no beta tag */ }
5311
6548
  target = beta || latest;
@@ -5412,6 +6649,10 @@ When users create specialized instances, suggest these configurations:
5412
6649
  // /view routes accept the read-only view.token (or web.token) and do
5413
6650
  // their own per-method auth in view-api.ts — skip the web-token gate.
5414
6651
  }
6652
+ else if (isUsagePath(new URL(req.url ?? "/", `http://localhost:${port}`).pathname)) {
6653
+ // /api/ai-usage is read-only GET data for the /view Usage panel — open
6654
+ // like the other /view data routes (usage-api.ts rejects non-GET).
6655
+ }
5415
6656
  else {
5416
6657
  // All other endpoints require a valid token (query ?token= or X-Agend-Token header).
5417
6658
  // /ui/* will also re-check in web-api.ts, which is harmless.
@@ -5426,34 +6667,34 @@ When users create specialized instances, suggest these configurations:
5426
6667
  }
5427
6668
  }
5428
6669
  if (req.method === "GET" && req.url === "/health") {
5429
- const instanceCount = this.fleetConfig?.instances
5430
- ? Object.keys(this.fleetConfig.instances).length
5431
- : 0;
5432
- res.writeHead(200);
5433
- res.end(JSON.stringify({
5434
- status: "ok",
5435
- instances: instanceCount,
5436
- uptime: Math.floor((Date.now() - this.startedAt) / 1000),
5437
- }));
6670
+ const health = this.getFleetHealth();
6671
+ // 503 when the fleet cannot do its job, so an external monitor sees it.
6672
+ // This used to always answer 200 "ok" with a count of CONFIGURED instances,
6673
+ // so every agent could be dead and every adapter down and it still looked
6674
+ // green.
6675
+ res.writeHead(health.status === "ok" ? 200 : 503);
6676
+ res.end(JSON.stringify(health));
5438
6677
  return;
5439
6678
  }
5440
6679
  if (req.method === "GET" && req.url === "/status") {
5441
6680
  const instances = Object.keys(this.fleetConfig?.instances ?? {}).map(name => {
5442
6681
  const statusFile = join(this.getInstanceDir(name), "statusline.json");
5443
- let context_pct = 0;
5444
6682
  let cost = 0;
5445
6683
  try {
5446
6684
  const data = JSON.parse(readFileSync(statusFile, "utf-8"));
5447
- context_pct = data.context_window?.used_percentage ?? 0;
5448
6685
  cost = data.cost?.total_cost_usd ?? 0;
5449
6686
  }
5450
6687
  catch (err) {
5451
6688
  this.logger.debug({ err, name }, "statusline.json read failed (/status)");
5452
6689
  }
6690
+ const backend = this.fleetConfig?.instances[name]?.backend
6691
+ ?? this.fleetConfig?.defaults?.backend
6692
+ ?? "claude-code";
6693
+ const { context } = resolveInstanceContext(this.dataDir, name, backend);
5453
6694
  return {
5454
6695
  name,
5455
6696
  status: this.getInstanceStatus(name),
5456
- context_pct,
6697
+ context_pct: context ?? 0,
5457
6698
  cost,
5458
6699
  };
5459
6700
  });
@@ -5568,7 +6809,10 @@ When users create specialized instances, suggest these configurations:
5568
6809
  res.writeHead(500);
5569
6810
  res.end(JSON.stringify({ error: `Start failed: ${err.message}` }));
5570
6811
  }
5571
- })();
6812
+ // The inner catch can itself throw (writeHead after a successful
6813
+ // writeHead is ERR_HTTP_HEADERS_SENT), and that rejection escapes the
6814
+ // IIFE. Same for the two handlers below.
6815
+ })().catch(err => this.logger.error({ err, name }, "HTTP start handler failed"));
5572
6816
  return;
5573
6817
  }
5574
6818
  // Instance restart (immediate, no idle wait)
@@ -5589,7 +6833,7 @@ When users create specialized instances, suggest these configurations:
5589
6833
  res.writeHead(status);
5590
6834
  res.end(JSON.stringify({ error: `Restart failed: ${err.message}` }));
5591
6835
  }
5592
- })();
6836
+ })().catch(err => this.logger.error({ err, name }, "HTTP restart handler failed"));
5593
6837
  return;
5594
6838
  }
5595
6839
  if (req.method === "POST" && req.url?.startsWith("/stop/")) {
@@ -5612,7 +6856,7 @@ When users create specialized instances, suggest these configurations:
5612
6856
  res.writeHead(500);
5613
6857
  res.end(JSON.stringify({ error: `Stop failed: ${err.message}` }));
5614
6858
  }
5615
- })();
6859
+ })().catch(err => this.logger.error({ err, name }, "HTTP stop handler failed"));
5616
6860
  return;
5617
6861
  }
5618
6862
  // ── Agent CLI endpoint ─────
@@ -5624,6 +6868,8 @@ When users create specialized instances, suggest these configurations:
5624
6868
  const url = new URL(req.url ?? "/", `http://localhost:${port}`);
5625
6869
  if (handleViewRequest(req, res, url, this))
5626
6870
  return;
6871
+ if (handleUsageRequest(req, res, url, this))
6872
+ return;
5627
6873
  if (handleSettingsRequest(req, res, url, this))
5628
6874
  return;
5629
6875
  if (handleWebRequest(req, res, url, this))
@@ -5670,20 +6916,35 @@ When users create specialized instances, suggest these configurations:
5670
6916
  this.logger.info({ url: `http://localhost:${port}/view?token=${this.viewToken}` }, "Web View available");
5671
6917
  }
5672
6918
  getUiStatus() {
5673
- const instances = Object.keys(this.fleetConfig?.instances ?? {}).map(name => {
6919
+ const fleetNames = Object.keys(this.fleetConfig?.instances ?? {});
6920
+ // Classic rooms live only in classicBot.yaml — /api/profiles merges them into
6921
+ // the View roster, but previously getUiStatus skipped them so context_pct was
6922
+ // always 0 (live map miss → l?.context_pct ?? 0).
6923
+ const classicOnly = (this.classicChannels?.getAll() ?? [])
6924
+ .map(ch => ch.instanceName)
6925
+ .filter(name => !fleetNames.includes(name));
6926
+ const names = [...fleetNames, ...classicOnly];
6927
+ const instances = names.map(name => {
5674
6928
  const statusFile = join(this.getInstanceDir(name), "statusline.json");
5675
- let context_pct = 0;
5676
6929
  let cost = 0;
5677
6930
  let model = "";
5678
6931
  try {
5679
6932
  const data = JSON.parse(readFileSync(statusFile, "utf-8"));
5680
- context_pct = data.context_window?.used_percentage ?? 0;
5681
6933
  cost = data.cost?.total_cost_usd ?? 0;
5682
6934
  model = data.model?.display_name ?? "";
5683
6935
  }
5684
6936
  catch (err) {
5685
6937
  this.logger.debug({ err, name }, "statusline.json read failed (getUiStatus)");
5686
6938
  }
6939
+ // Align with /ctx: statusline for claude-code, pane scrape for kiro/grok/codex.
6940
+ const classic = classicOnly.includes(name);
6941
+ const backend = classic
6942
+ ? this.classicChannels.getBackendByInstance(name, this.fleetConfig?.defaults?.backend)
6943
+ : (this.fleetConfig?.instances[name]?.backend
6944
+ ?? this.fleetConfig?.defaults?.backend
6945
+ ?? "claude-code");
6946
+ const { context } = resolveInstanceContext(this.dataDir, name, backend);
6947
+ const context_pct = context ?? 0;
5687
6948
  return { name, status: this.getInstanceStatus(name), context_pct, cost, model };
5688
6949
  });
5689
6950
  return {