@code-yeongyu/senpi 2026.9.21-2 → 2026.9.22

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 (239) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/dist/bundle/chunks/{anthropic-messages-C3ZY2ANT.js → anthropic-messages-2P7APOOQ.js} +1 -1
  3. package/dist/bundle/chunks/{app-server-command-HSX5RFAP.js → app-server-command-DLBXJ5K5.js} +1 -1
  4. package/dist/bundle/chunks/{azure-openai-responses-7TAGS2VU.js → azure-openai-responses-3AH7MJWF.js} +1 -1
  5. package/dist/bundle/chunks/{chunk-3SLCHXZO.js → chunk-4AXZDO3E.js} +2 -2
  6. package/dist/bundle/chunks/{chunk-Z3KQB2R3.js → chunk-7ICH7UFW.js} +12 -12
  7. package/dist/bundle/chunks/{chunk-KNM6SRPE.js → chunk-AAVNXTGQ.js} +1 -1
  8. package/dist/bundle/chunks/{chunk-IDTLJYJ5.js → chunk-AY37SZJZ.js} +4 -4
  9. package/dist/bundle/chunks/{chunk-XHMOFY4T.js → chunk-BUPX33Q4.js} +3 -3
  10. package/dist/bundle/chunks/{chunk-GLKVDRNP.js → chunk-CWCY7LXK.js} +1 -1
  11. package/dist/bundle/chunks/{chunk-POMPEGWQ.js → chunk-F3DXL5MX.js} +1 -1
  12. package/dist/bundle/chunks/{chunk-GVI2HP7N.js → chunk-I2HIIJPI.js} +1 -1
  13. package/dist/bundle/chunks/{chunk-T6XA2IZR.js → chunk-JR4X6ECO.js} +1 -1
  14. package/dist/bundle/chunks/{chunk-M2XAY6I7.js → chunk-M2HSO7MH.js} +1 -1
  15. package/dist/bundle/chunks/{chunk-MIVOQT3Q.js → chunk-N5AQJAQ2.js} +1 -1
  16. package/dist/bundle/chunks/{chunk-UYVPLEOL.js → chunk-NK2RNX25.js} +1 -1
  17. package/dist/bundle/chunks/chunk-NMB4C6ZZ.js +2 -0
  18. package/dist/bundle/chunks/{chunk-B7W62BM7.js → chunk-P4OHEJ7P.js} +1 -1
  19. package/dist/bundle/chunks/{chunk-I425CMTO.js → chunk-VBNHBSBD.js} +1 -1
  20. package/dist/bundle/chunks/{chunk-B2IM56LB.js → chunk-VYIJQQ5I.js} +1 -1
  21. package/dist/bundle/chunks/chunk-XRHUMMIW.js +8 -0
  22. package/dist/bundle/chunks/{chunk-47GF6XYZ.js → chunk-YT2ZSZOY.js} +1 -1
  23. package/dist/bundle/chunks/{chunk-OSDJ2SYO.js → chunk-ZCBX2K34.js} +1 -1
  24. package/dist/bundle/chunks/{chunk-D5CL7PPD.js → chunk-ZMVXBX33.js} +2 -2
  25. package/dist/bundle/chunks/{cli-main-GQTEEZ2V.js → cli-main-D2VPNIQ3.js} +1 -1
  26. package/dist/bundle/chunks/{google-generative-ai-JWIH75VF.js → google-generative-ai-Y2IYMUVC.js} +1 -1
  27. package/dist/bundle/chunks/{google-vertex-IRGAY5XR.js → google-vertex-TKBBMPHV.js} +1 -1
  28. package/dist/bundle/chunks/{host-command-KOEKIHIZ.js → host-command-IFIIOX5S.js} +1 -1
  29. package/dist/bundle/chunks/host-lifecycle-3OJZA4QQ.js +3 -0
  30. package/dist/bundle/chunks/host-lifecycle.js +3 -3
  31. package/dist/bundle/chunks/{interactive-host-runtime-2KTFEW7O.js → interactive-host-runtime-V7PBDIOJ.js} +1 -1
  32. package/dist/bundle/chunks/{interactive-mode-I3ILWXQB.js → interactive-mode-RFMMGQCT.js} +1 -1
  33. package/dist/bundle/chunks/kimi-coding.js +2 -2
  34. package/dist/bundle/chunks/{mistral-conversations-VOBYATVJ.js → mistral-conversations-ZYDVFRYF.js} +1 -1
  35. package/dist/bundle/chunks/{multi-session-host-S5FWCIWE.js → multi-session-host-45YMCQIH.js} +8 -7
  36. package/dist/bundle/chunks/openai-codex-responses-MEIUNROM.js +10 -0
  37. package/dist/bundle/chunks/{openai-completions-YK6QTYOH.js → openai-completions-4V76L5ZJ.js} +1 -1
  38. package/dist/bundle/chunks/openai-responses-YR7WRBG3.js +2 -0
  39. package/dist/bundle/chunks/{package-manager-cli-HOL6CAI6.js → package-manager-cli-7DQKRSI5.js} +1 -1
  40. package/dist/bundle/chunks/rotation-stream-YPZP3VJS.js +2 -0
  41. package/dist/bundle/chunks/{rpc-mode-L3DSGTVM.js → rpc-mode-4GWZCJKI.js} +1 -1
  42. package/dist/bundle/chunks/{session-picker-L3FYEQBL.js → session-picker-ZKRYWZGC.js} +1 -1
  43. package/dist/bundle/chunks/session-worker.js +38 -37
  44. package/dist/bundle/cli.js +1 -1
  45. package/dist/bundle/index.js +1 -1
  46. package/dist/bundle/rpc-entry.js +1 -1
  47. package/dist/core/agent-session.d.ts +6 -4
  48. package/dist/core/agent-session.d.ts.map +1 -1
  49. package/dist/core/agent-session.js +9 -7
  50. package/dist/core/agent-session.js.map +1 -1
  51. package/dist/core/credential-pool/classify.d.ts.map +1 -1
  52. package/dist/core/credential-pool/classify.js +12 -0
  53. package/dist/core/credential-pool/classify.js.map +1 -1
  54. package/dist/core/credential-pool/failover.d.ts +37 -5
  55. package/dist/core/credential-pool/failover.d.ts.map +1 -1
  56. package/dist/core/credential-pool/failover.js +60 -24
  57. package/dist/core/credential-pool/failover.js.map +1 -1
  58. package/dist/core/credential-pool/rotation-events.d.ts +5 -0
  59. package/dist/core/credential-pool/rotation-events.d.ts.map +1 -0
  60. package/dist/core/credential-pool/rotation-events.js +25 -0
  61. package/dist/core/credential-pool/rotation-events.js.map +1 -0
  62. package/dist/core/credential-pool/rotation-stream.d.ts +4 -3
  63. package/dist/core/credential-pool/rotation-stream.d.ts.map +1 -1
  64. package/dist/core/credential-pool/rotation-stream.js +8 -11
  65. package/dist/core/credential-pool/rotation-stream.js.map +1 -1
  66. package/dist/core/extensions/builtin/ask-user/schema.d.ts +2 -25
  67. package/dist/core/extensions/builtin/ask-user/schema.d.ts.map +1 -1
  68. package/dist/core/extensions/builtin/ask-user/schema.js.map +1 -1
  69. package/dist/core/extensions/builtin/compaction/deterministic-fallback.d.ts +2 -7
  70. package/dist/core/extensions/builtin/compaction/deterministic-fallback.d.ts.map +1 -1
  71. package/dist/core/extensions/builtin/compaction/deterministic-fallback.js +2 -8
  72. package/dist/core/extensions/builtin/compaction/deterministic-fallback.js.map +1 -1
  73. package/dist/core/extensions/builtin/mcp/expose/naming.d.ts +0 -1
  74. package/dist/core/extensions/builtin/mcp/expose/naming.d.ts.map +1 -1
  75. package/dist/core/extensions/builtin/mcp/expose/naming.js +0 -3
  76. package/dist/core/extensions/builtin/mcp/expose/naming.js.map +1 -1
  77. package/dist/core/extensions/builtin/mcp/expose/register.d.ts +1 -2
  78. package/dist/core/extensions/builtin/mcp/expose/register.d.ts.map +1 -1
  79. package/dist/core/extensions/builtin/mcp/expose/register.js +0 -21
  80. package/dist/core/extensions/builtin/mcp/expose/register.js.map +1 -1
  81. package/dist/core/extensions/builtin/mcp/expose/schema-compat.d.ts +2 -2
  82. package/dist/core/extensions/builtin/mcp/expose/schema-compat.d.ts.map +1 -1
  83. package/dist/core/extensions/builtin/mcp/expose/schema-compat.js +2 -2
  84. package/dist/core/extensions/builtin/mcp/expose/schema-compat.js.map +1 -1
  85. package/dist/core/http-dispatcher.d.ts +29 -0
  86. package/dist/core/http-dispatcher.d.ts.map +1 -1
  87. package/dist/core/http-dispatcher.js +30 -3
  88. package/dist/core/http-dispatcher.js.map +1 -1
  89. package/dist/modes/interactive/components/assistant-render-descriptors.d.ts.map +1 -1
  90. package/dist/modes/interactive/components/assistant-render-descriptors.js +8 -7
  91. package/dist/modes/interactive/components/assistant-render-descriptors.js.map +1 -1
  92. package/dist/modes/print-mode.d.ts.map +1 -1
  93. package/dist/modes/print-mode.js +7 -5
  94. package/dist/modes/print-mode.js.map +1 -1
  95. package/dist/modes/rpc/handoff-activity.d.ts +4 -0
  96. package/dist/modes/rpc/handoff-activity.d.ts.map +1 -0
  97. package/dist/modes/rpc/handoff-activity.js +6 -0
  98. package/dist/modes/rpc/handoff-activity.js.map +1 -0
  99. package/dist/modes/rpc/host-ensure.d.ts.map +1 -1
  100. package/dist/modes/rpc/host-ensure.js +60 -17
  101. package/dist/modes/rpc/host-ensure.js.map +1 -1
  102. package/dist/modes/rpc/host-lifecycle.d.ts +3 -0
  103. package/dist/modes/rpc/host-lifecycle.d.ts.map +1 -1
  104. package/dist/modes/rpc/host-lifecycle.js +25 -5
  105. package/dist/modes/rpc/host-lifecycle.js.map +1 -1
  106. package/dist/modes/rpc/multi-session-host.d.ts +1 -0
  107. package/dist/modes/rpc/multi-session-host.d.ts.map +1 -1
  108. package/dist/modes/rpc/multi-session-host.js +40 -7
  109. package/dist/modes/rpc/multi-session-host.js.map +1 -1
  110. package/dist/modes/rpc/rpc-types.d.ts +13 -0
  111. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  112. package/dist/modes/rpc/rpc-types.js.map +1 -1
  113. package/dist/modes/rpc/session-command-router.d.ts +10 -4
  114. package/dist/modes/rpc/session-command-router.d.ts.map +1 -1
  115. package/dist/modes/rpc/session-command-router.js +90 -18
  116. package/dist/modes/rpc/session-command-router.js.map +1 -1
  117. package/dist/modes/rpc/session-event-writer.d.ts +5 -3
  118. package/dist/modes/rpc/session-event-writer.d.ts.map +1 -1
  119. package/dist/modes/rpc/session-event-writer.js +21 -2
  120. package/dist/modes/rpc/session-event-writer.js.map +1 -1
  121. package/dist/modes/rpc/session-worker-client.d.ts +1 -0
  122. package/dist/modes/rpc/session-worker-client.d.ts.map +1 -1
  123. package/dist/modes/rpc/session-worker-client.js +3 -0
  124. package/dist/modes/rpc/session-worker-client.js.map +1 -1
  125. package/dist/modes/rpc/session-worker-protocol.d.ts +3 -1
  126. package/dist/modes/rpc/session-worker-protocol.d.ts.map +1 -1
  127. package/dist/modes/rpc/session-worker-protocol.js.map +1 -1
  128. package/dist/modes/rpc/session-worker.js +7 -1
  129. package/dist/modes/rpc/session-worker.js.map +1 -1
  130. package/docs/providers.md +9 -1
  131. package/docs/rpc.md +58 -8
  132. package/node_modules/@code-yeongyu/senpi-codemode/CHANGELOG.md +15 -0
  133. package/node_modules/@code-yeongyu/senpi-codemode/README.md +51 -13
  134. package/node_modules/@code-yeongyu/senpi-codemode/package.json +4 -4
  135. package/node_modules/@code-yeongyu/senpi-codemode/src/bridges/agent-bridge.ts +53 -9
  136. package/node_modules/@code-yeongyu/senpi-codemode/src/bridges/reserved-dispatch.ts +1 -0
  137. package/node_modules/@code-yeongyu/senpi-codemode/src/config/settings.ts +18 -0
  138. package/node_modules/@code-yeongyu/senpi-codemode/src/extension/eval-status.ts +9 -4
  139. package/node_modules/@code-yeongyu/senpi-codemode/src/index.ts +3 -0
  140. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/AGENTS.md +2 -2
  141. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/jl/prelude.jl +10 -0
  142. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/context-manager.ts +18 -6
  143. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/kernel-contract.ts +2 -6
  144. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/prelude.ts +1 -1
  145. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/run-queue.ts +17 -7
  146. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/worker-runtime.js +6 -1
  147. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/py/kernel-contract.ts +2 -5
  148. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/py/kernel.ts +37 -5
  149. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/py/prelude.py +11 -2
  150. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/rb/prelude.rb +6 -0
  151. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/shared/subprocess-contract.ts +2 -5
  152. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/shared/subprocess-kernel.ts +14 -4
  153. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/shared/subprocess-queue.ts +18 -5
  154. package/node_modules/@code-yeongyu/senpi-codemode/src/prompt/eval-prompt-template.ts +3 -2
  155. package/node_modules/@code-yeongyu/senpi-codemode/src/prompt/eval-prompt.ts +4 -1
  156. package/node_modules/@code-yeongyu/senpi-codemode/src/timeouts/idle-timeout.ts +9 -2
  157. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/AGENTS.md +2 -0
  158. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/cell-execution.ts +19 -2
  159. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/cell-runtime.ts +11 -3
  160. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/detached-cell-contract.ts +6 -1
  161. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/detached-cell-manager.ts +72 -20
  162. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/detached-cell-snapshot.ts +28 -4
  163. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/detached-cell-state.ts +5 -4
  164. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/detached-cell-status.ts +5 -2
  165. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/detached-eval-result.ts +76 -25
  166. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/eval-execution-event.ts +4 -0
  167. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/eval-kernel-reset-refused-error.ts +12 -0
  168. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/eval-request.ts +2 -1
  169. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/eval-tool-options.ts +3 -1
  170. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/eval-tool.ts +58 -37
  171. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/managed-cell.ts +15 -8
  172. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/render.ts +20 -6
  173. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/run-eval-cell.ts +89 -25
  174. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/terminal-snapshot-store.ts +4 -0
  175. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/types.ts +51 -10
  176. package/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
  177. package/node_modules/@earendil-works/pi-ai/README.md +1 -1
  178. package/node_modules/@earendil-works/pi-ai/dist/api/openai-codex-responses.js +14 -56
  179. package/node_modules/@earendil-works/pi-ai/dist/api/openai-codex-responses.js.map +1 -1
  180. package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.d.ts.map +1 -1
  181. package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.js +18 -27
  182. package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.js.map +1 -1
  183. package/node_modules/@earendil-works/pi-ai/dist/api/websocket-transport-failure.d.ts +40 -0
  184. package/node_modules/@earendil-works/pi-ai/dist/api/websocket-transport-failure.d.ts.map +1 -0
  185. package/node_modules/@earendil-works/pi-ai/dist/api/websocket-transport-failure.js +102 -0
  186. package/node_modules/@earendil-works/pi-ai/dist/api/websocket-transport-failure.js.map +1 -0
  187. package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/kimi-coding.d.ts +4 -3
  188. package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/kimi-coding.d.ts.map +1 -1
  189. package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/kimi-coding.js +28 -14
  190. package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/kimi-coding.js.map +1 -1
  191. package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/kimi-region.d.ts +44 -0
  192. package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/kimi-region.d.ts.map +1 -0
  193. package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/kimi-region.js +120 -0
  194. package/node_modules/@earendil-works/pi-ai/dist/auth/oauth/kimi-region.js.map +1 -0
  195. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/failover.d.ts +2 -2
  196. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/failover.d.ts.map +1 -1
  197. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/failover.js +2 -2
  198. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/failover.js.map +1 -1
  199. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/slots.d.ts +3 -0
  200. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/slots.d.ts.map +1 -1
  201. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/slots.js +21 -15
  202. package/node_modules/@earendil-works/pi-ai/dist/auth/pool/slots.js.map +1 -1
  203. package/node_modules/@earendil-works/pi-ai/dist/index.d.ts +1 -0
  204. package/node_modules/@earendil-works/pi-ai/dist/index.d.ts.map +1 -1
  205. package/node_modules/@earendil-works/pi-ai/dist/index.js +1 -0
  206. package/node_modules/@earendil-works/pi-ai/dist/index.js.map +1 -1
  207. package/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  208. package/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-ai-gateway.json +1 -1
  209. package/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-workers-ai.json +1 -1
  210. package/node_modules/@earendil-works/pi-ai/dist/providers/data/huggingface.json +1 -1
  211. package/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode-go.json +1 -1
  212. package/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  213. package/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  214. package/node_modules/@earendil-works/pi-ai/dist/providers/kimi-coding-auth.d.ts +9 -0
  215. package/node_modules/@earendil-works/pi-ai/dist/providers/kimi-coding-auth.d.ts.map +1 -0
  216. package/node_modules/@earendil-works/pi-ai/dist/providers/kimi-coding-auth.js +43 -0
  217. package/node_modules/@earendil-works/pi-ai/dist/providers/kimi-coding-auth.js.map +1 -0
  218. package/node_modules/@earendil-works/pi-ai/dist/providers/kimi-coding.d.ts.map +1 -1
  219. package/node_modules/@earendil-works/pi-ai/dist/providers/kimi-coding.js +3 -2
  220. package/node_modules/@earendil-works/pi-ai/dist/providers/kimi-coding.js.map +1 -1
  221. package/node_modules/@earendil-works/pi-ai/dist/utils/provider-failure-description.d.ts +19 -0
  222. package/node_modules/@earendil-works/pi-ai/dist/utils/provider-failure-description.d.ts.map +1 -0
  223. package/node_modules/@earendil-works/pi-ai/dist/utils/provider-failure-description.js +63 -0
  224. package/node_modules/@earendil-works/pi-ai/dist/utils/provider-failure-description.js.map +1 -0
  225. package/node_modules/@earendil-works/pi-ai/dist/utils/retry.d.ts +1 -0
  226. package/node_modules/@earendil-works/pi-ai/dist/utils/retry.d.ts.map +1 -1
  227. package/node_modules/@earendil-works/pi-ai/dist/utils/retry.js +1 -1
  228. package/node_modules/@earendil-works/pi-ai/dist/utils/retry.js.map +1 -1
  229. package/node_modules/@earendil-works/pi-ai/package.json +2 -2
  230. package/node_modules/@earendil-works/pi-pty/package.json +1 -1
  231. package/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  232. package/node_modules/@earendil-works/pi-tui/package.json +1 -1
  233. package/package.json +7 -7
  234. package/dist/bundle/chunks/chunk-5J5R5AMP.js +0 -8
  235. package/dist/bundle/chunks/chunk-I3F6VZZF.js +0 -2
  236. package/dist/bundle/chunks/host-lifecycle-DGZJTBDJ.js +0 -3
  237. package/dist/bundle/chunks/openai-codex-responses-L2PO2D6F.js +0 -10
  238. package/dist/bundle/chunks/openai-responses-YDUBVF4S.js +0 -2
  239. package/dist/bundle/chunks/rotation-stream-Y4YU6HV4.js +0 -2
@@ -1 +1 @@
1
- {"version":3,"file":"host-lifecycle.js","sourceRoot":"","sources":["../../../src/modes/rpc/host-lifecycle.ts"],"names":[],"mappings":";AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,OAAO,EAAqB,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC9D,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAC5E,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE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C,KAAc;IACvC,OAAO,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;AAClG,CAAC;AAED,SAAS,aAAa;IACrB,MAAM,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAC9B,IAAI,CAAC,KAAK;QAAE,OAAO,KAAK,CAAC;IACzB,IAAI,CAAC;QACJ,OAAO,aAAa,CAAC,OAAO,IAAI,CAAC,GAAG,CAAC,KAAK,YAAY,CAAC,KAAK,CAAC,CAAC;IAC/D,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,KAAK,CAAC;IACd,CAAC;AACF,CAAC;AAED,IAAI,CAAC,aAAa,IAAI,aAAa,EAAE,EAAE,CAAC;IACvC,MAAM,MAAM,GAAG,mBAAmB,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;IAC1D,IAAI,CAAC,MAAM,EAAE,CAAC;QACb,eAAe,CAAC,6DAA6D,CAAC,CAAC;QAC/E,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACjB,CAAC;IACD,KAAK,iBAAiB,CAAC,MAAM,CAAC,CAAC;AAChC,CAAC","sourcesContent":["#!/usr/bin/env node\n/**\n * Lifecycle supervisor for the shared RPC socket host started by ensureHost().\n *\n * Process tree:\n *\n * ensureHost() ──detached──▶ host-lifecycle.ts (this supervisor, owns the pidfile)\n * │ byte-proxies the public socket\n * ▼\n * cli-main --mode rpc --listen unix://<public>.internal\n *\n * The supervisor exists to enforce the host lifecycle policy without touching the\n * RPC host itself:\n *\n * - cold start: `transient` (default) means the host lives for the current login\n * session and idle-exits; `persistent` never idle-exits.\n * - idle exit: after a continuous window with zero attached client connections\n * and zero active agent turns, the supervisor tears the host down cleanly\n * (child SIGTERM first so the host flushes pending output and removes its own\n * socket, then pidfile/settings removal mirroring ensureHost's cleanupState).\n *\n * Observability without host changes: proxying the public socket yields the\n * exact connection count, and the supervisor keeps one always-on observer\n * connection to the internal socket. The multi-session host broadcasts every\n * session lifecycle/agent event to every connection, so the observer sees\n * `agent_start`/`agent_settled` for all sessions even when no client is\n * attached. If the observer connection is ever unhealthy, activity is reported\n * as unknown (non-idle), so a broken observer can only keep the host alive,\n * never kill it mid-turn.\n *\n * Lifetime binding: the host is spawned with an extra inherited pipe on fd 3\n * whose write end this supervisor holds and never writes to. The kernel closes\n * that end whenever the supervisor dies - including SIGKILL, an OOM kill, or a\n * crash, where no JS handler runs at all - so the host reads EOF and shuts down\n * cleanly, removing the private internal directory. `stopChild()` remains the\n * fast path for orderly shutdowns; the pipe is what makes an orphaned host\n * impossible. `SENPI_RPC_HOST_WATCH_PPID` is passed alongside as a belt-and-\n * braces fallback for platforms where the extra fd is not inherited.\n */\nimport { type ChildProcess, spawn } from \"node:child_process\";\nimport { randomUUID } from \"node:crypto\";\nimport { existsSync, readFileSync, realpathSync, writeSync } from \"node:fs\";\nimport { access, chmod, mkdir, readFile, rename, rm, unlink, writeFile } from \"node:fs/promises\";\nimport { createConnection, createServer, type Server, type Socket } from \"node:net\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, extname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { getAgentDir, isBunBinary, isBundledNode } from \"../../config.ts\";\nimport { processIsLive, readProcessStartTime } from \"../app-server/daemon/process.ts\";\nimport { createHostDaemonPaths, generationPaths, HOST_DAEMON_DIR_ENV } from \"./host-daemon-paths.ts\";\nimport { releaseGeneration } from \"./host-daemon-registration.ts\";\nimport { watchForSupersession } from \"./host-supersession.ts\";\nimport {\n\tHOST_CLEANUP_PATHS_ENV,\n\tHOST_PUBLIC_SOCKET_ENV,\n\tHOST_SCRATCH_DIR_ENV,\n\tHOST_WATCH_FD_ENV,\n\tHOST_WATCH_PPID_ENV,\n} from \"./host-watchdog.ts\";\nimport { attachJsonlLineReader, MAX_RPC_LINE_CHARACTERS } from \"./jsonl.ts\";\nimport { HOST_INSTANCE_ID_ENV } from \"./protocol-identity.ts\";\nimport {\n\tMAX_SOCKET_PATH_BYTES,\n\tPUBLIC_SOCKET_IDENTITY_FILE,\n\ttype SocketFileIdentity,\n\tshieldSocketDuringClose,\n\tstatSocketIdentity,\n\tunlinkOwnedSocket,\n\twriteSocketIdentityFile,\n} from \"./socket-ownership.ts\";\nimport {\n\tauthenticateSocket,\n\tcreateSocketSecret,\n\tensureSocketSecret,\n\tresolveSocketTransportAddress,\n\tSOCKET_SECRET_FILE_ENV,\n\tsendSocketHandshake,\n\tsocketSecretPath,\n} from \"./socket-transport.ts\";\n\nexport type HostColdStart = \"transient\" | \"persistent\";\n\n/** Environment override for the cold-start policy: `transient` or `persistent`. */\nexport const HOST_COLD_START_ENV = \"SENPI_RPC_HOST_COLD_START\";\n/** Environment override for the idle-exit window in milliseconds. */\nexport const HOST_IDLE_EXIT_MS_ENV = \"SENPI_RPC_HOST_IDLE_EXIT_MS\";\n/** Default idle-exit window: 15 minutes of continuous no-connection, no-turn idle. */\nexport const DEFAULT_HOST_IDLE_EXIT_MS = 15 * 60_000;\n\n/** The policy fields ensureHost() records in rpc-host-daemon/settings.json. */\nexport interface HostLifecyclePolicyInput {\n\treadonly coldStart?: HostColdStart;\n\treadonly idleExitMs?: number;\n}\n\nexport interface HostLifecyclePolicy {\n\treadonly coldStart: HostColdStart;\n\treadonly idleExitMs: number;\n}\n\nconst CHILD_STOP_TIMEOUT_MS = 5_000;\n/** Win32 named-pipe shutdown can leave supervisor handles live after close starts. */\nconst WINDOWS_SUPERVISOR_SHUTDOWN_HARD_EXIT_MS = 2_000;\n\n/**\n * Child stdio slot carrying the supervisor-lifetime pipe. The supervisor holds\n * the write end open and never writes; the kernel closes it when the supervisor\n * dies for ANY reason (SIGKILL, OOM kill, crash), so the host sees EOF on this\n * fd and shuts itself down. Catchable-signal cleanup alone cannot do this.\n */\nconst CHILD_WATCH_FD = 3;\n\n/**\n * The internal hop must stay short enough for sun_path (104 bytes on macOS)\n * regardless of where the public socket lives, and private against other local\n * users, so it gets its own 0700 directory under the OS temp directory.\n *\n * On win32 the directory lives under the caller-supplied rpc-host-daemon\n * directory, which ensureHost() creates but a direct --internal-rpc-host-supervisor\n * launch does not, so the parent is created recursively.\n */\nexport async function createInternalSocketPath(\n\tbaseDir = tmpdir(),\n\tplatform: NodeJS.Platform = process.platform,\n): Promise<{ socket: string; dir?: string; secretPath?: string }> {\n\tif (platform === \"win32\") {\n\t\tconst dir = join(baseDir, `internal-${randomUUID()}`);\n\t\tawait mkdir(dir, { recursive: true, mode: 0o700 });\n\t\treturn {\n\t\t\tsocket: `\\\\\\\\.\\\\pipe\\\\senpi-rpc-internal-${randomUUID()}`,\n\t\t\tdir,\n\t\t\tsecretPath: join(dir, \"secret\"),\n\t\t};\n\t}\n\tconst dir = join(tmpdir(), `senpi-rpc-host-internal-${randomUUID().slice(0, 8)}`);\n\tawait mkdir(dir, { recursive: false, mode: 0o700 });\n\tawait writeFile(\n\t\tjoin(dir, \".owner\"),\n\t\tJSON.stringify({\n\t\t\tpid: process.pid,\n\t\t\tprocessStartTime: await readProcessStartTime(process.pid),\n\t\t\tcreatedAt: Date.now(),\n\t\t}),\n\t\t{ mode: 0o600 },\n\t);\n\treturn { socket: join(dir, \"host.sock\"), dir, secretPath: join(dir, \".secret\") };\n}\n\nexport function parseColdStart(value: string | undefined): HostColdStart | undefined {\n\treturn value === \"transient\" || value === \"persistent\" ? value : undefined;\n}\n\nexport function parseIdleExitMs(value: string | undefined): number | undefined {\n\tif (value === undefined || !/^\\d+$/.test(value.trim())) return undefined;\n\tconst parsed = Number(value.trim());\n\treturn Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;\n}\n\n/**\n * Resolves the effective host policy. Precedence: environment overrides beat\n * settings.json, which beats the documented defaults (transient, 15 minutes).\n * Invalid values at either source fall through to the next source.\n */\nexport function resolveHostPolicy(\n\tsettings: unknown,\n\tenv: Readonly<Record<string, string | undefined>>,\n): HostLifecyclePolicy {\n\tconst record = isRecord(settings) ? settings : {};\n\tconst coldStart =\n\t\tparseColdStart(env[HOST_COLD_START_ENV]) ?? parseColdStart(asOptionalString(record.coldStart)) ?? \"transient\";\n\tconst idleExitMs =\n\t\tparseIdleExitMs(env[HOST_IDLE_EXIT_MS_ENV]) ??\n\t\tparseIdleExitMs(asOptionalString(record.idleExitMs)) ??\n\t\tDEFAULT_HOST_IDLE_EXIT_MS;\n\treturn { coldStart, idleExitMs };\n}\n\nexport interface HostActivity {\n\treadonly connections: number;\n\treadonly activeTurns: number;\n}\n\n/**\n * How the supervisor reads its child's exit. The RPC host exits 0 only through\n * its own clean shutdown path - including its idle/empty-host policy - so that\n * is an intentional stop, not a crash: the supervisor mirrors its own idle exit\n * instead of reporting failure. Any non-zero code or signal stays a crash.\n */\nexport function classifyChildExit(\n\tcode: number | null,\n\tsignal: NodeJS.Signals | null,\n): { reason: string; exitCode: number } {\n\tif (code === 0 && signal === null) return { reason: \"rpc host exited on its own idle policy\", exitCode: 0 };\n\treturn { reason: `rpc host process exited unexpectedly (${code ?? signal})`, exitCode: 1 };\n}\n\nexport type IdleExitDecision = \"active\" | \"idle\" | \"exit\";\n\n/**\n * Pure idle-window decision core. `update()` must be called with the CURRENT\n * activity state; the window only counts continuously idle time and any\n * activity resets it, so a busy host can never cross the threshold.\n */\nexport class IdleExitDecider {\n\tprivate idleSince: number | undefined;\n\tprivate readonly now: () => number;\n\treadonly idleExitMs: number;\n\n\tconstructor(idleExitMs: number, now: () => number = Date.now) {\n\t\tthis.idleExitMs = idleExitMs;\n\t\tthis.now = now;\n\t}\n\n\tupdate(activity: HostActivity): IdleExitDecision {\n\t\t// Any attachment or active turn both holds the host open and resets the\n\t\t// window, so only CONTINUOUS idle can ever cross the threshold.\n\t\tif (activity.connections > 0 || activity.activeTurns > 0) {\n\t\t\tthis.idleSince = undefined;\n\t\t\treturn \"active\";\n\t\t}\n\t\tif (this.idleExitMs === Number.POSITIVE_INFINITY) return \"idle\";\n\t\tif (this.idleSince === undefined) {\n\t\t\tthis.idleSince = this.now();\n\t\t\treturn \"idle\";\n\t\t}\n\t\treturn this.now() - this.idleSince >= this.idleExitMs ? \"exit\" : \"idle\";\n\t}\n}\n\nexport interface SupervisorLaunch {\n\treadonly socket: string;\n\treadonly hostArgs: readonly string[];\n\t/** Optional runtime command used by rebranded/bundled callers. */\n\treadonly childCommand?: string;\n\treadonly childArgs?: readonly string[];\n\t/** Explicit ownership directory for callers whose environment is not yet branded. */\n\treadonly agentDir?: string;\n\t/**\n\t * Where this supervisor BINDS, when it is a successor generation: `<socket>.next-<gen>`.\n\t * It renames that entry over `socket` once its host answers - and never binds the live\n\t * public path, which belongs to the generation currently serving it.\n\t */\n\treadonly bindSocket?: string;\n\t/**\n\t * The public socket entry this generation is allowed to replace (`<dev>:<ino>`). The rename\n\t * happens only while the path still refers to it: a socket that changed underneath belongs to\n\t * somebody else now, and replacing it would unlink an endpoint this process cannot prove it owns.\n\t */\n\treadonly replaceIdentity?: SocketFileIdentity;\n}\n\n/** Hidden internal launch route: wire-invisible, never advertised by the public CLI surface. */\nexport const INTERNAL_SUPERVISOR_FLAG = \"--internal-rpc-host-supervisor\";\n\n/**\n * Engine-global flags a rebranded wrapper may legitimately prepend when it\n * re-dispatches this binary. `packages/omo-native` injects `--extension <dir>`\n * for every non-early command, which pushed the sentinel off argv[0].\n */\nconst INJECTABLE_PREFIX_FLAGS = new Set([\"--extension\"]);\n\n/**\n * Returns the internal supervisor payload when argv selects that route.\n *\n * The route dispatches when the sentinel is argv[0] OR is preceded only by\n * known injectable prefix flags and their values - the one perturbation\n * wrappers legitimately perform. Everything else disqualifies it: a positional\n * operand, `--`, or an unknown flag before the sentinel all return undefined,\n * so a user-supplied value that happens to equal the sentinel can never reach\n * the supervisor.\n *\n * The skipped prefix is deliberately NOT forwarded to the host: a wrapper\n * re-injects its own prefix on every re-entry, so the host child receives it\n * from the wrapper rather than twice from here.\n */\nexport function findInternalSupervisorArgs(argv: readonly string[]): readonly string[] | undefined {\n\tfor (let index = 0; index < argv.length; index++) {\n\t\tconst arg = argv[index];\n\t\tif (arg === INTERNAL_SUPERVISOR_FLAG) return argv.slice(index + 1);\n\t\t// A prefix flag only counts when its value is actually present.\n\t\tif (!INJECTABLE_PREFIX_FLAGS.has(arg) || index + 1 >= argv.length) return undefined;\n\t\tindex++;\n\t}\n\treturn undefined;\n}\n\n/** `--socket <path>` selects the public socket; every other argument is forwarded to the host CLI. */\nexport function parseSupervisorArgs(argv: readonly string[]): SupervisorLaunch | undefined {\n\tconst hostArgs: string[] = [];\n\tlet socket: string | undefined;\n\tlet childCommand: string | undefined;\n\tlet childArgs: readonly string[] | undefined;\n\tlet agentDir: string | undefined;\n\tlet bindSocket: string | undefined;\n\tlet replaceIdentity: SocketFileIdentity | undefined;\n\tfor (let index = 0; index < argv.length; index++) {\n\t\tconst arg = argv[index];\n\t\tif (arg === \"--socket\" && index + 1 < argv.length) {\n\t\t\tsocket = argv[++index];\n\t\t\tcontinue;\n\t\t}\n\t\tif (arg === \"--child-command\" && index + 1 < argv.length) {\n\t\t\tchildCommand = argv[++index];\n\t\t\tcontinue;\n\t\t}\n\t\tif (arg === \"--child-args\" && index + 1 < argv.length) {\n\t\t\ttry {\n\t\t\t\tconst parsed: unknown = JSON.parse(argv[++index]);\n\t\t\t\tif (Array.isArray(parsed) && parsed.every((value) => typeof value === \"string\")) childArgs = parsed;\n\t\t\t} catch {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (arg === \"--agent-dir\" && index + 1 < argv.length) {\n\t\t\tagentDir = argv[++index];\n\t\t\tcontinue;\n\t\t}\n\t\tif (arg === \"--bind\" && index + 1 < argv.length) {\n\t\t\tbindSocket = argv[++index];\n\t\t\tcontinue;\n\t\t}\n\t\tif (arg === \"--replace\" && index + 1 < argv.length) {\n\t\t\treplaceIdentity = parseSocketIdentity(argv[++index]);\n\t\t\tcontinue;\n\t\t}\n\t\thostArgs.push(arg);\n\t}\n\treturn socket === undefined\n\t\t? undefined\n\t\t: { socket, hostArgs, childCommand, childArgs, agentDir, bindSocket, replaceIdentity };\n}\n\n/** `<dev>:<ino>` as the ensure captured it; anything else is no identity at all, never a guess. */\nfunction parseSocketIdentity(value: string): SocketFileIdentity | undefined {\n\tconst match = /^(\\d+):(\\d+)$/.exec(value);\n\treturn match ? { dev: Number(match[1]), ino: Number(match[2]) } : undefined;\n}\n\n/** Resolves the committed CLI entry this supervisor wraps (source tree or built dist). */\nexport function resolveCliMainPath(): string {\n\tconst modulePath = fileURLToPath(import.meta.url);\n\tconst extension = modulePath.endsWith(\".ts\") ? \".ts\" : \".js\";\n\tconst unbundled = resolve(dirname(modulePath), \"..\", \"..\", `cli-main${extension}`);\n\tif (existsSync(unbundled)) return unbundled;\n\t// Bundled, \"..\" twice reaches the PACKAGE ROOT rather than dist/, naming a cli-main that\n\t// was never emitted. Take the entry from the package's own declared bin instead of\n\t// counting directories: it is the one statement of where the CLI lives that holds in\n\t// every layout. Falls back to the old path when nothing is declared, so a caller that\n\t// was working keeps working.\n\treturn resolveDeclaredCliEntry(modulePath) ?? unbundled;\n}\n\n/** The CLI entry declared by the nearest enclosing package.json, when it exists on disk. */\nfunction resolveDeclaredCliEntry(modulePath: string): string | undefined {\n\tlet dir = dirname(modulePath);\n\tfor (let depth = 0; depth < 8; depth += 1) {\n\t\tconst manifestPath = resolve(dir, \"package.json\");\n\t\tif (existsSync(manifestPath)) {\n\t\t\ttry {\n\t\t\t\tconst manifest = JSON.parse(readFileSync(manifestPath, \"utf8\")) as {\n\t\t\t\t\tbin?: Record<string, string> | string;\n\t\t\t\t};\n\t\t\t\tconst declared = manifest.bin;\n\t\t\t\tconst candidates = typeof declared === \"string\" ? [declared] : Object.values(declared ?? {});\n\t\t\t\tfor (const candidate of candidates) {\n\t\t\t\t\tconst entry = resolve(dir, candidate);\n\t\t\t\t\tif (existsSync(entry)) return entry;\n\t\t\t\t}\n\t\t\t} catch {}\n\t\t\treturn undefined;\n\t\t}\n\t\tconst parent = dirname(dir);\n\t\tif (parent === dir) return undefined;\n\t\tdir = parent;\n\t}\n\treturn undefined;\n}\n\n/**\n * Resolves the host child spawn. Explicit child commands (desktop launchers)\n * are forwarded untouched. The default re-enters the committed CLI entry\n * through the runtime, except in compiled standalone binaries, which always\n * boot their embedded entrypoint and would parse a script path as CLI\n * arguments - there the executable itself is the CLI, so the mode flags are\n * passed directly. Exported for tests.\n */\nexport function resolveHostChildLaunch(\n\tlaunch: SupervisorLaunch,\n\tinternalSocket: string,\n\tcompiled: boolean = isBunBinary,\n): { command: string; args: string[] } {\n\tif (launch.childCommand) {\n\t\treturn {\n\t\t\tcommand: launch.childCommand,\n\t\t\targs: [...(launch.childArgs ?? []), \"--listen\", `unix://${internalSocket}`],\n\t\t};\n\t}\n\treturn {\n\t\tcommand: process.execPath,\n\t\targs: [\n\t\t\t...(compiled ? [] : [...process.execArgv, resolveCliMainPath()]),\n\t\t\t\"--mode\",\n\t\t\t\"rpc\",\n\t\t\t\"--multi-session\",\n\t\t\t\"--listen\",\n\t\t\t`unix://${internalSocket}`,\n\t\t\t...launch.hostArgs,\n\t\t],\n\t};\n}\n\n/** Mirrors cross-spawn: survives cmd.exe parsing and `CommandLineToArgvW`. */\nfunction quoteWindowsShellArg(value: string): string {\n\tconst escaped = value\n\t\t.replace(/(\\\\*)\"/g, '$1$1\\\\\"')\n\t\t.replace(/(\\\\*)$/, \"$1$1\")\n\t\t.replace(/([()%!^\"<>&|;,])/g, \"^$1\");\n\treturn `\"${escaped}\"`;\n}\n\n/**\n * Windows refuses to spawn a `.cmd`/`.bat` without a shell, and Node's\n * `shell: true` concatenates argv without escaping it. Escape each original\n * value before adding the surrounding quotes so `.cmd`/`.bat` launchers survive\n * cmd.exe parsing without double-escaping.\n * Exported for tests.\n */\nexport function spawnableChildLaunch(\n\tlaunch: { command: string; args: string[] },\n\tplatform: NodeJS.Platform = process.platform,\n): { command: string; args: string[]; shell: boolean } {\n\tconst extension = extname(launch.command).toLowerCase();\n\tif (platform !== \"win32\" || (extension !== \".cmd\" && extension !== \".bat\")) {\n\t\treturn { ...launch, shell: false };\n\t}\n\treturn {\n\t\tcommand: quoteWindowsShellArg(launch.command),\n\t\targs: launch.args.map(quoteWindowsShellArg),\n\t\tshell: true,\n\t};\n}\n\nexport async function runHostSupervisor(launch: SupervisorLaunch): Promise<void> {\n\tconst paths = createHostDaemonPaths({ socket: launch.socket, agentDir: launch.agentDir ?? getAgentDir() });\n\t// Which generation this supervisor is: the ensure that spawned it says so, and a DIRECT launch\n\t// (the hidden supervisor route, with no ensure behind it) names itself so its child agrees.\n\tconst told = process.env[HOST_INSTANCE_ID_ENV];\n\tconst instanceId = told !== undefined && told.trim() !== \"\" ? told : randomUUID();\n\tconst generation = generationPaths(paths, instanceId);\n\tconst policy = resolveHostPolicy(await readSettingsFile(paths.settingsFile), process.env);\n\tconst publicSocket = launch.socket;\n\t// A successor generation binds its own name and adopts the public one by rename; an ordinary\n\t// start binds the public name directly. Everything downstream - the child's environment, the\n\t// ownership token, the teardown - is expressed in terms of the PUBLIC path either way.\n\tconst bindSocket = launch.bindSocket ?? publicSocket;\n\tconst successor = launch.bindSocket !== undefined;\n\t// Direct-launch contract: the supervisor owns the public secret. ensureHost()\n\t// writes it before spawning, but the hidden --internal-rpc-host-supervisor route\n\t// has no such caller, so a fresh profile would otherwise die reading it (#1370).\n\t// It is provisioned BEFORE the internal hop and the child so a provisioning\n\t// failure leaves no scratch directory and no host process behind.\n\tconst publicSecret = process.platform === \"win32\" ? await ensurePublicSocketSecret(publicSocket) : undefined;\n\tconst internal = await createInternalSocketPath(paths.dir);\n\tconst internalSocket = internal.socket;\n\tconst internalSecretPath = internal.secretPath ?? socketSecretPath(internalSocket);\n\tconst internalSecret = process.platform === \"win32\" ? await createSocketSecret(internalSecretPath) : undefined;\n\tconst clientSockets = new Set<Socket>();\n\tconst busySessions = new Map<string, number>();\n\tlet observerHealthy = false;\n\tlet observerReconnectTimer: ReturnType<typeof setTimeout> | undefined;\n\tlet childExitWatchTimer: ReturnType<typeof setInterval> | undefined;\n\tlet stopSupersessionWatch: (() => void) | undefined;\n\tlet shuttingDown = false;\n\tlet draining = false;\n\tlet shutdownPromise: Promise<never> | undefined;\n\n\tconst childLaunch = spawnableChildLaunch(resolveHostChildLaunch(launch, internalSocket));\n\tconst child = spawn(childLaunch.command, childLaunch.args, {\n\t\tenv: {\n\t\t\t...process.env,\n\t\t\t...(launch.agentDir ? { SENPI_CODING_AGENT_DIR: launch.agentDir } : {}),\n\t\t\t// The child binds a PRIVATE socket, so it cannot derive this endpoint's daemon directory\n\t\t\t// from what it listens on: it is told, and it claims its session paths there.\n\t\t\t[HOST_DAEMON_DIR_ENV]: paths.dir,\n\t\t\t[HOST_INSTANCE_ID_ENV]: instanceId,\n\t\t\t[HOST_WATCH_FD_ENV]: String(CHILD_WATCH_FD),\n\t\t\t[HOST_WATCH_PPID_ENV]: String(process.pid),\n\t\t\t...(internal.dir ? { [HOST_SCRATCH_DIR_ENV]: internal.dir } : {}),\n\t\t\t...(internalSecret ? { [SOCKET_SECRET_FILE_ENV]: internalSecretPath } : {}),\n\t\t\t[HOST_CLEANUP_PATHS_ENV]: [\n\t\t\t\t// A successor writes no registration of its own until the ensure that spawned it does,\n\t\t\t\t// and the files under these paths still describe the generation being replaced.\n\t\t\t\t...(successor ? [] : [paths.pointerFile, generation.pidFile, paths.settingsFile]),\n\t\t\t\t// POSIX public sockets are removed ownership-checked by the host child\n\t\t\t\t// (token: the scratch-directory sidecar plus HOST_PUBLIC_SOCKET_ENV),\n\t\t\t\t// never by path from a crash-path cleanup: a blind removal here would\n\t\t\t\t// unlink a newer host's freshly published entry after a takeover.\n\t\t\t\t// Windows named pipes have no filesystem entry to own, so they stay\n\t\t\t\t// listed for the crash-path cleanup.\n\t\t\t\t...(process.platform === \"win32\" ? [publicSocket] : []),\n\t\t\t].join(\"\\n\"),\n\t\t\t...(process.platform === \"win32\" ? {} : { [HOST_PUBLIC_SOCKET_ENV]: publicSocket }),\n\t\t},\n\t\t// Slot 3 is the lifetime pipe: \"pipe\" gives the child a read end it can\n\t\t// wait on and keeps the write end owned by this process alone.\n\t\tshell: childLaunch.shell,\n\t\tstdio: [\"ignore\", \"ignore\", \"inherit\", \"pipe\"],\n\t\t// The supervisor is spawned detached, so on win32 it owns no console. A\n\t\t// console-subsystem child started from it would allocate a fresh one,\n\t\t// which Windows Terminal renders as an empty window that takes focus.\n\t\t// CREATE_NO_WINDOW gives the child a console with no window instead.\n\t\twindowsHide: true,\n\t});\n\t// Nothing is ever written; the pipe exists purely so its EOF is a reliable\n\t// death notification. Errors on it must not crash the supervisor.\n\tchild.stdio[CHILD_WATCH_FD]?.on(\"error\", () => {});\n\tchild.once(\"exit\", (code, signal) => {\n\t\tif (shuttingDown) return;\n\t\tconst { reason, exitCode } = classifyChildExit(code, signal);\n\t\tvoid shutdown(reason, exitCode);\n\t});\n\n\tconst server = createServer((client) => {\n\t\tconst accept = (): void => {\n\t\t\t// A draining supervisor serves what it already proxies and accepts nothing new. After a\n\t\t\t// handoff the public path resolves to the successor anyway; this covers the connection\n\t\t\t// that raced the rename, and a drain-stop with no successor at all.\n\t\t\tif (shuttingDown || draining) {\n\t\t\t\tclient.destroy();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst internal = createConnection(\n\t\t\t\tresolveSocketTransportAddress(internalSocket, process.platform, internalSecret),\n\t\t\t);\n\t\t\tif (internalSecret) sendSocketHandshake(internal, internalSecret);\n\t\t\tclientSockets.add(client);\n\t\t\t// A readiness exchange can begin and end between ticks. Record the\n\t\t\t// attachment now, before a later tick can reuse the preceding idle window.\n\t\t\tdecider.update(currentActivity());\n\t\t\tconst detach = (): void => {\n\t\t\t\tclientSockets.delete(client);\n\t\t\t\tdecider.update(currentActivity());\n\t\t\t\tinternal.destroy();\n\t\t\t\tclient.destroy();\n\t\t\t};\n\t\t\tclient.pipe(internal);\n\t\t\tinternal.pipe(client);\n\t\t\tclient.once(\"close\", detach);\n\t\t\tclient.once(\"error\", detach);\n\t\t\tinternal.once(\"close\", detach);\n\t\t\tinternal.once(\"error\", detach);\n\t\t};\n\t\tif (publicSecret) authenticateSocket(client, publicSecret, accept);\n\t\telse accept();\n\t});\n\tserver.once(\"error\", (cause) => {\n\t\tif (!shuttingDown) void shutdown(`public socket listener failed: ${errorMessage(cause)}`, 1);\n\t});\n\n\tconst decider = new IdleExitDecider(\n\t\tpolicy.coldStart === \"persistent\" ? Number.POSITIVE_INFINITY : policy.idleExitMs,\n\t);\n\tconst tickIntervalMs = Math.max(20, Math.min(1_000, policy.idleExitMs / 4));\n\tconst ticker = setInterval(() => {\n\t\tif (decider.update(currentActivity()) === \"exit\") void shutdown(\"idle\", 0);\n\t}, tickIntervalMs);\n\n\tfunction currentActivity(): HostActivity {\n\t\treturn {\n\t\t\tconnections: clientSockets.size,\n\t\t\tactiveTurns: observerHealthy ? countBusySessions() : 1,\n\t\t};\n\t}\n\n\tfunction countBusySessions(): number {\n\t\tlet busy = 0;\n\t\tfor (const count of busySessions.values()) if (count > 0) busy++;\n\t\treturn busy;\n\t}\n\n\tfunction observeHostEvent(line: string): void {\n\t\tlet event: unknown;\n\t\ttry {\n\t\t\tevent = JSON.parse(line);\n\t\t} catch {\n\t\t\treturn;\n\t\t}\n\t\tif (typeof event !== \"object\" || event === null) return;\n\t\tconst { type, sessionId } = event as { type?: unknown; sessionId?: unknown };\n\t\tif (typeof sessionId !== \"string\") return;\n\t\tif (type === \"agent_start\") busySessions.set(sessionId, (busySessions.get(sessionId) ?? 0) + 1);\n\t\telse if (type === \"agent_settled\")\n\t\t\tbusySessions.set(sessionId, Math.max(0, (busySessions.get(sessionId) ?? 1) - 1));\n\t\telse return;\n\t\tdecider.update(currentActivity());\n\t}\n\n\tasync function shutdown(reason: string, exitCode: number): Promise<never> {\n\t\t// Single-flight: concurrent triggers (listener error, child exit, signals)\n\t\t// must not process.exit mid-cleanup. Late callers park on this promise while\n\t\t// the first shutdown finishes tearing down and exits.\n\t\tshutdownPromise ??= performShutdown(reason, exitCode);\n\t\treturn shutdownPromise;\n\t}\n\n\tasync function performShutdown(reason: string, exitCode: number): Promise<never> {\n\t\tif (shuttingDown) process.exit(exitCode);\n\t\tshuttingDown = true;\n\t\tclearInterval(ticker);\n\t\tif (childExitWatchTimer) clearInterval(childExitWatchTimer);\n\t\tstopSupersessionWatch?.();\n\t\tconst hardExit =\n\t\t\tprocess.platform === \"win32\"\n\t\t\t\t? setTimeout(() => process.exit(exitCode), WINDOWS_SUPERVISOR_SHUTDOWN_HARD_EXIT_MS)\n\t\t\t\t: undefined;\n\t\ttry {\n\t\t\twriteStderrLine(`senpi rpc host supervisor: ${reason} shutdown`);\n\t\t\tfor (const client of clientSockets) client.destroy();\n\t\t\t// libuv unlinks the bound NAME when the listening handle closes - which\n\t\t\t// would delete a newer host's entry renamed over this path. Shield the\n\t\t\t// current entry for the close, then let the ownership check decide. A drained\n\t\t\t// supervisor already closed that handle when it stopped accepting.\n\t\t\tif (!draining) await shieldSocketDuringClose(publicSocket, () => closeServer(server));\n\t\t\t// Unlink the private directory BEFORE the child stop, which can take seconds:\n\t\t\t// an external SIGKILL landing during that wait (ensureHost escalates while\n\t\t\t// replacing a host) would otherwise leave the directory behind. The child\n\t\t\t// keeps serving through its already-open socket fd until it exits, and its\n\t\t\t// own watchdog cleanup makes the removal idempotent.\n\t\t\tif (internal.dir) await rm(internal.dir, { recursive: true, force: true });\n\t\t\tawait stopChild(child);\n\t\t\tobserver?.destroy();\n\t\t\tif (publicSocketOwned && process.platform !== \"win32\") {\n\t\t\t\t// Ownership-checked: after a takeover, a newer host may have published\n\t\t\t\t// a fresh entry at this path; only the entry THIS supervisor bound is\n\t\t\t\t// removed. (The host child applies the same rule to its crash path.)\n\t\t\t\tawait unlinkOwnedSocket(publicSocket, publicSocketIdentity, supervisorLog);\n\t\t\t}\n\t\t\t// The registration describes a LIVE host only; the stderr log stays for diagnostics.\n\t\t\t// After a handoff the pointer describes the SUCCESSOR, so this drops only the generation\n\t\t\t// directory of the process that is leaving, and the pointer only while it still names it.\n\t\t\tawait releaseGeneration(paths, { instanceId, pid: process.pid });\n\t\t} finally {\n\t\t\tif (hardExit) clearTimeout(hardExit);\n\t\t\t// Explicitly terminate after every supervisor shutdown trigger. Windows\n\t\t\t// named-pipe handles can outlive their JavaScript wrappers, so cleanup\n\t\t\t// failure must never leave the supervisor resident or the host orphaned.\n\t\t\tprocess.exit(exitCode);\n\t\t}\n\t}\n\n\tlet observer: Socket | undefined;\n\tlet publicSocketOwned = false;\n\tlet publicSocketIdentity: SocketFileIdentity | undefined;\n\tfunction supervisorLog(message: string): void {\n\t\twriteStderrLine(`senpi rpc host supervisor: ${message}`);\n\t}\n\t// Registered before the startup handshake, not after it: the private internal\n\t// directory already exists at this point, so a SIGTERM arriving during host\n\t// startup must run the same cleanup instead of Node's default kill, which\n\t// would leave that directory behind.\n\t/**\n\t * Hand this generation's work to the next one: stop accepting, keep every connection already\n\t * proxied, and tell the host child to park its retained sessions as their turns settle. The\n\t * child's exit is what ends this supervisor, so the drain never cuts a turn short.\n\t */\n\tfunction drainForHandoff(): void {\n\t\tif (draining || shuttingDown) return;\n\t\tdraining = true;\n\t\tsupervisorLog(\"draining into the next generation\");\n\t\t// The listening handle is deliberately NOT closed: libuv unlinks a pipe's bound NAME when it\n\t\t// closes, and after a handoff that name is the successor's entry. Nothing can reach this\n\t\t// listener by path any more (the rename moved the name), and the accept guard above turns\n\t\t// away whatever raced it, so leaving the handle open until exit costs nothing and keeps the\n\t\t// public path continuously answerable - no window where a client finds no socket at all.\n\t\tif (child.pid !== undefined && child.exitCode === null && child.signalCode === null) {\n\t\t\ttry {\n\t\t\t\tprocess.kill(child.pid, \"SIGUSR1\");\n\t\t\t} catch (cause) {\n\t\t\t\tsupervisorLog(`could not ask the host to drain: ${errorMessage(cause)}`);\n\t\t\t}\n\t\t}\n\t}\n\tregisterSupervisorSignals(shutdown, drainForHandoff);\n\ttry {\n\t\tawait waitForListener(internalSocket, 30_000, internalSecret);\n\t\tawait connectObserver();\n\t\tawait prepareSocketPath(bindSocket);\n\t\tawait listen(server, bindSocket, publicSecret);\n\t\tpublicSocketOwned = true;\n\t\tif (successor) await adoptPublicSocket(bindSocket, publicSocket, launch.replaceIdentity);\n\t\tpublicSocketIdentity = await statSocketIdentity(publicSocket);\n\t\t// Publish the ownership token inside this supervisor's private scratch\n\t\t// directory (which no replacement supervisor writes): the host child's\n\t\t// crash-path cleanup compares the public path against THIS entry only.\n\t\tif (publicSocketIdentity && internal.dir) {\n\t\t\tawait writeSocketIdentityFile(join(internal.dir, PUBLIC_SOCKET_IDENTITY_FILE), publicSocketIdentity);\n\t\t}\n\t\t// Losing the public entry IS a drain request: nothing can reach this supervisor by path any\n\t\t// more, and the handoff that replaced it may never have signalled (#1893).\n\t\tstopSupersessionWatch = watchForSupersession(\n\t\t\t{ path: publicSocket, identity: publicSocketIdentity, settled: () => shuttingDown || draining },\n\t\t\t() => {\n\t\t\t\tsupervisorLog(\"another generation owns the public socket; draining this one\");\n\t\t\t\tdrainForHandoff();\n\t\t\t},\n\t\t);\n\t} catch (cause) {\n\t\tawait shutdown(`startup failed: ${errorMessage(cause)}`, 1);\n\t}\n\tasync function connectObserver(): Promise<void> {\n\t\tconst secret = internalSecret;\n\t\tconst next = createConnection(resolveSocketTransportAddress(internalSocket, process.platform, secret));\n\t\tif (secret) sendSocketHandshake(next, secret);\n\t\tawait waitForConnect(next, 5_000);\n\t\tobserver = next;\n\t\tobserverHealthy = true;\n\t\tattachJsonlLineReader(next, observeHostEvent, { maxLineLength: MAX_RPC_LINE_CHARACTERS });\n\t\tconst lost = (): void => {\n\t\t\tif (observer !== next || shuttingDown) return;\n\t\t\tobserverHealthy = false;\n\t\t\tobserver = undefined;\n\t\t\tif (observerReconnectTimer === undefined) {\n\t\t\t\tobserverReconnectTimer = setTimeout(() => {\n\t\t\t\t\tobserverReconnectTimer = undefined;\n\t\t\t\t\tvoid connectObserver().catch(() => lost());\n\t\t\t\t}, 250);\n\t\t\t\tobserverReconnectTimer.unref?.();\n\t\t\t}\n\t\t};\n\t\tnext.once(\"close\", lost);\n\t\tnext.once(\"error\", lost);\n\t}\n\n\tif (process.platform === \"win32\" && child.pid !== undefined) {\n\t\t// This baseline read sits outside the startup try/catch, and readProcessStartTime\n\t\t// THROWS when the 1s CIM probe fails (execFile's timeout SIGTERMs the PowerShell\n\t\t// child). With no unhandledRejection handler the supervisor died right here on a\n\t\t// loaded runner: it never reached the \"host ready\" line, and the internal host it\n\t\t// owned vanished with it, surfacing downstream as `connect ENOENT` on the pipe and\n\t\t// as `reported dead`. A failed baseline read is UNKNOWN, so the watchdog simply\n\t\t// starts without one and relies on its own comparisons.\n\t\tconst childStartTime = await readProcessStartTime(child.pid, process.platform, 1_000).catch(() => undefined);\n\t\tlet missingIdentityChecks = 0;\n\t\tlet checkingChildIdentity = false;\n\t\tconst checkChildIdentity = (): void => {\n\t\t\tif (shuttingDown || checkingChildIdentity || child.exitCode !== null || child.signalCode !== null) return;\n\t\t\tcheckingChildIdentity = true;\n\t\t\tvoid readProcessStartTime(child.pid!, process.platform, 1_000)\n\t\t\t\t.then((currentStartTime) => {\n\t\t\t\t\t// An absent identity is only believed once kill(pid, 0) agrees the child is\n\t\t\t\t\t// gone. This probe is a 1s PowerShell CIM spawn polled every 500ms, so a\n\t\t\t\t\t// loaded runner produced two consecutive timeouts and this watchdog shut\n\t\t\t\t\t// down a perfectly healthy host (`does not exit while a turn is active`).\n\t\t\t\t\t// A timed-out probe means UNKNOWN, never EXITED.\n\t\t\t\t\tif (currentStartTime === undefined && !processIsLive(child.pid!)) missingIdentityChecks++;\n\t\t\t\t\telse if (currentStartTime !== undefined) missingIdentityChecks = 0;\n\t\t\t\t\tconst identityChanged =\n\t\t\t\t\t\tchildStartTime !== undefined && currentStartTime !== undefined && currentStartTime !== childStartTime;\n\t\t\t\t\tif (identityChanged || missingIdentityChecks >= 2) {\n\t\t\t\t\t\tvoid shutdown(\"rpc host child exit observed by identity watchdog\", 0);\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\t.catch(() => {})\n\t\t\t\t.finally(() => {\n\t\t\t\t\tcheckingChildIdentity = false;\n\t\t\t\t});\n\t\t};\n\t\tchildExitWatchTimer = setInterval(checkChildIdentity, 500);\n\t\tchildExitWatchTimer.unref?.();\n\t}\n\twriteStderrLine(\n\t\t`senpi rpc host ready on unix://${publicSocket} (coldStart=${policy.coldStart}, idleExitMs=${\n\t\t\tpolicy.coldStart === \"persistent\" ? \"never\" : String(policy.idleExitMs)\n\t\t})`,\n\t);\n\tawait new Promise<never>(() => {});\n}\n\n/**\n * External stop (ensureHost replacement, tests, QA) must clean up like idle exit; SIGUSR1 is the\n * gentler request - finish what you are doing and leave - that a generation handoff and\n * `stopHost({ drain: true })` both send. It exists on POSIX only, which is one reason win32 hosts\n * are attach-only: no signal there means anything but \"terminate\".\n */\nfunction registerSupervisorSignals(\n\tshutdown: (reason: string, exitCode: number) => Promise<never>,\n\tdrain: () => void,\n): void {\n\tfor (const signal of process.platform === \"win32\" ? ([\"SIGTERM\"] as const) : ([\"SIGTERM\", \"SIGHUP\"] as const)) {\n\t\tprocess.on(signal, () => {\n\t\t\tvoid shutdown(`signal:${signal}`, signal === \"SIGHUP\" ? 129 : 143);\n\t\t});\n\t}\n\tif (process.platform !== \"win32\") process.on(\"SIGUSR1\", drain);\n}\n\n/**\n * Takes the public name over with a rename, once - and only while - that name still refers to the\n * entry this handoff was decided against. A socket that changed underneath belongs to another\n * process now: replacing it would unlink an endpoint this generation cannot prove it owns, so the\n * successor aborts instead and leaves both the intruder's socket and its own bind entry alone.\n */\nasync function adoptPublicSocket(\n\tbindSocket: string,\n\tpublicSocket: string,\n\texpected: SocketFileIdentity | undefined,\n): Promise<void> {\n\tif (expected === undefined) throw new Error(`${publicSocket}: a generation launch must name the entry it replaces`);\n\tconst current = await statSocketIdentity(publicSocket);\n\tif (current === undefined || current.dev !== expected.dev || current.ino !== expected.ino) {\n\t\tthrow new Error(`${publicSocket}: owned by another socket entry now; refusing to replace it`);\n\t}\n\t// rename(2) is atomic for readers of the path: every connect either reaches the old entry or\n\t// this one, never nothing. The inode this supervisor bound simply answers to a second name.\n\tawait rename(bindSocket, publicSocket);\n}\n\n/**\n * Reuses an existing valid secret - including one ensureHost() just wrote - and\n * creates one (with its parent directories, mode 0600) when it is missing or\n * unusable. Reuse is required, not just an optimization: on win32 the pipe name\n * is derived from the socket path AND the secret, so rotating it here would\n * point this supervisor at a different endpoint than its caller published.\n * A failure names the bootstrap step and the path it could not provision.\n */\nasync function ensurePublicSocketSecret(publicSocket: string): Promise<Buffer> {\n\tconst secretPath = socketSecretPath(publicSocket);\n\ttry {\n\t\treturn await ensureSocketSecret(secretPath);\n\t} catch (cause) {\n\t\tthrow new Error(`senpi rpc host supervisor: cannot provision public socket secret ${secretPath}`, { cause });\n\t}\n}\n\nasync function readSettingsFile(settingsFile: string): Promise<unknown> {\n\ttry {\n\t\treturn JSON.parse(await readFile(settingsFile, \"utf8\"));\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nasync function stopChild(child: ChildProcess): Promise<void> {\n\tif (child.exitCode !== null || child.signalCode !== null) return;\n\ttry {\n\t\tchild.kill(\"SIGTERM\");\n\t} catch {\n\t\treturn;\n\t}\n\tif (await waitForChildExit(child, CHILD_STOP_TIMEOUT_MS)) return;\n\ttry {\n\t\tchild.kill(\"SIGKILL\");\n\t} catch {\n\t\treturn;\n\t}\n\tawait waitForChildExit(child, 2_000);\n}\n\nfunction waitForChildExit(child: ChildProcess, timeoutMs: number): Promise<boolean> {\n\tif (child.exitCode !== null || child.signalCode !== null) return Promise.resolve(true);\n\treturn new Promise((resolve) => {\n\t\tconst timer = setTimeout(() => {\n\t\t\tchild.off(\"exit\", onExit);\n\t\t\tresolve(false);\n\t\t}, timeoutMs);\n\t\tconst onExit = (): void => {\n\t\t\tclearTimeout(timer);\n\t\t\tresolve(true);\n\t\t};\n\t\tchild.once(\"exit\", onExit);\n\t});\n}\n\nasync function waitForListener(socketPath: string, timeoutMs: number, secret?: Uint8Array): Promise<void> {\n\tconst deadline = Date.now() + timeoutMs;\n\twhile (Date.now() <= deadline) {\n\t\tif (await canConnect(socketPath, secret)) return;\n\t\tawait delay(50);\n\t}\n\tthrow new Error(`${socketPath}: host did not start listening within ${timeoutMs}ms`);\n}\n\nfunction canConnect(socketPath: string, secret?: Uint8Array): Promise<boolean> {\n\treturn new Promise((resolve) => {\n\t\tconst socket = createConnection(resolveSocketTransportAddress(socketPath, process.platform, secret));\n\t\tif (secret) sendSocketHandshake(socket, secret);\n\t\tconst settle = (value: boolean): void => {\n\t\t\tsocket.destroy();\n\t\t\tresolve(value);\n\t\t};\n\t\tsocket.once(\"connect\", () => settle(true));\n\t\tsocket.once(\"error\", () => settle(false));\n\t});\n}\n\nfunction waitForConnect(socket: Socket, timeoutMs: number): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst timer = setTimeout(() => {\n\t\t\tcleanup();\n\t\t\treject(new Error(`observer connection to internal host timed out after ${timeoutMs}ms`));\n\t\t}, timeoutMs);\n\t\tconst onConnect = (): void => {\n\t\t\tcleanup();\n\t\t\tresolve();\n\t\t};\n\t\tconst onError = (cause: Error): void => {\n\t\t\tcleanup();\n\t\t\treject(cause);\n\t\t};\n\t\tconst cleanup = (): void => {\n\t\t\tclearTimeout(timer);\n\t\t\tsocket.off(\"connect\", onConnect);\n\t\t\tsocket.off(\"error\", onError);\n\t\t};\n\t\tsocket.once(\"connect\", onConnect);\n\t\tsocket.once(\"error\", onError);\n\t});\n}\n\nasync function prepareSocketPath(socketPath: string): Promise<void> {\n\tif (process.platform === \"win32\") return;\n\t// A path the kernel would truncate binds a DIFFERENT endpoint than the one every client was\n\t// told about, and the failure surfaces much later as \"the host does not answer\". Refuse here.\n\tif (Buffer.byteLength(socketPath) > MAX_SOCKET_PATH_BYTES) {\n\t\tthrow new Error(\n\t\t\t`${socketPath}: socket path is ${Buffer.byteLength(socketPath)} bytes, over the ${MAX_SOCKET_PATH_BYTES}-byte limit.`,\n\t\t);\n\t}\n\tawait mkdir(dirname(socketPath), { recursive: true, mode: 0o700 });\n\ttry {\n\t\tawait access(socketPath);\n\t} catch (cause) {\n\t\tif (isNodeErrorCode(cause, \"ENOENT\")) return;\n\t\tthrow cause;\n\t}\n\tif (await canConnect(socketPath)) throw new Error(`${socketPath}: address already in use by a live server.`);\n\tawait unlink(socketPath);\n}\n\nfunction listen(server: Server, socketPath: string, secret?: Uint8Array): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tserver.once(\"error\", reject);\n\t\tserver.listen(\n\t\t\t{\n\t\t\t\tpath: resolveSocketTransportAddress(socketPath, process.platform, secret),\n\t\t\t\treadableAll: false,\n\t\t\t\twritableAll: false,\n\t\t\t},\n\t\t\tasync () => {\n\t\t\t\tserver.off(\"error\", reject);\n\t\t\t\ttry {\n\t\t\t\t\tif (process.platform !== \"win32\" && !socketPath.startsWith(\"\\0\")) await chmod(socketPath, 0o600);\n\t\t\t\t\tresolve();\n\t\t\t\t} catch (cause) {\n\t\t\t\t\treject(cause);\n\t\t\t\t}\n\t\t\t},\n\t\t);\n\t});\n}\n\nfunction closeServer(server: Server): Promise<void> {\n\treturn new Promise((resolve) => {\n\t\tserver.close(() => resolve());\n\t});\n}\n\nfunction writeStderrLine(text: string): void {\n\t// A detached daemon exiting right after an async stderr.write to a file can\n\t// lose the output entirely; write synchronously so diagnostics always land.\n\ttry {\n\t\twriteSync(2, `${text}\\n`);\n\t} catch {\n\t\t/* fd 2 unavailable: nothing more we can do. */\n\t}\n}\n\nfunction delay(ms: number): Promise<void> {\n\treturn new Promise((resolveDelay) => setTimeout(resolveDelay, ms));\n}\n\nfunction errorMessage(cause: unknown): string {\n\treturn cause instanceof Error ? cause.message : String(cause);\n}\n\nfunction isNodeErrorCode(cause: unknown, code: string): boolean {\n\treturn cause instanceof Error && \"code\" in cause && cause.code === code;\n}\n\nfunction isRecord(value: unknown): value is Readonly<Record<string, unknown>> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction asOptionalString(value: unknown): string | undefined {\n\treturn typeof value === \"string\" ? value : typeof value === \"number\" ? String(value) : undefined;\n}\n\nfunction isEntryScript(): boolean {\n\tconst entry = process.argv[1];\n\tif (!entry) return false;\n\ttry {\n\t\treturn fileURLToPath(import.meta.url) === realpathSync(entry);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nif (!isBundledNode && isEntryScript()) {\n\tconst launch = parseSupervisorArgs(process.argv.slice(2));\n\tif (!launch) {\n\t\twriteStderrLine(\"usage: host-lifecycle.ts --socket <path> [host cli args...]\");\n\t\tprocess.exit(2);\n\t}\n\tvoid runHostSupervisor(launch);\n}\n"]}
1
+ {"version":3,"file":"host-lifecycle.js","sourceRoot":"","sources":["../../../src/modes/rpc/host-lifecycle.ts"],"names":[],"mappings":";AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AACH,OAAO,EAAqB,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC9D,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAC5E,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AACjG,OAAO,EAAE,gBAAgB,EAAE,YAAY,EAA4B,MAAM,UAAU,CAAC;AACpF,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC5D,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACz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AI,CAAC,MAAM,EAAE,CAAC;QACb,eAAe,CAAC,6DAA6D,CAAC,CAAC;QAC/E,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACjB,CAAC;IACD,KAAK,iBAAiB,CAAC,MAAM,CAAC,CAAC;AAChC,CAAC","sourcesContent":["#!/usr/bin/env node\n/**\n * Lifecycle supervisor for the shared RPC socket host started by ensureHost().\n *\n * Process tree:\n *\n * ensureHost() ──detached──▶ host-lifecycle.ts (this supervisor, owns the pidfile)\n * │ byte-proxies the public socket\n * ▼\n * cli-main --mode rpc --listen unix://<public>.internal\n *\n * The supervisor exists to enforce the host lifecycle policy without touching the\n * RPC host itself:\n *\n * - cold start: `transient` (default) means the host lives for the current login\n * session and idle-exits; `persistent` never idle-exits.\n * - idle exit: after a continuous window with zero attached client connections\n * and zero active agent turns, the supervisor tears the host down cleanly\n * (child SIGTERM first so the host flushes pending output and removes its own\n * socket, then pidfile/settings removal mirroring ensureHost's cleanupState).\n *\n * Observability without host changes: proxying the public socket yields the\n * exact connection count, and the supervisor keeps one always-on observer\n * connection to the internal socket. The multi-session host broadcasts every\n * session lifecycle/agent event to every connection, so the observer sees\n * `agent_start`/`agent_settled` for all sessions even when no client is\n * attached. If the observer connection is ever unhealthy, activity is reported\n * as unknown (non-idle), so a broken observer can only keep the host alive,\n * never kill it mid-turn.\n *\n * Lifetime binding: the host is spawned with an extra inherited pipe on fd 3\n * whose write end this supervisor holds and never writes to. The kernel closes\n * that end whenever the supervisor dies - including SIGKILL, an OOM kill, or a\n * crash, where no JS handler runs at all - so the host reads EOF and shuts down\n * cleanly, removing the private internal directory. `stopChild()` remains the\n * fast path for orderly shutdowns; the pipe is what makes an orphaned host\n * impossible. `SENPI_RPC_HOST_WATCH_PPID` is passed alongside as a belt-and-\n * braces fallback for platforms where the extra fd is not inherited.\n */\nimport { type ChildProcess, spawn } from \"node:child_process\";\nimport { randomUUID } from \"node:crypto\";\nimport { existsSync, readFileSync, realpathSync, writeSync } from \"node:fs\";\nimport { access, chmod, mkdir, readFile, rename, rm, unlink, writeFile } from \"node:fs/promises\";\nimport { createConnection, createServer, type Server, type Socket } from \"node:net\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, extname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { getAgentDir, isBunBinary, isBundledNode } from \"../../config.ts\";\nimport { processIsLive, readProcessStartTime } from \"../app-server/daemon/process.ts\";\nimport { createHostDaemonPaths, generationPaths, HOST_DAEMON_DIR_ENV } from \"./host-daemon-paths.ts\";\nimport { releaseGeneration } from \"./host-daemon-registration.ts\";\nimport { watchForSupersession } from \"./host-supersession.ts\";\nimport {\n\tHOST_CLEANUP_PATHS_ENV,\n\tHOST_PUBLIC_SOCKET_ENV,\n\tHOST_SCRATCH_DIR_ENV,\n\tHOST_WATCH_FD_ENV,\n\tHOST_WATCH_PPID_ENV,\n} from \"./host-watchdog.ts\";\nimport { attachJsonlLineReader, MAX_RPC_LINE_CHARACTERS } from \"./jsonl.ts\";\nimport { HOST_INSTANCE_ID_ENV } from \"./protocol-identity.ts\";\nimport {\n\tMAX_SOCKET_PATH_BYTES,\n\tPUBLIC_SOCKET_IDENTITY_FILE,\n\ttype SocketFileIdentity,\n\tshieldSocketDuringClose,\n\tstatSocketIdentity,\n\tunlinkOwnedSocket,\n\twriteSocketIdentityFile,\n} from \"./socket-ownership.ts\";\nimport {\n\tauthenticateSocket,\n\tcreateSocketSecret,\n\tensureSocketSecret,\n\tresolveSocketTransportAddress,\n\tSOCKET_SECRET_FILE_ENV,\n\tsendSocketHandshake,\n\tsocketSecretPath,\n} from \"./socket-transport.ts\";\n\nexport type HostColdStart = \"transient\" | \"persistent\";\n\n/** Environment override for the cold-start policy: `transient` or `persistent`. */\nexport const HOST_COLD_START_ENV = \"SENPI_RPC_HOST_COLD_START\";\n/** Environment override for the idle-exit window in milliseconds. */\nexport const HOST_IDLE_EXIT_MS_ENV = \"SENPI_RPC_HOST_IDLE_EXIT_MS\";\n/** Default idle-exit window: 15 minutes of continuous no-connection, no-turn idle. */\nexport const DEFAULT_HOST_IDLE_EXIT_MS = 15 * 60_000;\n/** Soft handoff deadline: rescan and report, never interrupt turns or in-flight requests. */\nexport const HANDOFF_GRACE_MS_ENV = \"SENPI_RPC_HANDOFF_GRACE_MS\";\nexport const DEFAULT_HANDOFF_GRACE_MS = 10 * 60_000;\n\n/** The policy fields ensureHost() records in rpc-host-daemon/settings.json. */\nexport interface HostLifecyclePolicyInput {\n\treadonly coldStart?: HostColdStart;\n\treadonly idleExitMs?: number;\n}\n\nexport interface HostLifecyclePolicy {\n\treadonly coldStart: HostColdStart;\n\treadonly idleExitMs: number;\n}\n\nconst CHILD_STOP_TIMEOUT_MS = 5_000;\n/** Win32 named-pipe shutdown can leave supervisor handles live after close starts. */\nconst WINDOWS_SUPERVISOR_SHUTDOWN_HARD_EXIT_MS = 2_000;\n\n/**\n * Child stdio slot carrying the supervisor-lifetime pipe. The supervisor holds\n * the write end open and never writes; the kernel closes it when the supervisor\n * dies for ANY reason (SIGKILL, OOM kill, crash), so the host sees EOF on this\n * fd and shuts itself down. Catchable-signal cleanup alone cannot do this.\n */\nconst CHILD_WATCH_FD = 3;\n\n/**\n * The internal hop must stay short enough for sun_path (104 bytes on macOS)\n * regardless of where the public socket lives, and private against other local\n * users, so it gets its own 0700 directory under the OS temp directory.\n *\n * On win32 the directory lives under the caller-supplied rpc-host-daemon\n * directory, which ensureHost() creates but a direct --internal-rpc-host-supervisor\n * launch does not, so the parent is created recursively.\n */\nexport async function createInternalSocketPath(\n\tbaseDir = tmpdir(),\n\tplatform: NodeJS.Platform = process.platform,\n): Promise<{ socket: string; dir?: string; secretPath?: string }> {\n\tif (platform === \"win32\") {\n\t\tconst dir = join(baseDir, `internal-${randomUUID()}`);\n\t\tawait mkdir(dir, { recursive: true, mode: 0o700 });\n\t\treturn {\n\t\t\tsocket: `\\\\\\\\.\\\\pipe\\\\senpi-rpc-internal-${randomUUID()}`,\n\t\t\tdir,\n\t\t\tsecretPath: join(dir, \"secret\"),\n\t\t};\n\t}\n\tconst dir = join(tmpdir(), `senpi-rpc-host-internal-${randomUUID().slice(0, 8)}`);\n\tawait mkdir(dir, { recursive: false, mode: 0o700 });\n\tawait writeFile(\n\t\tjoin(dir, \".owner\"),\n\t\tJSON.stringify({\n\t\t\tpid: process.pid,\n\t\t\tprocessStartTime: await readProcessStartTime(process.pid),\n\t\t\tcreatedAt: Date.now(),\n\t\t}),\n\t\t{ mode: 0o600 },\n\t);\n\treturn { socket: join(dir, \"host.sock\"), dir, secretPath: join(dir, \".secret\") };\n}\n\nexport function parseColdStart(value: string | undefined): HostColdStart | undefined {\n\treturn value === \"transient\" || value === \"persistent\" ? value : undefined;\n}\n\nexport function parseIdleExitMs(value: string | undefined): number | undefined {\n\tif (value === undefined || !/^\\d+$/.test(value.trim())) return undefined;\n\tconst parsed = Number(value.trim());\n\treturn Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;\n}\n\n/**\n * Resolves the effective host policy. Precedence: environment overrides beat\n * settings.json, which beats the documented defaults (transient, 15 minutes).\n * Invalid values at either source fall through to the next source.\n */\nexport function resolveHostPolicy(\n\tsettings: unknown,\n\tenv: Readonly<Record<string, string | undefined>>,\n): HostLifecyclePolicy {\n\tconst record = isRecord(settings) ? settings : {};\n\tconst coldStart =\n\t\tparseColdStart(env[HOST_COLD_START_ENV]) ?? parseColdStart(asOptionalString(record.coldStart)) ?? \"transient\";\n\tconst idleExitMs =\n\t\tparseIdleExitMs(env[HOST_IDLE_EXIT_MS_ENV]) ??\n\t\tparseIdleExitMs(asOptionalString(record.idleExitMs)) ??\n\t\tDEFAULT_HOST_IDLE_EXIT_MS;\n\treturn { coldStart, idleExitMs };\n}\n\nexport interface HostActivity {\n\treadonly connections: number;\n\treadonly activeTurns: number;\n}\n\n/**\n * How the supervisor reads its child's exit. The RPC host exits 0 only through\n * its own clean shutdown path - including its idle/empty-host policy - so that\n * is an intentional stop, not a crash: the supervisor mirrors its own idle exit\n * instead of reporting failure. Any non-zero code or signal stays a crash.\n */\nexport function classifyChildExit(\n\tcode: number | null,\n\tsignal: NodeJS.Signals | null,\n): { reason: string; exitCode: number } {\n\tif (code === 0 && signal === null) return { reason: \"rpc host exited on its own idle policy\", exitCode: 0 };\n\treturn { reason: `rpc host process exited unexpectedly (${code ?? signal})`, exitCode: 1 };\n}\n\nexport type IdleExitDecision = \"active\" | \"idle\" | \"exit\";\n\n/**\n * Pure idle-window decision core. `update()` must be called with the CURRENT\n * activity state; the window only counts continuously idle time and any\n * activity resets it, so a busy host can never cross the threshold.\n */\nexport class IdleExitDecider {\n\tprivate idleSince: number | undefined;\n\tprivate readonly now: () => number;\n\treadonly idleExitMs: number;\n\n\tconstructor(idleExitMs: number, now: () => number = Date.now) {\n\t\tthis.idleExitMs = idleExitMs;\n\t\tthis.now = now;\n\t}\n\n\tupdate(activity: HostActivity): IdleExitDecision {\n\t\t// Any attachment or active turn both holds the host open and resets the\n\t\t// window, so only CONTINUOUS idle can ever cross the threshold.\n\t\tif (activity.connections > 0 || activity.activeTurns > 0) {\n\t\t\tthis.idleSince = undefined;\n\t\t\treturn \"active\";\n\t\t}\n\t\tif (this.idleExitMs === Number.POSITIVE_INFINITY) return \"idle\";\n\t\tif (this.idleSince === undefined) {\n\t\t\tthis.idleSince = this.now();\n\t\t\treturn \"idle\";\n\t\t}\n\t\treturn this.now() - this.idleSince >= this.idleExitMs ? \"exit\" : \"idle\";\n\t}\n}\n\nexport interface SupervisorLaunch {\n\treadonly socket: string;\n\treadonly hostArgs: readonly string[];\n\t/** Optional runtime command used by rebranded/bundled callers. */\n\treadonly childCommand?: string;\n\treadonly childArgs?: readonly string[];\n\t/** Explicit ownership directory for callers whose environment is not yet branded. */\n\treadonly agentDir?: string;\n\t/**\n\t * Where this supervisor BINDS, when it is a successor generation: `<socket>.next-<gen>`.\n\t * It renames that entry over `socket` once its host answers - and never binds the live\n\t * public path, which belongs to the generation currently serving it.\n\t */\n\treadonly bindSocket?: string;\n\t/**\n\t * The public socket entry this generation is allowed to replace (`<dev>:<ino>`). The rename\n\t * happens only while the path still refers to it: a socket that changed underneath belongs to\n\t * somebody else now, and replacing it would unlink an endpoint this process cannot prove it owns.\n\t */\n\treadonly replaceIdentity?: SocketFileIdentity;\n}\n\n/** Hidden internal launch route: wire-invisible, never advertised by the public CLI surface. */\nexport const INTERNAL_SUPERVISOR_FLAG = \"--internal-rpc-host-supervisor\";\n\n/**\n * Engine-global flags a rebranded wrapper may legitimately prepend when it\n * re-dispatches this binary. `packages/omo-native` injects `--extension <dir>`\n * for every non-early command, which pushed the sentinel off argv[0].\n */\nconst INJECTABLE_PREFIX_FLAGS = new Set([\"--extension\"]);\n\n/**\n * Returns the internal supervisor payload when argv selects that route.\n *\n * The route dispatches when the sentinel is argv[0] OR is preceded only by\n * known injectable prefix flags and their values - the one perturbation\n * wrappers legitimately perform. Everything else disqualifies it: a positional\n * operand, `--`, or an unknown flag before the sentinel all return undefined,\n * so a user-supplied value that happens to equal the sentinel can never reach\n * the supervisor.\n *\n * The skipped prefix is deliberately NOT forwarded to the host: a wrapper\n * re-injects its own prefix on every re-entry, so the host child receives it\n * from the wrapper rather than twice from here.\n */\nexport function findInternalSupervisorArgs(argv: readonly string[]): readonly string[] | undefined {\n\tfor (let index = 0; index < argv.length; index++) {\n\t\tconst arg = argv[index];\n\t\tif (arg === INTERNAL_SUPERVISOR_FLAG) return argv.slice(index + 1);\n\t\t// A prefix flag only counts when its value is actually present.\n\t\tif (!INJECTABLE_PREFIX_FLAGS.has(arg) || index + 1 >= argv.length) return undefined;\n\t\tindex++;\n\t}\n\treturn undefined;\n}\n\n/** `--socket <path>` selects the public socket; every other argument is forwarded to the host CLI. */\nexport function parseSupervisorArgs(argv: readonly string[]): SupervisorLaunch | undefined {\n\tconst hostArgs: string[] = [];\n\tlet socket: string | undefined;\n\tlet childCommand: string | undefined;\n\tlet childArgs: readonly string[] | undefined;\n\tlet agentDir: string | undefined;\n\tlet bindSocket: string | undefined;\n\tlet replaceIdentity: SocketFileIdentity | undefined;\n\tfor (let index = 0; index < argv.length; index++) {\n\t\tconst arg = argv[index];\n\t\tif (arg === \"--socket\" && index + 1 < argv.length) {\n\t\t\tsocket = argv[++index];\n\t\t\tcontinue;\n\t\t}\n\t\tif (arg === \"--child-command\" && index + 1 < argv.length) {\n\t\t\tchildCommand = argv[++index];\n\t\t\tcontinue;\n\t\t}\n\t\tif (arg === \"--child-args\" && index + 1 < argv.length) {\n\t\t\ttry {\n\t\t\t\tconst parsed: unknown = JSON.parse(argv[++index]);\n\t\t\t\tif (Array.isArray(parsed) && parsed.every((value) => typeof value === \"string\")) childArgs = parsed;\n\t\t\t} catch {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (arg === \"--agent-dir\" && index + 1 < argv.length) {\n\t\t\tagentDir = argv[++index];\n\t\t\tcontinue;\n\t\t}\n\t\tif (arg === \"--bind\" && index + 1 < argv.length) {\n\t\t\tbindSocket = argv[++index];\n\t\t\tcontinue;\n\t\t}\n\t\tif (arg === \"--replace\" && index + 1 < argv.length) {\n\t\t\treplaceIdentity = parseSocketIdentity(argv[++index]);\n\t\t\tcontinue;\n\t\t}\n\t\thostArgs.push(arg);\n\t}\n\treturn socket === undefined\n\t\t? undefined\n\t\t: { socket, hostArgs, childCommand, childArgs, agentDir, bindSocket, replaceIdentity };\n}\n\n/** `<dev>:<ino>` as the ensure captured it; anything else is no identity at all, never a guess. */\nfunction parseSocketIdentity(value: string): SocketFileIdentity | undefined {\n\tconst match = /^(\\d+):(\\d+)$/.exec(value);\n\treturn match ? { dev: Number(match[1]), ino: Number(match[2]) } : undefined;\n}\n\n/** Resolves the committed CLI entry this supervisor wraps (source tree or built dist). */\nexport function resolveCliMainPath(): string {\n\tconst modulePath = fileURLToPath(import.meta.url);\n\tconst extension = modulePath.endsWith(\".ts\") ? \".ts\" : \".js\";\n\tconst unbundled = resolve(dirname(modulePath), \"..\", \"..\", `cli-main${extension}`);\n\tif (existsSync(unbundled)) return unbundled;\n\t// Bundled, \"..\" twice reaches the PACKAGE ROOT rather than dist/, naming a cli-main that\n\t// was never emitted. Take the entry from the package's own declared bin instead of\n\t// counting directories: it is the one statement of where the CLI lives that holds in\n\t// every layout. Falls back to the old path when nothing is declared, so a caller that\n\t// was working keeps working.\n\treturn resolveDeclaredCliEntry(modulePath) ?? unbundled;\n}\n\n/** The CLI entry declared by the nearest enclosing package.json, when it exists on disk. */\nfunction resolveDeclaredCliEntry(modulePath: string): string | undefined {\n\tlet dir = dirname(modulePath);\n\tfor (let depth = 0; depth < 8; depth += 1) {\n\t\tconst manifestPath = resolve(dir, \"package.json\");\n\t\tif (existsSync(manifestPath)) {\n\t\t\ttry {\n\t\t\t\tconst manifest = JSON.parse(readFileSync(manifestPath, \"utf8\")) as {\n\t\t\t\t\tbin?: Record<string, string> | string;\n\t\t\t\t};\n\t\t\t\tconst declared = manifest.bin;\n\t\t\t\tconst candidates = typeof declared === \"string\" ? [declared] : Object.values(declared ?? {});\n\t\t\t\tfor (const candidate of candidates) {\n\t\t\t\t\tconst entry = resolve(dir, candidate);\n\t\t\t\t\tif (existsSync(entry)) return entry;\n\t\t\t\t}\n\t\t\t} catch {}\n\t\t\treturn undefined;\n\t\t}\n\t\tconst parent = dirname(dir);\n\t\tif (parent === dir) return undefined;\n\t\tdir = parent;\n\t}\n\treturn undefined;\n}\n\n/**\n * Resolves the host child spawn. Explicit child commands (desktop launchers)\n * are forwarded untouched. The default re-enters the committed CLI entry\n * through the runtime, except in compiled standalone binaries, which always\n * boot their embedded entrypoint and would parse a script path as CLI\n * arguments - there the executable itself is the CLI, so the mode flags are\n * passed directly. Exported for tests.\n */\nexport function resolveHostChildLaunch(\n\tlaunch: SupervisorLaunch,\n\tinternalSocket: string,\n\tcompiled: boolean = isBunBinary,\n): { command: string; args: string[] } {\n\tif (launch.childCommand) {\n\t\treturn {\n\t\t\tcommand: launch.childCommand,\n\t\t\targs: [...(launch.childArgs ?? []), \"--listen\", `unix://${internalSocket}`],\n\t\t};\n\t}\n\treturn {\n\t\tcommand: process.execPath,\n\t\targs: [\n\t\t\t...(compiled ? [] : [...process.execArgv, resolveCliMainPath()]),\n\t\t\t\"--mode\",\n\t\t\t\"rpc\",\n\t\t\t\"--multi-session\",\n\t\t\t\"--listen\",\n\t\t\t`unix://${internalSocket}`,\n\t\t\t...launch.hostArgs,\n\t\t],\n\t};\n}\n\n/** Mirrors cross-spawn: survives cmd.exe parsing and `CommandLineToArgvW`. */\nfunction quoteWindowsShellArg(value: string): string {\n\tconst escaped = value\n\t\t.replace(/(\\\\*)\"/g, '$1$1\\\\\"')\n\t\t.replace(/(\\\\*)$/, \"$1$1\")\n\t\t.replace(/([()%!^\"<>&|;,])/g, \"^$1\");\n\treturn `\"${escaped}\"`;\n}\n\n/**\n * Windows refuses to spawn a `.cmd`/`.bat` without a shell, and Node's\n * `shell: true` concatenates argv without escaping it. Escape each original\n * value before adding the surrounding quotes so `.cmd`/`.bat` launchers survive\n * cmd.exe parsing without double-escaping.\n * Exported for tests.\n */\nexport function spawnableChildLaunch(\n\tlaunch: { command: string; args: string[] },\n\tplatform: NodeJS.Platform = process.platform,\n): { command: string; args: string[]; shell: boolean } {\n\tconst extension = extname(launch.command).toLowerCase();\n\tif (platform !== \"win32\" || (extension !== \".cmd\" && extension !== \".bat\")) {\n\t\treturn { ...launch, shell: false };\n\t}\n\treturn {\n\t\tcommand: quoteWindowsShellArg(launch.command),\n\t\targs: launch.args.map(quoteWindowsShellArg),\n\t\tshell: true,\n\t};\n}\n\nexport async function runHostSupervisor(launch: SupervisorLaunch): Promise<void> {\n\tconst paths = createHostDaemonPaths({ socket: launch.socket, agentDir: launch.agentDir ?? getAgentDir() });\n\t// Which generation this supervisor is: the ensure that spawned it says so, and a DIRECT launch\n\t// (the hidden supervisor route, with no ensure behind it) names itself so its child agrees.\n\tconst told = process.env[HOST_INSTANCE_ID_ENV];\n\tconst instanceId = told !== undefined && told.trim() !== \"\" ? told : randomUUID();\n\tconst generation = generationPaths(paths, instanceId);\n\tconst policy = resolveHostPolicy(await readSettingsFile(paths.settingsFile), process.env);\n\tconst publicSocket = launch.socket;\n\t// A successor generation binds its own name and adopts the public one by rename; an ordinary\n\t// start binds the public name directly. Everything downstream - the child's environment, the\n\t// ownership token, the teardown - is expressed in terms of the PUBLIC path either way.\n\tconst bindSocket = launch.bindSocket ?? publicSocket;\n\tconst successor = launch.bindSocket !== undefined;\n\t// Direct-launch contract: the supervisor owns the public secret. ensureHost()\n\t// writes it before spawning, but the hidden --internal-rpc-host-supervisor route\n\t// has no such caller, so a fresh profile would otherwise die reading it (#1370).\n\t// It is provisioned BEFORE the internal hop and the child so a provisioning\n\t// failure leaves no scratch directory and no host process behind.\n\tconst publicSecret = process.platform === \"win32\" ? await ensurePublicSocketSecret(publicSocket) : undefined;\n\tconst internal = await createInternalSocketPath(paths.dir);\n\tconst internalSocket = internal.socket;\n\tconst internalSecretPath = internal.secretPath ?? socketSecretPath(internalSocket);\n\tconst internalSecret = process.platform === \"win32\" ? await createSocketSecret(internalSecretPath) : undefined;\n\tconst clientSockets = new Set<Socket>();\n\tconst busySessions = new Map<string, number>();\n\tlet observerHealthy = false;\n\tlet observerReconnectTimer: ReturnType<typeof setTimeout> | undefined;\n\tlet childExitWatchTimer: ReturnType<typeof setInterval> | undefined;\n\tlet stopSupersessionWatch: (() => void) | undefined;\n\tlet shuttingDown = false;\n\tlet draining = false;\n\tlet handoffGraceTimer: ReturnType<typeof setTimeout> | undefined;\n\tlet shutdownPromise: Promise<never> | undefined;\n\n\tconst childLaunch = spawnableChildLaunch(resolveHostChildLaunch(launch, internalSocket));\n\tconst child = spawn(childLaunch.command, childLaunch.args, {\n\t\tenv: {\n\t\t\t...process.env,\n\t\t\t...(launch.agentDir ? { SENPI_CODING_AGENT_DIR: launch.agentDir } : {}),\n\t\t\t// The child binds a PRIVATE socket, so it cannot derive this endpoint's daemon directory\n\t\t\t// from what it listens on: it is told, and it claims its session paths there.\n\t\t\t[HOST_DAEMON_DIR_ENV]: paths.dir,\n\t\t\t[HOST_INSTANCE_ID_ENV]: instanceId,\n\t\t\t[HOST_WATCH_FD_ENV]: String(CHILD_WATCH_FD),\n\t\t\t[HOST_WATCH_PPID_ENV]: String(process.pid),\n\t\t\t...(internal.dir ? { [HOST_SCRATCH_DIR_ENV]: internal.dir } : {}),\n\t\t\t...(internalSecret ? { [SOCKET_SECRET_FILE_ENV]: internalSecretPath } : {}),\n\t\t\t[HOST_CLEANUP_PATHS_ENV]: [\n\t\t\t\t// A successor writes no registration of its own until the ensure that spawned it does,\n\t\t\t\t// and the files under these paths still describe the generation being replaced.\n\t\t\t\t...(successor ? [] : [paths.pointerFile, generation.pidFile, paths.settingsFile]),\n\t\t\t\t// POSIX public sockets are removed ownership-checked by the host child\n\t\t\t\t// (token: the scratch-directory sidecar plus HOST_PUBLIC_SOCKET_ENV),\n\t\t\t\t// never by path from a crash-path cleanup: a blind removal here would\n\t\t\t\t// unlink a newer host's freshly published entry after a takeover.\n\t\t\t\t// Windows named pipes have no filesystem entry to own, so they stay\n\t\t\t\t// listed for the crash-path cleanup.\n\t\t\t\t...(process.platform === \"win32\" ? [publicSocket] : []),\n\t\t\t].join(\"\\n\"),\n\t\t\t...(process.platform === \"win32\" ? {} : { [HOST_PUBLIC_SOCKET_ENV]: publicSocket }),\n\t\t},\n\t\t// Slot 3 is the lifetime pipe: \"pipe\" gives the child a read end it can\n\t\t// wait on and keeps the write end owned by this process alone.\n\t\tshell: childLaunch.shell,\n\t\tstdio: [\"ignore\", \"ignore\", \"inherit\", \"pipe\"],\n\t\t// The supervisor is spawned detached, so on win32 it owns no console. A\n\t\t// console-subsystem child started from it would allocate a fresh one,\n\t\t// which Windows Terminal renders as an empty window that takes focus.\n\t\t// CREATE_NO_WINDOW gives the child a console with no window instead.\n\t\twindowsHide: true,\n\t});\n\t// Nothing is ever written; the pipe exists purely so its EOF is a reliable\n\t// death notification. Errors on it must not crash the supervisor.\n\tchild.stdio[CHILD_WATCH_FD]?.on(\"error\", () => {});\n\tchild.once(\"exit\", (code, signal) => {\n\t\tif (shuttingDown) return;\n\t\tconst { reason, exitCode } = classifyChildExit(code, signal);\n\t\tvoid shutdown(reason, exitCode);\n\t});\n\n\tconst server = createServer((client) => {\n\t\tconst accept = (): void => {\n\t\t\t// A draining supervisor serves what it already proxies and accepts nothing new. After a\n\t\t\t// handoff the public path resolves to the successor anyway; this covers the connection\n\t\t\t// that raced the rename, and a drain-stop with no successor at all.\n\t\t\tif (shuttingDown || draining) {\n\t\t\t\tclient.destroy();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst internal = createConnection(\n\t\t\t\tresolveSocketTransportAddress(internalSocket, process.platform, internalSecret),\n\t\t\t);\n\t\t\tif (internalSecret) sendSocketHandshake(internal, internalSecret);\n\t\t\tclientSockets.add(client);\n\t\t\t// A readiness exchange can begin and end between ticks. Record the\n\t\t\t// attachment now, before a later tick can reuse the preceding idle window.\n\t\t\tdecider.update(currentActivity());\n\t\t\tconst detach = (): void => {\n\t\t\t\tclientSockets.delete(client);\n\t\t\t\tdecider.update(currentActivity());\n\t\t\t\tinternal.destroy();\n\t\t\t\tclient.destroy();\n\t\t\t};\n\t\t\tclient.pipe(internal);\n\t\t\tinternal.pipe(client);\n\t\t\tclient.once(\"close\", detach);\n\t\t\tclient.once(\"error\", detach);\n\t\t\t// Let the final lifecycle records drain through the public socket before closing it.\n\t\t\tinternal.once(\"end\", () => client.end(() => client.destroy()));\n\t\t\tinternal.once(\"close\", () => {\n\t\t\t\tif (!internal.readableEnded) detach();\n\t\t\t});\n\t\t\tinternal.once(\"error\", detach);\n\t\t};\n\t\tif (publicSecret) authenticateSocket(client, publicSecret, accept);\n\t\telse accept();\n\t});\n\tserver.once(\"error\", (cause) => {\n\t\tif (!shuttingDown) void shutdown(`public socket listener failed: ${errorMessage(cause)}`, 1);\n\t});\n\n\tconst decider = new IdleExitDecider(\n\t\tpolicy.coldStart === \"persistent\" ? Number.POSITIVE_INFINITY : policy.idleExitMs,\n\t);\n\tconst tickIntervalMs = Math.max(20, Math.min(1_000, policy.idleExitMs / 4));\n\tconst ticker = setInterval(() => {\n\t\tif (!draining && decider.update(currentActivity()) === \"exit\") void shutdown(\"idle\", 0);\n\t}, tickIntervalMs);\n\n\tfunction currentActivity(): HostActivity {\n\t\treturn {\n\t\t\tconnections: clientSockets.size,\n\t\t\tactiveTurns: observerHealthy ? countBusySessions() : 1,\n\t\t};\n\t}\n\n\tfunction countBusySessions(): number {\n\t\tlet busy = 0;\n\t\tfor (const count of busySessions.values()) if (count > 0) busy++;\n\t\treturn busy;\n\t}\n\n\tfunction observeHostEvent(line: string): void {\n\t\tlet event: unknown;\n\t\ttry {\n\t\t\tevent = JSON.parse(line);\n\t\t} catch {\n\t\t\treturn;\n\t\t}\n\t\tif (typeof event !== \"object\" || event === null) return;\n\t\tconst { type, sessionId } = event as { type?: unknown; sessionId?: unknown };\n\t\tif (typeof sessionId !== \"string\") return;\n\t\tif (type === \"agent_start\") busySessions.set(sessionId, (busySessions.get(sessionId) ?? 0) + 1);\n\t\telse if (type === \"agent_settled\")\n\t\t\tbusySessions.set(sessionId, Math.max(0, (busySessions.get(sessionId) ?? 1) - 1));\n\t\telse return;\n\t\tdecider.update(currentActivity());\n\t}\n\n\tasync function shutdown(reason: string, exitCode: number): Promise<never> {\n\t\t// Single-flight: concurrent triggers (listener error, child exit, signals)\n\t\t// must not process.exit mid-cleanup. Late callers park on this promise while\n\t\t// the first shutdown finishes tearing down and exits.\n\t\tshutdownPromise ??= performShutdown(reason, exitCode);\n\t\treturn shutdownPromise;\n\t}\n\n\tasync function performShutdown(reason: string, exitCode: number): Promise<never> {\n\t\tif (shuttingDown) process.exit(exitCode);\n\t\tshuttingDown = true;\n\t\tclearInterval(ticker);\n\t\tif (handoffGraceTimer) clearTimeout(handoffGraceTimer);\n\t\tif (childExitWatchTimer) clearInterval(childExitWatchTimer);\n\t\tstopSupersessionWatch?.();\n\t\tconst hardExit =\n\t\t\tprocess.platform === \"win32\"\n\t\t\t\t? setTimeout(() => process.exit(exitCode), WINDOWS_SUPERVISOR_SHUTDOWN_HARD_EXIT_MS)\n\t\t\t\t: undefined;\n\t\ttry {\n\t\t\twriteStderrLine(`senpi rpc host supervisor: ${reason} shutdown`);\n\t\t\tfor (const client of clientSockets) client.destroy();\n\t\t\t// libuv unlinks the bound NAME when the listening handle closes - which\n\t\t\t// would delete a newer host's entry renamed over this path. Shield the\n\t\t\t// current entry for the close, then let the ownership check decide. A drained\n\t\t\t// supervisor already closed that handle when it stopped accepting.\n\t\t\tif (!draining) await shieldSocketDuringClose(publicSocket, () => closeServer(server));\n\t\t\t// Unlink the private directory BEFORE the child stop, which can take seconds:\n\t\t\t// an external SIGKILL landing during that wait (ensureHost escalates while\n\t\t\t// replacing a host) would otherwise leave the directory behind. The child\n\t\t\t// keeps serving through its already-open socket fd until it exits, and its\n\t\t\t// own watchdog cleanup makes the removal idempotent.\n\t\t\tif (internal.dir) await rm(internal.dir, { recursive: true, force: true });\n\t\t\tawait stopChild(child);\n\t\t\tobserver?.destroy();\n\t\t\tif (publicSocketOwned && process.platform !== \"win32\") {\n\t\t\t\t// Ownership-checked: after a takeover, a newer host may have published\n\t\t\t\t// a fresh entry at this path; only the entry THIS supervisor bound is\n\t\t\t\t// removed. (The host child applies the same rule to its crash path.)\n\t\t\t\tawait unlinkOwnedSocket(publicSocket, publicSocketIdentity, supervisorLog);\n\t\t\t}\n\t\t\t// The registration describes a LIVE host only; the stderr log stays for diagnostics.\n\t\t\t// After a handoff the pointer describes the SUCCESSOR, so this drops only the generation\n\t\t\t// directory of the process that is leaving, and the pointer only while it still names it.\n\t\t\tawait releaseGeneration(paths, { instanceId, pid: process.pid });\n\t\t} finally {\n\t\t\tif (hardExit) clearTimeout(hardExit);\n\t\t\t// Explicitly terminate after every supervisor shutdown trigger. Windows\n\t\t\t// named-pipe handles can outlive their JavaScript wrappers, so cleanup\n\t\t\t// failure must never leave the supervisor resident or the host orphaned.\n\t\t\tprocess.exit(exitCode);\n\t\t}\n\t}\n\n\tlet observer: Socket | undefined;\n\tlet publicSocketOwned = false;\n\tlet publicSocketIdentity: SocketFileIdentity | undefined;\n\tfunction supervisorLog(message: string): void {\n\t\twriteStderrLine(`senpi rpc host supervisor: ${message}`);\n\t}\n\t// Registered before the startup handshake, not after it: the private internal\n\t// directory already exists at this point, so a SIGTERM arriving during host\n\t// startup must run the same cleanup instead of Node's default kill, which\n\t// would leave that directory behind.\n\t/**\n\t * Ask the child to announce and park attached sessions as turns/requests settle. The supervisor\n\t * owns the soft grace from this instant; expiry rescans but NEVER kills busy sessions. Child\n\t * exit ends the supervisor regardless of clients that keep their connections open.\n\t */\n\tfunction drainForHandoff(): void {\n\t\tif (draining || shuttingDown) return;\n\t\tdraining = true;\n\t\tsupervisorLog(\"draining into the next generation\");\n\t\tconst graceMs = parseIdleExitMs(process.env[HANDOFF_GRACE_MS_ENV]) ?? DEFAULT_HANDOFF_GRACE_MS;\n\t\thandoffGraceTimer = setTimeout(() => {\n\t\t\tsupervisorLog(JSON.stringify({ event: \"handoff_grace_expired\", graceMs }));\n\t\t\trequestChildDrain();\n\t\t}, graceMs);\n\t\thandoffGraceTimer.unref();\n\t\t// The listening handle is deliberately NOT closed: libuv unlinks a pipe's bound NAME when it\n\t\t// closes, and after a handoff that name is the successor's entry. Nothing can reach this\n\t\t// listener by path any more (the rename moved the name), and the accept guard above turns\n\t\t// away whatever raced it, so leaving the handle open until exit costs nothing and keeps the\n\t\t// public path continuously answerable - no window where a client finds no socket at all.\n\t\trequestChildDrain();\n\t}\n\tfunction requestChildDrain(): void {\n\t\tif (child.pid !== undefined && child.exitCode === null && child.signalCode === null) {\n\t\t\ttry {\n\t\t\t\tprocess.kill(child.pid, \"SIGUSR1\");\n\t\t\t} catch (cause) {\n\t\t\t\tsupervisorLog(`could not ask the host to drain: ${errorMessage(cause)}`);\n\t\t\t}\n\t\t}\n\t}\n\tregisterSupervisorSignals(shutdown, drainForHandoff);\n\ttry {\n\t\tawait waitForListener(internalSocket, 30_000, internalSecret);\n\t\tawait connectObserver();\n\t\tawait prepareSocketPath(bindSocket);\n\t\tawait listen(server, bindSocket, publicSecret);\n\t\tpublicSocketOwned = true;\n\t\tif (successor) await adoptPublicSocket(bindSocket, publicSocket, launch.replaceIdentity);\n\t\tpublicSocketIdentity = await statSocketIdentity(publicSocket);\n\t\t// Publish the ownership token inside this supervisor's private scratch\n\t\t// directory (which no replacement supervisor writes): the host child's\n\t\t// crash-path cleanup compares the public path against THIS entry only.\n\t\tif (publicSocketIdentity && internal.dir) {\n\t\t\tawait writeSocketIdentityFile(join(internal.dir, PUBLIC_SOCKET_IDENTITY_FILE), publicSocketIdentity);\n\t\t}\n\t\t// Losing the public entry IS a drain request: nothing can reach this supervisor by path any\n\t\t// more, and the handoff that replaced it may never have signalled (#1893).\n\t\tstopSupersessionWatch = watchForSupersession(\n\t\t\t{ path: publicSocket, identity: publicSocketIdentity, settled: () => shuttingDown || draining },\n\t\t\t() => {\n\t\t\t\tsupervisorLog(\"another generation owns the public socket; draining this one\");\n\t\t\t\tdrainForHandoff();\n\t\t\t},\n\t\t);\n\t} catch (cause) {\n\t\tawait shutdown(`startup failed: ${errorMessage(cause)}`, 1);\n\t}\n\tasync function connectObserver(): Promise<void> {\n\t\tconst secret = internalSecret;\n\t\tconst next = createConnection(resolveSocketTransportAddress(internalSocket, process.platform, secret));\n\t\tif (secret) sendSocketHandshake(next, secret);\n\t\tawait waitForConnect(next, 5_000);\n\t\tobserver = next;\n\t\tobserverHealthy = true;\n\t\tattachJsonlLineReader(next, observeHostEvent, { maxLineLength: MAX_RPC_LINE_CHARACTERS });\n\t\tconst lost = (): void => {\n\t\t\tif (observer !== next || shuttingDown) return;\n\t\t\tobserverHealthy = false;\n\t\t\tobserver = undefined;\n\t\t\tif (observerReconnectTimer === undefined) {\n\t\t\t\tobserverReconnectTimer = setTimeout(() => {\n\t\t\t\t\tobserverReconnectTimer = undefined;\n\t\t\t\t\tvoid connectObserver().catch(() => lost());\n\t\t\t\t}, 250);\n\t\t\t\tobserverReconnectTimer.unref?.();\n\t\t\t}\n\t\t};\n\t\tnext.once(\"close\", lost);\n\t\tnext.once(\"error\", lost);\n\t}\n\n\tif (process.platform === \"win32\" && child.pid !== undefined) {\n\t\t// This baseline read sits outside the startup try/catch, and readProcessStartTime\n\t\t// THROWS when the 1s CIM probe fails (execFile's timeout SIGTERMs the PowerShell\n\t\t// child). With no unhandledRejection handler the supervisor died right here on a\n\t\t// loaded runner: it never reached the \"host ready\" line, and the internal host it\n\t\t// owned vanished with it, surfacing downstream as `connect ENOENT` on the pipe and\n\t\t// as `reported dead`. A failed baseline read is UNKNOWN, so the watchdog simply\n\t\t// starts without one and relies on its own comparisons.\n\t\tconst childStartTime = await readProcessStartTime(child.pid, process.platform, 1_000).catch(() => undefined);\n\t\tlet missingIdentityChecks = 0;\n\t\tlet checkingChildIdentity = false;\n\t\tconst checkChildIdentity = (): void => {\n\t\t\tif (shuttingDown || checkingChildIdentity || child.exitCode !== null || child.signalCode !== null) return;\n\t\t\tcheckingChildIdentity = true;\n\t\t\tvoid readProcessStartTime(child.pid!, process.platform, 1_000)\n\t\t\t\t.then((currentStartTime) => {\n\t\t\t\t\t// An absent identity is only believed once kill(pid, 0) agrees the child is\n\t\t\t\t\t// gone. This probe is a 1s PowerShell CIM spawn polled every 500ms, so a\n\t\t\t\t\t// loaded runner produced two consecutive timeouts and this watchdog shut\n\t\t\t\t\t// down a perfectly healthy host (`does not exit while a turn is active`).\n\t\t\t\t\t// A timed-out probe means UNKNOWN, never EXITED.\n\t\t\t\t\tif (currentStartTime === undefined && !processIsLive(child.pid!)) missingIdentityChecks++;\n\t\t\t\t\telse if (currentStartTime !== undefined) missingIdentityChecks = 0;\n\t\t\t\t\tconst identityChanged =\n\t\t\t\t\t\tchildStartTime !== undefined && currentStartTime !== undefined && currentStartTime !== childStartTime;\n\t\t\t\t\tif (identityChanged || missingIdentityChecks >= 2) {\n\t\t\t\t\t\tvoid shutdown(\"rpc host child exit observed by identity watchdog\", 0);\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\t.catch(() => {})\n\t\t\t\t.finally(() => {\n\t\t\t\t\tcheckingChildIdentity = false;\n\t\t\t\t});\n\t\t};\n\t\tchildExitWatchTimer = setInterval(checkChildIdentity, 500);\n\t\tchildExitWatchTimer.unref?.();\n\t}\n\twriteStderrLine(\n\t\t`senpi rpc host ready on unix://${publicSocket} (coldStart=${policy.coldStart}, idleExitMs=${\n\t\t\tpolicy.coldStart === \"persistent\" ? \"never\" : String(policy.idleExitMs)\n\t\t})`,\n\t);\n\tawait new Promise<never>(() => {});\n}\n\n/**\n * External stop (ensureHost replacement, tests, QA) must clean up like idle exit; SIGUSR1 is the\n * gentler request - finish what you are doing and leave - that a generation handoff and\n * `stopHost({ drain: true })` both send. It exists on POSIX only, which is one reason win32 hosts\n * are attach-only: no signal there means anything but \"terminate\".\n */\nfunction registerSupervisorSignals(\n\tshutdown: (reason: string, exitCode: number) => Promise<never>,\n\tdrain: () => void,\n): void {\n\tfor (const signal of process.platform === \"win32\" ? ([\"SIGTERM\"] as const) : ([\"SIGTERM\", \"SIGHUP\"] as const)) {\n\t\tprocess.on(signal, () => {\n\t\t\tvoid shutdown(`signal:${signal}`, signal === \"SIGHUP\" ? 129 : 143);\n\t\t});\n\t}\n\tif (process.platform !== \"win32\") process.on(\"SIGUSR1\", drain);\n}\n\n/**\n * Takes the public name over with a rename, once - and only while - that name still refers to the\n * entry this handoff was decided against. A socket that changed underneath belongs to another\n * process now: replacing it would unlink an endpoint this generation cannot prove it owns, so the\n * successor aborts instead and leaves both the intruder's socket and its own bind entry alone.\n */\nasync function adoptPublicSocket(\n\tbindSocket: string,\n\tpublicSocket: string,\n\texpected: SocketFileIdentity | undefined,\n): Promise<void> {\n\tif (expected === undefined) throw new Error(`${publicSocket}: a generation launch must name the entry it replaces`);\n\tconst current = await statSocketIdentity(publicSocket);\n\tif (current === undefined || current.dev !== expected.dev || current.ino !== expected.ino) {\n\t\tthrow new Error(`${publicSocket}: owned by another socket entry now; refusing to replace it`);\n\t}\n\t// rename(2) is atomic for readers of the path: every connect either reaches the old entry or\n\t// this one, never nothing. The inode this supervisor bound simply answers to a second name.\n\tawait rename(bindSocket, publicSocket);\n}\n\n/**\n * Reuses an existing valid secret - including one ensureHost() just wrote - and\n * creates one (with its parent directories, mode 0600) when it is missing or\n * unusable. Reuse is required, not just an optimization: on win32 the pipe name\n * is derived from the socket path AND the secret, so rotating it here would\n * point this supervisor at a different endpoint than its caller published.\n * A failure names the bootstrap step and the path it could not provision.\n */\nasync function ensurePublicSocketSecret(publicSocket: string): Promise<Buffer> {\n\tconst secretPath = socketSecretPath(publicSocket);\n\ttry {\n\t\treturn await ensureSocketSecret(secretPath);\n\t} catch (cause) {\n\t\tthrow new Error(`senpi rpc host supervisor: cannot provision public socket secret ${secretPath}`, { cause });\n\t}\n}\n\nasync function readSettingsFile(settingsFile: string): Promise<unknown> {\n\ttry {\n\t\treturn JSON.parse(await readFile(settingsFile, \"utf8\"));\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nasync function stopChild(child: ChildProcess): Promise<void> {\n\tif (child.exitCode !== null || child.signalCode !== null) return;\n\ttry {\n\t\tchild.kill(\"SIGTERM\");\n\t} catch {\n\t\treturn;\n\t}\n\tif (await waitForChildExit(child, CHILD_STOP_TIMEOUT_MS)) return;\n\ttry {\n\t\tchild.kill(\"SIGKILL\");\n\t} catch {\n\t\treturn;\n\t}\n\tawait waitForChildExit(child, 2_000);\n}\n\nfunction waitForChildExit(child: ChildProcess, timeoutMs: number): Promise<boolean> {\n\tif (child.exitCode !== null || child.signalCode !== null) return Promise.resolve(true);\n\treturn new Promise((resolve) => {\n\t\tconst timer = setTimeout(() => {\n\t\t\tchild.off(\"exit\", onExit);\n\t\t\tresolve(false);\n\t\t}, timeoutMs);\n\t\tconst onExit = (): void => {\n\t\t\tclearTimeout(timer);\n\t\t\tresolve(true);\n\t\t};\n\t\tchild.once(\"exit\", onExit);\n\t});\n}\n\nasync function waitForListener(socketPath: string, timeoutMs: number, secret?: Uint8Array): Promise<void> {\n\tconst deadline = Date.now() + timeoutMs;\n\twhile (Date.now() <= deadline) {\n\t\tif (await canConnect(socketPath, secret)) return;\n\t\tawait delay(50);\n\t}\n\tthrow new Error(`${socketPath}: host did not start listening within ${timeoutMs}ms`);\n}\n\nfunction canConnect(socketPath: string, secret?: Uint8Array): Promise<boolean> {\n\treturn new Promise((resolve) => {\n\t\tconst socket = createConnection(resolveSocketTransportAddress(socketPath, process.platform, secret));\n\t\tif (secret) sendSocketHandshake(socket, secret);\n\t\tconst settle = (value: boolean): void => {\n\t\t\tsocket.destroy();\n\t\t\tresolve(value);\n\t\t};\n\t\tsocket.once(\"connect\", () => settle(true));\n\t\tsocket.once(\"error\", () => settle(false));\n\t});\n}\n\nfunction waitForConnect(socket: Socket, timeoutMs: number): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst timer = setTimeout(() => {\n\t\t\tcleanup();\n\t\t\treject(new Error(`observer connection to internal host timed out after ${timeoutMs}ms`));\n\t\t}, timeoutMs);\n\t\tconst onConnect = (): void => {\n\t\t\tcleanup();\n\t\t\tresolve();\n\t\t};\n\t\tconst onError = (cause: Error): void => {\n\t\t\tcleanup();\n\t\t\treject(cause);\n\t\t};\n\t\tconst cleanup = (): void => {\n\t\t\tclearTimeout(timer);\n\t\t\tsocket.off(\"connect\", onConnect);\n\t\t\tsocket.off(\"error\", onError);\n\t\t};\n\t\tsocket.once(\"connect\", onConnect);\n\t\tsocket.once(\"error\", onError);\n\t});\n}\n\nasync function prepareSocketPath(socketPath: string): Promise<void> {\n\tif (process.platform === \"win32\") return;\n\t// A path the kernel would truncate binds a DIFFERENT endpoint than the one every client was\n\t// told about, and the failure surfaces much later as \"the host does not answer\". Refuse here.\n\tif (Buffer.byteLength(socketPath) > MAX_SOCKET_PATH_BYTES) {\n\t\tthrow new Error(\n\t\t\t`${socketPath}: socket path is ${Buffer.byteLength(socketPath)} bytes, over the ${MAX_SOCKET_PATH_BYTES}-byte limit.`,\n\t\t);\n\t}\n\tawait mkdir(dirname(socketPath), { recursive: true, mode: 0o700 });\n\ttry {\n\t\tawait access(socketPath);\n\t} catch (cause) {\n\t\tif (isNodeErrorCode(cause, \"ENOENT\")) return;\n\t\tthrow cause;\n\t}\n\tif (await canConnect(socketPath)) throw new Error(`${socketPath}: address already in use by a live server.`);\n\tawait unlink(socketPath);\n}\n\nfunction listen(server: Server, socketPath: string, secret?: Uint8Array): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tserver.once(\"error\", reject);\n\t\tserver.listen(\n\t\t\t{\n\t\t\t\tpath: resolveSocketTransportAddress(socketPath, process.platform, secret),\n\t\t\t\treadableAll: false,\n\t\t\t\twritableAll: false,\n\t\t\t},\n\t\t\tasync () => {\n\t\t\t\tserver.off(\"error\", reject);\n\t\t\t\ttry {\n\t\t\t\t\tif (process.platform !== \"win32\" && !socketPath.startsWith(\"\\0\")) await chmod(socketPath, 0o600);\n\t\t\t\t\tresolve();\n\t\t\t\t} catch (cause) {\n\t\t\t\t\treject(cause);\n\t\t\t\t}\n\t\t\t},\n\t\t);\n\t});\n}\n\nfunction closeServer(server: Server): Promise<void> {\n\treturn new Promise((resolve) => {\n\t\tserver.close(() => resolve());\n\t});\n}\n\nfunction writeStderrLine(text: string): void {\n\t// A detached daemon exiting right after an async stderr.write to a file can\n\t// lose the output entirely; write synchronously so diagnostics always land.\n\ttry {\n\t\twriteSync(2, `${text}\\n`);\n\t} catch {\n\t\t/* fd 2 unavailable: nothing more we can do. */\n\t}\n}\n\nfunction delay(ms: number): Promise<void> {\n\treturn new Promise((resolveDelay) => setTimeout(resolveDelay, ms));\n}\n\nfunction errorMessage(cause: unknown): string {\n\treturn cause instanceof Error ? cause.message : String(cause);\n}\n\nfunction isNodeErrorCode(cause: unknown, code: string): boolean {\n\treturn cause instanceof Error && \"code\" in cause && cause.code === code;\n}\n\nfunction isRecord(value: unknown): value is Readonly<Record<string, unknown>> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction asOptionalString(value: unknown): string | undefined {\n\treturn typeof value === \"string\" ? value : typeof value === \"number\" ? String(value) : undefined;\n}\n\nfunction isEntryScript(): boolean {\n\tconst entry = process.argv[1];\n\tif (!entry) return false;\n\ttry {\n\t\treturn fileURLToPath(import.meta.url) === realpathSync(entry);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nif (!isBundledNode && isEntryScript()) {\n\tconst launch = parseSupervisorArgs(process.argv.slice(2));\n\tif (!launch) {\n\t\twriteStderrLine(\"usage: host-lifecycle.ts --socket <path> [host cli args...]\");\n\t\tprocess.exit(2);\n\t}\n\tvoid runHostSupervisor(launch);\n}\n"]}
@@ -35,6 +35,7 @@ export interface HostIdleOverrides {
35
35
  closeGraceMs?: number;
36
36
  /** Shutdown hook the empty-exit window invokes; hosts pass their exit path. */
37
37
  onEmptyExit?: () => void;
38
+ onHandoffParked?: (connections: readonly string[]) => Promise<void>;
38
39
  /** Gate consulted before the empty-exit window advances (connected clients block it). */
39
40
  canExitWhenEmpty?: () => boolean;
40
41
  }
@@ -1 +1 @@
1
- {"version":3,"file":"multi-session-host.d.ts","sourceRoot":"","sources":["../../../src/modes/rpc/multi-session-host.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,gCAAgC,EAAE,MAAM,qCAAqC,CAAC;AAS5F,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,eAAe,CAAC;AAe7D,OAAO,EAAE,KAAK,iBAAiB,EAAE,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AAC3F,OAAO,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAsB/D,MAAM,WAAW,uBAAuB;IACvC,QAAQ,EAAE,MAAM,CAAC;IACjB,aAAa,EAAE,gCAAgC,CAAC;IAChD,mBAAmB,CAAC,EAAE,uBAAuB,CAAC;IAC9C,GAAG,EAAE,MAAM,C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kGAAkG;AAClG,MAAM,WAAW,iBAAiB;IACjC,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;IACnB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,+EAA+E;IAC/E,WAAW,CAAC,EAAE,MAAM,IAAI,CAAC;IACzB,eAAe,CAAC,EAAE,CAAC,WAAW,EAAE,SAAS,MAAM,EAAE,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACpE,yFAAyF;IACzF,gBAAgB,CAAC,EAAE,MAAM,OAAO,CAAC;CACjC;AAED;;GAEG;AACH,wBAAgB,qBAAqB,CACpC,GAAG,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC,EACjD,SAAS,GAAE,iBAAsB,GAC/B;IAAE,GAAG,EAAE,MAAM,MAAM,CAAC;IAAC,cAAc,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAA;CAAE,CAUpE;AAsCD;;;;;GAKG;AACH,wBAAsB,mBAAmB,CAAC,OAAO,EAAE,uBAAuB,GAAG,OAAO,CAAC,KAAK,CAAC,CAG1F;AAED,wBAAgB,cAAc,CAC7B,OAAO,EAAE,uBAAuB,EAChC,MAAM,EAAE,kBAAkB,EAC1B,YAAY,WAA+D,EAC3E,IAAI,GAAE,iBAAsB;;mBAsCA,MAAM,KAAG,OAAO,CAAC,IAAI,CAAC;EAiBlD"}
@@ -14,7 +14,7 @@ import { createEndpointReservations } from "./host-reservations.js";
14
14
  import { armHostWatchdog, readHostWatchdogConfigFromBrandEnv } from "./host-watchdog.js";
15
15
  import { attachJsonlLineReader, MAX_RPC_LINE_CHARACTERS } from "./jsonl.js";
16
16
  import { LoopLagWatchdog } from "./loop-lag-watchdog.js";
17
- import { hostInstanceId } from "./protocol-identity.js";
17
+ import { hostGeneration, hostInstanceId } from "./protocol-identity.js";
18
18
  import { rpcCommandShapeError } from "./rpc-input-validation.js";
19
19
  import { SessionCommandRouter } from "./session-command-router.js";
20
20
  import { SessionEventWriter } from "./session-event-writer.js";
@@ -109,6 +109,7 @@ export function createHostCore(options, writer, capabilities = parseClientCapabi
109
109
  idleEvictionMs: policy.idleEvictionMs,
110
110
  emptyExitMs: policy.emptyExitMs,
111
111
  onEmptyExit: idle.onEmptyExit,
112
+ onHandoffParked: idle.onHandoffParked,
112
113
  canExitWhenEmpty: idle.canExitWhenEmpty,
113
114
  });
114
115
  const handle = async (line) => {
@@ -175,6 +176,7 @@ async function runSocketHost(options, socketPath) {
175
176
  const writer = new SessionEventWriter(() => { });
176
177
  const connections = new Map();
177
178
  let draining = false;
179
+ let handoffAnnounced = false;
178
180
  const { router, handle } = createHostCore(options, writer, [
179
181
  ...parseClientCapabilities(envValue("RPC_CLIENT_CAPABILITIES")).filter((capability) => capability !== "rendered_components"),
180
182
  // A socket host installs the SIGUSR1 drain below, so it can be handed off to a newer
@@ -188,7 +190,16 @@ async function runSocketHost(options, socketPath) {
188
190
  // under it would drop its socket and read as a crash to the supervisor.
189
191
  // While DRAINING the opposite is true: the successor generation owns the socket, so a
190
192
  // sessionless connection must not hold this host open.
191
- { onEmptyExit: () => void shutdown(0), canExitWhenEmpty: () => draining || connections.size === 0 });
193
+ {
194
+ onEmptyExit: () => void shutdown(0),
195
+ canExitWhenEmpty: () => draining || connections.size === 0,
196
+ onHandoffParked: async (ids) => {
197
+ await Promise.all(ids.map(async (id) => {
198
+ await writer.flushConnection(id);
199
+ connections.get(id)?.close();
200
+ }));
201
+ },
202
+ });
192
203
  const observers = startHostObservers(router, writer, {
193
204
  // The shape #1893 measured: gigabytes resident with `sessions.total 0`. Say it once, and when
194
205
  // this generation no longer owns the endpoint, leave - nobody can reach it to ask.
@@ -225,6 +236,10 @@ async function runSocketHost(options, socketPath) {
225
236
  let supervisorPublicIdentity;
226
237
  const server = createServer((socket) => {
227
238
  const accept = () => {
239
+ if (draining || shuttingDown) {
240
+ socket.destroy();
241
+ return;
242
+ }
228
243
  const id = `socket-${++nextConnection}`;
229
244
  const sink = socketSink(socket);
230
245
  writer.registerConnection(id, sink);
@@ -321,17 +336,35 @@ async function runSocketHost(options, socketPath) {
321
336
  }
322
337
  };
323
338
  /**
324
- * Drain for a generation handoff: keep serving every attached client and every running turn,
325
- * park each session as it settles, and exit once none is left. The successor already owns the
326
- * public socket by the time this signal arrives, so nothing new can reach this host.
339
+ * Announce through the record writer, never inside the supervisor's raw byte proxy. This
340
+ * preserves JSONL framing and FIFO before parking, including when a record spans proxy reads.
341
+ * Active turns/requests keep running; durable wake-source holds resume on reopen.
327
342
  */
328
343
  const drainForHandoff = () => {
329
- if (draining || shuttingDown)
344
+ if (shuttingDown)
345
+ return;
346
+ if (draining) {
347
+ if (handoffAnnounced)
348
+ router.beginDrain();
330
349
  return;
350
+ }
331
351
  draining = true;
332
352
  crashCleanupPaths.length = 0;
333
353
  hostLog("draining for a generation handoff");
334
- router.beginDrain();
354
+ void endpointSuperseded()
355
+ .then((superseded) => {
356
+ writer.broadcastHostRecord({
357
+ type: "host_superseded",
358
+ instanceId: hostInstanceId(),
359
+ generation: hostGeneration(process.env),
360
+ successor: superseded ? { socket: supervisorPublicSocketPath ?? socketPath } : null,
361
+ });
362
+ handoffAnnounced = true;
363
+ router.beginDrain();
364
+ })
365
+ .catch((cause) => {
366
+ hostLog(`handoff announcement failed: ${String(cause)}`);
367
+ });
335
368
  };
336
369
  /**
337
370
  * Whether the endpoint this host serves is held by another socket entry now. A supervised host