synabun 2.4.0 → 2.4.2

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 (319) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/README.md +1 -1
  3. package/browser-extension/content.js +73 -11
  4. package/browser-extension/engine.js +196 -15
  5. package/browser-extension/manifest.json +4 -2
  6. package/browser-extension/popup-strings.js +10 -4
  7. package/browser-extension/popup-view.js +1 -1
  8. package/browser-extension/popup.css +1 -0
  9. package/browser-extension/popup.html +4 -1
  10. package/browser-extension/popup.js +22 -10
  11. package/browser-extension/protocol.js +102 -11
  12. package/browser-extension/service-worker.js +20 -4
  13. package/browser-extension/tokens.css +1 -1
  14. package/docs/browser-extension-bridge.md +25 -5
  15. package/lib/data-home-files.js +47 -0
  16. package/lib/data-home-migration.js +34 -58
  17. package/lib/first-launch-protection.js +8 -2
  18. package/lib/update-snapshot.js +11 -4
  19. package/mcp-server/dist/http.d.ts.map +1 -1
  20. package/mcp-server/dist/http.js +25 -2
  21. package/mcp-server/dist/http.js.map +1 -1
  22. package/mcp-server/dist/index.d.ts.map +1 -1
  23. package/mcp-server/dist/index.js +62 -17
  24. package/mcp-server/dist/index.js.map +1 -1
  25. package/mcp-server/dist/services/browser-bench.d.ts +22 -22
  26. package/mcp-server/dist/services/memory-maintenance.d.ts +1 -0
  27. package/mcp-server/dist/services/memory-maintenance.d.ts.map +1 -1
  28. package/mcp-server/dist/services/memory-maintenance.js +34 -45
  29. package/mcp-server/dist/services/memory-maintenance.js.map +1 -1
  30. package/mcp-server/dist/services/memory-migration-copy.d.ts +144 -0
  31. package/mcp-server/dist/services/memory-migration-copy.d.ts.map +1 -0
  32. package/mcp-server/dist/services/memory-migration-copy.js +467 -0
  33. package/mcp-server/dist/services/memory-migration-copy.js.map +1 -0
  34. package/mcp-server/dist/services/memory-migration-worker.d.ts +2 -0
  35. package/mcp-server/dist/services/memory-migration-worker.d.ts.map +1 -0
  36. package/mcp-server/dist/services/memory-migration-worker.js +60 -0
  37. package/mcp-server/dist/services/memory-migration-worker.js.map +1 -0
  38. package/mcp-server/dist/services/memory-retrieval.d.ts +4 -0
  39. package/mcp-server/dist/services/memory-retrieval.d.ts.map +1 -1
  40. package/mcp-server/dist/services/memory-retrieval.js +188 -40
  41. package/mcp-server/dist/services/memory-retrieval.js.map +1 -1
  42. package/mcp-server/dist/services/memory-schema.d.ts +58 -2
  43. package/mcp-server/dist/services/memory-schema.d.ts.map +1 -1
  44. package/mcp-server/dist/services/memory-schema.js +190 -13
  45. package/mcp-server/dist/services/memory-schema.js.map +1 -1
  46. package/mcp-server/dist/services/memory-sessions.d.ts +19 -1
  47. package/mcp-server/dist/services/memory-sessions.d.ts.map +1 -1
  48. package/mcp-server/dist/services/memory-sessions.js +56 -20
  49. package/mcp-server/dist/services/memory-sessions.js.map +1 -1
  50. package/mcp-server/dist/services/memory-verification.d.ts.map +1 -1
  51. package/mcp-server/dist/services/memory-verification.js +8 -5
  52. package/mcp-server/dist/services/memory-verification.js.map +1 -1
  53. package/mcp-server/dist/services/neural-interface.d.ts +6 -0
  54. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  55. package/mcp-server/dist/services/neural-interface.js +19 -2
  56. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  57. package/mcp-server/dist/services/retrieval-reader-worker.d.ts +2 -0
  58. package/mcp-server/dist/services/retrieval-reader-worker.d.ts.map +1 -0
  59. package/mcp-server/dist/services/retrieval-reader-worker.js +76 -0
  60. package/mcp-server/dist/services/retrieval-reader-worker.js.map +1 -0
  61. package/mcp-server/dist/services/retrieval-reader.d.ts +38 -0
  62. package/mcp-server/dist/services/retrieval-reader.d.ts.map +1 -0
  63. package/mcp-server/dist/services/retrieval-reader.js +145 -0
  64. package/mcp-server/dist/services/retrieval-reader.js.map +1 -0
  65. package/mcp-server/dist/services/sqlite-write.d.ts +14 -0
  66. package/mcp-server/dist/services/sqlite-write.d.ts.map +1 -0
  67. package/mcp-server/dist/services/sqlite-write.js +94 -0
  68. package/mcp-server/dist/services/sqlite-write.js.map +1 -0
  69. package/mcp-server/dist/services/sqlite.d.ts +39 -0
  70. package/mcp-server/dist/services/sqlite.d.ts.map +1 -1
  71. package/mcp-server/dist/services/sqlite.js +249 -8
  72. package/mcp-server/dist/services/sqlite.js.map +1 -1
  73. package/mcp-server/dist/services/tool-catalog.d.ts +1 -1
  74. package/mcp-server/dist/services/typesafe-config.d.ts +7 -1
  75. package/mcp-server/dist/services/typesafe-config.d.ts.map +1 -1
  76. package/mcp-server/dist/services/typesafe-config.js +32 -10
  77. package/mcp-server/dist/services/typesafe-config.js.map +1 -1
  78. package/mcp-server/dist/services/typesafe.d.ts.map +1 -1
  79. package/mcp-server/dist/services/typesafe.js +9 -7
  80. package/mcp-server/dist/services/typesafe.js.map +1 -1
  81. package/mcp-server/dist/services/vector-cache.d.ts +32 -0
  82. package/mcp-server/dist/services/vector-cache.d.ts.map +1 -1
  83. package/mcp-server/dist/services/vector-cache.js +161 -8
  84. package/mcp-server/dist/services/vector-cache.js.map +1 -1
  85. package/mcp-server/dist/tools/agent-definition.d.ts +2 -2
  86. package/mcp-server/dist/tools/agents.d.ts +13 -8
  87. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  88. package/mcp-server/dist/tools/agents.js +35 -15
  89. package/mcp-server/dist/tools/agents.js.map +1 -1
  90. package/mcp-server/dist/tools/browser-advanced.d.ts +1 -1
  91. package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
  92. package/mcp-server/dist/tools/browser-advanced.js +10 -3
  93. package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
  94. package/mcp-server/dist/tools/browser-extension-setup.d.ts +5 -0
  95. package/mcp-server/dist/tools/browser-extension-setup.d.ts.map +1 -0
  96. package/mcp-server/dist/tools/browser-extension-setup.js +23 -0
  97. package/mcp-server/dist/tools/browser-extension-setup.js.map +1 -0
  98. package/mcp-server/dist/tools/browser-interact.d.ts.map +1 -1
  99. package/mcp-server/dist/tools/browser-interact.js +6 -1
  100. package/mcp-server/dist/tools/browser-interact.js.map +1 -1
  101. package/mcp-server/dist/tools/fb-groups.d.ts +2 -2
  102. package/mcp-server/dist/tools/skill-tools.d.ts +4 -4
  103. package/mcp-server/dist/tools/tool-groups.d.ts +1 -1
  104. package/mcp-server/package-lock.json +2 -2
  105. package/mcp-server/package.json +1 -1
  106. package/mcp-server/src/http.ts +20 -2
  107. package/mcp-server/src/index.ts +59 -17
  108. package/mcp-server/src/services/memory-maintenance.ts +31 -28
  109. package/mcp-server/src/services/memory-migration-copy.ts +419 -0
  110. package/mcp-server/src/services/memory-migration-worker.ts +55 -0
  111. package/mcp-server/src/services/memory-retrieval.ts +173 -32
  112. package/mcp-server/src/services/memory-schema.ts +194 -12
  113. package/mcp-server/src/services/memory-sessions.ts +54 -21
  114. package/mcp-server/src/services/memory-verification.ts +7 -4
  115. package/mcp-server/src/services/neural-interface.ts +23 -2
  116. package/mcp-server/src/services/retrieval-reader-worker.ts +67 -0
  117. package/mcp-server/src/services/retrieval-reader.ts +131 -0
  118. package/mcp-server/src/services/sqlite-write.ts +60 -0
  119. package/mcp-server/src/services/sqlite.ts +246 -8
  120. package/mcp-server/src/services/typesafe-config.ts +25 -6
  121. package/mcp-server/src/services/typesafe.ts +9 -7
  122. package/mcp-server/src/services/vector-cache.ts +154 -9
  123. package/mcp-server/src/tools/agents.ts +33 -14
  124. package/mcp-server/src/tools/browser-advanced.ts +10 -3
  125. package/mcp-server/src/tools/browser-extension-setup.ts +30 -0
  126. package/mcp-server/src/tools/browser-interact.ts +5 -1
  127. package/neural-interface/i18n/en.json +266 -2
  128. package/neural-interface/i18n/pt-BR.json +267 -3
  129. package/neural-interface/lib/agents/builtins.json +207 -0
  130. package/neural-interface/lib/agents/registry.js +60 -15
  131. package/neural-interface/lib/agents/resolve.js +69 -10
  132. package/neural-interface/lib/agents/split.js +32 -4
  133. package/neural-interface/lib/assistant-api.js +19 -8
  134. package/neural-interface/lib/assistant-brains/claude.js +2 -0
  135. package/neural-interface/lib/assistant-brains/opencode.js +60 -11
  136. package/neural-interface/lib/assistant-catalog.js +2 -2
  137. package/neural-interface/lib/assistant-config.js +0 -7
  138. package/neural-interface/lib/assistant-dispatch.js +384 -119
  139. package/neural-interface/lib/assistant-persona.js +17 -5
  140. package/neural-interface/lib/assistant-pricing.js +65 -14
  141. package/neural-interface/lib/assistant-router.js +181 -54
  142. package/neural-interface/lib/assistant-run-wait.js +45 -28
  143. package/neural-interface/lib/assistant-runtime.js +48 -34
  144. package/neural-interface/lib/backup-contents.js +158 -0
  145. package/neural-interface/lib/backup-crypto-io.js +330 -0
  146. package/neural-interface/lib/backup-crypto-worker.js +130 -0
  147. package/neural-interface/lib/backup-crypto.js +525 -0
  148. package/neural-interface/lib/backup-download.js +268 -0
  149. package/neural-interface/lib/backup-encryption.js +318 -0
  150. package/neural-interface/lib/backup-groups.js +287 -0
  151. package/neural-interface/lib/backup-restore-session.js +176 -0
  152. package/neural-interface/lib/backup-restore-stage.js +60 -0
  153. package/neural-interface/lib/backup-service.js +836 -322
  154. package/neural-interface/lib/backup-zip-reader.js +30 -18
  155. package/neural-interface/lib/backup-zip-writer.js +34 -10
  156. package/neural-interface/lib/browser-extension-adapter.js +109 -24
  157. package/neural-interface/lib/browser-extension-bridge.js +42 -8
  158. package/neural-interface/lib/claude-agent-bridge.js +1 -0
  159. package/neural-interface/lib/claude-session-cleanup.js +5 -1
  160. package/neural-interface/lib/cli-update-planner.js +105 -6
  161. package/neural-interface/lib/client-diagnostics.js +42 -0
  162. package/neural-interface/lib/confined-fs.js +7 -2
  163. package/neural-interface/lib/coordination/README.md +8 -2
  164. package/neural-interface/lib/coordination/contract.js +161 -0
  165. package/neural-interface/lib/coordination/database.js +999 -0
  166. package/neural-interface/lib/coordination/operations.js +436 -0
  167. package/neural-interface/lib/coordination/service.js +68 -537
  168. package/neural-interface/lib/coordination/storage-worker.js +101 -0
  169. package/neural-interface/lib/coordination/store.js +219 -1111
  170. package/neural-interface/lib/db.js +70 -32
  171. package/neural-interface/lib/health-count.js +37 -0
  172. package/neural-interface/lib/loop-stall.js +139 -0
  173. package/neural-interface/lib/maritaca/client.js +2 -2
  174. package/neural-interface/lib/maritaca/models.js +12 -17
  175. package/neural-interface/lib/maritaca/opencode.js +4 -2
  176. package/neural-interface/lib/memory-api.js +9 -1
  177. package/neural-interface/lib/memory-session-capture.js +42 -10
  178. package/neural-interface/lib/memory-store-gate.js +313 -0
  179. package/neural-interface/lib/memory-store-migrate.js +65 -0
  180. package/neural-interface/lib/memory-timers.js +7 -7
  181. package/neural-interface/lib/native-loop-providers.js +13 -16
  182. package/neural-interface/lib/native-loop-runtime.js +34 -14
  183. package/neural-interface/lib/opencode-build-preflight.js +30 -8
  184. package/neural-interface/lib/opencode-native-boundary.js +69 -8
  185. package/neural-interface/lib/opencode-provider-view.js +14 -3
  186. package/neural-interface/lib/opencode-v2-ws-requests.js +31 -1
  187. package/neural-interface/lib/opencode2-client.js +2 -1
  188. package/neural-interface/lib/peer-identity.js +13 -8
  189. package/neural-interface/lib/recall-impact.js +122 -0
  190. package/neural-interface/lib/scratch-evidence.js +420 -0
  191. package/neural-interface/lib/scratch-process-guard.js +139 -0
  192. package/neural-interface/lib/scratch-references.js +279 -0
  193. package/neural-interface/lib/scratch-retention-core.js +385 -0
  194. package/neural-interface/lib/scratch-retention-worker.js +37 -0
  195. package/neural-interface/lib/scratch-retention.js +151 -0
  196. package/neural-interface/lib/session-cache-builder.js +70 -44
  197. package/neural-interface/lib/session-cache-worker.js +157 -0
  198. package/neural-interface/lib/session-indexer.js +28 -21
  199. package/neural-interface/lib/session-search-index.js +85 -0
  200. package/neural-interface/lib/skills/creation.js +1 -1
  201. package/neural-interface/lib/sqlite-integrity-worker.js +3 -1
  202. package/neural-interface/lib/style-guide/store.js +43 -3
  203. package/neural-interface/lib/system-restore.js +50 -0
  204. package/neural-interface/lib/teams/api.js +15 -6
  205. package/neural-interface/lib/teams/claims.js +67 -31
  206. package/neural-interface/lib/teams/index.js +7 -7
  207. package/neural-interface/lib/teams/integration.js +40 -40
  208. package/neural-interface/lib/teams/landing.js +6 -6
  209. package/neural-interface/lib/teams/recovery.js +24 -23
  210. package/neural-interface/lib/teams/scheduler.js +196 -97
  211. package/neural-interface/lib/teams/schema.js +1 -1
  212. package/neural-interface/lib/teams/state.js +14 -14
  213. package/neural-interface/lib/teams/worktrees.js +27 -27
  214. package/neural-interface/lib/whatsapp/bridge.js +2 -1
  215. package/neural-interface/lib/worker-confinement.js +47 -2
  216. package/neural-interface/lib/worker-mcp-channel.js +2 -0
  217. package/neural-interface/lib/worker-resume.js +5 -0
  218. package/neural-interface/lib/worker-stop.js +86 -0
  219. package/neural-interface/package-lock.json +2 -2
  220. package/neural-interface/package.json +1 -1
  221. package/neural-interface/public/index.html +260 -0
  222. package/neural-interface/public/offline.html +4 -3
  223. package/neural-interface/public/onboarding.html +259 -34
  224. package/neural-interface/public/shared/agents/studio/ax-agent-view.js +2 -2
  225. package/neural-interface/public/shared/agents/studio/ax-editor-view.js +1 -1
  226. package/neural-interface/public/shared/agents/studio/ax-library.js +0 -6
  227. package/neural-interface/public/shared/agents/studio/ax-main.js +14 -7
  228. package/neural-interface/public/shared/agents/studio/ax-ui.js +2 -2
  229. package/neural-interface/public/shared/agy/agy-options.js +11 -0
  230. package/neural-interface/public/shared/agy/agy-panel.js +29 -10
  231. package/neural-interface/public/shared/agy/agy-styles.js +14 -12
  232. package/neural-interface/public/shared/agy/agy-tabs-logic.js +4 -1
  233. package/neural-interface/public/shared/api.js +3 -2
  234. package/neural-interface/public/shared/assistant/asst-api.js +3 -3
  235. package/neural-interface/public/shared/assistant/asst-brain-picker.js +13 -6
  236. package/neural-interface/public/shared/assistant/asst-control.js +2 -0
  237. package/neural-interface/public/shared/assistant/asst-motion-gate.js +78 -4
  238. package/neural-interface/public/shared/assistant/asst-panel.js +18 -2
  239. package/neural-interface/public/shared/assistant/asst-rack-styles.js +4 -0
  240. package/neural-interface/public/shared/assistant/asst-render.js +106 -38
  241. package/neural-interface/public/shared/assistant/asst-route.js +102 -21
  242. package/neural-interface/public/shared/assistant/asst-routes-editor.js +1 -1
  243. package/neural-interface/public/shared/assistant/asst-sidepanel.js +4 -2
  244. package/neural-interface/public/shared/assistant/asst-state.js +11 -0
  245. package/neural-interface/public/shared/assistant/asst-styles.js +10 -23
  246. package/neural-interface/public/shared/assistant/route-identity.js +2 -1
  247. package/neural-interface/public/shared/cc-dropdown.js +21 -15
  248. package/neural-interface/public/shared/cdx/cdx-render.js +9 -0
  249. package/neural-interface/public/shared/cdx/cdx-settings.js +3 -1
  250. package/neural-interface/public/shared/cdx/cdx-styles.js +6 -0
  251. package/neural-interface/public/shared/cdx/cdx-tabs.js +29 -9
  252. package/neural-interface/public/shared/client-diagnostics.js +94 -0
  253. package/neural-interface/public/shared/cp/cp-markdown.js +7 -2
  254. package/neural-interface/public/shared/cp/cp-styles.js +1 -1
  255. package/neural-interface/public/shared/effort-i18n.js +118 -0
  256. package/neural-interface/public/shared/html-shell.js +4 -51
  257. package/neural-interface/public/shared/loading-diagnostic-entry.js +64 -0
  258. package/neural-interface/public/shared/memory-store-wait.js +52 -0
  259. package/neural-interface/public/shared/morelogin-profile-field.js +1 -1
  260. package/neural-interface/public/shared/mtc/mtc-logic.js +2 -1
  261. package/neural-interface/public/shared/mtc/mtc-panel.js +8 -1
  262. package/neural-interface/public/shared/mtc/mtc-styles.js +13 -12
  263. package/neural-interface/public/shared/ocp-v2/ocp-v2-childpanel.js +7 -0
  264. package/neural-interface/public/shared/ocp-v2/ocp-v2-location-logic.js +109 -0
  265. package/neural-interface/public/shared/ocp-v2/ocp-v2-modelpicker.js +8 -1
  266. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +118 -6
  267. package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +27 -3
  268. package/neural-interface/public/shared/ocp-v2/ocp-v2-send.js +13 -0
  269. package/neural-interface/public/shared/ocp-v2/ocp-v2-session-actions.js +2 -1
  270. package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +27 -93
  271. package/neural-interface/public/shared/ocp-v2/ocp-v2-variantpicker.js +17 -6
  272. package/neural-interface/public/shared/output-format.js +294 -0
  273. package/neural-interface/public/shared/owner-authority-view.js +4 -10
  274. package/neural-interface/public/shared/page-session.js +1 -1
  275. package/neural-interface/public/shared/provider-icons.js +6 -0
  276. package/neural-interface/public/shared/schedules-view.js +2 -1
  277. package/neural-interface/public/shared/server-presence.js +77 -0
  278. package/neural-interface/public/shared/settings/settings-ai-browser.js +5 -5
  279. package/neural-interface/public/shared/settings/settings-backup-contents.js +241 -0
  280. package/neural-interface/public/shared/settings/settings-backup-download.js +298 -0
  281. package/neural-interface/public/shared/settings/settings-backup-encryption-pane.js +335 -0
  282. package/neural-interface/public/shared/settings/settings-backup-encryption.js +545 -0
  283. package/neural-interface/public/shared/settings/settings-ia.js +1 -1
  284. package/neural-interface/public/shared/skills/studio/sx-geometry.js +12 -3
  285. package/neural-interface/public/shared/skills/studio/sx-main.js +14 -7
  286. package/neural-interface/public/shared/start-bridge.js +2 -2
  287. package/neural-interface/public/shared/studio-attention.js +6 -0
  288. package/neural-interface/public/shared/styles.css +354 -438
  289. package/neural-interface/public/shared/transcript-rows.js +28 -3
  290. package/neural-interface/public/shared/tray-auto-close.js +18 -5
  291. package/neural-interface/public/shared/ui-agents.js +1 -2
  292. package/neural-interface/public/shared/ui-automation-studio.js +168 -108
  293. package/neural-interface/public/shared/ui-claude-panel.js +42 -65
  294. package/neural-interface/public/shared/ui-loading.js +185 -25
  295. package/neural-interface/public/shared/ui-native-loop-router.js +59 -20
  296. package/neural-interface/public/shared/ui-navbar.js +2 -1
  297. package/neural-interface/public/shared/ui-output.js +533 -0
  298. package/neural-interface/public/shared/ui-owner-authority.js +48 -25
  299. package/neural-interface/public/shared/ui-schedules-studio.js +165 -128
  300. package/neural-interface/public/shared/ui-scroll-follow.js +97 -6
  301. package/neural-interface/public/shared/ui-sessions.js +2 -2
  302. package/neural-interface/public/shared/ui-settings-entry.js +18 -0
  303. package/neural-interface/public/shared/ui-settings.js +234 -67
  304. package/neural-interface/public/shared/ui-sidepanel-tray.js +3 -2
  305. package/neural-interface/public/shared/ui-sync.js +1 -0
  306. package/neural-interface/public/shared/ui-tooltip.js +16 -0
  307. package/neural-interface/public/shared/ui-tutorial.js +5 -6
  308. package/neural-interface/public/shared/ui-worker-end.js +27 -8
  309. package/neural-interface/public/shared/worker-end.js +9 -4
  310. package/neural-interface/public/sw.js +4 -3
  311. package/neural-interface/public/variant/2d/main.js +5 -0
  312. package/neural-interface/public/variant/3d/app.js +10 -0
  313. package/neural-interface/public/variant/3d/main.js +17 -4
  314. package/neural-interface/scripts/scratch-retention.mjs +20 -0
  315. package/neural-interface/server.js +507 -160
  316. package/npm-shrinkwrap.json +2 -2
  317. package/package.json +2 -1
  318. package/scripts/restore-data-home-from-backup.mjs +175 -8
  319. package/setup.js +18 -4
@@ -24,7 +24,7 @@
24
24
  // itself enforces: only an actor of kind `owner` approves.
25
25
 
26
26
  import { createHash } from 'node:crypto';
27
- import { existsSync, mkdirSync, readdirSync, rmSync, rmdirSync, statSync, unlinkSync } from 'node:fs';
27
+ import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, rmdirSync, statSync, unlinkSync } from 'node:fs';
28
28
  import { isAbsolute, join } from 'node:path';
29
29
  import * as YAML from 'yaml';
30
30
  import { createFrontmatter } from '../../public/shared/skills/ss-frontmatter.js';
@@ -269,15 +269,45 @@ export function parseClaudeAgent(markdown, { fileName = '', id = null, scope = n
269
269
  };
270
270
  }
271
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
+
272
283
  /**
273
284
  * @param {object} o
274
285
  * @param {string} o.dir DATA_HOME/data/agents
286
+ * @param {object[]} [o.builtins] trusted definitions shipped with the application
275
287
  * @param {() => string|number} [o.now] the time (ISO text or epoch milliseconds)
276
288
  * @param {(event: object) => void} [o.emit] told of every change: { action, id, scope, revision, status }
277
289
  * @param {() => Iterable<string>|null} [o.knownMcpServers] the MCP servers that exist, for validation (null: not checked)
278
290
  */
279
- export function createAgentRegistry({ dir, now = () => new Date().toISOString(), emit = () => {}, knownMcpServers = () => null } = {}) {
291
+ export function createAgentRegistry({ dir, builtins = [], now = () => new Date().toISOString(), emit = () => {}, knownMcpServers = () => null } = {}) {
280
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
+ }
281
311
  const stamp = () => iso(now());
282
312
  const announce = (event) => { try { emit(event); } catch { /* a listener's own failure */ } };
283
313
  const validationOptions = () => { let servers = null; try { servers = knownMcpServers() || null; } catch { servers = null; } return servers ? { knownMcpServers: servers } : {}; };
@@ -342,17 +372,23 @@ export function createAgentRegistry({ dir, now = () => new Date().toISOString(),
342
372
  function load(id, scope) {
343
373
  const agentId = requireId(id);
344
374
  const where = scopeOf(scope);
345
- if (!existsSync(agentDir(agentId, where))) return null;
346
- const numbers = revisionNumbers(agentId, where);
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) : [];
347
379
  const revisions = numbers.map((n) => ({ number: n, ...(readRecord(revisionPath(agentId, where, n)) || { definition: null, damaged: true }) }));
348
- let draft = readRecord(draftPath(agentId, where), { draft: true });
380
+ let draft = stored ? readRecord(draftPath(agentId, where), { draft: true }) : null;
349
381
  // An approval writes the revision, then removes the draft: a draft whose number is already stored is that leftover.
350
382
  if (draft?.definition && numbers.includes(draft.definition.revision)) {
351
383
  try { unlinkSync(draftPath(agentId, where)); } catch { /* removed by the next write */ }
352
384
  draft = null;
353
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
+ }
354
391
  if (!draft && !revisions.length) return null;
355
- const meta = readJson(metaPath(agentId, where));
356
392
  const approved = [...revisions].reverse().find((rev) => rev.definition?.status === 'approved' && !rev.damaged) || null;
357
393
  return { id: agentId, scope: where, meta: isObject(meta) ? meta : null, draft, revisions, approved };
358
394
  }
@@ -383,6 +419,7 @@ export function createAgentRegistry({ dir, now = () => new Date().toISOString(),
383
419
  provider: shown?.provider || null, model: shown?.model || null, effort: shown?.effort || null,
384
420
  capability: shown?.capability || null, usesBrowser: !!shown?.usesBrowser, usesComputer: !!shown?.usesComputer,
385
421
  taskClasses: shown?.taskClasses || [], icon: shown?.icon || null, color: shown?.color || null,
422
+ ...(shown?.source ? { source: shown.source } : {}),
386
423
  status: overallStatus(found),
387
424
  approvedRevision: found.approved?.definition.revision ?? null,
388
425
  approvedEtag: found.approved?.definition.etag ?? null,
@@ -417,15 +454,20 @@ export function createAgentRegistry({ dir, now = () => new Date().toISOString(),
417
454
  try { const meta = readJson(join(dir, id, key, 'agent.json')); scope = isObject(meta?.scope) ? scopeOf(meta.scope) : null; } catch { scope = null; }
418
455
  return scope && scopeKey(scope) === key ? scope : null;
419
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
+
420
464
  function everyAgent() {
421
465
  let ids = [];
422
- try { ids = readdirSync(dir); } catch { return []; }
466
+ try { ids = readdirSync(dir); } catch { /* a new installation has no owner agents */ }
423
467
  const out = [];
424
- for (const id of ids.sort()) {
468
+ for (const id of [...new Set([...ids, ...library.keys()])].sort()) {
425
469
  if (!ID_RE.test(id)) continue;
426
- let keys = [];
427
- try { keys = readdirSync(join(dir, id)); } catch { continue; }
428
- for (const key of keys.sort()) {
470
+ for (const key of scopeKeys(id)) {
429
471
  const scope = storedScope(id, key);
430
472
  const found = scope ? load(id, scope) : null;
431
473
  if (found) out.push(found);
@@ -461,9 +503,7 @@ export function createAgentRegistry({ dir, now = () => new Date().toISOString(),
461
503
  function scopesOf(id) {
462
504
  let agentId;
463
505
  try { agentId = requireId(id); } catch { return []; }
464
- let keys = [];
465
- try { keys = readdirSync(join(dir, agentId)); } catch { return []; }
466
- return keys.sort().map((key) => storedScope(agentId, key)).filter((scope) => scope && load(agentId, scope));
506
+ return scopeKeys(agentId).map((key) => storedScope(agentId, key)).filter((scope) => scope && load(agentId, scope));
467
507
  }
468
508
 
469
509
  function get({ id, scope } = {}) { return detail(require(id, scope)); }
@@ -661,6 +701,7 @@ export function createAgentRegistry({ dir, now = () => new Date().toISOString(),
661
701
  };
662
702
  const withdrawStored = (rev) => {
663
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.');
664
705
  const next = move(rev.definition, 'withdrawn', actor);
665
706
  // The content of a stored revision is never changed: only its status moves.
666
707
  if (next.etag !== rev.definition.etag) throw new AgentRegistryError(500, 'revision_immutable', 'A stored revision cannot change its content.');
@@ -669,7 +710,7 @@ export function createAgentRegistry({ dir, now = () => new Date().toISOString(),
669
710
  };
670
711
  if (all) {
671
712
  withdrawDraft();
672
- for (const rev of found.revisions) if (rev.definition?.status === 'approved') withdrawStored(rev);
713
+ for (const rev of found.revisions) if (rev.definition?.status === 'approved' && rev.definition.source !== 'builtin') withdrawStored(rev);
673
714
  } else if (which === null || which === undefined) {
674
715
  if (!withdrawDraft()) {
675
716
  if (!found.approved) throw new AgentRegistryError(409, 'invalid_transition', 'This agent has nothing to withdraw.');
@@ -696,6 +737,9 @@ export function createAgentRegistry({ dir, now = () => new Date().toISOString(),
696
737
  /** Delete an agent of one scope: its draft and every revision. Runs that pinned one keep what they started with. */
697
738
  function remove({ id, scope } = {}) {
698
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
+ }
699
743
  removeFolder(found.id, found.scope);
700
744
  announce({ action: 'deleted', id: found.id, scope: found.scope });
701
745
  return { removed: true, id: found.id, scope: found.scope };
@@ -830,6 +874,7 @@ export function createAgentRegistry({ dir, now = () => new Date().toISOString(),
830
874
  return {
831
875
  dir,
832
876
  list, get, has, scopesOf, revision, revisions,
877
+ builtinIdForClass: (taskClass) => classAgents.get(taskClass) || null,
833
878
  create, openDraft, updateDraft, discardDraft, copy,
834
879
  submit, requestChanges, approve, withdraw, remove,
835
880
  diff, exportBundle, importBundle, importClaudeAgent,
@@ -86,6 +86,13 @@ export function agentRefOf(spec) {
86
86
  return ref === undefined ? undefined : String(ref).trim();
87
87
  }
88
88
 
89
+ function hasNamedProposal(body) {
90
+ return Array.isArray(body?.proposals) && body.proposals.some(proposal => {
91
+ const ref = agentRefOf(proposal);
92
+ return ref && ref !== 'none';
93
+ });
94
+ }
95
+
89
96
  /**
90
97
  * The scopes a ref is looked up in for a run in `projectPath`, first match wins: every project the registry has
91
98
  * that agent pinned to and that the run's folder is (or is inside), the deepest first, then the global library.
@@ -268,15 +275,15 @@ export function applyAgent(rawSpec = {}, definition, ctx = {}) {
268
275
 
269
276
  // ── what it runs on ──
270
277
  const provider = given(rawSpec.provider) ? String(rawSpec.provider).trim().toLowerCase() : fields.provider;
271
- if (!given(rawSpec.provider)) fill('provider', provider);
278
+ if (!ctx.routed && !given(rawSpec.provider)) fill('provider', provider);
272
279
  const sameProvider = provider === fields.provider;
273
- if (sameProvider) {
280
+ if (!ctx.routed && sameProvider) {
274
281
  // "auto" is the dispatch saying it has no preference (the dispatcher reads it as no model): the agent's applies.
275
282
  const modelSaid = given(rawSpec.model) && String(rawSpec.model).trim().toLowerCase() !== 'auto';
276
283
  if (!modelSaid && fields.model) fill('model', fields.model);
277
284
  if (!given(rawSpec.effort) && fields.effort) fill('effort', fields.effort);
278
285
  if (!given(firstGiven(rawSpec.accountId, rawSpec.codexAccountId, rawSpec.claudeAccountId)) && fields.accountId) fill('accountId', fields.accountId);
279
- } else if (fields.model || fields.effort || fields.accountId) {
286
+ } else if (!ctx.routed && (fields.model || fields.effort || fields.accountId)) {
280
287
  corrections.push(correction('provider', fields.provider, provider, 'explicit_provider', `agent ${name}: the dispatch runs on ${provider}, not the agent's ${fields.provider}, so the agent's model, effort and account were not applied`));
281
288
  }
282
289
  if (!given(rawSpec.permissionPolicy)) fill('permissionPolicy', fields.permissionPolicy);
@@ -379,11 +386,14 @@ export function stampAgentRun(entry, input) {
379
386
  entry.agentRevision = pin.revision;
380
387
  entry.agentPin = {
381
388
  id: pin.id, revision: pin.revision, etag: pin.etag, scope: pin.scope, name: pin.name, requested: pin.requested,
389
+ ...(pin.classDefault ? { classDefault: pin.classDefault } : {}),
390
+ ...(pin.source === 'builtin' ? { source: 'builtin' } : {}),
382
391
  ...(pin.status && pin.status !== 'approved' ? { status: pin.status, test: true } : {}),
383
392
  corrections: pin.corrections || [],
384
393
  };
385
394
  if (!Array.isArray(entry.notes)) entry.notes = [];
386
- entry.notes.push(`runs as agent "${pin.name}" (${pin.ref}${pin.status && pin.status !== 'approved' ? `, ${pin.status}: a test run` : ''})`);
395
+ const note = `runs as agent "${pin.name}" (${pin.ref}${pin.status && pin.status !== 'approved' ? `, ${pin.status}: a test run` : ''})`;
396
+ if (!entry.notes.includes(note)) entry.notes.push(note);
387
397
  for (const item of pin.corrections || []) if (item?.text && !entry.notes.includes(item.text)) entry.notes.push(item.text);
388
398
  return entry;
389
399
  }
@@ -415,12 +425,32 @@ export function createAgentResolver({ registry, limits = null } = {}) {
415
425
 
416
426
  const resolve = (ref, { projectPath = null } = {}) => resolveAgentRef(ref, { registry, projectPath });
417
427
 
428
+ function builtinTaskClass(definition, requestedClass) {
429
+ const [taskClass] = definition.taskClasses;
430
+ if (requestedClass && requestedClass !== taskClass) {
431
+ throw new AgentResolveError('AGENT_CLASS_MISMATCH', 409, `This bundled agent runs as ${taskClass}.`);
432
+ }
433
+ return taskClass;
434
+ }
435
+
418
436
  /** A definition applied to a spec, with its pin on the result. */
419
437
  function prepare(rawSpec, resolved, ctx = {}) {
420
438
  let extra = null;
421
439
  try { extra = typeof limits === 'function' ? limits({ ...ctx, rawSpec, definition: resolved.definition }) : limits; } catch { extra = null; }
422
440
  const applied = applyAgent(rawSpec, resolved.definition, { ...ctx, ref: resolved.ref, limits: { ...(isObject(extra) ? extra : {}), ...(isObject(ctx.limits) ? ctx.limits : {}) } });
441
+ if (resolved.definition.source === 'builtin' || ctx.classDefault) {
442
+ applied.spec.taskClass = ctx.classDefault || builtinTaskClass(resolved.definition, rawSpec.taskClass);
443
+ const ceiling = resolved.definition.capability;
444
+ const requestedLevel = String(applied.spec.capability).trim().toLowerCase();
445
+ if (!Object.hasOwn(CAPABILITY_RANK, requestedLevel) || CAPABILITY_RANK[requestedLevel] > CAPABILITY_RANK[ceiling]) {
446
+ applied.corrections.push(correction('capability', applied.spec.capability, ceiling, 'capability_ceiling',
447
+ `The bundled ${resolved.name} agent is limited to ${ceiling}.`));
448
+ applied.spec.capability = ceiling;
449
+ }
450
+ }
423
451
  applied.spec[AGENT_PIN] = {
452
+ ...(resolved.definition.source === 'builtin' ? { source: 'builtin' } : {}),
453
+ ...(ctx.classDefault ? { classDefault: ctx.classDefault } : {}),
424
454
  id: resolved.id, revision: resolved.revision, etag: resolved.etag, scope: resolved.scope, name: resolved.name || resolved.id,
425
455
  ref: resolved.ref, requested: resolved.requested || resolved.ref, status: resolved.definition.status,
426
456
  corrections: applied.corrections, filled: applied.filled,
@@ -436,7 +466,7 @@ export function createAgentResolver({ registry, limits = null } = {}) {
436
466
  */
437
467
  function intake(rawSpec = {}, ctx = {}) {
438
468
  const ref = agentRefOf(rawSpec);
439
- if (ref === undefined) return rawSpec;
469
+ if (ref === undefined || ref === 'none') return rawSpec;
440
470
  const resolved = resolve(ref, { projectPath: firstGiven(rawSpec.cwd, rawSpec.project) ?? null });
441
471
  return prepare(rawSpec, resolved, ctx);
442
472
  }
@@ -447,6 +477,7 @@ export function createAgentResolver({ registry, limits = null } = {}) {
447
477
  */
448
478
  function prepareRevision(rawSpec, definition, ctx = {}) {
449
479
  const def = normalizeAgentDefinition(definition);
480
+ if (definition.source === 'builtin') def.source = 'builtin';
450
481
  const checked = validateAgentDefinition(def);
451
482
  if (!checked.ok) throw new AgentResolveError('AGENT_NOT_VALID', 400, 'The definition has errors; fix them before running it.', { errors: checked.errors });
452
483
  return prepare(rawSpec, {
@@ -462,12 +493,16 @@ export function createAgentResolver({ registry, limits = null } = {}) {
462
493
  * @returns {object} the body, with such proposals filled (the same object when none names an agent)
463
494
  */
464
495
  function expandProposals(body = {}) {
465
- if (!isObject(body) || !Array.isArray(body.proposals) || !body.proposals.some((proposal) => agentRefOf(proposal) !== undefined)) return body;
496
+ if (!hasNamedProposal(body)) return body;
466
497
  const projectPath = firstGiven(body.cwd, body.project) ?? null;
498
+ let builtinClass;
467
499
  const proposals = body.proposals.map((proposal) => {
468
500
  const ref = agentRefOf(proposal);
469
- if (ref === undefined) return proposal;
501
+ if (ref === undefined || ref === 'none') return proposal;
470
502
  const resolved = resolve(ref, { projectPath });
503
+ if (resolved.definition.source === 'builtin') {
504
+ builtinClass = builtinTaskClass(resolved.definition, builtinClass || body.task_class || body.taskClass);
505
+ }
471
506
  const fields = dispatchFields(resolved.definition);
472
507
  const provider = given(proposal.provider) ? proposal.provider : fields.provider;
473
508
  const same = provider === fields.provider;
@@ -481,7 +516,7 @@ export function createAgentResolver({ registry, limits = null } = {}) {
481
516
  agent_ref: resolved.ref,
482
517
  };
483
518
  });
484
- return { ...body, proposals };
519
+ return { ...body, ...(builtinClass ? { task_class: builtinClass } : {}), proposals };
485
520
  }
486
521
 
487
522
  /**
@@ -502,6 +537,7 @@ export function createAgentResolver({ registry, limits = null } = {}) {
502
537
  ref: formatAgentRef({ id: agent.id, scope: agent.scope }), id: agent.id, name: agent.name, description: agent.description,
503
538
  provider: agent.provider, model: agent.model, effort: agent.effort, taskClasses: agent.taskClasses,
504
539
  scope: agent.scope.kind, ...(agent.scope.kind === 'project' ? { projectPath: agent.scope.path } : {}),
540
+ ...(agent.source ? { source: agent.source, status: 'approved' } : {}),
505
541
  revision: agent.approvedRevision, capability: agent.capability, usesBrowser: agent.usesBrowser, usesComputer: agent.usesComputer,
506
542
  });
507
543
  }
@@ -522,6 +558,24 @@ export function getAgentResolver() { return current; }
522
558
 
523
559
  const resolverOf = (agents) => { try { return (typeof agents === 'function' ? agents() : agents) || null; } catch { return null; } };
524
560
 
561
+ /** Resolve a worker role without contributing a runtime to the model router. Only implicit lookup is best effort. */
562
+ export function routedAgent(agents, taskClass, projectPath, requested, pinned = null) {
563
+ if (requested === 'none') return { meta: { agentRequest: 'none' } };
564
+ const resolver = resolverOf(agents);
565
+ const id = requested || pinned?.id || resolver?.registry?.builtinIdForClass?.(taskClass);
566
+ try {
567
+ if (!id || !resolver) throw new AgentResolveError('AGENTS_UNAVAILABLE', 503, 'No approved class agent is available.');
568
+ const resolved = pinned || resolver.resolve(id, { projectPath });
569
+ const meta = { agentRef: resolved.ref, agentRevision: resolved.revision, ...(requested ? { agentRequest: requested } : {}) };
570
+ return { resolved, resolver, meta };
571
+ } catch (error) {
572
+ if (requested) throw error;
573
+ const note = correction('agentRef', id || taskClass, null, 'class_agent_unavailable',
574
+ `The ${taskClass} worker will run without its default agent. ${error.message}`);
575
+ return { note };
576
+ }
577
+ }
578
+
525
579
  /**
526
580
  * The dispatcher's one call: `rawSpec` with the agent it names applied, or `rawSpec` itself when it names none.
527
581
  * A spec that names an agent on a server with no resolver is refused, never started as a plain worker.
@@ -529,7 +583,7 @@ const resolverOf = (agents) => { try { return (typeof agents === 'function' ? ag
529
583
  */
530
584
  export function agentIntake(agents, rawSpec = {}, ctx = {}) {
531
585
  const ref = agentRefOf(rawSpec);
532
- if (ref === undefined) return rawSpec;
586
+ if (ref === undefined || ref === 'none') return rawSpec;
533
587
  const resolver = resolverOf(agents);
534
588
  if (!resolver) throw new AgentResolveError('AGENTS_UNAVAILABLE', 503, 'This dispatch names an agent, and agents are not available on this server. Nothing was started.', { agentRef: ref.slice(0, 200) });
535
589
  return resolver.intake(rawSpec, ctx);
@@ -537,7 +591,12 @@ export function agentIntake(agents, rawSpec = {}, ctx = {}) {
537
591
 
538
592
  /** agent_route's proposals with their agents filled in; the body itself when there is nothing to fill. */
539
593
  export function expandAgentProposals(agents, body = {}) {
540
- if (!isObject(body) || !Array.isArray(body.proposals) || !body.proposals.some((proposal) => agentRefOf(proposal) !== undefined)) return body;
594
+ const requested = agentRefOf(body);
595
+ if (requested && Array.isArray(body.proposals)) {
596
+ body = { ...body, proposals: body.proposals.map(proposal =>
597
+ agentRefOf(proposal) || !isObject(proposal) ? proposal : { ...proposal, agent_ref: requested }) };
598
+ }
599
+ if (!hasNamedProposal(body)) return body;
541
600
  const resolver = resolverOf(agents);
542
601
  if (!resolver) throw new AgentResolveError('AGENTS_UNAVAILABLE', 503, 'A proposal names an agent, and agents are not available on this server.');
543
602
  return resolver.expandProposals(body);
@@ -2,11 +2,36 @@
2
2
  import { isAbsolute, resolve } from 'node:path';
3
3
  import { normalizeAgentDensity, maxWorkers } from './density.js';
4
4
  import { createGitRunner } from '../teams/git.js';
5
+ import { TEAM_LIMITS } from '../teams/schema.js';
6
+
7
+ /** One title limit for a route's planned_split and a team's slices: an approved split must always be startable. */
8
+ export const SPLIT_TITLE_MAX = TEAM_LIMITS.title;
9
+
10
+ /**
11
+ * A slice title as a route and a team compare it: runs of whitespace folded, trimmed, cut to the shared limit
12
+ * (never through a surrogate pair). A route stored before the limit may hold a longer title; the team's cut one equals it.
13
+ */
14
+ export function splitTitle(value) {
15
+ if (typeof value !== 'string') return '';
16
+ return value.replace(/\s+/g, ' ').trim().slice(0, SPLIT_TITLE_MAX).replace(/[\uD800-\uDBFF]$/, '').trimEnd();
17
+ }
5
18
 
6
19
  export const SPLIT_CLASSES = new Set(['code', 'complex', 'research', 'review']);
7
20
  const git = createGitRunner({ timeoutMs: 5000 });
8
21
  const fail = (code, message) => { throw Object.assign(new Error(message), { code, status: 400 }); };
9
22
 
23
+ /**
24
+ * Whether a re-route's planned_split asks for a different plan than the one a route holds (workers, titles as the
25
+ * team reads them, fewer reason). No split given, or a route whose project had no git commit, never counts.
26
+ */
27
+ export function splitChanged(raw, prior) {
28
+ if (!raw || typeof raw !== 'object' || !prior || prior.noRepo) return false;
29
+ const titles = Array.isArray(raw.slices) ? raw.slices.map(splitTitle) : [];
30
+ const reason = typeof raw.reason === 'string' ? raw.reason.trim() : '';
31
+ return raw.workers !== prior.workers || titles.length !== prior.slices.length
32
+ || titles.some((t, i) => t !== splitTitle(prior.slices[i])) || (reason || null) !== (prior.reason || null);
33
+ }
34
+
10
35
  export async function planRouteSplit(body, session, taskClass) {
11
36
  const density = normalizeAgentDensity(session.agentDensity);
12
37
  const target = maxWorkers(density);
@@ -21,14 +46,17 @@ export async function planRouteSplit(body, session, taskClass) {
21
46
  projectPath = resolve(body.cwd);
22
47
  const head = await git(['rev-parse', '--verify', 'HEAD'], { cwd: projectPath });
23
48
  if (!head.ok) return { density, target, workers: 1, slices: [String(body.summary || 'Task')],
24
- reason: 'The project is not a git repository with a commit; worktrees require one.', flow: 'single', projectPath };
49
+ reason: 'The project is not a git repository with a commit; worktrees require one.', flow: 'single', projectPath, noRepo: true };
25
50
  }
26
51
  if (!raw || typeof raw !== 'object') fail('ROUTE_SPLIT_REQUIRED', `Plan the implementation first, then pass planned_split with ${target} distinct slice titles, or fewer with a reason. Route the whole task once.`);
27
52
  const workers = raw.workers;
28
- const slices = Array.isArray(raw.slices) ? raw.slices.map(s => typeof s === 'string' ? s.trim() : '') : [];
53
+ // Normalised exactly as the team schema reads a slice title, so the same text is compared at start.
54
+ const slices = Array.isArray(raw.slices) ? raw.slices.map(s => typeof s === 'string' ? s.replace(/\s+/g, ' ').trim() : '') : [];
55
+ const long = slices.findIndex(s => s.length > SPLIT_TITLE_MAX);
56
+ if (long >= 0) fail('ROUTE_SPLIT_TITLE_TOO_LONG', `planned_split slice ${long + 1} has ${slices[long].length} characters; a slice title is at most ${SPLIT_TITLE_MAX} (agent_team uses the same titles). Shorten it and route again.`);
29
57
  const reason = typeof raw.reason === 'string' ? raw.reason.trim() : '';
30
- if (!Number.isInteger(workers) || workers < 1 || workers > target || slices.length !== workers || slices.some(s => !s || s.length > 200) || new Set(slices.map(s => s.toLowerCase())).size !== workers) {
31
- fail('ROUTE_SPLIT_INVALID', `planned_split needs 1–${target} workers and exactly that many distinct, nonempty slice titles (at most 200 characters each).`);
58
+ if (!Number.isInteger(workers) || workers < 1 || workers > target || slices.length !== workers || slices.some(s => !s) || new Set(slices.map(s => s.toLowerCase())).size !== workers) {
59
+ fail('ROUTE_SPLIT_INVALID', `planned_split needs 1–${target} workers and exactly that many distinct, nonempty slice titles (at most ${SPLIT_TITLE_MAX} characters each).`);
32
60
  }
33
61
  if (workers < target && !reason) fail('ROUTE_SPLIT_REASON_REQUIRED', `Using fewer than ${target} workers requires a short reason why this task cannot sensibly split further.`);
34
62
  if (reason.length > 400) fail('ROUTE_SPLIT_INVALID', 'The fewer-than-density reason must be at most 400 characters.');
@@ -7,6 +7,7 @@
7
7
  // composer attachments, Claude/Codex account management, and the sidepanel tab registry.
8
8
  // Mounted from server.js with `app.use('/api/assistant', createAssistantApi(deps))`.
9
9
 
10
+ import { assistantStopProvenance, pageStopProvenance, personAskedToStop } from './worker-stop.js';
10
11
  import { dispatchInput } from './assistant-tools.js';
11
12
  import { expandAgentProposals, getAgentResolver } from './agents/resolve.js'; // agents-p1
12
13
  import { Router } from 'express';
@@ -213,7 +214,7 @@ export function createAssistantApi({
213
214
  // identified (macOS, the lookup failed) never verifies: it is nobody here, and its refusals say 503
214
215
  // PEER_UNAVAILABLE (uiOnly, refuseRunRead) rather than a 403 the page could not cure.
215
216
  if (pageSession && typeof pageSession.verify === 'function' && !pageSession.verify(req)) return { kind: 'unknown', assistantSessionId: bodySession ? String(bodySession) : null, pin: '', pageless: true };
216
- return { kind: 'ui', assistantSessionId: bodySession ? String(bodySession) : null };
217
+ return { kind: 'ui', verifiedPage: typeof pageSession?.verify === 'function', assistantSessionId: bodySession ? String(bodySession) : null };
217
218
  }
218
219
  // The pin counts only with its proof: a forged one names nobody here, not even for attribution.
219
220
  let verdict = null;
@@ -921,9 +922,11 @@ export function createAssistantApi({
921
922
  if (!assistantSessionId && !workflowId && req.assistantCaller.kind !== 'ui') {
922
923
  return res.status(400).json({ ok: false, code: 'SCOPE_REQUIRED', error: 'Pass assistant_session_id (your ASSISTANT_SESSION_ID) or workflow_id to stop runs.' });
923
924
  }
924
- const reason = body.reason || 'kill_all';
925
- const result = await dispatcher.killAll({ assistantSessionId, workflowId, reason });
926
- // Who stopped every run, when: the records only say `kill_all` (2026-10-24 had to be traced by elimination).
925
+ const stopProvenance = { ...assistantStopProvenance(req.assistantCaller, body.action), scope: workflowId ? 'workflow' : assistantSessionId ? 'session' : 'all' };
926
+ // 'user' is recorded only for a control a person operated, whatever the request says.
927
+ const reason = body.reason && (body.reason !== 'user' || personAskedToStop(stopProvenance)) ? body.reason : 'kill_all';
928
+ const result = await dispatcher.killAll({ assistantSessionId, workflowId, reason, stopProvenance });
929
+ // Keep the scope in the operational log as well as provenance on each stopped run.
927
930
  const caller = req.assistantCaller.kind === 'ui' ? 'the page' : `the brain of ${req.assistantCaller.assistantSessionId || 'an unknown session'}`;
928
931
  const scope = [assistantSessionId ? `session ${assistantSessionId}` : null, workflowId ? `workflow ${workflowId}` : null].filter(Boolean).join(', ') || 'every session';
929
932
  const stopped = Array.isArray(result?.stopped) ? result.stopped : [];
@@ -1040,7 +1043,7 @@ export function createAssistantApi({
1040
1043
  // A run whose provider share is used up: the session's unspent budget is divided again first, then
1041
1044
  // sendTurn decides (it refuses with BUDGET_SHARE_EXHAUSTED when no money could move).
1042
1045
  try { await dispatcher.coverFollowUp?.(req.params.runId); } catch { /* sendTurn decides on the shares as they are */ }
1043
- res.json(dispatcher.sendTurn(req.params.runId, body.text ?? body.message, { origin, queue: body.queue !== false }));
1046
+ res.json(await dispatcher.sendTurn(req.params.runId, body.text ?? body.message, { origin, queue: body.queue !== false }));
1044
1047
  } catch (error) { sendError(res, error); }
1045
1048
  });
1046
1049
  router.post('/runs/:runId/permission', orchestrationGuard, (req, res) => {
@@ -1067,7 +1070,13 @@ export function createAssistantApi({
1067
1070
  } catch (error) { sendError(res, error); }
1068
1071
  });
1069
1072
  router.post('/runs/:runId/stop', orchestrationGuard, async (req, res) => {
1070
- try { res.json(await dispatcher.stop(req.params.runId, req.body?.reason || (req.assistantCaller.kind === 'ui' ? 'user' : 'assistant'))); } catch (error) { sendError(res, error); }
1073
+ const caller = req.assistantCaller;
1074
+ const stopProvenance = assistantStopProvenance(caller, req.body?.action);
1075
+ // 'user' is recorded only for a control a person operated, whatever the request says.
1076
+ const said = typeof req.body?.reason === 'string' ? req.body.reason.trim() : '';
1077
+ const person = personAskedToStop(stopProvenance);
1078
+ const reason = said && (said !== 'user' || person) ? said : person ? 'user' : caller.credentialed ? 'assistant' : 'unknown';
1079
+ try { res.json(await dispatcher.stop(req.params.runId, reason, stopProvenance)); } catch (error) { sendError(res, error); }
1071
1080
  });
1072
1081
  // Finished runs are cleared from the agents tray by the owner (the page) or the Assistant brain of the run's
1073
1082
  // own session; never by a worker (even its own run). A brain's delete is scoped to its session's runs.
@@ -1102,8 +1111,10 @@ export function createAssistantApi({
1102
1111
  // The user closed the sidepanel tab of a worker that finished its task: completed, never "stopped
1103
1112
  // by the user" (409 RUN_NOT_FINISHED for any other run, which the tab then stops as before).
1104
1113
  router.post('/runs/:runId/tab-closed', (req, res) => {
1105
- if (callerContext(req).kind !== 'ui') return uiOnly(req, res, 'Only the sidepanel that closed the tab reports it.');
1106
- try { res.json(dispatcher.completeClosedTab(req.params.runId)); } catch (error) { sendError(res, error); }
1114
+ const caller = callerContext(req);
1115
+ if (caller.kind !== 'ui') return uiOnly(req, res, 'Only the sidepanel that closed the tab reports it.');
1116
+ const action = req.body?.action === 'tray_auto_close' ? 'tray_auto_close' : 'tab_close';
1117
+ try { res.json(dispatcher.completeClosedTab(req.params.runId, pageStopProvenance(action, caller.verifiedPage))); } catch (error) { sendError(res, error); }
1107
1118
  });
1108
1119
  router.post('/runs/:runId/focus', (req, res) => {
1109
1120
  const run = dispatcher.get(req.params.runId);
@@ -119,6 +119,8 @@ export function createClaudeBrain({ session, sink, deps = {}, persona = '', hook
119
119
  // are CLI-oriented (greeting, loop driver, stop nudges) and are not loaded.
120
120
  settingSources: Array.isArray(deps.settingSources) ? deps.settingSources : ['user'],
121
121
  hooks: hooks || undefined,
122
+ // A resumed conversation must discover SynaBun's current tools after a server update.
123
+ synabunDiscoveryCache: false,
122
124
  mcpHeaders: {
123
125
  'X-Synabun-Role': 'assistant', 'X-Synabun-Terminal': session.id, 'X-Synabun-Memory-Session': session.id,
124
126
  ...(deps.desktopGrant ? { 'X-Synabun-Desktop-Grant': deps.desktopGrant } : {}),
@@ -209,6 +209,22 @@ export function createOpenCodeBrain({ session, sink, deps = {}, persona = '' } =
209
209
  let synabunExpected = false;
210
210
  let stops = 0;
211
211
  let waitingAbort = null;
212
+ let interruptPrompt = null;
213
+ let exited = false;
214
+ const serveExitMessage = 'The isolated OpenCode server stopped during this turn. Send the message again to resume.';
215
+ const serveExitError = () => Object.assign(new Error(serveExitMessage), { code: 'OPENCODE_SERVE_EXITED' });
216
+ const serveExited = () => exited || entry?.proc?.exitCode != null || entry?.proc?.signalCode != null;
217
+ function onServeExit() {
218
+ if (disposed) return;
219
+ exited = true;
220
+ clearInterval(keepAliveTimer);
221
+ waitingAbort?.abort();
222
+ interruptPrompt?.();
223
+ if (!turnActive && !pendingControls.size) return;
224
+ turnActive = false;
225
+ pendingControls.clear();
226
+ emit({ type: 'error', message: serveExitMessage });
227
+ }
212
228
  const mcpWait = {
213
229
  readyTimeoutMs: deps.mcpReadyTimeoutMs, settleMs: deps.mcpSettleMs,
214
230
  listGraceMs: deps.mcpListGraceMs, pollMs: deps.mcpPollMs,
@@ -240,11 +256,14 @@ export function createOpenCodeBrain({ session, sink, deps = {}, persona = '' } =
240
256
  const tool = packet.request?.tool_name;
241
257
  if (decision === 'deny') sink.send({ type: 'stderr', text: `Plan mode: declined ${tool || 'permission'}${remoteReadOnly ? ' (read-only)' : ' (no code changes)'}` });
242
258
  Promise.resolve(client.permission.reply({ requestID: body.requestID, reply: body.reply, directory: cwd, ...(decision === 'deny' ? { message: remoteReadOnly ? readOnlyDenyMessage(tool) : planDenyMessage(tool, { host: 'opencode' }) } : {}) }))
243
- .catch((error) => sink.send({ type: 'error', message: `OpenCode auto-${decision === 'allow' ? 'accept' : 'decline'} failed: ${error?.message || error}` }));
259
+ .catch((error) => { if (!serveExited()) emit({ type: 'error', message: `OpenCode auto-${decision === 'allow' ? 'accept' : 'decline'} failed: ${error?.message || error}` }); });
244
260
  return;
245
261
  }
246
262
  if (packet.type === 'control_request') pendingControls.set(packet.request_id, packet);
247
- if (packet.type === 'done' || packet.type === 'aborted') turnActive = false;
263
+ if (packet.type === 'done' || packet.type === 'aborted') {
264
+ turnActive = false;
265
+ pendingControls.clear();
266
+ }
248
267
  sink.send(packet);
249
268
  };
250
269
  sink.send({ type: 'engine', engine: 'opencode', brain: 'opencode' });
@@ -257,7 +276,9 @@ export function createOpenCodeBrain({ session, sink, deps = {}, persona = '' } =
257
276
  });
258
277
  if (unsubscribe) { try { unsubscribe(); } catch {} }
259
278
  const source = client?.onEvent ? client : client?.event;
260
- unsubscribe = source?.onEvent?.((envelope) => translator.handle(envelope?.eventType || '', envelope?.event || {})) || null;
279
+ unsubscribe = source?.onEvent?.((envelope) => {
280
+ if (!disposed && !serveExited()) translator.handle(envelope?.eventType || '', envelope?.event || {});
281
+ }) || null;
261
282
  }
262
283
 
263
284
  /** The serve's MCP servers as an `mcp_status` event (the runtime reads whether SynaBun, and so agent_route, is reachable). */
@@ -285,6 +306,7 @@ export function createOpenCodeBrain({ session, sink, deps = {}, persona = '' } =
285
306
  // the assistant and plan agents): the brain's serve never reads it.
286
307
  entry = await deps.ensureIsolatedServe(termId, { xdgRoot, keepAlive: true, tools: brain.tools ?? OPENCODE_BRAIN_TOOLS, brainCredential: deps.brainCredential || null, extraEnv: { OPENCODE_CONFIG_DIR: null } });
287
308
  if (!entry?.client) throw new Error('OpenCode isolated serve failed to start');
309
+ entry.proc?.once?.('exit', onServeExit);
288
310
  client = entry.client;
289
311
  await client.waitUntilConnected?.(20_000);
290
312
  if (!sessionId) {
@@ -298,6 +320,7 @@ export function createOpenCodeBrain({ session, sink, deps = {}, persona = '' } =
298
320
  keepAliveTimer = setInterval(() => { if (entry) entry.lastUsed = Date.now(); }, 60_000);
299
321
  keepAliveTimer.unref?.();
300
322
  await reportMcpStatus();
323
+ if (serveExited()) throw new Error('The isolated OpenCode server stopped during startup');
301
324
  return true;
302
325
  })();
303
326
  return startPromise;
@@ -305,11 +328,13 @@ export function createOpenCodeBrain({ session, sink, deps = {}, persona = '' } =
305
328
 
306
329
  return {
307
330
  kind: 'opencode',
331
+ needsRestart: serveExited,
308
332
  start,
309
333
  async sendUserTurn({ text, images = [], model = null, effort = null, permissionMode: mode = null, planMode: plan = null } = {}) {
310
334
  const stop = stops;
311
335
  await start();
312
336
  if (disposed || stops !== stop) return false;
337
+ if (serveExited()) throw serveExitError();
313
338
  applyModes(mode, plan);
314
339
  turnActive = true;
315
340
  // The runtime passes the effective model/effort on every turn (the record
@@ -344,15 +369,37 @@ export function createOpenCodeBrain({ session, sink, deps = {}, persona = '' } =
344
369
  onTimeout: (ms) => sink.send({ type: 'event', event: { type: 'system', subtype: 'status', text: synabunToolsTimeoutText(ms, 'brain') } }),
345
370
  });
346
371
  } finally { if (waitingAbort === controller) waitingAbort = null; }
347
- if (!ready || disposed || stops !== stop) { turnActive = false; return false; }
348
- const response = await client.session.promptAsync(request);
349
- const status = Number(response?.status);
350
- if (Number.isFinite(status) && status >= 400) { turnActive = false; throw new Error(`OpenCode prompt failed (${status})`); }
351
- return true;
372
+ if (disposed || stops !== stop) return false;
373
+ if (serveExited()) throw serveExitError();
374
+ if (!ready) { turnActive = false; return false; }
375
+ // A process exit releases this send even if the client is still waiting for a response.
376
+ const interrupted = new Promise((resolve) => {
377
+ interruptPrompt = () => { controller.abort(); resolve(); };
378
+ });
379
+ try {
380
+ const response = await Promise.race([client.session.promptAsync({ ...request, signal: controller.signal }), interrupted]);
381
+ if (disposed || stops !== stop) return false;
382
+ if (serveExited()) throw serveExitError();
383
+ const status = Number(response?.status);
384
+ if (Number.isFinite(status) && status >= 400) throw new Error(`OpenCode prompt failed (${status})`);
385
+ return true;
386
+ } catch (error) {
387
+ if (disposed || stops !== stop) return false;
388
+ turnActive = false;
389
+ pendingControls.clear();
390
+ throw serveExited() ? serveExitError() : error;
391
+ } finally { interruptPrompt = null; }
392
+ },
393
+ async abort() {
394
+ stops += 1;
395
+ waitingAbort?.abort();
396
+ if (serveExited()) return;
397
+ try { if (client && sessionId) await client.session.abort({ sessionID: sessionId, directory: cwd }); } catch {}
398
+ if (!serveExited()) emit({ type: 'aborted' });
352
399
  },
353
- async abort() { stops += 1; waitingAbort?.abort(); if (client && sessionId) await client.session.abort({ sessionID: sessionId, directory: cwd }).catch(() => {}); emit({ type: 'aborted' }); },
354
400
  async setPermissionMode(mode, { planMode: plan = null } = {}) { applyModes(mode, plan); sink.send({ type: 'mode_changed', mode: approvalMode, planMode }); },
355
401
  respondControl(requestId, response) {
402
+ if (serveExited()) return;
356
403
  const pending = pendingControls.get(String(requestId));
357
404
  if (!pending || !client) { sink.send({ type: 'error', message: `No pending OpenCode request ${requestId}` }); return; }
358
405
  pendingControls.delete(String(requestId));
@@ -360,7 +407,7 @@ export function createOpenCodeBrain({ session, sink, deps = {}, persona = '' } =
360
407
  const call = body.kind === 'question'
361
408
  ? (body.reject ? client.question.reject({ requestID: body.requestID, directory: cwd }) : client.question.reply({ requestID: body.requestID, answers: body.answers, directory: cwd }))
362
409
  : client.permission.reply({ requestID: body.requestID, reply: body.reply, directory: cwd });
363
- Promise.resolve(call).catch((error) => sink.send({ type: 'error', message: `OpenCode reply failed: ${error?.message || error}` }));
410
+ Promise.resolve(call).catch((error) => { if (!serveExited()) emit({ type: 'error', message: `OpenCode reply failed: ${error?.message || error}` }); });
364
411
  },
365
412
  // OpenCode compacts the session on the model it runs on.
366
413
  async compact() {
@@ -370,7 +417,7 @@ export function createOpenCodeBrain({ session, sink, deps = {}, persona = '' } =
370
417
  },
371
418
  async mcpStatus() { await reportMcpStatus(); },
372
419
  async reconcileUsage(meter) {
373
- if (!client || !sessionId || !meter) return false;
420
+ if (!client || !sessionId || !meter || serveExited()) return false;
374
421
  let failed = false;
375
422
  await meter.reconcile({
376
423
  children: async (id) => {
@@ -402,7 +449,9 @@ export function createOpenCodeBrain({ session, sink, deps = {}, persona = '' } =
402
449
  async dispose() {
403
450
  if (disposed) return;
404
451
  disposed = true;
452
+ entry?.proc?.off?.('exit', onServeExit);
405
453
  waitingAbort?.abort();
454
+ interruptPrompt?.();
406
455
  if (keepAliveTimer) clearInterval(keepAliveTimer);
407
456
  if (unsubscribe) { try { unsubscribe(); } catch {} }
408
457
  try { deps.stopIsolatedServe(termId); } catch {}