@songsid/agend 2.4.0-beta.23 → 2.4.0-beta.25

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 (499) hide show
  1. package/README.md +1 -1
  2. package/README.zh-TW.md +1 -1
  3. package/dist/agend-home.js +5 -5
  4. package/dist/agend-home.js.map +1 -1
  5. package/dist/agent-cli-instructions.md +4 -3
  6. package/dist/agent-cli.js +32 -2
  7. package/dist/agent-cli.js.map +1 -1
  8. package/dist/agent-endpoint.js +10 -0
  9. package/dist/agent-endpoint.js.map +1 -1
  10. package/dist/agent-file-read.js +2 -2
  11. package/dist/agent-file-read.js.map +1 -1
  12. package/dist/agent-whats-new.js +11 -1
  13. package/dist/agent-whats-new.js.map +1 -1
  14. package/dist/agent-workspace.d.ts +18 -2
  15. package/dist/agent-workspace.js +15 -4
  16. package/dist/agent-workspace.js.map +1 -1
  17. package/dist/backend/antigravity.js +8 -6
  18. package/dist/backend/antigravity.js.map +1 -1
  19. package/dist/backend/claude-code.d.ts +15 -0
  20. package/dist/backend/claude-code.js +25 -3
  21. package/dist/backend/claude-code.js.map +1 -1
  22. package/dist/backend/claude-mcp-carry.d.ts +63 -0
  23. package/dist/backend/claude-mcp-carry.js +242 -0
  24. package/dist/backend/claude-mcp-carry.js.map +1 -0
  25. package/dist/backend/claude-usage-credits.d.ts +8 -0
  26. package/dist/backend/claude-usage-credits.js +121 -0
  27. package/dist/backend/claude-usage-credits.js.map +1 -0
  28. package/dist/backend/types.d.ts +30 -0
  29. package/dist/backend/types.js.map +1 -1
  30. package/dist/build-provenance.json +1 -1
  31. package/dist/channel/adapters/discord.js +7 -1
  32. package/dist/channel/adapters/discord.js.map +1 -1
  33. package/dist/channel/mcp-tools.js +7 -6
  34. package/dist/channel/mcp-tools.js.map +1 -1
  35. package/dist/channel/tool-router.js +1 -0
  36. package/dist/channel/tool-router.js.map +1 -1
  37. package/dist/cli-audited.js +9 -4
  38. package/dist/cli-audited.js.map +1 -1
  39. package/dist/cli.js +184 -21
  40. package/dist/cli.js.map +1 -1
  41. package/dist/config-validator.js +17 -1
  42. package/dist/config-validator.js.map +1 -1
  43. package/dist/config.js +2 -0
  44. package/dist/config.js.map +1 -1
  45. package/dist/contact-auth-store.d.ts +18 -0
  46. package/dist/contact-auth-store.js +55 -8
  47. package/dist/contact-auth-store.js.map +1 -1
  48. package/dist/contact-auth-types.d.ts +3 -0
  49. package/dist/contact-auth-types.js.map +1 -1
  50. package/dist/contact-change-proposals.d.ts +34 -0
  51. package/dist/contact-change-proposals.js +1 -1
  52. package/dist/contact-change-proposals.js.map +1 -1
  53. package/dist/cross-instance-notice.d.ts +1 -0
  54. package/dist/cross-instance-notice.js +9 -8
  55. package/dist/cross-instance-notice.js.map +1 -1
  56. package/dist/daemon.d.ts +46 -0
  57. package/dist/daemon.js +299 -33
  58. package/dist/daemon.js.map +1 -1
  59. package/dist/dashboard-permissions.d.ts +8 -0
  60. package/dist/dashboard-permissions.js +8 -0
  61. package/dist/dashboard-permissions.js.map +1 -1
  62. package/dist/delivery-outbox.d.ts +56 -1
  63. package/dist/delivery-outbox.js +254 -22
  64. package/dist/delivery-outbox.js.map +1 -1
  65. package/dist/fleet-context.d.ts +8 -0
  66. package/dist/fleet-lock.d.ts +67 -2
  67. package/dist/fleet-lock.js +236 -2
  68. package/dist/fleet-lock.js.map +1 -1
  69. package/dist/fleet-manager.d.ts +177 -6
  70. package/dist/fleet-manager.js +1203 -75
  71. package/dist/fleet-manager.js.map +1 -1
  72. package/dist/fleet-windows-runtime.d.ts +20 -1
  73. package/dist/fleet-windows-runtime.js +98 -18
  74. package/dist/fleet-windows-runtime.js.map +1 -1
  75. package/dist/general-knowledge/skills/concepts/SKILL.md +22 -9
  76. package/dist/general-knowledge/skills/credential-profiles/SKILL.md +6 -0
  77. package/dist/general-knowledge/skills/cross-instance-messaging/SKILL.md +7 -0
  78. package/dist/general-knowledge/skills/fleet-config/SKILL.md +3 -3
  79. package/dist/general-knowledge/skills/instance-lifecycle/SKILL.md +1 -1
  80. package/dist/general-knowledge/skills/task-board/SKILL.md +17 -0
  81. package/dist/general-knowledge/skills/web-appearance/SKILL.md +4 -0
  82. package/dist/general-knowledge/skills/web-dashboard/SKILL.md +35 -7
  83. package/dist/home-update-lock.d.ts +35 -0
  84. package/dist/home-update-lock.js +81 -0
  85. package/dist/home-update-lock.js.map +1 -0
  86. package/dist/hub/compose/member.d.ts +5 -1
  87. package/dist/hub/compose/member.js +9 -5
  88. package/dist/hub/compose/member.js.map +1 -1
  89. package/dist/hub/group-policy/resources.d.ts +1 -1
  90. package/dist/hub/member/room-ask.d.ts +5 -0
  91. package/dist/hub/member/room-ask.js +43 -16
  92. package/dist/hub/member/room-ask.js.map +1 -1
  93. package/dist/hub/member/room-mention-feedback.d.ts +2 -0
  94. package/dist/hub/member/room-mention-feedback.js +1 -1
  95. package/dist/hub/member/room-mention-feedback.js.map +1 -1
  96. package/dist/hub/member/room-post-answers.d.ts +2 -0
  97. package/dist/hub/member/room-post-answers.js +1 -1
  98. package/dist/hub/member/room-post-answers.js.map +1 -1
  99. package/dist/hub/member/room-post.d.ts +5 -0
  100. package/dist/hub/member/room-post.js +4 -1
  101. package/dist/hub/member/room-post.js.map +1 -1
  102. package/dist/hub/member/updates.d.ts +7 -1
  103. package/dist/hub/member/updates.js +7 -1
  104. package/dist/hub/member/updates.js.map +1 -1
  105. package/dist/hub/representative.d.ts +7 -0
  106. package/dist/hub/representative.js +38 -5
  107. package/dist/hub/representative.js.map +1 -1
  108. package/dist/install-lock.d.ts +15 -1
  109. package/dist/install-lock.js +16 -8
  110. package/dist/install-lock.js.map +1 -1
  111. package/dist/install-ownership.d.ts +165 -0
  112. package/dist/install-ownership.js +404 -0
  113. package/dist/install-ownership.js.map +1 -0
  114. package/dist/instance-config-impact.js +2 -0
  115. package/dist/instance-config-impact.js.map +1 -1
  116. package/dist/instance-lifecycle.d.ts +2 -0
  117. package/dist/instance-lifecycle.js +29 -1
  118. package/dist/instance-lifecycle.js.map +1 -1
  119. package/dist/instructions.d.ts +4 -0
  120. package/dist/instructions.js +4 -0
  121. package/dist/instructions.js.map +1 -1
  122. package/dist/local-pane-endpoint.d.ts +4 -1
  123. package/dist/local-pane-endpoint.js +12 -2
  124. package/dist/local-pane-endpoint.js.map +1 -1
  125. package/dist/locale.js +170 -4
  126. package/dist/locale.js.map +1 -1
  127. package/dist/native-agent-admission.d.ts +7 -0
  128. package/dist/native-agent-admission.js +46 -3
  129. package/dist/native-agent-admission.js.map +1 -1
  130. package/dist/native-mcp.d.ts +16 -1
  131. package/dist/native-mcp.js +38 -5
  132. package/dist/native-mcp.js.map +1 -1
  133. package/dist/native-pane-lifecycle.d.ts +9 -0
  134. package/dist/native-pane-lifecycle.js +23 -0
  135. package/dist/native-pane-lifecycle.js.map +1 -1
  136. package/dist/native-pane-manager.d.ts +19 -6
  137. package/dist/native-pane-manager.js +79 -4
  138. package/dist/native-pane-manager.js.map +1 -1
  139. package/dist/needs-you-hub.d.ts +3 -0
  140. package/dist/needs-you-hub.js +31 -5
  141. package/dist/needs-you-hub.js.map +1 -1
  142. package/dist/needs-you.d.ts +22 -1
  143. package/dist/needs-you.js +6 -0
  144. package/dist/needs-you.js.map +1 -1
  145. package/dist/office-share-page.js +1 -1
  146. package/dist/office-share-page.js.map +1 -1
  147. package/dist/office-share.js +2 -1
  148. package/dist/office-share.js.map +1 -1
  149. package/dist/outbound-handlers.d.ts +12 -0
  150. package/dist/outbound-handlers.js +59 -8
  151. package/dist/outbound-handlers.js.map +1 -1
  152. package/dist/outbound-schemas.d.ts +3 -0
  153. package/dist/outbound-schemas.js +7 -5
  154. package/dist/outbound-schemas.js.map +1 -1
  155. package/dist/package-preimage.js +4 -0
  156. package/dist/package-preimage.js.map +1 -1
  157. package/dist/pane-port.d.ts +1 -0
  158. package/dist/plist-args.d.ts +9 -0
  159. package/dist/plist-args.js +22 -0
  160. package/dist/plist-args.js.map +1 -0
  161. package/dist/public-preview.d.ts +4 -6
  162. package/dist/public-preview.js +5 -2
  163. package/dist/public-preview.js.map +1 -1
  164. package/dist/public-web-gateway.js +11 -3
  165. package/dist/public-web-gateway.js.map +1 -1
  166. package/dist/public-web-link.d.ts +13 -1
  167. package/dist/public-web-link.js +28 -1
  168. package/dist/public-web-link.js.map +1 -1
  169. package/dist/recover.cjs +2452 -0
  170. package/dist/remote-card-prompt.d.ts +6 -2
  171. package/dist/remote-card-prompt.js +12 -3
  172. package/dist/remote-card-prompt.js.map +1 -1
  173. package/dist/reply-draft.d.ts +12 -0
  174. package/dist/reply-draft.js +81 -0
  175. package/dist/reply-draft.js.map +1 -0
  176. package/dist/request-contact-api.d.ts +15 -0
  177. package/dist/request-contact-api.js +120 -0
  178. package/dist/request-contact-api.js.map +1 -0
  179. package/dist/request-contact-card.d.ts +36 -0
  180. package/dist/request-contact-card.js +206 -0
  181. package/dist/request-contact-card.js.map +1 -0
  182. package/dist/request-contact-gate.d.ts +79 -0
  183. package/dist/request-contact-gate.js +262 -0
  184. package/dist/request-contact-gate.js.map +1 -0
  185. package/dist/request-contact-native.d.ts +52 -0
  186. package/dist/request-contact-native.js +83 -0
  187. package/dist/request-contact-native.js.map +1 -0
  188. package/dist/request-contact-types.d.ts +86 -0
  189. package/dist/request-contact-types.js +7 -0
  190. package/dist/request-contact-types.js.map +1 -0
  191. package/dist/request-context-call-protocol.d.ts +12 -0
  192. package/dist/request-context-call-protocol.js +14 -0
  193. package/dist/request-context-call-protocol.js.map +1 -0
  194. package/dist/request-context-call.d.ts +22 -0
  195. package/dist/request-context-call.js +35 -0
  196. package/dist/request-context-call.js.map +1 -0
  197. package/dist/request-context-compatibility.d.ts +20 -0
  198. package/dist/request-context-compatibility.js +74 -0
  199. package/dist/request-context-compatibility.js.map +1 -0
  200. package/dist/request-context-drain.d.ts +39 -0
  201. package/dist/request-context-drain.js +159 -0
  202. package/dist/request-context-drain.js.map +1 -0
  203. package/dist/request-context-fence.d.ts +28 -0
  204. package/dist/request-context-fence.js +58 -0
  205. package/dist/request-context-fence.js.map +1 -0
  206. package/dist/request-context-migration.d.ts +64 -0
  207. package/dist/request-context-migration.js +158 -0
  208. package/dist/request-context-migration.js.map +1 -0
  209. package/dist/request-context-pane.d.ts +25 -0
  210. package/dist/request-context-pane.js +48 -0
  211. package/dist/request-context-pane.js.map +1 -0
  212. package/dist/request-context-policy.d.ts +74 -0
  213. package/dist/request-context-policy.js +116 -0
  214. package/dist/request-context-policy.js.map +1 -0
  215. package/dist/request-context-protocol.d.ts +137 -0
  216. package/dist/request-context-protocol.js +38 -0
  217. package/dist/request-context-protocol.js.map +1 -0
  218. package/dist/request-context-recovery.d.ts +14 -0
  219. package/dist/request-context-recovery.js +56 -0
  220. package/dist/request-context-recovery.js.map +1 -0
  221. package/dist/request-context-relay.d.ts +19 -0
  222. package/dist/request-context-relay.js +63 -0
  223. package/dist/request-context-relay.js.map +1 -0
  224. package/dist/request-context-returns.d.ts +67 -0
  225. package/dist/request-context-returns.js +211 -0
  226. package/dist/request-context-returns.js.map +1 -0
  227. package/dist/request-context-store.d.ts +26 -0
  228. package/dist/request-context-store.js +144 -0
  229. package/dist/request-context-store.js.map +1 -0
  230. package/dist/request-context-turns.d.ts +99 -0
  231. package/dist/request-context-turns.js +215 -0
  232. package/dist/request-context-turns.js.map +1 -0
  233. package/dist/request-context-view.d.ts +33 -0
  234. package/dist/request-context-view.js +36 -0
  235. package/dist/request-context-view.js.map +1 -0
  236. package/dist/request-hub-context.d.ts +130 -0
  237. package/dist/request-hub-context.js +89 -0
  238. package/dist/request-hub-context.js.map +1 -0
  239. package/dist/request-hub-output.d.ts +11 -0
  240. package/dist/request-hub-output.js +21 -0
  241. package/dist/request-hub-output.js.map +1 -0
  242. package/dist/runtime-cli-install.js +13 -11
  243. package/dist/runtime-cli-install.js.map +1 -1
  244. package/dist/runtime-client.d.ts +2 -0
  245. package/dist/runtime-client.js +17 -4
  246. package/dist/runtime-client.js.map +1 -1
  247. package/dist/runtime-coordinator.d.ts +4 -1
  248. package/dist/runtime-coordinator.js +10 -3
  249. package/dist/runtime-coordinator.js.map +1 -1
  250. package/dist/runtime-pane-assets.d.ts +1 -1
  251. package/dist/runtime-pane-assets.js +1 -1
  252. package/dist/runtime-pane-assets.js.map +1 -1
  253. package/dist/runtime-pane-host.d.ts +3 -0
  254. package/dist/runtime-pane-host.js +39 -21
  255. package/dist/runtime-pane-host.js.map +1 -1
  256. package/dist/runtime-pane-link.d.ts +6 -2
  257. package/dist/runtime-pane-link.js +17 -4
  258. package/dist/runtime-pane-link.js.map +1 -1
  259. package/dist/runtime-pane-mcp-relay.d.ts +11 -1
  260. package/dist/runtime-pane-mcp-relay.js +69 -3
  261. package/dist/runtime-pane-mcp-relay.js.map +1 -1
  262. package/dist/runtime-pane-mcp.d.ts +28 -1
  263. package/dist/runtime-pane-mcp.js +92 -15
  264. package/dist/runtime-pane-mcp.js.map +1 -1
  265. package/dist/runtime-pane-port.d.ts +6 -0
  266. package/dist/runtime-pane-port.js +23 -4
  267. package/dist/runtime-pane-port.js.map +1 -1
  268. package/dist/runtime-pane-protocol.d.ts +4 -0
  269. package/dist/runtime-pane-protocol.js +11 -4
  270. package/dist/runtime-pane-protocol.js.map +1 -1
  271. package/dist/runtime-pane-service.d.ts +1 -0
  272. package/dist/runtime-pane-service.js +25 -9
  273. package/dist/runtime-pane-service.js.map +1 -1
  274. package/dist/runtime-pane-stdio-protocol.d.ts +4 -0
  275. package/dist/runtime-pane-stdio-protocol.js +12 -5
  276. package/dist/runtime-pane-stdio-protocol.js.map +1 -1
  277. package/dist/runtime-pane-stdio.js +5 -5
  278. package/dist/runtime-pane-stdio.js.map +1 -1
  279. package/dist/runtime-protocol.d.ts +3 -0
  280. package/dist/runtime-protocol.js.map +1 -1
  281. package/dist/scheduler/db.js +26 -0
  282. package/dist/scheduler/db.js.map +1 -1
  283. package/dist/scheduler/scheduler.d.ts +6 -0
  284. package/dist/scheduler/scheduler.js +19 -1
  285. package/dist/scheduler/scheduler.js.map +1 -1
  286. package/dist/scheduler/task-board-text.d.ts +2 -0
  287. package/dist/scheduler/task-board-text.js +12 -0
  288. package/dist/scheduler/task-board-text.js.map +1 -1
  289. package/dist/scheduler/task-board.d.ts +106 -2
  290. package/dist/scheduler/task-board.js +248 -24
  291. package/dist/scheduler/task-board.js.map +1 -1
  292. package/dist/scheduler/task-files.d.ts +80 -0
  293. package/dist/scheduler/task-files.js +357 -0
  294. package/dist/scheduler/task-files.js.map +1 -0
  295. package/dist/scheduler/types.d.ts +1 -1
  296. package/dist/service-activation.js +3 -13
  297. package/dist/service-activation.js.map +1 -1
  298. package/dist/service-lock.d.ts +28 -0
  299. package/dist/service-lock.js +85 -0
  300. package/dist/service-lock.js.map +1 -0
  301. package/dist/settings-api.d.ts +8 -0
  302. package/dist/settings-api.js +41 -1
  303. package/dist/settings-api.js.map +1 -1
  304. package/dist/settings-baseline.d.ts +1 -0
  305. package/dist/settings-baseline.js +1 -1
  306. package/dist/settings-baseline.js.map +1 -1
  307. package/dist/settings-change.js +1 -1
  308. package/dist/settings-change.js.map +1 -1
  309. package/dist/settings-effect.d.ts +2 -0
  310. package/dist/settings-effect.js +5 -1
  311. package/dist/settings-effect.js.map +1 -1
  312. package/dist/state-lease.d.ts +24 -0
  313. package/dist/state-lease.js +103 -0
  314. package/dist/state-lease.js.map +1 -0
  315. package/dist/task-attach-client.d.ts +43 -0
  316. package/dist/task-attach-client.js +125 -0
  317. package/dist/task-attach-client.js.map +1 -0
  318. package/dist/task-board-tool.d.ts +12 -0
  319. package/dist/task-board-tool.js +107 -6
  320. package/dist/task-board-tool.js.map +1 -1
  321. package/dist/task-file-limits.d.ts +15 -0
  322. package/dist/task-file-limits.js +21 -0
  323. package/dist/task-file-limits.js.map +1 -0
  324. package/dist/tmux-binary.js +1 -1
  325. package/dist/tmux-binary.js.map +1 -1
  326. package/dist/tool-permissions.d.ts +32 -0
  327. package/dist/tool-permissions.js +63 -0
  328. package/dist/tool-permissions.js.map +1 -1
  329. package/dist/tool-receipt-output.d.ts +2 -0
  330. package/dist/topic-commands.js +21 -1
  331. package/dist/topic-commands.js.map +1 -1
  332. package/dist/transcript-monitor.js +3 -0
  333. package/dist/transcript-monitor.js.map +1 -1
  334. package/dist/tunnel/named-link-test.d.ts +27 -0
  335. package/dist/tunnel/named-link-test.js +41 -0
  336. package/dist/tunnel/named-link-test.js.map +1 -1
  337. package/dist/types.d.ts +13 -0
  338. package/dist/ui/agent-details-settings.js +7 -5
  339. package/dist/ui/agent-who-can-use-strings.js +125 -0
  340. package/dist/ui/agent-who-can-use.js +238 -0
  341. package/dist/ui/chat-store.js +5 -4
  342. package/dist/ui/fleet-office-card.js +37 -6
  343. package/dist/ui/fleet-office-editor.js +5 -5
  344. package/dist/ui/fleet-office-pack.d.ts +10 -0
  345. package/dist/ui/fleet-office-pack.js +65 -2
  346. package/dist/ui/fleet-office-skin.js +75 -17
  347. package/dist/ui/fleet-office-store.js +33 -2
  348. package/dist/ui/fleet-office-vehicles.js +130 -0
  349. package/dist/ui/fleet-office-zones.js +13 -4
  350. package/dist/ui/fleet-office.js +245 -46
  351. package/dist/ui/fleet-task-activity.js +9 -82
  352. package/dist/ui/fleet-task-archive.js +111 -0
  353. package/dist/ui/fleet-task-card.js +6 -4
  354. package/dist/ui/fleet-task-common.js +2 -2
  355. package/dist/ui/fleet-task-edit.js +8 -1
  356. package/dist/ui/fleet-task-files.js +196 -0
  357. package/dist/ui/fleet-task-md.js +98 -0
  358. package/dist/ui/fleet-task-menu.js +1 -1
  359. package/dist/ui/fleet-task-stats.js +2 -2
  360. package/dist/ui/fleet-task-view.js +12 -8
  361. package/dist/ui/fleet-tasks.js +42 -18
  362. package/dist/ui/panel-chat.js +15 -2
  363. package/dist/ui/panel-details.js +3 -1
  364. package/dist/ui/panel-needs.js +25 -5
  365. package/dist/ui/panel-settings.js +37 -9
  366. package/dist/ui/settings-preview-address.js +156 -0
  367. package/dist/ui/settings-registry.js +3 -0
  368. package/dist/ui/settings-shared-strings.js +9 -0
  369. package/dist/ui/settings-shared.js +6 -1
  370. package/dist/ui/settings-strings.js +6 -6
  371. package/dist/ui/shared/app-i18n.js +2 -2
  372. package/dist/ui/shared/app-needs.js +8 -1
  373. package/dist/ui/shared/app.css +131 -5
  374. package/dist/ui/shared/chat-strings.js +10 -6
  375. package/dist/ui/shared/chat-thread.js +7 -1
  376. package/dist/ui/shared/preview-panel.js +1 -1
  377. package/dist/ui/shared/preview.js +11 -2
  378. package/dist/ui/shared/task-board.css +64 -0
  379. package/dist/ui/shared/tokens.css +18 -3
  380. package/dist/ui/shared/ui-confirm.js +5 -4
  381. package/dist/ui/shared/workspace.css +7 -0
  382. package/dist/ui/usage-credits-card.js +84 -0
  383. package/dist/ui/workspace-ignored-strings.js +16 -0
  384. package/dist/ui/workspace-panel.js +15 -6
  385. package/dist/update-card.d.ts +193 -0
  386. package/dist/update-card.js +620 -0
  387. package/dist/update-card.js.map +1 -0
  388. package/dist/update-dispatch.d.ts +16 -1
  389. package/dist/update-dispatch.js +12 -4
  390. package/dist/update-dispatch.js.map +1 -1
  391. package/dist/update-forward.d.ts +73 -0
  392. package/dist/update-forward.js +283 -0
  393. package/dist/update-forward.js.map +1 -0
  394. package/dist/update-idle.d.ts +1 -0
  395. package/dist/update-idle.js +12 -3
  396. package/dist/update-idle.js.map +1 -1
  397. package/dist/update-install.d.ts +2 -1
  398. package/dist/update-install.js +18 -10
  399. package/dist/update-install.js.map +1 -1
  400. package/dist/update-journal.d.ts +351 -0
  401. package/dist/update-journal.js +717 -0
  402. package/dist/update-journal.js.map +1 -0
  403. package/dist/update-launch.js +1 -1
  404. package/dist/update-launch.js.map +1 -1
  405. package/dist/update-npm-env.d.ts +45 -12
  406. package/dist/update-npm-env.js +48 -0
  407. package/dist/update-npm-env.js.map +1 -1
  408. package/dist/update-package-restore.d.ts +75 -0
  409. package/dist/update-package-restore.js +318 -0
  410. package/dist/update-package-restore.js.map +1 -0
  411. package/dist/update-quiescence.d.ts +192 -0
  412. package/dist/update-quiescence.js +330 -0
  413. package/dist/update-quiescence.js.map +1 -0
  414. package/dist/update-readiness-host.d.ts +61 -0
  415. package/dist/update-readiness-host.js +297 -0
  416. package/dist/update-readiness-host.js.map +1 -0
  417. package/dist/update-readiness.d.ts +83 -0
  418. package/dist/update-readiness.js +459 -0
  419. package/dist/update-readiness.js.map +1 -0
  420. package/dist/update-recovery/kit.d.ts +35 -0
  421. package/dist/update-recovery/kit.js +99 -0
  422. package/dist/update-recovery/kit.js.map +1 -0
  423. package/dist/update-recovery/pre-start.d.ts +34 -0
  424. package/dist/update-recovery/pre-start.js +103 -0
  425. package/dist/update-recovery/pre-start.js.map +1 -0
  426. package/dist/update-recovery/recover-main.d.ts +1 -0
  427. package/dist/update-recovery/recover-main.js +4 -0
  428. package/dist/update-recovery/recover-main.js.map +1 -0
  429. package/dist/update-recovery/recover.d.ts +22 -0
  430. package/dist/update-recovery/recover.js +124 -0
  431. package/dist/update-recovery/recover.js.map +1 -0
  432. package/dist/update-recovery/route.d.ts +53 -0
  433. package/dist/update-recovery/route.js +262 -0
  434. package/dist/update-recovery/route.js.map +1 -0
  435. package/dist/update-recovery/runner.d.ts +58 -0
  436. package/dist/update-recovery/runner.js +196 -0
  437. package/dist/update-recovery/runner.js.map +1 -0
  438. package/dist/update-recovery/service-manager.d.ts +39 -0
  439. package/dist/update-recovery/service-manager.js +57 -0
  440. package/dist/update-recovery/service-manager.js.map +1 -0
  441. package/dist/update-restore.d.ts +44 -0
  442. package/dist/update-restore.js +355 -0
  443. package/dist/update-restore.js.map +1 -0
  444. package/dist/update-retained.d.ts +38 -0
  445. package/dist/update-retained.js +91 -0
  446. package/dist/update-retained.js.map +1 -0
  447. package/dist/update-rollback.d.ts +74 -0
  448. package/dist/update-rollback.js +221 -0
  449. package/dist/update-rollback.js.map +1 -0
  450. package/dist/update-settings.d.ts +36 -0
  451. package/dist/update-settings.js +122 -0
  452. package/dist/update-settings.js.map +1 -0
  453. package/dist/update-snapshot-manifest.d.ts +32 -0
  454. package/dist/update-snapshot-manifest.js +65 -0
  455. package/dist/update-snapshot-manifest.js.map +1 -0
  456. package/dist/update-snapshot-scope.d.ts +67 -0
  457. package/dist/update-snapshot-scope.js +172 -0
  458. package/dist/update-snapshot-scope.js.map +1 -0
  459. package/dist/update-snapshot.d.ts +34 -0
  460. package/dist/update-snapshot.js +246 -0
  461. package/dist/update-snapshot.js.map +1 -0
  462. package/dist/update-writers.d.ts +71 -0
  463. package/dist/update-writers.js +235 -0
  464. package/dist/update-writers.js.map +1 -0
  465. package/dist/web-api.d.ts +6 -0
  466. package/dist/web-api.js +140 -22
  467. package/dist/web-api.js.map +1 -1
  468. package/dist/web-chat-history.d.ts +7 -0
  469. package/dist/web-chat-history.js +15 -0
  470. package/dist/web-chat-history.js.map +1 -1
  471. package/dist/web-office-acts.d.ts +16 -0
  472. package/dist/web-office-acts.js +27 -9
  473. package/dist/web-office-acts.js.map +1 -1
  474. package/dist/web-office-pack-read.js +1 -1
  475. package/dist/web-office-pack-read.js.map +1 -1
  476. package/dist/web-office-skins.d.ts +5 -3
  477. package/dist/web-office-skins.js +20 -16
  478. package/dist/web-office-skins.js.map +1 -1
  479. package/dist/web-preview.d.ts +5 -0
  480. package/dist/web-preview.js +1 -1
  481. package/dist/web-preview.js.map +1 -1
  482. package/dist/web-settings-patch.d.ts +27 -0
  483. package/dist/web-settings-patch.js +67 -0
  484. package/dist/web-settings-patch.js.map +1 -1
  485. package/dist/web-update.d.ts +6 -0
  486. package/dist/windows-agents.d.ts +12 -0
  487. package/dist/windows-agents.js +5 -0
  488. package/dist/windows-agents.js.map +1 -1
  489. package/dist/workflow-templates/default.md +1 -0
  490. package/launcher/agend +4 -1
  491. package/launcher/agend-agent +4 -1
  492. package/launcher/agend-install.cjs +16 -8
  493. package/launcher/install-admission.d.cts +8 -0
  494. package/launcher/npm-allow-scripts.cjs +72 -0
  495. package/launcher/npm-global-prefix.cjs +81 -0
  496. package/launcher/postinstall.cjs +9 -8
  497. package/launcher/runtime-select.cjs +8 -2
  498. package/package.json +3 -2
  499. package/scripts/preinstall-guard.cjs +1 -1
@@ -1,4 +1,10 @@
1
- import { prepareContactChange, shortContactTicketId } from "./contact-change-proposals.js";
1
+ import { requestDeliveryView, requestContextDisplayView } from "./request-context-view.js";
2
+ import { captureRequestHubOutput } from "./request-hub-output.js";
3
+ import { assertRequestContextOperation, requireRequestContextPolicy, RequestContextPolicyError } from "./request-context-policy.js";
4
+ import { permitWebContinuation } from "./web-continuation.js";
5
+ import { nativeContactCardText, nativeContactOutcome, nativeContactPrincipal, nativeDecisionFailure } from "./request-contact-native.js";
6
+ import { RequestContextReferenceMap } from "./request-context-fence.js";
7
+ import { ContactChangeSchema, prepareContactChange, resolvePendingTicket, shortContactTicketId } from "./contact-change-proposals.js";
2
8
  import { contactStateView, ownContactRequestsView } from "./contact-state-view.js";
3
9
  import { detectMonitoringPlatform } from './host-monitoring-defaults.js';
4
10
  import { SharedDefaultAdoption } from "./shared-default-adoption.js";
@@ -73,7 +79,7 @@ import { handleWebIconRequest, useAppIconStore } from "./web-icons.js";
73
79
  import { AppIconStore } from "./web-app-icon.js";
74
80
  import { trackWebServer } from "./web-server-drain.js";
75
81
  import { renderPublicLinkProgress, ThrottledMessageEditor } from "./public-link-progress.js";
76
- import { PublicWebLink, publicLinkNamedHostname, publicLinkSettings } from "./public-web-link.js";
82
+ import { PublicWebLink, publicLinkNamedHostname, publicLinkPreviewHostname, publicLinkSettings } from "./public-web-link.js";
77
83
  import { PublicLinkAutoOpen } from "./public-link-auto-open.js";
78
84
  import { clearPublicLinkOwner, readPublicLinkOwner, writePublicLinkOwner } from "./public-link-owner.js";
79
85
  import { PUBLIC_PREVIEW_FRAME_SRC, PUBLIC_PREVIEW_TUNNEL_DIR, PublicPreview, publicPreviewWanted } from "./public-preview.js";
@@ -81,7 +87,7 @@ import { CloudflaredProvider } from "./tunnel/cloudflared.js";
81
87
  import { ensureCloudflared } from "./tunnel/cloudflared-install.js";
82
88
  import { installExitMarker, unattendedInstallCommand, loginShell } from "./unattended-install.js";
83
89
  import { InstallStream } from "./install-stream.js";
84
- import { namedTestLane, runNamedLinkTest } from "./tunnel/named-link-test.js";
90
+ import { namedTestLane, runNamedLinkTest, runPreviewRouteTest } from "./tunnel/named-link-test.js";
85
91
  import { daemonTopicMode, isWebOnlyFleetConfig } from "./web-only-fleet.js";
86
92
  import { OFFICE_SHARE_TUNNEL_DIR, OfficeShareService } from "./office-share-service.js";
87
93
  import { OfficeTalk } from "./office-talk.js";
@@ -322,11 +328,15 @@ import { WebSettingsTools } from "./web-settings-tools.js";
322
328
  import { GUEST_COMMAND_RUNS, GUEST_PREF_WRITES, GUEST_SEARCHES, bindGuestRequest, guestRouteDecision } from "./web-guest-access.js";
323
329
  import { GUEST_ROOM_TICK_MS, GuestRoomMembership, guestGroupRooms } from "./web-guest-rooms.js";
324
330
  import { Delegations, TrafficLog, trafficItem } from "./fleet-traffic.js";
331
+ import { turnSource } from "./update-quiescence.js";
325
332
  import { installedChannel, updateNoticeKey } from "./update-check.js";
333
+ import { idleClaimOutcome, idleUpdateMessageId, UpdateOfferCard, updateAnswerLabel, updateOfferReply } from "./update-card.js";
334
+ import { preflightAllows } from "./update-readiness.js";
335
+ import { inUpdatePause, resolveUpdates } from "./update-settings.js";
326
336
  import { resolveInstalledAgend, npmForRunningInstall } from "./update-dispatch.js";
327
337
  import { HUB_UPDATE_NOTICE_FILE, HUB_UPDATE_REMIND_MS, hubNoticeDue, hubNoticeKey, readHubNoticeState, writeHubNoticeState } from "./hub-update-notice.js";
328
338
  import { resolveUpdateLaunch, openUpdateLog, updateLogPath, watchUpdateLaunch } from "./update-launch.js";
329
- import { isWebUpdateTarget, readLogTail, RUNNING_AGEND_VERSION, updateOffer, webProgressOf, webUpdateTarget } from "./web-update.js";
339
+ import { failureCause, isWebUpdateTarget, readLogTail, RUNNING_AGEND_VERSION, updateOffer, webProgressOf, webUpdateTarget } from "./web-update.js";
330
340
  import { admitProfileLogin, LoginController, LOGIN_TOKEN_RESEND_PREFIX, POST_LOGIN_RECOVERY_DEADLINE_MS } from "./login-controller.js";
331
341
  import { WebBackendLogins, dashboardSignInSupported } from "./web-backend-login.js";
332
342
  import { CLAUDE_NPM_PACKAGE, claudeInstallKind, displayHostPath } from "./claude-install-kind.js";
@@ -422,6 +432,7 @@ import { APPLY_FLEET_TARGET, ApplyJobStore, viewOf, } from "./apply-job.js";
422
432
  import { kiroHome } from "./backend/kiro-kas-store.js";
423
433
  import { CHAT_PROFILE_LOGIN_BACKENDS, claudeStoreEnded, credentialHomeSpec, credentialProfileHome, credentialProfileLaunch, credentialProfileLogin, credentialProfileLoginCommand, credentialProfileStoreHome, credentialSwitchCarriesConversation, credentialSwitchStartsFresh, instanceCredentialProfile, listConfiguredProfiles, resolveCredentialProfile } from "./backend/credential-profile.js";
424
434
  import { carryClaudeConversation } from "./backend/claude-carry.js";
435
+ import { carryClaudeMcpServers, claudeJsonFor, dismissClaudeMcpMissing, recordClaudeMcpBeforeSwitch } from "./backend/claude-mcp-carry.js";
425
436
  import { classicProfile, mergeBackendOptions, profileKey, profileName, profileOf, readClassicBindings, readClassicBindingsStrict } from "./classic-bindings.js";
426
437
  import { ACCOUNT_CLIS, PROFILE_CLIS, accountUsage, buildAccountsView, profilesOnDisk } from "./accounts-view.js";
427
438
  import { accountFolderExists, addAccountProfile, removeAccountProfile } from "./accounts-profiles.js";
@@ -660,13 +671,19 @@ const CLEAR_CONFIRM_CALLBACK_PREFIX = "clear-confirm:";
660
671
  const KIRO_MIGRATE_CALLBACK_PREFIX = "kiro-migrate:";
661
672
  /** M-3140: Update now on a Hub-recommended-version notice in General ("hub-update:" + 32 hex + ":update" = 50 bytes). */
662
673
  const HUB_UPDATE_CALLBACK_PREFIX = "hub-update:";
674
+ /** M-3770 1.5: the update card in General's chat ("update-card:" + 32 hex + ":" + its answer). */
675
+ const UPDATE_CARD_CALLBACK_PREFIX = "update-card:";
676
+ /** M-3770 1.5: where the chat card's message is (one per fleet), so later states edit it in place across a restart. */
677
+ const UPDATE_CHAT_CARD_FILE = "update-chat-card.json";
678
+ /** The chat card's buttons live a week (Not now's own length); a newer card replaces them sooner. */
679
+ const UPDATE_CHAT_CARD_MS = 7 * 24 * 60 * 60_000;
663
680
  const HUB_SHARING_CALLBACK_PREFIX = "hub-share:";
664
681
  /** M-3680: a held contact request's card in General ("contact-ticket:" + 32 hex + ":approve" = 55 bytes, under Telegram's 64). */
665
682
  const CONTACT_TICKET_PREFIX = "contact-ticket:";
666
683
  /** How many requests' cards are remembered (one card per request; a decided one is forgotten at once). */
667
684
  const HELD_CARDS_KEPT = 512;
668
685
  /** A held request's card, retired after it was decided elsewhere (the dashboard, Needs you, another card) or closed. */
669
- const heldCardOutcome = (state) => t(state === "approved" ? "contactHeld.approvedElsewhere"
686
+ const heldCardOutcome = (state, root = false) => t(state === "approved" ? root ? "contactCard.continued_elsewhere" : "contactHeld.approvedElsewhere"
670
687
  : state === "declined" ? "contactHeld.declinedElsewhere" : state === "expired" ? "contactHeld.expired" : "contactHeld.closed");
671
688
  const HUB_FLEET_UPDATE_CALLBACK_PREFIX = "hub-fleet-update:";
672
689
  const KIRO_RECONCILE_CALLBACK_PREFIX = "kiro-reconcile:";
@@ -828,6 +845,9 @@ export class FleetManager {
828
845
  static sighupHandlerInstalled = false;
829
846
  /** Test seam: inject a spy to verify saveFleetConfig calls fsync. Default: fsyncSync. */
830
847
  fsyncForTest = undefined;
848
+ /** S-244: the quiescence barrier. Unset, every pane write and admission proceeds as today. */
849
+ quiescence = null;
850
+ attachQuiescence(gate) { this.quiescence = gate; }
831
851
  children = new Map();
832
852
  lifecycle;
833
853
  stormWindow;
@@ -1054,6 +1074,82 @@ export class FleetManager {
1054
1074
  fleetConfig = null;
1055
1075
  fleetWindowsRuntime = null;
1056
1076
  nativeMcpStore = null;
1077
+ requestContextIpcCalls = new WeakMap();
1078
+ requestContextFleetCalls = new RequestContextReferenceMap(row => row.call.admission.coverage === "covered" ? row.call.admission.lease.snapshot.context.ref.rootContextId : null, row => `fleet-call:${row.call.id}`);
1079
+ setRequestContextDrainRegistration(registration) {
1080
+ if (this.instanceIpcClients.size)
1081
+ throw Error("Request context drain must bind before IPC starts");
1082
+ const calls = this.requestContextFleetCalls;
1083
+ if (!calls)
1084
+ throw Error("Request context drain registry unavailable");
1085
+ calls.installRegistration(registration);
1086
+ }
1087
+ get requestContextFleetDrainRevision() { return this.requestContextFleetCalls?.revision ?? "unavailable"; }
1088
+ requestContextFleetDrainView(rootId) { return this.requestContextFleetCalls?.view(rootId) ?? { registration: null, revision: "unavailable", references: [], unknown: true }; }
1089
+ finishRequestContextIpcCall(message) { const call = this.requestContextCallOf(message), calls = this.requestContextFleetCalls; if (call && calls)
1090
+ for (const [id, row] of calls)
1091
+ if (row.call === call)
1092
+ calls.delete(id); }
1093
+ purgeRequestContextIpcCalls(name, ipc) {
1094
+ const calls = this.requestContextFleetCalls;
1095
+ if (!calls)
1096
+ return;
1097
+ for (const [id, row] of calls)
1098
+ if (row.instance === name && row.ipc === ipc)
1099
+ calls.delete(id);
1100
+ }
1101
+ observeRequestContextResponses(name, ipc) {
1102
+ const calls = this.requestContextFleetCalls;
1103
+ if (!calls?.registrationGate)
1104
+ return;
1105
+ const send = ipc.send.bind(ipc);
1106
+ ipc.send = (message) => {
1107
+ try {
1108
+ return send(message);
1109
+ }
1110
+ finally {
1111
+ if (message && typeof message === "object") {
1112
+ const row = message, key = String(row.fleetRequestId ?? row.requestId ?? "");
1113
+ if (String(row.type ?? "").endsWith("_response") && key)
1114
+ for (const [id, call] of calls)
1115
+ if (call.instance === name && call.ipc === ipc && call.responseKey === key)
1116
+ calls.delete(id);
1117
+ }
1118
+ }
1119
+ };
1120
+ }
1121
+ /** Captured at IPC arrival, not a later lookup of this instance's current turn. */
1122
+ requestContextCallOf(message) { return this.requestContextIpcCalls?.get(message) ?? null; }
1123
+ captureRequestContextIpcCall(name, message, ipc) {
1124
+ const daemon = this.daemons.get(name);
1125
+ if (!daemon?.requestContextCallsRequired?.())
1126
+ return message.requestContextCallId === undefined;
1127
+ if (this.instanceIpcClients.get(name) !== ipc || message.sourceDaemonBootId !== daemon.bootId || typeof message.requestContextCallId !== "string")
1128
+ return false;
1129
+ const captured = daemon.requestContextCall(message.requestContextCallId);
1130
+ if (!captured)
1131
+ return false;
1132
+ const tool = message.type === "fleet_outbound" ? String(message.tool ?? "") : toolForIpcType(message.type);
1133
+ const originalBoot = daemon.bootId;
1134
+ const scoped = Object.freeze({ id: captured.id, admission: captured.admission,
1135
+ current: () => captured.current() && this.instanceIpcClients.get(name) === ipc && this.getDaemonBootId(name) === originalBoot
1136
+ && !!tool && this.checkToolPermission("ipc-outbound", name, tool === "hub_room_status" ? "hub_room_list" : tool).allowed });
1137
+ const calls = this.requestContextFleetCalls;
1138
+ if (calls?.registrationGate) {
1139
+ const responseKey = String(message.fleetRequestId ?? message.requestId ?? "");
1140
+ const key = JSON.stringify([name, originalBoot, responseKey]);
1141
+ if (!responseKey || calls.has(key))
1142
+ return false;
1143
+ try {
1144
+ calls.set(key, { call: scoped, instance: name, bootId: originalBoot, ipc, responseKey });
1145
+ }
1146
+ catch {
1147
+ return false;
1148
+ }
1149
+ }
1150
+ this.requestContextIpcCalls.set(message, scoped);
1151
+ return true;
1152
+ }
1057
1153
  paneManager = null;
1058
1154
  localPaneRelay = null;
1059
1155
  openingLocalPane = null;
@@ -1189,7 +1285,7 @@ export class FleetManager {
1189
1285
  this.scheduleOwnerNoticeFlush(30_000); // a notice kept before a restart is delivered once the fleet is up
1190
1286
  return this.runtimeHub ??= new RuntimeCoordinator(this.dataDir, {
1191
1287
  handleMcp: (machineId, runId, body) => this.runtimeWindowsExecutor().mcp(machineId, runId, body),
1192
- handlePaneMcp: async (machineId, body, current) => (await this.nativePanes()).handle(machineId, body, current),
1288
+ handlePaneMcp: async (machineId, body, current, stamp) => stamp ? (await this.nativePanes()).handle(machineId, body, current, stamp) : (await this.nativePanes()).handle(machineId, body, current),
1193
1289
  warn: (fields, message) => this.logger.warn(fields, message),
1194
1290
  // Issue, use, revocation (and a refused use) of an install-command token: ids and an opaque actor handle only, never the token.
1195
1291
  audit: entry => {
@@ -1253,8 +1349,8 @@ export class FleetManager {
1253
1349
  nativeInstanceRuntime() {
1254
1350
  return this.fleetWindowsRuntime ??= new FleetWindowsRuntime({
1255
1351
  owner: this, fleet: () => this.fleetConfig, save: () => this.saveFleetConfig(), stopping: () => this.shuttingDown, history: this.webChatHistory,
1256
- openMcp: (instance, requestId, sandbox, stillCurrent) => this.healthServerListening
1257
- ? this.nativeMcpSessions().grant({ instance, requestId, sandbox, stillCurrent, endpoint: `http://127.0.0.1:${this.fleetConfig?.health_port ?? 19280}/agent` }) : null,
1352
+ openMcp: (instance, requestId, sandbox, stillCurrent, requestContext) => this.healthServerListening
1353
+ ? this.nativeMcpSessions().grant({ instance, requestId, sandbox, stillCurrent, ...(requestContext ? { requestContext } : {}), endpoint: `http://127.0.0.1:${this.fleetConfig?.health_port ?? 19280}/agent` }) : null,
1258
1354
  warn: (message, error) => this.logger.warn({ err: error }, message),
1259
1355
  removed: name => this.nativeInstanceRemoved(name),
1260
1356
  paneCurrent: name => this.daemons.get(name)?.nativePaneCurrent?.() === true,
@@ -1550,7 +1646,7 @@ export class FleetManager {
1550
1646
  diagnostic: text => this.logger.warn({ stderr: text }, "Local Windows pane relay wrote to stderr"),
1551
1647
  version: provider => inventory.clis.find(row => row.id === provider && row.runnable)?.version ?? null,
1552
1648
  launch: () => launchLocalPaneRelay(this.dataDir, admit),
1553
- mcp: async (body, current) => (await this.nativePanes()).handle("local", body, current),
1649
+ mcp: async (body, current, stamp) => stamp ? (await this.nativePanes()).handle("local", body, current, stamp) : (await this.nativePanes()).handle("local", body, current),
1554
1650
  });
1555
1651
  try {
1556
1652
  admit();
@@ -1645,9 +1741,10 @@ export class FleetManager {
1645
1741
  delegate_task: "delegate", request_information: "ask", report_result: "report", delivery_status: "delivery-status" };
1646
1742
  const { nativeAgentAdmissionContext } = await import("./native-agent-admission.js");
1647
1743
  const { dispatchAgentOperation } = await import("./agent-endpoint.js");
1648
- return daemon.handlePaneToolCall(input, { current, allowed: tool => allowed(name, tool),
1744
+ return daemon.handlePaneToolCall(input, { current, allowed: tool => allowed(name, tool), ...(input.requestContext ? { requestContext: input.requestContext } : {}),
1649
1745
  dispatch: (tool, args) => ops[tool] ? dispatchAgentOperation(nativeAgentAdmissionContext(this, {
1650
- instance: name, current: () => current() && allowed(name, tool), taskAllowed: () => current() && allowed(name, "task"),
1746
+ instance: name, operation: { tool, args }, current: () => current() && allowed(name, tool), taskAllowed: () => current() && allowed(name, "task"),
1747
+ ...(input.requestContext?.coverage === "covered" ? { requestContext: input.requestContext.lease } : input.requestContext ? { notCoveredReason: input.requestContext.reason } : {}),
1651
1748
  }), name, ops[tool], args, input.operationId, () => current() && allowed(name, tool)) : undefined });
1652
1749
  },
1653
1750
  });
@@ -1981,14 +2078,251 @@ export class FleetManager {
1981
2078
  await this.launchInstalledUpdate(`hub-recommended /update by ${adapterId}:${by}`, () => this.fleetAdminGate(by, adapterId) === "ok" && !this.shuttingDown && this.hubRecommendationFor(pin) !== null, advice.version);
1982
2079
  return true;
1983
2080
  }
2081
+ // ── M-3770 1.5 (design #4480 §3.1): the update card in General's chat ──────────────────────────────────────────
2082
+ updateChatCardBusy = false;
2083
+ /** #4485 review 2: a sync asked for while one ran; the running one runs again. */
2084
+ updateChatCardAgain = false;
2085
+ /** #4485 review 2: each posted card's delivery address and the version it shows, by nonce (independent of the pending map). */
2086
+ updateChatCardSent = new Map();
2087
+ /** #4485 r2: the version each card's buttons answer for, bound when its delivery starts (before the platform answers). */
2088
+ updateChatCardVersion = new Map();
2089
+ /** #4485 review 2: an answer that came while its card was still being posted (the post records it when it returns). */
2090
+ updateChatCardAnswered = new Map();
2091
+ updateChatCardTimer = null;
2092
+ readUpdateChatCard() {
2093
+ try {
2094
+ const r = JSON.parse(readFileSync(join(this.dataDir, UPDATE_CHAT_CARD_FILE), "utf8"));
2095
+ return r && typeof r.messageId === "string" ? r : null;
2096
+ }
2097
+ catch {
2098
+ return null;
2099
+ }
2100
+ }
2101
+ writeUpdateChatCard(r) {
2102
+ try {
2103
+ if (r)
2104
+ writeFileSync(join(this.dataDir, UPDATE_CHAT_CARD_FILE), JSON.stringify(r));
2105
+ else
2106
+ rmSync(join(this.dataDir, UPDATE_CHAT_CARD_FILE), { force: true });
2107
+ }
2108
+ catch (err) {
2109
+ this.logger.warn({ err }, "Update chat card state could not be saved");
2110
+ }
2111
+ }
2112
+ /** The card's words for a state (the offer: two sentences, the second only where true — §3.1, Phase 1). */
2113
+ updateChatCardText(view, current) {
2114
+ if (view && view.state === "offered") {
2115
+ // M-3770 1.2's cached pre-flight, when this build has it (#4483): the second sentence only where it is true.
2116
+ const pre = this.updatePreflight;
2117
+ const p3 = pre?.checks.find(c => c.id === "P3");
2118
+ // The leader's copy pass (S-237): a title and one line, as on the web.
2119
+ const line = !p3 ? t("update.chatcard.continues") : p3.ok ? t("update.chatcard.back", current ?? "?") : t("update.chatcard.noWayBack");
2120
+ return `${t("update.chatcard.offer", view.version)}\n${line}`;
2121
+ }
2122
+ // The card's own short lines, as on the web (the leader's copy pass); anything else in /update's words.
2123
+ const at = (ms) => { if (!ms)
2124
+ return ""; const d = new Date(ms), p2 = (n) => String(n).padStart(2, "0"); return `${d.getFullYear()}-${p2(d.getMonth() + 1)}-${p2(d.getDate())} ${p2(d.getHours())}:${p2(d.getMinutes())}`; };
2125
+ if (view?.state === "waiting-idle")
2126
+ return t("update.chatcard.state_waiting", view.version);
2127
+ if (view?.state === "scheduled")
2128
+ return t("update.chatcard.state_scheduled", view.version, at(view.scheduledAt));
2129
+ if (view?.state === "not-now")
2130
+ return t("update.chatcard.state_not_now", view.version, at(view.notNowUntil));
2131
+ if (view?.state === "updating")
2132
+ return t("update.chatcard.state_updating", view.version);
2133
+ if (view?.state === "done")
2134
+ return t("update.chatcard.state_done", view.version);
2135
+ if (view?.state === "failed")
2136
+ return t("update.chatcard.state_failed", view.version, current ?? "?");
2137
+ const reply = updateOfferReply(view, current, !!resolveUpdates(this.fleetConfig?.updates).pin);
2138
+ return t(reply.key, ...reply.args);
2139
+ }
2140
+ /** General's chat place for the card, or null (no General, no chat: a web-only fleet's banner says it). */
2141
+ updateChatCardPlace() {
2142
+ if (this.webOnlyPromptPlace())
2143
+ return null;
2144
+ const general = this.findGeneralInstance();
2145
+ const adapterId = general ? this.getInstanceAdapterId(general) : undefined;
2146
+ const adapter = general ? this.getAdapterForInstance(general) : undefined;
2147
+ const chatId = general ? this.getGroupIdForInstance(general) : undefined;
2148
+ const topic = general ? String(this.fleetConfig?.instances[general]?.topic_id ?? "") : "";
2149
+ if (!general || !adapterId || !adapter || !chatId)
2150
+ return null;
2151
+ return { general, adapter, adapterId, chatId, ...(topic ? { threadId: topic } : {}) };
2152
+ }
2153
+ /**
2154
+ * M-3770 1.5: keep General's one update card in step with the fleet's card (S-234's UpdateOfferCard). An offer that
2155
+ * newly qualifies (a new version, or back after Not now) is posted with its buttons; every later state edits that same
2156
+ * message (its buttons retired: the adapters cannot swap them). Never throws; one at a time.
2157
+ */
2158
+ async syncUpdateChatCard() {
2159
+ // A call while one runs is not dropped: the running one syncs again when it is done (#4485 review 2).
2160
+ if (this.shuttingDown)
2161
+ return;
2162
+ if (this.updateChatCardBusy) {
2163
+ this.updateChatCardAgain = true;
2164
+ return;
2165
+ }
2166
+ this.updateChatCardBusy = true;
2167
+ try {
2168
+ const view = this.updateOfferView();
2169
+ let current = null;
2170
+ try {
2171
+ current = this.runningAgendVersion();
2172
+ }
2173
+ catch { /* unknown */ }
2174
+ const posted = this.readUpdateChatCard();
2175
+ const state = view?.state ?? "none";
2176
+ // #4485 review 1: an offered card whose buttons are gone (a restart empties the nonce map; they also expire) is not
2177
+ // a usable card: it is marked expired and one with live buttons is posted.
2178
+ const live = !!posted?.nonce && this.pendingNonceButtons.get(posted.nonce)?.prefix === UPDATE_CARD_CALLBACK_PREFIX;
2179
+ if (view && state === "offered" && view.installable && (!posted || posted.version !== view.version || posted.state !== "offered" || !live)) {
2180
+ const place = this.updateChatCardPlace();
2181
+ if (!place)
2182
+ return;
2183
+ if (posted) {
2184
+ const old = posted.state === "offered" && posted.version === view.version && !live ? t("update.chatcard.expired")
2185
+ : posted.version === view.version ? t("update.chatcard.cancelled", posted.version) : t("update.chatcard.replaced", view.version);
2186
+ await this.editUpdateChatCard(posted, old);
2187
+ }
2188
+ const version = view.version;
2189
+ const nonce = await this.postNonceButtonPromptOrThrow({
2190
+ prefix: UPDATE_CARD_CALLBACK_PREFIX, alertType: "tip", instanceName: place.general, adapter: place.adapter, adapterId: place.adapterId,
2191
+ chatId: place.chatId, ...(place.threadId ? { threadId: place.threadId } : {}),
2192
+ message: this.updateChatCardText(view, current),
2193
+ choices: [{ action: "when-idle", label: t("update.chatcard.when_idle") }, { action: "tonight", label: t("update.chatcard.tonight") }, { action: "not-now", label: t("update.chatcard.not_now") }],
2194
+ expiredText: t("update.chatcard.expired"),
2195
+ timeoutMs: UPDATE_CHAT_CARD_MS,
2196
+ // #4485 review 2: the provider's own delivery address, kept per nonce as it is sent — a click may consume the
2197
+ // pending entry before this post returns, so the entry is never the place to read it from.
2198
+ deliver: async (choices) => {
2199
+ // #4485 r2: the buttons' version is bound before anything is sent — a click can come before the platform answers.
2200
+ const nonceOf = (choices[0]?.id ?? "").slice(UPDATE_CARD_CALLBACK_PREFIX.length, UPDATE_CARD_CALLBACK_PREFIX.length + 32);
2201
+ this.updateChatCardVersion.set(nonceOf, version);
2202
+ const shown = this.renderPlaces(place.adapterId, this.updateChatCardText(view, current), place.threadId ? { threadId: place.threadId } : undefined);
2203
+ const sent = await place.adapter.notifyAlert(place.chatId, { type: "tip", instanceName: place.general, message: shown.text, choices }, shown.opts);
2204
+ const id = choices[0]?.id ?? "";
2205
+ this.updateChatCardSent.set(id.slice(UPDATE_CARD_CALLBACK_PREFIX.length, UPDATE_CARD_CALLBACK_PREFIX.length + 32), { version, chatId: sent.chatId, ...(sent.threadId !== undefined ? { threadId: sent.threadId } : {}), messageId: String(sent.messageId ?? "") });
2206
+ return sent;
2207
+ },
2208
+ });
2209
+ const sent = this.updateChatCardSent.get(nonce);
2210
+ const answered = this.updateChatCardAnswered.get(nonce);
2211
+ this.updateChatCardAnswered.delete(nonce);
2212
+ this.writeUpdateChatCard({ version, state: answered ?? "offered", nonce: answered ? null : nonce, messageId: sent?.messageId ?? "",
2213
+ chatId: sent?.chatId ?? place.chatId, ...((sent?.threadId ?? place.threadId) ? { threadId: sent?.threadId ?? place.threadId } : {}),
2214
+ adapterId: place.adapterId, at: Date.now() });
2215
+ // The card may have moved on while this was being posted (a newer version, an answer on the web): sync again.
2216
+ const after = this.updateOfferView();
2217
+ if (!answered && (after?.version !== version || (after?.state ?? "none") !== "offered"))
2218
+ this.updateChatCardAgain = true;
2219
+ return;
2220
+ }
2221
+ if (posted && posted.state !== state) {
2222
+ const text = state === "none" && posted.state !== "done" ? t("update.chatcard.cancelled", posted.version) : this.updateChatCardText(view, current);
2223
+ await this.editUpdateChatCard(posted, text);
2224
+ this.writeUpdateChatCard(state === "none" ? null : { ...posted, state, nonce: null });
2225
+ }
2226
+ }
2227
+ catch (err) {
2228
+ this.logger.warn({ err: err.message }, "Update chat card not posted");
2229
+ }
2230
+ finally {
2231
+ this.updateChatCardBusy = false;
2232
+ if (this.updateChatCardAgain && !this.shuttingDown) {
2233
+ this.updateChatCardAgain = false;
2234
+ void this.syncUpdateChatCard();
2235
+ }
2236
+ }
2237
+ }
2238
+ /** Edit the posted card: retire its buttons if they are still live (with `text`), else edit its text without buttons. */
2239
+ async editUpdateChatCard(posted, text) {
2240
+ const entry = posted.nonce ? this.pendingNonceButtons.get(posted.nonce) : undefined;
2241
+ if (entry && entry.prefix === UPDATE_CARD_CALLBACK_PREFIX) {
2242
+ this.pendingNonceButtons.delete(posted.nonce);
2243
+ await this.retireNonceButtons(entry, entry.messageId ?? posted.messageId, text);
2244
+ return;
2245
+ }
2246
+ const place = this.updateChatCardPlace();
2247
+ const adapter = this.adapters.get(posted.adapterId) ?? this.worlds.get(posted.adapterId)?.adapter ?? (place && place.adapterId === posted.adapterId ? place.adapter : undefined);
2248
+ if (!adapter || !posted.messageId)
2249
+ return;
2250
+ // Dead buttons (after a restart, or expired) go with the edit where the adapter can drop them.
2251
+ if (adapter.editMessageRemoveButtons)
2252
+ await adapter.editMessageRemoveButtons(posted.chatId, posted.messageId, text, posted.threadId).catch(() => { });
2253
+ else
2254
+ await adapter.editMessage(posted.chatId, posted.messageId, text, posted.threadId).catch(() => { });
2255
+ }
2256
+ /**
2257
+ * M-3770 1.5: a press on the chat card — a fleet admin's only (anyone else is told privately, the buttons stay: the
2258
+ * same gate as the Hub's Update now). The answer is the web's (the one card); the message is edited to its new state.
2259
+ */
2260
+ async handleUpdateCardCallback(data, adapterId, adapter) {
2261
+ const claimed = this.consumeNonceCallback(UPDATE_CARD_CALLBACK_PREFIX, /^update-card:([0-9a-f]{32}):(when-idle|tonight|not-now)$/, data, adapterId, adapter, undefined, userId => this.fleetAdminGate(userId, adapterId) === "ok");
2262
+ if (claimed === null)
2263
+ return false;
2264
+ if (claimed === "consumed")
2265
+ return true;
2266
+ const { entry, action } = claimed;
2267
+ const nonce = data.callbackData.slice(UPDATE_CARD_CALLBACK_PREFIX.length, UPDATE_CARD_CALLBACK_PREFIX.length + 32);
2268
+ const sent = this.updateChatCardSent.get(nonce);
2269
+ const messageId = entry.messageId ?? sent?.messageId ?? data.messageId;
2270
+ // #4485 review 2: a press answers the offer its message showed — never a newer one that came since. The version is
2271
+ // bound when the card's delivery starts; a press with no binding at all answers nothing (fail closed).
2272
+ const before = this.updateOfferView();
2273
+ const shownVersion = this.updateChatCardVersion.get(nonce);
2274
+ if (!shownVersion || !before || before.version !== shownVersion) {
2275
+ await this.retireNonceButtons(entry, messageId, shownVersion && before && before.version !== shownVersion ? t("update.chatcard.replaced", before.version) : t("update.chatcard.expired"));
2276
+ return true;
2277
+ }
2278
+ const tonight = (() => { const d = new Date(); d.setHours(22, 0, 0, 0); if (d.getTime() - Date.now() < 30 * 60_000)
2279
+ d.setDate(d.getDate() + 1); return d.getTime(); })();
2280
+ const body = action === "tonight" ? { action: "pick-time", at: tonight } : { action: action };
2281
+ const by = updateAnswerLabel(data.username ?? "");
2282
+ let text;
2283
+ try {
2284
+ const r = await this.ensureUpdateCard().answer(`chat-${nonce}`, by, body);
2285
+ const view = this.updateOfferView();
2286
+ let current = null;
2287
+ try {
2288
+ current = this.runningAgendVersion();
2289
+ }
2290
+ catch { /* unknown */ }
2291
+ const why = r.ok ? "" : ("key" in r.body && r.body.key !== "preflight" ? r.body.key : "error" in r.body ? r.body.error : r.body.key);
2292
+ text = r.ok ? t("update.chatcard.by", this.updateChatCardText(view, current), by) : t("update.chatcard.refused", why || String(r.status));
2293
+ const posted = this.readUpdateChatCard();
2294
+ const nextState = view?.state ?? "none";
2295
+ if (posted && posted.nonce === nonce) {
2296
+ // The press carries the message's own id where the post's record has none yet.
2297
+ this.writeUpdateChatCard({ ...posted, state: nextState, nonce: null, messageId: posted.messageId || sent?.messageId || String(messageId ?? "") });
2298
+ }
2299
+ else if (r.ok) {
2300
+ // The card is still being posted (its record is written when the post returns): it records this answer then.
2301
+ this.updateChatCardAnswered.set(nonce, nextState);
2302
+ }
2303
+ }
2304
+ catch (err) {
2305
+ text = t("update.chatcard.refused", err.message);
2306
+ }
2307
+ await this.retireNonceButtons(entry, messageId, text);
2308
+ return true;
2309
+ }
1984
2310
  hubUpdates = null;
1985
2311
  hubUpdateOwned = null;
1986
2312
  hubUpdateBootProgress = null;
2313
+ /** This process's local idle launch. Its own claim must not look like some other update holding the machine. */
2314
+ localIdleOwned = null;
2315
+ localIdleBootProgress = null;
1987
2316
  pendingHubFleetUpdates = new Map();
1988
2317
  hubFleetUpdates() { return this.hubUpdates; }
1989
- hubUpdateIdle() {
2318
+ /** `ownClaim` is this caller's launch, so that launch does not look busy to itself. The Hub queue passes its claim; the local card passes its own. */
2319
+ hubUpdateIdle(ownClaim = this.hubUpdateOwned?.claim ?? null) {
2320
+ const updates = resolveUpdates(this.fleetConfig?.updates);
2321
+ // Pause and pin hold the row. Update now forces idle on the Hub queue itself; allowed() must not cancel it.
2322
+ if (updates.pin || inUpdatePause(updates.pause, new Date()))
2323
+ return false;
1990
2324
  if (!this.startupComplete || this.shuttingDown || this.reconcileInFlight || this.topicCleanupInFlight
1991
- || this.deliveryPumpRunning || (this.webUpdateOwned && this.webUpdateOwned !== this.hubUpdateOwned?.claim))
2325
+ || this.deliveryPumpRunning || (this.webUpdateOwned && this.webUpdateOwned !== ownClaim))
1992
2326
  return false;
1993
2327
  for (const name of Object.keys(this.fleetConfig?.instances ?? {})) {
1994
2328
  if (this.restartsInFlight.has(name) || this.stopsInFlight.has(name) || this.handOffsInFlight.has(name)
@@ -2024,22 +2358,48 @@ export class FleetManager {
2024
2358
  return false;
2025
2359
  }
2026
2360
  }
2027
- async launchHubUpdate(row, control) {
2028
- if (this.shuttingDown || this.webUpdateOwned || isUpdateInProgress(this.dataDir) || !control.current())
2361
+ async launchHubUpdate(row, control, pressed = false) {
2362
+ return this.launchClaimedUpdate({
2363
+ id: row.id, version: row.version, origin: `Hub-requested update ${row.id}`, messageId: `hub-fleet-update:${row.id}`, control, hub: true,
2364
+ // M-3770 (#4480 §4.1): the owner's own Update now is a press; the idle wait starting the request is unattended.
2365
+ kind: pressed ? "press" : "unattended",
2366
+ onExit: () => {
2367
+ const outcome = this.hubUpdateOutcome(row);
2368
+ if (outcome)
2369
+ this.hubUpdates?.complete(row.id, outcome.state, outcome.currentVersion, "interrupted");
2370
+ },
2371
+ });
2372
+ }
2373
+ /**
2374
+ * One idle installer, Hub or local. Claims the machine and writes a marker before any await, then settles the row
2375
+ * when the child is gone and the marker is no longer in progress.
2376
+ */
2377
+ async launchClaimedUpdate(input) {
2378
+ if (this.shuttingDown || this.webUpdateOwned || isUpdateInProgress(this.dataDir) || !input.control.current())
2029
2379
  return false;
2030
- const claim = { startedAt: Date.now() }, owned = { id: row.id, claim };
2031
- this.hubUpdateOwned = owned;
2380
+ const claim = { startedAt: Date.now() };
2381
+ const hubOwned = input.hub ? { id: input.id, claim } : null;
2382
+ if (hubOwned)
2383
+ this.hubUpdateOwned = hubOwned;
2384
+ else
2385
+ this.localIdleOwned = claim;
2032
2386
  this.webUpdateOwned = claim;
2033
- const release = () => { if (this.hubUpdateOwned === owned)
2034
- this.hubUpdateOwned = null; if (this.webUpdateOwned === claim)
2035
- this.webUpdateOwned = null; };
2036
- if (!persistUpdateProgress(this.dataDir, { ...webUpdateTarget(claim.startedAt), messageId: `hub-fleet-update:${row.id}` }, claim.startedAt)
2037
- || !setUpdateProgressStage(this.dataDir, "preparing", { version: row.version })) {
2387
+ const owns = () => input.hub ? this.hubUpdateOwned === hubOwned : this.localIdleOwned === claim;
2388
+ const release = () => {
2389
+ if (hubOwned && this.hubUpdateOwned === hubOwned)
2390
+ this.hubUpdateOwned = null;
2391
+ if (!input.hub && this.localIdleOwned === claim)
2392
+ this.localIdleOwned = null;
2393
+ if (this.webUpdateOwned === claim)
2394
+ this.webUpdateOwned = null;
2395
+ };
2396
+ if (!persistUpdateProgress(this.dataDir, { ...webUpdateTarget(claim.startedAt), messageId: input.messageId }, claim.startedAt)
2397
+ || !setUpdateProgressStage(this.dataDir, "preparing", { version: input.version })) {
2038
2398
  release();
2039
2399
  return false;
2040
2400
  }
2041
2401
  try {
2042
- const child = await this.launchInstalledUpdate(`Hub-requested update ${row.id}`, () => !this.shuttingDown && this.hubUpdateOwned === owned && control.current() && control.claim(), row.version);
2402
+ const child = await this.launchInstalledUpdate(input.origin, () => !this.shuttingDown && owns() && input.control.current() && input.control.claim(), input.version, input.kind);
2043
2403
  if (!child) {
2044
2404
  release();
2045
2405
  return false;
@@ -2050,19 +2410,17 @@ export class FleetManager {
2050
2410
  return;
2051
2411
  endedOnce = true;
2052
2412
  const settle = () => {
2053
- if (this.shuttingDown || this.hubUpdateOwned !== owned)
2413
+ if (this.shuttingDown || !owns())
2054
2414
  return;
2055
2415
  // systemd-run may exit before its independent updater. Keep the claim while its bounded marker is active.
2056
2416
  const marker = readUpdateProgress(this.dataDir)?.progress;
2057
- if (marker?.target.messageId === `hub-fleet-update:${row.id}` && isUpdateInProgress(this.dataDir)) {
2417
+ if (marker?.target.messageId === input.messageId && isUpdateInProgress(this.dataDir)) {
2058
2418
  const timer = setTimeout(settle, 5000);
2059
2419
  timer.unref();
2060
2420
  return;
2061
2421
  }
2062
2422
  release();
2063
- const outcome = this.hubUpdateOutcome(row);
2064
- if (outcome)
2065
- this.hubUpdates?.complete(row.id, outcome.state, outcome.currentVersion, "interrupted");
2423
+ input.onExit();
2066
2424
  };
2067
2425
  settle();
2068
2426
  };
@@ -2075,6 +2433,22 @@ export class FleetManager {
2075
2433
  return false;
2076
2434
  }
2077
2435
  }
2436
+ claimedIdleOutcome(id, version) {
2437
+ let current = null;
2438
+ try {
2439
+ current = this.runningAgendVersion();
2440
+ }
2441
+ catch {
2442
+ current = null;
2443
+ }
2444
+ const messageId = idleUpdateMessageId(id);
2445
+ const matches = (marker) => !!marker
2446
+ && marker.progress.target.messageId === messageId
2447
+ && (marker.progress.version === undefined || marker.progress.version === version);
2448
+ const saved = readUpdateProgress(this.dataDir);
2449
+ const marker = matches(saved) ? saved : matches(this.localIdleBootProgress) ? this.localIdleBootProgress : null;
2450
+ return { state: idleClaimOutcome(version, current, marker) };
2451
+ }
2078
2452
  hubUpdateOutcome(row) {
2079
2453
  if (!this.startupComplete || this.hubUpdateOwned?.id === row.id)
2080
2454
  return null;
@@ -2802,6 +3176,7 @@ export class FleetManager {
2802
3176
  && (interaction.kind === "permission" || interaction.kind === "dangerous_command") };
2803
3177
  },
2804
3178
  deliver: input => this.deliverHubQuestion(input),
3179
+ updateHeld: () => this.quiescence?.armed() === true,
2805
3180
  agentToken: agent => this.hubAgentToken(agent),
2806
3181
  // attachments-v1: a question's files go into the agent's inbox; an answer's come from its own paths.
2807
3182
  files: { stateDir: this.dataDir,
@@ -2836,8 +3211,9 @@ export class FleetManager {
2836
3211
  }, caller.agent, receiptId),
2837
3212
  attachExposures: api => this.attachHubMemberExposures(api),
2838
3213
  attachAttention: (read, retry, close) => this.attachHubExecutionAttention(read, retry, close),
2839
- updates: { idle: () => this.hubUpdateIdle(), busy: () => !!this.webUpdateOwned || isUpdateInProgress(this.dataDir),
2840
- canInstall: () => this.hubUpdateCanInstall(), launch: (row, control) => this.launchHubUpdate(row, control),
3214
+ updates: { idle: () => this.hubUpdateIdle(), busy: () => !!this.webUpdateOwned || isUpdateInProgress(this.dataDir) || !!this.updateCard?.blocksAdmission(),
3215
+ canInstall: () => this.hubUpdateCanInstall(), launch: (row, control, pressed) => this.launchHubUpdate(row, control, pressed),
3216
+ onQueue: row => { this.ensureUpdateCard().observeHub(row); },
2841
3217
  active: id => this.hubUpdateOwned?.id === id, outcome: row => this.hubUpdateOutcome(row), notify: n => this.recordHubUpdateNotice(n) },
2842
3218
  attachUpdates: updates => { this.hubUpdates = updates; },
2843
3219
  attachRecommendations: read => { this.hubRecommendationRead = read; },
@@ -3976,8 +4352,13 @@ export class FleetManager {
3976
4352
  updateCheckTimer = null;
3977
4353
  /** M-2738: the last update check's answer, for the web (null until the first check settles). */
3978
4354
  updateCheckState = null;
4355
+ /** S-234: the one durable update offer. Opened on the first check or answer. */
4356
+ updateCard;
3979
4357
  /** M-2738: a web "check now" in flight, and when the last one ran (one a minute at most). */
3980
4358
  updateCheckNow = { running: null, lastAt: 0 };
4359
+ /** M-3770 (#4480 §4): the last pre-flight — a diagnostic for the page; every launch proves its local checks again. */
4360
+ updatePreflight = null;
4361
+ updatePreflightRunning = null;
3981
4362
  /** M-2738: a web start's Idempotency-Key → its answer (a retried request never starts a second update). */
3982
4363
  webUpdateStarts = new Map();
3983
4364
  /**
@@ -4590,6 +4971,7 @@ export class FleetManager {
4590
4971
  generalLocation: input => this.previewGeneralLocation(input),
4591
4972
  hubMembership: raw => hubMembershipSettings(raw),
4592
4973
  hubPageSharing: raw => hubPageSharingSettings(raw),
4974
+ guestDerivedScopes: () => this.guestDerivedScopes(),
4593
4975
  hostMonitoringAvailable: () => this.hostMonitoringAvailable(),
4594
4976
  hubPilotTrust: raw => hubPilotTrustSettings(raw, RUNNING_AGEND_VERSION),
4595
4977
  // S3c (S-55): a Hub exposure publish's confirmation summary, while a member composition is attached.
@@ -6339,6 +6721,8 @@ export class FleetManager {
6339
6721
  delivered: ticket => !!ticket.deliveryId && this.deliveryOutbox.get(ticket.deliveryId)?.state === "delivered",
6340
6722
  deliveryState: ticket => ticket.deliveryId ? this.deliveryOutbox.get(ticket.deliveryId)?.state : undefined,
6341
6723
  admit: (request, ticketId) => {
6724
+ if (this.daemons.get(request.target)?.requestContextCallsRequired?.() || this.fleetWindowsRuntime?.requestContextCallsRequired?.(request.target))
6725
+ throw Object.assign(Error(t("contact.legacyUpgrade")), { code: "request-context-legacy-decision-upgrade-required" });
6342
6726
  const payload = { ...request.payload, contactTicket: { id: ticketId, state: "delivered" } };
6343
6727
  const admitted = this.deliveryOutbox.admit({ operationId: request.operationId,
6344
6728
  sourceKey: `contact:${ticketId}`, sourceInstance: request.source,
@@ -6418,6 +6802,111 @@ export class FleetManager {
6418
6802
  ...(service.needsApplication(name) ? { originRestriction: { active: true,
6419
6803
  reason: !service.origin(name) || service.origin(name)?.kind === "unknown" ? "unknown-origin" : "earlier-non-admin", resetSupported: false } } : {}) };
6420
6804
  }
6805
+ /** Identity-only read. This does not install/enable the same-card host. */
6806
+ requestContextPolicy;
6807
+ requestContextRelay;
6808
+ /** L installs this explicitly; H defines no production switch. */
6809
+ makeRequestContextPolicy() {
6810
+ return { assert: input => {
6811
+ try {
6812
+ return assertRequestContextOperation(input);
6813
+ }
6814
+ catch (error) {
6815
+ if (error instanceof RequestContextPolicyError) {
6816
+ const call = input.admission, view = call?.coverage === "covered" && call.lease.snapshot.owner.instance === input.instance ? requestContextDisplayView(call.lease.snapshot.context) : null;
6817
+ this.emitSseEvent("message", { instance: input.instance, sender: "AgEnD", role: "status", wrap: true, text: error.message, ts: new Date().toISOString(), ...(view ? { requestProvenance: { ...view, refused: true } } : {}) });
6818
+ }
6819
+ throw error;
6820
+ }
6821
+ } };
6822
+ }
6823
+ requestContactPrincipal(req, url) {
6824
+ const resolve = () => {
6825
+ const verdict = evaluateWebRequest(req, url, this.webToken, this.webSessions, { touch: false });
6826
+ if (verdict.kind === "reject" && (verdict.reason === "csrf" || verdict.reason === "cross-site"))
6827
+ throw Error(verdict.reason);
6828
+ if (verdict.kind !== "allow" || verdict.via !== "session" || verdict.session.tier !== "admin")
6829
+ return null;
6830
+ const identity = this.webSessionIdentity(verdict.session);
6831
+ if (!identity)
6832
+ return null;
6833
+ const authority = this.webAuthority({ session: verdict.session, gateway: !!gatewayRequestContext(req), peer: gatewayRequestContext(req) ? gatewayRequestContext(req).named ? "named_link" : "quick_link" : classifyWebPeer(req) }).authority;
6834
+ const action = this.contactActor(req, url), person = { platform: identity.platform, adapterId: identity.adapter_id, userId: identity.user_id, label: identity.user_id };
6835
+ const verified = !!action && sameContactPerson(action, person);
6836
+ const binding = JSON.stringify([identity.session_handle, authority.authority_epoch, authority.kind === "web-verified" ? authority.session?.authorized_at : null]);
6837
+ return { person, binding, verified };
6838
+ };
6839
+ const first = resolve();
6840
+ if (!first)
6841
+ return null;
6842
+ return { ...first, current: () => { try {
6843
+ const now = resolve();
6844
+ return !!now && now.binding === first.binding && sameContactPerson(now.person, first.person) && now.verified === first.verified;
6845
+ }
6846
+ catch {
6847
+ return false;
6848
+ } } };
6849
+ }
6850
+ /**
6851
+ * S-229: the same-card service the native cards use. Null — today's M-3680 card and General proposals, unchanged —
6852
+ * until L installs it at the cutover; synthetic rigs install it directly. Installing it grants no actor: every
6853
+ * decision still comes from a platform callback's person through cards.decide.
6854
+ */
6855
+ requestContactCardsPort = null;
6856
+ installRequestContactCards(cards) { this.requestContactCardsPort = cards; }
6857
+ /** Dormant assembly for L and synthetic rigs; merely defining this method installs no service or route authority. */
6858
+ makeRequestContactCards() {
6859
+ this.ensureDeliveryOutbox();
6860
+ const outbox = this.deliveryOutbox, legacy = this.contactService();
6861
+ const names = () => [...new Set([...Object.keys(this.fleetConfig?.instances ?? {}), ...(this.classicChannels?.getAll() ?? []).map(room => room.instanceName)])].sort();
6862
+ const manage = (name, person) => this.contactAdminOf(name, person);
6863
+ const cards = outbox.requestContactCards({
6864
+ current: (_context, binding) => this.contactGeneration(binding.source.instance) === binding.source.incarnation && this.contactGeneration(binding.target.instance) === binding.target.incarnation && !this.hubContactRestricted(binding.source.instance),
6865
+ generation: name => { try {
6866
+ return this.contactGeneration(name);
6867
+ }
6868
+ catch {
6869
+ return null;
6870
+ } },
6871
+ canManage: manage, canDecide: (name, person) => { if (!manage(name, person))
6872
+ return false; const policy = legacy.host.store.policySnapshot(name, this.contactGeneration(name)); return person.platform === "host" && person.userId === "operator" || (policy.approvers ?? legacy.host.defaultApprovers(name)).some(row => sameContactPerson(row, person)); },
6873
+ adminOf: (name, person) => this.contactAdminOf(name, person),
6874
+ person: actor => {
6875
+ if (actor.kind !== "person" || actor.platform === "hub")
6876
+ return null;
6877
+ if (actor.platform === "host")
6878
+ return { platform: "host", adapterId: "host", userId: "operator", label: "Operator" };
6879
+ const channel = (this.fleetConfig?.channels ?? (this.fleetConfig?.channel ? [this.fleetConfig.channel] : [])).find(row => row.type === actor.platform);
6880
+ const adapter = [...this.adapters.values(), ...[...this.worlds.values()].map(world => world.adapter)].find(row => row.type === actor.platform);
6881
+ const adapterId = adapter?.id ?? channel?.id ?? channel?.type;
6882
+ if (!adapterId)
6883
+ return null;
6884
+ return { platform: actor.platform, adapterId, userId: actor.userId, label: actor.displayName ?? actor.userId };
6885
+ },
6886
+ managedTargets: person => names().filter(name => manage(name, person)),
6887
+ roleRevision: () => settingsFingerprint([settingsRevision(this.configPath), this.settingsRuntimeRevision, this.fleetConfig, names().map(name => [name, this.contactGeneration(name), legacy.host.defaultApprovers(name), legacy.host.store.policySnapshot(name).revision])]),
6888
+ label: name => this.fleetConfig?.instances[name]?.display_name ?? this.classicChannels?.getAll().find(room => room.instanceName === name)?.displayName ?? name,
6889
+ deliveryState: ticket => ticket.deliveryId ? outbox.get(ticket.deliveryId)?.state : undefined,
6890
+ legacyCurrent: request => !this.hubContactRestricted(request.source) && this.contactGeneration(request.source) === request.sourceGeneration && this.contactGeneration(request.target) === request.targetGeneration,
6891
+ admitLegacy: (request, id) => legacy.host.admit(request, id), changed: ticket => {
6892
+ this.sweepContactAuthorizationOutcomes();
6893
+ this.emitSseEvent("contact-auth", { instance: ticket.target, ticketId: ticket.id, revision: ticket.revision });
6894
+ // S-229: a decision anywhere (the web, a card) closes every native card of that request.
6895
+ try {
6896
+ this.syncHeldTicketCard(ticket);
6897
+ }
6898
+ catch (err) {
6899
+ this.logger?.warn?.({ err: err?.message, ticket: ticket.id }, "Held contact request card failed");
6900
+ }
6901
+ this.needsYou?.poke();
6902
+ },
6903
+ });
6904
+ return cards;
6905
+ }
6906
+ makeRequestContactApi() {
6907
+ const cards = this.makeRequestContactCards();
6908
+ return { principal: (req, url) => this.requestContactPrincipal(req, url), needs: actor => cards.needs(actor), permitContinuation: (req, res) => permitWebContinuation(req, res, { webToken: this.webToken, webSessions: this.webSessions }), canRead: (card, actor) => cards.canRead(card, actor), read: (id, actor) => cards.read(id, actor), list: (filter, actor) => cards.list(filter, actor), decide: (id, input, actor) => cards.decide(id, input, actor) };
6909
+ }
6421
6910
  contactActor(req, url) {
6422
6911
  const verdict = evaluateWebRequest(req, url, this.webToken, this.webSessions, { touch: false });
6423
6912
  if (verdict.kind !== "allow" || verdict.via !== "session" || verdict.session.tier !== "admin")
@@ -6523,9 +7012,13 @@ export class FleetManager {
6523
7012
  throw Error("general-only");
6524
7013
  if (this.hubContactRestricted(requester))
6525
7014
  throw Error("hub-contact-restricted");
6526
- const pending = [...this.pendingNonceButtons.values()].filter(e => e.prefix === "contact-change:");
7015
+ // S-229: a same-card proposal (contact-ticket: with a General) counts against the same limits.
7016
+ const pending = [...this.pendingNonceButtons.values()].filter(e => e.prefix === "contact-change:" || e.prefix === CONTACT_TICKET_PREFIX && !!e.generalName);
6527
7017
  if (pending.length >= 64 || pending.filter(e => e.generalName === requester).length >= 8)
6528
7018
  throw Error("contact-proposal-limit");
7019
+ const port = this.requestContactCardsPort;
7020
+ if (port && raw?.kind === "ticket-decision")
7021
+ return this.proposeSameContactCard(port, requester, raw, callerCurrent);
6529
7022
  const service = this.contactService();
6530
7023
  const plan = prepareContactChange(raw, { service, label: n => this.fleetConfig?.instances[n]?.display_name || this.contactRoom(n)?.displayName || n, timeZone: () => this.usageZone(), mode: n => { const room = this.contactRoom(n); return room ? room.restrictedMode ? "restricted" : "legacy" : undefined; },
6531
7024
  generation: n => this.contactGeneration(n), modeAdmin: (n, p) => this.contactAdminOf(n, p),
@@ -6626,7 +7119,7 @@ export class FleetManager {
6626
7119
  clearTimeout(entry.timer);
6627
7120
  // #4438 review: a card still being posted has no message yet; postHeldTicketCard retires it once it has one.
6628
7121
  if (entry.messageId)
6629
- void this.retireNonceButtons(entry, entry.messageId, heldCardOutcome(ticket.state));
7122
+ void this.retireNonceButtons(entry, entry.messageId, heldCardOutcome(ticket.state, !!ticket.requestContext));
6630
7123
  }
6631
7124
  return;
6632
7125
  }
@@ -6643,24 +7136,116 @@ export class FleetManager {
6643
7136
  }
6644
7137
  void this.postHeldTicketCard(ticket).catch((err) => this.logger?.warn?.({ err: err?.message, ticket: ticket.id }, "Could not post a held contact request to General"));
6645
7138
  }
6646
- async postHeldTicketCard(ticket) {
6647
- const adapter = this.contactAdapter(ticket.target);
7139
+ /** The one General on the target's Discord/Telegram connection that may carry its contact cards. */
7140
+ contactCardRoute(target) {
7141
+ const adapter = this.contactAdapter(target);
6648
7142
  if (!adapter || (adapter.type !== "discord" && adapter.type !== "telegram"))
6649
- return;
7143
+ return "use-web";
6650
7144
  const routes = Object.keys(this.fleetConfig?.instances ?? {}).flatMap(n => {
6651
7145
  const route = this.settingsGeneralRoute(n, adapter.type, new Set());
6652
7146
  return route && route.adapterId === adapter.id && route.adapter === adapter ? [{ name: n, ...route }] : [];
6653
7147
  });
6654
7148
  if (routes.length !== 1) {
6655
- this.logger.info({ ticket: ticket.id, routes: routes.length }, "No single General for a held contact request's card");
6656
- return;
7149
+ this.logger.info({ target, routes: routes.length }, "No single General for a held contact request's card");
7150
+ return "route-unavailable";
7151
+ }
7152
+ return { adapter, route: routes[0] };
7153
+ }
7154
+ /**
7155
+ * S-229: post slice I's same card. prepareForNativePost checks this exact General route as the posting owner before
7156
+ * and after reading (authority none, canDecide false); the entry keeps the card's CAS snapshot, so a click decides
7157
+ * exactly the image people saw, through cards.decide.
7158
+ */
7159
+ postSameContactCard(port, id, found, opts = {}) {
7160
+ const { adapter, route } = found;
7161
+ const owner = (ticket) => ticket.id === id && route.current() && this.contactAdapter(ticket.target) === adapter
7162
+ && this.adapters.get(adapter.id) === adapter && (!opts.proposalCurrent || opts.proposalCurrent());
7163
+ const card = port.prepareForNativePost(id, owner);
7164
+ if (card.ticket.state !== "pending" || card.continuedFrom)
7165
+ throw Error("contact-proposal-ticket-unavailable");
7166
+ const view = nativeContactCardText(card, opts.proposal ? { proposal: opts.proposal } : {});
7167
+ const left = Date.parse(card.ticket.expiresAt) - Date.now();
7168
+ return this.postNonceButtonPromptOrThrow({ prefix: CONTACT_TICKET_PREFIX, alertType: "clear_confirm", instanceName: route.name,
7169
+ adapter: route.adapter, adapterId: route.adapterId, chatId: route.chatId, threadId: route.topic,
7170
+ message: view.message, choices: view.choices,
7171
+ expiredText: t(opts.proposal ? "contactProposal.expired" : "contactHeld.expired"),
7172
+ timeoutMs: opts.proposal ? 5 * 60_000 : Math.max(60_000, Math.min(left, 24 * 3_600_000)),
7173
+ extra: { contactTicketId: id, contactSnapshot: card.snapshot, contactActions: view.choices.map(c => c.action), ...(opts.generalName ? { generalName: opts.generalName } : {}),
7174
+ ...(opts.proposalCurrent ? { contactProposalCurrent: opts.proposalCurrent } : {}) } });
7175
+ }
7176
+ /**
7177
+ * S-229: General proposes a decision on the same card — its one suggested choice plus Not now. General never decides:
7178
+ * the platform callback's person does, through cards.decide. Always allow needs people, expiry and a confirmation, so
7179
+ * a grant proposal is sent to the web.
7180
+ */
7181
+ async proposeSameContactCard(port, requester, raw, callerCurrent) {
7182
+ const input = ContactChangeSchema.parse(raw);
7183
+ if (input.kind !== "ticket-decision")
7184
+ throw Error("contact-proposal-use-web");
7185
+ if (input.grant)
7186
+ throw Error("contact-proposal-use-web");
7187
+ const ticket = resolvePendingTicket(this.contactService().host.store, input.ticket_id);
7188
+ if (input.revision !== undefined && input.revision !== ticket.revision)
7189
+ throw Error("conflict");
7190
+ const found = this.contactCardRoute(ticket.target);
7191
+ if (found === "use-web")
7192
+ throw Error("contact-proposal-use-web");
7193
+ if (found === "route-unavailable")
7194
+ throw Error("contact-proposal-route-unavailable");
7195
+ const requesterPin = this.lifecyclePin(requester), deadline = performance.now() + 5 * 60_000;
7196
+ let retired = false;
7197
+ const current = () => !retired && !this.shuttingDown && performance.now() < deadline && callerCurrent() && requesterPin()
7198
+ && this.fleetConfig?.instances[requester]?.general_topic === true && !this.hubContactRestricted(requester)
7199
+ && found.route.current() && this.contactAdapter(ticket.target) === found.adapter && this.adapters.get(found.adapter.id) === found.adapter;
7200
+ if (!current())
7201
+ throw Error("conflict");
7202
+ const armedBefore = new Set(this.pendingNonceButtons.values());
7203
+ const posted = this.postSameContactCard(port, ticket.id, found, { proposal: input.decision, generalName: requester, proposalCurrent: current });
7204
+ // The entry is armed synchronously; keep it, because a decision while the post is in flight removes it from the map
7205
+ // before it has a message (Prism #4501 P2) — the posted message must still close with the committed outcome.
7206
+ const entry = [...this.pendingNonceButtons.values()].find(e => !armedBefore.has(e) && e.contactTicketId === ticket.id && e.generalName === requester);
7207
+ let closed = false;
7208
+ const retire = (nonce) => {
7209
+ if (!entry || closed)
7210
+ return;
7211
+ const armed = this.pendingNonceButtons.get(nonce) === entry, fresh = this.contactService().host.store.get(ticket.id);
7212
+ if (armed && fresh?.state === "pending" && !retired && current())
7213
+ return;
7214
+ if (armed) {
7215
+ this.pendingNonceButtons.delete(nonce);
7216
+ if (entry.timer)
7217
+ clearTimeout(entry.timer);
7218
+ }
7219
+ if (!entry.messageId)
7220
+ return; // never an edit without a message
7221
+ closed = true;
7222
+ void this.retireNonceButtons(entry, entry.messageId, fresh && fresh.state !== "pending" ? heldCardOutcome(fresh.state, !!fresh.requestContext) : t("contactProposal.expired"));
7223
+ };
7224
+ void posted.then(retire, () => { });
7225
+ try {
7226
+ const nonce = await withinBudget(posted, performance.now() + 5000);
7227
+ if (!current() || this.contactService().host.store.get(ticket.id)?.state !== "pending") {
7228
+ retire(nonce);
7229
+ throw Error("conflict");
7230
+ }
7231
+ return { status: "awaiting_platform_admin_confirmation" };
7232
+ }
7233
+ catch (error) {
7234
+ retired = true;
7235
+ throw error;
6657
7236
  }
7237
+ }
7238
+ async postHeldTicketCard(ticket) {
7239
+ const found = this.contactCardRoute(ticket.target);
7240
+ if (typeof found === "string")
7241
+ return;
7242
+ const { route } = found, port = this.requestContactCardsPort;
6658
7243
  // A ClassicBot room by its own name (its display name, else its channel's), as Fleet lists it.
6659
- const route = routes[0], label = (n) => this.fleetConfig?.instances[n]?.display_name || this.contactRoom(n)?.displayName || this.contactRoom(n)?.name || n;
7244
+ const label = (n) => this.fleetConfig?.instances[n]?.display_name || this.contactRoom(n)?.displayName || this.contactRoom(n)?.name || n;
6660
7245
  const shortId = /^R[a-f0-9]{8}-/.test(ticket.id) ? ticket.id.slice(0, 9) : ticket.id;
6661
7246
  const left = Date.parse(ticket.expiresAt) - Date.now();
6662
7247
  const text = ticket.message.length > 300 ? `${ticket.message.slice(0, 299)}…` : ticket.message;
6663
- const posting = this.postNonceButtonPromptOrThrow({ prefix: CONTACT_TICKET_PREFIX, alertType: "clear_confirm", instanceName: route.name,
7248
+ const posting = port ? this.postSameContactCard(port, ticket.id, found) : this.postNonceButtonPromptOrThrow({ prefix: CONTACT_TICKET_PREFIX, alertType: "clear_confirm", instanceName: route.name,
6664
7249
  adapter: route.adapter, adapterId: route.adapterId, chatId: route.chatId, threadId: route.topic,
6665
7250
  message: [t("contactHeld.title", label(ticket.source), label(ticket.target)), `> ${text.replace(/\n+/g, " ")}`,
6666
7251
  t("contactHeld.meta", shortId, ticket.verb, left < 2 * 3_600_000 ? t("contactHeld.minutes", Math.max(1, Math.round(left / 60_000))) : t("contactHeld.hours", Math.round(left / 3_600_000))),
@@ -6669,7 +7254,7 @@ export class FleetManager {
6669
7254
  expiredText: t("contactHeld.expired"), timeoutMs: Math.max(60_000, Math.min(left, 24 * 3_600_000)),
6670
7255
  extra: { contactTicketId: ticket.id } });
6671
7256
  // The entry is armed before the platform answers (postNonceButtonPromptOrThrow sets it synchronously).
6672
- const entry = [...this.pendingNonceButtons.values()].find(e => e.prefix === CONTACT_TICKET_PREFIX && e.contactTicketId === ticket.id);
7257
+ const entry = [...this.pendingNonceButtons.values()].find(e => e.prefix === CONTACT_TICKET_PREFIX && e.contactTicketId === ticket.id && !e.generalName);
6673
7258
  const nonce = await posting;
6674
7259
  // #4438 review: decided elsewhere, or expired, while the card was being posted — it had no message to retire then; it
6675
7260
  // has one now. A card still armed for a request still waiting stays.
@@ -6683,7 +7268,7 @@ export class FleetManager {
6683
7268
  if (entry.timer)
6684
7269
  clearTimeout(entry.timer);
6685
7270
  }
6686
- await this.retireNonceButtons(entry, entry.messageId, !fresh || fresh.state === "pending" ? t("contactHeld.expired") : heldCardOutcome(fresh.state));
7271
+ await this.retireNonceButtons(entry, entry.messageId, !fresh || fresh.state === "pending" ? t("contactHeld.expired") : heldCardOutcome(fresh.state, !!fresh.requestContext));
6687
7272
  }
6688
7273
  async handleContactTicketCallback(data, adapterId, adapter) {
6689
7274
  if (!data.callbackData.startsWith(CONTACT_TICKET_PREFIX))
@@ -6691,8 +7276,28 @@ export class FleetManager {
6691
7276
  const person = data.userId && adapter && this.adapters.get(adapterId) === adapter && adapter.id === adapterId
6692
7277
  && (adapter.type === "discord" || adapter.type === "telegram") && data.userId !== adapter.getBotUserId?.()
6693
7278
  ? { platform: adapter.type, adapterId, userId: data.userId, label: data.username || data.userId } : null;
6694
- const service = this.contactService();
6695
- const mayDecide = (entry) => {
7279
+ const service = this.contactService(), port = this.requestContactCardsPort;
7280
+ // S-229: the clicker on the bot that posted the card; the nonce binds adapter, chat, thread and message.
7281
+ const nonce = /^contact-ticket:([0-9a-f]{32}):/.exec(data.callbackData)?.[1] ?? "";
7282
+ const principal = port ? nativeContactPrincipal({ adapter, adapterId, userId: data.userId, username: data.username, nonce,
7283
+ live: () => !!adapter && this.adapters.get(adapterId) === adapter && !this.shuttingDown }) : null;
7284
+ const sameCard = (entry) => !!port && !!entry.contactSnapshot;
7285
+ const mayDecide = (entry, action) => {
7286
+ if (sameCard(entry)) {
7287
+ // Only a choice this card offered: Not now exists only on a General proposal, and a proposal offers one decision.
7288
+ if (!principal || !entry.contactTicketId || !entry.contactActions?.includes(action))
7289
+ return false;
7290
+ // A reader who may decide it acts; a manager who reads a request already closed hears its outcome.
7291
+ try {
7292
+ const card = port.read(entry.contactTicketId, principal);
7293
+ return card.actions.canDecide || card.ticket.state !== "pending" && this.contactAdminOf(card.ticket.target, principal.person);
7294
+ }
7295
+ catch {
7296
+ return false;
7297
+ }
7298
+ }
7299
+ if (action === "cancel")
7300
+ return false;
6696
7301
  const ticket = person && entry.contactTicketId ? service.host.store.get(entry.contactTicketId) : undefined;
6697
7302
  try {
6698
7303
  return !!ticket && !!person && service.view(ticket, person).canDecide;
@@ -6701,12 +7306,17 @@ export class FleetManager {
6701
7306
  return false;
6702
7307
  }
6703
7308
  };
6704
- const claimed = this.consumeNonceCallback(CONTACT_TICKET_PREFIX, /^contact-ticket:([0-9a-f]{32}):(approve|decline)$/, data, adapterId, adapter, undefined, (_user, entry) => !!entry.messageId && !this.webPromptClicks.has(data) && mayDecide(entry));
7309
+ const action0 = /:(approve|decline|cancel)$/.exec(data.callbackData)?.[1] ?? "";
7310
+ const claimed = this.consumeNonceCallback(CONTACT_TICKET_PREFIX, /^contact-ticket:([0-9a-f]{32}):(approve|decline|cancel)$/, data, adapterId, adapter, undefined, (_user, entry) => !!entry.messageId && !this.webPromptClicks.has(data) && mayDecide(entry, action0));
6705
7311
  if (claimed === null)
6706
7312
  return false;
6707
7313
  if (claimed === "consumed")
6708
7314
  return true;
6709
7315
  const { entry, action } = claimed;
7316
+ if (sameCard(entry)) {
7317
+ await this.decideSameContactCard(port, principal, entry, action, data);
7318
+ return true;
7319
+ }
6710
7320
  const ticket = entry.contactTicketId ? service.host.store.get(entry.contactTicketId) : undefined;
6711
7321
  let text = t("contactHeld.closed");
6712
7322
  if (ticket?.state === "pending" && person) {
@@ -6721,6 +7331,55 @@ export class FleetManager {
6721
7331
  await this.retireNonceButtons(entry, entry.messageId ?? data.messageId, text);
6722
7332
  return true;
6723
7333
  }
7334
+ /**
7335
+ * S-229: one click on the same card. The decision is the clicker's, on the posted snapshot, through cards.decide —
7336
+ * the web's writer — so a duplicate, another card or the web racing it yields one committed outcome. A lost race
7337
+ * re-reads and shows that outcome; a changed request closes this card and posts one fresh card.
7338
+ */
7339
+ async decideSameContactCard(port, principal, entry, action, data) {
7340
+ const id = entry.contactTicketId, proposal = !!entry.generalName;
7341
+ const read = () => { try {
7342
+ return port.read(id, principal);
7343
+ }
7344
+ catch {
7345
+ return null;
7346
+ } };
7347
+ let text, repost = false;
7348
+ if (action === "cancel")
7349
+ text = t(entry.contactProposalCurrent?.() ? "contactCard.not_now_done" : "contactProposal.expired");
7350
+ else if (proposal && entry.contactProposalCurrent?.() !== true)
7351
+ text = t("contactProposal.expired");
7352
+ else {
7353
+ try {
7354
+ const card = port.decide(id, { snapshot: entry.contactSnapshot, decision: action === "approve" ? "approve-once" : "decline" }, principal);
7355
+ text = nativeContactOutcome(card, { decided: true, by: principal.person });
7356
+ }
7357
+ catch (error) {
7358
+ const failure = nativeDecisionFailure(error), card = read();
7359
+ if (failure === "changed" && card?.ticket.state === "pending") {
7360
+ text = t(proposal ? "contactProposal.expired" : "contactCard.changed");
7361
+ repost = !proposal;
7362
+ }
7363
+ else if (failure === "failed" && card?.ticket.state === "pending")
7364
+ text = t("contactHeld.failed");
7365
+ else
7366
+ text = nativeContactOutcome(card, { decided: false });
7367
+ this.logger.info({ ticket: id, code: error?.message }, "A native contact card's decision did not apply");
7368
+ }
7369
+ }
7370
+ await this.retireNonceButtons(entry, entry.messageId ?? data.messageId, text);
7371
+ const fresh = this.contactService().host.store.get(id);
7372
+ if (!fresh)
7373
+ return;
7374
+ if (repost)
7375
+ this.heldTicketCards?.delete(id);
7376
+ try {
7377
+ this.syncHeldTicketCard(fresh);
7378
+ }
7379
+ catch (err) {
7380
+ this.logger?.warn?.({ err: err?.message, ticket: id }, "Held contact request card failed");
7381
+ }
7382
+ }
6724
7383
  contactAuthorization(id, actor) {
6725
7384
  const service = this.contactService(), ticket = service.host.store.get(id);
6726
7385
  if (!ticket)
@@ -6850,6 +7509,8 @@ export class FleetManager {
6850
7509
  }
6851
7510
  /** Synchronous SQLite admission; the caller may acknowledge only after this returns. */
6852
7511
  admitDurableDelivery(input) {
7512
+ if (this.requestContextPolicy || this.requestContextRelay)
7513
+ throw Error("Scoped contact admission is required; no legacy fallback");
6853
7514
  const bindingHold = this.generalLocationDeliveryHold(input.targetInstance);
6854
7515
  if (bindingHold)
6855
7516
  throw Error(bindingHold);
@@ -6881,6 +7542,8 @@ export class FleetManager {
6881
7542
  service.host.store.inheritOrigin(input.targetInstance, { ...inheritedOrigin, chain: [...inheritedOrigin.chain, input.targetInstance] });
6882
7543
  const sourceKey = `mcp:${input.sourceInstance}:${input.operationId}:${input.targetInstance}:${input.targetSession ?? ""}:${input.kind}`;
6883
7544
  const admitted = outbox.admit({ ...input, sourceDaemonBootId, sourceKey });
7545
+ if (admitted.inserted)
7546
+ this.quiescence?.noteAdmission(admitted.delivery.deliveryId, admitted.delivery.createdSeq);
6884
7547
  if (admitted.inserted)
6885
7548
  this.publishTraffic(admitted.delivery);
6886
7549
  if (admitted.inserted)
@@ -6902,12 +7565,18 @@ export class FleetManager {
6902
7565
  kind: admitted.delivery.kind,
6903
7566
  };
6904
7567
  }
7568
+ requestDeliveryView(deliveryId) { return this.requestContextPolicy && this.requestContextRelay && this.deliveryOutbox ? requestDeliveryView(this.deliveryOutbox, deliveryId) : null; }
6905
7569
  queryDurableDeliveryStatus(callerInstance, selector) {
6906
7570
  this.ensureDeliveryOutbox();
6907
7571
  const page = this.deliveryOutbox.queryStatusForInstance(callerInstance, selector);
6908
7572
  // #1939 §10: a human receipt's authority as it reads now (switch, epoch, loopback_only).
6909
7573
  const state = page.items.some(item => item.authority) ? this.webAuthorityState() : null;
6910
7574
  const human = (item) => {
7575
+ if (selector.messageId) {
7576
+ const projection = this.requestDeliveryView(item.delivery_id);
7577
+ if (projection)
7578
+ item = { ...item, request_provenance: projection.view };
7579
+ }
6911
7580
  if (!item.authority || !state)
6912
7581
  return item;
6913
7582
  const authority = this.receiptAuthorityNow(item.authority, state);
@@ -8213,12 +8882,23 @@ export class FleetManager {
8213
8882
  await data.respond(gate === "disabled" ? t("update.disabled", this.adminListKey(adapterId)) : t("not_authorized"));
8214
8883
  return;
8215
8884
  }
8885
+ // Bare slash /update is the card. `/update now` (options.now) keeps today's immediate path.
8886
+ if (data.options?.now !== true) {
8887
+ await data.respond(this.describeUpdateOffer());
8888
+ return;
8889
+ }
8890
+ const refused = this.refuseImmediateUpdate();
8891
+ if (refused) {
8892
+ await data.respond(refused);
8893
+ return;
8894
+ }
8216
8895
  const messageId = await data.respond(t("update.progress.preparing", 0));
8217
8896
  const adapter = this.adapters.get(adapterId) ?? this.adapter;
8218
8897
  if (messageId && adapter) {
8219
8898
  const chatId = String(this.getChannelConfig(adapterId)?.group_id ?? data.channelId);
8220
8899
  this.beginUpdateProgress(adapter, chatId, data.channelId, messageId);
8221
8900
  }
8901
+ this.beginUpdateRun();
8222
8902
  // Plain `agend update`: the CLI picks the channel from the version it is about to replace (a beta install
8223
8903
  // stays on beta). Deciding here, from the package.json next to THIS code, read a source checkout's 1.22.0 as
8224
8904
  // "not a beta" and sent a beta install to @latest. #1450 C5: the INSTALLED agend, verified, by absolute path.
@@ -8229,8 +8909,14 @@ export class FleetManager {
8229
8909
  * independently with its log — or a failure in the progress marker. `stillAllowed` is asked again once the awaits
8230
8910
  * are done (the asker may have lost the right, or the fleet begun stopping, meanwhile).
8231
8911
  */
8232
- async launchInstalledUpdate(origin, stillAllowed, pin) {
8912
+ async launchInstalledUpdate(origin, stillAllowed, pin, kind = "press") {
8233
8913
  const { spawn } = await import("./child-process.js");
8914
+ // M-3770 (#4480 §4): the machine's pre-flight, proven again now — before the installed agend is resolved or run.
8915
+ const refused = await this.updatePreflightGate(kind);
8916
+ if (refused) {
8917
+ this.failUpdateProgress(refused);
8918
+ return null;
8919
+ }
8234
8920
  const installed = await resolveInstalledAgend();
8235
8921
  if (!installed.ok) {
8236
8922
  this.failUpdateProgress(`${t("update.failure.shell")} ${t("update.failure.installed", installed.reason)}`);
@@ -9187,6 +9873,18 @@ export class FleetManager {
9187
9873
  this.logger.warn({ instanceName, deliveryEpoch }, "Delivery held during tmux server recovery");
9188
9874
  await this.stormWindow.waitForDeliveryAllowed(instanceName);
9189
9875
  }
9876
+ /**
9877
+ * Last synchronous commit of a pane write (S-244). True: the barrier journaled an adapter or web turn, so it is
9878
+ * not sent. There is no await between this and `ipc.send`. Unarmed, or not an agent turn: false, and the send proceeds.
9879
+ * A Hub or room payload is not a copy: `refuseHubPane` refuses it before this, and the producer leaves the row queued.
9880
+ */
9881
+ holdPaneSend(payload) {
9882
+ return this.quiescence?.commitTurn(payload) === true;
9883
+ }
9884
+ /** The fence is up and this payload belongs to a durable Hub or room row. Do not send it and do not copy it. */
9885
+ refuseHubPane(payload) {
9886
+ return this.quiescence?.armed() === true && turnSource(payload) === "hub";
9887
+ }
9190
9888
  /**
9191
9889
  * Hand a payload to an instance's IPC, waiting out a *transient* disconnect.
9192
9890
  *
@@ -9215,7 +9913,12 @@ export class FleetManager {
9215
9913
  if (ipc?.connected) {
9216
9914
  if (beforeInput)
9217
9915
  return this.handOffAfterBeforeInput(instanceName, payload, deliveryEpoch, stillCurrent, beforeInput);
9218
- if (ipc.send(this.bindHumanReceiptPayload(instanceName, payload)))
9916
+ const wire = this.bindHumanReceiptPayload(instanceName, payload);
9917
+ if (this.refuseHubPane(wire))
9918
+ return false;
9919
+ if (this.holdPaneSend(wire))
9920
+ return true;
9921
+ if (ipc.send(wire))
9219
9922
  return true;
9220
9923
  }
9221
9924
  }
@@ -9247,15 +9950,31 @@ export class FleetManager {
9247
9950
  * goes in one attempt. After the intent is spent nothing here retries: false is the caller's uncertain outcome.
9248
9951
  */
9249
9952
  async handOffAfterBeforeInput(instanceName, payload, deliveryEpoch, stillCurrent, beforeInput) {
9953
+ // The flag is read before beforeInput and before prepareClassicForPerson. A Hub or room row stays
9954
+ // queued at its producer: no begin lease, no input intent, and no plaintext copy of the question.
9955
+ if (this.refuseHubPane(payload))
9956
+ return false;
9957
+ if (this.quiescence?.armed()) {
9958
+ const early = this.bindHumanReceiptPayload(instanceName, payload);
9959
+ if (this.holdPaneSend(early))
9960
+ return true;
9961
+ }
9250
9962
  if (!(await beforeInput()))
9251
9963
  return false;
9964
+ if (this.refuseHubPane(payload))
9965
+ return false;
9252
9966
  const privateToken = await this.prepareClassicForPerson(instanceName, payload, deliveryEpoch, stillCurrent);
9253
9967
  if (privateToken === false || this.shuttingDown || !this.deliveryCurrent(instanceName, deliveryEpoch, stillCurrent))
9254
9968
  return false;
9255
9969
  const ipc = this.instanceIpcClients.get(instanceName);
9256
9970
  if (!ipc?.connected || (privateToken && this.classicPrivacy().read(instanceName)?.token !== privateToken))
9257
9971
  return false;
9258
- const sent = ipc.send(this.bindHumanReceiptPayload(instanceName, payload));
9972
+ const wire = this.bindHumanReceiptPayload(instanceName, payload);
9973
+ if (this.refuseHubPane(wire))
9974
+ return false;
9975
+ if (this.holdPaneSend(wire))
9976
+ return true;
9977
+ const sent = ipc.send(wire);
9259
9978
  if (sent && privateToken) {
9260
9979
  try {
9261
9980
  if (this.classicPrivacy().resume(instanceName, privateToken)) {
@@ -9283,8 +10002,15 @@ export class FleetManager {
9283
10002
  const ipc = this.instanceIpcClients.get(instanceName);
9284
10003
  if (ipc?.connected && beforeInput)
9285
10004
  return this.handOffAfterBeforeInput(instanceName, payload, deliveryEpoch, stillCurrent, beforeInput);
9286
- if (ipc?.connected && ipc.send(this.bindHumanReceiptPayload(instanceName, payload)))
9287
- return true;
10005
+ if (ipc?.connected) {
10006
+ const wire = this.bindHumanReceiptPayload(instanceName, payload);
10007
+ if (this.refuseHubPane(wire))
10008
+ return false;
10009
+ if (this.holdPaneSend(wire))
10010
+ return true;
10011
+ if (ipc.send(wire))
10012
+ return true;
10013
+ }
9288
10014
  // #2484: while the instance waits for (or runs) its own start retry, the grace runs from now — so the message is
9289
10015
  // delivered once a retry brings it up, and fails only after the retries stop (they gave up, or a person stopped
9290
10016
  // or paused it) and a last grace passes without it.
@@ -9748,7 +10474,14 @@ export class FleetManager {
9748
10474
  const id = admitted.meta?.human_receipt_id;
9749
10475
  let sent = false;
9750
10476
  try {
9751
- sent = ipc.send(this.bindHumanReceiptPayload(instanceName, admitted));
10477
+ const wire = this.bindHumanReceiptPayload(instanceName, admitted);
10478
+ if (this.refuseHubPane(wire))
10479
+ return false;
10480
+ if (this.holdPaneSend(wire)) {
10481
+ sent = true;
10482
+ return true;
10483
+ }
10484
+ sent = ipc.send(wire);
9752
10485
  return sent;
9753
10486
  }
9754
10487
  finally {
@@ -11726,6 +12459,25 @@ export class FleetManager {
11726
12459
  this.writeFreshStartMarker(name);
11727
12460
  return null;
11728
12461
  }
12462
+ // M-3749: the agent's own MCP servers (user scope, and local scope for its folder) go along too, merged — whatever
12463
+ // becomes of the conversation. A failure is logged; the next launch's check tells the agent what it lacks.
12464
+ if (sw.backend === "claude-code") {
12465
+ const profileDir = (profile) => profile ? credentialProfileHome(this.dataDir, sw.backend, profile) : null;
12466
+ try {
12467
+ // What it has in the profile it leaves now (added this session too), so the next launch can say what is missing.
12468
+ recordClaudeMcpBeforeSwitch({ instanceDir: this.getInstanceDir(name), configDir: claudeConfigDirFor(profileDir(sw.from)),
12469
+ jsonPath: claudeJsonFor(profileDir(sw.from)), workingDirectory: sw.workingDirectory ?? "" });
12470
+ const mcp = carryClaudeMcpServers({ fromProfileDir: profileDir(sw.from), toProfileDir: profileDir(sw.to), workingDirectory: sw.workingDirectory ?? "" });
12471
+ const where = { name, from: sw.from ?? "default", to: sw.to ?? "default" };
12472
+ if (!mcp.carried)
12473
+ this.logger.warn({ ...where, reason: mcp.reason }, "MCP servers not carried to the new credential profile");
12474
+ else if (mcp.user.length || mcp.local.length || mcp.keptTarget.length)
12475
+ this.logger.info({ ...where, user: mcp.user, local: mcp.local, keptTarget: mcp.keptTarget }, "MCP servers carried to the new credential profile");
12476
+ }
12477
+ catch (err) {
12478
+ this.logger.warn({ name, err: err.message }, "MCP servers not carried to the new credential profile");
12479
+ }
12480
+ }
11729
12481
  let sessionId = null;
11730
12482
  try {
11731
12483
  sessionId = readFileSync(join(this.getInstanceDir(name), "session-id"), "utf-8");
@@ -11876,6 +12628,28 @@ export class FleetManager {
11876
12628
  this.namedLinkTestRunning = false;
11877
12629
  }
11878
12630
  }
12631
+ previewRouteTestRunning = false;
12632
+ /**
12633
+ * M-3814: Settings → Access → the fixed preview address's Check — the saved `web.public_link.preview_hostname`,
12634
+ * through the open fixed link's tunnel, to this preview listener (its boot id is the proof). One at a time; starts
12635
+ * nothing. An admin session only, over the public link too (M-3278; settings-api.ts).
12636
+ */
12637
+ async testPreviewRoute(input = {}) {
12638
+ if (this.previewRouteTestRunning)
12639
+ return { busy: true };
12640
+ this.previewRouteTestRunning = true;
12641
+ try {
12642
+ const listener = this.previewListening ? this.previewListener : null;
12643
+ const hostname = publicLinkPreviewHostname(this.fleetConfig?.web);
12644
+ const result = await runPreviewRouteTest({ hostname, linkOpen: !!hostname && this.publicWebLink?.fixedPreviewHost?.() === hostname,
12645
+ bootId: listener?.bootId ?? null, port: listener?.settings.port ?? null, ...(input.hostname !== undefined ? { shown: input.hostname } : {}) });
12646
+ this.logger.info({ steps: result.steps.map(s => `${s.step}:${s.code}`) }, "Fixed preview address check");
12647
+ return result;
12648
+ }
12649
+ finally {
12650
+ this.previewRouteTestRunning = false;
12651
+ }
12652
+ }
11879
12653
  getTunnelLane() {
11880
12654
  return this.tunnelPurposeLane ??= new TunnelPurposeLane(new ManagedTunnel({ dataDir: this.dataDir,
11881
12655
  log: () => this.logger.warn("Managed tunnel cleanup requires attention") }));
@@ -12558,6 +13332,17 @@ export class FleetManager {
12558
13332
  return { enabled: cfg?.enabled === true, chat: cfg?.chat !== false, explicit: cfg?.grants !== undefined, instances: Object.keys(this.fleetConfig?.instances ?? {}).sort(), rooms, connections, guests,
12559
13333
  audit: this.guestAudit() };
12560
13334
  }
13335
+ /**
13336
+ * M-3734: each guest's agents now, as guestOverview lists them (#1920's derived access while no grants are saved) — the
13337
+ * scopes "Start from today's guests" on an agent's page is checked against, as it is admitted and as it applies.
13338
+ */
13339
+ guestDerivedScopes() {
13340
+ const out = Object.create(null);
13341
+ for (const g of this.guestOverview().guests)
13342
+ if (g.scope.length)
13343
+ out[`${g.adapterId}:${g.userId}`] = [...g.scope];
13344
+ return out;
13345
+ }
12561
13346
  /** #2667: the ClassicBot rooms' instance names now — what a settings save's validation knows besides fleet.yaml's instances. */
12562
13347
  classicRoomNames() {
12563
13348
  return (this.classicChannels?.getAll() ?? []).map((r) => r.instanceName);
@@ -13473,6 +14258,7 @@ export class FleetManager {
13473
14258
  const bootUpdateMarker = updateMarkerIdentity(this.dataDir);
13474
14259
  const savedUpdateProgress = readUpdateProgress(this.dataDir);
13475
14260
  this.hubUpdateBootProgress = savedUpdateProgress;
14261
+ this.localIdleBootProgress = savedUpdateProgress;
13476
14262
  const pendingUpdateProgress = savedUpdateProgress
13477
14263
  && savedUpdateProgress.progress.stage !== "failed"
13478
14264
  && savedUpdateProgress.progress.stage !== "complete"
@@ -14060,6 +14846,9 @@ export class FleetManager {
14060
14846
  this.checkForUpdates();
14061
14847
  this.updateCheckTimer = setInterval(() => this.checkForUpdates(), 24 * 60 * 60 * 1000);
14062
14848
  }, 60 * 60 * 1000);
14849
+ // M-3770 1.5: General's update card follows the fleet's card (a Not now that ran out, a wait that started or ended).
14850
+ this.updateChatCardTimer = setInterval(() => { void this.syncUpdateChatCard(); }, 60_000);
14851
+ this.updateChatCardTimer.unref?.();
14063
14852
  const onRestart = () => this.onGracefulRestartSignal(() => process.once("SIGUSR2", onRestart));
14064
14853
  process.once("SIGUSR2", onRestart);
14065
14854
  // SIGUSR1: full process reload (graceful stop → exit). Nothing in this AgEnD sends it any more (#2356); an older
@@ -15049,6 +15838,7 @@ export class FleetManager {
15049
15838
  if (this.instanceIpcClients.get(name) === existing) {
15050
15839
  this.instanceIpcClients.delete(name);
15051
15840
  }
15841
+ this.purgeRequestContextIpcCalls(name, existing);
15052
15842
  }
15053
15843
  }
15054
15844
  const daemon = this.daemons.get(name);
@@ -15062,7 +15852,17 @@ export class FleetManager {
15062
15852
  try {
15063
15853
  await ipc.connect();
15064
15854
  this.instanceIpcClients.set(name, ipc);
15855
+ this.observeRequestContextResponses(name, ipc);
15065
15856
  ipc.on("message", safeHandler(async (msg) => {
15857
+ if ((msg.type === "fleet_outbound" || toolForIpcType(msg.type) !== null) && !this.captureRequestContextIpcCall(name, msg, ipc)) {
15858
+ if (this.instanceIpcClients.get(name) !== ipc)
15859
+ return;
15860
+ if (msg.type === "fleet_outbound")
15861
+ ipc.send({ type: "fleet_outbound_response", fleetRequestId: msg.fleetRequestId, error: "Originating request context is unavailable" });
15862
+ else
15863
+ this.refuseTypedIpc(name, msg, "Originating request context is unavailable");
15864
+ return;
15865
+ }
15066
15866
  if (msg.type === "mcp_ready") {
15067
15867
  // Register external sessions (sessionName differs from instance name)
15068
15868
  const sessionName = msg.sessionName;
@@ -15087,7 +15887,12 @@ export class FleetManager {
15087
15887
  this.sessionRegistry.set(sender, name);
15088
15888
  this.logger.info({ sessionName: sender, instanceName: name }, "Registered external session");
15089
15889
  }
15090
- await this.handleOutboundFromInstance(name, msg);
15890
+ try {
15891
+ await this.handleOutboundFromInstance(name, msg);
15892
+ }
15893
+ finally {
15894
+ this.finishRequestContextIpcCall(msg);
15895
+ }
15091
15896
  }
15092
15897
  else if (toolForIpcType(msg.type) !== null) {
15093
15898
  // Sink 2 of 3. Each of these types IS a tool and reaches its own
@@ -15208,6 +16013,7 @@ export class FleetManager {
15208
16013
  if (this.instanceIpcClients.get(name) !== ipc)
15209
16014
  return;
15210
16015
  this.instanceIpcClients.delete(name);
16016
+ this.purgeRequestContextIpcCalls(name, ipc);
15211
16017
  if (this.ipcStoppingInstances.has(name))
15212
16018
  return;
15213
16019
  this.ipcReconnect(name).catch(() => { });
@@ -16604,6 +17410,7 @@ export class FleetManager {
16604
17410
  return { allowed: true, message: "" };
16605
17411
  }
16606
17412
  async handleOutboundFromInstance(instanceName, msg) {
17413
+ const originatingCall = this.requestContextCallOf(msg);
16607
17414
  this.touchActivity(instanceName);
16608
17415
  this.setTopicIcon(instanceName, "green");
16609
17416
  const tool = msg.tool;
@@ -16644,13 +17451,30 @@ export class FleetManager {
16644
17451
  respond(null, permitted.message);
16645
17452
  return;
16646
17453
  }
17454
+ try {
17455
+ if (this.requestContextPolicy)
17456
+ requireRequestContextPolicy(this, instanceName, tool === "hub_room_status" ? "hub_room_list" : tool, args, originatingCall?.admission);
17457
+ }
17458
+ catch (error) {
17459
+ respond(null, error.message);
17460
+ return;
17461
+ }
16647
17462
  // Fleet tools resolve their own targets. A missing chat world must not prevent local
16648
17463
  // delivery, inspection or receipt lookup; only channel tools need reply routing below.
16649
17464
  const handler = outboundHandlers.get(tool);
16650
17465
  if (handler && !usesChannelAddress(tool)) {
16651
17466
  this.eventLog?.logActivity("tool_call", senderSessionName ?? instanceName, this.summarizeToolCall(tool, args));
16652
- await handler(this, args, respond, {
17467
+ let context = this;
17468
+ if (originatingCall || this.requestContextPolicy) {
17469
+ const entryBoot = sourceDaemonBootId ?? this.getDaemonBootId(instanceName);
17470
+ context = (await import("./native-agent-admission.js")).nativeAgentAdmissionContext(this, {
17471
+ instance: instanceName, operation: { tool, args }, current: () => originatingCall ? originatingCall.current() : !!entryBoot && this.getDaemonBootId(instanceName) === entryBoot, taskAllowed: () => this.checkToolPermission("ipc-outbound", instanceName, "task").allowed,
17472
+ ...(originatingCall?.admission.coverage === "covered" ? { requestContext: originatingCall.admission.lease } : { notCoveredReason: originatingCall?.admission.reason ?? "unbound-input" }),
17473
+ });
17474
+ }
17475
+ await handler(context, args, respond, {
16653
17476
  instanceName, requestId, fleetRequestId, senderSessionName, operationId, sourceDaemonBootId,
17477
+ ...(originatingCall ? { callerCurrent: () => originatingCall.current(), requestContextAdmission: originatingCall.admission } : {}),
16654
17478
  });
16655
17479
  return;
16656
17480
  }
@@ -16663,7 +17487,8 @@ export class FleetManager {
16663
17487
  return;
16664
17488
  }
16665
17489
  const claimed = this.hubReact({ correlationId: args.message_id, caller: instanceName, emoji: typeof args.emoji === "string" ? args.emoji : "",
16666
- callerCurrent: () => this.getDaemonBootId(instanceName) === bootSent });
17490
+ ...(this.requestContextPolicy ? { requestScope: captureRequestHubOutput(originatingCall?.admission) } : {}),
17491
+ callerCurrent: () => this.getDaemonBootId(instanceName) === bootSent && (!originatingCall || originatingCall.current()) });
16667
17492
  if (!claimed) {
16668
17493
  respond(null, "That message_id is not a Hub room question you were asked.");
16669
17494
  return;
@@ -16708,15 +17533,17 @@ export class FleetManager {
16708
17533
  return;
16709
17534
  }
16710
17535
  let replyBookkeeping = Promise.resolve();
16711
- const restrictedExtras = restrictedRoute ? {
16712
- prepareFiles: (paths) => this.prepareContactFiles(instanceName, paths),
17536
+ const restrictedExtras = restrictedRoute || originatingCall ? {
17537
+ ...(restrictedRoute ? { prepareFiles: (paths) => this.prepareContactFiles(instanceName, paths),
17538
+ downloadAttachment: (id) => this.downloadRoomAttachment(instanceName, id) } : {}),
16713
17539
  replyFinished: () => replyBookkeeping,
16714
- downloadAttachment: (id) => this.downloadRoomAttachment(instanceName, id),
16715
17540
  beforeSend: () => {
17541
+ if (originatingCall && !originatingCall.current())
17542
+ throw Error("Originating request context is no longer current");
16716
17543
  const current = this.restrictedClassicRouting(instanceName);
16717
- if (!current || current.adapterId !== restrictedRoute.adapterId || current.chatId !== restrictedRoute.chatId
17544
+ if (restrictedRoute && (!current || current.adapterId !== restrictedRoute.adapterId || current.chatId !== restrictedRoute.chatId
16718
17545
  || current.threadId !== restrictedRoute.threadId || this.contactGeneration(instanceName) !== restrictedIncarnation
16719
- || this.getDaemonBootId(instanceName) !== restrictedBoot)
17546
+ || this.getDaemonBootId(instanceName) !== restrictedBoot))
16720
17547
  throw Error("Restricted room route changed before delivery");
16721
17548
  },
16722
17549
  } : {};
@@ -17434,7 +18261,20 @@ export class FleetManager {
17434
18261
  ipc.send({ type: responseType, fleetRequestId, error: message });
17435
18262
  }
17436
18263
  dispatchTypedIpc(name, msg) {
18264
+ const captured = this.requestContextCallOf(msg);
18265
+ if (captured && !captured.current()) {
18266
+ this.refuseTypedIpc(name, msg, "Originating request context is no longer current");
18267
+ return;
18268
+ }
17437
18269
  const type = String(msg.type);
18270
+ try {
18271
+ if (this.requestContextPolicy)
18272
+ requireRequestContextPolicy(this, name, toolForIpcType(type) ?? type, (msg.payload ?? {}), captured?.admission);
18273
+ }
18274
+ catch (error) {
18275
+ this.refuseTypedIpc(name, msg, error.message);
18276
+ return;
18277
+ }
17438
18278
  if (type.startsWith("fleet_schedule_")) {
17439
18279
  this.handleScheduleCrud(name, msg);
17440
18280
  return;
@@ -17486,6 +18326,8 @@ export class FleetManager {
17486
18326
  const tool = String(msg.type).replace(/^fleet_/, "");
17487
18327
  try {
17488
18328
  const args = (msg.payload ?? {});
18329
+ if (this.requestContextPolicy)
18330
+ requireRequestContextPolicy(this, instanceName, tool, args, this.requestContextCallOf(msg)?.admission);
17489
18331
  const result = tool === "get_web_appearance" || tool === "preview_web_appearance"
17490
18332
  ? this.appearanceTools.handle(instanceName, tool, args)
17491
18333
  : tool === "office_view" || tool === "office_set" ? this.officeActs.handle(instanceName, tool, args)
@@ -17531,6 +18373,7 @@ export class FleetManager {
17531
18373
  try {
17532
18374
  const op = String(msg.type).replace("fleet_schedule_", "");
17533
18375
  const result = this.performScheduleOp(instanceName, op, payload, {
18376
+ requestContextAdmission: this.requestContextCallOf(msg)?.admission,
17534
18377
  // The daemon sends its last chat id, which is unset until the instance
17535
18378
  // has had a chat message — and cross-instance traffic never sets it. So
17536
18379
  // a worker that only takes delegated tasks, the very instance #895 lets
@@ -17697,7 +18540,7 @@ export class FleetManager {
17697
18540
  ipc.send({ type: "fleet_description_response", fleetRequestId, result: { description } });
17698
18541
  }
17699
18542
  // ── Agent CLI HTTP handlers ─────────────────────────────────────────
17700
- async handleScheduleCrudHttp(instance, op, args) {
18543
+ async handleScheduleCrudHttp(instance, op, args, requestContextAdmission) {
17701
18544
  if (!this.scheduler)
17702
18545
  return { error: "Scheduler not available" };
17703
18546
  if (op !== "create" && op !== "list" && op !== "update" && op !== "delete") {
@@ -17705,7 +18548,7 @@ export class FleetManager {
17705
18548
  }
17706
18549
  // No bound chat on this path, as before: a schedule made through the agent
17707
18550
  // endpoint has nowhere of its own to reply.
17708
- return this.performScheduleOp(instance, op, args, { chatId: "", threadId: null });
18551
+ return this.performScheduleOp(instance, op, args, { chatId: "", threadId: null, requestContextAdmission });
17709
18552
  }
17710
18553
  /**
17711
18554
  * The only place an agent's request creates, changes or removes a schedule
@@ -17720,6 +18563,8 @@ export class FleetManager {
17720
18563
  * of the schedule response on IPC.
17721
18564
  */
17722
18565
  performScheduleOp(caller, op, args, reply) {
18566
+ if (this.requestContextPolicy)
18567
+ requireRequestContextPolicy(this, caller, op === "list" ? "list_schedules" : `${op}_schedule`, args, reply.requestContextAdmission);
17723
18568
  const scheduler = this.scheduler;
17724
18569
  // Shape first, so the value the permission decision reads is the value the
17725
18570
  // scheduler gets. `target` used to be filtered through typeof for the
@@ -17921,10 +18766,12 @@ export class FleetManager {
17921
18766
  default: return { error: `Unknown decision op: ${op}` };
17922
18767
  }
17923
18768
  }
17924
- async handleTaskCrudHttp(instance, args) {
18769
+ async handleTaskCrudHttp(instance, args, _snapshot, requestContextAdmission) {
17925
18770
  if (!this.scheduler)
17926
18771
  return { error: "Scheduler not available" };
17927
18772
  const db = this.scheduler.db;
18773
+ if (this.requestContextPolicy)
18774
+ requireRequestContextPolicy(this, instance, "task", args, requestContextAdmission);
17928
18775
  const action = args.action;
17929
18776
  const asStr = (v) => typeof v === "string" ? v : undefined;
17930
18777
  const asStrArr = (v) => Array.isArray(v) && v.every(x => typeof x === "string") ? v : undefined;
@@ -18037,7 +18884,9 @@ export class FleetManager {
18037
18884
  return this.setPersonaEmoji(instance, args);
18038
18885
  }
18039
18886
  /** #1629: `agend-agent theme …` — the same service as the tools; `instance` is the token's. */
18040
- async handleWebThemeHttp(instance, tool, args) {
18887
+ async handleWebThemeHttp(instance, tool, args, requestContextAdmission) {
18888
+ if (this.requestContextPolicy)
18889
+ requireRequestContextPolicy(this, instance, tool, args, requestContextAdmission);
18041
18890
  if (isCanvasWorkerTool(tool))
18042
18891
  return { error: "canvas_worker_experimental", message: CANVAS_WORKER_EXPERIMENTAL_MESSAGE }; // #2799: removed
18043
18892
  if (tool === "get_web_appearance" || tool === "preview_web_appearance")
@@ -18094,6 +18943,14 @@ export class FleetManager {
18094
18943
  return;
18095
18944
  }
18096
18945
  const db = this.scheduler.db;
18946
+ try {
18947
+ if (this.requestContextPolicy)
18948
+ requireRequestContextPolicy(this, instanceName, "task", payload, this.requestContextCallOf(msg)?.admission);
18949
+ }
18950
+ catch (error) {
18951
+ ipc.send({ type: "fleet_task_response", fleetRequestId, error: error.message });
18952
+ return;
18953
+ }
18097
18954
  const action = payload.action;
18098
18955
  // #1336 P2: use the shared normalizer — trims whitespace AND drops empties,
18099
18956
  // so " \t " / [" ","\t"] are treated identically to undefined.
@@ -18560,7 +19417,9 @@ export class FleetManager {
18560
19417
  * document. Unknown keys and comments remain untouched; redundant
18561
19418
  * non-identity instance leaves are canonicalized to inheritance afterward.
18562
19419
  */
18563
- saveFleetConfig(explicitPatches = []) {
19420
+ saveFleetConfig(explicitPatches = [], requestContextAdmission) {
19421
+ if (this.requestContextPolicy && requestContextAdmission)
19422
+ requireRequestContextPolicy(this, requestContextAdmission.coverage === "covered" ? requestContextAdmission.lease.snapshot.owner.instance : "", "update_instance_config", {}, requestContextAdmission);
18564
19423
  if (!this.companyMembershipWrite && explicitPatches.some(p => p.path[0] === "hub_member"
18565
19424
  && (p.path[1] === "enabled" ? p.value !== true || p.remove : p.path.length === 1)))
18566
19425
  this.invalidateHubCompanyJoin();
@@ -20959,7 +21818,8 @@ export class FleetManager {
20959
21818
  entry.web = {
20960
21819
  text: web.text,
20961
21820
  ...(links ? { links } : {}),
20962
- actions: [...opts.choices.map(c => ({ id: c.action, label: c.label, ...(c.confirmation ? { confirmation: c.confirmation } : {}) })), ...(opts.webInput ? [{ id: opts.webInput.action, label: opts.webInput.label, input: true }] : [])],
21821
+ ...(opts.view ? { view: opts.view } : {}),
21822
+ actions: [...opts.choices.map(c => ({ id: c.action, label: c.label, ...(c.hint ? { hint: c.hint } : {}), ...(c.role ? { role: c.role } : {}), ...(c.confirmation ? { confirmation: c.confirmation } : {}) })), ...(opts.webInput ? [{ id: opts.webInput.action, label: opts.webInput.label, input: true }] : [])],
20963
21823
  expiresAt: Date.now() + (opts.timeoutMs ?? NONCE_BUTTON_TIMEOUT_MS),
20964
21824
  };
20965
21825
  this.emitSseEvent("prompt", { instance: entry.instanceName, nonce, ...entry.web });
@@ -21146,6 +22006,8 @@ export class FleetManager {
21146
22006
  return true;
21147
22007
  if (await this.handleHubUpdateCallback(data, adapterId, adapter))
21148
22008
  return true;
22009
+ if (await this.handleUpdateCardCallback(data, adapterId, adapter))
22010
+ return true; // M-3770 1.5
21149
22011
  if (await this.handleKiroReconcileCallback(data, adapterId, adapter))
21150
22012
  return true;
21151
22013
  if (await this.handleOfficePackCallback(data, adapterId, adapter))
@@ -21209,6 +22071,39 @@ export class FleetManager {
21209
22071
  this.needsPauseCache.delete(name);
21210
22072
  this.needsYou?.poke();
21211
22073
  }
22074
+ /** M-3749: the credential profile a Claude config dir belongs to, for people and agents: its name, or "default". */
22075
+ claudeProfileLabel(configDir) {
22076
+ const dir = resolvePath(configDir);
22077
+ return dirname(dir) === resolvePath(dirname(credentialProfileHome(this.dataDir, "claude-code", "x"))) ? basename(dir) : "default";
22078
+ }
22079
+ /**
22080
+ * M-3749: a launch found MCP servers the agent had under its previous profile and does not have now. Told to the agent
22081
+ * once per set (the outbox key), held until it is delivered; Needs you lists it from the daemon (instancesForNeeds).
22082
+ */
22083
+ onMcpMissing(name, missing) {
22084
+ if (!missing?.names.length)
22085
+ return;
22086
+ try {
22087
+ this.ensureDeliveryOutbox();
22088
+ const outbox = this.deliveryOutbox;
22089
+ if (!outbox)
22090
+ return;
22091
+ const digest = createHash("sha256").update(`${missing.fromConfigDir}\u0000${missing.toConfigDir}\u0000${missing.names.join(",")}`).digest("hex").slice(0, 16);
22092
+ const text = t("inst.mcp_missing", this.claudeProfileLabel(missing.fromConfigDir), this.claudeProfileLabel(missing.toConfigDir), missing.names.join(t("needs.mcp_missing_sep")));
22093
+ outbox.admitSystemNotice(name, `mcp-missing:${name}:${digest}`, text, new Date(missing.since));
22094
+ }
22095
+ catch (err) {
22096
+ this.logger.warn({ err, name }, "Could not queue the MCP-missing notice");
22097
+ }
22098
+ }
22099
+ /** M-3749: a person dismissed an agent's missing-MCP item (web or chat Acknowledge). false: nothing was outstanding. */
22100
+ acknowledgeMcpMissing(name) {
22101
+ const daemon = this.daemons.get(name);
22102
+ if (daemon?.dismissMcpMissing)
22103
+ return daemon.dismissMcpMissing();
22104
+ dismissClaudeMcpMissing(this.getInstanceDir(name));
22105
+ return false;
22106
+ }
21212
22107
  /** The list for the web: every world's items, and those of instances with no world (#1386 §5.0). */
21213
22108
  needsYouItems() {
21214
22109
  return this.needsYou?.webItems() ?? [];
@@ -21493,6 +22388,7 @@ export class FleetManager {
21493
22388
  signIn: pauseReason === "auth" ? this.signInFor(name) : null,
21494
22389
  modelSwitch: this.modelObservationForInstance(name)?.active ?? null,
21495
22390
  usageHold: this.daemons.get(name)?.usageHold?.() ?? null,
22391
+ mcpMissing: (() => { const m = this.daemons.get(name)?.mcpMissing?.(); return m ? { names: m.names, from: this.claudeProfileLabel(m.fromConfigDir), to: this.claudeProfileLabel(m.toConfigDir), since: m.since } : null; })(),
21496
22392
  nativeDeliveryHold: this.daemons.get(name)?.nativeDeliveryHold?.() ?? null,
21497
22393
  generalLocation: this.generalLocationAttention(name),
21498
22394
  paneRecovery: (() => {
@@ -21521,6 +22417,7 @@ export class FleetManager {
21521
22417
  createdAt: e.createdAt ?? Date.now(), adapterId: e.adapterId, chatId: e.chatId,
21522
22418
  ...(e.threadId !== undefined ? { threadId: e.threadId } : {}), ...(e.messageId ? { messageId: e.messageId } : {}),
21523
22419
  ...(e.assistFor ? { assistFor: e.assistFor } : {}),
22420
+ ...(e.web.view ? { view: e.web.view } : {}),
21524
22421
  });
21525
22422
  }
21526
22423
  return out;
@@ -21588,6 +22485,7 @@ export class FleetManager {
21588
22485
  id: m.id, instance: m.instance, owner: m.adapterId, username: m.username, place: m.place, preview: m.preview, since: m.since,
21589
22486
  })),
21590
22487
  acknowledgeMissed: (id, by) => this.missedOfflineStore?.acknowledge(id, by) ?? false,
22488
+ acknowledgeMcpMissing: instance => this.acknowledgeMcpMissing(instance),
21591
22489
  tasks: () => this.needsYouTaskItems(),
21592
22490
  backendSignIns: () => this.needsYouBackendSignIns(),
21593
22491
  signInKeepAlive: () => this.keepAliveAttention(),
@@ -23684,10 +24582,10 @@ export class FleetManager {
23684
24582
  ...card, title: redactSecrets(card.title), question: redactSecrets(card.question),
23685
24583
  options: card.options.map(o => ({ ...o, title: redactSecrets(o.title), description: o.description === null ? null : redactSecrets(o.description) })),
23686
24584
  } : card;
23687
- const prompt = remoteCardPrompt(instanceName, shown);
24585
+ const prompt = remoteCardPrompt(instanceName, shown, this.shownInstanceName(instanceName));
23688
24586
  const nonce = await this.postNonceButtonPrompt({
23689
24587
  prefix: REMOTE_CARD_CALLBACK_PREFIX, alertType: "interactive_prompt", instanceName, ...place,
23690
- message: prompt.message, choices: prompt.choices, webInput: prompt.webInput,
24588
+ message: prompt.message, choices: prompt.choices, webInput: prompt.webInput, ...(prompt.view ? { view: prompt.view } : {}),
23691
24589
  expiredText: t("card.expired", instanceName), timeoutMs: REMOTE_CARD_TIMEOUT_MS,
23692
24590
  extra: { remoteCard: { identity: card.identity, kind: card.kind, options: shown.kind === "question" ? shown.options.map(o => ({ n: o.n, title: o.title })) : [],
23693
24591
  requiresAdmin, ownerAdapterId: this.getInstanceAdapterId(instanceName), humanOnly: card.kind === "question" && card.humanOnly === true } },
@@ -26990,6 +27888,8 @@ export class FleetManager {
26990
27888
  posts: m.posts, // #2281: kept beside the row, never broadcast (not a row field)
26991
27889
  reserved: m.reserved, // #1774: an agent reply's place, taken when it was sent
26992
27890
  contactTicket: m.contactTicket,
27891
+ requestProvenance: m.requestProvenance,
27892
+ wrap: m.wrap,
26993
27893
  });
26994
27894
  // A sending page's own id for its pending bubble rides on the live copy only: never recorded, never replayed.
26995
27895
  const clientId = typeof data.clientId === "string" ? data.clientId : "";
@@ -30845,6 +31745,10 @@ export class FleetManager {
30845
31745
  // because we asked it to. Set synchronously — doStopAll runs to its first
30846
31746
  // await in the same tick as the signal handler, so no event can slip in.
30847
31747
  this.shuttingDown = true;
31748
+ try {
31749
+ this.updateCard?.close();
31750
+ }
31751
+ catch { /* stopping */ }
30848
31752
  this.hostMonitor?.stop();
30849
31753
  this.stopQuotaObserver?.();
30850
31754
  this.stopQuotaObserver = null;
@@ -30991,6 +31895,10 @@ export class FleetManager {
30991
31895
  clearInterval(this.updateCheckTimer);
30992
31896
  this.updateCheckTimer = null;
30993
31897
  }
31898
+ if (this.updateChatCardTimer) {
31899
+ clearInterval(this.updateChatCardTimer);
31900
+ this.updateChatCardTimer = null;
31901
+ }
30994
31902
  if (this.eventLogPruneTimer) {
30995
31903
  clearInterval(this.eventLogPruneTimer);
30996
31904
  this.eventLogPruneTimer = null;
@@ -31102,6 +32010,7 @@ export class FleetManager {
31102
32010
  // noticeable latency.
31103
32011
  await Promise.all([...this.instanceIpcClients.values()].map(ipc => Promise.resolve(ipc.close()).catch(() => { })));
31104
32012
  this.instanceIpcClients.clear();
32013
+ this.requestContextFleetCalls?.clear();
31105
32014
  this.ipcStoppingInstances.clear();
31106
32015
  for (const [, w] of this.worlds) {
31107
32016
  await w.stop().catch(() => { });
@@ -33108,6 +34017,7 @@ export class FleetManager {
33108
34017
  await ipc.close();
33109
34018
  }
33110
34019
  this.instanceIpcClients.clear();
34020
+ this.requestContextFleetCalls?.clear();
33111
34021
  await this.stopInstancesInBatches(instanceNames, name => this.stopInstance(name));
33112
34022
  // Kill remaining orphan windows to prevent stale state on restart
33113
34023
  try {
@@ -33294,10 +34204,200 @@ export class FleetManager {
33294
34204
  }
33295
34205
  return { target, fromChannel };
33296
34206
  }
33297
- /** M-2738: record a look's answer for the web — the same offer the notice below would make. */
34207
+ /** M-3770: the pre-flight probes (runUpdatePreflight; tests stub that module, so no real npm or systemctl runs). */
34208
+ async probeUpdatePreflight(opts) {
34209
+ const { defaultReadinessDeps, runUpdatePreflight } = await import("./update-readiness.js");
34210
+ return runUpdatePreflight(opts, { ...defaultReadinessDeps(), home: this.dataDir });
34211
+ }
34212
+ /**
34213
+ * M-3770: refresh the cached pre-flight for the offered version. One at a time; never throws. A run is bound to the
34214
+ * version it judged: if the offer moved meanwhile its result is not published (Prism #4483 3) and the run starts again
34215
+ * for the new one. What it finds is merged by check (mergePreflight): a launch's fresher local rows are kept.
34216
+ */
34217
+ refreshUpdatePreflight() {
34218
+ if (this.updatePreflightRunning)
34219
+ return this.updatePreflightRunning;
34220
+ const running = (async () => {
34221
+ const { mergePreflight } = await import("./update-readiness.js");
34222
+ for (let attempt = 0; attempt < 3; attempt++) {
34223
+ const target = this.updateCheckState?.offer?.version ?? null;
34224
+ let fresh;
34225
+ try {
34226
+ fresh = await this.probeUpdatePreflight({ target });
34227
+ }
34228
+ catch (err) {
34229
+ this.logger.warn({ err }, "Update pre-flight could not run");
34230
+ return;
34231
+ }
34232
+ const now = this.updateCheckState?.offer?.version ?? null;
34233
+ if (now !== target)
34234
+ continue; // the offer changed: judge the new one
34235
+ this.updatePreflight = mergePreflight(this.updatePreflight, fresh, now);
34236
+ return;
34237
+ }
34238
+ })().finally(() => { if (this.updatePreflightRunning === running)
34239
+ this.updatePreflightRunning = null; });
34240
+ this.updatePreflightRunning = running;
34241
+ return running;
34242
+ }
34243
+ /**
34244
+ * M-3770 (#4480 §4.2): identity is proven at the moment of change. The local checks run again now, whatever the cached
34245
+ * result says, and decide; the network ones (P7, P10) are `agend update`'s own. The cache takes the fresh rows and
34246
+ * keeps a cached P7/P10 only while it still applies, with its own age (mergePreflight).
34247
+ * Returns the refusal in words, or null to go ahead.
34248
+ */
34249
+ async updatePreflightGate(origin) {
34250
+ const { mergePreflight, preflightRefusal } = await import("./update-readiness.js");
34251
+ let fresh;
34252
+ try {
34253
+ fresh = await this.probeUpdatePreflight({ localOnly: true });
34254
+ }
34255
+ catch (err) {
34256
+ this.logger.warn({ err }, "Update pre-flight could not run at launch");
34257
+ return t("update.preflight.refused", t("update.preflight.code.unreadable"));
34258
+ }
34259
+ this.updatePreflight = mergePreflight(this.updatePreflight, fresh, this.updateCheckState?.offer?.version ?? null);
34260
+ return preflightRefusal(fresh, origin, (key, ...args) => t(key, ...args));
34261
+ }
34262
+ ensureUpdateCard() {
34263
+ if (this.updateCard)
34264
+ return this.updateCard;
34265
+ this.updateCard = new UpdateOfferCard({
34266
+ dataDir: this.dataDir,
34267
+ now: () => Date.now(),
34268
+ settings: () => this.fleetConfig?.updates,
34269
+ busyNames: () => this.updateBusyNames(),
34270
+ // The local claim only. The Hub queue keeps the default, so this launch still looks busy to it.
34271
+ agentsIdle: () => this.hubUpdateIdle(this.localIdleOwned),
34272
+ externalBusy: () => !!this.webUpdateOwned || isUpdateInProgress(this.dataDir) || !!this.hubUpdates?.idlePending(),
34273
+ launchNow: (by, stillAllowed) => this.startWebUpdate(by, () => !this.shuttingDown && stillAllowed()),
34274
+ launchHubNow: async (id, stillAllowed) => {
34275
+ const owner = this.hubUpdates;
34276
+ if (!owner)
34277
+ return { ok: false, status: 409, error: "request_not_found" };
34278
+ const current = () => !this.shuttingDown && this.hubUpdates === owner && stillAllowed();
34279
+ return await owner.updateNow(id, current) ? { ok: true } : { ok: false, status: 409, error: "update_not_started" };
34280
+ },
34281
+ cancelHub: id => { this.hubUpdates?.cancelWaiting(id); },
34282
+ // M-3770 (#4480 §4.1): the card refuses (412) what the machine's last pre-flight doesn't allow — a press needs
34283
+ // pressHere, a picked time (a schedule) needs self. No result yet: nothing is refused here; the launch decides.
34284
+ preflight: action => {
34285
+ const p = this.updatePreflight;
34286
+ if (!p || (action !== "when-idle" && action !== "now" && action !== "pick-time"))
34287
+ return null;
34288
+ return preflightAllows(p, action === "pick-time" ? "unattended" : "press") ? null : { preflight: p };
34289
+ },
34290
+ launchIdle: (version, control, id) => this.launchClaimedUpdate({
34291
+ id, version, origin: `idle update ${version}`, messageId: idleUpdateMessageId(id), control, hub: false,
34292
+ // M-3770 (#4480 §4.1): "Update when idle" is an admin's press that waits for idle; a picked time is a schedule,
34293
+ // which an admin-only machine never takes.
34294
+ kind: this.updateCard?.view()?.lastAnswer?.action === "when-idle" ? "press" : "unattended",
34295
+ onExit: () => { this.updateCard?.settleLocal(id, this.claimedIdleOutcome(id, version).state); },
34296
+ }),
34297
+ currentVersion: () => { try {
34298
+ return this.runningAgendVersion();
34299
+ }
34300
+ catch {
34301
+ return null;
34302
+ } },
34303
+ bootMarker: () => this.localIdleBootProgress,
34304
+ });
34305
+ return this.updateCard;
34306
+ }
34307
+ /** Display names of agents still working. Pause is not an agent. */
34308
+ updateBusyNames() {
34309
+ const out = [];
34310
+ for (const name of Object.keys(this.fleetConfig?.instances ?? {})) {
34311
+ try {
34312
+ if (this.restartsInFlight.has(name) || this.stopsInFlight.has(name) || this.handOffsInFlight.has(name)
34313
+ || this.ipcConnectInFlight.has(name) || this.ipcReconnectInFlight.has(name) || this.hasPendingIdleGatedDelivery(name)
34314
+ || this.webChannelEchoTails.has(name)) {
34315
+ out.push(this.shownInstanceName(name));
34316
+ continue;
34317
+ }
34318
+ const process = this.getInstanceStatus(name);
34319
+ if (process === "stopped" || process === "crashed")
34320
+ continue;
34321
+ if (process === "paused" && ["stopped", "crashed"].includes(this.daemons.get(name)?.getProcessStatus?.() ?? "unknown"))
34322
+ continue;
34323
+ if (process !== "running" || this.getInstanceExecutionState(name) !== "idle" || this.getInstanceInteraction(name)?.phase === "waiting") {
34324
+ out.push(this.shownInstanceName(name));
34325
+ }
34326
+ }
34327
+ catch { /* one agent that cannot be read is not named */ }
34328
+ }
34329
+ return out;
34330
+ }
34331
+ refreshUpdateCard() {
34332
+ try {
34333
+ const card = this.ensureUpdateCard();
34334
+ const marker = readUpdateProgress(this.dataDir);
34335
+ if (marker) {
34336
+ const progress = marker.progress;
34337
+ card.noteMarker({
34338
+ startedAt: marker.startedAt,
34339
+ stage: progress.stage,
34340
+ operation: progress.operation,
34341
+ ...(progress.version ? { version: progress.version } : {}),
34342
+ ...(progress.stage === "failed" ? { cause: failureCause(progress.error) } : {}),
34343
+ });
34344
+ }
34345
+ card.tick();
34346
+ void this.syncUpdateChatCard(); // M-3770 1.5: an answer from the web edits the chat card too
34347
+ return card.view();
34348
+ }
34349
+ catch (err) {
34350
+ this.logger.warn({ err }, "Update card could not be read");
34351
+ return null;
34352
+ }
34353
+ }
34354
+ /** The card, for a test or a chat reply. Null when nothing is offered, including a pin. */
34355
+ updateOfferView() {
34356
+ try {
34357
+ return this.ensureUpdateCard().view();
34358
+ }
34359
+ catch {
34360
+ return null;
34361
+ }
34362
+ }
34363
+ describeUpdateOffer() {
34364
+ let current = null;
34365
+ try {
34366
+ current = this.runningAgendVersion();
34367
+ }
34368
+ catch { /* unknown */ }
34369
+ const pinned = !!resolveUpdates(this.fleetConfig?.updates).pin;
34370
+ const reply = updateOfferReply(this.updateOfferView(), current, pinned);
34371
+ return t(reply.key, ...reply.args);
34372
+ }
34373
+ refuseImmediateUpdate() {
34374
+ return resolveUpdates(this.fleetConfig?.updates).pin ? t("update.offer.pinned") : null;
34375
+ }
34376
+ beginUpdateRun() {
34377
+ try {
34378
+ this.ensureUpdateCard().beginRun(this.updateCheckState?.offer?.version ?? "");
34379
+ }
34380
+ catch (err) {
34381
+ this.logger.warn({ err }, "Update card could not record the run");
34382
+ }
34383
+ }
34384
+ /** M-2738: record a look's answer for the web — the same offer the card keeps. */
33298
34385
  recordUpdateCheck(currentVersion, found) {
33299
34386
  const offer = found ? updateOffer(currentVersion, found.target, found.fromChannel, !!found.target && this.semverGt(found.target, currentVersion)) : null;
33300
34387
  this.updateCheckState = { offer, checkedAt: Date.now(), failed: found === null };
34388
+ try {
34389
+ const card = this.ensureUpdateCard();
34390
+ if (offer) {
34391
+ const channel = offer.channel === "latest" ? "stable" : offer.channel;
34392
+ card.noteOffer({ version: offer.version, channel, installable: offer.installable });
34393
+ }
34394
+ else if (found)
34395
+ card.clearQuietOffer();
34396
+ }
34397
+ catch (err) {
34398
+ this.logger.warn({ err }, "Update offer could not be recorded");
34399
+ }
34400
+ void this.syncUpdateChatCard(); // M-3770 1.5
33301
34401
  }
33302
34402
  async checkForUpdates() {
33303
34403
  let currentVersion;
@@ -33310,19 +34410,19 @@ export class FleetManager {
33310
34410
  try {
33311
34411
  const { target, fromChannel } = await this.lookUpUpdateTarget(currentVersion);
33312
34412
  this.recordUpdateCheck(currentVersion, { target, fromChannel });
34413
+ void this.refreshUpdatePreflight(); // M-3770: the page's "Updates on this machine" line
33313
34414
  // Only notify when target is genuinely newer (semver), so a beta user on
33314
34415
  // 2.0.8-beta.16 is never told that stable 2.0.7 is "available".
33315
34416
  if (target && this.semverGt(target, currentVersion)) {
33316
34417
  // #2910 D2 (#2925 review): a web-only fleet first — even with a General instance it has no chat for /update.
33317
34418
  const generalId = this.webOnlyPromptPlace() ? null : this.findGeneralInstance();
33318
34419
  if (generalId) {
33319
- // No release URL — Discord's SuppressEmbeds proved unreliable and the
33320
- // link preview looked bad. Version + /update instruction is enough.
33321
- // From the install's own channel tag, this is what /update installs — even a stable the release pointed the
33322
- // tag at (2.2.0 on @alpha / @beta): the plain /update text, never "/update stays on … use --stable" (#1928).
33323
- const key = fromChannel ? "update.available_current" : updateNoticeKey(currentVersion, target);
34420
+ // M-3770 1.5: an offer this install can take is General's update card (syncUpdateChatCard, from
34421
+ // recordUpdateCheck above) — posted once, edited in place — never the daily "Run: /update" post any more.
34422
+ // What stays is the line about a stable an alpha install can't take here (no card: nothing to press).
34423
+ const key = fromChannel ? null : updateNoticeKey(currentVersion, target);
33324
34424
  // #2775: null = a beta install and a stable target; beta users are never told to switch.
33325
- if (key)
34425
+ if (key && key !== "update.available_current")
33326
34426
  this.notifyInstanceTopic(generalId, t(key, `v${target}`, `v${currentVersion}`));
33327
34427
  }
33328
34428
  else if (this.webOnlyPromptPlace() && (fromChannel || updateNoticeKey(currentVersion, target))) {
@@ -33349,13 +34449,15 @@ export class FleetManager {
33349
34449
  }
33350
34450
  catch { /* unknown: the page compares nothing */ }
33351
34451
  const s = this.updateCheckState;
33352
- return { current, offer: s?.offer ?? null, hubRecommendation: this.hubRecommendedUpdate(), checkedAt: s?.checkedAt ?? null, checkFailed: s?.failed ?? false };
34452
+ return { current, offer: s?.offer ?? null, hubRecommendation: this.hubRecommendedUpdate(), checkedAt: s?.checkedAt ?? null, checkFailed: s?.failed ?? false, preflight: this.updatePreflight };
33353
34453
  },
33354
34454
  checkUpdateNow: () => this.checkUpdateNow(),
33355
34455
  updateProgress: () => webProgressOf(readUpdateProgress(this.dataDir)),
33356
34456
  startWebUpdate: (key, person, stillAllowed, pin) => this.startWebUpdateOnce(key, person, stillAllowed, pin),
33357
34457
  startHubRequestedUpdate: (key, person, stillAllowed, id) => this.startHubRequestedUpdateOnce(key, person, stillAllowed, id),
33358
34458
  updateLog: () => ({ text: readLogTail(updateLogPath(this.dataDir)), error: readUpdateProgress(this.dataDir)?.progress.error ?? null }),
34459
+ card: () => this.refreshUpdateCard(),
34460
+ answerUpdate: (key, by, body, stillAllowed) => this.ensureUpdateCard().answer(key, by, body, stillAllowed),
33359
34461
  };
33360
34462
  }
33361
34463
  /** "Check for updates": look now, no chat notice. One a minute; a second ask while one runs waits for it. */
@@ -33382,6 +34484,7 @@ export class FleetManager {
33382
34484
  catch {
33383
34485
  this.recordUpdateCheck(currentVersion, null);
33384
34486
  }
34487
+ await this.refreshUpdatePreflight(); // M-3770: answered with the page's next view
33385
34488
  })();
33386
34489
  try {
33387
34490
  await c.running;
@@ -33397,6 +34500,8 @@ export class FleetManager {
33397
34500
  * targets no chat message (WEB_UPDATE_ADAPTER); the page reads the stages the updater writes into it.
33398
34501
  */
33399
34502
  async startWebUpdate(person, stillAllowed, pin, hubRequestId) {
34503
+ if (resolveUpdates(this.fleetConfig?.updates).pin)
34504
+ return { ok: false, status: 409, error: "pinned" };
33400
34505
  if (this.shuttingDown)
33401
34506
  return { ok: false, status: 409, error: "stopping" };
33402
34507
  // Synchronous from here to the claim: a second start cannot slip in between on the event loop.
@@ -33435,6 +34540,12 @@ export class FleetManager {
33435
34540
  this.logger.error("Web update refused: its progress marker could not be written");
33436
34541
  return { ok: false, status: 503, error: "progress_not_recorded" };
33437
34542
  }
34543
+ try {
34544
+ this.ensureUpdateCard().beginRun(offer.version);
34545
+ }
34546
+ catch (err) {
34547
+ this.logger.warn({ err }, "Update card could not record the run");
34548
+ }
33438
34549
  const origin = `web update by ${person}`;
33439
34550
  // Prism #3505 P2-3: the asking session must still be current and an admin's when the updater is launched.
33440
34551
  void this.launchInstalledUpdate(origin, () => !this.shuttingDown && stillAllowed() && (!pin || this.hubRecommendationFor(pin) !== null)
@@ -34283,7 +35394,12 @@ export class FleetManager {
34283
35394
  }
34284
35395
  const listener = createPreviewListener({ settings, healthPort: boundPort, config: this.fleetConfig,
34285
35396
  // #1723: with a web.preview_origin, the open public link's dashboard frames this listener's preview too.
34286
- extraOrigins: () => { const o = settings.origin ? this.publicWebLink?.openDashboardOrigin() : null; return o ? [o] : []; },
35397
+ extraOrigins: () => {
35398
+ const o = settings.origin || this.publicWebLink?.fixedPreviewHost?.() ? this.publicWebLink?.openDashboardOrigin() : null;
35399
+ return o ? [o] : [];
35400
+ },
35401
+ // M-3814: the fixed link's preview address (a second route on its named tunnel to this port), only while it is open.
35402
+ extraHosts: () => { const h = this.publicWebLink?.fixedPreviewHost?.(); return h ? [h] : []; },
34287
35403
  // #2911 (7): CDN libraries in previews, as fleet.yaml says now (a change applies to the next preview started).
34288
35404
  cdn: () => this.fleetConfig?.web?.preview_cdn === true });
34289
35405
  this.previewListener = listener;
@@ -34367,6 +35483,18 @@ export class FleetManager {
34367
35483
  return off("needHttps", "Previews need an https web.preview_origin when the dashboard is reached over https.");
34368
35484
  return { dashboardOrigin, previewOrigin: configured, reason: null, code: null, boot: listener.bootId, frameSrc: `${configured}/frame` };
34369
35485
  }
35486
+ // M-3814: a fixed link with a fixed preview address frames this listener through its own named tunnel — never a
35487
+ // quick tunnel (no 429 from Cloudflare's limit on new temporary links).
35488
+ const fixedHost = this.publicWebLink?.fixedPreviewHost?.(exposureId) ?? null;
35489
+ if (fixedHost) {
35490
+ const listener = this.previewListening ? this.previewListener : null;
35491
+ if (!listener) {
35492
+ const why = this.previewNotListening();
35493
+ return off(why.code, why.reason, why.detail ? { detail: why.detail } : {});
35494
+ }
35495
+ const origin = `https://${fixedHost}`;
35496
+ return { dashboardOrigin, previewOrigin: origin, reason: null, code: null, boot: listener.bootId, frameSrc: `${origin}/frame` };
35497
+ }
34370
35498
  const status = this.publicWebLink?.previewStatus(exposureId) ?? null;
34371
35499
  if (!status)
34372
35500
  return off("publicLink", "Previews are not offered on this public link.");