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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (523) hide show
  1. package/dist/agent-endpoint.d.ts +1 -0
  2. package/dist/agent-endpoint.js +5 -0
  3. package/dist/agent-endpoint.js.map +1 -1
  4. package/dist/agent-file-read.js +1 -1
  5. package/dist/agent-file-read.js.map +1 -1
  6. package/dist/agent-whats-new.js +4 -0
  7. package/dist/agent-whats-new.js.map +1 -1
  8. package/dist/auth-api.js +3 -1
  9. package/dist/auth-api.js.map +1 -1
  10. package/dist/backend/kiro-auth-store.d.ts +15 -2
  11. package/dist/backend/kiro-auth-store.js +64 -0
  12. package/dist/backend/kiro-auth-store.js.map +1 -1
  13. package/dist/build-provenance.json +1 -1
  14. package/dist/channel/adapters/discord.js +4 -4
  15. package/dist/channel/adapters/discord.js.map +1 -1
  16. package/dist/channel/adapters/telegram.js +3 -3
  17. package/dist/channel/adapters/telegram.js.map +1 -1
  18. package/dist/channel/ipc-bridge.d.ts +7 -0
  19. package/dist/channel/ipc-bridge.js +45 -11
  20. package/dist/channel/ipc-bridge.js.map +1 -1
  21. package/dist/channel/mcp-server.js +3 -1
  22. package/dist/channel/mcp-server.js.map +1 -1
  23. package/dist/channel/mcp-tools.js +6 -4
  24. package/dist/channel/mcp-tools.js.map +1 -1
  25. package/dist/cli.js +35 -2
  26. package/dist/cli.js.map +1 -1
  27. package/dist/daemon.d.ts +64 -3
  28. package/dist/daemon.js +497 -102
  29. package/dist/daemon.js.map +1 -1
  30. package/dist/delivery-outbox.d.ts +107 -7
  31. package/dist/delivery-outbox.js +297 -9
  32. package/dist/delivery-outbox.js.map +1 -1
  33. package/dist/detached-fleet-stop.d.ts +40 -0
  34. package/dist/detached-fleet-stop.js +126 -0
  35. package/dist/detached-fleet-stop.js.map +1 -0
  36. package/dist/fleet-lock.d.ts +21 -0
  37. package/dist/fleet-lock.js +61 -2
  38. package/dist/fleet-lock.js.map +1 -1
  39. package/dist/fleet-manager.d.ts +502 -5
  40. package/dist/fleet-manager.js +2845 -228
  41. package/dist/fleet-manager.js.map +1 -1
  42. package/dist/fleet-windows-runtime.d.ts +39 -3
  43. package/dist/fleet-windows-runtime.js +208 -30
  44. package/dist/fleet-windows-runtime.js.map +1 -1
  45. package/dist/general-knowledge/skills/cross-instance-messaging/SKILL.md +6 -1
  46. package/dist/general-knowledge/skills/hub/SKILL.md +17 -2
  47. package/dist/general-knowledge/skills/web-appearance/SKILL.md +3 -1
  48. package/dist/general-knowledge/skills/web-dashboard/SKILL.md +102 -25
  49. package/dist/hub/admin-dashboard.js +1 -1
  50. package/dist/hub/admin-dashboard.js.map +1 -1
  51. package/dist/hub/agent-catalog.d.ts +1 -1
  52. package/dist/hub/agent-catalog.js +4 -3
  53. package/dist/hub/agent-catalog.js.map +1 -1
  54. package/dist/hub/agent-intro.d.ts +1 -1
  55. package/dist/hub/agent-intro.js +1 -1
  56. package/dist/hub/agent-intro.js.map +1 -1
  57. package/dist/hub/agent-pictures.d.ts +1 -1
  58. package/dist/hub/agent-pictures.js +4 -3
  59. package/dist/hub/agent-pictures.js.map +1 -1
  60. package/dist/hub/catalog.d.ts +2 -2
  61. package/dist/hub/catalog.js +16 -13
  62. package/dist/hub/catalog.js.map +1 -1
  63. package/dist/hub/client.js +16 -2
  64. package/dist/hub/client.js.map +1 -1
  65. package/dist/hub/compose/member.js +14 -2
  66. package/dist/hub/compose/member.js.map +1 -1
  67. package/dist/hub/compose/server.d.ts +1 -0
  68. package/dist/hub/compose/server.js +6 -3
  69. package/dist/hub/compose/server.js.map +1 -1
  70. package/dist/hub/fleet-updates.d.ts +2 -2
  71. package/dist/hub/fleet-updates.js +7 -5
  72. package/dist/hub/fleet-updates.js.map +1 -1
  73. package/dist/hub/fleet-versions.d.ts +1 -1
  74. package/dist/hub/fleet-versions.js +3 -2
  75. package/dist/hub/fleet-versions.js.map +1 -1
  76. package/dist/hub/group-policy/resources.d.ts +1 -1
  77. package/dist/hub/http/compose.js +59 -31
  78. package/dist/hub/http/compose.js.map +1 -1
  79. package/dist/hub/http/deps.d.ts +1 -0
  80. package/dist/hub/http/schema.js +4 -1
  81. package/dist/hub/http/schema.js.map +1 -1
  82. package/dist/hub/join/service.d.ts +6 -0
  83. package/dist/hub/join/service.js +10 -0
  84. package/dist/hub/join/service.js.map +1 -1
  85. package/dist/hub/member/room-ask.d.ts +7 -8
  86. package/dist/hub/member/room-ask.js +54 -13
  87. package/dist/hub/member/room-ask.js.map +1 -1
  88. package/dist/hub/member/room-post.d.ts +4 -0
  89. package/dist/hub/member/room-post.js +26 -1
  90. package/dist/hub/member/room-post.js.map +1 -1
  91. package/dist/hub/member/room-reaction-acks.d.ts +12 -0
  92. package/dist/hub/member/room-reaction-acks.js +44 -0
  93. package/dist/hub/member/room-reaction-acks.js.map +1 -0
  94. package/dist/hub/protocol.d.ts +62 -0
  95. package/dist/hub/protocol.js +5 -4
  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/audit-details.d.ts +2 -0
  110. package/dist/hub/roles/audit-details.js +1 -1
  111. package/dist/hub/roles/audit-details.js.map +1 -1
  112. package/dist/hub/roles/authority.d.ts +8 -3
  113. package/dist/hub/roles/authority.js +144 -102
  114. package/dist/hub/roles/authority.js.map +1 -1
  115. package/dist/hub/roles/clock.js +6 -5
  116. package/dist/hub/roles/clock.js.map +1 -1
  117. package/dist/hub/roles/delegation.js +2 -2
  118. package/dist/hub/roles/delegation.js.map +1 -1
  119. package/dist/hub/roles/model.d.ts +5 -2
  120. package/dist/hub/roles/model.js +5 -4
  121. package/dist/hub/roles/model.js.map +1 -1
  122. package/dist/hub/roles/read.d.ts +2 -0
  123. package/dist/hub/roles/read.js +27 -6
  124. package/dist/hub/roles/read.js.map +1 -1
  125. package/dist/hub/roles/review.js +2 -2
  126. package/dist/hub/roles/review.js.map +1 -1
  127. package/dist/hub/room-history-model.d.ts +87 -0
  128. package/dist/hub/room-history-model.js +14 -0
  129. package/dist/hub/room-history-model.js.map +1 -0
  130. package/dist/hub/room-react-ack-model.d.ts +2 -0
  131. package/dist/hub/room-react-ack-model.js +3 -0
  132. package/dist/hub/room-react-ack-model.js.map +1 -0
  133. package/dist/hub/rooms/admin.d.ts +6 -0
  134. package/dist/hub/rooms/admin.js +33 -0
  135. package/dist/hub/rooms/admin.js.map +1 -1
  136. package/dist/hub/rooms/agents.d.ts +3 -1
  137. package/dist/hub/rooms/agents.js +47 -5
  138. package/dist/hub/rooms/agents.js.map +1 -1
  139. package/dist/hub/rooms/history.d.ts +8 -0
  140. package/dist/hub/rooms/history.js +31 -0
  141. package/dist/hub/rooms/history.js.map +1 -0
  142. package/dist/hub/rooms/schema.d.ts +2 -0
  143. package/dist/hub/rooms/schema.js +4 -0
  144. package/dist/hub/rooms/schema.js.map +1 -1
  145. package/dist/hub/rooms/service.d.ts +40 -20
  146. package/dist/hub/rooms/service.js +181 -50
  147. package/dist/hub/rooms/service.js.map +1 -1
  148. package/dist/hub/rooms/types.d.ts +2 -0
  149. package/dist/hub/server.js +15 -3
  150. package/dist/hub/server.js.map +1 -1
  151. package/dist/hub/session-epoch.js +2 -1
  152. package/dist/hub/session-epoch.js.map +1 -1
  153. package/dist/hub/settings-directory-decision.js +3 -2
  154. package/dist/hub/settings-directory-decision.js.map +1 -1
  155. package/dist/hub/settings-member-address-decision.js +2 -1
  156. package/dist/hub/settings-member-address-decision.js.map +1 -1
  157. package/dist/hub/settings-web-address-decision.js +2 -1
  158. package/dist/hub/settings-web-address-decision.js.map +1 -1
  159. package/dist/hub/store.d.ts +1 -0
  160. package/dist/hub/store.js +12 -4
  161. package/dist/hub/store.js.map +1 -1
  162. package/dist/hub/types.d.ts +4 -2
  163. package/dist/hub-agent-incarnation-record.d.ts +24 -0
  164. package/dist/hub-agent-incarnation-record.js +46 -0
  165. package/dist/hub-agent-incarnation-record.js.map +1 -0
  166. package/dist/human-delivery-receipts.d.ts +16 -4
  167. package/dist/human-delivery-receipts.js +26 -5
  168. package/dist/human-delivery-receipts.js.map +1 -1
  169. package/dist/instance-lifecycle.d.ts +9 -3
  170. package/dist/instance-lifecycle.js +27 -10
  171. package/dist/instance-lifecycle.js.map +1 -1
  172. package/dist/instructions.d.ts +1 -1
  173. package/dist/local-pane-endpoint.d.ts +14 -0
  174. package/dist/local-pane-endpoint.js +32 -0
  175. package/dist/local-pane-endpoint.js.map +1 -1
  176. package/dist/locale.js +54 -6
  177. package/dist/locale.js.map +1 -1
  178. package/dist/native-agent-admission.js +9 -0
  179. package/dist/native-agent-admission.js.map +1 -1
  180. package/dist/native-exec-context.d.ts +11 -0
  181. package/dist/native-exec-context.js +18 -0
  182. package/dist/native-exec-context.js.map +1 -0
  183. package/dist/native-exec-input.d.ts +56 -0
  184. package/dist/native-exec-input.js +89 -0
  185. package/dist/native-exec-input.js.map +1 -0
  186. package/dist/native-mcp.d.ts +9 -1
  187. package/dist/native-mcp.js +29 -7
  188. package/dist/native-mcp.js.map +1 -1
  189. package/dist/native-pane-lifecycle.d.ts +3 -0
  190. package/dist/native-pane-lifecycle.js +2 -0
  191. package/dist/native-pane-lifecycle.js.map +1 -1
  192. package/dist/native-pane-manager.d.ts +18 -0
  193. package/dist/native-pane-manager.js +85 -8
  194. package/dist/native-pane-manager.js.map +1 -1
  195. package/dist/needs-you.d.ts +2 -1
  196. package/dist/needs-you.js.map +1 -1
  197. package/dist/outbound-handlers.d.ts +1 -0
  198. package/dist/outbound-handlers.js +9 -3
  199. package/dist/outbound-handlers.js.map +1 -1
  200. package/dist/outbound-schemas.d.ts +5 -0
  201. package/dist/outbound-schemas.js +2 -0
  202. package/dist/outbound-schemas.js.map +1 -1
  203. package/dist/public-web-gateway.js +5 -1
  204. package/dist/public-web-gateway.js.map +1 -1
  205. package/dist/recover.cjs +213 -26
  206. package/dist/reply-buttons-controller.d.ts +1 -0
  207. package/dist/reply-buttons-controller.js +1 -1
  208. package/dist/reply-buttons-controller.js.map +1 -1
  209. package/dist/request-contact-gate.d.ts +2 -0
  210. package/dist/request-contact-gate.js +8 -3
  211. package/dist/request-contact-gate.js.map +1 -1
  212. package/dist/request-contact-native.js +4 -0
  213. package/dist/request-contact-native.js.map +1 -1
  214. package/dist/request-context-activation.d.ts +29 -0
  215. package/dist/request-context-activation.js +74 -0
  216. package/dist/request-context-activation.js.map +1 -0
  217. package/dist/request-context-admission.d.ts +22 -0
  218. package/dist/request-context-admission.js +12 -0
  219. package/dist/request-context-admission.js.map +1 -0
  220. package/dist/request-context-boot.d.ts +35 -0
  221. package/dist/request-context-boot.js +97 -0
  222. package/dist/request-context-boot.js.map +1 -0
  223. package/dist/request-context-call.d.ts +2 -0
  224. package/dist/request-context-call.js.map +1 -1
  225. package/dist/request-context-continuation.d.ts +6 -0
  226. package/dist/request-context-continuation.js +24 -0
  227. package/dist/request-context-continuation.js.map +1 -0
  228. package/dist/request-context-control-api.d.ts +101 -0
  229. package/dist/request-context-control-api.js +177 -0
  230. package/dist/request-context-control-api.js.map +1 -0
  231. package/dist/request-context-control-copy.d.ts +3 -0
  232. package/dist/request-context-control-copy.js +7 -0
  233. package/dist/request-context-control-copy.js.map +1 -0
  234. package/dist/request-context-controller.d.ts +44 -0
  235. package/dist/request-context-controller.js +129 -0
  236. package/dist/request-context-controller.js.map +1 -0
  237. package/dist/request-context-delivery-resolver.d.ts +13 -0
  238. package/dist/request-context-delivery-resolver.js +30 -0
  239. package/dist/request-context-delivery-resolver.js.map +1 -0
  240. package/dist/request-context-drain.d.ts +13 -0
  241. package/dist/request-context-drain.js +79 -6
  242. package/dist/request-context-drain.js.map +1 -1
  243. package/dist/request-context-enable-offer.d.ts +13 -0
  244. package/dist/request-context-enable-offer.js +31 -0
  245. package/dist/request-context-enable-offer.js.map +1 -0
  246. package/dist/request-context-exec-owner.d.ts +39 -0
  247. package/dist/request-context-exec-owner.js +128 -0
  248. package/dist/request-context-exec-owner.js.map +1 -0
  249. package/dist/request-context-go-back-view.d.ts +1 -0
  250. package/dist/request-context-go-back-view.js +17 -0
  251. package/dist/request-context-go-back-view.js.map +1 -0
  252. package/dist/request-context-helper-readiness.d.ts +14 -0
  253. package/dist/request-context-helper-readiness.js +23 -0
  254. package/dist/request-context-helper-readiness.js.map +1 -0
  255. package/dist/request-context-helper.d.ts +20 -0
  256. package/dist/request-context-helper.js +41 -0
  257. package/dist/request-context-helper.js.map +1 -0
  258. package/dist/request-context-hub-resolver.d.ts +29 -0
  259. package/dist/request-context-hub-resolver.js +90 -0
  260. package/dist/request-context-hub-resolver.js.map +1 -0
  261. package/dist/request-context-human-resolver.d.ts +20 -0
  262. package/dist/request-context-human-resolver.js +77 -0
  263. package/dist/request-context-human-resolver.js.map +1 -0
  264. package/dist/request-context-human.d.ts +106 -0
  265. package/dist/request-context-human.js +153 -0
  266. package/dist/request-context-human.js.map +1 -0
  267. package/dist/request-context-inputs.d.ts +21 -0
  268. package/dist/request-context-inputs.js +63 -0
  269. package/dist/request-context-inputs.js.map +1 -0
  270. package/dist/request-context-installation.d.ts +117 -0
  271. package/dist/request-context-installation.js +328 -0
  272. package/dist/request-context-installation.js.map +1 -0
  273. package/dist/request-context-knowledge.d.ts +5 -0
  274. package/dist/request-context-knowledge.js +32 -0
  275. package/dist/request-context-knowledge.js.map +1 -0
  276. package/dist/request-context-native-human.d.ts +20 -0
  277. package/dist/request-context-native-human.js +91 -0
  278. package/dist/request-context-native-human.js.map +1 -0
  279. package/dist/request-context-native-output.d.ts +15 -0
  280. package/dist/request-context-native-output.js +46 -0
  281. package/dist/request-context-native-output.js.map +1 -0
  282. package/dist/request-context-native-result.d.ts +15 -0
  283. package/dist/request-context-native-result.js +46 -0
  284. package/dist/request-context-native-result.js.map +1 -0
  285. package/dist/request-context-off.d.ts +22 -0
  286. package/dist/request-context-off.js +77 -0
  287. package/dist/request-context-off.js.map +1 -0
  288. package/dist/request-context-outside-label.d.ts +5 -0
  289. package/dist/request-context-outside-label.js +28 -0
  290. package/dist/request-context-outside-label.js.map +1 -0
  291. package/dist/request-context-pane.d.ts +8 -0
  292. package/dist/request-context-pane.js +19 -0
  293. package/dist/request-context-pane.js.map +1 -1
  294. package/dist/request-context-pending-work.d.ts +11 -0
  295. package/dist/request-context-pending-work.js +43 -0
  296. package/dist/request-context-pending-work.js.map +1 -0
  297. package/dist/request-context-policy.d.ts +17 -1
  298. package/dist/request-context-policy.js +84 -6
  299. package/dist/request-context-policy.js.map +1 -1
  300. package/dist/request-context-readiness.d.ts +49 -0
  301. package/dist/request-context-readiness.js +64 -0
  302. package/dist/request-context-readiness.js.map +1 -0
  303. package/dist/request-context-recovery.d.ts +6 -2
  304. package/dist/request-context-recovery.js +25 -0
  305. package/dist/request-context-recovery.js.map +1 -1
  306. package/dist/request-context-relay.d.ts +2 -2
  307. package/dist/request-context-relay.js +10 -10
  308. package/dist/request-context-relay.js.map +1 -1
  309. package/dist/request-context-retirement.d.ts +19 -0
  310. package/dist/request-context-retirement.js +16 -0
  311. package/dist/request-context-retirement.js.map +1 -0
  312. package/dist/request-context-start.d.ts +15 -0
  313. package/dist/request-context-start.js +2 -0
  314. package/dist/request-context-start.js.map +1 -0
  315. package/dist/request-context-turns.d.ts +1 -1
  316. package/dist/request-context-turns.js +3 -2
  317. package/dist/request-context-turns.js.map +1 -1
  318. package/dist/request-context-unproved-label.d.ts +4 -0
  319. package/dist/request-context-unproved-label.js +25 -0
  320. package/dist/request-context-unproved-label.js.map +1 -0
  321. package/dist/request-context-update-guard.d.ts +15 -0
  322. package/dist/request-context-update-guard.js +54 -0
  323. package/dist/request-context-update-guard.js.map +1 -0
  324. package/dist/request-context-work.d.ts +50 -0
  325. package/dist/request-context-work.js +178 -0
  326. package/dist/request-context-work.js.map +1 -0
  327. package/dist/request-hub-context.d.ts +1 -0
  328. package/dist/request-hub-output.d.ts +2 -0
  329. package/dist/request-hub-output.js +12 -0
  330. package/dist/request-hub-output.js.map +1 -1
  331. package/dist/retained-human-control.d.ts +11 -0
  332. package/dist/retained-human-control.js +11 -0
  333. package/dist/retained-human-control.js.map +1 -0
  334. package/dist/runtime-build-info.js +1 -1
  335. package/dist/runtime-build-info.js.map +1 -1
  336. package/dist/runtime-cli.js +1 -1
  337. package/dist/runtime-cli.js.map +1 -1
  338. package/dist/runtime-client-store.js +7 -1
  339. package/dist/runtime-client-store.js.map +1 -1
  340. package/dist/runtime-client.js +15 -3
  341. package/dist/runtime-client.js.map +1 -1
  342. package/dist/runtime-coordinator.d.ts +23 -0
  343. package/dist/runtime-coordinator.js +103 -4
  344. package/dist/runtime-coordinator.js.map +1 -1
  345. package/dist/runtime-pane-mcp.d.ts +9 -0
  346. package/dist/runtime-pane-mcp.js +22 -2
  347. package/dist/runtime-pane-mcp.js.map +1 -1
  348. package/dist/runtime-protocol.d.ts +2 -0
  349. package/dist/runtime-protocol.js.map +1 -1
  350. package/dist/runtime-update-controller.js +1 -1
  351. package/dist/runtime-update-controller.js.map +1 -1
  352. package/dist/runtime-windows-bridge.d.ts +8 -0
  353. package/dist/runtime-windows-bridge.js +50 -3
  354. package/dist/runtime-windows-bridge.js.map +1 -1
  355. package/dist/scheduler/scheduler.d.ts +9 -0
  356. package/dist/scheduler/scheduler.js +26 -0
  357. package/dist/scheduler/scheduler.js.map +1 -1
  358. package/dist/scheduler/scheduler.test.js +17 -0
  359. package/dist/scheduler/scheduler.test.js.map +1 -1
  360. package/dist/service-install-handover.d.ts +52 -0
  361. package/dist/service-install-handover.js +50 -0
  362. package/dist/service-install-handover.js.map +1 -0
  363. package/dist/service-installer.d.ts +12 -0
  364. package/dist/service-installer.js +24 -10
  365. package/dist/service-installer.js.map +1 -1
  366. package/dist/settings-api.d.ts +2 -0
  367. package/dist/settings-api.js +76 -0
  368. package/dist/settings-api.js.map +1 -1
  369. package/dist/settings-baseline.d.ts +1 -0
  370. package/dist/settings-baseline.js +5 -4
  371. package/dist/settings-baseline.js.map +1 -1
  372. package/dist/settings-change.js +13 -0
  373. package/dist/settings-change.js.map +1 -1
  374. package/dist/settings-confirmation.d.ts +2 -0
  375. package/dist/settings-confirmation.js +6 -0
  376. package/dist/settings-confirmation.js.map +1 -1
  377. package/dist/settings-effect.d.ts +2 -0
  378. package/dist/settings-effect.js +55 -2
  379. package/dist/settings-effect.js.map +1 -1
  380. package/dist/settings-http-confirmation.d.ts +3 -0
  381. package/dist/settings-http-confirmation.js +29 -0
  382. package/dist/settings-http-confirmation.js.map +1 -1
  383. package/dist/settings-route-lifetime.d.ts +3 -1
  384. package/dist/settings-route-lifetime.js +15 -5
  385. package/dist/settings-route-lifetime.js.map +1 -1
  386. package/dist/settings-transaction.d.ts +3 -2
  387. package/dist/settings-transaction.js.map +1 -1
  388. package/dist/tips.js +1 -1
  389. package/dist/tips.js.map +1 -1
  390. package/dist/tool-permissions.js +3 -3
  391. package/dist/tool-permissions.js.map +1 -1
  392. package/dist/tool-receipt-output.d.ts +6 -6
  393. package/dist/turn-reply-guard.d.ts +16 -1
  394. package/dist/turn-reply-guard.js +20 -2
  395. package/dist/turn-reply-guard.js.map +1 -1
  396. package/dist/ui/app.html +2 -2
  397. package/dist/ui/contact-auth-strings.js +13 -8
  398. package/dist/ui/contact-authorizations.js +19 -1
  399. package/dist/ui/contact-grant-editor.js +71 -11
  400. package/dist/ui/contact-needs.js +27 -8
  401. package/dist/ui/contact-permissions.js +34 -9
  402. package/dist/ui/contact-tool-groups.js +1 -1
  403. package/dist/ui/fleet-office-pack.d.ts +2 -2
  404. package/dist/ui/fleet-office-pack.js +25 -8
  405. package/dist/ui/fleet-office-vehicles.js +28 -11
  406. package/dist/ui/fleet-office-zones.js +2 -2
  407. package/dist/ui/fleet-office.js +25 -5
  408. package/dist/ui/hub-admin-rooms-strings.js +6 -2
  409. package/dist/ui/hub-admin-rooms.js +3 -1
  410. package/dist/ui/hub-client.js +3 -0
  411. package/dist/ui/hub-group-search.js +2 -2
  412. package/dist/ui/hub-notify-keep.js +49 -0
  413. package/dist/ui/hub-role-view.js +1 -1
  414. package/dist/ui/hub-roles-strings.js +14 -10
  415. package/dist/ui/hub-roles.js +1 -1
  416. package/dist/ui/hub-room-members.js +4 -2
  417. package/dist/ui/hub-room-notify.js +2 -1
  418. package/dist/ui/hub-room-settings-strings.js +8 -0
  419. package/dist/ui/hub-room-settings.js +32 -0
  420. package/dist/ui/hub-room-strings.js +3 -3
  421. package/dist/ui/hub-room-thread.js +16 -5
  422. package/dist/ui/icons/hub-apple-touch-icon.png +0 -0
  423. package/dist/ui/icons/hub-favicon.ico +0 -0
  424. package/dist/ui/icons/hub-favicon.svg +10 -0
  425. package/dist/ui/icons/hub-icon-192.png +0 -0
  426. package/dist/ui/icons/hub-icon-512.png +0 -0
  427. package/dist/ui/icons/hub-icon-maskable-192.png +0 -0
  428. package/dist/ui/icons/hub-icon-maskable-512.png +0 -0
  429. package/dist/ui/icons/hub-maskable.svg +12 -0
  430. package/dist/ui/panel-hub.js +17 -5
  431. package/dist/ui/panel-needs.js +15 -6
  432. package/dist/ui/panel-settings.js +2 -1
  433. package/dist/ui/request-contact-card.js +287 -0
  434. package/dist/ui/request-contact-client.js +83 -0
  435. package/dist/ui/request-contact-page.js +78 -0
  436. package/dist/ui/request-context-control.js +171 -0
  437. package/dist/ui/settings-registry.js +2 -0
  438. package/dist/ui/settings-update.js +15 -1
  439. package/dist/ui/shared/app-install.js +123 -0
  440. package/dist/ui/shared/app-shell.js +17 -5
  441. package/dist/ui/shared/app-stream.js +1 -0
  442. package/dist/ui/shared/app-update.js +17 -2
  443. package/dist/ui/shared/app.css +136 -8
  444. package/dist/ui/shared/app.js +19 -2
  445. package/dist/ui/shared/hub-chat.css +6 -0
  446. package/dist/ui/shared/ui-confirm.js +4 -3
  447. package/dist/ui/shared/ui-icons.js +2 -0
  448. package/dist/ui/shared/ui-states.js +6 -0
  449. package/dist/ui/shared/update-card-ui.js +586 -0
  450. package/dist/ui/shared/view-strings.js +18 -0
  451. package/dist/ui/shared/web-authorize.js +1 -1
  452. package/dist/update-abandon.d.ts +26 -0
  453. package/dist/update-abandon.js +111 -0
  454. package/dist/update-abandon.js.map +1 -0
  455. package/dist/update-card.d.ts +1 -1
  456. package/dist/update-card.js +7 -7
  457. package/dist/update-card.js.map +1 -1
  458. package/dist/update-fix.d.ts +66 -0
  459. package/dist/update-fix.js +67 -0
  460. package/dist/update-fix.js.map +1 -0
  461. package/dist/update-forward.d.ts +5 -19
  462. package/dist/update-forward.js +19 -75
  463. package/dist/update-forward.js.map +1 -1
  464. package/dist/update-goback.d.ts +90 -0
  465. package/dist/update-goback.js +270 -0
  466. package/dist/update-goback.js.map +1 -0
  467. package/dist/update-journal.d.ts +8 -0
  468. package/dist/update-journal.js +8 -2
  469. package/dist/update-journal.js.map +1 -1
  470. package/dist/update-package-restore.d.ts +11 -2
  471. package/dist/update-package-restore.js +16 -5
  472. package/dist/update-package-restore.js.map +1 -1
  473. package/dist/update-quiescence.d.ts +38 -9
  474. package/dist/update-quiescence.js +50 -10
  475. package/dist/update-quiescence.js.map +1 -1
  476. package/dist/update-readiness.d.ts +2 -0
  477. package/dist/update-readiness.js +5 -1
  478. package/dist/update-readiness.js.map +1 -1
  479. package/dist/update-recovery/recover.js +10 -0
  480. package/dist/update-recovery/recover.js.map +1 -1
  481. package/dist/update-recovery/runner.d.ts +4 -0
  482. package/dist/update-recovery/runner.js +38 -5
  483. package/dist/update-recovery/runner.js.map +1 -1
  484. package/dist/update-restore.d.ts +7 -1
  485. package/dist/update-restore.js +10 -5
  486. package/dist/update-restore.js.map +1 -1
  487. package/dist/update-retained.d.ts +28 -1
  488. package/dist/update-retained.js +28 -3
  489. package/dist/update-retained.js.map +1 -1
  490. package/dist/update-settings.d.ts +27 -0
  491. package/dist/update-settings.js +40 -0
  492. package/dist/update-settings.js.map +1 -1
  493. package/dist/update-snapshot-scope.js +2 -0
  494. package/dist/update-snapshot-scope.js.map +1 -1
  495. package/dist/usage/i18n-keys.d.ts +1 -1
  496. package/dist/usage/i18n-keys.js +9 -0
  497. package/dist/usage/i18n-keys.js.map +1 -1
  498. package/dist/usage/providers.d.ts +3 -11
  499. package/dist/usage/providers.js +93 -131
  500. package/dist/usage/providers.js.map +1 -1
  501. package/dist/web-api.d.ts +4 -0
  502. package/dist/web-api.js +50 -7
  503. package/dist/web-api.js.map +1 -1
  504. package/dist/web-chat-history.d.ts +2 -0
  505. package/dist/web-chat-history.js.map +1 -1
  506. package/dist/web-icons.d.ts +20 -3
  507. package/dist/web-icons.js +76 -7
  508. package/dist/web-icons.js.map +1 -1
  509. package/dist/web-mentions.d.ts +27 -8
  510. package/dist/web-mentions.js +108 -1
  511. package/dist/web-mentions.js.map +1 -1
  512. package/dist/web-office-acts.js +3 -0
  513. package/dist/web-office-acts.js.map +1 -1
  514. package/dist/web-update.d.ts +9 -0
  515. package/dist/windows-agents.d.ts +24 -2
  516. package/dist/windows-agents.js +110 -4
  517. package/dist/windows-agents.js.map +1 -1
  518. package/dist/windows-cli-worker.js +9 -1
  519. package/dist/windows-cli-worker.js.map +1 -1
  520. package/dist/windows-cli.d.ts +15 -0
  521. package/dist/windows-cli.js +54 -6
  522. package/dist/windows-cli.js.map +1 -1
  523. package/package.json +2 -2
@@ -1,6 +1,30 @@
1
+ import { createRequire } from "node:module";
2
+ import { RequestContextController } from "./request-context-controller.js";
3
+ import { captureRequestContextEnableOffer } from "./request-context-enable-offer.js";
4
+ import { acquireRequestContextActivationLease, requestContextUpdateSettled } from "./request-context-update-guard.js";
5
+ import { installPrefixOf } from "./home-update-lock.js";
6
+ import { requestContextEnabledNotice } from "./request-context-control-copy.js";
7
+ import { createRequestContextExecOwner } from "./request-context-exec-owner.js";
8
+ import { makeRequestContextRelay } from "./request-context-relay.js";
9
+ import { rotateHubAgentIncarnation, forgetHubAgentIncarnation, requestWorkRegistrationEvidence } from "./hub-agent-incarnation-record.js";
10
+ import { projectRequestContextNativeOutput } from "./request-context-native-output.js";
11
+ import { validateNativeExecInputProof } from "./native-exec-input.js";
12
+ import { admitRequestContextNativeResult } from "./request-context-native-result.js";
13
+ import { RequestContextLocalTurns } from "./request-context-turns.js";
14
+ import { RequestHubInputResolver } from "./request-context-hub-resolver.js";
15
+ import { makeRequestDeliveryInputResolver } from "./request-context-delivery-resolver.js";
16
+ import { makeRequestHumanInputResolver, requestHumanReplyTarget } from "./request-context-human-resolver.js";
17
+ import { markRetainedHumanControl, retainedHumanControl } from "./retained-human-control.js";
18
+ import { requestContextDigest } from "./request-context-store.js";
19
+ import { RequestContextBoot, readRequestContextBootState } from "./request-context-boot.js";
20
+ import { RequestContextPreparedWork } from "./request-context-work.js";
21
+ import { requestContextSkillText, requestContextSteeringText } from "./request-context-knowledge.js";
22
+ import { requestDeliveryContinuation } from "./request-context-continuation.js";
23
+ import { runWithRequestContextAdmission } from "./request-context-admission.js";
24
+ import { RequestContextPendingWork } from "./request-context-pending-work.js";
1
25
  import { requestDeliveryView, requestContextDisplayView } from "./request-context-view.js";
2
26
  import { captureRequestHubOutput } from "./request-hub-output.js";
3
- import { assertRequestContextOperation, requireRequestContextPolicy, RequestContextPolicyError } from "./request-context-policy.js";
27
+ import { assertRequestContextOperation, assertRequestHubContactImage, requireRequestContextPolicy, requestContextInstructionMode, requestContextPolicyInstalled, requestContextInstalledMode, RequestContextPolicyError } from "./request-context-policy.js";
4
28
  import { permitWebContinuation } from "./web-continuation.js";
5
29
  import { nativeContactCardText, nativeContactOutcome, nativeContactPrincipal, nativeDecisionFailure } from "./request-contact-native.js";
6
30
  import { RequestContextReferenceMap } from "./request-context-fence.js";
@@ -26,7 +50,7 @@ import { changeIdleClaudeCredential } from "./claude-credential-change.js";
26
50
  import { readClaudeCredentialSelection, claudeSubscriptionSuppressed } from "./claude-credential-launch.js";
27
51
  import { ClaudeCredentialVault, ClaudeCredentialError } from "./claude-credential-vault.js";
28
52
  import { withHubRoomReplyWarning } from "./hub-room-reply-warning.js";
29
- import { ContactAuthService } from "./contact-auth-service.js";
53
+ import { ContactAuthService, ContactHeldError } from "./contact-auth-service.js";
30
54
  import { stageContactFiles } from "./contact-auth-files.js";
31
55
  import { ContactOriginClearSchema, ContactPermissionsSchema, sameContactPerson } from "./contact-auth-policy.js";
32
56
  import { CLASSIC_RESTRICTED_TOOLS } from "./contact-auth-types.js";
@@ -41,7 +65,7 @@ import { GENERAL_ROLE_INSTRUCTIONS } from "./general-role.js";
41
65
  import { placeGeneralRole } from "./general-role-block.js";
42
66
  import { NativePaneRecoveryError } from "./native-pane-recovery.js";
43
67
  import { nativePaneToolAvailable, nativePaneToolRefusal } from "./native-pane-tools.js";
44
- import { windowsAgentsFor } from "./windows-agents.js";
68
+ import { WindowsAgents, windowsAgentsFor } from "./windows-agents.js";
45
69
  import { AgentRuntimeChanges } from "./agent-runtime-change.js";
46
70
  import { SubagentService } from "./subagent-service.js";
47
71
  import { QuotaNotices } from "./usage/quota-notices.js";
@@ -57,7 +81,7 @@ import { loginNoticeMode, normalizeNoticeDelivery, setNoticeMode } from "./notic
57
81
  import { DEFAULT_REPLY_TRIGGERS } from "./reply-triggers.js";
58
82
  import { WorkingRecoveryCoordinator, WORKING_RECOVERY_KIND, buildWorkingRecoveryPrompt } from "./working-recovery.js";
59
83
  import { PUBLIC_TUNNEL_TOKEN_ENV, PUBLIC_TUNNEL_TOKEN_HINT, normalizePublicTunnelToken } from "./public-tunnel-config.js";
60
- import { humanOwnerObjectId, webHumanOrigin, isWebSessionIdentity } from "./human-delivery-receipts.js";
84
+ import { humanOwnerObjectId, admittedHumanWebIngress, admittedNativeHumanIngress, webHumanOrigin, isWebSessionIdentity } from "./human-delivery-receipts.js";
61
85
  import { SettingsBaselines } from "./settings-baseline.js";
62
86
  import { hubPilotTrustSettings } from "./hub-pilot-trust-settings.js";
63
87
  import { hubMembershipSettings } from "./hub-membership-settings.js";
@@ -257,7 +281,7 @@ export function applyTaskListCap(tasks, filterAssignee, filterStatus) {
257
281
  return tasks;
258
282
  }
259
283
  import { handleWebRequest, webPeerOf, broadcastSseEvent, broadcastToGuests, SSE_HEARTBEAT_MS } from "./web-api.js";
260
- import { windowsCliEnabled, closeWindowsBridge, inventoryProbed, LOCAL_WINDOWS_CLI_OFF } from "./windows-cli.js";
284
+ import { windowsCliEnabled, closeWindowsBridge, retireWindowsBridgeForRequestContext, windowsBridgeRequestContextIdle, inventoryProbed, LOCAL_WINDOWS_CLI_OFF } from "./windows-cli.js";
261
285
  import { nativeCliVersionState } from "./runtime-pane-native.js";
262
286
  import { localWindowsCliEnabled, remoteRuntimeEnabled, setConfiguredRuntimeSwitches, maxAgentsPerMachine } from "./runtime-switches.js";
263
287
  import { RuntimeInstallService } from "./runtime-install.js";
@@ -271,7 +295,7 @@ import { NativeMcpSessions } from "./native-mcp.js";
271
295
  import { nativeProviderMcpSupported } from "./windows-cli-providers.js";
272
296
  import { cachedNativeModelCatalog, refreshNativeModelCatalogAfterSignIn } from "./native-model-catalog.js";
273
297
  import { shapeWebModelCatalog } from "./web-model-groups.js";
274
- import { isWindowsInstance, isNativePaneInstance, isNativeExecInstance, WINDOWS_CONFIG_REFUSED, nativeCredentialProfile } from "./native-instance-registry.js";
298
+ import { isWindowsInstance, isNativePaneInstance, isNativeExecInstance, WINDOWS_CONFIG_REFUSED, nativeCredentialProfile, nativeAgentId } from "./native-instance-registry.js";
275
299
  import { createNativeWindowsInstance, updateNativeWindowsInstance } from "./native-instance-api.js";
276
300
  import { NativeInstanceConfigEdit, parseNativeInstanceCreate } from "./native-instance-input.js";
277
301
  import { LogService, thinkingOn } from "./log-service.js";
@@ -280,7 +304,7 @@ import { WebChatHistory, WEB_CHAT_TEXT_MAX, isWebMessageId, newWebMessageId, web
280
304
  import { WEB_ECHO_COPIES_MAX, WEB_MIRROR_TIMEOUT_MS, webReactionEmoji, webReactionProblem } from "./web-reactions.js";
281
305
  import { WebChatDiskStore, isSafeInstanceDirName } from "./web-chat-store.js";
282
306
  import { WebChatArchive } from "./web-chat-archive.js";
283
- import { SeenUsers, resolveMentions } from "./web-mentions.js";
307
+ import { SEEN_USERS_FILE, SeenUsers, resolveMentions } from "./web-mentions.js";
284
308
  import { OPERATOR, WebPrefsStore } from "./web-prefs.js";
285
309
  import { agendVersion } from "./agent-whats-new.js";
286
310
  import { OwnerCssStore } from "./web-owner-css-store.js";
@@ -325,13 +349,14 @@ import { crossInstanceVisibility, runVisibilityCommand, xmsgVisibility } from ".
325
349
  import { SEARCH_RETENTION_DAYS, SearchIndex } from "./search/search-index.js";
326
350
  import { chatDoc, taskDoc, xmsgDoc } from "./search/search-docs.js";
327
351
  import { WebSettingsTools } from "./web-settings-tools.js";
328
- import { GUEST_COMMAND_RUNS, GUEST_PREF_WRITES, GUEST_SEARCHES, bindGuestRequest, guestRouteDecision } from "./web-guest-access.js";
352
+ import { GUEST_COMMAND_RUNS, GUEST_PREF_WRITES, GUEST_SEARCHES, bindGuestRequest, guestSeesMessage, guestRouteDecision } from "./web-guest-access.js";
329
353
  import { GUEST_ROOM_TICK_MS, GuestRoomMembership, guestGroupRooms } from "./web-guest-rooms.js";
330
354
  import { Delegations, TrafficLog, trafficItem } from "./fleet-traffic.js";
331
- import { turnSource } from "./update-quiescence.js";
355
+ import { QuiescenceBarrier, stripHumanReceipt, UPDATE_HANDBACK_COPY_KIND, UPDATE_HANDBACK_SOURCE, handbackDue, turnSource } from "./update-quiescence.js";
356
+ import { readCurrent as readUpdateJournal } from "./update-journal.js";
332
357
  import { installedChannel, updateNoticeKey } from "./update-check.js";
333
358
  import { idleClaimOutcome, idleUpdateMessageId, UpdateOfferCard, updateAnswerLabel, updateOfferReply } from "./update-card.js";
334
- import { preflightAllows } from "./update-readiness.js";
359
+ import { preflightAllows, preflightBlocking, preflightRefusal, preflightWords } from "./update-readiness.js";
335
360
  import { inUpdatePause, resolveUpdates } from "./update-settings.js";
336
361
  import { resolveInstalledAgend, npmForRunningInstall } from "./update-dispatch.js";
337
362
  import { HUB_UPDATE_NOTICE_FILE, HUB_UPDATE_REMIND_MS, hubNoticeDue, hubNoticeKey, readHubNoticeState, writeHubNoticeState } from "./hub-update-notice.js";
@@ -376,7 +401,7 @@ import { readBackgroundWorkEndedMarker } from "./background-work-ended.js";
376
401
  import { DEFAULT_WARM_OVERFLOW, WakeCoordinator } from "./wake-coordinator.js";
377
402
  import { TargetQueueWorker } from "./target-queue-worker.js";
378
403
  import { resolveDeliveryWorkerMode } from "./types.js";
379
- import { isFleetStartCommandLine, readProcessCommandLine, releaseProcessFleetLock } from "./fleet-lock.js";
404
+ import { isFleetStartCommandLine, readProcessCommandLine, captureProcessFleetLease, releaseProcessFleetLock } from "./fleet-lock.js";
380
405
  import { isSetupComplete, markSetupComplete } from "./setup-marker.js";
381
406
  import { reapLeftoverTunnels } from "./tunnel/lease.js";
382
407
  import { buildToolPermissionsNotice } from "./tool-permissions-notice.js";
@@ -406,7 +431,7 @@ import { DeviceLoginRequests } from "./web-device-login.js";
406
431
  import { findSigninKnownEntry, addSigninKnownDevice } from "./web-signin-device.js";
407
432
  import { adminKey, HOST_ADMIN_KEY, isOutsideLinkOwner, OUTSIDE_LINK_OWNER, OUTSIDE_LINK_RETRY_MS, OUTSIDE_OWN_CLOSES, outsideDuration, outsideTimer, TOTP_SIGNIN_OVER_PUBLIC_LINK, TOTP_STEP_SECONDS, WEB_REMOTE_ACCESS_FILE, WebRemoteAccess } from "./web-remote-access.js";
408
433
  import { evaluateSettingsRole } from "./authority/settings-role.js";
409
- import { authorityNow, classifyWebPeer, evaluateGuestIdentity, evaluateWebAuthority, HOST_OPERATOR, VERIFIED_SESSION_HOURS, webAuthorityPolicy } from "./authority/web-authority.js";
434
+ import { authorityNow, classifyWebPeer, evaluateGuestIdentity, evaluateWebAuthority, HOST_OPERATOR, hostSessionHere, VERIFIED_SESSION_HOURS, webAuthorityPolicy } from "./authority/web-authority.js";
410
435
  import { AuthorityStateStore, namedLinkLastTurnedOff } from "./authority/authority-state.js";
411
436
  import { SessionAuthorizations } from "./authority/session-authorizations.js";
412
437
  import { SessionAuthorizationRequests } from "./web-session-authorization.js";
@@ -647,6 +672,9 @@ function callbackPrefix(callbackData) {
647
672
  const colon = callbackData.indexOf(":");
648
673
  return colon === -1 ? "(none)" : callbackData.slice(0, colon + 1);
649
674
  }
675
+ // Exact server-admitted payload objects only; metadata never chooses an exec input key.
676
+ const nativeHumanInputs = new WeakMap();
677
+ const requestPayloadContinuations = new WeakMap();
650
678
  const CLASSIC_BACKEND_SELECTION_TIMEOUT_MS = 60_000;
651
679
  const CLASSIC_BACKEND_CALLBACK_PREFIX = "classic-backend:";
652
680
  const CLASSIC_MODE_CALLBACK_PREFIX = "classic-mode:";
@@ -677,6 +705,28 @@ const UPDATE_CARD_CALLBACK_PREFIX = "update-card:";
677
705
  const UPDATE_CHAT_CARD_FILE = "update-chat-card.json";
678
706
  /** The chat card's buttons live a week (Not now's own length); a newer card replaces them sooner. */
679
707
  const UPDATE_CHAT_CARD_MS = 7 * 24 * 60 * 60_000;
708
+ /**
709
+ * M-3864 R2: the chat card's Tonight: 22:00 in the fleet's zone (`defaults.scheduler.default_timezone`, else the machine's),
710
+ * the next one when today's is under 30 min away. Before, 22:00 on the machine's clock: on a UTC server for a Taipei fleet
711
+ * that was 06:00 the next morning.
712
+ */
713
+ export function updateTonightAt(now, tz) {
714
+ let day;
715
+ try {
716
+ day = new Date(now).toLocaleString("sv-SE", { timeZone: tz, hour12: false }).slice(0, 10);
717
+ }
718
+ catch {
719
+ tz = "UTC";
720
+ day = new Date(now).toISOString().slice(0, 10);
721
+ }
722
+ // Prism #4585: the zone's offset AT the candidate instant (twice, so it settles across a DST change that day), never
723
+ // the offset at the wall clock read as UTC, which can sit on the other side of the change.
724
+ const offsetAt = (ms) => Date.parse(new Date(ms).toLocaleString("sv-SE", { timeZone: tz, hour12: false }).replace(" ", "T") + "Z") - Math.floor(ms / 1000) * 1000;
725
+ const at = (date) => { const wall = Date.parse(`${date}T22:00:00Z`); const first = wall - offsetAt(wall); return wall - offsetAt(first); };
726
+ const today = at(day);
727
+ return today - now >= 30 * 60_000 ? today : at(new Date(Date.parse(`${day}T12:00:00Z`) + 86_400_000).toISOString().slice(0, 10));
728
+ }
729
+ const UPDATE_CHAT_CARD_ALL = ["when-idle", "tonight", "not-now"];
680
730
  const HUB_SHARING_CALLBACK_PREFIX = "hub-share:";
681
731
  /** M-3680: a held contact request's card in General ("contact-ticket:" + 32 hex + ":approve" = 55 bytes, under Telegram's 64). */
682
732
  const CONTACT_TICKET_PREFIX = "contact-ticket:";
@@ -845,9 +895,729 @@ export class FleetManager {
845
895
  static sighupHandlerInstalled = false;
846
896
  /** Test seam: inject a spy to verify saveFleetConfig calls fsync. Default: fsyncSync. */
847
897
  fsyncForTest = undefined;
898
+ requestContextAdmission;
899
+ requestContextBoot;
900
+ requestContextModes;
901
+ requestContextControlBox;
902
+ requestContextDrainTimer;
903
+ requestContextAttentionSince;
904
+ requestContextCollectionTimer;
905
+ requestContextCutoverErrors = [];
906
+ requestContextRetirementProofs = new Map();
907
+ requestContextRootRetired = (_drain, root) => this.requestContextRetirementProofs.get(root)?.current() === true;
908
+ ownRequestContextModes(boot, drain, off, ports, current, retireRoot) {
909
+ const box = this.deliveryOutbox;
910
+ const modes = Object.freeze({ boot, drain, off, current, retireRoot, recordHuman: (...args) => { if (this.requestContextModes !== modes || !current() || !ports.serving)
911
+ throw Error("Request human owner unavailable"); return ports.serving.human(...args); },
912
+ publish: (ready) => {
913
+ const state = box.requestContextInstallation().read();
914
+ if (!state || !current() || !ready())
915
+ throw Error("Capable publication unavailable");
916
+ const fence = boot.publication.fence(), roots = state.mode === "draining" ? box.requestContextInstallation().drainRoots() : null;
917
+ if (!ready())
918
+ throw Error("Capable readiness changed");
919
+ boot.publication.publish(state, ports, fence, current, () => box.requestContextInstallation().read(), current, root => roots?.has(root) === true);
920
+ return state;
921
+ } });
922
+ this.requestContextModes = modes;
923
+ this.requestContextHumanAdmission = (...args) => modes.recordHuman(...args);
924
+ if (!this.requestContextCollectionTimer) {
925
+ this.requestContextCollectionTimer = setInterval(() => this.collectRequestContextRoots(), 60_000);
926
+ this.requestContextCollectionTimer.unref?.();
927
+ }
928
+ return modes;
929
+ }
930
+ requestContextFirstOn;
931
+ prepareRequestContextOwnerRegistration;
932
+ requestContextOwnerStarted;
933
+ requestContextRetainedFactory;
934
+ requestContextFactoryOwner;
935
+ prepareRequestContextStart;
936
+ configureRequestContextBeforeStart;
937
+ /** First-On owner attachment, not activation. Called only by the confirmed Settings controller.
938
+ * A failed attempt reuses this process-owned admission port; it never leaves a false capable boot installed.
939
+ */
940
+ prepareRequestContextFirstOn() {
941
+ const box = this.deliveryOutbox, lease = captureProcessFleetLease(this.dataDir), manager = this.managerBootId;
942
+ if (!box || !this.fleetConfig || !lease?.current() || this.requestContextBoot || this.requestContextPolicy || box.requestContextInstallation().read() !== null)
943
+ throw Error("First activation preparation unavailable");
944
+ const preparation = this.requestContextFirstOn ?? { boot: RequestContextBoot.prepareFirstOn(randomUUID(), lease) };
945
+ const boot = preparation.boot;
946
+ if (!boot.owner.current() || this.requestContextAdmission && this.requestContextAdmission !== boot.publication.admission)
947
+ throw Error("First activation owner changed");
948
+ this.requestContextFirstOn = preparation;
949
+ this.attachRequestContextAdmission(boot.publication.admission);
950
+ const fence = boot.publication.fence(), attempt = {};
951
+ preparation.attempt = attempt;
952
+ let adopted = false;
953
+ this.requestContextBoot = boot;
954
+ this.requestContextPolicy = boot.policy;
955
+ const current = () => !this.shuttingDown && this.managerBootId === manager && lease.current() && boot.owner.current()
956
+ && this.deliveryOutbox === box && this.requestContextBoot === boot && this.requestContextPolicy === boot.policy && (adopted || this.requestContextFirstOn === preparation && preparation.attempt === attempt);
957
+ return Object.freeze({ boot, fence, current,
958
+ /** The actual activation transaction already committed; only then publish capable policy ownership. */
959
+ adoptCommitted: (epoch) => {
960
+ const state = box.requestContextInstallation().read();
961
+ if (!current() || !fence.owned() || !state || state.owner !== boot.owner.owner || state.epoch !== epoch || state.mode !== "active")
962
+ throw Error("Activation commit owner changed");
963
+ adopted = true;
964
+ this.requestContextPolicy = boot.policy;
965
+ this.requestContextFirstOn = undefined;
966
+ return state;
967
+ },
968
+ /** Physical candidates/ports and the staged connection must be undone first by their owning orchestration. */
969
+ abandon: () => {
970
+ if (!current() || this.requestContextNativeGraph || box.requestContextInstallation().read() !== null)
971
+ throw Error("Activation preparation cannot revert");
972
+ this.requestContextBoot = undefined;
973
+ this.requestContextPolicy = undefined;
974
+ try {
975
+ boot.publication.abandon(fence, () => box.requestContextInstallation().read());
976
+ preparation.attempt = undefined;
977
+ }
978
+ catch (error) {
979
+ this.requestContextBoot = boot;
980
+ this.requestContextPolicy = boot.policy;
981
+ throw error;
982
+ }
983
+ }, });
984
+ }
985
+ /** Same-manager stop/start must reconstruct behind a new lease, never reuse an old published graph. */
986
+ async resetStoppedRequestContextAssembly() {
987
+ if (!this.requestContextBoot)
988
+ return;
989
+ if (this.daemons.size || this.instanceIpcClients.size || !this.requestContextPendingWork.empty)
990
+ throw Error("Request owners are still stopping");
991
+ const old = this.requestContextBoot, box = this.deliveryOutbox, factory = this.requestContextFactoryOwner;
992
+ await this.retireRequestContextNativeFactories(() => this.requestContextBoot === old && this.daemons.size === 0 && this.instanceIpcClients.size === 0);
993
+ const nativeRetired = () => this.requestContextBoot === old && !this.requestContextNativeGraph && !this.runtimeHub && !this.fleetWindowsRuntime && !this.nativeMcpStore && !this.paneManager && !this.localPaneRelay && !this.runtimeExecutor;
994
+ await factory?.disposeStopped(nativeRetired);
995
+ if (!nativeRetired())
996
+ throw Error("Native retirement changed");
997
+ if (this.requestContextCollectionTimer)
998
+ clearInterval(this.requestContextCollectionTimer);
999
+ this.requestContextCollectionTimer = undefined;
1000
+ if (this.requestContextDrainTimer)
1001
+ clearTimeout(this.requestContextDrainTimer);
1002
+ this.requestContextDrainTimer = undefined;
1003
+ box?.close();
1004
+ this.deliveryOutbox = null;
1005
+ this.deliveryOutboxRecovered = false;
1006
+ this.requestContextControl = undefined;
1007
+ this.requestContextControlBox = undefined;
1008
+ this.requestContextBoot = undefined;
1009
+ this.requestContextModes = undefined;
1010
+ this.requestContextFirstOn = undefined;
1011
+ this.requestContextFactoryOwner = undefined;
1012
+ this.requestContextPolicy = undefined;
1013
+ this.requestContextAdmission = undefined;
1014
+ this.requestContextHumanAdmission = undefined;
1015
+ this.requestContextHubAdmission = undefined;
1016
+ this.requestContextRelay = undefined;
1017
+ this.requestContactCardsPort = null;
1018
+ this.requestContactApi = undefined;
1019
+ this.prepareRequestContextStart = undefined;
1020
+ this.configureRequestContextBeforeStart = undefined;
1021
+ this.prepareRequestContextOwnerRegistration = undefined;
1022
+ this.requestContextOwnerStarted = undefined;
1023
+ this.requestContextRetireOwner = undefined;
1024
+ this.requestContextFleetCalls = new RequestContextReferenceMap(row => row.call.admission.coverage === "covered" ? row.call.admission.lease.snapshot.context.ref.rootContextId : null, row => `fleet-call:${row.call.id}`);
1025
+ this.requestContextRetirementProofs.clear();
1026
+ this.requestContextCutoverErrors = [];
1027
+ }
1028
+ /** Retry only a never-published, never-started construction; durable malformed state still refuses. */
1029
+ async resetRequestContextUnpublishedPreparation() {
1030
+ const boot = this.requestContextBoot;
1031
+ if (!boot?.publication.heldUnpublished() || this.daemons.size || this.instanceIpcClients.size || !this.requestContextPendingWork.empty)
1032
+ throw Error("Capable preparation is still owned");
1033
+ const factory = this.requestContextFactoryOwner;
1034
+ await this.retireRequestContextNativeFactories(() => this.requestContextBoot === boot && boot.publication.heldUnpublished());
1035
+ factory?.disposeUnstarted();
1036
+ this.requestContextFactoryOwner = undefined;
1037
+ this.requestContextRetireOwner = undefined;
1038
+ this.requestContextRetainedFactory = undefined;
1039
+ this.prepareRequestContextOwnerRegistration = undefined;
1040
+ this.configureRequestContextBeforeStart = undefined;
1041
+ this.prepareRequestContextStart = () => boot.requirePreparedOwner();
1042
+ this.requestContextOwnerStarted = undefined;
1043
+ if (this.requestContextFleetCalls.size)
1044
+ throw Error("Request calls are still owned");
1045
+ this.requestContextFleetCalls = new RequestContextReferenceMap(row => row.call.admission.coverage === "covered" ? row.call.admission.lease.snapshot.context.ref.rootContextId : null, row => `fleet-call:${row.call.id}`);
1046
+ }
1047
+ async prepareRequestContextCapableBoot(rootRetired) {
1048
+ const [{ RequestContextPaneProofs }, { RequestContextOffOwner }] = await Promise.all([import("./request-context-pane.js"), import("./request-context-off.js")]);
1049
+ const boot = this.requestContextBoot, box = this.deliveryOutbox, lease = captureProcessFleetLease(this.dataDir), manager = this.managerBootId;
1050
+ if (!boot || !box || !lease?.current() || !this.fleetConfig || !box.requestContextInstallation().read() || !boot.publication.heldUnpublished()
1051
+ || this.daemons.size || this.instanceIpcClients.size || this.requestContextNativeGraph)
1052
+ throw Error("Capable boot preparation unavailable");
1053
+ boot.publication.fence();
1054
+ const owned = () => !this.shuttingDown && lease.current() && this.managerBootId === manager && this.requestContextBoot === boot && this.deliveryOutbox === box;
1055
+ const drain = box.requestContextDrain(() => owned() ? boot.owner.owner : null), registration = drain.registration();
1056
+ this.setRequestContextDrainRegistration(registration);
1057
+ const policy = Object.freeze({ assert: (input) => boot.policy.assert(input), installedMode: () => boot.publication.installedMode(),
1058
+ instructionMode: () => boot.publication.installedMode() ?? (owned() && boot.publication.heldUnpublished() ? box.requestContextInstallation().read()?.mode ?? null : null) });
1059
+ const factory = this.installRequestContextRetainedOwners(policy, registration, owned);
1060
+ this.requestContextFactoryOwner = factory;
1061
+ this.stageRequestContextNativeGraph({ registration, panes: new RequestContextPaneProofs(randomBytes(32).toString("hex"), registration), execTurns: factory.execTurns, execOwner: factory.execOwner, execInput: factory.execInput, current: () => owned() && factory.current() });
1062
+ const inventory = await this.prepareRequestContextDrainOwners(drain, registration, factory, owned), current = () => owned() && factory.current() && inventory.current();
1063
+ const serving = this.prepareRequestContextServingOwners(current, root => rootRetired(drain, root), factory.hub, () => boot.publication.installedMode()), ports = { policy: serving.policy, serving };
1064
+ this.bindRequestContextServingPublication(boot);
1065
+ const off = new RequestContextOffOwner(box.requestContextInstallation(), drain, boot.publication, { owner: boot.owner.owner, current }, { ports, current });
1066
+ const modes = this.ownRequestContextModes(boot, drain, off, ports, current, root => serving.gate.retireRoot(root));
1067
+ return Object.freeze({ ...modes, factory });
1068
+ }
1069
+ /** Exact persistent roster for controlled On; exec owners and durable drain assessment are separate required participants. */
1070
+ async captureRequestContextOwnedLaunches() {
1071
+ const admission = this.requestContextAdmission, lease = captureProcessFleetLease(this.dataDir);
1072
+ if (!admission || admission.available() || !lease?.current())
1073
+ throw Error("Request-context owner preparation unavailable");
1074
+ const pending = this.requestContextPendingWork, revision = pending.revision, boot = this.managerBootId;
1075
+ const freeze = (value) => {
1076
+ if (value && typeof value === "object") {
1077
+ for (const child of Object.values(value))
1078
+ freeze(child);
1079
+ Object.freeze(value);
1080
+ }
1081
+ return value;
1082
+ };
1083
+ const roster = [...this.daemons.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([name, daemon]) => ({
1084
+ name, daemon, config: freeze(daemon.getConfigSnapshot()),
1085
+ }));
1086
+ const images = roster.map(row => requestContextDigest(row.config));
1087
+ const owned = () => admission === this.requestContextAdmission && !admission.available() && lease.current()
1088
+ && this.managerBootId === boot && !this.shuttingDown && pending.revision === revision
1089
+ && this.daemons.size === roster.length && roster.every((row, i) => this.daemons.get(row.name) === row.daemon
1090
+ && pending.count(row.name) === 0 && requestContextDigest(row.config) === images[i]
1091
+ && requestContextDigest(row.daemon.getConfigSnapshot()) === images[i]);
1092
+ const records = [];
1093
+ for (const row of roster) {
1094
+ const unavailable = () => Object.assign(Error("Request-context owner is not ready"), { code: "request-context-owner-not-ready", agent: row.name });
1095
+ if (!owned())
1096
+ throw unavailable();
1097
+ const idle = await row.daemon.captureRequestContextIdle();
1098
+ if (!owned() || !idle?.current())
1099
+ throw unavailable();
1100
+ const retirement = await row.daemon.captureRequestContextRetirement();
1101
+ if (!owned() || !idle.current() || retirement.daemonBootId !== idle.daemonBootId
1102
+ || retirement.spawnGeneration !== idle.spawnGeneration || retirement.launchFenceEpoch !== idle.launchFenceEpoch)
1103
+ throw unavailable();
1104
+ records.push(Object.freeze({ ...row, config: Object.freeze(row.config), idle, retirement }));
1105
+ }
1106
+ const current = () => { try {
1107
+ return owned() && records.every(row => row.idle.current());
1108
+ }
1109
+ catch {
1110
+ return false;
1111
+ } };
1112
+ if (!current())
1113
+ throw Error("Request-context owner preparation changed");
1114
+ return Object.freeze({ records: Object.freeze(records), current });
1115
+ }
1116
+ /** Passive capture first; only prepare() may reconstruct owned transports after native graph staging.
1117
+ * Required ids never shrink when retirement/disconnect removes a connection from the current roster.
1118
+ */
1119
+ captureRequestContextRuntimeSet() {
1120
+ const lease = captureProcessFleetLease(this.dataDir), manager = this.managerBootId, initialConfig = requestContextDigest(this.fleetConfig);
1121
+ if (!lease?.current() || !this.fleetConfig)
1122
+ throw Error("Runtime readiness owner unavailable");
1123
+ const required = new Set(), exec = new Set();
1124
+ let localPane = false, prepared = false;
1125
+ const names = [...new Set([...Object.keys(this.fleetConfig.instances), ...(this.classicChannels?.getAll() ?? []).map(row => row.instanceName)])];
1126
+ for (const name of names) {
1127
+ const cfg = this.hubAgentConfig(name);
1128
+ if (cfg?.runtime !== "windows")
1129
+ continue;
1130
+ if (cfg.machine_id) {
1131
+ required.add(cfg.machine_id);
1132
+ if (isNativeExecInstance(cfg))
1133
+ exec.add(cfg.machine_id);
1134
+ }
1135
+ else if (isNativePaneInstance(cfg))
1136
+ localPane = true;
1137
+ }
1138
+ const online = () => this.runtimeHub?.listMachines().filter(row => row.status === "online") ?? [];
1139
+ const include = () => { for (const row of online())
1140
+ required.add(row.id); if (this.localPaneRelay?.online())
1141
+ localPane = true; };
1142
+ include();
1143
+ const labels = new Map((this.runtimeHub?.listMachines() ?? []).map(row => [row.id, row.name || row.id]));
1144
+ const owned = () => lease.current() && !this.shuttingDown && this.managerBootId === manager && requestContextDigest(this.fleetConfig) === initialConfig;
1145
+ const snapshot = () => {
1146
+ if (!owned())
1147
+ throw Error("Runtime readiness owner changed");
1148
+ include();
1149
+ const peers = [...required].sort().map(id => this.runtimeHub?.requestContextReadiness(id) ?? { id, generation: "unavailable", connected: false, requestContextVersion: 0 });
1150
+ if (localPane)
1151
+ peers.push(this.localPaneRelay?.requestContextReadiness() ?? { id: "local", generation: "unavailable", connected: false, requestContextVersion: 0 });
1152
+ return { requiredPeers: [...required, ...(localPane ? ["local"] : [])].sort(), peers: peers.sort((a, b) => a.id.localeCompare(b.id)) };
1153
+ };
1154
+ const advertised = () => {
1155
+ include();
1156
+ return [...required].filter(id => {
1157
+ const machine = this.runtimeHub?.machine(id), caps = machine?.runtimeInfo?.capabilities ?? [];
1158
+ return !machine || machine.status !== "online" || machine.paneProtocol !== 1 || !caps.includes("request-context-call-v1") || exec.has(id) && !caps.includes("native-exec-input-v1");
1159
+ });
1160
+ };
1161
+ return Object.freeze({ snapshot, labels: () => [...required].map(id => ({ id, label: labels.get(id) ?? this.runtimeHub?.machine(id)?.name ?? id })), advertised,
1162
+ prepare: async () => {
1163
+ if (!owned() || !this.currentRequestContextNativeGraph())
1164
+ throw Error("Runtime graph is not prepared");
1165
+ if (required.size)
1166
+ this.runtimeCoordinator();
1167
+ if (localPane)
1168
+ await this.localNativePaneEndpoint();
1169
+ if (!owned())
1170
+ throw Error("Runtime readiness owner changed");
1171
+ prepared = true;
1172
+ },
1173
+ prove: () => {
1174
+ if (!prepared)
1175
+ throw Error("Runtime graph is not prepared");
1176
+ const first = snapshot(), sha = requestContextDigest(first);
1177
+ if (first.peers.some(row => !row.connected || row.requestContextVersion !== 1))
1178
+ throw Error("Runtime negotiation unavailable");
1179
+ const graph = this.currentRequestContextNativeGraph(), hub = this.runtimeHub, local = this.localPaneRelay;
1180
+ return Object.freeze({ current: () => { try {
1181
+ return owned() && this.currentRequestContextNativeGraph() === graph && this.runtimeHub === hub && this.localPaneRelay === local && requestContextDigest(snapshot()) === sha;
1182
+ }
1183
+ catch {
1184
+ return false;
1185
+ } } });
1186
+ },
1187
+ });
1188
+ }
1189
+ /** The confirmed first-On controller owns this complete preparation. No durable activation or input publication
1190
+ * happens here. Its readiness callbacks must come from the actual legacy drain and negotiated port inventories.
1191
+ */
1192
+ async prepareRequestContextFirstOnAssembly(durableDrained, transportsReady, rootRetired, offer, execution, reconstructTransports) {
1193
+ const [{ RequestContextPaneProofs }, { RequestContextOffOwner }, { captureRequestContextHelpers }] = await Promise.all([import("./request-context-pane.js"), import("./request-context-off.js"), import("./request-context-helper-readiness.js")]);
1194
+ execution?.assert();
1195
+ if (!offer.current())
1196
+ throw Error("stale");
1197
+ const first = this.prepareRequestContextFirstOn(), box = this.deliveryOutbox, boot = first.boot;
1198
+ let connection;
1199
+ try {
1200
+ connection = box.stageRequestContextConnection({ current: first.fence.owned });
1201
+ }
1202
+ catch (error) {
1203
+ first.abandon();
1204
+ throw error;
1205
+ }
1206
+ const drain = connection.drain(() => first.current() ? boot.owner.owner : null), registration = drain.registration();
1207
+ let factory;
1208
+ let inventory;
1209
+ let fleetRegistration;
1210
+ let relaunch;
1211
+ let committed = false, disposed = false;
1212
+ const owned = () => !disposed && first.current();
1213
+ // Rendering may be staged for a fenced replacement; policy execution still uses only the publication.
1214
+ const policy = Object.freeze({ assert: (input) => boot.policy.assert(input), installedMode: () => boot.publication.installedMode(),
1215
+ instructionMode: () => boot.publication.installedMode() ?? (owned() && first.fence.owned() ? "active" : null) });
1216
+ const undoNative = async () => {
1217
+ if (committed || box.requestContextInstallation().read() !== null)
1218
+ throw Error("Activated owners cannot revert");
1219
+ inventory?.dispose();
1220
+ inventory = undefined;
1221
+ await this.retireRequestContextNativeFactories(owned);
1222
+ await factory?.disposeStaged();
1223
+ if (this.requestContextFactoryOwner === factory)
1224
+ this.requestContextFactoryOwner = undefined;
1225
+ factory = undefined;
1226
+ fleetRegistration?.restore();
1227
+ fleetRegistration = undefined;
1228
+ };
1229
+ const abandon = () => { connection.restore(); first.abandon(); disposed = true; };
1230
+ try {
1231
+ relaunch = await this.prepareRequestContextPersistentRelaunch(policy, registration, first.fence, durableDrained, async () => {
1232
+ try {
1233
+ await this.retireRequestContextNativeFactories(owned);
1234
+ fleetRegistration = this.stageRequestContextFleetRegistration(registration, owned);
1235
+ factory = this.installRequestContextRetainedOwners(policy, registration, owned, [], { firstOnStage: { current: () => owned() && first.fence.owned() }, deferStartHooks: true });
1236
+ this.requestContextFactoryOwner = factory;
1237
+ this.stageRequestContextNativeGraph({ registration, panes: new RequestContextPaneProofs(randomBytes(32).toString("hex"), registration),
1238
+ execTurns: factory.execTurns, execOwner: factory.execOwner, execInput: factory.execInput, current: () => owned() && factory?.current() === true });
1239
+ inventory = await this.prepareRequestContextDrainOwners(drain, registration, factory, owned);
1240
+ await reconstructTransports?.();
1241
+ return undoNative;
1242
+ }
1243
+ catch (error) {
1244
+ await undoNative();
1245
+ throw error;
1246
+ }
1247
+ }, execution);
1248
+ execution?.assert();
1249
+ factory.adopt(relaunch.owners());
1250
+ // Do not start deliberately stopped agents. Prepare only their future owned start/exec closures.
1251
+ const names = [...new Set([...Object.keys(this.fleetConfig.instances), ...(this.classicChannels?.getAll() ?? []).map(room => room.instanceName)])].sort();
1252
+ const configurations = names.map(name => [name, this.hubAgentConfig(name)]), rosterImage = requestContextDigest(configurations);
1253
+ for (const [name, config] of configurations) {
1254
+ if (!config)
1255
+ throw Error("Request owner configuration unavailable");
1256
+ if (!this.daemons.has(name))
1257
+ await factory.beforeStart(name, config);
1258
+ execution?.assert();
1259
+ }
1260
+ const sameRoster = () => requestContextDigest(names.map(name => [name, this.hubAgentConfig(name)])) === rosterImage
1261
+ && requestContextDigest([...new Set([...Object.keys(this.fleetConfig?.instances ?? {}), ...(this.classicChannels?.getAll() ?? []).map(room => room.instanceName)])].sort()) === requestContextDigest(names);
1262
+ const baseReady = () => owned() && first.fence.current() && connection.current() && relaunch.ready() && factory.current() && inventory.current()
1263
+ && sameRoster() && durableDrained();
1264
+ const candidates = relaunch.owners(), readHelpers = () => captureRequestContextHelpers(candidates, name => this.daemons.get(name));
1265
+ let helpers = readHelpers(), peersReady = transportsReady();
1266
+ const helperDeadline = performance.now() + 30_000;
1267
+ while (!helpers.ready || !peersReady) {
1268
+ if (!baseReady() || !offer.current() || execution && !execution.current() || performance.now() >= helperDeadline)
1269
+ throw Object.assign(Error("Request-context owner or transport is not ready"), { code: helpers.ready ? "request-context-transport-not-ready" : "request-context-owner-not-ready", ...(helpers.unready[0] ? { agent: helpers.unready[0] } : {}) });
1270
+ // A timer only schedules another actual connection observation; elapsed time never proves readiness.
1271
+ await new Promise(resolve => setTimeout(resolve, 100));
1272
+ helpers = readHelpers();
1273
+ peersReady = transportsReady();
1274
+ }
1275
+ const processReady = () => baseReady() && helpers.current() && transportsReady();
1276
+ const ready = () => processReady() && offer.current() && (!execution || execution.current());
1277
+ if (!ready())
1278
+ throw Error("Request-context owner or transport is not ready");
1279
+ const portsCurrent = () => owned() && factory.current() && inventory.current();
1280
+ let serving;
1281
+ const off = new RequestContextOffOwner(box.requestContextInstallation(), drain, boot.publication, { owner: boot.owner.owner, current: owned }, {
1282
+ get ports() { if (!serving)
1283
+ throw Error("Serving preparation unavailable"); return { policy: serving.policy, serving }; }, current: () => committed && portsCurrent() && !!serving
1284
+ });
1285
+ return Object.freeze({ boot, drain, registration, policy, ready, off, offer,
1286
+ /** Call only inside the single installation.activate transaction. No publication or async work. */
1287
+ initialize: () => {
1288
+ if (!ready())
1289
+ throw Error("Activation preparation changed");
1290
+ const record = box.requestContextInstallation().activation();
1291
+ if (!record || requestContextDigest(record.invalidates) !== requestContextDigest(offer.invalidates) || record.offeredLatestDeadline !== offer.latestDeadline)
1292
+ throw Error("Activation offer differs from confirmation");
1293
+ relaunch.retain();
1294
+ factory.retain();
1295
+ serving = this.prepareRequestContextServingOwners(portsCurrent, root => rootRetired(drain, root), factory.hub, () => boot.publication.installedMode());
1296
+ },
1297
+ /** Synchronous post-COMMIT publication. Failure stays capable and fenced for recovery. */
1298
+ publish: () => {
1299
+ const state = box.requestContextInstallation().read();
1300
+ if (!state || state.mode !== "active" || !serving || !owned())
1301
+ throw Error("Activation publication unavailable");
1302
+ const publishReady = processReady();
1303
+ committed = true;
1304
+ first.adoptCommitted(state.epoch);
1305
+ relaunch.seal();
1306
+ factory.seal();
1307
+ relaunch.releaseStartHooks();
1308
+ factory.attach();
1309
+ this.ownRequestContextModes(boot, drain, off, { policy: serving.policy, serving }, portsCurrent, root => serving.gate.retireRoot(root));
1310
+ this.bindRequestContextServingPublication(boot);
1311
+ if (!publishReady)
1312
+ throw Error("Activation publication readiness changed");
1313
+ boot.publication.publish(state, { policy: serving.policy, serving }, first.fence, portsCurrent, () => box.requestContextInstallation().read(), portsCurrent);
1314
+ return state;
1315
+ },
1316
+ rollback: async () => { if (committed || box.requestContextInstallation().read() !== null)
1317
+ throw Error("Activated owners cannot revert"); await relaunch.rollback(); abandon(); },
1318
+ });
1319
+ }
1320
+ catch (error) {
1321
+ // Persistent preparation unwinds its own candidates. If it returned, retire them before native ownership.
1322
+ try {
1323
+ if (relaunch)
1324
+ await relaunch.rollback();
1325
+ else if (this.requestContextNativeGraph || factory || fleetRegistration)
1326
+ await undoNative();
1327
+ abandon();
1328
+ }
1329
+ catch (cleanup) {
1330
+ throw new AggregateError([error, cleanup], "Request-context preparation could not restore every owner; admission stays fenced");
1331
+ }
1332
+ throw error;
1333
+ }
1334
+ }
1335
+ /** First-On persistent replacements. This does not activate, publish, open admission or construct a native factory.
1336
+ * The installer separately stages native factories and checks every transport before its one activation COMMIT.
1337
+ */
1338
+ async prepareRequestContextPersistentRelaunch(policy, registration, fence, durableDrained, afterRetirement, execution) {
1339
+ const box = this.deliveryOutbox, admission = this.requestContextAdmission, lease = captureProcessFleetLease(this.dataDir), boot = this.managerBootId;
1340
+ if (!box || box.requestContextInstallation().read() !== null || !admission || admission.available() || !lease?.current() || !fence.current())
1341
+ throw Error("Request relaunch preparation unavailable");
1342
+ const inventory = await this.captureRequestContextOwnedLaunches();
1343
+ const rows = inventory.records.map(row => ({ ...row, spec: row.daemon.getRequestContextLaunchSpec(), incarnation: this.contactGeneration(row.name),
1344
+ target: requestContextDigest(this.hubAgentConfig(row.name)), stopped: false, published: false, candidate: null,
1345
+ startup: null,
1346
+ prepared: null }));
1347
+ const originalPrepare = this.prepareRequestContextStart, originalConfigure = this.configureRequestContextBeforeStart;
1348
+ let alive = true, committed = false, rollingBack = false, undoAfterRetirement;
1349
+ const processOwned = () => {
1350
+ try {
1351
+ return alive && !this.shuttingDown && this.managerBootId === boot && lease.current()
1352
+ && this.requestContextAdmission === admission && (committed || fence.owned() && !admission.available());
1353
+ }
1354
+ catch {
1355
+ return false;
1356
+ }
1357
+ };
1358
+ const configured = (row) => {
1359
+ try {
1360
+ return this.contactGeneration(row.name) === row.incarnation
1361
+ && requestContextDigest(this.hubAgentConfig(row.name)) === row.target;
1362
+ }
1363
+ catch {
1364
+ return false;
1365
+ }
1366
+ };
1367
+ const rosterOwned = () => processOwned() && [...this.daemons.keys()].every(name => rows.some(row => row.name === name))
1368
+ && rows.every(row => { const now = this.daemons.get(row.name); return row.candidate ? now === row.candidate || !row.published && !now : row.stopped ? !now : now === row.daemon; });
1369
+ const current = () => rosterOwned() && rows.every(configured);
1370
+ const prepare = (name, actual) => {
1371
+ const row = rows.find(item => item.name === name);
1372
+ if (rollingBack || !row?.prepared || !row.stopped || row.candidate || !current() || requestContextDigest(actual) !== requestContextDigest(row.spec.config))
1373
+ throw Error("Request relaunch start differs");
1374
+ return row.prepared.preparation;
1375
+ };
1376
+ const configure = (name, daemon, actual, offered) => {
1377
+ const row = rows.find(item => item.name === name);
1378
+ if (rollingBack || !row?.prepared || row.candidate || !current() || offered !== undefined && offered.policy !== policy)
1379
+ throw Error("Request relaunch owner differs");
1380
+ // Capture the object before any pre-start callback can fail. Even a startup rejection must retire it exactly.
1381
+ row.candidate = daemon;
1382
+ daemon.seedRequestContextReplacement(row.retirement);
1383
+ row.startup = daemon.prepareRequestContextStartupRetirement();
1384
+ originalConfigure?.(name, daemon, actual, offered);
1385
+ row.prepared.configure(daemon, actual, offered);
1386
+ };
1387
+ const hooksOwned = () => this.prepareRequestContextStart === prepare && this.configureRequestContextBeforeStart === configure;
1388
+ const restoreHooks = () => { if (!hooksOwned())
1389
+ throw Error("Request relaunch start hooks changed"); this.prepareRequestContextStart = originalPrepare; this.configureRequestContextBeforeStart = originalConfigure; };
1390
+ const failed = (name) => Object.assign(Error("Request-context owner is not ready"), { code: "request-context-owner-not-ready", agent: name });
1391
+ const rollback = async () => {
1392
+ if (committed || box.requestContextInstallation().read() !== null)
1393
+ throw Error("Activated owners cannot revert to legacy");
1394
+ if (!processOwned() || !hooksOwned())
1395
+ throw Error("Request relaunch rollback owner changed");
1396
+ rollingBack = true;
1397
+ // Stop/prove every candidate before regenerating legacy instructions or creating a legacy replacement.
1398
+ for (const row of rows.slice().reverse()) {
1399
+ if (!row.candidate)
1400
+ continue;
1401
+ const now = this.daemons.get(row.name);
1402
+ if (now && now !== row.candidate)
1403
+ throw failed(row.name);
1404
+ if (now === row.candidate)
1405
+ await this.lifecycle.stopIfCurrent(row.name, row.candidate);
1406
+ else
1407
+ await row.candidate.stop({ nativePane: "close" });
1408
+ if (!processOwned() || !row.startup || !await row.startup.retired())
1409
+ throw failed(row.name);
1410
+ row.candidate = null;
1411
+ row.prepared?.dispose();
1412
+ }
1413
+ if (undoAfterRetirement) {
1414
+ await undoAfterRetirement();
1415
+ undoAfterRetirement = undefined;
1416
+ }
1417
+ restoreHooks();
1418
+ for (const row of rows) {
1419
+ row.prepared?.dispose();
1420
+ if (!row.stopped)
1421
+ continue;
1422
+ if (!processOwned())
1423
+ throw failed(row.name);
1424
+ if (this.daemons.get(row.name) === row.daemon)
1425
+ await this.lifecycle.stopIfCurrent(row.name, row.daemon);
1426
+ // A deleted, re-targeted or externally replaced owner is never resurrected from this captured config.
1427
+ if (!configured(row) || this.daemons.has(row.name))
1428
+ continue;
1429
+ if (!await row.retirement.retired() || !processOwned())
1430
+ throw failed(row.name);
1431
+ await this.startInstance(row.name, row.spec.config, row.spec.topicMode, row.spec.kind);
1432
+ }
1433
+ alive = false;
1434
+ };
1435
+ if (!inventory.current() || !current() || !durableDrained() || !fence.current())
1436
+ throw Error("Request relaunch preparation changed");
1437
+ this.prepareRequestContextStart = prepare;
1438
+ this.configureRequestContextBeforeStart = configure;
1439
+ try {
1440
+ for (const row of rows) {
1441
+ if (!current() || !fence.current() || !durableDrained() || !row.idle.current())
1442
+ throw failed(row.name);
1443
+ execution?.assert();
1444
+ row.stopped = true;
1445
+ let stopped = false;
1446
+ if (execution)
1447
+ await execution.stopTarget(row.name, async (advance) => { stopped = await this.lifecycle.stopIfCurrent(row.name, row.daemon, advance); });
1448
+ else
1449
+ stopped = await this.lifecycle.stopIfCurrent(row.name, row.daemon);
1450
+ if (!stopped)
1451
+ throw failed(row.name);
1452
+ if (!current() || !await row.retirement.retired() || !current())
1453
+ throw failed(row.name);
1454
+ }
1455
+ if (afterRetirement) {
1456
+ undoAfterRetirement = await afterRetirement();
1457
+ if (!current() || !fence.current() || !durableDrained())
1458
+ throw Error("Request relaunch preparation changed");
1459
+ }
1460
+ for (const row of rows) {
1461
+ if (!current() || !fence.current() || !durableDrained())
1462
+ throw failed(row.name);
1463
+ row.prepared = this.prepareRequestContextDaemonOwner(row.name, row.spec.config, policy, registration, () => committed ? processOwned() && this.contactGeneration(row.name) === row.incarnation && this.daemons.get(row.name) === row.candidate : current());
1464
+ execution?.assert();
1465
+ await this.startInstance(row.name, row.spec.config, row.spec.topicMode, row.spec.kind, false, undefined, execution);
1466
+ execution?.assert();
1467
+ row.published = true;
1468
+ if (!current())
1469
+ throw failed(row.name);
1470
+ row.prepared.sealRegistered();
1471
+ }
1472
+ const ready = () => !rollingBack && current() && hooksOwned() && fence.current() && durableDrained() && rows.every(row => row.prepared?.bound());
1473
+ if (!ready())
1474
+ throw Error("Request relaunch preparation changed");
1475
+ return Object.freeze({
1476
+ ready,
1477
+ owners: () => rows.map(row => { if (!row.candidate || !row.startup || !row.prepared?.bound())
1478
+ throw Error("Request relaunch owner unavailable"); return Object.freeze({ name: row.name, daemon: row.candidate, prepared: row.prepared, resources: row.startup }); }),
1479
+ /** Synchronous initializer inside activation's outer SQLite transaction. */
1480
+ retain: () => { if (!ready())
1481
+ throw Error("Request relaunch preparation changed"); for (const row of rows)
1482
+ row.prepared.work.retainPrepared(); if (!ready())
1483
+ throw Error("Request relaunch preparation changed"); },
1484
+ /** Post-COMMIT only. The installer replaces the start hooks with its capable owner factory before releasing admission. */
1485
+ seal: () => {
1486
+ if (rollingBack || !current() || !hooksOwned() || !rows.every(row => row.prepared?.bound()) || box.requestContextInstallation().read() === null)
1487
+ throw Error("Request relaunch has not committed");
1488
+ for (const row of rows)
1489
+ row.prepared.work.sealRetained();
1490
+ committed = true;
1491
+ },
1492
+ executionCurrent: () => committed && processOwned(),
1493
+ releaseStartHooks: () => { if (!committed || !current())
1494
+ throw Error("Request relaunch has not committed"); restoreHooks(); },
1495
+ rollback,
1496
+ });
1497
+ }
1498
+ catch (error) {
1499
+ try {
1500
+ await rollback();
1501
+ }
1502
+ catch (rollbackError) {
1503
+ throw new AggregateError([error, rollbackError], "Request relaunch could not restore every owned agent; admission stays fenced");
1504
+ }
1505
+ throw error;
1506
+ }
1507
+ }
1508
+ /** Shared input gate only; C/D scope binding remains a separate pre-start preparation. */
1509
+ attachRequestContextAdmission(port) {
1510
+ if (this.requestContextAdmission === port)
1511
+ return;
1512
+ if (this.requestContextAdmission)
1513
+ throw Error("Request-context admission owner differs");
1514
+ this.requestContextAdmission = port;
1515
+ for (const daemon of this.daemons.values())
1516
+ daemon.setRequestContextAdmission(port);
1517
+ const prepare = this.configureRequestContextBeforeStart;
1518
+ this.configureRequestContextBeforeStart = (name, daemon, config, preparation) => { daemon.setRequestContextAdmission(port); prepare?.(name, daemon, config, preparation); };
1519
+ port.subscribe(available => {
1520
+ if ((available || port.dispatchAvailable?.()) && !this.shuttingDown && this.deliveryOutbox?.isOpen) {
1521
+ this.scheduleDeliveryOutboxPump();
1522
+ this.wakeCoordinator?.kick();
1523
+ }
1524
+ });
1525
+ }
848
1526
  /** S-244: the quiescence barrier. Unset, every pane write and admission proceeds as today. */
849
1527
  quiescence = null;
850
1528
  attachQuiescence(gate) { this.quiescence = gate; }
1529
+ updateHandbackTimer = null;
1530
+ /**
1531
+ * M-3770 §2.3/§2.6 (rev 15): this fleet was restarted by an abandon as the attempt's `old` generation (its handoff
1532
+ * nonce): it takes the held inbox and deferred jobs back. The first walk runs during the start, before the web chat,
1533
+ * the adapters and the agents open any ingress, so a held copy keeps its place ahead of anything newer (Fable #4536
1534
+ * design 3b): it waits, bounded, for the abandon driver to journal `restart-old`. Later walks every 10 s pick up
1535
+ * stragglers until `hand-back` is journaled or the attempt closes.
1536
+ */
1537
+ async startUpdateHandback(nonce = process.env.AGEND_UPDATE_HANDOFF ?? "", waitMs = 15_000, sleep = (ms) => new Promise(r => setTimeout(r, ms))) {
1538
+ if (!/^[0-9a-f]{32}$/.test(nonce))
1539
+ return;
1540
+ const own = { nonce, pid: process.pid };
1541
+ const mine = (a) => a.stage === "abandoning"
1542
+ && a.fleets?.some(g => g.gen === "old" && g.nonce === nonce) === true;
1543
+ const until = performance.now() + waitMs;
1544
+ for (;;) {
1545
+ const read = readUpdateJournal(this.dataDir);
1546
+ if (read.state !== "open" || !mine(read.attempt))
1547
+ return;
1548
+ if (handbackDue(read.attempt, own)) {
1549
+ this.walkUpdateHandback(read.attempt, own);
1550
+ break;
1551
+ }
1552
+ if (performance.now() >= until || this.shuttingDown) {
1553
+ this.logger.warn({ attemptId: read.attempt.id }, "Update hand-back: restart-old isn't journaled yet; the held work is taken back by the next walk");
1554
+ break;
1555
+ }
1556
+ await sleep(250);
1557
+ }
1558
+ const again = () => {
1559
+ this.updateHandbackTimer = null;
1560
+ if (this.shuttingDown)
1561
+ return;
1562
+ const read = readUpdateJournal(this.dataDir);
1563
+ if (read.state !== "open" || !mine(read.attempt))
1564
+ return;
1565
+ if (handbackDue(read.attempt, own))
1566
+ this.walkUpdateHandback(read.attempt, own);
1567
+ this.updateHandbackTimer = setTimeout(again, 10_000);
1568
+ this.updateHandbackTimer.unref?.();
1569
+ };
1570
+ this.updateHandbackTimer = setTimeout(again, 10_000);
1571
+ this.updateHandbackTimer.unref?.();
1572
+ }
1573
+ walkUpdateHandback(attempt, own) {
1574
+ try {
1575
+ const r = new QuiescenceBarrier(this.dataDir).runHandback(attempt, this.updateHandbackPorts(), own);
1576
+ if (r.walked)
1577
+ this.logger.info({ attemptId: attempt.id, acked: r.acked }, "Update hand-back walked");
1578
+ }
1579
+ catch (err) {
1580
+ this.logger.warn({ err, attemptId: attempt.id }, "Update hand-back walk failed; the next walk retries");
1581
+ }
1582
+ }
1583
+ /** §2.6 ports, rev 15 (Fable #4536 design): the pump owns a handed-back row again; copies go in as their own kind. */
1584
+ updateHandbackPorts() {
1585
+ const outbox = this.deliveryOutbox;
1586
+ if (!outbox)
1587
+ throw new Error("the delivery outbox isn't open");
1588
+ return {
1589
+ log: (fields, message) => this.logger.warn(fields, `Update hand-back: ${message}`),
1590
+ lookup: id => { const row = outbox.get(id); return row ? { state: row.state, target: row.targetInstance } : null; },
1591
+ // Queued and retry_wait rows (inside a backoff too) are the restarted pump's again: it delivers them per target in
1592
+ // order. Nothing is claimed here, so the pump's lane bookkeeping stays whole.
1593
+ claim: id => {
1594
+ const row = outbox.get(id);
1595
+ if (!row)
1596
+ return "missing";
1597
+ if (row.state !== "queued" && row.state !== "retry_wait")
1598
+ return "settled";
1599
+ this.scheduleDeliveryOutboxPump();
1600
+ return "claimed";
1601
+ },
1602
+ admitCopy: (sourceKey, body, target) => {
1603
+ if (!this.fleetConfig?.instances[target])
1604
+ return null;
1605
+ const payload = { ...body };
1606
+ const meta = payload.meta && typeof payload.meta === "object" ? payload.meta : undefined;
1607
+ if (meta) {
1608
+ const stripped = stripHumanReceipt(meta);
1609
+ payload.meta = stripped.meta;
1610
+ if (stripped.receiptId)
1611
+ outbox.markHumanReceiptUncertain(stripped.receiptId, target);
1612
+ }
1613
+ const admitted = outbox.admit({ operationId: sourceKey, sourceKey, sourceInstance: UPDATE_HANDBACK_SOURCE, sourceDaemonBootId: this.managerBootId,
1614
+ targetInstance: target, kind: UPDATE_HANDBACK_COPY_KIND, payload });
1615
+ return { deliveryId: admitted.delivery.deliveryId };
1616
+ },
1617
+ runDeferred: job => { this.scheduler?.runDeferredOccurrence(job.scheduleId, job.runId, name => !!this.fleetConfig?.instances[name]); },
1618
+ recordInterrupted: job => { this.scheduler?.recordInterruptedOccurrence(job.scheduleId, job.runId); },
1619
+ };
1620
+ }
851
1621
  children = new Map();
852
1622
  lifecycle;
853
1623
  stormWindow;
@@ -1074,6 +1844,7 @@ export class FleetManager {
1074
1844
  fleetConfig = null;
1075
1845
  fleetWindowsRuntime = null;
1076
1846
  nativeMcpStore = null;
1847
+ requestContextPendingWork = new RequestContextPendingWork();
1077
1848
  requestContextIpcCalls = new WeakMap();
1078
1849
  requestContextFleetCalls = new RequestContextReferenceMap(row => row.call.admission.coverage === "covered" ? row.call.admission.lease.snapshot.context.ref.rootContextId : null, row => `fleet-call:${row.call.id}`);
1079
1850
  setRequestContextDrainRegistration(registration) {
@@ -1084,6 +1855,28 @@ export class FleetManager {
1084
1855
  throw Error("Request context drain registry unavailable");
1085
1856
  calls.installRegistration(registration);
1086
1857
  }
1858
+ /** Unpublished first-On registration. Only an empty, physically disconnected attempt can restore its prior map. */
1859
+ stageRequestContextFleetRegistration(registration, current) {
1860
+ const box = this.deliveryOutbox, lease = captureProcessFleetLease(this.dataDir), original = this.requestContextFleetCalls;
1861
+ if (!box || !lease?.current() || !current() || this.requestContextAdmission?.available() !== false || !original || original.size || original.registrationGate
1862
+ || this.instanceIpcClients.size || !this.requestContextPendingWork?.empty || box.requestContextInstallation().read() !== null)
1863
+ throw Error("Fleet call registration preparation unavailable");
1864
+ const replacement = new RequestContextReferenceMap(row => row.call.admission.coverage === "covered" ? row.call.admission.lease.snapshot.context.ref.rootContextId : null, row => `fleet-call:${row.call.id}`);
1865
+ replacement.installRegistration(registration);
1866
+ this.requestContextFleetCalls = replacement;
1867
+ const owned = () => { try {
1868
+ return !this.shuttingDown && lease.current() && current() && this.deliveryOutbox === box && this.requestContextFleetCalls === replacement;
1869
+ }
1870
+ catch {
1871
+ return false;
1872
+ } };
1873
+ return Object.freeze({ current: owned, restore: () => {
1874
+ if (!owned() || this.requestContextAdmission?.available() !== false || this.instanceIpcClients.size || replacement.size
1875
+ || !this.requestContextPendingWork.empty || box.requestContextInstallation().read() !== null)
1876
+ throw Error("Fleet call registration cannot revert");
1877
+ this.requestContextFleetCalls = original;
1878
+ } });
1879
+ }
1087
1880
  get requestContextFleetDrainRevision() { return this.requestContextFleetCalls?.revision ?? "unavailable"; }
1088
1881
  requestContextFleetDrainView(rootId) { return this.requestContextFleetCalls?.view(rootId) ?? { registration: null, revision: "unavailable", references: [], unknown: true }; }
1089
1882
  finishRequestContextIpcCall(message) { const call = this.requestContextCallOf(message), calls = this.requestContextFleetCalls; if (call && calls)
@@ -1131,7 +1924,7 @@ export class FleetManager {
1131
1924
  return false;
1132
1925
  const tool = message.type === "fleet_outbound" ? String(message.tool ?? "") : toolForIpcType(message.type);
1133
1926
  const originalBoot = daemon.bootId;
1134
- const scoped = Object.freeze({ id: captured.id, admission: captured.admission,
1927
+ const scoped = Object.freeze({ id: captured.id, admission: captured.admission, replyRoute: captured.replyRoute,
1135
1928
  current: () => captured.current() && this.instanceIpcClients.get(name) === ipc && this.getDaemonBootId(name) === originalBoot
1136
1929
  && !!tool && this.checkToolPermission("ipc-outbound", name, tool === "hub_room_status" ? "hub_room_list" : tool).allowed });
1137
1930
  const calls = this.requestContextFleetCalls;
@@ -1277,13 +2070,146 @@ export class FleetManager {
1277
2070
  runtimeExecutor = null;
1278
2071
  runtimeStatusScheduled = false;
1279
2072
  reconciledRemoteResults = new Set();
2073
+ requestContextNativeGraph;
2074
+ requestContextNativeGraphLease;
2075
+ requestContextNativeFactoryOwners;
2076
+ requestContextOpeningPaneManagers = 0;
2077
+ requestContextNativeRetiring = false;
2078
+ /** Already-drained owned launches only. The callback owns the Fleet/process, not the browser/readiness. */
2079
+ async retireRequestContextNativeFactories(current) {
2080
+ const lease = captureProcessFleetLease(this.dataDir), owned = () => !!lease?.current() && current() && this.requestContextAdmission?.available() === false;
2081
+ if (!owned() || this.requestContextNativeRetiring)
2082
+ throw Error("Native factory retirement needs the owned admission fence");
2083
+ const [{ LocalPaneEndpoint }, { localPaneScope }, { NativePaneManager }] = await Promise.all([import("./local-pane-endpoint.js"), import("./local-pane-launcher.js"), import("./native-pane-manager.js")]);
2084
+ const scope = localPaneScope(this.dataDir), hub = this.runtimeHub, panes = this.paneManager, mcp = this.nativeMcpStore, runtime = this.fleetWindowsRuntime, executor = this.runtimeExecutor, relay = this.localPaneRelay;
2085
+ const same = () => this.runtimeHub === hub && this.localPaneRelay === relay && this.paneManager === panes && this.nativeMcpStore === mcp && this.fleetWindowsRuntime === runtime && this.runtimeExecutor === executor && !this.openingLocalPane && !this.requestContextOpeningPaneManagers;
2086
+ if (!owned() || !same() || runtime && !runtime.requestContextPhysicallyIdle() || panes && !panes.requestContextPhysicallyIdle() || mcp && !mcp.requestContextPhysicallyIdle() || executor && !executor.idleForRequestContext() || hub && !hub.requestContextPhysicallyIdle() || !windowsBridgeRequestContextIdle(this) || WindowsAgents.requestContextOwnersOnDisk(this.dataDir).length !== 0 || !hub && RuntimeCoordinator.requestContextPendingRunsOnDisk(this.dataDir).runs.length !== 0 || NativePaneManager.requestContextOrphanActivity(this.dataDir).unknown || !LocalPaneEndpoint.requestContextScopeIdle(scope))
2087
+ throw Error("Native factories still own work or an unconfirmed launch");
2088
+ this.requestContextNativeRetiring = true;
2089
+ try {
2090
+ runtime?.retireForRequestContext();
2091
+ panes?.retireForRequestContext();
2092
+ mcp?.retireForRequestContext();
2093
+ executor?.retireForRequestContext();
2094
+ retireWindowsBridgeForRequestContext(this);
2095
+ await Promise.all([hub?.retireForRequestContext(), LocalPaneEndpoint.retireScopeForRequestContext(scope)]);
2096
+ if (!owned() || !same())
2097
+ throw Error("Native factory owner changed during retirement");
2098
+ this.runtimeHub = null;
2099
+ this.localPaneRelay = null;
2100
+ this.paneManager = null;
2101
+ this.nativeMcpStore = null;
2102
+ this.fleetWindowsRuntime = null;
2103
+ this.runtimeExecutor = null;
2104
+ this.requestContextNativeGraph = undefined;
2105
+ this.requestContextNativeGraphLease = undefined;
2106
+ this.requestContextNativeFactoryOwners = undefined;
2107
+ }
2108
+ finally {
2109
+ this.requestContextNativeRetiring = false;
2110
+ }
2111
+ }
2112
+ /** Only after exact old-owner retirement and transport teardown, behind the shared Fleet admission fence. */
2113
+ stageRequestContextNativeGraph(graph) {
2114
+ const lease = captureProcessFleetLease(this.dataDir);
2115
+ if (this.requestContextNativeGraph || !lease?.current() || this.requestContextAdmission?.available() !== false || !graph.current()
2116
+ || this.runtimeHub || this.runtimeExecutor || this.localPaneRelay || this.openingLocalPane || this.requestContextOpeningPaneManagers || this.paneManager || this.nativeMcpStore || this.fleetWindowsRuntime
2117
+ || typeof graph.execInput !== "function" || graph.panes.drainView("").registration !== graph.registration)
2118
+ throw Error("Request-context native graph is not retired");
2119
+ this.requestContextNativeGraph = graph;
2120
+ this.requestContextNativeGraphLease = lease;
2121
+ }
2122
+ /** Inert native owner construction plus the complete eight-family inventory, behind the shared fence.
2123
+ * None of these accessors starts a provider, pane, coordinator or Fleet. Transport negotiation is separate.
2124
+ */
2125
+ async prepareRequestContextDrainOwners(drain, registration, owners, current) {
2126
+ const graph = this.requestContextNativeGraph, box = this.deliveryOutbox, lease = captureProcessFleetLease(this.dataDir);
2127
+ if (!graph || graph.registration !== registration || !graph.current() || !box || !lease?.current() || !current() || !owners.current()
2128
+ || this.requestContextAdmission?.available() !== false || this.requestContextFleetCalls?.registrationGate !== registration)
2129
+ throw Error("Drain owner preparation unavailable");
2130
+ const runtime = this.nativeInstanceRuntime(), grants = this.nativeMcpSessions(), panes = await this.nativePanes();
2131
+ let alive = true;
2132
+ const owned = () => {
2133
+ try {
2134
+ return alive && !this.shuttingDown && lease.current() && current() && owners.current() && this.deliveryOutbox === box
2135
+ && this.requestContextNativeGraph === graph && graph.current() && this.fleetWindowsRuntime === runtime && this.nativeMcpStore === grants
2136
+ && this.paneManager === panes && this.requestContextFleetCalls?.registrationGate === registration;
2137
+ }
2138
+ catch {
2139
+ return false;
2140
+ }
2141
+ };
2142
+ if (!owned() || this.requestContextAdmission?.available() !== false)
2143
+ throw Error("Drain owner preparation changed");
2144
+ const sources = [
2145
+ ["turns", owners.revision, owners.turnView], ["daemon-calls", owners.callRevision, owners.callView],
2146
+ ["fleet-calls", () => this.requestContextFleetDrainRevision, root => this.requestContextFleetDrainView(root)],
2147
+ ["native-exec", () => runtime.drainRevision, root => runtime.drainView(root)],
2148
+ ["native-grants", () => grants.drainRevision, root => grants.drainView(root)],
2149
+ ["pane-proofs", () => graph.panes.drainRevision, root => graph.panes.drainView(root), () => graph.panes.offRevision, root => graph.panes.offView(root)],
2150
+ ["pane-ledgers", () => panes.drainRevision, root => panes.drainView(root), () => panes.offRevision, root => panes.offView(root)],
2151
+ ["registered-work", owners.inputRevision, owners.inputView],
2152
+ ];
2153
+ const remove = [];
2154
+ try {
2155
+ for (const [family, revision, inspect, offRevision, inspectOff] of sources)
2156
+ remove.push(drain.register(family, "fleet", { registration,
2157
+ revision: () => owned() ? revision() : "owner-changed", inspect: root => owned() ? inspect(root) : { registration, revision: "owner-changed", references: [], unknown: true },
2158
+ ...(offRevision && inspectOff ? { offRevision: () => owned() ? offRevision() : "owner-changed", inspectOff: (root) => owned() ? inspectOff(root) : { registration, revision: "owner-changed", references: [], unknown: true } } : {}) }));
2159
+ }
2160
+ catch (error) {
2161
+ for (const undo of remove.reverse())
2162
+ undo();
2163
+ throw error;
2164
+ }
2165
+ return Object.freeze({ current: owned, runtime, grants, panes,
2166
+ /** The physical owners/connection have their own exact rollback; this only removes unpublished inventory. */
2167
+ dispose: () => {
2168
+ if (!owned() || this.requestContextAdmission?.available() !== false || box.requestContextInstallation().read() !== null
2169
+ || !runtime.requestContextPhysicallyIdle() || !grants.requestContextPhysicallyIdle() || !panes.requestContextPhysicallyIdle()
2170
+ || this.requestContextFleetCalls.size || !this.requestContextPendingWork.empty)
2171
+ throw Error("Published drain owners cannot revert");
2172
+ for (const undo of remove.slice().reverse())
2173
+ undo();
2174
+ alive = false;
2175
+ },
2176
+ });
2177
+ }
2178
+ currentRequestContextNativeGraph() {
2179
+ const graph = this.requestContextNativeGraph;
2180
+ if (graph) {
2181
+ if (!this.requestContextNativeGraphLease?.current() || !graph.current())
2182
+ throw Error("Request-context native graph owner changed");
2183
+ return graph;
2184
+ }
2185
+ if (this.requestContextBoot)
2186
+ throw Error("Request-context native graph is not prepared");
2187
+ return null;
2188
+ }
2189
+ ownRequestContextNativeFactory(value, graph) {
2190
+ if (this.currentRequestContextNativeGraph() !== graph)
2191
+ throw Error("Request-context native factory owner changed");
2192
+ (this.requestContextNativeFactoryOwners ??= new WeakMap()).set(value, graph);
2193
+ return value;
2194
+ }
2195
+ requireRequestContextNativeFactory(value, graph) {
2196
+ if (this.currentRequestContextNativeGraph() !== graph || this.requestContextNativeFactoryOwners?.get(value) !== graph)
2197
+ throw Error("Request-context native factory was not prepared");
2198
+ return value;
2199
+ }
1280
2200
  /** Machine credentials are separate from dashboard sessions and per-turn agent capabilities. */
1281
2201
  runtimeCoordinator() {
2202
+ if (this.requestContextNativeRetiring)
2203
+ throw Error("Native factory replacement is holding new work");
1282
2204
  if (!remoteRuntimeEnabled())
1283
2205
  throw new Error("Remote runtimes are not enabled");
1284
2206
  if (!this.runtimeHub && this.readPendingOwnerNotices().length)
1285
2207
  this.scheduleOwnerNoticeFlush(30_000); // a notice kept before a restart is delivered once the fleet is up
1286
- return this.runtimeHub ??= new RuntimeCoordinator(this.dataDir, {
2208
+ const graph = this.requestContextNativeGraph || this.requestContextBoot ? this.currentRequestContextNativeGraph() : null;
2209
+ if (this.runtimeHub)
2210
+ return graph ? this.requireRequestContextNativeFactory(this.runtimeHub, graph) : this.runtimeHub;
2211
+ const hub = new RuntimeCoordinator(this.dataDir, {
2212
+ ...(graph ? { requestContextProtocol: 1 } : {}),
1287
2213
  handleMcp: (machineId, runId, body) => this.runtimeWindowsExecutor().mcp(machineId, runId, body),
1288
2214
  handlePaneMcp: async (machineId, body, current, stamp) => stamp ? (await this.nativePanes()).handle(machineId, body, current, stamp) : (await this.nativePanes()).handle(machineId, body, current),
1289
2215
  warn: (fields, message) => this.logger.warn(fields, message),
@@ -1335,22 +2261,54 @@ export class FleetManager {
1335
2261
  });
1336
2262
  },
1337
2263
  });
2264
+ return this.runtimeHub = graph ? this.ownRequestContextNativeFactory(hub, graph) : hub;
1338
2265
  }
1339
2266
  runtimeWindowsExecutor() {
2267
+ if (this.requestContextNativeRetiring)
2268
+ throw Error("Native factory replacement is holding new work");
1340
2269
  return this.runtimeExecutor ??= new RuntimeWindowsBridge(this, () => remoteRuntimeEnabled() && !this.shuttingDown ? this.runtimeCoordinator() : null);
1341
2270
  }
1342
2271
  /** Per-turn capabilities for native MCP, separate from browser and Linux-agent credentials. */
1343
2272
  nativeMcpSessions() {
1344
- return this.nativeMcpStore ??= new NativeMcpSessions(this);
2273
+ if (this.requestContextNativeRetiring)
2274
+ throw Error("Native factory replacement is holding new work");
2275
+ const graph = this.requestContextNativeGraph || this.requestContextBoot ? this.currentRequestContextNativeGraph() : null;
2276
+ if (this.nativeMcpStore)
2277
+ return graph ? this.requireRequestContextNativeFactory(this.nativeMcpStore, graph) : this.nativeMcpStore;
2278
+ const sessions = new NativeMcpSessions(this, graph?.registration);
2279
+ if (graph)
2280
+ sessions.setRequestContextRequired(true, true);
2281
+ return this.nativeMcpStore = graph ? this.ownRequestContextNativeFactory(sessions, graph) : sessions;
1345
2282
  }
1346
2283
  /** Retire only existing native capabilities; ordinary lifecycle changes do not instantiate the Windows path. */
1347
2284
  invalidateNativeMcp(name) { this.nativeMcpStore?.closeInstance(name); }
1348
2285
  /** The same instance registry and delivery entry point, with a native Windows execution adapter. */
1349
2286
  nativeInstanceRuntime() {
1350
- return this.fleetWindowsRuntime ??= new FleetWindowsRuntime({
2287
+ if (this.requestContextNativeRetiring)
2288
+ throw Error("Native factory replacement is holding new work");
2289
+ const graph = this.requestContextNativeGraph || this.requestContextBoot ? this.currentRequestContextNativeGraph() : null;
2290
+ if (this.fleetWindowsRuntime)
2291
+ return graph ? this.requireRequestContextNativeFactory(this.fleetWindowsRuntime, graph) : this.fleetWindowsRuntime;
2292
+ const runtime = new FleetWindowsRuntime({
1351
2293
  owner: this, fleet: () => this.fleetConfig, save: () => this.saveFleetConfig(), stopping: () => this.shuttingDown, history: this.webChatHistory,
1352
- openMcp: (instance, requestId, sandbox, stillCurrent, requestContext) => this.healthServerListening
1353
- ? this.nativeMcpSessions().grant({ instance, requestId, sandbox, stillCurrent, ...(requestContext ? { requestContext } : {}), endpoint: `http://127.0.0.1:${this.fleetConfig?.health_port ?? 19280}/agent` }) : null,
2294
+ requestContextAdmission: () => this.requestContextAdmission,
2295
+ requestContextContinuation: (instance, inputId) => {
2296
+ if (!this.requestContextBoot)
2297
+ return;
2298
+ const match = /^delivery:([a-f0-9-]{36}):([1-9][0-9]*)$/.exec(inputId ?? "");
2299
+ if (!match)
2300
+ return;
2301
+ const row = this.deliveryOutbox?.get(match[1]);
2302
+ if (!row || row.targetInstance !== instance || row.managerBootId !== this.managerBootId || row.attemptNo !== Number(match[2])
2303
+ || row.targetDaemonBootId !== this.managerBootId || !["delivering", "submission_started"].includes(row.state))
2304
+ throw Error("Native continuation attempt changed");
2305
+ return this.requestContextDeliveryContinuation(row) ?? undefined;
2306
+ },
2307
+ openMcp: (instance, requestId, sandbox, stillCurrent, requestContext, inputReady) => this.healthServerListening
2308
+ ? this.nativeMcpSessions().grant({ instance, requestId, sandbox, stillCurrent, ...(requestContext ? { requestContext } : {}), ...(inputReady ? { inputReady } : {}), endpoint: `http://127.0.0.1:${this.fleetConfig?.health_port ?? 19280}/agent` }) : null,
2309
+ projectRequestContextOutput: (instance, task, completion) => this.deliveryOutbox ? projectRequestContextNativeOutput(this.deliveryOutbox, instance, task, completion, {
2310
+ admitted: root => this.requestContextNativeAdmissionCurrent(root), history: this.webChatHistory, session: handle => this.webSessions?.findByHandle(handle),
2311
+ }) : null,
1354
2312
  warn: (message, error) => this.logger.warn({ err: error }, message),
1355
2313
  removed: name => this.nativeInstanceRemoved(name),
1356
2314
  paneCurrent: name => this.daemons.get(name)?.nativePaneCurrent?.() === true,
@@ -1385,6 +2343,9 @@ export class FleetManager {
1385
2343
  this.scheduleDeliveryOutboxPump();
1386
2344
  },
1387
2345
  }, { bridge: this.runtimeWindowsExecutor() });
2346
+ if (graph)
2347
+ runtime.setRequestContextExecLifecycles(graph.execTurns, graph.execOwner, graph.registration, graph.execInput);
2348
+ return this.fleetWindowsRuntime = graph ? this.ownRequestContextNativeFactory(runtime, graph) : runtime;
1388
2349
  }
1389
2350
  agentRuntimeChangeService;
1390
2351
  agentRuntimeChanges() {
@@ -1626,13 +2587,17 @@ export class FleetManager {
1626
2587
  return { ...(result.version ? { native_cli_version: result.version } : {}), native_cli_verification: result.state };
1627
2588
  }
1628
2589
  async localNativePaneEndpoint() {
1629
- const admit = () => { if (this.shuttingDown || this.localPaneDrain || !localWindowsCliEnabled())
2590
+ if (this.requestContextNativeRetiring)
2591
+ throw Error("Native factory replacement is holding new work");
2592
+ const graph = this.requestContextNativeGraph || this.requestContextBoot ? this.currentRequestContextNativeGraph() : null;
2593
+ const admit = () => { if (graph && this.currentRequestContextNativeGraph() !== graph)
2594
+ throw Error("Request-context native factory owner changed"); if (this.shuttingDown || this.localPaneDrain || !localWindowsCliEnabled())
1630
2595
  throw Error("Local Windows runtime is switched off or draining"); };
1631
2596
  admit();
1632
2597
  if (this.localPaneDrain)
1633
2598
  throw Error("Local Windows runtime cleanup is pending");
1634
2599
  if (this.localPaneRelay?.online())
1635
- return this.localPaneRelay;
2600
+ return graph ? this.requireRequestContextNativeFactory(this.localPaneRelay, graph) : this.localPaneRelay;
1636
2601
  if (this.openingLocalPane)
1637
2602
  return this.openingLocalPane;
1638
2603
  const opening = (async () => {
@@ -1642,15 +2607,14 @@ export class FleetManager {
1642
2607
  admit();
1643
2608
  this.localPaneRelay?.stop();
1644
2609
  this.localPaneInventory = inventory;
1645
- const relay = await LocalPaneEndpoint.open({ scope: localPaneScope(this.dataDir), admit, maxAgents: maxAgentsPerMachine,
2610
+ const relay = await LocalPaneEndpoint.open({ scope: localPaneScope(this.dataDir), ...(graph ? { requestContextProtocol: 1 } : {}), admit, maxAgents: maxAgentsPerMachine,
1646
2611
  diagnostic: text => this.logger.warn({ stderr: text }, "Local Windows pane relay wrote to stderr"),
1647
2612
  version: provider => inventory.clis.find(row => row.id === provider && row.runnable)?.version ?? null,
1648
2613
  launch: () => launchLocalPaneRelay(this.dataDir, admit),
1649
- mcp: async (body, current, stamp) => stamp ? (await this.nativePanes()).handle("local", body, current, stamp) : (await this.nativePanes()).handle("local", body, current),
1650
- });
2614
+ mcp: async (body, current, stamp) => stamp ? (await this.nativePanes()).handle("local", body, current, stamp) : (await this.nativePanes()).handle("local", body, current), });
1651
2615
  try {
1652
2616
  admit();
1653
- this.localPaneRelay = relay;
2617
+ this.localPaneRelay = graph ? this.ownRequestContextNativeFactory(relay, graph) : relay;
1654
2618
  return relay;
1655
2619
  }
1656
2620
  catch (error) {
@@ -1669,85 +2633,101 @@ export class FleetManager {
1669
2633
  }
1670
2634
  /** Persistent ownership is independent of the exec worker's per-turn capabilities. */
1671
2635
  async nativePanes() {
2636
+ if (this.requestContextNativeRetiring)
2637
+ throw Error("Native factory replacement is holding new work");
2638
+ const graph = this.requestContextNativeGraph || this.requestContextBoot ? this.currentRequestContextNativeGraph() : null;
1672
2639
  if (this.paneManager)
1673
- return this.paneManager;
1674
- const { NativePaneManager } = await import("./native-pane-manager.js");
1675
- if (this.paneManager)
1676
- return this.paneManager;
1677
- const store = windowsAgentsFor(this, this.runtimeWindowsExecutor());
1678
- const allowed = (name, tool) => (!this.classicContactRestricted(name) || CLASSIC_RESTRICTED_TOOLS.includes(tool))
1679
- && nativePaneToolAvailable(tool) && mayUseTool(resolveToolSet(this.fleetConfig?.instances[name], name), tool)
1680
- && !dashboardRefusalIn(this.fleetConfig, name, tool);
1681
- return this.paneManager = new NativePaneManager({
1682
- home: this.dataDir, store, config: name => this.fleetConfig?.instances[name],
1683
- freshNotice: async (name, provider) => {
1684
- const message = t(provider === "codex" ? "native_pane.codex_fresh_started" : "native_pane.fresh_started");
1685
- this.eventLog?.insert(name, "native_pane_fresh_started", {});
1686
- this.logger.info({ name }, message);
1687
- await this.notifyInstanceTopic(name, message);
1688
- },
1689
- admit: (name, config) => {
1690
- const now = this.fleetConfig?.instances[name];
1691
- if (this.shuttingDown || !isNativePaneInstance(now) || now?.native_agent_id !== config.native_agent_id
1692
- || now?.machine_id !== config.machine_id || now?.working_directory !== config.working_directory || now?.backend !== config.backend
1693
- || now?.model !== config.model || now?.native_sandbox !== config.native_sandbox || now?.systemPrompt !== config.systemPrompt || now?.operations !== config.operations || now?.workflow !== config.workflow
1694
- || now?.general_topic !== config.general_topic || now?.native_general_binding !== config.native_general_binding
1695
- || nativeCredentialProfile(now) !== nativeCredentialProfile(config))
1696
- throw Error("Native pane configuration or lifetime changed");
1697
- // Fail closed: a Runtime that does not report the capability would start the terminal on the computer's own account.
1698
- if (nativeCredentialProfile(config) && !this.runtimeCoordinator().machine(config.machine_id)?.runtimeInfo?.capabilities.includes(RUNTIME_CREDENTIAL_CAPABILITY))
1699
- throw Error("This computer's Runtime is too old to choose a Claude account. Update the Runtime on that computer, then try again.");
1700
- if (config.machine_id ? this.remotePaneDrain || !remoteRuntimeEnabled() : this.localPaneDrain || !localWindowsCliEnabled())
1701
- throw Error("Native runtime is switched off");
1702
- },
1703
- endpoint: async (agent, cleanup = false) => {
1704
- if (!agent.machineId) {
1705
- if (!cleanup)
1706
- return this.localNativePaneEndpoint();
1707
- if (!this.localPaneRelay)
1708
- throw Error("Local cleanup transport is unavailable; pane remains reserved");
1709
- return this.localPaneRelay;
1710
- }
1711
- const hub = cleanup ? this.runtimeHub : this.runtimeCoordinator(), machineId = agent.machineId;
1712
- if (!hub)
1713
- throw Error("Remote cleanup transport is unavailable; pane remains reserved");
1714
- const draining = () => !!this.remotePaneDrain;
1715
- return { machineId, online: () => !this.shuttingDown && (draining() || remoteRuntimeEnabled()) && this.runtimeHub === hub && hub.machine(machineId)?.status === "online",
1716
- call: request => {
1717
- if (this.runtimeHub !== hub || !(draining() || remoteRuntimeEnabled()) || draining() && request.action !== "snapshot" && request.action !== "close")
1718
- return Promise.reject(Error("Remote pane transport only permits owned cleanup"));
1719
- return hub.callPane(machineId, request, maxAgentsPerMachine());
1720
- }, subscribe: listener => hub.subscribe(listener),
1721
- epoch: () => hub.paneTransportEpoch(machineId), version: provider => hub.machine(machineId)?.inventory?.clis.find(row => row.id === provider && row.runnable)?.version ?? null };
1722
- },
1723
- instructions: (name, config) => buildNativeFleetInstructions({ instanceName: name, workingDirectory: config.working_directory,
1724
- displayName: config.display_name, description: config.description, customPrompt: config.systemPrompt, operations: config.operations,
1725
- workflow: config.workflow, taskBoard: !dashboardRefusalIn(this.fleetConfig, name, "task"),
1726
- runtimeIdentity: { kind: "fleet-topic", backend: config.backend ?? "codex", model: config.model || "default" } }, config.general_topic === true),
1727
- menu: name => TOOLS.filter(tool => allowed(name, tool.name)).map(tool => ({ ...tool })),
1728
- allowed: (name, tool, args) => allowed(name, tool) && !nativePaneToolRefusal(tool, args), published: (name, daemon) => this.daemons.get(name) === daemon,
1729
- invoke: async (daemon, input, current, name) => {
1730
- if (input.tool === "list_models") {
1731
- const { ListModelsArgs } = await import("./outbound-schemas.js");
1732
- const parsed = ListModelsArgs.safeParse(input.args);
1733
- if (!parsed.success || !current())
1734
- return { result: null, error: "Invalid native model request or expired owner" };
1735
- const target = parsed.data.instance_name ?? name;
1736
- if (!isWindowsInstance(this.fleetConfig?.instances[target]))
1737
- return { result: null, error: "Native panes can only read Windows runtime model inventories" };
1738
- return { result: await this.listModelCatalog({ instanceName: target }) };
1739
- }
1740
- 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",
1741
- delegate_task: "delegate", request_information: "ask", report_result: "report", delivery_status: "delivery-status" };
1742
- const { nativeAgentAdmissionContext } = await import("./native-agent-admission.js");
1743
- const { dispatchAgentOperation } = await import("./agent-endpoint.js");
1744
- return daemon.handlePaneToolCall(input, { current, allowed: tool => allowed(name, tool), ...(input.requestContext ? { requestContext: input.requestContext } : {}),
1745
- dispatch: (tool, args) => ops[tool] ? dispatchAgentOperation(nativeAgentAdmissionContext(this, {
1746
- instance: name, operation: { tool, args }, current: () => current() && allowed(name, tool), taskAllowed: () => current() && allowed(name, "task"),
1747
- ...(input.requestContext?.coverage === "covered" ? { requestContext: input.requestContext.lease } : input.requestContext ? { notCoveredReason: input.requestContext.reason } : {}),
1748
- }), name, ops[tool], args, input.operationId, () => current() && allowed(name, tool)) : undefined });
1749
- },
1750
- });
2640
+ return graph ? this.requireRequestContextNativeFactory(this.paneManager, graph) : this.paneManager;
2641
+ const boot = this.requestContextBoot;
2642
+ this.requestContextOpeningPaneManagers = (this.requestContextOpeningPaneManagers ?? 0) + 1;
2643
+ try {
2644
+ const { NativePaneManager } = await import("./native-pane-manager.js");
2645
+ if (this.requestContextNativeGraph !== (graph ?? undefined) || this.requestContextBoot !== boot)
2646
+ throw Error("Request-context native factory owner changed");
2647
+ if (this.paneManager)
2648
+ return graph ? this.requireRequestContextNativeFactory(this.paneManager, graph) : this.paneManager;
2649
+ if (graph && this.currentRequestContextNativeGraph() !== graph)
2650
+ throw Error("Request-context native factory owner changed");
2651
+ const store = windowsAgentsFor(this, this.runtimeWindowsExecutor());
2652
+ const allowed = (name, tool) => (!this.classicContactRestricted(name) || CLASSIC_RESTRICTED_TOOLS.includes(tool))
2653
+ && nativePaneToolAvailable(tool) && mayUseTool(resolveToolSet(this.fleetConfig?.instances[name], name), tool)
2654
+ && !dashboardRefusalIn(this.fleetConfig, name, tool);
2655
+ const manager = new NativePaneManager({
2656
+ ...(graph ? { requestContexts: graph.panes, registration: graph.registration } : {}),
2657
+ home: this.dataDir, store, config: name => this.fleetConfig?.instances[name],
2658
+ freshNotice: async (name, provider) => {
2659
+ const message = t(provider === "codex" ? "native_pane.codex_fresh_started" : "native_pane.fresh_started");
2660
+ this.eventLog?.insert(name, "native_pane_fresh_started", {});
2661
+ this.logger.info({ name }, message);
2662
+ await this.notifyInstanceTopic(name, message);
2663
+ },
2664
+ admit: (name, config) => {
2665
+ const now = this.fleetConfig?.instances[name];
2666
+ if (this.shuttingDown || !isNativePaneInstance(now) || now?.native_agent_id !== config.native_agent_id
2667
+ || now?.machine_id !== config.machine_id || now?.working_directory !== config.working_directory || now?.backend !== config.backend
2668
+ || now?.model !== config.model || now?.native_sandbox !== config.native_sandbox || now?.systemPrompt !== config.systemPrompt || now?.operations !== config.operations || now?.workflow !== config.workflow
2669
+ || now?.general_topic !== config.general_topic || now?.native_general_binding !== config.native_general_binding
2670
+ || nativeCredentialProfile(now) !== nativeCredentialProfile(config))
2671
+ throw Error("Native pane configuration or lifetime changed");
2672
+ // Fail closed: a Runtime that does not report the capability would start the terminal on the computer's own account.
2673
+ if (nativeCredentialProfile(config) && !this.runtimeCoordinator().machine(config.machine_id)?.runtimeInfo?.capabilities.includes(RUNTIME_CREDENTIAL_CAPABILITY))
2674
+ throw Error("This computer's Runtime is too old to choose a Claude account. Update the Runtime on that computer, then try again.");
2675
+ if (config.machine_id ? this.remotePaneDrain || !remoteRuntimeEnabled() : this.localPaneDrain || !localWindowsCliEnabled())
2676
+ throw Error("Native runtime is switched off");
2677
+ },
2678
+ endpoint: async (agent, cleanup = false) => {
2679
+ if (!agent.machineId) {
2680
+ if (!cleanup)
2681
+ return this.localNativePaneEndpoint();
2682
+ if (!this.localPaneRelay)
2683
+ throw Error("Local cleanup transport is unavailable; pane remains reserved");
2684
+ return this.localPaneRelay;
2685
+ }
2686
+ const hub = cleanup ? this.runtimeHub : this.runtimeCoordinator(), machineId = agent.machineId;
2687
+ if (!hub)
2688
+ throw Error("Remote cleanup transport is unavailable; pane remains reserved");
2689
+ const draining = () => !!this.remotePaneDrain;
2690
+ return { machineId, online: () => !this.shuttingDown && (draining() || remoteRuntimeEnabled()) && this.runtimeHub === hub && hub.machine(machineId)?.status === "online",
2691
+ call: request => {
2692
+ if (this.runtimeHub !== hub || !(draining() || remoteRuntimeEnabled()) || draining() && request.action !== "snapshot" && request.action !== "close")
2693
+ return Promise.reject(Error("Remote pane transport only permits owned cleanup"));
2694
+ return hub.callPane(machineId, request, maxAgentsPerMachine());
2695
+ }, subscribe: listener => hub.subscribe(listener),
2696
+ epoch: () => hub.paneTransportEpoch(machineId), version: provider => hub.machine(machineId)?.inventory?.clis.find(row => row.id === provider && row.runnable)?.version ?? null };
2697
+ },
2698
+ instructions: (name, config) => buildNativeFleetInstructions({ instanceName: name, workingDirectory: config.working_directory,
2699
+ displayName: config.display_name, description: config.description, customPrompt: config.systemPrompt, operations: config.operations,
2700
+ workflow: config.workflow, taskBoard: !dashboardRefusalIn(this.fleetConfig, name, "task"),
2701
+ runtimeIdentity: { kind: "fleet-topic", backend: config.backend ?? "codex", model: config.model || "default" } }, config.general_topic === true),
2702
+ menu: name => TOOLS.filter(tool => allowed(name, tool.name)).map(tool => ({ ...tool })),
2703
+ allowed: (name, tool, args) => allowed(name, tool) && !nativePaneToolRefusal(tool, args), published: (name, daemon) => this.daemons.get(name) === daemon,
2704
+ invoke: async (daemon, input, current, name) => {
2705
+ if (input.tool === "list_models") {
2706
+ const { ListModelsArgs } = await import("./outbound-schemas.js");
2707
+ const parsed = ListModelsArgs.safeParse(input.args);
2708
+ if (!parsed.success || !current())
2709
+ return { result: null, error: "Invalid native model request or expired owner" };
2710
+ const target = parsed.data.instance_name ?? name;
2711
+ if (!isWindowsInstance(this.fleetConfig?.instances[target]))
2712
+ return { result: null, error: "Native panes can only read Windows runtime model inventories" };
2713
+ return { result: await this.listModelCatalog({ instanceName: target }) };
2714
+ }
2715
+ const ops = { hub_set_intro: "hub-set-intro", hub_room_list: "hub-room-list", hub_room_post: "hub-room-post", hub_room_history: "hub-room-history", hub_room_members: "hub-room-members", hub_people_search: "hub-people-search", list_instances: "list", describe_instance: "describe", task: "task", send_to_instance: "send",
2716
+ delegate_task: "delegate", request_information: "ask", report_result: "report", delivery_status: "delivery-status" };
2717
+ const { nativeAgentAdmissionContext } = await import("./native-agent-admission.js");
2718
+ const { dispatchAgentOperation } = await import("./agent-endpoint.js");
2719
+ return daemon.handlePaneToolCall(input, { current, allowed: tool => allowed(name, tool), ...(input.requestContext ? { requestContext: input.requestContext } : {}),
2720
+ dispatch: (tool, args) => ops[tool] ? dispatchAgentOperation(nativeAgentAdmissionContext(this, {
2721
+ instance: name, operation: { tool, args }, current: () => current() && allowed(name, tool), taskAllowed: () => current() && allowed(name, "task"),
2722
+ ...(input.requestContext?.coverage === "covered" ? { requestContext: input.requestContext.lease } : input.requestContext ? { notCoveredReason: input.requestContext.reason } : {}),
2723
+ }), name, ops[tool], args, input.operationId, () => current() && allowed(name, tool)) : undefined });
2724
+ },
2725
+ });
2726
+ return this.paneManager = graph ? this.ownRequestContextNativeFactory(manager, graph) : manager;
2727
+ }
2728
+ finally {
2729
+ this.requestContextOpeningPaneManagers--;
2730
+ }
1751
2731
  }
1752
2732
  /** Prepare only bundled role files; this neither switches General nor starts a provider process. */
1753
2733
  async prepareWindowsGeneralWorkspace(name, machineId, cli, bindingId, authorized) {
@@ -2088,6 +3068,8 @@ export class FleetManager {
2088
3068
  updateChatCardVersion = new Map();
2089
3069
  /** #4485 review 2: an answer that came while its card was still being posted (the post records it when it returns). */
2090
3070
  updateChatCardAnswered = new Map();
3071
+ /** Prism #4584 (1): a press refused while its card was still being posted (the post records it, so it isn't relabelled expired). */
3072
+ updateChatCardRefused = new Set();
2091
3073
  updateChatCardTimer = null;
2092
3074
  readUpdateChatCard() {
2093
3075
  try {
@@ -2114,14 +3096,18 @@ export class FleetManager {
2114
3096
  if (view && view.state === "offered") {
2115
3097
  // M-3770 1.2's cached pre-flight, when this build has it (#4483): the second sentence only where it is true.
2116
3098
  const pre = this.updatePreflight;
3099
+ // M-3864 R1: a machine where even an admin's press can't start it says why, as the web does (its card offers Not now only).
3100
+ const blocking = pre ? preflightBlocking(pre) : null;
3101
+ if (blocking)
3102
+ return `${t("update.chatcard.offer", view.version)}\n${t("update.chatcard.cant", preflightWords(blocking, (key, ...args) => t(key, ...args)))}`;
2117
3103
  const p3 = pre?.checks.find(c => c.id === "P3");
2118
3104
  // The leader's copy pass (S-237): a title and one line, as on the web.
2119
3105
  const line = !p3 ? t("update.chatcard.continues") : p3.ok ? t("update.chatcard.back", current ?? "?") : t("update.chatcard.noWayBack");
2120
3106
  return `${t("update.chatcard.offer", view.version)}\n${line}`;
2121
3107
  }
2122
3108
  // The card's own short lines, as on the web (the leader's copy pass); anything else in /update's words.
2123
- const at = (ms) => { if (!ms)
2124
- return ""; const d = new Date(ms), p2 = (n) => String(n).padStart(2, "0"); return `${d.getFullYear()}-${p2(d.getMonth() + 1)}-${p2(d.getDate())} ${p2(d.getHours())}:${p2(d.getMinutes())}`; };
3109
+ // M-3864 R2: the fleet's zone with its offset, as schedules say times (the web shows the person's own zone).
3110
+ const at = (ms) => (ms ? formatFleetTime(ms, this.usageZone()) : "");
2125
3111
  if (view?.state === "waiting-idle")
2126
3112
  return t("update.chatcard.state_waiting", view.version);
2127
3113
  if (view?.state === "scheduled")
@@ -2134,9 +3120,19 @@ export class FleetManager {
2134
3120
  return t("update.chatcard.state_done", view.version);
2135
3121
  if (view?.state === "failed")
2136
3122
  return t("update.chatcard.state_failed", view.version, current ?? "?");
2137
- const reply = updateOfferReply(view, current, !!resolveUpdates(this.fleetConfig?.updates).pin);
3123
+ const reply = updateOfferReply(view, current, !!resolveUpdates(this.fleetConfig?.updates).pin, this.usageZone());
2138
3124
  return t(reply.key, ...reply.args);
2139
3125
  }
3126
+ /**
3127
+ * M-3864 R1: the buttons General's card offers on this machine, by the same rule the web's card and the server use: an
3128
+ * admin's press (Update when idle) needs pressHere, a picked time (Tonight) a machine that updates itself. No pre-flight
3129
+ * result yet: all three (the launch decides, as on the web).
3130
+ */
3131
+ updateChatCardActions(pre = this.updatePreflight) {
3132
+ if (!pre)
3133
+ return [...UPDATE_CHAT_CARD_ALL];
3134
+ return UPDATE_CHAT_CARD_ALL.filter(a => a === "not-now" || preflightAllows(pre, a === "tonight" ? "unattended" : "press"));
3135
+ }
2140
3136
  /** General's chat place for the card, or null (no General, no chat: a web-only fleet's banner says it). */
2141
3137
  updateChatCardPlace() {
2142
3138
  if (this.webOnlyPromptPlace())
@@ -2176,13 +3172,21 @@ export class FleetManager {
2176
3172
  // #4485 review 1: an offered card whose buttons are gone (a restart empties the nonce map; they also expire) is not
2177
3173
  // a usable card: it is marked expired and one with live buttons is posted.
2178
3174
  const live = !!posted?.nonce && this.pendingNonceButtons.get(posted.nonce)?.prefix === UPDATE_CARD_CALLBACK_PREFIX;
2179
- if (view && state === "offered" && view.installable && (!posted || posted.version !== view.version || posted.state !== "offered" || !live)) {
3175
+ // M-3864 R1: a card whose buttons the machine no longer allows (or newly allows) is posted again with the right ones.
3176
+ const actions = this.updateChatCardActions(), actionsKey = actions.join(",");
3177
+ // Prism #4584 (2): and the reason it gives for not updating here (another stop keeps Not now only but must say so).
3178
+ const blockingCheck = this.updatePreflight ? preflightBlocking(this.updatePreflight) : null;
3179
+ const blockingKey = blockingCheck ? preflightWords(blockingCheck, (key, ...args) => t(key, ...args)) : "";
3180
+ const sameActions = (posted?.actions ?? UPDATE_CHAT_CARD_ALL.join(",")) === actionsKey && (posted?.blocking ?? "") === blockingKey;
3181
+ if (view && state === "offered" && view.installable && (!posted || posted.version !== view.version || posted.state !== "offered" || !live || !sameActions)) {
2180
3182
  const place = this.updateChatCardPlace();
2181
3183
  if (!place)
2182
3184
  return;
2183
- if (posted) {
3185
+ // A refused press already edited its card to say why; that text stays (it is not called expired).
3186
+ if (posted && !(posted.refused && posted.version === view.version && !live)) {
2184
3187
  const old = posted.state === "offered" && posted.version === view.version && !live ? t("update.chatcard.expired")
2185
- : posted.version === view.version ? t("update.chatcard.cancelled", posted.version) : t("update.chatcard.replaced", view.version);
3188
+ : posted.state === "offered" && posted.version === view.version && !sameActions ? t("update.chatcard.replaced", view.version)
3189
+ : posted.version === view.version ? t("update.chatcard.cancelled", posted.version) : t("update.chatcard.replaced", view.version);
2186
3190
  await this.editUpdateChatCard(posted, old);
2187
3191
  }
2188
3192
  const version = view.version;
@@ -2190,7 +3194,7 @@ export class FleetManager {
2190
3194
  prefix: UPDATE_CARD_CALLBACK_PREFIX, alertType: "tip", instanceName: place.general, adapter: place.adapter, adapterId: place.adapterId,
2191
3195
  chatId: place.chatId, ...(place.threadId ? { threadId: place.threadId } : {}),
2192
3196
  message: this.updateChatCardText(view, current),
2193
- choices: [{ action: "when-idle", label: t("update.chatcard.when_idle") }, { action: "tonight", label: t("update.chatcard.tonight") }, { action: "not-now", label: t("update.chatcard.not_now") }],
3197
+ choices: actions.map(action => ({ action, label: t(action === "when-idle" ? "update.chatcard.when_idle" : action === "tonight" ? "update.chatcard.tonight" : "update.chatcard.not_now") })),
2194
3198
  expiredText: t("update.chatcard.expired"),
2195
3199
  timeoutMs: UPDATE_CHAT_CARD_MS,
2196
3200
  // #4485 review 2: the provider's own delivery address, kept per nonce as it is sent — a click may consume the
@@ -2209,12 +3213,14 @@ export class FleetManager {
2209
3213
  const sent = this.updateChatCardSent.get(nonce);
2210
3214
  const answered = this.updateChatCardAnswered.get(nonce);
2211
3215
  this.updateChatCardAnswered.delete(nonce);
2212
- this.writeUpdateChatCard({ version, state: answered ?? "offered", nonce: answered ? null : nonce, messageId: sent?.messageId ?? "",
3216
+ const refused = this.updateChatCardRefused.delete(nonce);
3217
+ this.writeUpdateChatCard({ version, state: answered ?? "offered", nonce: answered || refused ? null : nonce, messageId: sent?.messageId ?? "",
2213
3218
  chatId: sent?.chatId ?? place.chatId, ...((sent?.threadId ?? place.threadId) ? { threadId: sent?.threadId ?? place.threadId } : {}),
2214
- adapterId: place.adapterId, at: Date.now() });
2215
- // The card may have moved on while this was being posted (a newer version, an answer on the web): sync again.
3219
+ adapterId: place.adapterId, at: Date.now(), actions: actionsKey, ...(blockingKey ? { blocking: blockingKey } : {}), ...(refused ? { refused: true } : {}) });
3220
+ // The card may have moved on while this was being posted (a newer version, an answer on the web), or a press on it
3221
+ // was refused (the machine changed): sync again.
2216
3222
  const after = this.updateOfferView();
2217
- if (!answered && (after?.version !== version || (after?.state ?? "none") !== "offered"))
3223
+ if (refused || !answered && (after?.version !== version || (after?.state ?? "none") !== "offered"))
2218
3224
  this.updateChatCardAgain = true;
2219
3225
  return;
2220
3226
  }
@@ -2275,8 +3281,7 @@ export class FleetManager {
2275
3281
  await this.retireNonceButtons(entry, messageId, shownVersion && before && before.version !== shownVersion ? t("update.chatcard.replaced", before.version) : t("update.chatcard.expired"));
2276
3282
  return true;
2277
3283
  }
2278
- const tonight = (() => { const d = new Date(); d.setHours(22, 0, 0, 0); if (d.getTime() - Date.now() < 30 * 60_000)
2279
- d.setDate(d.getDate() + 1); return d.getTime(); })();
3284
+ const tonight = updateTonightAt(Date.now(), this.usageZone());
2280
3285
  const body = action === "tonight" ? { action: "pick-time", at: tonight } : { action: action };
2281
3286
  const by = updateAnswerLabel(data.username ?? "");
2282
3287
  let text;
@@ -2289,17 +3294,24 @@ export class FleetManager {
2289
3294
  }
2290
3295
  catch { /* unknown */ }
2291
3296
  const why = r.ok ? "" : ("key" in r.body && r.body.key !== "preflight" ? r.body.key : "error" in r.body ? r.body.error : r.body.key);
2292
- text = r.ok ? t("update.chatcard.by", this.updateChatCardText(view, current), by) : t("update.chatcard.refused", why || String(r.status));
3297
+ // M-3864 R1: the machine's pre-flight refused it: the reason in words (as the web and /update say it), never the key.
3298
+ const preflight = !r.ok && "key" in r.body && r.body.key === "preflight" ? r.body.preflight : null;
3299
+ const refusal = preflight ? preflightRefusal(preflight, action === "tonight" ? "unattended" : "press", (key, ...args) => t(key, ...args)) : null;
3300
+ text = r.ok ? t("update.chatcard.by", this.updateChatCardText(view, current), by) : refusal ?? t("update.chatcard.refused", why || String(r.status));
2293
3301
  const posted = this.readUpdateChatCard();
2294
3302
  const nextState = view?.state ?? "none";
2295
3303
  if (posted && posted.nonce === nonce) {
2296
3304
  // The press carries the message's own id where the post's record has none yet.
2297
- this.writeUpdateChatCard({ ...posted, state: nextState, nonce: null, messageId: posted.messageId || sent?.messageId || String(messageId ?? "") });
3305
+ this.writeUpdateChatCard({ ...posted, state: nextState, nonce: null, messageId: posted.messageId || sent?.messageId || String(messageId ?? ""), ...(r.ok ? {} : { refused: true }) });
2298
3306
  }
2299
3307
  else if (r.ok) {
2300
3308
  // The card is still being posted (its record is written when the post returns): it records this answer then.
2301
3309
  this.updateChatCardAnswered.set(nonce, nextState);
2302
3310
  }
3311
+ else {
3312
+ // Prism #4584 (1): a refusal too, so that post records its text as what the message says (not expired).
3313
+ this.updateChatCardRefused.add(nonce);
3314
+ }
2303
3315
  }
2304
3316
  catch (err) {
2305
3317
  text = t("update.chatcard.refused", err.message);
@@ -3621,16 +4633,21 @@ export class FleetManager {
3621
4633
  }
3622
4634
  }
3623
4635
  /** The agent's durable incarnation id (create: make one if none; else null). A changed fingerprint rotates it. */
3624
- hubAgentIncarnation(agent, cfg, create) {
4636
+ hubAgentIncarnation(agent, cfg, create, explicitBirth = false) {
3625
4637
  const fp = createHash("sha256").update(JSON.stringify([cfg.backend ?? "claude-code", cfg.working_directory, cfg.runtime ?? "", cfg.machine_id ?? "", ...(cfg.hubClassicIdentity ? [cfg.hubClassicIdentity] : [])])).digest("hex");
3626
4638
  const map = this.readHubIncarnations(), entry = Object.prototype.hasOwnProperty.call(map, agent) ? map[agent] : undefined;
3627
- if (entry && entry.fp === fp && typeof entry.id === "string")
4639
+ if (entry && entry.fp === fp && typeof entry.id === "string") {
4640
+ if (explicitBirth && !entry.requestWork && !entry.retired?.length) {
4641
+ map[agent] = { ...entry, requestWork: "pending" };
4642
+ return this.writeHubIncarnations(map) === "written" ? entry.id : null;
4643
+ }
3628
4644
  return entry.id;
4645
+ }
3629
4646
  if (!entry && !create)
3630
4647
  return null;
3631
- map[agent] = { id: randomUUID(), fp, ...(cfg.hubClassicIdentity ? { classic: true } : {}) };
4648
+ map[agent] = rotateHubAgentIncarnation(entry, fp, !!cfg.hubClassicIdentity, Date.now(), explicitBirth);
3632
4649
  // A rotation that could only clear the file still invalidated the old id durably; the new one is made next time.
3633
- return this.writeHubIncarnations(map) === "written" ? map[agent].id : null;
4650
+ return this.writeHubIncarnations(map) === "written" ? map[agent].id ?? null : null;
3634
4651
  }
3635
4652
  /**
3636
4653
  * Every configuration in force: rotate a recorded agent's incarnation when its backend/folder/runtime changed; drop
@@ -3646,6 +4663,16 @@ export class FleetManager {
3646
4663
  this.settleHubIncarnations();
3647
4664
  if (this.hubIncarnationsBroken)
3648
4665
  throw new Error("Hub agent incarnations cannot be written here");
4666
+ // Only a strict new configuration entry can mint first-birth evidence. A lazy token read,
4667
+ // a restart or a missing/corrupt incarnation/work file can never invent that transition.
4668
+ if (strict && this.savedFleetConfigSnapshot?.instances) {
4669
+ for (const agent of Object.keys(this.fleetConfig.instances))
4670
+ if (!Object.hasOwn(this.savedFleetConfigSnapshot.instances, agent)) {
4671
+ const config = this.hubAgentConfig(agent);
4672
+ if (config)
4673
+ this.hubAgentIncarnation(agent, config, true, true);
4674
+ }
4675
+ }
3649
4676
  if (!existsSync(this.hubIncarnationsPath()))
3650
4677
  return;
3651
4678
  for (const agent of Object.keys(this.readHubIncarnations())) {
@@ -3671,7 +4698,9 @@ export class FleetManager {
3671
4698
  const map = this.readHubIncarnations();
3672
4699
  if (!Object.prototype.hasOwnProperty.call(map, agent))
3673
4700
  return;
3674
- delete map[agent];
4701
+ if (!map[agent]?.id)
4702
+ return;
4703
+ map[agent] = forgetHubAgentIncarnation(map[agent]);
3675
4704
  this.writeHubIncarnations(map);
3676
4705
  }
3677
4706
  catch (err) {
@@ -3788,7 +4817,19 @@ export class FleetManager {
3788
4817
  * A Hub question to its representative agent: ordinary cross-instance delivery (idle gate, wake, retries), from the
3789
4818
  * reserved Hub sender with the Hub-issued correlation id. beforeInput runs immediately before the IPC hand-off.
3790
4819
  */
4820
+ requestContextHubAdmission;
4821
+ /** Installed as one of the publication's ingress owners, never from a tool or a question selector. */
4822
+ makeRequestContextHubAdmission(resolve) {
4823
+ return (input) => {
4824
+ const resolver = resolve(input.agent);
4825
+ if (!resolver)
4826
+ throw Error("Hub request input owner is unavailable");
4827
+ return resolver.capture(input);
4828
+ };
4829
+ }
3791
4830
  async deliverHubQuestion(input) {
4831
+ if (this.requestContextAdmission && !await this.requestContextAdmission.wait(() => !this.shuttingDown && input.stillCurrent()))
4832
+ return false;
3792
4833
  const { HUB_REPORT_TARGET } = await import("./hub/representative.js");
3793
4834
  const config = this.hubAgentConfig(input.agent);
3794
4835
  if (this.shuttingDown || !config)
@@ -3796,6 +4837,9 @@ export class FleetManager {
3796
4837
  // Windows agents run through their own runtime, which has no pre-input hook: not a P1 representative.
3797
4838
  if (isNativeExecInstance(config))
3798
4839
  return false;
4840
+ const scoped = requestContextPolicyInstalled(this.requestContextPolicy) ? this.requestContextHubAdmission?.(input) : undefined;
4841
+ if (requestContextPolicyInstalled(this.requestContextPolicy) && !scoped)
4842
+ throw Error("Hub request input admission is unavailable");
3799
4843
  const ipcMeta = {
3800
4844
  chat_id: "",
3801
4845
  message_id: `hubmsg-${input.correlationId.slice(4)}`,
@@ -3815,7 +4859,7 @@ export class FleetManager {
3815
4859
  // M-3660: the share's opt-out travels with the question; its daemon's hub_question_input then opens no window.
3816
4860
  if (input.contactLimit === false)
3817
4861
  ipcMeta.hub_contact_limit = "off";
3818
- const result = await this.deliverToInstance(input.agent, { type: "fleet_inbound", targetSession: input.agent, content: this.screenHubText(input.text), meta: ipcMeta }, { isCrossInstance: true, stillCurrent: input.stillCurrent, beforeInput: async () => {
4862
+ const result = await this.deliverToInstance(input.agent, { type: "fleet_inbound", targetSession: input.agent, content: this.screenHubText(input.text), meta: ipcMeta, ...(scoped ? { request_context_input_id: scoped.inputId } : {}) }, { isCrossInstance: true, stillCurrent: input.stillCurrent, beforeInput: async () => {
3819
4863
  const classic = this.isClassicInstance(input.agent);
3820
4864
  // A busy Classic room must finish its public turn first; never force a private question into that turn's queue.
3821
4865
  const idle = () => this.waitForInstanceIdle(input.agent, 0, this.lastDeliveryAt.get(input.agent) ?? 0, () => !input.stillCurrent());
@@ -3826,6 +4870,8 @@ export class FleetManager {
3826
4870
  if (generation)
3827
4871
  ipcMeta.hub_room_context_generation = generation;
3828
4872
  }
4873
+ if (scoped && !await scoped.waitBeforeInput())
4874
+ return false;
3829
4875
  if (!(await input.beforeInput()))
3830
4876
  return false;
3831
4877
  if (classic) {
@@ -4032,6 +5078,12 @@ export class FleetManager {
4032
5078
  hubRoomList(caller) {
4033
5079
  return this.hubAgentRooms?.rooms(caller) ?? Promise.resolve({ ok: false, code: "unavailable" });
4034
5080
  }
5081
+ hubRoomHistory(caller, room, options) {
5082
+ const policy = this.requestContextPolicy;
5083
+ if (!policy || requestContextInstalledMode(policy) !== "active")
5084
+ return Promise.resolve({ ok: false, code: "denied" });
5085
+ return this.hubAgentRooms?.history({ ...caller, current: () => this.requestContextPolicy === policy && requestContextInstalledMode(policy) === "active" && caller.current() }, room, options) ?? Promise.resolve({ ok: false, code: "unavailable" });
5086
+ }
4035
5087
  hubRoomMembers(caller, room, options) {
4036
5088
  return this.hubAgentRooms?.members(caller, room, options) ?? Promise.resolve({ ok: false, code: "unavailable" });
4037
5089
  }
@@ -4359,6 +5411,9 @@ export class FleetManager {
4359
5411
  /** M-3770 (#4480 §4): the last pre-flight — a diagnostic for the page; every launch proves its local checks again. */
4360
5412
  updatePreflight = null;
4361
5413
  updatePreflightRunning = null;
5414
+ /** M-3770 1.6: the fix buttons' answers by person, fix and Idempotency-Key (the last 32), and the one fix running at a time. */
5415
+ updateFixAnswers = new Map();
5416
+ updateFixChain = Promise.resolve();
4362
5417
  /** M-2738: a web start's Idempotency-Key → its answer (a retried request never starts a second update). */
4363
5418
  webUpdateStarts = new Map();
4364
5419
  /**
@@ -4490,7 +5545,7 @@ export class FleetManager {
4490
5545
  }
4491
5546
  /** #1770: an instance's web-files byte cap (a field, so a test can make it small). */
4492
5547
  webReplyMaxBytes = REPLY_FILES_MAX_BYTES;
4493
- /** #1682: the people seen on inbound messages (id → name), for the web chat's mention pills; bounded, in memory. */
5548
+ /** #1682: the people seen on inbound messages (id → name), for the web chat's mention pills; bounded; on disk since M-3827. */
4494
5549
  seenUsers = new SeenUsers();
4495
5550
  webPrefsStore;
4496
5551
  /** #1665: the web preferences kept on the host (<home>/web-prefs.json), read on first use. */
@@ -4969,6 +6024,7 @@ export class FleetManager {
4969
6024
  const baselines = this.settingsBaselineReader = new SettingsBaselines({ dataDir: this.dataDir, configPath: () => this.configPath,
4970
6025
  config: () => this.fleetConfig, current: () => [this.settingsGeneration, this.settingsRuntimeRevision, this.shuttingDown],
4971
6026
  generalLocation: input => this.previewGeneralLocation(input),
6027
+ requestContextControl: () => this.requestContextControl?.snapshot() ?? null,
4972
6028
  hubMembership: raw => hubMembershipSettings(raw),
4973
6029
  hubPageSharing: raw => hubPageSharingSettings(raw),
4974
6030
  guestDerivedScopes: () => this.guestDerivedScopes(),
@@ -5038,6 +6094,7 @@ export class FleetManager {
5038
6094
  current: () => current() && sessions === this.webSessions && !!this.webToken
5039
6095
  && sessions.isCurrent(record, tokenEpoch(this.webToken)) && (!exposure || exposure.isCurrent()) };
5040
6096
  }, baseline: () => baselines.read(), snapshot: () => baselines.snapshot(),
6097
+ requestContextControl: () => this.requestContextControl,
5041
6098
  selfConfirm: (req, id) => this.settingsSelfConfirmation(store, req, id),
5042
6099
  totp: { state: (req, id) => this.settingsTotpState(store, req, id), confirm: (req, id, code, digest) => this.settingsTotpConfirm(store, req, id, code, digest) },
5043
6100
  remote: req => this.settingsPageIsRemote(req),
@@ -6439,7 +7496,22 @@ export class FleetManager {
6439
7496
  const dbPath = join(this.dataDir, "delivery-outbox.db");
6440
7497
  let outbox;
6441
7498
  try {
6442
- outbox = new DeliveryOutbox(dbPath, this.managerBootId);
7499
+ const activated = readRequestContextBootState(this.dataDir);
7500
+ if (activated && !this.requestContextBoot) {
7501
+ const lease = captureProcessFleetLease(this.dataDir);
7502
+ if (!lease)
7503
+ throw Error("Request-context Fleet lease unavailable");
7504
+ const boot = new RequestContextBoot(activated, lease);
7505
+ this.requestContextBoot = boot;
7506
+ this.attachRequestContextAdmission(boot.publication.admission);
7507
+ this.requestContextPolicy = boot.policy;
7508
+ // Replaced only by the controlled installer: a legacy launch must never slip through startup recovery.
7509
+ this.prepareRequestContextStart = () => boot.requirePreparedOwner();
7510
+ }
7511
+ outbox = new DeliveryOutbox(dbPath, this.managerBootId, this.requestContextBoot ? {
7512
+ requestContextDispatchVersion: 1, requestContextRelayVersion: 1,
7513
+ requestContextRecoveryFence: this.requestContextBoot.recoveryCurrent,
7514
+ } : {});
6443
7515
  if (!this.deliveryOutboxRecovered) {
6444
7516
  const recovered = outbox.recoverForBoot(this.managerBootId);
6445
7517
  this.logger.info({ ...recovered }, "Recovered durable delivery outbox for this process boot");
@@ -6458,12 +7530,20 @@ export class FleetManager {
6458
7530
  }
6459
7531
  this.deliveryOutbox = outbox;
6460
7532
  this.deliveryOutboxRecovered = true;
7533
+ this.ensureRequestContextController();
6461
7534
  this.initializeWorkingRecovery(outbox);
6462
7535
  outbox.on("working_references", (names) => {
6463
7536
  for (const name of names)
6464
7537
  this.observeWorkingState(name, "obligations");
6465
7538
  });
6466
- outbox.on("admitted", () => { this.scheduleDeliveryOutboxPump(); this.wakeCoordinator?.kick(); });
7539
+ outbox.on("request_context_admitted", () => {
7540
+ if (this.requestContextAdmission) {
7541
+ this.requestContextAdmission.arrived();
7542
+ this.scheduleDeliveryOutboxPump();
7543
+ this.wakeCoordinator?.kick();
7544
+ }
7545
+ });
7546
+ outbox.on("admitted", () => { this.requestContextAdmission?.arrived(); this.scheduleDeliveryOutboxPump(); this.wakeCoordinator?.kick(); });
6467
7547
  outbox.on("state", (event) => {
6468
7548
  if (event.deliveryId) {
6469
7549
  const row = outbox.get(event.deliveryId);
@@ -6809,7 +7889,23 @@ export class FleetManager {
6809
7889
  makeRequestContextPolicy() {
6810
7890
  return { assert: input => {
6811
7891
  try {
6812
- return assertRequestContextOperation(input);
7892
+ const permit = assertRequestContextOperation(input);
7893
+ // Ordinary ingress is not administrator authority. Recheck the ORIGINAL actor for owner-only
7894
+ // tools on every call, including commit-point calls; demotion alone never adds a contact hold.
7895
+ if (permit.context && toolsFor("coordinator").has(permit.tool) && !toolsFor("worker").has(permit.tool)) {
7896
+ if (permit.context.ingress === "guest" || permit.context.ingress === "hub")
7897
+ throw new RequestContextPolicyError("settings");
7898
+ const actor = permit.context.initiatingActor;
7899
+ const adapter = actor.kind === "person" && actor.platform !== "hub" && actor.platform !== "host"
7900
+ ? [...this.adapters.values(), ...[...this.worlds.values()].map(world => world.adapter)].find(row => row.type === actor.platform) : undefined;
7901
+ const channel = actor.kind === "person" && actor.platform !== "hub"
7902
+ ? (this.fleetConfig?.channels ?? (this.fleetConfig?.channel ? [this.fleetConfig.channel] : [])).find(row => row.type === actor.platform) : undefined;
7903
+ const person = actor.kind === "person" && actor.platform !== "hub"
7904
+ ? { platform: actor.platform, adapterId: actor.platform === "host" ? "host" : adapter?.id ?? channel?.id ?? channel?.type ?? "", userId: actor.userId, label: actor.displayName ?? actor.userId } : null;
7905
+ if (!person?.adapterId || !this.contactAdminOf(permit.context.source.instance, person))
7906
+ throw new RequestContextPolicyError("settings");
7907
+ }
7908
+ return permit;
6813
7909
  }
6814
7910
  catch (error) {
6815
7911
  if (error instanceof RequestContextPolicyError) {
@@ -6820,6 +7916,357 @@ export class FleetManager {
6820
7916
  }
6821
7917
  } };
6822
7918
  }
7919
+ /** Existing Settings administrator scope. This only identifies a principal; it never bypasses per-change confirmation. */
7920
+ requestContextControl;
7921
+ requestContextShadow() {
7922
+ const box = this.deliveryOutbox, lease = captureProcessFleetLease(this.dataDir);
7923
+ return box.requestContextMigrationShadow({ owner: () => this.requestContextBoot?.owner.owner ?? lease?.id ?? null,
7924
+ policyEpoch: () => requestContextDigest([this.fleetConfig, this.settingsRuntimeRevision]), generation: name => { try {
7925
+ return this.contactGeneration(name);
7926
+ }
7927
+ catch {
7928
+ return null;
7929
+ } }, canManage: (name, actor) => this.contactAdminOf(name, actor) }).inspect();
7930
+ }
7931
+ requestContextBlockers() {
7932
+ const box = this.deliveryOutbox;
7933
+ if (!box || !this.fleetConfig)
7934
+ return [{ id: "owners", kind: "owners", labels: [], ownerCause: "update", action: "inspect" }];
7935
+ const label = (name) => this.fleetConfig?.instances[name]?.display_name ?? this.classicChannels?.getAll().find(row => row.instanceName === name)?.displayName ?? name;
7936
+ const state = box.requestContextInstallation().read(), out = [];
7937
+ if (!requestContextUpdateSettled(this.dataDir))
7938
+ out.push({ id: "update", kind: "update", labels: [], action: "inspect" });
7939
+ if (state && (!this.requestContextModes?.current() || !this.requestContextBoot?.publication.installed()) && state.mode !== "draining")
7940
+ out.push({ id: "installation", kind: "owners", labels: [], ownerCause: "update", action: "inspect" });
7941
+ if (!state) {
7942
+ const shadow = this.requestContextShadow();
7943
+ // S-272 (Sentinel's settlement split): each earlier ticket by what settles it. Pending: decided on Authorizations.
7944
+ // Approved and still being delivered (queued … retry_wait): waits for that delivery's own outcome. Approved with a delivery
7945
+ // that ended unconfirmed (e.g. uncertain: terminal, never changes again, Fable #4593), with no or a mismatched record, or
7946
+ // unreadable: nothing here can settle it (absence is never a proof of delivery), so it is named as such.
7947
+ const ids = (...dispositions) => shadow.tickets.filter(row => dispositions.includes(row.disposition)).map(row => row.id);
7948
+ const pending = ids("preserve-legacy-pending"), inflight = ids("legacy-inflight"), unsettled = ids("legacy-unconfirmed", "missing-receipt", "malformed"), named = new Set([...pending, ...inflight, ...unsettled]);
7949
+ if (pending.length)
7950
+ out.push({ id: "legacy-pending", kind: "legacy", labels: pending.slice(0, 64), action: "inspect" });
7951
+ if (inflight.length)
7952
+ out.push({ id: "legacy-inflight", kind: "legacy", labels: inflight.slice(0, 64) });
7953
+ if (unsettled.length)
7954
+ out.push({ id: "legacy-unsettled", kind: "legacy", labels: unsettled.slice(0, 64) });
7955
+ const rest = shadow.blockers.map(row => row.id).filter(id => !named.has(id));
7956
+ if (rest.length || !shadow.complete && !named.size)
7957
+ out.push({ id: "legacy", kind: "legacy", labels: rest.slice(0, 64), action: "inspect" });
7958
+ const inventory = box.requestContextControlInventory(), legacy = inventory.deliveries.filter(row => !row.root);
7959
+ if (legacy.length)
7960
+ out.push({ id: "legacy-deliveries", kind: "legacy", labels: legacy.map(row => `${label(row.source)} → ${label(row.target)}`).slice(0, 64) });
7961
+ const busy = [...this.daemons].filter(([name, daemon]) => { const row = daemon.requestContextLaunchObservation(); return row.observation.processStatus !== "running" || row.observation.executionState !== "idle" || row.pendingCalls || row.responseWaiters || row.queuedInputs || row.transcriptOpen || row.starting || row.stopping || this.requestContextPendingWork.count(name); }).map(([name]) => name);
7962
+ for (const row of WindowsAgents.requestContextOwnersOnDisk(this.dataDir)) {
7963
+ const daemon = row.instance ? this.daemons.get(row.instance) : undefined;
7964
+ // An owned idle persistent pane participates in the controlled relaunch. An exec or cold orphan does not.
7965
+ if (row.kind === "pane" && row.instance && daemon?.usesNativePane() && nativeAgentId(this.hubAgentConfig(row.instance)) === row.agentId)
7966
+ continue;
7967
+ const name = row.instance ?? row.agentId;
7968
+ if (!busy.includes(name))
7969
+ busy.push(name);
7970
+ }
7971
+ if (busy.length)
7972
+ out.push({ id: "busy", kind: "owners", labels: busy.map(label).slice(0, 64), agents: busy.map(id => ({ id, label: label(id) })).slice(0, 64), ownerCause: "work", action: "inspect" });
7973
+ const peers = this.captureRequestContextRuntimeSet(), old = peers.advertised();
7974
+ if (old.length)
7975
+ out.push({ id: "peers", kind: "peers", labels: peers.labels().filter(row => old.includes(row.id)).map(row => row.label).slice(0, 64), action: "inspect" });
7976
+ }
7977
+ else if (state.mode === "draining") {
7978
+ const inventory = box.requestContextControlInventory(box.requestContextInstallation().drainRoots());
7979
+ for (const row of inventory.recoveries)
7980
+ out.push({ id: `recovery:${requestContextDigest(row.pointer)}`, kind: "recovery", labels: [label(row.instance)], agents: [{ id: row.instance, label: label(row.instance) }], action: "stop-work" });
7981
+ for (const row of inventory.returns)
7982
+ out.push({ id: `return:${row.requestDeliveryId}`, kind: "returns", labels: [`${label(row.requester.instance)} → ${label(row.responder.instance)}`], action: "stop-waiting" });
7983
+ for (const row of inventory.tickets)
7984
+ out.push({ id: `ticket:${row.id}`, kind: "tickets", labels: [`${label(row.source)} → ${label(row.target)}`], action: "decline" });
7985
+ for (const row of inventory.deliveries)
7986
+ out.push({ id: `delivery:${row.id}`, kind: "work", labels: [`${label(row.source)} → ${label(row.target)}`], action: ["queued", "retry_wait"].includes(row.state) ? "withdraw" : "inspect" });
7987
+ if (!out.length && this.requestContextModes)
7988
+ for (const root of box.requestContextInstallation().drainRoots())
7989
+ if (this.requestContextModes.drain.inspectWork(root).blockers.length) {
7990
+ out.push({ id: `work:${root}`, kind: "work", labels: [], action: "inspect" });
7991
+ break;
7992
+ }
7993
+ }
7994
+ return [...out, ...this.requestContextCutoverErrors].slice(0, 128);
7995
+ }
7996
+ requestContextActivationLease() {
7997
+ const lease = captureProcessFleetLease(this.dataDir), prefix = installPrefixOf(fileURLToPath(new URL("..", import.meta.url)));
7998
+ if (!lease || !prefix)
7999
+ return null;
8000
+ const admission = createRequire(import.meta.url)("../launcher/install-admission.cjs");
8001
+ return acquireRequestContextActivationLease(this.dataDir, prefix, { pid: process.pid, processStart: admission.processStart, startTicks: admission.startTicks, bootId: admission.bootId, newToken: () => randomBytes(16).toString("hex"), now: () => new Date(), log: message => this.logger.info(message) }, lease);
8002
+ }
8003
+ ensureRequestContextController() {
8004
+ const box = this.deliveryOutbox, lease = captureProcessFleetLease(this.dataDir), manager = this.managerBootId;
8005
+ if (!box || !lease?.current() || this.requestContextControlBox === box)
8006
+ return;
8007
+ const current = () => !this.shuttingDown && lease.current() && this.managerBootId === manager && this.deliveryOutbox === box;
8008
+ const controller = new RequestContextController({ current, enableUnavailable: () => true, principal: (req, url) => this.requestContextControlPrincipal(req, url),
8009
+ permitContinuation: (req, res) => permitWebContinuation(req, res, { webToken: this.webToken, webSessions: this.webSessions }),
8010
+ base: () => ({ state: box.requestContextInstallation().read(), offer: captureRequestContextEnableOffer(this.dataDir), restartCount: box.requestContextInstallation().read() ? 0 : this.daemons.size, timeZone: this.usageZone() }),
8011
+ inspect: () => this.requestContextBlockers(),
8012
+ enable: async (actor, offer, decisionCurrent) => {
8013
+ this.requestContextCutoverErrors = [];
8014
+ if (this.requestContextBlockers().length)
8015
+ return;
8016
+ const update = this.requestContextActivationLease();
8017
+ if (!update) {
8018
+ this.requestContextCutoverErrors = [{ id: "update-lock", kind: "update", labels: [], action: "inspect" }];
8019
+ return;
8020
+ }
8021
+ let stage, preparingPeerLabels = [];
8022
+ try {
8023
+ if (!decisionCurrent() || !offer.current())
8024
+ throw Error("stale");
8025
+ const state = box.requestContextInstallation().read(), peers = this.captureRequestContextRuntimeSet();
8026
+ preparingPeerLabels = peers.labels().map(row => row.label).slice(0, 64);
8027
+ let peerProof;
8028
+ const transports = () => { try {
8029
+ const proof = peers.prove();
8030
+ if (!peerProof)
8031
+ peerProof = proof;
8032
+ return peerProof.current();
8033
+ }
8034
+ catch {
8035
+ return false;
8036
+ } };
8037
+ if (!state) {
8038
+ let shadow;
8039
+ const drained = () => { if (!current())
8040
+ return false; const next = this.requestContextShadow(); if (!shadow)
8041
+ shadow = next; return next.complete && !next.blockers.length && next.sha256 === shadow.sha256 && !box.requestContextControlInventory().deliveries.some(row => !row.root) && this.requestContextPendingWork.empty; };
8042
+ stage = await this.prepareRequestContextFirstOnAssembly(drained, transports, this.requestContextRootRetired, offer, actor.execution, peers.prepare);
8043
+ if (!decisionCurrent() || !update.current() || !stage.ready())
8044
+ throw Error("stale");
8045
+ actor.execution.commit(() => { box.requestContextInstallation().activate({ epoch: randomUUID(), owner: stage.boot.owner.owner, activatedAt: Date.now(), invalidates: [...offer.invalidates], offeredLatestDeadline: offer.latestDeadline }, stage.boot.owner, update, () => decisionCurrent() && offer.current() && stage.ready(), 0, stage.initialize); stage.publish(); });
8046
+ }
8047
+ else {
8048
+ if (state.mode !== "off" || !this.requestContextModes?.current())
8049
+ throw Error("unavailable");
8050
+ await peers.prepare();
8051
+ peerProof = peers.prove();
8052
+ const modes = this.requestContextModes;
8053
+ actor.execution.commit(() => { box.requestContextInstallation().activate({ epoch: randomUUID(), owner: modes.boot.owner.owner, activatedAt: Date.now(), invalidates: [...offer.invalidates], offeredLatestDeadline: offer.latestDeadline }, modes.boot.owner, update, () => decisionCurrent() && offer.current() && peerProof.current(), state.revision); modes.publish(() => peerProof.current()); });
8054
+ }
8055
+ this.postFleetSecurityNotice(requestContextEnabledNotice(getLocale()), `request-context:${box.requestContextInstallation().read().epoch}`);
8056
+ }
8057
+ catch (error) {
8058
+ this.logger?.warn?.({ err: error }, "Request-context enable did not finish");
8059
+ if (stage && box.requestContextInstallation().read() === null)
8060
+ await stage.rollback();
8061
+ const detail = error;
8062
+ if (box.requestContextInstallation().read() === null && detail.code?.startsWith("request-context-")) {
8063
+ this.requestContextCutoverErrors = [{ id: "preparation", kind: detail.code.includes("transport") ? "peers" : "owners", labels: detail.agent ? [detail.agent] : detail.code.includes("transport") ? preparingPeerLabels : [], ...(detail.agent ? { agents: [{ id: detail.agent, label: detail.agent }] } : {}), ownerCause: "update", action: "inspect" }];
8064
+ return;
8065
+ }
8066
+ throw error;
8067
+ }
8068
+ finally {
8069
+ update.release();
8070
+ }
8071
+ },
8072
+ disable: async (actor, decisionCurrent) => {
8073
+ if (!this.requestContextModes?.current() && this.requestContextBoot?.publication.heldUnpublished()) {
8074
+ await this.resetRequestContextUnpublishedPreparation();
8075
+ if (!decisionCurrent())
8076
+ throw Error("stale");
8077
+ await this.prepareRequestContextCapableBoot(this.requestContextRootRetired);
8078
+ }
8079
+ const modes = this.requestContextModes, state = box.requestContextInstallation().read();
8080
+ if (!modes?.current() || !state)
8081
+ throw Error("unavailable");
8082
+ actor.execution.commit(() => { if (state.mode === "active")
8083
+ modes.off.begin(state.revision, decisionCurrent); });
8084
+ this.scheduleRequestContextDrain();
8085
+ },
8086
+ resolve: (blocker, actor, decisionCurrent) => this.resolveRequestContextBlocker(blocker, actor, decisionCurrent),
8087
+ changed: () => { this.needsYou?.poke(); this.emitSseEvent("request-context-control", controller.snapshot()); this.emitSseEvent("needs", { items: this.needsYouItems() }); }, });
8088
+ this.requestContextControl = controller;
8089
+ this.requestContextControlBox = box;
8090
+ }
8091
+ async prepareRequestContextFutureOwners() {
8092
+ const factory = this.requestContextFactoryOwner;
8093
+ if (!factory?.current())
8094
+ throw Error("Request owner factory unavailable");
8095
+ const names = [...new Set([...Object.keys(this.fleetConfig?.instances ?? {}), ...(this.classicChannels?.getAll() ?? []).map(row => row.instanceName)])];
8096
+ for (const name of names)
8097
+ if (!this.daemons.has(name)) {
8098
+ const config = this.hubAgentConfig(name);
8099
+ if (!config)
8100
+ throw Error("Request owner configuration unavailable");
8101
+ await factory.beforeStart(name, config);
8102
+ }
8103
+ }
8104
+ requestContextOwnersReady() {
8105
+ try {
8106
+ const factory = this.requestContextFactoryOwner, box = this.deliveryOutbox;
8107
+ if (!factory?.current() || !box)
8108
+ return false;
8109
+ for (const [name, daemon] of this.daemons)
8110
+ if (!factory.bound(name, daemon) || daemon.requestContextHelperReadiness()?.ready !== true)
8111
+ return false;
8112
+ const names = [...new Set([...Object.keys(this.fleetConfig?.instances ?? {}), ...(this.classicChannels?.getAll() ?? []).map(row => row.instanceName)])];
8113
+ return names.every(name => box.requestContextWork.read(name)?.incarnation === this.contactGeneration(name));
8114
+ }
8115
+ catch {
8116
+ return false;
8117
+ }
8118
+ }
8119
+ /** A clock selects old candidates; it never proves completion, delivery, or launch retirement. */
8120
+ collectRequestContextRoots() {
8121
+ const modes = this.requestContextModes, box = this.deliveryOutbox;
8122
+ if (this.shuttingDown || !box?.isOpen || !modes?.current() || !modes.boot.publication.installed())
8123
+ return;
8124
+ for (const candidate of box.requestContextRetirementCandidates()) {
8125
+ let epoch;
8126
+ try {
8127
+ epoch = candidate.epoch ? modes.drain.resume(candidate.root, candidate.epoch) : modes.drain.fence(candidate.root);
8128
+ const proof = modes.drain.prove(candidate.root, epoch);
8129
+ this.requestContextRetirementProofs.set(candidate.root, proof);
8130
+ modes.retireRoot(candidate.root);
8131
+ }
8132
+ catch (error) {
8133
+ this.logger.debug?.({ root: candidate.root, err: error.message }, "Request root remains retained");
8134
+ // Failed or busy candidates stay retained and reopen only while their exact root still exists.
8135
+ if (epoch && box.requestContext(candidate.root))
8136
+ try {
8137
+ modes.drain.release(candidate.root, epoch);
8138
+ }
8139
+ catch { /* still fenced, never guessed open */ }
8140
+ }
8141
+ finally {
8142
+ this.requestContextRetirementProofs.delete(candidate.root);
8143
+ }
8144
+ }
8145
+ }
8146
+ scheduleRequestContextDrain() {
8147
+ if (this.requestContextDrainTimer || this.shuttingDown)
8148
+ return;
8149
+ this.requestContextDrainTimer = setTimeout(() => {
8150
+ this.requestContextDrainTimer = undefined;
8151
+ const modes = this.requestContextModes, state = this.deliveryOutbox?.requestContextInstallation().read();
8152
+ if (!modes?.current() || !state || state.mode !== "draining")
8153
+ return;
8154
+ try {
8155
+ modes.off.advance(state.revision);
8156
+ }
8157
+ catch (error) {
8158
+ this.logger.warn({ err: error.message }, "Request-context drain remains held");
8159
+ }
8160
+ this.requestContextControl?.changed();
8161
+ if (this.deliveryOutbox?.requestContextInstallation().read()?.mode === "draining")
8162
+ this.scheduleRequestContextDrain();
8163
+ }, 500);
8164
+ this.requestContextDrainTimer.unref?.();
8165
+ }
8166
+ async resolveRequestContextBlocker(blocker, actor, current) {
8167
+ const box = this.deliveryOutbox, modes = this.requestContextModes, state = box?.requestContextInstallation().read();
8168
+ if (!box || !modes?.current() || state?.mode !== "draining" || !current())
8169
+ throw Error("stale");
8170
+ const inventory = box.requestContextControlInventory(box.requestContextInstallation().drainRoots());
8171
+ if (blocker.id.startsWith("ticket:")) {
8172
+ if (!actor.person || !this.requestContactCardsPort)
8173
+ throw Error("owner-required");
8174
+ const id = blocker.id.slice(7), principal = { person: actor.person, binding: actor.binding, verified: true, current };
8175
+ const card = this.requestContactCardsPort.read(id, principal);
8176
+ actor.execution.mutate(() => this.requestContactCardsPort.decide(id, { snapshot: card.snapshot, decision: "decline" }, principal));
8177
+ }
8178
+ else if (blocker.id.startsWith("delivery:")) {
8179
+ const id = blocker.id.slice(9), row = box.get(id);
8180
+ if (!inventory.deliveries.some(value => value.id === id) || !row)
8181
+ throw Error("stale");
8182
+ actor.execution.mutate(() => box.withdrawRequestContextDelivery(id, requestContextDigest(row), current));
8183
+ }
8184
+ else if (blocker.id.startsWith("return:")) {
8185
+ const id = blocker.id.slice(7), row = inventory.returns.find(value => value.requestDeliveryId === id);
8186
+ if (!row)
8187
+ throw Error("stale");
8188
+ actor.execution.mutate(() => box.closeRequestContextReturn(id, requestContextDigest(row), getLocale() === "zh-TW" ? "擁有者已結束這次等候;不再等候這則回覆。" : "The owner stopped waiting for this reply.", () => current() && this.contactGeneration(row.requester.instance) === row.requester.incarnation));
8189
+ this.scheduleDeliveryOutboxPump();
8190
+ }
8191
+ else if (blocker.id.startsWith("recovery:")) {
8192
+ const row = inventory.recoveries.find(value => `recovery:${requestContextDigest(value.pointer)}` === blocker.id);
8193
+ if (!row)
8194
+ throw Error("stale");
8195
+ await this.stopRequestContextWork(row.root, actor, current);
8196
+ actor.execution.mutate(() => box.requestContextRecovery.clear(row.pointer, () => current() && modes.drain.inspectWork(row.root).blockers.every(value => value === "recovery-pointer")));
8197
+ }
8198
+ else
8199
+ throw Error("invalid-request");
8200
+ this.scheduleRequestContextDrain();
8201
+ }
8202
+ async stopRequestContextWork(root, actor, current) {
8203
+ const modes = this.requestContextModes;
8204
+ if (!modes?.current() || !current())
8205
+ throw Error("stale");
8206
+ const nativeStops = this.fleetWindowsRuntime?.requestContextStops(root) ?? [];
8207
+ for (const stop of nativeStops) {
8208
+ if (!current())
8209
+ throw Error("stale");
8210
+ actor.execution.mutate(() => stop.stop(current));
8211
+ }
8212
+ for (const [name, daemon] of [...this.daemons]) {
8213
+ if (daemon.requestContextTurnSnapshot()?.context.ref.rootContextId !== root)
8214
+ continue;
8215
+ const retirement = await daemon.captureRequestContextRetirement();
8216
+ if (!current() || this.daemons.get(name) !== daemon)
8217
+ throw Error("stale");
8218
+ await actor.execution.stopTarget(name, advance => this.lifecycle.stopIfCurrent(name, daemon, advance));
8219
+ if (!current() || !await retirement.retired())
8220
+ throw Error("unavailable");
8221
+ // The future-start factory keeps the stored work/context; it removes only this positively retired live owner.
8222
+ if (!this.requestContextRetireOwner)
8223
+ throw Error("unavailable");
8224
+ await this.requestContextRetireOwner(name, daemon, retirement.retired);
8225
+ }
8226
+ // The wait bounds the HTTP action; only the owned run's positive completion can clear its pointer.
8227
+ const until = performance.now() + 30_000;
8228
+ while (nativeStops.some(stop => !stop.retired())) {
8229
+ if (!current())
8230
+ throw Error("stale");
8231
+ if (performance.now() >= until)
8232
+ throw Error("unavailable");
8233
+ await new Promise(resolve => setTimeout(resolve, 25));
8234
+ }
8235
+ }
8236
+ async requestContextOwnerStopped(name, daemon, retired) {
8237
+ if (!this.requestContextRetireOwner)
8238
+ return;
8239
+ if (await retired())
8240
+ await this.requestContextRetireOwner(name, daemon, retired);
8241
+ else
8242
+ this.logger.warn({ name }, "Stopped request owner remains held until launch and IPC retirement are proven");
8243
+ }
8244
+ requestContextRetireOwner;
8245
+ requestContextControlPrincipal(req, url) {
8246
+ const resolve = () => {
8247
+ const verdict = evaluateWebRequest(req, url, this.webToken, this.webSessions, { touch: false });
8248
+ if (verdict.kind === "reject" && (verdict.reason === "csrf" || verdict.reason === "cross-site"))
8249
+ throw Error(verdict.reason);
8250
+ if (verdict.kind !== "allow" || verdict.via !== "session" || verdict.session.tier !== "admin")
8251
+ return null;
8252
+ if (hostSessionHere(verdict.session, req))
8253
+ return { binding: requestContextDigest(["host-here", verdict.session.handle, verdict.session.tokenEpoch]), verified: true, person: { platform: "host", adapterId: "host", userId: "operator", label: "Operator" } };
8254
+ const contact = this.requestContactPrincipal(req, url);
8255
+ if (!contact || !contact.current() || (contact.person.platform === "host" ? !this.isWebOnlyFleet() : this.adminGate(contact.person.userId, contact.person.adapterId) !== "ok"))
8256
+ return null;
8257
+ return { binding: requestContextDigest([contact.binding, contact.person.platform, contact.person.userId]), verified: contact.verified, person: contact.person };
8258
+ };
8259
+ const first = resolve();
8260
+ if (!first)
8261
+ return null;
8262
+ return Object.freeze({ ...first, current: () => { try {
8263
+ const now = resolve();
8264
+ return !!now && now.binding === first.binding && now.verified === first.verified;
8265
+ }
8266
+ catch {
8267
+ return false;
8268
+ } } });
8269
+ }
6823
8270
  requestContactPrincipal(req, url) {
6824
8271
  const resolve = () => {
6825
8272
  const verdict = evaluateWebRequest(req, url, this.webToken, this.webSessions, { touch: false });
@@ -6831,7 +8278,7 @@ export class FleetManager {
6831
8278
  if (!identity)
6832
8279
  return null;
6833
8280
  const authority = this.webAuthority({ session: verdict.session, gateway: !!gatewayRequestContext(req), peer: gatewayRequestContext(req) ? gatewayRequestContext(req).named ? "named_link" : "quick_link" : classifyWebPeer(req) }).authority;
6834
- const action = this.contactActor(req, url), person = { platform: identity.platform, adapterId: identity.adapter_id, userId: identity.user_id, label: identity.user_id };
8281
+ const action = this.contactActor(req, url), person = { platform: identity.platform, adapterId: identity.adapter_id, userId: identity.user_id, label: this.contactPersonLabel(identity.adapter_id, identity.user_id) };
6835
8282
  const verified = !!action && sameContactPerson(action, person);
6836
8283
  const binding = JSON.stringify([identity.session_handle, authority.authority_epoch, authority.kind === "web-verified" ? authority.session?.authorized_at : null]);
6837
8284
  return { person, binding, verified };
@@ -6854,14 +8301,236 @@ export class FleetManager {
6854
8301
  */
6855
8302
  requestContactCardsPort = null;
6856
8303
  installRequestContactCards(cards) { this.requestContactCardsPort = cards; }
8304
+ /** Only a validated accepted room can supply a current room-policy override. Unknown recovery is not a Free-room proof. */
8305
+ requestContextSourceRoomRestricted(root) {
8306
+ try {
8307
+ if (!["free-room", "restricted-room"].includes(root.ingress))
8308
+ return undefined;
8309
+ const id = /^human:hmsg-([a-f0-9-]{36})$/.exec(root.rootEvidenceRef)?.[1];
8310
+ if (!id)
8311
+ return undefined;
8312
+ const captured = this.deliveryOutbox?.requestContextHumans.read(id);
8313
+ if (!captured || requestContextDigest(captured.context) !== requestContextDigest(root))
8314
+ return undefined;
8315
+ const basis = this.deliveryOutbox.requestContextHumans.classicBasis(id);
8316
+ if (!basis && (captured.route.kind !== "web" || root.initiatingActor.kind === "unknown"))
8317
+ return undefined;
8318
+ const room = this.contactRoom(root.source.instance);
8319
+ return room ? room.restrictedMode === true : undefined;
8320
+ }
8321
+ catch {
8322
+ return undefined;
8323
+ }
8324
+ }
8325
+ /** Re-run the original synchronous admission basis. It supplies no role or go-ahead authority. */
8326
+ requestContextNativeAdmissionCurrent(context) {
8327
+ try {
8328
+ const root = this.deliveryOutbox?.requestContext(context.ref.rootContextId);
8329
+ if (!root)
8330
+ return false;
8331
+ const source = root.source.instance, room = this.contactRoom(source);
8332
+ if (!Object.hasOwn(this.fleetConfig?.instances ?? {}, source) && !room && !this.daemons?.has(source))
8333
+ return false;
8334
+ if (this.contactGeneration(source) !== root.source.incarnation)
8335
+ return false;
8336
+ if ("platform" in root.initiatingActor && root.initiatingActor.platform === "hub")
8337
+ return true; // Hub's owning current-share/resource check is separate.
8338
+ const match = /^human:hmsg-([a-f0-9-]{36})$/.exec(root.rootEvidenceRef);
8339
+ // Unproved recovery has no human route to borrow. An actual unknown web input must still
8340
+ // recheck its own session below; being unidentified is never a session-revocation bypass.
8341
+ if (!match)
8342
+ return root.initiatingActor.kind === "unknown" && root.ingress !== "owner";
8343
+ if (root.initiatingActor.kind !== "person" && root.initiatingActor.kind !== "unknown")
8344
+ return false;
8345
+ const captured = this.deliveryOutbox.requestContextHumans.read(match[1]);
8346
+ if (!captured || requestContextDigest(captured.context) !== requestContextDigest(root))
8347
+ return false;
8348
+ const actor = root.initiatingActor;
8349
+ if (captured.route.kind === "web") {
8350
+ const session = captured.route.sessionHandle ? this.webSessions?.findByHandle(captured.route.sessionHandle) : null;
8351
+ if (!session || !this.webToken || !this.webSessions?.isCurrent(session, tokenEpoch(this.webToken)))
8352
+ return false;
8353
+ if (actor.kind === "person") {
8354
+ const identity = this.webSessionIdentity(session);
8355
+ if (!identity || identity.platform !== actor.platform || identity.user_id !== actor.userId)
8356
+ return false;
8357
+ }
8358
+ return root.ingress === "guest" ? session.tier === "guest" && !!session.owner && this.fleetConfig?.web?.guests?.enabled === true && this.guestScope(session.owner).has(source) : session.tier === "admin";
8359
+ }
8360
+ if (actor.kind !== "person")
8361
+ return false;
8362
+ const basis = this.deliveryOutbox.requestContextHumans.classicBasis(match[1]);
8363
+ if (basis) {
8364
+ if (!room || room.channelId !== basis.roomId || (room.adapterId ?? this.contactAdapter(source)?.id) !== basis.adapterId || !this.classicChannels?.isClassicChannel(basis.roomId, basis.adapterId))
8365
+ return false;
8366
+ // These are messages inside a registered room. Guild/group/user allowlists gate creation,
8367
+ // and Classic admins may bypass them; applying those lists here would tighten Free rooms.
8368
+ return this.classicChannels.getInstanceByChannel(basis.roomId, basis.adapterId) === source;
8369
+ }
8370
+ if (room)
8371
+ return false; // No historical guild/group/user basis means no guessed Classic admission.
8372
+ if (actor.platform === "host")
8373
+ return false; // Host identity is admitted only through its bound web session.
8374
+ const adapter = this.contactAdapter(source);
8375
+ if (!adapter || adapter.type !== actor.platform)
8376
+ return false;
8377
+ const person = { platform: actor.platform, adapterId: adapter.id, userId: actor.userId, label: actor.userId };
8378
+ if (this.contactAdminOf(source, person))
8379
+ return true;
8380
+ const access = this.worlds.get(adapter.id)?.accessManager ?? (adapter.id === this.getPrimaryAdapterId() ? this.accessManager : null);
8381
+ return access?.isAllowed(actor.userId) === true;
8382
+ }
8383
+ catch {
8384
+ return false;
8385
+ }
8386
+ }
8387
+ /** Off preserves the owner's current Hub contact setting. Elapsed contact-window time grants nothing. */
8388
+ requestContextHubOwnerAllowsContact(context) {
8389
+ try {
8390
+ const root = this.deliveryOutbox?.requestContext(context.ref.rootContextId), actor = root?.initiatingActor;
8391
+ if (!root || root.ingress !== "hub" || !actor || !("platform" in actor) || actor.platform !== "hub" || this.contactGeneration(root.source.instance) !== root.source.incarnation
8392
+ || this.hubMemberPairingApi?.boundHub()?.hubId !== actor.hubId)
8393
+ return false;
8394
+ const view = this.hubMemberExposureApi?.list().find(row => row.agent === root.source.instance);
8395
+ return view?.state === "published" && view.enforceable && !view.reason && view.contactLimit === false;
8396
+ }
8397
+ catch {
8398
+ return false;
8399
+ }
8400
+ }
8401
+ /** Only the receipt's original registered C parent may cross the Draining gate. */
8402
+ requestContextHumanContinuation(instance, receiptId) {
8403
+ const boot = this.requestContextBoot, box = this.deliveryOutbox, daemon = this.daemons.get(instance);
8404
+ if (!boot || !box || !daemon)
8405
+ return;
8406
+ const accepted = box.requestContextHumans.read(receiptId), mapped = accepted?.steer, owner = daemon.captureRequestContextOwner();
8407
+ if (!accepted || !mapped || !owner || owner.workGeneration !== mapped.workGeneration)
8408
+ return;
8409
+ const actor = mapped.actor;
8410
+ if (actor.kind !== "person" || actor.platform === "hub")
8411
+ throw Error("Steer continuation actor unavailable");
8412
+ const valid = () => {
8413
+ try {
8414
+ const live = box.getHumanReceipt(receiptId), actual = daemon.captureRequestContextOwner(), parent = box.requestContext(mapped.parentContextId);
8415
+ const adapter = actor.platform === "host" ? "host" : this.contactAdapter(instance)?.id;
8416
+ return this.requestContextBoot === boot && this.deliveryOutbox === box && this.daemons.get(instance) === daemon && !this.shuttingDown
8417
+ && requestContextDigest(actual) === requestContextDigest(owner) && !!parent && requestContextDigest(parent) === mapped.parentSha256
8418
+ && !!live && live.state === "queued" && live.target_instance === instance && live.manager_boot_id === this.managerBootId
8419
+ && (live.owner_key === null || live.owner_key === this.humanReceiptOwner(instance, daemon))
8420
+ && !!adapter && this.contactAdminOf(instance, { platform: actor.platform, adapterId: adapter, userId: actor.userId, label: actor.userId })
8421
+ && this.requestContextNativeAdmissionCurrent(accepted.context);
8422
+ }
8423
+ catch {
8424
+ return false;
8425
+ }
8426
+ };
8427
+ if (!valid())
8428
+ throw Error("Steer continuation owner changed");
8429
+ return boot.publication.continuation(mapped.rootContextId, valid);
8430
+ }
8431
+ /** One installed gate host for direct sends and same-card decisions. No lifetime origin or return-release lookup.
8432
+ * Currentness belongs to the installation/process, not a browser, transport-readiness poll or old Hub timer.
8433
+ */
8434
+ makeRequestContextContactHost(current, rootRetired, mode) {
8435
+ const incarnation = (name) => { try {
8436
+ return current() ? this.contactGeneration(name) : null;
8437
+ }
8438
+ catch {
8439
+ return null;
8440
+ } };
8441
+ const person = (actor) => {
8442
+ if (actor.kind !== "person" || actor.platform === "hub")
8443
+ return null;
8444
+ if (actor.platform === "host")
8445
+ return actor.userId === "operator" ? { platform: "host", adapterId: "host", userId: "operator", label: "Operator" } : null;
8446
+ const adapter = [...this.adapters.values(), ...[...this.worlds.values()].map(world => world.adapter)].find(row => row.type === actor.platform);
8447
+ const configured = (this.fleetConfig?.channels ?? (this.fleetConfig?.channel ? [this.fleetConfig.channel] : [])).find(row => row.type === actor.platform);
8448
+ const adapterId = adapter?.id ?? configured?.id ?? configured?.type;
8449
+ return adapterId ? { platform: actor.platform, adapterId, userId: actor.userId, label: actor.displayName ?? actor.userId } : null;
8450
+ };
8451
+ const manage = (name, actor) => current() && incarnation(name) !== null && this.contactAdminOf(name, actor);
8452
+ return {
8453
+ incarnation, person, adminOf: manage, canManage: manage,
8454
+ canDecide: (name, actor) => {
8455
+ if (!manage(name, actor))
8456
+ return false;
8457
+ const policy = this.deliveryOutbox.contactAuthorizations.policySnapshot(name, incarnation(name));
8458
+ return actor.platform === "host" && actor.userId === "operator" || (policy.approvers ?? this.contactDefaultApprovers(name)).some(value => sameContactPerson(value, actor));
8459
+ },
8460
+ current: (context, binding) => current() && incarnation(binding.source.instance) === binding.source.incarnation
8461
+ && incarnation(binding.target.instance) === binding.target.incarnation && this.requestContextNativeAdmissionCurrent(context),
8462
+ sourceRestricted: root => this.requestContextSourceRoomRestricted(root),
8463
+ rootRetired: root => current() && rootRetired(root),
8464
+ hubRelayAllowed: (context, binding, delivery) => {
8465
+ if (!current() || !assertRequestHubContactImage(context, binding, delivery))
8466
+ return false;
8467
+ const installed = mode();
8468
+ return installed === "active" || installed === "draining" || installed === "off" && this.requestContextHubOwnerAllowsContact(context);
8469
+ },
8470
+ accepted: () => { this.scheduleDeliveryOutboxPump(); this.needsYou?.poke(); },
8471
+ };
8472
+ }
8473
+ /** One publication owns every live ingress. These forwarding ports never cache a mode, owner or current turn. */
8474
+ requestContactApi;
8475
+ bindRequestContextServingPublication(boot) {
8476
+ if (this.requestContextBoot !== boot || this.requestContextAdmission !== boot.publication.admission)
8477
+ throw Error("Request serving publication owner differs");
8478
+ const serving = (execution = false) => {
8479
+ if (this.requestContextBoot !== boot || this.requestContextAdmission !== boot.publication.admission)
8480
+ throw Error("Request serving publication changed");
8481
+ const publication = execution ? boot.publication.captureExecution() : boot.publication.capture();
8482
+ const ports = publication?.ports.serving;
8483
+ if (!ports || !ports.current())
8484
+ throw Error("Request serving publication unavailable");
8485
+ return ports;
8486
+ };
8487
+ this.requestContextPolicy = boot.policy;
8488
+ this.requestContextRelay = { admit: (input, operation, current) => serving(operation.admission?.coverage === "covered").relay.admit(input, operation, current) };
8489
+ // Record-only identity admission is not a pane write. New input still waits at the shared gate.
8490
+ this.requestContextHumanAdmission = (...args) => boot.publication.heldUnpublished() && this.requestContextModes?.current() ? this.requestContextModes.recordHuman(...args) : serving(true).human(...args);
8491
+ this.requestContextHubAdmission = input => serving().hub(input);
8492
+ this.requestContactApi = {
8493
+ principal: (req, url) => this.requestContactPrincipal(req, url), permitContinuation: (req, res) => permitWebContinuation(req, res, { webToken: this.webToken, webSessions: this.webSessions }),
8494
+ needs: actor => serving(true).api.needs?.(actor) ?? [], canRead: (card, actor) => serving(true).api.canRead(card, actor),
8495
+ read: (id, actor) => serving(true).api.read(id, actor), list: (filter, actor) => serving(true).api.list(filter, actor), decide: (id, input, actor) => serving(true).api.decide(id, input, actor),
8496
+ };
8497
+ this.requestContactCardsPort = {
8498
+ canRead: (card, actor) => serving(true).cards.canRead(card, actor), read: (id, actor) => serving(true).cards.read(id, actor),
8499
+ needs: actor => serving(true).cards.needs(actor), list: (filter, actor) => serving(true).cards.list(filter, actor),
8500
+ decide: (id, input, actor) => serving(true).cards.decide(id, input, actor), prepareForNativePost: (id, current) => serving(true).cards.prepareForNativePost(id, current),
8501
+ };
8502
+ }
8503
+ /** Construct only inside the capable activation initializer or capable boot. Nothing is published here. */
8504
+ prepareRequestContextServingOwners(current, rootRetired, resolveHub, mode) {
8505
+ const box = this.deliveryOutbox;
8506
+ if (!box || !current())
8507
+ throw Error("Request-context serving owner unavailable");
8508
+ const host = this.makeRequestContextContactHost(current, rootRetired, mode), gate = box.requestHubContactGate(host);
8509
+ const relay = makeRequestContextRelay(box, host, gate), cards = this.makeRequestContactCards(host, gate), api = this.makeRequestContactApi(cards);
8510
+ const human = this.makeRequestContextHumanAdmission(), hub = this.makeRequestContextHubAdmission(resolveHub), policy = this.makeRequestContextPolicy();
8511
+ const admitted = { admit: (...args) => {
8512
+ if (!current())
8513
+ throw new RequestContextPolicyError("stale");
8514
+ try {
8515
+ return relay.admit(...args);
8516
+ }
8517
+ catch (error) {
8518
+ if (error instanceof ContactHeldError)
8519
+ this.contactService().host.changed?.(args[0].targetInstance, error.result.authorization_id);
8520
+ throw error;
8521
+ }
8522
+ } };
8523
+ return Object.freeze({ policy, relay: admitted, cards, api, human, hub, gate, current });
8524
+ }
6857
8525
  /** Dormant assembly for L and synthetic rigs; merely defining this method installs no service or route authority. */
6858
- makeRequestContactCards() {
8526
+ makeRequestContactCards(gateHost, gate) {
6859
8527
  this.ensureDeliveryOutbox();
6860
8528
  const outbox = this.deliveryOutbox, legacy = this.contactService();
6861
8529
  const names = () => [...new Set([...Object.keys(this.fleetConfig?.instances ?? {}), ...(this.classicChannels?.getAll() ?? []).map(room => room.instanceName)])].sort();
6862
8530
  const manage = (name, person) => this.contactAdminOf(name, person);
6863
8531
  const cards = outbox.requestContactCards({
6864
- current: (_context, binding) => this.contactGeneration(binding.source.instance) === binding.source.incarnation && this.contactGeneration(binding.target.instance) === binding.target.incarnation && !this.hubContactRestricted(binding.source.instance),
8532
+ current: (context, binding) => this.contactGeneration(binding.source.instance) === binding.source.incarnation && this.contactGeneration(binding.target.instance) === binding.target.incarnation
8533
+ && (!requestContextPolicyInstalled(this.requestContextPolicy) || this.requestContextNativeAdmissionCurrent(context)) && !this.hubContactRestricted(binding.source.instance),
6865
8534
  generation: name => { try {
6866
8535
  return this.contactGeneration(name);
6867
8536
  }
@@ -6871,6 +8540,7 @@ export class FleetManager {
6871
8540
  canManage: manage, canDecide: (name, person) => { if (!manage(name, person))
6872
8541
  return false; const policy = legacy.host.store.policySnapshot(name, this.contactGeneration(name)); return person.platform === "host" && person.userId === "operator" || (policy.approvers ?? legacy.host.defaultApprovers(name)).some(row => sameContactPerson(row, person)); },
6873
8542
  adminOf: (name, person) => this.contactAdminOf(name, person),
8543
+ sourceRestricted: root => this.requestContextSourceRoomRestricted(root),
6874
8544
  person: actor => {
6875
8545
  if (actor.kind !== "person" || actor.platform === "hub")
6876
8546
  return null;
@@ -6900,11 +8570,12 @@ export class FleetManager {
6900
8570
  }
6901
8571
  this.needsYou?.poke();
6902
8572
  },
6903
- });
8573
+ ...gateHost,
8574
+ }, gate);
6904
8575
  return cards;
6905
8576
  }
6906
- makeRequestContactApi() {
6907
- const cards = this.makeRequestContactCards();
8577
+ makeRequestContactApi(given) {
8578
+ const cards = given ?? this.makeRequestContactCards();
6908
8579
  return { principal: (req, url) => this.requestContactPrincipal(req, url), needs: actor => cards.needs(actor), permitContinuation: (req, res) => permitWebContinuation(req, res, { webToken: this.webToken, webSessions: this.webSessions }), canRead: (card, actor) => cards.canRead(card, actor), read: (id, actor) => cards.read(id, actor), list: (filter, actor) => cards.list(filter, actor), decide: (id, input, actor) => cards.decide(id, input, actor) };
6909
8580
  }
6910
8581
  contactActor(req, url) {
@@ -6921,7 +8592,21 @@ export class FleetManager {
6921
8592
  const adapter = this.adapters.get(actor.adapter_id);
6922
8593
  if (!adapter || (adapter.type !== "discord" && adapter.type !== "telegram"))
6923
8594
  return null;
6924
- return { platform: adapter.type, adapterId: actor.adapter_id, userId: actor.user_id, label: actor.user_id };
8595
+ return { platform: adapter.type, adapterId: actor.adapter_id, userId: actor.user_id, label: this.contactPersonLabel(actor.adapter_id, actor.user_id) };
8596
+ }
8597
+ /**
8598
+ * M-3864 R7: what Permissions and the history call a web-verified admin. That is their name as the rest of the dashboard
8599
+ * says it (their own, else their chat account's), never the bare account id. Display only: a person is matched by
8600
+ * platform and id (sameContactPerson).
8601
+ */
8602
+ contactPersonLabel(adapterId, userId) {
8603
+ try {
8604
+ const name = this.webPerson({ adapterId, userId }).name;
8605
+ return name && name !== WEB_NAME_FALLBACK ? name : userId;
8606
+ }
8607
+ catch {
8608
+ return userId;
8609
+ }
6925
8610
  }
6926
8611
  writeContactPermissions(name, raw, actor) {
6927
8612
  const parsed = ContactPermissionsSchema.safeParse(raw);
@@ -7119,7 +8804,7 @@ export class FleetManager {
7119
8804
  clearTimeout(entry.timer);
7120
8805
  // #4438 review: a card still being posted has no message yet; postHeldTicketCard retires it once it has one.
7121
8806
  if (entry.messageId)
7122
- void this.retireNonceButtons(entry, entry.messageId, heldCardOutcome(ticket.state, !!ticket.requestContext));
8807
+ void this.removeDecidedContactCard(entry, entry.messageId, heldCardOutcome(ticket.state, !!ticket.requestContext));
7123
8808
  }
7124
8809
  return;
7125
8810
  }
@@ -7219,7 +8904,10 @@ export class FleetManager {
7219
8904
  if (!entry.messageId)
7220
8905
  return; // never an edit without a message
7221
8906
  closed = true;
7222
- void this.retireNonceButtons(entry, entry.messageId, fresh && fresh.state !== "pending" ? heldCardOutcome(fresh.state, !!fresh.requestContext) : t("contactProposal.expired"));
8907
+ if (fresh && fresh.state !== "pending")
8908
+ void this.removeDecidedContactCard(entry, entry.messageId, heldCardOutcome(fresh.state, !!fresh.requestContext));
8909
+ else
8910
+ void this.retireNonceButtons(entry, entry.messageId, t("contactProposal.expired"));
7223
8911
  };
7224
8912
  void posted.then(retire, () => { });
7225
8913
  try {
@@ -7235,6 +8923,25 @@ export class FleetManager {
7235
8923
  throw error;
7236
8924
  }
7237
8925
  }
8926
+ /**
8927
+ * M-3820 (the user, 11-26: General filled with cards edited to "approved elsewhere"): a contact card whose request was
8928
+ * decided or expired somewhere else — the web, another card, a General proposal — is deleted; the card a person pressed
8929
+ * keeps its outcome, and the decision stays in the agent's Permissions history. One try: a delete the platform refuses
8930
+ * (no permission, a Telegram message over 48 h old, a gateway not ready) falls back to the edit it had before.
8931
+ */
8932
+ async removeDecidedContactCard(entry, messageId, text) {
8933
+ if (!entry.retire && entry.adapter.deleteMessage) {
8934
+ try {
8935
+ await entry.adapter.deleteMessage(entry.chatId, messageId, entry.threadId);
8936
+ this.webPromptGone(entry, text);
8937
+ return;
8938
+ }
8939
+ catch (err) {
8940
+ this.logger.info({ err: err?.message, instanceName: entry.instanceName }, "Could not delete a contact card decided elsewhere; editing it instead");
8941
+ }
8942
+ }
8943
+ await this.retireNonceButtons(entry, messageId, text);
8944
+ }
7238
8945
  async postHeldTicketCard(ticket) {
7239
8946
  const found = this.contactCardRoute(ticket.target);
7240
8947
  if (typeof found === "string")
@@ -7268,7 +8975,10 @@ export class FleetManager {
7268
8975
  if (entry.timer)
7269
8976
  clearTimeout(entry.timer);
7270
8977
  }
7271
- await this.retireNonceButtons(entry, entry.messageId, !fresh || fresh.state === "pending" ? t("contactHeld.expired") : heldCardOutcome(fresh.state, !!fresh.requestContext));
8978
+ if (!fresh || fresh.state === "pending")
8979
+ await this.retireNonceButtons(entry, entry.messageId, t("contactHeld.expired"));
8980
+ else
8981
+ await this.removeDecidedContactCard(entry, entry.messageId, heldCardOutcome(fresh.state, !!fresh.requestContext));
7272
8982
  }
7273
8983
  async handleContactTicketCallback(data, adapterId, adapter) {
7274
8984
  if (!data.callbackData.startsWith(CONTACT_TICKET_PREFIX))
@@ -7412,15 +9122,25 @@ export class FleetManager {
7412
9122
  return;
7413
9123
  try {
7414
9124
  outbox.contactAuthorizations.notifyOutcomes((ticket, outcome) => {
9125
+ const notify = (key, text) => {
9126
+ if (ticket.requestContext) {
9127
+ const context = outbox.requestContext(ticket.requestContext.contextId);
9128
+ if (!context || context.source.instance !== ticket.source)
9129
+ throw Error("Contact outcome context unavailable");
9130
+ outbox.admitRequestContextOutcome(context.ref.contextId, key, text, () => !this.shuttingDown && this.contactGeneration(ticket.source) === context.source.incarnation);
9131
+ }
9132
+ else
9133
+ outbox.admitSystemNotice(ticket.source, key, text);
9134
+ };
7415
9135
  if (outcome === "declined" || outcome === "expired") {
7416
- outbox.admitSystemNotice(ticket.source, `contact-outcome:${ticket.id}`, t(outcome === "declined" ? "contact.noticeDeclined" : "contact.noticeExpired", ticket.id, ticket.target));
9136
+ notify(`contact-outcome:${ticket.id}`, t(outcome === "declined" ? "contact.noticeDeclined" : "contact.noticeExpired", ticket.id, ticket.target));
7417
9137
  return;
7418
9138
  }
7419
9139
  // M-3716 (the user, 11-25): the requester learns who approved it, when, and whether the target has it.
7420
9140
  const by = ticket.decidedBy, when = ticket.decidedAt ? `${ticket.decidedAt.slice(0, 16).replace("T", " ")} UTC` : "";
7421
9141
  const who = !by ? "?" : by.platform === "host" ? t("contactProposal.host")
7422
9142
  : `${by.label}${getLocale() === "zh-TW" ? "(" : " ("}${by.platform === "discord" ? "Discord" : "Telegram"}${getLocale() === "zh-TW" ? ")" : ")"}`;
7423
- outbox.admitSystemNotice(ticket.source, `contact-approval:${ticket.id}`, t(`contact.noticeApproved_${outcome}`, shortContactTicketId(ticket.id), ticket.target, who, when));
9143
+ notify(`contact-approval:${ticket.id}`, t(`contact.noticeApproved_${outcome}`, shortContactTicketId(ticket.id), ticket.target, who, when));
7424
9144
  }, ticket => ticket.deliveryId ? outbox.get(ticket.deliveryId)?.state : undefined);
7425
9145
  }
7426
9146
  catch (err) {
@@ -7918,12 +9638,51 @@ export class FleetManager {
7918
9638
  }, Math.max(0, delayMs));
7919
9639
  this.deliveryPumpTimer.unref?.();
7920
9640
  }
9641
+ /** Only B-validated deliveries can pass Draining; a legacy row or a body root id cannot. */
9642
+ requestContextDeliveryContinuation(row) {
9643
+ const boot = this.requestContextBoot, box = this.deliveryOutbox;
9644
+ if (!boot || !box)
9645
+ return null;
9646
+ const owned = () => !this.shuttingDown && this.deliveryOutbox === box && this.requestContextBoot === boot && this.contactDeliveryCurrent(row);
9647
+ const bound = requestDeliveryContinuation(box, boot.publication, row, owned);
9648
+ if (bound)
9649
+ return bound;
9650
+ // An untouched queued human control uses its receipt's registered parent, never a legacy operation's speaker.
9651
+ const meta = row.payload.meta, id = meta?.human_receipt_id;
9652
+ if (row.kind !== "human_control" || row.sourceInstance !== "agend-system" || typeof id !== "string" || row.sourceKey !== `human-control:${id}`
9653
+ || row.operationId !== row.sourceKey || meta?.verification_id !== `hmsg-${id}`)
9654
+ return null;
9655
+ const parent = this.requestContextHumanContinuation(row.targetInstance, id);
9656
+ if (!parent)
9657
+ return null;
9658
+ const image = requestContextDigest(row), current = () => {
9659
+ try {
9660
+ const actual = box.get(row.deliveryId);
9661
+ return owned() && parent.current() && !!actual
9662
+ && ["queued", "delivering"].includes(actual.state) && requestContextDigest(actual) === image;
9663
+ }
9664
+ catch {
9665
+ return false;
9666
+ }
9667
+ };
9668
+ if (!current())
9669
+ throw Error("Retained steer continuation changed");
9670
+ return boot.publication.continuation(parent.rootContextId, current);
9671
+ }
9672
+ requestContextDeliveryAdmissionAllowed(row) {
9673
+ try {
9674
+ return this.requestContextAdmission?.available(this.requestContextDeliveryContinuation(row) ?? undefined) !== false;
9675
+ }
9676
+ catch {
9677
+ return false;
9678
+ }
9679
+ }
7921
9680
  async runDeliveryOutboxPump() {
7922
9681
  const outbox = this.deliveryOutbox;
7923
9682
  // A closed database is never queried: this runs from timers, where a throw
7924
9683
  // is an unhandled rejection. Checking here covers the finally block too:
7925
9684
  // the body below never awaits, so the database cannot close in between.
7926
- if (!outbox || this.shuttingDown || this.deliveryPumpRunning || !outbox.isOpen)
9685
+ if (!outbox || this.shuttingDown || this.deliveryPumpRunning || !outbox.isOpen || (this.requestContextAdmission?.dispatchAvailable?.() ?? this.requestContextAdmission?.available()) === false)
7927
9686
  return;
7928
9687
  this.deliveryPumpRunning = true;
7929
9688
  this.deliveryPumpScheduled = false;
@@ -7949,7 +9708,7 @@ export class FleetManager {
7949
9708
  // Phase 2c: a lane a queue worker owns is never claimed here.
7950
9709
  target => this.queueWorkers.has(target) || this.isInstanceRestarting(target) || this.wakeCoordinator?.blocksClaim(target)
7951
9710
  ? null
7952
- : this.deliveryBootId(target), this.activeDurableTargets, row => this.recoveryDeliveryEligible(row));
9711
+ : this.deliveryBootId(target), this.activeDurableTargets, row => this.recoveryDeliveryEligible(row) && (this.requestContextAdmission?.available() !== false || this.requestContextDeliveryAdmissionAllowed(row)));
7953
9712
  if (!claimed)
7954
9713
  break;
7955
9714
  this.activeDurableTargets.add(claimed.targetInstance);
@@ -8008,10 +9767,10 @@ export class FleetManager {
8008
9767
  const worker = new TargetQueueWorker(target, {
8009
9768
  owns: () => this.queueWorkers.get(target) === worker,
8010
9769
  wanted: () => this.deliveryWorkerMode(target) === "on",
8011
- available: () => !this.shuttingDown && this.deliveryOutbox?.isOpen === true,
9770
+ available: () => !this.shuttingDown && this.deliveryOutbox?.isOpen === true && (this.requestContextAdmission?.dispatchAvailable?.() ?? this.requestContextAdmission?.available()) !== false,
8012
9771
  blocked: () => this.isInstanceRestarting(target) || this.wakeCoordinator?.blocksClaim(target) === true,
8013
9772
  daemonBootId: () => this.deliveryBootId(target),
8014
- claim: bootId => this.deliveryOutbox?.claimNext(this.managerBootId, candidate => candidate === target ? bootId : null, new Set(), row => this.recoveryDeliveryEligible(row)),
9773
+ claim: bootId => (this.requestContextAdmission?.dispatchAvailable?.() ?? this.requestContextAdmission?.available()) === false ? undefined : this.deliveryOutbox?.claimNext(this.managerBootId, candidate => candidate === target ? bootId : null, new Set(), row => this.recoveryDeliveryEligible(row) && (this.requestContextAdmission?.available() !== false || this.requestContextDeliveryAdmissionAllowed(row))),
8015
9774
  tryAcquireBudget: () => {
8016
9775
  if (this.activeDurableTargets.size >= 8)
8017
9776
  return false;
@@ -8045,6 +9804,7 @@ export class FleetManager {
8045
9804
  await this.dispatchNativeDurableDelivery(claimed);
8046
9805
  return;
8047
9806
  }
9807
+ const humanControl = claimed.kind === "human_control";
8048
9808
  const target = claimed.targetInstance;
8049
9809
  const attempt = claimed.attemptNo;
8050
9810
  const payload = { ...claimed.payload };
@@ -8055,6 +9815,8 @@ export class FleetManager {
8055
9815
  // Arm the visible liveness alert as soon as this generation owns the lane,
8056
9816
  // including time spent waiting for a handoff/idle gate to return.
8057
9817
  try {
9818
+ if (humanControl && (claimed.sourceInstance !== "agend-system" || claimed.sourceKey !== claimed.operationId || !claimed.sourceKey.startsWith("human-control:")))
9819
+ throw Error("Invalid retained human control");
8058
9820
  let sent;
8059
9821
  if (claimed.kind === WORKING_RECOVERY_KIND) {
8060
9822
  const daemon = this.daemons.get(target), key = claimed.sourceKey.replace(/^working-recovery:/, "");
@@ -8073,6 +9835,19 @@ export class FleetManager {
8073
9835
  }
8074
9836
  sent = true;
8075
9837
  }
9838
+ else if (claimed.kind === UPDATE_HANDBACK_COPY_KIND) {
9839
+ // M-3770 §2.6 (rev 15, Fable #4536 design 3a): a turn the update barrier held, delivered as journaled. A person's
9840
+ // turn stays a person's — no from_instance is stamped — and only the fence's delivery id and attempt are added.
9841
+ if (payload.type === "raw_paste") {
9842
+ if (typeof payload.content !== "string")
9843
+ throw new Error("Durable hand-back copy has an invalid payload");
9844
+ sent = await this.deliverToInstance(target, { ...payload, delivery_id: claimed.deliveryId, delivery_attempt: String(claimed.attemptNo) }, { waitForIdle: false, noInlineWake: this.deliveryWorkerMode(target) !== "off" });
9845
+ }
9846
+ else {
9847
+ payload.meta = { ...rawMeta, delivery_id: claimed.deliveryId, delivery_attempt: String(claimed.attemptNo) };
9848
+ sent = await this.deliverToInstance(target, payload, { waitForIdle: true, noInlineWake: this.deliveryWorkerMode(target) !== "off" });
9849
+ }
9850
+ }
8076
9851
  else if (claimed.kind === "raw_paste") {
8077
9852
  if (payload.type !== "raw_paste" || typeof payload.content !== "string") {
8078
9853
  throw new Error("Durable raw_paste row has an invalid payload");
@@ -8092,15 +9867,24 @@ export class FleetManager {
8092
9867
  ...rawMeta,
8093
9868
  delivery_id: claimed.deliveryId,
8094
9869
  delivery_attempt: String(claimed.attemptNo),
8095
- from_instance: typeof rawMeta.from_instance === "string" && rawMeta.from_instance
8096
- ? rawMeta.from_instance
8097
- : claimed.sourceInstance,
9870
+ ...(!humanControl ? { from_instance: typeof rawMeta.from_instance === "string" && rawMeta.from_instance
9871
+ ? rawMeta.from_instance : claimed.sourceInstance } : {}),
8098
9872
  correlation_id: claimed.correlationId ?? String(rawMeta.correlation_id ?? ""),
8099
9873
  };
9874
+ if (humanControl) {
9875
+ payload.delivery_id = claimed.deliveryId;
9876
+ payload.delivery_attempt = String(claimed.attemptNo);
9877
+ markRetainedHumanControl(payload, claimed);
9878
+ }
9879
+ if (this.requestContextBoot) {
9880
+ const proof = this.requestContextDeliveryContinuation(outbox.get(claimed.deliveryId));
9881
+ if (proof)
9882
+ requestPayloadContinuations.set(payload, proof);
9883
+ }
8100
9884
  sent = await this.deliverToInstance(target, payload, {
8101
- isCrossInstance: true,
9885
+ isCrossInstance: !humanControl,
8102
9886
  stillCurrent: () => this.contactDeliveryCurrent(claimed),
8103
- waitForIdle: claimed.kind !== "steer",
9887
+ waitForIdle: !humanControl && claimed.kind !== "steer",
8104
9888
  noInlineWake: this.deliveryWorkerMode(target) !== "off",
8105
9889
  });
8106
9890
  }
@@ -8145,12 +9929,21 @@ export class FleetManager {
8145
9929
  }
8146
9930
  const meta = claimed.payload.meta && typeof claimed.payload.meta === "object" ? claimed.payload.meta : {};
8147
9931
  const task = await this.nativeInstanceRuntime().execute(target, { ...claimed.payload, requestId: deliveryId, meta: { ...meta, from_instance: claimed.sourceInstance, correlation_id: claimed.correlationId } }, {
9932
+ ...(this.requestContextPolicy ? { requestContextInputId: `delivery:${deliveryId}:${attemptNo}` } : {}),
8148
9933
  stillCurrent: () => !this.shuttingDown && this.contactDeliveryCurrent(claimed),
8149
9934
  beforeStart: () => { if (!this.contactDeliveryCurrent(claimed) || outbox.begin(deliveryId, targetDaemonBootId, attemptNo) !== "begun")
8150
9935
  throw new Error("Windows delivery attempt is no longer current"); begun = true; },
8151
9936
  });
8152
9937
  const outcome = task.outcomeConfirmed === false ? "uncertain" : task.status === "completed" ? "delivered" : "failed";
8153
9938
  outbox.complete(deliveryId, targetDaemonBootId, attemptNo, outcome, task.error || task.status);
9939
+ if (this.requestContextPolicy) {
9940
+ if (!this.requestContextRelay)
9941
+ throw Error("Native scoped return admission is unavailable");
9942
+ const completion = this.nativeInstanceRuntime().requestContextCompletion(target, deliveryId, `delivery:${deliveryId}:${attemptNo}`);
9943
+ admitRequestContextNativeResult(outbox, this.requestContextRelay, { deliveryId, task, ...completion });
9944
+ this.scheduleDeliveryOutboxPump();
9945
+ return;
9946
+ }
8154
9947
  // Return a requested peer report when the provider did not explicitly report it through scoped MCP.
8155
9948
  if (meta.requires_reply === "true" && claimed.correlationId && !task.reportedCorrelationIds?.includes(claimed.correlationId) && this.fleetConfig?.instances[claimed.sourceInstance]) {
8156
9949
  const text = (task.status === "completed" ? task.output : `Windows task ${task.status}: ${task.error || task.output}`).slice(0, 8000);
@@ -8184,6 +9977,27 @@ export class FleetManager {
8184
9977
  if (!row || !isNativeExecInstance(this.fleetConfig?.instances[row.targetInstance]) || this.fleetConfig?.instances[row.targetInstance]?.machine_id !== machineId
8185
9978
  || !row.targetDaemonBootId || this.activeDurableTargets.has(row.targetInstance))
8186
9979
  return;
9980
+ if (this.requestContextPolicy) {
9981
+ if (!this.requestContextRelay)
9982
+ throw Error("Native scoped return admission is unavailable");
9983
+ const completion = this.nativeInstanceRuntime().requestContextCompletion(row.targetInstance, row.deliveryId, `delivery:${row.deliveryId}:${row.attemptNo}`);
9984
+ if (!task.execInputProof)
9985
+ throw Error("Native scoped completion has no input proof");
9986
+ // Never let terminal status replace the worker's actual input boundary on a scoped run.
9987
+ validateNativeExecInputProof(task.execInputProof, completion.claim);
9988
+ if (row.state === "submission_started" || row.state === "reconciliation_pending") {
9989
+ if (!outbox.complete(row.deliveryId, row.targetDaemonBootId, row.attemptNo, "delivered", "Owned native input proof recovered"))
9990
+ return;
9991
+ }
9992
+ else if (!["delivered", "uncertain"].includes(row.state))
9993
+ return;
9994
+ if (outbox.markConsumed(row.deliveryId, row.targetDaemonBootId, row.attemptNo, "turn", "Owned native input proof recovered") === "ignored")
9995
+ return;
9996
+ admitRequestContextNativeResult(outbox, this.requestContextRelay, { deliveryId: row.deliveryId, task, ...completion });
9997
+ this.reconciledRemoteResults.add(key);
9998
+ this.scheduleDeliveryOutboxPump();
9999
+ return;
10000
+ }
8187
10001
  if (row.state === "submission_started" || row.state === "reconciliation_pending") {
8188
10002
  if (!outbox.complete(row.deliveryId, row.targetDaemonBootId, row.attemptNo, task.status === "completed" ? "delivered" : "failed", task.error || "Runtime completion recovered after reconnect"))
8189
10003
  return;
@@ -9878,8 +11692,8 @@ export class FleetManager {
9878
11692
  * not sent. There is no await between this and `ipc.send`. Unarmed, or not an agent turn: false, and the send proceeds.
9879
11693
  * A Hub or room payload is not a copy: `refuseHubPane` refuses it before this, and the producer leaves the row queued.
9880
11694
  */
9881
- holdPaneSend(payload) {
9882
- return this.quiescence?.commitTurn(payload) === true;
11695
+ holdPaneSend(instanceName, payload) {
11696
+ return this.quiescence?.commitTurn(payload, instanceName) === true;
9883
11697
  }
9884
11698
  /** The fence is up and this payload belongs to a durable Hub or room row. Do not send it and do not copy it. */
9885
11699
  refuseHubPane(payload) {
@@ -9905,6 +11719,8 @@ export class FleetManager {
9905
11719
  * retry brings it up, however long the backoff, and fails only once the retries give up.
9906
11720
  */
9907
11721
  async sendWhenConnected(instanceName, payload, deliveryEpoch = this.getDeliveryEpoch(instanceName), stillCurrent, onStartRetryHold, beforeInput) {
11722
+ if (this.requestContextAdmission && !await this.requestContextAdmission.wait(() => this.deliveryCurrent(instanceName, deliveryEpoch, stillCurrent), requestPayloadContinuations.get(payload)))
11723
+ return false;
9908
11724
  if (!this.deliveryCurrent(instanceName, deliveryEpoch, stillCurrent))
9909
11725
  return false;
9910
11726
  const queued = this.ipcWaitTails.get(instanceName);
@@ -9913,10 +11729,12 @@ export class FleetManager {
9913
11729
  if (ipc?.connected) {
9914
11730
  if (beforeInput)
9915
11731
  return this.handOffAfterBeforeInput(instanceName, payload, deliveryEpoch, stillCurrent, beforeInput);
11732
+ if (this.requestContextAdmission?.available(requestPayloadContinuations.get(payload)) === false)
11733
+ return this.sendAfterIpcReturns(instanceName, payload, deliveryEpoch, stillCurrent, onStartRetryHold, beforeInput);
9916
11734
  const wire = this.bindHumanReceiptPayload(instanceName, payload);
9917
11735
  if (this.refuseHubPane(wire))
9918
11736
  return false;
9919
- if (this.holdPaneSend(wire))
11737
+ if (this.holdPaneSend(instanceName, wire))
9920
11738
  return true;
9921
11739
  if (ipc.send(wire))
9922
11740
  return true;
@@ -9950,44 +11768,56 @@ export class FleetManager {
9950
11768
  * goes in one attempt. After the intent is spent nothing here retries: false is the caller's uncertain outcome.
9951
11769
  */
9952
11770
  async handOffAfterBeforeInput(instanceName, payload, deliveryEpoch, stillCurrent, beforeInput) {
11771
+ if (this.requestContextAdmission && !await this.requestContextAdmission.wait(() => this.deliveryCurrent(instanceName, deliveryEpoch, stillCurrent), requestPayloadContinuations.get(payload)))
11772
+ return false;
9953
11773
  // The flag is read before beforeInput and before prepareClassicForPerson. A Hub or room row stays
9954
11774
  // queued at its producer: no begin lease, no input intent, and no plaintext copy of the question.
9955
11775
  if (this.refuseHubPane(payload))
9956
11776
  return false;
9957
11777
  if (this.quiescence?.armed()) {
9958
11778
  const early = this.bindHumanReceiptPayload(instanceName, payload);
9959
- if (this.holdPaneSend(early))
11779
+ if (this.holdPaneSend(instanceName, early))
9960
11780
  return true;
9961
11781
  }
9962
- if (!(await beforeInput()))
11782
+ const begin = this.requestContextAdmission
11783
+ ? await runWithRequestContextAdmission(this.requestContextAdmission, () => this.deliveryCurrent(instanceName, deliveryEpoch, stillCurrent), beforeInput, requestPayloadContinuations.get(payload))
11784
+ : await beforeInput();
11785
+ if (!begin)
9963
11786
  return false;
9964
11787
  if (this.refuseHubPane(payload))
9965
11788
  return false;
9966
11789
  const privateToken = await this.prepareClassicForPerson(instanceName, payload, deliveryEpoch, stillCurrent);
9967
11790
  if (privateToken === false || this.shuttingDown || !this.deliveryCurrent(instanceName, deliveryEpoch, stillCurrent))
9968
11791
  return false;
9969
- const ipc = this.instanceIpcClients.get(instanceName);
9970
- if (!ipc?.connected || (privateToken && this.classicPrivacy().read(instanceName)?.token !== privateToken))
9971
- return false;
9972
- const wire = this.bindHumanReceiptPayload(instanceName, payload);
9973
- if (this.refuseHubPane(wire))
9974
- return false;
9975
- if (this.holdPaneSend(wire))
9976
- return true;
9977
- const sent = ipc.send(wire);
9978
- if (sent && privateToken) {
9979
- try {
9980
- if (this.classicPrivacy().resume(instanceName, privateToken)) {
9981
- this.instanceProgress.delete(instanceName);
9982
- this.instanceActivity.delete(instanceName);
11792
+ const send = () => {
11793
+ if (this.shuttingDown || !this.deliveryCurrent(instanceName, deliveryEpoch, stillCurrent))
11794
+ return false;
11795
+ const ipc = this.instanceIpcClients.get(instanceName);
11796
+ if (!ipc?.connected || (privateToken && this.classicPrivacy().read(instanceName)?.token !== privateToken))
11797
+ return false;
11798
+ const wire = this.bindHumanReceiptPayload(instanceName, payload);
11799
+ if (this.refuseHubPane(wire))
11800
+ return false;
11801
+ if (this.holdPaneSend(instanceName, wire))
11802
+ return true;
11803
+ const sent = ipc.send(wire);
11804
+ if (sent && privateToken) {
11805
+ try {
11806
+ if (this.classicPrivacy().resume(instanceName, privateToken)) {
11807
+ this.instanceProgress.delete(instanceName);
11808
+ this.instanceActivity.delete(instanceName);
11809
+ }
11810
+ }
11811
+ catch (err) {
11812
+ // Input was accepted: never invite a duplicate. Keep output closed if its durable release fails.
11813
+ this.logger.warn({ err, instanceName }, "Classic room output remains private after the person input");
9983
11814
  }
9984
11815
  }
9985
- catch (err) {
9986
- // Input was accepted: never invite a duplicate. Keep output closed if its durable release fails.
9987
- this.logger.warn({ err, instanceName }, "Classic room output remains private after the person input");
9988
- }
9989
- }
9990
- return sent;
11816
+ return sent;
11817
+ };
11818
+ return this.requestContextAdmission
11819
+ ? runWithRequestContextAdmission(this.requestContextAdmission, () => this.deliveryCurrent(instanceName, deliveryEpoch, stillCurrent), send, requestPayloadContinuations.get(payload))
11820
+ : send();
9991
11821
  }
9992
11822
  /** Poll for the instance's IPC to come back, then send. Throws if it does not. */
9993
11823
  async sendAfterIpcReturns(instanceName, payload, deliveryEpoch = this.getDeliveryEpoch(instanceName), stillCurrent, onStartRetryHold, beforeInput) {
@@ -9995,6 +11825,12 @@ export class FleetManager {
9995
11825
  let warned = false;
9996
11826
  let held = false;
9997
11827
  for (;;) {
11828
+ if (this.requestContextAdmission && !this.requestContextAdmission.available(requestPayloadContinuations.get(payload))) {
11829
+ if (!await this.requestContextAdmission.wait(() => this.deliveryCurrent(instanceName, deliveryEpoch, stillCurrent), requestPayloadContinuations.get(payload)))
11830
+ return false;
11831
+ deadline = Date.now() + IPC_RECONNECT_GRACE_MS; // Cutover waiting is not an IPC reconnect timeout.
11832
+ continue;
11833
+ }
9998
11834
  if (!this.deliveryCurrent(instanceName, deliveryEpoch, stillCurrent))
9999
11835
  return false;
10000
11836
  // Re-read every round: a reconnect replaces the IpcClient object entirely,
@@ -10006,7 +11842,7 @@ export class FleetManager {
10006
11842
  const wire = this.bindHumanReceiptPayload(instanceName, payload);
10007
11843
  if (this.refuseHubPane(wire))
10008
11844
  return false;
10009
- if (this.holdPaneSend(wire))
11845
+ if (this.holdPaneSend(instanceName, wire))
10010
11846
  return true;
10011
11847
  if (ipc.send(wire))
10012
11848
  return true;
@@ -10096,7 +11932,19 @@ export class FleetManager {
10096
11932
  * The tool's errors: an emoji outside the web set or one of the instance's delivery marks (web-reactions.ts), or a
10097
11933
  * message the chat does not have. An emoji the message already has is a success that changes nothing.
10098
11934
  */
10099
- async reactToWebMessage(instance, messageId, raw) {
11935
+ async reactToWebMessage(instance, messageId, raw, replyRoute) {
11936
+ if (replyRoute) {
11937
+ if (!replyRoute.current())
11938
+ return { ok: false, error: "Originating request context is no longer current" };
11939
+ const handle = replyRoute.target.webRoute?.sessionHandle;
11940
+ if (handle) {
11941
+ const session = this.webSessions?.findByHandle(handle), row = this.webChatHistory.findByReplyId(instance, messageId);
11942
+ if (!session || !row)
11943
+ return { ok: false, error: `react: ${messageId} is not a message in ${instance}'s web chat now (it left the history, or it is from before AgEnD restarted) — answer with reply instead` };
11944
+ if (session.tier === "guest" && (!session.owner || !guestSeesMessage(row, { owner: session.owner, current: () => replyRoute.current(), scope: () => this.guestScope(session.owner), ownRoom: name => this.guestOwnRoom(session.owner, name) }, this.guestScope(session.owner))))
11945
+ return { ok: false, error: `react: ${messageId} is not a message in ${instance}'s web chat now (it left the history, or it is from before AgEnD restarted) — answer with reply instead` };
11946
+ }
11947
+ }
10100
11948
  const problem = webReactionProblem(raw, this.statusEmojiAvoidList(instance));
10101
11949
  if (problem)
10102
11950
  return { ok: false, error: problem };
@@ -10107,13 +11955,20 @@ export class FleetManager {
10107
11955
  if (!r.added)
10108
11956
  return { ok: true, mirrored: Promise.resolve(0) };
10109
11957
  this.emitSseEvent("reactions", { instance, boot: r.message.boot, id: r.message.id, reactions: r.message.reactions ?? [] });
11958
+ const routeMatches = (copy) => !replyRoute || copy.chatId === replyRoute.target.chatId && (copy.threadId ?? "") === (replyRoute.target.threadId ?? "") && copy.adapterId === replyRoute.target.adapterId;
10110
11959
  const mirrorOne = (copy) => {
11960
+ if (!routeMatches(copy))
11961
+ return Promise.resolve(0);
10111
11962
  let timer;
10112
11963
  const timeout = new Promise((_, reject) => {
10113
11964
  timer = setTimeout(() => reject(new Error(`no answer in ${WEB_MIRROR_TIMEOUT_MS} ms`)), WEB_MIRROR_TIMEOUT_MS);
10114
11965
  timer.unref?.();
10115
11966
  });
10116
- return Promise.race([Promise.resolve().then(() => copy.adapter.react(copy.chatId, copy.messageId, reactionForm(copy.adapter.type, emoji), copy.threadId)), timeout])
11967
+ return Promise.race([Promise.resolve().then(() => {
11968
+ if (replyRoute && (!replyRoute.current() || !routeMatches(copy)))
11969
+ throw new RequestContextPolicyError("stale");
11970
+ return copy.adapter.react(copy.chatId, copy.messageId, reactionForm(copy.adapter.type, emoji), copy.threadId);
11971
+ }), timeout])
10117
11972
  .then(() => 1, (err) => {
10118
11973
  this.logger.warn({ err, instance, adapter: copy.adapter.type }, "Reaction on a web message's channel copy failed (shown on the web)");
10119
11974
  return 0;
@@ -10349,6 +12204,490 @@ export class FleetManager {
10349
12204
  }
10350
12205
  });
10351
12206
  }
12207
+ /** One controlled candidate, shared by instruction rendering and the lifecycle's actual pre-start hook. */
12208
+ prepareRequestContextDaemonOwner(instance, config, policy, registration, current) {
12209
+ const box = this.deliveryOutbox;
12210
+ if (!box)
12211
+ throw Error("Request input owner is unavailable");
12212
+ const firstActivation = box.requestContextInstallation().read() === null;
12213
+ const image = requestContextDigest(config), incarnation = this.contactGeneration(instance);
12214
+ let registered = false, daemon = null, binding = null;
12215
+ const ownerCurrent = () => {
12216
+ try {
12217
+ return current() && this.contactGeneration(instance) === incarnation
12218
+ && (!registered || !!daemon && this.daemons.get(instance) === daemon);
12219
+ }
12220
+ catch {
12221
+ return false;
12222
+ }
12223
+ };
12224
+ const work = new RequestContextPreparedWork(box.requestContextWork, instance, incarnation, ownerCurrent, firstActivation);
12225
+ const preparation = Object.freeze({ policy, current: () => work.current() && ownerCurrent() });
12226
+ return Object.freeze({ preparation, work,
12227
+ configure: (candidate, actual, offered) => {
12228
+ if (daemon || !preparation.current() || !offered?.current() || offered.policy !== policy
12229
+ || requestContextDigest(actual) !== image || requestContextDigest(candidate.getConfigSnapshot()) !== image)
12230
+ throw Error("Request owner preparation changed");
12231
+ daemon = candidate;
12232
+ try {
12233
+ binding = this.makeRequestContextDaemonBinding(instance, candidate, work, registration, ownerCurrent);
12234
+ if (candidate.captureRequestContextOwner()?.instance !== instance)
12235
+ throw Error("Request owner preparation changed");
12236
+ }
12237
+ catch (error) {
12238
+ work.dispose();
12239
+ throw error;
12240
+ }
12241
+ },
12242
+ /** Ownership only, not readiness: the installer must independently prove all real transport ports. */
12243
+ sealRegistered: () => {
12244
+ if (!daemon || this.daemons.get(instance) !== daemon || daemon.requestContextPolicy !== policy || !binding?.current() || !preparation.current())
12245
+ throw Error("Request owner is not bound");
12246
+ registered = true;
12247
+ },
12248
+ bound: () => registered && preparation.current() && binding?.current() === true,
12249
+ hub: () => registered && preparation.current() ? binding?.hub ?? null : null,
12250
+ dispose: () => work.dispose(), });
12251
+ }
12252
+ /** Installer-owned new-registration lane. Never called by a tool or inferred from an absent work row.
12253
+ * retirement is captured by the controlled relaunch before the old launch/IPC is stopped.
12254
+ */
12255
+ async registerRequestContextWork(instance, retirement) {
12256
+ const box = this.deliveryOutbox, admission = this.requestContextAdmission, lease = captureProcessFleetLease(this.dataDir);
12257
+ if (!box || !box.requestContextInstallation().read() || !admission || admission.available() || !lease?.current()
12258
+ || this.hubIncarnationsBroken || !retirement.current())
12259
+ throw Error("Request work registration unavailable");
12260
+ const incarnation = this.contactGeneration(instance), path = this.hubIncarnationsPath(), image = readFileSync(path, "utf8");
12261
+ const raw = JSON.parse(image), entry = Object.hasOwn(raw, instance) ? raw[instance] : undefined, previous = box.requestContextWork.read(instance);
12262
+ const mode = requestWorkRegistrationEvidence(instance, entry, incarnation, previous?.incarnation ?? null);
12263
+ const current = () => {
12264
+ try {
12265
+ return !this.shuttingDown && lease.current() && this.requestContextAdmission === admission && !admission.available()
12266
+ && !this.hubIncarnationsBroken && retirement.current() && this.contactGeneration(instance) === incarnation && readFileSync(path, "utf8") === image;
12267
+ }
12268
+ catch {
12269
+ return false;
12270
+ }
12271
+ };
12272
+ if (!current() || !await retirement.retired() || !current())
12273
+ throw Error("Request work predecessor is not retired");
12274
+ const value = mode === "resume" ? previous : box.requestContextWork.register({ instance, incarnation, generation: randomUUID() }, previous, current);
12275
+ if (!current())
12276
+ throw Error("Request work registration changed");
12277
+ // Commit precedes marker consumption. A crash in between resumes the exact row and finishes this write;
12278
+ // a consumed marker with a missing row can never recreate a birth.
12279
+ raw[instance] = { ...entry, requestWork: "registered" };
12280
+ if (this.writeHubIncarnations(raw) !== "written")
12281
+ throw Error("Request work registration evidence unavailable");
12282
+ if (!lease.current() || !retirement.current() || this.contactGeneration(instance) !== incarnation)
12283
+ throw Error("Request work registration changed");
12284
+ return value;
12285
+ }
12286
+ /** Finish a committed registration's marker, including crash recovery. This creates no work, context or permission. */
12287
+ sealRequestContextWorkRegistration(instance, current) {
12288
+ const box = this.deliveryOutbox, lease = captureProcessFleetLease(this.dataDir), incarnation = this.contactGeneration(instance), work = box?.requestContextWork.read(instance);
12289
+ if (!box || !work || work.incarnation !== incarnation || !lease?.current() || !current() || this.hubIncarnationsBroken)
12290
+ throw Error("Committed request registration unavailable");
12291
+ const path = this.hubIncarnationsPath(), image = readFileSync(path, "utf8"), raw = JSON.parse(image), entry = Object.hasOwn(raw, instance) ? raw[instance] : undefined;
12292
+ requestWorkRegistrationEvidence(instance, entry, incarnation, work.incarnation);
12293
+ const owned = () => lease.current() && current() && !this.hubIncarnationsBroken && this.contactGeneration(instance) === incarnation
12294
+ && requestContextDigest(box.requestContextWork.read(instance)) === requestContextDigest(work);
12295
+ if (!owned() || readFileSync(path, "utf8") !== image)
12296
+ throw Error("Committed request registration changed");
12297
+ if (entry.requestWork !== "registered") {
12298
+ raw[instance] = { ...entry, requestWork: "registered" };
12299
+ if (this.writeHubIncarnations(raw) !== "written")
12300
+ throw Error("Request registration marker unavailable");
12301
+ }
12302
+ if (!owned())
12303
+ throw Error("Committed request registration changed");
12304
+ }
12305
+ /** Capable boot/restart factory. A current retained work row is mandatory; a missing/new incarnation uses
12306
+ * only the explicit durable registration lane. No running daemon is hot-bound and no active turn is restored.
12307
+ */
12308
+ installRequestContextRetainedOwners(policy, registration, current, adopt = [], options = {}) {
12309
+ const box = this.deliveryOutbox, admission = this.requestContextAdmission, lease = captureProcessFleetLease(this.dataDir), token = {}, initial = box?.requestContextInstallation().read();
12310
+ if (!box || !initial && !options.firstOnStage?.current() || !admission || admission.available() || !lease?.current() || !current() || this.requestContextRetainedFactory)
12311
+ throw Error("Retained request owner factory unavailable");
12312
+ let sealed = !!initial, attached = false;
12313
+ const entries = new Map(), preparing = new Set(), retiredLaunches = new Map();
12314
+ let serial = 0;
12315
+ this.requestContextRetainedFactory = token;
12316
+ const owned = () => { try {
12317
+ return this.requestContextRetainedFactory === token && !this.shuttingDown && lease.current() && current() && this.requestContextAdmission === admission;
12318
+ }
12319
+ catch {
12320
+ return false;
12321
+ } };
12322
+ const entryCurrent = (entry) => {
12323
+ try {
12324
+ return owned() && entries.get(entry.name) === entry && this.contactGeneration(entry.name) === entry.incarnation
12325
+ && (!entry.daemon || this.daemons.get(entry.name) === entry.daemon || entry.starting && !this.daemons.has(entry.name));
12326
+ }
12327
+ catch {
12328
+ return false;
12329
+ }
12330
+ };
12331
+ const prepare = async (name, config) => {
12332
+ if (!owned() || preparing.has(name))
12333
+ throw Error("Request owner registration changed");
12334
+ preparing.add(name);
12335
+ try {
12336
+ const incarnation = this.contactGeneration(name), previous = entries.get(name), stored = box.requestContextWork.read(name), staging = !sealed && options.firstOnStage?.current() === true;
12337
+ if (previous?.exec) {
12338
+ if (!previous.exec.idle())
12339
+ throw Error("Request owner is still preparing or running");
12340
+ if (previous.incarnation === incarnation && previous.work.current()) {
12341
+ if (!staging)
12342
+ this.sealRequestContextWorkRegistration(name, owned);
12343
+ return;
12344
+ }
12345
+ }
12346
+ if (previous?.daemon && this.daemons.get(name) === previous.daemon)
12347
+ throw Error("Request owner is still running");
12348
+ if (previous?.daemon && (!previous.resources || !await previous.resources.retired()) || !owned())
12349
+ throw Error("Request predecessor has not retired");
12350
+ if ((!stored || stored.incarnation !== incarnation) && !(!stored && staging)) {
12351
+ // Cold unknown predecessors remain blocked. A new birth proves absence of any earlier owned launch;
12352
+ // a recorded predecessor must additionally have this factory's exact retired resource receipt.
12353
+ if (stored && !previous?.resources)
12354
+ throw Error("Request predecessor retirement unavailable");
12355
+ const absent = () => !this.daemons.has(name) && !existsSync(join(this.getInstanceDir(name), "window-id")) && !existsSync(join(this.getInstanceDir(name), "channel.sock"))
12356
+ && !WindowsAgents.requestContextOwnersOnDisk(this.dataDir).some(row => row.instance === name);
12357
+ await this.registerRequestContextWork(name, { current: () => owned() && this.contactGeneration(name) === incarnation && !this.daemons.has(name) && entries.get(name) === previous,
12358
+ retired: () => previous?.resources?.retired() ?? Promise.resolve(absent()) });
12359
+ }
12360
+ if (!owned() || this.contactGeneration(name) !== incarnation || this.daemons.has(name))
12361
+ throw Error("Request owner registration changed");
12362
+ if (!staging)
12363
+ this.sealRequestContextWorkRegistration(name, owned);
12364
+ previous?.prepared?.dispose();
12365
+ previous?.exec?.dispose();
12366
+ previous?.work.dispose();
12367
+ const entry = {};
12368
+ Object.assign(entry, { name, incarnation, config: structuredClone(config), starting: true, ...((previous?.daemon || retiredLaunches.has(name)) ? { previous: previous?.daemon?.requestContextLaunchObservation() ?? retiredLaunches.get(name) } : {}) });
12369
+ entries.set(name, entry);
12370
+ retiredLaunches.delete(name);
12371
+ serial++;
12372
+ const local = () => entryCurrent(entry);
12373
+ try {
12374
+ if (isNativeExecInstance(config)) {
12375
+ entry.work = new RequestContextPreparedWork(box.requestContextWork, name, incarnation, local, staging);
12376
+ entry.exec = createRequestContextExecOwner(box, { instance: name, managerBootId: this.managerBootId, work: entry.work, registration, current: local,
12377
+ incarnation: () => this.contactGeneration(name), deliveryEpoch: () => this.getDeliveryEpoch(name), admitted: root => this.requestContextNativeAdmissionCurrent(root),
12378
+ consumptionCurrent: delivery => this.contactDeliveryCurrent(delivery), canManage: actor => { const person = this.makeRequestContextContactHost(owned, () => false, () => "active").person(actor); return !!person && this.contactAdminOf(name, person); } });
12379
+ entry.starting = false;
12380
+ }
12381
+ else {
12382
+ entry.prepared = this.prepareRequestContextDaemonOwner(name, config, policy, registration, local);
12383
+ entry.work = entry.prepared.work;
12384
+ }
12385
+ }
12386
+ catch (error) {
12387
+ if (entries.get(name) === entry)
12388
+ entries.delete(name);
12389
+ serial++;
12390
+ throw error;
12391
+ }
12392
+ }
12393
+ finally {
12394
+ preparing.delete(name);
12395
+ }
12396
+ };
12397
+ const retire = async (name, daemon, retired) => {
12398
+ const entry = entries.get(name);
12399
+ if (!entry && !this.daemons.has(name) && owned() && await retired())
12400
+ return;
12401
+ if (!owned() || entry?.daemon !== daemon || this.daemons.has(name) || !await retired() || !owned() || entries.get(name) !== entry)
12402
+ throw Error("Request owner retirement changed");
12403
+ retiredLaunches.set(name, daemon.requestContextLaunchObservation());
12404
+ entry.prepared?.dispose();
12405
+ entry.work.dispose();
12406
+ entries.delete(name);
12407
+ serial++;
12408
+ };
12409
+ const attach = () => {
12410
+ if (attached || !owned() || admission.available())
12411
+ throw Error("Retained request start hooks unavailable");
12412
+ const originalConfigure = this.configureRequestContextBeforeStart;
12413
+ this.prepareRequestContextOwnerRegistration = prepare;
12414
+ this.requestContextRetireOwner = retire;
12415
+ this.prepareRequestContextStart = (name, config) => {
12416
+ const entry = entries.get(name);
12417
+ if (!entry?.prepared || entry.daemon || !entryCurrent(entry) || requestContextDigest(entry.config) !== requestContextDigest(config))
12418
+ throw Error("Retained request preparation unavailable");
12419
+ return entry.prepared.preparation;
12420
+ };
12421
+ this.configureRequestContextBeforeStart = (name, daemon, config, offered) => {
12422
+ const entry = entries.get(name);
12423
+ if (!entry?.prepared || entry.daemon || !entryCurrent(entry) || !offered?.current() || offered.policy !== policy
12424
+ || requestContextDigest(config) !== requestContextDigest(entry.config))
12425
+ throw Error("Retained request owner differs");
12426
+ entry.daemon = daemon;
12427
+ if (entry.previous)
12428
+ daemon.seedRequestContextReplacement(entry.previous);
12429
+ entry.resources = daemon.prepareRequestContextStartupRetirement();
12430
+ originalConfigure?.(name, daemon, config, offered);
12431
+ entry.prepared.configure(daemon, config, offered);
12432
+ };
12433
+ this.requestContextOwnerStarted = (name, daemon) => {
12434
+ const entry = entries.get(name);
12435
+ if (!entry?.prepared || entry.daemon !== daemon || this.daemons.get(name) !== daemon || !entryCurrent(entry))
12436
+ throw Error("Retained request owner differs");
12437
+ entry.prepared.sealRegistered();
12438
+ entry.starting = false;
12439
+ serial++;
12440
+ };
12441
+ attached = true;
12442
+ };
12443
+ const adoptOwners = (values) => {
12444
+ for (const row of values) {
12445
+ if (entries.has(row.name) || this.daemons.get(row.name) !== row.daemon || !row.prepared.bound())
12446
+ throw Error("Retained request adoption differs");
12447
+ const incarnation = this.contactGeneration(row.name), entry = { name: row.name, incarnation, config: row.daemon.getConfigSnapshot(), starting: false, daemon: row.daemon, prepared: row.prepared, resources: row.resources, work: row.prepared.work };
12448
+ entries.set(row.name, entry);
12449
+ serial++;
12450
+ }
12451
+ };
12452
+ adoptOwners(adopt);
12453
+ if (!options.deferStartHooks)
12454
+ attach();
12455
+ const exec = (name) => { const entry = entries.get(name); if (!entry?.exec || !entryCurrent(entry))
12456
+ throw Error("Retained native owner unavailable"); return entry.exec; };
12457
+ const aggregate = (kind, root) => {
12458
+ const views = [], image = [];
12459
+ let unknown = !owned();
12460
+ for (const [name, daemon] of this.daemons)
12461
+ if (entries.get(name)?.daemon !== daemon)
12462
+ unknown = true;
12463
+ for (const [name, row] of [...entries].sort(([a], [b]) => a.localeCompare(b))) {
12464
+ const current = entryCurrent(row) && row.work.current();
12465
+ if (!current)
12466
+ unknown = true;
12467
+ image.push([name, row.incarnation, row.work.revision, row.daemon?.bootId ?? null, !!row.exec, current]);
12468
+ try {
12469
+ const view = kind === "turns" ? (row.exec?.turns.drainView(root) ?? row.daemon?.requestContextTurnDrainView(root))
12470
+ : kind === "calls" ? row.daemon?.requestContextCallDrainView(root) : row.prepared?.hub()?.drainView(root);
12471
+ if (view) {
12472
+ views.push(view);
12473
+ image.push([name, view.revision]);
12474
+ if (view.unknown || view.registration !== registration)
12475
+ unknown = true;
12476
+ }
12477
+ else if (row.daemon)
12478
+ unknown = true;
12479
+ if (kind === "inputs" && row.daemon) {
12480
+ const pending = row.daemon.requestContextQueuedWorkDrainView(root);
12481
+ views.push(pending);
12482
+ image.push([name, "queued", pending.revision]);
12483
+ if (pending.unknown || pending.registration !== registration)
12484
+ unknown = true;
12485
+ } // A live/missing view cannot disappear from the whole-Fleet proof.
12486
+ }
12487
+ catch {
12488
+ unknown = true;
12489
+ image.push([name, "unavailable"]);
12490
+ }
12491
+ }
12492
+ return { registration, revision: requestContextDigest([serial, kind, image, [...this.daemons].map(([name, daemon]) => [name, daemon.bootId])]), references: views.flatMap(view => view.references), unknown };
12493
+ };
12494
+ return Object.freeze({ current: owned, beforeStart: prepare, attach, adopt: adoptOwners,
12495
+ disposeStopped: async (nativeRetired) => {
12496
+ if (this.daemons.size || preparing.size || !nativeRetired())
12497
+ throw Error("Request owners are not retired");
12498
+ for (const entry of entries.values())
12499
+ if (entry.daemon && (!entry.resources || !await entry.resources.retired()))
12500
+ throw Error("Request launch retirement unavailable");
12501
+ if (!nativeRetired())
12502
+ throw Error("Native owner retirement changed");
12503
+ for (const entry of entries.values()) {
12504
+ entry.exec?.dispose();
12505
+ entry.prepared?.dispose();
12506
+ entry.work.dispose();
12507
+ }
12508
+ entries.clear();
12509
+ serial++;
12510
+ if (this.requestContextRetainedFactory !== token)
12511
+ throw Error("Request owner factory changed");
12512
+ this.requestContextRetainedFactory = undefined;
12513
+ },
12514
+ disposeUnstarted: () => {
12515
+ if (entries.size || preparing.size || this.daemons.size || this.requestContextRetainedFactory !== token)
12516
+ throw Error("Request owners have already started");
12517
+ this.requestContextRetainedFactory = undefined;
12518
+ serial++;
12519
+ },
12520
+ bound: (name, daemon) => { const entry = entries.get(name); return !!entry && entry.daemon === daemon && entryCurrent(entry) && entry.prepared?.bound() === true; },
12521
+ retain: () => { if (sealed || !owned() || !options.firstOnStage?.current())
12522
+ throw Error("Request owner staging changed"); for (const entry of entries.values())
12523
+ entry.work.retainPrepared(); },
12524
+ seal: () => { if (!owned() || !box.requestContextInstallation().read())
12525
+ throw Error("Request owner staging has not committed"); for (const entry of entries.values()) {
12526
+ entry.work.sealRetained();
12527
+ this.sealRequestContextWorkRegistration(entry.name, owned);
12528
+ } sealed = true; },
12529
+ disposeStaged: async () => {
12530
+ if (sealed || box.requestContextInstallation().read() || !owned() || attached)
12531
+ throw Error("Retained request owners cannot revert");
12532
+ for (const entry of entries.values())
12533
+ if (entry.exec && !entry.exec.idle() || entry.daemon && (!entry.resources || !await entry.resources.retired()))
12534
+ throw Error("Staged request owner is still running");
12535
+ for (const entry of entries.values()) {
12536
+ entry.exec?.dispose();
12537
+ entry.prepared?.dispose();
12538
+ entry.work.dispose();
12539
+ }
12540
+ entries.clear();
12541
+ serial++;
12542
+ if (this.requestContextRetainedFactory !== token)
12543
+ throw Error("Retained request owner changed");
12544
+ this.requestContextRetainedFactory = undefined;
12545
+ },
12546
+ hub: (name) => { const entry = entries.get(name); return entry && entryCurrent(entry) ? entry.prepared?.hub() ?? null : null; },
12547
+ execTurns: (name) => exec(name).turns, execOwner: (name) => exec(name).owner(),
12548
+ execInput: (name, ...args) => exec(name).prepare(...args),
12549
+ revision: () => aggregate("turns", "").revision, turnView: (root) => aggregate("turns", root),
12550
+ callRevision: () => aggregate("calls", "").revision, callView: (root) => aggregate("calls", root),
12551
+ inputRevision: () => aggregate("inputs", "").revision, inputView: (root) => aggregate("inputs", root),
12552
+ });
12553
+ }
12554
+ /** One replacement's C/D-local binding. It is constructed before startup, never hot-bound or published here. */
12555
+ makeRequestContextDaemonBinding(instance, daemon, work, registration, current) {
12556
+ const box = this.deliveryOutbox;
12557
+ if (!box)
12558
+ throw Error("Request input owner is unavailable");
12559
+ const identity = () => {
12560
+ if (!work.current())
12561
+ throw Error("Request work identity is no longer current");
12562
+ const value = work.identity();
12563
+ if (value.incarnation !== this.contactGeneration(instance))
12564
+ throw Error("Request source incarnation changed");
12565
+ return Object.freeze({ incarnation: value.incarnation, workGeneration: value.workGeneration });
12566
+ };
12567
+ identity();
12568
+ const owned = () => { try {
12569
+ identity();
12570
+ return current() && work.current();
12571
+ }
12572
+ catch {
12573
+ return false;
12574
+ } };
12575
+ const manage = (actor) => {
12576
+ if (actor.kind !== "person" || actor.platform === "hub")
12577
+ return false;
12578
+ const adapter = actor.platform === "host" ? "host" : this.contactAdapter(instance)?.id;
12579
+ if (!adapter)
12580
+ return false;
12581
+ return owned() && this.contactAdminOf(instance, { platform: actor.platform, adapterId: adapter, userId: actor.userId, label: actor.userId });
12582
+ };
12583
+ const human = this.makeRequestContextHumanResolver(instance, daemon, owned), delivery = this.makeRequestContextDeliveryResolver(instance, daemon, owned), hub = this.makeRequestContextHubResolver(instance, daemon, owned, registration);
12584
+ const input = (id, wire, owner) => {
12585
+ if (!owned() || this.daemons.get(instance) !== daemon)
12586
+ throw Error("Request input owner changed");
12587
+ return human.prepare(id, wire, owner) ?? delivery.prepare(id, wire, owner) ?? hub.prepare(id, wire, owner);
12588
+ };
12589
+ const turns = new RequestContextLocalTurns({ ...box.requestContextRecovery.ports(instance, input, manage), registration });
12590
+ daemon.setRequestContextLocalLifecycle(turns, identity, () => {
12591
+ if (!owned())
12592
+ throw Error("Request work identity is no longer current");
12593
+ const before = identity();
12594
+ work.fresh();
12595
+ const after = identity();
12596
+ if (!owned() || after.incarnation !== before.incarnation || after.workGeneration === before.workGeneration)
12597
+ throw Error("Fresh request work identity did not rotate");
12598
+ }, snapshot => requestHumanReplyTarget(box, snapshot, () => owned() && daemon.requestContextTurnCurrent(snapshot), root => this.requestContextNativeAdmissionCurrent(root)), (id, recovery) => {
12599
+ const publication = this.requestContextBoot?.publication;
12600
+ if (!publication)
12601
+ return;
12602
+ if (recovery) {
12603
+ const parent = recovery.parent, owner = daemon.captureRequestContextOwner(), stored = box.requestContext(parent.context.ref.contextId);
12604
+ if (!owner || !stored || requestContextDigest(stored) !== requestContextDigest(parent.context) || parent.owner.instance !== owner.instance
12605
+ || parent.owner.incarnation !== owner.incarnation || parent.owner.workGeneration !== owner.workGeneration)
12606
+ throw Error("Recovery continuation owner changed");
12607
+ return publication.continuation(parent.context.ref.rootContextId, () => owned() && recovery.current());
12608
+ }
12609
+ const delivery = /^delivery:([a-f0-9-]{36}):([1-9][0-9]*)$/.exec(id ?? "");
12610
+ if (delivery) {
12611
+ const row = box.get(delivery[1]), owner = daemon.captureRequestContextOwner();
12612
+ if (!row || !owner || row.targetInstance !== instance || row.managerBootId !== this.managerBootId || row.targetDaemonBootId !== owner.daemonBootId
12613
+ || row.attemptNo !== Number(delivery[2]) || !["delivering", "submission_started"].includes(row.state))
12614
+ throw Error("Delivery continuation attempt changed");
12615
+ return this.requestContextDeliveryContinuation(row) ?? undefined;
12616
+ }
12617
+ const human = /^human:hmsg-([a-f0-9-]{36})$/.exec(id ?? "");
12618
+ return human ? this.requestContextHumanContinuation(instance, human[1]) : undefined;
12619
+ });
12620
+ return Object.freeze({ turns, hub, input, current: () => owned() && this.daemons.get(instance) === daemon && daemon.requestContextCallsRequired() });
12621
+ }
12622
+ /** Accepted Hub input owner; construction is pre-start and remains unpublished until the complete installer. */
12623
+ makeRequestContextHubResolver(instance, daemon, current, registration) {
12624
+ const box = this.deliveryOutbox;
12625
+ if (!box)
12626
+ throw Error("Hub request input owner is unavailable");
12627
+ return new RequestHubInputResolver(box, { instance, current: () => current() && this.daemons.get(instance) === daemon,
12628
+ runtimeOwner: () => daemon.captureRequestContextOwner(), active: () => daemon.requestContextTurnSnapshot(), registration });
12629
+ }
12630
+ /** Physical B attempt resolver for the exact replacement daemon; no origin or correlation fallback. */
12631
+ makeRequestContextDeliveryResolver(instance, daemon, current) {
12632
+ const box = this.deliveryOutbox;
12633
+ if (!box)
12634
+ throw Error("Request delivery input owner is unavailable");
12635
+ return makeRequestDeliveryInputResolver(box, { instance, managerBootId: this.managerBootId,
12636
+ current: () => current() && this.daemons.get(instance) === daemon, runtimeOwner: () => daemon.captureRequestContextOwner(),
12637
+ consumptionCurrent: delivery => this.contactDeliveryCurrent(delivery) });
12638
+ }
12639
+ /** Pre-start owner factory; this neither installs a lifecycle nor publishes serving input. */
12640
+ makeRequestContextHumanResolver(instance, daemon, current) {
12641
+ const box = this.deliveryOutbox;
12642
+ if (!box)
12643
+ throw Error("Human request input owner is unavailable");
12644
+ return makeRequestHumanInputResolver(box, { instance, managerBootId: this.managerBootId,
12645
+ current: () => current() && this.daemons.get(instance) === daemon,
12646
+ runtimeOwner: () => daemon.captureRequestContextOwner(), humanOwner: () => this.humanReceiptOwner(instance, daemon), active: () => daemon.requestContextTurnSnapshot(),
12647
+ admitted: context => this.requestContextNativeAdmissionCurrent(context),
12648
+ canManage: actor => {
12649
+ if (actor.kind !== "person" || actor.platform === "hub")
12650
+ return false;
12651
+ const adapter = actor.platform === "host" ? "host" : this.contactAdapter(instance)?.id;
12652
+ if (!adapter)
12653
+ return false;
12654
+ return this.contactAdminOf(instance, { platform: actor.platform, adapterId: adapter, userId: actor.userId, label: actor.userId });
12655
+ } });
12656
+ }
12657
+ /** Assigned only by the complete installer at publication; candidate launch rendering cannot install this. */
12658
+ requestContextHumanAdmission;
12659
+ makeRequestContextHumanAdmission() {
12660
+ this.ensureDeliveryOutbox();
12661
+ const box = this.deliveryOutbox;
12662
+ return (instance, payload, origin, body) => {
12663
+ const room = this.contactRoom(instance), meta = payload.meta;
12664
+ const platform = (id) => {
12665
+ const adapter = this.adapters.get(id) ?? this.worlds.get(id)?.adapter;
12666
+ const configured = (this.fleetConfig?.channels ?? (this.fleetConfig?.channel ? [this.fleetConfig.channel] : [])).find(channel => (channel.id ?? channel.type) === id);
12667
+ const kind = adapter?.type ?? configured?.type;
12668
+ return kind === "discord" || kind === "telegram" ? kind : null;
12669
+ };
12670
+ const nativeBasis = admittedNativeHumanIngress(origin), webBasis = origin.platform === "web" ? admittedHumanWebIngress(origin) : null;
12671
+ if (origin.platform === "web" && !webBasis?.sessionHandle)
12672
+ throw Error("Accepted web input route is unavailable");
12673
+ if (room && origin.platform !== "web" && (!nativeBasis || nativeBasis.roomId !== room.channelId || origin.adapter_id !== (room.adapterId ?? this.contactAdapter(instance)?.id)))
12674
+ throw Error("Accepted Classic admission basis is unavailable");
12675
+ const daemon = ["steer", "btw"].includes(String(payload.type)) ? this.lifecycle?.daemons.get(instance) : undefined, parent = daemon?.requestContextTurnSnapshot();
12676
+ const steer = parent && daemon ? { parent, current: () => this.daemons.get(instance) === daemon && daemon.requestContextTurnCurrent(parent), canManage: (actor) => {
12677
+ if (actor.kind !== "person" || actor.platform === "hub")
12678
+ return false;
12679
+ const adapter = actor.platform === "host" ? "host" : this.contactAdapter(instance)?.id;
12680
+ return !!adapter && this.contactAdminOf(instance, { platform: actor.platform, adapterId: adapter, userId: actor.userId, label: actor.userId });
12681
+ } } : undefined;
12682
+ const captured = box.createHumanReceiptWithRequestContext({ targetInstance: instance, originalBody: body, origin: { ...origin }, inputKind: String(payload.type), managerBootId: this.managerBootId }, { incarnation: this.contactGeneration(instance), steer, room: room ? { restricted: room.restrictedMode === true } : null,
12683
+ web: webBasis,
12684
+ classic: room && origin.platform !== "web" && nativeBasis ? { ...nativeBasis, adapterId: origin.adapter_id } : null,
12685
+ route: { kind: origin.platform === "web" ? "web" : "room", adapterId: origin.platform === "web" ? meta?.adapter_id : origin.adapter_id ?? undefined,
12686
+ chatId: meta?.chat_id ?? "", threadId: meta?.thread_id ?? "", ...(meta?.message_id ? { messageId: meta.message_id } : {}),
12687
+ ...(origin.platform === "web" ? { sessionHandle: webBasis.sessionHandle } : {}) }, platform });
12688
+ return captured.receipt;
12689
+ };
12690
+ }
10352
12691
  /** Evidence-only admission. Bots/system/agent payloads have no trusted origin. */
10353
12692
  humanReceiptPayload(instanceName, payload, origin, originalBody) {
10354
12693
  // #1939 S3: "via web (verified)" comes only from the receipt written here — never from a caller's meta.
@@ -10359,12 +12698,24 @@ export class FleetManager {
10359
12698
  }
10360
12699
  if (!origin || !this.deliveryOutbox)
10361
12700
  return payload;
10362
- const row = this.deliveryOutbox.createHumanReceipt({ targetInstance: instanceName, originalBody,
10363
- origin: { ...origin }, inputKind: String(payload.type), managerBootId: this.managerBootId });
10364
- const contactStore = this.deliveryOutbox.contactAuthorizations;
10365
- if (this.contactRoom(instanceName)?.restrictedMode === true && !contactStore)
12701
+ const installed = requestContextPolicyInstalled(this.requestContextPolicy);
12702
+ // A committed but unpublished bridge can retain exact input metadata while the actual write stays fenced.
12703
+ const prepared = this.requestContextBoot?.publication.heldUnpublished() === true && this.requestContextModes?.current() === true;
12704
+ const scoped = installed || prepared;
12705
+ if (scoped && !this.requestContextHumanAdmission)
12706
+ throw Error("Accepted human input admission is unavailable");
12707
+ const row = scoped ? this.requestContextHumanAdmission(instanceName, payload, origin, originalBody)
12708
+ : this.deliveryOutbox.createHumanReceipt({ targetInstance: instanceName, originalBody,
12709
+ origin: { ...origin }, inputKind: String(payload.type), managerBootId: this.managerBootId });
12710
+ // Installed work uses its admitted request only; lifetime history is no longer a permission input or shadow.
12711
+ const contactStore = scoped ? undefined : this.deliveryOutbox.contactAuthorizations;
12712
+ if (!scoped && this.contactRoom(instanceName)?.restrictedMode === true && !contactStore)
10366
12713
  throw Error("Contact origin storage unavailable");
10367
- if (contactStore && (this.contactRoom(instanceName)?.restrictedMode === true || contactStore.origin(instanceName))) {
12714
+ // M-3830 (user 11-26, Fable): a person's message becomes contact origin only in a restricted ClassicBot room. Who may
12715
+ // talk to a fleet agent in its own topic is the admin's channel access (#754); recording it only once some earlier
12716
+ // inheritance had created a row made a cleared agent re-arm on its next topic message (a project lead, 11-26). What an
12717
+ // agent inherits from peers, rooms, new instances and board notes still carries its origin.
12718
+ if (contactStore && this.contactRoom(instanceName)?.restrictedMode === true) {
10368
12719
  const authority = origin.authority;
10369
12720
  const identity = origin.platform === "web" && isWebSessionIdentity(origin.web_identity) ? origin.web_identity : undefined;
10370
12721
  const actor = origin.platform === "web" ? identity ?? (authority?.kind === "web-verified" ? authority.actor : null)
@@ -10395,8 +12746,14 @@ export class FleetManager {
10395
12746
  }
10396
12747
  }
10397
12748
  const verified = origin.platform === "web" && authority?.kind === "web-verified";
10398
- return { ...payload, meta: { ...(payload.meta ?? {}),
12749
+ const admitted = { ...payload, meta: { ...(payload.meta ?? {}),
10399
12750
  human_receipt_id: row.receipt_id, verification_id: row.message_id, ...(verified ? { web_verified: "1" } : {}) } };
12751
+ if (this.requestContextBoot) {
12752
+ const continuation = this.requestContextHumanContinuation(instanceName, row.receipt_id);
12753
+ if (continuation)
12754
+ requestPayloadContinuations.set(admitted, continuation);
12755
+ }
12756
+ return admitted;
10400
12757
  }
10401
12758
  /** Register owned preparation at IPC; bind once at the final pane write. No human retry lane. */
10402
12759
  bindHumanReceiptPayload(instanceName, payload) {
@@ -10405,6 +12762,11 @@ export class FleetManager {
10405
12762
  return payload;
10406
12763
  const daemon = this.daemons.get(instanceName);
10407
12764
  const owner = this.humanReceiptOwner(instanceName, daemon);
12765
+ const retained = retainedHumanControl(payload);
12766
+ const bind = (wire) => retained
12767
+ ? this.deliveryOutbox.bindRetainedHumanControlReceipt(retained, meta.human_receipt_id, instanceName, owner, wire, this.managerBootId, () => daemon?.bootId === retained.targetDaemonBootId && this.humanReceiptOwner(instanceName, daemon) === owner
12768
+ && (!this.requestContextAdmission || this.requestContextAdmission.available(requestPayloadContinuations.get(payload))))
12769
+ : this.deliveryOutbox.bindHumanReceipt(meta.human_receipt_id, instanceName, owner, wire, this.managerBootId);
10408
12770
  if (!daemon || !owner) {
10409
12771
  this.deliveryOutbox.markHumanReceiptUncertain(meta.human_receipt_id, instanceName);
10410
12772
  return payload;
@@ -10420,7 +12782,7 @@ export class FleetManager {
10420
12782
  throw new Error("Human delivery ownership changed");
10421
12783
  const dialectMeta = { ...originalMeta, human_wire_dialect: presentation.dialect ?? "legacy" };
10422
12784
  const wire = daemon.humanReceiptWire(content, dialectMeta, kind, presentation);
10423
- const row = this.deliveryOutbox.bindHumanReceipt(meta.human_receipt_id, instanceName, owner, wire, this.managerBootId);
12785
+ const row = bind(wire);
10424
12786
  if (this.humanReceiptOwner(instanceName, daemon) !== owner)
10425
12787
  throw new Error("Human delivery ownership changed");
10426
12788
  return { wire, meta: { human_owner_key: owner, human_daemon_owner: daemonOwner,
@@ -10429,7 +12791,7 @@ export class FleetManager {
10429
12791
  return { ...payload, meta: { ...meta, human_prepare_token: token } };
10430
12792
  }
10431
12793
  const wire = daemon.humanReceiptWire(String(payload.content ?? ""), meta, String(payload.type));
10432
- const row = this.deliveryOutbox.bindHumanReceipt(meta.human_receipt_id, instanceName, owner, wire, this.managerBootId);
12794
+ const row = bind(wire);
10433
12795
  if (!daemonOwner || this.humanReceiptOwner(instanceName, daemon) !== owner)
10434
12796
  throw new Error("Human delivery ownership changed");
10435
12797
  // /raw retains exact bytes and never acquires a positive verification capability.
@@ -10442,6 +12804,8 @@ export class FleetManager {
10442
12804
  async deliverHumanToInstance(instanceName, payload, origin, originalBody, options) {
10443
12805
  const admitted = this.humanReceiptPayload(instanceName, payload, origin, originalBody);
10444
12806
  const id = admitted.meta?.human_receipt_id;
12807
+ if (origin && id && requestContextPolicyInstalled(this.requestContextPolicy))
12808
+ nativeHumanInputs.set(admitted, { instance: instanceName, inputId: `human:hmsg-${id}` });
10445
12809
  let sent = false;
10446
12810
  try {
10447
12811
  const result = options ? await this.deliverToInstance(instanceName, admitted, options) : await this.deliverToInstance(instanceName, admitted);
@@ -10467,17 +12831,43 @@ export class FleetManager {
10467
12831
  }
10468
12832
  /** Synchronous steer/btw handoff, using the same evidence and owner binding. */
10469
12833
  sendHumanControl(instanceName, payload, origin, originalBody) {
10470
- const ipc = this.instanceIpcClients.get(instanceName);
10471
- if (this.shuttingDown || !ipc?.connected)
12834
+ if (this.shuttingDown || this.requestContextAdmission?.available() !== false && !this.instanceIpcClients.get(instanceName)?.connected)
10472
12835
  return false;
10473
12836
  const admitted = this.humanReceiptPayload(instanceName, payload, origin, originalBody);
10474
12837
  const id = admitted.meta?.human_receipt_id;
12838
+ if (this.requestContextAdmission && !this.requestContextAdmission.available(requestPayloadContinuations.get(admitted))) {
12839
+ try {
12840
+ if (!this.deliveryOutbox)
12841
+ throw Error("Held human control storage unavailable");
12842
+ const key = `human-control:${id ?? randomUUID()}`;
12843
+ this.deliveryOutbox.admit({ operationId: key, sourceKey: key, sourceInstance: "agend-system",
12844
+ sourceDaemonBootId: this.managerBootId, targetInstance: instanceName, kind: "human_control", payload: admitted });
12845
+ this.scheduleDeliveryOutboxPump();
12846
+ return true; // Acknowledged only after durable admission; publishing/aborting wakes the existing pump.
12847
+ }
12848
+ catch (error) {
12849
+ if (id)
12850
+ this.deliveryOutbox?.markHumanReceiptUncertain(id, instanceName);
12851
+ this.logger.warn({ err: error, instanceName }, "Human control could not be retained");
12852
+ return false;
12853
+ }
12854
+ }
12855
+ return FleetManager.prototype.sendAdmittedHumanControl.call(this, instanceName, admitted);
12856
+ }
12857
+ sendAdmittedHumanControl(instanceName, admitted) {
12858
+ const ipc = this.instanceIpcClients.get(instanceName);
12859
+ const id = admitted.meta?.human_receipt_id;
12860
+ if (this.shuttingDown || !ipc?.connected) {
12861
+ if (id)
12862
+ this.deliveryOutbox?.markHumanReceiptUncertain(id, instanceName);
12863
+ return false;
12864
+ }
10475
12865
  let sent = false;
10476
12866
  try {
10477
12867
  const wire = this.bindHumanReceiptPayload(instanceName, admitted);
10478
12868
  if (this.refuseHubPane(wire))
10479
12869
  return false;
10480
- if (this.holdPaneSend(wire)) {
12870
+ if (this.holdPaneSend(instanceName, wire)) {
10481
12871
  sent = true;
10482
12872
  return true;
10483
12873
  }
@@ -10491,16 +12881,23 @@ export class FleetManager {
10491
12881
  }
10492
12882
  /** Single delivery facade: wake paused CLIs and serialize non-user work behind idle. */
10493
12883
  async deliverToInstance(instanceName, payload, options = {}) {
12884
+ if (this.requestContextAdmission && !await this.requestContextAdmission.wait(() => !this.shuttingDown && options.stillCurrent?.() !== false, requestPayloadContinuations.get(payload)))
12885
+ return false;
10494
12886
  if (this.generalLocationDeliveryHold(instanceName))
10495
12887
  return false;
10496
12888
  if (isNativeExecInstance(this.fleetConfig?.instances[instanceName])) {
10497
12889
  if (options.beforeInput)
10498
12890
  return false; // no pre-input hook on the Windows runtime
12891
+ const input = nativeHumanInputs.get(payload);
10499
12892
  return this.nativeInstanceRuntime().deliver(instanceName, payload, { stillCurrent: options.stillCurrent,
12893
+ ...(input?.instance === instanceName ? { requestContextInputId: input.inputId } : {}),
10500
12894
  ...(options.authorityCurrent ? { authorityCurrent: options.authorityCurrent } : {}) });
10501
12895
  }
10502
12896
  const deliveryEpoch = this.getDeliveryEpoch(instanceName);
10503
12897
  const deliveryPayload = { ...payload, delivery_epoch: deliveryEpoch };
12898
+ const continuation = requestPayloadContinuations.get(payload);
12899
+ if (continuation)
12900
+ requestPayloadContinuations.set(deliveryPayload, continuation);
10504
12901
  const meta = payload.meta && typeof payload.meta === "object"
10505
12902
  ? payload.meta
10506
12903
  : undefined;
@@ -11337,6 +13734,8 @@ export class FleetManager {
11337
13734
  if (this.tmuxHold)
11338
13735
  throw new Error(this.tmuxHold.detail);
11339
13736
  if (isNativeExecInstance(config)) {
13737
+ if (this.prepareRequestContextOwnerRegistration)
13738
+ await this.prepareRequestContextOwnerRegistration(name, config);
11340
13739
  execution?.assert();
11341
13740
  if (!windowsCliEnabled())
11342
13741
  throw new Error("Windows runtime is disabled");
@@ -11412,11 +13811,23 @@ export class FleetManager {
11412
13811
  || (this.explicitStopGeneration.get(name) ?? 0) !== stopGen) {
11413
13812
  throw new SupersededStartError(name);
11414
13813
  }
13814
+ if (this.prepareRequestContextOwnerRegistration) {
13815
+ await this.prepareRequestContextOwnerRegistration(name, config);
13816
+ execution?.assert();
13817
+ if (this.lifecycle.epochOf(name) !== epoch || (this.explicitStopGeneration.get(name) ?? 0) !== stopGen)
13818
+ throw new SupersededStartError(name);
13819
+ }
13820
+ const ownedStart = this.prepareRequestContextStart?.(name, config);
13821
+ const instructionMode = requestContextInstructionMode(ownedStart?.policy);
13822
+ const requestContextStart = ownedStart ? Object.freeze({ policy: ownedStart.policy,
13823
+ current: () => ownedStart.current() && requestContextInstructionMode(ownedStart.policy) === instructionMode }) : undefined;
13824
+ if (requestContextStart && !requestContextStart.current())
13825
+ throw new SupersededStartError(name);
11415
13826
  const binary = BACKEND_INSTALLATION_INFO[backend]?.binary;
11416
13827
  if (binary && !windows)
11417
13828
  noteResolvedBinary(binary, resolved ?? binary);
11418
13829
  if (!windows && config.general_topic) {
11419
- this.ensureGeneralInstructions(config.working_directory, backend, name);
13830
+ this.ensureGeneralInstructions(config.working_directory, backend, name, instructionMode);
11420
13831
  }
11421
13832
  else if (!isWindowsInstance(config) && kind === "fleet-topic") {
11422
13833
  // Workers get only role-eligible on-demand skills. Classic instances are
@@ -11424,12 +13835,14 @@ export class FleetManager {
11424
13835
  // managed independently from fleet-topic workers.
11425
13836
  try {
11426
13837
  const skillsWorkDir = this.resolveKnowledgeWorkDir(config.working_directory, backend, name);
11427
- measureSyncWork("fleet.workerSkills", () => this.syncRoleSkills(skillsWorkDir, backend, "worker"));
13838
+ measureSyncWork("fleet.workerSkills", () => this.syncRoleSkills(skillsWorkDir, backend, "worker", undefined, false, instructionMode));
11428
13839
  }
11429
13840
  catch (err) {
11430
13841
  // Skill publishing is additive. A read-only or temporarily unavailable
11431
13842
  // workspace must not turn an otherwise valid worker startup into a
11432
13843
  // fleet outage.
13844
+ if (instructionMode !== null)
13845
+ throw err;
11433
13846
  this.logger.warn({ err, name, backend }, "Failed to sync worker skills — continuing startup");
11434
13847
  }
11435
13848
  }
@@ -11441,11 +13854,13 @@ export class FleetManager {
11441
13854
  try {
11442
13855
  const skillsWorkDir = this.resolveKnowledgeWorkDir(config.working_directory, backend, name);
11443
13856
  if (insideManagedWorkspaces(skillsWorkDir))
11444
- measureSyncWork("fleet.classicSkills", () => this.syncRoleSkills(skillsWorkDir, backend, "classic", undefined, this.classicContactRestricted(name)));
13857
+ measureSyncWork("fleet.classicSkills", () => this.syncRoleSkills(skillsWorkDir, backend, "classic", undefined, this.classicContactRestricted(name), instructionMode));
11445
13858
  else
11446
13859
  this.logger.debug({ name, skillsWorkDir }, "Classic workspace is not AgEnD-managed — no skills published");
11447
13860
  }
11448
13861
  catch (err) {
13862
+ if (instructionMode !== null)
13863
+ throw err;
11449
13864
  this.logger.warn({ err, name, backend }, "Failed to sync classic skills — continuing startup");
11450
13865
  }
11451
13866
  }
@@ -11457,10 +13872,10 @@ export class FleetManager {
11457
13872
  await this.lifecycle.start(name, config, topicMode, identity, transition, execution, daemon => {
11458
13873
  // Only this transition's actual publication can acquire its replacement.
11459
13874
  receipt.daemon = daemon;
11460
- });
13875
+ }, requestContextStart);
11461
13876
  }
11462
13877
  else
11463
- await this.lifecycle.start(name, config, topicMode, identity, transition, execution);
13878
+ await this.lifecycle.start(name, config, topicMode, identity, transition, execution, undefined, requestContextStart);
11464
13879
  }
11465
13880
  catch (err) {
11466
13881
  if (err instanceof LegacyWindowHoldError) {
@@ -11469,6 +13884,12 @@ export class FleetManager {
11469
13884
  }
11470
13885
  throw err;
11471
13886
  }
13887
+ if (this.requestContextOwnerStarted) {
13888
+ const owned = this.daemons.get(name);
13889
+ if (!owned)
13890
+ throw Error("Request owner did not start");
13891
+ this.requestContextOwnerStarted(name, owned);
13892
+ }
11472
13893
  if (this.legacyWindowHolds.delete(name))
11473
13894
  this.needsYou?.poke();
11474
13895
  execution?.assert();
@@ -14239,6 +16660,8 @@ export class FleetManager {
14239
16660
  finally {
14240
16661
  envLease.release();
14241
16662
  }
16663
+ if (this.requestContextBoot && !this.requestContextBoot.owner.current())
16664
+ await this.resetStoppedRequestContextAssembly();
14242
16665
  this.ensureDeliveryOutbox();
14243
16666
  // #1956: the spawn helper the fleet's tmux/stty commands are started by (its fork is cheap; the fleet's is not).
14244
16667
  // Started here and by the fleet's own timer — never by a tool handler — and stopped with the fleet.
@@ -14250,7 +16673,17 @@ export class FleetManager {
14250
16673
  const fleet = this.loadConfig(configPath, { startup: true });
14251
16674
  this.slimFleetConfigAtStartup();
14252
16675
  this.logConfigWarningsAtStartup();
14253
- this.initializeNativeInstances();
16676
+ if (this.requestContextBoot) {
16677
+ try {
16678
+ await this.prepareRequestContextCapableBoot(this.requestContextRootRetired);
16679
+ }
16680
+ catch (error) {
16681
+ this.requestContextCutoverErrors = [{ id: "boot", kind: "owners", labels: [], ownerCause: "update", action: "inspect" }];
16682
+ this.logger.error({ err: error.message }, "Capable request-context boot remains fenced");
16683
+ }
16684
+ }
16685
+ if (!this.requestContextBoot || this.requestContextModes?.current())
16686
+ this.initializeNativeInstances();
14254
16687
  // M-2255: from here on a change to the Windows runtimes' switches applies live (observeRuntimeSwitches).
14255
16688
  this.runtimeEffects = { windows_cli: localWindowsCliEnabled(), remote_runtime: remoteRuntimeEnabled() };
14256
16689
  setLocale(detectLocale(fleet)); // user-facing text language (fleet.yaml defaults.locale / timezone)
@@ -14271,6 +16704,8 @@ export class FleetManager {
14271
16704
  setUpdateProgressStage(this.dataDir, "starting", { version: pendingUpdateProgress.progress.version });
14272
16705
  }
14273
16706
  this.initializeWebAuthTokens();
16707
+ // M-3827: the people seen before this start keep their names in the web chat's mentions (before any adapter connects).
16708
+ this.seenUsers?.persistTo({ path: join(this.dataDir, SEEN_USERS_FILE), onWarn: message => this.logger.warn(message) });
14274
16709
  // Must run before the first General/CLI spawn: pressure can hold startup.
14275
16710
  // Logs remain available even before the adapters and health listener exist.
14276
16711
  this.memoryPressure.start();
@@ -14581,6 +17016,8 @@ export class FleetManager {
14581
17016
  // rows can never crowd an instance's own out (#3421 review). Nothing unbounded goes into process.env.
14582
17017
  this.snapshotActiveDecisions();
14583
17018
  }
17019
+ // M-3770 §2.6: a fleet an abandon restarted takes the held work back before any ingress opens (rev 15).
17020
+ await this.startUpdateHandback();
14584
17021
  // Phase 1: Start general instances first and wait for them
14585
17022
  // M-2457: a held fleet starts no agent (the hold's Needs-you line says why and what to do).
14586
17023
  const allEntries = this.tmuxHold ? [] : Object.entries(fleet.instances).filter(([, config]) => !isNativeExecInstance(config));
@@ -14859,6 +17296,22 @@ export class FleetManager {
14859
17296
  // startup-owned lifecycle work and signal handlers are in place.
14860
17297
  if (this.shuttingDown || this.startupMemoryDeadline !== deadline)
14861
17298
  return;
17299
+ if (this.requestContextModes?.current() && this.requestContextBoot?.publication.heldUnpublished()) {
17300
+ try {
17301
+ await this.prepareRequestContextFutureOwners();
17302
+ const peers = this.captureRequestContextRuntimeSet();
17303
+ await peers.prepare();
17304
+ const proof = peers.prove();
17305
+ this.requestContextModes.publish(() => proof.current() && this.requestContextOwnersReady());
17306
+ this.requestContextCutoverErrors = [];
17307
+ this.scheduleRequestContextDrain();
17308
+ }
17309
+ catch (error) {
17310
+ this.requestContextCutoverErrors = [{ id: "boot-readiness", kind: "owners", labels: [], ownerCause: "update", action: "inspect" }];
17311
+ this.logger.warn({ err: error.message }, "Request-context input remains fenced");
17312
+ }
17313
+ }
17314
+ this.requestContextControl?.changed();
14862
17315
  this.finishStartup(bootUpdateMarker);
14863
17316
  this.startupDashboard = null;
14864
17317
  this.publishStartupStatus();
@@ -15888,7 +18341,8 @@ export class FleetManager {
15888
18341
  this.logger.info({ sessionName: sender, instanceName: name }, "Registered external session");
15889
18342
  }
15890
18343
  try {
15891
- await this.handleOutboundFromInstance(name, msg);
18344
+ const run = () => this.handleOutboundFromInstance(name, msg);
18345
+ await (this.requestContextPendingWork ? this.requestContextPendingWork.run(name, run) : run());
15892
18346
  }
15893
18347
  finally {
15894
18348
  this.finishRequestContextIpcCall(msg);
@@ -15899,8 +18353,10 @@ export class FleetManager {
15899
18353
  // handler without passing through the outbound path — which is how
15900
18354
  // `update_decision`, a coordinator-only tool, kept a way through.
15901
18355
  const typed = this.checkToolPermission("ipc-typed", name, toolForIpcType(msg.type));
15902
- if (typed.allowed)
15903
- this.dispatchTypedIpc(name, msg);
18356
+ if (typed.allowed) {
18357
+ const run = () => this.dispatchTypedIpc(name, msg);
18358
+ await (this.requestContextPendingWork ? this.requestContextPendingWork.run(name, run) : run());
18359
+ }
15904
18360
  else
15905
18361
  this.refuseTypedIpc(name, msg, typed.message);
15906
18362
  }
@@ -17418,6 +19874,8 @@ export class FleetManager {
17418
19874
  // must never be read as a same-name replacement's (removed and re-registered meanwhile).
17419
19875
  const sentBy = tool === "reply" ? this.webChatIdentity(instanceName) : undefined;
17420
19876
  const args = (msg.args ?? {});
19877
+ const ownedReplyRoute = this.requestContextPolicy && ["reply", "react", "edit_message"].includes(tool) ? originatingCall?.replyRoute : undefined;
19878
+ const ownedReplyTarget = ownedReplyRoute?.target;
17421
19879
  const requestId = msg.requestId;
17422
19880
  const fleetRequestId = msg.fleetRequestId;
17423
19881
  const senderSessionName = msg.senderSessionName;
@@ -17453,7 +19911,7 @@ export class FleetManager {
17453
19911
  }
17454
19912
  try {
17455
19913
  if (this.requestContextPolicy)
17456
- requireRequestContextPolicy(this, instanceName, tool === "hub_room_status" ? "hub_room_list" : tool, args, originatingCall?.admission);
19914
+ requireRequestContextPolicy(this, instanceName, tool === "hub_room_status" ? "hub_room_list" : tool, args, originatingCall?.admission, originatingCall?.replyRoute);
17457
19915
  }
17458
19916
  catch (error) {
17459
19917
  respond(null, error.message);
@@ -17508,7 +19966,7 @@ export class FleetManager {
17508
19966
  if (tool === "react" && !this.classicChannels?.getAll?.().some(room => room.instanceName === instanceName && room.restrictedMode === true) && typeof args.message_id === "string" && isWebMessageId(args.message_id)) {
17509
19967
  // The socket's own instance, never a session name the caller wrote itself (as checkToolPermission: it was not
17510
19968
  // identified) — a channel tool's call from a daemon carries none anyway (#2310 review).
17511
- const r = await this.reactToWebMessage(instanceName, args.message_id, args.emoji);
19969
+ const r = await this.reactToWebMessage(instanceName, args.message_id, args.emoji, ownedReplyRoute);
17512
19970
  if (r.ok)
17513
19971
  respond("ok");
17514
19972
  else
@@ -17517,7 +19975,7 @@ export class FleetManager {
17517
19975
  }
17518
19976
  // A fleet with no chat platform at all is driven from the web dashboard alone: a reply has nowhere
17519
19977
  // else to go, and "retry shortly" would have the agent retry forever. It goes to the web chat.
17520
- const webOnlyReply = tool === "reply" && this.worlds.size === 0 && this.isWebOnlyFleet();
19978
+ const webOnlyReply = tool === "reply" && (ownedReplyTarget ? !ownedReplyTarget.chatId : this.worlds.size === 0 && this.isWebOnlyFleet());
17521
19979
  if (this.worlds.size === 0 && !webOnlyReply) {
17522
19980
  // #2910: on a web-only fleet there will never be an adapter — say so, so the agent does not retry forever.
17523
19981
  respond(null, this.isWebOnlyFleet()
@@ -17538,8 +19996,10 @@ export class FleetManager {
17538
19996
  downloadAttachment: (id) => this.downloadRoomAttachment(instanceName, id) } : {}),
17539
19997
  replyFinished: () => replyBookkeeping,
17540
19998
  beforeSend: () => {
17541
- if (originatingCall && !originatingCall.current())
19999
+ if (originatingCall && !originatingCall.current() || ownedReplyRoute && !ownedReplyRoute.current())
17542
20000
  throw Error("Originating request context is no longer current");
20001
+ if (ownedReplyTarget?.chatId && ownedReplyTarget.adapterId && (this.worlds.get(ownedReplyTarget.adapterId) !== contextWorld || contextWorld?.adapter !== outAdapter))
20002
+ throw new RequestContextPolicyError("stale");
17543
20003
  const current = this.restrictedClassicRouting(instanceName);
17544
20004
  if (restrictedRoute && (!current || current.adapterId !== restrictedRoute.adapterId || current.chatId !== restrictedRoute.chatId
17545
20005
  || current.threadId !== restrictedRoute.threadId || this.contactGeneration(instanceName) !== restrictedIncarnation
@@ -17549,7 +20009,7 @@ export class FleetManager {
17549
20009
  } : {};
17550
20010
  // Resolve threadId: use sender's topic_id if sender is a known fleet instance,
17551
20011
  // fall back to general topic if sender is unknown, or IPC owner if no sender.
17552
- const senderInstanceName = !restrictedRoute && senderSessionName && this.fleetConfig?.instances[senderSessionName]
20012
+ const senderInstanceName = !ownedReplyRoute && !restrictedRoute && senderSessionName && this.fleetConfig?.instances[senderSessionName]
17553
20013
  ? senderSessionName
17554
20014
  : null;
17555
20015
  const routingConfig = senderInstanceName
@@ -17561,18 +20021,15 @@ export class FleetManager {
17561
20021
  // ids are scoped to that bot/world; routing a secondary-world id through the
17562
20022
  // primary adapter produces a 404. Instance binding remains the compatibility
17563
20023
  // fallback for older daemons and calls without a live/persisted context.
17564
- const contextAdapterId = restrictedRoute?.adapterId ?? (typeof msg.adapterId === "string" && msg.adapterId
17565
- ? msg.adapterId
17566
- : undefined);
20024
+ const contextAdapterId = ownedReplyTarget ? ownedReplyTarget.chatId ? ownedReplyTarget.adapterId : undefined
20025
+ : restrictedRoute?.adapterId ?? (typeof msg.adapterId === "string" && msg.adapterId ? msg.adapterId : undefined);
17567
20026
  const contextWorld = contextAdapterId ? this.worlds.get(contextAdapterId) : undefined;
17568
20027
  if (contextAdapterId && !contextWorld) {
17569
20028
  respond(null, `Adapter world unavailable: ${contextAdapterId}`);
17570
20029
  return;
17571
20030
  }
17572
- const outAdapter = contextWorld?.adapter
17573
- ?? this.getAdapterForInstance(senderInstanceName ?? instanceName)
17574
- ?? this.adapter
17575
- ?? (webOnlyReply ? WEB_ONLY_REPLY_SINK : null);
20031
+ const outAdapter = ownedReplyTarget ? webOnlyReply ? WEB_ONLY_REPLY_SINK : contextWorld?.adapter
20032
+ : contextWorld?.adapter ?? this.getAdapterForInstance(senderInstanceName ?? instanceName) ?? this.adapter ?? (webOnlyReply ? WEB_ONLY_REPLY_SINK : null);
17576
20033
  if (!outAdapter) {
17577
20034
  respond(null, "No adapter available");
17578
20035
  return;
@@ -17605,6 +20062,18 @@ export class FleetManager {
17605
20062
  else
17606
20063
  delete args.thread_id;
17607
20064
  }
20065
+ if (ownedReplyTarget) {
20066
+ if (!ownedReplyRoute.current()) {
20067
+ respond(null, "Originating request context is no longer current");
20068
+ return;
20069
+ }
20070
+ args.chat_id = ownedReplyTarget.chatId;
20071
+ threadId = ownedReplyTarget.threadId;
20072
+ if (threadId)
20073
+ args.thread_id = threadId;
20074
+ else
20075
+ delete args.thread_id;
20076
+ }
17608
20077
  // Reply dedup: retries land here when the agent was told a send failed
17609
20078
  // (daemon budget elapsed, shell tool killed) while the adapter send was
17610
20079
  // still in flight and about to succeed. One real send, everyone gets its
@@ -18297,8 +20766,7 @@ export class FleetManager {
18297
20766
  }
18298
20767
  if (type === "fleet_list_emojis" || type === "fleet_set_persona_emoji" || type === "fleet_preview_emojis"
18299
20768
  || type === "fleet_list_stickers" || type === "fleet_preview_stickers") {
18300
- this.handlePersonaEmoji(name, msg);
18301
- return;
20769
+ return this.handlePersonaEmoji(name, msg);
18302
20770
  }
18303
20771
  if (type === "fleet_get_web_theme" || type === "fleet_set_web_theme" || type === "fleet_set_web_theme_asset" || type === "fleet_reset_web_theme"
18304
20772
  || type === "fleet_get_web_appearance" || type === "fleet_preview_web_appearance"
@@ -18351,7 +20819,7 @@ export class FleetManager {
18351
20819
  : msg.type === "fleet_list_stickers" ? this.listStickersFor(instanceName, payload)
18352
20820
  : msg.type === "fleet_preview_stickers" ? this.previewStickers(instanceName, payload)
18353
20821
  : this.setPersonaEmoji(instanceName, payload);
18354
- op.then((r) => typeof r.error === "string"
20822
+ return op.then((r) => typeof r.error === "string"
18355
20823
  ? ipc.send({ type: "fleet_persona_emoji_response", fleetRequestId, error: r.error })
18356
20824
  : ipc.send({ type: "fleet_persona_emoji_response", fleetRequestId, result: r }), (err) => ipc.send({ type: "fleet_persona_emoji_response", fleetRequestId, error: err.message }));
18357
20825
  }
@@ -22106,7 +24574,15 @@ export class FleetManager {
22106
24574
  }
22107
24575
  /** The list for the web: every world's items, and those of instances with no world (#1386 §5.0). */
22108
24576
  needsYouItems() {
22109
- return this.needsYou?.webItems() ?? [];
24577
+ const items = this.needsYou?.webItems?.() ?? [];
24578
+ const cutover = this.requestContextControl?.snapshot();
24579
+ if (cutover && (cutover.attempted || cutover.everActivated) && (cutover.phase === "draining" || cutover.enableFailed === true || cutover.blockers.length > 0)) {
24580
+ this.requestContextAttentionSince ??= Date.now();
24581
+ return [...items, { id: "request-context-cutover", type: "config", instance: "", reason: "request_context_cutover",
24582
+ detail: "", since: this.requestContextAttentionSince, requestContextCutover: cutover }];
24583
+ }
24584
+ this.requestContextAttentionSince = undefined;
24585
+ return items;
22110
24586
  }
22111
24587
  /** Enabled member composition supplies held-work readers and explicit owner retry/close operations. */
22112
24588
  attachHubExecutionAttention(read, retry = null, close = undefined) {
@@ -23994,7 +26470,7 @@ export class FleetManager {
23994
26470
  // #1827: a /steer or /btw reaches the agent as the web person who wrote it.
23995
26471
  chatId: this.getGroupIdForInstance(instance) || "", messageId: newWebMessageId(),
23996
26472
  username: opts.person?.name ?? WEB_NAME_FALLBACK, userId: opts.person?.userId ?? WEB_NAME_FALLBACK,
23997
- threadId: topicId != null ? String(topicId) : undefined, adapterId: this.getAdapterForInstance(instance)?.id ?? "", source: "web", humanOrigin: webHumanOrigin(true, opts.authority, opts.identity),
26473
+ threadId: topicId != null ? String(topicId) : undefined, adapterId: this.getAdapterForInstance(instance)?.id ?? "", source: "web", humanOrigin: webHumanOrigin(true, opts.authority, opts.identity, !!opts.guest, opts.sessionHandle),
23998
26474
  ...(opts.guest ? { webGuest: true } : {}), // #2855: a guest's /steer or /btw reaches the agent as a guest's
23999
26475
  };
24000
26476
  };
@@ -28134,10 +30610,10 @@ export class FleetManager {
28134
30610
  static INSTRUCTIONS_FILENAME = Object.fromEntries(Object.entries(INSTRUCTIONS_FILE).map(([id, e]) => [id, e.file]));
28135
30611
  static GENERAL_INSTRUCTIONS = GENERAL_ROLE_INSTRUCTIONS;
28136
30612
  /** Ensure the general instance has its project instructions file + knowledge */
28137
- ensureGeneralInstructions(workDir, backendName, instanceName) {
28138
- measureSyncWork("fleet.generalInstructions", () => this.ensureGeneralInstructionsSync(workDir, backendName, instanceName));
30613
+ ensureGeneralInstructions(workDir, backendName, instanceName, mode = requestContextInstructionMode(this.requestContextPolicy)) {
30614
+ measureSyncWork("fleet.generalInstructions", () => this.ensureGeneralInstructionsSync(workDir, backendName, instanceName, mode));
28139
30615
  }
28140
- ensureGeneralInstructionsSync(workDir, backendName, instanceName) {
30616
+ ensureGeneralInstructionsSync(workDir, backendName, instanceName, mode = requestContextInstructionMode(this.requestContextPolicy)) {
28141
30617
  const backend = backendName ?? "claude-code";
28142
30618
  workDir = this.resolveKnowledgeWorkDir(workDir, backend, instanceName);
28143
30619
  // Board 0340ec89: General's file from before, under the lowercase name agy never read, becomes the one it reads.
@@ -28173,7 +30649,7 @@ export class FleetManager {
28173
30649
  }
28174
30650
  }
28175
30651
  // Sync bundled knowledge files to general's steering and skills directories.
28176
- this.syncGeneralKnowledge(workDir, backend);
30652
+ this.syncGeneralKnowledge(workDir, backend, mode);
28177
30653
  }
28178
30654
  /** Resolve the workspace path a backend actually uses before publishing knowledge. */
28179
30655
  resolveKnowledgeWorkDir(workDir, backend, instanceName) {
@@ -28210,16 +30686,16 @@ export class FleetManager {
28210
30686
  "antigravity": [".agents", "skills"],
28211
30687
  };
28212
30688
  /** Copy general-knowledge steering + all role-eligible skills to General. */
28213
- syncGeneralKnowledge(workDir, backend) {
30689
+ syncGeneralKnowledge(workDir, backend, mode = requestContextInstructionMode(this.requestContextPolicy)) {
28214
30690
  const knowledgeDir = join(dirname(fileURLToPath(import.meta.url)), "general-knowledge");
28215
30691
  if (!existsSync(knowledgeDir))
28216
30692
  return;
28217
- this.syncGeneralSteering(workDir, backend, join(knowledgeDir, "steering"));
28218
- this.syncRoleSkills(workDir, backend, "general", knowledgeDir);
30693
+ this.syncGeneralSteering(workDir, backend, join(knowledgeDir, "steering"), mode);
30694
+ this.syncRoleSkills(workDir, backend, "general", knowledgeDir, false, mode);
28219
30695
  this.logger.debug({ knowledgeDir, workDir, backend }, "Synced general knowledge files");
28220
30696
  }
28221
30697
  /** Publish only the bundled skills eligible for an instance role. */
28222
- syncRoleSkills(workDir, backend, role, knowledgeDir, restrictedClassic = false) {
30698
+ syncRoleSkills(workDir, backend, role, knowledgeDir, restrictedClassic = false, mode = requestContextInstructionMode(this.requestContextPolicy)) {
28223
30699
  const skillSegments = FleetManager.SKILLS_DIR_SEGMENTS[backend];
28224
30700
  if (!skillSegments)
28225
30701
  return;
@@ -28234,7 +30710,7 @@ export class FleetManager {
28234
30710
  this.syncManagedSkills(join(workDir, ...skillSegments), join(root, "skills"), role, adoptLegacyUnmanaged,
28235
30711
  // #2163: a Classic bot's skills folder (or a skill in it) may be a link out of its workspace; every path is
28236
30712
  // checked where it really lands, just before it is written.
28237
- role === "classic" ? (path) => insideManagedWorkspaces(path) : undefined, role === "classic" && restrictedClassic ? new Set(["persona-emoji", "web-appearance"]) : undefined);
30713
+ role === "classic" ? (path) => insideManagedWorkspaces(path) : undefined, role === "classic" && restrictedClassic ? new Set(["persona-emoji", "web-appearance"]) : undefined, mode);
28238
30714
  this.logger.debug({ workDir, backend, role }, "Synced role-based bundled skills");
28239
30715
  }
28240
30716
  /**
@@ -28246,7 +30722,7 @@ export class FleetManager {
28246
30722
  * sync, so rule updates reach EXISTING workspaces; everything the user
28247
30723
  * wrote outside the markers is preserved byte-for-byte.
28248
30724
  */
28249
- syncGeneralSteering(workDir, backend, srcSteering) {
30725
+ syncGeneralSteering(workDir, backend, srcSteering, mode = requestContextInstructionMode(this.requestContextPolicy)) {
28250
30726
  if (!existsSync(srcSteering))
28251
30727
  return;
28252
30728
  const files = readdirSync(srcSteering).filter(f => f.endsWith(".md")).sort();
@@ -28257,7 +30733,7 @@ export class FleetManager {
28257
30733
  mkdirSync(steeringDir, { recursive: true });
28258
30734
  for (const file of files) {
28259
30735
  const dest = join(steeringDir, file);
28260
- const newContent = readFileSync(join(srcSteering, file), "utf-8");
30736
+ const newContent = requestContextSteeringText(readFileSync(join(srcSteering, file), "utf-8"), file === "core-rules.md" ? mode : null);
28261
30737
  try {
28262
30738
  if (existsSync(dest) && readFileSync(dest, "utf-8") === newContent)
28263
30739
  continue;
@@ -28271,7 +30747,7 @@ export class FleetManager {
28271
30747
  const instructionsPath = join(workDir, filename);
28272
30748
  if (backend === "antigravity" && danglingSymlink(instructionsPath))
28273
30749
  return; // kept, not followed (#1914 review; logged above)
28274
- const body = files.map(f => readFileSync(join(srcSteering, f), "utf-8").trim()).join("\n\n");
30750
+ const body = files.map(f => requestContextSteeringText(readFileSync(join(srcSteering, f), "utf-8"), f === "core-rules.md" ? mode : null).trim()).join("\n\n");
28275
30751
  const block = `${FleetManager.STEERING_BLOCK_BEGIN}\n${body}\n${FleetManager.STEERING_BLOCK_END}`;
28276
30752
  let existing = "";
28277
30753
  try {
@@ -28361,7 +30837,7 @@ export class FleetManager {
28361
30837
  catch { /* said this time; said again next start */ }
28362
30838
  this.logger.warn({ skills: names, destSkills }, "Skipping bundled skills — skills of these names exist but were not published by AgEnD");
28363
30839
  }
28364
- syncManagedSkills(destSkills, srcSkills, role, adoptLegacyUnmanaged = false, confined, excluded) {
30840
+ syncManagedSkills(destSkills, srcSkills, role, adoptLegacyUnmanaged = false, confined, excluded, mode = null) {
28365
30841
  if (!existsSync(srcSkills))
28366
30842
  return;
28367
30843
  const refuse = (path) => {
@@ -28424,7 +30900,7 @@ export class FleetManager {
28424
30900
  continue;
28425
30901
  }
28426
30902
  managed.push(name);
28427
- const newContent = bundledSkillContents(join(srcSkills, name));
30903
+ const newContent = requestContextSkillText(name, bundledSkillContents(join(srcSkills, name)), mode);
28428
30904
  if (refuse(dest))
28429
30905
  continue;
28430
30906
  try {
@@ -31596,6 +34072,16 @@ export class FleetManager {
31596
34072
  const instanceName = classicChannels.deriveInstanceName(channelName || channelId, channelId, adapterId);
31597
34073
  clearPausedMarker(this.getInstanceDir(instanceName));
31598
34074
  const selectedBackend = isSelectableClassicBackend(backend) ? backend : undefined;
34075
+ if (requestContextPolicyInstalled(this.requestContextPolicy) && !classicChannels.get(channelId, adapterId)) {
34076
+ // Durable first-birth intent precedes the Classic registry's own save. A restart/token read cannot mint it.
34077
+ this.settleHubIncarnations();
34078
+ if (this.hubIncarnationsBroken)
34079
+ throw Error("Request work registration evidence unavailable");
34080
+ const planned = { ...DEFAULT_INSTANCE_CONFIG, ...this.fleetConfig?.defaults, backend: selectedBackend ?? this.fleetConfig?.defaults?.backend ?? "claude-code",
34081
+ working_directory: this.classicWorkspaceDir(instanceName), hubClassicIdentity: JSON.stringify([adapterId ?? "", channelId]) };
34082
+ if (!this.hubAgentIncarnation(instanceName, planned, true, true))
34083
+ throw Error("Request work registration evidence unavailable");
34084
+ }
31599
34085
  classicChannels.register(channelId, adapterId, instanceName, channelName || channelId, userId, selectedBackend, restricted);
31600
34086
  // Bind this classic instance to the bot that started it (authoritative), so
31601
34087
  // replies/cancel go out through that bot even though every same-guild bot
@@ -31745,6 +34231,13 @@ export class FleetManager {
31745
34231
  // because we asked it to. Set synchronously — doStopAll runs to its first
31746
34232
  // await in the same tick as the signal handler, so no event can slip in.
31747
34233
  this.shuttingDown = true;
34234
+ if (this.requestContextDrainTimer)
34235
+ clearTimeout(this.requestContextDrainTimer);
34236
+ this.requestContextDrainTimer = undefined;
34237
+ if (this.requestContextCollectionTimer)
34238
+ clearInterval(this.requestContextCollectionTimer);
34239
+ this.requestContextCollectionTimer = undefined;
34240
+ this.requestContextAdmission?.changed();
31748
34241
  try {
31749
34242
  this.updateCard?.close();
31750
34243
  }
@@ -32039,6 +34532,7 @@ export class FleetManager {
32039
34532
  // write that failed and is still owed — is paid now, so a restart neither shortens the idle window
32040
34533
  // nor revives a session that was revoked while the disk was refusing writes.
32041
34534
  this.webSessions?.flush();
34535
+ this.seenUsers?.flush(); // M-3827: the names seen since the last write
32042
34536
  this.eventLog?.close();
32043
34537
  this.replyButtonsCtl?.stop();
32044
34538
  this.replyButtonsStore?.close();
@@ -32053,6 +34547,13 @@ export class FleetManager {
32053
34547
  }
32054
34548
  // The lock contains a nonce, so an older/shutting-down process can never
32055
34549
  // remove a lock acquired by a newer fleet owner.
34550
+ if (this.requestContextBoot)
34551
+ try {
34552
+ await this.resetStoppedRequestContextAssembly();
34553
+ }
34554
+ catch (error) {
34555
+ this.logger.warn({ err: error.message }, "Request owners remain fenced for positive retirement before restart");
34556
+ }
32056
34557
  releaseProcessFleetLock();
32057
34558
  }
32058
34559
  /**
@@ -34233,6 +36734,7 @@ export class FleetManager {
34233
36734
  if (now !== target)
34234
36735
  continue; // the offer changed: judge the new one
34235
36736
  this.updatePreflight = mergePreflight(this.updatePreflight, fresh, now);
36737
+ void this.syncUpdateChatCard(); // M-3864 R1: the chat card's buttons follow it
34236
36738
  return;
34237
36739
  }
34238
36740
  })().finally(() => { if (this.updatePreflightRunning === running)
@@ -34259,6 +36761,120 @@ export class FleetManager {
34259
36761
  this.updatePreflight = mergePreflight(this.updatePreflight, fresh, this.updateCheckState?.offer?.version ?? null);
34260
36762
  return preflightRefusal(fresh, origin, (key, ...args) => t(key, ...args));
34261
36763
  }
36764
+ /** M-3770 1.6: make a pre-flight fix (update-fix.ts; tests stub this, so no real loginctl runs). */
36765
+ async runUpdateFix(fix) {
36766
+ const [{ applyUpdateFix }, { defaultReadinessDeps }] = await Promise.all([import("./update-fix.js"), import("./update-readiness.js")]);
36767
+ return applyUpdateFix(fix, defaultReadinessDeps());
36768
+ }
36769
+ /**
36770
+ * M-3770 S-246: Install as a service — this install's own `agend install` (never the PATH's), started apart from this
36771
+ * fleet so it outlives it, with its words in `<home>/service-install.log`. It stops this fleet by its proof and starts
36772
+ * the service (service-install-handover.ts). Waits up to 30 s to tell a refusal (nothing stopped) from the hand-over
36773
+ * (this fleet begins to stop). Tests stub this, so nothing is installed or stopped.
36774
+ */
36775
+ async startServiceInstall() {
36776
+ const [{ spawn }, { selfCommand }, { watchServiceInstall }, { SERVICE_LOCK_TOKEN_ENV }, { DIRECT_FLEET_START_ENV }] = await Promise.all([
36777
+ import("./child-process.js"), import("./cli-entry.js"), import("./update-fix.js"), import("./service-lock.js"), import("./service-owner.js")
36778
+ ]);
36779
+ const logPath = join(this.dataDir, "service-install.log");
36780
+ const logFd = openUpdateLog(logPath, `--- agend install (web, Install as a service) ${new Date().toISOString()} ---`);
36781
+ const command = selfCommand(["install"]);
36782
+ // Its own admission to the service lock, and its own fleet start if the service can't start: none of this fleet's.
36783
+ const env = { ...process.env };
36784
+ delete env[SERVICE_LOCK_TOKEN_ENV];
36785
+ delete env[DIRECT_FLEET_START_ENV];
36786
+ let exitCode;
36787
+ const child = spawn(command.command, command.args, {
36788
+ detached: true, stdio: ["ignore", logFd ? logFd.fd : "ignore", logFd ? logFd.fd : "ignore"], env,
36789
+ });
36790
+ if (logFd)
36791
+ closeSync(logFd.fd); // the child keeps its own copy
36792
+ child.on("exit", code => { exitCode = code; });
36793
+ child.on("error", () => { exitCode ??= -1; });
36794
+ child.unref();
36795
+ return watchServiceInstall({
36796
+ exitCode: () => exitCode, shuttingDown: () => this.shuttingDown,
36797
+ // This run's words only: from its own header on (the log keeps earlier runs above it).
36798
+ output: () => { const text = readLogTail(logPath) ?? ""; return text.slice(Math.max(0, text.lastIndexOf("--- agend install (web"))); },
36799
+ now: () => performance.now(), sleep: ms => new Promise(resolve => setTimeout(resolve, ms)), waitMs: 30_000,
36800
+ });
36801
+ }
36802
+ /**
36803
+ * M-3770 1.6: POST /ui/update/fixes. The same key gets the same answer; one fix runs at a time. The local checks run
36804
+ * again first and decide whether the fix is still asked for (a page drawn from an older result never runs it); the
36805
+ * session is asked again right before it runs; the checks run once more after it, and the page gets that result.
36806
+ */
36807
+ fixUpdateOnce(key, person, fix, stillAllowed) {
36808
+ // Scoped to the person and the fix (#4557 review): one admin's key never replays another's answer.
36809
+ const slot = JSON.stringify([person, fix, key]);
36810
+ const seen = this.updateFixAnswers.get(slot);
36811
+ if (seen)
36812
+ return seen;
36813
+ const answer = this.updateFixChain.then(() => this.fixUpdateNow(person, fix, stillAllowed));
36814
+ this.updateFixChain = answer.then(() => undefined, () => undefined);
36815
+ this.updateFixAnswers.set(slot, answer);
36816
+ if (this.updateFixAnswers.size > 32)
36817
+ this.updateFixAnswers.delete(this.updateFixAnswers.keys().next().value);
36818
+ return answer;
36819
+ }
36820
+ async fixUpdateNow(person, fix, stillAllowed) {
36821
+ const [{ mergePreflight }, { fixOffered }] = await Promise.all([import("./update-readiness.js"), import("./update-fix.js")]);
36822
+ const local = async () => {
36823
+ try {
36824
+ const fresh = await this.probeUpdatePreflight({ localOnly: true });
36825
+ this.updatePreflight = mergePreflight(this.updatePreflight, fresh, this.updateCheckState?.offer?.version ?? null);
36826
+ return fresh;
36827
+ }
36828
+ catch (err) {
36829
+ this.logger.warn({ err }, "Update pre-flight could not run for a fix");
36830
+ return null;
36831
+ }
36832
+ };
36833
+ const before = await local();
36834
+ if (!before)
36835
+ return { status: 503, body: { error: "preflight_unavailable", preflight: this.updatePreflight } };
36836
+ if (!fixOffered(before, fix))
36837
+ return { status: 409, body: { error: "not_needed", preflight: this.updatePreflight } };
36838
+ if (this.shuttingDown || !stillAllowed())
36839
+ return { status: 403, body: { error: "update_needs_an_admin_session" } };
36840
+ if (fix === "service") {
36841
+ // S-246: the hand-over to the service manager. 202 { restarting } once this fleet begins to stop; 202 { pending } when
36842
+ // the command still runs after the wait (nothing may have stopped yet, and it can still refuse: the page says so and
36843
+ // looks again, never claiming a restart — #4564 review); 422 with the command's own words when it refused (nothing was
36844
+ // stopped) or failed (the fleet was started again).
36845
+ let result;
36846
+ try {
36847
+ result = await this.startServiceInstall();
36848
+ }
36849
+ catch (err) {
36850
+ this.logger.warn({ err }, "Install as a service could not start");
36851
+ result = { kind: "failed", reason: "agend install could not start" };
36852
+ }
36853
+ this.logger.info({ person, fix, result: result.kind }, "web: update pre-flight fix");
36854
+ if (result.kind === "restarting")
36855
+ return { status: 202, body: { restarting: true } };
36856
+ await local();
36857
+ if (result.kind === "pending")
36858
+ return { status: 202, body: { pending: true, preflight: this.updatePreflight } };
36859
+ if (result.kind !== "failed")
36860
+ return { status: 200, body: { preflight: this.updatePreflight } };
36861
+ const [{ serviceInstallCause }, { installRunsOnWsl }] = await Promise.all([import("./update-fix.js"), import("./install-user-systemd.js")]);
36862
+ const cause = serviceInstallCause(result.reason);
36863
+ // On WSL the user-manager cause has its own known fix (wsl --update); elsewhere the page names the generic check (#4564 look).
36864
+ const where = cause === "user-manager" && installRunsOnWsl() ? "wsl" : null;
36865
+ return { status: 422, body: { error: "fix_failed", reason: result.reason, cause, ...(where ? { where } : {}), preflight: this.updatePreflight } };
36866
+ }
36867
+ let ok = false;
36868
+ try {
36869
+ ok = (await this.runUpdateFix(fix)).ok;
36870
+ }
36871
+ catch (err) {
36872
+ this.logger.warn({ err, fix }, "Update pre-flight fix failed");
36873
+ }
36874
+ this.logger.info({ person, fix, ok }, "web: update pre-flight fix");
36875
+ await local();
36876
+ return ok ? { status: 200, body: { preflight: this.updatePreflight } } : { status: 422, body: { error: "fix_failed", preflight: this.updatePreflight } };
36877
+ }
34262
36878
  ensureUpdateCard() {
34263
36879
  if (this.updateCard)
34264
36880
  return this.updateCard;
@@ -34367,7 +36983,7 @@ export class FleetManager {
34367
36983
  }
34368
36984
  catch { /* unknown */ }
34369
36985
  const pinned = !!resolveUpdates(this.fleetConfig?.updates).pin;
34370
- const reply = updateOfferReply(this.updateOfferView(), current, pinned);
36986
+ const reply = updateOfferReply(this.updateOfferView(), current, pinned, this.usageZone());
34371
36987
  return t(reply.key, ...reply.args);
34372
36988
  }
34373
36989
  refuseImmediateUpdate() {
@@ -34458,6 +37074,7 @@ export class FleetManager {
34458
37074
  updateLog: () => ({ text: readLogTail(updateLogPath(this.dataDir)), error: readUpdateProgress(this.dataDir)?.progress.error ?? null }),
34459
37075
  card: () => this.refreshUpdateCard(),
34460
37076
  answerUpdate: (key, by, body, stillAllowed) => this.ensureUpdateCard().answer(key, by, body, stillAllowed),
37077
+ fixUpdate: (key, person, fix, stillAllowed) => this.fixUpdateOnce(key, person, fix, stillAllowed),
34461
37078
  };
34462
37079
  }
34463
37080
  /** "Check for updates": look now, no chat notice. One a minute; a second ask while one runs waits for it. */