@songsid/agend 2.3.5-alpha.5 → 2.3.5-alpha.7

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 (410) hide show
  1. package/THIRD_PARTY_NOTICES.md +0 -1
  2. package/dist/accounts-profiles.d.ts +96 -0
  3. package/dist/accounts-profiles.js +178 -0
  4. package/dist/accounts-profiles.js.map +1 -0
  5. package/dist/accounts-signout.d.ts +59 -0
  6. package/dist/accounts-signout.js +184 -0
  7. package/dist/accounts-signout.js.map +1 -0
  8. package/dist/accounts-view.d.ts +54 -0
  9. package/dist/accounts-view.js +55 -11
  10. package/dist/accounts-view.js.map +1 -1
  11. package/dist/agent-workspace.d.ts +11 -0
  12. package/dist/agent-workspace.js +28 -0
  13. package/dist/agent-workspace.js.map +1 -1
  14. package/dist/auth-api.js +38 -5
  15. package/dist/auth-api.js.map +1 -1
  16. package/dist/authority/session-authorizations.d.ts +2 -0
  17. package/dist/authority/session-authorizations.js +7 -1
  18. package/dist/authority/session-authorizations.js.map +1 -1
  19. package/dist/authority/web-authority.d.ts +13 -0
  20. package/dist/authority/web-authority.js +12 -0
  21. package/dist/authority/web-authority.js.map +1 -1
  22. package/dist/backend/claude-code.js +47 -9
  23. package/dist/backend/claude-code.js.map +1 -1
  24. package/dist/backend/codex.js +1 -0
  25. package/dist/backend/codex.js.map +1 -1
  26. package/dist/backend/kiro.js +1 -1
  27. package/dist/backend/kiro.js.map +1 -1
  28. package/dist/backend/types.d.ts +2 -0
  29. package/dist/backend/types.js.map +1 -1
  30. package/dist/build-provenance.json +1 -1
  31. package/dist/bundled-tmux-guard.d.ts +19 -0
  32. package/dist/bundled-tmux-guard.js +83 -0
  33. package/dist/bundled-tmux-guard.js.map +1 -0
  34. package/dist/channel/access-manager.d.ts +1 -6
  35. package/dist/channel/access-manager.js +4 -94
  36. package/dist/channel/access-manager.js.map +1 -1
  37. package/dist/channel/adapters/discord.d.ts +0 -2
  38. package/dist/channel/adapters/discord.js +0 -8
  39. package/dist/channel/adapters/discord.js.map +1 -1
  40. package/dist/channel/adapters/telegram.d.ts +0 -3
  41. package/dist/channel/adapters/telegram.js +1 -30
  42. package/dist/channel/adapters/telegram.js.map +1 -1
  43. package/dist/channel/types.d.ts +0 -2
  44. package/dist/classic-bindings.d.ts +13 -0
  45. package/dist/classic-bindings.js +28 -2
  46. package/dist/classic-bindings.js.map +1 -1
  47. package/dist/classic-channel-manager.d.ts +2 -0
  48. package/dist/classic-channel-manager.js +5 -1
  49. package/dist/classic-channel-manager.js.map +1 -1
  50. package/dist/cli.js +117 -30
  51. package/dist/cli.js.map +1 -1
  52. package/dist/config-validator.js +11 -0
  53. package/dist/config-validator.js.map +1 -1
  54. package/dist/config.js +3 -1
  55. package/dist/config.js.map +1 -1
  56. package/dist/daemon.d.ts +27 -2
  57. package/dist/daemon.js +107 -6
  58. package/dist/daemon.js.map +1 -1
  59. package/dist/doctor.js +3 -4
  60. package/dist/doctor.js.map +1 -1
  61. package/dist/e2e-isolation.js +5 -2
  62. package/dist/e2e-isolation.js.map +1 -1
  63. package/dist/fleet-control-audit.d.ts +1 -1
  64. package/dist/fleet-manager.d.ts +188 -1
  65. package/dist/fleet-manager.js +1059 -79
  66. package/dist/fleet-manager.js.map +1 -1
  67. package/dist/general-knowledge/skills/concepts/SKILL.md +22 -7
  68. package/dist/general-knowledge/skills/credential-profiles/SKILL.md +10 -0
  69. package/dist/general-knowledge/steering/core-rules.md +6 -4
  70. package/dist/hub/buttons.js +4 -2
  71. package/dist/hub/buttons.js.map +1 -1
  72. package/dist/hub/catalog.d.ts +1 -1
  73. package/dist/hub/catalog.js +82 -15
  74. package/dist/hub/catalog.js.map +1 -1
  75. package/dist/hub/compose/server.d.ts +4 -1
  76. package/dist/hub/compose/server.js +30 -3
  77. package/dist/hub/compose/server.js.map +1 -1
  78. package/dist/hub/directory/directory.d.ts +1 -1
  79. package/dist/hub/directory/directory.js +142 -21
  80. package/dist/hub/directory/directory.js.map +1 -1
  81. package/dist/hub/directory/groups.d.ts +29 -0
  82. package/dist/hub/directory/groups.js +29 -0
  83. package/dist/hub/directory/groups.js.map +1 -0
  84. package/dist/hub/directory/index.d.ts +2 -1
  85. package/dist/hub/directory/types.d.ts +12 -2
  86. package/dist/hub/directory/types.js.map +1 -1
  87. package/dist/hub/group-policy/admin-context.d.ts +23 -0
  88. package/dist/hub/group-policy/admin-context.js +52 -0
  89. package/dist/hub/group-policy/admin-context.js.map +1 -0
  90. package/dist/hub/group-policy/admin-dto.d.ts +235 -0
  91. package/dist/hub/group-policy/admin-dto.js +55 -0
  92. package/dist/hub/group-policy/admin-dto.js.map +1 -0
  93. package/dist/hub/group-policy/admin-inventory.d.ts +24 -0
  94. package/dist/hub/group-policy/admin-inventory.js +72 -0
  95. package/dist/hub/group-policy/admin-inventory.js.map +1 -0
  96. package/dist/hub/group-policy/admin-read.d.ts +21 -0
  97. package/dist/hub/group-policy/admin-read.js +90 -0
  98. package/dist/hub/group-policy/admin-read.js.map +1 -0
  99. package/dist/hub/group-policy/authorization.d.ts +43 -0
  100. package/dist/hub/group-policy/authorization.js +170 -0
  101. package/dist/hub/group-policy/authorization.js.map +1 -0
  102. package/dist/hub/group-policy/model.d.ts +56 -0
  103. package/dist/hub/group-policy/model.js +46 -0
  104. package/dist/hub/group-policy/model.js.map +1 -0
  105. package/dist/hub/group-policy/resources.d.ts +60 -0
  106. package/dist/hub/group-policy/resources.js +191 -0
  107. package/dist/hub/group-policy/resources.js.map +1 -0
  108. package/dist/hub/group-policy/store.d.ts +58 -0
  109. package/dist/hub/group-policy/store.js +155 -0
  110. package/dist/hub/group-policy/store.js.map +1 -0
  111. package/dist/hub/http/compose.js +9 -9
  112. package/dist/hub/http/compose.js.map +1 -1
  113. package/dist/hub/http/core.d.ts +23 -3
  114. package/dist/hub/http/core.js +138 -5
  115. package/dist/hub/http/core.js.map +1 -1
  116. package/dist/hub/http/deps.d.ts +3 -0
  117. package/dist/hub/pairing.d.ts +3 -1
  118. package/dist/hub/pairing.js +6 -3
  119. package/dist/hub/pairing.js.map +1 -1
  120. package/dist/hub/policy.d.ts +3 -1
  121. package/dist/hub/policy.js +13 -6
  122. package/dist/hub/policy.js.map +1 -1
  123. package/dist/hub/rooms.d.ts +1 -0
  124. package/dist/hub/rooms.js +76 -26
  125. package/dist/hub/rooms.js.map +1 -1
  126. package/dist/hub/server.d.ts +2 -0
  127. package/dist/hub/server.js +12 -2
  128. package/dist/hub/server.js.map +1 -1
  129. package/dist/hub/sessions.js +2 -1
  130. package/dist/hub/sessions.js.map +1 -1
  131. package/dist/hub/types.d.ts +2 -0
  132. package/dist/instance-config-impact.js +4 -3
  133. package/dist/instance-config-impact.js.map +1 -1
  134. package/dist/instance-lifecycle.d.ts +17 -0
  135. package/dist/instance-lifecycle.js +38 -1
  136. package/dist/instance-lifecycle.js.map +1 -1
  137. package/dist/locale.js +45 -18
  138. package/dist/locale.js.map +1 -1
  139. package/dist/login-controller.d.ts +5 -0
  140. package/dist/login-controller.js +11 -0
  141. package/dist/login-controller.js.map +1 -1
  142. package/dist/login-window-lock.d.ts +2 -1
  143. package/dist/login-window-lock.js.map +1 -1
  144. package/dist/ls-rows.d.ts +1 -1
  145. package/dist/ls-rows.js +1 -1
  146. package/dist/ls-rows.js.map +1 -1
  147. package/dist/machine-accounts.d.ts +110 -0
  148. package/dist/machine-accounts.js +229 -0
  149. package/dist/machine-accounts.js.map +1 -0
  150. package/dist/machine-signins.d.ts +89 -0
  151. package/dist/machine-signins.js +182 -0
  152. package/dist/machine-signins.js.map +1 -0
  153. package/dist/muse-usage-relay.d.ts +2 -0
  154. package/dist/muse-usage-relay.js +5 -3
  155. package/dist/muse-usage-relay.js.map +1 -1
  156. package/dist/needs-you-hub.d.ts +3 -0
  157. package/dist/needs-you-hub.js +13 -3
  158. package/dist/needs-you-hub.js.map +1 -1
  159. package/dist/needs-you.d.ts +35 -2
  160. package/dist/needs-you.js +19 -0
  161. package/dist/needs-you.js.map +1 -1
  162. package/dist/quickstart.js +7 -18
  163. package/dist/quickstart.js.map +1 -1
  164. package/dist/quiet-run.d.ts +31 -0
  165. package/dist/quiet-run.js +50 -0
  166. package/dist/quiet-run.js.map +1 -0
  167. package/dist/quota-notice-config.d.ts +22 -0
  168. package/dist/quota-notice-config.js +41 -0
  169. package/dist/quota-notice-config.js.map +1 -0
  170. package/dist/runtime-api.d.ts +13 -0
  171. package/dist/runtime-api.js +134 -2
  172. package/dist/runtime-api.js.map +1 -1
  173. package/dist/runtime-build-info.d.ts +2 -1
  174. package/dist/runtime-build-info.js +7 -3
  175. package/dist/runtime-build-info.js.map +1 -1
  176. package/dist/runtime-cli-install.d.ts +153 -0
  177. package/dist/runtime-cli-install.js +675 -0
  178. package/dist/runtime-cli-install.js.map +1 -0
  179. package/dist/runtime-cli.js +157 -12
  180. package/dist/runtime-cli.js.map +1 -1
  181. package/dist/runtime-client.d.ts +64 -2
  182. package/dist/runtime-client.js +277 -20
  183. package/dist/runtime-client.js.map +1 -1
  184. package/dist/runtime-coordinator.d.ts +10 -1
  185. package/dist/runtime-coordinator.js +93 -2
  186. package/dist/runtime-coordinator.js.map +1 -1
  187. package/dist/runtime-credential-profiles.d.ts +11 -2
  188. package/dist/runtime-credential-profiles.js +28 -4
  189. package/dist/runtime-credential-profiles.js.map +1 -1
  190. package/dist/runtime-install.js +9 -6
  191. package/dist/runtime-install.js.map +1 -1
  192. package/dist/runtime-pane-link.js +2 -1
  193. package/dist/runtime-pane-link.js.map +1 -1
  194. package/dist/runtime-pane-service.js +2 -2
  195. package/dist/runtime-pane-service.js.map +1 -1
  196. package/dist/runtime-pane-store.d.ts +10 -0
  197. package/dist/runtime-pane-store.js +13 -1
  198. package/dist/runtime-pane-store.js.map +1 -1
  199. package/dist/runtime-profile-ownership.d.ts +66 -0
  200. package/dist/runtime-profile-ownership.js +391 -0
  201. package/dist/runtime-profile-ownership.js.map +1 -0
  202. package/dist/runtime-protocol.d.ts +88 -2
  203. package/dist/runtime-protocol.js +40 -0
  204. package/dist/runtime-protocol.js.map +1 -1
  205. package/dist/runtime-remote-accounts.d.ts +197 -0
  206. package/dist/runtime-remote-accounts.js +663 -0
  207. package/dist/runtime-remote-accounts.js.map +1 -0
  208. package/dist/runtime-remote-setup.d.ts +105 -0
  209. package/dist/runtime-remote-setup.js +529 -0
  210. package/dist/runtime-remote-setup.js.map +1 -0
  211. package/dist/runtime-signin-transport.d.ts +39 -0
  212. package/dist/runtime-signin-transport.js +110 -0
  213. package/dist/runtime-signin-transport.js.map +1 -0
  214. package/dist/runtime-signin.d.ts +132 -0
  215. package/dist/runtime-signin.js +289 -0
  216. package/dist/runtime-signin.js.map +1 -0
  217. package/dist/runtime-update-attention.d.ts +4 -0
  218. package/dist/runtime-update-attention.js +11 -0
  219. package/dist/runtime-update-attention.js.map +1 -0
  220. package/dist/runtime-update-controller.d.ts +75 -0
  221. package/dist/runtime-update-controller.js +691 -0
  222. package/dist/runtime-update-controller.js.map +1 -0
  223. package/dist/runtime-update-ipc.d.ts +42 -0
  224. package/dist/runtime-update-ipc.js +144 -0
  225. package/dist/runtime-update-ipc.js.map +1 -0
  226. package/dist/runtime-update-journal.d.ts +5 -0
  227. package/dist/runtime-update-journal.js +7 -0
  228. package/dist/runtime-update-journal.js.map +1 -1
  229. package/dist/runtime-update-lock.js +17 -2
  230. package/dist/runtime-update-lock.js.map +1 -1
  231. package/dist/runtime-update-status.d.ts +30 -0
  232. package/dist/runtime-update-status.js +31 -0
  233. package/dist/runtime-update-status.js.map +1 -0
  234. package/dist/settings-api.js +6 -2
  235. package/dist/settings-api.js.map +1 -1
  236. package/dist/settings-change.d.ts +10 -0
  237. package/dist/settings-change.js +25 -1
  238. package/dist/settings-change.js.map +1 -1
  239. package/dist/settings-confirmation.d.ts +25 -1
  240. package/dist/settings-confirmation.js +11 -3
  241. package/dist/settings-confirmation.js.map +1 -1
  242. package/dist/settings-effect.js +18 -6
  243. package/dist/settings-effect.js.map +1 -1
  244. package/dist/settings-http-confirmation.d.ts +21 -0
  245. package/dist/settings-http-confirmation.js +74 -3
  246. package/dist/settings-http-confirmation.js.map +1 -1
  247. package/dist/settings-instance-patch.js +1 -1
  248. package/dist/settings-instance-patch.js.map +1 -1
  249. package/dist/setup-wizard.js +3 -5
  250. package/dist/setup-wizard.js.map +1 -1
  251. package/dist/signin-keepalive.d.ts +203 -0
  252. package/dist/signin-keepalive.js +652 -0
  253. package/dist/signin-keepalive.js.map +1 -0
  254. package/dist/structured-signin-transport.js +4 -0
  255. package/dist/structured-signin-transport.js.map +1 -1
  256. package/dist/structured-signin.d.ts +7 -0
  257. package/dist/structured-signin.js +4 -2
  258. package/dist/structured-signin.js.map +1 -1
  259. package/dist/tips.js +4 -4
  260. package/dist/tips.js.map +1 -1
  261. package/dist/tmux-binary.d.ts +23 -23
  262. package/dist/tmux-binary.js +35 -46
  263. package/dist/tmux-binary.js.map +1 -1
  264. package/dist/tmux-exec-helper.js +3 -3
  265. package/dist/tmux-exec-helper.js.map +1 -1
  266. package/dist/tmux-legacy.d.ts +94 -0
  267. package/dist/tmux-legacy.js +309 -0
  268. package/dist/tmux-legacy.js.map +1 -0
  269. package/dist/tmux-manager.d.ts +7 -1
  270. package/dist/tmux-manager.js +21 -11
  271. package/dist/tmux-manager.js.map +1 -1
  272. package/dist/tmux-rollback.d.ts +31 -0
  273. package/dist/tmux-rollback.js +72 -0
  274. package/dist/tmux-rollback.js.map +1 -0
  275. package/dist/tmux-server.d.ts +102 -0
  276. package/dist/tmux-server.js +248 -0
  277. package/dist/tmux-server.js.map +1 -0
  278. package/dist/transcript-monitor.js +43 -5
  279. package/dist/transcript-monitor.js.map +1 -1
  280. package/dist/transcript-records.d.ts +2 -1
  281. package/dist/transcript-records.js +3 -0
  282. package/dist/transcript-records.js.map +1 -1
  283. package/dist/transcript-sources.js +3 -0
  284. package/dist/transcript-sources.js.map +1 -1
  285. package/dist/types.d.ts +5 -0
  286. package/dist/types.js.map +1 -1
  287. package/dist/ui/accounts-keepalive.js +113 -0
  288. package/dist/ui/accounts-manage.js +237 -0
  289. package/dist/ui/accounts-view.js +191 -36
  290. package/dist/ui/agent-runtime-settings.js +2 -1
  291. package/dist/ui/app.html +8 -1
  292. package/dist/ui/backend-signin.js +12 -3
  293. package/dist/ui/general-location.js +28 -14
  294. package/dist/ui/hub-attachments.js +90 -0
  295. package/dist/ui/hub-chat-store.js +11 -5
  296. package/dist/ui/hub-client.js +20 -1
  297. package/dist/ui/hub-grant-strings.js +13 -0
  298. package/dist/ui/hub-owner-strings.js +6 -2
  299. package/dist/ui/hub-preview.js +101 -0
  300. package/dist/ui/hub-strings.js +4 -2
  301. package/dist/ui/machine-signin.js +56 -0
  302. package/dist/ui/panel-fleet.js +1 -1
  303. package/dist/ui/panel-hub.js +194 -54
  304. package/dist/ui/panel-log.js +2 -2
  305. package/dist/ui/panel-needs.js +14 -8
  306. package/dist/ui/panel-notices.js +4 -3
  307. package/dist/ui/panel-runtimes.js +32 -11
  308. package/dist/ui/panel-settings.js +18 -24
  309. package/dist/ui/panel-windows-agent.js +2 -1
  310. package/dist/ui/preview-pages.js +3 -41
  311. package/dist/ui/preview-panel-actions.js +3 -161
  312. package/dist/ui/preview-panel.js +10 -557
  313. package/dist/ui/preview-versions.js +3 -155
  314. package/dist/ui/runtime-cli-install.js +134 -0
  315. package/dist/ui/runtime-update-commands.d.ts +2 -0
  316. package/dist/ui/runtime-update-commands.js +11 -0
  317. package/dist/ui/runtime-update-status.js +53 -0
  318. package/dist/ui/search-dialog.js +3 -2
  319. package/dist/ui/settings-confirm.js +28 -0
  320. package/dist/ui/settings-devices.js +6 -10
  321. package/dist/ui/settings-guests.js +3 -2
  322. package/dist/ui/settings-hub-browser-certificate.js +2 -0
  323. package/dist/ui/settings-hub-membership.js +17 -11
  324. package/dist/ui/settings-hub-retention.js +2 -0
  325. package/dist/ui/settings-hub-section.js +35 -0
  326. package/dist/ui/settings-hub.js +17 -5
  327. package/dist/ui/settings-layout.js +6 -2
  328. package/dist/ui/settings-named-test.js +2 -2
  329. package/dist/ui/settings-outside.js +1 -1
  330. package/dist/ui/settings-quota-notice.js +102 -0
  331. package/dist/ui/settings-registry.js +4 -0
  332. package/dist/ui/settings-strings.js +6 -6
  333. package/dist/ui/settings-web-authority.js +2 -1
  334. package/dist/ui/shared/accounts-keepalive.css +7 -0
  335. package/dist/ui/shared/accounts.css +13 -0
  336. package/dist/ui/shared/app-i18n.js +4 -2
  337. package/dist/ui/shared/app-route.js +1 -1
  338. package/dist/ui/shared/app-shell.js +111 -8
  339. package/dist/ui/shared/app-store.js +2 -2
  340. package/dist/ui/shared/app.css +29 -0
  341. package/dist/ui/shared/app.js +2 -1
  342. package/dist/ui/shared/chat-strings.js +8 -8
  343. package/dist/ui/shared/hub-chat.css +1 -0
  344. package/dist/ui/shared/hub-owner.css +3 -3
  345. package/dist/ui/shared/hub-signin.css +24 -0
  346. package/dist/ui/shared/loading.css +37 -0
  347. package/dist/ui/shared/preview-pages.js +41 -0
  348. package/dist/ui/shared/preview-panel-actions.js +168 -0
  349. package/dist/ui/shared/preview-panel.js +565 -0
  350. package/dist/ui/shared/preview-versions.js +155 -0
  351. package/dist/ui/shared/runtime-install.css +4 -0
  352. package/dist/ui/shared/signin.js +68 -6
  353. package/dist/ui/shared/ui-states.js +14 -3
  354. package/dist/ui/shared/view-strings.js +4 -4
  355. package/dist/ui/shared/workspace-follow.css +19 -0
  356. package/dist/ui/signin.html +7 -3
  357. package/dist/ui/structured-signin.js +43 -11
  358. package/dist/ui/workspace-follow-strings.js +28 -0
  359. package/dist/ui/workspace-panel.js +225 -36
  360. package/dist/update-install.d.ts +7 -0
  361. package/dist/update-install.js +23 -0
  362. package/dist/update-install.js.map +1 -1
  363. package/dist/usage/providers.d.ts +6 -0
  364. package/dist/usage/providers.js +18 -9
  365. package/dist/usage/providers.js.map +1 -1
  366. package/dist/usage/quota-notices.d.ts +38 -0
  367. package/dist/usage/quota-notices.js +160 -0
  368. package/dist/usage/quota-notices.js.map +1 -0
  369. package/dist/usage/usage-api.d.ts +1 -0
  370. package/dist/usage/usage-api.js +16 -0
  371. package/dist/usage/usage-api.js.map +1 -1
  372. package/dist/web-api.d.ts +38 -0
  373. package/dist/web-api.js +357 -14
  374. package/dist/web-api.js.map +1 -1
  375. package/dist/web-login.d.ts +35 -1
  376. package/dist/web-login.js +51 -5
  377. package/dist/web-login.js.map +1 -1
  378. package/dist/web-remote-access.d.ts +6 -0
  379. package/dist/web-remote-access.js +10 -1
  380. package/dist/web-remote-access.js.map +1 -1
  381. package/dist/web-session.d.ts +11 -0
  382. package/dist/web-session.js +38 -1
  383. package/dist/web-session.js.map +1 -1
  384. package/dist/web-shell-routes.d.ts +1 -1
  385. package/dist/web-shell-routes.js +1 -1
  386. package/dist/web-shell-routes.js.map +1 -1
  387. package/dist/web-signin-link.d.ts +42 -0
  388. package/dist/web-signin-link.js +110 -0
  389. package/dist/web-signin-link.js.map +1 -0
  390. package/dist/windows-cli-api.d.ts +14 -0
  391. package/dist/windows-cli-api.js +21 -0
  392. package/dist/windows-cli-api.js.map +1 -1
  393. package/dist/windows-cli-worker.d.ts +3 -1
  394. package/dist/windows-cli-worker.js +18 -3
  395. package/dist/windows-cli-worker.js.map +1 -1
  396. package/dist/workspace-follow-parse.d.ts +36 -0
  397. package/dist/workspace-follow-parse.js +208 -0
  398. package/dist/workspace-follow-parse.js.map +1 -0
  399. package/dist/workspace-follow-records.d.ts +17 -0
  400. package/dist/workspace-follow-records.js +88 -0
  401. package/dist/workspace-follow-records.js.map +1 -0
  402. package/dist/workspace-follow.d.ts +41 -0
  403. package/dist/workspace-follow.js +143 -0
  404. package/dist/workspace-follow.js.map +1 -0
  405. package/dist/wsl-detect.d.ts +1 -0
  406. package/dist/wsl-detect.js +20 -0
  407. package/dist/wsl-detect.js.map +1 -0
  408. package/launcher/tmux-bundle.cjs +26 -10
  409. package/package.json +7 -2
  410. package/templates/runtime-install/install.ps1 +154 -13
@@ -5,6 +5,9 @@ import { NativePaneRecoveryError } from "./native-pane-recovery.js";
5
5
  import { nativePaneToolAvailable, nativePaneToolRefusal } from "./native-pane-tools.js";
6
6
  import { windowsAgentsFor } from "./windows-agents.js";
7
7
  import { AgentRuntimeChanges } from "./agent-runtime-change.js";
8
+ import { QuotaNotices } from "./usage/quota-notices.js";
9
+ import { quotaNoticeRule } from "./quota-notice-config.js";
10
+ import { onUsageSnapshot } from "./usage/usage-api.js";
8
11
  import { supportsVerifiedKiroMigration, getCachedKiroCliCompatibility, kiroV1DbPath, kiroV2SessionsDir } from "./backend/kiro.js";
9
12
  import { listKiroV1Sessions, readKiroClassicLinks } from "./backend/kiro-identity.js";
10
13
  import { readKiroV1SavedModel } from "./backend/kiro-retired-model.js";
@@ -68,6 +71,7 @@ import { join, dirname, basename, delimiter, isAbsolute, relative, resolve as re
68
71
  import { fileURLToPath } from "node:url";
69
72
  import { isDeepStrictEqual } from "node:util";
70
73
  import { getAgendHome, ensureWorkspaceGit } from "./paths.js";
74
+ import { LegacyWindowHoldError } from "./tmux-legacy.js";
71
75
  import { planKiroReconciliation, applyKiroReconciliation, kiroReconciliationPrompt } from "./kiro-reconcile.js";
72
76
  import { applyKiroMigration, kiroMigrationPrompt, planKiroMigration } from "./kiro-migrate.js";
73
77
  import { fleetLabel } from "./fleet-label.js";
@@ -213,8 +217,9 @@ import { windowsCliEnabled, closeWindowsBridge, inventoryProbed, LOCAL_WINDOWS_C
213
217
  import { nativeCliVersionState } from "./runtime-pane-native.js";
214
218
  import { localWindowsCliEnabled, remoteRuntimeEnabled, setConfiguredRuntimeSwitches, maxAgentsPerMachine } from "./runtime-switches.js";
215
219
  import { RuntimeInstallService } from "./runtime-install.js";
216
- import { RUNTIME_CREDENTIAL_CAPABILITY } from "./runtime-credential-profiles.js";
220
+ import { RUNTIME_CREDENTIAL_CAPABILITY, validCredentialProfileName } from "./runtime-credential-profiles.js";
217
221
  import { RuntimeCoordinator } from "./runtime-coordinator.js";
222
+ import { runtimeUpdateAttention } from "./runtime-update-attention.js";
218
223
  import { RuntimeWindowsBridge } from "./runtime-windows-bridge.js";
219
224
  import { FleetWindowsRuntime } from "./fleet-windows-runtime.js";
220
225
  import { NativeMcpSessions } from "./native-mcp.js";
@@ -309,6 +314,8 @@ import { isSetupComplete, markSetupComplete } from "./setup-marker.js";
309
314
  import { manualCleanupMessage, reapStaleTunnel } from "./tunnel/lease.js";
310
315
  import { buildToolPermissionsNotice } from "./tool-permissions-notice.js";
311
316
  import { NeedsYouHub } from "./needs-you-hub.js";
317
+ import { SignInKeepAlive, isKeepAliveBackend } from "./signin-keepalive.js";
318
+ import { BACKEND_LABELS } from "./interaction-observation.js";
312
319
  import { GENERAL_NAME, GENERAL_PAUSE_ERROR, adoptGeneralByName, freeGeneralName, isGeneralInstance } from "./general-instance.js";
313
320
  import { buildOrgChart } from "./web-org.js";
314
321
  import { topMemoryHogs } from "./memory-hogs.js";
@@ -328,7 +335,7 @@ import { guestSessionPolicy, localSessionPolicy, sessionVia, tokenEpoch, WebSess
328
335
  import { WebNotices, WEB_NOTICES_FILE } from "./web-notices.js";
329
336
  import { DeviceLoginRequests } from "./web-device-login.js";
330
337
  import { isOutsideLinkOwner, OUTSIDE_LINK_OWNER, OUTSIDE_LINK_RETRY_MS, OUTSIDE_OWN_CLOSES, outsideDuration, outsideTimer, TOTP_STEP_SECONDS, WEB_REMOTE_ACCESS_FILE, WebRemoteAccess } from "./web-remote-access.js";
331
- import { authorityNow, evaluateWebAuthority, HOST_OPERATOR, VERIFIED_SESSION_HOURS, webAuthorityPolicy } from "./authority/web-authority.js";
338
+ import { authorityNow, evaluateWebAuthority, HOST_OPERATOR, hostSessionHere, VERIFIED_SESSION_HOURS, webAuthorityPolicy } from "./authority/web-authority.js";
332
339
  import { AuthorityStateStore } from "./authority/authority-state.js";
333
340
  import { SessionAuthorizations } from "./authority/session-authorizations.js";
334
341
  import { SessionAuthorizationRequests } from "./web-session-authorization.js";
@@ -349,10 +356,22 @@ import { PROVIDER_SECRET_SPECS, PUBLIC_TUNNEL_SECRET_SPEC, providerSecretSpec, p
349
356
  const SELF_RESTART_DEADLINE_MS = 300_000;
350
357
  import { APPLY_FLEET_TARGET, ApplyJobStore, viewOf, } from "./apply-job.js";
351
358
  import { kiroHome } from "./backend/kiro-kas-store.js";
352
- import { CHAT_PROFILE_LOGIN_BACKENDS, credentialHomeSpec, credentialProfileHome, credentialProfileEnv, credentialProfileLogin, credentialProfileLoginCommand, credentialProfileStoreHome, credentialSwitchCarriesConversation, credentialSwitchStartsFresh, instanceCredentialProfile, listConfiguredProfiles } from "./backend/credential-profile.js";
359
+ import { CHAT_PROFILE_LOGIN_BACKENDS, credentialHomeSpec, credentialProfileHome, credentialProfileEnv, credentialProfileLogin, credentialProfileLoginCommand, credentialProfileStoreHome, credentialSwitchCarriesConversation, credentialSwitchStartsFresh, instanceCredentialProfile, listConfiguredProfiles, resolveCredentialProfile } from "./backend/credential-profile.js";
353
360
  import { carryClaudeConversation } from "./backend/claude-carry.js";
354
- import { classicProfile, mergeBackendOptions, profileKey, profileName, profileOf, readClassicBindings } from "./classic-bindings.js";
361
+ import { classicProfile, mergeBackendOptions, profileKey, profileName, profileOf, readClassicBindings, readClassicBindingsStrict } from "./classic-bindings.js";
355
362
  import { ACCOUNT_CLIS, PROFILE_CLIS, buildAccountsView, profilesOnDisk, weeklyUsage } from "./accounts-view.js";
363
+ import { addAccountProfile, removeAccountProfile } from "./accounts-profiles.js";
364
+ import { signOutAccount } from "./accounts-signout.js";
365
+ import { MachineAccounts, machineAgents } from "./machine-accounts.js";
366
+ import { MachineSignIns } from "./machine-signins.js";
367
+ import { runQuiet } from "./quiet-run.js";
368
+ const ACCOUNT_SIGN_OUT_DEPS = {
369
+ platform: process.platform,
370
+ run: (binary, args, env) => runQuiet(binary, args, env), // its `gone` is kept by withAccountWriter
371
+ // #3305 review P2-5: a deadline is a failure (runQuiet), for the Keychain query too; it only reads, so its child is not
372
+ // held as a credential writer (its answer is a failure until it exits 0 in time).
373
+ keychainHas: async (service) => (await runQuiet("security", ["find-generic-password", "-s", service], process.env, { timeoutMs: 15_000 })).code === 0,
374
+ };
356
375
  import { classifyInstanceChange, CLASSIC_HOT_CONFIG_KEYS, HOT_INSTANCE_CONFIG_KEYS, hotConfigUpdate, } from "./instance-config-impact.js";
357
376
  import { cleanupWatchVerdict, formatRestartProgressCompletion, RestartProgress, } from "./restart-progress.js";
358
377
  import { FleetStartup } from "./fleet-startup.js";
@@ -826,6 +845,8 @@ export class FleetManager {
826
845
  handlePaneMcp: async (machineId, body, current) => (await this.nativePanes()).handle(machineId, body, current),
827
846
  warn: (fields, message) => this.logger.warn(fields, message),
828
847
  changed: event => {
848
+ if (event?.type === "machine")
849
+ this.needsYou?.poke();
829
850
  if (event?.type === "machine" && this.runtimeHub?.machine(event.machineId)?.status !== "online") {
830
851
  for (const [name, config] of Object.entries(this.fleetConfig?.instances ?? {}))
831
852
  if (config.machine_id === event.machineId) {
@@ -835,7 +856,6 @@ export class FleetManager {
835
856
  this.holdGeneralOldDeliveries(name);
836
857
  }
837
858
  }
838
- this.needsYou?.poke();
839
859
  }
840
860
  if (this.runtimeStatusScheduled || this.shuttingDown)
841
861
  return;
@@ -2202,6 +2222,10 @@ export class FleetManager {
2202
2222
  hubEffectsReady = false;
2203
2223
  hubEffectsScheduled = false;
2204
2224
  hubHolds = [];
2225
+ /** M-2457 §6 rule 2: the fleet is held — an old tmux server is still on the socket and AgEnD can't prove it its own. */
2226
+ tmuxHold = null;
2227
+ /** M-2457 §6 rule 3: instances held by an old 2.3 window AgEnD could not prove its own. */
2228
+ legacyWindowHolds = new Map();
2205
2229
  rawFleetDocument = null;
2206
2230
  /** #2208: the paths a saveFleetConfig() wrote, for its check that nothing else changed. */
2207
2231
  fleetDocumentWrites = null;
@@ -2380,6 +2404,8 @@ export class FleetManager {
2380
2404
  kiroMigrationRuns = new Map();
2381
2405
  /** #1386 "Needs you": the list, its live chat messages and Acknowledge. Started with the fleet (finishStartup). */
2382
2406
  needsYou = null;
2407
+ /** #3292: "Keep sign-in alive" (signin-keepalive.ts); built at startup, stopped at shutdown. */
2408
+ signInKeepAlive = null;
2383
2409
  hubExecutionAttention = null;
2384
2410
  missedOfflineStore = null;
2385
2411
  configHistory = null;
@@ -2426,6 +2452,8 @@ export class FleetManager {
2426
2452
  startupDashboard = null;
2427
2453
  adapterState = new Map();
2428
2454
  adapterRetryInFlight = new Map();
2455
+ /** #3365 review P2: connections whose adapter could not be confirmed stopped — none is admitted for them until a restart. */
2456
+ adapterTeardownUnknown = new Set();
2429
2457
  /** Web Settings secret rotation is deliberately separate from reconnect
2430
2458
  * recovery: a rotation must build a fresh provider client with the new token,
2431
2459
  * and stale callbacks from the old client must not win. */
@@ -3134,6 +3162,7 @@ export class FleetManager {
3134
3162
  && sessions.isCurrent(record, tokenEpoch(this.webToken)) && (!exposure || exposure.isCurrent()) };
3135
3163
  }, baseline: () => baselines.read(), snapshot: () => baselines.snapshot(),
3136
3164
  selfConfirm: (req, id) => this.settingsSelfConfirmation(store, req, id),
3165
+ totp: { state: (req, id) => this.settingsTotpState(store, req, id), confirm: (req, id, code, digest) => this.settingsTotpConfirm(store, req, id, code, digest) },
3137
3166
  directAgentCreation: true,
3138
3167
  job: async (id) => {
3139
3168
  const settlement = this.settingsJobSettlements.get(id);
@@ -3169,13 +3198,40 @@ export class FleetManager {
3169
3198
  const auth = authorizeSession(req, this.webToken, this.webSessions, { touch: false });
3170
3199
  if (auth.kind !== "ok")
3171
3200
  return null;
3201
+ // D3 (decision bcbb541f): on a fleet with a chat connection, a change no General can take a card for would wait for
3202
+ // `agend settings confirm` on the host. The host's own session, used on this computer (hostSessionHere: its code came
3203
+ // from `agend web` here; never bare loopback), carries that same trust — it confirms at Save, with no click added. A
3204
+ // change a General can take keeps its card (D1). Asked again at execution: the same session, still here, still no card.
3205
+ // (A web-only fleet's host operator has its own rule below, with its revocable authorization.) The noSelfConfirm changes
3206
+ // the leader ruled on are included: the outward Hub changes (hostLocalConfirm) and a link option turned on
3207
+ // (hostSessionOnly, cid-d3) — this session is exactly the one those allow.
3208
+ // "No card": none could be posted now, or the one tried could not be (posting failed or ran out — the view says
3209
+ // host_cli; #3362 review N1).
3210
+ const noCard = () => !this.settingsCardPossible(store, id) || store.inspect(id)?.confirmation.kind === "host_cli";
3211
+ if (!this.isWebOnlyFleet() && hostSessionHere(auth.session, req) && noCard()
3212
+ && (store.selfConfirmable(id) || store.hostLocalConfirmable(id) || store.hostSessionConfirmable(id))) {
3213
+ // A card that could not be posted stays unposted (no card is attached later): fixed now, not re-read at execution,
3214
+ // where the store has already marked the change as confirmed from the web.
3215
+ const handle = auth.session.handle, postFailed = store.inspect(id)?.confirmation.kind === "host_cli";
3216
+ const here = () => {
3217
+ const now = authorizeSession(req, this.webToken, this.webSessions, { touch: false });
3218
+ return now.kind === "ok" && now.session.handle === handle && hostSessionHere(now.session, req) && !this.isWebOnlyFleet();
3219
+ };
3220
+ return {
3221
+ label: t("settings_confirm.host_operator_label"),
3222
+ current: () => here() && (postFailed || !this.settingsCardPossible(store, id)),
3223
+ done: view => { this.logger.info({ id: view.id, state: view.state }, "Settings change confirmed from the web by this computer's admin (no General could take it)"); },
3224
+ };
3225
+ }
3172
3226
  // #2453 (§0.2): never over the public link — not even a named-link session that is web-verified there. #3008: except
3173
3227
  // this computer's admin signed in from outside (the authenticator's code, over the link connections from outside
3174
3228
  // opened): the web-only fleet's owner, judged below by the same authority as here (hostOperator).
3175
3229
  if (gatewayRequestContext(req) && auth.session.remote !== "totp")
3176
3230
  return null;
3177
- // …and never a change that turns the named-link option on: that one needs a General's card or the host.
3178
- if (!store.selfConfirmable(id))
3231
+ // …and never a change that turns the named-link option on: that one needs a General's card or the host. B2b (the leader's
3232
+ // ruling on #3352 F1; threat model A 64a289a0): the outward Hub changes (hostLocalConfirm) are the one exception — for
3233
+ // the host operator's own local session only (below).
3234
+ if (!store.selfConfirmable(id) && !store.hostLocalConfirmable(id) && !store.hostSessionConfirmable(id))
3179
3235
  return null;
3180
3236
  const record = auth.session, gateway = !!gatewayRequestContext(req), peer = webPeerOf(req);
3181
3237
  const verified = () => {
@@ -3190,13 +3246,19 @@ export class FleetManager {
3190
3246
  // change — the trust `agend settings confirm` has here; there is no account to be an admin of and no General to
3191
3247
  // ask. Asked again at execution: still the host operator now (this computer, not revoked or run out), still web-only.
3192
3248
  const hostOperator = (a) => !!a && a.adapter_id === HOST_OPERATOR.adapterId && a.user_id === HOST_OPERATOR.userId && this.isWebOnlyFleet();
3193
- if (hostOperator(actor)) {
3249
+ // The host operator's own LOCAL session: its host session (the bootstrap or launch link), over loopback with no
3250
+ // forwarding header and no gateway (classifyWebPeer, as #3345). Only that one may Apply-now an outward Hub change, or a
3251
+ // link option turned on (hostSessionOnly — the outside sign-in, a gateway, never may).
3252
+ const hostLocal = () => hostSessionHere(record, req);
3253
+ if (hostOperator(actor) && (store.selfConfirmable(id) || hostLocal())) {
3194
3254
  return {
3195
3255
  label: t("settings_confirm.host_operator_label"),
3196
- current: () => hostOperator(verified()),
3256
+ current: () => hostOperator(verified()) && (store.selfConfirmable(id) || hostLocal()),
3197
3257
  done: view => { this.logger.info({ id: view.id, state: view.state }, "Settings change confirmed from the web by this computer's admin"); },
3198
3258
  };
3199
3259
  }
3260
+ if (!store.selfConfirmable(id))
3261
+ return null;
3200
3262
  const chat = this.settingsChatAuthority(store, id);
3201
3263
  if (!chat)
3202
3264
  return null;
@@ -3218,6 +3280,99 @@ export class FleetManager {
3218
3280
  done: view => this.settingsWebConfirmedNotice(view, affected, name, chat.platform),
3219
3281
  };
3220
3282
  }
3283
+ /**
3284
+ * alpha.6 feedback #2c — the user's decision hmsg-468cc290 (option A; decisions 28c2d3a3/0471da59 keep the second factor): on a
3285
+ * web-only fleet, a pending change can be confirmed on THIS computer's own page with the owner's authenticator code, by a
3286
+ * local admin session that is not the host operator (who already has "Apply now"), on this computer or the LAN. Never over
3287
+ * a link (named or quick), never a guest; only a change that can be self-confirmed at all (a named-link opener cannot); the code is checked by
3288
+ * the same store as signing in from outside (#3008): each time step once, the fleet-wide wrong-code limit. Asked again at
3289
+ * execution (`current`): the same session, still an admin here (this computer or the LAN), the fleet still web-only, the
3290
+ * same app still set up (not replaced, nor removed and set up again). Audited by the store under its own label; a correct and a refused use are logged.
3291
+ */
3292
+ settingsTotpSession(req) {
3293
+ // Who is offered the code (the leader's ruling, (b) — Fable's view; threat model 64a289a0): on a web-only fleet, an admin
3294
+ // session with no chat account, on this computer (loopback, no forwarding header) or on the LAN — any such session not
3295
+ // otherwise allowed (a local non-host session may be another OS user). NEVER over a link, named or quick: "over a link" is
3296
+ // the gateway's own context, never a peer address (both links are tunnels arriving from 127.0.0.1). Never a guest.
3297
+ // The code is the authority; the session only carries it (#3352 security review, point 4).
3298
+ const allowed = () => {
3299
+ if (!this.isWebOnlyFleet())
3300
+ return null;
3301
+ const auth = authorizeSession(req, this.webToken, this.webSessions, { touch: false });
3302
+ if (auth.kind !== "ok")
3303
+ return null;
3304
+ const s = auth.session, gateway = gatewayRequestContext(req);
3305
+ if (s.tier !== "admin" || s.owner)
3306
+ return null;
3307
+ if (gateway)
3308
+ return null;
3309
+ const peer = webPeerOf(req);
3310
+ return s.surface === "local" && (peer === "loopback" || peer === "lan") ? { handle: s.handle } : null;
3311
+ };
3312
+ const first = allowed();
3313
+ if (!first)
3314
+ return null;
3315
+ return { handle: first.handle, current: () => { const now = allowed(); return !!now && now.handle === first.handle && !!this.webRemoteAccess()?.enrolled; } };
3316
+ }
3317
+ settingsTotpState(store, req, id) {
3318
+ // A link option turned on (hostSessionOnly): never a code. On a web-only fleet (no General to send it to), any session
3319
+ // but the host's own here is told in plain words to do it in the browser on the AgEnD computer.
3320
+ if (store.hostSessionConfirmable(id))
3321
+ return this.isWebOnlyFleet() && !this.settingsSelfConfirmation(store, req, id) ? "host_browser" : null;
3322
+ if (!(store.selfConfirmable(id) || store.hostLocalConfirmable(id)))
3323
+ return null;
3324
+ // Over a link (web-only fleet): never a code here — the card says to do it in the host computer's own browser, or in General.
3325
+ if (gatewayRequestContext(req))
3326
+ return this.isWebOnlyFleet() && !this.settingsSelfConfirmation(store, req, id) ? "on_host" : null;
3327
+ if (!this.settingsTotpSession(req))
3328
+ return null;
3329
+ if (this.settingsSelfConfirmation(store, req, id))
3330
+ return null; // "Apply now" already (the host operator here)
3331
+ return this.webRemoteAccess()?.enrolled ? "ready" : "not_set_up";
3332
+ }
3333
+ settingsTotpConfirm(store, req, id, code, digest) {
3334
+ if (!(store.selfConfirmable(id) || store.hostLocalConfirmable(id)) || this.settingsSelfConfirmation(store, req, id))
3335
+ return { error: "not_here" };
3336
+ const local = this.settingsTotpSession(req), access = this.webRemoteAccess();
3337
+ if (!local || !local.current() || !access?.enrolled)
3338
+ return { error: "not_here" };
3339
+ // #3352 security review, point 2: the code confirms exactly the change the page showed — checked before the code is.
3340
+ if (digest !== store.confirmDigest(id))
3341
+ return { error: "changed" };
3342
+ const shown = store.inspectHost(id)?.view.summary ?? [];
3343
+ // #3355 review (Prism P2): the code's authority is the app it came from. Bound to that enrollment through execution — an
3344
+ // app replaced, or removed and set up again, while the change waits ends it, for good (a later match never revives it).
3345
+ const enrollment = access.enrollment;
3346
+ const v = access.verify(code);
3347
+ if (v.kind === "ok") {
3348
+ if (!enrollment)
3349
+ return { error: "not_here" };
3350
+ this.logger.info({ id, handle: local.handle }, "Settings change confirmed on this computer with the authenticator code");
3351
+ let lost = false;
3352
+ const current = () => {
3353
+ if (!lost && !(local.current() && this.webRemoteAccess()?.enrollment === enrollment))
3354
+ lost = true;
3355
+ return !lost;
3356
+ };
3357
+ return { label: t("settings_confirm.totp_label"), current, audit: { confirmed_with: "authenticator_code", summary: shown },
3358
+ done: view => { this.logger.info({ id: view.id, state: view.state }, "Settings change confirmed with the authenticator code: done"); } };
3359
+ }
3360
+ if (v.kind === "paused")
3361
+ return { error: "paused", retryAfterMs: v.retryAfterMs };
3362
+ if (v.kind === "not_enrolled")
3363
+ return { error: "not_here" };
3364
+ if (v.kind === "unavailable")
3365
+ return { error: "unavailable" };
3366
+ if (v.skewSteps !== null)
3367
+ this.logger.warn({ offsetSeconds: v.skewSteps * TOTP_STEP_SECONDS }, "A wrong authenticator code matched a nearby time step: this computer's clock may be off");
3368
+ this.logger.info({ id, handle: local.handle }, "Settings change: a wrong authenticator code was refused");
3369
+ if (v.paused) {
3370
+ this.logger.warn({ waitMs: v.retryAfterMs }, "Authenticator codes paused after wrong codes");
3371
+ this.recordWebNotice("fleet", t("outside.notice_paused", outsideDuration(v.retryAfterMs), v.wrong));
3372
+ return { error: "paused", retryAfterMs: v.retryAfterMs };
3373
+ }
3374
+ return { error: "wrong" };
3375
+ }
3221
3376
  /**
3222
3377
  * alpha.2 (M-2300; #2973's agent requests, junsion's §6): on a fleet with no chat connection there is no General to
3223
3378
  * post an agent's Windows request in — it waited for `agend settings confirm` on the host. Its owner (decision
@@ -3593,13 +3748,25 @@ export class FleetManager {
3593
3748
  return updateNativeWindowsInstance(this, name, edit, () => allowed() && sameTarget() && (execution.completed || execution.current()), execution);
3594
3749
  } });
3595
3750
  }
3751
+ /**
3752
+ * D3: whether a General could take this change's confirmation card now — the same authority and routes
3753
+ * promptSettingsChange posts by. False: it would wait for the host's command (confirmation kind host_cli).
3754
+ */
3755
+ settingsCardPossible(store, id) {
3756
+ const authority = this.settingsChatAuthority(store, id);
3757
+ if (!authority)
3758
+ return false;
3759
+ const excluded = new Set(store.affectedConnections(id));
3760
+ return Object.keys(this.fleetConfig?.instances ?? {}).some(name => !!this.settingsGeneralRoute(name, authority.platform, excluded));
3761
+ }
3596
3762
  async promptSettingsChange(store, view) {
3597
3763
  const generation = this.settingsGeneration;
3598
3764
  const authority = this.settingsChatAuthority(store, view.id);
3599
3765
  if (!authority) {
3600
3766
  this.logger.info({ id: view.id }, "Settings authority is unknown or spans platforms; host CLI confirmation required");
3601
- return;
3767
+ return this.settingsNoCardReason(null, [...store.affectedConnections(view.id), ...(store.authorityOf(view.id)?.connections ?? [])], false);
3602
3768
  }
3769
+ let attempted = false;
3603
3770
  const excluded = new Set(store.affectedConnections(view.id));
3604
3771
  for (const name of Object.keys(this.fleetConfig?.instances ?? {})) {
3605
3772
  const route = this.settingsGeneralRoute(name, authority.platform, excluded);
@@ -3612,6 +3779,7 @@ export class FleetManager {
3612
3779
  && route.current() && authority.current();
3613
3780
  if (!current())
3614
3781
  continue;
3782
+ attempted = true;
3615
3783
  try {
3616
3784
  const posted = this.postNonceButtonPromptOrThrow({ prefix: "settings-confirm:", alertType: "clear_confirm",
3617
3785
  instanceName: name, adapterId, adapter, chatId, threadId: topic,
@@ -3655,6 +3823,39 @@ export class FleetManager {
3655
3823
  }
3656
3824
  // No platform confirmation was reachable. Host inspection is still required.
3657
3825
  this.logger.info({ id: view.id }, "Settings change requires local `agend settings confirm <id>`");
3826
+ return this.settingsNoCardReason(authority.platform, store.affectedConnections(view.id), attempted);
3827
+ }
3828
+ /**
3829
+ * alpha.6 feedback #2c: why no General could take a change's confirm card, so the page says what is missing in plain words
3830
+ * (the user's decision hmsg-77256f66: never "type a host command"). `platform` null: the authority is unknown or spans
3831
+ * platforms. `attempted`: a General route existed and posting to it failed.
3832
+ */
3833
+ settingsNoCardReason(platform, affected, attempted) {
3834
+ const channels = this.fleetConfig?.channels ?? (this.fleetConfig?.channel ? [this.fleetConfig.channel] : []);
3835
+ if (!channels.length)
3836
+ return "no_chat";
3837
+ if (attempted)
3838
+ return "post_failed";
3839
+ // No General at all comes first: then there is no authority to resolve either (the primary General's is unknown).
3840
+ if (!Object.values(this.fleetConfig?.instances ?? {}).some(cfg => cfg?.general_topic === true))
3841
+ return "no_general";
3842
+ // #3352 review N1: "spans platforms" only when it does — the connections the change touches are on more than one platform.
3843
+ // Any other unresolved authority (a duplicated or missing connection id): no specific reason; the page says the general one.
3844
+ if (!platform) {
3845
+ const touched = new Set(affected);
3846
+ const types = new Set(channels.filter(ch => touched.has(ch.id ?? ch.type)).map(ch => ch.type));
3847
+ return types.size > 1 ? "cross_platform" : undefined;
3848
+ }
3849
+ const excluded = new Set(affected);
3850
+ const generals = Object.keys(this.fleetConfig?.instances ?? {}).filter(name => this.fleetConfig?.instances[name]?.general_topic === true)
3851
+ .filter(name => { const id = this.getInstanceAdapterId(name), adapter = this.getAdapterForInstance(name); return !!id && !!adapter && adapter.type === platform && !excluded.has(id); });
3852
+ if (!generals.length)
3853
+ return "no_general";
3854
+ if (!generals.some(name => this.adapterState.get(this.getInstanceAdapterId(name))?.status === "connected"))
3855
+ return "chat_disconnected";
3856
+ if (!generals.some(name => !!this.getGroupIdForInstance(name) && String(this.fleetConfig?.instances[name]?.topic_id ?? "") !== ""))
3857
+ return "no_topic";
3858
+ return "post_failed";
3658
3859
  }
3659
3860
  kiroMigrateDeps() {
3660
3861
  let token;
@@ -5058,6 +5259,7 @@ export class FleetManager {
5058
5259
  finishStartup(bootUpdateMarker = null) {
5059
5260
  this.startupComplete = true;
5060
5261
  this.startNeedsYou();
5262
+ this.startSignInKeepAlive();
5061
5263
  // Resolve whatever a previous run — or a setup host that crashed — left
5062
5264
  // behind. A tunnel nobody is tracking is a public entrance nobody is
5063
5265
  // watching, and the fleet starting is the moment there is finally a process
@@ -7511,6 +7713,7 @@ export class FleetManager {
7511
7713
  }
7512
7714
  classicBehaviorUpdate(instanceName) {
7513
7715
  return {
7716
+ quota_notice: this.classicChannels?.getQuotaNoticeByInstance?.(instanceName) ?? null,
7514
7717
  reply_triggers: this.classicChannels?.getReplyTriggersByInstance(instanceName, this.fleetConfig?.defaults?.reply_triggers) ?? DEFAULT_REPLY_TRIGGERS,
7515
7718
  tool_progress: this.classicChannels?.getToolProgressByInstance(instanceName, this.fleetConfig?.defaults?.tool_progress) ?? "off",
7516
7719
  reply_completion_guard: this.classicChannels?.getReplyCompletionGuardByInstance(instanceName, this.fleetConfig?.defaults?.reply_completion_guard) ?? true,
@@ -7662,6 +7865,9 @@ export class FleetManager {
7662
7865
  resumePaused = false,
7663
7866
  /** Phase 2a: the caller's transition, for a start made from inside a restart or wake. */
7664
7867
  transition, execution, kiroMigration) {
7868
+ // M-2457 §6: no agent starts on a held tmux server (an old one AgEnD could not prove its own may still run it).
7869
+ if (this.tmuxHold)
7870
+ throw new Error(this.tmuxHold.detail);
7665
7871
  if (isNativeExecInstance(config)) {
7666
7872
  execution?.assert();
7667
7873
  if (!windowsCliEnabled())
@@ -7775,14 +7981,26 @@ export class FleetManager {
7775
7981
  }
7776
7982
  const receipt = execution ? this.classicSettingsOwners.get(execution) : undefined;
7777
7983
  const identity = { kind, backend, model: isWindowsInstance(config) ? config.model || "default" : this.resolveInstanceModel(name).display };
7778
- if (receipt) {
7779
- await this.lifecycle.start(name, config, topicMode, identity, transition, execution, daemon => {
7780
- // Only this transition's actual publication can acquire its replacement.
7781
- receipt.daemon = daemon;
7782
- });
7984
+ // M-2457 §6 rule 3: an old 2.3 window AgEnD can't prove its own holds only this instance (Needs-you says why).
7985
+ try {
7986
+ if (receipt) {
7987
+ await this.lifecycle.start(name, config, topicMode, identity, transition, execution, daemon => {
7988
+ // Only this transition's actual publication can acquire its replacement.
7989
+ receipt.daemon = daemon;
7990
+ });
7991
+ }
7992
+ else
7993
+ await this.lifecycle.start(name, config, topicMode, identity, transition, execution);
7783
7994
  }
7784
- else
7785
- await this.lifecycle.start(name, config, topicMode, identity, transition, execution);
7995
+ catch (err) {
7996
+ if (err instanceof LegacyWindowHoldError) {
7997
+ this.legacyWindowHolds.set(name, { key: `legacy:${Date.now()}`, detail: err.message, since: Date.now() });
7998
+ this.needsYou?.poke();
7999
+ }
8000
+ throw err;
8001
+ }
8002
+ if (this.legacyWindowHolds.delete(name))
8003
+ this.needsYou?.poke();
7786
8004
  execution?.assert();
7787
8005
  // Only clear a stale process status after a real start succeeded. Clearing
7788
8006
  // it before lifecycle.start() can turn a crash-loop daemon's dead pane into
@@ -10245,7 +10463,7 @@ export class FleetManager {
10245
10463
  }
10246
10464
  async startAllWithinDeadline(configPath, deadline) {
10247
10465
  if (!this.structuredLoginCleanupFailed)
10248
- this.loginWindow.reopen(); // a stopAll → startAll restart must accept login windows again
10466
+ this.reopenLoginWindow(); // a stopAll → startAll restart must accept login windows again
10249
10467
  this.loginController?.reopen();
10250
10468
  const startupStartedAt = Date.now();
10251
10469
  FleetManager.signalTarget = this;
@@ -10300,11 +10518,64 @@ export class FleetManager {
10300
10518
  // #2910: a web-only fleet's agents run in topic mode too (their cross-instance tools work; the dashboard is their place).
10301
10519
  const topicMode = daemonTopicMode(fleet);
10302
10520
  // Set tmux socket isolation for custom AGEND_HOME
10303
- // M-2457: the bundled tmux's socket while it is on; getTmuxSocketName() as before while off.
10304
- const { tmuxSocket } = await import("./tmux-binary.js");
10521
+ // M-2457: AgEnD's own tmux socket (`agend` for the real home).
10522
+ const { tmuxSocket, resolveTmux } = await import("./tmux-binary.js");
10305
10523
  TmuxManager.setSocketName(tmuxSocket());
10306
- await TmuxManager.ensureSession(getTmuxSession());
10307
- this.tmuxSessionEnsured = true;
10524
+ // M-2457 §6 rule 3: 2.3's window ids (untagged window-id files) move into the migration journal before anything —
10525
+ // a stop, a pane check, a restart — can read one as a window on AgEnD's own server.
10526
+ try {
10527
+ const { sweepLegacyWindowIds } = await import("./tmux-legacy.js");
10528
+ const moved = sweepLegacyWindowIds(getAgendHome(), Object.keys(fleet.instances ?? {}).map(name => ({ name, dir: this.getInstanceDir(name) })), tmuxSocket());
10529
+ if (moved.length)
10530
+ this.logger.info({ instances: moved }, "2.3 tmux window ids moved to the migration journal");
10531
+ }
10532
+ catch (err) {
10533
+ this.logger.warn({ err }, "Could not move 2.3 tmux window ids to the migration journal; each instance does it as it starts");
10534
+ }
10535
+ // M-2457 §6 rule 2: a server from another pin still on the socket is ended by its own recorded
10536
+ // client, positively, before ours starts; one AgEnD cannot prove its own holds the whole fleet (nothing is killed).
10537
+ const bundled = await (async () => {
10538
+ const srv = await import("./tmux-server.js");
10539
+ const binary = resolveTmux().binary;
10540
+ return { srv, socket: tmuxSocket(), current: { binary, sha256: srv.sha256File(binary) }, previous: srv.readServerRecord(getAgendHome()) };
10541
+ })();
10542
+ // M-2457 §5 (Fable #3312 N3): an upgraded home — agents ran here before (their output or session ids are on disk
10543
+ // from an earlier start) and no AgEnD tmux server was ever recorded — gets the one own-tmux notice. A cleanly stopped
10544
+ // 2.3 fleet leaves no window ids (no migration journal), so this, not the journal, is the evidence. Read before any
10545
+ // agent of this start writes its own.
10546
+ // Persisted before this start records server.json (see ownTmuxStartDecision).
10547
+ this.ownTmuxUpgradedHome = FleetManager.ownTmuxStartDecision(getAgendHome(), bundled.previous, this.logger);
10548
+ this.tmuxHold = null;
10549
+ TmuxManager.setHold(null);
10550
+ if (bundled) {
10551
+ const reason = await bundled.srv.reconcileServer({ agendHome: getAgendHome(), socket: bundled.socket, current: bundled.current,
10552
+ log: (msg, data) => this.logger.info(data ?? {}, msg) });
10553
+ if (reason) {
10554
+ this.tmuxHold = { key: `server:${Date.now()}`, detail: reason, since: Date.now() };
10555
+ TmuxManager.setHold(reason); // every other way in (sign-in/install windows, a daemon) is refused too
10556
+ this.logger.error({ reason }, "Fleet held: AgEnD's previous tmux server can't be verified; no agent starts");
10557
+ }
10558
+ }
10559
+ if (!this.tmuxHold) {
10560
+ await TmuxManager.ensureSession(getTmuxSession());
10561
+ this.tmuxSessionEnsured = true;
10562
+ if (bundled) {
10563
+ await bundled.srv.recordServer({ agendHome: getAgendHome(), socket: bundled.socket, current: bundled.current, version: "",
10564
+ log: (msg, data) => this.logger.warn(data ?? {}, msg) });
10565
+ // A server AgEnD starts later (the session re-created after the server crashed) is recorded the same way, so
10566
+ // server.json always names the server that runs (leg M: an unrecorded server made `agend rollback` refuse).
10567
+ TmuxManager.onSessionCreated(async () => {
10568
+ const r = await bundled.srv.recordServer({ agendHome: getAgendHome(), socket: bundled.socket, current: bundled.current, version: "",
10569
+ log: (msg, data) => this.logger.warn(data ?? {}, msg) });
10570
+ if (r)
10571
+ this.logger.info({ serverPid: r.serverPid }, "tmux server recorded (session created)");
10572
+ });
10573
+ // The current copy and the one the previous server ran (kept for a handover/rollback); older ones go.
10574
+ const removed = bundled.srv.pruneCopies(getAgendHome(), [bundled.current.binary, ...(bundled.previous ? [bundled.previous.binary] : [])]);
10575
+ if (removed.length)
10576
+ this.logger.info({ removed }, "Pruned old bundled tmux copies");
10577
+ }
10578
+ }
10308
10579
  // #2072: what this host can run — probed in the background, published for every picker.
10309
10580
  this.startAvailabilityRefresh();
10310
10581
  // Pre-flight (advisory, fire-and-forget): warm the per-backend auth cache
@@ -10316,7 +10587,7 @@ export class FleetManager {
10316
10587
  return { backend, profile: credentialHomeSpec(backend) ? instanceCredentialProfile(config, fleet.defaults, backend) : null };
10317
10588
  }));
10318
10589
  // Start tmux control mode client for idle detection
10319
- if (!this.controlClient) {
10590
+ if (!this.controlClient && !this.tmuxHold) {
10320
10591
  this.controlClient = new TmuxControlClient(getTmuxSession(), 2000, this.logger);
10321
10592
  this.controlClient.start();
10322
10593
  }
@@ -10329,25 +10600,26 @@ export class FleetManager {
10329
10600
  // windows from deleted instances that are no longer in fleet.yaml.
10330
10601
  const agendNames = new Set(Object.keys(fleet.instances));
10331
10602
  agendNames.add("general");
10332
- try {
10333
- const existingWindows = await TmuxManager.listWindows(getTmuxSession());
10334
- for (const w of existingWindows) {
10335
- // Kill known instance windows (will be recreated)
10336
- // Also kill orphaned windows: any window with a topic ID suffix (name-tNNNNN)
10337
- // that isn't in the current config — these are leftovers from deleted instances
10338
- const isKnownInstance = agendNames.has(w.name);
10339
- const isOrphanedInstance = !isKnownInstance && isOrphanInstanceWindowName(w.name);
10340
- if (isKnownInstance || isOrphanedInstance) {
10341
- if (isOrphanedInstance)
10342
- this.logger.info({ window: w.name }, "Cleaning up orphaned tmux window");
10343
- const tm = new TmuxManager(getTmuxSession(), w.id);
10344
- await tm.killWindow();
10603
+ if (!this.tmuxHold)
10604
+ try {
10605
+ const existingWindows = await TmuxManager.listWindows(getTmuxSession());
10606
+ for (const w of existingWindows) {
10607
+ // Kill known instance windows (will be recreated)
10608
+ // Also kill orphaned windows: any window with a topic ID suffix (name-tNNNNN)
10609
+ // that isn't in the current config — these are leftovers from deleted instances
10610
+ const isKnownInstance = agendNames.has(w.name);
10611
+ const isOrphanedInstance = !isKnownInstance && isOrphanInstanceWindowName(w.name);
10612
+ if (isKnownInstance || isOrphanedInstance) {
10613
+ if (isOrphanedInstance)
10614
+ this.logger.info({ window: w.name }, "Cleaning up orphaned tmux window");
10615
+ const tm = new TmuxManager(getTmuxSession(), w.id);
10616
+ await tm.killWindow();
10617
+ }
10345
10618
  }
10346
10619
  }
10347
- }
10348
- catch (err) {
10349
- this.logger.debug({ err }, "Startup tmux window cleanup failed (best effort)");
10350
- }
10620
+ catch (err) {
10621
+ this.logger.debug({ err }, "Startup tmux window cleanup failed (best effort)");
10622
+ }
10351
10623
  const pidPath = join(this.dataDir, "fleet.pid");
10352
10624
  writeFileSync(pidPath, String(process.pid), "utf-8");
10353
10625
  this.eventLog = this.openEventLog();
@@ -10555,14 +10827,15 @@ export class FleetManager {
10555
10827
  }
10556
10828
  }
10557
10829
  // Phase 1: Start general instances first and wait for them
10558
- const allEntries = Object.entries(fleet.instances).filter(([, config]) => !isNativeExecInstance(config));
10830
+ // M-2457: a held fleet starts no agent (the hold's Needs-you line says why and what to do).
10831
+ const allEntries = this.tmuxHold ? [] : Object.entries(fleet.instances).filter(([, config]) => !isNativeExecInstance(config));
10559
10832
  const generals = allEntries.filter(([_, cfg]) => cfg.general_topic);
10560
10833
  const others = allEntries.filter(([_, cfg]) => !cfg.general_topic);
10561
- const startupProgress = new RestartProgress(this.runnableStartupCount(fleet, topicMode), pendingUpdateProgress?.startedAt ?? startupStartedAt, this.logger, { mode: pendingProgressOperation === "full-restart" ? "reload" : pendingUpdateProgress ? "update" : "restart" });
10834
+ const startupProgress = new RestartProgress(this.tmuxHold ? 0 : this.runnableStartupCount(fleet, topicMode), pendingUpdateProgress?.startedAt ?? startupStartedAt, this.logger, { mode: pendingProgressOperation === "full-restart" ? "reload" : pendingUpdateProgress ? "update" : "restart" });
10562
10835
  this.startupProgress = startupProgress;
10563
10836
  // Auth, restored chat, Classic roster and the task DB are ready. Listening is not service readiness:
10564
10837
  // the dashboard observes startup, while /health and READY retain their existing completion boundary.
10565
- this.startupDashboard = new FleetStartup(this.configuredStartupInstanceNames(fleet, topicMode)
10838
+ this.startupDashboard = new FleetStartup(this.tmuxHold ? [] : this.configuredStartupInstanceNames(fleet, topicMode)
10566
10839
  .filter(name => !this.lifecycle.isPaused(name)));
10567
10840
  await this.startHealthServer(fleet.health_port ?? 19280);
10568
10841
  if (this.shuttingDown)
@@ -10807,6 +11080,8 @@ export class FleetManager {
10807
11080
  // #1266: buttons that ended while AgEnD was down (expired, or chosen before a restart) are shown as ended now.
10808
11081
  // #1823: and polls: a deadline that passed meanwhile closes now (results once); an open one's countdown is redrawn.
10809
11082
  void this.replyButtons()?.sweep().catch(err => this.logger.warn({ err }, "Reply-button sweep failed"));
11083
+ // M-2457 §5: the first start on AgEnD's own tmux says so, once per home: `tmux attach` no longer shows the agents.
11084
+ this.announceOwnTmux();
10810
11085
  // Daily update check — first check after 1 hour, then every 24 hours
10811
11086
  this.updateCheckTimer = setTimeout(() => {
10812
11087
  this.checkForUpdates();
@@ -10856,7 +11131,47 @@ export class FleetManager {
10856
11131
  * Discord bot and while some account has a running agent, read every 30 min — the same cached read (its 5-minute TTL
10857
11132
  * still bounds the vendor calls), recorded like any other.
10858
11133
  */
11134
+ quotaNotices = null;
11135
+ stopQuotaObserver = null;
11136
+ quotaNoticePolicy() {
11137
+ const defaults = this.fleetConfig?.defaults.quota_notice;
11138
+ const wanted = defaults?.target ?? "general";
11139
+ const instances = this.fleetConfig?.instances ?? {};
11140
+ const target = wanted === "general"
11141
+ ? Object.entries(instances).find(([name, c]) => c.general_topic === true || name === "general")?.[0]
11142
+ : Object.hasOwn(instances, wanted) ? wanted : undefined;
11143
+ const webOnly = !!this.webOnlyPromptPlace();
11144
+ const config = target ? instances[target] : undefined;
11145
+ const adapterId = target ? this.getInstanceAdapterId(target) : undefined;
11146
+ const groupId = target ? this.getChannelConfig(adapterId)?.group_id : undefined;
11147
+ const ready = !!target && (webOnly || (config?.topic_id != null && !!groupId && !!(this.getAdapterForInstance(target) ?? this.adapter)));
11148
+ return {
11149
+ target: this.shuttingDown ? "" : ready ? target : !target && wanted === "general" && webOnly ? "/notices" : "",
11150
+ destinationBinding: JSON.stringify([webOnly, adapterId, groupId, config?.topic_id]),
11151
+ locale: this.fleetConfig?.defaults.locale ?? getLocale(),
11152
+ subscriptions: this.shuttingDown ? [] : this.activeBackendBindings().flatMap(([name, backend, profile]) => {
11153
+ // Local WSL usage cannot prove a Windows/paired machine's credential source.
11154
+ const instance = instances[name];
11155
+ if (instance?.runtime === "windows" || instance?.machine_id)
11156
+ return [];
11157
+ const provider = usageProviderIdForBackend(backend);
11158
+ if (!provider)
11159
+ return [];
11160
+ const providerId = profile ? `${provider}:${profile}` : provider;
11161
+ return [{ account: `${backend}:host:${profile ?? ""}`, providerId,
11162
+ rule: quotaNoticeRule(defaults, backend, instances[name]?.quota_notice ?? this.classicChannels?.getQuotaNoticeByInstance?.(name)) }];
11163
+ }),
11164
+ };
11165
+ }
10859
11166
  startQuotaBackgroundReads() {
11167
+ if (!this.quotaNotices) {
11168
+ this.quotaNotices = new QuotaNotices({
11169
+ file: join(this.dataDir, "quota-notices.json"), policy: () => this.quotaNoticePolicy(),
11170
+ send: (target, text) => target === "/notices" ? this.recordWebNotice("fleet", text) : this.notifyInstanceTopic(target, text),
11171
+ warn: err => this.logger.warn({ err }, "Optional quota reminders held: could not retain dispatch state"),
11172
+ });
11173
+ this.stopQuotaObserver = onUsageSnapshot(payload => { void this.quotaNotices?.observe(payload); });
11174
+ }
10860
11175
  if (this.quotaReadTimer)
10861
11176
  clearInterval(this.quotaReadTimer);
10862
11177
  this.quotaReadTimer = setInterval(() => { void this.backgroundQuotaRead(); }, FleetManager.QUOTA_BACKGROUND_READ_MS);
@@ -11200,6 +11515,8 @@ export class FleetManager {
11200
11515
  const state = this.adapterState.get(adapterId);
11201
11516
  if (this.shuttingDown || !state || state.retryTimer || this.adapterRetryInFlight.has(adapterId))
11202
11517
  return;
11518
+ if (this.adapterTeardownUnknown.has(adapterId))
11519
+ return; // #3365 review P2: held until a restart, never retried
11203
11520
  const delay = Math.min(INITIAL_DELAY_MS * Math.pow(2, Math.min(state.retryCount, 6)), MAX_DELAY_MS);
11204
11521
  this.logger.info({ adapterId, attempt: state.retryCount + 1, delay_ms: delay }, "Scheduling adapter retry");
11205
11522
  const timer = setTimeout(() => {
@@ -11454,6 +11771,8 @@ export class FleetManager {
11454
11771
  assertSettingsLease(`connection:${this.dataDir}:${ownerId}`, operation?.owner);
11455
11772
  if (this.shuttingDown || this.settingsGeneration !== generation)
11456
11773
  throw new Error("adapter admission superseded");
11774
+ if (this.adapterTeardownUnknown.has(ownerId))
11775
+ throw new Error("an earlier adapter for this connection could not be confirmed stopped — restart AgEnD");
11457
11776
  };
11458
11777
  check();
11459
11778
  const botToken = process.env[channelConfig.bot_token_env];
@@ -11613,6 +11932,8 @@ export class FleetManager {
11613
11932
  assertSettingsLease(`connection:${this.dataDir}:${ownerId}`, operation?.owner);
11614
11933
  if (this.shuttingDown || this.settingsGeneration !== generation)
11615
11934
  throw new Error("adapter admission superseded");
11935
+ if (this.adapterTeardownUnknown.has(ownerId))
11936
+ throw new Error("an earlier adapter for this connection could not be confirmed stopped — restart AgEnD");
11616
11937
  };
11617
11938
  check();
11618
11939
  const botToken = process.env[channelConfig.bot_token_env];
@@ -16829,6 +17150,74 @@ export class FleetManager {
16829
17150
  }
16830
17151
  return { chatId, opts: {} };
16831
17152
  }
17153
+ /**
17154
+ * M-2457 §5: one fleet notice, the first time an upgraded home's fleet runs on AgEnD's own tmux. Marked done only once it
17155
+ * was dispatched (General, the channel's notice target, or a web-only fleet's Notices), so a start with nowhere to
17156
+ * post it tries again next start.
17157
+ */
17158
+ /** Set at fleet start (before any agent starts): this home ran agents on an earlier AgEnD's system tmux. */
17159
+ ownTmuxUpgradedHome = false;
17160
+ /** An upgraded home: agent state from an earlier start, and no AgEnD tmux server ever recorded (`previous`). */
17161
+ static ownTmuxUpgraded(agendHome, previous) {
17162
+ return previous === null && FleetManager.priorAgentState(join(agendHome, "instances"));
17163
+ }
17164
+ /** Whether any instance directory holds state from an earlier start (its output log or a session id). */
17165
+ static priorAgentState(instancesDir) {
17166
+ let names = [];
17167
+ try {
17168
+ names = readdirSync(instancesDir);
17169
+ }
17170
+ catch {
17171
+ return false;
17172
+ }
17173
+ return names.some(n => ["output.log", "session-id"].some(f => existsSync(join(instancesDir, n, f))));
17174
+ }
17175
+ /** Where an upgraded home's not-yet-dispatched own-tmux notice is kept across restarts; only a dispatch clears it. */
17176
+ static ownTmuxPendingPath(agendHome) { return join(agendHome, "tmux", "own-server-notice-pending"); }
17177
+ /**
17178
+ * Fleet start's decision, made before this start records server.json: an upgraded home is persisted as owing the
17179
+ * notice. A restart before the notice is dispatched (a slow first start; alpha.6 leg M on the real Mac) would otherwise
17180
+ * read the just-recorded server as "not an upgrade" and drop it.
17181
+ */
17182
+ static ownTmuxStartDecision(agendHome, previous, logger) {
17183
+ const upgraded = FleetManager.ownTmuxUpgraded(agendHome, previous);
17184
+ if (upgraded)
17185
+ FleetManager.persistOwnTmuxPending(agendHome, logger);
17186
+ return upgraded;
17187
+ }
17188
+ /** Record that this home owes the own-tmux notice (unless it was already posted). */
17189
+ static persistOwnTmuxPending(agendHome, logger) {
17190
+ if (existsSync(join(agendHome, "tmux", "own-server-announced")))
17191
+ return;
17192
+ try {
17193
+ mkdirSync(join(agendHome, "tmux"), { recursive: true });
17194
+ writeFileSync(FleetManager.ownTmuxPendingPath(agendHome), `${new Date().toISOString()}\n`);
17195
+ }
17196
+ catch (err) {
17197
+ logger?.warn({ err }, "Could not record the pending own-tmux notice");
17198
+ }
17199
+ }
17200
+ announceOwnTmux() {
17201
+ const marker = join(getAgendHome(), "tmux", "own-server-announced");
17202
+ const pending = FleetManager.ownTmuxPendingPath(getAgendHome());
17203
+ if (existsSync(marker))
17204
+ return;
17205
+ // Only a home an earlier AgEnD ran its agents in (on the system tmux) has something to be told (Fable #3312 N3):
17206
+ // agent state from before this start and no recorded AgEnD tmux server (set at fleet start), or a migration journal
17207
+ // (2.3 window ids found). A fresh home is marked without a notice.
17208
+ // A pending notice persisted by an earlier start counts too: that start's server record must not hide the upgrade.
17209
+ const upgraded = this.ownTmuxUpgradedHome || existsSync(pending) || existsSync(join(getAgendHome(), "tmux-migration.json"));
17210
+ if (upgraded && !this.notifyFleetError(t("tmux.own_server_notice"), { throttle: false }))
17211
+ return;
17212
+ try {
17213
+ mkdirSync(dirname(marker), { recursive: true });
17214
+ writeFileSync(marker, `${new Date().toISOString()}\n`);
17215
+ rmSync(pending, { force: true });
17216
+ }
17217
+ catch (err) {
17218
+ this.logger.warn({ err }, "Could not record that the own-tmux notice was posted");
17219
+ }
17220
+ }
16832
17221
  /**
16833
17222
  * Post the daily summary where fleet-wide notices go.
16834
17223
  *
@@ -17745,12 +18134,16 @@ export class FleetManager {
17745
18134
  acknowledgeMissed: (id, by) => this.missedOfflineStore?.acknowledge(id, by) ?? false,
17746
18135
  tasks: () => this.needsYouTaskItems(),
17747
18136
  backendSignIns: () => this.needsYouBackendSignIns(),
18137
+ signInKeepAlive: () => this.keepAliveAttention(),
17748
18138
  hubExecution: () => this.hubExecutionAttention?.() ?? [],
18139
+ runtimeUpdates: () => remoteRuntimeEnabled() ? runtimeUpdateAttention(this.runtimeHub?.listMachines() ?? [], t, this.worlds.keys().next().value) : [],
17749
18140
  hubHolds: () => this.hubHolds.map(h => {
17750
18141
  // A provider hold carries a bounded setup reason; its guidance (S4b's copy) when present, else the code's text.
17751
18142
  const guidance = h.reason ? t(`hub.provider.${h.reason}`) : "";
17752
18143
  return { side: h.side, code: h.code, since: h.since, detail: guidance && guidance !== `hub.provider.${h.reason}` ? guidance : t(`hub.hold.${h.code}`) };
17753
18144
  }),
18145
+ tmuxHolds: () => [...(this.tmuxHold ? [{ instance: null, ...this.tmuxHold }] : []),
18146
+ ...[...this.legacyWindowHolds].map(([instance, h]) => ({ instance, ...h }))],
17754
18147
  configIssues: () => (this.configHistory?.currentIssues() ?? []).map(issue => ({
17755
18148
  ...issue, detail: configIssueText(issue, t), owner: this.worlds.keys().next().value,
17756
18149
  })),
@@ -18434,8 +18827,12 @@ export class FleetManager {
18434
18827
  const r = store.confirmEnrollment(owner.handle, code);
18435
18828
  if (r === "ok") {
18436
18829
  this.logger.info({ again: had }, "Authenticator app set up for connections from outside");
18437
- if (had)
18830
+ if (had) {
18438
18831
  this.endOutsideSessions();
18832
+ // #3327: an authenticator set up again is announced where the owner looks (web Notices on a web-only fleet), so a
18833
+ // set-up they did not make is noticed.
18834
+ this.notifyFleetError(t("outside.reenrolled_notice"));
18835
+ }
18439
18836
  }
18440
18837
  return r;
18441
18838
  }
@@ -18445,8 +18842,11 @@ export class FleetManager {
18445
18842
  if (!owner || !store || !owner.current())
18446
18843
  return "not_here";
18447
18844
  // #3008 review (Prism P2 1): shut at once whatever the disk says; say so when it could not be saved (retried).
18845
+ const had = store.enrolled;
18448
18846
  const saved = store.remove();
18449
18847
  this.closeOutsideLink("outside removed");
18848
+ if (had)
18849
+ this.notifyFleetError(t("outside.removed_notice")); // #3327: as above
18450
18850
  this.logger.info({ saved }, "Authenticator app removed; connections from outside off");
18451
18851
  return saved ? "ok" : "unsaved";
18452
18852
  }
@@ -20279,6 +20679,43 @@ export class FleetManager {
20279
20679
  }
20280
20680
  return this.loginController;
20281
20681
  }
20682
+ /**
20683
+ * #3190 Part 3c: dashboard sign-ins on a paired computer (machine-signins.ts): #3212's StructuredSignIn over a RuntimeSignInTransport, one computer and one
20684
+ * credential profile at a time. Its own coordinator, not the host's: it never touches the host's sign-in checklist or login window.
20685
+ */
20686
+ machineSignInsInstance = null;
20687
+ get machineSignIns() {
20688
+ return this.machineSignInsInstance ??= new MachineSignIns({
20689
+ call: (id, operation, payload, timeoutMs) => this.runtimeCoordinator().callAccount(id, operation, payload, timeoutMs),
20690
+ current: owner => this.browserSignInOwnerCurrent(owner),
20691
+ reported: (id, profile) => this.machineAccounts.profileState(id, profile),
20692
+ readiness: id => this.machineAccounts.readiness(id),
20693
+ actor: owner => { const handle = owner.handle; return typeof handle === "string" && /^[a-f0-9]{16}$/.test(handle) ? `admin:${handle}` : null; },
20694
+ changed: (event, owner) => {
20695
+ // Safe fields only: the computer, the profile name, a phase and a fixed reason. Never a URL, a code, output or an e-mail address.
20696
+ this.logger.info({ machine: event.machine, profile: event.profile, phase: event.phase, ...(event.reason ? { reason: event.reason } : {}), by: owner.label }, "Computer account sign-in from Settings → Accounts");
20697
+ broadcastSseEvent(this.sseClients, "backend_login", {}, err => this.logger.debug({ err }, "backend_login event failed"));
20698
+ this.needsYou?.poke();
20699
+ },
20700
+ });
20701
+ }
20702
+ machineAccountsInstance = null;
20703
+ /** #3190 Part 3c: a paired computer's accounts in Settings → Accounts (machine-accounts.ts). */
20704
+ get machineAccounts() {
20705
+ return this.machineAccountsInstance ??= new MachineAccounts({
20706
+ call: (id, operation, payload, timeoutMs) => this.runtimeCoordinator().callAccount(id, operation, payload, timeoutMs),
20707
+ machine: id => remoteRuntimeEnabled() ? this.runtimeCoordinator().machine(id) ?? undefined : undefined,
20708
+ machines: () => remoteRuntimeEnabled() ? this.runtimeCoordinator().listMachines() : [],
20709
+ agents: id => machineAgents(this.fleetConfig?.instances, id, name => { try {
20710
+ return nativeCredentialProfile(this.fleetConfig?.instances[name]) ?? null;
20711
+ }
20712
+ catch {
20713
+ return null;
20714
+ } }, this.fleetConfig?.defaults?.backend ?? "claude-code"),
20715
+ signingIn: (id, profile) => this.machineSignInsInstance?.signingIn(id, profile) ?? false,
20716
+ log: entry => this.logger.info(entry, entry.outcome === "ok" ? "Computer account changed from Settings → Accounts" : "Computer account change refused"),
20717
+ });
20718
+ }
20282
20719
  browserBackendSignInsInstance = null;
20283
20720
  structuredLoginCleanupFailed = false;
20284
20721
  pendingBackendSince = new Map();
@@ -20434,8 +20871,6 @@ export class FleetManager {
20434
20871
  * usage is the usage panel's cached read (never forced), given at most `usageWaitMs` before the view is sent without it.
20435
20872
  */
20436
20873
  async accountsView(usageWaitMs = 1500) {
20437
- const fleet = this.fleetConfig;
20438
- const defaultBackend = fleet?.defaults?.backend ?? "claude-code";
20439
20874
  this.refreshSignInIdentities();
20440
20875
  const targets = this.backendSignInTargets();
20441
20876
  const diskProfiles = new Map();
@@ -20455,19 +20890,7 @@ export class FleetManager {
20455
20890
  }
20456
20891
  diskProfiles.set(backend, rows);
20457
20892
  }
20458
- // Host agents only: an agent on a paired Windows computer runs on that computer's accounts (its own scope, later).
20459
- const agents = Object.keys(fleet?.instances ?? {}).filter(name => !isWindowsInstance(fleet.instances[name])).sort()
20460
- .map(name => { const backend = this.backendNameForInstance(name); return { name, backend, profile: this.credentialProfileOf(name, backend) }; });
20461
- const classic = readClassicBindings(this.dataDir).map(b => {
20462
- const backend = b.backend ?? defaultBackend;
20463
- return { key: b.key, backend, profile: profileName(classicProfile(b.backend_options, fleet?.defaults?.backend_options, backend)) };
20464
- });
20465
- const fleetDefaults = new Map();
20466
- for (const backend of PROFILE_CLIS) {
20467
- const p = profileName(profileOf(fleet?.defaults?.backend_options, backend));
20468
- if (p)
20469
- fleetDefaults.set(backend, p);
20470
- }
20893
+ const { agents, classic, fleetDefaults } = this.accountUses();
20471
20894
  // Weekly usage, from the usage panel's own (cached, never forced) read.
20472
20895
  const usage = new Map();
20473
20896
  const ids = new Map(); // provider id → backend\0profile
@@ -20489,7 +20912,437 @@ export class FleetManager {
20489
20912
  }
20490
20913
  }
20491
20914
  catch { /* the view without usage */ }
20492
- return buildAccountsView({ targets, diskProfiles, agents, classic, fleetDefaults, usage });
20915
+ // #3292: each Claude Code / Codex row's "Keep sign-in alive" part (the setting, its last run, the dates its file says).
20916
+ const keepAlive = new Map();
20917
+ const ka = this.keepAliveService();
20918
+ for (const backend of ACCOUNT_CLIS) {
20919
+ if (!isKeepAliveBackend(backend))
20920
+ continue;
20921
+ for (const profile of [null, ...new Set([...(diskProfiles.get(backend) ?? []).map(d => d.profile), ...targets.filter(t => t.backend === backend && t.profile).map(t => t.profile)])]) {
20922
+ const v = ka.view(backend, profile);
20923
+ if (v)
20924
+ keepAlive.set(`${backend}\0${profile ?? ""}`, v);
20925
+ }
20926
+ }
20927
+ // #3190 Part 3c: each paired computer's accounts, as rows under the `machine` scope. Read from what the computers reported; the view never waits long for one.
20928
+ // (Keep-alive is the host's: it is built from the host's profiles above and never given to a computer's rows.)
20929
+ let machines = [];
20930
+ if (remoteRuntimeEnabled()) {
20931
+ try {
20932
+ machines = await this.machineAccounts.list();
20933
+ }
20934
+ catch (err) {
20935
+ this.logger.debug({ err: err.message }, "Computer accounts not read");
20936
+ }
20937
+ }
20938
+ return buildAccountsView({ targets, diskProfiles, agents, classic, fleetDefaults, usage, keepAlive, machines });
20939
+ }
20940
+ /** #3292: the keep-alive service (built on first use, so the Accounts view can read settings before startup finishes). */
20941
+ keepAliveService() {
20942
+ return this.signInKeepAlive ??= new SignInKeepAlive({
20943
+ dataDir: this.dataDir,
20944
+ log: (level, msg, fields) => this.logger[level](fields, msg),
20945
+ homeOf: (backend, profile) => profile ? credentialProfileHome(this.dataDir, backend, profile) : credentialHomeSpec(backend)?.sharedRoot() ?? null,
20946
+ acquire: (backend, profile) => this.acquireKeepAliveRun(backend, profile),
20947
+ changed: () => {
20948
+ this.needsYou?.poke();
20949
+ // #3313 review P2-7: the Accounts view reads itself again on `backend_login` (no details: each page reads its own
20950
+ // view). That event, not a new one: a tab whose cached shell predates this still passes it on.
20951
+ broadcastSseEvent(this.sseClients, "backend_login", {}, err => this.logger.debug({ err }, "backend_login event failed"));
20952
+ },
20953
+ claudeKeychain: process.platform === "darwin",
20954
+ });
20955
+ }
20956
+ startSignInKeepAlive() { this.keepAliveService().start(); }
20957
+ /**
20958
+ * #3292 review: which sign-in each host agent is starting or running on, recorded at its start (InstanceLifecycle
20959
+ * admitCredentialUse) from the configuration it launched with — never re-resolved against today's defaults. An entry
20960
+ * whose start ended without a daemon, or whose daemon is gone, is dropped when next read.
20961
+ */
20962
+ credentialLeases = new Map();
20963
+ /** #3292 review: Keep sign-in alive runs in flight, by sign-in: a start on that sign-in waits for its end. */
20964
+ keepAliveRenewing = new Map();
20965
+ credentialKey(backend, profile) { return `${backend}\0${(profile ?? "").toLowerCase()}`; }
20966
+ /**
20967
+ * The sign-in a start launches on, from the instance's own (defaults-expanded at load) options — exactly what the
20968
+ * Daemon's clone of that config hands its CLI. Never today's defaults: an older config object keeps its own.
20969
+ */
20970
+ launchCredentialKey(config, backend) {
20971
+ let profile = null;
20972
+ try {
20973
+ profile = resolveCredentialProfile(config.backend_options?.[backend]);
20974
+ }
20975
+ catch {
20976
+ profile = null;
20977
+ }
20978
+ return this.credentialKey(backend, profile);
20979
+ }
20980
+ /**
20981
+ * #3313 review r2: failed starts whose CLI was not proven gone keep holding their sign-in (across a retry of the same
20982
+ * agent too) until a check finds it ended.
20983
+ */
20984
+ credentialOrphans = new Map();
20985
+ orphanCheck = null;
20986
+ recheckCredentialOrphans() {
20987
+ if (this.orphanCheck || !this.credentialOrphans.size)
20988
+ return;
20989
+ this.orphanCheck = (async () => {
20990
+ for (const [id, o] of [...this.credentialOrphans]) {
20991
+ let gone = false;
20992
+ try {
20993
+ gone = await o.ended();
20994
+ }
20995
+ catch {
20996
+ gone = false;
20997
+ }
20998
+ if (gone)
20999
+ this.credentialOrphans.delete(id);
21000
+ }
21001
+ })().finally(() => { this.orphanCheck = null; });
21002
+ }
21003
+ /**
21004
+ * LifecycleContext: hold the sign-in a start will launch on (waits while Keep sign-in alive renews it). The key is
21005
+ * read again after every wait; `current(config)` lets the start check, with no await before it builds its Daemon,
21006
+ * that the config still names that sign-in (a save may have changed it meanwhile: then it asks again).
21007
+ */
21008
+ async admitCredentialUse(name, config, backend, assertCurrent) {
21009
+ if (!isKeepAliveBackend(backend) || isWindowsInstance(config))
21010
+ return null;
21011
+ let key = this.launchCredentialKey(config, backend);
21012
+ for (let renewing = this.keepAliveRenewing.get(key); renewing; renewing = this.keepAliveRenewing.get(key)) {
21013
+ await renewing;
21014
+ assertCurrent();
21015
+ key = this.launchCredentialKey(config, backend);
21016
+ }
21017
+ const lease = { key, starting: true };
21018
+ this.credentialLeases.set(name, lease);
21019
+ const drop = () => { if (this.credentialLeases.get(name) === lease)
21020
+ this.credentialLeases.delete(name); };
21021
+ return {
21022
+ published: () => { lease.starting = false; },
21023
+ release: drop,
21024
+ current: c => this.launchCredentialKey(c, backend) === key,
21025
+ // A failed start whose CLI may still run: the sign-in stays held (by itself, not by the agent's name) until it is seen gone.
21026
+ unknownEnd: ended => { drop(); this.credentialOrphans.set(Symbol(name), { key, ended }); this.recheckCredentialOrphans(); },
21027
+ };
21028
+ }
21029
+ /**
21030
+ * #3292: a sign-in is in use when a host agent is starting or running on it (as launched), a ClassicBot room is bound
21031
+ * to it (or the rooms cannot be read — none when there is no classicBot.yaml), or a sign-in for it is running. Codex
21032
+ * refresh tokens are single-use: a refresh beside a live user could spend the one it holds; and use keeps it alive.
21033
+ */
21034
+ keepAliveInUse(backend, profile) {
21035
+ const key = this.credentialKey(backend, profile);
21036
+ for (const o of this.credentialOrphans.values())
21037
+ if (o.key === key) {
21038
+ this.recheckCredentialOrphans();
21039
+ return true;
21040
+ }
21041
+ for (const [name, lease] of [...this.credentialLeases]) {
21042
+ if (!lease.starting && !this.daemons?.has(name)) {
21043
+ this.credentialLeases.delete(name);
21044
+ continue;
21045
+ }
21046
+ if (lease.key === key)
21047
+ return true;
21048
+ }
21049
+ const same = (p) => profile === null ? !p : !!p && p.toLowerCase() === profile.toLowerCase();
21050
+ const defaults = this.fleetConfig?.defaults, defaultBackend = defaults?.backend ?? "claude-code";
21051
+ // A running agent with no record (started some other way): only its own setting is trusted; none names an account, so it may be on any.
21052
+ for (const [name, daemon] of this.daemons ?? []) {
21053
+ if (this.credentialLeases.has(name))
21054
+ continue;
21055
+ let snap;
21056
+ try {
21057
+ snap = daemon.getConfigSnapshot?.();
21058
+ }
21059
+ catch {
21060
+ snap = undefined;
21061
+ }
21062
+ if (snap && isWindowsInstance(snap))
21063
+ continue;
21064
+ if (!snap)
21065
+ return true;
21066
+ if ((snap.backend ?? defaultBackend) !== backend)
21067
+ continue;
21068
+ let own = null;
21069
+ try {
21070
+ own = resolveCredentialProfile(snap.backend_options?.[backend]);
21071
+ }
21072
+ catch {
21073
+ return true;
21074
+ }
21075
+ if (!own || same(own))
21076
+ return true;
21077
+ }
21078
+ const rooms = readClassicBindingsStrict(this.dataDir);
21079
+ if (rooms.kind === "unknown")
21080
+ return true;
21081
+ for (const b of rooms.kind === "ok" ? rooms.bindings : []) {
21082
+ const cli = b.backend ?? defaultBackend;
21083
+ if (cli === backend && same(profileName(classicProfile(b.backend_options, defaults?.backend_options, cli))))
21084
+ return true;
21085
+ }
21086
+ return this.loginController?.signingIn(backend, profile) ?? false;
21087
+ }
21088
+ /**
21089
+ * #3292 review: one keep-alive run's admission, decided synchronously: not in use, the shared login window taken, and the
21090
+ * sign-in marked as renewing (a start on it waits). The run's life is an account writer: a stop waits for it, and
21091
+ * sign-in admission reopens after a restart only once it has ended. `release()` only after its CLI has exited.
21092
+ */
21093
+ acquireKeepAliveRun(backend, profile) {
21094
+ if (this.keepAliveInUse(backend, profile))
21095
+ return "in_use";
21096
+ const claim = this.loginWindow.tryClaim("keepalive", backend);
21097
+ if (!claim)
21098
+ return "busy";
21099
+ const key = this.credentialKey(backend, profile);
21100
+ let finished;
21101
+ const life = new Promise(r => { finished = r; });
21102
+ this.keepAliveRenewing.set(key, life);
21103
+ this.accountWriters.add(life);
21104
+ let released = false;
21105
+ return {
21106
+ release: () => {
21107
+ if (released)
21108
+ return;
21109
+ released = true;
21110
+ this.loginWindow.release(claim);
21111
+ if (this.keepAliveRenewing.get(key) === life)
21112
+ this.keepAliveRenewing.delete(key);
21113
+ this.accountWriters.delete(life);
21114
+ finished();
21115
+ },
21116
+ };
21117
+ }
21118
+ /** #3292: Needs you's lines for kept sign-ins, in the fleet's language (posted in General's world, like config issues). */
21119
+ keepAliveAttention() {
21120
+ const ka = this.signInKeepAlive;
21121
+ if (!ka)
21122
+ return [];
21123
+ const day = (ms) => ms === undefined ? "?" : new Date(ms).toISOString().slice(0, 10);
21124
+ const owner = this.worlds.keys().next().value;
21125
+ return ka.attention().map(a => ({
21126
+ backend: a.backend, profile: a.profile, kind: a.kind, since: a.since, signIn: dashboardSignInSupported(a.backend, a.profile),
21127
+ ...(owner ? { owner } : {}),
21128
+ detail: t(`keepalive.${a.kind}`, BACKEND_LABELS[a.backend] ?? a.backend, a.profile ?? t("keepalive.default_name"), day(a.kind === "transient" ? a.failedSince ?? a.since : a.endsAt)),
21129
+ }));
21130
+ }
21131
+ /** #3292: Settings → Accounts → Keep sign-in alive (POST /ui/accounts/keep-alive). `by`: the session's label, for the fleet log. */
21132
+ setAccountKeepAlive(backend, profile, enabled, fallback, by) {
21133
+ const r = this.keepAliveService().set(backend, profile, enabled, fallback);
21134
+ if (r.ok)
21135
+ this.logger.info({ backend, profile: profile ?? "(default)", enabled, by }, "Keep sign-in alive changed from Settings → Accounts");
21136
+ return r;
21137
+ }
21138
+ /**
21139
+ * Who uses which account: host agents (an agent on a paired Windows computer runs on that computer's accounts — its
21140
+ * own scope), ClassicBot rooms and the fleet default per CLI, each with its effective profile (null: the default sign-in).
21141
+ */
21142
+ accountUses() {
21143
+ const fleet = this.fleetConfig;
21144
+ const defaultBackend = fleet?.defaults?.backend ?? "claude-code";
21145
+ const agents = Object.keys(fleet?.instances ?? {}).filter(name => !isWindowsInstance(fleet.instances[name])).sort()
21146
+ .map(name => { const backend = this.backendNameForInstance(name); return { name, backend, profile: this.credentialProfileOf(name, backend) }; });
21147
+ const classic = readClassicBindings(this.dataDir).map(b => {
21148
+ const backend = b.backend ?? defaultBackend;
21149
+ return { key: b.key, backend, profile: profileName(classicProfile(b.backend_options, fleet?.defaults?.backend_options, backend)) };
21150
+ });
21151
+ const fleetDefaults = new Map();
21152
+ for (const backend of PROFILE_CLIS) {
21153
+ const p = profileName(profileOf(fleet?.defaults?.backend_options, backend));
21154
+ if (p)
21155
+ fleetDefaults.set(backend, p);
21156
+ }
21157
+ return { agents, classic, fleetDefaults };
21158
+ }
21159
+ /** #3212 PR 2: Settings → Accounts → + Add account (accounts-profiles.ts). `by`: the session's label, for the fleet log. */
21160
+ addAccountProfile(backend, name, by, machine) {
21161
+ // #3190 Part 3c: on a paired computer the profile's folder is made by its Runtime when the first sign-in starts; this only checks what can be checked first.
21162
+ if (machine)
21163
+ return this.machineAccounts.add(backend, name, machine.id, by);
21164
+ const { agents, classic, fleetDefaults } = this.accountUses();
21165
+ const configured = new Set();
21166
+ for (const x of [...agents, ...classic])
21167
+ if (x.backend === backend && x.profile)
21168
+ configured.add(x.profile);
21169
+ const fd = fleetDefaults.get(backend);
21170
+ if (fd)
21171
+ configured.add(fd);
21172
+ const result = addAccountProfile(this.dataDir, backend, name, configured);
21173
+ if (result.ok)
21174
+ this.logger.info({ backend, profile: name, by }, "Credential profile added from Settings → Accounts");
21175
+ return result;
21176
+ }
21177
+ /**
21178
+ * #3212 PR 2: Settings → Accounts → Remove. Refused while anything uses it or a sign-in for it runs (the login controller,
21179
+ * or the login window held for this backend by a sign-in whose profile is not known yet); see accounts-profiles.ts.
21180
+ * The fleet log records who removed which backend's profile — never what was in it.
21181
+ */
21182
+ async removeAccountProfile(backend, name, confirm, by, machine) {
21183
+ if (machine)
21184
+ return this.machineAccounts.remove(backend, name, confirm, machine.id, machine, by); // #3190 Part 3c: that computer's Runtime deletes its own folder
21185
+ const profile = typeof name === "string" ? name : "";
21186
+ const shown = validCredentialProfileName(name) ? name : "(invalid)";
21187
+ const refused = (r) => { if (!r.ok)
21188
+ this.logger.info({ backend, profile: shown, by, refused: r.error }, "Credential profile removal refused"); return r; };
21189
+ // #3212 PR 3: on macOS, Claude Code keeps the account's token in the Keychain, outside the folder — its own logout
21190
+ // (run with the folder, once every Remove check has passed) removes that item first. AgEnD never deletes it itself.
21191
+ // #3305 review: the logout holds the shared login window (no sign-in or other logout starts meanwhile), and after it
21192
+ // every check is made again — who uses it, sign-ins, ClassicBot's settings — on the same folder (its identity).
21193
+ const signOutDeps = this.accountSignOutDeps ?? ACCOUNT_SIGN_OUT_DEPS;
21194
+ let keychainLeft = false;
21195
+ let removed;
21196
+ if (backend === "claude-code" && signOutDeps.platform === "darwin") {
21197
+ const dry = removeAccountProfile(this.dataDir, this.removalRequest(backend, name, confirm, null), undefined, { dryRun: true });
21198
+ if (!dry.ok)
21199
+ return refused(dry);
21200
+ const claim = this.loginWindow.tryClaim("web", backend);
21201
+ if (!claim)
21202
+ return refused({ ok: false, error: "signing_in" });
21203
+ const step = await this.withAccountWriter(claim, async (deps) => {
21204
+ const out = await signOutAccount(this.dataDir, { backend, profile, confirm: true, signingIn: false }, deps);
21205
+ if (!out.ok)
21206
+ return { ok: false, error: out.error === "unsafe" ? "unsafe" : "failed" };
21207
+ if (!this.loginWindow.isCurrent(claim))
21208
+ return { ok: false, error: "failed" }; // the fleet is stopping
21209
+ keychainLeft = out.keychainLeft === true;
21210
+ return removeAccountProfile(this.dataDir, this.removalRequest(backend, name, confirm, claim), undefined, { expect: dry.identity });
21211
+ });
21212
+ if (!step.ok)
21213
+ return refused(step);
21214
+ removed = step;
21215
+ }
21216
+ else
21217
+ removed = removeAccountProfile(this.dataDir, this.removalRequest(backend, name, confirm, null));
21218
+ if (!removed.ok)
21219
+ return refused(removed);
21220
+ this.logger.info({ backend, profile, by, ...(keychainLeft ? { keychainLeft } : {}) }, "Credential profile removed from Settings → Accounts");
21221
+ return keychainLeft ? { ok: true, keychainLeft: true } : { ok: true };
21222
+ }
21223
+ /**
21224
+ * Remove's whole safety proof, read now (#3291 review): who uses the account — configured agents and live daemons, the
21225
+ * fleet default, ClassicBot rooms read strictly — and whether a sign-in for it runs. `ownClaim`: the login window this
21226
+ * removal holds itself, which is not someone else's sign-in.
21227
+ */
21228
+ removalRequest(backend, name, confirm, ownClaim) {
21229
+ const profile = typeof name === "string" ? name : "";
21230
+ // #3291 review (Prism P2-3): one folder on a case-insensitive disk (Windows, default macOS) — `Work` and `work` are the
21231
+ // same account for every safety check here.
21232
+ const same = (p) => !!p && p.toLowerCase() === profile.toLowerCase();
21233
+ const { agents, fleetDefaults } = this.accountUses();
21234
+ const defaultBackend = this.fleetConfig?.defaults?.backend ?? "claude-code";
21235
+ // #3291 review (Prism P2-2): ClassicBot rooms read strictly — an unreadable or malformed classicBot.yaml is not "no rooms".
21236
+ const rooms = readClassicBindingsStrict(this.dataDir);
21237
+ const classic = rooms.kind === "ok" ? rooms.bindings.map(b => {
21238
+ const cli = b.backend ?? defaultBackend;
21239
+ return { key: b.key, backend: cli, profile: profileName(classicProfile(b.backend_options, this.fleetConfig?.defaults?.backend_options, cli)) };
21240
+ }) : [];
21241
+ // #3291 review (Prism P2-1): what a running CLI was launched with. An agent or room moved off this account keeps
21242
+ // running on it until its process stops (the configuration changes first): it is still a user until then.
21243
+ const live = [];
21244
+ for (const [instance, daemon] of this.daemons ?? []) {
21245
+ let snap;
21246
+ try {
21247
+ snap = daemon.getConfigSnapshot?.();
21248
+ }
21249
+ catch {
21250
+ snap = undefined;
21251
+ }
21252
+ if (!snap || isWindowsInstance(snap))
21253
+ continue;
21254
+ const cli = snap.backend ?? defaultBackend;
21255
+ if (cli !== backend)
21256
+ continue;
21257
+ let launched = null;
21258
+ try {
21259
+ launched = resolveCredentialProfile(snap.backend_options?.[cli]);
21260
+ }
21261
+ catch {
21262
+ launched = null;
21263
+ }
21264
+ if (same(launched))
21265
+ live.push(instance);
21266
+ }
21267
+ const users = {
21268
+ agents: [...new Set([...agents.filter(a => a.backend === backend && same(a.profile)).map(a => a.name), ...live])].sort(),
21269
+ classic: classic.filter(c => c.backend === backend && same(c.profile)).map(c => c.key),
21270
+ fleetDefault: same(fleetDefaults.get(backend)),
21271
+ };
21272
+ const held = this.loginWindow.current;
21273
+ const signingIn = (this.loginController?.signingIn(backend, profile) ?? false)
21274
+ || (!!held && held !== ownClaim && held.backend === backend && !this.loginController?.activeBackend);
21275
+ return { backend, name, confirm, users, signingIn, usersUnknown: rooms.kind === "unknown" };
21276
+ }
21277
+ /**
21278
+ * #3212 PR 3: Settings → Accounts → Sign out (accounts-signout.ts): the CLI's own logout for the default sign-in
21279
+ * (`profile` null) or a named account. Refused while a sign-in for it runs (case-insensitive, as Remove). The fleet
21280
+ * log records who signed out which backend's account; then every page reads the sign-ins again.
21281
+ */
21282
+ /** How a CLI's logout is run and the Keychain asked (a test's stand-in; the platform with it). */
21283
+ accountSignOutDeps = ACCOUNT_SIGN_OUT_DEPS;
21284
+ /** #3305 review: every account logout's whole life — its CLI children until positively gone (shutdown drains them). */
21285
+ accountWriters = new Set();
21286
+ /**
21287
+ * #3305 review P2-3/P2-5: run `work` as the owner of the credential writer (`claim`). Its CLIs run through a runner
21288
+ * that records each child's positive end; the work is told whether it still owns the writer (`stillOwner`) before it
21289
+ * cleans anything; and the claim is released only once every child it started is positively gone — a child whose end
21290
+ * is unknown keeps sign-in admission closed (logged). Shutdown waits for these (shutdownLoginWindows), and a restart
21291
+ * reopens admission only after they are gone.
21292
+ */
21293
+ async withAccountWriter(claim, work) {
21294
+ const base = this.accountSignOutDeps ?? ACCOUNT_SIGN_OUT_DEPS;
21295
+ const children = [];
21296
+ const watch = async (r) => { if (r.gone)
21297
+ children.push(r.gone); return r; };
21298
+ const deps = {
21299
+ platform: base.platform,
21300
+ run: async (b, a, e) => watch(await base.run(b, a, e)),
21301
+ keychainHas: base.keychainHas,
21302
+ stillOwner: () => this.loginWindow.isCurrent(claim),
21303
+ };
21304
+ let finished;
21305
+ const life = new Promise(r => { finished = r; });
21306
+ this.accountWriters.add(life);
21307
+ try {
21308
+ return await work(deps);
21309
+ }
21310
+ finally {
21311
+ const settle = () => { this.loginWindow.release(claim); this.accountWriters.delete(life); finished(); };
21312
+ if (!children.length)
21313
+ settle();
21314
+ else {
21315
+ let warned = false;
21316
+ const t = setTimeout(() => { warned = true; this.logger.error("An account logout's CLI has not ended: sign-in stays closed until it does"); }, 30_000);
21317
+ t.unref?.();
21318
+ void Promise.all(children).then(() => { clearTimeout(t); if (warned)
21319
+ this.logger.info("The account logout's CLI ended: sign-in is open again"); settle(); });
21320
+ }
21321
+ }
21322
+ }
21323
+ async signOutAccount(backend, profile, confirm, by, machine) {
21324
+ if (machine)
21325
+ return this.machineAccounts.signOut(backend, profile, confirm, machine.id, machine, by); // #3190 Part 3c: that computer's Runtime runs the CLI's own logout
21326
+ const named = typeof profile === "string" ? profile : null;
21327
+ const shown = named === null ? "(default)" : validCredentialProfileName(named) ? named : "(invalid)";
21328
+ // #3305 review P2-3: the logout holds the shared login window from before it runs until its cleanup is done — no
21329
+ // sign-in (chat, dashboard, install) and no other logout starts meanwhile; one already running refuses this.
21330
+ const signingIn = this.loginController?.signingIn(backend, named) ?? false;
21331
+ const claim = signingIn ? null : this.loginWindow.tryClaim("web", backend);
21332
+ let result;
21333
+ if (!claim)
21334
+ result = { ok: false, error: "signing_in" };
21335
+ else
21336
+ result = await this.withAccountWriter(claim, deps => signOutAccount(this.dataDir, { backend, profile: profile ?? null, confirm, signingIn: false }, deps));
21337
+ if (result.ok) {
21338
+ this.logger.info({ backend, profile: shown, by, ...(result.keychainLeft ? { keychainLeft: true } : {}) }, "Account signed out from Settings → Accounts");
21339
+ this.forgetSignInIdentities();
21340
+ void this.backendAvailability.refresh([backend], { force: true }).catch(() => { });
21341
+ broadcastSseEvent(this.sseClients, "backend_login", {}, err => this.logger.debug({ err }, "backend_login event failed"));
21342
+ }
21343
+ else
21344
+ this.logger.info({ backend, profile: shown, by, refused: result.error }, "Account sign-out refused");
21345
+ return result;
20493
21346
  }
20494
21347
  backendSignInTargets() {
20495
21348
  const out = [];
@@ -20795,11 +21648,32 @@ export class FleetManager {
20795
21648
  return this.webLogin.start(backendArg, chat, opts);
20796
21649
  }
20797
21650
  /** Fleet shutdown: end any web login or install window and wait for its confirmed teardown. */
21651
+ /**
21652
+ * #3305 review P2-3: reopen sign-in admission after a restart — only once no account logout's CLI from before is still
21653
+ * alive (a fresh sign-in must never overlap it). Each reopen supersedes a deferred one.
21654
+ */
21655
+ loginReopenGen = 0;
21656
+ reopenLoginWindow() {
21657
+ const gen = ++this.loginReopenGen;
21658
+ const pending = [...this.accountWriters];
21659
+ if (!pending.length) {
21660
+ this.loginWindow.reopen();
21661
+ return;
21662
+ }
21663
+ this.logger.warn({ pending: pending.length }, "Sign-in admission reopens once an account logout from before the restart has ended");
21664
+ void Promise.all(pending).then(() => { if (gen === this.loginReopenGen && !this.structuredLoginCleanupFailed)
21665
+ this.loginWindow.reopen(); });
21666
+ }
20798
21667
  async shutdownLoginWindows() {
21668
+ // #3305 review: a newer stop supersedes a reopen still waiting for an old account logout's CLI.
21669
+ this.loginReopenGen++;
20799
21670
  // Close the lock FIRST: in-flight starts parked in a pre-check or
20800
21671
  // ensureSession observe !isCurrent when they resume and stop; no new
20801
21672
  // window can be claimed while we stop.
20802
21673
  this.loginWindow.close();
21674
+ // #3292 review: Keep sign-in alive stops asking for runs and stops its CLI; its run's life is an account writer,
21675
+ // waited for below like an account logout.
21676
+ void this.signInKeepAlive?.stop();
20803
21677
  // Completion semantics live INSIDE the sessions: each awaits its own
20804
21678
  // confirmed cleanup, every tmux op on that path has a hard per-op bound
20805
21679
  // (web: abort ≤10 s + kill ≤31 s; legacy: create/list/kill ≤10 s each,
@@ -20836,8 +21710,17 @@ export class FleetManager {
20836
21710
  this.logger.error("Structured login cleanup failed; sign-in admission remains closed until the host is restarted.");
20837
21711
  }
20838
21712
  }), "browser-controls"),
21713
+ // #3190 Part 3c: a sign-in running on a paired computer is ended (its Runtime also ends it when the connection goes). One that could not be shown gone is logged.
21714
+ bounded(this.machineSignInsInstance?.close().then(confirmed => {
21715
+ if (confirmed)
21716
+ this.machineSignInsInstance = null;
21717
+ else
21718
+ this.logger.error("A computer's account sign-in could not be confirmed ended; check that computer's Runtime window.");
21719
+ }), "machine-signins"),
20839
21720
  bounded(this.loginController?.shutdown(), "web-login"),
20840
21721
  bounded(this.activeInstall?.session.cancel("cancelled"), "install"),
21722
+ // #3305 review P2-3: an account logout in flight (its CLI) — the closed window fences its cleanup; this waits for it.
21723
+ bounded(this.accountWriters.size ? Promise.all([...this.accountWriters]).then(() => undefined) : undefined, "account-logout"),
20841
21724
  ]);
20842
21725
  }
20843
21726
  /** `/login cancel` — abort the active session and remove its window. */
@@ -22095,7 +22978,11 @@ export class FleetManager {
22095
22978
  // re-enters this path.
22096
22979
  const selfMentionRe = new RegExp(`<@${adapterBotUserId}>`, "g");
22097
22980
  const strippedText = text.replace(selfMentionRe, "").trim();
22098
- if (!strippedText && !msg.attachments?.length)
22981
+ // A bare @mention says nothing by itself, so it is dropped (unchanged)... unless it is a REPLY that carries the mention: then the
22982
+ // replied-to message is what is being asked about, and it travels as reply_to_text (#3340). Telegram already forwards this shape
22983
+ // ("/chat @bot (you)"). Only with the mention in the text: an empty reply to one of our own messages (addressed through #2551, a
22984
+ // sticker or embed only) stays dropped, never an empty turn quoting our own answer (Fable #3342 F1).
22985
+ if (!strippedText && !msg.attachments?.length && !(msg.replyToText && mentionTag && addressText.includes(mentionTag)))
22099
22986
  return;
22100
22987
  const selfMarker = mentionWorld?.botUsername ? `@${mentionWorld.botUsername} (you)` : `${mentionTag} (you)`;
22101
22988
  const cleanText = text.replace(selfMentionRe, selfMarker).trim();
@@ -24356,6 +25243,7 @@ export class FleetManager {
24356
25243
  ...this.fleetConfig?.defaults,
24357
25244
  working_directory: workDir,
24358
25245
  lightweight: true,
25246
+ quota_notice: classicIdentity?.quotaNotice,
24359
25247
  tool_progress: toolProgress ?? "off",
24360
25248
  reply_completion_guard: replyCompletionGuard ?? true,
24361
25249
  ...(backend ? { backend } : {}),
@@ -24535,6 +25423,9 @@ export class FleetManager {
24535
25423
  // because we asked it to. Set synchronously — doStopAll runs to its first
24536
25424
  // await in the same tick as the signal handler, so no event can slip in.
24537
25425
  this.shuttingDown = true;
25426
+ this.stopQuotaObserver?.();
25427
+ this.stopQuotaObserver = null;
25428
+ const quotaNoticesStopped = this.quotaNotices?.stop();
24538
25429
  // Stop receive admission before the first await or any instance shutdown; outbound
24539
25430
  // adapters remain available below to retire notices and pending prompts.
24540
25431
  for (const state of this.adapterState.values()) {
@@ -24630,6 +25521,8 @@ export class FleetManager {
24630
25521
  await needsStopped;
24631
25522
  await settingsControlStopped;
24632
25523
  await cacheStopped;
25524
+ await quotaNoticesStopped;
25525
+ this.quotaNotices = null;
24633
25526
  await webChatStopped;
24634
25527
  await this.cpuProfileControl?.close();
24635
25528
  this.cpuProfileControl = null;
@@ -25337,7 +26230,9 @@ export class FleetManager {
25337
26230
  return {
25338
26231
  ok: false,
25339
26232
  status: 503,
25340
- 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",
26233
+ error: this.isWebOnlyFleet()
26234
+ ? "the restart rate-limit file cannot be read"
26235
+ : "the restart rate-limit file cannot be read — send /restart in General",
25341
26236
  };
25342
26237
  }
25343
26238
  return {
@@ -25367,7 +26262,7 @@ export class FleetManager {
25367
26262
  return {
25368
26263
  ok: false,
25369
26264
  status: 409,
25370
- error: "no chat channel is available to announce the restart — run `agend restart` on the host instead",
26265
+ error: "no chat channel is available to announce the restart",
25371
26266
  };
25372
26267
  }
25373
26268
  // Consume the row: it moves to running, which is also what lets the next
@@ -26195,6 +27090,9 @@ export class FleetManager {
26195
27090
  let store;
26196
27091
  const generation = this.settingsGeneration;
26197
27092
  let replaced = false;
27093
+ // S-91: whether an adapter ran before. One that did not is never "restored" by starting it with the old token (the token
27094
+ // that would not start it); a failed start goes back to the background retry instead.
27095
+ const wasRunning = this.adapters.has(job.connectionId);
26198
27096
  try {
26199
27097
  if (!channel || !envKey || !allowed.has(envKey))
26200
27098
  throw new Error("connection is not configured for secret rotation");
@@ -26244,17 +27142,29 @@ export class FleetManager {
26244
27142
  else
26245
27143
  process.env[envKey] = oldToken;
26246
27144
  }
26247
- // Build a fresh adapter from the restored token. If the old adapter
26248
- // was stopped already, this is the only safe way to return to the
26249
- // previous runtime without claiming a disk-only rollback succeeded.
26250
- const cleanup = { owner: execution?.owner ?? Symbol("secret-cleanup"), assert: () => {
26251
- if (this.shuttingDown || this.settingsGeneration !== generation)
26252
- throw new Error("secret cleanup superseded");
26253
- } };
26254
- const restored = await this.rebuildAdapterForSecret(job.connectionId, this.secureConnectionChannel(job.connectionId) ?? channel, true, cleanup);
26255
- if (!restored)
26256
- throw new Error("adapter rollback did not become connected");
26257
- job.result = "rolled_back";
27145
+ if (!wasRunning) {
27146
+ // S-91: it was not running: the new adapter that did not come up is taken down (never left half-started), and
27147
+ // the connection is the background retry's again, as before the token was entered.
27148
+ if (await this.dropAdapterAfterFailedStart(job.connectionId, message))
27149
+ job.result = "rolled_back";
27150
+ else {
27151
+ job.result = "rollback_failed";
27152
+ job.error = "the new adapter could not be confirmed stopped; restart AgEnD";
27153
+ }
27154
+ }
27155
+ else {
27156
+ // Build a fresh adapter from the restored token. If the old adapter
27157
+ // was stopped already, this is the only safe way to return to the
27158
+ // previous runtime without claiming a disk-only rollback succeeded.
27159
+ const cleanup = { owner: execution?.owner ?? Symbol("secret-cleanup"), assert: () => {
27160
+ if (this.shuttingDown || this.settingsGeneration !== generation)
27161
+ throw new Error("secret cleanup superseded");
27162
+ } };
27163
+ const restored = await this.rebuildAdapterForSecret(job.connectionId, this.secureConnectionChannel(job.connectionId) ?? channel, true, cleanup);
27164
+ if (!restored)
27165
+ throw new Error("adapter rollback did not become connected");
27166
+ job.result = "rolled_back";
27167
+ }
26258
27168
  }
26259
27169
  catch (rollbackErr) {
26260
27170
  this.logger.error({ connectionId: job.connectionId, reason: safeSecretError(rollbackErr, oldToken, [secret]) }, "Settings connection secret rollback failed");
@@ -26272,6 +27182,57 @@ export class FleetManager {
26272
27182
  secret = "";
26273
27183
  }
26274
27184
  }
27185
+ /**
27186
+ * S-91: how a connection stands against what this process set up at start. "same": its adapter start ran (and failed, or
27187
+ * found no token), so starting it now is what the background retry does. "changed": its binding waits for the restart —
27188
+ * never started live, whatever its role (#3365 review P2). "added": #1519 P6's rule.
27189
+ */
27190
+ startedWithConnection(connectionId, channel) {
27191
+ const started = this.startupFleetConfig;
27192
+ const list = started?.channels ?? (started?.channel ? [started.channel] : []);
27193
+ const then = list.find(item => (item.id ?? item.type) === connectionId);
27194
+ return !then ? "added" : isDeepStrictEqual(then, channel) ? "same" : "changed";
27195
+ }
27196
+ /**
27197
+ * S-91: a token's live start for a connection that was not running did not come up. Whatever adapter it left is taken
27198
+ * down (handlers off, stopped, unregistered), and the connection goes back to the background retry with the error.
27199
+ */
27200
+ async dropAdapterAfterFailedStart(connectionId, error) {
27201
+ const fresh = this.adapters.get(connectionId);
27202
+ // #3365 review P3: the primary's prune interval goes with it (a later start sets it up again, once).
27203
+ if (this.getPrimaryAdapterId() === connectionId && this.sessionPruneTimer) {
27204
+ clearInterval(this.sessionPruneTimer);
27205
+ this.sessionPruneTimer = null;
27206
+ }
27207
+ let stopped = true;
27208
+ if (fresh) {
27209
+ fresh.removeAllListeners();
27210
+ stopped = await fresh.stop().then(() => true, () => false);
27211
+ if (this.adapters.get(connectionId) === fresh)
27212
+ this.adapters.delete(connectionId);
27213
+ if (this.worlds.get(connectionId)?.adapter === fresh)
27214
+ this.worlds.delete(connectionId);
27215
+ if (this.adapter === fresh)
27216
+ this.adapter = null;
27217
+ }
27218
+ const previous = this.adapterState.get(connectionId);
27219
+ if (previous?.retryTimer)
27220
+ clearTimeout(previous.retryTimer);
27221
+ if (!stopped) {
27222
+ // #3365 review P2: a stop that failed leaves the provider client's end unknown (it may still poll the bot). Said so —
27223
+ // never "rolled back" — and no adapter for this connection is admitted again in this process: no retry, and every
27224
+ // start refuses it (startSingleAdapterOwned / startAdditionalAdapterOwned). A restart of AgEnD clears it.
27225
+ this.adapterTeardownUnknown.add(connectionId);
27226
+ this.adapterState.set(connectionId, { status: "failed", retryCount: previous?.retryCount ?? 0, lastError: "the new adapter could not be confirmed stopped — restart AgEnD" });
27227
+ this.logger.error({ connectionId, reason: error }, "Settings connection secret: the adapter that did not start could not be confirmed stopped");
27228
+ return false;
27229
+ }
27230
+ if (this.shuttingDown || !this.secureConnectionChannel(connectionId))
27231
+ return true;
27232
+ this.adapterState.set(connectionId, { status: "retrying", retryCount: previous?.retryCount ?? 0, lastError: error });
27233
+ this.scheduleAdapterRetry(connectionId);
27234
+ return true;
27235
+ }
26275
27236
  /** Stop the old provider client and construct a new one from process.env. */
26276
27237
  async rebuildAdapterForSecret(connectionId, channel, force = false, execution) {
26277
27238
  const generation = this.settingsGeneration;
@@ -26279,11 +27240,25 @@ export class FleetManager {
26279
27240
  const check = () => { execution?.assert(); if (!current())
26280
27241
  throw new Error("adapter operation superseded"); };
26281
27242
  check();
27243
+ // S-91: never two starts of one connection at once. A background retry in flight finishes first: it read the token
27244
+ // before this one was stored, so it gives way (its own check), or it came up and is replaced below like any adapter.
27245
+ const inFlight = this.adapterRetryInFlight.get(connectionId);
27246
+ if (inFlight) {
27247
+ await inFlight.catch(() => { });
27248
+ check();
27249
+ }
26282
27250
  const old = this.adapters.get(connectionId);
26283
- // No adapter: a connection that is not the primary, in a fleet already running connections, starts now (#1519 P6);
26284
- // otherwise the secret is valid on disk and the next start adopts it.
26285
- if (!old && !force && (this.getPrimaryAdapterId() === connectionId || this.adapters.size === 0))
26286
- return false;
27251
+ // No adapter: one this process started with, unchanged since (its start failed, or it had no token), starts now — S-91,
27252
+ // the way the background retry starts it, the primary included. One added since starts now when it is not the primary
27253
+ // and the fleet runs connections (#1519 P6). One changed since (its binding pending) never does: the secret is valid on
27254
+ // disk and the next start adopts it with its binding.
27255
+ if (!old && !force) {
27256
+ const since = this.startedWithConnection(connectionId, channel);
27257
+ if (since === "changed")
27258
+ return false;
27259
+ if (since === "added" && (this.getPrimaryAdapterId() === connectionId || this.adapters.size === 0))
27260
+ return false;
27261
+ }
26287
27262
  if (!old) {
26288
27263
  const pending = this.adapterState.get(connectionId)?.retryTimer;
26289
27264
  if (pending)
@@ -26340,10 +27315,15 @@ export class FleetManager {
26340
27315
  this.adapterState.set(connectionId, { status: "connected", retryCount: 0 });
26341
27316
  return true;
26342
27317
  }
27318
+ // S-91: a retry timer set while it was coming up (the in-flight retry's own, giving way) must not start it a second time.
27319
+ const settled = () => { const st = this.adapterState.get(connectionId); if (st?.retryTimer) {
27320
+ clearTimeout(st.retryTimer);
27321
+ st.retryTimer = undefined;
27322
+ } return true; };
26343
27323
  while (performance.now() < deadline) {
26344
27324
  const health = fresh.getHealthSnapshot?.();
26345
27325
  if (health?.status === "connected" || this.adapterState.get(connectionId)?.status === "connected")
26346
- return true;
27326
+ return settled();
26347
27327
  await new Promise(resolve => setTimeout(resolve, 100));
26348
27328
  check();
26349
27329
  }