synabun 2.3.1 → 2.4.1

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 (370) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/README.md +1 -1
  3. package/browser-extension/content.js +189 -0
  4. package/browser-extension/engine.js +508 -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 +250 -0
  17. package/browser-extension/popup-view.js +151 -0
  18. package/browser-extension/popup.css +166 -0
  19. package/browser-extension/popup.html +108 -0
  20. package/browser-extension/popup.js +359 -0
  21. package/browser-extension/protocol.js +232 -0
  22. package/browser-extension/service-worker.js +275 -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/lib/data-home-files.js +45 -0
  28. package/lib/data-home-migration.js +34 -58
  29. package/mcp-server/dist/http.d.ts +2 -0
  30. package/mcp-server/dist/http.d.ts.map +1 -1
  31. package/mcp-server/dist/http.js +9 -1
  32. package/mcp-server/dist/http.js.map +1 -1
  33. package/mcp-server/dist/index.d.ts +11 -0
  34. package/mcp-server/dist/index.d.ts.map +1 -1
  35. package/mcp-server/dist/index.js +38 -3
  36. package/mcp-server/dist/index.js.map +1 -1
  37. package/mcp-server/dist/services/browser-route-flow.d.ts +6 -2
  38. package/mcp-server/dist/services/browser-route-flow.d.ts.map +1 -1
  39. package/mcp-server/dist/services/browser-route-flow.js +10 -3
  40. package/mcp-server/dist/services/browser-route-flow.js.map +1 -1
  41. package/mcp-server/dist/services/codex-config-heal.d.ts.map +1 -1
  42. package/mcp-server/dist/services/codex-config-heal.js +7 -0
  43. package/mcp-server/dist/services/codex-config-heal.js.map +1 -1
  44. package/mcp-server/dist/services/neural-interface.d.ts +95 -3
  45. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  46. package/mcp-server/dist/services/neural-interface.js +168 -23
  47. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  48. package/mcp-server/dist/services/team-context.d.ts +18 -0
  49. package/mcp-server/dist/services/team-context.d.ts.map +1 -0
  50. package/mcp-server/dist/services/team-context.js +29 -0
  51. package/mcp-server/dist/services/team-context.js.map +1 -0
  52. package/mcp-server/dist/services/tool-catalog.d.ts +5 -2
  53. package/mcp-server/dist/services/tool-catalog.d.ts.map +1 -1
  54. package/mcp-server/dist/services/tool-catalog.js +22 -6
  55. package/mcp-server/dist/services/tool-catalog.js.map +1 -1
  56. package/mcp-server/dist/services/tool-list.d.ts.map +1 -1
  57. package/mcp-server/dist/services/tool-list.js +4 -0
  58. package/mcp-server/dist/services/tool-list.js.map +1 -1
  59. package/mcp-server/dist/services/tool-runtime.d.ts +8 -1
  60. package/mcp-server/dist/services/tool-runtime.d.ts.map +1 -1
  61. package/mcp-server/dist/services/tool-runtime.js +18 -1
  62. package/mcp-server/dist/services/tool-runtime.js.map +1 -1
  63. package/mcp-server/dist/tools/agent-definition.d.ts +133 -0
  64. package/mcp-server/dist/tools/agent-definition.d.ts.map +1 -0
  65. package/mcp-server/dist/tools/agent-definition.js +483 -0
  66. package/mcp-server/dist/tools/agent-definition.js.map +1 -0
  67. package/mcp-server/dist/tools/agents.d.ts +92 -9
  68. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  69. package/mcp-server/dist/tools/agents.js +163 -20
  70. package/mcp-server/dist/tools/agents.js.map +1 -1
  71. package/mcp-server/dist/tools/browser-advanced.d.ts +8 -1
  72. package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
  73. package/mcp-server/dist/tools/browser-advanced.js +70 -6
  74. package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
  75. package/mcp-server/dist/tools/git-tools.d.ts +4 -2
  76. package/mcp-server/dist/tools/git-tools.d.ts.map +1 -1
  77. package/mcp-server/dist/tools/git-tools.js +283 -2
  78. package/mcp-server/dist/tools/git-tools.js.map +1 -1
  79. package/mcp-server/dist/tools/morelogin.d.ts +8 -2
  80. package/mcp-server/dist/tools/morelogin.d.ts.map +1 -1
  81. package/mcp-server/dist/tools/morelogin.js +22 -5
  82. package/mcp-server/dist/tools/morelogin.js.map +1 -1
  83. package/mcp-server/dist/tools/team.d.ts +32 -0
  84. package/mcp-server/dist/tools/team.d.ts.map +1 -0
  85. package/mcp-server/dist/tools/team.js +87 -0
  86. package/mcp-server/dist/tools/team.js.map +1 -0
  87. package/mcp-server/package-lock.json +2 -2
  88. package/mcp-server/package.json +1 -1
  89. package/mcp-server/src/http.ts +9 -1
  90. package/mcp-server/src/index.ts +34 -4
  91. package/mcp-server/src/services/browser-route-flow.ts +12 -5
  92. package/mcp-server/src/services/codex-config-heal.ts +7 -0
  93. package/mcp-server/src/services/neural-interface.ts +191 -29
  94. package/mcp-server/src/services/team-context.ts +27 -0
  95. package/mcp-server/src/services/tool-catalog.ts +26 -8
  96. package/mcp-server/src/services/tool-list.ts +4 -0
  97. package/mcp-server/src/services/tool-runtime.ts +21 -2
  98. package/mcp-server/src/tools/agent-definition.ts +458 -0
  99. package/mcp-server/src/tools/agents.ts +177 -19
  100. package/mcp-server/src/tools/browser-advanced.ts +60 -6
  101. package/mcp-server/src/tools/git-tools.ts +249 -3
  102. package/mcp-server/src/tools/morelogin.ts +20 -5
  103. package/mcp-server/src/tools/team.ts +97 -0
  104. package/neural-interface/i18n/en.json +1119 -47
  105. package/neural-interface/i18n/pt-BR.json +1119 -47
  106. package/neural-interface/lib/account-usage.js +1 -1
  107. package/neural-interface/lib/agents/builtins.json +207 -0
  108. package/neural-interface/lib/agents/density.js +101 -0
  109. package/neural-interface/lib/agents/forge-host.js +223 -0
  110. package/neural-interface/lib/agents/native-export-targets.js +190 -0
  111. package/neural-interface/lib/agents/native-export.js +365 -0
  112. package/neural-interface/lib/agents/registry.js +885 -0
  113. package/neural-interface/lib/agents/resolve.js +603 -0
  114. package/neural-interface/lib/agents/schema.js +642 -0
  115. package/neural-interface/lib/agents/split.js +37 -0
  116. package/neural-interface/lib/agents-studio-api.js +591 -0
  117. package/neural-interface/lib/assistant-api.js +76 -7
  118. package/neural-interface/lib/assistant-brains/opencode.js +60 -11
  119. package/neural-interface/lib/assistant-catalog.js +2 -0
  120. package/neural-interface/lib/assistant-continuity.js +49 -0
  121. package/neural-interface/lib/assistant-dispatch.js +351 -121
  122. package/neural-interface/lib/assistant-persona.js +105 -8
  123. package/neural-interface/lib/assistant-route-gate.js +24 -9
  124. package/neural-interface/lib/assistant-router.js +432 -47
  125. package/neural-interface/lib/assistant-run-tail.js +151 -0
  126. package/neural-interface/lib/assistant-run-wait.js +183 -0
  127. package/neural-interface/lib/assistant-runtime.js +449 -94
  128. package/neural-interface/lib/assistant-task-prompt.js +11 -2
  129. package/neural-interface/lib/assistant-usage.js +3 -2
  130. package/neural-interface/lib/automation-approval.js +2 -2
  131. package/neural-interface/lib/backup-service.js +64 -105
  132. package/neural-interface/lib/browser-close-evidence.js +80 -0
  133. package/neural-interface/lib/browser-default.js +210 -0
  134. package/neural-interface/lib/browser-extension-adapter.js +264 -0
  135. package/neural-interface/lib/browser-extension-bridge.js +441 -0
  136. package/neural-interface/lib/browser-extension-folder.js +116 -0
  137. package/neural-interface/lib/browser-extension-setup.js +140 -0
  138. package/neural-interface/lib/browser-profile-choices.js +3 -3
  139. package/neural-interface/lib/browser-tool-policy.js +1 -1
  140. package/neural-interface/lib/claude-account-links.js +301 -0
  141. package/neural-interface/lib/claude-accounts.js +45 -20
  142. package/neural-interface/lib/claude-agent-bridge.js +142 -10
  143. package/neural-interface/lib/claude-model-catalog.js +6 -0
  144. package/neural-interface/lib/claude-panel-session.js +33 -0
  145. package/neural-interface/lib/codex-accounts.js +67 -24
  146. package/neural-interface/lib/coordination/README.md +384 -0
  147. package/neural-interface/lib/coordination/service.js +563 -0
  148. package/neural-interface/lib/coordination/store.js +1138 -0
  149. package/neural-interface/lib/db.js +22 -1
  150. package/neural-interface/lib/effort-levels.js +10 -1
  151. package/neural-interface/lib/memory-list-page.js +49 -0
  152. package/neural-interface/lib/memory-list-stamp.js +60 -0
  153. package/neural-interface/lib/morelogin-outside-close.js +186 -0
  154. package/neural-interface/lib/morelogin-profile-failures.js +206 -0
  155. package/neural-interface/lib/morelogin-start-cooldown.js +160 -0
  156. package/neural-interface/lib/morelogin.js +194 -8
  157. package/neural-interface/lib/native-loop-runtime.js +26 -7
  158. package/neural-interface/lib/opencode-build-preflight.js +28 -8
  159. package/neural-interface/lib/opencode-native-boundary.js +83 -13
  160. package/neural-interface/lib/opencode-serve-records.js +14 -9
  161. package/neural-interface/lib/page-session.js +1 -1
  162. package/neural-interface/lib/peer-identity.js +73 -29
  163. package/neural-interface/lib/process-identity.js +68 -7
  164. package/neural-interface/lib/request-gate.js +3 -0
  165. package/neural-interface/lib/screenshot-location.js +33 -0
  166. package/neural-interface/lib/session-cache-builder.js +41 -3
  167. package/neural-interface/lib/skills/creation.js +1 -1
  168. package/neural-interface/lib/skills/known-bridge-digests.json +40 -0
  169. package/neural-interface/lib/studio-attention.js +56 -0
  170. package/neural-interface/lib/teams/README.md +382 -0
  171. package/neural-interface/lib/teams/api.js +287 -0
  172. package/neural-interface/lib/teams/brief.js +185 -0
  173. package/neural-interface/lib/teams/claims.js +315 -0
  174. package/neural-interface/lib/teams/git.js +293 -0
  175. package/neural-interface/lib/teams/index.js +122 -0
  176. package/neural-interface/lib/teams/integration.js +580 -0
  177. package/neural-interface/lib/teams/landing.js +184 -0
  178. package/neural-interface/lib/teams/recovery.js +256 -0
  179. package/neural-interface/lib/teams/scheduler.js +1474 -0
  180. package/neural-interface/lib/teams/schema.js +559 -0
  181. package/neural-interface/lib/teams/state.js +181 -0
  182. package/neural-interface/lib/teams/test-runner.js +86 -0
  183. package/neural-interface/lib/teams/test-sandbox.js +99 -0
  184. package/neural-interface/lib/teams/worktrees.js +757 -0
  185. package/neural-interface/lib/tool-permission-choices.js +226 -0
  186. package/neural-interface/lib/whatsapp/cards.js +24 -10
  187. package/neural-interface/lib/worker-confinement.js +206 -6
  188. package/neural-interface/package-lock.json +2 -2
  189. package/neural-interface/package.json +1 -1
  190. package/neural-interface/public/extension-setup.html +107 -0
  191. package/neural-interface/public/index.html +103 -12
  192. package/neural-interface/public/offline.html +4 -3
  193. package/neural-interface/public/shared/agent-runtime-options.js +3 -1
  194. package/neural-interface/public/shared/agents/studio/ax-agent-view.js +614 -0
  195. package/neural-interface/public/shared/agents/studio/ax-api.js +198 -0
  196. package/neural-interface/public/shared/agents/studio/ax-create-view.js +221 -0
  197. package/neural-interface/public/shared/agents/studio/ax-diff.js +143 -0
  198. package/neural-interface/public/shared/agents/studio/ax-editor-view.js +392 -0
  199. package/neural-interface/public/shared/agents/studio/ax-export-view.js +94 -0
  200. package/neural-interface/public/shared/agents/studio/ax-form.js +191 -0
  201. package/neural-interface/public/shared/agents/studio/ax-icons.js +87 -0
  202. package/neural-interface/public/shared/agents/studio/ax-library-view.js +158 -0
  203. package/neural-interface/public/shared/agents/studio/ax-library.js +162 -0
  204. package/neural-interface/public/shared/agents/studio/ax-main.js +712 -0
  205. package/neural-interface/public/shared/agents/studio/ax-native-export.js +35 -0
  206. package/neural-interface/public/shared/agents/studio/ax-options.js +198 -0
  207. package/neural-interface/public/shared/agents/studio/ax-review-view.js +175 -0
  208. package/neural-interface/public/shared/agents/studio/ax-revisions-view.js +189 -0
  209. package/neural-interface/public/shared/agents/studio/ax-runs-view.js +202 -0
  210. package/neural-interface/public/shared/agents/studio/ax-runs.js +82 -0
  211. package/neural-interface/public/shared/agents/studio/ax-teams-view.js +256 -0
  212. package/neural-interface/public/shared/agents/studio/ax-teams.js +200 -0
  213. package/neural-interface/public/shared/agents/studio/ax-templates.js +50 -0
  214. package/neural-interface/public/shared/agents/studio/ax-ui.js +194 -0
  215. package/neural-interface/public/shared/agents/studio/ax-views.js +170 -0
  216. package/neural-interface/public/shared/agy/agy-panel.js +142 -28
  217. package/neural-interface/public/shared/agy/agy-styles.js +25 -5
  218. package/neural-interface/public/shared/api.js +2 -1
  219. package/neural-interface/public/shared/assistant/asst-account-menu.js +13 -13
  220. package/neural-interface/public/shared/assistant/asst-ask-styles.js +2 -3
  221. package/neural-interface/public/shared/assistant/asst-brain-picker.js +91 -9
  222. package/neural-interface/public/shared/assistant/asst-control.js +3 -0
  223. package/neural-interface/public/shared/assistant/asst-interaction-hold.js +99 -0
  224. package/neural-interface/public/shared/assistant/asst-limit-dismissals.js +111 -0
  225. package/neural-interface/public/shared/assistant/asst-limit-dock.js +37 -3
  226. package/neural-interface/public/shared/assistant/asst-limit-wait.js +30 -7
  227. package/neural-interface/public/shared/assistant/asst-panel.js +177 -30
  228. package/neural-interface/public/shared/assistant/asst-rack-styles.js +15 -8
  229. package/neural-interface/public/shared/assistant/asst-render.js +37 -6
  230. package/neural-interface/public/shared/assistant/asst-route.js +80 -12
  231. package/neural-interface/public/shared/assistant/asst-routes-editor.js +148 -70
  232. package/neural-interface/public/shared/assistant/asst-roving.js +17 -1
  233. package/neural-interface/public/shared/assistant/asst-scene-styles.js +7 -2
  234. package/neural-interface/public/shared/assistant/asst-scenes.js +12 -1
  235. package/neural-interface/public/shared/assistant/asst-sidepanel.js +12 -2
  236. package/neural-interface/public/shared/assistant/asst-state.js +66 -1
  237. package/neural-interface/public/shared/assistant/asst-styles.js +98 -44
  238. package/neural-interface/public/shared/assistant/route-identity.js +16 -0
  239. package/neural-interface/public/shared/cc-dropdown.js +21 -15
  240. package/neural-interface/public/shared/cdx/cdx-output.js +10 -0
  241. package/neural-interface/public/shared/cdx/cdx-panel.js +18 -16
  242. package/neural-interface/public/shared/cdx/cdx-plan.js +3 -2
  243. package/neural-interface/public/shared/cdx/cdx-render.js +122 -45
  244. package/neural-interface/public/shared/cdx/cdx-requests.js +4 -4
  245. package/neural-interface/public/shared/cdx/cdx-styles.js +8 -36
  246. package/neural-interface/public/shared/cdx/cdx-tabs.js +110 -42
  247. package/neural-interface/public/shared/claude-panel-lazy.js +12 -0
  248. package/neural-interface/public/shared/code-copy.js +120 -0
  249. package/neural-interface/public/shared/constants.js +7 -0
  250. package/neural-interface/public/shared/context-menu-model.js +1 -0
  251. package/neural-interface/public/shared/cp/cp-markdown.js +7 -2
  252. package/neural-interface/public/shared/cp/cp-session-model.js +86 -5
  253. package/neural-interface/public/shared/cp/cp-session-settings.js +58 -30
  254. package/neural-interface/public/shared/cp/cp-styles.js +9 -0
  255. package/neural-interface/public/shared/dom-change-flag.js +66 -0
  256. package/neural-interface/public/shared/dom-morph.js +124 -0
  257. package/neural-interface/public/shared/extension-setup/es-page.css +134 -0
  258. package/neural-interface/public/shared/extension-setup/es-page.js +120 -0
  259. package/neural-interface/public/shared/extension-setup/es-view.js +100 -0
  260. package/neural-interface/public/shared/html-shell.js +34 -4
  261. package/neural-interface/public/shared/i18n.js +14 -1
  262. package/neural-interface/public/shared/idle-queue.js +78 -0
  263. package/neural-interface/public/shared/iface-config.js +227 -0
  264. package/neural-interface/public/shared/lazy-module.js +108 -0
  265. package/neural-interface/public/shared/memory-list.js +117 -0
  266. package/neural-interface/public/shared/morelogin-profile-choices.js +1 -1
  267. package/neural-interface/public/shared/morelogin-profile-field.js +3 -3
  268. package/neural-interface/public/shared/mtc/mtc-panel.js +3 -1
  269. package/neural-interface/public/shared/mtc/mtc-styles.js +4 -1
  270. package/neural-interface/public/shared/ocp-v2/ocp-v2-manager.js +35 -15
  271. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +77 -23
  272. package/neural-interface/public/shared/ocp-v2/ocp-v2-projectbar.js +3 -6
  273. package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +24 -21
  274. package/neural-interface/public/shared/ocp-v2/ocp-v2-send-logic.js +16 -5
  275. package/neural-interface/public/shared/ocp-v2/ocp-v2-sessions-logic.js +16 -2
  276. package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +27 -43
  277. package/neural-interface/public/shared/ocp-v2/ocp-v2-ws.js +73 -9
  278. package/neural-interface/public/shared/owner-authority-view.js +4 -10
  279. package/neural-interface/public/shared/page-session.js +1 -1
  280. package/neural-interface/public/shared/schedules-view.js +2 -2
  281. package/neural-interface/public/shared/session-project-items.js +11 -0
  282. package/neural-interface/public/shared/settings/settings-ai-browser.js +119 -0
  283. package/neural-interface/public/shared/settings/settings-browser-extension.js +446 -0
  284. package/neural-interface/public/shared/settings/settings-ia.js +4 -2
  285. package/neural-interface/public/shared/settings/settings-morelogin-cooldown.js +63 -0
  286. package/neural-interface/public/shared/settings/settings-tool-permissions.js +70 -0
  287. package/neural-interface/public/shared/sidepanel-lazy.js +40 -0
  288. package/neural-interface/public/shared/sidepanel-session-status.js +8 -14
  289. package/neural-interface/public/shared/sidepanel-shown.js +73 -0
  290. package/neural-interface/public/shared/start-bridge.js +2 -2
  291. package/neural-interface/public/shared/storage.js +6 -1
  292. package/neural-interface/public/shared/studio-attention.js +83 -0
  293. package/neural-interface/public/shared/styles.css +694 -50
  294. package/neural-interface/public/shared/term-browser-tabs.js +34 -0
  295. package/neural-interface/public/shared/transcript-rows.js +334 -0
  296. package/neural-interface/public/shared/tray-auto-close.js +106 -0
  297. package/neural-interface/public/shared/ui-agents.js +97 -0
  298. package/neural-interface/public/shared/ui-antigravity-panel.js +16 -14
  299. package/neural-interface/public/shared/ui-automation-studio.js +3 -3
  300. package/neural-interface/public/shared/ui-claude-panel.js +162 -95
  301. package/neural-interface/public/shared/ui-code-copy.js +256 -0
  302. package/neural-interface/public/shared/ui-codex-panel.js +14 -10
  303. package/neural-interface/public/shared/ui-context-menu.js +1 -1
  304. package/neural-interface/public/shared/ui-file-explorer.js +2 -3
  305. package/neural-interface/public/shared/ui-games.js +1 -1
  306. package/neural-interface/public/shared/ui-loading.js +83 -19
  307. package/neural-interface/public/shared/ui-maritaca-panel.js +12 -11
  308. package/neural-interface/public/shared/ui-menubar.js +23 -0
  309. package/neural-interface/public/shared/ui-native-loop-router.js +50 -21
  310. package/neural-interface/public/shared/ui-navbar.js +15 -9
  311. package/neural-interface/public/shared/ui-opencode-panel-v2.js +13 -11
  312. package/neural-interface/public/shared/ui-owner-authority.js +48 -25
  313. package/neural-interface/public/shared/ui-schedules-studio.js +3 -3
  314. package/neural-interface/public/shared/ui-scroll-follow.js +39 -0
  315. package/neural-interface/public/shared/ui-sessions.js +3 -3
  316. package/neural-interface/public/shared/ui-settings-entry.js +55 -0
  317. package/neural-interface/public/shared/ui-settings.js +363 -400
  318. package/neural-interface/public/shared/ui-sidepanel-layout.js +44 -25
  319. package/neural-interface/public/shared/ui-sidepanel-session-entry.js +22 -9
  320. package/neural-interface/public/shared/ui-sidepanel-sessions.js +10 -2
  321. package/neural-interface/public/shared/ui-sidepanel-tray.js +36 -41
  322. package/neural-interface/public/shared/ui-sidepanel-windows.js +14 -1
  323. package/neural-interface/public/shared/ui-styleguide.js +10 -2
  324. package/neural-interface/public/shared/ui-sync.js +6 -0
  325. package/neural-interface/public/shared/ui-terminal.js +13 -9
  326. package/neural-interface/public/shared/ui-tooltip.js +28 -7
  327. package/neural-interface/public/shared/ui-topright-overflow.js +26 -4
  328. package/neural-interface/public/shared/ui-tray-columns.js +375 -0
  329. package/neural-interface/public/shared/ui-whiteboard.js +51 -6
  330. package/neural-interface/public/shared/ui-worker-end.js +28 -1
  331. package/neural-interface/public/shared/ui-workspaces.js +13 -0
  332. package/neural-interface/public/shared/window-keys.js +71 -0
  333. package/neural-interface/public/sw.js +4 -3
  334. package/neural-interface/public/variant/2d/main.js +2 -0
  335. package/neural-interface/public/variant/3d/app.js +620 -0
  336. package/neural-interface/public/variant/3d/boot-reveal.js +47 -0
  337. package/neural-interface/public/variant/3d/main.js +30 -544
  338. package/neural-interface/public/variant/3d/map-controls.js +4 -2
  339. package/neural-interface/public/vendor/fonts/fonts.css +508 -0
  340. package/neural-interface/public/vendor/fonts/inter-OFL.txt +93 -0
  341. package/neural-interface/public/vendor/fonts/inter-cyrillic-ext.woff2 +0 -0
  342. package/neural-interface/public/vendor/fonts/inter-cyrillic.woff2 +0 -0
  343. package/neural-interface/public/vendor/fonts/inter-greek-ext.woff2 +0 -0
  344. package/neural-interface/public/vendor/fonts/inter-greek.woff2 +0 -0
  345. package/neural-interface/public/vendor/fonts/inter-latin-ext.woff2 +0 -0
  346. package/neural-interface/public/vendor/fonts/inter-latin.woff2 +0 -0
  347. package/neural-interface/public/vendor/fonts/inter-vietnamese.woff2 +0 -0
  348. package/neural-interface/public/vendor/fonts/jetbrains-mono-OFL.txt +93 -0
  349. package/neural-interface/public/vendor/fonts/jetbrains-mono-cyrillic-ext.woff2 +0 -0
  350. package/neural-interface/public/vendor/fonts/jetbrains-mono-cyrillic.woff2 +0 -0
  351. package/neural-interface/public/vendor/fonts/jetbrains-mono-greek.woff2 +0 -0
  352. package/neural-interface/public/vendor/fonts/jetbrains-mono-latin-ext.woff2 +0 -0
  353. package/neural-interface/public/vendor/fonts/jetbrains-mono-latin.woff2 +0 -0
  354. package/neural-interface/public/vendor/fonts/jetbrains-mono-vietnamese.woff2 +0 -0
  355. package/neural-interface/public/vendor/fonts/manifest.json +142 -0
  356. package/neural-interface/public/vendor/fonts/space-grotesk-OFL.txt +93 -0
  357. package/neural-interface/public/vendor/fonts/space-grotesk-latin-ext.woff2 +0 -0
  358. package/neural-interface/public/vendor/fonts/space-grotesk-latin.woff2 +0 -0
  359. package/neural-interface/public/vendor/fonts/space-grotesk-vietnamese.woff2 +0 -0
  360. package/neural-interface/scripts/boot-graph.mjs +270 -0
  361. package/neural-interface/scripts/vendor-fonts.mjs +124 -0
  362. package/neural-interface/server.js +1083 -164
  363. package/npm-shrinkwrap.json +2 -2
  364. package/package.json +4 -1
  365. package/skills/agent-forge/SKILL.md +182 -0
  366. package/skills/agent-forge/evals/evals.json +56 -0
  367. package/skills/agent-forge/references/definition-fields.md +61 -0
  368. package/skills/agent-forge/references/examples.md +105 -0
  369. package/skills/agent-forge/references/instructions.md +51 -0
  370. package/skills/agent-forge/references/review-and-export.md +84 -0
@@ -0,0 +1,885 @@
1
+ // ═══════════════════════════════════════════
2
+ // SynaBun — Agents: the registry (phase P1)
3
+ // ═══════════════════════════════════════════
4
+ //
5
+ // Where agent definitions are kept. One folder per agent and scope under SynaBun's data home:
6
+ //
7
+ // DATA_HOME/data/agents/<id>/global/ the global library's agent of that id
8
+ // DATA_HOME/data/agents/<id>/p-<16 hex>/ the same id pinned to one project (the hex is its path's digest)
9
+ // agent.json { id, scope, createdAt }, written once
10
+ // draft.json the one working revision: status draft or in_review
11
+ // revisions/000003.json a stored revision: approved, or withdrawn
12
+ //
13
+ // The lifecycle is the contract's (lib/agents/schema.js: createDraft, applyTransition) and follows the skills
14
+ // library (lib/skills/library.js, reviews.js): one editable draft, sent to review, and only the owner's approval
15
+ // makes it a revision a run may use. A stored revision's content is never changed: it is created exclusively, and
16
+ // the one later write it can get is its withdrawal, which is refused unless the content digest is the same. A change
17
+ // to an approved agent is a new draft over it, with the next number.
18
+ //
19
+ // Every write is one atomic file replace (lib/confined-fs.js) and every method is synchronous, so two requests
20
+ // never interleave inside one. A draft is checked by etag: an update names the etag it read, and a draft that
21
+ // changed meanwhile is a 409 with the current one.
22
+ //
23
+ // This module decides nothing about who may call it (lib/agents-studio-api.js does) beyond what the contract
24
+ // itself enforces: only an actor of kind `owner` approves.
25
+
26
+ import { createHash } from 'node:crypto';
27
+ import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, rmdirSync, statSync, unlinkSync } from 'node:fs';
28
+ import { isAbsolute, join } from 'node:path';
29
+ import * as YAML from 'yaml';
30
+ import { createFrontmatter } from '../../public/shared/skills/ss-frontmatter.js';
31
+ import { readConfinedFile, replaceFileAtomic, writeConfinedFile } from '../confined-fs.js';
32
+ import {
33
+ AGENT_CONTENT_FIELDS, AGENT_LIMITS, RESERVED_AGENT_IDS, AgentSchemaError,
34
+ applyTransition, contentOf, createDraft, formatAgentRef, lintAgentDefinition, normalizeAgentDefinition, privilegeDelta,
35
+ sameScope, validateAgentDefinition,
36
+ } from './schema.js';
37
+
38
+ export const AGENT_BUNDLE_FORMAT = 'synabun-agents';
39
+ export const AGENT_BUNDLE_VERSION = 1;
40
+ export const REGISTRY_LIMITS = Object.freeze({
41
+ /** One stored file (a definition with 16,000 characters of instructions is far below it). */
42
+ fileBytes: 512 * 1024,
43
+ /** Agents in one bundle. */
44
+ bundleAgents: 200,
45
+ /** A Claude Code agent file read by importClaudeAgent. */
46
+ claudeAgentBytes: 256 * 1024,
47
+ /** Lines per side of an instructions diff; longer texts are compared whole, without a line list. */
48
+ diffLines: 1500,
49
+ });
50
+
51
+ const ID_RE = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
52
+ const SCOPE_KEY_RE = /^(?:global|p-[0-9a-f]{16})$/;
53
+ const REVISION_FILE_RE = /^(\d{6})\.json$/;
54
+ const ETAG_RE = /^sha256:[0-9a-f]{64}$/;
55
+ const META_KEYS = new Set(['schemaVersion', 'revision', 'parentRevision', 'parent_revision', 'status', 'author', 'createdAt', 'created_at', 'approvedAt', 'approved_at', 'etag']);
56
+ const frontmatter = createFrontmatter(YAML);
57
+
58
+ export class AgentRegistryError extends Error {
59
+ /** @param {number} status @param {string} code @param {string} message @param {object} [extra] */
60
+ constructor(status, code, message, extra = {}) {
61
+ super(message);
62
+ this.name = 'AgentRegistryError';
63
+ this.status = status;
64
+ this.code = code;
65
+ Object.assign(this, extra);
66
+ }
67
+ }
68
+
69
+ const isObject = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
70
+ const iso = (value) => (typeof value === 'number' ? new Date(value).toISOString() : String(value));
71
+ const pad = (n) => String(n).padStart(6, '0');
72
+
73
+ /** The scope a caller names, in the contract's form. Throws 400 for one that is not a scope. */
74
+ export function scopeOf(input) {
75
+ if (input === undefined || input === null || input === '' || input === 'global') return { kind: 'global' };
76
+ const raw = isObject(input) ? input : { kind: 'project', path: String(input) };
77
+ const kind = String(raw.kind || '').trim().toLowerCase();
78
+ if (kind !== 'global' && kind !== 'project') throw new AgentRegistryError(400, 'invalid_scope', 'scope is { kind: "global" } or { kind: "project", path }.');
79
+ const scope = normalizeAgentDefinition({ scope: { kind, path: raw.path } }).scope;
80
+ if (scope.kind === 'global') return scope;
81
+ // eslint-disable-next-line no-control-regex
82
+ if (typeof raw.path !== 'string' || !scope.path || /[\u0000-\u001f\u007f]/.test(scope.path) || !isAbsolute(scope.path) || scope.path.length > AGENT_LIMITS.projectPath) {
83
+ throw new AgentRegistryError(400, 'invalid_scope', 'A project agent names its project: scope.path is the absolute path of the project folder.');
84
+ }
85
+ return scope;
86
+ }
87
+
88
+ /** The folder name of a scope: `global`, or `p-` and 16 hex digits of the project path's digest. Never request text. */
89
+ export function scopeKey(scope) {
90
+ const s = scopeOf(scope);
91
+ return s.kind === 'project' ? `p-${createHash('sha256').update(s.path).digest('hex').slice(0, 16)}` : 'global';
92
+ }
93
+
94
+ function requireId(id) {
95
+ const value = typeof id === 'string' ? id.trim().toLowerCase() : '';
96
+ if (!ID_RE.test(value) || RESERVED_AGENT_IDS.includes(value)) throw new AgentRegistryError(400, 'invalid_id', 'An agent id is lower-case letters, digits and hyphens (at most 64), and not a reserved word.');
97
+ return value;
98
+ }
99
+
100
+ /** A name as an id: "Release Notes Writer" → "release-notes-writer". '' when nothing is left. */
101
+ export function slugifyAgentId(name) {
102
+ const slug = String(name || '').normalize('NFKD').replace(/[̀-ͯ]/g, '').toLowerCase()
103
+ .replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, AGENT_LIMITS.id).replace(/-+$/g, '');
104
+ return slug && !RESERVED_AGENT_IDS.includes(slug) ? slug : (slug ? `${slug}-agent`.slice(0, AGENT_LIMITS.id) : '');
105
+ }
106
+
107
+ const snakeOf = (key) => key.replace(/[A-Z]/g, (ch) => `_${ch.toLowerCase()}`);
108
+ /**
109
+ * The content a caller sent, in the contract's spelling (`usesBrowser`, also when it was written `uses_browser`),
110
+ * without the revision metadata (which only the registry writes) and without keys the contract does not have.
111
+ * A field the caller did not name is not in the answer: a patch changes what it names and nothing else.
112
+ */
113
+ function contentInput(input) {
114
+ const src = isObject(input) ? input : {};
115
+ const out = {};
116
+ for (const field of AGENT_CONTENT_FIELDS) {
117
+ if (META_KEYS.has(field)) continue;
118
+ const snake = snakeOf(field);
119
+ if (Object.prototype.hasOwnProperty.call(src, field)) { if (src[field] !== undefined) out[field] = src[field]; }
120
+ else if (snake !== field && Object.prototype.hasOwnProperty.call(src, snake) && src[snake] !== undefined) out[field] = src[snake];
121
+ }
122
+ return out;
123
+ }
124
+
125
+ /** Type errors of a patch: a value that cannot be what its field holds is refused, not silently defaulted. */
126
+ function typeErrors(input) {
127
+ return validateAgentDefinition(isObject(input) ? input : {}).errors.filter((error) => error.code === 'invalid_type');
128
+ }
129
+
130
+ // ── a small line diff (for instructions) ─────────────────────────────────────
131
+ /** → [{ op: ' ' | '+' | '-', line }] or null when either side is over the limit. */
132
+ function lineDiff(before, after, limit = REGISTRY_LIMITS.diffLines) {
133
+ const a = String(before || '').split('\n');
134
+ const b = String(after || '').split('\n');
135
+ if (a.length > limit || b.length > limit) return null;
136
+ const rows = a.length + 1;
137
+ const cols = b.length + 1;
138
+ const table = new Uint16Array(rows * cols);
139
+ for (let i = a.length - 1; i >= 0; i -= 1) {
140
+ for (let j = b.length - 1; j >= 0; j -= 1) {
141
+ table[i * cols + j] = a[i] === b[j] ? table[(i + 1) * cols + j + 1] + 1 : Math.max(table[(i + 1) * cols + j], table[i * cols + j + 1]);
142
+ }
143
+ }
144
+ const out = [];
145
+ let i = 0;
146
+ let j = 0;
147
+ while (i < a.length && j < b.length) {
148
+ if (a[i] === b[j]) { out.push({ op: ' ', line: a[i] }); i += 1; j += 1; }
149
+ else if (table[(i + 1) * cols + j] >= table[i * cols + j + 1]) { out.push({ op: '-', line: a[i] }); i += 1; }
150
+ else { out.push({ op: '+', line: b[j] }); j += 1; }
151
+ }
152
+ while (i < a.length) { out.push({ op: '-', line: a[i] }); i += 1; }
153
+ while (j < b.length) { out.push({ op: '+', line: b[j] }); j += 1; }
154
+ return out;
155
+ }
156
+
157
+ const sameValue = (x, y) => JSON.stringify(x ?? null) === JSON.stringify(y ?? null);
158
+
159
+ /** What differs between two definitions, field by field, and what the second may do that the first may not. */
160
+ export function diffDefinitions(before, after) {
161
+ const a = before ? contentOf(normalizeAgentDefinition(before)) : null;
162
+ const b = contentOf(normalizeAgentDefinition(after));
163
+ const changes = [];
164
+ for (const field of AGENT_CONTENT_FIELDS) {
165
+ const from = a ? a[field] : null;
166
+ if (a && sameValue(from, b[field])) continue;
167
+ if (!a && sameValue(b[field], null)) continue;
168
+ const change = { field, from, to: b[field] };
169
+ if (field === 'instructions') {
170
+ const lines = lineDiff(from, b[field]);
171
+ if (lines) {
172
+ change.lines = lines;
173
+ change.added = lines.filter((row) => row.op === '+').length;
174
+ change.removed = lines.filter((row) => row.op === '-').length;
175
+ }
176
+ }
177
+ changes.push(change);
178
+ }
179
+ return { changed: changes.length > 0, changes, privileges: privilegeDelta(before || null, after) };
180
+ }
181
+
182
+ // ── a Claude Code agent file ─────────────────────────────────────────────────
183
+ // ~/.claude/agents/<name>.md or <project>/.claude/agents/<name>.md: YAML frontmatter (name, description, tools,
184
+ // model, and newer keys) and a body that is the agent's system prompt.
185
+
186
+ const CLAUDE_WRITE_TOOLS = new Set(['write', 'edit', 'multiedit', 'notebookedit', 'bash']);
187
+ const CLAUDE_MODEL_INHERIT = new Set(['', 'inherit', 'default', 'auto']);
188
+
189
+ function claudeToolNames(value) {
190
+ if (Array.isArray(value)) return value.filter((item) => typeof item === 'string').map((item) => item.trim()).filter(Boolean);
191
+ if (typeof value === 'string') return value.split(',').map((item) => item.trim()).filter(Boolean);
192
+ return null;
193
+ }
194
+
195
+ /**
196
+ * A Claude Code agent file as the content of a SynaBun agent draft, with what was mapped and what was left out.
197
+ * Pure: reads no file. The tool names of a Claude agent (Read, Bash…) are Claude Code's own, not SynaBun tool
198
+ * groups, so `tools` stays the worker's default; the MCP servers its tool list names become `mcpServers`, and a
199
+ * tool list with nothing that writes makes the agent read-only.
200
+ * @param {string} markdown the file's text
201
+ * @param {{ fileName?: string, id?: string, scope?: object }} [options]
202
+ * @returns {{ content: object, notes: string[] }}
203
+ * @throws {AgentRegistryError} 400 `claude_agent_unreadable`, 413 `too_large`
204
+ */
205
+ export function parseClaudeAgent(markdown, { fileName = '', id = null, scope = null } = {}) {
206
+ if (typeof markdown !== 'string' || !markdown.trim()) throw new AgentRegistryError(400, 'claude_agent_unreadable', 'Send the text of a Claude Code agent file (frontmatter and body).');
207
+ if (Buffer.byteLength(markdown, 'utf8') > REGISTRY_LIMITS.claudeAgentBytes) throw new AgentRegistryError(413, 'too_large', `A Claude Code agent file is at most ${REGISTRY_LIMITS.claudeAgentBytes / 1024} KB.`);
208
+ const parsed = frontmatter.parse(markdown);
209
+ const errors = parsed.diagnostics.filter((d) => d.severity === 'error');
210
+ if (parsed.data === null || errors.length) {
211
+ throw new AgentRegistryError(400, 'claude_agent_unreadable', `The frontmatter could not be read: ${errors[0]?.message || 'it is not a YAML mapping'}.`, { diagnostics: errors.slice(0, 10) });
212
+ }
213
+ const fm = parsed.data || {};
214
+ const notes = [];
215
+ const baseName = String(fileName || '').replace(/\\/g, '/').split('/').pop().replace(/\.md$/i, '');
216
+ const rawName = typeof fm.name === 'string' && fm.name.trim() ? fm.name.trim() : baseName;
217
+ const agentId = id ? String(id).trim().toLowerCase() : slugifyAgentId(rawName);
218
+ if (!agentId) throw new AgentRegistryError(400, 'claude_agent_unreadable', 'The file names no agent: its frontmatter has no name, and no file name was given.');
219
+ if (!parsed.hasFrontmatter) notes.push('The file has no frontmatter: the whole text became the instructions.');
220
+
221
+ let description = typeof fm.description === 'string' ? fm.description.replace(/\s+/g, ' ').trim() : '';
222
+ if (description.length > AGENT_LIMITS.description) {
223
+ description = `${description.slice(0, AGENT_LIMITS.description - 1).trimEnd()}…`;
224
+ notes.push(`The description was cut to ${AGENT_LIMITS.description} characters.`);
225
+ }
226
+ let instructions = String(parsed.body || '').replace(/\r\n?/g, '\n').trim();
227
+ if (instructions.length > AGENT_LIMITS.instructions) {
228
+ instructions = instructions.slice(0, AGENT_LIMITS.instructions).trimEnd();
229
+ notes.push(`The instructions were cut to ${AGENT_LIMITS.instructions} characters.`);
230
+ }
231
+
232
+ const model = typeof fm.model === 'string' && !CLAUDE_MODEL_INHERIT.has(fm.model.trim().toLowerCase()) ? fm.model.trim() : null;
233
+ const effort = typeof fm.effort === 'string' && fm.effort.trim() ? fm.effort.trim().toLowerCase() : null;
234
+ const tools = claudeToolNames(fm.tools);
235
+ const servers = new Set();
236
+ for (const name of tools || []) {
237
+ // Claude Code writes an MCP tool as mcp__<server>__<tool> (or mcp__<server> for every tool of it).
238
+ const match = /^mcp__(.+?)(?:__.*)?$/.exec(name);
239
+ if (match && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/.test(match[1]) && match[1].toLowerCase() !== 'synabun') servers.add(match[1]);
240
+ }
241
+ if (isObject(fm.mcpServers)) for (const name of Object.keys(fm.mcpServers)) if (/^[A-Za-z0-9._:-]{1,64}$/.test(name) && name.toLowerCase() !== 'synabun') servers.add(name);
242
+ if (Array.isArray(fm.mcpServers)) for (const name of fm.mcpServers) if (typeof name === 'string' && /^[A-Za-z0-9._:-]{1,64}$/.test(name) && name.toLowerCase() !== 'synabun') servers.add(name);
243
+ const readOnly = (tools && tools.length > 0 && !tools.some((name) => CLAUDE_WRITE_TOOLS.has(name.toLowerCase().replace(/\(.*$/, '')))) || String(fm.permissionMode || '').toLowerCase() === 'plan';
244
+ if (tools) notes.push(`Claude Code tools (${tools.slice(0, 12).join(', ')}${tools.length > 12 ? ', …' : ''}) are not SynaBun tool groups: the agent keeps the worker's default tools${readOnly ? ' and is read-only, because that list has nothing that writes' : ''}.`);
245
+ if (servers.size) notes.push(`MCP servers named by the file: ${[...servers].join(', ')}.`);
246
+ const skills = Array.isArray(fm.skills) ? fm.skills.filter((item) => typeof item === 'string').map((item) => item.trim().toLowerCase()).filter(Boolean)
247
+ : (typeof fm.skills === 'string' ? fm.skills.split(',').map((item) => item.trim().toLowerCase()).filter(Boolean) : []);
248
+ if (fm.color !== undefined) notes.push('The colour was left out: a SynaBun agent takes a style-guide token.');
249
+ const known = new Set(['name', 'description', 'tools', 'model', 'effort', 'skills', 'color', 'mcpServers', 'permissionMode']);
250
+ const dropped = Object.keys(fm).filter((key) => !known.has(key));
251
+ if (dropped.length) notes.push(`Not carried over: ${dropped.slice(0, 12).join(', ')}.`);
252
+
253
+ return {
254
+ content: {
255
+ id: agentId,
256
+ name: rawName.replace(/\s+/g, ' ').slice(0, AGENT_LIMITS.name) || agentId,
257
+ description,
258
+ instructions,
259
+ provider: 'claude-code',
260
+ model,
261
+ effort,
262
+ tools: null,
263
+ mcpServers: [...servers],
264
+ capability: readOnly ? 'read-only' : 'workspace',
265
+ skills,
266
+ scope: scope ? scopeOf(scope) : { kind: 'global' },
267
+ },
268
+ notes,
269
+ };
270
+ }
271
+
272
+ export function loadBuiltinAgents(path = new URL('./builtins.json', import.meta.url)) {
273
+ try {
274
+ const rows = JSON.parse(readFileSync(path, 'utf8'));
275
+ if (!Array.isArray(rows)) throw new Error('expected an array');
276
+ return rows;
277
+ } catch (error) {
278
+ console.warn('Unable to load built-in agents:', error.message);
279
+ return [];
280
+ }
281
+ }
282
+
283
+ /**
284
+ * @param {object} o
285
+ * @param {string} o.dir DATA_HOME/data/agents
286
+ * @param {object[]} [o.builtins] trusted definitions shipped with the application
287
+ * @param {() => string|number} [o.now] the time (ISO text or epoch milliseconds)
288
+ * @param {(event: object) => void} [o.emit] told of every change: { action, id, scope, revision, status }
289
+ * @param {() => Iterable<string>|null} [o.knownMcpServers] the MCP servers that exist, for validation (null: not checked)
290
+ */
291
+ export function createAgentRegistry({ dir, builtins = [], now = () => new Date().toISOString(), emit = () => {}, knownMcpServers = () => null } = {}) {
292
+ if (!dir || typeof dir !== 'string') throw new Error('createAgentRegistry needs { dir }');
293
+ // Shipped revision 1 lives only in the package. Owner revisions use the normal data directory.
294
+ const library = new Map();
295
+ const classAgents = new Map();
296
+ const released = '2026-11-19T00:00:00.000Z';
297
+ for (const row of Array.isArray(builtins) ? builtins : []) {
298
+ try {
299
+ const checked = validateAgentDefinition({ ...row, revision: 1, status: 'approved',
300
+ author: { kind: 'system' }, createdAt: released, approvedAt: released }, { requireMeta: true });
301
+ if (!checked.ok || row.id !== checked.value.id || checked.value.taskClasses.length !== 1 ||
302
+ checked.value.scope.kind !== 'global' || library.has(row.id) || classAgents.has(checked.value.taskClasses[0])) {
303
+ throw new Error(checked.errors[0]?.message || 'expected a unique global id and a unique task class');
304
+ }
305
+ library.set(row.id, checked.value);
306
+ classAgents.set(checked.value.taskClasses[0], row.id);
307
+ } catch (error) {
308
+ console.warn('Skipping built-in agent:', row?.id, error.message);
309
+ }
310
+ }
311
+ const stamp = () => iso(now());
312
+ const announce = (event) => { try { emit(event); } catch { /* a listener's own failure */ } };
313
+ const validationOptions = () => { let servers = null; try { servers = knownMcpServers() || null; } catch { servers = null; } return servers ? { knownMcpServers: servers } : {}; };
314
+
315
+ // ── paths (an id is checked by shape and a scope key is computed: neither is ever a path a caller wrote) ──
316
+ const agentDir = (id, scope) => join(dir, requireId(id), scopeKey(scope));
317
+ const draftPath = (id, scope) => join(agentDir(id, scope), 'draft.json');
318
+ const metaPath = (id, scope) => join(agentDir(id, scope), 'agent.json');
319
+ const revisionsDir = (id, scope) => join(agentDir(id, scope), 'revisions');
320
+ const revisionPath = (id, scope, n) => join(revisionsDir(id, scope), `${pad(n)}.json`);
321
+
322
+ function readJson(path) {
323
+ let text;
324
+ try { text = readConfinedFile(dir, path, { maxBytes: REGISTRY_LIMITS.fileBytes, encoding: 'utf-8' }); } catch (error) {
325
+ if (error?.code === 'ENOENT' || error?.status === 404) return undefined;
326
+ throw error;
327
+ }
328
+ try { return JSON.parse(text); } catch { return null; }
329
+ }
330
+ function writeJson(path, value, { exclusive = false } = {}) {
331
+ const data = `${JSON.stringify(value, null, 2)}\n`;
332
+ if (Buffer.byteLength(data, 'utf8') > REGISTRY_LIMITS.fileBytes) throw new AgentRegistryError(413, 'too_large', 'The definition is too large to store.');
333
+ if (exclusive) {
334
+ try { writeConfinedFile(dir, path, data, { exclusive: true, mode: 0o600 }); } catch (error) {
335
+ if (error?.code === 'EEXIST' || error?.status === 409) throw new AgentRegistryError(409, 'revision_exists', 'That revision already exists; a stored revision is never replaced.');
336
+ throw error;
337
+ }
338
+ return;
339
+ }
340
+ replaceFileAtomic(path, data, { mode: 0o600 });
341
+ }
342
+ const ensureDirs = (id, scope) => mkdirSync(revisionsDir(id, scope), { recursive: true, mode: 0o700 });
343
+
344
+ /**
345
+ * A stored record → { definition, updatedAt, review, damaged }. A stored revision that no longer validates (its
346
+ * content does not match its etag, a field is not what the contract holds) is kept and marked: it is never run.
347
+ * A draft may be incomplete while it is worked on, so only one whose content was changed behind its etag, or
348
+ * that is not a definition at all, is damaged.
349
+ */
350
+ function readRecord(path, { draft = false } = {}) {
351
+ const raw = readJson(path);
352
+ if (raw === undefined) return null;
353
+ if (!isObject(raw) || !isObject(raw.definition)) return { definition: null, damaged: true, problems: [{ field: '', code: 'unreadable', message: 'The stored file is not an agent revision.' }] };
354
+ const checked = validateAgentDefinition(raw.definition, { requireMeta: true });
355
+ const problems = draft ? checked.errors.filter((error) => error.code === 'etag_mismatch' || error.field === 'id' || error.field === 'createdAt') : checked.errors;
356
+ return {
357
+ definition: checked.value,
358
+ updatedAt: typeof raw.updatedAt === 'string' ? raw.updatedAt : checked.value.createdAt,
359
+ review: isObject(raw.review) ? raw.review : null,
360
+ ...(problems.length ? { damaged: true, problems } : {}),
361
+ };
362
+ }
363
+ const record = (definition, extra = {}) => ({ kind: 'synabun-agent-revision', definition, updatedAt: stamp(), ...extra });
364
+
365
+ function revisionNumbers(id, scope) {
366
+ let names = [];
367
+ try { names = readdirSync(revisionsDir(id, scope)); } catch { return []; }
368
+ return names.map((name) => REVISION_FILE_RE.exec(name)).filter(Boolean).map((match) => Number(match[1])).sort((a, b) => a - b);
369
+ }
370
+
371
+ /** Everything stored for one agent and scope, or null when there is none. */
372
+ function load(id, scope) {
373
+ const agentId = requireId(id);
374
+ const where = scopeOf(scope);
375
+ const bundled = where.kind === 'global' && library.get(agentId);
376
+ const stored = existsSync(agentDir(agentId, where));
377
+ if (!bundled && !stored) return null;
378
+ const numbers = stored ? revisionNumbers(agentId, where) : [];
379
+ const revisions = numbers.map((n) => ({ number: n, ...(readRecord(revisionPath(agentId, where, n)) || { definition: null, damaged: true }) }));
380
+ let draft = stored ? readRecord(draftPath(agentId, where), { draft: true }) : null;
381
+ // An approval writes the revision, then removes the draft: a draft whose number is already stored is that leftover.
382
+ if (draft?.definition && numbers.includes(draft.definition.revision)) {
383
+ try { unlinkSync(draftPath(agentId, where)); } catch { /* removed by the next write */ }
384
+ draft = null;
385
+ }
386
+ const meta = stored ? readJson(metaPath(agentId, where)) : undefined;
387
+ // An independently created owner agent (even a draft or damaged revision) keeps its entire history.
388
+ if (bundled && meta == null && !numbers.includes(1) && (!draft || draft.definition?.revision > 1)) {
389
+ revisions.unshift({ number: 1, definition: { ...structuredClone(bundled), source: 'builtin' }, updatedAt: bundled.createdAt });
390
+ }
391
+ if (!draft && !revisions.length) return null;
392
+ const approved = [...revisions].reverse().find((rev) => rev.definition?.status === 'approved' && !rev.damaged) || null;
393
+ return { id: agentId, scope: where, meta: isObject(meta) ? meta : null, draft, revisions, approved };
394
+ }
395
+ function require(id, scope) {
396
+ const found = load(id, scope);
397
+ if (!found) throw new AgentRegistryError(404, 'agent_not_found', `There is no agent "${String(id).slice(0, 80)}" in ${scopeOf(scope).kind === 'project' ? 'that project' : 'the global library'}.`);
398
+ return found;
399
+ }
400
+
401
+ // ── views ──
402
+ const revisionMeta = (rev) => (rev.definition ? {
403
+ revision: rev.definition.revision, parentRevision: rev.definition.parentRevision, status: rev.definition.status, etag: rev.definition.etag,
404
+ author: rev.definition.author, createdAt: rev.definition.createdAt, approvedAt: rev.definition.approvedAt, updatedAt: rev.updatedAt || null,
405
+ ...(rev.review ? { review: rev.review } : {}), ...(rev.damaged ? { damaged: true } : {}),
406
+ } : { revision: rev.number ?? null, damaged: true });
407
+
408
+ function overallStatus(found) {
409
+ if (found.approved) return 'approved';
410
+ if (found.draft?.definition) return found.draft.definition.status;
411
+ return 'withdrawn';
412
+ }
413
+ function summary(found) {
414
+ const shown = found.approved?.definition || found.draft?.definition || [...found.revisions].reverse().find((rev) => rev.definition)?.definition || null;
415
+ const times = [found.draft?.updatedAt, ...found.revisions.map((rev) => rev.updatedAt)].filter(Boolean).sort();
416
+ return {
417
+ id: found.id, scope: found.scope, ref: formatAgentRef({ id: found.id, scope: found.scope }),
418
+ name: shown?.name || found.id, description: shown?.description || '',
419
+ provider: shown?.provider || null, model: shown?.model || null, effort: shown?.effort || null,
420
+ capability: shown?.capability || null, usesBrowser: !!shown?.usesBrowser, usesComputer: !!shown?.usesComputer,
421
+ taskClasses: shown?.taskClasses || [], icon: shown?.icon || null, color: shown?.color || null,
422
+ ...(shown?.source ? { source: shown.source } : {}),
423
+ status: overallStatus(found),
424
+ approvedRevision: found.approved?.definition.revision ?? null,
425
+ approvedEtag: found.approved?.definition.etag ?? null,
426
+ approvedAt: found.approved?.definition.approvedAt ?? null,
427
+ draft: found.draft?.definition ? { ...revisionMeta(found.draft) } : null,
428
+ revisionCount: found.revisions.length,
429
+ createdAt: found.meta?.createdAt || shown?.createdAt || null,
430
+ updatedAt: times.at(-1) || null,
431
+ ...(found.draft?.damaged || found.revisions.some((rev) => rev.damaged) ? { damaged: true } : {}),
432
+ };
433
+ }
434
+ function detail(found) {
435
+ return {
436
+ ...summary(found),
437
+ draftDefinition: found.draft?.definition || null,
438
+ approvedDefinition: found.approved?.definition || null,
439
+ revisions: found.revisions.map(revisionMeta),
440
+ };
441
+ }
442
+ /** A draft with what the page shows beside it: its problems and the softer findings. */
443
+ function checks(definition) {
444
+ const checked = validateAgentDefinition(definition, validationOptions());
445
+ return { validation: { ok: checked.ok, errors: checked.errors }, warnings: lintAgentDefinition(definition) };
446
+ }
447
+
448
+ // ── listing ──
449
+ /** The scope a folder `<id>/<key>` holds, read back from what is stored (the folder name is only its digest). */
450
+ function storedScope(id, key) {
451
+ if (!SCOPE_KEY_RE.test(key)) return null;
452
+ if (key === 'global') return { kind: 'global' };
453
+ let scope = null;
454
+ try { const meta = readJson(join(dir, id, key, 'agent.json')); scope = isObject(meta?.scope) ? scopeOf(meta.scope) : null; } catch { scope = null; }
455
+ return scope && scopeKey(scope) === key ? scope : null;
456
+ }
457
+ function scopeKeys(id) {
458
+ let keys = [];
459
+ try { keys = readdirSync(join(dir, id)); } catch { /* bundled only */ }
460
+ if (library.has(id) && !keys.includes('global')) keys.push('global');
461
+ return keys.sort();
462
+ }
463
+
464
+ function everyAgent() {
465
+ let ids = [];
466
+ try { ids = readdirSync(dir); } catch { /* a new installation has no owner agents */ }
467
+ const out = [];
468
+ for (const id of [...new Set([...ids, ...library.keys()])].sort()) {
469
+ if (!ID_RE.test(id)) continue;
470
+ for (const key of scopeKeys(id)) {
471
+ const scope = storedScope(id, key);
472
+ const found = scope ? load(id, scope) : null;
473
+ if (found) out.push(found);
474
+ }
475
+ }
476
+ return out;
477
+ }
478
+
479
+ /**
480
+ * @param {object} [filter]
481
+ * @param {'all'|'global'|'project'} [filter.scope] which library (default: all)
482
+ * @param {string} [filter.projectPath] with scope `project`: the agents pinned to exactly that project
483
+ * @param {string|string[]} [filter.status] approved | in_review | draft | withdrawn (the agent's overall status)
484
+ * @param {string} [filter.q] text in the id, name or description
485
+ */
486
+ function list({ scope = 'all', projectPath = null, status = null, q = '' } = {}) {
487
+ const wanted = status ? new Set([].concat(status).map((s) => String(s).trim().toLowerCase().replace(/-/g, '_'))) : null;
488
+ const needle = String(q || '').trim().toLowerCase();
489
+ const project = projectPath ? scopeOf({ kind: 'project', path: projectPath }) : null;
490
+ return everyAgent().filter((found) => {
491
+ if (scope === 'global' && found.scope.kind !== 'global') return false;
492
+ if (scope === 'project' && (found.scope.kind !== 'project' || (project && !sameScope(found.scope, project)))) return false;
493
+ if (wanted && !wanted.has(overallStatus(found)) && !(found.draft?.definition && wanted.has(found.draft.definition.status))) return false;
494
+ if (needle) {
495
+ const view = summary(found);
496
+ if (![view.id, view.name, view.description].some((value) => String(value || '').toLowerCase().includes(needle))) return false;
497
+ }
498
+ return true;
499
+ }).map(summary);
500
+ }
501
+
502
+ /** The scopes an id is stored under (the resolver walks them: a project's agent wins over the global one). */
503
+ function scopesOf(id) {
504
+ let agentId;
505
+ try { agentId = requireId(id); } catch { return []; }
506
+ return scopeKeys(agentId).map((key) => storedScope(agentId, key)).filter((scope) => scope && load(agentId, scope));
507
+ }
508
+
509
+ function get({ id, scope } = {}) { return detail(require(id, scope)); }
510
+ function has({ id, scope } = {}) { try { return !!load(id, scope); } catch { return false; } }
511
+
512
+ /** One stored revision's definition; `draft` is the working one. null when there is none. */
513
+ function revision({ id, scope } = {}, which) {
514
+ const found = load(id, scope);
515
+ if (!found) return null;
516
+ if (which === 'draft') return found.draft?.definition || null;
517
+ if (which === 'approved' || which === 'current' || which === undefined || which === null) return found.approved?.definition || null;
518
+ const n = Number(which);
519
+ return found.revisions.find((rev) => rev.number === n)?.definition || null;
520
+ }
521
+ function revisions({ id, scope } = {}) { return require(id, scope).revisions.map(revisionMeta); }
522
+
523
+ // ── drafts ──
524
+ function draftBase(found) {
525
+ return found.approved?.definition || [...found.revisions].reverse().find((rev) => rev.definition)?.definition || null;
526
+ }
527
+ function nextRevision(found) {
528
+ return Math.max(0, ...found.revisions.map((rev) => rev.number)) + 1;
529
+ }
530
+ /** The revision a new draft is made over; an agent whose every stored revision is unreadable has none. */
531
+ function requireBase(found) {
532
+ const base = draftBase(found);
533
+ if (!base) throw new AgentRegistryError(409, 'revision_damaged', 'None of this agent\'s stored revisions can be read, so no draft can be made over one.');
534
+ return base;
535
+ }
536
+ function saveDraft(id, scope, definition, extra = {}) {
537
+ ensureDirs(id, scope);
538
+ writeJson(draftPath(id, scope), record(definition, extra));
539
+ return definition;
540
+ }
541
+ function draftAnswer(found, definition, action) {
542
+ const fresh = load(found.id, found.scope);
543
+ announce({ action, id: found.id, scope: found.scope, revision: definition.revision, status: definition.status });
544
+ return { agent: detail(fresh), draft: definition, etag: definition.etag, ...checks(definition) };
545
+ }
546
+
547
+ /**
548
+ * A new agent: its first draft. The id and the scope are part of what is sent (`scope` defaults to the global
549
+ * library). 409 `agent_exists` when that scope already has an agent of the id.
550
+ * @param {object} input the content (any accepted spelling)
551
+ * @param {{ author?: object|string }} [options]
552
+ */
553
+ function create(input, { author = 'owner' } = {}) {
554
+ if (!isObject(input)) throw new AgentRegistryError(400, 'invalid_body', 'An agent definition is an object.');
555
+ const types = typeErrors(contentInput(input));
556
+ if (types.length) throw new AgentRegistryError(400, 'not_valid', types[0].message, { errors: types });
557
+ const content = contentInput(input);
558
+ const id = requireId(content.id);
559
+ const scope = scopeOf(content.scope);
560
+ if (load(id, scope)) throw new AgentRegistryError(409, 'agent_exists', `${scope.kind === 'project' ? 'That project' : 'The global library'} already has an agent "${id}".`);
561
+ const definition = createDraft({ ...content, id, scope }, { now: stamp(), author });
562
+ ensureDirs(id, scope);
563
+ writeJson(metaPath(id, scope), { kind: 'synabun-agent', id, scope, createdAt: definition.createdAt });
564
+ saveDraft(id, scope, definition);
565
+ return draftAnswer({ id, scope }, definition, 'created');
566
+ }
567
+
568
+ /** The working draft, made over the newest revision when there is none yet. Changes nothing when one exists. */
569
+ function openDraft({ id, scope } = {}, { author = 'owner' } = {}) {
570
+ const found = require(id, scope);
571
+ if (found.draft?.definition) return { agent: detail(found), draft: found.draft.definition, etag: found.draft.definition.etag, ...checks(found.draft.definition) };
572
+ const base = requireBase(found);
573
+ const definition = createDraft({}, { now: stamp(), base, revision: nextRevision(found), author });
574
+ saveDraft(found.id, found.scope, definition);
575
+ return draftAnswer(found, definition, 'draft_opened');
576
+ }
577
+
578
+ /**
579
+ * Change the draft. `expectedEtag` is the etag the caller read: the draft's, or (when there is no draft yet and
580
+ * this patch starts one) the newest revision's. A draft that is in review is not edited: it goes back first.
581
+ * @throws 428 `etag_required`, 409 `etag_conflict` (with `currentEtag`), 409 `not_editable`, 409 `scope_changed`,
582
+ * 400 `id_changed` / `not_valid`
583
+ */
584
+ function updateDraft({ id, scope } = {}, patch, { expectedEtag = null, author = null } = {}) {
585
+ const found = require(id, scope);
586
+ if (!isObject(patch)) throw new AgentRegistryError(400, 'invalid_body', 'A patch is an object of the fields to change.');
587
+ const content = contentInput(patch);
588
+ const types = typeErrors(content);
589
+ if (types.length) throw new AgentRegistryError(400, 'not_valid', types[0].message, { errors: types });
590
+ if (content.id !== undefined && content.id !== null && String(content.id).trim().toLowerCase() !== found.id) throw new AgentRegistryError(400, 'id_changed', 'A revision keeps the id of the agent it revises.', { field: 'id' });
591
+ if (content.scope !== undefined && content.scope !== null && !sameScope(scopeOf(content.scope), found.scope)) {
592
+ throw new AgentRegistryError(409, 'scope_changed', 'An agent stays in its library: copy it to the other one instead.', { field: 'scope' });
593
+ }
594
+ const current = found.draft?.definition || null;
595
+ const base = current || requireBase(found);
596
+ if (typeof expectedEtag !== 'string' || !ETAG_RE.test(expectedEtag)) throw new AgentRegistryError(428, 'etag_required', 'Name the etag you read (If-Match, or expectedEtag).', { currentEtag: base?.etag || null });
597
+ if (base && expectedEtag !== base.etag) throw new AgentRegistryError(409, 'etag_conflict', 'The draft changed since you read it.', { currentEtag: base.etag, current: base });
598
+ if (current && current.status !== 'draft') throw new AgentRegistryError(409, 'not_editable', 'This revision is in review: send it back to draft before changing it.', { revisionStatus: current.status });
599
+ const { id: _id, scope: _scope, ...fields } = content;
600
+ const definition = current
601
+ ? normalizeAgentDefinition({ ...current, ...fields, id: found.id, scope: found.scope, status: 'draft', author: author || current.author, approvedAt: null })
602
+ : createDraft(fields, { now: stamp(), base, revision: nextRevision(found), author: author || 'owner' });
603
+ saveDraft(found.id, found.scope, definition);
604
+ return draftAnswer(found, definition, 'draft_saved');
605
+ }
606
+
607
+ /** Throw the draft away (a draft only: one in review is withdrawn or sent back first). */
608
+ function discardDraft({ id, scope } = {}, { expectedEtag = null } = {}) {
609
+ const found = require(id, scope);
610
+ const current = found.draft?.definition;
611
+ if (!current) throw new AgentRegistryError(404, 'draft_not_found', 'This agent has no draft.');
612
+ if (expectedEtag && expectedEtag !== current.etag) throw new AgentRegistryError(409, 'etag_conflict', 'The draft changed since you read it.', { currentEtag: current.etag });
613
+ if (current.status !== 'draft') throw new AgentRegistryError(409, 'not_editable', 'A revision in review is withdrawn or sent back, not discarded.', { revisionStatus: current.status });
614
+ try { unlinkSync(draftPath(found.id, found.scope)); } catch { /* already gone */ }
615
+ announce({ action: 'draft_discarded', id: found.id, scope: found.scope, revision: current.revision });
616
+ const left = load(found.id, found.scope);
617
+ // An agent that was only ever a draft is gone with it.
618
+ if (!left) { removeFolder(found.id, found.scope); return { agent: null, removed: true }; }
619
+ return { agent: detail(left), removed: false };
620
+ }
621
+
622
+ // ── transitions ──
623
+ function transitionError(error) {
624
+ if (error instanceof AgentSchemaError) throw new AgentRegistryError(error.status || 400, error.code, error.message, { ...(error.errors ? { errors: error.errors } : {}), ...(error.from ? { from: error.from, to: error.to } : {}) });
625
+ throw error;
626
+ }
627
+ function move(definition, to, actor) {
628
+ try { return applyTransition(definition, to, { now: stamp(), actor }); } catch (error) { return transitionError(error); }
629
+ }
630
+ function requireDraft(found, expectedEtag) {
631
+ const current = found.draft?.definition;
632
+ if (!current) throw new AgentRegistryError(404, 'draft_not_found', 'This agent has no draft.');
633
+ if (found.draft.damaged) throw new AgentRegistryError(409, 'revision_damaged', 'The stored draft no longer reads as a valid definition; fix it first.', { errors: found.draft.problems || [] });
634
+ if (expectedEtag && expectedEtag !== current.etag) throw new AgentRegistryError(409, 'etag_conflict', 'The draft changed since you read it.', { currentEtag: current.etag, current });
635
+ return current;
636
+ }
637
+
638
+ /** draft → in_review. The definition must be valid. */
639
+ function submit({ id, scope } = {}, { actor = 'owner', expectedEtag = null, note = null } = {}) {
640
+ const found = require(id, scope);
641
+ const current = requireDraft(found, expectedEtag);
642
+ const next = move(current, 'in_review', actor);
643
+ saveDraft(found.id, found.scope, next, { review: { submittedAt: stamp(), submittedBy: normalizeAgentDefinition({ author: actor }).author, ...(note ? { note: String(note).slice(0, 2000) } : {}) } });
644
+ return draftAnswer(found, next, 'submitted');
645
+ }
646
+
647
+ /** in_review → draft: the owner asks for changes, or the author takes it back to edit. */
648
+ function requestChanges({ id, scope } = {}, { actor = 'owner', expectedEtag = null, note = null } = {}) {
649
+ const found = require(id, scope);
650
+ const current = requireDraft(found, expectedEtag);
651
+ const next = move(current, 'draft', actor);
652
+ saveDraft(found.id, found.scope, next, { review: { ...(found.draft.review || {}), returnedAt: stamp(), returnedBy: normalizeAgentDefinition({ author: actor }).author, ...(note ? { returnNote: String(note).slice(0, 2000) } : {}) } });
653
+ return draftAnswer(found, next, 'changes_requested');
654
+ }
655
+
656
+ /**
657
+ * The owner approves the draft: it becomes a stored revision, and the agent's current one. A draft the owner
658
+ * did not send to review first is sent and approved in one step. `expectedEtag` is required: an approval belongs
659
+ * to the content that was looked at.
660
+ * @throws 403 `approval_requires_owner`, 428 `etag_required`, 409 `etag_conflict`, 400 `not_valid`
661
+ */
662
+ function approve({ id, scope } = {}, { actor = 'owner', expectedEtag = null, note = null } = {}) {
663
+ const found = require(id, scope);
664
+ if (typeof expectedEtag !== 'string' || !ETAG_RE.test(expectedEtag)) throw new AgentRegistryError(428, 'etag_required', 'Name the etag of the revision you are approving (If-Match, or expectedEtag).', { currentEtag: found.draft?.definition?.etag || null });
665
+ let current = requireDraft(found, expectedEtag);
666
+ if (current.status === 'draft') current = move(current, 'in_review', actor);
667
+ const approved = move(current, 'approved', actor);
668
+ ensureDirs(found.id, found.scope);
669
+ writeJson(revisionPath(found.id, found.scope, approved.revision), record(approved, { review: { ...(found.draft.review || {}), decidedAt: stamp(), decision: 'approved', ...(note ? { decisionNote: String(note).slice(0, 2000) } : {}) } }), { exclusive: true });
670
+ try { unlinkSync(draftPath(found.id, found.scope)); } catch { /* load() drops the leftover */ }
671
+ announce({ action: 'approved', id: found.id, scope: found.scope, revision: approved.revision, status: 'approved' });
672
+ return { agent: detail(load(found.id, found.scope)), revision: approved, etag: approved.etag };
673
+ }
674
+
675
+ /**
676
+ * Withdraw a revision. With no `revision`: the working draft when there is one (it is kept as a withdrawn
677
+ * revision), else the current approved revision. `all`: every approved revision and the draft, which takes the
678
+ * agent out of use.
679
+ * @returns {{ agent: object, withdrawn: number[] }}
680
+ */
681
+ function withdraw({ id, scope } = {}, { revision: which = null, all = false, actor = 'owner', note = null } = {}) {
682
+ const found = require(id, scope);
683
+ const done = [];
684
+ const review = (rev) => ({ ...(rev?.review || {}), withdrawnAt: stamp(), withdrawnBy: normalizeAgentDefinition({ author: actor }).author, ...(note ? { withdrawNote: String(note).slice(0, 2000) } : {}) });
685
+ let discarded = false;
686
+ const withdrawDraft = () => {
687
+ const current = found.draft?.definition;
688
+ if (!current) return false;
689
+ const next = move(current, 'withdrawn', actor);
690
+ // A draft that never was a valid definition is not history: it is dropped, not stored as a revision.
691
+ if (!validateAgentDefinition(next, { requireMeta: true }).ok) {
692
+ try { unlinkSync(draftPath(found.id, found.scope)); } catch { /* already gone */ }
693
+ discarded = true;
694
+ return true;
695
+ }
696
+ ensureDirs(found.id, found.scope);
697
+ writeJson(revisionPath(found.id, found.scope, next.revision), record(next, { review: review(found.draft) }), { exclusive: true });
698
+ try { unlinkSync(draftPath(found.id, found.scope)); } catch { /* load() drops the leftover */ }
699
+ done.push(next.revision);
700
+ return true;
701
+ };
702
+ const withdrawStored = (rev) => {
703
+ if (!rev?.definition) throw new AgentRegistryError(404, 'revision_not_found', 'There is no such revision.');
704
+ if (rev.definition.source === 'builtin') throw new AgentRegistryError(409, 'builtin_read_only', 'Bundled revisions are read-only.');
705
+ const next = move(rev.definition, 'withdrawn', actor);
706
+ // The content of a stored revision is never changed: only its status moves.
707
+ if (next.etag !== rev.definition.etag) throw new AgentRegistryError(500, 'revision_immutable', 'A stored revision cannot change its content.');
708
+ writeJson(revisionPath(found.id, found.scope, rev.number), record(next, { review: review(rev) }));
709
+ done.push(rev.number);
710
+ };
711
+ if (all) {
712
+ withdrawDraft();
713
+ for (const rev of found.revisions) if (rev.definition?.status === 'approved' && rev.definition.source !== 'builtin') withdrawStored(rev);
714
+ } else if (which === null || which === undefined) {
715
+ if (!withdrawDraft()) {
716
+ if (!found.approved) throw new AgentRegistryError(409, 'invalid_transition', 'This agent has nothing to withdraw.');
717
+ withdrawStored(found.approved);
718
+ }
719
+ } else if (which === 'draft' || Number(which) === found.draft?.definition?.revision) {
720
+ if (!withdrawDraft()) throw new AgentRegistryError(404, 'draft_not_found', 'This agent has no draft.');
721
+ } else {
722
+ withdrawStored(found.revisions.find((rev) => rev.number === Number(which)));
723
+ }
724
+ if (!done.length && !discarded) throw new AgentRegistryError(409, 'invalid_transition', 'This agent has nothing to withdraw.');
725
+ announce({ action: discarded && !done.length ? 'draft_discarded' : 'withdrawn', id: found.id, scope: found.scope, revisions: done, status: 'withdrawn' });
726
+ const left = load(found.id, found.scope);
727
+ if (!left) removeFolder(found.id, found.scope);
728
+ return { agent: left ? detail(left) : null, withdrawn: done, ...(discarded ? { discarded: true } : {}) };
729
+ }
730
+
731
+ // ── removal ──
732
+ function removeFolder(id, scope) {
733
+ const folder = agentDir(id, scope);
734
+ try { rmSync(folder, { recursive: true, force: true }); } catch { /* nothing to remove */ }
735
+ try { rmdirSync(join(dir, requireId(id))); } catch { /* another scope still holds this id */ }
736
+ }
737
+ /** Delete an agent of one scope: its draft and every revision. Runs that pinned one keep what they started with. */
738
+ function remove({ id, scope } = {}) {
739
+ const found = require(id, scope);
740
+ if (!found.draft && found.revisions.every((rev) => rev.definition?.source === 'builtin')) {
741
+ throw new AgentRegistryError(409, 'builtin_read_only', 'Bundled agents are read-only. Open a draft to customize this agent.');
742
+ }
743
+ removeFolder(found.id, found.scope);
744
+ announce({ action: 'deleted', id: found.id, scope: found.scope });
745
+ return { removed: true, id: found.id, scope: found.scope };
746
+ }
747
+
748
+ // ── diff ──
749
+ /**
750
+ * What changed between two revisions. `from` / `to`: a number, `draft` or `approved`. Defaults: `to` is the draft
751
+ * when there is one, else the current approved revision; `from` is what `to` was made over (null: a first revision).
752
+ */
753
+ function diff({ id, scope } = {}, { from = null, to = null } = {}) {
754
+ const found = require(id, scope);
755
+ const pick = (which) => {
756
+ if (which === 'draft') return found.draft?.definition || null;
757
+ if (which === 'approved' || which === 'current') return found.approved?.definition || null;
758
+ return found.revisions.find((rev) => rev.number === Number(which))?.definition || null;
759
+ };
760
+ const after = to === null || to === undefined || to === '' ? (found.draft?.definition || found.approved?.definition) : pick(to);
761
+ if (!after) throw new AgentRegistryError(404, 'revision_not_found', 'There is no such revision to compare.');
762
+ let before = null;
763
+ if (from !== null && from !== undefined && from !== '') {
764
+ before = pick(from);
765
+ if (!before) throw new AgentRegistryError(404, 'revision_not_found', 'There is no such revision to compare with.');
766
+ } else if (after.parentRevision) before = pick(after.parentRevision);
767
+ const side = (def) => (def ? { revision: def.revision, status: def.status, etag: def.etag } : null);
768
+ return { id: found.id, scope: found.scope, from: side(before), to: side(after), ...diffDefinitions(before, after) };
769
+ }
770
+
771
+ // ── export / import ──
772
+ /**
773
+ * A JSON bundle of agents: for each, its current approved revision and its draft. `agents`: the ones to take
774
+ * ({ id, scope }), default every agent.
775
+ */
776
+ function exportBundle({ agents = null } = {}) {
777
+ const chosen = Array.isArray(agents) ? agents.map((key) => require(key.id, key.scope)) : everyAgent();
778
+ return {
779
+ format: AGENT_BUNDLE_FORMAT, version: AGENT_BUNDLE_VERSION, exportedAt: stamp(),
780
+ agents: chosen.map((found) => ({
781
+ id: found.id, scope: found.scope,
782
+ approved: found.approved?.definition || null,
783
+ draft: found.draft?.definition || null,
784
+ })).filter((entry) => entry.approved || entry.draft),
785
+ };
786
+ }
787
+
788
+ /**
789
+ * Take the agents of a bundle in, each as a draft: nothing a bundle says is approved here. For an agent that
790
+ * exists, the content becomes its draft over the current revision (`unchanged` when it is the same content).
791
+ * @param {object} bundle an export, a list of definitions, or one definition
792
+ * @param {object} [options]
793
+ * @param {object|string} [options.author]
794
+ * @param {object} [options.scope] put every agent in this scope instead of the one the bundle names
795
+ * @param {boolean} [options.replaceDrafts] replace a draft that is already there (default: skip that agent)
796
+ * @param {'approved'|'draft'} [options.prefer] which side of an entry to take when it has both (default approved)
797
+ * @returns {{ results: { id, scope, action, reason?, errors?, revision?, etag? }[], imported: number }}
798
+ */
799
+ function importBundle(bundle, { author = 'owner', scope: forcedScope = null, replaceDrafts = false, prefer = 'approved' } = {}) {
800
+ let entries;
801
+ if (Array.isArray(bundle)) entries = bundle;
802
+ else if (isObject(bundle) && Array.isArray(bundle.agents)) {
803
+ if (bundle.format !== undefined && bundle.format !== AGENT_BUNDLE_FORMAT) throw new AgentRegistryError(400, 'invalid_bundle', `Not a SynaBun agents bundle (format "${String(bundle.format).slice(0, 40)}").`);
804
+ if (Number(bundle.version) > AGENT_BUNDLE_VERSION) throw new AgentRegistryError(400, 'bundle_newer', 'This bundle was made by a newer SynaBun.');
805
+ entries = bundle.agents;
806
+ } else if (isObject(bundle) && (bundle.provider !== undefined || bundle.name !== undefined)) entries = [bundle];
807
+ else throw new AgentRegistryError(400, 'invalid_bundle', 'Send a bundle ({ format: "synabun-agents", agents: [...] }), a list of definitions, or one definition.');
808
+ if (entries.length > REGISTRY_LIMITS.bundleAgents) throw new AgentRegistryError(413, 'too_large', `A bundle holds at most ${REGISTRY_LIMITS.bundleAgents} agents.`);
809
+ const target = forcedScope ? scopeOf(forcedScope) : null;
810
+ const results = [];
811
+ for (const entry of entries) {
812
+ const source = isObject(entry) && (isObject(entry.approved) || isObject(entry.draft))
813
+ ? (prefer === 'draft' ? (entry.draft || entry.approved) : (entry.approved || entry.draft))
814
+ : entry;
815
+ if (!isObject(source)) { results.push({ id: null, scope: null, action: 'invalid', reason: 'not a definition' }); continue; }
816
+ const content = contentInput(source);
817
+ let scope;
818
+ try { scope = target || scopeOf(content.scope); } catch (error) { results.push({ id: String(content.id || '').slice(0, 80) || null, scope: null, action: 'invalid', reason: error.message }); continue; }
819
+ const candidate = normalizeAgentDefinition({ ...content, scope });
820
+ const checked = validateAgentDefinition({ ...contentOf(candidate) }, validationOptions());
821
+ if (!checked.ok) { results.push({ id: candidate.id || null, scope, action: 'invalid', errors: checked.errors }); continue; }
822
+ const found = load(candidate.id, scope);
823
+ if (!found) {
824
+ const made = create(contentOf(candidate), { author });
825
+ results.push({ id: candidate.id, scope, action: 'created', revision: made.draft.revision, etag: made.etag });
826
+ continue;
827
+ }
828
+ if (found.approved?.definition.etag === candidate.etag && !found.draft) { results.push({ id: candidate.id, scope, action: 'unchanged', revision: found.approved.definition.revision, etag: candidate.etag }); continue; }
829
+ if (found.draft?.definition) {
830
+ if (found.draft.definition.etag === candidate.etag) { results.push({ id: candidate.id, scope, action: 'unchanged', revision: found.draft.definition.revision, etag: candidate.etag }); continue; }
831
+ if (!replaceDrafts) { results.push({ id: candidate.id, scope, action: 'skipped', reason: 'draft_exists' }); continue; }
832
+ if (found.draft.definition.status !== 'draft') { results.push({ id: candidate.id, scope, action: 'skipped', reason: 'in_review' }); continue; }
833
+ }
834
+ const definition = createDraft(contentOf(candidate), { now: stamp(), base: draftBase(found), revision: nextRevision(found), author });
835
+ saveDraft(found.id, found.scope, definition);
836
+ announce({ action: 'draft_saved', id: found.id, scope: found.scope, revision: definition.revision, status: 'draft' });
837
+ results.push({ id: candidate.id, scope, action: 'drafted', revision: definition.revision, etag: definition.etag });
838
+ }
839
+ return { results, imported: results.filter((row) => row.action === 'created' || row.action === 'drafted').length };
840
+ }
841
+
842
+ /**
843
+ * A Claude Code agent file as a draft (parseClaudeAgent). For an agent that already exists in that scope the
844
+ * content becomes its draft, unless one is already there (409 `draft_exists`; `replaceDraft` replaces a draft).
845
+ */
846
+ function importClaudeAgent(markdown, { fileName = '', id = null, scope = null, author = 'owner', replaceDraft = false } = {}) {
847
+ const { content, notes } = parseClaudeAgent(markdown, { fileName, id, scope });
848
+ const found = load(content.id, content.scope);
849
+ if (!found) return { ...create(content, { author }), notes, action: 'created' };
850
+ if (found.draft?.definition && (!replaceDraft || found.draft.definition.status !== 'draft')) {
851
+ throw new AgentRegistryError(409, 'draft_exists', `Agent "${content.id}" already has a draft; change that one, or pass another id.`, { currentEtag: found.draft.definition.etag });
852
+ }
853
+ const definition = createDraft(content, { now: stamp(), base: draftBase(found), revision: nextRevision(found), author });
854
+ saveDraft(found.id, found.scope, definition);
855
+ return { ...draftAnswer(found, definition, 'draft_saved'), notes, action: 'drafted' };
856
+ }
857
+
858
+ /** A copy of an agent's newest content as a new draft under another id or in another scope. */
859
+ function copy({ id, scope } = {}, { id: newId = null, scope: newScope = null, author = 'owner' } = {}) {
860
+ const found = require(id, scope);
861
+ const source = found.draft?.definition || draftBase(found);
862
+ return create({ ...contentOf(source), id: newId || found.id, scope: newScope ? scopeOf(newScope) : found.scope }, { author });
863
+ }
864
+
865
+ /** How much is stored (for a status line and the tests). */
866
+ function stats() {
867
+ const all = everyAgent();
868
+ let bytes = 0;
869
+ const walk = (folder) => { let names = []; try { names = readdirSync(folder); } catch { return; } for (const name of names) { const path = join(folder, name); let st; try { st = statSync(path); } catch { continue; } if (st.isDirectory()) walk(path); else bytes += st.size; } };
870
+ walk(dir);
871
+ return { agents: all.length, approved: all.filter((found) => found.approved).length, drafts: all.filter((found) => found.draft).length, bytes };
872
+ }
873
+
874
+ return {
875
+ dir,
876
+ list, get, has, scopesOf, revision, revisions,
877
+ builtinIdForClass: (taskClass) => classAgents.get(taskClass) || null,
878
+ create, openDraft, updateDraft, discardDraft, copy,
879
+ submit, requestChanges, approve, withdraw, remove,
880
+ diff, exportBundle, importBundle, importClaudeAgent,
881
+ validate: (input) => validateAgentDefinition(input, validationOptions()),
882
+ lint: (input, options) => lintAgentDefinition(input, options),
883
+ stats,
884
+ };
885
+ }