alchemylab-opencode 1.0.7 → 1.0.8

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 (358) hide show
  1. package/package.json +2 -15
  2. package/build.mjs +0 -192
  3. package/packages/opencode/package.json +0 -138
  4. package/packages/opencode/src/account/account.sql.ts +0 -39
  5. package/packages/opencode/src/account/index.ts +0 -463
  6. package/packages/opencode/src/account/repo.ts +0 -163
  7. package/packages/opencode/src/account/schema.ts +0 -91
  8. package/packages/opencode/src/acp/README.md +0 -174
  9. package/packages/opencode/src/acp/agent.ts +0 -1847
  10. package/packages/opencode/src/acp/session.ts +0 -116
  11. package/packages/opencode/src/acp/types.ts +0 -24
  12. package/packages/opencode/src/agent/agent.ts +0 -420
  13. package/packages/opencode/src/agent/generate.txt +0 -75
  14. package/packages/opencode/src/agent/prompt/compaction.txt +0 -15
  15. package/packages/opencode/src/agent/prompt/explore.txt +0 -18
  16. package/packages/opencode/src/agent/prompt/summary.txt +0 -11
  17. package/packages/opencode/src/agent/prompt/title.txt +0 -44
  18. package/packages/opencode/src/auth/index.ts +0 -110
  19. package/packages/opencode/src/bus/bus-event.ts +0 -40
  20. package/packages/opencode/src/bus/global.ts +0 -10
  21. package/packages/opencode/src/bus/index.ts +0 -185
  22. package/packages/opencode/src/cli/bootstrap.ts +0 -17
  23. package/packages/opencode/src/cli/cmd/cmd.ts +0 -7
  24. package/packages/opencode/src/cli/cmd/run.ts +0 -689
  25. package/packages/opencode/src/cli/cmd/serve.ts +0 -24
  26. package/packages/opencode/src/cli/cmd/tui/event.ts +0 -49
  27. package/packages/opencode/src/cli/effect/prompt.ts +0 -25
  28. package/packages/opencode/src/cli/error.ts +0 -46
  29. package/packages/opencode/src/cli/heap.ts +0 -59
  30. package/packages/opencode/src/cli/logo.ts +0 -6
  31. package/packages/opencode/src/cli/network.ts +0 -60
  32. package/packages/opencode/src/cli/ui.ts +0 -133
  33. package/packages/opencode/src/cli/upgrade.ts +0 -31
  34. package/packages/opencode/src/command/index.ts +0 -195
  35. package/packages/opencode/src/command/template/initialize.txt +0 -66
  36. package/packages/opencode/src/command/template/review.txt +0 -101
  37. package/packages/opencode/src/config/config.ts +0 -1599
  38. package/packages/opencode/src/config/console-state.ts +0 -15
  39. package/packages/opencode/src/config/markdown.ts +0 -99
  40. package/packages/opencode/src/config/paths.ts +0 -167
  41. package/packages/opencode/src/config/tui-migrate.ts +0 -155
  42. package/packages/opencode/src/config/tui-schema.ts +0 -37
  43. package/packages/opencode/src/config/tui.ts +0 -179
  44. package/packages/opencode/src/control-plane/adaptors/index.ts +0 -20
  45. package/packages/opencode/src/control-plane/adaptors/worktree.ts +0 -42
  46. package/packages/opencode/src/control-plane/schema.ts +0 -17
  47. package/packages/opencode/src/control-plane/sse.ts +0 -66
  48. package/packages/opencode/src/control-plane/types.ts +0 -32
  49. package/packages/opencode/src/control-plane/workspace.sql.ts +0 -17
  50. package/packages/opencode/src/control-plane/workspace.ts +0 -168
  51. package/packages/opencode/src/effect/cross-spawn-spawner.ts +0 -502
  52. package/packages/opencode/src/effect/instance-ref.ts +0 -6
  53. package/packages/opencode/src/effect/instance-registry.ts +0 -12
  54. package/packages/opencode/src/effect/instance-state.ts +0 -82
  55. package/packages/opencode/src/effect/run-service.ts +0 -33
  56. package/packages/opencode/src/effect/runner.ts +0 -216
  57. package/packages/opencode/src/env/index.ts +0 -28
  58. package/packages/opencode/src/file/ignore.ts +0 -82
  59. package/packages/opencode/src/file/index.ts +0 -686
  60. package/packages/opencode/src/file/protected.ts +0 -59
  61. package/packages/opencode/src/file/ripgrep.ts +0 -376
  62. package/packages/opencode/src/file/time.ts +0 -133
  63. package/packages/opencode/src/file/watcher.ts +0 -173
  64. package/packages/opencode/src/filesystem/index.ts +0 -236
  65. package/packages/opencode/src/flag/flag.ts +0 -156
  66. package/packages/opencode/src/format/formatter.ts +0 -413
  67. package/packages/opencode/src/format/index.ts +0 -203
  68. package/packages/opencode/src/git/index.ts +0 -303
  69. package/packages/opencode/src/global/index.ts +0 -56
  70. package/packages/opencode/src/id/id.ts +0 -85
  71. package/packages/opencode/src/ide/index.ts +0 -74
  72. package/packages/opencode/src/installation/index.ts +0 -355
  73. package/packages/opencode/src/installation/meta.ts +0 -7
  74. package/packages/opencode/src/lsp/client.ts +0 -252
  75. package/packages/opencode/src/lsp/index.ts +0 -558
  76. package/packages/opencode/src/lsp/language.ts +0 -120
  77. package/packages/opencode/src/lsp/launch.ts +0 -21
  78. package/packages/opencode/src/lsp/server.ts +0 -1968
  79. package/packages/opencode/src/mcp/auth.ts +0 -173
  80. package/packages/opencode/src/mcp/index.ts +0 -931
  81. package/packages/opencode/src/mcp/oauth-callback.ts +0 -216
  82. package/packages/opencode/src/mcp/oauth-provider.ts +0 -185
  83. package/packages/opencode/src/node-loader.mjs +0 -104
  84. package/packages/opencode/src/node-preload.mjs +0 -39
  85. package/packages/opencode/src/node.ts +0 -1
  86. package/packages/opencode/src/npm/index.ts +0 -188
  87. package/packages/opencode/src/patch/index.ts +0 -680
  88. package/packages/opencode/src/permission/arity.ts +0 -163
  89. package/packages/opencode/src/permission/evaluate.ts +0 -15
  90. package/packages/opencode/src/permission/index.ts +0 -325
  91. package/packages/opencode/src/permission/schema.ts +0 -17
  92. package/packages/opencode/src/plugin/cloudflare.ts +0 -67
  93. package/packages/opencode/src/plugin/codex.ts +0 -608
  94. package/packages/opencode/src/plugin/github-copilot/copilot.ts +0 -361
  95. package/packages/opencode/src/plugin/github-copilot/models.ts +0 -144
  96. package/packages/opencode/src/plugin/index.ts +0 -299
  97. package/packages/opencode/src/plugin/install.ts +0 -439
  98. package/packages/opencode/src/plugin/loader.ts +0 -174
  99. package/packages/opencode/src/plugin/meta.ts +0 -188
  100. package/packages/opencode/src/plugin/shared.ts +0 -323
  101. package/packages/opencode/src/project/bootstrap.ts +0 -31
  102. package/packages/opencode/src/project/instance.ts +0 -175
  103. package/packages/opencode/src/project/project.sql.ts +0 -16
  104. package/packages/opencode/src/project/project.ts +0 -519
  105. package/packages/opencode/src/project/schema.ts +0 -16
  106. package/packages/opencode/src/project/state.ts +0 -70
  107. package/packages/opencode/src/project/vcs.ts +0 -240
  108. package/packages/opencode/src/provider/auth.ts +0 -253
  109. package/packages/opencode/src/provider/error.ts +0 -197
  110. package/packages/opencode/src/provider/models.ts +0 -162
  111. package/packages/opencode/src/provider/provider.ts +0 -1709
  112. package/packages/opencode/src/provider/schema.ts +0 -38
  113. package/packages/opencode/src/provider/sdk/copilot/README.md +0 -5
  114. package/packages/opencode/src/provider/sdk/copilot/chat/convert-to-openai-compatible-chat-messages.ts +0 -170
  115. package/packages/opencode/src/provider/sdk/copilot/chat/get-response-metadata.ts +0 -15
  116. package/packages/opencode/src/provider/sdk/copilot/chat/map-openai-compatible-finish-reason.ts +0 -19
  117. package/packages/opencode/src/provider/sdk/copilot/chat/openai-compatible-api-types.ts +0 -64
  118. package/packages/opencode/src/provider/sdk/copilot/chat/openai-compatible-chat-language-model.ts +0 -815
  119. package/packages/opencode/src/provider/sdk/copilot/chat/openai-compatible-chat-options.ts +0 -28
  120. package/packages/opencode/src/provider/sdk/copilot/chat/openai-compatible-metadata-extractor.ts +0 -44
  121. package/packages/opencode/src/provider/sdk/copilot/chat/openai-compatible-prepare-tools.ts +0 -83
  122. package/packages/opencode/src/provider/sdk/copilot/copilot-provider.ts +0 -100
  123. package/packages/opencode/src/provider/sdk/copilot/index.ts +0 -2
  124. package/packages/opencode/src/provider/sdk/copilot/openai-compatible-error.ts +0 -27
  125. package/packages/opencode/src/provider/sdk/copilot/responses/convert-to-openai-responses-input.ts +0 -335
  126. package/packages/opencode/src/provider/sdk/copilot/responses/map-openai-responses-finish-reason.ts +0 -22
  127. package/packages/opencode/src/provider/sdk/copilot/responses/openai-config.ts +0 -18
  128. package/packages/opencode/src/provider/sdk/copilot/responses/openai-error.ts +0 -22
  129. package/packages/opencode/src/provider/sdk/copilot/responses/openai-responses-api-types.ts +0 -214
  130. package/packages/opencode/src/provider/sdk/copilot/responses/openai-responses-language-model.ts +0 -1769
  131. package/packages/opencode/src/provider/sdk/copilot/responses/openai-responses-prepare-tools.ts +0 -173
  132. package/packages/opencode/src/provider/sdk/copilot/responses/openai-responses-settings.ts +0 -1
  133. package/packages/opencode/src/provider/sdk/copilot/responses/tool/code-interpreter.ts +0 -87
  134. package/packages/opencode/src/provider/sdk/copilot/responses/tool/file-search.ts +0 -127
  135. package/packages/opencode/src/provider/sdk/copilot/responses/tool/image-generation.ts +0 -114
  136. package/packages/opencode/src/provider/sdk/copilot/responses/tool/local-shell.ts +0 -64
  137. package/packages/opencode/src/provider/sdk/copilot/responses/tool/web-search-preview.ts +0 -103
  138. package/packages/opencode/src/provider/sdk/copilot/responses/tool/web-search.ts +0 -102
  139. package/packages/opencode/src/provider/transform.ts +0 -1050
  140. package/packages/opencode/src/pty/index.ts +0 -397
  141. package/packages/opencode/src/pty/pty.node.ts +0 -27
  142. package/packages/opencode/src/pty/pty.ts +0 -25
  143. package/packages/opencode/src/pty/schema.ts +0 -17
  144. package/packages/opencode/src/question/index.ts +0 -224
  145. package/packages/opencode/src/question/schema.ts +0 -17
  146. package/packages/opencode/src/run.ts +0 -28
  147. package/packages/opencode/src/serve.ts +0 -45
  148. package/packages/opencode/src/server/error.ts +0 -36
  149. package/packages/opencode/src/server/event.ts +0 -7
  150. package/packages/opencode/src/server/instance.ts +0 -324
  151. package/packages/opencode/src/server/mdns.ts +0 -60
  152. package/packages/opencode/src/server/middleware.ts +0 -33
  153. package/packages/opencode/src/server/projectors.ts +0 -28
  154. package/packages/opencode/src/server/proxy.ts +0 -131
  155. package/packages/opencode/src/server/router.ts +0 -105
  156. package/packages/opencode/src/server/routes/config.ts +0 -92
  157. package/packages/opencode/src/server/routes/event.ts +0 -83
  158. package/packages/opencode/src/server/routes/experimental.ts +0 -374
  159. package/packages/opencode/src/server/routes/file.ts +0 -197
  160. package/packages/opencode/src/server/routes/global.ts +0 -312
  161. package/packages/opencode/src/server/routes/mcp.ts +0 -225
  162. package/packages/opencode/src/server/routes/permission.ts +0 -69
  163. package/packages/opencode/src/server/routes/project.ts +0 -118
  164. package/packages/opencode/src/server/routes/provider.ts +0 -171
  165. package/packages/opencode/src/server/routes/pty.ts +0 -210
  166. package/packages/opencode/src/server/routes/question.ts +0 -99
  167. package/packages/opencode/src/server/routes/session.ts +0 -1030
  168. package/packages/opencode/src/server/routes/tui.ts +0 -379
  169. package/packages/opencode/src/server/routes/workspace.ts +0 -94
  170. package/packages/opencode/src/server/server.ts +0 -353
  171. package/packages/opencode/src/session/compaction.ts +0 -428
  172. package/packages/opencode/src/session/index.ts +0 -887
  173. package/packages/opencode/src/session/instruction.ts +0 -258
  174. package/packages/opencode/src/session/llm.ts +0 -354
  175. package/packages/opencode/src/session/message-v2.ts +0 -1031
  176. package/packages/opencode/src/session/message.ts +0 -191
  177. package/packages/opencode/src/session/overflow.ts +0 -22
  178. package/packages/opencode/src/session/processor.ts +0 -523
  179. package/packages/opencode/src/session/projectors.ts +0 -135
  180. package/packages/opencode/src/session/prompt/anthropic.txt +0 -105
  181. package/packages/opencode/src/session/prompt/beast.txt +0 -147
  182. package/packages/opencode/src/session/prompt/build-switch.txt +0 -5
  183. package/packages/opencode/src/session/prompt/codex.txt +0 -79
  184. package/packages/opencode/src/session/prompt/copilot-gpt-5.txt +0 -143
  185. package/packages/opencode/src/session/prompt/default.txt +0 -105
  186. package/packages/opencode/src/session/prompt/gemini.txt +0 -155
  187. package/packages/opencode/src/session/prompt/gpt.txt +0 -107
  188. package/packages/opencode/src/session/prompt/kimi.txt +0 -95
  189. package/packages/opencode/src/session/prompt/max-steps.txt +0 -16
  190. package/packages/opencode/src/session/prompt/plan-reminder-anthropic.txt +0 -67
  191. package/packages/opencode/src/session/prompt/plan.txt +0 -26
  192. package/packages/opencode/src/session/prompt/trinity.txt +0 -97
  193. package/packages/opencode/src/session/prompt.ts +0 -1911
  194. package/packages/opencode/src/session/retry.ts +0 -106
  195. package/packages/opencode/src/session/revert.ts +0 -176
  196. package/packages/opencode/src/session/schema.ts +0 -38
  197. package/packages/opencode/src/session/session.sql.ts +0 -103
  198. package/packages/opencode/src/session/status.ts +0 -102
  199. package/packages/opencode/src/session/summary.ts +0 -177
  200. package/packages/opencode/src/session/system.ts +0 -76
  201. package/packages/opencode/src/session/todo.ts +0 -95
  202. package/packages/opencode/src/share/share-next.ts +0 -369
  203. package/packages/opencode/src/share/share.sql.ts +0 -13
  204. package/packages/opencode/src/shell/shell.ts +0 -110
  205. package/packages/opencode/src/skill/discovery.ts +0 -116
  206. package/packages/opencode/src/skill/index.ts +0 -277
  207. package/packages/opencode/src/snapshot/index.ts +0 -726
  208. package/packages/opencode/src/sql.d.ts +0 -4
  209. package/packages/opencode/src/storage/db.node.ts +0 -8
  210. package/packages/opencode/src/storage/db.ts +0 -177
  211. package/packages/opencode/src/storage/json-migration.ts +0 -425
  212. package/packages/opencode/src/storage/schema.sql.ts +0 -10
  213. package/packages/opencode/src/storage/schema.ts +0 -5
  214. package/packages/opencode/src/storage/storage.ts +0 -353
  215. package/packages/opencode/src/sync/README.md +0 -179
  216. package/packages/opencode/src/sync/event.sql.ts +0 -16
  217. package/packages/opencode/src/sync/index.ts +0 -263
  218. package/packages/opencode/src/sync/schema.ts +0 -14
  219. package/packages/opencode/src/tool/apply_patch.ts +0 -281
  220. package/packages/opencode/src/tool/apply_patch.txt +0 -33
  221. package/packages/opencode/src/tool/bash.ts +0 -496
  222. package/packages/opencode/src/tool/bash.txt +0 -117
  223. package/packages/opencode/src/tool/batch.ts +0 -183
  224. package/packages/opencode/src/tool/batch.txt +0 -24
  225. package/packages/opencode/src/tool/codesearch.ts +0 -132
  226. package/packages/opencode/src/tool/codesearch.txt +0 -12
  227. package/packages/opencode/src/tool/edit.ts +0 -667
  228. package/packages/opencode/src/tool/edit.txt +0 -10
  229. package/packages/opencode/src/tool/external-directory.ts +0 -46
  230. package/packages/opencode/src/tool/glob.ts +0 -78
  231. package/packages/opencode/src/tool/glob.txt +0 -6
  232. package/packages/opencode/src/tool/grep.ts +0 -156
  233. package/packages/opencode/src/tool/grep.txt +0 -8
  234. package/packages/opencode/src/tool/invalid.ts +0 -17
  235. package/packages/opencode/src/tool/ls.ts +0 -121
  236. package/packages/opencode/src/tool/ls.txt +0 -1
  237. package/packages/opencode/src/tool/lsp.ts +0 -97
  238. package/packages/opencode/src/tool/lsp.txt +0 -19
  239. package/packages/opencode/src/tool/multiedit.ts +0 -46
  240. package/packages/opencode/src/tool/multiedit.txt +0 -41
  241. package/packages/opencode/src/tool/plan-enter.txt +0 -14
  242. package/packages/opencode/src/tool/plan-exit.txt +0 -13
  243. package/packages/opencode/src/tool/plan.ts +0 -131
  244. package/packages/opencode/src/tool/question.ts +0 -46
  245. package/packages/opencode/src/tool/question.txt +0 -10
  246. package/packages/opencode/src/tool/read.ts +0 -332
  247. package/packages/opencode/src/tool/read.txt +0 -14
  248. package/packages/opencode/src/tool/registry.ts +0 -265
  249. package/packages/opencode/src/tool/schema.ts +0 -17
  250. package/packages/opencode/src/tool/skill.ts +0 -105
  251. package/packages/opencode/src/tool/task.ts +0 -166
  252. package/packages/opencode/src/tool/task.txt +0 -60
  253. package/packages/opencode/src/tool/todo.ts +0 -48
  254. package/packages/opencode/src/tool/todowrite.txt +0 -167
  255. package/packages/opencode/src/tool/tool.ts +0 -112
  256. package/packages/opencode/src/tool/truncate.ts +0 -144
  257. package/packages/opencode/src/tool/truncation-dir.ts +0 -4
  258. package/packages/opencode/src/tool/webfetch.ts +0 -206
  259. package/packages/opencode/src/tool/webfetch.txt +0 -13
  260. package/packages/opencode/src/tool/websearch.ts +0 -150
  261. package/packages/opencode/src/tool/websearch.txt +0 -14
  262. package/packages/opencode/src/tool/write.ts +0 -84
  263. package/packages/opencode/src/tool/write.txt +0 -8
  264. package/packages/opencode/src/util/abort.ts +0 -35
  265. package/packages/opencode/src/util/archive.ts +0 -17
  266. package/packages/opencode/src/util/color.ts +0 -19
  267. package/packages/opencode/src/util/context.ts +0 -25
  268. package/packages/opencode/src/util/data-url.ts +0 -9
  269. package/packages/opencode/src/util/defer.ts +0 -12
  270. package/packages/opencode/src/util/effect-http-client.ts +0 -11
  271. package/packages/opencode/src/util/effect-zod.ts +0 -98
  272. package/packages/opencode/src/util/error.ts +0 -77
  273. package/packages/opencode/src/util/filesystem.ts +0 -245
  274. package/packages/opencode/src/util/flock.ts +0 -333
  275. package/packages/opencode/src/util/fn.ts +0 -21
  276. package/packages/opencode/src/util/format.ts +0 -20
  277. package/packages/opencode/src/util/glob.ts +0 -34
  278. package/packages/opencode/src/util/hash.ts +0 -7
  279. package/packages/opencode/src/util/iife.ts +0 -3
  280. package/packages/opencode/src/util/keybind.ts +0 -103
  281. package/packages/opencode/src/util/lazy.ts +0 -23
  282. package/packages/opencode/src/util/locale.ts +0 -81
  283. package/packages/opencode/src/util/lock.ts +0 -98
  284. package/packages/opencode/src/util/log.ts +0 -182
  285. package/packages/opencode/src/util/network.ts +0 -9
  286. package/packages/opencode/src/util/process.ts +0 -176
  287. package/packages/opencode/src/util/queue.ts +0 -32
  288. package/packages/opencode/src/util/record.ts +0 -3
  289. package/packages/opencode/src/util/rpc.ts +0 -66
  290. package/packages/opencode/src/util/schema.ts +0 -53
  291. package/packages/opencode/src/util/scrap.ts +0 -10
  292. package/packages/opencode/src/util/signal.ts +0 -12
  293. package/packages/opencode/src/util/timeout.ts +0 -14
  294. package/packages/opencode/src/util/token.ts +0 -7
  295. package/packages/opencode/src/util/update-schema.ts +0 -13
  296. package/packages/opencode/src/util/which.ts +0 -14
  297. package/packages/opencode/src/util/wildcard.ts +0 -59
  298. package/packages/opencode/src/worktree/index.ts +0 -612
  299. package/packages/plugin/package.json +0 -38
  300. package/packages/plugin/src/example.ts +0 -18
  301. package/packages/plugin/src/index.ts +0 -282
  302. package/packages/plugin/src/shell.ts +0 -136
  303. package/packages/plugin/src/tool.ts +0 -38
  304. package/packages/plugin/src/tui.ts +0 -508
  305. package/packages/script/package.json +0 -16
  306. package/packages/script/src/index.ts +0 -77
  307. package/packages/sdk/package.json +0 -33
  308. package/packages/sdk/src/client.ts +0 -55
  309. package/packages/sdk/src/gen/client/client.gen.ts +0 -212
  310. package/packages/sdk/src/gen/client/index.ts +0 -25
  311. package/packages/sdk/src/gen/client/types.gen.ts +0 -222
  312. package/packages/sdk/src/gen/client/utils.gen.ts +0 -287
  313. package/packages/sdk/src/gen/client.gen.ts +0 -22
  314. package/packages/sdk/src/gen/core/auth.gen.ts +0 -41
  315. package/packages/sdk/src/gen/core/bodySerializer.gen.ts +0 -74
  316. package/packages/sdk/src/gen/core/params.gen.ts +0 -144
  317. package/packages/sdk/src/gen/core/pathSerializer.gen.ts +0 -167
  318. package/packages/sdk/src/gen/core/queryKeySerializer.gen.ts +0 -111
  319. package/packages/sdk/src/gen/core/serverSentEvents.gen.ts +0 -210
  320. package/packages/sdk/src/gen/core/types.gen.ts +0 -91
  321. package/packages/sdk/src/gen/core/utils.gen.ts +0 -109
  322. package/packages/sdk/src/gen/sdk.gen.ts +0 -1197
  323. package/packages/sdk/src/gen/types.gen.ts +0 -3904
  324. package/packages/sdk/src/index.ts +0 -21
  325. package/packages/sdk/src/process.ts +0 -31
  326. package/packages/sdk/src/server.ts +0 -134
  327. package/packages/sdk/src/v2/client.ts +0 -81
  328. package/packages/sdk/src/v2/gen/client/client.gen.ts +0 -285
  329. package/packages/sdk/src/v2/gen/client/index.ts +0 -25
  330. package/packages/sdk/src/v2/gen/client/types.gen.ts +0 -202
  331. package/packages/sdk/src/v2/gen/client/utils.gen.ts +0 -289
  332. package/packages/sdk/src/v2/gen/client.gen.ts +0 -18
  333. package/packages/sdk/src/v2/gen/core/auth.gen.ts +0 -41
  334. package/packages/sdk/src/v2/gen/core/bodySerializer.gen.ts +0 -82
  335. package/packages/sdk/src/v2/gen/core/params.gen.ts +0 -169
  336. package/packages/sdk/src/v2/gen/core/pathSerializer.gen.ts +0 -167
  337. package/packages/sdk/src/v2/gen/core/queryKeySerializer.gen.ts +0 -111
  338. package/packages/sdk/src/v2/gen/core/serverSentEvents.gen.ts +0 -239
  339. package/packages/sdk/src/v2/gen/core/types.gen.ts +0 -86
  340. package/packages/sdk/src/v2/gen/core/utils.gen.ts +0 -137
  341. package/packages/sdk/src/v2/gen/sdk.gen.ts +0 -4223
  342. package/packages/sdk/src/v2/gen/types.gen.ts +0 -5265
  343. package/packages/sdk/src/v2/index.ts +0 -21
  344. package/packages/sdk/src/v2/server.ts +0 -134
  345. package/packages/util/package.json +0 -20
  346. package/packages/util/src/array.ts +0 -10
  347. package/packages/util/src/binary.ts +0 -41
  348. package/packages/util/src/encode.ts +0 -51
  349. package/packages/util/src/error.ts +0 -54
  350. package/packages/util/src/fn.ts +0 -11
  351. package/packages/util/src/identifier.ts +0 -48
  352. package/packages/util/src/iife.ts +0 -3
  353. package/packages/util/src/lazy.ts +0 -11
  354. package/packages/util/src/module.ts +0 -10
  355. package/packages/util/src/path.ts +0 -37
  356. package/packages/util/src/retry.ts +0 -41
  357. package/packages/util/src/slug.ts +0 -74
  358. package/postinstall.cjs +0 -55
@@ -1,931 +0,0 @@
1
- import { dynamicTool, type Tool, jsonSchema, type JSONSchema7 } from "ai"
2
- import { Client } from "@modelcontextprotocol/sdk/client/index.js"
3
- import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"
4
- import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js"
5
- import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"
6
- import { UnauthorizedError } from "@modelcontextprotocol/sdk/client/auth.js"
7
- import {
8
- CallToolResultSchema,
9
- type Tool as MCPToolDef,
10
- ToolListChangedNotificationSchema,
11
- } from "@modelcontextprotocol/sdk/types.js"
12
- import { Config } from "../config/config"
13
- import { Log } from "../util/log"
14
- import { NamedError } from "@opencode-ai/util/error"
15
- import z from "zod/v4"
16
- import { Instance } from "../project/instance"
17
- import { Installation } from "../installation"
18
- import { withTimeout } from "@/util/timeout"
19
- import { AppFileSystem } from "@/filesystem"
20
- import { McpOAuthProvider } from "./oauth-provider"
21
- import { McpOAuthCallback } from "./oauth-callback"
22
- import { McpAuth } from "./auth"
23
- import { BusEvent } from "../bus/bus-event"
24
- import { Bus } from "@/bus"
25
- import { TuiEvent } from "@/cli/cmd/tui/event"
26
- import open from "open"
27
- import { Effect, Exit, Layer, Option, ServiceMap, Stream } from "effect"
28
- import { InstanceState } from "@/effect/instance-state"
29
- import { makeRuntime } from "@/effect/run-service"
30
- import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"
31
- import * as CrossSpawnSpawner from "@/effect/cross-spawn-spawner"
32
-
33
- export namespace MCP {
34
- const log = Log.create({ service: "mcp" })
35
- const DEFAULT_TIMEOUT = 30_000
36
-
37
- export const Resource = z
38
- .object({
39
- name: z.string(),
40
- uri: z.string(),
41
- description: z.string().optional(),
42
- mimeType: z.string().optional(),
43
- client: z.string(),
44
- })
45
- .meta({ ref: "McpResource" })
46
- export type Resource = z.infer<typeof Resource>
47
-
48
- export const ToolsChanged = BusEvent.define(
49
- "mcp.tools.changed",
50
- z.object({
51
- server: z.string(),
52
- }),
53
- )
54
-
55
- export const BrowserOpenFailed = BusEvent.define(
56
- "mcp.browser.open.failed",
57
- z.object({
58
- mcpName: z.string(),
59
- url: z.string(),
60
- }),
61
- )
62
-
63
- export const Failed = NamedError.create(
64
- "MCPFailed",
65
- z.object({
66
- name: z.string(),
67
- }),
68
- )
69
-
70
- type MCPClient = Client
71
-
72
- export const Status = z
73
- .discriminatedUnion("status", [
74
- z
75
- .object({
76
- status: z.literal("connected"),
77
- })
78
- .meta({
79
- ref: "MCPStatusConnected",
80
- }),
81
- z
82
- .object({
83
- status: z.literal("disabled"),
84
- })
85
- .meta({
86
- ref: "MCPStatusDisabled",
87
- }),
88
- z
89
- .object({
90
- status: z.literal("failed"),
91
- error: z.string(),
92
- })
93
- .meta({
94
- ref: "MCPStatusFailed",
95
- }),
96
- z
97
- .object({
98
- status: z.literal("needs_auth"),
99
- })
100
- .meta({
101
- ref: "MCPStatusNeedsAuth",
102
- }),
103
- z
104
- .object({
105
- status: z.literal("needs_client_registration"),
106
- error: z.string(),
107
- })
108
- .meta({
109
- ref: "MCPStatusNeedsClientRegistration",
110
- }),
111
- ])
112
- .meta({
113
- ref: "MCPStatus",
114
- })
115
- export type Status = z.infer<typeof Status>
116
-
117
- // Store transports for OAuth servers to allow finishing auth
118
- type TransportWithAuth = StreamableHTTPClientTransport | SSEClientTransport
119
- const pendingOAuthTransports = new Map<string, TransportWithAuth>()
120
-
121
- // Prompt cache types
122
- type PromptInfo = Awaited<ReturnType<MCPClient["listPrompts"]>>["prompts"][number]
123
- type ResourceInfo = Awaited<ReturnType<MCPClient["listResources"]>>["resources"][number]
124
- type McpEntry = NonNullable<Config.Info["mcp"]>[string]
125
-
126
- function isMcpConfigured(entry: McpEntry): entry is Config.Mcp {
127
- return typeof entry === "object" && entry !== null && "type" in entry
128
- }
129
-
130
- const sanitize = (s: string) => s.replace(/[^a-zA-Z0-9_-]/g, "_")
131
-
132
- // Thread-local context for passing session identity to MCP tool calls.
133
- // Set by prompt.ts before each tool execution, read by callTool below.
134
- export let currentToolContext: { sessionId?: string; messageId?: string } = {}
135
-
136
- // Convert MCP tool definition to AI SDK Tool type
137
- function convertMcpTool(mcpTool: MCPToolDef, client: MCPClient, timeout?: number): Tool {
138
- const inputSchema = mcpTool.inputSchema
139
-
140
- // Spread first, then override type to ensure it's always "object"
141
- const schema: JSONSchema7 = {
142
- ...(inputSchema as JSONSchema7),
143
- type: "object",
144
- properties: (inputSchema.properties ?? {}) as JSONSchema7["properties"],
145
- additionalProperties: false,
146
- }
147
-
148
- return dynamicTool({
149
- description: mcpTool.description ?? "",
150
- inputSchema: jsonSchema(schema),
151
- execute: async (args: unknown) => {
152
- // Include session identity in _meta so the MCP server knows which session
153
- // this tool call belongs to (avoids races when MCP processes are shared)
154
- const _meta: Record<string, unknown> = {}
155
- if (currentToolContext.sessionId) _meta.sessionId = currentToolContext.sessionId
156
- if (currentToolContext.messageId) _meta.messageId = currentToolContext.messageId
157
- return client.callTool(
158
- {
159
- name: mcpTool.name,
160
- arguments: (args || {}) as Record<string, unknown>,
161
- _meta: Object.keys(_meta).length > 0 ? _meta : undefined,
162
- },
163
- CallToolResultSchema,
164
- {
165
- resetTimeoutOnProgress: true,
166
- timeout,
167
- },
168
- )
169
- },
170
- })
171
- }
172
-
173
- function defs(key: string, client: MCPClient, timeout?: number) {
174
- return Effect.tryPromise({
175
- try: () => withTimeout(client.listTools(), timeout ?? DEFAULT_TIMEOUT),
176
- catch: (err) => (err instanceof Error ? err : new Error(String(err))),
177
- }).pipe(
178
- Effect.map((result) => result.tools),
179
- Effect.catch((err) => {
180
- log.error("failed to get tools from client", { key, error: err })
181
- return Effect.succeed(undefined)
182
- }),
183
- )
184
- }
185
-
186
- function fetchFromClient<T extends { name: string }>(
187
- clientName: string,
188
- client: Client,
189
- listFn: (c: Client) => Promise<T[]>,
190
- label: string,
191
- ) {
192
- return Effect.tryPromise({
193
- try: () => listFn(client),
194
- catch: (e: any) => {
195
- log.error(`failed to get ${label}`, { clientName, error: e.message })
196
- return e
197
- },
198
- }).pipe(
199
- Effect.map((items) => {
200
- const out: Record<string, T & { client: string }> = {}
201
- const sanitizedClient = sanitize(clientName)
202
- for (const item of items) {
203
- out[sanitizedClient + ":" + sanitize(item.name)] = { ...item, client: clientName }
204
- }
205
- return out
206
- }),
207
- Effect.orElseSucceed(() => undefined),
208
- )
209
- }
210
-
211
- interface CreateResult {
212
- mcpClient?: MCPClient
213
- status: Status
214
- defs?: MCPToolDef[]
215
- }
216
-
217
- // --- Effect Service ---
218
-
219
- interface State {
220
- status: Record<string, Status>
221
- clients: Record<string, MCPClient>
222
- defs: Record<string, MCPToolDef[]>
223
- }
224
-
225
- export interface Interface {
226
- readonly status: () => Effect.Effect<Record<string, Status>>
227
- readonly clients: () => Effect.Effect<Record<string, MCPClient>>
228
- readonly tools: () => Effect.Effect<Record<string, Tool>>
229
- readonly prompts: () => Effect.Effect<Record<string, PromptInfo & { client: string }>>
230
- readonly resources: () => Effect.Effect<Record<string, ResourceInfo & { client: string }>>
231
- readonly add: (name: string, mcp: Config.Mcp) => Effect.Effect<{ status: Record<string, Status> | Status }>
232
- readonly connect: (name: string) => Effect.Effect<void>
233
- readonly disconnect: (name: string) => Effect.Effect<void>
234
- readonly getPrompt: (
235
- clientName: string,
236
- name: string,
237
- args?: Record<string, string>,
238
- ) => Effect.Effect<Awaited<ReturnType<MCPClient["getPrompt"]>> | undefined>
239
- readonly readResource: (
240
- clientName: string,
241
- resourceUri: string,
242
- ) => Effect.Effect<Awaited<ReturnType<MCPClient["readResource"]>> | undefined>
243
- readonly startAuth: (mcpName: string) => Effect.Effect<{ authorizationUrl: string; oauthState: string }>
244
- readonly authenticate: (mcpName: string) => Effect.Effect<Status>
245
- readonly finishAuth: (mcpName: string, authorizationCode: string) => Effect.Effect<Status>
246
- readonly removeAuth: (mcpName: string) => Effect.Effect<void>
247
- readonly supportsOAuth: (mcpName: string) => Effect.Effect<boolean>
248
- readonly hasStoredTokens: (mcpName: string) => Effect.Effect<boolean>
249
- readonly getAuthStatus: (mcpName: string) => Effect.Effect<AuthStatus>
250
- }
251
-
252
- export class Service extends ServiceMap.Service<Service, Interface>()("@opencode/MCP") {}
253
-
254
- export const layer = Layer.effect(
255
- Service,
256
- Effect.gen(function* () {
257
- const spawner = yield* ChildProcessSpawner.ChildProcessSpawner
258
- const auth = yield* McpAuth.Service
259
- const bus = yield* Bus.Service
260
-
261
- type Transport = StdioClientTransport | StreamableHTTPClientTransport | SSEClientTransport
262
-
263
- /**
264
- * Connect a client via the given transport with resource safety:
265
- * on failure the transport is closed; on success the caller owns it.
266
- */
267
- const connectTransport = (transport: Transport, timeout: number) =>
268
- Effect.acquireUseRelease(
269
- Effect.succeed(transport),
270
- (t) =>
271
- Effect.tryPromise({
272
- try: () => {
273
- const client = new Client({ name: "opencode", version: Installation.VERSION })
274
- return withTimeout(client.connect(t), timeout).then(() => client)
275
- },
276
- catch: (e) => (e instanceof Error ? e : new Error(String(e))),
277
- }),
278
- (t, exit) => (Exit.isFailure(exit) ? Effect.tryPromise(() => t.close()).pipe(Effect.ignore) : Effect.void),
279
- )
280
-
281
- const DISABLED_RESULT: CreateResult = { status: { status: "disabled" } }
282
-
283
- const connectRemote = Effect.fn("MCP.connectRemote")(function* (
284
- key: string,
285
- mcp: Config.Mcp & { type: "remote" },
286
- ) {
287
- const oauthDisabled = mcp.oauth === false
288
- const oauthConfig = typeof mcp.oauth === "object" ? mcp.oauth : undefined
289
- let authProvider: McpOAuthProvider | undefined
290
-
291
- if (!oauthDisabled) {
292
- authProvider = new McpOAuthProvider(
293
- key,
294
- mcp.url,
295
- {
296
- clientId: oauthConfig?.clientId,
297
- clientSecret: oauthConfig?.clientSecret,
298
- scope: oauthConfig?.scope,
299
- },
300
- {
301
- onRedirect: async (url) => {
302
- log.info("oauth redirect requested", { key, url: url.toString() })
303
- },
304
- },
305
- )
306
- }
307
-
308
- const transports: Array<{ name: string; transport: TransportWithAuth }> = [
309
- {
310
- name: "StreamableHTTP",
311
- transport: new StreamableHTTPClientTransport(new URL(mcp.url), {
312
- authProvider,
313
- requestInit: mcp.headers ? { headers: mcp.headers } : undefined,
314
- }),
315
- },
316
- {
317
- name: "SSE",
318
- transport: new SSEClientTransport(new URL(mcp.url), {
319
- authProvider,
320
- requestInit: mcp.headers ? { headers: mcp.headers } : undefined,
321
- }),
322
- },
323
- ]
324
-
325
- const connectTimeout = mcp.timeout ?? DEFAULT_TIMEOUT
326
- let lastStatus: Status | undefined
327
-
328
- for (const { name, transport } of transports) {
329
- const result = yield* connectTransport(transport, connectTimeout).pipe(
330
- Effect.map((client) => ({ client, transportName: name })),
331
- Effect.catch((error) => {
332
- const lastError = error instanceof Error ? error : new Error(String(error))
333
- const isAuthError =
334
- error instanceof UnauthorizedError || (authProvider && lastError.message.includes("OAuth"))
335
-
336
- if (isAuthError) {
337
- log.info("mcp server requires authentication", { key, transport: name })
338
-
339
- if (lastError.message.includes("registration") || lastError.message.includes("client_id")) {
340
- lastStatus = {
341
- status: "needs_client_registration" as const,
342
- error: "Server does not support dynamic client registration. Please provide clientId in config.",
343
- }
344
- return bus
345
- .publish(TuiEvent.ToastShow, {
346
- title: "MCP Authentication Required",
347
- message: `Server "${key}" requires a pre-registered client ID. Add clientId to your config.`,
348
- variant: "warning",
349
- duration: 8000,
350
- })
351
- .pipe(Effect.ignore, Effect.as(undefined))
352
- } else {
353
- pendingOAuthTransports.set(key, transport)
354
- lastStatus = { status: "needs_auth" as const }
355
- return bus
356
- .publish(TuiEvent.ToastShow, {
357
- title: "MCP Authentication Required",
358
- message: `Server "${key}" requires authentication. Run: opencode mcp auth ${key}`,
359
- variant: "warning",
360
- duration: 8000,
361
- })
362
- .pipe(Effect.ignore, Effect.as(undefined))
363
- }
364
- }
365
-
366
- log.debug("transport connection failed", {
367
- key,
368
- transport: name,
369
- url: mcp.url,
370
- error: lastError.message,
371
- })
372
- lastStatus = { status: "failed" as const, error: lastError.message }
373
- return Effect.succeed(undefined)
374
- }),
375
- )
376
- if (result) {
377
- log.info("connected", { key, transport: result.transportName })
378
- return { client: result.client as MCPClient | undefined, status: { status: "connected" } as Status }
379
- }
380
- // If this was an auth error, stop trying other transports
381
- if (lastStatus?.status === "needs_auth" || lastStatus?.status === "needs_client_registration") break
382
- }
383
-
384
- return {
385
- client: undefined as MCPClient | undefined,
386
- status: (lastStatus ?? { status: "failed", error: "Unknown error" }) as Status,
387
- }
388
- })
389
-
390
- const connectLocal = Effect.fn("MCP.connectLocal")(function* (key: string, mcp: Config.Mcp & { type: "local" }) {
391
- const [cmd, ...args] = mcp.command
392
- const cwd = Instance.directory
393
- const transport = new StdioClientTransport({
394
- stderr: "pipe",
395
- command: cmd,
396
- args,
397
- cwd,
398
- env: {
399
- ...process.env,
400
- ...(cmd === "opencode" ? { BUN_BE_BUN: "1" } : {}),
401
- ...mcp.environment,
402
- },
403
- })
404
- transport.stderr?.on("data", (chunk: Buffer) => {
405
- log.info(`mcp stderr: ${chunk.toString()}`, { key })
406
- })
407
-
408
- const connectTimeout = mcp.timeout ?? DEFAULT_TIMEOUT
409
- return yield* connectTransport(transport, connectTimeout).pipe(
410
- Effect.map((client): { client: MCPClient | undefined; status: Status } => ({
411
- client,
412
- status: { status: "connected" },
413
- })),
414
- Effect.catch((error): Effect.Effect<{ client: MCPClient | undefined; status: Status }> => {
415
- const msg = error instanceof Error ? error.message : String(error)
416
- log.error("local mcp startup failed", { key, command: mcp.command, cwd, error: msg })
417
- return Effect.succeed({ client: undefined, status: { status: "failed", error: msg } })
418
- }),
419
- )
420
- })
421
-
422
- const create = Effect.fn("MCP.create")(function* (key: string, mcp: Config.Mcp) {
423
- if (mcp.enabled === false) {
424
- log.info("mcp server disabled", { key })
425
- return DISABLED_RESULT
426
- }
427
-
428
- log.info("found", { key, type: mcp.type })
429
-
430
- const { client: mcpClient, status } =
431
- mcp.type === "remote"
432
- ? yield* connectRemote(key, mcp as Config.Mcp & { type: "remote" })
433
- : yield* connectLocal(key, mcp as Config.Mcp & { type: "local" })
434
-
435
- if (!mcpClient) {
436
- return { status } satisfies CreateResult
437
- }
438
-
439
- const listed = yield* defs(key, mcpClient, mcp.timeout)
440
- if (!listed) {
441
- yield* Effect.tryPromise(() => mcpClient.close()).pipe(Effect.ignore)
442
- return { status: { status: "failed", error: "Failed to get tools" } } satisfies CreateResult
443
- }
444
-
445
- log.info("create() successfully created client", { key, toolCount: listed.length })
446
- return { mcpClient, status, defs: listed } satisfies CreateResult
447
- })
448
- const cfgSvc = yield* Config.Service
449
-
450
- const descendants = Effect.fnUntraced(
451
- function* (pid: number) {
452
- if (process.platform === "win32") return [] as number[]
453
- const pids: number[] = []
454
- const queue = [pid]
455
- while (queue.length > 0) {
456
- const current = queue.shift()!
457
- const handle = yield* spawner.spawn(
458
- ChildProcess.make("pgrep", ["-P", String(current)], { stdin: "ignore" }),
459
- )
460
- const text = yield* Stream.mkString(Stream.decodeText(handle.stdout))
461
- yield* handle.exitCode
462
- for (const tok of text.split("\n")) {
463
- const cpid = parseInt(tok, 10)
464
- if (!isNaN(cpid) && !pids.includes(cpid)) {
465
- pids.push(cpid)
466
- queue.push(cpid)
467
- }
468
- }
469
- }
470
- return pids
471
- },
472
- Effect.scoped,
473
- Effect.catch(() => Effect.succeed([] as number[])),
474
- )
475
-
476
- function watch(s: State, name: string, client: MCPClient, timeout?: number) {
477
- client.setNotificationHandler(ToolListChangedNotificationSchema, async () => {
478
- log.info("tools list changed notification received", { server: name })
479
- if (s.clients[name] !== client || s.status[name]?.status !== "connected") return
480
-
481
- const listed = await Effect.runPromise(defs(name, client, timeout))
482
- if (!listed) return
483
- if (s.clients[name] !== client || s.status[name]?.status !== "connected") return
484
-
485
- s.defs[name] = listed
486
- await Effect.runPromise(bus.publish(ToolsChanged, { server: name }).pipe(Effect.ignore))
487
- })
488
- }
489
-
490
- const state = yield* InstanceState.make<State>(
491
- Effect.fn("MCP.state")(function* () {
492
- const cfg = yield* cfgSvc.get()
493
- const config = cfg.mcp ?? {}
494
- const s: State = {
495
- status: {},
496
- clients: {},
497
- defs: {},
498
- }
499
-
500
- yield* Effect.forEach(
501
- Object.entries(config),
502
- ([key, mcp]) =>
503
- Effect.gen(function* () {
504
- if (!isMcpConfigured(mcp)) {
505
- log.error("Ignoring MCP config entry without type", { key })
506
- return
507
- }
508
-
509
- if (mcp.enabled === false) {
510
- s.status[key] = { status: "disabled" }
511
- return
512
- }
513
-
514
- const result = yield* create(key, mcp).pipe(Effect.catch(() => Effect.succeed(undefined)))
515
- if (!result) return
516
-
517
- s.status[key] = result.status
518
- if (result.mcpClient) {
519
- s.clients[key] = result.mcpClient
520
- s.defs[key] = result.defs!
521
- watch(s, key, result.mcpClient, mcp.timeout)
522
- }
523
- }),
524
- { concurrency: "unbounded" },
525
- )
526
-
527
- yield* Effect.addFinalizer(() =>
528
- Effect.gen(function* () {
529
- yield* Effect.forEach(
530
- Object.values(s.clients),
531
- (client) =>
532
- Effect.gen(function* () {
533
- const pid = (client.transport as any)?.pid
534
- if (typeof pid === "number") {
535
- const pids = yield* descendants(pid)
536
- for (const dpid of pids) {
537
- try {
538
- process.kill(dpid, "SIGTERM")
539
- } catch {}
540
- }
541
- }
542
- yield* Effect.tryPromise(() => client.close()).pipe(Effect.ignore)
543
- }),
544
- { concurrency: "unbounded" },
545
- )
546
- pendingOAuthTransports.clear()
547
- }),
548
- )
549
-
550
- return s
551
- }),
552
- )
553
-
554
- function closeClient(s: State, name: string) {
555
- const client = s.clients[name]
556
- delete s.defs[name]
557
- if (!client) return Effect.void
558
- return Effect.tryPromise(() => client.close()).pipe(Effect.ignore)
559
- }
560
-
561
- const status = Effect.fn("MCP.status")(function* () {
562
- const s = yield* InstanceState.get(state)
563
-
564
- const cfg = yield* cfgSvc.get()
565
- const config = cfg.mcp ?? {}
566
- const result: Record<string, Status> = {}
567
-
568
- for (const [key, mcp] of Object.entries(config)) {
569
- if (!isMcpConfigured(mcp)) continue
570
- result[key] = s.status[key] ?? { status: "disabled" }
571
- }
572
-
573
- return result
574
- })
575
-
576
- const clients = Effect.fn("MCP.clients")(function* () {
577
- const s = yield* InstanceState.get(state)
578
- return s.clients
579
- })
580
-
581
- const createAndStore = Effect.fn("MCP.createAndStore")(function* (name: string, mcp: Config.Mcp) {
582
- const s = yield* InstanceState.get(state)
583
- const result = yield* create(name, mcp)
584
-
585
- s.status[name] = result.status
586
- if (!result.mcpClient) {
587
- yield* closeClient(s, name)
588
- delete s.clients[name]
589
- return result.status
590
- }
591
-
592
- yield* closeClient(s, name)
593
- s.clients[name] = result.mcpClient
594
- s.defs[name] = result.defs!
595
- watch(s, name, result.mcpClient, mcp.timeout)
596
- return result.status
597
- })
598
-
599
- const add = Effect.fn("MCP.add")(function* (name: string, mcp: Config.Mcp) {
600
- yield* createAndStore(name, mcp)
601
- const s = yield* InstanceState.get(state)
602
- return { status: s.status }
603
- })
604
-
605
- const connect = Effect.fn("MCP.connect")(function* (name: string) {
606
- const mcp = yield* getMcpConfig(name)
607
- if (!mcp) {
608
- log.error("MCP config not found or invalid", { name })
609
- return
610
- }
611
- yield* createAndStore(name, { ...mcp, enabled: true })
612
- })
613
-
614
- const disconnect = Effect.fn("MCP.disconnect")(function* (name: string) {
615
- const s = yield* InstanceState.get(state)
616
- yield* closeClient(s, name)
617
- delete s.clients[name]
618
- s.status[name] = { status: "disabled" }
619
- })
620
-
621
- const tools = Effect.fn("MCP.tools")(function* () {
622
- const result: Record<string, Tool> = {}
623
- const s = yield* InstanceState.get(state)
624
-
625
- const cfg = yield* cfgSvc.get()
626
- const config = cfg.mcp ?? {}
627
- const defaultTimeout = cfg.experimental?.mcp_timeout
628
-
629
- const connectedClients = Object.entries(s.clients).filter(
630
- ([clientName]) => s.status[clientName]?.status === "connected",
631
- )
632
-
633
- yield* Effect.forEach(
634
- connectedClients,
635
- ([clientName, client]) =>
636
- Effect.gen(function* () {
637
- const mcpConfig = config[clientName]
638
- const entry = mcpConfig && isMcpConfigured(mcpConfig) ? mcpConfig : undefined
639
-
640
- const listed = s.defs[clientName]
641
- if (!listed) {
642
- log.warn("missing cached tools for connected server", { clientName })
643
- return
644
- }
645
-
646
- const timeout = entry?.timeout ?? defaultTimeout
647
- for (const mcpTool of listed) {
648
- result[sanitize(clientName) + "_" + sanitize(mcpTool.name)] = convertMcpTool(mcpTool, client, timeout)
649
- }
650
- }),
651
- { concurrency: "unbounded" },
652
- )
653
- return result
654
- })
655
-
656
- function collectFromConnected<T extends { name: string }>(
657
- s: State,
658
- listFn: (c: Client) => Promise<T[]>,
659
- label: string,
660
- ) {
661
- return Effect.forEach(
662
- Object.entries(s.clients).filter(([name]) => s.status[name]?.status === "connected"),
663
- ([clientName, client]) =>
664
- fetchFromClient(clientName, client, listFn, label).pipe(Effect.map((items) => Object.entries(items ?? {}))),
665
- { concurrency: "unbounded" },
666
- ).pipe(Effect.map((results) => Object.fromEntries<T & { client: string }>(results.flat())))
667
- }
668
-
669
- const prompts = Effect.fn("MCP.prompts")(function* () {
670
- const s = yield* InstanceState.get(state)
671
- return yield* collectFromConnected(s, (c) => c.listPrompts().then((r) => r.prompts), "prompts")
672
- })
673
-
674
- const resources = Effect.fn("MCP.resources")(function* () {
675
- const s = yield* InstanceState.get(state)
676
- return yield* collectFromConnected(s, (c) => c.listResources().then((r) => r.resources), "resources")
677
- })
678
-
679
- const withClient = Effect.fnUntraced(function* <A>(
680
- clientName: string,
681
- fn: (client: MCPClient) => Promise<A>,
682
- label: string,
683
- meta?: Record<string, unknown>,
684
- ) {
685
- const s = yield* InstanceState.get(state)
686
- const client = s.clients[clientName]
687
- if (!client) {
688
- log.warn(`client not found for ${label}`, { clientName })
689
- return undefined
690
- }
691
- return yield* Effect.tryPromise({
692
- try: () => fn(client),
693
- catch: (e: any) => {
694
- log.error(`failed to ${label}`, { clientName, ...meta, error: e?.message })
695
- return e
696
- },
697
- }).pipe(Effect.orElseSucceed(() => undefined))
698
- })
699
-
700
- const getPrompt = Effect.fn("MCP.getPrompt")(function* (
701
- clientName: string,
702
- name: string,
703
- args?: Record<string, string>,
704
- ) {
705
- return yield* withClient(clientName, (client) => client.getPrompt({ name, arguments: args }), "getPrompt", {
706
- promptName: name,
707
- })
708
- })
709
-
710
- const readResource = Effect.fn("MCP.readResource")(function* (clientName: string, resourceUri: string) {
711
- return yield* withClient(clientName, (client) => client.readResource({ uri: resourceUri }), "readResource", {
712
- resourceUri,
713
- })
714
- })
715
-
716
- const getMcpConfig = Effect.fnUntraced(function* (mcpName: string) {
717
- const cfg = yield* cfgSvc.get()
718
- const mcpConfig = cfg.mcp?.[mcpName]
719
- if (!mcpConfig || !isMcpConfigured(mcpConfig)) return undefined
720
- return mcpConfig
721
- })
722
-
723
- const startAuth = Effect.fn("MCP.startAuth")(function* (mcpName: string) {
724
- const mcpConfig = yield* getMcpConfig(mcpName)
725
- if (!mcpConfig) throw new Error(`MCP server ${mcpName} not found or disabled`)
726
- if (mcpConfig.type !== "remote") throw new Error(`MCP server ${mcpName} is not a remote server`)
727
- if (mcpConfig.oauth === false) throw new Error(`MCP server ${mcpName} has OAuth explicitly disabled`)
728
-
729
- yield* Effect.promise(() => McpOAuthCallback.ensureRunning())
730
-
731
- const oauthState = Array.from(crypto.getRandomValues(new Uint8Array(32)))
732
- .map((b) => b.toString(16).padStart(2, "0"))
733
- .join("")
734
- yield* auth.updateOAuthState(mcpName, oauthState)
735
- const oauthConfig = typeof mcpConfig.oauth === "object" ? mcpConfig.oauth : undefined
736
- let capturedUrl: URL | undefined
737
- const authProvider = new McpOAuthProvider(
738
- mcpName,
739
- mcpConfig.url,
740
- {
741
- clientId: oauthConfig?.clientId,
742
- clientSecret: oauthConfig?.clientSecret,
743
- scope: oauthConfig?.scope,
744
- },
745
- {
746
- onRedirect: async (url) => {
747
- capturedUrl = url
748
- },
749
- },
750
- )
751
-
752
- const transport = new StreamableHTTPClientTransport(new URL(mcpConfig.url), { authProvider })
753
-
754
- return yield* Effect.tryPromise({
755
- try: () => {
756
- const client = new Client({ name: "opencode", version: Installation.VERSION })
757
- return client.connect(transport).then(() => ({ authorizationUrl: "", oauthState }))
758
- },
759
- catch: (error) => error,
760
- }).pipe(
761
- Effect.catch((error) => {
762
- if (error instanceof UnauthorizedError && capturedUrl) {
763
- pendingOAuthTransports.set(mcpName, transport)
764
- return Effect.succeed({ authorizationUrl: capturedUrl.toString(), oauthState })
765
- }
766
- return Effect.die(error)
767
- }),
768
- )
769
- })
770
-
771
- const authenticate = Effect.fn("MCP.authenticate")(function* (mcpName: string) {
772
- const { authorizationUrl, oauthState } = yield* startAuth(mcpName)
773
- if (!authorizationUrl) return { status: "connected" } as Status
774
-
775
- log.info("opening browser for oauth", { mcpName, url: authorizationUrl, state: oauthState })
776
-
777
- const callbackPromise = McpOAuthCallback.waitForCallback(oauthState, mcpName)
778
-
779
- yield* Effect.tryPromise(() => open(authorizationUrl)).pipe(
780
- Effect.flatMap((subprocess) =>
781
- Effect.callback<void, Error>((resume) => {
782
- const timer = setTimeout(() => resume(Effect.void), 500)
783
- subprocess.on("error", (err) => {
784
- clearTimeout(timer)
785
- resume(Effect.fail(err))
786
- })
787
- subprocess.on("exit", (code) => {
788
- if (code !== null && code !== 0) {
789
- clearTimeout(timer)
790
- resume(Effect.fail(new Error(`Browser open failed with exit code ${code}`)))
791
- }
792
- })
793
- }),
794
- ),
795
- Effect.catch(() => {
796
- log.warn("failed to open browser, user must open URL manually", { mcpName })
797
- return bus.publish(BrowserOpenFailed, { mcpName, url: authorizationUrl }).pipe(Effect.ignore)
798
- }),
799
- )
800
-
801
- const code = yield* Effect.promise(() => callbackPromise)
802
-
803
- const storedState = yield* auth.getOAuthState(mcpName)
804
- if (storedState !== oauthState) {
805
- yield* auth.clearOAuthState(mcpName)
806
- throw new Error("OAuth state mismatch - potential CSRF attack")
807
- }
808
- yield* auth.clearOAuthState(mcpName)
809
- return yield* finishAuth(mcpName, code)
810
- })
811
-
812
- const finishAuth = Effect.fn("MCP.finishAuth")(function* (mcpName: string, authorizationCode: string) {
813
- const transport = pendingOAuthTransports.get(mcpName)
814
- if (!transport) throw new Error(`No pending OAuth flow for MCP server: ${mcpName}`)
815
-
816
- const result = yield* Effect.tryPromise({
817
- try: () => transport.finishAuth(authorizationCode).then(() => true as const),
818
- catch: (error) => {
819
- log.error("failed to finish oauth", { mcpName, error })
820
- return error
821
- },
822
- }).pipe(Effect.option)
823
-
824
- if (Option.isNone(result)) {
825
- return { status: "failed", error: "OAuth completion failed" } as Status
826
- }
827
-
828
- yield* auth.clearCodeVerifier(mcpName)
829
- pendingOAuthTransports.delete(mcpName)
830
-
831
- const mcpConfig = yield* getMcpConfig(mcpName)
832
- if (!mcpConfig) return { status: "failed", error: "MCP config not found after auth" } as Status
833
-
834
- return yield* createAndStore(mcpName, mcpConfig)
835
- })
836
-
837
- const removeAuth = Effect.fn("MCP.removeAuth")(function* (mcpName: string) {
838
- yield* auth.remove(mcpName)
839
- McpOAuthCallback.cancelPending(mcpName)
840
- pendingOAuthTransports.delete(mcpName)
841
- log.info("removed oauth credentials", { mcpName })
842
- })
843
-
844
- const supportsOAuth = Effect.fn("MCP.supportsOAuth")(function* (mcpName: string) {
845
- const mcpConfig = yield* getMcpConfig(mcpName)
846
- if (!mcpConfig) return false
847
- return mcpConfig.type === "remote" && mcpConfig.oauth !== false
848
- })
849
-
850
- const hasStoredTokens = Effect.fn("MCP.hasStoredTokens")(function* (mcpName: string) {
851
- const entry = yield* auth.get(mcpName)
852
- return !!entry?.tokens
853
- })
854
-
855
- const getAuthStatus = Effect.fn("MCP.getAuthStatus")(function* (mcpName: string) {
856
- const entry = yield* auth.get(mcpName)
857
- if (!entry?.tokens) return "not_authenticated" as AuthStatus
858
- const expired = yield* auth.isTokenExpired(mcpName)
859
- return (expired ? "expired" : "authenticated") as AuthStatus
860
- })
861
-
862
- return Service.of({
863
- status,
864
- clients,
865
- tools,
866
- prompts,
867
- resources,
868
- add,
869
- connect,
870
- disconnect,
871
- getPrompt,
872
- readResource,
873
- startAuth,
874
- authenticate,
875
- finishAuth,
876
- removeAuth,
877
- supportsOAuth,
878
- hasStoredTokens,
879
- getAuthStatus,
880
- })
881
- }),
882
- )
883
-
884
- export type AuthStatus = "authenticated" | "expired" | "not_authenticated"
885
-
886
- // --- Per-service runtime ---
887
-
888
- export const defaultLayer = layer.pipe(
889
- Layer.provide(McpAuth.layer),
890
- Layer.provide(Bus.layer),
891
- Layer.provide(Config.defaultLayer),
892
- Layer.provide(CrossSpawnSpawner.defaultLayer),
893
- Layer.provide(AppFileSystem.defaultLayer),
894
- )
895
-
896
- const { runPromise } = makeRuntime(Service, defaultLayer)
897
-
898
- // --- Async facade functions ---
899
-
900
- export const status = async () => runPromise((svc) => svc.status())
901
-
902
- export const tools = async () => runPromise((svc) => svc.tools())
903
-
904
- export const prompts = async () => runPromise((svc) => svc.prompts())
905
-
906
- export const resources = async () => runPromise((svc) => svc.resources())
907
-
908
- export const add = async (name: string, mcp: Config.Mcp) => runPromise((svc) => svc.add(name, mcp))
909
-
910
- export const connect = async (name: string) => runPromise((svc) => svc.connect(name))
911
-
912
- export const disconnect = async (name: string) => runPromise((svc) => svc.disconnect(name))
913
-
914
- export const getPrompt = async (clientName: string, name: string, args?: Record<string, string>) =>
915
- runPromise((svc) => svc.getPrompt(clientName, name, args))
916
-
917
- export const startAuth = async (mcpName: string) => runPromise((svc) => svc.startAuth(mcpName))
918
-
919
- export const authenticate = async (mcpName: string) => runPromise((svc) => svc.authenticate(mcpName))
920
-
921
- export const finishAuth = async (mcpName: string, authorizationCode: string) =>
922
- runPromise((svc) => svc.finishAuth(mcpName, authorizationCode))
923
-
924
- export const removeAuth = async (mcpName: string) => runPromise((svc) => svc.removeAuth(mcpName))
925
-
926
- export const supportsOAuth = async (mcpName: string) => runPromise((svc) => svc.supportsOAuth(mcpName))
927
-
928
- export const hasStoredTokens = async (mcpName: string) => runPromise((svc) => svc.hasStoredTokens(mcpName))
929
-
930
- export const getAuthStatus = async (mcpName: string) => runPromise((svc) => svc.getAuthStatus(mcpName))
931
- }