config.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  1. import { Log } from "../util/log"
  2. import path from "path"
  3. import os from "os"
  4. import { z } from "zod"
  5. import { App } from "../app/app"
  6. import { Filesystem } from "../util/filesystem"
  7. import { ModelsDev } from "../provider/models"
  8. import { mergeDeep, pipe } from "remeda"
  9. import { Global } from "../global"
  10. import fs from "fs/promises"
  11. import { lazy } from "../util/lazy"
  12. import { NamedError } from "../util/error"
  13. import matter from "gray-matter"
  14. import { Flag } from "../flag/flag"
  15. import { Auth } from "../auth"
  16. import { type ParseError as JsoncParseError, parse as parseJsonc, printParseErrorCode } from "jsonc-parser"
  17. export namespace Config {
  18. const log = Log.create({ service: "config" })
  19. export const state = App.state("config", async (app) => {
  20. const auth = await Auth.all()
  21. let result = await global()
  22. for (const file of ["opencode.jsonc", "opencode.json"]) {
  23. const found = await Filesystem.findUp(file, app.path.cwd, app.path.root)
  24. for (const resolved of found.toReversed()) {
  25. result = mergeDeep(result, await loadFile(resolved))
  26. }
  27. }
  28. // Override with custom config if provided
  29. if (Flag.OPENCODE_CONFIG) {
  30. result = mergeDeep(result, await loadFile(Flag.OPENCODE_CONFIG))
  31. log.debug("loaded custom config", { path: Flag.OPENCODE_CONFIG })
  32. }
  33. for (const [key, value] of Object.entries(auth)) {
  34. if (value.type === "wellknown") {
  35. process.env[value.key] = value.token
  36. const wellknown = await fetch(`${key}/.well-known/opencode`).then((x) => x.json())
  37. result = mergeDeep(result, await load(JSON.stringify(wellknown.config ?? {}), process.cwd()))
  38. }
  39. }
  40. result.agent = result.agent || {}
  41. const markdownAgents = [
  42. ...(await Filesystem.globUp("agent/**/*.md", Global.Path.config, Global.Path.config)),
  43. ...(await Filesystem.globUp(".opencode/agent/**/*.md", app.path.cwd, app.path.root)),
  44. ]
  45. for (const item of markdownAgents) {
  46. const content = await Bun.file(item).text()
  47. const md = matter(content)
  48. if (!md.data) continue
  49. // Extract relative path from agent folder for nested agents
  50. let agentName = path.basename(item, ".md")
  51. const agentFolderPath = item.includes("/.opencode/agent/")
  52. ? item.split("/.opencode/agent/")[1]
  53. : item.includes("/agent/")
  54. ? item.split("/agent/")[1]
  55. : agentName + ".md"
  56. // If agent is in a subfolder, include folder path in name
  57. if (agentFolderPath.includes("/")) {
  58. const relativePath = agentFolderPath.replace(".md", "")
  59. const pathParts = relativePath.split("/")
  60. agentName = pathParts.slice(0, -1).join("/") + "/" + pathParts[pathParts.length - 1]
  61. }
  62. const config = {
  63. name: agentName,
  64. ...md.data,
  65. prompt: md.content.trim(),
  66. }
  67. const parsed = Agent.safeParse(config)
  68. if (parsed.success) {
  69. result.agent = mergeDeep(result.agent, {
  70. [config.name]: parsed.data,
  71. })
  72. continue
  73. }
  74. throw new InvalidError({ path: item }, { cause: parsed.error })
  75. }
  76. // Load mode markdown files
  77. result.mode = result.mode || {}
  78. const markdownModes = [
  79. ...(await Filesystem.globUp("mode/*.md", Global.Path.config, Global.Path.config)),
  80. ...(await Filesystem.globUp(".opencode/mode/*.md", app.path.cwd, app.path.root)),
  81. ]
  82. for (const item of markdownModes) {
  83. const content = await Bun.file(item).text()
  84. const md = matter(content)
  85. if (!md.data) continue
  86. const config = {
  87. name: path.basename(item, ".md"),
  88. ...md.data,
  89. prompt: md.content.trim(),
  90. }
  91. const parsed = Agent.safeParse(config)
  92. if (parsed.success) {
  93. result.mode = mergeDeep(result.mode, {
  94. [config.name]: parsed.data,
  95. })
  96. continue
  97. }
  98. throw new InvalidError({ path: item }, { cause: parsed.error })
  99. }
  100. // Load command markdown files
  101. result.command = result.command || {}
  102. const markdownCommands = [
  103. ...(await Filesystem.globUp("command/*.md", Global.Path.config, Global.Path.config)),
  104. ...(await Filesystem.globUp(".opencode/command/*.md", app.path.cwd, app.path.root)),
  105. ]
  106. for (const item of markdownCommands) {
  107. const content = await Bun.file(item).text()
  108. const md = matter(content)
  109. if (!md.data) continue
  110. const config = {
  111. name: path.basename(item, ".md"),
  112. ...md.data,
  113. template: md.content.trim(),
  114. }
  115. const parsed = Command.safeParse(config)
  116. if (parsed.success) {
  117. result.command = mergeDeep(result.command, {
  118. [config.name]: parsed.data,
  119. })
  120. continue
  121. }
  122. throw new InvalidError({ path: item }, { cause: parsed.error })
  123. }
  124. // Migrate deprecated mode field to agent field
  125. for (const [name, mode] of Object.entries(result.mode)) {
  126. result.agent = mergeDeep(result.agent ?? {}, {
  127. [name]: {
  128. ...mode,
  129. mode: "primary" as const,
  130. },
  131. })
  132. }
  133. result.plugin = result.plugin || []
  134. result.plugin.push(
  135. ...[
  136. ...(await Filesystem.globUp("plugin/*.{ts,js}", Global.Path.config, Global.Path.config)),
  137. ...(await Filesystem.globUp(".opencode/plugin/*.{ts,js}", app.path.cwd, app.path.root)),
  138. ].map((x) => "file://" + x),
  139. )
  140. if (Flag.OPENCODE_PERMISSION) {
  141. result.permission = mergeDeep(result.permission ?? {}, JSON.parse(Flag.OPENCODE_PERMISSION))
  142. }
  143. // Handle migration from autoshare to share field
  144. if (result.autoshare === true && !result.share) {
  145. result.share = "auto"
  146. }
  147. if (result.keybinds?.messages_revert && !result.keybinds.messages_undo) {
  148. result.keybinds.messages_undo = result.keybinds.messages_revert
  149. }
  150. if (result.keybinds?.switch_mode && !result.keybinds.switch_agent) {
  151. result.keybinds.switch_agent = result.keybinds.switch_mode
  152. }
  153. if (result.keybinds?.switch_mode_reverse && !result.keybinds.switch_agent_reverse) {
  154. result.keybinds.switch_agent_reverse = result.keybinds.switch_mode_reverse
  155. }
  156. if (result.keybinds?.switch_agent && !result.keybinds.agent_cycle) {
  157. result.keybinds.agent_cycle = result.keybinds.switch_agent
  158. }
  159. if (result.keybinds?.switch_agent_reverse && !result.keybinds.agent_cycle_reverse) {
  160. result.keybinds.agent_cycle_reverse = result.keybinds.switch_agent_reverse
  161. }
  162. if (!result.username) {
  163. const os = await import("os")
  164. result.username = os.userInfo().username
  165. }
  166. log.info("loaded", result)
  167. return result
  168. })
  169. export const McpLocal = z
  170. .object({
  171. type: z.literal("local").describe("Type of MCP server connection"),
  172. command: z.string().array().describe("Command and arguments to run the MCP server"),
  173. environment: z
  174. .record(z.string(), z.string())
  175. .optional()
  176. .describe("Environment variables to set when running the MCP server"),
  177. enabled: z.boolean().optional().describe("Enable or disable the MCP server on startup"),
  178. })
  179. .strict()
  180. .openapi({
  181. ref: "McpLocalConfig",
  182. })
  183. export const McpRemote = z
  184. .object({
  185. type: z.literal("remote").describe("Type of MCP server connection"),
  186. url: z.string().describe("URL of the remote MCP server"),
  187. enabled: z.boolean().optional().describe("Enable or disable the MCP server on startup"),
  188. headers: z.record(z.string(), z.string()).optional().describe("Headers to send with the request"),
  189. })
  190. .strict()
  191. .openapi({
  192. ref: "McpRemoteConfig",
  193. })
  194. export const Mcp = z.discriminatedUnion("type", [McpLocal, McpRemote])
  195. export type Mcp = z.infer<typeof Mcp>
  196. export const Permission = z.union([z.literal("ask"), z.literal("allow"), z.literal("deny")])
  197. export type Permission = z.infer<typeof Permission>
  198. export const Command = z.object({
  199. template: z.string(),
  200. description: z.string().optional(),
  201. agent: z.string().optional(),
  202. model: z.string().optional(),
  203. })
  204. export type Command = z.infer<typeof Command>
  205. export const Agent = z
  206. .object({
  207. model: z.string().optional(),
  208. temperature: z.number().optional(),
  209. top_p: z.number().optional(),
  210. prompt: z.string().optional(),
  211. tools: z.record(z.string(), z.boolean()).optional(),
  212. disable: z.boolean().optional(),
  213. description: z.string().optional().describe("Description of when to use the agent"),
  214. mode: z.union([z.literal("subagent"), z.literal("primary"), z.literal("all")]).optional(),
  215. permission: z
  216. .object({
  217. edit: Permission.optional(),
  218. bash: z.union([Permission, z.record(z.string(), Permission)]).optional(),
  219. webfetch: Permission.optional(),
  220. })
  221. .optional(),
  222. })
  223. .catchall(z.any())
  224. .openapi({
  225. ref: "AgentConfig",
  226. })
  227. export type Agent = z.infer<typeof Agent>
  228. export const Keybinds = z
  229. .object({
  230. leader: z.string().optional().default("ctrl+x").describe("Leader key for keybind combinations"),
  231. app_help: z.string().optional().default("<leader>h").describe("Show help dialog"),
  232. app_exit: z.string().optional().default("ctrl+c,<leader>q").describe("Exit the application"),
  233. editor_open: z.string().optional().default("<leader>e").describe("Open external editor"),
  234. theme_list: z.string().optional().default("<leader>t").describe("List available themes"),
  235. project_init: z.string().optional().default("<leader>i").describe("Create/update AGENTS.md"),
  236. tool_details: z.string().optional().default("<leader>d").describe("Toggle tool details"),
  237. thinking_blocks: z.string().optional().default("<leader>b").describe("Toggle thinking blocks"),
  238. session_export: z.string().optional().default("<leader>x").describe("Export session to editor"),
  239. session_new: z.string().optional().default("<leader>n").describe("Create a new session"),
  240. session_list: z.string().optional().default("<leader>l").describe("List all sessions"),
  241. session_timeline: z.string().optional().default("<leader>g").describe("Show session timeline"),
  242. session_share: z.string().optional().default("<leader>s").describe("Share current session"),
  243. session_unshare: z.string().optional().default("none").describe("Unshare current session"),
  244. session_interrupt: z.string().optional().default("esc").describe("Interrupt current session"),
  245. session_compact: z.string().optional().default("<leader>c").describe("Compact the session"),
  246. session_child_cycle: z.string().optional().default("ctrl+right").describe("Cycle to next child session"),
  247. session_child_cycle_reverse: z
  248. .string()
  249. .optional()
  250. .default("ctrl+left")
  251. .describe("Cycle to previous child session"),
  252. messages_page_up: z.string().optional().default("pgup").describe("Scroll messages up by one page"),
  253. messages_page_down: z.string().optional().default("pgdown").describe("Scroll messages down by one page"),
  254. messages_half_page_up: z.string().optional().default("ctrl+alt+u").describe("Scroll messages up by half page"),
  255. messages_half_page_down: z
  256. .string()
  257. .optional()
  258. .default("ctrl+alt+d")
  259. .describe("Scroll messages down by half page"),
  260. messages_first: z.string().optional().default("ctrl+g").describe("Navigate to first message"),
  261. messages_last: z.string().optional().default("ctrl+alt+g").describe("Navigate to last message"),
  262. messages_copy: z.string().optional().default("<leader>y").describe("Copy message"),
  263. messages_undo: z.string().optional().default("<leader>u").describe("Undo message"),
  264. messages_redo: z.string().optional().default("<leader>r").describe("Redo message"),
  265. model_list: z.string().optional().default("<leader>m").describe("List available models"),
  266. model_cycle_recent: z.string().optional().default("f2").describe("Next recent model"),
  267. model_cycle_recent_reverse: z.string().optional().default("shift+f2").describe("Previous recent model"),
  268. agent_list: z.string().optional().default("<leader>a").describe("List agents"),
  269. agent_cycle: z.string().optional().default("tab").describe("Next agent"),
  270. agent_cycle_reverse: z.string().optional().default("shift+tab").describe("Previous agent"),
  271. input_clear: z.string().optional().default("ctrl+c").describe("Clear input field"),
  272. input_paste: z.string().optional().default("ctrl+v").describe("Paste from clipboard"),
  273. input_submit: z.string().optional().default("enter").describe("Submit input"),
  274. input_newline: z.string().optional().default("shift+enter,ctrl+j").describe("Insert newline in input"),
  275. // Deprecated commands
  276. switch_mode: z.string().optional().default("none").describe("@deprecated use agent_cycle. Next mode"),
  277. switch_mode_reverse: z
  278. .string()
  279. .optional()
  280. .default("none")
  281. .describe("@deprecated use agent_cycle_reverse. Previous mode"),
  282. switch_agent: z.string().optional().default("tab").describe("@deprecated use agent_cycle. Next agent"),
  283. switch_agent_reverse: z
  284. .string()
  285. .optional()
  286. .default("shift+tab")
  287. .describe("@deprecated use agent_cycle_reverse. Previous agent"),
  288. file_list: z.string().optional().default("none").describe("@deprecated Currently not available. List files"),
  289. file_close: z.string().optional().default("none").describe("@deprecated Close file"),
  290. file_search: z.string().optional().default("none").describe("@deprecated Search file"),
  291. file_diff_toggle: z.string().optional().default("none").describe("@deprecated Split/unified diff"),
  292. messages_previous: z.string().optional().default("none").describe("@deprecated Navigate to previous message"),
  293. messages_next: z.string().optional().default("none").describe("@deprecated Navigate to next message"),
  294. messages_layout_toggle: z.string().optional().default("none").describe("@deprecated Toggle layout"),
  295. messages_revert: z.string().optional().default("none").describe("@deprecated use messages_undo. Revert message"),
  296. })
  297. .strict()
  298. .openapi({
  299. ref: "KeybindsConfig",
  300. })
  301. export const TUI = z.object({
  302. scroll_speed: z.number().min(1).optional().default(2).describe("TUI scroll speed"),
  303. })
  304. export const Layout = z.enum(["auto", "stretch"]).openapi({
  305. ref: "LayoutConfig",
  306. })
  307. export type Layout = z.infer<typeof Layout>
  308. export const Info = z
  309. .object({
  310. $schema: z.string().optional().describe("JSON schema reference for configuration validation"),
  311. theme: z.string().optional().describe("Theme name to use for the interface"),
  312. keybinds: Keybinds.optional().describe("Custom keybind configurations"),
  313. tui: TUI.optional().describe("TUI specific settings"),
  314. command: z.record(z.string(), Command).optional(),
  315. plugin: z.string().array().optional(),
  316. snapshot: z.boolean().optional(),
  317. share: z
  318. .enum(["manual", "auto", "disabled"])
  319. .optional()
  320. .describe(
  321. "Control sharing behavior:'manual' allows manual sharing via commands, 'auto' enables automatic sharing, 'disabled' disables all sharing",
  322. ),
  323. autoshare: z
  324. .boolean()
  325. .optional()
  326. .describe("@deprecated Use 'share' field instead. Share newly created sessions automatically"),
  327. autoupdate: z.boolean().optional().describe("Automatically update to the latest version"),
  328. disabled_providers: z.array(z.string()).optional().describe("Disable providers that are loaded automatically"),
  329. model: z.string().describe("Model to use in the format of provider/model, eg anthropic/claude-2").optional(),
  330. small_model: z
  331. .string()
  332. .describe("Small model to use for tasks like title generation in the format of provider/model")
  333. .optional(),
  334. username: z
  335. .string()
  336. .optional()
  337. .describe("Custom username to display in conversations instead of system username"),
  338. mode: z
  339. .object({
  340. build: Agent.optional(),
  341. plan: Agent.optional(),
  342. })
  343. .catchall(Agent)
  344. .optional()
  345. .describe("@deprecated Use `agent` field instead."),
  346. agent: z
  347. .object({
  348. plan: Agent.optional(),
  349. build: Agent.optional(),
  350. general: Agent.optional(),
  351. })
  352. .catchall(Agent)
  353. .optional()
  354. .describe("Agent configuration, see https://opencode.ai/docs/agent"),
  355. provider: z
  356. .record(
  357. ModelsDev.Provider.partial()
  358. .extend({
  359. models: z.record(ModelsDev.Model.partial()).optional(),
  360. options: z
  361. .object({
  362. apiKey: z.string().optional(),
  363. baseURL: z.string().optional(),
  364. })
  365. .catchall(z.any())
  366. .optional(),
  367. })
  368. .strict(),
  369. )
  370. .optional()
  371. .describe("Custom provider configurations and model overrides"),
  372. mcp: z.record(z.string(), Mcp).optional().describe("MCP (Model Context Protocol) server configurations"),
  373. formatter: z
  374. .record(
  375. z.string(),
  376. z.object({
  377. disabled: z.boolean().optional(),
  378. command: z.array(z.string()).optional(),
  379. environment: z.record(z.string(), z.string()).optional(),
  380. extensions: z.array(z.string()).optional(),
  381. }),
  382. )
  383. .optional(),
  384. lsp: z
  385. .record(
  386. z.string(),
  387. z.union([
  388. z.object({
  389. disabled: z.literal(true),
  390. }),
  391. z.object({
  392. command: z.array(z.string()),
  393. extensions: z.array(z.string()).optional(),
  394. disabled: z.boolean().optional(),
  395. env: z.record(z.string(), z.string()).optional(),
  396. initialization: z.record(z.string(), z.any()).optional(),
  397. }),
  398. ]),
  399. )
  400. .optional(),
  401. instructions: z.array(z.string()).optional().describe("Additional instruction files or patterns to include"),
  402. layout: Layout.optional().describe("@deprecated Always uses stretch layout."),
  403. permission: z
  404. .object({
  405. edit: Permission.optional(),
  406. bash: z.union([Permission, z.record(z.string(), Permission)]).optional(),
  407. webfetch: Permission.optional(),
  408. })
  409. .optional(),
  410. tools: z.record(z.string(), z.boolean()).optional(),
  411. experimental: z
  412. .object({
  413. hook: z
  414. .object({
  415. file_edited: z
  416. .record(
  417. z.string(),
  418. z
  419. .object({
  420. command: z.string().array(),
  421. environment: z.record(z.string(), z.string()).optional(),
  422. })
  423. .array(),
  424. )
  425. .optional(),
  426. session_completed: z
  427. .object({
  428. command: z.string().array(),
  429. environment: z.record(z.string(), z.string()).optional(),
  430. })
  431. .array()
  432. .optional(),
  433. })
  434. .optional(),
  435. })
  436. .optional(),
  437. })
  438. .strict()
  439. .openapi({
  440. ref: "Config",
  441. })
  442. export type Info = z.output<typeof Info>
  443. export const global = lazy(async () => {
  444. let result: Info = pipe(
  445. {},
  446. mergeDeep(await loadFile(path.join(Global.Path.config, "config.json"))),
  447. mergeDeep(await loadFile(path.join(Global.Path.config, "opencode.json"))),
  448. mergeDeep(await loadFile(path.join(Global.Path.config, "opencode.jsonc"))),
  449. )
  450. await import(path.join(Global.Path.config, "config"), {
  451. with: {
  452. type: "toml",
  453. },
  454. })
  455. .then(async (mod) => {
  456. const { provider, model, ...rest } = mod.default
  457. if (provider && model) result.model = `${provider}/${model}`
  458. result["$schema"] = "https://opencode.ai/config.json"
  459. result = mergeDeep(result, rest)
  460. await Bun.write(path.join(Global.Path.config, "config.json"), JSON.stringify(result, null, 2))
  461. await fs.unlink(path.join(Global.Path.config, "config"))
  462. })
  463. .catch(() => {})
  464. return result
  465. })
  466. async function loadFile(filepath: string): Promise<Info> {
  467. log.info("loading", { path: filepath })
  468. let text = await Bun.file(filepath)
  469. .text()
  470. .catch((err) => {
  471. if (err.code === "ENOENT") return
  472. throw new JsonError({ path: filepath }, { cause: err })
  473. })
  474. if (!text) return {}
  475. return load(text, filepath)
  476. }
  477. async function load(text: string, configFilepath: string) {
  478. text = text.replace(/\{env:([^}]+)\}/g, (_, varName) => {
  479. return process.env[varName] || ""
  480. })
  481. const fileMatches = text.match(/\{file:[^}]+\}/g)
  482. if (fileMatches) {
  483. const configDir = path.dirname(configFilepath)
  484. const lines = text.split("\n")
  485. for (const match of fileMatches) {
  486. const lineIndex = lines.findIndex((line) => line.includes(match))
  487. if (lineIndex !== -1 && lines[lineIndex].trim().startsWith("//")) {
  488. continue // Skip if line is commented
  489. }
  490. let filePath = match.replace(/^\{file:/, "").replace(/\}$/, "")
  491. if (filePath.startsWith("~/")) {
  492. filePath = path.join(os.homedir(), filePath.slice(2))
  493. }
  494. const resolvedPath = path.isAbsolute(filePath) ? filePath : path.resolve(configDir, filePath)
  495. const fileContent = (
  496. await Bun.file(resolvedPath)
  497. .text()
  498. .catch((error) => {
  499. const errMsg = `bad file reference: "${match}"`
  500. if (error.code === "ENOENT") {
  501. throw new InvalidError(
  502. { path: configFilepath, message: errMsg + ` ${resolvedPath} does not exist` },
  503. { cause: error },
  504. )
  505. }
  506. throw new InvalidError({ path: configFilepath, message: errMsg }, { cause: error })
  507. })
  508. ).trim()
  509. // escape newlines/quotes, strip outer quotes
  510. text = text.replace(match, JSON.stringify(fileContent).slice(1, -1))
  511. }
  512. }
  513. const errors: JsoncParseError[] = []
  514. const data = parseJsonc(text, errors, { allowTrailingComma: true })
  515. if (errors.length) {
  516. const lines = text.split("\n")
  517. const errorDetails = errors
  518. .map((e) => {
  519. const beforeOffset = text.substring(0, e.offset).split("\n")
  520. const line = beforeOffset.length
  521. const column = beforeOffset[beforeOffset.length - 1].length + 1
  522. const problemLine = lines[line - 1]
  523. const error = `${printParseErrorCode(e.error)} at line ${line}, column ${column}`
  524. if (!problemLine) return error
  525. return `${error}\n Line ${line}: ${problemLine}\n${"".padStart(column + 9)}^`
  526. })
  527. .join("\n")
  528. throw new JsonError({
  529. path: configFilepath,
  530. message: `\n--- JSONC Input ---\n${text}\n--- Errors ---\n${errorDetails}\n--- End ---`,
  531. })
  532. }
  533. const parsed = Info.safeParse(data)
  534. if (parsed.success) {
  535. if (!parsed.data.$schema) {
  536. parsed.data.$schema = "https://opencode.ai/config.json"
  537. await Bun.write(configFilepath, JSON.stringify(parsed.data, null, 2))
  538. }
  539. const data = parsed.data
  540. if (data.plugin) {
  541. for (let i = 0; i < data.plugin?.length; i++) {
  542. const plugin = data.plugin[i]
  543. try {
  544. data.plugin[i] = import.meta.resolve(plugin, configFilepath)
  545. } catch (err) {}
  546. }
  547. }
  548. return data
  549. }
  550. throw new InvalidError({ path: configFilepath, issues: parsed.error.issues })
  551. }
  552. export const JsonError = NamedError.create(
  553. "ConfigJsonError",
  554. z.object({
  555. path: z.string(),
  556. message: z.string().optional(),
  557. }),
  558. )
  559. export const InvalidError = NamedError.create(
  560. "ConfigInvalidError",
  561. z.object({
  562. path: z.string(),
  563. issues: z.custom<z.ZodIssue[]>().optional(),
  564. message: z.string().optional(),
  565. }),
  566. )
  567. export function get() {
  568. return state()
  569. }
  570. }