@code-yeongyu/senpi 2026.9.12-3 → 2026.9.13-2

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 (270) hide show
  1. package/CHANGELOG.md +63 -0
  2. package/README.md +3 -1
  3. package/dist/bun/cli.js +2 -3
  4. package/dist/bun/cli.js.map +1 -1
  5. package/dist/bun/runtime-modules.d.ts +3 -0
  6. package/dist/bun/runtime-modules.d.ts.map +1 -0
  7. package/dist/bun/runtime-modules.js +17 -0
  8. package/dist/bun/runtime-modules.js.map +1 -0
  9. package/dist/bun/runtime-setup.js +2 -5
  10. package/dist/bun/runtime-setup.js.map +1 -1
  11. package/dist/core/agent-session.d.ts +2 -2
  12. package/dist/core/agent-session.d.ts.map +1 -1
  13. package/dist/core/agent-session.js +38 -30
  14. package/dist/core/agent-session.js.map +1 -1
  15. package/dist/core/discovered-resource-scope.d.ts +23 -0
  16. package/dist/core/discovered-resource-scope.d.ts.map +1 -0
  17. package/dist/core/discovered-resource-scope.js +44 -0
  18. package/dist/core/discovered-resource-scope.js.map +1 -0
  19. package/dist/core/extensions/builtin/ask-user/notify.d.ts +24 -0
  20. package/dist/core/extensions/builtin/ask-user/notify.d.ts.map +1 -0
  21. package/dist/core/extensions/builtin/ask-user/notify.js +11 -0
  22. package/dist/core/extensions/builtin/ask-user/notify.js.map +1 -0
  23. package/dist/core/extensions/builtin/ask-user/registry.d.ts +2 -0
  24. package/dist/core/extensions/builtin/ask-user/registry.d.ts.map +1 -1
  25. package/dist/core/extensions/builtin/ask-user/registry.js.map +1 -1
  26. package/dist/core/extensions/builtin/ask-user/resume.d.ts +1 -1
  27. package/dist/core/extensions/builtin/ask-user/resume.d.ts.map +1 -1
  28. package/dist/core/extensions/builtin/ask-user/resume.js +10 -20
  29. package/dist/core/extensions/builtin/ask-user/resume.js.map +1 -1
  30. package/dist/core/extensions/builtin/ask-user/tool.d.ts +5 -2
  31. package/dist/core/extensions/builtin/ask-user/tool.d.ts.map +1 -1
  32. package/dist/core/extensions/builtin/ask-user/tool.js +41 -6
  33. package/dist/core/extensions/builtin/ask-user/tool.js.map +1 -1
  34. package/dist/core/extensions/builtin/goal/channel-state-subscriptions.d.ts +2 -1
  35. package/dist/core/extensions/builtin/goal/channel-state-subscriptions.d.ts.map +1 -1
  36. package/dist/core/extensions/builtin/goal/channel-state-subscriptions.js +1 -1
  37. package/dist/core/extensions/builtin/goal/channel-state-subscriptions.js.map +1 -1
  38. package/dist/core/extensions/builtin/goal/monitor-continuation.d.ts.map +1 -1
  39. package/dist/core/extensions/builtin/goal/monitor-continuation.js +27 -13
  40. package/dist/core/extensions/builtin/goal/monitor-continuation.js.map +1 -1
  41. package/dist/core/extensions/builtin/hooks/config-loader.d.ts +2 -0
  42. package/dist/core/extensions/builtin/hooks/config-loader.d.ts.map +1 -1
  43. package/dist/core/extensions/builtin/hooks/config-loader.js +27 -0
  44. package/dist/core/extensions/builtin/hooks/config-loader.js.map +1 -1
  45. package/dist/core/extensions/builtin/hooks/dispatcher.js +1 -0
  46. package/dist/core/extensions/builtin/hooks/dispatcher.js.map +1 -1
  47. package/dist/core/extensions/builtin/hooks/index.d.ts.map +1 -1
  48. package/dist/core/extensions/builtin/hooks/index.js +51 -2
  49. package/dist/core/extensions/builtin/hooks/index.js.map +1 -1
  50. package/dist/core/extensions/builtin/hooks/lifecycle-adapter.d.ts +18 -1
  51. package/dist/core/extensions/builtin/hooks/lifecycle-adapter.d.ts.map +1 -1
  52. package/dist/core/extensions/builtin/hooks/lifecycle-adapter.js +36 -1
  53. package/dist/core/extensions/builtin/hooks/lifecycle-adapter.js.map +1 -1
  54. package/dist/core/extensions/builtin/hooks/matcher.js +1 -0
  55. package/dist/core/extensions/builtin/hooks/matcher.js.map +1 -1
  56. package/dist/core/extensions/builtin/hooks/output-parser.js +6 -0
  57. package/dist/core/extensions/builtin/hooks/output-parser.js.map +1 -1
  58. package/dist/core/extensions/builtin/hooks/trust-storage.d.ts +2 -0
  59. package/dist/core/extensions/builtin/hooks/trust-storage.d.ts.map +1 -1
  60. package/dist/core/extensions/builtin/hooks/trust-storage.js +13 -0
  61. package/dist/core/extensions/builtin/hooks/trust-storage.js.map +1 -1
  62. package/dist/core/extensions/builtin/hooks/types.d.ts +14 -2
  63. package/dist/core/extensions/builtin/hooks/types.d.ts.map +1 -1
  64. package/dist/core/extensions/builtin/hooks/types.js +1 -1
  65. package/dist/core/extensions/builtin/hooks/types.js.map +1 -1
  66. package/dist/core/extensions/builtin/monitor-state-event.d.ts +1 -0
  67. package/dist/core/extensions/builtin/monitor-state-event.d.ts.map +1 -1
  68. package/dist/core/extensions/builtin/monitor-state-event.js.map +1 -1
  69. package/dist/core/extensions/builtin/terminal/tools/bash.d.ts +1 -0
  70. package/dist/core/extensions/builtin/terminal/tools/bash.d.ts.map +1 -1
  71. package/dist/core/extensions/builtin/terminal/tools/bash.js +13 -2
  72. package/dist/core/extensions/builtin/terminal/tools/bash.js.map +1 -1
  73. package/dist/core/extensions/loader.d.ts.map +1 -1
  74. package/dist/core/extensions/loader.js +5 -1
  75. package/dist/core/extensions/loader.js.map +1 -1
  76. package/dist/core/extensions/runner.d.ts +5 -16
  77. package/dist/core/extensions/runner.d.ts.map +1 -1
  78. package/dist/core/extensions/runner.js +16 -5
  79. package/dist/core/extensions/runner.js.map +1 -1
  80. package/dist/core/extensions/types.d.ts +28 -5
  81. package/dist/core/extensions/types.d.ts.map +1 -1
  82. package/dist/core/extensions/types.js.map +1 -1
  83. package/dist/core/extensions/wrapper.d.ts +8 -3
  84. package/dist/core/extensions/wrapper.d.ts.map +1 -1
  85. package/dist/core/extensions/wrapper.js +12 -6
  86. package/dist/core/extensions/wrapper.js.map +1 -1
  87. package/dist/core/keybindings.d.ts +8 -1
  88. package/dist/core/keybindings.d.ts.map +1 -1
  89. package/dist/core/keybindings.js +7 -1
  90. package/dist/core/keybindings.js.map +1 -1
  91. package/dist/core/package-manager.d.ts +4 -2
  92. package/dist/core/package-manager.d.ts.map +1 -1
  93. package/dist/core/package-manager.js +7 -2
  94. package/dist/core/package-manager.js.map +1 -1
  95. package/dist/core/pi-manifest.d.ts +2 -0
  96. package/dist/core/pi-manifest.d.ts.map +1 -1
  97. package/dist/core/pi-manifest.js +3 -0
  98. package/dist/core/pi-manifest.js.map +1 -1
  99. package/dist/core/resource-loader.d.ts +9 -0
  100. package/dist/core/resource-loader.d.ts.map +1 -1
  101. package/dist/core/resource-loader.js +69 -21
  102. package/dist/core/resource-loader.js.map +1 -1
  103. package/dist/core/settings-manager.d.ts +1 -0
  104. package/dist/core/settings-manager.d.ts.map +1 -1
  105. package/dist/core/settings-manager.js +1 -0
  106. package/dist/core/settings-manager.js.map +1 -1
  107. package/dist/core/settings-shapes.d.ts +1 -0
  108. package/dist/core/settings-shapes.d.ts.map +1 -1
  109. package/dist/core/settings-shapes.js.map +1 -1
  110. package/dist/core/source-info.d.ts +5 -1
  111. package/dist/core/source-info.d.ts.map +1 -1
  112. package/dist/core/source-info.js.map +1 -1
  113. package/dist/core/tools/bash.d.ts.map +1 -1
  114. package/dist/core/tools/bash.js +5 -0
  115. package/dist/core/tools/bash.js.map +1 -1
  116. package/dist/modes/app-server/server/skills.d.ts.map +1 -1
  117. package/dist/modes/app-server/server/skills.js +1 -0
  118. package/dist/modes/app-server/server/skills.js.map +1 -1
  119. package/dist/modes/interactive/components/ask-user-answer-chip.d.ts +17 -0
  120. package/dist/modes/interactive/components/ask-user-answer-chip.d.ts.map +1 -0
  121. package/dist/modes/interactive/components/ask-user-answer-chip.js +86 -0
  122. package/dist/modes/interactive/components/ask-user-answer-chip.js.map +1 -0
  123. package/dist/modes/interactive/components/ask-user-answer-key.d.ts +3 -1
  124. package/dist/modes/interactive/components/ask-user-answer-key.d.ts.map +1 -1
  125. package/dist/modes/interactive/components/ask-user-answer-key.js +11 -1
  126. package/dist/modes/interactive/components/ask-user-answer-key.js.map +1 -1
  127. package/dist/modes/interactive/components/ask-user-async-widget.d.ts +5 -2
  128. package/dist/modes/interactive/components/ask-user-async-widget.d.ts.map +1 -1
  129. package/dist/modes/interactive/components/ask-user-async-widget.js +18 -12
  130. package/dist/modes/interactive/components/ask-user-async-widget.js.map +1 -1
  131. package/dist/modes/interactive/components/ask-user-countdown.d.ts +8 -0
  132. package/dist/modes/interactive/components/ask-user-countdown.d.ts.map +1 -0
  133. package/dist/modes/interactive/components/ask-user-countdown.js +23 -0
  134. package/dist/modes/interactive/components/ask-user-countdown.js.map +1 -0
  135. package/dist/modes/interactive/components/ask-user-question-keys.d.ts.map +1 -1
  136. package/dist/modes/interactive/components/ask-user-question-keys.js +85 -17
  137. package/dist/modes/interactive/components/ask-user-question-keys.js.map +1 -1
  138. package/dist/modes/interactive/components/ask-user-question-render.d.ts.map +1 -1
  139. package/dist/modes/interactive/components/ask-user-question-render.js +22 -7
  140. package/dist/modes/interactive/components/ask-user-question-render.js.map +1 -1
  141. package/dist/modes/interactive/components/ask-user-question-state.d.ts +15 -0
  142. package/dist/modes/interactive/components/ask-user-question-state.d.ts.map +1 -1
  143. package/dist/modes/interactive/components/ask-user-question-state.js +57 -13
  144. package/dist/modes/interactive/components/ask-user-question-state.js.map +1 -1
  145. package/dist/modes/interactive/components/ask-user-question.d.ts +8 -2
  146. package/dist/modes/interactive/components/ask-user-question.d.ts.map +1 -1
  147. package/dist/modes/interactive/components/ask-user-question.js +16 -8
  148. package/dist/modes/interactive/components/ask-user-question.js.map +1 -1
  149. package/dist/modes/interactive/components/config-selector.d.ts +2 -1
  150. package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
  151. package/dist/modes/interactive/components/config-selector.js.map +1 -1
  152. package/dist/modes/interactive/components/custom-editor.d.ts +2 -0
  153. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
  154. package/dist/modes/interactive/components/custom-editor.js +10 -1
  155. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  156. package/dist/modes/interactive/components/loaded-resource-section.d.ts +14 -0
  157. package/dist/modes/interactive/components/loaded-resource-section.d.ts.map +1 -0
  158. package/dist/modes/interactive/components/loaded-resource-section.js +25 -0
  159. package/dist/modes/interactive/components/loaded-resource-section.js.map +1 -0
  160. package/dist/modes/interactive/components/user-message.d.ts +2 -1
  161. package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
  162. package/dist/modes/interactive/components/user-message.js +12 -2
  163. package/dist/modes/interactive/components/user-message.js.map +1 -1
  164. package/dist/modes/interactive/interactive-mode.d.ts +14 -11
  165. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  166. package/dist/modes/interactive/interactive-mode.js +263 -165
  167. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  168. package/dist/modes/interactive/loaded-resource-scopes.d.ts +28 -0
  169. package/dist/modes/interactive/loaded-resource-scopes.d.ts.map +1 -0
  170. package/dist/modes/interactive/loaded-resource-scopes.js +107 -0
  171. package/dist/modes/interactive/loaded-resource-scopes.js.map +1 -0
  172. package/dist/modes/interactive/tips/catalog/input-tips.d.ts +1 -1
  173. package/dist/modes/interactive/tips/catalog/input-tips.js +2 -2
  174. package/dist/modes/interactive/tips/catalog/input-tips.js.map +1 -1
  175. package/dist/modes/rpc/host-lifecycle.d.ts.map +1 -1
  176. package/dist/modes/rpc/host-lifecycle.js +7 -0
  177. package/dist/modes/rpc/host-lifecycle.js.map +1 -1
  178. package/dist/modes/rpc/session-worker.js +5 -0
  179. package/dist/modes/rpc/session-worker.js.map +1 -1
  180. package/docs/environment-variables.md +5 -1
  181. package/docs/extensions.md +43 -5
  182. package/docs/keybindings.md +5 -2
  183. package/docs/packages.md +17 -0
  184. package/docs/rpc.md +6 -3
  185. package/docs/settings.md +5 -1
  186. package/docs/tui.md +15 -3
  187. package/node_modules/@code-yeongyu/senpi-codemode/CHANGELOG.md +28 -0
  188. package/node_modules/@code-yeongyu/senpi-codemode/README.md +16 -4
  189. package/node_modules/@code-yeongyu/senpi-codemode/package.json +4 -4
  190. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/js/worker-core.js +2 -0
  191. package/node_modules/@code-yeongyu/senpi-codemode/src/kernels/session-env.ts +6 -0
  192. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/detached-cell-manager.ts +6 -1
  193. package/node_modules/@code-yeongyu/senpi-codemode/src/tool/run-eval-cell.ts +31 -12
  194. package/node_modules/@earendil-works/chord/package.json +1 -1
  195. package/node_modules/@earendil-works/pi-agent-core/dist/harness/messages.d.ts +1 -1
  196. package/node_modules/@earendil-works/pi-agent-core/dist/harness/messages.d.ts.map +1 -1
  197. package/node_modules/@earendil-works/pi-agent-core/dist/harness/messages.js +1 -1
  198. package/node_modules/@earendil-works/pi-agent-core/dist/harness/messages.js.map +1 -1
  199. package/node_modules/@earendil-works/pi-agent-core/package.json +4 -4
  200. package/node_modules/@earendil-works/pi-ai/dist/api/devin-agent.lazy.d.ts +2 -0
  201. package/node_modules/@earendil-works/pi-ai/dist/api/devin-agent.lazy.d.ts.map +1 -1
  202. package/node_modules/@earendil-works/pi-ai/dist/api/devin-agent.lazy.js +6 -1
  203. package/node_modules/@earendil-works/pi-ai/dist/api/devin-agent.lazy.js.map +1 -1
  204. package/node_modules/@earendil-works/pi-ai/dist/api/openai-codex-responses.d.ts.map +1 -1
  205. package/node_modules/@earendil-works/pi-ai/dist/api/openai-codex-responses.js +55 -17
  206. package/node_modules/@earendil-works/pi-ai/dist/api/openai-codex-responses.js.map +1 -1
  207. package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses-shared.d.ts.map +1 -1
  208. package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses-shared.js +2 -1
  209. package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses-shared.js.map +1 -1
  210. package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.d.ts +2 -1
  211. package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.d.ts.map +1 -1
  212. package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.js +9 -0
  213. package/node_modules/@earendil-works/pi-ai/dist/api/openai-responses.js.map +1 -1
  214. package/node_modules/@earendil-works/pi-ai/dist/api/responses-completion-grace.d.ts +30 -0
  215. package/node_modules/@earendil-works/pi-ai/dist/api/responses-completion-grace.d.ts.map +1 -0
  216. package/node_modules/@earendil-works/pi-ai/dist/api/responses-completion-grace.js +94 -0
  217. package/node_modules/@earendil-works/pi-ai/dist/api/responses-completion-grace.js.map +1 -0
  218. package/node_modules/@earendil-works/pi-ai/dist/api/websocket-liveness.d.ts +48 -0
  219. package/node_modules/@earendil-works/pi-ai/dist/api/websocket-liveness.d.ts.map +1 -0
  220. package/node_modules/@earendil-works/pi-ai/dist/api/websocket-liveness.js +104 -0
  221. package/node_modules/@earendil-works/pi-ai/dist/api/websocket-liveness.js.map +1 -0
  222. package/node_modules/@earendil-works/pi-ai/dist/devin-provider.d.ts +6 -0
  223. package/node_modules/@earendil-works/pi-ai/dist/devin-provider.d.ts.map +1 -0
  224. package/node_modules/@earendil-works/pi-ai/dist/devin-provider.js +4 -0
  225. package/node_modules/@earendil-works/pi-ai/dist/devin-provider.js.map +1 -0
  226. package/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  227. package/node_modules/@earendil-works/pi-ai/dist/providers/data/nvidia.json +1 -1
  228. package/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  229. package/node_modules/@earendil-works/pi-ai/dist/providers/data/together.json +1 -1
  230. package/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  231. package/node_modules/@earendil-works/pi-ai/dist/utils/retry.d.ts.map +1 -1
  232. package/node_modules/@earendil-works/pi-ai/dist/utils/retry.js +7 -3
  233. package/node_modules/@earendil-works/pi-ai/dist/utils/retry.js.map +1 -1
  234. package/node_modules/@earendil-works/pi-ai/package.json +10 -2
  235. package/node_modules/@earendil-works/pi-pty/package.json +1 -1
  236. package/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  237. package/node_modules/@earendil-works/pi-tui/README.md +11 -3
  238. package/node_modules/@earendil-works/pi-tui/dist/index.d.ts +2 -1
  239. package/node_modules/@earendil-works/pi-tui/dist/index.d.ts.map +1 -1
  240. package/node_modules/@earendil-works/pi-tui/dist/index.js +1 -0
  241. package/node_modules/@earendil-works/pi-tui/dist/index.js.map +1 -1
  242. package/node_modules/@earendil-works/pi-tui/dist/mouse-input.d.ts +37 -0
  243. package/node_modules/@earendil-works/pi-tui/dist/mouse-input.d.ts.map +1 -0
  244. package/node_modules/@earendil-works/pi-tui/dist/mouse-input.js +97 -0
  245. package/node_modules/@earendil-works/pi-tui/dist/mouse-input.js.map +1 -0
  246. package/node_modules/@earendil-works/pi-tui/dist/stdin-buffer.d.ts +2 -0
  247. package/node_modules/@earendil-works/pi-tui/dist/stdin-buffer.d.ts.map +1 -1
  248. package/node_modules/@earendil-works/pi-tui/dist/stdin-buffer.js +38 -0
  249. package/node_modules/@earendil-works/pi-tui/dist/stdin-buffer.js.map +1 -1
  250. package/node_modules/@earendil-works/pi-tui/dist/terminal.d.ts +25 -1
  251. package/node_modules/@earendil-works/pi-tui/dist/terminal.d.ts.map +1 -1
  252. package/node_modules/@earendil-works/pi-tui/dist/terminal.js +110 -4
  253. package/node_modules/@earendil-works/pi-tui/dist/terminal.js.map +1 -1
  254. package/node_modules/@earendil-works/pi-tui/dist/tui-alt-screen.d.ts.map +1 -1
  255. package/node_modules/@earendil-works/pi-tui/dist/tui-alt-screen.js +5 -50
  256. package/node_modules/@earendil-works/pi-tui/dist/tui-alt-screen.js.map +1 -1
  257. package/node_modules/@earendil-works/pi-tui/dist/tui-main-screen.d.ts +12 -0
  258. package/node_modules/@earendil-works/pi-tui/dist/tui-main-screen.d.ts.map +1 -1
  259. package/node_modules/@earendil-works/pi-tui/dist/tui-main-screen.js +129 -3
  260. package/node_modules/@earendil-works/pi-tui/dist/tui-main-screen.js.map +1 -1
  261. package/node_modules/@earendil-works/pi-tui/dist/tui.d.ts +28 -0
  262. package/node_modules/@earendil-works/pi-tui/dist/tui.d.ts.map +1 -1
  263. package/node_modules/@earendil-works/pi-tui/dist/tui.js +160 -0
  264. package/node_modules/@earendil-works/pi-tui/dist/tui.js.map +1 -1
  265. package/node_modules/@earendil-works/pi-tui/package.json +1 -1
  266. package/package.json +13 -9
  267. package/dist/bun/register-cursor-agent.d.ts +0 -2
  268. package/dist/bun/register-cursor-agent.d.ts.map +0 -1
  269. package/dist/bun/register-cursor-agent.js +0 -4
  270. package/dist/bun/register-cursor-agent.js.map +0 -1
@@ -0,0 +1,28 @@
1
+ import type { SourceInfo, SourceScope } from "../../core/source-info.ts";
2
+ export type ResourceScopeGroup = "project" | "user" | "path" | "system";
3
+ export interface ScopedResource {
4
+ readonly path: string;
5
+ readonly sourceInfo?: SourceInfo;
6
+ }
7
+ export interface ResourceScopeGroups {
8
+ readonly scope: ResourceScopeGroup;
9
+ readonly paths: ScopedResource[];
10
+ readonly packages: Map<string, ScopedResource[]>;
11
+ }
12
+ export interface ResourceScopeGroupFormat {
13
+ readonly formatPath: (item: ScopedResource) => string;
14
+ readonly formatPackagePath: (item: ScopedResource, source: string) => string;
15
+ }
16
+ export interface DisplaySourceInfo {
17
+ readonly label: string;
18
+ readonly scopeLabel?: string;
19
+ readonly color: "accent" | "muted";
20
+ }
21
+ export declare function isSystemResource(sourceInfo?: SourceInfo): boolean;
22
+ export declare function isPackageSourceInfo(sourceInfo?: SourceInfo): boolean;
23
+ export declare function getResourceScopeGroup(sourceInfo?: SourceInfo): ResourceScopeGroup;
24
+ export declare function buildResourceScopeGroups(items: readonly ScopedResource[]): ResourceScopeGroups[];
25
+ export declare function formatResourceScopeGroups(groups: readonly ResourceScopeGroups[], options: ResourceScopeGroupFormat): string;
26
+ export declare function getScopeAutocompleteTag(scope: SourceScope): "u" | "p" | "t" | "s";
27
+ export declare function getDisplaySourceInfo(sourceInfo?: SourceInfo): DisplaySourceInfo;
28
+ //# sourceMappingURL=loaded-resource-scopes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loaded-resource-scopes.d.ts","sourceRoot":"","sources":["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AAyB,CACxC,MAAM,EAAE,SAAS,mBAAmB,EAAE,EACtC,OAAO,EAAE,wBAAwB,GAC/B,MAAM,CAsBR;AAED,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,WAAW,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,CAajF;AAED,wBAAgB,oBAAoB,CAAC,UAAU,CAAC,EAAE,UAAU,GAAG,iBAAiB,CA0B/E"}
@@ -0,0 +1,107 @@
1
+ import { theme } from "./theme/theme.js";
2
+ const GROUP_ORDER = ["project", "user", "path", "system"];
3
+ export function isSystemResource(sourceInfo) {
4
+ return sourceInfo?.scope === "system";
5
+ }
6
+ export function isPackageSourceInfo(sourceInfo) {
7
+ const source = sourceInfo?.source ?? "";
8
+ return source.startsWith("npm:") || source.startsWith("git:");
9
+ }
10
+ export function getResourceScopeGroup(sourceInfo) {
11
+ const source = sourceInfo?.source ?? "local";
12
+ const scope = sourceInfo?.scope ?? "project";
13
+ if (scope === "system")
14
+ return "system";
15
+ if (source === "cli")
16
+ return "path";
17
+ switch (scope) {
18
+ case "temporary":
19
+ return "path";
20
+ case "user":
21
+ return "user";
22
+ case "project":
23
+ return "project";
24
+ default:
25
+ return assertNever(scope);
26
+ }
27
+ }
28
+ export function buildResourceScopeGroups(items) {
29
+ const groups = new Map(GROUP_ORDER.map((scope) => [scope, { scope, paths: [], packages: new Map() }]));
30
+ for (const item of items) {
31
+ const group = groups.get(getResourceScopeGroup(item.sourceInfo));
32
+ if (group === undefined)
33
+ continue;
34
+ if (isPackageSourceInfo(item.sourceInfo)) {
35
+ const source = item.sourceInfo?.source ?? "local";
36
+ const list = group.packages.get(source) ?? [];
37
+ list.push(item);
38
+ group.packages.set(source, list);
39
+ }
40
+ else {
41
+ group.paths.push(item);
42
+ }
43
+ }
44
+ return GROUP_ORDER.map((scope) => groups.get(scope)).filter((group) => group !== undefined && (group.paths.length > 0 || group.packages.size > 0));
45
+ }
46
+ export function formatResourceScopeGroups(groups, options) {
47
+ const lines = [];
48
+ for (const group of groups) {
49
+ lines.push(` ${theme.fg("accent", group.scope)}`);
50
+ const sortedPaths = [...group.paths].sort((a, b) => a.path.localeCompare(b.path));
51
+ for (const item of sortedPaths) {
52
+ lines.push(theme.fg("dim", ` ${options.formatPath(item)}`));
53
+ }
54
+ const sortedPackages = Array.from(group.packages.entries()).sort(([a], [b]) => a.localeCompare(b));
55
+ for (const [source, items] of sortedPackages) {
56
+ lines.push(` ${theme.fg("mdLink", source)}`);
57
+ const sortedPackagePaths = [...items].sort((a, b) => a.path.localeCompare(b.path));
58
+ for (const item of sortedPackagePaths) {
59
+ lines.push(theme.fg("dim", ` ${options.formatPackagePath(item, source)}`));
60
+ }
61
+ }
62
+ }
63
+ return lines.join("\n");
64
+ }
65
+ export function getScopeAutocompleteTag(scope) {
66
+ switch (scope) {
67
+ case "user":
68
+ return "u";
69
+ case "project":
70
+ return "p";
71
+ case "temporary":
72
+ return "t";
73
+ case "system":
74
+ return "s";
75
+ default:
76
+ return assertNever(scope);
77
+ }
78
+ }
79
+ export function getDisplaySourceInfo(sourceInfo) {
80
+ const source = sourceInfo?.source ?? "local";
81
+ const scope = sourceInfo?.scope ?? "project";
82
+ if (scope === "system") {
83
+ return { label: "system", color: "muted" };
84
+ }
85
+ if (source === "local") {
86
+ if (scope === "user") {
87
+ return { label: "user", color: "muted" };
88
+ }
89
+ if (scope === "project") {
90
+ return { label: "project", color: "muted" };
91
+ }
92
+ return { label: "path", scopeLabel: "temp", color: "muted" };
93
+ }
94
+ if (source === "cli") {
95
+ return {
96
+ label: "path",
97
+ scopeLabel: scope === "temporary" ? "temp" : undefined,
98
+ color: "muted",
99
+ };
100
+ }
101
+ const scopeLabel = scope === "user" ? "user" : scope === "project" ? "project" : "temp";
102
+ return { label: source, scopeLabel, color: "accent" };
103
+ }
104
+ function assertNever(value) {
105
+ throw new Error(`Unexpected resource scope: ${String(value)}`);
106
+ }
107
+ //# sourceMappingURL=loaded-resource-scopes.js.map
@@ -0,0 +1 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,SAAS;YACtD,KAAK,EAAE,OAAO;SACd,CAAC;IACH,CAAC;IAED,MAAM,UAAU,GAAG,KAAK,KAAK,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC;IACxF,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,UAAU,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC;AACvD,CAAC;AAED,SAAS,WAAW,CAAC,KAAY;IAChC,MAAM,IAAI,KAAK,CAAC,8BAA8B,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;AAChE,CAAC","sourcesContent":["import type { SourceInfo, SourceScope } from \"../../core/source-info.ts\";\nimport { theme } from \"./theme/theme.ts\";\n\nexport type ResourceScopeGroup = \"project\" | \"user\" | \"path\" | \"system\";\n\nexport interface ScopedResource {\n\treadonly path: string;\n\treadonly sourceInfo?: SourceInfo;\n}\n\nexport interface ResourceScopeGroups {\n\treadonly scope: ResourceScopeGroup;\n\treadonly paths: ScopedResource[];\n\treadonly packages: Map<string, ScopedResource[]>;\n}\n\nexport interface ResourceScopeGroupFormat {\n\treadonly formatPath: (item: ScopedResource) => string;\n\treadonly formatPackagePath: (item: ScopedResource, source: string) => string;\n}\n\nexport interface DisplaySourceInfo {\n\treadonly label: string;\n\treadonly scopeLabel?: string;\n\treadonly color: \"accent\" | \"muted\";\n}\n\nconst GROUP_ORDER: readonly ResourceScopeGroup[] = [\"project\", \"user\", \"path\", \"system\"];\n\nexport function isSystemResource(sourceInfo?: SourceInfo): boolean {\n\treturn sourceInfo?.scope === \"system\";\n}\n\nexport function isPackageSourceInfo(sourceInfo?: SourceInfo): boolean {\n\tconst source = sourceInfo?.source ?? \"\";\n\treturn source.startsWith(\"npm:\") || source.startsWith(\"git:\");\n}\n\nexport function getResourceScopeGroup(sourceInfo?: SourceInfo): ResourceScopeGroup {\n\tconst source = sourceInfo?.source ?? \"local\";\n\tconst scope = sourceInfo?.scope ?? \"project\";\n\tif (scope === \"system\") return \"system\";\n\tif (source === \"cli\") return \"path\";\n\tswitch (scope) {\n\t\tcase \"temporary\":\n\t\t\treturn \"path\";\n\t\tcase \"user\":\n\t\t\treturn \"user\";\n\t\tcase \"project\":\n\t\t\treturn \"project\";\n\t\tdefault:\n\t\t\treturn assertNever(scope);\n\t}\n}\n\nexport function buildResourceScopeGroups(items: readonly ScopedResource[]): ResourceScopeGroups[] {\n\tconst groups = new Map<ResourceScopeGroup, ResourceScopeGroups>(\n\t\tGROUP_ORDER.map((scope) => [scope, { scope, paths: [], packages: new Map() }]),\n\t);\n\n\tfor (const item of items) {\n\t\tconst group = groups.get(getResourceScopeGroup(item.sourceInfo));\n\t\tif (group === undefined) continue;\n\t\tif (isPackageSourceInfo(item.sourceInfo)) {\n\t\t\tconst source = item.sourceInfo?.source ?? \"local\";\n\t\t\tconst list = group.packages.get(source) ?? [];\n\t\t\tlist.push(item);\n\t\t\tgroup.packages.set(source, list);\n\t\t} else {\n\t\t\tgroup.paths.push(item);\n\t\t}\n\t}\n\n\treturn GROUP_ORDER.map((scope) => groups.get(scope)).filter(\n\t\t(group): group is ResourceScopeGroups =>\n\t\t\tgroup !== undefined && (group.paths.length > 0 || group.packages.size > 0),\n\t);\n}\n\nexport function formatResourceScopeGroups(\n\tgroups: readonly ResourceScopeGroups[],\n\toptions: ResourceScopeGroupFormat,\n): string {\n\tconst lines: string[] = [];\n\n\tfor (const group of groups) {\n\t\tlines.push(` ${theme.fg(\"accent\", group.scope)}`);\n\n\t\tconst sortedPaths = [...group.paths].sort((a, b) => a.path.localeCompare(b.path));\n\t\tfor (const item of sortedPaths) {\n\t\t\tlines.push(theme.fg(\"dim\", ` ${options.formatPath(item)}`));\n\t\t}\n\n\t\tconst sortedPackages = Array.from(group.packages.entries()).sort(([a], [b]) => a.localeCompare(b));\n\t\tfor (const [source, items] of sortedPackages) {\n\t\t\tlines.push(` ${theme.fg(\"mdLink\", source)}`);\n\t\t\tconst sortedPackagePaths = [...items].sort((a, b) => a.path.localeCompare(b.path));\n\t\t\tfor (const item of sortedPackagePaths) {\n\t\t\t\tlines.push(theme.fg(\"dim\", ` ${options.formatPackagePath(item, source)}`));\n\t\t\t}\n\t\t}\n\t}\n\n\treturn lines.join(\"\\n\");\n}\n\nexport function getScopeAutocompleteTag(scope: SourceScope): \"u\" | \"p\" | \"t\" | \"s\" {\n\tswitch (scope) {\n\t\tcase \"user\":\n\t\t\treturn \"u\";\n\t\tcase \"project\":\n\t\t\treturn \"p\";\n\t\tcase \"temporary\":\n\t\t\treturn \"t\";\n\t\tcase \"system\":\n\t\t\treturn \"s\";\n\t\tdefault:\n\t\t\treturn assertNever(scope);\n\t}\n}\n\nexport function getDisplaySourceInfo(sourceInfo?: SourceInfo): DisplaySourceInfo {\n\tconst source = sourceInfo?.source ?? \"local\";\n\tconst scope = sourceInfo?.scope ?? \"project\";\n\tif (scope === \"system\") {\n\t\treturn { label: \"system\", color: \"muted\" };\n\t}\n\tif (source === \"local\") {\n\t\tif (scope === \"user\") {\n\t\t\treturn { label: \"user\", color: \"muted\" };\n\t\t}\n\t\tif (scope === \"project\") {\n\t\t\treturn { label: \"project\", color: \"muted\" };\n\t\t}\n\t\treturn { label: \"path\", scopeLabel: \"temp\", color: \"muted\" };\n\t}\n\n\tif (source === \"cli\") {\n\t\treturn {\n\t\t\tlabel: \"path\",\n\t\t\tscopeLabel: scope === \"temporary\" ? \"temp\" : undefined,\n\t\t\tcolor: \"muted\",\n\t\t};\n\t}\n\n\tconst scopeLabel = scope === \"user\" ? \"user\" : scope === \"project\" ? \"project\" : \"temp\";\n\treturn { label: source, scopeLabel, color: \"accent\" };\n}\n\nfunction assertNever(value: never): never {\n\tthrow new Error(`Unexpected resource scope: ${String(value)}`);\n}\n"]}
@@ -56,7 +56,7 @@ export declare const INPUT_TIPS: ({
56
56
  } | {
57
57
  requiresCommand?: undefined;
58
58
  id: string;
59
- bindings: "app.question.answer"[];
59
+ bindings: ("app.question.answer" | "app.question.next")[];
60
60
  render: (keys: (binding: import("@earendil-works/pi-tui").Keybinding) => string) => string;
61
61
  })[];
62
62
  //# sourceMappingURL=input-tips.d.ts.map
@@ -87,8 +87,8 @@ export const INPUT_TIPS = [
87
87
  },
88
88
  {
89
89
  id: "open-pending-question",
90
- bindings: ["app.question.answer"],
91
- render: (keys) => `A question parked above the editor while the agent works shows what it asks; open it with Enter on an empty editor, /answer, or ${keys("app.question.answer")}.`,
90
+ bindings: ["app.question.answer", "app.question.next"],
91
+ render: (keys) => `Pending questions queue above the editor. An empty-composer digit selects an option; ${keys("app.question.answer")} opens the shown request and ${keys("app.question.next")} cycles requests. /answer lists them.`,
92
92
  },
93
93
  ];
94
94
  //# sourceMappingURL=input-tips.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"input-tips.js","sourceRoot":"","sources":["../../../../../src/modes/interactive/tips/catalog/input-tips.ts"],"names":[],"mappings":"AAEA,MAAM,CAAC,MAAM,UAAU,GAAG;IACzB;QACC,EAAE,EAAE,iBAAiB;QACrB,QAAQ,EAAE,CAAC,sBAAsB,CAAC;QAClC,MAAM,EAAE,CAAC,IAAI,EAAE,EAAE,CAChB,mCAAmC,IAAI,CAAC,sBAAsB,CAAC,8CAA8C;KAC9G;IACD;QACC,EAAE,EAAE,kBAAkB;QACtB,QAAQ,EAAE,CAAC,kBAAkB,EAAE,sBAAsB,CAAC;QACtD,MAAM,EAAE,CAAC,IAAI,EAAE,EAAE,CAChB,SAAS,IAAI,CAAC,kBAAkB,CAAC,oEAAoE,IAAI,CAAC,sBAAsB,CAAC,gCAAgC;KAClK;IACD;QACC,EAAE,EAAE,qBAAqB;QACzB,QAAQ,EAAE,CAAC,qBAAqB,CAAC;QACjC,MAAM,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,OAAO,IAAI,CAAC,qBAAqB,CAAC,6CAA6C;KACjG;IACD;QACC,EAAE,EAAE,0BAA0B;QAC9B,QAAQ,EAAE,CAAC,e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AC;QACtC,MAAM,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,0CAA0C,IAAI,CAAC,0BAA0B,CAAC,GAAG;KAC/F;IACD;QACC,EAAE,EAAE,cAAc;QAClB,QAAQ,EAAE,CAAC,kBAAkB,CAAC;QAC9B,MAAM,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,0CAA0C,IAAI,CAAC,kBAAkB,CAAC,GAAG;KACvF;IACD;QACC,EAAE,EAAE,eAAe;QACnB,QAAQ,EAAE,CAAC,mBAAmB,CAAC;QAC/B,MAAM,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,yCAAyC,IAAI,CAAC,mBAAmB,CAAC,GAAG;KACvF;IACD;QACC,EAAE,EAAE,eAAe;QACnB,QAAQ,EAAE,EAAE;QACZ,MAAM,EAAE,GAAG,EAAE,CAAC,mGAAmG;KACjH;IACD;QACC,EAAE,EAAE,iBAAiB;QACrB,QAAQ,EAAE,EAAE;QACZ,MAAM,EAAE,GAAG,EAAE,CAAC,0EAA0E;KACxF;IACD;QACC,EAAE,EAAE,uBAAuB;QAC3B,QAAQ,EAAE,EAAE;QACZ,MAAM,EAAE,GAAG,EAAE,CACZ,oNAAoN;KACrN;IACD;QACC,EAAE,EAAE,uBAAuB;QAC3B,QAAQ,EAAE,CAAC,qBAAqB,CAAC;QACjC,MAAM,EAAE,CAAC,IAAI,EAAE,EAAE,CAChB,mIAAmI,IAAI,CAAC,qBAAqB,CAAC,GAAG;KAClK;CACkC,CAAC","sourcesContent":["import type { TipDefinition } from \"./types.ts\";\n\nexport const INPUT_TIPS = [\n\t{\n\t\tid: \"queue-follow-up\",\n\t\tbindings: [\"app.message.followUp\"],\n\t\trender: (keys) =>\n\t\t\t`While the agent is working, use ${keys(\"app.message.followUp\")} to queue a follow-up for after it finishes.`,\n\t},\n\t{\n\t\tid: \"steering-message\",\n\t\tbindings: [\"tui.input.submit\", \"app.message.followUp\"],\n\t\trender: (keys) =>\n\t\t\t`Press ${keys(\"tui.input.submit\")} while the agent works to steer it after the current tool batch; ${keys(\"app.message.followUp\")} waits until all work is done.`,\n\t},\n\t{\n\t\tid: \"edit-queued-message\",\n\t\tbindings: [\"app.message.dequeue\"],\n\t\trender: (keys) => `Use ${keys(\"app.message.dequeue\")} to bring queued messages back for editing.`,\n\t},\n\t{\n\t\tid: \"interrupt-restores-queue\",\n\t\tbindings: [\"app.interrupt\"],\n\t\trender: (keys) =>\n\t\t\t`Press ${keys(\"app.interrupt\")} to abort the current turn and restore queued messages to the editor.`,\n\t},\n\t{\n\t\tid: \"file-reference\",\n\t\tbindings: [],\n\t\trender: () => \"Type @ in the editor to fuzzy-search project files and insert their paths.\",\n\t},\n\t{\n\t\tid: \"path-completion\",\n\t\tbindings: [\"tui.input.tab\"],\n\t\trender: (keys) => `Press ${keys(\"tui.input.tab\")} to complete file paths while typing.`,\n\t},\n\t{\n\t\tid: \"shortcut-overlay\",\n\t\tbindings: [],\n\t\trender: () => \"Type ? in an empty editor to pop up the full shortcut grid.\",\n\t},\n\t{\n\t\tid: \"prompt-history\",\n\t\tbindings: [\"app.history.search\"],\n\t\trequiresCommand: \"history\",\n\t\trender: (keys) => `Search prompt history across sessions with ${keys(\"app.history.search\")}.`,\n\t},\n\t{\n\t\tid: \"external-editor\",\n\t\tbindings: [\"app.editor.external\"],\n\t\trender: (keys) => `Open the current prompt in your external editor with ${keys(\"app.editor.external\")}.`,\n\t},\n\t{\n\t\tid: \"expand-tool-output\",\n\t\tbindings: [\"app.tools.expand\"],\n\t\trender: (keys) => `Collapse or expand tool output with ${keys(\"app.tools.expand\")}.`,\n\t},\n\t{\n\t\tid: \"thinking-blocks\",\n\t\tbindings: [\"app.thinking.toggle\"],\n\t\trender: (keys) => `Collapse or expand thinking blocks with ${keys(\"app.thinking.toggle\")}.`,\n\t},\n\t{\n\t\tid: \"paste-image\",\n\t\tbindings: [\"app.clipboard.pasteImage\"],\n\t\trender: (keys) => `Paste an image from the clipboard with ${keys(\"app.clipboard.pasteImage\")}.`,\n\t},\n\t{\n\t\tid: \"copy-message\",\n\t\tbindings: [\"app.message.copy\"],\n\t\trender: (keys) => `Copy the latest assistant message with ${keys(\"app.message.copy\")}.`,\n\t},\n\t{\n\t\tid: \"input-newline\",\n\t\tbindings: [\"tui.input.newLine\"],\n\t\trender: (keys) => `Insert a newline without sending with ${keys(\"tui.input.newLine\")}.`,\n\t},\n\t{\n\t\tid: \"bash-prefixes\",\n\t\tbindings: [],\n\t\trender: () => \"Prefix a prompt with ! to run bash, or !! to run bash without adding its output to model context.\",\n\t},\n\t{\n\t\tid: \"drag-drop-files\",\n\t\tbindings: [],\n\t\trender: () => \"Drag and drop files into the terminal to add their paths to your prompt.\",\n\t},\n\t{\n\t\tid: \"answer-agent-question\",\n\t\tbindings: [],\n\t\trender: () =>\n\t\t\t\"When the agent asks you a question, pick options with digits or arrows, press Enter to advance, and use the final Submit tab for a comment or partial answers; anything unanswered is reported back as unanswered.\",\n\t},\n\t{\n\t\tid: \"open-pending-question\",\n\t\tbindings: [\"app.question.answer\"],\n\t\trender: (keys) =>\n\t\t\t`A question parked above the editor while the agent works shows what it asks; open it with Enter on an empty editor, /answer, or ${keys(\"app.question.answer\")}.`,\n\t},\n] satisfies readonly TipDefinition[];\n"]}
1
+ {"version":3,"file":"input-tips.js","sourceRoot":"","sources":["../../../../../src/modes/interactive/tips/catalog/input-tips.ts"],"names":[],"mappings":"AAEA,MAAM,CAAC,MAAM,UAAU,GAAG;IACzB;QACC,EAAE,EAAE,iBAAiB;QACrB,QAAQ,EAAE,CAAC,sBAAsB,CAAC;QAClC,MAAM,EAAE,CAAC,IAAI,EAAE,EAAE,CAChB,mCAAmC,IAAI,CAAC,sBAAsB,CAAC,8CAA8C;KAC9G;IACD;QACC,EAAE,EAAE,kBAAkB;QACtB,QAAQ,EAAE,CAAC,kBAAkB,EAAE,sBAAsB,CAAC;QACtD,MAAM,EAAE,CAAC,IAAI,EAAE,EAAE,CAChB,SAAS,IAAI,CAAC,kBAAkB,CAAC,oEAA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C,CAAC","sourcesContent":["import type { TipDefinition } from \"./types.ts\";\n\nexport const INPUT_TIPS = [\n\t{\n\t\tid: \"queue-follow-up\",\n\t\tbindings: [\"app.message.followUp\"],\n\t\trender: (keys) =>\n\t\t\t`While the agent is working, use ${keys(\"app.message.followUp\")} to queue a follow-up for after it finishes.`,\n\t},\n\t{\n\t\tid: \"steering-message\",\n\t\tbindings: [\"tui.input.submit\", \"app.message.followUp\"],\n\t\trender: (keys) =>\n\t\t\t`Press ${keys(\"tui.input.submit\")} while the agent works to steer it after the current tool batch; ${keys(\"app.message.followUp\")} waits until all work is done.`,\n\t},\n\t{\n\t\tid: \"edit-queued-message\",\n\t\tbindings: [\"app.message.dequeue\"],\n\t\trender: (keys) => `Use ${keys(\"app.message.dequeue\")} to bring queued messages back for editing.`,\n\t},\n\t{\n\t\tid: \"interrupt-restores-queue\",\n\t\tbindings: [\"app.interrupt\"],\n\t\trender: (keys) =>\n\t\t\t`Press ${keys(\"app.interrupt\")} to abort the current turn and restore queued messages to the editor.`,\n\t},\n\t{\n\t\tid: \"file-reference\",\n\t\tbindings: [],\n\t\trender: () => \"Type @ in the editor to fuzzy-search project files and insert their paths.\",\n\t},\n\t{\n\t\tid: \"path-completion\",\n\t\tbindings: [\"tui.input.tab\"],\n\t\trender: (keys) => `Press ${keys(\"tui.input.tab\")} to complete file paths while typing.`,\n\t},\n\t{\n\t\tid: \"shortcut-overlay\",\n\t\tbindings: [],\n\t\trender: () => \"Type ? in an empty editor to pop up the full shortcut grid.\",\n\t},\n\t{\n\t\tid: \"prompt-history\",\n\t\tbindings: [\"app.history.search\"],\n\t\trequiresCommand: \"history\",\n\t\trender: (keys) => `Search prompt history across sessions with ${keys(\"app.history.search\")}.`,\n\t},\n\t{\n\t\tid: \"external-editor\",\n\t\tbindings: [\"app.editor.external\"],\n\t\trender: (keys) => `Open the current prompt in your external editor with ${keys(\"app.editor.external\")}.`,\n\t},\n\t{\n\t\tid: \"expand-tool-output\",\n\t\tbindings: [\"app.tools.expand\"],\n\t\trender: (keys) => `Collapse or expand tool output with ${keys(\"app.tools.expand\")}.`,\n\t},\n\t{\n\t\tid: \"thinking-blocks\",\n\t\tbindings: [\"app.thinking.toggle\"],\n\t\trender: (keys) => `Collapse or expand thinking blocks with ${keys(\"app.thinking.toggle\")}.`,\n\t},\n\t{\n\t\tid: \"paste-image\",\n\t\tbindings: [\"app.clipboard.pasteImage\"],\n\t\trender: (keys) => `Paste an image from the clipboard with ${keys(\"app.clipboard.pasteImage\")}.`,\n\t},\n\t{\n\t\tid: \"copy-message\",\n\t\tbindings: [\"app.message.copy\"],\n\t\trender: (keys) => `Copy the latest assistant message with ${keys(\"app.message.copy\")}.`,\n\t},\n\t{\n\t\tid: \"input-newline\",\n\t\tbindings: [\"tui.input.newLine\"],\n\t\trender: (keys) => `Insert a newline without sending with ${keys(\"tui.input.newLine\")}.`,\n\t},\n\t{\n\t\tid: \"bash-prefixes\",\n\t\tbindings: [],\n\t\trender: () => \"Prefix a prompt with ! to run bash, or !! to run bash without adding its output to model context.\",\n\t},\n\t{\n\t\tid: \"drag-drop-files\",\n\t\tbindings: [],\n\t\trender: () => \"Drag and drop files into the terminal to add their paths to your prompt.\",\n\t},\n\t{\n\t\tid: \"answer-agent-question\",\n\t\tbindings: [],\n\t\trender: () =>\n\t\t\t\"When the agent asks you a question, pick options with digits or arrows, press Enter to advance, and use the final Submit tab for a comment or partial answers; anything unanswered is reported back as unanswered.\",\n\t},\n\t{\n\t\tid: \"open-pending-question\",\n\t\tbindings: [\"app.question.answer\", \"app.question.next\"],\n\t\trender: (keys) =>\n\t\t\t`Pending questions queue above the editor. An empty-composer digit selects an option; ${keys(\"app.question.answer\")} opens the shown request and ${keys(\"app.question.next\")} cycles requests. /answer lists them.`,\n\t},\n] satisfies readonly TipDefinition[];\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"host-lifecycle.d.ts","sourceRoot":"","sources":["../../../src/modes/rpc/host-lifecycle.ts"],"names":[],"mappings":";AA4EA,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ret);
359
359
  clientSockets.add(client);
360
+ // A readiness exchange can begin and end between ticks. Record the
361
+ // attachment now, before a later tick can reuse the preceding idle window.
362
+ decider.update(currentActivity());
360
363
  const detach = () => {
361
364
  clientSockets.delete(client);
365
+ decider.update(currentActivity());
362
366
  internal.destroy();
363
367
  client.destroy();
364
368
  };
@@ -414,6 +418,9 @@ export async function runHostSupervisor(launch) {
414
418
  busySessions.set(sessionId, (busySessions.get(sessionId) ?? 0) + 1);
415
419
  else if (type === "agent_settled")
416
420
  busySessions.set(sessionId, Math.max(0, (busySessions.get(sessionId) ?? 1) - 1));
421
+ else
422
+ return;
423
+ decider.update(currentActivity());
417
424
  }
418
425
  async function shutdown(reason, exitCode) {
419
426
  // Single-flight: concurrent triggers (listener error, child exit, signals)
@@ -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,YAAY,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAClD,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,EAAE,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AACzF,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;AACzC,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC3D,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C;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 { realpathSync, writeSync } from \"node:fs\";\nimport { access, chmod, mkdir, readFile, 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 } from \"../../config.ts\";\nimport { processIsLive, readProcessStartTime } from \"../app-server/daemon/process.ts\";\nimport { createHostDaemonPaths } from \"./host-ensure.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 {\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}\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\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\thostArgs.push(arg);\n\t}\n\treturn socket === undefined ? undefined : { socket, hostArgs, childCommand, childArgs, agentDir };\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\treturn resolve(dirname(modulePath), \"..\", \"..\", `cli-main${extension}`);\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(launch.agentDir ?? getAgentDir());\n\tconst policy = resolveHostPolicy(await readSettingsFile(paths.settingsFile), process.env);\n\tconst publicSocket = launch.socket;\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 shuttingDown = 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[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\tpaths.pidFile,\n\t\t\t\tpaths.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\tif (shuttingDown) {\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\tconst detach = (): void => {\n\t\t\t\tclientSockets.delete(client);\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}\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\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.\n\t\t\tawait 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// Mirror ensureHost's cleanupState: the pidfile and settings describe a\n\t\t\t// live host only; the stderr log stays for diagnostics.\n\t\t\tawait rm(paths.pidFile, { force: true });\n\t\t\tawait rm(paths.settingsFile, { force: true });\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\tregisterSupervisorSignals(shutdown);\n\ttry {\n\t\tawait waitForListener(internalSocket, 30_000, internalSecret);\n\t\tawait connectObserver();\n\t\tawait prepareSocketPath(publicSocket);\n\t\tawait listen(server, publicSocket, publicSecret);\n\t\tpublicSocketOwned = true;\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} 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/** External stop (ensureHost replacement, tests, QA) must clean up like idle exit. */\nfunction registerSupervisorSignals(shutdown: (reason: string, exitCode: number) => Promise<never>): 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}\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\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 (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,O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7E,CAAC;AAED,SAAS,gBAAgB,CAAC,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,aAAa,EAAE,EAAE,CAAC;IACrB,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 { realpathSync, writeSync } from \"node:fs\";\nimport { access, chmod, mkdir, readFile, 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 } from \"../../config.ts\";\nimport { processIsLive, readProcessStartTime } from \"../app-server/daemon/process.ts\";\nimport { createHostDaemonPaths } from \"./host-ensure.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 {\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}\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\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\thostArgs.push(arg);\n\t}\n\treturn socket === undefined ? undefined : { socket, hostArgs, childCommand, childArgs, agentDir };\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\treturn resolve(dirname(modulePath), \"..\", \"..\", `cli-main${extension}`);\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(launch.agentDir ?? getAgentDir());\n\tconst policy = resolveHostPolicy(await readSettingsFile(paths.settingsFile), process.env);\n\tconst publicSocket = launch.socket;\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 shuttingDown = 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[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\tpaths.pidFile,\n\t\t\t\tpaths.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\tif (shuttingDown) {\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\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.\n\t\t\tawait 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// Mirror ensureHost's cleanupState: the pidfile and settings describe a\n\t\t\t// live host only; the stderr log stays for diagnostics.\n\t\t\tawait rm(paths.pidFile, { force: true });\n\t\t\tawait rm(paths.settingsFile, { force: true });\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\tregisterSupervisorSignals(shutdown);\n\ttry {\n\t\tawait waitForListener(internalSocket, 30_000, internalSecret);\n\t\tawait connectObserver();\n\t\tawait prepareSocketPath(publicSocket);\n\t\tawait listen(server, publicSocket, publicSecret);\n\t\tpublicSocketOwned = true;\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} 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/** External stop (ensureHost replacement, tests, QA) must clean up like idle exit. */\nfunction registerSupervisorSignals(shutdown: (reason: string, exitCode: number) => Promise<never>): 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}\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\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 (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"]}
@@ -3,6 +3,7 @@ import { existsSync, realpathSync } from "node:fs";
3
3
  import { basename, dirname, join, resolve } from "node:path";
4
4
  import { parentPort } from "node:worker_threads";
5
5
  import { runWithProviderScope } from "@earendil-works/pi-ai/node/provider-scope";
6
+ import { isBunBinary } from "../../config.js";
6
7
  import { WAKE_SOURCE_STATE_EVENT } from "../../core/extensions/builtin/monitor-state-event.js";
7
8
  import { takeOverStdout } from "../../core/output-guard.js";
8
9
  import { getDefaultSessionDir } from "../../core/session-manager.js";
@@ -16,6 +17,10 @@ import { SessionEventWriter } from "./session-event-writer.js";
16
17
  import { RpcSessionRegistry } from "./session-registry.js";
17
18
  import { createWorkerCredit } from "./session-worker-credit.js";
18
19
  import { SESSION_WORKER_LIMITS, } from "./session-worker-protocol.js";
20
+ if (isBunBinary) {
21
+ const { registerBunRuntimeModules } = await import("../../bun/runtime-modules.js");
22
+ registerBunRuntimeModules();
23
+ }
19
24
  takeOverStdout();
20
25
  const port = parentPort;
21
26
  if (!port)