synabun 2.4.1 → 2.4.3

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 (345) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/README.md +1 -1
  3. package/docs/browser-extension-bridge.md +46 -6
  4. package/lib/data-home-files.js +4 -2
  5. package/lib/first-launch-protection.js +8 -2
  6. package/lib/release-npm-ci.mjs +23 -1
  7. package/lib/update-snapshot.js +11 -4
  8. package/mcp-server/dist/http.d.ts.map +1 -1
  9. package/mcp-server/dist/http.js +25 -2
  10. package/mcp-server/dist/http.js.map +1 -1
  11. package/mcp-server/dist/index.d.ts.map +1 -1
  12. package/mcp-server/dist/index.js +62 -17
  13. package/mcp-server/dist/index.js.map +1 -1
  14. package/mcp-server/dist/services/browser-bench.d.ts +22 -22
  15. package/mcp-server/dist/services/memory-maintenance.d.ts +1 -0
  16. package/mcp-server/dist/services/memory-maintenance.d.ts.map +1 -1
  17. package/mcp-server/dist/services/memory-maintenance.js +34 -45
  18. package/mcp-server/dist/services/memory-maintenance.js.map +1 -1
  19. package/mcp-server/dist/services/memory-migration-copy.d.ts +144 -0
  20. package/mcp-server/dist/services/memory-migration-copy.d.ts.map +1 -0
  21. package/mcp-server/dist/services/memory-migration-copy.js +467 -0
  22. package/mcp-server/dist/services/memory-migration-copy.js.map +1 -0
  23. package/mcp-server/dist/services/memory-migration-worker.d.ts +2 -0
  24. package/mcp-server/dist/services/memory-migration-worker.d.ts.map +1 -0
  25. package/mcp-server/dist/services/memory-migration-worker.js +60 -0
  26. package/mcp-server/dist/services/memory-migration-worker.js.map +1 -0
  27. package/mcp-server/dist/services/memory-retrieval.d.ts +4 -0
  28. package/mcp-server/dist/services/memory-retrieval.d.ts.map +1 -1
  29. package/mcp-server/dist/services/memory-retrieval.js +188 -40
  30. package/mcp-server/dist/services/memory-retrieval.js.map +1 -1
  31. package/mcp-server/dist/services/memory-schema.d.ts +58 -2
  32. package/mcp-server/dist/services/memory-schema.d.ts.map +1 -1
  33. package/mcp-server/dist/services/memory-schema.js +190 -13
  34. package/mcp-server/dist/services/memory-schema.js.map +1 -1
  35. package/mcp-server/dist/services/memory-sessions.d.ts +19 -1
  36. package/mcp-server/dist/services/memory-sessions.d.ts.map +1 -1
  37. package/mcp-server/dist/services/memory-sessions.js +56 -20
  38. package/mcp-server/dist/services/memory-sessions.js.map +1 -1
  39. package/mcp-server/dist/services/memory-verification.d.ts.map +1 -1
  40. package/mcp-server/dist/services/memory-verification.js +8 -5
  41. package/mcp-server/dist/services/memory-verification.js.map +1 -1
  42. package/mcp-server/dist/services/neural-interface.d.ts +5 -0
  43. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  44. package/mcp-server/dist/services/neural-interface.js +19 -2
  45. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  46. package/mcp-server/dist/services/retrieval-reader-worker.d.ts +2 -0
  47. package/mcp-server/dist/services/retrieval-reader-worker.d.ts.map +1 -0
  48. package/mcp-server/dist/services/retrieval-reader-worker.js +76 -0
  49. package/mcp-server/dist/services/retrieval-reader-worker.js.map +1 -0
  50. package/mcp-server/dist/services/retrieval-reader.d.ts +38 -0
  51. package/mcp-server/dist/services/retrieval-reader.d.ts.map +1 -0
  52. package/mcp-server/dist/services/retrieval-reader.js +145 -0
  53. package/mcp-server/dist/services/retrieval-reader.js.map +1 -0
  54. package/mcp-server/dist/services/sqlite-write.d.ts +14 -0
  55. package/mcp-server/dist/services/sqlite-write.d.ts.map +1 -0
  56. package/mcp-server/dist/services/sqlite-write.js +94 -0
  57. package/mcp-server/dist/services/sqlite-write.js.map +1 -0
  58. package/mcp-server/dist/services/sqlite.d.ts +39 -0
  59. package/mcp-server/dist/services/sqlite.d.ts.map +1 -1
  60. package/mcp-server/dist/services/sqlite.js +249 -8
  61. package/mcp-server/dist/services/sqlite.js.map +1 -1
  62. package/mcp-server/dist/services/tool-catalog.d.ts +1 -1
  63. package/mcp-server/dist/services/typesafe-config.d.ts +7 -1
  64. package/mcp-server/dist/services/typesafe-config.d.ts.map +1 -1
  65. package/mcp-server/dist/services/typesafe-config.js +32 -10
  66. package/mcp-server/dist/services/typesafe-config.js.map +1 -1
  67. package/mcp-server/dist/services/typesafe.d.ts.map +1 -1
  68. package/mcp-server/dist/services/typesafe.js +9 -7
  69. package/mcp-server/dist/services/typesafe.js.map +1 -1
  70. package/mcp-server/dist/services/vector-cache.d.ts +32 -0
  71. package/mcp-server/dist/services/vector-cache.d.ts.map +1 -1
  72. package/mcp-server/dist/services/vector-cache.js +161 -8
  73. package/mcp-server/dist/services/vector-cache.js.map +1 -1
  74. package/mcp-server/dist/tools/agent-definition.d.ts +2 -2
  75. package/mcp-server/dist/tools/agents.d.ts +11 -7
  76. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  77. package/mcp-server/dist/tools/agents.js +27 -9
  78. package/mcp-server/dist/tools/agents.js.map +1 -1
  79. package/mcp-server/dist/tools/browser-advanced.d.ts +1 -1
  80. package/mcp-server/dist/tools/browser-advanced.d.ts.map +1 -1
  81. package/mcp-server/dist/tools/browser-advanced.js +10 -3
  82. package/mcp-server/dist/tools/browser-advanced.js.map +1 -1
  83. package/mcp-server/dist/tools/browser-extension-setup.d.ts +5 -0
  84. package/mcp-server/dist/tools/browser-extension-setup.d.ts.map +1 -0
  85. package/mcp-server/dist/tools/browser-extension-setup.js +29 -0
  86. package/mcp-server/dist/tools/browser-extension-setup.js.map +1 -0
  87. package/mcp-server/dist/tools/browser-interact.d.ts.map +1 -1
  88. package/mcp-server/dist/tools/browser-interact.js +6 -1
  89. package/mcp-server/dist/tools/browser-interact.js.map +1 -1
  90. package/mcp-server/dist/tools/fb-groups.d.ts +2 -2
  91. package/mcp-server/dist/tools/skill-tools.d.ts +4 -4
  92. package/mcp-server/dist/tools/tool-groups.d.ts +1 -1
  93. package/mcp-server/package-lock.json +5 -5
  94. package/mcp-server/package.json +1 -1
  95. package/mcp-server/src/http.ts +20 -2
  96. package/mcp-server/src/index.ts +59 -17
  97. package/mcp-server/src/services/memory-maintenance.ts +31 -28
  98. package/mcp-server/src/services/memory-migration-copy.ts +419 -0
  99. package/mcp-server/src/services/memory-migration-worker.ts +55 -0
  100. package/mcp-server/src/services/memory-retrieval.ts +173 -32
  101. package/mcp-server/src/services/memory-schema.ts +194 -12
  102. package/mcp-server/src/services/memory-sessions.ts +54 -21
  103. package/mcp-server/src/services/memory-verification.ts +7 -4
  104. package/mcp-server/src/services/neural-interface.ts +22 -2
  105. package/mcp-server/src/services/retrieval-reader-worker.ts +67 -0
  106. package/mcp-server/src/services/retrieval-reader.ts +131 -0
  107. package/mcp-server/src/services/sqlite-write.ts +60 -0
  108. package/mcp-server/src/services/sqlite.ts +246 -8
  109. package/mcp-server/src/services/typesafe-config.ts +25 -6
  110. package/mcp-server/src/services/typesafe.ts +9 -7
  111. package/mcp-server/src/services/vector-cache.ts +154 -9
  112. package/mcp-server/src/tools/agents.ts +26 -9
  113. package/mcp-server/src/tools/browser-advanced.ts +10 -3
  114. package/mcp-server/src/tools/browser-extension-setup.ts +36 -0
  115. package/mcp-server/src/tools/browser-interact.ts +5 -1
  116. package/neural-interface/i18n/en.json +313 -2
  117. package/neural-interface/i18n/pt-BR.json +321 -10
  118. package/neural-interface/lib/agents/split.js +32 -4
  119. package/neural-interface/lib/assistant-api.js +52 -8
  120. package/neural-interface/lib/assistant-brains/claude.js +2 -0
  121. package/neural-interface/lib/assistant-brains/opencode.js +121 -7
  122. package/neural-interface/lib/assistant-catalog.js +2 -2
  123. package/neural-interface/lib/assistant-config.js +0 -7
  124. package/neural-interface/lib/assistant-dispatch.js +281 -95
  125. package/neural-interface/lib/assistant-envelope.js +40 -0
  126. package/neural-interface/lib/assistant-persona.js +16 -4
  127. package/neural-interface/lib/assistant-pricing.js +65 -14
  128. package/neural-interface/lib/assistant-router.js +131 -47
  129. package/neural-interface/lib/assistant-run-wait.js +45 -28
  130. package/neural-interface/lib/assistant-runtime.js +133 -42
  131. package/neural-interface/lib/backup-contents.js +158 -0
  132. package/neural-interface/lib/backup-crypto-io.js +330 -0
  133. package/neural-interface/lib/backup-crypto-worker.js +130 -0
  134. package/neural-interface/lib/backup-crypto.js +525 -0
  135. package/neural-interface/lib/backup-download.js +268 -0
  136. package/neural-interface/lib/backup-encryption.js +318 -0
  137. package/neural-interface/lib/backup-groups.js +287 -0
  138. package/neural-interface/lib/backup-restore-session.js +176 -0
  139. package/neural-interface/lib/backup-restore-stage.js +60 -0
  140. package/neural-interface/lib/backup-service.js +788 -233
  141. package/neural-interface/lib/backup-zip-reader.js +30 -18
  142. package/neural-interface/lib/backup-zip-writer.js +34 -10
  143. package/neural-interface/lib/browser-extension-adapter.js +89 -15
  144. package/neural-interface/lib/browser-extension-archive.js +149 -0
  145. package/neural-interface/lib/browser-extension-bridge.js +24 -10
  146. package/neural-interface/lib/browser-extension-folder.js +596 -76
  147. package/neural-interface/lib/browser-extension-package.js +200 -0
  148. package/neural-interface/lib/browser-extension-pin.js +84 -0
  149. package/neural-interface/lib/browser-extension-pin.json +33 -0
  150. package/{browser-extension/protocol.js → neural-interface/lib/browser-extension-protocol.js} +91 -6
  151. package/neural-interface/lib/browser-extension-setup.js +105 -18
  152. package/neural-interface/lib/claude-agent-bridge.js +1 -0
  153. package/neural-interface/lib/claude-session-cleanup.js +5 -1
  154. package/neural-interface/lib/cli-install.js +23 -3
  155. package/neural-interface/lib/cli-update-planner.js +171 -9
  156. package/neural-interface/lib/client-diagnostics.js +42 -0
  157. package/neural-interface/lib/confined-fs.js +7 -2
  158. package/neural-interface/lib/coordination/README.md +8 -2
  159. package/neural-interface/lib/coordination/contract.js +161 -0
  160. package/neural-interface/lib/coordination/database.js +999 -0
  161. package/neural-interface/lib/coordination/operations.js +436 -0
  162. package/neural-interface/lib/coordination/service.js +68 -537
  163. package/neural-interface/lib/coordination/storage-worker.js +101 -0
  164. package/neural-interface/lib/coordination/store.js +219 -1111
  165. package/neural-interface/lib/db.js +70 -32
  166. package/neural-interface/lib/health-count.js +37 -0
  167. package/neural-interface/lib/loop-stall.js +139 -0
  168. package/neural-interface/lib/maritaca/client.js +2 -2
  169. package/neural-interface/lib/maritaca/models.js +12 -17
  170. package/neural-interface/lib/maritaca/opencode.js +4 -2
  171. package/neural-interface/lib/memory-api.js +9 -1
  172. package/neural-interface/lib/memory-session-capture.js +42 -10
  173. package/neural-interface/lib/memory-store-gate.js +313 -0
  174. package/neural-interface/lib/memory-store-migrate.js +65 -0
  175. package/neural-interface/lib/memory-timers.js +7 -7
  176. package/neural-interface/lib/native-loop-providers.js +23 -17
  177. package/neural-interface/lib/native-loop-runtime.js +48 -9
  178. package/neural-interface/lib/opencode-build-preflight.js +18 -1
  179. package/neural-interface/lib/opencode-native-boundary.js +69 -8
  180. package/neural-interface/lib/opencode-provider-view.js +14 -3
  181. package/neural-interface/lib/opencode-shell-read.js +107 -0
  182. package/neural-interface/lib/opencode-stop-failures.js +40 -0
  183. package/neural-interface/lib/opencode-turn-release.js +173 -0
  184. package/neural-interface/lib/opencode-v2-client.js +4 -1
  185. package/neural-interface/lib/opencode-v2-ws-requests.js +65 -1
  186. package/neural-interface/lib/opencode2-client.js +343 -7
  187. package/neural-interface/lib/opencode2-translate.js +161 -4
  188. package/neural-interface/lib/recall-impact.js +122 -0
  189. package/neural-interface/lib/scratch-evidence.js +420 -0
  190. package/neural-interface/lib/scratch-process-guard.js +139 -0
  191. package/neural-interface/lib/scratch-references.js +279 -0
  192. package/neural-interface/lib/scratch-retention-core.js +385 -0
  193. package/neural-interface/lib/scratch-retention-worker.js +37 -0
  194. package/neural-interface/lib/scratch-retention.js +151 -0
  195. package/neural-interface/lib/session-cache-builder.js +31 -43
  196. package/neural-interface/lib/session-cache-worker.js +157 -0
  197. package/neural-interface/lib/session-indexer.js +28 -21
  198. package/neural-interface/lib/session-search-index.js +85 -0
  199. package/neural-interface/lib/skills/creation.js +1 -1
  200. package/neural-interface/lib/sqlite-integrity-worker.js +3 -1
  201. package/neural-interface/lib/style-guide/store.js +43 -3
  202. package/neural-interface/lib/system-restore.js +50 -0
  203. package/neural-interface/lib/teams/api.js +15 -6
  204. package/neural-interface/lib/teams/claims.js +67 -31
  205. package/neural-interface/lib/teams/index.js +7 -7
  206. package/neural-interface/lib/teams/integration.js +40 -40
  207. package/neural-interface/lib/teams/landing.js +6 -6
  208. package/neural-interface/lib/teams/recovery.js +24 -23
  209. package/neural-interface/lib/teams/scheduler.js +194 -95
  210. package/neural-interface/lib/teams/state.js +14 -14
  211. package/neural-interface/lib/teams/worktrees.js +27 -27
  212. package/neural-interface/lib/terminal-token-redaction.js +83 -0
  213. package/neural-interface/lib/whatsapp/bridge.js +54 -7
  214. package/neural-interface/lib/worker-confinement.js +47 -2
  215. package/neural-interface/lib/worker-mcp-channel.js +2 -0
  216. package/neural-interface/lib/worker-resume.js +5 -0
  217. package/neural-interface/lib/worker-stop.js +86 -0
  218. package/neural-interface/package-lock.json +5 -5
  219. package/neural-interface/package.json +1 -1
  220. package/neural-interface/public/extension-setup.html +5 -2
  221. package/neural-interface/public/index.html +233 -24
  222. package/neural-interface/public/onboarding.html +259 -34
  223. package/neural-interface/public/shared/agents/studio/ax-library.js +0 -6
  224. package/neural-interface/public/shared/agents/studio/ax-main.js +14 -7
  225. package/neural-interface/public/shared/agy/agy-options.js +11 -0
  226. package/neural-interface/public/shared/agy/agy-panel.js +67 -20
  227. package/neural-interface/public/shared/agy/agy-styles.js +14 -12
  228. package/neural-interface/public/shared/agy/agy-tabs-logic.js +4 -1
  229. package/neural-interface/public/shared/api.js +1 -1
  230. package/neural-interface/public/shared/assistant/asst-api.js +28 -3
  231. package/neural-interface/public/shared/assistant/asst-brain-picker.js +13 -6
  232. package/neural-interface/public/shared/assistant/asst-control.js +2 -0
  233. package/neural-interface/public/shared/assistant/asst-motion-gate.js +78 -4
  234. package/neural-interface/public/shared/assistant/asst-panel.js +87 -3
  235. package/neural-interface/public/shared/assistant/asst-rack-styles.js +27 -0
  236. package/neural-interface/public/shared/assistant/asst-render.js +243 -44
  237. package/neural-interface/public/shared/assistant/asst-route.js +100 -21
  238. package/neural-interface/public/shared/assistant/asst-routes-editor.js +1 -1
  239. package/neural-interface/public/shared/assistant/asst-shell-logic.js +200 -0
  240. package/neural-interface/public/shared/assistant/asst-shell.js +111 -0
  241. package/neural-interface/public/shared/assistant/asst-sidepanel.js +4 -2
  242. package/neural-interface/public/shared/assistant/asst-state.js +11 -0
  243. package/neural-interface/public/shared/assistant/asst-styles.js +11 -23
  244. package/neural-interface/public/shared/assistant/route-identity.js +2 -1
  245. package/neural-interface/public/shared/cdx/cdx-render.js +9 -0
  246. package/neural-interface/public/shared/cdx/cdx-settings.js +3 -1
  247. package/neural-interface/public/shared/cdx/cdx-styles.js +6 -0
  248. package/neural-interface/public/shared/cdx/cdx-tabs.js +54 -9
  249. package/neural-interface/public/shared/client-diagnostics.js +94 -0
  250. package/neural-interface/public/shared/cp/cp-markdown.js +7 -2
  251. package/neural-interface/public/shared/cp/cp-styles.js +1 -1
  252. package/neural-interface/public/shared/effort-i18n.js +118 -0
  253. package/neural-interface/public/shared/extension-setup/es-page.js +10 -4
  254. package/neural-interface/public/shared/extension-setup/es-view.js +25 -10
  255. package/neural-interface/public/shared/html-shell.js +4 -52
  256. package/neural-interface/public/shared/loading-diagnostic-entry.js +64 -0
  257. package/neural-interface/public/shared/memory-store-wait.js +52 -0
  258. package/neural-interface/public/shared/morelogin-profile-field.js +1 -1
  259. package/neural-interface/public/shared/mtc/mtc-logic.js +2 -1
  260. package/neural-interface/public/shared/mtc/mtc-panel.js +25 -3
  261. package/neural-interface/public/shared/mtc/mtc-styles.js +13 -12
  262. package/neural-interface/public/shared/ocp-v2/ocp-v2-childpanel.js +7 -0
  263. package/neural-interface/public/shared/ocp-v2/ocp-v2-events.js +5 -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-manager.js +1 -0
  266. package/neural-interface/public/shared/ocp-v2/ocp-v2-modelpicker.js +8 -1
  267. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +152 -8
  268. package/neural-interface/public/shared/ocp-v2/ocp-v2-rehydrate.js +7 -1
  269. package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +53 -4
  270. package/neural-interface/public/shared/ocp-v2/ocp-v2-send.js +52 -6
  271. package/neural-interface/public/shared/ocp-v2/ocp-v2-session-actions.js +22 -2
  272. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell-block.js +165 -0
  273. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell-logic.js +346 -0
  274. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell.js +108 -0
  275. package/neural-interface/public/shared/ocp-v2/ocp-v2-state.js +49 -3
  276. package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +67 -93
  277. package/neural-interface/public/shared/ocp-v2/ocp-v2-tools-logic.js +20 -5
  278. package/neural-interface/public/shared/ocp-v2/ocp-v2-tools.js +7 -1
  279. package/neural-interface/public/shared/ocp-v2/ocp-v2-variantpicker.js +17 -6
  280. package/neural-interface/public/shared/ocp-v2/ocp-v2-ws.js +7 -2
  281. package/neural-interface/public/shared/output-format.js +294 -0
  282. package/neural-interface/public/shared/provider-icons.js +6 -0
  283. package/neural-interface/public/shared/schedules-view.js +2 -1
  284. package/neural-interface/public/shared/server-presence.js +77 -0
  285. package/neural-interface/public/shared/settings/settings-backup-contents.js +241 -0
  286. package/neural-interface/public/shared/settings/settings-backup-download.js +298 -0
  287. package/neural-interface/public/shared/settings/settings-backup-encryption-pane.js +335 -0
  288. package/neural-interface/public/shared/settings/settings-backup-encryption.js +545 -0
  289. package/neural-interface/public/shared/settings/settings-browser-extension.js +54 -12
  290. package/neural-interface/public/shared/settings/settings-ia.js +1 -1
  291. package/neural-interface/public/shared/shell-stop-view.js +83 -0
  292. package/neural-interface/public/shared/skills/studio/sx-geometry.js +12 -3
  293. package/neural-interface/public/shared/skills/studio/sx-main.js +14 -7
  294. package/neural-interface/public/shared/studio-attention.js +6 -0
  295. package/neural-interface/public/shared/styles.css +341 -437
  296. package/neural-interface/public/shared/tour/tour-actor.js +14 -3
  297. package/neural-interface/public/shared/transcript-rows.js +28 -3
  298. package/neural-interface/public/shared/tray-auto-close.js +49 -6
  299. package/neural-interface/public/shared/ui-agents.js +1 -2
  300. package/neural-interface/public/shared/ui-automation-studio.js +168 -108
  301. package/neural-interface/public/shared/ui-claude-panel.js +62 -65
  302. package/neural-interface/public/shared/ui-loading.js +124 -17
  303. package/neural-interface/public/shared/ui-native-loop-router.js +52 -0
  304. package/neural-interface/public/shared/ui-navbar.js +2 -1
  305. package/neural-interface/public/shared/ui-output.js +533 -0
  306. package/neural-interface/public/shared/ui-schedules-studio.js +165 -128
  307. package/neural-interface/public/shared/ui-scroll-follow.js +101 -6
  308. package/neural-interface/public/shared/ui-sessions.js +2 -2
  309. package/neural-interface/public/shared/ui-settings-entry.js +18 -0
  310. package/neural-interface/public/shared/ui-settings.js +224 -65
  311. package/neural-interface/public/shared/ui-sidepanel-tray.js +3 -2
  312. package/neural-interface/public/shared/ui-tooltip.js +16 -0
  313. package/neural-interface/public/shared/ui-tutorial.js +5 -6
  314. package/neural-interface/public/shared/ui-worker-end.js +27 -8
  315. package/neural-interface/public/shared/worker-end.js +9 -4
  316. package/neural-interface/public/variant/2d/main.js +5 -0
  317. package/neural-interface/public/variant/3d/app.js +10 -0
  318. package/neural-interface/public/variant/3d/main.js +5 -1
  319. package/neural-interface/scripts/scratch-retention.mjs +20 -0
  320. package/neural-interface/server.js +725 -173
  321. package/npm-shrinkwrap.json +5 -5
  322. package/package.json +1 -2
  323. package/scripts/restore-data-home-from-backup.mjs +175 -8
  324. package/setup.js +18 -4
  325. package/browser-extension/content.js +0 -189
  326. package/browser-extension/engine.js +0 -508
  327. package/browser-extension/icons/icon-128.png +0 -0
  328. package/browser-extension/icons/icon-16.png +0 -0
  329. package/browser-extension/icons/icon-32.png +0 -0
  330. package/browser-extension/icons/icon-48.png +0 -0
  331. package/browser-extension/icons/status-off-16.png +0 -0
  332. package/browser-extension/icons/status-off-32.png +0 -0
  333. package/browser-extension/icons/status-off-48.png +0 -0
  334. package/browser-extension/icons/status-on-16.png +0 -0
  335. package/browser-extension/icons/status-on-32.png +0 -0
  336. package/browser-extension/icons/status-on-48.png +0 -0
  337. package/browser-extension/manifest.json +0 -56
  338. package/browser-extension/popup-strings.js +0 -250
  339. package/browser-extension/popup-view.js +0 -151
  340. package/browser-extension/popup.css +0 -166
  341. package/browser-extension/popup.html +0 -108
  342. package/browser-extension/popup.js +0 -359
  343. package/browser-extension/service-worker.js +0 -275
  344. package/browser-extension/setup-content.js +0 -36
  345. package/browser-extension/tokens.css +0 -326
@@ -4,6 +4,13 @@
4
4
  // shows the folder in Finder, Explorer or the file manager. The owner does the three steps no app may do for them
5
5
  // (the extensions page, Developer mode, Load unpacked); the extension then pairs by itself with a one-time token.
6
6
  //
7
+ // The folder's files are the one package this release pins, downloaded from synabun.ai and verified
8
+ // (lib/browser-extension-package.js). A folder that is already there is used as it is, in the same request as before.
9
+ // One that is not there yet, or is older than the pin, is fetched first: the setup is then `downloading` (with the
10
+ // bytes so far), and the browser and the folder are opened only once the verified files are in place. A download that
11
+ // fails ends the setup with its code (offline, unavailable, verification failed) and Start again tries once more;
12
+ // nothing is ever installed that did not verify.
13
+ //
7
14
  // Every route that reaches this is the owner's (server.js mounts them behind the same guard as pairing and the mode:
8
15
  // ownerRouteGuard, this boot's page secret, no automation caller). Nothing here starts a program by itself: `exec` is
9
16
  // injected (server.js: execFile, no shell, detached) and gets a plan from lib/browser-default.js.
@@ -13,29 +20,60 @@
13
20
  // bridge accepts it once, in its pairing handshake, and forgets it (lib/browser-extension-bridge.js
14
21
  // beginSetupPairing). It is never logged, never in a status and never in a URL.
15
22
  import { launchPlan, revealPlan, SUPPORTED_BROWSER_IDS } from './browser-default.js';
16
- import { SETUP_PAGE_PATH } from './browser-extension-folder.js';
23
+ import { compareVersions, SETUP_PAGE_PATH } from './browser-extension-folder.js';
17
24
  import { randomBytes } from 'node:crypto';
18
25
 
19
- export const SETUP_STATES = Object.freeze(['idle', 'waiting-for-extension', 'pairing', 'connected', 'unsupported', 'error']);
26
+ export const SETUP_STATES = Object.freeze(['idle', 'downloading', 'waiting-for-extension', 'pairing', 'connected', 'unsupported', 'error']);
27
+ /** The codes a download of the extension package can end a setup with (lib/browser-extension-package.js). */
28
+ export const DOWNLOAD_ERRORS = Object.freeze(['EXTENSION_DOWNLOAD_OFFLINE', 'EXTENSION_DOWNLOAD_UNAVAILABLE', 'EXTENSION_VERIFY_FAILED']);
20
29
  export const SETUP_WINDOW_MS = 15 * 60 * 1000;
21
30
  export const TICKET_MS = 2 * 60 * 1000;
22
31
  export const MAX_TICKETS = 5;
23
32
  const fail = (code, message = code) => { throw Object.assign(new Error(message), { code }); };
24
33
 
34
+ /**
35
+ * Whether the browser should be told to reload the extension: it is connected, the folder holds what this release
36
+ * wants (the pinned version, or a newer one a later release left there) and the browser runs something else. While
37
+ * the folder itself is older than the pin a Reload changes nothing: that is `updateNeeded`, which SynaBun settles by
38
+ * downloading the pinned package. `reloadPending`: the folder's marker asks for a Reload until the setup page saw the
39
+ * extension running again; `reloadReason` says why. 'port': the setup port changed while the version stayed, and the
40
+ * browser still runs the old manifest (asked only while the extension is connected). 'repair': files that were not
41
+ * the pinned extension were replaced, and the browser may still run them at the same version, connected or not (the
42
+ * changed code may not connect at all): asked until the owner confirms the Reload in Settings, and said in its own
43
+ * words (`reloadRepaired`).
44
+ */
45
+ export function extensionVersions({ connected, extensionVersion, folderVersion, pinnedVersion, reloadPending = false, reloadReason = null }) {
46
+ const current = !!folderVersion && (!pinnedVersion || compareVersions(folderVersion, pinnedVersion) >= 0);
47
+ const repaired = current && reloadPending === true && reloadReason === 'repair';
48
+ const reloadNeeded = repaired || !!(connected && current && (extensionVersion !== folderVersion || reloadPending === true));
49
+ return {
50
+ reloadNeeded,
51
+ updateNeeded: !!(folderVersion && pinnedVersion && compareVersions(folderVersion, pinnedVersion) < 0),
52
+ ...(repaired ? { reloadRepaired: true } : {}),
53
+ };
54
+ }
55
+
25
56
  /**
26
57
  * `bridge` (createExtensionBridge), `detect()` → { browser, installedBrowsers } (browser-default.js detectBrowsers with
27
- * the system's runners), `prepare()` → { folder, version, changed } (browser-extension-folder.js), `exec(cmd, args)`
28
- * starts a program (never a shell), `appOrigin()` is this server's own origin on loopback (http://127.0.0.1:<port>),
29
- * `platform` the OS, `folderVersion()` the version the folder holds.
58
+ * the system's runners), `prepare({ signal })` → { folder, version, changed } once the folder is ready to load
59
+ * (browser-extension-package.js ensure: it may download), `exec(cmd, args)` starts a program (never a shell),
60
+ * `appOrigin()` is this server's own origin on loopback (http://127.0.0.1:<port>), `platform` the OS,
61
+ * `folderVersion()` the version the folder holds, `packageStatus()` → { pinnedVersion, needs, phase, received, total,
62
+ * code, reloadPending } (browser-extension-package.js status; `needs` says that `prepare` will download),
63
+ * `confirmReload()` the setup page saw the extension's content script on this port (browser-extension-package.js; it
64
+ * never clears a repair's Reload).
30
65
  */
31
66
  export function createExtensionSetup({ bridge, detect, prepare, exec, appOrigin, platform = process.platform, now = Date.now,
32
- windowMs = SETUP_WINDOW_MS, ticketMs = TICKET_MS, maxTickets = MAX_TICKETS, folderVersion = () => null } = {}) {
67
+ windowMs = SETUP_WINDOW_MS, ticketMs = TICKET_MS, maxTickets = MAX_TICKETS, folderVersion = () => null, packageStatus = () => ({}), confirmReload = () => false } = {}) {
33
68
  let setup = null;
69
+ // The latest start, from its first step: a cancel or a later start ends it before it prepares or opens anything.
70
+ let attempt = null;
34
71
  const pageUrl = () => `${appOrigin()}${SETUP_PAGE_PATH}`;
35
72
  const describe = browser => browser ? { id: browser.id, name: browser.name, supported: browser.supported === true, extensionsUrl: browser.extensionsUrl || null } : null;
36
73
  function state() {
37
74
  if (!setup) return 'idle';
38
75
  if (setup.error) return 'error';
76
+ if (setup.preparing) return 'downloading';
39
77
  const bridgeStatus = bridge.status();
40
78
  // Paired by this setup: a pairing made after it began (its token, or the typed code as a fallback). Connected once
41
79
  // the extension's first inventory arrived; "Pairing…" from the token's handshake until then.
@@ -59,16 +97,20 @@ export function createExtensionSetup({ bridge, detect, prepare, exec, appOrigin,
59
97
  }
60
98
  function view() {
61
99
  const current = state(), bridgeStatus = bridge.status();
62
- const version = folderVersion();
100
+ const version = folderVersion(), pkg = packageStatus() || {};
101
+ const pinnedVersion = typeof pkg.pinnedVersion === 'string' ? pkg.pinnedVersion : null;
63
102
  return {
64
103
  state: current,
65
104
  ...(setup ? { setupId: setup.id, browser: describe(setup.browser), defaultBrowser: describe(setup.defaultBrowser), installedBrowsers: setup.installed.map(describe),
66
105
  folder: setup.folder, extensionsUrl: setup.browser?.extensionsUrl || null, opened: setup.opened, revealed: setup.revealed, expiresAt: setup.until } : {}),
67
106
  ...(setup?.error ? { code: setup.error.code } : {}),
68
107
  connected: bridgeStatus.connected, paired: bridgeStatus.paired, bridgePort: bridgeStatus.port,
69
- extensionVersion: bridgeStatus.extensionVersion || null, folderVersion: version,
70
- // The browser runs an older copy than the folder holds (or an extension from before versions were reported).
71
- reloadNeeded: !!(bridgeStatus.connected && version && bridgeStatus.extensionVersion !== version),
108
+ extensionVersion: bridgeStatus.extensionVersion || null, folderVersion: version, pinnedVersion,
109
+ // The bytes so far while the pinned package is on its way (the setup's own download, or an update's).
110
+ ...(pkg.phase === 'downloading' ? { download: { received: Number(pkg.received) || 0, total: Number(pkg.total) || 0 } } : {}),
111
+ // The browser runs another copy than the folder holds (or an extension from before versions were reported);
112
+ // or the folder itself is older than this release's extension, which a download settles, never a Reload.
113
+ ...extensionVersions({ connected: bridgeStatus.connected, extensionVersion: bridgeStatus.extensionVersion, folderVersion: version, pinnedVersion, reloadPending: pkg.reloadPending === true, reloadReason: pkg.reloadReason ?? null }),
72
114
  };
73
115
  }
74
116
  return {
@@ -79,9 +121,16 @@ export function createExtensionSetup({ bridge, detect, prepare, exec, appOrigin,
79
121
  */
80
122
  async start({ browserId } = {}) {
81
123
  if (browserId !== undefined && browserId !== null && !SUPPORTED_BROWSER_IDS.includes(browserId)) fail('INVALID_MESSAGE');
82
- if (setup) bridge.endSetupPairing();
124
+ if (setup) { bridge.endSetupPairing(); setup.stop?.abort(); }
125
+ // This start is the current one before its first wait: a cancel during the browser detection, or a later start
126
+ // whose detection ends first, leaves this one nothing to do when its own detection ends.
127
+ attempt?.stop.abort();
128
+ const own = { stop: new AbortController() };
129
+ attempt = own;
130
+ const superseded = () => attempt !== own || own.stop.signal.aborted;
83
131
  let detected;
84
132
  try { detected = await detect(); } catch { detected = { browser: null, installedBrowsers: [] }; }
133
+ if (superseded()) return view();
85
134
  const installed = Array.isArray(detected?.installedBrowsers) ? detected.installedBrowsers.filter(b => b?.supported) : [];
86
135
  const defaultBrowser = detected?.browser || { id: 'unknown', name: 'Unknown browser', supported: false, extensionsUrl: null };
87
136
  let browser = defaultBrowser;
@@ -91,16 +140,47 @@ export function createExtensionSetup({ bridge, detect, prepare, exec, appOrigin,
91
140
  }
92
141
  setup = { id: randomBytes(12).toString('hex'), startedAt: now(), until: now() + windowMs, browser, defaultBrowser, installed,
93
142
  folder: null, opened: false, revealed: false, tickets: 0, pairedBefore: bridge.status().pairedAt || 0, error: null };
94
- try { setup.folder = (await prepare()).folder; }
95
- catch { setup.error = { code: 'EXTENSION_FOLDER_FAILED' }; return view(); }
96
- if (browser.supported) {
97
- setup.opened = await open(browser);
98
- setup.revealed = (await reveal()).ok === true;
99
- if (!setup.opened) setup.error = { code: 'OPEN_FAILED' };
143
+ const mine = setup;
144
+ mine.stop = own.stop;
145
+ // A browser that cannot run the extension gets no download: the page offers the installed ones, and choosing one
146
+ // starts the setup again.
147
+ if (!browser.supported && (packageStatus() || {}).needs) return view();
148
+ // Once the folder is ready: the page in the browser, the folder in the file manager (never for a start that was
149
+ // cancelled or replaced meanwhile).
150
+ const present = async () => {
151
+ if (!browser.supported || setup !== mine || superseded()) return;
152
+ mine.opened = await open(browser);
153
+ if (setup !== mine) return;
154
+ mine.revealed = (await reveal()).ok === true;
155
+ if (!mine.opened) mine.error = { code: 'OPEN_FAILED' };
156
+ };
157
+ // Started in this step, so the answer below already carries a download's progress.
158
+ let preparing;
159
+ try { preparing = Promise.resolve(prepare({ signal: mine.stop.signal })); } catch (error) { preparing = Promise.reject(error); }
160
+ const ready = preparing.then(
161
+ prepared => { mine.folder = prepared.folder; },
162
+ error => { mine.error = { code: DOWNLOAD_ERRORS.includes(error?.code) || error?.code === 'EXTENSION_FOLDER_UNSAFE' ? error.code : 'EXTENSION_FOLDER_FAILED' }; });
163
+ // A folder that needs no download answers in this request, as it always did. A download runs on: the setup is
164
+ // `downloading` until its files are verified and in place, and this request returns at once so its progress shows.
165
+ const needed = packageStatus() || {};
166
+ if (needed.needs || needed.phase === 'downloading') {
167
+ mine.preparing = true;
168
+ mine.settled = ready.then(async () => { mine.preparing = false; if (setup === mine && !mine.error) await present(); }).catch(() => { mine.preparing = false; });
169
+ return view();
100
170
  }
171
+ await ready;
172
+ if (setup !== mine || mine.error) return view();
173
+ await present();
101
174
  return view();
102
175
  },
103
176
  status: view,
177
+ /**
178
+ * The setup page saw the extension's content script on this server's port (POST …/setup/seen): the browser runs
179
+ * the folder's manifest for this port, so the Reload a port change asked for is done. A repair's Reload is not: the
180
+ * copy the browser still runs answers the page just the same, so only the owner's confirmation in Settings clears it
181
+ * (POST …/reload/confirm, browser-extension-package.js confirmRepairReload).
182
+ */
183
+ seen() { confirmReload(); return view(); },
104
184
  /**
105
185
  * The one-time token for the setup page (POST …/setup/ticket): only while the setup waits for the extension.
106
186
  * Returns { token, bridgePort, expiresAt }.
@@ -111,11 +191,14 @@ export function createExtensionSetup({ bridge, detect, prepare, exec, appOrigin,
111
191
  if (current !== 'waiting-for-extension') fail(current === 'error' ? setup.error?.code || 'SETUP_NOT_ACTIVE' : 'SETUP_NOT_WAITING');
112
192
  if (setup.tickets >= maxTickets) fail('SETUP_TICKETS_USED');
113
193
  setup.tickets++;
194
+ // A ticket clears no pending Reload: the page sends `seen` for that (it does before it asks for a ticket).
114
195
  const until = Math.min(setup.until, now() + ticketMs);
115
196
  const made = await bridge.beginSetupPairing({ until });
116
197
  return { token: made.token, bridgePort: made.port, expiresAt: made.expiresAt };
117
198
  },
118
- cancel() { if (setup) bridge.endSetupPairing(); setup = null; return view(); },
199
+ cancel() { attempt?.stop.abort(); attempt = null; if (setup) { bridge.endSetupPairing(); setup.stop?.abort(); } setup = null; return view(); },
200
+ /** Resolves when a download this setup waits for has ended, either way (tests). */
201
+ settled: () => setup?.settled || Promise.resolve(),
119
202
  reveal,
120
203
  /** Opens the setup page again (in the setup's browser). */
121
204
  async reopen() { if (!setup?.browser?.supported) fail('SETUP_NOT_ACTIVE'); setup.opened = await open(setup.browser); return view(); },
@@ -130,6 +213,10 @@ export const SETUP_ERROR_TEXT = Object.freeze({
130
213
  SETUP_EXPIRED: 'This setup ran out of time (15 minutes). Start "Connect your browser" again.',
131
214
  BROWSER_NOT_INSTALLED: 'That browser was not found on this computer.',
132
215
  EXTENSION_FOLDER_FAILED: 'SynaBun could not prepare the extension folder in its data folder.',
216
+ EXTENSION_FOLDER_UNSAFE: 'SynaBun did not use the extension folder in its data folder (browser-extension): it is a link, belongs to another user, or others can write to it (on Linux, a group that is not your own private group counts as others). Nothing was changed. Fix or remove that folder, then start "Connect your browser" again.',
217
+ EXTENSION_DOWNLOAD_OFFLINE: 'SynaBun could not reach synabun.ai to download the extension. Check the internet connection, then start "Connect your browser" again.',
218
+ EXTENSION_DOWNLOAD_UNAVAILABLE: 'synabun.ai did not have the extension this SynaBun version needs. Try again later, or update SynaBun.',
219
+ EXTENSION_VERIFY_FAILED: 'The downloaded extension was not the file this SynaBun version expects, so it was not installed. Try again; if it keeps failing, update SynaBun.',
133
220
  OPEN_FAILED: 'SynaBun could not open the setup page in the browser. Open it yourself from Settings → Browser.',
134
221
  REVEAL_FAILED: 'SynaBun could not show the folder. Copy its path from the setup page.',
135
222
  INVALID_MESSAGE: 'Invalid setup request.',
@@ -747,6 +747,7 @@ export class ClaudeSession {
747
747
  SynaBun: {
748
748
  type: 'http',
749
749
  url: deps.mcpUrl,
750
+ ...(sessionOpts.synabunDiscoveryCache === false ? { discoveryCache: false } : {}),
750
751
  headers: {
751
752
  'X-Synabun-Terminal': this.synabunOwnerKey,
752
753
  'X-Synabun-Project': memoryProject(workDir),
@@ -56,7 +56,10 @@ export function deleteSessionRows(db, sessionId, provider) {
56
56
  if (!isSessionId(sessionId)) return out;
57
57
  const failures = [];
58
58
  const drop = (key, table, sql, ...params) => {
59
- try { out[key] = Number(db.prepare(sql).run(...params).changes) || 0; }
59
+ try {
60
+ const changes = db.prepare(sql).run(...params).changes;
61
+ if (key) out[key] = Number(changes) || 0;
62
+ }
60
63
  catch (err) {
61
64
  const message = String(err?.message || err);
62
65
  if (/no such table/i.test(message)) return;
@@ -65,6 +68,7 @@ export function deleteSessionRows(db, sessionId, provider) {
65
68
  };
66
69
  drop('chunks', 'session_chunks', 'DELETE FROM session_chunks WHERE session_id = ?', sessionId);
67
70
  drop('fts', 'session_fts', 'DELETE FROM session_fts WHERE session_id = ? AND provider = ?', sessionId, provider);
71
+ drop(null, 'session_fts_lookup', 'DELETE FROM session_fts_lookup WHERE session_id = ? AND provider = ?', sessionId, provider);
68
72
  drop('cache', 'session_cache', 'DELETE FROM session_cache WHERE session_id = ? AND provider = ?', sessionId, provider);
69
73
  if (failures.length) throw Object.assign(new Error(failures.join('; ')), { partial: out });
70
74
  return out;
@@ -249,6 +249,11 @@ async function writeAll(handle, buffer) {
249
249
  /**
250
250
  * Download `url` into `destination` (a new file), HTTPS only and only through
251
251
  * hosts `allow` accepts. Checks the size and, when given, the SHA-256.
252
+ * `identityOnly`: an answer with any Content-Encoding but identity is refused
253
+ * before its body is read, so `maxBytes` bounds the bytes on the wire and no
254
+ * decoding work is done (fetch would otherwise decode gzip or br by itself and
255
+ * count the decoded bytes). Every answer that is refused, and every transfer
256
+ * that fails, ends its request: the body is cancelled and the request aborted.
252
257
  * Resolves { sha256, size, url } (the address the file came from).
253
258
  */
254
259
  export async function downloadFile({
@@ -263,6 +268,7 @@ export async function downloadFile({
263
268
  onProgress = () => {},
264
269
  stallMs = 60_000,
265
270
  accept = 'application/octet-stream',
271
+ identityOnly = false,
266
272
  }) {
267
273
  let current;
268
274
  try { current = new URL(url); } catch { throw new CliInstallError('internal', `Not an address: ${url}`); }
@@ -280,26 +286,33 @@ export async function downloadFile({
280
286
  let made = false;
281
287
  let answered = false;
282
288
  let received = 0;
289
+ // The body still open (an answer being looked at, then the reader): cancelled whenever the download is given up.
290
+ let release = null;
283
291
  const hash = createHash('sha256');
284
292
  try {
285
293
  alive();
286
294
  let response = null;
287
295
  for (let hop = 0; ; hop++) {
288
296
  response = await fetchImpl(current, { redirect: 'manual', signal: stop.signal, headers: { accept, 'accept-encoding': 'identity', 'user-agent': 'synabun' } });
297
+ const answer = response;
298
+ release = () => answer.body?.cancel();
289
299
  if (response.status < 300 || response.status >= 400) break;
290
300
  const next = nextHop(response, current, allow);
291
301
  try { await response.body?.cancel(); } catch { /* nothing to drain */ }
302
+ release = null;
292
303
  if (hop >= MAX_REDIRECTS) throw new CliInstallError('http', 'The download server redirected too many times.');
293
304
  current = next;
294
305
  alive();
295
306
  }
296
307
  if (response.status !== 200 || !response.body) {
297
- try { await response.body?.cancel(); } catch { /* nothing to drain */ }
298
308
  throw new CliInstallError('http', `${current.hostname} answered ${response.status} instead of the file.`, { detail: String(response.status) });
299
309
  }
310
+ const encoding = String(response.headers.get('content-encoding') || '').trim().toLowerCase();
311
+ if (identityOnly && encoding && encoding !== 'identity') {
312
+ throw new CliInstallError('http', `${current.hostname} sent the file encoded (${encoding.slice(0, 20)}) although it was asked for the file as it is. It was not downloaded.`, { detail: 'content-encoding' });
313
+ }
300
314
  const announced = Number(response.headers.get('content-length'));
301
315
  if (Number.isFinite(announced) && announced > 0 && ((expectedSize && announced !== expectedSize) || announced > maxBytes)) {
302
- try { await response.body.cancel(); } catch { /* nothing to drain */ }
303
316
  throw new CliInstallError('checksum', `${current.hostname} offered ${announced} bytes${expectedSize ? `; the published file has ${expectedSize}` : ''}. It was not downloaded.`);
304
317
  }
305
318
  answered = true;
@@ -310,6 +323,7 @@ export async function downloadFile({
310
323
  // Read through a reader of our own, cancelled on a stall or a stop: the transfer ends then whatever the
311
324
  // transport does with the signal.
312
325
  const reader = response.body.getReader();
326
+ release = () => reader.cancel();
313
327
  const onStop = () => { reader.cancel(stop.signal.reason).catch(() => {}); };
314
328
  stop.signal.addEventListener('abort', onStop, { once: true });
315
329
  try {
@@ -336,12 +350,18 @@ export async function downloadFile({
336
350
  await handle.sync();
337
351
  await handle.close();
338
352
  handle = null;
353
+ release = null;
339
354
  return { sha256: digest, size: received, url: current.href };
340
355
  } catch (error) {
356
+ const stoppedFor = stop.signal.aborted && stop.signal.reason instanceof CliInstallError ? stop.signal.reason : null;
357
+ // Whatever ended it, the request ends here too: nothing more arrives, is decoded or is read.
358
+ if (!stop.signal.aborted) stop.abort(new CliInstallError('cancelled', 'The download was given up.'));
359
+ try { await release?.(); } catch { /* cancelled already */ }
360
+ release = null;
341
361
  try { await handle?.close(); } catch { /* closed */ }
342
362
  handle = null;
343
363
  if (made) rmSync(destination, { force: true });
344
- if (stop.signal.aborted && stop.signal.reason instanceof CliInstallError) throw stop.signal.reason;
364
+ if (stoppedFor) throw stoppedFor;
345
365
  if (error instanceof CliInstallError) throw error;
346
366
  if (DISK_CODES.has(errorCode(error))) throw asInstallError(error, 'disk', `The download could not be saved (${errorCode(error)}).`);
347
367
  if (answered) throw new CliInstallError('interrupted', `The download from ${current.hostname} ended after ${received} bytes.`, { cause: error, detail: errorCode(error) || error?.message });
@@ -16,6 +16,8 @@
16
16
  // PATH, so the update silently does nothing and the badge never clears.
17
17
  // ═══════════════════════════════════════════
18
18
 
19
+ import { semverNewer } from './synabun-version.js';
20
+
19
21
  /**
20
22
  * npm package name per tool key. OpenCode has none: npm's opencode-ai is
21
23
  * OpenCode 1, which SynaBun does not drive, and OpenCode 2 is installed by its
@@ -57,6 +59,98 @@ export const BREW_KINDS = {
57
59
  'opencode': 'formula',
58
60
  };
59
61
 
62
+ /**
63
+ * Where OpenCode 2 publishes its newest version, per install channel (checked
64
+ * 2026-11-21 against OpenCode 2.3.2). It has no npm package SynaBun could ask
65
+ * the registry about under the old name (opencode-ai is OpenCode 1), so without
66
+ * these the update check had nothing to compare an install with.
67
+ * vendor what OpenCode's own installer reads to find the release it
68
+ * downloads (https://opencode.ai/v2/install): JSON with a
69
+ * `version`. The yardstick of every install Homebrew does not own.
70
+ * brewFormula the formula of OpenCode's Homebrew tap as it is published.
71
+ * `brew outdated` only knows the local clone of a tap, which
72
+ * nothing refreshes until the user runs brew themselves (the
73
+ * probe runs with HOMEBREW_NO_AUTO_UPDATE), so a tap install
74
+ * never showed an update. The formula is exactly what
75
+ * `brew upgrade` installs once the tap is refreshed, so it can
76
+ * never run ahead of Homebrew the way npm does for a cask.
77
+ * brewToken the formula that file is (the tap's `opencode` is OpenCode 1).
78
+ */
79
+ export const OPENCODE_UPDATE_SOURCES = Object.freeze({
80
+ vendor: 'https://opencode.ai/update/api/latest/cli/npm',
81
+ brewFormula: 'https://raw.githubusercontent.com/anomalyco/homebrew-tap/HEAD/opencode-v2.rb',
82
+ brewToken: 'opencode-v2',
83
+ });
84
+
85
+ /**
86
+ * OpenCode 2 in WinGet (checked 2026-11-23): the package id, and the arguments OpenCode's own updater asks WinGet
87
+ * with to find the version it can install (`winget search …`). WinGet is the yardstick of a WinGet install, not
88
+ * OpenCode's update API: a release reaches WinGet's repository days after it is published, and some never do (on
89
+ * 2026-11-23 the API said 2.4.1 while WinGet's newest was 2.3.2, after 2.2.7 with nothing between). `opencode
90
+ * upgrade --method winget` installs what WinGet has, so a badge measured against the API stays lit after an update
91
+ * that did all it could.
92
+ */
93
+ export const OPENCODE_WINGET_ID = 'Anomaly.OpenCode';
94
+ export const OPENCODE_WINGET_SEARCH_ARGS = Object.freeze([
95
+ 'search', '--id', OPENCODE_WINGET_ID, '--exact', '--source', 'winget', '--accept-source-agreements', '--disable-interactivity',
96
+ ]);
97
+
98
+ const PLAIN_VERSION_RE = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
99
+ const plainVersion = (value) => {
100
+ const text = typeof value === 'string' ? value.trim().replace(/^v(?=\d)/i, '') : '';
101
+ return PLAIN_VERSION_RE.test(text) ? text : null;
102
+ };
103
+
104
+ /** The `version` of OpenCode's update API answer (`{"version":"2.3.2",…}`), or null. */
105
+ export function parseVendorLatest(body) {
106
+ let data = body;
107
+ if (typeof body === 'string') {
108
+ try { data = JSON.parse(body); } catch { return null; }
109
+ }
110
+ if (!data || typeof data !== 'object' || data.active === false) return null;
111
+ return plainVersion(data.version);
112
+ }
113
+
114
+ /** The `version "…"` line of a Homebrew formula file, or null. */
115
+ export function parseFormulaVersion(text) {
116
+ const match = String(text ?? '').match(/^[ \t]*version[ \t]+["']([^"'\s]+)["'][ \t]*$/m);
117
+ return match ? plainVersion(match[1]) : null;
118
+ }
119
+
120
+ /**
121
+ * The version `winget search --id <id> --exact` lists for a package, or null. Read as OpenCode's own updater reads
122
+ * it: on any line, the word after the package id (the table's columns are Name, Id, Version, Source; a progress
123
+ * spinner may share the first line, separated by carriage returns).
124
+ */
125
+ export function parseWingetSearchVersion(output, id = OPENCODE_WINGET_ID) {
126
+ const wanted = String(id || '').toLowerCase();
127
+ if (!wanted) return null;
128
+ for (const line of String(output ?? '').split(/\r?\n|\r/)) {
129
+ const words = line.trim().split(/\s+/);
130
+ const at = words.findIndex((word) => word.toLowerCase() === wanted);
131
+ if (at === -1) continue;
132
+ const version = plainVersion(words[at + 1]);
133
+ if (version) return version;
134
+ }
135
+ return null;
136
+ }
137
+
138
+ /**
139
+ * Where a tool's newest version is read from when it has no npm package:
140
+ * `{ url, channel, read(text) }`, or null (an npm tool, a tool with no such
141
+ * source, a Homebrew install of a formula SynaBun does not know the tap of:
142
+ * `brew outdated` alone speaks for that one).
143
+ */
144
+ export function upstreamVersionSource(toolKey, installSource, brewToken = null) {
145
+ if (toolKey !== 'opencode') return null;
146
+ if (isBrewSource(installSource)) {
147
+ const bare = String(brewToken || '').split('/').pop();
148
+ if (installSource !== 'brew-formula' || bare !== OPENCODE_UPDATE_SOURCES.brewToken) return null;
149
+ return { url: OPENCODE_UPDATE_SOURCES.brewFormula, channel: 'brew-formula', read: parseFormulaVersion };
150
+ }
151
+ return { url: OPENCODE_UPDATE_SOURCES.vendor, channel: 'vendor', read: parseVendorLatest };
152
+ }
153
+
60
154
  /** Tools that can update themselves when they own their own install. */
61
155
  const SELF_UPDATERS = {
62
156
  'claude-code': 'claude update',
@@ -226,13 +320,38 @@ export function quoteCommandPath(file, platform = process.platform) {
226
320
  * very installation the panels use, also when a terminal's PATH does not name
227
321
  * its folder (a Windows server started before the CLI was installed, a folder
228
322
  * found among the known install locations).
323
+ *
324
+ * `refreshBrew` (brewNeedsRefresh): the newer version is in the tap as it is
325
+ * published, and this machine's Homebrew has not heard of it yet. `brew
326
+ * upgrade` refreshes by itself only once in a while (HOMEBREW_AUTO_UPDATE_SECS,
327
+ * a day by default) and would answer "already installed", leaving the badge
328
+ * lit: the command refreshes first.
329
+ *
330
+ * `gitBash`: a Git Bash this PC has (lib/git-bash resolver: bash.exe), for OpenCode 2's own installer on Windows.
331
+ * `opencode upgrade --method curl` runs that installer, a bash script, with Git Bash, which it looks for through
332
+ * `git --exec-path`: a PC whose git is not on PATH (Git's "Git Bash only" setup, or SynaBun's own copy of Git) has
333
+ * one all the same, and is told where it is (OPENCODE_GIT_BASH_PATH, for that one command).
334
+ *
335
+ * `installedVersion`: the version found, when the caller knows it. An OpenCode in %USERPROFILE%\.opencode\bin that
336
+ * is not OpenCode 2 (the release archive an older SynaBun put there was OpenCode 1) gets no command, as before: its
337
+ * own upgrade is not the one meant here, and SynaBun's panel already says how to get OpenCode 2.
229
338
  */
230
- export function buildUpdateCommand(toolKey, installSource, { brewToken = null, binPath = null, platform = null } = {}) {
231
- const command = planUpdateCommand(toolKey, installSource, { brewToken, platform });
339
+ export function buildUpdateCommand(toolKey, installSource, { brewToken = null, binPath = null, platform = null, refreshBrew = false, gitBash = null, installedVersion = null } = {}) {
340
+ if (toolKey === 'opencode' && installSource === 'standalone' && platform === 'win32' && installedVersion != null && !/^v?2\./.test(String(installedVersion).trim())) return null;
341
+ const planned = planUpdateCommand(toolKey, installSource, { brewToken, platform });
342
+ const command = planned && refreshBrew && isBrewSource(installSource) ? `brew update && ${planned}` : planned;
232
343
  const name = TOOL_COMMANDS[toolKey];
233
344
  if (!command || !binPath || !name) return command;
234
345
  if (command !== name && !command.startsWith(`${name} `)) return command;
235
- return `${quoteCommandPath(binPath, platform || process.platform)}${command.slice(name.length)}`;
346
+ const started = `${quoteCommandPath(binPath, platform || process.platform)}${command.slice(name.length)}`;
347
+ const bash = toolKey === 'opencode' && platform === 'win32' && installSource === 'standalone' ? cmdSetValue(gitBash) : null;
348
+ return bash ? `set "OPENCODE_GIT_BASH_PATH=${bash}" && ${started}` : started;
349
+ }
350
+
351
+ /** A value cmd.exe takes unchanged inside `set "NAME=value"`, or null (a quote, a variable or an escape in it). */
352
+ function cmdSetValue(value) {
353
+ const text = typeof value === 'string' ? value.trim() : '';
354
+ return text && !/["%!^\r\n]/.test(text) ? text : null;
236
355
  }
237
356
 
238
357
  function planUpdateCommand(toolKey, installSource, { brewToken = null, platform = null } = {}) {
@@ -256,8 +375,10 @@ function planUpdateCommand(toolKey, installSource, { brewToken = null, platform
256
375
 
257
376
  // OpenCode 2 updates itself through the channel it came from (brew is handled above).
258
377
  if (toolKey === 'opencode') {
259
- // Its installer script is bash: a copy in %USERPROFILE%\.opencode\bin on Windows is no OpenCode 2 install.
260
- if (installSource === 'standalone' && platform === 'win32') return null;
378
+ // %USERPROFILE%\.opencode\bin\opencode.exe is an install of OpenCode 2's own script on Windows too (the script
379
+ // runs in Git Bash and names the file opencode.exe), and OpenCode 2 updates it there with `--method curl`
380
+ // through Git Bash (read in the Windows builds of 2.2.7 and 2.4.1, 2026-11-23). It used to get no command here,
381
+ // so its badge could only say "update via the official installer".
261
382
  if (OPENCODE_METHODS[installSource]) return `opencode upgrade --method ${OPENCODE_METHODS[installSource]}`;
262
383
  if (['volta', 'scoop', 'choco'].includes(installSource)) return null; // not an OpenCode 2 channel: the caller shows a hint
263
384
  return selfUpdate;
@@ -331,22 +452,63 @@ export function parseBrewOutdated(raw) {
331
452
  *
332
453
  * When the brew probe itself failed we fail CLOSED (latest = installed)
333
454
  * rather than falling back to npm, for the same reason.
455
+ *
456
+ * `npmLatest` is the upstream version of an install Homebrew does not own: the
457
+ * npm registry's for Claude Code and Codex, OpenCode's own update API for
458
+ * OpenCode 2 (upstreamVersionSource). `brewUpstream` is the version of the
459
+ * tool's formula as its tap publishes it (OpenCode's tap only): what Homebrew
460
+ * installs once the tap is refreshed, so it counts when it is newer than the
461
+ * install and `brew outdated` has not heard of it yet.
462
+ *
463
+ * `winget`: what WinGet was asked about a WinGet install (OpenCode 2 only):
464
+ * `{ version }`, the version WinGet lists, or null when it could not be
465
+ * asked. WinGet is then the yardstick, as Homebrew is for a Homebrew install:
466
+ * its version when that is newer than the install, else the install itself (no
467
+ * badge), and the install itself when WinGet could not be asked (fail closed:
468
+ * the update API's version is one WinGet may not have).
334
469
  */
335
470
  export function resolveLatest({
336
471
  installSource,
337
472
  brewToken = null,
338
473
  brewOutdated = null,
339
474
  npmLatest = null,
475
+ brewUpstream = null,
340
476
  installed = null,
477
+ winget = undefined,
341
478
  } = {}) {
479
+ if (installSource === 'winget' && winget !== undefined) {
480
+ if (!installed) return null;
481
+ return winget?.version && semverNewer(installed, winget.version) ? winget.version : installed;
482
+ }
342
483
  if (!isBrewSource(installSource)) return npmLatest;
343
484
  if (!installed) return null;
344
485
  if (!brewOutdated) return installed;
486
+ const hit = brewOutdatedVersion(brewOutdated, brewToken);
487
+ if (hit) return hit;
488
+ return brewUpstream && semverNewer(installed, brewUpstream) ? brewUpstream : installed;
489
+ }
490
+
491
+ function brewOutdatedVersion(brewOutdated, brewToken) {
345
492
  const token = brewToken || null;
346
- const hit = (token && brewOutdated.get(token))
347
- || (token && brewOutdated.get(String(token).split('/').pop()))
348
- || null;
349
- return hit || installed;
493
+ if (!token || !brewOutdated) return null;
494
+ return brewOutdated.get(token) || brewOutdated.get(String(token).split('/').pop()) || null;
495
+ }
496
+
497
+ /**
498
+ * Whether the update of a Homebrew install has to refresh Homebrew first
499
+ * (buildUpdateCommand `refreshBrew`): the tap publishes a newer version than
500
+ * the one installed, and `brew outdated` does not list the tool.
501
+ */
502
+ export function brewNeedsRefresh({
503
+ installSource,
504
+ brewToken = null,
505
+ brewOutdated = null,
506
+ brewUpstream = null,
507
+ installed = null,
508
+ } = {}) {
509
+ if (!isBrewSource(installSource) || !installed || !brewOutdated || !brewUpstream) return false;
510
+ if (brewOutdatedVersion(brewOutdated, brewToken)) return false;
511
+ return semverNewer(installed, brewUpstream);
350
512
  }
351
513
 
352
514
  /**
@@ -0,0 +1,42 @@
1
+ import express from 'express';
2
+ import { DIAGNOSTIC_BATCH, validDiagnosticEntry } from '../public/shared/loading-diagnostic-entry.js';
3
+
4
+ // Leave this stream for its route's small parser behind the request/peer gates.
5
+ // Every other request uses the same application/json match as express.json().
6
+ export function useDefaultJsonParser(req) {
7
+ if (req.method === 'POST' && /^\/api\/client-diagnostics\/?$/i.test(req.path)) return false;
8
+ return req.is('application/json');
9
+ }
10
+
11
+ // Cap chunked bodies and whitespace too. Parser errors can contain the raw body.
12
+ const parse = express.json({ limit: 12 * 1024, inflate: false });
13
+ export function parseClientDiagnostics(req, res, next) {
14
+ if (!req.is('application/json')) return res.sendStatus(415);
15
+ parse(req, res, err => err ? res.sendStatus(err.status || 400) : next());
16
+ }
17
+
18
+ export function createClientDiagnostics({ ownerPage, refuseOwner, log = console.log, now = Date.now }) {
19
+ const pages = new Map();
20
+ let resetAt = 0;
21
+ return (req, res) => {
22
+ // Host has already passed the server's host gate. Compare the scheme and port too.
23
+ if (req.headers.origin !== `${req.protocol}://${req.headers.host}`) return res.sendStatus(403);
24
+ if (!ownerPage(req)) return refuseOwner(req, res, 'Client diagnostics require the owner’s page.');
25
+ const batch = req.body;
26
+ if (!Array.isArray(batch) || !batch.length || batch.length > DIAGNOSTIC_BATCH) return res.sendStatus(400);
27
+ if (!batch.every(entry => validDiagnosticEntry(entry) && entry.pageId === batch[0].pageId)) return res.sendStatus(400);
28
+
29
+ const time = now();
30
+ if (time >= resetAt) { pages.clear(); resetAt = time + 60000; }
31
+ const id = batch[0].pageId;
32
+ const count = pages.get(id) || 0;
33
+ // One page can drain the entire retained trail at once. Bound the accounting
34
+ // itself as well, even if an owner client invents a fresh ID for every request.
35
+ if (count + batch.length > 240 || (!count && pages.size >= 256)) return res.sendStatus(429);
36
+ pages.set(id, count + batch.length);
37
+ for (const { iso, pageId, event, currentBoot, visibility, data } of batch) {
38
+ log(`[client-diag] ${iso} ${pageId} ${event} ${JSON.stringify({ currentBoot, visibility, ...data })}`);
39
+ }
40
+ res.status(204).end();
41
+ };
42
+ }
@@ -76,6 +76,12 @@ function openExisting(real, flags) {
76
76
  * @returns a Buffer, or a string when `encoding` is given
77
77
  */
78
78
  export function readConfinedFile(base, path, { maxBytes = MAX_FILE_BYTES, encoding = null } = {}) {
79
+ const { bytes } = readConfinedFileWithMetadata(base, path, { maxBytes });
80
+ return encoding ? bytes.toString(encoding) : bytes;
81
+ }
82
+
83
+ /** Bytes and modification time from the same verified, open regular file. */
84
+ export function readConfinedFileWithMetadata(base, path, { maxBytes = MAX_FILE_BYTES } = {}) {
79
85
  const real = canonicalInside(base, path);
80
86
  const fd = openExisting(real, constants.O_RDONLY);
81
87
  try {
@@ -89,8 +95,7 @@ export function readConfinedFile(base, path, { maxBytes = MAX_FILE_BYTES, encodi
89
95
  if (n <= 0) break;
90
96
  got += n;
91
97
  }
92
- const data = got === st.size ? buf : buf.subarray(0, got);
93
- return encoding ? data.toString(encoding) : data;
98
+ return { bytes: got === st.size ? buf : buf.subarray(0, got), lastModified: Math.trunc(st.mtimeMs) };
94
99
  } finally { try { closeSync(fd); } catch {} }
95
100
  }
96
101