config.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852
  1. import { Log } from "../util/log"
  2. import path from "path"
  3. import os from "os"
  4. import z from "zod"
  5. import { Filesystem } from "../util/filesystem"
  6. import { ModelsDev } from "../provider/models"
  7. import { mergeDeep, pipe } from "remeda"
  8. import { Global } from "../global"
  9. import fs from "fs/promises"
  10. import { lazy } from "../util/lazy"
  11. import { NamedError } from "@opencode-ai/util/error"
  12. import { Flag } from "../flag/flag"
  13. import { Auth } from "../auth"
  14. import { type ParseError as JsoncParseError, parse as parseJsonc, printParseErrorCode } from "jsonc-parser"
  15. import { Instance } from "../project/instance"
  16. import { LSPServer } from "../lsp/server"
  17. import { BunProc } from "@/bun"
  18. import { Installation } from "@/installation"
  19. import { ConfigMarkdown } from "./markdown"
  20. export namespace Config {
  21. const log = Log.create({ service: "config" })
  22. // Custom merge function that concatenates plugin arrays instead of replacing them
  23. function mergeConfigWithPlugins(target: Info, source: Info): Info {
  24. const merged = mergeDeep(target, source)
  25. // If both configs have plugin arrays, concatenate them instead of replacing
  26. if (target.plugin && source.plugin) {
  27. const pluginSet = new Set([...target.plugin, ...source.plugin])
  28. merged.plugin = Array.from(pluginSet)
  29. }
  30. return merged
  31. }
  32. export const state = Instance.state(async () => {
  33. const auth = await Auth.all()
  34. let result = await global()
  35. // Override with custom config if provided
  36. if (Flag.OPENCODE_CONFIG) {
  37. result = mergeConfigWithPlugins(result, await loadFile(Flag.OPENCODE_CONFIG))
  38. log.debug("loaded custom config", { path: Flag.OPENCODE_CONFIG })
  39. }
  40. for (const file of ["opencode.jsonc", "opencode.json"]) {
  41. const found = await Filesystem.findUp(file, Instance.directory, Instance.worktree)
  42. for (const resolved of found.toReversed()) {
  43. result = mergeConfigWithPlugins(result, await loadFile(resolved))
  44. }
  45. }
  46. if (Flag.OPENCODE_CONFIG_CONTENT) {
  47. result = mergeConfigWithPlugins(result, JSON.parse(Flag.OPENCODE_CONFIG_CONTENT))
  48. log.debug("loaded custom config from OPENCODE_CONFIG_CONTENT")
  49. }
  50. for (const [key, value] of Object.entries(auth)) {
  51. if (value.type === "wellknown") {
  52. process.env[value.key] = value.token
  53. const wellknown = (await fetch(`${key}/.well-known/opencode`).then((x) => x.json())) as any
  54. result = mergeConfigWithPlugins(result, await load(JSON.stringify(wellknown.config ?? {}), process.cwd()))
  55. }
  56. }
  57. result.agent = result.agent || {}
  58. result.mode = result.mode || {}
  59. result.plugin = result.plugin || []
  60. const directories = [
  61. Global.Path.config,
  62. ...(await Array.fromAsync(
  63. Filesystem.up({
  64. targets: [".opencode"],
  65. start: Instance.directory,
  66. stop: Instance.worktree,
  67. }),
  68. )),
  69. ]
  70. if (Flag.OPENCODE_CONFIG_DIR) {
  71. directories.push(Flag.OPENCODE_CONFIG_DIR)
  72. log.debug("loading config from OPENCODE_CONFIG_DIR", { path: Flag.OPENCODE_CONFIG_DIR })
  73. }
  74. const promises: Promise<void>[] = []
  75. for (const dir of directories) {
  76. await assertValid(dir)
  77. if (dir.endsWith(".opencode") || dir === Flag.OPENCODE_CONFIG_DIR) {
  78. for (const file of ["opencode.jsonc", "opencode.json"]) {
  79. log.debug(`loading config from ${path.join(dir, file)}`)
  80. result = mergeConfigWithPlugins(result, await loadFile(path.join(dir, file)))
  81. // to satisy the type checker
  82. result.agent ??= {}
  83. result.mode ??= {}
  84. result.plugin ??= []
  85. }
  86. }
  87. promises.push(installDependencies(dir))
  88. result.command = mergeDeep(result.command ?? {}, await loadCommand(dir))
  89. result.agent = mergeDeep(result.agent, await loadAgent(dir))
  90. result.agent = mergeDeep(result.agent, await loadMode(dir))
  91. result.plugin.push(...(await loadPlugin(dir)))
  92. }
  93. await Promise.allSettled(promises)
  94. // Migrate deprecated mode field to agent field
  95. for (const [name, mode] of Object.entries(result.mode)) {
  96. result.agent = mergeDeep(result.agent ?? {}, {
  97. [name]: {
  98. ...mode,
  99. mode: "primary" as const,
  100. },
  101. })
  102. }
  103. if (Flag.OPENCODE_PERMISSION) {
  104. result.permission = mergeDeep(result.permission ?? {}, JSON.parse(Flag.OPENCODE_PERMISSION))
  105. }
  106. if (!result.username) result.username = os.userInfo().username
  107. // Handle migration from autoshare to share field
  108. if (result.autoshare === true && !result.share) {
  109. result.share = "auto"
  110. }
  111. // Handle migration from autoshare to share field
  112. if (result.autoshare === true && !result.share) {
  113. result.share = "auto"
  114. }
  115. if (!result.keybinds) result.keybinds = Info.shape.keybinds.parse({})
  116. return {
  117. config: result,
  118. directories,
  119. }
  120. })
  121. const INVALID_DIRS = new Bun.Glob(`{${["agents", "commands", "plugins", "tools"].join(",")}}/`)
  122. async function assertValid(dir: string) {
  123. const invalid = await Array.fromAsync(
  124. INVALID_DIRS.scan({
  125. onlyFiles: false,
  126. cwd: dir,
  127. }),
  128. )
  129. for (const item of invalid) {
  130. throw new ConfigDirectoryTypoError({
  131. path: dir,
  132. dir: item,
  133. suggestion: item.substring(0, item.length - 1),
  134. })
  135. }
  136. }
  137. async function installDependencies(dir: string) {
  138. if (Installation.isLocal()) return
  139. const pkg = path.join(dir, "package.json")
  140. if (!(await Bun.file(pkg).exists())) {
  141. await Bun.write(pkg, "{}")
  142. }
  143. const gitignore = path.join(dir, ".gitignore")
  144. const hasGitIgnore = await Bun.file(gitignore).exists()
  145. if (!hasGitIgnore) await Bun.write(gitignore, ["node_modules", "package.json", "bun.lock", ".gitignore"].join("\n"))
  146. await BunProc.run(
  147. ["add", "@opencode-ai/plugin@" + (Installation.isLocal() ? "latest" : Installation.VERSION), "--exact"],
  148. {
  149. cwd: dir,
  150. },
  151. ).catch(() => {})
  152. }
  153. const COMMAND_GLOB = new Bun.Glob("command/**/*.md")
  154. async function loadCommand(dir: string) {
  155. const result: Record<string, Command> = {}
  156. for await (const item of COMMAND_GLOB.scan({
  157. absolute: true,
  158. followSymlinks: true,
  159. dot: true,
  160. cwd: dir,
  161. })) {
  162. const md = await ConfigMarkdown.parse(item)
  163. if (!md.data) continue
  164. const name = (() => {
  165. const patterns = ["/.opencode/command/", "/command/"]
  166. const pattern = patterns.find((p) => item.includes(p))
  167. if (pattern) {
  168. const index = item.indexOf(pattern)
  169. return item.slice(index + pattern.length, -3)
  170. }
  171. return path.basename(item, ".md")
  172. })()
  173. const config = {
  174. name,
  175. ...md.data,
  176. template: md.content.trim(),
  177. }
  178. const parsed = Command.safeParse(config)
  179. if (parsed.success) {
  180. result[config.name] = parsed.data
  181. continue
  182. }
  183. throw new InvalidError({ path: item }, { cause: parsed.error })
  184. }
  185. return result
  186. }
  187. const AGENT_GLOB = new Bun.Glob("agent/**/*.md")
  188. async function loadAgent(dir: string) {
  189. const result: Record<string, Agent> = {}
  190. for await (const item of AGENT_GLOB.scan({
  191. absolute: true,
  192. followSymlinks: true,
  193. dot: true,
  194. cwd: dir,
  195. })) {
  196. const md = await ConfigMarkdown.parse(item)
  197. if (!md.data) continue
  198. // Extract relative path from agent folder for nested agents
  199. let agentName = path.basename(item, ".md")
  200. const agentFolderPath = item.includes("/.opencode/agent/")
  201. ? item.split("/.opencode/agent/")[1]
  202. : item.includes("/agent/")
  203. ? item.split("/agent/")[1]
  204. : agentName + ".md"
  205. // If agent is in a subfolder, include folder path in name
  206. if (agentFolderPath.includes("/")) {
  207. const relativePath = agentFolderPath.replace(".md", "")
  208. const pathParts = relativePath.split("/")
  209. agentName = pathParts.slice(0, -1).join("/") + "/" + pathParts[pathParts.length - 1]
  210. }
  211. const config = {
  212. name: agentName,
  213. ...md.data,
  214. prompt: md.content.trim(),
  215. }
  216. const parsed = Agent.safeParse(config)
  217. if (parsed.success) {
  218. result[config.name] = parsed.data
  219. continue
  220. }
  221. throw new InvalidError({ path: item }, { cause: parsed.error })
  222. }
  223. return result
  224. }
  225. const MODE_GLOB = new Bun.Glob("mode/*.md")
  226. async function loadMode(dir: string) {
  227. const result: Record<string, Agent> = {}
  228. for await (const item of MODE_GLOB.scan({
  229. absolute: true,
  230. followSymlinks: true,
  231. dot: true,
  232. cwd: dir,
  233. })) {
  234. const md = await ConfigMarkdown.parse(item)
  235. if (!md.data) continue
  236. const config = {
  237. name: path.basename(item, ".md"),
  238. ...md.data,
  239. prompt: md.content.trim(),
  240. }
  241. const parsed = Agent.safeParse(config)
  242. if (parsed.success) {
  243. result[config.name] = {
  244. ...parsed.data,
  245. mode: "primary" as const,
  246. }
  247. continue
  248. }
  249. }
  250. return result
  251. }
  252. const PLUGIN_GLOB = new Bun.Glob("plugin/*.{ts,js}")
  253. async function loadPlugin(dir: string) {
  254. const plugins: string[] = []
  255. for await (const item of PLUGIN_GLOB.scan({
  256. absolute: true,
  257. followSymlinks: true,
  258. dot: true,
  259. cwd: dir,
  260. })) {
  261. plugins.push("file://" + item)
  262. }
  263. return plugins
  264. }
  265. export const McpLocal = z
  266. .object({
  267. type: z.literal("local").describe("Type of MCP server connection"),
  268. command: z.string().array().describe("Command and arguments to run the MCP server"),
  269. environment: z
  270. .record(z.string(), z.string())
  271. .optional()
  272. .describe("Environment variables to set when running the MCP server"),
  273. enabled: z.boolean().optional().describe("Enable or disable the MCP server on startup"),
  274. timeout: z
  275. .number()
  276. .int()
  277. .positive()
  278. .optional()
  279. .describe(
  280. "Timeout in ms for fetching tools from the MCP server. Defaults to 5000 (5 seconds) if not specified.",
  281. ),
  282. })
  283. .strict()
  284. .meta({
  285. ref: "McpLocalConfig",
  286. })
  287. export const McpRemote = z
  288. .object({
  289. type: z.literal("remote").describe("Type of MCP server connection"),
  290. url: z.string().describe("URL of the remote MCP server"),
  291. enabled: z.boolean().optional().describe("Enable or disable the MCP server on startup"),
  292. headers: z.record(z.string(), z.string()).optional().describe("Headers to send with the request"),
  293. timeout: z
  294. .number()
  295. .int()
  296. .positive()
  297. .optional()
  298. .describe(
  299. "Timeout in ms for fetching tools from the MCP server. Defaults to 5000 (5 seconds) if not specified.",
  300. ),
  301. })
  302. .strict()
  303. .meta({
  304. ref: "McpRemoteConfig",
  305. })
  306. export const Mcp = z.discriminatedUnion("type", [McpLocal, McpRemote])
  307. export type Mcp = z.infer<typeof Mcp>
  308. export const Permission = z.enum(["ask", "allow", "deny"])
  309. export type Permission = z.infer<typeof Permission>
  310. export const Command = z.object({
  311. template: z.string(),
  312. description: z.string().optional(),
  313. agent: z.string().optional(),
  314. model: z.string().optional(),
  315. subtask: z.boolean().optional(),
  316. })
  317. export type Command = z.infer<typeof Command>
  318. export const Agent = z
  319. .object({
  320. model: z.string().optional(),
  321. temperature: z.number().optional(),
  322. top_p: z.number().optional(),
  323. prompt: z.string().optional(),
  324. tools: z.record(z.string(), z.boolean()).optional(),
  325. disable: z.boolean().optional(),
  326. description: z.string().optional().describe("Description of when to use the agent"),
  327. mode: z.enum(["subagent", "primary", "all"]).optional(),
  328. color: z
  329. .string()
  330. .regex(/^#[0-9a-fA-F]{6}$/, "Invalid hex color format")
  331. .optional()
  332. .describe("Hex color code for the agent (e.g., #FF5733)"),
  333. permission: z
  334. .object({
  335. edit: Permission.optional(),
  336. bash: z.union([Permission, z.record(z.string(), Permission)]).optional(),
  337. webfetch: Permission.optional(),
  338. doom_loop: Permission.optional(),
  339. external_directory: Permission.optional(),
  340. })
  341. .optional(),
  342. })
  343. .catchall(z.any())
  344. .meta({
  345. ref: "AgentConfig",
  346. })
  347. export type Agent = z.infer<typeof Agent>
  348. export const Keybinds = z
  349. .object({
  350. leader: z.string().optional().default("ctrl+x").describe("Leader key for keybind combinations"),
  351. app_exit: z.string().optional().default("ctrl+c,ctrl+d,<leader>q").describe("Exit the application"),
  352. editor_open: z.string().optional().default("<leader>e").describe("Open external editor"),
  353. theme_list: z.string().optional().default("<leader>t").describe("List available themes"),
  354. sidebar_toggle: z.string().optional().default("<leader>b").describe("Toggle sidebar"),
  355. username_toggle: z.string().optional().default("none").describe("Toggle username visibility"),
  356. status_view: z.string().optional().default("<leader>s").describe("View status"),
  357. session_export: z.string().optional().default("<leader>x").describe("Export session to editor"),
  358. session_new: z.string().optional().default("<leader>n").describe("Create a new session"),
  359. session_list: z.string().optional().default("<leader>l").describe("List all sessions"),
  360. session_timeline: z.string().optional().default("<leader>g").describe("Show session timeline"),
  361. session_share: z.string().optional().default("none").describe("Share current session"),
  362. session_unshare: z.string().optional().default("none").describe("Unshare current session"),
  363. session_interrupt: z.string().optional().default("escape").describe("Interrupt current session"),
  364. session_compact: z.string().optional().default("<leader>c").describe("Compact the session"),
  365. messages_page_up: z.string().optional().default("pageup").describe("Scroll messages up by one page"),
  366. messages_page_down: z.string().optional().default("pagedown").describe("Scroll messages down by one page"),
  367. messages_half_page_up: z.string().optional().default("ctrl+alt+u").describe("Scroll messages up by half page"),
  368. messages_half_page_down: z
  369. .string()
  370. .optional()
  371. .default("ctrl+alt+d")
  372. .describe("Scroll messages down by half page"),
  373. messages_first: z.string().optional().default("ctrl+g,home").describe("Navigate to first message"),
  374. messages_last: z.string().optional().default("ctrl+alt+g,end").describe("Navigate to last message"),
  375. messages_copy: z.string().optional().default("<leader>y").describe("Copy message"),
  376. messages_undo: z.string().optional().default("<leader>u").describe("Undo message"),
  377. messages_redo: z.string().optional().default("<leader>r").describe("Redo message"),
  378. messages_toggle_conceal: z
  379. .string()
  380. .optional()
  381. .default("<leader>h")
  382. .describe("Toggle code block concealment in messages"),
  383. model_list: z.string().optional().default("<leader>m").describe("List available models"),
  384. model_cycle_recent: z.string().optional().default("f2").describe("Next recently used model"),
  385. model_cycle_recent_reverse: z.string().optional().default("shift+f2").describe("Previous recently used model"),
  386. command_list: z.string().optional().default("ctrl+p").describe("List available commands"),
  387. agent_list: z.string().optional().default("<leader>a").describe("List agents"),
  388. agent_cycle: z.string().optional().default("tab").describe("Next agent"),
  389. agent_cycle_reverse: z.string().optional().default("shift+tab").describe("Previous agent"),
  390. input_clear: z.string().optional().default("ctrl+c").describe("Clear input field"),
  391. input_forward_delete: z.string().optional().default("ctrl+d").describe("Forward delete"),
  392. input_paste: z.string().optional().default("ctrl+v").describe("Paste from clipboard"),
  393. input_submit: z.string().optional().default("return").describe("Submit input"),
  394. input_newline: z.string().optional().default("shift+return,ctrl+j").describe("Insert newline in input"),
  395. history_previous: z.string().optional().default("up").describe("Previous history item"),
  396. history_next: z.string().optional().default("down").describe("Next history item"),
  397. session_child_cycle: z.string().optional().default("<leader>right").describe("Next child session"),
  398. session_child_cycle_reverse: z.string().optional().default("<leader>left").describe("Previous child session"),
  399. terminal_suspend: z.string().optional().default("ctrl+z").describe("Suspend terminal"),
  400. })
  401. .strict()
  402. .meta({
  403. ref: "KeybindsConfig",
  404. })
  405. export const TUI = z.object({
  406. scroll_speed: z.number().min(0.001).optional().describe("TUI scroll speed"),
  407. scroll_acceleration: z
  408. .object({
  409. enabled: z.boolean().describe("Enable scroll acceleration"),
  410. })
  411. .optional()
  412. .describe("Scroll acceleration settings"),
  413. diff_style: z
  414. .enum(["auto", "stacked"])
  415. .optional()
  416. .describe("Control diff rendering style: 'auto' adapts to terminal width, 'stacked' always shows single column"),
  417. })
  418. export const Layout = z.enum(["auto", "stretch"]).meta({
  419. ref: "LayoutConfig",
  420. })
  421. export type Layout = z.infer<typeof Layout>
  422. export const Info = z
  423. .object({
  424. $schema: z.string().optional().describe("JSON schema reference for configuration validation"),
  425. theme: z.string().optional().describe("Theme name to use for the interface"),
  426. keybinds: Keybinds.optional().describe("Custom keybind configurations"),
  427. tui: TUI.optional().describe("TUI specific settings"),
  428. command: z
  429. .record(z.string(), Command)
  430. .optional()
  431. .describe("Command configuration, see https://opencode.ai/docs/commands"),
  432. watcher: z
  433. .object({
  434. ignore: z.array(z.string()).optional(),
  435. })
  436. .optional(),
  437. plugin: z.string().array().optional(),
  438. snapshot: z.boolean().optional(),
  439. share: z
  440. .enum(["manual", "auto", "disabled"])
  441. .optional()
  442. .describe(
  443. "Control sharing behavior:'manual' allows manual sharing via commands, 'auto' enables automatic sharing, 'disabled' disables all sharing",
  444. ),
  445. autoshare: z
  446. .boolean()
  447. .optional()
  448. .describe("@deprecated Use 'share' field instead. Share newly created sessions automatically"),
  449. autoupdate: z
  450. .union([z.boolean(), z.literal("notify")])
  451. .optional()
  452. .describe(
  453. "Automatically update to the latest version. Set to true to auto-update, false to disable, or 'notify' to show update notifications",
  454. ),
  455. disabled_providers: z.array(z.string()).optional().describe("Disable providers that are loaded automatically"),
  456. enabled_providers: z
  457. .array(z.string())
  458. .optional()
  459. .describe("When set, ONLY these providers will be enabled. All other providers will be ignored"),
  460. model: z.string().describe("Model to use in the format of provider/model, eg anthropic/claude-2").optional(),
  461. small_model: z
  462. .string()
  463. .describe("Small model to use for tasks like title generation in the format of provider/model")
  464. .optional(),
  465. username: z
  466. .string()
  467. .optional()
  468. .describe("Custom username to display in conversations instead of system username"),
  469. mode: z
  470. .object({
  471. build: Agent.optional(),
  472. plan: Agent.optional(),
  473. })
  474. .catchall(Agent)
  475. .optional()
  476. .describe("@deprecated Use `agent` field instead."),
  477. agent: z
  478. .object({
  479. plan: Agent.optional(),
  480. build: Agent.optional(),
  481. general: Agent.optional(),
  482. explore: Agent.optional(),
  483. })
  484. .catchall(Agent)
  485. .optional()
  486. .describe("Agent configuration, see https://opencode.ai/docs/agent"),
  487. provider: z
  488. .record(
  489. z.string(),
  490. ModelsDev.Provider.partial()
  491. .extend({
  492. whitelist: z.array(z.string()).optional(),
  493. blacklist: z.array(z.string()).optional(),
  494. models: z.record(z.string(), ModelsDev.Model.partial()).optional(),
  495. options: z
  496. .object({
  497. apiKey: z.string().optional(),
  498. baseURL: z.string().optional(),
  499. enterpriseUrl: z.string().optional().describe("GitHub Enterprise URL for copilot authentication"),
  500. setCacheKey: z
  501. .boolean()
  502. .optional()
  503. .describe("Enable promptCacheKey for this provider (default false)"),
  504. timeout: z
  505. .union([
  506. z
  507. .number()
  508. .int()
  509. .positive()
  510. .describe(
  511. "Timeout in milliseconds for requests to this provider. Default is 300000 (5 minutes). Set to false to disable timeout.",
  512. ),
  513. z.literal(false).describe("Disable timeout for this provider entirely."),
  514. ])
  515. .optional()
  516. .describe(
  517. "Timeout in milliseconds for requests to this provider. Default is 300000 (5 minutes). Set to false to disable timeout.",
  518. ),
  519. })
  520. .catchall(z.any())
  521. .optional(),
  522. })
  523. .strict(),
  524. )
  525. .optional()
  526. .describe("Custom provider configurations and model overrides"),
  527. mcp: z.record(z.string(), Mcp).optional().describe("MCP (Model Context Protocol) server configurations"),
  528. formatter: z
  529. .union([
  530. z.literal(false),
  531. z.record(
  532. z.string(),
  533. z.object({
  534. disabled: z.boolean().optional(),
  535. command: z.array(z.string()).optional(),
  536. environment: z.record(z.string(), z.string()).optional(),
  537. extensions: z.array(z.string()).optional(),
  538. }),
  539. ),
  540. ])
  541. .optional(),
  542. lsp: z
  543. .union([
  544. z.literal(false),
  545. z.record(
  546. z.string(),
  547. z.union([
  548. z.object({
  549. disabled: z.literal(true),
  550. }),
  551. z.object({
  552. command: z.array(z.string()),
  553. extensions: z.array(z.string()).optional(),
  554. disabled: z.boolean().optional(),
  555. env: z.record(z.string(), z.string()).optional(),
  556. initialization: z.record(z.string(), z.any()).optional(),
  557. }),
  558. ]),
  559. ),
  560. ])
  561. .optional()
  562. .refine(
  563. (data) => {
  564. if (!data) return true
  565. if (typeof data === "boolean") return true
  566. const serverIds = new Set(Object.values(LSPServer).map((s) => s.id))
  567. return Object.entries(data).every(([id, config]) => {
  568. if (config.disabled) return true
  569. if (serverIds.has(id)) return true
  570. return Boolean(config.extensions)
  571. })
  572. },
  573. {
  574. error: "For custom LSP servers, 'extensions' array is required.",
  575. },
  576. ),
  577. instructions: z.array(z.string()).optional().describe("Additional instruction files or patterns to include"),
  578. layout: Layout.optional().describe("@deprecated Always uses stretch layout."),
  579. permission: z
  580. .object({
  581. edit: Permission.optional(),
  582. bash: z.union([Permission, z.record(z.string(), Permission)]).optional(),
  583. webfetch: Permission.optional(),
  584. doom_loop: Permission.optional(),
  585. external_directory: Permission.optional(),
  586. })
  587. .optional(),
  588. tools: z.record(z.string(), z.boolean()).optional(),
  589. enterprise: z
  590. .object({
  591. url: z.string().optional().describe("Enterprise URL"),
  592. })
  593. .optional(),
  594. experimental: z
  595. .object({
  596. hook: z
  597. .object({
  598. file_edited: z
  599. .record(
  600. z.string(),
  601. z
  602. .object({
  603. command: z.string().array(),
  604. environment: z.record(z.string(), z.string()).optional(),
  605. })
  606. .array(),
  607. )
  608. .optional(),
  609. session_completed: z
  610. .object({
  611. command: z.string().array(),
  612. environment: z.record(z.string(), z.string()).optional(),
  613. })
  614. .array()
  615. .optional(),
  616. })
  617. .optional(),
  618. chatMaxRetries: z.number().optional().describe("Number of retries for chat completions on failure"),
  619. disable_paste_summary: z.boolean().optional(),
  620. batch_tool: z.boolean().optional().describe("Enable the batch tool"),
  621. primary_tools: z
  622. .array(z.string())
  623. .optional()
  624. .describe("Tools that should only be available to primary agents."),
  625. })
  626. .optional(),
  627. })
  628. .strict()
  629. .meta({
  630. ref: "Config",
  631. })
  632. export type Info = z.output<typeof Info>
  633. export const global = lazy(async () => {
  634. let result: Info = pipe(
  635. {},
  636. mergeDeep(await loadFile(path.join(Global.Path.config, "config.json"))),
  637. mergeDeep(await loadFile(path.join(Global.Path.config, "opencode.json"))),
  638. mergeDeep(await loadFile(path.join(Global.Path.config, "opencode.jsonc"))),
  639. )
  640. await import(path.join(Global.Path.config, "config"), {
  641. with: {
  642. type: "toml",
  643. },
  644. })
  645. .then(async (mod) => {
  646. const { provider, model, ...rest } = mod.default
  647. if (provider && model) result.model = `${provider}/${model}`
  648. result["$schema"] = "https://opencode.ai/config.json"
  649. result = mergeDeep(result, rest)
  650. await Bun.write(path.join(Global.Path.config, "config.json"), JSON.stringify(result, null, 2))
  651. await fs.unlink(path.join(Global.Path.config, "config"))
  652. })
  653. .catch(() => {})
  654. return result
  655. })
  656. async function loadFile(filepath: string): Promise<Info> {
  657. log.info("loading", { path: filepath })
  658. let text = await Bun.file(filepath)
  659. .text()
  660. .catch((err) => {
  661. if (err.code === "ENOENT") return
  662. throw new JsonError({ path: filepath }, { cause: err })
  663. })
  664. if (!text) return {}
  665. return load(text, filepath)
  666. }
  667. async function load(text: string, configFilepath: string) {
  668. text = text.replace(/\{env:([^}]+)\}/g, (_, varName) => {
  669. return process.env[varName] || ""
  670. })
  671. const fileMatches = text.match(/\{file:[^}]+\}/g)
  672. if (fileMatches) {
  673. const configDir = path.dirname(configFilepath)
  674. const lines = text.split("\n")
  675. for (const match of fileMatches) {
  676. const lineIndex = lines.findIndex((line) => line.includes(match))
  677. if (lineIndex !== -1 && lines[lineIndex].trim().startsWith("//")) {
  678. continue // Skip if line is commented
  679. }
  680. let filePath = match.replace(/^\{file:/, "").replace(/\}$/, "")
  681. if (filePath.startsWith("~/")) {
  682. filePath = path.join(os.homedir(), filePath.slice(2))
  683. }
  684. const resolvedPath = path.isAbsolute(filePath) ? filePath : path.resolve(configDir, filePath)
  685. const fileContent = (
  686. await Bun.file(resolvedPath)
  687. .text()
  688. .catch((error) => {
  689. const errMsg = `bad file reference: "${match}"`
  690. if (error.code === "ENOENT") {
  691. throw new InvalidError(
  692. {
  693. path: configFilepath,
  694. message: errMsg + ` ${resolvedPath} does not exist`,
  695. },
  696. { cause: error },
  697. )
  698. }
  699. throw new InvalidError({ path: configFilepath, message: errMsg }, { cause: error })
  700. })
  701. ).trim()
  702. // escape newlines/quotes, strip outer quotes
  703. text = text.replace(match, JSON.stringify(fileContent).slice(1, -1))
  704. }
  705. }
  706. const errors: JsoncParseError[] = []
  707. const data = parseJsonc(text, errors, { allowTrailingComma: true })
  708. if (errors.length) {
  709. const lines = text.split("\n")
  710. const errorDetails = errors
  711. .map((e) => {
  712. const beforeOffset = text.substring(0, e.offset).split("\n")
  713. const line = beforeOffset.length
  714. const column = beforeOffset[beforeOffset.length - 1].length + 1
  715. const problemLine = lines[line - 1]
  716. const error = `${printParseErrorCode(e.error)} at line ${line}, column ${column}`
  717. if (!problemLine) return error
  718. return `${error}\n Line ${line}: ${problemLine}\n${"".padStart(column + 9)}^`
  719. })
  720. .join("\n")
  721. throw new JsonError({
  722. path: configFilepath,
  723. message: `\n--- JSONC Input ---\n${text}\n--- Errors ---\n${errorDetails}\n--- End ---`,
  724. })
  725. }
  726. const parsed = Info.safeParse(data)
  727. if (parsed.success) {
  728. if (!parsed.data.$schema) {
  729. parsed.data.$schema = "https://opencode.ai/config.json"
  730. await Bun.write(configFilepath, JSON.stringify(parsed.data, null, 2))
  731. }
  732. const data = parsed.data
  733. if (data.plugin) {
  734. for (let i = 0; i < data.plugin.length; i++) {
  735. const plugin = data.plugin[i]
  736. try {
  737. data.plugin[i] = import.meta.resolve!(plugin, configFilepath)
  738. } catch (err) {}
  739. }
  740. }
  741. return data
  742. }
  743. throw new InvalidError({
  744. path: configFilepath,
  745. issues: parsed.error.issues,
  746. })
  747. }
  748. export const JsonError = NamedError.create(
  749. "ConfigJsonError",
  750. z.object({
  751. path: z.string(),
  752. message: z.string().optional(),
  753. }),
  754. )
  755. export const ConfigDirectoryTypoError = NamedError.create(
  756. "ConfigDirectoryTypoError",
  757. z.object({
  758. path: z.string(),
  759. dir: z.string(),
  760. suggestion: z.string(),
  761. }),
  762. )
  763. export const InvalidError = NamedError.create(
  764. "ConfigInvalidError",
  765. z.object({
  766. path: z.string(),
  767. issues: z.custom<z.core.$ZodIssue[]>().optional(),
  768. message: z.string().optional(),
  769. }),
  770. )
  771. export async function get() {
  772. return state().then((x) => x.config)
  773. }
  774. export async function update(config: Info) {
  775. const filepath = path.join(Instance.directory, "config.json")
  776. const existing = await loadFile(filepath)
  777. await Bun.write(filepath, JSON.stringify(mergeDeep(existing, config), null, 2))
  778. await Instance.dispose()
  779. }
  780. export async function directories() {
  781. return state().then((x) => x.directories)
  782. }
  783. }