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,345 @@
1
+ // ═══════════════════════════════════════════
2
+ // SynaBun — Maritaca for OpenCode: the stream and request repairs (pure)
3
+ // ═══════════════════════════════════════════
4
+ //
5
+ // OpenCode 2 (2.2.5) reads an OpenAI-compatible provider's stream with its "OpenAI Chat" protocol, which refuses a
6
+ // chunk that carries tool-call deltas (an id, a name or arguments) once an earlier chunk has carried `finish_reason`:
7
+ // "OpenAI Chat received content after the finish reason". No `compatibility` option of OpenCode turns that check off
8
+ // (requireFinishReason, streamUsage, maxTokensField… do not touch it), and every OpenAI-style package of OpenCode reads
9
+ // through the same step. Maritaca's streaming API does exactly that on a tool call: a chunk with `finish_reason`, then
10
+ // tool-call deltas. So OpenCode's requests for Maritaca go through SynaBun (lib/maritaca/opencode-proxy.js), which hands
11
+ // every chunk to the normalizer below before OpenCode sees it:
12
+ //
13
+ // • `finish_reason` (and `native_finish_reason`) is taken off every chunk and said once, in a last chunk of its own,
14
+ // after everything else the stream carried (text, reasoning and tool calls that came after it included). Several
15
+ // finish reasons become one: the first, unless a later one says more than "stop".
16
+ // • Tool-call deltas are held and folded into whole calls, sent as one chunk right before that finish: a call the
17
+ // server repeats after the finish (the same arguments again, or the whole arguments where the pieces were partial)
18
+ // is one call, never two and never doubled arguments; a call without an id gets one (OpenCode refuses a call without
19
+ // an id or a name); `arguments` sent as an object are sent as JSON text; no arguments at all are "{}".
20
+ // • Text, reasoning and usage pass through as they come (reasoning in whichever field Maritaca names it: OpenCode reads
21
+ // reasoning_content, reasoning and reasoning_text). An `error` chunk passes untouched.
22
+ // • A stream that ended with [DONE] but never named a finish reason gets one ("tool_calls" when it carried calls,
23
+ // else "stop"); one that broke off without [DONE] does not, so OpenCode still says the stream was cut short.
24
+ //
25
+ // What arrived after the finish is recorded by its shape only (the names of the fields, the counts), never a value, so
26
+ // a log line can say what Maritaca sent without repeating a word of the conversation or its tool arguments.
27
+ //
28
+ // `prepareUpstreamBody` is the request side: OpenCode echoes a thinking model's reasoning back on the assistant
29
+ // messages of the history (as `reasoning_content` / `reasoning`, the field it read it from, plus OpenRouter's
30
+ // `reasoning_details`); SynaBun's own Maritaca panel never sends those, and a conversation with Sabiá 4 Thinking works
31
+ // that way, so they are left out of what reaches Maritaca. Nothing else in the request is changed.
32
+
33
+ import { randomBytes } from 'node:crypto';
34
+
35
+ /** The fields of an assistant message that carry reasoning back, taken out before a request reaches Maritaca. */
36
+ export const REASONING_ECHO_FIELDS = Object.freeze(['reasoning_content', 'reasoning', 'reasoning_text', 'reasoning_details']);
37
+ const REASONING_DELTA_FIELDS = Object.freeze(['reasoning_content', 'reasoning', 'reasoning_text']);
38
+ const MAX_SHAPES = 12;
39
+
40
+ const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
41
+ const newCallId = () => `call_${randomBytes(12).toString('hex')}`;
42
+
43
+ /** Text that parses as one whole JSON object or array (the arguments of a finished call). */
44
+ function wholeJson(text) {
45
+ if (typeof text !== 'string' || !text.trim()) return null;
46
+ try { const value = JSON.parse(text); return value !== null && typeof value === 'object' ? value : null; } catch { return null; }
47
+ }
48
+
49
+ /** Canonical text of a JSON value with its object keys sorted: two spellings of the same arguments compare equal. */
50
+ function canonical(value) {
51
+ if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;
52
+ if (isObject(value)) return `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${canonical(value[k])}`).join(',')}}`;
53
+ return JSON.stringify(value);
54
+ }
55
+
56
+ /**
57
+ * The names (never the values) of the fields a chunk carries, as paths: `choices[].delta.tool_calls[].function.name`.
58
+ * Bounded in depth and in count.
59
+ */
60
+ export function shapeOf(value, prefix = '', depth = 0, out = new Set()) {
61
+ if (out.size >= 40 || depth > 8) return out;
62
+ if (Array.isArray(value)) {
63
+ for (const item of value.slice(0, 8)) shapeOf(item, `${prefix}[]`, depth + 1, out);
64
+ if (!value.length) out.add(`${prefix}[]`);
65
+ return out;
66
+ }
67
+ if (isObject(value)) {
68
+ for (const key of Object.keys(value)) {
69
+ if (value[key] === null || value[key] === undefined) continue;
70
+ const path = prefix ? `${prefix}.${key}` : key;
71
+ if (isObject(value[key]) || Array.isArray(value[key])) shapeOf(value[key], path, depth + 1, out);
72
+ else out.add(path);
73
+ }
74
+ }
75
+ return out;
76
+ }
77
+
78
+ /** A shape as one short line: the paths sorted, the meta fields (id, object, created, model…) left out. */
79
+ export function shapeLine(chunk) {
80
+ const meta = new Set(['id', 'object', 'created', 'model', 'system_fingerprint', 'service_tier', 'provider']);
81
+ return [...shapeOf(chunk)].filter((p) => !meta.has(p) && !/^choices\[\]\.(index|logprobs)$/.test(p)).sort().join(', ') || '(empty)';
82
+ }
83
+
84
+ /**
85
+ * The normalizer of one streamed chat completion. `push(chunk)` takes one parsed `data:` payload and returns the payloads
86
+ * to send on now (zero or more, in order); `end({ done })` returns the last ones (the held tool calls, the one finish
87
+ * chunk) once the stream is over (`done`: Maritaca sent [DONE]); `report()` says what had to be repaired.
88
+ */
89
+ export function createChatStreamNormalizer({ newId = newCallId } = {}) {
90
+ const meta = {}; // id, object, created, model, system_fingerprint of the latest chunk that named them
91
+ const finishes = new Map(); // choice index → { reason, native }
92
+ const calls = new Map(); // choice index → { list: [call], byKey: Map }
93
+ let afterFinish = false;
94
+ let ended = false;
95
+ const stats = {
96
+ finishChunks: 0, finishSynthesized: false, finishReasons: [],
97
+ afterFinish: { chunks: 0, text: 0, reasoning: 0, toolDeltas: 0, usage: 0 },
98
+ toolCalls: 0, toolDeltas: 0, duplicateFragments: 0, snapshots: 0, conflicts: 0, idsAdded: 0, indexesAdded: 0,
99
+ shapes: [],
100
+ };
101
+
102
+ function remember(chunk) {
103
+ for (const key of ['id', 'object', 'created', 'model', 'system_fingerprint']) {
104
+ if (chunk[key] !== undefined && chunk[key] !== null && chunk[key] !== '') meta[key] = chunk[key];
105
+ }
106
+ }
107
+
108
+ function noteFinish(index, reason, native) {
109
+ stats.finishChunks += 1;
110
+ if (!stats.finishReasons.includes(reason) && stats.finishReasons.length < 6) stats.finishReasons.push(reason);
111
+ const held = finishes.get(index);
112
+ // The first reason, unless a later one says more than "stop" (a server that says stop, then tool_calls).
113
+ if (!held || (held.reason === 'stop' && reason !== 'stop')) finishes.set(index, { reason, native: native ?? held?.native ?? null });
114
+ }
115
+
116
+ function callsOf(index) {
117
+ if (!calls.has(index)) calls.set(index, { list: [], byKey: new Map() });
118
+ return calls.get(index);
119
+ }
120
+
121
+ /** One tool-call delta folded into its call. */
122
+ function foldToolPiece(index, piece, position, pieceCount) {
123
+ if (!isObject(piece)) return;
124
+ stats.toolDeltas += 1;
125
+ const group = callsOf(index);
126
+ const id = typeof piece.id === 'string' && piece.id.trim() && piece.id !== 'null' ? piece.id.trim() : '';
127
+ const fn = isObject(piece.function) ? piece.function : {};
128
+ const name = typeof fn.name === 'string' ? fn.name.trim() : '';
129
+ // Which call: an id already seen names its call whatever the index says (a repeat under another index is the same
130
+ // call); then the index; then, without either, a new call when the piece names a function, else the latest call.
131
+ let call = id ? group.list.find((c) => c.id === id) : undefined;
132
+ if (!call && Number.isInteger(piece.index)) call = group.byKey.get(`i${piece.index}`);
133
+ if (!call && !Number.isInteger(piece.index)) {
134
+ const latest = group.list[group.list.length - 1];
135
+ if (pieceCount > 1) call = group.byKey.get(`p${position}`);
136
+ else if (latest && !name) call = latest;
137
+ else if (latest && name === latest.name && !(id && latest.id && id !== latest.id)) {
138
+ // The latest call's name again, without an index: the same call restated (its arguments partial, or the same
139
+ // whole arguments again), or a new call of the same function (whole, different arguments, or none yet).
140
+ const held = wholeJson(latest.args);
141
+ const raw = isObject(fn.arguments) || Array.isArray(fn.arguments) ? JSON.stringify(fn.arguments) : fn.arguments;
142
+ const incoming = wholeJson(raw);
143
+ if (!held || (incoming && canonical(incoming) === canonical(held))) call = latest;
144
+ }
145
+ }
146
+ if (!call) {
147
+ call = { id: '', name: '', args: '' };
148
+ group.list.push(call);
149
+ if (Number.isInteger(piece.index)) group.byKey.set(`i${piece.index}`, call);
150
+ else { stats.indexesAdded += 1; if (pieceCount > 1) group.byKey.set(`p${position}`, call); }
151
+ }
152
+ if (id && !call.id) call.id = id;
153
+ if (name && !call.name) call.name = name;
154
+ let args = fn.arguments;
155
+ if (isObject(args) || Array.isArray(args)) args = JSON.stringify(args);
156
+ if (typeof args !== 'string' || !args) return;
157
+ const held = wholeJson(call.args);
158
+ if (held) {
159
+ const incoming = wholeJson(args);
160
+ if (incoming && canonical(incoming) === canonical(held)) { stats.duplicateFragments += 1; return; }
161
+ if (incoming) { call.args = args; stats.conflicts += 1; return; } // two whole, different answers: the later one stands
162
+ if (args.trim() === call.args.trim()) { stats.duplicateFragments += 1; return; }
163
+ call.args += args; // a whole object cannot be continued: OpenCode will say the arguments are not JSON, as it would have
164
+ return;
165
+ }
166
+ if (call.args && args.length > call.args.length && args.startsWith(call.args) && wholeJson(args)) { call.args = args; stats.snapshots += 1; return; }
167
+ call.args += args;
168
+ }
169
+
170
+ function push(chunk) {
171
+ if (ended) return [];
172
+ if (!isObject(chunk)) return [chunk];
173
+ if (chunk.error !== undefined && chunk.error !== null) return [chunk];
174
+ remember(chunk);
175
+ if (afterFinish) {
176
+ stats.afterFinish.chunks += 1;
177
+ if (chunk.usage) stats.afterFinish.usage += 1;
178
+ const line = shapeLine(chunk);
179
+ if (!stats.shapes.includes(line) && stats.shapes.length < MAX_SHAPES) stats.shapes.push(line);
180
+ }
181
+ if (!Array.isArray(chunk.choices)) return [chunk];
182
+ const choices = [];
183
+ let changed = false;
184
+ chunk.choices.forEach((choice, position) => {
185
+ if (!isObject(choice)) { choices.push(choice); return; }
186
+ const index = Number.isInteger(choice.index) ? choice.index : position;
187
+ const copy = { ...choice };
188
+ let touched = false;
189
+ const delta = isObject(choice.delta) ? { ...choice.delta } : null;
190
+ if (delta) {
191
+ if (afterFinish) {
192
+ if (typeof delta.content === 'string' && delta.content) stats.afterFinish.text += 1;
193
+ if (REASONING_DELTA_FIELDS.some((f) => typeof delta[f] === 'string' && delta[f])) stats.afterFinish.reasoning += 1;
194
+ }
195
+ if ('tool_calls' in delta) {
196
+ const pieces = Array.isArray(delta.tool_calls) ? delta.tool_calls : [];
197
+ if (afterFinish && pieces.length) stats.afterFinish.toolDeltas += pieces.length;
198
+ pieces.forEach((piece, i) => foldToolPiece(index, piece, i, pieces.length));
199
+ delete delta.tool_calls;
200
+ touched = true;
201
+ }
202
+ copy.delta = delta;
203
+ }
204
+ if (choice.finish_reason !== undefined && choice.finish_reason !== null) {
205
+ noteFinish(index, String(choice.finish_reason), choice.native_finish_reason ?? null);
206
+ afterFinish = true;
207
+ touched = true;
208
+ }
209
+ if ('finish_reason' in copy) copy.finish_reason = null;
210
+ if ('native_finish_reason' in copy) delete copy.native_finish_reason;
211
+ if (touched) changed = true;
212
+ // A choice left with nothing to say once its tool calls and finish are taken off is not sent.
213
+ const rest = Object.keys(copy).filter((k) => !['index', 'finish_reason', 'delta', 'logprobs'].includes(k) && copy[k] !== null && copy[k] !== undefined);
214
+ const deltaSays = delta && Object.keys(delta).some((k) => delta[k] !== null && delta[k] !== undefined && delta[k] !== '');
215
+ if (touched && !deltaSays && !rest.length && (copy.logprobs === undefined || copy.logprobs === null)) return;
216
+ choices.push(copy);
217
+ });
218
+ if (!changed) return [chunk];
219
+ const others = Object.keys(chunk).filter((k) => !['id', 'object', 'created', 'model', 'system_fingerprint', 'choices'].includes(k) && chunk[k] !== null && chunk[k] !== undefined);
220
+ if (!choices.length && !others.length) return [];
221
+ return [{ ...chunk, choices }];
222
+ }
223
+
224
+ function base() {
225
+ return { ...(meta.id !== undefined ? { id: meta.id } : {}), object: meta.object || 'chat.completion.chunk', ...(meta.created !== undefined ? { created: meta.created } : {}), ...(meta.model !== undefined ? { model: meta.model } : {}), ...(meta.system_fingerprint !== undefined ? { system_fingerprint: meta.system_fingerprint } : {}) };
226
+ }
227
+
228
+ function end({ done = false } = {}) {
229
+ if (ended) return [];
230
+ ended = true;
231
+ const out = [];
232
+ const indexes = [...new Set([...calls.keys(), ...finishes.keys()])].sort((a, b) => a - b);
233
+ const callChoices = [];
234
+ for (const index of indexes) {
235
+ const group = calls.get(index);
236
+ if (!group?.list.length) continue;
237
+ const toolCalls = group.list.map((call, i) => {
238
+ if (!call.id) { call.id = newId(); stats.idsAdded += 1; }
239
+ stats.toolCalls += 1;
240
+ return { index: i, id: call.id, type: 'function', function: { name: call.name, arguments: call.args.trim() ? call.args : '{}' } };
241
+ });
242
+ callChoices.push({ index, delta: { tool_calls: toolCalls }, finish_reason: null });
243
+ }
244
+ if (callChoices.length) out.push({ ...base(), choices: callChoices });
245
+ if (!finishes.size && done) {
246
+ // [DONE] without a finish reason: the stream ended as the server meant it to; say how.
247
+ finishes.set(indexes[0] ?? 0, { reason: callChoices.length ? 'tool_calls' : 'stop', native: null });
248
+ stats.finishSynthesized = true;
249
+ }
250
+ if (finishes.size) {
251
+ const finishChoices = [...finishes].sort((a, b) => a[0] - b[0]).map(([index, f]) => ({ index, delta: {}, finish_reason: f.reason, ...(f.native ? { native_finish_reason: f.native } : {}) }));
252
+ out.push({ ...base(), choices: finishChoices });
253
+ }
254
+ return out;
255
+ }
256
+
257
+ /**
258
+ * What the stream needed: `repaired` when Maritaca sent something OpenCode refuses or would read wrong (content after
259
+ * the finish, several finishes, a repeated or restated call, a call without an id, no finish before [DONE]). A chunk
260
+ * with only usage after the finish is OpenAI's own shape (stream_options.include_usage), not a repair.
261
+ */
262
+ function report() {
263
+ const finish = [...finishes.values()][0]?.reason ?? null;
264
+ const a = stats.afterFinish;
265
+ const repaired = a.text + a.reasoning + a.toolDeltas > 0 || stats.finishChunks > 1 || stats.duplicateFragments > 0 || stats.snapshots > 0
266
+ || stats.conflicts > 0 || stats.idsAdded > 0 || stats.finishSynthesized;
267
+ return { ...stats, afterFinish: { ...stats.afterFinish }, finishReasons: [...stats.finishReasons], shapes: [...stats.shapes], finishReason: finish, repaired };
268
+ }
269
+
270
+ return { push, end, report, get finished() { return finishes.size > 0; } };
271
+ }
272
+
273
+ /** One line for the log: what Maritaca sent after its finish reason and what was repaired, without a single value. */
274
+ export function describeRepair(report, { model = '' } = {}) {
275
+ if (!report?.repaired) return '';
276
+ const parts = [];
277
+ const a = report.afterFinish || {};
278
+ if ((a.text || 0) + (a.reasoning || 0) + (a.toolDeltas || 0) > 0) {
279
+ const what = [a.toolDeltas ? `${a.toolDeltas} tool-call delta(s)` : '', a.text ? `${a.text} text delta(s)` : '', a.reasoning ? `${a.reasoning} reasoning delta(s)` : '', a.usage ? `${a.usage} usage` : ''].filter(Boolean).join(', ') || 'nothing OpenCode reads';
280
+ parts.push(`finish_reason ${JSON.stringify(report.finishReasons?.[0] ?? report.finishReason)} was followed by ${a.chunks} chunk(s) (${what}) [${(report.shapes || []).join(' | ')}]`);
281
+ }
282
+ if (report.finishChunks > 1) parts.push(`${report.finishChunks} finish chunks (${(report.finishReasons || []).join(', ')}) made one`);
283
+ if (report.duplicateFragments) parts.push(`${report.duplicateFragments} repeated tool-call fragment(s) dropped`);
284
+ if (report.snapshots) parts.push(`${report.snapshots} whole-arguments restatement(s) taken in place of the pieces`);
285
+ if (report.conflicts) parts.push(`${report.conflicts} conflicting restatement(s): the later arguments kept`);
286
+ if (report.idsAdded) parts.push(`${report.idsAdded} tool-call id(s) added`);
287
+ if (report.finishSynthesized) parts.push(`no finish_reason before [DONE]: ${JSON.stringify(report.finishReason)} said`);
288
+ return `[maritaca] OpenCode stream repaired${model ? ` (${String(model).slice(0, 60)})` : ''}: ${parts.join('; ')}`;
289
+ }
290
+
291
+ /**
292
+ * The lines of a server-sent-events body, chunk by chunk (bytes or text): `push(chunk)` returns the complete lines,
293
+ * `end()` the last one when the body did not end with a newline. CRLF and CR-free line ends both read; a character
294
+ * split across two chunks is put back together.
295
+ */
296
+ export function createSseLineReader() {
297
+ const decoder = new TextDecoder();
298
+ let buffer = '';
299
+ function lines() {
300
+ const out = [];
301
+ let at;
302
+ while ((at = buffer.indexOf('\n')) >= 0) {
303
+ out.push(buffer.slice(0, at).replace(/\r$/, ''));
304
+ buffer = buffer.slice(at + 1);
305
+ }
306
+ return out;
307
+ }
308
+ return {
309
+ push(chunk) { buffer += typeof chunk === 'string' ? chunk : decoder.decode(chunk, { stream: true }); return lines(); },
310
+ end() { buffer += decoder.decode(); const out = lines(); if (buffer.trim()) out.push(buffer.replace(/\r$/, '')); buffer = ''; return out; },
311
+ };
312
+ }
313
+
314
+ /**
315
+ * One line of the stream, read: `{ kind: 'data', payload }` (parsed JSON), `{ kind: 'done' }` ([DONE]),
316
+ * `{ kind: 'raw', data }` (a data line that is not JSON: sent on as it was), `{ kind: 'comment', line }` (a keep-alive),
317
+ * or null (a blank line, an `event:` / `id:` / `retry:` field: OpenAI-style streams carry nothing there).
318
+ */
319
+ export function readSseLine(line) {
320
+ const text = String(line ?? '');
321
+ if (!text.trim()) return null;
322
+ if (text.startsWith(':')) return { kind: 'comment', line: text };
323
+ if (!text.startsWith('data:')) return null;
324
+ const data = text.slice(5).trim();
325
+ if (!data) return null;
326
+ if (data === '[DONE]') return { kind: 'done' };
327
+ try { return { kind: 'data', payload: JSON.parse(data) }; } catch { return { kind: 'raw', data }; }
328
+ }
329
+
330
+ /**
331
+ * The request as it goes to Maritaca: a copy of OpenCode's body without the reasoning echoed on assistant messages
332
+ * (REASONING_ECHO_FIELDS). Returns { body, strippedReasoning } (how many messages lost a field); the input is never changed.
333
+ */
334
+ export function prepareUpstreamBody(body) {
335
+ if (!isObject(body)) return { body, strippedReasoning: 0 };
336
+ let strippedReasoning = 0;
337
+ const messages = Array.isArray(body.messages) ? body.messages.map((m) => {
338
+ if (!isObject(m) || m.role !== 'assistant' || !REASONING_ECHO_FIELDS.some((f) => f in m)) return m;
339
+ const copy = { ...m };
340
+ for (const f of REASONING_ECHO_FIELDS) delete copy[f];
341
+ strippedReasoning += 1;
342
+ return copy;
343
+ }) : body.messages;
344
+ return { body: { ...body, ...(Array.isArray(body.messages) ? { messages } : {}) }, strippedReasoning };
345
+ }
@@ -0,0 +1,218 @@
1
+ // ═══════════════════════════════════════════
2
+ // SynaBun — Maritaca AI as an OpenCode provider (Settings → OpenCode → Providers)
3
+ // ═══════════════════════════════════════════
4
+ //
5
+ // Maritaca's API is OpenAI-compatible, so OpenCode's own `@opencode/ai/providers/openai-compatible` package drives
6
+ // it (the same package the Ollama card writes: nothing is installed). Its base URL is SynaBun's own route
7
+ // (lib/maritaca/opencode-proxy.js, http://127.0.0.1:<port>/api/maritaca/opencode/v1), not Maritaca's API: OpenCode 2
8
+ // refuses Maritaca's stream on the first tool call ("received content after the finish reason"), and the route puts
9
+ // the stream in the order OpenCode reads. A block written before that (Maritaca's address) reads as out of sync, so
10
+ // the Settings card offers Re-sync. The provider block goes into the user's global
11
+ // opencode.json under `providers.maritaca` with every Sabiá model of models.js, and the API key as a reference OpenCode
12
+ // resolves when it reads its configuration (`{file:<the key file>}` for a saved key, `{env:MARITACA_API_KEY}` for an
13
+ // environment key): the key itself is never written into opencode.json and never logged. OpenCode reads the change at
14
+ // once (reloadSharedOpencodeConfig in server.js, as the Ollama path does): no restart. The Maritaca panel's own chat
15
+ // (lib/maritaca/client.js) does not go through OpenCode; this is for OpenCode workers and the Assistant's catalog,
16
+ // which lists OpenCode's connected providers as `opencode` models (`maritaca/<model-id>`).
17
+ //
18
+ // The pure part (the entry, the key reference, the state of a document) is unit-tested; the factory takes what
19
+ // server.js has (the config document reader and writer, OpenCode's own conversion of an OpenCode 1 provider section,
20
+ // the reload, the broadcast) so nothing here opens a file by itself.
21
+
22
+ import { join } from 'node:path';
23
+ import { MARITACA_MODELS } from './models.js';
24
+ import { MARITACA_BASE_URL } from './client.js';
25
+ import { MARITACA_ENV_KEY, MARITACA_KEY_FILE } from './key-store.js';
26
+ import { MARITACA_OPENCODE_PROXY_URL_RE } from './opencode-proxy.js';
27
+ import { hasOpencode1Providers, providerOf, removeProvider, setProvider } from '../opencode-config.js';
28
+
29
+ export const MARITACA_OPENCODE_PROVIDER_ID = 'maritaca';
30
+ export const MARITACA_OPENCODE_PROVIDER_NAME = 'Maritaca AI';
31
+ export const MARITACA_OPENCODE_PACKAGE = '@opencode/ai/providers/openai-compatible';
32
+
33
+ /** How OpenCode is told the key: a reference it resolves itself, never the key. null without a key. */
34
+ export function maritacaApiKeyReference({ source, keyPath } = {}) {
35
+ if (source === 'file' && keyPath) return `{file:${keyPath}}`;
36
+ if (source === 'env') return `{env:${MARITACA_ENV_KEY}}`;
37
+ return null;
38
+ }
39
+
40
+ /**
41
+ * OpenCode's `models` map of the table: name, limits and whether the model takes tools (prices are in BRL and would be
42
+ * read as USD). OpenCode 2's Config.Model says tools under `capabilities.tools` (default true when absent), so a row
43
+ * with `toolcall: false` (S5-free) is written `capabilities: { tools: false }` and OpenCode never sends it tools.
44
+ */
45
+ export function maritacaOpencodeModels(models = MARITACA_MODELS) {
46
+ const out = {};
47
+ for (const m of Array.isArray(models) ? models : []) {
48
+ if (!m || typeof m.id !== 'string' || !m.id.trim()) continue;
49
+ const entry = { name: String(m.label || m.id) };
50
+ const context = Number(m.contextWindow); const output = Number(m.maxOutput);
51
+ if (context > 0 || output > 0) entry.limit = { ...(context > 0 ? { context } : {}), ...(output > 0 ? { output } : {}) };
52
+ if (typeof m.toolcall === 'boolean') entry.capabilities = { tools: m.toolcall };
53
+ out[m.id] = entry;
54
+ }
55
+ return out;
56
+ }
57
+
58
+ /** Each model's tools flag as a block says it: `{ id: true | false | null }` (null: the block does not say). */
59
+ function toolFlags(models) {
60
+ const out = {};
61
+ for (const [id, m] of Object.entries(models && typeof models === 'object' ? models : {})) {
62
+ const tools = m?.capabilities?.tools;
63
+ out[id] = typeof tools === 'boolean' ? tools : null;
64
+ }
65
+ return out;
66
+ }
67
+
68
+ /** The `providers.maritaca` block of opencode.json. `apiKey` is a reference from maritacaApiKeyReference, required. */
69
+ export function maritacaOpencodeProviderEntry({ apiKey, models = MARITACA_MODELS, baseUrl = MARITACA_BASE_URL } = {}) {
70
+ if (typeof apiKey !== 'string' || !/^\{(file|env):[^{}]+\}$/.test(apiKey)) throw Object.assign(new Error('The API key must be an OpenCode reference ({file:…} or {env:…}).'), { code: 'KEY_REFERENCE' });
71
+ return {
72
+ name: MARITACA_OPENCODE_PROVIDER_NAME,
73
+ package: MARITACA_OPENCODE_PACKAGE,
74
+ settings: { baseURL: String(baseUrl).replace(/\/+$/, ''), apiKey },
75
+ models: maritacaOpencodeModels(models),
76
+ };
77
+ }
78
+
79
+ const trimUrl = (url) => String(url ?? '').trim().replace(/\/+$/, '');
80
+
81
+ /**
82
+ * Where a block's base URL sends OpenCode: 'synabun' (a SynaBun server's route, lib/maritaca/opencode-proxy.js),
83
+ * 'maritaca' (Maritaca's API itself: a block written before the route, whose tool calls OpenCode refuses), 'other'
84
+ * (anything else, a hand edit), or null (no base URL).
85
+ */
86
+ export function maritacaOpencodeRoute(baseUrl) {
87
+ const url = trimUrl(baseUrl);
88
+ if (!url) return null;
89
+ if (MARITACA_OPENCODE_PROXY_URL_RE.test(url)) return 'synabun';
90
+ if (url === trimUrl(MARITACA_BASE_URL)) return 'maritaca';
91
+ return 'other';
92
+ }
93
+
94
+ /**
95
+ * What a document and the key store say together: whether the provider is registered, how many models it lists,
96
+ * whether the block matches what SynaBun would write now (`inSync`: the key reference, the model ids and the base URL
97
+ * `baseUrl`, this server's route), and where the block sends OpenCode (`route`). Never the key.
98
+ */
99
+ export function maritacaOpencodeState({ config, keyStatus, keyPath, models = MARITACA_MODELS, baseUrl = MARITACA_BASE_URL } = {}) {
100
+ const entry = providerOf(config, MARITACA_OPENCODE_PROVIDER_ID);
101
+ const source = keyStatus?.configured ? keyStatus.source || null : null;
102
+ const expectedKey = maritacaApiKeyReference({ source, keyPath });
103
+ const currentKey = typeof entry?.settings?.apiKey === 'string' ? entry.settings.apiKey : null;
104
+ const currentIds = Object.keys(entry?.models && typeof entry.models === 'object' ? entry.models : {}).sort();
105
+ const expectedModels = maritacaOpencodeModels(models);
106
+ const expectedIds = Object.keys(expectedModels).sort();
107
+ // A block written before the tools flag (or edited by hand) is out of sync: OpenCode would send S5-free tools.
108
+ const currentTools = toolFlags(entry?.models);
109
+ const expectedTools = toolFlags(expectedModels);
110
+ const toolsInSync = expectedIds.every((id) => currentTools[id] === expectedTools[id]);
111
+ const currentUrl = typeof entry?.settings?.baseURL === 'string' ? trimUrl(entry.settings.baseURL) : '';
112
+ const registered = !!entry;
113
+ const inSync = registered && !!expectedKey && currentKey === expectedKey && JSON.stringify(currentIds) === JSON.stringify(expectedIds)
114
+ && currentUrl === trimUrl(baseUrl) && toolsInSync;
115
+ return {
116
+ registered, modelCount: currentIds.length, inSync,
117
+ // The block's models for the card's per-model visibility list (OpenCode lists them as `maritaca/<id>`).
118
+ models: currentIds.map((id) => ({ id, name: typeof entry.models[id]?.name === 'string' ? entry.models[id].name : id, tools: currentTools[id] })), route: registered ? maritacaOpencodeRoute(currentUrl) : null, keyConfigured: !!expectedKey, keySource: source,
119
+ // A reference is said by its kind only; a literal key typed by hand into opencode.json is never echoed.
120
+ keyReference: currentKey ? (/^\{(file|env):.*\}$/.test(currentKey) ? currentKey.replace(/^\{(file|env):.*\}$/, '{$1:…}') : 'literal (hidden)') : null,
121
+ opencode1: hasOpencode1Providers(config, MARITACA_OPENCODE_PROVIDER_ID),
122
+ };
123
+ }
124
+
125
+ export function maritacaOpencodeError(code, message, status = 500) {
126
+ return Object.assign(new Error(message), { code, status });
127
+ }
128
+
129
+ /**
130
+ * The sync: status / configure / remove, and what a key change does. Dependencies are server.js's:
131
+ * keyStore lib/maritaca/key-store.js (status(), dir)
132
+ * readConfig() the global opencode.json as an object (readOpencodeConfigDocument(path).config)
133
+ * updateConfig(fn) updateOpencodeConfigFile(dir, fn) → the path written
134
+ * configPath() the path of that file (for messages)
135
+ * convertProviders() opencodeConvertedProviders(path): the `providers` OpenCode converted from an OpenCode 1
136
+ * section (object), or undefined when OpenCode cannot say now
137
+ * reload() reloadSharedOpencodeConfig(); broadcast() tells the panels `providers:changed`
138
+ * catalogChanged() refreshOpencodeProviderConsumers(): OpenCode's kept provider list read again and the Assistant's
139
+ * catalog rebuilt, so agent_catalog and the Routes editor list maritaca/<id> at once (the catalog
140
+ * keeps a build for 30 s and nothing else tells it about a file SynaBun wrote). Not awaited.
141
+ * baseUrl the base URL the block gives OpenCode: a string, or a function read at each call. server.js hands
142
+ * this server's route (maritacaOpencodeProxyBaseUrl(PORT)); Maritaca's own API is only the default
143
+ * of a sync built without a server (tests), whose blocks OpenCode cannot use for tool calls.
144
+ */
145
+ export function createMaritacaOpencodeSync({
146
+ keyStore, readConfig, updateConfig, configPath = () => 'opencode.json', convertProviders = async () => undefined,
147
+ reload = async () => false, broadcast = () => {}, catalogChanged = () => {}, log = () => {}, models = MARITACA_MODELS, baseUrl = MARITACA_BASE_URL,
148
+ } = {}) {
149
+ if (!keyStore || typeof readConfig !== 'function' || typeof updateConfig !== 'function') throw new Error('createMaritacaOpencodeSync needs keyStore, readConfig and updateConfig');
150
+ const keyPath = () => join(keyStore.dir, MARITACA_KEY_FILE);
151
+ const currentBaseUrl = () => trimUrl(typeof baseUrl === 'function' ? baseUrl() : baseUrl);
152
+
153
+ function status() {
154
+ const keyStatus = keyStore.status();
155
+ const state = maritacaOpencodeState({ config: readConfig(), keyStatus, keyPath: keyPath(), models, baseUrl: currentBaseUrl() });
156
+ return { ...state, configPath: configPath() };
157
+ }
158
+
159
+ async function announce() {
160
+ try { await reload(); } catch { /* the serve is not running: it reads the file when it starts */ }
161
+ try { broadcast(); } catch { /* no panel */ }
162
+ // After the reload: the serve already reads the new file when the list is asked again. The answer to Configure
163
+ // does not wait for a catalog build.
164
+ try { const pending = catalogChanged(); pending?.catch?.(() => {}); } catch { /* no Assistant */ }
165
+ }
166
+
167
+ /** Writes the block. Throws NO_KEY (412) without a key, OPENCODE1_PROVIDERS (409) when the file cannot take a `providers` section now. */
168
+ async function configure() {
169
+ const keyStatus = keyStore.status();
170
+ const apiKey = maritacaApiKeyReference({ source: keyStatus.configured ? keyStatus.source : null, keyPath: keyPath() });
171
+ if (!apiKey) throw maritacaOpencodeError('NO_KEY', 'Save a Maritaca API key first (the Maritaca panel, the cog).', 412);
172
+ const target = currentBaseUrl();
173
+ const entry = maritacaOpencodeProviderEntry({ apiKey, models, baseUrl: target });
174
+ const converted = hasOpencode1Providers(readConfig(), MARITACA_OPENCODE_PROVIDER_ID) ? await convertProviders() : null;
175
+ if (converted === undefined) {
176
+ throw maritacaOpencodeError('OPENCODE1_PROVIDERS', `${configPath()} keeps its providers in OpenCode 1's "provider" section. Start OpenCode so SynaBun can move them to "providers" first, or move them yourself.`, 409);
177
+ }
178
+ const written = updateConfig((cfg) => {
179
+ if (converted) { delete cfg.provider; cfg.providers = { ...converted, ...(cfg.providers && typeof cfg.providers === 'object' ? cfg.providers : {}) }; }
180
+ return setProvider(cfg, MARITACA_OPENCODE_PROVIDER_ID, entry);
181
+ });
182
+ const modelsConfigured = Object.keys(entry.models).length;
183
+ const via = maritacaOpencodeRoute(target) === 'synabun' ? `through SynaBun at ${target}` : `straight to ${target}`;
184
+ log(`[maritaca] Registered ${modelsConfigured} model(s) as OpenCode provider "${MARITACA_OPENCODE_PROVIDER_ID}" in ${written} (key by ${keyStatus.source === 'env' ? 'environment' : 'file'} reference, ${via})`);
185
+ await announce();
186
+ return { modelsConfigured, keySource: keyStatus.source, configPath: written };
187
+ }
188
+
189
+ /** Takes the block out (either shape). Returns whether there was one. */
190
+ async function remove() {
191
+ const had = !!providerOf(readConfig(), MARITACA_OPENCODE_PROVIDER_ID);
192
+ if (had) {
193
+ updateConfig((cfg) => removeProvider(cfg, MARITACA_OPENCODE_PROVIDER_ID));
194
+ log('[maritaca] Removed the OpenCode provider block');
195
+ await announce();
196
+ }
197
+ return { removed: had };
198
+ }
199
+
200
+ /**
201
+ * After the key store changed (a key saved or forgotten): a registered block is written again (the reference may
202
+ * move between file and environment), and one left without any key is removed, because a dangling `{file:…}`
203
+ * would make OpenCode's configuration unreadable. Never throws: the key save must not fail for this.
204
+ */
205
+ async function onKeyChanged() {
206
+ try {
207
+ if (!providerOf(readConfig(), MARITACA_OPENCODE_PROVIDER_ID)) return { action: 'none' };
208
+ if (!keyStore.status().configured) { await remove(); return { action: 'removed' }; }
209
+ await configure();
210
+ return { action: 'resynced' };
211
+ } catch (error) {
212
+ log(`[maritaca] OpenCode provider re-sync skipped: ${error?.code || 'ERROR'}`);
213
+ return { action: 'failed', code: error?.code || 'ERROR' };
214
+ }
215
+ }
216
+
217
+ return { status, configure, remove, onKeyChanged };
218
+ }