synabun 2.2.2 → 2.3.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 (276) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +1 -1
  3. package/docs/whatsapp.md +52 -20
  4. package/lib/mcp-build.js +519 -0
  5. package/lib/mcp-dist.js +10 -4
  6. package/lib/server-supervisor.js +7 -1
  7. package/lib/virustotal.mjs +4 -2
  8. package/mcp-server/dist/http.d.ts +38 -0
  9. package/mcp-server/dist/http.d.ts.map +1 -1
  10. package/mcp-server/dist/http.js +75 -7
  11. package/mcp-server/dist/http.js.map +1 -1
  12. package/mcp-server/dist/services/browser-route-flow.d.ts +3 -2
  13. package/mcp-server/dist/services/browser-route-flow.d.ts.map +1 -1
  14. package/mcp-server/dist/services/browser-route-flow.js +4 -3
  15. package/mcp-server/dist/services/browser-route-flow.js.map +1 -1
  16. package/mcp-server/dist/services/embedding-service.d.ts.map +1 -1
  17. package/mcp-server/dist/services/embedding-service.js +2 -1
  18. package/mcp-server/dist/services/embedding-service.js.map +1 -1
  19. package/mcp-server/dist/services/neural-interface.d.ts +21 -0
  20. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  21. package/mcp-server/dist/services/neural-interface.js +76 -4
  22. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  23. package/mcp-server/dist/services/tool-catalog.js +2 -2
  24. package/mcp-server/dist/services/tool-catalog.js.map +1 -1
  25. package/mcp-server/dist/tools/agents.d.ts +3 -2
  26. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  27. package/mcp-server/dist/tools/agents.js +6 -4
  28. package/mcp-server/dist/tools/agents.js.map +1 -1
  29. package/mcp-server/dist/tools/browser-advanced.d.ts +3 -1
  30. package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
  31. package/mcp-server/dist/tools/browser-advanced.js +30 -8
  32. package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
  33. package/mcp-server/dist/tools/browser-navigate.d.ts +3 -3
  34. package/mcp-server/dist/tools/browser-navigate.d.ts.map +1 -1
  35. package/mcp-server/dist/tools/browser-navigate.js +19 -16
  36. package/mcp-server/dist/tools/browser-navigate.js.map +1 -1
  37. package/mcp-server/dist/tools/browser-observe.d.ts +2 -1
  38. package/mcp-server/dist/tools/browser-observe.d.ts.map +1 -1
  39. package/mcp-server/dist/tools/browser-observe.js +61 -20
  40. package/mcp-server/dist/tools/browser-observe.js.map +1 -1
  41. package/mcp-server/dist/tools/morelogin.d.ts +13 -3
  42. package/mcp-server/dist/tools/morelogin.d.ts.map +1 -1
  43. package/mcp-server/dist/tools/morelogin.js +81 -20
  44. package/mcp-server/dist/tools/morelogin.js.map +1 -1
  45. package/mcp-server/dist/tools/youtube/upload.d.ts.map +1 -1
  46. package/mcp-server/dist/tools/youtube/upload.js +225 -88
  47. package/mcp-server/dist/tools/youtube/upload.js.map +1 -1
  48. package/mcp-server/package-lock.json +2 -2
  49. package/mcp-server/package.json +1 -1
  50. package/mcp-server/src/http.ts +79 -7
  51. package/mcp-server/src/services/browser-route-flow.ts +4 -3
  52. package/mcp-server/src/services/embedding-service.ts +2 -1
  53. package/mcp-server/src/services/neural-interface.ts +77 -4
  54. package/mcp-server/src/services/tool-catalog.ts +2 -2
  55. package/mcp-server/src/tools/agents.ts +8 -4
  56. package/mcp-server/src/tools/browser-advanced.ts +29 -8
  57. package/mcp-server/src/tools/browser-navigate.ts +19 -16
  58. package/mcp-server/src/tools/browser-observe.ts +62 -20
  59. package/mcp-server/src/tools/morelogin.ts +81 -20
  60. package/mcp-server/src/tools/youtube/upload.ts +218 -99
  61. package/neural-interface/i18n/en.json +631 -123
  62. package/neural-interface/i18n/pt-BR.json +518 -10
  63. package/neural-interface/lib/assistant-api.js +26 -0
  64. package/neural-interface/lib/assistant-brains/claude.js +5 -0
  65. package/neural-interface/lib/assistant-catalog.js +114 -1
  66. package/neural-interface/lib/assistant-dispatch.js +71 -1
  67. package/neural-interface/lib/assistant-persona.js +14 -7
  68. package/neural-interface/lib/assistant-router.js +6 -4
  69. package/neural-interface/lib/assistant-runtime.js +3 -0
  70. package/neural-interface/lib/assistant-task-prompt.js +5 -0
  71. package/neural-interface/lib/automation-approval.js +249 -0
  72. package/neural-interface/lib/automation-browser-owner-access.js +82 -0
  73. package/neural-interface/lib/backup-service.js +16 -1
  74. package/neural-interface/lib/browser-background-tab.js +72 -3
  75. package/neural-interface/lib/browser-extraction.js +106 -45
  76. package/neural-interface/lib/browser-profile-choices.js +143 -0
  77. package/neural-interface/lib/browser-profiles.js +142 -0
  78. package/neural-interface/lib/browser-tab-recovery.js +153 -0
  79. package/neural-interface/lib/browser-tool-policy.js +2 -0
  80. package/neural-interface/lib/chromium-on-device-model.js +67 -0
  81. package/neural-interface/lib/claude-agent-bridge.js +7 -4
  82. package/neural-interface/lib/claude-model-catalog.js +12 -0
  83. package/neural-interface/lib/effort-levels.js +28 -2
  84. package/neural-interface/lib/local-profile-proxy.js +362 -0
  85. package/neural-interface/lib/local-profiles.js +929 -0
  86. package/neural-interface/lib/loop-logger.js +25 -4
  87. package/neural-interface/lib/maritaca/api.js +179 -0
  88. package/neural-interface/lib/maritaca/attachments.js +44 -0
  89. package/neural-interface/lib/maritaca/client.js +362 -0
  90. package/neural-interface/lib/maritaca/key-store.js +122 -0
  91. package/neural-interface/lib/maritaca/models.js +181 -0
  92. package/neural-interface/lib/maritaca/modes.js +39 -0
  93. package/neural-interface/lib/maritaca/opencode-proxy.js +236 -0
  94. package/neural-interface/lib/maritaca/opencode-stream.js +345 -0
  95. package/neural-interface/lib/maritaca/opencode.js +218 -0
  96. package/neural-interface/lib/maritaca/panel-bridge.js +273 -0
  97. package/neural-interface/lib/maritaca/sessions.js +198 -0
  98. package/neural-interface/lib/morelogin-agent-profiles.js +149 -0
  99. package/neural-interface/lib/morelogin.js +278 -14
  100. package/neural-interface/lib/native-loop-providers.js +3 -1
  101. package/neural-interface/lib/owner-authority.js +30 -12
  102. package/neural-interface/lib/page-session.js +43 -17
  103. package/neural-interface/lib/request-gate.js +2 -0
  104. package/neural-interface/lib/system-activity.js +1 -1
  105. package/neural-interface/lib/terminal-tokens.js +82 -5
  106. package/neural-interface/package-lock.json +3 -2
  107. package/neural-interface/package.json +2 -1
  108. package/neural-interface/public/assets/mascot/README.md +11 -0
  109. package/neural-interface/public/assets/mascot/ask.gif +0 -0
  110. package/neural-interface/public/assets/mascot/ask.png +0 -0
  111. package/neural-interface/public/assets/mascot/blocked.gif +0 -0
  112. package/neural-interface/public/assets/mascot/blocked.png +0 -0
  113. package/neural-interface/public/assets/mascot/budget.gif +0 -0
  114. package/neural-interface/public/assets/mascot/budget.png +0 -0
  115. package/neural-interface/public/assets/mascot/computer.gif +0 -0
  116. package/neural-interface/public/assets/mascot/computer.png +0 -0
  117. package/neural-interface/public/assets/mascot/edit.gif +0 -0
  118. package/neural-interface/public/assets/mascot/edit.png +0 -0
  119. package/neural-interface/public/assets/mascot/error.gif +0 -0
  120. package/neural-interface/public/assets/mascot/error.png +0 -0
  121. package/neural-interface/public/assets/mascot/hover-attention.gif +0 -0
  122. package/neural-interface/public/assets/mascot/hover-attention.png +0 -0
  123. package/neural-interface/public/assets/mascot/idle-hero.gif +0 -0
  124. package/neural-interface/public/assets/mascot/idle-hero.png +0 -0
  125. package/neural-interface/public/assets/mascot/idle.gif +0 -0
  126. package/neural-interface/public/assets/mascot/idle.png +0 -0
  127. package/neural-interface/public/assets/mascot/manifest.json +254 -0
  128. package/neural-interface/public/assets/mascot/mcp.gif +0 -0
  129. package/neural-interface/public/assets/mascot/mcp.png +0 -0
  130. package/neural-interface/public/assets/mascot/memory.gif +0 -0
  131. package/neural-interface/public/assets/mascot/memory.png +0 -0
  132. package/neural-interface/public/assets/mascot/offline.gif +0 -0
  133. package/neural-interface/public/assets/mascot/offline.png +0 -0
  134. package/neural-interface/public/assets/mascot/pick.gif +0 -0
  135. package/neural-interface/public/assets/mascot/pick.png +0 -0
  136. package/neural-interface/public/assets/mascot/plan.gif +0 -0
  137. package/neural-interface/public/assets/mascot/plan.png +0 -0
  138. package/neural-interface/public/assets/mascot/present.gif +0 -0
  139. package/neural-interface/public/assets/mascot/present.png +0 -0
  140. package/neural-interface/public/assets/mascot/project.gif +0 -0
  141. package/neural-interface/public/assets/mascot/project.png +0 -0
  142. package/neural-interface/public/assets/mascot/read.gif +0 -0
  143. package/neural-interface/public/assets/mascot/read.png +0 -0
  144. package/neural-interface/public/assets/mascot/runs.gif +0 -0
  145. package/neural-interface/public/assets/mascot/runs.png +0 -0
  146. package/neural-interface/public/assets/mascot/scenes/automation.gif +0 -0
  147. package/neural-interface/public/assets/mascot/scenes/automation.png +0 -0
  148. package/neural-interface/public/assets/mascot/scenes/browser.gif +0 -0
  149. package/neural-interface/public/assets/mascot/scenes/browser.png +0 -0
  150. package/neural-interface/public/assets/mascot/scenes/code.gif +0 -0
  151. package/neural-interface/public/assets/mascot/scenes/code.png +0 -0
  152. package/neural-interface/public/assets/mascot/scenes/complex.gif +0 -0
  153. package/neural-interface/public/assets/mascot/scenes/complex.png +0 -0
  154. package/neural-interface/public/assets/mascot/scenes/computer.gif +0 -0
  155. package/neural-interface/public/assets/mascot/scenes/computer.png +0 -0
  156. package/neural-interface/public/assets/mascot/scenes/design.gif +0 -0
  157. package/neural-interface/public/assets/mascot/scenes/design.png +0 -0
  158. package/neural-interface/public/assets/mascot/scenes/edit.gif +0 -0
  159. package/neural-interface/public/assets/mascot/scenes/edit.png +0 -0
  160. package/neural-interface/public/assets/mascot/scenes/generic.gif +0 -0
  161. package/neural-interface/public/assets/mascot/scenes/generic.png +0 -0
  162. package/neural-interface/public/assets/mascot/scenes/image_gen.gif +0 -0
  163. package/neural-interface/public/assets/mascot/scenes/image_gen.png +0 -0
  164. package/neural-interface/public/assets/mascot/scenes/manifest.json +173 -0
  165. package/neural-interface/public/assets/mascot/scenes/memory.gif +0 -0
  166. package/neural-interface/public/assets/mascot/scenes/memory.png +0 -0
  167. package/neural-interface/public/assets/mascot/scenes/quick.gif +0 -0
  168. package/neural-interface/public/assets/mascot/scenes/quick.png +0 -0
  169. package/neural-interface/public/assets/mascot/scenes/read.gif +0 -0
  170. package/neural-interface/public/assets/mascot/scenes/read.png +0 -0
  171. package/neural-interface/public/assets/mascot/scenes/research.gif +0 -0
  172. package/neural-interface/public/assets/mascot/scenes/research.png +0 -0
  173. package/neural-interface/public/assets/mascot/scenes/review.gif +0 -0
  174. package/neural-interface/public/assets/mascot/scenes/review.png +0 -0
  175. package/neural-interface/public/assets/mascot/scenes/search.gif +0 -0
  176. package/neural-interface/public/assets/mascot/scenes/search.png +0 -0
  177. package/neural-interface/public/assets/mascot/scenes/shell.gif +0 -0
  178. package/neural-interface/public/assets/mascot/scenes/shell.png +0 -0
  179. package/neural-interface/public/assets/mascot/scenes/thinking.gif +0 -0
  180. package/neural-interface/public/assets/mascot/scenes/thinking.png +0 -0
  181. package/neural-interface/public/assets/mascot/scenes/video_gen.gif +0 -0
  182. package/neural-interface/public/assets/mascot/scenes/video_gen.png +0 -0
  183. package/neural-interface/public/assets/mascot/scenes/web.gif +0 -0
  184. package/neural-interface/public/assets/mascot/scenes/web.png +0 -0
  185. package/neural-interface/public/assets/mascot/search.gif +0 -0
  186. package/neural-interface/public/assets/mascot/search.png +0 -0
  187. package/neural-interface/public/assets/mascot/shell.gif +0 -0
  188. package/neural-interface/public/assets/mascot/shell.png +0 -0
  189. package/neural-interface/public/assets/mascot/skill.gif +0 -0
  190. package/neural-interface/public/assets/mascot/skill.png +0 -0
  191. package/neural-interface/public/assets/mascot/sleep.gif +0 -0
  192. package/neural-interface/public/assets/mascot/sleep.png +0 -0
  193. package/neural-interface/public/assets/mascot/subagent.gif +0 -0
  194. package/neural-interface/public/assets/mascot/subagent.png +0 -0
  195. package/neural-interface/public/assets/mascot/success.gif +0 -0
  196. package/neural-interface/public/assets/mascot/success.png +0 -0
  197. package/neural-interface/public/assets/mascot/think.gif +0 -0
  198. package/neural-interface/public/assets/mascot/think.png +0 -0
  199. package/neural-interface/public/assets/mascot/wait.gif +0 -0
  200. package/neural-interface/public/assets/mascot/wait.png +0 -0
  201. package/neural-interface/public/assets/mascot/watch.gif +0 -0
  202. package/neural-interface/public/assets/mascot/watch.png +0 -0
  203. package/neural-interface/public/assets/mascot/web.gif +0 -0
  204. package/neural-interface/public/assets/mascot/web.png +0 -0
  205. package/neural-interface/public/onboarding.html +14 -1
  206. package/neural-interface/public/shared/agent-runtime-options.js +49 -8
  207. package/neural-interface/public/shared/agy/agy-panel.js +2 -2
  208. package/neural-interface/public/shared/api.js +4 -4
  209. package/neural-interface/public/shared/assistant/asst-ask-styles.js +8 -8
  210. package/neural-interface/public/shared/assistant/asst-ask.js +1 -1
  211. package/neural-interface/public/shared/assistant/asst-brain-picker.js +99 -9
  212. package/neural-interface/public/shared/assistant/asst-control.js +1 -1
  213. package/neural-interface/public/shared/assistant/asst-limit-wait.js +4 -4
  214. package/neural-interface/public/shared/assistant/asst-panel.js +6 -2
  215. package/neural-interface/public/shared/assistant/asst-rack-styles.js +4 -4
  216. package/neural-interface/public/shared/assistant/asst-render.js +6 -6
  217. package/neural-interface/public/shared/assistant/asst-route-models.js +64 -4
  218. package/neural-interface/public/shared/assistant/asst-route.js +24 -7
  219. package/neural-interface/public/shared/assistant/asst-routes-editor.js +154 -39
  220. package/neural-interface/public/shared/assistant/asst-run-stage.js +3 -3
  221. package/neural-interface/public/shared/assistant/asst-scene-styles.js +8 -111
  222. package/neural-interface/public/shared/assistant/asst-scenes.js +46 -318
  223. package/neural-interface/public/shared/assistant/asst-sidepanel.js +2 -2
  224. package/neural-interface/public/shared/assistant/asst-state.js +72 -2
  225. package/neural-interface/public/shared/assistant/asst-styles.js +58 -14
  226. package/neural-interface/public/shared/automation-approval-view.js +75 -0
  227. package/neural-interface/public/shared/cdx/cdx-panel.js +2 -2
  228. package/neural-interface/public/shared/context-menu-model.js +2 -0
  229. package/neural-interface/public/shared/editor/editor-panel-logic.js +10 -0
  230. package/neural-interface/public/shared/editor/editor-panel.js +10 -2
  231. package/neural-interface/public/shared/html-shell.js +30 -22
  232. package/neural-interface/public/shared/morelogin-profile-choices.js +107 -0
  233. package/neural-interface/public/shared/morelogin-profile-field.js +186 -0
  234. package/neural-interface/public/shared/mtc/mtc-client.js +181 -0
  235. package/neural-interface/public/shared/mtc/mtc-compose.js +40 -0
  236. package/neural-interface/public/shared/mtc/mtc-copy.js +253 -0
  237. package/neural-interface/public/shared/mtc/mtc-logic.js +478 -0
  238. package/neural-interface/public/shared/mtc/mtc-panel.js +1354 -0
  239. package/neural-interface/public/shared/mtc/mtc-render.js +172 -0
  240. package/neural-interface/public/shared/mtc/mtc-styles.js +437 -0
  241. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +6 -2
  242. package/neural-interface/public/shared/provider-icons.js +3 -0
  243. package/neural-interface/public/shared/schedules-view.js +7 -0
  244. package/neural-interface/public/shared/server-back.js +50 -0
  245. package/neural-interface/public/shared/settings/settings-browser-owner-access.js +72 -0
  246. package/neural-interface/public/shared/settings/settings-data.js +1 -0
  247. package/neural-interface/public/shared/settings/settings-ia.js +3 -1
  248. package/neural-interface/public/shared/settings/settings-local-profiles.js +153 -0
  249. package/neural-interface/public/shared/settings/settings-maritaca-opencode.js +105 -0
  250. package/neural-interface/public/shared/sidepanel-session-status.js +16 -2
  251. package/neural-interface/public/shared/state.js +1 -1
  252. package/neural-interface/public/shared/styles.css +356 -157
  253. package/neural-interface/public/shared/synabun-mascot-assets.js +67 -0
  254. package/neural-interface/public/shared/synabun-mascot.js +136 -12
  255. package/neural-interface/public/shared/synabun-ticker.js +3 -0
  256. package/neural-interface/public/shared/topright-overflow-logic.js +1 -0
  257. package/neural-interface/public/shared/ui-automation-approval.js +188 -0
  258. package/neural-interface/public/shared/ui-automation-studio.js +130 -90
  259. package/neural-interface/public/shared/ui-claude-panel.js +50 -2
  260. package/neural-interface/public/shared/ui-maritaca-panel.js +15 -0
  261. package/neural-interface/public/shared/ui-navbar.js +17 -0
  262. package/neural-interface/public/shared/ui-panels.js +3 -1
  263. package/neural-interface/public/shared/ui-schedules-studio.js +118 -17
  264. package/neural-interface/public/shared/ui-scroll-follow.js +3 -0
  265. package/neural-interface/public/shared/ui-settings.js +590 -27
  266. package/neural-interface/public/shared/ui-sidepanel-session-entry.js +8 -2
  267. package/neural-interface/public/shared/ui-sidepanel-sessions.js +3 -3
  268. package/neural-interface/public/shared/ui-sidepanel-tray.js +24 -0
  269. package/neural-interface/public/shared/ui-sidepanel-windows.js +1 -1
  270. package/neural-interface/scripts/build-mascot-assets.mjs +30 -0
  271. package/neural-interface/server.js +1784 -195
  272. package/npm-shrinkwrap.json +5 -17
  273. package/package.json +5 -6
  274. package/postinstall.js +38 -39
  275. package/setup.js +33 -31
  276. package/skills/synabun/modules/changelog.md +14 -0
@@ -20,12 +20,13 @@ import { createCodexAccounts, applyCodexLaunchEnv, codexAppServerArgs, codexExec
20
20
  import { codexWindowsSandbox, codexWindowsSandboxArgs } from './lib/agent-sandbox-elevation.js';
21
21
  import { createAdminSandboxSetting } from './lib/agent-sandbox-setting.js';
22
22
  import { createWorkerGuardSetting } from './lib/worker-guard-setting.js';
23
+ import { createAutomationBrowserOwnerAccess } from './lib/automation-browser-owner-access.js';
23
24
  import { resolveWorkerConfinement } from './lib/worker-confinement.js';
24
25
  import { SANDBOX_EXEC, buildWorkerSandboxProfile, canonicalPath, sandboxExecArgv, sandboxExecAvailable, sandboxSupported, workerSandboxPlan, writeWorkerSandbox } from './lib/worker-sandbox.js';
25
26
  import { createWorkerMcpChannel } from './lib/worker-mcp-channel.js';
26
27
  import { createPageSession, PAGE_SECRET_PATHS, PAGE_SECRET_REFRESH_PATH, SERVICE_WORKER_PATH } from './lib/page-session.js';
27
28
  import { normalizeViewUrl } from './public/shared/view-variant.js';
28
- import { createPeerIdentity, debugClientPolicy } from './lib/peer-identity.js';
29
+ import { createPeerIdentity, debugClientPolicy, PEER_VERDICT, peerAuthority } from './lib/peer-identity.js';
29
30
  import { createOwnerAuthority, isAgentCall } from './lib/owner-authority.js';
30
31
  import { collectRelayListenerPorts, localProxyPorts } from './lib/worker-relay-ports.js';
31
32
  import { machineNames } from './lib/machine-names.js';
@@ -40,8 +41,12 @@ import { createBrowserStartHandoff, startWaitMs } from './lib/browser-start-hand
40
41
  import { browserRequestDeadline, browserV2Enabled, browserRequestMiddleware, assertBrowserRequestActive, browserActionTimeout, markBrowserActionStarted, runBrowserRequest, cancellableBrowserDelay, measureBrowserPhase, createEngagementScheduler, engagementTargetSelector, isEngagementWriteSelector, isXShortcutPublish, isXScriptedWrite } from './lib/browser-execution.js';
41
42
  import { sessionCloseDecision, profileStopDecision, otherSessionOwners } from './lib/browser-session-close.js';
42
43
  import { isAutomationBrowserRoute, ownerOnlyCreateFields } from './lib/browser-automation-routes.js';
44
+ import { withOnDeviceModelBlocked } from './lib/chromium-on-device-model.js';
43
45
  import { browserOwnerId, listedOwners } from './lib/browser-owner.js';
44
- import { createTerminalTokenRegistry, TERMINAL_TOKEN_ENV, TERMINAL_TOKEN_HEADER, BRAIN_CREDENTIAL_HEADER, redactTerminalSecrets } from './lib/terminal-tokens.js';
46
+ import { createProfileChoiceStore, resolveProfileRef } from './lib/browser-profile-choices.js';
47
+ import { scheduleReview, templateReview, sameDigest, scheduleMarked, templateMarked, clearScheduleMark, clearTemplateMark, markRecordsUnreviewed, REVIEW_CHANGED, UNREVIEWED_SOURCES } from './lib/automation-approval.js';
48
+ import { AGENT_PROFILES_KEY, PROFILE_NOT_ALLOWED, normalizeAgentProfiles, agentProfileAllowed, withAgentProfile, profileNotAllowedError, pinUseRefusal, scheduleProfileAuthority, scheduleProfileRefusalText, describeProfile, profileKindLabel } from './lib/morelogin-agent-profiles.js';
49
+ import { createTerminalTokenRegistry, TERMINAL_TOKEN_ENV, TERMINAL_TOKEN_HEADER, BRAIN_CREDENTIAL_HEADER, redactTerminalSecrets, logIdOf } from './lib/terminal-tokens.js';
45
50
  import { decideFailedTabRecovery } from './lib/browser-wedge-retire.js';
46
51
  import { createSocialWritePacer, socialPaceAccountKey, socialPaceRequest, socialPacingBlock, SOCIAL_PACE_LIMITS, SOCIAL_WRITE_GAPS } from './lib/social-write-pacing.js';
47
52
  import { describeLocatorMatches, healLocatorByText, validNthMatch, captureTargetIdentity, matchesTargetIdentity } from './lib/browser-targets.js';
@@ -56,7 +61,7 @@ import { runBrowserExtraction, readBrowserContentHtml } from './lib/browser-extr
56
61
  import { attachConsoleBuffer, readConsoleBuffer, parseConsoleSince } from './lib/browser-console.js';
57
62
  import { resolveBrowserLanguage, validateBrowserLanguageConfig } from './lib/browser-language.js';
58
63
  import { parseScreenshotOptions, captureScreenshot, screenshotPathRefusal, defaultScreenshotPath, writeScreenshotFile } from './lib/browser-screenshot.js';
59
- import { openBackgroundPage, selectedTabReading } from './lib/browser-background-tab.js';
64
+ import { openBackgroundPageStrict, backgroundTabsEnabled, newContextWithId, selectedTabReading } from './lib/browser-background-tab.js';
60
65
  import { memoryRevision } from '../mcp-server/dist/services/memory-maintenance.js';
61
66
  import { startGatedMemoryMaintenance } from './lib/memory-timers.js';
62
67
  import { createEventLoopMonitor } from './lib/event-loop-monitor.js';
@@ -81,8 +86,16 @@ import {
81
86
  BROWSER_RECOVERY_PROBE_DEADLINE_MS,
82
87
  BROWSER_RECOVERY_STEP_DEADLINE_MS,
83
88
  BrowserPageFailureDisposition,
89
+ NAVIGATE_DCL_CAP_MS,
90
+ PAGE_STILL_PARSING_NOTICE,
91
+ SLOW_NAVIGATION_NOTICE,
92
+ SNAPSHOT_DCL_WAIT_MS,
84
93
  classifyBrowserPageError,
85
94
  isIgnorablePlaywrightLifecycleError,
95
+ navigationLandedDespiteTimeout,
96
+ scheduleSlowLoadProbe,
97
+ trackMainDocumentCommit,
98
+ waitForDomContentLoadedCapped,
86
99
  withBrowserOperationDeadline,
87
100
  } from './lib/browser-tab-recovery.js';
88
101
 
@@ -139,7 +152,8 @@ import { bindOpenCodeChildSessionTools } from './public/shared/ocp-v2/ocp-v2-too
139
152
  import { startIndexing, getIndexingStatus, mirrorExistingChunks } from './lib/session-indexer.js';
140
153
  import * as mcpInstaller from './lib/mcp-installer.js';
141
154
  import * as pluginInstaller from './lib/plugin-installer.js';
142
- import { loopLog, loopLogPath, flushLoopLogs } from './lib/loop-logger.js';
155
+ // loopLog here is the wrapper below browserCaller (it never names a log file after a whole MCP session id).
156
+ import { loopLog as writeLoopLog, loopLogPath, flushLoopLogs } from './lib/loop-logger.js';
143
157
  import {
144
158
  buildInstallCommand,
145
159
  buildUpdateCommand,
@@ -238,7 +252,8 @@ import {
238
252
  mergeScheduleLaunchSnapshot,
239
253
  resolveScheduleRunPresentation,
240
254
  } from './lib/schedule-launch-intent.js';
241
- import * as moreLogin from './lib/morelogin.js';
255
+ // MoreLogin's profiles and SynaBun's own local profiles behind one face (lib/browser-profiles.js routes by profile id).
256
+ import * as moreLogin from './lib/browser-profiles.js';
242
257
  import { createStyleGuideStore } from './lib/style-guide/store.js';
243
258
  import { registerStyleGuideRoutes } from './lib/style-guide/api.js';
244
259
  import { initBlobStore, blobGetNamespace, blobGet, blobPut, blobDelete, blobClearNamespace, blobPrune, closeBlobStore } from './lib/ui-blob-store.js';
@@ -258,6 +273,13 @@ import { ANTIGRAVITY_PANEL_CAPABILITIES, ANTIGRAVITY_WS_PATH, createAntigravityP
258
273
  import { migrateGeminiFiles, migrateUiStateValues as migrateGeminiUiState } from './lib/antigravity/migrate-gemini.js';
259
274
  import { groupSessionsByProject, listAntigravityModels, listAntigravitySessions } from './lib/antigravity/catalog.js';
260
275
  import { defaultAntigravityPolicy } from './lib/antigravity/policy.js';
276
+ import { createMaritacaClient } from './lib/maritaca/client.js';
277
+ import { createMaritacaKeyStore } from './lib/maritaca/key-store.js';
278
+ import { createMaritacaSessionStore } from './lib/maritaca/sessions.js';
279
+ import { createMaritacaPanelBridge } from './lib/maritaca/panel-bridge.js';
280
+ import { registerMaritacaRoutes } from './lib/maritaca/api.js';
281
+ import { createMaritacaOpencodeSync } from './lib/maritaca/opencode.js';
282
+ import { createMaritacaOpencodeProxy, maritacaOpencodeProxyBaseUrl } from './lib/maritaca/opencode-proxy.js';
261
283
  import { antigravityHomeDir, antigravityHomesRoot, pruneAntigravityHomes } from './lib/antigravity/home.js';
262
284
  import { antigravityStores, findUserConversation, parseAntigravityTranscript, readTranscriptText } from './lib/antigravity/transcripts.js';
263
285
  import {
@@ -330,6 +352,7 @@ import { claudeBoolean } from './public/shared/skills/ss-profiles.js';
330
352
  import { generateSessionTitle } from './lib/session-title-generator.js';
331
353
  import {
332
354
  CLAUDE_EFFORT_LEVELS,
355
+ CLAUDE_EFFORT_OFF,
333
356
  CLAUDE_FALLBACK_MODELS,
334
357
  binaryIdentity,
335
358
  checkClaudeCliSkew,
@@ -379,7 +402,7 @@ import { prunePreUpdateSnapshots, resolvePreUpdateKeep } from '../lib/update-sna
379
402
  import { launcherRegistrationAllowed, registerStartLauncher, startLauncherState } from '../lib/start-launcher.js';
380
403
  import { effectiveNpmPrefix } from '../lib/child-path.js';
381
404
  import { checkRuntimeDependencies, fallbackInstallArgs, fallbackInstallEnv, findInstalled, mcpCompiler, npmCommand, npmInvocation } from '../lib/runtime-dependencies.js';
382
- import { mcpDistBuilt } from '../lib/mcp-dist.js';
405
+ import { buildMcpServerSafelyAsync, mcpBuildNeeded, mcpDistWhole } from '../lib/mcp-build.js';
383
406
  import { STOP_MARKER_NAME, STOP_TOKEN_ENV, stopAnnouncement, writeStopMarker } from '../lib/server-exit.js';
384
407
  import { redactDeep, redactSecrets } from '../lib/log-redact.js';
385
408
  import { applyPackagedChildPath, durableEntry, mcpStdioCommand, npmGlobalBinFor, packagedNpmPrefix, packagedPathFolders, packagedRuntime } from '../lib/packaged-runtime.js';
@@ -577,7 +600,9 @@ _peerIdentity.probe();
577
600
  // and the agents' feature data, the two reads that hand out a secret, and the owner's sockets are refused to the
578
601
  // automation browser (its marker or its process), relays, other SynaBun servers, remote logins and an agent's tree
579
602
  // that does not say it is an agent's call. Requests from outside keep the guest rules.
580
- const _ownerAuthority = createOwnerAuthority({ pageSession: () => _pageSession, isRemote: (req) => requestGates.isRemote(req), peer: _peerIdentity, log: (line) => console.warn(line) });
603
+ // The owner's setting "Let the automation browser act as owner" (lib/automation-browser-owner-access.js, made further
604
+ // down with the data home): while on, the automation browser is not refused here nor by the page secret.
605
+ const _ownerAuthority = createOwnerAuthority({ pageSession: () => _pageSession, isRemote: (req) => requestGates.isRemote(req), peer: _peerIdentity, log: (line) => console.warn(line), automationBrowserAllowed: () => _automationBrowserOwnerAccess.enabled() });
581
606
  app.use(_peerIdentity.middleware({ needs: peerLookupWanted }));
582
607
  app.use(_ownerAuthority.restGate);
583
608
 
@@ -990,7 +1015,7 @@ app.use(function uploadedLogoHeaders(req, res, next) {
990
1015
  // middleware that sets it. GET /api/page-session is how an open tab gets this boot's cookie after a restart
991
1016
  // (public/shared/page-session.js retries the refused write once with it).
992
1017
  // The page secret, asked of the peer lookup mounted in front of every route (_peerIdentity, above).
993
- const _pageSession = createPageSession({ port: Number(PORT), isGuest: isGuestRequest, peer: _peerIdentity });
1018
+ const _pageSession = createPageSession({ port: Number(PORT), isGuest: isGuestRequest, peer: _peerIdentity, automationBrowserAllowed: () => _automationBrowserOwnerAccess.enabled() });
994
1019
  /** Whether a request asks for the page secret (the app's pages, the refresh route, the Studio's owner reads, the
995
1020
  * service worker's script), is one of the owner's writes, or carries this boot's secret on an API request: only
996
1021
  * then is its peer looked up. */
@@ -1004,6 +1029,9 @@ function peerLookupWanted(req) {
1004
1029
  }
1005
1030
  // One of the owner's writes, or a read that hands out a secret (lib/owner-authority.js).
1006
1031
  if (_ownerAuthority.needsLookup(req)) return true;
1032
+ // A new session of the plain /mcp mount (an initialize: a POST with no Mcp-Session-Id): whether it may get a proof
1033
+ // of its own depends on what is at the other end (mcpSessionProofEligible: never a relay or a proxy).
1034
+ if (req.method === 'POST' && (path === '/mcp' || path === '/mcp/') && req.headers['mcp-session-id'] === undefined) return true;
1007
1035
  return path.startsWith('/api/') && _pageSession.carriesSecret(req);
1008
1036
  }
1009
1037
  app.use(_pageSession.serviceWorker); // GET /sw.js: a worker that takes itself away, for a browser refused the secret
@@ -2437,6 +2465,8 @@ async function runGracefulShutdown(reason) {
2437
2465
  try { stopAllIsolatedServes(); } catch (err) { console.warn(' isolated opencode stop err:', err?.message); }
2438
2466
  // The Antigravity panel's `agy acp` processes (one per open panel socket).
2439
2467
  try { await antigravityPanel.closeAll(); } catch (err) { console.warn(' antigravity panel stop err:', err?.message); }
2468
+ // The Maritaca panel's streaming turns (HTTP requests in flight).
2469
+ try { await maritacaPanel.closeAll(); } catch (err) { console.warn(' maritaca panel stop err:', err?.message); }
2440
2470
  // The code editor's completion serve, and today's autocomplete counters.
2441
2471
  try { await editorCompletion.stop(); } catch (err) { console.warn(' editor completion stop err:', err?.message); }
2442
2472
 
@@ -2541,13 +2571,24 @@ let _restartRequestedAt = 0;
2541
2571
  // The supervisor an unsupervised restart started for itself: ended when a later stop calls the restart off.
2542
2572
  let _restartRespawn = null;
2543
2573
  app.post('/api/server/restart', async (req, res) => {
2574
+ res.json(requestServerRestart());
2575
+ });
2576
+ // The body of the restart, after its route, so the restart reads as one piece between the two routes.
2577
+ /**
2578
+ * Restart this server: the one way for everything in-process (the route below; the MCP build of /api/setup/build and
2579
+ * of a restore, whose new dist the running server, with the old one in its module cache, cannot load). Answers at
2580
+ * once with what the pages read (`bootId`: "back" is a different one in /api/health), tells every window, then shuts
2581
+ * down: supervised (setup.js) with exit code 75, else with a detached setup.js of its own. A second call while a
2582
+ * restart is under way starts nothing more (`already`).
2583
+ */
2584
+ function requestServerRestart() {
2544
2585
  const supervised = process.env.SYNABUN_SUPERVISED === '1';
2545
2586
  if (_restartRequestedAt) {
2546
- return res.json({ ok: true, message: 'Server restarting...', supervised, bootId: SERVER_BOOT_ID, at: _restartRequestedAt, already: true });
2587
+ return { ok: true, message: 'Server restarting...', supervised, bootId: SERVER_BOOT_ID, at: _restartRequestedAt, already: true };
2547
2588
  }
2548
2589
  console.log('[server] Restart requested.');
2549
2590
  _restartRequestedAt = Date.now();
2550
- res.json({ ok: true, message: 'Server restarting...', supervised, bootId: SERVER_BOOT_ID, at: _restartRequestedAt });
2591
+ const answer = { ok: true, message: 'Server restarting...', supervised, bootId: SERVER_BOOT_ID, at: _restartRequestedAt };
2551
2592
  // Every open window is told before anything is torn down, so each one shows
2552
2593
  // the restart at once instead of finding its sockets closed (ui-loading.js).
2553
2594
  try { broadcastSync({ type: 'server:restarting', bootId: SERVER_BOOT_ID, supervised, at: _restartRequestedAt }); } catch {}
@@ -2590,7 +2631,8 @@ app.post('/api/server/restart', async (req, res) => {
2590
2631
  if (supervised && restart) _preserveExitCode = true; // supervisor needs RESTART_EXIT_CODE; skip SIGKILL
2591
2632
  process.exit(supervised && restart ? RESTART_EXIT_CODE : 0);
2592
2633
  }, 200);
2593
- });
2634
+ return answer;
2635
+ }
2594
2636
 
2595
2637
  // POST /api/server/shutdown — Graceful shutdown without restart. Used by
2596
2638
  // `npm uninstall synabun` (preuninstall.js) and the in-app updater.
@@ -4106,6 +4148,16 @@ const _workerGuard = createWorkerGuardSetting({
4106
4148
  });
4107
4149
  /** The `-c` words every Codex SynaBun starts gets for the setting (outside an account's launch plan). */
4108
4150
  function codexSandboxArgs() { return codexWindowsSandboxArgs(adminSandboxOn()); }
4151
+ // Let the automation browser act as owner (lib/automation-browser-owner-access.js): off by default; while on, the
4152
+ // page secret and the owner gate (made above, they read it on every request) treat SynaBun's automation browser as
4153
+ // the owner, so screenshot and visual-QA runs see the real UI. Settings → Browser → Automation browser access; the
4154
+ // owner's page only (PUT /api/assistant/automation-browser-owner-access), never the automation browser itself.
4155
+ const _automationBrowserOwnerAccess = createAutomationBrowserOwnerAccess({
4156
+ path: resolve(DATA_HOME, 'data', 'automation-browser-owner-access.json'),
4157
+ broadcast: (message) => broadcastSync(message),
4158
+ log: (tag, message) => console.warn(`[${tag}]`, message),
4159
+ });
4160
+ { const notice = _automationBrowserOwnerAccess.startupNotice(); if (notice) console.warn(notice); }
4109
4161
 
4110
4162
  // ── Worker OS isolation (macOS Seatbelt) ─────────────────────────────────────
4111
4163
  // A guarded Claude / OpenCode worker (Protect workers = Enforce) runs its whole process tree under sandbox-exec
@@ -4121,16 +4173,34 @@ let _workerMcpChannel = null;
4121
4173
  // Who a run is (lib/terminal-tokens.js): one token per run SynaBun starts (an agent, a terminal or exec loop, a native
4122
4174
  // run, a dispatched worker), minted with its terminal id, handed to that run's SynaBun MCP alone, revoked at its end.
4123
4175
  // The browser routes take a run's X-Synabun-Terminal only with that run's token (browserCaller). In memory only.
4124
- const _terminalTokens = createTerminalTokenRegistry({ log: (line) => console.warn(line) });
4176
+ const _terminalTokens = createTerminalTokenRegistry({
4177
+ log: (line) => console.warn(line),
4178
+ // An id's owner ended (a run, a closed MCP session): what it held as its MoreLogin profile goes with it, so a pin or
4179
+ // a saved choice never outlives its owner (review b6631e9d, finding 2). Declared further down; called at run time only.
4180
+ onEnded: (id) => { try { forgetRunMoreLoginProfile(id); } catch (err) { console.warn(`[morelogin] ${logOwnerId(id)}: its profile pin was not forgotten: ${err.message}`); } },
4181
+ });
4125
4182
  /** The launch beacon's loopback port (lib/start-launcher.js startBeaconPort): a SynaBun listener while a launch lives. */
4126
4183
  function workerBeaconPort() { const p = Number(PORT) || 3344; return p + 10000 <= 65535 ? p + 10000 : p - 10000; }
4127
4184
  /** Browser-control ports a guarded worker must not reach, by fixed knowledge (dynamic ones come from detection,
4128
4185
  * workerRelayPorts): MoreLogin's local API (a worker there starts another profile with its own CDP) and the CDP
4129
4186
  * port SynaBun's own attach mode uses. Denied even when nothing is listening at profile-generation time. */
4187
+ /** Every port kept for the local profiles' relays and DevTools ports (lib/local-profiles.js LOCAL_PROFILE_PORT_RANGE). */
4188
+ function workerLocalProfilePorts() {
4189
+ const range = moreLogin.localProfilePortRange();
4190
+ const ports = [];
4191
+ for (let p = range.from; p <= range.to; p += 1) ports.push(p);
4192
+ return ports;
4193
+ }
4130
4194
  function workerBrowserControlPorts() {
4131
4195
  const ports = new Set([...moreLogin.MORELOGIN_FIXED_API_PORTS]);
4132
4196
  try { const p = moreLogin.getMoreLoginPort(loadBrowserConfig()); if (p > 0) ports.add(p); } catch {}
4133
4197
  try { if (CDP_PORT > 0) ports.add(CDP_PORT); } catch {}
4198
+ // The ports kept for the local profiles (lib/local-profiles.js LOCAL_PROFILE_PORT_RANGE), all of them: every proxy
4199
+ // relay (a loopback proxy without a login, a way out through a profile's own proxy) and every DevTools port of a
4200
+ // local profile (full control of it) is allocated inside this range and nowhere else. Denied whole, as the
4201
+ // OpenCode range is, so a relay or a profile started AFTER this worker's profile was written is covered too.
4202
+ // (No try here: a range that could not be read must fail the profile's generation, never leave the range open.)
4203
+ for (const p of workerLocalProfilePorts()) ports.add(p);
4134
4204
  return [...ports];
4135
4205
  }
4136
4206
  /** SynaBun's MCP server over HTTP (mcp-server/dist/http.js reads MCP_HTTP_PORT from its environment or this data
@@ -9190,6 +9260,39 @@ const antigravityPanel = createAntigravityPanelBridge({
9190
9260
  log: (line) => console.log(line),
9191
9261
  });
9192
9262
 
9263
+ // ── Maritaca AI side panel (/ws/maritaca, /api/maritaca) ──
9264
+ // Maritaca's Sabiá models over their OpenAI-compatible HTTP API (lib/maritaca/*; docs/maritaca-sidepanel.md): a chat
9265
+ // provider with a panel of its own, never a worker or a brain. The key lives in DATA_HOME/data/maritaca/.synabun-api-key
9266
+ // (or MARITACA_API_KEY), the conversations in DATA_HOME/data/maritaca/sessions/.
9267
+ const maritacaKeyStore = createMaritacaKeyStore({ dir: resolve(DATA_HOME, 'data', 'maritaca') });
9268
+ const maritacaSessions = createMaritacaSessionStore({ dir: resolve(DATA_HOME, 'data', 'maritaca', 'sessions') });
9269
+ const maritacaClient = createMaritacaClient({ baseUrl: process.env.SYNABUN_MARITACA_BASE_URL || undefined });
9270
+ const maritacaPanel = createMaritacaPanelBridge({
9271
+ client: maritacaClient, keyStore: maritacaKeyStore, sessions: maritacaSessions,
9272
+ onHumanPrompt: ({ project, words }) => { try { _greeting?.noteActivity({ cwd: project || PACKAGE_ROOT, surface: 'maritaca-panel', words }); } catch {} },
9273
+ log: (line) => console.warn(line),
9274
+ });
9275
+ // OpenCode's requests for a Sabiá model come through this server (lib/maritaca/opencode-proxy.js): OpenCode 2 refuses
9276
+ // Maritaca's stream on a tool call ("received content after the finish reason"), and the route puts the stream in the
9277
+ // order OpenCode reads. It takes only a caller that presents the saved key, and sends the request on to the same API as
9278
+ // the panel's client.
9279
+ const maritacaOpencodeProxy = createMaritacaOpencodeProxy({ keyStore: maritacaKeyStore, upstreamBaseUrl: maritacaClient.baseUrl, log: (line) => console.log(line) });
9280
+ // Maritaca as an OpenCode provider (lib/maritaca/opencode.js; Settings → OpenCode → Providers): the provider block in
9281
+ // the global opencode.json, the key as a {file:…} / {env:…} reference OpenCode resolves itself, reloaded like the
9282
+ // Ollama card's, its base URL this server's route above. Everything it touches is handed in: it opens no file of its own.
9283
+ const maritacaOpencode = createMaritacaOpencodeSync({
9284
+ keyStore: maritacaKeyStore,
9285
+ baseUrl: () => maritacaOpencodeProxyBaseUrl(PORT),
9286
+ readConfig: () => readOpencodeConfigDocument(getOpencodeConfigPath()).config,
9287
+ updateConfig: (mutate) => updateOpencodeConfigFile(getOpencodeConfigDir(), mutate),
9288
+ configPath: () => getOpencodeConfigPath(),
9289
+ convertProviders: () => opencodeConvertedProviders(getOpencodeConfigPath()),
9290
+ reload: () => reloadSharedOpencodeConfig(),
9291
+ broadcast: () => broadcastToOpencodeV2Clients({ type: 'providers:changed' }),
9292
+ catalogChanged: () => refreshOpencodeProviderConsumers(),
9293
+ log: (line) => console.log(line),
9294
+ });
9295
+
9193
9296
  function handleOpencodeV2Ws(ws) {
9194
9297
  _ocpV2WsClients.add(ws);
9195
9298
  ws._nativeLoopWindowId = null;
@@ -9979,6 +10082,15 @@ async function reloadSharedOpencodeConfig() {
9979
10082
  }
9980
10083
  }
9981
10084
 
10085
+ // A provider block SynaBun wrote into opencode.json (Ollama, Maritaca) after reloadSharedOpencodeConfig: the kept
10086
+ // provider list is read from the serve again and the Assistant's catalog rebuilt from it, so agent_catalog and the
10087
+ // Routes editor list the new models at once. Neither notices by itself: the list's change hook compares answers under
10088
+ // one key and a written file is another key, and the catalog keeps a build for 30 s.
10089
+ async function refreshOpencodeProviderConsumers() {
10090
+ if (_ocpReady) { try { await readOpencodeProviders('compact', { refresh: true }); } catch { /* the catalog says why */ } }
10091
+ try { await _assistantCatalog?.refresh?.(); } catch { /* no Assistant */ }
10092
+ }
10093
+
9982
10094
  // ── Ollama local model endpoints ──
9983
10095
 
9984
10096
  const OLLAMA_BASE = 'http://localhost:11434';
@@ -10062,6 +10174,7 @@ app.post('/api/ollama/configure', async (req, res) => {
10062
10174
  console.log(`[ollama] Configured ${Object.keys(models).length} model(s) in ${configPath}`);
10063
10175
  await reloadSharedOpencodeConfig();
10064
10176
  broadcastToOpencodeV2Clients({ type: 'providers:changed' });
10177
+ refreshOpencodeProviderConsumers().catch(() => {});
10065
10178
 
10066
10179
  _ollamaUserRemoved = false;
10067
10180
  _ollamaManagedByUs = true;
@@ -10078,6 +10191,7 @@ app.delete('/api/ollama/configure', async (req, res) => {
10078
10191
  console.log('[ollama] Removed Ollama provider from config');
10079
10192
  await reloadSharedOpencodeConfig();
10080
10193
  broadcastToOpencodeV2Clients({ type: 'providers:changed' });
10194
+ refreshOpencodeProviderConsumers().catch(() => {});
10081
10195
  }
10082
10196
  _ollamaUserRemoved = true;
10083
10197
  res.json({ ok: true });
@@ -10451,6 +10565,8 @@ async function readOpencodeProviders(view = 'full', { refresh = false } = {}) {
10451
10565
  // Every window learns the list changed (an OpenCode panel's own socket says so only where one is open).
10452
10566
  function announceOpencodeProvidersChanged() {
10453
10567
  try { broadcastSync({ type: 'opencode:providers-changed' }); } catch {}
10568
+ // The Assistant's catalog is a copy of this list (opencode rows): it is rebuilt with it.
10569
+ try { _assistantCatalog?.refresh?.().catch(() => {}); } catch {}
10454
10570
  _announcingOpencodeProviders = true;
10455
10571
  try { broadcastToOpencodeV2Clients({ type: 'providers:changed' }); } finally { _announcingOpencodeProviders = false; }
10456
10572
  }
@@ -14077,6 +14193,8 @@ app.post('/api/loop/templates', (req, res) => {
14077
14193
  createdAt: new Date().toISOString(),
14078
14194
  updatedAt: new Date().toISOString(),
14079
14195
  };
14196
+ // Who wrote what a schedule with a MoreLogin profile would run (markTemplateAuthor; never read from the body).
14197
+ markTemplateAuthor(template, req);
14080
14198
  templates.push(template);
14081
14199
  writeLoopTemplates(templates);
14082
14200
  res.json(toolListRecord(template, toolListOptions()));
@@ -14171,6 +14289,8 @@ app.post('/api/loop/templates/import', (req, res) => {
14171
14289
  createdAt: t.createdAt || new Date().toISOString(),
14172
14290
  updatedAt: new Date().toISOString(),
14173
14291
  };
14292
+ // A file's entry is not the owner's reading of it: an agent's mark survives an export and import (markTemplateAuthor).
14293
+ markTemplateAuthor(template, req, { before: existingIdx >= 0 ? existing[existingIdx] : null, source: t });
14174
14294
  if (existingIdx >= 0) {
14175
14295
  template.id = existing[existingIdx].id; // keep original id
14176
14296
  existing[existingIdx] = template;
@@ -14214,10 +14334,45 @@ app.put('/api/loop/templates/:id', (req, res) => {
14214
14334
  if (platform !== undefined) templates[idx].platform = platform || null;
14215
14335
  if (folderId !== undefined) templates[idx].folderId = folderId || null;
14216
14336
  templates[idx].updatedAt = new Date().toISOString();
14337
+ // `before` is only "this is an edit": the mark goes when the body carries the instructions, never for a move (B2).
14338
+ markTemplateAuthor(templates[idx], req, { before: templates[idx] });
14217
14339
  writeLoopTemplates(templates);
14218
14340
  res.json(toolListRecord(templates[idx], toolListOptions()));
14219
14341
  });
14220
14342
 
14343
+ // Template review and approval (finding 3 of the re-review of 2026-11-11; the block above /api/schedules/:id/approve).
14344
+ function templateReviewContext(id) {
14345
+ const templates = readLoopTemplates();
14346
+ const idx = templates.findIndex((t) => t.id === id);
14347
+ if (idx === -1) return null;
14348
+ const cfg = loadBrowserConfig();
14349
+ const review = templateReview({ template: templates[idx], schedules: loadSchedules(), groups: loadScheduleGroups(), browserDefault: cfg, allowed: (envId) => agentProfileAllowed(cfg, envId), profileName: approvalProfileName(cfg) });
14350
+ return { templates, idx, template: templates[idx], review };
14351
+ }
14352
+ app.get('/api/loop/templates/:id/review', (req, res) => {
14353
+ if (!ownerPageApprovalCall(req)) return refuseApprovalCaller(req, res);
14354
+ const ctx = templateReviewContext(req.params.id);
14355
+ if (!ctx) return res.status(404).json({ ok: false, error: 'Template not found' });
14356
+ res.json({ ok: true, review: ctx.review });
14357
+ });
14358
+ app.post('/api/loop/templates/:id/approve', (req, res) => {
14359
+ if (!ownerPageApprovalCall(req)) return refuseApprovalCaller(req, res);
14360
+ const digest = req.body?.digest;
14361
+ if (typeof digest !== 'string' || !digest) return res.status(400).json({ ok: false, code: 'DIGEST_REQUIRED', error: 'digest is required: the one of the review you were shown (GET /api/loop/templates/:id/review).' });
14362
+ const ctx = templateReviewContext(req.params.id);
14363
+ if (!ctx) return res.status(404).json({ ok: false, error: 'Template not found' });
14364
+ if (!sameDigest(digest, ctx.review.digest)) {
14365
+ return res.status(409).json({ ok: false, code: REVIEW_CHANGED, review: ctx.review, error: 'This template\'s instructions changed after you opened the review (possibly by an agent). Nothing was approved: look at them again.' });
14366
+ }
14367
+ if (!ctx.review.needsApproval) return res.json({ ok: true, unchanged: true, template: ctx.template, review: ctx.review });
14368
+ clearTemplateMark(ctx.templates[ctx.idx]);
14369
+ ctx.templates[ctx.idx].updatedAt = new Date().toISOString();
14370
+ writeLoopTemplates(ctx.templates);
14371
+ console.log(`[loop] the owner approved template "${String(ctx.template.name || ctx.template.id).slice(0, 80)}"`);
14372
+ const fresh = templateReviewContext(req.params.id);
14373
+ res.json({ ok: true, template: fresh?.template || null, review: fresh?.review || null });
14374
+ });
14375
+
14221
14376
  // DELETE /api/loop/templates/:id — delete a template
14222
14377
  app.delete('/api/loop/templates/:id', (req, res) => {
14223
14378
  const templates = readLoopTemplates();
@@ -14590,9 +14745,15 @@ app.post('/api/loop/launch', async (req, res) => {
14590
14745
  let pendingNativeBrowserCleanup = null;
14591
14746
  // A terminal or exec loop's terminal token (lib/terminal-tokens.js), revoked when the launch fails before it runs.
14592
14747
  let issuedLoopTerminal = null;
14748
+ // The run this launch pinned to a MoreLogin profile, unpinned when the launch fails before it runs.
14749
+ let pinnedLoopTerminal = null;
14593
14750
  try {
14594
14751
  const { task: rawTask, context, iterations, maxMinutes, usesBrowser, cwd, profile, model: requestedModel, contextMode: requestedContextMode, effort, tools, platform, codexAccountId, browserSessionId: requestedBrowserSessionId, sidepanelWindowId, sidepanelClaimToken } = req.body;
14595
14752
  if (!rawTask?.trim()) return res.status(400).json({ error: 'task is required' });
14753
+ // Optional moreloginEnvId (+ moreloginEnvName): the MoreLogin profile this launch opens its browser in. Decided
14754
+ // here, before anything of the run exists: the owner's page may name any Chrome-type profile; any other caller
14755
+ // (this route is agent-open) only one on the owner's list that MoreLogin lists (requestedLaunchMoreLoginProfile).
14756
+ const launchMoreLogin = usesBrowser ? await requestedLaunchMoreLoginProfile(req) : null;
14596
14757
  // Resolve Facebook deal-link tokens against current fresh-release deals before the task is
14597
14758
  // stored, so the post links a real game page (/games/<slug>) — never the /deals listing.
14598
14759
  const { task, resolved: dealResolved, link: dealLink } = await resolveDealLink(rawTask);
@@ -14673,6 +14834,13 @@ app.post('/api/loop/launch', async (req, res) => {
14673
14834
  // A terminal or exec loop's token is minted with its id; a native run's by its runtime (NativeLoopRuntime.launch).
14674
14835
  const loopTerminalToken = nativeRuntime ? null : _terminalTokens.issue(terminalSessionId);
14675
14836
  if (loopTerminalToken) issuedLoopTerminal = terminalSessionId;
14837
+ // The launch's MoreLogin profile (decided above) becomes the run's pin, as a schedule's does. None: the default
14838
+ // browser of Settings → Browser, as before.
14839
+ if (launchMoreLogin) {
14840
+ pinRunMoreLoginProfile(terminalSessionId, launchMoreLogin.moreloginEnvId, launchMoreLogin.moreloginEnvName, launchMoreLogin.moreloginEnvBy);
14841
+ pinnedLoopTerminal = terminalSessionId;
14842
+ loopLog(terminalSessionId, 'launch:browser', `this launch runs in ${describeMoreLoginPin(runMoreLoginPin(terminalSessionId))}`);
14843
+ }
14676
14844
  if (usesBrowser) {
14677
14845
  // Serialized reuse-or-create of the shared loop browser + a dedicated tab.
14678
14846
  // The mutex inside acquireLoopBrowserAndTab() prevents concurrent launches
@@ -14680,7 +14848,8 @@ app.post('/api/loop/launch', async (req, res) => {
14680
14848
  const acq = await acquireLoopBrowserAndTab({ requestedBrowserSessionId, terminalSessionId });
14681
14849
  if (acq.error) {
14682
14850
  loopLog(terminalSessionId, 'launch:browser', 'ABORT: browser acquisition failed — returning 500', { error: acq.error });
14683
- return res.status(500).json({ error: acq.error, ...(acq.code ? { code: acq.code, offenders: acq.offenders } : {}) });
14851
+ forgetRunMoreLoginProfile(terminalSessionId);
14852
+ return res.status(acq.code === PROFILE_NOT_ALLOWED ? 403 : 500).json({ error: acq.error, ...(acq.code ? { code: acq.code, offenders: acq.offenders } : {}) });
14684
14853
  }
14685
14854
  browserSessionId = acq.browserSessionId;
14686
14855
  browserTabId = acq.browserTabId;
@@ -14726,6 +14895,8 @@ app.post('/api/loop/launch', async (req, res) => {
14726
14895
  surface: nativeRuntime ? 'sidepanel' : 'terminal',
14727
14896
  runId: nativeRuntime ? terminalSessionId : null,
14728
14897
  cwd: loopCwd,
14898
+ // The run's pinned MoreLogin profile (runMoreLoginPin reads it back when the in-memory pin is gone).
14899
+ ...(launchMoreLogin || {}),
14729
14900
  };
14730
14901
  writeFileSync(resolve(LOOP_DIR, `${pendingId}.json`), JSON.stringify(loopState, null, 2));
14731
14902
  loopLog(terminalSessionId, 'launch:state', 'wrote pending loop file', { pendingId, loopFile: `${pendingId}.json`, loopState });
@@ -14856,6 +15027,7 @@ app.post('/api/loop/launch', async (req, res) => {
14856
15027
  // loop-stop cleanup owns it from this point onward (its terminal token too: endAutomationBrowser revokes it).
14857
15028
  pendingNativeBrowserCleanup = null;
14858
15029
  issuedLoopTerminal = null;
15030
+ pinnedLoopTerminal = null;
14859
15031
  broadcastSync({ type: 'terminal:session-created', sessionId: terminalSessionId, profile: cliProfile });
14860
15032
 
14861
15033
  const responsePayload = {
@@ -14881,6 +15053,7 @@ app.post('/api/loop/launch', async (req, res) => {
14881
15053
  }
14882
15054
  // The loop never ran: nothing may act as it.
14883
15055
  if (issuedLoopTerminal) _terminalTokens.revoke(issuedLoopTerminal);
15056
+ if (pinnedLoopTerminal) forgetRunMoreLoginProfile(pinnedLoopTerminal);
14884
15057
  loopLog(null, 'launch:error', 'POST /api/loop/launch threw', { err: err.message, stack: err.stack?.slice(0, 800) });
14885
15058
  res.status(err.status || 500).json({ error: err.message, ...(err.code ? { code: err.code, problems: err.problems } : {}) });
14886
15059
  }
@@ -15062,6 +15235,10 @@ app.post('/api/loop/recover-browser', async (req, res) => {
15062
15235
  if (named && caller !== named) {
15063
15236
  return res.status(403).json({ error: `This caller (${caller}) may not take over the browser of run ${named}.`, code: 'TERMINAL_MISMATCH' });
15064
15237
  }
15238
+ // The caller's MoreLogin profile pin (this route is not under /api/browser, so browserTerminalGate does not ask):
15239
+ // never for an id this request did not prove, never in a profile off the owner's list (callerProfileRefusal).
15240
+ const pinRefused = callerProfileRefusal(who);
15241
+ if (pinRefused) return res.status(pinRefused.status).json({ ok: false, code: pinRefused.code, error: pinRefused.error });
15065
15242
  const owner = named || caller;
15066
15243
  if (named && automationRunState(named, { files: true }) === 'ended') {
15067
15244
  return res.status(409).json({ error: `Run ${named} has ended: its browser is not reopened.`, code: 'RUN_ENDED' });
@@ -15072,7 +15249,7 @@ app.post('/api/loop/recover-browser', async (req, res) => {
15072
15249
  const tabId = browserOwnerId(adopt.tabId);
15073
15250
  const cfg = loadBrowserConfig();
15074
15251
  const owned = !!named && !!sessionId && !!tabId && startedTabAlive(sessionId, tabId, named)
15075
- && (cfg.connectMode !== 'morelogin' || sessionServesMoreLoginDefault(browserSessions.get(sessionId), cfg));
15252
+ && sessionServesRun(browserSessions.get(sessionId), cfg, named);
15076
15253
  if (!owned) return res.status(409).json({ error: `That tab is not an open tab of run ${named || caller} in the default browser.`, code: 'NOT_OWNED' });
15077
15254
  noteAutomationBrowserRoute(named, { browserSessionId: sessionId, browserTabId: tabId }, 'adopted');
15078
15255
  return res.json({ ok: true, sessionId, tabId, adopted: true });
@@ -15341,6 +15518,227 @@ function applyScheduleLaunchOverrides(schedule, source) {
15341
15518
  delete schedule.mcpProfile;
15342
15519
  }
15343
15520
 
15521
+ // A schedule's or a schedule group's own MoreLogin profile (optional). Empty / null clears it: the run then opens the
15522
+ // default browser of Settings → Browser, as every record without the field does. The name is kept for display only.
15523
+ // At launch a schedule's own profile wins, then its group's (scheduleMoreLoginProfile); nothing is copied from a group
15524
+ // onto its schedules.
15525
+ function applyScheduleMoreLoginProfile(schedule, source) {
15526
+ if (!source || source.moreloginEnvId === undefined) return;
15527
+ const id = source.moreloginEnvId === null ? '' : String(source.moreloginEnvId).trim();
15528
+ if (!id) {
15529
+ delete schedule.moreloginEnvId;
15530
+ delete schedule.moreloginEnvName;
15531
+ return;
15532
+ }
15533
+ if (id.length > 128 || /[\u0000-\u001f]/.test(id)) {
15534
+ throw Object.assign(new Error('moreloginEnvId is not a MoreLogin profile id'), { status: 400 });
15535
+ }
15536
+ schedule.moreloginEnvId = id;
15537
+ const name = typeof source.moreloginEnvName === 'string' ? source.moreloginEnvName.trim().slice(0, 200) : '';
15538
+ if (name) schedule.moreloginEnvName = name;
15539
+ else if (source.moreloginEnvName !== undefined) delete schedule.moreloginEnvName;
15540
+ }
15541
+
15542
+ /** The MoreLogin profile a request names for one launch (a quick timer, a manual launch): both fields, or neither. */
15543
+ function requestedMoreLoginProfile(source) {
15544
+ const choice = {};
15545
+ applyScheduleMoreLoginProfile(choice, source || {});
15546
+ return choice.moreloginEnvId ? { moreloginEnvId: choice.moreloginEnvId, moreloginEnvName: choice.moreloginEnvName || null } : null;
15547
+ }
15548
+
15549
+ /** The MoreLogin profile a schedule's run opens: its own, else its group's, else none (the default browser). */
15550
+ function scheduleMoreLoginProfile(schedule, group = null) {
15551
+ const owner = schedule?.moreloginEnvId ? schedule : (group?.moreloginEnvId ? group : null);
15552
+ return owner ? { envId: String(owner.moreloginEnvId), name: owner.moreloginEnvName || null, source: owner === schedule ? 'schedule' : 'group', holder: owner } : null;
15553
+ }
15554
+
15555
+ // ── Who chose a profile on the launch and record routes (review b6631e9d, finding 4) ──
15556
+ // /api/loop, /api/schedules and /api/schedule-groups are agent-open (lib/owner-authority.js AGENT_OPEN_PREFIXES: the
15557
+ // /synabun skill creates loops and schedules with curl), and /api/quick-timer and /api/agents/launch let an agent's
15558
+ // process tree through as soon as it sends any agent header (ownerRefusal: `agentOpen || isAgentCall(req)`); where the
15559
+ // peer lookup does not run (not macOS, or off) every local caller reaches all of them. All took `moreloginEnvId` from
15560
+ // the body, checked for its shape only: an agent launched a run of its own task in any profile, any account.
15561
+ // Now the body's profile counts as the owner's choice only when the request is the owner's page (browserOwnerPageOnly:
15562
+ // this boot's page secret, never a guest, never the automation browser). From anybody else it must be on the owner's
15563
+ // list AND a profile MoreLogin lists, and it is recorded as an agent's (`moreloginEnvBy: 'agent'`), so the list is
15564
+ // asked again when the run starts and at every browser call. The marker is written here only, never read from a body.
15565
+
15566
+ /** Whether a request's profile choice is the owner's own (SynaBun's page). */
15567
+ function profileChosenByOwner(req) { return browserOwnerPageOnly(req); }
15568
+
15569
+ /**
15570
+ * A profile an agent names, as it may be used: on the owner's list (checked first, so a refusal needs no MoreLogin
15571
+ * and tells nothing about its profiles), then among MoreLogin's listed Chrome-type profiles. → { envId, name }.
15572
+ * Throws 403 MORELOGIN_PROFILE_NOT_ALLOWED, or the resolver's own refusal (404 ENV_NOT_FOUND, 400 MORELOGIN_NOT_CHROMIUM…).
15573
+ */
15574
+ async function agentMoreLoginProfileChoice(ref) {
15575
+ const id = ref?.envId === undefined || ref?.envId === null ? '' : String(ref.envId).trim();
15576
+ if (id && !moreLoginProfileAllowed(id)) throw profileNotAllowedError(id, typeof ref?.name === 'string' ? ref.name : null);
15577
+ const found = await resolveMoreLoginProfileChoice(ref);
15578
+ // Named by its name: the id is known only now.
15579
+ if (!moreLoginProfileAllowed(found.envId)) throw profileNotAllowedError(found.envId, found.name);
15580
+ return found;
15581
+ }
15582
+
15583
+ /**
15584
+ * The MoreLogin profile one launch request names (POST /api/loop/launch, /api/quick-timer, /api/quick-timer/now,
15585
+ * /api/agents/launch), with who chose it: { moreloginEnvId, moreloginEnvName, moreloginEnvBy } or null (none named).
15586
+ */
15587
+ async function requestedLaunchMoreLoginProfile(req) {
15588
+ const choice = requestedMoreLoginProfile(req.body);
15589
+ if (!choice) return null;
15590
+ if (profileChosenByOwner(req)) {
15591
+ await refuseFirefoxMoreLoginChoice(req.body); // never a Firefox-type profile: the run would only fail
15592
+ return { ...choice, moreloginEnvBy: 'owner' };
15593
+ }
15594
+ const found = await agentMoreLoginProfileChoice({ envId: choice.moreloginEnvId });
15595
+ return { moreloginEnvId: found.envId, moreloginEnvName: found.name || choice.moreloginEnvName || null, moreloginEnvBy: 'agent' };
15596
+ }
15597
+
15598
+ /**
15599
+ * What a save of a schedule or a group does to the record's MoreLogin profile, decided before the store is read (it
15600
+ * may wait for MoreLogin; nothing waits between the store's read and its write). `saved`: the record as it is now
15601
+ * (null for a new one). → { op: 'keep' } (the body names none), { op: 'clear' }, { op: 'same', envId } (an agent sent
15602
+ * back the profile the record holds: nothing changes, not even who chose it) or { op: 'set', envId, name, by }.
15603
+ * An agent may clear a profile (the run then opens the default browser, which every agent has) and may set one only
15604
+ * from the owner's list; it can never move a record to a profile off the list, whoever set the one it holds.
15605
+ */
15606
+ async function prepareRecordMoreLoginProfile(req, saved = null) {
15607
+ const body = req.body || {};
15608
+ if (body.moreloginEnvId === undefined) return { op: 'keep' };
15609
+ const choice = requestedMoreLoginProfile(body); // throws 400 for a malformed id
15610
+ if (!choice) return { op: 'clear' };
15611
+ if (profileChosenByOwner(req)) {
15612
+ // The profile the record already holds may be saved back by the owner (a Firefox one from before that rule too).
15613
+ await refuseFirefoxMoreLoginChoice(body, saved?.moreloginEnvId ?? null);
15614
+ return { op: 'set', envId: choice.moreloginEnvId, name: choice.moreloginEnvName, by: 'owner' };
15615
+ }
15616
+ if (saved?.moreloginEnvId && String(saved.moreloginEnvId) === choice.moreloginEnvId) return { op: 'same', envId: choice.moreloginEnvId };
15617
+ const found = await agentMoreLoginProfileChoice({ envId: choice.moreloginEnvId });
15618
+ return { op: 'set', envId: found.envId, name: found.name || choice.moreloginEnvName || null, by: 'agent' };
15619
+ }
15620
+
15621
+ /** Applies prepareRecordMoreLoginProfile's decision to the record read from the store (synchronous). */
15622
+ function applyPreparedMoreLoginProfile(record, prepared) {
15623
+ if (!prepared || prepared.op === 'keep') return;
15624
+ if (prepared.op === 'same') {
15625
+ // The record changed between the decision and this write: the decision was about another profile.
15626
+ if (String(record.moreloginEnvId || '') !== prepared.envId) throw Object.assign(new Error('This record\'s MoreLogin profile changed while it was being saved. Save again.'), { status: 409, code: 'PROFILE_CHANGED' });
15627
+ return;
15628
+ }
15629
+ if (prepared.op === 'clear') {
15630
+ delete record.moreloginEnvId; delete record.moreloginEnvName; delete record.moreloginEnvBy;
15631
+ return;
15632
+ }
15633
+ record.moreloginEnvId = prepared.envId;
15634
+ if (prepared.name) record.moreloginEnvName = prepared.name; else delete record.moreloginEnvName;
15635
+ record.moreloginEnvBy = prepared.by;
15636
+ }
15637
+
15638
+ /** The fields of a schedule that decide WHAT runs in its profile (scheduleProfileAuthority reads `taskBy`). */
15639
+ const SCHEDULE_TASK_FIELDS = Object.freeze(['templateId', 'overrides', 'dayThemes', 'groupId']);
15640
+ // ── Who decided what a schedule or template runs, and when a mark goes away (re-review of 2026-11-11, finding 3) ──
15641
+ // The marks (`taskBy` on a schedule, `editedBy` on a template) say "an agent decided what this runs, the owner has
15642
+ // not approved it"; a marked record is held to the owner's list (scheduleProfileAuthority).
15643
+ // History: until 2026-11-10 any save from the owner's page deleted them (B2 of that day's re-review: a drag into a
15644
+ // folder or a group, the switch, a reset). That fix let a save that carried the "confirming" fields take the mark
15645
+ // away, and the Schedules editor then sent those fields by itself for a marked schedule, so renaming one cleared the
15646
+ // mark although the owner reviewed nothing (finding 3 of the re-review of 2026-11-11).
15647
+ // Now: NO save takes a mark away, whatever fields it carries and whoever sends it. The one way is the approve action
15648
+ // (POST /api/schedules/:id/approve, POST /api/loop/templates/:id/approve: the owner's page only, tied to the digest of
15649
+ // the content the owner was shown; lib/automation-approval.js). A record the owner's page creates starts without one.
15650
+ /**
15651
+ * Marks a schedule an agent created or whose task fields (SCHEDULE_TASK_FIELDS) an agent changed `taskBy: 'agent'`.
15652
+ * The owner's page creating a schedule leaves it unmarked; an owner's edit never touches the mark.
15653
+ * `before`: the record's task fields as they were (null for a new schedule).
15654
+ */
15655
+ function markScheduleTaskAuthor(schedule, req, before = null) {
15656
+ const body = req.body || {};
15657
+ if (profileChosenByOwner(req)) {
15658
+ // A new record is all the owner's request. Never a delete on an edit (finding 3).
15659
+ if (!before) { delete schedule.taskBy; delete schedule.unreviewedFrom; }
15660
+ return;
15661
+ }
15662
+ const changed = !before || SCHEDULE_TASK_FIELDS.some((field) => body[field] !== undefined && JSON.stringify(schedule[field] ?? null) !== JSON.stringify(before[field] ?? null));
15663
+ if (changed) { schedule.taskBy = 'agent'; delete schedule.unreviewedFrom; }
15664
+ }
15665
+ /** The fields of a template that are its instructions (an import that brings other ones marks it). */
15666
+ const TEMPLATE_INSTRUCTION_FIELDS = Object.freeze(['task', 'context']);
15667
+ /**
15668
+ * The same for a loop template. An agent that creates, changes or imports one marks it `editedBy: 'agent'`.
15669
+ * • the owner's page creating one (`before` null, no `source`): unmarked, the whole template is the owner's request;
15670
+ * • the owner's edit: the mark stays as it is (finding 3: only the approve action takes it away);
15671
+ * • the owner's import (`source`: the file's entry): instructions a file brings are unreviewed. A new template, or
15672
+ * one whose task or context differ from what is stored, comes in marked (`unreviewedFrom: 'import'`), and so does
15673
+ * an entry the file marks. Only an entry that puts back, word for word, the instructions of a stored template keeps
15674
+ * that template's state (marked stays marked, unmarked stays unmarked). Nothing in a file takes a mark away.
15675
+ */
15676
+ function markTemplateAuthor(template, req, { before = null, source = null } = {}) {
15677
+ if (!profileChosenByOwner(req)) { template.editedBy = 'agent'; delete template.unreviewedFrom; return; }
15678
+ if (source) {
15679
+ const sameInstructions = !!before && TEMPLATE_INSTRUCTION_FIELDS.every((field) => (template[field] ?? null) === (before[field] ?? null));
15680
+ if (source.editedBy === 'agent') { template.editedBy = 'agent'; delete template.unreviewedFrom; }
15681
+ else if (sameInstructions) {
15682
+ // The stored instructions, word for word: the stored template's state, unchanged.
15683
+ if (before.editedBy === 'agent') { template.editedBy = 'agent'; if (before.unreviewedFrom) template.unreviewedFrom = before.unreviewedFrom; else delete template.unreviewedFrom; }
15684
+ else { delete template.editedBy; delete template.unreviewedFrom; }
15685
+ } else { template.editedBy = 'agent'; template.unreviewedFrom = 'import'; }
15686
+ return;
15687
+ }
15688
+ if (!before) { delete template.editedBy; delete template.unreviewedFrom; }
15689
+ }
15690
+
15691
+ // How long a save or a launch waits to learn which browser a newly chosen MoreLogin profile runs. Past it the
15692
+ // profile's browser is unknown, which is accepted (the start of the run still refuses a Firefox one).
15693
+ const MORELOGIN_CHOICE_LOOKUP_MS = 4000;
15694
+
15695
+ /**
15696
+ * Refuses a newly chosen MoreLogin profile that is known to run MoreLogin's Firefox browser: SynaBun drives a profile
15697
+ * over the Chrome DevTools protocol, so a schedule, a group, a timer, a launch or the Browser default set to one
15698
+ * could only fail when it runs. Throws status 400, code MORELOGIN_NOT_CHROMIUM. A browser MoreLogin does not say (the
15699
+ * app closed, an older MoreLogin, no answer in time) is accepted.
15700
+ * `saved`: the profile the record already holds. Sending it back unchanged is no new choice, so a record saved before
15701
+ * this rule can still be edited and saved (its editor shows the warning); choosing a Firefox profile anew is refused.
15702
+ * Awaited before a route reads the store it then writes, never between the read and the write.
15703
+ */
15704
+ async function refuseFirefoxMoreLoginChoice(source, saved = null) {
15705
+ if (!source || source.moreloginEnvId === undefined || source.moreloginEnvId === null) return;
15706
+ const id = String(source.moreloginEnvId).trim();
15707
+ if (!id || id.length > 128 || /[\u0000-\u001f]/.test(id)) return; // empty clears; a malformed id is refused where it is read
15708
+ if (saved !== null && saved !== undefined && String(saved) === id) return;
15709
+ let timer = null;
15710
+ let kernel = null;
15711
+ try {
15712
+ kernel = await Promise.race([
15713
+ moreLogin.lookupProfileKernel(id, { ..._moreLoginOpts(), timeout: MORELOGIN_CHOICE_LOOKUP_MS }),
15714
+ new Promise((done) => { timer = setTimeout(() => done(null), MORELOGIN_CHOICE_LOOKUP_MS); timer.unref?.(); }),
15715
+ ]);
15716
+ } catch { kernel = null; }
15717
+ finally { clearTimeout(timer); }
15718
+ if (kernel === 'firefox') {
15719
+ const name = typeof source.moreloginEnvName === 'string' ? source.moreloginEnvName.trim().slice(0, 200) : '';
15720
+ throw moreLogin.notChromiumChoiceError(id, name || null);
15721
+ }
15722
+ }
15723
+
15724
+ /**
15725
+ * MoreLogin's listed profiles, each with the browser it runs: `browser` is 'chromium', 'firefox' or null (not known,
15726
+ * or not known yet). A Firefox-type profile cannot be driven by SynaBun; the pickers show it and do not offer it.
15727
+ * Never the list's failure: whatever goes wrong here leaves every profile listed with `browser: null`.
15728
+ * → { envs, browsersPending } (the count still being asked; a later call has them).
15729
+ */
15730
+ async function withMoreLoginBrowsers(envs, opts = {}) {
15731
+ const rows = Array.isArray(envs) ? envs : [];
15732
+ let kernels = {};
15733
+ let pending = 0;
15734
+ try {
15735
+ const answer = await moreLogin.profileKernels(rows.map((env) => env.id), { ...opts, timeout: 10000 });
15736
+ kernels = answer?.kernels || {};
15737
+ pending = Number(answer?.pending) || 0;
15738
+ } catch { kernels = {}; pending = 0; }
15739
+ return { envs: rows.map((env) => ({ ...env, browser: kernels[String(env.id)] || null })), browsersPending: pending };
15740
+ }
15741
+
15344
15742
  function boundedScheduleNumber(value, fallback, min, max) {
15345
15743
  const n = Number(value);
15346
15744
  const resolved = Number.isFinite(n) ? n : fallback;
@@ -15647,6 +16045,26 @@ async function launchScheduledLoop(schedule) {
15647
16045
  schedExtraEnv.OPENCODE_EXPERIMENTAL_BASH_DEFAULT_TIMEOUT_MS =
15648
16046
  process.env.OPENCODE_EXPERIMENTAL_BASH_DEFAULT_TIMEOUT_MS || '300000';
15649
16047
  }
16048
+ // The schedule's own MoreLogin profile, when it has one: the run is pinned to it before its browser is acquired,
16049
+ // so the acquisition, every later recovery and the browser tools' gate all land in that profile and no other.
16050
+ // A schedule without one takes its group's (a quick timer is a schedule of its own here, with the timer's profile).
16051
+ const scheduledMoreLogin = scheduledUsesBrowser ? scheduleMoreLoginProfile(schedule, group) : null;
16052
+ const scheduledMoreLoginEnvId = scheduledMoreLogin?.envId || null;
16053
+ // Whose choice that profile is (lib/morelogin-agent-profiles.js scheduleProfileAuthority): the owner's only when
16054
+ // the owner's page chose it on the schedule or the group AND no agent decided since what runs there (the
16055
+ // schedule's task fields, its template). Anything else is an agent's and needs the profile on the owner's list,
16056
+ // now and at every browser call of the run (the pin carries `by`). A refusal fails this launch by name; the run
16057
+ // is not started in the default profile or in Chrome.
16058
+ const scheduledMoreLoginAuthority = scheduledMoreLoginEnvId
16059
+ ? scheduleProfileAuthority({ schedule: schedule._quickTimer ? null : schedule, holder: scheduledMoreLogin.holder, template, source: schedule._quickTimer ? 'timer' : scheduledMoreLogin.source })
16060
+ : null;
16061
+ if (scheduledMoreLoginEnvId && scheduledMoreLoginAuthority.by !== 'owner' && !moreLoginProfileAllowed(scheduledMoreLoginEnvId)) {
16062
+ throw Object.assign(new Error(scheduleProfileRefusalText(scheduledMoreLoginEnvId, scheduledMoreLogin.name, scheduledMoreLoginAuthority)), { code: PROFILE_NOT_ALLOWED });
16063
+ }
16064
+ if (scheduledMoreLoginEnvId) {
16065
+ pinRunMoreLoginProfile(terminalSessionId, scheduledMoreLoginEnvId, scheduledMoreLogin.name, scheduledMoreLoginAuthority.by);
16066
+ console.log(`[schedule] "${schedule.name}" runs in ${describeMoreLoginPin(runMoreLoginPin(terminalSessionId))}${scheduledMoreLogin.source === 'group' ? ' (its group\'s profile)' : ''}`);
16067
+ }
15650
16068
  if (scheduledUsesBrowser) {
15651
16069
  // Same serialized shared-browser + dedicated-tab acquisition as manual loops.
15652
16070
  const acq = await acquireLoopBrowserAndTab({ terminalSessionId, logTag: 'schedule:browser' });
@@ -15821,6 +16239,9 @@ async function launchScheduledLoop(schedule) {
15821
16239
  runId: nativeRuntime ? terminalSessionId : null,
15822
16240
  cwd: PACKAGE_ROOT,
15823
16241
  scheduledBy: schedule.id,
16242
+ // The run's pinned MoreLogin profile (runMoreLoginPin reads it back when the in-memory pin is gone).
16243
+ // `moreloginEnvBy`: whose choice it was at launch ('owner' is not held to the owner's list at use).
16244
+ ...(scheduledMoreLoginEnvId ? { moreloginEnvId: scheduledMoreLoginEnvId, moreloginEnvName: scheduledMoreLogin.name, moreloginEnvBy: scheduledMoreLoginAuthority.by } : {}),
15824
16245
  };
15825
16246
  writeFileSync(resolve(LOOP_DIR, `${pendingId}.json`), JSON.stringify(loopState, null, 2));
15826
16247
 
@@ -15914,6 +16335,7 @@ async function launchScheduledLoop(schedule) {
15914
16335
  } catch (err) {
15915
16336
  if (registeredScheduledRunId) _runningScheduledLoops.delete(registeredScheduledRunId);
15916
16337
  // The loop never ran: nothing may act as it.
16338
+ if (scheduledLaunchTerminalId) forgetRunMoreLoginProfile(scheduledLaunchTerminalId);
15917
16339
  if (issuedSchedTerminal) _terminalTokens.revoke(issuedSchedTerminal);
15918
16340
  if (scheduledLaunchTerminalId) {
15919
16341
  const terminal = terminalSessions.get(scheduledLaunchTerminalId);
@@ -16450,6 +16872,9 @@ function launchQuickTimer(timerId, templateId, context) {
16450
16872
  platform: timerData.platform,
16451
16873
  codexAccountId: timerData.codexAccountId || undefined,
16452
16874
  usesBrowser: timerData.usesBrowser,
16875
+ // The timer's own MoreLogin profile (none: the default browser), pinned by the schedule fire path.
16876
+ // `moreloginEnvBy`: who chose it when the timer was set (the owner's page, or an agent held to the owner's list).
16877
+ ...(timerData.moreloginEnvId ? { moreloginEnvId: timerData.moreloginEnvId, moreloginEnvName: timerData.moreloginEnvName || null, moreloginEnvBy: timerData.moreloginEnvBy === 'owner' ? 'owner' : 'agent' } : {}),
16453
16878
  // Synthetic schedule (not persisted) — must bypass the queue's stillDue and
16454
16879
  // disabled/deleted guards, both of which key off persisted schedule state.
16455
16880
  _forced: true,
@@ -16488,16 +16913,20 @@ app.post('/api/quick-timer', async (req, res) => {
16488
16913
  try { await resolveAutomationLaunchChoice(timerProfile, timerModel, timerContextMode, timerCodexAccount?.home); }
16489
16914
  catch (error) { return res.status(400).json({ error: error.message }); }
16490
16915
  const timerUsesBrowser = usesBrowser !== undefined ? !!usesBrowser : !!template.usesBrowser;
16916
+ // Optional: the MoreLogin profile this one run opens its browser in (moreloginEnvId + moreloginEnvName, as a
16917
+ // schedule's). The owner's page: any Chrome-type profile. Anybody else (an agent's tree reaches this route with any
16918
+ // agent header): only a profile on the owner's list, asked again when the timer fires (launchScheduledLoop).
16919
+ const timerMoreLogin = timerUsesBrowser ? await requestedLaunchMoreLoginProfile(req) : null;
16491
16920
 
16492
16921
  const timeoutId = setTimeout(() => {
16493
16922
  launchQuickTimer(timerId, templateId, context);
16494
16923
  _quickTimers.delete(timerId);
16495
16924
  }, mins * 60_000);
16496
16925
 
16497
- _quickTimers.set(timerId, { timeoutId, templateId, templateName: template.name, firesAt, minutes: mins, profile: timerProfile, model: timerModel, contextMode: timerContextMode, effort: timerEffort, tools: timerTools, platform: automationPlatform({ platform }, null, template), codexAccountId: timerCodexAccountId, usesBrowser: timerUsesBrowser, createdAt: new Date().toISOString() });
16926
+ _quickTimers.set(timerId, { timeoutId, templateId, templateName: template.name, firesAt, minutes: mins, profile: timerProfile, model: timerModel, contextMode: timerContextMode, effort: timerEffort, tools: timerTools, platform: automationPlatform({ platform }, null, template), codexAccountId: timerCodexAccountId, usesBrowser: timerUsesBrowser, ...(timerMoreLogin || {}), createdAt: new Date().toISOString() });
16498
16927
  console.log(`[quick-timer] Set: "${template.name}" fires in ${mins}m at ${firesAt} (${timerProfile}/${timerModel || 'default'}${timerEffort ? '/' + timerEffort : ''}${'/tools:' + serializeToolList(timerTools)})`);
16499
- broadcastSync({ type: 'quick-timer:set', timerId, templateName: template.name, firesAt, minutes: mins, profile: timerProfile, model: timerModel, contextMode: timerContextMode, effort: timerEffort, tools: timerTools, platform: automationPlatform({ platform }, null, template), usesBrowser: timerUsesBrowser });
16500
- res.json({ ok: true, timerId, templateName: template.name, firesAt, minutes: mins, profile: timerProfile, model: timerModel, contextMode: timerContextMode, effort: timerEffort, tools: timerTools, platform: automationPlatform({ platform }, null, template), usesBrowser: timerUsesBrowser });
16928
+ broadcastSync({ type: 'quick-timer:set', timerId, templateName: template.name, firesAt, minutes: mins, profile: timerProfile, model: timerModel, contextMode: timerContextMode, effort: timerEffort, tools: timerTools, platform: automationPlatform({ platform }, null, template), usesBrowser: timerUsesBrowser, ...(timerMoreLogin || {}) });
16929
+ res.json({ ok: true, timerId, templateName: template.name, firesAt, minutes: mins, profile: timerProfile, model: timerModel, contextMode: timerContextMode, effort: timerEffort, tools: timerTools, platform: automationPlatform({ platform }, null, template), usesBrowser: timerUsesBrowser, ...(timerMoreLogin || {}) });
16501
16930
  } catch (err) {
16502
16931
  res.status(err.status || 500).json({ error: err.message, ...(err.code ? { code: err.code, problems: err.problems } : {}) });
16503
16932
  }
@@ -16507,7 +16936,7 @@ app.post('/api/quick-timer', async (req, res) => {
16507
16936
  app.get('/api/quick-timers', (_req, res) => {
16508
16937
  const timers = [];
16509
16938
  for (const [id, t] of _quickTimers) {
16510
- timers.push({ id, templateId: t.templateId, templateName: t.templateName, firesAt: t.firesAt, minutes: t.minutes, profile: t.profile, model: t.model, contextMode: t.contextMode, effort: t.effort, tools: storedToolList(t, toolListOptions()), usesBrowser: t.usesBrowser, createdAt: t.createdAt });
16939
+ timers.push({ id, templateId: t.templateId, templateName: t.templateName, firesAt: t.firesAt, minutes: t.minutes, profile: t.profile, model: t.model, contextMode: t.contextMode, effort: t.effort, tools: storedToolList(t, toolListOptions()), usesBrowser: t.usesBrowser, ...(t.moreloginEnvId ? { moreloginEnvId: t.moreloginEnvId, moreloginEnvName: t.moreloginEnvName || null } : {}), createdAt: t.createdAt });
16511
16940
  }
16512
16941
  res.json(timers);
16513
16942
  });
@@ -16549,6 +16978,8 @@ app.post('/api/quick-timer/now', async (req, res) => {
16549
16978
  try { await resolveAutomationLaunchChoice(timerProfile, timerModel, timerContextMode, timerCodexAccount?.home); }
16550
16979
  catch (error) { return res.status(400).json({ error: error.message }); }
16551
16980
  const timerUsesBrowser = usesBrowser !== undefined ? !!usesBrowser : !!template.usesBrowser;
16981
+ // As POST /api/quick-timer: the owner's page, or a profile on the owner's list.
16982
+ const timerMoreLogin = timerUsesBrowser ? await requestedLaunchMoreLoginProfile(req) : null;
16552
16983
 
16553
16984
  const fakeSchedule = {
16554
16985
  id: `qt-now-${randomBytes(4).toString('hex')}`,
@@ -16563,6 +16994,7 @@ app.post('/api/quick-timer/now', async (req, res) => {
16563
16994
  tools: timerTools, platform: automationPlatform({ platform }, null, template),
16564
16995
  codexAccountId: timerCodexAccountId || undefined,
16565
16996
  usesBrowser: timerUsesBrowser,
16997
+ ...(timerMoreLogin || {}),
16566
16998
  // Synthetic schedule (not persisted) — must bypass the queue's stillDue and
16567
16999
  // disabled/deleted guards, both of which key off persisted schedule state.
16568
17000
  _forced: true,
@@ -16575,7 +17007,7 @@ app.post('/api/quick-timer/now', async (req, res) => {
16575
17007
  processScheduleQueue();
16576
17008
 
16577
17009
  broadcastSync({ type: 'quick-timer:fired-now', templateName: template.name, profile: timerProfile, model: timerModel, contextMode: timerContextMode, effort: timerEffort, tools: timerTools });
16578
- res.json({ ok: true, templateName: template.name, profile: timerProfile, model: timerModel, contextMode: timerContextMode, effort: timerEffort, tools: timerTools, platform: automationPlatform({ platform }, null, template), usesBrowser: timerUsesBrowser });
17010
+ res.json({ ok: true, templateName: template.name, profile: timerProfile, model: timerModel, contextMode: timerContextMode, effort: timerEffort, tools: timerTools, platform: automationPlatform({ platform }, null, template), usesBrowser: timerUsesBrowser, ...(timerMoreLogin || {}) });
16579
17011
  } catch (err) {
16580
17012
  res.status(err.status || 500).json({ error: err.message, ...(err.code ? { code: err.code, problems: err.problems } : {}) });
16581
17013
  }
@@ -16587,11 +17019,14 @@ app.get('/api/schedule-groups', (_req, res) => {
16587
17019
  res.json(loadScheduleGroups());
16588
17020
  });
16589
17021
 
16590
- app.post('/api/schedule-groups', (req, res) => {
17022
+ app.post('/api/schedule-groups', async (req, res) => {
16591
17023
  try {
16592
17024
  const { name, color, icon, collapsed, mutualExclusion, profile, model, contextMode, effort, tools, platform, usesBrowser, codexAccountId } = req.body || {};
16593
17025
  if (unknownAutomationContextMode(contextMode)) return res.status(400).json({ error: `Invalid context mode: ${contextMode}` });
16594
17026
  if (!name?.trim()) return res.status(400).json({ error: 'name is required' });
17027
+ // The group's MoreLogin profile, decided before the store is read (nothing waits between that read and the
17028
+ // save): the owner's page may pick any Chrome-type profile, anybody else only one on the owner's list.
17029
+ const groupMoreLogin = await prepareRecordMoreLoginProfile(req, null);
16595
17030
 
16596
17031
  const groups = loadScheduleGroups();
16597
17032
  const group = {
@@ -16606,6 +17041,8 @@ app.post('/api/schedule-groups', (req, res) => {
16606
17041
  updatedAt: new Date().toISOString(),
16607
17042
  };
16608
17043
  applyScheduleLaunchOverrides(group, { profile, model, contextMode, effort, tools, platform, usesBrowser, codexAccountId });
17044
+ // The group's MoreLogin profile (optional): what a schedule of the group without one of its own runs in.
17045
+ applyPreparedMoreLoginProfile(group, groupMoreLogin);
16609
17046
  groups.push(group);
16610
17047
  saveScheduleGroups(groups);
16611
17048
  broadcastSync({ type: 'schedule-group:created', group });
@@ -16615,8 +17052,10 @@ app.post('/api/schedule-groups', (req, res) => {
16615
17052
  }
16616
17053
  });
16617
17054
 
16618
- app.put('/api/schedule-groups/:id', (req, res) => {
17055
+ app.put('/api/schedule-groups/:id', async (req, res) => {
16619
17056
  try {
17057
+ // Decided before the store is read below; the profile the group already holds may be sent back unchanged.
17058
+ const groupMoreLogin = await prepareRecordMoreLoginProfile(req, loadScheduleGroups().find(g => g.id === req.params.id) || null);
16620
17059
  const store = loadScheduleStore();
16621
17060
  const groups = store.groups;
16622
17061
  const idx = groups.findIndex(g => g.id === req.params.id);
@@ -16645,6 +17084,9 @@ app.put('/api/schedule-groups/:id', (req, res) => {
16645
17084
  codexAccountId: groups[idx].codexAccountId,
16646
17085
  };
16647
17086
  applyScheduleLaunchOverrides(groups[idx], { profile, model, contextMode, effort, tools, platform, usesBrowser, codexAccountId });
17087
+ // Read at launch through the group (scheduleMoreLoginProfile), never written through onto the schedules below:
17088
+ // a schedule's own profile is what tells two accounts apart, and a group save must not replace it.
17089
+ applyPreparedMoreLoginProfile(groups[idx], groupMoreLogin);
16648
17090
  groups[idx].updatedAt = new Date().toISOString();
16649
17091
 
16650
17092
  // Write-through: a launch override deliberately CHANGED in the group window is
@@ -16867,7 +17309,7 @@ app.get('/api/schedules/timers', (_req, res) => {
16867
17309
  });
16868
17310
 
16869
17311
  // POST /api/schedules — create a new schedule
16870
- app.post('/api/schedules', (req, res) => {
17312
+ app.post('/api/schedules', async (req, res) => {
16871
17313
  try {
16872
17314
  const { name, templateId, cron, timezone, enabled, dayThemes, overrides, groupId, profile, model, contextMode, effort, tools, platform, usesBrowser, codexAccountId } = req.body;
16873
17315
  if (unknownAutomationContextMode(contextMode)) return res.status(400).json({ error: `Invalid context mode: ${contextMode}` });
@@ -16875,6 +17317,9 @@ app.post('/api/schedules', (req, res) => {
16875
17317
  if (!templateId?.trim()) return res.status(400).json({ error: 'templateId is required' });
16876
17318
  if (!cron?.trim()) return res.status(400).json({ error: 'cron is required' });
16877
17319
  if (cron.trim().split(/\s+/).length !== 5) return res.status(400).json({ error: 'cron must be a 5-field expression' });
17320
+ // The schedule's MoreLogin profile, decided before the store is read (nothing waits between that read and the
17321
+ // save): the owner's page may pick any Chrome-type profile, anybody else only one on the owner's list.
17322
+ const scheduleMoreLogin = await prepareRecordMoreLoginProfile(req, null);
16878
17323
 
16879
17324
  const templates = readLoopTemplates();
16880
17325
  if (!templates.find(t => t.id === templateId)) return res.status(400).json({ error: 'Template not found' });
@@ -16900,6 +17345,8 @@ app.post('/api/schedules', (req, res) => {
16900
17345
  updatedAt: new Date().toISOString(),
16901
17346
  };
16902
17347
  applyScheduleLaunchOverrides(schedule, { profile, model, contextMode, effort, tools, platform, usesBrowser, codexAccountId });
17348
+ applyPreparedMoreLoginProfile(schedule, scheduleMoreLogin);
17349
+ markScheduleTaskAuthor(schedule, req, null);
16903
17350
 
16904
17351
  const schedules = loadSchedules();
16905
17352
  schedules.push(schedule);
@@ -16921,11 +17368,15 @@ app.get('/api/schedules/:id', (req, res) => {
16921
17368
  });
16922
17369
 
16923
17370
  // PUT /api/schedules/:id — update a schedule
16924
- app.put('/api/schedules/:id', (req, res) => {
17371
+ app.put('/api/schedules/:id', async (req, res) => {
16925
17372
  try {
17373
+ // Decided before the store is read below; the profile the schedule already holds may be sent back unchanged.
17374
+ const scheduleMoreLogin = await prepareRecordMoreLoginProfile(req, loadSchedules().find(s => s.id === req.params.id) || null);
16926
17375
  const schedules = loadSchedules();
16927
17376
  const idx = schedules.findIndex(s => s.id === req.params.id);
16928
17377
  if (idx === -1) return res.status(404).json({ error: 'Schedule not found' });
17378
+ // What it ran before this save (markScheduleTaskAuthor compares).
17379
+ const taskBefore = Object.fromEntries(SCHEDULE_TASK_FIELDS.map((field) => [field, schedules[idx][field]]));
16929
17380
 
16930
17381
  const { name, templateId, cron, timezone, enabled, dayThemes, overrides, groupId, profile, model, contextMode, effort, tools, platform, usesBrowser, codexAccountId } = req.body;
16931
17382
  if (unknownAutomationContextMode(contextMode)) return res.status(400).json({ error: `Invalid context mode: ${contextMode}` });
@@ -16949,6 +17400,8 @@ app.put('/api/schedules/:id', (req, res) => {
16949
17400
  schedules[idx].groupId = normalizedGroupId;
16950
17401
  }
16951
17402
  applyScheduleLaunchOverrides(schedules[idx], { profile, model, contextMode, effort, tools, platform, usesBrowser, codexAccountId });
17403
+ applyPreparedMoreLoginProfile(schedules[idx], scheduleMoreLogin);
17404
+ markScheduleTaskAuthor(schedules[idx], req, taskBefore);
16952
17405
 
16953
17406
  schedules[idx].updatedAt = new Date().toISOString();
16954
17407
  schedules[idx].nextRun = getNextCronRun(schedules[idx].cron, schedules[idx].timezone);
@@ -16961,6 +17414,100 @@ app.put('/api/schedules/:id', (req, res) => {
16961
17414
  }
16962
17415
  });
16963
17416
 
17417
+ // ── The owner's approval of a schedule or template an agent changed (re-review of 2026-11-11, finding 3) ──
17418
+ // GET /api/schedules/:id/review → { ok, review } (lib/automation-approval.js scheduleReview)
17419
+ // POST /api/schedules/:id/approve { digest } → { ok, schedule, template, review }
17420
+ // GET /api/loop/templates/:id/review → { ok, review } (templateReview)
17421
+ // POST /api/loop/templates/:id/approve { digest } → { ok, template, review }
17422
+ // GET /api/automation-approvals → { ok, schedules: { id: summary }, templates: { id: summary } } (the flags)
17423
+ // The owner's page only (ownerPageApprovalCall: this boot's page secret, never a guest, no run or agent header): an
17424
+ // agent, a run, a worker, the Assistant, a CLI MCP session, a guest and a bare request are refused 403
17425
+ // (PAGE_SECRET_REQUIRED; 503 where the caller could not be identified on macOS). The review is built from the stored
17426
+ // records each time it is served, and its digest covers every stored field a launch reads for what runs and where
17427
+ // (automation-approval.js scheduleCore / templateCore / groupCore / defaultCore). The approve request carries the
17428
+ // digest it was shown; the server builds the review again from the store and refuses 409 REVIEW_CHANGED (with the
17429
+ // fresh review) when they differ: the record, its template, its group's profile, its day themes or the default
17430
+ // changed since. Read, compare and write are synchronous, with no await in between, so nothing changes in between.
17431
+ // Approving a schedule clears its mark and its template's in one act; any later change by an agent marks again.
17432
+ /** Whether a request is the owner's page acting for itself (the same test as the default browser's writers). */
17433
+ function ownerPageApprovalCall(req) { return moreLoginOwnerPageCall(req); }
17434
+ function refuseApprovalCaller(req, res) {
17435
+ return refuseNotOwnerPage(req, res, 'Approving what an agent changed is the owner\'s, from SynaBun\'s own page (Automation Studio or Schedules): no agent, run, session or program can approve it. Tell the user: the schedule or template waits for their approval there.');
17436
+ }
17437
+ /** The profile names the server knows without asking MoreLogin (the records' own names, the owner's list). */
17438
+ function approvalProfileName(cfg) {
17439
+ const listed = normalizeAgentProfiles(cfg);
17440
+ return (envId) => listed.find((row) => row.envId === String(envId))?.name || null;
17441
+ }
17442
+ /** Everything a schedule's review is built from, read from the store now. */
17443
+ function scheduleReviewContext(id) {
17444
+ const schedules = loadSchedules();
17445
+ const idx = schedules.findIndex((s) => s.id === id);
17446
+ if (idx === -1) return null;
17447
+ const schedule = schedules[idx];
17448
+ const templates = readLoopTemplates();
17449
+ const tIdx = templates.findIndex((t) => t.id === schedule.templateId);
17450
+ const template = tIdx === -1 ? null : templates[tIdx];
17451
+ const group = schedule.groupId ? loadScheduleGroups().find((g) => g.id === schedule.groupId) || null : null;
17452
+ const cfg = loadBrowserConfig();
17453
+ const review = scheduleReview({ schedule, template, group, browserDefault: cfg, allowed: (envId) => agentProfileAllowed(cfg, envId), profileName: approvalProfileName(cfg) });
17454
+ return { schedules, idx, schedule, templates, tIdx, template, group, review };
17455
+ }
17456
+ app.get('/api/automation-approvals', (req, res) => {
17457
+ if (!ownerPageApprovalCall(req)) return refuseApprovalCaller(req, res);
17458
+ try {
17459
+ const cfg = loadBrowserConfig();
17460
+ const allowed = (envId) => agentProfileAllowed(cfg, envId);
17461
+ const profileName = approvalProfileName(cfg);
17462
+ const templates = readLoopTemplates();
17463
+ const groups = loadScheduleGroups();
17464
+ const schedules = loadSchedules();
17465
+ const out = { schedules: {}, templates: {} };
17466
+ for (const schedule of schedules) {
17467
+ const template = templates.find((t) => t.id === schedule.templateId) || null;
17468
+ if (!scheduleMarked(schedule) && !templateMarked(template)) continue;
17469
+ const group = schedule.groupId ? groups.find((g) => g.id === schedule.groupId) || null : null;
17470
+ const r = scheduleReview({ schedule, template, group, browserDefault: cfg, allowed, profileName });
17471
+ out.schedules[schedule.id] = { case: r.case, marks: r.marks, account: r.account, afterApproval: r.afterApproval };
17472
+ }
17473
+ for (const template of templates) if (templateMarked(template)) out.templates[template.id] = { marks: { template: true, templateFrom: UNREVIEWED_SOURCES.includes(template.unreviewedFrom) ? template.unreviewedFrom : 'agent' } };
17474
+ res.json({ ok: true, ...out });
17475
+ } catch (err) {
17476
+ res.status(500).json({ ok: false, error: err.message });
17477
+ }
17478
+ });
17479
+ app.get('/api/schedules/:id/review', (req, res) => {
17480
+ if (!ownerPageApprovalCall(req)) return refuseApprovalCaller(req, res);
17481
+ const ctx = scheduleReviewContext(req.params.id);
17482
+ if (!ctx) return res.status(404).json({ ok: false, error: 'Schedule not found' });
17483
+ res.json({ ok: true, review: ctx.review });
17484
+ });
17485
+ app.post('/api/schedules/:id/approve', (req, res) => {
17486
+ if (!ownerPageApprovalCall(req)) return refuseApprovalCaller(req, res);
17487
+ const digest = req.body?.digest;
17488
+ if (typeof digest !== 'string' || !digest) return res.status(400).json({ ok: false, code: 'DIGEST_REQUIRED', error: 'digest is required: the one of the review you were shown (GET /api/schedules/:id/review).' });
17489
+ // Read, compare, write: synchronous from here to the answer (no await), so the content approved is the content stored.
17490
+ const ctx = scheduleReviewContext(req.params.id);
17491
+ if (!ctx) return res.status(404).json({ ok: false, error: 'Schedule not found' });
17492
+ if (!sameDigest(digest, ctx.review.digest)) {
17493
+ return res.status(409).json({ ok: false, code: REVIEW_CHANGED, review: ctx.review, error: 'What this schedule runs or where it runs changed after you opened the review (its template, its day themes, its group\'s profile or the default browser, possibly by an agent). Nothing was approved: look at it again.' });
17494
+ }
17495
+ if (!ctx.review.needsApproval) return res.json({ ok: true, unchanged: true, schedule: ctx.schedule, template: ctx.template, review: ctx.review });
17496
+ const ownProfile = ctx.review.account.kind === 'morelogin' && ctx.review.account.source === 'schedule';
17497
+ if (ctx.template && templateMarked(ctx.template)) {
17498
+ clearTemplateMark(ctx.templates[ctx.tIdx]);
17499
+ ctx.templates[ctx.tIdx].updatedAt = new Date().toISOString();
17500
+ writeLoopTemplates(ctx.templates);
17501
+ }
17502
+ clearScheduleMark(ctx.schedules[ctx.idx], { ownProfileToOwner: ownProfile });
17503
+ ctx.schedules[ctx.idx].updatedAt = new Date().toISOString();
17504
+ saveSchedules(ctx.schedules);
17505
+ console.log(`[schedule] the owner approved "${String(ctx.schedule.name || ctx.schedule.id).slice(0, 80)}"${ctx.review.marks.template ? ' and its template' : ''} (${ctx.review.account.kind === 'morelogin' ? `MoreLogin profile ${ctx.review.account.envId}, ${ctx.review.afterApproval === 'owner' ? 'the owner\'s choice from now on' : 'the group\'s profile, still held to the list'}` : 'the default browser'})`);
17506
+ const fresh = scheduleReviewContext(req.params.id);
17507
+ broadcastSync({ type: 'schedule:updated', schedule: fresh?.schedule || ctx.schedules[ctx.idx] });
17508
+ res.json({ ok: true, schedule: fresh?.schedule || null, template: fresh?.template || null, review: fresh?.review || null });
17509
+ });
17510
+
16964
17511
  // DELETE /api/schedules/:id — delete a schedule
16965
17512
  app.delete('/api/schedules/:id', (req, res) => {
16966
17513
  try {
@@ -17129,6 +17676,7 @@ function spawnAgentProcess(agent, prompt, extraEnv = {}) {
17129
17676
 
17130
17677
  if (agent.model && agent.model !== 'default') args.push('--model', toCliModelName(agent.model));
17131
17678
  if (agent.effort && CLAUDE_EFFORT_LEVELS.includes(agent.effort)) args.push('--effort', agent.effort);
17679
+ else if (agent.effort === CLAUDE_EFFORT_OFF) args.push('--thinking', 'disabled');
17132
17680
  if (agent._maxTurns) args.push('--max-turns', String(agent._maxTurns));
17133
17681
  if (agent._systemPrompt) args.push('--system-prompt', agent._systemPrompt);
17134
17682
  if (agent._allowedTools?.length) args.push('--allowedTools', ...agent._allowedTools);
@@ -17569,6 +18117,10 @@ app.post('/api/agents/launch', async (req, res) => {
17569
18117
  mode, iterations, maxMinutes, context,
17570
18118
  } = req.body;
17571
18119
  if (!task?.trim()) return res.status(400).json({ error: 'task is required' });
18120
+ // Optional moreloginEnvId (+ moreloginEnvName): the MoreLogin profile this agent works in. The owner's page: any
18121
+ // Chrome-type profile. Anybody else (an agent's tree reaches this route with any agent header): only a profile on
18122
+ // the owner's list. Decided before anything of the agent exists.
18123
+ const agentMoreLogin = withSynabun ? await requestedLaunchMoreLoginProfile(req) : null;
17572
18124
  if (req.body.tools !== undefined && !Array.isArray(req.body.tools)) throw Object.assign(new Error('tools must be an array'), { code: 'TOOLS_INVALID', status: 400 });
17573
18125
  const tools = requireToolList(resolveToolList(req.body.tools ?? [], { source: 'runtime' })).items;
17574
18126
  selectExternalServers(tools, externalInventory('claude-code', cwd || PACKAGE_ROOT));
@@ -17584,11 +18136,15 @@ app.post('/api/agents/launch', async (req, res) => {
17584
18136
  let browserSessionId = null;
17585
18137
  let browserTabId = null;
17586
18138
  const agentId = randomUUID();
18139
+ // The agent's MoreLogin profile (decided above) is its owner key's pin, every iteration, as a schedule's run is.
18140
+ // None: the default browser.
18141
+ if (agentMoreLogin) pinRunMoreLoginProfile(`agent:${agentId}`, agentMoreLogin.moreloginEnvId, agentMoreLogin.moreloginEnvName, agentMoreLogin.moreloginEnvBy);
17587
18142
  if (withSynabun) {
17588
18143
  const acq = await acquireSharedBrowserTab({ ownerKey: `agent:${agentId}`, ownerType: 'interactive', logTag: 'agent:browser' });
17589
18144
  if (acq.error) {
18145
+ forgetRunMoreLoginProfile(`agent:${agentId}`);
17590
18146
  console.warn(`[agent] Browser tab acquire failed: ${acq.error}`);
17591
- return res.status(500).json({ error: `Could not start browser session for this automation: ${acq.error}`, ...(acq.code ? { code: acq.code, offenders: acq.offenders } : {}) });
18147
+ return res.status(acq.code === PROFILE_NOT_ALLOWED ? 403 : 500).json({ error: `Could not start browser session for this automation: ${acq.error}`, ...(acq.code ? { code: acq.code, offenders: acq.offenders } : {}) });
17592
18148
  }
17593
18149
  browserSessionId = acq.browserSessionId;
17594
18150
  browserTabId = acq.browserTabId;
@@ -18033,6 +18589,8 @@ function systemActivitySources() {
18033
18589
  },
18034
18590
  // A prompt running in an Antigravity panel tab (lib/antigravity/panel-bridge.js); dispatched runs are under assistant.
18035
18591
  'antigravity-panel': () => antigravityPanel.turnsRunning(),
18592
+ // A reply streaming in a Maritaca panel tab (lib/maritaca/panel-bridge.js).
18593
+ 'maritaca-panel': () => maritacaPanel.turnsRunning(),
18036
18594
  'claude-cli': () => recentCliSessions(sessionRegistry),
18037
18595
  loop: () => {
18038
18596
  // A dispatched worker also runs in the native runtime: it is counted under assistant.
@@ -18391,7 +18949,66 @@ app.get('/api/system/backup', async (req, res) => {
18391
18949
  const RESTORE_STAGING_DIR = resolve(DATA_HOME, 'backups', 'restore-staging');
18392
18950
 
18393
18951
  // POST /api/system/restore/preview — Read manifest from uploaded ZIP without applying
18952
+ /** One sentence for a failed MCP server build (lib/mcp-build.js result), with what the compiler said when it said anything. */
18953
+ function mcpBuildFailureMessage(build) {
18954
+ const why = {
18955
+ 'no-compiler': 'TypeScript is not installed (npm install in the package root installs it)',
18956
+ 'no-source': 'this copy has no mcp-server/src to build from',
18957
+ compile: 'the TypeScript compile failed',
18958
+ 'incomplete-output': 'the compiler wrote an incomplete build',
18959
+ swap: 'the new build could not replace the previous one',
18960
+ busy: 'another SynaBun process is building it right now: try again in a moment',
18961
+ lock: 'the build lock could not be taken',
18962
+ error: 'the build stopped on an error',
18963
+ }[build.reason] || build.reason;
18964
+ const detail = build.output ? `: ${String(build.output).trim()}` : '';
18965
+ return `${why}${detail}. The previous build is kept.`;
18966
+ }
18967
+
18968
+ // ── Restore is the owner's page's alone (re-review of 2026-11-11, finding 2) ──
18969
+ // POST /api/system/restore writes into DATA_HOME/data whatever the archive holds: browser-config.json (the owner's
18970
+ // list of profiles agents may choose, the default profile, the connect mode), the schedules and templates stores (and
18971
+ // with them the agent marks), the .env, ~/.claude/settings.json. It asked nothing itself, and lib/owner-authority.js
18972
+ // lets an agent's own call through on its route's rules (an agent or run header), so an agent process could replace
18973
+ // the list and the default. Now it, and its preview (which takes the same upload), need this boot's page secret, never
18974
+ // a guest, no run or agent header (restoreOwnerPageCall). Both of SynaBun's callers are pages that carry it (Settings →
18975
+ // Data, onboarding.html). Sibling routes checked: GET /api/system/backup and /backups read only; PUT /api/system/
18976
+ // auto-backup and POST /auto-backup/trigger write backups, never data; POST /api/system/run-update replaces the app,
18977
+ // not its data; POST /api/settings/move-db moves memory.db only; POST /api/loop/templates/import is agent-open on
18978
+ // purpose and marks what it brings (markTemplateAuthor). None of them can change the list, the default profile or a mark.
18979
+ // What a restore brings is the owner's act, the list included; but an archive is data: restored schedules and
18980
+ // templates come back marked unreviewed (markRestoredAutomationRecords), never with fewer marks than the archive.
18981
+ function restoreOwnerPageCall(req) { return moreLoginOwnerPageCall(req); }
18982
+ function refuseRestoreCaller(req, res) {
18983
+ return refuseNotOwnerPage(req, res, 'Restoring a backup replaces the owner\'s settings and data: it is done from SynaBun\'s own page (Settings → Data → Restore), never by an agent, a run or another program.');
18984
+ }
18985
+ /**
18986
+ * After a restore wrote its files: every schedule and template it put back is marked unreviewed (lib/automation-
18987
+ * approval.js markRecordsUnreviewed: marks only added, a file's `moreloginEnvBy: 'owner'` not believed). `targets`:
18988
+ * the paths the restore wrote. Returns how many records were marked.
18989
+ */
18990
+ function markRestoredAutomationRecords(targets) {
18991
+ let marked = 0;
18992
+ for (const target of targets) {
18993
+ if (resolve(dirname(target)) !== resolve(LOOP_DATA_DIR)) continue;
18994
+ const name = basename(target);
18995
+ const kind = LOOP_TEMPLATES_PATTERN.test(name) ? 'templates' : (LOOP_SCHEDULES_PATTERN.test(name) ? 'schedules' : null);
18996
+ if (!kind) continue;
18997
+ try {
18998
+ const data = JSON.parse(readFileSync(target, 'utf-8'));
18999
+ const out = markRecordsUnreviewed(data, kind, 'restore');
19000
+ writeFileSync(target, JSON.stringify(out.data, null, 2));
19001
+ marked += out.marked;
19002
+ } catch (err) {
19003
+ console.warn(`[restore] ${name}: its records could not be marked unreviewed (${err.message}); the file was left as the archive had it`);
19004
+ }
19005
+ }
19006
+ _scheduleFilesCache = null;
19007
+ return marked;
19008
+ }
19009
+
18394
19010
  app.post('/api/system/restore/preview', async (req, res) => {
19011
+ if (!restoreOwnerPageCall(req)) return refuseRestoreCaller(req, res);
18395
19012
  let upload = null;
18396
19013
  let zip = null;
18397
19014
  try {
@@ -18416,6 +19033,8 @@ app.post('/api/system/restore/preview', async (req, res) => {
18416
19033
 
18417
19034
  // POST /api/system/restore — Apply a full system backup from uploaded ZIP
18418
19035
  app.post('/api/system/restore', async (req, res) => {
19036
+ // Finding 2 of the re-review of 2026-11-11: before the upload is read.
19037
+ if (!restoreOwnerPageCall(req)) return refuseRestoreCaller(req, res);
18419
19038
  let upload = null;
18420
19039
  let zip = null;
18421
19040
  try {
@@ -18489,6 +19108,9 @@ app.post('/api/system/restore', async (req, res) => {
18489
19108
  await extractZipEntry(zip, entry, target);
18490
19109
  results.files.push(rel);
18491
19110
  }
19111
+ // An archive is data: what it puts back in the schedules and templates stores is unreviewed (finding 2).
19112
+ const unreviewed = markRestoredAutomationRecords(writes.map((w) => w.target));
19113
+ if (unreviewed) results.unreviewed = unreviewed;
18492
19114
  }
18493
19115
 
18494
19116
  // Normalize SQLITE_DB_PATH from restored .env to local default
@@ -18538,23 +19160,29 @@ app.post('/api/system/restore', async (req, res) => {
18538
19160
  }
18539
19161
 
18540
19162
  // Post-restore: ensure MCP server is built (critical for fresh installs + restore). Built means dist/index.js
18541
- // and every module it imports (lib/mcp-dist.js).
18542
- if (!mcpDistBuilt(PACKAGE_ROOT)) {
19163
+ // and every module it imports (lib/mcp-dist.js), stamped with this version and source (lib/mcp-build.js): the
19164
+ // builder compiles into a temp folder and swaps it in only on success, so a failure keeps whatever dist there was.
19165
+ // A packaged application is replaced whole: only a dist that is not whole counts, and nothing compiles it here.
19166
+ // A new dist cannot be loaded by this server (the old one is in its module cache): a build asks for a restart.
19167
+ if (mcpBuildNeeded(PACKAGE_ROOT, { packaged: !!PACKAGED_RUNTIME }).needed) {
18543
19168
  try {
18544
- // TypeScript is a devDependency of the package root (a development checkout also has it in mcp-server/).
18545
- const mcpDir = resolve(PACKAGE_ROOT, 'mcp-server');
19169
+ // TypeScript is a dependency of the package root (a development checkout also has it in mcp-server/).
19170
+ if (PACKAGED_RUNTIME) throw new Error('this application is incomplete: reinstall SynaBun');
18546
19171
  if (!mcpCompiler(PACKAGE_ROOT)) {
18547
19172
  const npm = npmCommand(npmInvocation(), fallbackInstallArgs({ includeDev: true }));
18548
19173
  await execFileAsync(npm.file, npm.args, { cwd: PACKAGE_ROOT, timeout: 600_000, maxBuffer: 16 * 1024 * 1024, shell: npm.shell, windowsHide: true, env: withPackagedPathLast(fallbackInstallEnv({ ...process.env, NODE_ENV: 'development' })) });
18549
19174
  }
18550
- await execFileAsync(process.execPath, [mcpCompiler(PACKAGE_ROOT), '-p', mcpDir], { cwd: mcpDir, timeout: 120_000, maxBuffer: 16 * 1024 * 1024, windowsHide: true });
18551
- results.files.push('(auto-built MCP server)');
19175
+ const build = await buildMcpServerSafelyAsync(PACKAGE_ROOT, { windowsHide: true });
19176
+ if (build.status === 'failed') throw new Error(mcpBuildFailureMessage(build));
19177
+ if (build.status === 'built') { results.files.push('(auto-built MCP server)'); results.restart = true; }
18552
19178
  } catch (buildErr) {
18553
19179
  results.errors.push(`MCP server auto-build failed: ${buildErr.message}`);
18554
19180
  }
18555
19181
  }
18556
19182
 
18557
- res.json({ ok: true, message: 'Backup restored successfully', results });
19183
+ res.json({ ok: true, message: 'Backup restored successfully', results, ...(results.restart ? { restart: true, bootId: SERVER_BOOT_ID } : {}) });
19184
+ // The new build loads only in a new server: the same restart as Apps → Restart Server, once the answer is out.
19185
+ if (results.restart) setTimeout(() => { try { requestServerRestart(); } catch (err) { console.error('[restore] restart after the MCP build failed:', err?.message); } }, 500);
18558
19186
  } catch (err) {
18559
19187
  console.error('POST /api/system/restore error:', err.message);
18560
19188
  if (!res.headersSent) res.status(500).json({ error: err.message });
@@ -19420,15 +20048,139 @@ function _moreLoginOpts() { return { savedCfg: loadBrowserConfig() }; }
19420
20048
  // They act with the owner's powers: MoreLogin's local API with the owner's credentials, the default AI browser (a
19421
20049
  // setting), the profiles' browsers. The owner's page (this boot's page secret, never an invite guest) calls every one
19422
20050
  // of them; an automation that says who it is calls the ones the `morelogin` MCP tool uses (status, list, create, start,
19423
- // stop, use_default) with rails: start and use_default only for a run SynaBun started (its terminal token, never an id
19424
- // merely said), start answers no CDP port, stop only a profile the caller holds, use_default never while another
19425
- // automation works in the browser. The API settings (config), the probe (test) and MoreLogin's own MCP registration
20051
+ // stop, use) with rails: start only for a run SynaBun started (its terminal token, never an id merely said) and only a
20052
+ // profile on the owner's list of profiles agents may choose (B1, moreLoginAutomationProfileCheck), start answers no CDP
20053
+ // port, stop only a profile the caller holds. use-default (the saved default profile and connect mode) is the owner's
20054
+ // page's alone since the re-review of 2026-11-11, finding 1 (refuseDefaultBrowserChange). The API settings (config), the probe (test) and MoreLogin's own MCP registration
19426
20055
  // (register-mcp, which writes a command into the agents' configurations) are the owner's page's only. Before, every
19427
20056
  // route answered whatever asked, and a request with no header stopped any profile as the owner.
19428
20057
  /** [method path] under /api/morelogin an automation may call (the `morelogin` MCP tool, mcp-server services). */
19429
- const MORELOGIN_AUTOMATION_ROUTES = new Set(['GET /status', 'GET /profiles', 'POST /profiles', 'POST /start', 'POST /stop', 'POST /use-default']);
20058
+ const MORELOGIN_AUTOMATION_ROUTES = new Set(['GET /status', 'GET /profiles', 'POST /profiles', 'POST /start', 'POST /stop', 'POST /use']);
19430
20059
  /** Of those, the ones a run must prove (verified: its terminal token or a brain's credential), never an id said. */
19431
- const MORELOGIN_VERIFIED_ROUTES = new Set(['POST /start', 'POST /use-default']);
20060
+ const MORELOGIN_VERIFIED_ROUTES = new Set(['POST /start', 'POST /use']);
20061
+ // ── MCP_SESSION_PROOFS: a plain CLI window's own MCP session (2026-11-10) ──
20062
+ // "A plain CLI terminal window's own MCP session" is an MCP client SynaBun did not start (the user's own Claude Code or
20063
+ // Codex in a terminal tab or any terminal, connected to this server's /mcp with no X-Synabun-Terminal pin). It names no
20064
+ // run: SynaBun's in-process MCP routes it as its Mcp-Session-Id (mcp-server/src/http.ts deriveIdentity), and sent that
20065
+ // id in X-Synabun-Terminal with no proof, so here it was `unregistered`: an id taken as said, which any local process
20066
+ // could also say (the id is in this server's log lines). That is why it was refused the verified routes: `start` (a
20067
+ // MoreLogin profile is another real account; the 2026-11-05 review, 972afb74 findings 1 and 7, closed every way for an
20068
+ // automation to choose a browser or act with the owner's MoreLogin powers by merely naming an id), `use_default`
20069
+ // (changes the browser of every session) and, today, `use`.
20070
+ // Now such a session gets a proof of its own when it initializes from this computer (loopback, no pin, never through
20071
+ // the tunnel; lib/terminal-tokens.js issueSession, kind 'mcp-session'): minted here, held only by the in-process MCP for
20072
+ // that one transport session (the SDK checks the Mcp-Session-Id, a random UUID only that client was given), sent by it
20073
+ // with the id on every request it makes for that session, never to the client, revoked when the session closes or is
20074
+ // evicted. The session's id is then `verified`: another process naming it is refused (403 TERMINAL_TOKEN_REQUIRED, on
20075
+ // every route that reads browserCaller, where before it was taken as said), and moreLoginGate lets it call `use` (its
20076
+ // own pin only: POST /use pins browserOwnerId(caller.id), never an id from the body). `start` and `use-default` stay
20077
+ // refused for this kind (MORELOGIN_RUN_ONLY_ROUTES): it is not a run SynaBun started. `use` needs no `start`: the
20078
+ // profile is started as part of acquiring the session's own tab (acquireSharedBrowserTab), as for any pinned run.
20079
+ // Its choice is not kept across a restart (its id dies with the server) and is dropped when the session ends.
20080
+ // What the proof is NOT (review b6631e9d of the same day, finding 1): it shows "the same MCP session", never "the
20081
+ // user's CLI window". Any program on this computer can initialize /mcp with no pin and is given one, so `use`'s
20082
+ // VERIFIED_RUN_REQUIRED excludes nobody local, and refusing `start` excludes nobody either (the acquisition starts the
20083
+ // profile). Decision: the proof is kept, because the owner's list of profiles agents may choose now bounds what such a
20084
+ // session reaches (agentMoreLoginProfileChoice in POST /use when the pin is set; moreLoginPinRefusal every time it is
20085
+ // used). With nothing on the list it reaches no profile. With profiles on the list, ANY local process can enter those
20086
+ // profiles, and only those: that residual is what the owner's toggle says ("agents may choose this profile") and it is
20087
+ // not closed. What the proof still does: one local process cannot act as ANOTHER session by naming its id, so a
20088
+ // session's tab, its pin and its choice are its own (findings 2 and 3 rest on that).
20089
+ /** Of the verified routes, the ones a plain MCP session's proof is not enough for (it is not a run SynaBun started). */
20090
+ const MORELOGIN_RUN_ONLY_ROUTES = new Set(['POST /start']);
20091
+ /** Set on a request that came in through the plain /mcp mount (never the keyed /mcp/<key> one). */
20092
+ const MCP_PLAIN_MOUNT = Symbol('synabun.mcpPlainMount');
20093
+ /**
20094
+ * Whether an MCP initialize may get a session proof (review b6631e9d, finding 5). Before, the one router mounted at
20095
+ * both /mcp and /mcp/<key> issued a proof to anything whose socket was loopback and that carried no CF-Connecting-IP:
20096
+ * a reverse proxy on this computer (not Cloudflare's) in front of the keyed mount made a remote key holder look local.
20097
+ * Now, all of:
20098
+ * • the plain /mcp mount (the keyed mount is how the outside comes in, and never issues one);
20099
+ * • not from outside by this server's own reading (requestGates.isRemote: the tunnel's and the invite proxy's
20100
+ * headers and names) and not from another machine (fromAnotherMachine: the socket's peer address);
20101
+ * • where the peer lookup runs (macOS), the process at the other end is not a relay, a listener (a proxy), an
20102
+ * automation browser, another SynaBun server or a closed client, and the lookup did not fail. An AI agent's CLI
20103
+ * (the case this exists for) and a plain local program pass. Where the lookup does not run (Windows, Linux,
20104
+ * SYNABUN_PEER_IDENTITY=off) a local proxy on the plain mount cannot be told apart: said in docs/browser-v2.md.
20105
+ * A session without a proof still works as before; it only cannot call `use` (403 VERIFIED_RUN_REQUIRED).
20106
+ */
20107
+ function mcpSessionProofEligible(req) {
20108
+ try {
20109
+ if (!req || req[MCP_PLAIN_MOUNT] !== true) return false;
20110
+ if (requestGates.isRemote(req) || requestGates.fromAnotherMachine(req)) return false;
20111
+ const auth = peerAuthority(req[PEER_VERDICT]);
20112
+ if (auth.decision === 'before') return _peerIdentity.supported !== true; // macOS with no verdict: never identified
20113
+ if (auth.decision === 'allowed') return true;
20114
+ return auth.decision === 'refused' && auth.gone !== true && auth.kind === 'agent';
20115
+ } catch { return false; }
20116
+ }
20117
+ /** Whether `ownerKey` is a plain MCP session proven by its own proof (MCP_SESSION_PROOFS). */
20118
+ function isMcpSessionOwner(ownerKey) { return _terminalTokens.kindOf(ownerKey) === 'mcp-session'; }
20119
+ /** A plain MCP session closed: what it held in any browser is released, its choice dropped, then its proof revoked. */
20120
+ async function endMcpSessionProof(sessionId) {
20121
+ if (!isMcpSessionOwner(sessionId)) return;
20122
+ try {
20123
+ // Nothing of a closed session is written anywhere (finding 6: this used to `set(sessionId, null)`, which wrote a
20124
+ // row for every session that ever closed and pushed real saved choices out of the file). Its pin is forgotten by
20125
+ // the token registry's onEnded when the proof is revoked below (forgetRunMoreLoginProfile).
20126
+ _movedAutomationRoutes.delete(sessionId);
20127
+ await releaseBrowserOwnerEverywhere(sessionId);
20128
+ } catch (err) {
20129
+ console.warn(`[morelogin] MCP session ${logOwnerId(sessionId)}: release on close failed: ${err.message}`);
20130
+ } finally {
20131
+ _terminalTokens.revokeSession(sessionId);
20132
+ }
20133
+ }
20134
+ // ── `start` and `use-default` are held to the owner's list (re-review of 2026-11-10, finding B1) ──
20135
+ // (For use-default this was superseded the next day: it is the owner's page's alone, refuseDefaultBrowserChange below.)
20136
+ // The list of profiles agents may choose was asked where a session picks a profile for itself (POST /use), where a
20137
+ // launch or a record names one, and where a pin is used, but not here. A run SynaBun started (its terminal token),
20138
+ // alone in the browser, called `use-default` with ANY Chrome-type profile: its next browser call landed there "as the
20139
+ // default" (the default is not held to the list), and the setting was saved, so every later run without a profile of
20140
+ // its own landed there too. `start` alone started any profile, any account. With nothing on the list an agent still
20141
+ // selected a profile, which is the one thing the list promises it cannot.
20142
+ // Now both routes refuse a caller that is not the owner's page (403 MORELOGIN_PROFILE_NOT_ALLOWED) unless the profile
20143
+ // is on the list. The owner's page keeps both for every profile. Other writers of the default: PUT /api/browser/config
20144
+ // is the owner's page's alone (browserTerminalGate: not an automation route), and `clear` here is the owner's too.
20145
+ /**
20146
+ * Whether a MoreLogin request is the owner's page acting for itself: this boot's page secret, never a guest
20147
+ * (browserOwnerPageOnly), and no run or agent header on it (browserCaller). moreLoginGate lets in the owner's page or
20148
+ * an automation that named itself, so everything this is false for is an automation.
20149
+ */
20150
+ function moreLoginOwnerPageCall(req) {
20151
+ return browserOwnerPageOnly(req) && !browserCaller(req).automation;
20152
+ }
20153
+ /** Throws 403 MORELOGIN_PROFILE_NOT_ALLOWED when an automation names a profile that is not on the owner's list. */
20154
+ function moreLoginAutomationProfileCheck(req, envId) {
20155
+ if (moreLoginOwnerPageCall(req)) return;
20156
+ if (!moreLoginProfileAllowed(envId)) throw profileNotAllowedError(String(envId).trim().slice(0, 128));
20157
+ }
20158
+ // ── The default profile and the connect mode are the owner's page's alone (re-review of 2026-11-11, finding 1) ──
20159
+ // B1 above held `use-default` to the owner's list. That was not enough: the default is not a pin, so nothing recorded
20160
+ // who chose it. A run made a listed profile the default; the owner then switched the profile off the list; every run
20161
+ // without a profile of its own still acquired and drove it "as the default" (pinUseRefusal lets a missing pin through,
20162
+ // sessionServesRun takes the configured default), and the list was read before an awaited profile lookup and not again
20163
+ // before the save. The owner's decision: changing the saved default MoreLogin profile, or the browser connect mode, is
20164
+ // the owner's page's only (moreLoginOwnerPageCall: this boot's page secret, never a guest, no run or agent header). No
20165
+ // automation of any kind can do it: a run SynaBun started, a worker, the Assistant, a CLI MCP session, a guest, a bare
20166
+ // request, a listed profile or not. That is what keeps "the default" the owner's choice, so it needs no list. The
20167
+ // writers: POST /api/morelogin/use-default (refused in moreLoginGate before anything else) and PUT /api/browser/config
20168
+ // (browserDefaultChangeRefused). `start` stays what B1 made it (a verified run, a listed profile, no CDP port): it
20169
+ // changes nobody's browser, and a listed profile is one the run could enter anyway with `use`.
20170
+ /** What an automation that tried to change the default AI browser is told (status 403). */
20171
+ function refuseDefaultBrowserChange(res) {
20172
+ return res.status(403).json({
20173
+ ok: false, code: 'MORELOGIN_DEFAULT_OWNER_ONLY',
20174
+ 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.',
20175
+ });
20176
+ }
20177
+ /** Whether a write of the browser settings would change the default (connect mode or default profile) and its caller may not. */
20178
+ function browserDefaultChangeRefused(req, body, saved) {
20179
+ if (moreLoginOwnerPageCall(req)) return false;
20180
+ const mode = (cfg) => (['attach', 'morelogin'].includes(cfg?.connectMode) ? cfg.connectMode : 'mirror');
20181
+ const env = (cfg) => (cfg?.moreloginEnvId ? String(cfg.moreloginEnvId) : null);
20182
+ return mode(body) !== mode(saved) || env(body) !== env(saved);
20183
+ }
19432
20184
  /** envId → the automations that started that profile through POST /api/morelogin/start (what stop counts as held). */
19433
20185
  const _moreLoginStartedBy = new Map();
19434
20186
  function moreLoginGate(req, res, next) {
@@ -19436,10 +20188,20 @@ function moreLoginGate(req, res, next) {
19436
20188
  if (!caller.accepted) return refuseBrowserCaller(res, caller);
19437
20189
  const method = String(req.method || '').toUpperCase() === 'HEAD' ? 'GET' : String(req.method || '').toUpperCase();
19438
20190
  const key = `${method} ${String(req.path || '').replace(/\/$/, '')}`;
20191
+ // Finding 1 of the re-review of 2026-11-11: the saved default profile and the connect mode are the owner's page's
20192
+ // alone. Asked before anything else, so every other caller gets the same answer (MORELOGIN_DEFAULT_OWNER_ONLY).
20193
+ if (key === 'POST /use-default' && !moreLoginOwnerPageCall(req)) return refuseDefaultBrowserChange(res);
19439
20194
  if (browserOwnerPageOnly(req)) return next();
19440
20195
  if (caller.id && MORELOGIN_AUTOMATION_ROUTES.has(key)) {
19441
20196
  if (MORELOGIN_VERIFIED_ROUTES.has(key) && caller.status !== 'verified') {
19442
- return res.status(403).json({ ok: false, code: 'VERIFIED_RUN_REQUIRED', error: `Starting a MoreLogin profile or making one the default AI browser is for a run SynaBun started (it proves its id with its terminal token), or the owner in Settings → Browser. ${String(caller.id).slice(0, 128)} is an id SynaBun gave no token.` });
20197
+ 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).` });
20198
+ }
20199
+ // An id that holds a profile pin and was not proven by this request reaches no MoreLogin route (finding 2). A pin
20200
+ // off the owner's list does not close these routes: the session needs status, list and `use` to go back.
20201
+ const pinRefused = callerProfileRefusal(caller);
20202
+ if (pinRefused && pinRefused.code === 'PROFILE_PIN_UNVERIFIED') return res.status(pinRefused.status).json({ ok: false, code: pinRefused.code, error: pinRefused.error });
20203
+ if (MORELOGIN_RUN_ONLY_ROUTES.has(key) && isMcpSessionOwner(caller.id)) {
20204
+ 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).' });
19443
20205
  }
19444
20206
  return next();
19445
20207
  }
@@ -19461,6 +20223,87 @@ function otherAutomationsInBrowser(caller) {
19461
20223
  }
19462
20224
  app.use('/api/morelogin', moreLoginGate);
19463
20225
 
20226
+ // ── Local profiles (2026-11-11): profiles SynaBun creates and runs itself, next to MoreLogin's ──
20227
+ // A local profile is a Chrome SynaBun starts with a data folder of its own (lib/local-profiles.js, DATA_HOME/data/
20228
+ // local-profiles/<id>). It is not a MoreLogin profile: nothing of MoreLogin's (its app data, its browser, its account,
20229
+ // its API) is used for it, and MoreLogin does not list it. Its id (`lp-` + 12 hex characters) travels every rail a
20230
+ // MoreLogin profile id does: `moreLogin` here is lib/browser-profiles.js, which sends a local id to the local launcher
20231
+ // and every other id to MoreLogin. So the default AI browser, the owner's list of profiles agents may choose, the pins,
20232
+ // the pickers and start / stop need nothing of their own for it.
20233
+ // Creating, changing, deleting one and checking its proxy are the owner's page's alone: none of these paths is in
20234
+ // MORELOGIN_AUTOMATION_ROUTES, so moreLoginGate answers every automation 403, and each route asks again by itself.
20235
+ moreLogin.configureLocalProfiles({
20236
+ root: resolve(DATA_HOME, 'data', 'local-profiles'),
20237
+ launchChrome: (launch) => _launchChromeAndWaitForCdp(launch),
20238
+ // Attach mode's resolution: the path of Settings → Browser, the installed browser of its channel, Chrome on macOS.
20239
+ resolveChromeBin: () => {
20240
+ const cfg = loadBrowserConfig();
20241
+ return [cfg.executablePath, findBrowserExecutable(cfg.channel)].find((p) => p && existsSync(p))
20242
+ || (process.platform === 'darwin' ? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' : null);
20243
+ },
20244
+ log: (line) => console.log(`[local-profile] ${line}`),
20245
+ });
20246
+ /** Answers 403 and returns true when a local-profile route was not called by the owner's page. */
20247
+ function localProfileRouteRefused(req, res) {
20248
+ if (moreLoginOwnerPageCall(req)) return false;
20249
+ res.status(403).json({ ok: false, code: 'OWNER_ROUTE', error: 'Local profiles are created, changed and deleted by the owner in SynaBun → Settings → Connected tools → MoreLogin. An agent works in one the owner allowed: morelogin "list", then "use".' });
20250
+ return true;
20251
+ }
20252
+ function localProfileRouteError(res, err) {
20253
+ res.status(err?.status || 500).json({ ok: false, error: err?.message || String(err), ...(err?.code ? { code: err.code } : {}), ...(err?.field ? { field: err.field } : {}) });
20254
+ }
20255
+ // GET /api/morelogin/local-profiles — the editor's rows (never a proxy password; `hasPassword` says there is one)
20256
+ app.get('/api/morelogin/local-profiles', async (req, res) => {
20257
+ try {
20258
+ if (localProfileRouteRefused(req, res)) return;
20259
+ res.json({ ok: true, profiles: await moreLogin.localProfileDetails() });
20260
+ } catch (err) { localProfileRouteError(res, err); }
20261
+ });
20262
+ // POST /api/morelogin/local-profiles — { name, proxy?, language?, timezone?, window?, notes? } → { profile }
20263
+ app.post('/api/morelogin/local-profiles', async (req, res) => {
20264
+ try {
20265
+ if (localProfileRouteRefused(req, res)) return;
20266
+ const profile = await moreLogin.createLocalProfile(req.body || {});
20267
+ console.log(`[local-profile] the owner created ${profile.id} "${profile.name}"`);
20268
+ res.json({ ok: true, profile });
20269
+ } catch (err) { localProfileRouteError(res, err); }
20270
+ });
20271
+ // PUT /api/morelogin/local-profiles/:id — new settings; they hold from the profile's next start (`restartNeeded`)
20272
+ app.put('/api/morelogin/local-profiles/:id', async (req, res) => {
20273
+ try {
20274
+ if (localProfileRouteRefused(req, res)) return;
20275
+ const profile = await moreLogin.updateLocalProfile(String(req.params.id), req.body || {});
20276
+ res.json({ ok: true, profile, restartNeeded: profile.restartNeeded === true });
20277
+ } catch (err) { localProfileRouteError(res, err); }
20278
+ });
20279
+ // DELETE /api/morelogin/local-profiles/:id — stops it, removes its folder (cookies, logins) and its entry
20280
+ app.delete('/api/morelogin/local-profiles/:id', async (req, res) => {
20281
+ try {
20282
+ if (localProfileRouteRefused(req, res)) return;
20283
+ const id = String(req.params.id);
20284
+ const cfg = loadBrowserConfig();
20285
+ if (cfg.connectMode === 'morelogin' && String(cfg.moreloginEnvId || '') === id) {
20286
+ 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.' });
20287
+ }
20288
+ const removed = await moreLogin.deleteLocalProfile(id);
20289
+ _moreLoginStartedBy.delete(id);
20290
+ // Off the agents' list with it (the list's one writer). A pin that still names it fails at its next use: the
20291
+ // profile is not found.
20292
+ try { if (moreLoginProfileAllowed(id)) writeAgentProfileChoice(id, null, false); }
20293
+ catch (err) { console.warn(`[local-profile] ${id} was deleted but is still on the agents' list: ${err.message}`); }
20294
+ console.log(`[local-profile] the owner deleted ${id} "${removed.name}"`);
20295
+ res.json({ ok: true, id, name: removed.name });
20296
+ } catch (err) { localProfileRouteError(res, err); }
20297
+ });
20298
+ // POST /api/morelogin/local-profiles/:id/check-proxy — { proxy? } (the editor's unsaved values) → { ok, ip, via, ms }
20299
+ app.post('/api/morelogin/local-profiles/:id/check-proxy', async (req, res) => {
20300
+ try {
20301
+ if (localProfileRouteRefused(req, res)) return;
20302
+ const result = await moreLogin.checkLocalProfileProxy(String(req.params.id), req.body && req.body.proxy);
20303
+ res.json(result);
20304
+ } catch (err) { localProfileRouteError(res, err); }
20305
+ });
20306
+
19464
20307
  // GET /api/morelogin/status — install + running + port + default-profile state
19465
20308
  app.get('/api/morelogin/status', async (req, res) => {
19466
20309
  try {
@@ -19471,6 +20314,21 @@ app.get('/api/morelogin/status', async (req, res) => {
19471
20314
  ...status,
19472
20315
  isDefault: cfg.connectMode === 'morelogin',
19473
20316
  defaultEnvId: cfg.moreloginEnvId || null,
20317
+ // SynaBun's own local profiles (lib/local-profiles.js): `installed`, `running` and `profileCount` are MoreLogin's.
20318
+ localProfileCount: moreLogin.localProfileCount(),
20319
+ // The profile the calling session's own browser tools work in (POST /api/morelogin/use, or the profile its run
20320
+ // was launched with), when that is not the default.
20321
+ // Only for a caller this request proved (finding 2): an id merely said learns nothing about a pin.
20322
+ ...(() => {
20323
+ const who = browserCaller(req);
20324
+ const pin = who.automation && who.accepted && who.status === 'verified' ? runMoreLoginPin(browserOwnerId(who.id)) : null;
20325
+ if (!pin) return {};
20326
+ const refused = moreLoginPinRefusal(browserOwnerId(who.id), pin);
20327
+ return { yourProfile: { envId: pin.envId, name: pin.name || null, ...(refused ? { refused: refused.error } : {}) } };
20328
+ })(),
20329
+ // The owner's list of profiles agents may choose (Settings → Connected tools → MoreLogin): an agent reads it
20330
+ // here before it tries a profile. Empty: no session, dispatch or agent-made launch can choose one.
20331
+ agentProfiles: moreLoginAgentProfiles(),
19474
20332
  // MoreLogin's local API does not expose its website blacklist/whitelist, so
19475
20333
  // report the blocks we actually observed instead of the config we can't read.
19476
20334
  blockedNavigations: moreLoginBlockStats.count,
@@ -19525,10 +20383,20 @@ app.post('/api/morelogin/test', async (req, res) => {
19525
20383
  // GET /api/morelogin/profiles — list browser profiles (environments)
19526
20384
  app.get('/api/morelogin/profiles', async (req, res) => {
19527
20385
  try {
19528
- const envs = await moreLogin.listProfiles(_moreLoginOpts());
19529
- res.json({ ok: true, envs });
20386
+ // Each with the browser it runs (`browser`): "use as default" is not offered for a Firefox-type one.
20387
+ // MoreLogin's profiles and SynaBun's local ones (`kind: 'local'`). With MoreLogin closed the local ones are still
20388
+ // listed, and `moreloginError` says why MoreLogin's are missing.
20389
+ const rows = await moreLogin.listProfiles(_moreLoginOpts());
20390
+ const listed = await withMoreLoginBrowsers(rows, _moreLoginOpts());
20391
+ // `agentsMayChoose`: on the owner's list (the Settings toggle, and what the `morelogin` tool's "list" shows).
20392
+ const allowed = moreLoginAgentProfiles();
20393
+ res.json({
20394
+ ok: true, envs: listed.envs.map((env) => ({ ...env, agentsMayChoose: allowed.some((row) => row.envId === String(env.id)) })), browsersPending: listed.browsersPending, agentProfiles: allowed,
20395
+ local: { count: listed.envs.filter((env) => env.kind === 'local').length },
20396
+ ...(rows.moreloginError ? { moreloginError: rows.moreloginError.message } : {}),
20397
+ });
19530
20398
  } catch (err) {
19531
- res.json({ ok: false, error: err.message, envs: [] });
20399
+ res.json({ ok: false, error: err.message, envs: [], local: { count: 0 } });
19532
20400
  }
19533
20401
  });
19534
20402
 
@@ -19539,6 +20407,11 @@ app.post('/api/morelogin/profiles', async (req, res) => {
19539
20407
  const result = await moreLogin.createProfile({ ..._moreLoginOpts(), name });
19540
20408
  res.json({ ok: true, ...result });
19541
20409
  } catch (err) {
20410
+ // MoreLogin's plan holds no more profiles: said as such, so the page can offer a local profile (which needs no
20411
+ // MoreLogin slot). The match is loose (lib/browser-profiles.js isMoreLoginPlanLimit): MoreLogin's words vary.
20412
+ if (moreLogin.isMoreLoginPlanLimit(err)) {
20413
+ return res.status(409).json({ ok: false, code: 'MORELOGIN_PLAN_LIMIT', error: `${err.message}. Its plan seems to hold no more profiles. A local profile needs no MoreLogin slot: SynaBun runs it itself on this computer (Settings → Connected tools → MoreLogin → Profiles, "Where": Local).` });
20414
+ }
19542
20415
  res.status(500).json({ ok: false, error: err.message });
19543
20416
  }
19544
20417
  });
@@ -19548,12 +20421,17 @@ app.post('/api/morelogin/start', async (req, res) => {
19548
20421
  try {
19549
20422
  const envId = req.body && req.body.envId;
19550
20423
  if (!envId) return res.status(400).json({ ok: false, error: 'envId is required' });
19551
- const out = await moreLogin.startProfile(envId, _moreLoginOpts());
20424
+ // B1: an automation starts only a profile on the owner's list, checked before MoreLogin is asked for anything.
20425
+ moreLoginAutomationProfileCheck(req, envId);
20426
+ // `owner`: the owner's own Start (the page; moreLoginGate let nobody else through without the automation mark).
20427
+ // Only that may end a running local profile to start it again (lib/local-profiles.js startNow); an automation
20428
+ // gets LOCAL_PROFILE_RESTART_NEEDED / LOCAL_PROFILE_BUSY by name below, and no browser.
19552
20429
  const who = browserCaller(req);
20430
+ const out = await moreLogin.startProfile(envId, { ..._moreLoginOpts(), owner: !who.automation && moreLoginOwnerPageCall(req) });
19553
20431
  if (!who.automation) return res.json({ ok: true, ...out });
19554
20432
  // An automation's start: the profile is the caller's to stop later (POST /api/morelogin/stop), and the answer
19555
20433
  // carries no CDP port (a raw debugging connection drives the profile's browser past every check SynaBun makes;
19556
- // SynaBun's browser tools reach the default profile without it).
20434
+ // SynaBun's browser tools reach the caller's own profile without it: POST /api/morelogin/use).
19557
20435
  if (who.id) {
19558
20436
  const starters = _moreLoginStartedBy.get(String(envId)) || new Set();
19559
20437
  starters.add(who.id);
@@ -19562,7 +20440,7 @@ app.post('/api/morelogin/start', async (req, res) => {
19562
20440
  }
19563
20441
  res.json({ ok: true, started: true, envId: String(envId) });
19564
20442
  } catch (err) {
19565
- res.status(500).json({ ok: false, error: err.message });
20443
+ res.status(err.status || 500).json({ ok: false, error: err.message, ...(err.code ? { code: err.code } : {}) });
19566
20444
  }
19567
20445
  });
19568
20446
 
@@ -19580,11 +20458,11 @@ app.post('/api/morelogin/stop', async (req, res) => {
19580
20458
  const caller = who.automation ? who.ownerKey : null;
19581
20459
  const decision = profileStopDecision(browserSessions, envId, caller, { startedBy: (id) => _moreLoginStartedBy.get(id) || [] });
19582
20460
  if (decision.action === 'refuse' && decision.reason === 'not_owned') {
19583
- console.warn(`[morelogin] stop of env ${envId} by ${caller} refused: it holds nothing on that profile`);
20461
+ console.warn(`[morelogin] stop of env ${envId} by ${logOwnerId(caller)} refused: it holds nothing on that profile`);
19584
20462
  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.` });
19585
20463
  }
19586
20464
  if (decision.action === 'refuse') {
19587
- console.warn(`[morelogin] stop of env ${envId} by ${caller} refused: ${decision.others.length} other automation(s) work in it (${decision.others.join(', ')})`);
20465
+ 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(', ')})`);
19588
20466
  return res.status(409).json({
19589
20467
  ok: false, code: 'PROFILE_IN_USE', others: decision.others.length, sessionIds: decision.sessionIds,
19590
20468
  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.`,
@@ -19602,18 +20480,9 @@ app.post('/api/morelogin/stop', async (req, res) => {
19602
20480
  // { envId } to set, or { clear: true } to revert to the normal mirror browser.
19603
20481
  app.post('/api/morelogin/use-default', async (req, res) => {
19604
20482
  try {
19605
- // An automation's change of the default AI browser (moreLoginGate let a verified run through): to a profile
19606
- // MoreLogin lists, never back to another browser (`clear` is the owner's), and never while another automation works
19607
- // in the browser (its next call would be refused NOT_DEFAULT_BROWSER mid-task).
19608
- const who = browserCaller(req);
19609
- if (who.automation) {
19610
- if (req.body?.clear || !req.body?.envId) return res.status(403).json({ ok: false, code: 'OWNER_ROUTE', error: 'Going back from MoreLogin to another default browser is the owner\'s (Settings → Browser).' });
19611
- const busy = otherAutomationsInBrowser(who.ownerKey);
19612
- if (busy.length) return res.status(409).json({ ok: false, code: 'BROWSER_IN_USE', others: busy.length, error: `The default AI browser was not changed: ${busy.length} other automation(s) work in the browser now, and their next call would land in another profile. Try again when they are done, or ask the owner.` });
19613
- let envs = [];
19614
- try { envs = await moreLogin.listProfiles(_moreLoginOpts()); } catch (err) { return res.status(502).json({ ok: false, error: `MoreLogin's profile list could not be read: ${err.message}` }); }
19615
- if (!(envs || []).some((env) => String(env?.id) === String(req.body.envId))) return res.status(404).json({ ok: false, code: 'ENV_NOT_FOUND', error: `MoreLogin has no profile ${String(req.body.envId).slice(0, 64)}. Use the "list" action for its ids.` });
19616
- }
20483
+ // The owner's page only (finding 1 of the re-review of 2026-11-11): moreLoginGate refused everybody else before
20484
+ // this ran. Asked again here so the route never depends on the gate's order.
20485
+ if (!moreLoginOwnerPageCall(req)) return refuseDefaultBrowserChange(res);
19617
20486
  const cfg = loadBrowserConfig();
19618
20487
  if (req.body && req.body.clear) {
19619
20488
  cfg.connectMode = 'mirror';
@@ -19621,13 +20490,174 @@ app.post('/api/morelogin/use-default', async (req, res) => {
19621
20490
  } else {
19622
20491
  const envId = req.body && req.body.envId;
19623
20492
  if (!envId) return res.status(400).json({ ok: false, error: 'envId is required' });
20493
+ // The default AI browser is driven over CDP: never a profile known to be Firefox-type (starting one stays allowed).
20494
+ await refuseFirefoxMoreLoginChoice({ moreloginEnvId: envId });
19624
20495
  cfg.connectMode = 'morelogin';
19625
20496
  cfg.moreloginEnvId = String(envId);
19626
20497
  }
19627
20498
  saveBrowserConfig(cfg);
19628
20499
  res.json({ ok: true, connectMode: cfg.connectMode, moreloginEnvId: cfg.moreloginEnvId || null });
19629
20500
  } catch (err) {
19630
- res.status(500).json({ ok: false, error: err.message });
20501
+ res.status(err.status || 500).json({ ok: false, error: err.message, ...(err.code ? { code: err.code } : {}) });
20502
+ }
20503
+ });
20504
+
20505
+ // ── A session's own MoreLogin profile (2026-11-10) ──
20506
+ // POST /api/morelogin/use — the calling session works in a MoreLogin profile of its own from now on:
20507
+ // { envId }, { name } or { profile } (either; a profile MoreLogin lists), or { default: true } to go back to the default of Settings →
20508
+ // Browser. The choice is the caller's pin (pinRunMoreLoginProfile, the pin a schedule's run is launched with), so its
20509
+ // acquisitions, its recoveries, the per-request gate and its view of GET /api/browser/sessions all follow it. Nothing
20510
+ // else changes: not the default AI browser, not another session's pin, tab or route. This is what an agent uses to
20511
+ // work in a second profile while other automations work in the default one; use-default (which moves everybody) keeps
20512
+ // its refusal while others use the browser.
20513
+ // A switch is clean: what the caller owned in a browser that is no longer its own is released here, before the answer,
20514
+ // and from then on the gate refuses its requests there (409 NOT_DEFAULT_BROWSER); its next browser call opens its tab
20515
+ // in the new profile (started then; a profile that cannot start fails that call by name, never another profile or
20516
+ // Chrome). A Firefox-type profile is refused (400 MORELOGIN_NOT_CHROMIUM) and the choice stays what it was.
20517
+ // For a session that proves its id (moreLoginGate: a run's terminal token, a brain's credential, or a plain CLI MCP
20518
+ // session's own proof, MCP_SESSION_PROOFS), never the owner's page (which has no session: the
20519
+ // owner picks in Settings → Browser or where the run is set up).
20520
+ const _profileChoiceStore = createProfileChoiceStore({
20521
+ file: resolve(LOOP_DATA_DIR, 'browser-profile-choices.json'),
20522
+ log: (line) => console.warn(`[morelogin] ${line}`),
20523
+ });
20524
+
20525
+ /**
20526
+ * The owners of the saved choices are retired when the server starts (called once, as it starts listening, before any
20527
+ * request is answered): their ids are refused until their owner registers again (a side panel's new token, a brain's
20528
+ * credential, a resumed run's token; lib/terminal-tokens.js retire). The choices themselves stay in the file and are
20529
+ * read when their owner, verified, next uses the browser (runMoreLoginPin).
20530
+ * Before (finding 2) every saved choice was put straight back into the pin map, and the token registry is empty after
20531
+ * a restart: every saved id was `unregistered`, taken as said, so any process that named one (they are in this file
20532
+ * in plain text) got a tab in that id's profile. A choice is deleted when its owner ends (forgetRunMoreLoginProfile),
20533
+ * and one older than 14 days is not read back.
20534
+ */
20535
+ function retireSavedProfileChoiceOwners() {
20536
+ let retired = 0;
20537
+ for (const [owner] of _profileChoiceStore.entries()) { if (_terminalTokens.retire(owner)) retired++; }
20538
+ return retired;
20539
+ }
20540
+
20541
+ /**
20542
+ * The profile a request names ({ envId } / { name } / { profile }: id or name) among MoreLogin's and the local ones,
20543
+ * Chrome-type only. With MoreLogin closed a local profile is still found; a profile that is not found then may be one
20544
+ * of MoreLogin's, so the answer stays 502 MORELOGIN_UNREACHABLE, never "no such profile".
20545
+ */
20546
+ async function resolveMoreLoginProfileChoice(ref) {
20547
+ let envs = [];
20548
+ const unreachable = (reason) => Object.assign(new Error(`MoreLogin's profile list could not be read: ${reason}. Open the MoreLogin app (its Local API must be on).`), { status: 502, code: 'MORELOGIN_UNREACHABLE' });
20549
+ try { envs = await moreLogin.listProfiles(_moreLoginOpts()); } catch (err) { throw unreachable(err.message); }
20550
+ let found;
20551
+ try { found = resolveProfileRef(ref, envs); } catch (err) {
20552
+ if (envs.moreloginError && err?.code === 'ENV_NOT_FOUND') throw unreachable(envs.moreloginError.message);
20553
+ throw err;
20554
+ }
20555
+ await refuseFirefoxMoreLoginChoice({ moreloginEnvId: found.envId, moreloginEnvName: found.name });
20556
+ return found;
20557
+ }
20558
+
20559
+ /**
20560
+ * `ownerKey` works in `choice` ({ envId, name }) from now on, or in the default browser (null). Its pin is set and
20561
+ * kept (the choices file), and whatever it owned in a browser that is not its own any more is released: its tab
20562
+ * closed (left open only when it is the browser's last), its claims and its recorded route dropped.
20563
+ * → { previous, released: [{ sessionId, tabId }] }
20564
+ */
20565
+ async function chooseSessionMoreLoginProfile(ownerKey, choice) {
20566
+ const previous = runMoreLoginPin(ownerKey);
20567
+ // 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
20568
+ // every use (moreLoginPinRefusal).
20569
+ pinRunMoreLoginProfile(ownerKey, choice?.envId || null, choice?.name || null, 'agent');
20570
+ // A plain MCP session's id dies with this server: its choice is never kept for a restart (MCP_SESSION_PROOFS).
20571
+ if (!isMcpSessionOwner(ownerKey)) _profileChoiceStore.set(ownerKey, choice?.envId ? choice : null);
20572
+ const cfg = loadBrowserConfig();
20573
+ const agent = agentForTerminal(ownerKey);
20574
+ const released = [];
20575
+ for (const [sessionId, session] of [...browserSessions]) {
20576
+ const holds = session._tabOwners?.has(ownerKey) || session._loopOwned?.has(ownerKey) || session._interactiveOwned?.has(ownerKey);
20577
+ if (!holds || sessionServesRun(session, cfg, ownerKey)) continue;
20578
+ const tabId = session._tabOwners?.get(ownerKey) || null;
20579
+ await releaseSharedBrowserTab(sessionId, ownerKey).catch(() => {});
20580
+ if (agent) session._agentOwnedSet?.delete(agent.id);
20581
+ released.push({ sessionId, tabId });
20582
+ }
20583
+ const moved = _movedAutomationRoutes.get(ownerKey);
20584
+ if (moved && !sessionServesRun(browserSessions.get(moved.browserSessionId), cfg, ownerKey)) _movedAutomationRoutes.delete(ownerKey);
20585
+ try { _assistantDispatcher?.noteBrowserProfile?.(ownerKey, choice?.envId ? { envId: choice.envId, name: choice.name || null } : null); } catch (err) { console.warn(`[morelogin] run ${logOwnerId(ownerKey)}: run record not updated: ${err.message}`); }
20586
+ loopLog(ownerKey, 'browser:profile', `this session now works in ${describeMoreLoginPin(choice?.envId ? choice : null)}`, { previous: previous?.envId || null, released });
20587
+ return { previous, released };
20588
+ }
20589
+
20590
+ app.post('/api/morelogin/use', async (req, res) => {
20591
+ try {
20592
+ const who = browserCaller(req);
20593
+ if (!who.accepted) return refuseBrowserCaller(res, who);
20594
+ const owner = who.automation ? browserOwnerId(who.id) : null;
20595
+ if (!owner) {
20596
+ 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.' });
20597
+ }
20598
+ if (automationRunState(owner) === 'ended') {
20599
+ return res.status(409).json({ ok: false, code: 'RUN_ENDED', error: `Run ${owner} has ended: its browser profile is not changed.` });
20600
+ }
20601
+ const body = req.body || {};
20602
+ const toDefault = body.default === true || body.default === 'true';
20603
+ // The owner's list (review b6631e9d, finding 1): a session works only in a profile the owner allowed agents to
20604
+ // choose. Going back to the default needs no entry. Whoever calls this is never the owner's page (SESSION_REQUIRED
20605
+ // above), so there is no exception here. The gate in front proved the caller's id (MORELOGIN_VERIFIED_ROUTES).
20606
+ const choice = toDefault ? null : await agentMoreLoginProfileChoice({ envId: body.envId, name: body.name, profile: body.profile });
20607
+ const before = runMoreLoginPin(owner);
20608
+ // Asked again for what it already has: nothing is released (its tab there stays its tab), and a pin the owner's
20609
+ // page set at launch stays the owner's (it is not rewritten as the session's own).
20610
+ if ((before?.envId || null) === (choice?.envId || null)) {
20611
+ if (choice && before?.by !== 'owner') { pinRunMoreLoginProfile(owner, choice.envId, choice.name, 'agent'); if (!isMcpSessionOwner(owner)) _profileChoiceStore.set(owner, choice); }
20612
+ return res.json({ ok: true, changed: false, envId: choice?.envId || null, name: choice?.name || null, default: !choice, released: [] });
20613
+ }
20614
+ const { previous, released } = await chooseSessionMoreLoginProfile(owner, choice);
20615
+ res.json({
20616
+ ok: true, changed: true, envId: choice?.envId || null, name: choice?.name || null, default: !choice,
20617
+ previous: previous ? { envId: previous.envId, name: previous.name || null } : null,
20618
+ released,
20619
+ });
20620
+ } catch (err) {
20621
+ res.status(err.status || 500).json({ ok: false, error: err.message, ...(err.code ? { code: err.code } : {}), ...(err.ids ? { ids: err.ids } : {}) });
20622
+ }
20623
+ });
20624
+
20625
+ // ── The owner's list of profiles agents may choose (2026-11-10, review b6631e9d) ──
20626
+ // GET /api/morelogin/agent-profiles → { ok, profiles: [{ envId, name }] }
20627
+ // PUT /api/morelogin/agent-profiles { envId, name?, allowed: boolean } → the list after the change
20628
+ // The owner's page only: neither path is in MORELOGIN_AUTOMATION_ROUTES, so moreLoginGate answers a run, an MCP
20629
+ // session, a worker, a brain, a guest and a bare request 403 (OWNER_ROUTE / TERMINAL_REQUIRED / PAGE_SECRET_REQUIRED),
20630
+ // and lib/owner-authority.js refuses the write from the automation browser, a relay or an agent's tree before that. A
20631
+ // tunnel caller is a guest at best. Agents read the list through GET /status and GET /profiles (`agentProfiles`,
20632
+ // `agentsMayChoose`). Kept in the owner's browser settings (browser-config.json `moreloginAgentProfiles`); PUT
20633
+ // /api/browser/config keeps the saved list whatever its body says, so this route is its only writer. One profile per
20634
+ // request, so two toggles never overwrite each other. A change holds from the next request: nothing caches the list.
20635
+ /**
20636
+ * The list's one writer: `envId` put on the owner's list of profiles agents may choose (`allowed` true) or taken off
20637
+ * it. Called by the owner's page's own routes only: PUT /api/morelogin/agent-profiles (the switch) and DELETE
20638
+ * /api/morelogin/local-profiles/:id (a deleted local profile leaves the list). → the list after the change.
20639
+ */
20640
+ function writeAgentProfileChoice(envId, name, allowed) {
20641
+ const cfg = loadBrowserConfig();
20642
+ if (browserConfigUnreadable(cfg)) throw Object.assign(new Error(`browser-config.json is unreadable (${browserConfigUnreadable(cfg)}); fix it in Settings → Browser first.`), { status: 500 });
20643
+ cfg[AGENT_PROFILES_KEY] = withAgentProfile(cfg, envId, name, allowed);
20644
+ saveBrowserConfig(cfg);
20645
+ return cfg[AGENT_PROFILES_KEY];
20646
+ }
20647
+ app.get('/api/morelogin/agent-profiles', (req, res) => {
20648
+ res.json({ ok: true, profiles: moreLoginAgentProfiles() });
20649
+ });
20650
+ app.put('/api/morelogin/agent-profiles', (req, res) => {
20651
+ try {
20652
+ const body = req.body || {};
20653
+ const envId = body.envId === undefined || body.envId === null ? '' : String(body.envId).trim();
20654
+ if (!envId || envId.length > 128 || /[\u0000-\u001f]/.test(envId)) return res.status(400).json({ ok: false, code: 'PROFILE_REQUIRED', error: 'envId is required: the id of the MoreLogin profile.' });
20655
+ if (typeof body.allowed !== 'boolean') return res.status(400).json({ ok: false, code: 'ALLOWED_REQUIRED', error: 'allowed must be true or false.' });
20656
+ const profiles = writeAgentProfileChoice(envId, typeof body.name === 'string' ? body.name : null, body.allowed);
20657
+ console.log(`[morelogin] the owner ${body.allowed ? 'allowed agents to choose' : 'took off the agents\' list'} profile ${envId.slice(0, 64)} (${profiles.length} on the list)`);
20658
+ res.json({ ok: true, profiles });
20659
+ } catch (err) {
20660
+ res.status(err.status || 500).json({ ok: false, error: err.message });
19631
20661
  }
19632
20662
  });
19633
20663
 
@@ -19855,7 +20885,7 @@ app.get('/api/setup/onboarding', async (req, res) => {
19855
20885
  const vars = parseEnvFile(ENV_PATH);
19856
20886
  const setupComplete = vars.SETUP_COMPLETE === 'true';
19857
20887
  const dbExists = existsSync(getDbPath());
19858
- const mcpBuilt = mcpDistBuilt(PACKAGE_ROOT);
20888
+ const mcpBuilt = mcpDistWhole(PACKAGE_ROOT).complete;
19859
20889
  const { mcpCommand, mcpArgs } = getMcpPaths();
19860
20890
 
19861
20891
  res.json({
@@ -19930,9 +20960,13 @@ app.post('/api/setup/build', async (req, res) => {
19930
20960
  { name: 'MCP Server', path: resolve(PACKAGE_ROOT, 'mcp-server') },
19931
20961
  ];
19932
20962
 
19933
- // Check if MCP server needs building (determines if we need dev deps): dist/index.js and every module it imports.
19934
- const mcpDist = resolve(PACKAGE_ROOT, 'mcp-server', 'dist', 'index.js');
19935
- const mcpNeedsBuild = !mcpDistBuilt(PACKAGE_ROOT);
20963
+ // Everything below is inside one try: the stream always ends with a `complete` event the wizard reads, and a
20964
+ // throw never reaches the process-wide unhandled-rejection handler, which would exit the server.
20965
+ try {
20966
+ // Check if MCP server needs building (determines if we need dev deps): every runtime entry of dist and every
20967
+ // module it imports, stamped with this version and source (lib/mcp-build.js). A packaged application is replaced
20968
+ // whole and has no compiler: there only completeness counts, and a whole dist is never built again.
20969
+ const mcpNeedsBuild = mcpBuildNeeded(PACKAGE_ROOT, { packaged: !!PACKAGED_RUNTIME }).needed;
19936
20970
 
19937
20971
  // Phase 1: the dependencies. `npm i -g synabun` installed them at the package root (lib/runtime-dependencies.js
19938
20972
  // checks that Node finds them from both parts); only what is missing is installed, once, at the package root,
@@ -19966,37 +21000,39 @@ app.post('/api/setup/build', async (req, res) => {
19966
21000
  }
19967
21001
  }
19968
21002
 
19969
- // Phase 2: Build MCP server
19970
- const mcpSrc = resolve(PACKAGE_ROOT, 'mcp-server', 'src', 'index.ts');
19971
- let needsBuild = !mcpDistBuilt(PACKAGE_ROOT);
19972
- if (!needsBuild) {
19973
- try { needsBuild = statSync(mcpSrc).mtimeMs > statSync(mcpDist).mtimeMs; } catch { needsBuild = true; }
19974
- }
19975
-
19976
- if (!needsBuild) {
21003
+ // Phase 2: Build MCP server (lib/mcp-build.js: compiled into a temp folder, checked, swapped in only on success,
21004
+ // stamped so setup.js sees it as current at the next launch; a failure keeps the previous dist).
21005
+ let restart = false;
21006
+ if (!mcpNeedsBuild) {
19977
21007
  send('build', { status: 'skipped', output: 'dist/index.js is up to date' });
21008
+ } else if (PACKAGED_RUNTIME) {
21009
+ // Whole or not, nothing compiles it here (mcpBuildNeeded said it is not whole).
21010
+ send('build', { status: 'error', output: 'This application is incomplete: reinstall SynaBun.' });
21011
+ send('complete', { ok: false, error: 'The application is incomplete' });
21012
+ return res.end();
19978
21013
  } else {
19979
21014
  send('build', { status: 'start' });
19980
- try {
19981
- // The TypeScript Node finds from mcp-server/ (the root's devDependency in a fresh checkout), by this Node.
19982
- const tsc = mcpCompiler(PACKAGE_ROOT);
19983
- if (!tsc) throw new Error('TypeScript is not installed: npm install in the package root installs it');
19984
- const { stdout } = await execFileAsync(process.execPath, [tsc, '-p', resolve(PACKAGE_ROOT, 'mcp-server')], {
19985
- cwd: resolve(PACKAGE_ROOT, 'mcp-server'),
19986
- timeout: 120_000,
19987
- maxBuffer: 16 * 1024 * 1024,
19988
- windowsHide: true,
19989
- });
19990
- send('build', { status: 'done', output: tail(stdout) });
19991
- } catch (err) {
19992
- send('build', { status: 'error', output: tail(err.stderr || err.message) });
19993
- send('complete', { ok: false, error: 'MCP server build failed' });
21015
+ const build = await buildMcpServerSafelyAsync(PACKAGE_ROOT, { windowsHide: true });
21016
+ if (build.status === 'failed') {
21017
+ send('build', { status: 'error', output: tail(mcpBuildFailureMessage(build)) });
21018
+ send('complete', { ok: false, error: build.reason === 'busy' ? 'MCP server build already running' : 'MCP server build failed' });
19994
21019
  return res.end();
19995
21020
  }
21021
+ send('build', { status: build.status === 'built' ? 'done' : 'skipped', output: tail(build.output || (build.status === 'built' ? 'MCP server built' : 'dist/index.js is up to date')) });
21022
+ // This server has the previous dist in its module cache: only a new server loads the build (requestServerRestart,
21023
+ // the same restart as Apps → Restart Server). The wizard waits for a new bootId before it goes on.
21024
+ restart = build.status === 'built';
19996
21025
  }
19997
21026
 
19998
- send('complete', { ok: true });
21027
+ send('complete', { ok: true, ...(restart ? { restart: true, bootId: SERVER_BOOT_ID } : {}) });
19999
21028
  res.end();
21029
+ if (restart) setTimeout(() => { try { requestServerRestart(); } catch (err) { console.error('[setup/build] restart after the MCP build failed:', err?.message); } }, 500);
21030
+ } catch (err) {
21031
+ console.error('POST /api/setup/build error:', err?.message);
21032
+ try { send('build', { status: 'error', output: tail(err?.message || String(err)) }); } catch {}
21033
+ try { send('complete', { ok: false, error: 'MCP server build failed' }); } catch {}
21034
+ try { res.end(); } catch {}
21035
+ }
20000
21036
  });
20001
21037
 
20002
21038
  // Legacy setup stubs for UI compatibility
@@ -21667,6 +22703,11 @@ app.get('/api/antigravity/panel', (req, res) => {
21667
22703
  res.json({ ok: true, socket: ANTIGRAVITY_WS_PATH, capabilities: [...ANTIGRAVITY_PANEL_CAPABILITIES], live: antigravityPanel.liveCount() });
21668
22704
  });
21669
22705
 
22706
+ // /api/maritaca — the Maritaca panel's REST side (lib/maritaca/api.js): the key and defaults (never the key back),
22707
+ // a key test, the model list and the conversations. Owner routes (editorOwnerGuard) under an admin-only prefix; and
22708
+ // OpenCode's way to Maritaca (POST /api/maritaca/opencode/v1/chat/completions: loopback, the saved key presented).
22709
+ registerMaritacaRoutes(app, { client: maritacaClient, keyStore: maritacaKeyStore, sessions: maritacaSessions, bridge: maritacaPanel, guard: editorOwnerGuard, opencode: maritacaOpencode, proxy: maritacaOpencodeProxy, log: (line) => console.warn(line) });
22710
+
21670
22711
  // ── Hybrid session content search (FTS5 + semantic re-rank for Claude) ──
21671
22712
  // GET /api/session-search?q=<query>&provider=<p>&project=<path>&limit=50
21672
22713
  app.get('/api/session-search', async (req, res) => {
@@ -23348,6 +24389,12 @@ function skillBrowserAvailability() {
23348
24389
  const cfg = loadBrowserConfig();
23349
24390
  const unreadable = browserConfigUnreadable(cfg);
23350
24391
  if (unreadable) return { available: false, reason: `The browser settings cannot be read (${unreadable}): fix them in Settings → Browser.` };
24392
+ if (cfg.connectMode === 'morelogin' && cfg.moreloginEnvId && moreLogin.isLocalProfileId(String(cfg.moreloginEnvId))) {
24393
+ // The default is one of SynaBun's own local profiles: MoreLogin is not needed for it.
24394
+ return moreLogin.localProfileName(String(cfg.moreloginEnvId))
24395
+ ? { available: true, reason: null }
24396
+ : { available: false, reason: 'The default browser (Settings → Browser) is a local profile that no longer exists: choose another one.' };
24397
+ }
23351
24398
  if (cfg.connectMode === 'morelogin') {
23352
24399
  // The exe in a known folder, or the local API answered lately (an install in a custom folder). This is read
23353
24400
  // synchronously, so a miss refreshes the answer in the background for the next call.
@@ -25555,7 +26602,7 @@ function applyRuntimeTools(req, res) {
25555
26602
  }
25556
26603
  const who = browserCaller(req);
25557
26604
  if (!who.accepted) {
25558
- noteRefusedBrowserCaller(`runtime-tools:${who.code}:${asserted.slice(0, 128)}`, `[mcp/tools] runtime tools of ${asserted.slice(0, 128)} refused: ${who.code}`);
26605
+ noteRefusedBrowserCaller(`runtime-tools:${who.code}:${asserted.slice(0, 128)}`, `[mcp/tools] runtime tools of ${logOwnerId(asserted)} refused: ${who.code}`);
25559
26606
  return res.status(who.httpStatus || 403).json({ ok: false, code: who.code, error: who.error });
25560
26607
  }
25561
26608
  const terminalId = who.id || asserted;
@@ -25695,7 +26742,7 @@ function applyRuntimeTools(req, res) {
25695
26742
  { nativeRunId: run?.provider === 'opencode' ? run.runId : null },
25696
26743
  );
25697
26744
  }
25698
- console.log(`[mcp/tools] OpenCode MCP reconnected terminal=${terminalId} tools=${toolKey} correlation=${refreshCorrelationId}`);
26745
+ console.log(`[mcp/tools] OpenCode MCP reconnected terminal=${logOwnerId(terminalId)} tools=${toolKey} correlation=${refreshCorrelationId}`);
25699
26746
  } catch (err) {
25700
26747
  if (_ocpIsoServes.get(terminalId) !== entry || serializeToolList(entry.tools) !== toolKey) return;
25701
26748
  entry.toolsRefreshFailed = true;
@@ -26642,7 +27689,11 @@ try {
26642
27689
  // (lib/terminal-tokens.js): the MCP server routes it as its own MCP session, so it never shares the run's identity
26643
27690
  // (its browser pins, its recovered tab) and never sends the run's id to the browser routes.
26644
27691
  const terminalAuth = (pin, token) => _terminalTokens.accepts(pin, token);
26645
- const mcpRouter = createMcpRoutes({ terminalAuth });
27692
+ // A plain MCP session's own proof (a CLI window SynaBun did not start; mcp-server/src/http.ts sessionProof): see
27693
+ // MCP_SESSION_PROOFS above moreLoginGate. Only this router's sessions get one: the worker-only channel's never do.
27694
+ // `eligible` is this server's own answer to "is this initialize a program on this computer talking to the plain
27695
+ // /mcp mount directly" (mcpSessionProofEligible, finding 5); the MCP's own loopback check stays in front of it.
27696
+ const mcpRouter = createMcpRoutes({ terminalAuth, sessionProof: { eligible: (req) => mcpSessionProofEligible(req), issue: (sid) => _terminalTokens.issueSession(sid), revoke: (sid) => { endMcpSessionProof(sid); } } });
26646
27697
 
26647
27698
  // Keyed path: /mcp/<key> — validates key, then forwards to MCP router
26648
27699
  app.use('/mcp/:key', (req, res, next) => {
@@ -26655,7 +27706,8 @@ try {
26655
27706
  // Open path: /mcp — for this computer only. What comes in from outside (the tunnel, or anything under the
26656
27707
  // tunnel's or the invite proxy's name) needs /mcp/<key>, and is refused while no key is set
26657
27708
  // (lib/request-gate.js mcpWithoutKey)
26658
- app.use('/mcp', requestGates.mcpWithoutKey, mcpRouter);
27709
+ // Marked as the plain mount: only a session initialized here can get a proof of its own (never /mcp/<key>).
27710
+ app.use('/mcp', requestGates.mcpWithoutKey, (req, _res, next) => { req[MCP_PLAIN_MOUNT] = true; next(); }, mcpRouter);
26659
27711
 
26660
27712
  console.log(' MCP HTTP endpoint mounted at /mcp' + (activeMcpKey ? ' (from outside: /mcp/<key>)' : ' (local only: no key is set)'));
26661
27713
 
@@ -26819,6 +27871,11 @@ function getTerminalProfile(profileId, opts = {}) {
26819
27871
  if (opts.effort && profileId === 'claude-code') {
26820
27872
  if (CLAUDE_EFFORT_LEVELS.includes(opts.effort)) {
26821
27873
  cmd = `${cmd} --effort ${opts.effort}`;
27874
+ } else if (opts.effort === CLAUDE_EFFORT_OFF) {
27875
+ // Off (a schedule's, loop's or timer's `none`): thinking disabled, the flag the Agent SDK passes
27876
+ // for `thinking: { type: 'disabled' }`, over any effortLevel in the user's settings. `off` (Auto)
27877
+ // passes nothing: the model's own default.
27878
+ cmd = `${cmd} --thinking disabled`;
26822
27879
  }
26823
27880
  } else if (opts.effort && profileId === 'codex') {
26824
27881
  const codexEffort = toCodexReasoningEffort(opts.effort);
@@ -28409,6 +29466,12 @@ _nativeLoopRuntime = new NativeLoopRuntime({
28409
29466
  localPortRange: { from: OCP_SHARED_PORT_MIN, to: OCP_ISO_PORT_MAX },
28410
29467
  toolListOptions,
28411
29468
  acquireLoopBrowserAndTab, releaseSharedBrowserTab, reconcileKeepAwake,
29469
+ // A worker's own MoreLogin profile (agent_dispatch morelogin_profile): the pin a schedule's run is launched with.
29470
+ // Held to the owner's list of profiles agents may choose (agentMoreLoginProfileChoice: 403
29471
+ // MORELOGIN_PROFILE_NOT_ALLOWED), whoever dispatches; the pin is an agent's, so the list is asked again when the
29472
+ // worker's tab is acquired (a start, a resume) and at each of its browser calls.
29473
+ resolveBrowserProfile: (ref) => agentMoreLoginProfileChoice(ref),
29474
+ pinBrowserProfile: (runId, envId, name) => pinRunMoreLoginProfile(runId, envId, name, 'agent'),
28412
29475
  memory: assistantMemory, detectProject: assistantDetectProject,
28413
29476
  // Limits are read live from assistant-config.json `limits`; the money is the session budget (the planner).
28414
29477
  limits: {},
@@ -28542,6 +29605,8 @@ _nativeLoopRuntime = new NativeLoopRuntime({
28542
29605
  adminSandbox: _agentSandbox,
28543
29606
  // GET / PUT /api/assistant/worker-guard (the PUT answers UI_ONLY to agents).
28544
29607
  workerGuard: _workerGuard,
29608
+ // GET / PUT /api/assistant/automation-browser-owner-access (the owner's page only; never the automation browser).
29609
+ automationBrowserOwnerAccess: _automationBrowserOwnerAccess,
28545
29610
  // A request without an agent pin is the owner's page only with this boot's page secret (lib/page-session.js).
28546
29611
  pageSession: _pageSession,
28547
29612
  // A pin counts only with its proof (lib/terminal-tokens.js): a worker's run id, a brain's id.
@@ -31196,7 +32261,156 @@ function moreLoginDefaultEnvId(cfg) {
31196
32261
  function sessionServesMoreLoginDefault(session, cfg) {
31197
32262
  if (!session || session._profileMode !== 'morelogin') return false;
31198
32263
  const envId = moreLoginDefaultEnvId(cfg);
31199
- return !envId || String(session._mlEnvId || '') === String(envId);
32264
+ // No default profile chosen yet: any MoreLogin session serves, except one opened for a schedule's own profile.
32265
+ if (!envId) return !session._mlPinned;
32266
+ return String(session._mlEnvId || '') === String(envId);
32267
+ }
32268
+
32269
+ // ── A run's own MoreLogin profile (a schedule's, its group's, a quick timer's, a manual launch's, an agent's) ──
32270
+ // ownerKey (the run's terminalSessionId) → { envId, name, by }. A pinned run works in that profile only: its
32271
+ // acquisition, its recoveries, the browser tools' gate and its view of GET /api/browser/sessions all read the pin, so
32272
+ // it never lands in the default browser or in another run's profile, and an unpinned run never lands in a pinned
32273
+ // profile's session unless that profile is the default too. Sessions of different profiles coexist in browserSessions;
32274
+ // two runs pinned to the same profile share its one session, each in its own tab.
32275
+ //
32276
+ // What the review of 2026-11-10 (run b6631e9d) changed here, and why:
32277
+ // • `by` says who chose the profile: 'owner' only where this server saw the owner's page choose it (a schedule, a
32278
+ // group, a timer, a launch set up there); everything else is 'agent' (a session's own `use`, a dispatch, a launch
32279
+ // or record an agent made, a record with no marker). An 'agent' pin needs its profile on the owner's list every time
32280
+ // it is USED, not only when it is set (moreLoginPinRefusal, lib/morelogin-agent-profiles.js pinUseRefusal), so
32281
+ // taking a profile off the list stops the sessions on it at their next browser call: refused, never the default
32282
+ // profile and never Chrome.
32283
+ // • A pin is honoured for a REQUEST only when the server verified who sent it (callerProfileRefusal, finding 2):
32284
+ // before, any process that said a pinned id (they are in loop files and logs) got a tab in that id's profile.
32285
+ // • Nothing a request sends can evict a pin (finding 3). Before, a miss was cached as null in this one map, capped
32286
+ // at 2,000 with oldest-first eviction: 2,000 made-up ids pushed every real pin out, and a session that chose its
32287
+ // profile with `use` (no loop file to read back) fell to the default profile, another account. Now this map holds
32288
+ // only what this server decided (a launch, a `use`, a dispatch, a pin read back from its own files) and never
32289
+ // evicts: a new pin is refused when the table is full. Misses go to a map of their own (_runMoreLoginNoPin),
32290
+ // whose eviction only costs a re-read.
32291
+ // • A pin ends with its owner (forgetRunMoreLoginProfile, called by the token registry's onEnded for every ended
32292
+ // run and every closed MCP session), with its saved choice.
32293
+ const _runMoreLoginPins = new Map();
32294
+ /** Owner keys known to hold no pin (a cache of misses only: losing an entry costs one re-read, never a pin). */
32295
+ const _runMoreLoginNoPin = new Map();
32296
+ const RUN_MORELOGIN_PINS_MAX = 5000;
32297
+ const RUN_MORELOGIN_NO_PIN_MAX = 5000;
32298
+ /** Plain MCP sessions (anybody on this computer can open one) share this many pins at most, apart from the runs'. */
32299
+ const RUN_MORELOGIN_SESSION_PINS_MAX = 200;
32300
+
32301
+ /**
32302
+ * `ownerKey` works in MoreLogin profile `envId` from now on, or (no envId) in the default browser by its own choice.
32303
+ * Only for code that decided it: a launch, POST /api/morelogin/use after its checks, a dispatch. `by`: 'owner' when
32304
+ * the owner's page chose the profile, else 'agent'. Throws 503 PROFILE_PINS_FULL in place of evicting another pin.
32305
+ */
32306
+ function pinRunMoreLoginProfile(ownerKey, envId, name = null, by = 'agent') {
32307
+ if (!ownerKey) return;
32308
+ _runMoreLoginNoPin.delete(ownerKey);
32309
+ if (!_runMoreLoginPins.has(ownerKey)) {
32310
+ const session = isMcpSessionOwner(ownerKey);
32311
+ const sessionPins = session ? [..._runMoreLoginPins.keys()].filter((key) => isMcpSessionOwner(key)).length : 0;
32312
+ if (_runMoreLoginPins.size >= RUN_MORELOGIN_PINS_MAX || (session && sessionPins >= RUN_MORELOGIN_SESSION_PINS_MAX)) {
32313
+ 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' });
32314
+ }
32315
+ }
32316
+ _runMoreLoginPins.set(ownerKey, envId ? { envId: String(envId), name: name ? String(name) : null, by: by === 'owner' ? 'owner' : 'agent' } : null);
32317
+ }
32318
+
32319
+ /** `ownerKey` ended, or its launch failed: its pin and its saved choice are forgotten (nothing outlives its owner). */
32320
+ function forgetRunMoreLoginProfile(ownerKey) {
32321
+ if (!ownerKey || typeof ownerKey !== 'string') return;
32322
+ _runMoreLoginPins.delete(ownerKey);
32323
+ _runMoreLoginNoPin.delete(ownerKey);
32324
+ _profileChoiceStore.delete(ownerKey);
32325
+ }
32326
+
32327
+ /**
32328
+ * The pin of a run ({ envId, name, by }) or null. What this process did not decide itself is read from its own files:
32329
+ * the choice the owner key saved with `use` (it wins; `envId: null` is "the default, by choice"), else the run's loop
32330
+ * file (`moreloginEnvBy` says who chose it; absent is 'agent'). Reading never evicts anything (see above).
32331
+ * This is the pin of an OWNER KEY. Whether a request may use it is callerProfileRefusal's question, never this one's.
32332
+ */
32333
+ function runMoreLoginPin(ownerKey) {
32334
+ if (!ownerKey || typeof ownerKey !== 'string') return null;
32335
+ if (_runMoreLoginPins.has(ownerKey)) return _runMoreLoginPins.get(ownerKey);
32336
+ if (_runMoreLoginNoPin.has(ownerKey)) return null;
32337
+ let pin = null;
32338
+ let decided = false;
32339
+ try {
32340
+ const chosen = _profileChoiceStore.get(ownerKey);
32341
+ if (chosen !== undefined) {
32342
+ decided = true;
32343
+ pin = chosen.envId ? { envId: String(chosen.envId), name: chosen.name || null, by: 'agent' } : null;
32344
+ } else {
32345
+ const loopFile = findLoopFileForTerminal(ownerKey);
32346
+ if (loopFile) {
32347
+ const data = JSON.parse(readFileSync(resolve(LOOP_DIR, loopFile), 'utf-8'));
32348
+ if (data.moreloginEnvId) pin = { envId: String(data.moreloginEnvId), name: data.moreloginEnvName ? String(data.moreloginEnvName) : null, by: data.moreloginEnvBy === 'owner' ? 'owner' : 'agent' };
32349
+ }
32350
+ }
32351
+ } catch { /* no pin */ }
32352
+ if (pin || decided) {
32353
+ // From this server's own files: kept while there is room, read again otherwise. Never by evicting another.
32354
+ if (_runMoreLoginPins.size < RUN_MORELOGIN_PINS_MAX) _runMoreLoginPins.set(ownerKey, pin);
32355
+ } else {
32356
+ _runMoreLoginNoPin.set(ownerKey, true);
32357
+ while (_runMoreLoginNoPin.size > RUN_MORELOGIN_NO_PIN_MAX) _runMoreLoginNoPin.delete(_runMoreLoginNoPin.keys().next().value);
32358
+ }
32359
+ return pin;
32360
+ }
32361
+
32362
+ function describeMoreLoginPin(pin) {
32363
+ if (!pin) return 'the default browser';
32364
+ // `MoreLogin profile "X" (id)`, or `local profile "X" (id)` for one of SynaBun's own (lib/local-profiles.js).
32365
+ return describeProfile(pin.envId, pin.name);
32366
+ }
32367
+
32368
+ // ── The owner's list of profiles agents may choose (lib/morelogin-agent-profiles.js) ──
32369
+ /** The list as kept in the owner's browser settings: [{ envId, name }]. An unreadable config allows none. */
32370
+ function moreLoginAgentProfiles() { return normalizeAgentProfiles(loadBrowserConfig()); }
32371
+ /** Whether agents may choose `envId` (the owner's list, read at every check: a change holds from the next request). */
32372
+ function moreLoginProfileAllowed(envId) { return agentProfileAllowed(loadBrowserConfig(), envId); }
32373
+ /**
32374
+ * Why `ownerKey`'s pin may not be USED now, or null: an 'agent' pin whose profile is not on the owner's list
32375
+ * ({ status: 403, code: 'MORELOGIN_PROFILE_NOT_ALLOWED', error }). Asked wherever a pin leads to a browser: the
32376
+ * acquisition (acquireSharedBrowserTab), every request of a pinned caller (callerProfileRefusal) and sessionServesRun.
32377
+ */
32378
+ function moreLoginPinRefusal(ownerKey, pin = runMoreLoginPin(ownerKey)) {
32379
+ return pinUseRefusal(pin, loadBrowserConfig());
32380
+ }
32381
+ /**
32382
+ * Why a request may not act with the MoreLogin profile its caller id is pinned to, or null (no pin, or it may).
32383
+ * • PROFILE_PIN_UNVERIFIED (finding 2): the id holds a pin and this request did not prove it is that id (an id
32384
+ * SynaBun gave no proof is otherwise taken as said, and a grace acceptance is no proof either). Refused outright:
32385
+ * it gets neither the pinned profile nor, silently, the default one.
32386
+ * • MORELOGIN_PROFILE_NOT_ALLOWED: the pin is an agent's and its profile is not on the owner's list (any more).
32387
+ * Called by browserTerminalGate (every /api/browser route), moreLoginGate and POST /api/loop/recover-browser.
32388
+ */
32389
+ function callerProfileRefusal(who) {
32390
+ if (!who?.automation || !who.accepted || !who.id) return null;
32391
+ const owner = browserOwnerId(who.id);
32392
+ const pin = owner ? runMoreLoginPin(owner) : null;
32393
+ if (!pin) return null;
32394
+ if (who.status !== 'verified') {
32395
+ return {
32396
+ status: 403, code: 'PROFILE_PIN_UNVERIFIED',
32397
+ error: `${String(who.id).slice(0, 128)} works in ${describeMoreLoginPin(pin)}, and this request did not prove it is that session (no terminal token or session proof for the id it names). A browser profile is another account: SynaBun acts in one only for the session it verified. Nothing was opened, in that profile or in the default one.`,
32398
+ };
32399
+ }
32400
+ return moreLoginPinRefusal(owner, pin);
32401
+ }
32402
+
32403
+ function sessionServesMoreLoginEnv(session, envId) {
32404
+ return !!session && session._profileMode === 'morelogin' && String(session._mlEnvId || '') === String(envId);
32405
+ }
32406
+
32407
+ /** Whether `session` is a browser run `ownerKey` may work in: its pinned profile's, else the default browser's. */
32408
+ function sessionServesRun(session, cfg, ownerKey) {
32409
+ const pin = runMoreLoginPin(ownerKey);
32410
+ // 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
32411
+ // profile's, and never the default browser's.
32412
+ if (pin) return !pinUseRefusal(pin, cfg) && sessionServesMoreLoginEnv(session, pin.envId);
32413
+ return cfg.connectMode !== 'morelogin' || sessionServesMoreLoginDefault(session, cfg);
31200
32414
  }
31201
32415
 
31202
32416
  function describeBrowserSessionForLog(session) {
@@ -31207,7 +32421,7 @@ function describeBrowserSessionForLog(session) {
31207
32421
  }
31208
32422
 
31209
32423
  async function findReusableBrowserSession(opts = {}) {
31210
- const { excludeAgentOwned = true, excludeLoopOwned = true } = opts;
32424
+ const { excludeAgentOwned = true, excludeLoopOwned = true, moreloginEnvId = null } = opts;
31211
32425
  const cfg = loadBrowserConfig();
31212
32426
  // Don't reuse across connect modes: an attach (cdp) session and a mirror session
31213
32427
  // are not interchangeable. Protects in-flight loops when the mode is switched.
@@ -31235,7 +32449,10 @@ async function findReusableBrowserSession(opts = {}) {
31235
32449
  // MoreLogin sessions are keyed by env id (not a userDataDir). When either the
31236
32450
  // active config OR this session is MoreLogin-backed, both must be — and the env
31237
32451
  // id must line up exactly — otherwise they aren't interchangeable.
31238
- if (wantMoreLogin || session._profileMode === 'morelogin') {
32452
+ if (moreloginEnvId) {
32453
+ // A run pinned to a profile reuses that profile's session and no other, whatever the default browser is.
32454
+ if (!sessionServesMoreLoginEnv(session, moreloginEnvId)) continue;
32455
+ } else if (wantMoreLogin || session._profileMode === 'morelogin') {
31239
32456
  if (!wantMoreLogin || !sessionServesMoreLoginDefault(session, cfg)) continue;
31240
32457
  } else {
31241
32458
  if (wantAttach && session._profileMode !== 'cdp') continue;
@@ -31268,24 +32485,81 @@ async function findReusableBrowserSession(opts = {}) {
31268
32485
  return null;
31269
32486
  }
31270
32487
 
31271
- // Serializes shared-loop-browser acquisition so concurrent loop/cron launches
31272
- // don't each create a separate "shared" browser. Without this mutex, two launches
31273
- // in the same tick both see findReusableBrowserSession() === null (before either
31274
- // createBrowserSession() registers its session) and each spawns a browser —
31275
- // breaking the single-shared-browser model that tab isolation depends on.
31276
- let _loopBrowserAcquireChain = Promise.resolve();
31277
- function withLoopBrowserLock(fn) {
31278
- const result = _loopBrowserAcquireChain.then(fn, fn);
31279
- // Keep the chain from latching into a rejected state after a failed acquisition.
31280
- _loopBrowserAcquireChain = result.then(() => {}, () => {});
32488
+ // Serializes shared-browser acquisition per browser, so concurrent loop / cron launches of ONE browser don't each
32489
+ // create it. Without this, two launches in the same tick both see findReusableBrowserSession() === null (before either
32490
+ // createBrowserSession() registers its session) and each spawns a browser — breaking the single-shared-browser model
32491
+ // that tab isolation depends on.
32492
+ //
32493
+ // One queue per browser (loopBrowserLockKey): `ml:<envId>` for a MoreLogin profile, 'default' for everything else
32494
+ // (the clean, persistent and attach browsers of Settings → Browser, which keep the one queue they always had).
32495
+ // Acquisitions of different profiles run side by side, so a cold start of one profile (up to about two minutes) no
32496
+ // longer holds back another profile's run; two runs of one profile still queue, and the second finds the first one's
32497
+ // session and takes a tab in it. Before 2026-11-10 there was one queue for everything.
32498
+ //
32499
+ // What the one queue also covered, and what covers it now:
32500
+ // - find-or-create of a browser, the owner marks and the owner's tab in it: all of one session, and a session
32501
+ // belongs to one key, so its queue;
32502
+ // - the health checks that destroy a dead session (strategy 0, findReusableBrowserSession): they only reach
32503
+ // sessions the caller may run in, which are its key's (an acquisition that could reach another key's takes the
32504
+ // whole registry, below);
32505
+ // - starting the MoreLogin app itself: lib/morelogin.js ensureMoreLoginRunning is one start shared by everybody
32506
+ // who waits for it at once (profiles of different queues would otherwise each launch the app);
32507
+ // - browserSessions and the pin map are only ever changed synchronously, and createBrowserSession touches nothing
32508
+ // shared until it registers its own session id; the idle reaper and the grace timers never ran under the queue.
32509
+ // An acquisition whose browser cannot be named before it runs (MoreLogin is the default with no profile chosen yet,
32510
+ // or a requested session of another key) takes the whole registry: it waits for every queue and every queue waits
32511
+ // for it, which is the old behaviour.
32512
+ let _loopBrowserAcquireChain = Promise.resolve(); // the tail of the whole-registry acquisitions
32513
+ const _loopBrowserAcquireTails = new Map(); // key → the tail of that browser's queue
32514
+
32515
+ function withLoopBrowserLock(key, fn) {
32516
+ const settled = () => {};
32517
+ if (key === null) {
32518
+ // Everything queued so far, on every key, then this one alone.
32519
+ const result = Promise.all([..._loopBrowserAcquireTails.values(), _loopBrowserAcquireChain]).then(fn);
32520
+ // Never latch into a rejected state after a failed acquisition.
32521
+ _loopBrowserAcquireChain = result.then(settled, settled);
32522
+ return result;
32523
+ }
32524
+ const result = Promise.all([_loopBrowserAcquireTails.get(key), _loopBrowserAcquireChain]).then(fn);
32525
+ // A failure or a timeout ends this holder's turn on its own key and on no other.
32526
+ const tail = result.then(settled, settled);
32527
+ _loopBrowserAcquireTails.set(key, tail);
32528
+ tail.then(() => { if (_loopBrowserAcquireTails.get(key) === tail) _loopBrowserAcquireTails.delete(key); });
31281
32529
  return result;
31282
32530
  }
31283
32531
 
32532
+ /** The queue of the browser a session is: its MoreLogin profile's, or the one of every other browser. */
32533
+ function browserSessionLockKey(session) {
32534
+ return session?._profileMode === 'morelogin' && session._mlEnvId ? `ml:${session._mlEnvId}` : 'default';
32535
+ }
32536
+
32537
+ /**
32538
+ * The queue an acquisition waits in: the browser `ownerKey` will get. null = it cannot be named up front, so the
32539
+ * acquisition takes the whole registry (withLoopBrowserLock).
32540
+ */
32541
+ function loopBrowserLockKey(ownerKey, requestedBrowserSessionId, cfg) {
32542
+ const pin = runMoreLoginPin(ownerKey);
32543
+ let key;
32544
+ if (pin) key = `ml:${pin.envId}`;
32545
+ else if (cfg.connectMode === 'morelogin') {
32546
+ const envId = moreLoginDefaultEnvId(cfg);
32547
+ // No default profile chosen: createBrowserSession picks (or creates) one, which may be a pinned run's.
32548
+ if (!envId) return null;
32549
+ key = `ml:${envId}`;
32550
+ } else key = 'default';
32551
+ // Strategy 0 works in the requested session when the owner may run in it: that session's queue must be this one.
32552
+ const requested = requestedBrowserSessionId ? browserSessions.get(requestedBrowserSessionId) : null;
32553
+ if (requested && sessionServesRun(requested, cfg, ownerKey) && browserSessionLockKey(requested) !== key) return null;
32554
+ return key;
32555
+ }
32556
+
31284
32557
  /**
31285
32558
  * Acquire (reuse-or-create) the ONE shared browser and create a dedicated tab for
31286
32559
  * the caller, recording ownerKey → tabId so getTargetPage() can route that caller's
31287
- * tab-less calls back to its own tab. Serialized via withLoopBrowserLock so
31288
- * concurrent launches share one browser and never collide during find-or-create.
32560
+ * tab-less calls back to its own tab. Serialized per browser via withLoopBrowserLock so
32561
+ * concurrent launches of one browser share it and never collide during find-or-create,
32562
+ * while launches of different MoreLogin profiles proceed side by side.
31289
32563
  *
31290
32564
  * ownerType: 'loop' marks the session _loopOwned (active-automation semantics);
31291
32565
  * 'interactive' marks it _interactiveOwned (a non-loop CLI MCP process claiming a
@@ -31295,7 +32569,11 @@ function withLoopBrowserLock(fn) {
31295
32569
  * Returns { browserSessionId, browserTabId } on success, or { error } on failure.
31296
32570
  */
31297
32571
  async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, ownerKey, ownerType = 'loop', logTag = 'launch:browser' }) {
31298
- return withLoopBrowserLock(async () => {
32572
+ const lockKey = loopBrowserLockKey(ownerKey, requestedBrowserSessionId, loadBrowserConfig());
32573
+ const acquired = await withLoopBrowserLock(lockKey, async () => {
32574
+ // The browser this owner gets changed while it waited (Settings → Browser, a requested session that went away):
32575
+ // it queues again for the right one, outside this turn.
32576
+ if (loopBrowserLockKey(ownerKey, requestedBrowserSessionId, loadBrowserConfig()) !== lockKey) return { requeue: true };
31299
32577
  let browserSessionId = null;
31300
32578
  let browserTabId = null;
31301
32579
  const ownerProp = ownerType === 'interactive' ? '_interactiveOwned' : '_loopOwned';
@@ -31305,13 +32583,23 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
31305
32583
  // the default MoreLogin profile.
31306
32584
  const policyCfg = loadBrowserConfig();
31307
32585
  const moreLoginDefault = policyCfg.connectMode === 'morelogin';
32586
+ // The owner's own MoreLogin profile (a schedule's), when it is pinned to one: then that profile is the only
32587
+ // browser it may get, in place of the default.
32588
+ const pin = runMoreLoginPin(ownerKey);
32589
+ // The owner's list, at use: an agent's pin whose profile is not on it (any more) gets no browser at all. This is
32590
+ // the one place every acquisition passes (a launch, a recovery, a session create, a resume after a restart).
32591
+ const pinRefused = pinUseRefusal(pin, policyCfg);
32592
+ if (pinRefused) {
32593
+ loopLog(ownerKey, logTag, 'ABORT: the run\'s MoreLogin profile is not on the owner\'s list of profiles agents may choose', { envId: pin.envId });
32594
+ return { error: pinRefused.error, code: pinRefused.code };
32595
+ }
31308
32596
  if (requestedBrowserSessionId) {
31309
32597
  const requested = browserSessions.get(requestedBrowserSessionId);
31310
- const unfit = requested && moreLoginDefault && !sessionServesMoreLoginDefault(requested, policyCfg);
32598
+ const unfit = requested && !sessionServesRun(requested, policyCfg, ownerKey);
31311
32599
  if (unfit) {
31312
32600
  loopLog(ownerKey, logTag, 'strategy 0 skipped: requested browser is not the default browser profile', {
31313
32601
  requestedBrowserSessionId, ...describeBrowserSessionForLog(requested),
31314
- wantMoreLoginEnvId: moreLoginDefault ? moreLoginDefaultEnvId(policyCfg) : null,
32602
+ wantMoreLoginEnvId: pin ? pin.envId : (moreLoginDefault ? moreLoginDefaultEnvId(policyCfg) : null),
31315
32603
  });
31316
32604
  } else if (requested) {
31317
32605
  try {
@@ -31334,7 +32622,10 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
31334
32622
  // have its own browser, so keep agent-owned excluded to preserve per-agent isolation.
31335
32623
  if (!browserSessionId) {
31336
32624
  const persistentProfile = !!loadBrowserConfig().userDataDir;
31337
- const reusable = await findReusableBrowserSession({ excludeAgentOwned: !persistentProfile, excludeLoopOwned: false });
32625
+ const reusable = pin
32626
+ // One Chromium per MoreLogin profile: every run pinned to it joins the same session, each in its own tab.
32627
+ ? await findReusableBrowserSession({ excludeAgentOwned: false, excludeLoopOwned: false, moreloginEnvId: pin.envId })
32628
+ : await findReusableBrowserSession({ excludeAgentOwned: !persistentProfile, excludeLoopOwned: false });
31338
32629
  if (reusable) {
31339
32630
  browserSessionId = reusable.id;
31340
32631
  loopLog(ownerKey, logTag, 'strategy 1: reusing shared browser session', { browserSessionId });
@@ -31349,7 +32640,9 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
31349
32640
  let createError = null;
31350
32641
  if (!browserSessionId) {
31351
32642
  try {
31352
- const result = await createBrowserSession({ url: 'about:blank' });
32643
+ const result = await createBrowserSession(pin
32644
+ ? { url: 'about:blank', connectMode: 'morelogin', moreloginEnvId: pin.envId, _mlPinned: true }
32645
+ : { url: 'about:blank' });
31353
32646
  browserSessionId = result.sessionId;
31354
32647
  loopLog(ownerKey, logTag, 'strategy 2: created shared browser session', {
31355
32648
  browserSessionId, profileMode: result.profileMode, profileSource: result.profileSource,
@@ -31369,7 +32662,13 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
31369
32662
  // Carry the real reason (e.g. "MoreLogin connect failed: … unreachable") into the
31370
32663
  // run's log, lastRunResult and the schedule:failed toast.
31371
32664
  return {
31372
- error: createError
32665
+ error: pin
32666
+ // Never another profile and never regular Chrome: the run fails and says which profile it was.
32667
+ ? `Could not start ${describeMoreLoginPin(pin)} for this run${createError ? `: ${createError.error}` : '.'} The run was not started in another profile or browser: ${
32668
+ createError?.code === 'MORELOGIN_NOT_CHROMIUM' || createError?.code === 'MORELOGIN_NOT_DEVTOOLS'
32669
+ ? 'pick a Chrome-type profile where this run is set up.'
32670
+ : 'check that MoreLogin is open and that the profile still exists, or pick another profile where this run is set up.'}`
32671
+ : createError
31373
32672
  ? `Could not start the shared browser session: ${createError.error}`
31374
32673
  : 'Could not start the shared browser session. Open Browser Settings and verify the selected profile can launch.',
31375
32674
  ...(createError?.code ? { code: createError.code, offenders: createError.offenders } : {}),
@@ -31379,7 +32678,15 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
31379
32678
  // Invariant: never hand an automation a browser other than the default MoreLogin
31380
32679
  // profile while MoreLogin is the default (strategies 0–2 already enforce it).
31381
32680
  const chosenSession = browserSessions.get(browserSessionId);
31382
- if (moreLoginDefault && chosenSession && !sessionServesMoreLoginDefault(chosenSession, policyCfg)) {
32681
+ if (pin && chosenSession && !sessionServesMoreLoginEnv(chosenSession, pin.envId)) {
32682
+ loopLog(ownerKey, logTag, 'ABORT: acquired session is not the run\'s MoreLogin profile', {
32683
+ browserSessionId, ...describeBrowserSessionForLog(chosenSession), wantMoreLoginEnvId: pin.envId,
32684
+ });
32685
+ return {
32686
+ error: `Refusing browser session ${browserSessionId} (${chosenSession._profileMode || 'unknown'} mode${chosenSession._mlEnvId ? `, MoreLogin env ${chosenSession._mlEnvId}` : ''}): this run is set to ${describeMoreLoginPin(pin)} and never falls back to another profile or browser.`,
32687
+ };
32688
+ }
32689
+ if (!pin && moreLoginDefault && chosenSession && !sessionServesMoreLoginDefault(chosenSession, policyCfg)) {
31383
32690
  loopLog(ownerKey, logTag, 'ABORT: acquired session is not the default MoreLogin profile', {
31384
32691
  browserSessionId, ...describeBrowserSessionForLog(chosenSession),
31385
32692
  });
@@ -31437,8 +32744,20 @@ async function acquireSharedBrowserTab({ requestedBrowserSessionId = null, owner
31437
32744
  }
31438
32745
  }
31439
32746
 
32747
+ // The owner chose another profile while this tab was being opened (its own POST /api/morelogin/use, during a cold
32748
+ // start): the tab is in a browser that is no longer its own. It goes, and the acquisition runs again for the
32749
+ // profile it has now, so nothing of the owner's is left where it does not work any more.
32750
+ if ((runMoreLoginPin(ownerKey)?.envId || null) !== (pin?.envId || null)) {
32751
+ claimedSession[ownerProp]?.delete(ownerKey);
32752
+ if (claimedSession._tabOwners?.get(ownerKey) === browserTabId) claimedSession._tabOwners.delete(ownerKey);
32753
+ if (browserTabId && claimedSession.tabs.size > 1) await closeSessionTab(claimedSession, browserSessionId, browserTabId).catch(() => {});
32754
+ loopLog(ownerKey, logTag, 'the owner\'s MoreLogin profile changed during the acquisition: tab released, acquiring again', { browserSessionId, browserTabId });
32755
+ return { requeue: true };
32756
+ }
32757
+
31440
32758
  return { browserSessionId, browserTabId };
31441
32759
  });
32760
+ return acquired?.requeue ? acquireSharedBrowserTab({ requestedBrowserSessionId, ownerKey, ownerType, logTag }) : acquired;
31442
32761
  }
31443
32762
 
31444
32763
  /**
@@ -31545,7 +32864,7 @@ async function closeUnclaimedBrowserStart(sessionId, ownerKey, { tabId = null, s
31545
32864
  const decision = sessionCloseDecision(session, ownerKey);
31546
32865
  if (decision.action === 'release') await releaseSharedBrowserTab(sessionId, ownerKey);
31547
32866
  else await destroyBrowserSession(sessionId, { closeOwnTabs: true });
31548
- console.warn(`[browser] a browser start nobody took was ${decision.action === 'release' ? 'released' : 'closed'}: session ${sessionId} of ${ownerKey || 'the page'}`);
32867
+ console.warn(`[browser] a browser start nobody took was ${decision.action === 'release' ? 'released' : 'closed'}: session ${sessionId} of ${ownerKey ? logOwnerId(ownerKey) : 'the page'}`);
31549
32868
  }
31550
32869
 
31551
32870
  // Native runs the runtime still runs (or will resume): every other status has ended.
@@ -31632,7 +32951,7 @@ function liveAutomationRoute(terminalSessionId, { files = false, cfg: knownCfg =
31632
32951
  const route = recordedAutomationRoute(terminalSessionId, { files });
31633
32952
  if (!route?.browserTabId || !startedTabAlive(route.browserSessionId, route.browserTabId, terminalSessionId)) return null;
31634
32953
  const cfg = knownCfg || loadBrowserConfig();
31635
- if (cfg.connectMode === 'morelogin' && !sessionServesMoreLoginDefault(browserSessions.get(route.browserSessionId), cfg)) return null;
32954
+ if (!sessionServesRun(browserSessions.get(route.browserSessionId), cfg, terminalSessionId)) return null;
31636
32955
  return route;
31637
32956
  }
31638
32957
 
@@ -31648,7 +32967,7 @@ function noteAutomationBrowserRoute(terminalSessionId, acq, reason = 'recovered'
31648
32967
  if (automationRunState(terminalSessionId) === 'ended') return;
31649
32968
  const agent = agentForTerminal(terminalSessionId);
31650
32969
  if (_nativeLoopRuntime?.get?.(terminalSessionId)) {
31651
- try { _nativeLoopRuntime.setBrowserRoute(terminalSessionId, route); } catch (err) { console.warn(`[browser] run ${terminalSessionId}: route not recorded: ${err.message}`); }
32970
+ try { _nativeLoopRuntime.setBrowserRoute(terminalSessionId, route); } catch (err) { console.warn(`[browser] run ${logOwnerId(terminalSessionId)}: route not recorded: ${err.message}`); }
31652
32971
  } else if (agent) {
31653
32972
  // The agent's record and its claim on the session (grace / reuse checks) move with it; its iteration and its end
31654
32973
  // release what it owns wherever that is (releaseAgentBrowser).
@@ -31672,7 +32991,7 @@ function noteAutomationBrowserRoute(terminalSessionId, acq, reason = 'recovered'
31672
32991
  }
31673
32992
  }
31674
32993
  }
31675
- try { _assistantDispatcher?.noteBrowserRoute?.(terminalSessionId, { ...route, reason }); } catch (err) { console.warn(`[browser] run ${terminalSessionId}: run record not updated: ${err.message}`); }
32994
+ try { _assistantDispatcher?.noteBrowserRoute?.(terminalSessionId, { ...route, reason }); } catch (err) { console.warn(`[browser] run ${logOwnerId(terminalSessionId)}: run record not updated: ${err.message}`); }
31676
32995
  loopLog(terminalSessionId, 'browser:route', `browser route ${reason}`, route);
31677
32996
  }
31678
32997
 
@@ -32469,6 +33788,7 @@ async function _launchChromeAndWaitForCdp({
32469
33788
  userDataDir,
32470
33789
  timeoutMs,
32471
33790
  allowPreferredPortProbe,
33791
+ env = null, // a local profile's own environment (its timezone); the server's when not given
32472
33792
  }) {
32473
33793
  const { spawn: spawnChild } = await import('node:child_process');
32474
33794
  const stderrLines = [];
@@ -32476,7 +33796,7 @@ async function _launchChromeAndWaitForCdp({
32476
33796
  let spawnError = null;
32477
33797
 
32478
33798
  console.log(`[browser] Spawning: ${chromeBin} ${chromeArgs.join(' ')}`);
32479
- const cp = spawnChild(chromeBin, chromeArgs, { stdio: ['ignore', 'ignore', 'pipe'], detached: true });
33799
+ const cp = spawnChild(chromeBin, chromeArgs, { stdio: ['ignore', 'ignore', 'pipe'], detached: true, ...(env && { env }) });
32480
33800
  cp.on('error', (err) => { spawnError = err; });
32481
33801
  cp.stderr?.on('data', (chunk) => {
32482
33802
  const text = String(chunk || '');
@@ -32612,7 +33932,8 @@ async function ensureChromeDebuggable(opts = {}) {
32612
33932
 
32613
33933
  const vpW = viewport?.width || 1280;
32614
33934
  const vpH = viewport?.height || 800;
32615
- const baseArgs = [
33935
+ // withOnDeviceModelBlocked: keeps Chrome from downloading its on-device model into the profile.
33936
+ const baseArgs = withOnDeviceModelBlocked([
32616
33937
  '--no-first-run',
32617
33938
  '--no-default-browser-check',
32618
33939
  '--disable-popup-blocking',
@@ -32621,7 +33942,7 @@ async function ensureChromeDebuggable(opts = {}) {
32621
33942
  '--disable-renderer-backgrounding',
32622
33943
  '--disable-background-timer-throttling',
32623
33944
  '--restore-last-session',
32624
- ];
33945
+ ]);
32625
33946
  if (userDataDir) baseArgs.push(`--user-data-dir=${userDataDir}`);
32626
33947
  if (profileDirectory) baseArgs.push(`--profile-directory=${profileDirectory}`);
32627
33948
 
@@ -32803,6 +34124,7 @@ async function protectNativeServeContext(ctx, { deadline = Infinity, signal = nu
32803
34124
  function browserStartFailure(err) {
32804
34125
  const out = { error: err?.message || String(err) };
32805
34126
  if (err?.code === 'NATIVE_SERVE_UNVERIFIED') { out.code = err.code; out.offenders = narrowOffenders(err.offenders); }
34127
+ if (err?.code === 'MORELOGIN_NOT_CHROMIUM' || err?.code === 'MORELOGIN_NOT_DEVTOOLS') out.code = err.code;
32806
34128
  return out;
32807
34129
  }
32808
34130
 
@@ -33048,7 +34370,10 @@ async function createBrowserSession(options = {}) {
33048
34370
  const extra = savedCfg.extraArgs.split(/\s+/).filter(Boolean);
33049
34371
  stealthArgs.push(...extra);
33050
34372
  }
33051
- const launchOpts = { headless: headlessVal, args: stealthArgs, timeout: 45000 };
34373
+ // One --disable-features (Chromium reads only one), which also keeps Chromium from downloading its
34374
+ // on-device model into the profile (lib/chromium-on-device-model.js).
34375
+ const chromiumArgs = withOnDeviceModelBlocked(stealthArgs);
34376
+ const launchOpts = { headless: headlessVal, args: chromiumArgs, timeout: 45000 };
33052
34377
  // Priority: user-configured executablePath > channel > auto-detected executablePath.
33053
34378
  // User explicitly set executablePath = intentional override, always respect it.
33054
34379
  // Channel = let Playwright resolve the binary for that browser brand.
@@ -33155,6 +34480,7 @@ async function createBrowserSession(options = {}) {
33155
34480
  }
33156
34481
 
33157
34482
  let browser, context, page;
34483
+ let _browserContextId = null; // the clean launch's own context, for its background tabs
33158
34484
  let _isPersistent = false;
33159
34485
  let _chromeProcess = null; // CDP mode: ref to spawned Chrome process
33160
34486
  let _profileMode = userDataDir ? (_selectedProfileKind === 'managed' ? 'managed' : 'direct') : 'clean';
@@ -33176,6 +34502,9 @@ async function createBrowserSession(options = {}) {
33176
34502
  let _mlEnvId = null;
33177
34503
  let _mlDebugPort = null;
33178
34504
  let _moreLoginConnected = false;
34505
+ // A local profile (lib/local-profiles.js): a Chrome SynaBun starts itself, driven the same way. Its id takes the
34506
+ // place of a MoreLogin env id everywhere below; only the MoreLogin app is not asked for it.
34507
+ let _localProfileTimezone = null;
33179
34508
  // Localhost opens in MoreLogin like any other URL. A port missing from the
33180
34509
  // profile's Port scan protection list lands on the stop page, which the start
33181
34510
  // navigation below reports (moreLoginBlockError).
@@ -33183,10 +34512,17 @@ async function createBrowserSession(options = {}) {
33183
34512
  || !!options.moreloginEnvId
33184
34513
  || savedCfg.connectMode === 'morelogin';
33185
34514
  if (_wantMoreLogin) {
34515
+ // The profile asked for, and whether it is one of SynaBun's own local profiles (by its id).
34516
+ const _wantedEnvId = options.moreloginEnvId
34517
+ || savedCfg.moreloginEnvId
34518
+ || (savedCfg.morelogin && savedCfg.morelogin.defaultEnvId)
34519
+ || null;
34520
+ const _localProfile = !!_wantedEnvId && moreLogin.isLocalProfileId(String(_wantedEnvId));
34521
+ const _localProfileInfo = _localProfile ? moreLogin.localProfileSettings(String(_wantedEnvId)) : null;
33186
34522
  try {
33187
34523
  // An install outside the known folders (a custom folder on Windows) still
33188
34524
  // counts when its local API answers.
33189
- if (!moreLogin.isMoreLoginInstalled().installed && !(await moreLogin.probeMoreLoginApi({ savedCfg })).running) {
34525
+ if (!_localProfile && !moreLogin.isMoreLoginInstalled().installed && !(await moreLogin.probeMoreLoginApi({ savedCfg })).running) {
33190
34526
  throw new Error(`MoreLogin desktop app was not found and its local API does not answer on port ${moreLogin.getMoreLoginPort(savedCfg)}`);
33191
34527
  }
33192
34528
  // Installed but possibly not running (e.g. an autonomous schedule fires with
@@ -33196,20 +34532,20 @@ async function createBrowserSession(options = {}) {
33196
34532
  // MoreLogin is a heavy multi-process Electron app whose API port can accept
33197
34533
  // connections well before it actually serves (observed cold-boot timeouts
33198
34534
  // past the old 25s default).
33199
- const running = await moreLogin.ensureMoreLoginRunning({ savedCfg, timeoutMs: 120000 });
34535
+ // A local profile needs no MoreLogin: the app is neither looked for nor started.
34536
+ const running = _localProfile ? { running: true } : await moreLogin.ensureMoreLoginRunning({ savedCfg, timeoutMs: 120000 });
33200
34537
  if (!running.running) {
33201
34538
  throw new Error(`MoreLogin app is not reachable (${running.launchError || running.error || 'unknown error'})`);
33202
34539
  }
33203
34540
  const mlOpts = { savedCfg };
33204
- let envId = options.moreloginEnvId
33205
- || savedCfg.moreloginEnvId
33206
- || (savedCfg.morelogin && savedCfg.morelogin.defaultEnvId)
33207
- || null;
34541
+ let envId = _wantedEnvId;
33208
34542
  if (!envId) {
33209
34543
  const def = await moreLogin.ensureDefaultProfile(mlOpts);
33210
34544
  envId = def.id;
33211
34545
  }
33212
- const { debugPort } = await moreLogin.startProfile(envId, mlOpts);
34546
+ // requireCdp: a Firefox-type profile has no DevTools endpoint and is refused, before it is started when
34547
+ // MoreLogin says what it is up front.
34548
+ const { debugPort } = await moreLogin.startProfile(envId, { ...mlOpts, requireCdp: true });
33213
34549
  // Wait for MoreLogin's Chromium DevTools endpoint to come up.
33214
34550
  let endpoint = null;
33215
34551
  for (let i = 0; i < 40; i++) {
@@ -33217,12 +34553,21 @@ async function createBrowserSession(options = {}) {
33217
34553
  if (probed.ok) { endpoint = probed.httpEndpoint; break; }
33218
34554
  await new Promise(r => setTimeout(r, 250));
33219
34555
  }
33220
- if (!endpoint) endpoint = `http://127.0.0.1:${debugPort}`;
34556
+ if (!endpoint) {
34557
+ // Ten seconds without a DevTools answer. A port that answers HTTP as something else will never become
34558
+ // one: say what it is, in place of Playwright's "Unexpected status 404 … try connecting via ws://". A
34559
+ // port nothing listens on yet still gets the connect attempt below.
34560
+ const seen = await moreLogin.describeDebugEndpoint(debugPort);
34561
+ if (seen.kind === 'not-devtools') throw moreLogin.notDevToolsError(envId, debugPort, seen);
34562
+ endpoint = `http://127.0.0.1:${debugPort}`;
34563
+ }
33221
34564
 
33222
34565
  const { browser: cdpBrowser, context: cdpContext, page: cdpPage } = await moreLogin.attachProfileBrowser(
33223
34566
  chromium, endpoint,
33224
34567
  (cdpBrowser, cdpContext) => newSessionPage({ browser: cdpBrowser, context: cdpContext, _profileMode: 'morelogin' }),
33225
34568
  ); // fresh tab in the real profile; never substitute an incognito context
34569
+ // A local profile's timezone on this first tab (every later tab gets it in newSessionPage, from the session).
34570
+ if (_localProfileInfo?.timezone) await applyPageTimezone(cdpContext, cdpPage, _localProfileInfo.timezone);
33226
34571
 
33227
34572
  browser = cdpBrowser;
33228
34573
  context = cdpContext;
@@ -33232,11 +34577,31 @@ async function createBrowserSession(options = {}) {
33232
34577
  _chromeProcess = null; // teardown disconnects; MoreLogin owns the Chromium
33233
34578
  _mlEnvId = String(envId);
33234
34579
  _mlDebugPort = debugPort;
33235
- _profileSourceName = `MoreLogin · ${envId}`;
34580
+ _profileSourceName = _localProfile ? `Local · ${_localProfileInfo?.name || envId}` : `MoreLogin · ${envId}`;
34581
+ _localProfileTimezone = _localProfile ? (_localProfileInfo?.timezone || null) : null;
33236
34582
  _moreLoginConnected = true;
33237
- console.log(`[browser] Connected to MoreLogin env ${envId} via CDP at ${endpoint}`);
34583
+ console.log(`[browser] Connected to ${_localProfile ? `local profile ${envId}` : `MoreLogin env ${envId}`} via CDP at ${endpoint}`);
33238
34584
  } catch (err) {
34585
+ if (_localProfile) {
34586
+ // SynaBun's own profile: MoreLogin has no part in it, so no "open the MoreLogin app" advice.
34587
+ const refused = new Error(`Local profile ${_localProfileInfo?.name ? `"${_localProfileInfo.name}" (${_wantedEnvId})` : _wantedEnvId} could not be opened: ${err.message}. Nothing was opened elsewhere: ${options.moreloginEnvId ? 'a session asked for a profile never falls back to another profile or to Chrome' : 'sessions do not fall back to Chrome while a profile is the default browser'}.`);
34588
+ if (err?.code) refused.code = err.code;
34589
+ throw refused;
34590
+ }
33239
34591
  const port = moreLogin.getMoreLoginPort(savedCfg);
34592
+ if (err?.code === 'MORELOGIN_NOT_CHROMIUM' || err?.code === 'MORELOGIN_NOT_DEVTOOLS') {
34593
+ // MoreLogin is open and the profile exists: it is the profile's browser SynaBun cannot drive. No "open the
34594
+ // MoreLogin app" advice, and the code travels so the run's message does not add it either.
34595
+ const rule = options.moreloginEnvId
34596
+ ? 'a session asked for a MoreLogin profile never falls back to another profile or to Chrome'
34597
+ : 'sessions will not fall back to Chrome while MoreLogin is the default browser';
34598
+ const refused = new Error(`MoreLogin connect failed: ${err.message}. Nothing was opened elsewhere: ${rule}.`);
34599
+ refused.code = err.code;
34600
+ throw refused;
34601
+ }
34602
+ if (options.moreloginEnvId) {
34603
+ throw new Error(`MoreLogin connect failed for profile ${options.moreloginEnvId}: ${err.message}. Open the MoreLogin app (or check its Local API on :${port}) — a session asked for a MoreLogin profile never falls back to another profile or to Chrome.`);
34604
+ }
33240
34605
  throw new Error(`MoreLogin connect failed: ${err.message}. Open the MoreLogin app (or check its Local API on :${port}) — sessions will not fall back to Chrome while MoreLogin is the default browser.`);
33241
34606
  }
33242
34607
  }
@@ -33250,7 +34615,7 @@ async function createBrowserSession(options = {}) {
33250
34615
 
33251
34616
  const _browserLabel = _sourceBrowser === 'msedge' ? 'Edge' : _sourceBrowser === 'chromium' ? 'Chromium' : 'Chrome';
33252
34617
  const launchPersistentProfile = async (launchRoot, launchProfileDir, launchMode) => {
33253
- const launchArgs = [...stealthArgs];
34618
+ const launchArgs = [...chromiumArgs];
33254
34619
 
33255
34620
  // Kill orphan Chrome processes holding this user-data-dir BEFORE removing locks.
33256
34621
  // Otherwise launchPersistentContext hangs indefinitely waiting for the singleton.
@@ -33356,7 +34721,8 @@ async function createBrowserSession(options = {}) {
33356
34721
 
33357
34722
  const launchBrowser = launchContext;
33358
34723
  const existingPages = launchContext.pages();
33359
- const launchPage = await launchContext.newPage();
34724
+ // The session's tab opens behind the window's first tab (strict: never selected, never brought forward).
34725
+ const launchPage = await newSessionPage({ browser: launchContext.browser?.() || launchContext, context: launchContext, _profileMode: launchMode });
33360
34726
  for (const existing of existingPages) {
33361
34727
  await existing.close().catch(() => {});
33362
34728
  }
@@ -33441,8 +34807,13 @@ async function createBrowserSession(options = {}) {
33441
34807
  } else {
33442
34808
  // ── Standard: clean sandboxed browser ──
33443
34809
  browser = await chromium.launch(launchOpts);
33444
- context = await browser.newContext(contextOpts);
33445
- page = await context.newPage();
34810
+ // The context's CDP id lets its first tab be created in the background in that context.
34811
+ const created = backgroundTabsEnabled(loadBrowserConfig())
34812
+ ? await newContextWithId(browser, contextOpts)
34813
+ : { context: await browser.newContext(contextOpts), browserContextId: null };
34814
+ context = created.context;
34815
+ _browserContextId = created.browserContextId;
34816
+ page = await newSessionPage({ browser, context, _profileMode: 'clean', _browserContextId });
33446
34817
  }
33447
34818
 
33448
34819
  // ── Decrypt and inject cookies from Chrome profile (macOS) ──
@@ -33547,13 +34918,16 @@ async function createBrowserSession(options = {}) {
33547
34918
  cdpSession, // alias → active tab's CDP session (backward compat)
33548
34919
  _isPersistent,
33549
34920
  _profileMode: _profileMode || 'clean',
34921
+ _browserContextId,
33550
34922
  _profileSourceName: _profileSourceName || null,
33551
34923
  _storageStatePath: STORAGE_STATE_PATH,
33552
34924
  _launchUserDataDir: _launchUserDataDir || null,
33553
34925
  _launchProfileDirectory: _launchProfileDirectory || null,
33554
34926
  _selectedProfilePath: _sourceProfilePath || null,
33555
34927
  _chromeProcess: _chromeProcess || null, // CDP mode: spawned Chrome process
33556
- _mlEnvId: _mlEnvId || null, // MoreLogin env id (morelogin mode)
34928
+ _mlEnvId: _mlEnvId || null, // MoreLogin env id (morelogin mode), or a local profile's id
34929
+ _tzOverride: _localProfileTimezone || null, // a local profile's timezone, set on every tab SynaBun opens there
34930
+ _mlPinned: _profileMode === 'morelogin' && options._mlPinned === true, // opened for a schedule's own profile
33557
34931
  _mlDebugPort: _mlDebugPort || null,
33558
34932
  clients: new Set(), // WebSocket connections for screencast
33559
34933
  screencastActive: false,
@@ -33677,7 +35051,7 @@ async function createBrowserSession(options = {}) {
33677
35051
  // Handle context close (browser quit / crash)
33678
35052
  context.on('close', () => {
33679
35053
  const orphanedLoops = session._loopOwned?.size > 0 ? [...session._loopOwned] : [];
33680
- console.log(`Browser context closed for session ${sessionId}${session._agentOwnedSet?.size ? ` (agent-owned: ${[...session._agentOwnedSet].join(',')})` : ''}${orphanedLoops.length ? ` (orphaning loops: ${orphanedLoops.join(', ')})` : ''}`);
35054
+ console.log(`Browser context closed for session ${sessionId}${session._agentOwnedSet?.size ? ` (agent-owned: ${[...session._agentOwnedSet].join(',')})` : ''}${orphanedLoops.length ? ` (orphaning loops: ${orphanedLoops.map(logOwnerId).join(', ')})` : ''}`);
33681
35055
  session.screencastActive = false;
33682
35056
  detachScreencastFrameHandler(session);
33683
35057
  // Stop autosave interval
@@ -33844,37 +35218,55 @@ async function stopScreencast(session) {
33844
35218
  // ── Multi-tab helpers ──
33845
35219
 
33846
35220
  /**
33847
- * The page of a new tab, for every tab SynaBun opens in a browser the user
33848
- * shares with the runs (`_profileMode` morelogin or cdp): the first tab of a
33849
- * session (createBrowserSession, which has no session object yet and passes
33850
- * browser, context and mode), each further tab (createSessionTab) and the
33851
- * replacement of a wedged tab (recoverSessionTabPage).
35221
+ * The page of a new tab, for every tab SynaBun opens in any session: the first
35222
+ * tab of a session (createBrowserSession: MoreLogin, attached Chrome, the
35223
+ * managed / mirror / direct persistent launches and the clean launch, which
35224
+ * have no session object yet and pass browser, context and mode), each further
35225
+ * tab (createSessionTab) and the replacement of a wedged tab
35226
+ * (recoverSessionTabPage).
33852
35227
  *
33853
- * openTabsInBackground: true in browser-config.json (only that; not set or
33854
- * anything else, this is context.newPage() exactly as before) opens such a tab
33855
- * behind the selected one: the window is neither restored nor brought forward,
33856
- * and the tab is not the selected tab when it opens. It does not cover SynaBun's
33857
- * own windows (managed, mirror, direct and clean sessions), tabs a page opens
33858
- * itself, or what selects a tab afterwards (the user, or the selected tab
33859
- * closing next to it). A browser that cannot gets a normal tab.
35228
+ * Background tabs are on unless browser-config.json says
35229
+ * `openTabsInBackground: false` (backgroundTabsEnabled). On, the tab opens with
35230
+ * Target.createTarget { background: true } behind the selected one: the window
35231
+ * is neither restored nor brought forward and on macOS the user's Space does
35232
+ * not switch. Strict: one retry in the background, then BackgroundTabError;
35233
+ * never context.newPage(), which selects the tab and activates the window. Not
35234
+ * covered: tabs a page opens itself, what selects a tab afterwards, and the
35235
+ * window a launch itself puts on screen. Off, this is context.newPage().
33860
35236
  *
33861
35237
  * Every page it returns is recorded in synabunOpenedPages: an explicit close
33862
35238
  * of such a session closes those, and only those (closeOwnTabsBeforeDisconnect).
33863
35239
  */
33864
35240
  async function newSessionPage(session, { timeoutMs } = {}) {
33865
- if (loadBrowserConfig().openTabsInBackground === true && (session._profileMode === 'morelogin' || session._profileMode === 'cdp')) {
33866
- const page = await openBackgroundPage(session.browser, session.context, timeoutMs ? { timeoutMs } : undefined).catch(() => null);
33867
- if (page) {
33868
- synabunOpenedPages.add(page);
33869
- return page;
33870
- }
33871
- console.warn('[browser] could not open the tab in the background; opening it as the selected tab');
35241
+ let page;
35242
+ if (backgroundTabsEnabled(loadBrowserConfig())) {
35243
+ page = await openBackgroundPageStrict(session.browser, session.context, {
35244
+ ...(timeoutMs && { timeoutMs }),
35245
+ ...(session._browserContextId && { browserContextId: session._browserContextId }),
35246
+ });
35247
+ } else {
35248
+ page = await session.context.newPage();
33872
35249
  }
33873
- const page = await session.context.newPage();
33874
35250
  synabunOpenedPages.add(page);
35251
+ // A local profile's timezone (lib/local-profiles.js). Its Chrome is started with TZ, which Chrome on Windows does
35252
+ // not read: the tabs SynaBun opens there are told over DevTools too. The CDP session stays with the page (the
35253
+ // override ends when it detaches). Best effort: a tab without it still has the timezone of the profile's start.
35254
+ if (session._tzOverride) await applyPageTimezone(session.context, page, session._tzOverride);
33875
35255
  return page;
33876
35256
  }
33877
35257
 
35258
+ /**
35259
+ * Tells one page its timezone over DevTools (`Emulation.setTimezoneOverride`). The CDP session stays with the page:
35260
+ * the override ends when it detaches. Best effort, never throws: a tab without it still has the timezone its Chrome
35261
+ * was started with.
35262
+ */
35263
+ async function applyPageTimezone(context, page, timezoneId) {
35264
+ try {
35265
+ const tzSession = await context.newCDPSession(page);
35266
+ await tzSession.send('Emulation.setTimezoneOverride', { timezoneId });
35267
+ } catch (err) { console.warn(`[browser] timezone ${timezoneId} not set on a new tab: ${err.message}`); }
35268
+ }
35269
+
33878
35270
  // The pages newSessionPage opened. In a browser the user owns (MoreLogin, their Chrome over CDP) context.pages() is
33879
35271
  // the whole browser: the user's tabs, other sessions' tabs and what pages opened. A page is SynaBun's to close only
33880
35272
  // when it is in here; one that was open before SynaBun connected, or that someone else opened, never is.
@@ -33943,8 +35335,8 @@ async function recoverSessionTabPage(session, sessionId, tabId, reason = 'page b
33943
35335
  };
33944
35336
  try {
33945
35337
  replacementPage = await withBrowserOperationDeadline(
33946
- // A background attempt gets half of the step, so a normal tab still fits after it.
33947
- newSessionPage(session, { timeoutMs: BROWSER_RECOVERY_STEP_DEADLINE_MS / 2 }),
35338
+ // Two background attempts (strict, no foreground tab) share the step.
35339
+ newSessionPage(session, { timeoutMs: BROWSER_RECOVERY_STEP_DEADLINE_MS / 3 }),
33948
35340
  BROWSER_RECOVERY_STEP_DEADLINE_MS,
33949
35341
  'Creating replacement browser tab',
33950
35342
  {
@@ -34453,6 +35845,33 @@ function browserCaller(req) {
34453
35845
  if (req && typeof req === 'object') { try { Object.defineProperty(req, BROWSER_CALLER, { value: caller, configurable: true }); } catch { /* frozen */ } }
34454
35846
  return caller;
34455
35847
  }
35848
+ // ── A session id as a log shows it (re-review of 2026-11-10: session ids in logs) ──
35849
+ // An Mcp-Session-Id is all a client needs to send requests on an MCP session (the SDK checks nothing else), and a
35850
+ // session with a proof can pick its MoreLogin profile: the whole id is a bearer. mcp-server/src/http.ts prints its
35851
+ // first 8 characters (sessionLogId); this server printed it whole wherever an owner key reached a log line: the browser
35852
+ // gate's refusals, the MoreLogin stop and close refusals, the release warning of a closed session, and the name of
35853
+ // the per-owner log file (data/logs/loop-<id>.log) of every browser acquisition and `browser:profile` line.
35854
+ /**
35855
+ * `id` as a log line may show it. An MCP session's id (a proof of kind 'mcp-session', or an id of the shape the MCP
35856
+ * transport mints, a UUID, that holds no other proof) is cut to its first 8 characters and "…", like sessionLogId. A
35857
+ * run's id is not a bearer (it is nothing without its terminal token) and stays whole, up to 128 characters, so a
35858
+ * log still finds the run.
35859
+ */
35860
+ function logOwnerId(id) {
35861
+ let kind = null;
35862
+ try { kind = _terminalTokens.kindOf(String(id ?? '')) || null; } catch { kind = null; }
35863
+ // A proof of another kind (a run's token) is never cut, even for an id of the UUID shape.
35864
+ if (kind && kind !== 'mcp-session') return String(id ?? '').slice(0, 128);
35865
+ return logIdOf(id, kind === 'mcp-session');
35866
+ }
35867
+ /**
35868
+ * loopLog for every caller in this file. An MCP session's lines go to a file named by its 8 characters and a digest
35869
+ * of the whole id (lib/loop-logger.js loopLogFileKey, finding 5 of the re-review of 2026-11-11), never by the id.
35870
+ */
35871
+ function loopLog(ownerKey, tag, msg, meta = undefined) {
35872
+ const mcpSession = !!ownerKey && logOwnerId(ownerKey).endsWith('…');
35873
+ return writeLoopLog(ownerKey, tag, msg, meta, { mcpSession });
35874
+ }
34456
35875
  /** The answer to a request that names a run it cannot prove it is (TERMINAL_TOKEN_REQUIRED / TERMINAL_TOKEN_INVALID). */
34457
35876
  function refuseBrowserCaller(res, caller) {
34458
35877
  return res.status(caller.httpStatus || 403).json({ error: caller.error, code: caller.code });
@@ -34512,18 +35931,35 @@ function browserSessionCountRead(req, caller = browserCaller(req)) {
34512
35931
  function browserTerminalGate(req, res, next) {
34513
35932
  const caller = browserCaller(req);
34514
35933
  if (!caller.accepted) {
34515
- noteRefusedBrowserCaller(`${caller.code}:${String(caller.asserted).slice(0, 128)}`, `[browser] ${req.method} ${String(req.path || '').slice(0, 80)} refused: ${caller.code} (X-Synabun-Terminal ${String(caller.asserted).slice(0, 128)})`);
35934
+ noteRefusedBrowserCaller(`${caller.code}:${String(caller.asserted).slice(0, 128)}`, `[browser] ${req.method} ${String(req.path || '').slice(0, 80)} refused: ${caller.code} (X-Synabun-Terminal ${logOwnerId(caller.asserted)})`);
34516
35935
  return refuseBrowserCaller(res, caller);
34517
35936
  }
34518
35937
  const automationRoute = isAutomationBrowserRoute(req.method, req.path);
34519
- if (caller.id && automationRoute) return next();
35938
+ if (caller.id && automationRoute) {
35939
+ // The caller's MoreLogin profile pin, before any browser route runs (callerProfileRefusal; review b6631e9d):
35940
+ // • an id that holds a pin and was not proven by this request reaches nothing (finding 2), its release included
35941
+ // (an unproven caller never closes a pinned session's tab);
35942
+ // • an agent's pin whose profile is not on the owner's list is refused every route that opens or drives a page.
35943
+ // It still lists the sessions, releases and closes what it holds, so it can leave the profile cleanly.
35944
+ const pinRefused = callerProfileRefusal(caller);
35945
+ if (pinRefused) {
35946
+ const method = String(req.method || 'GET').toUpperCase();
35947
+ const bare = String(req.path || '').replace(/\/$/, '');
35948
+ const leaving = (method === 'GET' && bare === '/sessions') || (method === 'POST' && bare === '/release') || (method === 'DELETE' && /^\/sessions\/[^/]+$/.test(bare));
35949
+ if (pinRefused.code === 'PROFILE_PIN_UNVERIFIED' || !leaving) {
35950
+ noteRefusedBrowserCaller(`${pinRefused.code}:${String(caller.id).slice(0, 128)}`, `[browser] ${req.method} ${String(req.path || '').slice(0, 80)} refused: ${pinRefused.code} (X-Synabun-Terminal ${logOwnerId(caller.id)})`);
35951
+ return res.status(pinRefused.status).json({ ok: false, code: pinRefused.code, error: pinRefused.error });
35952
+ }
35953
+ }
35954
+ return next();
35955
+ }
34520
35956
  // The owner's page; an invite guest the guest rules let use the browser, on the browser panel's routes only.
34521
35957
  if (automationRoute ? browserPageOwner(req) : browserOwnerPageOnly(req)) return next();
34522
35958
  if (browserSessionCountRead(req, caller)) return next();
34523
35959
  let guest = false;
34524
35960
  try { guest = !!isGuestRequest(req); } catch { guest = true; }
34525
35961
  if (caller.id || guest) {
34526
- noteRefusedBrowserCaller(`OWNER_ROUTE:${String(req.path || '').slice(0, 80)}`, `[browser] ${req.method} ${String(req.path || '').slice(0, 80)} refused: OWNER_ROUTE (automation ${String(caller.id).slice(0, 128)})`);
35962
+ noteRefusedBrowserCaller(`OWNER_ROUTE:${String(req.path || '').slice(0, 80)}`, `[browser] ${req.method} ${String(req.path || '').slice(0, 80)} refused: OWNER_ROUTE (automation ${logOwnerId(caller.id)})`);
34527
35963
  return res.status(403).json({ ok: false, code: 'OWNER_ROUTE', error: 'This browser route is the owner\'s (SynaBun\'s page: the browser settings, the money guard, CDP, tab management). An automation drives the browser through SynaBun\'s browser tools only.' });
34528
35964
  }
34529
35965
  if (caller.automation) {
@@ -34555,7 +35991,7 @@ function refuseNotOwnerPage(req, res, error) {
34555
35991
  function browserSocketRefusal(req, sessionId) {
34556
35992
  if (browserPageOwner(req)) return null;
34557
35993
  const who = browserCaller(req);
34558
- const logRefusal = (code) => noteRefusedBrowserCaller(`ws:${code}:${String(who.asserted || '').slice(0, 128)}`, `[ws-browser] socket for session ${String(sessionId).slice(0, 80)} refused: ${code}${who.asserted ? ` (X-Synabun-Terminal ${String(who.asserted).slice(0, 128)})` : ''}`);
35994
+ const logRefusal = (code) => noteRefusedBrowserCaller(`ws:${code}:${String(who.asserted || '').slice(0, 128)}`, `[ws-browser] socket for session ${String(sessionId).slice(0, 80)} refused: ${code}${who.asserted ? ` (X-Synabun-Terminal ${logOwnerId(who.asserted)})` : ''}`);
34559
35995
  if (!who.accepted) { logRefusal(who.code); return { status: who.httpStatus || 403, code: who.code }; }
34560
35996
  if (!who.automation) {
34561
35997
  let down = null;
@@ -34583,7 +36019,7 @@ function trackRoute(session, identityKey, tabId, source) {
34583
36019
  const key = identityKey || 'anon';
34584
36020
  const prev = session._routeLog.get(key);
34585
36021
  if (prev && prev.tabId !== tabId) {
34586
- console.warn(`[browser] route-change: id=${key} tab ${prev.tabId} (${prev.source}) → ${tabId} (${source})`);
36022
+ console.warn(`[browser] route-change: id=${logOwnerId(key)} tab ${prev.tabId} (${prev.source}) → ${tabId} (${source})`);
34587
36023
  }
34588
36024
  session._routeLog.set(key, { tabId, source, count: (prev?.count || 0) + 1, lastSeen: Date.now() });
34589
36025
  }
@@ -34615,7 +36051,7 @@ function getTargetPage(session, req) {
34615
36051
  const tab = session.tabs?.get(tabId);
34616
36052
  if (!tab) return null;
34617
36053
  if (isAutomation && ownTabId !== tabId) {
34618
- console.warn(`[browser] tab-not-owned: refusing explicit tab ${String(tabId).slice(0, 40)} to an automation that does not own it (id=${terminalId || 'none'})`);
36054
+ console.warn(`[browser] tab-not-owned: refusing explicit tab ${String(tabId).slice(0, 40)} to an automation that does not own it (id=${terminalId ? logOwnerId(terminalId) : 'none'})`);
34619
36055
  return null;
34620
36056
  }
34621
36057
  trackRoute(session, terminalId, tabId, 'explicit-tab');
@@ -34638,7 +36074,7 @@ function getTargetPage(session, req) {
34638
36074
  // 3. An automation that owns no open tab here: FAIL CLOSED. It never inherits another automation's tab, a tab nobody
34639
36075
  // owns, or the owner's manual tab; the MCP-side recovery acquires it a fresh owned tab instead.
34640
36076
  if (isAutomation) {
34641
- console.warn(`[browser] tab-pin-missing: refusing a tab the automation does not own (id=${terminalId || 'none'}, tabs=${session.tabs?.size ?? 0}, owners=${sessionOwnerCount(session)}) — returning 404 to avoid cross-automation leak`);
36077
+ console.warn(`[browser] tab-pin-missing: refusing a tab the automation does not own (id=${terminalId ? logOwnerId(terminalId) : 'none'}, tabs=${session.tabs?.size ?? 0}, owners=${sessionOwnerCount(session)}) — returning 404 to avoid cross-automation leak`);
34642
36078
  return null;
34643
36079
  }
34644
36080
 
@@ -34722,7 +36158,16 @@ app.use('/api/browser/sessions/:id', (req, res, next) => {
34722
36158
  const session = browserSessions.get(req.params.id);
34723
36159
  if (!session) return next();
34724
36160
  const cfg = loadBrowserConfig();
34725
- if (cfg.connectMode !== 'morelogin' || sessionServesMoreLoginDefault(session, cfg)) return next();
36161
+ // A run pinned to a MoreLogin profile of its own (its schedule's) acts on that profile's session only.
36162
+ const callerPin = runMoreLoginPin(browserOwnerId(browserCaller(req).id));
36163
+ if (sessionServesRun(session, cfg, browserOwnerId(browserCaller(req).id))) return next();
36164
+ // (A pin this caller may not use was refused by browserTerminalGate in front: callerProfileRefusal.)
36165
+ if (callerPin) {
36166
+ return res.status(409).json({
36167
+ error: `Session ${req.params.id} is not this run's browser (${session._profileMode || 'unknown'} mode${session._mlEnvId ? `, MoreLogin env ${session._mlEnvId}` : ''}; this run is set to ${describeMoreLoginPin(callerPin)}), so SynaBun's browser tools do not act on it. Leave sessionId out: browser_navigate opens the page in this run's profile.`,
36168
+ code: 'NOT_DEFAULT_BROWSER',
36169
+ });
36170
+ }
34726
36171
  const envId = moreLoginDefaultEnvId(cfg);
34727
36172
  res.status(409).json({
34728
36173
  error: `Session ${req.params.id} is not the default browser (${session._profileMode || 'unknown'} mode${session._mlEnvId ? `, MoreLogin env ${session._mlEnvId}` : ''}; the default is MoreLogin${envId ? ` env ${envId}` : ''}), so SynaBun's browser tools do not act on it. Leave sessionId out: browser_navigate opens the page in the default browser.`,
@@ -34763,6 +36208,7 @@ app.get('/api/browser/sessions', (req, res) => {
34763
36208
  // run's or the owner's tabs, nor the session's address and title, which are its active tab's (2026-11-05: workers
34764
36209
  // listed every tab of the shared MoreLogin session and could not tell theirs).
34765
36210
  const automationView = who.automation && !revealOwners;
36211
+ const callerPin = who.automation ? runMoreLoginPin(caller) : null;
34766
36212
  const liveUrl = (t) => { try { return t.page?.url?.() || t.url; } catch { return t.url; } };
34767
36213
  const sessions = [...browserSessions.entries()].map(([id, s]) => {
34768
36214
  const allTabs = s.tabs ? [...s.tabs.entries()] : [];
@@ -34779,7 +36225,8 @@ app.get('/api/browser/sessions', (req, res) => {
34779
36225
  profileMode: s._profileMode || 'clean',
34780
36226
  profileSource: s._profileSourceName || null,
34781
36227
  moreloginEnvId: s._mlEnvId || null,
34782
- servesDefault: moreLoginDefault ? sessionServesMoreLoginDefault(s, policyCfg) : true,
36228
+ // For a run pinned to a MoreLogin profile of its own, "the default" is that profile's session (sessionServesRun).
36229
+ servesDefault: callerPin ? sessionServesMoreLoginEnv(s, callerPin.envId) : (moreLoginDefault ? sessionServesMoreLoginDefault(s, policyCfg) : true),
34783
36230
  // The browser's own CDP endpoint drives every tab past every check here: the owner's page's only.
34784
36231
  wsEndpoint: who.automation || s._isPersistent ? null : (s.browser.wsEndpoint?.() || null),
34785
36232
  activeTabId: automationView ? (ownTabId && s.activeTabId === ownTabId ? ownTabId : null) : (s.activeTabId || null),
@@ -34805,10 +36252,18 @@ app.get('/api/browser/sessions', (req, res) => {
34805
36252
  const yourRoute = caller ? liveAutomationRoute(caller, { cfg: policyCfg }) : null;
34806
36253
  res.json({
34807
36254
  sessions,
34808
- defaultBrowser: moreLoginDefault
36255
+ defaultBrowser: callerPin
36256
+ ? { connectMode: 'morelogin', moreloginEnvId: callerPin.envId }
36257
+ : moreLoginDefault
34809
36258
  ? { connectMode: 'morelogin', moreloginEnvId: moreLoginDefaultEnvId(policyCfg) }
34810
36259
  : { connectMode: policyCfg.connectMode || null },
34811
36260
  ...(yourRoute ? { yourRoute: { sessionId: yourRoute.browserSessionId, tabId: yourRoute.browserTabId } } : {}),
36261
+ // The MoreLogin profile this caller works in when it is not the default (its launch's, or its own choice: POST
36262
+ // /api/morelogin/use). The MCP reads it to move a run whose pinned tab is in a browser it left.
36263
+ ...(callerPin ? { yourProfile: { envId: callerPin.envId, name: callerPin.name || null } } : {}),
36264
+ // The caller chose its browser itself (a profile, or back to the default): a run's launch tab may be in the
36265
+ // browser it left, and its MCP then moves it instead of failing the run.
36266
+ ...(caller && who.automation && _profileChoiceStore.get(caller) !== undefined ? { profileChosen: true } : {}),
34812
36267
  // POST /api/loop/recover-browser records a run's move to a tab of its own (`adopt`): an MCP asks it only of a
34813
36268
  // server that says so (an older one reads the request as a recovery and opens a tab).
34814
36269
  adoptRoute: true,
@@ -34819,10 +36274,15 @@ app.post('/api/browser/sessions', async (req, res) => {
34819
36274
  const { url, width, height, screenWidth, screenHeight, deviceScaleFactor, timezone, connectMode, moreloginEnvId } = req.body;
34820
36275
  // Which browser or MoreLogin profile a session starts on is the owner's choice (Settings → Browser): an automation's
34821
36276
  // create opens the default browser and names neither (lib/browser-automation-routes.js; review 972afb74, finding 1).
36277
+ // N1 (re-review of 2026-11-10): the check asked `creator.automation` only, so an invite guest with the `browser`
36278
+ // permission (browserTerminalGate lets a guest reach this route: browserPageOwner) who knew a profile's id opened
36279
+ // that profile, any account, past the owner's list. Now only the owner's page itself (its page secret, never a
36280
+ // guest, no run or agent header: browserOwnerPageOnly) names either field; a guest's create opens the default browser.
34822
36281
  const creator = browserCaller(req);
34823
- const ownerFields = creator.automation ? ownerOnlyCreateFields(req.body) : [];
36282
+ const ownerFields = (creator.automation || !browserOwnerPageOnly(req)) ? ownerOnlyCreateFields(req.body) : [];
34824
36283
  if (ownerFields.length) {
34825
- return res.status(403).json({ ok: false, code: 'OWNER_ONLY_FIELDS', fields: ownerFields, error: `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.` });
36284
+ const guestCreate = !creator.automation;
36285
+ 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.` });
34826
36286
  }
34827
36287
  // A create-session startUrl that points at one of SynaBun's own live OpenCode serve ports is refused up front, like
34828
36288
  // navigate and new-tab: the serve's API can change what a worker session may do, and createBrowserSession navigates
@@ -34849,6 +36309,25 @@ app.post('/api/browser/sessions', async (req, res) => {
34849
36309
  const who = browserCaller(req);
34850
36310
  if (!who.accepted) return refuseBrowserCaller(res, who);
34851
36311
  const creatorTerminalId = browserOwnerId(who.id);
36312
+ // An automation that works in a MoreLogin profile of its own (its launch's, or its own choice: POST
36313
+ // /api/morelogin/use) gets a tab of its own in that profile's one browser, like every other owner there, never a
36314
+ // second connection to it and never the default browser. `handedOver` tells the MCP the tab is at about:blank.
36315
+ const creatorPin = who.automation && creatorTerminalId ? runMoreLoginPin(creatorTerminalId) : null;
36316
+ if (creatorPin) {
36317
+ const outcome = await browserStartHandoff.run(`acquire:${creatorTerminalId}`, async () => {
36318
+ const acq = await acquireSharedBrowserTab({ ownerKey: creatorTerminalId, ownerType: 'interactive', logTag: 'create:profile' });
36319
+ if (acq.error) throw Object.assign(new Error(acq.error), { acquisition: acq });
36320
+ return acq;
36321
+ }, {
36322
+ gone: browserCallerGone(req, res),
36323
+ waitMs: startWaitMs(req.browserRequest?.deadline),
36324
+ alive: (acq) => startedTabAlive(acq.browserSessionId, acq.browserTabId, creatorTerminalId),
36325
+ onUnclaimed: (acq, info) => closeUnclaimedBrowserStart(acq.browserSessionId, creatorTerminalId, { tabId: acq.browserTabId, since: info?.parkedAt, run: creatorTerminalId }),
36326
+ });
36327
+ if (outcome.pending) return res.status(202).json(browserStartingAnswer('create'));
36328
+ const acq = outcome.value;
36329
+ return res.json({ sessionId: acq.browserSessionId, tabId: acq.browserTabId || null, url: 'about:blank', wsEndpoint: null, profileMode: 'morelogin', profileSource: `${profileKindLabel(creatorPin.envId) === 'local profile' ? 'Local' : 'MoreLogin'} · ${creatorPin.envId}`, shared: true, handedOver: outcome.from !== 'started' ? outcome.from : 'profile' });
36330
+ }
34852
36331
  // The start, its owner and its broadcast: once per start, whoever ends up with it.
34853
36332
  const start = async () => {
34854
36333
  const result = await createBrowserSession({
@@ -34891,6 +36370,8 @@ app.post('/api/browser/sessions', async (req, res) => {
34891
36370
  });
34892
36371
  } catch (err) {
34893
36372
  console.error('Browser session create error:', err.message);
36373
+ const acq = err?.acquisition;
36374
+ if (acq) return res.status(500).json({ error: acq.error, ...(acq.code ? { code: acq.code, offenders: acq.offenders } : {}) });
34894
36375
  res.status(500).json(browserStartFailure(err));
34895
36376
  }
34896
36377
  });
@@ -34908,12 +36389,12 @@ app.delete('/api/browser/sessions/:id', async (req, res) => {
34908
36389
  // An automation closes only a session it works in (a tab of its own, or a hold on the session): the owner's manual
34909
36390
  // session, or a session nobody holds, is the owner's to close (review 972afb74, finding 4).
34910
36391
  if (decision.action === 'refuse') {
34911
- console.warn(`[browser] close of session ${req.params.id} by ${caller} refused: it owns no tab and holds nothing there`);
36392
+ console.warn(`[browser] close of session ${req.params.id} by ${logOwnerId(caller)} refused: it owns no tab and holds nothing there`);
34912
36393
  return res.status(403).json({ ok: false, code: 'NOT_OWNED', error: `Session ${req.params.id} is not yours to close: you have no tab in it. Close only the sessions you opened; the owner closes the others from SynaBun's page.` });
34913
36394
  }
34914
36395
  if (decision.action === 'release') {
34915
36396
  await releaseSharedBrowserTab(req.params.id, caller);
34916
- console.warn(`[browser] close of shared session ${req.params.id} by ${caller}: kept for ${decision.others.length} other owner(s) (${decision.others.join(', ')}); ${decision.ownTabId ? `closed only its tab ${decision.ownTabId}` : 'it had no tab of its own there'}`);
36397
+ console.warn(`[browser] close of shared session ${req.params.id} by ${logOwnerId(caller)}: kept for ${decision.others.length} other owner(s) (${decision.others.map(logOwnerId).join(', ')}); ${decision.ownTabId ? `closed only its tab ${decision.ownTabId}` : 'it had no tab of its own there'}`);
34917
36398
  return res.json({ ok: true, sessionKept: true, releasedTabId: decision.ownTabId, otherOwners: decision.others.length });
34918
36399
  }
34919
36400
  // An explicit close (browser_session close, the UI): in MoreLogin or the user's Chrome, the tabs SynaBun opened for it close too.
@@ -35283,17 +36764,45 @@ app.post('/api/browser/sessions/:id/navigate', async (req, res) => {
35283
36764
  retryAfterMs: circuit.remainingMs,
35284
36765
  });
35285
36766
  }
36767
+ // A new navigation of this tab ends the delayed probe an earlier slow load left on it.
36768
+ session._slowLoadProbes?.get(routed.tabId)?.cancel();
36769
+ // Whether the main frame committed the requested document (or its redirect target) while the
36770
+ // goto ran: a timeout after that is a slow page (x.com's cold first load), answered below,
36771
+ // never a wedged tab to reset. Its listeners go on every exit (finally below).
36772
+ let commit = null;
35286
36773
  try {
35287
36774
  await humanThink(session, req, true);
35288
36775
  markBrowserActionStarted(req);
35289
- const response = await measureBrowserPhase('action', () => routed.page.goto(url, { waitUntil: 'domcontentloaded', timeout: browserActionTimeout(req, 15000) }));
36776
+ commit = trackMainDocumentCommit(routed.page, url);
36777
+ // Answer once the document commits (the action timeout still bounds the commit), then give
36778
+ // DOMContentLoaded a short, never-failing wait: callers learn which one they got (loadState).
36779
+ const navTimeout = browserActionTimeout(req, 15000);
36780
+ const response = await measureBrowserPhase('action', () => routed.page.goto(url, { waitUntil: 'commit', timeout: navTimeout })
36781
+ .finally(() => commit.stop()));
35290
36782
  let httpStatus = null;
35291
36783
  try { httpStatus = response ? response.status() : null; } catch { httpStatus = null; }
35292
36784
  clearBrowserNavigationWedge(session, routed.tabId, url);
36785
+ const wantsSnapshot = !!(snapshot && snapshot !== 'none') || !!returnSnapshot;
36786
+ // An explicit snapshot waits for DCL within the old budget, so it never captures a document
36787
+ // still being replaced ("Page navigated during capture"); otherwise only the short cap.
36788
+ const loadState = await waitForDomContentLoadedCapped(routed.page,
36789
+ wantsSnapshot ? navTimeout : Math.min(NAVIGATE_DCL_CAP_MS, navTimeout));
36790
+ if (wantsSnapshot && loadState !== 'domcontentloaded') {
36791
+ // What a DCL timeout answered before: a slow page, read later, probed once.
36792
+ res.json({ ok: true, url: routed.page.url(), title: '', slowLoad: true, loadState, notice: SLOW_NAVIGATION_NOTICE });
36793
+ scheduleSlowLoadRecheck(session, req.params.id, routed, req, url, new Error(`Timeout ${navTimeout}ms exceeded waiting for DOMContentLoaded`));
36794
+ return;
36795
+ }
35293
36796
  const state = await getBrowserActionState(session, routed, compact);
35294
36797
  const blocked = moreLoginBlockError(session, url, state.url);
35295
36798
  if (blocked) return res.status(502).json({ error: blocked, moreLoginBlocked: true, landedUrl: state.url });
35296
- const body = { ok: true, url: state.url, title: state.title };
36799
+ const body = { ok: true, url: state.url, title: state.title, loadState };
36800
+ if (httpStatus != null) body.status = httpStatus;
36801
+ if (loadState === 'commit') {
36802
+ body.notice = PAGE_STILL_PARSING_NOTICE;
36803
+ // Nobody waited for this page to parse: one delayed liveness probe still resets a dead tab.
36804
+ scheduleSlowLoadRecheck(session, req.params.id, routed, req, url, new Error(`DOMContentLoaded did not arrive within ${NAVIGATE_DCL_CAP_MS}ms`));
36805
+ }
35297
36806
  if (snapshot && snapshot !== 'none') {
35298
36807
  await settleAfterAction(routed.page);
35299
36808
  const snap = await buildSnapshotResponse(routed.page, {
@@ -35312,18 +36821,19 @@ app.post('/api/browser/sessions/:id/navigate', async (req, res) => {
35312
36821
  }).catch(err => ({ snapshot: null, snapshotError: err.message }));
35313
36822
  Object.assign(body, snap);
35314
36823
  }
35315
- // Bounded, value-free context for the page-state judgment, in the same round
35316
- // trip. A plain DOM scan (never a snapshot, which would replace the refs just
35317
- // delivered), time-boxed, and its failure never fails the navigation.
35318
- if (req.body.semanticContext === true && req.get('X-Synabun-Batch') !== '1') {
35319
- try {
35320
- if (!(snapshot && snapshot !== 'none')) await settleAfterAction(routed.page);
35321
- body.semanticContext = await runBrowserRequest(req, () => measureBrowserPhase('semanticContext',
35322
- () => collectSemanticContext(routed.page, { purpose: 'navigation', httpStatus })), 1500);
35323
- } catch { body.semanticContextError = 'unavailable'; }
35324
- }
36824
+ // No page-state judgment here any more (2026-11-08): it cost a settle and a DOM scan per
36825
+ // navigate. browser_batch asks for its one assessment through the context route.
35325
36826
  res.json(body);
35326
36827
  } catch (err) {
36828
+ commit?.stop();
36829
+ if (navigationLandedDespiteTimeout(err, { committed: commit?.committed === true, url: routed.page.url() })) {
36830
+ // The document is there and still loading; its renderer may be too busy for a probe, a
36831
+ // snapshot or a title. Answer what is known and let the next call read the page; a
36832
+ // delayed, bounded probe (below) still resets a tab that turns out to be dead.
36833
+ res.json({ ok: true, url: routed.page.url(), title: '', slowLoad: true, notice: SLOW_NAVIGATION_NOTICE });
36834
+ scheduleSlowLoadRecheck(session, req.params.id, routed, req, url, err);
36835
+ return;
36836
+ }
35327
36837
  const recovery = await recoverBrowserRouteFailure(session, req.params.id, routed, req, 'navigate', err);
35328
36838
  if (recovery?.recovered) rememberBrowserNavigationWedge(session, routed.tabId, url, err);
35329
36839
  res.status(500).json({
@@ -35332,9 +36842,34 @@ app.post('/api/browser/sessions/:id/navigate', async (req, res) => {
35332
36842
  ...(recovery?.sessionInvalidated && { sessionInvalidated: true }),
35333
36843
  ...(recovery?.wedgedTabRetired && { wedgedTabRetired: true }),
35334
36844
  });
36845
+ } finally {
36846
+ commit?.stop();
35335
36847
  }
35336
36848
  });
35337
36849
 
36850
+ /**
36851
+ * The delayed liveness probe of a slow load (lib/browser-tab-recovery.js scheduleSlowLoadProbe):
36852
+ * after the answer went out, ask the tab once; a dead one gets the recovery a failed navigate
36853
+ * gets (reset, and the URL on the two-minute circuit). One probe per tab: a new navigate, the
36854
+ * tab's close, its replacement or a new document in it cancels it.
36855
+ */
36856
+ function scheduleSlowLoadRecheck(session, sessionId, routed, req, url, err) {
36857
+ if (!session._slowLoadProbes) session._slowLoadProbes = new Map();
36858
+ session._slowLoadProbes.get(routed.tabId)?.cancel();
36859
+ const isCurrent = () => !session._invalidating && browserSessions.get(sessionId) === session
36860
+ && session.tabs.get(routed.tabId)?.page === routed.page;
36861
+ const probe = scheduleSlowLoadProbe(routed.page, {
36862
+ isCurrent,
36863
+ onDead: async (probeError) => {
36864
+ const failure = Object.assign(new Error(`${err.message}; the slow page then failed its liveness probe: ${probeError.message}`), { code: probeError.code });
36865
+ const recovery = await recoverBrowserRouteFailure(session, sessionId, routed, req, 'navigate', failure);
36866
+ if (recovery?.recovered) rememberBrowserNavigationWedge(session, routed.tabId, url, failure);
36867
+ },
36868
+ });
36869
+ session._slowLoadProbes.set(routed.tabId, probe);
36870
+ probe.done.finally(() => { if (session._slowLoadProbes?.get(routed.tabId) === probe) session._slowLoadProbes.delete(routed.tabId); });
36871
+ }
36872
+
35338
36873
  app.post('/api/browser/sessions/:id/back', async (req, res) => {
35339
36874
  const session = browserSessions.get(req.params.id);
35340
36875
  if (!session) return res.status(404).json({ error: 'Session not found' });
@@ -35999,6 +37534,9 @@ app.post('/api/browser/sessions/:id/snapshot', async (req, res) => {
35999
37534
  const { selector: rawSel, mode, viewport, depth, diff, force, maxChars, baselineId, includeFullText } = req.body || {};
36000
37535
  const scopeSel = rawSel ? normalizeSelector(rawSel) : null;
36001
37536
  try {
37537
+ // A page browser_navigate answered at commit may still be parsing: let it, briefly, so the
37538
+ // capture does not race the document ("Page navigated during capture").
37539
+ await waitForDomContentLoadedCapped(routed.page, SNAPSHOT_DCL_WAIT_MS);
36002
37540
  const payload = await buildSnapshotResponse(routed.page, {
36003
37541
  scopeSel, mode, viewport, depth, diff, force, maxChars, baselineId, includeFullText: includeFullText === true,
36004
37542
  ...snapshotRequestOptions(req, res, req.params.id, routed),
@@ -36739,18 +38277,32 @@ app.get('/api/browser/config', async (req, res) => {
36739
38277
  || (await moreLogin.probeMoreLoginApi({ savedCfg: config, timeout: 1500 })).running;
36740
38278
  } catch {}
36741
38279
  const unreadable = browserConfigUnreadable(config);
36742
- res.json({ config, detectedPath: detected, chromeRunning, attachSeeded, moreloginInstalled, ...(unreadable && { configError: `browser-config.json is unreadable (${unreadable}); saving these settings replaces it` }) });
38280
+ res.json({ config, backgroundTabs: backgroundTabsEnabled(config), detectedPath: detected, chromeRunning, attachSeeded, moreloginInstalled, ...(unreadable && { configError: `browser-config.json is unreadable (${unreadable}); saving these settings replaces it` }) });
36743
38281
  });
36744
38282
 
36745
- app.put('/api/browser/config', (req, res) => {
38283
+ app.put('/api/browser/config', async (req, res) => {
36746
38284
  try {
36747
38285
  // Full replacement — the frontend sends the complete config object
36748
38286
  const body = validateBrowserLanguageConfig(req.body || {});
38287
+ // Finding 1 of the re-review of 2026-11-11: only the owner's page changes the default AI browser (connect mode,
38288
+ // default MoreLogin profile). browserTerminalGate already keeps this route from automations; this is the route's own.
38289
+ if (browserDefaultChangeRefused(req, body, loadBrowserConfig())) return refuseDefaultBrowserChange(res);
36749
38290
  if (body.connectMode !== undefined) body.connectMode = ['attach', 'morelogin'].includes(body.connectMode) ? body.connectMode : 'mirror';
36750
38291
  if (body.attachSeed !== undefined) body.attachSeed = body.attachSeed === 'fresh' ? 'fresh' : 'real';
36751
38292
  if (body.moreloginEnvId !== undefined && body.moreloginEnvId !== null && body.moreloginEnvId !== '') body.moreloginEnvId = String(body.moreloginEnvId);
38293
+ // The default MoreLogin profile is driven over CDP: a newly chosen one known to be Firefox-type is refused. The
38294
+ // one already in use as the default may be saved back with the rest of the form.
38295
+ if (body.connectMode === 'morelogin' && body.moreloginEnvId) {
38296
+ const before = loadBrowserConfig();
38297
+ await refuseFirefoxMoreLoginChoice({ moreloginEnvId: body.moreloginEnvId }, before.connectMode === 'morelogin' ? before.moreloginEnvId : null);
38298
+ }
36752
38299
  // openTabsInBackground is not in the Settings form: a save from the form keeps
36753
38300
  // it. What it covers is said at newSessionPage, which reads it.
38301
+ // The owner's list of profiles agents may choose is not in the form either, and has one writer (PUT
38302
+ // /api/morelogin/agent-profiles): a save here keeps the saved list whatever the body carries.
38303
+ const savedAgentProfiles = normalizeAgentProfiles(loadBrowserConfig());
38304
+ delete body[AGENT_PROFILES_KEY];
38305
+ if (savedAgentProfiles.length) body[AGENT_PROFILES_KEY] = savedAgentProfiles;
36754
38306
  const savedBackgroundTabs = loadBrowserConfig().openTabsInBackground;
36755
38307
  if (body.openTabsInBackground === undefined && typeof savedBackgroundTabs === 'boolean') body.openTabsInBackground = savedBackgroundTabs;
36756
38308
  saveBrowserConfig(body);
@@ -36762,7 +38314,8 @@ app.put('/api/browser/config', (req, res) => {
36762
38314
  res.json({ ok: true });
36763
38315
  } catch (err) {
36764
38316
  const invalidLanguage = err.status === 400 && ['locale', 'acceptLanguage'].includes(err.field);
36765
- res.status(invalidLanguage ? 400 : 500).json({ error: err.message, ...(invalidLanguage && { field: err.field }) });
38317
+ const refusedProfile = err.status === 400 && err.code === 'MORELOGIN_NOT_CHROMIUM';
38318
+ res.status(invalidLanguage || refusedProfile ? 400 : 500).json({ error: err.message, ...(invalidLanguage && { field: err.field }), ...(refusedProfile && { code: err.code, field: 'moreloginEnvId' }) });
36766
38319
  }
36767
38320
  });
36768
38321
 
@@ -36783,21 +38336,36 @@ app.get('/api/browser/morelogin-envs', async (req, res) => {
36783
38336
  try {
36784
38337
  const cfg = loadBrowserConfig();
36785
38338
  const port = moreLogin.getMoreLoginPort(cfg);
38339
+ // The default browser's mode: the schedule editor shows its MoreLogin profile row where MoreLogin is in use.
38340
+ const connectMode = cfg.connectMode || null;
38341
+ // SynaBun's own local profiles (`kind: 'local'`, lib/local-profiles.js) are in every answer, also while MoreLogin
38342
+ // is closed, not installed or refusing: `installed`, `running`, `port` and `error` keep describing MoreLogin
38343
+ // alone, and `local.count` says how many of `envs` are local.
38344
+ let localEnvs = [];
38345
+ let localError = null;
38346
+ try { localEnvs = (await moreLogin.listLocalProfiles()).map((env) => ({ ...env, browser: 'chromium' })); }
38347
+ catch (err) { localError = err.message; }
38348
+ const local = { count: localEnvs.length, ...(localError ? { error: localError } : {}) };
36786
38349
  // Probe first: the install-folder check knows only the default folders, and an
36787
38350
  // answering local API proves the app is there wherever it was installed.
36788
38351
  const probe = await moreLogin.probeMoreLoginApi({ savedCfg: cfg, port });
36789
38352
  const installed = probe.running || moreLogin.isMoreLoginInstalled().installed;
36790
- if (!installed) return res.json({ ok: true, installed: false, running: false, port, envs: [], error: probe.error || null });
36791
- if (!probe.running) return res.json({ ok: true, installed: true, running: false, port, envs: [], error: probe.error || null });
38353
+ if (!installed) return res.json({ connectMode, ok: true, installed: false, running: false, port, envs: localEnvs, local, error: probe.error || null });
38354
+ if (!probe.running) return res.json({ connectMode, ok: true, installed: true, running: false, port, envs: localEnvs, local, error: probe.error || null });
36792
38355
  // The API answered with an error (signature required, API off): say why, never an empty list.
36793
- if (probe.apiError) return res.json({ ok: false, installed: true, running: true, port, envs: [], error: probe.apiError });
36794
- const envs = await moreLogin.listProfiles({ savedCfg: cfg, port });
38356
+ if (probe.apiError) return res.json({ connectMode, ok: false, installed: true, running: true, port, envs: localEnvs, local, error: probe.apiError });
38357
+ // MoreLogin's own rows (the list holds the local ones too: they are added once, below).
38358
+ const listedEnvs = (await moreLogin.listProfiles({ savedCfg: cfg, port })).filter((env) => env.kind !== 'local');
36795
38359
  // The API counted profiles but none could be read: a shape problem, never "no profiles yet".
36796
- if (probe.count > 0 && !envs.length) {
36797
- return res.json({ ok: false, installed: true, running: true, port, envs: [], error: `MoreLogin reports ${probe.count} profile(s) but SynaBun could not read them from its answer; a newer MoreLogin may have changed its API.` });
38360
+ if (probe.count > 0 && !listedEnvs.length) {
38361
+ 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.` });
36798
38362
  }
38363
+ // Each profile with the browser it runs (`browser`: 'chromium' | 'firefox' | null = not known): the list call
38364
+ // does not say it, so it is looked up per profile, kept, and never waited for longer than the lookup's budget.
38365
+ // A Firefox-type profile cannot be driven (CDP only): the pickers list it and do not offer it.
38366
+ const { envs, browsersPending } = await withMoreLoginBrowsers(listedEnvs, { savedCfg: cfg, port });
36799
38367
  res.json({
36800
- ok: true, installed: true, running: true, port, envs,
38368
+ connectMode, ok: true, installed: true, running: true, port, envs: [...envs, ...localEnvs], local, browsersPending,
36801
38369
  // Observed website-policy blocks — MoreLogin's local API never exposes the
36802
38370
  // blacklist/whitelist itself, so the picker reports what actually happened.
36803
38371
  blockedNavigations: moreLoginBlockStats.count,
@@ -36976,6 +38544,9 @@ function startLaunchWarmup() {
36976
38544
  reloadConfig();
36977
38545
 
36978
38546
  const httpServer = app.listen(PORT, async () => {
38547
+ // Before anything else: the sessions that saved a MoreLogin profile choice (POST /api/morelogin/use) must prove
38548
+ // who they are again before that choice is used (retireSavedProfileChoiceOwners).
38549
+ try { retireSavedProfileChoiceOwners(); } catch (err) { console.warn(`[morelogin] the owners of the saved profile choices were not retired: ${err.message}`); }
36979
38550
  console.log(`\n Neural Memory Interface`);
36980
38551
  console.log(` ──────────────────────`);
36981
38552
  console.log(` Server: http://localhost:${PORT}`);
@@ -37042,6 +38613,18 @@ const httpServer = app.listen(PORT, async () => {
37042
38613
  try { memoryVectors.size(); } catch { /* cache builds lazily on failure */ }
37043
38614
  }, 500);
37044
38615
 
38616
+ // Local profiles still running from before this start (their Chrome outlives the server, as a MoreLogin profile
38617
+ // does): the proxy relay of each is put back on the port its Chrome was started with. Until then, and when the port
38618
+ // was taken meanwhile, that profile's pages fail (never a direct connection); its next start starts it again.
38619
+ setTimeout(async () => {
38620
+ try {
38621
+ const adopted = await moreLogin.adoptLocalProfiles();
38622
+ if (!adopted.length) return;
38623
+ const stuck = adopted.filter((p) => p.relay === 'restart-needed');
38624
+ console.log(` Local profiles: ${adopted.length} running${stuck.length ? ` · ${stuck.length} need a restart (proxy relay port taken): ${stuck.map((p) => p.name).join(', ')}` : ''}`);
38625
+ } catch (err) { console.warn(` Local profiles: not picked up (${err.message})`); }
38626
+ }, 200);
38627
+
37045
38628
  // Detect MoreLogin (anti-detect browser) — DETECTION ONLY, never auto-activates.
37046
38629
  // Activation is an explicit user choice via Settings → Browser / the MoreLogin tab.
37047
38630
  setTimeout(async () => {
@@ -37327,7 +38910,7 @@ httpServer.on('upgrade', function onUpgrade(req, socket, head) {
37327
38910
  if (guest) {
37328
38911
  if (url.pathname.startsWith('/ws/terminal/') && !invitePermissions.terminal) { socket.destroy(); return; }
37329
38912
  if (url.pathname.startsWith('/ws/browser/') && !invitePermissions.browser) { socket.destroy(); return; }
37330
- if (['/ws/claude-skin', '/ws/codex-skin', '/ws/opencode-v2', '/ws/antigravity'].includes(url.pathname) || url.pathname.startsWith('/ws/assistant/')) {
38913
+ if (['/ws/claude-skin', '/ws/codex-skin', '/ws/opencode-v2', '/ws/antigravity', '/ws/maritaca'].includes(url.pathname) || url.pathname.startsWith('/ws/assistant/')) {
37331
38914
  socket.destroy();
37332
38915
  return;
37333
38916
  }
@@ -37375,7 +38958,7 @@ httpServer.on('upgrade', function onUpgrade(req, socket, head) {
37375
38958
  }
37376
38959
  }
37377
38960
 
37378
- if (url.pathname.startsWith('/ws/browser/') || url.pathname.startsWith('/ws/assistant/') || url.pathname === '/ws/whiteboard' || url.pathname === '/ws/cards' || url.pathname === '/ws/sync' || url.pathname === '/ws/claude-skin' || url.pathname === '/ws/codex-skin' || url.pathname === '/ws/opencode-v2' || url.pathname === '/ws/antigravity' || url.pathname === '/ws/sessions') {
38961
+ if (url.pathname.startsWith('/ws/browser/') || url.pathname.startsWith('/ws/assistant/') || url.pathname === '/ws/whiteboard' || url.pathname === '/ws/cards' || url.pathname === '/ws/sync' || url.pathname === '/ws/claude-skin' || url.pathname === '/ws/codex-skin' || url.pathname === '/ws/opencode-v2' || url.pathname === '/ws/antigravity' || url.pathname === '/ws/maritaca' || url.pathname === '/ws/sessions') {
37379
38962
  wss.handleUpgrade(req, socket, head, (ws) => {
37380
38963
  wss.emit('connection', ws, req);
37381
38964
  });
@@ -37448,6 +39031,12 @@ wss.on('connection', (ws, req) => {
37448
39031
  return;
37449
39032
  }
37450
39033
 
39034
+ // ── Route: Maritaca AI side panel (Sabiá models over HTTP) ──
39035
+ if (url.pathname === '/ws/maritaca') {
39036
+ maritacaPanel.handleSocket(ws);
39037
+ return;
39038
+ }
39039
+
37451
39040
  // ── Terminal sessions ── are handed off to the pty-host in the upgrade
37452
39041
  // handler (lib/pty-host); nothing else should reach this point.
37453
39042
  try { ws.close(1008, 'Unsupported WebSocket path'); } catch {}