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

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 (506) hide show
  1. package/dist/agent-cli-instructions.md +2 -1
  2. package/dist/agent-cli.js +6 -0
  3. package/dist/agent-cli.js.map +1 -1
  4. package/dist/agent-endpoint.d.ts +1 -0
  5. package/dist/agent-endpoint.js +5 -0
  6. package/dist/agent-endpoint.js.map +1 -1
  7. package/dist/agent-whats-new.js +4 -0
  8. package/dist/agent-whats-new.js.map +1 -1
  9. package/dist/backend/kiro-auth-store.d.ts +15 -2
  10. package/dist/backend/kiro-auth-store.js +64 -0
  11. package/dist/backend/kiro-auth-store.js.map +1 -1
  12. package/dist/build-provenance.json +1 -1
  13. package/dist/channel/adapters/discord.js +4 -4
  14. package/dist/channel/adapters/discord.js.map +1 -1
  15. package/dist/channel/adapters/telegram.js +3 -3
  16. package/dist/channel/adapters/telegram.js.map +1 -1
  17. package/dist/channel/ipc-bridge.d.ts +7 -0
  18. package/dist/channel/ipc-bridge.js +45 -11
  19. package/dist/channel/ipc-bridge.js.map +1 -1
  20. package/dist/channel/mcp-server.js +3 -1
  21. package/dist/channel/mcp-server.js.map +1 -1
  22. package/dist/channel/mcp-tools.js +6 -4
  23. package/dist/channel/mcp-tools.js.map +1 -1
  24. package/dist/claude-turn-boundaries.d.ts +15 -0
  25. package/dist/claude-turn-boundaries.js +88 -0
  26. package/dist/claude-turn-boundaries.js.map +1 -0
  27. package/dist/cli.js +35 -2
  28. package/dist/cli.js.map +1 -1
  29. package/dist/contact-auth-service.js +3 -0
  30. package/dist/contact-auth-service.js.map +1 -1
  31. package/dist/contact-auth-store.d.ts +16 -0
  32. package/dist/contact-auth-store.js +61 -1
  33. package/dist/contact-auth-store.js.map +1 -1
  34. package/dist/daemon.d.ts +76 -4
  35. package/dist/daemon.js +621 -115
  36. package/dist/daemon.js.map +1 -1
  37. package/dist/delivery-outbox.d.ts +145 -7
  38. package/dist/delivery-outbox.js +373 -8
  39. package/dist/delivery-outbox.js.map +1 -1
  40. package/dist/detached-fleet-stop.d.ts +40 -0
  41. package/dist/detached-fleet-stop.js +126 -0
  42. package/dist/detached-fleet-stop.js.map +1 -0
  43. package/dist/fleet-lock.d.ts +5 -0
  44. package/dist/fleet-lock.js +21 -2
  45. package/dist/fleet-lock.js.map +1 -1
  46. package/dist/fleet-manager.d.ts +499 -5
  47. package/dist/fleet-manager.js +2917 -217
  48. package/dist/fleet-manager.js.map +1 -1
  49. package/dist/fleet-windows-runtime.d.ts +39 -3
  50. package/dist/fleet-windows-runtime.js +208 -30
  51. package/dist/fleet-windows-runtime.js.map +1 -1
  52. package/dist/general-knowledge/skills/concepts/SKILL.md +5 -0
  53. package/dist/general-knowledge/skills/hub/SKILL.md +5 -1
  54. package/dist/general-knowledge/skills/task-board/SKILL.md +14 -0
  55. package/dist/general-knowledge/skills/web-dashboard/SKILL.md +96 -26
  56. package/dist/hub/admin-dashboard.js +1 -1
  57. package/dist/hub/admin-dashboard.js.map +1 -1
  58. package/dist/hub/agent-catalog.d.ts +1 -1
  59. package/dist/hub/agent-catalog.js +4 -3
  60. package/dist/hub/agent-catalog.js.map +1 -1
  61. package/dist/hub/agent-intro.d.ts +1 -1
  62. package/dist/hub/agent-intro.js +1 -1
  63. package/dist/hub/agent-intro.js.map +1 -1
  64. package/dist/hub/agent-pictures.d.ts +1 -1
  65. package/dist/hub/agent-pictures.js +4 -3
  66. package/dist/hub/agent-pictures.js.map +1 -1
  67. package/dist/hub/catalog.d.ts +2 -2
  68. package/dist/hub/catalog.js +16 -13
  69. package/dist/hub/catalog.js.map +1 -1
  70. package/dist/hub/client.js +9 -2
  71. package/dist/hub/client.js.map +1 -1
  72. package/dist/hub/compose/member.js +8 -1
  73. package/dist/hub/compose/member.js.map +1 -1
  74. package/dist/hub/compose/server.js +4 -2
  75. package/dist/hub/compose/server.js.map +1 -1
  76. package/dist/hub/fleet-updates.d.ts +2 -2
  77. package/dist/hub/fleet-updates.js +7 -5
  78. package/dist/hub/fleet-updates.js.map +1 -1
  79. package/dist/hub/fleet-versions.d.ts +1 -1
  80. package/dist/hub/fleet-versions.js +3 -2
  81. package/dist/hub/fleet-versions.js.map +1 -1
  82. package/dist/hub/http/compose.js +57 -30
  83. package/dist/hub/http/compose.js.map +1 -1
  84. package/dist/hub/http/schema.js +4 -1
  85. package/dist/hub/http/schema.js.map +1 -1
  86. package/dist/hub/join/service.d.ts +6 -0
  87. package/dist/hub/join/service.js +10 -0
  88. package/dist/hub/join/service.js.map +1 -1
  89. package/dist/hub/member/room-ask.js +2 -0
  90. package/dist/hub/member/room-ask.js.map +1 -1
  91. package/dist/hub/member/room-post.d.ts +4 -0
  92. package/dist/hub/member/room-post.js +26 -1
  93. package/dist/hub/member/room-post.js.map +1 -1
  94. package/dist/hub/protocol.d.ts +58 -0
  95. package/dist/hub/protocol.js +3 -2
  96. package/dist/hub/protocol.js.map +1 -1
  97. package/dist/hub/quota.d.ts +2 -2
  98. package/dist/hub/quota.js +6 -4
  99. package/dist/hub/quota.js.map +1 -1
  100. package/dist/hub/read-statement.d.ts +6 -0
  101. package/dist/hub/read-statement.js +33 -0
  102. package/dist/hub/read-statement.js.map +1 -0
  103. package/dist/hub/recommendations.d.ts +1 -1
  104. package/dist/hub/recommendations.js +3 -2
  105. package/dist/hub/recommendations.js.map +1 -1
  106. package/dist/hub/representative.d.ts +2 -0
  107. package/dist/hub/representative.js +8 -4
  108. package/dist/hub/representative.js.map +1 -1
  109. package/dist/hub/roles/clock.d.ts +1 -1
  110. package/dist/hub/roles/clock.js +9 -7
  111. package/dist/hub/roles/clock.js.map +1 -1
  112. package/dist/hub/roles/read.d.ts +4 -0
  113. package/dist/hub/roles/read.js +37 -7
  114. package/dist/hub/roles/read.js.map +1 -1
  115. package/dist/hub/room-history-model.d.ts +87 -0
  116. package/dist/hub/room-history-model.js +14 -0
  117. package/dist/hub/room-history-model.js.map +1 -0
  118. package/dist/hub/rooms/agents.d.ts +1 -1
  119. package/dist/hub/rooms/agents.js +3 -2
  120. package/dist/hub/rooms/agents.js.map +1 -1
  121. package/dist/hub/rooms/history.d.ts +8 -0
  122. package/dist/hub/rooms/history.js +31 -0
  123. package/dist/hub/rooms/history.js.map +1 -0
  124. package/dist/hub/rooms/schema.d.ts +2 -0
  125. package/dist/hub/rooms/schema.js +4 -0
  126. package/dist/hub/rooms/schema.js.map +1 -1
  127. package/dist/hub/rooms/service.d.ts +35 -19
  128. package/dist/hub/rooms/service.js +105 -26
  129. package/dist/hub/rooms/service.js.map +1 -1
  130. package/dist/hub/server.js +10 -3
  131. package/dist/hub/server.js.map +1 -1
  132. package/dist/hub/session-epoch.js +2 -1
  133. package/dist/hub/session-epoch.js.map +1 -1
  134. package/dist/hub/settings-directory-decision.js +14 -7
  135. package/dist/hub/settings-directory-decision.js.map +1 -1
  136. package/dist/hub/settings-member-address-decision.js +3 -2
  137. package/dist/hub/settings-member-address-decision.js.map +1 -1
  138. package/dist/hub/settings-web-address-decision.js +2 -1
  139. package/dist/hub/settings-web-address-decision.js.map +1 -1
  140. package/dist/hub/store.d.ts +5 -0
  141. package/dist/hub/store.js +28 -5
  142. package/dist/hub/store.js.map +1 -1
  143. package/dist/hub/types.d.ts +2 -2
  144. package/dist/hub-agent-incarnation-record.d.ts +24 -0
  145. package/dist/hub-agent-incarnation-record.js +46 -0
  146. package/dist/hub-agent-incarnation-record.js.map +1 -0
  147. package/dist/human-delivery-receipts.d.ts +16 -4
  148. package/dist/human-delivery-receipts.js +26 -5
  149. package/dist/human-delivery-receipts.js.map +1 -1
  150. package/dist/instance-lifecycle.d.ts +9 -3
  151. package/dist/instance-lifecycle.js +27 -10
  152. package/dist/instance-lifecycle.js.map +1 -1
  153. package/dist/instructions.d.ts +1 -1
  154. package/dist/local-pane-endpoint.d.ts +14 -0
  155. package/dist/local-pane-endpoint.js +32 -0
  156. package/dist/local-pane-endpoint.js.map +1 -1
  157. package/dist/locale.js +68 -4
  158. package/dist/locale.js.map +1 -1
  159. package/dist/native-agent-admission.js +9 -0
  160. package/dist/native-agent-admission.js.map +1 -1
  161. package/dist/native-exec-context.d.ts +11 -0
  162. package/dist/native-exec-context.js +18 -0
  163. package/dist/native-exec-context.js.map +1 -0
  164. package/dist/native-exec-input.d.ts +56 -0
  165. package/dist/native-exec-input.js +89 -0
  166. package/dist/native-exec-input.js.map +1 -0
  167. package/dist/native-mcp.d.ts +9 -1
  168. package/dist/native-mcp.js +29 -7
  169. package/dist/native-mcp.js.map +1 -1
  170. package/dist/native-pane-lifecycle.d.ts +3 -0
  171. package/dist/native-pane-lifecycle.js +2 -0
  172. package/dist/native-pane-lifecycle.js.map +1 -1
  173. package/dist/native-pane-manager.d.ts +18 -0
  174. package/dist/native-pane-manager.js +85 -8
  175. package/dist/native-pane-manager.js.map +1 -1
  176. package/dist/needs-you.d.ts +2 -1
  177. package/dist/needs-you.js.map +1 -1
  178. package/dist/outbound-handlers.d.ts +1 -0
  179. package/dist/outbound-handlers.js +9 -3
  180. package/dist/outbound-handlers.js.map +1 -1
  181. package/dist/outbound-schemas.d.ts +8 -0
  182. package/dist/outbound-schemas.js +6 -2
  183. package/dist/outbound-schemas.js.map +1 -1
  184. package/dist/public-web-gateway.js +3 -1
  185. package/dist/public-web-gateway.js.map +1 -1
  186. package/dist/recover.cjs +1 -0
  187. package/dist/reply-buttons-controller.d.ts +1 -0
  188. package/dist/reply-buttons-controller.js +1 -1
  189. package/dist/reply-buttons-controller.js.map +1 -1
  190. package/dist/request-contact-gate.d.ts +2 -0
  191. package/dist/request-contact-gate.js +8 -3
  192. package/dist/request-contact-gate.js.map +1 -1
  193. package/dist/request-context-activation.d.ts +29 -0
  194. package/dist/request-context-activation.js +85 -0
  195. package/dist/request-context-activation.js.map +1 -0
  196. package/dist/request-context-admission.d.ts +22 -0
  197. package/dist/request-context-admission.js +12 -0
  198. package/dist/request-context-admission.js.map +1 -0
  199. package/dist/request-context-boot.d.ts +35 -0
  200. package/dist/request-context-boot.js +97 -0
  201. package/dist/request-context-boot.js.map +1 -0
  202. package/dist/request-context-call.d.ts +3 -0
  203. package/dist/request-context-call.js.map +1 -1
  204. package/dist/request-context-compatibility.js +10 -2
  205. package/dist/request-context-compatibility.js.map +1 -1
  206. package/dist/request-context-continuation.d.ts +6 -0
  207. package/dist/request-context-continuation.js +24 -0
  208. package/dist/request-context-continuation.js.map +1 -0
  209. package/dist/request-context-control-api.d.ts +119 -0
  210. package/dist/request-context-control-api.js +179 -0
  211. package/dist/request-context-control-api.js.map +1 -0
  212. package/dist/request-context-control-copy.d.ts +3 -0
  213. package/dist/request-context-control-copy.js +7 -0
  214. package/dist/request-context-control-copy.js.map +1 -0
  215. package/dist/request-context-controller.d.ts +44 -0
  216. package/dist/request-context-controller.js +129 -0
  217. package/dist/request-context-controller.js.map +1 -0
  218. package/dist/request-context-delivery-resolver.d.ts +13 -0
  219. package/dist/request-context-delivery-resolver.js +30 -0
  220. package/dist/request-context-delivery-resolver.js.map +1 -0
  221. package/dist/request-context-drain-projection.d.ts +8 -0
  222. package/dist/request-context-drain-projection.js +40 -0
  223. package/dist/request-context-drain-projection.js.map +1 -0
  224. package/dist/request-context-drain.d.ts +22 -0
  225. package/dist/request-context-drain.js +139 -7
  226. package/dist/request-context-drain.js.map +1 -1
  227. package/dist/request-context-enable-offer.d.ts +13 -0
  228. package/dist/request-context-enable-offer.js +31 -0
  229. package/dist/request-context-enable-offer.js.map +1 -0
  230. package/dist/request-context-exec-owner.d.ts +39 -0
  231. package/dist/request-context-exec-owner.js +128 -0
  232. package/dist/request-context-exec-owner.js.map +1 -0
  233. package/dist/request-context-go-back-view.d.ts +1 -0
  234. package/dist/request-context-go-back-view.js +17 -0
  235. package/dist/request-context-go-back-view.js.map +1 -0
  236. package/dist/request-context-helper-readiness.d.ts +14 -0
  237. package/dist/request-context-helper-readiness.js +23 -0
  238. package/dist/request-context-helper-readiness.js.map +1 -0
  239. package/dist/request-context-helper.d.ts +20 -0
  240. package/dist/request-context-helper.js +41 -0
  241. package/dist/request-context-helper.js.map +1 -0
  242. package/dist/request-context-hub-resolver.d.ts +29 -0
  243. package/dist/request-context-hub-resolver.js +90 -0
  244. package/dist/request-context-hub-resolver.js.map +1 -0
  245. package/dist/request-context-human-resolver.d.ts +20 -0
  246. package/dist/request-context-human-resolver.js +77 -0
  247. package/dist/request-context-human-resolver.js.map +1 -0
  248. package/dist/request-context-human.d.ts +112 -0
  249. package/dist/request-context-human.js +176 -0
  250. package/dist/request-context-human.js.map +1 -0
  251. package/dist/request-context-inputs.d.ts +21 -0
  252. package/dist/request-context-inputs.js +63 -0
  253. package/dist/request-context-inputs.js.map +1 -0
  254. package/dist/request-context-installation.d.ts +117 -0
  255. package/dist/request-context-installation.js +328 -0
  256. package/dist/request-context-installation.js.map +1 -0
  257. package/dist/request-context-knowledge.d.ts +5 -0
  258. package/dist/request-context-knowledge.js +32 -0
  259. package/dist/request-context-knowledge.js.map +1 -0
  260. package/dist/request-context-migration.d.ts +11 -0
  261. package/dist/request-context-migration.js +16 -3
  262. package/dist/request-context-migration.js.map +1 -1
  263. package/dist/request-context-native-human.d.ts +20 -0
  264. package/dist/request-context-native-human.js +91 -0
  265. package/dist/request-context-native-human.js.map +1 -0
  266. package/dist/request-context-native-output.d.ts +15 -0
  267. package/dist/request-context-native-output.js +46 -0
  268. package/dist/request-context-native-output.js.map +1 -0
  269. package/dist/request-context-native-result.d.ts +15 -0
  270. package/dist/request-context-native-result.js +46 -0
  271. package/dist/request-context-native-result.js.map +1 -0
  272. package/dist/request-context-off.d.ts +22 -0
  273. package/dist/request-context-off.js +77 -0
  274. package/dist/request-context-off.js.map +1 -0
  275. package/dist/request-context-outside-label.d.ts +5 -0
  276. package/dist/request-context-outside-label.js +28 -0
  277. package/dist/request-context-outside-label.js.map +1 -0
  278. package/dist/request-context-pane.d.ts +8 -0
  279. package/dist/request-context-pane.js +19 -0
  280. package/dist/request-context-pane.js.map +1 -1
  281. package/dist/request-context-pending-work.d.ts +11 -0
  282. package/dist/request-context-pending-work.js +43 -0
  283. package/dist/request-context-pending-work.js.map +1 -0
  284. package/dist/request-context-policy.d.ts +17 -1
  285. package/dist/request-context-policy.js +84 -6
  286. package/dist/request-context-policy.js.map +1 -1
  287. package/dist/request-context-readiness.d.ts +49 -0
  288. package/dist/request-context-readiness.js +64 -0
  289. package/dist/request-context-readiness.js.map +1 -0
  290. package/dist/request-context-recovery.d.ts +6 -2
  291. package/dist/request-context-recovery.js +25 -0
  292. package/dist/request-context-recovery.js.map +1 -1
  293. package/dist/request-context-relay.d.ts +2 -2
  294. package/dist/request-context-relay.js +10 -10
  295. package/dist/request-context-relay.js.map +1 -1
  296. package/dist/request-context-reply-pending.d.ts +16 -0
  297. package/dist/request-context-reply-pending.js +77 -0
  298. package/dist/request-context-reply-pending.js.map +1 -0
  299. package/dist/request-context-resolution.d.ts +35 -0
  300. package/dist/request-context-resolution.js +86 -0
  301. package/dist/request-context-resolution.js.map +1 -0
  302. package/dist/request-context-retirement.d.ts +21 -0
  303. package/dist/request-context-retirement.js +16 -0
  304. package/dist/request-context-retirement.js.map +1 -0
  305. package/dist/request-context-start.d.ts +15 -0
  306. package/dist/request-context-start.js +2 -0
  307. package/dist/request-context-start.js.map +1 -0
  308. package/dist/request-context-turns.d.ts +1 -1
  309. package/dist/request-context-turns.js +3 -2
  310. package/dist/request-context-turns.js.map +1 -1
  311. package/dist/request-context-unproved-label.d.ts +4 -0
  312. package/dist/request-context-unproved-label.js +25 -0
  313. package/dist/request-context-unproved-label.js.map +1 -0
  314. package/dist/request-context-update-guard.d.ts +15 -0
  315. package/dist/request-context-update-guard.js +54 -0
  316. package/dist/request-context-update-guard.js.map +1 -0
  317. package/dist/request-context-work.d.ts +50 -0
  318. package/dist/request-context-work.js +178 -0
  319. package/dist/request-context-work.js.map +1 -0
  320. package/dist/request-hub-context.d.ts +1 -0
  321. package/dist/request-hub-output.d.ts +2 -0
  322. package/dist/request-hub-output.js +12 -0
  323. package/dist/request-hub-output.js.map +1 -1
  324. package/dist/retained-human-control.d.ts +11 -0
  325. package/dist/retained-human-control.js +11 -0
  326. package/dist/retained-human-control.js.map +1 -0
  327. package/dist/runtime-build-info.js +1 -1
  328. package/dist/runtime-build-info.js.map +1 -1
  329. package/dist/runtime-cli.js +1 -1
  330. package/dist/runtime-cli.js.map +1 -1
  331. package/dist/runtime-client-store.js +7 -1
  332. package/dist/runtime-client-store.js.map +1 -1
  333. package/dist/runtime-client.js +15 -3
  334. package/dist/runtime-client.js.map +1 -1
  335. package/dist/runtime-coordinator.d.ts +23 -0
  336. package/dist/runtime-coordinator.js +103 -4
  337. package/dist/runtime-coordinator.js.map +1 -1
  338. package/dist/runtime-pane-mcp.d.ts +9 -0
  339. package/dist/runtime-pane-mcp.js +22 -2
  340. package/dist/runtime-pane-mcp.js.map +1 -1
  341. package/dist/runtime-protocol.d.ts +2 -0
  342. package/dist/runtime-protocol.js.map +1 -1
  343. package/dist/runtime-update-controller.js +1 -1
  344. package/dist/runtime-update-controller.js.map +1 -1
  345. package/dist/runtime-windows-bridge.d.ts +8 -0
  346. package/dist/runtime-windows-bridge.js +50 -3
  347. package/dist/runtime-windows-bridge.js.map +1 -1
  348. package/dist/scheduler/db.js +9 -0
  349. package/dist/scheduler/db.js.map +1 -1
  350. package/dist/scheduler/task-board-text.d.ts +3 -6
  351. package/dist/scheduler/task-board-text.js +15 -10
  352. package/dist/scheduler/task-board-text.js.map +1 -1
  353. package/dist/scheduler/task-board-unread.d.ts +90 -0
  354. package/dist/scheduler/task-board-unread.js +192 -0
  355. package/dist/scheduler/task-board-unread.js.map +1 -0
  356. package/dist/scheduler/task-board.d.ts +324 -6
  357. package/dist/scheduler/task-board.js +786 -47
  358. package/dist/scheduler/task-board.js.map +1 -1
  359. package/dist/service-install-handover.d.ts +52 -0
  360. package/dist/service-install-handover.js +50 -0
  361. package/dist/service-install-handover.js.map +1 -0
  362. package/dist/service-installer.d.ts +12 -0
  363. package/dist/service-installer.js +24 -10
  364. package/dist/service-installer.js.map +1 -1
  365. package/dist/settings-api.d.ts +2 -0
  366. package/dist/settings-api.js +4 -0
  367. package/dist/settings-api.js.map +1 -1
  368. package/dist/settings-baseline.d.ts +1 -0
  369. package/dist/settings-baseline.js +5 -4
  370. package/dist/settings-baseline.js.map +1 -1
  371. package/dist/settings-confirmation.d.ts +2 -0
  372. package/dist/settings-confirmation.js +6 -0
  373. package/dist/settings-confirmation.js.map +1 -1
  374. package/dist/settings-effect.d.ts +2 -0
  375. package/dist/settings-effect.js +59 -1
  376. package/dist/settings-effect.js.map +1 -1
  377. package/dist/settings-http-confirmation.d.ts +3 -0
  378. package/dist/settings-http-confirmation.js +29 -0
  379. package/dist/settings-http-confirmation.js.map +1 -1
  380. package/dist/settings-route-lifetime.d.ts +3 -1
  381. package/dist/settings-route-lifetime.js +15 -5
  382. package/dist/settings-route-lifetime.js.map +1 -1
  383. package/dist/settings-transaction.d.ts +3 -2
  384. package/dist/settings-transaction.js.map +1 -1
  385. package/dist/task-board-tool.js +24 -3
  386. package/dist/task-board-tool.js.map +1 -1
  387. package/dist/task-board-waker.d.ts +53 -2
  388. package/dist/task-board-waker.js +183 -12
  389. package/dist/task-board-waker.js.map +1 -1
  390. package/dist/tips.js +1 -1
  391. package/dist/tips.js.map +1 -1
  392. package/dist/tool-permissions.js +3 -3
  393. package/dist/tool-permissions.js.map +1 -1
  394. package/dist/tool-receipt-output.d.ts +6 -6
  395. package/dist/transcript-monitor.d.ts +6 -1
  396. package/dist/transcript-monitor.js +59 -4
  397. package/dist/transcript-monitor.js.map +1 -1
  398. package/dist/transcript-turns.d.ts +3 -0
  399. package/dist/transcript-turns.js +5 -0
  400. package/dist/transcript-turns.js.map +1 -1
  401. package/dist/turn-reply-guard.d.ts +16 -1
  402. package/dist/turn-reply-guard.js +20 -2
  403. package/dist/turn-reply-guard.js.map +1 -1
  404. package/dist/ui/app.html +2 -2
  405. package/dist/ui/contact-auth-strings.js +6 -6
  406. package/dist/ui/contact-authorizations.js +19 -1
  407. package/dist/ui/contact-grant-editor.js +71 -11
  408. package/dist/ui/contact-needs.js +27 -8
  409. package/dist/ui/contact-permissions.js +25 -8
  410. package/dist/ui/contact-tool-groups.js +1 -1
  411. package/dist/ui/fleet-task-activity.js +164 -24
  412. package/dist/ui/fleet-task-card.js +77 -13
  413. package/dist/ui/fleet-task-common.js +14 -0
  414. package/dist/ui/fleet-task-flow.js +353 -0
  415. package/dist/ui/fleet-task-md.js +1 -1
  416. package/dist/ui/fleet-task-run.js +98 -22
  417. package/dist/ui/fleet-task-thread.js +245 -0
  418. package/dist/ui/fleet-task-unread.js +100 -0
  419. package/dist/ui/fleet-task-view.js +6 -5
  420. package/dist/ui/fleet-task-wake.js +140 -0
  421. package/dist/ui/fleet-tasks.js +13 -6
  422. package/dist/ui/hub-client.js +3 -0
  423. package/dist/ui/hub-room-members.js +4 -2
  424. package/dist/ui/hub-room-settings-strings.js +8 -0
  425. package/dist/ui/hub-room-settings.js +32 -0
  426. package/dist/ui/hub-room-thread.js +7 -1
  427. package/dist/ui/icons/hub-apple-touch-icon.png +0 -0
  428. package/dist/ui/icons/hub-favicon.ico +0 -0
  429. package/dist/ui/icons/hub-favicon.svg +10 -0
  430. package/dist/ui/icons/hub-icon-192.png +0 -0
  431. package/dist/ui/icons/hub-icon-512.png +0 -0
  432. package/dist/ui/icons/hub-icon-maskable-192.png +0 -0
  433. package/dist/ui/icons/hub-icon-maskable-512.png +0 -0
  434. package/dist/ui/icons/hub-maskable.svg +12 -0
  435. package/dist/ui/panel-hub.js +14 -3
  436. package/dist/ui/panel-needs.js +2 -1
  437. package/dist/ui/panel-settings.js +2 -1
  438. package/dist/ui/panel-windows-cli.js +2 -2
  439. package/dist/ui/request-contact-card.js +287 -0
  440. package/dist/ui/request-contact-client.js +83 -0
  441. package/dist/ui/request-contact-page.js +78 -0
  442. package/dist/ui/request-context-control.js +209 -0
  443. package/dist/ui/settings-registry.js +2 -0
  444. package/dist/ui/settings-update.js +3 -2
  445. package/dist/ui/shared/access-overview.css +1 -1
  446. package/dist/ui/shared/app-i18n.js +2 -2
  447. package/dist/ui/shared/app-install.js +2 -2
  448. package/dist/ui/shared/app-shell.js +17 -4
  449. package/dist/ui/shared/app-stream.js +4 -1
  450. package/dist/ui/shared/app-update.js +2 -1
  451. package/dist/ui/shared/app.css +101 -10
  452. package/dist/ui/shared/app.js +19 -2
  453. package/dist/ui/shared/task-board.css +164 -0
  454. package/dist/ui/shared/ui-icons.js +3 -0
  455. package/dist/ui/shared/ui-states.js +6 -0
  456. package/dist/ui/shared/update-card-ui.js +178 -11
  457. package/dist/ui/shared/view-strings.js +18 -0
  458. package/dist/ui/shared/web-authorize.js +1 -1
  459. package/dist/ui/task-unread.js +70 -0
  460. package/dist/ui/windows-cli-catalog.js +33 -6
  461. package/dist/update-card.d.ts +1 -1
  462. package/dist/update-card.js +7 -7
  463. package/dist/update-card.js.map +1 -1
  464. package/dist/update-fix.d.ts +66 -0
  465. package/dist/update-fix.js +67 -0
  466. package/dist/update-fix.js.map +1 -0
  467. package/dist/update-goback.js +15 -3
  468. package/dist/update-goback.js.map +1 -1
  469. package/dist/update-readiness.d.ts +2 -0
  470. package/dist/update-readiness.js +5 -1
  471. package/dist/update-readiness.js.map +1 -1
  472. package/dist/update-snapshot-scope.js +1 -0
  473. package/dist/update-snapshot-scope.js.map +1 -1
  474. package/dist/usage/i18n-keys.d.ts +1 -1
  475. package/dist/usage/i18n-keys.js +9 -0
  476. package/dist/usage/i18n-keys.js.map +1 -1
  477. package/dist/usage/providers.d.ts +3 -11
  478. package/dist/usage/providers.js +93 -131
  479. package/dist/usage/providers.js.map +1 -1
  480. package/dist/web-api.d.ts +49 -1
  481. package/dist/web-api.js +234 -13
  482. package/dist/web-api.js.map +1 -1
  483. package/dist/web-chat-history.d.ts +2 -0
  484. package/dist/web-chat-history.js.map +1 -1
  485. package/dist/web-icons.d.ts +9 -3
  486. package/dist/web-icons.js +62 -5
  487. package/dist/web-icons.js.map +1 -1
  488. package/dist/web-update.d.ts +9 -0
  489. package/dist/windows-agents.d.ts +24 -2
  490. package/dist/windows-agents.js +110 -4
  491. package/dist/windows-agents.js.map +1 -1
  492. package/dist/windows-cli-api.js +4 -2
  493. package/dist/windows-cli-api.js.map +1 -1
  494. package/dist/windows-cli-worker.js +9 -1
  495. package/dist/windows-cli-worker.js.map +1 -1
  496. package/dist/windows-cli.d.ts +55 -1
  497. package/dist/windows-cli.js +147 -17
  498. package/dist/windows-cli.js.map +1 -1
  499. package/dist/windows-shortcuts.d.ts +3 -22
  500. package/dist/windows-shortcuts.js +5 -45
  501. package/dist/windows-shortcuts.js.map +1 -1
  502. package/dist/workflow-templates/default.md +3 -2
  503. package/dist/wsl-host.d.ts +52 -0
  504. package/dist/wsl-host.js +97 -0
  505. package/dist/wsl-host.js.map +1 -0
  506. package/package.json +1 -1
@@ -1,6 +1,33 @@
1
+ import { cacheRetainedUnavailable } from "./update-retained.js";
2
+ import { projectRequestContextWork } from "./request-context-drain-projection.js";
3
+ import { createRequire } from "node:module";
4
+ import { RequestContextController } from "./request-context-controller.js";
5
+ import { captureRequestContextEnableOffer } from "./request-context-enable-offer.js";
6
+ import { acquireRequestContextActivationLease, requestContextUpdateSettled } from "./request-context-update-guard.js";
7
+ import { installPrefixOf } from "./home-update-lock.js";
8
+ import { requestContextEnabledNotice } from "./request-context-control-copy.js";
9
+ import { createRequestContextExecOwner } from "./request-context-exec-owner.js";
10
+ import { makeRequestContextRelay } from "./request-context-relay.js";
11
+ import { rotateHubAgentIncarnation, forgetHubAgentIncarnation, requestWorkRegistrationEvidence } from "./hub-agent-incarnation-record.js";
12
+ import { projectRequestContextNativeOutput } from "./request-context-native-output.js";
13
+ import { validateNativeExecInputProof } from "./native-exec-input.js";
14
+ import { admitRequestContextNativeResult } from "./request-context-native-result.js";
15
+ import { RequestContextLocalTurns } from "./request-context-turns.js";
16
+ import { RequestHubInputResolver } from "./request-context-hub-resolver.js";
17
+ import { makeRequestDeliveryInputResolver } from "./request-context-delivery-resolver.js";
18
+ import { makeRequestHumanInputResolver, requestHumanReplyTarget } from "./request-context-human-resolver.js";
19
+ import { markRetainedHumanControl, retainedHumanControl } from "./retained-human-control.js";
20
+ import { requestContextDigest } from "./request-context-store.js";
21
+ import { RETIRABLE_LEGACY_DISPOSITIONS } from "./request-context-migration.js";
22
+ import { RequestContextBoot, readRequestContextBootState } from "./request-context-boot.js";
23
+ import { RequestContextPreparedWork } from "./request-context-work.js";
24
+ import { requestContextSkillText, requestContextSteeringText } from "./request-context-knowledge.js";
25
+ import { requestDeliveryContinuation } from "./request-context-continuation.js";
26
+ import { runWithRequestContextAdmission } from "./request-context-admission.js";
27
+ import { RequestContextPendingWork } from "./request-context-pending-work.js";
1
28
  import { requestDeliveryView, requestContextDisplayView } from "./request-context-view.js";
2
29
  import { captureRequestHubOutput } from "./request-hub-output.js";
3
- import { assertRequestContextOperation, requireRequestContextPolicy, RequestContextPolicyError } from "./request-context-policy.js";
30
+ import { assertRequestContextOperation, assertRequestHubContactImage, requireRequestContextPolicy, requestContextInstructionMode, requestContextPolicyInstalled, requestContextInstalledMode, RequestContextPolicyError } from "./request-context-policy.js";
4
31
  import { permitWebContinuation } from "./web-continuation.js";
5
32
  import { nativeContactCardText, nativeContactOutcome, nativeContactPrincipal, nativeDecisionFailure } from "./request-contact-native.js";
6
33
  import { RequestContextReferenceMap } from "./request-context-fence.js";
@@ -26,7 +53,7 @@ import { changeIdleClaudeCredential } from "./claude-credential-change.js";
26
53
  import { readClaudeCredentialSelection, claudeSubscriptionSuppressed } from "./claude-credential-launch.js";
27
54
  import { ClaudeCredentialVault, ClaudeCredentialError } from "./claude-credential-vault.js";
28
55
  import { withHubRoomReplyWarning } from "./hub-room-reply-warning.js";
29
- import { ContactAuthService } from "./contact-auth-service.js";
56
+ import { ContactAuthService, ContactHeldError } from "./contact-auth-service.js";
30
57
  import { stageContactFiles } from "./contact-auth-files.js";
31
58
  import { ContactOriginClearSchema, ContactPermissionsSchema, sameContactPerson } from "./contact-auth-policy.js";
32
59
  import { CLASSIC_RESTRICTED_TOOLS } from "./contact-auth-types.js";
@@ -41,7 +68,7 @@ import { GENERAL_ROLE_INSTRUCTIONS } from "./general-role.js";
41
68
  import { placeGeneralRole } from "./general-role-block.js";
42
69
  import { NativePaneRecoveryError } from "./native-pane-recovery.js";
43
70
  import { nativePaneToolAvailable, nativePaneToolRefusal } from "./native-pane-tools.js";
44
- import { windowsAgentsFor } from "./windows-agents.js";
71
+ import { WindowsAgents, windowsAgentsFor } from "./windows-agents.js";
45
72
  import { AgentRuntimeChanges } from "./agent-runtime-change.js";
46
73
  import { SubagentService } from "./subagent-service.js";
47
74
  import { QuotaNotices } from "./usage/quota-notices.js";
@@ -57,7 +84,7 @@ import { loginNoticeMode, normalizeNoticeDelivery, setNoticeMode } from "./notic
57
84
  import { DEFAULT_REPLY_TRIGGERS } from "./reply-triggers.js";
58
85
  import { WorkingRecoveryCoordinator, WORKING_RECOVERY_KIND, buildWorkingRecoveryPrompt } from "./working-recovery.js";
59
86
  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";
87
+ import { humanOwnerObjectId, admittedHumanWebIngress, admittedNativeHumanIngress, webHumanOrigin, isWebSessionIdentity } from "./human-delivery-receipts.js";
61
88
  import { SettingsBaselines } from "./settings-baseline.js";
62
89
  import { hubPilotTrustSettings } from "./hub-pilot-trust-settings.js";
63
90
  import { hubMembershipSettings } from "./hub-membership-settings.js";
@@ -173,7 +200,7 @@ import { processAttachments } from "./channel/attachment-handler.js";
173
200
  import { routeToolCall } from "./channel/tool-router.js";
174
201
  import { Scheduler } from "./scheduler/index.js";
175
202
  import { boardActivity, boardCardLimit, boardCommentWakesOn, boardLeader, boardProgressWakesOn, boardToolAction } from "./task-board-tool.js";
176
- import { TaskBoardWaker } from "./task-board-waker.js";
203
+ import { TaskBoardWaker, cardsOfKey } from "./task-board-waker.js";
177
204
  import { DispatcherLiveness, LIVENESS_STARTUP_GRACE_MS, livenessSettings, questionNotices, turnQuestion } from "./dispatcher-liveness.js";
178
205
  import { TaskBoardError, waitsForPerson, wrapUpGap } from "./scheduler/task-board.js";
179
206
  import { escapeTelegramHtml, scheduleClock, scheduleRetryLabel } from "./scheduler/retry-label.js";
@@ -257,7 +284,7 @@ export function applyTaskListCap(tasks, filterAssignee, filterStatus) {
257
284
  return tasks;
258
285
  }
259
286
  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";
287
+ import { windowsCliEnabled, closeWindowsBridge, retireWindowsBridgeForRequestContext, windowsBridgeRequestContextIdle, inventoryProbed, LOCAL_WINDOWS_CLI_OFF } from "./windows-cli.js";
261
288
  import { nativeCliVersionState } from "./runtime-pane-native.js";
262
289
  import { localWindowsCliEnabled, remoteRuntimeEnabled, setConfiguredRuntimeSwitches, maxAgentsPerMachine } from "./runtime-switches.js";
263
290
  import { RuntimeInstallService } from "./runtime-install.js";
@@ -271,7 +298,7 @@ import { NativeMcpSessions } from "./native-mcp.js";
271
298
  import { nativeProviderMcpSupported } from "./windows-cli-providers.js";
272
299
  import { cachedNativeModelCatalog, refreshNativeModelCatalogAfterSignIn } from "./native-model-catalog.js";
273
300
  import { shapeWebModelCatalog } from "./web-model-groups.js";
274
- import { isWindowsInstance, isNativePaneInstance, isNativeExecInstance, WINDOWS_CONFIG_REFUSED, nativeCredentialProfile } from "./native-instance-registry.js";
301
+ import { isWindowsInstance, isNativePaneInstance, isNativeExecInstance, WINDOWS_CONFIG_REFUSED, nativeCredentialProfile, nativeAgentId } from "./native-instance-registry.js";
275
302
  import { createNativeWindowsInstance, updateNativeWindowsInstance } from "./native-instance-api.js";
276
303
  import { NativeInstanceConfigEdit, parseNativeInstanceCreate } from "./native-instance-input.js";
277
304
  import { LogService, thinkingOn } from "./log-service.js";
@@ -325,14 +352,14 @@ import { crossInstanceVisibility, runVisibilityCommand, xmsgVisibility } from ".
325
352
  import { SEARCH_RETENTION_DAYS, SearchIndex } from "./search/search-index.js";
326
353
  import { chatDoc, taskDoc, xmsgDoc } from "./search/search-docs.js";
327
354
  import { WebSettingsTools } from "./web-settings-tools.js";
328
- import { GUEST_COMMAND_RUNS, GUEST_PREF_WRITES, GUEST_SEARCHES, bindGuestRequest, guestRouteDecision } from "./web-guest-access.js";
355
+ import { GUEST_COMMAND_RUNS, GUEST_PREF_WRITES, GUEST_SEARCHES, bindGuestRequest, guestSeesMessage, guestRouteDecision } from "./web-guest-access.js";
329
356
  import { GUEST_ROOM_TICK_MS, GuestRoomMembership, guestGroupRooms } from "./web-guest-rooms.js";
330
357
  import { Delegations, TrafficLog, trafficItem } from "./fleet-traffic.js";
331
358
  import { QuiescenceBarrier, stripHumanReceipt, UPDATE_HANDBACK_COPY_KIND, UPDATE_HANDBACK_SOURCE, handbackDue, turnSource } from "./update-quiescence.js";
332
359
  import { readCurrent as readUpdateJournal } from "./update-journal.js";
333
360
  import { installedChannel, updateNoticeKey } from "./update-check.js";
334
361
  import { idleClaimOutcome, idleUpdateMessageId, UpdateOfferCard, updateAnswerLabel, updateOfferReply } from "./update-card.js";
335
- import { preflightAllows } from "./update-readiness.js";
362
+ import { preflightAllows, preflightBlocking, preflightRefusal, preflightWords } from "./update-readiness.js";
336
363
  import { inUpdatePause, resolveUpdates } from "./update-settings.js";
337
364
  import { resolveInstalledAgend, npmForRunningInstall } from "./update-dispatch.js";
338
365
  import { HUB_UPDATE_NOTICE_FILE, HUB_UPDATE_REMIND_MS, hubNoticeDue, hubNoticeKey, readHubNoticeState, writeHubNoticeState } from "./hub-update-notice.js";
@@ -377,7 +404,7 @@ import { readBackgroundWorkEndedMarker } from "./background-work-ended.js";
377
404
  import { DEFAULT_WARM_OVERFLOW, WakeCoordinator } from "./wake-coordinator.js";
378
405
  import { TargetQueueWorker } from "./target-queue-worker.js";
379
406
  import { resolveDeliveryWorkerMode } from "./types.js";
380
- import { isFleetStartCommandLine, readProcessCommandLine, releaseProcessFleetLock } from "./fleet-lock.js";
407
+ import { isFleetStartCommandLine, readProcessCommandLine, captureProcessFleetLease, releaseProcessFleetLock } from "./fleet-lock.js";
381
408
  import { isSetupComplete, markSetupComplete } from "./setup-marker.js";
382
409
  import { reapLeftoverTunnels } from "./tunnel/lease.js";
383
410
  import { buildToolPermissionsNotice } from "./tool-permissions-notice.js";
@@ -407,7 +434,7 @@ import { DeviceLoginRequests } from "./web-device-login.js";
407
434
  import { findSigninKnownEntry, addSigninKnownDevice } from "./web-signin-device.js";
408
435
  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
436
  import { evaluateSettingsRole } from "./authority/settings-role.js";
410
- import { authorityNow, classifyWebPeer, evaluateGuestIdentity, evaluateWebAuthority, HOST_OPERATOR, VERIFIED_SESSION_HOURS, webAuthorityPolicy } from "./authority/web-authority.js";
437
+ import { authorityNow, classifyWebPeer, evaluateGuestIdentity, evaluateWebAuthority, HOST_OPERATOR, hostSessionHere, VERIFIED_SESSION_HOURS, webAuthorityPolicy } from "./authority/web-authority.js";
411
438
  import { AuthorityStateStore, namedLinkLastTurnedOff } from "./authority/authority-state.js";
412
439
  import { SessionAuthorizations } from "./authority/session-authorizations.js";
413
440
  import { SessionAuthorizationRequests } from "./web-session-authorization.js";
@@ -648,6 +675,9 @@ function callbackPrefix(callbackData) {
648
675
  const colon = callbackData.indexOf(":");
649
676
  return colon === -1 ? "(none)" : callbackData.slice(0, colon + 1);
650
677
  }
678
+ // Exact server-admitted payload objects only; metadata never chooses an exec input key.
679
+ const nativeHumanInputs = new WeakMap();
680
+ const requestPayloadContinuations = new WeakMap();
651
681
  const CLASSIC_BACKEND_SELECTION_TIMEOUT_MS = 60_000;
652
682
  const CLASSIC_BACKEND_CALLBACK_PREFIX = "classic-backend:";
653
683
  const CLASSIC_MODE_CALLBACK_PREFIX = "classic-mode:";
@@ -678,6 +708,28 @@ const UPDATE_CARD_CALLBACK_PREFIX = "update-card:";
678
708
  const UPDATE_CHAT_CARD_FILE = "update-chat-card.json";
679
709
  /** The chat card's buttons live a week (Not now's own length); a newer card replaces them sooner. */
680
710
  const UPDATE_CHAT_CARD_MS = 7 * 24 * 60 * 60_000;
711
+ /**
712
+ * M-3864 R2: the chat card's Tonight: 22:00 in the fleet's zone (`defaults.scheduler.default_timezone`, else the machine's),
713
+ * 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
714
+ * that was 06:00 the next morning.
715
+ */
716
+ export function updateTonightAt(now, tz) {
717
+ let day;
718
+ try {
719
+ day = new Date(now).toLocaleString("sv-SE", { timeZone: tz, hour12: false }).slice(0, 10);
720
+ }
721
+ catch {
722
+ tz = "UTC";
723
+ day = new Date(now).toISOString().slice(0, 10);
724
+ }
725
+ // Prism #4585: the zone's offset AT the candidate instant (twice, so it settles across a DST change that day), never
726
+ // the offset at the wall clock read as UTC, which can sit on the other side of the change.
727
+ const offsetAt = (ms) => Date.parse(new Date(ms).toLocaleString("sv-SE", { timeZone: tz, hour12: false }).replace(" ", "T") + "Z") - Math.floor(ms / 1000) * 1000;
728
+ const at = (date) => { const wall = Date.parse(`${date}T22:00:00Z`); const first = wall - offsetAt(wall); return wall - offsetAt(first); };
729
+ const today = at(day);
730
+ return today - now >= 30 * 60_000 ? today : at(new Date(Date.parse(`${day}T12:00:00Z`) + 86_400_000).toISOString().slice(0, 10));
731
+ }
732
+ const UPDATE_CHAT_CARD_ALL = ["when-idle", "tonight", "not-now"];
681
733
  const HUB_SHARING_CALLBACK_PREFIX = "hub-share:";
682
734
  /** M-3680: a held contact request's card in General ("contact-ticket:" + 32 hex + ":approve" = 55 bytes, under Telegram's 64). */
683
735
  const CONTACT_TICKET_PREFIX = "contact-ticket:";
@@ -846,6 +898,634 @@ export class FleetManager {
846
898
  static sighupHandlerInstalled = false;
847
899
  /** Test seam: inject a spy to verify saveFleetConfig calls fsync. Default: fsyncSync. */
848
900
  fsyncForTest = undefined;
901
+ requestContextAdmission;
902
+ requestContextBoot;
903
+ requestContextModes;
904
+ requestContextControlBox;
905
+ requestContextDrainTimer;
906
+ requestContextAttentionSince;
907
+ requestContextCollectionTimer;
908
+ requestContextCutoverErrors = [];
909
+ requestContextRetirementProofs = new Map();
910
+ requestContextRootRetired = (_drain, root) => this.requestContextRetirementProofs.get(root)?.current() === true;
911
+ ownRequestContextModes(boot, drain, off, ports, current, retireRoot) {
912
+ const box = this.deliveryOutbox;
913
+ const modes = Object.freeze({ boot, drain, off, current, retireRoot, recordHuman: (...args) => { if (this.requestContextModes !== modes || !current() || !ports.serving)
914
+ throw Error("Request human owner unavailable"); return ports.serving.human(...args); },
915
+ publish: (ready) => {
916
+ const state = box.requestContextInstallation().read();
917
+ if (!state || !current() || !ready())
918
+ throw Error("Capable publication unavailable");
919
+ const fence = boot.publication.fence(), roots = state.mode === "draining" ? box.requestContextInstallation().drainRoots() : null;
920
+ if (!ready())
921
+ throw Error("Capable readiness changed");
922
+ boot.publication.publish(state, ports, fence, current, () => box.requestContextInstallation().read(), current, root => roots?.has(root) === true);
923
+ return state;
924
+ } });
925
+ this.requestContextModes = modes;
926
+ this.requestContextHumanAdmission = (...args) => modes.recordHuman(...args);
927
+ if (!this.requestContextCollectionTimer) {
928
+ this.requestContextCollectionTimer = setInterval(() => this.collectRequestContextRoots(), 60_000);
929
+ this.requestContextCollectionTimer.unref?.();
930
+ }
931
+ return modes;
932
+ }
933
+ requestContextFirstOn;
934
+ prepareRequestContextOwnerRegistration;
935
+ requestContextOwnerStarted;
936
+ requestContextRetainedFactory;
937
+ requestContextFactoryOwner;
938
+ prepareRequestContextStart;
939
+ configureRequestContextBeforeStart;
940
+ /** First-On owner attachment, not activation. Called only by the confirmed Settings controller.
941
+ * A failed attempt reuses this process-owned admission port; it never leaves a false capable boot installed.
942
+ */
943
+ prepareRequestContextFirstOn() {
944
+ const box = this.deliveryOutbox, lease = captureProcessFleetLease(this.dataDir), manager = this.managerBootId;
945
+ if (!box || !this.fleetConfig || !lease?.current() || this.requestContextBoot || this.requestContextPolicy || box.requestContextInstallation().read() !== null)
946
+ throw Error("First activation preparation unavailable");
947
+ const preparation = this.requestContextFirstOn ?? { boot: RequestContextBoot.prepareFirstOn(randomUUID(), lease) };
948
+ const boot = preparation.boot;
949
+ if (!boot.owner.current() || this.requestContextAdmission && this.requestContextAdmission !== boot.publication.admission)
950
+ throw Error("First activation owner changed");
951
+ this.requestContextFirstOn = preparation;
952
+ this.attachRequestContextAdmission(boot.publication.admission);
953
+ const fence = boot.publication.fence(), attempt = {};
954
+ preparation.attempt = attempt;
955
+ let adopted = false;
956
+ this.requestContextBoot = boot;
957
+ this.requestContextPolicy = boot.policy;
958
+ const current = () => !this.shuttingDown && this.managerBootId === manager && lease.current() && boot.owner.current()
959
+ && this.deliveryOutbox === box && this.requestContextBoot === boot && this.requestContextPolicy === boot.policy && (adopted || this.requestContextFirstOn === preparation && preparation.attempt === attempt);
960
+ return Object.freeze({ boot, fence, current,
961
+ /** The actual activation transaction already committed; only then publish capable policy ownership. */
962
+ adoptCommitted: (epoch) => {
963
+ const state = box.requestContextInstallation().read();
964
+ if (!current() || !fence.owned() || !state || state.owner !== boot.owner.owner || state.epoch !== epoch || state.mode !== "active")
965
+ throw Error("Activation commit owner changed");
966
+ adopted = true;
967
+ this.requestContextPolicy = boot.policy;
968
+ this.requestContextFirstOn = undefined;
969
+ return state;
970
+ },
971
+ /** Physical candidates/ports and the staged connection must be undone first by their owning orchestration. */
972
+ abandon: () => {
973
+ if (!current() || this.requestContextNativeGraph || box.requestContextInstallation().read() !== null)
974
+ throw Error("Activation preparation cannot revert");
975
+ this.requestContextBoot = undefined;
976
+ this.requestContextPolicy = undefined;
977
+ try {
978
+ boot.publication.abandon(fence, () => box.requestContextInstallation().read());
979
+ preparation.attempt = undefined;
980
+ }
981
+ catch (error) {
982
+ this.requestContextBoot = boot;
983
+ this.requestContextPolicy = boot.policy;
984
+ throw error;
985
+ }
986
+ }, });
987
+ }
988
+ /** Same-manager stop/start must reconstruct behind a new lease, never reuse an old published graph. */
989
+ async resetStoppedRequestContextAssembly() {
990
+ if (!this.requestContextBoot)
991
+ return;
992
+ if (this.daemons.size || this.instanceIpcClients.size || !this.requestContextPendingWork.empty)
993
+ throw Error("Request owners are still stopping");
994
+ const old = this.requestContextBoot, box = this.deliveryOutbox, factory = this.requestContextFactoryOwner;
995
+ await this.retireRequestContextNativeFactories(() => this.requestContextBoot === old && this.daemons.size === 0 && this.instanceIpcClients.size === 0);
996
+ const nativeRetired = () => this.requestContextBoot === old && !this.requestContextNativeGraph && !this.runtimeHub && !this.fleetWindowsRuntime && !this.nativeMcpStore && !this.paneManager && !this.localPaneRelay && !this.runtimeExecutor;
997
+ await factory?.disposeStopped(nativeRetired);
998
+ if (!nativeRetired())
999
+ throw Error("Native retirement changed");
1000
+ if (this.requestContextCollectionTimer)
1001
+ clearInterval(this.requestContextCollectionTimer);
1002
+ this.requestContextCollectionTimer = undefined;
1003
+ if (this.requestContextDrainTimer)
1004
+ clearTimeout(this.requestContextDrainTimer);
1005
+ this.requestContextDrainTimer = undefined;
1006
+ box?.close();
1007
+ this.deliveryOutbox = null;
1008
+ this.deliveryOutboxRecovered = false;
1009
+ this.requestContextControl = undefined;
1010
+ this.requestContextControlBox = undefined;
1011
+ this.requestContextBoot = undefined;
1012
+ this.requestContextModes = undefined;
1013
+ this.requestContextFirstOn = undefined;
1014
+ this.requestContextFactoryOwner = undefined;
1015
+ this.requestContextPolicy = undefined;
1016
+ this.requestContextAdmission = undefined;
1017
+ this.requestContextHumanAdmission = undefined;
1018
+ this.requestContextHubAdmission = undefined;
1019
+ this.requestContextRelay = undefined;
1020
+ this.requestContactCardsPort = null;
1021
+ this.requestContactApi = undefined;
1022
+ this.prepareRequestContextStart = undefined;
1023
+ this.configureRequestContextBeforeStart = undefined;
1024
+ this.prepareRequestContextOwnerRegistration = undefined;
1025
+ this.requestContextOwnerStarted = undefined;
1026
+ this.requestContextRetireOwner = undefined;
1027
+ 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}`);
1028
+ this.requestContextRetirementProofs.clear();
1029
+ this.requestContextCutoverErrors = [];
1030
+ }
1031
+ /** Retry only a never-published, never-started construction; durable malformed state still refuses. */
1032
+ async resetRequestContextUnpublishedPreparation() {
1033
+ const boot = this.requestContextBoot;
1034
+ if (!boot?.publication.heldUnpublished() || this.daemons.size || this.instanceIpcClients.size || !this.requestContextPendingWork.empty)
1035
+ throw Error("Capable preparation is still owned");
1036
+ const factory = this.requestContextFactoryOwner;
1037
+ await this.retireRequestContextNativeFactories(() => this.requestContextBoot === boot && boot.publication.heldUnpublished());
1038
+ factory?.disposeUnstarted();
1039
+ this.requestContextFactoryOwner = undefined;
1040
+ this.requestContextRetireOwner = undefined;
1041
+ this.requestContextRetainedFactory = undefined;
1042
+ this.prepareRequestContextOwnerRegistration = undefined;
1043
+ this.configureRequestContextBeforeStart = undefined;
1044
+ this.prepareRequestContextStart = () => boot.requirePreparedOwner();
1045
+ this.requestContextOwnerStarted = undefined;
1046
+ if (this.requestContextFleetCalls.size)
1047
+ throw Error("Request calls are still owned");
1048
+ 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}`);
1049
+ }
1050
+ async prepareRequestContextCapableBoot(rootRetired) {
1051
+ const [{ RequestContextPaneProofs }, { RequestContextOffOwner }] = await Promise.all([import("./request-context-pane.js"), import("./request-context-off.js")]);
1052
+ const boot = this.requestContextBoot, box = this.deliveryOutbox, lease = captureProcessFleetLease(this.dataDir), manager = this.managerBootId;
1053
+ if (!boot || !box || !lease?.current() || !this.fleetConfig || !box.requestContextInstallation().read() || !boot.publication.heldUnpublished()
1054
+ || this.daemons.size || this.instanceIpcClients.size || this.requestContextNativeGraph)
1055
+ throw Error("Capable boot preparation unavailable");
1056
+ boot.publication.fence();
1057
+ const owned = () => !this.shuttingDown && lease.current() && this.managerBootId === manager && this.requestContextBoot === boot && this.deliveryOutbox === box;
1058
+ const drain = box.requestContextDrain(() => owned() ? boot.owner.owner : null), registration = drain.registration();
1059
+ this.setRequestContextDrainRegistration(registration);
1060
+ const policy = Object.freeze({ assert: (input) => boot.policy.assert(input), installedMode: () => boot.publication.installedMode(),
1061
+ instructionMode: () => boot.publication.installedMode() ?? (owned() && boot.publication.heldUnpublished() ? box.requestContextInstallation().read()?.mode ?? null : null) });
1062
+ const factory = this.installRequestContextRetainedOwners(policy, registration, owned);
1063
+ this.requestContextFactoryOwner = factory;
1064
+ this.stageRequestContextNativeGraph({ registration, panes: new RequestContextPaneProofs(randomBytes(32).toString("hex"), registration), execTurns: factory.execTurns, execOwner: factory.execOwner, execInput: factory.execInput, current: () => owned() && factory.current() });
1065
+ const inventory = await this.prepareRequestContextDrainOwners(drain, registration, factory, owned), current = () => owned() && factory.current() && inventory.current();
1066
+ const serving = this.prepareRequestContextServingOwners(current, root => rootRetired(drain, root), factory.hub, () => boot.publication.installedMode()), ports = { policy: serving.policy, serving };
1067
+ this.bindRequestContextServingPublication(boot);
1068
+ const off = new RequestContextOffOwner(box.requestContextInstallation(), drain, boot.publication, { owner: boot.owner.owner, current }, { ports, current });
1069
+ const modes = this.ownRequestContextModes(boot, drain, off, ports, current, root => serving.gate.retireRoot(root));
1070
+ return Object.freeze({ ...modes, factory });
1071
+ }
1072
+ /** Exact persistent roster for controlled On; exec owners and durable drain assessment are separate required participants. */
1073
+ async captureRequestContextOwnedLaunches() {
1074
+ const admission = this.requestContextAdmission, lease = captureProcessFleetLease(this.dataDir);
1075
+ if (!admission || admission.available() || !lease?.current())
1076
+ throw Error("Request-context owner preparation unavailable");
1077
+ const pending = this.requestContextPendingWork, revision = pending.revision, boot = this.managerBootId;
1078
+ const freeze = (value) => {
1079
+ if (value && typeof value === "object") {
1080
+ for (const child of Object.values(value))
1081
+ freeze(child);
1082
+ Object.freeze(value);
1083
+ }
1084
+ return value;
1085
+ };
1086
+ const roster = [...this.daemons.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([name, daemon]) => ({
1087
+ name, daemon, config: freeze(daemon.getConfigSnapshot()),
1088
+ }));
1089
+ const images = roster.map(row => requestContextDigest(row.config));
1090
+ const owned = () => admission === this.requestContextAdmission && !admission.available() && lease.current()
1091
+ && this.managerBootId === boot && !this.shuttingDown && pending.revision === revision
1092
+ && this.daemons.size === roster.length && roster.every((row, i) => this.daemons.get(row.name) === row.daemon
1093
+ && pending.count(row.name) === 0 && requestContextDigest(row.config) === images[i]
1094
+ && requestContextDigest(row.daemon.getConfigSnapshot()) === images[i]);
1095
+ const records = [];
1096
+ for (const row of roster) {
1097
+ const unavailable = () => Object.assign(Error("Request-context owner is not ready"), { code: "request-context-owner-not-ready", agent: row.name });
1098
+ if (!owned())
1099
+ throw unavailable();
1100
+ const idle = await row.daemon.captureRequestContextIdle();
1101
+ if (!owned() || !idle?.current())
1102
+ throw unavailable();
1103
+ const retirement = await row.daemon.captureRequestContextRetirement();
1104
+ if (!owned() || !idle.current() || retirement.daemonBootId !== idle.daemonBootId
1105
+ || retirement.spawnGeneration !== idle.spawnGeneration || retirement.launchFenceEpoch !== idle.launchFenceEpoch)
1106
+ throw unavailable();
1107
+ records.push(Object.freeze({ ...row, config: Object.freeze(row.config), idle, retirement }));
1108
+ }
1109
+ const current = () => { try {
1110
+ return owned() && records.every(row => row.idle.current());
1111
+ }
1112
+ catch {
1113
+ return false;
1114
+ } };
1115
+ if (!current())
1116
+ throw Error("Request-context owner preparation changed");
1117
+ return Object.freeze({ records: Object.freeze(records), current });
1118
+ }
1119
+ /** Passive capture first; only prepare() may reconstruct owned transports after native graph staging.
1120
+ * Required ids never shrink when retirement/disconnect removes a connection from the current roster.
1121
+ */
1122
+ captureRequestContextRuntimeSet() {
1123
+ const lease = captureProcessFleetLease(this.dataDir), manager = this.managerBootId, initialConfig = requestContextDigest(this.fleetConfig);
1124
+ if (!lease?.current() || !this.fleetConfig)
1125
+ throw Error("Runtime readiness owner unavailable");
1126
+ const required = new Set(), exec = new Set();
1127
+ let localPane = false, prepared = false;
1128
+ const names = [...new Set([...Object.keys(this.fleetConfig.instances), ...(this.classicChannels?.getAll() ?? []).map(row => row.instanceName)])];
1129
+ for (const name of names) {
1130
+ const cfg = this.hubAgentConfig(name);
1131
+ if (cfg?.runtime !== "windows")
1132
+ continue;
1133
+ if (cfg.machine_id) {
1134
+ required.add(cfg.machine_id);
1135
+ if (isNativeExecInstance(cfg))
1136
+ exec.add(cfg.machine_id);
1137
+ }
1138
+ else if (isNativePaneInstance(cfg))
1139
+ localPane = true;
1140
+ }
1141
+ const online = () => this.runtimeHub?.listMachines().filter(row => row.status === "online") ?? [];
1142
+ const include = () => { for (const row of online())
1143
+ required.add(row.id); if (this.localPaneRelay?.online())
1144
+ localPane = true; };
1145
+ include();
1146
+ const labels = new Map((this.runtimeHub?.listMachines() ?? []).map(row => [row.id, row.name || row.id]));
1147
+ const owned = () => lease.current() && !this.shuttingDown && this.managerBootId === manager && requestContextDigest(this.fleetConfig) === initialConfig;
1148
+ const snapshot = () => {
1149
+ if (!owned())
1150
+ throw Error("Runtime readiness owner changed");
1151
+ include();
1152
+ const peers = [...required].sort().map(id => this.runtimeHub?.requestContextReadiness(id) ?? { id, generation: "unavailable", connected: false, requestContextVersion: 0 });
1153
+ if (localPane)
1154
+ peers.push(this.localPaneRelay?.requestContextReadiness() ?? { id: "local", generation: "unavailable", connected: false, requestContextVersion: 0 });
1155
+ return { requiredPeers: [...required, ...(localPane ? ["local"] : [])].sort(), peers: peers.sort((a, b) => a.id.localeCompare(b.id)) };
1156
+ };
1157
+ const advertised = () => {
1158
+ include();
1159
+ return [...required].filter(id => {
1160
+ const machine = this.runtimeHub?.machine(id), caps = machine?.runtimeInfo?.capabilities ?? [];
1161
+ return !machine || machine.status !== "online" || machine.paneProtocol !== 1 || !caps.includes("request-context-call-v1") || exec.has(id) && !caps.includes("native-exec-input-v1");
1162
+ });
1163
+ };
1164
+ return Object.freeze({ snapshot, labels: () => [...required].map(id => ({ id, label: labels.get(id) ?? this.runtimeHub?.machine(id)?.name ?? id })), advertised,
1165
+ prepare: async () => {
1166
+ if (!owned() || !this.currentRequestContextNativeGraph())
1167
+ throw Error("Runtime graph is not prepared");
1168
+ if (required.size)
1169
+ this.runtimeCoordinator();
1170
+ if (localPane)
1171
+ await this.localNativePaneEndpoint();
1172
+ if (!owned())
1173
+ throw Error("Runtime readiness owner changed");
1174
+ prepared = true;
1175
+ },
1176
+ prove: () => {
1177
+ if (!prepared)
1178
+ throw Error("Runtime graph is not prepared");
1179
+ const first = snapshot(), sha = requestContextDigest(first);
1180
+ if (first.peers.some(row => !row.connected || row.requestContextVersion !== 1))
1181
+ throw Error("Runtime negotiation unavailable");
1182
+ const graph = this.currentRequestContextNativeGraph(), hub = this.runtimeHub, local = this.localPaneRelay;
1183
+ return Object.freeze({ current: () => { try {
1184
+ return owned() && this.currentRequestContextNativeGraph() === graph && this.runtimeHub === hub && this.localPaneRelay === local && requestContextDigest(snapshot()) === sha;
1185
+ }
1186
+ catch {
1187
+ return false;
1188
+ } } });
1189
+ },
1190
+ });
1191
+ }
1192
+ /** The confirmed first-On controller owns this complete preparation. No durable activation or input publication
1193
+ * happens here. Its readiness callbacks must come from the actual legacy drain and negotiated port inventories.
1194
+ */
1195
+ async prepareRequestContextFirstOnAssembly(durableDrained, transportsReady, rootRetired, offer, execution, reconstructTransports) {
1196
+ const [{ RequestContextPaneProofs }, { RequestContextOffOwner }, { captureRequestContextHelpers }] = await Promise.all([import("./request-context-pane.js"), import("./request-context-off.js"), import("./request-context-helper-readiness.js")]);
1197
+ execution?.assert();
1198
+ if (!offer.current())
1199
+ throw Error("stale");
1200
+ const first = this.prepareRequestContextFirstOn(), box = this.deliveryOutbox, boot = first.boot;
1201
+ let connection;
1202
+ try {
1203
+ connection = box.stageRequestContextConnection({ current: first.fence.owned });
1204
+ }
1205
+ catch (error) {
1206
+ first.abandon();
1207
+ throw error;
1208
+ }
1209
+ const drain = connection.drain(() => first.current() ? boot.owner.owner : null), registration = drain.registration();
1210
+ let factory;
1211
+ let inventory;
1212
+ let fleetRegistration;
1213
+ let relaunch;
1214
+ let committed = false, disposed = false;
1215
+ const owned = () => !disposed && first.current();
1216
+ // Rendering may be staged for a fenced replacement; policy execution still uses only the publication.
1217
+ const policy = Object.freeze({ assert: (input) => boot.policy.assert(input), installedMode: () => boot.publication.installedMode(),
1218
+ instructionMode: () => boot.publication.installedMode() ?? (owned() && first.fence.owned() ? "active" : null) });
1219
+ const undoNative = async () => {
1220
+ if (committed || box.requestContextInstallation().read() !== null)
1221
+ throw Error("Activated owners cannot revert");
1222
+ inventory?.dispose();
1223
+ inventory = undefined;
1224
+ await this.retireRequestContextNativeFactories(owned);
1225
+ await factory?.disposeStaged();
1226
+ if (this.requestContextFactoryOwner === factory)
1227
+ this.requestContextFactoryOwner = undefined;
1228
+ factory = undefined;
1229
+ fleetRegistration?.restore();
1230
+ fleetRegistration = undefined;
1231
+ };
1232
+ const abandon = () => { connection.restore(); first.abandon(); disposed = true; };
1233
+ try {
1234
+ relaunch = await this.prepareRequestContextPersistentRelaunch(policy, registration, first.fence, durableDrained, async () => {
1235
+ try {
1236
+ await this.retireRequestContextNativeFactories(owned);
1237
+ fleetRegistration = this.stageRequestContextFleetRegistration(registration, owned);
1238
+ factory = this.installRequestContextRetainedOwners(policy, registration, owned, [], { firstOnStage: { current: () => owned() && first.fence.owned() }, deferStartHooks: true });
1239
+ this.requestContextFactoryOwner = factory;
1240
+ this.stageRequestContextNativeGraph({ registration, panes: new RequestContextPaneProofs(randomBytes(32).toString("hex"), registration),
1241
+ execTurns: factory.execTurns, execOwner: factory.execOwner, execInput: factory.execInput, current: () => owned() && factory?.current() === true });
1242
+ inventory = await this.prepareRequestContextDrainOwners(drain, registration, factory, owned);
1243
+ await reconstructTransports?.();
1244
+ return undoNative;
1245
+ }
1246
+ catch (error) {
1247
+ await undoNative();
1248
+ throw error;
1249
+ }
1250
+ }, execution);
1251
+ execution?.assert();
1252
+ factory.adopt(relaunch.owners());
1253
+ // Do not start deliberately stopped agents. Prepare only their future owned start/exec closures.
1254
+ const names = [...new Set([...Object.keys(this.fleetConfig.instances), ...(this.classicChannels?.getAll() ?? []).map(room => room.instanceName)])].sort();
1255
+ const configurations = names.map(name => [name, this.hubAgentConfig(name)]), rosterImage = requestContextDigest(configurations);
1256
+ for (const [name, config] of configurations) {
1257
+ if (!config)
1258
+ throw Error("Request owner configuration unavailable");
1259
+ if (!this.daemons.has(name))
1260
+ await factory.beforeStart(name, config);
1261
+ execution?.assert();
1262
+ }
1263
+ const sameRoster = () => requestContextDigest(names.map(name => [name, this.hubAgentConfig(name)])) === rosterImage
1264
+ && requestContextDigest([...new Set([...Object.keys(this.fleetConfig?.instances ?? {}), ...(this.classicChannels?.getAll() ?? []).map(room => room.instanceName)])].sort()) === requestContextDigest(names);
1265
+ const baseReady = () => owned() && first.fence.current() && connection.current() && relaunch.ready() && factory.current() && inventory.current()
1266
+ && sameRoster() && durableDrained();
1267
+ const candidates = relaunch.owners(), readHelpers = () => captureRequestContextHelpers(candidates, name => this.daemons.get(name));
1268
+ let helpers = readHelpers(), peersReady = transportsReady();
1269
+ const helperDeadline = performance.now() + 30_000;
1270
+ while (!helpers.ready || !peersReady) {
1271
+ if (!baseReady() || !offer.current() || execution && !execution.current() || performance.now() >= helperDeadline)
1272
+ 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] } : {}) });
1273
+ // A timer only schedules another actual connection observation; elapsed time never proves readiness.
1274
+ await new Promise(resolve => setTimeout(resolve, 100));
1275
+ helpers = readHelpers();
1276
+ peersReady = transportsReady();
1277
+ }
1278
+ const processReady = () => baseReady() && helpers.current() && transportsReady();
1279
+ const ready = () => processReady() && offer.current() && (!execution || execution.current());
1280
+ if (!ready())
1281
+ throw Error("Request-context owner or transport is not ready");
1282
+ const portsCurrent = () => owned() && factory.current() && inventory.current();
1283
+ let serving;
1284
+ const off = new RequestContextOffOwner(box.requestContextInstallation(), drain, boot.publication, { owner: boot.owner.owner, current: owned }, {
1285
+ get ports() { if (!serving)
1286
+ throw Error("Serving preparation unavailable"); return { policy: serving.policy, serving }; }, current: () => committed && portsCurrent() && !!serving
1287
+ });
1288
+ return Object.freeze({ boot, drain, registration, policy, ready, off, offer,
1289
+ /** Call only inside the single installation.activate transaction. No publication or async work. */
1290
+ initialize: () => {
1291
+ if (!ready())
1292
+ throw Error("Activation preparation changed");
1293
+ const record = box.requestContextInstallation().activation();
1294
+ if (!record || requestContextDigest(record.invalidates) !== requestContextDigest(offer.invalidates) || record.offeredLatestDeadline !== offer.latestDeadline)
1295
+ throw Error("Activation offer differs from confirmation");
1296
+ relaunch.retain();
1297
+ factory.retain();
1298
+ serving = this.prepareRequestContextServingOwners(portsCurrent, root => rootRetired(drain, root), factory.hub, () => boot.publication.installedMode());
1299
+ },
1300
+ /** Synchronous post-COMMIT publication. Failure stays capable and fenced for recovery. */
1301
+ publish: () => {
1302
+ const state = box.requestContextInstallation().read();
1303
+ if (!state || state.mode !== "active" || !serving || !owned())
1304
+ throw Error("Activation publication unavailable");
1305
+ const publishReady = processReady();
1306
+ committed = true;
1307
+ first.adoptCommitted(state.epoch);
1308
+ relaunch.seal();
1309
+ factory.seal();
1310
+ relaunch.releaseStartHooks();
1311
+ factory.attach();
1312
+ this.ownRequestContextModes(boot, drain, off, { policy: serving.policy, serving }, portsCurrent, root => serving.gate.retireRoot(root));
1313
+ this.bindRequestContextServingPublication(boot);
1314
+ if (!publishReady)
1315
+ throw Error("Activation publication readiness changed");
1316
+ boot.publication.publish(state, { policy: serving.policy, serving }, first.fence, portsCurrent, () => box.requestContextInstallation().read(), portsCurrent);
1317
+ return state;
1318
+ },
1319
+ rollback: async () => { if (committed || box.requestContextInstallation().read() !== null)
1320
+ throw Error("Activated owners cannot revert"); await relaunch.rollback(); abandon(); },
1321
+ });
1322
+ }
1323
+ catch (error) {
1324
+ // Persistent preparation unwinds its own candidates. If it returned, retire them before native ownership.
1325
+ try {
1326
+ if (relaunch)
1327
+ await relaunch.rollback();
1328
+ else if (this.requestContextNativeGraph || factory || fleetRegistration)
1329
+ await undoNative();
1330
+ abandon();
1331
+ }
1332
+ catch (cleanup) {
1333
+ throw new AggregateError([error, cleanup], "Request-context preparation could not restore every owner; admission stays fenced");
1334
+ }
1335
+ throw error;
1336
+ }
1337
+ }
1338
+ /** First-On persistent replacements. This does not activate, publish, open admission or construct a native factory.
1339
+ * The installer separately stages native factories and checks every transport before its one activation COMMIT.
1340
+ */
1341
+ async prepareRequestContextPersistentRelaunch(policy, registration, fence, durableDrained, afterRetirement, execution) {
1342
+ const box = this.deliveryOutbox, admission = this.requestContextAdmission, lease = captureProcessFleetLease(this.dataDir), boot = this.managerBootId;
1343
+ if (!box || box.requestContextInstallation().read() !== null || !admission || admission.available() || !lease?.current() || !fence.current())
1344
+ throw Error("Request relaunch preparation unavailable");
1345
+ const inventory = await this.captureRequestContextOwnedLaunches();
1346
+ const rows = inventory.records.map(row => ({ ...row, spec: row.daemon.getRequestContextLaunchSpec(), incarnation: this.contactGeneration(row.name),
1347
+ target: requestContextDigest(this.hubAgentConfig(row.name)), stopped: false, published: false, candidate: null,
1348
+ startup: null,
1349
+ prepared: null }));
1350
+ const originalPrepare = this.prepareRequestContextStart, originalConfigure = this.configureRequestContextBeforeStart;
1351
+ let alive = true, committed = false, rollingBack = false, undoAfterRetirement;
1352
+ const processOwned = () => {
1353
+ try {
1354
+ return alive && !this.shuttingDown && this.managerBootId === boot && lease.current()
1355
+ && this.requestContextAdmission === admission && (committed || fence.owned() && !admission.available());
1356
+ }
1357
+ catch {
1358
+ return false;
1359
+ }
1360
+ };
1361
+ const configured = (row) => {
1362
+ try {
1363
+ return this.contactGeneration(row.name) === row.incarnation
1364
+ && requestContextDigest(this.hubAgentConfig(row.name)) === row.target;
1365
+ }
1366
+ catch {
1367
+ return false;
1368
+ }
1369
+ };
1370
+ const rosterOwned = () => processOwned() && [...this.daemons.keys()].every(name => rows.some(row => row.name === name))
1371
+ && 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; });
1372
+ const current = () => rosterOwned() && rows.every(configured);
1373
+ const prepare = (name, actual) => {
1374
+ const row = rows.find(item => item.name === name);
1375
+ if (rollingBack || !row?.prepared || !row.stopped || row.candidate || !current() || requestContextDigest(actual) !== requestContextDigest(row.spec.config))
1376
+ throw Error("Request relaunch start differs");
1377
+ return row.prepared.preparation;
1378
+ };
1379
+ const configure = (name, daemon, actual, offered) => {
1380
+ const row = rows.find(item => item.name === name);
1381
+ if (rollingBack || !row?.prepared || row.candidate || !current() || offered !== undefined && offered.policy !== policy)
1382
+ throw Error("Request relaunch owner differs");
1383
+ // Capture the object before any pre-start callback can fail. Even a startup rejection must retire it exactly.
1384
+ row.candidate = daemon;
1385
+ daemon.seedRequestContextReplacement(row.retirement);
1386
+ row.startup = daemon.prepareRequestContextStartupRetirement();
1387
+ originalConfigure?.(name, daemon, actual, offered);
1388
+ row.prepared.configure(daemon, actual, offered);
1389
+ };
1390
+ const hooksOwned = () => this.prepareRequestContextStart === prepare && this.configureRequestContextBeforeStart === configure;
1391
+ const restoreHooks = () => { if (!hooksOwned())
1392
+ throw Error("Request relaunch start hooks changed"); this.prepareRequestContextStart = originalPrepare; this.configureRequestContextBeforeStart = originalConfigure; };
1393
+ const failed = (name) => Object.assign(Error("Request-context owner is not ready"), { code: "request-context-owner-not-ready", agent: name });
1394
+ const rollback = async () => {
1395
+ if (committed || box.requestContextInstallation().read() !== null)
1396
+ throw Error("Activated owners cannot revert to legacy");
1397
+ if (!processOwned() || !hooksOwned())
1398
+ throw Error("Request relaunch rollback owner changed");
1399
+ rollingBack = true;
1400
+ // Stop/prove every candidate before regenerating legacy instructions or creating a legacy replacement.
1401
+ for (const row of rows.slice().reverse()) {
1402
+ if (!row.candidate)
1403
+ continue;
1404
+ const now = this.daemons.get(row.name);
1405
+ if (now && now !== row.candidate)
1406
+ throw failed(row.name);
1407
+ if (now === row.candidate)
1408
+ await this.lifecycle.stopIfCurrent(row.name, row.candidate);
1409
+ else
1410
+ await row.candidate.stop({ nativePane: "close" });
1411
+ if (!processOwned() || !row.startup || !await row.startup.retired())
1412
+ throw failed(row.name);
1413
+ row.candidate = null;
1414
+ row.prepared?.dispose();
1415
+ }
1416
+ if (undoAfterRetirement) {
1417
+ await undoAfterRetirement();
1418
+ undoAfterRetirement = undefined;
1419
+ }
1420
+ restoreHooks();
1421
+ for (const row of rows) {
1422
+ row.prepared?.dispose();
1423
+ if (!row.stopped)
1424
+ continue;
1425
+ if (!processOwned())
1426
+ throw failed(row.name);
1427
+ if (this.daemons.get(row.name) === row.daemon)
1428
+ await this.lifecycle.stopIfCurrent(row.name, row.daemon);
1429
+ // A deleted, re-targeted or externally replaced owner is never resurrected from this captured config.
1430
+ if (!configured(row) || this.daemons.has(row.name))
1431
+ continue;
1432
+ if (!await row.retirement.retired() || !processOwned())
1433
+ throw failed(row.name);
1434
+ await this.startInstance(row.name, row.spec.config, row.spec.topicMode, row.spec.kind);
1435
+ }
1436
+ alive = false;
1437
+ };
1438
+ if (!inventory.current() || !current() || !durableDrained() || !fence.current())
1439
+ throw Error("Request relaunch preparation changed");
1440
+ this.prepareRequestContextStart = prepare;
1441
+ this.configureRequestContextBeforeStart = configure;
1442
+ try {
1443
+ for (const row of rows) {
1444
+ if (!current() || !fence.current() || !durableDrained() || !row.idle.current())
1445
+ throw failed(row.name);
1446
+ execution?.assert();
1447
+ row.stopped = true;
1448
+ let stopped = false;
1449
+ if (execution)
1450
+ await execution.stopTarget(row.name, async (advance) => { stopped = await this.lifecycle.stopIfCurrent(row.name, row.daemon, advance); });
1451
+ else
1452
+ stopped = await this.lifecycle.stopIfCurrent(row.name, row.daemon);
1453
+ if (!stopped)
1454
+ throw failed(row.name);
1455
+ if (!current() || !await row.retirement.retired() || !current())
1456
+ throw failed(row.name);
1457
+ }
1458
+ if (afterRetirement) {
1459
+ undoAfterRetirement = await afterRetirement();
1460
+ if (!current() || !fence.current() || !durableDrained())
1461
+ throw Error("Request relaunch preparation changed");
1462
+ }
1463
+ for (const row of rows) {
1464
+ if (!current() || !fence.current() || !durableDrained())
1465
+ throw failed(row.name);
1466
+ 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());
1467
+ execution?.assert();
1468
+ await this.startInstance(row.name, row.spec.config, row.spec.topicMode, row.spec.kind, false, undefined, execution);
1469
+ execution?.assert();
1470
+ row.published = true;
1471
+ if (!current())
1472
+ throw failed(row.name);
1473
+ row.prepared.sealRegistered();
1474
+ }
1475
+ const ready = () => !rollingBack && current() && hooksOwned() && fence.current() && durableDrained() && rows.every(row => row.prepared?.bound());
1476
+ if (!ready())
1477
+ throw Error("Request relaunch preparation changed");
1478
+ return Object.freeze({
1479
+ ready,
1480
+ owners: () => rows.map(row => { if (!row.candidate || !row.startup || !row.prepared?.bound())
1481
+ throw Error("Request relaunch owner unavailable"); return Object.freeze({ name: row.name, daemon: row.candidate, prepared: row.prepared, resources: row.startup }); }),
1482
+ /** Synchronous initializer inside activation's outer SQLite transaction. */
1483
+ retain: () => { if (!ready())
1484
+ throw Error("Request relaunch preparation changed"); for (const row of rows)
1485
+ row.prepared.work.retainPrepared(); if (!ready())
1486
+ throw Error("Request relaunch preparation changed"); },
1487
+ /** Post-COMMIT only. The installer replaces the start hooks with its capable owner factory before releasing admission. */
1488
+ seal: () => {
1489
+ if (rollingBack || !current() || !hooksOwned() || !rows.every(row => row.prepared?.bound()) || box.requestContextInstallation().read() === null)
1490
+ throw Error("Request relaunch has not committed");
1491
+ for (const row of rows)
1492
+ row.prepared.work.sealRetained();
1493
+ committed = true;
1494
+ },
1495
+ executionCurrent: () => committed && processOwned(),
1496
+ releaseStartHooks: () => { if (!committed || !current())
1497
+ throw Error("Request relaunch has not committed"); restoreHooks(); },
1498
+ rollback,
1499
+ });
1500
+ }
1501
+ catch (error) {
1502
+ try {
1503
+ await rollback();
1504
+ }
1505
+ catch (rollbackError) {
1506
+ throw new AggregateError([error, rollbackError], "Request relaunch could not restore every owned agent; admission stays fenced");
1507
+ }
1508
+ throw error;
1509
+ }
1510
+ }
1511
+ /** Shared input gate only; C/D scope binding remains a separate pre-start preparation. */
1512
+ attachRequestContextAdmission(port) {
1513
+ if (this.requestContextAdmission === port)
1514
+ return;
1515
+ if (this.requestContextAdmission)
1516
+ throw Error("Request-context admission owner differs");
1517
+ this.requestContextAdmission = port;
1518
+ for (const daemon of this.daemons.values())
1519
+ daemon.setRequestContextAdmission(port);
1520
+ const prepare = this.configureRequestContextBeforeStart;
1521
+ this.configureRequestContextBeforeStart = (name, daemon, config, preparation) => { daemon.setRequestContextAdmission(port); prepare?.(name, daemon, config, preparation); };
1522
+ port.subscribe(available => {
1523
+ if ((available || port.dispatchAvailable?.()) && !this.shuttingDown && this.deliveryOutbox?.isOpen) {
1524
+ this.scheduleDeliveryOutboxPump();
1525
+ this.wakeCoordinator?.kick();
1526
+ }
1527
+ });
1528
+ }
849
1529
  /** S-244: the quiescence barrier. Unset, every pane write and admission proceeds as today. */
850
1530
  quiescence = null;
851
1531
  attachQuiescence(gate) { this.quiescence = gate; }
@@ -1167,6 +1847,7 @@ export class FleetManager {
1167
1847
  fleetConfig = null;
1168
1848
  fleetWindowsRuntime = null;
1169
1849
  nativeMcpStore = null;
1850
+ requestContextPendingWork = new RequestContextPendingWork();
1170
1851
  requestContextIpcCalls = new WeakMap();
1171
1852
  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
1853
  setRequestContextDrainRegistration(registration) {
@@ -1177,6 +1858,28 @@ export class FleetManager {
1177
1858
  throw Error("Request context drain registry unavailable");
1178
1859
  calls.installRegistration(registration);
1179
1860
  }
1861
+ /** Unpublished first-On registration. Only an empty, physically disconnected attempt can restore its prior map. */
1862
+ stageRequestContextFleetRegistration(registration, current) {
1863
+ const box = this.deliveryOutbox, lease = captureProcessFleetLease(this.dataDir), original = this.requestContextFleetCalls;
1864
+ if (!box || !lease?.current() || !current() || this.requestContextAdmission?.available() !== false || !original || original.size || original.registrationGate
1865
+ || this.instanceIpcClients.size || !this.requestContextPendingWork?.empty || box.requestContextInstallation().read() !== null)
1866
+ throw Error("Fleet call registration preparation unavailable");
1867
+ 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}`);
1868
+ replacement.installRegistration(registration);
1869
+ this.requestContextFleetCalls = replacement;
1870
+ const owned = () => { try {
1871
+ return !this.shuttingDown && lease.current() && current() && this.deliveryOutbox === box && this.requestContextFleetCalls === replacement;
1872
+ }
1873
+ catch {
1874
+ return false;
1875
+ } };
1876
+ return Object.freeze({ current: owned, restore: () => {
1877
+ if (!owned() || this.requestContextAdmission?.available() !== false || this.instanceIpcClients.size || replacement.size
1878
+ || !this.requestContextPendingWork.empty || box.requestContextInstallation().read() !== null)
1879
+ throw Error("Fleet call registration cannot revert");
1880
+ this.requestContextFleetCalls = original;
1881
+ } });
1882
+ }
1180
1883
  get requestContextFleetDrainRevision() { return this.requestContextFleetCalls?.revision ?? "unavailable"; }
1181
1884
  requestContextFleetDrainView(rootId) { return this.requestContextFleetCalls?.view(rootId) ?? { registration: null, revision: "unavailable", references: [], unknown: true }; }
1182
1885
  finishRequestContextIpcCall(message) { const call = this.requestContextCallOf(message), calls = this.requestContextFleetCalls; if (call && calls)
@@ -1224,7 +1927,7 @@ export class FleetManager {
1224
1927
  return false;
1225
1928
  const tool = message.type === "fleet_outbound" ? String(message.tool ?? "") : toolForIpcType(message.type);
1226
1929
  const originalBoot = daemon.bootId;
1227
- const scoped = Object.freeze({ id: captured.id, admission: captured.admission,
1930
+ const scoped = Object.freeze({ id: captured.id, admission: captured.admission, replyRoute: captured.replyRoute,
1228
1931
  current: () => captured.current() && this.instanceIpcClients.get(name) === ipc && this.getDaemonBootId(name) === originalBoot
1229
1932
  && !!tool && this.checkToolPermission("ipc-outbound", name, tool === "hub_room_status" ? "hub_room_list" : tool).allowed });
1230
1933
  const calls = this.requestContextFleetCalls;
@@ -1370,13 +2073,146 @@ export class FleetManager {
1370
2073
  runtimeExecutor = null;
1371
2074
  runtimeStatusScheduled = false;
1372
2075
  reconciledRemoteResults = new Set();
2076
+ requestContextNativeGraph;
2077
+ requestContextNativeGraphLease;
2078
+ requestContextNativeFactoryOwners;
2079
+ requestContextOpeningPaneManagers = 0;
2080
+ requestContextNativeRetiring = false;
2081
+ /** Already-drained owned launches only. The callback owns the Fleet/process, not the browser/readiness. */
2082
+ async retireRequestContextNativeFactories(current) {
2083
+ const lease = captureProcessFleetLease(this.dataDir), owned = () => !!lease?.current() && current() && this.requestContextAdmission?.available() === false;
2084
+ if (!owned() || this.requestContextNativeRetiring)
2085
+ throw Error("Native factory retirement needs the owned admission fence");
2086
+ const [{ LocalPaneEndpoint }, { localPaneScope }, { NativePaneManager }] = await Promise.all([import("./local-pane-endpoint.js"), import("./local-pane-launcher.js"), import("./native-pane-manager.js")]);
2087
+ const scope = localPaneScope(this.dataDir), hub = this.runtimeHub, panes = this.paneManager, mcp = this.nativeMcpStore, runtime = this.fleetWindowsRuntime, executor = this.runtimeExecutor, relay = this.localPaneRelay;
2088
+ const same = () => this.runtimeHub === hub && this.localPaneRelay === relay && this.paneManager === panes && this.nativeMcpStore === mcp && this.fleetWindowsRuntime === runtime && this.runtimeExecutor === executor && !this.openingLocalPane && !this.requestContextOpeningPaneManagers;
2089
+ 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))
2090
+ throw Error("Native factories still own work or an unconfirmed launch");
2091
+ this.requestContextNativeRetiring = true;
2092
+ try {
2093
+ runtime?.retireForRequestContext();
2094
+ panes?.retireForRequestContext();
2095
+ mcp?.retireForRequestContext();
2096
+ executor?.retireForRequestContext();
2097
+ retireWindowsBridgeForRequestContext(this);
2098
+ await Promise.all([hub?.retireForRequestContext(), LocalPaneEndpoint.retireScopeForRequestContext(scope)]);
2099
+ if (!owned() || !same())
2100
+ throw Error("Native factory owner changed during retirement");
2101
+ this.runtimeHub = null;
2102
+ this.localPaneRelay = null;
2103
+ this.paneManager = null;
2104
+ this.nativeMcpStore = null;
2105
+ this.fleetWindowsRuntime = null;
2106
+ this.runtimeExecutor = null;
2107
+ this.requestContextNativeGraph = undefined;
2108
+ this.requestContextNativeGraphLease = undefined;
2109
+ this.requestContextNativeFactoryOwners = undefined;
2110
+ }
2111
+ finally {
2112
+ this.requestContextNativeRetiring = false;
2113
+ }
2114
+ }
2115
+ /** Only after exact old-owner retirement and transport teardown, behind the shared Fleet admission fence. */
2116
+ stageRequestContextNativeGraph(graph) {
2117
+ const lease = captureProcessFleetLease(this.dataDir);
2118
+ if (this.requestContextNativeGraph || !lease?.current() || this.requestContextAdmission?.available() !== false || !graph.current()
2119
+ || this.runtimeHub || this.runtimeExecutor || this.localPaneRelay || this.openingLocalPane || this.requestContextOpeningPaneManagers || this.paneManager || this.nativeMcpStore || this.fleetWindowsRuntime
2120
+ || typeof graph.execInput !== "function" || graph.panes.drainView("").registration !== graph.registration)
2121
+ throw Error("Request-context native graph is not retired");
2122
+ this.requestContextNativeGraph = graph;
2123
+ this.requestContextNativeGraphLease = lease;
2124
+ }
2125
+ /** Inert native owner construction plus the complete eight-family inventory, behind the shared fence.
2126
+ * None of these accessors starts a provider, pane, coordinator or Fleet. Transport negotiation is separate.
2127
+ */
2128
+ async prepareRequestContextDrainOwners(drain, registration, owners, current) {
2129
+ const graph = this.requestContextNativeGraph, box = this.deliveryOutbox, lease = captureProcessFleetLease(this.dataDir);
2130
+ if (!graph || graph.registration !== registration || !graph.current() || !box || !lease?.current() || !current() || !owners.current()
2131
+ || this.requestContextAdmission?.available() !== false || this.requestContextFleetCalls?.registrationGate !== registration)
2132
+ throw Error("Drain owner preparation unavailable");
2133
+ const runtime = this.nativeInstanceRuntime(), grants = this.nativeMcpSessions(), panes = await this.nativePanes();
2134
+ let alive = true;
2135
+ const owned = () => {
2136
+ try {
2137
+ return alive && !this.shuttingDown && lease.current() && current() && owners.current() && this.deliveryOutbox === box
2138
+ && this.requestContextNativeGraph === graph && graph.current() && this.fleetWindowsRuntime === runtime && this.nativeMcpStore === grants
2139
+ && this.paneManager === panes && this.requestContextFleetCalls?.registrationGate === registration;
2140
+ }
2141
+ catch {
2142
+ return false;
2143
+ }
2144
+ };
2145
+ if (!owned() || this.requestContextAdmission?.available() !== false)
2146
+ throw Error("Drain owner preparation changed");
2147
+ const sources = [
2148
+ ["turns", owners.revision, owners.turnView], ["daemon-calls", owners.callRevision, owners.callView],
2149
+ ["fleet-calls", () => this.requestContextFleetDrainRevision, root => this.requestContextFleetDrainView(root)],
2150
+ ["native-exec", () => runtime.drainRevision, root => runtime.drainView(root)],
2151
+ ["native-grants", () => grants.drainRevision, root => grants.drainView(root)],
2152
+ ["pane-proofs", () => graph.panes.drainRevision, root => graph.panes.drainView(root), () => graph.panes.offRevision, root => graph.panes.offView(root)],
2153
+ ["pane-ledgers", () => panes.drainRevision, root => panes.drainView(root), () => panes.offRevision, root => panes.offView(root)],
2154
+ ["registered-work", owners.inputRevision, owners.inputView],
2155
+ ];
2156
+ const remove = [];
2157
+ try {
2158
+ for (const [family, revision, inspect, offRevision, inspectOff] of sources)
2159
+ remove.push(drain.register(family, "fleet", { registration,
2160
+ revision: () => owned() ? revision() : "owner-changed", inspect: root => owned() ? inspect(root) : { registration, revision: "owner-changed", references: [], unknown: true },
2161
+ ...(offRevision && inspectOff ? { offRevision: () => owned() ? offRevision() : "owner-changed", inspectOff: (root) => owned() ? inspectOff(root) : { registration, revision: "owner-changed", references: [], unknown: true } } : {}) }));
2162
+ }
2163
+ catch (error) {
2164
+ for (const undo of remove.reverse())
2165
+ undo();
2166
+ throw error;
2167
+ }
2168
+ return Object.freeze({ current: owned, runtime, grants, panes,
2169
+ /** The physical owners/connection have their own exact rollback; this only removes unpublished inventory. */
2170
+ dispose: () => {
2171
+ if (!owned() || this.requestContextAdmission?.available() !== false || box.requestContextInstallation().read() !== null
2172
+ || !runtime.requestContextPhysicallyIdle() || !grants.requestContextPhysicallyIdle() || !panes.requestContextPhysicallyIdle()
2173
+ || this.requestContextFleetCalls.size || !this.requestContextPendingWork.empty)
2174
+ throw Error("Published drain owners cannot revert");
2175
+ for (const undo of remove.slice().reverse())
2176
+ undo();
2177
+ alive = false;
2178
+ },
2179
+ });
2180
+ }
2181
+ currentRequestContextNativeGraph() {
2182
+ const graph = this.requestContextNativeGraph;
2183
+ if (graph) {
2184
+ if (!this.requestContextNativeGraphLease?.current() || !graph.current())
2185
+ throw Error("Request-context native graph owner changed");
2186
+ return graph;
2187
+ }
2188
+ if (this.requestContextBoot)
2189
+ throw Error("Request-context native graph is not prepared");
2190
+ return null;
2191
+ }
2192
+ ownRequestContextNativeFactory(value, graph) {
2193
+ if (this.currentRequestContextNativeGraph() !== graph)
2194
+ throw Error("Request-context native factory owner changed");
2195
+ (this.requestContextNativeFactoryOwners ??= new WeakMap()).set(value, graph);
2196
+ return value;
2197
+ }
2198
+ requireRequestContextNativeFactory(value, graph) {
2199
+ if (this.currentRequestContextNativeGraph() !== graph || this.requestContextNativeFactoryOwners?.get(value) !== graph)
2200
+ throw Error("Request-context native factory was not prepared");
2201
+ return value;
2202
+ }
1373
2203
  /** Machine credentials are separate from dashboard sessions and per-turn agent capabilities. */
1374
2204
  runtimeCoordinator() {
2205
+ if (this.requestContextNativeRetiring)
2206
+ throw Error("Native factory replacement is holding new work");
1375
2207
  if (!remoteRuntimeEnabled())
1376
2208
  throw new Error("Remote runtimes are not enabled");
1377
2209
  if (!this.runtimeHub && this.readPendingOwnerNotices().length)
1378
2210
  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, {
2211
+ const graph = this.requestContextNativeGraph || this.requestContextBoot ? this.currentRequestContextNativeGraph() : null;
2212
+ if (this.runtimeHub)
2213
+ return graph ? this.requireRequestContextNativeFactory(this.runtimeHub, graph) : this.runtimeHub;
2214
+ const hub = new RuntimeCoordinator(this.dataDir, {
2215
+ ...(graph ? { requestContextProtocol: 1 } : {}),
1380
2216
  handleMcp: (machineId, runId, body) => this.runtimeWindowsExecutor().mcp(machineId, runId, body),
1381
2217
  handlePaneMcp: async (machineId, body, current, stamp) => stamp ? (await this.nativePanes()).handle(machineId, body, current, stamp) : (await this.nativePanes()).handle(machineId, body, current),
1382
2218
  warn: (fields, message) => this.logger.warn(fields, message),
@@ -1428,22 +2264,54 @@ export class FleetManager {
1428
2264
  });
1429
2265
  },
1430
2266
  });
2267
+ return this.runtimeHub = graph ? this.ownRequestContextNativeFactory(hub, graph) : hub;
1431
2268
  }
1432
2269
  runtimeWindowsExecutor() {
2270
+ if (this.requestContextNativeRetiring)
2271
+ throw Error("Native factory replacement is holding new work");
1433
2272
  return this.runtimeExecutor ??= new RuntimeWindowsBridge(this, () => remoteRuntimeEnabled() && !this.shuttingDown ? this.runtimeCoordinator() : null);
1434
2273
  }
1435
2274
  /** Per-turn capabilities for native MCP, separate from browser and Linux-agent credentials. */
1436
2275
  nativeMcpSessions() {
1437
- return this.nativeMcpStore ??= new NativeMcpSessions(this);
2276
+ if (this.requestContextNativeRetiring)
2277
+ throw Error("Native factory replacement is holding new work");
2278
+ const graph = this.requestContextNativeGraph || this.requestContextBoot ? this.currentRequestContextNativeGraph() : null;
2279
+ if (this.nativeMcpStore)
2280
+ return graph ? this.requireRequestContextNativeFactory(this.nativeMcpStore, graph) : this.nativeMcpStore;
2281
+ const sessions = new NativeMcpSessions(this, graph?.registration);
2282
+ if (graph)
2283
+ sessions.setRequestContextRequired(true, true);
2284
+ return this.nativeMcpStore = graph ? this.ownRequestContextNativeFactory(sessions, graph) : sessions;
1438
2285
  }
1439
2286
  /** Retire only existing native capabilities; ordinary lifecycle changes do not instantiate the Windows path. */
1440
2287
  invalidateNativeMcp(name) { this.nativeMcpStore?.closeInstance(name); }
1441
2288
  /** The same instance registry and delivery entry point, with a native Windows execution adapter. */
1442
2289
  nativeInstanceRuntime() {
1443
- return this.fleetWindowsRuntime ??= new FleetWindowsRuntime({
2290
+ if (this.requestContextNativeRetiring)
2291
+ throw Error("Native factory replacement is holding new work");
2292
+ const graph = this.requestContextNativeGraph || this.requestContextBoot ? this.currentRequestContextNativeGraph() : null;
2293
+ if (this.fleetWindowsRuntime)
2294
+ return graph ? this.requireRequestContextNativeFactory(this.fleetWindowsRuntime, graph) : this.fleetWindowsRuntime;
2295
+ const runtime = new FleetWindowsRuntime({
1444
2296
  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,
2297
+ requestContextAdmission: () => this.requestContextAdmission,
2298
+ requestContextContinuation: (instance, inputId) => {
2299
+ if (!this.requestContextBoot)
2300
+ return;
2301
+ const match = /^delivery:([a-f0-9-]{36}):([1-9][0-9]*)$/.exec(inputId ?? "");
2302
+ if (!match)
2303
+ return;
2304
+ const row = this.deliveryOutbox?.get(match[1]);
2305
+ if (!row || row.targetInstance !== instance || row.managerBootId !== this.managerBootId || row.attemptNo !== Number(match[2])
2306
+ || row.targetDaemonBootId !== this.managerBootId || !["delivering", "submission_started"].includes(row.state))
2307
+ throw Error("Native continuation attempt changed");
2308
+ return this.requestContextDeliveryContinuation(row) ?? undefined;
2309
+ },
2310
+ openMcp: (instance, requestId, sandbox, stillCurrent, requestContext, inputReady) => this.healthServerListening
2311
+ ? this.nativeMcpSessions().grant({ instance, requestId, sandbox, stillCurrent, ...(requestContext ? { requestContext } : {}), ...(inputReady ? { inputReady } : {}), endpoint: `http://127.0.0.1:${this.fleetConfig?.health_port ?? 19280}/agent` }) : null,
2312
+ projectRequestContextOutput: (instance, task, completion) => this.deliveryOutbox ? projectRequestContextNativeOutput(this.deliveryOutbox, instance, task, completion, {
2313
+ admitted: root => this.requestContextNativeAdmissionCurrent(root), history: this.webChatHistory, session: handle => this.webSessions?.findByHandle(handle),
2314
+ }) : null,
1447
2315
  warn: (message, error) => this.logger.warn({ err: error }, message),
1448
2316
  removed: name => this.nativeInstanceRemoved(name),
1449
2317
  paneCurrent: name => this.daemons.get(name)?.nativePaneCurrent?.() === true,
@@ -1478,6 +2346,9 @@ export class FleetManager {
1478
2346
  this.scheduleDeliveryOutboxPump();
1479
2347
  },
1480
2348
  }, { bridge: this.runtimeWindowsExecutor() });
2349
+ if (graph)
2350
+ runtime.setRequestContextExecLifecycles(graph.execTurns, graph.execOwner, graph.registration, graph.execInput);
2351
+ return this.fleetWindowsRuntime = graph ? this.ownRequestContextNativeFactory(runtime, graph) : runtime;
1481
2352
  }
1482
2353
  agentRuntimeChangeService;
1483
2354
  agentRuntimeChanges() {
@@ -1719,13 +2590,17 @@ export class FleetManager {
1719
2590
  return { ...(result.version ? { native_cli_version: result.version } : {}), native_cli_verification: result.state };
1720
2591
  }
1721
2592
  async localNativePaneEndpoint() {
1722
- const admit = () => { if (this.shuttingDown || this.localPaneDrain || !localWindowsCliEnabled())
2593
+ if (this.requestContextNativeRetiring)
2594
+ throw Error("Native factory replacement is holding new work");
2595
+ const graph = this.requestContextNativeGraph || this.requestContextBoot ? this.currentRequestContextNativeGraph() : null;
2596
+ const admit = () => { if (graph && this.currentRequestContextNativeGraph() !== graph)
2597
+ throw Error("Request-context native factory owner changed"); if (this.shuttingDown || this.localPaneDrain || !localWindowsCliEnabled())
1723
2598
  throw Error("Local Windows runtime is switched off or draining"); };
1724
2599
  admit();
1725
2600
  if (this.localPaneDrain)
1726
2601
  throw Error("Local Windows runtime cleanup is pending");
1727
2602
  if (this.localPaneRelay?.online())
1728
- return this.localPaneRelay;
2603
+ return graph ? this.requireRequestContextNativeFactory(this.localPaneRelay, graph) : this.localPaneRelay;
1729
2604
  if (this.openingLocalPane)
1730
2605
  return this.openingLocalPane;
1731
2606
  const opening = (async () => {
@@ -1735,15 +2610,14 @@ export class FleetManager {
1735
2610
  admit();
1736
2611
  this.localPaneRelay?.stop();
1737
2612
  this.localPaneInventory = inventory;
1738
- const relay = await LocalPaneEndpoint.open({ scope: localPaneScope(this.dataDir), admit, maxAgents: maxAgentsPerMachine,
2613
+ const relay = await LocalPaneEndpoint.open({ scope: localPaneScope(this.dataDir), ...(graph ? { requestContextProtocol: 1 } : {}), admit, maxAgents: maxAgentsPerMachine,
1739
2614
  diagnostic: text => this.logger.warn({ stderr: text }, "Local Windows pane relay wrote to stderr"),
1740
2615
  version: provider => inventory.clis.find(row => row.id === provider && row.runnable)?.version ?? null,
1741
2616
  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
- });
2617
+ mcp: async (body, current, stamp) => stamp ? (await this.nativePanes()).handle("local", body, current, stamp) : (await this.nativePanes()).handle("local", body, current), });
1744
2618
  try {
1745
2619
  admit();
1746
- this.localPaneRelay = relay;
2620
+ this.localPaneRelay = graph ? this.ownRequestContextNativeFactory(relay, graph) : relay;
1747
2621
  return relay;
1748
2622
  }
1749
2623
  catch (error) {
@@ -1762,85 +2636,101 @@ export class FleetManager {
1762
2636
  }
1763
2637
  /** Persistent ownership is independent of the exec worker's per-turn capabilities. */
1764
2638
  async nativePanes() {
2639
+ if (this.requestContextNativeRetiring)
2640
+ throw Error("Native factory replacement is holding new work");
2641
+ const graph = this.requestContextNativeGraph || this.requestContextBoot ? this.currentRequestContextNativeGraph() : null;
1765
2642
  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
- });
2643
+ return graph ? this.requireRequestContextNativeFactory(this.paneManager, graph) : this.paneManager;
2644
+ const boot = this.requestContextBoot;
2645
+ this.requestContextOpeningPaneManagers = (this.requestContextOpeningPaneManagers ?? 0) + 1;
2646
+ try {
2647
+ const { NativePaneManager } = await import("./native-pane-manager.js");
2648
+ if (this.requestContextNativeGraph !== (graph ?? undefined) || this.requestContextBoot !== boot)
2649
+ throw Error("Request-context native factory owner changed");
2650
+ if (this.paneManager)
2651
+ return graph ? this.requireRequestContextNativeFactory(this.paneManager, graph) : this.paneManager;
2652
+ if (graph && this.currentRequestContextNativeGraph() !== graph)
2653
+ throw Error("Request-context native factory owner changed");
2654
+ const store = windowsAgentsFor(this, this.runtimeWindowsExecutor());
2655
+ const allowed = (name, tool) => (!this.classicContactRestricted(name) || CLASSIC_RESTRICTED_TOOLS.includes(tool))
2656
+ && nativePaneToolAvailable(tool) && mayUseTool(resolveToolSet(this.fleetConfig?.instances[name], name), tool)
2657
+ && !dashboardRefusalIn(this.fleetConfig, name, tool);
2658
+ const manager = new NativePaneManager({
2659
+ ...(graph ? { requestContexts: graph.panes, registration: graph.registration } : {}),
2660
+ home: this.dataDir, store, config: name => this.fleetConfig?.instances[name],
2661
+ freshNotice: async (name, provider) => {
2662
+ const message = t(provider === "codex" ? "native_pane.codex_fresh_started" : "native_pane.fresh_started");
2663
+ this.eventLog?.insert(name, "native_pane_fresh_started", {});
2664
+ this.logger.info({ name }, message);
2665
+ await this.notifyInstanceTopic(name, message);
2666
+ },
2667
+ admit: (name, config) => {
2668
+ const now = this.fleetConfig?.instances[name];
2669
+ if (this.shuttingDown || !isNativePaneInstance(now) || now?.native_agent_id !== config.native_agent_id
2670
+ || now?.machine_id !== config.machine_id || now?.working_directory !== config.working_directory || now?.backend !== config.backend
2671
+ || now?.model !== config.model || now?.native_sandbox !== config.native_sandbox || now?.systemPrompt !== config.systemPrompt || now?.operations !== config.operations || now?.workflow !== config.workflow
2672
+ || now?.general_topic !== config.general_topic || now?.native_general_binding !== config.native_general_binding
2673
+ || nativeCredentialProfile(now) !== nativeCredentialProfile(config))
2674
+ throw Error("Native pane configuration or lifetime changed");
2675
+ // Fail closed: a Runtime that does not report the capability would start the terminal on the computer's own account.
2676
+ if (nativeCredentialProfile(config) && !this.runtimeCoordinator().machine(config.machine_id)?.runtimeInfo?.capabilities.includes(RUNTIME_CREDENTIAL_CAPABILITY))
2677
+ throw Error("This computer's Runtime is too old to choose a Claude account. Update the Runtime on that computer, then try again.");
2678
+ if (config.machine_id ? this.remotePaneDrain || !remoteRuntimeEnabled() : this.localPaneDrain || !localWindowsCliEnabled())
2679
+ throw Error("Native runtime is switched off");
2680
+ },
2681
+ endpoint: async (agent, cleanup = false) => {
2682
+ if (!agent.machineId) {
2683
+ if (!cleanup)
2684
+ return this.localNativePaneEndpoint();
2685
+ if (!this.localPaneRelay)
2686
+ throw Error("Local cleanup transport is unavailable; pane remains reserved");
2687
+ return this.localPaneRelay;
2688
+ }
2689
+ const hub = cleanup ? this.runtimeHub : this.runtimeCoordinator(), machineId = agent.machineId;
2690
+ if (!hub)
2691
+ throw Error("Remote cleanup transport is unavailable; pane remains reserved");
2692
+ const draining = () => !!this.remotePaneDrain;
2693
+ return { machineId, online: () => !this.shuttingDown && (draining() || remoteRuntimeEnabled()) && this.runtimeHub === hub && hub.machine(machineId)?.status === "online",
2694
+ call: request => {
2695
+ if (this.runtimeHub !== hub || !(draining() || remoteRuntimeEnabled()) || draining() && request.action !== "snapshot" && request.action !== "close")
2696
+ return Promise.reject(Error("Remote pane transport only permits owned cleanup"));
2697
+ return hub.callPane(machineId, request, maxAgentsPerMachine());
2698
+ }, subscribe: listener => hub.subscribe(listener),
2699
+ epoch: () => hub.paneTransportEpoch(machineId), version: provider => hub.machine(machineId)?.inventory?.clis.find(row => row.id === provider && row.runnable)?.version ?? null };
2700
+ },
2701
+ instructions: (name, config) => buildNativeFleetInstructions({ instanceName: name, workingDirectory: config.working_directory,
2702
+ displayName: config.display_name, description: config.description, customPrompt: config.systemPrompt, operations: config.operations,
2703
+ workflow: config.workflow, taskBoard: !dashboardRefusalIn(this.fleetConfig, name, "task"),
2704
+ runtimeIdentity: { kind: "fleet-topic", backend: config.backend ?? "codex", model: config.model || "default" } }, config.general_topic === true),
2705
+ menu: name => TOOLS.filter(tool => allowed(name, tool.name)).map(tool => ({ ...tool })),
2706
+ allowed: (name, tool, args) => allowed(name, tool) && !nativePaneToolRefusal(tool, args), published: (name, daemon) => this.daemons.get(name) === daemon,
2707
+ invoke: async (daemon, input, current, name) => {
2708
+ if (input.tool === "list_models") {
2709
+ const { ListModelsArgs } = await import("./outbound-schemas.js");
2710
+ const parsed = ListModelsArgs.safeParse(input.args);
2711
+ if (!parsed.success || !current())
2712
+ return { result: null, error: "Invalid native model request or expired owner" };
2713
+ const target = parsed.data.instance_name ?? name;
2714
+ if (!isWindowsInstance(this.fleetConfig?.instances[target]))
2715
+ return { result: null, error: "Native panes can only read Windows runtime model inventories" };
2716
+ return { result: await this.listModelCatalog({ instanceName: target }) };
2717
+ }
2718
+ 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",
2719
+ delegate_task: "delegate", request_information: "ask", report_result: "report", delivery_status: "delivery-status" };
2720
+ const { nativeAgentAdmissionContext } = await import("./native-agent-admission.js");
2721
+ const { dispatchAgentOperation } = await import("./agent-endpoint.js");
2722
+ return daemon.handlePaneToolCall(input, { current, allowed: tool => allowed(name, tool), ...(input.requestContext ? { requestContext: input.requestContext } : {}),
2723
+ dispatch: (tool, args) => ops[tool] ? dispatchAgentOperation(nativeAgentAdmissionContext(this, {
2724
+ instance: name, operation: { tool, args }, current: () => current() && allowed(name, tool), taskAllowed: () => current() && allowed(name, "task"),
2725
+ ...(input.requestContext?.coverage === "covered" ? { requestContext: input.requestContext.lease } : input.requestContext ? { notCoveredReason: input.requestContext.reason } : {}),
2726
+ }), name, ops[tool], args, input.operationId, () => current() && allowed(name, tool)) : undefined });
2727
+ },
2728
+ });
2729
+ return this.paneManager = graph ? this.ownRequestContextNativeFactory(manager, graph) : manager;
2730
+ }
2731
+ finally {
2732
+ this.requestContextOpeningPaneManagers--;
2733
+ }
1844
2734
  }
1845
2735
  /** Prepare only bundled role files; this neither switches General nor starts a provider process. */
1846
2736
  async prepareWindowsGeneralWorkspace(name, machineId, cli, bindingId, authorized) {
@@ -2181,6 +3071,8 @@ export class FleetManager {
2181
3071
  updateChatCardVersion = new Map();
2182
3072
  /** #4485 review 2: an answer that came while its card was still being posted (the post records it when it returns). */
2183
3073
  updateChatCardAnswered = new Map();
3074
+ /** Prism #4584 (1): a press refused while its card was still being posted (the post records it, so it isn't relabelled expired). */
3075
+ updateChatCardRefused = new Set();
2184
3076
  updateChatCardTimer = null;
2185
3077
  readUpdateChatCard() {
2186
3078
  try {
@@ -2207,14 +3099,18 @@ export class FleetManager {
2207
3099
  if (view && view.state === "offered") {
2208
3100
  // M-3770 1.2's cached pre-flight, when this build has it (#4483): the second sentence only where it is true.
2209
3101
  const pre = this.updatePreflight;
3102
+ // 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).
3103
+ const blocking = pre ? preflightBlocking(pre) : null;
3104
+ if (blocking)
3105
+ return `${t("update.chatcard.offer", view.version)}\n${t("update.chatcard.cant", preflightWords(blocking, (key, ...args) => t(key, ...args)))}`;
2210
3106
  const p3 = pre?.checks.find(c => c.id === "P3");
2211
3107
  // The leader's copy pass (S-237): a title and one line, as on the web.
2212
3108
  const line = !p3 ? t("update.chatcard.continues") : p3.ok ? t("update.chatcard.back", current ?? "?") : t("update.chatcard.noWayBack");
2213
3109
  return `${t("update.chatcard.offer", view.version)}\n${line}`;
2214
3110
  }
2215
3111
  // 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())}`; };
3112
+ // M-3864 R2: the fleet's zone with its offset, as schedules say times (the web shows the person's own zone).
3113
+ const at = (ms) => (ms ? formatFleetTime(ms, this.usageZone()) : "");
2218
3114
  if (view?.state === "waiting-idle")
2219
3115
  return t("update.chatcard.state_waiting", view.version);
2220
3116
  if (view?.state === "scheduled")
@@ -2227,9 +3123,19 @@ export class FleetManager {
2227
3123
  return t("update.chatcard.state_done", view.version);
2228
3124
  if (view?.state === "failed")
2229
3125
  return t("update.chatcard.state_failed", view.version, current ?? "?");
2230
- const reply = updateOfferReply(view, current, !!resolveUpdates(this.fleetConfig?.updates).pin);
3126
+ const reply = updateOfferReply(view, current, !!resolveUpdates(this.fleetConfig?.updates).pin, this.usageZone());
2231
3127
  return t(reply.key, ...reply.args);
2232
3128
  }
3129
+ /**
3130
+ * 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
3131
+ * admin's press (Update when idle) needs pressHere, a picked time (Tonight) a machine that updates itself. No pre-flight
3132
+ * result yet: all three (the launch decides, as on the web).
3133
+ */
3134
+ updateChatCardActions(pre = this.updatePreflight) {
3135
+ if (!pre)
3136
+ return [...UPDATE_CHAT_CARD_ALL];
3137
+ return UPDATE_CHAT_CARD_ALL.filter(a => a === "not-now" || preflightAllows(pre, a === "tonight" ? "unattended" : "press"));
3138
+ }
2233
3139
  /** General's chat place for the card, or null (no General, no chat: a web-only fleet's banner says it). */
2234
3140
  updateChatCardPlace() {
2235
3141
  if (this.webOnlyPromptPlace())
@@ -2269,13 +3175,21 @@ export class FleetManager {
2269
3175
  // #4485 review 1: an offered card whose buttons are gone (a restart empties the nonce map; they also expire) is not
2270
3176
  // a usable card: it is marked expired and one with live buttons is posted.
2271
3177
  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)) {
3178
+ // M-3864 R1: a card whose buttons the machine no longer allows (or newly allows) is posted again with the right ones.
3179
+ const actions = this.updateChatCardActions(), actionsKey = actions.join(",");
3180
+ // Prism #4584 (2): and the reason it gives for not updating here (another stop keeps Not now only but must say so).
3181
+ const blockingCheck = this.updatePreflight ? preflightBlocking(this.updatePreflight) : null;
3182
+ const blockingKey = blockingCheck ? preflightWords(blockingCheck, (key, ...args) => t(key, ...args)) : "";
3183
+ const sameActions = (posted?.actions ?? UPDATE_CHAT_CARD_ALL.join(",")) === actionsKey && (posted?.blocking ?? "") === blockingKey;
3184
+ if (view && state === "offered" && view.installable && (!posted || posted.version !== view.version || posted.state !== "offered" || !live || !sameActions)) {
2273
3185
  const place = this.updateChatCardPlace();
2274
3186
  if (!place)
2275
3187
  return;
2276
- if (posted) {
3188
+ // A refused press already edited its card to say why; that text stays (it is not called expired).
3189
+ if (posted && !(posted.refused && posted.version === view.version && !live)) {
2277
3190
  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);
3191
+ : posted.state === "offered" && posted.version === view.version && !sameActions ? t("update.chatcard.replaced", view.version)
3192
+ : posted.version === view.version ? t("update.chatcard.cancelled", posted.version) : t("update.chatcard.replaced", view.version);
2279
3193
  await this.editUpdateChatCard(posted, old);
2280
3194
  }
2281
3195
  const version = view.version;
@@ -2283,7 +3197,7 @@ export class FleetManager {
2283
3197
  prefix: UPDATE_CARD_CALLBACK_PREFIX, alertType: "tip", instanceName: place.general, adapter: place.adapter, adapterId: place.adapterId,
2284
3198
  chatId: place.chatId, ...(place.threadId ? { threadId: place.threadId } : {}),
2285
3199
  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") }],
3200
+ choices: actions.map(action => ({ action, label: t(action === "when-idle" ? "update.chatcard.when_idle" : action === "tonight" ? "update.chatcard.tonight" : "update.chatcard.not_now") })),
2287
3201
  expiredText: t("update.chatcard.expired"),
2288
3202
  timeoutMs: UPDATE_CHAT_CARD_MS,
2289
3203
  // #4485 review 2: the provider's own delivery address, kept per nonce as it is sent — a click may consume the
@@ -2302,12 +3216,14 @@ export class FleetManager {
2302
3216
  const sent = this.updateChatCardSent.get(nonce);
2303
3217
  const answered = this.updateChatCardAnswered.get(nonce);
2304
3218
  this.updateChatCardAnswered.delete(nonce);
2305
- this.writeUpdateChatCard({ version, state: answered ?? "offered", nonce: answered ? null : nonce, messageId: sent?.messageId ?? "",
3219
+ const refused = this.updateChatCardRefused.delete(nonce);
3220
+ this.writeUpdateChatCard({ version, state: answered ?? "offered", nonce: answered || refused ? null : nonce, messageId: sent?.messageId ?? "",
2306
3221
  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.
3222
+ adapterId: place.adapterId, at: Date.now(), actions: actionsKey, ...(blockingKey ? { blocking: blockingKey } : {}), ...(refused ? { refused: true } : {}) });
3223
+ // The card may have moved on while this was being posted (a newer version, an answer on the web), or a press on it
3224
+ // was refused (the machine changed): sync again.
2309
3225
  const after = this.updateOfferView();
2310
- if (!answered && (after?.version !== version || (after?.state ?? "none") !== "offered"))
3226
+ if (refused || !answered && (after?.version !== version || (after?.state ?? "none") !== "offered"))
2311
3227
  this.updateChatCardAgain = true;
2312
3228
  return;
2313
3229
  }
@@ -2368,8 +3284,7 @@ export class FleetManager {
2368
3284
  await this.retireNonceButtons(entry, messageId, shownVersion && before && before.version !== shownVersion ? t("update.chatcard.replaced", before.version) : t("update.chatcard.expired"));
2369
3285
  return true;
2370
3286
  }
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(); })();
3287
+ const tonight = updateTonightAt(Date.now(), this.usageZone());
2373
3288
  const body = action === "tonight" ? { action: "pick-time", at: tonight } : { action: action };
2374
3289
  const by = updateAnswerLabel(data.username ?? "");
2375
3290
  let text;
@@ -2382,17 +3297,24 @@ export class FleetManager {
2382
3297
  }
2383
3298
  catch { /* unknown */ }
2384
3299
  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));
3300
+ // M-3864 R1: the machine's pre-flight refused it: the reason in words (as the web and /update say it), never the key.
3301
+ const preflight = !r.ok && "key" in r.body && r.body.key === "preflight" ? r.body.preflight : null;
3302
+ const refusal = preflight ? preflightRefusal(preflight, action === "tonight" ? "unattended" : "press", (key, ...args) => t(key, ...args)) : null;
3303
+ text = r.ok ? t("update.chatcard.by", this.updateChatCardText(view, current), by) : refusal ?? t("update.chatcard.refused", why || String(r.status));
2386
3304
  const posted = this.readUpdateChatCard();
2387
3305
  const nextState = view?.state ?? "none";
2388
3306
  if (posted && posted.nonce === nonce) {
2389
3307
  // 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 ?? "") });
3308
+ this.writeUpdateChatCard({ ...posted, state: nextState, nonce: null, messageId: posted.messageId || sent?.messageId || String(messageId ?? ""), ...(r.ok ? {} : { refused: true }) });
2391
3309
  }
2392
3310
  else if (r.ok) {
2393
3311
  // The card is still being posted (its record is written when the post returns): it records this answer then.
2394
3312
  this.updateChatCardAnswered.set(nonce, nextState);
2395
3313
  }
3314
+ else {
3315
+ // Prism #4584 (1): a refusal too, so that post records its text as what the message says (not expired).
3316
+ this.updateChatCardRefused.add(nonce);
3317
+ }
2396
3318
  }
2397
3319
  catch (err) {
2398
3320
  text = t("update.chatcard.refused", err.message);
@@ -3714,16 +4636,21 @@ export class FleetManager {
3714
4636
  }
3715
4637
  }
3716
4638
  /** The agent's durable incarnation id (create: make one if none; else null). A changed fingerprint rotates it. */
3717
- hubAgentIncarnation(agent, cfg, create) {
4639
+ hubAgentIncarnation(agent, cfg, create, explicitBirth = false) {
3718
4640
  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
4641
  const map = this.readHubIncarnations(), entry = Object.prototype.hasOwnProperty.call(map, agent) ? map[agent] : undefined;
3720
- if (entry && entry.fp === fp && typeof entry.id === "string")
4642
+ if (entry && entry.fp === fp && typeof entry.id === "string") {
4643
+ if (explicitBirth && !entry.requestWork && !entry.retired?.length) {
4644
+ map[agent] = { ...entry, requestWork: "pending" };
4645
+ return this.writeHubIncarnations(map) === "written" ? entry.id : null;
4646
+ }
3721
4647
  return entry.id;
4648
+ }
3722
4649
  if (!entry && !create)
3723
4650
  return null;
3724
- map[agent] = { id: randomUUID(), fp, ...(cfg.hubClassicIdentity ? { classic: true } : {}) };
4651
+ map[agent] = rotateHubAgentIncarnation(entry, fp, !!cfg.hubClassicIdentity, Date.now(), explicitBirth);
3725
4652
  // 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;
4653
+ return this.writeHubIncarnations(map) === "written" ? map[agent].id ?? null : null;
3727
4654
  }
3728
4655
  /**
3729
4656
  * Every configuration in force: rotate a recorded agent's incarnation when its backend/folder/runtime changed; drop
@@ -3739,6 +4666,16 @@ export class FleetManager {
3739
4666
  this.settleHubIncarnations();
3740
4667
  if (this.hubIncarnationsBroken)
3741
4668
  throw new Error("Hub agent incarnations cannot be written here");
4669
+ // Only a strict new configuration entry can mint first-birth evidence. A lazy token read,
4670
+ // a restart or a missing/corrupt incarnation/work file can never invent that transition.
4671
+ if (strict && this.savedFleetConfigSnapshot?.instances) {
4672
+ for (const agent of Object.keys(this.fleetConfig.instances))
4673
+ if (!Object.hasOwn(this.savedFleetConfigSnapshot.instances, agent)) {
4674
+ const config = this.hubAgentConfig(agent);
4675
+ if (config)
4676
+ this.hubAgentIncarnation(agent, config, true, true);
4677
+ }
4678
+ }
3742
4679
  if (!existsSync(this.hubIncarnationsPath()))
3743
4680
  return;
3744
4681
  for (const agent of Object.keys(this.readHubIncarnations())) {
@@ -3764,7 +4701,9 @@ export class FleetManager {
3764
4701
  const map = this.readHubIncarnations();
3765
4702
  if (!Object.prototype.hasOwnProperty.call(map, agent))
3766
4703
  return;
3767
- delete map[agent];
4704
+ if (!map[agent]?.id)
4705
+ return;
4706
+ map[agent] = forgetHubAgentIncarnation(map[agent]);
3768
4707
  this.writeHubIncarnations(map);
3769
4708
  }
3770
4709
  catch (err) {
@@ -3881,7 +4820,19 @@ export class FleetManager {
3881
4820
  * A Hub question to its representative agent: ordinary cross-instance delivery (idle gate, wake, retries), from the
3882
4821
  * reserved Hub sender with the Hub-issued correlation id. beforeInput runs immediately before the IPC hand-off.
3883
4822
  */
4823
+ requestContextHubAdmission;
4824
+ /** Installed as one of the publication's ingress owners, never from a tool or a question selector. */
4825
+ makeRequestContextHubAdmission(resolve) {
4826
+ return (input) => {
4827
+ const resolver = resolve(input.agent);
4828
+ if (!resolver)
4829
+ throw Error("Hub request input owner is unavailable");
4830
+ return resolver.capture(input);
4831
+ };
4832
+ }
3884
4833
  async deliverHubQuestion(input) {
4834
+ if (this.requestContextAdmission && !await this.requestContextAdmission.wait(() => !this.shuttingDown && input.stillCurrent()))
4835
+ return false;
3885
4836
  const { HUB_REPORT_TARGET } = await import("./hub/representative.js");
3886
4837
  const config = this.hubAgentConfig(input.agent);
3887
4838
  if (this.shuttingDown || !config)
@@ -3889,6 +4840,9 @@ export class FleetManager {
3889
4840
  // Windows agents run through their own runtime, which has no pre-input hook: not a P1 representative.
3890
4841
  if (isNativeExecInstance(config))
3891
4842
  return false;
4843
+ const scoped = requestContextPolicyInstalled(this.requestContextPolicy) ? this.requestContextHubAdmission?.(input) : undefined;
4844
+ if (requestContextPolicyInstalled(this.requestContextPolicy) && !scoped)
4845
+ throw Error("Hub request input admission is unavailable");
3892
4846
  const ipcMeta = {
3893
4847
  chat_id: "",
3894
4848
  message_id: `hubmsg-${input.correlationId.slice(4)}`,
@@ -3908,7 +4862,7 @@ export class FleetManager {
3908
4862
  // M-3660: the share's opt-out travels with the question; its daemon's hub_question_input then opens no window.
3909
4863
  if (input.contactLimit === false)
3910
4864
  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 () => {
4865
+ 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
4866
  const classic = this.isClassicInstance(input.agent);
3913
4867
  // A busy Classic room must finish its public turn first; never force a private question into that turn's queue.
3914
4868
  const idle = () => this.waitForInstanceIdle(input.agent, 0, this.lastDeliveryAt.get(input.agent) ?? 0, () => !input.stillCurrent());
@@ -3919,6 +4873,8 @@ export class FleetManager {
3919
4873
  if (generation)
3920
4874
  ipcMeta.hub_room_context_generation = generation;
3921
4875
  }
4876
+ if (scoped && !await scoped.waitBeforeInput())
4877
+ return false;
3922
4878
  if (!(await input.beforeInput()))
3923
4879
  return false;
3924
4880
  if (classic) {
@@ -4125,6 +5081,12 @@ export class FleetManager {
4125
5081
  hubRoomList(caller) {
4126
5082
  return this.hubAgentRooms?.rooms(caller) ?? Promise.resolve({ ok: false, code: "unavailable" });
4127
5083
  }
5084
+ hubRoomHistory(caller, room, options) {
5085
+ const policy = this.requestContextPolicy;
5086
+ if (!policy || requestContextInstalledMode(policy) !== "active")
5087
+ return Promise.resolve({ ok: false, code: "denied" });
5088
+ return this.hubAgentRooms?.history({ ...caller, current: () => this.requestContextPolicy === policy && requestContextInstalledMode(policy) === "active" && caller.current() }, room, options) ?? Promise.resolve({ ok: false, code: "unavailable" });
5089
+ }
4128
5090
  hubRoomMembers(caller, room, options) {
4129
5091
  return this.hubAgentRooms?.members(caller, room, options) ?? Promise.resolve({ ok: false, code: "unavailable" });
4130
5092
  }
@@ -4452,6 +5414,9 @@ export class FleetManager {
4452
5414
  /** M-3770 (#4480 §4): the last pre-flight — a diagnostic for the page; every launch proves its local checks again. */
4453
5415
  updatePreflight = null;
4454
5416
  updatePreflightRunning = null;
5417
+ /** 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. */
5418
+ updateFixAnswers = new Map();
5419
+ updateFixChain = Promise.resolve();
4455
5420
  /** M-2738: a web start's Idempotency-Key → its answer (a retried request never starts a second update). */
4456
5421
  webUpdateStarts = new Map();
4457
5422
  /**
@@ -5062,6 +6027,7 @@ export class FleetManager {
5062
6027
  const baselines = this.settingsBaselineReader = new SettingsBaselines({ dataDir: this.dataDir, configPath: () => this.configPath,
5063
6028
  config: () => this.fleetConfig, current: () => [this.settingsGeneration, this.settingsRuntimeRevision, this.shuttingDown],
5064
6029
  generalLocation: input => this.previewGeneralLocation(input),
6030
+ requestContextControl: () => this.requestContextControl?.snapshot() ?? null,
5065
6031
  hubMembership: raw => hubMembershipSettings(raw),
5066
6032
  hubPageSharing: raw => hubPageSharingSettings(raw),
5067
6033
  guestDerivedScopes: () => this.guestDerivedScopes(),
@@ -5131,6 +6097,7 @@ export class FleetManager {
5131
6097
  current: () => current() && sessions === this.webSessions && !!this.webToken
5132
6098
  && sessions.isCurrent(record, tokenEpoch(this.webToken)) && (!exposure || exposure.isCurrent()) };
5133
6099
  }, baseline: () => baselines.read(), snapshot: () => baselines.snapshot(),
6100
+ requestContextControl: () => this.requestContextControl,
5134
6101
  selfConfirm: (req, id) => this.settingsSelfConfirmation(store, req, id),
5135
6102
  totp: { state: (req, id) => this.settingsTotpState(store, req, id), confirm: (req, id, code, digest) => this.settingsTotpConfirm(store, req, id, code, digest) },
5136
6103
  remote: req => this.settingsPageIsRemote(req),
@@ -6532,7 +7499,22 @@ export class FleetManager {
6532
7499
  const dbPath = join(this.dataDir, "delivery-outbox.db");
6533
7500
  let outbox;
6534
7501
  try {
6535
- outbox = new DeliveryOutbox(dbPath, this.managerBootId);
7502
+ const activated = readRequestContextBootState(this.dataDir);
7503
+ if (activated && !this.requestContextBoot) {
7504
+ const lease = captureProcessFleetLease(this.dataDir);
7505
+ if (!lease)
7506
+ throw Error("Request-context Fleet lease unavailable");
7507
+ const boot = new RequestContextBoot(activated, lease);
7508
+ this.requestContextBoot = boot;
7509
+ this.attachRequestContextAdmission(boot.publication.admission);
7510
+ this.requestContextPolicy = boot.policy;
7511
+ // Replaced only by the controlled installer: a legacy launch must never slip through startup recovery.
7512
+ this.prepareRequestContextStart = () => boot.requirePreparedOwner();
7513
+ }
7514
+ outbox = new DeliveryOutbox(dbPath, this.managerBootId, this.requestContextBoot ? {
7515
+ requestContextDispatchVersion: 1, requestContextRelayVersion: 1,
7516
+ requestContextRecoveryFence: this.requestContextBoot.recoveryCurrent,
7517
+ } : {});
6536
7518
  if (!this.deliveryOutboxRecovered) {
6537
7519
  const recovered = outbox.recoverForBoot(this.managerBootId);
6538
7520
  this.logger.info({ ...recovered }, "Recovered durable delivery outbox for this process boot");
@@ -6551,12 +7533,20 @@ export class FleetManager {
6551
7533
  }
6552
7534
  this.deliveryOutbox = outbox;
6553
7535
  this.deliveryOutboxRecovered = true;
7536
+ this.ensureRequestContextController();
6554
7537
  this.initializeWorkingRecovery(outbox);
6555
7538
  outbox.on("working_references", (names) => {
6556
7539
  for (const name of names)
6557
7540
  this.observeWorkingState(name, "obligations");
6558
7541
  });
6559
- outbox.on("admitted", () => { this.scheduleDeliveryOutboxPump(); this.wakeCoordinator?.kick(); });
7542
+ outbox.on("request_context_admitted", () => {
7543
+ if (this.requestContextAdmission) {
7544
+ this.requestContextAdmission.arrived();
7545
+ this.scheduleDeliveryOutboxPump();
7546
+ this.wakeCoordinator?.kick();
7547
+ }
7548
+ });
7549
+ outbox.on("admitted", () => { this.requestContextAdmission?.arrived(); this.scheduleDeliveryOutboxPump(); this.wakeCoordinator?.kick(); });
6560
7550
  outbox.on("state", (event) => {
6561
7551
  if (event.deliveryId) {
6562
7552
  const row = outbox.get(event.deliveryId);
@@ -6606,11 +7596,13 @@ export class FleetManager {
6606
7596
  const row = event.deliveryId ? outbox.get(event.deliveryId) : undefined;
6607
7597
  if (row)
6608
7598
  this.publishTraffic(row);
7599
+ this.noteTaskWakeDelivery(event.deliveryId);
6609
7600
  });
6610
7601
  outbox.on("consumed", (event) => {
6611
7602
  const row = event.deliveryId ? outbox.get(event.deliveryId) : undefined;
6612
7603
  if (row)
6613
7604
  this.publishTraffic(row, "consumed");
7605
+ this.noteTaskWakeDelivery(event.deliveryId);
6614
7606
  });
6615
7607
  outbox.on("generation_recovered", () => this.scheduleDeliveryOutboxPump());
6616
7608
  this.sweepContactAuthorizationOutcomes();
@@ -6902,7 +7894,23 @@ export class FleetManager {
6902
7894
  makeRequestContextPolicy() {
6903
7895
  return { assert: input => {
6904
7896
  try {
6905
- return assertRequestContextOperation(input);
7897
+ const permit = assertRequestContextOperation(input);
7898
+ // Ordinary ingress is not administrator authority. Recheck the ORIGINAL actor for owner-only
7899
+ // tools on every call, including commit-point calls; demotion alone never adds a contact hold.
7900
+ if (permit.context && toolsFor("coordinator").has(permit.tool) && !toolsFor("worker").has(permit.tool)) {
7901
+ if (permit.context.ingress === "guest" || permit.context.ingress === "hub")
7902
+ throw new RequestContextPolicyError("settings");
7903
+ const actor = permit.context.initiatingActor;
7904
+ const adapter = actor.kind === "person" && actor.platform !== "hub" && actor.platform !== "host"
7905
+ ? [...this.adapters.values(), ...[...this.worlds.values()].map(world => world.adapter)].find(row => row.type === actor.platform) : undefined;
7906
+ const channel = actor.kind === "person" && actor.platform !== "hub"
7907
+ ? (this.fleetConfig?.channels ?? (this.fleetConfig?.channel ? [this.fleetConfig.channel] : [])).find(row => row.type === actor.platform) : undefined;
7908
+ const person = actor.kind === "person" && actor.platform !== "hub"
7909
+ ? { platform: actor.platform, adapterId: actor.platform === "host" ? "host" : adapter?.id ?? channel?.id ?? channel?.type ?? "", userId: actor.userId, label: actor.displayName ?? actor.userId } : null;
7910
+ if (!person?.adapterId || !this.contactAdminOf(permit.context.source.instance, person))
7911
+ throw new RequestContextPolicyError("settings");
7912
+ }
7913
+ return permit;
6906
7914
  }
6907
7915
  catch (error) {
6908
7916
  if (error instanceof RequestContextPolicyError) {
@@ -6913,6 +7921,526 @@ export class FleetManager {
6913
7921
  }
6914
7922
  } };
6915
7923
  }
7924
+ /** Existing Settings administrator scope. This only identifies a principal; it never bypasses per-change confirmation. */
7925
+ requestContextControl;
7926
+ requestContextShadow() {
7927
+ const box = this.deliveryOutbox, lease = captureProcessFleetLease(this.dataDir);
7928
+ return box.requestContextMigrationShadow({ owner: () => this.requestContextBoot?.owner.owner ?? lease?.id ?? null,
7929
+ policyEpoch: () => requestContextDigest([this.fleetConfig, this.settingsRuntimeRevision]), generation: name => { try {
7930
+ return this.contactGeneration(name);
7931
+ }
7932
+ catch {
7933
+ return null;
7934
+ } }, canManage: (name, actor) => this.contactAdminOf(name, actor) }).inspect();
7935
+ }
7936
+ requestContextBlockers() {
7937
+ const box = this.deliveryOutbox;
7938
+ if (!box || !this.fleetConfig)
7939
+ return [{ id: "owners", kind: "owners", labels: [], ownerCause: "update", action: "inspect" }];
7940
+ const label = (name) => this.fleetConfig?.instances[name]?.display_name ?? this.classicChannels?.getAll().find(row => row.instanceName === name)?.displayName ?? name;
7941
+ const state = box.requestContextInstallation().read(), out = [];
7942
+ if (!requestContextUpdateSettled(this.dataDir))
7943
+ out.push({ id: "update", kind: "update", labels: [], action: "inspect" });
7944
+ if (state && (!this.requestContextModes?.current() || !this.requestContextBoot?.publication.installed()) && state.mode !== "draining")
7945
+ out.push({ id: "installation", kind: "owners", labels: [], ownerCause: "update", action: "inspect" });
7946
+ if (!state) {
7947
+ const shadow = this.requestContextShadow();
7948
+ // S-272 (Sentinel's settlement split): each earlier ticket by what settles it. Pending: decided on Authorizations.
7949
+ // Approved and still being delivered (queued … retry_wait): waits for that delivery's own outcome. Approved with a delivery
7950
+ // that ended unconfirmed (e.g. uncertain: terminal, never changes again, Fable #4593), with no or a mismatched record, or
7951
+ // unreadable: nothing here can settle it (absence is never a proof of delivery), so it is named as such.
7952
+ const ids = (...dispositions) => shadow.tickets.filter(row => dispositions.includes(row.disposition)).map(row => row.id);
7953
+ const pending = ids("preserve-legacy-pending"), inflight = ids("legacy-inflight"), unsettled = ids("legacy-unconfirmed", "missing-receipt", "malformed"), named = new Set([...pending, ...inflight, ...unsettled]);
7954
+ if (pending.length)
7955
+ out.push({ id: "legacy-pending", kind: "legacy", labels: pending.slice(0, 64), action: "inspect" });
7956
+ if (inflight.length)
7957
+ out.push({ id: "legacy-inflight", kind: "legacy", labels: inflight.slice(0, 64) });
7958
+ // M-3897: each one an owner can retire (its exact image is readable) gets its own blocker and Retire; an oversized one
7959
+ // that cannot be bound to an image stays named, with no action.
7960
+ const retirable = new Set(shadow.tickets.filter(row => unsettled.includes(row.id) && row.sha256).map(row => row.id));
7961
+ for (const id of unsettled.filter(id => retirable.has(id)).slice(0, 32))
7962
+ out.push({ id: `legacy-retire:${id}`, kind: "legacy", labels: [id], action: "retire" });
7963
+ const unbound = unsettled.filter(id => !retirable.has(id));
7964
+ if (unbound.length)
7965
+ out.push({ id: "legacy-unsettled", kind: "legacy", labels: unbound.slice(0, 64) });
7966
+ const rest = shadow.blockers.map(row => row.id).filter(id => !named.has(id));
7967
+ if (rest.length || !shadow.complete && !named.size)
7968
+ out.push({ id: "legacy", kind: "legacy", labels: rest.slice(0, 64), action: "inspect" });
7969
+ const inventory = box.requestContextControlInventory(), legacy = inventory.deliveries.filter(row => !row.root);
7970
+ // M-3897: an earlier delivery still queued (or waiting to retry) can be withdrawn by its exact image; one being sent
7971
+ // waits for its own outcome; an uncertain one never changes by itself and is named as such (no guess, no relabel).
7972
+ const pair = (row) => `${label(row.source)} → ${label(row.target)}`;
7973
+ for (const row of legacy.filter(row => ["queued", "retry_wait"].includes(row.state)).slice(0, 32))
7974
+ out.push({ id: `legacy-withdraw:${row.id}`, kind: "legacy", labels: [pair(row)], action: "withdraw" });
7975
+ const sending = legacy.filter(row => ["delivering", "submission_started"].includes(row.state));
7976
+ if (sending.length)
7977
+ out.push({ id: "legacy-deliveries", kind: "legacy", labels: sending.map(pair).slice(0, 64) });
7978
+ const needsTicketRetirement = new Set(shadow.tickets.filter(row => ["legacy-unconfirmed", "missing-receipt", "malformed"].includes(row.disposition)).map(row => `contact:${row.id}`));
7979
+ for (const row of legacy.filter(row => row.state === "uncertain")) {
7980
+ const delivery = box.get(row.id);
7981
+ if (!delivery || needsTicketRetirement.has(delivery.sourceKey))
7982
+ continue;
7983
+ out.push({ id: `legacy-uncertain:${row.id}:${box.requestContextLegacyAcknowledgementImage(row.id)}`, kind: "legacy", labels: [`${label(row.source)} → ${label(row.target)}`], action: "acknowledge" });
7984
+ }
7985
+ 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);
7986
+ for (const row of WindowsAgents.requestContextOwnersOnDisk(this.dataDir)) {
7987
+ const daemon = row.instance ? this.daemons.get(row.instance) : undefined;
7988
+ // An owned idle persistent pane participates in the controlled relaunch. An exec or cold orphan does not.
7989
+ if (row.kind === "pane" && row.instance && daemon?.usesNativePane() && nativeAgentId(this.hubAgentConfig(row.instance)) === row.agentId)
7990
+ continue;
7991
+ const name = row.instance ?? row.agentId;
7992
+ if (!busy.includes(name))
7993
+ busy.push(name);
7994
+ }
7995
+ if (busy.length)
7996
+ 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" });
7997
+ const peers = this.captureRequestContextRuntimeSet(), old = peers.advertised();
7998
+ if (old.length)
7999
+ out.push({ id: "peers", kind: "peers", labels: peers.labels().filter(row => old.includes(row.id)).map(row => row.label).slice(0, 64), action: "inspect" });
8000
+ }
8001
+ else if (state.mode === "draining") {
8002
+ const inventory = box.requestContextControlInventory(box.requestContextInstallation().drainRoots());
8003
+ for (const row of inventory.recoveries)
8004
+ out.push({ id: `recovery:${requestContextDigest(row.pointer)}`, kind: "recovery", labels: [label(row.instance)], agents: [{ id: row.instance, label: label(row.instance) }], action: "stop-work" });
8005
+ for (const row of inventory.returns)
8006
+ out.push({ id: `return:${row.requestDeliveryId}`, kind: "returns", labels: [`${label(row.requester.instance)} → ${label(row.responder.instance)}`], action: "stop-waiting" });
8007
+ for (const row of inventory.tickets)
8008
+ out.push({ id: `ticket:${row.id}`, kind: "tickets", labels: [`${label(row.source)} → ${label(row.target)}`], action: "decline" });
8009
+ for (const row of inventory.deliveries)
8010
+ out.push({ id: `delivery:${row.id}`, kind: "work", labels: [`${label(row.source)} → ${label(row.target)}`], action: ["queued", "retry_wait"].includes(row.state) ? "withdraw" : "inspect" });
8011
+ if (this.requestContextModes)
8012
+ for (const root of box.requestContextInstallation().drainRoots()) {
8013
+ const view = this.requestContextModes.drain.inspectWork(root), projected = projectRequestContextWork(view.blockers);
8014
+ const recoveryIds = new Set(inventory.recoveries.filter(row => row.root === root).map(row => `recovery:${requestContextDigest(row.pointer)}`));
8015
+ if (!projected.families.length) {
8016
+ if (view.blockers.some(value => value !== "recovery-pointer"))
8017
+ for (const row of out)
8018
+ if (recoveryIds.has(row.id))
8019
+ row.action = "inspect";
8020
+ continue;
8021
+ }
8022
+ // One root action names the whole stop. Do not show a second pointer-only
8023
+ // action that could stop the owner and then fail on its human receipt.
8024
+ for (let index = out.length - 1; index >= 0; index--)
8025
+ if (recoveryIds.has(out[index].id))
8026
+ out.splice(index, 1);
8027
+ const context = box.requestContext(root), names = new Set(context ? [context.source.instance] : []);
8028
+ for (const row of inventory.recoveries)
8029
+ if (row.root === root)
8030
+ names.add(row.instance);
8031
+ for (const [name, daemon] of this.daemons)
8032
+ if (daemon.requestContextTurnSnapshot()?.context.ref.rootContextId === root)
8033
+ names.add(name);
8034
+ const receipts = box.requestContextUncertainHumanImages(root), pointers = inventory.recoveries.filter(row => row.root === root).map(row => row.pointer);
8035
+ const sha = requestContextDigest({ root, blockers: view.blockers, revisions: [...view.revisions], receipts, pointers });
8036
+ out.push({ id: `work:${root}:${sha}`, kind: "work", labels: [...names].map(label).slice(0, 64), agents: [...names].map(id => ({ id, label: label(id) })).slice(0, 64),
8037
+ families: projected.families, unknownEnd: projected.unknownEnd, action: projected.stoppable ? "stop-work" : "inspect" });
8038
+ }
8039
+ }
8040
+ return [...out, ...this.requestContextCutoverErrors].slice(0, 128);
8041
+ }
8042
+ requestContextActivationLease() {
8043
+ const lease = captureProcessFleetLease(this.dataDir), prefix = installPrefixOf(fileURLToPath(new URL("..", import.meta.url)));
8044
+ if (!lease || !prefix)
8045
+ return null;
8046
+ const admission = createRequire(import.meta.url)("../launcher/install-admission.cjs");
8047
+ 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);
8048
+ }
8049
+ ensureRequestContextController() {
8050
+ const box = this.deliveryOutbox, lease = captureProcessFleetLease(this.dataDir), manager = this.managerBootId;
8051
+ if (!box || !lease?.current() || this.requestContextControlBox === box)
8052
+ return;
8053
+ const current = () => !this.shuttingDown && lease.current() && this.managerBootId === manager && this.deliveryOutbox === box;
8054
+ const controller = new RequestContextController({ current, enableUnavailable: () => true, principal: (req, url) => this.requestContextControlPrincipal(req, url),
8055
+ permitContinuation: (req, res) => permitWebContinuation(req, res, { webToken: this.webToken, webSessions: this.webSessions }),
8056
+ base: () => ({ state: box.requestContextInstallation().read(), offer: captureRequestContextEnableOffer(this.dataDir), restartCount: box.requestContextInstallation().read() ? 0 : this.daemons.size, timeZone: this.usageZone() }),
8057
+ inspect: () => this.requestContextBlockers(),
8058
+ enable: async (actor, offer, decisionCurrent) => {
8059
+ this.requestContextCutoverErrors = [];
8060
+ if (this.requestContextBlockers().length)
8061
+ return;
8062
+ const update = this.requestContextActivationLease();
8063
+ if (!update) {
8064
+ this.requestContextCutoverErrors = [{ id: "update-lock", kind: "update", labels: [], action: "inspect" }];
8065
+ return;
8066
+ }
8067
+ let stage, preparingPeerLabels = [];
8068
+ try {
8069
+ if (!decisionCurrent() || !offer.current())
8070
+ throw Error("stale");
8071
+ const state = box.requestContextInstallation().read(), peers = this.captureRequestContextRuntimeSet();
8072
+ preparingPeerLabels = peers.labels().map(row => row.label).slice(0, 64);
8073
+ let peerProof;
8074
+ const transports = () => { try {
8075
+ const proof = peers.prove();
8076
+ if (!peerProof)
8077
+ peerProof = proof;
8078
+ return peerProof.current();
8079
+ }
8080
+ catch {
8081
+ return false;
8082
+ } };
8083
+ if (!state) {
8084
+ let shadow;
8085
+ const drained = () => { if (!current())
8086
+ return false; const next = this.requestContextShadow(); if (!shadow)
8087
+ shadow = next; return next.complete && !next.blockers.length && next.sha256 === shadow.sha256 && !box.requestContextControlInventory().deliveries.some(row => !row.root) && this.requestContextPendingWork.empty; };
8088
+ stage = await this.prepareRequestContextFirstOnAssembly(drained, transports, this.requestContextRootRetired, offer, actor.execution, peers.prepare);
8089
+ if (!decisionCurrent() || !update.current() || !stage.ready())
8090
+ throw Error("stale");
8091
+ 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(); });
8092
+ }
8093
+ else {
8094
+ if (state.mode !== "off" || !this.requestContextModes?.current())
8095
+ throw Error("unavailable");
8096
+ await peers.prepare();
8097
+ peerProof = peers.prove();
8098
+ const modes = this.requestContextModes;
8099
+ 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()); });
8100
+ }
8101
+ this.postFleetSecurityNotice(requestContextEnabledNotice(getLocale()), `request-context:${box.requestContextInstallation().read().epoch}`);
8102
+ }
8103
+ catch (error) {
8104
+ this.logger?.warn?.({ err: error }, "Request-context enable did not finish");
8105
+ if (stage && box.requestContextInstallation().read() === null)
8106
+ await stage.rollback();
8107
+ const detail = error;
8108
+ if (box.requestContextInstallation().read() === null && detail.code?.startsWith("request-context-")) {
8109
+ 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" }];
8110
+ return;
8111
+ }
8112
+ throw error;
8113
+ }
8114
+ finally {
8115
+ update.release();
8116
+ }
8117
+ },
8118
+ disable: async (actor, decisionCurrent) => {
8119
+ if (!this.requestContextModes?.current() && this.requestContextBoot?.publication.heldUnpublished()) {
8120
+ await this.resetRequestContextUnpublishedPreparation();
8121
+ if (!decisionCurrent())
8122
+ throw Error("stale");
8123
+ await this.prepareRequestContextCapableBoot(this.requestContextRootRetired);
8124
+ }
8125
+ const modes = this.requestContextModes, state = box.requestContextInstallation().read();
8126
+ if (!modes?.current() || !state)
8127
+ throw Error("unavailable");
8128
+ actor.execution.commit(() => { if (state.mode === "active")
8129
+ modes.off.begin(state.revision, decisionCurrent); });
8130
+ this.scheduleRequestContextDrain();
8131
+ },
8132
+ resolve: (blocker, actor, decisionCurrent) => this.resolveRequestContextBlocker(blocker, actor, decisionCurrent),
8133
+ changed: () => { this.needsYou?.poke(); this.emitSseEvent("request-context-control", controller.snapshot()); this.emitSseEvent("needs", { items: this.needsYouItems() }); }, });
8134
+ this.requestContextControl = controller;
8135
+ this.requestContextControlBox = box;
8136
+ }
8137
+ async prepareRequestContextFutureOwners() {
8138
+ const factory = this.requestContextFactoryOwner;
8139
+ if (!factory?.current())
8140
+ throw Error("Request owner factory unavailable");
8141
+ const names = [...new Set([...Object.keys(this.fleetConfig?.instances ?? {}), ...(this.classicChannels?.getAll() ?? []).map(row => row.instanceName)])];
8142
+ for (const name of names)
8143
+ if (!this.daemons.has(name)) {
8144
+ const config = this.hubAgentConfig(name);
8145
+ if (!config)
8146
+ throw Error("Request owner configuration unavailable");
8147
+ await factory.beforeStart(name, config);
8148
+ }
8149
+ }
8150
+ requestContextOwnersReady() {
8151
+ try {
8152
+ const factory = this.requestContextFactoryOwner, box = this.deliveryOutbox;
8153
+ if (!factory?.current() || !box)
8154
+ return false;
8155
+ for (const [name, daemon] of this.daemons)
8156
+ if (!factory.bound(name, daemon) || daemon.requestContextHelperReadiness()?.ready !== true)
8157
+ return false;
8158
+ const names = [...new Set([...Object.keys(this.fleetConfig?.instances ?? {}), ...(this.classicChannels?.getAll() ?? []).map(row => row.instanceName)])];
8159
+ return names.every(name => box.requestContextWork.read(name)?.incarnation === this.contactGeneration(name));
8160
+ }
8161
+ catch {
8162
+ return false;
8163
+ }
8164
+ }
8165
+ /** A clock selects old candidates; it never proves completion, delivery, or launch retirement. */
8166
+ collectRequestContextRoots() {
8167
+ const modes = this.requestContextModes, box = this.deliveryOutbox;
8168
+ if (this.shuttingDown || !box?.isOpen || !modes?.current() || !modes.boot.publication.installed())
8169
+ return;
8170
+ for (const candidate of box.requestContextRetirementCandidates()) {
8171
+ let epoch;
8172
+ try {
8173
+ epoch = candidate.epoch ? modes.drain.resume(candidate.root, candidate.epoch) : modes.drain.fence(candidate.root);
8174
+ const proof = modes.drain.prove(candidate.root, epoch);
8175
+ this.requestContextRetirementProofs.set(candidate.root, proof);
8176
+ modes.retireRoot(candidate.root);
8177
+ }
8178
+ catch (error) {
8179
+ this.logger.debug?.({ root: candidate.root, err: error.message }, "Request root remains retained");
8180
+ // Failed or busy candidates stay retained and reopen only while their exact root still exists.
8181
+ if (epoch && box.requestContext(candidate.root))
8182
+ try {
8183
+ modes.drain.release(candidate.root, epoch);
8184
+ }
8185
+ catch { /* still fenced, never guessed open */ }
8186
+ }
8187
+ finally {
8188
+ this.requestContextRetirementProofs.delete(candidate.root);
8189
+ }
8190
+ }
8191
+ }
8192
+ scheduleRequestContextDrain() {
8193
+ if (this.requestContextDrainTimer || this.shuttingDown)
8194
+ return;
8195
+ this.requestContextDrainTimer = setTimeout(() => {
8196
+ this.requestContextDrainTimer = undefined;
8197
+ const modes = this.requestContextModes, state = this.deliveryOutbox?.requestContextInstallation().read();
8198
+ if (!modes?.current() || !state || state.mode !== "draining")
8199
+ return;
8200
+ try {
8201
+ modes.off.advance(state.revision);
8202
+ }
8203
+ catch (error) {
8204
+ this.logger.warn({ err: error.message }, "Request-context drain remains held");
8205
+ }
8206
+ this.requestContextControl?.changed();
8207
+ if (this.deliveryOutbox?.requestContextInstallation().read()?.mode === "draining")
8208
+ this.scheduleRequestContextDrain();
8209
+ }, 500);
8210
+ this.requestContextDrainTimer.unref?.();
8211
+ }
8212
+ /**
8213
+ * M-3897 (Sentinel's settlement split): before the first On, an owner settles an earlier ticket or delivery nothing else
8214
+ * can. Retire: a ticket the shadow names retirable (no readable delivery record), bound to the exact image it shows;
8215
+ * the retirement is appended and nothing is relabelled. Withdraw: an earlier delivery still queued or waiting to retry,
8216
+ * by its exact image (withdrawRequestContextDelivery's own CAS). Never after activation: those blockers are the drain's.
8217
+ */
8218
+ resolveLegacyBlocker(blocker, actor, current) {
8219
+ const box = this.deliveryOutbox;
8220
+ if (!box || box.requestContextInstallation().read() !== null || !current())
8221
+ throw Error("stale");
8222
+ // Sentinel's Go back contract: the same home-update exclusion the first On and Stop hold, so a retirement or a
8223
+ // withdrawal can never land between Go back's check and its restore.
8224
+ const update = this.requestContextActivationLease();
8225
+ if (!update)
8226
+ throw Error("update-lock");
8227
+ try {
8228
+ this.resolveLegacyBlockerHeld(blocker, actor, () => current() && update.current());
8229
+ }
8230
+ finally {
8231
+ update.release();
8232
+ }
8233
+ }
8234
+ resolveLegacyBlockerHeld(blocker, actor, current) {
8235
+ const box = this.deliveryOutbox;
8236
+ if (blocker.id.startsWith("legacy-retire:")) {
8237
+ if (!actor.person)
8238
+ throw Error("owner-required");
8239
+ const id = blocker.id.slice("legacy-retire:".length), entry = this.requestContextShadow().tickets.find(row => row.id === id);
8240
+ if (!entry?.sha256 || !RETIRABLE_LEGACY_DISPOSITIONS.includes(entry.disposition))
8241
+ throw Error("stale");
8242
+ const person = actor.person, image = entry.sha256, disposition = entry.disposition;
8243
+ actor.execution.mutate(() => box.contactAuthorizations.retireLegacy(id, image, disposition, person, current, (deliveryId, by) => box.acknowledge(deliveryId, by)));
8244
+ return;
8245
+ }
8246
+ const id = blocker.id.slice("legacy-withdraw:".length), row = box.get(id);
8247
+ if (!row || !box.requestContextControlInventory().deliveries.some(value => value.id === id && !value.root && ["queued", "retry_wait"].includes(value.state)))
8248
+ throw Error("stale");
8249
+ actor.execution.mutate(() => box.withdrawRequestContextDelivery(id, requestContextDigest(row), current));
8250
+ }
8251
+ async resolveRequestContextBlocker(blocker, actor, current) {
8252
+ if (blocker.id.startsWith("legacy-retire:") || blocker.id.startsWith("legacy-withdraw:")) {
8253
+ this.resolveLegacyBlocker(blocker, actor, current);
8254
+ return;
8255
+ }
8256
+ const box = this.deliveryOutbox, modes = this.requestContextModes, state = box?.requestContextInstallation().read();
8257
+ if (box && !state && blocker.id.startsWith("legacy-uncertain:") && blocker.action === "acknowledge") {
8258
+ const match = /^legacy-uncertain:([A-Za-z0-9._:-]{1,128}):([a-f0-9]{64})$/.exec(blocker.id);
8259
+ if (!match || !actor.verified || !actor.execution || !current())
8260
+ throw Error("stale");
8261
+ actor.execution.mutate(() => box.acknowledgeRequestContextLegacyDelivery(match[1], match[2], actor.binding, current));
8262
+ return;
8263
+ }
8264
+ if (!box || !modes?.current() || state?.mode !== "draining" || !current())
8265
+ throw Error("stale");
8266
+ const inventory = box.requestContextControlInventory(box.requestContextInstallation().drainRoots());
8267
+ if (blocker.id.startsWith("ticket:")) {
8268
+ if (!actor.person || !this.requestContactCardsPort)
8269
+ throw Error("owner-required");
8270
+ const id = blocker.id.slice(7), principal = { person: actor.person, binding: actor.binding, verified: true, current };
8271
+ const card = this.requestContactCardsPort.read(id, principal);
8272
+ actor.execution.mutate(() => this.requestContactCardsPort.decide(id, { snapshot: card.snapshot, decision: "decline" }, principal));
8273
+ }
8274
+ else if (blocker.id.startsWith("delivery:")) {
8275
+ const id = blocker.id.slice(9), row = box.get(id);
8276
+ if (!inventory.deliveries.some(value => value.id === id) || !row)
8277
+ throw Error("stale");
8278
+ actor.execution.mutate(() => box.withdrawRequestContextDelivery(id, requestContextDigest(row), current));
8279
+ }
8280
+ else if (blocker.id.startsWith("return:")) {
8281
+ const id = blocker.id.slice(7), row = inventory.returns.find(value => value.requestDeliveryId === id);
8282
+ if (!row)
8283
+ throw Error("stale");
8284
+ 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));
8285
+ this.scheduleDeliveryOutboxPump();
8286
+ }
8287
+ else if (blocker.id.startsWith("work:")) {
8288
+ const match = /^work:([a-f0-9-]{36}):([a-f0-9]{64})$/.exec(blocker.id);
8289
+ if (!match || blocker.action !== "stop-work")
8290
+ throw Error("stale");
8291
+ const update = this.requestContextActivationLease();
8292
+ if (!update)
8293
+ throw Error("unavailable");
8294
+ try {
8295
+ const decisionCurrent = () => current() && update.current();
8296
+ if (!decisionCurrent())
8297
+ throw Error("stale");
8298
+ const stopOffer = captureRequestContextEnableOffer(this.dataDir);
8299
+ const root = match[1], view = modes.drain.inspectWork(root), receipts = box.requestContextUncertainHumanImages(root), pointers = inventory.recoveries.filter(row => row.root === root).map(row => row.pointer);
8300
+ if (!projectRequestContextWork(view.blockers).stoppable || requestContextDigest({ root, blockers: view.blockers, revisions: [...view.revisions], receipts, pointers }) !== match[2])
8301
+ throw Error("stale");
8302
+ const saved = modes.drain.retainedEpoch(root);
8303
+ // A prior crash can leave the root fence durable. Rotate its epoch under
8304
+ // this owned coordinator before re-running the positive stop proof.
8305
+ let epoch;
8306
+ actor.execution.mutate(() => { epoch = saved ? modes.drain.resume(root, saved) : modes.drain.fence(root); });
8307
+ const retired = await this.stopRequestContextWork(root, actor, decisionCurrent);
8308
+ actor.execution.mutate(() => box.resolveRequestContextStoppedWork(root, epoch, { ownerBinding: actor.binding, blockerSha256: match[2], receipts, pointers }, modes.drain, retired, decisionCurrent));
8309
+ this.cacheStoppedWorkGoBack(stopOffer.invalidates);
8310
+ }
8311
+ finally {
8312
+ update.release();
8313
+ }
8314
+ }
8315
+ else if (blocker.id.startsWith("recovery:")) {
8316
+ const row = inventory.recoveries.find(value => `recovery:${requestContextDigest(value.pointer)}` === blocker.id);
8317
+ if (!row)
8318
+ throw Error("stale");
8319
+ const update = this.requestContextActivationLease();
8320
+ if (!update)
8321
+ throw Error("unavailable");
8322
+ try {
8323
+ const decisionCurrent = () => current() && update.current();
8324
+ if (!decisionCurrent())
8325
+ throw Error("stale");
8326
+ const stopOffer = captureRequestContextEnableOffer(this.dataDir);
8327
+ const saved = modes.drain.retainedEpoch(row.root);
8328
+ let epoch;
8329
+ actor.execution.mutate(() => { epoch = saved ? modes.drain.resume(row.root, saved) : modes.drain.fence(row.root); });
8330
+ const retired = await this.stopRequestContextWork(row.root, actor, decisionCurrent);
8331
+ actor.execution.mutate(() => box.resolveRequestContextStoppedWork(row.root, epoch, { ownerBinding: actor.binding, blockerSha256: requestContextDigest(blocker), receipts: [], pointers: [row.pointer] }, modes.drain, retired, decisionCurrent));
8332
+ this.cacheStoppedWorkGoBack(stopOffer.invalidates);
8333
+ }
8334
+ finally {
8335
+ update.release();
8336
+ }
8337
+ }
8338
+ else
8339
+ throw Error("invalid-request");
8340
+ this.scheduleRequestContextDrain();
8341
+ }
8342
+ /** Projection only, after the authoritative root COMMIT. A crash here cannot permit a restore. */
8343
+ cacheStoppedWorkGoBack(attempts) {
8344
+ for (const id of attempts)
8345
+ try {
8346
+ const cached = cacheRetainedUnavailable(this.dataDir, id, t("request_context_control.goBackStopped"));
8347
+ if (!cached.ok)
8348
+ this.logger.warn({ reason: cached.reason }, "Could not refresh stopped-work Go back availability");
8349
+ }
8350
+ catch (err) {
8351
+ this.logger.warn({ err }, "Could not refresh stopped-work Go back availability");
8352
+ }
8353
+ }
8354
+ async stopRequestContextWork(root, actor, current) {
8355
+ const modes = this.requestContextModes;
8356
+ if (!modes?.current() || !current())
8357
+ throw Error("stale");
8358
+ const nativeStops = this.fleetWindowsRuntime?.requestContextStops(root) ?? [], owners = [];
8359
+ for (const stop of nativeStops) {
8360
+ if (!current())
8361
+ throw Error("stale");
8362
+ actor.execution.mutate(() => stop.stop(current));
8363
+ }
8364
+ for (const [name, daemon] of [...this.daemons]) {
8365
+ const snapshot = daemon.requestContextTurnSnapshot();
8366
+ if (snapshot?.context.ref.rootContextId !== root)
8367
+ continue;
8368
+ const owner = daemon.captureRequestContextOwner();
8369
+ if (!owner || requestContextDigest(owner) !== requestContextDigest(snapshot.owner))
8370
+ throw Error("Request root owner changed");
8371
+ const retirement = await daemon.captureRequestContextRetirement();
8372
+ if (!current() || this.daemons.get(name) !== daemon)
8373
+ throw Error("stale");
8374
+ if (retirement.daemonBootId !== owner.daemonBootId || retirement.spawnGeneration !== owner.spawnGeneration || retirement.launchFenceEpoch !== owner.launchFenceEpoch)
8375
+ throw Error("Request launch owner changed");
8376
+ const sameTurn = () => daemon.requestContextTurnSnapshot()?.token === snapshot.token;
8377
+ if (!sameTurn())
8378
+ throw Error("Request root turn changed");
8379
+ await actor.execution.stopTarget(name, advance => this.lifecycle.stopIfCurrent(name, daemon, (before, after) => {
8380
+ advance?.(before, after);
8381
+ if (!current() || !sameTurn())
8382
+ throw Error("Request root turn changed");
8383
+ }));
8384
+ if (!current() || !await retirement.retired())
8385
+ throw Error("unavailable");
8386
+ // The future-start factory keeps the stored work/context; it removes only this positively retired live owner.
8387
+ if (!this.requestContextRetireOwner)
8388
+ throw Error("unavailable");
8389
+ await this.requestContextRetireOwner(name, daemon, retirement.retired);
8390
+ // C's identity has been disposed. Only the pre-stop physical receipt can
8391
+ // keep its own positive retirement current; a replacement is never adopted.
8392
+ owners.push(() => !this.daemons.has(name) && retirement.retiredCurrent());
8393
+ }
8394
+ // The wait bounds the HTTP action; only the owned run's positive completion can clear its pointer.
8395
+ const until = performance.now() + 30_000;
8396
+ while (nativeStops.some(stop => !stop.retired())) {
8397
+ if (!current())
8398
+ throw Error("stale");
8399
+ if (performance.now() >= until)
8400
+ throw Error("unavailable");
8401
+ await new Promise(resolve => setTimeout(resolve, 25));
8402
+ }
8403
+ return () => { try {
8404
+ return current() && nativeStops.every(stop => stop.retired()) && owners.every(check => check());
8405
+ }
8406
+ catch {
8407
+ return false;
8408
+ } };
8409
+ }
8410
+ async requestContextOwnerStopped(name, daemon, retired) {
8411
+ if (!this.requestContextRetireOwner)
8412
+ return;
8413
+ if (await retired())
8414
+ await this.requestContextRetireOwner(name, daemon, retired);
8415
+ else
8416
+ this.logger.warn({ name }, "Stopped request owner remains held until launch and IPC retirement are proven");
8417
+ }
8418
+ requestContextRetireOwner;
8419
+ requestContextControlPrincipal(req, url) {
8420
+ const resolve = () => {
8421
+ const verdict = evaluateWebRequest(req, url, this.webToken, this.webSessions, { touch: false });
8422
+ if (verdict.kind === "reject" && (verdict.reason === "csrf" || verdict.reason === "cross-site"))
8423
+ throw Error(verdict.reason);
8424
+ if (verdict.kind !== "allow" || verdict.via !== "session" || verdict.session.tier !== "admin")
8425
+ return null;
8426
+ if (hostSessionHere(verdict.session, req))
8427
+ return { binding: requestContextDigest(["host-here", verdict.session.handle, verdict.session.tokenEpoch]), verified: true, person: { platform: "host", adapterId: "host", userId: "operator", label: "Operator" } };
8428
+ const contact = this.requestContactPrincipal(req, url);
8429
+ if (!contact || !contact.current() || (contact.person.platform === "host" ? !this.isWebOnlyFleet() : this.adminGate(contact.person.userId, contact.person.adapterId) !== "ok"))
8430
+ return null;
8431
+ return { binding: requestContextDigest([contact.binding, contact.person.platform, contact.person.userId]), verified: contact.verified, person: contact.person };
8432
+ };
8433
+ const first = resolve();
8434
+ if (!first)
8435
+ return null;
8436
+ return Object.freeze({ ...first, current: () => { try {
8437
+ const now = resolve();
8438
+ return !!now && now.binding === first.binding && now.verified === first.verified;
8439
+ }
8440
+ catch {
8441
+ return false;
8442
+ } } });
8443
+ }
6916
8444
  requestContactPrincipal(req, url) {
6917
8445
  const resolve = () => {
6918
8446
  const verdict = evaluateWebRequest(req, url, this.webToken, this.webSessions, { touch: false });
@@ -6924,7 +8452,7 @@ export class FleetManager {
6924
8452
  if (!identity)
6925
8453
  return null;
6926
8454
  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 };
8455
+ 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
8456
  const verified = !!action && sameContactPerson(action, person);
6929
8457
  const binding = JSON.stringify([identity.session_handle, authority.authority_epoch, authority.kind === "web-verified" ? authority.session?.authorized_at : null]);
6930
8458
  return { person, binding, verified };
@@ -6947,14 +8475,236 @@ export class FleetManager {
6947
8475
  */
6948
8476
  requestContactCardsPort = null;
6949
8477
  installRequestContactCards(cards) { this.requestContactCardsPort = cards; }
8478
+ /** Only a validated accepted room can supply a current room-policy override. Unknown recovery is not a Free-room proof. */
8479
+ requestContextSourceRoomRestricted(root) {
8480
+ try {
8481
+ if (!["free-room", "restricted-room"].includes(root.ingress))
8482
+ return undefined;
8483
+ const id = /^human:hmsg-([a-f0-9-]{36})$/.exec(root.rootEvidenceRef)?.[1];
8484
+ if (!id)
8485
+ return undefined;
8486
+ const captured = this.deliveryOutbox?.requestContextHumans.read(id);
8487
+ if (!captured || requestContextDigest(captured.context) !== requestContextDigest(root))
8488
+ return undefined;
8489
+ const basis = this.deliveryOutbox.requestContextHumans.classicBasis(id);
8490
+ if (!basis && (captured.route.kind !== "web" || root.initiatingActor.kind === "unknown"))
8491
+ return undefined;
8492
+ const room = this.contactRoom(root.source.instance);
8493
+ return room ? room.restrictedMode === true : undefined;
8494
+ }
8495
+ catch {
8496
+ return undefined;
8497
+ }
8498
+ }
8499
+ /** Re-run the original synchronous admission basis. It supplies no role or go-ahead authority. */
8500
+ requestContextNativeAdmissionCurrent(context) {
8501
+ try {
8502
+ const root = this.deliveryOutbox?.requestContext(context.ref.rootContextId);
8503
+ if (!root)
8504
+ return false;
8505
+ const source = root.source.instance, room = this.contactRoom(source);
8506
+ if (!Object.hasOwn(this.fleetConfig?.instances ?? {}, source) && !room && !this.daemons?.has(source))
8507
+ return false;
8508
+ if (this.contactGeneration(source) !== root.source.incarnation)
8509
+ return false;
8510
+ if ("platform" in root.initiatingActor && root.initiatingActor.platform === "hub")
8511
+ return true; // Hub's owning current-share/resource check is separate.
8512
+ const match = /^human:hmsg-([a-f0-9-]{36})$/.exec(root.rootEvidenceRef);
8513
+ // Unproved recovery has no human route to borrow. An actual unknown web input must still
8514
+ // recheck its own session below; being unidentified is never a session-revocation bypass.
8515
+ if (!match)
8516
+ return root.initiatingActor.kind === "unknown" && root.ingress !== "owner";
8517
+ if (root.initiatingActor.kind !== "person" && root.initiatingActor.kind !== "unknown")
8518
+ return false;
8519
+ const captured = this.deliveryOutbox.requestContextHumans.read(match[1]);
8520
+ if (!captured || requestContextDigest(captured.context) !== requestContextDigest(root))
8521
+ return false;
8522
+ const actor = root.initiatingActor;
8523
+ if (captured.route.kind === "web") {
8524
+ const session = captured.route.sessionHandle ? this.webSessions?.findByHandle(captured.route.sessionHandle) : null;
8525
+ if (!session || !this.webToken || !this.webSessions?.isCurrent(session, tokenEpoch(this.webToken)))
8526
+ return false;
8527
+ if (actor.kind === "person") {
8528
+ const identity = this.webSessionIdentity(session);
8529
+ if (!identity || identity.platform !== actor.platform || identity.user_id !== actor.userId)
8530
+ return false;
8531
+ }
8532
+ return root.ingress === "guest" ? session.tier === "guest" && !!session.owner && this.fleetConfig?.web?.guests?.enabled === true && this.guestScope(session.owner).has(source) : session.tier === "admin";
8533
+ }
8534
+ if (actor.kind !== "person")
8535
+ return false;
8536
+ const basis = this.deliveryOutbox.requestContextHumans.classicBasis(match[1]);
8537
+ if (basis) {
8538
+ if (!room || room.channelId !== basis.roomId || (room.adapterId ?? this.contactAdapter(source)?.id) !== basis.adapterId || !this.classicChannels?.isClassicChannel(basis.roomId, basis.adapterId))
8539
+ return false;
8540
+ // These are messages inside a registered room. Guild/group/user allowlists gate creation,
8541
+ // and Classic admins may bypass them; applying those lists here would tighten Free rooms.
8542
+ return this.classicChannels.getInstanceByChannel(basis.roomId, basis.adapterId) === source;
8543
+ }
8544
+ if (room)
8545
+ return false; // No historical guild/group/user basis means no guessed Classic admission.
8546
+ if (actor.platform === "host")
8547
+ return false; // Host identity is admitted only through its bound web session.
8548
+ const adapter = this.contactAdapter(source);
8549
+ if (!adapter || adapter.type !== actor.platform)
8550
+ return false;
8551
+ const person = { platform: actor.platform, adapterId: adapter.id, userId: actor.userId, label: actor.userId };
8552
+ if (this.contactAdminOf(source, person))
8553
+ return true;
8554
+ const access = this.worlds.get(adapter.id)?.accessManager ?? (adapter.id === this.getPrimaryAdapterId() ? this.accessManager : null);
8555
+ return access?.isAllowed(actor.userId) === true;
8556
+ }
8557
+ catch {
8558
+ return false;
8559
+ }
8560
+ }
8561
+ /** Off preserves the owner's current Hub contact setting. Elapsed contact-window time grants nothing. */
8562
+ requestContextHubOwnerAllowsContact(context) {
8563
+ try {
8564
+ const root = this.deliveryOutbox?.requestContext(context.ref.rootContextId), actor = root?.initiatingActor;
8565
+ if (!root || root.ingress !== "hub" || !actor || !("platform" in actor) || actor.platform !== "hub" || this.contactGeneration(root.source.instance) !== root.source.incarnation
8566
+ || this.hubMemberPairingApi?.boundHub()?.hubId !== actor.hubId)
8567
+ return false;
8568
+ const view = this.hubMemberExposureApi?.list().find(row => row.agent === root.source.instance);
8569
+ return view?.state === "published" && view.enforceable && !view.reason && view.contactLimit === false;
8570
+ }
8571
+ catch {
8572
+ return false;
8573
+ }
8574
+ }
8575
+ /** Only the receipt's original registered C parent may cross the Draining gate. */
8576
+ requestContextHumanContinuation(instance, receiptId) {
8577
+ const boot = this.requestContextBoot, box = this.deliveryOutbox, daemon = this.daemons.get(instance);
8578
+ if (!boot || !box || !daemon)
8579
+ return;
8580
+ const accepted = box.requestContextHumans.read(receiptId), mapped = accepted?.steer, owner = daemon.captureRequestContextOwner();
8581
+ if (!accepted || !mapped || !owner || owner.workGeneration !== mapped.workGeneration)
8582
+ return;
8583
+ const actor = mapped.actor;
8584
+ if (actor.kind !== "person" || actor.platform === "hub")
8585
+ throw Error("Steer continuation actor unavailable");
8586
+ const valid = () => {
8587
+ try {
8588
+ const live = box.getHumanReceipt(receiptId), actual = daemon.captureRequestContextOwner(), parent = box.requestContext(mapped.parentContextId);
8589
+ const adapter = actor.platform === "host" ? "host" : this.contactAdapter(instance)?.id;
8590
+ return this.requestContextBoot === boot && this.deliveryOutbox === box && this.daemons.get(instance) === daemon && !this.shuttingDown
8591
+ && requestContextDigest(actual) === requestContextDigest(owner) && !!parent && requestContextDigest(parent) === mapped.parentSha256
8592
+ && !!live && live.state === "queued" && live.target_instance === instance && live.manager_boot_id === this.managerBootId
8593
+ && (live.owner_key === null || live.owner_key === this.humanReceiptOwner(instance, daemon))
8594
+ && !!adapter && this.contactAdminOf(instance, { platform: actor.platform, adapterId: adapter, userId: actor.userId, label: actor.userId })
8595
+ && this.requestContextNativeAdmissionCurrent(accepted.context);
8596
+ }
8597
+ catch {
8598
+ return false;
8599
+ }
8600
+ };
8601
+ if (!valid())
8602
+ throw Error("Steer continuation owner changed");
8603
+ return boot.publication.continuation(mapped.rootContextId, valid);
8604
+ }
8605
+ /** One installed gate host for direct sends and same-card decisions. No lifetime origin or return-release lookup.
8606
+ * Currentness belongs to the installation/process, not a browser, transport-readiness poll or old Hub timer.
8607
+ */
8608
+ makeRequestContextContactHost(current, rootRetired, mode) {
8609
+ const incarnation = (name) => { try {
8610
+ return current() ? this.contactGeneration(name) : null;
8611
+ }
8612
+ catch {
8613
+ return null;
8614
+ } };
8615
+ const person = (actor) => {
8616
+ if (actor.kind !== "person" || actor.platform === "hub")
8617
+ return null;
8618
+ if (actor.platform === "host")
8619
+ return actor.userId === "operator" ? { platform: "host", adapterId: "host", userId: "operator", label: "Operator" } : null;
8620
+ const adapter = [...this.adapters.values(), ...[...this.worlds.values()].map(world => world.adapter)].find(row => row.type === actor.platform);
8621
+ const configured = (this.fleetConfig?.channels ?? (this.fleetConfig?.channel ? [this.fleetConfig.channel] : [])).find(row => row.type === actor.platform);
8622
+ const adapterId = adapter?.id ?? configured?.id ?? configured?.type;
8623
+ return adapterId ? { platform: actor.platform, adapterId, userId: actor.userId, label: actor.displayName ?? actor.userId } : null;
8624
+ };
8625
+ const manage = (name, actor) => current() && incarnation(name) !== null && this.contactAdminOf(name, actor);
8626
+ return {
8627
+ incarnation, person, adminOf: manage, canManage: manage,
8628
+ canDecide: (name, actor) => {
8629
+ if (!manage(name, actor))
8630
+ return false;
8631
+ const policy = this.deliveryOutbox.contactAuthorizations.policySnapshot(name, incarnation(name));
8632
+ return actor.platform === "host" && actor.userId === "operator" || (policy.approvers ?? this.contactDefaultApprovers(name)).some(value => sameContactPerson(value, actor));
8633
+ },
8634
+ current: (context, binding) => current() && incarnation(binding.source.instance) === binding.source.incarnation
8635
+ && incarnation(binding.target.instance) === binding.target.incarnation && this.requestContextNativeAdmissionCurrent(context),
8636
+ sourceRestricted: root => this.requestContextSourceRoomRestricted(root),
8637
+ rootRetired: root => current() && rootRetired(root),
8638
+ hubRelayAllowed: (context, binding, delivery) => {
8639
+ if (!current() || !assertRequestHubContactImage(context, binding, delivery))
8640
+ return false;
8641
+ const installed = mode();
8642
+ return installed === "active" || installed === "draining" || installed === "off" && this.requestContextHubOwnerAllowsContact(context);
8643
+ },
8644
+ accepted: () => { this.scheduleDeliveryOutboxPump(); this.needsYou?.poke(); },
8645
+ };
8646
+ }
8647
+ /** One publication owns every live ingress. These forwarding ports never cache a mode, owner or current turn. */
8648
+ requestContactApi;
8649
+ bindRequestContextServingPublication(boot) {
8650
+ if (this.requestContextBoot !== boot || this.requestContextAdmission !== boot.publication.admission)
8651
+ throw Error("Request serving publication owner differs");
8652
+ const serving = (execution = false) => {
8653
+ if (this.requestContextBoot !== boot || this.requestContextAdmission !== boot.publication.admission)
8654
+ throw Error("Request serving publication changed");
8655
+ const publication = execution ? boot.publication.captureExecution() : boot.publication.capture();
8656
+ const ports = publication?.ports.serving;
8657
+ if (!ports || !ports.current())
8658
+ throw Error("Request serving publication unavailable");
8659
+ return ports;
8660
+ };
8661
+ this.requestContextPolicy = boot.policy;
8662
+ this.requestContextRelay = { admit: (input, operation, current) => serving(operation.admission?.coverage === "covered").relay.admit(input, operation, current) };
8663
+ // Record-only identity admission is not a pane write. New input still waits at the shared gate.
8664
+ this.requestContextHumanAdmission = (...args) => boot.publication.heldUnpublished() && this.requestContextModes?.current() ? this.requestContextModes.recordHuman(...args) : serving(true).human(...args);
8665
+ this.requestContextHubAdmission = input => serving().hub(input);
8666
+ this.requestContactApi = {
8667
+ principal: (req, url) => this.requestContactPrincipal(req, url), permitContinuation: (req, res) => permitWebContinuation(req, res, { webToken: this.webToken, webSessions: this.webSessions }),
8668
+ needs: actor => serving(true).api.needs?.(actor) ?? [], canRead: (card, actor) => serving(true).api.canRead(card, actor),
8669
+ 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),
8670
+ };
8671
+ this.requestContactCardsPort = {
8672
+ canRead: (card, actor) => serving(true).cards.canRead(card, actor), read: (id, actor) => serving(true).cards.read(id, actor),
8673
+ needs: actor => serving(true).cards.needs(actor), list: (filter, actor) => serving(true).cards.list(filter, actor),
8674
+ decide: (id, input, actor) => serving(true).cards.decide(id, input, actor), prepareForNativePost: (id, current) => serving(true).cards.prepareForNativePost(id, current),
8675
+ };
8676
+ }
8677
+ /** Construct only inside the capable activation initializer or capable boot. Nothing is published here. */
8678
+ prepareRequestContextServingOwners(current, rootRetired, resolveHub, mode) {
8679
+ const box = this.deliveryOutbox;
8680
+ if (!box || !current())
8681
+ throw Error("Request-context serving owner unavailable");
8682
+ const host = this.makeRequestContextContactHost(current, rootRetired, mode), gate = box.requestHubContactGate(host);
8683
+ const relay = makeRequestContextRelay(box, host, gate), cards = this.makeRequestContactCards(host, gate), api = this.makeRequestContactApi(cards);
8684
+ const human = this.makeRequestContextHumanAdmission(), hub = this.makeRequestContextHubAdmission(resolveHub), policy = this.makeRequestContextPolicy();
8685
+ const admitted = { admit: (...args) => {
8686
+ if (!current())
8687
+ throw new RequestContextPolicyError("stale");
8688
+ try {
8689
+ return relay.admit(...args);
8690
+ }
8691
+ catch (error) {
8692
+ if (error instanceof ContactHeldError)
8693
+ this.contactService().host.changed?.(args[0].targetInstance, error.result.authorization_id);
8694
+ throw error;
8695
+ }
8696
+ } };
8697
+ return Object.freeze({ policy, relay: admitted, cards, api, human, hub, gate, current });
8698
+ }
6950
8699
  /** Dormant assembly for L and synthetic rigs; merely defining this method installs no service or route authority. */
6951
- makeRequestContactCards() {
8700
+ makeRequestContactCards(gateHost, gate) {
6952
8701
  this.ensureDeliveryOutbox();
6953
8702
  const outbox = this.deliveryOutbox, legacy = this.contactService();
6954
8703
  const names = () => [...new Set([...Object.keys(this.fleetConfig?.instances ?? {}), ...(this.classicChannels?.getAll() ?? []).map(room => room.instanceName)])].sort();
6955
8704
  const manage = (name, person) => this.contactAdminOf(name, person);
6956
8705
  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),
8706
+ current: (context, binding) => this.contactGeneration(binding.source.instance) === binding.source.incarnation && this.contactGeneration(binding.target.instance) === binding.target.incarnation
8707
+ && (!requestContextPolicyInstalled(this.requestContextPolicy) || this.requestContextNativeAdmissionCurrent(context)) && !this.hubContactRestricted(binding.source.instance),
6958
8708
  generation: name => { try {
6959
8709
  return this.contactGeneration(name);
6960
8710
  }
@@ -6964,6 +8714,7 @@ export class FleetManager {
6964
8714
  canManage: manage, canDecide: (name, person) => { if (!manage(name, person))
6965
8715
  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
8716
  adminOf: (name, person) => this.contactAdminOf(name, person),
8717
+ sourceRestricted: root => this.requestContextSourceRoomRestricted(root),
6967
8718
  person: actor => {
6968
8719
  if (actor.kind !== "person" || actor.platform === "hub")
6969
8720
  return null;
@@ -6993,11 +8744,12 @@ export class FleetManager {
6993
8744
  }
6994
8745
  this.needsYou?.poke();
6995
8746
  },
6996
- });
8747
+ ...gateHost,
8748
+ }, gate);
6997
8749
  return cards;
6998
8750
  }
6999
- makeRequestContactApi() {
7000
- const cards = this.makeRequestContactCards();
8751
+ makeRequestContactApi(given) {
8752
+ const cards = given ?? this.makeRequestContactCards();
7001
8753
  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
8754
  }
7003
8755
  contactActor(req, url) {
@@ -7014,7 +8766,21 @@ export class FleetManager {
7014
8766
  const adapter = this.adapters.get(actor.adapter_id);
7015
8767
  if (!adapter || (adapter.type !== "discord" && adapter.type !== "telegram"))
7016
8768
  return null;
7017
- return { platform: adapter.type, adapterId: actor.adapter_id, userId: actor.user_id, label: actor.user_id };
8769
+ return { platform: adapter.type, adapterId: actor.adapter_id, userId: actor.user_id, label: this.contactPersonLabel(actor.adapter_id, actor.user_id) };
8770
+ }
8771
+ /**
8772
+ * M-3864 R7: what Permissions and the history call a web-verified admin. That is their name as the rest of the dashboard
8773
+ * says it (their own, else their chat account's), never the bare account id. Display only: a person is matched by
8774
+ * platform and id (sameContactPerson).
8775
+ */
8776
+ contactPersonLabel(adapterId, userId) {
8777
+ try {
8778
+ const name = this.webPerson({ adapterId, userId }).name;
8779
+ return name && name !== WEB_NAME_FALLBACK ? name : userId;
8780
+ }
8781
+ catch {
8782
+ return userId;
8783
+ }
7018
8784
  }
7019
8785
  writeContactPermissions(name, raw, actor) {
7020
8786
  const parsed = ContactPermissionsSchema.safeParse(raw);
@@ -7530,15 +9296,25 @@ export class FleetManager {
7530
9296
  return;
7531
9297
  try {
7532
9298
  outbox.contactAuthorizations.notifyOutcomes((ticket, outcome) => {
9299
+ const notify = (key, text) => {
9300
+ if (ticket.requestContext) {
9301
+ const context = outbox.requestContext(ticket.requestContext.contextId);
9302
+ if (!context || context.source.instance !== ticket.source)
9303
+ throw Error("Contact outcome context unavailable");
9304
+ outbox.admitRequestContextOutcome(context.ref.contextId, key, text, () => !this.shuttingDown && this.contactGeneration(ticket.source) === context.source.incarnation);
9305
+ }
9306
+ else
9307
+ outbox.admitSystemNotice(ticket.source, key, text);
9308
+ };
7533
9309
  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));
9310
+ notify(`contact-outcome:${ticket.id}`, t(outcome === "declined" ? "contact.noticeDeclined" : "contact.noticeExpired", ticket.id, ticket.target));
7535
9311
  return;
7536
9312
  }
7537
9313
  // M-3716 (the user, 11-25): the requester learns who approved it, when, and whether the target has it.
7538
9314
  const by = ticket.decidedBy, when = ticket.decidedAt ? `${ticket.decidedAt.slice(0, 16).replace("T", " ")} UTC` : "";
7539
9315
  const who = !by ? "?" : by.platform === "host" ? t("contactProposal.host")
7540
9316
  : `${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));
9317
+ notify(`contact-approval:${ticket.id}`, t(`contact.noticeApproved_${outcome}`, shortContactTicketId(ticket.id), ticket.target, who, when));
7542
9318
  }, ticket => ticket.deliveryId ? outbox.get(ticket.deliveryId)?.state : undefined);
7543
9319
  }
7544
9320
  catch (err) {
@@ -8036,12 +9812,51 @@ export class FleetManager {
8036
9812
  }, Math.max(0, delayMs));
8037
9813
  this.deliveryPumpTimer.unref?.();
8038
9814
  }
9815
+ /** Only B-validated deliveries can pass Draining; a legacy row or a body root id cannot. */
9816
+ requestContextDeliveryContinuation(row) {
9817
+ const boot = this.requestContextBoot, box = this.deliveryOutbox;
9818
+ if (!boot || !box)
9819
+ return null;
9820
+ const owned = () => !this.shuttingDown && this.deliveryOutbox === box && this.requestContextBoot === boot && this.contactDeliveryCurrent(row);
9821
+ const bound = requestDeliveryContinuation(box, boot.publication, row, owned);
9822
+ if (bound)
9823
+ return bound;
9824
+ // An untouched queued human control uses its receipt's registered parent, never a legacy operation's speaker.
9825
+ const meta = row.payload.meta, id = meta?.human_receipt_id;
9826
+ if (row.kind !== "human_control" || row.sourceInstance !== "agend-system" || typeof id !== "string" || row.sourceKey !== `human-control:${id}`
9827
+ || row.operationId !== row.sourceKey || meta?.verification_id !== `hmsg-${id}`)
9828
+ return null;
9829
+ const parent = this.requestContextHumanContinuation(row.targetInstance, id);
9830
+ if (!parent)
9831
+ return null;
9832
+ const image = requestContextDigest(row), current = () => {
9833
+ try {
9834
+ const actual = box.get(row.deliveryId);
9835
+ return owned() && parent.current() && !!actual
9836
+ && ["queued", "delivering"].includes(actual.state) && requestContextDigest(actual) === image;
9837
+ }
9838
+ catch {
9839
+ return false;
9840
+ }
9841
+ };
9842
+ if (!current())
9843
+ throw Error("Retained steer continuation changed");
9844
+ return boot.publication.continuation(parent.rootContextId, current);
9845
+ }
9846
+ requestContextDeliveryAdmissionAllowed(row) {
9847
+ try {
9848
+ return this.requestContextAdmission?.available(this.requestContextDeliveryContinuation(row) ?? undefined) !== false;
9849
+ }
9850
+ catch {
9851
+ return false;
9852
+ }
9853
+ }
8039
9854
  async runDeliveryOutboxPump() {
8040
9855
  const outbox = this.deliveryOutbox;
8041
9856
  // A closed database is never queried: this runs from timers, where a throw
8042
9857
  // is an unhandled rejection. Checking here covers the finally block too:
8043
9858
  // the body below never awaits, so the database cannot close in between.
8044
- if (!outbox || this.shuttingDown || this.deliveryPumpRunning || !outbox.isOpen)
9859
+ if (!outbox || this.shuttingDown || this.deliveryPumpRunning || !outbox.isOpen || (this.requestContextAdmission?.dispatchAvailable?.() ?? this.requestContextAdmission?.available()) === false)
8045
9860
  return;
8046
9861
  this.deliveryPumpRunning = true;
8047
9862
  this.deliveryPumpScheduled = false;
@@ -8067,7 +9882,7 @@ export class FleetManager {
8067
9882
  // Phase 2c: a lane a queue worker owns is never claimed here.
8068
9883
  target => this.queueWorkers.has(target) || this.isInstanceRestarting(target) || this.wakeCoordinator?.blocksClaim(target)
8069
9884
  ? null
8070
- : this.deliveryBootId(target), this.activeDurableTargets, row => this.recoveryDeliveryEligible(row));
9885
+ : this.deliveryBootId(target), this.activeDurableTargets, row => this.recoveryDeliveryEligible(row) && (this.requestContextAdmission?.available() !== false || this.requestContextDeliveryAdmissionAllowed(row)));
8071
9886
  if (!claimed)
8072
9887
  break;
8073
9888
  this.activeDurableTargets.add(claimed.targetInstance);
@@ -8126,10 +9941,10 @@ export class FleetManager {
8126
9941
  const worker = new TargetQueueWorker(target, {
8127
9942
  owns: () => this.queueWorkers.get(target) === worker,
8128
9943
  wanted: () => this.deliveryWorkerMode(target) === "on",
8129
- available: () => !this.shuttingDown && this.deliveryOutbox?.isOpen === true,
9944
+ available: () => !this.shuttingDown && this.deliveryOutbox?.isOpen === true && (this.requestContextAdmission?.dispatchAvailable?.() ?? this.requestContextAdmission?.available()) !== false,
8130
9945
  blocked: () => this.isInstanceRestarting(target) || this.wakeCoordinator?.blocksClaim(target) === true,
8131
9946
  daemonBootId: () => this.deliveryBootId(target),
8132
- claim: bootId => this.deliveryOutbox?.claimNext(this.managerBootId, candidate => candidate === target ? bootId : null, new Set(), row => this.recoveryDeliveryEligible(row)),
9947
+ 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
9948
  tryAcquireBudget: () => {
8134
9949
  if (this.activeDurableTargets.size >= 8)
8135
9950
  return false;
@@ -8163,6 +9978,7 @@ export class FleetManager {
8163
9978
  await this.dispatchNativeDurableDelivery(claimed);
8164
9979
  return;
8165
9980
  }
9981
+ const humanControl = claimed.kind === "human_control";
8166
9982
  const target = claimed.targetInstance;
8167
9983
  const attempt = claimed.attemptNo;
8168
9984
  const payload = { ...claimed.payload };
@@ -8173,6 +9989,8 @@ export class FleetManager {
8173
9989
  // Arm the visible liveness alert as soon as this generation owns the lane,
8174
9990
  // including time spent waiting for a handoff/idle gate to return.
8175
9991
  try {
9992
+ if (humanControl && (claimed.sourceInstance !== "agend-system" || claimed.sourceKey !== claimed.operationId || !claimed.sourceKey.startsWith("human-control:")))
9993
+ throw Error("Invalid retained human control");
8176
9994
  let sent;
8177
9995
  if (claimed.kind === WORKING_RECOVERY_KIND) {
8178
9996
  const daemon = this.daemons.get(target), key = claimed.sourceKey.replace(/^working-recovery:/, "");
@@ -8223,15 +10041,24 @@ export class FleetManager {
8223
10041
  ...rawMeta,
8224
10042
  delivery_id: claimed.deliveryId,
8225
10043
  delivery_attempt: String(claimed.attemptNo),
8226
- from_instance: typeof rawMeta.from_instance === "string" && rawMeta.from_instance
8227
- ? rawMeta.from_instance
8228
- : claimed.sourceInstance,
10044
+ ...(!humanControl ? { from_instance: typeof rawMeta.from_instance === "string" && rawMeta.from_instance
10045
+ ? rawMeta.from_instance : claimed.sourceInstance } : {}),
8229
10046
  correlation_id: claimed.correlationId ?? String(rawMeta.correlation_id ?? ""),
8230
10047
  };
10048
+ if (humanControl) {
10049
+ payload.delivery_id = claimed.deliveryId;
10050
+ payload.delivery_attempt = String(claimed.attemptNo);
10051
+ markRetainedHumanControl(payload, claimed);
10052
+ }
10053
+ if (this.requestContextBoot) {
10054
+ const proof = this.requestContextDeliveryContinuation(outbox.get(claimed.deliveryId));
10055
+ if (proof)
10056
+ requestPayloadContinuations.set(payload, proof);
10057
+ }
8231
10058
  sent = await this.deliverToInstance(target, payload, {
8232
- isCrossInstance: true,
10059
+ isCrossInstance: !humanControl,
8233
10060
  stillCurrent: () => this.contactDeliveryCurrent(claimed),
8234
- waitForIdle: claimed.kind !== "steer",
10061
+ waitForIdle: !humanControl && claimed.kind !== "steer",
8235
10062
  noInlineWake: this.deliveryWorkerMode(target) !== "off",
8236
10063
  });
8237
10064
  }
@@ -8276,12 +10103,21 @@ export class FleetManager {
8276
10103
  }
8277
10104
  const meta = claimed.payload.meta && typeof claimed.payload.meta === "object" ? claimed.payload.meta : {};
8278
10105
  const task = await this.nativeInstanceRuntime().execute(target, { ...claimed.payload, requestId: deliveryId, meta: { ...meta, from_instance: claimed.sourceInstance, correlation_id: claimed.correlationId } }, {
10106
+ ...(this.requestContextPolicy ? { requestContextInputId: `delivery:${deliveryId}:${attemptNo}` } : {}),
8279
10107
  stillCurrent: () => !this.shuttingDown && this.contactDeliveryCurrent(claimed),
8280
10108
  beforeStart: () => { if (!this.contactDeliveryCurrent(claimed) || outbox.begin(deliveryId, targetDaemonBootId, attemptNo) !== "begun")
8281
10109
  throw new Error("Windows delivery attempt is no longer current"); begun = true; },
8282
10110
  });
8283
10111
  const outcome = task.outcomeConfirmed === false ? "uncertain" : task.status === "completed" ? "delivered" : "failed";
8284
10112
  outbox.complete(deliveryId, targetDaemonBootId, attemptNo, outcome, task.error || task.status);
10113
+ if (this.requestContextPolicy) {
10114
+ if (!this.requestContextRelay)
10115
+ throw Error("Native scoped return admission is unavailable");
10116
+ const completion = this.nativeInstanceRuntime().requestContextCompletion(target, deliveryId, `delivery:${deliveryId}:${attemptNo}`);
10117
+ admitRequestContextNativeResult(outbox, this.requestContextRelay, { deliveryId, task, ...completion });
10118
+ this.scheduleDeliveryOutboxPump();
10119
+ return;
10120
+ }
8285
10121
  // Return a requested peer report when the provider did not explicitly report it through scoped MCP.
8286
10122
  if (meta.requires_reply === "true" && claimed.correlationId && !task.reportedCorrelationIds?.includes(claimed.correlationId) && this.fleetConfig?.instances[claimed.sourceInstance]) {
8287
10123
  const text = (task.status === "completed" ? task.output : `Windows task ${task.status}: ${task.error || task.output}`).slice(0, 8000);
@@ -8315,6 +10151,27 @@ export class FleetManager {
8315
10151
  if (!row || !isNativeExecInstance(this.fleetConfig?.instances[row.targetInstance]) || this.fleetConfig?.instances[row.targetInstance]?.machine_id !== machineId
8316
10152
  || !row.targetDaemonBootId || this.activeDurableTargets.has(row.targetInstance))
8317
10153
  return;
10154
+ if (this.requestContextPolicy) {
10155
+ if (!this.requestContextRelay)
10156
+ throw Error("Native scoped return admission is unavailable");
10157
+ const completion = this.nativeInstanceRuntime().requestContextCompletion(row.targetInstance, row.deliveryId, `delivery:${row.deliveryId}:${row.attemptNo}`);
10158
+ if (!task.execInputProof)
10159
+ throw Error("Native scoped completion has no input proof");
10160
+ // Never let terminal status replace the worker's actual input boundary on a scoped run.
10161
+ validateNativeExecInputProof(task.execInputProof, completion.claim);
10162
+ if (row.state === "submission_started" || row.state === "reconciliation_pending") {
10163
+ if (!outbox.complete(row.deliveryId, row.targetDaemonBootId, row.attemptNo, "delivered", "Owned native input proof recovered"))
10164
+ return;
10165
+ }
10166
+ else if (!["delivered", "uncertain"].includes(row.state))
10167
+ return;
10168
+ if (outbox.markConsumed(row.deliveryId, row.targetDaemonBootId, row.attemptNo, "turn", "Owned native input proof recovered") === "ignored")
10169
+ return;
10170
+ admitRequestContextNativeResult(outbox, this.requestContextRelay, { deliveryId: row.deliveryId, task, ...completion });
10171
+ this.reconciledRemoteResults.add(key);
10172
+ this.scheduleDeliveryOutboxPump();
10173
+ return;
10174
+ }
8318
10175
  if (row.state === "submission_started" || row.state === "reconciliation_pending") {
8319
10176
  if (!outbox.complete(row.deliveryId, row.targetDaemonBootId, row.attemptNo, task.status === "completed" ? "delivered" : "failed", task.error || "Runtime completion recovered after reconnect"))
8320
10177
  return;
@@ -10036,6 +11893,8 @@ export class FleetManager {
10036
11893
  * retry brings it up, however long the backoff, and fails only once the retries give up.
10037
11894
  */
10038
11895
  async sendWhenConnected(instanceName, payload, deliveryEpoch = this.getDeliveryEpoch(instanceName), stillCurrent, onStartRetryHold, beforeInput) {
11896
+ if (this.requestContextAdmission && !await this.requestContextAdmission.wait(() => this.deliveryCurrent(instanceName, deliveryEpoch, stillCurrent), requestPayloadContinuations.get(payload)))
11897
+ return false;
10039
11898
  if (!this.deliveryCurrent(instanceName, deliveryEpoch, stillCurrent))
10040
11899
  return false;
10041
11900
  const queued = this.ipcWaitTails.get(instanceName);
@@ -10044,6 +11903,8 @@ export class FleetManager {
10044
11903
  if (ipc?.connected) {
10045
11904
  if (beforeInput)
10046
11905
  return this.handOffAfterBeforeInput(instanceName, payload, deliveryEpoch, stillCurrent, beforeInput);
11906
+ if (this.requestContextAdmission?.available(requestPayloadContinuations.get(payload)) === false)
11907
+ return this.sendAfterIpcReturns(instanceName, payload, deliveryEpoch, stillCurrent, onStartRetryHold, beforeInput);
10047
11908
  const wire = this.bindHumanReceiptPayload(instanceName, payload);
10048
11909
  if (this.refuseHubPane(wire))
10049
11910
  return false;
@@ -10081,6 +11942,8 @@ export class FleetManager {
10081
11942
  * goes in one attempt. After the intent is spent nothing here retries: false is the caller's uncertain outcome.
10082
11943
  */
10083
11944
  async handOffAfterBeforeInput(instanceName, payload, deliveryEpoch, stillCurrent, beforeInput) {
11945
+ if (this.requestContextAdmission && !await this.requestContextAdmission.wait(() => this.deliveryCurrent(instanceName, deliveryEpoch, stillCurrent), requestPayloadContinuations.get(payload)))
11946
+ return false;
10084
11947
  // The flag is read before beforeInput and before prepareClassicForPerson. A Hub or room row stays
10085
11948
  // queued at its producer: no begin lease, no input intent, and no plaintext copy of the question.
10086
11949
  if (this.refuseHubPane(payload))
@@ -10090,35 +11953,45 @@ export class FleetManager {
10090
11953
  if (this.holdPaneSend(instanceName, early))
10091
11954
  return true;
10092
11955
  }
10093
- if (!(await beforeInput()))
11956
+ const begin = this.requestContextAdmission
11957
+ ? await runWithRequestContextAdmission(this.requestContextAdmission, () => this.deliveryCurrent(instanceName, deliveryEpoch, stillCurrent), beforeInput, requestPayloadContinuations.get(payload))
11958
+ : await beforeInput();
11959
+ if (!begin)
10094
11960
  return false;
10095
11961
  if (this.refuseHubPane(payload))
10096
11962
  return false;
10097
11963
  const privateToken = await this.prepareClassicForPerson(instanceName, payload, deliveryEpoch, stillCurrent);
10098
11964
  if (privateToken === false || this.shuttingDown || !this.deliveryCurrent(instanceName, deliveryEpoch, stillCurrent))
10099
11965
  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);
11966
+ const send = () => {
11967
+ if (this.shuttingDown || !this.deliveryCurrent(instanceName, deliveryEpoch, stillCurrent))
11968
+ return false;
11969
+ const ipc = this.instanceIpcClients.get(instanceName);
11970
+ if (!ipc?.connected || (privateToken && this.classicPrivacy().read(instanceName)?.token !== privateToken))
11971
+ return false;
11972
+ const wire = this.bindHumanReceiptPayload(instanceName, payload);
11973
+ if (this.refuseHubPane(wire))
11974
+ return false;
11975
+ if (this.holdPaneSend(instanceName, wire))
11976
+ return true;
11977
+ const sent = ipc.send(wire);
11978
+ if (sent && privateToken) {
11979
+ try {
11980
+ if (this.classicPrivacy().resume(instanceName, privateToken)) {
11981
+ this.instanceProgress.delete(instanceName);
11982
+ this.instanceActivity.delete(instanceName);
11983
+ }
11984
+ }
11985
+ catch (err) {
11986
+ // Input was accepted: never invite a duplicate. Keep output closed if its durable release fails.
11987
+ this.logger.warn({ err, instanceName }, "Classic room output remains private after the person input");
10114
11988
  }
10115
11989
  }
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;
11990
+ return sent;
11991
+ };
11992
+ return this.requestContextAdmission
11993
+ ? runWithRequestContextAdmission(this.requestContextAdmission, () => this.deliveryCurrent(instanceName, deliveryEpoch, stillCurrent), send, requestPayloadContinuations.get(payload))
11994
+ : send();
10122
11995
  }
10123
11996
  /** Poll for the instance's IPC to come back, then send. Throws if it does not. */
10124
11997
  async sendAfterIpcReturns(instanceName, payload, deliveryEpoch = this.getDeliveryEpoch(instanceName), stillCurrent, onStartRetryHold, beforeInput) {
@@ -10126,6 +11999,12 @@ export class FleetManager {
10126
11999
  let warned = false;
10127
12000
  let held = false;
10128
12001
  for (;;) {
12002
+ if (this.requestContextAdmission && !this.requestContextAdmission.available(requestPayloadContinuations.get(payload))) {
12003
+ if (!await this.requestContextAdmission.wait(() => this.deliveryCurrent(instanceName, deliveryEpoch, stillCurrent), requestPayloadContinuations.get(payload)))
12004
+ return false;
12005
+ deadline = Date.now() + IPC_RECONNECT_GRACE_MS; // Cutover waiting is not an IPC reconnect timeout.
12006
+ continue;
12007
+ }
10129
12008
  if (!this.deliveryCurrent(instanceName, deliveryEpoch, stillCurrent))
10130
12009
  return false;
10131
12010
  // Re-read every round: a reconnect replaces the IpcClient object entirely,
@@ -10227,7 +12106,19 @@ export class FleetManager {
10227
12106
  * The tool's errors: an emoji outside the web set or one of the instance's delivery marks (web-reactions.ts), or a
10228
12107
  * message the chat does not have. An emoji the message already has is a success that changes nothing.
10229
12108
  */
10230
- async reactToWebMessage(instance, messageId, raw) {
12109
+ async reactToWebMessage(instance, messageId, raw, replyRoute) {
12110
+ if (replyRoute) {
12111
+ if (!replyRoute.current())
12112
+ return { ok: false, error: "Originating request context is no longer current" };
12113
+ const handle = replyRoute.target.webRoute?.sessionHandle;
12114
+ if (handle) {
12115
+ const session = this.webSessions?.findByHandle(handle), row = this.webChatHistory.findByReplyId(instance, messageId);
12116
+ if (!session || !row)
12117
+ 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` };
12118
+ 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))))
12119
+ 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` };
12120
+ }
12121
+ }
10231
12122
  const problem = webReactionProblem(raw, this.statusEmojiAvoidList(instance));
10232
12123
  if (problem)
10233
12124
  return { ok: false, error: problem };
@@ -10238,13 +12129,20 @@ export class FleetManager {
10238
12129
  if (!r.added)
10239
12130
  return { ok: true, mirrored: Promise.resolve(0) };
10240
12131
  this.emitSseEvent("reactions", { instance, boot: r.message.boot, id: r.message.id, reactions: r.message.reactions ?? [] });
12132
+ const routeMatches = (copy) => !replyRoute || copy.chatId === replyRoute.target.chatId && (copy.threadId ?? "") === (replyRoute.target.threadId ?? "") && copy.adapterId === replyRoute.target.adapterId;
10241
12133
  const mirrorOne = (copy) => {
12134
+ if (!routeMatches(copy))
12135
+ return Promise.resolve(0);
10242
12136
  let timer;
10243
12137
  const timeout = new Promise((_, reject) => {
10244
12138
  timer = setTimeout(() => reject(new Error(`no answer in ${WEB_MIRROR_TIMEOUT_MS} ms`)), WEB_MIRROR_TIMEOUT_MS);
10245
12139
  timer.unref?.();
10246
12140
  });
10247
- return Promise.race([Promise.resolve().then(() => copy.adapter.react(copy.chatId, copy.messageId, reactionForm(copy.adapter.type, emoji), copy.threadId)), timeout])
12141
+ return Promise.race([Promise.resolve().then(() => {
12142
+ if (replyRoute && (!replyRoute.current() || !routeMatches(copy)))
12143
+ throw new RequestContextPolicyError("stale");
12144
+ return copy.adapter.react(copy.chatId, copy.messageId, reactionForm(copy.adapter.type, emoji), copy.threadId);
12145
+ }), timeout])
10248
12146
  .then(() => 1, (err) => {
10249
12147
  this.logger.warn({ err, instance, adapter: copy.adapter.type }, "Reaction on a web message's channel copy failed (shown on the web)");
10250
12148
  return 0;
@@ -10480,6 +12378,490 @@ export class FleetManager {
10480
12378
  }
10481
12379
  });
10482
12380
  }
12381
+ /** One controlled candidate, shared by instruction rendering and the lifecycle's actual pre-start hook. */
12382
+ prepareRequestContextDaemonOwner(instance, config, policy, registration, current) {
12383
+ const box = this.deliveryOutbox;
12384
+ if (!box)
12385
+ throw Error("Request input owner is unavailable");
12386
+ const firstActivation = box.requestContextInstallation().read() === null;
12387
+ const image = requestContextDigest(config), incarnation = this.contactGeneration(instance);
12388
+ let registered = false, daemon = null, binding = null;
12389
+ const ownerCurrent = () => {
12390
+ try {
12391
+ return current() && this.contactGeneration(instance) === incarnation
12392
+ && (!registered || !!daemon && this.daemons.get(instance) === daemon);
12393
+ }
12394
+ catch {
12395
+ return false;
12396
+ }
12397
+ };
12398
+ const work = new RequestContextPreparedWork(box.requestContextWork, instance, incarnation, ownerCurrent, firstActivation);
12399
+ const preparation = Object.freeze({ policy, current: () => work.current() && ownerCurrent() });
12400
+ return Object.freeze({ preparation, work,
12401
+ configure: (candidate, actual, offered) => {
12402
+ if (daemon || !preparation.current() || !offered?.current() || offered.policy !== policy
12403
+ || requestContextDigest(actual) !== image || requestContextDigest(candidate.getConfigSnapshot()) !== image)
12404
+ throw Error("Request owner preparation changed");
12405
+ daemon = candidate;
12406
+ try {
12407
+ binding = this.makeRequestContextDaemonBinding(instance, candidate, work, registration, ownerCurrent);
12408
+ if (candidate.captureRequestContextOwner()?.instance !== instance)
12409
+ throw Error("Request owner preparation changed");
12410
+ }
12411
+ catch (error) {
12412
+ work.dispose();
12413
+ throw error;
12414
+ }
12415
+ },
12416
+ /** Ownership only, not readiness: the installer must independently prove all real transport ports. */
12417
+ sealRegistered: () => {
12418
+ if (!daemon || this.daemons.get(instance) !== daemon || daemon.requestContextPolicy !== policy || !binding?.current() || !preparation.current())
12419
+ throw Error("Request owner is not bound");
12420
+ registered = true;
12421
+ },
12422
+ bound: () => registered && preparation.current() && binding?.current() === true,
12423
+ hub: () => registered && preparation.current() ? binding?.hub ?? null : null,
12424
+ dispose: () => work.dispose(), });
12425
+ }
12426
+ /** Installer-owned new-registration lane. Never called by a tool or inferred from an absent work row.
12427
+ * retirement is captured by the controlled relaunch before the old launch/IPC is stopped.
12428
+ */
12429
+ async registerRequestContextWork(instance, retirement) {
12430
+ const box = this.deliveryOutbox, admission = this.requestContextAdmission, lease = captureProcessFleetLease(this.dataDir);
12431
+ if (!box || !box.requestContextInstallation().read() || !admission || admission.available() || !lease?.current()
12432
+ || this.hubIncarnationsBroken || !retirement.current())
12433
+ throw Error("Request work registration unavailable");
12434
+ const incarnation = this.contactGeneration(instance), path = this.hubIncarnationsPath(), image = readFileSync(path, "utf8");
12435
+ const raw = JSON.parse(image), entry = Object.hasOwn(raw, instance) ? raw[instance] : undefined, previous = box.requestContextWork.read(instance);
12436
+ const mode = requestWorkRegistrationEvidence(instance, entry, incarnation, previous?.incarnation ?? null);
12437
+ const current = () => {
12438
+ try {
12439
+ return !this.shuttingDown && lease.current() && this.requestContextAdmission === admission && !admission.available()
12440
+ && !this.hubIncarnationsBroken && retirement.current() && this.contactGeneration(instance) === incarnation && readFileSync(path, "utf8") === image;
12441
+ }
12442
+ catch {
12443
+ return false;
12444
+ }
12445
+ };
12446
+ if (!current() || !await retirement.retired() || !current())
12447
+ throw Error("Request work predecessor is not retired");
12448
+ const value = mode === "resume" ? previous : box.requestContextWork.register({ instance, incarnation, generation: randomUUID() }, previous, current);
12449
+ if (!current())
12450
+ throw Error("Request work registration changed");
12451
+ // Commit precedes marker consumption. A crash in between resumes the exact row and finishes this write;
12452
+ // a consumed marker with a missing row can never recreate a birth.
12453
+ raw[instance] = { ...entry, requestWork: "registered" };
12454
+ if (this.writeHubIncarnations(raw) !== "written")
12455
+ throw Error("Request work registration evidence unavailable");
12456
+ if (!lease.current() || !retirement.current() || this.contactGeneration(instance) !== incarnation)
12457
+ throw Error("Request work registration changed");
12458
+ return value;
12459
+ }
12460
+ /** Finish a committed registration's marker, including crash recovery. This creates no work, context or permission. */
12461
+ sealRequestContextWorkRegistration(instance, current) {
12462
+ const box = this.deliveryOutbox, lease = captureProcessFleetLease(this.dataDir), incarnation = this.contactGeneration(instance), work = box?.requestContextWork.read(instance);
12463
+ if (!box || !work || work.incarnation !== incarnation || !lease?.current() || !current() || this.hubIncarnationsBroken)
12464
+ throw Error("Committed request registration unavailable");
12465
+ const path = this.hubIncarnationsPath(), image = readFileSync(path, "utf8"), raw = JSON.parse(image), entry = Object.hasOwn(raw, instance) ? raw[instance] : undefined;
12466
+ requestWorkRegistrationEvidence(instance, entry, incarnation, work.incarnation);
12467
+ const owned = () => lease.current() && current() && !this.hubIncarnationsBroken && this.contactGeneration(instance) === incarnation
12468
+ && requestContextDigest(box.requestContextWork.read(instance)) === requestContextDigest(work);
12469
+ if (!owned() || readFileSync(path, "utf8") !== image)
12470
+ throw Error("Committed request registration changed");
12471
+ if (entry.requestWork !== "registered") {
12472
+ raw[instance] = { ...entry, requestWork: "registered" };
12473
+ if (this.writeHubIncarnations(raw) !== "written")
12474
+ throw Error("Request registration marker unavailable");
12475
+ }
12476
+ if (!owned())
12477
+ throw Error("Committed request registration changed");
12478
+ }
12479
+ /** Capable boot/restart factory. A current retained work row is mandatory; a missing/new incarnation uses
12480
+ * only the explicit durable registration lane. No running daemon is hot-bound and no active turn is restored.
12481
+ */
12482
+ installRequestContextRetainedOwners(policy, registration, current, adopt = [], options = {}) {
12483
+ const box = this.deliveryOutbox, admission = this.requestContextAdmission, lease = captureProcessFleetLease(this.dataDir), token = {}, initial = box?.requestContextInstallation().read();
12484
+ if (!box || !initial && !options.firstOnStage?.current() || !admission || admission.available() || !lease?.current() || !current() || this.requestContextRetainedFactory)
12485
+ throw Error("Retained request owner factory unavailable");
12486
+ let sealed = !!initial, attached = false;
12487
+ const entries = new Map(), preparing = new Set(), retiredLaunches = new Map();
12488
+ let serial = 0;
12489
+ this.requestContextRetainedFactory = token;
12490
+ const owned = () => { try {
12491
+ return this.requestContextRetainedFactory === token && !this.shuttingDown && lease.current() && current() && this.requestContextAdmission === admission;
12492
+ }
12493
+ catch {
12494
+ return false;
12495
+ } };
12496
+ const entryCurrent = (entry) => {
12497
+ try {
12498
+ return owned() && entries.get(entry.name) === entry && this.contactGeneration(entry.name) === entry.incarnation
12499
+ && (!entry.daemon || this.daemons.get(entry.name) === entry.daemon || entry.starting && !this.daemons.has(entry.name));
12500
+ }
12501
+ catch {
12502
+ return false;
12503
+ }
12504
+ };
12505
+ const prepare = async (name, config) => {
12506
+ if (!owned() || preparing.has(name))
12507
+ throw Error("Request owner registration changed");
12508
+ preparing.add(name);
12509
+ try {
12510
+ const incarnation = this.contactGeneration(name), previous = entries.get(name), stored = box.requestContextWork.read(name), staging = !sealed && options.firstOnStage?.current() === true;
12511
+ if (previous?.exec) {
12512
+ if (!previous.exec.idle())
12513
+ throw Error("Request owner is still preparing or running");
12514
+ if (previous.incarnation === incarnation && previous.work.current()) {
12515
+ if (!staging)
12516
+ this.sealRequestContextWorkRegistration(name, owned);
12517
+ return;
12518
+ }
12519
+ }
12520
+ if (previous?.daemon && this.daemons.get(name) === previous.daemon)
12521
+ throw Error("Request owner is still running");
12522
+ if (previous?.daemon && (!previous.resources || !await previous.resources.retired()) || !owned())
12523
+ throw Error("Request predecessor has not retired");
12524
+ if ((!stored || stored.incarnation !== incarnation) && !(!stored && staging)) {
12525
+ // Cold unknown predecessors remain blocked. A new birth proves absence of any earlier owned launch;
12526
+ // a recorded predecessor must additionally have this factory's exact retired resource receipt.
12527
+ if (stored && !previous?.resources)
12528
+ throw Error("Request predecessor retirement unavailable");
12529
+ const absent = () => !this.daemons.has(name) && !existsSync(join(this.getInstanceDir(name), "window-id")) && !existsSync(join(this.getInstanceDir(name), "channel.sock"))
12530
+ && !WindowsAgents.requestContextOwnersOnDisk(this.dataDir).some(row => row.instance === name);
12531
+ await this.registerRequestContextWork(name, { current: () => owned() && this.contactGeneration(name) === incarnation && !this.daemons.has(name) && entries.get(name) === previous,
12532
+ retired: () => previous?.resources?.retired() ?? Promise.resolve(absent()) });
12533
+ }
12534
+ if (!owned() || this.contactGeneration(name) !== incarnation || this.daemons.has(name))
12535
+ throw Error("Request owner registration changed");
12536
+ if (!staging)
12537
+ this.sealRequestContextWorkRegistration(name, owned);
12538
+ previous?.prepared?.dispose();
12539
+ previous?.exec?.dispose();
12540
+ previous?.work.dispose();
12541
+ const entry = {};
12542
+ Object.assign(entry, { name, incarnation, config: structuredClone(config), starting: true, ...((previous?.daemon || retiredLaunches.has(name)) ? { previous: previous?.daemon?.requestContextLaunchObservation() ?? retiredLaunches.get(name) } : {}) });
12543
+ entries.set(name, entry);
12544
+ retiredLaunches.delete(name);
12545
+ serial++;
12546
+ const local = () => entryCurrent(entry);
12547
+ try {
12548
+ if (isNativeExecInstance(config)) {
12549
+ entry.work = new RequestContextPreparedWork(box.requestContextWork, name, incarnation, local, staging);
12550
+ entry.exec = createRequestContextExecOwner(box, { instance: name, managerBootId: this.managerBootId, work: entry.work, registration, current: local,
12551
+ incarnation: () => this.contactGeneration(name), deliveryEpoch: () => this.getDeliveryEpoch(name), admitted: root => this.requestContextNativeAdmissionCurrent(root),
12552
+ consumptionCurrent: delivery => this.contactDeliveryCurrent(delivery), canManage: actor => { const person = this.makeRequestContextContactHost(owned, () => false, () => "active").person(actor); return !!person && this.contactAdminOf(name, person); } });
12553
+ entry.starting = false;
12554
+ }
12555
+ else {
12556
+ entry.prepared = this.prepareRequestContextDaemonOwner(name, config, policy, registration, local);
12557
+ entry.work = entry.prepared.work;
12558
+ }
12559
+ }
12560
+ catch (error) {
12561
+ if (entries.get(name) === entry)
12562
+ entries.delete(name);
12563
+ serial++;
12564
+ throw error;
12565
+ }
12566
+ }
12567
+ finally {
12568
+ preparing.delete(name);
12569
+ }
12570
+ };
12571
+ const retire = async (name, daemon, retired) => {
12572
+ const entry = entries.get(name);
12573
+ if (!entry && !this.daemons.has(name) && owned() && await retired())
12574
+ return;
12575
+ if (!owned() || entry?.daemon !== daemon || this.daemons.has(name) || !await retired() || !owned() || entries.get(name) !== entry)
12576
+ throw Error("Request owner retirement changed");
12577
+ retiredLaunches.set(name, daemon.requestContextLaunchObservation());
12578
+ entry.prepared?.dispose();
12579
+ entry.work.dispose();
12580
+ entries.delete(name);
12581
+ serial++;
12582
+ };
12583
+ const attach = () => {
12584
+ if (attached || !owned() || admission.available())
12585
+ throw Error("Retained request start hooks unavailable");
12586
+ const originalConfigure = this.configureRequestContextBeforeStart;
12587
+ this.prepareRequestContextOwnerRegistration = prepare;
12588
+ this.requestContextRetireOwner = retire;
12589
+ this.prepareRequestContextStart = (name, config) => {
12590
+ const entry = entries.get(name);
12591
+ if (!entry?.prepared || entry.daemon || !entryCurrent(entry) || requestContextDigest(entry.config) !== requestContextDigest(config))
12592
+ throw Error("Retained request preparation unavailable");
12593
+ return entry.prepared.preparation;
12594
+ };
12595
+ this.configureRequestContextBeforeStart = (name, daemon, config, offered) => {
12596
+ const entry = entries.get(name);
12597
+ if (!entry?.prepared || entry.daemon || !entryCurrent(entry) || !offered?.current() || offered.policy !== policy
12598
+ || requestContextDigest(config) !== requestContextDigest(entry.config))
12599
+ throw Error("Retained request owner differs");
12600
+ entry.daemon = daemon;
12601
+ if (entry.previous)
12602
+ daemon.seedRequestContextReplacement(entry.previous);
12603
+ entry.resources = daemon.prepareRequestContextStartupRetirement();
12604
+ originalConfigure?.(name, daemon, config, offered);
12605
+ entry.prepared.configure(daemon, config, offered);
12606
+ };
12607
+ this.requestContextOwnerStarted = (name, daemon) => {
12608
+ const entry = entries.get(name);
12609
+ if (!entry?.prepared || entry.daemon !== daemon || this.daemons.get(name) !== daemon || !entryCurrent(entry))
12610
+ throw Error("Retained request owner differs");
12611
+ entry.prepared.sealRegistered();
12612
+ entry.starting = false;
12613
+ serial++;
12614
+ };
12615
+ attached = true;
12616
+ };
12617
+ const adoptOwners = (values) => {
12618
+ for (const row of values) {
12619
+ if (entries.has(row.name) || this.daemons.get(row.name) !== row.daemon || !row.prepared.bound())
12620
+ throw Error("Retained request adoption differs");
12621
+ 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 };
12622
+ entries.set(row.name, entry);
12623
+ serial++;
12624
+ }
12625
+ };
12626
+ adoptOwners(adopt);
12627
+ if (!options.deferStartHooks)
12628
+ attach();
12629
+ const exec = (name) => { const entry = entries.get(name); if (!entry?.exec || !entryCurrent(entry))
12630
+ throw Error("Retained native owner unavailable"); return entry.exec; };
12631
+ const aggregate = (kind, root) => {
12632
+ const views = [], image = [];
12633
+ let unknown = !owned();
12634
+ for (const [name, daemon] of this.daemons)
12635
+ if (entries.get(name)?.daemon !== daemon)
12636
+ unknown = true;
12637
+ for (const [name, row] of [...entries].sort(([a], [b]) => a.localeCompare(b))) {
12638
+ const current = entryCurrent(row) && row.work.current();
12639
+ if (!current)
12640
+ unknown = true;
12641
+ image.push([name, row.incarnation, row.work.revision, row.daemon?.bootId ?? null, !!row.exec, current]);
12642
+ try {
12643
+ const view = kind === "turns" ? (row.exec?.turns.drainView(root) ?? row.daemon?.requestContextTurnDrainView(root))
12644
+ : kind === "calls" ? row.daemon?.requestContextCallDrainView(root) : row.prepared?.hub()?.drainView(root);
12645
+ if (view) {
12646
+ views.push(view);
12647
+ image.push([name, view.revision]);
12648
+ if (view.unknown || view.registration !== registration)
12649
+ unknown = true;
12650
+ }
12651
+ else if (row.daemon)
12652
+ unknown = true;
12653
+ if (kind === "inputs" && row.daemon) {
12654
+ const pending = row.daemon.requestContextQueuedWorkDrainView(root);
12655
+ views.push(pending);
12656
+ image.push([name, "queued", pending.revision]);
12657
+ if (pending.unknown || pending.registration !== registration)
12658
+ unknown = true;
12659
+ } // A live/missing view cannot disappear from the whole-Fleet proof.
12660
+ }
12661
+ catch {
12662
+ unknown = true;
12663
+ image.push([name, "unavailable"]);
12664
+ }
12665
+ }
12666
+ return { registration, revision: requestContextDigest([serial, kind, image, [...this.daemons].map(([name, daemon]) => [name, daemon.bootId])]), references: views.flatMap(view => view.references), unknown };
12667
+ };
12668
+ return Object.freeze({ current: owned, beforeStart: prepare, attach, adopt: adoptOwners,
12669
+ disposeStopped: async (nativeRetired) => {
12670
+ if (this.daemons.size || preparing.size || !nativeRetired())
12671
+ throw Error("Request owners are not retired");
12672
+ for (const entry of entries.values())
12673
+ if (entry.daemon && (!entry.resources || !await entry.resources.retired()))
12674
+ throw Error("Request launch retirement unavailable");
12675
+ if (!nativeRetired())
12676
+ throw Error("Native owner retirement changed");
12677
+ for (const entry of entries.values()) {
12678
+ entry.exec?.dispose();
12679
+ entry.prepared?.dispose();
12680
+ entry.work.dispose();
12681
+ }
12682
+ entries.clear();
12683
+ serial++;
12684
+ if (this.requestContextRetainedFactory !== token)
12685
+ throw Error("Request owner factory changed");
12686
+ this.requestContextRetainedFactory = undefined;
12687
+ },
12688
+ disposeUnstarted: () => {
12689
+ if (entries.size || preparing.size || this.daemons.size || this.requestContextRetainedFactory !== token)
12690
+ throw Error("Request owners have already started");
12691
+ this.requestContextRetainedFactory = undefined;
12692
+ serial++;
12693
+ },
12694
+ bound: (name, daemon) => { const entry = entries.get(name); return !!entry && entry.daemon === daemon && entryCurrent(entry) && entry.prepared?.bound() === true; },
12695
+ retain: () => { if (sealed || !owned() || !options.firstOnStage?.current())
12696
+ throw Error("Request owner staging changed"); for (const entry of entries.values())
12697
+ entry.work.retainPrepared(); },
12698
+ seal: () => { if (!owned() || !box.requestContextInstallation().read())
12699
+ throw Error("Request owner staging has not committed"); for (const entry of entries.values()) {
12700
+ entry.work.sealRetained();
12701
+ this.sealRequestContextWorkRegistration(entry.name, owned);
12702
+ } sealed = true; },
12703
+ disposeStaged: async () => {
12704
+ if (sealed || box.requestContextInstallation().read() || !owned() || attached)
12705
+ throw Error("Retained request owners cannot revert");
12706
+ for (const entry of entries.values())
12707
+ if (entry.exec && !entry.exec.idle() || entry.daemon && (!entry.resources || !await entry.resources.retired()))
12708
+ throw Error("Staged request owner is still running");
12709
+ for (const entry of entries.values()) {
12710
+ entry.exec?.dispose();
12711
+ entry.prepared?.dispose();
12712
+ entry.work.dispose();
12713
+ }
12714
+ entries.clear();
12715
+ serial++;
12716
+ if (this.requestContextRetainedFactory !== token)
12717
+ throw Error("Retained request owner changed");
12718
+ this.requestContextRetainedFactory = undefined;
12719
+ },
12720
+ hub: (name) => { const entry = entries.get(name); return entry && entryCurrent(entry) ? entry.prepared?.hub() ?? null : null; },
12721
+ execTurns: (name) => exec(name).turns, execOwner: (name) => exec(name).owner(),
12722
+ execInput: (name, ...args) => exec(name).prepare(...args),
12723
+ revision: () => aggregate("turns", "").revision, turnView: (root) => aggregate("turns", root),
12724
+ callRevision: () => aggregate("calls", "").revision, callView: (root) => aggregate("calls", root),
12725
+ inputRevision: () => aggregate("inputs", "").revision, inputView: (root) => aggregate("inputs", root),
12726
+ });
12727
+ }
12728
+ /** One replacement's C/D-local binding. It is constructed before startup, never hot-bound or published here. */
12729
+ makeRequestContextDaemonBinding(instance, daemon, work, registration, current) {
12730
+ const box = this.deliveryOutbox;
12731
+ if (!box)
12732
+ throw Error("Request input owner is unavailable");
12733
+ const identity = () => {
12734
+ if (!work.current())
12735
+ throw Error("Request work identity is no longer current");
12736
+ const value = work.identity();
12737
+ if (value.incarnation !== this.contactGeneration(instance))
12738
+ throw Error("Request source incarnation changed");
12739
+ return Object.freeze({ incarnation: value.incarnation, workGeneration: value.workGeneration });
12740
+ };
12741
+ identity();
12742
+ const owned = () => { try {
12743
+ identity();
12744
+ return current() && work.current();
12745
+ }
12746
+ catch {
12747
+ return false;
12748
+ } };
12749
+ const manage = (actor) => {
12750
+ if (actor.kind !== "person" || actor.platform === "hub")
12751
+ return false;
12752
+ const adapter = actor.platform === "host" ? "host" : this.contactAdapter(instance)?.id;
12753
+ if (!adapter)
12754
+ return false;
12755
+ return owned() && this.contactAdminOf(instance, { platform: actor.platform, adapterId: adapter, userId: actor.userId, label: actor.userId });
12756
+ };
12757
+ const human = this.makeRequestContextHumanResolver(instance, daemon, owned), delivery = this.makeRequestContextDeliveryResolver(instance, daemon, owned), hub = this.makeRequestContextHubResolver(instance, daemon, owned, registration);
12758
+ const input = (id, wire, owner) => {
12759
+ if (!owned() || this.daemons.get(instance) !== daemon)
12760
+ throw Error("Request input owner changed");
12761
+ return human.prepare(id, wire, owner) ?? delivery.prepare(id, wire, owner) ?? hub.prepare(id, wire, owner);
12762
+ };
12763
+ const turns = new RequestContextLocalTurns({ ...box.requestContextRecovery.ports(instance, input, manage), registration });
12764
+ daemon.setRequestContextLocalLifecycle(turns, identity, () => {
12765
+ if (!owned())
12766
+ throw Error("Request work identity is no longer current");
12767
+ const before = identity();
12768
+ work.fresh();
12769
+ const after = identity();
12770
+ if (!owned() || after.incarnation !== before.incarnation || after.workGeneration === before.workGeneration)
12771
+ throw Error("Fresh request work identity did not rotate");
12772
+ }, snapshot => requestHumanReplyTarget(box, snapshot, () => owned() && daemon.requestContextTurnCurrent(snapshot), root => this.requestContextNativeAdmissionCurrent(root)), (id, recovery) => {
12773
+ const publication = this.requestContextBoot?.publication;
12774
+ if (!publication)
12775
+ return;
12776
+ if (recovery) {
12777
+ const parent = recovery.parent, owner = daemon.captureRequestContextOwner(), stored = box.requestContext(parent.context.ref.contextId);
12778
+ if (!owner || !stored || requestContextDigest(stored) !== requestContextDigest(parent.context) || parent.owner.instance !== owner.instance
12779
+ || parent.owner.incarnation !== owner.incarnation || parent.owner.workGeneration !== owner.workGeneration)
12780
+ throw Error("Recovery continuation owner changed");
12781
+ return publication.continuation(parent.context.ref.rootContextId, () => owned() && recovery.current());
12782
+ }
12783
+ const delivery = /^delivery:([a-f0-9-]{36}):([1-9][0-9]*)$/.exec(id ?? "");
12784
+ if (delivery) {
12785
+ const row = box.get(delivery[1]), owner = daemon.captureRequestContextOwner();
12786
+ if (!row || !owner || row.targetInstance !== instance || row.managerBootId !== this.managerBootId || row.targetDaemonBootId !== owner.daemonBootId
12787
+ || row.attemptNo !== Number(delivery[2]) || !["delivering", "submission_started"].includes(row.state))
12788
+ throw Error("Delivery continuation attempt changed");
12789
+ return this.requestContextDeliveryContinuation(row) ?? undefined;
12790
+ }
12791
+ const human = /^human:hmsg-([a-f0-9-]{36})$/.exec(id ?? "");
12792
+ return human ? this.requestContextHumanContinuation(instance, human[1]) : undefined;
12793
+ });
12794
+ return Object.freeze({ turns, hub, input, current: () => owned() && this.daemons.get(instance) === daemon && daemon.requestContextCallsRequired() });
12795
+ }
12796
+ /** Accepted Hub input owner; construction is pre-start and remains unpublished until the complete installer. */
12797
+ makeRequestContextHubResolver(instance, daemon, current, registration) {
12798
+ const box = this.deliveryOutbox;
12799
+ if (!box)
12800
+ throw Error("Hub request input owner is unavailable");
12801
+ return new RequestHubInputResolver(box, { instance, current: () => current() && this.daemons.get(instance) === daemon,
12802
+ runtimeOwner: () => daemon.captureRequestContextOwner(), active: () => daemon.requestContextTurnSnapshot(), registration });
12803
+ }
12804
+ /** Physical B attempt resolver for the exact replacement daemon; no origin or correlation fallback. */
12805
+ makeRequestContextDeliveryResolver(instance, daemon, current) {
12806
+ const box = this.deliveryOutbox;
12807
+ if (!box)
12808
+ throw Error("Request delivery input owner is unavailable");
12809
+ return makeRequestDeliveryInputResolver(box, { instance, managerBootId: this.managerBootId,
12810
+ current: () => current() && this.daemons.get(instance) === daemon, runtimeOwner: () => daemon.captureRequestContextOwner(),
12811
+ consumptionCurrent: delivery => this.contactDeliveryCurrent(delivery) });
12812
+ }
12813
+ /** Pre-start owner factory; this neither installs a lifecycle nor publishes serving input. */
12814
+ makeRequestContextHumanResolver(instance, daemon, current) {
12815
+ const box = this.deliveryOutbox;
12816
+ if (!box)
12817
+ throw Error("Human request input owner is unavailable");
12818
+ return makeRequestHumanInputResolver(box, { instance, managerBootId: this.managerBootId,
12819
+ current: () => current() && this.daemons.get(instance) === daemon,
12820
+ runtimeOwner: () => daemon.captureRequestContextOwner(), humanOwner: () => this.humanReceiptOwner(instance, daemon), active: () => daemon.requestContextTurnSnapshot(),
12821
+ admitted: context => this.requestContextNativeAdmissionCurrent(context),
12822
+ canManage: actor => {
12823
+ if (actor.kind !== "person" || actor.platform === "hub")
12824
+ return false;
12825
+ const adapter = actor.platform === "host" ? "host" : this.contactAdapter(instance)?.id;
12826
+ if (!adapter)
12827
+ return false;
12828
+ return this.contactAdminOf(instance, { platform: actor.platform, adapterId: adapter, userId: actor.userId, label: actor.userId });
12829
+ } });
12830
+ }
12831
+ /** Assigned only by the complete installer at publication; candidate launch rendering cannot install this. */
12832
+ requestContextHumanAdmission;
12833
+ makeRequestContextHumanAdmission() {
12834
+ this.ensureDeliveryOutbox();
12835
+ const box = this.deliveryOutbox;
12836
+ return (instance, payload, origin, body) => {
12837
+ const room = this.contactRoom(instance), meta = payload.meta;
12838
+ const platform = (id) => {
12839
+ const adapter = this.adapters.get(id) ?? this.worlds.get(id)?.adapter;
12840
+ const configured = (this.fleetConfig?.channels ?? (this.fleetConfig?.channel ? [this.fleetConfig.channel] : [])).find(channel => (channel.id ?? channel.type) === id);
12841
+ const kind = adapter?.type ?? configured?.type;
12842
+ return kind === "discord" || kind === "telegram" ? kind : null;
12843
+ };
12844
+ const nativeBasis = admittedNativeHumanIngress(origin), webBasis = origin.platform === "web" ? admittedHumanWebIngress(origin) : null;
12845
+ if (origin.platform === "web" && !webBasis?.sessionHandle)
12846
+ throw Error("Accepted web input route is unavailable");
12847
+ if (room && origin.platform !== "web" && (!nativeBasis || nativeBasis.roomId !== room.channelId || origin.adapter_id !== (room.adapterId ?? this.contactAdapter(instance)?.id)))
12848
+ throw Error("Accepted Classic admission basis is unavailable");
12849
+ const daemon = ["steer", "btw"].includes(String(payload.type)) ? this.lifecycle?.daemons.get(instance) : undefined, parent = daemon?.requestContextTurnSnapshot();
12850
+ const steer = parent && daemon ? { parent, current: () => this.daemons.get(instance) === daemon && daemon.requestContextTurnCurrent(parent), canManage: (actor) => {
12851
+ if (actor.kind !== "person" || actor.platform === "hub")
12852
+ return false;
12853
+ const adapter = actor.platform === "host" ? "host" : this.contactAdapter(instance)?.id;
12854
+ return !!adapter && this.contactAdminOf(instance, { platform: actor.platform, adapterId: adapter, userId: actor.userId, label: actor.userId });
12855
+ } } : undefined;
12856
+ 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,
12857
+ web: webBasis,
12858
+ classic: room && origin.platform !== "web" && nativeBasis ? { ...nativeBasis, adapterId: origin.adapter_id } : null,
12859
+ route: { kind: origin.platform === "web" ? "web" : "room", adapterId: origin.platform === "web" ? meta?.adapter_id : origin.adapter_id ?? undefined,
12860
+ chatId: meta?.chat_id ?? "", threadId: meta?.thread_id ?? "", ...(meta?.message_id ? { messageId: meta.message_id } : {}),
12861
+ ...(origin.platform === "web" ? { sessionHandle: webBasis.sessionHandle } : {}) }, platform });
12862
+ return captured.receipt;
12863
+ };
12864
+ }
10483
12865
  /** Evidence-only admission. Bots/system/agent payloads have no trusted origin. */
10484
12866
  humanReceiptPayload(instanceName, payload, origin, originalBody) {
10485
12867
  // #1939 S3: "via web (verified)" comes only from the receipt written here — never from a caller's meta.
@@ -10490,10 +12872,18 @@ export class FleetManager {
10490
12872
  }
10491
12873
  if (!origin || !this.deliveryOutbox)
10492
12874
  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)
12875
+ const installed = requestContextPolicyInstalled(this.requestContextPolicy);
12876
+ // A committed but unpublished bridge can retain exact input metadata while the actual write stays fenced.
12877
+ const prepared = this.requestContextBoot?.publication.heldUnpublished() === true && this.requestContextModes?.current() === true;
12878
+ const scoped = installed || prepared;
12879
+ if (scoped && !this.requestContextHumanAdmission)
12880
+ throw Error("Accepted human input admission is unavailable");
12881
+ const row = scoped ? this.requestContextHumanAdmission(instanceName, payload, origin, originalBody)
12882
+ : this.deliveryOutbox.createHumanReceipt({ targetInstance: instanceName, originalBody,
12883
+ origin: { ...origin }, inputKind: String(payload.type), managerBootId: this.managerBootId });
12884
+ // Installed work uses its admitted request only; lifetime history is no longer a permission input or shadow.
12885
+ const contactStore = scoped ? undefined : this.deliveryOutbox.contactAuthorizations;
12886
+ if (!scoped && this.contactRoom(instanceName)?.restrictedMode === true && !contactStore)
10497
12887
  throw Error("Contact origin storage unavailable");
10498
12888
  // M-3830 (user 11-26, Fable): a person's message becomes contact origin only in a restricted ClassicBot room. Who may
10499
12889
  // talk to a fleet agent in its own topic is the admin's channel access (#754); recording it only once some earlier
@@ -10530,8 +12920,14 @@ export class FleetManager {
10530
12920
  }
10531
12921
  }
10532
12922
  const verified = origin.platform === "web" && authority?.kind === "web-verified";
10533
- return { ...payload, meta: { ...(payload.meta ?? {}),
12923
+ const admitted = { ...payload, meta: { ...(payload.meta ?? {}),
10534
12924
  human_receipt_id: row.receipt_id, verification_id: row.message_id, ...(verified ? { web_verified: "1" } : {}) } };
12925
+ if (this.requestContextBoot) {
12926
+ const continuation = this.requestContextHumanContinuation(instanceName, row.receipt_id);
12927
+ if (continuation)
12928
+ requestPayloadContinuations.set(admitted, continuation);
12929
+ }
12930
+ return admitted;
10535
12931
  }
10536
12932
  /** Register owned preparation at IPC; bind once at the final pane write. No human retry lane. */
10537
12933
  bindHumanReceiptPayload(instanceName, payload) {
@@ -10540,6 +12936,11 @@ export class FleetManager {
10540
12936
  return payload;
10541
12937
  const daemon = this.daemons.get(instanceName);
10542
12938
  const owner = this.humanReceiptOwner(instanceName, daemon);
12939
+ const retained = retainedHumanControl(payload);
12940
+ const bind = (wire) => retained
12941
+ ? this.deliveryOutbox.bindRetainedHumanControlReceipt(retained, meta.human_receipt_id, instanceName, owner, wire, this.managerBootId, () => daemon?.bootId === retained.targetDaemonBootId && this.humanReceiptOwner(instanceName, daemon) === owner
12942
+ && (!this.requestContextAdmission || this.requestContextAdmission.available(requestPayloadContinuations.get(payload))))
12943
+ : this.deliveryOutbox.bindHumanReceipt(meta.human_receipt_id, instanceName, owner, wire, this.managerBootId);
10543
12944
  if (!daemon || !owner) {
10544
12945
  this.deliveryOutbox.markHumanReceiptUncertain(meta.human_receipt_id, instanceName);
10545
12946
  return payload;
@@ -10555,7 +12956,7 @@ export class FleetManager {
10555
12956
  throw new Error("Human delivery ownership changed");
10556
12957
  const dialectMeta = { ...originalMeta, human_wire_dialect: presentation.dialect ?? "legacy" };
10557
12958
  const wire = daemon.humanReceiptWire(content, dialectMeta, kind, presentation);
10558
- const row = this.deliveryOutbox.bindHumanReceipt(meta.human_receipt_id, instanceName, owner, wire, this.managerBootId);
12959
+ const row = bind(wire);
10559
12960
  if (this.humanReceiptOwner(instanceName, daemon) !== owner)
10560
12961
  throw new Error("Human delivery ownership changed");
10561
12962
  return { wire, meta: { human_owner_key: owner, human_daemon_owner: daemonOwner,
@@ -10564,7 +12965,7 @@ export class FleetManager {
10564
12965
  return { ...payload, meta: { ...meta, human_prepare_token: token } };
10565
12966
  }
10566
12967
  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);
12968
+ const row = bind(wire);
10568
12969
  if (!daemonOwner || this.humanReceiptOwner(instanceName, daemon) !== owner)
10569
12970
  throw new Error("Human delivery ownership changed");
10570
12971
  // /raw retains exact bytes and never acquires a positive verification capability.
@@ -10577,6 +12978,8 @@ export class FleetManager {
10577
12978
  async deliverHumanToInstance(instanceName, payload, origin, originalBody, options) {
10578
12979
  const admitted = this.humanReceiptPayload(instanceName, payload, origin, originalBody);
10579
12980
  const id = admitted.meta?.human_receipt_id;
12981
+ if (origin && id && requestContextPolicyInstalled(this.requestContextPolicy))
12982
+ nativeHumanInputs.set(admitted, { instance: instanceName, inputId: `human:hmsg-${id}` });
10580
12983
  let sent = false;
10581
12984
  try {
10582
12985
  const result = options ? await this.deliverToInstance(instanceName, admitted, options) : await this.deliverToInstance(instanceName, admitted);
@@ -10602,11 +13005,37 @@ export class FleetManager {
10602
13005
  }
10603
13006
  /** Synchronous steer/btw handoff, using the same evidence and owner binding. */
10604
13007
  sendHumanControl(instanceName, payload, origin, originalBody) {
10605
- const ipc = this.instanceIpcClients.get(instanceName);
10606
- if (this.shuttingDown || !ipc?.connected)
13008
+ if (this.shuttingDown || this.requestContextAdmission?.available() !== false && !this.instanceIpcClients.get(instanceName)?.connected)
10607
13009
  return false;
10608
13010
  const admitted = this.humanReceiptPayload(instanceName, payload, origin, originalBody);
10609
13011
  const id = admitted.meta?.human_receipt_id;
13012
+ if (this.requestContextAdmission && !this.requestContextAdmission.available(requestPayloadContinuations.get(admitted))) {
13013
+ try {
13014
+ if (!this.deliveryOutbox)
13015
+ throw Error("Held human control storage unavailable");
13016
+ const key = `human-control:${id ?? randomUUID()}`;
13017
+ this.deliveryOutbox.admit({ operationId: key, sourceKey: key, sourceInstance: "agend-system",
13018
+ sourceDaemonBootId: this.managerBootId, targetInstance: instanceName, kind: "human_control", payload: admitted });
13019
+ this.scheduleDeliveryOutboxPump();
13020
+ return true; // Acknowledged only after durable admission; publishing/aborting wakes the existing pump.
13021
+ }
13022
+ catch (error) {
13023
+ if (id)
13024
+ this.deliveryOutbox?.markHumanReceiptUncertain(id, instanceName);
13025
+ this.logger.warn({ err: error, instanceName }, "Human control could not be retained");
13026
+ return false;
13027
+ }
13028
+ }
13029
+ return FleetManager.prototype.sendAdmittedHumanControl.call(this, instanceName, admitted);
13030
+ }
13031
+ sendAdmittedHumanControl(instanceName, admitted) {
13032
+ const ipc = this.instanceIpcClients.get(instanceName);
13033
+ const id = admitted.meta?.human_receipt_id;
13034
+ if (this.shuttingDown || !ipc?.connected) {
13035
+ if (id)
13036
+ this.deliveryOutbox?.markHumanReceiptUncertain(id, instanceName);
13037
+ return false;
13038
+ }
10610
13039
  let sent = false;
10611
13040
  try {
10612
13041
  const wire = this.bindHumanReceiptPayload(instanceName, admitted);
@@ -10626,16 +13055,23 @@ export class FleetManager {
10626
13055
  }
10627
13056
  /** Single delivery facade: wake paused CLIs and serialize non-user work behind idle. */
10628
13057
  async deliverToInstance(instanceName, payload, options = {}) {
13058
+ if (this.requestContextAdmission && !await this.requestContextAdmission.wait(() => !this.shuttingDown && options.stillCurrent?.() !== false, requestPayloadContinuations.get(payload)))
13059
+ return false;
10629
13060
  if (this.generalLocationDeliveryHold(instanceName))
10630
13061
  return false;
10631
13062
  if (isNativeExecInstance(this.fleetConfig?.instances[instanceName])) {
10632
13063
  if (options.beforeInput)
10633
13064
  return false; // no pre-input hook on the Windows runtime
13065
+ const input = nativeHumanInputs.get(payload);
10634
13066
  return this.nativeInstanceRuntime().deliver(instanceName, payload, { stillCurrent: options.stillCurrent,
13067
+ ...(input?.instance === instanceName ? { requestContextInputId: input.inputId } : {}),
10635
13068
  ...(options.authorityCurrent ? { authorityCurrent: options.authorityCurrent } : {}) });
10636
13069
  }
10637
13070
  const deliveryEpoch = this.getDeliveryEpoch(instanceName);
10638
13071
  const deliveryPayload = { ...payload, delivery_epoch: deliveryEpoch };
13072
+ const continuation = requestPayloadContinuations.get(payload);
13073
+ if (continuation)
13074
+ requestPayloadContinuations.set(deliveryPayload, continuation);
10639
13075
  const meta = payload.meta && typeof payload.meta === "object"
10640
13076
  ? payload.meta
10641
13077
  : undefined;
@@ -11472,6 +13908,8 @@ export class FleetManager {
11472
13908
  if (this.tmuxHold)
11473
13909
  throw new Error(this.tmuxHold.detail);
11474
13910
  if (isNativeExecInstance(config)) {
13911
+ if (this.prepareRequestContextOwnerRegistration)
13912
+ await this.prepareRequestContextOwnerRegistration(name, config);
11475
13913
  execution?.assert();
11476
13914
  if (!windowsCliEnabled())
11477
13915
  throw new Error("Windows runtime is disabled");
@@ -11547,11 +13985,23 @@ export class FleetManager {
11547
13985
  || (this.explicitStopGeneration.get(name) ?? 0) !== stopGen) {
11548
13986
  throw new SupersededStartError(name);
11549
13987
  }
13988
+ if (this.prepareRequestContextOwnerRegistration) {
13989
+ await this.prepareRequestContextOwnerRegistration(name, config);
13990
+ execution?.assert();
13991
+ if (this.lifecycle.epochOf(name) !== epoch || (this.explicitStopGeneration.get(name) ?? 0) !== stopGen)
13992
+ throw new SupersededStartError(name);
13993
+ }
13994
+ const ownedStart = this.prepareRequestContextStart?.(name, config);
13995
+ const instructionMode = requestContextInstructionMode(ownedStart?.policy);
13996
+ const requestContextStart = ownedStart ? Object.freeze({ policy: ownedStart.policy,
13997
+ current: () => ownedStart.current() && requestContextInstructionMode(ownedStart.policy) === instructionMode }) : undefined;
13998
+ if (requestContextStart && !requestContextStart.current())
13999
+ throw new SupersededStartError(name);
11550
14000
  const binary = BACKEND_INSTALLATION_INFO[backend]?.binary;
11551
14001
  if (binary && !windows)
11552
14002
  noteResolvedBinary(binary, resolved ?? binary);
11553
14003
  if (!windows && config.general_topic) {
11554
- this.ensureGeneralInstructions(config.working_directory, backend, name);
14004
+ this.ensureGeneralInstructions(config.working_directory, backend, name, instructionMode);
11555
14005
  }
11556
14006
  else if (!isWindowsInstance(config) && kind === "fleet-topic") {
11557
14007
  // Workers get only role-eligible on-demand skills. Classic instances are
@@ -11559,12 +14009,14 @@ export class FleetManager {
11559
14009
  // managed independently from fleet-topic workers.
11560
14010
  try {
11561
14011
  const skillsWorkDir = this.resolveKnowledgeWorkDir(config.working_directory, backend, name);
11562
- measureSyncWork("fleet.workerSkills", () => this.syncRoleSkills(skillsWorkDir, backend, "worker"));
14012
+ measureSyncWork("fleet.workerSkills", () => this.syncRoleSkills(skillsWorkDir, backend, "worker", undefined, false, instructionMode));
11563
14013
  }
11564
14014
  catch (err) {
11565
14015
  // Skill publishing is additive. A read-only or temporarily unavailable
11566
14016
  // workspace must not turn an otherwise valid worker startup into a
11567
14017
  // fleet outage.
14018
+ if (instructionMode !== null)
14019
+ throw err;
11568
14020
  this.logger.warn({ err, name, backend }, "Failed to sync worker skills — continuing startup");
11569
14021
  }
11570
14022
  }
@@ -11576,11 +14028,13 @@ export class FleetManager {
11576
14028
  try {
11577
14029
  const skillsWorkDir = this.resolveKnowledgeWorkDir(config.working_directory, backend, name);
11578
14030
  if (insideManagedWorkspaces(skillsWorkDir))
11579
- measureSyncWork("fleet.classicSkills", () => this.syncRoleSkills(skillsWorkDir, backend, "classic", undefined, this.classicContactRestricted(name)));
14031
+ measureSyncWork("fleet.classicSkills", () => this.syncRoleSkills(skillsWorkDir, backend, "classic", undefined, this.classicContactRestricted(name), instructionMode));
11580
14032
  else
11581
14033
  this.logger.debug({ name, skillsWorkDir }, "Classic workspace is not AgEnD-managed — no skills published");
11582
14034
  }
11583
14035
  catch (err) {
14036
+ if (instructionMode !== null)
14037
+ throw err;
11584
14038
  this.logger.warn({ err, name, backend }, "Failed to sync classic skills — continuing startup");
11585
14039
  }
11586
14040
  }
@@ -11592,10 +14046,10 @@ export class FleetManager {
11592
14046
  await this.lifecycle.start(name, config, topicMode, identity, transition, execution, daemon => {
11593
14047
  // Only this transition's actual publication can acquire its replacement.
11594
14048
  receipt.daemon = daemon;
11595
- });
14049
+ }, requestContextStart);
11596
14050
  }
11597
14051
  else
11598
- await this.lifecycle.start(name, config, topicMode, identity, transition, execution);
14052
+ await this.lifecycle.start(name, config, topicMode, identity, transition, execution, undefined, requestContextStart);
11599
14053
  }
11600
14054
  catch (err) {
11601
14055
  if (err instanceof LegacyWindowHoldError) {
@@ -11604,6 +14058,12 @@ export class FleetManager {
11604
14058
  }
11605
14059
  throw err;
11606
14060
  }
14061
+ if (this.requestContextOwnerStarted) {
14062
+ const owned = this.daemons.get(name);
14063
+ if (!owned)
14064
+ throw Error("Request owner did not start");
14065
+ this.requestContextOwnerStarted(name, owned);
14066
+ }
11607
14067
  if (this.legacyWindowHolds.delete(name))
11608
14068
  this.needsYou?.poke();
11609
14069
  execution?.assert();
@@ -14374,6 +16834,8 @@ export class FleetManager {
14374
16834
  finally {
14375
16835
  envLease.release();
14376
16836
  }
16837
+ if (this.requestContextBoot && !this.requestContextBoot.owner.current())
16838
+ await this.resetStoppedRequestContextAssembly();
14377
16839
  this.ensureDeliveryOutbox();
14378
16840
  // #1956: the spawn helper the fleet's tmux/stty commands are started by (its fork is cheap; the fleet's is not).
14379
16841
  // Started here and by the fleet's own timer — never by a tool handler — and stopped with the fleet.
@@ -14385,7 +16847,17 @@ export class FleetManager {
14385
16847
  const fleet = this.loadConfig(configPath, { startup: true });
14386
16848
  this.slimFleetConfigAtStartup();
14387
16849
  this.logConfigWarningsAtStartup();
14388
- this.initializeNativeInstances();
16850
+ if (this.requestContextBoot) {
16851
+ try {
16852
+ await this.prepareRequestContextCapableBoot(this.requestContextRootRetired);
16853
+ }
16854
+ catch (error) {
16855
+ this.requestContextCutoverErrors = [{ id: "boot", kind: "owners", labels: [], ownerCause: "update", action: "inspect" }];
16856
+ this.logger.error({ err: error.message }, "Capable request-context boot remains fenced");
16857
+ }
16858
+ }
16859
+ if (!this.requestContextBoot || this.requestContextModes?.current())
16860
+ this.initializeNativeInstances();
14389
16861
  // M-2255: from here on a change to the Windows runtimes' switches applies live (observeRuntimeSwitches).
14390
16862
  this.runtimeEffects = { windows_cli: localWindowsCliEnabled(), remote_runtime: remoteRuntimeEnabled() };
14391
16863
  setLocale(detectLocale(fleet)); // user-facing text language (fleet.yaml defaults.locale / timezone)
@@ -14998,6 +17470,22 @@ export class FleetManager {
14998
17470
  // startup-owned lifecycle work and signal handlers are in place.
14999
17471
  if (this.shuttingDown || this.startupMemoryDeadline !== deadline)
15000
17472
  return;
17473
+ if (this.requestContextModes?.current() && this.requestContextBoot?.publication.heldUnpublished()) {
17474
+ try {
17475
+ await this.prepareRequestContextFutureOwners();
17476
+ const peers = this.captureRequestContextRuntimeSet();
17477
+ await peers.prepare();
17478
+ const proof = peers.prove();
17479
+ this.requestContextModes.publish(() => proof.current() && this.requestContextOwnersReady());
17480
+ this.requestContextCutoverErrors = [];
17481
+ this.scheduleRequestContextDrain();
17482
+ }
17483
+ catch (error) {
17484
+ this.requestContextCutoverErrors = [{ id: "boot-readiness", kind: "owners", labels: [], ownerCause: "update", action: "inspect" }];
17485
+ this.logger.warn({ err: error.message }, "Request-context input remains fenced");
17486
+ }
17487
+ }
17488
+ this.requestContextControl?.changed();
15001
17489
  this.finishStartup(bootUpdateMarker);
15002
17490
  this.startupDashboard = null;
15003
17491
  this.publishStartupStatus();
@@ -16027,7 +18515,8 @@ export class FleetManager {
16027
18515
  this.logger.info({ sessionName: sender, instanceName: name }, "Registered external session");
16028
18516
  }
16029
18517
  try {
16030
- await this.handleOutboundFromInstance(name, msg);
18518
+ const run = () => this.handleOutboundFromInstance(name, msg);
18519
+ await (this.requestContextPendingWork ? this.requestContextPendingWork.run(name, run) : run());
16031
18520
  }
16032
18521
  finally {
16033
18522
  this.finishRequestContextIpcCall(msg);
@@ -16038,8 +18527,10 @@ export class FleetManager {
16038
18527
  // handler without passing through the outbound path — which is how
16039
18528
  // `update_decision`, a coordinator-only tool, kept a way through.
16040
18529
  const typed = this.checkToolPermission("ipc-typed", name, toolForIpcType(msg.type));
16041
- if (typed.allowed)
16042
- this.dispatchTypedIpc(name, msg);
18530
+ if (typed.allowed) {
18531
+ const run = () => this.dispatchTypedIpc(name, msg);
18532
+ await (this.requestContextPendingWork ? this.requestContextPendingWork.run(name, run) : run());
18533
+ }
16043
18534
  else
16044
18535
  this.refuseTypedIpc(name, msg, typed.message);
16045
18536
  }
@@ -17557,6 +20048,8 @@ export class FleetManager {
17557
20048
  // must never be read as a same-name replacement's (removed and re-registered meanwhile).
17558
20049
  const sentBy = tool === "reply" ? this.webChatIdentity(instanceName) : undefined;
17559
20050
  const args = (msg.args ?? {});
20051
+ const ownedReplyRoute = this.requestContextPolicy && ["reply", "react", "edit_message"].includes(tool) ? originatingCall?.replyRoute : undefined;
20052
+ const ownedReplyTarget = ownedReplyRoute?.target;
17560
20053
  const requestId = msg.requestId;
17561
20054
  const fleetRequestId = msg.fleetRequestId;
17562
20055
  const senderSessionName = msg.senderSessionName;
@@ -17592,7 +20085,7 @@ export class FleetManager {
17592
20085
  }
17593
20086
  try {
17594
20087
  if (this.requestContextPolicy)
17595
- requireRequestContextPolicy(this, instanceName, tool === "hub_room_status" ? "hub_room_list" : tool, args, originatingCall?.admission);
20088
+ requireRequestContextPolicy(this, instanceName, tool === "hub_room_status" ? "hub_room_list" : tool, args, originatingCall?.admission, originatingCall?.replyRoute);
17596
20089
  }
17597
20090
  catch (error) {
17598
20091
  respond(null, error.message);
@@ -17647,7 +20140,7 @@ export class FleetManager {
17647
20140
  if (tool === "react" && !this.classicChannels?.getAll?.().some(room => room.instanceName === instanceName && room.restrictedMode === true) && typeof args.message_id === "string" && isWebMessageId(args.message_id)) {
17648
20141
  // The socket's own instance, never a session name the caller wrote itself (as checkToolPermission: it was not
17649
20142
  // 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);
20143
+ const r = await this.reactToWebMessage(instanceName, args.message_id, args.emoji, ownedReplyRoute);
17651
20144
  if (r.ok)
17652
20145
  respond("ok");
17653
20146
  else
@@ -17656,7 +20149,7 @@ export class FleetManager {
17656
20149
  }
17657
20150
  // A fleet with no chat platform at all is driven from the web dashboard alone: a reply has nowhere
17658
20151
  // 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();
20152
+ const webOnlyReply = tool === "reply" && (ownedReplyTarget ? !ownedReplyTarget.chatId : this.worlds.size === 0 && this.isWebOnlyFleet());
17660
20153
  if (this.worlds.size === 0 && !webOnlyReply) {
17661
20154
  // #2910: on a web-only fleet there will never be an adapter — say so, so the agent does not retry forever.
17662
20155
  respond(null, this.isWebOnlyFleet()
@@ -17677,8 +20170,10 @@ export class FleetManager {
17677
20170
  downloadAttachment: (id) => this.downloadRoomAttachment(instanceName, id) } : {}),
17678
20171
  replyFinished: () => replyBookkeeping,
17679
20172
  beforeSend: () => {
17680
- if (originatingCall && !originatingCall.current())
20173
+ if (originatingCall && !originatingCall.current() || ownedReplyRoute && !ownedReplyRoute.current())
17681
20174
  throw Error("Originating request context is no longer current");
20175
+ if (ownedReplyTarget?.chatId && ownedReplyTarget.adapterId && (this.worlds.get(ownedReplyTarget.adapterId) !== contextWorld || contextWorld?.adapter !== outAdapter))
20176
+ throw new RequestContextPolicyError("stale");
17682
20177
  const current = this.restrictedClassicRouting(instanceName);
17683
20178
  if (restrictedRoute && (!current || current.adapterId !== restrictedRoute.adapterId || current.chatId !== restrictedRoute.chatId
17684
20179
  || current.threadId !== restrictedRoute.threadId || this.contactGeneration(instanceName) !== restrictedIncarnation
@@ -17688,7 +20183,7 @@ export class FleetManager {
17688
20183
  } : {};
17689
20184
  // Resolve threadId: use sender's topic_id if sender is a known fleet instance,
17690
20185
  // fall back to general topic if sender is unknown, or IPC owner if no sender.
17691
- const senderInstanceName = !restrictedRoute && senderSessionName && this.fleetConfig?.instances[senderSessionName]
20186
+ const senderInstanceName = !ownedReplyRoute && !restrictedRoute && senderSessionName && this.fleetConfig?.instances[senderSessionName]
17692
20187
  ? senderSessionName
17693
20188
  : null;
17694
20189
  const routingConfig = senderInstanceName
@@ -17700,18 +20195,15 @@ export class FleetManager {
17700
20195
  // ids are scoped to that bot/world; routing a secondary-world id through the
17701
20196
  // primary adapter produces a 404. Instance binding remains the compatibility
17702
20197
  // 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);
20198
+ const contextAdapterId = ownedReplyTarget ? ownedReplyTarget.chatId ? ownedReplyTarget.adapterId : undefined
20199
+ : restrictedRoute?.adapterId ?? (typeof msg.adapterId === "string" && msg.adapterId ? msg.adapterId : undefined);
17706
20200
  const contextWorld = contextAdapterId ? this.worlds.get(contextAdapterId) : undefined;
17707
20201
  if (contextAdapterId && !contextWorld) {
17708
20202
  respond(null, `Adapter world unavailable: ${contextAdapterId}`);
17709
20203
  return;
17710
20204
  }
17711
- const outAdapter = contextWorld?.adapter
17712
- ?? this.getAdapterForInstance(senderInstanceName ?? instanceName)
17713
- ?? this.adapter
17714
- ?? (webOnlyReply ? WEB_ONLY_REPLY_SINK : null);
20205
+ const outAdapter = ownedReplyTarget ? webOnlyReply ? WEB_ONLY_REPLY_SINK : contextWorld?.adapter
20206
+ : contextWorld?.adapter ?? this.getAdapterForInstance(senderInstanceName ?? instanceName) ?? this.adapter ?? (webOnlyReply ? WEB_ONLY_REPLY_SINK : null);
17715
20207
  if (!outAdapter) {
17716
20208
  respond(null, "No adapter available");
17717
20209
  return;
@@ -17744,6 +20236,18 @@ export class FleetManager {
17744
20236
  else
17745
20237
  delete args.thread_id;
17746
20238
  }
20239
+ if (ownedReplyTarget) {
20240
+ if (!ownedReplyRoute.current()) {
20241
+ respond(null, "Originating request context is no longer current");
20242
+ return;
20243
+ }
20244
+ args.chat_id = ownedReplyTarget.chatId;
20245
+ threadId = ownedReplyTarget.threadId;
20246
+ if (threadId)
20247
+ args.thread_id = threadId;
20248
+ else
20249
+ delete args.thread_id;
20250
+ }
17747
20251
  // Reply dedup: retries land here when the agent was told a send failed
17748
20252
  // (daemon budget elapsed, shell tool killed) while the adapter send was
17749
20253
  // still in flight and about to succeed. One real send, everyone gets its
@@ -18436,8 +20940,7 @@ export class FleetManager {
18436
20940
  }
18437
20941
  if (type === "fleet_list_emojis" || type === "fleet_set_persona_emoji" || type === "fleet_preview_emojis"
18438
20942
  || type === "fleet_list_stickers" || type === "fleet_preview_stickers") {
18439
- this.handlePersonaEmoji(name, msg);
18440
- return;
20943
+ return this.handlePersonaEmoji(name, msg);
18441
20944
  }
18442
20945
  if (type === "fleet_get_web_theme" || type === "fleet_set_web_theme" || type === "fleet_set_web_theme_asset" || type === "fleet_reset_web_theme"
18443
20946
  || type === "fleet_get_web_appearance" || type === "fleet_preview_web_appearance"
@@ -18490,7 +20993,7 @@ export class FleetManager {
18490
20993
  : msg.type === "fleet_list_stickers" ? this.listStickersFor(instanceName, payload)
18491
20994
  : msg.type === "fleet_preview_stickers" ? this.previewStickers(instanceName, payload)
18492
20995
  : this.setPersonaEmoji(instanceName, payload);
18493
- op.then((r) => typeof r.error === "string"
20996
+ return op.then((r) => typeof r.error === "string"
18494
20997
  ? ipc.send({ type: "fleet_persona_emoji_response", fleetRequestId, error: r.error })
18495
20998
  : ipc.send({ type: "fleet_persona_emoji_response", fleetRequestId, result: r }), (err) => ipc.send({ type: "fleet_persona_emoji_response", fleetRequestId, error: err.message }));
18496
20999
  }
@@ -22245,7 +24748,15 @@ export class FleetManager {
22245
24748
  }
22246
24749
  /** The list for the web: every world's items, and those of instances with no world (#1386 §5.0). */
22247
24750
  needsYouItems() {
22248
- return this.needsYou?.webItems() ?? [];
24751
+ const items = this.needsYou?.webItems?.() ?? [];
24752
+ const cutover = this.requestContextControl?.snapshot();
24753
+ if (cutover && (cutover.attempted || cutover.everActivated) && (cutover.phase === "draining" || cutover.enableFailed === true || cutover.blockers.length > 0)) {
24754
+ this.requestContextAttentionSince ??= Date.now();
24755
+ return [...items, { id: "request-context-cutover", type: "config", instance: "", reason: "request_context_cutover",
24756
+ detail: "", since: this.requestContextAttentionSince, requestContextCutover: cutover }];
24757
+ }
24758
+ this.requestContextAttentionSince = undefined;
24759
+ return items;
22249
24760
  }
22250
24761
  /** Enabled member composition supplies held-work readers and explicit owner retry/close operations. */
22251
24762
  attachHubExecutionAttention(read, retry = null, close = undefined) {
@@ -24133,7 +26644,7 @@ export class FleetManager {
24133
26644
  // #1827: a /steer or /btw reaches the agent as the web person who wrote it.
24134
26645
  chatId: this.getGroupIdForInstance(instance) || "", messageId: newWebMessageId(),
24135
26646
  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),
26647
+ 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
26648
  ...(opts.guest ? { webGuest: true } : {}), // #2855: a guest's /steer or /btw reaches the agent as a guest's
24138
26649
  };
24139
26650
  };
@@ -28072,6 +30583,8 @@ export class FleetManager {
28072
30583
  // An agent's words reach another instance by the board (a comment, an @mention, a follower's progress) only as its
28073
30584
  // contact rules allow, as a peer message does (M-3160 / M-3384): asked as it writes and again as the notice goes out.
28074
30585
  db.board.setContactGate((source, target) => this.taskBoardMayReach(source, target));
30586
+ // A card's `handedAt` counts a hand-over only while its notice reached the instance (or the outbox has no word of it).
30587
+ db.board.setNoticeProgress((keys) => this.taskWakeProgress(keys));
28075
30588
  const waker = this.taskBoardWaker = new TaskBoardWaker({
28076
30589
  deliver: (instance, message, key, origins) => this.admitTaskBoardNotice(instance, message, key, origins),
28077
30590
  mayReach: (source, target) => this.taskBoardMayReach(source, target),
@@ -28082,7 +30595,18 @@ export class FleetManager {
28082
30595
  const outbox = this.deliveryOutbox;
28083
30596
  return outbox?.isOpen ? outbox.withdrawWaitingNotices(prefix, stale, reason).length : 0;
28084
30597
  },
30598
+ noticeState: (key) => (this.deliveryOutbox?.isOpen ? this.deliveryOutbox.noticeStateByKey(key) : null),
28085
30599
  changedAt: (uuid) => db.board.lastChangeAt(uuid),
30600
+ // The comment status: what became of a card's news for an instance — handed to delivery (its key), or not sent — is kept with
30601
+ // the comments it carried, and the open card pages read it again (the card numbers only: never who or why).
30602
+ // A card's news that handed it to the instance to start is kept the same way (the handoffs under its main task's activity, "Handoffs").
30603
+ settled: ({ uuid, instance, kind, key, skip, replaces }) => {
30604
+ const board = db.board;
30605
+ const touched = kind === "handoff"
30606
+ ? (key ? board.handoffHanded(uuid, instance, key, replaces) : skip ? board.handoffDropped(uuid, instance, skip, replaces) : [])
30607
+ : (key ? board.wakeHanded(uuid, instance, key, replaces) : skip ? board.wakeDropped(uuid, instance, skip, replaces) : []);
30608
+ this.emitTaskWakes(touched);
30609
+ },
28086
30610
  holds: (wake) => db.board.wakeHolds(wake),
28087
30611
  card: (uuid) => db.board.findCard(uuid),
28088
30612
  // #2352: the card's Needs you buttons are in this instance's own channel (it is the card's lane).
@@ -28099,19 +30623,55 @@ export class FleetManager {
28099
30623
  },
28100
30624
  log: (level, message, extra) => this.logger[level](extra ?? {}, message),
28101
30625
  });
28102
- db.board.onChange(({ rev, ids, projects, wakes, changed }) => {
30626
+ db.board.onChange(({ rev, ids, projects, wakes, changed, recalled }) => {
28103
30627
  // Refresh both old and new owners on reassignment; wakes are not an ownership index.
28104
30628
  if (ids.length)
28105
30629
  for (const name of this.daemons.keys())
28106
30630
  this.observeWorkingState(name, "tasks");
28107
30631
  this.emitSseEvent("tasks", { rev, ids, projects });
28108
30632
  waker.changed(changed);
30633
+ // A comment edited or deleted: a notice still waiting that quotes it is withdrawn and told anew with what stands (the waker).
30634
+ if (recalled?.length)
30635
+ waker.recalled(recalled);
28109
30636
  waker.note(this.withWriterOrigins(wakes));
28110
30637
  // step 3: cards waiting for the person are Needs you items; #2355 review: a project's lead routes them too.
28111
30638
  if (ids.length || projects)
28112
30639
  this.needsYou?.poke();
28113
30640
  });
28114
30641
  }
30642
+ /** A card page showing a comment's status reads it again: the card numbers whose comments moved (the page asks for the rest). */
30643
+ emitTaskWakes(ids) {
30644
+ if (ids.length)
30645
+ this.emitSseEvent("task_wakes", { ids: [...ids] });
30646
+ }
30647
+ /** A delivery changed (state or consumed): when it is a task board notice, the cards it names have comments whose status moved. */
30648
+ noteTaskWakeDelivery(deliveryId) {
30649
+ const outbox = this.deliveryOutbox;
30650
+ const board = this.scheduler?.db.board;
30651
+ if (!deliveryId || !outbox || !board)
30652
+ return;
30653
+ const key = outbox.get(deliveryId)?.sourceKey ?? "";
30654
+ const uuids = cardsOfKey(key);
30655
+ if (!uuids.length)
30656
+ return;
30657
+ // The cards the notice names, and their main tasks: a main task's page lists the handoffs of its sub tasks.
30658
+ const codes = new Set();
30659
+ for (const u of uuids) {
30660
+ const card = board.findCard(u);
30661
+ if (!card)
30662
+ continue;
30663
+ codes.add(card.code);
30664
+ const main = card.parent ? board.findCard(card.parent) : undefined;
30665
+ if (main)
30666
+ codes.add(main.code);
30667
+ }
30668
+ this.emitTaskWakes([...codes]);
30669
+ }
30670
+ /** How far the notices carrying comments (the task board's) got in the delivery outbox, by their keys (the card page's comment status). */
30671
+ taskWakeProgress(keys) {
30672
+ const outbox = this.deliveryOutbox;
30673
+ return outbox?.isOpen ? outbox.noticeProgress(keys) : new Map();
30674
+ }
28115
30675
  /**
28116
30676
  * A task board notice, as AgEnD's own: through the delivery outbox, held until delivered. `origins`: the writers whose
28117
30677
  * own words it carries (a comment, a mention, a follower's progress) with their contact origin as they wrote; the
@@ -28273,10 +30833,10 @@ export class FleetManager {
28273
30833
  static INSTRUCTIONS_FILENAME = Object.fromEntries(Object.entries(INSTRUCTIONS_FILE).map(([id, e]) => [id, e.file]));
28274
30834
  static GENERAL_INSTRUCTIONS = GENERAL_ROLE_INSTRUCTIONS;
28275
30835
  /** Ensure the general instance has its project instructions file + knowledge */
28276
- ensureGeneralInstructions(workDir, backendName, instanceName) {
28277
- measureSyncWork("fleet.generalInstructions", () => this.ensureGeneralInstructionsSync(workDir, backendName, instanceName));
30836
+ ensureGeneralInstructions(workDir, backendName, instanceName, mode = requestContextInstructionMode(this.requestContextPolicy)) {
30837
+ measureSyncWork("fleet.generalInstructions", () => this.ensureGeneralInstructionsSync(workDir, backendName, instanceName, mode));
28278
30838
  }
28279
- ensureGeneralInstructionsSync(workDir, backendName, instanceName) {
30839
+ ensureGeneralInstructionsSync(workDir, backendName, instanceName, mode = requestContextInstructionMode(this.requestContextPolicy)) {
28280
30840
  const backend = backendName ?? "claude-code";
28281
30841
  workDir = this.resolveKnowledgeWorkDir(workDir, backend, instanceName);
28282
30842
  // Board 0340ec89: General's file from before, under the lowercase name agy never read, becomes the one it reads.
@@ -28312,7 +30872,7 @@ export class FleetManager {
28312
30872
  }
28313
30873
  }
28314
30874
  // Sync bundled knowledge files to general's steering and skills directories.
28315
- this.syncGeneralKnowledge(workDir, backend);
30875
+ this.syncGeneralKnowledge(workDir, backend, mode);
28316
30876
  }
28317
30877
  /** Resolve the workspace path a backend actually uses before publishing knowledge. */
28318
30878
  resolveKnowledgeWorkDir(workDir, backend, instanceName) {
@@ -28349,16 +30909,16 @@ export class FleetManager {
28349
30909
  "antigravity": [".agents", "skills"],
28350
30910
  };
28351
30911
  /** Copy general-knowledge steering + all role-eligible skills to General. */
28352
- syncGeneralKnowledge(workDir, backend) {
30912
+ syncGeneralKnowledge(workDir, backend, mode = requestContextInstructionMode(this.requestContextPolicy)) {
28353
30913
  const knowledgeDir = join(dirname(fileURLToPath(import.meta.url)), "general-knowledge");
28354
30914
  if (!existsSync(knowledgeDir))
28355
30915
  return;
28356
- this.syncGeneralSteering(workDir, backend, join(knowledgeDir, "steering"));
28357
- this.syncRoleSkills(workDir, backend, "general", knowledgeDir);
30916
+ this.syncGeneralSteering(workDir, backend, join(knowledgeDir, "steering"), mode);
30917
+ this.syncRoleSkills(workDir, backend, "general", knowledgeDir, false, mode);
28358
30918
  this.logger.debug({ knowledgeDir, workDir, backend }, "Synced general knowledge files");
28359
30919
  }
28360
30920
  /** Publish only the bundled skills eligible for an instance role. */
28361
- syncRoleSkills(workDir, backend, role, knowledgeDir, restrictedClassic = false) {
30921
+ syncRoleSkills(workDir, backend, role, knowledgeDir, restrictedClassic = false, mode = requestContextInstructionMode(this.requestContextPolicy)) {
28362
30922
  const skillSegments = FleetManager.SKILLS_DIR_SEGMENTS[backend];
28363
30923
  if (!skillSegments)
28364
30924
  return;
@@ -28373,7 +30933,7 @@ export class FleetManager {
28373
30933
  this.syncManagedSkills(join(workDir, ...skillSegments), join(root, "skills"), role, adoptLegacyUnmanaged,
28374
30934
  // #2163: a Classic bot's skills folder (or a skill in it) may be a link out of its workspace; every path is
28375
30935
  // 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);
30936
+ role === "classic" ? (path) => insideManagedWorkspaces(path) : undefined, role === "classic" && restrictedClassic ? new Set(["persona-emoji", "web-appearance"]) : undefined, mode);
28377
30937
  this.logger.debug({ workDir, backend, role }, "Synced role-based bundled skills");
28378
30938
  }
28379
30939
  /**
@@ -28385,7 +30945,7 @@ export class FleetManager {
28385
30945
  * sync, so rule updates reach EXISTING workspaces; everything the user
28386
30946
  * wrote outside the markers is preserved byte-for-byte.
28387
30947
  */
28388
- syncGeneralSteering(workDir, backend, srcSteering) {
30948
+ syncGeneralSteering(workDir, backend, srcSteering, mode = requestContextInstructionMode(this.requestContextPolicy)) {
28389
30949
  if (!existsSync(srcSteering))
28390
30950
  return;
28391
30951
  const files = readdirSync(srcSteering).filter(f => f.endsWith(".md")).sort();
@@ -28396,7 +30956,7 @@ export class FleetManager {
28396
30956
  mkdirSync(steeringDir, { recursive: true });
28397
30957
  for (const file of files) {
28398
30958
  const dest = join(steeringDir, file);
28399
- const newContent = readFileSync(join(srcSteering, file), "utf-8");
30959
+ const newContent = requestContextSteeringText(readFileSync(join(srcSteering, file), "utf-8"), file === "core-rules.md" ? mode : null);
28400
30960
  try {
28401
30961
  if (existsSync(dest) && readFileSync(dest, "utf-8") === newContent)
28402
30962
  continue;
@@ -28410,7 +30970,7 @@ export class FleetManager {
28410
30970
  const instructionsPath = join(workDir, filename);
28411
30971
  if (backend === "antigravity" && danglingSymlink(instructionsPath))
28412
30972
  return; // kept, not followed (#1914 review; logged above)
28413
- const body = files.map(f => readFileSync(join(srcSteering, f), "utf-8").trim()).join("\n\n");
30973
+ const body = files.map(f => requestContextSteeringText(readFileSync(join(srcSteering, f), "utf-8"), f === "core-rules.md" ? mode : null).trim()).join("\n\n");
28414
30974
  const block = `${FleetManager.STEERING_BLOCK_BEGIN}\n${body}\n${FleetManager.STEERING_BLOCK_END}`;
28415
30975
  let existing = "";
28416
30976
  try {
@@ -28500,7 +31060,7 @@ export class FleetManager {
28500
31060
  catch { /* said this time; said again next start */ }
28501
31061
  this.logger.warn({ skills: names, destSkills }, "Skipping bundled skills — skills of these names exist but were not published by AgEnD");
28502
31062
  }
28503
- syncManagedSkills(destSkills, srcSkills, role, adoptLegacyUnmanaged = false, confined, excluded) {
31063
+ syncManagedSkills(destSkills, srcSkills, role, adoptLegacyUnmanaged = false, confined, excluded, mode = null) {
28504
31064
  if (!existsSync(srcSkills))
28505
31065
  return;
28506
31066
  const refuse = (path) => {
@@ -28563,7 +31123,7 @@ export class FleetManager {
28563
31123
  continue;
28564
31124
  }
28565
31125
  managed.push(name);
28566
- const newContent = bundledSkillContents(join(srcSkills, name));
31126
+ const newContent = requestContextSkillText(name, bundledSkillContents(join(srcSkills, name)), mode);
28567
31127
  if (refuse(dest))
28568
31128
  continue;
28569
31129
  try {
@@ -31735,6 +34295,16 @@ export class FleetManager {
31735
34295
  const instanceName = classicChannels.deriveInstanceName(channelName || channelId, channelId, adapterId);
31736
34296
  clearPausedMarker(this.getInstanceDir(instanceName));
31737
34297
  const selectedBackend = isSelectableClassicBackend(backend) ? backend : undefined;
34298
+ if (requestContextPolicyInstalled(this.requestContextPolicy) && !classicChannels.get(channelId, adapterId)) {
34299
+ // Durable first-birth intent precedes the Classic registry's own save. A restart/token read cannot mint it.
34300
+ this.settleHubIncarnations();
34301
+ if (this.hubIncarnationsBroken)
34302
+ throw Error("Request work registration evidence unavailable");
34303
+ const planned = { ...DEFAULT_INSTANCE_CONFIG, ...this.fleetConfig?.defaults, backend: selectedBackend ?? this.fleetConfig?.defaults?.backend ?? "claude-code",
34304
+ working_directory: this.classicWorkspaceDir(instanceName), hubClassicIdentity: JSON.stringify([adapterId ?? "", channelId]) };
34305
+ if (!this.hubAgentIncarnation(instanceName, planned, true, true))
34306
+ throw Error("Request work registration evidence unavailable");
34307
+ }
31738
34308
  classicChannels.register(channelId, adapterId, instanceName, channelName || channelId, userId, selectedBackend, restricted);
31739
34309
  // Bind this classic instance to the bot that started it (authoritative), so
31740
34310
  // replies/cancel go out through that bot even though every same-guild bot
@@ -31884,6 +34454,13 @@ export class FleetManager {
31884
34454
  // because we asked it to. Set synchronously — doStopAll runs to its first
31885
34455
  // await in the same tick as the signal handler, so no event can slip in.
31886
34456
  this.shuttingDown = true;
34457
+ if (this.requestContextDrainTimer)
34458
+ clearTimeout(this.requestContextDrainTimer);
34459
+ this.requestContextDrainTimer = undefined;
34460
+ if (this.requestContextCollectionTimer)
34461
+ clearInterval(this.requestContextCollectionTimer);
34462
+ this.requestContextCollectionTimer = undefined;
34463
+ this.requestContextAdmission?.changed();
31887
34464
  try {
31888
34465
  this.updateCard?.close();
31889
34466
  }
@@ -32193,6 +34770,13 @@ export class FleetManager {
32193
34770
  }
32194
34771
  // The lock contains a nonce, so an older/shutting-down process can never
32195
34772
  // remove a lock acquired by a newer fleet owner.
34773
+ if (this.requestContextBoot)
34774
+ try {
34775
+ await this.resetStoppedRequestContextAssembly();
34776
+ }
34777
+ catch (error) {
34778
+ this.logger.warn({ err: error.message }, "Request owners remain fenced for positive retirement before restart");
34779
+ }
32196
34780
  releaseProcessFleetLock();
32197
34781
  }
32198
34782
  /**
@@ -34373,6 +36957,7 @@ export class FleetManager {
34373
36957
  if (now !== target)
34374
36958
  continue; // the offer changed: judge the new one
34375
36959
  this.updatePreflight = mergePreflight(this.updatePreflight, fresh, now);
36960
+ void this.syncUpdateChatCard(); // M-3864 R1: the chat card's buttons follow it
34376
36961
  return;
34377
36962
  }
34378
36963
  })().finally(() => { if (this.updatePreflightRunning === running)
@@ -34399,6 +36984,120 @@ export class FleetManager {
34399
36984
  this.updatePreflight = mergePreflight(this.updatePreflight, fresh, this.updateCheckState?.offer?.version ?? null);
34400
36985
  return preflightRefusal(fresh, origin, (key, ...args) => t(key, ...args));
34401
36986
  }
36987
+ /** M-3770 1.6: make a pre-flight fix (update-fix.ts; tests stub this, so no real loginctl runs). */
36988
+ async runUpdateFix(fix) {
36989
+ const [{ applyUpdateFix }, { defaultReadinessDeps }] = await Promise.all([import("./update-fix.js"), import("./update-readiness.js")]);
36990
+ return applyUpdateFix(fix, defaultReadinessDeps());
36991
+ }
36992
+ /**
36993
+ * M-3770 S-246: Install as a service — this install's own `agend install` (never the PATH's), started apart from this
36994
+ * fleet so it outlives it, with its words in `<home>/service-install.log`. It stops this fleet by its proof and starts
36995
+ * the service (service-install-handover.ts). Waits up to 30 s to tell a refusal (nothing stopped) from the hand-over
36996
+ * (this fleet begins to stop). Tests stub this, so nothing is installed or stopped.
36997
+ */
36998
+ async startServiceInstall() {
36999
+ const [{ spawn }, { selfCommand }, { watchServiceInstall }, { SERVICE_LOCK_TOKEN_ENV }, { DIRECT_FLEET_START_ENV }] = await Promise.all([
37000
+ import("./child-process.js"), import("./cli-entry.js"), import("./update-fix.js"), import("./service-lock.js"), import("./service-owner.js")
37001
+ ]);
37002
+ const logPath = join(this.dataDir, "service-install.log");
37003
+ const logFd = openUpdateLog(logPath, `--- agend install (web, Install as a service) ${new Date().toISOString()} ---`);
37004
+ const command = selfCommand(["install"]);
37005
+ // Its own admission to the service lock, and its own fleet start if the service can't start: none of this fleet's.
37006
+ const env = { ...process.env };
37007
+ delete env[SERVICE_LOCK_TOKEN_ENV];
37008
+ delete env[DIRECT_FLEET_START_ENV];
37009
+ let exitCode;
37010
+ const child = spawn(command.command, command.args, {
37011
+ detached: true, stdio: ["ignore", logFd ? logFd.fd : "ignore", logFd ? logFd.fd : "ignore"], env,
37012
+ });
37013
+ if (logFd)
37014
+ closeSync(logFd.fd); // the child keeps its own copy
37015
+ child.on("exit", code => { exitCode = code; });
37016
+ child.on("error", () => { exitCode ??= -1; });
37017
+ child.unref();
37018
+ return watchServiceInstall({
37019
+ exitCode: () => exitCode, shuttingDown: () => this.shuttingDown,
37020
+ // This run's words only: from its own header on (the log keeps earlier runs above it).
37021
+ output: () => { const text = readLogTail(logPath) ?? ""; return text.slice(Math.max(0, text.lastIndexOf("--- agend install (web"))); },
37022
+ now: () => performance.now(), sleep: ms => new Promise(resolve => setTimeout(resolve, ms)), waitMs: 30_000,
37023
+ });
37024
+ }
37025
+ /**
37026
+ * 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
37027
+ * again first and decide whether the fix is still asked for (a page drawn from an older result never runs it); the
37028
+ * session is asked again right before it runs; the checks run once more after it, and the page gets that result.
37029
+ */
37030
+ fixUpdateOnce(key, person, fix, stillAllowed) {
37031
+ // Scoped to the person and the fix (#4557 review): one admin's key never replays another's answer.
37032
+ const slot = JSON.stringify([person, fix, key]);
37033
+ const seen = this.updateFixAnswers.get(slot);
37034
+ if (seen)
37035
+ return seen;
37036
+ const answer = this.updateFixChain.then(() => this.fixUpdateNow(person, fix, stillAllowed));
37037
+ this.updateFixChain = answer.then(() => undefined, () => undefined);
37038
+ this.updateFixAnswers.set(slot, answer);
37039
+ if (this.updateFixAnswers.size > 32)
37040
+ this.updateFixAnswers.delete(this.updateFixAnswers.keys().next().value);
37041
+ return answer;
37042
+ }
37043
+ async fixUpdateNow(person, fix, stillAllowed) {
37044
+ const [{ mergePreflight }, { fixOffered }] = await Promise.all([import("./update-readiness.js"), import("./update-fix.js")]);
37045
+ const local = async () => {
37046
+ try {
37047
+ const fresh = await this.probeUpdatePreflight({ localOnly: true });
37048
+ this.updatePreflight = mergePreflight(this.updatePreflight, fresh, this.updateCheckState?.offer?.version ?? null);
37049
+ return fresh;
37050
+ }
37051
+ catch (err) {
37052
+ this.logger.warn({ err }, "Update pre-flight could not run for a fix");
37053
+ return null;
37054
+ }
37055
+ };
37056
+ const before = await local();
37057
+ if (!before)
37058
+ return { status: 503, body: { error: "preflight_unavailable", preflight: this.updatePreflight } };
37059
+ if (!fixOffered(before, fix))
37060
+ return { status: 409, body: { error: "not_needed", preflight: this.updatePreflight } };
37061
+ if (this.shuttingDown || !stillAllowed())
37062
+ return { status: 403, body: { error: "update_needs_an_admin_session" } };
37063
+ if (fix === "service") {
37064
+ // S-246: the hand-over to the service manager. 202 { restarting } once this fleet begins to stop; 202 { pending } when
37065
+ // the command still runs after the wait (nothing may have stopped yet, and it can still refuse: the page says so and
37066
+ // looks again, never claiming a restart — #4564 review); 422 with the command's own words when it refused (nothing was
37067
+ // stopped) or failed (the fleet was started again).
37068
+ let result;
37069
+ try {
37070
+ result = await this.startServiceInstall();
37071
+ }
37072
+ catch (err) {
37073
+ this.logger.warn({ err }, "Install as a service could not start");
37074
+ result = { kind: "failed", reason: "agend install could not start" };
37075
+ }
37076
+ this.logger.info({ person, fix, result: result.kind }, "web: update pre-flight fix");
37077
+ if (result.kind === "restarting")
37078
+ return { status: 202, body: { restarting: true } };
37079
+ await local();
37080
+ if (result.kind === "pending")
37081
+ return { status: 202, body: { pending: true, preflight: this.updatePreflight } };
37082
+ if (result.kind !== "failed")
37083
+ return { status: 200, body: { preflight: this.updatePreflight } };
37084
+ const [{ serviceInstallCause }, { installRunsOnWsl }] = await Promise.all([import("./update-fix.js"), import("./install-user-systemd.js")]);
37085
+ const cause = serviceInstallCause(result.reason);
37086
+ // On WSL the user-manager cause has its own known fix (wsl --update); elsewhere the page names the generic check (#4564 look).
37087
+ const where = cause === "user-manager" && installRunsOnWsl() ? "wsl" : null;
37088
+ return { status: 422, body: { error: "fix_failed", reason: result.reason, cause, ...(where ? { where } : {}), preflight: this.updatePreflight } };
37089
+ }
37090
+ let ok = false;
37091
+ try {
37092
+ ok = (await this.runUpdateFix(fix)).ok;
37093
+ }
37094
+ catch (err) {
37095
+ this.logger.warn({ err, fix }, "Update pre-flight fix failed");
37096
+ }
37097
+ this.logger.info({ person, fix, ok }, "web: update pre-flight fix");
37098
+ await local();
37099
+ return ok ? { status: 200, body: { preflight: this.updatePreflight } } : { status: 422, body: { error: "fix_failed", preflight: this.updatePreflight } };
37100
+ }
34402
37101
  ensureUpdateCard() {
34403
37102
  if (this.updateCard)
34404
37103
  return this.updateCard;
@@ -34507,7 +37206,7 @@ export class FleetManager {
34507
37206
  }
34508
37207
  catch { /* unknown */ }
34509
37208
  const pinned = !!resolveUpdates(this.fleetConfig?.updates).pin;
34510
- const reply = updateOfferReply(this.updateOfferView(), current, pinned);
37209
+ const reply = updateOfferReply(this.updateOfferView(), current, pinned, this.usageZone());
34511
37210
  return t(reply.key, ...reply.args);
34512
37211
  }
34513
37212
  refuseImmediateUpdate() {
@@ -34598,6 +37297,7 @@ export class FleetManager {
34598
37297
  updateLog: () => ({ text: readLogTail(updateLogPath(this.dataDir)), error: readUpdateProgress(this.dataDir)?.progress.error ?? null }),
34599
37298
  card: () => this.refreshUpdateCard(),
34600
37299
  answerUpdate: (key, by, body, stillAllowed) => this.ensureUpdateCard().answer(key, by, body, stillAllowed),
37300
+ fixUpdate: (key, person, fix, stillAllowed) => this.fixUpdateOnce(key, person, fix, stillAllowed),
34601
37301
  };
34602
37302
  }
34603
37303
  /** "Check for updates": look now, no chat notice. One a minute; a second ask while one runs waits for it. */