@openchamber/web 1.24.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (442) hide show
  1. package/bin/cli.test.js +22 -0
  2. package/bin/lib/commands-connect-url.js +3 -8
  3. package/bin/lib/commands-status.js +5 -0
  4. package/bin/lib/commands-tunnel.js +3 -0
  5. package/dist/assets/{CodeMirrorCommentWidgets-DvUH815P.js → CodeMirrorCommentWidgets-hJbl3JX4.js} +1 -1
  6. package/dist/assets/DiffView-BucGEJYa.js +4 -0
  7. package/dist/assets/FilesView-CQcaaAVP.js +17 -0
  8. package/dist/assets/{GitView-Bxuv3dfP.js → GitView-DY4pelsO.js} +4 -4
  9. package/dist/assets/{GuestAttachDialog-B0u3Q5uO.js → GuestAttachDialog-D6mHDTB2.js} +1 -1
  10. package/dist/assets/GuestSurfacePane--DJ7rsmY.js +1 -0
  11. package/dist/assets/{JsonTreeView-BBVPFM5K.js → JsonTreeView-DEXI2NvJ.js} +1 -1
  12. package/dist/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
  13. package/dist/assets/KaTeX_AMS-Regular-DMm9YOAa.woff +0 -0
  14. package/dist/assets/KaTeX_AMS-Regular-DRggAlZN.ttf +0 -0
  15. package/dist/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf +0 -0
  16. package/dist/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff +0 -0
  17. package/dist/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
  18. package/dist/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff +0 -0
  19. package/dist/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
  20. package/dist/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf +0 -0
  21. package/dist/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf +0 -0
  22. package/dist/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff +0 -0
  23. package/dist/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
  24. package/dist/assets/KaTeX_Fraktur-Regular-CB_wures.ttf +0 -0
  25. package/dist/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
  26. package/dist/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff +0 -0
  27. package/dist/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
  28. package/dist/assets/KaTeX_Main-Bold-Jm3AIy58.woff +0 -0
  29. package/dist/assets/KaTeX_Main-Bold-waoOVXN0.ttf +0 -0
  30. package/dist/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
  31. package/dist/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf +0 -0
  32. package/dist/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff +0 -0
  33. package/dist/assets/KaTeX_Main-Italic-3WenGoN9.ttf +0 -0
  34. package/dist/assets/KaTeX_Main-Italic-BMLOBm91.woff +0 -0
  35. package/dist/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
  36. package/dist/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
  37. package/dist/assets/KaTeX_Main-Regular-Dr94JaBh.woff +0 -0
  38. package/dist/assets/KaTeX_Main-Regular-ypZvNtVU.ttf +0 -0
  39. package/dist/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf +0 -0
  40. package/dist/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
  41. package/dist/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff +0 -0
  42. package/dist/assets/KaTeX_Math-Italic-DA0__PXp.woff +0 -0
  43. package/dist/assets/KaTeX_Math-Italic-flOr_0UB.ttf +0 -0
  44. package/dist/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
  45. package/dist/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf +0 -0
  46. package/dist/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
  47. package/dist/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff +0 -0
  48. package/dist/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
  49. package/dist/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff +0 -0
  50. package/dist/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf +0 -0
  51. package/dist/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf +0 -0
  52. package/dist/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff +0 -0
  53. package/dist/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
  54. package/dist/assets/KaTeX_Script-Regular-C5JkGWo-.ttf +0 -0
  55. package/dist/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
  56. package/dist/assets/KaTeX_Script-Regular-D5yQViql.woff +0 -0
  57. package/dist/assets/KaTeX_Size1-Regular-C195tn64.woff +0 -0
  58. package/dist/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf +0 -0
  59. package/dist/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
  60. package/dist/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf +0 -0
  61. package/dist/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
  62. package/dist/assets/KaTeX_Size2-Regular-oD1tc_U0.woff +0 -0
  63. package/dist/assets/KaTeX_Size3-Regular-CTq5MqoE.woff +0 -0
  64. package/dist/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf +0 -0
  65. package/dist/assets/KaTeX_Size4-Regular-BF-4gkZK.woff +0 -0
  66. package/dist/assets/KaTeX_Size4-Regular-DWFBv043.ttf +0 -0
  67. package/dist/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
  68. package/dist/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff +0 -0
  69. package/dist/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
  70. package/dist/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf +0 -0
  71. package/dist/assets/LinearIssuesView-BTNc-4dN.js +1 -0
  72. package/dist/assets/MarkdownImageGallery-wcUUcf8l.js +1 -0
  73. package/dist/assets/MarkdownRendererImpl-BPe2TVV2.js +12 -0
  74. package/dist/assets/OnboardingScreen-FJUreEgI.js +1 -0
  75. package/dist/assets/{PatchDiff-C4rE5k6z.js → PatchDiff-C0oOkKnO.js} +1 -1
  76. package/dist/assets/PierreDiffViewer-asuSQAsf.js +210 -0
  77. package/dist/assets/PlanView-DGbasNHP.js +5 -0
  78. package/dist/assets/PluginPane-DImv8hV2.js +3 -0
  79. package/dist/assets/SettingsView-DOjuOljf.js +29 -0
  80. package/dist/assets/SettingsWindow-By4cqnqy.js +1 -0
  81. package/dist/assets/SubmoduleDiffSummary-C0P2tXLU.js +1 -0
  82. package/dist/assets/ToolOutputDialog-Cayc-yIM.js +15 -0
  83. package/dist/assets/ToolPartDiffPreview-B0jmpPQz.js +8 -0
  84. package/dist/assets/{VirtualizedFileDiff-CZgXWHjU.js → VirtualizedFileDiff-DsOpvWZD.js} +4 -4
  85. package/dist/assets/{WalkthroughView-wSpED5L4.js → WalkthroughView-CCakjyn9.js} +2 -2
  86. package/dist/assets/appThemeRegistry-Bw5oTm41.js +1 -0
  87. package/dist/assets/{commitAndPush-DZnzlhvc.js → commitAndPush-sGEelpjh.js} +1 -1
  88. package/dist/assets/{computeVirtualFileMetrics-VYnT_A2h.js → computeVirtualFileMetrics-B-4aLf4A.js} +1 -1
  89. package/dist/assets/de-CD9utsNj.js +10 -0
  90. package/dist/assets/es-NNum2rX8.js +16 -0
  91. package/dist/assets/fr-CJLGmduQ.js +14 -0
  92. package/dist/assets/index-B6r0Kv-B.js +1 -0
  93. package/dist/assets/index-DjGPR5vW.js +41 -0
  94. package/dist/assets/index-fCXJ-8Qt.css +1 -0
  95. package/dist/assets/{isDiffPlainText-ImDG3Uhg.js → isDiffPlainText-Ok-kgtJA.js} +1 -1
  96. package/dist/assets/{isFilePlainText-D_YDVYDb.js → isFilePlainText-0dLnkYm8.js} +1 -1
  97. package/dist/assets/ja-BuddHNi6.js +16 -0
  98. package/dist/assets/ko-BrwMbHmf.js +16 -0
  99. package/dist/assets/main-CjXBM_Xe.js +2 -0
  100. package/dist/assets/main-CxVyUDU_.js +896 -0
  101. package/dist/assets/markdownCore-B6PpX409.js +5 -0
  102. package/dist/assets/miniChat-DZ3OAeLN.js +2 -0
  103. package/dist/assets/mobile-CH0LOIF-.js +2 -0
  104. package/dist/assets/{patchFileDiff-DDQ6Rq5e.js → patchFileDiff-BFRGKaGH.js} +3 -3
  105. package/dist/assets/pl-BwN4TNlP.js +16 -0
  106. package/dist/assets/pt-BR-BhMtownO.js +16 -0
  107. package/dist/assets/renderElectronMiniChatApp-CB1uLYvh.js +2 -0
  108. package/dist/assets/renderMobileApp-nQ4sjQtb.js +25 -0
  109. package/dist/assets/runtimeEndpointReset-9ZGlXU4J.js +27 -0
  110. package/dist/assets/scheduledTasksApi-6DsL_SwM.js +1 -0
  111. package/dist/assets/{shikiHighlight-1imXsir9.js → shikiHighlight-CocY80VR.js} +1 -1
  112. package/dist/assets/{textMateThemeFromAppTheme-Dgqc63LZ.js → textMateThemeFromAppTheme-CF77r8FA.js} +1 -1
  113. package/dist/assets/tr-DRzvqMdi.js +7 -0
  114. package/dist/assets/uk-b2aYOSNh.js +16 -0
  115. package/dist/assets/useAppFontEffects-Dc5nTHi8.js +7337 -0
  116. package/dist/assets/useInlineCommentController-Dbza5c8l.js +2 -0
  117. package/dist/assets/useRootScrollLock-CSCLv396.js +2 -0
  118. package/dist/assets/{vendor-codemirror-language-data-BDyxuqK4.js → vendor-codemirror-language-data-CkmYWcRI.js} +2 -2
  119. package/dist/assets/vendor-cron-parser-CjvYVigk.js +2 -0
  120. package/dist/assets/vendor-katex-Cp579UoJ.css +1 -0
  121. package/dist/assets/vendor-opencode-client-_BAHQo4R.js +12 -0
  122. package/dist/assets/{vendor-remixicon-react-BDmGmFCA.js → vendor-remixicon-react-D6dZ0UwF.js} +1 -1
  123. package/dist/assets/{vendor-zod-fZppILAM.js → vendor-zod-Gea9uBlY.js} +4 -4
  124. package/dist/assets/{web-components-D7FinaeH.js → web-components-nsStrYq9.js} +2 -2
  125. package/dist/assets/zh-CN-DZeUThm_.js +16 -0
  126. package/dist/assets/zh-TW-2fRE7uc6.js +16 -0
  127. package/dist/index.html +15 -7
  128. package/dist/mini-chat.html +7 -5
  129. package/dist/mobile.html +7 -5
  130. package/package.json +8 -7
  131. package/server/index.d.ts +1 -0
  132. package/server/index.js +248 -90
  133. package/server/lib/agent-tool/DOCUMENTATION.md +45 -15
  134. package/server/lib/agent-tool/runtime.js +189 -61
  135. package/server/lib/agent-tool/runtime.test.js +229 -75
  136. package/server/lib/browser-control/DOCUMENTATION.md +37 -2
  137. package/server/lib/browser-control/provider.js +217 -0
  138. package/server/lib/browser-control/provider.test.js +251 -0
  139. package/server/lib/context-obligatory/runtime.js +61 -50
  140. package/server/lib/context-obligatory/runtime.test.js +62 -162
  141. package/server/lib/event-stream/DOCUMENTATION.md +12 -1
  142. package/server/lib/event-stream/delta-coalescer.js +0 -0
  143. package/server/lib/event-stream/delta-coalescer.test.js +68 -57
  144. package/server/lib/event-stream/directory-ws-bridge.js +1 -1
  145. package/server/lib/event-stream/global-hub.js +10 -1
  146. package/server/lib/event-stream/global-hub.test.js +27 -26
  147. package/server/lib/event-stream/index.js +6 -0
  148. package/server/lib/event-stream/protocol.js +26 -19
  149. package/server/lib/event-stream/protocol.test.js +18 -7
  150. package/server/lib/event-stream/rebind.test.js +5 -5
  151. package/server/lib/event-stream/runtime.test.js +17 -15
  152. package/server/lib/event-stream/translate-v2.js +313 -0
  153. package/server/lib/event-stream/translate-v2.test.js +209 -0
  154. package/server/lib/event-stream/upstream-reader.test.js +16 -16
  155. package/server/lib/fs/DOCUMENTATION.md +6 -3
  156. package/server/lib/fs/byte-range.js +35 -0
  157. package/server/lib/fs/byte-range.test.js +31 -0
  158. package/server/lib/fs/routes.js +103 -46
  159. package/server/lib/fs/routes.test.js +239 -18
  160. package/server/lib/git/DOCUMENTATION.md +2 -2
  161. package/server/lib/git/service.js +106 -9
  162. package/server/lib/git/service.test.js +18 -0
  163. package/server/lib/github/DOCUMENTATION.md +1 -1
  164. package/server/lib/github/pr-status.js +22 -2
  165. package/server/lib/github/pr-status.test.js +27 -14
  166. package/server/lib/guests/DOCUMENTATION.md +13 -0
  167. package/server/lib/guests/catalog.js +12 -0
  168. package/server/lib/guests/catalog.test.js +33 -0
  169. package/server/lib/guests/routes.js +10 -1
  170. package/server/lib/guests/service.js +192 -14
  171. package/server/lib/guests/service.test.js +201 -1
  172. package/server/lib/guests/surface.js +630 -0
  173. package/server/lib/guests/surface.test.js +486 -0
  174. package/server/lib/markdown-image-grants/routes.js +18 -5
  175. package/server/lib/markdown-image-grants/routes.test.js +9 -6
  176. package/server/lib/message-queue/DOCUMENTATION.md +36 -22
  177. package/server/lib/message-queue/runtime.js +170 -100
  178. package/server/lib/message-queue/runtime.test.js +184 -82
  179. package/server/lib/notifications/DOCUMENTATION.md +28 -0
  180. package/server/lib/notifications/control-stream.http.test.js +68 -0
  181. package/server/lib/notifications/emitter-runtime.js +15 -0
  182. package/server/lib/notifications/emitter-runtime.test.js +32 -0
  183. package/server/lib/notifications/push-runtime.js +5 -1
  184. package/server/lib/notifications/push-runtime.test.js +2 -2
  185. package/server/lib/notifications/routes.js +5 -0
  186. package/server/lib/notifications/runtime.js +115 -26
  187. package/server/lib/notifications/template-runtime.js +13 -15
  188. package/server/lib/notifications/template-runtime.test.js +16 -9
  189. package/server/lib/notifications/trigger-runtime.test.js +187 -0
  190. package/server/lib/openchamber-control/DOCUMENTATION.md +10 -0
  191. package/server/lib/openchamber-control/actions.js +3 -2
  192. package/server/lib/openchamber-control/error.js +1 -1
  193. package/server/lib/openchamber-control/file-open.js +59 -0
  194. package/server/lib/openchamber-control/file-open.test.js +57 -0
  195. package/server/lib/openchamber-control/routes.test.js +12 -0
  196. package/server/lib/openchamber-control/service.js +102 -49
  197. package/server/lib/openchamber-control/service.test.js +84 -44
  198. package/server/lib/openchamber-sessions/archive-store.js +224 -0
  199. package/server/lib/openchamber-sessions/archive-store.test.js +187 -0
  200. package/server/lib/openchamber-sessions/opencode-client.js +22 -0
  201. package/server/lib/openchamber-sessions/routes.js +398 -328
  202. package/server/lib/openchamber-sessions/routes.test.js +786 -700
  203. package/server/lib/openchamber-sessions/session-metadata-store.js +285 -0
  204. package/server/lib/openchamber-sessions/session-metadata-store.test.js +259 -0
  205. package/server/lib/opencode/DOCUMENTATION.md +450 -30
  206. package/server/lib/opencode/agents.js +233 -327
  207. package/server/lib/opencode/auth.js +41 -44
  208. package/server/lib/opencode/auth.test.js +92 -0
  209. package/server/lib/opencode/bootstrap-runtime.js +1 -0
  210. package/server/lib/opencode/cli-upgrade.d.ts +4 -0
  211. package/server/lib/opencode/cli-upgrade.js +18 -0
  212. package/server/lib/opencode/cli-upgrade.test.js +36 -0
  213. package/server/lib/opencode/commands.js +164 -145
  214. package/server/lib/opencode/compatibility.d.ts +16 -0
  215. package/server/lib/opencode/compatibility.js +88 -0
  216. package/server/lib/opencode/compatibility.test.js +62 -0
  217. package/server/lib/opencode/config-entity-routes.js +58 -29
  218. package/server/lib/opencode/config-entity-v2.test.js +290 -0
  219. package/server/lib/opencode/config-mutation-response.js +17 -7
  220. package/server/lib/opencode/config-mutation-response.test.js +4 -7
  221. package/server/lib/opencode/config-paths.test.js +2 -2
  222. package/server/lib/opencode/config-v2.d.ts +183 -0
  223. package/server/lib/opencode/config-v2.js +801 -0
  224. package/server/lib/opencode/config-v2.test.js +466 -0
  225. package/server/lib/opencode/credential-db.js +144 -0
  226. package/server/lib/opencode/credential-db.test.js +104 -0
  227. package/server/lib/opencode/env-runtime.js +48 -9
  228. package/server/lib/opencode/env-runtime.test.js +45 -0
  229. package/server/lib/opencode/feature-routes-runtime.js +15 -5
  230. package/server/lib/opencode/lifecycle-process.test.js +7 -4
  231. package/server/lib/opencode/lifecycle.js +85 -30
  232. package/server/lib/opencode/lifecycle.test.js +80 -8
  233. package/server/lib/opencode/login-shell-env.js +27 -0
  234. package/server/lib/opencode/managed-config-file.js +119 -0
  235. package/server/lib/opencode/managed-config-file.test.js +152 -0
  236. package/server/lib/opencode/managed-plugin-config.js +33 -13
  237. package/server/lib/opencode/mcp.js +43 -149
  238. package/server/lib/opencode/network-runtime.js +6 -7
  239. package/server/lib/opencode/openchamber-routes.test.js +0 -1
  240. package/server/lib/opencode/plugin-routes.js +3 -3
  241. package/server/lib/opencode/plugin-routes.test.js +6 -24
  242. package/server/lib/opencode/plugins.js +91 -40
  243. package/server/lib/opencode/plugins.test.js +28 -15
  244. package/server/lib/opencode/providers.js +63 -83
  245. package/server/lib/opencode/providers.test.js +128 -59
  246. package/server/lib/opencode/proxy-agent-wiring.test.js +4 -2
  247. package/server/lib/opencode/proxy.js +179 -129
  248. package/server/lib/opencode/pwa-manifest-routes.js +4 -2
  249. package/server/lib/opencode/pwa-manifest-routes.test.js +3 -2
  250. package/server/lib/opencode/response-envelope.js +14 -0
  251. package/server/lib/opencode/response-envelope.test.js +23 -0
  252. package/server/lib/opencode/routes-upgrade.test.js +73 -116
  253. package/server/lib/opencode/routes.js +121 -428
  254. package/server/lib/opencode/server-utils-runtime.js +10 -4
  255. package/server/lib/opencode/session-activity.js +78 -0
  256. package/server/lib/opencode/session-runtime.js +79 -0
  257. package/server/lib/opencode/session-runtime.test.js +43 -0
  258. package/server/lib/opencode/settings-helpers.js +9 -9
  259. package/server/lib/opencode/settings-helpers.test.js +7 -12
  260. package/server/lib/opencode/settings-registry.json +6 -8
  261. package/server/lib/opencode/settings-runtime.js +18 -1
  262. package/server/lib/opencode/settings-runtime.test.js +31 -2
  263. package/server/lib/opencode/shared.js +54 -22
  264. package/server/lib/opencode/shared.test.js +8 -4
  265. package/server/lib/opencode/shutdown-runtime.js +54 -7
  266. package/server/lib/opencode/shutdown-runtime.test.js +224 -30
  267. package/server/lib/opencode/skill-routes.js +23 -24
  268. package/server/lib/opencode/skills.js +7 -5
  269. package/server/lib/opencode/tunnel-wiring-runtime.js +2 -1
  270. package/server/lib/opencode/upgrade-capability.test.js +1 -1
  271. package/server/lib/opencode/v1-migration-topup.js +288 -0
  272. package/server/lib/opencode/v1-migration-topup.test.js +266 -0
  273. package/server/lib/opencode/v2-install.d.ts +8 -0
  274. package/server/lib/opencode/v2-install.js +158 -0
  275. package/server/lib/opencode/v2-install.test.js +124 -0
  276. package/server/lib/opencode/watcher.js +10 -3
  277. package/server/lib/opencode/watcher.test.js +17 -21
  278. package/server/lib/opencode/websearch-config.js +66 -0
  279. package/server/lib/permission-auto-accept/runtime.js +38 -22
  280. package/server/lib/permission-auto-accept/runtime.test.js +39 -17
  281. package/server/lib/projects/project-config.js +2 -2
  282. package/server/lib/quota/DOCUMENTATION.md +4 -0
  283. package/server/lib/quota/providers/xai.js +4 -4
  284. package/server/lib/realtime-proxy-terminal.test.js +150 -0
  285. package/server/lib/realtime-proxy.js +2 -0
  286. package/server/lib/relay/tunnel-host.js +4 -1
  287. package/server/lib/relay/tunnel-host.test.js +7 -0
  288. package/server/lib/routing/DOCUMENTATION.md +52 -19
  289. package/server/lib/routing/defaults.js +23 -6
  290. package/server/lib/routing/jev.js +17 -7
  291. package/server/lib/routing/routes.http.test.js +68 -33
  292. package/server/lib/routing/routes.js +65 -22
  293. package/server/lib/routing/runtime.js +145 -48
  294. package/server/lib/routing/runtime.test.js +79 -55
  295. package/server/lib/scheduled-tasks/DOCUMENTATION.md +4 -0
  296. package/server/lib/scheduled-tasks/issue-2710-double-execution.test.js +51 -46
  297. package/server/lib/scheduled-tasks/runtime.js +83 -76
  298. package/server/lib/scheduled-tasks/runtime.test.js +67 -1
  299. package/server/lib/session-assist/DOCUMENTATION.md +8 -3
  300. package/server/lib/session-assist/context.js +122 -46
  301. package/server/lib/session-assist/context.test.js +117 -49
  302. package/server/lib/session-assist/runtime.js +52 -22
  303. package/server/lib/session-assist/runtime.test.js +145 -173
  304. package/server/lib/session-goal/DOCUMENTATION.md +23 -15
  305. package/server/lib/session-goal/create.js +9 -12
  306. package/server/lib/session-goal/create.test.js +27 -28
  307. package/server/lib/session-goal/runtime.js +164 -77
  308. package/server/lib/session-goal/runtime.test.js +271 -519
  309. package/server/lib/session-knowledge/DOCUMENTATION.md +5 -0
  310. package/server/lib/session-knowledge/runtime.js +59 -41
  311. package/server/lib/session-knowledge/runtime.test.js +90 -20
  312. package/server/lib/small-model/DOCUMENTATION.md +154 -196
  313. package/server/lib/small-model/client.js +113 -0
  314. package/server/lib/small-model/index.js +296 -158
  315. package/server/lib/small-model/index.test.js +423 -256
  316. package/server/lib/small-model/routes.js +1 -1
  317. package/server/lib/spaces/DOCUMENTATION.md +807 -0
  318. package/server/lib/spaces/code-in-bait.js +185 -0
  319. package/server/lib/spaces/code-in.js +641 -0
  320. package/server/lib/spaces/code-in.test.js +1048 -0
  321. package/server/lib/spaces/errors.js +8 -0
  322. package/server/lib/spaces/exec-http.js +94 -0
  323. package/server/lib/spaces/gatekeeper-channel.js +202 -0
  324. package/server/lib/spaces/gatekeeper-channel.test.js +215 -0
  325. package/server/lib/spaces/gatekeeper-program.cjs +914 -0
  326. package/server/lib/spaces/gatekeeper-program.test.js +1391 -0
  327. package/server/lib/spaces/hardening.js +457 -0
  328. package/server/lib/spaces/hardening.test.js +368 -0
  329. package/server/lib/spaces/host-git.js +127 -0
  330. package/server/lib/spaces/host-git.test.js +137 -0
  331. package/server/lib/spaces/labels.js +234 -0
  332. package/server/lib/spaces/labels.test.js +219 -0
  333. package/server/lib/spaces/layout.js +184 -0
  334. package/server/lib/spaces/layout.test.js +30 -0
  335. package/server/lib/spaces/manager.js +82 -0
  336. package/server/lib/spaces/manager.test.js +114 -0
  337. package/server/lib/spaces/places/code-in.docker.live.test.js +216 -0
  338. package/server/lib/spaces/places/contract-suite.js +156 -0
  339. package/server/lib/spaces/places/contract.docker.live.test.js +7 -0
  340. package/server/lib/spaces/places/contract.test.js +6 -0
  341. package/server/lib/spaces/places/docker-engine.js +126 -0
  342. package/server/lib/spaces/places/docker-live-support.js +202 -0
  343. package/server/lib/spaces/places/docker-tools.js +186 -0
  344. package/server/lib/spaces/places/docker.js +587 -0
  345. package/server/lib/spaces/places/docker.test.js +1610 -0
  346. package/server/lib/spaces/places/escape-suite.js +1018 -0
  347. package/server/lib/spaces/places/escape.docker.live.test.js +7 -0
  348. package/server/lib/spaces/places/fake-docker.js +375 -0
  349. package/server/lib/spaces/places/memory-place.js +103 -0
  350. package/server/lib/spaces/places/packed.docker.live.test.js +77 -0
  351. package/server/lib/spaces/places/registry.js +43 -0
  352. package/server/lib/spaces/places/registry.test.js +50 -0
  353. package/server/lib/spaces/places/server.docker.live.test.js +225 -0
  354. package/server/lib/spaces/run-command.js +261 -0
  355. package/server/lib/spaces/run-command.test.js +396 -0
  356. package/server/lib/spaces/space-server.js +190 -0
  357. package/server/lib/spaces/space-server.test.js +335 -0
  358. package/server/lib/spaces/tools-filler.js +82 -0
  359. package/server/lib/spaces/tools-filler.test.js +148 -0
  360. package/server/lib/spaces/tools-pack.js +49 -0
  361. package/server/lib/spaces/tools-pack.test.js +57 -0
  362. package/server/lib/spaces/tools.js +137 -0
  363. package/server/lib/spaces/tools.test.js +153 -0
  364. package/server/lib/terminal/DOCUMENTATION.md +21 -2
  365. package/server/lib/terminal/runtime.js +10 -3
  366. package/server/lib/terminal/runtime.test.js +22 -0
  367. package/server/lib/terminal/shutdown.js +106 -0
  368. package/server/lib/terminal/shutdown.test.js +84 -0
  369. package/server/lib/tts/openai-sdk.js +11 -0
  370. package/server/lib/tts/service.js +7 -5
  371. package/server/lib/tts/service.test.js +78 -0
  372. package/server/lib/tts/stt.js +3 -2
  373. package/server/lib/tunnels/DOCUMENTATION.md +2 -0
  374. package/server/lib/tunnels/routes.js +7 -0
  375. package/server/lib/tunnels/routes.test.js +55 -0
  376. package/server/lib/ui-auth/ui-auth.js +38 -2
  377. package/server/lib/ui-auth/ui-auth.test.js +42 -0
  378. package/server/lib/ui-auth/ui-passkeys.js +12 -10
  379. package/server/lib/walkthrough/DOCUMENTATION.md +10 -1
  380. package/server/lib/walkthrough/pull-request.js +61 -8
  381. package/server/lib/walkthrough/pull-request.test.js +54 -1
  382. package/server/lib/walkthrough/routes.js +20 -0
  383. package/server/lib/walkthrough/routes.test.js +19 -0
  384. package/server/opencode-proxy.test.js +190 -166
  385. package/server/opencode-worktree-readiness.test.js +5 -4
  386. package/dist/assets/DiffView-DkC3xlRJ.js +0 -4
  387. package/dist/assets/FilesView-D0bM9FVB.js +0 -13
  388. package/dist/assets/LinearIssuesView-UI1FcSC8.js +0 -1
  389. package/dist/assets/MarkdownImageGallery-CUJxH8Le.js +0 -1
  390. package/dist/assets/MarkdownRendererImpl-D5BZOg8X.js +0 -12
  391. package/dist/assets/OnboardingScreen-5Gou9cGD.js +0 -1
  392. package/dist/assets/PierreDiffViewer-ByRVu6ss.js +0 -161
  393. package/dist/assets/PlanView-u2yi5XGJ.js +0 -5
  394. package/dist/assets/PluginPane-QxjsKYeO.js +0 -3
  395. package/dist/assets/SettingsView-Fo5ZqMaT.js +0 -29
  396. package/dist/assets/SettingsWindow-HVDVANjJ.js +0 -1
  397. package/dist/assets/SubmoduleDiffSummary-D3hzkybB.js +0 -1
  398. package/dist/assets/ToolOutputDialog-3J6IRayW.js +0 -15
  399. package/dist/assets/ToolPartDiffPreview-DarxPjSd.js +0 -8
  400. package/dist/assets/appThemeRegistry-Cf8KitzT.js +0 -1
  401. package/dist/assets/de-BM_8EDD3.js +0 -10
  402. package/dist/assets/es-CxZjlqpo.js +0 -16
  403. package/dist/assets/fr-VCixCnMW.js +0 -14
  404. package/dist/assets/index-3U4CtS9b.js +0 -1
  405. package/dist/assets/index-B9Hvzjwl.css +0 -1
  406. package/dist/assets/index-DLHQogv8.js +0 -40
  407. package/dist/assets/ja-CZ5k_GyD.js +0 -16
  408. package/dist/assets/ko-7YM3A1Xh.js +0 -16
  409. package/dist/assets/main-CycplCph.js +0 -2
  410. package/dist/assets/main-DFYTCx5o.js +0 -896
  411. package/dist/assets/markdownCore-DHvqMxPn.js +0 -5
  412. package/dist/assets/miniChat-DIQKfY2V.js +0 -2
  413. package/dist/assets/mobile-BMwz5q-m.js +0 -2
  414. package/dist/assets/pl-BcgDO_w5.js +0 -16
  415. package/dist/assets/pt-BR-CU2u_1q5.js +0 -16
  416. package/dist/assets/renderElectronMiniChatApp-3_d6g6CU.js +0 -2
  417. package/dist/assets/renderMobileApp-D0Y8DtkA.js +0 -25
  418. package/dist/assets/runtimeEndpointReset-DhC3REb2.js +0 -25
  419. package/dist/assets/scheduledTasksApi-D8pq6gQz.js +0 -1
  420. package/dist/assets/tr-DuYhOzNe.js +0 -7
  421. package/dist/assets/uk-Cuk7-uvq.js +0 -16
  422. package/dist/assets/useAppFontEffects-BItUWdo4.js +0 -7333
  423. package/dist/assets/useInlineCommentController-CkbKsm7m.js +0 -2
  424. package/dist/assets/useRootScrollLock-vmzxZjWA.js +0 -2
  425. package/dist/assets/vendor-cron-parser-CUcP7OfX.js +0 -2
  426. package/dist/assets/vendor-opencode-sdk-BJ73u-bH.js +0 -7
  427. package/dist/assets/zh-CN-CUWoiRHd.js +0 -16
  428. package/dist/assets/zh-TW-CQ8EBSBN.js +0 -16
  429. package/server/lib/opencode/mcp-oauth-callback.test.js +0 -111
  430. package/server/lib/routing/feature-flag.js +0 -11
  431. package/server/lib/small-model/call.js +0 -820
  432. package/server/lib/small-model/call.test.js +0 -1110
  433. package/server/lib/small-model/catalog.js +0 -13
  434. package/server/lib/small-model/resolve.js +0 -131
  435. package/server/lib/small-model/resolve.test.js +0 -197
  436. package/server/lib/small-model/runtime-providers.js +0 -164
  437. package/server/lib/small-model/runtime-providers.test.js +0 -118
  438. package/server/lib/system-prompt/DOCUMENTATION.md +0 -36
  439. package/server/lib/system-prompt/runtime.js +0 -49
  440. package/server/lib/system-prompt/runtime.test.js +0 -76
  441. package/server/lib/walkthrough/reproduce-2607.test.js +0 -148
  442. /package/dist/assets/{vendor-katex-k3Ppq1Ha.js → vendor-katex-CHD9BdDO.js} +0 -0
@@ -1,820 +0,0 @@
1
- import fs from 'fs';
2
- import os from 'os';
3
- import path from 'path';
4
- import { randomUUID } from 'node:crypto';
5
- import { readAuthFile, writeAuthFile } from '../opencode/auth.js';
6
- import { readConfig, readConfigLayers, isPlainObject } from '../opencode/shared.js';
7
- import { getCatalogProvider } from './catalog.js';
8
- import { getAuthEntryForProvider } from './resolve.js';
9
- import { getRuntimeProvider } from './runtime-providers.js';
10
-
11
- // Direct, non-streaming text generation against the provider APIs, replicating
12
- // how OpenCode authenticates each of them (see the plugin auth loaders in the
13
- // opencode repo). auth.json credentials never leave this process.
14
-
15
- const REQUEST_TIMEOUT_MS = 60_000;
16
- const COPILOT_MODELS_TIMEOUT_MS = 5_000;
17
- // Generous default: thinking models that can't be switched off (DeepSeek,
18
- // Qwen, …) spend part of this budget on reasoning before the actual answer.
19
- const DEFAULT_MAX_OUTPUT_TOKENS = 4_000;
20
-
21
- const USER_AGENT = 'opencode/1.0 openchamber';
22
-
23
- const mergeHeadersCaseInsensitive = (base, overrides) => {
24
- const merged = { ...base };
25
- for (const [name, value] of Object.entries(overrides || {})) {
26
- const existingName = Object.keys(merged).find((key) => key.toLowerCase() === name.toLowerCase());
27
- if (existingName) {
28
- delete merged[existingName];
29
- }
30
- merged[name] = value;
31
- }
32
- return merged;
33
- };
34
-
35
- const CODEX_TOKEN_URL = 'https://auth.openai.com/oauth/token';
36
- const CODEX_CLIENT_ID = 'app_EMoamEEZ73f0CkXaXp7hrann';
37
- const CODEX_RESPONSES_URL = 'https://chatgpt.com/backend-api/codex/responses';
38
-
39
- const httpError = async (response, provider) => {
40
- const body = await response.text().catch(() => '');
41
- const snippet = body ? `: ${body.slice(0, 300)}` : '';
42
- // Callers need the status to tell "this provider rejected the request shape"
43
- // (retryable with a different shape) from "this provider is down".
44
- return Object.assign(new Error(`${provider} request failed with ${response.status}${snippet}`), {
45
- status: response.status,
46
- provider,
47
- });
48
- };
49
-
50
- // Callers own two independent reasons to stop: their own abort signal (user
51
- // navigated away, request cancelled) and a per-call deadline. Long-running
52
- // callers such as the diff walkthrough need a deadline well past the default.
53
- const requestSignal = (timeoutMs, signal) => {
54
- const deadline = AbortSignal.timeout(Number(timeoutMs) > 0 ? Number(timeoutMs) : REQUEST_TIMEOUT_MS);
55
- return signal ? AbortSignal.any([deadline, signal]) : deadline;
56
- };
57
-
58
- const STRUCTURED_OUTPUT_NAME = 'response';
59
-
60
- // Google's schema dialect is OpenAPI-flavored and rejects JSON Schema keywords
61
- // it does not know, so unsupported keys are dropped rather than passed through.
62
- const GOOGLE_UNSUPPORTED_SCHEMA_KEYS = new Set([
63
- '$schema',
64
- 'additionalProperties',
65
- 'definitions',
66
- '$defs',
67
- '$ref',
68
- 'strict',
69
- ]);
70
-
71
- const toGoogleSchema = (schema) => {
72
- if (Array.isArray(schema)) return schema.map(toGoogleSchema);
73
- if (!schema || typeof schema !== 'object') return schema;
74
- const result = {};
75
- for (const [key, value] of Object.entries(schema)) {
76
- if (GOOGLE_UNSUPPORTED_SCHEMA_KEYS.has(key)) continue;
77
- result[key] = toGoogleSchema(value);
78
- }
79
- return result;
80
- };
81
-
82
- // ---------------------------------------------------------------------------
83
- // OpenAI OAuth (ChatGPT plan / codex) token refresh — single-flight, with the
84
- // refreshed token written back to auth.json exactly like OpenCode does.
85
- // ---------------------------------------------------------------------------
86
-
87
- let openaiRefreshPromise = null;
88
-
89
- const decodeJwtClaims = (token) => {
90
- try {
91
- const payload = token.split('.')[1];
92
- return JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));
93
- } catch {
94
- return null;
95
- }
96
- };
97
-
98
- const extractChatgptAccountId = (accessToken) => {
99
- const claims = decodeJwtClaims(accessToken);
100
- const auth = claims?.['https://api.openai.com/auth'];
101
- const value = auth?.chatgpt_account_id;
102
- return typeof value === 'string' && value ? value : null;
103
- };
104
-
105
- const refreshOpenaiOauth = async (entry) => {
106
- if (!openaiRefreshPromise) {
107
- openaiRefreshPromise = (async () => {
108
- const response = await fetch(CODEX_TOKEN_URL, {
109
- method: 'POST',
110
- headers: { 'Content-Type': 'application/json' },
111
- body: JSON.stringify({
112
- grant_type: 'refresh_token',
113
- refresh_token: entry.refresh,
114
- client_id: CODEX_CLIENT_ID,
115
- }),
116
- signal: AbortSignal.timeout(30_000),
117
- });
118
- if (!response.ok) {
119
- throw await httpError(response, 'OpenAI token refresh');
120
- }
121
- const payload = await response.json();
122
- const access = typeof payload?.access_token === 'string' ? payload.access_token : '';
123
- if (!access) {
124
- throw new Error('OpenAI token refresh returned no access token');
125
- }
126
- const refreshed = {
127
- ...entry,
128
- type: 'oauth',
129
- access,
130
- refresh: typeof payload?.refresh_token === 'string' && payload.refresh_token
131
- ? payload.refresh_token
132
- : entry.refresh,
133
- expires: Date.now() + (Number(payload?.expires_in) > 0 ? Number(payload.expires_in) : 3600) * 1000,
134
- };
135
- const auth = readAuthFile();
136
- auth.openai = refreshed;
137
- writeAuthFile(auth);
138
- return refreshed;
139
- })().finally(() => {
140
- openaiRefreshPromise = null;
141
- });
142
- }
143
- return openaiRefreshPromise;
144
- };
145
-
146
- const ensureFreshOpenaiOauth = async (entry) => {
147
- if (entry.access && Number(entry.expires) > Date.now()) {
148
- return entry;
149
- }
150
- if (!entry.refresh) {
151
- throw new Error('OpenAI OAuth entry has no refresh token');
152
- }
153
- return refreshOpenaiOauth(entry);
154
- };
155
-
156
- // ---------------------------------------------------------------------------
157
- // Wire formats
158
- // ---------------------------------------------------------------------------
159
-
160
- const callOpenaiCompatible = async ({ baseURL, headers, modelID, prompt, system, maxOutputTokens, providerLabel, extraBody, responseSchema, timeoutMs, signal }) => {
161
- const trimmedBase = baseURL.replace(/\/+$/, '');
162
- console.log('[small-model:diagnostic] request', {
163
- provider: providerLabel,
164
- model: modelID,
165
- maxOutputTokens,
166
- thinkingDisabled: extraBody?.thinking?.type === 'disabled',
167
- promptChars: prompt.length,
168
- systemChars: system?.length ?? 0,
169
- inputChars: prompt.length + (system?.length ?? 0),
170
- });
171
- const response = await fetch(`${trimmedBase}/chat/completions`, {
172
- method: 'POST',
173
- headers: mergeHeadersCaseInsensitive({
174
- 'Content-Type': 'application/json',
175
- Accept: 'application/json',
176
- }, headers),
177
- body: JSON.stringify({
178
- model: modelID,
179
- messages: [
180
- ...(system ? [{ role: 'system', content: system }] : []),
181
- { role: 'user', content: prompt },
182
- ],
183
- max_tokens: maxOutputTokens,
184
- stream: false,
185
- ...(responseSchema
186
- ? {
187
- response_format: {
188
- type: 'json_schema',
189
- json_schema: { name: STRUCTURED_OUTPUT_NAME, strict: true, schema: responseSchema },
190
- },
191
- }
192
- : {}),
193
- ...(extraBody || {}),
194
- }),
195
- signal: requestSignal(timeoutMs, signal),
196
- });
197
- console.log('[small-model:diagnostic] response', {
198
- provider: providerLabel,
199
- model: modelID,
200
- httpStatus: response.status,
201
- ok: response.ok,
202
- });
203
- if (!response.ok) {
204
- throw await httpError(response, providerLabel);
205
- }
206
- const payload = await response.json();
207
- const message = payload?.choices?.[0]?.message;
208
- console.log('[small-model:diagnostic] completion', {
209
- provider: providerLabel,
210
- model: modelID,
211
- finishReason: payload?.choices?.[0]?.finish_reason ?? null,
212
- contentType: Array.isArray(message?.content) ? 'parts' : typeof message?.content,
213
- contentChars: typeof message?.content === 'string'
214
- ? message.content.length
215
- : Array.isArray(message?.content)
216
- ? message.content.reduce((total, part) => total + (typeof part?.text === 'string' ? part.text.length : 0), 0)
217
- : 0,
218
- reasoningChars: typeof message?.reasoning_content === 'string' ? message.reasoning_content.length : 0,
219
- });
220
-
221
- // Providers disagree on the content shape: plain string, an array of
222
- // typed parts, or (thinking models) an empty content with the budget spent
223
- // on reasoning_content.
224
- let text = '';
225
- if (typeof message?.content === 'string') {
226
- text = message.content;
227
- } else if (Array.isArray(message?.content)) {
228
- text = message.content
229
- .map((part) => (typeof part?.text === 'string' ? part.text : ''))
230
- .join('');
231
- }
232
- const finishReason = payload?.choices?.[0]?.finish_reason;
233
- if (!text.trim() && (finishReason === 'length' || (typeof message?.reasoning_content === 'string' && message.reasoning_content.trim()))) {
234
- // The model produced only reasoning, or was cut off before answering. This
235
- // is a budget problem, not a transport problem, and callers can act on it.
236
- throw Object.assign(
237
- new Error(
238
- `${providerLabel} spent the output budget on reasoning and returned no answer`
239
- + (finishReason ? ` (finish_reason: ${finishReason})` : ''),
240
- ),
241
- { code: 'output-exhausted', provider: providerLabel },
242
- );
243
- }
244
- if (!text.trim()) {
245
- throw new Error(`${providerLabel} returned no message content`);
246
- }
247
- return text;
248
- };
249
-
250
- const callOpenaiResponses = async ({ baseURL, headers, modelID, prompt, system, maxOutputTokens, providerLabel, responseSchema, timeoutMs, signal }) => {
251
- const trimmedBase = baseURL.replace(/\/+$/, '');
252
- const response = await fetch(`${trimmedBase}/responses`, {
253
- method: 'POST',
254
- headers: {
255
- 'Content-Type': 'application/json',
256
- Accept: 'application/json',
257
- ...headers,
258
- },
259
- body: JSON.stringify({
260
- model: modelID,
261
- ...(system ? { instructions: system } : {}),
262
- input: [{
263
- role: 'user',
264
- content: [{ type: 'input_text', text: prompt }],
265
- }],
266
- max_output_tokens: maxOutputTokens,
267
- ...(responseSchema
268
- ? {
269
- text: {
270
- format: {
271
- type: 'json_schema',
272
- name: STRUCTURED_OUTPUT_NAME,
273
- strict: true,
274
- schema: responseSchema,
275
- },
276
- },
277
- }
278
- : {}),
279
- stream: false,
280
- store: false,
281
- }),
282
- signal: requestSignal(timeoutMs, signal),
283
- });
284
- if (!response.ok) {
285
- throw await httpError(response, providerLabel);
286
- }
287
- const payload = await response.json();
288
- const text = typeof payload?.output_text === 'string'
289
- ? payload.output_text
290
- : Array.isArray(payload?.output)
291
- ? payload.output
292
- .flatMap((item) => (Array.isArray(item?.content) ? item.content : []))
293
- .map((part) => (part?.type === 'output_text' && typeof part.text === 'string' ? part.text : ''))
294
- .join('')
295
- : '';
296
- if (!text.trim()) {
297
- throw new Error(`${providerLabel} returned no text output`);
298
- }
299
- return text;
300
- };
301
-
302
- const callMessages = async ({ url, headers, modelID, prompt, system, maxOutputTokens, providerLabel, responseSchema, timeoutMs, signal }) => {
303
- const response = await fetch(url, {
304
- method: 'POST',
305
- headers: {
306
- 'Content-Type': 'application/json',
307
- Accept: 'application/json',
308
- ...headers,
309
- },
310
- body: JSON.stringify({
311
- model: modelID,
312
- max_tokens: maxOutputTokens,
313
- ...(system ? { system } : {}),
314
- messages: [{ role: 'user', content: prompt }],
315
- // The messages API has no response_format; a forced single-tool call is
316
- // the supported way to get schema-shaped output.
317
- ...(responseSchema
318
- ? {
319
- tools: [{
320
- name: STRUCTURED_OUTPUT_NAME,
321
- description: 'Return the answer in the required structure.',
322
- input_schema: responseSchema,
323
- }],
324
- tool_choice: { type: 'tool', name: STRUCTURED_OUTPUT_NAME },
325
- }
326
- : {}),
327
- }),
328
- signal: requestSignal(timeoutMs, signal),
329
- });
330
- if (!response.ok) {
331
- throw await httpError(response, providerLabel);
332
- }
333
- const payload = await response.json();
334
-
335
- if (responseSchema) {
336
- const toolUse = (payload?.content || []).find(
337
- (part) => part?.type === 'tool_use' && part.name === STRUCTURED_OUTPUT_NAME,
338
- );
339
- if (!toolUse || typeof toolUse.input !== 'object' || toolUse.input === null) {
340
- throw new Error(`${providerLabel} returned no structured output`);
341
- }
342
- return JSON.stringify(toolUse.input);
343
- }
344
-
345
- const text = (payload?.content || [])
346
- .filter((part) => part?.type === 'text' && typeof part.text === 'string')
347
- .map((part) => part.text)
348
- .join('');
349
- if (!text) {
350
- throw new Error(`${providerLabel} returned no text content`);
351
- }
352
- return text;
353
- };
354
-
355
- const callAnthropic = async ({ apiKey, baseURL, modelID, prompt, system, maxOutputTokens, responseSchema, timeoutMs, signal }) => callMessages({
356
- // Matches @ai-sdk/anthropic: baseURL is the full API prefix (commonly
357
- // already ending in /v1), so it gets /messages appended as-is rather than
358
- // having /v1/messages appended, which would double up a configured /v1.
359
- url: `${(baseURL || 'https://api.anthropic.com/v1').replace(/\/+$/, '')}/messages`,
360
- headers: {
361
- 'x-api-key': apiKey,
362
- 'anthropic-version': '2023-06-01',
363
- },
364
- modelID,
365
- prompt,
366
- system,
367
- maxOutputTokens,
368
- providerLabel: 'Anthropic',
369
- responseSchema,
370
- timeoutMs,
371
- signal,
372
- });
373
-
374
- const getCopilotEndpoint = async ({ baseURL, headers, modelID }) => {
375
- const trimmedBase = baseURL.replace(/\/+$/, '');
376
- const response = await fetch(`${trimmedBase}/models`, {
377
- headers: {
378
- Accept: 'application/json',
379
- ...headers,
380
- },
381
- signal: AbortSignal.timeout(COPILOT_MODELS_TIMEOUT_MS),
382
- });
383
- if (!response.ok) {
384
- throw await httpError(response, 'GitHub Copilot models');
385
- }
386
-
387
- let payload;
388
- try {
389
- payload = await response.json();
390
- } catch {
391
- throw new Error('GitHub Copilot models returned invalid JSON');
392
- }
393
- if (!Array.isArray(payload?.data)) {
394
- throw new Error('GitHub Copilot models returned an invalid model list');
395
- }
396
-
397
- const model = payload.data.find((item) => item && typeof item === 'object' && item.id === modelID);
398
- if (!model) {
399
- throw new Error(`GitHub Copilot model "${modelID}" was not returned by /models`);
400
- }
401
- if (model.supported_endpoints === undefined) {
402
- return 'chat';
403
- }
404
- if (!Array.isArray(model.supported_endpoints)) {
405
- throw new Error(`GitHub Copilot model "${modelID}" returned invalid endpoint metadata`);
406
- }
407
- if (model.supported_endpoints.includes('/v1/messages')) {
408
- return 'messages';
409
- }
410
- if (model.supported_endpoints.includes('/responses')) {
411
- return 'responses';
412
- }
413
- if (model.supported_endpoints.includes('/chat/completions')) {
414
- return 'chat';
415
- }
416
- throw new Error(`GitHub Copilot model "${modelID}" has no supported text endpoint`);
417
- };
418
-
419
- const callGoogle = async ({ apiKey, modelID, prompt, system, maxOutputTokens, responseSchema, timeoutMs, signal }) => {
420
- const url = `https://generativelanguage.googleapis.com/v1beta/models/${encodeURIComponent(modelID)}:generateContent`;
421
- const lowerModelID = modelID.toLowerCase();
422
- const thinkingConfig = lowerModelID.startsWith('gemini-3')
423
- ? { thinkingLevel: lowerModelID.includes('flash') ? 'minimal' : 'low' }
424
- : lowerModelID.startsWith('gemini-2') ? { thinkingBudget: 0 } : null;
425
- const response = await fetch(url, {
426
- method: 'POST',
427
- headers: {
428
- 'Content-Type': 'application/json',
429
- Accept: 'application/json',
430
- 'x-goog-api-key': apiKey,
431
- },
432
- body: JSON.stringify({
433
- contents: [{ role: 'user', parts: [{ text: prompt }] }],
434
- ...(system && { systemInstruction: { parts: [{ text: system }] } }),
435
- generationConfig: {
436
- maxOutputTokens,
437
- ...(thinkingConfig && { thinkingConfig }),
438
- ...(responseSchema && { responseMimeType: 'application/json', responseSchema: toGoogleSchema(responseSchema) }),
439
- },
440
- }),
441
- signal: requestSignal(timeoutMs, signal),
442
- });
443
- if (!response.ok) {
444
- throw await httpError(response, 'Google');
445
- }
446
- const payload = await response.json();
447
- const text = (payload?.candidates?.[0]?.content?.parts || [])
448
- .map((part) => (typeof part?.text === 'string' ? part.text : ''))
449
- .join('');
450
- if (!text) {
451
- throw new Error('Google returned no text content');
452
- }
453
- return text;
454
- };
455
-
456
- // ChatGPT-plan traffic goes to the codex backend, which only speaks the
457
- // streaming Responses API — collect the output_text deltas from the SSE body.
458
- const callCodexResponses = async ({ accessToken, accountId, modelID, prompt, system, timeoutMs, signal }) => {
459
- const response = await fetch(CODEX_RESPONSES_URL, {
460
- method: 'POST',
461
- headers: {
462
- 'Content-Type': 'application/json',
463
- Accept: 'text/event-stream',
464
- Authorization: `Bearer ${accessToken}`,
465
- ...(accountId ? { 'ChatGPT-Account-Id': accountId } : {}),
466
- originator: 'opencode',
467
- 'User-Agent': USER_AGENT,
468
- },
469
- body: JSON.stringify({
470
- model: modelID,
471
- ...(system ? { instructions: system } : {}),
472
- input: [
473
- {
474
- type: 'message',
475
- role: 'user',
476
- content: [{ type: 'input_text', text: prompt }],
477
- },
478
- ],
479
- // The codex backend rejects max_output_tokens (OpenCode forces it to
480
- // undefined for this provider too).
481
- stream: true,
482
- store: false,
483
- }),
484
- signal: requestSignal(timeoutMs, signal),
485
- });
486
- if (!response.ok) {
487
- throw await httpError(response, 'OpenAI (ChatGPT plan)');
488
- }
489
-
490
- const raw = await response.text();
491
- let text = '';
492
- let completedText = '';
493
- for (const line of raw.split('\n')) {
494
- if (!line.startsWith('data:')) continue;
495
- const data = line.slice(5).trim();
496
- if (!data || data === '[DONE]') continue;
497
- let event;
498
- try {
499
- event = JSON.parse(data);
500
- } catch {
501
- continue;
502
- }
503
- if (event?.type === 'response.output_text.delta' && typeof event.delta === 'string') {
504
- text += event.delta;
505
- }
506
- if (event?.type === 'response.output_text.done' && typeof event.text === 'string') {
507
- completedText = event.text;
508
- }
509
- if (event?.type === 'response.failed' || event?.type === 'error') {
510
- const message = event?.response?.error?.message || event?.message || 'response failed';
511
- throw new Error(`OpenAI (ChatGPT plan) stream error: ${message}`);
512
- }
513
- }
514
- const result = completedText || text;
515
- if (!result) {
516
- throw new Error('OpenAI (ChatGPT plan) returned no text output');
517
- }
518
- return result;
519
- };
520
-
521
- // ---------------------------------------------------------------------------
522
- // Custom provider configuration support
523
- // ---------------------------------------------------------------------------
524
-
525
- const resolveConfigValue = (value, workingDirectory, providerID, headerName = null) => {
526
- const envMatch = value.match(/^\{env:([^}]+)\}$/i);
527
- if (envMatch) {
528
- return process.env[envMatch[1].trim()]?.trim() || null;
529
- }
530
-
531
- const fileMatch = value.match(/^\{file:(.+)\}$/i);
532
- if (!fileMatch) return value;
533
-
534
- const configuredPath = fileMatch[1].trim();
535
- let resolvedPath;
536
- if (configuredPath === '~' || configuredPath.startsWith('~/') || configuredPath.startsWith('~\\')) {
537
- resolvedPath = path.join(os.homedir(), configuredPath.slice(2));
538
- } else if (path.isAbsolute(configuredPath)) {
539
- resolvedPath = configuredPath;
540
- } else {
541
- const layers = readConfigLayers(workingDirectory);
542
- const source = [
543
- { config: layers.customConfig, filePath: layers.paths.customPath },
544
- { config: layers.projectConfig, filePath: layers.paths.projectPath },
545
- { config: layers.userConfig, filePath: layers.paths.userPath },
546
- ].find(({ config }) => {
547
- const options = config?.provider?.[providerID]?.options;
548
- return headerName
549
- ? options?.headers?.[headerName] === value
550
- : options?.apiKey === value;
551
- });
552
- resolvedPath = path.resolve(source?.filePath ? path.dirname(source.filePath) : workingDirectory || process.cwd(), configuredPath);
553
- }
554
-
555
- try {
556
- const key = fs.readFileSync(resolvedPath, 'utf8').trim();
557
- if (!key) throw new Error('empty file');
558
- return key;
559
- } catch {
560
- throw new Error(`Failed to resolve configured ${headerName ? `header "${headerName}"` : 'apiKey'} file for provider "${providerID}"`);
561
- }
562
- };
563
-
564
- /**
565
- * `options.headers` from the provider config, with the same `{env:…}`/`{file:…}`
566
- * substitutions the API key gets.
567
- *
568
- * OpenCode sends these on every request, so dropping them here would have the
569
- * small model authenticating differently from the request path against the same
570
- * URL. Gateways fronted by an API-management layer reject a bearer-only request
571
- * outright, because the header is the credential rather than a supplement to it.
572
- */
573
- const readConfiguredHeaders = (providerCfg, workingDirectory, providerID) => {
574
- const configured = providerCfg?.options?.headers;
575
- if (!isPlainObject(configured)) return null;
576
- const headers = {};
577
- for (const [name, value] of Object.entries(configured)) {
578
- // Config headers are strings; a malformed entry is skipped rather than
579
- // stringified into a header the gateway would reject.
580
- if (String(value) !== value) continue;
581
- const resolved = resolveConfigValue(value.trim(), workingDirectory, providerID, name);
582
- if (resolved) headers[name] = resolved;
583
- }
584
- return Object.keys(headers).length ? headers : null;
585
- };
586
-
587
- const readProviderConfig = (workingDirectory, providerID) => {
588
- try {
589
- const config = readConfig(workingDirectory);
590
- const providerCfg = config?.provider?.[providerID];
591
- if (!providerCfg || typeof providerCfg !== 'object') return null;
592
- const baseURL = typeof providerCfg?.options?.baseURL === 'string' ? providerCfg.options.baseURL.trim() : null;
593
- const rawApiKey = typeof providerCfg?.options?.apiKey === 'string' ? providerCfg.options.apiKey.trim() : null;
594
- const apiKey = rawApiKey ? resolveConfigValue(rawApiKey, workingDirectory, providerID) : null;
595
- return {
596
- baseURL,
597
- headers: readConfiguredHeaders(providerCfg, workingDirectory, providerID),
598
- // Shape the config-supplied key as a regular api-key auth entry so it
599
- // can win the precedence check below and flow through the dispatch's
600
- // `entry.type === 'api' ? entry.key : ...` branch unchanged.
601
- auth: apiKey ? { type: 'api', key: apiKey } : null,
602
- };
603
- } catch {
604
- // Provider config is non-essential — continue with catalog-only resolution.
605
- return null;
606
- }
607
- }
608
-
609
- const getRuntimeModel = (runtimeProvider, modelID) => runtimeProvider?.models?.get(modelID) ?? null;
610
-
611
- // ---------------------------------------------------------------------------
612
- // Dispatch
613
- // ---------------------------------------------------------------------------
614
-
615
- /**
616
- * Providers reached through a dedicated wire format below: a token exchange,
617
- * an OAuth refresh, or a non-bearer header. OpenCode's runtime
618
- * `options.apiKey` is not the value those branches need — the ChatGPT-plan
619
- * `openai` login is the clearest case, where the runtime key is an OAuth
620
- * access token that api.openai.com answers with 401 — so the runtime
621
- * credential never stands in for them, and the runtime listing skips them
622
- * because the auth.json scan already covers them.
623
- */
624
- export const DEDICATED_WIRE_FORMAT_PROVIDERS = new Set(['github-copilot', 'copilot', 'openai', 'anthropic', 'google']);
625
-
626
- /**
627
- * The runtime credential shaped as an auth entry, or `null` when the provider
628
- * owns its credential handling or OpenCode reports nothing usable.
629
- */
630
- const runtimeCredential = (providerID, runtime) => (
631
- !DEDICATED_WIRE_FORMAT_PROVIDERS.has(providerID) && runtime?.apiKey
632
- ? { type: 'api', key: runtime.apiKey }
633
- : null
634
- );
635
-
636
- /**
637
- * Same credential resolution the request path uses: config
638
- * `provider.<id>.options.apiKey` wins, then the runtime credential OpenCode
639
- * resolved for a plugin provider, then the auth.json entry.
640
- * Callers that need to refuse before spending a request (walkthrough readiness)
641
- * must use this rather than inventing a second rule.
642
- */
643
- export async function resolveProviderLogin({ auth, workingDirectory, providerID }) {
644
- const providerConfig = readProviderConfig(workingDirectory, providerID);
645
- return providerConfig?.auth
646
- || runtimeCredential(providerID, await getRuntimeProvider(providerID))
647
- || getAuthEntryForProvider(auth, providerID)
648
- || null;
649
- }
650
-
651
- export async function callSmallModel({ auth, catalog, workingDirectory, sessionID, providerID, modelID, prompt, system, maxOutputTokens, responseSchema, timeoutMs, signal }) {
652
- const tokens = Number(maxOutputTokens) > 0 ? Number(maxOutputTokens) : DEFAULT_MAX_OUTPUT_TOKENS;
653
- const providerConfig = readProviderConfig(workingDirectory, providerID);
654
- const runtimeProvider = await getRuntimeProvider(providerID);
655
- const runtimeModel = getRuntimeModel(runtimeProvider, modelID);
656
- // Match OpenCode's resolveSDK precedence: config `provider.<id>.options`
657
- // wins, then what OpenCode itself resolved at runtime (the only place a
658
- // plugin's credential exists), and the auth.json entry last.
659
- const entry = providerConfig?.auth
660
- || runtimeCredential(providerID, runtimeProvider)
661
- || getAuthEntryForProvider(auth, providerID);
662
- if (!entry) {
663
- // Structured so the walkthrough (and any other caller) can show a blocker
664
- // instead of a raw 500 banner with this developer-oriented sentence.
665
- throw Object.assign(new Error(`No OpenCode login found for provider "${providerID}"`), {
666
- statusCode: 401,
667
- code: 'no-provider-login',
668
- providerID,
669
- });
670
- }
671
-
672
- if (providerID === 'github-copilot') {
673
- // OpenCode uses the stored device-OAuth token directly as the bearer —
674
- // access === refresh, no exchange, no expiry.
675
- const token = entry.refresh || entry.access || entry.key;
676
- if (!token) {
677
- throw new Error('GitHub Copilot login has no token');
678
- }
679
- const baseURL = entry.enterpriseUrl
680
- ? `https://copilot-api.${String(entry.enterpriseUrl).replace(/^https?:\/\//, '').replace(/\/+$/, '')}`
681
- : 'https://api.githubcopilot.com';
682
- const authHeaders = {
683
- Authorization: `Bearer ${token}`,
684
- 'User-Agent': USER_AGENT,
685
- 'X-GitHub-Api-Version': '2026-06-01',
686
- };
687
- const headers = {
688
- ...authHeaders,
689
- 'Openai-Intent': 'conversation-edits',
690
- 'x-initiator': 'agent',
691
- };
692
- const endpoint = await getCopilotEndpoint({
693
- baseURL,
694
- headers: authHeaders,
695
- modelID,
696
- });
697
- const request = {
698
- baseURL,
699
- headers,
700
- modelID,
701
- prompt,
702
- system,
703
- maxOutputTokens: tokens,
704
- providerLabel: 'GitHub Copilot',
705
- responseSchema,
706
- timeoutMs,
707
- signal,
708
- };
709
- if (endpoint === 'messages') {
710
- return callMessages({
711
- ...request,
712
- url: `${baseURL.replace(/\/+$/, '')}/v1/messages`,
713
- headers: {
714
- ...headers,
715
- 'anthropic-version': '2023-06-01',
716
- },
717
- });
718
- }
719
- if (endpoint === 'responses') {
720
- return callOpenaiResponses(request);
721
- }
722
- return callOpenaiCompatible(request);
723
- }
724
-
725
- if (providerID === 'openai' && entry.type === 'oauth') {
726
- // The codex backend speaks only the streaming Responses API and rejects
727
- // the structured-output fields, so a schema request fails loudly here
728
- // instead of silently returning free-form prose.
729
- if (responseSchema) {
730
- throw Object.assign(
731
- new Error('The ChatGPT-plan OpenAI login does not support structured output — choose another small model'),
732
- { code: 'structured-output-unsupported' },
733
- );
734
- }
735
- const fresh = await ensureFreshOpenaiOauth(entry);
736
- return callCodexResponses({
737
- accessToken: fresh.access,
738
- accountId: fresh.accountId || extractChatgptAccountId(fresh.access),
739
- modelID,
740
- prompt,
741
- system,
742
- timeoutMs,
743
- signal,
744
- });
745
- }
746
-
747
- const apiKey = entry.type === 'api' ? entry.key
748
- : entry.type === 'wellknown' ? entry.token
749
- : entry.access;
750
- if (!apiKey) {
751
- throw new Error(`OpenCode login for "${providerID}" has no usable credential`);
752
- }
753
-
754
- if (providerID === 'anthropic') {
755
- return callAnthropic({ apiKey, baseURL: providerConfig?.baseURL, modelID, prompt, system, maxOutputTokens: tokens, responseSchema, timeoutMs, signal });
756
- }
757
- if (providerID === 'google') {
758
- return callGoogle({ apiKey, modelID, prompt, system, maxOutputTokens: tokens, responseSchema, timeoutMs, signal });
759
- }
760
-
761
- // Everything else: OpenAI-compatible chat completions against the catalog's
762
- // base URL for that provider (openai itself included). When a custom provider
763
- // is not in the catalog (e.g. a user-configured OpenAI-compatible proxy),
764
- // fall back to its baseURL from the OpenCode provider config, then to the
765
- // selected model's endpoint OpenCode resolved at runtime, then to the
766
- // provider-level runtime endpoint. For a plugin provider, the runtime listing
767
- // is the only place those endpoints exist, and several are local proxies the
768
- // plugin itself runs. The openai provider also respects
769
- // provider.openai.options.baseURL — OpenCode itself uses the same config for
770
- // all providers including openai.
771
- const provider = getCatalogProvider(catalog, providerID);
772
- const providerConfigUrl = providerConfig?.baseURL;
773
- const defaultOpenaiUrl = 'https://api.openai.com/v1';
774
- const baseURL = typeof providerConfigUrl === 'string' && providerConfigUrl
775
- ? providerConfigUrl
776
- : providerID === 'openai'
777
- ? defaultOpenaiUrl
778
- : runtimeModel?.api?.url
779
- ?? runtimeProvider?.baseURL
780
- ?? (typeof provider?.api === 'string' && provider.api
781
- ? provider.api
782
- : null);
783
- if (!baseURL) {
784
- throw new Error(`Provider "${providerID}" has no known API base URL`);
785
- }
786
-
787
- // Thinking models burn the output budget on reasoning and leave content
788
- // empty — disable thinking where a wire-format switch exists (mirrors
789
- // OpenCode's smallOptions/variants special cases). There is NO universal
790
- // parameter: unknown body fields 400 on some providers, so this stays an
791
- // explicit allowlist. Models without a switch (DeepSeek, Qwen, Kimi, …)
792
- // just get the generous output budget.
793
- const lowerModel = modelID.toLowerCase();
794
- const supportsThinkingToggle = providerID.includes('zai')
795
- || providerID.includes('zhipu')
796
- || lowerModel.includes('glm')
797
- || lowerModel.includes('minimax-m3');
798
- const extraBody = supportsThinkingToggle ? { thinking: { type: 'disabled' } } : undefined;
799
-
800
- return callOpenaiCompatible({
801
- baseURL,
802
- // Configured headers last: a gateway that authenticates on its own header
803
- // must be able to override the bearer default rather than sit beside it.
804
- headers: mergeHeadersCaseInsensitive(
805
- mergeHeadersCaseInsensitive({ Authorization: `Bearer ${apiKey}` }, providerConfig?.headers),
806
- providerID.startsWith('opencode')
807
- ? { 'x-opencode-session': typeof sessionID === 'string' && sessionID.trim() ? sessionID.trim() : randomUUID() }
808
- : null,
809
- ),
810
- modelID,
811
- prompt,
812
- system,
813
- maxOutputTokens: tokens,
814
- providerLabel: provider?.name || providerID,
815
- extraBody,
816
- responseSchema,
817
- timeoutMs,
818
- signal,
819
- });
820
- }