@otium-team/negotium 0.0.0-stage → 0.23.13

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 (572) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +329 -2
  3. package/bin/codex-sdk-window-hide.mjs +40 -0
  4. package/bin/negotium.mjs +22 -0
  5. package/dist/agent-helpers.js +23090 -0
  6. package/dist/agent-helpers.js.map +171 -0
  7. package/dist/background-bash.js +535 -0
  8. package/dist/background-bash.js.map +16 -0
  9. package/dist/browser-runtime.js +2334 -0
  10. package/dist/browser-runtime.js.map +35 -0
  11. package/dist/canonical-mcp-bridge.js +13 -0
  12. package/dist/canonical-mcp-bridge.js.map +9 -0
  13. package/dist/chunk-22kg3fsw.js +79 -0
  14. package/dist/chunk-22kg3fsw.js.map +9 -0
  15. package/dist/chunk-d4j77adx.js +336 -0
  16. package/dist/chunk-d4j77adx.js.map +13 -0
  17. package/dist/chunk-mk9x18jn.js +172 -0
  18. package/dist/chunk-mk9x18jn.js.map +12 -0
  19. package/dist/chunk-qd0vtfm2.js +3923 -0
  20. package/dist/chunk-qd0vtfm2.js.map +47 -0
  21. package/dist/chunk-wf7ny8eq.js +206 -0
  22. package/dist/chunk-wf7ny8eq.js.map +10 -0
  23. package/dist/chunk-ww8a4ej4.js +54 -0
  24. package/dist/chunk-ww8a4ej4.js.map +10 -0
  25. package/dist/cron.js +1 -0
  26. package/dist/hosted-agent.js +5982 -0
  27. package/dist/hosted-agent.js.map +62 -0
  28. package/dist/main.js +60229 -0
  29. package/dist/main.js.map +340 -0
  30. package/dist/mcp-catalog.js +39 -0
  31. package/dist/mcp-catalog.js.map +10 -0
  32. package/dist/mcp-factories.js +25767 -0
  33. package/dist/mcp-factories.js.map +181 -0
  34. package/dist/mcp-servers.js +50 -0
  35. package/dist/mcp-servers.js.map +10 -0
  36. package/dist/media.js +570 -0
  37. package/dist/media.js.map +15 -0
  38. package/dist/outbox.js +354 -0
  39. package/dist/outbox.js.map +15 -0
  40. package/dist/platform-runtime.js +73 -0
  41. package/dist/platform-runtime.js.map +12 -0
  42. package/dist/prompts.js +892 -0
  43. package/dist/prompts.js.map +15 -0
  44. package/dist/query-runtime.js +1071 -0
  45. package/dist/query-runtime.js.map +26 -0
  46. package/dist/registry.js +335 -0
  47. package/dist/registry.js.map +14 -0
  48. package/dist/rollout.js +57 -0
  49. package/dist/rollout.js.map +10 -0
  50. package/dist/runtime/cron/background-sessions.ts +119 -0
  51. package/dist/runtime/cron/context.ts +123 -0
  52. package/dist/runtime/cron/host.ts +67 -0
  53. package/dist/runtime/cron/index.ts +95 -0
  54. package/dist/runtime/cron/mcp-server.ts +556 -0
  55. package/dist/runtime/cron/module.ts +174 -0
  56. package/dist/runtime/cron/package.json +6 -0
  57. package/dist/runtime/cron/schedule.ts +211 -0
  58. package/dist/runtime/cron/scheduler.ts +444 -0
  59. package/dist/runtime/cron/scripts.ts +203 -0
  60. package/dist/runtime/cron/store.ts +1163 -0
  61. package/dist/runtime/cron/summarize.ts +115 -0
  62. package/dist/runtime/package.json +6 -0
  63. package/dist/runtime/scripts/faster-whisper-wrapper.py +87 -0
  64. package/dist/runtime/src/agents/api-topic-agent-switch.ts +179 -0
  65. package/dist/runtime/src/agents/archiver.ts +677 -0
  66. package/dist/runtime/src/agents/auth-check.ts +156 -0
  67. package/dist/runtime/src/agents/claude-notices.ts +130 -0
  68. package/dist/runtime/src/agents/claude-provider.ts +941 -0
  69. package/dist/runtime/src/agents/claude-registry.ts +117 -0
  70. package/dist/runtime/src/agents/claude-runtime-inspection.ts +43 -0
  71. package/dist/runtime/src/agents/codex-app-server.ts +138 -0
  72. package/dist/runtime/src/agents/codex-native-multi-agent.ts +360 -0
  73. package/dist/runtime/src/agents/codex-provider.ts +1193 -0
  74. package/dist/runtime/src/agents/codex-registry.ts +116 -0
  75. package/dist/runtime/src/agents/codex-tier-resolver.ts +74 -0
  76. package/dist/runtime/src/agents/codex-tree-kill.ts +54 -0
  77. package/dist/runtime/src/agents/codex-tree-manager.ts +230 -0
  78. package/dist/runtime/src/agents/codex-vault-hook-bridge.ts +240 -0
  79. package/dist/runtime/src/agents/codex-vault-hook.mjs +50 -0
  80. package/dist/runtime/src/agents/codex-windows-wrapper.ts +174 -0
  81. package/dist/runtime/src/agents/compaction-support.ts +75 -0
  82. package/dist/runtime/src/agents/compaction-tool-projection.ts +125 -0
  83. package/dist/runtime/src/agents/contracts.ts +75 -0
  84. package/dist/runtime/src/agents/deep-map.ts +13 -0
  85. package/dist/runtime/src/agents/execution-host.ts +118 -0
  86. package/dist/runtime/src/agents/explicit-agent-switch.ts +106 -0
  87. package/dist/runtime/src/agents/fixtures/claude-attachments.jsonl +2 -0
  88. package/dist/runtime/src/agents/fixtures/codex-shell.jsonl +5 -0
  89. package/dist/runtime/src/agents/fork.ts +100 -0
  90. package/dist/runtime/src/agents/hosted-agent.ts +78 -0
  91. package/dist/runtime/src/agents/idle-archiver.ts +225 -0
  92. package/dist/runtime/src/agents/idle-compact.ts +225 -0
  93. package/dist/runtime/src/agents/index.ts +225 -0
  94. package/dist/runtime/src/agents/maestro-provider.ts +246 -0
  95. package/dist/runtime/src/agents/maestro-registry.ts +189 -0
  96. package/dist/runtime/src/agents/mcp-tools/ask-user.ts +653 -0
  97. package/dist/runtime/src/agents/mcp-tools/common.ts +23 -0
  98. package/dist/runtime/src/agents/mcp-tools/inline-assets.ts +203 -0
  99. package/dist/runtime/src/agents/mcp-tools/publish-html.ts +183 -0
  100. package/dist/runtime/src/agents/mcp-tools/request-vault.ts +684 -0
  101. package/dist/runtime/src/agents/mcp-tools/self-config.ts +353 -0
  102. package/dist/runtime/src/agents/mcp-tools/spawn-subagent.ts +1349 -0
  103. package/dist/runtime/src/agents/mcp-tools/visual-compat.ts +18 -0
  104. package/dist/runtime/src/agents/mcp-tools/visuals.ts +60 -0
  105. package/dist/runtime/src/agents/memory-archive-policy.ts +54 -0
  106. package/dist/runtime/src/agents/model-catalog.ts +439 -0
  107. package/dist/runtime/src/agents/public-helpers.ts +149 -0
  108. package/dist/runtime/src/agents/registry.ts +35 -0
  109. package/dist/runtime/src/agents/rollout/claude.ts +336 -0
  110. package/dist/runtime/src/agents/rollout/codex.ts +910 -0
  111. package/dist/runtime/src/agents/rollout/index.ts +26 -0
  112. package/dist/runtime/src/agents/rollout/shared.ts +293 -0
  113. package/dist/runtime/src/agents/self-config-core.ts +704 -0
  114. package/dist/runtime/src/agents/task-events.ts +59 -0
  115. package/dist/runtime/src/agents/tool-format.ts +613 -0
  116. package/dist/runtime/src/agents/topic-agent-switch.ts +189 -0
  117. package/dist/runtime/src/agents/topic-cleanup.ts +285 -0
  118. package/dist/runtime/src/agents/vault-tool-policy.ts +36 -0
  119. package/dist/runtime/src/application/execute-external-user-turn.ts +23 -0
  120. package/dist/runtime/src/application/submit-runtime-gateway-turn.ts +484 -0
  121. package/dist/runtime/src/application/submit-user-message.ts +60 -0
  122. package/dist/runtime/src/application/switch-topic-effort.ts +48 -0
  123. package/dist/runtime/src/application/switch-topic-model.ts +79 -0
  124. package/dist/runtime/src/application/topic-service.ts +190 -0
  125. package/dist/runtime/src/application/turn-follow-ups.ts +291 -0
  126. package/dist/runtime/src/application/vault-command.ts +170 -0
  127. package/dist/runtime/src/bus.ts +409 -0
  128. package/dist/runtime/src/config-public.ts +2 -0
  129. package/dist/runtime/src/cron-host.ts +33 -0
  130. package/dist/runtime/src/cron-mcp-host.ts +5 -0
  131. package/dist/runtime/src/identifiers.ts +49 -0
  132. package/dist/runtime/src/index.ts +573 -0
  133. package/dist/runtime/src/mcp/agent-health-server.ts +8 -0
  134. package/dist/runtime/src/mcp/canonical-bridge-config.ts +84 -0
  135. package/dist/runtime/src/mcp/canonical-proxy-server.ts +308 -0
  136. package/dist/runtime/src/mcp/compaction-log-server.ts +25 -0
  137. package/dist/runtime/src/mcp/decision-server.ts +21 -0
  138. package/dist/runtime/src/mcp/dm-ipc.ts +60 -0
  139. package/dist/runtime/src/mcp/factories/agent-health.ts +394 -0
  140. package/dist/runtime/src/mcp/factories/compaction-log.ts +135 -0
  141. package/dist/runtime/src/mcp/factories/decision.ts +186 -0
  142. package/dist/runtime/src/mcp/factories/index.ts +73 -0
  143. package/dist/runtime/src/mcp/factories/session-comm.ts +184 -0
  144. package/dist/runtime/src/mcp/factories/session-history.ts +103 -0
  145. package/dist/runtime/src/mcp/factories/stdio-protection.ts +24 -0
  146. package/dist/runtime/src/mcp/factories/system-health.ts +259 -0
  147. package/dist/runtime/src/mcp/factories/task.ts +185 -0
  148. package/dist/runtime/src/mcp/factories/token-stats.ts +145 -0
  149. package/dist/runtime/src/mcp/factories/vault.ts +32 -0
  150. package/dist/runtime/src/mcp/mcp-helpers.ts +40 -0
  151. package/dist/runtime/src/mcp/peer-bridge.ts +119 -0
  152. package/dist/runtime/src/mcp/runtime-spec.ts +473 -0
  153. package/dist/runtime/src/mcp/session-comm/actor-policy.ts +160 -0
  154. package/dist/runtime/src/mcp/session-comm/bridge-ipc-config.ts +27 -0
  155. package/dist/runtime/src/mcp/session-comm/context.ts +113 -0
  156. package/dist/runtime/src/mcp/session-comm/default-host.ts +723 -0
  157. package/dist/runtime/src/mcp/session-comm/history-target.ts +89 -0
  158. package/dist/runtime/src/mcp/session-comm/history-tools.ts +113 -0
  159. package/dist/runtime/src/mcp/session-comm/hub-remote-session.ts +553 -0
  160. package/dist/runtime/src/mcp/session-comm/limits.ts +8 -0
  161. package/dist/runtime/src/mcp/session-comm/peer-forward.ts +251 -0
  162. package/dist/runtime/src/mcp/session-comm/runtime.ts +128 -0
  163. package/dist/runtime/src/mcp/session-comm/server.ts +1036 -0
  164. package/dist/runtime/src/mcp/session-comm/tell-permissions.ts +79 -0
  165. package/dist/runtime/src/mcp/session-comm/topic-catalog.ts +155 -0
  166. package/dist/runtime/src/mcp/session-comm/topic-config.ts +137 -0
  167. package/dist/runtime/src/mcp/session-comm/topics.ts +313 -0
  168. package/dist/runtime/src/mcp/session-history-limits.ts +36 -0
  169. package/dist/runtime/src/mcp/session-history-reader.ts +359 -0
  170. package/dist/runtime/src/mcp/session-history-server.ts +19 -0
  171. package/dist/runtime/src/mcp/stdio-protect.ts +7 -0
  172. package/dist/runtime/src/mcp/system-health-server.ts +5 -0
  173. package/dist/runtime/src/mcp/task-server.ts +17 -0
  174. package/dist/runtime/src/mcp/token-stats-server.ts +10 -0
  175. package/dist/runtime/src/mcp/vault-server.ts +12 -0
  176. package/dist/runtime/src/mcp/wiki-search-index.ts +359 -0
  177. package/dist/runtime/src/mcp/wiki-server.ts +2386 -0
  178. package/dist/runtime/src/mcp-runtime-host.ts +81 -0
  179. package/dist/runtime/src/media/file-events.ts +33 -0
  180. package/dist/runtime/src/media/text-extractor.ts +334 -0
  181. package/dist/runtime/src/media/video.ts +92 -0
  182. package/dist/runtime/src/node-host.ts +211 -0
  183. package/dist/runtime/src/outbox/coalescing-runner.ts +157 -0
  184. package/dist/runtime/src/outbox/file-ops.ts +267 -0
  185. package/dist/runtime/src/outbox/index.ts +26 -0
  186. package/dist/runtime/src/outbox/utils.ts +74 -0
  187. package/dist/runtime/src/platform/background-bash/context.ts +9 -0
  188. package/dist/runtime/src/platform/background-bash/manager.ts +292 -0
  189. package/dist/runtime/src/platform/background-bash/output-buffer.ts +323 -0
  190. package/dist/runtime/src/platform/config-helpers.ts +47 -0
  191. package/dist/runtime/src/platform/config.ts +618 -0
  192. package/dist/runtime/src/platform/constants.ts +30 -0
  193. package/dist/runtime/src/platform/debug-users.ts +14 -0
  194. package/dist/runtime/src/platform/delay.ts +1 -0
  195. package/dist/runtime/src/platform/error.ts +9 -0
  196. package/dist/runtime/src/platform/file-utils.ts +35 -0
  197. package/dist/runtime/src/platform/ipc.ts +55 -0
  198. package/dist/runtime/src/platform/jsonl.ts +277 -0
  199. package/dist/runtime/src/platform/lifecycle.ts +176 -0
  200. package/dist/runtime/src/platform/log-rotation.ts +45 -0
  201. package/dist/runtime/src/platform/logger.ts +42 -0
  202. package/dist/runtime/src/platform/maestro-bootstrap-env.ts +3 -0
  203. package/dist/runtime/src/platform/mcp-catalog-policy.ts +63 -0
  204. package/dist/runtime/src/platform/mcp-config.ts +1329 -0
  205. package/dist/runtime/src/platform/memoize-import.ts +26 -0
  206. package/dist/runtime/src/platform/modules.ts +145 -0
  207. package/dist/runtime/src/platform/node-plugins.ts +46 -0
  208. package/dist/runtime/src/platform/paths.ts +62 -0
  209. package/dist/runtime/src/platform/playwright/browser-processes.ts +300 -0
  210. package/dist/runtime/src/platform/playwright/capability.ts +5 -0
  211. package/dist/runtime/src/platform/playwright/headed-launch.ts +61 -0
  212. package/dist/runtime/src/platform/playwright/manager-utils.ts +128 -0
  213. package/dist/runtime/src/platform/playwright/manager.ts +1502 -0
  214. package/dist/runtime/src/platform/playwright/mcp-transport.ts +35 -0
  215. package/dist/runtime/src/platform/playwright/profile-management.ts +33 -0
  216. package/dist/runtime/src/platform/playwright/public-runtime.ts +52 -0
  217. package/dist/runtime/src/platform/playwright/transport-probe.ts +89 -0
  218. package/dist/runtime/src/platform/playwright/vault-broker.ts +261 -0
  219. package/dist/runtime/src/platform/public-runtime.ts +18 -0
  220. package/dist/runtime/src/prompts/agents/wiki-archiver.md +194 -0
  221. package/dist/runtime/src/prompts/builders.ts +696 -0
  222. package/dist/runtime/src/prompts/sessions/_shared-tools.md +38 -0
  223. package/dist/runtime/src/prompts/sessions/channel-system.md +13 -0
  224. package/dist/runtime/src/prompts/sessions/manager-system.md +34 -0
  225. package/dist/runtime/src/prompts/sessions/surfaces/cli.md +6 -0
  226. package/dist/runtime/src/prompts/sessions/surfaces/otium-manager.md +18 -0
  227. package/dist/runtime/src/prompts/sessions/surfaces/otium.md +6 -0
  228. package/dist/runtime/src/prompts/sessions/surfaces/telegram.md +5 -0
  229. package/dist/runtime/src/prompts/sessions/surfaces/terminal.md +6 -0
  230. package/dist/runtime/src/prompts/sessions/topic-system.md +9 -0
  231. package/dist/runtime/src/prompts/sessions/visual-design.md +38 -0
  232. package/dist/runtime/src/query/active-rooms.ts +514 -0
  233. package/dist/runtime/src/query/index.ts +23 -0
  234. package/dist/runtime/src/query/public-runtime.ts +28 -0
  235. package/dist/runtime/src/query/room-query-registry.ts +217 -0
  236. package/dist/runtime/src/query/session-inbox-cleanup.ts +45 -0
  237. package/dist/runtime/src/query/session-inbox-path.ts +42 -0
  238. package/dist/runtime/src/query/state.ts +116 -0
  239. package/dist/runtime/src/query/types.ts +8 -0
  240. package/dist/runtime/src/runtime/actor-topic-reach.ts +123 -0
  241. package/dist/runtime/src/runtime/actor-topic-scope.ts +255 -0
  242. package/dist/runtime/src/runtime/ask-callbacks.ts +217 -0
  243. package/dist/runtime/src/runtime/attachments.ts +149 -0
  244. package/dist/runtime/src/runtime/background-session-policy.ts +1 -0
  245. package/dist/runtime/src/runtime/background-sessions.ts +288 -0
  246. package/dist/runtime/src/runtime/bashrs-completions.ts +350 -0
  247. package/dist/runtime/src/runtime/channel-context.ts +115 -0
  248. package/dist/runtime/src/runtime/context-warning.ts +131 -0
  249. package/dist/runtime/src/runtime/cron-sessions.ts +35 -0
  250. package/dist/runtime/src/runtime/delivery-ack.ts +112 -0
  251. package/dist/runtime/src/runtime/errors.ts +70 -0
  252. package/dist/runtime/src/runtime/event-heartbeat.ts +77 -0
  253. package/dist/runtime/src/runtime/file-hooks.ts +81 -0
  254. package/dist/runtime/src/runtime/footer.ts +23 -0
  255. package/dist/runtime/src/runtime/gateway-capabilities.ts +22 -0
  256. package/dist/runtime/src/runtime/inbox.ts +1307 -0
  257. package/dist/runtime/src/runtime/playwright-turn-abort.ts +59 -0
  258. package/dist/runtime/src/runtime/public-helpers.ts +78 -0
  259. package/dist/runtime/src/runtime/remote-session-grant.ts +221 -0
  260. package/dist/runtime/src/runtime/remote-session-inbox.ts +943 -0
  261. package/dist/runtime/src/runtime/remote-session-reply-outbox.ts +168 -0
  262. package/dist/runtime/src/runtime/task-format.ts +18 -0
  263. package/dist/runtime/src/runtime/tasks.ts +53 -0
  264. package/dist/runtime/src/runtime/thread-context.ts +123 -0
  265. package/dist/runtime/src/runtime/thread-read.ts +67 -0
  266. package/dist/runtime/src/runtime/topic-config.ts +29 -0
  267. package/dist/runtime/src/runtime/turn-event-stream.ts +1051 -0
  268. package/dist/runtime/src/runtime/turn-runner.ts +2311 -0
  269. package/dist/runtime/src/runtime/turn-session.ts +116 -0
  270. package/dist/runtime/src/runtime/usage-alert.ts +51 -0
  271. package/dist/runtime/src/runtime/user-turn-envelope.ts +94 -0
  272. package/dist/runtime/src/runtime/visual-html.ts +175 -0
  273. package/dist/runtime/src/runtime/visual-store.ts +480 -0
  274. package/dist/runtime/src/runtime/visuals.ts +209 -0
  275. package/dist/runtime/src/runtime-gateway.ts +1045 -0
  276. package/dist/runtime/src/security/sanitize.ts +27 -0
  277. package/dist/runtime/src/security/sensitive-path.ts +41 -0
  278. package/dist/runtime/src/storage/activity-log.ts +167 -0
  279. package/dist/runtime/src/storage/api-messages.ts +766 -0
  280. package/dist/runtime/src/storage/api-topic-brief.ts +134 -0
  281. package/dist/runtime/src/storage/api-topic-config.ts +197 -0
  282. package/dist/runtime/src/storage/api-topics.ts +1647 -0
  283. package/dist/runtime/src/storage/app-settings.ts +50 -0
  284. package/dist/runtime/src/storage/ask-user-gates.ts +359 -0
  285. package/dist/runtime/src/storage/browser-profiles.ts +186 -0
  286. package/dist/runtime/src/storage/conversation-migration.ts +180 -0
  287. package/dist/runtime/src/storage/conversations.ts +377 -0
  288. package/dist/runtime/src/storage/decisions.ts +231 -0
  289. package/dist/runtime/src/storage/forum/agent-settings.ts +20 -0
  290. package/dist/runtime/src/storage/forum/index.ts +4 -0
  291. package/dist/runtime/src/storage/forum/repository.ts +283 -0
  292. package/dist/runtime/src/storage/forum/schema.ts +314 -0
  293. package/dist/runtime/src/storage/forum-db.ts +4 -0
  294. package/dist/runtime/src/storage/remote-session.ts +1028 -0
  295. package/dist/runtime/src/storage/runtime-events.ts +209 -0
  296. package/dist/runtime/src/storage/runtime-follow-ups.ts +212 -0
  297. package/dist/runtime/src/storage/runtime-gateway-submissions.ts +132 -0
  298. package/dist/runtime/src/storage/runtime-leases.ts +190 -0
  299. package/dist/runtime/src/storage/runtime-process-leases.ts +288 -0
  300. package/dist/runtime/src/storage/runtime-topic-state.ts +181 -0
  301. package/dist/runtime/src/storage/runtime-turn-requests.ts +846 -0
  302. package/dist/runtime/src/storage/self-schedules.ts +306 -0
  303. package/dist/runtime/src/storage/session-asks.ts +468 -0
  304. package/dist/runtime/src/storage/session-inbox-signal.ts +76 -0
  305. package/dist/runtime/src/storage/session-inbox.ts +161 -0
  306. package/dist/runtime/src/storage/sqlite.ts +154 -0
  307. package/dist/runtime/src/storage/storage-contract.ts +54 -0
  308. package/dist/runtime/src/storage/storage-host.ts +336 -0
  309. package/dist/runtime/src/storage/storage-public-host.ts +16 -0
  310. package/dist/runtime/src/storage/storage-public.ts +66 -0
  311. package/dist/runtime/src/storage/tasks.ts +172 -0
  312. package/dist/runtime/src/storage/token-stats.ts +432 -0
  313. package/dist/runtime/src/storage/topic-archive-state.ts +226 -0
  314. package/dist/runtime/src/storage/topic-archive.ts +169 -0
  315. package/dist/runtime/src/storage/topic-host-mcp-grants.ts +54 -0
  316. package/dist/runtime/src/storage/topic-link-records.ts +1085 -0
  317. package/dist/runtime/src/storage/topic-settings.ts +67 -0
  318. package/dist/runtime/src/storage/topic-tool-capabilities.ts +89 -0
  319. package/dist/runtime/src/storage/topic-transcript.ts +98 -0
  320. package/dist/runtime/src/storage/vault-crypto-core.ts +65 -0
  321. package/dist/runtime/src/storage/vault-crypto.ts +31 -0
  322. package/dist/runtime/src/storage/vault-public.ts +27 -0
  323. package/dist/runtime/src/storage/vault-request-gates.ts +359 -0
  324. package/dist/runtime/src/storage/vault.ts +388 -0
  325. package/dist/runtime/src/storage/wiki-summary-names.ts +52 -0
  326. package/dist/runtime/src/storage/wiki.ts +90 -0
  327. package/dist/runtime/src/topics/claim-abort.ts +190 -0
  328. package/dist/runtime/src/topics/create.ts +192 -0
  329. package/dist/runtime/src/topics/derive.ts +600 -0
  330. package/dist/runtime/src/topics/lifecycle.ts +425 -0
  331. package/dist/runtime/src/topics/links.ts +7 -0
  332. package/dist/runtime/src/topics/personal-general.ts +91 -0
  333. package/dist/runtime/src/topics/session.ts +1041 -0
  334. package/dist/runtime/src/topics/update.ts +287 -0
  335. package/dist/runtime/src/types/api.ts +591 -0
  336. package/dist/runtime/src/types.ts +418 -0
  337. package/dist/runtime/src/version.ts +1 -0
  338. package/dist/runtime/tsconfig.json +13 -0
  339. package/dist/runtime-gateway.js +514 -0
  340. package/dist/runtime-gateway.js.map +10 -0
  341. package/dist/runtime-helpers.js +1792 -0
  342. package/dist/runtime-helpers.js.map +40 -0
  343. package/dist/sqlite.js +66 -0
  344. package/dist/sqlite.js.map +10 -0
  345. package/dist/storage.js +5223 -0
  346. package/dist/storage.js.map +47 -0
  347. package/dist/types/apps/negotium/src/mcp-servers.d.ts +20 -0
  348. package/dist/types/packages/core/src/agents/api-topic-agent-switch.d.ts +38 -0
  349. package/dist/types/packages/core/src/agents/archiver.d.ts +87 -0
  350. package/dist/types/packages/core/src/agents/auth-check.d.ts +19 -0
  351. package/dist/types/packages/core/src/agents/claude-notices.d.ts +15 -0
  352. package/dist/types/packages/core/src/agents/claude-provider.d.ts +25 -0
  353. package/dist/types/packages/core/src/agents/claude-registry.d.ts +3 -0
  354. package/dist/types/packages/core/src/agents/claude-runtime-inspection.d.ts +9 -0
  355. package/dist/types/packages/core/src/agents/codex-app-server.d.ts +13 -0
  356. package/dist/types/packages/core/src/agents/codex-native-multi-agent.d.ts +20 -0
  357. package/dist/types/packages/core/src/agents/codex-provider.d.ts +64 -0
  358. package/dist/types/packages/core/src/agents/codex-registry.d.ts +3 -0
  359. package/dist/types/packages/core/src/agents/codex-tier-resolver.d.ts +10 -0
  360. package/dist/types/packages/core/src/agents/codex-tree-kill.d.ts +13 -0
  361. package/dist/types/packages/core/src/agents/codex-tree-manager.d.ts +28 -0
  362. package/dist/types/packages/core/src/agents/codex-vault-hook-bridge.d.ts +28 -0
  363. package/dist/types/packages/core/src/agents/codex-windows-wrapper.d.ts +30 -0
  364. package/dist/types/packages/core/src/agents/compaction-support.d.ts +5 -0
  365. package/dist/types/packages/core/src/agents/compaction-tool-projection.d.ts +9 -0
  366. package/dist/types/packages/core/src/agents/contracts.d.ts +68 -0
  367. package/dist/types/packages/core/src/agents/deep-map.d.ts +2 -0
  368. package/dist/types/packages/core/src/agents/execution-host.d.ts +33 -0
  369. package/dist/types/packages/core/src/agents/explicit-agent-switch.d.ts +26 -0
  370. package/dist/types/packages/core/src/agents/fork.d.ts +50 -0
  371. package/dist/types/packages/core/src/agents/hosted-agent.d.ts +15 -0
  372. package/dist/types/packages/core/src/agents/idle-archiver.d.ts +35 -0
  373. package/dist/types/packages/core/src/agents/idle-compact.d.ts +37 -0
  374. package/dist/types/packages/core/src/agents/index.d.ts +8 -0
  375. package/dist/types/packages/core/src/agents/maestro-provider.d.ts +75 -0
  376. package/dist/types/packages/core/src/agents/maestro-registry.d.ts +3 -0
  377. package/dist/types/packages/core/src/agents/mcp-tools/ask-user.d.ts +147 -0
  378. package/dist/types/packages/core/src/agents/mcp-tools/common.d.ts +14 -0
  379. package/dist/types/packages/core/src/agents/mcp-tools/inline-assets.d.ts +24 -0
  380. package/dist/types/packages/core/src/agents/mcp-tools/publish-html.d.ts +18 -0
  381. package/dist/types/packages/core/src/agents/mcp-tools/request-vault.d.ts +124 -0
  382. package/dist/types/packages/core/src/agents/mcp-tools/self-config.d.ts +45 -0
  383. package/dist/types/packages/core/src/agents/mcp-tools/spawn-subagent.d.ts +148 -0
  384. package/dist/types/packages/core/src/agents/mcp-tools/visual-compat.d.ts +55 -0
  385. package/dist/types/packages/core/src/agents/mcp-tools/visuals.d.ts +70 -0
  386. package/dist/types/packages/core/src/agents/memory-archive-policy.d.ts +24 -0
  387. package/dist/types/packages/core/src/agents/model-catalog.d.ts +132 -0
  388. package/dist/types/packages/core/src/agents/public-helpers.d.ts +17 -0
  389. package/dist/types/packages/core/src/agents/registry.d.ts +5 -0
  390. package/dist/types/packages/core/src/agents/rollout/claude.d.ts +77 -0
  391. package/dist/types/packages/core/src/agents/rollout/codex.d.ts +119 -0
  392. package/dist/types/packages/core/src/agents/rollout/index.d.ts +6 -0
  393. package/dist/types/packages/core/src/agents/rollout/shared.d.ts +56 -0
  394. package/dist/types/packages/core/src/agents/self-config-core.d.ts +199 -0
  395. package/dist/types/packages/core/src/agents/task-events.d.ts +19 -0
  396. package/dist/types/packages/core/src/agents/tool-format.d.ts +25 -0
  397. package/dist/types/packages/core/src/agents/topic-cleanup.d.ts +83 -0
  398. package/dist/types/packages/core/src/agents/vault-tool-policy.d.ts +2 -0
  399. package/dist/types/packages/core/src/bus.d.ts +141 -0
  400. package/dist/types/packages/core/src/identifiers.d.ts +27 -0
  401. package/dist/types/packages/core/src/mcp/canonical-bridge-config.d.ts +21 -0
  402. package/dist/types/packages/core/src/mcp/factories/agent-health.d.ts +5 -0
  403. package/dist/types/packages/core/src/mcp/factories/compaction-log.d.ts +8 -0
  404. package/dist/types/packages/core/src/mcp/factories/decision.d.ts +18 -0
  405. package/dist/types/packages/core/src/mcp/factories/index.d.ts +13 -0
  406. package/dist/types/packages/core/src/mcp/factories/session-comm.d.ts +38 -0
  407. package/dist/types/packages/core/src/mcp/factories/session-history.d.ts +11 -0
  408. package/dist/types/packages/core/src/mcp/factories/stdio-protection.d.ts +10 -0
  409. package/dist/types/packages/core/src/mcp/factories/system-health.d.ts +37 -0
  410. package/dist/types/packages/core/src/mcp/factories/task.d.ts +13 -0
  411. package/dist/types/packages/core/src/mcp/factories/token-stats.d.ts +20 -0
  412. package/dist/types/packages/core/src/mcp/factories/vault.d.ts +9 -0
  413. package/dist/types/packages/core/src/mcp/mcp-helpers.d.ts +26 -0
  414. package/dist/types/packages/core/src/mcp/peer-bridge.d.ts +92 -0
  415. package/dist/types/packages/core/src/mcp/runtime-spec.d.ts +147 -0
  416. package/dist/types/packages/core/src/mcp/session-comm/actor-policy.d.ts +120 -0
  417. package/dist/types/packages/core/src/mcp/session-comm/bridge-ipc-config.d.ts +6 -0
  418. package/dist/types/packages/core/src/mcp/session-comm/context.d.ts +44 -0
  419. package/dist/types/packages/core/src/mcp/session-comm/history-tools.d.ts +31 -0
  420. package/dist/types/packages/core/src/mcp/session-comm/hub-remote-session.d.ts +149 -0
  421. package/dist/types/packages/core/src/mcp/session-comm/limits.d.ts +8 -0
  422. package/dist/types/packages/core/src/mcp/session-comm/peer-forward.d.ts +85 -0
  423. package/dist/types/packages/core/src/mcp/session-comm/tell-permissions.d.ts +29 -0
  424. package/dist/types/packages/core/src/mcp/session-comm/topic-catalog.d.ts +59 -0
  425. package/dist/types/packages/core/src/mcp/session-history-limits.d.ts +20 -0
  426. package/dist/types/packages/core/src/mcp/session-history-reader.d.ts +35 -0
  427. package/dist/types/packages/core/src/mcp/wiki-search-index.d.ts +59 -0
  428. package/dist/types/packages/core/src/mcp/wiki-server.d.ts +53 -0
  429. package/dist/types/packages/core/src/media/file-events.d.ts +14 -0
  430. package/dist/types/packages/core/src/media/text-extractor.d.ts +34 -0
  431. package/dist/types/packages/core/src/outbox/coalescing-runner.d.ts +68 -0
  432. package/dist/types/packages/core/src/outbox/file-ops.d.ts +79 -0
  433. package/dist/types/packages/core/src/outbox/index.d.ts +3 -0
  434. package/dist/types/packages/core/src/outbox/utils.d.ts +16 -0
  435. package/dist/types/packages/core/src/platform/background-bash/context.d.ts +1 -0
  436. package/dist/types/packages/core/src/platform/background-bash/manager.d.ts +34 -0
  437. package/dist/types/packages/core/src/platform/config-helpers.d.ts +20 -0
  438. package/dist/types/packages/core/src/platform/config.d.ts +178 -0
  439. package/dist/types/packages/core/src/platform/constants.d.ts +20 -0
  440. package/dist/types/packages/core/src/platform/delay.d.ts +1 -0
  441. package/dist/types/packages/core/src/platform/error.d.ts +6 -0
  442. package/dist/types/packages/core/src/platform/file-utils.d.ts +16 -0
  443. package/dist/types/packages/core/src/platform/ipc.d.ts +32 -0
  444. package/dist/types/packages/core/src/platform/jsonl.d.ts +46 -0
  445. package/dist/types/packages/core/src/platform/lifecycle.d.ts +40 -0
  446. package/dist/types/packages/core/src/platform/logger.d.ts +20 -0
  447. package/dist/types/packages/core/src/platform/maestro-bootstrap-env.d.ts +0 -0
  448. package/dist/types/packages/core/src/platform/mcp-catalog-policy.d.ts +73 -0
  449. package/dist/types/packages/core/src/platform/mcp-config.d.ts +286 -0
  450. package/dist/types/packages/core/src/platform/memoize-import.d.ts +15 -0
  451. package/dist/types/packages/core/src/platform/paths.d.ts +18 -0
  452. package/dist/types/packages/core/src/platform/playwright/browser-processes.d.ts +60 -0
  453. package/dist/types/packages/core/src/platform/playwright/capability.d.ts +1 -0
  454. package/dist/types/packages/core/src/platform/playwright/headed-launch.d.ts +13 -0
  455. package/dist/types/packages/core/src/platform/playwright/manager-utils.d.ts +34 -0
  456. package/dist/types/packages/core/src/platform/playwright/manager.d.ts +194 -0
  457. package/dist/types/packages/core/src/platform/playwright/mcp-transport.d.ts +4 -0
  458. package/dist/types/packages/core/src/platform/playwright/profile-management.d.ts +8 -0
  459. package/dist/types/packages/core/src/platform/playwright/public-runtime.d.ts +6 -0
  460. package/dist/types/packages/core/src/platform/playwright/transport-probe.d.ts +13 -0
  461. package/dist/types/packages/core/src/platform/playwright/vault-broker.d.ts +6 -0
  462. package/dist/types/packages/core/src/platform/public-runtime.d.ts +3 -0
  463. package/dist/types/packages/core/src/prompts/builders.d.ts +78 -0
  464. package/dist/types/packages/core/src/query/active-rooms.d.ts +240 -0
  465. package/dist/types/packages/core/src/query/public-runtime.d.ts +4 -0
  466. package/dist/types/packages/core/src/query/room-query-registry.d.ts +71 -0
  467. package/dist/types/packages/core/src/query/session-inbox-cleanup.d.ts +5 -0
  468. package/dist/types/packages/core/src/query/session-inbox-path.d.ts +8 -0
  469. package/dist/types/packages/core/src/query/state.d.ts +25 -0
  470. package/dist/types/packages/core/src/query/types.d.ts +6 -0
  471. package/dist/types/packages/core/src/runtime/actor-topic-reach.d.ts +63 -0
  472. package/dist/types/packages/core/src/runtime/actor-topic-scope.d.ts +127 -0
  473. package/dist/types/packages/core/src/runtime/ask-callbacks.d.ts +53 -0
  474. package/dist/types/packages/core/src/runtime/attachments.d.ts +36 -0
  475. package/dist/types/packages/core/src/runtime/background-session-policy.d.ts +1 -0
  476. package/dist/types/packages/core/src/runtime/background-sessions.d.ts +27 -0
  477. package/dist/types/packages/core/src/runtime/bashrs-completions.d.ts +50 -0
  478. package/dist/types/packages/core/src/runtime/channel-context.d.ts +13 -0
  479. package/dist/types/packages/core/src/runtime/context-warning.d.ts +46 -0
  480. package/dist/types/packages/core/src/runtime/cron-sessions.d.ts +9 -0
  481. package/dist/types/packages/core/src/runtime/errors.d.ts +6 -0
  482. package/dist/types/packages/core/src/runtime/event-heartbeat.d.ts +17 -0
  483. package/dist/types/packages/core/src/runtime/file-hooks.d.ts +38 -0
  484. package/dist/types/packages/core/src/runtime/playwright-turn-abort.d.ts +12 -0
  485. package/dist/types/packages/core/src/runtime/public-helpers.d.ts +17 -0
  486. package/dist/types/packages/core/src/runtime/remote-session-grant.d.ts +91 -0
  487. package/dist/types/packages/core/src/runtime/remote-session-inbox.d.ts +206 -0
  488. package/dist/types/packages/core/src/runtime/remote-session-reply-outbox.d.ts +37 -0
  489. package/dist/types/packages/core/src/runtime/task-format.d.ts +4 -0
  490. package/dist/types/packages/core/src/runtime/tasks.d.ts +3 -0
  491. package/dist/types/packages/core/src/runtime/thread-context.d.ts +62 -0
  492. package/dist/types/packages/core/src/runtime/topic-config.d.ts +24 -0
  493. package/dist/types/packages/core/src/runtime/turn-event-stream.d.ts +47 -0
  494. package/dist/types/packages/core/src/runtime/turn-runner.d.ts +284 -0
  495. package/dist/types/packages/core/src/runtime/turn-session.d.ts +49 -0
  496. package/dist/types/packages/core/src/runtime/usage-alert.d.ts +11 -0
  497. package/dist/types/packages/core/src/runtime/user-turn-envelope.d.ts +37 -0
  498. package/dist/types/packages/core/src/runtime/visual-html.d.ts +13 -0
  499. package/dist/types/packages/core/src/runtime/visual-store.d.ts +71 -0
  500. package/dist/types/packages/core/src/runtime/visuals.d.ts +33 -0
  501. package/dist/types/packages/core/src/runtime-gateway.d.ts +282 -0
  502. package/dist/types/packages/core/src/security/sanitize.d.ts +16 -0
  503. package/dist/types/packages/core/src/security/sensitive-path.d.ts +1 -0
  504. package/dist/types/packages/core/src/storage/activity-log.d.ts +25 -0
  505. package/dist/types/packages/core/src/storage/api-messages.d.ts +156 -0
  506. package/dist/types/packages/core/src/storage/api-topic-brief.d.ts +39 -0
  507. package/dist/types/packages/core/src/storage/api-topic-config.d.ts +23 -0
  508. package/dist/types/packages/core/src/storage/api-topics.d.ts +274 -0
  509. package/dist/types/packages/core/src/storage/app-settings.d.ts +4 -0
  510. package/dist/types/packages/core/src/storage/ask-user-gates.d.ts +65 -0
  511. package/dist/types/packages/core/src/storage/browser-profiles.d.ts +31 -0
  512. package/dist/types/packages/core/src/storage/conversations.d.ts +149 -0
  513. package/dist/types/packages/core/src/storage/decisions.d.ts +45 -0
  514. package/dist/types/packages/core/src/storage/forum/agent-settings.d.ts +3 -0
  515. package/dist/types/packages/core/src/storage/forum/index.d.ts +4 -0
  516. package/dist/types/packages/core/src/storage/forum/repository.d.ts +42 -0
  517. package/dist/types/packages/core/src/storage/forum/schema.d.ts +38 -0
  518. package/dist/types/packages/core/src/storage/forum-db.d.ts +2 -0
  519. package/dist/types/packages/core/src/storage/remote-session.d.ts +318 -0
  520. package/dist/types/packages/core/src/storage/runtime-events.d.ts +33 -0
  521. package/dist/types/packages/core/src/storage/runtime-leases.d.ts +27 -0
  522. package/dist/types/packages/core/src/storage/runtime-process-leases.d.ts +47 -0
  523. package/dist/types/packages/core/src/storage/runtime-topic-state.d.ts +39 -0
  524. package/dist/types/packages/core/src/storage/runtime-turn-requests.d.ts +163 -0
  525. package/dist/types/packages/core/src/storage/self-schedules.d.ts +54 -0
  526. package/dist/types/packages/core/src/storage/session-asks.d.ts +78 -0
  527. package/dist/types/packages/core/src/storage/session-inbox-signal.d.ts +35 -0
  528. package/dist/types/packages/core/src/storage/session-inbox.d.ts +36 -0
  529. package/dist/types/packages/core/src/storage/sqlite.d.ts +20 -0
  530. package/dist/types/packages/core/src/storage/storage-contract.d.ts +46 -0
  531. package/dist/types/packages/core/src/storage/storage-host.d.ts +41 -0
  532. package/dist/types/packages/core/src/storage/storage-public-host.d.ts +7 -0
  533. package/dist/types/packages/core/src/storage/storage-public.d.ts +45 -0
  534. package/dist/types/packages/core/src/storage/tasks.d.ts +49 -0
  535. package/dist/types/packages/core/src/storage/token-stats.d.ts +69 -0
  536. package/dist/types/packages/core/src/storage/topic-archive-state.d.ts +33 -0
  537. package/dist/types/packages/core/src/storage/topic-archive.d.ts +42 -0
  538. package/dist/types/packages/core/src/storage/topic-host-mcp-grants.d.ts +5 -0
  539. package/dist/types/packages/core/src/storage/topic-link-records.d.ts +281 -0
  540. package/dist/types/packages/core/src/storage/topic-settings.d.ts +19 -0
  541. package/dist/types/packages/core/src/storage/topic-tool-capabilities.d.ts +37 -0
  542. package/dist/types/packages/core/src/storage/topic-transcript.d.ts +38 -0
  543. package/dist/types/packages/core/src/storage/vault-crypto-core.d.ts +6 -0
  544. package/dist/types/packages/core/src/storage/vault-crypto.d.ts +12 -0
  545. package/dist/types/packages/core/src/storage/vault-public.d.ts +3 -0
  546. package/dist/types/packages/core/src/storage/vault-request-gates.d.ts +69 -0
  547. package/dist/types/packages/core/src/storage/vault.d.ts +49 -0
  548. package/dist/types/packages/core/src/storage/wiki-summary-names.d.ts +13 -0
  549. package/dist/types/packages/core/src/storage/wiki.d.ts +15 -0
  550. package/dist/types/packages/core/src/topics/derive.d.ts +83 -0
  551. package/dist/types/packages/core/src/topics/lifecycle.d.ts +75 -0
  552. package/dist/types/packages/core/src/topics/links.d.ts +2 -0
  553. package/dist/types/packages/core/src/topics/personal-general.d.ts +15 -0
  554. package/dist/types/packages/core/src/topics/session.d.ts +70 -0
  555. package/dist/types/packages/core/src/types/api.d.ts +551 -0
  556. package/dist/types/packages/core/src/types.d.ts +405 -0
  557. package/dist/types/packages/core/src/version.d.ts +1 -0
  558. package/dist/types/packages/module-cron/src/background-sessions.d.ts +2 -0
  559. package/dist/types/packages/module-cron/src/context.d.ts +15 -0
  560. package/dist/types/packages/module-cron/src/host.d.ts +23 -0
  561. package/dist/types/packages/module-cron/src/index.d.ts +14 -0
  562. package/dist/types/packages/module-cron/src/module.d.ts +13 -0
  563. package/dist/types/packages/module-cron/src/schedule.d.ts +23 -0
  564. package/dist/types/packages/module-cron/src/scheduler.d.ts +46 -0
  565. package/dist/types/packages/module-cron/src/scripts.d.ts +29 -0
  566. package/dist/types/packages/module-cron/src/store.d.ts +152 -0
  567. package/dist/types/packages/module-cron/src/summarize.d.ts +4 -0
  568. package/dist/vault.js +848 -0
  569. package/dist/vault.js.map +18 -0
  570. package/install-bash-rs.mjs +90 -0
  571. package/install-browser-rs.mjs +83 -0
  572. package/package.json +171 -4
@@ -0,0 +1,1502 @@
1
+ import { type ChildProcess, execFileSync, spawn } from "node:child_process";
2
+ import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
3
+ import {
4
+ cpSync,
5
+ existsSync,
6
+ mkdirSync,
7
+ readFileSync,
8
+ rmSync,
9
+ unlinkSync,
10
+ writeFileSync,
11
+ } from "node:fs";
12
+ import { dirname, join, resolve } from "node:path";
13
+ import {
14
+ BROWSER_PROFILES_DIR,
15
+ BROWSER_RS_BIN,
16
+ type BrowserProxyConfig,
17
+ PLAYWRIGHT_BASE_PORT,
18
+ PLAYWRIGHT_MAX_PORT,
19
+ PLAYWRIGHT_MCP_BIN,
20
+ PLAYWRIGHT_PORTS_DIR,
21
+ resolveBrowserProxy,
22
+ } from "#platform/config";
23
+ import { delay } from "#platform/delay";
24
+ import { logger } from "#platform/logger";
25
+ import {
26
+ cleanSingletonFiles,
27
+ isPortInUse,
28
+ killBrowserProcsForUserDataDir,
29
+ killProcessTreeChildren,
30
+ reapOrphanBrowsers,
31
+ reserveAvailableLoopbackPort,
32
+ } from "#platform/playwright/browser-processes";
33
+ import {
34
+ type HeadedPlaywrightSpawnSpec,
35
+ resolveHeadedPlaywrightSpawn,
36
+ } from "#platform/playwright/headed-launch";
37
+ import { probePlaywrightMcpTransports } from "#platform/playwright/transport-probe";
38
+ import {
39
+ type BrowserVaultBrokerHandle,
40
+ createBrowserVaultBroker,
41
+ } from "#platform/playwright/vault-broker";
42
+ import { sanitizeTopicName } from "#security/sanitize";
43
+ import {
44
+ assignTopicBrowserProfile,
45
+ getBrowserProfileOwner,
46
+ getTopicBrowserConnectPort,
47
+ getTopicBrowserProfile,
48
+ hasBrowserProfileTopic,
49
+ normalizeBrowserProfileName,
50
+ setTopicBrowserConnectPort,
51
+ } from "#storage/browser-profiles";
52
+ import {
53
+ browserCdpIsLost,
54
+ isLiveOwnedChildProcess,
55
+ matchesSpawnedBrowserHealth,
56
+ selectIdleEvictionKey,
57
+ waitForChildProcessExit,
58
+ } from "./manager-utils";
59
+
60
+ export interface PlaywrightProfileBinding {
61
+ readonly instanceKey: string;
62
+ readonly ownerId: string;
63
+ readonly profile: string;
64
+ }
65
+
66
+ export interface PlaywrightChildEnvironmentContext {
67
+ instanceKey: string;
68
+ ownerId: string;
69
+ capability: string;
70
+ proxy: BrowserProxyConfig | null;
71
+ browserRsBin?: string;
72
+ environment: NodeJS.ProcessEnv;
73
+ }
74
+
75
+ export interface PlaywrightManagerHost {
76
+ readonly portsDir: string;
77
+ readonly basePort: number;
78
+ readonly maxPort: number;
79
+ readonly browserBin: string;
80
+ readonly browserRsBin?: string;
81
+ readonly resolveProxy: () => BrowserProxyConfig | null;
82
+ readonly resolveTopicBinding: (userId: string, topic?: string) => PlaywrightProfileBinding;
83
+ readonly resolveNamedBinding: (ownerId: string, rawProfile: string) => PlaywrightProfileBinding;
84
+ readonly resolveInstanceDataDir: (instanceKey: string) => string;
85
+ readonly createChildEnvironment: (
86
+ context: PlaywrightChildEnvironmentContext,
87
+ ) => NodeJS.ProcessEnv;
88
+ /** Reap an orphan that owns this exact host-managed data directory. */
89
+ readonly cleanupBrowserProcessesForDataDir: (userDataDir: string) => void;
90
+ /** Remove an exact host-managed profile directory, rejecting paths outside the host's root. */
91
+ readonly removeProfileDataDir?: (userDataDir: string) => boolean;
92
+ /** Reap host-managed browsers that are not represented by the supplied live directories. */
93
+ readonly reapOrphanBrowsers: (liveUserDataDirs: Iterable<string>) => void;
94
+ }
95
+
96
+ function removeDefaultProfileDataDir(userDataDir: string): boolean {
97
+ const root = resolve(BROWSER_PROFILES_DIR);
98
+ const target = resolve(userDataDir);
99
+ if (dirname(target) !== root) {
100
+ throw new Error(`Refusing to delete browser profile outside managed root: ${target}`);
101
+ }
102
+ const existed = existsSync(target);
103
+ rmSync(target, { recursive: true, force: true });
104
+ return existed;
105
+ }
106
+
107
+ export {
108
+ cleanupZombiePlaywright,
109
+ isBrowserJanitorOwner,
110
+ reapOrphanBrowsers,
111
+ selectOrphanBrowserPids,
112
+ } from "#platform/playwright/browser-processes";
113
+ export { probePlaywrightMcpTransports } from "#platform/playwright/transport-probe";
114
+ export {
115
+ browserCdpIsLost,
116
+ browserProcessMatchesExpectedProfile,
117
+ extractUserDataDirArg,
118
+ isLiveOwnedChildProcess,
119
+ matchesSpawnedBrowserHealth,
120
+ selectIdleEvictionKey,
121
+ selectReusablePort,
122
+ waitForChildProcessExit,
123
+ waitForChildProcessSpawnError,
124
+ } from "./manager-utils";
125
+ export { PLAYWRIGHT_PORTS_DIR };
126
+
127
+ /** Multiple topics assigned to one profile reuse one browser process. */
128
+ export function makeInstanceKey(userId: string, topic: string | undefined): string {
129
+ return resolvePlaywrightTopicBinding(userId, topic).instanceKey;
130
+ }
131
+
132
+ export function resolvePlaywrightTopicBinding(
133
+ userId: string,
134
+ topic: string | undefined,
135
+ ): PlaywrightProfileBinding {
136
+ return validateProfileBinding(managerHost.resolveTopicBinding(userId, topic));
137
+ }
138
+
139
+ function defaultTopicBinding(userId: string, topic: string | undefined): PlaywrightProfileBinding {
140
+ if (!topic) return managerHost.resolveNamedBinding(userId, "default");
141
+ const connectPort = getTopicBrowserConnectPort(topic);
142
+ if (connectPort !== undefined) return connectBinding(connectPort);
143
+ const ownerId = getBrowserProfileOwner(topic, userId);
144
+ const profile = getTopicBrowserProfile(topic);
145
+ return managerHost.resolveNamedBinding(ownerId, profile);
146
+ }
147
+
148
+ export function makeBrowserProfileInstanceKey(ownerId: string, rawProfile: string): string {
149
+ return resolvePlaywrightProfileBinding(ownerId, rawProfile).instanceKey;
150
+ }
151
+
152
+ export function resolvePlaywrightProfileBinding(
153
+ ownerId: string,
154
+ rawProfile: string,
155
+ ): PlaywrightProfileBinding {
156
+ return validateProfileBinding(managerHost.resolveNamedBinding(ownerId, rawProfile));
157
+ }
158
+
159
+ function validateProfileBinding(binding: PlaywrightProfileBinding): PlaywrightProfileBinding {
160
+ if (
161
+ !binding ||
162
+ typeof binding.instanceKey !== "string" ||
163
+ !binding.instanceKey.trim() ||
164
+ typeof binding.ownerId !== "string" ||
165
+ !binding.ownerId.trim() ||
166
+ typeof binding.profile !== "string" ||
167
+ !binding.profile.trim()
168
+ ) {
169
+ throw new Error("invalid Playwright profile binding");
170
+ }
171
+ return Object.freeze({ ...binding });
172
+ }
173
+
174
+ /**
175
+ * Every room pointing at one host-run Chrome shares one Browser.rs attached to
176
+ * it, whoever owns the room: the Chrome, not a node profile, is the identity.
177
+ */
178
+ function connectBinding(port: number): PlaywrightProfileBinding {
179
+ return { instanceKey: `connect:${port}`, ownerId: "local", profile: `connect-${port}` };
180
+ }
181
+
182
+ function parseConnectInstanceKey(instanceKey: string): number | undefined {
183
+ const match = /^connect:(\d+)$/.exec(instanceKey);
184
+ return match ? Number(match[1]) : undefined;
185
+ }
186
+
187
+ /**
188
+ * Browser.rs argv for one instance. A `connect:` instance attaches to the
189
+ * host's Chrome through `--connect`, which overrides any inherited
190
+ * `AB_CONNECT`; Browser.rs still requires a `--user-data-dir` it then ignores.
191
+ */
192
+ export function browserRsArgs(instanceKey: string, port: number, userDataDir: string): string[] {
193
+ const connectPort = parseConnectInstanceKey(instanceKey);
194
+ return [
195
+ "--port",
196
+ String(port),
197
+ // Pin to IPv4 so every MCP client reaches the same address family and a
198
+ // future launcher default cannot resolve localhost to an IPv6-only bind.
199
+ "--host",
200
+ "127.0.0.1",
201
+ // Keep the browser visible. Do not rely on the launcher's implicit
202
+ // default: an explicit flag prevents wrapper/upstream default changes
203
+ // from silently switching topic browsers back to headless mode.
204
+ "--headed",
205
+ "--user-data-dir",
206
+ userDataDir,
207
+ ...(connectPort === undefined ? [] : ["--connect", String(connectPort)]),
208
+ ];
209
+ }
210
+
211
+ function defaultNamedBinding(_ownerId: string, rawProfile: string): PlaywrightProfileBinding {
212
+ const profile = normalizeBrowserProfileName(rawProfile);
213
+ const instanceKey = `profile:${profile}`;
214
+ return {
215
+ instanceKey,
216
+ ownerId: "local",
217
+ profile,
218
+ };
219
+ }
220
+
221
+ export function legacyBrowserProfileName(topic: string): string {
222
+ return `legacy_${createHash("sha256").update(topic).digest("hex").slice(0, 12)}`;
223
+ }
224
+
225
+ /** Passed through on every host. */
226
+ const CHILD_ENVIRONMENT_KEYS = [
227
+ "HOME",
228
+ "PATH",
229
+ "TMPDIR",
230
+ "TMP",
231
+ "TEMP",
232
+ "LANG",
233
+ "LC_ALL",
234
+ "LC_CTYPE",
235
+ "DISPLAY",
236
+ "WAYLAND_DISPLAY",
237
+ "XAUTHORITY",
238
+ "DBUS_SESSION_BUS_ADDRESS",
239
+ "XDG_RUNTIME_DIR",
240
+ "XDG_CONFIG_HOME",
241
+ "XDG_CACHE_HOME",
242
+ "XDG_DATA_HOME",
243
+ "AB_CHROME",
244
+ "AB_CONNECT",
245
+ "RUST_LOG",
246
+ "RUST_BACKTRACE",
247
+ ];
248
+
249
+ /**
250
+ * Windows equivalents of what the list above carries on POSIX.
251
+ *
252
+ * The allowlist is deliberately narrow, but on Windows it used to name nothing
253
+ * the platform actually needs: `SystemRoot` is required by winsock, so a child
254
+ * without it often cannot open a socket at all, and Chrome is located through
255
+ * the `ProgramFiles*` / `LOCALAPPDATA` roots — without them Browser.rs reports
256
+ * "chrome executable not found" on a machine where Chrome is plainly installed.
257
+ * `USERPROFILE` is the `HOME` of this platform, and `ComSpec`/`PATHEXT` are
258
+ * what make command resolution work.
259
+ */
260
+ const WINDOWS_CHILD_ENVIRONMENT_KEYS = [
261
+ "SystemRoot",
262
+ "windir",
263
+ "SystemDrive",
264
+ "ProgramFiles",
265
+ "ProgramFiles(x86)",
266
+ "ProgramW6432",
267
+ "ProgramData",
268
+ "LOCALAPPDATA",
269
+ "APPDATA",
270
+ "USERPROFILE",
271
+ "ComSpec",
272
+ "PATHEXT",
273
+ "NUMBER_OF_PROCESSORS",
274
+ "PROCESSOR_ARCHITECTURE",
275
+ ];
276
+
277
+ function defaultChildEnvironment(context: PlaywrightChildEnvironmentContext): NodeJS.ProcessEnv {
278
+ const childEnvironment: NodeJS.ProcessEnv = {};
279
+ const keys =
280
+ process.platform === "win32"
281
+ ? [...CHILD_ENVIRONMENT_KEYS, ...WINDOWS_CHILD_ENVIRONMENT_KEYS]
282
+ : CHILD_ENVIRONMENT_KEYS;
283
+ for (const key of keys) {
284
+ if (context.environment[key] !== undefined) childEnvironment[key] = context.environment[key];
285
+ }
286
+ return childEnvironment;
287
+ }
288
+
289
+ const defaultManagerHost: Readonly<PlaywrightManagerHost> = Object.freeze({
290
+ portsDir: PLAYWRIGHT_PORTS_DIR,
291
+ basePort: PLAYWRIGHT_BASE_PORT,
292
+ maxPort: PLAYWRIGHT_MAX_PORT,
293
+ browserBin: PLAYWRIGHT_MCP_BIN,
294
+ browserRsBin: BROWSER_RS_BIN,
295
+ resolveProxy: resolveBrowserProxy,
296
+ resolveTopicBinding: defaultTopicBinding,
297
+ resolveNamedBinding: defaultNamedBinding,
298
+ resolveInstanceDataDir(instanceKey: string) {
299
+ const { ownerId, profile } = parseInstanceKey(instanceKey);
300
+ return defaultProfileDir(ownerId, profile);
301
+ },
302
+ createChildEnvironment: defaultChildEnvironment,
303
+ cleanupBrowserProcessesForDataDir: killBrowserProcsForUserDataDir,
304
+ removeProfileDataDir: removeDefaultProfileDataDir,
305
+ reapOrphanBrowsers,
306
+ });
307
+
308
+ let managerHost: Readonly<PlaywrightManagerHost> = defaultManagerHost;
309
+
310
+ /**
311
+ * Configure product-specific profile storage and browser launch glue.
312
+ * Call once during bootstrap, before any browser instance is started.
313
+ */
314
+ export function configurePlaywrightManagerHost(
315
+ overrides: Partial<PlaywrightManagerHost>,
316
+ ): Readonly<PlaywrightManagerHost> {
317
+ if (instances.size > 0 || spawning.size > 0 || pinnedInstances.size > 0) {
318
+ throw new Error("cannot configure Playwright manager while browser instances are active");
319
+ }
320
+ const next = { ...managerHost, ...overrides };
321
+ if (!next.portsDir || !Number.isInteger(next.basePort) || !Number.isInteger(next.maxPort)) {
322
+ throw new Error("invalid Playwright manager paths or port range");
323
+ }
324
+ if (next.basePort < 1 || next.maxPort > 65_535 || next.basePort > next.maxPort) {
325
+ throw new Error("invalid Playwright manager port range");
326
+ }
327
+ if (!next.browserBin) {
328
+ throw new Error("Browser manager gateway is required");
329
+ }
330
+ if (
331
+ next.resolveInstanceDataDir !== defaultManagerHost.resolveInstanceDataDir &&
332
+ (next.cleanupBrowserProcessesForDataDir ===
333
+ defaultManagerHost.cleanupBrowserProcessesForDataDir ||
334
+ !next.removeProfileDataDir ||
335
+ next.removeProfileDataDir === defaultManagerHost.removeProfileDataDir ||
336
+ next.reapOrphanBrowsers === defaultManagerHost.reapOrphanBrowsers)
337
+ ) {
338
+ throw new Error(
339
+ "custom Playwright profile paths require host crash cleanup, profile removal, and orphan sweep hooks",
340
+ );
341
+ }
342
+ managerHost = Object.freeze(next);
343
+ return managerHost;
344
+ }
345
+
346
+ export function getPlaywrightManagerHost(): Readonly<PlaywrightManagerHost> {
347
+ return managerHost;
348
+ }
349
+
350
+ /** Restore Negotium's built-in browser host after all instances are stopped. */
351
+ export function resetPlaywrightManagerHost(): void {
352
+ configurePlaywrightManagerHost(defaultManagerHost);
353
+ }
354
+
355
+ interface InstanceKeyParts {
356
+ ownerId: string;
357
+ profile: string;
358
+ }
359
+
360
+ function parseInstanceKey(instanceKey: string): InstanceKeyParts {
361
+ const connectPort = parseConnectInstanceKey(instanceKey);
362
+ // The leading underscore is outside the profile-name grammar, so no named
363
+ // profile can share (or delete) the placeholder dir of a connect instance.
364
+ if (connectPort !== undefined) return { ownerId: "local", profile: `_connect-${connectPort}` };
365
+ const shared = /^profile:(.+)$/.exec(instanceKey);
366
+ if (shared && !shared[1]!.includes(":")) {
367
+ return { ownerId: "local", profile: normalizeBrowserProfileName(shared[1]!) };
368
+ }
369
+ const match = /^profile:([^:]+):(.+)$/.exec(instanceKey);
370
+ if (!match) return { ownerId: "legacy", profile: sanitizeTopicName(instanceKey) };
371
+ return {
372
+ ownerId: decodeURIComponent(match[1]!),
373
+ profile: normalizeBrowserProfileName(match[2]!),
374
+ };
375
+ }
376
+
377
+ function portFileName(instanceKey: string): string {
378
+ return createHash("sha256").update(instanceKey).digest("hex").slice(0, 24);
379
+ }
380
+
381
+ function writePortFile(instanceKey: string, port: number) {
382
+ try {
383
+ mkdirSync(managerHost.portsDir, { recursive: true });
384
+ writeFileSync(join(managerHost.portsDir, portFileName(instanceKey)), String(port));
385
+ } catch (e) {
386
+ logger.warn({ err: e, instanceKey, port }, "Failed to save playwright port file");
387
+ }
388
+ }
389
+
390
+ function deletePortFile(instanceKey: string) {
391
+ try {
392
+ unlinkSync(join(managerHost.portsDir, portFileName(instanceKey)));
393
+ } catch (e) {
394
+ if ((e as NodeJS.ErrnoException).code === "ENOENT") return;
395
+ logger.warn({ err: e, instanceKey }, "Failed to delete playwright port file");
396
+ }
397
+ }
398
+
399
+ function readPortFile(instanceKey: string): number | null {
400
+ try {
401
+ const port = Number.parseInt(
402
+ readFileSync(join(managerHost.portsDir, portFileName(instanceKey)), "utf8").trim(),
403
+ 10,
404
+ );
405
+ return Number.isInteger(port) ? port : null;
406
+ } catch {
407
+ return null;
408
+ }
409
+ }
410
+
411
+ const MAX_IDLE_MS = 2 * 60 * 60 * 1000; // 2 hours idle → eligible for eviction
412
+
413
+ interface PlaywrightInstance {
414
+ process: ChildProcess;
415
+ port: number;
416
+ ownerId: string;
417
+ startedAt: number;
418
+ lastUsedAt: number;
419
+ capability: string;
420
+ vaultBroker: BrowserVaultBrokerHandle;
421
+ }
422
+
423
+ const instances = new Map<string, PlaywrightInstance>();
424
+
425
+ function assertInstanceOwner(instanceKey: string, ownerId: string): void {
426
+ const existing = instances.get(instanceKey);
427
+ if (existing && existing.ownerId !== ownerId) {
428
+ throw new Error(
429
+ `Playwright profile binding owner changed for "${instanceKey}" (${existing.ownerId} -> ${ownerId})`,
430
+ );
431
+ }
432
+ }
433
+
434
+ // Track used ports to avoid collisions
435
+ const usedPorts = new Set<number>();
436
+
437
+ // Prevent concurrent spawns for the same key
438
+ const spawning = new Map<string, Promise<number | null>>();
439
+
440
+ export interface PlaywrightMaintenanceControl {
441
+ /** Stop one of the locked instances before mutating its profile directory. */
442
+ stopInstance(instanceKey: string): Promise<boolean>;
443
+ }
444
+
445
+ /** Serialize destructive profile maintenance with normal browser startup. */
446
+ export async function withPlaywrightInstanceMaintenance<T>(
447
+ rawKeys: string[],
448
+ operation: (control: PlaywrightMaintenanceControl) => Promise<T>,
449
+ ): Promise<T> {
450
+ const keys = [...new Set(rawKeys)].sort();
451
+ const lockedKeys = new Set(keys);
452
+ for (;;) {
453
+ const pending = keys
454
+ .map((key) => spawning.get(key))
455
+ .filter((promise): promise is Promise<number | null> => promise !== undefined);
456
+ if (pending.length > 0) {
457
+ await Promise.allSettled(pending);
458
+ continue;
459
+ }
460
+
461
+ let releaseBarrier!: () => void;
462
+ const barrier = new Promise<number | null>((resolveBarrier) => {
463
+ releaseBarrier = () => resolveBarrier(null);
464
+ });
465
+ // No await occurs between the registry check and registration, so another
466
+ // event-loop task cannot acquire any of these keys concurrently.
467
+ for (const key of keys) spawning.set(key, barrier);
468
+
469
+ try {
470
+ return await operation({
471
+ async stopInstance(instanceKey) {
472
+ if (!lockedKeys.has(instanceKey)) {
473
+ throw new Error(`Playwright maintenance does not own instance "${instanceKey}"`);
474
+ }
475
+ const process = instances.get(instanceKey)?.process;
476
+ if (!process) return false;
477
+ killInstance(instanceKey);
478
+ if (!(await waitForChildProcessExit(process, 3000))) {
479
+ logger.warn(
480
+ { instanceKey, pid: process.pid },
481
+ "Playwright MCP ignored SIGTERM during profile maintenance",
482
+ );
483
+ try {
484
+ process.kill("SIGKILL");
485
+ } catch (error) {
486
+ logger.warn(
487
+ { err: error, instanceKey, pid: process.pid },
488
+ "Failed to SIGKILL Playwright MCP during profile maintenance",
489
+ );
490
+ }
491
+ await waitForChildProcessExit(process, 1000);
492
+ }
493
+ return true;
494
+ },
495
+ });
496
+ } finally {
497
+ for (const key of keys) {
498
+ if (spawning.get(key) === barrier) spawning.delete(key);
499
+ }
500
+ releaseBarrier();
501
+ }
502
+ }
503
+ }
504
+
505
+ /** Stop one managed instance under the same serialization used by startup and profile mutation. */
506
+ export function stopPlaywrightInstance(instanceKey: string): Promise<boolean> {
507
+ return withPlaywrightInstanceMaintenance([instanceKey], ({ stopInstance }) =>
508
+ stopInstance(instanceKey),
509
+ );
510
+ }
511
+
512
+ /** Run owner-aware named-profile maintenance under one lifecycle barrier. */
513
+ export function withPlaywrightProfileMaintenance<T>(
514
+ ownerId: string,
515
+ rawProfile: string,
516
+ operation: (
517
+ binding: PlaywrightProfileBinding,
518
+ control: PlaywrightMaintenanceControl,
519
+ ) => Promise<T>,
520
+ ): Promise<T> {
521
+ const binding = resolvePlaywrightProfileBinding(ownerId, rawProfile);
522
+ return withPlaywrightInstanceMaintenance([binding.instanceKey], async (control) => {
523
+ assertInstanceOwner(binding.instanceKey, binding.ownerId);
524
+ return operation(binding, control);
525
+ });
526
+ }
527
+
528
+ /** Stop a named profile before deleting or replacing its host-managed data directory. */
529
+ export function stopPlaywrightProfile(ownerId: string, rawProfile: string): Promise<boolean> {
530
+ return withPlaywrightProfileMaintenance(ownerId, rawProfile, (binding, { stopInstance }) =>
531
+ stopInstance(binding.instanceKey),
532
+ );
533
+ }
534
+
535
+ export interface RemovePlaywrightProfileDataResult {
536
+ dataDir: string;
537
+ processStopped: boolean;
538
+ dataRemoved: boolean;
539
+ }
540
+
541
+ export interface RemovePlaywrightProfileDataOptions {
542
+ /** Revalidate external ownership immediately before the synchronous removal. */
543
+ beforeRemove?: () => void;
544
+ /** Commit external metadata before releasing the profile lifecycle barrier. */
545
+ afterRemove?: () => void;
546
+ }
547
+
548
+ /** Stop all exact-profile processes and remove its data through the configured host boundary. */
549
+ export function removePlaywrightProfileData(
550
+ ownerId: string,
551
+ rawProfile: string,
552
+ options: RemovePlaywrightProfileDataOptions = {},
553
+ ): Promise<RemovePlaywrightProfileDataResult> {
554
+ return withPlaywrightProfileMaintenance(
555
+ ownerId,
556
+ rawProfile,
557
+ async (binding, { stopInstance }) => {
558
+ const dataDir = resolveUserDataDir(binding.instanceKey);
559
+ const processStopped = await stopInstance(binding.instanceKey);
560
+ managerHost.cleanupBrowserProcessesForDataDir(dataDir);
561
+ deletePortFile(binding.instanceKey);
562
+ options.beforeRemove?.();
563
+ const removeProfileDataDir = managerHost.removeProfileDataDir;
564
+ if (!removeProfileDataDir) {
565
+ throw new Error("Browser profile deletion is not configured for this host.");
566
+ }
567
+ const dataRemoved = removeProfileDataDir(dataDir);
568
+ options.afterRemove?.();
569
+ return { dataDir, processStopped, dataRemoved };
570
+ },
571
+ );
572
+ }
573
+
574
+ // A shared profile may have several concurrent turns. Reference counts keep an
575
+ // idle sweep from evicting the process until every borrower has finished.
576
+ const pinnedInstances = new Map<string, number>();
577
+
578
+ export function pinPlaywrightInstance(instanceKey: string): void {
579
+ pinnedInstances.set(instanceKey, (pinnedInstances.get(instanceKey) ?? 0) + 1);
580
+ }
581
+
582
+ export function unpinPlaywrightInstance(instanceKey: string): void {
583
+ const count = pinnedInstances.get(instanceKey);
584
+ if (count === undefined) return;
585
+ if (count <= 1) pinnedInstances.delete(instanceKey);
586
+ else pinnedInstances.set(instanceKey, count - 1);
587
+ }
588
+
589
+ export function getPlaywrightCapability(instanceKey: string): string | undefined {
590
+ return instances.get(instanceKey)?.capability;
591
+ }
592
+
593
+ /** Resolve a live browser capability back to its owning user. */
594
+ export function resolvePlaywrightCapabilityOwner(capability: string): string | undefined {
595
+ if (!capability) return undefined;
596
+ const provided = Buffer.from(capability);
597
+ for (const instance of instances.values()) {
598
+ const expected = Buffer.from(instance.capability);
599
+ if (provided.length === expected.length && timingSafeEqual(provided, expected)) {
600
+ return instance.ownerId;
601
+ }
602
+ }
603
+ return undefined;
604
+ }
605
+
606
+ /** Run the configured host's path-bounded orphan sweep against current live instances. */
607
+ export function reapPlaywrightOrphans(): void {
608
+ managerHost.reapOrphanBrowsers([...instances.keys()].map(resolveUserDataDir));
609
+ }
610
+
611
+ // --- Browser MCP failure notification callback ---
612
+ // Fired when a managed process fails or its transport becomes unhealthy.
613
+ // Intentional cleanup paths do not notify consumers.
614
+ export interface PlaywrightFailure {
615
+ reason: "exit" | "process-error" | "unhealthy";
616
+ code?: number | null;
617
+ error?: string;
618
+ }
619
+
620
+ type PlaywrightFailureHandler = (instanceKey: string, failure: PlaywrightFailure) => void;
621
+ const playwrightFailureHandlers = new Set<PlaywrightFailureHandler>();
622
+ export function onPlaywrightFailure(handler: PlaywrightFailureHandler): () => void {
623
+ playwrightFailureHandlers.add(handler);
624
+ return () => playwrightFailureHandlers.delete(handler);
625
+ }
626
+
627
+ function notifyPlaywrightFailure(instanceKey: string, failure: PlaywrightFailure): void {
628
+ for (const handler of playwrightFailureHandlers) {
629
+ try {
630
+ handler(instanceKey, failure);
631
+ } catch (err) {
632
+ logger.warn({ err, instanceKey, failure }, "Playwright failure handler failed");
633
+ }
634
+ }
635
+ }
636
+
637
+ /**
638
+ * Evict the oldest idle instance to free a port.
639
+ * Returns the evicted port, or null when no instance was eligible.
640
+ */
641
+ function evictIdleInstance(): number | null {
642
+ const now = Date.now();
643
+ const oldestKey = selectIdleEvictionKey(
644
+ instances,
645
+ pinnedInstances.keys(),
646
+ spawning.keys(),
647
+ now,
648
+ MAX_IDLE_MS,
649
+ );
650
+ if (oldestKey) {
651
+ const instance = instances.get(oldestKey);
652
+ if (!instance) return null;
653
+ const idleMin = ((now - instance.lastUsedAt) / 60000).toFixed(0);
654
+ logger.info({ key: oldestKey, idleMin }, "Evicting idle playwright instance");
655
+ killInstance(oldestKey);
656
+ return instance.port;
657
+ }
658
+ return null;
659
+ }
660
+
661
+ /**
662
+ * Find an available port without depending on platform process-inspection tools.
663
+ * If all ports are taken, evicts the oldest idle instance.
664
+ */
665
+ async function allocatePort(): Promise<number> {
666
+ const port = await reserveAvailableLoopbackPort(
667
+ managerHost.basePort,
668
+ managerHost.maxPort,
669
+ usedPorts,
670
+ async (candidate) => {
671
+ // A real loopback bind probe is portable and fail-closed. In particular,
672
+ // a missing `lsof` must never make an occupied port appear available.
673
+ const occupied = await isPortInUse(candidate);
674
+ if (occupied) logger.warn({ port: candidate }, "Port occupied by external process, skipping");
675
+ return occupied;
676
+ },
677
+ );
678
+ if (port !== null) return port;
679
+
680
+ // All ports used — try evicting an idle instance
681
+ const evictedPort = evictIdleInstance();
682
+ if (evictedPort !== null) {
683
+ // SIGTERM only requests shutdown. Do not hand the port to a replacement
684
+ // until the old listener is actually gone, and recheck every candidate in
685
+ // case another allocator claimed a different port while we were waiting.
686
+ await waitForPortRelease(evictedPort);
687
+ return allocatePort();
688
+ }
689
+
690
+ throw new Error(
691
+ `No available ports for Playwright MCP (${instances.size} active instances, range ${managerHost.basePort}-${managerHost.maxPort})`,
692
+ );
693
+ }
694
+
695
+ function releasePort(port: number) {
696
+ usedPorts.delete(port);
697
+ }
698
+
699
+ function defaultProfileDir(_ownerId: string, profile: string): string {
700
+ return resolve(BROWSER_PROFILES_DIR, profile);
701
+ }
702
+
703
+ /** Resolve the shared profile userDataDir for an instanceKey. */
704
+ function resolveUserDataDir(instanceKey: string): string {
705
+ return managerHost.resolveInstanceDataDir(instanceKey);
706
+ }
707
+
708
+ /**
709
+ * Kill and clean up a specific instance.
710
+ * Also kills Chrome child processes and cleans up Singleton files.
711
+ * @param keepPort - If true, don't release the port (for same-port respawn).
712
+ */
713
+ function killInstance(instanceKey: string, opts?: { keepPort?: boolean }) {
714
+ const inst = instances.get(instanceKey);
715
+ if (!inst) return;
716
+
717
+ // Kill Chrome children first (before killing the MCP server)
718
+ if (inst.process.pid) {
719
+ killProcessTreeChildren(inst.process.pid);
720
+ }
721
+
722
+ try {
723
+ inst.process.kill("SIGTERM");
724
+ } catch (e) {
725
+ logger.warn({ err: e, instanceKey }, "Failed to kill playwright instance");
726
+ }
727
+ void inst.vaultBroker.close();
728
+
729
+ // Drop the spawn-time error/exit handlers. Cleanup is done synchronously
730
+ // here, so the late-firing listeners only add duplicate instances.delete()
731
+ // calls and keep the process reference alive until exit. Removing them
732
+ // also lets callers (e.g. killAllPlaywright) attach their own exit waiter
733
+ // without the spawn handler racing against it.
734
+ inst.process.removeAllListeners("error");
735
+ inst.process.removeAllListeners("exit");
736
+
737
+ cleanSingletonFiles(resolveUserDataDir(instanceKey));
738
+
739
+ if (!opts?.keepPort) releasePort(inst.port);
740
+ instances.delete(instanceKey);
741
+ deletePortFile(instanceKey);
742
+ logger.info(
743
+ { instanceKey, port: inst.port, keepPort: !!opts?.keepPort },
744
+ "Killed Playwright MCP (with cleanup)",
745
+ );
746
+ }
747
+
748
+ const PLAYWRIGHT_STARTUP_STDERR_LIMIT = 8 * 1024;
749
+
750
+ function captureBoundedStderr(proc: ChildProcess): () => string {
751
+ let tail = Buffer.alloc(0);
752
+ proc.stderr?.on("data", (chunk: Buffer | string) => {
753
+ const next = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
754
+ tail = Buffer.concat([tail, next]);
755
+ if (tail.byteLength > PLAYWRIGHT_STARTUP_STDERR_LIMIT) {
756
+ tail = tail.subarray(tail.byteLength - PLAYWRIGHT_STARTUP_STDERR_LIMIT);
757
+ }
758
+ });
759
+ return () => tail.toString("utf8").trim();
760
+ }
761
+
762
+ export function watchChildStartup(
763
+ proc: ChildProcess,
764
+ stderrTail: () => string,
765
+ ): { failure: Promise<never>; stop: () => void } {
766
+ let stopped = false;
767
+ let rejectFailure: (error: Error) => void = () => undefined;
768
+ const diagnostics = () => {
769
+ const stderr = stderrTail();
770
+ return stderr ? `\nstderr (last ${PLAYWRIGHT_STARTUP_STDERR_LIMIT} bytes):\n${stderr}` : "";
771
+ };
772
+ const onError = (error: Error) => {
773
+ rejectFailure(
774
+ new Error(`Playwright MCP failed to spawn: ${error.message}${diagnostics()}`, {
775
+ cause: error,
776
+ }),
777
+ );
778
+ };
779
+ const onExit = (code: number | null, signal: NodeJS.Signals | null) => {
780
+ rejectFailure(
781
+ new Error(
782
+ `Playwright MCP exited during startup (code=${code ?? "null"}, signal=${signal ?? "null"})${diagnostics()}`,
783
+ ),
784
+ );
785
+ };
786
+ const failure = new Promise<never>((_resolve, reject) => {
787
+ rejectFailure = reject;
788
+ proc.once("error", onError);
789
+ proc.once("exit", onExit);
790
+ });
791
+ const stop = () => {
792
+ if (stopped) return;
793
+ stopped = true;
794
+ proc.off("error", onError);
795
+ proc.off("exit", onExit);
796
+ };
797
+ return { failure, stop };
798
+ }
799
+
800
+ /**
801
+ * Spawn a browser MCP HTTP server for a shared named profile. The profile
802
+ * identity is encoded in `instanceKey` and decoded inside `resolveUserDataDir`.
803
+ */
804
+ /**
805
+ * Spawn a Playwright MCP process for the given instanceKey.
806
+ * @param instanceKey Unique key identifying this instance.
807
+ * @param ownerId Canonical profile owner ID (stored in the instance record).
808
+ * @param reservedPort When provided the process binds to this already-reserved
809
+ * port (restart path). When omitted a fresh port is allocated.
810
+ */
811
+ async function spawnPlaywright(
812
+ instanceKey: string,
813
+ ownerId: string,
814
+ reservedPort?: number,
815
+ browserBin = managerHost.browserBin,
816
+ ): Promise<number> {
817
+ if (!managerHost.browserRsBin) {
818
+ throw new Error("Browser.rs is unavailable or below the minimum secure version");
819
+ }
820
+ const userDataDir = resolveUserDataDir(instanceKey);
821
+ const port = reservedPort ?? (await allocatePort());
822
+ mkdirSync(userDataDir, { recursive: true });
823
+
824
+ const mcpArgs = browserRsArgs(instanceKey, port, userDataDir);
825
+ // Pass the egress proxy to the child through the environment rather than
826
+ // argv so the credentials never surface in `ps`/`/proc` command lines. The
827
+ // Browser.rs currently rejects this configuration rather than bypassing it.
828
+ const proxy = managerHost.resolveProxy();
829
+ if (proxy) {
830
+ releasePort(port);
831
+ throw new Error("Browser.rs managed mode does not support authenticated egress proxies");
832
+ }
833
+ const capability = randomBytes(32).toString("hex");
834
+ const spawnNonce = randomBytes(32).toString("hex");
835
+ let vaultBroker: BrowserVaultBrokerHandle;
836
+ try {
837
+ vaultBroker = await createBrowserVaultBroker(ownerId);
838
+ } catch (error) {
839
+ releasePort(port);
840
+ throw error;
841
+ }
842
+ const childEnv = {
843
+ ...managerHost.createChildEnvironment({
844
+ instanceKey,
845
+ ownerId,
846
+ capability,
847
+ proxy,
848
+ browserRsBin: managerHost.browserRsBin,
849
+ environment: process.env,
850
+ }),
851
+ AB_MANAGED: "1",
852
+ AB_HTTP_CAPABILITY: capability,
853
+ AB_SPAWN_NONCE: spawnNonce,
854
+ AB_SECRET_BROKER_SOCKET: vaultBroker.socketPath,
855
+ AB_SECRET_BROKER_TOKEN: vaultBroker.token,
856
+ };
857
+ // Managed Browser.rs authenticates owner-scoped transports with this root
858
+ // capability. Product hooks may add launch details but cannot remove it.
859
+ const command = browserBin.endsWith(".mjs") ? process.execPath : browserBin;
860
+ const args = browserBin.endsWith(".mjs") ? [browserBin, ...mcpArgs] : mcpArgs;
861
+ let spawnSpec: HeadedPlaywrightSpawnSpec;
862
+ try {
863
+ spawnSpec = resolveHeadedPlaywrightSpawn(command, args, { environment: childEnv });
864
+ } catch (err) {
865
+ await vaultBroker.close();
866
+ releasePort(port);
867
+ throw err;
868
+ }
869
+ let proc: ChildProcess;
870
+ try {
871
+ proc = spawn(spawnSpec.command, spawnSpec.args, {
872
+ stdio: ["ignore", "ignore", "pipe"],
873
+ detached: false,
874
+ env: childEnv,
875
+ // The managed browser server is long-lived background plumbing; without
876
+ // this Windows opens a console window for it. Ignored on POSIX.
877
+ windowsHide: true,
878
+ });
879
+ } catch (err) {
880
+ await vaultBroker.close();
881
+ releasePort(port);
882
+ throw err;
883
+ }
884
+ const stderrTail = captureBoundedStderr(proc);
885
+ const startup = watchChildStartup(proc, stderrTail);
886
+
887
+ // When the MCP dies on its own (crash / OOM), its Chrome subtree is reparented
888
+ // to init and escapes the tracked-instance map. Reap it by user-data-dir here
889
+ // so a crash can't leak an orphan Chrome that keeps holding memory (the exact
890
+ // cascade that piles up dozens of zombies under pressure). killInstance()
891
+ // removes these listeners before signalling, so this only runs on real deaths.
892
+ const reapCrashedBrowser = () => {
893
+ const userDataDir = resolveUserDataDir(instanceKey);
894
+ managerHost.cleanupBrowserProcessesForDataDir(userDataDir);
895
+ cleanSingletonFiles(userDataDir);
896
+ };
897
+
898
+ proc.once("error", (err) => {
899
+ logger.error({ err, instanceKey, stderr: stderrTail() || undefined }, "Playwright MCP error");
900
+ if (instances.get(instanceKey)?.process === proc) {
901
+ releasePort(port);
902
+ instances.delete(instanceKey);
903
+ void vaultBroker.close();
904
+ reapCrashedBrowser();
905
+ notifyPlaywrightFailure(instanceKey, {
906
+ reason: "process-error",
907
+ error: err instanceof Error ? err.message : String(err),
908
+ });
909
+ }
910
+ });
911
+
912
+ proc.once("exit", (code) => {
913
+ logger.info({ instanceKey, code, stderr: stderrTail() || undefined }, "Playwright MCP exited");
914
+ // `wasOurs` distinguishes a crash from our own killInstance(): the latter
915
+ // calls removeAllListeners("exit") + instances.delete() BEFORE the kill
916
+ // signal lands, so this listener either doesn't fire or sees wasOurs=false.
917
+ // wasOurs=true here therefore implies the MCP died on its own — Claude
918
+ // SDK queries waiting on its tool results need to be aborted.
919
+ const wasOurs = instances.get(instanceKey)?.process === proc;
920
+ if (wasOurs) {
921
+ releasePort(port);
922
+ instances.delete(instanceKey);
923
+ void vaultBroker.close();
924
+ reapCrashedBrowser();
925
+ notifyPlaywrightFailure(instanceKey, { reason: "exit", code });
926
+ }
927
+ });
928
+
929
+ const now = Date.now();
930
+ instances.set(instanceKey, {
931
+ process: proc,
932
+ port,
933
+ ownerId,
934
+ startedAt: now,
935
+ lastUsedAt: now,
936
+ capability,
937
+ vaultBroker,
938
+ });
939
+
940
+ let startupError: Error | undefined;
941
+ let ready = false;
942
+ try {
943
+ ready = await Promise.race([
944
+ (async () =>
945
+ (await waitForServer(port, spawnNonce, 10_000)) &&
946
+ (await supportsOwnerCleanup(port, capability)) &&
947
+ (await probePlaywrightMcpTransports(port, capability)))(),
948
+ startup.failure,
949
+ ]);
950
+ } catch (error) {
951
+ startupError = error instanceof Error ? error : new Error(String(error));
952
+ } finally {
953
+ startup.stop();
954
+ }
955
+ if (ready && !isLiveOwnedChildProcess(instances.get(instanceKey), proc)) {
956
+ ready = false;
957
+ startupError = new Error(
958
+ `Playwright MCP exited after readiness but before publication on port ${port}` +
959
+ (stderrTail() ? `\nstderr:\n${stderrTail()}` : ""),
960
+ );
961
+ }
962
+ if (!ready) {
963
+ const exitCode = proc.exitCode;
964
+ killInstance(instanceKey);
965
+ if (startupError) throw startupError;
966
+ throw new Error(
967
+ `Playwright MCP failed health check after spawn on port ${port}` +
968
+ (exitCode === null ? "" : ` (exitCode=${exitCode})`) +
969
+ (stderrTail() ? `\nstderr:\n${stderrTail()}` : ""),
970
+ );
971
+ }
972
+ writePortFile(instanceKey, port);
973
+ logger.info(
974
+ { instanceKey, port, pid: proc.pid, ready, virtualDisplay: spawnSpec.virtualDisplay },
975
+ "Playwright MCP started",
976
+ );
977
+ return port;
978
+ }
979
+
980
+ async function supportsOwnerCleanup(port: number, capability: string): Promise<boolean> {
981
+ try {
982
+ const query = new URLSearchParams({ owner: "__negotium_capability_probe__" });
983
+ const response = await fetch(`http://127.0.0.1:${port}/owners?${query}`, {
984
+ method: "DELETE",
985
+ headers: {
986
+ "X-Browser-Capability": capability,
987
+ },
988
+ signal: AbortSignal.timeout(2000),
989
+ });
990
+ await response.body?.cancel();
991
+ return response.ok;
992
+ } catch {
993
+ return false;
994
+ }
995
+ }
996
+
997
+ /**
998
+ * Ensure a healthy browser MCP server is running for this topic's profile.
999
+ * Topics assigned to the same profile reuse one process and data directory.
1000
+ * - If running and healthy → reuse
1001
+ * - If running but unhealthy → kill and respawn
1002
+ * - If not running → spawn
1003
+ */
1004
+ export async function ensurePlaywright(userId: string, topic?: string): Promise<number> {
1005
+ const binding = resolvePlaywrightTopicBinding(userId, topic);
1006
+ const { instanceKey, ownerId } = binding;
1007
+
1008
+ // If a spawn/restart is already in progress for this key, wait for it
1009
+ const inProgress = spawning.get(instanceKey);
1010
+ if (inProgress) {
1011
+ const port = await inProgress;
1012
+ assertInstanceOwner(instanceKey, ownerId);
1013
+ if (port !== null) return port;
1014
+ // Restart failed — re-enter: by now another caller may have registered a
1015
+ // newer attempt to join, otherwise we start one ourselves.
1016
+ return ensurePlaywright(userId, topic);
1017
+ }
1018
+
1019
+ // The ENTIRE health-check → kill → spawn sequence lives inside the spawning
1020
+ // promise. The old shape awaited isHealthy() between the guard check and
1021
+ // spawning.set(), so two concurrent callers could both pass the guard: one
1022
+ // would killInstance() the instance the other had just spawned, or both
1023
+ // would spawn and the second instances.set() orphaned the first process
1024
+ // (its port leaked from usedPorts until restart). With no await between
1025
+ // spawning.get() above and spawning.set() below, the guard is airtight on
1026
+ // a single-threaded event loop.
1027
+ const promise = (async (): Promise<number> => {
1028
+ const existing = instances.get(instanceKey);
1029
+ assertInstanceOwner(instanceKey, ownerId);
1030
+
1031
+ if (existing && !existing.process.killed && existing.process.exitCode === null) {
1032
+ if (
1033
+ (await probePlaywrightMcpTransports(existing.port, existing.capability)) &&
1034
+ !(await browserTransportLost(existing.port))
1035
+ ) {
1036
+ existing.lastUsedAt = Date.now();
1037
+ return existing.port;
1038
+ }
1039
+ logger.warn({ instanceKey }, "Playwright MCP unresponsive, restarting");
1040
+ const oldPort = existing.port;
1041
+ killInstance(instanceKey);
1042
+ notifyPlaywrightFailure(instanceKey, { reason: "unhealthy" });
1043
+ await waitForPortRelease(oldPort);
1044
+ cleanSingletonFiles(resolveUserDataDir(instanceKey));
1045
+ } else if (existing) {
1046
+ releasePort(existing.port);
1047
+ instances.delete(instanceKey);
1048
+ cleanSingletonFiles(resolveUserDataDir(instanceKey));
1049
+ notifyPlaywrightFailure(instanceKey, {
1050
+ reason: "exit",
1051
+ code: existing.process.exitCode,
1052
+ });
1053
+ }
1054
+
1055
+ return spawnPlaywright(instanceKey, ownerId);
1056
+ })().finally(() => spawning.delete(instanceKey));
1057
+ spawning.set(instanceKey, promise);
1058
+ return promise;
1059
+ }
1060
+
1061
+ async function waitForPortRelease(port: number, timeoutMs = 3000): Promise<void> {
1062
+ const start = Date.now();
1063
+ while (Date.now() - start < timeoutMs) {
1064
+ if (!(await isPortInUse(port))) return;
1065
+ await delay(200);
1066
+ }
1067
+ }
1068
+
1069
+ /** Start or reuse a named shared profile before assigning more topics to it. */
1070
+ export async function ensureBrowserProfile(ownerId: string, rawProfile: string): Promise<number> {
1071
+ const binding = resolvePlaywrightProfileBinding(ownerId, rawProfile);
1072
+ const instanceKey = binding.instanceKey;
1073
+ const inProgress = spawning.get(instanceKey);
1074
+ if (inProgress) {
1075
+ const port = await inProgress;
1076
+ assertInstanceOwner(instanceKey, binding.ownerId);
1077
+ const capability = instances.get(instanceKey)?.capability;
1078
+ if (port !== null && capability && (await probePlaywrightMcpTransports(port, capability))) {
1079
+ return port;
1080
+ }
1081
+ if (port === null) return ensureBrowserProfile(ownerId, rawProfile);
1082
+ throw new Error(`Browser profile "${rawProfile}" failed to start.`);
1083
+ }
1084
+
1085
+ const promise = (async (): Promise<number> => {
1086
+ const publishedPort = readPortFile(instanceKey);
1087
+ const existing = instances.get(instanceKey);
1088
+ assertInstanceOwner(instanceKey, binding.ownerId);
1089
+ if (publishedPort !== null && !existing) {
1090
+ // A port file without an in-memory instance belongs to a previous runtime.
1091
+ // Its per-process capability and ChildProcess handle cannot be recovered,
1092
+ // so adopting it would bypass owner cleanup and lifecycle tracking. Reap
1093
+ // only the browser serving this exact profile, then spawn a tracked one.
1094
+ logger.warn(
1095
+ { instanceKey, publishedPort },
1096
+ "Recycling untracked browser profile process from stale port file",
1097
+ );
1098
+ managerHost.cleanupBrowserProcessesForDataDir(resolveUserDataDir(instanceKey));
1099
+ await waitForPortRelease(publishedPort);
1100
+ deletePortFile(instanceKey);
1101
+ }
1102
+
1103
+ if (existing && !existing.process.killed && existing.process.exitCode === null) {
1104
+ if (
1105
+ (await probePlaywrightMcpTransports(existing.port, existing.capability)) &&
1106
+ !(await browserTransportLost(existing.port))
1107
+ ) {
1108
+ existing.lastUsedAt = Date.now();
1109
+ return existing.port;
1110
+ }
1111
+ const oldPort = existing.port;
1112
+ killInstance(instanceKey);
1113
+ notifyPlaywrightFailure(instanceKey, { reason: "unhealthy" });
1114
+ await waitForPortRelease(oldPort);
1115
+ cleanSingletonFiles(resolveUserDataDir(instanceKey));
1116
+ } else if (existing) {
1117
+ releasePort(existing.port);
1118
+ instances.delete(instanceKey);
1119
+ cleanSingletonFiles(resolveUserDataDir(instanceKey));
1120
+ notifyPlaywrightFailure(instanceKey, {
1121
+ reason: "exit",
1122
+ code: existing.process.exitCode,
1123
+ });
1124
+ }
1125
+ const port = await spawnPlaywright(instanceKey, binding.ownerId);
1126
+ const capability = instances.get(instanceKey)?.capability;
1127
+ if (!capability || !(await probePlaywrightMcpTransports(port, capability))) {
1128
+ killInstance(instanceKey);
1129
+ throw new Error(`Browser profile "${rawProfile}" did not pass its health check.`);
1130
+ }
1131
+ return port;
1132
+ })().finally(() => spawning.delete(instanceKey));
1133
+ spawning.set(instanceKey, promise);
1134
+ return promise;
1135
+ }
1136
+
1137
+ /** Close only one topic/job's tabs while preserving the shared profile. */
1138
+ export async function closeBrowserOwnerTabs(
1139
+ ownerId: string,
1140
+ rawProfile: string,
1141
+ owner: string,
1142
+ ): Promise<number> {
1143
+ return closeBindingOwnerTabs(resolvePlaywrightProfileBinding(ownerId, rawProfile), owner);
1144
+ }
1145
+
1146
+ /** Close a deleted topic's tabs on the browser its turns used. */
1147
+ export function closeTopicBrowserTabs(userId: string, topicId: string): Promise<number> {
1148
+ const connectPort = getTopicBrowserConnectPort(topicId);
1149
+ const binding =
1150
+ connectPort === undefined
1151
+ ? resolvePlaywrightProfileBinding(
1152
+ getBrowserProfileOwner(topicId, userId),
1153
+ getTopicBrowserProfile(topicId),
1154
+ )
1155
+ : connectBinding(connectPort);
1156
+ return closeBindingOwnerTabs(binding, `topic:${topicId}`);
1157
+ }
1158
+
1159
+ async function closeBindingOwnerTabs(
1160
+ binding: PlaywrightProfileBinding,
1161
+ owner: string,
1162
+ ): Promise<number> {
1163
+ const instanceKey = binding.instanceKey;
1164
+ const inProgress = spawning.get(instanceKey);
1165
+ if (inProgress) await inProgress;
1166
+ assertInstanceOwner(instanceKey, binding.ownerId);
1167
+ const instance = instances.get(instanceKey);
1168
+ if (!instance) return 0;
1169
+ const port = instance.port;
1170
+
1171
+ const query = new URLSearchParams({ owner });
1172
+ const response = await fetch(`http://127.0.0.1:${port}/owners?${query}`, {
1173
+ method: "DELETE",
1174
+ headers: {
1175
+ "X-Browser-Capability": instance.capability,
1176
+ },
1177
+ signal: AbortSignal.timeout(5000),
1178
+ });
1179
+ if (!response.ok) throw new Error(`browser MCP owner cleanup failed (${response.status})`);
1180
+ const result = (await response.json()) as { closed?: number };
1181
+ return typeof result.closed === "number" ? result.closed : 0;
1182
+ }
1183
+
1184
+ /**
1185
+ * Poll until the SSE server responds, or timeout.
1186
+ * Returns true if the server is healthy, false on timeout.
1187
+ */
1188
+ /**
1189
+ * Ask the engine whether Chrome is still attached.
1190
+ *
1191
+ * Deliberately fails open: a refused, slow, or malformed `/health` says
1192
+ * nothing about CDP, and treating that as a fault would kill instances for
1193
+ * unrelated reasons. Returns true only when the engine positively reports a
1194
+ * launched browser with a dead transport.
1195
+ */
1196
+ async function browserTransportLost(port: number): Promise<boolean> {
1197
+ try {
1198
+ const response = await fetch(`http://127.0.0.1:${port}/health`, {
1199
+ signal: AbortSignal.timeout(1000),
1200
+ });
1201
+ if (!response.ok) {
1202
+ await response.body?.cancel();
1203
+ return false;
1204
+ }
1205
+ return browserCdpIsLost(await response.json());
1206
+ } catch {
1207
+ return false;
1208
+ }
1209
+ }
1210
+
1211
+ async function waitForServer(
1212
+ port: number,
1213
+ expectedSpawnNonce: string,
1214
+ timeoutMs: number,
1215
+ ): Promise<boolean> {
1216
+ const start = Date.now();
1217
+ while (Date.now() - start < timeoutMs) {
1218
+ try {
1219
+ const response = await fetch(`http://127.0.0.1:${port}/health`, {
1220
+ signal: AbortSignal.timeout(1000),
1221
+ });
1222
+ if (response.ok) {
1223
+ const health: unknown = await response.json();
1224
+ if (matchesSpawnedBrowserHealth(health, expectedSpawnNonce)) {
1225
+ return true;
1226
+ }
1227
+ } else {
1228
+ await response.body?.cancel();
1229
+ }
1230
+ } catch {
1231
+ // The owned child may still be loading or binding its listener.
1232
+ }
1233
+ await delay(300);
1234
+ }
1235
+ logger.warn({ port, timeoutMs }, "Playwright MCP not ready before timeout");
1236
+ return false;
1237
+ }
1238
+
1239
+ /**
1240
+ * Kill all Playwright MCP instances for a specific user.
1241
+ */
1242
+ export function killPlaywrightForUser(userId: string): void {
1243
+ logger.info({ userId }, "killPlaywrightForUser: no user-scoped browser profile to kill");
1244
+ }
1245
+
1246
+ /**
1247
+ * Legacy API retained for callers that still request topic-scoped shutdown.
1248
+ * Shared profiles cannot be killed through a single topic.
1249
+ */
1250
+ export function killPlaywrightForTopic(userId: string, topic: string): void {
1251
+ logger.info(
1252
+ { userId, topic },
1253
+ "killPlaywrightForTopic skipped: topic uses a shared browser profile",
1254
+ );
1255
+ }
1256
+
1257
+ /**
1258
+ * Resolve the on-disk Playwright user-data-dir for a topic/profile id.
1259
+ * Useful for external callers that need to inspect / copy / delete the dir without
1260
+ * touching the running process.
1261
+ */
1262
+ export function resolveTopicProfileDir(userId: string, topic: string): string {
1263
+ return resolveUserDataDir(makeInstanceKey(userId, topic));
1264
+ }
1265
+
1266
+ export interface CloneProfileResult {
1267
+ copied: boolean;
1268
+ srcDir: string;
1269
+ dstDir: string;
1270
+ /** Set when `copied=false` to explain why (e.g. src-missing, same-dir, copy-failed:…) */
1271
+ reason?: string;
1272
+ }
1273
+
1274
+ /**
1275
+ * Assign a child to its parent's shared profile when owners match. Browser
1276
+ * credentials never cross an owner boundary.
1277
+ *
1278
+ * Safety: if the parent instance is currently running, we kill it first to flush
1279
+ * SQLite WAL state to disk, then copy. The parent is NOT respawned here — the
1280
+ * next user message on the parent topic will trigger ensurePlaywright() to bring
1281
+ * it back. This avoids a race where copy and live writes interleave.
1282
+ *
1283
+ * Copy strategy:
1284
+ * - macOS APFS: `cp -cR` triggers clonefile() (metadata-only, ms-level).
1285
+ * - Other platforms, or if clonefile fails: regular recursive copy.
1286
+ */
1287
+ export async function cloneProfileForChild(opts: {
1288
+ userId: string;
1289
+ srcTopic: string;
1290
+ dstTopic: string;
1291
+ }): Promise<CloneProfileResult> {
1292
+ const srcOwner = getBrowserProfileOwner(opts.srcTopic, opts.userId);
1293
+ const dstOwner = getBrowserProfileOwner(opts.dstTopic, opts.userId);
1294
+ if (srcOwner !== dstOwner) {
1295
+ const srcBinding = resolvePlaywrightProfileBinding(
1296
+ srcOwner,
1297
+ getTopicBrowserProfile(opts.srcTopic),
1298
+ );
1299
+ const dstBinding = resolvePlaywrightProfileBinding(
1300
+ dstOwner,
1301
+ getTopicBrowserProfile(opts.dstTopic),
1302
+ );
1303
+ return {
1304
+ copied: false,
1305
+ srcDir: resolveUserDataDir(srcBinding.instanceKey),
1306
+ dstDir: resolveUserDataDir(dstBinding.instanceKey),
1307
+ reason: "cross-owner-fresh-profile",
1308
+ };
1309
+ }
1310
+ if (srcOwner === dstOwner && hasBrowserProfileTopic(opts.dstTopic)) {
1311
+ const profile = getTopicBrowserProfile(opts.srcTopic);
1312
+ assignTopicBrowserProfile({ topicId: opts.dstTopic, actorUserId: dstOwner, profile });
1313
+ // A child of a room on the host's Chrome keeps working in that Chrome;
1314
+ // falling back to a managed profile would drop the login it was made for.
1315
+ setTopicBrowserConnectPort(opts.dstTopic, getTopicBrowserConnectPort(opts.srcTopic) ?? null);
1316
+ const binding = resolvePlaywrightProfileBinding(srcOwner, profile);
1317
+ const sharedDir = resolveUserDataDir(binding.instanceKey);
1318
+ return {
1319
+ copied: false,
1320
+ srcDir: sharedDir,
1321
+ dstDir: sharedDir,
1322
+ reason: "shared-profile-assignment",
1323
+ };
1324
+ }
1325
+
1326
+ const srcKey = makeInstanceKey(opts.userId, opts.srcTopic);
1327
+ const dstKey = makeInstanceKey(opts.userId, opts.dstTopic);
1328
+ const srcDir = resolveUserDataDir(srcKey);
1329
+ const dstDir = resolveUserDataDir(dstKey);
1330
+
1331
+ if (srcDir === dstDir) {
1332
+ return { copied: false, srcDir, dstDir, reason: "same-dir" };
1333
+ }
1334
+ // A connect instance's dir is an unused placeholder; the real profile lives
1335
+ // in the host's Chrome, which is never copied, quiesced or overwritten.
1336
+ if (
1337
+ parseConnectInstanceKey(srcKey) !== undefined ||
1338
+ parseConnectInstanceKey(dstKey) !== undefined
1339
+ ) {
1340
+ return { copied: false, srcDir, dstDir, reason: "connect-binding" };
1341
+ }
1342
+
1343
+ return withPlaywrightInstanceMaintenance([srcKey, dstKey], async () => {
1344
+ // Quiesce parent if running so Chrome flushes SQLite (Cookies, Login Data)
1345
+ // before we read the bytes. The maintenance barrier prevents a concurrent
1346
+ // ensurePlaywright() from reopening either profile until copying finishes.
1347
+ //
1348
+ // killInstance() sends SIGTERM and removes the instance map entry synchronously,
1349
+ // but Chrome's subprocess exit + on-disk flush is async. Empirically 1.0–1.5s
1350
+ // is enough for the cookie store to settle; we wait 1.5s to be safe.
1351
+ const parentWasLive = instances.has(srcKey);
1352
+ if (parentWasLive) {
1353
+ logger.info({ srcKey }, "Quiescing parent Playwright before profile clone");
1354
+ killInstance(srcKey);
1355
+ await delay(1500);
1356
+ }
1357
+
1358
+ // Defensive: dst should be brand-new but kill any stray instance just in case
1359
+ if (instances.has(dstKey)) {
1360
+ killInstance(dstKey);
1361
+ await delay(500);
1362
+ }
1363
+
1364
+ if (!existsSync(srcDir)) {
1365
+ return { copied: false, srcDir, dstDir, reason: "src-missing" };
1366
+ }
1367
+
1368
+ try {
1369
+ if (existsSync(dstDir)) {
1370
+ rmSync(dstDir, { recursive: true, force: true });
1371
+ }
1372
+ mkdirSync(dirname(dstDir), { recursive: true });
1373
+ if (process.platform === "darwin") {
1374
+ try {
1375
+ // `-c` requests clonefile() on APFS for a fast copy-on-write clone.
1376
+ execFileSync("cp", ["-cR", srcDir, dstDir], { stdio: "pipe" });
1377
+ } catch {
1378
+ cpSync(srcDir, dstDir, { recursive: true });
1379
+ }
1380
+ } else {
1381
+ cpSync(srcDir, dstDir, { recursive: true });
1382
+ }
1383
+ } catch (e) {
1384
+ const reason = `copy-failed: ${e instanceof Error ? e.message : String(e)}`;
1385
+ logger.warn({ srcDir, dstDir, err: e }, "Playwright profile clone failed");
1386
+ return { copied: false, srcDir, dstDir, reason };
1387
+ }
1388
+
1389
+ // Strip per-process locks copied from the parent so the child Chrome can
1390
+ // launch on its fresh dir without a fake "another instance is running" error.
1391
+ cleanSingletonFiles(dstDir);
1392
+ for (const f of ["DevToolsActivePort", "LOCK"]) {
1393
+ try {
1394
+ unlinkSync(resolve(dstDir, f));
1395
+ } catch {
1396
+ // Not all profiles have these — ignore.
1397
+ }
1398
+ }
1399
+
1400
+ logger.info({ srcKey, dstKey, srcDir, dstDir }, "Cloned Playwright profile for child topic");
1401
+ return { copied: true, srcDir, dstDir };
1402
+ });
1403
+ }
1404
+
1405
+ /**
1406
+ * Compatibility API for hard-delete callers. Shared profile directories are
1407
+ * preserved; lifecycle cleanup closes only the deleted topic's owner tabs.
1408
+ */
1409
+ export function deleteTopicProfileDir(
1410
+ userId: string,
1411
+ topic: string,
1412
+ ): { deleted: boolean; dir: string } {
1413
+ const key = makeInstanceKey(userId, topic);
1414
+ const dir = resolveUserDataDir(key);
1415
+ logger.info({ dir, userId, topic }, "Preserved shared browser profile on topic deletion");
1416
+ return { deleted: false, dir };
1417
+ }
1418
+
1419
+ /**
1420
+ * Kill all running Playwright MCP instances and wait for them to exit.
1421
+ * Call on bot shutdown. Waits up to 3s per instance before giving up.
1422
+ */
1423
+ export async function killAllPlaywright(): Promise<void> {
1424
+ const procs = [...instances.entries()].map(([key, inst]) => ({ key, proc: inst.process }));
1425
+ for (const { key } of procs) killInstance(key);
1426
+
1427
+ await Promise.all(
1428
+ procs.map(async ({ key, proc }) => {
1429
+ if (await waitForChildProcessExit(proc, 3000)) return;
1430
+ logger.warn({ instanceKey: key, pid: proc.pid }, "Playwright MCP ignored SIGTERM");
1431
+ try {
1432
+ proc.kill("SIGKILL");
1433
+ } catch (err) {
1434
+ logger.warn({ err, instanceKey: key, pid: proc.pid }, "Failed to SIGKILL Playwright MCP");
1435
+ }
1436
+ if (!(await waitForChildProcessExit(proc, 1000))) {
1437
+ logger.warn({ instanceKey: key, pid: proc.pid }, "Playwright MCP did not report exit");
1438
+ }
1439
+ }),
1440
+ );
1441
+ }
1442
+
1443
+ /**
1444
+ * Return the manager to a configurable state: no instances, no pins, no
1445
+ * in-flight spawns.
1446
+ *
1447
+ * `configurePlaywrightManagerHost` refuses while any of `instances`,
1448
+ * `spawning`, or `pinnedInstances` is non-empty, and `killAllPlaywright`
1449
+ * clears only the first of the three. That gap is a real problem for embedders'
1450
+ * test suites: driving a route that starts a turn leaves a pin behind, because
1451
+ * pins are released in the turn promise's `.finally` and a test that asserts on
1452
+ * dispatch never lets the turn finish. The manager is a module global, so the
1453
+ * next file that calls `configurePlaywrightManagerHost` — or
1454
+ * `resetPlaywrightManagerHost`, which is the same call — throws, and the
1455
+ * failure surfaces in a full run but never in isolation. Draining from outside
1456
+ * was not possible: `pinnedInstances` and `spawning` are module-private, and
1457
+ * unpinning by key requires knowing every key some route happened to pin.
1458
+ *
1459
+ * Order matters. Pins are dropped first so nothing can block teardown, then
1460
+ * in-flight spawns are awaited rather than abandoned — a spawn that settles
1461
+ * after we return would re-register an instance and put the manager right back
1462
+ * into the state we are clearing. Only then are the instances killed, and
1463
+ * `spawning` is drained once more to catch anything the kill path started.
1464
+ *
1465
+ * Intended for test teardown and host shutdown. Safe to call when already
1466
+ * clean, and it never throws: teardown must not turn a failing assertion into
1467
+ * a confusing unhandled rejection.
1468
+ */
1469
+ export async function drainPlaywrightManager(): Promise<void> {
1470
+ pinnedInstances.clear();
1471
+ // Settle, don't discard: `spawning` entries delete themselves in a `.finally`.
1472
+ await Promise.allSettled([...spawning.values()]);
1473
+ try {
1474
+ await killAllPlaywright();
1475
+ } catch (err) {
1476
+ logger.warn({ err }, "drainPlaywrightManager: killAllPlaywright failed; continuing");
1477
+ }
1478
+ await Promise.allSettled([...spawning.values()]);
1479
+ // A spawn whose promise never settles (a wedged child) would otherwise pin
1480
+ // the manager shut forever; the wait above gave it its chance.
1481
+ spawning.clear();
1482
+ pinnedInstances.clear();
1483
+ }
1484
+
1485
+ // Proactively evict all idle instances every 30 minutes
1486
+ // Every 30 minutes: evict idle instances, then reap any orphaned browser the
1487
+ // tracked-instance map has lost sight of. The orphan reap is only a backstop —
1488
+ // the crash-exit handler already reaps in real time (killBrowserProcsForUserDataDir),
1489
+ // so this catches just the rare miss (an exit event that never fired). A single
1490
+ // low-frequency sweep keeps it cheap: one `pgrep` that returns nothing when no
1491
+ // browser is running, a few `ps` calls only while automation is active.
1492
+ setInterval(
1493
+ () => {
1494
+ while (evictIdleInstance() !== null) {}
1495
+ try {
1496
+ reapPlaywrightOrphans();
1497
+ } catch (e) {
1498
+ logger.debug({ err: e }, "reapOrphanBrowsers sweep failed");
1499
+ }
1500
+ },
1501
+ 30 * 60 * 1000,
1502
+ ).unref();