@vantran-se/openchamber-web 1.24.3 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (367) hide show
  1. package/README.md +2 -8
  2. package/bin/lib/commands-connect-url.js +3 -8
  3. package/bin/lib/commands-tunnel.js +3 -0
  4. package/dist/assets/{CodeMirrorCommentWidgets-BjJHrzmU.js → CodeMirrorCommentWidgets-ntXIbhV2.js} +1 -1
  5. package/dist/assets/DiffView-CjxUovbM.js +4 -0
  6. package/dist/assets/FilesView-DFWD0RQR.js +17 -0
  7. package/dist/assets/{GitView-CDOJy5Ay.js → GitView-BWa7e5vw.js} +4 -4
  8. package/dist/assets/{GuestAttachDialog-D3S0Rjic.js → GuestAttachDialog-DdOuyZzp.js} +1 -1
  9. package/dist/assets/GuestSurfacePane-DDfzid3U.js +1 -0
  10. package/dist/assets/{JsonTreeView-D0C9nU7K.js → JsonTreeView-3sGwqexh.js} +1 -1
  11. package/dist/assets/LinearIssuesView-C6dpIdjw.js +1 -0
  12. package/dist/assets/MarkdownImageGallery-Q7YR_tl4.js +1 -0
  13. package/dist/assets/MarkdownRendererImpl-DxDV56bL.js +12 -0
  14. package/dist/assets/OnboardingScreen-rK4Stg__.js +1 -0
  15. package/dist/assets/{PatchDiff-DnEhjXcC.js → PatchDiff-DS-IMU1j.js} +1 -1
  16. package/dist/assets/{PierreDiffViewer-DyxZVVVR.js → PierreDiffViewer-DW23KWKZ.js} +1 -1
  17. package/dist/assets/PlanView-BCk_VobP.js +5 -0
  18. package/dist/assets/PluginPane-BPP1dbck.js +3 -0
  19. package/dist/assets/SettingsView-kMmrpn43.js +29 -0
  20. package/dist/assets/SettingsWindow-BpvD6IYQ.js +1 -0
  21. package/dist/assets/SubmoduleDiffSummary-BLttSS1X.js +1 -0
  22. package/dist/assets/ToolOutputDialog-CtqDqbyr.js +15 -0
  23. package/dist/assets/ToolPartDiffPreview-5FcKdyRy.js +8 -0
  24. package/dist/assets/{VirtualizedFileDiff-0pyr_mHY.js → VirtualizedFileDiff-C763hNCR.js} +4 -4
  25. package/dist/assets/{WalkthroughView-yNj4nOP5.js → WalkthroughView-lap5btCF.js} +2 -2
  26. package/dist/assets/appThemeRegistry-u4zw1l0B.js +1 -0
  27. package/dist/assets/{commitAndPush-DvJKa3Ks.js → commitAndPush-CwGJfJG-.js} +1 -1
  28. package/dist/assets/{computeVirtualFileMetrics-DxTBMuu-.js → computeVirtualFileMetrics-DW5jjX4n.js} +1 -1
  29. package/dist/assets/de-CndEg67T.js +10 -0
  30. package/dist/assets/es-DglvPlaC.js +16 -0
  31. package/dist/assets/fr-DejPCpbS.js +14 -0
  32. package/dist/assets/index-C2r64QfD.js +1 -0
  33. package/dist/assets/index-CLcM8HKx.css +1 -0
  34. package/dist/assets/index-CvLgnuNI.js +41 -0
  35. package/dist/assets/{isDiffPlainText-D7FkBMP6.js → isDiffPlainText-D47a6hMP.js} +1 -1
  36. package/dist/assets/{isFilePlainText-CL2vsrIZ.js → isFilePlainText-B-mGgeKl.js} +1 -1
  37. package/dist/assets/ja-CVpQawCd.js +16 -0
  38. package/dist/assets/ko-Bw446h9j.js +16 -0
  39. package/dist/assets/main-Bz4WWXbr.js +2 -0
  40. package/dist/assets/main-oreqDsOV.js +896 -0
  41. package/dist/assets/{markdownCore-Dh7WEsdM.js → markdownCore-D2e5sp9y.js} +4 -4
  42. package/dist/assets/miniChat-D1v2gsBI.js +2 -0
  43. package/dist/assets/mobile-DBj3lCf2.js +2 -0
  44. package/dist/assets/{patchFileDiff-Bsba8KFp.js → patchFileDiff-BpeUOV91.js} +3 -3
  45. package/dist/assets/pl-BYNlPdhm.js +16 -0
  46. package/dist/assets/pt-BR-CL-Yfv9H.js +16 -0
  47. package/dist/assets/renderElectronMiniChatApp-DVtfEB2z.js +2 -0
  48. package/dist/assets/renderMobileApp-DFp9-xbG.js +25 -0
  49. package/dist/assets/runtimeEndpointReset-CsIpUep1.js +27 -0
  50. package/dist/assets/scheduledTasksApi-B5OHVpPM.js +1 -0
  51. package/dist/assets/{shikiHighlight-8_3csmr6.js → shikiHighlight-DNm2Z_Jc.js} +1 -1
  52. package/dist/assets/{textMateThemeFromAppTheme-CHo2fCgW.js → textMateThemeFromAppTheme-DGF2kG7g.js} +1 -1
  53. package/dist/assets/tr-DzmbxLy-.js +7 -0
  54. package/dist/assets/uk-C7vQnwro.js +16 -0
  55. package/dist/assets/useAppFontEffects-Ci3FEaPf.js +7337 -0
  56. package/dist/assets/{useInlineCommentController-DkQ_gqpn.js → useInlineCommentController-CuUuakrt.js} +2 -2
  57. package/dist/assets/useRootScrollLock-CQIsyERq.js +2 -0
  58. package/dist/assets/{vendor-codemirror-language-data-CdzUmUyZ.js → vendor-codemirror-language-data-CQa7_1cr.js} +2 -2
  59. package/dist/assets/vendor-cron-parser-CjvYVigk.js +2 -0
  60. package/dist/assets/vendor-opencode-client-_BAHQo4R.js +12 -0
  61. package/dist/assets/{vendor-remixicon-react-BDmGmFCA.js → vendor-remixicon-react-D6dZ0UwF.js} +1 -1
  62. package/dist/assets/{vendor-zod-CgAdXWZO.js → vendor-zod-Gea9uBlY.js} +1 -1
  63. package/dist/assets/{web-components-B8IcVQAA.js → web-components-B6tKQyJN.js} +2 -2
  64. package/dist/assets/zh-CN-Cl0srS-z.js +16 -0
  65. package/dist/assets/zh-TW-DtII5bDb.js +16 -0
  66. package/dist/index.html +13 -7
  67. package/dist/mini-chat.html +5 -5
  68. package/dist/mobile.html +5 -5
  69. package/package.json +6 -5
  70. package/server/index.d.ts +1 -0
  71. package/server/index.js +246 -91
  72. package/server/lib/agent-tool/DOCUMENTATION.md +32 -15
  73. package/server/lib/agent-tool/runtime.js +135 -54
  74. package/server/lib/agent-tool/runtime.test.js +155 -87
  75. package/server/lib/browser-control/DOCUMENTATION.md +37 -2
  76. package/server/lib/browser-control/provider.js +217 -0
  77. package/server/lib/browser-control/provider.test.js +251 -0
  78. package/server/lib/context-obligatory/runtime.js +61 -50
  79. package/server/lib/context-obligatory/runtime.test.js +62 -162
  80. package/server/lib/event-stream/DOCUMENTATION.md +12 -1
  81. package/server/lib/event-stream/delta-coalescer.js +0 -0
  82. package/server/lib/event-stream/delta-coalescer.test.js +68 -57
  83. package/server/lib/event-stream/directory-ws-bridge.js +1 -1
  84. package/server/lib/event-stream/global-hub.js +10 -1
  85. package/server/lib/event-stream/global-hub.test.js +27 -26
  86. package/server/lib/event-stream/index.js +6 -0
  87. package/server/lib/event-stream/protocol.js +26 -19
  88. package/server/lib/event-stream/protocol.test.js +18 -7
  89. package/server/lib/event-stream/rebind.test.js +5 -5
  90. package/server/lib/event-stream/runtime.test.js +17 -15
  91. package/server/lib/event-stream/translate-v2.js +313 -0
  92. package/server/lib/event-stream/translate-v2.test.js +209 -0
  93. package/server/lib/event-stream/upstream-reader.test.js +16 -16
  94. package/server/lib/fs/DOCUMENTATION.md +4 -2
  95. package/server/lib/fs/byte-range.js +35 -0
  96. package/server/lib/fs/byte-range.test.js +31 -0
  97. package/server/lib/fs/routes.js +47 -42
  98. package/server/lib/fs/routes.test.js +123 -18
  99. package/server/lib/git/service.js +12 -0
  100. package/server/lib/github/DOCUMENTATION.md +1 -1
  101. package/server/lib/github/pr-status.js +22 -2
  102. package/server/lib/github/pr-status.test.js +27 -14
  103. package/server/lib/guests/DOCUMENTATION.md +13 -0
  104. package/server/lib/guests/catalog.js +12 -0
  105. package/server/lib/guests/catalog.test.js +33 -0
  106. package/server/lib/guests/routes.js +10 -1
  107. package/server/lib/guests/service.js +192 -14
  108. package/server/lib/guests/service.test.js +201 -1
  109. package/server/lib/guests/surface.js +630 -0
  110. package/server/lib/guests/surface.test.js +486 -0
  111. package/server/lib/markdown-image-grants/routes.js +18 -5
  112. package/server/lib/markdown-image-grants/routes.test.js +9 -6
  113. package/server/lib/message-queue/DOCUMENTATION.md +33 -22
  114. package/server/lib/message-queue/runtime.js +155 -100
  115. package/server/lib/message-queue/runtime.test.js +168 -82
  116. package/server/lib/notifications/DOCUMENTATION.md +28 -0
  117. package/server/lib/notifications/control-stream.http.test.js +68 -0
  118. package/server/lib/notifications/emitter-runtime.js +15 -0
  119. package/server/lib/notifications/emitter-runtime.test.js +32 -0
  120. package/server/lib/notifications/push-runtime.js +5 -1
  121. package/server/lib/notifications/push-runtime.test.js +2 -2
  122. package/server/lib/notifications/routes.js +1 -1
  123. package/server/lib/notifications/runtime.js +115 -26
  124. package/server/lib/notifications/template-runtime.js +13 -15
  125. package/server/lib/notifications/template-runtime.test.js +16 -9
  126. package/server/lib/notifications/trigger-runtime.test.js +187 -0
  127. package/server/lib/openchamber-control/DOCUMENTATION.md +10 -0
  128. package/server/lib/openchamber-control/actions.js +3 -2
  129. package/server/lib/openchamber-control/error.js +1 -1
  130. package/server/lib/openchamber-control/file-open.js +59 -0
  131. package/server/lib/openchamber-control/file-open.test.js +57 -0
  132. package/server/lib/openchamber-control/routes.test.js +12 -0
  133. package/server/lib/openchamber-control/service.js +102 -49
  134. package/server/lib/openchamber-control/service.test.js +84 -44
  135. package/server/lib/openchamber-sessions/archive-store.js +224 -0
  136. package/server/lib/openchamber-sessions/archive-store.test.js +187 -0
  137. package/server/lib/openchamber-sessions/opencode-client.js +22 -0
  138. package/server/lib/openchamber-sessions/routes.js +398 -328
  139. package/server/lib/openchamber-sessions/routes.test.js +777 -740
  140. package/server/lib/openchamber-sessions/session-metadata-store.js +285 -0
  141. package/server/lib/openchamber-sessions/session-metadata-store.test.js +259 -0
  142. package/server/lib/opencode/DOCUMENTATION.md +449 -29
  143. package/server/lib/opencode/agents.js +233 -327
  144. package/server/lib/opencode/auth.js +41 -44
  145. package/server/lib/opencode/auth.test.js +92 -0
  146. package/server/lib/opencode/cli-upgrade.d.ts +4 -0
  147. package/server/lib/opencode/cli-upgrade.js +18 -0
  148. package/server/lib/opencode/cli-upgrade.test.js +36 -0
  149. package/server/lib/opencode/commands.js +164 -145
  150. package/server/lib/opencode/compatibility.d.ts +16 -0
  151. package/server/lib/opencode/compatibility.js +88 -0
  152. package/server/lib/opencode/compatibility.test.js +62 -0
  153. package/server/lib/opencode/config-entity-routes.js +58 -29
  154. package/server/lib/opencode/config-entity-v2.test.js +290 -0
  155. package/server/lib/opencode/config-mutation-response.js +17 -7
  156. package/server/lib/opencode/config-mutation-response.test.js +4 -7
  157. package/server/lib/opencode/config-paths.test.js +2 -2
  158. package/server/lib/opencode/config-v2.d.ts +183 -0
  159. package/server/lib/opencode/config-v2.js +801 -0
  160. package/server/lib/opencode/config-v2.test.js +466 -0
  161. package/server/lib/opencode/credential-db.js +144 -0
  162. package/server/lib/opencode/credential-db.test.js +104 -0
  163. package/server/lib/opencode/env-runtime.js +48 -9
  164. package/server/lib/opencode/env-runtime.test.js +45 -0
  165. package/server/lib/opencode/feature-routes-runtime.js +15 -5
  166. package/server/lib/opencode/lifecycle-process.test.js +7 -4
  167. package/server/lib/opencode/lifecycle.js +85 -30
  168. package/server/lib/opencode/lifecycle.test.js +80 -8
  169. package/server/lib/opencode/login-shell-env.js +27 -0
  170. package/server/lib/opencode/managed-config-file.js +119 -0
  171. package/server/lib/opencode/managed-config-file.test.js +152 -0
  172. package/server/lib/opencode/managed-plugin-config.js +33 -13
  173. package/server/lib/opencode/mcp.js +43 -149
  174. package/server/lib/opencode/network-runtime.js +6 -7
  175. package/server/lib/opencode/openchamber-routes.test.js +2 -5
  176. package/server/lib/opencode/plugin-routes.js +3 -3
  177. package/server/lib/opencode/plugin-routes.test.js +6 -24
  178. package/server/lib/opencode/plugins.js +91 -40
  179. package/server/lib/opencode/plugins.test.js +28 -15
  180. package/server/lib/opencode/providers.js +63 -83
  181. package/server/lib/opencode/providers.test.js +128 -59
  182. package/server/lib/opencode/proxy-agent-wiring.test.js +4 -2
  183. package/server/lib/opencode/proxy.js +179 -129
  184. package/server/lib/opencode/pwa-manifest-routes.js +4 -2
  185. package/server/lib/opencode/pwa-manifest-routes.test.js +3 -2
  186. package/server/lib/opencode/response-envelope.js +14 -0
  187. package/server/lib/opencode/response-envelope.test.js +23 -0
  188. package/server/lib/opencode/routes-upgrade.test.js +73 -116
  189. package/server/lib/opencode/routes.js +121 -428
  190. package/server/lib/opencode/server-utils-runtime.js +10 -4
  191. package/server/lib/opencode/session-activity.js +78 -0
  192. package/server/lib/opencode/session-runtime.js +21 -10
  193. package/server/lib/opencode/session-runtime.test.js +9 -9
  194. package/server/lib/opencode/settings-helpers.js +9 -9
  195. package/server/lib/opencode/settings-helpers.test.js +7 -12
  196. package/server/lib/opencode/settings-registry.json +6 -8
  197. package/server/lib/opencode/settings-runtime.js +18 -1
  198. package/server/lib/opencode/settings-runtime.test.js +31 -2
  199. package/server/lib/opencode/shared.js +54 -22
  200. package/server/lib/opencode/shared.test.js +8 -4
  201. package/server/lib/opencode/shutdown-runtime.js +54 -7
  202. package/server/lib/opencode/shutdown-runtime.test.js +224 -30
  203. package/server/lib/opencode/skill-routes.js +23 -24
  204. package/server/lib/opencode/skills.js +7 -5
  205. package/server/lib/opencode/tunnel-wiring-runtime.js +2 -1
  206. package/server/lib/opencode/upgrade-capability.test.js +1 -1
  207. package/server/lib/opencode/v1-migration-topup.js +288 -0
  208. package/server/lib/opencode/v1-migration-topup.test.js +266 -0
  209. package/server/lib/opencode/v2-install.d.ts +8 -0
  210. package/server/lib/opencode/v2-install.js +158 -0
  211. package/server/lib/opencode/v2-install.test.js +124 -0
  212. package/server/lib/opencode/watcher.js +10 -3
  213. package/server/lib/opencode/watcher.test.js +17 -21
  214. package/server/lib/opencode/websearch-config.js +66 -0
  215. package/server/lib/package-manager.js +55 -68
  216. package/server/lib/package-manager.test.js +241 -75
  217. package/server/lib/permission-auto-accept/runtime.js +38 -22
  218. package/server/lib/permission-auto-accept/runtime.test.js +39 -17
  219. package/server/lib/quota/DOCUMENTATION.md +4 -0
  220. package/server/lib/quota/providers/xai.js +4 -4
  221. package/server/lib/relay/tunnel-host.js +4 -1
  222. package/server/lib/relay/tunnel-host.test.js +7 -0
  223. package/server/lib/routing/DOCUMENTATION.md +52 -21
  224. package/server/lib/routing/defaults.js +23 -6
  225. package/server/lib/routing/jev.js +17 -7
  226. package/server/lib/routing/routes.http.test.js +68 -33
  227. package/server/lib/routing/routes.js +65 -22
  228. package/server/lib/routing/runtime.js +145 -48
  229. package/server/lib/routing/runtime.test.js +79 -55
  230. package/server/lib/scheduled-tasks/DOCUMENTATION.md +4 -0
  231. package/server/lib/scheduled-tasks/issue-2710-double-execution.test.js +51 -46
  232. package/server/lib/scheduled-tasks/runtime.js +81 -74
  233. package/server/lib/scheduled-tasks/runtime.test.js +53 -1
  234. package/server/lib/session-assist/DOCUMENTATION.md +8 -3
  235. package/server/lib/session-assist/context.js +122 -46
  236. package/server/lib/session-assist/context.test.js +117 -49
  237. package/server/lib/session-assist/runtime.js +52 -22
  238. package/server/lib/session-assist/runtime.test.js +145 -173
  239. package/server/lib/session-goal/DOCUMENTATION.md +23 -15
  240. package/server/lib/session-goal/create.js +9 -12
  241. package/server/lib/session-goal/create.test.js +27 -28
  242. package/server/lib/session-goal/runtime.js +164 -77
  243. package/server/lib/session-goal/runtime.test.js +271 -519
  244. package/server/lib/session-knowledge/DOCUMENTATION.md +5 -0
  245. package/server/lib/session-knowledge/runtime.js +59 -41
  246. package/server/lib/session-knowledge/runtime.test.js +90 -20
  247. package/server/lib/small-model/DOCUMENTATION.md +154 -208
  248. package/server/lib/small-model/client.js +113 -0
  249. package/server/lib/small-model/index.js +296 -158
  250. package/server/lib/small-model/index.test.js +423 -256
  251. package/server/lib/small-model/routes.js +1 -1
  252. package/server/lib/spaces/DOCUMENTATION.md +807 -0
  253. package/server/lib/spaces/code-in-bait.js +185 -0
  254. package/server/lib/spaces/code-in.js +641 -0
  255. package/server/lib/spaces/code-in.test.js +1048 -0
  256. package/server/lib/spaces/errors.js +8 -0
  257. package/server/lib/spaces/exec-http.js +94 -0
  258. package/server/lib/spaces/gatekeeper-channel.js +202 -0
  259. package/server/lib/spaces/gatekeeper-channel.test.js +215 -0
  260. package/server/lib/spaces/gatekeeper-program.cjs +914 -0
  261. package/server/lib/spaces/gatekeeper-program.test.js +1391 -0
  262. package/server/lib/spaces/hardening.js +457 -0
  263. package/server/lib/spaces/hardening.test.js +368 -0
  264. package/server/lib/spaces/host-git.js +127 -0
  265. package/server/lib/spaces/host-git.test.js +137 -0
  266. package/server/lib/spaces/labels.js +234 -0
  267. package/server/lib/spaces/labels.test.js +219 -0
  268. package/server/lib/spaces/layout.js +184 -0
  269. package/server/lib/spaces/layout.test.js +30 -0
  270. package/server/lib/spaces/manager.js +82 -0
  271. package/server/lib/spaces/manager.test.js +114 -0
  272. package/server/lib/spaces/places/code-in.docker.live.test.js +216 -0
  273. package/server/lib/spaces/places/contract-suite.js +156 -0
  274. package/server/lib/spaces/places/contract.docker.live.test.js +7 -0
  275. package/server/lib/spaces/places/contract.test.js +6 -0
  276. package/server/lib/spaces/places/docker-engine.js +126 -0
  277. package/server/lib/spaces/places/docker-live-support.js +202 -0
  278. package/server/lib/spaces/places/docker-tools.js +186 -0
  279. package/server/lib/spaces/places/docker.js +587 -0
  280. package/server/lib/spaces/places/docker.test.js +1610 -0
  281. package/server/lib/spaces/places/escape-suite.js +1018 -0
  282. package/server/lib/spaces/places/escape.docker.live.test.js +7 -0
  283. package/server/lib/spaces/places/fake-docker.js +375 -0
  284. package/server/lib/spaces/places/memory-place.js +103 -0
  285. package/server/lib/spaces/places/packed.docker.live.test.js +77 -0
  286. package/server/lib/spaces/places/registry.js +43 -0
  287. package/server/lib/spaces/places/registry.test.js +50 -0
  288. package/server/lib/spaces/places/server.docker.live.test.js +225 -0
  289. package/server/lib/spaces/run-command.js +261 -0
  290. package/server/lib/spaces/run-command.test.js +396 -0
  291. package/server/lib/spaces/space-server.js +190 -0
  292. package/server/lib/spaces/space-server.test.js +335 -0
  293. package/server/lib/spaces/tools-filler.js +82 -0
  294. package/server/lib/spaces/tools-filler.test.js +148 -0
  295. package/server/lib/spaces/tools-pack.js +49 -0
  296. package/server/lib/spaces/tools-pack.test.js +57 -0
  297. package/server/lib/spaces/tools.js +138 -0
  298. package/server/lib/spaces/tools.test.js +153 -0
  299. package/server/lib/tts/openai-sdk.js +11 -0
  300. package/server/lib/tts/service.js +7 -5
  301. package/server/lib/tts/stt.js +3 -2
  302. package/server/lib/tunnels/DOCUMENTATION.md +2 -0
  303. package/server/lib/tunnels/routes.js +7 -0
  304. package/server/lib/tunnels/routes.test.js +55 -0
  305. package/server/lib/ui-auth/ui-auth.js +38 -2
  306. package/server/lib/ui-auth/ui-auth.test.js +42 -0
  307. package/server/lib/ui-auth/ui-passkeys.js +12 -10
  308. package/server/lib/walkthrough/DOCUMENTATION.md +10 -1
  309. package/server/lib/walkthrough/pull-request.js +61 -8
  310. package/server/lib/walkthrough/pull-request.test.js +54 -1
  311. package/server/lib/walkthrough/routes.js +20 -0
  312. package/server/lib/walkthrough/routes.test.js +19 -0
  313. package/server/opencode-proxy.test.js +190 -166
  314. package/server/opencode-worktree-readiness.test.js +5 -4
  315. package/dist/assets/DiffView-COVQhWGd.js +0 -4
  316. package/dist/assets/FilesView-B1V5JxFX.js +0 -13
  317. package/dist/assets/LinearIssuesView-D7FKg1XJ.js +0 -1
  318. package/dist/assets/MarkdownImageGallery-BrFjAVEf.js +0 -1
  319. package/dist/assets/MarkdownRendererImpl-DWepTafh.js +0 -12
  320. package/dist/assets/OnboardingScreen-Dyxxiqdt.js +0 -1
  321. package/dist/assets/PlanView-LW2z_EAP.js +0 -5
  322. package/dist/assets/PluginPane-B4tKno2h.js +0 -3
  323. package/dist/assets/SettingsView-DEaMulN9.js +0 -29
  324. package/dist/assets/SettingsWindow-FLDJXOgQ.js +0 -1
  325. package/dist/assets/SubmoduleDiffSummary-CvVwD-Vi.js +0 -1
  326. package/dist/assets/ToolOutputDialog-BiP0x2Rw.js +0 -15
  327. package/dist/assets/ToolPartDiffPreview-CkR4msKP.js +0 -8
  328. package/dist/assets/appThemeRegistry-BuUKhbYQ.js +0 -1
  329. package/dist/assets/de-DgxgFyGG.js +0 -10
  330. package/dist/assets/es-BFsZj5F_.js +0 -16
  331. package/dist/assets/fr-jdZ5KKQi.js +0 -14
  332. package/dist/assets/index-CKHjPKbq.js +0 -1
  333. package/dist/assets/index-Cbci4i1W.js +0 -40
  334. package/dist/assets/index-DqaMWNrC.css +0 -1
  335. package/dist/assets/ja-C5kKrhO4.js +0 -16
  336. package/dist/assets/ko-DXDTT_0O.js +0 -16
  337. package/dist/assets/main-CZALtVek.js +0 -896
  338. package/dist/assets/main-CgXMBNvG.js +0 -2
  339. package/dist/assets/miniChat-CwTmDixi.js +0 -2
  340. package/dist/assets/mobile-CLf2vCtO.js +0 -2
  341. package/dist/assets/pl-D-7x4Y8Q.js +0 -16
  342. package/dist/assets/pt-BR-CSBZrHa8.js +0 -16
  343. package/dist/assets/renderElectronMiniChatApp-C5gAFBk0.js +0 -2
  344. package/dist/assets/renderMobileApp-V4hYd32H.js +0 -25
  345. package/dist/assets/runtimeEndpointReset-DhlHCn-2.js +0 -25
  346. package/dist/assets/scheduledTasksApi-DzjbLd8P.js +0 -1
  347. package/dist/assets/tr-Dr-oJ22L.js +0 -7
  348. package/dist/assets/uk-9Nx83UcI.js +0 -16
  349. package/dist/assets/useAppFontEffects-khZXpFL_.js +0 -7333
  350. package/dist/assets/useRootScrollLock-DdvHf9Pt.js +0 -2
  351. package/dist/assets/vendor-cron-parser-CUcP7OfX.js +0 -2
  352. package/dist/assets/vendor-opencode-sdk-BJ73u-bH.js +0 -7
  353. package/dist/assets/zh-CN-Bxy_Hj3r.js +0 -16
  354. package/dist/assets/zh-TW-0BB4gpHM.js +0 -16
  355. package/server/lib/opencode/mcp-oauth-callback.test.js +0 -111
  356. package/server/lib/routing/feature-flag.js +0 -11
  357. package/server/lib/small-model/call.js +0 -851
  358. package/server/lib/small-model/call.test.js +0 -1292
  359. package/server/lib/small-model/catalog.js +0 -13
  360. package/server/lib/small-model/resolve.js +0 -131
  361. package/server/lib/small-model/resolve.test.js +0 -197
  362. package/server/lib/small-model/runtime-providers.js +0 -164
  363. package/server/lib/small-model/runtime-providers.test.js +0 -118
  364. package/server/lib/system-prompt/DOCUMENTATION.md +0 -36
  365. package/server/lib/system-prompt/runtime.js +0 -49
  366. package/server/lib/system-prompt/runtime.test.js +0 -76
  367. package/server/lib/walkthrough/reproduce-2607.test.js +0 -148
@@ -1,851 +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
- // Providers whose endpoint lives inside their dedicated AI SDK package, so the
24
- // models.dev catalog carries no `api` URL and OpenCode reports none at runtime.
25
- // Each of these serves OpenAI-compatible `/chat/completions` at the URL below.
26
- const SDK_DEFAULT_BASE_URLS = new Map([
27
- ['groq', 'https://api.groq.com/openai/v1'],
28
- ['xai', 'https://api.x.ai/v1'],
29
- ['mistral', 'https://api.mistral.ai/v1'],
30
- ['cerebras', 'https://api.cerebras.ai/v1'],
31
- ['togetherai', 'https://api.together.xyz/v1'],
32
- ['deepinfra', 'https://api.deepinfra.com/v1/openai'],
33
- ['perplexity', 'https://api.perplexity.ai'],
34
- ['cohere', 'https://api.cohere.ai/compatibility/v1'],
35
- ]);
36
-
37
- // Where `thinking: { type: 'disabled' }` is a real switch rather than an
38
- // unknown field (mirrors the gates in OpenCode's provider/transform.ts).
39
- const ZAI_ENDPOINT_HOSTS = ['api.z.ai', 'bigmodel.cn'];
40
- const MINIMAX_THINKING_ADAPTERS = new Set(['@ai-sdk/openai-compatible', '@ai-sdk/anthropic']);
41
-
42
- const mergeHeadersCaseInsensitive = (base, overrides) => {
43
- const merged = { ...base };
44
- for (const [name, value] of Object.entries(overrides || {})) {
45
- const existingName = Object.keys(merged).find((key) => key.toLowerCase() === name.toLowerCase());
46
- if (existingName) {
47
- delete merged[existingName];
48
- }
49
- merged[name] = value;
50
- }
51
- return merged;
52
- };
53
-
54
- const CODEX_TOKEN_URL = 'https://auth.openai.com/oauth/token';
55
- const CODEX_CLIENT_ID = 'app_EMoamEEZ73f0CkXaXp7hrann';
56
- const CODEX_RESPONSES_URL = 'https://chatgpt.com/backend-api/codex/responses';
57
-
58
- const httpError = async (response, provider) => {
59
- const body = await response.text().catch(() => '');
60
- const snippet = body ? `: ${body.slice(0, 300)}` : '';
61
- // Callers need the status to tell "this provider rejected the request shape"
62
- // (retryable with a different shape) from "this provider is down".
63
- return Object.assign(new Error(`${provider} request failed with ${response.status}${snippet}`), {
64
- status: response.status,
65
- provider,
66
- });
67
- };
68
-
69
- // Callers own two independent reasons to stop: their own abort signal (user
70
- // navigated away, request cancelled) and a per-call deadline. Long-running
71
- // callers such as the diff walkthrough need a deadline well past the default.
72
- const requestSignal = (timeoutMs, signal) => {
73
- const deadline = AbortSignal.timeout(Number(timeoutMs) > 0 ? Number(timeoutMs) : REQUEST_TIMEOUT_MS);
74
- return signal ? AbortSignal.any([deadline, signal]) : deadline;
75
- };
76
-
77
- const STRUCTURED_OUTPUT_NAME = 'response';
78
-
79
- // Google's schema dialect is OpenAPI-flavored and rejects JSON Schema keywords
80
- // it does not know, so unsupported keys are dropped rather than passed through.
81
- const GOOGLE_UNSUPPORTED_SCHEMA_KEYS = new Set([
82
- '$schema',
83
- 'additionalProperties',
84
- 'definitions',
85
- '$defs',
86
- '$ref',
87
- 'strict',
88
- ]);
89
-
90
- const toGoogleSchema = (schema) => {
91
- if (Array.isArray(schema)) return schema.map(toGoogleSchema);
92
- if (!schema || typeof schema !== 'object') return schema;
93
- const result = {};
94
- for (const [key, value] of Object.entries(schema)) {
95
- if (GOOGLE_UNSUPPORTED_SCHEMA_KEYS.has(key)) continue;
96
- result[key] = toGoogleSchema(value);
97
- }
98
- return result;
99
- };
100
-
101
- // ---------------------------------------------------------------------------
102
- // OpenAI OAuth (ChatGPT plan / codex) token refresh — single-flight, with the
103
- // refreshed token written back to auth.json exactly like OpenCode does.
104
- // ---------------------------------------------------------------------------
105
-
106
- let openaiRefreshPromise = null;
107
-
108
- const decodeJwtClaims = (token) => {
109
- try {
110
- const payload = token.split('.')[1];
111
- return JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));
112
- } catch {
113
- return null;
114
- }
115
- };
116
-
117
- const extractChatgptAccountId = (accessToken) => {
118
- const claims = decodeJwtClaims(accessToken);
119
- const auth = claims?.['https://api.openai.com/auth'];
120
- const value = auth?.chatgpt_account_id;
121
- return typeof value === 'string' && value ? value : null;
122
- };
123
-
124
- const refreshOpenaiOauth = async (entry) => {
125
- if (!openaiRefreshPromise) {
126
- openaiRefreshPromise = (async () => {
127
- const response = await fetch(CODEX_TOKEN_URL, {
128
- method: 'POST',
129
- headers: { 'Content-Type': 'application/json' },
130
- body: JSON.stringify({
131
- grant_type: 'refresh_token',
132
- refresh_token: entry.refresh,
133
- client_id: CODEX_CLIENT_ID,
134
- }),
135
- signal: AbortSignal.timeout(30_000),
136
- });
137
- if (!response.ok) {
138
- throw await httpError(response, 'OpenAI token refresh');
139
- }
140
- const payload = await response.json();
141
- const access = typeof payload?.access_token === 'string' ? payload.access_token : '';
142
- if (!access) {
143
- throw new Error('OpenAI token refresh returned no access token');
144
- }
145
- const refreshed = {
146
- ...entry,
147
- type: 'oauth',
148
- access,
149
- refresh: typeof payload?.refresh_token === 'string' && payload.refresh_token
150
- ? payload.refresh_token
151
- : entry.refresh,
152
- expires: Date.now() + (Number(payload?.expires_in) > 0 ? Number(payload.expires_in) : 3600) * 1000,
153
- };
154
- const auth = readAuthFile();
155
- auth.openai = refreshed;
156
- writeAuthFile(auth);
157
- return refreshed;
158
- })().finally(() => {
159
- openaiRefreshPromise = null;
160
- });
161
- }
162
- return openaiRefreshPromise;
163
- };
164
-
165
- const ensureFreshOpenaiOauth = async (entry) => {
166
- if (entry.access && Number(entry.expires) > Date.now()) {
167
- return entry;
168
- }
169
- if (!entry.refresh) {
170
- throw new Error('OpenAI OAuth entry has no refresh token');
171
- }
172
- return refreshOpenaiOauth(entry);
173
- };
174
-
175
- // ---------------------------------------------------------------------------
176
- // Wire formats
177
- // ---------------------------------------------------------------------------
178
-
179
- const callOpenaiCompatible = async ({ baseURL, headers, modelID, prompt, system, maxOutputTokens, providerLabel, extraBody, responseSchema, timeoutMs, signal }) => {
180
- const trimmedBase = baseURL.replace(/\/+$/, '');
181
- console.log('[small-model:diagnostic] request', {
182
- provider: providerLabel,
183
- model: modelID,
184
- maxOutputTokens,
185
- thinkingDisabled: extraBody?.thinking?.type === 'disabled',
186
- promptChars: prompt.length,
187
- systemChars: system?.length ?? 0,
188
- inputChars: prompt.length + (system?.length ?? 0),
189
- });
190
- const response = await fetch(`${trimmedBase}/chat/completions`, {
191
- method: 'POST',
192
- headers: mergeHeadersCaseInsensitive({
193
- 'Content-Type': 'application/json',
194
- Accept: 'application/json',
195
- }, headers),
196
- body: JSON.stringify({
197
- model: modelID,
198
- messages: [
199
- ...(system ? [{ role: 'system', content: system }] : []),
200
- { role: 'user', content: prompt },
201
- ],
202
- max_tokens: maxOutputTokens,
203
- stream: false,
204
- ...(responseSchema
205
- ? {
206
- response_format: {
207
- type: 'json_schema',
208
- json_schema: { name: STRUCTURED_OUTPUT_NAME, strict: true, schema: responseSchema },
209
- },
210
- }
211
- : {}),
212
- ...(extraBody || {}),
213
- }),
214
- signal: requestSignal(timeoutMs, signal),
215
- });
216
- console.log('[small-model:diagnostic] response', {
217
- provider: providerLabel,
218
- model: modelID,
219
- httpStatus: response.status,
220
- ok: response.ok,
221
- });
222
- if (!response.ok) {
223
- throw await httpError(response, providerLabel);
224
- }
225
- const payload = await response.json();
226
- const message = payload?.choices?.[0]?.message;
227
- console.log('[small-model:diagnostic] completion', {
228
- provider: providerLabel,
229
- model: modelID,
230
- finishReason: payload?.choices?.[0]?.finish_reason ?? null,
231
- contentType: Array.isArray(message?.content) ? 'parts' : typeof message?.content,
232
- contentChars: typeof message?.content === 'string'
233
- ? message.content.length
234
- : Array.isArray(message?.content)
235
- ? message.content.reduce((total, part) => total + (typeof part?.text === 'string' ? part.text.length : 0), 0)
236
- : 0,
237
- reasoningChars: typeof message?.reasoning_content === 'string' ? message.reasoning_content.length : 0,
238
- });
239
-
240
- // Providers disagree on the content shape: plain string, an array of
241
- // typed parts, or (thinking models) an empty content with the budget spent
242
- // on reasoning_content.
243
- let text = '';
244
- if (typeof message?.content === 'string') {
245
- text = message.content;
246
- } else if (Array.isArray(message?.content)) {
247
- text = message.content
248
- .map((part) => (typeof part?.text === 'string' ? part.text : ''))
249
- .join('');
250
- }
251
- const finishReason = payload?.choices?.[0]?.finish_reason;
252
- if (!text.trim() && (finishReason === 'length' || (typeof message?.reasoning_content === 'string' && message.reasoning_content.trim()))) {
253
- // The model produced only reasoning, or was cut off before answering. This
254
- // is a budget problem, not a transport problem, and callers can act on it.
255
- throw Object.assign(
256
- new Error(
257
- `${providerLabel} spent the output budget on reasoning and returned no answer`
258
- + (finishReason ? ` (finish_reason: ${finishReason})` : ''),
259
- ),
260
- { code: 'output-exhausted', provider: providerLabel },
261
- );
262
- }
263
- if (!text.trim()) {
264
- throw new Error(`${providerLabel} returned no message content`);
265
- }
266
- return text;
267
- };
268
-
269
- const callOpenaiResponses = async ({ baseURL, headers, modelID, prompt, system, maxOutputTokens, providerLabel, responseSchema, timeoutMs, signal }) => {
270
- const trimmedBase = baseURL.replace(/\/+$/, '');
271
- const response = await fetch(`${trimmedBase}/responses`, {
272
- method: 'POST',
273
- headers: {
274
- 'Content-Type': 'application/json',
275
- Accept: 'application/json',
276
- ...headers,
277
- },
278
- body: JSON.stringify({
279
- model: modelID,
280
- ...(system ? { instructions: system } : {}),
281
- input: [{
282
- role: 'user',
283
- content: [{ type: 'input_text', text: prompt }],
284
- }],
285
- max_output_tokens: maxOutputTokens,
286
- ...(responseSchema
287
- ? {
288
- text: {
289
- format: {
290
- type: 'json_schema',
291
- name: STRUCTURED_OUTPUT_NAME,
292
- strict: true,
293
- schema: responseSchema,
294
- },
295
- },
296
- }
297
- : {}),
298
- stream: false,
299
- store: false,
300
- }),
301
- signal: requestSignal(timeoutMs, signal),
302
- });
303
- if (!response.ok) {
304
- throw await httpError(response, providerLabel);
305
- }
306
- const payload = await response.json();
307
- const text = typeof payload?.output_text === 'string'
308
- ? payload.output_text
309
- : Array.isArray(payload?.output)
310
- ? payload.output
311
- .flatMap((item) => (Array.isArray(item?.content) ? item.content : []))
312
- .map((part) => (part?.type === 'output_text' && typeof part.text === 'string' ? part.text : ''))
313
- .join('')
314
- : '';
315
- if (!text.trim()) {
316
- throw new Error(`${providerLabel} returned no text output`);
317
- }
318
- return text;
319
- };
320
-
321
- const callMessages = async ({ url, headers, modelID, prompt, system, maxOutputTokens, providerLabel, responseSchema, timeoutMs, signal }) => {
322
- const response = await fetch(url, {
323
- method: 'POST',
324
- headers: {
325
- 'Content-Type': 'application/json',
326
- Accept: 'application/json',
327
- ...headers,
328
- },
329
- body: JSON.stringify({
330
- model: modelID,
331
- max_tokens: maxOutputTokens,
332
- ...(system ? { system } : {}),
333
- messages: [{ role: 'user', content: prompt }],
334
- // The messages API has no response_format; a forced single-tool call is
335
- // the supported way to get schema-shaped output.
336
- ...(responseSchema
337
- ? {
338
- tools: [{
339
- name: STRUCTURED_OUTPUT_NAME,
340
- description: 'Return the answer in the required structure.',
341
- input_schema: responseSchema,
342
- }],
343
- tool_choice: { type: 'tool', name: STRUCTURED_OUTPUT_NAME },
344
- }
345
- : {}),
346
- }),
347
- signal: requestSignal(timeoutMs, signal),
348
- });
349
- if (!response.ok) {
350
- throw await httpError(response, providerLabel);
351
- }
352
- const payload = await response.json();
353
-
354
- if (responseSchema) {
355
- const toolUse = (payload?.content || []).find(
356
- (part) => part?.type === 'tool_use' && part.name === STRUCTURED_OUTPUT_NAME,
357
- );
358
- if (!toolUse || typeof toolUse.input !== 'object' || toolUse.input === null) {
359
- throw new Error(`${providerLabel} returned no structured output`);
360
- }
361
- return JSON.stringify(toolUse.input);
362
- }
363
-
364
- const text = (payload?.content || [])
365
- .filter((part) => part?.type === 'text' && typeof part.text === 'string')
366
- .map((part) => part.text)
367
- .join('');
368
- if (!text) {
369
- throw new Error(`${providerLabel} returned no text content`);
370
- }
371
- return text;
372
- };
373
-
374
- const callAnthropic = async ({ apiKey, baseURL, modelID, prompt, system, maxOutputTokens, responseSchema, timeoutMs, signal }) => callMessages({
375
- // Matches @ai-sdk/anthropic: baseURL is the full API prefix (commonly
376
- // already ending in /v1), so it gets /messages appended as-is rather than
377
- // having /v1/messages appended, which would double up a configured /v1.
378
- url: `${(baseURL || 'https://api.anthropic.com/v1').replace(/\/+$/, '')}/messages`,
379
- headers: {
380
- 'x-api-key': apiKey,
381
- 'anthropic-version': '2023-06-01',
382
- },
383
- modelID,
384
- prompt,
385
- system,
386
- maxOutputTokens,
387
- providerLabel: 'Anthropic',
388
- responseSchema,
389
- timeoutMs,
390
- signal,
391
- });
392
-
393
- const getCopilotEndpoint = async ({ baseURL, headers, modelID }) => {
394
- const trimmedBase = baseURL.replace(/\/+$/, '');
395
- const response = await fetch(`${trimmedBase}/models`, {
396
- headers: {
397
- Accept: 'application/json',
398
- ...headers,
399
- },
400
- signal: AbortSignal.timeout(COPILOT_MODELS_TIMEOUT_MS),
401
- });
402
- if (!response.ok) {
403
- throw await httpError(response, 'GitHub Copilot models');
404
- }
405
-
406
- let payload;
407
- try {
408
- payload = await response.json();
409
- } catch {
410
- throw new Error('GitHub Copilot models returned invalid JSON');
411
- }
412
- if (!Array.isArray(payload?.data)) {
413
- throw new Error('GitHub Copilot models returned an invalid model list');
414
- }
415
-
416
- const model = payload.data.find((item) => item && typeof item === 'object' && item.id === modelID);
417
- if (!model) {
418
- throw new Error(`GitHub Copilot model "${modelID}" was not returned by /models`);
419
- }
420
- if (model.supported_endpoints === undefined) {
421
- return 'chat';
422
- }
423
- if (!Array.isArray(model.supported_endpoints)) {
424
- throw new Error(`GitHub Copilot model "${modelID}" returned invalid endpoint metadata`);
425
- }
426
- if (model.supported_endpoints.includes('/v1/messages')) {
427
- return 'messages';
428
- }
429
- if (model.supported_endpoints.includes('/responses')) {
430
- return 'responses';
431
- }
432
- if (model.supported_endpoints.includes('/chat/completions')) {
433
- return 'chat';
434
- }
435
- throw new Error(`GitHub Copilot model "${modelID}" has no supported text endpoint`);
436
- };
437
-
438
- const callGoogle = async ({ apiKey, modelID, prompt, system, maxOutputTokens, responseSchema, timeoutMs, signal }) => {
439
- const url = `https://generativelanguage.googleapis.com/v1beta/models/${encodeURIComponent(modelID)}:generateContent`;
440
- const lowerModelID = modelID.toLowerCase();
441
- const thinkingConfig = lowerModelID.startsWith('gemini-3')
442
- ? { thinkingLevel: lowerModelID.includes('flash') ? 'minimal' : 'low' }
443
- : lowerModelID.startsWith('gemini-2') ? { thinkingBudget: 0 } : null;
444
- const response = await fetch(url, {
445
- method: 'POST',
446
- headers: {
447
- 'Content-Type': 'application/json',
448
- Accept: 'application/json',
449
- 'x-goog-api-key': apiKey,
450
- },
451
- body: JSON.stringify({
452
- contents: [{ role: 'user', parts: [{ text: prompt }] }],
453
- ...(system && { systemInstruction: { parts: [{ text: system }] } }),
454
- generationConfig: {
455
- maxOutputTokens,
456
- ...(thinkingConfig && { thinkingConfig }),
457
- ...(responseSchema && { responseMimeType: 'application/json', responseSchema: toGoogleSchema(responseSchema) }),
458
- },
459
- }),
460
- signal: requestSignal(timeoutMs, signal),
461
- });
462
- if (!response.ok) {
463
- throw await httpError(response, 'Google');
464
- }
465
- const payload = await response.json();
466
- const text = (payload?.candidates?.[0]?.content?.parts || [])
467
- .map((part) => (typeof part?.text === 'string' ? part.text : ''))
468
- .join('');
469
- if (!text) {
470
- throw new Error('Google returned no text content');
471
- }
472
- return text;
473
- };
474
-
475
- // ChatGPT-plan traffic goes to the codex backend, which only speaks the
476
- // streaming Responses API — collect the output_text deltas from the SSE body.
477
- const callCodexResponses = async ({ accessToken, accountId, modelID, prompt, system, timeoutMs, signal }) => {
478
- const response = await fetch(CODEX_RESPONSES_URL, {
479
- method: 'POST',
480
- headers: {
481
- 'Content-Type': 'application/json',
482
- Accept: 'text/event-stream',
483
- Authorization: `Bearer ${accessToken}`,
484
- ...(accountId ? { 'ChatGPT-Account-Id': accountId } : {}),
485
- originator: 'opencode',
486
- 'User-Agent': USER_AGENT,
487
- },
488
- body: JSON.stringify({
489
- model: modelID,
490
- ...(system ? { instructions: system } : {}),
491
- input: [
492
- {
493
- type: 'message',
494
- role: 'user',
495
- content: [{ type: 'input_text', text: prompt }],
496
- },
497
- ],
498
- // The codex backend rejects max_output_tokens (OpenCode forces it to
499
- // undefined for this provider too).
500
- stream: true,
501
- store: false,
502
- }),
503
- signal: requestSignal(timeoutMs, signal),
504
- });
505
- if (!response.ok) {
506
- throw await httpError(response, 'OpenAI (ChatGPT plan)');
507
- }
508
-
509
- const raw = await response.text();
510
- let text = '';
511
- let completedText = '';
512
- for (const line of raw.split('\n')) {
513
- if (!line.startsWith('data:')) continue;
514
- const data = line.slice(5).trim();
515
- if (!data || data === '[DONE]') continue;
516
- let event;
517
- try {
518
- event = JSON.parse(data);
519
- } catch {
520
- continue;
521
- }
522
- if (event?.type === 'response.output_text.delta' && typeof event.delta === 'string') {
523
- text += event.delta;
524
- }
525
- if (event?.type === 'response.output_text.done' && typeof event.text === 'string') {
526
- completedText = event.text;
527
- }
528
- if (event?.type === 'response.failed' || event?.type === 'error') {
529
- const message = event?.response?.error?.message || event?.message || 'response failed';
530
- throw new Error(`OpenAI (ChatGPT plan) stream error: ${message}`);
531
- }
532
- }
533
- const result = completedText || text;
534
- if (!result) {
535
- throw new Error('OpenAI (ChatGPT plan) returned no text output');
536
- }
537
- return result;
538
- };
539
-
540
- // ---------------------------------------------------------------------------
541
- // Custom provider configuration support
542
- // ---------------------------------------------------------------------------
543
-
544
- const resolveConfigValue = (value, workingDirectory, providerID, headerName = null) => {
545
- const envMatch = value.match(/^\{env:([^}]+)\}$/i);
546
- if (envMatch) {
547
- return process.env[envMatch[1].trim()]?.trim() || null;
548
- }
549
-
550
- const fileMatch = value.match(/^\{file:(.+)\}$/i);
551
- if (!fileMatch) return value;
552
-
553
- const configuredPath = fileMatch[1].trim();
554
- let resolvedPath;
555
- if (configuredPath === '~' || configuredPath.startsWith('~/') || configuredPath.startsWith('~\\')) {
556
- resolvedPath = path.join(os.homedir(), configuredPath.slice(2));
557
- } else if (path.isAbsolute(configuredPath)) {
558
- resolvedPath = configuredPath;
559
- } else {
560
- const layers = readConfigLayers(workingDirectory);
561
- const source = [
562
- { config: layers.customConfig, filePath: layers.paths.customPath },
563
- { config: layers.projectConfig, filePath: layers.paths.projectPath },
564
- { config: layers.userConfig, filePath: layers.paths.userPath },
565
- ].find(({ config }) => {
566
- const options = config?.provider?.[providerID]?.options;
567
- return headerName
568
- ? options?.headers?.[headerName] === value
569
- : options?.apiKey === value;
570
- });
571
- resolvedPath = path.resolve(source?.filePath ? path.dirname(source.filePath) : workingDirectory || process.cwd(), configuredPath);
572
- }
573
-
574
- try {
575
- const key = fs.readFileSync(resolvedPath, 'utf8').trim();
576
- if (!key) throw new Error('empty file');
577
- return key;
578
- } catch {
579
- throw new Error(`Failed to resolve configured ${headerName ? `header "${headerName}"` : 'apiKey'} file for provider "${providerID}"`);
580
- }
581
- };
582
-
583
- /**
584
- * `options.headers` from the provider config, with the same `{env:…}`/`{file:…}`
585
- * substitutions the API key gets.
586
- *
587
- * OpenCode sends these on every request, so dropping them here would have the
588
- * small model authenticating differently from the request path against the same
589
- * URL. Gateways fronted by an API-management layer reject a bearer-only request
590
- * outright, because the header is the credential rather than a supplement to it.
591
- */
592
- const readConfiguredHeaders = (providerCfg, workingDirectory, providerID) => {
593
- const configured = providerCfg?.options?.headers;
594
- if (!isPlainObject(configured)) return null;
595
- const headers = {};
596
- for (const [name, value] of Object.entries(configured)) {
597
- // Config headers are strings; a malformed entry is skipped rather than
598
- // stringified into a header the gateway would reject.
599
- if (String(value) !== value) continue;
600
- const resolved = resolveConfigValue(value.trim(), workingDirectory, providerID, name);
601
- if (resolved) headers[name] = resolved;
602
- }
603
- return Object.keys(headers).length ? headers : null;
604
- };
605
-
606
- const readProviderConfig = (workingDirectory, providerID) => {
607
- try {
608
- const config = readConfig(workingDirectory);
609
- const providerCfg = config?.provider?.[providerID];
610
- if (!providerCfg || typeof providerCfg !== 'object') return null;
611
- const baseURL = typeof providerCfg?.options?.baseURL === 'string' ? providerCfg.options.baseURL.trim() : null;
612
- const rawApiKey = typeof providerCfg?.options?.apiKey === 'string' ? providerCfg.options.apiKey.trim() : null;
613
- const apiKey = rawApiKey ? resolveConfigValue(rawApiKey, workingDirectory, providerID) : null;
614
- return {
615
- baseURL,
616
- headers: readConfiguredHeaders(providerCfg, workingDirectory, providerID),
617
- // Shape the config-supplied key as a regular api-key auth entry so it
618
- // can win the precedence check below and flow through the dispatch's
619
- // `entry.type === 'api' ? entry.key : ...` branch unchanged.
620
- auth: apiKey ? { type: 'api', key: apiKey } : null,
621
- };
622
- } catch {
623
- // Provider config is non-essential — continue with catalog-only resolution.
624
- return null;
625
- }
626
- }
627
-
628
- const getRuntimeModel = (runtimeProvider, modelID) => runtimeProvider?.models?.get(modelID) ?? null;
629
-
630
- // ---------------------------------------------------------------------------
631
- // Dispatch
632
- // ---------------------------------------------------------------------------
633
-
634
- /**
635
- * Providers reached through a dedicated wire format below: a token exchange,
636
- * an OAuth refresh, or a non-bearer header. OpenCode's runtime
637
- * `options.apiKey` is not the value those branches need — the ChatGPT-plan
638
- * `openai` login is the clearest case, where the runtime key is an OAuth
639
- * access token that api.openai.com answers with 401 — so the runtime
640
- * credential never stands in for them, and the runtime listing skips them
641
- * because the auth.json scan already covers them.
642
- */
643
- export const DEDICATED_WIRE_FORMAT_PROVIDERS = new Set(['github-copilot', 'copilot', 'openai', 'anthropic', 'google']);
644
-
645
- /**
646
- * The runtime credential shaped as an auth entry, or `null` when the provider
647
- * owns its credential handling or OpenCode reports nothing usable.
648
- */
649
- const runtimeCredential = (providerID, runtime) => (
650
- !DEDICATED_WIRE_FORMAT_PROVIDERS.has(providerID) && runtime?.apiKey
651
- ? { type: 'api', key: runtime.apiKey }
652
- : null
653
- );
654
-
655
- /**
656
- * Same credential resolution the request path uses: config
657
- * `provider.<id>.options.apiKey` wins, then the runtime credential OpenCode
658
- * resolved for a plugin provider, then the auth.json entry.
659
- * Callers that need to refuse before spending a request (walkthrough readiness)
660
- * must use this rather than inventing a second rule.
661
- */
662
- export async function resolveProviderLogin({ auth, workingDirectory, providerID }) {
663
- const providerConfig = readProviderConfig(workingDirectory, providerID);
664
- return providerConfig?.auth
665
- || runtimeCredential(providerID, await getRuntimeProvider(providerID))
666
- || getAuthEntryForProvider(auth, providerID)
667
- || null;
668
- }
669
-
670
- export async function callSmallModel({ auth, catalog, workingDirectory, sessionID, providerID, modelID, prompt, system, maxOutputTokens, responseSchema, timeoutMs, signal }) {
671
- const tokens = Number(maxOutputTokens) > 0 ? Number(maxOutputTokens) : DEFAULT_MAX_OUTPUT_TOKENS;
672
- const providerConfig = readProviderConfig(workingDirectory, providerID);
673
- const runtimeProvider = await getRuntimeProvider(providerID);
674
- const runtimeModel = getRuntimeModel(runtimeProvider, modelID);
675
- // Match OpenCode's resolveSDK precedence: config `provider.<id>.options`
676
- // wins, then what OpenCode itself resolved at runtime (the only place a
677
- // plugin's credential exists), and the auth.json entry last.
678
- const entry = providerConfig?.auth
679
- || runtimeCredential(providerID, runtimeProvider)
680
- || getAuthEntryForProvider(auth, providerID);
681
- if (!entry) {
682
- // Structured so the walkthrough (and any other caller) can show a blocker
683
- // instead of a raw 500 banner with this developer-oriented sentence.
684
- throw Object.assign(new Error(`No OpenCode login found for provider "${providerID}"`), {
685
- statusCode: 401,
686
- code: 'no-provider-login',
687
- providerID,
688
- });
689
- }
690
-
691
- if (providerID === 'github-copilot') {
692
- // OpenCode uses the stored device-OAuth token directly as the bearer —
693
- // access === refresh, no exchange, no expiry.
694
- const token = entry.refresh || entry.access || entry.key;
695
- if (!token) {
696
- throw new Error('GitHub Copilot login has no token');
697
- }
698
- const baseURL = entry.enterpriseUrl
699
- ? `https://copilot-api.${String(entry.enterpriseUrl).replace(/^https?:\/\//, '').replace(/\/+$/, '')}`
700
- : 'https://api.githubcopilot.com';
701
- const authHeaders = {
702
- Authorization: `Bearer ${token}`,
703
- 'User-Agent': USER_AGENT,
704
- 'X-GitHub-Api-Version': '2026-06-01',
705
- };
706
- const headers = {
707
- ...authHeaders,
708
- 'Openai-Intent': 'conversation-edits',
709
- 'x-initiator': 'agent',
710
- };
711
- const endpoint = await getCopilotEndpoint({
712
- baseURL,
713
- headers: authHeaders,
714
- modelID,
715
- });
716
- const request = {
717
- baseURL,
718
- headers,
719
- modelID,
720
- prompt,
721
- system,
722
- maxOutputTokens: tokens,
723
- providerLabel: 'GitHub Copilot',
724
- responseSchema,
725
- timeoutMs,
726
- signal,
727
- };
728
- if (endpoint === 'messages') {
729
- return callMessages({
730
- ...request,
731
- url: `${baseURL.replace(/\/+$/, '')}/v1/messages`,
732
- headers: {
733
- ...headers,
734
- 'anthropic-version': '2023-06-01',
735
- },
736
- });
737
- }
738
- if (endpoint === 'responses') {
739
- return callOpenaiResponses(request);
740
- }
741
- return callOpenaiCompatible(request);
742
- }
743
-
744
- if (providerID === 'openai' && entry.type === 'oauth') {
745
- // The codex backend speaks only the streaming Responses API and rejects
746
- // the structured-output fields, so a schema request fails loudly here
747
- // instead of silently returning free-form prose.
748
- if (responseSchema) {
749
- throw Object.assign(
750
- new Error('The ChatGPT-plan OpenAI login does not support structured output — choose another small model'),
751
- { code: 'structured-output-unsupported' },
752
- );
753
- }
754
- const fresh = await ensureFreshOpenaiOauth(entry);
755
- return callCodexResponses({
756
- accessToken: fresh.access,
757
- accountId: fresh.accountId || extractChatgptAccountId(fresh.access),
758
- modelID,
759
- prompt,
760
- system,
761
- timeoutMs,
762
- signal,
763
- });
764
- }
765
-
766
- const apiKey = entry.type === 'api' ? entry.key
767
- : entry.type === 'wellknown' ? entry.token
768
- : entry.access;
769
- if (!apiKey) {
770
- throw new Error(`OpenCode login for "${providerID}" has no usable credential`);
771
- }
772
-
773
- if (providerID === 'anthropic') {
774
- return callAnthropic({ apiKey, baseURL: providerConfig?.baseURL, modelID, prompt, system, maxOutputTokens: tokens, responseSchema, timeoutMs, signal });
775
- }
776
- if (providerID === 'google') {
777
- return callGoogle({ apiKey, modelID, prompt, system, maxOutputTokens: tokens, responseSchema, timeoutMs, signal });
778
- }
779
-
780
- // Everything else: OpenAI-compatible chat completions against the catalog's
781
- // base URL for that provider (openai itself included). When a custom provider
782
- // is not in the catalog (e.g. a user-configured OpenAI-compatible proxy),
783
- // fall back to its baseURL from the OpenCode provider config, then to the
784
- // selected model's endpoint OpenCode resolved at runtime, then to the
785
- // provider-level runtime endpoint. For a plugin provider, the runtime listing
786
- // is the only place those endpoints exist, and several are local proxies the
787
- // plugin itself runs. Last comes SDK_DEFAULT_BASE_URLS, for providers whose
788
- // endpoint only their SDK package knows. The openai provider also respects
789
- // provider.openai.options.baseURL — OpenCode itself uses the same config for
790
- // all providers including openai.
791
- const provider = getCatalogProvider(catalog, providerID);
792
- const providerConfigUrl = providerConfig?.baseURL;
793
- const defaultOpenaiUrl = 'https://api.openai.com/v1';
794
- const baseURL = typeof providerConfigUrl === 'string' && providerConfigUrl
795
- ? providerConfigUrl
796
- : providerID === 'openai'
797
- ? defaultOpenaiUrl
798
- : runtimeModel?.api?.url
799
- ?? runtimeProvider?.baseURL
800
- ?? (typeof provider?.api === 'string' && provider.api
801
- ? provider.api
802
- : SDK_DEFAULT_BASE_URLS.get(providerID) ?? null);
803
- if (!baseURL) {
804
- throw new Error(`Provider "${providerID}" has no known API base URL`);
805
- }
806
-
807
- // Thinking models burn the output budget on reasoning and leave content
808
- // empty — disable thinking where a wire-format switch exists (mirrors
809
- // OpenCode's smallOptions/variants special cases). There is NO universal
810
- // parameter: unknown body fields 400 on some providers, so this stays an
811
- // explicit allowlist. Models without a switch (DeepSeek, Qwen, Kimi, …)
812
- // just get the generous output budget.
813
- // GLM's switch belongs to the Z.ai/Zhipu endpoints, not to the model: the
814
- // same GLM served by another provider (OpenCode Go) rejects the field. The
815
- // host check keeps the switch for a custom-named provider pointed at them.
816
- const servedByZai = providerID.includes('zai')
817
- || providerID.includes('zhipu')
818
- || ZAI_ENDPOINT_HOSTS.some((host) => baseURL.includes(host));
819
- // MiniMax M3's switch is understood only behind the adapters OpenCode sends
820
- // it through. An adapter nobody reports (a custom provider) is OpenAI-
821
- // compatible by OpenCode's own default.
822
- const adapter = runtimeModel?.api?.npm
823
- ?? provider?.models?.[modelID]?.provider?.npm
824
- ?? provider?.npm
825
- ?? null;
826
- const minimaxSwitch = modelID.toLowerCase().includes('minimax-m3')
827
- && (adapter === null || MINIMAX_THINKING_ADAPTERS.has(adapter));
828
- const supportsThinkingToggle = servedByZai || minimaxSwitch;
829
- const extraBody = supportsThinkingToggle ? { thinking: { type: 'disabled' } } : undefined;
830
-
831
- return callOpenaiCompatible({
832
- baseURL,
833
- // Configured headers last: a gateway that authenticates on its own header
834
- // must be able to override the bearer default rather than sit beside it.
835
- headers: mergeHeadersCaseInsensitive(
836
- mergeHeadersCaseInsensitive({ Authorization: `Bearer ${apiKey}` }, providerConfig?.headers),
837
- providerID.startsWith('opencode')
838
- ? { 'x-opencode-session': typeof sessionID === 'string' && sessionID.trim() ? sessionID.trim() : randomUUID() }
839
- : null,
840
- ),
841
- modelID,
842
- prompt,
843
- system,
844
- maxOutputTokens: tokens,
845
- providerLabel: provider?.name || providerID,
846
- extraBody,
847
- responseSchema,
848
- timeoutMs,
849
- signal,
850
- });
851
- }