@songsid/agend 2.3.5-beta.1 → 2.3.5-beta.3

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 (199) hide show
  1. package/dist/agent-cli-instructions.md +3 -3
  2. package/dist/agent-cli.js +5 -2
  3. package/dist/agent-cli.js.map +1 -1
  4. package/dist/agent-whats-new.js +4 -0
  5. package/dist/agent-whats-new.js.map +1 -1
  6. package/dist/auth-api.d.ts +3 -1
  7. package/dist/auth-api.js +6 -2
  8. package/dist/auth-api.js.map +1 -1
  9. package/dist/backend/claude-code.d.ts +3 -0
  10. package/dist/backend/claude-code.js +72 -13
  11. package/dist/backend/claude-code.js.map +1 -1
  12. package/dist/backend/cli-env-probe.js +6 -2
  13. package/dist/backend/cli-env-probe.js.map +1 -1
  14. package/dist/backend/codex.d.ts +5 -3
  15. package/dist/backend/codex.js +31 -13
  16. package/dist/backend/codex.js.map +1 -1
  17. package/dist/backend/kiro.js +1 -1
  18. package/dist/backend/kiro.js.map +1 -1
  19. package/dist/backend/types.d.ts +9 -1
  20. package/dist/backend/types.js.map +1 -1
  21. package/dist/bundled-tmux-guard.d.ts +4 -0
  22. package/dist/bundled-tmux-guard.js +7 -0
  23. package/dist/bundled-tmux-guard.js.map +1 -1
  24. package/dist/cache-service.d.ts +6 -0
  25. package/dist/cache-service.js +105 -0
  26. package/dist/cache-service.js.map +1 -1
  27. package/dist/channel/access-manager.d.ts +1 -6
  28. package/dist/channel/access-manager.js +4 -94
  29. package/dist/channel/access-manager.js.map +1 -1
  30. package/dist/channel/adapters/discord.d.ts +0 -2
  31. package/dist/channel/adapters/discord.js +0 -8
  32. package/dist/channel/adapters/discord.js.map +1 -1
  33. package/dist/channel/adapters/telegram.d.ts +0 -3
  34. package/dist/channel/adapters/telegram.js +1 -30
  35. package/dist/channel/adapters/telegram.js.map +1 -1
  36. package/dist/channel/mcp-tools.js +4 -4
  37. package/dist/channel/mcp-tools.js.map +1 -1
  38. package/dist/channel/types.d.ts +0 -2
  39. package/dist/claude-model-minimum.d.ts +7 -0
  40. package/dist/claude-model-minimum.js +16 -0
  41. package/dist/claude-model-minimum.js.map +1 -0
  42. package/dist/cli.js +1 -19
  43. package/dist/cli.js.map +1 -1
  44. package/dist/config-validator.js +2 -1
  45. package/dist/config-validator.js.map +1 -1
  46. package/dist/daemon.d.ts +46 -1
  47. package/dist/daemon.js +193 -29
  48. package/dist/daemon.js.map +1 -1
  49. package/dist/decision-list.d.ts +2 -0
  50. package/dist/decision-list.js +1 -1
  51. package/dist/decision-list.js.map +1 -1
  52. package/dist/fleet-manager.d.ts +95 -0
  53. package/dist/fleet-manager.js +491 -113
  54. package/dist/fleet-manager.js.map +1 -1
  55. package/dist/fleet-process-handlers.d.ts +1 -1
  56. package/dist/fleet-process-handlers.js +3 -2
  57. package/dist/fleet-process-handlers.js.map +1 -1
  58. package/dist/general-knowledge/skills/concepts/SKILL.md +28 -18
  59. package/dist/general-knowledge/skills/cross-instance-messaging/SKILL.md +9 -1
  60. package/dist/general-knowledge/skills/delegation-playbook/SKILL.md +4 -1
  61. package/dist/general-knowledge/skills/fleet-config/SKILL.md +12 -0
  62. package/dist/general-knowledge/skills/fleet-health/SKILL.md +1 -1
  63. package/dist/general-knowledge/skills/instance-lifecycle/SKILL.md +4 -0
  64. package/dist/general-knowledge/skills/web-dashboard/SKILL.md +16 -11
  65. package/dist/general-knowledge/steering/core-rules.md +6 -4
  66. package/dist/instance-lifecycle.d.ts +4 -1
  67. package/dist/instance-lifecycle.js +20 -1
  68. package/dist/instance-lifecycle.js.map +1 -1
  69. package/dist/instructions.js +29 -6
  70. package/dist/instructions.js.map +1 -1
  71. package/dist/kiro-history-scan.d.ts +26 -0
  72. package/dist/kiro-history-scan.js +141 -0
  73. package/dist/kiro-history-scan.js.map +1 -0
  74. package/dist/kiro-history-worker.d.ts +1 -0
  75. package/dist/kiro-history-worker.js +9 -0
  76. package/dist/kiro-history-worker.js.map +1 -0
  77. package/dist/kiro-history.d.ts +20 -0
  78. package/dist/kiro-history.js +96 -0
  79. package/dist/kiro-history.js.map +1 -0
  80. package/dist/kiro-usage-run.d.ts +2 -0
  81. package/dist/kiro-usage-run.js +4 -1
  82. package/dist/kiro-usage-run.js.map +1 -1
  83. package/dist/locale.js +107 -97
  84. package/dist/locale.js.map +1 -1
  85. package/dist/login-flows.d.ts +4 -0
  86. package/dist/login-flows.js +8 -4
  87. package/dist/login-flows.js.map +1 -1
  88. package/dist/office-levels.d.ts +4 -3
  89. package/dist/office-levels.js +3 -3
  90. package/dist/office-levels.js.map +1 -1
  91. package/dist/outbound-handlers.js +33 -13
  92. package/dist/outbound-handlers.js.map +1 -1
  93. package/dist/outbound-schemas.d.ts +16 -0
  94. package/dist/outbound-schemas.js +8 -2
  95. package/dist/outbound-schemas.js.map +1 -1
  96. package/dist/quickstart-api.js +2 -2
  97. package/dist/quickstart-api.js.map +1 -1
  98. package/dist/reply-buttons-controller.d.ts +5 -1
  99. package/dist/reply-buttons-controller.js +8 -4
  100. package/dist/reply-buttons-controller.js.map +1 -1
  101. package/dist/reply-buttons.d.ts +6 -2
  102. package/dist/reply-buttons.js +7 -3
  103. package/dist/reply-buttons.js.map +1 -1
  104. package/dist/scheduler/db.d.ts +10 -0
  105. package/dist/scheduler/db.js +38 -11
  106. package/dist/scheduler/db.js.map +1 -1
  107. package/dist/scheduler/types.d.ts +6 -1
  108. package/dist/setup-i18n.js +4 -4
  109. package/dist/setup-i18n.js.map +1 -1
  110. package/dist/structured-signin.js +3 -1
  111. package/dist/structured-signin.js.map +1 -1
  112. package/dist/subagent-records.d.ts +42 -0
  113. package/dist/subagent-records.js +159 -0
  114. package/dist/subagent-records.js.map +1 -0
  115. package/dist/subagent-service.d.ts +27 -0
  116. package/dist/subagent-service.js +199 -0
  117. package/dist/subagent-service.js.map +1 -0
  118. package/dist/team-membership.d.ts +7 -0
  119. package/dist/team-membership.js +10 -0
  120. package/dist/team-membership.js.map +1 -0
  121. package/dist/tips.js +4 -4
  122. package/dist/tips.js.map +1 -1
  123. package/dist/tmux-manager.d.ts +1 -1
  124. package/dist/tmux-manager.js +4 -1
  125. package/dist/tmux-manager.js.map +1 -1
  126. package/dist/tool-permissions.d.ts +2 -3
  127. package/dist/tool-permissions.js +3 -3
  128. package/dist/tool-permissions.js.map +1 -1
  129. package/dist/topic-commands.js +1 -1
  130. package/dist/topic-commands.js.map +1 -1
  131. package/dist/types.d.ts +2 -0
  132. package/dist/types.js.map +1 -1
  133. package/dist/ui/backend-signin.js +62 -62
  134. package/dist/ui/chat-commands.js +7 -0
  135. package/dist/ui/chat-store.js +9 -4
  136. package/dist/ui/chat-strings.js +25 -25
  137. package/dist/ui/fleet-cache.js +3 -3
  138. package/dist/ui/fleet-canvas.js +2 -2
  139. package/dist/ui/fleet-office-editor.js +1 -1
  140. package/dist/ui/fleet-office.js +1 -1
  141. package/dist/ui/fleet-org.js +2 -2
  142. package/dist/ui/fleet-task-card.js +1 -1
  143. package/dist/ui/fleet-task-common.js +7 -7
  144. package/dist/ui/model-picker.js +64 -0
  145. package/dist/ui/panel-chat.js +47 -16
  146. package/dist/ui/panel-fleet.js +8 -8
  147. package/dist/ui/panel-needs.js +3 -3
  148. package/dist/ui/panel-settings.js +16 -6
  149. package/dist/ui/settings-catalog.js +19 -4
  150. package/dist/ui/settings-dialogs.js +28 -9
  151. package/dist/ui/settings-guests.js +1 -1
  152. package/dist/ui/settings-quota-notice.js +8 -6
  153. package/dist/ui/settings-registry.js +3 -1
  154. package/dist/ui/settings-strings.js +36 -30
  155. package/dist/ui/settings-update.js +69 -0
  156. package/dist/ui/shared/app-i18n.js +12 -6
  157. package/dist/ui/shared/app-shell.js +10 -3
  158. package/dist/ui/shared/app-update.js +215 -0
  159. package/dist/ui/shared/app.css +48 -2
  160. package/dist/ui/shared/instance-nav.js +1 -1
  161. package/dist/ui/shared/model-picker.css +21 -0
  162. package/dist/ui/shared/setup-host-text.js +8 -5
  163. package/dist/ui/shared/signin.js +35 -17
  164. package/dist/ui/shared/subagent-row.css +15 -0
  165. package/dist/ui/shared/view-strings.js +17 -17
  166. package/dist/ui/shared/web-authorize.js +4 -4
  167. package/dist/ui/structured-signin.js +26 -26
  168. package/dist/ui/subagent-row.js +64 -0
  169. package/dist/ui/web-terminal/terminal.js +9 -9
  170. package/dist/update-dispatch.d.ts +32 -4
  171. package/dist/update-dispatch.js +146 -16
  172. package/dist/update-dispatch.js.map +1 -1
  173. package/dist/update-launch.d.ts +1 -1
  174. package/dist/update-launch.js +2 -2
  175. package/dist/update-launch.js.map +1 -1
  176. package/dist/update-marker.d.ts +2 -2
  177. package/dist/update-marker.js +4 -3
  178. package/dist/update-marker.js.map +1 -1
  179. package/dist/usage/providers.d.ts +1 -0
  180. package/dist/usage/providers.js +13 -9
  181. package/dist/usage/providers.js.map +1 -1
  182. package/dist/usage-rollup.d.ts +3 -0
  183. package/dist/usage-rollup.js +2 -0
  184. package/dist/usage-rollup.js.map +1 -1
  185. package/dist/view-api.d.ts +2 -8
  186. package/dist/view-api.js +3 -9
  187. package/dist/view-api.js.map +1 -1
  188. package/dist/web-api.d.ts +14 -0
  189. package/dist/web-api.js +216 -2
  190. package/dist/web-api.js.map +1 -1
  191. package/dist/web-auth.js +2 -1
  192. package/dist/web-auth.js.map +1 -1
  193. package/dist/web-commands.d.ts +8 -0
  194. package/dist/web-commands.js +6 -0
  195. package/dist/web-commands.js.map +1 -1
  196. package/dist/web-update.d.ts +77 -0
  197. package/dist/web-update.js +102 -0
  198. package/dist/web-update.js.map +1 -0
  199. package/package.json +3 -2
@@ -1,3 +1,4 @@
1
+ import { SubagentService } from "./subagent-service.js";
1
2
  import { QuotaNotices } from "./usage/quota-notices.js";
2
3
  import { quotaNoticeRule } from "./quota-notice-config.js";
3
4
  import { onUsageSnapshot } from "./usage/usage-api.js";
@@ -239,6 +240,7 @@ import { Delegations, TrafficLog, trafficItem } from "./fleet-traffic.js";
239
240
  import { installedChannel, updateNoticeKey } from "./update-check.js";
240
241
  import { resolveInstalledAgend } from "./update-dispatch.js";
241
242
  import { resolveUpdateLaunch, openUpdateLog, updateLogPath, watchUpdateLaunch } from "./update-launch.js";
243
+ import { isWebUpdateTarget, readLogTail, RUNNING_AGEND_VERSION, updateOffer, webProgressOf, webUpdateTarget } from "./web-update.js";
242
244
  import { admitProfileLogin, LoginController, LOGIN_TOKEN_RESEND_PREFIX, POST_LOGIN_RECOVERY_DEADLINE_MS } from "./login-controller.js";
243
245
  import { WebBackendLogins, dashboardSignInSupported } from "./web-backend-login.js";
244
246
  import { runBeforeDeadline } from "./deadline.js";
@@ -669,6 +671,7 @@ export class RestartSupersededError extends Error {
669
671
  }
670
672
  export class FleetManager {
671
673
  dataDir;
674
+ decisionSnapshot = [];
672
675
  static signalTarget = null;
673
676
  static sighupHandlerInstalled = false;
674
677
  /** Test seam: inject a spy to verify saveFleetConfig calls fsync. Default: fsyncSync. */
@@ -1040,6 +1043,18 @@ export class FleetManager {
1040
1043
  previewInputs = "";
1041
1044
  healthPortRetried = false;
1042
1045
  updateCheckTimer = null;
1046
+ /** M-2738: the last update check's answer, for the web (null until the first check settles). */
1047
+ updateCheckState = null;
1048
+ /** M-2738: a web "check now" in flight, and when the last one ran (one a minute at most). */
1049
+ updateCheckNow = { running: null, lastAt: 0 };
1050
+ /** M-2738: a web start's Idempotency-Key → its answer (a retried request never starts a second update). */
1051
+ webUpdateStarts = new Map();
1052
+ /**
1053
+ * M-2738 (Prism #3505 P2-2): this fleet's own claim on a web-started update, from admission until its updater exits
1054
+ * (or was never launched). The progress marker expires after 15 minutes so a crashed update cannot silence incident
1055
+ * reports; that expiry never proves the update ended, so it never admits a second one while this is held.
1056
+ */
1057
+ webUpdateOwned = null;
1043
1058
  updateProgressTimer = null;
1044
1059
  updateProgressEditRunning = false;
1045
1060
  lastUpdateProgressText = null;
@@ -3233,7 +3248,7 @@ export class FleetManager {
3233
3248
  if (current && !sameUpdateMarker(current, bootUpdateMarker))
3234
3249
  return;
3235
3250
  const leftover = readUpdateProgress(this.dataDir)?.progress;
3236
- if (leftover?.cleanup === "pending" && leftover.stage !== "failed" && leftover.stage !== "complete")
3251
+ if (leftover?.cleanup === "pending" && !isWebUpdateTarget(leftover.target) && leftover.stage !== "failed" && leftover.stage !== "complete")
3237
3252
  return;
3238
3253
  clearUpdateMarker(this.dataDir);
3239
3254
  }
@@ -3590,25 +3605,32 @@ export class FleetManager {
3590
3605
  const chatId = String(this.getChannelConfig(adapterId)?.group_id ?? data.channelId);
3591
3606
  this.beginUpdateProgress(adapter, chatId, data.channelId, messageId);
3592
3607
  }
3593
- const { spawn } = await import("./child-process.js");
3594
3608
  // Plain `agend update`: the CLI picks the channel from the version it is about to replace (a beta install
3595
3609
  // stays on beta). Deciding here, from the package.json next to THIS code, read a source checkout's 1.22.0 as
3596
3610
  // "not a beta" and sent a beta install to @latest. #1450 C5: the INSTALLED agend, verified, by absolute path.
3611
+ await this.launchInstalledUpdate(`slash /update by ${adapterId}:${data.userId}`, () => this.fleetAdminGate(data.userId, adapterId) === "ok" && !this.shuttingDown);
3612
+ }
3613
+ /**
3614
+ * The update itself, for slash `/update` and the web's Update (M-2738): the installed `agend`, verified, launched
3615
+ * independently with its log — or a failure in the progress marker. `stillAllowed` is asked again once the awaits
3616
+ * are done (the asker may have lost the right, or the fleet begun stopping, meanwhile).
3617
+ */
3618
+ async launchInstalledUpdate(origin, stillAllowed) {
3619
+ const { spawn } = await import("./child-process.js");
3597
3620
  const installed = await resolveInstalledAgend();
3598
3621
  if (!installed.ok) {
3599
3622
  this.failUpdateProgress(`${t("update.failure.shell")} ${t("update.failure.installed", installed.reason)}`);
3600
- return;
3623
+ return null;
3601
3624
  }
3602
- const origin = `slash /update by ${adapterId}:${data.userId}`;
3603
3625
  recordInternalRequest(this.dataDir, "update", origin);
3604
- const launch = await resolveUpdateLaunch(installed.agend);
3626
+ const launch = await resolveUpdateLaunch(installed.agend, undefined, installed.npmDir);
3605
3627
  if (!launch.ok) {
3606
3628
  this.failUpdateProgress(`${t("update.failure.shell")} ${t("update.failure.independent", launch.reason)}`);
3607
- return;
3629
+ return null;
3608
3630
  }
3609
- if (this.fleetAdminGate(data.userId, adapterId) !== "ok" || this.shuttingDown) {
3631
+ if (!stillAllowed()) {
3610
3632
  this.failUpdateProgress(t("not_authorized"));
3611
- return;
3633
+ return null;
3612
3634
  }
3613
3635
  const logPath = updateLogPath(this.dataDir);
3614
3636
  const ts = new Date().toISOString();
@@ -3620,6 +3642,7 @@ export class FleetManager {
3620
3642
  closeSync(logFd.fd); // parent closes its copy; the child's fd stays open
3621
3643
  watchUpdateLaunch(child, message => this.failUpdateProgress(message), logFd ? logPath : undefined, logFd?.offset, installed.agend);
3622
3644
  child.unref();
3645
+ return child;
3623
3646
  }
3624
3647
  async handleProfileSlash(data, adapterId) {
3625
3648
  const route = this.routing.resolve(data.channelId);
@@ -4127,6 +4150,8 @@ export class FleetManager {
4127
4150
  }
4128
4151
  /** #1218: GET /ui/steps — an instance's steps, read on demand (null: no such instance). */
4129
4152
  logSteps(name, q) { return this.log.steps(name, q); }
4153
+ subagentReader = new SubagentService(name => this.lifecycle.daemons.get(name)?.subagentSource() ?? null);
4154
+ subagentRuns(name) { return this.subagentReader.read(name); }
4130
4155
  /**
4131
4156
  * #1218: where an instance's steps are read from, resolved only when its Log asks: the transcript its daemon follows
4132
4157
  * now; for claude-code, also the path its statusline last named (so a stopped instance's Log still shows its last
@@ -6160,6 +6185,22 @@ export class FleetManager {
6160
6185
  * Stopped/paused ClassicBot entries count too; their workspace is exactly
6161
6186
  * the one startClassicInstance builds, not this FleetManager's dataDir.
6162
6187
  */
6188
+ /** Take the startup snapshot of every active decision (text cut to 200 characters); see activeDecisions. */
6189
+ snapshotActiveDecisions() {
6190
+ try {
6191
+ const decisions = this.scheduler?.db.listAllActiveDecisions() ?? [];
6192
+ this.decisionSnapshot = decisions.map(d => ({ title: d.title, content: (d.content ?? "").slice(0, 200), scope: d.scope, project_root: d.project_root, ...(d.team ? { team: d.team } : {}) }));
6193
+ if (decisions.length > 0)
6194
+ this.logger.info({ count: decisions.length }, "Active decisions snapshotted for instance instructions");
6195
+ }
6196
+ catch (err) {
6197
+ this.logger.debug({ err }, "Decision injection skipped (no decisions db or query failed)");
6198
+ }
6199
+ }
6200
+ /** The startup snapshot of active decisions, for a daemon's Active Decisions (it selects and caps its own). */
6201
+ activeDecisions() {
6202
+ return this.decisionSnapshot;
6203
+ }
6163
6204
  kiroPeerWorkingDirectories(name) {
6164
6205
  if (!this.fleetConfig || !this.classicChannels)
6165
6206
  throw new Error("Kiro peer configuration is not loaded");
@@ -8032,6 +8073,9 @@ export class FleetManager {
8032
8073
  updateCleanupAtCompletion(pending, operation) {
8033
8074
  if (!pending || operation !== "update")
8034
8075
  return null;
8076
+ // M-2738: no chat message to append a retire warning to; the updater's log keeps it.
8077
+ if (isWebUpdateTarget(pending.progress.target))
8078
+ return null;
8035
8079
  const receipt = updateReceiptOf(pending);
8036
8080
  if (!receipt)
8037
8081
  return null;
@@ -8295,13 +8339,10 @@ export class FleetManager {
8295
8339
  // main / the 2.3 line ONLY: on the 2.4 line (release/2.3.5-alpha) AgEnD's own server IS the one on `agend` — a
8296
8340
  // main → alpha sync must keep alpha's side of this block, never both.
8297
8341
  {
8298
- const { newerTmuxServer, realGuardDeps, guardMessage } = await import("./bundled-tmux-guard.js");
8342
+ const { newerTmuxServer, realGuardDeps, BundledTmuxStartupError } = await import("./bundled-tmux-guard.js");
8299
8343
  const hit = await newerTmuxServer(realGuardDeps(getAgendHome(), isDefaultAgendHome(), getSocket()));
8300
- if (hit) {
8301
- const message = guardMessage(hit);
8302
- this.logger.error({ socket: hit.socket, confirmed: hit.confirmed }, message);
8303
- throw new Error(message);
8304
- }
8344
+ if (hit)
8345
+ throw new BundledTmuxStartupError(hit);
8305
8346
  }
8306
8347
  await TmuxManager.ensureSession(getTmuxSession());
8307
8348
  this.tmuxSessionEnsured = true;
@@ -8369,6 +8410,8 @@ export class FleetManager {
8369
8410
  if (ch.adapterId)
8370
8411
  this.instanceWorldBinding.set(ch.instanceName, ch.adapterId);
8371
8412
  }
8413
+ // #3526: catalogs belong to the fleet, including a fleet with no chat adapter.
8414
+ this.probeCliEnvs();
8372
8415
  // #1565: the web chat as it was before this process — the configured instances' only (fleet.yaml and ClassicBot
8373
8416
  // rooms), before the dashboard serves anything; from now on every change is written back (off the loop).
8374
8417
  this.restoreWebChat(fleet);
@@ -8538,20 +8581,12 @@ export class FleetManager {
8538
8581
  this.logger.warn({ err }, "Failed to send daily tip");
8539
8582
  }));
8540
8583
  this.dailyTipScheduler.start();
8541
- // Inject active decisions as env var for MCP instructions.
8542
- // Snapshotted at startup — new decisions via post_decision are available
8543
- // through list_decisions tool but not auto-injected until restart.
8544
- try {
8545
- const decisions = this.scheduler.db.listAllActiveDecisions();
8546
- if (decisions.length > 0) {
8547
- const capped = decisions.slice(0, 20).map(d => ({ title: d.title, content: (d.content ?? "").slice(0, 200), scope: d.scope, project_root: d.project_root }));
8548
- process.env.AGEND_DECISIONS = JSON.stringify(capped);
8549
- this.logger.info({ count: decisions.length, injected: capped.length }, "Injected active decisions into env");
8550
- }
8551
- }
8552
- catch (err) {
8553
- this.logger.debug({ err }, "Decision injection skipped (no decisions db or query failed)");
8554
- }
8584
+ // Active decisions for each instance's instructions, snapshotted at startup — new decisions via post_decision are
8585
+ // available through list_decisions but not auto-injected until restart. The whole active set is kept here (each
8586
+ // entry's text cut to 200 characters) and handed to each daemon at spawn (activeDecisions): the daemon selects
8587
+ // its own — fleet, its teams, its directory — and only then applies its caps, so other teams' or directories'
8588
+ // rows can never crowd an instance's own out (#3421 review). Nothing unbounded goes into process.env.
8589
+ this.snapshotActiveDecisions();
8555
8590
  }
8556
8591
  // Phase 1: Start general instances first and wait for them
8557
8592
  const allEntries = Object.entries(fleet.instances);
@@ -8612,7 +8647,8 @@ export class FleetManager {
8612
8647
  this.reportClassicUnrecoverableIds();
8613
8648
  })();
8614
8649
  progressStart = adapterStartup.then(() => {
8615
- if (pendingUpdateProgress) {
8650
+ // M-2738: a web-started update has no chat message to adopt: the boot is announced as any restart is.
8651
+ if (pendingUpdateProgress && !isWebUpdateTarget(pendingUpdateProgress.progress.target)) {
8616
8652
  const saved = pendingUpdateProgress.progress.target;
8617
8653
  const target = {
8618
8654
  adapter: this.adapters.get(saved.adapterId),
@@ -9539,9 +9575,6 @@ export class FleetManager {
9539
9575
  }, this.logger, "adapter.slash_command"));
9540
9576
  // This adapter's own Telegram menus — each Telegram adapter registers its own when it starts (#1191).
9541
9577
  this.registerTelegramCommandsFor(channelConfig);
9542
- // Background-probe each backend's CLI env (version/models) → cli-env cache.
9543
- // Non-blocking: /model & status views read the cache; never delays startup.
9544
- this.probeCliEnvs();
9545
9578
  adapter.on("started", safeHandler((username, userId) => {
9546
9579
  if (!isCurrentAdapter())
9547
9580
  return;
@@ -11492,6 +11525,13 @@ export class FleetManager {
11492
11525
  isWebOnlyFleet() {
11493
11526
  return isWebOnlyFleetConfig(this.fleetConfig);
11494
11527
  }
11528
+ /**
11529
+ * S-117 story 1: the sign-in page's "no chat" words (no /web to send) — a web-only fleet, or one whose chat is not
11530
+ * connected yet (a fresh install whose bot is still being set up, or is down): /web cannot answer there.
11531
+ */
11532
+ signinWithoutChat() {
11533
+ return this.isWebOnlyFleet() || ![...this.adapterState.values()].some(state => state.status === "connected");
11534
+ }
11495
11535
  /** On a fleet with no chat platform, the dashboard is where an instance-health prompt is posted (#1307 item 6). */
11496
11536
  webOnlyPromptPlace() {
11497
11537
  return this.worlds.size === 0 && this.isWebOnlyFleet() ? { adapter: WEB_ONLY_PROMPT_SINK, adapterId: "web", chatId: "web" } : null;
@@ -12075,6 +12115,11 @@ export class FleetManager {
12075
12115
  let result;
12076
12116
  switch (msg.type) {
12077
12117
  case "fleet_decision_create": {
12118
+ const scoped = this.decisionScopeFor(instanceName, payload.scope, payload.team);
12119
+ if ("error" in scoped) {
12120
+ ipc.send({ type: "fleet_decision_response", fleetRequestId, error: scoped.error });
12121
+ return;
12122
+ }
12078
12123
  const supersedes = this.decisionSupersedes("ipc-typed", instanceName, payload.supersedes);
12079
12124
  if ("error" in supersedes) {
12080
12125
  ipc.send({ type: "fleet_decision_response", fleetRequestId, error: supersedes.error });
@@ -12084,7 +12129,9 @@ export class FleetManager {
12084
12129
  db.pruneExpiredDecisions();
12085
12130
  result = db.createDecision({
12086
12131
  project_root: projectRoot,
12087
- scope: payload.scope,
12132
+ scope: scoped.scope,
12133
+ team: scoped.team,
12134
+ poster_teams: scoped.teams,
12088
12135
  title: payload.title,
12089
12136
  content: payload.content,
12090
12137
  tags: payload.tags,
@@ -12100,10 +12147,16 @@ export class FleetManager {
12100
12147
  result = decisionListAnswer(db.listDecisions(projectRoot, {
12101
12148
  includeArchived: payload.include_archived,
12102
12149
  tags: payload.tags,
12150
+ teams: instanceTeams(this.fleetConfig?.teams, instanceName),
12103
12151
  }), { id: payload.id, full: payload.full });
12104
12152
  break;
12105
12153
  case "fleet_decision_update": {
12106
12154
  const id = payload.id;
12155
+ const hidden = this.decisionHiddenFrom(instanceName, id);
12156
+ if (hidden) {
12157
+ ipc.send({ type: "fleet_decision_response", fleetRequestId, error: hidden });
12158
+ return;
12159
+ }
12107
12160
  if (payload.archive) {
12108
12161
  db.archiveDecision(id);
12109
12162
  result = { archived: true, id };
@@ -12282,28 +12335,95 @@ export class FleetManager {
12282
12335
  return { error: `Superseding a decision needs update_decision. ${permitted.message}` };
12283
12336
  return { id: value };
12284
12337
  }
12338
+ /**
12339
+ * The scope (and team) a new decision gets. Team membership is read from fleet.yaml now. Omitted scope: the poster's
12340
+ * team when they are in exactly one, project (this exact directory) when they are in none; in several, they choose.
12341
+ * A team decision goes only to a team the poster is in.
12342
+ */
12343
+ decisionScopeFor(instance, scope, team) {
12344
+ const teams = instanceTeams(this.fleetConfig?.teams, instance);
12345
+ const named = typeof team === "string" && team.trim() ? team.trim() : undefined;
12346
+ if (scope !== undefined && scope !== null && scope !== "project" && scope !== "team" && scope !== "fleet") {
12347
+ return { error: `scope must be "project", "team" or "fleet"` };
12348
+ }
12349
+ if (scope === "project" || scope === "fleet") {
12350
+ return named ? { error: `team goes with scope "team", not "${scope}"` } : { scope, teams };
12351
+ }
12352
+ if (named) {
12353
+ if (!teams.includes(named)) {
12354
+ return { error: teams.length ? `You are not in team "${named}". Your teams: ${teams.join(", ")}` : `You are not in team "${named}" (you are in no team)` };
12355
+ }
12356
+ return { scope: "team", team: named, teams };
12357
+ }
12358
+ if (teams.length === 1)
12359
+ return { scope: "team", team: teams[0], teams };
12360
+ if (teams.length > 1)
12361
+ return { error: `You are in several teams (${teams.join(", ")}): name one with team, or use scope "project" or "fleet"` };
12362
+ if (scope === "team")
12363
+ return { error: `You are in no team: use scope "project" (this directory) or "fleet"` };
12364
+ return { scope: "project", teams };
12365
+ }
12366
+ /**
12367
+ * #3421 review: a team decision is only for its team's current members — reading it back through an update (even an
12368
+ * empty one) or archiving it is refused to anyone else, exactly as list/get and supersede are. The refusal names it
12369
+ * "not found", as for an id that does not exist, and changes nothing. Project and fleet decisions: as before.
12370
+ */
12371
+ decisionHiddenFrom(instance, id) {
12372
+ if (typeof id !== "string" || !this.scheduler)
12373
+ return null;
12374
+ const d = this.scheduler.db.getDecision(id);
12375
+ if (!d || d.scope !== "team")
12376
+ return null;
12377
+ return d.team && instanceTeams(this.fleetConfig?.teams, instance).includes(d.team) ? null : `Decision "${id}" not found`;
12378
+ }
12379
+ /** A ClassicBot agent's own folder — where startClassicInstance launches it, and its project for decisions (#3454). */
12380
+ classicWorkspaceDir(instanceName) {
12381
+ return join(getAgendHome(), "workspaces", instanceName);
12382
+ }
12383
+ /**
12384
+ * #3454: the project root of an agent calling the agent endpoint (CLI mode), as the MCP path has it from the daemon's
12385
+ * own working directory. A fleet instance: its fleet.yaml working_directory, as before. A ClassicBot agent (not in
12386
+ * fleet.yaml): its own workspace — it used to fall back to "", one project shared by every CLI-mode ClassicBot room.
12387
+ * Anything else: null, and the caller refuses rather than guess.
12388
+ */
12389
+ decisionProjectRootFor(instance) {
12390
+ const fleet = this.fleetConfig?.instances;
12391
+ if (fleet && Object.hasOwn(fleet, instance))
12392
+ return fleet[instance]?.working_directory ?? "";
12393
+ if (this.classicChannels?.getAll().some(ch => ch.instanceName === instance))
12394
+ return this.classicWorkspaceDir(instance);
12395
+ return null;
12396
+ }
12285
12397
  async handleDecisionCrudHttp(instance, op, args) {
12286
12398
  if (!this.scheduler)
12287
12399
  return { error: "Scheduler not available" };
12288
12400
  const db = this.scheduler.db;
12289
- const projectRoot = this.fleetConfig?.instances[instance]?.working_directory ?? "";
12401
+ const root = this.decisionProjectRootFor(instance);
12402
+ const unknownRoot = { error: `Decisions are unavailable for "${instance}": it is neither a fleet instance nor a ClassicBot agent, so its working directory is unknown` };
12403
+ const projectRoot = root ?? "";
12290
12404
  const asStr = (v) => typeof v === "string" ? v : undefined;
12291
12405
  const asNum = (v) => typeof v === "number" ? v : undefined;
12292
12406
  const asStrArr = (v) => Array.isArray(v) && v.every(x => typeof x === "string") ? v : undefined;
12293
12407
  switch (op) {
12294
12408
  case "post": {
12409
+ if (root === null)
12410
+ return unknownRoot;
12295
12411
  const title = asStr(args.title);
12296
12412
  const content = asStr(args.content);
12297
12413
  if (!title || !content)
12298
12414
  return { error: "title and content are required" };
12299
- const scope = args.scope === "fleet" ? "fleet" : "project";
12415
+ const scoped = this.decisionScopeFor(instance, args.scope, args.team);
12416
+ if ("error" in scoped)
12417
+ return { error: scoped.error };
12300
12418
  const supersedes = this.decisionSupersedes("agent-endpoint", instance, args.supersedes);
12301
12419
  if ("error" in supersedes)
12302
12420
  return { error: supersedes.error };
12303
12421
  try {
12304
12422
  return db.createDecision({
12305
12423
  project_root: projectRoot,
12306
- scope,
12424
+ scope: scoped.scope,
12425
+ team: scoped.team,
12426
+ poster_teams: scoped.teams,
12307
12427
  title,
12308
12428
  content,
12309
12429
  tags: asStrArr(args.tags),
@@ -12322,14 +12442,20 @@ export class FleetManager {
12322
12442
  case "get":
12323
12443
  if (op === "get" && !asStr(args.id)?.trim())
12324
12444
  return { error: "id is required" };
12445
+ if (root === null)
12446
+ return unknownRoot;
12325
12447
  return decisionListAnswer(db.listDecisions(projectRoot, {
12326
12448
  includeArchived: args.includeArchived === true || args.include_archived === true,
12327
12449
  tags: asStrArr(args.tags),
12450
+ teams: instanceTeams(this.fleetConfig?.teams, instance),
12328
12451
  }), { id: op === "get" ? asStr(args.id) ?? "" : args.id, full: args.full });
12329
12452
  case "update": {
12330
12453
  const id = asStr(args.id);
12331
12454
  if (!id)
12332
12455
  return { error: "id is required" };
12456
+ const hidden = this.decisionHiddenFrom(instance, id);
12457
+ if (hidden)
12458
+ return { error: hidden };
12333
12459
  return db.updateDecision(id, {
12334
12460
  content: asStr(args.content),
12335
12461
  tags: asStrArr(args.tags),
@@ -13088,7 +13214,9 @@ export class FleetManager {
13088
13214
  delete current[key];
13089
13215
  Object.assign(current, resolved);
13090
13216
  }
13217
+ const previousCatalogConfig = this.savedFleetConfigSnapshot;
13091
13218
  this.savedFleetConfigSnapshot = structuredClone(this.fleetConfig);
13219
+ this.probeChangedCliEnvs(previousCatalogConfig);
13092
13220
  this.agentCredentialsCache?.observePolicies();
13093
13221
  this.refreshSavedDashboardPermissions();
13094
13222
  this.logger.info({ path: this.configPath, strippedDefaults: redundantPaths.length }, "Saved fleet config (lossless patch)");
@@ -16473,13 +16601,13 @@ export class FleetManager {
16473
16601
  ...(opts.guest ? { webGuest: true } : {}), // #2855: a guest's /steer or /btw reaches the agent as a guest's
16474
16602
  };
16475
16603
  };
16476
- const choicesFromCache = (instance) => {
16604
+ const choicesFromCache = (instance, more = false) => {
16477
16605
  const backend = this.backendNameForInstance(instance);
16478
- const cached = this.readCliEnv(backend, this.catalogProfile(backend, instance)); // the cached catalog only: never a probe here
16479
- if (!cached?.models.length)
16480
- return null;
16606
+ const env = this.webModelEnv(backend, instance);
16481
16607
  const current = this.resolveInstanceModel(instance).model;
16482
- return { current, options: this.withCurrentModel(cached.models, current).map(o => ({ id: o.id, label: this.modelChoiceLabel(o, current) })) };
16608
+ const models = more ? this.modelCatalogFor(backend, instance) : env?.models ?? [];
16609
+ return { current, options: this.withCurrentModel(models, current).map(o => ({ id: o.id, label: this.modelChoiceLabel(o, current) })),
16610
+ actions: more ? ["refreshAll"] : backend === "claude-code" ? ["refresh", "more"] : ["refresh"] };
16483
16611
  };
16484
16612
  return runWebCommand({
16485
16613
  scope: (instance) => this.webCommandScope(instance),
@@ -16503,6 +16631,31 @@ export class FleetManager {
16503
16631
  },
16504
16632
  applyModel: (instance, name) => this.applyModel(instance, name),
16505
16633
  modelChoices: choicesFromCache,
16634
+ modelAction: async (instance, command, args, action, actionOpts) => {
16635
+ const tokens = backendArgs(args);
16636
+ if ((command === "model" && args) || (command === "backend" && (tokens.length !== 1 || action !== "refresh")))
16637
+ return { error: t("menu.click_stale") };
16638
+ const backend = command === "model" ? this.backendNameForInstance(instance) : tokens[0];
16639
+ if (command === "backend") {
16640
+ const refusal = this.backendCommandRefusal(instance);
16641
+ if (refusal)
16642
+ return { error: refusal };
16643
+ const step = await backendStep(this.backendCommandDeps(instance, { live: false }), instance, tokens);
16644
+ if (step.kind !== "choose" || step.step !== "model")
16645
+ return { error: step.kind === "refuse" ? step.text : t("menu.click_stale") };
16646
+ }
16647
+ if (action === "more" && backend !== "claude-code")
16648
+ return { error: t("menu.click_stale") };
16649
+ if (action !== "more" || !this.webModelEnv(backend, instance)?.apiModels?.length) {
16650
+ const result = await this.refreshModelCatalogFor(backend, instance);
16651
+ if (!result.refreshed)
16652
+ return { error: t("model.refresh_failed") };
16653
+ }
16654
+ if (command === "model")
16655
+ return { choices: choicesFromCache(instance, action !== "refresh") };
16656
+ // Re-enter the shared backend→model→effort→confirm flow; no configuration write during refresh.
16657
+ return this.webCommand({ instance, command: "backend", args }, { ...opts, publicLink: actionOpts.publicLink }).then(r => r.body);
16658
+ },
16506
16659
  applyEffort: (instance, level) => this.applyEffort(instance, level),
16507
16660
  effortChoices: (instance) => {
16508
16661
  const levels = this.effortLevelsFor(instance);
@@ -16516,12 +16669,12 @@ export class FleetManager {
16516
16669
  if (refusal)
16517
16670
  return { error: refusal };
16518
16671
  // The cached model lists only, as the web's /model: never a live probe on this path.
16519
- const step = await backendStep(this.backendCommandDeps(instance, { live: false }), instance, backendArgs(args));
16672
+ const step = await backendStep({ ...this.backendCommandDeps(instance, { live: false }), models: async (backend) => this.modelCatalogFor(backend, instance) }, instance, backendArgs(args));
16520
16673
  if (step.kind === "refuse")
16521
16674
  return step.noop ? { text: step.text } : { error: step.text };
16522
16675
  if (step.kind === "choose") {
16523
16676
  const id = (token) => joinBackendArgs([...step.args, token]);
16524
- return { choices: { prompt: step.text, current: step.current === null ? null : id(step.current), options: step.choices.map(c => {
16677
+ return { choices: { step: step.step, args: joinBackendArgs(step.args), ...(step.step === "model" ? { actions: ["refresh"] } : {}), prompt: step.text, current: step.current === null ? null : id(step.current), options: step.choices.map(c => {
16525
16678
  // #2233: the web offers Sign in beside it, so its reason is no longer "use /login".
16526
16679
  // Not over the public link: Sign in is refused there, so the choice keeps its "(use /login)" (#2262 review).
16527
16680
  const signIn = c.signIn && !stepOpts?.publicLink && dashboardSignInSupported(c.signIn) ? c.signIn : null;
@@ -19624,7 +19777,11 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
19624
19777
  // re-enters this path.
19625
19778
  const selfMentionRe = new RegExp(`<@${adapterBotUserId}>`, "g");
19626
19779
  const strippedText = text.replace(selfMentionRe, "").trim();
19627
- if (!strippedText && !msg.attachments?.length)
19780
+ // A bare @mention says nothing by itself, so it is dropped (unchanged)... unless it is a REPLY that carries the mention: then the
19781
+ // replied-to message is what is being asked about, and it travels as reply_to_text (#3340). Telegram already forwards this shape
19782
+ // ("/chat @bot (you)"). Only with the mention in the text: an empty reply to one of our own messages (addressed through #2551, a
19783
+ // sticker or embed only) stays dropped, never an empty turn quoting our own answer (Fable #3342 F1).
19784
+ if (!strippedText && !msg.attachments?.length && !(msg.replyToText && mentionTag && addressText.includes(mentionTag)))
19628
19785
  return;
19629
19786
  const selfMarker = mentionWorld?.botUsername ? `@${mentionWorld.botUsername} (you)` : `${mentionTag} (you)`;
19630
19787
  const cleanText = text.replace(selfMentionRe, selfMarker).trim();
@@ -19889,7 +20046,7 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
19889
20046
  /** #1806: null on a switch INTO claude-code — the configured model then belongs to the backend being left. */
19890
20047
  configured = this.fleetConfig?.instances[instanceName]?.model ?? this.fleetConfig?.defaults?.model) {
19891
20048
  const aliases = ["default", "sonnet", "opus", "haiku", "opusplan", "Fable"];
19892
- const api = (this.readCliEnv("claude-code", this.catalogProfile("claude-code", instanceName))?.apiModels ?? []).map(m => m.id);
20049
+ const api = (this.webModelEnv("claude-code", instanceName)?.apiModels ?? []).map(m => m.id);
19893
20050
  const lower = model.trim().toLowerCase();
19894
20051
  const bare = lower.replace(/\[1m\]$/, "");
19895
20052
  const known = aliases.some(a => a.toLowerCase() === bare)
@@ -20032,6 +20189,8 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
20032
20189
  this.pendingCliEnvProbes.clear();
20033
20190
  this.pendingVendorCliEnvProbes.clear();
20034
20191
  this.pendingInstanceModelProbes.clear();
20192
+ this.webModelRefreshes.clear();
20193
+ this.webModelCatalogs.clear();
20035
20194
  }
20036
20195
  runBackendProbeWorker(key, input) {
20037
20196
  if (this.shuttingDown)
@@ -20203,18 +20362,35 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
20203
20362
  // indefinitely — each is wrapped by CLI_ENV_PROBE_DEADLINE_MS.
20204
20363
  for (const b of backends)
20205
20364
  void this.probeBackendBounded(b);
20206
- // #2072: each Claude credential profile in use has its own account catalog. Only fleet.yaml's agents are walked
20207
- // here; a ClassicBot room on a profile is probed on its first /model (catalogProfile knows rooms too).
20208
- const profiles = new Set();
20365
+ this.probeChangedCliEnvs(null);
20366
+ }
20367
+ /** Maintain discovery after committed config changes; a model-field read remains passive. */
20368
+ probeChangedCliEnvs(previous) {
20369
+ const signature = (fleet, name) => {
20370
+ const inst = fleet?.instances[name];
20371
+ if (!inst)
20372
+ return null;
20373
+ const backend = inst.backend ?? fleet?.defaults?.backend ?? "claude-code";
20374
+ return JSON.stringify({ backend, options: { ...fleet?.defaults?.backend_options?.[backend], ...inst.backend_options?.[backend] } });
20375
+ };
20209
20376
  for (const name of Object.keys(this.fleetConfig?.instances ?? {})) {
20210
- if (this.backendNameForInstance(name) !== "claude-code")
20377
+ const backend = this.backendNameForInstance(name);
20378
+ const binding = this.webModelBinding(backend, name);
20379
+ // A named agy account has no verified relocation/discovery contract. In particular,
20380
+ // never publish the ambient account's models under that profile (#3526 / D7).
20381
+ if (!binding || (binding.profile && !credentialHomeSpec(backend)))
20382
+ continue;
20383
+ // A description/defaults save can retire a scoped answer's full binding even
20384
+ // though its account signature is unchanged. Keep the conservative fence and
20385
+ // re-arm the current binding, unless its answer or flight is already present.
20386
+ if (previous && signature(previous, name) === signature(this.fleetConfig, name)
20387
+ && (!binding.scoped || this.webModelEnv(backend, name) || this.webModelRefreshes.has(binding.key)))
20211
20388
  continue;
20212
- const profile = this.catalogProfile("claude-code", name);
20213
- if (profile)
20214
- profiles.add(profile);
20389
+ const work = binding.scoped
20390
+ ? this.refreshModelCatalogFor(backend, name)
20391
+ : this.probeBackendBounded(backend, { profile: binding.profile });
20392
+ void work.catch(err => this.logger.debug({ backend, name, err }, "Background model discovery failed"));
20215
20393
  }
20216
- for (const profile of profiles)
20217
- void this.probeBackendBounded("claude-code", { profile });
20218
20394
  }
20219
20395
  /** Best-effort model list for `/model`: cached CLI env first, else live probe. Never throws. */
20220
20396
  async getModelOptions(instanceName, refresh = false, onLiveProbe) {
@@ -21129,7 +21305,7 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
21129
21305
  currentBackend: (name) => this.backendNameForInstance(name),
21130
21306
  currentDisplay: (name) => `${this.backendNameForInstance(name)} · ${this.resolveInstanceModel(name).display}`,
21131
21307
  availability: () => this.backendAvailabilityFor(instanceName),
21132
- models: (backend) => this.backendModelOptions(backend, opts),
21308
+ models: (backend) => this.backendModelOptions(backend, { ...opts, instance: instanceName }),
21133
21309
  // #1808: the same rule update_instance_config's switch applies (backendModelVerdict).
21134
21310
  modelKnown: (backend, model) => this.backendModelVerdict(instanceName, backend, model).ok,
21135
21311
  effortLevels: (backend, model) => this.backendEffortLevels(instanceName, backend, model),
@@ -21184,7 +21360,7 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
21184
21360
  // review): only the launch-line rule applies — never the account's list or the default provider's naming pattern.
21185
21361
  if (opts.provider)
21186
21362
  return modelNameCarried(backend, model) ? { ok: true } : { ok: false, choices: [] };
21187
- const listed = this.readCliEnv(backend)?.models ?? [];
21363
+ const listed = this.webModelEnv(backend, instanceName)?.models ?? [];
21188
21364
  const choices = listed.slice(0, 24).map(o => o.id);
21189
21365
  if (!modelNameCarried(backend, model))
21190
21366
  return { ok: false, choices };
@@ -21238,19 +21414,81 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
21238
21414
  * #2072 part 3: the models a Settings field offers for `backend` — the cached catalog (an instance's own credential
21239
21415
  * profile's, when it is named and has one), claude's account catalog included. Read only: never a probe.
21240
21416
  */
21241
- modelCatalogFor(backend, instance) {
21417
+ webModelTargetIds = new WeakMap();
21418
+ webModelTargetSequence = 0;
21419
+ webModelCatalogs = new Map();
21420
+ webModelRefreshes = new Map();
21421
+ /** Resolve only trusted config; the browser never supplies a home, provider URL or credentials. */
21422
+ webModelBinding(backend, instance) {
21423
+ // Some read-only integration harnesses construct the prototype without its class initializers.
21424
+ this.webModelTargetIds ??= new WeakMap();
21425
+ this.webModelTargetSequence ??= 0;
21426
+ this.webModelCatalogs ??= new Map();
21427
+ this.webModelRefreshes ??= new Map();
21242
21428
  if (!KNOWN_BACKENDS.includes(backend) || backend === "mock")
21243
- return [];
21244
- const own = instance && Object.prototype.hasOwnProperty.call(this.fleetConfig?.instances ?? {}, instance) ? instance
21245
- : instance && this.classicChannels?.getChannelIdByInstance(instance) !== undefined ? instance : null;
21246
- const env = this.readCliEnv(backend, this.catalogProfile(backend, own));
21247
- const seen = new Set(), out = [];
21248
- for (const m of [...(env?.models ?? []), ...(env?.apiModels ?? [])])
21249
- if (!seen.has(m.id)) {
21250
- seen.add(m.id);
21251
- out.push(m);
21252
- }
21253
- return out;
21429
+ return null;
21430
+ const instances = this.fleetConfig?.instances ?? {};
21431
+ const own = instance && Object.hasOwn(instances, instance) ? instances[instance] : null;
21432
+ const classic = instance && !own ? this.classicChannels?.getAll().find(c => c.instanceName === instance) : null;
21433
+ if (instance && !own && !classic)
21434
+ return null;
21435
+ const options = { ...this.fleetConfig?.defaults?.backend_options?.[backend], ...(own?.backend_options?.[backend] ?? (instance ? this.classicChannels?.getBackendOptionsByInstance(instance)?.[backend] : undefined)) };
21436
+ const profile = typeof options.credential_profile === "string" ? options.credential_profile : null;
21437
+ const instanceDir = instance ? this.getInstanceDir(instance) : join(getAgendHome(), "cli-env");
21438
+ const config = structuredClone({ workingDirectory: own?.working_directory ?? "", instanceDir,
21439
+ instanceName: instance ?? `probe-${backend}`, mcpServers: {}, backendOptions: options,
21440
+ ...(profile ? { credentialStoreHome: credentialProfileStoreHome(getAgendHome(), backend, profile) } : {}) });
21441
+ const target = own ?? classic;
21442
+ if (target && !this.webModelTargetIds.has(target))
21443
+ this.webModelTargetIds.set(target, ++this.webModelTargetSequence);
21444
+ const targetId = target ? this.webModelTargetIds.get(target) : 0;
21445
+ const key = JSON.stringify({ backend, instance, config, targetId, target: own ?? classic, defaults: this.fleetConfig?.defaults });
21446
+ return { key, own, classic, profile, config, scoped: !!options.provider || (!!profile && backend !== "claude-code") };
21447
+ }
21448
+ webModelEnv(backend, instance) {
21449
+ const binding = this.webModelBinding(backend, instance);
21450
+ if (!binding)
21451
+ return null;
21452
+ const disk = binding.scoped ? null : this.readCliEnv(backend, binding.profile);
21453
+ const hit = this.webModelCatalogs.get(binding.key);
21454
+ if (hit && Date.now() - hit.probedAt < CLI_ENV_TTL_MS && (!disk || hit.probedAt >= disk.probedAt))
21455
+ return hit;
21456
+ return disk;
21457
+ }
21458
+ modelCatalogFor(backend, instance) {
21459
+ const env = this.webModelEnv(backend, instance);
21460
+ const seen = new Set();
21461
+ return [...(env?.models ?? []), ...(env?.apiModels ?? [])].filter(m => !seen.has(m.id) && !!seen.add(m.id));
21462
+ }
21463
+ /** Explicit, bounded vendor rediscovery. Never publish an answer under a different account/config/instance. */
21464
+ async refreshModelCatalogFor(backend, instance) {
21465
+ const binding = this.webModelBinding(backend, instance);
21466
+ if (!binding || this.shuttingDown)
21467
+ return { models: [], refreshed: false };
21468
+ const pending = this.webModelRefreshes.get(binding.key);
21469
+ if (pending)
21470
+ return pending;
21471
+ const epoch = this.cliEnvProbeEpoch;
21472
+ const current = () => {
21473
+ const next = this.webModelBinding(backend, instance);
21474
+ return !this.shuttingDown && epoch === this.cliEnvProbeEpoch && next?.key === binding.key && next.own === binding.own && next.classic === binding.classic;
21475
+ };
21476
+ const work = this.runBackendProbeWorker(binding.scoped && !binding.profile ? `instance:${backend}:${binding.config.instanceDir}` : `global:${backend}${binding.profile ? `@${binding.profile}` : ""}`, {
21477
+ mode: "env", backend, instanceDir: binding.config.instanceDir, config: binding.config, refreshVendorCatalog: true,
21478
+ }).then(result => {
21479
+ if (!current())
21480
+ return { models: [], refreshed: false };
21481
+ // Raw failure/empty discovery never masquerades as a successful refresh of the retained catalog.
21482
+ if (!result || Array.isArray(result) || (!Array.isArray(result.models) || !result.models.length || result.catalogRefreshFailed))
21483
+ return { models: this.modelCatalogFor(backend, instance), refreshed: false };
21484
+ if (this.webModelCatalogs.size >= 64)
21485
+ this.webModelCatalogs.delete(this.webModelCatalogs.keys().next().value);
21486
+ this.webModelCatalogs.set(binding.key, { ...result, backend, probedAt: Date.now() });
21487
+ return { models: this.modelCatalogFor(backend, instance), refreshed: true };
21488
+ }).finally(() => { if (this.webModelRefreshes.get(binding.key) === work)
21489
+ this.webModelRefreshes.delete(binding.key); });
21490
+ this.webModelRefreshes.set(binding.key, work);
21491
+ return work;
21254
21492
  }
21255
21493
  /**
21256
21494
  * #2072 (#2078 review): the snapshot as THIS instance would see it. Its sign-in on a backend is its own credential
@@ -21300,6 +21538,8 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
21300
21538
  }
21301
21539
  /** The models `/model` would offer on a backend: the cached CLI env, else (live) a bounded probe. Never throws. */
21302
21540
  async backendModelOptions(backend, opts) {
21541
+ if (!opts.live && opts.instance)
21542
+ return this.modelCatalogFor(backend, opts.instance);
21303
21543
  const cached = this.readCliEnv(backend);
21304
21544
  if (!opts.live || (cached?.models.length && !this.cliEnvNeedsRefresh(cached)))
21305
21545
  return cached?.models ?? [];
@@ -21792,7 +22032,7 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
21792
22032
  execution?.assert();
21793
22033
  if (this.daemons.has(instanceName))
21794
22034
  return;
21795
- const workDir = join(getAgendHome(), "workspaces", instanceName);
22035
+ const workDir = this.classicWorkspaceDir(instanceName);
21796
22036
  ensureWorkspaceGit(workDir);
21797
22037
  const classicIdentity = this.classicChannels?.getAll().find(ch => ch.instanceName === instanceName);
21798
22038
  const toolProgress = classicIdentity
@@ -22417,6 +22657,7 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
22417
22657
  this.agentCredentialsCache?.observePolicies();
22418
22658
  if (this.loadedFleetSource)
22419
22659
  this.getConfigHistory().accepted("fleet.yaml", this.configPath, this.loadedFleetSource);
22660
+ this.probeChangedCliEnvs(oldConfig);
22420
22661
  this.migrateOfficeStorage();
22421
22662
  this.migrateNoticeDeliveryStorage();
22422
22663
  // Classic behavior settings share the fleet defaults but are not entries
@@ -22764,7 +23005,9 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
22764
23005
  return {
22765
23006
  ok: false,
22766
23007
  status: 503,
22767
- error: "the restart rate-limit file cannot be read — remove self-restart.json from the data dir on the host, or run `agend restart` there",
23008
+ error: this.isWebOnlyFleet()
23009
+ ? "the restart rate-limit file cannot be read"
23010
+ : "the restart rate-limit file cannot be read — send /restart in General",
22768
23011
  };
22769
23012
  }
22770
23013
  return {
@@ -22794,7 +23037,7 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
22794
23037
  return {
22795
23038
  ok: false,
22796
23039
  status: 409,
22797
- error: "no chat channel is available to announce the restart — run `agend restart` on the host instead",
23040
+ error: "no chat channel is available to announce the restart",
22798
23041
  };
22799
23042
  }
22800
23043
  // Consume the row: it moves to running, which is also what lets the next
@@ -24139,47 +24382,74 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
24139
24382
  }
24140
24383
  }
24141
24384
  // ── Update check ────────────────────────────────────────────────────
24385
+ /** The running package's version (package.json next to this code). */
24386
+ runningAgendVersion() {
24387
+ // M-2738 (rig): the version THIS process runs, read when it loaded. The file on disk is the installed one: during an
24388
+ // update it is briefly missing, then the new version while the old fleet still runs (a tab would be told to reload early).
24389
+ if (!RUNNING_AGEND_VERSION)
24390
+ throw new Error("the running AgEnD version is unknown");
24391
+ return RUNNING_AGEND_VERSION;
24392
+ }
24393
+ /**
24394
+ * What the install's own channel offers: the target version and whether it came from that channel's dist-tag. Throws
24395
+ * when npm cannot be asked (the callers decide what a failed look means).
24396
+ */
24397
+ async lookUpUpdateTarget(currentVersion) {
24398
+ // Both npm lookups are async: as execSync they froze the fleet event loop for
24399
+ // up to 15s each, and on a beta build BOTH ran — 30s with no WATCHDOG ping,
24400
+ // past WatchdogSec's half-interval and enough for systemd to SIGABRT the fleet
24401
+ // for a background version check.
24402
+ const { execFile } = await import("./child-process.js");
24403
+ const { promisify } = await import("node:util");
24404
+ const execFileP = promisify(execFile);
24405
+ const npmVersion = async (spec) => {
24406
+ const { stdout } = await execFileP("npm", ["view", spec, "version"], { timeout: 15_000 });
24407
+ return stdout.toString().trim();
24408
+ };
24409
+ const latest = await npmVersion("@songsid/agend");
24410
+ let target = latest;
24411
+ let fromChannel = false;
24412
+ // The same channel rule as `agend update` (#1259): an alpha follows @alpha, any other prerelease @beta.
24413
+ const channel = installedChannel(currentVersion);
24414
+ if (channel !== "latest") {
24415
+ let pre = "";
24416
+ try {
24417
+ pre = await npmVersion(`@songsid/agend@${channel}`);
24418
+ }
24419
+ catch { /* no such tag */ }
24420
+ // #1926: a beta install hears about @beta only: beta users stay on the beta line after a stable ships, so
24421
+ // @latest is not their target. Taking the higher of the two made a same-core stable (2.2.0 over beta.16) the
24422
+ // target, which the same-core guard then dropped, so the newer beta.17 was never announced.
24423
+ target = pre;
24424
+ fromChannel = true;
24425
+ // An alpha is still told about a stable that passed its own minor (with --stable, #1259): only a stable of
24426
+ // another core that is newer than its channel's release. A same-core @latest (2.2.0 for 2.2.0-alpha.3) is not
24427
+ // taken from @latest and no longer hides a newer alpha; once the release points @alpha at it, it comes from
24428
+ // @alpha like any channel release.
24429
+ const core = (v) => v.replace(/^v/, "").split("-")[0];
24430
+ if (channel === "alpha" && latest && core(latest) !== core(currentVersion) && (!pre || this.semverGt(latest, pre))) {
24431
+ target = latest;
24432
+ fromChannel = false;
24433
+ }
24434
+ }
24435
+ return { target, fromChannel };
24436
+ }
24437
+ /** M-2738: record a look's answer for the web — the same offer the notice below would make. */
24438
+ recordUpdateCheck(currentVersion, found) {
24439
+ const offer = found ? updateOffer(currentVersion, found.target, found.fromChannel, !!found.target && this.semverGt(found.target, currentVersion)) : null;
24440
+ this.updateCheckState = { offer, checkedAt: Date.now(), failed: found === null };
24441
+ }
24142
24442
  async checkForUpdates() {
24443
+ let currentVersion;
24143
24444
  try {
24144
- // Both npm lookups are async: as execSync they froze the fleet event loop for
24145
- // up to 15s each, and on a beta build BOTH ran — 30s with no WATCHDOG ping,
24146
- // past WatchdogSec's half-interval and enough for systemd to SIGABRT the fleet
24147
- // for a background version check.
24148
- const { execFile } = await import("./child-process.js");
24149
- const { promisify } = await import("node:util");
24150
- const execFileP = promisify(execFile);
24151
- const npmVersion = async (spec) => {
24152
- const { stdout } = await execFileP("npm", ["view", spec, "version"], { timeout: 15_000 });
24153
- return stdout.toString().trim();
24154
- };
24155
- const pkgPath = join(dirname(fileURLToPath(import.meta.url)), "..", "package.json");
24156
- const currentVersion = JSON.parse(readFileSync(pkgPath, "utf-8")).version ?? "0.0.0";
24157
- const latest = await npmVersion("@songsid/agend");
24158
- let target = latest;
24159
- let fromChannel = false;
24160
- // The same channel rule as `agend update` (#1259): an alpha follows @alpha, any other prerelease @beta.
24161
- const channel = installedChannel(currentVersion);
24162
- if (channel !== "latest") {
24163
- let pre = "";
24164
- try {
24165
- pre = await npmVersion(`@songsid/agend@${channel}`);
24166
- }
24167
- catch { /* no such tag */ }
24168
- // #1926: a beta install hears about @beta only: beta users stay on the beta line after a stable ships, so
24169
- // @latest is not their target. Taking the higher of the two made a same-core stable (2.2.0 over beta.16) the
24170
- // target, which the same-core guard then dropped, so the newer beta.17 was never announced.
24171
- target = pre;
24172
- fromChannel = true;
24173
- // An alpha is still told about a stable that passed its own minor (with --stable, #1259): only a stable of
24174
- // another core that is newer than its channel's release. A same-core @latest (2.2.0 for 2.2.0-alpha.3) is not
24175
- // taken from @latest and no longer hides a newer alpha; once the release points @alpha at it, it comes from
24176
- // @alpha like any channel release.
24177
- const core = (v) => v.replace(/^v/, "").split("-")[0];
24178
- if (channel === "alpha" && latest && core(latest) !== core(currentVersion) && (!pre || this.semverGt(latest, pre))) {
24179
- target = latest;
24180
- fromChannel = false;
24181
- }
24182
- }
24445
+ currentVersion = this.runningAgendVersion();
24446
+ }
24447
+ catch {
24448
+ return;
24449
+ }
24450
+ try {
24451
+ const { target, fromChannel } = await this.lookUpUpdateTarget(currentVersion);
24452
+ this.recordUpdateCheck(currentVersion, { target, fromChannel });
24183
24453
  // Only notify when target is genuinely newer (semver), so a beta user on
24184
24454
  // 2.0.8-beta.16 is never told that stable 2.0.7 is "available".
24185
24455
  if (target && this.semverGt(target, currentVersion)) {
@@ -24196,14 +24466,122 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
24196
24466
  this.notifyInstanceTopic(generalId, t(key, `v${target}`, `v${currentVersion}`));
24197
24467
  }
24198
24468
  else if (this.webOnlyPromptPlace() && (fromChannel || updateNoticeKey(currentVersion, target))) {
24199
- // #2910 D2: a web-only fleet: a Notice, once per version (the check runs daily); installed from this computer.
24469
+ // #2910 D2: a web-only fleet: a Notice, once per version (the check runs daily). M-2738: updated from the web.
24200
24470
  const text = t("update.available_web_only", `v${target}`, `v${currentVersion}`);
24201
24471
  if (this.webNoticeStore()?.latest("update")?.text !== text)
24202
24472
  this.recordWebNotice("update", text);
24203
24473
  }
24204
24474
  }
24205
24475
  }
24206
- catch { /* silent — network issues */ }
24476
+ catch {
24477
+ this.recordUpdateCheck(currentVersion, null); /* silent — network issues */
24478
+ }
24479
+ }
24480
+ // ── M-2738: updating from the web (src/web-update.ts) ───────────────
24481
+ /** The web's update routes (web-api.ts handleWebUpdate) read and start through this. */
24482
+ get webUpdate() {
24483
+ return {
24484
+ updateState: () => {
24485
+ let current = null;
24486
+ try {
24487
+ current = this.runningAgendVersion();
24488
+ }
24489
+ catch { /* unknown: the page compares nothing */ }
24490
+ const s = this.updateCheckState;
24491
+ return { current, offer: s?.offer ?? null, checkedAt: s?.checkedAt ?? null, checkFailed: s?.failed ?? false };
24492
+ },
24493
+ checkUpdateNow: () => this.checkUpdateNow(),
24494
+ updateProgress: () => webProgressOf(readUpdateProgress(this.dataDir)),
24495
+ startWebUpdate: (key, person, stillAllowed) => this.startWebUpdateOnce(key, person, stillAllowed),
24496
+ updateLog: () => ({ text: readLogTail(updateLogPath(this.dataDir)), error: readUpdateProgress(this.dataDir)?.progress.error ?? null }),
24497
+ };
24498
+ }
24499
+ /** "Check for updates": look now, no chat notice. One a minute; a second ask while one runs waits for it. */
24500
+ async checkUpdateNow() {
24501
+ const c = this.updateCheckNow;
24502
+ if (c.running) {
24503
+ await c.running;
24504
+ return { ok: true };
24505
+ }
24506
+ if (Date.now() - c.lastAt < 60_000 && Date.now() >= c.lastAt)
24507
+ return { ok: false, status: 429, error: "checked_recently" };
24508
+ c.lastAt = Date.now();
24509
+ c.running = (async () => {
24510
+ let currentVersion;
24511
+ try {
24512
+ currentVersion = this.runningAgendVersion();
24513
+ }
24514
+ catch {
24515
+ return;
24516
+ }
24517
+ try {
24518
+ this.recordUpdateCheck(currentVersion, await this.lookUpUpdateTarget(currentVersion));
24519
+ }
24520
+ catch {
24521
+ this.recordUpdateCheck(currentVersion, null);
24522
+ }
24523
+ })();
24524
+ try {
24525
+ await c.running;
24526
+ }
24527
+ finally {
24528
+ c.running = null;
24529
+ }
24530
+ return { ok: true };
24531
+ }
24532
+ /**
24533
+ * M-2738: Update from the web — a fleet admin's session, after its own confirmation (the leader's D1). Only what the
24534
+ * last check offers as installable; the update itself is chat `/update`'s (launchInstalledUpdate). Its progress marker
24535
+ * targets no chat message (WEB_UPDATE_ADAPTER); the page reads the stages the updater writes into it.
24536
+ */
24537
+ async startWebUpdate(person, stillAllowed) {
24538
+ if (this.shuttingDown)
24539
+ return { ok: false, status: 409, error: "stopping" };
24540
+ // Synchronous from here to the claim: a second start cannot slip in between on the event loop.
24541
+ if (this.webUpdateOwned || isUpdateInProgress(this.dataDir))
24542
+ return { ok: false, status: 409, error: "update_running" };
24543
+ const offer = this.updateCheckState?.offer;
24544
+ if (!offer?.installable)
24545
+ return { ok: false, status: 409, error: "nothing_to_install" };
24546
+ const startedAt = Date.now();
24547
+ const claim = { startedAt };
24548
+ this.webUpdateOwned = claim;
24549
+ const release = () => { if (this.webUpdateOwned === claim)
24550
+ this.webUpdateOwned = null; };
24551
+ // Its progress must be recorded before anything runs: every other tab, and the next start, read it.
24552
+ if (!persistUpdateProgress(this.dataDir, webUpdateTarget(startedAt), startedAt)
24553
+ || !setUpdateProgressStage(this.dataDir, "preparing", { version: offer.version })) {
24554
+ release();
24555
+ this.logger.error("Web update refused: its progress marker could not be written");
24556
+ return { ok: false, status: 503, error: "progress_not_recorded" };
24557
+ }
24558
+ const origin = `web update by ${person}`;
24559
+ // Prism #3505 P2-3: the asking session must still be current and an admin's when the updater is launched.
24560
+ void this.launchInstalledUpdate(origin, () => !this.shuttingDown && stillAllowed()).then(child => {
24561
+ if (!child) {
24562
+ release();
24563
+ return;
24564
+ }
24565
+ child.once("exit", release);
24566
+ child.once("error", release);
24567
+ }, err => {
24568
+ release();
24569
+ this.logger.error({ err }, "Web update launch failed");
24570
+ this.failUpdateProgress(t("update.failure.launch"));
24571
+ });
24572
+ return { ok: true };
24573
+ }
24574
+ /** M-2738: a web start's answer for its key, the same on a retry (at most 32 kept). */
24575
+ startWebUpdateOnce(key, person, stillAllowed) {
24576
+ // Prism #3505 P3: reserved before anything is awaited — a concurrent request with the same key shares this answer.
24577
+ const known = this.webUpdateStarts.get(key);
24578
+ if (known)
24579
+ return known;
24580
+ const answer = this.startWebUpdate(person, stillAllowed);
24581
+ this.webUpdateStarts.set(key, answer);
24582
+ while (this.webUpdateStarts.size > 32)
24583
+ this.webUpdateStarts.delete(this.webUpdateStarts.keys().next().value);
24584
+ return answer;
24207
24585
  }
24208
24586
  /**
24209
24587
  * Semver "a > b". Compares major.minor.patch numerically; a version without a
@@ -24514,7 +24892,7 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
24514
24892
  if (decision.reason === "no-credential" && req.method === "GET"
24515
24893
  && String(req.headers.accept ?? "").includes("text/html")
24516
24894
  && isWebPageNavigation(requestPath)) {
24517
- serveSigninPage(res, 401, { webOnly: this.isWebOnlyFleet() });
24895
+ serveSigninPage(res, 401, { webOnly: this.signinWithoutChat() });
24518
24896
  return;
24519
24897
  }
24520
24898
  res.writeHead(decision.status);