synabun 2.3.1 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (356) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +1 -1
  3. package/browser-extension/content.js +169 -0
  4. package/browser-extension/engine.js +477 -0
  5. package/browser-extension/icons/icon-128.png +0 -0
  6. package/browser-extension/icons/icon-16.png +0 -0
  7. package/browser-extension/icons/icon-32.png +0 -0
  8. package/browser-extension/icons/icon-48.png +0 -0
  9. package/browser-extension/icons/status-off-16.png +0 -0
  10. package/browser-extension/icons/status-off-32.png +0 -0
  11. package/browser-extension/icons/status-off-48.png +0 -0
  12. package/browser-extension/icons/status-on-16.png +0 -0
  13. package/browser-extension/icons/status-on-32.png +0 -0
  14. package/browser-extension/icons/status-on-48.png +0 -0
  15. package/browser-extension/manifest.json +56 -0
  16. package/browser-extension/popup-strings.js +244 -0
  17. package/browser-extension/popup-view.js +151 -0
  18. package/browser-extension/popup.css +165 -0
  19. package/browser-extension/popup.html +105 -0
  20. package/browser-extension/popup.js +347 -0
  21. package/browser-extension/protocol.js +226 -0
  22. package/browser-extension/service-worker.js +267 -0
  23. package/browser-extension/setup-content.js +36 -0
  24. package/browser-extension/tokens.css +326 -0
  25. package/docs/browser-extension-bridge.md +84 -0
  26. package/docs/whatsapp.md +1 -1
  27. package/mcp-server/dist/http.d.ts +2 -0
  28. package/mcp-server/dist/http.d.ts.map +1 -1
  29. package/mcp-server/dist/http.js +9 -1
  30. package/mcp-server/dist/http.js.map +1 -1
  31. package/mcp-server/dist/index.d.ts +11 -0
  32. package/mcp-server/dist/index.d.ts.map +1 -1
  33. package/mcp-server/dist/index.js +38 -3
  34. package/mcp-server/dist/index.js.map +1 -1
  35. package/mcp-server/dist/services/browser-route-flow.d.ts +6 -2
  36. package/mcp-server/dist/services/browser-route-flow.d.ts.map +1 -1
  37. package/mcp-server/dist/services/browser-route-flow.js +10 -3
  38. package/mcp-server/dist/services/browser-route-flow.js.map +1 -1
  39. package/mcp-server/dist/services/codex-config-heal.d.ts.map +1 -1
  40. package/mcp-server/dist/services/codex-config-heal.js +7 -0
  41. package/mcp-server/dist/services/codex-config-heal.js.map +1 -1
  42. package/mcp-server/dist/services/neural-interface.d.ts +94 -3
  43. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  44. package/mcp-server/dist/services/neural-interface.js +168 -23
  45. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  46. package/mcp-server/dist/services/team-context.d.ts +18 -0
  47. package/mcp-server/dist/services/team-context.d.ts.map +1 -0
  48. package/mcp-server/dist/services/team-context.js +29 -0
  49. package/mcp-server/dist/services/team-context.js.map +1 -0
  50. package/mcp-server/dist/services/tool-catalog.d.ts +5 -2
  51. package/mcp-server/dist/services/tool-catalog.d.ts.map +1 -1
  52. package/mcp-server/dist/services/tool-catalog.js +22 -6
  53. package/mcp-server/dist/services/tool-catalog.js.map +1 -1
  54. package/mcp-server/dist/services/tool-list.d.ts.map +1 -1
  55. package/mcp-server/dist/services/tool-list.js +4 -0
  56. package/mcp-server/dist/services/tool-list.js.map +1 -1
  57. package/mcp-server/dist/services/tool-runtime.d.ts +8 -1
  58. package/mcp-server/dist/services/tool-runtime.d.ts.map +1 -1
  59. package/mcp-server/dist/services/tool-runtime.js +18 -1
  60. package/mcp-server/dist/services/tool-runtime.js.map +1 -1
  61. package/mcp-server/dist/tools/agent-definition.d.ts +133 -0
  62. package/mcp-server/dist/tools/agent-definition.d.ts.map +1 -0
  63. package/mcp-server/dist/tools/agent-definition.js +483 -0
  64. package/mcp-server/dist/tools/agent-definition.js.map +1 -0
  65. package/mcp-server/dist/tools/agents.d.ts +91 -9
  66. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  67. package/mcp-server/dist/tools/agents.js +161 -20
  68. package/mcp-server/dist/tools/agents.js.map +1 -1
  69. package/mcp-server/dist/tools/browser-advanced.d.ts +8 -1
  70. package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
  71. package/mcp-server/dist/tools/browser-advanced.js +70 -6
  72. package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
  73. package/mcp-server/dist/tools/git-tools.d.ts +4 -2
  74. package/mcp-server/dist/tools/git-tools.d.ts.map +1 -1
  75. package/mcp-server/dist/tools/git-tools.js +283 -2
  76. package/mcp-server/dist/tools/git-tools.js.map +1 -1
  77. package/mcp-server/dist/tools/morelogin.d.ts +8 -2
  78. package/mcp-server/dist/tools/morelogin.d.ts.map +1 -1
  79. package/mcp-server/dist/tools/morelogin.js +22 -5
  80. package/mcp-server/dist/tools/morelogin.js.map +1 -1
  81. package/mcp-server/dist/tools/team.d.ts +32 -0
  82. package/mcp-server/dist/tools/team.d.ts.map +1 -0
  83. package/mcp-server/dist/tools/team.js +87 -0
  84. package/mcp-server/dist/tools/team.js.map +1 -0
  85. package/mcp-server/package-lock.json +2 -2
  86. package/mcp-server/package.json +1 -1
  87. package/mcp-server/src/http.ts +9 -1
  88. package/mcp-server/src/index.ts +34 -4
  89. package/mcp-server/src/services/browser-route-flow.ts +12 -5
  90. package/mcp-server/src/services/codex-config-heal.ts +7 -0
  91. package/mcp-server/src/services/neural-interface.ts +190 -29
  92. package/mcp-server/src/services/team-context.ts +27 -0
  93. package/mcp-server/src/services/tool-catalog.ts +26 -8
  94. package/mcp-server/src/services/tool-list.ts +4 -0
  95. package/mcp-server/src/services/tool-runtime.ts +21 -2
  96. package/mcp-server/src/tools/agent-definition.ts +458 -0
  97. package/mcp-server/src/tools/agents.ts +175 -19
  98. package/mcp-server/src/tools/browser-advanced.ts +60 -6
  99. package/mcp-server/src/tools/git-tools.ts +249 -3
  100. package/mcp-server/src/tools/morelogin.ts +20 -5
  101. package/mcp-server/src/tools/team.ts +97 -0
  102. package/neural-interface/i18n/en.json +1117 -47
  103. package/neural-interface/i18n/pt-BR.json +1117 -47
  104. package/neural-interface/lib/account-usage.js +1 -1
  105. package/neural-interface/lib/agents/density.js +101 -0
  106. package/neural-interface/lib/agents/forge-host.js +223 -0
  107. package/neural-interface/lib/agents/native-export-targets.js +190 -0
  108. package/neural-interface/lib/agents/native-export.js +365 -0
  109. package/neural-interface/lib/agents/registry.js +840 -0
  110. package/neural-interface/lib/agents/resolve.js +544 -0
  111. package/neural-interface/lib/agents/schema.js +642 -0
  112. package/neural-interface/lib/agents/split.js +37 -0
  113. package/neural-interface/lib/agents-studio-api.js +591 -0
  114. package/neural-interface/lib/assistant-api.js +76 -7
  115. package/neural-interface/lib/assistant-catalog.js +2 -0
  116. package/neural-interface/lib/assistant-continuity.js +49 -0
  117. package/neural-interface/lib/assistant-dispatch.js +229 -102
  118. package/neural-interface/lib/assistant-persona.js +105 -8
  119. package/neural-interface/lib/assistant-route-gate.js +24 -9
  120. package/neural-interface/lib/assistant-router.js +384 -42
  121. package/neural-interface/lib/assistant-run-tail.js +151 -0
  122. package/neural-interface/lib/assistant-run-wait.js +183 -0
  123. package/neural-interface/lib/assistant-runtime.js +440 -93
  124. package/neural-interface/lib/assistant-task-prompt.js +11 -2
  125. package/neural-interface/lib/assistant-usage.js +3 -2
  126. package/neural-interface/lib/automation-approval.js +2 -2
  127. package/neural-interface/lib/browser-close-evidence.js +80 -0
  128. package/neural-interface/lib/browser-default.js +210 -0
  129. package/neural-interface/lib/browser-extension-adapter.js +255 -0
  130. package/neural-interface/lib/browser-extension-bridge.js +418 -0
  131. package/neural-interface/lib/browser-extension-folder.js +116 -0
  132. package/neural-interface/lib/browser-extension-setup.js +140 -0
  133. package/neural-interface/lib/browser-profile-choices.js +3 -3
  134. package/neural-interface/lib/browser-tool-policy.js +1 -1
  135. package/neural-interface/lib/claude-account-links.js +301 -0
  136. package/neural-interface/lib/claude-accounts.js +45 -20
  137. package/neural-interface/lib/claude-agent-bridge.js +142 -10
  138. package/neural-interface/lib/claude-model-catalog.js +6 -0
  139. package/neural-interface/lib/claude-panel-session.js +33 -0
  140. package/neural-interface/lib/codex-accounts.js +67 -24
  141. package/neural-interface/lib/coordination/README.md +384 -0
  142. package/neural-interface/lib/coordination/service.js +563 -0
  143. package/neural-interface/lib/coordination/store.js +1138 -0
  144. package/neural-interface/lib/db.js +22 -1
  145. package/neural-interface/lib/effort-levels.js +10 -1
  146. package/neural-interface/lib/memory-list-page.js +49 -0
  147. package/neural-interface/lib/memory-list-stamp.js +60 -0
  148. package/neural-interface/lib/morelogin-outside-close.js +186 -0
  149. package/neural-interface/lib/morelogin-profile-failures.js +206 -0
  150. package/neural-interface/lib/morelogin-start-cooldown.js +160 -0
  151. package/neural-interface/lib/morelogin.js +194 -8
  152. package/neural-interface/lib/native-loop-runtime.js +20 -0
  153. package/neural-interface/lib/opencode-build-preflight.js +16 -1
  154. package/neural-interface/lib/opencode-native-boundary.js +83 -13
  155. package/neural-interface/lib/opencode-serve-records.js +14 -9
  156. package/neural-interface/lib/page-session.js +1 -1
  157. package/neural-interface/lib/peer-identity.js +60 -21
  158. package/neural-interface/lib/process-identity.js +68 -7
  159. package/neural-interface/lib/request-gate.js +3 -0
  160. package/neural-interface/lib/screenshot-location.js +33 -0
  161. package/neural-interface/lib/skills/creation.js +1 -1
  162. package/neural-interface/lib/skills/known-bridge-digests.json +40 -0
  163. package/neural-interface/lib/studio-attention.js +56 -0
  164. package/neural-interface/lib/teams/README.md +382 -0
  165. package/neural-interface/lib/teams/api.js +287 -0
  166. package/neural-interface/lib/teams/brief.js +185 -0
  167. package/neural-interface/lib/teams/claims.js +315 -0
  168. package/neural-interface/lib/teams/git.js +293 -0
  169. package/neural-interface/lib/teams/index.js +122 -0
  170. package/neural-interface/lib/teams/integration.js +580 -0
  171. package/neural-interface/lib/teams/landing.js +184 -0
  172. package/neural-interface/lib/teams/recovery.js +256 -0
  173. package/neural-interface/lib/teams/scheduler.js +1474 -0
  174. package/neural-interface/lib/teams/schema.js +559 -0
  175. package/neural-interface/lib/teams/state.js +181 -0
  176. package/neural-interface/lib/teams/test-runner.js +86 -0
  177. package/neural-interface/lib/teams/test-sandbox.js +99 -0
  178. package/neural-interface/lib/teams/worktrees.js +757 -0
  179. package/neural-interface/lib/tool-permission-choices.js +226 -0
  180. package/neural-interface/lib/whatsapp/cards.js +24 -10
  181. package/neural-interface/lib/worker-confinement.js +206 -6
  182. package/neural-interface/package-lock.json +2 -2
  183. package/neural-interface/package.json +1 -1
  184. package/neural-interface/public/extension-setup.html +107 -0
  185. package/neural-interface/public/index.html +52 -12
  186. package/neural-interface/public/shared/agent-runtime-options.js +3 -1
  187. package/neural-interface/public/shared/agents/studio/ax-agent-view.js +614 -0
  188. package/neural-interface/public/shared/agents/studio/ax-api.js +198 -0
  189. package/neural-interface/public/shared/agents/studio/ax-create-view.js +221 -0
  190. package/neural-interface/public/shared/agents/studio/ax-diff.js +143 -0
  191. package/neural-interface/public/shared/agents/studio/ax-editor-view.js +392 -0
  192. package/neural-interface/public/shared/agents/studio/ax-export-view.js +94 -0
  193. package/neural-interface/public/shared/agents/studio/ax-form.js +191 -0
  194. package/neural-interface/public/shared/agents/studio/ax-icons.js +87 -0
  195. package/neural-interface/public/shared/agents/studio/ax-library-view.js +158 -0
  196. package/neural-interface/public/shared/agents/studio/ax-library.js +162 -0
  197. package/neural-interface/public/shared/agents/studio/ax-main.js +712 -0
  198. package/neural-interface/public/shared/agents/studio/ax-native-export.js +35 -0
  199. package/neural-interface/public/shared/agents/studio/ax-options.js +198 -0
  200. package/neural-interface/public/shared/agents/studio/ax-review-view.js +175 -0
  201. package/neural-interface/public/shared/agents/studio/ax-revisions-view.js +189 -0
  202. package/neural-interface/public/shared/agents/studio/ax-runs-view.js +202 -0
  203. package/neural-interface/public/shared/agents/studio/ax-runs.js +82 -0
  204. package/neural-interface/public/shared/agents/studio/ax-teams-view.js +256 -0
  205. package/neural-interface/public/shared/agents/studio/ax-teams.js +200 -0
  206. package/neural-interface/public/shared/agents/studio/ax-templates.js +50 -0
  207. package/neural-interface/public/shared/agents/studio/ax-ui.js +194 -0
  208. package/neural-interface/public/shared/agents/studio/ax-views.js +170 -0
  209. package/neural-interface/public/shared/agy/agy-panel.js +142 -28
  210. package/neural-interface/public/shared/agy/agy-styles.js +25 -5
  211. package/neural-interface/public/shared/assistant/asst-account-menu.js +13 -13
  212. package/neural-interface/public/shared/assistant/asst-ask-styles.js +2 -3
  213. package/neural-interface/public/shared/assistant/asst-brain-picker.js +91 -9
  214. package/neural-interface/public/shared/assistant/asst-control.js +3 -0
  215. package/neural-interface/public/shared/assistant/asst-interaction-hold.js +99 -0
  216. package/neural-interface/public/shared/assistant/asst-limit-dismissals.js +111 -0
  217. package/neural-interface/public/shared/assistant/asst-limit-dock.js +37 -3
  218. package/neural-interface/public/shared/assistant/asst-limit-wait.js +30 -7
  219. package/neural-interface/public/shared/assistant/asst-panel.js +177 -30
  220. package/neural-interface/public/shared/assistant/asst-rack-styles.js +15 -8
  221. package/neural-interface/public/shared/assistant/asst-render.js +36 -6
  222. package/neural-interface/public/shared/assistant/asst-route.js +78 -12
  223. package/neural-interface/public/shared/assistant/asst-routes-editor.js +148 -70
  224. package/neural-interface/public/shared/assistant/asst-roving.js +17 -1
  225. package/neural-interface/public/shared/assistant/asst-scene-styles.js +7 -2
  226. package/neural-interface/public/shared/assistant/asst-scenes.js +12 -1
  227. package/neural-interface/public/shared/assistant/asst-sidepanel.js +12 -2
  228. package/neural-interface/public/shared/assistant/asst-state.js +66 -1
  229. package/neural-interface/public/shared/assistant/asst-styles.js +98 -44
  230. package/neural-interface/public/shared/assistant/route-identity.js +16 -0
  231. package/neural-interface/public/shared/cdx/cdx-output.js +10 -0
  232. package/neural-interface/public/shared/cdx/cdx-panel.js +18 -16
  233. package/neural-interface/public/shared/cdx/cdx-plan.js +3 -2
  234. package/neural-interface/public/shared/cdx/cdx-render.js +122 -45
  235. package/neural-interface/public/shared/cdx/cdx-requests.js +4 -4
  236. package/neural-interface/public/shared/cdx/cdx-styles.js +8 -36
  237. package/neural-interface/public/shared/cdx/cdx-tabs.js +110 -42
  238. package/neural-interface/public/shared/claude-panel-lazy.js +12 -0
  239. package/neural-interface/public/shared/code-copy.js +120 -0
  240. package/neural-interface/public/shared/constants.js +7 -0
  241. package/neural-interface/public/shared/context-menu-model.js +1 -0
  242. package/neural-interface/public/shared/cp/cp-markdown.js +7 -2
  243. package/neural-interface/public/shared/cp/cp-session-model.js +86 -5
  244. package/neural-interface/public/shared/cp/cp-session-settings.js +58 -30
  245. package/neural-interface/public/shared/cp/cp-styles.js +9 -0
  246. package/neural-interface/public/shared/dom-change-flag.js +66 -0
  247. package/neural-interface/public/shared/dom-morph.js +124 -0
  248. package/neural-interface/public/shared/extension-setup/es-page.css +134 -0
  249. package/neural-interface/public/shared/extension-setup/es-page.js +120 -0
  250. package/neural-interface/public/shared/extension-setup/es-view.js +100 -0
  251. package/neural-interface/public/shared/html-shell.js +33 -4
  252. package/neural-interface/public/shared/i18n.js +14 -1
  253. package/neural-interface/public/shared/idle-queue.js +78 -0
  254. package/neural-interface/public/shared/iface-config.js +227 -0
  255. package/neural-interface/public/shared/lazy-module.js +108 -0
  256. package/neural-interface/public/shared/memory-list.js +117 -0
  257. package/neural-interface/public/shared/morelogin-profile-choices.js +1 -1
  258. package/neural-interface/public/shared/morelogin-profile-field.js +3 -3
  259. package/neural-interface/public/shared/mtc/mtc-panel.js +3 -1
  260. package/neural-interface/public/shared/mtc/mtc-styles.js +4 -1
  261. package/neural-interface/public/shared/ocp-v2/ocp-v2-manager.js +35 -15
  262. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +77 -23
  263. package/neural-interface/public/shared/ocp-v2/ocp-v2-projectbar.js +3 -6
  264. package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +24 -21
  265. package/neural-interface/public/shared/ocp-v2/ocp-v2-send-logic.js +16 -5
  266. package/neural-interface/public/shared/ocp-v2/ocp-v2-sessions-logic.js +16 -2
  267. package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +27 -43
  268. package/neural-interface/public/shared/ocp-v2/ocp-v2-ws.js +73 -9
  269. package/neural-interface/public/shared/schedules-view.js +2 -2
  270. package/neural-interface/public/shared/session-project-items.js +11 -0
  271. package/neural-interface/public/shared/settings/settings-ai-browser.js +119 -0
  272. package/neural-interface/public/shared/settings/settings-browser-extension.js +446 -0
  273. package/neural-interface/public/shared/settings/settings-ia.js +4 -2
  274. package/neural-interface/public/shared/settings/settings-morelogin-cooldown.js +63 -0
  275. package/neural-interface/public/shared/settings/settings-tool-permissions.js +70 -0
  276. package/neural-interface/public/shared/sidepanel-lazy.js +40 -0
  277. package/neural-interface/public/shared/sidepanel-session-status.js +8 -14
  278. package/neural-interface/public/shared/sidepanel-shown.js +73 -0
  279. package/neural-interface/public/shared/storage.js +6 -1
  280. package/neural-interface/public/shared/studio-attention.js +83 -0
  281. package/neural-interface/public/shared/styles.css +682 -50
  282. package/neural-interface/public/shared/term-browser-tabs.js +34 -0
  283. package/neural-interface/public/shared/transcript-rows.js +334 -0
  284. package/neural-interface/public/shared/tray-auto-close.js +106 -0
  285. package/neural-interface/public/shared/ui-agents.js +97 -0
  286. package/neural-interface/public/shared/ui-antigravity-panel.js +16 -14
  287. package/neural-interface/public/shared/ui-automation-studio.js +3 -3
  288. package/neural-interface/public/shared/ui-claude-panel.js +162 -95
  289. package/neural-interface/public/shared/ui-code-copy.js +256 -0
  290. package/neural-interface/public/shared/ui-codex-panel.js +14 -10
  291. package/neural-interface/public/shared/ui-context-menu.js +1 -1
  292. package/neural-interface/public/shared/ui-file-explorer.js +2 -3
  293. package/neural-interface/public/shared/ui-games.js +1 -1
  294. package/neural-interface/public/shared/ui-loading.js +12 -1
  295. package/neural-interface/public/shared/ui-maritaca-panel.js +12 -11
  296. package/neural-interface/public/shared/ui-menubar.js +23 -0
  297. package/neural-interface/public/shared/ui-native-loop-router.js +1 -1
  298. package/neural-interface/public/shared/ui-navbar.js +15 -9
  299. package/neural-interface/public/shared/ui-opencode-panel-v2.js +13 -11
  300. package/neural-interface/public/shared/ui-schedules-studio.js +3 -3
  301. package/neural-interface/public/shared/ui-scroll-follow.js +39 -0
  302. package/neural-interface/public/shared/ui-sessions.js +3 -3
  303. package/neural-interface/public/shared/ui-settings-entry.js +55 -0
  304. package/neural-interface/public/shared/ui-settings.js +355 -400
  305. package/neural-interface/public/shared/ui-sidepanel-layout.js +44 -25
  306. package/neural-interface/public/shared/ui-sidepanel-session-entry.js +22 -9
  307. package/neural-interface/public/shared/ui-sidepanel-sessions.js +10 -2
  308. package/neural-interface/public/shared/ui-sidepanel-tray.js +36 -41
  309. package/neural-interface/public/shared/ui-sidepanel-windows.js +14 -1
  310. package/neural-interface/public/shared/ui-styleguide.js +10 -2
  311. package/neural-interface/public/shared/ui-sync.js +5 -0
  312. package/neural-interface/public/shared/ui-terminal.js +13 -9
  313. package/neural-interface/public/shared/ui-tooltip.js +28 -7
  314. package/neural-interface/public/shared/ui-topright-overflow.js +26 -4
  315. package/neural-interface/public/shared/ui-tray-columns.js +375 -0
  316. package/neural-interface/public/shared/ui-whiteboard.js +51 -6
  317. package/neural-interface/public/shared/ui-worker-end.js +28 -1
  318. package/neural-interface/public/shared/ui-workspaces.js +13 -0
  319. package/neural-interface/public/shared/window-keys.js +71 -0
  320. package/neural-interface/public/variant/2d/main.js +2 -0
  321. package/neural-interface/public/variant/3d/app.js +620 -0
  322. package/neural-interface/public/variant/3d/boot-reveal.js +47 -0
  323. package/neural-interface/public/variant/3d/main.js +21 -544
  324. package/neural-interface/public/variant/3d/map-controls.js +4 -2
  325. package/neural-interface/public/vendor/fonts/fonts.css +508 -0
  326. package/neural-interface/public/vendor/fonts/inter-OFL.txt +93 -0
  327. package/neural-interface/public/vendor/fonts/inter-cyrillic-ext.woff2 +0 -0
  328. package/neural-interface/public/vendor/fonts/inter-cyrillic.woff2 +0 -0
  329. package/neural-interface/public/vendor/fonts/inter-greek-ext.woff2 +0 -0
  330. package/neural-interface/public/vendor/fonts/inter-greek.woff2 +0 -0
  331. package/neural-interface/public/vendor/fonts/inter-latin-ext.woff2 +0 -0
  332. package/neural-interface/public/vendor/fonts/inter-latin.woff2 +0 -0
  333. package/neural-interface/public/vendor/fonts/inter-vietnamese.woff2 +0 -0
  334. package/neural-interface/public/vendor/fonts/jetbrains-mono-OFL.txt +93 -0
  335. package/neural-interface/public/vendor/fonts/jetbrains-mono-cyrillic-ext.woff2 +0 -0
  336. package/neural-interface/public/vendor/fonts/jetbrains-mono-cyrillic.woff2 +0 -0
  337. package/neural-interface/public/vendor/fonts/jetbrains-mono-greek.woff2 +0 -0
  338. package/neural-interface/public/vendor/fonts/jetbrains-mono-latin-ext.woff2 +0 -0
  339. package/neural-interface/public/vendor/fonts/jetbrains-mono-latin.woff2 +0 -0
  340. package/neural-interface/public/vendor/fonts/jetbrains-mono-vietnamese.woff2 +0 -0
  341. package/neural-interface/public/vendor/fonts/manifest.json +142 -0
  342. package/neural-interface/public/vendor/fonts/space-grotesk-OFL.txt +93 -0
  343. package/neural-interface/public/vendor/fonts/space-grotesk-latin-ext.woff2 +0 -0
  344. package/neural-interface/public/vendor/fonts/space-grotesk-latin.woff2 +0 -0
  345. package/neural-interface/public/vendor/fonts/space-grotesk-vietnamese.woff2 +0 -0
  346. package/neural-interface/scripts/boot-graph.mjs +270 -0
  347. package/neural-interface/scripts/vendor-fonts.mjs +124 -0
  348. package/neural-interface/server.js +1050 -140
  349. package/npm-shrinkwrap.json +2 -2
  350. package/package.json +3 -1
  351. package/skills/agent-forge/SKILL.md +182 -0
  352. package/skills/agent-forge/evals/evals.json +56 -0
  353. package/skills/agent-forge/references/definition-fields.md +61 -0
  354. package/skills/agent-forge/references/examples.md +105 -0
  355. package/skills/agent-forge/references/instructions.md +51 -0
  356. package/skills/agent-forge/references/review-and-export.md +84 -0
@@ -153,7 +153,7 @@ export function chooseUsageAccount(rows, choice, defaultId = 'default') {
153
153
  const known = available.filter(row => typeof row.usage?.remainingPercent === 'number');
154
154
  const highest = Math.max(...known.map(row => row.usage.remainingPercent));
155
155
  const best = known.filter(row => row.usage.remainingPercent === highest);
156
- let row = (best.length > 1 ? available.find(row => row.id === defaultId) : null) || best.find(row => row.id === defaultId) || best[0];
156
+ let row = best.find(row => row.id === defaultId) || best[0];
157
157
  if (!row) row = available.find(row => row.id === defaultId) || available[0];
158
158
  let reason = choice === 'auto' ? 'account_auto' : 'account_limited';
159
159
  if (!available.length && candidates.length) {
@@ -0,0 +1,101 @@
1
+ // ═══════════════════════════════════════════
2
+ // SynaBun — Agents: agent density
3
+ // ═══════════════════════════════════════════
4
+ //
5
+ // How many workers the Assistant may put on ONE task. The user picks a level next to the Test density control in
6
+ // the Assistant's composer; like that setting (assistant-test-density.js) it is stored per session (null = the
7
+ // default) and read when needed. Density is a target for code, complex, research and review; fewer workers need
8
+ // a reason. Every split worker gets its own git worktree: code slices are joined and tested; research/review
9
+ // workers get read-only worktrees that are removed when they end.
10
+ //
11
+ // This module is the wording and the numbers: the levels and their caps, the line the brain's prompt carries, and
12
+ // the "[SynaBun Agents]" line a change sends. Pure module: no I/O, no server imports.
13
+
14
+ export const AGENT_DENSITIES = Object.freeze(['solo', 'pair', 'team', 'swarm']);
15
+ export const DEFAULT_AGENT_DENSITY = 'solo';
16
+ export const AGENT_DENSITY_LABELS = Object.freeze({ solo: 'Solo', pair: 'Pair', team: 'Team', swarm: 'Swarm' });
17
+ /** The most workers one task may be given at a level. */
18
+ export const AGENT_DENSITY_WORKERS = Object.freeze({ solo: 1, pair: 2, team: 4, swarm: 6 });
19
+ /** The most workers any level allows (the hard ceiling of a team plan). */
20
+ export const MAX_TEAM_WORKERS = AGENT_DENSITY_WORKERS.swarm;
21
+ export const AGENTS_HEADER = '[SynaBun Agents]';
22
+
23
+ /** A known level, else `fallback` (the default level unless the caller wants to tell "not set" apart). */
24
+ export function normalizeAgentDensity(value, fallback = DEFAULT_AGENT_DENSITY) {
25
+ const key = String(value ?? '').trim().toLowerCase();
26
+ return AGENT_DENSITIES.includes(key) ? key : fallback;
27
+ }
28
+
29
+ export function agentDensityLabel(level) {
30
+ return AGENT_DENSITY_LABELS[normalizeAgentDensity(level)];
31
+ }
32
+
33
+ /** The cap of a level: 1, 2, 4 or 6 workers on one task. An unknown level is the default (Solo: 1). */
34
+ export function maxWorkers(level) {
35
+ return AGENT_DENSITY_WORKERS[normalizeAgentDensity(level)];
36
+ }
37
+
38
+ /** May a task be split at this level at all? (Solo never splits.) */
39
+ export function allowsTeams(level) {
40
+ return maxWorkers(level) > 1;
41
+ }
42
+
43
+ /** How many workers a plan gets at a level: what was asked for, at least 1, at most the cap. */
44
+ export function clampWorkers(level, requested) {
45
+ const n = Math.floor(Number(requested));
46
+ return Math.max(1, Math.min(maxWorkers(level), Number.isFinite(n) ? n : 1));
47
+ }
48
+
49
+ /** Does a plan of `workers` workers fit the level? */
50
+ export function fitsDensity(level, workers) {
51
+ const n = Number(workers);
52
+ return Number.isInteger(n) && n >= 1 && n <= maxWorkers(level);
53
+ }
54
+
55
+ /** The lowest level that allows `workers` workers on one task, or null when no level does. */
56
+ export function densityForWorkers(workers) {
57
+ const n = Number(workers);
58
+ if (!Number.isInteger(n) || n < 1) return null;
59
+ return AGENT_DENSITIES.find((level) => AGENT_DENSITY_WORKERS[level] >= n) || null;
60
+ }
61
+
62
+ const SPLIT_RULE = 'a target: plan the whole task first; split code/complex and research/review with agent_team, every worker in its own worktree (read-only for research/review); fewer only with a reason; one agent_route approval for the whole split, never per worker; all other classes stay single';
63
+
64
+ /** What a level means, in one clause (the brain's line and the change announcement). */
65
+ const DENSITY_SUMMARY = Object.freeze({
66
+ solo: 'one worker per task; never split a task across workers',
67
+ pair: `2 workers on one eligible task; ${SPLIT_RULE}`,
68
+ team: `4 workers on one eligible task; ${SPLIT_RULE}`,
69
+ swarm: `6 workers on one eligible task; ${SPLIT_RULE}`,
70
+ });
71
+
72
+ export function agentDensitySummary(level) {
73
+ return DENSITY_SUMMARY[normalizeAgentDensity(level)];
74
+ }
75
+
76
+ /**
77
+ * The entry of the brain's system prompt (assistant-persona.js, Rails), per level.
78
+ * `where`: how the prompt names the control (a chat channel has no composer).
79
+ */
80
+ export function agentDensityPersonaLine(level, { where = 'next to the Test density control' } = {}) {
81
+ const id = normalizeAgentDensity(level);
82
+ const head = `- Agent density: ${AGENT_DENSITY_LABELS[id]} (the user's setting, ${where}): ${DENSITY_SUMMARY[id]}.`;
83
+ const tail = ` A change of level arrives as a "${AGENTS_HEADER}" line.`;
84
+ if (id === 'solo') {
85
+ return `${head} Give each task to a single worker, as before. Separate tasks may still run side by side, and a review by a second model is its own task, not a split.${tail}`;
86
+ }
87
+ const cap = AGENT_DENSITY_WORKERS[id];
88
+ return `${head} Use ${cap} workers when the task can sensibly split that far. `
89
+ + 'For code/complex, split into parts that are file-disjoint (no file is written by two parts) and say which files each part owns; parts that depend on each other name that dependency, and at most one part changes dependency lockfiles. '
90
+ + 'SynaBun gives every part its own git worktree and branch under the project\'s .worktrees folder, never the user\'s checkout or branch, and joins the finished parts on an integration branch for the user to merge. '
91
+ + `Research/review use distinct questions or review scopes through agent_team (empty owned_paths), each worker in its own read-only worktree, removed when it ends (changes are kept and reported); no integration or landing; synthesize their results. SynaBun refuses a plan with more parts than ${cap}, with overlapping files or with a dependency cycle.${tail}`;
92
+ }
93
+
94
+ /** The line a running brain gets when the level changes (like "[SynaBun Tests]" and "[SynaBun Router]"). */
95
+ export function agentDensityStamp(level) {
96
+ const id = normalizeAgentDensity(level);
97
+ return `${AGENTS_HEADER} Agent density: ${AGENT_DENSITY_LABELS[id]} - ${DENSITY_SUMMARY[id]}.`;
98
+ }
99
+
100
+ // The short name the phase plan uses.
101
+ export { normalizeAgentDensity as normalize };
@@ -0,0 +1,223 @@
1
+ // ═══════════════════════════════════════════
2
+ // SynaBun — Agents: what agent-forge reads from this server (phase P6)
3
+ // ═══════════════════════════════════════════
4
+ //
5
+ // agent-forge is the workflow the Assistant follows to turn a request into an agent definition (the shipped skill
6
+ // `skills/agent-forge`, read through the MCP tool `agent_definition` action "guide"). To fill a definition without
7
+ // guessing it needs what exists here: the providers and their models and efforts, the tool groups, the MCP servers,
8
+ // the colour tokens, the MoreLogin profiles agents may choose, the registered projects. None of that is a list kept
9
+ // in this file: each piece is asked of the part of the server that owns it (the Assistant's catalog, the tool
10
+ // catalog, the style guide, the browser settings), handed over by server.js.
11
+ //
12
+ // It also holds the two things that touch the disk for agent-forge and native export, each confined:
13
+ // - the guide: one file of the shipped skill folder, by a name the folder itself lists;
14
+ // - a Claude Code agent file given by its path: read only from an agents folder Claude Code reads (an account's
15
+ // `agents/`, a registered project's `.claude/agents/`), never from anywhere else on the disk.
16
+ // Where a native export is written is lib/agents/native-export-targets.js, made here from the same folders.
17
+
18
+ import os from 'node:os';
19
+ import { basename, isAbsolute, join, resolve } from 'node:path';
20
+ import { toolCatalogView } from '../../../mcp-server/dist/services/tool-catalog.js';
21
+ import { readConfinedFile } from '../confined-fs.js';
22
+ import { PathConfineError, isInside, realPathOf } from '../path-confine.js';
23
+ import { collectFolder } from '../skills/bundle.js';
24
+ import { createNativeExportTargets } from './native-export-targets.js';
25
+ import { REGISTRY_LIMITS } from './registry.js';
26
+ import { AGENT_ACCOUNT_PROVIDERS, AGENT_PROVIDERS } from './schema.js';
27
+
28
+ /** The shipped skill agent-forge is (skills/agent-forge). */
29
+ export const AGENT_FORGE = 'agent-forge';
30
+ export const FORGE_LIMITS = Object.freeze({
31
+ /** Models listed per provider (a provider with more is searched: `provider` + `q`). */
32
+ models: 40,
33
+ /** Colour tokens listed. */
34
+ colorTokens: 120,
35
+ mcpServers: 100,
36
+ projects: 200,
37
+ moreloginProfiles: 100,
38
+ /** One file of the guide. */
39
+ guideBytes: 512 * 1024,
40
+ });
41
+
42
+ export class AgentForgeError extends Error {
43
+ /** @param {number} status @param {string} code @param {string} message @param {object} [extra] */
44
+ constructor(status, code, message, extra = {}) {
45
+ super(message);
46
+ this.name = 'AgentForgeError';
47
+ this.status = status;
48
+ this.code = code;
49
+ Object.assign(this, extra);
50
+ }
51
+ }
52
+
53
+ const isObject = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
54
+ const arr = (value) => (Array.isArray(value) ? value : []);
55
+ const text = (value, max = 400) => (typeof value === 'string' ? value.slice(0, max) : '');
56
+
57
+ /**
58
+ * The colour tokens a style guide defines, as an agent's `color` names them ("group.key": lib/agents/schema.js).
59
+ * A status colour, a semantic role, a step of a palette. Pure.
60
+ * @param {object|null} config a style guide (lib/style-guide/schema.js), or null
61
+ * @returns {string[]}
62
+ */
63
+ export function colorTokensOf(config) {
64
+ if (!isObject(config?.colors)) return [];
65
+ const out = [];
66
+ const keys = (map) => (isObject(map) ? Object.keys(map) : []);
67
+ for (const key of keys(config.colors.status)) out.push(`status.${key}`);
68
+ const theme = config.colors.themes?.default;
69
+ const semantic = isObject(config.colors.semantic) ? (config.colors.semantic[theme] || Object.values(config.colors.semantic).find(isObject)) : null;
70
+ for (const key of keys(semantic)) out.push(`semantic.${key}`);
71
+ for (const [name, palette] of Object.entries(isObject(config.colors.palettes) ? config.colors.palettes : {})) {
72
+ for (const step of keys(palette?.steps)) out.push(`${name}.${step}`);
73
+ }
74
+ return [...new Set(out.filter((token) => /^[A-Za-z0-9-]{1,40}\.[A-Za-z0-9-]{1,40}$/.test(token)))];
75
+ }
76
+
77
+ /** One model row, as much of it as a definition needs. */
78
+ function modelRow(row) {
79
+ return {
80
+ id: row.id, ...(row.label && row.label !== row.id ? { label: text(row.label, 80) } : {}),
81
+ tier: row.tier || null, vision: row.vision ?? null,
82
+ ...(arr(row.efforts).length ? { efforts: row.efforts } : {}),
83
+ ...(row.defaultEffort ? { defaultEffort: row.defaultEffort } : {}),
84
+ ...(row.default ? { default: true } : {}),
85
+ };
86
+ }
87
+
88
+ /**
89
+ * @param {object} o
90
+ * @param {string} o.skillsDir the folder of the skills SynaBun ships (PACKAGE_ROOT/skills)
91
+ * @param {(q: { provider?: string|null, q?: string|null }) => Promise<object|null>} [o.catalog] the Assistant's model
92
+ * catalog in its brain view (lib/assistant-catalog.js get), or null while the Assistant is not built
93
+ * @param {(projectPath: string) => object|null} [o.styleGuide] a project's style guide, or null
94
+ * @param {() => { envId: string, name: string|null }[]} [o.moreloginProfiles] the profiles the owner lets agents choose
95
+ * @param {() => { path: string, label?: string }[]} [o.projects] the registered projects
96
+ * @param {() => string} o.claudeHome Claude Code's config dir
97
+ * @param {() => { id: string, home: string }[]} [o.claudeHomes] every Claude Code account's config dir (default: the one)
98
+ * @param {() => string} o.opencodeConfigDir OpenCode's configuration folder
99
+ * @param {string} [o.homeDir] the user's home folder (for a path written `~/…`)
100
+ * @param {(event: object) => void} [o.onExport] told when the owner wrote a native export
101
+ */
102
+ export function createAgentForgeHost({
103
+ skillsDir, catalog = async () => null, styleGuide = () => null, moreloginProfiles = () => [], projects = () => [],
104
+ claudeHome, claudeHomes = null, opencodeConfigDir, homeDir = os.homedir(), onExport = () => {},
105
+ } = {}) {
106
+ if (!skillsDir || typeof claudeHome !== 'function' || typeof opencodeConfigDir !== 'function') throw new Error('createAgentForgeHost needs { skillsDir, claudeHome, opencodeConfigDir }');
107
+ const projectList = () => { try { return arr(projects()).filter((p) => p && typeof p.path === 'string' && p.path); } catch { return []; } };
108
+ const isRegisteredProject = (path) => typeof path === 'string' && !!path && projectList().some((p) => resolve(p.path) === resolve(path));
109
+ const targets = createNativeExportTargets({ claudeHome, opencodeConfigDir, isRegisteredProject });
110
+
111
+ // ── the guide ──
112
+ /**
113
+ * One file of the shipped agent-forge skill: `SKILL.md`, or one the folder lists. A link in the folder is never
114
+ * followed and a name the folder does not list is not a path that is tried.
115
+ * @returns {{ skill: string, path: string, files: string[], content: string }}
116
+ * @throws {AgentForgeError} 404 `guide_missing` / `file_not_found`
117
+ */
118
+ function guide(file = 'SKILL.md') {
119
+ const wanted = typeof file === 'string' && file ? file : 'SKILL.md';
120
+ let files;
121
+ try { files = collectFolder(realPathOf(join(skillsDir, AGENT_FORGE))).files; } catch { files = []; }
122
+ const names = files.map((entry) => entry.path).filter((path) => !path.startsWith('evals/'));
123
+ if (!names.includes('SKILL.md')) throw new AgentForgeError(404, 'guide_missing', 'This SynaBun ships no agent-forge.');
124
+ const entry = files.find((item) => item.path === wanted && names.includes(item.path));
125
+ if (!entry) throw new AgentForgeError(404, 'file_not_found', `agent-forge has no file "${wanted.slice(0, 200)}".`, { files: names });
126
+ if (entry.bytes.length > FORGE_LIMITS.guideBytes) throw new AgentForgeError(413, 'too_large', 'That file of the guide is too large to send.');
127
+ return { skill: AGENT_FORGE, path: entry.path, files: names, content: entry.bytes.toString('utf-8') };
128
+ }
129
+
130
+ // ── the catalog a definition is filled from ──
131
+ /**
132
+ * @param {{ provider?: string|null, q?: string|null, projectPath?: string|null }} [query] `provider` and `q` narrow
133
+ * the models (a provider with more than the limit is searched this way); `projectPath` picks whose colour tokens
134
+ * @returns {Promise<object>} see docs/agents.md → agent-forge
135
+ */
136
+ async function describe({ provider = null, q = null, projectPath = null } = {}) {
137
+ const wantedProvider = AGENT_PROVIDERS.includes(provider) ? provider : null;
138
+ let view = null;
139
+ try { view = await catalog({ provider: wantedProvider, q: q ? text(q, 200) : null }); } catch { view = null; }
140
+ const models = {};
141
+ const providers = [];
142
+ for (const id of AGENT_PROVIDERS) {
143
+ if (wantedProvider && id !== wantedProvider) continue;
144
+ const rows = arr(view?.models?.[id]);
145
+ models[id] = rows.slice(0, FORGE_LIMITS.models).map(modelRow);
146
+ const info = arr(view?.providers).find((row) => row?.id === id) || {};
147
+ const accounts = AGENT_ACCOUNT_PROVIDERS.includes(id)
148
+ ? arr(view?.accounts?.[id]).map((row) => ({ id: row?.id, ...(row?.label ? { label: text(row.label, 80) } : {}) })).filter((row) => typeof row.id === 'string' && row.id).slice(0, 20)
149
+ : null;
150
+ providers.push({
151
+ id, efforts: arr(info.efforts), permissionPolicies: arr(info.permissionPolicies),
152
+ priced: info.priced !== false, source: view?.sources?.[id] || (view ? 'unknown' : 'unavailable'),
153
+ ...(rows.length > FORGE_LIMITS.models ? { more: rows.length - FORGE_LIMITS.models } : {}),
154
+ ...(accounts ? { accounts } : {}),
155
+ });
156
+ }
157
+ // The tool groups are the tool catalog's own (the one list: mcp-server tool-catalog.ts); never a copy kept here.
158
+ const tools = toolCatalogView();
159
+ let servers = [];
160
+ try { servers = arr(view?.tools?.servers); } catch { servers = []; }
161
+ const project = projectPath && isRegisteredProject(projectPath) ? resolve(projectPath) : null;
162
+ let guideOf = null;
163
+ try { guideOf = project ? styleGuide(project) : null; } catch { guideOf = null; }
164
+ let profiles = [];
165
+ try { profiles = arr(moreloginProfiles()); } catch { profiles = []; }
166
+ const tokens = colorTokensOf(guideOf);
167
+ return {
168
+ modelsAvailable: !!view,
169
+ providers, models,
170
+ toolGroups: tools.groups.map((group) => ({ id: group.id, label: group.label, purpose: group.purpose, browser: group.browser })),
171
+ defaultTools: tools.default,
172
+ mcpServers: servers.filter((row) => row && typeof row.ref === 'string').slice(0, FORGE_LIMITS.mcpServers).map((row) => ({
173
+ name: row.ref.replace(/^mcp:/, ''), ...(row.selectable === false ? { selectable: false } : {}),
174
+ providers: Object.fromEntries(Object.entries(isObject(row.providers) ? row.providers : {}).filter(([id]) => AGENT_PROVIDERS.includes(id))),
175
+ })),
176
+ colorTokens: { project, source: project ? (tokens.length ? 'style-guide' : 'none') : 'no-project', tokens: tokens.slice(0, FORGE_LIMITS.colorTokens) },
177
+ moreloginProfiles: profiles.filter((row) => row && typeof row.envId === 'string').slice(0, FORGE_LIMITS.moreloginProfiles).map((row) => ({ envId: row.envId, name: row.name || null })),
178
+ projects: projectList().slice(0, FORGE_LIMITS.projects).map((p) => ({ path: p.path, label: text(p.label || '', 200) || basename(p.path) })),
179
+ };
180
+ }
181
+
182
+ // ── a Claude Code agent file, by its path ──
183
+ /** The agents folders Claude Code reads here: every account's, and every registered project's. */
184
+ function claudeAgentFolders() {
185
+ let homes = [];
186
+ try { homes = typeof claudeHomes === 'function' ? arr(claudeHomes()).map((row) => row?.home).filter((home) => typeof home === 'string' && home) : []; } catch { homes = []; }
187
+ let own = null;
188
+ try { own = claudeHome(); } catch { own = null; }
189
+ const bases = [...new Set([own, ...homes].filter(Boolean).map((home) => join(resolve(home), 'agents')))];
190
+ for (const project of projectList()) bases.push(join(resolve(project.path), '.claude', 'agents'));
191
+ return bases;
192
+ }
193
+
194
+ /**
195
+ * The text of a Claude Code agent file named by its path. Only a `.md` file inside an agents folder Claude Code
196
+ * reads (an account's, a registered project's) is read; a link that leads out of that folder is refused.
197
+ * @param {string} path absolute, or `~/…`
198
+ * @returns {{ markdown: string, fileName: string, path: string }}
199
+ * @throws {AgentForgeError} 400 `invalid_path`, 403 `path_not_allowed`, 404 `file_not_found`, 413 `too_large`
200
+ */
201
+ function readClaudeAgentFile(path) {
202
+ const raw = typeof path === 'string' ? path.trim() : '';
203
+ // eslint-disable-next-line no-control-regex
204
+ if (!raw || raw.length > 4000 || /[\u0000-\u001f]/.test(raw)) throw new AgentForgeError(400, 'invalid_path', 'path is the absolute path of a Claude Code agent file (.md).');
205
+ const expanded = raw === '~' || raw.startsWith('~/') ? join(homeDir, raw.slice(1)) : raw;
206
+ if (!isAbsolute(expanded) || !/\.md$/i.test(expanded)) throw new AgentForgeError(400, 'invalid_path', 'path is the absolute path of a Claude Code agent file (.md).');
207
+ const full = resolve(expanded);
208
+ const base = claudeAgentFolders().find((folder) => isInside(folder, full));
209
+ if (!base) throw new AgentForgeError(403, 'path_not_allowed', 'Only a file in an agents folder Claude Code reads is read by its path (an account\'s agents folder, or a registered project\'s .claude/agents): send the file\'s text instead.');
210
+ try {
211
+ const markdown = readConfinedFile(base, full, { maxBytes: REGISTRY_LIMITS.claudeAgentBytes, encoding: 'utf-8' });
212
+ return { markdown, fileName: basename(full), path: full };
213
+ } catch (error) {
214
+ if (error instanceof PathConfineError) {
215
+ const status = [403, 404, 413].includes(error.status) ? error.status : 400;
216
+ throw new AgentForgeError(status, status === 404 ? 'file_not_found' : status === 413 ? 'too_large' : 'path_not_allowed', error.message);
217
+ }
218
+ throw error;
219
+ }
220
+ }
221
+
222
+ return { guide, describe, readClaudeAgentFile, targets, isRegisteredProject, onExport: (event) => { try { onExport(event); } catch { /* a listener's own failure */ } } };
223
+ }
@@ -0,0 +1,190 @@
1
+ // ═══════════════════════════════════════════
2
+ // SynaBun — Agents: where a native export goes, and the write (phase P6)
3
+ // ═══════════════════════════════════════════
4
+ //
5
+ // The one place that turns "Claude Code, this account" or "OpenCode, that project" into a path, looks at what is
6
+ // there, and writes an export (lib/agents/native-export.js makes the text). The rules are the ones Skills Studio's
7
+ // own agent creation follows (server.js POST /api/skills-studio/create):
8
+ //
9
+ // - two places only: the account level (Claude Code's config dir, OpenCode's configuration folder) or a project
10
+ // SynaBun has registered. A project that is not registered is refused; no path is ever taken from a request.
11
+ // - the file must really land in that folder (lib/path-confine.js confineToRoot): a linked `.claude/agents` in a
12
+ // project that leads elsewhere is refused before any folder is made.
13
+ // - a new file is created exclusively (lib/confined-fs.js). Nothing that exists is replaced unless the owner says
14
+ // so AND names the digest of what is there now; a link, a folder or a device at the file's place is never written.
15
+ // - OpenCode has one document for many things: only the `agents.<id>` key is set, the rest of the user's file stays
16
+ // as it is, and a file that is not JSON is never overwritten. `opencode.jsonc` is the user's and is never written.
17
+ //
18
+ // Nothing here decides who may write: lib/agents-studio-api.js lets only the owner's page reach `write`. `inspect`
19
+ // reads and never writes, so a preview is safe for the Assistant.
20
+
21
+ import { lstatSync, statSync } from 'node:fs';
22
+ import { join, resolve } from 'node:path';
23
+ import { entryKind, readConfinedFile, replaceFileAtomic, writeConfinedFile } from '../confined-fs.js';
24
+ import { OPENCODE_CONFIG_FILE, OPENCODE_CONFIG_SCHEMA, agentOf, parseJsonc, setAgent } from '../opencode-config.js';
25
+ import { PathConfineError, confineToRoot } from '../path-confine.js';
26
+ import { NativeExportError, entryDigest, nativeDigest } from './native-export.js';
27
+
28
+ export const NATIVE_TARGET_KINDS = Object.freeze(['account', 'project']);
29
+ /** The most an existing file is read to compare it (an agent file or an opencode.json is far smaller). */
30
+ export const NATIVE_TARGET_MAX_BYTES = 2 * 1024 * 1024;
31
+
32
+ const isObject = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
33
+
34
+ /**
35
+ * @param {object} o
36
+ * @param {() => string} o.claudeHome Claude Code's config dir (CLAUDE_CONFIG_DIR, else ~/.claude)
37
+ * @param {() => string} o.opencodeConfigDir OpenCode's configuration folder (lib/opencode-config.js opencodeConfigDir)
38
+ * @param {(path: string) => boolean} o.isRegisteredProject is this folder a project SynaBun has registered?
39
+ */
40
+ export function createNativeExportTargets({ claudeHome, opencodeConfigDir, isRegisteredProject } = {}) {
41
+ if (typeof claudeHome !== 'function' || typeof opencodeConfigDir !== 'function' || typeof isRegisteredProject !== 'function') {
42
+ throw new Error('createNativeExportTargets needs { claudeHome, opencodeConfigDir, isRegisteredProject }');
43
+ }
44
+
45
+ /**
46
+ * Where an export of `exported` would be written.
47
+ * @param {object} exported an exportNative() result (supported)
48
+ * @param {{ id: string, target?: 'account'|'project', projectPath?: string|null }} where
49
+ * @returns {{ host, kind: 'account'|'project', projectPath: string|null, path: string, root: { dir: string, anchor: string } }}
50
+ * @throws {NativeExportError} 400 `no_native_format` / `invalid_target` / `project_required`, 403 `project_not_registered`
51
+ */
52
+ function resolveTarget(exported, { id, target = 'account', projectPath = null } = {}) {
53
+ if (!exported?.supported) throw new NativeExportError(400, 'no_native_format', exported?.reason || 'This host has no native agent format.', { host: exported?.host || null });
54
+ const kind = String(target || 'account').trim().toLowerCase();
55
+ if (!NATIVE_TARGET_KINDS.includes(kind)) throw new NativeExportError(400, 'invalid_target', 'target is "account" (the host\'s own folder) or "project" (a registered project).');
56
+ let project = null;
57
+ if (kind === 'project') {
58
+ if (typeof projectPath !== 'string' || !projectPath.trim()) throw new NativeExportError(400, 'project_required', 'A project target names its project: the absolute path of a registered project.');
59
+ let registered = false;
60
+ try { registered = !!isRegisteredProject(projectPath); } catch { registered = false; }
61
+ if (!registered) throw new NativeExportError(403, 'project_not_registered', 'Not a registered project: an export goes to the account level or to a project SynaBun knows.');
62
+ project = resolve(projectPath);
63
+ }
64
+ let dir;
65
+ let path;
66
+ if (exported.host === 'claude-code') {
67
+ dir = join(project || resolve(claudeHome()), ...(project ? ['.claude', 'agents'] : ['agents']));
68
+ path = join(dir, `${id}.md`);
69
+ } else {
70
+ dir = project || resolve(opencodeConfigDir());
71
+ path = join(dir, OPENCODE_CONFIG_FILE);
72
+ }
73
+ // The folder the file must really land in, and (for a folder inside a project) the project it must stay within.
74
+ // OpenCode's project document sits in the project's own folder: there is no folder between them to check.
75
+ const root = { dir, anchor: project && dir !== project ? project : '' };
76
+ try { confineToRoot(root, path); } catch (error) {
77
+ if (error instanceof PathConfineError) throw new NativeExportError(403, 'target_leaves_folder', 'That place leads out of its folder through a link: nothing is written there.');
78
+ throw error;
79
+ }
80
+ return { host: exported.host, kind, projectPath: project, path, root };
81
+ }
82
+
83
+ /** The text of the file at a target, or what is in its place: { kind, text, stat }. Never follows a link. */
84
+ function onDisk(resolved) {
85
+ const kind = entryKind(resolved.path);
86
+ if (kind !== 'file') return { kind, text: null, stat: null };
87
+ let text;
88
+ try { text = readConfinedFile(resolved.root.dir, resolved.path, { maxBytes: NATIVE_TARGET_MAX_BYTES, encoding: 'utf-8' }); } catch (error) {
89
+ if (error instanceof PathConfineError) return { kind: 'unreadable', text: null, stat: null, problem: error.message };
90
+ throw error;
91
+ }
92
+ let stat = null;
93
+ try { const st = lstatSync(resolved.path); stat = { dev: st.dev, ino: st.ino, mtimeMs: st.mtimeMs, size: st.size, mode: st.mode & 0o777 }; } catch { stat = null; }
94
+ return { kind, text, stat };
95
+ }
96
+
97
+ /** An OpenCode document's text as its object. `error` when it is not a JSON object (such a file is never written). */
98
+ function readDocument(text) {
99
+ try {
100
+ const value = text.trim() ? JSON.parse(text.replace(/^/, '')) : {};
101
+ return isObject(value) ? { config: value, error: null } : { config: null, error: 'it does not hold a JSON object' };
102
+ } catch (error) { return { config: null, error: error?.message || 'it is not JSON' }; }
103
+ }
104
+
105
+ /** Does the `opencode.jsonc` beside a document define this agent too? (It wins over opencode.json.) */
106
+ function jsoncOverrides(resolved, id) {
107
+ const path = join(resolved.root.dir, 'opencode.jsonc');
108
+ if (entryKind(path) !== 'file') return false;
109
+ try {
110
+ const config = parseJsonc(readConfinedFile(resolved.root.dir, path, { maxBytes: NATIVE_TARGET_MAX_BYTES, encoding: 'utf-8' }));
111
+ return isObject(config) && (isObject(config.agents?.[id]) || isObject(config.agent?.[id]));
112
+ } catch { return false; }
113
+ }
114
+
115
+ /**
116
+ * What is at the target now, compared with what an export would put there. Reads only.
117
+ * @returns {{ host, kind, projectPath, path, exists: boolean, existingDigest: string|null, same: boolean,
118
+ * writable: boolean, problem: string|null, overriddenByJsonc?: boolean }}
119
+ * `exists`: the agent is there already (the file, or the entry of that id). `existingDigest`: of the file's text
120
+ * (Claude Code) or of the entry (OpenCode): what a replace must name.
121
+ */
122
+ function inspect(resolved, exported, { id } = {}) {
123
+ return inspectDisk(resolved, exported, id, onDisk(resolved));
124
+ }
125
+ function inspectDisk(resolved, exported, id, disk) {
126
+ const base = { host: resolved.host, kind: resolved.kind, projectPath: resolved.projectPath, path: resolved.path };
127
+ if (disk.kind !== 'file' && disk.kind !== 'absent') {
128
+ return { ...base, exists: disk.kind !== 'unreadable', existingDigest: null, same: false, writable: false, problem: disk.problem || `There is a ${disk.kind === 'dir' ? 'folder' : disk.kind === 'link' ? 'link' : 'special file'} at that place: nothing is written over it.` };
129
+ }
130
+ if (exported.kind === 'file') {
131
+ if (disk.kind === 'absent') return { ...base, exists: false, existingDigest: null, same: false, writable: true, problem: null };
132
+ const existingDigest = nativeDigest(disk.text);
133
+ return { ...base, exists: true, existingDigest, same: existingDigest === exported.digest, writable: true, problem: null };
134
+ }
135
+ // An entry of a document.
136
+ const overriddenByJsonc = jsoncOverrides(resolved, id);
137
+ if (disk.kind === 'absent') return { ...base, exists: false, existingDigest: null, same: false, writable: true, problem: null, ...(overriddenByJsonc ? { overriddenByJsonc } : {}) };
138
+ const doc = readDocument(disk.text);
139
+ if (doc.error) return { ...base, exists: false, existingDigest: null, same: false, writable: false, problem: `The file could not be read (${doc.error}); SynaBun does not change it.` };
140
+ const has = isObject(doc.config.agents?.[id]) || isObject(doc.config.agent?.[id]);
141
+ const existingDigest = has ? entryDigest(agentOf(doc.config, id)) : null;
142
+ // The same entry, already in OpenCode 2's own key (an OpenCode 1 `agent.<id>` of the same content is still moved).
143
+ const unchanged = has && existingDigest === exported.entryDigest && isObject(doc.config.agents?.[id]) && !isObject(doc.config.agent?.[id]);
144
+ return { ...base, exists: has, existingDigest, same: unchanged, writable: true, problem: null, ...(overriddenByJsonc ? { overriddenByJsonc } : {}) };
145
+ }
146
+
147
+ /**
148
+ * Write an export to its target. The caller is the owner's page (lib/agents-studio-api.js): nothing else reaches this.
149
+ * @param {object} resolved a resolveTarget() result
150
+ * @param {object} exported an exportNative() result
151
+ * @param {{ id: string, replace?: boolean, expectedDigest?: string|null }} options `replace` with the
152
+ * `existingDigest` the owner saw replaces what is there; without both, an agent that exists is left alone.
153
+ * @returns {{ host, kind, projectPath, path, action: 'created'|'replaced'|'unchanged', digest: string }}
154
+ * @throws {NativeExportError} 409 `export_exists` (with `existingDigest`), 409 `export_changed`, 409 `target_not_writable`
155
+ */
156
+ function write(resolved, exported, { id, replace = false, expectedDigest = null } = {}) {
157
+ // One read: what is compared and what is replaced are the same bytes (`expect` refuses a file that changed since).
158
+ const disk = onDisk(resolved);
159
+ const before = inspectDisk(resolved, exported, id, disk);
160
+ const base = { host: resolved.host, kind: resolved.kind, projectPath: resolved.projectPath, path: resolved.path };
161
+ if (!before.writable) throw new NativeExportError(409, 'target_not_writable', before.problem || 'That place cannot be written.', { path: resolved.path });
162
+ if (before.same) return { ...base, action: 'unchanged', digest: exported.kind === 'file' ? exported.digest : exported.entryDigest };
163
+ if (before.exists) {
164
+ if (replace !== true) throw new NativeExportError(409, 'export_exists', `${exported.kind === 'file' ? 'A file' : 'An agent'} "${id}" is already there. Look at it first: replacing it needs replace and its digest.`, { path: resolved.path, existingDigest: before.existingDigest });
165
+ if (typeof expectedDigest !== 'string' || expectedDigest !== before.existingDigest) throw new NativeExportError(409, 'export_changed', 'What is there is not what you looked at: read it again before replacing it.', { path: resolved.path, existingDigest: before.existingDigest });
166
+ }
167
+ try {
168
+ if (exported.kind === 'file') {
169
+ if (disk.kind === 'absent') writeConfinedFile(resolved.root.dir, resolved.path, exported.content, { exclusive: true, mode: 0o644 });
170
+ else replaceFileAtomic(resolved.path, exported.content, { mode: disk.stat?.mode || 0o644, expect: disk.stat, exactMode: true });
171
+ return { ...base, action: disk.kind === 'absent' ? 'created' : 'replaced', digest: exported.digest };
172
+ }
173
+ const doc = disk.kind === 'absent' ? { config: { $schema: OPENCODE_CONFIG_SCHEMA }, error: null } : readDocument(disk.text);
174
+ if (doc.error) throw new NativeExportError(409, 'target_not_writable', `The file could not be read (${doc.error}); SynaBun does not change it.`, { path: resolved.path });
175
+ const next = `${JSON.stringify(setAgent(doc.config, id, exported.entry), null, 2)}\n`;
176
+ // A new opencode.json is the user's alone (it can come to hold keys); one that exists keeps the mode it had.
177
+ if (disk.kind === 'absent') writeConfinedFile(resolved.root.dir, resolved.path, next, { exclusive: true, mode: 0o600 });
178
+ else replaceFileAtomic(resolved.path, next, { mode: disk.stat?.mode || 0o600, expect: disk.stat, exactMode: true });
179
+ return { ...base, action: before.exists ? 'replaced' : 'created', digest: exported.entryDigest };
180
+ } catch (error) {
181
+ if (error instanceof PathConfineError) throw new NativeExportError(error.status === 409 ? 409 : 403, error.status === 409 ? 'export_changed' : 'target_leaves_folder', error.message, { path: resolved.path });
182
+ throw error;
183
+ }
184
+ }
185
+
186
+ /** Is anything at this path a regular file? (For a test and a status line.) */
187
+ function exists(path) { try { return statSync(path).isFile(); } catch { return false; } }
188
+
189
+ return { resolveTarget, inspect, write, exists };
190
+ }