chad-code 1.3.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 (338) hide show
  1. package/AGENTS.md +27 -0
  2. package/Dockerfile +18 -0
  3. package/README.md +15 -0
  4. package/README.npm.md +64 -0
  5. package/bin/chad-code +84 -0
  6. package/bunfig.toml +7 -0
  7. package/eslint.config.js +29 -0
  8. package/package.json +107 -0
  9. package/parsers-config.ts +253 -0
  10. package/script/build.ts +167 -0
  11. package/script/postinstall.mjs +122 -0
  12. package/script/publish-registries.ts +187 -0
  13. package/script/publish.ts +93 -0
  14. package/script/schema.ts +47 -0
  15. package/src/acp/README.md +164 -0
  16. package/src/acp/agent.ts +1086 -0
  17. package/src/acp/session.ts +101 -0
  18. package/src/acp/types.ts +22 -0
  19. package/src/agent/agent.ts +253 -0
  20. package/src/agent/generate.txt +75 -0
  21. package/src/agent/prompt/compaction.txt +12 -0
  22. package/src/agent/prompt/explore.txt +18 -0
  23. package/src/agent/prompt/summary.txt +11 -0
  24. package/src/agent/prompt/title.txt +36 -0
  25. package/src/auth/index.ts +70 -0
  26. package/src/bun/index.ts +130 -0
  27. package/src/bus/bus-event.ts +43 -0
  28. package/src/bus/global.ts +10 -0
  29. package/src/bus/index.ts +105 -0
  30. package/src/cli/bootstrap.ts +17 -0
  31. package/src/cli/cmd/acp.ts +69 -0
  32. package/src/cli/cmd/agent.ts +257 -0
  33. package/src/cli/cmd/auth.ts +132 -0
  34. package/src/cli/cmd/cmd.ts +7 -0
  35. package/src/cli/cmd/debug/agent.ts +28 -0
  36. package/src/cli/cmd/debug/config.ts +15 -0
  37. package/src/cli/cmd/debug/file.ts +91 -0
  38. package/src/cli/cmd/debug/index.ts +45 -0
  39. package/src/cli/cmd/debug/lsp.ts +48 -0
  40. package/src/cli/cmd/debug/ripgrep.ts +83 -0
  41. package/src/cli/cmd/debug/scrap.ts +15 -0
  42. package/src/cli/cmd/debug/skill.ts +15 -0
  43. package/src/cli/cmd/debug/snapshot.ts +48 -0
  44. package/src/cli/cmd/export.ts +88 -0
  45. package/src/cli/cmd/generate.ts +38 -0
  46. package/src/cli/cmd/github.ts +32 -0
  47. package/src/cli/cmd/import.ts +98 -0
  48. package/src/cli/cmd/mcp.ts +670 -0
  49. package/src/cli/cmd/models.ts +42 -0
  50. package/src/cli/cmd/pr.ts +112 -0
  51. package/src/cli/cmd/run.ts +374 -0
  52. package/src/cli/cmd/serve.ts +16 -0
  53. package/src/cli/cmd/session.ts +135 -0
  54. package/src/cli/cmd/stats.ts +402 -0
  55. package/src/cli/cmd/tui/app.tsx +705 -0
  56. package/src/cli/cmd/tui/attach.ts +32 -0
  57. package/src/cli/cmd/tui/component/border.tsx +21 -0
  58. package/src/cli/cmd/tui/component/dialog-agent.tsx +31 -0
  59. package/src/cli/cmd/tui/component/dialog-command.tsx +124 -0
  60. package/src/cli/cmd/tui/component/dialog-mcp.tsx +86 -0
  61. package/src/cli/cmd/tui/component/dialog-model.tsx +232 -0
  62. package/src/cli/cmd/tui/component/dialog-provider.tsx +228 -0
  63. package/src/cli/cmd/tui/component/dialog-session-list.tsx +115 -0
  64. package/src/cli/cmd/tui/component/dialog-session-rename.tsx +31 -0
  65. package/src/cli/cmd/tui/component/dialog-stash.tsx +86 -0
  66. package/src/cli/cmd/tui/component/dialog-status.tsx +162 -0
  67. package/src/cli/cmd/tui/component/dialog-tag.tsx +44 -0
  68. package/src/cli/cmd/tui/component/dialog-theme-list.tsx +50 -0
  69. package/src/cli/cmd/tui/component/did-you-know.tsx +85 -0
  70. package/src/cli/cmd/tui/component/logo.tsx +43 -0
  71. package/src/cli/cmd/tui/component/prompt/autocomplete.tsx +654 -0
  72. package/src/cli/cmd/tui/component/prompt/history.tsx +108 -0
  73. package/src/cli/cmd/tui/component/prompt/index.tsx +1078 -0
  74. package/src/cli/cmd/tui/component/prompt/stash.tsx +101 -0
  75. package/src/cli/cmd/tui/component/textarea-keybindings.ts +73 -0
  76. package/src/cli/cmd/tui/component/tips.ts +92 -0
  77. package/src/cli/cmd/tui/component/todo-item.tsx +32 -0
  78. package/src/cli/cmd/tui/context/args.tsx +14 -0
  79. package/src/cli/cmd/tui/context/directory.ts +13 -0
  80. package/src/cli/cmd/tui/context/exit.tsx +23 -0
  81. package/src/cli/cmd/tui/context/helper.tsx +25 -0
  82. package/src/cli/cmd/tui/context/keybind.tsx +101 -0
  83. package/src/cli/cmd/tui/context/kv.tsx +49 -0
  84. package/src/cli/cmd/tui/context/local.tsx +392 -0
  85. package/src/cli/cmd/tui/context/prompt.tsx +18 -0
  86. package/src/cli/cmd/tui/context/route.tsx +46 -0
  87. package/src/cli/cmd/tui/context/sdk.tsx +75 -0
  88. package/src/cli/cmd/tui/context/sync.tsx +384 -0
  89. package/src/cli/cmd/tui/context/theme/aura.json +69 -0
  90. package/src/cli/cmd/tui/context/theme/ayu.json +80 -0
  91. package/src/cli/cmd/tui/context/theme/catppuccin-frappe.json +233 -0
  92. package/src/cli/cmd/tui/context/theme/catppuccin-macchiato.json +233 -0
  93. package/src/cli/cmd/tui/context/theme/catppuccin.json +112 -0
  94. package/src/cli/cmd/tui/context/theme/chad.json +245 -0
  95. package/src/cli/cmd/tui/context/theme/cobalt2.json +228 -0
  96. package/src/cli/cmd/tui/context/theme/cursor.json +249 -0
  97. package/src/cli/cmd/tui/context/theme/dracula.json +219 -0
  98. package/src/cli/cmd/tui/context/theme/everforest.json +241 -0
  99. package/src/cli/cmd/tui/context/theme/flexoki.json +237 -0
  100. package/src/cli/cmd/tui/context/theme/github.json +233 -0
  101. package/src/cli/cmd/tui/context/theme/gruvbox.json +95 -0
  102. package/src/cli/cmd/tui/context/theme/kanagawa.json +77 -0
  103. package/src/cli/cmd/tui/context/theme/lucent-orng.json +227 -0
  104. package/src/cli/cmd/tui/context/theme/material.json +235 -0
  105. package/src/cli/cmd/tui/context/theme/matrix.json +77 -0
  106. package/src/cli/cmd/tui/context/theme/mercury.json +252 -0
  107. package/src/cli/cmd/tui/context/theme/monokai.json +221 -0
  108. package/src/cli/cmd/tui/context/theme/nightowl.json +221 -0
  109. package/src/cli/cmd/tui/context/theme/nord.json +223 -0
  110. package/src/cli/cmd/tui/context/theme/one-dark.json +84 -0
  111. package/src/cli/cmd/tui/context/theme/orng.json +245 -0
  112. package/src/cli/cmd/tui/context/theme/osaka-jade.json +93 -0
  113. package/src/cli/cmd/tui/context/theme/palenight.json +222 -0
  114. package/src/cli/cmd/tui/context/theme/rosepine.json +234 -0
  115. package/src/cli/cmd/tui/context/theme/solarized.json +223 -0
  116. package/src/cli/cmd/tui/context/theme/synthwave84.json +226 -0
  117. package/src/cli/cmd/tui/context/theme/tokyonight.json +243 -0
  118. package/src/cli/cmd/tui/context/theme/vercel.json +245 -0
  119. package/src/cli/cmd/tui/context/theme/vesper.json +218 -0
  120. package/src/cli/cmd/tui/context/theme/zenburn.json +223 -0
  121. package/src/cli/cmd/tui/context/theme.tsx +1137 -0
  122. package/src/cli/cmd/tui/event.ts +46 -0
  123. package/src/cli/cmd/tui/routes/home.tsx +138 -0
  124. package/src/cli/cmd/tui/routes/session/dialog-fork-from-timeline.tsx +64 -0
  125. package/src/cli/cmd/tui/routes/session/dialog-message.tsx +109 -0
  126. package/src/cli/cmd/tui/routes/session/dialog-subagent.tsx +26 -0
  127. package/src/cli/cmd/tui/routes/session/dialog-timeline.tsx +47 -0
  128. package/src/cli/cmd/tui/routes/session/footer.tsx +88 -0
  129. package/src/cli/cmd/tui/routes/session/header.tsx +125 -0
  130. package/src/cli/cmd/tui/routes/session/index.tsx +1814 -0
  131. package/src/cli/cmd/tui/routes/session/permission.tsx +416 -0
  132. package/src/cli/cmd/tui/routes/session/sidebar.tsx +318 -0
  133. package/src/cli/cmd/tui/spawn.ts +48 -0
  134. package/src/cli/cmd/tui/thread.ts +111 -0
  135. package/src/cli/cmd/tui/ui/dialog-alert.tsx +57 -0
  136. package/src/cli/cmd/tui/ui/dialog-confirm.tsx +83 -0
  137. package/src/cli/cmd/tui/ui/dialog-export-options.tsx +204 -0
  138. package/src/cli/cmd/tui/ui/dialog-help.tsx +38 -0
  139. package/src/cli/cmd/tui/ui/dialog-prompt.tsx +77 -0
  140. package/src/cli/cmd/tui/ui/dialog-select.tsx +345 -0
  141. package/src/cli/cmd/tui/ui/dialog.tsx +171 -0
  142. package/src/cli/cmd/tui/ui/link.tsx +28 -0
  143. package/src/cli/cmd/tui/ui/spinner.ts +368 -0
  144. package/src/cli/cmd/tui/ui/toast.tsx +100 -0
  145. package/src/cli/cmd/tui/util/clipboard.ts +127 -0
  146. package/src/cli/cmd/tui/util/editor.ts +32 -0
  147. package/src/cli/cmd/tui/util/signal.ts +7 -0
  148. package/src/cli/cmd/tui/util/terminal.ts +114 -0
  149. package/src/cli/cmd/tui/util/transcript.ts +98 -0
  150. package/src/cli/cmd/tui/worker.ts +68 -0
  151. package/src/cli/cmd/uninstall.ts +344 -0
  152. package/src/cli/cmd/upgrade.ts +67 -0
  153. package/src/cli/cmd/web.ts +73 -0
  154. package/src/cli/error.ts +56 -0
  155. package/src/cli/network.ts +53 -0
  156. package/src/cli/ui.ts +87 -0
  157. package/src/cli/upgrade.ts +25 -0
  158. package/src/command/index.ts +131 -0
  159. package/src/command/template/initialize.txt +10 -0
  160. package/src/command/template/review.txt +97 -0
  161. package/src/config/config.ts +1124 -0
  162. package/src/config/markdown.ts +41 -0
  163. package/src/env/index.ts +26 -0
  164. package/src/file/ignore.ts +83 -0
  165. package/src/file/index.ts +411 -0
  166. package/src/file/ripgrep.ts +402 -0
  167. package/src/file/time.ts +64 -0
  168. package/src/file/watcher.ts +117 -0
  169. package/src/flag/flag.ts +52 -0
  170. package/src/format/formatter.ts +359 -0
  171. package/src/format/index.ts +137 -0
  172. package/src/global/index.ts +55 -0
  173. package/src/id/id.ts +73 -0
  174. package/src/ide/index.ts +77 -0
  175. package/src/index.ts +159 -0
  176. package/src/installation/index.ts +198 -0
  177. package/src/lsp/client.ts +252 -0
  178. package/src/lsp/index.ts +485 -0
  179. package/src/lsp/language.ts +119 -0
  180. package/src/lsp/server.ts +2023 -0
  181. package/src/mcp/auth.ts +135 -0
  182. package/src/mcp/index.ts +874 -0
  183. package/src/mcp/oauth-callback.ts +200 -0
  184. package/src/mcp/oauth-provider.ts +154 -0
  185. package/src/patch/index.ts +622 -0
  186. package/src/permission/arity.ts +163 -0
  187. package/src/permission/index.ts +210 -0
  188. package/src/permission/next.ts +268 -0
  189. package/src/plugin/index.ts +106 -0
  190. package/src/project/bootstrap.ts +31 -0
  191. package/src/project/instance.ts +78 -0
  192. package/src/project/project.ts +263 -0
  193. package/src/project/state.ts +65 -0
  194. package/src/project/vcs.ts +76 -0
  195. package/src/provider/auth.ts +143 -0
  196. package/src/provider/models-macro.ts +4 -0
  197. package/src/provider/models.ts +77 -0
  198. package/src/provider/provider.ts +516 -0
  199. package/src/provider/transform.ts +114 -0
  200. package/src/pty/index.ts +212 -0
  201. package/src/server/error.ts +36 -0
  202. package/src/server/mdns.ts +57 -0
  203. package/src/server/project.ts +79 -0
  204. package/src/server/server.ts +2866 -0
  205. package/src/server/tui.ts +71 -0
  206. package/src/session/compaction.ts +225 -0
  207. package/src/session/index.ts +469 -0
  208. package/src/session/llm.ts +213 -0
  209. package/src/session/message-v2.ts +742 -0
  210. package/src/session/message.ts +189 -0
  211. package/src/session/processor.ts +402 -0
  212. package/src/session/prompt/anthropic-20250930.txt +166 -0
  213. package/src/session/prompt/anthropic.txt +105 -0
  214. package/src/session/prompt/anthropic_spoof.txt +1 -0
  215. package/src/session/prompt/beast.txt +147 -0
  216. package/src/session/prompt/build-switch.txt +5 -0
  217. package/src/session/prompt/codex.txt +318 -0
  218. package/src/session/prompt/copilot-gpt-5.txt +143 -0
  219. package/src/session/prompt/gemini.txt +155 -0
  220. package/src/session/prompt/max-steps.txt +16 -0
  221. package/src/session/prompt/plan-reminder-anthropic.txt +67 -0
  222. package/src/session/prompt/plan.txt +26 -0
  223. package/src/session/prompt/qwen.txt +109 -0
  224. package/src/session/prompt.ts +1621 -0
  225. package/src/session/retry.ts +90 -0
  226. package/src/session/revert.ts +108 -0
  227. package/src/session/status.ts +76 -0
  228. package/src/session/summary.ts +194 -0
  229. package/src/session/system.ts +108 -0
  230. package/src/session/todo.ts +37 -0
  231. package/src/share/share-next.ts +194 -0
  232. package/src/share/share.ts +23 -0
  233. package/src/shell/shell.ts +67 -0
  234. package/src/skill/index.ts +1 -0
  235. package/src/skill/skill.ts +124 -0
  236. package/src/snapshot/index.ts +197 -0
  237. package/src/storage/storage.ts +226 -0
  238. package/src/tool/bash.ts +262 -0
  239. package/src/tool/bash.txt +116 -0
  240. package/src/tool/batch.ts +175 -0
  241. package/src/tool/batch.txt +24 -0
  242. package/src/tool/codesearch.ts +132 -0
  243. package/src/tool/codesearch.txt +12 -0
  244. package/src/tool/edit.ts +655 -0
  245. package/src/tool/edit.txt +10 -0
  246. package/src/tool/glob.ts +75 -0
  247. package/src/tool/glob.txt +6 -0
  248. package/src/tool/grep.ts +132 -0
  249. package/src/tool/grep.txt +8 -0
  250. package/src/tool/invalid.ts +17 -0
  251. package/src/tool/ls.ts +119 -0
  252. package/src/tool/ls.txt +1 -0
  253. package/src/tool/lsp.ts +94 -0
  254. package/src/tool/lsp.txt +19 -0
  255. package/src/tool/multiedit.ts +46 -0
  256. package/src/tool/multiedit.txt +41 -0
  257. package/src/tool/patch.ts +210 -0
  258. package/src/tool/patch.txt +1 -0
  259. package/src/tool/read.ts +191 -0
  260. package/src/tool/read.txt +12 -0
  261. package/src/tool/registry.ts +137 -0
  262. package/src/tool/skill.ts +77 -0
  263. package/src/tool/task.ts +167 -0
  264. package/src/tool/task.txt +60 -0
  265. package/src/tool/todo.ts +53 -0
  266. package/src/tool/todoread.txt +14 -0
  267. package/src/tool/todowrite.txt +167 -0
  268. package/src/tool/tool.ts +73 -0
  269. package/src/tool/webfetch.ts +182 -0
  270. package/src/tool/webfetch.txt +13 -0
  271. package/src/tool/websearch.ts +144 -0
  272. package/src/tool/websearch.txt +11 -0
  273. package/src/tool/write.ts +84 -0
  274. package/src/tool/write.txt +8 -0
  275. package/src/util/archive.ts +16 -0
  276. package/src/util/color.ts +19 -0
  277. package/src/util/context.ts +25 -0
  278. package/src/util/defer.ts +12 -0
  279. package/src/util/eventloop.ts +20 -0
  280. package/src/util/filesystem.ts +83 -0
  281. package/src/util/fn.ts +11 -0
  282. package/src/util/iife.ts +3 -0
  283. package/src/util/keybind.ts +102 -0
  284. package/src/util/lazy.ts +18 -0
  285. package/src/util/locale.ts +81 -0
  286. package/src/util/lock.ts +98 -0
  287. package/src/util/log.ts +180 -0
  288. package/src/util/queue.ts +32 -0
  289. package/src/util/rpc.ts +42 -0
  290. package/src/util/scrap.ts +10 -0
  291. package/src/util/signal.ts +12 -0
  292. package/src/util/timeout.ts +14 -0
  293. package/src/util/token.ts +7 -0
  294. package/src/util/wildcard.ts +54 -0
  295. package/src/worktree/index.ts +217 -0
  296. package/sst-env.d.ts +9 -0
  297. package/test/agent/agent.test.ts +448 -0
  298. package/test/bun.test.ts +53 -0
  299. package/test/cli/github-action.test.ts +129 -0
  300. package/test/cli/github-remote.test.ts +80 -0
  301. package/test/cli/tui/transcript.test.ts +297 -0
  302. package/test/config/agent-color.test.ts +66 -0
  303. package/test/config/config.test.ts +870 -0
  304. package/test/config/markdown.test.ts +89 -0
  305. package/test/file/ignore.test.ts +10 -0
  306. package/test/file/path-traversal.test.ts +115 -0
  307. package/test/fixture/fixture.ts +45 -0
  308. package/test/fixture/lsp/fake-lsp-server.js +77 -0
  309. package/test/ide/ide.test.ts +82 -0
  310. package/test/keybind.test.ts +421 -0
  311. package/test/lsp/client.test.ts +95 -0
  312. package/test/mcp/headers.test.ts +153 -0
  313. package/test/patch/patch.test.ts +348 -0
  314. package/test/permission/arity.test.ts +33 -0
  315. package/test/permission/next.test.ts +652 -0
  316. package/test/preload.ts +63 -0
  317. package/test/project/project.test.ts +120 -0
  318. package/test/provider/amazon-bedrock.test.ts +236 -0
  319. package/test/provider/provider.test.ts +2127 -0
  320. package/test/provider/transform.test.ts +980 -0
  321. package/test/server/session-select.test.ts +78 -0
  322. package/test/session/compaction.test.ts +251 -0
  323. package/test/session/message-v2.test.ts +570 -0
  324. package/test/session/retry.test.ts +131 -0
  325. package/test/session/revert-compact.test.ts +285 -0
  326. package/test/session/session.test.ts +71 -0
  327. package/test/skill/skill.test.ts +185 -0
  328. package/test/snapshot/snapshot.test.ts +939 -0
  329. package/test/tool/__snapshots__/tool.test.ts.snap +9 -0
  330. package/test/tool/bash.test.ts +232 -0
  331. package/test/tool/grep.test.ts +109 -0
  332. package/test/tool/patch.test.ts +261 -0
  333. package/test/tool/read.test.ts +167 -0
  334. package/test/util/iife.test.ts +36 -0
  335. package/test/util/lazy.test.ts +50 -0
  336. package/test/util/timeout.test.ts +21 -0
  337. package/test/util/wildcard.test.ts +55 -0
  338. package/tsconfig.json +16 -0
@@ -0,0 +1,670 @@
1
+ import { cmd } from "./cmd"
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 { UnauthorizedError } from "@modelcontextprotocol/sdk/client/auth.js"
6
+ import * as prompts from "@clack/prompts"
7
+ import { UI } from "../ui"
8
+ import { MCP } from "../../mcp"
9
+ import { McpAuth } from "../../mcp/auth"
10
+ import { McpOAuthProvider } from "../../mcp/oauth-provider"
11
+ import { Config } from "../../config/config"
12
+ import { Instance } from "../../project/instance"
13
+ import { Installation } from "../../installation"
14
+ import path from "path"
15
+ import { Global } from "../../global"
16
+
17
+ function getAuthStatusIcon(status: MCP.AuthStatus): string {
18
+ switch (status) {
19
+ case "authenticated":
20
+ return "✓"
21
+ case "expired":
22
+ return "⚠"
23
+ case "not_authenticated":
24
+ return "○"
25
+ }
26
+ }
27
+
28
+ function getAuthStatusText(status: MCP.AuthStatus): string {
29
+ switch (status) {
30
+ case "authenticated":
31
+ return "authenticated"
32
+ case "expired":
33
+ return "expired"
34
+ case "not_authenticated":
35
+ return "not authenticated"
36
+ }
37
+ }
38
+
39
+ type McpEntry = NonNullable<Config.Info["mcp"]>[string]
40
+
41
+ type McpConfigured = Config.Mcp
42
+ function isMcpConfigured(config: McpEntry): config is McpConfigured {
43
+ return typeof config === "object" && config !== null && "type" in config
44
+ }
45
+
46
+ type McpRemote = Extract<McpConfigured, { type: "remote" }>
47
+ function isMcpRemote(config: McpEntry): config is McpRemote {
48
+ return isMcpConfigured(config) && config.type === "remote"
49
+ }
50
+
51
+ export const McpCommand = cmd({
52
+ command: "mcp",
53
+ builder: (yargs) =>
54
+ yargs
55
+ .command(McpAddCommand)
56
+ .command(McpListCommand)
57
+ .command(McpAuthCommand)
58
+ .command(McpLogoutCommand)
59
+ .command(McpDebugCommand)
60
+ .demandCommand(),
61
+ async handler() {},
62
+ })
63
+
64
+ export const McpListCommand = cmd({
65
+ command: "list",
66
+ aliases: ["ls"],
67
+ describe: "list MCP servers and their status",
68
+ async handler() {
69
+ await Instance.provide({
70
+ directory: process.cwd(),
71
+ async fn() {
72
+ UI.empty()
73
+ prompts.intro("MCP Servers")
74
+
75
+ const config = await Config.get()
76
+ const mcpServers = config.mcp ?? {}
77
+ const statuses = await MCP.status()
78
+
79
+ const servers = Object.entries(mcpServers).filter((entry): entry is [string, McpConfigured] =>
80
+ isMcpConfigured(entry[1]),
81
+ )
82
+
83
+ if (servers.length === 0) {
84
+ prompts.log.warn("No MCP servers configured")
85
+ prompts.outro("Add servers with: opencode mcp add")
86
+ return
87
+ }
88
+
89
+ for (const [name, serverConfig] of servers) {
90
+ const status = statuses[name]
91
+ const hasOAuth = isMcpRemote(serverConfig) && !!serverConfig.oauth
92
+ const hasStoredTokens = await MCP.hasStoredTokens(name)
93
+
94
+ let statusIcon: string
95
+ let statusText: string
96
+ let hint = ""
97
+
98
+ if (!status) {
99
+ statusIcon = "○"
100
+ statusText = "not initialized"
101
+ } else if (status.status === "connected") {
102
+ statusIcon = "✓"
103
+ statusText = "connected"
104
+ if (hasOAuth && hasStoredTokens) {
105
+ hint = " (OAuth)"
106
+ }
107
+ } else if (status.status === "disabled") {
108
+ statusIcon = "○"
109
+ statusText = "disabled"
110
+ } else if (status.status === "needs_auth") {
111
+ statusIcon = "⚠"
112
+ statusText = "needs authentication"
113
+ } else if (status.status === "needs_client_registration") {
114
+ statusIcon = "✗"
115
+ statusText = "needs client registration"
116
+ hint = "\n " + status.error
117
+ } else {
118
+ statusIcon = "✗"
119
+ statusText = "failed"
120
+ hint = "\n " + status.error
121
+ }
122
+
123
+ const typeHint = serverConfig.type === "remote" ? serverConfig.url : serverConfig.command.join(" ")
124
+ prompts.log.info(
125
+ `${statusIcon} ${name} ${UI.Style.TEXT_DIM}${statusText}${hint}\n ${UI.Style.TEXT_DIM}${typeHint}`,
126
+ )
127
+ }
128
+
129
+ prompts.outro(`${servers.length} server(s)`)
130
+ },
131
+ })
132
+ },
133
+ })
134
+
135
+ export const McpAuthCommand = cmd({
136
+ command: "auth [name]",
137
+ describe: "authenticate with an OAuth-enabled MCP server",
138
+ builder: (yargs) =>
139
+ yargs
140
+ .positional("name", {
141
+ describe: "name of the MCP server",
142
+ type: "string",
143
+ })
144
+ .command(McpAuthListCommand),
145
+ async handler(args) {
146
+ await Instance.provide({
147
+ directory: process.cwd(),
148
+ async fn() {
149
+ UI.empty()
150
+ prompts.intro("MCP OAuth Authentication")
151
+
152
+ const config = await Config.get()
153
+ const mcpServers = config.mcp ?? {}
154
+
155
+ // Get OAuth-capable servers (remote servers with oauth not explicitly disabled)
156
+ const oauthServers = Object.entries(mcpServers).filter(
157
+ (entry): entry is [string, McpRemote] => isMcpRemote(entry[1]) && entry[1].oauth !== false,
158
+ )
159
+
160
+ if (oauthServers.length === 0) {
161
+ prompts.log.warn("No OAuth-capable MCP servers configured")
162
+ prompts.log.info("Remote MCP servers support OAuth by default. Add a remote server in chad-code.json:")
163
+ prompts.log.info(`
164
+ "mcp": {
165
+ "my-server": {
166
+ "type": "remote",
167
+ "url": "https://example.com/mcp"
168
+ }
169
+ }`)
170
+ prompts.outro("Done")
171
+ return
172
+ }
173
+
174
+ let serverName = args.name
175
+ if (!serverName) {
176
+ // Build options with auth status
177
+ const options = await Promise.all(
178
+ oauthServers.map(async ([name, cfg]) => {
179
+ const authStatus = await MCP.getAuthStatus(name)
180
+ const icon = getAuthStatusIcon(authStatus)
181
+ const statusText = getAuthStatusText(authStatus)
182
+ const url = cfg.url
183
+ return {
184
+ label: `${icon} ${name} (${statusText})`,
185
+ value: name,
186
+ hint: url,
187
+ }
188
+ }),
189
+ )
190
+
191
+ const selected = await prompts.select({
192
+ message: "Select MCP server to authenticate",
193
+ options,
194
+ })
195
+ if (prompts.isCancel(selected)) throw new UI.CancelledError()
196
+ serverName = selected
197
+ }
198
+
199
+ const serverConfig = mcpServers[serverName]
200
+ if (!serverConfig) {
201
+ prompts.log.error(`MCP server not found: ${serverName}`)
202
+ prompts.outro("Done")
203
+ return
204
+ }
205
+
206
+ if (!isMcpRemote(serverConfig) || serverConfig.oauth === false) {
207
+ prompts.log.error(`MCP server ${serverName} is not an OAuth-capable remote server`)
208
+ prompts.outro("Done")
209
+ return
210
+ }
211
+
212
+ // Check if already authenticated
213
+ const authStatus = await MCP.getAuthStatus(serverName)
214
+ if (authStatus === "authenticated") {
215
+ const confirm = await prompts.confirm({
216
+ message: `${serverName} already has valid credentials. Re-authenticate?`,
217
+ })
218
+ if (prompts.isCancel(confirm) || !confirm) {
219
+ prompts.outro("Cancelled")
220
+ return
221
+ }
222
+ } else if (authStatus === "expired") {
223
+ prompts.log.warn(`${serverName} has expired credentials. Re-authenticating...`)
224
+ }
225
+
226
+ const spinner = prompts.spinner()
227
+ spinner.start("Starting OAuth flow...")
228
+
229
+ try {
230
+ const status = await MCP.authenticate(serverName)
231
+
232
+ if (status.status === "connected") {
233
+ spinner.stop("Authentication successful!")
234
+ } else if (status.status === "needs_client_registration") {
235
+ spinner.stop("Authentication failed", 1)
236
+ prompts.log.error(status.error)
237
+ prompts.log.info("Add clientId to your MCP server config:")
238
+ prompts.log.info(`
239
+ "mcp": {
240
+ "${serverName}": {
241
+ "type": "remote",
242
+ "url": "${serverConfig.url}",
243
+ "oauth": {
244
+ "clientId": "your-client-id",
245
+ "clientSecret": "your-client-secret"
246
+ }
247
+ }
248
+ }`)
249
+ } else if (status.status === "failed") {
250
+ spinner.stop("Authentication failed", 1)
251
+ prompts.log.error(status.error)
252
+ } else {
253
+ spinner.stop("Unexpected status: " + status.status, 1)
254
+ }
255
+ } catch (error) {
256
+ spinner.stop("Authentication failed", 1)
257
+ prompts.log.error(error instanceof Error ? error.message : String(error))
258
+ }
259
+
260
+ prompts.outro("Done")
261
+ },
262
+ })
263
+ },
264
+ })
265
+
266
+ export const McpAuthListCommand = cmd({
267
+ command: "list",
268
+ aliases: ["ls"],
269
+ describe: "list OAuth-capable MCP servers and their auth status",
270
+ async handler() {
271
+ await Instance.provide({
272
+ directory: process.cwd(),
273
+ async fn() {
274
+ UI.empty()
275
+ prompts.intro("MCP OAuth Status")
276
+
277
+ const config = await Config.get()
278
+ const mcpServers = config.mcp ?? {}
279
+
280
+ // Get OAuth-capable servers
281
+ const oauthServers = Object.entries(mcpServers).filter(
282
+ (entry): entry is [string, McpRemote] => isMcpRemote(entry[1]) && entry[1].oauth !== false,
283
+ )
284
+
285
+ if (oauthServers.length === 0) {
286
+ prompts.log.warn("No OAuth-capable MCP servers configured")
287
+ prompts.outro("Done")
288
+ return
289
+ }
290
+
291
+ for (const [name, serverConfig] of oauthServers) {
292
+ const authStatus = await MCP.getAuthStatus(name)
293
+ const icon = getAuthStatusIcon(authStatus)
294
+ const statusText = getAuthStatusText(authStatus)
295
+ const url = serverConfig.url
296
+
297
+ prompts.log.info(`${icon} ${name} ${UI.Style.TEXT_DIM}${statusText}\n ${UI.Style.TEXT_DIM}${url}`)
298
+ }
299
+
300
+ prompts.outro(`${oauthServers.length} OAuth-capable server(s)`)
301
+ },
302
+ })
303
+ },
304
+ })
305
+
306
+ export const McpLogoutCommand = cmd({
307
+ command: "logout [name]",
308
+ describe: "remove OAuth credentials for an MCP server",
309
+ builder: (yargs) =>
310
+ yargs.positional("name", {
311
+ describe: "name of the MCP server",
312
+ type: "string",
313
+ }),
314
+ async handler(args) {
315
+ await Instance.provide({
316
+ directory: process.cwd(),
317
+ async fn() {
318
+ UI.empty()
319
+ prompts.intro("MCP OAuth Logout")
320
+
321
+ const authPath = path.join(Global.Path.data, "mcp-auth.json")
322
+ const credentials = await McpAuth.all()
323
+ const serverNames = Object.keys(credentials)
324
+
325
+ if (serverNames.length === 0) {
326
+ prompts.log.warn("No MCP OAuth credentials stored")
327
+ prompts.outro("Done")
328
+ return
329
+ }
330
+
331
+ let serverName = args.name
332
+ if (!serverName) {
333
+ const selected = await prompts.select({
334
+ message: "Select MCP server to logout",
335
+ options: serverNames.map((name) => {
336
+ const entry = credentials[name]
337
+ const hasTokens = !!entry.tokens
338
+ const hasClient = !!entry.clientInfo
339
+ let hint = ""
340
+ if (hasTokens && hasClient) hint = "tokens + client"
341
+ else if (hasTokens) hint = "tokens"
342
+ else if (hasClient) hint = "client registration"
343
+ return {
344
+ label: name,
345
+ value: name,
346
+ hint,
347
+ }
348
+ }),
349
+ })
350
+ if (prompts.isCancel(selected)) throw new UI.CancelledError()
351
+ serverName = selected
352
+ }
353
+
354
+ if (!credentials[serverName]) {
355
+ prompts.log.error(`No credentials found for: ${serverName}`)
356
+ prompts.outro("Done")
357
+ return
358
+ }
359
+
360
+ await MCP.removeAuth(serverName)
361
+ prompts.log.success(`Removed OAuth credentials for ${serverName}`)
362
+ prompts.outro("Done")
363
+ },
364
+ })
365
+ },
366
+ })
367
+
368
+ export const McpAddCommand = cmd({
369
+ command: "add",
370
+ describe: "add an MCP server",
371
+ async handler() {
372
+ UI.empty()
373
+ prompts.intro("Add MCP server")
374
+
375
+ const name = await prompts.text({
376
+ message: "Enter MCP server name",
377
+ validate: (x) => (x && x.length > 0 ? undefined : "Required"),
378
+ })
379
+ if (prompts.isCancel(name)) throw new UI.CancelledError()
380
+
381
+ const type = await prompts.select({
382
+ message: "Select MCP server type",
383
+ options: [
384
+ {
385
+ label: "Local",
386
+ value: "local",
387
+ hint: "Run a local command",
388
+ },
389
+ {
390
+ label: "Remote",
391
+ value: "remote",
392
+ hint: "Connect to a remote URL",
393
+ },
394
+ ],
395
+ })
396
+ if (prompts.isCancel(type)) throw new UI.CancelledError()
397
+
398
+ if (type === "local") {
399
+ const command = await prompts.text({
400
+ message: "Enter command to run",
401
+ placeholder: "e.g., opencode x @modelcontextprotocol/server-filesystem",
402
+ validate: (x) => (x && x.length > 0 ? undefined : "Required"),
403
+ })
404
+ if (prompts.isCancel(command)) throw new UI.CancelledError()
405
+
406
+ prompts.log.info(`Local MCP server "${name}" configured with command: ${command}`)
407
+ prompts.outro("MCP server added successfully")
408
+ return
409
+ }
410
+
411
+ if (type === "remote") {
412
+ const url = await prompts.text({
413
+ message: "Enter MCP server URL",
414
+ placeholder: "e.g., https://example.com/mcp",
415
+ validate: (x) => {
416
+ if (!x) return "Required"
417
+ if (x.length === 0) return "Required"
418
+ const isValid = URL.canParse(x)
419
+ return isValid ? undefined : "Invalid URL"
420
+ },
421
+ })
422
+ if (prompts.isCancel(url)) throw new UI.CancelledError()
423
+
424
+ const useOAuth = await prompts.confirm({
425
+ message: "Does this server require OAuth authentication?",
426
+ initialValue: false,
427
+ })
428
+ if (prompts.isCancel(useOAuth)) throw new UI.CancelledError()
429
+
430
+ if (useOAuth) {
431
+ const hasClientId = await prompts.confirm({
432
+ message: "Do you have a pre-registered client ID?",
433
+ initialValue: false,
434
+ })
435
+ if (prompts.isCancel(hasClientId)) throw new UI.CancelledError()
436
+
437
+ if (hasClientId) {
438
+ const clientId = await prompts.text({
439
+ message: "Enter client ID",
440
+ validate: (x) => (x && x.length > 0 ? undefined : "Required"),
441
+ })
442
+ if (prompts.isCancel(clientId)) throw new UI.CancelledError()
443
+
444
+ const hasSecret = await prompts.confirm({
445
+ message: "Do you have a client secret?",
446
+ initialValue: false,
447
+ })
448
+ if (prompts.isCancel(hasSecret)) throw new UI.CancelledError()
449
+
450
+ let clientSecret: string | undefined
451
+ if (hasSecret) {
452
+ const secret = await prompts.password({
453
+ message: "Enter client secret",
454
+ })
455
+ if (prompts.isCancel(secret)) throw new UI.CancelledError()
456
+ clientSecret = secret
457
+ }
458
+
459
+ prompts.log.info(`Remote MCP server "${name}" configured with OAuth (client ID: ${clientId})`)
460
+ prompts.log.info("Add this to your chad-code.json:")
461
+ prompts.log.info(`
462
+ "mcp": {
463
+ "${name}": {
464
+ "type": "remote",
465
+ "url": "${url}",
466
+ "oauth": {
467
+ "clientId": "${clientId}"${clientSecret ? `,\n "clientSecret": "${clientSecret}"` : ""}
468
+ }
469
+ }
470
+ }`)
471
+ } else {
472
+ prompts.log.info(`Remote MCP server "${name}" configured with OAuth (dynamic registration)`)
473
+ prompts.log.info("Add this to your chad-code.json:")
474
+ prompts.log.info(`
475
+ "mcp": {
476
+ "${name}": {
477
+ "type": "remote",
478
+ "url": "${url}",
479
+ "oauth": {}
480
+ }
481
+ }`)
482
+ }
483
+ } else {
484
+ const client = new Client({
485
+ name: "opencode",
486
+ version: "1.0.0",
487
+ })
488
+ const transport = new StreamableHTTPClientTransport(new URL(url))
489
+ await client.connect(transport)
490
+ prompts.log.info(`Remote MCP server "${name}" configured with URL: ${url}`)
491
+ }
492
+ }
493
+
494
+ prompts.outro("MCP server added successfully")
495
+ },
496
+ })
497
+
498
+ export const McpDebugCommand = cmd({
499
+ command: "debug <name>",
500
+ describe: "debug OAuth connection for an MCP server",
501
+ builder: (yargs) =>
502
+ yargs.positional("name", {
503
+ describe: "name of the MCP server",
504
+ type: "string",
505
+ demandOption: true,
506
+ }),
507
+ async handler(args) {
508
+ await Instance.provide({
509
+ directory: process.cwd(),
510
+ async fn() {
511
+ UI.empty()
512
+ prompts.intro("MCP OAuth Debug")
513
+
514
+ const config = await Config.get()
515
+ const mcpServers = config.mcp ?? {}
516
+ const serverName = args.name
517
+
518
+ const serverConfig = mcpServers[serverName]
519
+ if (!serverConfig) {
520
+ prompts.log.error(`MCP server not found: ${serverName}`)
521
+ prompts.outro("Done")
522
+ return
523
+ }
524
+
525
+ if (!isMcpRemote(serverConfig)) {
526
+ prompts.log.error(`MCP server ${serverName} is not a remote server`)
527
+ prompts.outro("Done")
528
+ return
529
+ }
530
+
531
+ if (serverConfig.oauth === false) {
532
+ prompts.log.warn(`MCP server ${serverName} has OAuth explicitly disabled`)
533
+ prompts.outro("Done")
534
+ return
535
+ }
536
+
537
+ prompts.log.info(`Server: ${serverName}`)
538
+ prompts.log.info(`URL: ${serverConfig.url}`)
539
+
540
+ // Check stored auth status
541
+ const authStatus = await MCP.getAuthStatus(serverName)
542
+ prompts.log.info(`Auth status: ${getAuthStatusIcon(authStatus)} ${getAuthStatusText(authStatus)}`)
543
+
544
+ const entry = await McpAuth.get(serverName)
545
+ if (entry?.tokens) {
546
+ prompts.log.info(` Access token: ${entry.tokens.accessToken.substring(0, 20)}...`)
547
+ if (entry.tokens.expiresAt) {
548
+ const expiresDate = new Date(entry.tokens.expiresAt * 1000)
549
+ const isExpired = entry.tokens.expiresAt < Date.now() / 1000
550
+ prompts.log.info(` Expires: ${expiresDate.toISOString()} ${isExpired ? "(EXPIRED)" : ""}`)
551
+ }
552
+ if (entry.tokens.refreshToken) {
553
+ prompts.log.info(` Refresh token: present`)
554
+ }
555
+ }
556
+ if (entry?.clientInfo) {
557
+ prompts.log.info(` Client ID: ${entry.clientInfo.clientId}`)
558
+ if (entry.clientInfo.clientSecretExpiresAt) {
559
+ const expiresDate = new Date(entry.clientInfo.clientSecretExpiresAt * 1000)
560
+ prompts.log.info(` Client secret expires: ${expiresDate.toISOString()}`)
561
+ }
562
+ }
563
+
564
+ const spinner = prompts.spinner()
565
+ spinner.start("Testing connection...")
566
+
567
+ // Test basic HTTP connectivity first
568
+ try {
569
+ const response = await fetch(serverConfig.url, {
570
+ method: "POST",
571
+ headers: {
572
+ "Content-Type": "application/json",
573
+ Accept: "application/json, text/event-stream",
574
+ },
575
+ body: JSON.stringify({
576
+ jsonrpc: "2.0",
577
+ method: "initialize",
578
+ params: {
579
+ protocolVersion: "2024-11-05",
580
+ capabilities: {},
581
+ clientInfo: { name: "opencode-debug", version: Installation.VERSION },
582
+ },
583
+ id: 1,
584
+ }),
585
+ })
586
+
587
+ spinner.stop(`HTTP response: ${response.status} ${response.statusText}`)
588
+
589
+ // Check for WWW-Authenticate header
590
+ const wwwAuth = response.headers.get("www-authenticate")
591
+ if (wwwAuth) {
592
+ prompts.log.info(`WWW-Authenticate: ${wwwAuth}`)
593
+ }
594
+
595
+ if (response.status === 401) {
596
+ prompts.log.warn("Server returned 401 Unauthorized")
597
+
598
+ // Try to discover OAuth metadata
599
+ const oauthConfig = typeof serverConfig.oauth === "object" ? serverConfig.oauth : undefined
600
+ const authProvider = new McpOAuthProvider(
601
+ serverName,
602
+ serverConfig.url,
603
+ {
604
+ clientId: oauthConfig?.clientId,
605
+ clientSecret: oauthConfig?.clientSecret,
606
+ scope: oauthConfig?.scope,
607
+ },
608
+ {
609
+ onRedirect: async () => {},
610
+ },
611
+ )
612
+
613
+ prompts.log.info("Testing OAuth flow (without completing authorization)...")
614
+
615
+ // Try creating transport with auth provider to trigger discovery
616
+ const transport = new StreamableHTTPClientTransport(new URL(serverConfig.url), {
617
+ authProvider,
618
+ })
619
+
620
+ try {
621
+ const client = new Client({
622
+ name: "opencode-debug",
623
+ version: Installation.VERSION,
624
+ })
625
+ await client.connect(transport)
626
+ prompts.log.success("Connection successful (already authenticated)")
627
+ await client.close()
628
+ } catch (error) {
629
+ if (error instanceof UnauthorizedError) {
630
+ prompts.log.info(`OAuth flow triggered: ${error.message}`)
631
+
632
+ // Check if dynamic registration would be attempted
633
+ const clientInfo = await authProvider.clientInformation()
634
+ if (clientInfo) {
635
+ prompts.log.info(`Client ID available: ${clientInfo.client_id}`)
636
+ } else {
637
+ prompts.log.info("No client ID - dynamic registration will be attempted")
638
+ }
639
+ } else {
640
+ prompts.log.error(`Connection error: ${error instanceof Error ? error.message : String(error)}`)
641
+ }
642
+ }
643
+ } else if (response.status >= 200 && response.status < 300) {
644
+ prompts.log.success("Server responded successfully (no auth required or already authenticated)")
645
+ const body = await response.text()
646
+ try {
647
+ const json = JSON.parse(body)
648
+ if (json.result?.serverInfo) {
649
+ prompts.log.info(`Server info: ${JSON.stringify(json.result.serverInfo)}`)
650
+ }
651
+ } catch {
652
+ // Not JSON, ignore
653
+ }
654
+ } else {
655
+ prompts.log.warn(`Unexpected status: ${response.status}`)
656
+ const body = await response.text().catch(() => "")
657
+ if (body) {
658
+ prompts.log.info(`Response body: ${body.substring(0, 500)}`)
659
+ }
660
+ }
661
+ } catch (error) {
662
+ spinner.stop("Connection failed", 1)
663
+ prompts.log.error(`Error: ${error instanceof Error ? error.message : String(error)}`)
664
+ }
665
+
666
+ prompts.outro("Debug complete")
667
+ },
668
+ })
669
+ },
670
+ })
@@ -0,0 +1,42 @@
1
+ import type { Argv } from "yargs"
2
+ import { Instance } from "../../project/instance"
3
+ import { Provider } from "../../provider/provider"
4
+ import { cmd } from "./cmd"
5
+ import { UI } from "../ui"
6
+ import { EOL } from "os"
7
+
8
+ export const ModelsCommand = cmd({
9
+ command: "models",
10
+ describe: "list available Chad models",
11
+ builder: (yargs: Argv) => {
12
+ return yargs.option("verbose", {
13
+ describe: "use more verbose model output (includes metadata like costs)",
14
+ type: "boolean",
15
+ })
16
+ },
17
+ handler: async (args) => {
18
+ await Instance.provide({
19
+ directory: process.cwd(),
20
+ async fn() {
21
+ const providers = await Provider.list()
22
+
23
+ if (Object.keys(providers).length === 0) {
24
+ UI.error("No providers available. Please set CORETHINK_API_KEY environment variable.")
25
+ return
26
+ }
27
+
28
+ for (const [providerID, provider] of Object.entries(providers)) {
29
+ const sortedModels = Object.entries(provider.models).sort(([a], [b]) => a.localeCompare(b))
30
+ for (const [modelID, model] of sortedModels) {
31
+ process.stdout.write(`${providerID}/${modelID}`)
32
+ process.stdout.write(EOL)
33
+ if (args.verbose) {
34
+ process.stdout.write(JSON.stringify(model, null, 2))
35
+ process.stdout.write(EOL)
36
+ }
37
+ }
38
+ }
39
+ },
40
+ })
41
+ },
42
+ })