@songsid/agend 2.3.5-beta.2 → 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 (135) hide show
  1. package/dist/agent-cli-instructions.md +2 -2
  2. package/dist/auth-api.d.ts +2 -0
  3. package/dist/auth-api.js +5 -1
  4. package/dist/auth-api.js.map +1 -1
  5. package/dist/backend/claude-code.d.ts +2 -0
  6. package/dist/backend/claude-code.js +16 -3
  7. package/dist/backend/claude-code.js.map +1 -1
  8. package/dist/backend/cli-env-probe.js +6 -2
  9. package/dist/backend/cli-env-probe.js.map +1 -1
  10. package/dist/backend/codex.d.ts +5 -3
  11. package/dist/backend/codex.js +31 -13
  12. package/dist/backend/codex.js.map +1 -1
  13. package/dist/backend/kiro.js +1 -1
  14. package/dist/backend/kiro.js.map +1 -1
  15. package/dist/backend/types.d.ts +5 -1
  16. package/dist/backend/types.js.map +1 -1
  17. package/dist/bundled-tmux-guard.d.ts +4 -0
  18. package/dist/bundled-tmux-guard.js +7 -0
  19. package/dist/bundled-tmux-guard.js.map +1 -1
  20. package/dist/cache-service.d.ts +6 -0
  21. package/dist/cache-service.js +105 -0
  22. package/dist/cache-service.js.map +1 -1
  23. package/dist/channel/mcp-tools.js +2 -2
  24. package/dist/channel/mcp-tools.js.map +1 -1
  25. package/dist/daemon.d.ts +3 -0
  26. package/dist/daemon.js +17 -2
  27. package/dist/daemon.js.map +1 -1
  28. package/dist/fleet-manager.d.ts +71 -0
  29. package/dist/fleet-manager.js +393 -92
  30. package/dist/fleet-manager.js.map +1 -1
  31. package/dist/fleet-process-handlers.d.ts +1 -1
  32. package/dist/fleet-process-handlers.js +3 -2
  33. package/dist/fleet-process-handlers.js.map +1 -1
  34. package/dist/general-knowledge/skills/concepts/SKILL.md +11 -12
  35. package/dist/general-knowledge/skills/cross-instance-messaging/SKILL.md +9 -1
  36. package/dist/general-knowledge/skills/fleet-config/SKILL.md +12 -0
  37. package/dist/general-knowledge/skills/fleet-health/SKILL.md +1 -1
  38. package/dist/general-knowledge/skills/instance-lifecycle/SKILL.md +4 -0
  39. package/dist/general-knowledge/skills/web-dashboard/SKILL.md +16 -11
  40. package/dist/instance-lifecycle.d.ts +1 -1
  41. package/dist/instance-lifecycle.js +16 -1
  42. package/dist/instance-lifecycle.js.map +1 -1
  43. package/dist/instructions.js +29 -6
  44. package/dist/instructions.js.map +1 -1
  45. package/dist/kiro-history-scan.d.ts +26 -0
  46. package/dist/kiro-history-scan.js +141 -0
  47. package/dist/kiro-history-scan.js.map +1 -0
  48. package/dist/kiro-history-worker.d.ts +1 -0
  49. package/dist/kiro-history-worker.js +9 -0
  50. package/dist/kiro-history-worker.js.map +1 -0
  51. package/dist/kiro-history.d.ts +20 -0
  52. package/dist/kiro-history.js +96 -0
  53. package/dist/kiro-history.js.map +1 -0
  54. package/dist/kiro-usage-run.d.ts +2 -0
  55. package/dist/kiro-usage-run.js +4 -1
  56. package/dist/kiro-usage-run.js.map +1 -1
  57. package/dist/locale.js +67 -67
  58. package/dist/locale.js.map +1 -1
  59. package/dist/login-flows.d.ts +4 -0
  60. package/dist/login-flows.js +8 -4
  61. package/dist/login-flows.js.map +1 -1
  62. package/dist/office-levels.d.ts +4 -3
  63. package/dist/office-levels.js +3 -3
  64. package/dist/office-levels.js.map +1 -1
  65. package/dist/outbound-handlers.js +32 -12
  66. package/dist/outbound-handlers.js.map +1 -1
  67. package/dist/outbound-schemas.d.ts +14 -0
  68. package/dist/outbound-schemas.js +4 -0
  69. package/dist/outbound-schemas.js.map +1 -1
  70. package/dist/setup-i18n.js +4 -4
  71. package/dist/setup-i18n.js.map +1 -1
  72. package/dist/subagent-records.d.ts +42 -0
  73. package/dist/subagent-records.js +159 -0
  74. package/dist/subagent-records.js.map +1 -0
  75. package/dist/subagent-service.d.ts +27 -0
  76. package/dist/subagent-service.js +199 -0
  77. package/dist/subagent-service.js.map +1 -0
  78. package/dist/tool-permissions.d.ts +2 -3
  79. package/dist/tool-permissions.js +3 -3
  80. package/dist/tool-permissions.js.map +1 -1
  81. package/dist/ui/backend-signin.js +62 -62
  82. package/dist/ui/chat-commands.js +7 -0
  83. package/dist/ui/chat-store.js +9 -4
  84. package/dist/ui/chat-strings.js +18 -18
  85. package/dist/ui/fleet-cache.js +3 -3
  86. package/dist/ui/fleet-canvas.js +2 -2
  87. package/dist/ui/fleet-office-editor.js +1 -1
  88. package/dist/ui/fleet-office.js +1 -1
  89. package/dist/ui/fleet-org.js +2 -2
  90. package/dist/ui/fleet-task-card.js +1 -1
  91. package/dist/ui/fleet-task-common.js +7 -7
  92. package/dist/ui/model-picker.js +64 -0
  93. package/dist/ui/panel-chat.js +47 -16
  94. package/dist/ui/panel-fleet.js +8 -8
  95. package/dist/ui/panel-needs.js +3 -3
  96. package/dist/ui/panel-settings.js +16 -6
  97. package/dist/ui/settings-catalog.js +19 -4
  98. package/dist/ui/settings-dialogs.js +25 -8
  99. package/dist/ui/settings-guests.js +1 -1
  100. package/dist/ui/settings-registry.js +3 -1
  101. package/dist/ui/settings-strings.js +30 -26
  102. package/dist/ui/settings-update.js +69 -0
  103. package/dist/ui/shared/app-i18n.js +8 -4
  104. package/dist/ui/shared/app-shell.js +2 -0
  105. package/dist/ui/shared/app-update.js +215 -0
  106. package/dist/ui/shared/app.css +48 -2
  107. package/dist/ui/shared/instance-nav.js +1 -1
  108. package/dist/ui/shared/model-picker.css +21 -0
  109. package/dist/ui/shared/setup-host-text.js +4 -4
  110. package/dist/ui/shared/signin.js +32 -16
  111. package/dist/ui/shared/subagent-row.css +15 -0
  112. package/dist/ui/shared/view-strings.js +17 -17
  113. package/dist/ui/structured-signin.js +26 -26
  114. package/dist/ui/subagent-row.js +64 -0
  115. package/dist/ui/web-terminal/terminal.js +9 -9
  116. package/dist/update-marker.d.ts +2 -2
  117. package/dist/update-marker.js +4 -3
  118. package/dist/update-marker.js.map +1 -1
  119. package/dist/usage/providers.js +2 -2
  120. package/dist/usage/providers.js.map +1 -1
  121. package/dist/usage-rollup.d.ts +3 -0
  122. package/dist/usage-rollup.js +2 -0
  123. package/dist/usage-rollup.js.map +1 -1
  124. package/dist/web-api.d.ts +14 -0
  125. package/dist/web-api.js +216 -2
  126. package/dist/web-api.js.map +1 -1
  127. package/dist/web-auth.js +2 -1
  128. package/dist/web-auth.js.map +1 -1
  129. package/dist/web-commands.d.ts +8 -0
  130. package/dist/web-commands.js +6 -0
  131. package/dist/web-commands.js.map +1 -1
  132. package/dist/web-update.d.ts +77 -0
  133. package/dist/web-update.js +102 -0
  134. package/dist/web-update.js.map +1 -0
  135. package/package.json +2 -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";
@@ -1041,6 +1043,18 @@ export class FleetManager {
1041
1043
  previewInputs = "";
1042
1044
  healthPortRetried = false;
1043
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;
1044
1058
  updateProgressTimer = null;
1045
1059
  updateProgressEditRunning = false;
1046
1060
  lastUpdateProgressText = null;
@@ -3234,7 +3248,7 @@ export class FleetManager {
3234
3248
  if (current && !sameUpdateMarker(current, bootUpdateMarker))
3235
3249
  return;
3236
3250
  const leftover = readUpdateProgress(this.dataDir)?.progress;
3237
- if (leftover?.cleanup === "pending" && leftover.stage !== "failed" && leftover.stage !== "complete")
3251
+ if (leftover?.cleanup === "pending" && !isWebUpdateTarget(leftover.target) && leftover.stage !== "failed" && leftover.stage !== "complete")
3238
3252
  return;
3239
3253
  clearUpdateMarker(this.dataDir);
3240
3254
  }
@@ -3591,25 +3605,32 @@ export class FleetManager {
3591
3605
  const chatId = String(this.getChannelConfig(adapterId)?.group_id ?? data.channelId);
3592
3606
  this.beginUpdateProgress(adapter, chatId, data.channelId, messageId);
3593
3607
  }
3594
- const { spawn } = await import("./child-process.js");
3595
3608
  // Plain `agend update`: the CLI picks the channel from the version it is about to replace (a beta install
3596
3609
  // stays on beta). Deciding here, from the package.json next to THIS code, read a source checkout's 1.22.0 as
3597
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");
3598
3620
  const installed = await resolveInstalledAgend();
3599
3621
  if (!installed.ok) {
3600
3622
  this.failUpdateProgress(`${t("update.failure.shell")} ${t("update.failure.installed", installed.reason)}`);
3601
- return;
3623
+ return null;
3602
3624
  }
3603
- const origin = `slash /update by ${adapterId}:${data.userId}`;
3604
3625
  recordInternalRequest(this.dataDir, "update", origin);
3605
3626
  const launch = await resolveUpdateLaunch(installed.agend, undefined, installed.npmDir);
3606
3627
  if (!launch.ok) {
3607
3628
  this.failUpdateProgress(`${t("update.failure.shell")} ${t("update.failure.independent", launch.reason)}`);
3608
- return;
3629
+ return null;
3609
3630
  }
3610
- if (this.fleetAdminGate(data.userId, adapterId) !== "ok" || this.shuttingDown) {
3631
+ if (!stillAllowed()) {
3611
3632
  this.failUpdateProgress(t("not_authorized"));
3612
- return;
3633
+ return null;
3613
3634
  }
3614
3635
  const logPath = updateLogPath(this.dataDir);
3615
3636
  const ts = new Date().toISOString();
@@ -3621,6 +3642,7 @@ export class FleetManager {
3621
3642
  closeSync(logFd.fd); // parent closes its copy; the child's fd stays open
3622
3643
  watchUpdateLaunch(child, message => this.failUpdateProgress(message), logFd ? logPath : undefined, logFd?.offset, installed.agend);
3623
3644
  child.unref();
3645
+ return child;
3624
3646
  }
3625
3647
  async handleProfileSlash(data, adapterId) {
3626
3648
  const route = this.routing.resolve(data.channelId);
@@ -4128,6 +4150,8 @@ export class FleetManager {
4128
4150
  }
4129
4151
  /** #1218: GET /ui/steps — an instance's steps, read on demand (null: no such instance). */
4130
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); }
4131
4155
  /**
4132
4156
  * #1218: where an instance's steps are read from, resolved only when its Log asks: the transcript its daemon follows
4133
4157
  * now; for claude-code, also the path its statusline last named (so a stopped instance's Log still shows its last
@@ -8049,6 +8073,9 @@ export class FleetManager {
8049
8073
  updateCleanupAtCompletion(pending, operation) {
8050
8074
  if (!pending || operation !== "update")
8051
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;
8052
8079
  const receipt = updateReceiptOf(pending);
8053
8080
  if (!receipt)
8054
8081
  return null;
@@ -8312,13 +8339,10 @@ export class FleetManager {
8312
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
8313
8340
  // main → alpha sync must keep alpha's side of this block, never both.
8314
8341
  {
8315
- const { newerTmuxServer, realGuardDeps, guardMessage } = await import("./bundled-tmux-guard.js");
8342
+ const { newerTmuxServer, realGuardDeps, BundledTmuxStartupError } = await import("./bundled-tmux-guard.js");
8316
8343
  const hit = await newerTmuxServer(realGuardDeps(getAgendHome(), isDefaultAgendHome(), getSocket()));
8317
- if (hit) {
8318
- const message = guardMessage(hit);
8319
- this.logger.error({ socket: hit.socket, confirmed: hit.confirmed }, message);
8320
- throw new Error(message);
8321
- }
8344
+ if (hit)
8345
+ throw new BundledTmuxStartupError(hit);
8322
8346
  }
8323
8347
  await TmuxManager.ensureSession(getTmuxSession());
8324
8348
  this.tmuxSessionEnsured = true;
@@ -8386,6 +8410,8 @@ export class FleetManager {
8386
8410
  if (ch.adapterId)
8387
8411
  this.instanceWorldBinding.set(ch.instanceName, ch.adapterId);
8388
8412
  }
8413
+ // #3526: catalogs belong to the fleet, including a fleet with no chat adapter.
8414
+ this.probeCliEnvs();
8389
8415
  // #1565: the web chat as it was before this process — the configured instances' only (fleet.yaml and ClassicBot
8390
8416
  // rooms), before the dashboard serves anything; from now on every change is written back (off the loop).
8391
8417
  this.restoreWebChat(fleet);
@@ -8621,7 +8647,8 @@ export class FleetManager {
8621
8647
  this.reportClassicUnrecoverableIds();
8622
8648
  })();
8623
8649
  progressStart = adapterStartup.then(() => {
8624
- 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)) {
8625
8652
  const saved = pendingUpdateProgress.progress.target;
8626
8653
  const target = {
8627
8654
  adapter: this.adapters.get(saved.adapterId),
@@ -9548,9 +9575,6 @@ export class FleetManager {
9548
9575
  }, this.logger, "adapter.slash_command"));
9549
9576
  // This adapter's own Telegram menus — each Telegram adapter registers its own when it starts (#1191).
9550
9577
  this.registerTelegramCommandsFor(channelConfig);
9551
- // Background-probe each backend's CLI env (version/models) → cli-env cache.
9552
- // Non-blocking: /model & status views read the cache; never delays startup.
9553
- this.probeCliEnvs();
9554
9578
  adapter.on("started", safeHandler((username, userId) => {
9555
9579
  if (!isCurrentAdapter())
9556
9580
  return;
@@ -11501,6 +11525,13 @@ export class FleetManager {
11501
11525
  isWebOnlyFleet() {
11502
11526
  return isWebOnlyFleetConfig(this.fleetConfig);
11503
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
+ }
11504
11535
  /** On a fleet with no chat platform, the dashboard is where an instance-health prompt is posted (#1307 item 6). */
11505
11536
  webOnlyPromptPlace() {
11506
11537
  return this.worlds.size === 0 && this.isWebOnlyFleet() ? { adapter: WEB_ONLY_PROMPT_SINK, adapterId: "web", chatId: "web" } : null;
@@ -12345,16 +12376,38 @@ export class FleetManager {
12345
12376
  return null;
12346
12377
  return d.team && instanceTeams(this.fleetConfig?.teams, instance).includes(d.team) ? null : `Decision "${id}" not found`;
12347
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
+ }
12348
12397
  async handleDecisionCrudHttp(instance, op, args) {
12349
12398
  if (!this.scheduler)
12350
12399
  return { error: "Scheduler not available" };
12351
12400
  const db = this.scheduler.db;
12352
- 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 ?? "";
12353
12404
  const asStr = (v) => typeof v === "string" ? v : undefined;
12354
12405
  const asNum = (v) => typeof v === "number" ? v : undefined;
12355
12406
  const asStrArr = (v) => Array.isArray(v) && v.every(x => typeof x === "string") ? v : undefined;
12356
12407
  switch (op) {
12357
12408
  case "post": {
12409
+ if (root === null)
12410
+ return unknownRoot;
12358
12411
  const title = asStr(args.title);
12359
12412
  const content = asStr(args.content);
12360
12413
  if (!title || !content)
@@ -12389,6 +12442,8 @@ export class FleetManager {
12389
12442
  case "get":
12390
12443
  if (op === "get" && !asStr(args.id)?.trim())
12391
12444
  return { error: "id is required" };
12445
+ if (root === null)
12446
+ return unknownRoot;
12392
12447
  return decisionListAnswer(db.listDecisions(projectRoot, {
12393
12448
  includeArchived: args.includeArchived === true || args.include_archived === true,
12394
12449
  tags: asStrArr(args.tags),
@@ -13159,7 +13214,9 @@ export class FleetManager {
13159
13214
  delete current[key];
13160
13215
  Object.assign(current, resolved);
13161
13216
  }
13217
+ const previousCatalogConfig = this.savedFleetConfigSnapshot;
13162
13218
  this.savedFleetConfigSnapshot = structuredClone(this.fleetConfig);
13219
+ this.probeChangedCliEnvs(previousCatalogConfig);
13163
13220
  this.agentCredentialsCache?.observePolicies();
13164
13221
  this.refreshSavedDashboardPermissions();
13165
13222
  this.logger.info({ path: this.configPath, strippedDefaults: redundantPaths.length }, "Saved fleet config (lossless patch)");
@@ -16544,13 +16601,13 @@ export class FleetManager {
16544
16601
  ...(opts.guest ? { webGuest: true } : {}), // #2855: a guest's /steer or /btw reaches the agent as a guest's
16545
16602
  };
16546
16603
  };
16547
- const choicesFromCache = (instance) => {
16604
+ const choicesFromCache = (instance, more = false) => {
16548
16605
  const backend = this.backendNameForInstance(instance);
16549
- const cached = this.readCliEnv(backend, this.catalogProfile(backend, instance)); // the cached catalog only: never a probe here
16550
- if (!cached?.models.length)
16551
- return null;
16606
+ const env = this.webModelEnv(backend, instance);
16552
16607
  const current = this.resolveInstanceModel(instance).model;
16553
- 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"] };
16554
16611
  };
16555
16612
  return runWebCommand({
16556
16613
  scope: (instance) => this.webCommandScope(instance),
@@ -16574,6 +16631,31 @@ export class FleetManager {
16574
16631
  },
16575
16632
  applyModel: (instance, name) => this.applyModel(instance, name),
16576
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
+ },
16577
16659
  applyEffort: (instance, level) => this.applyEffort(instance, level),
16578
16660
  effortChoices: (instance) => {
16579
16661
  const levels = this.effortLevelsFor(instance);
@@ -16587,12 +16669,12 @@ export class FleetManager {
16587
16669
  if (refusal)
16588
16670
  return { error: refusal };
16589
16671
  // The cached model lists only, as the web's /model: never a live probe on this path.
16590
- 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));
16591
16673
  if (step.kind === "refuse")
16592
16674
  return step.noop ? { text: step.text } : { error: step.text };
16593
16675
  if (step.kind === "choose") {
16594
16676
  const id = (token) => joinBackendArgs([...step.args, token]);
16595
- 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 => {
16596
16678
  // #2233: the web offers Sign in beside it, so its reason is no longer "use /login".
16597
16679
  // Not over the public link: Sign in is refused there, so the choice keeps its "(use /login)" (#2262 review).
16598
16680
  const signIn = c.signIn && !stepOpts?.publicLink && dashboardSignInSupported(c.signIn) ? c.signIn : null;
@@ -19964,7 +20046,7 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
19964
20046
  /** #1806: null on a switch INTO claude-code — the configured model then belongs to the backend being left. */
19965
20047
  configured = this.fleetConfig?.instances[instanceName]?.model ?? this.fleetConfig?.defaults?.model) {
19966
20048
  const aliases = ["default", "sonnet", "opus", "haiku", "opusplan", "Fable"];
19967
- 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);
19968
20050
  const lower = model.trim().toLowerCase();
19969
20051
  const bare = lower.replace(/\[1m\]$/, "");
19970
20052
  const known = aliases.some(a => a.toLowerCase() === bare)
@@ -20107,6 +20189,8 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
20107
20189
  this.pendingCliEnvProbes.clear();
20108
20190
  this.pendingVendorCliEnvProbes.clear();
20109
20191
  this.pendingInstanceModelProbes.clear();
20192
+ this.webModelRefreshes.clear();
20193
+ this.webModelCatalogs.clear();
20110
20194
  }
20111
20195
  runBackendProbeWorker(key, input) {
20112
20196
  if (this.shuttingDown)
@@ -20278,18 +20362,35 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
20278
20362
  // indefinitely — each is wrapped by CLI_ENV_PROBE_DEADLINE_MS.
20279
20363
  for (const b of backends)
20280
20364
  void this.probeBackendBounded(b);
20281
- // #2072: each Claude credential profile in use has its own account catalog. Only fleet.yaml's agents are walked
20282
- // here; a ClassicBot room on a profile is probed on its first /model (catalogProfile knows rooms too).
20283
- 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
+ };
20284
20376
  for (const name of Object.keys(this.fleetConfig?.instances ?? {})) {
20285
- 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)))
20286
20382
  continue;
20287
- const profile = this.catalogProfile("claude-code", name);
20288
- if (profile)
20289
- profiles.add(profile);
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)))
20388
+ continue;
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"));
20290
20393
  }
20291
- for (const profile of profiles)
20292
- void this.probeBackendBounded("claude-code", { profile });
20293
20394
  }
20294
20395
  /** Best-effort model list for `/model`: cached CLI env first, else live probe. Never throws. */
20295
20396
  async getModelOptions(instanceName, refresh = false, onLiveProbe) {
@@ -21204,7 +21305,7 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
21204
21305
  currentBackend: (name) => this.backendNameForInstance(name),
21205
21306
  currentDisplay: (name) => `${this.backendNameForInstance(name)} · ${this.resolveInstanceModel(name).display}`,
21206
21307
  availability: () => this.backendAvailabilityFor(instanceName),
21207
- models: (backend) => this.backendModelOptions(backend, opts),
21308
+ models: (backend) => this.backendModelOptions(backend, { ...opts, instance: instanceName }),
21208
21309
  // #1808: the same rule update_instance_config's switch applies (backendModelVerdict).
21209
21310
  modelKnown: (backend, model) => this.backendModelVerdict(instanceName, backend, model).ok,
21210
21311
  effortLevels: (backend, model) => this.backendEffortLevels(instanceName, backend, model),
@@ -21259,7 +21360,7 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
21259
21360
  // review): only the launch-line rule applies — never the account's list or the default provider's naming pattern.
21260
21361
  if (opts.provider)
21261
21362
  return modelNameCarried(backend, model) ? { ok: true } : { ok: false, choices: [] };
21262
- const listed = this.readCliEnv(backend)?.models ?? [];
21363
+ const listed = this.webModelEnv(backend, instanceName)?.models ?? [];
21263
21364
  const choices = listed.slice(0, 24).map(o => o.id);
21264
21365
  if (!modelNameCarried(backend, model))
21265
21366
  return { ok: false, choices };
@@ -21313,19 +21414,81 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
21313
21414
  * #2072 part 3: the models a Settings field offers for `backend` — the cached catalog (an instance's own credential
21314
21415
  * profile's, when it is named and has one), claude's account catalog included. Read only: never a probe.
21315
21416
  */
21316
- 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();
21317
21428
  if (!KNOWN_BACKENDS.includes(backend) || backend === "mock")
21318
- return [];
21319
- const own = instance && Object.prototype.hasOwnProperty.call(this.fleetConfig?.instances ?? {}, instance) ? instance
21320
- : instance && this.classicChannels?.getChannelIdByInstance(instance) !== undefined ? instance : null;
21321
- const env = this.readCliEnv(backend, this.catalogProfile(backend, own));
21322
- const seen = new Set(), out = [];
21323
- for (const m of [...(env?.models ?? []), ...(env?.apiModels ?? [])])
21324
- if (!seen.has(m.id)) {
21325
- seen.add(m.id);
21326
- out.push(m);
21327
- }
21328
- 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;
21329
21492
  }
21330
21493
  /**
21331
21494
  * #2072 (#2078 review): the snapshot as THIS instance would see it. Its sign-in on a backend is its own credential
@@ -21375,6 +21538,8 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
21375
21538
  }
21376
21539
  /** The models `/model` would offer on a backend: the cached CLI env, else (live) a bounded probe. Never throws. */
21377
21540
  async backendModelOptions(backend, opts) {
21541
+ if (!opts.live && opts.instance)
21542
+ return this.modelCatalogFor(backend, opts.instance);
21378
21543
  const cached = this.readCliEnv(backend);
21379
21544
  if (!opts.live || (cached?.models.length && !this.cliEnvNeedsRefresh(cached)))
21380
21545
  return cached?.models ?? [];
@@ -21867,7 +22032,7 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
21867
22032
  execution?.assert();
21868
22033
  if (this.daemons.has(instanceName))
21869
22034
  return;
21870
- const workDir = join(getAgendHome(), "workspaces", instanceName);
22035
+ const workDir = this.classicWorkspaceDir(instanceName);
21871
22036
  ensureWorkspaceGit(workDir);
21872
22037
  const classicIdentity = this.classicChannels?.getAll().find(ch => ch.instanceName === instanceName);
21873
22038
  const toolProgress = classicIdentity
@@ -22492,6 +22657,7 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
22492
22657
  this.agentCredentialsCache?.observePolicies();
22493
22658
  if (this.loadedFleetSource)
22494
22659
  this.getConfigHistory().accepted("fleet.yaml", this.configPath, this.loadedFleetSource);
22660
+ this.probeChangedCliEnvs(oldConfig);
22495
22661
  this.migrateOfficeStorage();
22496
22662
  this.migrateNoticeDeliveryStorage();
22497
22663
  // Classic behavior settings share the fleet defaults but are not entries
@@ -24216,47 +24382,74 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
24216
24382
  }
24217
24383
  }
24218
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
+ }
24219
24442
  async checkForUpdates() {
24443
+ let currentVersion;
24220
24444
  try {
24221
- // Both npm lookups are async: as execSync they froze the fleet event loop for
24222
- // up to 15s each, and on a beta build BOTH ran — 30s with no WATCHDOG ping,
24223
- // past WatchdogSec's half-interval and enough for systemd to SIGABRT the fleet
24224
- // for a background version check.
24225
- const { execFile } = await import("./child-process.js");
24226
- const { promisify } = await import("node:util");
24227
- const execFileP = promisify(execFile);
24228
- const npmVersion = async (spec) => {
24229
- const { stdout } = await execFileP("npm", ["view", spec, "version"], { timeout: 15_000 });
24230
- return stdout.toString().trim();
24231
- };
24232
- const pkgPath = join(dirname(fileURLToPath(import.meta.url)), "..", "package.json");
24233
- const currentVersion = JSON.parse(readFileSync(pkgPath, "utf-8")).version ?? "0.0.0";
24234
- const latest = await npmVersion("@songsid/agend");
24235
- let target = latest;
24236
- let fromChannel = false;
24237
- // The same channel rule as `agend update` (#1259): an alpha follows @alpha, any other prerelease @beta.
24238
- const channel = installedChannel(currentVersion);
24239
- if (channel !== "latest") {
24240
- let pre = "";
24241
- try {
24242
- pre = await npmVersion(`@songsid/agend@${channel}`);
24243
- }
24244
- catch { /* no such tag */ }
24245
- // #1926: a beta install hears about @beta only: beta users stay on the beta line after a stable ships, so
24246
- // @latest is not their target. Taking the higher of the two made a same-core stable (2.2.0 over beta.16) the
24247
- // target, which the same-core guard then dropped, so the newer beta.17 was never announced.
24248
- target = pre;
24249
- fromChannel = true;
24250
- // An alpha is still told about a stable that passed its own minor (with --stable, #1259): only a stable of
24251
- // 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
24252
- // taken from @latest and no longer hides a newer alpha; once the release points @alpha at it, it comes from
24253
- // @alpha like any channel release.
24254
- const core = (v) => v.replace(/^v/, "").split("-")[0];
24255
- if (channel === "alpha" && latest && core(latest) !== core(currentVersion) && (!pre || this.semverGt(latest, pre))) {
24256
- target = latest;
24257
- fromChannel = false;
24258
- }
24259
- }
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 });
24260
24453
  // Only notify when target is genuinely newer (semver), so a beta user on
24261
24454
  // 2.0.8-beta.16 is never told that stable 2.0.7 is "available".
24262
24455
  if (target && this.semverGt(target, currentVersion)) {
@@ -24273,14 +24466,122 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
24273
24466
  this.notifyInstanceTopic(generalId, t(key, `v${target}`, `v${currentVersion}`));
24274
24467
  }
24275
24468
  else if (this.webOnlyPromptPlace() && (fromChannel || updateNoticeKey(currentVersion, target))) {
24276
- // #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.
24277
24470
  const text = t("update.available_web_only", `v${target}`, `v${currentVersion}`);
24278
24471
  if (this.webNoticeStore()?.latest("update")?.text !== text)
24279
24472
  this.recordWebNotice("update", text);
24280
24473
  }
24281
24474
  }
24282
24475
  }
24283
- 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;
24284
24585
  }
24285
24586
  /**
24286
24587
  * Semver "a > b". Compares major.minor.patch numerically; a version without a
@@ -24591,7 +24892,7 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
24591
24892
  if (decision.reason === "no-credential" && req.method === "GET"
24592
24893
  && String(req.headers.accept ?? "").includes("text/html")
24593
24894
  && isWebPageNavigation(requestPath)) {
24594
- serveSigninPage(res, 401, { webOnly: this.isWebOnlyFleet() });
24895
+ serveSigninPage(res, 401, { webOnly: this.signinWithoutChat() });
24595
24896
  return;
24596
24897
  }
24597
24898
  res.writeHead(decision.status);