@songsid/agend 2.4.0-beta.26 → 2.4.0-beta.27

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 (430) hide show
  1. package/dist/agent-endpoint.d.ts +1 -0
  2. package/dist/agent-endpoint.js +5 -0
  3. package/dist/agent-endpoint.js.map +1 -1
  4. package/dist/agent-whats-new.js +4 -0
  5. package/dist/agent-whats-new.js.map +1 -1
  6. package/dist/backend/kiro-auth-store.d.ts +15 -2
  7. package/dist/backend/kiro-auth-store.js +64 -0
  8. package/dist/backend/kiro-auth-store.js.map +1 -1
  9. package/dist/build-provenance.json +1 -1
  10. package/dist/channel/adapters/discord.js +4 -4
  11. package/dist/channel/adapters/discord.js.map +1 -1
  12. package/dist/channel/adapters/telegram.js +3 -3
  13. package/dist/channel/adapters/telegram.js.map +1 -1
  14. package/dist/channel/ipc-bridge.d.ts +7 -0
  15. package/dist/channel/ipc-bridge.js +45 -11
  16. package/dist/channel/ipc-bridge.js.map +1 -1
  17. package/dist/channel/mcp-server.js +3 -1
  18. package/dist/channel/mcp-server.js.map +1 -1
  19. package/dist/channel/mcp-tools.js +5 -3
  20. package/dist/channel/mcp-tools.js.map +1 -1
  21. package/dist/cli.js +35 -2
  22. package/dist/cli.js.map +1 -1
  23. package/dist/daemon.d.ts +64 -3
  24. package/dist/daemon.js +497 -102
  25. package/dist/daemon.js.map +1 -1
  26. package/dist/delivery-outbox.d.ts +107 -7
  27. package/dist/delivery-outbox.js +293 -8
  28. package/dist/delivery-outbox.js.map +1 -1
  29. package/dist/detached-fleet-stop.d.ts +40 -0
  30. package/dist/detached-fleet-stop.js +126 -0
  31. package/dist/detached-fleet-stop.js.map +1 -0
  32. package/dist/fleet-lock.d.ts +5 -0
  33. package/dist/fleet-lock.js +21 -2
  34. package/dist/fleet-lock.js.map +1 -1
  35. package/dist/fleet-manager.d.ts +482 -4
  36. package/dist/fleet-manager.js +2692 -215
  37. package/dist/fleet-manager.js.map +1 -1
  38. package/dist/fleet-windows-runtime.d.ts +39 -3
  39. package/dist/fleet-windows-runtime.js +208 -30
  40. package/dist/fleet-windows-runtime.js.map +1 -1
  41. package/dist/general-knowledge/skills/hub/SKILL.md +5 -1
  42. package/dist/general-knowledge/skills/web-dashboard/SKILL.md +95 -25
  43. package/dist/hub/admin-dashboard.js +1 -1
  44. package/dist/hub/admin-dashboard.js.map +1 -1
  45. package/dist/hub/agent-catalog.d.ts +1 -1
  46. package/dist/hub/agent-catalog.js +4 -3
  47. package/dist/hub/agent-catalog.js.map +1 -1
  48. package/dist/hub/agent-intro.d.ts +1 -1
  49. package/dist/hub/agent-intro.js +1 -1
  50. package/dist/hub/agent-intro.js.map +1 -1
  51. package/dist/hub/agent-pictures.d.ts +1 -1
  52. package/dist/hub/agent-pictures.js +4 -3
  53. package/dist/hub/agent-pictures.js.map +1 -1
  54. package/dist/hub/catalog.d.ts +2 -2
  55. package/dist/hub/catalog.js +16 -13
  56. package/dist/hub/catalog.js.map +1 -1
  57. package/dist/hub/client.js +9 -2
  58. package/dist/hub/client.js.map +1 -1
  59. package/dist/hub/compose/member.js +8 -1
  60. package/dist/hub/compose/member.js.map +1 -1
  61. package/dist/hub/compose/server.js +4 -2
  62. package/dist/hub/compose/server.js.map +1 -1
  63. package/dist/hub/fleet-updates.d.ts +2 -2
  64. package/dist/hub/fleet-updates.js +7 -5
  65. package/dist/hub/fleet-updates.js.map +1 -1
  66. package/dist/hub/fleet-versions.d.ts +1 -1
  67. package/dist/hub/fleet-versions.js +3 -2
  68. package/dist/hub/fleet-versions.js.map +1 -1
  69. package/dist/hub/group-policy/resources.d.ts +1 -1
  70. package/dist/hub/http/compose.js +57 -30
  71. package/dist/hub/http/compose.js.map +1 -1
  72. package/dist/hub/http/schema.js +4 -1
  73. package/dist/hub/http/schema.js.map +1 -1
  74. package/dist/hub/join/service.d.ts +6 -0
  75. package/dist/hub/join/service.js +10 -0
  76. package/dist/hub/join/service.js.map +1 -1
  77. package/dist/hub/member/room-ask.js +2 -0
  78. package/dist/hub/member/room-ask.js.map +1 -1
  79. package/dist/hub/member/room-post.d.ts +4 -0
  80. package/dist/hub/member/room-post.js +26 -1
  81. package/dist/hub/member/room-post.js.map +1 -1
  82. package/dist/hub/protocol.d.ts +58 -0
  83. package/dist/hub/protocol.js +3 -2
  84. package/dist/hub/protocol.js.map +1 -1
  85. package/dist/hub/quota.d.ts +2 -2
  86. package/dist/hub/quota.js +6 -4
  87. package/dist/hub/quota.js.map +1 -1
  88. package/dist/hub/read-statement.d.ts +6 -0
  89. package/dist/hub/read-statement.js +33 -0
  90. package/dist/hub/read-statement.js.map +1 -0
  91. package/dist/hub/recommendations.d.ts +1 -1
  92. package/dist/hub/recommendations.js +3 -2
  93. package/dist/hub/recommendations.js.map +1 -1
  94. package/dist/hub/representative.d.ts +2 -0
  95. package/dist/hub/representative.js +8 -4
  96. package/dist/hub/representative.js.map +1 -1
  97. package/dist/hub/roles/clock.js +6 -5
  98. package/dist/hub/roles/clock.js.map +1 -1
  99. package/dist/hub/roles/read.d.ts +2 -0
  100. package/dist/hub/roles/read.js +27 -6
  101. package/dist/hub/roles/read.js.map +1 -1
  102. package/dist/hub/room-history-model.d.ts +87 -0
  103. package/dist/hub/room-history-model.js +14 -0
  104. package/dist/hub/room-history-model.js.map +1 -0
  105. package/dist/hub/rooms/agents.d.ts +1 -1
  106. package/dist/hub/rooms/agents.js +3 -2
  107. package/dist/hub/rooms/agents.js.map +1 -1
  108. package/dist/hub/rooms/history.d.ts +8 -0
  109. package/dist/hub/rooms/history.js +31 -0
  110. package/dist/hub/rooms/history.js.map +1 -0
  111. package/dist/hub/rooms/schema.d.ts +2 -0
  112. package/dist/hub/rooms/schema.js +4 -0
  113. package/dist/hub/rooms/schema.js.map +1 -1
  114. package/dist/hub/rooms/service.d.ts +35 -19
  115. package/dist/hub/rooms/service.js +105 -26
  116. package/dist/hub/rooms/service.js.map +1 -1
  117. package/dist/hub/server.js +10 -3
  118. package/dist/hub/server.js.map +1 -1
  119. package/dist/hub/session-epoch.js +2 -1
  120. package/dist/hub/session-epoch.js.map +1 -1
  121. package/dist/hub/settings-directory-decision.js +3 -2
  122. package/dist/hub/settings-directory-decision.js.map +1 -1
  123. package/dist/hub/settings-member-address-decision.js +2 -1
  124. package/dist/hub/settings-member-address-decision.js.map +1 -1
  125. package/dist/hub/settings-web-address-decision.js +2 -1
  126. package/dist/hub/settings-web-address-decision.js.map +1 -1
  127. package/dist/hub/store.d.ts +1 -0
  128. package/dist/hub/store.js +12 -4
  129. package/dist/hub/store.js.map +1 -1
  130. package/dist/hub/types.d.ts +2 -2
  131. package/dist/hub-agent-incarnation-record.d.ts +24 -0
  132. package/dist/hub-agent-incarnation-record.js +46 -0
  133. package/dist/hub-agent-incarnation-record.js.map +1 -0
  134. package/dist/human-delivery-receipts.d.ts +16 -4
  135. package/dist/human-delivery-receipts.js +26 -5
  136. package/dist/human-delivery-receipts.js.map +1 -1
  137. package/dist/instance-lifecycle.d.ts +9 -3
  138. package/dist/instance-lifecycle.js +27 -10
  139. package/dist/instance-lifecycle.js.map +1 -1
  140. package/dist/instructions.d.ts +1 -1
  141. package/dist/local-pane-endpoint.d.ts +14 -0
  142. package/dist/local-pane-endpoint.js +32 -0
  143. package/dist/local-pane-endpoint.js.map +1 -1
  144. package/dist/locale.js +52 -4
  145. package/dist/locale.js.map +1 -1
  146. package/dist/native-agent-admission.js +9 -0
  147. package/dist/native-agent-admission.js.map +1 -1
  148. package/dist/native-exec-context.d.ts +11 -0
  149. package/dist/native-exec-context.js +18 -0
  150. package/dist/native-exec-context.js.map +1 -0
  151. package/dist/native-exec-input.d.ts +56 -0
  152. package/dist/native-exec-input.js +89 -0
  153. package/dist/native-exec-input.js.map +1 -0
  154. package/dist/native-mcp.d.ts +9 -1
  155. package/dist/native-mcp.js +29 -7
  156. package/dist/native-mcp.js.map +1 -1
  157. package/dist/native-pane-lifecycle.d.ts +3 -0
  158. package/dist/native-pane-lifecycle.js +2 -0
  159. package/dist/native-pane-lifecycle.js.map +1 -1
  160. package/dist/native-pane-manager.d.ts +18 -0
  161. package/dist/native-pane-manager.js +85 -8
  162. package/dist/native-pane-manager.js.map +1 -1
  163. package/dist/needs-you.d.ts +2 -1
  164. package/dist/needs-you.js.map +1 -1
  165. package/dist/outbound-handlers.d.ts +1 -0
  166. package/dist/outbound-handlers.js +9 -3
  167. package/dist/outbound-handlers.js.map +1 -1
  168. package/dist/outbound-schemas.d.ts +5 -0
  169. package/dist/outbound-schemas.js +2 -0
  170. package/dist/outbound-schemas.js.map +1 -1
  171. package/dist/public-web-gateway.js +3 -1
  172. package/dist/public-web-gateway.js.map +1 -1
  173. package/dist/recover.cjs +1 -0
  174. package/dist/reply-buttons-controller.d.ts +1 -0
  175. package/dist/reply-buttons-controller.js +1 -1
  176. package/dist/reply-buttons-controller.js.map +1 -1
  177. package/dist/request-contact-gate.d.ts +2 -0
  178. package/dist/request-contact-gate.js +8 -3
  179. package/dist/request-contact-gate.js.map +1 -1
  180. package/dist/request-context-activation.d.ts +29 -0
  181. package/dist/request-context-activation.js +74 -0
  182. package/dist/request-context-activation.js.map +1 -0
  183. package/dist/request-context-admission.d.ts +22 -0
  184. package/dist/request-context-admission.js +12 -0
  185. package/dist/request-context-admission.js.map +1 -0
  186. package/dist/request-context-boot.d.ts +35 -0
  187. package/dist/request-context-boot.js +97 -0
  188. package/dist/request-context-boot.js.map +1 -0
  189. package/dist/request-context-call.d.ts +2 -0
  190. package/dist/request-context-call.js.map +1 -1
  191. package/dist/request-context-continuation.d.ts +6 -0
  192. package/dist/request-context-continuation.js +24 -0
  193. package/dist/request-context-continuation.js.map +1 -0
  194. package/dist/request-context-control-api.d.ts +101 -0
  195. package/dist/request-context-control-api.js +177 -0
  196. package/dist/request-context-control-api.js.map +1 -0
  197. package/dist/request-context-control-copy.d.ts +3 -0
  198. package/dist/request-context-control-copy.js +7 -0
  199. package/dist/request-context-control-copy.js.map +1 -0
  200. package/dist/request-context-controller.d.ts +44 -0
  201. package/dist/request-context-controller.js +129 -0
  202. package/dist/request-context-controller.js.map +1 -0
  203. package/dist/request-context-delivery-resolver.d.ts +13 -0
  204. package/dist/request-context-delivery-resolver.js +30 -0
  205. package/dist/request-context-delivery-resolver.js.map +1 -0
  206. package/dist/request-context-drain.d.ts +13 -0
  207. package/dist/request-context-drain.js +79 -6
  208. package/dist/request-context-drain.js.map +1 -1
  209. package/dist/request-context-enable-offer.d.ts +13 -0
  210. package/dist/request-context-enable-offer.js +31 -0
  211. package/dist/request-context-enable-offer.js.map +1 -0
  212. package/dist/request-context-exec-owner.d.ts +39 -0
  213. package/dist/request-context-exec-owner.js +128 -0
  214. package/dist/request-context-exec-owner.js.map +1 -0
  215. package/dist/request-context-go-back-view.d.ts +1 -0
  216. package/dist/request-context-go-back-view.js +17 -0
  217. package/dist/request-context-go-back-view.js.map +1 -0
  218. package/dist/request-context-helper-readiness.d.ts +14 -0
  219. package/dist/request-context-helper-readiness.js +23 -0
  220. package/dist/request-context-helper-readiness.js.map +1 -0
  221. package/dist/request-context-helper.d.ts +20 -0
  222. package/dist/request-context-helper.js +41 -0
  223. package/dist/request-context-helper.js.map +1 -0
  224. package/dist/request-context-hub-resolver.d.ts +29 -0
  225. package/dist/request-context-hub-resolver.js +90 -0
  226. package/dist/request-context-hub-resolver.js.map +1 -0
  227. package/dist/request-context-human-resolver.d.ts +20 -0
  228. package/dist/request-context-human-resolver.js +77 -0
  229. package/dist/request-context-human-resolver.js.map +1 -0
  230. package/dist/request-context-human.d.ts +106 -0
  231. package/dist/request-context-human.js +153 -0
  232. package/dist/request-context-human.js.map +1 -0
  233. package/dist/request-context-inputs.d.ts +21 -0
  234. package/dist/request-context-inputs.js +63 -0
  235. package/dist/request-context-inputs.js.map +1 -0
  236. package/dist/request-context-installation.d.ts +117 -0
  237. package/dist/request-context-installation.js +328 -0
  238. package/dist/request-context-installation.js.map +1 -0
  239. package/dist/request-context-knowledge.d.ts +5 -0
  240. package/dist/request-context-knowledge.js +32 -0
  241. package/dist/request-context-knowledge.js.map +1 -0
  242. package/dist/request-context-native-human.d.ts +20 -0
  243. package/dist/request-context-native-human.js +91 -0
  244. package/dist/request-context-native-human.js.map +1 -0
  245. package/dist/request-context-native-output.d.ts +15 -0
  246. package/dist/request-context-native-output.js +46 -0
  247. package/dist/request-context-native-output.js.map +1 -0
  248. package/dist/request-context-native-result.d.ts +15 -0
  249. package/dist/request-context-native-result.js +46 -0
  250. package/dist/request-context-native-result.js.map +1 -0
  251. package/dist/request-context-off.d.ts +22 -0
  252. package/dist/request-context-off.js +77 -0
  253. package/dist/request-context-off.js.map +1 -0
  254. package/dist/request-context-outside-label.d.ts +5 -0
  255. package/dist/request-context-outside-label.js +28 -0
  256. package/dist/request-context-outside-label.js.map +1 -0
  257. package/dist/request-context-pane.d.ts +8 -0
  258. package/dist/request-context-pane.js +19 -0
  259. package/dist/request-context-pane.js.map +1 -1
  260. package/dist/request-context-pending-work.d.ts +11 -0
  261. package/dist/request-context-pending-work.js +43 -0
  262. package/dist/request-context-pending-work.js.map +1 -0
  263. package/dist/request-context-policy.d.ts +17 -1
  264. package/dist/request-context-policy.js +84 -6
  265. package/dist/request-context-policy.js.map +1 -1
  266. package/dist/request-context-readiness.d.ts +49 -0
  267. package/dist/request-context-readiness.js +64 -0
  268. package/dist/request-context-readiness.js.map +1 -0
  269. package/dist/request-context-recovery.d.ts +6 -2
  270. package/dist/request-context-recovery.js +25 -0
  271. package/dist/request-context-recovery.js.map +1 -1
  272. package/dist/request-context-relay.d.ts +2 -2
  273. package/dist/request-context-relay.js +10 -10
  274. package/dist/request-context-relay.js.map +1 -1
  275. package/dist/request-context-retirement.d.ts +19 -0
  276. package/dist/request-context-retirement.js +16 -0
  277. package/dist/request-context-retirement.js.map +1 -0
  278. package/dist/request-context-start.d.ts +15 -0
  279. package/dist/request-context-start.js +2 -0
  280. package/dist/request-context-start.js.map +1 -0
  281. package/dist/request-context-turns.d.ts +1 -1
  282. package/dist/request-context-turns.js +3 -2
  283. package/dist/request-context-turns.js.map +1 -1
  284. package/dist/request-context-unproved-label.d.ts +4 -0
  285. package/dist/request-context-unproved-label.js +25 -0
  286. package/dist/request-context-unproved-label.js.map +1 -0
  287. package/dist/request-context-update-guard.d.ts +15 -0
  288. package/dist/request-context-update-guard.js +54 -0
  289. package/dist/request-context-update-guard.js.map +1 -0
  290. package/dist/request-context-work.d.ts +50 -0
  291. package/dist/request-context-work.js +178 -0
  292. package/dist/request-context-work.js.map +1 -0
  293. package/dist/request-hub-context.d.ts +1 -0
  294. package/dist/request-hub-output.d.ts +2 -0
  295. package/dist/request-hub-output.js +12 -0
  296. package/dist/request-hub-output.js.map +1 -1
  297. package/dist/retained-human-control.d.ts +11 -0
  298. package/dist/retained-human-control.js +11 -0
  299. package/dist/retained-human-control.js.map +1 -0
  300. package/dist/runtime-build-info.js +1 -1
  301. package/dist/runtime-build-info.js.map +1 -1
  302. package/dist/runtime-cli.js +1 -1
  303. package/dist/runtime-cli.js.map +1 -1
  304. package/dist/runtime-client-store.js +7 -1
  305. package/dist/runtime-client-store.js.map +1 -1
  306. package/dist/runtime-client.js +15 -3
  307. package/dist/runtime-client.js.map +1 -1
  308. package/dist/runtime-coordinator.d.ts +23 -0
  309. package/dist/runtime-coordinator.js +103 -4
  310. package/dist/runtime-coordinator.js.map +1 -1
  311. package/dist/runtime-pane-mcp.d.ts +9 -0
  312. package/dist/runtime-pane-mcp.js +22 -2
  313. package/dist/runtime-pane-mcp.js.map +1 -1
  314. package/dist/runtime-protocol.d.ts +2 -0
  315. package/dist/runtime-protocol.js.map +1 -1
  316. package/dist/runtime-update-controller.js +1 -1
  317. package/dist/runtime-update-controller.js.map +1 -1
  318. package/dist/runtime-windows-bridge.d.ts +8 -0
  319. package/dist/runtime-windows-bridge.js +50 -3
  320. package/dist/runtime-windows-bridge.js.map +1 -1
  321. package/dist/service-install-handover.d.ts +52 -0
  322. package/dist/service-install-handover.js +50 -0
  323. package/dist/service-install-handover.js.map +1 -0
  324. package/dist/service-installer.d.ts +12 -0
  325. package/dist/service-installer.js +24 -10
  326. package/dist/service-installer.js.map +1 -1
  327. package/dist/settings-api.d.ts +2 -0
  328. package/dist/settings-api.js +4 -0
  329. package/dist/settings-api.js.map +1 -1
  330. package/dist/settings-baseline.d.ts +1 -0
  331. package/dist/settings-baseline.js +5 -4
  332. package/dist/settings-baseline.js.map +1 -1
  333. package/dist/settings-confirmation.d.ts +2 -0
  334. package/dist/settings-confirmation.js +6 -0
  335. package/dist/settings-confirmation.js.map +1 -1
  336. package/dist/settings-effect.d.ts +2 -0
  337. package/dist/settings-effect.js +44 -1
  338. package/dist/settings-effect.js.map +1 -1
  339. package/dist/settings-http-confirmation.d.ts +3 -0
  340. package/dist/settings-http-confirmation.js +29 -0
  341. package/dist/settings-http-confirmation.js.map +1 -1
  342. package/dist/settings-route-lifetime.d.ts +3 -1
  343. package/dist/settings-route-lifetime.js +15 -5
  344. package/dist/settings-route-lifetime.js.map +1 -1
  345. package/dist/settings-transaction.d.ts +3 -2
  346. package/dist/settings-transaction.js.map +1 -1
  347. package/dist/tips.js +1 -1
  348. package/dist/tips.js.map +1 -1
  349. package/dist/tool-permissions.js +3 -3
  350. package/dist/tool-permissions.js.map +1 -1
  351. package/dist/tool-receipt-output.d.ts +6 -6
  352. package/dist/turn-reply-guard.d.ts +16 -1
  353. package/dist/turn-reply-guard.js +20 -2
  354. package/dist/turn-reply-guard.js.map +1 -1
  355. package/dist/ui/app.html +2 -2
  356. package/dist/ui/contact-auth-strings.js +6 -6
  357. package/dist/ui/contact-authorizations.js +19 -1
  358. package/dist/ui/contact-grant-editor.js +71 -11
  359. package/dist/ui/contact-needs.js +27 -8
  360. package/dist/ui/contact-permissions.js +25 -8
  361. package/dist/ui/contact-tool-groups.js +1 -1
  362. package/dist/ui/hub-client.js +3 -0
  363. package/dist/ui/hub-room-members.js +4 -2
  364. package/dist/ui/hub-room-settings-strings.js +8 -0
  365. package/dist/ui/hub-room-settings.js +32 -0
  366. package/dist/ui/hub-room-thread.js +7 -1
  367. package/dist/ui/icons/hub-apple-touch-icon.png +0 -0
  368. package/dist/ui/icons/hub-favicon.ico +0 -0
  369. package/dist/ui/icons/hub-favicon.svg +10 -0
  370. package/dist/ui/icons/hub-icon-192.png +0 -0
  371. package/dist/ui/icons/hub-icon-512.png +0 -0
  372. package/dist/ui/icons/hub-icon-maskable-192.png +0 -0
  373. package/dist/ui/icons/hub-icon-maskable-512.png +0 -0
  374. package/dist/ui/icons/hub-maskable.svg +12 -0
  375. package/dist/ui/panel-hub.js +14 -3
  376. package/dist/ui/panel-needs.js +2 -1
  377. package/dist/ui/panel-settings.js +2 -1
  378. package/dist/ui/request-contact-card.js +287 -0
  379. package/dist/ui/request-contact-client.js +83 -0
  380. package/dist/ui/request-contact-page.js +78 -0
  381. package/dist/ui/request-context-control.js +171 -0
  382. package/dist/ui/settings-registry.js +2 -0
  383. package/dist/ui/settings-update.js +3 -2
  384. package/dist/ui/shared/app-install.js +2 -2
  385. package/dist/ui/shared/app-shell.js +13 -3
  386. package/dist/ui/shared/app-stream.js +1 -0
  387. package/dist/ui/shared/app-update.js +2 -1
  388. package/dist/ui/shared/app.css +93 -8
  389. package/dist/ui/shared/app.js +16 -2
  390. package/dist/ui/shared/ui-states.js +6 -0
  391. package/dist/ui/shared/update-card-ui.js +178 -11
  392. package/dist/ui/shared/view-strings.js +18 -0
  393. package/dist/ui/shared/web-authorize.js +1 -1
  394. package/dist/update-card.d.ts +1 -1
  395. package/dist/update-card.js +7 -7
  396. package/dist/update-card.js.map +1 -1
  397. package/dist/update-fix.d.ts +66 -0
  398. package/dist/update-fix.js +67 -0
  399. package/dist/update-fix.js.map +1 -0
  400. package/dist/update-goback.js +12 -2
  401. package/dist/update-goback.js.map +1 -1
  402. package/dist/update-readiness.d.ts +2 -0
  403. package/dist/update-readiness.js +5 -1
  404. package/dist/update-readiness.js.map +1 -1
  405. package/dist/update-snapshot-scope.js +1 -0
  406. package/dist/update-snapshot-scope.js.map +1 -1
  407. package/dist/usage/i18n-keys.d.ts +1 -1
  408. package/dist/usage/i18n-keys.js +9 -0
  409. package/dist/usage/i18n-keys.js.map +1 -1
  410. package/dist/usage/providers.d.ts +3 -11
  411. package/dist/usage/providers.js +93 -131
  412. package/dist/usage/providers.js.map +1 -1
  413. package/dist/web-api.d.ts +4 -0
  414. package/dist/web-api.js +50 -7
  415. package/dist/web-api.js.map +1 -1
  416. package/dist/web-chat-history.d.ts +2 -0
  417. package/dist/web-chat-history.js.map +1 -1
  418. package/dist/web-icons.d.ts +9 -3
  419. package/dist/web-icons.js +62 -5
  420. package/dist/web-icons.js.map +1 -1
  421. package/dist/web-update.d.ts +9 -0
  422. package/dist/windows-agents.d.ts +24 -2
  423. package/dist/windows-agents.js +110 -4
  424. package/dist/windows-agents.js.map +1 -1
  425. package/dist/windows-cli-worker.js +9 -1
  426. package/dist/windows-cli-worker.js.map +1 -1
  427. package/dist/windows-cli.d.ts +15 -0
  428. package/dist/windows-cli.js +54 -6
  429. package/dist/windows-cli.js.map +1 -1
  430. package/package.json +1 -1
@@ -1,6 +1,30 @@
1
+ import { createRequire } from "node:module";
2
+ import { RequestContextController } from "./request-context-controller.js";
3
+ import { captureRequestContextEnableOffer } from "./request-context-enable-offer.js";
4
+ import { acquireRequestContextActivationLease, requestContextUpdateSettled } from "./request-context-update-guard.js";
5
+ import { installPrefixOf } from "./home-update-lock.js";
6
+ import { requestContextEnabledNotice } from "./request-context-control-copy.js";
7
+ import { createRequestContextExecOwner } from "./request-context-exec-owner.js";
8
+ import { makeRequestContextRelay } from "./request-context-relay.js";
9
+ import { rotateHubAgentIncarnation, forgetHubAgentIncarnation, requestWorkRegistrationEvidence } from "./hub-agent-incarnation-record.js";
10
+ import { projectRequestContextNativeOutput } from "./request-context-native-output.js";
11
+ import { validateNativeExecInputProof } from "./native-exec-input.js";
12
+ import { admitRequestContextNativeResult } from "./request-context-native-result.js";
13
+ import { RequestContextLocalTurns } from "./request-context-turns.js";
14
+ import { RequestHubInputResolver } from "./request-context-hub-resolver.js";
15
+ import { makeRequestDeliveryInputResolver } from "./request-context-delivery-resolver.js";
16
+ import { makeRequestHumanInputResolver, requestHumanReplyTarget } from "./request-context-human-resolver.js";
17
+ import { markRetainedHumanControl, retainedHumanControl } from "./retained-human-control.js";
18
+ import { requestContextDigest } from "./request-context-store.js";
19
+ import { RequestContextBoot, readRequestContextBootState } from "./request-context-boot.js";
20
+ import { RequestContextPreparedWork } from "./request-context-work.js";
21
+ import { requestContextSkillText, requestContextSteeringText } from "./request-context-knowledge.js";
22
+ import { requestDeliveryContinuation } from "./request-context-continuation.js";
23
+ import { runWithRequestContextAdmission } from "./request-context-admission.js";
24
+ import { RequestContextPendingWork } from "./request-context-pending-work.js";
1
25
  import { requestDeliveryView, requestContextDisplayView } from "./request-context-view.js";
2
26
  import { captureRequestHubOutput } from "./request-hub-output.js";
3
- import { assertRequestContextOperation, requireRequestContextPolicy, RequestContextPolicyError } from "./request-context-policy.js";
27
+ import { assertRequestContextOperation, assertRequestHubContactImage, requireRequestContextPolicy, requestContextInstructionMode, requestContextPolicyInstalled, requestContextInstalledMode, RequestContextPolicyError } from "./request-context-policy.js";
4
28
  import { permitWebContinuation } from "./web-continuation.js";
5
29
  import { nativeContactCardText, nativeContactOutcome, nativeContactPrincipal, nativeDecisionFailure } from "./request-contact-native.js";
6
30
  import { RequestContextReferenceMap } from "./request-context-fence.js";
@@ -26,7 +50,7 @@ import { changeIdleClaudeCredential } from "./claude-credential-change.js";
26
50
  import { readClaudeCredentialSelection, claudeSubscriptionSuppressed } from "./claude-credential-launch.js";
27
51
  import { ClaudeCredentialVault, ClaudeCredentialError } from "./claude-credential-vault.js";
28
52
  import { withHubRoomReplyWarning } from "./hub-room-reply-warning.js";
29
- import { ContactAuthService } from "./contact-auth-service.js";
53
+ import { ContactAuthService, ContactHeldError } from "./contact-auth-service.js";
30
54
  import { stageContactFiles } from "./contact-auth-files.js";
31
55
  import { ContactOriginClearSchema, ContactPermissionsSchema, sameContactPerson } from "./contact-auth-policy.js";
32
56
  import { CLASSIC_RESTRICTED_TOOLS } from "./contact-auth-types.js";
@@ -41,7 +65,7 @@ import { GENERAL_ROLE_INSTRUCTIONS } from "./general-role.js";
41
65
  import { placeGeneralRole } from "./general-role-block.js";
42
66
  import { NativePaneRecoveryError } from "./native-pane-recovery.js";
43
67
  import { nativePaneToolAvailable, nativePaneToolRefusal } from "./native-pane-tools.js";
44
- import { windowsAgentsFor } from "./windows-agents.js";
68
+ import { WindowsAgents, windowsAgentsFor } from "./windows-agents.js";
45
69
  import { AgentRuntimeChanges } from "./agent-runtime-change.js";
46
70
  import { SubagentService } from "./subagent-service.js";
47
71
  import { QuotaNotices } from "./usage/quota-notices.js";
@@ -57,7 +81,7 @@ import { loginNoticeMode, normalizeNoticeDelivery, setNoticeMode } from "./notic
57
81
  import { DEFAULT_REPLY_TRIGGERS } from "./reply-triggers.js";
58
82
  import { WorkingRecoveryCoordinator, WORKING_RECOVERY_KIND, buildWorkingRecoveryPrompt } from "./working-recovery.js";
59
83
  import { PUBLIC_TUNNEL_TOKEN_ENV, PUBLIC_TUNNEL_TOKEN_HINT, normalizePublicTunnelToken } from "./public-tunnel-config.js";
60
- import { humanOwnerObjectId, webHumanOrigin, isWebSessionIdentity } from "./human-delivery-receipts.js";
84
+ import { humanOwnerObjectId, admittedHumanWebIngress, admittedNativeHumanIngress, webHumanOrigin, isWebSessionIdentity } from "./human-delivery-receipts.js";
61
85
  import { SettingsBaselines } from "./settings-baseline.js";
62
86
  import { hubPilotTrustSettings } from "./hub-pilot-trust-settings.js";
63
87
  import { hubMembershipSettings } from "./hub-membership-settings.js";
@@ -257,7 +281,7 @@ export function applyTaskListCap(tasks, filterAssignee, filterStatus) {
257
281
  return tasks;
258
282
  }
259
283
  import { handleWebRequest, webPeerOf, broadcastSseEvent, broadcastToGuests, SSE_HEARTBEAT_MS } from "./web-api.js";
260
- import { windowsCliEnabled, closeWindowsBridge, inventoryProbed, LOCAL_WINDOWS_CLI_OFF } from "./windows-cli.js";
284
+ import { windowsCliEnabled, closeWindowsBridge, retireWindowsBridgeForRequestContext, windowsBridgeRequestContextIdle, inventoryProbed, LOCAL_WINDOWS_CLI_OFF } from "./windows-cli.js";
261
285
  import { nativeCliVersionState } from "./runtime-pane-native.js";
262
286
  import { localWindowsCliEnabled, remoteRuntimeEnabled, setConfiguredRuntimeSwitches, maxAgentsPerMachine } from "./runtime-switches.js";
263
287
  import { RuntimeInstallService } from "./runtime-install.js";
@@ -271,7 +295,7 @@ import { NativeMcpSessions } from "./native-mcp.js";
271
295
  import { nativeProviderMcpSupported } from "./windows-cli-providers.js";
272
296
  import { cachedNativeModelCatalog, refreshNativeModelCatalogAfterSignIn } from "./native-model-catalog.js";
273
297
  import { shapeWebModelCatalog } from "./web-model-groups.js";
274
- import { isWindowsInstance, isNativePaneInstance, isNativeExecInstance, WINDOWS_CONFIG_REFUSED, nativeCredentialProfile } from "./native-instance-registry.js";
298
+ import { isWindowsInstance, isNativePaneInstance, isNativeExecInstance, WINDOWS_CONFIG_REFUSED, nativeCredentialProfile, nativeAgentId } from "./native-instance-registry.js";
275
299
  import { createNativeWindowsInstance, updateNativeWindowsInstance } from "./native-instance-api.js";
276
300
  import { NativeInstanceConfigEdit, parseNativeInstanceCreate } from "./native-instance-input.js";
277
301
  import { LogService, thinkingOn } from "./log-service.js";
@@ -325,14 +349,14 @@ import { crossInstanceVisibility, runVisibilityCommand, xmsgVisibility } from ".
325
349
  import { SEARCH_RETENTION_DAYS, SearchIndex } from "./search/search-index.js";
326
350
  import { chatDoc, taskDoc, xmsgDoc } from "./search/search-docs.js";
327
351
  import { WebSettingsTools } from "./web-settings-tools.js";
328
- import { GUEST_COMMAND_RUNS, GUEST_PREF_WRITES, GUEST_SEARCHES, bindGuestRequest, guestRouteDecision } from "./web-guest-access.js";
352
+ import { GUEST_COMMAND_RUNS, GUEST_PREF_WRITES, GUEST_SEARCHES, bindGuestRequest, guestSeesMessage, guestRouteDecision } from "./web-guest-access.js";
329
353
  import { GUEST_ROOM_TICK_MS, GuestRoomMembership, guestGroupRooms } from "./web-guest-rooms.js";
330
354
  import { Delegations, TrafficLog, trafficItem } from "./fleet-traffic.js";
331
355
  import { QuiescenceBarrier, stripHumanReceipt, UPDATE_HANDBACK_COPY_KIND, UPDATE_HANDBACK_SOURCE, handbackDue, turnSource } from "./update-quiescence.js";
332
356
  import { readCurrent as readUpdateJournal } from "./update-journal.js";
333
357
  import { installedChannel, updateNoticeKey } from "./update-check.js";
334
358
  import { idleClaimOutcome, idleUpdateMessageId, UpdateOfferCard, updateAnswerLabel, updateOfferReply } from "./update-card.js";
335
- import { preflightAllows } from "./update-readiness.js";
359
+ import { preflightAllows, preflightBlocking, preflightRefusal, preflightWords } from "./update-readiness.js";
336
360
  import { inUpdatePause, resolveUpdates } from "./update-settings.js";
337
361
  import { resolveInstalledAgend, npmForRunningInstall } from "./update-dispatch.js";
338
362
  import { HUB_UPDATE_NOTICE_FILE, HUB_UPDATE_REMIND_MS, hubNoticeDue, hubNoticeKey, readHubNoticeState, writeHubNoticeState } from "./hub-update-notice.js";
@@ -377,7 +401,7 @@ import { readBackgroundWorkEndedMarker } from "./background-work-ended.js";
377
401
  import { DEFAULT_WARM_OVERFLOW, WakeCoordinator } from "./wake-coordinator.js";
378
402
  import { TargetQueueWorker } from "./target-queue-worker.js";
379
403
  import { resolveDeliveryWorkerMode } from "./types.js";
380
- import { isFleetStartCommandLine, readProcessCommandLine, releaseProcessFleetLock } from "./fleet-lock.js";
404
+ import { isFleetStartCommandLine, readProcessCommandLine, captureProcessFleetLease, releaseProcessFleetLock } from "./fleet-lock.js";
381
405
  import { isSetupComplete, markSetupComplete } from "./setup-marker.js";
382
406
  import { reapLeftoverTunnels } from "./tunnel/lease.js";
383
407
  import { buildToolPermissionsNotice } from "./tool-permissions-notice.js";
@@ -407,7 +431,7 @@ import { DeviceLoginRequests } from "./web-device-login.js";
407
431
  import { findSigninKnownEntry, addSigninKnownDevice } from "./web-signin-device.js";
408
432
  import { adminKey, HOST_ADMIN_KEY, isOutsideLinkOwner, OUTSIDE_LINK_OWNER, OUTSIDE_LINK_RETRY_MS, OUTSIDE_OWN_CLOSES, outsideDuration, outsideTimer, TOTP_SIGNIN_OVER_PUBLIC_LINK, TOTP_STEP_SECONDS, WEB_REMOTE_ACCESS_FILE, WebRemoteAccess } from "./web-remote-access.js";
409
433
  import { evaluateSettingsRole } from "./authority/settings-role.js";
410
- import { authorityNow, classifyWebPeer, evaluateGuestIdentity, evaluateWebAuthority, HOST_OPERATOR, VERIFIED_SESSION_HOURS, webAuthorityPolicy } from "./authority/web-authority.js";
434
+ import { authorityNow, classifyWebPeer, evaluateGuestIdentity, evaluateWebAuthority, HOST_OPERATOR, hostSessionHere, VERIFIED_SESSION_HOURS, webAuthorityPolicy } from "./authority/web-authority.js";
411
435
  import { AuthorityStateStore, namedLinkLastTurnedOff } from "./authority/authority-state.js";
412
436
  import { SessionAuthorizations } from "./authority/session-authorizations.js";
413
437
  import { SessionAuthorizationRequests } from "./web-session-authorization.js";
@@ -648,6 +672,9 @@ function callbackPrefix(callbackData) {
648
672
  const colon = callbackData.indexOf(":");
649
673
  return colon === -1 ? "(none)" : callbackData.slice(0, colon + 1);
650
674
  }
675
+ // Exact server-admitted payload objects only; metadata never chooses an exec input key.
676
+ const nativeHumanInputs = new WeakMap();
677
+ const requestPayloadContinuations = new WeakMap();
651
678
  const CLASSIC_BACKEND_SELECTION_TIMEOUT_MS = 60_000;
652
679
  const CLASSIC_BACKEND_CALLBACK_PREFIX = "classic-backend:";
653
680
  const CLASSIC_MODE_CALLBACK_PREFIX = "classic-mode:";
@@ -678,6 +705,28 @@ const UPDATE_CARD_CALLBACK_PREFIX = "update-card:";
678
705
  const UPDATE_CHAT_CARD_FILE = "update-chat-card.json";
679
706
  /** The chat card's buttons live a week (Not now's own length); a newer card replaces them sooner. */
680
707
  const UPDATE_CHAT_CARD_MS = 7 * 24 * 60 * 60_000;
708
+ /**
709
+ * M-3864 R2: the chat card's Tonight: 22:00 in the fleet's zone (`defaults.scheduler.default_timezone`, else the machine's),
710
+ * the next one when today's is under 30 min away. Before, 22:00 on the machine's clock: on a UTC server for a Taipei fleet
711
+ * that was 06:00 the next morning.
712
+ */
713
+ export function updateTonightAt(now, tz) {
714
+ let day;
715
+ try {
716
+ day = new Date(now).toLocaleString("sv-SE", { timeZone: tz, hour12: false }).slice(0, 10);
717
+ }
718
+ catch {
719
+ tz = "UTC";
720
+ day = new Date(now).toISOString().slice(0, 10);
721
+ }
722
+ // Prism #4585: the zone's offset AT the candidate instant (twice, so it settles across a DST change that day), never
723
+ // the offset at the wall clock read as UTC, which can sit on the other side of the change.
724
+ const offsetAt = (ms) => Date.parse(new Date(ms).toLocaleString("sv-SE", { timeZone: tz, hour12: false }).replace(" ", "T") + "Z") - Math.floor(ms / 1000) * 1000;
725
+ const at = (date) => { const wall = Date.parse(`${date}T22:00:00Z`); const first = wall - offsetAt(wall); return wall - offsetAt(first); };
726
+ const today = at(day);
727
+ return today - now >= 30 * 60_000 ? today : at(new Date(Date.parse(`${day}T12:00:00Z`) + 86_400_000).toISOString().slice(0, 10));
728
+ }
729
+ const UPDATE_CHAT_CARD_ALL = ["when-idle", "tonight", "not-now"];
681
730
  const HUB_SHARING_CALLBACK_PREFIX = "hub-share:";
682
731
  /** M-3680: a held contact request's card in General ("contact-ticket:" + 32 hex + ":approve" = 55 bytes, under Telegram's 64). */
683
732
  const CONTACT_TICKET_PREFIX = "contact-ticket:";
@@ -846,6 +895,634 @@ export class FleetManager {
846
895
  static sighupHandlerInstalled = false;
847
896
  /** Test seam: inject a spy to verify saveFleetConfig calls fsync. Default: fsyncSync. */
848
897
  fsyncForTest = undefined;
898
+ requestContextAdmission;
899
+ requestContextBoot;
900
+ requestContextModes;
901
+ requestContextControlBox;
902
+ requestContextDrainTimer;
903
+ requestContextAttentionSince;
904
+ requestContextCollectionTimer;
905
+ requestContextCutoverErrors = [];
906
+ requestContextRetirementProofs = new Map();
907
+ requestContextRootRetired = (_drain, root) => this.requestContextRetirementProofs.get(root)?.current() === true;
908
+ ownRequestContextModes(boot, drain, off, ports, current, retireRoot) {
909
+ const box = this.deliveryOutbox;
910
+ const modes = Object.freeze({ boot, drain, off, current, retireRoot, recordHuman: (...args) => { if (this.requestContextModes !== modes || !current() || !ports.serving)
911
+ throw Error("Request human owner unavailable"); return ports.serving.human(...args); },
912
+ publish: (ready) => {
913
+ const state = box.requestContextInstallation().read();
914
+ if (!state || !current() || !ready())
915
+ throw Error("Capable publication unavailable");
916
+ const fence = boot.publication.fence(), roots = state.mode === "draining" ? box.requestContextInstallation().drainRoots() : null;
917
+ if (!ready())
918
+ throw Error("Capable readiness changed");
919
+ boot.publication.publish(state, ports, fence, current, () => box.requestContextInstallation().read(), current, root => roots?.has(root) === true);
920
+ return state;
921
+ } });
922
+ this.requestContextModes = modes;
923
+ this.requestContextHumanAdmission = (...args) => modes.recordHuman(...args);
924
+ if (!this.requestContextCollectionTimer) {
925
+ this.requestContextCollectionTimer = setInterval(() => this.collectRequestContextRoots(), 60_000);
926
+ this.requestContextCollectionTimer.unref?.();
927
+ }
928
+ return modes;
929
+ }
930
+ requestContextFirstOn;
931
+ prepareRequestContextOwnerRegistration;
932
+ requestContextOwnerStarted;
933
+ requestContextRetainedFactory;
934
+ requestContextFactoryOwner;
935
+ prepareRequestContextStart;
936
+ configureRequestContextBeforeStart;
937
+ /** First-On owner attachment, not activation. Called only by the confirmed Settings controller.
938
+ * A failed attempt reuses this process-owned admission port; it never leaves a false capable boot installed.
939
+ */
940
+ prepareRequestContextFirstOn() {
941
+ const box = this.deliveryOutbox, lease = captureProcessFleetLease(this.dataDir), manager = this.managerBootId;
942
+ if (!box || !this.fleetConfig || !lease?.current() || this.requestContextBoot || this.requestContextPolicy || box.requestContextInstallation().read() !== null)
943
+ throw Error("First activation preparation unavailable");
944
+ const preparation = this.requestContextFirstOn ?? { boot: RequestContextBoot.prepareFirstOn(randomUUID(), lease) };
945
+ const boot = preparation.boot;
946
+ if (!boot.owner.current() || this.requestContextAdmission && this.requestContextAdmission !== boot.publication.admission)
947
+ throw Error("First activation owner changed");
948
+ this.requestContextFirstOn = preparation;
949
+ this.attachRequestContextAdmission(boot.publication.admission);
950
+ const fence = boot.publication.fence(), attempt = {};
951
+ preparation.attempt = attempt;
952
+ let adopted = false;
953
+ this.requestContextBoot = boot;
954
+ this.requestContextPolicy = boot.policy;
955
+ const current = () => !this.shuttingDown && this.managerBootId === manager && lease.current() && boot.owner.current()
956
+ && this.deliveryOutbox === box && this.requestContextBoot === boot && this.requestContextPolicy === boot.policy && (adopted || this.requestContextFirstOn === preparation && preparation.attempt === attempt);
957
+ return Object.freeze({ boot, fence, current,
958
+ /** The actual activation transaction already committed; only then publish capable policy ownership. */
959
+ adoptCommitted: (epoch) => {
960
+ const state = box.requestContextInstallation().read();
961
+ if (!current() || !fence.owned() || !state || state.owner !== boot.owner.owner || state.epoch !== epoch || state.mode !== "active")
962
+ throw Error("Activation commit owner changed");
963
+ adopted = true;
964
+ this.requestContextPolicy = boot.policy;
965
+ this.requestContextFirstOn = undefined;
966
+ return state;
967
+ },
968
+ /** Physical candidates/ports and the staged connection must be undone first by their owning orchestration. */
969
+ abandon: () => {
970
+ if (!current() || this.requestContextNativeGraph || box.requestContextInstallation().read() !== null)
971
+ throw Error("Activation preparation cannot revert");
972
+ this.requestContextBoot = undefined;
973
+ this.requestContextPolicy = undefined;
974
+ try {
975
+ boot.publication.abandon(fence, () => box.requestContextInstallation().read());
976
+ preparation.attempt = undefined;
977
+ }
978
+ catch (error) {
979
+ this.requestContextBoot = boot;
980
+ this.requestContextPolicy = boot.policy;
981
+ throw error;
982
+ }
983
+ }, });
984
+ }
985
+ /** Same-manager stop/start must reconstruct behind a new lease, never reuse an old published graph. */
986
+ async resetStoppedRequestContextAssembly() {
987
+ if (!this.requestContextBoot)
988
+ return;
989
+ if (this.daemons.size || this.instanceIpcClients.size || !this.requestContextPendingWork.empty)
990
+ throw Error("Request owners are still stopping");
991
+ const old = this.requestContextBoot, box = this.deliveryOutbox, factory = this.requestContextFactoryOwner;
992
+ await this.retireRequestContextNativeFactories(() => this.requestContextBoot === old && this.daemons.size === 0 && this.instanceIpcClients.size === 0);
993
+ const nativeRetired = () => this.requestContextBoot === old && !this.requestContextNativeGraph && !this.runtimeHub && !this.fleetWindowsRuntime && !this.nativeMcpStore && !this.paneManager && !this.localPaneRelay && !this.runtimeExecutor;
994
+ await factory?.disposeStopped(nativeRetired);
995
+ if (!nativeRetired())
996
+ throw Error("Native retirement changed");
997
+ if (this.requestContextCollectionTimer)
998
+ clearInterval(this.requestContextCollectionTimer);
999
+ this.requestContextCollectionTimer = undefined;
1000
+ if (this.requestContextDrainTimer)
1001
+ clearTimeout(this.requestContextDrainTimer);
1002
+ this.requestContextDrainTimer = undefined;
1003
+ box?.close();
1004
+ this.deliveryOutbox = null;
1005
+ this.deliveryOutboxRecovered = false;
1006
+ this.requestContextControl = undefined;
1007
+ this.requestContextControlBox = undefined;
1008
+ this.requestContextBoot = undefined;
1009
+ this.requestContextModes = undefined;
1010
+ this.requestContextFirstOn = undefined;
1011
+ this.requestContextFactoryOwner = undefined;
1012
+ this.requestContextPolicy = undefined;
1013
+ this.requestContextAdmission = undefined;
1014
+ this.requestContextHumanAdmission = undefined;
1015
+ this.requestContextHubAdmission = undefined;
1016
+ this.requestContextRelay = undefined;
1017
+ this.requestContactCardsPort = null;
1018
+ this.requestContactApi = undefined;
1019
+ this.prepareRequestContextStart = undefined;
1020
+ this.configureRequestContextBeforeStart = undefined;
1021
+ this.prepareRequestContextOwnerRegistration = undefined;
1022
+ this.requestContextOwnerStarted = undefined;
1023
+ this.requestContextRetireOwner = undefined;
1024
+ this.requestContextFleetCalls = new RequestContextReferenceMap(row => row.call.admission.coverage === "covered" ? row.call.admission.lease.snapshot.context.ref.rootContextId : null, row => `fleet-call:${row.call.id}`);
1025
+ this.requestContextRetirementProofs.clear();
1026
+ this.requestContextCutoverErrors = [];
1027
+ }
1028
+ /** Retry only a never-published, never-started construction; durable malformed state still refuses. */
1029
+ async resetRequestContextUnpublishedPreparation() {
1030
+ const boot = this.requestContextBoot;
1031
+ if (!boot?.publication.heldUnpublished() || this.daemons.size || this.instanceIpcClients.size || !this.requestContextPendingWork.empty)
1032
+ throw Error("Capable preparation is still owned");
1033
+ const factory = this.requestContextFactoryOwner;
1034
+ await this.retireRequestContextNativeFactories(() => this.requestContextBoot === boot && boot.publication.heldUnpublished());
1035
+ factory?.disposeUnstarted();
1036
+ this.requestContextFactoryOwner = undefined;
1037
+ this.requestContextRetireOwner = undefined;
1038
+ this.requestContextRetainedFactory = undefined;
1039
+ this.prepareRequestContextOwnerRegistration = undefined;
1040
+ this.configureRequestContextBeforeStart = undefined;
1041
+ this.prepareRequestContextStart = () => boot.requirePreparedOwner();
1042
+ this.requestContextOwnerStarted = undefined;
1043
+ if (this.requestContextFleetCalls.size)
1044
+ throw Error("Request calls are still owned");
1045
+ this.requestContextFleetCalls = new RequestContextReferenceMap(row => row.call.admission.coverage === "covered" ? row.call.admission.lease.snapshot.context.ref.rootContextId : null, row => `fleet-call:${row.call.id}`);
1046
+ }
1047
+ async prepareRequestContextCapableBoot(rootRetired) {
1048
+ const [{ RequestContextPaneProofs }, { RequestContextOffOwner }] = await Promise.all([import("./request-context-pane.js"), import("./request-context-off.js")]);
1049
+ const boot = this.requestContextBoot, box = this.deliveryOutbox, lease = captureProcessFleetLease(this.dataDir), manager = this.managerBootId;
1050
+ if (!boot || !box || !lease?.current() || !this.fleetConfig || !box.requestContextInstallation().read() || !boot.publication.heldUnpublished()
1051
+ || this.daemons.size || this.instanceIpcClients.size || this.requestContextNativeGraph)
1052
+ throw Error("Capable boot preparation unavailable");
1053
+ boot.publication.fence();
1054
+ const owned = () => !this.shuttingDown && lease.current() && this.managerBootId === manager && this.requestContextBoot === boot && this.deliveryOutbox === box;
1055
+ const drain = box.requestContextDrain(() => owned() ? boot.owner.owner : null), registration = drain.registration();
1056
+ this.setRequestContextDrainRegistration(registration);
1057
+ const policy = Object.freeze({ assert: (input) => boot.policy.assert(input), installedMode: () => boot.publication.installedMode(),
1058
+ instructionMode: () => boot.publication.installedMode() ?? (owned() && boot.publication.heldUnpublished() ? box.requestContextInstallation().read()?.mode ?? null : null) });
1059
+ const factory = this.installRequestContextRetainedOwners(policy, registration, owned);
1060
+ this.requestContextFactoryOwner = factory;
1061
+ this.stageRequestContextNativeGraph({ registration, panes: new RequestContextPaneProofs(randomBytes(32).toString("hex"), registration), execTurns: factory.execTurns, execOwner: factory.execOwner, execInput: factory.execInput, current: () => owned() && factory.current() });
1062
+ const inventory = await this.prepareRequestContextDrainOwners(drain, registration, factory, owned), current = () => owned() && factory.current() && inventory.current();
1063
+ const serving = this.prepareRequestContextServingOwners(current, root => rootRetired(drain, root), factory.hub, () => boot.publication.installedMode()), ports = { policy: serving.policy, serving };
1064
+ this.bindRequestContextServingPublication(boot);
1065
+ const off = new RequestContextOffOwner(box.requestContextInstallation(), drain, boot.publication, { owner: boot.owner.owner, current }, { ports, current });
1066
+ const modes = this.ownRequestContextModes(boot, drain, off, ports, current, root => serving.gate.retireRoot(root));
1067
+ return Object.freeze({ ...modes, factory });
1068
+ }
1069
+ /** Exact persistent roster for controlled On; exec owners and durable drain assessment are separate required participants. */
1070
+ async captureRequestContextOwnedLaunches() {
1071
+ const admission = this.requestContextAdmission, lease = captureProcessFleetLease(this.dataDir);
1072
+ if (!admission || admission.available() || !lease?.current())
1073
+ throw Error("Request-context owner preparation unavailable");
1074
+ const pending = this.requestContextPendingWork, revision = pending.revision, boot = this.managerBootId;
1075
+ const freeze = (value) => {
1076
+ if (value && typeof value === "object") {
1077
+ for (const child of Object.values(value))
1078
+ freeze(child);
1079
+ Object.freeze(value);
1080
+ }
1081
+ return value;
1082
+ };
1083
+ const roster = [...this.daemons.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([name, daemon]) => ({
1084
+ name, daemon, config: freeze(daemon.getConfigSnapshot()),
1085
+ }));
1086
+ const images = roster.map(row => requestContextDigest(row.config));
1087
+ const owned = () => admission === this.requestContextAdmission && !admission.available() && lease.current()
1088
+ && this.managerBootId === boot && !this.shuttingDown && pending.revision === revision
1089
+ && this.daemons.size === roster.length && roster.every((row, i) => this.daemons.get(row.name) === row.daemon
1090
+ && pending.count(row.name) === 0 && requestContextDigest(row.config) === images[i]
1091
+ && requestContextDigest(row.daemon.getConfigSnapshot()) === images[i]);
1092
+ const records = [];
1093
+ for (const row of roster) {
1094
+ const unavailable = () => Object.assign(Error("Request-context owner is not ready"), { code: "request-context-owner-not-ready", agent: row.name });
1095
+ if (!owned())
1096
+ throw unavailable();
1097
+ const idle = await row.daemon.captureRequestContextIdle();
1098
+ if (!owned() || !idle?.current())
1099
+ throw unavailable();
1100
+ const retirement = await row.daemon.captureRequestContextRetirement();
1101
+ if (!owned() || !idle.current() || retirement.daemonBootId !== idle.daemonBootId
1102
+ || retirement.spawnGeneration !== idle.spawnGeneration || retirement.launchFenceEpoch !== idle.launchFenceEpoch)
1103
+ throw unavailable();
1104
+ records.push(Object.freeze({ ...row, config: Object.freeze(row.config), idle, retirement }));
1105
+ }
1106
+ const current = () => { try {
1107
+ return owned() && records.every(row => row.idle.current());
1108
+ }
1109
+ catch {
1110
+ return false;
1111
+ } };
1112
+ if (!current())
1113
+ throw Error("Request-context owner preparation changed");
1114
+ return Object.freeze({ records: Object.freeze(records), current });
1115
+ }
1116
+ /** Passive capture first; only prepare() may reconstruct owned transports after native graph staging.
1117
+ * Required ids never shrink when retirement/disconnect removes a connection from the current roster.
1118
+ */
1119
+ captureRequestContextRuntimeSet() {
1120
+ const lease = captureProcessFleetLease(this.dataDir), manager = this.managerBootId, initialConfig = requestContextDigest(this.fleetConfig);
1121
+ if (!lease?.current() || !this.fleetConfig)
1122
+ throw Error("Runtime readiness owner unavailable");
1123
+ const required = new Set(), exec = new Set();
1124
+ let localPane = false, prepared = false;
1125
+ const names = [...new Set([...Object.keys(this.fleetConfig.instances), ...(this.classicChannels?.getAll() ?? []).map(row => row.instanceName)])];
1126
+ for (const name of names) {
1127
+ const cfg = this.hubAgentConfig(name);
1128
+ if (cfg?.runtime !== "windows")
1129
+ continue;
1130
+ if (cfg.machine_id) {
1131
+ required.add(cfg.machine_id);
1132
+ if (isNativeExecInstance(cfg))
1133
+ exec.add(cfg.machine_id);
1134
+ }
1135
+ else if (isNativePaneInstance(cfg))
1136
+ localPane = true;
1137
+ }
1138
+ const online = () => this.runtimeHub?.listMachines().filter(row => row.status === "online") ?? [];
1139
+ const include = () => { for (const row of online())
1140
+ required.add(row.id); if (this.localPaneRelay?.online())
1141
+ localPane = true; };
1142
+ include();
1143
+ const labels = new Map((this.runtimeHub?.listMachines() ?? []).map(row => [row.id, row.name || row.id]));
1144
+ const owned = () => lease.current() && !this.shuttingDown && this.managerBootId === manager && requestContextDigest(this.fleetConfig) === initialConfig;
1145
+ const snapshot = () => {
1146
+ if (!owned())
1147
+ throw Error("Runtime readiness owner changed");
1148
+ include();
1149
+ const peers = [...required].sort().map(id => this.runtimeHub?.requestContextReadiness(id) ?? { id, generation: "unavailable", connected: false, requestContextVersion: 0 });
1150
+ if (localPane)
1151
+ peers.push(this.localPaneRelay?.requestContextReadiness() ?? { id: "local", generation: "unavailable", connected: false, requestContextVersion: 0 });
1152
+ return { requiredPeers: [...required, ...(localPane ? ["local"] : [])].sort(), peers: peers.sort((a, b) => a.id.localeCompare(b.id)) };
1153
+ };
1154
+ const advertised = () => {
1155
+ include();
1156
+ return [...required].filter(id => {
1157
+ const machine = this.runtimeHub?.machine(id), caps = machine?.runtimeInfo?.capabilities ?? [];
1158
+ return !machine || machine.status !== "online" || machine.paneProtocol !== 1 || !caps.includes("request-context-call-v1") || exec.has(id) && !caps.includes("native-exec-input-v1");
1159
+ });
1160
+ };
1161
+ return Object.freeze({ snapshot, labels: () => [...required].map(id => ({ id, label: labels.get(id) ?? this.runtimeHub?.machine(id)?.name ?? id })), advertised,
1162
+ prepare: async () => {
1163
+ if (!owned() || !this.currentRequestContextNativeGraph())
1164
+ throw Error("Runtime graph is not prepared");
1165
+ if (required.size)
1166
+ this.runtimeCoordinator();
1167
+ if (localPane)
1168
+ await this.localNativePaneEndpoint();
1169
+ if (!owned())
1170
+ throw Error("Runtime readiness owner changed");
1171
+ prepared = true;
1172
+ },
1173
+ prove: () => {
1174
+ if (!prepared)
1175
+ throw Error("Runtime graph is not prepared");
1176
+ const first = snapshot(), sha = requestContextDigest(first);
1177
+ if (first.peers.some(row => !row.connected || row.requestContextVersion !== 1))
1178
+ throw Error("Runtime negotiation unavailable");
1179
+ const graph = this.currentRequestContextNativeGraph(), hub = this.runtimeHub, local = this.localPaneRelay;
1180
+ return Object.freeze({ current: () => { try {
1181
+ return owned() && this.currentRequestContextNativeGraph() === graph && this.runtimeHub === hub && this.localPaneRelay === local && requestContextDigest(snapshot()) === sha;
1182
+ }
1183
+ catch {
1184
+ return false;
1185
+ } } });
1186
+ },
1187
+ });
1188
+ }
1189
+ /** The confirmed first-On controller owns this complete preparation. No durable activation or input publication
1190
+ * happens here. Its readiness callbacks must come from the actual legacy drain and negotiated port inventories.
1191
+ */
1192
+ async prepareRequestContextFirstOnAssembly(durableDrained, transportsReady, rootRetired, offer, execution, reconstructTransports) {
1193
+ const [{ RequestContextPaneProofs }, { RequestContextOffOwner }, { captureRequestContextHelpers }] = await Promise.all([import("./request-context-pane.js"), import("./request-context-off.js"), import("./request-context-helper-readiness.js")]);
1194
+ execution?.assert();
1195
+ if (!offer.current())
1196
+ throw Error("stale");
1197
+ const first = this.prepareRequestContextFirstOn(), box = this.deliveryOutbox, boot = first.boot;
1198
+ let connection;
1199
+ try {
1200
+ connection = box.stageRequestContextConnection({ current: first.fence.owned });
1201
+ }
1202
+ catch (error) {
1203
+ first.abandon();
1204
+ throw error;
1205
+ }
1206
+ const drain = connection.drain(() => first.current() ? boot.owner.owner : null), registration = drain.registration();
1207
+ let factory;
1208
+ let inventory;
1209
+ let fleetRegistration;
1210
+ let relaunch;
1211
+ let committed = false, disposed = false;
1212
+ const owned = () => !disposed && first.current();
1213
+ // Rendering may be staged for a fenced replacement; policy execution still uses only the publication.
1214
+ const policy = Object.freeze({ assert: (input) => boot.policy.assert(input), installedMode: () => boot.publication.installedMode(),
1215
+ instructionMode: () => boot.publication.installedMode() ?? (owned() && first.fence.owned() ? "active" : null) });
1216
+ const undoNative = async () => {
1217
+ if (committed || box.requestContextInstallation().read() !== null)
1218
+ throw Error("Activated owners cannot revert");
1219
+ inventory?.dispose();
1220
+ inventory = undefined;
1221
+ await this.retireRequestContextNativeFactories(owned);
1222
+ await factory?.disposeStaged();
1223
+ if (this.requestContextFactoryOwner === factory)
1224
+ this.requestContextFactoryOwner = undefined;
1225
+ factory = undefined;
1226
+ fleetRegistration?.restore();
1227
+ fleetRegistration = undefined;
1228
+ };
1229
+ const abandon = () => { connection.restore(); first.abandon(); disposed = true; };
1230
+ try {
1231
+ relaunch = await this.prepareRequestContextPersistentRelaunch(policy, registration, first.fence, durableDrained, async () => {
1232
+ try {
1233
+ await this.retireRequestContextNativeFactories(owned);
1234
+ fleetRegistration = this.stageRequestContextFleetRegistration(registration, owned);
1235
+ factory = this.installRequestContextRetainedOwners(policy, registration, owned, [], { firstOnStage: { current: () => owned() && first.fence.owned() }, deferStartHooks: true });
1236
+ this.requestContextFactoryOwner = factory;
1237
+ this.stageRequestContextNativeGraph({ registration, panes: new RequestContextPaneProofs(randomBytes(32).toString("hex"), registration),
1238
+ execTurns: factory.execTurns, execOwner: factory.execOwner, execInput: factory.execInput, current: () => owned() && factory?.current() === true });
1239
+ inventory = await this.prepareRequestContextDrainOwners(drain, registration, factory, owned);
1240
+ await reconstructTransports?.();
1241
+ return undoNative;
1242
+ }
1243
+ catch (error) {
1244
+ await undoNative();
1245
+ throw error;
1246
+ }
1247
+ }, execution);
1248
+ execution?.assert();
1249
+ factory.adopt(relaunch.owners());
1250
+ // Do not start deliberately stopped agents. Prepare only their future owned start/exec closures.
1251
+ const names = [...new Set([...Object.keys(this.fleetConfig.instances), ...(this.classicChannels?.getAll() ?? []).map(room => room.instanceName)])].sort();
1252
+ const configurations = names.map(name => [name, this.hubAgentConfig(name)]), rosterImage = requestContextDigest(configurations);
1253
+ for (const [name, config] of configurations) {
1254
+ if (!config)
1255
+ throw Error("Request owner configuration unavailable");
1256
+ if (!this.daemons.has(name))
1257
+ await factory.beforeStart(name, config);
1258
+ execution?.assert();
1259
+ }
1260
+ const sameRoster = () => requestContextDigest(names.map(name => [name, this.hubAgentConfig(name)])) === rosterImage
1261
+ && requestContextDigest([...new Set([...Object.keys(this.fleetConfig?.instances ?? {}), ...(this.classicChannels?.getAll() ?? []).map(room => room.instanceName)])].sort()) === requestContextDigest(names);
1262
+ const baseReady = () => owned() && first.fence.current() && connection.current() && relaunch.ready() && factory.current() && inventory.current()
1263
+ && sameRoster() && durableDrained();
1264
+ const candidates = relaunch.owners(), readHelpers = () => captureRequestContextHelpers(candidates, name => this.daemons.get(name));
1265
+ let helpers = readHelpers(), peersReady = transportsReady();
1266
+ const helperDeadline = performance.now() + 30_000;
1267
+ while (!helpers.ready || !peersReady) {
1268
+ if (!baseReady() || !offer.current() || execution && !execution.current() || performance.now() >= helperDeadline)
1269
+ throw Object.assign(Error("Request-context owner or transport is not ready"), { code: helpers.ready ? "request-context-transport-not-ready" : "request-context-owner-not-ready", ...(helpers.unready[0] ? { agent: helpers.unready[0] } : {}) });
1270
+ // A timer only schedules another actual connection observation; elapsed time never proves readiness.
1271
+ await new Promise(resolve => setTimeout(resolve, 100));
1272
+ helpers = readHelpers();
1273
+ peersReady = transportsReady();
1274
+ }
1275
+ const processReady = () => baseReady() && helpers.current() && transportsReady();
1276
+ const ready = () => processReady() && offer.current() && (!execution || execution.current());
1277
+ if (!ready())
1278
+ throw Error("Request-context owner or transport is not ready");
1279
+ const portsCurrent = () => owned() && factory.current() && inventory.current();
1280
+ let serving;
1281
+ const off = new RequestContextOffOwner(box.requestContextInstallation(), drain, boot.publication, { owner: boot.owner.owner, current: owned }, {
1282
+ get ports() { if (!serving)
1283
+ throw Error("Serving preparation unavailable"); return { policy: serving.policy, serving }; }, current: () => committed && portsCurrent() && !!serving
1284
+ });
1285
+ return Object.freeze({ boot, drain, registration, policy, ready, off, offer,
1286
+ /** Call only inside the single installation.activate transaction. No publication or async work. */
1287
+ initialize: () => {
1288
+ if (!ready())
1289
+ throw Error("Activation preparation changed");
1290
+ const record = box.requestContextInstallation().activation();
1291
+ if (!record || requestContextDigest(record.invalidates) !== requestContextDigest(offer.invalidates) || record.offeredLatestDeadline !== offer.latestDeadline)
1292
+ throw Error("Activation offer differs from confirmation");
1293
+ relaunch.retain();
1294
+ factory.retain();
1295
+ serving = this.prepareRequestContextServingOwners(portsCurrent, root => rootRetired(drain, root), factory.hub, () => boot.publication.installedMode());
1296
+ },
1297
+ /** Synchronous post-COMMIT publication. Failure stays capable and fenced for recovery. */
1298
+ publish: () => {
1299
+ const state = box.requestContextInstallation().read();
1300
+ if (!state || state.mode !== "active" || !serving || !owned())
1301
+ throw Error("Activation publication unavailable");
1302
+ const publishReady = processReady();
1303
+ committed = true;
1304
+ first.adoptCommitted(state.epoch);
1305
+ relaunch.seal();
1306
+ factory.seal();
1307
+ relaunch.releaseStartHooks();
1308
+ factory.attach();
1309
+ this.ownRequestContextModes(boot, drain, off, { policy: serving.policy, serving }, portsCurrent, root => serving.gate.retireRoot(root));
1310
+ this.bindRequestContextServingPublication(boot);
1311
+ if (!publishReady)
1312
+ throw Error("Activation publication readiness changed");
1313
+ boot.publication.publish(state, { policy: serving.policy, serving }, first.fence, portsCurrent, () => box.requestContextInstallation().read(), portsCurrent);
1314
+ return state;
1315
+ },
1316
+ rollback: async () => { if (committed || box.requestContextInstallation().read() !== null)
1317
+ throw Error("Activated owners cannot revert"); await relaunch.rollback(); abandon(); },
1318
+ });
1319
+ }
1320
+ catch (error) {
1321
+ // Persistent preparation unwinds its own candidates. If it returned, retire them before native ownership.
1322
+ try {
1323
+ if (relaunch)
1324
+ await relaunch.rollback();
1325
+ else if (this.requestContextNativeGraph || factory || fleetRegistration)
1326
+ await undoNative();
1327
+ abandon();
1328
+ }
1329
+ catch (cleanup) {
1330
+ throw new AggregateError([error, cleanup], "Request-context preparation could not restore every owner; admission stays fenced");
1331
+ }
1332
+ throw error;
1333
+ }
1334
+ }
1335
+ /** First-On persistent replacements. This does not activate, publish, open admission or construct a native factory.
1336
+ * The installer separately stages native factories and checks every transport before its one activation COMMIT.
1337
+ */
1338
+ async prepareRequestContextPersistentRelaunch(policy, registration, fence, durableDrained, afterRetirement, execution) {
1339
+ const box = this.deliveryOutbox, admission = this.requestContextAdmission, lease = captureProcessFleetLease(this.dataDir), boot = this.managerBootId;
1340
+ if (!box || box.requestContextInstallation().read() !== null || !admission || admission.available() || !lease?.current() || !fence.current())
1341
+ throw Error("Request relaunch preparation unavailable");
1342
+ const inventory = await this.captureRequestContextOwnedLaunches();
1343
+ const rows = inventory.records.map(row => ({ ...row, spec: row.daemon.getRequestContextLaunchSpec(), incarnation: this.contactGeneration(row.name),
1344
+ target: requestContextDigest(this.hubAgentConfig(row.name)), stopped: false, published: false, candidate: null,
1345
+ startup: null,
1346
+ prepared: null }));
1347
+ const originalPrepare = this.prepareRequestContextStart, originalConfigure = this.configureRequestContextBeforeStart;
1348
+ let alive = true, committed = false, rollingBack = false, undoAfterRetirement;
1349
+ const processOwned = () => {
1350
+ try {
1351
+ return alive && !this.shuttingDown && this.managerBootId === boot && lease.current()
1352
+ && this.requestContextAdmission === admission && (committed || fence.owned() && !admission.available());
1353
+ }
1354
+ catch {
1355
+ return false;
1356
+ }
1357
+ };
1358
+ const configured = (row) => {
1359
+ try {
1360
+ return this.contactGeneration(row.name) === row.incarnation
1361
+ && requestContextDigest(this.hubAgentConfig(row.name)) === row.target;
1362
+ }
1363
+ catch {
1364
+ return false;
1365
+ }
1366
+ };
1367
+ const rosterOwned = () => processOwned() && [...this.daemons.keys()].every(name => rows.some(row => row.name === name))
1368
+ && rows.every(row => { const now = this.daemons.get(row.name); return row.candidate ? now === row.candidate || !row.published && !now : row.stopped ? !now : now === row.daemon; });
1369
+ const current = () => rosterOwned() && rows.every(configured);
1370
+ const prepare = (name, actual) => {
1371
+ const row = rows.find(item => item.name === name);
1372
+ if (rollingBack || !row?.prepared || !row.stopped || row.candidate || !current() || requestContextDigest(actual) !== requestContextDigest(row.spec.config))
1373
+ throw Error("Request relaunch start differs");
1374
+ return row.prepared.preparation;
1375
+ };
1376
+ const configure = (name, daemon, actual, offered) => {
1377
+ const row = rows.find(item => item.name === name);
1378
+ if (rollingBack || !row?.prepared || row.candidate || !current() || offered !== undefined && offered.policy !== policy)
1379
+ throw Error("Request relaunch owner differs");
1380
+ // Capture the object before any pre-start callback can fail. Even a startup rejection must retire it exactly.
1381
+ row.candidate = daemon;
1382
+ daemon.seedRequestContextReplacement(row.retirement);
1383
+ row.startup = daemon.prepareRequestContextStartupRetirement();
1384
+ originalConfigure?.(name, daemon, actual, offered);
1385
+ row.prepared.configure(daemon, actual, offered);
1386
+ };
1387
+ const hooksOwned = () => this.prepareRequestContextStart === prepare && this.configureRequestContextBeforeStart === configure;
1388
+ const restoreHooks = () => { if (!hooksOwned())
1389
+ throw Error("Request relaunch start hooks changed"); this.prepareRequestContextStart = originalPrepare; this.configureRequestContextBeforeStart = originalConfigure; };
1390
+ const failed = (name) => Object.assign(Error("Request-context owner is not ready"), { code: "request-context-owner-not-ready", agent: name });
1391
+ const rollback = async () => {
1392
+ if (committed || box.requestContextInstallation().read() !== null)
1393
+ throw Error("Activated owners cannot revert to legacy");
1394
+ if (!processOwned() || !hooksOwned())
1395
+ throw Error("Request relaunch rollback owner changed");
1396
+ rollingBack = true;
1397
+ // Stop/prove every candidate before regenerating legacy instructions or creating a legacy replacement.
1398
+ for (const row of rows.slice().reverse()) {
1399
+ if (!row.candidate)
1400
+ continue;
1401
+ const now = this.daemons.get(row.name);
1402
+ if (now && now !== row.candidate)
1403
+ throw failed(row.name);
1404
+ if (now === row.candidate)
1405
+ await this.lifecycle.stopIfCurrent(row.name, row.candidate);
1406
+ else
1407
+ await row.candidate.stop({ nativePane: "close" });
1408
+ if (!processOwned() || !row.startup || !await row.startup.retired())
1409
+ throw failed(row.name);
1410
+ row.candidate = null;
1411
+ row.prepared?.dispose();
1412
+ }
1413
+ if (undoAfterRetirement) {
1414
+ await undoAfterRetirement();
1415
+ undoAfterRetirement = undefined;
1416
+ }
1417
+ restoreHooks();
1418
+ for (const row of rows) {
1419
+ row.prepared?.dispose();
1420
+ if (!row.stopped)
1421
+ continue;
1422
+ if (!processOwned())
1423
+ throw failed(row.name);
1424
+ if (this.daemons.get(row.name) === row.daemon)
1425
+ await this.lifecycle.stopIfCurrent(row.name, row.daemon);
1426
+ // A deleted, re-targeted or externally replaced owner is never resurrected from this captured config.
1427
+ if (!configured(row) || this.daemons.has(row.name))
1428
+ continue;
1429
+ if (!await row.retirement.retired() || !processOwned())
1430
+ throw failed(row.name);
1431
+ await this.startInstance(row.name, row.spec.config, row.spec.topicMode, row.spec.kind);
1432
+ }
1433
+ alive = false;
1434
+ };
1435
+ if (!inventory.current() || !current() || !durableDrained() || !fence.current())
1436
+ throw Error("Request relaunch preparation changed");
1437
+ this.prepareRequestContextStart = prepare;
1438
+ this.configureRequestContextBeforeStart = configure;
1439
+ try {
1440
+ for (const row of rows) {
1441
+ if (!current() || !fence.current() || !durableDrained() || !row.idle.current())
1442
+ throw failed(row.name);
1443
+ execution?.assert();
1444
+ row.stopped = true;
1445
+ let stopped = false;
1446
+ if (execution)
1447
+ await execution.stopTarget(row.name, async (advance) => { stopped = await this.lifecycle.stopIfCurrent(row.name, row.daemon, advance); });
1448
+ else
1449
+ stopped = await this.lifecycle.stopIfCurrent(row.name, row.daemon);
1450
+ if (!stopped)
1451
+ throw failed(row.name);
1452
+ if (!current() || !await row.retirement.retired() || !current())
1453
+ throw failed(row.name);
1454
+ }
1455
+ if (afterRetirement) {
1456
+ undoAfterRetirement = await afterRetirement();
1457
+ if (!current() || !fence.current() || !durableDrained())
1458
+ throw Error("Request relaunch preparation changed");
1459
+ }
1460
+ for (const row of rows) {
1461
+ if (!current() || !fence.current() || !durableDrained())
1462
+ throw failed(row.name);
1463
+ row.prepared = this.prepareRequestContextDaemonOwner(row.name, row.spec.config, policy, registration, () => committed ? processOwned() && this.contactGeneration(row.name) === row.incarnation && this.daemons.get(row.name) === row.candidate : current());
1464
+ execution?.assert();
1465
+ await this.startInstance(row.name, row.spec.config, row.spec.topicMode, row.spec.kind, false, undefined, execution);
1466
+ execution?.assert();
1467
+ row.published = true;
1468
+ if (!current())
1469
+ throw failed(row.name);
1470
+ row.prepared.sealRegistered();
1471
+ }
1472
+ const ready = () => !rollingBack && current() && hooksOwned() && fence.current() && durableDrained() && rows.every(row => row.prepared?.bound());
1473
+ if (!ready())
1474
+ throw Error("Request relaunch preparation changed");
1475
+ return Object.freeze({
1476
+ ready,
1477
+ owners: () => rows.map(row => { if (!row.candidate || !row.startup || !row.prepared?.bound())
1478
+ throw Error("Request relaunch owner unavailable"); return Object.freeze({ name: row.name, daemon: row.candidate, prepared: row.prepared, resources: row.startup }); }),
1479
+ /** Synchronous initializer inside activation's outer SQLite transaction. */
1480
+ retain: () => { if (!ready())
1481
+ throw Error("Request relaunch preparation changed"); for (const row of rows)
1482
+ row.prepared.work.retainPrepared(); if (!ready())
1483
+ throw Error("Request relaunch preparation changed"); },
1484
+ /** Post-COMMIT only. The installer replaces the start hooks with its capable owner factory before releasing admission. */
1485
+ seal: () => {
1486
+ if (rollingBack || !current() || !hooksOwned() || !rows.every(row => row.prepared?.bound()) || box.requestContextInstallation().read() === null)
1487
+ throw Error("Request relaunch has not committed");
1488
+ for (const row of rows)
1489
+ row.prepared.work.sealRetained();
1490
+ committed = true;
1491
+ },
1492
+ executionCurrent: () => committed && processOwned(),
1493
+ releaseStartHooks: () => { if (!committed || !current())
1494
+ throw Error("Request relaunch has not committed"); restoreHooks(); },
1495
+ rollback,
1496
+ });
1497
+ }
1498
+ catch (error) {
1499
+ try {
1500
+ await rollback();
1501
+ }
1502
+ catch (rollbackError) {
1503
+ throw new AggregateError([error, rollbackError], "Request relaunch could not restore every owned agent; admission stays fenced");
1504
+ }
1505
+ throw error;
1506
+ }
1507
+ }
1508
+ /** Shared input gate only; C/D scope binding remains a separate pre-start preparation. */
1509
+ attachRequestContextAdmission(port) {
1510
+ if (this.requestContextAdmission === port)
1511
+ return;
1512
+ if (this.requestContextAdmission)
1513
+ throw Error("Request-context admission owner differs");
1514
+ this.requestContextAdmission = port;
1515
+ for (const daemon of this.daemons.values())
1516
+ daemon.setRequestContextAdmission(port);
1517
+ const prepare = this.configureRequestContextBeforeStart;
1518
+ this.configureRequestContextBeforeStart = (name, daemon, config, preparation) => { daemon.setRequestContextAdmission(port); prepare?.(name, daemon, config, preparation); };
1519
+ port.subscribe(available => {
1520
+ if ((available || port.dispatchAvailable?.()) && !this.shuttingDown && this.deliveryOutbox?.isOpen) {
1521
+ this.scheduleDeliveryOutboxPump();
1522
+ this.wakeCoordinator?.kick();
1523
+ }
1524
+ });
1525
+ }
849
1526
  /** S-244: the quiescence barrier. Unset, every pane write and admission proceeds as today. */
850
1527
  quiescence = null;
851
1528
  attachQuiescence(gate) { this.quiescence = gate; }
@@ -1167,6 +1844,7 @@ export class FleetManager {
1167
1844
  fleetConfig = null;
1168
1845
  fleetWindowsRuntime = null;
1169
1846
  nativeMcpStore = null;
1847
+ requestContextPendingWork = new RequestContextPendingWork();
1170
1848
  requestContextIpcCalls = new WeakMap();
1171
1849
  requestContextFleetCalls = new RequestContextReferenceMap(row => row.call.admission.coverage === "covered" ? row.call.admission.lease.snapshot.context.ref.rootContextId : null, row => `fleet-call:${row.call.id}`);
1172
1850
  setRequestContextDrainRegistration(registration) {
@@ -1177,6 +1855,28 @@ export class FleetManager {
1177
1855
  throw Error("Request context drain registry unavailable");
1178
1856
  calls.installRegistration(registration);
1179
1857
  }
1858
+ /** Unpublished first-On registration. Only an empty, physically disconnected attempt can restore its prior map. */
1859
+ stageRequestContextFleetRegistration(registration, current) {
1860
+ const box = this.deliveryOutbox, lease = captureProcessFleetLease(this.dataDir), original = this.requestContextFleetCalls;
1861
+ if (!box || !lease?.current() || !current() || this.requestContextAdmission?.available() !== false || !original || original.size || original.registrationGate
1862
+ || this.instanceIpcClients.size || !this.requestContextPendingWork?.empty || box.requestContextInstallation().read() !== null)
1863
+ throw Error("Fleet call registration preparation unavailable");
1864
+ const replacement = new RequestContextReferenceMap(row => row.call.admission.coverage === "covered" ? row.call.admission.lease.snapshot.context.ref.rootContextId : null, row => `fleet-call:${row.call.id}`);
1865
+ replacement.installRegistration(registration);
1866
+ this.requestContextFleetCalls = replacement;
1867
+ const owned = () => { try {
1868
+ return !this.shuttingDown && lease.current() && current() && this.deliveryOutbox === box && this.requestContextFleetCalls === replacement;
1869
+ }
1870
+ catch {
1871
+ return false;
1872
+ } };
1873
+ return Object.freeze({ current: owned, restore: () => {
1874
+ if (!owned() || this.requestContextAdmission?.available() !== false || this.instanceIpcClients.size || replacement.size
1875
+ || !this.requestContextPendingWork.empty || box.requestContextInstallation().read() !== null)
1876
+ throw Error("Fleet call registration cannot revert");
1877
+ this.requestContextFleetCalls = original;
1878
+ } });
1879
+ }
1180
1880
  get requestContextFleetDrainRevision() { return this.requestContextFleetCalls?.revision ?? "unavailable"; }
1181
1881
  requestContextFleetDrainView(rootId) { return this.requestContextFleetCalls?.view(rootId) ?? { registration: null, revision: "unavailable", references: [], unknown: true }; }
1182
1882
  finishRequestContextIpcCall(message) { const call = this.requestContextCallOf(message), calls = this.requestContextFleetCalls; if (call && calls)
@@ -1224,7 +1924,7 @@ export class FleetManager {
1224
1924
  return false;
1225
1925
  const tool = message.type === "fleet_outbound" ? String(message.tool ?? "") : toolForIpcType(message.type);
1226
1926
  const originalBoot = daemon.bootId;
1227
- const scoped = Object.freeze({ id: captured.id, admission: captured.admission,
1927
+ const scoped = Object.freeze({ id: captured.id, admission: captured.admission, replyRoute: captured.replyRoute,
1228
1928
  current: () => captured.current() && this.instanceIpcClients.get(name) === ipc && this.getDaemonBootId(name) === originalBoot
1229
1929
  && !!tool && this.checkToolPermission("ipc-outbound", name, tool === "hub_room_status" ? "hub_room_list" : tool).allowed });
1230
1930
  const calls = this.requestContextFleetCalls;
@@ -1370,13 +2070,146 @@ export class FleetManager {
1370
2070
  runtimeExecutor = null;
1371
2071
  runtimeStatusScheduled = false;
1372
2072
  reconciledRemoteResults = new Set();
2073
+ requestContextNativeGraph;
2074
+ requestContextNativeGraphLease;
2075
+ requestContextNativeFactoryOwners;
2076
+ requestContextOpeningPaneManagers = 0;
2077
+ requestContextNativeRetiring = false;
2078
+ /** Already-drained owned launches only. The callback owns the Fleet/process, not the browser/readiness. */
2079
+ async retireRequestContextNativeFactories(current) {
2080
+ const lease = captureProcessFleetLease(this.dataDir), owned = () => !!lease?.current() && current() && this.requestContextAdmission?.available() === false;
2081
+ if (!owned() || this.requestContextNativeRetiring)
2082
+ throw Error("Native factory retirement needs the owned admission fence");
2083
+ const [{ LocalPaneEndpoint }, { localPaneScope }, { NativePaneManager }] = await Promise.all([import("./local-pane-endpoint.js"), import("./local-pane-launcher.js"), import("./native-pane-manager.js")]);
2084
+ const scope = localPaneScope(this.dataDir), hub = this.runtimeHub, panes = this.paneManager, mcp = this.nativeMcpStore, runtime = this.fleetWindowsRuntime, executor = this.runtimeExecutor, relay = this.localPaneRelay;
2085
+ const same = () => this.runtimeHub === hub && this.localPaneRelay === relay && this.paneManager === panes && this.nativeMcpStore === mcp && this.fleetWindowsRuntime === runtime && this.runtimeExecutor === executor && !this.openingLocalPane && !this.requestContextOpeningPaneManagers;
2086
+ if (!owned() || !same() || runtime && !runtime.requestContextPhysicallyIdle() || panes && !panes.requestContextPhysicallyIdle() || mcp && !mcp.requestContextPhysicallyIdle() || executor && !executor.idleForRequestContext() || hub && !hub.requestContextPhysicallyIdle() || !windowsBridgeRequestContextIdle(this) || WindowsAgents.requestContextOwnersOnDisk(this.dataDir).length !== 0 || !hub && RuntimeCoordinator.requestContextPendingRunsOnDisk(this.dataDir).runs.length !== 0 || NativePaneManager.requestContextOrphanActivity(this.dataDir).unknown || !LocalPaneEndpoint.requestContextScopeIdle(scope))
2087
+ throw Error("Native factories still own work or an unconfirmed launch");
2088
+ this.requestContextNativeRetiring = true;
2089
+ try {
2090
+ runtime?.retireForRequestContext();
2091
+ panes?.retireForRequestContext();
2092
+ mcp?.retireForRequestContext();
2093
+ executor?.retireForRequestContext();
2094
+ retireWindowsBridgeForRequestContext(this);
2095
+ await Promise.all([hub?.retireForRequestContext(), LocalPaneEndpoint.retireScopeForRequestContext(scope)]);
2096
+ if (!owned() || !same())
2097
+ throw Error("Native factory owner changed during retirement");
2098
+ this.runtimeHub = null;
2099
+ this.localPaneRelay = null;
2100
+ this.paneManager = null;
2101
+ this.nativeMcpStore = null;
2102
+ this.fleetWindowsRuntime = null;
2103
+ this.runtimeExecutor = null;
2104
+ this.requestContextNativeGraph = undefined;
2105
+ this.requestContextNativeGraphLease = undefined;
2106
+ this.requestContextNativeFactoryOwners = undefined;
2107
+ }
2108
+ finally {
2109
+ this.requestContextNativeRetiring = false;
2110
+ }
2111
+ }
2112
+ /** Only after exact old-owner retirement and transport teardown, behind the shared Fleet admission fence. */
2113
+ stageRequestContextNativeGraph(graph) {
2114
+ const lease = captureProcessFleetLease(this.dataDir);
2115
+ if (this.requestContextNativeGraph || !lease?.current() || this.requestContextAdmission?.available() !== false || !graph.current()
2116
+ || this.runtimeHub || this.runtimeExecutor || this.localPaneRelay || this.openingLocalPane || this.requestContextOpeningPaneManagers || this.paneManager || this.nativeMcpStore || this.fleetWindowsRuntime
2117
+ || typeof graph.execInput !== "function" || graph.panes.drainView("").registration !== graph.registration)
2118
+ throw Error("Request-context native graph is not retired");
2119
+ this.requestContextNativeGraph = graph;
2120
+ this.requestContextNativeGraphLease = lease;
2121
+ }
2122
+ /** Inert native owner construction plus the complete eight-family inventory, behind the shared fence.
2123
+ * None of these accessors starts a provider, pane, coordinator or Fleet. Transport negotiation is separate.
2124
+ */
2125
+ async prepareRequestContextDrainOwners(drain, registration, owners, current) {
2126
+ const graph = this.requestContextNativeGraph, box = this.deliveryOutbox, lease = captureProcessFleetLease(this.dataDir);
2127
+ if (!graph || graph.registration !== registration || !graph.current() || !box || !lease?.current() || !current() || !owners.current()
2128
+ || this.requestContextAdmission?.available() !== false || this.requestContextFleetCalls?.registrationGate !== registration)
2129
+ throw Error("Drain owner preparation unavailable");
2130
+ const runtime = this.nativeInstanceRuntime(), grants = this.nativeMcpSessions(), panes = await this.nativePanes();
2131
+ let alive = true;
2132
+ const owned = () => {
2133
+ try {
2134
+ return alive && !this.shuttingDown && lease.current() && current() && owners.current() && this.deliveryOutbox === box
2135
+ && this.requestContextNativeGraph === graph && graph.current() && this.fleetWindowsRuntime === runtime && this.nativeMcpStore === grants
2136
+ && this.paneManager === panes && this.requestContextFleetCalls?.registrationGate === registration;
2137
+ }
2138
+ catch {
2139
+ return false;
2140
+ }
2141
+ };
2142
+ if (!owned() || this.requestContextAdmission?.available() !== false)
2143
+ throw Error("Drain owner preparation changed");
2144
+ const sources = [
2145
+ ["turns", owners.revision, owners.turnView], ["daemon-calls", owners.callRevision, owners.callView],
2146
+ ["fleet-calls", () => this.requestContextFleetDrainRevision, root => this.requestContextFleetDrainView(root)],
2147
+ ["native-exec", () => runtime.drainRevision, root => runtime.drainView(root)],
2148
+ ["native-grants", () => grants.drainRevision, root => grants.drainView(root)],
2149
+ ["pane-proofs", () => graph.panes.drainRevision, root => graph.panes.drainView(root), () => graph.panes.offRevision, root => graph.panes.offView(root)],
2150
+ ["pane-ledgers", () => panes.drainRevision, root => panes.drainView(root), () => panes.offRevision, root => panes.offView(root)],
2151
+ ["registered-work", owners.inputRevision, owners.inputView],
2152
+ ];
2153
+ const remove = [];
2154
+ try {
2155
+ for (const [family, revision, inspect, offRevision, inspectOff] of sources)
2156
+ remove.push(drain.register(family, "fleet", { registration,
2157
+ revision: () => owned() ? revision() : "owner-changed", inspect: root => owned() ? inspect(root) : { registration, revision: "owner-changed", references: [], unknown: true },
2158
+ ...(offRevision && inspectOff ? { offRevision: () => owned() ? offRevision() : "owner-changed", inspectOff: (root) => owned() ? inspectOff(root) : { registration, revision: "owner-changed", references: [], unknown: true } } : {}) }));
2159
+ }
2160
+ catch (error) {
2161
+ for (const undo of remove.reverse())
2162
+ undo();
2163
+ throw error;
2164
+ }
2165
+ return Object.freeze({ current: owned, runtime, grants, panes,
2166
+ /** The physical owners/connection have their own exact rollback; this only removes unpublished inventory. */
2167
+ dispose: () => {
2168
+ if (!owned() || this.requestContextAdmission?.available() !== false || box.requestContextInstallation().read() !== null
2169
+ || !runtime.requestContextPhysicallyIdle() || !grants.requestContextPhysicallyIdle() || !panes.requestContextPhysicallyIdle()
2170
+ || this.requestContextFleetCalls.size || !this.requestContextPendingWork.empty)
2171
+ throw Error("Published drain owners cannot revert");
2172
+ for (const undo of remove.slice().reverse())
2173
+ undo();
2174
+ alive = false;
2175
+ },
2176
+ });
2177
+ }
2178
+ currentRequestContextNativeGraph() {
2179
+ const graph = this.requestContextNativeGraph;
2180
+ if (graph) {
2181
+ if (!this.requestContextNativeGraphLease?.current() || !graph.current())
2182
+ throw Error("Request-context native graph owner changed");
2183
+ return graph;
2184
+ }
2185
+ if (this.requestContextBoot)
2186
+ throw Error("Request-context native graph is not prepared");
2187
+ return null;
2188
+ }
2189
+ ownRequestContextNativeFactory(value, graph) {
2190
+ if (this.currentRequestContextNativeGraph() !== graph)
2191
+ throw Error("Request-context native factory owner changed");
2192
+ (this.requestContextNativeFactoryOwners ??= new WeakMap()).set(value, graph);
2193
+ return value;
2194
+ }
2195
+ requireRequestContextNativeFactory(value, graph) {
2196
+ if (this.currentRequestContextNativeGraph() !== graph || this.requestContextNativeFactoryOwners?.get(value) !== graph)
2197
+ throw Error("Request-context native factory was not prepared");
2198
+ return value;
2199
+ }
1373
2200
  /** Machine credentials are separate from dashboard sessions and per-turn agent capabilities. */
1374
2201
  runtimeCoordinator() {
2202
+ if (this.requestContextNativeRetiring)
2203
+ throw Error("Native factory replacement is holding new work");
1375
2204
  if (!remoteRuntimeEnabled())
1376
2205
  throw new Error("Remote runtimes are not enabled");
1377
2206
  if (!this.runtimeHub && this.readPendingOwnerNotices().length)
1378
2207
  this.scheduleOwnerNoticeFlush(30_000); // a notice kept before a restart is delivered once the fleet is up
1379
- return this.runtimeHub ??= new RuntimeCoordinator(this.dataDir, {
2208
+ const graph = this.requestContextNativeGraph || this.requestContextBoot ? this.currentRequestContextNativeGraph() : null;
2209
+ if (this.runtimeHub)
2210
+ return graph ? this.requireRequestContextNativeFactory(this.runtimeHub, graph) : this.runtimeHub;
2211
+ const hub = new RuntimeCoordinator(this.dataDir, {
2212
+ ...(graph ? { requestContextProtocol: 1 } : {}),
1380
2213
  handleMcp: (machineId, runId, body) => this.runtimeWindowsExecutor().mcp(machineId, runId, body),
1381
2214
  handlePaneMcp: async (machineId, body, current, stamp) => stamp ? (await this.nativePanes()).handle(machineId, body, current, stamp) : (await this.nativePanes()).handle(machineId, body, current),
1382
2215
  warn: (fields, message) => this.logger.warn(fields, message),
@@ -1428,22 +2261,54 @@ export class FleetManager {
1428
2261
  });
1429
2262
  },
1430
2263
  });
2264
+ return this.runtimeHub = graph ? this.ownRequestContextNativeFactory(hub, graph) : hub;
1431
2265
  }
1432
2266
  runtimeWindowsExecutor() {
2267
+ if (this.requestContextNativeRetiring)
2268
+ throw Error("Native factory replacement is holding new work");
1433
2269
  return this.runtimeExecutor ??= new RuntimeWindowsBridge(this, () => remoteRuntimeEnabled() && !this.shuttingDown ? this.runtimeCoordinator() : null);
1434
2270
  }
1435
2271
  /** Per-turn capabilities for native MCP, separate from browser and Linux-agent credentials. */
1436
2272
  nativeMcpSessions() {
1437
- return this.nativeMcpStore ??= new NativeMcpSessions(this);
2273
+ if (this.requestContextNativeRetiring)
2274
+ throw Error("Native factory replacement is holding new work");
2275
+ const graph = this.requestContextNativeGraph || this.requestContextBoot ? this.currentRequestContextNativeGraph() : null;
2276
+ if (this.nativeMcpStore)
2277
+ return graph ? this.requireRequestContextNativeFactory(this.nativeMcpStore, graph) : this.nativeMcpStore;
2278
+ const sessions = new NativeMcpSessions(this, graph?.registration);
2279
+ if (graph)
2280
+ sessions.setRequestContextRequired(true, true);
2281
+ return this.nativeMcpStore = graph ? this.ownRequestContextNativeFactory(sessions, graph) : sessions;
1438
2282
  }
1439
2283
  /** Retire only existing native capabilities; ordinary lifecycle changes do not instantiate the Windows path. */
1440
2284
  invalidateNativeMcp(name) { this.nativeMcpStore?.closeInstance(name); }
1441
2285
  /** The same instance registry and delivery entry point, with a native Windows execution adapter. */
1442
2286
  nativeInstanceRuntime() {
1443
- return this.fleetWindowsRuntime ??= new FleetWindowsRuntime({
2287
+ if (this.requestContextNativeRetiring)
2288
+ throw Error("Native factory replacement is holding new work");
2289
+ const graph = this.requestContextNativeGraph || this.requestContextBoot ? this.currentRequestContextNativeGraph() : null;
2290
+ if (this.fleetWindowsRuntime)
2291
+ return graph ? this.requireRequestContextNativeFactory(this.fleetWindowsRuntime, graph) : this.fleetWindowsRuntime;
2292
+ const runtime = new FleetWindowsRuntime({
1444
2293
  owner: this, fleet: () => this.fleetConfig, save: () => this.saveFleetConfig(), stopping: () => this.shuttingDown, history: this.webChatHistory,
1445
- openMcp: (instance, requestId, sandbox, stillCurrent, requestContext) => this.healthServerListening
1446
- ? this.nativeMcpSessions().grant({ instance, requestId, sandbox, stillCurrent, ...(requestContext ? { requestContext } : {}), endpoint: `http://127.0.0.1:${this.fleetConfig?.health_port ?? 19280}/agent` }) : null,
2294
+ requestContextAdmission: () => this.requestContextAdmission,
2295
+ requestContextContinuation: (instance, inputId) => {
2296
+ if (!this.requestContextBoot)
2297
+ return;
2298
+ const match = /^delivery:([a-f0-9-]{36}):([1-9][0-9]*)$/.exec(inputId ?? "");
2299
+ if (!match)
2300
+ return;
2301
+ const row = this.deliveryOutbox?.get(match[1]);
2302
+ if (!row || row.targetInstance !== instance || row.managerBootId !== this.managerBootId || row.attemptNo !== Number(match[2])
2303
+ || row.targetDaemonBootId !== this.managerBootId || !["delivering", "submission_started"].includes(row.state))
2304
+ throw Error("Native continuation attempt changed");
2305
+ return this.requestContextDeliveryContinuation(row) ?? undefined;
2306
+ },
2307
+ openMcp: (instance, requestId, sandbox, stillCurrent, requestContext, inputReady) => this.healthServerListening
2308
+ ? this.nativeMcpSessions().grant({ instance, requestId, sandbox, stillCurrent, ...(requestContext ? { requestContext } : {}), ...(inputReady ? { inputReady } : {}), endpoint: `http://127.0.0.1:${this.fleetConfig?.health_port ?? 19280}/agent` }) : null,
2309
+ projectRequestContextOutput: (instance, task, completion) => this.deliveryOutbox ? projectRequestContextNativeOutput(this.deliveryOutbox, instance, task, completion, {
2310
+ admitted: root => this.requestContextNativeAdmissionCurrent(root), history: this.webChatHistory, session: handle => this.webSessions?.findByHandle(handle),
2311
+ }) : null,
1447
2312
  warn: (message, error) => this.logger.warn({ err: error }, message),
1448
2313
  removed: name => this.nativeInstanceRemoved(name),
1449
2314
  paneCurrent: name => this.daemons.get(name)?.nativePaneCurrent?.() === true,
@@ -1478,6 +2343,9 @@ export class FleetManager {
1478
2343
  this.scheduleDeliveryOutboxPump();
1479
2344
  },
1480
2345
  }, { bridge: this.runtimeWindowsExecutor() });
2346
+ if (graph)
2347
+ runtime.setRequestContextExecLifecycles(graph.execTurns, graph.execOwner, graph.registration, graph.execInput);
2348
+ return this.fleetWindowsRuntime = graph ? this.ownRequestContextNativeFactory(runtime, graph) : runtime;
1481
2349
  }
1482
2350
  agentRuntimeChangeService;
1483
2351
  agentRuntimeChanges() {
@@ -1719,13 +2587,17 @@ export class FleetManager {
1719
2587
  return { ...(result.version ? { native_cli_version: result.version } : {}), native_cli_verification: result.state };
1720
2588
  }
1721
2589
  async localNativePaneEndpoint() {
1722
- const admit = () => { if (this.shuttingDown || this.localPaneDrain || !localWindowsCliEnabled())
2590
+ if (this.requestContextNativeRetiring)
2591
+ throw Error("Native factory replacement is holding new work");
2592
+ const graph = this.requestContextNativeGraph || this.requestContextBoot ? this.currentRequestContextNativeGraph() : null;
2593
+ const admit = () => { if (graph && this.currentRequestContextNativeGraph() !== graph)
2594
+ throw Error("Request-context native factory owner changed"); if (this.shuttingDown || this.localPaneDrain || !localWindowsCliEnabled())
1723
2595
  throw Error("Local Windows runtime is switched off or draining"); };
1724
2596
  admit();
1725
2597
  if (this.localPaneDrain)
1726
2598
  throw Error("Local Windows runtime cleanup is pending");
1727
2599
  if (this.localPaneRelay?.online())
1728
- return this.localPaneRelay;
2600
+ return graph ? this.requireRequestContextNativeFactory(this.localPaneRelay, graph) : this.localPaneRelay;
1729
2601
  if (this.openingLocalPane)
1730
2602
  return this.openingLocalPane;
1731
2603
  const opening = (async () => {
@@ -1735,15 +2607,14 @@ export class FleetManager {
1735
2607
  admit();
1736
2608
  this.localPaneRelay?.stop();
1737
2609
  this.localPaneInventory = inventory;
1738
- const relay = await LocalPaneEndpoint.open({ scope: localPaneScope(this.dataDir), admit, maxAgents: maxAgentsPerMachine,
2610
+ const relay = await LocalPaneEndpoint.open({ scope: localPaneScope(this.dataDir), ...(graph ? { requestContextProtocol: 1 } : {}), admit, maxAgents: maxAgentsPerMachine,
1739
2611
  diagnostic: text => this.logger.warn({ stderr: text }, "Local Windows pane relay wrote to stderr"),
1740
2612
  version: provider => inventory.clis.find(row => row.id === provider && row.runnable)?.version ?? null,
1741
2613
  launch: () => launchLocalPaneRelay(this.dataDir, admit),
1742
- mcp: async (body, current, stamp) => stamp ? (await this.nativePanes()).handle("local", body, current, stamp) : (await this.nativePanes()).handle("local", body, current),
1743
- });
2614
+ mcp: async (body, current, stamp) => stamp ? (await this.nativePanes()).handle("local", body, current, stamp) : (await this.nativePanes()).handle("local", body, current), });
1744
2615
  try {
1745
2616
  admit();
1746
- this.localPaneRelay = relay;
2617
+ this.localPaneRelay = graph ? this.ownRequestContextNativeFactory(relay, graph) : relay;
1747
2618
  return relay;
1748
2619
  }
1749
2620
  catch (error) {
@@ -1762,85 +2633,101 @@ export class FleetManager {
1762
2633
  }
1763
2634
  /** Persistent ownership is independent of the exec worker's per-turn capabilities. */
1764
2635
  async nativePanes() {
2636
+ if (this.requestContextNativeRetiring)
2637
+ throw Error("Native factory replacement is holding new work");
2638
+ const graph = this.requestContextNativeGraph || this.requestContextBoot ? this.currentRequestContextNativeGraph() : null;
1765
2639
  if (this.paneManager)
1766
- return this.paneManager;
1767
- const { NativePaneManager } = await import("./native-pane-manager.js");
1768
- if (this.paneManager)
1769
- return this.paneManager;
1770
- const store = windowsAgentsFor(this, this.runtimeWindowsExecutor());
1771
- const allowed = (name, tool) => (!this.classicContactRestricted(name) || CLASSIC_RESTRICTED_TOOLS.includes(tool))
1772
- && nativePaneToolAvailable(tool) && mayUseTool(resolveToolSet(this.fleetConfig?.instances[name], name), tool)
1773
- && !dashboardRefusalIn(this.fleetConfig, name, tool);
1774
- return this.paneManager = new NativePaneManager({
1775
- home: this.dataDir, store, config: name => this.fleetConfig?.instances[name],
1776
- freshNotice: async (name, provider) => {
1777
- const message = t(provider === "codex" ? "native_pane.codex_fresh_started" : "native_pane.fresh_started");
1778
- this.eventLog?.insert(name, "native_pane_fresh_started", {});
1779
- this.logger.info({ name }, message);
1780
- await this.notifyInstanceTopic(name, message);
1781
- },
1782
- admit: (name, config) => {
1783
- const now = this.fleetConfig?.instances[name];
1784
- if (this.shuttingDown || !isNativePaneInstance(now) || now?.native_agent_id !== config.native_agent_id
1785
- || now?.machine_id !== config.machine_id || now?.working_directory !== config.working_directory || now?.backend !== config.backend
1786
- || now?.model !== config.model || now?.native_sandbox !== config.native_sandbox || now?.systemPrompt !== config.systemPrompt || now?.operations !== config.operations || now?.workflow !== config.workflow
1787
- || now?.general_topic !== config.general_topic || now?.native_general_binding !== config.native_general_binding
1788
- || nativeCredentialProfile(now) !== nativeCredentialProfile(config))
1789
- throw Error("Native pane configuration or lifetime changed");
1790
- // Fail closed: a Runtime that does not report the capability would start the terminal on the computer's own account.
1791
- if (nativeCredentialProfile(config) && !this.runtimeCoordinator().machine(config.machine_id)?.runtimeInfo?.capabilities.includes(RUNTIME_CREDENTIAL_CAPABILITY))
1792
- throw Error("This computer's Runtime is too old to choose a Claude account. Update the Runtime on that computer, then try again.");
1793
- if (config.machine_id ? this.remotePaneDrain || !remoteRuntimeEnabled() : this.localPaneDrain || !localWindowsCliEnabled())
1794
- throw Error("Native runtime is switched off");
1795
- },
1796
- endpoint: async (agent, cleanup = false) => {
1797
- if (!agent.machineId) {
1798
- if (!cleanup)
1799
- return this.localNativePaneEndpoint();
1800
- if (!this.localPaneRelay)
1801
- throw Error("Local cleanup transport is unavailable; pane remains reserved");
1802
- return this.localPaneRelay;
1803
- }
1804
- const hub = cleanup ? this.runtimeHub : this.runtimeCoordinator(), machineId = agent.machineId;
1805
- if (!hub)
1806
- throw Error("Remote cleanup transport is unavailable; pane remains reserved");
1807
- const draining = () => !!this.remotePaneDrain;
1808
- return { machineId, online: () => !this.shuttingDown && (draining() || remoteRuntimeEnabled()) && this.runtimeHub === hub && hub.machine(machineId)?.status === "online",
1809
- call: request => {
1810
- if (this.runtimeHub !== hub || !(draining() || remoteRuntimeEnabled()) || draining() && request.action !== "snapshot" && request.action !== "close")
1811
- return Promise.reject(Error("Remote pane transport only permits owned cleanup"));
1812
- return hub.callPane(machineId, request, maxAgentsPerMachine());
1813
- }, subscribe: listener => hub.subscribe(listener),
1814
- epoch: () => hub.paneTransportEpoch(machineId), version: provider => hub.machine(machineId)?.inventory?.clis.find(row => row.id === provider && row.runnable)?.version ?? null };
1815
- },
1816
- instructions: (name, config) => buildNativeFleetInstructions({ instanceName: name, workingDirectory: config.working_directory,
1817
- displayName: config.display_name, description: config.description, customPrompt: config.systemPrompt, operations: config.operations,
1818
- workflow: config.workflow, taskBoard: !dashboardRefusalIn(this.fleetConfig, name, "task"),
1819
- runtimeIdentity: { kind: "fleet-topic", backend: config.backend ?? "codex", model: config.model || "default" } }, config.general_topic === true),
1820
- menu: name => TOOLS.filter(tool => allowed(name, tool.name)).map(tool => ({ ...tool })),
1821
- allowed: (name, tool, args) => allowed(name, tool) && !nativePaneToolRefusal(tool, args), published: (name, daemon) => this.daemons.get(name) === daemon,
1822
- invoke: async (daemon, input, current, name) => {
1823
- if (input.tool === "list_models") {
1824
- const { ListModelsArgs } = await import("./outbound-schemas.js");
1825
- const parsed = ListModelsArgs.safeParse(input.args);
1826
- if (!parsed.success || !current())
1827
- return { result: null, error: "Invalid native model request or expired owner" };
1828
- const target = parsed.data.instance_name ?? name;
1829
- if (!isWindowsInstance(this.fleetConfig?.instances[target]))
1830
- return { result: null, error: "Native panes can only read Windows runtime model inventories" };
1831
- return { result: await this.listModelCatalog({ instanceName: target }) };
1832
- }
1833
- const ops = { hub_set_intro: "hub-set-intro", hub_room_list: "hub-room-list", hub_room_post: "hub-room-post", hub_room_members: "hub-room-members", hub_people_search: "hub-people-search", list_instances: "list", describe_instance: "describe", task: "task", send_to_instance: "send",
1834
- delegate_task: "delegate", request_information: "ask", report_result: "report", delivery_status: "delivery-status" };
1835
- const { nativeAgentAdmissionContext } = await import("./native-agent-admission.js");
1836
- const { dispatchAgentOperation } = await import("./agent-endpoint.js");
1837
- return daemon.handlePaneToolCall(input, { current, allowed: tool => allowed(name, tool), ...(input.requestContext ? { requestContext: input.requestContext } : {}),
1838
- dispatch: (tool, args) => ops[tool] ? dispatchAgentOperation(nativeAgentAdmissionContext(this, {
1839
- instance: name, operation: { tool, args }, current: () => current() && allowed(name, tool), taskAllowed: () => current() && allowed(name, "task"),
1840
- ...(input.requestContext?.coverage === "covered" ? { requestContext: input.requestContext.lease } : input.requestContext ? { notCoveredReason: input.requestContext.reason } : {}),
1841
- }), name, ops[tool], args, input.operationId, () => current() && allowed(name, tool)) : undefined });
1842
- },
1843
- });
2640
+ return graph ? this.requireRequestContextNativeFactory(this.paneManager, graph) : this.paneManager;
2641
+ const boot = this.requestContextBoot;
2642
+ this.requestContextOpeningPaneManagers = (this.requestContextOpeningPaneManagers ?? 0) + 1;
2643
+ try {
2644
+ const { NativePaneManager } = await import("./native-pane-manager.js");
2645
+ if (this.requestContextNativeGraph !== (graph ?? undefined) || this.requestContextBoot !== boot)
2646
+ throw Error("Request-context native factory owner changed");
2647
+ if (this.paneManager)
2648
+ return graph ? this.requireRequestContextNativeFactory(this.paneManager, graph) : this.paneManager;
2649
+ if (graph && this.currentRequestContextNativeGraph() !== graph)
2650
+ throw Error("Request-context native factory owner changed");
2651
+ const store = windowsAgentsFor(this, this.runtimeWindowsExecutor());
2652
+ const allowed = (name, tool) => (!this.classicContactRestricted(name) || CLASSIC_RESTRICTED_TOOLS.includes(tool))
2653
+ && nativePaneToolAvailable(tool) && mayUseTool(resolveToolSet(this.fleetConfig?.instances[name], name), tool)
2654
+ && !dashboardRefusalIn(this.fleetConfig, name, tool);
2655
+ const manager = new NativePaneManager({
2656
+ ...(graph ? { requestContexts: graph.panes, registration: graph.registration } : {}),
2657
+ home: this.dataDir, store, config: name => this.fleetConfig?.instances[name],
2658
+ freshNotice: async (name, provider) => {
2659
+ const message = t(provider === "codex" ? "native_pane.codex_fresh_started" : "native_pane.fresh_started");
2660
+ this.eventLog?.insert(name, "native_pane_fresh_started", {});
2661
+ this.logger.info({ name }, message);
2662
+ await this.notifyInstanceTopic(name, message);
2663
+ },
2664
+ admit: (name, config) => {
2665
+ const now = this.fleetConfig?.instances[name];
2666
+ if (this.shuttingDown || !isNativePaneInstance(now) || now?.native_agent_id !== config.native_agent_id
2667
+ || now?.machine_id !== config.machine_id || now?.working_directory !== config.working_directory || now?.backend !== config.backend
2668
+ || now?.model !== config.model || now?.native_sandbox !== config.native_sandbox || now?.systemPrompt !== config.systemPrompt || now?.operations !== config.operations || now?.workflow !== config.workflow
2669
+ || now?.general_topic !== config.general_topic || now?.native_general_binding !== config.native_general_binding
2670
+ || nativeCredentialProfile(now) !== nativeCredentialProfile(config))
2671
+ throw Error("Native pane configuration or lifetime changed");
2672
+ // Fail closed: a Runtime that does not report the capability would start the terminal on the computer's own account.
2673
+ if (nativeCredentialProfile(config) && !this.runtimeCoordinator().machine(config.machine_id)?.runtimeInfo?.capabilities.includes(RUNTIME_CREDENTIAL_CAPABILITY))
2674
+ throw Error("This computer's Runtime is too old to choose a Claude account. Update the Runtime on that computer, then try again.");
2675
+ if (config.machine_id ? this.remotePaneDrain || !remoteRuntimeEnabled() : this.localPaneDrain || !localWindowsCliEnabled())
2676
+ throw Error("Native runtime is switched off");
2677
+ },
2678
+ endpoint: async (agent, cleanup = false) => {
2679
+ if (!agent.machineId) {
2680
+ if (!cleanup)
2681
+ return this.localNativePaneEndpoint();
2682
+ if (!this.localPaneRelay)
2683
+ throw Error("Local cleanup transport is unavailable; pane remains reserved");
2684
+ return this.localPaneRelay;
2685
+ }
2686
+ const hub = cleanup ? this.runtimeHub : this.runtimeCoordinator(), machineId = agent.machineId;
2687
+ if (!hub)
2688
+ throw Error("Remote cleanup transport is unavailable; pane remains reserved");
2689
+ const draining = () => !!this.remotePaneDrain;
2690
+ return { machineId, online: () => !this.shuttingDown && (draining() || remoteRuntimeEnabled()) && this.runtimeHub === hub && hub.machine(machineId)?.status === "online",
2691
+ call: request => {
2692
+ if (this.runtimeHub !== hub || !(draining() || remoteRuntimeEnabled()) || draining() && request.action !== "snapshot" && request.action !== "close")
2693
+ return Promise.reject(Error("Remote pane transport only permits owned cleanup"));
2694
+ return hub.callPane(machineId, request, maxAgentsPerMachine());
2695
+ }, subscribe: listener => hub.subscribe(listener),
2696
+ epoch: () => hub.paneTransportEpoch(machineId), version: provider => hub.machine(machineId)?.inventory?.clis.find(row => row.id === provider && row.runnable)?.version ?? null };
2697
+ },
2698
+ instructions: (name, config) => buildNativeFleetInstructions({ instanceName: name, workingDirectory: config.working_directory,
2699
+ displayName: config.display_name, description: config.description, customPrompt: config.systemPrompt, operations: config.operations,
2700
+ workflow: config.workflow, taskBoard: !dashboardRefusalIn(this.fleetConfig, name, "task"),
2701
+ runtimeIdentity: { kind: "fleet-topic", backend: config.backend ?? "codex", model: config.model || "default" } }, config.general_topic === true),
2702
+ menu: name => TOOLS.filter(tool => allowed(name, tool.name)).map(tool => ({ ...tool })),
2703
+ allowed: (name, tool, args) => allowed(name, tool) && !nativePaneToolRefusal(tool, args), published: (name, daemon) => this.daemons.get(name) === daemon,
2704
+ invoke: async (daemon, input, current, name) => {
2705
+ if (input.tool === "list_models") {
2706
+ const { ListModelsArgs } = await import("./outbound-schemas.js");
2707
+ const parsed = ListModelsArgs.safeParse(input.args);
2708
+ if (!parsed.success || !current())
2709
+ return { result: null, error: "Invalid native model request or expired owner" };
2710
+ const target = parsed.data.instance_name ?? name;
2711
+ if (!isWindowsInstance(this.fleetConfig?.instances[target]))
2712
+ return { result: null, error: "Native panes can only read Windows runtime model inventories" };
2713
+ return { result: await this.listModelCatalog({ instanceName: target }) };
2714
+ }
2715
+ const ops = { hub_set_intro: "hub-set-intro", hub_room_list: "hub-room-list", hub_room_post: "hub-room-post", hub_room_history: "hub-room-history", hub_room_members: "hub-room-members", hub_people_search: "hub-people-search", list_instances: "list", describe_instance: "describe", task: "task", send_to_instance: "send",
2716
+ delegate_task: "delegate", request_information: "ask", report_result: "report", delivery_status: "delivery-status" };
2717
+ const { nativeAgentAdmissionContext } = await import("./native-agent-admission.js");
2718
+ const { dispatchAgentOperation } = await import("./agent-endpoint.js");
2719
+ return daemon.handlePaneToolCall(input, { current, allowed: tool => allowed(name, tool), ...(input.requestContext ? { requestContext: input.requestContext } : {}),
2720
+ dispatch: (tool, args) => ops[tool] ? dispatchAgentOperation(nativeAgentAdmissionContext(this, {
2721
+ instance: name, operation: { tool, args }, current: () => current() && allowed(name, tool), taskAllowed: () => current() && allowed(name, "task"),
2722
+ ...(input.requestContext?.coverage === "covered" ? { requestContext: input.requestContext.lease } : input.requestContext ? { notCoveredReason: input.requestContext.reason } : {}),
2723
+ }), name, ops[tool], args, input.operationId, () => current() && allowed(name, tool)) : undefined });
2724
+ },
2725
+ });
2726
+ return this.paneManager = graph ? this.ownRequestContextNativeFactory(manager, graph) : manager;
2727
+ }
2728
+ finally {
2729
+ this.requestContextOpeningPaneManagers--;
2730
+ }
1844
2731
  }
1845
2732
  /** Prepare only bundled role files; this neither switches General nor starts a provider process. */
1846
2733
  async prepareWindowsGeneralWorkspace(name, machineId, cli, bindingId, authorized) {
@@ -2181,6 +3068,8 @@ export class FleetManager {
2181
3068
  updateChatCardVersion = new Map();
2182
3069
  /** #4485 review 2: an answer that came while its card was still being posted (the post records it when it returns). */
2183
3070
  updateChatCardAnswered = new Map();
3071
+ /** Prism #4584 (1): a press refused while its card was still being posted (the post records it, so it isn't relabelled expired). */
3072
+ updateChatCardRefused = new Set();
2184
3073
  updateChatCardTimer = null;
2185
3074
  readUpdateChatCard() {
2186
3075
  try {
@@ -2207,14 +3096,18 @@ export class FleetManager {
2207
3096
  if (view && view.state === "offered") {
2208
3097
  // M-3770 1.2's cached pre-flight, when this build has it (#4483): the second sentence only where it is true.
2209
3098
  const pre = this.updatePreflight;
3099
+ // M-3864 R1: a machine where even an admin's press can't start it says why, as the web does (its card offers Not now only).
3100
+ const blocking = pre ? preflightBlocking(pre) : null;
3101
+ if (blocking)
3102
+ return `${t("update.chatcard.offer", view.version)}\n${t("update.chatcard.cant", preflightWords(blocking, (key, ...args) => t(key, ...args)))}`;
2210
3103
  const p3 = pre?.checks.find(c => c.id === "P3");
2211
3104
  // The leader's copy pass (S-237): a title and one line, as on the web.
2212
3105
  const line = !p3 ? t("update.chatcard.continues") : p3.ok ? t("update.chatcard.back", current ?? "?") : t("update.chatcard.noWayBack");
2213
3106
  return `${t("update.chatcard.offer", view.version)}\n${line}`;
2214
3107
  }
2215
3108
  // The card's own short lines, as on the web (the leader's copy pass); anything else in /update's words.
2216
- const at = (ms) => { if (!ms)
2217
- 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())}`; };
3109
+ // M-3864 R2: the fleet's zone with its offset, as schedules say times (the web shows the person's own zone).
3110
+ const at = (ms) => (ms ? formatFleetTime(ms, this.usageZone()) : "");
2218
3111
  if (view?.state === "waiting-idle")
2219
3112
  return t("update.chatcard.state_waiting", view.version);
2220
3113
  if (view?.state === "scheduled")
@@ -2227,9 +3120,19 @@ export class FleetManager {
2227
3120
  return t("update.chatcard.state_done", view.version);
2228
3121
  if (view?.state === "failed")
2229
3122
  return t("update.chatcard.state_failed", view.version, current ?? "?");
2230
- const reply = updateOfferReply(view, current, !!resolveUpdates(this.fleetConfig?.updates).pin);
3123
+ const reply = updateOfferReply(view, current, !!resolveUpdates(this.fleetConfig?.updates).pin, this.usageZone());
2231
3124
  return t(reply.key, ...reply.args);
2232
3125
  }
3126
+ /**
3127
+ * M-3864 R1: the buttons General's card offers on this machine, by the same rule the web's card and the server use: an
3128
+ * admin's press (Update when idle) needs pressHere, a picked time (Tonight) a machine that updates itself. No pre-flight
3129
+ * result yet: all three (the launch decides, as on the web).
3130
+ */
3131
+ updateChatCardActions(pre = this.updatePreflight) {
3132
+ if (!pre)
3133
+ return [...UPDATE_CHAT_CARD_ALL];
3134
+ return UPDATE_CHAT_CARD_ALL.filter(a => a === "not-now" || preflightAllows(pre, a === "tonight" ? "unattended" : "press"));
3135
+ }
2233
3136
  /** General's chat place for the card, or null (no General, no chat: a web-only fleet's banner says it). */
2234
3137
  updateChatCardPlace() {
2235
3138
  if (this.webOnlyPromptPlace())
@@ -2269,13 +3172,21 @@ export class FleetManager {
2269
3172
  // #4485 review 1: an offered card whose buttons are gone (a restart empties the nonce map; they also expire) is not
2270
3173
  // a usable card: it is marked expired and one with live buttons is posted.
2271
3174
  const live = !!posted?.nonce && this.pendingNonceButtons.get(posted.nonce)?.prefix === UPDATE_CARD_CALLBACK_PREFIX;
2272
- if (view && state === "offered" && view.installable && (!posted || posted.version !== view.version || posted.state !== "offered" || !live)) {
3175
+ // M-3864 R1: a card whose buttons the machine no longer allows (or newly allows) is posted again with the right ones.
3176
+ const actions = this.updateChatCardActions(), actionsKey = actions.join(",");
3177
+ // Prism #4584 (2): and the reason it gives for not updating here (another stop keeps Not now only but must say so).
3178
+ const blockingCheck = this.updatePreflight ? preflightBlocking(this.updatePreflight) : null;
3179
+ const blockingKey = blockingCheck ? preflightWords(blockingCheck, (key, ...args) => t(key, ...args)) : "";
3180
+ const sameActions = (posted?.actions ?? UPDATE_CHAT_CARD_ALL.join(",")) === actionsKey && (posted?.blocking ?? "") === blockingKey;
3181
+ if (view && state === "offered" && view.installable && (!posted || posted.version !== view.version || posted.state !== "offered" || !live || !sameActions)) {
2273
3182
  const place = this.updateChatCardPlace();
2274
3183
  if (!place)
2275
3184
  return;
2276
- if (posted) {
3185
+ // A refused press already edited its card to say why; that text stays (it is not called expired).
3186
+ if (posted && !(posted.refused && posted.version === view.version && !live)) {
2277
3187
  const old = posted.state === "offered" && posted.version === view.version && !live ? t("update.chatcard.expired")
2278
- : posted.version === view.version ? t("update.chatcard.cancelled", posted.version) : t("update.chatcard.replaced", view.version);
3188
+ : posted.state === "offered" && posted.version === view.version && !sameActions ? t("update.chatcard.replaced", view.version)
3189
+ : posted.version === view.version ? t("update.chatcard.cancelled", posted.version) : t("update.chatcard.replaced", view.version);
2279
3190
  await this.editUpdateChatCard(posted, old);
2280
3191
  }
2281
3192
  const version = view.version;
@@ -2283,7 +3194,7 @@ export class FleetManager {
2283
3194
  prefix: UPDATE_CARD_CALLBACK_PREFIX, alertType: "tip", instanceName: place.general, adapter: place.adapter, adapterId: place.adapterId,
2284
3195
  chatId: place.chatId, ...(place.threadId ? { threadId: place.threadId } : {}),
2285
3196
  message: this.updateChatCardText(view, current),
2286
- 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") }],
3197
+ choices: actions.map(action => ({ action, label: t(action === "when-idle" ? "update.chatcard.when_idle" : action === "tonight" ? "update.chatcard.tonight" : "update.chatcard.not_now") })),
2287
3198
  expiredText: t("update.chatcard.expired"),
2288
3199
  timeoutMs: UPDATE_CHAT_CARD_MS,
2289
3200
  // #4485 review 2: the provider's own delivery address, kept per nonce as it is sent — a click may consume the
@@ -2302,12 +3213,14 @@ export class FleetManager {
2302
3213
  const sent = this.updateChatCardSent.get(nonce);
2303
3214
  const answered = this.updateChatCardAnswered.get(nonce);
2304
3215
  this.updateChatCardAnswered.delete(nonce);
2305
- this.writeUpdateChatCard({ version, state: answered ?? "offered", nonce: answered ? null : nonce, messageId: sent?.messageId ?? "",
3216
+ const refused = this.updateChatCardRefused.delete(nonce);
3217
+ this.writeUpdateChatCard({ version, state: answered ?? "offered", nonce: answered || refused ? null : nonce, messageId: sent?.messageId ?? "",
2306
3218
  chatId: sent?.chatId ?? place.chatId, ...((sent?.threadId ?? place.threadId) ? { threadId: sent?.threadId ?? place.threadId } : {}),
2307
- adapterId: place.adapterId, at: Date.now() });
2308
- // The card may have moved on while this was being posted (a newer version, an answer on the web): sync again.
3219
+ adapterId: place.adapterId, at: Date.now(), actions: actionsKey, ...(blockingKey ? { blocking: blockingKey } : {}), ...(refused ? { refused: true } : {}) });
3220
+ // The card may have moved on while this was being posted (a newer version, an answer on the web), or a press on it
3221
+ // was refused (the machine changed): sync again.
2309
3222
  const after = this.updateOfferView();
2310
- if (!answered && (after?.version !== version || (after?.state ?? "none") !== "offered"))
3223
+ if (refused || !answered && (after?.version !== version || (after?.state ?? "none") !== "offered"))
2311
3224
  this.updateChatCardAgain = true;
2312
3225
  return;
2313
3226
  }
@@ -2368,8 +3281,7 @@ export class FleetManager {
2368
3281
  await this.retireNonceButtons(entry, messageId, shownVersion && before && before.version !== shownVersion ? t("update.chatcard.replaced", before.version) : t("update.chatcard.expired"));
2369
3282
  return true;
2370
3283
  }
2371
- const tonight = (() => { const d = new Date(); d.setHours(22, 0, 0, 0); if (d.getTime() - Date.now() < 30 * 60_000)
2372
- d.setDate(d.getDate() + 1); return d.getTime(); })();
3284
+ const tonight = updateTonightAt(Date.now(), this.usageZone());
2373
3285
  const body = action === "tonight" ? { action: "pick-time", at: tonight } : { action: action };
2374
3286
  const by = updateAnswerLabel(data.username ?? "");
2375
3287
  let text;
@@ -2382,17 +3294,24 @@ export class FleetManager {
2382
3294
  }
2383
3295
  catch { /* unknown */ }
2384
3296
  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);
2385
- text = r.ok ? t("update.chatcard.by", this.updateChatCardText(view, current), by) : t("update.chatcard.refused", why || String(r.status));
3297
+ // M-3864 R1: the machine's pre-flight refused it: the reason in words (as the web and /update say it), never the key.
3298
+ const preflight = !r.ok && "key" in r.body && r.body.key === "preflight" ? r.body.preflight : null;
3299
+ const refusal = preflight ? preflightRefusal(preflight, action === "tonight" ? "unattended" : "press", (key, ...args) => t(key, ...args)) : null;
3300
+ text = r.ok ? t("update.chatcard.by", this.updateChatCardText(view, current), by) : refusal ?? t("update.chatcard.refused", why || String(r.status));
2386
3301
  const posted = this.readUpdateChatCard();
2387
3302
  const nextState = view?.state ?? "none";
2388
3303
  if (posted && posted.nonce === nonce) {
2389
3304
  // The press carries the message's own id where the post's record has none yet.
2390
- this.writeUpdateChatCard({ ...posted, state: nextState, nonce: null, messageId: posted.messageId || sent?.messageId || String(messageId ?? "") });
3305
+ this.writeUpdateChatCard({ ...posted, state: nextState, nonce: null, messageId: posted.messageId || sent?.messageId || String(messageId ?? ""), ...(r.ok ? {} : { refused: true }) });
2391
3306
  }
2392
3307
  else if (r.ok) {
2393
3308
  // The card is still being posted (its record is written when the post returns): it records this answer then.
2394
3309
  this.updateChatCardAnswered.set(nonce, nextState);
2395
3310
  }
3311
+ else {
3312
+ // Prism #4584 (1): a refusal too, so that post records its text as what the message says (not expired).
3313
+ this.updateChatCardRefused.add(nonce);
3314
+ }
2396
3315
  }
2397
3316
  catch (err) {
2398
3317
  text = t("update.chatcard.refused", err.message);
@@ -3714,16 +4633,21 @@ export class FleetManager {
3714
4633
  }
3715
4634
  }
3716
4635
  /** The agent's durable incarnation id (create: make one if none; else null). A changed fingerprint rotates it. */
3717
- hubAgentIncarnation(agent, cfg, create) {
4636
+ hubAgentIncarnation(agent, cfg, create, explicitBirth = false) {
3718
4637
  const fp = createHash("sha256").update(JSON.stringify([cfg.backend ?? "claude-code", cfg.working_directory, cfg.runtime ?? "", cfg.machine_id ?? "", ...(cfg.hubClassicIdentity ? [cfg.hubClassicIdentity] : [])])).digest("hex");
3719
4638
  const map = this.readHubIncarnations(), entry = Object.prototype.hasOwnProperty.call(map, agent) ? map[agent] : undefined;
3720
- if (entry && entry.fp === fp && typeof entry.id === "string")
4639
+ if (entry && entry.fp === fp && typeof entry.id === "string") {
4640
+ if (explicitBirth && !entry.requestWork && !entry.retired?.length) {
4641
+ map[agent] = { ...entry, requestWork: "pending" };
4642
+ return this.writeHubIncarnations(map) === "written" ? entry.id : null;
4643
+ }
3721
4644
  return entry.id;
4645
+ }
3722
4646
  if (!entry && !create)
3723
4647
  return null;
3724
- map[agent] = { id: randomUUID(), fp, ...(cfg.hubClassicIdentity ? { classic: true } : {}) };
4648
+ map[agent] = rotateHubAgentIncarnation(entry, fp, !!cfg.hubClassicIdentity, Date.now(), explicitBirth);
3725
4649
  // A rotation that could only clear the file still invalidated the old id durably; the new one is made next time.
3726
- return this.writeHubIncarnations(map) === "written" ? map[agent].id : null;
4650
+ return this.writeHubIncarnations(map) === "written" ? map[agent].id ?? null : null;
3727
4651
  }
3728
4652
  /**
3729
4653
  * Every configuration in force: rotate a recorded agent's incarnation when its backend/folder/runtime changed; drop
@@ -3739,6 +4663,16 @@ export class FleetManager {
3739
4663
  this.settleHubIncarnations();
3740
4664
  if (this.hubIncarnationsBroken)
3741
4665
  throw new Error("Hub agent incarnations cannot be written here");
4666
+ // Only a strict new configuration entry can mint first-birth evidence. A lazy token read,
4667
+ // a restart or a missing/corrupt incarnation/work file can never invent that transition.
4668
+ if (strict && this.savedFleetConfigSnapshot?.instances) {
4669
+ for (const agent of Object.keys(this.fleetConfig.instances))
4670
+ if (!Object.hasOwn(this.savedFleetConfigSnapshot.instances, agent)) {
4671
+ const config = this.hubAgentConfig(agent);
4672
+ if (config)
4673
+ this.hubAgentIncarnation(agent, config, true, true);
4674
+ }
4675
+ }
3742
4676
  if (!existsSync(this.hubIncarnationsPath()))
3743
4677
  return;
3744
4678
  for (const agent of Object.keys(this.readHubIncarnations())) {
@@ -3764,7 +4698,9 @@ export class FleetManager {
3764
4698
  const map = this.readHubIncarnations();
3765
4699
  if (!Object.prototype.hasOwnProperty.call(map, agent))
3766
4700
  return;
3767
- delete map[agent];
4701
+ if (!map[agent]?.id)
4702
+ return;
4703
+ map[agent] = forgetHubAgentIncarnation(map[agent]);
3768
4704
  this.writeHubIncarnations(map);
3769
4705
  }
3770
4706
  catch (err) {
@@ -3881,7 +4817,19 @@ export class FleetManager {
3881
4817
  * A Hub question to its representative agent: ordinary cross-instance delivery (idle gate, wake, retries), from the
3882
4818
  * reserved Hub sender with the Hub-issued correlation id. beforeInput runs immediately before the IPC hand-off.
3883
4819
  */
4820
+ requestContextHubAdmission;
4821
+ /** Installed as one of the publication's ingress owners, never from a tool or a question selector. */
4822
+ makeRequestContextHubAdmission(resolve) {
4823
+ return (input) => {
4824
+ const resolver = resolve(input.agent);
4825
+ if (!resolver)
4826
+ throw Error("Hub request input owner is unavailable");
4827
+ return resolver.capture(input);
4828
+ };
4829
+ }
3884
4830
  async deliverHubQuestion(input) {
4831
+ if (this.requestContextAdmission && !await this.requestContextAdmission.wait(() => !this.shuttingDown && input.stillCurrent()))
4832
+ return false;
3885
4833
  const { HUB_REPORT_TARGET } = await import("./hub/representative.js");
3886
4834
  const config = this.hubAgentConfig(input.agent);
3887
4835
  if (this.shuttingDown || !config)
@@ -3889,6 +4837,9 @@ export class FleetManager {
3889
4837
  // Windows agents run through their own runtime, which has no pre-input hook: not a P1 representative.
3890
4838
  if (isNativeExecInstance(config))
3891
4839
  return false;
4840
+ const scoped = requestContextPolicyInstalled(this.requestContextPolicy) ? this.requestContextHubAdmission?.(input) : undefined;
4841
+ if (requestContextPolicyInstalled(this.requestContextPolicy) && !scoped)
4842
+ throw Error("Hub request input admission is unavailable");
3892
4843
  const ipcMeta = {
3893
4844
  chat_id: "",
3894
4845
  message_id: `hubmsg-${input.correlationId.slice(4)}`,
@@ -3908,7 +4859,7 @@ export class FleetManager {
3908
4859
  // M-3660: the share's opt-out travels with the question; its daemon's hub_question_input then opens no window.
3909
4860
  if (input.contactLimit === false)
3910
4861
  ipcMeta.hub_contact_limit = "off";
3911
- const result = await this.deliverToInstance(input.agent, { type: "fleet_inbound", targetSession: input.agent, content: this.screenHubText(input.text), meta: ipcMeta }, { isCrossInstance: true, stillCurrent: input.stillCurrent, beforeInput: async () => {
4862
+ const result = await this.deliverToInstance(input.agent, { type: "fleet_inbound", targetSession: input.agent, content: this.screenHubText(input.text), meta: ipcMeta, ...(scoped ? { request_context_input_id: scoped.inputId } : {}) }, { isCrossInstance: true, stillCurrent: input.stillCurrent, beforeInput: async () => {
3912
4863
  const classic = this.isClassicInstance(input.agent);
3913
4864
  // A busy Classic room must finish its public turn first; never force a private question into that turn's queue.
3914
4865
  const idle = () => this.waitForInstanceIdle(input.agent, 0, this.lastDeliveryAt.get(input.agent) ?? 0, () => !input.stillCurrent());
@@ -3919,6 +4870,8 @@ export class FleetManager {
3919
4870
  if (generation)
3920
4871
  ipcMeta.hub_room_context_generation = generation;
3921
4872
  }
4873
+ if (scoped && !await scoped.waitBeforeInput())
4874
+ return false;
3922
4875
  if (!(await input.beforeInput()))
3923
4876
  return false;
3924
4877
  if (classic) {
@@ -4125,6 +5078,12 @@ export class FleetManager {
4125
5078
  hubRoomList(caller) {
4126
5079
  return this.hubAgentRooms?.rooms(caller) ?? Promise.resolve({ ok: false, code: "unavailable" });
4127
5080
  }
5081
+ hubRoomHistory(caller, room, options) {
5082
+ const policy = this.requestContextPolicy;
5083
+ if (!policy || requestContextInstalledMode(policy) !== "active")
5084
+ return Promise.resolve({ ok: false, code: "denied" });
5085
+ return this.hubAgentRooms?.history({ ...caller, current: () => this.requestContextPolicy === policy && requestContextInstalledMode(policy) === "active" && caller.current() }, room, options) ?? Promise.resolve({ ok: false, code: "unavailable" });
5086
+ }
4128
5087
  hubRoomMembers(caller, room, options) {
4129
5088
  return this.hubAgentRooms?.members(caller, room, options) ?? Promise.resolve({ ok: false, code: "unavailable" });
4130
5089
  }
@@ -4452,6 +5411,9 @@ export class FleetManager {
4452
5411
  /** M-3770 (#4480 §4): the last pre-flight — a diagnostic for the page; every launch proves its local checks again. */
4453
5412
  updatePreflight = null;
4454
5413
  updatePreflightRunning = null;
5414
+ /** M-3770 1.6: the fix buttons' answers by person, fix and Idempotency-Key (the last 32), and the one fix running at a time. */
5415
+ updateFixAnswers = new Map();
5416
+ updateFixChain = Promise.resolve();
4455
5417
  /** M-2738: a web start's Idempotency-Key → its answer (a retried request never starts a second update). */
4456
5418
  webUpdateStarts = new Map();
4457
5419
  /**
@@ -5062,6 +6024,7 @@ export class FleetManager {
5062
6024
  const baselines = this.settingsBaselineReader = new SettingsBaselines({ dataDir: this.dataDir, configPath: () => this.configPath,
5063
6025
  config: () => this.fleetConfig, current: () => [this.settingsGeneration, this.settingsRuntimeRevision, this.shuttingDown],
5064
6026
  generalLocation: input => this.previewGeneralLocation(input),
6027
+ requestContextControl: () => this.requestContextControl?.snapshot() ?? null,
5065
6028
  hubMembership: raw => hubMembershipSettings(raw),
5066
6029
  hubPageSharing: raw => hubPageSharingSettings(raw),
5067
6030
  guestDerivedScopes: () => this.guestDerivedScopes(),
@@ -5131,6 +6094,7 @@ export class FleetManager {
5131
6094
  current: () => current() && sessions === this.webSessions && !!this.webToken
5132
6095
  && sessions.isCurrent(record, tokenEpoch(this.webToken)) && (!exposure || exposure.isCurrent()) };
5133
6096
  }, baseline: () => baselines.read(), snapshot: () => baselines.snapshot(),
6097
+ requestContextControl: () => this.requestContextControl,
5134
6098
  selfConfirm: (req, id) => this.settingsSelfConfirmation(store, req, id),
5135
6099
  totp: { state: (req, id) => this.settingsTotpState(store, req, id), confirm: (req, id, code, digest) => this.settingsTotpConfirm(store, req, id, code, digest) },
5136
6100
  remote: req => this.settingsPageIsRemote(req),
@@ -6532,7 +7496,22 @@ export class FleetManager {
6532
7496
  const dbPath = join(this.dataDir, "delivery-outbox.db");
6533
7497
  let outbox;
6534
7498
  try {
6535
- outbox = new DeliveryOutbox(dbPath, this.managerBootId);
7499
+ const activated = readRequestContextBootState(this.dataDir);
7500
+ if (activated && !this.requestContextBoot) {
7501
+ const lease = captureProcessFleetLease(this.dataDir);
7502
+ if (!lease)
7503
+ throw Error("Request-context Fleet lease unavailable");
7504
+ const boot = new RequestContextBoot(activated, lease);
7505
+ this.requestContextBoot = boot;
7506
+ this.attachRequestContextAdmission(boot.publication.admission);
7507
+ this.requestContextPolicy = boot.policy;
7508
+ // Replaced only by the controlled installer: a legacy launch must never slip through startup recovery.
7509
+ this.prepareRequestContextStart = () => boot.requirePreparedOwner();
7510
+ }
7511
+ outbox = new DeliveryOutbox(dbPath, this.managerBootId, this.requestContextBoot ? {
7512
+ requestContextDispatchVersion: 1, requestContextRelayVersion: 1,
7513
+ requestContextRecoveryFence: this.requestContextBoot.recoveryCurrent,
7514
+ } : {});
6536
7515
  if (!this.deliveryOutboxRecovered) {
6537
7516
  const recovered = outbox.recoverForBoot(this.managerBootId);
6538
7517
  this.logger.info({ ...recovered }, "Recovered durable delivery outbox for this process boot");
@@ -6551,12 +7530,20 @@ export class FleetManager {
6551
7530
  }
6552
7531
  this.deliveryOutbox = outbox;
6553
7532
  this.deliveryOutboxRecovered = true;
7533
+ this.ensureRequestContextController();
6554
7534
  this.initializeWorkingRecovery(outbox);
6555
7535
  outbox.on("working_references", (names) => {
6556
7536
  for (const name of names)
6557
7537
  this.observeWorkingState(name, "obligations");
6558
7538
  });
6559
- outbox.on("admitted", () => { this.scheduleDeliveryOutboxPump(); this.wakeCoordinator?.kick(); });
7539
+ outbox.on("request_context_admitted", () => {
7540
+ if (this.requestContextAdmission) {
7541
+ this.requestContextAdmission.arrived();
7542
+ this.scheduleDeliveryOutboxPump();
7543
+ this.wakeCoordinator?.kick();
7544
+ }
7545
+ });
7546
+ outbox.on("admitted", () => { this.requestContextAdmission?.arrived(); this.scheduleDeliveryOutboxPump(); this.wakeCoordinator?.kick(); });
6560
7547
  outbox.on("state", (event) => {
6561
7548
  if (event.deliveryId) {
6562
7549
  const row = outbox.get(event.deliveryId);
@@ -6902,7 +7889,23 @@ export class FleetManager {
6902
7889
  makeRequestContextPolicy() {
6903
7890
  return { assert: input => {
6904
7891
  try {
6905
- return assertRequestContextOperation(input);
7892
+ const permit = assertRequestContextOperation(input);
7893
+ // Ordinary ingress is not administrator authority. Recheck the ORIGINAL actor for owner-only
7894
+ // tools on every call, including commit-point calls; demotion alone never adds a contact hold.
7895
+ if (permit.context && toolsFor("coordinator").has(permit.tool) && !toolsFor("worker").has(permit.tool)) {
7896
+ if (permit.context.ingress === "guest" || permit.context.ingress === "hub")
7897
+ throw new RequestContextPolicyError("settings");
7898
+ const actor = permit.context.initiatingActor;
7899
+ const adapter = actor.kind === "person" && actor.platform !== "hub" && actor.platform !== "host"
7900
+ ? [...this.adapters.values(), ...[...this.worlds.values()].map(world => world.adapter)].find(row => row.type === actor.platform) : undefined;
7901
+ const channel = actor.kind === "person" && actor.platform !== "hub"
7902
+ ? (this.fleetConfig?.channels ?? (this.fleetConfig?.channel ? [this.fleetConfig.channel] : [])).find(row => row.type === actor.platform) : undefined;
7903
+ const person = actor.kind === "person" && actor.platform !== "hub"
7904
+ ? { platform: actor.platform, adapterId: actor.platform === "host" ? "host" : adapter?.id ?? channel?.id ?? channel?.type ?? "", userId: actor.userId, label: actor.displayName ?? actor.userId } : null;
7905
+ if (!person?.adapterId || !this.contactAdminOf(permit.context.source.instance, person))
7906
+ throw new RequestContextPolicyError("settings");
7907
+ }
7908
+ return permit;
6906
7909
  }
6907
7910
  catch (error) {
6908
7911
  if (error instanceof RequestContextPolicyError) {
@@ -6913,6 +7916,357 @@ export class FleetManager {
6913
7916
  }
6914
7917
  } };
6915
7918
  }
7919
+ /** Existing Settings administrator scope. This only identifies a principal; it never bypasses per-change confirmation. */
7920
+ requestContextControl;
7921
+ requestContextShadow() {
7922
+ const box = this.deliveryOutbox, lease = captureProcessFleetLease(this.dataDir);
7923
+ return box.requestContextMigrationShadow({ owner: () => this.requestContextBoot?.owner.owner ?? lease?.id ?? null,
7924
+ policyEpoch: () => requestContextDigest([this.fleetConfig, this.settingsRuntimeRevision]), generation: name => { try {
7925
+ return this.contactGeneration(name);
7926
+ }
7927
+ catch {
7928
+ return null;
7929
+ } }, canManage: (name, actor) => this.contactAdminOf(name, actor) }).inspect();
7930
+ }
7931
+ requestContextBlockers() {
7932
+ const box = this.deliveryOutbox;
7933
+ if (!box || !this.fleetConfig)
7934
+ return [{ id: "owners", kind: "owners", labels: [], ownerCause: "update", action: "inspect" }];
7935
+ const label = (name) => this.fleetConfig?.instances[name]?.display_name ?? this.classicChannels?.getAll().find(row => row.instanceName === name)?.displayName ?? name;
7936
+ const state = box.requestContextInstallation().read(), out = [];
7937
+ if (!requestContextUpdateSettled(this.dataDir))
7938
+ out.push({ id: "update", kind: "update", labels: [], action: "inspect" });
7939
+ if (state && (!this.requestContextModes?.current() || !this.requestContextBoot?.publication.installed()) && state.mode !== "draining")
7940
+ out.push({ id: "installation", kind: "owners", labels: [], ownerCause: "update", action: "inspect" });
7941
+ if (!state) {
7942
+ const shadow = this.requestContextShadow();
7943
+ // S-272 (Sentinel's settlement split): each earlier ticket by what settles it. Pending: decided on Authorizations.
7944
+ // Approved and still being delivered (queued … retry_wait): waits for that delivery's own outcome. Approved with a delivery
7945
+ // that ended unconfirmed (e.g. uncertain: terminal, never changes again, Fable #4593), with no or a mismatched record, or
7946
+ // unreadable: nothing here can settle it (absence is never a proof of delivery), so it is named as such.
7947
+ const ids = (...dispositions) => shadow.tickets.filter(row => dispositions.includes(row.disposition)).map(row => row.id);
7948
+ const pending = ids("preserve-legacy-pending"), inflight = ids("legacy-inflight"), unsettled = ids("legacy-unconfirmed", "missing-receipt", "malformed"), named = new Set([...pending, ...inflight, ...unsettled]);
7949
+ if (pending.length)
7950
+ out.push({ id: "legacy-pending", kind: "legacy", labels: pending.slice(0, 64), action: "inspect" });
7951
+ if (inflight.length)
7952
+ out.push({ id: "legacy-inflight", kind: "legacy", labels: inflight.slice(0, 64) });
7953
+ if (unsettled.length)
7954
+ out.push({ id: "legacy-unsettled", kind: "legacy", labels: unsettled.slice(0, 64) });
7955
+ const rest = shadow.blockers.map(row => row.id).filter(id => !named.has(id));
7956
+ if (rest.length || !shadow.complete && !named.size)
7957
+ out.push({ id: "legacy", kind: "legacy", labels: rest.slice(0, 64), action: "inspect" });
7958
+ const inventory = box.requestContextControlInventory(), legacy = inventory.deliveries.filter(row => !row.root);
7959
+ if (legacy.length)
7960
+ out.push({ id: "legacy-deliveries", kind: "legacy", labels: legacy.map(row => `${label(row.source)} → ${label(row.target)}`).slice(0, 64) });
7961
+ const busy = [...this.daemons].filter(([name, daemon]) => { const row = daemon.requestContextLaunchObservation(); return row.observation.processStatus !== "running" || row.observation.executionState !== "idle" || row.pendingCalls || row.responseWaiters || row.queuedInputs || row.transcriptOpen || row.starting || row.stopping || this.requestContextPendingWork.count(name); }).map(([name]) => name);
7962
+ for (const row of WindowsAgents.requestContextOwnersOnDisk(this.dataDir)) {
7963
+ const daemon = row.instance ? this.daemons.get(row.instance) : undefined;
7964
+ // An owned idle persistent pane participates in the controlled relaunch. An exec or cold orphan does not.
7965
+ if (row.kind === "pane" && row.instance && daemon?.usesNativePane() && nativeAgentId(this.hubAgentConfig(row.instance)) === row.agentId)
7966
+ continue;
7967
+ const name = row.instance ?? row.agentId;
7968
+ if (!busy.includes(name))
7969
+ busy.push(name);
7970
+ }
7971
+ if (busy.length)
7972
+ out.push({ id: "busy", kind: "owners", labels: busy.map(label).slice(0, 64), agents: busy.map(id => ({ id, label: label(id) })).slice(0, 64), ownerCause: "work", action: "inspect" });
7973
+ const peers = this.captureRequestContextRuntimeSet(), old = peers.advertised();
7974
+ if (old.length)
7975
+ out.push({ id: "peers", kind: "peers", labels: peers.labels().filter(row => old.includes(row.id)).map(row => row.label).slice(0, 64), action: "inspect" });
7976
+ }
7977
+ else if (state.mode === "draining") {
7978
+ const inventory = box.requestContextControlInventory(box.requestContextInstallation().drainRoots());
7979
+ for (const row of inventory.recoveries)
7980
+ out.push({ id: `recovery:${requestContextDigest(row.pointer)}`, kind: "recovery", labels: [label(row.instance)], agents: [{ id: row.instance, label: label(row.instance) }], action: "stop-work" });
7981
+ for (const row of inventory.returns)
7982
+ out.push({ id: `return:${row.requestDeliveryId}`, kind: "returns", labels: [`${label(row.requester.instance)} → ${label(row.responder.instance)}`], action: "stop-waiting" });
7983
+ for (const row of inventory.tickets)
7984
+ out.push({ id: `ticket:${row.id}`, kind: "tickets", labels: [`${label(row.source)} → ${label(row.target)}`], action: "decline" });
7985
+ for (const row of inventory.deliveries)
7986
+ out.push({ id: `delivery:${row.id}`, kind: "work", labels: [`${label(row.source)} → ${label(row.target)}`], action: ["queued", "retry_wait"].includes(row.state) ? "withdraw" : "inspect" });
7987
+ if (!out.length && this.requestContextModes)
7988
+ for (const root of box.requestContextInstallation().drainRoots())
7989
+ if (this.requestContextModes.drain.inspectWork(root).blockers.length) {
7990
+ out.push({ id: `work:${root}`, kind: "work", labels: [], action: "inspect" });
7991
+ break;
7992
+ }
7993
+ }
7994
+ return [...out, ...this.requestContextCutoverErrors].slice(0, 128);
7995
+ }
7996
+ requestContextActivationLease() {
7997
+ const lease = captureProcessFleetLease(this.dataDir), prefix = installPrefixOf(fileURLToPath(new URL("..", import.meta.url)));
7998
+ if (!lease || !prefix)
7999
+ return null;
8000
+ const admission = createRequire(import.meta.url)("../launcher/install-admission.cjs");
8001
+ return acquireRequestContextActivationLease(this.dataDir, prefix, { pid: process.pid, processStart: admission.processStart, startTicks: admission.startTicks, bootId: admission.bootId, newToken: () => randomBytes(16).toString("hex"), now: () => new Date(), log: message => this.logger.info(message) }, lease);
8002
+ }
8003
+ ensureRequestContextController() {
8004
+ const box = this.deliveryOutbox, lease = captureProcessFleetLease(this.dataDir), manager = this.managerBootId;
8005
+ if (!box || !lease?.current() || this.requestContextControlBox === box)
8006
+ return;
8007
+ const current = () => !this.shuttingDown && lease.current() && this.managerBootId === manager && this.deliveryOutbox === box;
8008
+ const controller = new RequestContextController({ current, enableUnavailable: () => true, principal: (req, url) => this.requestContextControlPrincipal(req, url),
8009
+ permitContinuation: (req, res) => permitWebContinuation(req, res, { webToken: this.webToken, webSessions: this.webSessions }),
8010
+ base: () => ({ state: box.requestContextInstallation().read(), offer: captureRequestContextEnableOffer(this.dataDir), restartCount: box.requestContextInstallation().read() ? 0 : this.daemons.size, timeZone: this.usageZone() }),
8011
+ inspect: () => this.requestContextBlockers(),
8012
+ enable: async (actor, offer, decisionCurrent) => {
8013
+ this.requestContextCutoverErrors = [];
8014
+ if (this.requestContextBlockers().length)
8015
+ return;
8016
+ const update = this.requestContextActivationLease();
8017
+ if (!update) {
8018
+ this.requestContextCutoverErrors = [{ id: "update-lock", kind: "update", labels: [], action: "inspect" }];
8019
+ return;
8020
+ }
8021
+ let stage, preparingPeerLabels = [];
8022
+ try {
8023
+ if (!decisionCurrent() || !offer.current())
8024
+ throw Error("stale");
8025
+ const state = box.requestContextInstallation().read(), peers = this.captureRequestContextRuntimeSet();
8026
+ preparingPeerLabels = peers.labels().map(row => row.label).slice(0, 64);
8027
+ let peerProof;
8028
+ const transports = () => { try {
8029
+ const proof = peers.prove();
8030
+ if (!peerProof)
8031
+ peerProof = proof;
8032
+ return peerProof.current();
8033
+ }
8034
+ catch {
8035
+ return false;
8036
+ } };
8037
+ if (!state) {
8038
+ let shadow;
8039
+ const drained = () => { if (!current())
8040
+ return false; const next = this.requestContextShadow(); if (!shadow)
8041
+ shadow = next; return next.complete && !next.blockers.length && next.sha256 === shadow.sha256 && !box.requestContextControlInventory().deliveries.some(row => !row.root) && this.requestContextPendingWork.empty; };
8042
+ stage = await this.prepareRequestContextFirstOnAssembly(drained, transports, this.requestContextRootRetired, offer, actor.execution, peers.prepare);
8043
+ if (!decisionCurrent() || !update.current() || !stage.ready())
8044
+ throw Error("stale");
8045
+ actor.execution.commit(() => { box.requestContextInstallation().activate({ epoch: randomUUID(), owner: stage.boot.owner.owner, activatedAt: Date.now(), invalidates: [...offer.invalidates], offeredLatestDeadline: offer.latestDeadline }, stage.boot.owner, update, () => decisionCurrent() && offer.current() && stage.ready(), 0, stage.initialize); stage.publish(); });
8046
+ }
8047
+ else {
8048
+ if (state.mode !== "off" || !this.requestContextModes?.current())
8049
+ throw Error("unavailable");
8050
+ await peers.prepare();
8051
+ peerProof = peers.prove();
8052
+ const modes = this.requestContextModes;
8053
+ actor.execution.commit(() => { box.requestContextInstallation().activate({ epoch: randomUUID(), owner: modes.boot.owner.owner, activatedAt: Date.now(), invalidates: [...offer.invalidates], offeredLatestDeadline: offer.latestDeadline }, modes.boot.owner, update, () => decisionCurrent() && offer.current() && peerProof.current(), state.revision); modes.publish(() => peerProof.current()); });
8054
+ }
8055
+ this.postFleetSecurityNotice(requestContextEnabledNotice(getLocale()), `request-context:${box.requestContextInstallation().read().epoch}`);
8056
+ }
8057
+ catch (error) {
8058
+ this.logger?.warn?.({ err: error }, "Request-context enable did not finish");
8059
+ if (stage && box.requestContextInstallation().read() === null)
8060
+ await stage.rollback();
8061
+ const detail = error;
8062
+ if (box.requestContextInstallation().read() === null && detail.code?.startsWith("request-context-")) {
8063
+ this.requestContextCutoverErrors = [{ id: "preparation", kind: detail.code.includes("transport") ? "peers" : "owners", labels: detail.agent ? [detail.agent] : detail.code.includes("transport") ? preparingPeerLabels : [], ...(detail.agent ? { agents: [{ id: detail.agent, label: detail.agent }] } : {}), ownerCause: "update", action: "inspect" }];
8064
+ return;
8065
+ }
8066
+ throw error;
8067
+ }
8068
+ finally {
8069
+ update.release();
8070
+ }
8071
+ },
8072
+ disable: async (actor, decisionCurrent) => {
8073
+ if (!this.requestContextModes?.current() && this.requestContextBoot?.publication.heldUnpublished()) {
8074
+ await this.resetRequestContextUnpublishedPreparation();
8075
+ if (!decisionCurrent())
8076
+ throw Error("stale");
8077
+ await this.prepareRequestContextCapableBoot(this.requestContextRootRetired);
8078
+ }
8079
+ const modes = this.requestContextModes, state = box.requestContextInstallation().read();
8080
+ if (!modes?.current() || !state)
8081
+ throw Error("unavailable");
8082
+ actor.execution.commit(() => { if (state.mode === "active")
8083
+ modes.off.begin(state.revision, decisionCurrent); });
8084
+ this.scheduleRequestContextDrain();
8085
+ },
8086
+ resolve: (blocker, actor, decisionCurrent) => this.resolveRequestContextBlocker(blocker, actor, decisionCurrent),
8087
+ changed: () => { this.needsYou?.poke(); this.emitSseEvent("request-context-control", controller.snapshot()); this.emitSseEvent("needs", { items: this.needsYouItems() }); }, });
8088
+ this.requestContextControl = controller;
8089
+ this.requestContextControlBox = box;
8090
+ }
8091
+ async prepareRequestContextFutureOwners() {
8092
+ const factory = this.requestContextFactoryOwner;
8093
+ if (!factory?.current())
8094
+ throw Error("Request owner factory unavailable");
8095
+ const names = [...new Set([...Object.keys(this.fleetConfig?.instances ?? {}), ...(this.classicChannels?.getAll() ?? []).map(row => row.instanceName)])];
8096
+ for (const name of names)
8097
+ if (!this.daemons.has(name)) {
8098
+ const config = this.hubAgentConfig(name);
8099
+ if (!config)
8100
+ throw Error("Request owner configuration unavailable");
8101
+ await factory.beforeStart(name, config);
8102
+ }
8103
+ }
8104
+ requestContextOwnersReady() {
8105
+ try {
8106
+ const factory = this.requestContextFactoryOwner, box = this.deliveryOutbox;
8107
+ if (!factory?.current() || !box)
8108
+ return false;
8109
+ for (const [name, daemon] of this.daemons)
8110
+ if (!factory.bound(name, daemon) || daemon.requestContextHelperReadiness()?.ready !== true)
8111
+ return false;
8112
+ const names = [...new Set([...Object.keys(this.fleetConfig?.instances ?? {}), ...(this.classicChannels?.getAll() ?? []).map(row => row.instanceName)])];
8113
+ return names.every(name => box.requestContextWork.read(name)?.incarnation === this.contactGeneration(name));
8114
+ }
8115
+ catch {
8116
+ return false;
8117
+ }
8118
+ }
8119
+ /** A clock selects old candidates; it never proves completion, delivery, or launch retirement. */
8120
+ collectRequestContextRoots() {
8121
+ const modes = this.requestContextModes, box = this.deliveryOutbox;
8122
+ if (this.shuttingDown || !box?.isOpen || !modes?.current() || !modes.boot.publication.installed())
8123
+ return;
8124
+ for (const candidate of box.requestContextRetirementCandidates()) {
8125
+ let epoch;
8126
+ try {
8127
+ epoch = candidate.epoch ? modes.drain.resume(candidate.root, candidate.epoch) : modes.drain.fence(candidate.root);
8128
+ const proof = modes.drain.prove(candidate.root, epoch);
8129
+ this.requestContextRetirementProofs.set(candidate.root, proof);
8130
+ modes.retireRoot(candidate.root);
8131
+ }
8132
+ catch (error) {
8133
+ this.logger.debug?.({ root: candidate.root, err: error.message }, "Request root remains retained");
8134
+ // Failed or busy candidates stay retained and reopen only while their exact root still exists.
8135
+ if (epoch && box.requestContext(candidate.root))
8136
+ try {
8137
+ modes.drain.release(candidate.root, epoch);
8138
+ }
8139
+ catch { /* still fenced, never guessed open */ }
8140
+ }
8141
+ finally {
8142
+ this.requestContextRetirementProofs.delete(candidate.root);
8143
+ }
8144
+ }
8145
+ }
8146
+ scheduleRequestContextDrain() {
8147
+ if (this.requestContextDrainTimer || this.shuttingDown)
8148
+ return;
8149
+ this.requestContextDrainTimer = setTimeout(() => {
8150
+ this.requestContextDrainTimer = undefined;
8151
+ const modes = this.requestContextModes, state = this.deliveryOutbox?.requestContextInstallation().read();
8152
+ if (!modes?.current() || !state || state.mode !== "draining")
8153
+ return;
8154
+ try {
8155
+ modes.off.advance(state.revision);
8156
+ }
8157
+ catch (error) {
8158
+ this.logger.warn({ err: error.message }, "Request-context drain remains held");
8159
+ }
8160
+ this.requestContextControl?.changed();
8161
+ if (this.deliveryOutbox?.requestContextInstallation().read()?.mode === "draining")
8162
+ this.scheduleRequestContextDrain();
8163
+ }, 500);
8164
+ this.requestContextDrainTimer.unref?.();
8165
+ }
8166
+ async resolveRequestContextBlocker(blocker, actor, current) {
8167
+ const box = this.deliveryOutbox, modes = this.requestContextModes, state = box?.requestContextInstallation().read();
8168
+ if (!box || !modes?.current() || state?.mode !== "draining" || !current())
8169
+ throw Error("stale");
8170
+ const inventory = box.requestContextControlInventory(box.requestContextInstallation().drainRoots());
8171
+ if (blocker.id.startsWith("ticket:")) {
8172
+ if (!actor.person || !this.requestContactCardsPort)
8173
+ throw Error("owner-required");
8174
+ const id = blocker.id.slice(7), principal = { person: actor.person, binding: actor.binding, verified: true, current };
8175
+ const card = this.requestContactCardsPort.read(id, principal);
8176
+ actor.execution.mutate(() => this.requestContactCardsPort.decide(id, { snapshot: card.snapshot, decision: "decline" }, principal));
8177
+ }
8178
+ else if (blocker.id.startsWith("delivery:")) {
8179
+ const id = blocker.id.slice(9), row = box.get(id);
8180
+ if (!inventory.deliveries.some(value => value.id === id) || !row)
8181
+ throw Error("stale");
8182
+ actor.execution.mutate(() => box.withdrawRequestContextDelivery(id, requestContextDigest(row), current));
8183
+ }
8184
+ else if (blocker.id.startsWith("return:")) {
8185
+ const id = blocker.id.slice(7), row = inventory.returns.find(value => value.requestDeliveryId === id);
8186
+ if (!row)
8187
+ throw Error("stale");
8188
+ actor.execution.mutate(() => box.closeRequestContextReturn(id, requestContextDigest(row), getLocale() === "zh-TW" ? "擁有者已結束這次等候;不再等候這則回覆。" : "The owner stopped waiting for this reply.", () => current() && this.contactGeneration(row.requester.instance) === row.requester.incarnation));
8189
+ this.scheduleDeliveryOutboxPump();
8190
+ }
8191
+ else if (blocker.id.startsWith("recovery:")) {
8192
+ const row = inventory.recoveries.find(value => `recovery:${requestContextDigest(value.pointer)}` === blocker.id);
8193
+ if (!row)
8194
+ throw Error("stale");
8195
+ await this.stopRequestContextWork(row.root, actor, current);
8196
+ actor.execution.mutate(() => box.requestContextRecovery.clear(row.pointer, () => current() && modes.drain.inspectWork(row.root).blockers.every(value => value === "recovery-pointer")));
8197
+ }
8198
+ else
8199
+ throw Error("invalid-request");
8200
+ this.scheduleRequestContextDrain();
8201
+ }
8202
+ async stopRequestContextWork(root, actor, current) {
8203
+ const modes = this.requestContextModes;
8204
+ if (!modes?.current() || !current())
8205
+ throw Error("stale");
8206
+ const nativeStops = this.fleetWindowsRuntime?.requestContextStops(root) ?? [];
8207
+ for (const stop of nativeStops) {
8208
+ if (!current())
8209
+ throw Error("stale");
8210
+ actor.execution.mutate(() => stop.stop(current));
8211
+ }
8212
+ for (const [name, daemon] of [...this.daemons]) {
8213
+ if (daemon.requestContextTurnSnapshot()?.context.ref.rootContextId !== root)
8214
+ continue;
8215
+ const retirement = await daemon.captureRequestContextRetirement();
8216
+ if (!current() || this.daemons.get(name) !== daemon)
8217
+ throw Error("stale");
8218
+ await actor.execution.stopTarget(name, advance => this.lifecycle.stopIfCurrent(name, daemon, advance));
8219
+ if (!current() || !await retirement.retired())
8220
+ throw Error("unavailable");
8221
+ // The future-start factory keeps the stored work/context; it removes only this positively retired live owner.
8222
+ if (!this.requestContextRetireOwner)
8223
+ throw Error("unavailable");
8224
+ await this.requestContextRetireOwner(name, daemon, retirement.retired);
8225
+ }
8226
+ // The wait bounds the HTTP action; only the owned run's positive completion can clear its pointer.
8227
+ const until = performance.now() + 30_000;
8228
+ while (nativeStops.some(stop => !stop.retired())) {
8229
+ if (!current())
8230
+ throw Error("stale");
8231
+ if (performance.now() >= until)
8232
+ throw Error("unavailable");
8233
+ await new Promise(resolve => setTimeout(resolve, 25));
8234
+ }
8235
+ }
8236
+ async requestContextOwnerStopped(name, daemon, retired) {
8237
+ if (!this.requestContextRetireOwner)
8238
+ return;
8239
+ if (await retired())
8240
+ await this.requestContextRetireOwner(name, daemon, retired);
8241
+ else
8242
+ this.logger.warn({ name }, "Stopped request owner remains held until launch and IPC retirement are proven");
8243
+ }
8244
+ requestContextRetireOwner;
8245
+ requestContextControlPrincipal(req, url) {
8246
+ const resolve = () => {
8247
+ const verdict = evaluateWebRequest(req, url, this.webToken, this.webSessions, { touch: false });
8248
+ if (verdict.kind === "reject" && (verdict.reason === "csrf" || verdict.reason === "cross-site"))
8249
+ throw Error(verdict.reason);
8250
+ if (verdict.kind !== "allow" || verdict.via !== "session" || verdict.session.tier !== "admin")
8251
+ return null;
8252
+ if (hostSessionHere(verdict.session, req))
8253
+ return { binding: requestContextDigest(["host-here", verdict.session.handle, verdict.session.tokenEpoch]), verified: true, person: { platform: "host", adapterId: "host", userId: "operator", label: "Operator" } };
8254
+ const contact = this.requestContactPrincipal(req, url);
8255
+ if (!contact || !contact.current() || (contact.person.platform === "host" ? !this.isWebOnlyFleet() : this.adminGate(contact.person.userId, contact.person.adapterId) !== "ok"))
8256
+ return null;
8257
+ return { binding: requestContextDigest([contact.binding, contact.person.platform, contact.person.userId]), verified: contact.verified, person: contact.person };
8258
+ };
8259
+ const first = resolve();
8260
+ if (!first)
8261
+ return null;
8262
+ return Object.freeze({ ...first, current: () => { try {
8263
+ const now = resolve();
8264
+ return !!now && now.binding === first.binding && now.verified === first.verified;
8265
+ }
8266
+ catch {
8267
+ return false;
8268
+ } } });
8269
+ }
6916
8270
  requestContactPrincipal(req, url) {
6917
8271
  const resolve = () => {
6918
8272
  const verdict = evaluateWebRequest(req, url, this.webToken, this.webSessions, { touch: false });
@@ -6924,7 +8278,7 @@ export class FleetManager {
6924
8278
  if (!identity)
6925
8279
  return null;
6926
8280
  const authority = this.webAuthority({ session: verdict.session, gateway: !!gatewayRequestContext(req), peer: gatewayRequestContext(req) ? gatewayRequestContext(req).named ? "named_link" : "quick_link" : classifyWebPeer(req) }).authority;
6927
- const action = this.contactActor(req, url), person = { platform: identity.platform, adapterId: identity.adapter_id, userId: identity.user_id, label: identity.user_id };
8281
+ const action = this.contactActor(req, url), person = { platform: identity.platform, adapterId: identity.adapter_id, userId: identity.user_id, label: this.contactPersonLabel(identity.adapter_id, identity.user_id) };
6928
8282
  const verified = !!action && sameContactPerson(action, person);
6929
8283
  const binding = JSON.stringify([identity.session_handle, authority.authority_epoch, authority.kind === "web-verified" ? authority.session?.authorized_at : null]);
6930
8284
  return { person, binding, verified };
@@ -6947,14 +8301,236 @@ export class FleetManager {
6947
8301
  */
6948
8302
  requestContactCardsPort = null;
6949
8303
  installRequestContactCards(cards) { this.requestContactCardsPort = cards; }
8304
+ /** Only a validated accepted room can supply a current room-policy override. Unknown recovery is not a Free-room proof. */
8305
+ requestContextSourceRoomRestricted(root) {
8306
+ try {
8307
+ if (!["free-room", "restricted-room"].includes(root.ingress))
8308
+ return undefined;
8309
+ const id = /^human:hmsg-([a-f0-9-]{36})$/.exec(root.rootEvidenceRef)?.[1];
8310
+ if (!id)
8311
+ return undefined;
8312
+ const captured = this.deliveryOutbox?.requestContextHumans.read(id);
8313
+ if (!captured || requestContextDigest(captured.context) !== requestContextDigest(root))
8314
+ return undefined;
8315
+ const basis = this.deliveryOutbox.requestContextHumans.classicBasis(id);
8316
+ if (!basis && (captured.route.kind !== "web" || root.initiatingActor.kind === "unknown"))
8317
+ return undefined;
8318
+ const room = this.contactRoom(root.source.instance);
8319
+ return room ? room.restrictedMode === true : undefined;
8320
+ }
8321
+ catch {
8322
+ return undefined;
8323
+ }
8324
+ }
8325
+ /** Re-run the original synchronous admission basis. It supplies no role or go-ahead authority. */
8326
+ requestContextNativeAdmissionCurrent(context) {
8327
+ try {
8328
+ const root = this.deliveryOutbox?.requestContext(context.ref.rootContextId);
8329
+ if (!root)
8330
+ return false;
8331
+ const source = root.source.instance, room = this.contactRoom(source);
8332
+ if (!Object.hasOwn(this.fleetConfig?.instances ?? {}, source) && !room && !this.daemons?.has(source))
8333
+ return false;
8334
+ if (this.contactGeneration(source) !== root.source.incarnation)
8335
+ return false;
8336
+ if ("platform" in root.initiatingActor && root.initiatingActor.platform === "hub")
8337
+ return true; // Hub's owning current-share/resource check is separate.
8338
+ const match = /^human:hmsg-([a-f0-9-]{36})$/.exec(root.rootEvidenceRef);
8339
+ // Unproved recovery has no human route to borrow. An actual unknown web input must still
8340
+ // recheck its own session below; being unidentified is never a session-revocation bypass.
8341
+ if (!match)
8342
+ return root.initiatingActor.kind === "unknown" && root.ingress !== "owner";
8343
+ if (root.initiatingActor.kind !== "person" && root.initiatingActor.kind !== "unknown")
8344
+ return false;
8345
+ const captured = this.deliveryOutbox.requestContextHumans.read(match[1]);
8346
+ if (!captured || requestContextDigest(captured.context) !== requestContextDigest(root))
8347
+ return false;
8348
+ const actor = root.initiatingActor;
8349
+ if (captured.route.kind === "web") {
8350
+ const session = captured.route.sessionHandle ? this.webSessions?.findByHandle(captured.route.sessionHandle) : null;
8351
+ if (!session || !this.webToken || !this.webSessions?.isCurrent(session, tokenEpoch(this.webToken)))
8352
+ return false;
8353
+ if (actor.kind === "person") {
8354
+ const identity = this.webSessionIdentity(session);
8355
+ if (!identity || identity.platform !== actor.platform || identity.user_id !== actor.userId)
8356
+ return false;
8357
+ }
8358
+ return root.ingress === "guest" ? session.tier === "guest" && !!session.owner && this.fleetConfig?.web?.guests?.enabled === true && this.guestScope(session.owner).has(source) : session.tier === "admin";
8359
+ }
8360
+ if (actor.kind !== "person")
8361
+ return false;
8362
+ const basis = this.deliveryOutbox.requestContextHumans.classicBasis(match[1]);
8363
+ if (basis) {
8364
+ if (!room || room.channelId !== basis.roomId || (room.adapterId ?? this.contactAdapter(source)?.id) !== basis.adapterId || !this.classicChannels?.isClassicChannel(basis.roomId, basis.adapterId))
8365
+ return false;
8366
+ // These are messages inside a registered room. Guild/group/user allowlists gate creation,
8367
+ // and Classic admins may bypass them; applying those lists here would tighten Free rooms.
8368
+ return this.classicChannels.getInstanceByChannel(basis.roomId, basis.adapterId) === source;
8369
+ }
8370
+ if (room)
8371
+ return false; // No historical guild/group/user basis means no guessed Classic admission.
8372
+ if (actor.platform === "host")
8373
+ return false; // Host identity is admitted only through its bound web session.
8374
+ const adapter = this.contactAdapter(source);
8375
+ if (!adapter || adapter.type !== actor.platform)
8376
+ return false;
8377
+ const person = { platform: actor.platform, adapterId: adapter.id, userId: actor.userId, label: actor.userId };
8378
+ if (this.contactAdminOf(source, person))
8379
+ return true;
8380
+ const access = this.worlds.get(adapter.id)?.accessManager ?? (adapter.id === this.getPrimaryAdapterId() ? this.accessManager : null);
8381
+ return access?.isAllowed(actor.userId) === true;
8382
+ }
8383
+ catch {
8384
+ return false;
8385
+ }
8386
+ }
8387
+ /** Off preserves the owner's current Hub contact setting. Elapsed contact-window time grants nothing. */
8388
+ requestContextHubOwnerAllowsContact(context) {
8389
+ try {
8390
+ const root = this.deliveryOutbox?.requestContext(context.ref.rootContextId), actor = root?.initiatingActor;
8391
+ if (!root || root.ingress !== "hub" || !actor || !("platform" in actor) || actor.platform !== "hub" || this.contactGeneration(root.source.instance) !== root.source.incarnation
8392
+ || this.hubMemberPairingApi?.boundHub()?.hubId !== actor.hubId)
8393
+ return false;
8394
+ const view = this.hubMemberExposureApi?.list().find(row => row.agent === root.source.instance);
8395
+ return view?.state === "published" && view.enforceable && !view.reason && view.contactLimit === false;
8396
+ }
8397
+ catch {
8398
+ return false;
8399
+ }
8400
+ }
8401
+ /** Only the receipt's original registered C parent may cross the Draining gate. */
8402
+ requestContextHumanContinuation(instance, receiptId) {
8403
+ const boot = this.requestContextBoot, box = this.deliveryOutbox, daemon = this.daemons.get(instance);
8404
+ if (!boot || !box || !daemon)
8405
+ return;
8406
+ const accepted = box.requestContextHumans.read(receiptId), mapped = accepted?.steer, owner = daemon.captureRequestContextOwner();
8407
+ if (!accepted || !mapped || !owner || owner.workGeneration !== mapped.workGeneration)
8408
+ return;
8409
+ const actor = mapped.actor;
8410
+ if (actor.kind !== "person" || actor.platform === "hub")
8411
+ throw Error("Steer continuation actor unavailable");
8412
+ const valid = () => {
8413
+ try {
8414
+ const live = box.getHumanReceipt(receiptId), actual = daemon.captureRequestContextOwner(), parent = box.requestContext(mapped.parentContextId);
8415
+ const adapter = actor.platform === "host" ? "host" : this.contactAdapter(instance)?.id;
8416
+ return this.requestContextBoot === boot && this.deliveryOutbox === box && this.daemons.get(instance) === daemon && !this.shuttingDown
8417
+ && requestContextDigest(actual) === requestContextDigest(owner) && !!parent && requestContextDigest(parent) === mapped.parentSha256
8418
+ && !!live && live.state === "queued" && live.target_instance === instance && live.manager_boot_id === this.managerBootId
8419
+ && (live.owner_key === null || live.owner_key === this.humanReceiptOwner(instance, daemon))
8420
+ && !!adapter && this.contactAdminOf(instance, { platform: actor.platform, adapterId: adapter, userId: actor.userId, label: actor.userId })
8421
+ && this.requestContextNativeAdmissionCurrent(accepted.context);
8422
+ }
8423
+ catch {
8424
+ return false;
8425
+ }
8426
+ };
8427
+ if (!valid())
8428
+ throw Error("Steer continuation owner changed");
8429
+ return boot.publication.continuation(mapped.rootContextId, valid);
8430
+ }
8431
+ /** One installed gate host for direct sends and same-card decisions. No lifetime origin or return-release lookup.
8432
+ * Currentness belongs to the installation/process, not a browser, transport-readiness poll or old Hub timer.
8433
+ */
8434
+ makeRequestContextContactHost(current, rootRetired, mode) {
8435
+ const incarnation = (name) => { try {
8436
+ return current() ? this.contactGeneration(name) : null;
8437
+ }
8438
+ catch {
8439
+ return null;
8440
+ } };
8441
+ const person = (actor) => {
8442
+ if (actor.kind !== "person" || actor.platform === "hub")
8443
+ return null;
8444
+ if (actor.platform === "host")
8445
+ return actor.userId === "operator" ? { platform: "host", adapterId: "host", userId: "operator", label: "Operator" } : null;
8446
+ const adapter = [...this.adapters.values(), ...[...this.worlds.values()].map(world => world.adapter)].find(row => row.type === actor.platform);
8447
+ const configured = (this.fleetConfig?.channels ?? (this.fleetConfig?.channel ? [this.fleetConfig.channel] : [])).find(row => row.type === actor.platform);
8448
+ const adapterId = adapter?.id ?? configured?.id ?? configured?.type;
8449
+ return adapterId ? { platform: actor.platform, adapterId, userId: actor.userId, label: actor.displayName ?? actor.userId } : null;
8450
+ };
8451
+ const manage = (name, actor) => current() && incarnation(name) !== null && this.contactAdminOf(name, actor);
8452
+ return {
8453
+ incarnation, person, adminOf: manage, canManage: manage,
8454
+ canDecide: (name, actor) => {
8455
+ if (!manage(name, actor))
8456
+ return false;
8457
+ const policy = this.deliveryOutbox.contactAuthorizations.policySnapshot(name, incarnation(name));
8458
+ return actor.platform === "host" && actor.userId === "operator" || (policy.approvers ?? this.contactDefaultApprovers(name)).some(value => sameContactPerson(value, actor));
8459
+ },
8460
+ current: (context, binding) => current() && incarnation(binding.source.instance) === binding.source.incarnation
8461
+ && incarnation(binding.target.instance) === binding.target.incarnation && this.requestContextNativeAdmissionCurrent(context),
8462
+ sourceRestricted: root => this.requestContextSourceRoomRestricted(root),
8463
+ rootRetired: root => current() && rootRetired(root),
8464
+ hubRelayAllowed: (context, binding, delivery) => {
8465
+ if (!current() || !assertRequestHubContactImage(context, binding, delivery))
8466
+ return false;
8467
+ const installed = mode();
8468
+ return installed === "active" || installed === "draining" || installed === "off" && this.requestContextHubOwnerAllowsContact(context);
8469
+ },
8470
+ accepted: () => { this.scheduleDeliveryOutboxPump(); this.needsYou?.poke(); },
8471
+ };
8472
+ }
8473
+ /** One publication owns every live ingress. These forwarding ports never cache a mode, owner or current turn. */
8474
+ requestContactApi;
8475
+ bindRequestContextServingPublication(boot) {
8476
+ if (this.requestContextBoot !== boot || this.requestContextAdmission !== boot.publication.admission)
8477
+ throw Error("Request serving publication owner differs");
8478
+ const serving = (execution = false) => {
8479
+ if (this.requestContextBoot !== boot || this.requestContextAdmission !== boot.publication.admission)
8480
+ throw Error("Request serving publication changed");
8481
+ const publication = execution ? boot.publication.captureExecution() : boot.publication.capture();
8482
+ const ports = publication?.ports.serving;
8483
+ if (!ports || !ports.current())
8484
+ throw Error("Request serving publication unavailable");
8485
+ return ports;
8486
+ };
8487
+ this.requestContextPolicy = boot.policy;
8488
+ this.requestContextRelay = { admit: (input, operation, current) => serving(operation.admission?.coverage === "covered").relay.admit(input, operation, current) };
8489
+ // Record-only identity admission is not a pane write. New input still waits at the shared gate.
8490
+ this.requestContextHumanAdmission = (...args) => boot.publication.heldUnpublished() && this.requestContextModes?.current() ? this.requestContextModes.recordHuman(...args) : serving(true).human(...args);
8491
+ this.requestContextHubAdmission = input => serving().hub(input);
8492
+ this.requestContactApi = {
8493
+ principal: (req, url) => this.requestContactPrincipal(req, url), permitContinuation: (req, res) => permitWebContinuation(req, res, { webToken: this.webToken, webSessions: this.webSessions }),
8494
+ needs: actor => serving(true).api.needs?.(actor) ?? [], canRead: (card, actor) => serving(true).api.canRead(card, actor),
8495
+ read: (id, actor) => serving(true).api.read(id, actor), list: (filter, actor) => serving(true).api.list(filter, actor), decide: (id, input, actor) => serving(true).api.decide(id, input, actor),
8496
+ };
8497
+ this.requestContactCardsPort = {
8498
+ canRead: (card, actor) => serving(true).cards.canRead(card, actor), read: (id, actor) => serving(true).cards.read(id, actor),
8499
+ needs: actor => serving(true).cards.needs(actor), list: (filter, actor) => serving(true).cards.list(filter, actor),
8500
+ decide: (id, input, actor) => serving(true).cards.decide(id, input, actor), prepareForNativePost: (id, current) => serving(true).cards.prepareForNativePost(id, current),
8501
+ };
8502
+ }
8503
+ /** Construct only inside the capable activation initializer or capable boot. Nothing is published here. */
8504
+ prepareRequestContextServingOwners(current, rootRetired, resolveHub, mode) {
8505
+ const box = this.deliveryOutbox;
8506
+ if (!box || !current())
8507
+ throw Error("Request-context serving owner unavailable");
8508
+ const host = this.makeRequestContextContactHost(current, rootRetired, mode), gate = box.requestHubContactGate(host);
8509
+ const relay = makeRequestContextRelay(box, host, gate), cards = this.makeRequestContactCards(host, gate), api = this.makeRequestContactApi(cards);
8510
+ const human = this.makeRequestContextHumanAdmission(), hub = this.makeRequestContextHubAdmission(resolveHub), policy = this.makeRequestContextPolicy();
8511
+ const admitted = { admit: (...args) => {
8512
+ if (!current())
8513
+ throw new RequestContextPolicyError("stale");
8514
+ try {
8515
+ return relay.admit(...args);
8516
+ }
8517
+ catch (error) {
8518
+ if (error instanceof ContactHeldError)
8519
+ this.contactService().host.changed?.(args[0].targetInstance, error.result.authorization_id);
8520
+ throw error;
8521
+ }
8522
+ } };
8523
+ return Object.freeze({ policy, relay: admitted, cards, api, human, hub, gate, current });
8524
+ }
6950
8525
  /** Dormant assembly for L and synthetic rigs; merely defining this method installs no service or route authority. */
6951
- makeRequestContactCards() {
8526
+ makeRequestContactCards(gateHost, gate) {
6952
8527
  this.ensureDeliveryOutbox();
6953
8528
  const outbox = this.deliveryOutbox, legacy = this.contactService();
6954
8529
  const names = () => [...new Set([...Object.keys(this.fleetConfig?.instances ?? {}), ...(this.classicChannels?.getAll() ?? []).map(room => room.instanceName)])].sort();
6955
8530
  const manage = (name, person) => this.contactAdminOf(name, person);
6956
8531
  const cards = outbox.requestContactCards({
6957
- current: (_context, binding) => this.contactGeneration(binding.source.instance) === binding.source.incarnation && this.contactGeneration(binding.target.instance) === binding.target.incarnation && !this.hubContactRestricted(binding.source.instance),
8532
+ current: (context, binding) => this.contactGeneration(binding.source.instance) === binding.source.incarnation && this.contactGeneration(binding.target.instance) === binding.target.incarnation
8533
+ && (!requestContextPolicyInstalled(this.requestContextPolicy) || this.requestContextNativeAdmissionCurrent(context)) && !this.hubContactRestricted(binding.source.instance),
6958
8534
  generation: name => { try {
6959
8535
  return this.contactGeneration(name);
6960
8536
  }
@@ -6964,6 +8540,7 @@ export class FleetManager {
6964
8540
  canManage: manage, canDecide: (name, person) => { if (!manage(name, person))
6965
8541
  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)); },
6966
8542
  adminOf: (name, person) => this.contactAdminOf(name, person),
8543
+ sourceRestricted: root => this.requestContextSourceRoomRestricted(root),
6967
8544
  person: actor => {
6968
8545
  if (actor.kind !== "person" || actor.platform === "hub")
6969
8546
  return null;
@@ -6993,11 +8570,12 @@ export class FleetManager {
6993
8570
  }
6994
8571
  this.needsYou?.poke();
6995
8572
  },
6996
- });
8573
+ ...gateHost,
8574
+ }, gate);
6997
8575
  return cards;
6998
8576
  }
6999
- makeRequestContactApi() {
7000
- const cards = this.makeRequestContactCards();
8577
+ makeRequestContactApi(given) {
8578
+ const cards = given ?? this.makeRequestContactCards();
7001
8579
  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) };
7002
8580
  }
7003
8581
  contactActor(req, url) {
@@ -7014,7 +8592,21 @@ export class FleetManager {
7014
8592
  const adapter = this.adapters.get(actor.adapter_id);
7015
8593
  if (!adapter || (adapter.type !== "discord" && adapter.type !== "telegram"))
7016
8594
  return null;
7017
- return { platform: adapter.type, adapterId: actor.adapter_id, userId: actor.user_id, label: actor.user_id };
8595
+ return { platform: adapter.type, adapterId: actor.adapter_id, userId: actor.user_id, label: this.contactPersonLabel(actor.adapter_id, actor.user_id) };
8596
+ }
8597
+ /**
8598
+ * M-3864 R7: what Permissions and the history call a web-verified admin. That is their name as the rest of the dashboard
8599
+ * says it (their own, else their chat account's), never the bare account id. Display only: a person is matched by
8600
+ * platform and id (sameContactPerson).
8601
+ */
8602
+ contactPersonLabel(adapterId, userId) {
8603
+ try {
8604
+ const name = this.webPerson({ adapterId, userId }).name;
8605
+ return name && name !== WEB_NAME_FALLBACK ? name : userId;
8606
+ }
8607
+ catch {
8608
+ return userId;
8609
+ }
7018
8610
  }
7019
8611
  writeContactPermissions(name, raw, actor) {
7020
8612
  const parsed = ContactPermissionsSchema.safeParse(raw);
@@ -7530,15 +9122,25 @@ export class FleetManager {
7530
9122
  return;
7531
9123
  try {
7532
9124
  outbox.contactAuthorizations.notifyOutcomes((ticket, outcome) => {
9125
+ const notify = (key, text) => {
9126
+ if (ticket.requestContext) {
9127
+ const context = outbox.requestContext(ticket.requestContext.contextId);
9128
+ if (!context || context.source.instance !== ticket.source)
9129
+ throw Error("Contact outcome context unavailable");
9130
+ outbox.admitRequestContextOutcome(context.ref.contextId, key, text, () => !this.shuttingDown && this.contactGeneration(ticket.source) === context.source.incarnation);
9131
+ }
9132
+ else
9133
+ outbox.admitSystemNotice(ticket.source, key, text);
9134
+ };
7533
9135
  if (outcome === "declined" || outcome === "expired") {
7534
- outbox.admitSystemNotice(ticket.source, `contact-outcome:${ticket.id}`, t(outcome === "declined" ? "contact.noticeDeclined" : "contact.noticeExpired", ticket.id, ticket.target));
9136
+ notify(`contact-outcome:${ticket.id}`, t(outcome === "declined" ? "contact.noticeDeclined" : "contact.noticeExpired", ticket.id, ticket.target));
7535
9137
  return;
7536
9138
  }
7537
9139
  // M-3716 (the user, 11-25): the requester learns who approved it, when, and whether the target has it.
7538
9140
  const by = ticket.decidedBy, when = ticket.decidedAt ? `${ticket.decidedAt.slice(0, 16).replace("T", " ")} UTC` : "";
7539
9141
  const who = !by ? "?" : by.platform === "host" ? t("contactProposal.host")
7540
9142
  : `${by.label}${getLocale() === "zh-TW" ? "(" : " ("}${by.platform === "discord" ? "Discord" : "Telegram"}${getLocale() === "zh-TW" ? ")" : ")"}`;
7541
- outbox.admitSystemNotice(ticket.source, `contact-approval:${ticket.id}`, t(`contact.noticeApproved_${outcome}`, shortContactTicketId(ticket.id), ticket.target, who, when));
9143
+ notify(`contact-approval:${ticket.id}`, t(`contact.noticeApproved_${outcome}`, shortContactTicketId(ticket.id), ticket.target, who, when));
7542
9144
  }, ticket => ticket.deliveryId ? outbox.get(ticket.deliveryId)?.state : undefined);
7543
9145
  }
7544
9146
  catch (err) {
@@ -8036,12 +9638,51 @@ export class FleetManager {
8036
9638
  }, Math.max(0, delayMs));
8037
9639
  this.deliveryPumpTimer.unref?.();
8038
9640
  }
9641
+ /** Only B-validated deliveries can pass Draining; a legacy row or a body root id cannot. */
9642
+ requestContextDeliveryContinuation(row) {
9643
+ const boot = this.requestContextBoot, box = this.deliveryOutbox;
9644
+ if (!boot || !box)
9645
+ return null;
9646
+ const owned = () => !this.shuttingDown && this.deliveryOutbox === box && this.requestContextBoot === boot && this.contactDeliveryCurrent(row);
9647
+ const bound = requestDeliveryContinuation(box, boot.publication, row, owned);
9648
+ if (bound)
9649
+ return bound;
9650
+ // An untouched queued human control uses its receipt's registered parent, never a legacy operation's speaker.
9651
+ const meta = row.payload.meta, id = meta?.human_receipt_id;
9652
+ if (row.kind !== "human_control" || row.sourceInstance !== "agend-system" || typeof id !== "string" || row.sourceKey !== `human-control:${id}`
9653
+ || row.operationId !== row.sourceKey || meta?.verification_id !== `hmsg-${id}`)
9654
+ return null;
9655
+ const parent = this.requestContextHumanContinuation(row.targetInstance, id);
9656
+ if (!parent)
9657
+ return null;
9658
+ const image = requestContextDigest(row), current = () => {
9659
+ try {
9660
+ const actual = box.get(row.deliveryId);
9661
+ return owned() && parent.current() && !!actual
9662
+ && ["queued", "delivering"].includes(actual.state) && requestContextDigest(actual) === image;
9663
+ }
9664
+ catch {
9665
+ return false;
9666
+ }
9667
+ };
9668
+ if (!current())
9669
+ throw Error("Retained steer continuation changed");
9670
+ return boot.publication.continuation(parent.rootContextId, current);
9671
+ }
9672
+ requestContextDeliveryAdmissionAllowed(row) {
9673
+ try {
9674
+ return this.requestContextAdmission?.available(this.requestContextDeliveryContinuation(row) ?? undefined) !== false;
9675
+ }
9676
+ catch {
9677
+ return false;
9678
+ }
9679
+ }
8039
9680
  async runDeliveryOutboxPump() {
8040
9681
  const outbox = this.deliveryOutbox;
8041
9682
  // A closed database is never queried: this runs from timers, where a throw
8042
9683
  // is an unhandled rejection. Checking here covers the finally block too:
8043
9684
  // the body below never awaits, so the database cannot close in between.
8044
- if (!outbox || this.shuttingDown || this.deliveryPumpRunning || !outbox.isOpen)
9685
+ if (!outbox || this.shuttingDown || this.deliveryPumpRunning || !outbox.isOpen || (this.requestContextAdmission?.dispatchAvailable?.() ?? this.requestContextAdmission?.available()) === false)
8045
9686
  return;
8046
9687
  this.deliveryPumpRunning = true;
8047
9688
  this.deliveryPumpScheduled = false;
@@ -8067,7 +9708,7 @@ export class FleetManager {
8067
9708
  // Phase 2c: a lane a queue worker owns is never claimed here.
8068
9709
  target => this.queueWorkers.has(target) || this.isInstanceRestarting(target) || this.wakeCoordinator?.blocksClaim(target)
8069
9710
  ? null
8070
- : this.deliveryBootId(target), this.activeDurableTargets, row => this.recoveryDeliveryEligible(row));
9711
+ : this.deliveryBootId(target), this.activeDurableTargets, row => this.recoveryDeliveryEligible(row) && (this.requestContextAdmission?.available() !== false || this.requestContextDeliveryAdmissionAllowed(row)));
8071
9712
  if (!claimed)
8072
9713
  break;
8073
9714
  this.activeDurableTargets.add(claimed.targetInstance);
@@ -8126,10 +9767,10 @@ export class FleetManager {
8126
9767
  const worker = new TargetQueueWorker(target, {
8127
9768
  owns: () => this.queueWorkers.get(target) === worker,
8128
9769
  wanted: () => this.deliveryWorkerMode(target) === "on",
8129
- available: () => !this.shuttingDown && this.deliveryOutbox?.isOpen === true,
9770
+ available: () => !this.shuttingDown && this.deliveryOutbox?.isOpen === true && (this.requestContextAdmission?.dispatchAvailable?.() ?? this.requestContextAdmission?.available()) !== false,
8130
9771
  blocked: () => this.isInstanceRestarting(target) || this.wakeCoordinator?.blocksClaim(target) === true,
8131
9772
  daemonBootId: () => this.deliveryBootId(target),
8132
- claim: bootId => this.deliveryOutbox?.claimNext(this.managerBootId, candidate => candidate === target ? bootId : null, new Set(), row => this.recoveryDeliveryEligible(row)),
9773
+ claim: bootId => (this.requestContextAdmission?.dispatchAvailable?.() ?? this.requestContextAdmission?.available()) === false ? undefined : this.deliveryOutbox?.claimNext(this.managerBootId, candidate => candidate === target ? bootId : null, new Set(), row => this.recoveryDeliveryEligible(row) && (this.requestContextAdmission?.available() !== false || this.requestContextDeliveryAdmissionAllowed(row))),
8133
9774
  tryAcquireBudget: () => {
8134
9775
  if (this.activeDurableTargets.size >= 8)
8135
9776
  return false;
@@ -8163,6 +9804,7 @@ export class FleetManager {
8163
9804
  await this.dispatchNativeDurableDelivery(claimed);
8164
9805
  return;
8165
9806
  }
9807
+ const humanControl = claimed.kind === "human_control";
8166
9808
  const target = claimed.targetInstance;
8167
9809
  const attempt = claimed.attemptNo;
8168
9810
  const payload = { ...claimed.payload };
@@ -8173,6 +9815,8 @@ export class FleetManager {
8173
9815
  // Arm the visible liveness alert as soon as this generation owns the lane,
8174
9816
  // including time spent waiting for a handoff/idle gate to return.
8175
9817
  try {
9818
+ if (humanControl && (claimed.sourceInstance !== "agend-system" || claimed.sourceKey !== claimed.operationId || !claimed.sourceKey.startsWith("human-control:")))
9819
+ throw Error("Invalid retained human control");
8176
9820
  let sent;
8177
9821
  if (claimed.kind === WORKING_RECOVERY_KIND) {
8178
9822
  const daemon = this.daemons.get(target), key = claimed.sourceKey.replace(/^working-recovery:/, "");
@@ -8223,15 +9867,24 @@ export class FleetManager {
8223
9867
  ...rawMeta,
8224
9868
  delivery_id: claimed.deliveryId,
8225
9869
  delivery_attempt: String(claimed.attemptNo),
8226
- from_instance: typeof rawMeta.from_instance === "string" && rawMeta.from_instance
8227
- ? rawMeta.from_instance
8228
- : claimed.sourceInstance,
9870
+ ...(!humanControl ? { from_instance: typeof rawMeta.from_instance === "string" && rawMeta.from_instance
9871
+ ? rawMeta.from_instance : claimed.sourceInstance } : {}),
8229
9872
  correlation_id: claimed.correlationId ?? String(rawMeta.correlation_id ?? ""),
8230
9873
  };
9874
+ if (humanControl) {
9875
+ payload.delivery_id = claimed.deliveryId;
9876
+ payload.delivery_attempt = String(claimed.attemptNo);
9877
+ markRetainedHumanControl(payload, claimed);
9878
+ }
9879
+ if (this.requestContextBoot) {
9880
+ const proof = this.requestContextDeliveryContinuation(outbox.get(claimed.deliveryId));
9881
+ if (proof)
9882
+ requestPayloadContinuations.set(payload, proof);
9883
+ }
8231
9884
  sent = await this.deliverToInstance(target, payload, {
8232
- isCrossInstance: true,
9885
+ isCrossInstance: !humanControl,
8233
9886
  stillCurrent: () => this.contactDeliveryCurrent(claimed),
8234
- waitForIdle: claimed.kind !== "steer",
9887
+ waitForIdle: !humanControl && claimed.kind !== "steer",
8235
9888
  noInlineWake: this.deliveryWorkerMode(target) !== "off",
8236
9889
  });
8237
9890
  }
@@ -8276,12 +9929,21 @@ export class FleetManager {
8276
9929
  }
8277
9930
  const meta = claimed.payload.meta && typeof claimed.payload.meta === "object" ? claimed.payload.meta : {};
8278
9931
  const task = await this.nativeInstanceRuntime().execute(target, { ...claimed.payload, requestId: deliveryId, meta: { ...meta, from_instance: claimed.sourceInstance, correlation_id: claimed.correlationId } }, {
9932
+ ...(this.requestContextPolicy ? { requestContextInputId: `delivery:${deliveryId}:${attemptNo}` } : {}),
8279
9933
  stillCurrent: () => !this.shuttingDown && this.contactDeliveryCurrent(claimed),
8280
9934
  beforeStart: () => { if (!this.contactDeliveryCurrent(claimed) || outbox.begin(deliveryId, targetDaemonBootId, attemptNo) !== "begun")
8281
9935
  throw new Error("Windows delivery attempt is no longer current"); begun = true; },
8282
9936
  });
8283
9937
  const outcome = task.outcomeConfirmed === false ? "uncertain" : task.status === "completed" ? "delivered" : "failed";
8284
9938
  outbox.complete(deliveryId, targetDaemonBootId, attemptNo, outcome, task.error || task.status);
9939
+ if (this.requestContextPolicy) {
9940
+ if (!this.requestContextRelay)
9941
+ throw Error("Native scoped return admission is unavailable");
9942
+ const completion = this.nativeInstanceRuntime().requestContextCompletion(target, deliveryId, `delivery:${deliveryId}:${attemptNo}`);
9943
+ admitRequestContextNativeResult(outbox, this.requestContextRelay, { deliveryId, task, ...completion });
9944
+ this.scheduleDeliveryOutboxPump();
9945
+ return;
9946
+ }
8285
9947
  // Return a requested peer report when the provider did not explicitly report it through scoped MCP.
8286
9948
  if (meta.requires_reply === "true" && claimed.correlationId && !task.reportedCorrelationIds?.includes(claimed.correlationId) && this.fleetConfig?.instances[claimed.sourceInstance]) {
8287
9949
  const text = (task.status === "completed" ? task.output : `Windows task ${task.status}: ${task.error || task.output}`).slice(0, 8000);
@@ -8315,6 +9977,27 @@ export class FleetManager {
8315
9977
  if (!row || !isNativeExecInstance(this.fleetConfig?.instances[row.targetInstance]) || this.fleetConfig?.instances[row.targetInstance]?.machine_id !== machineId
8316
9978
  || !row.targetDaemonBootId || this.activeDurableTargets.has(row.targetInstance))
8317
9979
  return;
9980
+ if (this.requestContextPolicy) {
9981
+ if (!this.requestContextRelay)
9982
+ throw Error("Native scoped return admission is unavailable");
9983
+ const completion = this.nativeInstanceRuntime().requestContextCompletion(row.targetInstance, row.deliveryId, `delivery:${row.deliveryId}:${row.attemptNo}`);
9984
+ if (!task.execInputProof)
9985
+ throw Error("Native scoped completion has no input proof");
9986
+ // Never let terminal status replace the worker's actual input boundary on a scoped run.
9987
+ validateNativeExecInputProof(task.execInputProof, completion.claim);
9988
+ if (row.state === "submission_started" || row.state === "reconciliation_pending") {
9989
+ if (!outbox.complete(row.deliveryId, row.targetDaemonBootId, row.attemptNo, "delivered", "Owned native input proof recovered"))
9990
+ return;
9991
+ }
9992
+ else if (!["delivered", "uncertain"].includes(row.state))
9993
+ return;
9994
+ if (outbox.markConsumed(row.deliveryId, row.targetDaemonBootId, row.attemptNo, "turn", "Owned native input proof recovered") === "ignored")
9995
+ return;
9996
+ admitRequestContextNativeResult(outbox, this.requestContextRelay, { deliveryId: row.deliveryId, task, ...completion });
9997
+ this.reconciledRemoteResults.add(key);
9998
+ this.scheduleDeliveryOutboxPump();
9999
+ return;
10000
+ }
8318
10001
  if (row.state === "submission_started" || row.state === "reconciliation_pending") {
8319
10002
  if (!outbox.complete(row.deliveryId, row.targetDaemonBootId, row.attemptNo, task.status === "completed" ? "delivered" : "failed", task.error || "Runtime completion recovered after reconnect"))
8320
10003
  return;
@@ -10036,6 +11719,8 @@ export class FleetManager {
10036
11719
  * retry brings it up, however long the backoff, and fails only once the retries give up.
10037
11720
  */
10038
11721
  async sendWhenConnected(instanceName, payload, deliveryEpoch = this.getDeliveryEpoch(instanceName), stillCurrent, onStartRetryHold, beforeInput) {
11722
+ if (this.requestContextAdmission && !await this.requestContextAdmission.wait(() => this.deliveryCurrent(instanceName, deliveryEpoch, stillCurrent), requestPayloadContinuations.get(payload)))
11723
+ return false;
10039
11724
  if (!this.deliveryCurrent(instanceName, deliveryEpoch, stillCurrent))
10040
11725
  return false;
10041
11726
  const queued = this.ipcWaitTails.get(instanceName);
@@ -10044,6 +11729,8 @@ export class FleetManager {
10044
11729
  if (ipc?.connected) {
10045
11730
  if (beforeInput)
10046
11731
  return this.handOffAfterBeforeInput(instanceName, payload, deliveryEpoch, stillCurrent, beforeInput);
11732
+ if (this.requestContextAdmission?.available(requestPayloadContinuations.get(payload)) === false)
11733
+ return this.sendAfterIpcReturns(instanceName, payload, deliveryEpoch, stillCurrent, onStartRetryHold, beforeInput);
10047
11734
  const wire = this.bindHumanReceiptPayload(instanceName, payload);
10048
11735
  if (this.refuseHubPane(wire))
10049
11736
  return false;
@@ -10081,6 +11768,8 @@ export class FleetManager {
10081
11768
  * goes in one attempt. After the intent is spent nothing here retries: false is the caller's uncertain outcome.
10082
11769
  */
10083
11770
  async handOffAfterBeforeInput(instanceName, payload, deliveryEpoch, stillCurrent, beforeInput) {
11771
+ if (this.requestContextAdmission && !await this.requestContextAdmission.wait(() => this.deliveryCurrent(instanceName, deliveryEpoch, stillCurrent), requestPayloadContinuations.get(payload)))
11772
+ return false;
10084
11773
  // The flag is read before beforeInput and before prepareClassicForPerson. A Hub or room row stays
10085
11774
  // queued at its producer: no begin lease, no input intent, and no plaintext copy of the question.
10086
11775
  if (this.refuseHubPane(payload))
@@ -10090,35 +11779,45 @@ export class FleetManager {
10090
11779
  if (this.holdPaneSend(instanceName, early))
10091
11780
  return true;
10092
11781
  }
10093
- if (!(await beforeInput()))
11782
+ const begin = this.requestContextAdmission
11783
+ ? await runWithRequestContextAdmission(this.requestContextAdmission, () => this.deliveryCurrent(instanceName, deliveryEpoch, stillCurrent), beforeInput, requestPayloadContinuations.get(payload))
11784
+ : await beforeInput();
11785
+ if (!begin)
10094
11786
  return false;
10095
11787
  if (this.refuseHubPane(payload))
10096
11788
  return false;
10097
11789
  const privateToken = await this.prepareClassicForPerson(instanceName, payload, deliveryEpoch, stillCurrent);
10098
11790
  if (privateToken === false || this.shuttingDown || !this.deliveryCurrent(instanceName, deliveryEpoch, stillCurrent))
10099
11791
  return false;
10100
- const ipc = this.instanceIpcClients.get(instanceName);
10101
- if (!ipc?.connected || (privateToken && this.classicPrivacy().read(instanceName)?.token !== privateToken))
10102
- return false;
10103
- const wire = this.bindHumanReceiptPayload(instanceName, payload);
10104
- if (this.refuseHubPane(wire))
10105
- return false;
10106
- if (this.holdPaneSend(instanceName, wire))
10107
- return true;
10108
- const sent = ipc.send(wire);
10109
- if (sent && privateToken) {
10110
- try {
10111
- if (this.classicPrivacy().resume(instanceName, privateToken)) {
10112
- this.instanceProgress.delete(instanceName);
10113
- this.instanceActivity.delete(instanceName);
11792
+ const send = () => {
11793
+ if (this.shuttingDown || !this.deliveryCurrent(instanceName, deliveryEpoch, stillCurrent))
11794
+ return false;
11795
+ const ipc = this.instanceIpcClients.get(instanceName);
11796
+ if (!ipc?.connected || (privateToken && this.classicPrivacy().read(instanceName)?.token !== privateToken))
11797
+ return false;
11798
+ const wire = this.bindHumanReceiptPayload(instanceName, payload);
11799
+ if (this.refuseHubPane(wire))
11800
+ return false;
11801
+ if (this.holdPaneSend(instanceName, wire))
11802
+ return true;
11803
+ const sent = ipc.send(wire);
11804
+ if (sent && privateToken) {
11805
+ try {
11806
+ if (this.classicPrivacy().resume(instanceName, privateToken)) {
11807
+ this.instanceProgress.delete(instanceName);
11808
+ this.instanceActivity.delete(instanceName);
11809
+ }
11810
+ }
11811
+ catch (err) {
11812
+ // Input was accepted: never invite a duplicate. Keep output closed if its durable release fails.
11813
+ this.logger.warn({ err, instanceName }, "Classic room output remains private after the person input");
10114
11814
  }
10115
11815
  }
10116
- catch (err) {
10117
- // Input was accepted: never invite a duplicate. Keep output closed if its durable release fails.
10118
- this.logger.warn({ err, instanceName }, "Classic room output remains private after the person input");
10119
- }
10120
- }
10121
- return sent;
11816
+ return sent;
11817
+ };
11818
+ return this.requestContextAdmission
11819
+ ? runWithRequestContextAdmission(this.requestContextAdmission, () => this.deliveryCurrent(instanceName, deliveryEpoch, stillCurrent), send, requestPayloadContinuations.get(payload))
11820
+ : send();
10122
11821
  }
10123
11822
  /** Poll for the instance's IPC to come back, then send. Throws if it does not. */
10124
11823
  async sendAfterIpcReturns(instanceName, payload, deliveryEpoch = this.getDeliveryEpoch(instanceName), stillCurrent, onStartRetryHold, beforeInput) {
@@ -10126,6 +11825,12 @@ export class FleetManager {
10126
11825
  let warned = false;
10127
11826
  let held = false;
10128
11827
  for (;;) {
11828
+ if (this.requestContextAdmission && !this.requestContextAdmission.available(requestPayloadContinuations.get(payload))) {
11829
+ if (!await this.requestContextAdmission.wait(() => this.deliveryCurrent(instanceName, deliveryEpoch, stillCurrent), requestPayloadContinuations.get(payload)))
11830
+ return false;
11831
+ deadline = Date.now() + IPC_RECONNECT_GRACE_MS; // Cutover waiting is not an IPC reconnect timeout.
11832
+ continue;
11833
+ }
10129
11834
  if (!this.deliveryCurrent(instanceName, deliveryEpoch, stillCurrent))
10130
11835
  return false;
10131
11836
  // Re-read every round: a reconnect replaces the IpcClient object entirely,
@@ -10227,7 +11932,19 @@ export class FleetManager {
10227
11932
  * The tool's errors: an emoji outside the web set or one of the instance's delivery marks (web-reactions.ts), or a
10228
11933
  * message the chat does not have. An emoji the message already has is a success that changes nothing.
10229
11934
  */
10230
- async reactToWebMessage(instance, messageId, raw) {
11935
+ async reactToWebMessage(instance, messageId, raw, replyRoute) {
11936
+ if (replyRoute) {
11937
+ if (!replyRoute.current())
11938
+ return { ok: false, error: "Originating request context is no longer current" };
11939
+ const handle = replyRoute.target.webRoute?.sessionHandle;
11940
+ if (handle) {
11941
+ const session = this.webSessions?.findByHandle(handle), row = this.webChatHistory.findByReplyId(instance, messageId);
11942
+ if (!session || !row)
11943
+ return { ok: false, error: `react: ${messageId} is not a message in ${instance}'s web chat now (it left the history, or it is from before AgEnD restarted) — answer with reply instead` };
11944
+ if (session.tier === "guest" && (!session.owner || !guestSeesMessage(row, { owner: session.owner, current: () => replyRoute.current(), scope: () => this.guestScope(session.owner), ownRoom: name => this.guestOwnRoom(session.owner, name) }, this.guestScope(session.owner))))
11945
+ return { ok: false, error: `react: ${messageId} is not a message in ${instance}'s web chat now (it left the history, or it is from before AgEnD restarted) — answer with reply instead` };
11946
+ }
11947
+ }
10231
11948
  const problem = webReactionProblem(raw, this.statusEmojiAvoidList(instance));
10232
11949
  if (problem)
10233
11950
  return { ok: false, error: problem };
@@ -10238,13 +11955,20 @@ export class FleetManager {
10238
11955
  if (!r.added)
10239
11956
  return { ok: true, mirrored: Promise.resolve(0) };
10240
11957
  this.emitSseEvent("reactions", { instance, boot: r.message.boot, id: r.message.id, reactions: r.message.reactions ?? [] });
11958
+ const routeMatches = (copy) => !replyRoute || copy.chatId === replyRoute.target.chatId && (copy.threadId ?? "") === (replyRoute.target.threadId ?? "") && copy.adapterId === replyRoute.target.adapterId;
10241
11959
  const mirrorOne = (copy) => {
11960
+ if (!routeMatches(copy))
11961
+ return Promise.resolve(0);
10242
11962
  let timer;
10243
11963
  const timeout = new Promise((_, reject) => {
10244
11964
  timer = setTimeout(() => reject(new Error(`no answer in ${WEB_MIRROR_TIMEOUT_MS} ms`)), WEB_MIRROR_TIMEOUT_MS);
10245
11965
  timer.unref?.();
10246
11966
  });
10247
- return Promise.race([Promise.resolve().then(() => copy.adapter.react(copy.chatId, copy.messageId, reactionForm(copy.adapter.type, emoji), copy.threadId)), timeout])
11967
+ return Promise.race([Promise.resolve().then(() => {
11968
+ if (replyRoute && (!replyRoute.current() || !routeMatches(copy)))
11969
+ throw new RequestContextPolicyError("stale");
11970
+ return copy.adapter.react(copy.chatId, copy.messageId, reactionForm(copy.adapter.type, emoji), copy.threadId);
11971
+ }), timeout])
10248
11972
  .then(() => 1, (err) => {
10249
11973
  this.logger.warn({ err, instance, adapter: copy.adapter.type }, "Reaction on a web message's channel copy failed (shown on the web)");
10250
11974
  return 0;
@@ -10480,6 +12204,490 @@ export class FleetManager {
10480
12204
  }
10481
12205
  });
10482
12206
  }
12207
+ /** One controlled candidate, shared by instruction rendering and the lifecycle's actual pre-start hook. */
12208
+ prepareRequestContextDaemonOwner(instance, config, policy, registration, current) {
12209
+ const box = this.deliveryOutbox;
12210
+ if (!box)
12211
+ throw Error("Request input owner is unavailable");
12212
+ const firstActivation = box.requestContextInstallation().read() === null;
12213
+ const image = requestContextDigest(config), incarnation = this.contactGeneration(instance);
12214
+ let registered = false, daemon = null, binding = null;
12215
+ const ownerCurrent = () => {
12216
+ try {
12217
+ return current() && this.contactGeneration(instance) === incarnation
12218
+ && (!registered || !!daemon && this.daemons.get(instance) === daemon);
12219
+ }
12220
+ catch {
12221
+ return false;
12222
+ }
12223
+ };
12224
+ const work = new RequestContextPreparedWork(box.requestContextWork, instance, incarnation, ownerCurrent, firstActivation);
12225
+ const preparation = Object.freeze({ policy, current: () => work.current() && ownerCurrent() });
12226
+ return Object.freeze({ preparation, work,
12227
+ configure: (candidate, actual, offered) => {
12228
+ if (daemon || !preparation.current() || !offered?.current() || offered.policy !== policy
12229
+ || requestContextDigest(actual) !== image || requestContextDigest(candidate.getConfigSnapshot()) !== image)
12230
+ throw Error("Request owner preparation changed");
12231
+ daemon = candidate;
12232
+ try {
12233
+ binding = this.makeRequestContextDaemonBinding(instance, candidate, work, registration, ownerCurrent);
12234
+ if (candidate.captureRequestContextOwner()?.instance !== instance)
12235
+ throw Error("Request owner preparation changed");
12236
+ }
12237
+ catch (error) {
12238
+ work.dispose();
12239
+ throw error;
12240
+ }
12241
+ },
12242
+ /** Ownership only, not readiness: the installer must independently prove all real transport ports. */
12243
+ sealRegistered: () => {
12244
+ if (!daemon || this.daemons.get(instance) !== daemon || daemon.requestContextPolicy !== policy || !binding?.current() || !preparation.current())
12245
+ throw Error("Request owner is not bound");
12246
+ registered = true;
12247
+ },
12248
+ bound: () => registered && preparation.current() && binding?.current() === true,
12249
+ hub: () => registered && preparation.current() ? binding?.hub ?? null : null,
12250
+ dispose: () => work.dispose(), });
12251
+ }
12252
+ /** Installer-owned new-registration lane. Never called by a tool or inferred from an absent work row.
12253
+ * retirement is captured by the controlled relaunch before the old launch/IPC is stopped.
12254
+ */
12255
+ async registerRequestContextWork(instance, retirement) {
12256
+ const box = this.deliveryOutbox, admission = this.requestContextAdmission, lease = captureProcessFleetLease(this.dataDir);
12257
+ if (!box || !box.requestContextInstallation().read() || !admission || admission.available() || !lease?.current()
12258
+ || this.hubIncarnationsBroken || !retirement.current())
12259
+ throw Error("Request work registration unavailable");
12260
+ const incarnation = this.contactGeneration(instance), path = this.hubIncarnationsPath(), image = readFileSync(path, "utf8");
12261
+ const raw = JSON.parse(image), entry = Object.hasOwn(raw, instance) ? raw[instance] : undefined, previous = box.requestContextWork.read(instance);
12262
+ const mode = requestWorkRegistrationEvidence(instance, entry, incarnation, previous?.incarnation ?? null);
12263
+ const current = () => {
12264
+ try {
12265
+ return !this.shuttingDown && lease.current() && this.requestContextAdmission === admission && !admission.available()
12266
+ && !this.hubIncarnationsBroken && retirement.current() && this.contactGeneration(instance) === incarnation && readFileSync(path, "utf8") === image;
12267
+ }
12268
+ catch {
12269
+ return false;
12270
+ }
12271
+ };
12272
+ if (!current() || !await retirement.retired() || !current())
12273
+ throw Error("Request work predecessor is not retired");
12274
+ const value = mode === "resume" ? previous : box.requestContextWork.register({ instance, incarnation, generation: randomUUID() }, previous, current);
12275
+ if (!current())
12276
+ throw Error("Request work registration changed");
12277
+ // Commit precedes marker consumption. A crash in between resumes the exact row and finishes this write;
12278
+ // a consumed marker with a missing row can never recreate a birth.
12279
+ raw[instance] = { ...entry, requestWork: "registered" };
12280
+ if (this.writeHubIncarnations(raw) !== "written")
12281
+ throw Error("Request work registration evidence unavailable");
12282
+ if (!lease.current() || !retirement.current() || this.contactGeneration(instance) !== incarnation)
12283
+ throw Error("Request work registration changed");
12284
+ return value;
12285
+ }
12286
+ /** Finish a committed registration's marker, including crash recovery. This creates no work, context or permission. */
12287
+ sealRequestContextWorkRegistration(instance, current) {
12288
+ const box = this.deliveryOutbox, lease = captureProcessFleetLease(this.dataDir), incarnation = this.contactGeneration(instance), work = box?.requestContextWork.read(instance);
12289
+ if (!box || !work || work.incarnation !== incarnation || !lease?.current() || !current() || this.hubIncarnationsBroken)
12290
+ throw Error("Committed request registration unavailable");
12291
+ const path = this.hubIncarnationsPath(), image = readFileSync(path, "utf8"), raw = JSON.parse(image), entry = Object.hasOwn(raw, instance) ? raw[instance] : undefined;
12292
+ requestWorkRegistrationEvidence(instance, entry, incarnation, work.incarnation);
12293
+ const owned = () => lease.current() && current() && !this.hubIncarnationsBroken && this.contactGeneration(instance) === incarnation
12294
+ && requestContextDigest(box.requestContextWork.read(instance)) === requestContextDigest(work);
12295
+ if (!owned() || readFileSync(path, "utf8") !== image)
12296
+ throw Error("Committed request registration changed");
12297
+ if (entry.requestWork !== "registered") {
12298
+ raw[instance] = { ...entry, requestWork: "registered" };
12299
+ if (this.writeHubIncarnations(raw) !== "written")
12300
+ throw Error("Request registration marker unavailable");
12301
+ }
12302
+ if (!owned())
12303
+ throw Error("Committed request registration changed");
12304
+ }
12305
+ /** Capable boot/restart factory. A current retained work row is mandatory; a missing/new incarnation uses
12306
+ * only the explicit durable registration lane. No running daemon is hot-bound and no active turn is restored.
12307
+ */
12308
+ installRequestContextRetainedOwners(policy, registration, current, adopt = [], options = {}) {
12309
+ const box = this.deliveryOutbox, admission = this.requestContextAdmission, lease = captureProcessFleetLease(this.dataDir), token = {}, initial = box?.requestContextInstallation().read();
12310
+ if (!box || !initial && !options.firstOnStage?.current() || !admission || admission.available() || !lease?.current() || !current() || this.requestContextRetainedFactory)
12311
+ throw Error("Retained request owner factory unavailable");
12312
+ let sealed = !!initial, attached = false;
12313
+ const entries = new Map(), preparing = new Set(), retiredLaunches = new Map();
12314
+ let serial = 0;
12315
+ this.requestContextRetainedFactory = token;
12316
+ const owned = () => { try {
12317
+ return this.requestContextRetainedFactory === token && !this.shuttingDown && lease.current() && current() && this.requestContextAdmission === admission;
12318
+ }
12319
+ catch {
12320
+ return false;
12321
+ } };
12322
+ const entryCurrent = (entry) => {
12323
+ try {
12324
+ return owned() && entries.get(entry.name) === entry && this.contactGeneration(entry.name) === entry.incarnation
12325
+ && (!entry.daemon || this.daemons.get(entry.name) === entry.daemon || entry.starting && !this.daemons.has(entry.name));
12326
+ }
12327
+ catch {
12328
+ return false;
12329
+ }
12330
+ };
12331
+ const prepare = async (name, config) => {
12332
+ if (!owned() || preparing.has(name))
12333
+ throw Error("Request owner registration changed");
12334
+ preparing.add(name);
12335
+ try {
12336
+ const incarnation = this.contactGeneration(name), previous = entries.get(name), stored = box.requestContextWork.read(name), staging = !sealed && options.firstOnStage?.current() === true;
12337
+ if (previous?.exec) {
12338
+ if (!previous.exec.idle())
12339
+ throw Error("Request owner is still preparing or running");
12340
+ if (previous.incarnation === incarnation && previous.work.current()) {
12341
+ if (!staging)
12342
+ this.sealRequestContextWorkRegistration(name, owned);
12343
+ return;
12344
+ }
12345
+ }
12346
+ if (previous?.daemon && this.daemons.get(name) === previous.daemon)
12347
+ throw Error("Request owner is still running");
12348
+ if (previous?.daemon && (!previous.resources || !await previous.resources.retired()) || !owned())
12349
+ throw Error("Request predecessor has not retired");
12350
+ if ((!stored || stored.incarnation !== incarnation) && !(!stored && staging)) {
12351
+ // Cold unknown predecessors remain blocked. A new birth proves absence of any earlier owned launch;
12352
+ // a recorded predecessor must additionally have this factory's exact retired resource receipt.
12353
+ if (stored && !previous?.resources)
12354
+ throw Error("Request predecessor retirement unavailable");
12355
+ const absent = () => !this.daemons.has(name) && !existsSync(join(this.getInstanceDir(name), "window-id")) && !existsSync(join(this.getInstanceDir(name), "channel.sock"))
12356
+ && !WindowsAgents.requestContextOwnersOnDisk(this.dataDir).some(row => row.instance === name);
12357
+ await this.registerRequestContextWork(name, { current: () => owned() && this.contactGeneration(name) === incarnation && !this.daemons.has(name) && entries.get(name) === previous,
12358
+ retired: () => previous?.resources?.retired() ?? Promise.resolve(absent()) });
12359
+ }
12360
+ if (!owned() || this.contactGeneration(name) !== incarnation || this.daemons.has(name))
12361
+ throw Error("Request owner registration changed");
12362
+ if (!staging)
12363
+ this.sealRequestContextWorkRegistration(name, owned);
12364
+ previous?.prepared?.dispose();
12365
+ previous?.exec?.dispose();
12366
+ previous?.work.dispose();
12367
+ const entry = {};
12368
+ Object.assign(entry, { name, incarnation, config: structuredClone(config), starting: true, ...((previous?.daemon || retiredLaunches.has(name)) ? { previous: previous?.daemon?.requestContextLaunchObservation() ?? retiredLaunches.get(name) } : {}) });
12369
+ entries.set(name, entry);
12370
+ retiredLaunches.delete(name);
12371
+ serial++;
12372
+ const local = () => entryCurrent(entry);
12373
+ try {
12374
+ if (isNativeExecInstance(config)) {
12375
+ entry.work = new RequestContextPreparedWork(box.requestContextWork, name, incarnation, local, staging);
12376
+ entry.exec = createRequestContextExecOwner(box, { instance: name, managerBootId: this.managerBootId, work: entry.work, registration, current: local,
12377
+ incarnation: () => this.contactGeneration(name), deliveryEpoch: () => this.getDeliveryEpoch(name), admitted: root => this.requestContextNativeAdmissionCurrent(root),
12378
+ consumptionCurrent: delivery => this.contactDeliveryCurrent(delivery), canManage: actor => { const person = this.makeRequestContextContactHost(owned, () => false, () => "active").person(actor); return !!person && this.contactAdminOf(name, person); } });
12379
+ entry.starting = false;
12380
+ }
12381
+ else {
12382
+ entry.prepared = this.prepareRequestContextDaemonOwner(name, config, policy, registration, local);
12383
+ entry.work = entry.prepared.work;
12384
+ }
12385
+ }
12386
+ catch (error) {
12387
+ if (entries.get(name) === entry)
12388
+ entries.delete(name);
12389
+ serial++;
12390
+ throw error;
12391
+ }
12392
+ }
12393
+ finally {
12394
+ preparing.delete(name);
12395
+ }
12396
+ };
12397
+ const retire = async (name, daemon, retired) => {
12398
+ const entry = entries.get(name);
12399
+ if (!entry && !this.daemons.has(name) && owned() && await retired())
12400
+ return;
12401
+ if (!owned() || entry?.daemon !== daemon || this.daemons.has(name) || !await retired() || !owned() || entries.get(name) !== entry)
12402
+ throw Error("Request owner retirement changed");
12403
+ retiredLaunches.set(name, daemon.requestContextLaunchObservation());
12404
+ entry.prepared?.dispose();
12405
+ entry.work.dispose();
12406
+ entries.delete(name);
12407
+ serial++;
12408
+ };
12409
+ const attach = () => {
12410
+ if (attached || !owned() || admission.available())
12411
+ throw Error("Retained request start hooks unavailable");
12412
+ const originalConfigure = this.configureRequestContextBeforeStart;
12413
+ this.prepareRequestContextOwnerRegistration = prepare;
12414
+ this.requestContextRetireOwner = retire;
12415
+ this.prepareRequestContextStart = (name, config) => {
12416
+ const entry = entries.get(name);
12417
+ if (!entry?.prepared || entry.daemon || !entryCurrent(entry) || requestContextDigest(entry.config) !== requestContextDigest(config))
12418
+ throw Error("Retained request preparation unavailable");
12419
+ return entry.prepared.preparation;
12420
+ };
12421
+ this.configureRequestContextBeforeStart = (name, daemon, config, offered) => {
12422
+ const entry = entries.get(name);
12423
+ if (!entry?.prepared || entry.daemon || !entryCurrent(entry) || !offered?.current() || offered.policy !== policy
12424
+ || requestContextDigest(config) !== requestContextDigest(entry.config))
12425
+ throw Error("Retained request owner differs");
12426
+ entry.daemon = daemon;
12427
+ if (entry.previous)
12428
+ daemon.seedRequestContextReplacement(entry.previous);
12429
+ entry.resources = daemon.prepareRequestContextStartupRetirement();
12430
+ originalConfigure?.(name, daemon, config, offered);
12431
+ entry.prepared.configure(daemon, config, offered);
12432
+ };
12433
+ this.requestContextOwnerStarted = (name, daemon) => {
12434
+ const entry = entries.get(name);
12435
+ if (!entry?.prepared || entry.daemon !== daemon || this.daemons.get(name) !== daemon || !entryCurrent(entry))
12436
+ throw Error("Retained request owner differs");
12437
+ entry.prepared.sealRegistered();
12438
+ entry.starting = false;
12439
+ serial++;
12440
+ };
12441
+ attached = true;
12442
+ };
12443
+ const adoptOwners = (values) => {
12444
+ for (const row of values) {
12445
+ if (entries.has(row.name) || this.daemons.get(row.name) !== row.daemon || !row.prepared.bound())
12446
+ throw Error("Retained request adoption differs");
12447
+ const incarnation = this.contactGeneration(row.name), entry = { name: row.name, incarnation, config: row.daemon.getConfigSnapshot(), starting: false, daemon: row.daemon, prepared: row.prepared, resources: row.resources, work: row.prepared.work };
12448
+ entries.set(row.name, entry);
12449
+ serial++;
12450
+ }
12451
+ };
12452
+ adoptOwners(adopt);
12453
+ if (!options.deferStartHooks)
12454
+ attach();
12455
+ const exec = (name) => { const entry = entries.get(name); if (!entry?.exec || !entryCurrent(entry))
12456
+ throw Error("Retained native owner unavailable"); return entry.exec; };
12457
+ const aggregate = (kind, root) => {
12458
+ const views = [], image = [];
12459
+ let unknown = !owned();
12460
+ for (const [name, daemon] of this.daemons)
12461
+ if (entries.get(name)?.daemon !== daemon)
12462
+ unknown = true;
12463
+ for (const [name, row] of [...entries].sort(([a], [b]) => a.localeCompare(b))) {
12464
+ const current = entryCurrent(row) && row.work.current();
12465
+ if (!current)
12466
+ unknown = true;
12467
+ image.push([name, row.incarnation, row.work.revision, row.daemon?.bootId ?? null, !!row.exec, current]);
12468
+ try {
12469
+ const view = kind === "turns" ? (row.exec?.turns.drainView(root) ?? row.daemon?.requestContextTurnDrainView(root))
12470
+ : kind === "calls" ? row.daemon?.requestContextCallDrainView(root) : row.prepared?.hub()?.drainView(root);
12471
+ if (view) {
12472
+ views.push(view);
12473
+ image.push([name, view.revision]);
12474
+ if (view.unknown || view.registration !== registration)
12475
+ unknown = true;
12476
+ }
12477
+ else if (row.daemon)
12478
+ unknown = true;
12479
+ if (kind === "inputs" && row.daemon) {
12480
+ const pending = row.daemon.requestContextQueuedWorkDrainView(root);
12481
+ views.push(pending);
12482
+ image.push([name, "queued", pending.revision]);
12483
+ if (pending.unknown || pending.registration !== registration)
12484
+ unknown = true;
12485
+ } // A live/missing view cannot disappear from the whole-Fleet proof.
12486
+ }
12487
+ catch {
12488
+ unknown = true;
12489
+ image.push([name, "unavailable"]);
12490
+ }
12491
+ }
12492
+ return { registration, revision: requestContextDigest([serial, kind, image, [...this.daemons].map(([name, daemon]) => [name, daemon.bootId])]), references: views.flatMap(view => view.references), unknown };
12493
+ };
12494
+ return Object.freeze({ current: owned, beforeStart: prepare, attach, adopt: adoptOwners,
12495
+ disposeStopped: async (nativeRetired) => {
12496
+ if (this.daemons.size || preparing.size || !nativeRetired())
12497
+ throw Error("Request owners are not retired");
12498
+ for (const entry of entries.values())
12499
+ if (entry.daemon && (!entry.resources || !await entry.resources.retired()))
12500
+ throw Error("Request launch retirement unavailable");
12501
+ if (!nativeRetired())
12502
+ throw Error("Native owner retirement changed");
12503
+ for (const entry of entries.values()) {
12504
+ entry.exec?.dispose();
12505
+ entry.prepared?.dispose();
12506
+ entry.work.dispose();
12507
+ }
12508
+ entries.clear();
12509
+ serial++;
12510
+ if (this.requestContextRetainedFactory !== token)
12511
+ throw Error("Request owner factory changed");
12512
+ this.requestContextRetainedFactory = undefined;
12513
+ },
12514
+ disposeUnstarted: () => {
12515
+ if (entries.size || preparing.size || this.daemons.size || this.requestContextRetainedFactory !== token)
12516
+ throw Error("Request owners have already started");
12517
+ this.requestContextRetainedFactory = undefined;
12518
+ serial++;
12519
+ },
12520
+ bound: (name, daemon) => { const entry = entries.get(name); return !!entry && entry.daemon === daemon && entryCurrent(entry) && entry.prepared?.bound() === true; },
12521
+ retain: () => { if (sealed || !owned() || !options.firstOnStage?.current())
12522
+ throw Error("Request owner staging changed"); for (const entry of entries.values())
12523
+ entry.work.retainPrepared(); },
12524
+ seal: () => { if (!owned() || !box.requestContextInstallation().read())
12525
+ throw Error("Request owner staging has not committed"); for (const entry of entries.values()) {
12526
+ entry.work.sealRetained();
12527
+ this.sealRequestContextWorkRegistration(entry.name, owned);
12528
+ } sealed = true; },
12529
+ disposeStaged: async () => {
12530
+ if (sealed || box.requestContextInstallation().read() || !owned() || attached)
12531
+ throw Error("Retained request owners cannot revert");
12532
+ for (const entry of entries.values())
12533
+ if (entry.exec && !entry.exec.idle() || entry.daemon && (!entry.resources || !await entry.resources.retired()))
12534
+ throw Error("Staged request owner is still running");
12535
+ for (const entry of entries.values()) {
12536
+ entry.exec?.dispose();
12537
+ entry.prepared?.dispose();
12538
+ entry.work.dispose();
12539
+ }
12540
+ entries.clear();
12541
+ serial++;
12542
+ if (this.requestContextRetainedFactory !== token)
12543
+ throw Error("Retained request owner changed");
12544
+ this.requestContextRetainedFactory = undefined;
12545
+ },
12546
+ hub: (name) => { const entry = entries.get(name); return entry && entryCurrent(entry) ? entry.prepared?.hub() ?? null : null; },
12547
+ execTurns: (name) => exec(name).turns, execOwner: (name) => exec(name).owner(),
12548
+ execInput: (name, ...args) => exec(name).prepare(...args),
12549
+ revision: () => aggregate("turns", "").revision, turnView: (root) => aggregate("turns", root),
12550
+ callRevision: () => aggregate("calls", "").revision, callView: (root) => aggregate("calls", root),
12551
+ inputRevision: () => aggregate("inputs", "").revision, inputView: (root) => aggregate("inputs", root),
12552
+ });
12553
+ }
12554
+ /** One replacement's C/D-local binding. It is constructed before startup, never hot-bound or published here. */
12555
+ makeRequestContextDaemonBinding(instance, daemon, work, registration, current) {
12556
+ const box = this.deliveryOutbox;
12557
+ if (!box)
12558
+ throw Error("Request input owner is unavailable");
12559
+ const identity = () => {
12560
+ if (!work.current())
12561
+ throw Error("Request work identity is no longer current");
12562
+ const value = work.identity();
12563
+ if (value.incarnation !== this.contactGeneration(instance))
12564
+ throw Error("Request source incarnation changed");
12565
+ return Object.freeze({ incarnation: value.incarnation, workGeneration: value.workGeneration });
12566
+ };
12567
+ identity();
12568
+ const owned = () => { try {
12569
+ identity();
12570
+ return current() && work.current();
12571
+ }
12572
+ catch {
12573
+ return false;
12574
+ } };
12575
+ const manage = (actor) => {
12576
+ if (actor.kind !== "person" || actor.platform === "hub")
12577
+ return false;
12578
+ const adapter = actor.platform === "host" ? "host" : this.contactAdapter(instance)?.id;
12579
+ if (!adapter)
12580
+ return false;
12581
+ return owned() && this.contactAdminOf(instance, { platform: actor.platform, adapterId: adapter, userId: actor.userId, label: actor.userId });
12582
+ };
12583
+ const human = this.makeRequestContextHumanResolver(instance, daemon, owned), delivery = this.makeRequestContextDeliveryResolver(instance, daemon, owned), hub = this.makeRequestContextHubResolver(instance, daemon, owned, registration);
12584
+ const input = (id, wire, owner) => {
12585
+ if (!owned() || this.daemons.get(instance) !== daemon)
12586
+ throw Error("Request input owner changed");
12587
+ return human.prepare(id, wire, owner) ?? delivery.prepare(id, wire, owner) ?? hub.prepare(id, wire, owner);
12588
+ };
12589
+ const turns = new RequestContextLocalTurns({ ...box.requestContextRecovery.ports(instance, input, manage), registration });
12590
+ daemon.setRequestContextLocalLifecycle(turns, identity, () => {
12591
+ if (!owned())
12592
+ throw Error("Request work identity is no longer current");
12593
+ const before = identity();
12594
+ work.fresh();
12595
+ const after = identity();
12596
+ if (!owned() || after.incarnation !== before.incarnation || after.workGeneration === before.workGeneration)
12597
+ throw Error("Fresh request work identity did not rotate");
12598
+ }, snapshot => requestHumanReplyTarget(box, snapshot, () => owned() && daemon.requestContextTurnCurrent(snapshot), root => this.requestContextNativeAdmissionCurrent(root)), (id, recovery) => {
12599
+ const publication = this.requestContextBoot?.publication;
12600
+ if (!publication)
12601
+ return;
12602
+ if (recovery) {
12603
+ const parent = recovery.parent, owner = daemon.captureRequestContextOwner(), stored = box.requestContext(parent.context.ref.contextId);
12604
+ if (!owner || !stored || requestContextDigest(stored) !== requestContextDigest(parent.context) || parent.owner.instance !== owner.instance
12605
+ || parent.owner.incarnation !== owner.incarnation || parent.owner.workGeneration !== owner.workGeneration)
12606
+ throw Error("Recovery continuation owner changed");
12607
+ return publication.continuation(parent.context.ref.rootContextId, () => owned() && recovery.current());
12608
+ }
12609
+ const delivery = /^delivery:([a-f0-9-]{36}):([1-9][0-9]*)$/.exec(id ?? "");
12610
+ if (delivery) {
12611
+ const row = box.get(delivery[1]), owner = daemon.captureRequestContextOwner();
12612
+ if (!row || !owner || row.targetInstance !== instance || row.managerBootId !== this.managerBootId || row.targetDaemonBootId !== owner.daemonBootId
12613
+ || row.attemptNo !== Number(delivery[2]) || !["delivering", "submission_started"].includes(row.state))
12614
+ throw Error("Delivery continuation attempt changed");
12615
+ return this.requestContextDeliveryContinuation(row) ?? undefined;
12616
+ }
12617
+ const human = /^human:hmsg-([a-f0-9-]{36})$/.exec(id ?? "");
12618
+ return human ? this.requestContextHumanContinuation(instance, human[1]) : undefined;
12619
+ });
12620
+ return Object.freeze({ turns, hub, input, current: () => owned() && this.daemons.get(instance) === daemon && daemon.requestContextCallsRequired() });
12621
+ }
12622
+ /** Accepted Hub input owner; construction is pre-start and remains unpublished until the complete installer. */
12623
+ makeRequestContextHubResolver(instance, daemon, current, registration) {
12624
+ const box = this.deliveryOutbox;
12625
+ if (!box)
12626
+ throw Error("Hub request input owner is unavailable");
12627
+ return new RequestHubInputResolver(box, { instance, current: () => current() && this.daemons.get(instance) === daemon,
12628
+ runtimeOwner: () => daemon.captureRequestContextOwner(), active: () => daemon.requestContextTurnSnapshot(), registration });
12629
+ }
12630
+ /** Physical B attempt resolver for the exact replacement daemon; no origin or correlation fallback. */
12631
+ makeRequestContextDeliveryResolver(instance, daemon, current) {
12632
+ const box = this.deliveryOutbox;
12633
+ if (!box)
12634
+ throw Error("Request delivery input owner is unavailable");
12635
+ return makeRequestDeliveryInputResolver(box, { instance, managerBootId: this.managerBootId,
12636
+ current: () => current() && this.daemons.get(instance) === daemon, runtimeOwner: () => daemon.captureRequestContextOwner(),
12637
+ consumptionCurrent: delivery => this.contactDeliveryCurrent(delivery) });
12638
+ }
12639
+ /** Pre-start owner factory; this neither installs a lifecycle nor publishes serving input. */
12640
+ makeRequestContextHumanResolver(instance, daemon, current) {
12641
+ const box = this.deliveryOutbox;
12642
+ if (!box)
12643
+ throw Error("Human request input owner is unavailable");
12644
+ return makeRequestHumanInputResolver(box, { instance, managerBootId: this.managerBootId,
12645
+ current: () => current() && this.daemons.get(instance) === daemon,
12646
+ runtimeOwner: () => daemon.captureRequestContextOwner(), humanOwner: () => this.humanReceiptOwner(instance, daemon), active: () => daemon.requestContextTurnSnapshot(),
12647
+ admitted: context => this.requestContextNativeAdmissionCurrent(context),
12648
+ canManage: actor => {
12649
+ if (actor.kind !== "person" || actor.platform === "hub")
12650
+ return false;
12651
+ const adapter = actor.platform === "host" ? "host" : this.contactAdapter(instance)?.id;
12652
+ if (!adapter)
12653
+ return false;
12654
+ return this.contactAdminOf(instance, { platform: actor.platform, adapterId: adapter, userId: actor.userId, label: actor.userId });
12655
+ } });
12656
+ }
12657
+ /** Assigned only by the complete installer at publication; candidate launch rendering cannot install this. */
12658
+ requestContextHumanAdmission;
12659
+ makeRequestContextHumanAdmission() {
12660
+ this.ensureDeliveryOutbox();
12661
+ const box = this.deliveryOutbox;
12662
+ return (instance, payload, origin, body) => {
12663
+ const room = this.contactRoom(instance), meta = payload.meta;
12664
+ const platform = (id) => {
12665
+ const adapter = this.adapters.get(id) ?? this.worlds.get(id)?.adapter;
12666
+ const configured = (this.fleetConfig?.channels ?? (this.fleetConfig?.channel ? [this.fleetConfig.channel] : [])).find(channel => (channel.id ?? channel.type) === id);
12667
+ const kind = adapter?.type ?? configured?.type;
12668
+ return kind === "discord" || kind === "telegram" ? kind : null;
12669
+ };
12670
+ const nativeBasis = admittedNativeHumanIngress(origin), webBasis = origin.platform === "web" ? admittedHumanWebIngress(origin) : null;
12671
+ if (origin.platform === "web" && !webBasis?.sessionHandle)
12672
+ throw Error("Accepted web input route is unavailable");
12673
+ if (room && origin.platform !== "web" && (!nativeBasis || nativeBasis.roomId !== room.channelId || origin.adapter_id !== (room.adapterId ?? this.contactAdapter(instance)?.id)))
12674
+ throw Error("Accepted Classic admission basis is unavailable");
12675
+ const daemon = ["steer", "btw"].includes(String(payload.type)) ? this.lifecycle?.daemons.get(instance) : undefined, parent = daemon?.requestContextTurnSnapshot();
12676
+ const steer = parent && daemon ? { parent, current: () => this.daemons.get(instance) === daemon && daemon.requestContextTurnCurrent(parent), canManage: (actor) => {
12677
+ if (actor.kind !== "person" || actor.platform === "hub")
12678
+ return false;
12679
+ const adapter = actor.platform === "host" ? "host" : this.contactAdapter(instance)?.id;
12680
+ return !!adapter && this.contactAdminOf(instance, { platform: actor.platform, adapterId: adapter, userId: actor.userId, label: actor.userId });
12681
+ } } : undefined;
12682
+ const captured = box.createHumanReceiptWithRequestContext({ targetInstance: instance, originalBody: body, origin: { ...origin }, inputKind: String(payload.type), managerBootId: this.managerBootId }, { incarnation: this.contactGeneration(instance), steer, room: room ? { restricted: room.restrictedMode === true } : null,
12683
+ web: webBasis,
12684
+ classic: room && origin.platform !== "web" && nativeBasis ? { ...nativeBasis, adapterId: origin.adapter_id } : null,
12685
+ route: { kind: origin.platform === "web" ? "web" : "room", adapterId: origin.platform === "web" ? meta?.adapter_id : origin.adapter_id ?? undefined,
12686
+ chatId: meta?.chat_id ?? "", threadId: meta?.thread_id ?? "", ...(meta?.message_id ? { messageId: meta.message_id } : {}),
12687
+ ...(origin.platform === "web" ? { sessionHandle: webBasis.sessionHandle } : {}) }, platform });
12688
+ return captured.receipt;
12689
+ };
12690
+ }
10483
12691
  /** Evidence-only admission. Bots/system/agent payloads have no trusted origin. */
10484
12692
  humanReceiptPayload(instanceName, payload, origin, originalBody) {
10485
12693
  // #1939 S3: "via web (verified)" comes only from the receipt written here — never from a caller's meta.
@@ -10490,10 +12698,18 @@ export class FleetManager {
10490
12698
  }
10491
12699
  if (!origin || !this.deliveryOutbox)
10492
12700
  return payload;
10493
- const row = this.deliveryOutbox.createHumanReceipt({ targetInstance: instanceName, originalBody,
10494
- origin: { ...origin }, inputKind: String(payload.type), managerBootId: this.managerBootId });
10495
- const contactStore = this.deliveryOutbox.contactAuthorizations;
10496
- if (this.contactRoom(instanceName)?.restrictedMode === true && !contactStore)
12701
+ const installed = requestContextPolicyInstalled(this.requestContextPolicy);
12702
+ // A committed but unpublished bridge can retain exact input metadata while the actual write stays fenced.
12703
+ const prepared = this.requestContextBoot?.publication.heldUnpublished() === true && this.requestContextModes?.current() === true;
12704
+ const scoped = installed || prepared;
12705
+ if (scoped && !this.requestContextHumanAdmission)
12706
+ throw Error("Accepted human input admission is unavailable");
12707
+ const row = scoped ? this.requestContextHumanAdmission(instanceName, payload, origin, originalBody)
12708
+ : this.deliveryOutbox.createHumanReceipt({ targetInstance: instanceName, originalBody,
12709
+ origin: { ...origin }, inputKind: String(payload.type), managerBootId: this.managerBootId });
12710
+ // Installed work uses its admitted request only; lifetime history is no longer a permission input or shadow.
12711
+ const contactStore = scoped ? undefined : this.deliveryOutbox.contactAuthorizations;
12712
+ if (!scoped && this.contactRoom(instanceName)?.restrictedMode === true && !contactStore)
10497
12713
  throw Error("Contact origin storage unavailable");
10498
12714
  // M-3830 (user 11-26, Fable): a person's message becomes contact origin only in a restricted ClassicBot room. Who may
10499
12715
  // talk to a fleet agent in its own topic is the admin's channel access (#754); recording it only once some earlier
@@ -10530,8 +12746,14 @@ export class FleetManager {
10530
12746
  }
10531
12747
  }
10532
12748
  const verified = origin.platform === "web" && authority?.kind === "web-verified";
10533
- return { ...payload, meta: { ...(payload.meta ?? {}),
12749
+ const admitted = { ...payload, meta: { ...(payload.meta ?? {}),
10534
12750
  human_receipt_id: row.receipt_id, verification_id: row.message_id, ...(verified ? { web_verified: "1" } : {}) } };
12751
+ if (this.requestContextBoot) {
12752
+ const continuation = this.requestContextHumanContinuation(instanceName, row.receipt_id);
12753
+ if (continuation)
12754
+ requestPayloadContinuations.set(admitted, continuation);
12755
+ }
12756
+ return admitted;
10535
12757
  }
10536
12758
  /** Register owned preparation at IPC; bind once at the final pane write. No human retry lane. */
10537
12759
  bindHumanReceiptPayload(instanceName, payload) {
@@ -10540,6 +12762,11 @@ export class FleetManager {
10540
12762
  return payload;
10541
12763
  const daemon = this.daemons.get(instanceName);
10542
12764
  const owner = this.humanReceiptOwner(instanceName, daemon);
12765
+ const retained = retainedHumanControl(payload);
12766
+ const bind = (wire) => retained
12767
+ ? this.deliveryOutbox.bindRetainedHumanControlReceipt(retained, meta.human_receipt_id, instanceName, owner, wire, this.managerBootId, () => daemon?.bootId === retained.targetDaemonBootId && this.humanReceiptOwner(instanceName, daemon) === owner
12768
+ && (!this.requestContextAdmission || this.requestContextAdmission.available(requestPayloadContinuations.get(payload))))
12769
+ : this.deliveryOutbox.bindHumanReceipt(meta.human_receipt_id, instanceName, owner, wire, this.managerBootId);
10543
12770
  if (!daemon || !owner) {
10544
12771
  this.deliveryOutbox.markHumanReceiptUncertain(meta.human_receipt_id, instanceName);
10545
12772
  return payload;
@@ -10555,7 +12782,7 @@ export class FleetManager {
10555
12782
  throw new Error("Human delivery ownership changed");
10556
12783
  const dialectMeta = { ...originalMeta, human_wire_dialect: presentation.dialect ?? "legacy" };
10557
12784
  const wire = daemon.humanReceiptWire(content, dialectMeta, kind, presentation);
10558
- const row = this.deliveryOutbox.bindHumanReceipt(meta.human_receipt_id, instanceName, owner, wire, this.managerBootId);
12785
+ const row = bind(wire);
10559
12786
  if (this.humanReceiptOwner(instanceName, daemon) !== owner)
10560
12787
  throw new Error("Human delivery ownership changed");
10561
12788
  return { wire, meta: { human_owner_key: owner, human_daemon_owner: daemonOwner,
@@ -10564,7 +12791,7 @@ export class FleetManager {
10564
12791
  return { ...payload, meta: { ...meta, human_prepare_token: token } };
10565
12792
  }
10566
12793
  const wire = daemon.humanReceiptWire(String(payload.content ?? ""), meta, String(payload.type));
10567
- const row = this.deliveryOutbox.bindHumanReceipt(meta.human_receipt_id, instanceName, owner, wire, this.managerBootId);
12794
+ const row = bind(wire);
10568
12795
  if (!daemonOwner || this.humanReceiptOwner(instanceName, daemon) !== owner)
10569
12796
  throw new Error("Human delivery ownership changed");
10570
12797
  // /raw retains exact bytes and never acquires a positive verification capability.
@@ -10577,6 +12804,8 @@ export class FleetManager {
10577
12804
  async deliverHumanToInstance(instanceName, payload, origin, originalBody, options) {
10578
12805
  const admitted = this.humanReceiptPayload(instanceName, payload, origin, originalBody);
10579
12806
  const id = admitted.meta?.human_receipt_id;
12807
+ if (origin && id && requestContextPolicyInstalled(this.requestContextPolicy))
12808
+ nativeHumanInputs.set(admitted, { instance: instanceName, inputId: `human:hmsg-${id}` });
10580
12809
  let sent = false;
10581
12810
  try {
10582
12811
  const result = options ? await this.deliverToInstance(instanceName, admitted, options) : await this.deliverToInstance(instanceName, admitted);
@@ -10602,11 +12831,37 @@ export class FleetManager {
10602
12831
  }
10603
12832
  /** Synchronous steer/btw handoff, using the same evidence and owner binding. */
10604
12833
  sendHumanControl(instanceName, payload, origin, originalBody) {
10605
- const ipc = this.instanceIpcClients.get(instanceName);
10606
- if (this.shuttingDown || !ipc?.connected)
12834
+ if (this.shuttingDown || this.requestContextAdmission?.available() !== false && !this.instanceIpcClients.get(instanceName)?.connected)
10607
12835
  return false;
10608
12836
  const admitted = this.humanReceiptPayload(instanceName, payload, origin, originalBody);
10609
12837
  const id = admitted.meta?.human_receipt_id;
12838
+ if (this.requestContextAdmission && !this.requestContextAdmission.available(requestPayloadContinuations.get(admitted))) {
12839
+ try {
12840
+ if (!this.deliveryOutbox)
12841
+ throw Error("Held human control storage unavailable");
12842
+ const key = `human-control:${id ?? randomUUID()}`;
12843
+ this.deliveryOutbox.admit({ operationId: key, sourceKey: key, sourceInstance: "agend-system",
12844
+ sourceDaemonBootId: this.managerBootId, targetInstance: instanceName, kind: "human_control", payload: admitted });
12845
+ this.scheduleDeliveryOutboxPump();
12846
+ return true; // Acknowledged only after durable admission; publishing/aborting wakes the existing pump.
12847
+ }
12848
+ catch (error) {
12849
+ if (id)
12850
+ this.deliveryOutbox?.markHumanReceiptUncertain(id, instanceName);
12851
+ this.logger.warn({ err: error, instanceName }, "Human control could not be retained");
12852
+ return false;
12853
+ }
12854
+ }
12855
+ return FleetManager.prototype.sendAdmittedHumanControl.call(this, instanceName, admitted);
12856
+ }
12857
+ sendAdmittedHumanControl(instanceName, admitted) {
12858
+ const ipc = this.instanceIpcClients.get(instanceName);
12859
+ const id = admitted.meta?.human_receipt_id;
12860
+ if (this.shuttingDown || !ipc?.connected) {
12861
+ if (id)
12862
+ this.deliveryOutbox?.markHumanReceiptUncertain(id, instanceName);
12863
+ return false;
12864
+ }
10610
12865
  let sent = false;
10611
12866
  try {
10612
12867
  const wire = this.bindHumanReceiptPayload(instanceName, admitted);
@@ -10626,16 +12881,23 @@ export class FleetManager {
10626
12881
  }
10627
12882
  /** Single delivery facade: wake paused CLIs and serialize non-user work behind idle. */
10628
12883
  async deliverToInstance(instanceName, payload, options = {}) {
12884
+ if (this.requestContextAdmission && !await this.requestContextAdmission.wait(() => !this.shuttingDown && options.stillCurrent?.() !== false, requestPayloadContinuations.get(payload)))
12885
+ return false;
10629
12886
  if (this.generalLocationDeliveryHold(instanceName))
10630
12887
  return false;
10631
12888
  if (isNativeExecInstance(this.fleetConfig?.instances[instanceName])) {
10632
12889
  if (options.beforeInput)
10633
12890
  return false; // no pre-input hook on the Windows runtime
12891
+ const input = nativeHumanInputs.get(payload);
10634
12892
  return this.nativeInstanceRuntime().deliver(instanceName, payload, { stillCurrent: options.stillCurrent,
12893
+ ...(input?.instance === instanceName ? { requestContextInputId: input.inputId } : {}),
10635
12894
  ...(options.authorityCurrent ? { authorityCurrent: options.authorityCurrent } : {}) });
10636
12895
  }
10637
12896
  const deliveryEpoch = this.getDeliveryEpoch(instanceName);
10638
12897
  const deliveryPayload = { ...payload, delivery_epoch: deliveryEpoch };
12898
+ const continuation = requestPayloadContinuations.get(payload);
12899
+ if (continuation)
12900
+ requestPayloadContinuations.set(deliveryPayload, continuation);
10639
12901
  const meta = payload.meta && typeof payload.meta === "object"
10640
12902
  ? payload.meta
10641
12903
  : undefined;
@@ -11472,6 +13734,8 @@ export class FleetManager {
11472
13734
  if (this.tmuxHold)
11473
13735
  throw new Error(this.tmuxHold.detail);
11474
13736
  if (isNativeExecInstance(config)) {
13737
+ if (this.prepareRequestContextOwnerRegistration)
13738
+ await this.prepareRequestContextOwnerRegistration(name, config);
11475
13739
  execution?.assert();
11476
13740
  if (!windowsCliEnabled())
11477
13741
  throw new Error("Windows runtime is disabled");
@@ -11547,11 +13811,23 @@ export class FleetManager {
11547
13811
  || (this.explicitStopGeneration.get(name) ?? 0) !== stopGen) {
11548
13812
  throw new SupersededStartError(name);
11549
13813
  }
13814
+ if (this.prepareRequestContextOwnerRegistration) {
13815
+ await this.prepareRequestContextOwnerRegistration(name, config);
13816
+ execution?.assert();
13817
+ if (this.lifecycle.epochOf(name) !== epoch || (this.explicitStopGeneration.get(name) ?? 0) !== stopGen)
13818
+ throw new SupersededStartError(name);
13819
+ }
13820
+ const ownedStart = this.prepareRequestContextStart?.(name, config);
13821
+ const instructionMode = requestContextInstructionMode(ownedStart?.policy);
13822
+ const requestContextStart = ownedStart ? Object.freeze({ policy: ownedStart.policy,
13823
+ current: () => ownedStart.current() && requestContextInstructionMode(ownedStart.policy) === instructionMode }) : undefined;
13824
+ if (requestContextStart && !requestContextStart.current())
13825
+ throw new SupersededStartError(name);
11550
13826
  const binary = BACKEND_INSTALLATION_INFO[backend]?.binary;
11551
13827
  if (binary && !windows)
11552
13828
  noteResolvedBinary(binary, resolved ?? binary);
11553
13829
  if (!windows && config.general_topic) {
11554
- this.ensureGeneralInstructions(config.working_directory, backend, name);
13830
+ this.ensureGeneralInstructions(config.working_directory, backend, name, instructionMode);
11555
13831
  }
11556
13832
  else if (!isWindowsInstance(config) && kind === "fleet-topic") {
11557
13833
  // Workers get only role-eligible on-demand skills. Classic instances are
@@ -11559,12 +13835,14 @@ export class FleetManager {
11559
13835
  // managed independently from fleet-topic workers.
11560
13836
  try {
11561
13837
  const skillsWorkDir = this.resolveKnowledgeWorkDir(config.working_directory, backend, name);
11562
- measureSyncWork("fleet.workerSkills", () => this.syncRoleSkills(skillsWorkDir, backend, "worker"));
13838
+ measureSyncWork("fleet.workerSkills", () => this.syncRoleSkills(skillsWorkDir, backend, "worker", undefined, false, instructionMode));
11563
13839
  }
11564
13840
  catch (err) {
11565
13841
  // Skill publishing is additive. A read-only or temporarily unavailable
11566
13842
  // workspace must not turn an otherwise valid worker startup into a
11567
13843
  // fleet outage.
13844
+ if (instructionMode !== null)
13845
+ throw err;
11568
13846
  this.logger.warn({ err, name, backend }, "Failed to sync worker skills — continuing startup");
11569
13847
  }
11570
13848
  }
@@ -11576,11 +13854,13 @@ export class FleetManager {
11576
13854
  try {
11577
13855
  const skillsWorkDir = this.resolveKnowledgeWorkDir(config.working_directory, backend, name);
11578
13856
  if (insideManagedWorkspaces(skillsWorkDir))
11579
- measureSyncWork("fleet.classicSkills", () => this.syncRoleSkills(skillsWorkDir, backend, "classic", undefined, this.classicContactRestricted(name)));
13857
+ measureSyncWork("fleet.classicSkills", () => this.syncRoleSkills(skillsWorkDir, backend, "classic", undefined, this.classicContactRestricted(name), instructionMode));
11580
13858
  else
11581
13859
  this.logger.debug({ name, skillsWorkDir }, "Classic workspace is not AgEnD-managed — no skills published");
11582
13860
  }
11583
13861
  catch (err) {
13862
+ if (instructionMode !== null)
13863
+ throw err;
11584
13864
  this.logger.warn({ err, name, backend }, "Failed to sync classic skills — continuing startup");
11585
13865
  }
11586
13866
  }
@@ -11592,10 +13872,10 @@ export class FleetManager {
11592
13872
  await this.lifecycle.start(name, config, topicMode, identity, transition, execution, daemon => {
11593
13873
  // Only this transition's actual publication can acquire its replacement.
11594
13874
  receipt.daemon = daemon;
11595
- });
13875
+ }, requestContextStart);
11596
13876
  }
11597
13877
  else
11598
- await this.lifecycle.start(name, config, topicMode, identity, transition, execution);
13878
+ await this.lifecycle.start(name, config, topicMode, identity, transition, execution, undefined, requestContextStart);
11599
13879
  }
11600
13880
  catch (err) {
11601
13881
  if (err instanceof LegacyWindowHoldError) {
@@ -11604,6 +13884,12 @@ export class FleetManager {
11604
13884
  }
11605
13885
  throw err;
11606
13886
  }
13887
+ if (this.requestContextOwnerStarted) {
13888
+ const owned = this.daemons.get(name);
13889
+ if (!owned)
13890
+ throw Error("Request owner did not start");
13891
+ this.requestContextOwnerStarted(name, owned);
13892
+ }
11607
13893
  if (this.legacyWindowHolds.delete(name))
11608
13894
  this.needsYou?.poke();
11609
13895
  execution?.assert();
@@ -14374,6 +16660,8 @@ export class FleetManager {
14374
16660
  finally {
14375
16661
  envLease.release();
14376
16662
  }
16663
+ if (this.requestContextBoot && !this.requestContextBoot.owner.current())
16664
+ await this.resetStoppedRequestContextAssembly();
14377
16665
  this.ensureDeliveryOutbox();
14378
16666
  // #1956: the spawn helper the fleet's tmux/stty commands are started by (its fork is cheap; the fleet's is not).
14379
16667
  // Started here and by the fleet's own timer — never by a tool handler — and stopped with the fleet.
@@ -14385,7 +16673,17 @@ export class FleetManager {
14385
16673
  const fleet = this.loadConfig(configPath, { startup: true });
14386
16674
  this.slimFleetConfigAtStartup();
14387
16675
  this.logConfigWarningsAtStartup();
14388
- this.initializeNativeInstances();
16676
+ if (this.requestContextBoot) {
16677
+ try {
16678
+ await this.prepareRequestContextCapableBoot(this.requestContextRootRetired);
16679
+ }
16680
+ catch (error) {
16681
+ this.requestContextCutoverErrors = [{ id: "boot", kind: "owners", labels: [], ownerCause: "update", action: "inspect" }];
16682
+ this.logger.error({ err: error.message }, "Capable request-context boot remains fenced");
16683
+ }
16684
+ }
16685
+ if (!this.requestContextBoot || this.requestContextModes?.current())
16686
+ this.initializeNativeInstances();
14389
16687
  // M-2255: from here on a change to the Windows runtimes' switches applies live (observeRuntimeSwitches).
14390
16688
  this.runtimeEffects = { windows_cli: localWindowsCliEnabled(), remote_runtime: remoteRuntimeEnabled() };
14391
16689
  setLocale(detectLocale(fleet)); // user-facing text language (fleet.yaml defaults.locale / timezone)
@@ -14998,6 +17296,22 @@ export class FleetManager {
14998
17296
  // startup-owned lifecycle work and signal handlers are in place.
14999
17297
  if (this.shuttingDown || this.startupMemoryDeadline !== deadline)
15000
17298
  return;
17299
+ if (this.requestContextModes?.current() && this.requestContextBoot?.publication.heldUnpublished()) {
17300
+ try {
17301
+ await this.prepareRequestContextFutureOwners();
17302
+ const peers = this.captureRequestContextRuntimeSet();
17303
+ await peers.prepare();
17304
+ const proof = peers.prove();
17305
+ this.requestContextModes.publish(() => proof.current() && this.requestContextOwnersReady());
17306
+ this.requestContextCutoverErrors = [];
17307
+ this.scheduleRequestContextDrain();
17308
+ }
17309
+ catch (error) {
17310
+ this.requestContextCutoverErrors = [{ id: "boot-readiness", kind: "owners", labels: [], ownerCause: "update", action: "inspect" }];
17311
+ this.logger.warn({ err: error.message }, "Request-context input remains fenced");
17312
+ }
17313
+ }
17314
+ this.requestContextControl?.changed();
15001
17315
  this.finishStartup(bootUpdateMarker);
15002
17316
  this.startupDashboard = null;
15003
17317
  this.publishStartupStatus();
@@ -16027,7 +18341,8 @@ export class FleetManager {
16027
18341
  this.logger.info({ sessionName: sender, instanceName: name }, "Registered external session");
16028
18342
  }
16029
18343
  try {
16030
- await this.handleOutboundFromInstance(name, msg);
18344
+ const run = () => this.handleOutboundFromInstance(name, msg);
18345
+ await (this.requestContextPendingWork ? this.requestContextPendingWork.run(name, run) : run());
16031
18346
  }
16032
18347
  finally {
16033
18348
  this.finishRequestContextIpcCall(msg);
@@ -16038,8 +18353,10 @@ export class FleetManager {
16038
18353
  // handler without passing through the outbound path — which is how
16039
18354
  // `update_decision`, a coordinator-only tool, kept a way through.
16040
18355
  const typed = this.checkToolPermission("ipc-typed", name, toolForIpcType(msg.type));
16041
- if (typed.allowed)
16042
- this.dispatchTypedIpc(name, msg);
18356
+ if (typed.allowed) {
18357
+ const run = () => this.dispatchTypedIpc(name, msg);
18358
+ await (this.requestContextPendingWork ? this.requestContextPendingWork.run(name, run) : run());
18359
+ }
16043
18360
  else
16044
18361
  this.refuseTypedIpc(name, msg, typed.message);
16045
18362
  }
@@ -17557,6 +19874,8 @@ export class FleetManager {
17557
19874
  // must never be read as a same-name replacement's (removed and re-registered meanwhile).
17558
19875
  const sentBy = tool === "reply" ? this.webChatIdentity(instanceName) : undefined;
17559
19876
  const args = (msg.args ?? {});
19877
+ const ownedReplyRoute = this.requestContextPolicy && ["reply", "react", "edit_message"].includes(tool) ? originatingCall?.replyRoute : undefined;
19878
+ const ownedReplyTarget = ownedReplyRoute?.target;
17560
19879
  const requestId = msg.requestId;
17561
19880
  const fleetRequestId = msg.fleetRequestId;
17562
19881
  const senderSessionName = msg.senderSessionName;
@@ -17592,7 +19911,7 @@ export class FleetManager {
17592
19911
  }
17593
19912
  try {
17594
19913
  if (this.requestContextPolicy)
17595
- requireRequestContextPolicy(this, instanceName, tool === "hub_room_status" ? "hub_room_list" : tool, args, originatingCall?.admission);
19914
+ requireRequestContextPolicy(this, instanceName, tool === "hub_room_status" ? "hub_room_list" : tool, args, originatingCall?.admission, originatingCall?.replyRoute);
17596
19915
  }
17597
19916
  catch (error) {
17598
19917
  respond(null, error.message);
@@ -17647,7 +19966,7 @@ export class FleetManager {
17647
19966
  if (tool === "react" && !this.classicChannels?.getAll?.().some(room => room.instanceName === instanceName && room.restrictedMode === true) && typeof args.message_id === "string" && isWebMessageId(args.message_id)) {
17648
19967
  // The socket's own instance, never a session name the caller wrote itself (as checkToolPermission: it was not
17649
19968
  // identified) — a channel tool's call from a daemon carries none anyway (#2310 review).
17650
- const r = await this.reactToWebMessage(instanceName, args.message_id, args.emoji);
19969
+ const r = await this.reactToWebMessage(instanceName, args.message_id, args.emoji, ownedReplyRoute);
17651
19970
  if (r.ok)
17652
19971
  respond("ok");
17653
19972
  else
@@ -17656,7 +19975,7 @@ export class FleetManager {
17656
19975
  }
17657
19976
  // A fleet with no chat platform at all is driven from the web dashboard alone: a reply has nowhere
17658
19977
  // else to go, and "retry shortly" would have the agent retry forever. It goes to the web chat.
17659
- const webOnlyReply = tool === "reply" && this.worlds.size === 0 && this.isWebOnlyFleet();
19978
+ const webOnlyReply = tool === "reply" && (ownedReplyTarget ? !ownedReplyTarget.chatId : this.worlds.size === 0 && this.isWebOnlyFleet());
17660
19979
  if (this.worlds.size === 0 && !webOnlyReply) {
17661
19980
  // #2910: on a web-only fleet there will never be an adapter — say so, so the agent does not retry forever.
17662
19981
  respond(null, this.isWebOnlyFleet()
@@ -17677,8 +19996,10 @@ export class FleetManager {
17677
19996
  downloadAttachment: (id) => this.downloadRoomAttachment(instanceName, id) } : {}),
17678
19997
  replyFinished: () => replyBookkeeping,
17679
19998
  beforeSend: () => {
17680
- if (originatingCall && !originatingCall.current())
19999
+ if (originatingCall && !originatingCall.current() || ownedReplyRoute && !ownedReplyRoute.current())
17681
20000
  throw Error("Originating request context is no longer current");
20001
+ if (ownedReplyTarget?.chatId && ownedReplyTarget.adapterId && (this.worlds.get(ownedReplyTarget.adapterId) !== contextWorld || contextWorld?.adapter !== outAdapter))
20002
+ throw new RequestContextPolicyError("stale");
17682
20003
  const current = this.restrictedClassicRouting(instanceName);
17683
20004
  if (restrictedRoute && (!current || current.adapterId !== restrictedRoute.adapterId || current.chatId !== restrictedRoute.chatId
17684
20005
  || current.threadId !== restrictedRoute.threadId || this.contactGeneration(instanceName) !== restrictedIncarnation
@@ -17688,7 +20009,7 @@ export class FleetManager {
17688
20009
  } : {};
17689
20010
  // Resolve threadId: use sender's topic_id if sender is a known fleet instance,
17690
20011
  // fall back to general topic if sender is unknown, or IPC owner if no sender.
17691
- const senderInstanceName = !restrictedRoute && senderSessionName && this.fleetConfig?.instances[senderSessionName]
20012
+ const senderInstanceName = !ownedReplyRoute && !restrictedRoute && senderSessionName && this.fleetConfig?.instances[senderSessionName]
17692
20013
  ? senderSessionName
17693
20014
  : null;
17694
20015
  const routingConfig = senderInstanceName
@@ -17700,18 +20021,15 @@ export class FleetManager {
17700
20021
  // ids are scoped to that bot/world; routing a secondary-world id through the
17701
20022
  // primary adapter produces a 404. Instance binding remains the compatibility
17702
20023
  // fallback for older daemons and calls without a live/persisted context.
17703
- const contextAdapterId = restrictedRoute?.adapterId ?? (typeof msg.adapterId === "string" && msg.adapterId
17704
- ? msg.adapterId
17705
- : undefined);
20024
+ const contextAdapterId = ownedReplyTarget ? ownedReplyTarget.chatId ? ownedReplyTarget.adapterId : undefined
20025
+ : restrictedRoute?.adapterId ?? (typeof msg.adapterId === "string" && msg.adapterId ? msg.adapterId : undefined);
17706
20026
  const contextWorld = contextAdapterId ? this.worlds.get(contextAdapterId) : undefined;
17707
20027
  if (contextAdapterId && !contextWorld) {
17708
20028
  respond(null, `Adapter world unavailable: ${contextAdapterId}`);
17709
20029
  return;
17710
20030
  }
17711
- const outAdapter = contextWorld?.adapter
17712
- ?? this.getAdapterForInstance(senderInstanceName ?? instanceName)
17713
- ?? this.adapter
17714
- ?? (webOnlyReply ? WEB_ONLY_REPLY_SINK : null);
20031
+ const outAdapter = ownedReplyTarget ? webOnlyReply ? WEB_ONLY_REPLY_SINK : contextWorld?.adapter
20032
+ : contextWorld?.adapter ?? this.getAdapterForInstance(senderInstanceName ?? instanceName) ?? this.adapter ?? (webOnlyReply ? WEB_ONLY_REPLY_SINK : null);
17715
20033
  if (!outAdapter) {
17716
20034
  respond(null, "No adapter available");
17717
20035
  return;
@@ -17744,6 +20062,18 @@ export class FleetManager {
17744
20062
  else
17745
20063
  delete args.thread_id;
17746
20064
  }
20065
+ if (ownedReplyTarget) {
20066
+ if (!ownedReplyRoute.current()) {
20067
+ respond(null, "Originating request context is no longer current");
20068
+ return;
20069
+ }
20070
+ args.chat_id = ownedReplyTarget.chatId;
20071
+ threadId = ownedReplyTarget.threadId;
20072
+ if (threadId)
20073
+ args.thread_id = threadId;
20074
+ else
20075
+ delete args.thread_id;
20076
+ }
17747
20077
  // Reply dedup: retries land here when the agent was told a send failed
17748
20078
  // (daemon budget elapsed, shell tool killed) while the adapter send was
17749
20079
  // still in flight and about to succeed. One real send, everyone gets its
@@ -18436,8 +20766,7 @@ export class FleetManager {
18436
20766
  }
18437
20767
  if (type === "fleet_list_emojis" || type === "fleet_set_persona_emoji" || type === "fleet_preview_emojis"
18438
20768
  || type === "fleet_list_stickers" || type === "fleet_preview_stickers") {
18439
- this.handlePersonaEmoji(name, msg);
18440
- return;
20769
+ return this.handlePersonaEmoji(name, msg);
18441
20770
  }
18442
20771
  if (type === "fleet_get_web_theme" || type === "fleet_set_web_theme" || type === "fleet_set_web_theme_asset" || type === "fleet_reset_web_theme"
18443
20772
  || type === "fleet_get_web_appearance" || type === "fleet_preview_web_appearance"
@@ -18490,7 +20819,7 @@ export class FleetManager {
18490
20819
  : msg.type === "fleet_list_stickers" ? this.listStickersFor(instanceName, payload)
18491
20820
  : msg.type === "fleet_preview_stickers" ? this.previewStickers(instanceName, payload)
18492
20821
  : this.setPersonaEmoji(instanceName, payload);
18493
- op.then((r) => typeof r.error === "string"
20822
+ return op.then((r) => typeof r.error === "string"
18494
20823
  ? ipc.send({ type: "fleet_persona_emoji_response", fleetRequestId, error: r.error })
18495
20824
  : ipc.send({ type: "fleet_persona_emoji_response", fleetRequestId, result: r }), (err) => ipc.send({ type: "fleet_persona_emoji_response", fleetRequestId, error: err.message }));
18496
20825
  }
@@ -22245,7 +24574,15 @@ export class FleetManager {
22245
24574
  }
22246
24575
  /** The list for the web: every world's items, and those of instances with no world (#1386 §5.0). */
22247
24576
  needsYouItems() {
22248
- return this.needsYou?.webItems() ?? [];
24577
+ const items = this.needsYou?.webItems?.() ?? [];
24578
+ const cutover = this.requestContextControl?.snapshot();
24579
+ if (cutover && (cutover.attempted || cutover.everActivated) && (cutover.phase === "draining" || cutover.enableFailed === true || cutover.blockers.length > 0)) {
24580
+ this.requestContextAttentionSince ??= Date.now();
24581
+ return [...items, { id: "request-context-cutover", type: "config", instance: "", reason: "request_context_cutover",
24582
+ detail: "", since: this.requestContextAttentionSince, requestContextCutover: cutover }];
24583
+ }
24584
+ this.requestContextAttentionSince = undefined;
24585
+ return items;
22249
24586
  }
22250
24587
  /** Enabled member composition supplies held-work readers and explicit owner retry/close operations. */
22251
24588
  attachHubExecutionAttention(read, retry = null, close = undefined) {
@@ -24133,7 +26470,7 @@ export class FleetManager {
24133
26470
  // #1827: a /steer or /btw reaches the agent as the web person who wrote it.
24134
26471
  chatId: this.getGroupIdForInstance(instance) || "", messageId: newWebMessageId(),
24135
26472
  username: opts.person?.name ?? WEB_NAME_FALLBACK, userId: opts.person?.userId ?? WEB_NAME_FALLBACK,
24136
- threadId: topicId != null ? String(topicId) : undefined, adapterId: this.getAdapterForInstance(instance)?.id ?? "", source: "web", humanOrigin: webHumanOrigin(true, opts.authority, opts.identity),
26473
+ threadId: topicId != null ? String(topicId) : undefined, adapterId: this.getAdapterForInstance(instance)?.id ?? "", source: "web", humanOrigin: webHumanOrigin(true, opts.authority, opts.identity, !!opts.guest, opts.sessionHandle),
24137
26474
  ...(opts.guest ? { webGuest: true } : {}), // #2855: a guest's /steer or /btw reaches the agent as a guest's
24138
26475
  };
24139
26476
  };
@@ -28273,10 +30610,10 @@ export class FleetManager {
28273
30610
  static INSTRUCTIONS_FILENAME = Object.fromEntries(Object.entries(INSTRUCTIONS_FILE).map(([id, e]) => [id, e.file]));
28274
30611
  static GENERAL_INSTRUCTIONS = GENERAL_ROLE_INSTRUCTIONS;
28275
30612
  /** Ensure the general instance has its project instructions file + knowledge */
28276
- ensureGeneralInstructions(workDir, backendName, instanceName) {
28277
- measureSyncWork("fleet.generalInstructions", () => this.ensureGeneralInstructionsSync(workDir, backendName, instanceName));
30613
+ ensureGeneralInstructions(workDir, backendName, instanceName, mode = requestContextInstructionMode(this.requestContextPolicy)) {
30614
+ measureSyncWork("fleet.generalInstructions", () => this.ensureGeneralInstructionsSync(workDir, backendName, instanceName, mode));
28278
30615
  }
28279
- ensureGeneralInstructionsSync(workDir, backendName, instanceName) {
30616
+ ensureGeneralInstructionsSync(workDir, backendName, instanceName, mode = requestContextInstructionMode(this.requestContextPolicy)) {
28280
30617
  const backend = backendName ?? "claude-code";
28281
30618
  workDir = this.resolveKnowledgeWorkDir(workDir, backend, instanceName);
28282
30619
  // Board 0340ec89: General's file from before, under the lowercase name agy never read, becomes the one it reads.
@@ -28312,7 +30649,7 @@ export class FleetManager {
28312
30649
  }
28313
30650
  }
28314
30651
  // Sync bundled knowledge files to general's steering and skills directories.
28315
- this.syncGeneralKnowledge(workDir, backend);
30652
+ this.syncGeneralKnowledge(workDir, backend, mode);
28316
30653
  }
28317
30654
  /** Resolve the workspace path a backend actually uses before publishing knowledge. */
28318
30655
  resolveKnowledgeWorkDir(workDir, backend, instanceName) {
@@ -28349,16 +30686,16 @@ export class FleetManager {
28349
30686
  "antigravity": [".agents", "skills"],
28350
30687
  };
28351
30688
  /** Copy general-knowledge steering + all role-eligible skills to General. */
28352
- syncGeneralKnowledge(workDir, backend) {
30689
+ syncGeneralKnowledge(workDir, backend, mode = requestContextInstructionMode(this.requestContextPolicy)) {
28353
30690
  const knowledgeDir = join(dirname(fileURLToPath(import.meta.url)), "general-knowledge");
28354
30691
  if (!existsSync(knowledgeDir))
28355
30692
  return;
28356
- this.syncGeneralSteering(workDir, backend, join(knowledgeDir, "steering"));
28357
- this.syncRoleSkills(workDir, backend, "general", knowledgeDir);
30693
+ this.syncGeneralSteering(workDir, backend, join(knowledgeDir, "steering"), mode);
30694
+ this.syncRoleSkills(workDir, backend, "general", knowledgeDir, false, mode);
28358
30695
  this.logger.debug({ knowledgeDir, workDir, backend }, "Synced general knowledge files");
28359
30696
  }
28360
30697
  /** Publish only the bundled skills eligible for an instance role. */
28361
- syncRoleSkills(workDir, backend, role, knowledgeDir, restrictedClassic = false) {
30698
+ syncRoleSkills(workDir, backend, role, knowledgeDir, restrictedClassic = false, mode = requestContextInstructionMode(this.requestContextPolicy)) {
28362
30699
  const skillSegments = FleetManager.SKILLS_DIR_SEGMENTS[backend];
28363
30700
  if (!skillSegments)
28364
30701
  return;
@@ -28373,7 +30710,7 @@ export class FleetManager {
28373
30710
  this.syncManagedSkills(join(workDir, ...skillSegments), join(root, "skills"), role, adoptLegacyUnmanaged,
28374
30711
  // #2163: a Classic bot's skills folder (or a skill in it) may be a link out of its workspace; every path is
28375
30712
  // checked where it really lands, just before it is written.
28376
- role === "classic" ? (path) => insideManagedWorkspaces(path) : undefined, role === "classic" && restrictedClassic ? new Set(["persona-emoji", "web-appearance"]) : undefined);
30713
+ role === "classic" ? (path) => insideManagedWorkspaces(path) : undefined, role === "classic" && restrictedClassic ? new Set(["persona-emoji", "web-appearance"]) : undefined, mode);
28377
30714
  this.logger.debug({ workDir, backend, role }, "Synced role-based bundled skills");
28378
30715
  }
28379
30716
  /**
@@ -28385,7 +30722,7 @@ export class FleetManager {
28385
30722
  * sync, so rule updates reach EXISTING workspaces; everything the user
28386
30723
  * wrote outside the markers is preserved byte-for-byte.
28387
30724
  */
28388
- syncGeneralSteering(workDir, backend, srcSteering) {
30725
+ syncGeneralSteering(workDir, backend, srcSteering, mode = requestContextInstructionMode(this.requestContextPolicy)) {
28389
30726
  if (!existsSync(srcSteering))
28390
30727
  return;
28391
30728
  const files = readdirSync(srcSteering).filter(f => f.endsWith(".md")).sort();
@@ -28396,7 +30733,7 @@ export class FleetManager {
28396
30733
  mkdirSync(steeringDir, { recursive: true });
28397
30734
  for (const file of files) {
28398
30735
  const dest = join(steeringDir, file);
28399
- const newContent = readFileSync(join(srcSteering, file), "utf-8");
30736
+ const newContent = requestContextSteeringText(readFileSync(join(srcSteering, file), "utf-8"), file === "core-rules.md" ? mode : null);
28400
30737
  try {
28401
30738
  if (existsSync(dest) && readFileSync(dest, "utf-8") === newContent)
28402
30739
  continue;
@@ -28410,7 +30747,7 @@ export class FleetManager {
28410
30747
  const instructionsPath = join(workDir, filename);
28411
30748
  if (backend === "antigravity" && danglingSymlink(instructionsPath))
28412
30749
  return; // kept, not followed (#1914 review; logged above)
28413
- const body = files.map(f => readFileSync(join(srcSteering, f), "utf-8").trim()).join("\n\n");
30750
+ const body = files.map(f => requestContextSteeringText(readFileSync(join(srcSteering, f), "utf-8"), f === "core-rules.md" ? mode : null).trim()).join("\n\n");
28414
30751
  const block = `${FleetManager.STEERING_BLOCK_BEGIN}\n${body}\n${FleetManager.STEERING_BLOCK_END}`;
28415
30752
  let existing = "";
28416
30753
  try {
@@ -28500,7 +30837,7 @@ export class FleetManager {
28500
30837
  catch { /* said this time; said again next start */ }
28501
30838
  this.logger.warn({ skills: names, destSkills }, "Skipping bundled skills — skills of these names exist but were not published by AgEnD");
28502
30839
  }
28503
- syncManagedSkills(destSkills, srcSkills, role, adoptLegacyUnmanaged = false, confined, excluded) {
30840
+ syncManagedSkills(destSkills, srcSkills, role, adoptLegacyUnmanaged = false, confined, excluded, mode = null) {
28504
30841
  if (!existsSync(srcSkills))
28505
30842
  return;
28506
30843
  const refuse = (path) => {
@@ -28563,7 +30900,7 @@ export class FleetManager {
28563
30900
  continue;
28564
30901
  }
28565
30902
  managed.push(name);
28566
- const newContent = bundledSkillContents(join(srcSkills, name));
30903
+ const newContent = requestContextSkillText(name, bundledSkillContents(join(srcSkills, name)), mode);
28567
30904
  if (refuse(dest))
28568
30905
  continue;
28569
30906
  try {
@@ -31735,6 +34072,16 @@ export class FleetManager {
31735
34072
  const instanceName = classicChannels.deriveInstanceName(channelName || channelId, channelId, adapterId);
31736
34073
  clearPausedMarker(this.getInstanceDir(instanceName));
31737
34074
  const selectedBackend = isSelectableClassicBackend(backend) ? backend : undefined;
34075
+ if (requestContextPolicyInstalled(this.requestContextPolicy) && !classicChannels.get(channelId, adapterId)) {
34076
+ // Durable first-birth intent precedes the Classic registry's own save. A restart/token read cannot mint it.
34077
+ this.settleHubIncarnations();
34078
+ if (this.hubIncarnationsBroken)
34079
+ throw Error("Request work registration evidence unavailable");
34080
+ const planned = { ...DEFAULT_INSTANCE_CONFIG, ...this.fleetConfig?.defaults, backend: selectedBackend ?? this.fleetConfig?.defaults?.backend ?? "claude-code",
34081
+ working_directory: this.classicWorkspaceDir(instanceName), hubClassicIdentity: JSON.stringify([adapterId ?? "", channelId]) };
34082
+ if (!this.hubAgentIncarnation(instanceName, planned, true, true))
34083
+ throw Error("Request work registration evidence unavailable");
34084
+ }
31738
34085
  classicChannels.register(channelId, adapterId, instanceName, channelName || channelId, userId, selectedBackend, restricted);
31739
34086
  // Bind this classic instance to the bot that started it (authoritative), so
31740
34087
  // replies/cancel go out through that bot even though every same-guild bot
@@ -31884,6 +34231,13 @@ export class FleetManager {
31884
34231
  // because we asked it to. Set synchronously — doStopAll runs to its first
31885
34232
  // await in the same tick as the signal handler, so no event can slip in.
31886
34233
  this.shuttingDown = true;
34234
+ if (this.requestContextDrainTimer)
34235
+ clearTimeout(this.requestContextDrainTimer);
34236
+ this.requestContextDrainTimer = undefined;
34237
+ if (this.requestContextCollectionTimer)
34238
+ clearInterval(this.requestContextCollectionTimer);
34239
+ this.requestContextCollectionTimer = undefined;
34240
+ this.requestContextAdmission?.changed();
31887
34241
  try {
31888
34242
  this.updateCard?.close();
31889
34243
  }
@@ -32193,6 +34547,13 @@ export class FleetManager {
32193
34547
  }
32194
34548
  // The lock contains a nonce, so an older/shutting-down process can never
32195
34549
  // remove a lock acquired by a newer fleet owner.
34550
+ if (this.requestContextBoot)
34551
+ try {
34552
+ await this.resetStoppedRequestContextAssembly();
34553
+ }
34554
+ catch (error) {
34555
+ this.logger.warn({ err: error.message }, "Request owners remain fenced for positive retirement before restart");
34556
+ }
32196
34557
  releaseProcessFleetLock();
32197
34558
  }
32198
34559
  /**
@@ -34373,6 +36734,7 @@ export class FleetManager {
34373
36734
  if (now !== target)
34374
36735
  continue; // the offer changed: judge the new one
34375
36736
  this.updatePreflight = mergePreflight(this.updatePreflight, fresh, now);
36737
+ void this.syncUpdateChatCard(); // M-3864 R1: the chat card's buttons follow it
34376
36738
  return;
34377
36739
  }
34378
36740
  })().finally(() => { if (this.updatePreflightRunning === running)
@@ -34399,6 +36761,120 @@ export class FleetManager {
34399
36761
  this.updatePreflight = mergePreflight(this.updatePreflight, fresh, this.updateCheckState?.offer?.version ?? null);
34400
36762
  return preflightRefusal(fresh, origin, (key, ...args) => t(key, ...args));
34401
36763
  }
36764
+ /** M-3770 1.6: make a pre-flight fix (update-fix.ts; tests stub this, so no real loginctl runs). */
36765
+ async runUpdateFix(fix) {
36766
+ const [{ applyUpdateFix }, { defaultReadinessDeps }] = await Promise.all([import("./update-fix.js"), import("./update-readiness.js")]);
36767
+ return applyUpdateFix(fix, defaultReadinessDeps());
36768
+ }
36769
+ /**
36770
+ * M-3770 S-246: Install as a service — this install's own `agend install` (never the PATH's), started apart from this
36771
+ * fleet so it outlives it, with its words in `<home>/service-install.log`. It stops this fleet by its proof and starts
36772
+ * the service (service-install-handover.ts). Waits up to 30 s to tell a refusal (nothing stopped) from the hand-over
36773
+ * (this fleet begins to stop). Tests stub this, so nothing is installed or stopped.
36774
+ */
36775
+ async startServiceInstall() {
36776
+ const [{ spawn }, { selfCommand }, { watchServiceInstall }, { SERVICE_LOCK_TOKEN_ENV }, { DIRECT_FLEET_START_ENV }] = await Promise.all([
36777
+ import("./child-process.js"), import("./cli-entry.js"), import("./update-fix.js"), import("./service-lock.js"), import("./service-owner.js")
36778
+ ]);
36779
+ const logPath = join(this.dataDir, "service-install.log");
36780
+ const logFd = openUpdateLog(logPath, `--- agend install (web, Install as a service) ${new Date().toISOString()} ---`);
36781
+ const command = selfCommand(["install"]);
36782
+ // Its own admission to the service lock, and its own fleet start if the service can't start: none of this fleet's.
36783
+ const env = { ...process.env };
36784
+ delete env[SERVICE_LOCK_TOKEN_ENV];
36785
+ delete env[DIRECT_FLEET_START_ENV];
36786
+ let exitCode;
36787
+ const child = spawn(command.command, command.args, {
36788
+ detached: true, stdio: ["ignore", logFd ? logFd.fd : "ignore", logFd ? logFd.fd : "ignore"], env,
36789
+ });
36790
+ if (logFd)
36791
+ closeSync(logFd.fd); // the child keeps its own copy
36792
+ child.on("exit", code => { exitCode = code; });
36793
+ child.on("error", () => { exitCode ??= -1; });
36794
+ child.unref();
36795
+ return watchServiceInstall({
36796
+ exitCode: () => exitCode, shuttingDown: () => this.shuttingDown,
36797
+ // This run's words only: from its own header on (the log keeps earlier runs above it).
36798
+ output: () => { const text = readLogTail(logPath) ?? ""; return text.slice(Math.max(0, text.lastIndexOf("--- agend install (web"))); },
36799
+ now: () => performance.now(), sleep: ms => new Promise(resolve => setTimeout(resolve, ms)), waitMs: 30_000,
36800
+ });
36801
+ }
36802
+ /**
36803
+ * M-3770 1.6: POST /ui/update/fixes. The same key gets the same answer; one fix runs at a time. The local checks run
36804
+ * again first and decide whether the fix is still asked for (a page drawn from an older result never runs it); the
36805
+ * session is asked again right before it runs; the checks run once more after it, and the page gets that result.
36806
+ */
36807
+ fixUpdateOnce(key, person, fix, stillAllowed) {
36808
+ // Scoped to the person and the fix (#4557 review): one admin's key never replays another's answer.
36809
+ const slot = JSON.stringify([person, fix, key]);
36810
+ const seen = this.updateFixAnswers.get(slot);
36811
+ if (seen)
36812
+ return seen;
36813
+ const answer = this.updateFixChain.then(() => this.fixUpdateNow(person, fix, stillAllowed));
36814
+ this.updateFixChain = answer.then(() => undefined, () => undefined);
36815
+ this.updateFixAnswers.set(slot, answer);
36816
+ if (this.updateFixAnswers.size > 32)
36817
+ this.updateFixAnswers.delete(this.updateFixAnswers.keys().next().value);
36818
+ return answer;
36819
+ }
36820
+ async fixUpdateNow(person, fix, stillAllowed) {
36821
+ const [{ mergePreflight }, { fixOffered }] = await Promise.all([import("./update-readiness.js"), import("./update-fix.js")]);
36822
+ const local = async () => {
36823
+ try {
36824
+ const fresh = await this.probeUpdatePreflight({ localOnly: true });
36825
+ this.updatePreflight = mergePreflight(this.updatePreflight, fresh, this.updateCheckState?.offer?.version ?? null);
36826
+ return fresh;
36827
+ }
36828
+ catch (err) {
36829
+ this.logger.warn({ err }, "Update pre-flight could not run for a fix");
36830
+ return null;
36831
+ }
36832
+ };
36833
+ const before = await local();
36834
+ if (!before)
36835
+ return { status: 503, body: { error: "preflight_unavailable", preflight: this.updatePreflight } };
36836
+ if (!fixOffered(before, fix))
36837
+ return { status: 409, body: { error: "not_needed", preflight: this.updatePreflight } };
36838
+ if (this.shuttingDown || !stillAllowed())
36839
+ return { status: 403, body: { error: "update_needs_an_admin_session" } };
36840
+ if (fix === "service") {
36841
+ // S-246: the hand-over to the service manager. 202 { restarting } once this fleet begins to stop; 202 { pending } when
36842
+ // the command still runs after the wait (nothing may have stopped yet, and it can still refuse: the page says so and
36843
+ // looks again, never claiming a restart — #4564 review); 422 with the command's own words when it refused (nothing was
36844
+ // stopped) or failed (the fleet was started again).
36845
+ let result;
36846
+ try {
36847
+ result = await this.startServiceInstall();
36848
+ }
36849
+ catch (err) {
36850
+ this.logger.warn({ err }, "Install as a service could not start");
36851
+ result = { kind: "failed", reason: "agend install could not start" };
36852
+ }
36853
+ this.logger.info({ person, fix, result: result.kind }, "web: update pre-flight fix");
36854
+ if (result.kind === "restarting")
36855
+ return { status: 202, body: { restarting: true } };
36856
+ await local();
36857
+ if (result.kind === "pending")
36858
+ return { status: 202, body: { pending: true, preflight: this.updatePreflight } };
36859
+ if (result.kind !== "failed")
36860
+ return { status: 200, body: { preflight: this.updatePreflight } };
36861
+ const [{ serviceInstallCause }, { installRunsOnWsl }] = await Promise.all([import("./update-fix.js"), import("./install-user-systemd.js")]);
36862
+ const cause = serviceInstallCause(result.reason);
36863
+ // On WSL the user-manager cause has its own known fix (wsl --update); elsewhere the page names the generic check (#4564 look).
36864
+ const where = cause === "user-manager" && installRunsOnWsl() ? "wsl" : null;
36865
+ return { status: 422, body: { error: "fix_failed", reason: result.reason, cause, ...(where ? { where } : {}), preflight: this.updatePreflight } };
36866
+ }
36867
+ let ok = false;
36868
+ try {
36869
+ ok = (await this.runUpdateFix(fix)).ok;
36870
+ }
36871
+ catch (err) {
36872
+ this.logger.warn({ err, fix }, "Update pre-flight fix failed");
36873
+ }
36874
+ this.logger.info({ person, fix, ok }, "web: update pre-flight fix");
36875
+ await local();
36876
+ return ok ? { status: 200, body: { preflight: this.updatePreflight } } : { status: 422, body: { error: "fix_failed", preflight: this.updatePreflight } };
36877
+ }
34402
36878
  ensureUpdateCard() {
34403
36879
  if (this.updateCard)
34404
36880
  return this.updateCard;
@@ -34507,7 +36983,7 @@ export class FleetManager {
34507
36983
  }
34508
36984
  catch { /* unknown */ }
34509
36985
  const pinned = !!resolveUpdates(this.fleetConfig?.updates).pin;
34510
- const reply = updateOfferReply(this.updateOfferView(), current, pinned);
36986
+ const reply = updateOfferReply(this.updateOfferView(), current, pinned, this.usageZone());
34511
36987
  return t(reply.key, ...reply.args);
34512
36988
  }
34513
36989
  refuseImmediateUpdate() {
@@ -34598,6 +37074,7 @@ export class FleetManager {
34598
37074
  updateLog: () => ({ text: readLogTail(updateLogPath(this.dataDir)), error: readUpdateProgress(this.dataDir)?.progress.error ?? null }),
34599
37075
  card: () => this.refreshUpdateCard(),
34600
37076
  answerUpdate: (key, by, body, stillAllowed) => this.ensureUpdateCard().answer(key, by, body, stillAllowed),
37077
+ fixUpdate: (key, person, fix, stillAllowed) => this.fixUpdateOnce(key, person, fix, stillAllowed),
34601
37078
  };
34602
37079
  }
34603
37080
  /** "Check for updates": look now, no chat notice. One a minute; a second ask while one runs waits for it. */