synabun 2.3.0 → 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 (367) hide show
  1. package/CHANGELOG.md +38 -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 +1174 -47
  103. package/neural-interface/i18n/pt-BR.json +1174 -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-profiles.js +1 -1
  135. package/neural-interface/lib/browser-tool-policy.js +1 -1
  136. package/neural-interface/lib/claude-account-links.js +301 -0
  137. package/neural-interface/lib/claude-accounts.js +45 -20
  138. package/neural-interface/lib/claude-agent-bridge.js +142 -10
  139. package/neural-interface/lib/claude-model-catalog.js +6 -0
  140. package/neural-interface/lib/claude-panel-session.js +33 -0
  141. package/neural-interface/lib/cli-install-api.js +23 -0
  142. package/neural-interface/lib/codex-accounts.js +67 -24
  143. package/neural-interface/lib/coordination/README.md +384 -0
  144. package/neural-interface/lib/coordination/service.js +563 -0
  145. package/neural-interface/lib/coordination/store.js +1138 -0
  146. package/neural-interface/lib/db.js +22 -1
  147. package/neural-interface/lib/editor-completion-opencode.js +4 -3
  148. package/neural-interface/lib/effort-levels.js +10 -1
  149. package/neural-interface/lib/maritaca/opencode-proxy.js +7 -2
  150. package/neural-interface/lib/maritaca/opencode.js +35 -0
  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 +219 -7
  157. package/neural-interface/lib/native-loop-runtime.js +24 -1
  158. package/neural-interface/lib/opencode-build-preflight.js +116 -0
  159. package/neural-interface/lib/opencode-launch-error.js +13 -0
  160. package/neural-interface/lib/opencode-native-boundary.js +800 -84
  161. package/neural-interface/lib/opencode-serve-probe.js +426 -0
  162. package/neural-interface/lib/opencode-serve-records.js +14 -9
  163. package/neural-interface/lib/opencode-serve-scan.js +108 -0
  164. package/neural-interface/lib/page-session.js +1 -1
  165. package/neural-interface/lib/peer-identity.js +60 -21
  166. package/neural-interface/lib/process-identity.js +235 -7
  167. package/neural-interface/lib/request-gate.js +3 -0
  168. package/neural-interface/lib/screenshot-location.js +33 -0
  169. package/neural-interface/lib/skills/creation.js +1 -1
  170. package/neural-interface/lib/skills/known-bridge-digests.json +40 -0
  171. package/neural-interface/lib/studio-attention.js +56 -0
  172. package/neural-interface/lib/teams/README.md +382 -0
  173. package/neural-interface/lib/teams/api.js +287 -0
  174. package/neural-interface/lib/teams/brief.js +185 -0
  175. package/neural-interface/lib/teams/claims.js +315 -0
  176. package/neural-interface/lib/teams/git.js +293 -0
  177. package/neural-interface/lib/teams/index.js +122 -0
  178. package/neural-interface/lib/teams/integration.js +580 -0
  179. package/neural-interface/lib/teams/landing.js +184 -0
  180. package/neural-interface/lib/teams/recovery.js +256 -0
  181. package/neural-interface/lib/teams/scheduler.js +1474 -0
  182. package/neural-interface/lib/teams/schema.js +559 -0
  183. package/neural-interface/lib/teams/state.js +181 -0
  184. package/neural-interface/lib/teams/test-runner.js +86 -0
  185. package/neural-interface/lib/teams/test-sandbox.js +99 -0
  186. package/neural-interface/lib/teams/worktrees.js +757 -0
  187. package/neural-interface/lib/tool-permission-choices.js +226 -0
  188. package/neural-interface/lib/whatsapp/cards.js +24 -10
  189. package/neural-interface/lib/worker-confinement.js +206 -6
  190. package/neural-interface/lib/worker-mcp-channel.js +38 -1
  191. package/neural-interface/package-lock.json +4 -2
  192. package/neural-interface/package.json +3 -1
  193. package/neural-interface/public/extension-setup.html +107 -0
  194. package/neural-interface/public/index.html +52 -12
  195. package/neural-interface/public/shared/agent-runtime-options.js +3 -1
  196. package/neural-interface/public/shared/agents/studio/ax-agent-view.js +614 -0
  197. package/neural-interface/public/shared/agents/studio/ax-api.js +198 -0
  198. package/neural-interface/public/shared/agents/studio/ax-create-view.js +221 -0
  199. package/neural-interface/public/shared/agents/studio/ax-diff.js +143 -0
  200. package/neural-interface/public/shared/agents/studio/ax-editor-view.js +392 -0
  201. package/neural-interface/public/shared/agents/studio/ax-export-view.js +94 -0
  202. package/neural-interface/public/shared/agents/studio/ax-form.js +191 -0
  203. package/neural-interface/public/shared/agents/studio/ax-icons.js +87 -0
  204. package/neural-interface/public/shared/agents/studio/ax-library-view.js +158 -0
  205. package/neural-interface/public/shared/agents/studio/ax-library.js +162 -0
  206. package/neural-interface/public/shared/agents/studio/ax-main.js +712 -0
  207. package/neural-interface/public/shared/agents/studio/ax-native-export.js +35 -0
  208. package/neural-interface/public/shared/agents/studio/ax-options.js +198 -0
  209. package/neural-interface/public/shared/agents/studio/ax-review-view.js +175 -0
  210. package/neural-interface/public/shared/agents/studio/ax-revisions-view.js +189 -0
  211. package/neural-interface/public/shared/agents/studio/ax-runs-view.js +202 -0
  212. package/neural-interface/public/shared/agents/studio/ax-runs.js +82 -0
  213. package/neural-interface/public/shared/agents/studio/ax-teams-view.js +256 -0
  214. package/neural-interface/public/shared/agents/studio/ax-teams.js +200 -0
  215. package/neural-interface/public/shared/agents/studio/ax-templates.js +50 -0
  216. package/neural-interface/public/shared/agents/studio/ax-ui.js +194 -0
  217. package/neural-interface/public/shared/agents/studio/ax-views.js +170 -0
  218. package/neural-interface/public/shared/agy/agy-panel.js +142 -28
  219. package/neural-interface/public/shared/agy/agy-styles.js +25 -5
  220. package/neural-interface/public/shared/assistant/asst-account-menu.js +13 -13
  221. package/neural-interface/public/shared/assistant/asst-ask-styles.js +2 -3
  222. package/neural-interface/public/shared/assistant/asst-brain-picker.js +91 -9
  223. package/neural-interface/public/shared/assistant/asst-control.js +3 -0
  224. package/neural-interface/public/shared/assistant/asst-interaction-hold.js +99 -0
  225. package/neural-interface/public/shared/assistant/asst-limit-dismissals.js +111 -0
  226. package/neural-interface/public/shared/assistant/asst-limit-dock.js +37 -3
  227. package/neural-interface/public/shared/assistant/asst-limit-wait.js +30 -7
  228. package/neural-interface/public/shared/assistant/asst-panel.js +177 -30
  229. package/neural-interface/public/shared/assistant/asst-rack-styles.js +15 -8
  230. package/neural-interface/public/shared/assistant/asst-render.js +36 -6
  231. package/neural-interface/public/shared/assistant/asst-route.js +78 -12
  232. package/neural-interface/public/shared/assistant/asst-routes-editor.js +148 -70
  233. package/neural-interface/public/shared/assistant/asst-roving.js +17 -1
  234. package/neural-interface/public/shared/assistant/asst-scene-styles.js +7 -2
  235. package/neural-interface/public/shared/assistant/asst-scenes.js +12 -1
  236. package/neural-interface/public/shared/assistant/asst-sidepanel.js +12 -2
  237. package/neural-interface/public/shared/assistant/asst-state.js +66 -1
  238. package/neural-interface/public/shared/assistant/asst-styles.js +98 -44
  239. package/neural-interface/public/shared/assistant/route-identity.js +16 -0
  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 +33 -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/opencode-verify-view.js +175 -0
  279. package/neural-interface/public/shared/schedules-view.js +2 -2
  280. package/neural-interface/public/shared/session-project-items.js +11 -0
  281. package/neural-interface/public/shared/settings/settings-ai-browser.js +119 -0
  282. package/neural-interface/public/shared/settings/settings-browser-extension.js +446 -0
  283. package/neural-interface/public/shared/settings/settings-ia.js +4 -2
  284. package/neural-interface/public/shared/settings/settings-morelogin-cooldown.js +63 -0
  285. package/neural-interface/public/shared/settings/settings-tool-permissions.js +70 -0
  286. package/neural-interface/public/shared/sidepanel-lazy.js +40 -0
  287. package/neural-interface/public/shared/sidepanel-session-status.js +8 -14
  288. package/neural-interface/public/shared/sidepanel-shown.js +73 -0
  289. package/neural-interface/public/shared/storage.js +6 -1
  290. package/neural-interface/public/shared/studio-attention.js +83 -0
  291. package/neural-interface/public/shared/styles.css +713 -61
  292. package/neural-interface/public/shared/term-browser-tabs.js +34 -0
  293. package/neural-interface/public/shared/transcript-rows.js +334 -0
  294. package/neural-interface/public/shared/tray-auto-close.js +106 -0
  295. package/neural-interface/public/shared/ui-agents.js +97 -0
  296. package/neural-interface/public/shared/ui-antigravity-panel.js +16 -14
  297. package/neural-interface/public/shared/ui-automation-studio.js +3 -3
  298. package/neural-interface/public/shared/ui-claude-panel.js +162 -95
  299. package/neural-interface/public/shared/ui-code-copy.js +256 -0
  300. package/neural-interface/public/shared/ui-codex-panel.js +14 -10
  301. package/neural-interface/public/shared/ui-context-menu.js +1 -1
  302. package/neural-interface/public/shared/ui-file-explorer.js +2 -3
  303. package/neural-interface/public/shared/ui-games.js +1 -1
  304. package/neural-interface/public/shared/ui-loading.js +12 -1
  305. package/neural-interface/public/shared/ui-maritaca-panel.js +12 -11
  306. package/neural-interface/public/shared/ui-menubar.js +23 -0
  307. package/neural-interface/public/shared/ui-native-loop-router.js +1 -1
  308. package/neural-interface/public/shared/ui-navbar.js +15 -9
  309. package/neural-interface/public/shared/ui-opencode-panel-v2.js +13 -11
  310. package/neural-interface/public/shared/ui-opencode-verify.js +120 -0
  311. package/neural-interface/public/shared/ui-schedules-studio.js +3 -3
  312. package/neural-interface/public/shared/ui-scroll-follow.js +39 -0
  313. package/neural-interface/public/shared/ui-sessions.js +3 -3
  314. package/neural-interface/public/shared/ui-settings-entry.js +55 -0
  315. package/neural-interface/public/shared/ui-settings.js +372 -402
  316. package/neural-interface/public/shared/ui-sidepanel-layout.js +44 -25
  317. package/neural-interface/public/shared/ui-sidepanel-session-entry.js +22 -9
  318. package/neural-interface/public/shared/ui-sidepanel-sessions.js +10 -2
  319. package/neural-interface/public/shared/ui-sidepanel-tray.js +36 -41
  320. package/neural-interface/public/shared/ui-sidepanel-windows.js +14 -1
  321. package/neural-interface/public/shared/ui-styleguide.js +10 -2
  322. package/neural-interface/public/shared/ui-sync.js +5 -0
  323. package/neural-interface/public/shared/ui-terminal.js +13 -9
  324. package/neural-interface/public/shared/ui-tooltip.js +28 -7
  325. package/neural-interface/public/shared/ui-topright-overflow.js +26 -4
  326. package/neural-interface/public/shared/ui-tray-columns.js +375 -0
  327. package/neural-interface/public/shared/ui-whiteboard.js +51 -6
  328. package/neural-interface/public/shared/ui-worker-end.js +28 -1
  329. package/neural-interface/public/shared/ui-workspaces.js +13 -0
  330. package/neural-interface/public/shared/window-keys.js +71 -0
  331. package/neural-interface/public/variant/2d/main.js +2 -0
  332. package/neural-interface/public/variant/3d/app.js +620 -0
  333. package/neural-interface/public/variant/3d/boot-reveal.js +47 -0
  334. package/neural-interface/public/variant/3d/main.js +21 -544
  335. package/neural-interface/public/variant/3d/map-controls.js +4 -2
  336. package/neural-interface/public/vendor/fonts/fonts.css +508 -0
  337. package/neural-interface/public/vendor/fonts/inter-OFL.txt +93 -0
  338. package/neural-interface/public/vendor/fonts/inter-cyrillic-ext.woff2 +0 -0
  339. package/neural-interface/public/vendor/fonts/inter-cyrillic.woff2 +0 -0
  340. package/neural-interface/public/vendor/fonts/inter-greek-ext.woff2 +0 -0
  341. package/neural-interface/public/vendor/fonts/inter-greek.woff2 +0 -0
  342. package/neural-interface/public/vendor/fonts/inter-latin-ext.woff2 +0 -0
  343. package/neural-interface/public/vendor/fonts/inter-latin.woff2 +0 -0
  344. package/neural-interface/public/vendor/fonts/inter-vietnamese.woff2 +0 -0
  345. package/neural-interface/public/vendor/fonts/jetbrains-mono-OFL.txt +93 -0
  346. package/neural-interface/public/vendor/fonts/jetbrains-mono-cyrillic-ext.woff2 +0 -0
  347. package/neural-interface/public/vendor/fonts/jetbrains-mono-cyrillic.woff2 +0 -0
  348. package/neural-interface/public/vendor/fonts/jetbrains-mono-greek.woff2 +0 -0
  349. package/neural-interface/public/vendor/fonts/jetbrains-mono-latin-ext.woff2 +0 -0
  350. package/neural-interface/public/vendor/fonts/jetbrains-mono-latin.woff2 +0 -0
  351. package/neural-interface/public/vendor/fonts/jetbrains-mono-vietnamese.woff2 +0 -0
  352. package/neural-interface/public/vendor/fonts/manifest.json +142 -0
  353. package/neural-interface/public/vendor/fonts/space-grotesk-OFL.txt +93 -0
  354. package/neural-interface/public/vendor/fonts/space-grotesk-latin-ext.woff2 +0 -0
  355. package/neural-interface/public/vendor/fonts/space-grotesk-latin.woff2 +0 -0
  356. package/neural-interface/public/vendor/fonts/space-grotesk-vietnamese.woff2 +0 -0
  357. package/neural-interface/scripts/boot-graph.mjs +270 -0
  358. package/neural-interface/scripts/vendor-fonts.mjs +124 -0
  359. package/neural-interface/server.js +1164 -157
  360. package/npm-shrinkwrap.json +2 -2
  361. package/package.json +3 -1
  362. package/skills/agent-forge/SKILL.md +182 -0
  363. package/skills/agent-forge/evals/evals.json +56 -0
  364. package/skills/agent-forge/references/definition-fields.md +61 -0
  365. package/skills/agent-forge/references/examples.md +105 -0
  366. package/skills/agent-forge/references/instructions.md +51 -0
  367. package/skills/agent-forge/references/review-and-export.md +84 -0
@@ -0,0 +1,591 @@
1
+ // ── /api/agents-studio/v1: the agent registry over HTTP (Agents system, phase P1) ──
2
+ // The routes Agents Studio (the page) and the agent-forge workflow use; lib/agents/registry.js keeps the
3
+ // definitions and lib/agents/resolve.js turns one into a run. The older /api/agents routes (the isolated agent
4
+ // processes of server.js) are another thing and are not touched.
5
+ //
6
+ // Who may do what (the tiers of lib/skills/api-v2.js, which this file follows):
7
+ //
8
+ // read the owner, the Assistant and agents: the library, one agent, its revisions, a diff, an export, what a
9
+ // ref would run as. Never a guest (an agent's instructions are the owner's).
10
+ // draft the owner (from SynaBun's own page) and agents (the Assistant by its brain's launch credential, a
11
+ // worker by its run's proof): a new draft, a change to one, a copy, an import, sending a draft to
12
+ // review, taking one's own back or withdrawing it. What the Assistant or an agent makes waits in
13
+ // review; neither may touch a draft the owner is working on.
14
+ // owner the owner, from SynaBun's own page only: approving, asking for changes, withdrawing an approved
15
+ // revision, deleting an agent, a test run (which runs a draft, so it is an approval of a kind). A
16
+ // request with an agent's headers is refused here (403 UI_ONLY) whatever else it says, as is a guest,
17
+ // another site's page, a request without the page's X-SynaBun-UI header, or one without this boot's
18
+ // page secret cookie (lib/page-session.js, 403 PAGE_SECRET_REQUIRED): the gating of the Skills
19
+ // Service's installs and of the Test density setting.
20
+ //
21
+ // An agent is named by its id in the path and its scope in the query: `?scope=project&project=<absolute path>`
22
+ // (nothing: the global library). Ids are checked by shape before anything is looked up; no id is ever a path.
23
+ // Errors are JSON `{ ok: false, error, code, … }`: 400 for what the request says, 403 for who sent it, 404, 409
24
+ // for a conflict (with the current etag), 413 for a limit, 428 when an etag is missing.
25
+
26
+ import { sendGuardError } from './http-guards.js';
27
+ import { registerTeamStudioRoutes } from './teams/api.js'; // agents-p4
28
+ import { sharedTeamScheduler } from './teams/scheduler.js'; // agents-p4
29
+ import { principalOf } from './skills/api-v2.js';
30
+ import { scopeOf } from './agents/registry.js';
31
+ import {
32
+ AGENT_CAPABILITIES, AGENT_LIMITS, AGENT_PERMISSION_POLICIES, AGENT_PROVIDERS, AGENT_STATUSES, AGENT_TASK_CLASSES,
33
+ dispatchFields, lintAgentDefinition, sameScope,
34
+ } from './agents/schema.js';
35
+ // agents-p6: agent-forge (the guide, the catalog a definition is filled from, the privilege check) and native export
36
+ import { AgentRegistryError } from './agents/registry.js';
37
+ import { privilegeDelta, privilegesOf } from './agents/schema.js';
38
+ import { exportNative, importNative, nativeFormats } from './agents/native-export.js';
39
+
40
+ export const AGENTS_STUDIO_BASE = '/api/agents-studio/v1';
41
+ export const AGENTS_STUDIO_VERSION = 1;
42
+ /** What this server's routes can do: the page shows a feature only while it is listed (public/ reloads before lib/). */
43
+ export const AGENTS_STUDIO_CAPABILITIES = Object.freeze([
44
+ 'agents', 'drafts', 'validate', 'lint', 'reviews', 'revisions', 'diff', 'copy', 'export', 'import', 'import-claude-agent', 'resolve', 'runs', 'test-run',
45
+ 'teams', // agents-p4: GET /teams, GET /teams/:id, POST /teams/:id/land, POST /teams/:id/discard
46
+ // agents-p6: agent-forge and native export (the routes of the agents-p6 block below)
47
+ 'guide', 'forge-catalog', 'checks', 'native-export', 'native-import',
48
+ ]);
49
+ /** The work time of a test run when the request names none (the dispatcher's own minimum). */
50
+ export const TEST_RUN_MINUTES = 20;
51
+ export const TEST_RUN_TAG = 'agent-test';
52
+
53
+ const ID_RE = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
54
+ const ETAG_RE = /^sha256:[0-9a-f]{64}$/;
55
+ const isObject = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
56
+ const text = (value, max = 4000) => (typeof value === 'string' ? value.slice(0, max) : '');
57
+
58
+ function fail(res, err) {
59
+ const status = Number.isInteger(err?.status) && err.status >= 400 && err.status < 600 ? err.status : 500;
60
+ const body = { ok: false, error: status >= 500 ? `The agents service failed: ${err?.message || err}` : (err?.message || String(err)) };
61
+ if (typeof err?.code === 'string' && !/^E[A-Z]+$/.test(err.code)) body.code = err.code;
62
+ for (const key of ['errors', 'currentEtag', 'current', 'found', 'problems', 'field', 'revisionStatus', 'agentRef', 'suggestions', 'diagnostics']) if (err?.[key] !== undefined) body[key] = err[key];
63
+ return res.status(status).json(body);
64
+ }
65
+
66
+ /** The etag a request names: `If-Match` (quoted or not) or `expectedEtag` in the body. null when it names none. */
67
+ function expectedEtagOf(req) {
68
+ const header = typeof req.headers['if-match'] === 'string' ? req.headers['if-match'].trim().replace(/^W\//, '').replace(/^"|"$/g, '') : '';
69
+ const named = header || (typeof req.body?.expectedEtag === 'string' ? req.body.expectedEtag.trim() : '');
70
+ return ETAG_RE.test(named) ? named : null;
71
+ }
72
+
73
+ /** Who made (or is changing) a revision, as the contract's author: { kind, ref }. */
74
+ export function authorOf(principal) {
75
+ if (principal?.kind === 'assistant') return { kind: 'assistant', ref: principal.assistantSessionId || principal.terminal || null };
76
+ if (principal?.kind === 'agent') return { kind: 'agent', ref: principal.terminal || null };
77
+ return { kind: 'owner', ref: null };
78
+ }
79
+
80
+ /**
81
+ * May this caller change that draft? The owner changes any. The Assistant changes what it or an agent made; an
82
+ * agent only what it made itself. Neither changes a draft the owner is working on.
83
+ */
84
+ export function mayEditDraft(principal, draftAuthor) {
85
+ if (principal?.kind === 'owner') return true;
86
+ const author = isObject(draftAuthor) ? draftAuthor : { kind: 'owner', ref: null };
87
+ if (author.kind === 'owner' || author.kind === 'system') return false;
88
+ if (principal?.kind === 'assistant') return true;
89
+ return principal?.kind === 'agent' && author.kind === 'agent' && !!principal.terminal && author.ref === principal.terminal;
90
+ }
91
+
92
+ /** One run of an agent, as the list of its runs shows it. */
93
+ function runRow(run) {
94
+ return {
95
+ runId: run.runId, title: run.title || null, state: run.state, status: run.status || null, outcome: run.outcome || null,
96
+ summary: text(run.lastResult?.summary || '', 600) || null,
97
+ provider: run.provider || null, model: run.model || null, effort: run.effort || null, capability: run.capability || null,
98
+ agentRef: run.agentRef || null, agentRevision: run.agentRevision ?? null, test: run.agentPin?.test === true,
99
+ corrections: Array.isArray(run.agentPin?.corrections) ? run.agentPin.corrections : [],
100
+ assistantSessionId: run.assistantSessionId || null, cwd: run.cwd || null, project: run.project || null,
101
+ createdAt: run.createdAt || null, startedAt: run.startedAt || null, finishedAt: run.finishedAt || null,
102
+ elapsedMs: run.elapsedMs ?? null, costUsd: run.costUsd ?? 0, active: run.active === true,
103
+ };
104
+ }
105
+
106
+ /**
107
+ * @param {object} app express app
108
+ * @param {object} o
109
+ * @param {object} o.registry lib/agents/registry.js
110
+ * @param {object} o.resolver lib/agents/resolve.js createAgentResolver
111
+ * @param {() => object|null} [o.dispatcher] the Assistant's dispatcher (the runs of an agent, a test run)
112
+ * @param {(req) => boolean} [o.isGuestRequest]
113
+ * @param {Function} [o.ownerGuard] lib/http-guards.js ownerRouteGuard(…) of this server (Host, Origin, guests)
114
+ * @param {{ verify(req): boolean, require(req, res, next) }} [o.pageSession] lib/page-session.js: the owner's writes
115
+ * carry this boot's page secret
116
+ * @param {(req) => string|null} [o.assistantOf] the Assistant session a request's brain credential belongs to
117
+ * @param {(req) => ({ status, code, error }|null)} [o.terminalRefusal] an agent's pin counts only with its proof
118
+ * @param {() => { path: string, label?: string }[]} [o.projects] the registered projects (for the page's scope picker)
119
+ * @param {(definition: object) => object} [o.lintContext] what the host knows, for the softer checks:
120
+ * { knownSkills, knownModels, knownCategories, knownColorTokens } (lib/agents/schema.js lintAgentDefinition)
121
+ * @param {object|null} [o.forge] agents-p6: lib/agents/forge-host.js createAgentForgeHost(…): the agent-forge guide,
122
+ * the catalog a definition is filled from, a Claude Code agent file read by its path, and where a native export
123
+ * is written. Without it the agent-forge routes answer 503 `FORGE_UNAVAILABLE`.
124
+ */
125
+ export function registerAgentsStudioRoutes(app, {
126
+ registry, resolver, dispatcher = () => null, isGuestRequest = null, ownerGuard = null, pageSession = null,
127
+ assistantOf = null, terminalRefusal = null, projects = () => [], lintContext = null,
128
+ // agents-p4: the team scheduler (lib/teams/scheduler.js), or what returns it. Default: the one server.js shares.
129
+ teams = sharedTeamScheduler,
130
+ forge = null, // agents-p6
131
+ } = {}) {
132
+ if (!registry || !resolver) throw new Error('registerAgentsStudioRoutes needs { registry, resolver }');
133
+ const route = (method, path, ...handlers) => app[method](`${AGENTS_STUDIO_BASE}${path}`, ...handlers);
134
+ const safe = (fn) => async (req, res) => { try { await fn(req, res); } catch (err) { fail(res, err); } };
135
+
136
+ // ── who is asking ──
137
+ const refusedPin = (req, res) => {
138
+ let refused = null;
139
+ try { refused = typeof terminalRefusal === 'function' ? terminalRefusal(req) : null; } catch { refused = { status: 403, code: 'TERMINAL_TOKEN_INVALID', error: 'The run this request names could not be checked.' }; }
140
+ if (!refused) return false;
141
+ sendGuardError(res, Number(refused.status) || 403, String(refused.code || 'TERMINAL_TOKEN_INVALID'), String(refused.error || 'This request names a run it cannot prove it is.'));
142
+ return true;
143
+ };
144
+ const json = (req, res, next) => {
145
+ if (String(req.headers['sec-fetch-site'] || '').toLowerCase() === 'cross-site') return sendGuardError(res, 403, 'CROSS_SITE', 'Cross-site requests are refused.');
146
+ const hasBody = Number(req.headers['content-length'] || 0) > 0 || req.headers['transfer-encoding'] !== undefined;
147
+ if (hasBody && typeof req.is === 'function' && !req.is('application/json')) return sendGuardError(res, 415, 'UNSUPPORTED_MEDIA_TYPE', 'Send JSON (Content-Type: application/json).');
148
+ if (req.body !== undefined && req.body !== null && (typeof req.body !== 'object' || Array.isArray(req.body))) return res.status(400).json({ ok: false, error: 'The body is a JSON object.', code: 'invalid_body' });
149
+ next();
150
+ };
151
+ /** The owner's own page: no agent header, the page's header, this boot's page secret, the owner route guard. */
152
+ const ownerPage = (req, res, next) => {
153
+ if (req.headers['x-synabun-ui'] !== '1') return sendGuardError(res, 403, 'UI_HEADER_REQUIRED', 'Send the X-SynaBun-UI: 1 header.');
154
+ if (pageSession && !pageSession.verify(req)) return pageSession.require(req, res, next);
155
+ return ownerGuard ? ownerGuard(req, res, next) : next();
156
+ };
157
+ const reader = (req, res, next) => {
158
+ if (refusedPin(req, res)) return;
159
+ req.principal = principalOf(req, isGuestRequest, assistantOf);
160
+ if (req.principal.kind === 'guest') return sendGuardError(res, 403, 'GUEST_FORBIDDEN', 'Available to the owner only.');
161
+ next();
162
+ };
163
+ const writer = (req, res, next) => {
164
+ if (refusedPin(req, res)) return;
165
+ req.principal = principalOf(req, isGuestRequest, assistantOf);
166
+ if (req.principal.kind === 'guest') return sendGuardError(res, 403, 'GUEST_FORBIDDEN', 'Available to the owner only.');
167
+ // A request without an agent's headers is the owner's page only when it proves it: a local process that merely
168
+ // left the headers out is nobody.
169
+ if (req.principal.kind === 'owner') return ownerPage(req, res, next);
170
+ next();
171
+ };
172
+ const owner = (req, res, next) => {
173
+ req.principal = principalOf(req, isGuestRequest, assistantOf);
174
+ if (req.principal.kind !== 'owner') {
175
+ const guest = req.principal.kind === 'guest';
176
+ return sendGuardError(res, 403, guest ? 'GUEST_FORBIDDEN' : 'UI_ONLY', guest ? 'Available to the owner only.' : 'Approving, withdrawing, deleting and test runs are the owner\'s, from SynaBun\'s own page: send the draft to review and ask the owner to look at it in Agents.');
177
+ }
178
+ return ownerPage(req, res, next);
179
+ };
180
+
181
+ // ── what the request names ──
182
+ const idCheck = (req, res, next) => (ID_RE.test(String(req.params.id || '')) ? next() : res.status(400).json({ ok: false, error: 'Not an agent id.', code: 'invalid_id' }));
183
+ /** The scope a request names in its query: `scope=project&project=<path>`; nothing is the global library. */
184
+ const scopeFromQuery = (query = {}) => {
185
+ const kind = String(query.scope || '').trim().toLowerCase();
186
+ const project = typeof query.project === 'string' && query.project ? query.project : null;
187
+ if (kind === 'project' || (!kind && project)) return scopeOf({ kind: 'project', path: project || '' });
188
+ if (kind && kind !== 'global') return scopeOf({ kind });
189
+ return { kind: 'global' };
190
+ };
191
+ const keyOf = (req) => ({ id: req.params.id, scope: scopeFromQuery(req.query) });
192
+ const lintOf = (definition) => {
193
+ let known = {};
194
+ try { known = (typeof lintContext === 'function' ? lintContext(definition) : null) || {}; } catch { known = {}; }
195
+ return lintAgentDefinition(definition, known);
196
+ };
197
+ const withEtag = (res, etag) => { if (etag) res.set('ETag', `"${etag}"`); return res; };
198
+ const draftBody = (out) => ({ ok: true, agent: out.agent, draft: out.draft, etag: out.etag, validation: out.validation, warnings: lintOf(out.draft), ...(out.notes ? { notes: out.notes } : {}), ...(out.action ? { action: out.action } : {}) });
199
+ /** 403 unless the caller may change the draft this agent has (a caller that is making the first draft may). */
200
+ const refuseOthersDraft = (req, res, key) => {
201
+ if (req.principal.kind === 'owner') return false;
202
+ const draft = registry.revision(key, 'draft');
203
+ if (!draft || mayEditDraft(req.principal, draft.author)) return false;
204
+ sendGuardError(res, 403, 'NOT_AUTHOR', draft.author?.kind === 'owner' ? 'The owner is working on this draft: it is not an agent\'s to change.' : 'This draft was made by another agent.');
205
+ return true;
206
+ };
207
+ const dispatcherOf = () => { try { return (typeof dispatcher === 'function' ? dispatcher() : dispatcher) || null; } catch { return null; } };
208
+
209
+ // ── reading ──
210
+ route('get', '/capabilities', reader, safe(async (req, res) => {
211
+ let list = [];
212
+ try { list = (typeof projects === 'function' ? projects() : projects) || []; } catch { list = []; }
213
+ res.json({
214
+ ok: true, version: AGENTS_STUDIO_VERSION, capabilities: AGENTS_STUDIO_CAPABILITIES,
215
+ providers: AGENT_PROVIDERS, capabilityLevels: AGENT_CAPABILITIES, permissionPolicies: AGENT_PERMISSION_POLICIES,
216
+ taskClasses: AGENT_TASK_CLASSES, statuses: AGENT_STATUSES, limits: AGENT_LIMITS,
217
+ projects: list.filter((p) => p && typeof p.path === 'string' && p.path).map((p) => ({ path: p.path, label: text(p.label || '', 200) || null })).slice(0, 500),
218
+ testRun: { available: !!dispatcherOf(), minutes: TEST_RUN_MINUTES },
219
+ stats: registry.stats(),
220
+ });
221
+ }));
222
+ route('get', '/agents', reader, safe(async (req, res) => {
223
+ const q = req.query || {};
224
+ // What a run would get: the agents that can run, a project's own in place of the global one of its id.
225
+ if (q.view === 'catalog') return res.json({ ok: true, agents: resolver.runnable({ projectPath: typeof q.cwd === 'string' && q.cwd ? q.cwd : null }) });
226
+ const scope = ['global', 'project'].includes(String(q.scope || '').toLowerCase()) ? String(q.scope).toLowerCase() : 'all';
227
+ const status = typeof q.status === 'string' && q.status ? q.status.split(',').map((item) => item.trim()).filter(Boolean) : null;
228
+ res.json({ ok: true, agents: registry.list({ scope, projectPath: typeof q.project === 'string' && q.project ? q.project : null, status, q: text(q.q || '', 200) }) });
229
+ }));
230
+ route('get', '/resolve', reader, safe(async (req, res) => {
231
+ const resolved = resolver.resolve(text(req.query?.ref || '', 200), { projectPath: typeof req.query?.cwd === 'string' && req.query.cwd ? req.query.cwd : null });
232
+ res.json({ ok: true, ref: resolved.ref, requested: resolved.requested, id: resolved.id, revision: resolved.revision, etag: resolved.etag, scope: resolved.scope, name: resolved.name, fields: dispatchFields(resolved.definition) });
233
+ }));
234
+ route('get', '/export', reader, safe(async (req, res) => {
235
+ const q = req.query || {};
236
+ const scope = ['global', 'project'].includes(String(q.scope || '').toLowerCase()) ? String(q.scope).toLowerCase() : 'all';
237
+ const chosen = scope === 'all' && !q.project ? null : registry.list({ scope, projectPath: typeof q.project === 'string' && q.project ? q.project : null }).map((agent) => ({ id: agent.id, scope: agent.scope }));
238
+ res.json({ ok: true, bundle: registry.exportBundle({ agents: chosen }) });
239
+ }));
240
+ route('get', '/agents/:id', reader, idCheck, safe(async (req, res) => {
241
+ const agent = registry.get(keyOf(req));
242
+ const draft = agent.draftDefinition;
243
+ const checked = draft ? registry.validate(draft) : null;
244
+ withEtag(res, draft?.etag || agent.approvedEtag).json({ ok: true, agent, ...(draft ? { validation: { ok: checked.ok, errors: checked.errors }, warnings: lintOf(draft) } : {}) });
245
+ }));
246
+ route('get', '/agents/:id/revisions', reader, idCheck, safe(async (req, res) => res.json({ ok: true, revisions: registry.revisions(keyOf(req)) })));
247
+ route('get', '/agents/:id/revisions/:revision', reader, idCheck, safe(async (req, res) => {
248
+ const which = /^[1-9][0-9]{0,8}$/.test(req.params.revision) ? Number(req.params.revision) : ['draft', 'approved'].includes(req.params.revision) ? req.params.revision : null;
249
+ if (which === null) return res.status(400).json({ ok: false, error: 'A revision is a number, "draft" or "approved".', code: 'invalid_revision' });
250
+ registry.get(keyOf(req)); // 404 for an agent that does not exist
251
+ const definition = registry.revision(keyOf(req), which);
252
+ if (!definition) return res.status(404).json({ ok: false, error: 'There is no such revision.', code: 'revision_not_found' });
253
+ withEtag(res, definition.etag).json({ ok: true, revision: definition });
254
+ }));
255
+ route('get', '/agents/:id/diff', reader, idCheck, safe(async (req, res) => {
256
+ const pick = (value) => (typeof value === 'string' && value ? value : null);
257
+ res.json({ ok: true, diff: registry.diff(keyOf(req), { from: pick(req.query?.from), to: pick(req.query?.to) }) });
258
+ }));
259
+ route('get', '/agents/:id/export', reader, idCheck, safe(async (req, res) => res.json({ ok: true, bundle: registry.exportBundle({ agents: [keyOf(req)] }) })));
260
+ route('get', '/agents/:id/runs', reader, idCheck, safe(async (req, res) => {
261
+ // The roster of runs is the owner's, and the Assistant's for its own session's: never a worker's.
262
+ if (req.principal.kind === 'agent') return sendGuardError(res, 403, 'RUNS_FORBIDDEN', 'The runs of an agent are listed for the owner and for the Assistant\'s own session.');
263
+ // The owner's page proves itself by this boot's page secret: a local process that merely sends no agent header
264
+ // reads no roster of runs (as GET /api/assistant/runs).
265
+ if (req.principal.kind === 'owner' && pageSession && !pageSession.verify(req)) return pageSession.require(req, res, () => {});
266
+ const key = keyOf(req);
267
+ registry.get(key);
268
+ const from = dispatcherOf();
269
+ if (!from) return res.json({ ok: true, runs: [], available: false });
270
+ const limit = Math.min(200, Math.max(1, Number(req.query?.limit) || 50));
271
+ const rows = from.list({ limit: 500, ...(req.principal.kind === 'assistant' ? { assistantSessionId: req.principal.assistantSessionId } : {}) })
272
+ .filter((run) => run.agentPin?.id === key.id && sameScope(run.agentPin.scope, key.scope));
273
+ res.json({ ok: true, available: true, runs: rows.slice(0, limit).map(runRow), total: rows.length });
274
+ }));
275
+
276
+ // ── checks (nothing is stored) ──
277
+ const definitionOf = (body) => (isObject(body?.definition) ? body.definition : body);
278
+ route('post', '/validate', json, reader, safe(async (req, res) => {
279
+ const checked = registry.validate(definitionOf(req.body || {}));
280
+ res.json({ ok: true, valid: checked.ok, errors: checked.errors, value: checked.value, warnings: lintOf(checked.value) });
281
+ }));
282
+ route('post', '/lint', json, reader, safe(async (req, res) => res.json({ ok: true, warnings: lintOf(definitionOf(req.body || {})) })));
283
+
284
+ // ── drafts ──
285
+ route('post', '/agents', json, writer, safe(async (req, res) => {
286
+ const out = registry.create(definitionOf(req.body || {}), { author: authorOf(req.principal) });
287
+ withEtag(res, out.etag).status(201).json(draftBody(out));
288
+ }));
289
+ route('post', '/agents/:id/draft', json, writer, idCheck, safe(async (req, res) => {
290
+ const key = keyOf(req);
291
+ if (refuseOthersDraft(req, res, key)) return;
292
+ const out = registry.openDraft(key, { author: authorOf(req.principal) });
293
+ withEtag(res, out.etag).json(draftBody(out));
294
+ }));
295
+ route('patch', '/agents/:id/draft', json, writer, idCheck, safe(async (req, res) => {
296
+ const key = keyOf(req);
297
+ if (refuseOthersDraft(req, res, key)) return;
298
+ const body = req.body || {};
299
+ const { expectedEtag: _etag, patch: named, ...rest } = body;
300
+ const out = registry.updateDraft(key, isObject(named) ? named : rest, { expectedEtag: expectedEtagOf(req), author: authorOf(req.principal) });
301
+ withEtag(res, out.etag).json(draftBody(out));
302
+ }));
303
+ route('delete', '/agents/:id/draft', json, writer, idCheck, safe(async (req, res) => {
304
+ const key = keyOf(req);
305
+ if (refuseOthersDraft(req, res, key)) return;
306
+ res.json({ ok: true, ...registry.discardDraft(key, { expectedEtag: expectedEtagOf(req) }) });
307
+ }));
308
+ route('post', '/agents/:id/copy', json, writer, idCheck, safe(async (req, res) => {
309
+ const body = req.body || {};
310
+ const out = registry.copy(keyOf(req), { id: typeof body.id === 'string' && body.id ? body.id : null, scope: body.scope !== undefined && body.scope !== null ? scopeOf(body.scope) : null, author: authorOf(req.principal) });
311
+ withEtag(res, out.etag).status(201).json(draftBody(out));
312
+ }));
313
+ route('post', '/import', json, writer, safe(async (req, res) => {
314
+ const body = req.body || {};
315
+ const bundle = body.bundle !== undefined ? body.bundle : body;
316
+ // Replacing a draft that is already there is the owner's: an agent's import never overwrites one.
317
+ const out = registry.importBundle(bundle, {
318
+ author: authorOf(req.principal), scope: body.scope !== undefined && body.scope !== null ? scopeOf(body.scope) : null,
319
+ replaceDrafts: req.principal.kind === 'owner' && body.replaceDrafts === true, prefer: body.prefer === 'draft' ? 'draft' : 'approved',
320
+ });
321
+ res.json({ ok: true, ...out });
322
+ }));
323
+ route('post', '/import-claude-agent', json, writer, safe(async (req, res) => {
324
+ const body = req.body || {};
325
+ const out = registry.importClaudeAgent(body.markdown, {
326
+ fileName: text(body.fileName || '', 500), id: typeof body.id === 'string' && body.id ? body.id : null,
327
+ scope: body.scope !== undefined && body.scope !== null ? scopeOf(body.scope) : null, author: authorOf(req.principal),
328
+ replaceDraft: req.principal.kind === 'owner' && body.replaceDraft === true,
329
+ });
330
+ withEtag(res, out.etag).status(out.action === 'created' ? 201 : 200).json(draftBody(out));
331
+ }));
332
+
333
+ // ── review ──
334
+ route('post', '/agents/:id/submit', json, writer, idCheck, safe(async (req, res) => {
335
+ const key = keyOf(req);
336
+ if (refuseOthersDraft(req, res, key)) return;
337
+ const out = registry.submit(key, { actor: authorOf(req.principal), expectedEtag: expectedEtagOf(req), note: text(req.body?.note || '', 2000) || null });
338
+ withEtag(res, out.etag).json(draftBody(out));
339
+ }));
340
+ route('post', '/agents/:id/request-changes', json, writer, idCheck, safe(async (req, res) => {
341
+ // The owner asks for changes; the author takes its own submission back to edit it.
342
+ const key = keyOf(req);
343
+ if (refuseOthersDraft(req, res, key)) return;
344
+ const out = registry.requestChanges(key, { actor: authorOf(req.principal), expectedEtag: expectedEtagOf(req), note: text(req.body?.note || '', 2000) || null });
345
+ withEtag(res, out.etag).json(draftBody(out));
346
+ }));
347
+ route('post', '/agents/:id/approve', json, owner, idCheck, safe(async (req, res) => {
348
+ const out = registry.approve(keyOf(req), { actor: 'owner', expectedEtag: expectedEtagOf(req), note: text(req.body?.note || '', 2000) || null });
349
+ withEtag(res, out.etag).json({ ok: true, agent: out.agent, revision: out.revision, etag: out.etag });
350
+ }));
351
+ route('post', '/agents/:id/withdraw', json, writer, idCheck, safe(async (req, res) => {
352
+ const key = keyOf(req);
353
+ const body = req.body || {};
354
+ const which = body.revision === undefined || body.revision === null || body.revision === '' ? null : body.revision;
355
+ if (req.principal.kind !== 'owner') {
356
+ // An agent withdraws the working revision it made, never a stored one: taking an approved agent out of use is the owner's.
357
+ const draft = registry.revision(key, 'draft');
358
+ if (body.all === true || !draft || (which !== null && which !== 'draft' && Number(which) !== draft.revision)) {
359
+ return sendGuardError(res, 403, 'UI_ONLY', 'Withdrawing an approved revision is the owner\'s, from SynaBun\'s own page.');
360
+ }
361
+ if (refuseOthersDraft(req, res, key)) return;
362
+ }
363
+ const out = registry.withdraw(key, { revision: req.principal.kind === 'owner' ? which : 'draft', all: req.principal.kind === 'owner' && body.all === true, actor: authorOf(req.principal), note: text(body.note || '', 2000) || null });
364
+ res.json({ ok: true, ...out });
365
+ }));
366
+ route('delete', '/agents/:id', json, owner, idCheck, safe(async (req, res) => res.json({ ok: true, ...registry.remove(keyOf(req)) })));
367
+
368
+ // ── a test run ──
369
+ // The owner tries an agent before approving it: a short run of the draft (or of a stored revision), dispatched
370
+ // from the page, outside every Assistant session. The run is marked as a test on its record.
371
+ route('post', '/agents/:id/test-run', json, owner, idCheck, safe(async (req, res) => {
372
+ const key = keyOf(req);
373
+ const body = req.body || {};
374
+ const agent = registry.get(key);
375
+ const from = dispatcherOf();
376
+ if (!from) return res.status(503).json({ ok: false, error: 'Runs are not available on this server yet.', code: 'DISPATCH_UNAVAILABLE' });
377
+ const asked = body.revision === undefined || body.revision === null || body.revision === '' ? (agent.draftDefinition ? 'draft' : 'approved') : body.revision;
378
+ const which = asked === 'draft' || asked === 'approved' ? asked : (/^[1-9][0-9]{0,8}$/.test(String(asked)) ? Number(asked) : null);
379
+ if (which === null) return res.status(400).json({ ok: false, error: 'revision is a number, "draft" or "approved".', code: 'invalid_revision' });
380
+ const definition = registry.revision(key, which);
381
+ if (!definition) return res.status(404).json({ ok: false, error: 'There is no such revision to run.', code: 'revision_not_found' });
382
+ if (definition.status === 'withdrawn') return res.status(409).json({ ok: false, error: 'A withdrawn revision is not run.', code: 'AGENT_NOT_APPROVED' });
383
+ const task = text(body.task || '', 16000).trim();
384
+ if (!task) return res.status(400).json({ ok: false, error: 'task is required: what the agent should do in this test.', code: 'TASK_REQUIRED' });
385
+ const cwd = typeof body.cwd === 'string' && body.cwd ? body.cwd : (definition.scope.kind === 'project' ? definition.scope.path : null);
386
+ if (!cwd) return res.status(400).json({ ok: false, error: 'cwd is required: the folder the test runs in.', code: 'CWD_REQUIRED' });
387
+ const spec = { task, cwd, title: text(body.title || `Test: ${definition.name || definition.id}`, 80), maxMinutes: Number(body.maxMinutes ?? body.max_minutes) || TEST_RUN_MINUTES, tags: [TEST_RUN_TAG, ...(Array.isArray(body.tags) ? body.tags.filter((tag) => typeof tag === 'string' && tag && tag !== TEST_RUN_TAG).slice(0, 9) : [])] };
388
+ // What the owner overrides for this one test (the dispatcher's own spelling, and the tools' snake case).
389
+ for (const [key2, ...names] of [['provider', 'provider'], ['model', 'model'], ['effort', 'effort'], ['accountId', 'accountId', 'account_id'], ['capability', 'capability'], ['permissionPolicy', 'permissionPolicy', 'permission_policy'], ['tools', 'tools'], ['usesBrowser', 'usesBrowser', 'uses_browser'], ['usesComputer', 'usesComputer', 'uses_computer'], ['moreloginProfile', 'moreloginProfile', 'morelogin_profile'], ['context', 'context'], ['budgetUsd', 'budgetUsd', 'budget_usd']]) {
390
+ const value = names.map((name) => body[name]).find((item) => item !== undefined && item !== null && item !== '');
391
+ if (value !== undefined) spec[key2] = value;
392
+ }
393
+ const prepared = resolver.prepareRevision(spec, definition, { requested: `${key.id}@${which}` });
394
+ const result = await from.dispatch(prepared, { assistantSessionId: null, origin: 'ui' });
395
+ res.status(result.queued ? 202 : 200).json({ ...result, ok: true, test: true, revision: definition.revision, revisionStatus: definition.status });
396
+ }));
397
+
398
+ // ── agents-p4 BEGIN: teams (lib/teams/api.js) ──────────────────────────────
399
+ // The list and one team for whoever reads the library; landing and discarding are the owner's, from SynaBun's own
400
+ // page only (the `owner` tier above: no agent header, X-SynaBun-UI, the page secret, the owner route guard).
401
+ registerTeamStudioRoutes({ route, reader, owner, json, scheduler: teams });
402
+ // ── agents-p4 END ──────────────────────────────────────────────────────────
403
+ // ════ agents-p6 BEGIN: agent-forge and native export (docs/agents.md → agent-forge, Native export) ════
404
+ // What the MCP tool `agent_definition` and Agents Studio add to the routes above. Nothing here approves, and
405
+ // nothing here makes a draft usable: a draft still waits for the owner's approval (POST /agents/:id/approve).
406
+ // forge the owner and the Assistant (by its brain's launch credential): the guide, the catalog, the
407
+ // privilege check, an export's preview, an import of a host's own agent as a draft. Never a worker
408
+ // (403 FORGE_ASSISTANT_ONLY): agent-forge is the Assistant's workflow.
409
+ // owner writing an export into a host's folder: the owner's page only, as an approval is.
410
+ const FORGE_ERROR_KEYS = ['existingDigest', 'currentDigest', 'path', 'files', 'hosts', 'host', 'instead', 'agents'];
411
+ /** `safe`, with the keys the forge's own errors carry (a digest to name, the files of the guide, the hosts). */
412
+ const forgeSafe = (fn) => async (req, res) => {
413
+ try { await fn(req, res); } catch (err) {
414
+ const extra = {};
415
+ for (const key of FORGE_ERROR_KEYS) if (err?.[key] !== undefined) extra[key] = err[key];
416
+ if (Object.keys(extra).length) { const send = res.json.bind(res); res.json = (body) => send({ ...body, ...extra }); }
417
+ fail(res, err);
418
+ }
419
+ };
420
+ const forgeUnavailable = (res) => res.status(503).json({ ok: false, error: 'agent-forge is not available on this server yet.', code: 'FORGE_UNAVAILABLE' });
421
+ const noWorker = (req, res, next) => {
422
+ if (req.principal.kind === 'agent') return sendGuardError(res, 403, 'FORGE_ASSISTANT_ONLY', 'agent-forge is the Assistant\'s workflow and the owner\'s page: a worker neither reads its guide nor previews or imports through it.');
423
+ if (!forge) return forgeUnavailable(res);
424
+ next();
425
+ };
426
+ const forgeReader = (req, res, next) => reader(req, res, () => noWorker(req, res, next));
427
+ const forgeWriter = (req, res, next) => writer(req, res, () => noWorker(req, res, next));
428
+ const forgeOwner = (req, res, next) => owner(req, res, () => (forge ? next() : forgeUnavailable(res)));
429
+ const queryText = (value, max = 4000) => (typeof value === 'string' && value ? value.slice(0, max) : null);
430
+ /** `draft`, `approved` or a number, as a request names a revision; undefined for anything else. */
431
+ const revisionOf = (value, fallback) => {
432
+ if (value === undefined || value === null || value === '') return fallback;
433
+ if (value === 'draft' || value === 'approved') return value;
434
+ return /^[1-9][0-9]{0,8}$/.test(String(value)) ? Number(value) : undefined;
435
+ };
436
+
437
+ // The agent-forge workflow SynaBun ships (skills/agent-forge): its SKILL.md, or one of its files (`file`).
438
+ route('get', '/guide', forgeReader, forgeSafe(async (req, res) => res.json({ ok: true, ...forge.guide(queryText(req.query?.file, 512) || 'SKILL.md') })));
439
+
440
+ // Everything a definition is filled from, so nothing in one is a guess: the agents there are (with their status),
441
+ // and what exists on this server (providers, models, efforts, tool groups, MCP servers, colour tokens, MoreLogin
442
+ // profiles agents may choose, registered projects). `provider` + `q` narrow the models; `project` picks whose
443
+ // colour tokens; `search` narrows the agents.
444
+ route('get', '/forge/catalog', forgeReader, forgeSafe(async (req, res) => {
445
+ const q = req.query || {};
446
+ const described = await forge.describe({ provider: queryText(q.provider, 40), q: queryText(q.q, 200), projectPath: queryText(q.project) });
447
+ const agents = registry.list({ q: queryText(q.search, 200) || '' }).map((agent) => ({
448
+ ref: agent.ref, id: agent.id, scope: agent.scope.kind, ...(agent.scope.kind === 'project' ? { projectPath: agent.scope.path } : {}),
449
+ name: agent.name, description: text(agent.description, 200), status: agent.status, approvedRevision: agent.approvedRevision,
450
+ draft: agent.draft ? { revision: agent.draft.revision, status: agent.draft.status, author: agent.draft.author?.kind || null } : null,
451
+ provider: agent.provider, model: agent.model, capability: agent.capability, taskClasses: agent.taskClasses,
452
+ }));
453
+ res.json({
454
+ ok: true, version: AGENTS_STUDIO_VERSION, agents, ...described,
455
+ taskClasses: AGENT_TASK_CLASSES, capabilityLevels: AGENT_CAPABILITIES, permissionPolicies: AGENT_PERMISSION_POLICIES,
456
+ limits: { id: AGENT_LIMITS.id, name: AGENT_LIMITS.name, description: AGENT_LIMITS.description, instructions: AGENT_LIMITS.instructions, mcpServers: AGENT_LIMITS.mcpServers, skills: AGENT_LIMITS.skills },
457
+ nativeHosts: nativeFormats().map((format) => ({ host: format.host, supported: format.supported, format: format.format })),
458
+ });
459
+ }));
460
+
461
+ // The checks of a definition with what it would let a worker do: the contract's errors, the softer findings, the
462
+ // privileges (capability, browser, computer, servers, profile) and what is wider than the approved revision.
463
+ const checksOf = (definition, against) => {
464
+ const checked = registry.validate(definition);
465
+ return {
466
+ valid: checked.ok, errors: checked.errors, warnings: lintOf(checked.value), privileges: privilegesOf(checked.value),
467
+ delta: { against: against ? against.revision : null, ...privilegeDelta(against || null, checked.value) },
468
+ };
469
+ };
470
+ route('post', '/checks', json, forgeReader, forgeSafe(async (req, res) => {
471
+ const definition = definitionOf(req.body || {});
472
+ let against = null;
473
+ try { if (ID_RE.test(String(definition?.id || ''))) against = registry.revision({ id: definition.id, scope: definition.scope !== undefined && definition.scope !== null ? scopeOf(definition.scope) : { kind: 'global' } }, 'approved'); } catch { against = null; }
474
+ res.json({ ok: true, ...checksOf(isObject(definition) ? definition : {}, against) });
475
+ }));
476
+ route('get', '/agents/:id/checks', forgeReader, idCheck, forgeSafe(async (req, res) => {
477
+ const key = keyOf(req);
478
+ const agent = registry.get(key);
479
+ const which = revisionOf(req.query?.revision, agent.draftDefinition ? 'draft' : 'approved');
480
+ if (which === undefined) return res.status(400).json({ ok: false, error: 'A revision is a number, "draft" or "approved".', code: 'invalid_revision' });
481
+ const definition = registry.revision(key, which);
482
+ if (!definition) return res.status(404).json({ ok: false, error: 'There is no such revision.', code: 'revision_not_found' });
483
+ // A working revision is compared with what is approved now; a stored one with the revision it was made over.
484
+ const against = definition.status === 'draft' || definition.status === 'in_review'
485
+ ? registry.revision(key, 'approved')
486
+ : (definition.parentRevision ? registry.revision(key, definition.parentRevision) : null);
487
+ withEtag(res, definition.etag).json({ ok: true, id: agent.id, scope: agent.scope, revision: definition.revision, status: definition.status, etag: definition.etag, ...checksOf(definition, against) });
488
+ }));
489
+
490
+ // ── native export ──
491
+ // What each host has for an agent of its own (or why it has nothing): the table of docs/agents.md.
492
+ route('get', '/native-export/formats', reader, safe(async (req, res) => res.json({ ok: true, formats: nativeFormats(), writes: !!forge })));
493
+
494
+ /** The revision a native export is made from, with the agent it belongs to. */
495
+ const exportSource = (req, res, fallback) => {
496
+ const key = keyOf(req);
497
+ const agent = registry.get(key);
498
+ const which = revisionOf(req.query?.revision ?? req.body?.revision, fallback(agent));
499
+ if (which === undefined) { res.status(400).json({ ok: false, error: 'A revision is a number, "draft" or "approved".', code: 'invalid_revision' }); return null; }
500
+ const definition = registry.revision(key, which);
501
+ if (!definition) { res.status(404).json({ ok: false, error: 'There is no such revision.', code: 'revision_not_found' }); return null; }
502
+ return { key, agent, definition };
503
+ };
504
+ /**
505
+ * Where an export goes unless the request says (`target`, and `targetProject` for a project: `project` in the
506
+ * query is the agent's own scope): a project's agent into its project, a global one to the account.
507
+ */
508
+ const targetOf = (source, definition) => {
509
+ const kind = queryText(source?.target, 20);
510
+ const project = queryText(source?.targetProject);
511
+ if (kind) return { target: kind, projectPath: project };
512
+ if (project) return { target: 'project', projectPath: project };
513
+ return definition.scope.kind === 'project' ? { target: 'project', projectPath: definition.scope.path } : { target: 'account', projectPath: null };
514
+ };
515
+
516
+ // A preview: the file's text for a host, what it cannot hold, and what is at its place now. Reads only: nothing
517
+ // is written by this route, whoever asks. A draft may be previewed; only an approved revision is ever written.
518
+ route('get', '/agents/:id/native-export', forgeReader, idCheck, forgeSafe(async (req, res) => {
519
+ const found = exportSource(req, res, (agent) => (agent.approvedDefinition ? 'approved' : 'draft'));
520
+ if (!found) return;
521
+ const { key, definition } = found;
522
+ const exported = exportNative(definition, queryText(req.query?.host, 40) || definition.provider);
523
+ const head = { ok: true, id: key.id, scope: definition.scope, revision: definition.revision, status: definition.status, approved: definition.status === 'approved', written: false };
524
+ if (!exported.supported) return res.json({ ...head, ...exported, target: null, writable: false });
525
+ let target = null;
526
+ let targetProblem = null;
527
+ try { target = forge.targets.inspect(forge.targets.resolveTarget(exported, { id: key.id, ...targetOf(req.query, definition) }), exported, { id: key.id }); } catch (err) {
528
+ if (!Number.isInteger(err?.status) || err.status >= 500) throw err;
529
+ targetProblem = { code: err.code || null, error: err.message };
530
+ }
531
+ res.json({
532
+ ...head, ...exported, target, ...(targetProblem ? { targetProblem } : {}),
533
+ writable: head.approved && !!target?.writable,
534
+ next: head.approved ? 'Only the owner writes it, from Agents Studio (the agent\'s Export): this preview wrote nothing.' : 'This revision is not approved: only an approved revision is exported, and only by the owner from Agents Studio.',
535
+ });
536
+ }));
537
+
538
+ // The owner writes an export into the host's folder: the account level, or a registered project. Exactly what was
539
+ // previewed (`contentDigest`), of an approved revision only; what is already there is replaced only with `replace`
540
+ // and the digest the owner saw (`expectedDigest`).
541
+ route('post', '/agents/:id/native-export', json, forgeOwner, idCheck, forgeSafe(async (req, res) => {
542
+ const body = req.body || {};
543
+ const found = exportSource(req, res, () => 'approved');
544
+ if (!found) return;
545
+ const { key, definition } = found;
546
+ if (definition.status !== 'approved') return res.status(409).json({ ok: false, error: 'Only an approved revision is exported: approve the draft first.', code: 'AGENT_NOT_APPROVED', revisionStatus: definition.status });
547
+ const exported = exportNative(definition, text(body.host || '', 40) || definition.provider);
548
+ if (!exported.supported) return res.status(400).json({ ok: false, error: exported.reason, code: 'no_native_format', host: exported.host, instead: exported.instead });
549
+ const named = typeof body.contentDigest === 'string' ? body.contentDigest.trim() : '';
550
+ if (!ETAG_RE.test(named)) return res.status(428).json({ ok: false, error: 'Name the digest of the export you looked at (contentDigest): what is written is exactly what was previewed.', code: 'digest_required', currentDigest: exported.digest });
551
+ if (named !== exported.digest) return res.status(409).json({ ok: false, error: 'The export is not what you looked at any more: preview it again.', code: 'content_changed', currentDigest: exported.digest });
552
+ const resolved = forge.targets.resolveTarget(exported, { id: key.id, ...targetOf(body, definition) });
553
+ const result = forge.targets.write(resolved, exported, { id: key.id, replace: body.replace === true, expectedDigest: typeof body.expectedDigest === 'string' ? body.expectedDigest.trim() : null });
554
+ forge.onExport?.({ action: 'exported', id: key.id, scope: definition.scope, revision: definition.revision, host: exported.host, target: result.kind, path: result.path, result: result.action });
555
+ res.status(result.action === 'created' ? 201 : 200).json({ ok: true, id: key.id, revision: definition.revision, format: exported.format, ...result, unrepresented: exported.unrepresented, notes: exported.notes });
556
+ }));
557
+
558
+ // ── native import ──
559
+ // A host's own agent as a draft: a Claude Code agent file (its text, or its path in an agents folder Claude Code
560
+ // reads) or an OpenCode agent (the text of an opencode.json, or one entry). It lands as a draft, whatever it says.
561
+ route('post', '/native-import', json, forgeWriter, forgeSafe(async (req, res) => {
562
+ const body = req.body || {};
563
+ const host = text(body.host || 'claude-code', 40).trim().toLowerCase();
564
+ const author = authorOf(req.principal);
565
+ const replaceDraft = req.principal.kind === 'owner' && body.replaceDraft === true;
566
+ const scope = body.scope !== undefined && body.scope !== null ? scopeOf(body.scope) : null;
567
+ const id = typeof body.id === 'string' && body.id ? body.id : null;
568
+ if (host === 'claude-code') {
569
+ const file = typeof body.path === 'string' && body.path && body.source === undefined ? forge.readClaudeAgentFile(body.path) : null;
570
+ const out = registry.importClaudeAgent(file ? file.markdown : body.source, { fileName: file ? file.fileName : text(body.fileName || '', 500), id, scope, author, replaceDraft });
571
+ return withEtag(res, out.etag).status(out.action === 'created' ? 201 : 200).json(draftBody(out));
572
+ }
573
+ const { content, notes } = importNative(host, body.source, { name: text(body.name || '', 200), id, scope });
574
+ const key = { id: content.id, scope: content.scope };
575
+ if (!registry.has(key)) {
576
+ const out = registry.create(content, { author });
577
+ return withEtag(res, out.etag).status(201).json(draftBody({ ...out, notes, action: 'created' }));
578
+ }
579
+ const agent = registry.get(key);
580
+ const draft = agent.draftDefinition;
581
+ if (draft && (!replaceDraft || draft.status !== 'draft')) throw new AgentRegistryError(409, 'draft_exists', `Agent "${content.id}" already has a draft; change that one, or pass another id.`, { currentEtag: draft.etag });
582
+ // The content becomes the draft over the newest revision (an update with that revision's etag starts the draft).
583
+ const etag = draft ? draft.etag : (agent.approvedEtag || [...agent.revisions].reverse().find((rev) => rev.etag)?.etag || null);
584
+ const { id: _id, scope: _scope, ...fields } = content;
585
+ const out = registry.updateDraft(key, fields, { expectedEtag: etag, author });
586
+ withEtag(res, out.etag).json(draftBody({ ...out, notes, action: 'drafted' }));
587
+ }));
588
+ // ════ agents-p6 END ════
589
+
590
+ return { base: AGENTS_STUDIO_BASE, capabilities: AGENTS_STUDIO_CAPABILITIES };
591
+ }