synabun 2.3.1 → 2.4.0

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 (356) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +1 -1
  3. package/browser-extension/content.js +169 -0
  4. package/browser-extension/engine.js +477 -0
  5. package/browser-extension/icons/icon-128.png +0 -0
  6. package/browser-extension/icons/icon-16.png +0 -0
  7. package/browser-extension/icons/icon-32.png +0 -0
  8. package/browser-extension/icons/icon-48.png +0 -0
  9. package/browser-extension/icons/status-off-16.png +0 -0
  10. package/browser-extension/icons/status-off-32.png +0 -0
  11. package/browser-extension/icons/status-off-48.png +0 -0
  12. package/browser-extension/icons/status-on-16.png +0 -0
  13. package/browser-extension/icons/status-on-32.png +0 -0
  14. package/browser-extension/icons/status-on-48.png +0 -0
  15. package/browser-extension/manifest.json +56 -0
  16. package/browser-extension/popup-strings.js +244 -0
  17. package/browser-extension/popup-view.js +151 -0
  18. package/browser-extension/popup.css +165 -0
  19. package/browser-extension/popup.html +105 -0
  20. package/browser-extension/popup.js +347 -0
  21. package/browser-extension/protocol.js +226 -0
  22. package/browser-extension/service-worker.js +267 -0
  23. package/browser-extension/setup-content.js +36 -0
  24. package/browser-extension/tokens.css +326 -0
  25. package/docs/browser-extension-bridge.md +84 -0
  26. package/docs/whatsapp.md +1 -1
  27. package/mcp-server/dist/http.d.ts +2 -0
  28. package/mcp-server/dist/http.d.ts.map +1 -1
  29. package/mcp-server/dist/http.js +9 -1
  30. package/mcp-server/dist/http.js.map +1 -1
  31. package/mcp-server/dist/index.d.ts +11 -0
  32. package/mcp-server/dist/index.d.ts.map +1 -1
  33. package/mcp-server/dist/index.js +38 -3
  34. package/mcp-server/dist/index.js.map +1 -1
  35. package/mcp-server/dist/services/browser-route-flow.d.ts +6 -2
  36. package/mcp-server/dist/services/browser-route-flow.d.ts.map +1 -1
  37. package/mcp-server/dist/services/browser-route-flow.js +10 -3
  38. package/mcp-server/dist/services/browser-route-flow.js.map +1 -1
  39. package/mcp-server/dist/services/codex-config-heal.d.ts.map +1 -1
  40. package/mcp-server/dist/services/codex-config-heal.js +7 -0
  41. package/mcp-server/dist/services/codex-config-heal.js.map +1 -1
  42. package/mcp-server/dist/services/neural-interface.d.ts +94 -3
  43. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  44. package/mcp-server/dist/services/neural-interface.js +168 -23
  45. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  46. package/mcp-server/dist/services/team-context.d.ts +18 -0
  47. package/mcp-server/dist/services/team-context.d.ts.map +1 -0
  48. package/mcp-server/dist/services/team-context.js +29 -0
  49. package/mcp-server/dist/services/team-context.js.map +1 -0
  50. package/mcp-server/dist/services/tool-catalog.d.ts +5 -2
  51. package/mcp-server/dist/services/tool-catalog.d.ts.map +1 -1
  52. package/mcp-server/dist/services/tool-catalog.js +22 -6
  53. package/mcp-server/dist/services/tool-catalog.js.map +1 -1
  54. package/mcp-server/dist/services/tool-list.d.ts.map +1 -1
  55. package/mcp-server/dist/services/tool-list.js +4 -0
  56. package/mcp-server/dist/services/tool-list.js.map +1 -1
  57. package/mcp-server/dist/services/tool-runtime.d.ts +8 -1
  58. package/mcp-server/dist/services/tool-runtime.d.ts.map +1 -1
  59. package/mcp-server/dist/services/tool-runtime.js +18 -1
  60. package/mcp-server/dist/services/tool-runtime.js.map +1 -1
  61. package/mcp-server/dist/tools/agent-definition.d.ts +133 -0
  62. package/mcp-server/dist/tools/agent-definition.d.ts.map +1 -0
  63. package/mcp-server/dist/tools/agent-definition.js +483 -0
  64. package/mcp-server/dist/tools/agent-definition.js.map +1 -0
  65. package/mcp-server/dist/tools/agents.d.ts +91 -9
  66. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  67. package/mcp-server/dist/tools/agents.js +161 -20
  68. package/mcp-server/dist/tools/agents.js.map +1 -1
  69. package/mcp-server/dist/tools/browser-advanced.d.ts +8 -1
  70. package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
  71. package/mcp-server/dist/tools/browser-advanced.js +70 -6
  72. package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
  73. package/mcp-server/dist/tools/git-tools.d.ts +4 -2
  74. package/mcp-server/dist/tools/git-tools.d.ts.map +1 -1
  75. package/mcp-server/dist/tools/git-tools.js +283 -2
  76. package/mcp-server/dist/tools/git-tools.js.map +1 -1
  77. package/mcp-server/dist/tools/morelogin.d.ts +8 -2
  78. package/mcp-server/dist/tools/morelogin.d.ts.map +1 -1
  79. package/mcp-server/dist/tools/morelogin.js +22 -5
  80. package/mcp-server/dist/tools/morelogin.js.map +1 -1
  81. package/mcp-server/dist/tools/team.d.ts +32 -0
  82. package/mcp-server/dist/tools/team.d.ts.map +1 -0
  83. package/mcp-server/dist/tools/team.js +87 -0
  84. package/mcp-server/dist/tools/team.js.map +1 -0
  85. package/mcp-server/package-lock.json +2 -2
  86. package/mcp-server/package.json +1 -1
  87. package/mcp-server/src/http.ts +9 -1
  88. package/mcp-server/src/index.ts +34 -4
  89. package/mcp-server/src/services/browser-route-flow.ts +12 -5
  90. package/mcp-server/src/services/codex-config-heal.ts +7 -0
  91. package/mcp-server/src/services/neural-interface.ts +190 -29
  92. package/mcp-server/src/services/team-context.ts +27 -0
  93. package/mcp-server/src/services/tool-catalog.ts +26 -8
  94. package/mcp-server/src/services/tool-list.ts +4 -0
  95. package/mcp-server/src/services/tool-runtime.ts +21 -2
  96. package/mcp-server/src/tools/agent-definition.ts +458 -0
  97. package/mcp-server/src/tools/agents.ts +175 -19
  98. package/mcp-server/src/tools/browser-advanced.ts +60 -6
  99. package/mcp-server/src/tools/git-tools.ts +249 -3
  100. package/mcp-server/src/tools/morelogin.ts +20 -5
  101. package/mcp-server/src/tools/team.ts +97 -0
  102. package/neural-interface/i18n/en.json +1117 -47
  103. package/neural-interface/i18n/pt-BR.json +1117 -47
  104. package/neural-interface/lib/account-usage.js +1 -1
  105. package/neural-interface/lib/agents/density.js +101 -0
  106. package/neural-interface/lib/agents/forge-host.js +223 -0
  107. package/neural-interface/lib/agents/native-export-targets.js +190 -0
  108. package/neural-interface/lib/agents/native-export.js +365 -0
  109. package/neural-interface/lib/agents/registry.js +840 -0
  110. package/neural-interface/lib/agents/resolve.js +544 -0
  111. package/neural-interface/lib/agents/schema.js +642 -0
  112. package/neural-interface/lib/agents/split.js +37 -0
  113. package/neural-interface/lib/agents-studio-api.js +591 -0
  114. package/neural-interface/lib/assistant-api.js +76 -7
  115. package/neural-interface/lib/assistant-catalog.js +2 -0
  116. package/neural-interface/lib/assistant-continuity.js +49 -0
  117. package/neural-interface/lib/assistant-dispatch.js +229 -102
  118. package/neural-interface/lib/assistant-persona.js +105 -8
  119. package/neural-interface/lib/assistant-route-gate.js +24 -9
  120. package/neural-interface/lib/assistant-router.js +384 -42
  121. package/neural-interface/lib/assistant-run-tail.js +151 -0
  122. package/neural-interface/lib/assistant-run-wait.js +183 -0
  123. package/neural-interface/lib/assistant-runtime.js +440 -93
  124. package/neural-interface/lib/assistant-task-prompt.js +11 -2
  125. package/neural-interface/lib/assistant-usage.js +3 -2
  126. package/neural-interface/lib/automation-approval.js +2 -2
  127. package/neural-interface/lib/browser-close-evidence.js +80 -0
  128. package/neural-interface/lib/browser-default.js +210 -0
  129. package/neural-interface/lib/browser-extension-adapter.js +255 -0
  130. package/neural-interface/lib/browser-extension-bridge.js +418 -0
  131. package/neural-interface/lib/browser-extension-folder.js +116 -0
  132. package/neural-interface/lib/browser-extension-setup.js +140 -0
  133. package/neural-interface/lib/browser-profile-choices.js +3 -3
  134. package/neural-interface/lib/browser-tool-policy.js +1 -1
  135. package/neural-interface/lib/claude-account-links.js +301 -0
  136. package/neural-interface/lib/claude-accounts.js +45 -20
  137. package/neural-interface/lib/claude-agent-bridge.js +142 -10
  138. package/neural-interface/lib/claude-model-catalog.js +6 -0
  139. package/neural-interface/lib/claude-panel-session.js +33 -0
  140. package/neural-interface/lib/codex-accounts.js +67 -24
  141. package/neural-interface/lib/coordination/README.md +384 -0
  142. package/neural-interface/lib/coordination/service.js +563 -0
  143. package/neural-interface/lib/coordination/store.js +1138 -0
  144. package/neural-interface/lib/db.js +22 -1
  145. package/neural-interface/lib/effort-levels.js +10 -1
  146. package/neural-interface/lib/memory-list-page.js +49 -0
  147. package/neural-interface/lib/memory-list-stamp.js +60 -0
  148. package/neural-interface/lib/morelogin-outside-close.js +186 -0
  149. package/neural-interface/lib/morelogin-profile-failures.js +206 -0
  150. package/neural-interface/lib/morelogin-start-cooldown.js +160 -0
  151. package/neural-interface/lib/morelogin.js +194 -8
  152. package/neural-interface/lib/native-loop-runtime.js +20 -0
  153. package/neural-interface/lib/opencode-build-preflight.js +16 -1
  154. package/neural-interface/lib/opencode-native-boundary.js +83 -13
  155. package/neural-interface/lib/opencode-serve-records.js +14 -9
  156. package/neural-interface/lib/page-session.js +1 -1
  157. package/neural-interface/lib/peer-identity.js +60 -21
  158. package/neural-interface/lib/process-identity.js +68 -7
  159. package/neural-interface/lib/request-gate.js +3 -0
  160. package/neural-interface/lib/screenshot-location.js +33 -0
  161. package/neural-interface/lib/skills/creation.js +1 -1
  162. package/neural-interface/lib/skills/known-bridge-digests.json +40 -0
  163. package/neural-interface/lib/studio-attention.js +56 -0
  164. package/neural-interface/lib/teams/README.md +382 -0
  165. package/neural-interface/lib/teams/api.js +287 -0
  166. package/neural-interface/lib/teams/brief.js +185 -0
  167. package/neural-interface/lib/teams/claims.js +315 -0
  168. package/neural-interface/lib/teams/git.js +293 -0
  169. package/neural-interface/lib/teams/index.js +122 -0
  170. package/neural-interface/lib/teams/integration.js +580 -0
  171. package/neural-interface/lib/teams/landing.js +184 -0
  172. package/neural-interface/lib/teams/recovery.js +256 -0
  173. package/neural-interface/lib/teams/scheduler.js +1474 -0
  174. package/neural-interface/lib/teams/schema.js +559 -0
  175. package/neural-interface/lib/teams/state.js +181 -0
  176. package/neural-interface/lib/teams/test-runner.js +86 -0
  177. package/neural-interface/lib/teams/test-sandbox.js +99 -0
  178. package/neural-interface/lib/teams/worktrees.js +757 -0
  179. package/neural-interface/lib/tool-permission-choices.js +226 -0
  180. package/neural-interface/lib/whatsapp/cards.js +24 -10
  181. package/neural-interface/lib/worker-confinement.js +206 -6
  182. package/neural-interface/package-lock.json +2 -2
  183. package/neural-interface/package.json +1 -1
  184. package/neural-interface/public/extension-setup.html +107 -0
  185. package/neural-interface/public/index.html +52 -12
  186. package/neural-interface/public/shared/agent-runtime-options.js +3 -1
  187. package/neural-interface/public/shared/agents/studio/ax-agent-view.js +614 -0
  188. package/neural-interface/public/shared/agents/studio/ax-api.js +198 -0
  189. package/neural-interface/public/shared/agents/studio/ax-create-view.js +221 -0
  190. package/neural-interface/public/shared/agents/studio/ax-diff.js +143 -0
  191. package/neural-interface/public/shared/agents/studio/ax-editor-view.js +392 -0
  192. package/neural-interface/public/shared/agents/studio/ax-export-view.js +94 -0
  193. package/neural-interface/public/shared/agents/studio/ax-form.js +191 -0
  194. package/neural-interface/public/shared/agents/studio/ax-icons.js +87 -0
  195. package/neural-interface/public/shared/agents/studio/ax-library-view.js +158 -0
  196. package/neural-interface/public/shared/agents/studio/ax-library.js +162 -0
  197. package/neural-interface/public/shared/agents/studio/ax-main.js +712 -0
  198. package/neural-interface/public/shared/agents/studio/ax-native-export.js +35 -0
  199. package/neural-interface/public/shared/agents/studio/ax-options.js +198 -0
  200. package/neural-interface/public/shared/agents/studio/ax-review-view.js +175 -0
  201. package/neural-interface/public/shared/agents/studio/ax-revisions-view.js +189 -0
  202. package/neural-interface/public/shared/agents/studio/ax-runs-view.js +202 -0
  203. package/neural-interface/public/shared/agents/studio/ax-runs.js +82 -0
  204. package/neural-interface/public/shared/agents/studio/ax-teams-view.js +256 -0
  205. package/neural-interface/public/shared/agents/studio/ax-teams.js +200 -0
  206. package/neural-interface/public/shared/agents/studio/ax-templates.js +50 -0
  207. package/neural-interface/public/shared/agents/studio/ax-ui.js +194 -0
  208. package/neural-interface/public/shared/agents/studio/ax-views.js +170 -0
  209. package/neural-interface/public/shared/agy/agy-panel.js +142 -28
  210. package/neural-interface/public/shared/agy/agy-styles.js +25 -5
  211. package/neural-interface/public/shared/assistant/asst-account-menu.js +13 -13
  212. package/neural-interface/public/shared/assistant/asst-ask-styles.js +2 -3
  213. package/neural-interface/public/shared/assistant/asst-brain-picker.js +91 -9
  214. package/neural-interface/public/shared/assistant/asst-control.js +3 -0
  215. package/neural-interface/public/shared/assistant/asst-interaction-hold.js +99 -0
  216. package/neural-interface/public/shared/assistant/asst-limit-dismissals.js +111 -0
  217. package/neural-interface/public/shared/assistant/asst-limit-dock.js +37 -3
  218. package/neural-interface/public/shared/assistant/asst-limit-wait.js +30 -7
  219. package/neural-interface/public/shared/assistant/asst-panel.js +177 -30
  220. package/neural-interface/public/shared/assistant/asst-rack-styles.js +15 -8
  221. package/neural-interface/public/shared/assistant/asst-render.js +36 -6
  222. package/neural-interface/public/shared/assistant/asst-route.js +78 -12
  223. package/neural-interface/public/shared/assistant/asst-routes-editor.js +148 -70
  224. package/neural-interface/public/shared/assistant/asst-roving.js +17 -1
  225. package/neural-interface/public/shared/assistant/asst-scene-styles.js +7 -2
  226. package/neural-interface/public/shared/assistant/asst-scenes.js +12 -1
  227. package/neural-interface/public/shared/assistant/asst-sidepanel.js +12 -2
  228. package/neural-interface/public/shared/assistant/asst-state.js +66 -1
  229. package/neural-interface/public/shared/assistant/asst-styles.js +98 -44
  230. package/neural-interface/public/shared/assistant/route-identity.js +16 -0
  231. package/neural-interface/public/shared/cdx/cdx-output.js +10 -0
  232. package/neural-interface/public/shared/cdx/cdx-panel.js +18 -16
  233. package/neural-interface/public/shared/cdx/cdx-plan.js +3 -2
  234. package/neural-interface/public/shared/cdx/cdx-render.js +122 -45
  235. package/neural-interface/public/shared/cdx/cdx-requests.js +4 -4
  236. package/neural-interface/public/shared/cdx/cdx-styles.js +8 -36
  237. package/neural-interface/public/shared/cdx/cdx-tabs.js +110 -42
  238. package/neural-interface/public/shared/claude-panel-lazy.js +12 -0
  239. package/neural-interface/public/shared/code-copy.js +120 -0
  240. package/neural-interface/public/shared/constants.js +7 -0
  241. package/neural-interface/public/shared/context-menu-model.js +1 -0
  242. package/neural-interface/public/shared/cp/cp-markdown.js +7 -2
  243. package/neural-interface/public/shared/cp/cp-session-model.js +86 -5
  244. package/neural-interface/public/shared/cp/cp-session-settings.js +58 -30
  245. package/neural-interface/public/shared/cp/cp-styles.js +9 -0
  246. package/neural-interface/public/shared/dom-change-flag.js +66 -0
  247. package/neural-interface/public/shared/dom-morph.js +124 -0
  248. package/neural-interface/public/shared/extension-setup/es-page.css +134 -0
  249. package/neural-interface/public/shared/extension-setup/es-page.js +120 -0
  250. package/neural-interface/public/shared/extension-setup/es-view.js +100 -0
  251. package/neural-interface/public/shared/html-shell.js +33 -4
  252. package/neural-interface/public/shared/i18n.js +14 -1
  253. package/neural-interface/public/shared/idle-queue.js +78 -0
  254. package/neural-interface/public/shared/iface-config.js +227 -0
  255. package/neural-interface/public/shared/lazy-module.js +108 -0
  256. package/neural-interface/public/shared/memory-list.js +117 -0
  257. package/neural-interface/public/shared/morelogin-profile-choices.js +1 -1
  258. package/neural-interface/public/shared/morelogin-profile-field.js +3 -3
  259. package/neural-interface/public/shared/mtc/mtc-panel.js +3 -1
  260. package/neural-interface/public/shared/mtc/mtc-styles.js +4 -1
  261. package/neural-interface/public/shared/ocp-v2/ocp-v2-manager.js +35 -15
  262. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +77 -23
  263. package/neural-interface/public/shared/ocp-v2/ocp-v2-projectbar.js +3 -6
  264. package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +24 -21
  265. package/neural-interface/public/shared/ocp-v2/ocp-v2-send-logic.js +16 -5
  266. package/neural-interface/public/shared/ocp-v2/ocp-v2-sessions-logic.js +16 -2
  267. package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +27 -43
  268. package/neural-interface/public/shared/ocp-v2/ocp-v2-ws.js +73 -9
  269. package/neural-interface/public/shared/schedules-view.js +2 -2
  270. package/neural-interface/public/shared/session-project-items.js +11 -0
  271. package/neural-interface/public/shared/settings/settings-ai-browser.js +119 -0
  272. package/neural-interface/public/shared/settings/settings-browser-extension.js +446 -0
  273. package/neural-interface/public/shared/settings/settings-ia.js +4 -2
  274. package/neural-interface/public/shared/settings/settings-morelogin-cooldown.js +63 -0
  275. package/neural-interface/public/shared/settings/settings-tool-permissions.js +70 -0
  276. package/neural-interface/public/shared/sidepanel-lazy.js +40 -0
  277. package/neural-interface/public/shared/sidepanel-session-status.js +8 -14
  278. package/neural-interface/public/shared/sidepanel-shown.js +73 -0
  279. package/neural-interface/public/shared/storage.js +6 -1
  280. package/neural-interface/public/shared/studio-attention.js +83 -0
  281. package/neural-interface/public/shared/styles.css +682 -50
  282. package/neural-interface/public/shared/term-browser-tabs.js +34 -0
  283. package/neural-interface/public/shared/transcript-rows.js +334 -0
  284. package/neural-interface/public/shared/tray-auto-close.js +106 -0
  285. package/neural-interface/public/shared/ui-agents.js +97 -0
  286. package/neural-interface/public/shared/ui-antigravity-panel.js +16 -14
  287. package/neural-interface/public/shared/ui-automation-studio.js +3 -3
  288. package/neural-interface/public/shared/ui-claude-panel.js +162 -95
  289. package/neural-interface/public/shared/ui-code-copy.js +256 -0
  290. package/neural-interface/public/shared/ui-codex-panel.js +14 -10
  291. package/neural-interface/public/shared/ui-context-menu.js +1 -1
  292. package/neural-interface/public/shared/ui-file-explorer.js +2 -3
  293. package/neural-interface/public/shared/ui-games.js +1 -1
  294. package/neural-interface/public/shared/ui-loading.js +12 -1
  295. package/neural-interface/public/shared/ui-maritaca-panel.js +12 -11
  296. package/neural-interface/public/shared/ui-menubar.js +23 -0
  297. package/neural-interface/public/shared/ui-native-loop-router.js +1 -1
  298. package/neural-interface/public/shared/ui-navbar.js +15 -9
  299. package/neural-interface/public/shared/ui-opencode-panel-v2.js +13 -11
  300. package/neural-interface/public/shared/ui-schedules-studio.js +3 -3
  301. package/neural-interface/public/shared/ui-scroll-follow.js +39 -0
  302. package/neural-interface/public/shared/ui-sessions.js +3 -3
  303. package/neural-interface/public/shared/ui-settings-entry.js +55 -0
  304. package/neural-interface/public/shared/ui-settings.js +355 -400
  305. package/neural-interface/public/shared/ui-sidepanel-layout.js +44 -25
  306. package/neural-interface/public/shared/ui-sidepanel-session-entry.js +22 -9
  307. package/neural-interface/public/shared/ui-sidepanel-sessions.js +10 -2
  308. package/neural-interface/public/shared/ui-sidepanel-tray.js +36 -41
  309. package/neural-interface/public/shared/ui-sidepanel-windows.js +14 -1
  310. package/neural-interface/public/shared/ui-styleguide.js +10 -2
  311. package/neural-interface/public/shared/ui-sync.js +5 -0
  312. package/neural-interface/public/shared/ui-terminal.js +13 -9
  313. package/neural-interface/public/shared/ui-tooltip.js +28 -7
  314. package/neural-interface/public/shared/ui-topright-overflow.js +26 -4
  315. package/neural-interface/public/shared/ui-tray-columns.js +375 -0
  316. package/neural-interface/public/shared/ui-whiteboard.js +51 -6
  317. package/neural-interface/public/shared/ui-worker-end.js +28 -1
  318. package/neural-interface/public/shared/ui-workspaces.js +13 -0
  319. package/neural-interface/public/shared/window-keys.js +71 -0
  320. package/neural-interface/public/variant/2d/main.js +2 -0
  321. package/neural-interface/public/variant/3d/app.js +620 -0
  322. package/neural-interface/public/variant/3d/boot-reveal.js +47 -0
  323. package/neural-interface/public/variant/3d/main.js +21 -544
  324. package/neural-interface/public/variant/3d/map-controls.js +4 -2
  325. package/neural-interface/public/vendor/fonts/fonts.css +508 -0
  326. package/neural-interface/public/vendor/fonts/inter-OFL.txt +93 -0
  327. package/neural-interface/public/vendor/fonts/inter-cyrillic-ext.woff2 +0 -0
  328. package/neural-interface/public/vendor/fonts/inter-cyrillic.woff2 +0 -0
  329. package/neural-interface/public/vendor/fonts/inter-greek-ext.woff2 +0 -0
  330. package/neural-interface/public/vendor/fonts/inter-greek.woff2 +0 -0
  331. package/neural-interface/public/vendor/fonts/inter-latin-ext.woff2 +0 -0
  332. package/neural-interface/public/vendor/fonts/inter-latin.woff2 +0 -0
  333. package/neural-interface/public/vendor/fonts/inter-vietnamese.woff2 +0 -0
  334. package/neural-interface/public/vendor/fonts/jetbrains-mono-OFL.txt +93 -0
  335. package/neural-interface/public/vendor/fonts/jetbrains-mono-cyrillic-ext.woff2 +0 -0
  336. package/neural-interface/public/vendor/fonts/jetbrains-mono-cyrillic.woff2 +0 -0
  337. package/neural-interface/public/vendor/fonts/jetbrains-mono-greek.woff2 +0 -0
  338. package/neural-interface/public/vendor/fonts/jetbrains-mono-latin-ext.woff2 +0 -0
  339. package/neural-interface/public/vendor/fonts/jetbrains-mono-latin.woff2 +0 -0
  340. package/neural-interface/public/vendor/fonts/jetbrains-mono-vietnamese.woff2 +0 -0
  341. package/neural-interface/public/vendor/fonts/manifest.json +142 -0
  342. package/neural-interface/public/vendor/fonts/space-grotesk-OFL.txt +93 -0
  343. package/neural-interface/public/vendor/fonts/space-grotesk-latin-ext.woff2 +0 -0
  344. package/neural-interface/public/vendor/fonts/space-grotesk-latin.woff2 +0 -0
  345. package/neural-interface/public/vendor/fonts/space-grotesk-vietnamese.woff2 +0 -0
  346. package/neural-interface/scripts/boot-graph.mjs +270 -0
  347. package/neural-interface/scripts/vendor-fonts.mjs +124 -0
  348. package/neural-interface/server.js +1050 -140
  349. package/npm-shrinkwrap.json +2 -2
  350. package/package.json +3 -1
  351. package/skills/agent-forge/SKILL.md +182 -0
  352. package/skills/agent-forge/evals/evals.json +56 -0
  353. package/skills/agent-forge/references/definition-fields.md +61 -0
  354. package/skills/agent-forge/references/examples.md +105 -0
  355. package/skills/agent-forge/references/instructions.md +51 -0
  356. package/skills/agent-forge/references/review-and-export.md +84 -0
@@ -37,6 +37,7 @@ import { createProviderPanelTerminalAuth, providerLoginSpec, registerProviderPan
37
37
  import { claudeLegacyPricing, claudeUsageCostUsd } from './lib/assistant-pricing.js';
38
38
  import { HOOK_SCRIPTS, hookDefinitionsForEvent, hookCommandString, hookInstallBlocker, hookInstallPlan, isSynaBunHookCommand, sweepSettingsHooks, ensureHookRoot } from '../lib/claude-hooks.js';
39
39
  import { claudeHooksStatus } from './lib/claude-hooks-status.js';
40
+ import { createToolPermissionChoices, reconcileToolPermissions, TOOL_CHOICES_FILE } from './lib/tool-permission-choices.js';
40
41
  import { createBrowserStartHandoff, startWaitMs } from './lib/browser-start-handoff.js';
41
42
  import { browserRequestDeadline, browserV2Enabled, browserRequestMiddleware, assertBrowserRequestActive, browserActionTimeout, markBrowserActionStarted, runBrowserRequest, cancellableBrowserDelay, measureBrowserPhase, createEngagementScheduler, engagementTargetSelector, isEngagementWriteSelector, isXShortcutPublish, isXScriptedWrite } from './lib/browser-execution.js';
42
43
  import { sessionCloseDecision, profileStopDecision, otherSessionOwners } from './lib/browser-session-close.js';
@@ -44,6 +45,7 @@ import { isAutomationBrowserRoute, ownerOnlyCreateFields } from './lib/browser-a
44
45
  import { withOnDeviceModelBlocked } from './lib/chromium-on-device-model.js';
45
46
  import { browserOwnerId, listedOwners } from './lib/browser-owner.js';
46
47
  import { createProfileChoiceStore, resolveProfileRef } from './lib/browser-profile-choices.js';
48
+ import { createProfileFailureStore, namesFailedProfile, profileSwitchBarError, profileSwitchDecision } from './lib/morelogin-profile-failures.js';
47
49
  import { scheduleReview, templateReview, sameDigest, scheduleMarked, templateMarked, clearScheduleMark, clearTemplateMark, markRecordsUnreviewed, REVIEW_CHANGED, UNREVIEWED_SOURCES } from './lib/automation-approval.js';
48
50
  import { AGENT_PROFILES_KEY, PROFILE_NOT_ALLOWED, normalizeAgentProfiles, agentProfileAllowed, withAgentProfile, profileNotAllowedError, pinUseRefusal, scheduleProfileAuthority, scheduleProfileRefusalText, describeProfile, profileKindLabel } from './lib/morelogin-agent-profiles.js';
49
51
  import { createTerminalTokenRegistry, TERMINAL_TOKEN_ENV, TERMINAL_TOKEN_HEADER, BRAIN_CREDENTIAL_HEADER, redactTerminalSecrets, logIdOf } from './lib/terminal-tokens.js';
@@ -194,6 +196,7 @@ import { OPENCODE_MIN_VERSION, basicAuthHeader, checkPrivateOpencodeServer as ch
194
196
  import { SERVE_TOKEN_ENV } from './lib/process-identity.js';
195
197
  import { commandArgs, createServeRecords } from './lib/opencode-serve-records.js';
196
198
  import { opencode2Proxy } from './lib/opencode2-proxy.js';
199
+ import { macScreenshotDir } from './lib/screenshot-location.js';
197
200
  import { integrationCredentialIds, integrationsWithCredentials } from './lib/opencode2-translate.js';
198
201
  import { OPENCODE_SESSION_TABLES, hasOpencodeSessionTables } from './lib/opencode-db-schema.js';
199
202
  import {
@@ -226,7 +229,7 @@ import {
226
229
  } from './lib/native-loop-providers.js';
227
230
  import { createOpenCodeActivityRelay } from './lib/opencode-worker-activity.js';
228
231
  import { browserServePortDenial, browserSessionLossRule } from './lib/browser-tool-policy.js';
229
- import { createNativeServeBoundary, createVerdictFile, nativeServeCapability, nativeServeReason, nativeServeVersionPolicy, narrowOffenders } from './lib/opencode-native-boundary.js';
232
+ import { createNativeServeBoundary, createVerdictFile, nativeContextRevocation, nativeServeCapability, nativeServeReason, nativeServeVersionPolicy, narrowOffenders } from './lib/opencode-native-boundary.js';
230
233
  import { isolatedServeFailure } from './lib/opencode-launch-error.js';
231
234
  import { reconcilePreflightProfiles, preflightExcludedPorts, runOpencodeBuildPreflight } from './lib/opencode-build-preflight.js';
232
235
  import { binaryIdentity as opencodeBinaryIdentity, binaryKey as opencodeBinaryKey } from './lib/opencode-serve-probe.js';
@@ -244,8 +247,8 @@ const nativeServeBoundary = createNativeServeBoundary({
244
247
  for (const envId of nativePreflightProfiles) profiles.set(envId, { envId });
245
248
  const remote = [...profiles.values()].filter(p => !moreLogin.isLocalProfileId(p.envId));
246
249
  const liveProfiles = remote.length ? await reconcilePreflightProfiles(remote,
247
- () => moreLogin.listCompleteProfiles({ savedCfg: cfg, timeout: 5000 }),
248
- { log: line => { if (!nativeStaleProfilesLogged.has(line)) { nativeStaleProfilesLogged.add(line); console.warn(`[opencode] ${line}`); } } }) : [];
250
+ () => moreLogin.listCompleteProfiles({ savedCfg: cfg, firstPageTimeout: 5000 }),
251
+ { allowUnavailable: true, log: line => { if (!nativeStaleProfilesLogged.has(line)) { nativeStaleProfilesLogged.add(line); console.warn(`[opencode] ${line}`); } } }) : [];
249
252
  const excludedPorts = await preflightExcludedPorts(liveProfiles,
250
253
  envId => moreLogin.profileDetail(envId, { savedCfg: cfg, timeout: 5000 }));
251
254
  const token = opencodeServeRecords.newToken();
@@ -254,7 +257,7 @@ const nativeServeBoundary = createNativeServeBoundary({
254
257
  track: (proc, detail) => {
255
258
  operations.track(proc, { ...detail, kill: signal => signalOpencodeServeProcess(proc, signal) });
256
259
  // A crash must leave the throwaway serve on the same ownership record as every normal serve.
257
- trackOpencodeServe(proc, { kind: 'isolated', id: 'build-preflight', port: detail.port, token, boundaryTracked: true });
260
+ trackOpencodeServe(proc, { kind: 'isolated', id: 'build-preflight', port: detail.port, token, boundaryTracked: true, recordOnAnswer: false });
258
261
  },
259
262
  });
260
263
  },
@@ -442,10 +445,13 @@ import { applyPackagedChildPath, durableEntry, mcpStdioCommand, npmGlobalBinFor,
442
445
  import { dataHomeId } from '../lib/desktop-app.js';
443
446
  import { pruneExternalTools } from '../lib/external-tools.js';
444
447
  import { renderOfflinePage } from './lib/offline-page.js';
448
+ import { logUnexpectedProfileClose } from './lib/browser-close-evidence.js';
449
+ import { etagMatches, memoryListEtag, memoryListStamp } from './lib/memory-list-stamp.js';
450
+ import { parseMemoryPage, pageEtagPart, describePage, isLastPage } from './lib/memory-list-page.js';
445
451
  import {
446
452
  getDb, closeDb, getDbPath, getEmbedding, getEmbeddingBatch, getEmbeddingDims, warmupEmbeddings,
447
453
  encodeVector, decodeVector, cosineSimilarity,
448
- searchMemories as dbSearchMemories, getAllMemories, getAllMemoriesWithVectors,
454
+ searchMemories as dbSearchMemories, getAllMemories, getMemoriesPage, getAllMemoriesWithVectors,
449
455
  getMemoryById, getMemoryWithVector, updateMemoryPayload,
450
456
  softDeleteMemory, hardDeleteMemory, restoreMemory as dbRestoreMemory,
451
457
  getTrashedMemories, purgeTrash, countMemories, getMemoryStats,
@@ -527,6 +533,11 @@ let _greeting = null;
527
533
  let _greetingRouter = null;
528
534
  let _greetingError = null;
529
535
  let _assistantDispatcher = null;
536
+ // The server's one coordination service (lib/coordination/service.js, DATA_HOME/data/coordination.db), once the
537
+ // Assistant's block made and shared it: the dispatcher, the runtime, and later a team scheduler (its `.store` is what
538
+ // lib/teams takes) all use this instance. Kept here so that every stop path closes it (runGracefulShutdown).
539
+ let _assistantCoordination = null;
540
+ let _assistantTeamScheduler = null;
530
541
  // The Assistant's settings store (assistant-config.json), once the Assistant is built: Skills Studio's AI drafting reads
531
542
  // the owner's saved route for Coding from it (skillDraftDefaultTarget).
532
543
  let _assistantConfigStore = null;
@@ -652,6 +663,12 @@ import {
652
663
  import { createOpencodeCompletionEngine } from './lib/editor-completion-opencode.js';
653
664
  import { createEndpointCompletionEngine } from './lib/editor-completion-endpoint.js';
654
665
  import { ownerRouteGuard } from './lib/http-guards.js';
666
+ import { createBridgeStore, createExtensionBridge } from './lib/browser-extension-bridge.js';
667
+ import { createExtensionAdapter, EXTENSION_FOLDER } from './lib/browser-extension-adapter.js';
668
+ import { detectBrowsers } from './lib/browser-default.js';
669
+ import { extensionFolderState, prepareExtensionFolder } from './lib/browser-extension-folder.js';
670
+ import { createExtensionSetup, setupError as extensionSetupError } from './lib/browser-extension-setup.js';
671
+ import { safeError as extensionSafeError } from '../browser-extension/protocol.js';
655
672
  import { setUntrustedFileHeaders } from './lib/untrusted-file-headers.js';
656
673
  import { BUNDLED_LOGO_FILES, UPLOADED_IMAGE_PATH } from './lib/request-gate.js';
657
674
  import { createCloudflaredManager } from './lib/cloudflared/manager.js';
@@ -1070,6 +1087,11 @@ function peerLookupWanted(req) {
1070
1087
  app.use(_pageSession.serviceWorker); // GET /sw.js: a worker that takes itself away, for a browser refused the secret
1071
1088
  app.use(_pageSession.pages);
1072
1089
  app.get('/api/page-session', (req, res) => _pageSession.refresh(req, res)); // PAGE_SECRET_REFRESH_PATH
1090
+ // The extension's "Connect your browser" page, opened by the one-button setup in the owner's everyday browser. One of
1091
+ // the app's pages (PAGE_SECRET_PATHS): it gets this boot's page secret like any of them, so its reads of the setup's
1092
+ // status and its one ticket are the owner's, under the same owner guard; an automation browser and an agent's process
1093
+ // never get the secret (lib/page-session.js). The extension's content script runs on this exact origin and path only.
1094
+ app.get('/extension-setup', (_req, res) => { res.setHeader('Cache-Control', 'no-store'); res.sendFile(join(__dirname, 'public', 'extension-setup.html')); });
1073
1095
  // Retired 2D bookmarks and explicit variant links always enter the 3D page. Keep their other URL state.
1074
1096
  app.get(['/', '/index.html', '/index2d.html'], (req, res, next) => {
1075
1097
  const target = normalizeViewUrl(req.originalUrl);
@@ -1453,10 +1475,39 @@ app.get('/api/memories', async (req, res) => {
1453
1475
  // metadata columns dropped. ~4x smaller JSON for large graphs.
1454
1476
  const slim = req.query.fields === 'graph';
1455
1477
  const SLIM_CONTENT_CHARS = 500;
1478
+ // One page of the list (lib/memory-list-page.js), only without links: `offset` / `limit`. Without `limit`,
1479
+ // every memory, as always (the same body and the same ETag).
1480
+ const page = includeLinks ? null : parseMemoryPage(req.query);
1481
+ if (page?.error) return res.status(400).json({ error: page.error });
1482
+
1483
+ // The list without links (the page's first load): a page that still holds this very answer is told
1484
+ // so before a row is read (lib/memory-list-stamp.js). 32 MB were read, built and serialised on every
1485
+ // load only to find out, from the finished body, that nothing had changed.
1486
+ let listVersion = null;
1487
+ if (!includeLinks) {
1488
+ const ocBridgeNow = loadBridgeConfig('openclaw');
1489
+ if (_openclawNodes !== _openclawNodesSeen) { _openclawNodesSeen = _openclawNodes; _openclawNodesRev += 1; }
1490
+ let listStamp = null;
1491
+ try { listStamp = memoryListStamp(getDb()); } catch { /* no stamp: the full answer, as before */ }
1492
+ const listParts = [
1493
+ listStamp, slim ? 'graph' : 'full', SLIM_CONTENT_CHARS,
1494
+ ocBridgeNow?.enabled ? `openclaw:${_openclawNodesRev}:${_openclawNodes.length}` : 'openclaw:off',
1495
+ ];
1496
+ listVersion = memoryListEtag(listParts);
1497
+ // A page's ETag is the list's plus the page's place: an unchanged list is a 304 page by page.
1498
+ const listEtag = page ? memoryListEtag([...listParts, pageEtagPart(page)]) : listVersion;
1499
+ if (listEtag) {
1500
+ res.set('ETag', listEtag);
1501
+ res.set('Cache-Control', 'no-cache');
1502
+ if (etagMatches(req.headers['if-none-match'], listEtag)) return res.status(304).end();
1503
+ }
1504
+ }
1456
1505
 
1457
1506
  const cachedLinks = includeLinks ? getValidLinkCache() : null;
1458
1507
  const needVectors = includeLinks && !cachedLinks;
1459
- const allPoints = needVectors ? getAllMemoriesWithVectors() : getAllMemories();
1508
+ // A page reads its own rows only (and how many there are); the whole list reads them all.
1509
+ const pageRead = page ? getMemoriesPage(page) : null;
1510
+ const allPoints = pageRead ? pageRead.rows : (needVectors ? getAllMemoriesWithVectors() : getAllMemories());
1460
1511
 
1461
1512
  // Build nodes
1462
1513
  const nodes = allPoints.map(p => ({
@@ -1465,9 +1516,9 @@ app.get('/api/memories', async (req, res) => {
1465
1516
  vector: p.vector || null,
1466
1517
  }));
1467
1518
 
1468
- // Merge OpenClaw bridge nodes
1519
+ // Merge OpenClaw bridge nodes (after the stored memories: in a paged list, on the last page)
1469
1520
  const ocBridge = loadBridgeConfig('openclaw');
1470
- if (ocBridge?.enabled && _openclawNodes.length > 0) {
1521
+ if (ocBridge?.enabled && _openclawNodes.length > 0 && (!page || isLastPage({ ...page, total: pageRead.total }))) {
1471
1522
  for (const ocNode of _openclawNodes) {
1472
1523
  nodes.push({ ...ocNode, vector: null });
1473
1524
  }
@@ -1504,7 +1555,9 @@ app.get('/api/memories', async (req, res) => {
1504
1555
  return { ...rest, payload: slimPayload };
1505
1556
  });
1506
1557
 
1507
- res.json({ nodes: clientNodes, links, totalVectors: allPoints.length, openclawNodes: ocBridge?.enabled ? _openclawNodes.length : 0 });
1558
+ const body = { nodes: clientNodes, links, totalVectors: pageRead ? pageRead.total : allPoints.length, openclawNodes: ocBridge?.enabled ? _openclawNodes.length : 0 };
1559
+ if (page) body.page = describePage({ ...page, total: pageRead.total, count: clientNodes.length, version: listVersion });
1560
+ res.json(body);
1508
1561
  } catch (err) {
1509
1562
  console.error('GET /api/memories error:', err.message);
1510
1563
  res.status(500).json({ error: err.message });
@@ -2487,6 +2540,8 @@ async function runGracefulShutdown(reason) {
2487
2540
  // Assistant's Claude Code workers that can continue are suspended (they resume
2488
2541
  // on the next start, lib/assistant-dispatch.js), and the runtime keeps them;
2489
2542
  // every other run is stopped. Either way each worker's CLI is ended now.
2543
+ // Stop team work on every exit path before the workers and the shared store close.
2544
+ try { await _assistantTeamScheduler?.shutdown(); } catch (err) { console.warn(' team scheduler stop err:', err?.message); }
2490
2545
  let keepRuns = [];
2491
2546
  try { keepRuns = _assistantDispatcher?.suspendForShutdown?.(reason) || []; } catch (err) { console.warn(' assistant suspend err:', err?.message); }
2492
2547
  try { await _nativeLoopRuntime?.shutdown(reason, { keep: keepRuns }); } catch (err) { console.warn(' native loop stop err:', err?.message); }
@@ -2552,6 +2607,10 @@ async function runGracefulShutdown(reason) {
2552
2607
  // The judge backfill flushes its last counters and releases its lease so
2553
2608
  // the respawned server resumes immediately instead of waiting out the lease.
2554
2609
  try { stopJudgeBackfill(); } catch {}
2610
+ // The coordination store (agent events, the Assistant's mailbox, the follow-up outbox): closed once the workers
2611
+ // are stopped or suspended and what that changed is recorded. Every open wait is answered, the write-ahead log is
2612
+ // folded into the file. Signals and the restart/update/shutdown routes all use this teardown.
2613
+ try { _assistantCoordination?.close(); } catch (err) { console.warn(' coordination close err:', err?.message); }
2555
2614
  try { closeDb(); } catch {}
2556
2615
  try { closeBlobStore(); } catch {}
2557
2616
 
@@ -4152,9 +4211,10 @@ async function resolveOpenCodeMcpDirectory(entry, sessionIds) {
4152
4211
 
4153
4212
  // ── Multi-account Codex (per-tab CODEX_HOME) ────────────────────────────────
4154
4213
  // Each ChatGPT account gets its own CODEX_HOME directory holding its own
4155
- // auth.json + sessions/ + state DB, while config.toml and prompts/ are
4156
- // symlinked back to the canonical ~/.codex so model/MCP/tool-permission config
4157
- // and custom prompts stay shared. The "default" account IS ~/.codex itself.
4214
+ // auth.json + sessions/ + state DB, while config.toml, AGENTS.md and prompts/ are
4215
+ // linked back to the canonical ~/.codex so model/MCP/tool-permission config
4216
+ // and custom prompts stay shared (how, on each system: lib/claude-account-links.js).
4217
+ // The "default" account IS ~/.codex itself.
4158
4218
  const CODEX_DEFAULT_HOME = resolve(process.env.CODEX_HOME || resolve(getHomePath(), '.codex'));
4159
4219
  const CODEX_ACCOUNTS_ROOT = resolve(getHomePath(), '.codex-accounts');
4160
4220
 
@@ -4488,6 +4548,13 @@ function _codexAccounts() {
4488
4548
  return _codexAccountsInstance;
4489
4549
  }
4490
4550
 
4551
+ // Default's config.toml was written (by SynaBun, or by Codex for a panel's settings): every named account
4552
+ // reads the same again. Only where an account shares it by a hard link or a copy (Windows without symbolic
4553
+ // links, lib/claude-account-links.js): a symbolic link has nothing to bring in step. Never stops a write.
4554
+ function codexSharedFilesChanged() {
4555
+ try { _codexAccounts().syncShared?.(); } catch { /* the next launch of an account puts it in step */ }
4556
+ }
4557
+
4491
4558
  // The registry rows (id, label, home, …) for readers that only need where an account lives.
4492
4559
  function loadCodexAccounts() {
4493
4560
  return { accounts: _codexAccounts().registryRows(), defaultId: 'default' };
@@ -7435,6 +7502,8 @@ CRITICAL — When you need clarification during planning:
7435
7502
  const nextConfig = validateCodexConfigRequirements(supported, await readCodexRequirements());
7436
7503
  const edits = buildCodexConfigEdits(nextConfig);
7437
7504
  await request('config/batchWrite', { edits, reloadUserConfig: true }, 10000);
7505
+ // Codex wrote this account's config.toml as a new file: Default and the other accounts get it too.
7506
+ try { codexSharedFilesChanged(); } catch { /* never stops a save */ }
7438
7507
  const config = await readConfigState(msg.cwd || PACKAGE_ROOT);
7439
7508
  codexContextModels = [];
7440
7509
  // config.toml is every account's (shared): their kept model lists are read again.
@@ -8416,7 +8485,7 @@ function noteOpencodeServePort(port, delta) {
8416
8485
  if (next > 0) _opencodeServePortCounts.set(p, next); else _opencodeServePortCounts.delete(p);
8417
8486
  }
8418
8487
 
8419
- function trackOpencodeServe(proc, { kind, id = null, port, token, nativeWebSocketSafe = false, nativeServe = null, boundaryTracked = false }) {
8488
+ function trackOpencodeServe(proc, { kind, id = null, port, token, nativeWebSocketSafe = false, nativeServe = null, boundaryTracked = false, recordOnAnswer = true }) {
8420
8489
  // A serve that fails its runtime check while a native context is attached is stopped (its pages could reach it).
8421
8490
  // A serve that fails its runtime check is stopped by the boundary: SIGTERM, then SIGKILL, until the OS confirms
8422
8491
  // its process and its listener are gone (lib/opencode-native-boundary.js terminate).
@@ -8432,7 +8501,10 @@ function trackOpencodeServe(proc, { kind, id = null, port, token, nativeWebSocke
8432
8501
  // A spawn that failed (no pid) may never exit; a failed kill leaves the process running.
8433
8502
  proc.once?.('error', () => { if (!proc.pid || exited()) release(); });
8434
8503
  }
8435
- const spawned = pid ? opencodeServeRecords.record({ kind, id, port, pid, token }).catch(() => null) : Promise.resolve(null);
8504
+ // Right after the spawn the process may not show its environment yet (its token): a miss here is expected when
8505
+ // answering() records it again once it answers, and only that second try says why (recordOnAnswer: the caller
8506
+ // calls answering(); the build pre-flight does not, so its one try says it).
8507
+ const spawned = pid ? opencodeServeRecords.record({ kind, id, port, pid, token, quiet: recordOnAnswer }).catch(() => null) : Promise.resolve(null);
8436
8508
  let started = Promise.resolve(null);
8437
8509
  const forget = () => {
8438
8510
  spawned.then((record) => { if (record) opencodeServeRecords.remove(record); }).catch(() => {});
@@ -8952,6 +9024,11 @@ async function ensureIsolatedServe(termId, { xdgRoot: requestedXdgRoot = null, c
8952
9024
  const wanted = () => _ocpIsoServes.get(termId) === entry;
8953
9025
  let check = null;
8954
9026
  let started = 'cancelled';
9027
+ // Validate this run's pin once, before taking the global start lock. An offline API must not delay every
9028
+ // other start, nor be listed again for each port collision. Later live pages retain the normal 15s budget.
9029
+ const pin = runMoreLoginPin(termId);
9030
+ if (pin?.envId && !moreLogin.isLocalProfileId(pin.envId)) await reconcilePreflightProfiles([],
9031
+ () => moreLogin.listCompleteProfiles({ ..._moreLoginOpts(), firstPageTimeout: 5000 }), { requested: [pin.envId], allowUnavailable: true });
8955
9032
  // Another server that takes the port while this serve boots is a start collision: it is left running (and never
8956
9033
  // put on record), this start's own process is ended, and the start tries the next free port (three at most).
8957
9034
  for (let attempt = 1; attempt <= 3; attempt++) {
@@ -8962,9 +9039,6 @@ async function ensureIsolatedServe(termId, { xdgRoot: requestedXdgRoot = null, c
8962
9039
  const token = opencodeServeRecords.newToken();
8963
9040
  // A protected worker's serve (hidePassword): no password variable in any environment, its own shell's
8964
9041
  // included; the serve prints the password it made, read here from its output (and never logged).
8965
- const pin = runMoreLoginPin(termId);
8966
- if (pin?.envId && !moreLogin.isLocalProfileId(pin.envId)) await reconcilePreflightProfiles([],
8967
- () => moreLogin.listCompleteProfiles(_moreLoginOpts()), { requested: [pin.envId] });
8968
9042
  const launch = await opencodeServeLaunch(port, { env: { ...isolatedEnv, [SERVE_TOKEN_ENV]: token }, passwordFrom: 'stdout' });
8969
9043
  const readPassword = launch.passwordFrom === 'stdout' ? servePasswordReader() : null;
8970
9044
  // A guarded worker's serve (macOS): run the whole serve tree under the run's Seatbelt profile, so its shell
@@ -13868,6 +13942,10 @@ function parseDailyLogs(memoryDir) {
13868
13942
  // --- OpenClaw Bridge: In-Memory Store ---
13869
13943
 
13870
13944
  let _openclawNodes = [];
13945
+ // The list above is replaced whole when the bridge syncs: which one GET /api/memories last saw, and how
13946
+ // many times it has changed (part of that route's ETag).
13947
+ let _openclawNodesSeen = null;
13948
+ let _openclawNodesRev = 0;
13871
13949
  let _openclawCategories = [];
13872
13950
  let _openclawLastSync = null;
13873
13951
 
@@ -14201,6 +14279,7 @@ function writeLoopTemplates(templates) {
14201
14279
  for (const [path, fileTemplates] of byPath) {
14202
14280
  writeLoopTemplateFile(path, fileTemplates, formatByPath.get(path) || 'array');
14203
14281
  }
14282
+ if (!_scheduleFilesWatcher) broadcastSync({ type: 'assistant:automation-records-changed', templates: true });
14204
14283
  }
14205
14284
 
14206
14285
  function readLoopFolders() {
@@ -14900,7 +14979,7 @@ app.post('/api/loop/launch', async (req, res) => {
14900
14979
  const loopTerminalToken = nativeRuntime ? null : _terminalTokens.issue(terminalSessionId);
14901
14980
  if (loopTerminalToken) issuedLoopTerminal = terminalSessionId;
14902
14981
  // The launch's MoreLogin profile (decided above) becomes the run's pin, as a schedule's does. None: the default
14903
- // browser of Settings → Browser, as before.
14982
+ // AI browser (Settings → Connected tools → MoreLogin), as before.
14904
14983
  if (launchMoreLogin) {
14905
14984
  pinRunMoreLoginProfile(terminalSessionId, launchMoreLogin.moreloginEnvId, launchMoreLogin.moreloginEnvName, launchMoreLogin.moreloginEnvBy);
14906
14985
  pinnedLoopTerminal = terminalSessionId;
@@ -15293,6 +15372,9 @@ app.post('/api/loop/recover-browser', async (req, res) => {
15293
15372
  // token, so naming a run (or routing as it) moves nothing without it (403 TERMINAL_TOKEN_REQUIRED / _INVALID).
15294
15373
  const who = browserCaller(req);
15295
15374
  if (!who.accepted) return refuseBrowserCaller(res, who);
15375
+ if (loadBrowserConfig().connectMode === 'extension' && !runMoreLoginPin(who.id) && who.status !== 'verified') {
15376
+ return res.status(403).json(extensionSafeError({ code: 'AUTH_FAILED' }));
15377
+ }
15296
15378
  const caller = browserOwnerId(who.id);
15297
15379
  if (!caller) {
15298
15380
  return res.status(403).json({ error: 'A browser recovery says who asks (X-Synabun-Terminal, sent by SynaBun\'s MCP on every request); this request did not.', code: 'TERMINAL_REQUIRED' });
@@ -15320,6 +15402,11 @@ app.post('/api/loop/recover-browser', async (req, res) => {
15320
15402
  return res.json({ ok: true, sessionId, tabId, adopted: true });
15321
15403
  }
15322
15404
  const fresh = req.body?.reason === 'create';
15405
+ // A create that takes over one of the owner's tabs in the everyday browser (extension mode only).
15406
+ const takeOverTab = fresh && typeof req.body?.takeOverTab === 'string' && loadBrowserConfig().connectMode === 'extension' ? req.body.takeOverTab : null;
15407
+ if (loadBrowserConfig().connectMode === 'extension' && !runMoreLoginPin(who.id) && !fresh) {
15408
+ return res.status(410).json(extensionSafeError({ code: 'TAB_CLOSED' }));
15409
+ }
15323
15410
  const lost = req.body?.lost && typeof req.body.lost === 'object' ? req.body.lost : null;
15324
15411
  if (named && !fresh) {
15325
15412
  const current = liveAutomationRoute(named, { files: true });
@@ -15328,7 +15415,10 @@ app.post('/api/loop/recover-browser', async (req, res) => {
15328
15415
  }
15329
15416
  }
15330
15417
  const start = async () => {
15331
- const acq = await acquireLoopBrowserAndTab({ terminalSessionId: owner, logTag: fresh ? 'create:browser' : 'recover:browser' });
15418
+ const acq = await acquireLoopBrowserAndTab({ terminalSessionId: owner, logTag: fresh ? 'create:browser' : 'recover:browser', takeOverTab });
15419
+ // Its profile was closed outside SynaBun under it and is not started again for it: the loop ends when its turn
15420
+ // ends, never asking again iteration after iteration.
15421
+ if (acq.code === 'MORELOGIN_CLOSED_OUTSIDE') finishBlockedLoop(owner, acq);
15332
15422
  if (acq.error) throw Object.assign(new Error(acq.error), { acquisition: acq });
15333
15423
  // The run ended while its tab was being opened (a cold start): the tab goes at once, never left to a dead run.
15334
15424
  if (named && automationRunState(named, { files: true }) === 'ended') {
@@ -15342,7 +15432,7 @@ app.post('/api/loop/recover-browser', async (req, res) => {
15342
15432
  if (named) noteAutomationBrowserRoute(named, acq, fresh ? 'created' : 'recovered');
15343
15433
  return acq;
15344
15434
  };
15345
- const outcome = await browserStartHandoff.run(`run:${owner}`, start, {
15435
+ const outcome = await browserStartHandoff.run(takeOverTab ? `run:${owner}:take:${takeOverTab}` : `run:${owner}`, start, {
15346
15436
  gone: browserCallerGone(req, res),
15347
15437
  waitMs: startWaitMs(browserRequestDeadline(req)),
15348
15438
  alive: (acq) => startedTabAlive(acq.browserSessionId, acq.browserTabId, owner),
@@ -15354,11 +15444,57 @@ app.post('/api/loop/recover-browser', async (req, res) => {
15354
15444
  res.json({ ok: true, sessionId: acq.browserSessionId, tabId: acq.browserTabId || null, ...(outcome.from !== 'started' && { handedOver: outcome.from }) });
15355
15445
  } catch (err) {
15356
15446
  const acq = err?.acquisition;
15357
- if (acq) return res.status(500).json({ error: acq.error, ...(acq.code ? { code: acq.code, offenders: acq.offenders } : {}) });
15447
+ // A run blocked by a close outside SynaBun: 409 (nothing is wrong with the server, the run is refused on purpose).
15448
+ if (acq?.code === 'MORELOGIN_CLOSED_OUTSIDE') {
15449
+ return res.status(409).json(closedOutsideAnswer(acq));
15450
+ }
15451
+ if (acq) return res.status(500).json({ error: acq.error, ...(acq.code ? { code: acq.code, offenders: acq.offenders } : {}), ...(acq.needsUser ? { needsUser: true } : {}) });
15358
15452
  res.status(err.status || 500).json({ error: err.message, ...(err.code ? { code: err.code, problems: err.problems } : {}) });
15359
15453
  }
15360
15454
  });
15361
15455
 
15456
+ /**
15457
+ * A loop whose browser was refused because its MoreLogin profile was closed outside SynaBun under it
15458
+ * (lib/morelogin-outside-close.js): it ends when its current turn ends, stoppedReason 'browser_closed_outside', in
15459
+ * place of starting its next iteration and asking again. A native loop through NativeLoopRuntime.finishAfterTurn
15460
+ * (the turn under way reports the refusal it got); a terminal loop's state file is marked inactive the way a PTY
15461
+ * exit marks it, which its driver reads before the next iteration. A dispatched task run is left to its brain (it
15462
+ * gets the refusal, needsUser). Once per run. Returns whether the loop was set to end.
15463
+ */
15464
+ const _blockedLoopsEnded = new Set();
15465
+ function finishBlockedLoop(ownerKey, acq = null) {
15466
+ if (!ownerKey || _blockedLoopsEnded.has(ownerKey)) return false;
15467
+ let ended = false;
15468
+ try {
15469
+ if (_nativeLoopRuntime?.isAlive?.(ownerKey)) {
15470
+ ended = !!_nativeLoopRuntime.finishAfterTurn?.(ownerKey, 'browser_closed_outside');
15471
+ } else {
15472
+ const loopFile = findLoopFileForTerminal(ownerKey);
15473
+ if (loopFile) {
15474
+ const loopPath = resolve(LOOP_DIR, loopFile);
15475
+ const ls = JSON.parse(readFileSync(loopPath, 'utf-8'));
15476
+ if (ls.active && ls.runtimeType !== 'native' && ls.driverType !== 'native' && ls.runMode !== 'task') {
15477
+ ls.active = false;
15478
+ ls.pending = false;
15479
+ ls.completedAt = new Date().toISOString();
15480
+ ls.stoppedReason = 'browser_closed_outside';
15481
+ writeFileSync(loopPath, JSON.stringify(ls, null, 2));
15482
+ if (ls.driverType === 'exec' && ls.scheduledBy) persistExecScheduleOutcome(ls, 'stopped', 'browser_closed_outside');
15483
+ ended = true;
15484
+ }
15485
+ }
15486
+ }
15487
+ } catch (err) {
15488
+ loopLog(ownerKey, 'browser:blocked', 'could not set the loop to end after its turn', { err: err?.message || String(err) });
15489
+ }
15490
+ if (ended) {
15491
+ if (_blockedLoopsEnded.size > 2000) _blockedLoopsEnded.delete(_blockedLoopsEnded.values().next().value);
15492
+ _blockedLoopsEnded.add(ownerKey);
15493
+ loopLog(ownerKey, 'browser:blocked', 'the loop ends when this turn ends: its MoreLogin profile was closed outside SynaBun and is not started again for it', { closedAt: acq?.closedAt || null });
15494
+ }
15495
+ return ended;
15496
+ }
15497
+
15362
15498
  // GET /api/loop/history — no history keeping, always empty
15363
15499
  app.get('/api/loop/history', (_req, res) => { res.json([]); });
15364
15500
 
@@ -15419,8 +15555,10 @@ function _armScheduleFilesWatcher() {
15419
15555
  if (_scheduleFilesWatcher) return true;
15420
15556
  try {
15421
15557
  const w = fsWatch(LOOP_DATA_DIR, (eventType, filename) => {
15422
- if (filename && !LOOP_SCHEDULES_PATTERN.test(filename)) return;
15423
- _scheduleFilesCache = null;
15558
+ const schedules = !filename || LOOP_SCHEDULES_PATTERN.test(filename);
15559
+ const templates = !filename || LOOP_TEMPLATES_PATTERN.test(filename);
15560
+ if (schedules) _scheduleFilesCache = null;
15561
+ if (schedules || templates) broadcastSync({ type: 'assistant:automation-records-changed', schedules, templates });
15424
15562
  });
15425
15563
  w.unref?.();
15426
15564
  w.on('error', () => {
@@ -15538,6 +15676,7 @@ function saveScheduleStore(store) {
15538
15676
  for (const [path, schedules] of byPath) {
15539
15677
  writeLoopScheduleFile(path, schedules, path === LOOP_SCHEDULES_PATH ? groups : [], formatByPath.get(path) || 'object', files);
15540
15678
  }
15679
+ if (!_scheduleFilesWatcher) broadcastSync({ type: 'assistant:automation-records-changed', schedules: true });
15541
15680
  }
15542
15681
 
15543
15682
  function loadSchedules() {
@@ -15584,7 +15723,7 @@ function applyScheduleLaunchOverrides(schedule, source) {
15584
15723
  }
15585
15724
 
15586
15725
  // A schedule's or a schedule group's own MoreLogin profile (optional). Empty / null clears it: the run then opens the
15587
- // default browser of Settings → Browser, as every record without the field does. The name is kept for display only.
15726
+ // default AI browser (Settings → Connected tools → MoreLogin), as every record without the field does. The name is kept for display only.
15588
15727
  // At launch a schedule's own profile wins, then its group's (scheduleMoreLoginProfile); nothing is copied from a group
15589
15728
  // onto its schedules.
15590
15729
  function applyScheduleMoreLoginProfile(schedule, source) {
@@ -16131,8 +16270,9 @@ async function launchScheduledLoop(schedule) {
16131
16270
  console.log(`[schedule] "${schedule.name}" runs in ${describeMoreLoginPin(runMoreLoginPin(terminalSessionId))}${scheduledMoreLogin.source === 'group' ? ' (its group\'s profile)' : ''}`);
16132
16271
  }
16133
16272
  if (scheduledUsesBrowser) {
16134
- // Same serialized shared-browser + dedicated-tab acquisition as manual loops.
16135
- const acq = await acquireLoopBrowserAndTab({ terminalSessionId, logTag: 'schedule:browser' });
16273
+ // Same serialized shared-browser + dedicated-tab acquisition as manual loops. A new firing may start a profile
16274
+ // closed outside SynaBun (lib/morelogin-outside-close.js): that is what the schedule is for.
16275
+ const acq = await acquireLoopBrowserAndTab({ terminalSessionId, logTag: 'schedule:browser', scheduledFiring: true });
16136
16276
  if (acq.error) {
16137
16277
  throw new Error(acq.error);
16138
16278
  }
@@ -20250,7 +20390,7 @@ function moreLoginAutomationProfileCheck(req, envId) {
20250
20390
  function refuseDefaultBrowserChange(res) {
20251
20391
  return res.status(403).json({
20252
20392
  ok: false, code: 'MORELOGIN_DEFAULT_OWNER_ONLY',
20253
- error: 'The default AI browser (the default MoreLogin profile and the browser connect mode) is the owner\'s choice, made in SynaBun → Settings → Browser; no agent, run, session or program can change it, whatever the profile. Nothing was changed. To work in another MoreLogin profile yourself, call morelogin with action "use" (envId or name): only your own browser tools move there. Tell the user: if every automation should use that profile by default, set it in Settings → Browser.',
20393
+ error: 'The default AI browser (the default MoreLogin profile and the browser connect mode) is the owner\'s choice, made in SynaBun → Settings → Connected tools → MoreLogin (Default AI browser). No agent, run, session or program can change it, whatever the profile. Nothing was changed. To work in another MoreLogin profile yourself, call morelogin with action "use" (envId or name): only your own browser tools move there. Tell the user: if every automation should use that profile by default, set it in Settings → Connected tools → MoreLogin (Default AI browser).',
20254
20394
  });
20255
20395
  }
20256
20396
  /** Whether a write of the browser settings would change the default (connect mode or default profile) and its caller may not. */
@@ -20273,21 +20413,21 @@ function moreLoginGate(req, res, next) {
20273
20413
  if (browserOwnerPageOnly(req)) return next();
20274
20414
  if (caller.id && MORELOGIN_AUTOMATION_ROUTES.has(key)) {
20275
20415
  if (MORELOGIN_VERIFIED_ROUTES.has(key) && caller.status !== 'verified') {
20276
- return res.status(403).json({ ok: false, code: 'VERIFIED_RUN_REQUIRED', error: `Starting a MoreLogin profile, working in one, or making one the default AI browser is for a session that proves its id: a run SynaBun started (its terminal token), or a CLI window's own session of SynaBun's HTTP MCP (working in a profile only), or the owner in Settings → Browser. ${String(caller.id).slice(0, 128)} is an id SynaBun gave no proof (a stdio MCP server's own id, for one).` });
20416
+ return res.status(403).json({ ok: false, code: 'VERIFIED_RUN_REQUIRED', error: `Starting a MoreLogin profile, working in one, or making one the default AI browser is for a session that proves its id: a run SynaBun started (its terminal token), or a CLI window's own session of SynaBun's HTTP MCP (working in a profile only), or the owner in the MoreLogin tab in Settings. ${String(caller.id).slice(0, 128)} is an id SynaBun gave no proof (a stdio MCP server's own id, for one).` });
20277
20417
  }
20278
20418
  // An id that holds a profile pin and was not proven by this request reaches no MoreLogin route (finding 2). A pin
20279
20419
  // off the owner's list does not close these routes: the session needs status, list and `use` to go back.
20280
20420
  const pinRefused = callerProfileRefusal(caller);
20281
20421
  if (pinRefused && pinRefused.code === 'PROFILE_PIN_UNVERIFIED') return res.status(pinRefused.status).json({ ok: false, code: pinRefused.code, error: pinRefused.error });
20282
20422
  if (MORELOGIN_RUN_ONLY_ROUTES.has(key) && isMcpSessionOwner(caller.id)) {
20283
- return res.status(403).json({ ok: false, code: 'VERIFIED_RUN_REQUIRED', error: 'Starting a MoreLogin profile by itself or changing the default AI browser is for a run SynaBun started, or the owner in Settings → Browser. This session can work in a profile of its own: call morelogin with action "use" (the profile is started by your next browser call).' });
20423
+ return res.status(403).json({ ok: false, code: 'VERIFIED_RUN_REQUIRED', error: 'Starting a MoreLogin profile by itself or changing the default AI browser is for a run SynaBun started, or the owner in Settings → Connected tools → MoreLogin (Default AI browser). This session can work in a profile of its own: call morelogin with action "use" (the profile is started by your next browser call).' });
20284
20424
  }
20285
20425
  return next();
20286
20426
  }
20287
20427
  let guest = false;
20288
20428
  try { guest = !!isGuestRequest(req); } catch { guest = true; }
20289
20429
  if (caller.id || guest) {
20290
- return res.status(403).json({ ok: false, code: 'OWNER_ROUTE', error: 'This MoreLogin route is the owner\'s (SynaBun\'s page, Settings → Browser).' });
20430
+ return res.status(403).json({ ok: false, code: 'OWNER_ROUTE', error: 'This MoreLogin route is the owner\'s (SynaBun\'s page, Settings → Connected tools → MoreLogin).' });
20291
20431
  }
20292
20432
  if (caller.automation) {
20293
20433
  return res.status(403).json({ ok: false, code: 'TERMINAL_REQUIRED', error: 'An automation says which run it is (X-Synabun-Terminal, sent by SynaBun\'s MCP on every request); an agent header alone is not the owner\'s page.' });
@@ -20362,7 +20502,7 @@ app.delete('/api/morelogin/local-profiles/:id', async (req, res) => {
20362
20502
  const id = String(req.params.id);
20363
20503
  const cfg = loadBrowserConfig();
20364
20504
  if (cfg.connectMode === 'morelogin' && String(cfg.moreloginEnvId || '') === id) {
20365
- return res.status(409).json({ ok: false, code: 'LOCAL_PROFILE_IS_DEFAULT', error: 'This local profile is the default AI browser: choose another default first (Settings → Browser, or "Use as default" on another profile), then delete it.' });
20505
+ return res.status(409).json({ ok: false, code: 'LOCAL_PROFILE_IS_DEFAULT', error: 'This local profile is the default AI browser: choose another default first (Settings → Connected tools → MoreLogin (Default AI browser), or "Use as default" on another profile), then delete it.' });
20366
20506
  }
20367
20507
  const removed = await moreLogin.deleteLocalProfile(id);
20368
20508
  _moreLoginStartedBy.delete(id);
@@ -20395,6 +20535,13 @@ app.get('/api/morelogin/status', async (req, res) => {
20395
20535
  defaultEnvId: cfg.moreloginEnvId || null,
20396
20536
  // SynaBun's own local profiles (lib/local-profiles.js): `installed`, `running` and `profileCount` are MoreLogin's.
20397
20537
  localProfileCount: moreLogin.localProfileCount(),
20538
+ // Profiles MoreLogin refused to start for its plan's daily limit, until its day resets (lib/morelogin-start-cooldown.js):
20539
+ // meanwhile SynaBun does not ask MoreLogin to start them. [{ envId, name, resetAt, resetLocal, since, apiCode }]
20540
+ startCooldowns: moreLoginStartCooldowns(),
20541
+ // Profiles closed outside SynaBun (lib/morelogin-outside-close.js): no automatic path starts them again until the
20542
+ // owner starts them, a new scheduled run fires, or MoreLogin's daily reset (`holdUntil`).
20543
+ // [{ envId, name, closedAt, closedLocal, holdUntil, holdUntilLocal, runs }] (the orphaned runs counted, not listed).
20544
+ closedOutside: moreLoginClosedOutside(),
20398
20545
  // The profile the calling session's own browser tools work in (POST /api/morelogin/use, or the profile its run
20399
20546
  // was launched with), when that is not the default.
20400
20547
  // Only for a caller this request proved (finding 2): an id merely said learns nothing about a pin.
@@ -20467,6 +20614,7 @@ app.get('/api/morelogin/profiles', async (req, res) => {
20467
20614
  // listed, and `moreloginError` says why MoreLogin's are missing.
20468
20615
  const rows = await moreLogin.listProfiles({ ..._moreLoginOpts(), complete: true });
20469
20616
  const listed = await withMoreLoginBrowsers(rows, _moreLoginOpts());
20617
+ rememberMoreLoginEnvNames(rows);
20470
20618
  // `agentsMayChoose`: on the owner's list (the Settings toggle, and what the `morelogin` tool's "list" shows).
20471
20619
  const allowed = moreLoginAgentProfiles();
20472
20620
  res.json({
@@ -20507,9 +20655,33 @@ app.post('/api/morelogin/start', async (req, res) => {
20507
20655
  // Only that may end a running local profile to start it again (lib/local-profiles.js startNow); an automation
20508
20656
  // gets LOCAL_PROFILE_RESTART_NEEDED / LOCAL_PROFILE_BUSY by name below, and no browser.
20509
20657
  const who = browserCaller(req);
20658
+ // A profile closed outside SynaBun (lib/morelogin-outside-close.js) is not started here for an automation (a run's
20659
+ // or an agent's morelogin "start") or anybody else; the owner's own Start lifts the mark (it starts the profile).
20660
+ const startOwner = who.automation && who.id ? browserOwnerId(who.id) : null;
20661
+ // A run whose own profile failed in this run does not start another one either (each start spends one of
20662
+ // MoreLogin's daily launches, and it may not move there: lib/morelogin-profile-failures.js). A start of the failed
20663
+ // profile itself is how it is fixed, and goes on. The owner's Start is never asked.
20664
+ const failedBar = startOwner ? runProfileSwitchRefusal(startOwner, { envId: String(envId), name: _moreLoginEnvNames.get(String(envId)) || null, resolved: true }, { action: 'start' }) : null;
20665
+ if (failedBar) return refuseProfileSwitchAfterFailure(res, failedBar);
20510
20666
  nativePreflightProfiles.add(String(envId));
20511
- const out = await moreLogin.startProfile(envId, { ..._moreLoginOpts(), owner: !who.automation && moreLoginOwnerPageCall(req) });
20667
+ // The run's own profile (its pin, else the MoreLogin default) that fails to start here bars it from switching, as a
20668
+ // failed browser start does (acquireSharedBrowserTab).
20669
+ const ownProfile = startOwner ? runEffectiveProfile(startOwner) : null;
20670
+ let out;
20671
+ try {
20672
+ out = await moreLogin.startProfile(envId, { ..._moreLoginOpts(), owner: !who.automation && moreLoginOwnerPageCall(req),
20673
+ ...(startOwner ? { refuseStart: moreLoginStartGuardFor(startOwner) } : {}), profileLabel: moreLoginProfileLabel });
20674
+ } catch (err) {
20675
+ if (ownProfile && ownProfile.envId === String(envId)) noteRunProfileFailure(startOwner, ownProfile, err);
20676
+ throw err;
20677
+ }
20678
+ // Running now: a close outside SynaBun is over. Started (by the owner, or by an automation the mark did not hold),
20679
+ // or found running by the owner. An automation that only found it running has not attached to it yet: its browser
20680
+ // call clears the mark when it attaches (a profile MoreLogin still lists while it closes must not lose it here).
20681
+ if (!out.alreadyRunning || !who.automation) { try { moreLogin.clearOutsideClose(String(envId)); } catch { /* nothing held */ } }
20512
20682
  if (!who.automation) return res.json({ ok: true, ...out });
20683
+ // Already running (MoreLogin's status said so, nothing was started): the profile is not the caller's to stop.
20684
+ if (out.alreadyRunning) return res.json({ ok: true, started: false, alreadyRunning: true, envId: String(envId) });
20513
20685
  // An automation's start: the profile is the caller's to stop later (POST /api/morelogin/stop), and the answer
20514
20686
  // carries no CDP port (a raw debugging connection drives the profile's browser past every check SynaBun makes;
20515
20687
  // SynaBun's browser tools reach the caller's own profile without it: POST /api/morelogin/use).
@@ -20521,7 +20693,8 @@ app.post('/api/morelogin/start', async (req, res) => {
20521
20693
  }
20522
20694
  res.json({ ok: true, started: true, envId: String(envId) });
20523
20695
  } catch (err) {
20524
- res.status(err.status || 500).json({ ok: false, error: err.message, ...(err.code ? { code: err.code } : {}) });
20696
+ res.status(err.status || 500).json({ ok: false, error: err.message, ...(err.code ? { code: err.code } : {}),
20697
+ ...(err.needsUser ? { needsUser: true } : {}), ...(err.closedAt ? { closedAt: err.closedAt } : {}), ...(err.holdUntil ? { holdUntil: err.holdUntil } : {}) });
20525
20698
  }
20526
20699
  });
20527
20700
 
@@ -20540,7 +20713,7 @@ app.post('/api/morelogin/stop', async (req, res) => {
20540
20713
  const decision = profileStopDecision(browserSessions, envId, caller, { startedBy: (id) => _moreLoginStartedBy.get(id) || [] });
20541
20714
  if (decision.action === 'refuse' && decision.reason === 'not_owned') {
20542
20715
  console.warn(`[morelogin] stop of env ${envId} by ${logOwnerId(caller)} refused: it holds nothing on that profile`);
20543
- return res.status(403).json({ ok: false, code: 'NOT_OWNED', error: `MoreLogin profile ${envId} was not stopped: you did not start it and have no tab in it. Stop only a profile you started; the owner stops the others in Settings → Browser.` });
20716
+ return res.status(403).json({ ok: false, code: 'NOT_OWNED', error: `MoreLogin profile ${envId} was not stopped: you did not start it and have no tab in it. Stop only a profile you started; the owner stops the others in the MoreLogin tab in Settings.` });
20544
20717
  }
20545
20718
  if (decision.action === 'refuse') {
20546
20719
  console.warn(`[morelogin] stop of env ${envId} by ${logOwnerId(caller)} refused: ${decision.others.length} other automation(s) work in it (${decision.others.map(logOwnerId).join(', ')})`);
@@ -20549,6 +20722,8 @@ app.post('/api/morelogin/stop', async (req, res) => {
20549
20722
  error: `MoreLogin profile ${envId} was not stopped: ${decision.others.length} other automation(s) have a tab in it, and stopping the profile would close their tabs. To start over in a fresh tab, close only your own (browser_session close, which keeps a shared session for the others); to stop the profile, ask the owner or wait until the other runs end.`,
20550
20723
  });
20551
20724
  }
20725
+ // SynaBun's own stop: the sessions in that profile see their browser go, and that is not a close by someone else.
20726
+ _moreLoginStoppedBySynaBun.set(String(envId), Date.now());
20552
20727
  await moreLogin.stopProfile(envId, _moreLoginOpts());
20553
20728
  _moreLoginStartedBy.delete(String(envId));
20554
20729
  res.json({ ok: true });
@@ -20585,8 +20760,8 @@ app.post('/api/morelogin/use-default', async (req, res) => {
20585
20760
 
20586
20761
  // ── A session's own MoreLogin profile (2026-11-10) ──
20587
20762
  // POST /api/morelogin/use — the calling session works in a MoreLogin profile of its own from now on:
20588
- // { envId }, { name } or { profile } (either; a profile MoreLogin lists), or { default: true } to go back to the default of Settings →
20589
- // Browser. The choice is the caller's pin (pinRunMoreLoginProfile, the pin a schedule's run is launched with), so its
20763
+ // { envId }, { name } or { profile } (either; a profile MoreLogin lists), or { default: true } to go back to the default AI
20764
+ // browser (Settings → Connected tools → MoreLogin). The choice is the caller's pin (pinRunMoreLoginProfile, the pin a schedule's run is launched with), so its
20590
20765
  // acquisitions, its recoveries, the per-request gate and its view of GET /api/browser/sessions all follow it. Nothing
20591
20766
  // else changes: not the default AI browser, not another session's pin, tab or route. This is what an agent uses to
20592
20767
  // work in a second profile while other automations work in the default one; use-default (which moves everybody) keeps
@@ -20597,11 +20772,17 @@ app.post('/api/morelogin/use-default', async (req, res) => {
20597
20772
  // Chrome). A Firefox-type profile is refused (400 MORELOGIN_NOT_CHROMIUM) and the choice stays what it was.
20598
20773
  // For a session that proves its id (moreLoginGate: a run's terminal token, a brain's credential, or a plain CLI MCP
20599
20774
  // session's own proof, MCP_SESSION_PROOFS), never the owner's page (which has no session: the
20600
- // owner picks in Settings → Browser or where the run is set up).
20775
+ // owner picks in Settings → Connected tools → MoreLogin (Default AI browser) or where the run is set up).
20601
20776
  const _profileChoiceStore = createProfileChoiceStore({
20602
20777
  file: resolve(LOOP_DATA_DIR, 'browser-profile-choices.json'),
20603
20778
  log: (line) => console.warn(`[morelogin] ${line}`),
20604
20779
  });
20780
+ // A run whose own profile failed to start or connect in this run (lib/morelogin-profile-failures.js): it may not move to
20781
+ // another profile until that profile connects again for it, the owner moves it, or it ends (runProfileSwitchRefusal).
20782
+ const _runProfileFailures = createProfileFailureStore({
20783
+ file: resolve(LOOP_DATA_DIR, 'morelogin-profile-failures.json'),
20784
+ log: (line) => console.warn(`[morelogin] ${line}`),
20785
+ });
20605
20786
 
20606
20787
  /**
20607
20788
  * The owners of the saved choices are retired when the server starts (called once, as it starts listening, before any
@@ -20647,8 +20828,8 @@ async function resolveMoreLoginProfileChoice(ref) {
20647
20828
  async function chooseSessionMoreLoginProfile(ownerKey, choice) {
20648
20829
  const previous = runMoreLoginPin(ownerKey);
20649
20830
  // A session's own choice is always an agent's ('agent'): held to the owner's list when it is set (the route) and at
20650
- // every use (moreLoginPinRefusal).
20651
- pinRunMoreLoginProfile(ownerKey, choice?.envId || null, choice?.name || null, 'agent');
20831
+ // every use (moreLoginPinRefusal). Not locked: the session chose it, and may choose again.
20832
+ pinRunMoreLoginProfile(ownerKey, choice?.envId || null, choice?.name || null, 'agent', { locked: false });
20652
20833
  // A plain MCP session's id dies with this server: its choice is never kept for a restart (MCP_SESSION_PROOFS).
20653
20834
  if (!isMcpSessionOwner(ownerKey)) _profileChoiceStore.set(ownerKey, choice?.envId ? choice : null);
20654
20835
  const cfg = loadBrowserConfig();
@@ -20669,28 +20850,62 @@ async function chooseSessionMoreLoginProfile(ownerKey, choice) {
20669
20850
  return { previous, released };
20670
20851
  }
20671
20852
 
20853
+ /**
20854
+ * 409 PROFILE_PINNED: `owner`'s profile was set up with the run (`pin.locked`), and it asked to move to `choice` (a
20855
+ * profile { envId, name }, or null for the default browser). Nothing changes.
20856
+ */
20857
+ function refusePinnedProfileMove(res, owner, pin, choice) {
20858
+ const here = describeMoreLoginPin(pin);
20859
+ const there = choice?.envId ? describeMoreLoginPin(choice) : 'the default browser';
20860
+ console.warn(`[morelogin] ${logOwnerId(owner)} is pinned to ${here}: its move to ${there} was refused`);
20861
+ loopLog(owner, 'browser:profile', `refused: this run is pinned to ${here} and cannot move to ${there}`, { pinned: pin.envId, asked: choice?.envId || null });
20862
+ return res.status(409).json({
20863
+ ok: false, code: 'PROFILE_PINNED', envId: pin.envId, name: pin.name || null,
20864
+ error: `This run is pinned to ${here} (set where the run is set up: its schedule, group, launch or dispatch); it cannot move to ${there}. Nothing was changed: it still works in ${here}. A pinned run never switches profiles by itself: if its profile cannot be used (closed, not running, refused by MoreLogin), report that to the user and stop. The owner changes a run's profile where the run is set up.`,
20865
+ });
20866
+ }
20867
+
20672
20868
  app.post('/api/morelogin/use', async (req, res) => {
20673
20869
  try {
20674
20870
  const who = browserCaller(req);
20675
20871
  if (!who.accepted) return refuseBrowserCaller(res, who);
20676
20872
  const owner = who.automation ? browserOwnerId(who.id) : null;
20677
20873
  if (!owner) {
20678
- return res.status(400).json({ ok: false, code: 'SESSION_REQUIRED', error: 'This picks the MoreLogin profile of the calling agent session (the morelogin tool\'s "use" action). The owner picks the default in Settings → Browser, and a run\'s profile where the run is set up.' });
20874
+ return res.status(400).json({ ok: false, code: 'SESSION_REQUIRED', error: 'This picks the MoreLogin profile of the calling agent session (the morelogin tool\'s "use" action). The owner picks the default in Settings → Connected tools → MoreLogin (Default AI browser), and a run\'s profile where the run is set up.' });
20679
20875
  }
20680
20876
  if (automationRunState(owner) === 'ended') {
20681
20877
  return res.status(409).json({ ok: false, code: 'RUN_ENDED', error: `Run ${owner} has ended: its browser profile is not changed.` });
20682
20878
  }
20683
20879
  const body = req.body || {};
20684
20880
  const toDefault = body.default === true || body.default === 'true';
20881
+ // A run whose own profile failed to start or connect in this run does not move to another profile or browser, even
20882
+ // one it chose itself (2026-11-15 21:13:43: run 8d50b030 had chosen P-4 with `use`, P-4 failed to connect, it moved
20883
+ // itself to P-1 and its next browser call started P-1, one of MoreLogin's daily launches). Refused here, before
20884
+ // MoreLogin is asked for anything; naming the failed profile itself is no move and goes on below. Lifted when that
20885
+ // profile connects again for the run, the owner moves the run, or it ends (lib/morelogin-profile-failures.js).
20886
+ const failedBar = runProfileSwitchRefusal(owner, toDefault ? { toDefault: true } : { envId: body.envId, name: body.name, profile: body.profile });
20887
+ if (failedBar) return refuseProfileSwitchAfterFailure(res, failedBar);
20888
+ // A run whose setup pinned its profile (a schedule, a group, a timer, a launch, a dispatch's morelogin_profile)
20889
+ // stays there: it is refused before anything is resolved or changed when it asks for the default browser, and
20890
+ // below when it names another profile (2026-11-15: a run on P-4 whose profile had gone moved itself to P-1, and
20891
+ // its recovery started P-1, one of MoreLogin's daily launches). A session that chose its profile itself may still
20892
+ // choose again (today's behaviour).
20893
+ const pinnedBefore = runMoreLoginPin(owner);
20894
+ if (pinnedBefore?.locked && toDefault) return refusePinnedProfileMove(res, owner, pinnedBefore, null);
20685
20895
  // The owner's list (review b6631e9d, finding 1): a session works only in a profile the owner allowed agents to
20686
20896
  // choose. Going back to the default needs no entry. Whoever calls this is never the owner's page (SESSION_REQUIRED
20687
20897
  // above), so there is no exception here. The gate in front proved the caller's id (MORELOGIN_VERIFIED_ROUTES).
20688
20898
  const choice = toDefault ? null : await agentMoreLoginProfileChoice({ envId: body.envId, name: body.name, profile: body.profile });
20899
+ // Asked again with what the name resolved to (a name the failed profile had may now be another profile's).
20900
+ const resolvedBar = choice ? runProfileSwitchRefusal(owner, { envId: choice.envId, name: choice.name, resolved: true }) : null;
20901
+ if (resolvedBar) return refuseProfileSwitchAfterFailure(res, resolvedBar);
20689
20902
  const before = runMoreLoginPin(owner);
20690
- // Asked again for what it already has: nothing is released (its tab there stays its tab), and a pin the owner's
20691
- // page set at launch stays the owner's (it is not rewritten as the session's own).
20903
+ if (before?.locked && (before.envId || null) !== (choice?.envId || null)) return refusePinnedProfileMove(res, owner, before, choice);
20904
+ // Asked again for what it already has: nothing is released (its tab there stays its tab), a pin the owner's
20905
+ // page set at launch stays the owner's (it is not rewritten as the session's own), and a pin its setup made stays
20906
+ // locked.
20692
20907
  if ((before?.envId || null) === (choice?.envId || null)) {
20693
- if (choice && before?.by !== 'owner') { pinRunMoreLoginProfile(owner, choice.envId, choice.name, 'agent'); if (!isMcpSessionOwner(owner)) _profileChoiceStore.set(owner, choice); }
20908
+ if (choice && before?.by !== 'owner' && !before?.locked) { pinRunMoreLoginProfile(owner, choice.envId, choice.name, 'agent', { locked: false }); if (!isMcpSessionOwner(owner)) _profileChoiceStore.set(owner, choice); }
20694
20909
  return res.json({ ok: true, changed: false, envId: choice?.envId || null, name: choice?.name || null, default: !choice, released: [] });
20695
20910
  }
20696
20911
  const { previous, released } = await chooseSessionMoreLoginProfile(owner, choice);
@@ -21213,16 +21428,31 @@ function readClaudeSettingsForWrite(filePath) {
21213
21428
  function writeClaudeSettings(filePath, data) {
21214
21429
  const dir = dirname(filePath);
21215
21430
  if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
21431
+ // The settings file may be a link (dotfiles, a synced folder): the file behind it is the one written, and the
21432
+ // link stays. A rename over the link would leave a plain file here and the linked one as it was, so whatever
21433
+ // makes the link again later brings the old content back, without anything changed through SynaBun.
21434
+ let target = filePath;
21435
+ try { if (existsSync(filePath)) target = realpathSync(filePath); } catch { /* written where it was asked */ }
21216
21436
  // Write atomically. A half-written settings.json (crash or full disk during
21217
21437
  // writeFileSync) is what makes the corrupt-read path reachable to begin with.
21218
- const tmpPath = `${filePath}.tmp-${process.pid}`;
21438
+ const tmpPath = `${target}.tmp-${process.pid}`;
21439
+ // A file with other names (a named Claude account on Windows shares settings.json by a hard link,
21440
+ // lib/claude-account-links.js) is written in place: a rename would leave the other names the old file.
21441
+ let names = 1;
21442
+ try { names = Number(statSync(target).nlink) || 1; } catch {}
21219
21443
  try {
21220
21444
  writeFileSync(tmpPath, JSON.stringify(data, null, 2), 'utf-8');
21221
- renameSync(tmpPath, filePath);
21445
+ if (names > 1) { writeFileSync(target, readFileSync(tmpPath)); unlinkSync(tmpPath); } else renameSync(tmpPath, target);
21222
21446
  } catch (err) {
21223
21447
  try { if (existsSync(tmpPath)) unlinkSync(tmpPath); } catch {}
21224
21448
  throw err;
21225
21449
  }
21450
+ // The default's settings changed: every named account reads the same (a hard link that Claude Code's own
21451
+ // rename-write split, or a copy, is brought back in step). Never stops a write.
21452
+ try {
21453
+ const accounts = _panelClaudeAccounts();
21454
+ if ([getGlobalClaudeSettingsPath(), join(accounts.defaultHome, 'settings.json')].some((path) => resolve(path) === resolve(filePath))) accounts.syncShared();
21455
+ } catch {}
21226
21456
  }
21227
21457
 
21228
21458
  function isHookInstalled(settings, targetProjectPath) {
@@ -21599,11 +21829,51 @@ const SYNABUN_TOOL_CATEGORIES = [
21599
21829
  },
21600
21830
  ];
21601
21831
 
21832
+ // ── The owner's tool-permission choices (lib/tool-permission-choices.js) ──
21833
+ // The switches of Settings → Tool permissions are drawn from, and change, the allow list of the user's
21834
+ // ~/.claude/settings.json: Claude Code's own file, which other things rewrite and replace. SynaBun keeps what the
21835
+ // owner chose in its data home too (DATA_HOME/data/tool-permissions.json, never touched by an install or an
21836
+ // update) and puts back what went missing: every saved tool at a start (an update is a start), and at a read
21837
+ // only when all of them are gone at once. A tool the owner switched off is never allowed by SynaBun itself; a
21838
+ // tool nobody chose (one that is new in an update) keeps the default: off until it is switched on.
21839
+ const TOOL_PERMISSION_KEYS = new Set(SYNABUN_TOOL_CATEGORIES.flatMap(cat => cat.tools.map(t => t.key)));
21840
+ const toolChoices = createToolPermissionChoices({
21841
+ path: resolve(DATA_HOME, 'data', TOOL_CHOICES_FILE),
21842
+ appVersion: SERVER_VERSION,
21843
+ log: (line) => console.log(line),
21844
+ });
21845
+ /** Bring the allow list in line with the saved choices. `reason`: 'start' | 'read'. Never throws. */
21846
+ function reconcileSavedToolPermissions(reason) {
21847
+ try {
21848
+ const result = reconcileToolPermissions({
21849
+ store: toolChoices, settingsPath: getGlobalClaudeSettingsPath(), known: TOOL_PERMISSION_KEYS, reason,
21850
+ read: readClaudeSettingsForWrite, write: writeClaudeSettings, log: (line) => console.log(line),
21851
+ });
21852
+ if (result.state === 'error' && reason === 'start') console.warn(`[tool-permissions] the saved choices were not applied: ${result.message}`);
21853
+ // Codex reads its own copy of the list (config.toml): it gets what was put back.
21854
+ if (result.state === 'restored') { try { syncCodexToolPermissions(result.allow); } catch { /* Codex's file is its own matter */ } }
21855
+ return result;
21856
+ } catch (err) {
21857
+ console.warn(`[tool-permissions] the saved choices were not applied: ${err.message}`);
21858
+ return { state: 'error', restored: [], adopted: [], allow: [], message: err.message };
21859
+ }
21860
+ }
21861
+ /** The on / off state of every tool, as the allow list has it. */
21862
+ function toolPermissionStates(allow) {
21863
+ const allowed = new Set(Array.isArray(allow) ? allow : []);
21864
+ const tools = {};
21865
+ for (const cat of SYNABUN_TOOL_CATEGORIES) {
21866
+ for (const t of cat.tools) tools[t.key] = allowed.has(t.key);
21867
+ }
21868
+ return tools;
21869
+ }
21870
+
21602
21871
  // ── Memory-tool permission auto-injection ──
21603
- // On MCP enable for any provider, force-allow the 7 SynaBun memory tools
21872
+ // On MCP enable for any provider, allow the 7 SynaBun memory tools
21604
21873
  // (recall/remember/reflect/forget/memories/restore/sync) so PTY/CLI sessions
21605
21874
  // can use SynaBun memory without per-call permission prompts. Inject-only,
21606
- // never overwrites existing entries. Falls back to project-scoped settings
21875
+ // never overwrites existing entries, and never a tool the owner switched off
21876
+ // in Settings → Tool permissions. Falls back to project-scoped settings
21607
21877
  // when the user has no global settings file.
21608
21878
  function getMemoryToolKeys() {
21609
21879
  const cat = SYNABUN_TOOL_CATEGORIES.find(c => c.id === 'memory');
@@ -21623,7 +21893,7 @@ function ensureOpenCodeCoreMcpPermissions(config) {
21623
21893
  }
21624
21894
 
21625
21895
  function injectClaudeMemoryPerms() {
21626
- const keys = getMemoryToolKeys();
21896
+ const keys = getMemoryToolKeys().filter(k => !toolChoices.isOff(k));
21627
21897
  const globalPath = getGlobalClaudeSettingsPath();
21628
21898
 
21629
21899
  if (existsSync(globalPath)) {
@@ -21634,6 +21904,7 @@ function injectClaudeMemoryPerms() {
21634
21904
  for (const k of keys) set.add(k);
21635
21905
  settings.permissions.allow = [...set];
21636
21906
  writeClaudeSettings(globalPath, settings);
21907
+ toolChoices.adopt(settings.permissions.allow, TOOL_PERMISSION_KEYS);
21637
21908
  return { scope: 'global', paths: [globalPath] };
21638
21909
  }
21639
21910
 
@@ -23589,19 +23860,20 @@ app.get('/api/claude-code/tool-categories', (req, res) => {
23589
23860
  });
23590
23861
 
23591
23862
  // GET /api/claude-code/tool-permissions — current permission state for all SynaBun tools
23863
+ // `capabilities`: what the PUT below takes beyond one tool or one category (`categories`: several groups in one
23864
+ // request), so a page that was reloaded before this server was restarted knows what it can ask.
23592
23865
  app.get('/api/claude-code/tool-permissions', (req, res) => {
23593
23866
  try {
23867
+ // A file that lost every saved tool at once was replaced: the saved choices go back before it is read.
23868
+ const reconciled = reconcileSavedToolPermissions('read');
23594
23869
  const globalPath = getGlobalClaudeSettingsPath();
23595
23870
  const settings = readClaudeSettings(globalPath) || {};
23596
- const allowed = new Set(settings.permissions?.allow || []);
23597
-
23598
- const tools = {};
23599
- for (const cat of SYNABUN_TOOL_CATEGORIES) {
23600
- for (const t of cat.tools) {
23601
- tools[t.key] = allowed.has(t.key);
23602
- }
23603
- }
23604
- res.json({ ok: true, tools });
23871
+ res.json({
23872
+ ok: true,
23873
+ tools: toolPermissionStates(settings.permissions?.allow),
23874
+ capabilities: ['categories'],
23875
+ ...(reconciled.restored.length ? { restored: reconciled.restored.length } : {}),
23876
+ });
23605
23877
  } catch (err) {
23606
23878
  res.status(500).json({ error: err.message });
23607
23879
  }
@@ -23686,30 +23958,48 @@ app.delete('/api/claude-code/permission-rules', express.json(), (req, res) => {
23686
23958
  // The user scope of a tab under a named account is that account's file.
23687
23959
  const accountHome = panelAccountHome(req.body?.account);
23688
23960
  const result = removePermissionRule({ home: process.env.USERPROFILE || process.env.HOME, accountHome, project, scope, list, rule });
23961
+ // An allow rule of one of SynaBun's tools, taken out of the user's own settings: that tool is off by the owner's
23962
+ // choice from now on, so a start does not put it back (lib/tool-permission-choices.js).
23963
+ if (result.removed && scope === 'user' && list === 'allow' && TOOL_PERMISSION_KEYS.has(rule)
23964
+ && (!accountHome || userSettingsFile({ home: process.env.USERPROFILE || process.env.HOME, accountHome }).shared)) {
23965
+ toolChoices.note([rule], false);
23966
+ }
23689
23967
  res.json({ ok: true, removed: result.removed });
23690
23968
  } catch (err) {
23691
23969
  res.status(err?.status || 500).json({ ok: false, error: err.message, ...(err?.code ? { code: err.code } : {}) });
23692
23970
  }
23693
23971
  });
23694
23972
 
23695
- // PUT /api/claude-code/tool-permissions — toggle individual tool or category group
23973
+ // PUT /api/claude-code/tool-permissions — toggle one tool, one category group, or several groups at once
23974
+ // (`categories`: the switch in the section's header sends the groups it shows). What is switched is also
23975
+ // written down as the owner's choice (toolChoices), which is what a later start puts back.
23696
23976
  app.put('/api/claude-code/tool-permissions', (req, res) => {
23697
23977
  try {
23698
- const { tool, category, enabled } = req.body;
23978
+ const { tool, category, categories, enabled } = req.body || {};
23699
23979
  if (typeof enabled !== 'boolean') {
23700
23980
  return res.status(400).json({ error: 'enabled (boolean) is required.' });
23701
23981
  }
23702
- if (!tool && !category) {
23703
- return res.status(400).json({ error: 'Provide tool (string) or category (string).' });
23982
+ if (categories !== undefined && (!Array.isArray(categories) || !categories.length || categories.some(id => typeof id !== 'string'))) {
23983
+ return res.status(400).json({ error: 'categories must be a list of category ids.' });
23984
+ }
23985
+ if (!tool && !category && !categories) {
23986
+ return res.status(400).json({ error: 'Provide tool (string), category (string) or categories (list).' });
23704
23987
  }
23705
23988
 
23706
23989
  // Resolve which tool keys to toggle
23707
23990
  let keys = [];
23708
- if (category) {
23991
+ if (categories) {
23992
+ for (const id of new Set(categories)) {
23993
+ const cat = SYNABUN_TOOL_CATEGORIES.find(c => c.id === id);
23994
+ if (!cat) return res.status(400).json({ error: `Unknown category: ${id}` });
23995
+ keys.push(...cat.tools.map(t => t.key));
23996
+ }
23997
+ } else if (category) {
23709
23998
  const cat = SYNABUN_TOOL_CATEGORIES.find(c => c.id === category);
23710
23999
  if (!cat) return res.status(400).json({ error: `Unknown category: ${category}` });
23711
24000
  keys = cat.tools.map(t => t.key);
23712
24001
  } else {
24002
+ if (typeof tool !== 'string') return res.status(400).json({ error: 'tool must be a string.' });
23713
24003
  keys = [tool];
23714
24004
  }
23715
24005
 
@@ -23726,6 +24016,8 @@ app.put('/api/claude-code/tool-permissions', (req, res) => {
23726
24016
  }
23727
24017
  settings.permissions.allow = [...allowSet];
23728
24018
  writeClaudeSettings(globalPath, settings);
24019
+ // The owner's choice, in SynaBun's own data home: what an update, a restore or a replaced file cannot take.
24020
+ toolChoices.note(keys, enabled);
23729
24021
 
23730
24022
  // Cascade to registered projects
23731
24023
  const projects = loadHookProjects();
@@ -23749,14 +24041,7 @@ app.put('/api/claude-code/tool-permissions', (req, res) => {
23749
24041
  syncCodexToolPermissions(settings.permissions.allow);
23750
24042
 
23751
24043
  // Return updated state
23752
- const updatedAllowed = new Set(settings.permissions.allow);
23753
- const tools = {};
23754
- for (const cat of SYNABUN_TOOL_CATEGORIES) {
23755
- for (const t of cat.tools) {
23756
- tools[t.key] = updatedAllowed.has(t.key);
23757
- }
23758
- }
23759
- res.json({ ok: true, tools });
24044
+ res.json({ ok: true, tools: toolPermissionStates(settings.permissions.allow) });
23760
24045
  } catch (err) {
23761
24046
  res.status(500).json({ error: err.message });
23762
24047
  }
@@ -23978,6 +24263,7 @@ function syncCodexToolPermissions(allowedKeys, codexHome = CODEX_DEFAULT_HOME) {
23978
24263
  }
23979
24264
 
23980
24265
  writeFileSync(configPath, content, 'utf-8');
24266
+ try { codexSharedFilesChanged(); } catch { /* never stops the write */ }
23981
24267
  } catch (err) {
23982
24268
  console.error('[codex-perm-sync] Failed to sync Codex tool permissions:', err.message);
23983
24269
  }
@@ -24101,6 +24387,7 @@ app.post('/api/setup/codex/mcp', (req, res) => {
24101
24387
  const health = upsertCodexMcpConfig(configPath, buildCodexMcpDefinition());
24102
24388
  // Force-allow the 7 SynaBun memory tools so CLI sessions skip prompts.
24103
24389
  injectCodexMemoryPerms();
24390
+ codexSharedFilesChanged();
24104
24391
  res.json({ ok: true, ...health, message: 'SynaBun MCP registered in Codex CLI. Restart Codex to connect.', rules: syncRulesWithMcp('codex', 'install', req.body) });
24105
24392
  } catch (err) {
24106
24393
  res.status(500).json({ error: err.message });
@@ -24112,6 +24399,7 @@ app.delete('/api/setup/codex/mcp', (req, res) => {
24112
24399
  const configPath = join(CODEX_DEFAULT_HOME, 'config.toml');
24113
24400
  if (!existsSync(configPath)) return res.json({ ok: true, rules: syncRulesWithMcp('codex', 'remove') });
24114
24401
  const health = removeCodexMcpConfig(configPath);
24402
+ codexSharedFilesChanged();
24115
24403
  res.json({ ok: true, ...health, message: 'SynaBun MCP removed from Codex CLI.', rules: syncRulesWithMcp('codex', 'remove') });
24116
24404
  } catch (err) {
24117
24405
  res.status(500).json({ error: err.message });
@@ -24344,6 +24632,70 @@ registerSkillEvalRoutes(app, {
24344
24632
  pageSession: _pageSession,
24345
24633
  });
24346
24634
 
24635
+ // ════ agents-p1 BEGIN: the Agents system's registry, resolver and API (docs/agents.md, lib/coordination/README.md) ════
24636
+ // The one block of the Agents system's phase P1 in this file. The registry of agent definitions
24637
+ // (DATA_HOME/data/agents: one editable draft and immutable approved revisions per agent and scope, lib/agents/registry.js),
24638
+ // the resolver that turns a dispatch's `agent_ref` into a run (lib/agents/resolve.js: the dispatcher's intake and the
24639
+ // Assistant's /route ask the resolver of the process, which is set here, so nothing else in this file hands it over),
24640
+ // and the routes of Agents Studio under /api/agents-studio/v1 (lib/agents-studio-api.js: approving, deleting and test
24641
+ // runs are the owner's page only, as the Skills Service's installs are). The older /api/agents routes above (isolated
24642
+ // agent processes) are another thing and stay as they are.
24643
+ import { createAgentRegistry } from './lib/agents/registry.js';
24644
+ import { createAgentResolver, setAgentResolver } from './lib/agents/resolve.js';
24645
+ import { registerStudioAttention } from './lib/studio-attention.js';
24646
+ import { registerAgentsStudioRoutes } from './lib/agents-studio-api.js';
24647
+ const agentDefinitions = createAgentRegistry({
24648
+ dir: resolve(DATA_HOME, 'data', 'agents'),
24649
+ // Every page of the owner hears of a change; invite guests do not (broadcastSync keeps `assistant:` to the owner).
24650
+ emit: (event) => { try { broadcastSync({ type: 'assistant:agents-changed', event }); } catch { /* no page is listening */ } },
24651
+ });
24652
+ registerStudioAttention(app, {
24653
+ ownerPage: (req, res, next) => ownerPageApprovalCall(req) ? next() : refuseNotOwnerPage(req, res, 'The Studio attention indicator is available on the owner’s page.'),
24654
+ agents: () => agentDefinitions.list({ status: 'in_review' }),
24655
+ teams: () => _assistantTeamScheduler?.list({ open: true }) || [],
24656
+ reviews: () => skillReviews.list({ state: 'pending' }),
24657
+ // Only the marks and schedule state are used. No tool resolution or approval evidence is needed.
24658
+ templates: () => mergeLoopItemsById(readLoopTemplateFiles(), 'templates'),
24659
+ schedules: () => mergeLoopItemsById(readLoopScheduleFiles(), 'schedules'),
24660
+ workers: () => _assistantDispatcher?.hasRunAwaitingOwner() || false,
24661
+ nativeRuns: () => _nativeLoopRuntime?.list({ activeOnly: true }) || [],
24662
+ });
24663
+ const agentDefinitionResolver = setAgentResolver(createAgentResolver({ registry: agentDefinitions }));
24664
+ // ── agents-p6 BEGIN: what agent-forge and native export read from this server (lib/agents/forge-host.js) ──
24665
+ // The guide is the shipped skill skills/agent-forge; the catalog a definition is filled from is asked of the parts
24666
+ // that own it (the Assistant's model catalog, the tool catalog, the project's style guide, the MoreLogin profiles
24667
+ // the owner lets agents choose); a native export goes where Skills Studio's own agent files go (Claude Code's config
24668
+ // dir, OpenCode's configuration folder, or a registered project), and only the owner's page writes one.
24669
+ import { createAgentForgeHost } from './lib/agents/forge-host.js';
24670
+ const agentForgeHost = createAgentForgeHost({
24671
+ skillsDir: SKILLS_SOURCE_DIR,
24672
+ catalog: async ({ provider = null, q = null } = {}) => (_assistantCatalog ? _assistantCatalog.get({ view: 'brain', provider, q }) : null),
24673
+ styleGuide: (projectPath) => { const guide = styleGuideStore.load(projectPath); return guide?.saved ? guide.config : null; },
24674
+ moreloginProfiles: () => moreLoginAgentProfiles(),
24675
+ projects: () => { try { return loadHookProjects().filter((p) => p?.path).map((p) => ({ path: p.path, label: p.label || basename(p.path) })); } catch { return []; } },
24676
+ claudeHome: () => studioClaudeHome(),
24677
+ claudeHomes: () => { try { return _panelClaudeAccounts().list().map((row) => ({ id: row.id, home: row.home })); } catch { return []; } },
24678
+ opencodeConfigDir: () => getOpencodeConfigDir(),
24679
+ homeDir: getHomePath(),
24680
+ onExport: (event) => { try { broadcastSync({ type: 'assistant:agents-changed', event }); } catch { /* no page is listening */ } },
24681
+ });
24682
+ // ── agents-p6 END ──
24683
+ registerAgentsStudioRoutes(app, {
24684
+ registry: agentDefinitions, resolver: agentDefinitionResolver, isGuestRequest,
24685
+ forge: agentForgeHost, // agents-p6
24686
+ // The runs of an agent and the owner's test run (the dispatcher is made later, with the Assistant).
24687
+ dispatcher: () => _assistantDispatcher,
24688
+ ownerGuard: ownerRouteGuard({ isGuestRequest, port: PORT, allowedOrigins: publicWebOrigins, refuseCrossSite: true, ownOriginsOnly: true, requireOrigin: true }),
24689
+ // The owner's writes carry the page secret (lib/page-session.js): a local process without it is refused.
24690
+ pageSession: _pageSession,
24691
+ // An agent is the Assistant only by its brain's launch credential (never by X-Synabun-Role alone).
24692
+ assistantOf: (req) => skillsAssistantOf(req),
24693
+ // An agent's X-Synabun-Terminal (its author's name) counts only with its proof (browserCaller).
24694
+ terminalRefusal: (req) => { const who = browserCaller(req); return who.accepted ? null : { status: who.httpStatus || 403, code: who.code, error: who.error }; },
24695
+ projects: () => { try { return loadHookProjects().filter((p) => p?.path).map((p) => ({ path: p.path, label: p.label || basename(p.path) })); } catch { return []; } },
24696
+ });
24697
+ // ════ agents-p1 END ════
24698
+
24347
24699
  /**
24348
24700
  * Each runtime an evaluation can run on here: found (the same answer as drafting's), held to its folder, and whether
24349
24701
  * a case that needs a shell can have one (Codex: its own sandbox, always, and Codex is the owner's opt-in per skill
@@ -24465,7 +24817,7 @@ function skillDraftingAvailability() {
24465
24817
  return { available: !!any, reason: any ? null : (claude?.reason || 'No provider that can draft was found on this computer.'), providers };
24466
24818
  }
24467
24819
 
24468
- /** Whether the SynaBun browser (the one Settings → Browser chose) can open a page for a draft now, and if not why. */
24820
+ /** Whether the SynaBun browser (the default AI browser: a MoreLogin tab profile, else SynaBun's own) can open a page for a draft now, and if not why. */
24469
24821
  function skillBrowserAvailability() {
24470
24822
  try {
24471
24823
  const cfg = loadBrowserConfig();
@@ -24475,14 +24827,14 @@ function skillBrowserAvailability() {
24475
24827
  // The default is one of SynaBun's own local profiles: MoreLogin is not needed for it.
24476
24828
  return moreLogin.localProfileName(String(cfg.moreloginEnvId))
24477
24829
  ? { available: true, reason: null }
24478
- : { available: false, reason: 'The default browser (Settings → Browser) is a local profile that no longer exists: choose another one.' };
24830
+ : { available: false, reason: 'The default AI browser (Settings → Connected tools → MoreLogin) is a local profile that no longer exists: choose another one.' };
24479
24831
  }
24480
24832
  if (cfg.connectMode === 'morelogin') {
24481
24833
  // The exe in a known folder, or the local API answered lately (an install in a custom folder). This is read
24482
24834
  // synchronously, so a miss refreshes the answer in the background for the next call.
24483
24835
  const installed = moreLogin.isMoreLoginPresent();
24484
24836
  if (!installed) moreLogin.probeMoreLoginApi({ savedCfg: cfg, timeout: 1500 }).catch(() => {});
24485
- return installed ? { available: true, reason: null } : { available: false, reason: 'MoreLogin is the default browser (Settings → Browser) and it was not found: its app is in no known folder and its local API does not answer.' };
24837
+ return installed ? { available: true, reason: null } : { available: false, reason: 'MoreLogin is the default AI browser (Settings → Connected tools → MoreLogin) and it was not found: its app is in no known folder and its local API does not answer.' };
24486
24838
  }
24487
24839
  if ([...browserSessions.values()].some((s) => s?.context)) return { available: true, reason: null };
24488
24840
  if (findBrowserExecutable(cfg.channel)) return { available: true, reason: null };
@@ -29059,6 +29411,48 @@ _nativeLoopRuntime = new NativeLoopRuntime({
29059
29411
  },
29060
29412
  });
29061
29413
 
29414
+ // What the computer-use service says about who holds the desktop now (its `status().control`), once it exists: read by
29415
+ // the evidence line of a MoreLogin profile closed outside SynaBun (lib/browser-close-evidence.js). null until then.
29416
+ let _desktopControlProbe = null;
29417
+ // MoreLogin profiles SynaBun itself stopped (POST /api/morelogin/stop): envId → when. A browser that goes within
29418
+ // a minute of that is not reported as closed outside SynaBun.
29419
+ const _moreLoginStoppedBySynaBun = new Map();
29420
+
29421
+ /**
29422
+ * A MoreLogin profile session's browser context closed (createBrowserSession's context 'close' handler): who closed
29423
+ * it, said once. Returns what it decided:
29424
+ * 'revoked' — SynaBun's OpenCode serve boundary let go of the context (lib/opencode-native-boundary.js
29425
+ * revokeNativeContext: the profile's window is kept). Never "outside SynaBun", never a mark.
29426
+ * 'synabun' — SynaBun closed it: its own teardown (destroyBrowserSession took the session out of the map first) or
29427
+ * POST /api/morelogin/stop in the last minute.
29428
+ * 'outside' — nobody in SynaBun: the evidence line (lib/browser-close-evidence.js), and the close is remembered for
29429
+ * the profile (lib/morelogin-outside-close.js): no automatic path starts it again (each start spends one
29430
+ * of MoreLogin's daily launches) until the owner starts it, a new scheduled run fires, or MoreLogin's
29431
+ * daily reset. The runs it orphaned are kept on the mark (their loops end after their turn).
29432
+ * null — not a MoreLogin profile (a local profile, another browser).
29433
+ * Before 2026-11-15 a revocation was reported as closed outside SynaBun: the 21:13:30 and 21:14:22 lines of that night
29434
+ * were SynaBun's own (a foreign OpenCode serve failed its check while it was exiting, and the revocation closed every
29435
+ * page of P-1 and P-4).
29436
+ */
29437
+ function noteMoreLoginContextClose(session, sessionId, context = session?.context) {
29438
+ if (session?._profileMode !== 'morelogin' || !session._mlEnvId || moreLogin.isLocalProfileId(String(session._mlEnvId))) return null;
29439
+ const envId = String(session._mlEnvId);
29440
+ const revoked = nativeContextRevocation(context);
29441
+ if (revoked) {
29442
+ console.log(`[morelogin] SynaBun let go of profile ${envId} (session ${sessionId}): the OpenCode serve check revoked its browser context (${revoked.why || 'no reason given'}). Its window was kept open; nobody else closed it, and the runs there attach again without a new start`);
29443
+ return 'revoked';
29444
+ }
29445
+ if (browserSessions.get(sessionId) !== session || session._tearingDown
29446
+ || Date.now() - (_moreLoginStoppedBySynaBun.get(envId) || 0) < 60_000) return 'synabun';
29447
+ const owners = [...(session._loopOwned || [])];
29448
+ logUnexpectedProfileClose({ envId, sessionId, desktopControl: () => _desktopControlProbe?.() || null }).catch(() => {});
29449
+ let mark = null;
29450
+ try { mark = moreLogin.noteOutsideClose(envId, { at: Date.now(), sessionId, owners, name: _moreLoginEnvNames.get(envId) || null }); }
29451
+ catch (err) { console.warn(`[morelogin] the close of profile ${envId} outside SynaBun was not remembered: ${err?.message || err}`); }
29452
+ if (mark) console.log(`[morelogin] profile ${envId} is not started again by SynaBun for anybody (${owners.length ? `it served ${owners.map(logOwnerId).join(', ')}` : 'it served no run'}) until the owner starts it, a new scheduled run fires, or MoreLogin's daily reset at ${new Date(mark.until).toISOString()}`);
29453
+ return 'outside';
29454
+ }
29455
+
29062
29456
  // ── Main assistant: brains + orchestration (lib/assistant-*.js) ──
29063
29457
  // Everything lives in lib/; this block only wires dependencies and mounts the
29064
29458
  // router + WebSocket handler. Failure here degrades to "assistant unavailable"
@@ -29526,10 +29920,26 @@ _nativeLoopRuntime = new NativeLoopRuntime({
29526
29920
  log: (tag, message) => assistantLog(tag, message),
29527
29921
  });
29528
29922
  app.use('/api/desktop', createDesktopApi({ desktop: assistantDesktop, isGuestRequest, log: (tag, message) => assistantLog(tag, message) }));
29923
+ { const desktop = assistantDesktop; _desktopControlProbe = () => desktop.status()?.control || null; }
29529
29924
  } catch (err) {
29530
29925
  console.warn('[assistant] computer use unavailable:', err.message);
29531
29926
  assistantDesktop = null;
29532
29927
  }
29928
+ // ══ Agents P2: durable agent messaging ═════════════════════════════════════════════════════════════════════
29929
+ // This server's one coordination store (DATA_HOME/data/coordination.db; lib/coordination/README.md): the run
29930
+ // events the dispatcher records, the Assistant's mailbox, the follow-up outbox. The dispatcher and the Assistant
29931
+ // runtime made right below take the shared service by themselves, so this block is the only place in this file
29932
+ // that creates it. runGracefulShutdown closes it after the scheduler and workers stop, including on signals;
29933
+ // an abrupt exit leaves the write-ahead log, which the next start reads back.
29934
+ {
29935
+ const { createCoordinationService, shareCoordinationService } = await import('./lib/coordination/service.js');
29936
+ const assistantCoordination = shareCoordinationService(createCoordinationService({ dataDir: LOOP_DATA_DIR, log: (tag, message) => assistantLog(tag, message) }));
29937
+ // The one instance of this server (never a second createCoordinationService in this file): a stop that is not
29938
+ // a signal (Restart Server, /api/server/shutdown, an update) closes it at the end of runGracefulShutdown.
29939
+ _assistantCoordination = assistantCoordination;
29940
+ if (assistantCoordination.degraded) console.warn(`[assistant] coordination store unavailable (${assistantCoordination.degraded.message}): agent events are kept in memory until the next start`);
29941
+ }
29942
+ // ══ end Agents P2 ══════════════════════════════════════════════════════════════════════════════════════════
29533
29943
  _assistantDispatcher = createAssistantDispatcher({
29534
29944
  resolveExternalTools: (spec, tools) => spec.provider
29535
29945
  ? selectExternalServers(tools, externalInventory(spec.provider, spec.cwd || PACKAGE_ROOT, { readProject: spec.provider !== 'opencode' || !openCodeProtectedWorker({ ...spec, cwd: spec.cwd || PACKAGE_ROOT, guardMode: _workerGuard.mode() }) }))
@@ -29559,8 +29969,13 @@ _nativeLoopRuntime = new NativeLoopRuntime({
29559
29969
  // Held to the owner's list of profiles agents may choose (agentMoreLoginProfileChoice: 403
29560
29970
  // MORELOGIN_PROFILE_NOT_ALLOWED), whoever dispatches; the pin is an agent's, so the list is asked again when the
29561
29971
  // worker's tab is acquired (a start, a resume) and at each of its browser calls.
29972
+ // pinBrowserProfile: a dispatch's morelogin_profile is the run's setup, locked (POST /api/morelogin/use refuses a
29973
+ // move). A resume re-pins the run's record, which a worker's own `use` rewrote (noteBrowserProfile): that one
29974
+ // stays the worker's own choice, as its saved choice says (_profileChoiceStore), and is not locked.
29562
29975
  resolveBrowserProfile: (ref) => agentMoreLoginProfileChoice(ref),
29563
- pinBrowserProfile: (runId, envId, name) => pinRunMoreLoginProfile(runId, envId, name, 'agent'),
29976
+ pinBrowserProfile: (runId, envId, name) => pinRunMoreLoginProfile(runId, envId, name, 'agent', {
29977
+ locked: (() => { try { return String(_profileChoiceStore.get(runId)?.envId || '') !== String(envId || ''); } catch { return true; } })(),
29978
+ }),
29564
29979
  memory: assistantMemory, detectProject: assistantDetectProject,
29565
29980
  // Limits are read live from assistant-config.json `limits`; the money is the session budget (the planner).
29566
29981
  limits: {},
@@ -29576,6 +29991,8 @@ _nativeLoopRuntime = new NativeLoopRuntime({
29576
29991
  clarifier: assistantClarifier,
29577
29992
  // The session's Test density, read when a worker's prompt is composed (assistant-test-density.js).
29578
29993
  testDensity: (sessionId) => _assistantRuntime?.testDensityFor?.(sessionId) ?? null,
29994
+ // agents-p4: the session's Agent density (lib/agents/density.js): the cap the team scheduler enforces.
29995
+ agentDensity: (sessionId) => _assistantRuntime?.agentDensityFor?.(sessionId) ?? null,
29579
29996
  // After a restart, workers are resumed once this server listens and the worker-only MCP channel (a sandboxed
29580
29997
  // worker's) is up or known to be off: a resumed CLI connects to SynaBun's MCP as it starts. 15 s at most.
29581
29998
  serverReady: () => new Promise((resolveReady) => {
@@ -29635,6 +30052,57 @@ _nativeLoopRuntime = new NativeLoopRuntime({
29635
30052
  // A brain's pin is proven by its launch credential (lib/terminal-tokens.js bind), revoked with the brain.
29636
30053
  terminalTokens: _terminalTokens,
29637
30054
  });
30055
+ // ════ agents-p4 BEGIN: the team scheduler (lib/teams/scheduler.js; docs/agents.md → Teams) ════
30056
+ // One task given to several workers, each in its own git worktree (lib/teams/, phase P3), within the session's
30057
+ // Agent density. The one scheduler of this server: it takes the coordination service's own store (claims, the
30058
+ // journal, the team channel and the run events are one file), dispatches through the Assistant's dispatcher and
30059
+ // is shared (shareTeamScheduler) for the Assistant's API (agent_team, a worker's team tool) and Agents Studio's
30060
+ // routes. The integration tests run under the worker sandbox where the platform has one (lib/teams/test-sandbox.js);
30061
+ // ignored node_modules folders are cloned into each worktree where the file system can (cloneNodeModules).
30062
+ // In its own try/catch: the Assistant runs without teams when this fails, and the team routes then answer 503.
30063
+ try {
30064
+ const { createTeams, createGitRunner, cloneNodeModules } = await import('./lib/teams/index.js');
30065
+ const { createTeamScheduler, shareTeamScheduler } = await import('./lib/teams/scheduler.js');
30066
+ const { createSandboxedTestRunner } = await import('./lib/teams/test-sandbox.js');
30067
+ const teamGit = createGitRunner();
30068
+ const teamScheduler = shareTeamScheduler(createTeamScheduler({
30069
+ teams: createTeams({
30070
+ store: _assistantCoordination.store, git: teamGit, setup: cloneNodeModules(),
30071
+ runTests: createSandboxedTestRunner({
30072
+ serverPort: () => Number(PORT) || null,
30073
+ reservedPortRange: () => ({ from: OCP_SHARED_PORT_MIN, to: OCP_ISO_PORT_MAX }),
30074
+ denyPaths: () => workerSecretTrees(),
30075
+ profileDir: resolve(LOOP_DATA_DIR, 'teams', 'sandbox'),
30076
+ log: (tag, message) => assistantLog(tag, message),
30077
+ }),
30078
+ log: (tag, detail) => assistantLog(tag, typeof detail === 'string' ? detail : JSON.stringify(detail)),
30079
+ }),
30080
+ coordination: _assistantCoordination,
30081
+ dispatcher: () => _assistantDispatcher,
30082
+ router: assistantRouter,
30083
+ // A remote conversation (WhatsApp) starts no team: one approved route covers one worker there.
30084
+ session: (sessionId) => ({ remote: !!_assistantRuntime?.sessionPolicy?.(sessionId), taskId: _assistantRuntime?.currentTask?.(sessionId) }),
30085
+ // The owner's latest UI turn: cleanup needs one after the team landed, so a worktree is never deleted on the model's word alone.
30086
+ lastOwnerTurnAt: (sessionId) => _assistantRuntime?.lastOwnerTurnAt?.(sessionId) ?? null,
30087
+ git: teamGit,
30088
+ dataDir: LOOP_DATA_DIR,
30089
+ // Every team event, to the owner's pages (broadcastSync keeps `assistant:` messages to the owner).
30090
+ broadcast: (message) => { try { broadcastSync(message); } catch { /* no page is listening */ } },
30091
+ log: (tag, detail) => assistantLog(tag, typeof detail === 'string' ? detail : JSON.stringify(detail)),
30092
+ }));
30093
+ // The `team` tool is advertised to a run that works a team slice (mcp-server/src/services/team-context.ts):
30094
+ // this server's answer for a run id, asked by its own /mcp mount and the worker-only channel.
30095
+ import('../mcp-server/dist/services/team-context.js')
30096
+ .then((m) => m.setTeamContextResolver((runId) => !!teamScheduler.member(runId)))
30097
+ .catch((err) => console.warn('[assistant] team tool unavailable (mcp-server needs a build):', err?.message || err));
30098
+ // After a restart: the library's own recovery, then every team under way is taken up again. Never awaited here.
30099
+ teamScheduler.recover().catch((err) => console.warn('[assistant] team recovery failed:', err?.message || err))
30100
+ .finally(() => broadcastSync({ type: 'assistant:team-changed', event: 'recovered' }));
30101
+ _assistantTeamScheduler = teamScheduler;
30102
+ } catch (err) {
30103
+ console.warn('[assistant] teams unavailable:', err?.message || err);
30104
+ }
30105
+ // ════ agents-p4 END ════
29638
30106
  assistantDesktop?.attach?.({ runtime: _assistantRuntime, dispatcher: _assistantDispatcher });
29639
30107
  // Warm the catalog so brain capabilities (vision, tier) are known on first attach,
29640
30108
  // then repair saved routes whose effort their model does not run (idempotent;
@@ -32300,6 +32768,69 @@ app.post('/api/terminal/links/:id/nudge', (req, res) => {
32300
32768
  // Exposes CDP endpoint so Claude Code's Playwright MCP can connect.
32301
32769
 
32302
32770
  const browserSessions = new Map(); // sessionId → { browser, context, page, clients, cdpSession, screencastActive, ... }
32771
+ // The listener is lazy: the owner's pairing action opens its loopback port, and so does a pairing a previous process
32772
+ // stored (restore() below), so the extension reconnects by itself after a restart.
32773
+ const extensionUploadRoot = resolve(DATA_HOME, 'data/extension-uploads');
32774
+ // SynaBun's own ports, which no agent reaches through the owner's browser (docs/browser-extension-bridge.md): this
32775
+ // server and its launch beacon unless the owner lets the automation browser act as owner (Settings → Browser), and
32776
+ // always the browser-control ports (the CDP port, MoreLogin's local API) and SynaBun's live OpenCode serves.
32777
+ function extensionBlockedPorts() {
32778
+ const ports = new Set([CDP_PORT, ...moreLogin.MORELOGIN_FIXED_API_PORTS]);
32779
+ try { for (const p of liveOpencodeServePorts()) ports.add(Number(p)); } catch {}
32780
+ if (!_automationBrowserOwnerAccess.enabled()) { ports.add(Number(PORT) || 3344); ports.add(workerBeaconPort()); }
32781
+ return [...ports].filter(p => Number.isInteger(p) && p > 0 && p <= 65535);
32782
+ }
32783
+ // This computer's names and interface addresses: one of SynaBun's ports on any of them is SynaBun.
32784
+ function extensionSelfHosts() {
32785
+ const hosts = new Set(machineNames.names().flatMap(name => [name, `${name}.local`]));
32786
+ try { for (const list of Object.values(os.networkInterfaces())) for (const entry of list || []) if (entry?.address) hosts.add(entry.address.split('%')[0]); } catch {}
32787
+ return [...hosts];
32788
+ }
32789
+ const extensionBridge = createExtensionBridge({
32790
+ forbiddenOrigins: publicWebOrigins,
32791
+ blockedPorts: extensionBlockedPorts,
32792
+ selfHosts: extensionSelfHosts,
32793
+ // The pairing and the owner's mode, across restarts: outside data/ (no backup carries the credential), 0600.
32794
+ store: createBridgeStore(resolve(DATA_HOME, 'browser-extension', 'bridge.json')),
32795
+ log: record => console.log('[extension-bridge]', JSON.stringify(record)),
32796
+ onInventory: state => extensionAdapter.sync(state),
32797
+ });
32798
+ const extensionAdapter = createExtensionAdapter({
32799
+ bridge: extensionBridge, sessions: browserSessions, uploadRoot: extensionUploadRoot, dataHome: DATA_HOME,
32800
+ caller: browserCaller, ownerPage: browserOwnerPageOnly,
32801
+ selected: req => loadBrowserConfig().connectMode === 'extension' && !runMoreLoginPin(browserCaller(req).id),
32802
+ });
32803
+ // The extension folder the owner loads (DATA_HOME/browser-extension/unpacked): refreshed at start when the bundled
32804
+ // extension changed and is not older (lib/browser-extension-folder.js). The browser then needs the extension's Reload,
32805
+ // which Settings and the setup page say (`reloadNeeded`). Never fatal: a folder that cannot be written is prepared
32806
+ // again by the one-button setup, which says so.
32807
+ const prepareOwnerExtensionFolder = () => prepareExtensionFolder({ source: EXTENSION_FOLDER, home: DATA_HOME, appPort: Number(PORT) || 3344 });
32808
+ try { const prepared = prepareOwnerExtensionFolder(); if (prepared.changed) console.log(`[extension-bridge] extension folder ${prepared.previousVersion ? `refreshed ${prepared.previousVersion} → ${prepared.version}` : `prepared (${prepared.version})`}; reload the extension in the browser`); }
32809
+ catch (error) { console.warn(`[extension-bridge] extension folder not prepared (${error?.code || 'error'})`); }
32810
+ // The one-button setup (Settings → Browser → "Connect your browser"; docs/browser-extension-bridge.md → One-button
32811
+ // setup). Programs are started with execFile/spawn and argument arrays, never a shell; reads time out.
32812
+ const extensionSetup = createExtensionSetup({
32813
+ bridge: extensionBridge,
32814
+ detect: () => detectBrowsers({
32815
+ platform: process.platform, home: os.homedir(),
32816
+ run: (cmd, args) => new Promise((resolveRun, rejectRun) => execFile(cmd, args, { timeout: 5000, windowsHide: true, maxBuffer: 1024 * 1024, encoding: 'utf8' }, (error, stdout) => error ? rejectRun(error) : resolveRun({ stdout }))),
32817
+ exists: path => { try { return existsSync(path); } catch { return false; } },
32818
+ list: dir => { try { return readdirSync(dir); } catch { return []; } },
32819
+ }),
32820
+ prepare: () => prepareOwnerExtensionFolder(),
32821
+ exec: (cmd, args) => new Promise((resolveExec, rejectExec) => {
32822
+ const child = spawn(cmd, args, { detached: true, stdio: 'ignore', windowsHide: true, shell: false });
32823
+ child.once('error', rejectExec); child.once('spawn', () => { child.unref(); resolveExec(); });
32824
+ }),
32825
+ appOrigin: () => `http://127.0.0.1:${Number(PORT) || 3344}`,
32826
+ folderVersion: () => extensionFolderState(DATA_HOME).version,
32827
+ });
32828
+ {
32829
+ const restored = extensionBridge.restore();
32830
+ restored.listening?.then(
32831
+ port => console.log(`[extension-bridge] pairing restored; listening on 127.0.0.1:${port}`),
32832
+ error => console.warn(`[extension-bridge] pairing restored, but the bridge port could not open (${error?.code || 'error'})`));
32833
+ }
32303
32834
  const BROWSER_GRACE_PERIOD_MS = 5 * 60 * 1000; // 5 min before orphaned browser is killed
32304
32835
 
32305
32836
  /** Check if a browser session is actively used by a running automation loop or agent.
@@ -32331,7 +32862,7 @@ setInterval(() => {
32331
32862
  for (const [id, session] of browserSessions) {
32332
32863
  // Never reap an attach (CDP) session — it backs a live Chrome window the user is
32333
32864
  // using; reaping would disconnect it and a later call would spawn a 2nd debug Chrome.
32334
- if (session._profileMode === 'cdp' || session._profileMode === 'morelogin') { session._idleSince = null; continue; }
32865
+ if (['cdp', 'morelogin', 'extension'].includes(session._profileMode)) { session._idleSince = null; continue; }
32335
32866
  const idle = (session.clients?.size || 0) === 0
32336
32867
  && sessionOwnerCount(session) === 0
32337
32868
  && !isSessionUsedByActiveLoop(id);
@@ -32395,8 +32926,11 @@ const RUN_MORELOGIN_SESSION_PINS_MAX = 200;
32395
32926
  * `ownerKey` works in MoreLogin profile `envId` from now on, or (no envId) in the default browser by its own choice.
32396
32927
  * Only for code that decided it: a launch, POST /api/morelogin/use after its checks, a dispatch. `by`: 'owner' when
32397
32928
  * the owner's page chose the profile, else 'agent'. Throws 503 PROFILE_PINS_FULL in place of evicting another pin.
32929
+ * `locked` (the default): the run's setup chose the profile (a schedule, a group, a timer, a launch, an agent's
32930
+ * spawn, a dispatch's morelogin_profile), and the run cannot move to another one (POST /api/morelogin/use answers 409
32931
+ * PROFILE_PINNED, 2026-11-15). Only a session's own choice (`use`) is not locked: such a session may choose again.
32398
32932
  */
32399
- function pinRunMoreLoginProfile(ownerKey, envId, name = null, by = 'agent') {
32933
+ function pinRunMoreLoginProfile(ownerKey, envId, name = null, by = 'agent', { locked = true } = {}) {
32400
32934
  if (!ownerKey) return;
32401
32935
  _runMoreLoginNoPin.delete(ownerKey);
32402
32936
  if (!_runMoreLoginPins.has(ownerKey)) {
@@ -32406,7 +32940,7 @@ function pinRunMoreLoginProfile(ownerKey, envId, name = null, by = 'agent') {
32406
32940
  throw Object.assign(new Error('Too many sessions hold a browser profile of their own right now; nothing was changed. Try again when some have ended.'), { status: 503, code: 'PROFILE_PINS_FULL' });
32407
32941
  }
32408
32942
  }
32409
- _runMoreLoginPins.set(ownerKey, envId ? { envId: String(envId), name: name ? String(name) : null, by: by === 'owner' ? 'owner' : 'agent' } : null);
32943
+ _runMoreLoginPins.set(ownerKey, envId ? { envId: String(envId), name: name ? String(name) : null, by: by === 'owner' ? 'owner' : 'agent', locked: locked !== false } : null);
32410
32944
  }
32411
32945
 
32412
32946
  /** `ownerKey` ended, or its launch failed: its pin and its saved choice are forgotten (nothing outlives its owner). */
@@ -32415,6 +32949,93 @@ function forgetRunMoreLoginProfile(ownerKey) {
32415
32949
  _runMoreLoginPins.delete(ownerKey);
32416
32950
  _runMoreLoginNoPin.delete(ownerKey);
32417
32951
  _profileChoiceStore.delete(ownerKey);
32952
+ // A failure of its profile bars nothing once it has ended (lib/morelogin-profile-failures.js).
32953
+ _runProfileFailures.clear(ownerKey);
32954
+ }
32955
+
32956
+ // ── A run's own profile failed in this run: it does not move to another one (lib/morelogin-profile-failures.js) ──
32957
+ // Noted where a run's start or connection fails (acquireSharedBrowserTab, an automation's POST /api/browser/sessions,
32958
+ // its own POST /api/morelogin/start of its profile); asked by POST /api/morelogin/use and an automation's POST
32959
+ // /api/morelogin/start of another profile (409 PROFILE_FAILED_NO_SWITCH). Lifted by a connection of the run to that
32960
+ // profile again (noteRunProfileConnected), by the owner moving the run (its effective profile changed: `lifted`), or by
32961
+ // the run's end (forgetRunMoreLoginProfile).
32962
+ /**
32963
+ * The profile `ownerKey` works in now ({ envId, name, pinned }): its pin, else the MoreLogin (or local) profile that is
32964
+ * the default AI browser (Settings → Connected tools → MoreLogin); null when that default is no profile (Chrome, the
32965
+ * mirror, the extension).
32966
+ */
32967
+ function runEffectiveProfile(ownerKey, cfg = loadBrowserConfig()) {
32968
+ const pin = runMoreLoginPin(ownerKey);
32969
+ if (pin?.envId) return { envId: String(pin.envId), name: pin.name || null, pinned: true };
32970
+ const defaultEnv = cfg?.connectMode === 'morelogin' ? moreLoginDefaultEnvId(cfg) : null;
32971
+ return defaultEnv ? { envId: String(defaultEnv), name: _moreLoginEnvNames.get(String(defaultEnv)) || null, pinned: false } : null;
32972
+ }
32973
+
32974
+ /**
32975
+ * `ownerKey`'s own profile (`profile`: { envId, name }) failed to start or connect in this run (`failure`: what the
32976
+ * start answered, { code, error } or an Error). From now on the run may not move to another profile. Never throws.
32977
+ */
32978
+ function noteRunProfileFailure(ownerKey, profile, failure) {
32979
+ if (!ownerKey || !profile?.envId) return null;
32980
+ try {
32981
+ const entry = _runProfileFailures.note(ownerKey, {
32982
+ envId: String(profile.envId), name: profile.name || _moreLoginEnvNames.get(String(profile.envId)) || null,
32983
+ code: failure?.code || null, reason: failure?.error || failure?.message || null,
32984
+ });
32985
+ if (entry) console.warn(`[morelogin] ${logOwnerId(ownerKey)}: its own profile ${describeProfile(entry.envId, entry.name)} failed to start or connect (${entry.code || 'no code'}); it may not move to another profile until that one connects again for it, the owner moves it, or it ends`);
32986
+ return entry;
32987
+ } catch { return null; }
32988
+ }
32989
+
32990
+ /** `ownerKey` is connected to profile `envId`: a failure noted for that profile in this run is over. Never throws. */
32991
+ function noteRunProfileConnected(ownerKey, envId) {
32992
+ if (!ownerKey || !envId) return null;
32993
+ try {
32994
+ const dropped = _runProfileFailures.clear(ownerKey, { envId: String(envId) });
32995
+ if (dropped) console.log(`[morelogin] ${logOwnerId(ownerKey)}: ${describeProfile(dropped.envId, dropped.name)} connects again in this run: it may switch profiles again`);
32996
+ return dropped;
32997
+ } catch { return null; }
32998
+ }
32999
+
33000
+ /**
33001
+ * Why `ownerKey` may not switch now, or null. `target`: `{ toDefault: true }` (back to the default AI browser,
33002
+ * Settings → Connected tools → MoreLogin), or the profile it names ({ envId, name, profile }, resolved or as a request said it). `action`: 'use' (a
33003
+ * move, POST /api/morelogin/use) or 'start' (an automation's start of a profile). → an Error with code
33004
+ * PROFILE_FAILED_NO_SWITCH, status 409 (refuseProfileSwitchAfterFailure answers it). A failure of a profile the run no
33005
+ * longer works in (the owner moved it) is dropped here; naming the failed profile itself is no move.
33006
+ */
33007
+ function runProfileSwitchRefusal(ownerKey, target = {}, { action = 'use', cfg = loadBrowserConfig() } = {}) {
33008
+ let failure = null;
33009
+ try { failure = _runProfileFailures.get(ownerKey); } catch { failure = null; }
33010
+ if (!failure) return null;
33011
+ const defaultEnv = cfg?.connectMode === 'morelogin' ? moreLoginDefaultEnvId(cfg) : null;
33012
+ // A resolved profile is compared by its id alone; a request's words by id or name (namesFailedProfile).
33013
+ const sameTarget = target?.toDefault ? String(defaultEnv || '') === failure.envId
33014
+ : target?.resolved ? String(target.envId || '') === failure.envId : namesFailedProfile(target, failure);
33015
+ const decision = profileSwitchDecision({ failure, current: runEffectiveProfile(ownerKey, cfg)?.envId || null, sameTarget });
33016
+ if (decision === 'lifted') {
33017
+ _runProfileFailures.clear(ownerKey, { envId: failure.envId });
33018
+ console.log(`[morelogin] ${logOwnerId(ownerKey)} no longer works in ${describeProfile(failure.envId, failure.name)} (the owner moved it): its failure there no longer bars a switch`);
33019
+ return null;
33020
+ }
33021
+ if (decision !== 'barred') return null;
33022
+ const named = target?.toDefault
33023
+ ? (defaultEnv ? `the default browser, ${describeProfile(String(defaultEnv), _moreLoginEnvNames.get(String(defaultEnv)) || null)}` : 'the default browser')
33024
+ : target?.envId ? describeProfile(String(target.envId), target.name || _moreLoginEnvNames.get(String(target.envId)) || null)
33025
+ : (target?.name || target?.profile) ? `the profile "${String(target.name || target.profile).slice(0, 64)}"` : 'another profile';
33026
+ const err = profileSwitchBarError(failure, { label: describeProfile(failure.envId, failure.name), targetLabel: named, action });
33027
+ console.warn(`[morelogin] ${logOwnerId(ownerKey)}: its ${action === 'start' ? 'start of' : 'move to'} ${named} was refused: its own profile ${describeProfile(failure.envId, failure.name)} failed in this run (${failure.code || 'no code'})`);
33028
+ loopLog(ownerKey, 'browser:profile', `refused: its own profile failed in this run, so it does not ${action === 'start' ? 'start' : 'move to'} ${named}`, { failed: failure.envId, failedAt: err.failedAt || null, code: failure.code || null, asked: target?.toDefault ? 'default' : (target?.envId || target?.name || target?.profile || null) });
33029
+ return err;
33030
+ }
33031
+
33032
+ /** 409 PROFILE_FAILED_NO_SWITCH: the answer of a refusal from runProfileSwitchRefusal. Nothing was changed or started. */
33033
+ function refuseProfileSwitchAfterFailure(res, err) {
33034
+ return res.status(err.status || 409).json({
33035
+ ok: false, code: err.code, envId: err.envId, needsUser: true,
33036
+ ...(err.failedAt ? { failedAt: err.failedAt } : {}), ...(err.failedCode ? { failedCode: err.failedCode } : {}),
33037
+ error: err.message,
33038
+ });
32418
33039
  }
32419
33040
 
32420
33041
  /**
@@ -32433,12 +33054,14 @@ function runMoreLoginPin(ownerKey) {
32433
33054
  const chosen = _profileChoiceStore.get(ownerKey);
32434
33055
  if (chosen !== undefined) {
32435
33056
  decided = true;
32436
- pin = chosen.envId ? { envId: String(chosen.envId), name: chosen.name || null, by: 'agent' } : null;
33057
+ // The session's own choice (`use`): it may choose again.
33058
+ pin = chosen.envId ? { envId: String(chosen.envId), name: chosen.name || null, by: 'agent', locked: false } : null;
32437
33059
  } else {
32438
33060
  const loopFile = findLoopFileForTerminal(ownerKey);
32439
33061
  if (loopFile) {
32440
33062
  const data = JSON.parse(readFileSync(resolve(LOOP_DIR, loopFile), 'utf-8'));
32441
- if (data.moreloginEnvId) pin = { envId: String(data.moreloginEnvId), name: data.moreloginEnvName ? String(data.moreloginEnvName) : null, by: data.moreloginEnvBy === 'owner' ? 'owner' : 'agent' };
33063
+ // The run was launched with this profile (its schedule, group, timer or launch): it stays there.
33064
+ if (data.moreloginEnvId) pin = { envId: String(data.moreloginEnvId), name: data.moreloginEnvName ? String(data.moreloginEnvName) : null, by: data.moreloginEnvBy === 'owner' ? 'owner' : 'agent', locked: true };
32442
33065
  }
32443
33066
  }
32444
33067
  } catch { /* no pin */ }
@@ -32452,6 +33075,34 @@ function runMoreLoginPin(ownerKey) {
32452
33075
  return pin;
32453
33076
  }
32454
33077
 
33078
+ // MoreLogin profile names last read from its list (GET /api/browser/morelogin-envs, /api/morelogin/profiles): what the
33079
+ // start cooldowns are called by. id → name, bounded.
33080
+ const _moreLoginEnvNames = new Map();
33081
+ function rememberMoreLoginEnvNames(envs) {
33082
+ for (const env of envs || []) {
33083
+ if (env?.id == null || !env.name || env.kind === 'local') continue;
33084
+ _moreLoginEnvNames.delete(String(env.id));
33085
+ _moreLoginEnvNames.set(String(env.id), String(env.name));
33086
+ }
33087
+ while (_moreLoginEnvNames.size > 500) _moreLoginEnvNames.delete(_moreLoginEnvNames.keys().next().value);
33088
+ }
33089
+ /**
33090
+ * The profiles MoreLogin refused to start for its plan's daily limit, held until its day resets
33091
+ * (lib/morelogin-start-cooldown.js): [{ envId, name, since, resetAt, resetLocal, apiCode }]. Never throws.
33092
+ */
33093
+ function moreLoginStartCooldowns(envs = null) {
33094
+ let list = [];
33095
+ try { list = moreLogin.listStartCooldowns(); } catch { return []; }
33096
+ if (!list.length) return [];
33097
+ if (envs) rememberMoreLoginEnvNames(envs);
33098
+ const names = new Map(_moreLoginEnvNames);
33099
+ try { for (const p of moreLoginAgentProfiles()) if (p?.envId && p.name && !names.has(String(p.envId))) names.set(String(p.envId), p.name); } catch { /* unreadable config: ids only */ }
33100
+ return list.map((c) => ({
33101
+ envId: c.envId, name: names.get(c.envId) || null,
33102
+ since: c.since ? new Date(c.since).toISOString() : null, resetAt: c.resetAt, resetLocal: c.resetLocal, apiCode: c.apiCode ?? null,
33103
+ }));
33104
+ }
33105
+
32455
33106
  function describeMoreLoginPin(pin) {
32456
33107
  if (!pin) return 'the default browser';
32457
33108
  // `MoreLogin profile "X" (id)`, or `local profile "X" (id)` for one of SynaBun's own (lib/local-profiles.js).
@@ -32503,6 +33154,7 @@ function sessionServesRun(session, cfg, ownerKey) {
32503
33154
  // A pin that may not be used (an agent's, its profile off the owner's list) serves in no session at all: not its
32504
33155
  // profile's, and never the default browser's.
32505
33156
  if (pin) return !pinUseRefusal(pin, cfg) && sessionServesMoreLoginEnv(session, pin.envId);
33157
+ if (cfg.connectMode === 'extension' || session?._profileMode === 'extension') return cfg.connectMode === 'extension' && session?._profileMode === 'extension';
32506
33158
  return cfg.connectMode !== 'morelogin' || sessionServesMoreLoginDefault(session, cfg);
32507
33159
  }
32508
33160
 
@@ -32528,6 +33180,10 @@ async function findReusableBrowserSession(opts = {}) {
32528
33180
  const normalize = (p) => (p || '').replace(/[\\/]+$/, '').replace(/\\/g, '/').toLowerCase();
32529
33181
  const selectedNorm = normalize(selectedPath);
32530
33182
  for (const [id, session] of browserSessions) {
33183
+ if (session._profileMode === 'extension' || cfg.connectMode === 'extension' && !moreloginEnvId) {
33184
+ if (session._profileMode === 'extension' && cfg.connectMode === 'extension' && extensionBridge.status().connected && !moreloginEnvId) return { id, session };
33185
+ continue;
33186
+ }
32531
33187
  if (excludeAgentOwned && session._agentOwnedSet?.size > 0) continue;
32532
33188
  if (excludeLoopOwned && session._loopOwned?.size > 0) continue;
32533
33189
  // Belt-and-suspenders: also check agent registry in case the ownership set
@@ -32661,10 +33317,15 @@ function loopBrowserLockKey(ownerKey, requestedBrowserSessionId, cfg) {
32661
33317
  *
32662
33318
  * Returns { browserSessionId, browserTabId } on success, or { error } on failure.
32663
33319
  */
32664
- async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, ownerKey, ownerType = 'loop', logTag = 'launch:browser' }) {
33320
+ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, ownerKey, ownerType = 'loop', logTag = 'launch:browser', takeOverTab = null, scheduledFiring = false }) {
33321
+ if (loadBrowserConfig().connectMode === 'extension' && !runMoreLoginPin(ownerKey)) {
33322
+ // takeOverTab: one of the owner's open tabs in the everyday browser (full control), named by browser_session create.
33323
+ try { return await extensionAdapter.acquire(ownerKey, ownerType, { adopt: takeOverTab || undefined }); }
33324
+ catch (error) { return extensionSafeError(error); }
33325
+ }
32665
33326
  const lockKey = loopBrowserLockKey(ownerKey, requestedBrowserSessionId, loadBrowserConfig());
32666
33327
  const acquired = await withLoopBrowserLock(lockKey, async () => {
32667
- // The browser this owner gets changed while it waited (Settings → Browser, a requested session that went away):
33328
+ // The browser this owner gets changed while it waited (the owner's settings, a requested session that went away):
32668
33329
  // it queues again for the right one, outside this turn.
32669
33330
  if (loopBrowserLockKey(ownerKey, requestedBrowserSessionId, loadBrowserConfig()) !== lockKey) return { requeue: true };
32670
33331
  let browserSessionId = null;
@@ -32733,9 +33394,14 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
32733
33394
  let createError = null;
32734
33395
  if (!browserSessionId) {
32735
33396
  try {
33397
+ // The start guard: a profile closed outside SynaBun is not started again by this acquisition (an attach to the
33398
+ // profile running again is always allowed). Only a new scheduled firing's launch may start it
33399
+ // (`scheduledFiring`, the schedule:browser acquisition; never a recovery or a create of a run under way).
33400
+ const moreloginStartGuard = moreLoginStartGuardFor(ownerKey, pin, { scheduled: scheduledFiring === true });
33401
+ const moreloginAfterOutsideClose = scheduledFiring === true ? 'schedule' : null;
32736
33402
  const result = await createBrowserSession(pin
32737
- ? { url: 'about:blank', connectMode: 'morelogin', moreloginEnvId: pin.envId, _mlPinned: true }
32738
- : { url: 'about:blank' });
33403
+ ? { url: 'about:blank', connectMode: 'morelogin', moreloginEnvId: pin.envId, _mlPinned: true, moreloginStartGuard, moreloginAfterOutsideClose }
33404
+ : { url: 'about:blank', moreloginStartGuard, moreloginAfterOutsideClose });
32739
33405
  browserSessionId = result.sessionId;
32740
33406
  loopLog(ownerKey, logTag, 'strategy 2: created shared browser session', {
32741
33407
  browserSessionId, profileMode: result.profileMode, profileSource: result.profileSource,
@@ -32752,6 +33418,19 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
32752
33418
  }
32753
33419
 
32754
33420
  if (!browserSessionId) {
33421
+ // The run's own profile (its pin, else the MoreLogin default) failed to start or connect in this run: from now on
33422
+ // it may not move to another profile (POST /api/morelogin/use answers 409 PROFILE_FAILED_NO_SWITCH) until that
33423
+ // profile connects again for it (below), the owner moves it, or it ends (lib/morelogin-profile-failures.js).
33424
+ if (createError) {
33425
+ const own = pin || (moreLoginDefault && moreLoginDefaultEnvId(policyCfg) ? { envId: String(moreLoginDefaultEnvId(policyCfg)), name: null } : null);
33426
+ noteRunProfileFailure(ownerKey, own, createError);
33427
+ }
33428
+ // The profile was closed outside SynaBun: the sentence says it all (which profile, when, that SynaBun does not
33429
+ // reopen it, how to go on); no "could not start" around it.
33430
+ if (createError?.code === 'MORELOGIN_CLOSED_OUTSIDE') {
33431
+ loopLog(ownerKey, logTag, 'BLOCKED: the MoreLogin profile was closed outside SynaBun; SynaBun does not reopen it', { closedAt: createError.closedAt || null, holdUntil: createError.holdUntil || null });
33432
+ return { error: createError.error, code: createError.code, needsUser: true, blocked: true, ...(createError.closedAt ? { closedAt: createError.closedAt } : {}), ...(createError.holdUntil ? { holdUntil: createError.holdUntil } : {}) };
33433
+ }
32755
33434
  // Carry the real reason (e.g. "MoreLogin connect failed: … unreachable") into the
32756
33435
  // run's log, lastRunResult and the schedule:failed toast.
32757
33436
  return {
@@ -32760,11 +33439,17 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
32760
33439
  ? `Could not start ${describeMoreLoginPin(pin)} for this run${createError ? `: ${createError.error}` : '.'} The run was not started in another profile or browser: ${
32761
33440
  createError?.code === 'MORELOGIN_NOT_CHROMIUM' || createError?.code === 'MORELOGIN_NOT_DEVTOOLS'
32762
33441
  ? 'pick a Chrome-type profile where this run is set up.'
33442
+ : createError?.code === 'MORELOGIN_START_REFUSED'
33443
+ ? `this needs the user, not a retry: ${createError.planLimit ? 'wait for MoreLogin\'s daily reset, upgrade the MoreLogin plan, or keep the profile open so runs need no new start' : 'fix what MoreLogin names in the MoreLogin app'}.`
33444
+ : createError?.code === 'MORELOGIN_PROFILE_WINDOWLESS'
33445
+ ? 'this needs the user, not a retry: open the profile\'s window again in MoreLogin (or close it fully there and start it again).'
32763
33446
  : 'check that MoreLogin is open and that the profile still exists, or pick another profile where this run is set up.'}`
32764
33447
  : createError
32765
33448
  ? `Could not start the shared browser session: ${createError.error}`
32766
33449
  : 'Could not start the shared browser session. Open Browser Settings and verify the selected profile can launch.',
32767
33450
  ...(createError?.code ? { code: createError.code, offenders: createError.offenders } : {}),
33451
+ ...(createError?.needsUser ? { needsUser: true } : {}),
33452
+ ...(createError?.resetAt ? { resetAt: createError.resetAt } : {}),
32768
33453
  };
32769
33454
  }
32770
33455
 
@@ -32848,17 +33533,56 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
32848
33533
  return { requeue: true };
32849
33534
  }
32850
33535
 
33536
+ // Connected to its profile: a failure of that profile noted earlier in this run is over (it may switch again).
33537
+ if (claimedSession._mlEnvId) noteRunProfileConnected(ownerKey, claimedSession._mlEnvId);
32851
33538
  return { browserSessionId, browserTabId };
32852
33539
  });
32853
- return acquired?.requeue ? acquireSharedBrowserTab({ requestedBrowserSessionId, ownerKey, ownerType, logTag }) : acquired;
33540
+ return acquired?.requeue ? acquireSharedBrowserTab({ requestedBrowserSessionId, ownerKey, ownerType, logTag, scheduledFiring }) : acquired;
33541
+ }
33542
+
33543
+ /**
33544
+ * The start guard of `ownerKey`'s acquisition (createBrowserSession `moreloginStartGuard` → lib/morelogin.js
33545
+ * startProfile `refuseStart`, asked only when MoreLogin says the profile is not running): a profile closed outside
33546
+ * SynaBun (lib/morelogin-outside-close.js) is not started again, for this run or any other, named the way the run
33547
+ * knows it. `scheduled`: the launch acquisition of a new scheduled firing, which may start it (startProfile is told
33548
+ * the same through `allowAfterOutsideClose`). → (envId) => Error | null.
33549
+ */
33550
+ function moreLoginStartGuardFor(ownerKey, pin = null, { scheduled = false } = {}) {
33551
+ return (envId) => {
33552
+ if (scheduled) return null;
33553
+ const held = moreLogin.outsideCloseFor(String(envId));
33554
+ if (!held) return null;
33555
+ const name = (pin && String(pin.envId) === String(envId) ? pin.name : null) || _moreLoginEnvNames.get(String(envId)) || held.name || null;
33556
+ return moreLogin.outsideCloseError(String(envId), held, { label: describeProfile(String(envId), name) });
33557
+ };
33558
+ }
33559
+
33560
+ /**
33561
+ * The profiles closed outside SynaBun that SynaBun does not reopen (lib/morelogin-outside-close.js), for the status
33562
+ * answers and Settings: [{ envId, name, closedAt, closedLocal, holdUntil, holdUntilLocal, runs }] (the orphaned runs
33563
+ * counted, never listed). `envs`: a list just read, for names. Never throws.
33564
+ */
33565
+ function moreLoginClosedOutside(envs = null) {
33566
+ try {
33567
+ const listed = new Map((envs || []).filter((e) => e?.id != null && e.name).map((e) => [String(e.id), String(e.name)]));
33568
+ return moreLogin.listOutsideCloses().map((c) => ({
33569
+ envId: c.envId, name: listed.get(c.envId) || _moreLoginEnvNames.get(c.envId) || c.name || null,
33570
+ closedAt: c.closedAt, closedLocal: c.closedLocal, holdUntil: c.holdUntil, holdUntilLocal: c.holdUntilLocal, runs: c.owners.length,
33571
+ }));
33572
+ } catch { return []; }
33573
+ }
33574
+
33575
+ /** A profile as a refusal names it (lib/morelogin.js startProfile `profileLabel`): its name as MoreLogin last listed it. */
33576
+ function moreLoginProfileLabel(envId, name = null) {
33577
+ return describeProfile(String(envId), _moreLoginEnvNames.get(String(envId)) || name || null);
32854
33578
  }
32855
33579
 
32856
33580
  /**
32857
33581
  * Backward-compatible loop wrapper around acquireSharedBrowserTab. Existing callers
32858
33582
  * pass { terminalSessionId } and expect loop-owned semantics.
32859
33583
  */
32860
- async function acquireLoopBrowserAndTab({ requestedBrowserSessionId = null, terminalSessionId, logTag = 'launch:browser' }) {
32861
- return acquireSharedBrowserTab({ requestedBrowserSessionId, ownerKey: terminalSessionId, ownerType: 'loop', logTag });
33584
+ async function acquireLoopBrowserAndTab({ requestedBrowserSessionId = null, terminalSessionId, logTag = 'launch:browser', takeOverTab = null, scheduledFiring = false }) {
33585
+ return acquireSharedBrowserTab({ requestedBrowserSessionId, ownerKey: terminalSessionId, ownerType: 'loop', logTag, takeOverTab, scheduledFiring });
32862
33586
  }
32863
33587
 
32864
33588
  /**
@@ -32869,6 +33593,7 @@ async function acquireLoopBrowserAndTab({ requestedBrowserSessionId = null, term
32869
33593
  */
32870
33594
  async function releaseSharedBrowserTab(sessionId, ownerKey) {
32871
33595
  const session = browserSessions.get(sessionId);
33596
+ if (session?._profileMode === 'extension') return extensionAdapter.release(sessionId, ownerKey);
32872
33597
  if (!session) return;
32873
33598
  session._interactiveOwned?.delete(ownerKey);
32874
33599
  session._loopOwned?.delete(ownerKey);
@@ -32923,7 +33648,7 @@ function startedTabAlive(sessionId, tabId, ownerKey) {
32923
33648
  const session = sessionId ? browserSessions.get(sessionId) : null;
32924
33649
  if (!session) return false;
32925
33650
  if (tabId && session.tabs && !session.tabs.has(tabId)) return false;
32926
- if (ownerKey && tabId && session._tabOwners?.get(ownerKey) !== tabId) return false;
33651
+ if (ownerKey && tabId && !(session._profileMode === 'extension' ? extensionAdapter.ownsTab(session, ownerKey, tabId) : session._tabOwners?.get(ownerKey) === tabId)) return false;
32927
33652
  return true;
32928
33653
  }
32929
33654
 
@@ -34218,6 +34943,22 @@ function browserStartFailure(err) {
34218
34943
  const out = { error: err?.message || String(err) };
34219
34944
  if (err?.code === 'NATIVE_SERVE_UNVERIFIED') { out.code = err.code; out.offenders = narrowOffenders(err.offenders); }
34220
34945
  if (err?.code === 'MORELOGIN_NOT_CHROMIUM' || err?.code === 'MORELOGIN_NOT_DEVTOOLS') out.code = err.code;
34946
+ // MoreLogin refused the start (a plan limit, …): the user has to act, a retry or another run hits the same answer.
34947
+ if (err?.code === 'MORELOGIN_START_REFUSED') {
34948
+ out.code = err.code;
34949
+ out.needsUser = true;
34950
+ if (err.apiCode != null) out.apiCode = err.apiCode;
34951
+ if (err.planLimit) out.planLimit = true;
34952
+ if (err.resetAt) out.resetAt = err.resetAt;
34953
+ }
34954
+ // The run's profile was closed outside SynaBun and is not started again for it (lib/morelogin-outside-close.js), or
34955
+ // MoreLogin lists it running with no window: the user acts (starts or reopens it), a retry gets the same answer.
34956
+ if (err?.code === 'MORELOGIN_CLOSED_OUTSIDE' || err?.code === 'MORELOGIN_PROFILE_WINDOWLESS') {
34957
+ out.code = err.code;
34958
+ out.needsUser = true;
34959
+ if (err.closedAt) out.closedAt = err.closedAt;
34960
+ if (err.holdUntil) out.holdUntil = err.holdUntil;
34961
+ }
34221
34962
  return out;
34222
34963
  }
34223
34964
 
@@ -34326,6 +35067,10 @@ function moreLoginBlockError(session, requestedUrl, landedUrl) {
34326
35067
  async function createBrowserSession(options = {}) {
34327
35068
  const sessionId = randomBytes(16).toString('hex');
34328
35069
  const savedCfg = loadBrowserConfig();
35070
+ if (savedCfg.connectMode === 'extension' && options.connectMode !== 'morelogin') {
35071
+ const acquired = await extensionAdapter.acquire(options._extensionOwner || 'owner-page');
35072
+ return { sessionId: acquired.browserSessionId, tabId: acquired.browserTabId, profileMode: 'extension', wsEndpoint: null };
35073
+ }
34329
35074
  // Settings that exist but cannot be read are not "no settings": never fall back to Chrome.
34330
35075
  const unreadableCfg = browserConfigUnreadable(savedCfg);
34331
35076
  if (unreadableCfg) throw new Error(`browser-config.json is unreadable; fix it in Settings → Browser (${unreadableCfg})`);
@@ -34588,7 +35333,7 @@ async function createBrowserSession(options = {}) {
34588
35333
  let _launchProfileDirectory = _profileDirectory || (userDataDir ? 'Default' : null);
34589
35334
 
34590
35335
  // ── MoreLogin connect mode ──
34591
- // When configured (Settings → Browser → MoreLogin, or an explicit per-session
35336
+ // When configured (Settings → Connected tools → MoreLogin → Default AI browser, or an explicit per-session
34592
35337
  // moreloginEnvId), launch/attach a MoreLogin anti-detect profile and drive it
34593
35338
  // over CDP. MoreLogin's /api/env/start returns a debugPort — the exact same CDP
34594
35339
  // path as "attach" mode, so we reuse connectOverCDP + probeCdpEndpoint here.
@@ -34642,27 +35387,48 @@ async function createBrowserSession(options = {}) {
34642
35387
  // requireCdp: a Firefox-type profile has no DevTools endpoint and is refused, before it is started when
34643
35388
  // MoreLogin says what it is up front.
34644
35389
  nativePreflightProfiles.add(String(envId));
34645
- const { debugPort } = await moreLogin.startProfile(envId, { ...mlOpts, requireCdp: true });
34646
- // Wait for MoreLogin's Chromium DevTools endpoint to come up.
35390
+ // `moreloginStartGuard` (acquireSharedBrowserTab): the run's own reason not to spend a launch. Asked only when
35391
+ // MoreLogin says the profile is not running. A profile closed outside SynaBun is refused by startProfile for
35392
+ // everybody but `moreloginAfterOutsideClose` ('owner': the owner's page; 'schedule': a new scheduled firing).
35393
+ const startOpts = { ...mlOpts, requireCdp: true, ...(typeof options.moreloginStartGuard === 'function' ? { refuseStart: options.moreloginStartGuard } : {}),
35394
+ ...(options.moreloginAfterOutsideClose ? { allowAfterOutsideClose: options.moreloginAfterOutsideClose } : {}), profileLabel: moreLoginProfileLabel };
35395
+ let { debugPort } = await moreLogin.startProfile(envId, startOpts);
34647
35396
  let endpoint = null;
34648
- for (let i = 0; i < 40; i++) {
34649
- const probed = await probeCdpEndpoint(debugPort);
34650
- if (probed.ok) { endpoint = probed.httpEndpoint; break; }
34651
- await new Promise(r => setTimeout(r, 250));
34652
- }
34653
- if (!endpoint) {
34654
- // Ten seconds without a DevTools answer. A port that answers HTTP as something else will never become
34655
- // one: say what it is, in place of Playwright's "Unexpected status 404 … try connecting via ws://". A
34656
- // port nothing listens on yet still gets the connect attempt below.
34657
- const seen = await moreLogin.describeDebugEndpoint(debugPort);
34658
- if (seen.kind === 'not-devtools') throw moreLogin.notDevToolsError(envId, debugPort, seen);
34659
- endpoint = `http://127.0.0.1:${debugPort}`;
34660
- }
34661
-
34662
- const { browser: cdpBrowser, context: cdpContext, page: cdpPage } = await moreLogin.attachProfileBrowser(
34663
- chromium, endpoint,
34664
- (cdpBrowser, cdpContext) => newSessionPage({ browser: cdpBrowser, context: cdpContext, _profileMode: 'morelogin' }),
34665
- ); // fresh tab in the real profile; never substitute an incognito context
35397
+ let attached = null;
35398
+ for (let attempt = 0; !attached; attempt++) {
35399
+ // Wait for MoreLogin's Chromium DevTools endpoint to come up.
35400
+ endpoint = null;
35401
+ for (let i = 0; i < 40; i++) {
35402
+ const probed = await probeCdpEndpoint(debugPort);
35403
+ if (probed.ok) { endpoint = probed.httpEndpoint; break; }
35404
+ await new Promise(r => setTimeout(r, 250));
35405
+ }
35406
+ if (!endpoint) {
35407
+ // Ten seconds without a DevTools answer. A port that answers HTTP as something else will never become
35408
+ // one: say what it is, in place of Playwright's "Unexpected status 404 … try connecting via ws://". A
35409
+ // port nothing listens on yet still gets the connect attempt below.
35410
+ const seen = await moreLogin.describeDebugEndpoint(debugPort);
35411
+ if (seen.kind === 'not-devtools') throw moreLogin.notDevToolsError(envId, debugPort, seen);
35412
+ endpoint = `http://127.0.0.1:${debugPort}`;
35413
+ }
35414
+ try {
35415
+ attached = await moreLogin.attachProfileBrowser(
35416
+ chromium, endpoint,
35417
+ (cdpBrowser, cdpContext) => newSessionPage({ browser: cdpBrowser, context: cdpContext, _profileMode: 'morelogin' }),
35418
+ ); // fresh tab in the real profile; never substitute an incognito context
35419
+ } catch (attachError) {
35420
+ // MoreLogin lists the profile running, but its browser holds no profile (its window was closed and the
35421
+ // process lives on, or it is still starting: P-4 at 21:13:36 on 2026-11-15). Asked once more after a short
35422
+ // wait, through the status again (a profile that finished closing is then started only as startProfile and
35423
+ // the run's guard allow); never a start of a profile MoreLogin still lists as running.
35424
+ if (attachError?.code !== 'MORELOGIN_PROFILE_WINDOWLESS') throw attachError;
35425
+ if (attempt >= 1) throw moreLogin.windowlessProfileError(envId, endpoint, attachError.cause || attachError);
35426
+ console.warn(`[browser] MoreLogin profile ${envId}: DevTools port ${debugPort} answers but its browser has no profile (closing or still starting); asking MoreLogin again in 2 s`);
35427
+ await new Promise(r => setTimeout(r, 2000));
35428
+ ({ debugPort } = await moreLogin.startProfile(envId, startOpts));
35429
+ }
35430
+ }
35431
+ const { browser: cdpBrowser, context: cdpContext, page: cdpPage } = attached;
34666
35432
  // A local profile's timezone on this first tab (every later tab gets it in newSessionPage, from the session).
34667
35433
  if (_localProfileInfo?.timezone) await applyPageTimezone(cdpContext, cdpPage, _localProfileInfo.timezone);
34668
35434
 
@@ -34677,6 +35443,8 @@ async function createBrowserSession(options = {}) {
34677
35443
  _profileSourceName = _localProfile ? `Local · ${_localProfileInfo?.name || envId}` : `MoreLogin · ${envId}`;
34678
35444
  _localProfileTimezone = _localProfile ? (_localProfileInfo?.timezone || null) : null;
34679
35445
  _moreLoginConnected = true;
35446
+ // The profile runs and SynaBun is attached: a close outside SynaBun remembered for it is over, for every run.
35447
+ if (!_localProfile) { try { moreLogin.clearOutsideClose(String(envId)); } catch { /* nothing held */ } }
34680
35448
  console.log(`[browser] Connected to ${_localProfile ? `local profile ${envId}` : `MoreLogin env ${envId}`} via CDP at ${endpoint}`);
34681
35449
  } catch (err) {
34682
35450
  if (_localProfile) {
@@ -34686,14 +35454,27 @@ async function createBrowserSession(options = {}) {
34686
35454
  throw refused;
34687
35455
  }
34688
35456
  const port = moreLogin.getMoreLoginPort(savedCfg);
34689
- if (err?.code === 'MORELOGIN_NOT_CHROMIUM' || err?.code === 'MORELOGIN_NOT_DEVTOOLS') {
34690
- // MoreLogin is open and the profile exists: it is the profile's browser SynaBun cannot drive. No "open the
34691
- // MoreLogin app" advice, and the code travels so the run's message does not add it either.
35457
+ if (err?.code === 'MORELOGIN_NOT_CHROMIUM' || err?.code === 'MORELOGIN_NOT_DEVTOOLS' || err?.code === 'MORELOGIN_START_REFUSED'
35458
+ || err?.code === 'MORELOGIN_CLOSED_OUTSIDE' || err?.code === 'MORELOGIN_PROFILE_WINDOWLESS') {
35459
+ // MoreLogin is open and the profile exists: it is the profile's browser SynaBun cannot drive, MoreLogin
35460
+ // itself refused the start (a plan limit, …), the run's profile was closed outside SynaBun and is not started
35461
+ // again for it, or MoreLogin lists it running with no window. No "open the MoreLogin app" advice, and the code
35462
+ // travels so the run's message does not add it either.
34692
35463
  const rule = options.moreloginEnvId
34693
35464
  ? 'a session asked for a MoreLogin profile never falls back to another profile or to Chrome'
34694
35465
  : 'sessions will not fall back to Chrome while MoreLogin is the default browser';
34695
- const refused = new Error(`MoreLogin connect failed: ${err.message}. Nothing was opened elsewhere: ${rule}.`);
35466
+ // A run whose profile was closed outside SynaBun: nothing failed to connect, SynaBun chose not to start it, and
35467
+ // the sentence (lib/morelogin-outside-close.js outsideCloseError) already says all of it.
35468
+ const refused = new Error(err.code === 'MORELOGIN_CLOSED_OUTSIDE'
35469
+ ? `${err.message}.`
35470
+ : `MoreLogin connect failed: ${err.message}. Nothing was opened elsewhere: ${rule}.`);
34696
35471
  refused.code = err.code;
35472
+ if (err.needsUser) refused.needsUser = true;
35473
+ if (err.apiCode != null) refused.apiCode = err.apiCode;
35474
+ if (err.planLimit) refused.planLimit = true;
35475
+ if (err.resetAt) refused.resetAt = err.resetAt;
35476
+ if (err.closedAt) refused.closedAt = err.closedAt;
35477
+ if (err.holdUntil) refused.holdUntil = err.holdUntil;
34697
35478
  throw refused;
34698
35479
  }
34699
35480
  if (options.moreloginEnvId) {
@@ -35149,6 +35930,10 @@ async function createBrowserSession(options = {}) {
35149
35930
  context.on('close', () => {
35150
35931
  const orphanedLoops = session._loopOwned?.size > 0 ? [...session._loopOwned] : [];
35151
35932
  console.log(`Browser context closed for session ${sessionId}${session._agentOwnedSet?.size ? ` (agent-owned: ${[...session._agentOwnedSet].join(',')})` : ''}${orphanedLoops.length ? ` (orphaning loops: ${orphanedLoops.map(logOwnerId).join(', ')})` : ''}`);
35933
+ // A MoreLogin profile's browser went away: who closed it (SynaBun's own revocation or teardown, or somebody
35934
+ // else: then one line of evidence, and the runs it orphaned do not start it again). The profile is never
35935
+ // reopened from here (each start spends one of MoreLogin's daily launches).
35936
+ try { noteMoreLoginContextClose(session, sessionId, context); } catch { /* the close goes on */ }
35152
35937
  session.screencastActive = false;
35153
35938
  detachScreencastFrameHandler(session);
35154
35939
  // Stop autosave interval
@@ -35335,6 +36120,7 @@ async function stopScreencast(session) {
35335
36120
  * of such a session closes those, and only those (closeOwnTabsBeforeDisconnect).
35336
36121
  */
35337
36122
  async function newSessionPage(session, { timeoutMs } = {}) {
36123
+ if (session._profileMode === 'extension') throw Object.assign(new Error('Use the extension adapter to create tabs.'), { code: 'UNSUPPORTED_IN_EXTENSION_MODE' });
35338
36124
  let page;
35339
36125
  if (backgroundTabsEnabled(loadBrowserConfig())) {
35340
36126
  page = await openBackgroundPageStrict(session.browser, session.context, {
@@ -35686,6 +36472,11 @@ async function _switchSessionTab(session, sessionId, tabId) {
35686
36472
  * Close a single tab in a session. If it's the last tab, destroys the whole session.
35687
36473
  */
35688
36474
  async function closeSessionTab(session, sessionId, tabId) {
36475
+ if (session._profileMode === 'extension') {
36476
+ const owner = [...session._tabOwners.keys()].find(key => extensionAdapter.ownsTab(session, key, tabId));
36477
+ if (owner) await extensionAdapter.release(sessionId, owner, tabId);
36478
+ return;
36479
+ }
35689
36480
  const tabEntry = session.tabs.get(tabId);
35690
36481
  if (!tabEntry) return;
35691
36482
 
@@ -35743,6 +36534,7 @@ async function closeSessionTab(session, sessionId, tabId) {
35743
36534
  */
35744
36535
  async function destroyBrowserSession(sessionId, { closeOwnTabs = false, closingPage = null } = {}) {
35745
36536
  const session = browserSessions.get(sessionId);
36537
+ if (session?._profileMode === 'extension') return extensionAdapter.destroy(sessionId);
35746
36538
  if (!session) return;
35747
36539
 
35748
36540
  try {
@@ -36280,7 +37072,47 @@ app.use('/api/browser/sessions/:id', (req, res, next) => {
36280
37072
  }
36281
37073
  return gate();
36282
37074
  });
36283
- // Read-only semantic context for the browser judgments (the judgments themselves run in the MCP layer).
37075
+ // Read-only semantic context for the browser judgments and extension backend dispatch.
37076
+ // All extension endpoints terminate here; none falls through to Playwright or raw CDP.
37077
+ app.use('/api/browser', extensionAdapter.middleware);
37078
+ const extensionOwnerGuard = ownerRouteGuard({ isGuestRequest, port: PORT, allowedOrigins: publicWebOrigins, refuseCrossSite: true, ownOriginsOnly: true, requireOrigin: true });
37079
+ app.use('/api/browser/extension', extensionOwnerGuard, (req, res, next) => {
37080
+ if (browserCaller(req).automation || !browserOwnerPageOnly(req)) return res.status(403).json({ code: 'OWNER_ROUTE', error: 'Extension pairing and approval belong to the owner.' });
37081
+ res.setHeader('Cache-Control', 'no-store'); next();
37082
+ });
37083
+ app.get('/api/browser/extension', (_req, res) => {
37084
+ const folderState = extensionFolderState(DATA_HOME), status = extensionBridge.status();
37085
+ // `folder`: the folder the owner loads (the prepared copy; the bundled one only when none could be prepared).
37086
+ res.json({ ...status, folder: folderState.prepared ? folderState.folder : EXTENSION_FOLDER, bundledFolder: EXTENSION_FOLDER, uploadFolder: extensionUploadRoot,
37087
+ folderVersion: folderState.version, reloadNeeded: !!(status.connected && folderState.version && status.extensionVersion !== folderState.version),
37088
+ setup: extensionSetup.status().state });
37089
+ });
37090
+ // The one-button setup. Owner only: these sit under the guard above (ownerRouteGuard, the page secret, no automation
37091
+ // caller), like pairing and the mode. The token (ticket) goes to SynaBun's own setup page only, never into a log or URL.
37092
+ const sendSetup = (res, run) => Promise.resolve().then(run).then(value => res.json({ ok: true, ...value }),
37093
+ error => res.status(400).json(extensionSetupError(error) || extensionSafeError(error)));
37094
+ app.get('/api/browser/extension/setup/status', (_req, res) => sendSetup(res, () => extensionSetup.status()));
37095
+ app.post('/api/browser/extension/setup/start', (req, res) => sendSetup(res, () => extensionSetup.start({ browserId: typeof req.body?.browser === 'string' ? req.body.browser : undefined })));
37096
+ app.post('/api/browser/extension/setup/ticket', (_req, res) => { res.setHeader('Cache-Control', 'no-store'); return sendSetup(res, () => extensionSetup.ticket()); });
37097
+ app.post('/api/browser/extension/setup/cancel', (_req, res) => sendSetup(res, () => extensionSetup.cancel()));
37098
+ app.post('/api/browser/extension/setup/reveal', (_req, res) => sendSetup(res, () => extensionSetup.reveal()));
37099
+ app.post('/api/browser/extension/setup/reopen', (_req, res) => sendSetup(res, () => extensionSetup.reopen()));
37100
+ app.post('/api/browser/extension/:action', async (req, res) => {
37101
+ try {
37102
+ const action = req.params.action;
37103
+ if (action === 'pair') return res.json(await extensionBridge.beginPairing(Number(req.body?.port || 3345)));
37104
+ if (action === 'disconnect') extensionBridge.disconnect();
37105
+ else if (action === 'resume') extensionBridge.resume();
37106
+ else if (action === 'revoke') extensionBridge.revoke();
37107
+ else if (action === 'revoke-tab') await extensionBridge.revokeTab(req.body?.tab);
37108
+ else if (action === 'revoke-site') await extensionBridge.revokeSite(req.body?.site);
37109
+ // The owner's mode: full control (any site and tab of the paired browser) or only what the owner shares.
37110
+ else if (action === 'mode') await extensionBridge.setMode(req.body?.fullControl);
37111
+ else return res.status(400).json({ code: 'INVALID_MESSAGE', error: 'Unknown extension action.' });
37112
+ return res.json({ ok: true, ...extensionBridge.status() });
37113
+ } catch (error) { return res.status(400).json(extensionSafeError(error)); }
37114
+ });
37115
+ // Semantic context itself runs only on Playwright sessions; the extension adapter has already answered.
36284
37116
  app.use('/api/browser', createBrowserAssistRouter({ browserSessions, getTargetPage, normalizeSelector }));
36285
37117
 
36286
37118
  app.get('/api/browser/sessions', (req, res) => {
@@ -36310,7 +37142,7 @@ app.get('/api/browser/sessions', (req, res) => {
36310
37142
  const sessions = [...browserSessions.entries()].map(([id, s]) => {
36311
37143
  const allTabs = s.tabs ? [...s.tabs.entries()] : [];
36312
37144
  const ownTabId = automationView && caller ? (s._tabOwners?.get(caller) || null) : null;
36313
- const shownTabs = automationView ? allTabs.filter(([tid]) => tid === ownTabId) : allTabs;
37145
+ const shownTabs = automationView ? allTabs.filter(([tid]) => s._profileMode === 'extension' ? extensionAdapter.ownsTab(s, caller, tid) : tid === ownTabId) : allTabs;
36314
37146
  const ownTab = automationView && shownTabs.length ? shownTabs[0][1] : null;
36315
37147
  return {
36316
37148
  id,
@@ -36323,9 +37155,9 @@ app.get('/api/browser/sessions', (req, res) => {
36323
37155
  profileSource: s._profileSourceName || null,
36324
37156
  moreloginEnvId: s._mlEnvId || null,
36325
37157
  // For a run pinned to a MoreLogin profile of its own, "the default" is that profile's session (sessionServesRun).
36326
- servesDefault: callerPin ? sessionServesMoreLoginEnv(s, callerPin.envId) : (moreLoginDefault ? sessionServesMoreLoginDefault(s, policyCfg) : true),
37158
+ servesDefault: sessionServesRun(s, policyCfg, caller),
36327
37159
  // The browser's own CDP endpoint drives every tab past every check here: the owner's page's only.
36328
- wsEndpoint: who.automation || s._isPersistent ? null : (s.browser.wsEndpoint?.() || null),
37160
+ wsEndpoint: who.automation || s._isPersistent ? null : (s.browser?.wsEndpoint?.() || null),
36329
37161
  activeTabId: automationView ? (ownTabId && s.activeTabId === ownTabId ? ownTabId : null) : (s.activeTabId || null),
36330
37162
  loopOwned: (s._loopOwned?.size || 0) > 0,
36331
37163
  interactiveOwned: (s._interactiveOwned?.size || 0) > 0,
@@ -36364,12 +37196,18 @@ app.get('/api/browser/sessions', (req, res) => {
36364
37196
  // POST /api/loop/recover-browser records a run's move to a tab of its own (`adopt`): an MCP asks it only of a
36365
37197
  // server that says so (an older one reads the request as a recovery and opens a tab).
36366
37198
  adoptRoute: true,
37199
+ // The everyday browser through the extension, in full control: the owner's open tabs no agent holds, which an
37200
+ // agent may take over (browser_session create with that tabId). Only for a verified run or the owner's page.
37201
+ ...(policyCfg.connectMode === 'extension' && !callerPin && (who.automation ? who.status === 'verified' : browserOwnerPageOnly(req))
37202
+ ? (() => { const tabs = extensionAdapter.ownerTabs({ caller, includeOwned: true }); return tabs ? { extensionTabs: { fullControl: true, tabs } } : {}; })()
37203
+ : {}),
36367
37204
  });
36368
37205
  });
36369
37206
 
36370
37207
  app.post('/api/browser/sessions', async (req, res) => {
36371
37208
  const { url, width, height, screenWidth, screenHeight, deviceScaleFactor, timezone, connectMode, moreloginEnvId } = req.body;
36372
- // Which browser or MoreLogin profile a session starts on is the owner's choice (Settings → Browser): an automation's
37209
+ // Which browser or MoreLogin profile a session starts on is the owner's choice (Settings → Browser for SynaBun's own
37210
+ // browser, Settings → Connected tools → MoreLogin for the default AI browser profile): an automation's
36373
37211
  // create opens the default browser and names neither (lib/browser-automation-routes.js; review 972afb74, finding 1).
36374
37212
  // N1 (re-review of 2026-11-10): the check asked `creator.automation` only, so an invite guest with the `browser`
36375
37213
  // permission (browserTerminalGate lets a guest reach this route: browserPageOwner) who knew a profile's id opened
@@ -36379,7 +37217,12 @@ app.post('/api/browser/sessions', async (req, res) => {
36379
37217
  const ownerFields = (creator.automation || !browserOwnerPageOnly(req)) ? ownerOnlyCreateFields(req.body) : [];
36380
37218
  if (ownerFields.length) {
36381
37219
  const guestCreate = !creator.automation;
36382
- return res.status(403).json({ ok: false, code: 'OWNER_ONLY_FIELDS', fields: ownerFields, error: `${guestCreate ? 'A guest' : 'An automation'} opens the default browser: ${ownerFields.join(' and ')} ${ownerFields.length === 1 ? 'is' : 'are'} the owner's choice (Settings → Browser). Leave ${ownerFields.length === 1 ? 'it' : 'them'} out.` });
37220
+ // Where the owner makes each choice: a MoreLogin profile (the default AI browser) in the MoreLogin tab, SynaBun's
37221
+ // own browser (connect mode, folders, executable) in Settings → Browser.
37222
+ const profileFields = ownerFields.some((f) => /^morelogin/i.test(f));
37223
+ const browserFields = ownerFields.some((f) => !/^morelogin/i.test(f));
37224
+ const where = [profileFields && 'Settings → Connected tools → MoreLogin (Default AI browser)', browserFields && 'Settings → Browser'].filter(Boolean).join('; ');
37225
+ return res.status(403).json({ ok: false, code: 'OWNER_ONLY_FIELDS', fields: ownerFields, error: `${guestCreate ? 'A guest' : 'An automation'} opens the default browser: ${ownerFields.join(' and ')} ${ownerFields.length === 1 ? 'is' : 'are'} the owner's choice (${where}). Leave ${ownerFields.length === 1 ? 'it' : 'them'} out.` });
36383
37226
  }
36384
37227
  // A create-session startUrl that points at one of SynaBun's own live OpenCode serve ports is refused up front, like
36385
37228
  // navigate and new-tab: the serve's API can change what a worker session may do, and createBrowserSession navigates
@@ -36427,15 +37270,28 @@ app.post('/api/browser/sessions', async (req, res) => {
36427
37270
  }
36428
37271
  // The start, its owner and its broadcast: once per start, whoever ends up with it.
36429
37272
  const start = async () => {
36430
- const result = await createBrowserSession({
36431
- url, width, height, screenWidth, screenHeight, deviceScaleFactor, timezone, _realHeaders,
36432
- // Its deadline bounds the native serve check (installServePortGuard) inside the caller's timeout.
36433
- browserRequest: req.browserRequest,
36434
- // Optional per-session override to target a specific MoreLogin env (multi-identity)
36435
- ...(connectMode === 'morelogin' ? { connectMode } : {}),
36436
- ...(moreloginEnvId ? { moreloginEnvId: String(moreloginEnvId) } : {}),
36437
- });
37273
+ let result;
37274
+ try {
37275
+ result = await createBrowserSession({
37276
+ url, width, height, screenWidth, screenHeight, deviceScaleFactor, timezone, _realHeaders,
37277
+ // Its deadline bounds the native serve check (installServePortGuard) inside the caller's timeout.
37278
+ browserRequest: req.browserRequest,
37279
+ // Optional per-session override to target a specific MoreLogin env (multi-identity)
37280
+ ...(connectMode === 'morelogin' ? { connectMode } : {}),
37281
+ ...(moreloginEnvId ? { moreloginEnvId: String(moreloginEnvId) } : {}),
37282
+ // The owner's own page (its page secret, no run or agent header) opening a session is the owner starting
37283
+ // the profile: it may start one closed outside SynaBun (lib/morelogin-outside-close.js). Nobody else may.
37284
+ ...(!creator.automation && browserOwnerPageOnly(req) ? { moreloginAfterOutsideClose: 'owner' } : {}),
37285
+ });
37286
+ } catch (err) {
37287
+ // An automation's own profile here is the MoreLogin default: when it fails to start or connect, the run may not
37288
+ // move to another profile (lib/morelogin-profile-failures.js). The owner's page has no run to bar.
37289
+ if (who.automation && creatorTerminalId) noteRunProfileFailure(creatorTerminalId, runEffectiveProfile(creatorTerminalId), browserStartFailure(err));
37290
+ throw err;
37291
+ }
36438
37292
  const createdSession = browserSessions.get(result.sessionId);
37293
+ // Connected to the profile: a failure of it noted earlier in this run is over.
37294
+ if (who.automation && creatorTerminalId && createdSession?._mlEnvId) noteRunProfileConnected(creatorTerminalId, createdSession._mlEnvId);
36439
37295
  if (creatorTerminalId && createdSession) {
36440
37296
  if (!createdSession._tabOwners) createdSession._tabOwners = new Map();
36441
37297
  createdSession._tabOwners.set(creatorTerminalId, createdSession.activeTabId);
@@ -36468,8 +37324,11 @@ app.post('/api/browser/sessions', async (req, res) => {
36468
37324
  } catch (err) {
36469
37325
  console.error('Browser session create error:', err.message);
36470
37326
  const acq = err?.acquisition;
36471
- if (acq) return res.status(500).json({ error: acq.error, ...(acq.code ? { code: acq.code, offenders: acq.offenders } : {}) });
36472
- res.status(500).json(browserStartFailure(err));
37327
+ if (acq?.code === 'MORELOGIN_CLOSED_OUTSIDE') return res.status(409).json(closedOutsideAnswer(acq));
37328
+ if (acq) return res.status(500).json({ error: acq.error, ...(acq.code ? { code: acq.code, offenders: acq.offenders } : {}), ...(acq.needsUser ? { needsUser: true } : {}) });
37329
+ const failure = browserStartFailure(err);
37330
+ if (failure.code === 'MORELOGIN_CLOSED_OUTSIDE') return res.status(409).json(closedOutsideAnswer(failure));
37331
+ res.status(500).json(failure);
36473
37332
  }
36474
37333
  });
36475
37334
 
@@ -36536,11 +37395,19 @@ app.post('/api/browser/acquire', async (req, res) => {
36536
37395
  res.json({ ok: true, sessionId: acq.browserSessionId, tabId: acq.browserTabId || null, ...(outcome.from !== 'started' && { handedOver: outcome.from }) });
36537
37396
  } catch (err) {
36538
37397
  const acq = err?.acquisition;
36539
- if (acq) return res.status(500).json({ error: acq.error, ...(acq.code ? { code: acq.code, offenders: acq.offenders } : {}) });
37398
+ // The profile was closed outside SynaBun and SynaBun does not reopen it: 409, the user acts (never a replacement).
37399
+ if (acq?.code === 'MORELOGIN_CLOSED_OUTSIDE') return res.status(409).json(closedOutsideAnswer(acq));
37400
+ if (acq) return res.status(500).json({ error: acq.error, ...(acq.code ? { code: acq.code, offenders: acq.offenders } : {}), ...(acq.needsUser ? { needsUser: true } : {}) });
36540
37401
  res.status(err.status || 500).json({ error: err.message, ...(err.code ? { code: err.code } : {}) });
36541
37402
  }
36542
37403
  });
36543
37404
 
37405
+ /** The answer of a browser route refused because its MoreLogin profile was closed outside SynaBun (409). */
37406
+ function closedOutsideAnswer(acq) {
37407
+ return { ok: false, error: acq.error, code: 'MORELOGIN_CLOSED_OUTSIDE', needsUser: true, blocked: true,
37408
+ ...(acq.closedAt ? { closedAt: acq.closedAt } : {}), ...(acq.holdUntil ? { holdUntil: acq.holdUntil } : {}) };
37409
+ }
37410
+
36544
37411
  // POST /api/browser/release — interactive MCP process relinquishes its owned tab on
36545
37412
  // exit. Closes the dedicated tab and drops the ownership/routing entries so the shared
36546
37413
  // browser can be grace-reaped once no owners remain. Best-effort; body: { clientId }.
@@ -38384,7 +39251,7 @@ app.put('/api/browser/config', async (req, res) => {
38384
39251
  // Finding 1 of the re-review of 2026-11-11: only the owner's page changes the default AI browser (connect mode,
38385
39252
  // default MoreLogin profile). browserTerminalGate already keeps this route from automations; this is the route's own.
38386
39253
  if (browserDefaultChangeRefused(req, body, loadBrowserConfig())) return refuseDefaultBrowserChange(res);
38387
- if (body.connectMode !== undefined) body.connectMode = ['attach', 'morelogin'].includes(body.connectMode) ? body.connectMode : 'mirror';
39254
+ if (body.connectMode !== undefined) body.connectMode = ['attach', 'morelogin', 'extension'].includes(body.connectMode) ? body.connectMode : 'mirror';
38388
39255
  if (body.attachSeed !== undefined) body.attachSeed = body.attachSeed === 'fresh' ? 'fresh' : 'real';
38389
39256
  if (body.moreloginEnvId !== undefined && body.moreloginEnvId !== null && body.moreloginEnvId !== '') body.moreloginEnvId = String(body.moreloginEnvId);
38390
39257
  // The default MoreLogin profile is driven over CDP: a newly chosen one known to be Firefox-type is refused. The
@@ -38428,7 +39295,7 @@ app.get('/api/browser/detect-profiles', (req, res) => {
38428
39295
  }
38429
39296
  });
38430
39297
 
38431
- // List MoreLogin profiles (environments) for the Browser settings profile picker
39298
+ // List MoreLogin profiles (environments) for the profile pickers (the MoreLogin tab's Default AI browser, schedules)
38432
39299
  app.get('/api/browser/morelogin-envs', async (req, res) => {
38433
39300
  try {
38434
39301
  const cfg = loadBrowserConfig();
@@ -38443,19 +39310,25 @@ app.get('/api/browser/morelogin-envs', async (req, res) => {
38443
39310
  try { localEnvs = (await moreLogin.listLocalProfiles()).map((env) => ({ ...env, browser: 'chromium' })); }
38444
39311
  catch (err) { localError = err.message; }
38445
39312
  const local = { count: localEnvs.length, ...(localError ? { error: localError } : {}) };
39313
+ // Profiles whose start MoreLogin refused for its plan's daily limit, until its day resets (SynaBun's own record:
39314
+ // said whatever state MoreLogin is in). Named from the list below when it is read.
39315
+ const startCooldowns = moreLoginStartCooldowns();
39316
+ // Profiles closed outside SynaBun that SynaBun does not reopen (lib/morelogin-outside-close.js), said in every
39317
+ // answer too: [{ envId, name, closedAt, closedLocal, holdUntil, holdUntilLocal, runs }].
39318
+ const closedOutside = moreLoginClosedOutside();
38446
39319
  // Probe first: the install-folder check knows only the default folders, and an
38447
39320
  // answering local API proves the app is there wherever it was installed.
38448
39321
  const probe = await moreLogin.probeMoreLoginApi({ savedCfg: cfg, port });
38449
39322
  const installed = probe.running || moreLogin.isMoreLoginInstalled().installed;
38450
- if (!installed) return res.json({ connectMode, ok: true, installed: false, running: false, port, envs: localEnvs, local, error: probe.error || null });
38451
- if (!probe.running) return res.json({ connectMode, ok: true, installed: true, running: false, port, envs: localEnvs, local, error: probe.error || null });
39323
+ if (!installed) return res.json({ connectMode, ok: true, installed: false, running: false, port, envs: localEnvs, local, startCooldowns, closedOutside, error: probe.error || null });
39324
+ if (!probe.running) return res.json({ connectMode, ok: true, installed: true, running: false, port, envs: localEnvs, local, startCooldowns, closedOutside, error: probe.error || null });
38452
39325
  // The API answered with an error (signature required, API off): say why, never an empty list.
38453
- if (probe.apiError) return res.json({ connectMode, ok: false, installed: true, running: true, port, envs: localEnvs, local, error: probe.apiError });
39326
+ if (probe.apiError) return res.json({ connectMode, ok: false, installed: true, running: true, port, envs: localEnvs, local, startCooldowns, closedOutside, error: probe.apiError });
38454
39327
  // MoreLogin's own rows (the list holds the local ones too: they are added once, below).
38455
39328
  const listedEnvs = (await moreLogin.listProfiles({ savedCfg: cfg, port })).filter((env) => env.kind !== 'local');
38456
39329
  // The API counted profiles but none could be read: a shape problem, never "no profiles yet".
38457
39330
  if (probe.count > 0 && !listedEnvs.length) {
38458
- return res.json({ connectMode, ok: false, installed: true, running: true, port, envs: localEnvs, local, error: `MoreLogin reports ${probe.count} profile(s) but SynaBun could not read them from its answer; a newer MoreLogin may have changed its API.` });
39331
+ return res.json({ connectMode, ok: false, installed: true, running: true, port, envs: localEnvs, local, startCooldowns, closedOutside, error: `MoreLogin reports ${probe.count} profile(s) but SynaBun could not read them from its answer; a newer MoreLogin may have changed its API.` });
38459
39332
  }
38460
39333
  // Each profile with the browser it runs (`browser`: 'chromium' | 'firefox' | null = not known): the list call
38461
39334
  // does not say it, so it is looked up per profile, kept, and never waited for longer than the lookup's budget.
@@ -38463,6 +39336,8 @@ app.get('/api/browser/morelogin-envs', async (req, res) => {
38463
39336
  const { envs, browsersPending } = await withMoreLoginBrowsers(listedEnvs, { savedCfg: cfg, port });
38464
39337
  res.json({
38465
39338
  connectMode, ok: true, installed: true, running: true, port, envs: [...envs, ...localEnvs], local, browsersPending,
39339
+ startCooldowns: moreLoginStartCooldowns(listedEnvs),
39340
+ closedOutside: moreLoginClosedOutside(listedEnvs),
38466
39341
  // Observed website-policy blocks — MoreLogin's local API never exposes the
38467
39342
  // blacklist/whitelist itself, so the picker reports what actually happened.
38468
39343
  blockedNavigations: moreLoginBlockStats.count,
@@ -38723,7 +39598,7 @@ const httpServer = app.listen(PORT, async () => {
38723
39598
  }, 200);
38724
39599
 
38725
39600
  // Detect MoreLogin (anti-detect browser) — DETECTION ONLY, never auto-activates.
38726
- // Activation is an explicit user choice via Settings → Browser / the MoreLogin tab.
39601
+ // Activation is an explicit user choice in the MoreLogin tab (Default AI browser).
38727
39602
  setTimeout(async () => {
38728
39603
  try {
38729
39604
  const mlBootCfg = loadBrowserConfig();
@@ -38866,6 +39741,39 @@ const httpServer = app.listen(PORT, async () => {
38866
39741
  console.warn(' Rules reconcile warning:', err.message);
38867
39742
  }
38868
39743
 
39744
+ // The owner's tool permissions (Settings → Tool permissions): what was switched on and is missing from the
39745
+ // allow list of ~/.claude/settings.json is put back, and what the list allows is written down as chosen
39746
+ // (lib/tool-permission-choices.js). An update is a start, so this is what keeps the choices across one.
39747
+ {
39748
+ const kept = reconcileSavedToolPermissions('start');
39749
+ if (kept.restored.length) console.log(` Tools: ${kept.restored.length} saved tool permission${kept.restored.length === 1 ? '' : 's'} put back in ${getGlobalClaudeSettingsPath()}`);
39750
+ }
39751
+
39752
+ // Every named Claude account reads the default's settings.json (allow list, hooks), CLAUDE.md, rules and skills
39753
+ // (lib/claude-account-links.js): a missing link is made, the junction to a file that an older SynaBun made
39754
+ // on Windows (it opens as a broken folder, so the account read no settings at all) is replaced, and a hard
39755
+ // link or copy two writes apart is brought back in step. Never stops the boot.
39756
+ try {
39757
+ const shared = _panelClaudeAccounts().syncShared();
39758
+ const repaired = shared.filter((row) => row.repaired.length);
39759
+ if (repaired.length) console.log(` Accounts: shared Claude settings put back in order for ${repaired.length} account${repaired.length === 1 ? '' : 's'} (${[...new Set(repaired.flatMap((row) => row.repaired))].join(', ')})`);
39760
+ } catch (err) {
39761
+ console.warn(' Claude accounts warning:', err.message);
39762
+ }
39763
+
39764
+ // Every named Codex account reads Default's config.toml (model, MCP servers, tool settings), AGENTS.md and
39765
+ // prompts/ the same way (lib/codex-accounts.js syncShared). On Windows SynaBun linked the two files with a
39766
+ // symbolic link only, which Windows refuses without Developer Mode or administrator rights: such an account
39767
+ // ran on a config.toml of its own and without AGENTS.md. Put in order once here; a hard link or a copy two
39768
+ // writes apart is brought back in step at every start. Never stops the boot.
39769
+ try {
39770
+ const shared = _codexAccounts().syncShared();
39771
+ const changed = shared.filter((row) => row.repaired.length || row.linked.length);
39772
+ if (changed.length) console.log(` Accounts: shared Codex files put back in order for ${changed.length} account${changed.length === 1 ? '' : 's'} (${[...new Set(changed.flatMap((row) => [...row.repaired, ...row.linked]))].join(', ')})`);
39773
+ } catch (err) {
39774
+ console.warn(' Codex accounts warning:', err.message);
39775
+ }
39776
+
38869
39777
  // SynaBun's Antigravity homes (lib/antigravity/home.js): a run's home lives a week past its last use (a run resumes
38870
39778
  // within minutes of a restart), an Assistant brain's two months (its conversation can be picked up later).
38871
39779
  try {
@@ -39277,10 +40185,8 @@ function handleWhiteboardWebSocket(ws, req) {
39277
40185
  let _screenshotPattern = null;
39278
40186
 
39279
40187
  if (process.platform === 'darwin') {
39280
- try {
39281
- _screenshotDir = execSync('defaults read com.apple.screencapture location', { encoding: 'utf8' }).trim();
39282
- } catch { /* not set — use default */ }
39283
- if (!_screenshotDir || !existsSync(_screenshotDir)) _screenshotDir = join(os.homedir(), 'Desktop');
40188
+ // The Screenshot app's folder, else ~/Desktop (lib/screenshot-location.js: quiet when none was ever set).
40189
+ _screenshotDir = macScreenshotDir();
39284
40190
  // macOS screenshot filenames: "Screenshot ..." (EN), "Captura de..." (ES/PT)
39285
40191
  _screenshotPattern = /^(Screenshot\b|Captura de).*\.png$/i;
39286
40192
  } else if (process.platform === 'win32') {
@@ -39455,6 +40361,10 @@ function handleCardsWebSocket(ws) {
39455
40361
  async function handleBrowserWebSocket(ws, url) {
39456
40362
  const sessionId = url.pathname.replace('/ws/browser/', '');
39457
40363
  const session = browserSessions.get(sessionId);
40364
+ if (session?._profileMode === 'extension') {
40365
+ ws.send(JSON.stringify({ type: 'error', code: 'UNSUPPORTED_IN_EXTENSION_MODE', message: 'Use the everyday browser window. Extension mode has no CDP screencast or remote input socket.' }));
40366
+ ws.close(); return;
40367
+ }
39458
40368
 
39459
40369
  if (!session) {
39460
40370
  ws.send(JSON.stringify({ type: 'error', message: 'Browser session not found' }));