config.ts 28 KB

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