synabun 2.2.1 → 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 (365) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/README.md +1 -1
  3. package/docs/whatsapp.md +52 -20
  4. package/hooks/claude-code/pre-websearch.mjs +4 -1
  5. package/hooks/claude-code/prompt-submit.mjs +7 -0
  6. package/lib/mcp-build.js +519 -0
  7. package/lib/mcp-dist.js +10 -4
  8. package/lib/release-scan.mjs +23 -10
  9. package/lib/server-supervisor.js +7 -1
  10. package/lib/virustotal.mjs +146 -40
  11. package/mcp-server/dist/http.d.ts +57 -0
  12. package/mcp-server/dist/http.d.ts.map +1 -1
  13. package/mcp-server/dist/http.js +128 -18
  14. package/mcp-server/dist/http.js.map +1 -1
  15. package/mcp-server/dist/index.d.ts.map +1 -1
  16. package/mcp-server/dist/index.js +14 -9
  17. package/mcp-server/dist/index.js.map +1 -1
  18. package/mcp-server/dist/services/browser-route-flow.d.ts +119 -0
  19. package/mcp-server/dist/services/browser-route-flow.d.ts.map +1 -0
  20. package/mcp-server/dist/services/browser-route-flow.js +340 -0
  21. package/mcp-server/dist/services/browser-route-flow.js.map +1 -0
  22. package/mcp-server/dist/services/desktop-client.js +2 -2
  23. package/mcp-server/dist/services/desktop-client.js.map +1 -1
  24. package/mcp-server/dist/services/embedding-service.d.ts.map +1 -1
  25. package/mcp-server/dist/services/embedding-service.js +2 -1
  26. package/mcp-server/dist/services/embedding-service.js.map +1 -1
  27. package/mcp-server/dist/services/identity.d.ts +66 -3
  28. package/mcp-server/dist/services/identity.d.ts.map +1 -1
  29. package/mcp-server/dist/services/identity.js +61 -4
  30. package/mcp-server/dist/services/identity.js.map +1 -1
  31. package/mcp-server/dist/services/neural-interface.d.ts +133 -1
  32. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  33. package/mcp-server/dist/services/neural-interface.js +630 -64
  34. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  35. package/mcp-server/dist/services/tool-catalog.js +2 -2
  36. package/mcp-server/dist/services/tool-catalog.js.map +1 -1
  37. package/mcp-server/dist/tools/agents.d.ts +3 -2
  38. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  39. package/mcp-server/dist/tools/agents.js +6 -4
  40. package/mcp-server/dist/tools/agents.js.map +1 -1
  41. package/mcp-server/dist/tools/bluesky.d.ts +20 -7
  42. package/mcp-server/dist/tools/bluesky.d.ts.map +1 -1
  43. package/mcp-server/dist/tools/bluesky.js +147 -45
  44. package/mcp-server/dist/tools/bluesky.js.map +1 -1
  45. package/mcp-server/dist/tools/browser-advanced.d.ts +13 -2
  46. package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
  47. package/mcp-server/dist/tools/browser-advanced.js +153 -18
  48. package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
  49. package/mcp-server/dist/tools/browser-cheatsheet.d.ts +2 -0
  50. package/mcp-server/dist/tools/browser-cheatsheet.d.ts.map +1 -1
  51. package/mcp-server/dist/tools/browser-cheatsheet.js +3 -0
  52. package/mcp-server/dist/tools/browser-cheatsheet.js.map +1 -1
  53. package/mcp-server/dist/tools/browser-navigate.d.ts +3 -3
  54. package/mcp-server/dist/tools/browser-navigate.d.ts.map +1 -1
  55. package/mcp-server/dist/tools/browser-navigate.js +19 -16
  56. package/mcp-server/dist/tools/browser-navigate.js.map +1 -1
  57. package/mcp-server/dist/tools/browser-observe.d.ts +2 -1
  58. package/mcp-server/dist/tools/browser-observe.d.ts.map +1 -1
  59. package/mcp-server/dist/tools/browser-observe.js +61 -20
  60. package/mcp-server/dist/tools/browser-observe.js.map +1 -1
  61. package/mcp-server/dist/tools/morelogin.d.ts +13 -3
  62. package/mcp-server/dist/tools/morelogin.d.ts.map +1 -1
  63. package/mcp-server/dist/tools/morelogin.js +82 -19
  64. package/mcp-server/dist/tools/morelogin.js.map +1 -1
  65. package/mcp-server/dist/tools/skill-tools.d.ts +4 -4
  66. package/mcp-server/dist/tools/youtube/helpers.d.ts +1 -0
  67. package/mcp-server/dist/tools/youtube/helpers.d.ts.map +1 -1
  68. package/mcp-server/dist/tools/youtube/helpers.js +1 -1
  69. package/mcp-server/dist/tools/youtube/helpers.js.map +1 -1
  70. package/mcp-server/dist/tools/youtube/upload.d.ts.map +1 -1
  71. package/mcp-server/dist/tools/youtube/upload.js +225 -88
  72. package/mcp-server/dist/tools/youtube/upload.js.map +1 -1
  73. package/mcp-server/package-lock.json +2 -2
  74. package/mcp-server/package.json +1 -1
  75. package/mcp-server/src/http.ts +135 -17
  76. package/mcp-server/src/index.ts +15 -9
  77. package/mcp-server/src/services/browser-route-flow.ts +403 -0
  78. package/mcp-server/src/services/desktop-client.ts +2 -2
  79. package/mcp-server/src/services/embedding-service.ts +2 -1
  80. package/mcp-server/src/services/identity.ts +80 -4
  81. package/mcp-server/src/services/neural-interface.ts +648 -73
  82. package/mcp-server/src/services/tool-catalog.ts +2 -2
  83. package/mcp-server/src/tools/agents.ts +8 -4
  84. package/mcp-server/src/tools/bluesky.ts +164 -51
  85. package/mcp-server/src/tools/browser-advanced.ts +142 -17
  86. package/mcp-server/src/tools/browser-cheatsheet.ts +3 -0
  87. package/mcp-server/src/tools/browser-navigate.ts +19 -16
  88. package/mcp-server/src/tools/browser-observe.ts +62 -20
  89. package/mcp-server/src/tools/morelogin.ts +82 -19
  90. package/mcp-server/src/tools/youtube/helpers.ts +2 -2
  91. package/mcp-server/src/tools/youtube/upload.ts +218 -99
  92. package/neural-interface/i18n/en.json +655 -123
  93. package/neural-interface/i18n/pt-BR.json +542 -10
  94. package/neural-interface/lib/assistant-api.js +90 -23
  95. package/neural-interface/lib/assistant-brains/claude.js +5 -0
  96. package/neural-interface/lib/assistant-catalog.js +134 -3
  97. package/neural-interface/lib/assistant-dispatch.js +97 -1
  98. package/neural-interface/lib/assistant-persona.js +15 -7
  99. package/neural-interface/lib/assistant-router.js +6 -4
  100. package/neural-interface/lib/assistant-runtime.js +18 -1
  101. package/neural-interface/lib/assistant-task-prompt.js +5 -0
  102. package/neural-interface/lib/assistant-tools.js +10 -1
  103. package/neural-interface/lib/automation-approval.js +249 -0
  104. package/neural-interface/lib/automation-browser-owner-access.js +82 -0
  105. package/neural-interface/lib/backup-service.js +16 -1
  106. package/neural-interface/lib/browser-automation-routes.js +84 -0
  107. package/neural-interface/lib/browser-background-tab.js +72 -3
  108. package/neural-interface/lib/browser-execution.js +16 -3
  109. package/neural-interface/lib/browser-extraction.js +106 -45
  110. package/neural-interface/lib/browser-owner.js +48 -0
  111. package/neural-interface/lib/browser-profile-choices.js +143 -0
  112. package/neural-interface/lib/browser-profiles.js +142 -0
  113. package/neural-interface/lib/browser-session-close.js +84 -0
  114. package/neural-interface/lib/browser-start-handoff.js +202 -0
  115. package/neural-interface/lib/browser-tab-recovery.js +153 -0
  116. package/neural-interface/lib/browser-tool-policy.js +23 -4
  117. package/neural-interface/lib/browser-wedge-retire.js +64 -0
  118. package/neural-interface/lib/chromium-on-device-model.js +67 -0
  119. package/neural-interface/lib/claude-agent-bridge.js +43 -5
  120. package/neural-interface/lib/claude-background-hold.js +239 -0
  121. package/neural-interface/lib/claude-model-catalog.js +12 -0
  122. package/neural-interface/lib/effort-levels.js +28 -2
  123. package/neural-interface/lib/exec-loop-command.js +8 -0
  124. package/neural-interface/lib/http-guards.js +11 -6
  125. package/neural-interface/lib/local-profile-proxy.js +362 -0
  126. package/neural-interface/lib/local-profiles.js +929 -0
  127. package/neural-interface/lib/loop-logger.js +31 -5
  128. package/neural-interface/lib/maritaca/api.js +179 -0
  129. package/neural-interface/lib/maritaca/attachments.js +44 -0
  130. package/neural-interface/lib/maritaca/client.js +362 -0
  131. package/neural-interface/lib/maritaca/key-store.js +122 -0
  132. package/neural-interface/lib/maritaca/models.js +181 -0
  133. package/neural-interface/lib/maritaca/modes.js +39 -0
  134. package/neural-interface/lib/maritaca/opencode-proxy.js +236 -0
  135. package/neural-interface/lib/maritaca/opencode-stream.js +345 -0
  136. package/neural-interface/lib/maritaca/opencode.js +218 -0
  137. package/neural-interface/lib/maritaca/panel-bridge.js +273 -0
  138. package/neural-interface/lib/maritaca/sessions.js +198 -0
  139. package/neural-interface/lib/mcp-external-servers.js +37 -10
  140. package/neural-interface/lib/morelogin-agent-profiles.js +149 -0
  141. package/neural-interface/lib/morelogin.js +278 -14
  142. package/neural-interface/lib/native-loop-providers.js +124 -11
  143. package/neural-interface/lib/native-loop-runtime.js +112 -11
  144. package/neural-interface/lib/owner-authority.js +137 -43
  145. package/neural-interface/lib/page-session.js +111 -27
  146. package/neural-interface/lib/peer-identity.js +263 -43
  147. package/neural-interface/lib/provider-panel-api-key-auth.js +7 -2
  148. package/neural-interface/lib/pty-host/core.js +36 -0
  149. package/neural-interface/lib/pty-host/protocol.js +2 -0
  150. package/neural-interface/lib/request-gate.js +2 -0
  151. package/neural-interface/lib/skills/api-v2.js +13 -2
  152. package/neural-interface/lib/skills/creation-api.js +3 -1
  153. package/neural-interface/lib/skills/evals-api.js +5 -1
  154. package/neural-interface/lib/social-write-pacing.js +151 -0
  155. package/neural-interface/lib/system-activity.js +1 -1
  156. package/neural-interface/lib/terminal-token-redaction.js +293 -0
  157. package/neural-interface/lib/terminal-tokens.js +436 -0
  158. package/neural-interface/lib/worker-mcp-channel.js +45 -10
  159. package/neural-interface/package-lock.json +3 -2
  160. package/neural-interface/package.json +2 -1
  161. package/neural-interface/public/assets/mascot/README.md +11 -0
  162. package/neural-interface/public/assets/mascot/ask.gif +0 -0
  163. package/neural-interface/public/assets/mascot/ask.png +0 -0
  164. package/neural-interface/public/assets/mascot/blocked.gif +0 -0
  165. package/neural-interface/public/assets/mascot/blocked.png +0 -0
  166. package/neural-interface/public/assets/mascot/budget.gif +0 -0
  167. package/neural-interface/public/assets/mascot/budget.png +0 -0
  168. package/neural-interface/public/assets/mascot/computer.gif +0 -0
  169. package/neural-interface/public/assets/mascot/computer.png +0 -0
  170. package/neural-interface/public/assets/mascot/edit.gif +0 -0
  171. package/neural-interface/public/assets/mascot/edit.png +0 -0
  172. package/neural-interface/public/assets/mascot/error.gif +0 -0
  173. package/neural-interface/public/assets/mascot/error.png +0 -0
  174. package/neural-interface/public/assets/mascot/hover-attention.gif +0 -0
  175. package/neural-interface/public/assets/mascot/hover-attention.png +0 -0
  176. package/neural-interface/public/assets/mascot/idle-hero.gif +0 -0
  177. package/neural-interface/public/assets/mascot/idle-hero.png +0 -0
  178. package/neural-interface/public/assets/mascot/idle.gif +0 -0
  179. package/neural-interface/public/assets/mascot/idle.png +0 -0
  180. package/neural-interface/public/assets/mascot/manifest.json +254 -0
  181. package/neural-interface/public/assets/mascot/mcp.gif +0 -0
  182. package/neural-interface/public/assets/mascot/mcp.png +0 -0
  183. package/neural-interface/public/assets/mascot/memory.gif +0 -0
  184. package/neural-interface/public/assets/mascot/memory.png +0 -0
  185. package/neural-interface/public/assets/mascot/offline.gif +0 -0
  186. package/neural-interface/public/assets/mascot/offline.png +0 -0
  187. package/neural-interface/public/assets/mascot/pick.gif +0 -0
  188. package/neural-interface/public/assets/mascot/pick.png +0 -0
  189. package/neural-interface/public/assets/mascot/plan.gif +0 -0
  190. package/neural-interface/public/assets/mascot/plan.png +0 -0
  191. package/neural-interface/public/assets/mascot/present.gif +0 -0
  192. package/neural-interface/public/assets/mascot/present.png +0 -0
  193. package/neural-interface/public/assets/mascot/project.gif +0 -0
  194. package/neural-interface/public/assets/mascot/project.png +0 -0
  195. package/neural-interface/public/assets/mascot/read.gif +0 -0
  196. package/neural-interface/public/assets/mascot/read.png +0 -0
  197. package/neural-interface/public/assets/mascot/runs.gif +0 -0
  198. package/neural-interface/public/assets/mascot/runs.png +0 -0
  199. package/neural-interface/public/assets/mascot/scenes/automation.gif +0 -0
  200. package/neural-interface/public/assets/mascot/scenes/automation.png +0 -0
  201. package/neural-interface/public/assets/mascot/scenes/browser.gif +0 -0
  202. package/neural-interface/public/assets/mascot/scenes/browser.png +0 -0
  203. package/neural-interface/public/assets/mascot/scenes/code.gif +0 -0
  204. package/neural-interface/public/assets/mascot/scenes/code.png +0 -0
  205. package/neural-interface/public/assets/mascot/scenes/complex.gif +0 -0
  206. package/neural-interface/public/assets/mascot/scenes/complex.png +0 -0
  207. package/neural-interface/public/assets/mascot/scenes/computer.gif +0 -0
  208. package/neural-interface/public/assets/mascot/scenes/computer.png +0 -0
  209. package/neural-interface/public/assets/mascot/scenes/design.gif +0 -0
  210. package/neural-interface/public/assets/mascot/scenes/design.png +0 -0
  211. package/neural-interface/public/assets/mascot/scenes/edit.gif +0 -0
  212. package/neural-interface/public/assets/mascot/scenes/edit.png +0 -0
  213. package/neural-interface/public/assets/mascot/scenes/generic.gif +0 -0
  214. package/neural-interface/public/assets/mascot/scenes/generic.png +0 -0
  215. package/neural-interface/public/assets/mascot/scenes/image_gen.gif +0 -0
  216. package/neural-interface/public/assets/mascot/scenes/image_gen.png +0 -0
  217. package/neural-interface/public/assets/mascot/scenes/manifest.json +173 -0
  218. package/neural-interface/public/assets/mascot/scenes/memory.gif +0 -0
  219. package/neural-interface/public/assets/mascot/scenes/memory.png +0 -0
  220. package/neural-interface/public/assets/mascot/scenes/quick.gif +0 -0
  221. package/neural-interface/public/assets/mascot/scenes/quick.png +0 -0
  222. package/neural-interface/public/assets/mascot/scenes/read.gif +0 -0
  223. package/neural-interface/public/assets/mascot/scenes/read.png +0 -0
  224. package/neural-interface/public/assets/mascot/scenes/research.gif +0 -0
  225. package/neural-interface/public/assets/mascot/scenes/research.png +0 -0
  226. package/neural-interface/public/assets/mascot/scenes/review.gif +0 -0
  227. package/neural-interface/public/assets/mascot/scenes/review.png +0 -0
  228. package/neural-interface/public/assets/mascot/scenes/search.gif +0 -0
  229. package/neural-interface/public/assets/mascot/scenes/search.png +0 -0
  230. package/neural-interface/public/assets/mascot/scenes/shell.gif +0 -0
  231. package/neural-interface/public/assets/mascot/scenes/shell.png +0 -0
  232. package/neural-interface/public/assets/mascot/scenes/thinking.gif +0 -0
  233. package/neural-interface/public/assets/mascot/scenes/thinking.png +0 -0
  234. package/neural-interface/public/assets/mascot/scenes/video_gen.gif +0 -0
  235. package/neural-interface/public/assets/mascot/scenes/video_gen.png +0 -0
  236. package/neural-interface/public/assets/mascot/scenes/web.gif +0 -0
  237. package/neural-interface/public/assets/mascot/scenes/web.png +0 -0
  238. package/neural-interface/public/assets/mascot/search.gif +0 -0
  239. package/neural-interface/public/assets/mascot/search.png +0 -0
  240. package/neural-interface/public/assets/mascot/shell.gif +0 -0
  241. package/neural-interface/public/assets/mascot/shell.png +0 -0
  242. package/neural-interface/public/assets/mascot/skill.gif +0 -0
  243. package/neural-interface/public/assets/mascot/skill.png +0 -0
  244. package/neural-interface/public/assets/mascot/sleep.gif +0 -0
  245. package/neural-interface/public/assets/mascot/sleep.png +0 -0
  246. package/neural-interface/public/assets/mascot/subagent.gif +0 -0
  247. package/neural-interface/public/assets/mascot/subagent.png +0 -0
  248. package/neural-interface/public/assets/mascot/success.gif +0 -0
  249. package/neural-interface/public/assets/mascot/success.png +0 -0
  250. package/neural-interface/public/assets/mascot/think.gif +0 -0
  251. package/neural-interface/public/assets/mascot/think.png +0 -0
  252. package/neural-interface/public/assets/mascot/wait.gif +0 -0
  253. package/neural-interface/public/assets/mascot/wait.png +0 -0
  254. package/neural-interface/public/assets/mascot/watch.gif +0 -0
  255. package/neural-interface/public/assets/mascot/watch.png +0 -0
  256. package/neural-interface/public/assets/mascot/web.gif +0 -0
  257. package/neural-interface/public/assets/mascot/web.png +0 -0
  258. package/neural-interface/public/onboarding.html +14 -1
  259. package/neural-interface/public/shared/agent-runtime-options.js +49 -8
  260. package/neural-interface/public/shared/agy/agy-panel.js +2 -2
  261. package/neural-interface/public/shared/agy/agy-render.js +41 -1
  262. package/neural-interface/public/shared/agy/agy-styles.js +5 -0
  263. package/neural-interface/public/shared/api.js +5 -4
  264. package/neural-interface/public/shared/assistant/asst-ask-styles.js +8 -8
  265. package/neural-interface/public/shared/assistant/asst-ask.js +1 -1
  266. package/neural-interface/public/shared/assistant/asst-brain-picker.js +99 -9
  267. package/neural-interface/public/shared/assistant/asst-computer.js +47 -2
  268. package/neural-interface/public/shared/assistant/asst-control.js +1 -1
  269. package/neural-interface/public/shared/assistant/asst-limit-wait.js +7 -5
  270. package/neural-interface/public/shared/assistant/asst-panel.js +13 -5
  271. package/neural-interface/public/shared/assistant/asst-rack-styles.js +4 -4
  272. package/neural-interface/public/shared/assistant/asst-render.js +16 -10
  273. package/neural-interface/public/shared/assistant/asst-route-models.js +64 -4
  274. package/neural-interface/public/shared/assistant/asst-route.js +24 -7
  275. package/neural-interface/public/shared/assistant/asst-routes-editor.js +154 -39
  276. package/neural-interface/public/shared/assistant/asst-run-stage.js +3 -3
  277. package/neural-interface/public/shared/assistant/asst-scene-styles.js +8 -111
  278. package/neural-interface/public/shared/assistant/asst-scenes.js +46 -318
  279. package/neural-interface/public/shared/assistant/asst-sidepanel.js +2 -2
  280. package/neural-interface/public/shared/assistant/asst-state.js +72 -2
  281. package/neural-interface/public/shared/assistant/asst-styles.js +60 -15
  282. package/neural-interface/public/shared/automation-approval-view.js +75 -0
  283. package/neural-interface/public/shared/cdx/cdx-panel.js +2 -2
  284. package/neural-interface/public/shared/cdx/cdx-render.js +73 -7
  285. package/neural-interface/public/shared/cdx/cdx-tabs.js +3 -3
  286. package/neural-interface/public/shared/context-menu-model.js +2 -0
  287. package/neural-interface/public/shared/cp/cp-agents.js +8 -0
  288. package/neural-interface/public/shared/cp/cp-permissions.js +6 -2
  289. package/neural-interface/public/shared/cp/cp-rehydrate.js +25 -1
  290. package/neural-interface/public/shared/cp/cp-tasks-model.js +33 -0
  291. package/neural-interface/public/shared/editor/editor-panel-logic.js +10 -0
  292. package/neural-interface/public/shared/editor/editor-panel.js +10 -2
  293. package/neural-interface/public/shared/html-shell.js +30 -22
  294. package/neural-interface/public/shared/judgments-log-origins.js +29 -0
  295. package/neural-interface/public/shared/morelogin-profile-choices.js +107 -0
  296. package/neural-interface/public/shared/morelogin-profile-field.js +186 -0
  297. package/neural-interface/public/shared/mtc/mtc-client.js +181 -0
  298. package/neural-interface/public/shared/mtc/mtc-compose.js +40 -0
  299. package/neural-interface/public/shared/mtc/mtc-copy.js +253 -0
  300. package/neural-interface/public/shared/mtc/mtc-logic.js +478 -0
  301. package/neural-interface/public/shared/mtc/mtc-panel.js +1354 -0
  302. package/neural-interface/public/shared/mtc/mtc-render.js +172 -0
  303. package/neural-interface/public/shared/mtc/mtc-styles.js +437 -0
  304. package/neural-interface/public/shared/ocp-v2/ocp-v2-automation-ownership.js +23 -0
  305. package/neural-interface/public/shared/ocp-v2/ocp-v2-events.js +13 -0
  306. package/neural-interface/public/shared/ocp-v2/ocp-v2-icons.js +3 -1
  307. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +10 -4
  308. package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +6 -86
  309. package/neural-interface/public/shared/ocp-v2/ocp-v2-ws.js +5 -2
  310. package/neural-interface/public/shared/owner-access.js +134 -0
  311. package/neural-interface/public/shared/owner-authority-view.js +92 -0
  312. package/neural-interface/public/shared/page-session.js +143 -14
  313. package/neural-interface/public/shared/poll-backoff.js +59 -0
  314. package/neural-interface/public/shared/provider-icons.js +3 -0
  315. package/neural-interface/public/shared/schedules-view.js +7 -0
  316. package/neural-interface/public/shared/server-back.js +50 -0
  317. package/neural-interface/public/shared/settings/settings-browser-owner-access.js +72 -0
  318. package/neural-interface/public/shared/settings/settings-data.js +7 -1
  319. package/neural-interface/public/shared/settings/settings-ia.js +3 -1
  320. package/neural-interface/public/shared/settings/settings-kit.js +11 -3
  321. package/neural-interface/public/shared/settings/settings-local-profiles.js +153 -0
  322. package/neural-interface/public/shared/settings/settings-maritaca-opencode.js +105 -0
  323. package/neural-interface/public/shared/settings/settings-shell.js +7 -0
  324. package/neural-interface/public/shared/shown-children.js +72 -0
  325. package/neural-interface/public/shared/sidepanel-session-status.js +16 -2
  326. package/neural-interface/public/shared/state.js +1 -1
  327. package/neural-interface/public/shared/static-bg-state.js +22 -0
  328. package/neural-interface/public/shared/styles.css +457 -164
  329. package/neural-interface/public/shared/synabun-mascot-assets.js +67 -0
  330. package/neural-interface/public/shared/synabun-mascot.js +136 -12
  331. package/neural-interface/public/shared/synabun-ticker.js +3 -0
  332. package/neural-interface/public/shared/synabun-tools.js +173 -0
  333. package/neural-interface/public/shared/tool-heartbeat.js +43 -0
  334. package/neural-interface/public/shared/tool-list-picker.js +3 -1
  335. package/neural-interface/public/shared/tool-list-view.js +23 -4
  336. package/neural-interface/public/shared/topright-overflow-logic.js +1 -0
  337. package/neural-interface/public/shared/ui-automation-approval.js +188 -0
  338. package/neural-interface/public/shared/ui-automation-studio.js +138 -91
  339. package/neural-interface/public/shared/ui-claude-panel.js +209 -31
  340. package/neural-interface/public/shared/ui-judgments.js +37 -10
  341. package/neural-interface/public/shared/ui-maritaca-panel.js +15 -0
  342. package/neural-interface/public/shared/ui-navbar.js +23 -0
  343. package/neural-interface/public/shared/ui-owner-access.js +191 -0
  344. package/neural-interface/public/shared/ui-owner-authority.js +162 -0
  345. package/neural-interface/public/shared/ui-panels.js +3 -1
  346. package/neural-interface/public/shared/ui-schedules-studio.js +118 -17
  347. package/neural-interface/public/shared/ui-scroll-follow.js +3 -0
  348. package/neural-interface/public/shared/ui-sessions.js +45 -16
  349. package/neural-interface/public/shared/ui-settings.js +676 -42
  350. package/neural-interface/public/shared/ui-sidepanel-session-entry.js +8 -2
  351. package/neural-interface/public/shared/ui-sidepanel-sessions.js +3 -3
  352. package/neural-interface/public/shared/ui-sidepanel-tray.js +24 -0
  353. package/neural-interface/public/shared/ui-sidepanel-windows.js +1 -1
  354. package/neural-interface/public/shared/ui-terminal.js +15 -7
  355. package/neural-interface/public/shared/ui-tutorial-preview.js +4 -0
  356. package/neural-interface/public/shared/ui-update.js +3 -0
  357. package/neural-interface/public/shared/ui-whiteboard.js +4 -0
  358. package/neural-interface/public/shared/window-keys.js +38 -0
  359. package/neural-interface/scripts/build-mascot-assets.mjs +30 -0
  360. package/neural-interface/server.js +2903 -359
  361. package/npm-shrinkwrap.json +5 -17
  362. package/package.json +5 -6
  363. package/postinstall.js +38 -39
  364. package/setup.js +33 -31
  365. package/skills/synabun/modules/changelog.md +14 -0
@@ -0,0 +1,82 @@
1
+ // ═══════════════════════════════════════════
2
+ // SynaBun — Let the automation browser act as owner: the one global value
3
+ // ═══════════════════════════════════════════
4
+ //
5
+ // DATA_HOME/data/automation-browser-owner-access.json ({ enabled, updatedAt }), read live: whether SynaBun's own
6
+ // automation browser (the Playwright / MoreLogin browser the browser_* tools drive) may use the Neural Interface
7
+ // on this server as the owner. Off by default, and off whenever the file is missing or cannot be read.
8
+ //
9
+ // What it changes (lib/page-session.js, lib/owner-authority.js read it through `enabled()` on every request):
10
+ // while on, a request that carries the automation browser's marker (cookie or host-proof header), or whose peer
11
+ // process the lookup names an automation browser, is handed the page secret, verifies as the owner and passes the
12
+ // owner gate (its writes, its reads, its sockets: /ws/assistant, the panels, the memory map's data), so a
13
+ // screenshot or visual-QA run sees the real UI. Every other refusal stays: an agent's process tree, a relay,
14
+ // another SynaBun server, a remote login, a guest, a failed lookup. The automation browser still gets no service
15
+ // worker (nothing it does is answered out of the server's sight).
16
+ //
17
+ // Who may change it: only the owner's own page (PUT /api/assistant/automation-browser-owner-access: this boot's
18
+ // page secret, no agent header, and never from the automation browser itself, whatever the setting says). No
19
+ // agent tool, mailbox, worker or hook writes it; nothing reads it from a request. A change is broadcast to every
20
+ // window and said in the server log; a server that starts with it on says so too.
21
+
22
+ import { mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
23
+ import { dirname } from 'node:path';
24
+
25
+ export const AUTOMATION_BROWSER_OWNER_ACCESS_EVENT = 'browser:owner-access-changed';
26
+ export const AUTOMATION_BROWSER_OWNER_ACCESS_FILE = 'automation-browser-owner-access.json';
27
+ export const AUTOMATION_BROWSER_OWNER_ACCESS_DEFAULT = false;
28
+ /** The one-line notice the server log carries while the setting is on (at start, and on every change to on). */
29
+ export const AUTOMATION_BROWSER_OWNER_ACCESS_NOTICE = 'the automation browser acts as the owner on this server: agents driving the SynaBun browser can read and act on the Neural Interface as the owner (Settings → Browser → Automation browser access)';
30
+
31
+ /** Only `true` / `false` (and the strings "true" / "false") are a value; anything else is refused. */
32
+ export function normalizeOwnerAccessValue(value) {
33
+ if (value === true || value === 'true') return true;
34
+ if (value === false || value === 'false') return false;
35
+ return null;
36
+ }
37
+
38
+ export function createAutomationBrowserOwnerAccess({ path, broadcast = () => {}, log = () => {}, now = Date.now } = {}) {
39
+ if (!path) throw new Error('createAutomationBrowserOwnerAccess requires a path');
40
+ const listeners = new Set();
41
+ let cache = null; // { mtimeMs, value }
42
+
43
+ /** Whether the setting is on: the file's `enabled` when it is exactly true, else off. Never throws. */
44
+ function read() {
45
+ try {
46
+ const stat = statSync(path);
47
+ if (cache && cache.mtimeMs === stat.mtimeMs) return cache.value;
48
+ const data = JSON.parse(readFileSync(path, 'utf8'));
49
+ const value = data?.enabled === true;
50
+ cache = { mtimeMs: stat.mtimeMs, value };
51
+ return value;
52
+ } catch {
53
+ return AUTOMATION_BROWSER_OWNER_ACCESS_DEFAULT;
54
+ }
55
+ }
56
+ /** What the UI shows: the value in effect and the default. */
57
+ function view() {
58
+ return { enabled: read(), defaultEnabled: AUTOMATION_BROWSER_OWNER_ACCESS_DEFAULT };
59
+ }
60
+ function set(value) {
61
+ const next = normalizeOwnerAccessValue(value);
62
+ if (next === null) throw Object.assign(new Error('enabled must be true or false.'), { code: 'INVALID_VALUE', status: 400 });
63
+ const before = read();
64
+ mkdirSync(dirname(path), { recursive: true });
65
+ const tmp = `${path}.${process.pid}.tmp`;
66
+ writeFileSync(tmp, JSON.stringify({ enabled: next, updatedAt: new Date(now()).toISOString() }, null, 2) + '\n', 'utf8');
67
+ renameSync(tmp, path);
68
+ cache = null;
69
+ const changed = next !== before;
70
+ if (changed) log('automation-browser', next ? `owner access ON: ${AUTOMATION_BROWSER_OWNER_ACCESS_NOTICE}` : 'owner access OFF: the automation browser is refused the owner\'s page secret and authority again');
71
+ try { broadcast({ type: AUTOMATION_BROWSER_OWNER_ACCESS_EVENT, ...view() }); } catch { /* nobody listening */ }
72
+ if (changed) for (const listener of [...listeners]) { try { listener(next); } catch { /* the listener's own failure */ } }
73
+ return view();
74
+ }
75
+ /** The notice a server that starts with the setting on writes to its log (null when off). */
76
+ function startupNotice() {
77
+ return read() ? `[automation-browser] owner access is ON: ${AUTOMATION_BROWSER_OWNER_ACCESS_NOTICE}` : null;
78
+ }
79
+ function subscribe(listener) { listeners.add(listener); return () => listeners.delete(listener); }
80
+
81
+ return { enabled: read, view, set, subscribe, startupNotice, path };
82
+ }
@@ -228,10 +228,24 @@ function createConsistentSqliteSnapshot(sourcePath, snapshotPath) {
228
228
  // they belonged to, and that file is snapshotted consistently or not at all.
229
229
  const SQLITE_JOURNAL_RE = /\.(?:db|bak)-journal$/i;
230
230
 
231
+ /**
232
+ * True for what lies inside a local browser profile's folder (data/local-profiles/<id>/…, lib/local-profiles.js): a
233
+ * whole Chrome profile, which Chrome locks and rewrites while it runs, as large as a browser gets, and holding the
234
+ * profile's cookies and logins. No archive of any kind holds it (a copy taken under a running Chrome would not be a
235
+ * profile anyway). The profiles' definitions, data/local-profiles/profiles.json, are a plain file of that folder and
236
+ * stay in every backup and upgrade snapshot, so a rollback brings the list back; that file holds the proxy passwords
237
+ * as typed (docs/browser-v2.md).
238
+ */
239
+ export function isLocalProfileFolderPath(relativePath) {
240
+ const parts = String(relativePath).replace(/\\/g, '/').split('/');
241
+ return parts[0] === 'local-profiles' && parts.length > 2;
242
+ }
243
+
231
244
  function shouldSkipDataPath(relativePath) {
232
245
  const normalized = relativePath.replace(/\\/g, '/');
233
246
  const parts = normalized.split('/');
234
247
  const name = parts.at(-1);
248
+ if (isLocalProfileFolderPath(normalized)) return true;
235
249
  if (parts[0] === 'updater') return true;
236
250
  if (parts[0] === 'logs') return true;
237
251
  if (parts.length > 1 && EXCLUDED_DATA_DIRS.has(parts[0])) return true;
@@ -930,7 +944,8 @@ export function sameBackupFile(path, stamp) {
930
944
  // and transcript captures, the MCP tool counters; the caches the server rebuilds from the memories (the map's layout,
931
945
  // the links); and the automation browser's Chromium profiles, which Chromium locks and rewrites while it runs (the
932
946
  // "attach" one even when SynaBun does not), and which no SynaBun update touches. Upgrade snapshots leave them out;
933
- // the full backups keep everything.
947
+ // the full backups keep everything. (The folders of the local browser profiles, data/local-profiles/<id>/, are in no
948
+ // archive at all: shouldSkipDataPath. Their definitions, data/local-profiles/profiles.json, are in every one.)
934
949
  const UPGRADE_RUNTIME_FILES = Object.freeze({
935
950
  data: new Set(['supervisor.json', 'start-launcher.lock', 'update-handoff.json', 'last-session.json', 'memory-map.json', 'links-cache.json']),
936
951
  'mcp-data': new Set(['tool-usage.json']),
@@ -0,0 +1,84 @@
1
+ // ── The browser routes an automation may call (DOM-free, no imports) ──
2
+ //
3
+ // SynaBun's browser API (/api/browser) serves two callers: the owner's page (the browser panel, Settings → Browser)
4
+ // and the automations that drive the browser through SynaBun's MCP tools (loops, dispatched workers, agents, the side
5
+ // panels, a CLI window). The MCP tools call a fixed set of routes (mcp-server/src/services/neural-interface.ts: the
6
+ // session list, create and close, acquire and release, and the page actions on a session); everything else under
7
+ // /api/browser is the owner's: the browser settings (PUT /config: attach to the user's real Chrome, pick a MoreLogin
8
+ // profile), the money guard's lift (paid-surfaces), the raw CDP endpoints (cdp, claude-connect), tab management
9
+ // outside a run's own tab (tabs: list, open, activate, close), the folder picker and the profile and browser
10
+ // detection. Until 2026-11-05 a run that proved its id reached all of them, and the worker-only MCP channel forwarded
11
+ // every /browser/* path with the run's token, so a sandboxed worker could switch the default browser to the user's
12
+ // real Chrome profile or lift the money guard (review 972afb74, finding 1).
13
+ //
14
+ // This list is the one answer to "may an automation call this": the worker channel forwards nothing else
15
+ // (lib/worker-mcp-channel.js), and server.js browserTerminalGate answers every other route the owner's page only (its
16
+ // page secret, or an invite guest the guest rules let in), whatever agent headers the request carries. A route a new
17
+ // MCP tool calls is added here, with its test (tests/browser-automation-routes.test.mjs checks the list against the
18
+ // paths the MCP server's source calls).
19
+
20
+ /** One path segment of a session or tab id SynaBun mints (hex today; base64url and uuid shapes allowed). */
21
+ const ID = '[A-Za-z0-9_-]{1,128}';
22
+ /** Page actions on a session the MCP tools post (navigate, click, …). */
23
+ const POST_ACTIONS = Object.freeze([
24
+ 'navigate', 'back', 'forward', 'reload', 'click', 'fill', 'type', 'hover', 'select', 'press', 'scroll', 'upload',
25
+ 'snapshot', 'evaluate', 'extract', 'x-compose-state', 'semantic-context', 'wait', 'bluesky/upload-blob',
26
+ ]);
27
+ /** Reads of a session the MCP tools get. */
28
+ const GET_READS = Object.freeze(['snapshot', 'content', 'markdown', 'screenshot-base64', 'console']);
29
+
30
+ const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
31
+
32
+ /** [method, path pattern relative to /api/browser] for every route an automation may call. */
33
+ export const AUTOMATION_BROWSER_ROUTES = Object.freeze([
34
+ ['GET', '/sessions'],
35
+ ['POST', '/sessions'],
36
+ ['POST', '/acquire'],
37
+ ['POST', '/release'],
38
+ ['DELETE', '/sessions/:id'],
39
+ ...POST_ACTIONS.map((action) => ['POST', `/sessions/:id/${action}`]),
40
+ ...GET_READS.map((read) => ['GET', `/sessions/:id/${read}`]),
41
+ ].map((route) => Object.freeze(route)));
42
+
43
+ const MATCHERS = AUTOMATION_BROWSER_ROUTES.map(([method, path]) => ({
44
+ method,
45
+ re: new RegExp(`^${path.split('/').map((part) => (part === ':id' ? ID : escape(part))).join('/')}/?$`),
46
+ }));
47
+
48
+ /**
49
+ * Whether an automation may call `method` `path`. `path` is relative to /api/browser (`/sessions/abc/navigate`), as
50
+ * Express's req.path is under that mount; a query string is ignored. Anything that is not exactly one of the listed
51
+ * routes is the owner's: another method, another path, an encoded or dot segment, a doubled slash.
52
+ */
53
+ export function isAutomationBrowserRoute(method, path) {
54
+ const verb = String(method || '').toUpperCase() === 'HEAD' ? 'GET' : String(method || '').toUpperCase();
55
+ const bare = String(path || '').split('?')[0];
56
+ if (!bare.startsWith('/') || bare.includes('//')) return false;
57
+ return MATCHERS.some((m) => m.method === verb && m.re.test(bare));
58
+ }
59
+
60
+ /**
61
+ * The fields of a session create that pick which browser or profile it starts (POST /api/browser/sessions): the
62
+ * owner's choice (Settings → Browser), never an automation's. An automation's create opens the default browser.
63
+ */
64
+ export const OWNER_ONLY_CREATE_FIELDS = Object.freeze(['connectMode', 'moreloginEnvId']);
65
+
66
+ /**
67
+ * Every field that names a browser, a MoreLogin profile or a browser setting (PUT /api/browser/config's fields and
68
+ * the names an agent reaches for: profile, config, a profile folder, a CDP endpoint). The owner's choice, never an
69
+ * automation's: an automation's session create naming one is refused (403 OWNER_ONLY_FIELDS), and SynaBun's browser
70
+ * MCP tools refuse a call that names one instead of dropping it (mcp-server/src/services/browser-route-flow.ts
71
+ * OWNER_ONLY_FIELDS mirrors this list; tests/browser-automation-routes.test.mjs keeps the two equal). Until
72
+ * 2026-11-05 the tools' schemas dropped them silently, so `profile: "other"` looked accepted.
73
+ */
74
+ export const OWNER_ONLY_BROWSER_FIELDS = Object.freeze([
75
+ ...OWNER_ONLY_CREATE_FIELDS, 'attachSeed', 'openTabsInBackground',
76
+ 'config', 'profile', 'profileDir', 'profilePath', 'userDataDir', 'executablePath',
77
+ 'moreloginProfile', 'moreloginEnv', 'moreloginEnvironment', 'cdpUrl', 'wsEndpoint',
78
+ ]);
79
+
80
+ /** The owner-only fields a create body names (an empty list when none). */
81
+ export function ownerOnlyCreateFields(body) {
82
+ if (!body || typeof body !== 'object') return [];
83
+ return OWNER_ONLY_BROWSER_FIELDS.filter((field) => body[field] !== undefined && body[field] !== null && body[field] !== '');
84
+ }
@@ -28,6 +28,17 @@ const closeTarget = (session, targetId) => within(Promise.resolve().then(() => s
28
28
  // How long the browser session stays attached for a tab asked for and not yet answered, to close it when it comes.
29
29
  const LATE_TARGET_MS = 60_000;
30
30
 
31
+ // The Browser that can open a browser-level CDP session: the one given, else the context's own (a persistent
32
+ // context is passed where a browser is expected and has none of its own methods for it).
33
+ function browserOf(browser, context) {
34
+ if (typeof browser?.newBrowserCDPSession === 'function') return browser;
35
+ try {
36
+ const owner = context?.browser?.();
37
+ if (typeof owner?.newBrowserCDPSession === 'function') return owner;
38
+ } catch { /* no owner */ }
39
+ return null;
40
+ }
41
+
31
42
  // The pages this module opened behind the selected tab.
32
43
  const backgroundPages = new WeakSet();
33
44
 
@@ -54,8 +65,9 @@ async function targetIdOf(context, page, until) {
54
65
  * the answer, so the caller is not kept waiting, and also when the browser only
55
66
  * creates it after the wait was given up — and the caller opens a normal one.
56
67
  */
57
- export async function openBackgroundPage(browser, context, { timeoutMs = 5000 } = {}) {
58
- if (typeof browser?.newBrowserCDPSession !== 'function') return null;
68
+ export async function openBackgroundPage(browser, context, { timeoutMs = 5000, browserContextId = null } = {}) {
69
+ browser = browserOf(browser, context);
70
+ if (!browser) return null;
59
71
  const until = Date.now() + timeoutMs;
60
72
  const left = () => Math.max(1, until - Date.now());
61
73
  const appeared = [];
@@ -70,7 +82,7 @@ export async function openBackgroundPage(browser, context, { timeoutMs = 5000 }
70
82
  cdp = await within(Promise.resolve().then(() => browser.newBrowserCDPSession()), left(), 'opening a browser CDP session', (late) => late?.detach?.());
71
83
  const session = cdp;
72
84
  let answered = false;
73
- const creating = Promise.resolve().then(() => session.send('Target.createTarget', { url: 'about:blank', background: true }));
85
+ const creating = Promise.resolve().then(() => session.send('Target.createTarget', { url: 'about:blank', background: true, ...(browserContextId && { browserContextId }) }));
74
86
  creating.then(() => { answered = true; }, () => { answered = true; });
75
87
  try {
76
88
  ({ targetId } = await within(creating, left(), 'creating the tab'));
@@ -132,3 +144,60 @@ export function selectedTabReading(page) {
132
144
  return { reading: 'unknown', basis: 'unreadable' };
133
145
  }
134
146
  }
147
+
148
+ /**
149
+ * Whether tabs open in the background: on unless browser-config.json says
150
+ * `openTabsInBackground: false` (only the boolean false turns it off; not set,
151
+ * or anything else, is on). Default on since 2026-11-08 so an automation on
152
+ * macOS never brings its window forward or switches the user's Space.
153
+ */
154
+ export function backgroundTabsEnabled(config) {
155
+ return config?.openTabsInBackground !== false;
156
+ }
157
+
158
+ /** The error of a tab that could not be opened in the background: never replaced by a foreground tab. */
159
+ export class BackgroundTabError extends Error {
160
+ constructor(attempts) {
161
+ super(`Could not open the browser tab in the background (${attempts} attempts). SynaBun does not open it in the foreground, which would bring the browser window forward; set openTabsInBackground to false in browser-config.json to allow that`);
162
+ this.name = 'BackgroundTabError';
163
+ this.code = 'BACKGROUND_TAB_FAILED';
164
+ }
165
+ }
166
+
167
+ /**
168
+ * openBackgroundPage, strictly: one retry, then BackgroundTabError. It never
169
+ * falls back to context.newPage(), which selects the tab and brings the
170
+ * window (and on macOS its Space) to the front. `timeoutMs` is per attempt.
171
+ */
172
+ export async function openBackgroundPageStrict(browser, context, { timeoutMs = 5000, attempts = 2, browserContextId = null, open = openBackgroundPage } = {}) {
173
+ for (let attempt = 1; attempt <= attempts; attempt += 1) {
174
+ const page = await Promise.resolve().then(() => open(browser, context, { timeoutMs, browserContextId })).catch(() => null);
175
+ if (page) return page;
176
+ if (attempt < attempts) console.warn(`[browser] background tab attempt ${attempt} failed; trying again in the background`);
177
+ }
178
+ throw new BackgroundTabError(attempts);
179
+ }
180
+
181
+ /**
182
+ * browser.newContext(options) plus the CDP id of the context it made, so a
183
+ * background tab can be created in it (Target.createTarget without an id
184
+ * opens in the default context). The id is the one that was not there before;
185
+ * null when that cannot be told (no CDP, or more than one new context).
186
+ */
187
+ export async function newContextWithId(browser, options) {
188
+ const ids = async () => {
189
+ const session = await browser.newBrowserCDPSession();
190
+ try { return (await session.send('Target.getBrowserContexts')).browserContextIds || []; } finally { detach(session); }
191
+ };
192
+ let before = null;
193
+ try { before = new Set(await ids()); } catch { /* unknown */ }
194
+ const context = await browser.newContext(options);
195
+ let browserContextId = null;
196
+ if (before) {
197
+ try {
198
+ const added = (await ids()).filter((id) => !before.has(id));
199
+ if (added.length === 1) [browserContextId] = added;
200
+ } catch { /* unknown */ }
201
+ }
202
+ return { context, browserContextId };
203
+ }
@@ -86,15 +86,28 @@ export function cancellableBrowserDelay(ms, req) {
86
86
  });
87
87
  }
88
88
 
89
+ /**
90
+ * The longest a browser request is answered after (/api/browser/*, and the run recovery POST /api/loop/recover-browser):
91
+ * a caller's X-Synabun-Deadline is honoured up to this. A browser start that is still running then is answered
92
+ * BROWSER_STARTING and kept for its caller (lib/browser-start-handoff.js). The MCP's create / recovery timeout
93
+ * (mcp-server/src/services/neural-interface.ts SESSION_CREATE_TIMEOUT) is longer, so it reads that answer, never a
94
+ * timeout of its own.
95
+ */
96
+ export const BROWSER_REQUEST_MAX_MS = 120_000;
97
+
98
+ /** A request's deadline: its X-Synabun-Deadline, at most BROWSER_REQUEST_MAX_MS from now. */
99
+ export function browserRequestDeadline(req, now = Date.now()) {
100
+ const requested = Number(req?.get?.('X-Synabun-Deadline'));
101
+ return Number.isFinite(requested) && requested > 0 ? Math.min(requested, now + BROWSER_REQUEST_MAX_MS) : now + BROWSER_REQUEST_MAX_MS;
102
+ }
103
+
89
104
  /** Metadata only: never logs URLs, selectors, form values, scripts or response bodies. */
90
105
  export function browserRequestMiddleware(req, res, next) {
91
106
  const controller = new AbortController();
92
107
  const start = performance.now();
93
108
  const supplied = req.get('X-Synabun-Request-Id');
94
109
  const requestId = /^[\w-]{1,80}$/.test(supplied || '') ? supplied : randomUUID();
95
- const requestedDeadline = Number(req.get('X-Synabun-Deadline'));
96
- const deadline = Number.isFinite(requestedDeadline) && requestedDeadline > 0
97
- ? Math.min(requestedDeadline, Date.now() + 120_000) : Date.now() + 120_000;
110
+ const deadline = browserRequestDeadline(req);
98
111
  const state = { requestId, deadline, signal: controller.signal, actionStarted: false, phases: {}, counts: {} };
99
112
  state.cancelForProtection = reason => { state.protectionError = String(reason); controller.abort(); };
100
113
  req.browserRequest = state;
@@ -11,9 +11,15 @@ function extractionError(message, code) {
11
11
  return Object.assign(new Error(message), { code });
12
12
  }
13
13
 
14
- /** Apply the output budget to complete items, after deduplication, preserving JSON. */
14
+ /**
15
+ * Apply the output budget to complete items, after deduplication, preserving JSON.
16
+ * `types` is read before the projection: the distinct `type` of the returned items (null for
17
+ * an item without a string one), so a caller whose `fields` drop `type` still knows what it got
18
+ * (browser_extract_tweets says "trend(s)" for an Explore tab's trends).
19
+ */
15
20
  export function budgetExtractionItems(items, { fields, maxItems = 50, maxChars } = {}) {
16
21
  const selected = [];
22
+ const types = new Set();
17
23
  let chars = 2; // JSON array brackets
18
24
  let reason;
19
25
  for (const item of items) {
@@ -22,9 +28,101 @@ export function budgetExtractionItems(items, { fields, maxItems = 50, maxChars }
22
28
  const size = JSON.stringify(value).length + (selected.length ? 1 : 0);
23
29
  if (maxChars !== undefined && chars + size > maxChars) { reason = 'max_chars'; break; }
24
30
  selected.push(value);
31
+ types.add(typeof item.type === 'string' ? item.type : null);
25
32
  chars += size;
26
33
  }
27
- return { items: selected, truncated: selected.length < items.length, budgetReason: reason };
34
+ return { items: selected, types: [...types], truncated: selected.length < items.length, budgetReason: reason };
35
+ }
36
+
37
+ // ── Page functions ──
38
+ // Everything that runs in the page is a function with the extractor and the scroll
39
+ // target written into its source. Playwright evaluates a function's source once,
40
+ // inside the DevTools call, which Chromium exempts from the page's Content Security
41
+ // Policy; the readiness polls that follow run the compiled function on the page's
42
+ // own timer, where the page's CSP applies and nothing may call eval. Until
43
+ // 2026-11-06 the polls did `(0, eval)(script)` in the page, and x.com, whose
44
+ // `script-src` has no 'unsafe-eval', refused the second poll of every scrolled
45
+ // extraction with an EvalError ("the tweet extractor doesn't work on X").
46
+
47
+ const BUSY_SELECTOR = '[aria-busy="true"], [role="progressbar"]';
48
+
49
+ /** An extractor or a scroll target is one JavaScript expression (statements go in an IIFE). */
50
+ function expressionSource(source, what) {
51
+ const text = typeof source === 'string' ? source.trim().replace(/;+\s*$/, '') : '';
52
+ if (!text) throw new Error(`${what} required`);
53
+ return text;
54
+ }
55
+
56
+ /**
57
+ * Compile a page function from its source. The function is only ever serialized for
58
+ * the page (Playwright sends its source and runs it there); nothing calls it here.
59
+ * A script that is not an expression fails here, before anything touches the page.
60
+ */
61
+ function pageFunction(parameter, body, what) {
62
+ try {
63
+ return new Function(parameter, body);
64
+ } catch (error) {
65
+ throw new Error(`${what} must be a JavaScript expression that returns an array of objects: ${error.message}`);
66
+ }
67
+ }
68
+
69
+ /**
70
+ * The four page functions of one extraction: the first read, the scroll (returns whether
71
+ * the scroll root was already loading), the readiness predicate `page.waitForFunction`
72
+ * polls, and the one read after a readiness timeout. None of them evaluates a string.
73
+ * Their own locals are `__sb`-prefixed: the extractor and the scroll target were evaluated
74
+ * in the page's global scope before, and an expression that names `items`, `root` or
75
+ * `target` must still mean the page's, never a local of the function around it.
76
+ */
77
+ export function extractionPageFunctions(script, scrollTarget = 'window') {
78
+ const items = expressionSource(script, 'Extractor script');
79
+ const target = expressionSource(scrollTarget, 'Scroll target');
80
+ const observe = `
81
+ const __sbTarget = (
82
+ ${target}
83
+ );
84
+ const __sbRoot = __sbTarget === window ? document : __sbTarget;
85
+ if (!__sbRoot) throw new Error('Scroll container disappeared while waiting.');
86
+ const __sbBusy = ${JSON.stringify(BUSY_SELECTOR)};
87
+ const __sbLoading = !!(__sbRoot.matches?.(__sbBusy) || __sbRoot.querySelector(__sbBusy));`;
88
+ return {
89
+ read: pageFunction('', `return (
90
+ ${items}
91
+ );`, 'Extractor script'),
92
+ scroll: pageFunction('__sbState', `
93
+ const __sbTarget = (
94
+ ${target}
95
+ );
96
+ if (!__sbTarget || typeof __sbTarget.scrollBy !== 'function') throw new Error('Scroll container not found.');
97
+ const __sbRoot = __sbTarget === window ? document : __sbTarget;
98
+ const __sbBusy = ${JSON.stringify(BUSY_SELECTOR)};
99
+ const __sbLoading = !!(__sbRoot.matches?.(__sbBusy) || __sbRoot.querySelector(__sbBusy));
100
+ __sbTarget.scrollBy(0, __sbState.distance);
101
+ return __sbLoading;`, 'Scroll target'),
102
+ readiness: pageFunction('__sbState', `
103
+ const __sbItems = (
104
+ ${items}
105
+ );
106
+ if (!Array.isArray(__sbItems)) throw new Error('Extractor must return an array of objects.');
107
+ const __sbKnown = new Set(__sbState.seen);
108
+ const __sbHasNew = __sbItems.some(__sbItem => {
109
+ if (!__sbItem || typeof __sbItem !== 'object' || Array.isArray(__sbItem)) throw new Error('Extractor must return an array of objects.');
110
+ let __sbKey;
111
+ for (const __sbField of __sbState.dedupeKeys) {
112
+ if (__sbItem[__sbField] !== null && __sbItem[__sbField] !== undefined && __sbItem[__sbField] !== '') { __sbKey = __sbField + ':' + __sbItem[__sbField]; break; }
113
+ }
114
+ return !__sbKnown.has(__sbKey ?? JSON.stringify(__sbItem));
115
+ });${observe}
116
+ // Playwright reuses this argument between predicate polls. Remember loading
117
+ // that begins after scroll dispatch as well as before it.
118
+ __sbState.loadingBefore ||= __sbLoading;
119
+ const __sbLoadingEnded = __sbState.loadingBefore && !__sbLoading;
120
+ return !__sbLoading && (__sbHasNew || __sbLoadingEnded) ? { items: __sbItems } : false;`, 'Extractor script'),
121
+ finalRead: pageFunction('', `${observe}
122
+ return { loading: __sbLoading, items: __sbLoading ? [] : (
123
+ ${items}
124
+ ) };`, 'Extractor script'),
125
+ };
28
126
  }
29
127
 
30
128
  /**
@@ -40,6 +138,8 @@ export async function runBrowserExtraction(page, script, opts = {}, runtime = {}
40
138
  const deadline = Math.min(Date.now() + timeoutMs, runtime.deadline ?? Infinity);
41
139
  const signal = runtime.signal;
42
140
  const measure = runtime.measure || ((_name, fn) => fn());
141
+ // A script that is not an expression is refused here, before any page call.
142
+ const fns = extractionPageFunctions(script, opts.scrollTarget || 'window');
43
143
  const collected = new Map();
44
144
  let raw = 0;
45
145
  let scrollsUsed = 0;
@@ -86,7 +186,7 @@ export async function runBrowserExtraction(page, script, opts = {}, runtime = {}
86
186
  }
87
187
 
88
188
  try {
89
- let items = await bounded('extraction', () => page.evaluate(script));
189
+ let items = await bounded('extraction', () => page.evaluate(fns.read));
90
190
  for (let round = 0; ; round++) {
91
191
  active();
92
192
  const added = merge(items);
@@ -100,60 +200,21 @@ export async function runBrowserExtraction(page, script, opts = {}, runtime = {}
100
200
  if (round >= scrolls + bonusRounds) break;
101
201
 
102
202
  const distance = (opts.scrollDistance ?? 1200) * (opts.scrollDirection ?? 1);
103
- const scrollTarget = opts.scrollTarget || 'window';
104
- const loadingBefore = await bounded('action', () => page.evaluate(({ scrollTarget, distance }) => {
105
- const target = (0, eval)(scrollTarget);
106
- if (!target || typeof target.scrollBy !== 'function') throw new Error('Scroll container not found.');
107
- const root = target === window ? document : target;
108
- const busy = '[aria-busy="true"], [role="progressbar"]';
109
- const loading = !!(root.matches?.(busy) || root.querySelector(busy));
110
- target.scrollBy(0, distance);
111
- return loading;
112
- }, { scrollTarget, distance }));
203
+ const loadingBefore = await bounded('action', () => page.evaluate(fns.scroll, { distance }));
113
204
  scrollsUsed++;
114
205
  // Poll inside the renderer, not over HTTP. Reuse the first newly visible
115
206
  // extraction so virtualized items cannot disappear between wait and read.
116
207
  const waitMs = Math.min(opts.settleMs ?? 3000, Math.max(1, deadline - Date.now()));
117
208
  try {
118
209
  items = await bounded('readiness', async () => {
119
- const handle = await page.waitForFunction(state => {
120
- const { script, dedupeKeys, seen, scrollTarget } = state;
121
- const items = (0, eval)(script);
122
- if (!Array.isArray(items)) throw new Error('Extractor must return an array of objects.');
123
- const known = new Set(seen);
124
- const hasNew = items.some(item => {
125
- if (!item || typeof item !== 'object' || Array.isArray(item)) throw new Error('Extractor must return an array of objects.');
126
- let key;
127
- for (const field of dedupeKeys) {
128
- if (item[field] !== null && item[field] !== undefined && item[field] !== '') { key = `${field}:${item[field]}`; break; }
129
- }
130
- return !known.has(key ?? JSON.stringify(item));
131
- });
132
- const target = (0, eval)(scrollTarget);
133
- const root = target === window ? document : target;
134
- if (!root) throw new Error('Scroll container disappeared while waiting.');
135
- const busy = '[aria-busy="true"], [role="progressbar"]';
136
- const loading = !!(root.matches?.(busy) || root.querySelector(busy));
137
- // Playwright reuses this argument between predicate polls. Remember
138
- // loading that begins after scroll dispatch as well as before it.
139
- state.loadingBefore ||= loading;
140
- const loadingEnded = state.loadingBefore && !loading;
141
- return !loading && (hasNew || loadingEnded) ? { items } : false;
142
- }, { script, dedupeKeys, seen: [...collected.keys()], scrollTarget, loadingBefore }, { timeout: waitMs, polling: 50 });
210
+ const handle = await page.waitForFunction(fns.readiness, { dedupeKeys, seen: [...collected.keys()], loadingBefore }, { timeout: waitMs, polling: 50 });
143
211
  try { return (await handle.jsonValue()).items; } finally { await handle.dispose(); }
144
212
  });
145
213
  } catch (error) {
146
214
  if (error.name !== 'TimeoutError') throw error;
147
215
  // Read once at the readiness boundary, but never accept known loading
148
216
  // skeletons merely because the readiness timer elapsed.
149
- const finalRead = await bounded('extraction', () => page.evaluate(({ script, scrollTarget }) => {
150
- const target = (0, eval)(scrollTarget);
151
- const root = target === window ? document : target;
152
- if (!root) throw new Error('Scroll container disappeared while waiting.');
153
- const busy = '[aria-busy="true"], [role="progressbar"]';
154
- const loading = !!(root.matches?.(busy) || root.querySelector(busy));
155
- return { loading, items: loading ? [] : (0, eval)(script) };
156
- }, { script, scrollTarget }));
217
+ const finalRead = await bounded('extraction', () => page.evaluate(fns.finalRead));
157
218
  if (finalRead.loading) throw extractionError('Feed is still loading after the readiness deadline; collected items are preserved.', 'readiness_timeout');
158
219
  items = finalRead.items;
159
220
  }
@@ -0,0 +1,48 @@
1
+ // ── Who owns a browser tab, as the routes read it (DOM-free) ──
2
+ //
3
+ // Every automation that uses SynaBun's browser names itself in X-Synabun-Terminal (its MCP sends it on every
4
+ // request): a loop's terminal id, a native run's or a dispatched worker's run id, a sidepanel's owner key, an MCP
5
+ // process's client id, and `agent:<uuid>` for an automation-window agent (server.js launchAgentController). Before
6
+ // 2026-11-04 two routes only took `[A-Za-z0-9_-]`, so an agent's own id was read as no id at all: its recovery was
7
+ // filed under a random owner, and its next call was refused that tab as "claimed by another" (a create loop and an
8
+ // orphan tab per round). One test for every route: browserOwnerId(). The MCP side (mcp-server identity.ts
9
+ // sanitizePin) accepts the same characters.
10
+
11
+ /** The ids the server mints: letters, digits, `_`, `-`, and `:` (`agent:<uuid>`). No spaces, no template junk. */
12
+ export const BROWSER_OWNER_ID_RE = /^[A-Za-z0-9_:-]{1,128}$/;
13
+
14
+ /** `value` as an owner id, or null (absent, not a string, or not shaped like one the server mints). */
15
+ export function browserOwnerId(value) {
16
+ return typeof value === 'string' && BROWSER_OWNER_ID_RE.test(value) ? value : null;
17
+ }
18
+
19
+ /**
20
+ * The owner keys of one session as GET /api/browser/sessions shows them. The owner's own page (`reveal`) sees every
21
+ * key (collision debugging). Anyone else sees its own key as it is and the other owners only as `other-1`, `other-2`…
22
+ * in a stable order: an automation needs to know that another one holds a tab (never adopt it), not which run that is.
23
+ * A run's key is what X-Synabun-Terminal names, so handing it out would let one agent speak as another run.
24
+ * @param {Map<string,string>|null|undefined} tabOwners owner key → tab id
25
+ * @param {{ loops?: Iterable<string>, interactive?: Iterable<string>, agents?: Iterable<string> }} sets
26
+ * @param {{ caller?: string|null, reveal?: boolean }} opts
27
+ * @returns {{ tabOwners: Record<string,string>, owners: { loops: string[], interactive: string[], agents: string[] } }}
28
+ */
29
+ export function listedOwners(tabOwners, { loops = [], interactive = [], agents = [] } = {}, { caller = null, reveal = false } = {}) {
30
+ const tabEntries = tabOwners ? [...tabOwners] : [];
31
+ const lists = { loops: [...loops], interactive: [...interactive], agents: [...agents] };
32
+ if (reveal) return { tabOwners: Object.fromEntries(tabEntries), owners: lists };
33
+ const labels = new Map();
34
+ const label = (key) => {
35
+ if (caller && key === caller) return key;
36
+ if (!labels.has(key)) labels.set(key, `other-${labels.size + 1}`);
37
+ return labels.get(key);
38
+ };
39
+ return {
40
+ tabOwners: Object.fromEntries(tabEntries.map(([key, tabId]) => [label(key), tabId])),
41
+ // An agent is listed by its agent id; its routing key is `agent:<id>`: the caller's own when it is that agent.
42
+ owners: {
43
+ loops: lists.loops.map(label),
44
+ interactive: lists.interactive.map(label),
45
+ agents: lists.agents.map((agentId) => (caller && caller === `agent:${agentId}` ? agentId : label(`agent:${agentId}`))),
46
+ },
47
+ };
48
+ }