config.test.ts 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414
  1. import { test, expect, describe, mock } from "bun:test"
  2. import { Config } from "../../src/config/config"
  3. import { Instance } from "../../src/project/instance"
  4. import { Auth } from "../../src/auth"
  5. import { tmpdir } from "../fixture/fixture"
  6. import path from "path"
  7. import fs from "fs/promises"
  8. import { pathToFileURL } from "url"
  9. test("loads config with defaults when no files exist", async () => {
  10. await using tmp = await tmpdir()
  11. await Instance.provide({
  12. directory: tmp.path,
  13. fn: async () => {
  14. const config = await Config.get()
  15. expect(config.username).toBeDefined()
  16. },
  17. })
  18. })
  19. test("loads JSON config file", async () => {
  20. await using tmp = await tmpdir({
  21. init: async (dir) => {
  22. await Bun.write(
  23. path.join(dir, "opencode.json"),
  24. JSON.stringify({
  25. $schema: "https://opencode.ai/config.json",
  26. model: "test/model",
  27. username: "testuser",
  28. }),
  29. )
  30. },
  31. })
  32. await Instance.provide({
  33. directory: tmp.path,
  34. fn: async () => {
  35. const config = await Config.get()
  36. expect(config.model).toBe("test/model")
  37. expect(config.username).toBe("testuser")
  38. },
  39. })
  40. })
  41. test("loads JSONC config file", async () => {
  42. await using tmp = await tmpdir({
  43. init: async (dir) => {
  44. await Bun.write(
  45. path.join(dir, "opencode.jsonc"),
  46. `{
  47. // This is a comment
  48. "$schema": "https://opencode.ai/config.json",
  49. "model": "test/model",
  50. "username": "testuser"
  51. }`,
  52. )
  53. },
  54. })
  55. await Instance.provide({
  56. directory: tmp.path,
  57. fn: async () => {
  58. const config = await Config.get()
  59. expect(config.model).toBe("test/model")
  60. expect(config.username).toBe("testuser")
  61. },
  62. })
  63. })
  64. test("merges multiple config files with correct precedence", async () => {
  65. await using tmp = await tmpdir({
  66. init: async (dir) => {
  67. await Bun.write(
  68. path.join(dir, "opencode.jsonc"),
  69. JSON.stringify({
  70. $schema: "https://opencode.ai/config.json",
  71. model: "base",
  72. username: "base",
  73. }),
  74. )
  75. await Bun.write(
  76. path.join(dir, "opencode.json"),
  77. JSON.stringify({
  78. $schema: "https://opencode.ai/config.json",
  79. model: "override",
  80. }),
  81. )
  82. },
  83. })
  84. await Instance.provide({
  85. directory: tmp.path,
  86. fn: async () => {
  87. const config = await Config.get()
  88. expect(config.model).toBe("override")
  89. expect(config.username).toBe("base")
  90. },
  91. })
  92. })
  93. test("handles environment variable substitution", async () => {
  94. const originalEnv = process.env["TEST_VAR"]
  95. process.env["TEST_VAR"] = "test_theme"
  96. try {
  97. await using tmp = await tmpdir({
  98. init: async (dir) => {
  99. await Bun.write(
  100. path.join(dir, "opencode.json"),
  101. JSON.stringify({
  102. $schema: "https://opencode.ai/config.json",
  103. theme: "{env:TEST_VAR}",
  104. }),
  105. )
  106. },
  107. })
  108. await Instance.provide({
  109. directory: tmp.path,
  110. fn: async () => {
  111. const config = await Config.get()
  112. expect(config.theme).toBe("test_theme")
  113. },
  114. })
  115. } finally {
  116. if (originalEnv !== undefined) {
  117. process.env["TEST_VAR"] = originalEnv
  118. } else {
  119. delete process.env["TEST_VAR"]
  120. }
  121. }
  122. })
  123. test("preserves env variables when adding $schema to config", async () => {
  124. const originalEnv = process.env["PRESERVE_VAR"]
  125. process.env["PRESERVE_VAR"] = "secret_value"
  126. try {
  127. await using tmp = await tmpdir({
  128. init: async (dir) => {
  129. // Config without $schema - should trigger auto-add
  130. await Bun.write(
  131. path.join(dir, "opencode.json"),
  132. JSON.stringify({
  133. theme: "{env:PRESERVE_VAR}",
  134. }),
  135. )
  136. },
  137. })
  138. await Instance.provide({
  139. directory: tmp.path,
  140. fn: async () => {
  141. const config = await Config.get()
  142. expect(config.theme).toBe("secret_value")
  143. // Read the file to verify the env variable was preserved
  144. const content = await Bun.file(path.join(tmp.path, "opencode.json")).text()
  145. expect(content).toContain("{env:PRESERVE_VAR}")
  146. expect(content).not.toContain("secret_value")
  147. expect(content).toContain("$schema")
  148. },
  149. })
  150. } finally {
  151. if (originalEnv !== undefined) {
  152. process.env["PRESERVE_VAR"] = originalEnv
  153. } else {
  154. delete process.env["PRESERVE_VAR"]
  155. }
  156. }
  157. })
  158. test("handles file inclusion substitution", async () => {
  159. await using tmp = await tmpdir({
  160. init: async (dir) => {
  161. await Bun.write(path.join(dir, "included.txt"), "test_theme")
  162. await Bun.write(
  163. path.join(dir, "opencode.json"),
  164. JSON.stringify({
  165. $schema: "https://opencode.ai/config.json",
  166. theme: "{file:included.txt}",
  167. }),
  168. )
  169. },
  170. })
  171. await Instance.provide({
  172. directory: tmp.path,
  173. fn: async () => {
  174. const config = await Config.get()
  175. expect(config.theme).toBe("test_theme")
  176. },
  177. })
  178. })
  179. test("validates config schema and throws on invalid fields", async () => {
  180. await using tmp = await tmpdir({
  181. init: async (dir) => {
  182. await Bun.write(
  183. path.join(dir, "opencode.json"),
  184. JSON.stringify({
  185. $schema: "https://opencode.ai/config.json",
  186. invalid_field: "should cause error",
  187. }),
  188. )
  189. },
  190. })
  191. await Instance.provide({
  192. directory: tmp.path,
  193. fn: async () => {
  194. // Strict schema should throw an error for invalid fields
  195. await expect(Config.get()).rejects.toThrow()
  196. },
  197. })
  198. })
  199. test("throws error for invalid JSON", async () => {
  200. await using tmp = await tmpdir({
  201. init: async (dir) => {
  202. await Bun.write(path.join(dir, "opencode.json"), "{ invalid json }")
  203. },
  204. })
  205. await Instance.provide({
  206. directory: tmp.path,
  207. fn: async () => {
  208. await expect(Config.get()).rejects.toThrow()
  209. },
  210. })
  211. })
  212. test("handles agent configuration", async () => {
  213. await using tmp = await tmpdir({
  214. init: async (dir) => {
  215. await Bun.write(
  216. path.join(dir, "opencode.json"),
  217. JSON.stringify({
  218. $schema: "https://opencode.ai/config.json",
  219. agent: {
  220. test_agent: {
  221. model: "test/model",
  222. temperature: 0.7,
  223. description: "test agent",
  224. },
  225. },
  226. }),
  227. )
  228. },
  229. })
  230. await Instance.provide({
  231. directory: tmp.path,
  232. fn: async () => {
  233. const config = await Config.get()
  234. expect(config.agent?.["test_agent"]).toEqual(
  235. expect.objectContaining({
  236. model: "test/model",
  237. temperature: 0.7,
  238. description: "test agent",
  239. }),
  240. )
  241. },
  242. })
  243. })
  244. test("handles command configuration", async () => {
  245. await using tmp = await tmpdir({
  246. init: async (dir) => {
  247. await Bun.write(
  248. path.join(dir, "opencode.json"),
  249. JSON.stringify({
  250. $schema: "https://opencode.ai/config.json",
  251. command: {
  252. test_command: {
  253. template: "test template",
  254. description: "test command",
  255. agent: "test_agent",
  256. },
  257. },
  258. }),
  259. )
  260. },
  261. })
  262. await Instance.provide({
  263. directory: tmp.path,
  264. fn: async () => {
  265. const config = await Config.get()
  266. expect(config.command?.["test_command"]).toEqual({
  267. template: "test template",
  268. description: "test command",
  269. agent: "test_agent",
  270. })
  271. },
  272. })
  273. })
  274. test("migrates autoshare to share field", async () => {
  275. await using tmp = await tmpdir({
  276. init: async (dir) => {
  277. await Bun.write(
  278. path.join(dir, "opencode.json"),
  279. JSON.stringify({
  280. $schema: "https://opencode.ai/config.json",
  281. autoshare: true,
  282. }),
  283. )
  284. },
  285. })
  286. await Instance.provide({
  287. directory: tmp.path,
  288. fn: async () => {
  289. const config = await Config.get()
  290. expect(config.share).toBe("auto")
  291. expect(config.autoshare).toBe(true)
  292. },
  293. })
  294. })
  295. test("migrates mode field to agent field", async () => {
  296. await using tmp = await tmpdir({
  297. init: async (dir) => {
  298. await Bun.write(
  299. path.join(dir, "opencode.json"),
  300. JSON.stringify({
  301. $schema: "https://opencode.ai/config.json",
  302. mode: {
  303. test_mode: {
  304. model: "test/model",
  305. temperature: 0.5,
  306. },
  307. },
  308. }),
  309. )
  310. },
  311. })
  312. await Instance.provide({
  313. directory: tmp.path,
  314. fn: async () => {
  315. const config = await Config.get()
  316. expect(config.agent?.["test_mode"]).toEqual({
  317. model: "test/model",
  318. temperature: 0.5,
  319. mode: "primary",
  320. options: {},
  321. permission: {},
  322. })
  323. },
  324. })
  325. })
  326. test("loads config from .opencode directory", async () => {
  327. await using tmp = await tmpdir({
  328. init: async (dir) => {
  329. const opencodeDir = path.join(dir, ".opencode")
  330. await fs.mkdir(opencodeDir, { recursive: true })
  331. const agentDir = path.join(opencodeDir, "agent")
  332. await fs.mkdir(agentDir, { recursive: true })
  333. await Bun.write(
  334. path.join(agentDir, "test.md"),
  335. `---
  336. model: test/model
  337. ---
  338. Test agent prompt`,
  339. )
  340. },
  341. })
  342. await Instance.provide({
  343. directory: tmp.path,
  344. fn: async () => {
  345. const config = await Config.get()
  346. expect(config.agent?.["test"]).toEqual(
  347. expect.objectContaining({
  348. name: "test",
  349. model: "test/model",
  350. prompt: "Test agent prompt",
  351. }),
  352. )
  353. },
  354. })
  355. })
  356. test("loads agents from .opencode/agents (plural)", async () => {
  357. await using tmp = await tmpdir({
  358. init: async (dir) => {
  359. const opencodeDir = path.join(dir, ".opencode")
  360. await fs.mkdir(opencodeDir, { recursive: true })
  361. const agentsDir = path.join(opencodeDir, "agents")
  362. await fs.mkdir(path.join(agentsDir, "nested"), { recursive: true })
  363. await Bun.write(
  364. path.join(agentsDir, "helper.md"),
  365. `---
  366. model: test/model
  367. mode: subagent
  368. ---
  369. Helper agent prompt`,
  370. )
  371. await Bun.write(
  372. path.join(agentsDir, "nested", "child.md"),
  373. `---
  374. model: test/model
  375. mode: subagent
  376. ---
  377. Nested agent prompt`,
  378. )
  379. },
  380. })
  381. await Instance.provide({
  382. directory: tmp.path,
  383. fn: async () => {
  384. const config = await Config.get()
  385. expect(config.agent?.["helper"]).toMatchObject({
  386. name: "helper",
  387. model: "test/model",
  388. mode: "subagent",
  389. prompt: "Helper agent prompt",
  390. })
  391. expect(config.agent?.["nested/child"]).toMatchObject({
  392. name: "nested/child",
  393. model: "test/model",
  394. mode: "subagent",
  395. prompt: "Nested agent prompt",
  396. })
  397. },
  398. })
  399. })
  400. test("loads commands from .opencode/command (singular)", async () => {
  401. await using tmp = await tmpdir({
  402. init: async (dir) => {
  403. const opencodeDir = path.join(dir, ".opencode")
  404. await fs.mkdir(opencodeDir, { recursive: true })
  405. const commandDir = path.join(opencodeDir, "command")
  406. await fs.mkdir(path.join(commandDir, "nested"), { recursive: true })
  407. await Bun.write(
  408. path.join(commandDir, "hello.md"),
  409. `---
  410. description: Test command
  411. ---
  412. Hello from singular command`,
  413. )
  414. await Bun.write(
  415. path.join(commandDir, "nested", "child.md"),
  416. `---
  417. description: Nested command
  418. ---
  419. Nested command template`,
  420. )
  421. },
  422. })
  423. await Instance.provide({
  424. directory: tmp.path,
  425. fn: async () => {
  426. const config = await Config.get()
  427. expect(config.command?.["hello"]).toEqual({
  428. description: "Test command",
  429. template: "Hello from singular command",
  430. })
  431. expect(config.command?.["nested/child"]).toEqual({
  432. description: "Nested command",
  433. template: "Nested command template",
  434. })
  435. },
  436. })
  437. })
  438. test("loads commands from .opencode/commands (plural)", async () => {
  439. await using tmp = await tmpdir({
  440. init: async (dir) => {
  441. const opencodeDir = path.join(dir, ".opencode")
  442. await fs.mkdir(opencodeDir, { recursive: true })
  443. const commandsDir = path.join(opencodeDir, "commands")
  444. await fs.mkdir(path.join(commandsDir, "nested"), { recursive: true })
  445. await Bun.write(
  446. path.join(commandsDir, "hello.md"),
  447. `---
  448. description: Test command
  449. ---
  450. Hello from plural commands`,
  451. )
  452. await Bun.write(
  453. path.join(commandsDir, "nested", "child.md"),
  454. `---
  455. description: Nested command
  456. ---
  457. Nested command template`,
  458. )
  459. },
  460. })
  461. await Instance.provide({
  462. directory: tmp.path,
  463. fn: async () => {
  464. const config = await Config.get()
  465. expect(config.command?.["hello"]).toEqual({
  466. description: "Test command",
  467. template: "Hello from plural commands",
  468. })
  469. expect(config.command?.["nested/child"]).toEqual({
  470. description: "Nested command",
  471. template: "Nested command template",
  472. })
  473. },
  474. })
  475. })
  476. test("updates config and writes to file", async () => {
  477. await using tmp = await tmpdir()
  478. await Instance.provide({
  479. directory: tmp.path,
  480. fn: async () => {
  481. const newConfig = { model: "updated/model" }
  482. await Config.update(newConfig as any)
  483. const writtenConfig = JSON.parse(await Bun.file(path.join(tmp.path, "config.json")).text())
  484. expect(writtenConfig.model).toBe("updated/model")
  485. },
  486. })
  487. })
  488. test("gets config directories", async () => {
  489. await using tmp = await tmpdir()
  490. await Instance.provide({
  491. directory: tmp.path,
  492. fn: async () => {
  493. const dirs = await Config.directories()
  494. expect(dirs.length).toBeGreaterThanOrEqual(1)
  495. },
  496. })
  497. })
  498. test("resolves scoped npm plugins in config", async () => {
  499. await using tmp = await tmpdir({
  500. init: async (dir) => {
  501. const pluginDir = path.join(dir, "node_modules", "@scope", "plugin")
  502. await fs.mkdir(pluginDir, { recursive: true })
  503. await Bun.write(
  504. path.join(dir, "package.json"),
  505. JSON.stringify({ name: "config-fixture", version: "1.0.0", type: "module" }, null, 2),
  506. )
  507. await Bun.write(
  508. path.join(pluginDir, "package.json"),
  509. JSON.stringify(
  510. {
  511. name: "@scope/plugin",
  512. version: "1.0.0",
  513. type: "module",
  514. main: "./index.js",
  515. },
  516. null,
  517. 2,
  518. ),
  519. )
  520. await Bun.write(path.join(pluginDir, "index.js"), "export default {}\n")
  521. await Bun.write(
  522. path.join(dir, "opencode.json"),
  523. JSON.stringify({ $schema: "https://opencode.ai/config.json", plugin: ["@scope/plugin"] }, null, 2),
  524. )
  525. },
  526. })
  527. await Instance.provide({
  528. directory: tmp.path,
  529. fn: async () => {
  530. const config = await Config.get()
  531. const pluginEntries = config.plugin ?? []
  532. const baseUrl = pathToFileURL(path.join(tmp.path, "opencode.json")).href
  533. const expected = import.meta.resolve("@scope/plugin", baseUrl)
  534. expect(pluginEntries.includes(expected)).toBe(true)
  535. const scopedEntry = pluginEntries.find((entry) => entry === expected)
  536. expect(scopedEntry).toBeDefined()
  537. expect(scopedEntry?.includes("/node_modules/@scope/plugin/")).toBe(true)
  538. },
  539. })
  540. })
  541. test("merges plugin arrays from global and local configs", async () => {
  542. await using tmp = await tmpdir({
  543. init: async (dir) => {
  544. // Create a nested project structure with local .opencode config
  545. const projectDir = path.join(dir, "project")
  546. const opencodeDir = path.join(projectDir, ".opencode")
  547. await fs.mkdir(opencodeDir, { recursive: true })
  548. // Global config with plugins
  549. await Bun.write(
  550. path.join(dir, "opencode.json"),
  551. JSON.stringify({
  552. $schema: "https://opencode.ai/config.json",
  553. plugin: ["global-plugin-1", "global-plugin-2"],
  554. }),
  555. )
  556. // Local .opencode config with different plugins
  557. await Bun.write(
  558. path.join(opencodeDir, "opencode.json"),
  559. JSON.stringify({
  560. $schema: "https://opencode.ai/config.json",
  561. plugin: ["local-plugin-1"],
  562. }),
  563. )
  564. },
  565. })
  566. await Instance.provide({
  567. directory: path.join(tmp.path, "project"),
  568. fn: async () => {
  569. const config = await Config.get()
  570. const plugins = config.plugin ?? []
  571. // Should contain both global and local plugins
  572. expect(plugins.some((p) => p.includes("global-plugin-1"))).toBe(true)
  573. expect(plugins.some((p) => p.includes("global-plugin-2"))).toBe(true)
  574. expect(plugins.some((p) => p.includes("local-plugin-1"))).toBe(true)
  575. // Should have all 3 plugins (not replaced, but merged)
  576. const pluginNames = plugins.filter((p) => p.includes("global-plugin") || p.includes("local-plugin"))
  577. expect(pluginNames.length).toBeGreaterThanOrEqual(3)
  578. },
  579. })
  580. })
  581. test("does not error when only custom agent is a subagent", async () => {
  582. await using tmp = await tmpdir({
  583. init: async (dir) => {
  584. const opencodeDir = path.join(dir, ".opencode")
  585. await fs.mkdir(opencodeDir, { recursive: true })
  586. const agentDir = path.join(opencodeDir, "agent")
  587. await fs.mkdir(agentDir, { recursive: true })
  588. await Bun.write(
  589. path.join(agentDir, "helper.md"),
  590. `---
  591. model: test/model
  592. mode: subagent
  593. ---
  594. Helper subagent prompt`,
  595. )
  596. },
  597. })
  598. await Instance.provide({
  599. directory: tmp.path,
  600. fn: async () => {
  601. const config = await Config.get()
  602. expect(config.agent?.["helper"]).toMatchObject({
  603. name: "helper",
  604. model: "test/model",
  605. mode: "subagent",
  606. prompt: "Helper subagent prompt",
  607. })
  608. },
  609. })
  610. })
  611. test("merges instructions arrays from global and local configs", async () => {
  612. await using tmp = await tmpdir({
  613. init: async (dir) => {
  614. const projectDir = path.join(dir, "project")
  615. const opencodeDir = path.join(projectDir, ".opencode")
  616. await fs.mkdir(opencodeDir, { recursive: true })
  617. await Bun.write(
  618. path.join(dir, "opencode.json"),
  619. JSON.stringify({
  620. $schema: "https://opencode.ai/config.json",
  621. instructions: ["global-instructions.md", "shared-rules.md"],
  622. }),
  623. )
  624. await Bun.write(
  625. path.join(opencodeDir, "opencode.json"),
  626. JSON.stringify({
  627. $schema: "https://opencode.ai/config.json",
  628. instructions: ["local-instructions.md"],
  629. }),
  630. )
  631. },
  632. })
  633. await Instance.provide({
  634. directory: path.join(tmp.path, "project"),
  635. fn: async () => {
  636. const config = await Config.get()
  637. const instructions = config.instructions ?? []
  638. expect(instructions).toContain("global-instructions.md")
  639. expect(instructions).toContain("shared-rules.md")
  640. expect(instructions).toContain("local-instructions.md")
  641. expect(instructions.length).toBe(3)
  642. },
  643. })
  644. })
  645. test("deduplicates duplicate instructions from global and local configs", async () => {
  646. await using tmp = await tmpdir({
  647. init: async (dir) => {
  648. const projectDir = path.join(dir, "project")
  649. const opencodeDir = path.join(projectDir, ".opencode")
  650. await fs.mkdir(opencodeDir, { recursive: true })
  651. await Bun.write(
  652. path.join(dir, "opencode.json"),
  653. JSON.stringify({
  654. $schema: "https://opencode.ai/config.json",
  655. instructions: ["duplicate.md", "global-only.md"],
  656. }),
  657. )
  658. await Bun.write(
  659. path.join(opencodeDir, "opencode.json"),
  660. JSON.stringify({
  661. $schema: "https://opencode.ai/config.json",
  662. instructions: ["duplicate.md", "local-only.md"],
  663. }),
  664. )
  665. },
  666. })
  667. await Instance.provide({
  668. directory: path.join(tmp.path, "project"),
  669. fn: async () => {
  670. const config = await Config.get()
  671. const instructions = config.instructions ?? []
  672. expect(instructions).toContain("global-only.md")
  673. expect(instructions).toContain("local-only.md")
  674. expect(instructions).toContain("duplicate.md")
  675. const duplicates = instructions.filter((i) => i === "duplicate.md")
  676. expect(duplicates.length).toBe(1)
  677. expect(instructions.length).toBe(3)
  678. },
  679. })
  680. })
  681. test("deduplicates duplicate plugins from global and local configs", async () => {
  682. await using tmp = await tmpdir({
  683. init: async (dir) => {
  684. // Create a nested project structure with local .opencode config
  685. const projectDir = path.join(dir, "project")
  686. const opencodeDir = path.join(projectDir, ".opencode")
  687. await fs.mkdir(opencodeDir, { recursive: true })
  688. // Global config with plugins
  689. await Bun.write(
  690. path.join(dir, "opencode.json"),
  691. JSON.stringify({
  692. $schema: "https://opencode.ai/config.json",
  693. plugin: ["duplicate-plugin", "global-plugin-1"],
  694. }),
  695. )
  696. // Local .opencode config with some overlapping plugins
  697. await Bun.write(
  698. path.join(opencodeDir, "opencode.json"),
  699. JSON.stringify({
  700. $schema: "https://opencode.ai/config.json",
  701. plugin: ["duplicate-plugin", "local-plugin-1"],
  702. }),
  703. )
  704. },
  705. })
  706. await Instance.provide({
  707. directory: path.join(tmp.path, "project"),
  708. fn: async () => {
  709. const config = await Config.get()
  710. const plugins = config.plugin ?? []
  711. // Should contain all unique plugins
  712. expect(plugins.some((p) => p.includes("global-plugin-1"))).toBe(true)
  713. expect(plugins.some((p) => p.includes("local-plugin-1"))).toBe(true)
  714. expect(plugins.some((p) => p.includes("duplicate-plugin"))).toBe(true)
  715. // Should deduplicate the duplicate plugin
  716. const duplicatePlugins = plugins.filter((p) => p.includes("duplicate-plugin"))
  717. expect(duplicatePlugins.length).toBe(1)
  718. // Should have exactly 3 unique plugins
  719. const pluginNames = plugins.filter(
  720. (p) => p.includes("global-plugin") || p.includes("local-plugin") || p.includes("duplicate-plugin"),
  721. )
  722. expect(pluginNames.length).toBe(3)
  723. },
  724. })
  725. })
  726. // Legacy tools migration tests
  727. test("migrates legacy tools config to permissions - allow", async () => {
  728. await using tmp = await tmpdir({
  729. init: async (dir) => {
  730. await Bun.write(
  731. path.join(dir, "opencode.json"),
  732. JSON.stringify({
  733. $schema: "https://opencode.ai/config.json",
  734. agent: {
  735. test: {
  736. tools: {
  737. bash: true,
  738. read: true,
  739. },
  740. },
  741. },
  742. }),
  743. )
  744. },
  745. })
  746. await Instance.provide({
  747. directory: tmp.path,
  748. fn: async () => {
  749. const config = await Config.get()
  750. expect(config.agent?.["test"]?.permission).toEqual({
  751. bash: "allow",
  752. read: "allow",
  753. })
  754. },
  755. })
  756. })
  757. test("migrates legacy tools config to permissions - deny", async () => {
  758. await using tmp = await tmpdir({
  759. init: async (dir) => {
  760. await Bun.write(
  761. path.join(dir, "opencode.json"),
  762. JSON.stringify({
  763. $schema: "https://opencode.ai/config.json",
  764. agent: {
  765. test: {
  766. tools: {
  767. bash: false,
  768. webfetch: false,
  769. },
  770. },
  771. },
  772. }),
  773. )
  774. },
  775. })
  776. await Instance.provide({
  777. directory: tmp.path,
  778. fn: async () => {
  779. const config = await Config.get()
  780. expect(config.agent?.["test"]?.permission).toEqual({
  781. bash: "deny",
  782. webfetch: "deny",
  783. })
  784. },
  785. })
  786. })
  787. test("migrates legacy write tool to edit permission", async () => {
  788. await using tmp = await tmpdir({
  789. init: async (dir) => {
  790. await Bun.write(
  791. path.join(dir, "opencode.json"),
  792. JSON.stringify({
  793. $schema: "https://opencode.ai/config.json",
  794. agent: {
  795. test: {
  796. tools: {
  797. write: true,
  798. },
  799. },
  800. },
  801. }),
  802. )
  803. },
  804. })
  805. await Instance.provide({
  806. directory: tmp.path,
  807. fn: async () => {
  808. const config = await Config.get()
  809. expect(config.agent?.["test"]?.permission).toEqual({
  810. edit: "allow",
  811. })
  812. },
  813. })
  814. })
  815. test("migrates legacy edit tool to edit permission", async () => {
  816. await using tmp = await tmpdir({
  817. init: async (dir) => {
  818. await Bun.write(
  819. path.join(dir, "opencode.json"),
  820. JSON.stringify({
  821. $schema: "https://opencode.ai/config.json",
  822. agent: {
  823. test: {
  824. tools: {
  825. edit: false,
  826. },
  827. },
  828. },
  829. }),
  830. )
  831. },
  832. })
  833. await Instance.provide({
  834. directory: tmp.path,
  835. fn: async () => {
  836. const config = await Config.get()
  837. expect(config.agent?.["test"]?.permission).toEqual({
  838. edit: "deny",
  839. })
  840. },
  841. })
  842. })
  843. test("migrates legacy patch tool to edit permission", async () => {
  844. await using tmp = await tmpdir({
  845. init: async (dir) => {
  846. await Bun.write(
  847. path.join(dir, "opencode.json"),
  848. JSON.stringify({
  849. $schema: "https://opencode.ai/config.json",
  850. agent: {
  851. test: {
  852. tools: {
  853. patch: true,
  854. },
  855. },
  856. },
  857. }),
  858. )
  859. },
  860. })
  861. await Instance.provide({
  862. directory: tmp.path,
  863. fn: async () => {
  864. const config = await Config.get()
  865. expect(config.agent?.["test"]?.permission).toEqual({
  866. edit: "allow",
  867. })
  868. },
  869. })
  870. })
  871. test("migrates legacy multiedit tool to edit permission", async () => {
  872. await using tmp = await tmpdir({
  873. init: async (dir) => {
  874. await Bun.write(
  875. path.join(dir, "opencode.json"),
  876. JSON.stringify({
  877. $schema: "https://opencode.ai/config.json",
  878. agent: {
  879. test: {
  880. tools: {
  881. multiedit: false,
  882. },
  883. },
  884. },
  885. }),
  886. )
  887. },
  888. })
  889. await Instance.provide({
  890. directory: tmp.path,
  891. fn: async () => {
  892. const config = await Config.get()
  893. expect(config.agent?.["test"]?.permission).toEqual({
  894. edit: "deny",
  895. })
  896. },
  897. })
  898. })
  899. test("migrates mixed legacy tools config", async () => {
  900. await using tmp = await tmpdir({
  901. init: async (dir) => {
  902. await Bun.write(
  903. path.join(dir, "opencode.json"),
  904. JSON.stringify({
  905. $schema: "https://opencode.ai/config.json",
  906. agent: {
  907. test: {
  908. tools: {
  909. bash: true,
  910. write: true,
  911. read: false,
  912. webfetch: true,
  913. },
  914. },
  915. },
  916. }),
  917. )
  918. },
  919. })
  920. await Instance.provide({
  921. directory: tmp.path,
  922. fn: async () => {
  923. const config = await Config.get()
  924. expect(config.agent?.["test"]?.permission).toEqual({
  925. bash: "allow",
  926. edit: "allow",
  927. read: "deny",
  928. webfetch: "allow",
  929. })
  930. },
  931. })
  932. })
  933. test("merges legacy tools with existing permission config", async () => {
  934. await using tmp = await tmpdir({
  935. init: async (dir) => {
  936. await Bun.write(
  937. path.join(dir, "opencode.json"),
  938. JSON.stringify({
  939. $schema: "https://opencode.ai/config.json",
  940. agent: {
  941. test: {
  942. permission: {
  943. glob: "allow",
  944. },
  945. tools: {
  946. bash: true,
  947. },
  948. },
  949. },
  950. }),
  951. )
  952. },
  953. })
  954. await Instance.provide({
  955. directory: tmp.path,
  956. fn: async () => {
  957. const config = await Config.get()
  958. expect(config.agent?.["test"]?.permission).toEqual({
  959. glob: "allow",
  960. bash: "allow",
  961. })
  962. },
  963. })
  964. })
  965. test("permission config preserves key order", async () => {
  966. await using tmp = await tmpdir({
  967. init: async (dir) => {
  968. await Bun.write(
  969. path.join(dir, "opencode.json"),
  970. JSON.stringify({
  971. $schema: "https://opencode.ai/config.json",
  972. permission: {
  973. "*": "deny",
  974. edit: "ask",
  975. write: "ask",
  976. external_directory: "ask",
  977. read: "allow",
  978. todowrite: "allow",
  979. todoread: "allow",
  980. "thoughts_*": "allow",
  981. "reasoning_model_*": "allow",
  982. "tools_*": "allow",
  983. "pr_comments_*": "allow",
  984. },
  985. }),
  986. )
  987. },
  988. })
  989. await Instance.provide({
  990. directory: tmp.path,
  991. fn: async () => {
  992. const config = await Config.get()
  993. expect(Object.keys(config.permission!)).toEqual([
  994. "*",
  995. "edit",
  996. "write",
  997. "external_directory",
  998. "read",
  999. "todowrite",
  1000. "todoread",
  1001. "thoughts_*",
  1002. "reasoning_model_*",
  1003. "tools_*",
  1004. "pr_comments_*",
  1005. ])
  1006. },
  1007. })
  1008. })
  1009. // MCP config merging tests
  1010. test("project config can override MCP server enabled status", async () => {
  1011. await using tmp = await tmpdir({
  1012. init: async (dir) => {
  1013. // Simulates a base config (like from remote .well-known) with disabled MCP
  1014. await Bun.write(
  1015. path.join(dir, "opencode.jsonc"),
  1016. JSON.stringify({
  1017. $schema: "https://opencode.ai/config.json",
  1018. mcp: {
  1019. jira: {
  1020. type: "remote",
  1021. url: "https://jira.example.com/mcp",
  1022. enabled: false,
  1023. },
  1024. wiki: {
  1025. type: "remote",
  1026. url: "https://wiki.example.com/mcp",
  1027. enabled: false,
  1028. },
  1029. },
  1030. }),
  1031. )
  1032. // Project config enables just jira
  1033. await Bun.write(
  1034. path.join(dir, "opencode.json"),
  1035. JSON.stringify({
  1036. $schema: "https://opencode.ai/config.json",
  1037. mcp: {
  1038. jira: {
  1039. type: "remote",
  1040. url: "https://jira.example.com/mcp",
  1041. enabled: true,
  1042. },
  1043. },
  1044. }),
  1045. )
  1046. },
  1047. })
  1048. await Instance.provide({
  1049. directory: tmp.path,
  1050. fn: async () => {
  1051. const config = await Config.get()
  1052. // jira should be enabled (overridden by project config)
  1053. expect(config.mcp?.jira).toEqual({
  1054. type: "remote",
  1055. url: "https://jira.example.com/mcp",
  1056. enabled: true,
  1057. })
  1058. // wiki should still be disabled (not overridden)
  1059. expect(config.mcp?.wiki).toEqual({
  1060. type: "remote",
  1061. url: "https://wiki.example.com/mcp",
  1062. enabled: false,
  1063. })
  1064. },
  1065. })
  1066. })
  1067. test("MCP config deep merges preserving base config properties", async () => {
  1068. await using tmp = await tmpdir({
  1069. init: async (dir) => {
  1070. // Base config with full MCP definition
  1071. await Bun.write(
  1072. path.join(dir, "opencode.jsonc"),
  1073. JSON.stringify({
  1074. $schema: "https://opencode.ai/config.json",
  1075. mcp: {
  1076. myserver: {
  1077. type: "remote",
  1078. url: "https://myserver.example.com/mcp",
  1079. enabled: false,
  1080. headers: {
  1081. "X-Custom-Header": "value",
  1082. },
  1083. },
  1084. },
  1085. }),
  1086. )
  1087. // Override just enables it, should preserve other properties
  1088. await Bun.write(
  1089. path.join(dir, "opencode.json"),
  1090. JSON.stringify({
  1091. $schema: "https://opencode.ai/config.json",
  1092. mcp: {
  1093. myserver: {
  1094. type: "remote",
  1095. url: "https://myserver.example.com/mcp",
  1096. enabled: true,
  1097. },
  1098. },
  1099. }),
  1100. )
  1101. },
  1102. })
  1103. await Instance.provide({
  1104. directory: tmp.path,
  1105. fn: async () => {
  1106. const config = await Config.get()
  1107. expect(config.mcp?.myserver).toEqual({
  1108. type: "remote",
  1109. url: "https://myserver.example.com/mcp",
  1110. enabled: true,
  1111. headers: {
  1112. "X-Custom-Header": "value",
  1113. },
  1114. })
  1115. },
  1116. })
  1117. })
  1118. test("local .opencode config can override MCP from project config", async () => {
  1119. await using tmp = await tmpdir({
  1120. init: async (dir) => {
  1121. // Project config with disabled MCP
  1122. await Bun.write(
  1123. path.join(dir, "opencode.json"),
  1124. JSON.stringify({
  1125. $schema: "https://opencode.ai/config.json",
  1126. mcp: {
  1127. docs: {
  1128. type: "remote",
  1129. url: "https://docs.example.com/mcp",
  1130. enabled: false,
  1131. },
  1132. },
  1133. }),
  1134. )
  1135. // Local .opencode directory config enables it
  1136. const opencodeDir = path.join(dir, ".opencode")
  1137. await fs.mkdir(opencodeDir, { recursive: true })
  1138. await Bun.write(
  1139. path.join(opencodeDir, "opencode.json"),
  1140. JSON.stringify({
  1141. $schema: "https://opencode.ai/config.json",
  1142. mcp: {
  1143. docs: {
  1144. type: "remote",
  1145. url: "https://docs.example.com/mcp",
  1146. enabled: true,
  1147. },
  1148. },
  1149. }),
  1150. )
  1151. },
  1152. })
  1153. await Instance.provide({
  1154. directory: tmp.path,
  1155. fn: async () => {
  1156. const config = await Config.get()
  1157. expect(config.mcp?.docs?.enabled).toBe(true)
  1158. },
  1159. })
  1160. })
  1161. test("project config overrides remote well-known config", async () => {
  1162. const originalFetch = globalThis.fetch
  1163. let fetchedUrl: string | undefined
  1164. const mockFetch = mock((url: string | URL | Request) => {
  1165. const urlStr = url.toString()
  1166. if (urlStr.includes(".well-known/opencode")) {
  1167. fetchedUrl = urlStr
  1168. return Promise.resolve(
  1169. new Response(
  1170. JSON.stringify({
  1171. config: {
  1172. mcp: {
  1173. jira: {
  1174. type: "remote",
  1175. url: "https://jira.example.com/mcp",
  1176. enabled: false,
  1177. },
  1178. },
  1179. },
  1180. }),
  1181. { status: 200 },
  1182. ),
  1183. )
  1184. }
  1185. return originalFetch(url)
  1186. })
  1187. globalThis.fetch = mockFetch as unknown as typeof fetch
  1188. const originalAuthAll = Auth.all
  1189. Auth.all = mock(() =>
  1190. Promise.resolve({
  1191. "https://example.com": {
  1192. type: "wellknown" as const,
  1193. key: "TEST_TOKEN",
  1194. token: "test-token",
  1195. },
  1196. }),
  1197. )
  1198. try {
  1199. await using tmp = await tmpdir({
  1200. git: true,
  1201. init: async (dir) => {
  1202. // Project config enables jira (overriding remote default)
  1203. await Bun.write(
  1204. path.join(dir, "opencode.json"),
  1205. JSON.stringify({
  1206. $schema: "https://opencode.ai/config.json",
  1207. mcp: {
  1208. jira: {
  1209. type: "remote",
  1210. url: "https://jira.example.com/mcp",
  1211. enabled: true,
  1212. },
  1213. },
  1214. }),
  1215. )
  1216. },
  1217. })
  1218. await Instance.provide({
  1219. directory: tmp.path,
  1220. fn: async () => {
  1221. const config = await Config.get()
  1222. // Verify fetch was called for wellknown config
  1223. expect(fetchedUrl).toBe("https://example.com/.well-known/opencode")
  1224. // Project config (enabled: true) should override remote (enabled: false)
  1225. expect(config.mcp?.jira?.enabled).toBe(true)
  1226. },
  1227. })
  1228. } finally {
  1229. globalThis.fetch = originalFetch
  1230. Auth.all = originalAuthAll
  1231. }
  1232. })
  1233. describe("getPluginName", () => {
  1234. test("extracts name from file:// URL", () => {
  1235. expect(Config.getPluginName("file:///path/to/plugin/foo.js")).toBe("foo")
  1236. expect(Config.getPluginName("file:///path/to/plugin/bar.ts")).toBe("bar")
  1237. expect(Config.getPluginName("file:///some/path/my-plugin.js")).toBe("my-plugin")
  1238. })
  1239. test("extracts name from npm package with version", () => {
  1240. expect(Config.getPluginName("[email protected]")).toBe("oh-my-opencode")
  1241. expect(Config.getPluginName("[email protected]")).toBe("some-plugin")
  1242. expect(Config.getPluginName("plugin@latest")).toBe("plugin")
  1243. })
  1244. test("extracts name from scoped npm package", () => {
  1245. expect(Config.getPluginName("@scope/[email protected]")).toBe("@scope/pkg")
  1246. expect(Config.getPluginName("@opencode/[email protected]")).toBe("@opencode/plugin")
  1247. })
  1248. test("returns full string for package without version", () => {
  1249. expect(Config.getPluginName("some-plugin")).toBe("some-plugin")
  1250. expect(Config.getPluginName("@scope/pkg")).toBe("@scope/pkg")
  1251. })
  1252. })
  1253. describe("deduplicatePlugins", () => {
  1254. test("removes duplicates keeping higher priority (later entries)", () => {
  1255. const plugins = ["[email protected]", "[email protected]", "[email protected]", "[email protected]"]
  1256. const result = Config.deduplicatePlugins(plugins)
  1257. expect(result).toContain("[email protected]")
  1258. expect(result).toContain("[email protected]")
  1259. expect(result).toContain("[email protected]")
  1260. expect(result).not.toContain("[email protected]")
  1261. expect(result.length).toBe(3)
  1262. })
  1263. test("prefers local file over npm package with same name", () => {
  1264. const plugins = ["[email protected]", "file:///project/.opencode/plugin/oh-my-opencode.js"]
  1265. const result = Config.deduplicatePlugins(plugins)
  1266. expect(result.length).toBe(1)
  1267. expect(result[0]).toBe("file:///project/.opencode/plugin/oh-my-opencode.js")
  1268. })
  1269. test("preserves order of remaining plugins", () => {
  1270. const plugins = ["[email protected]", "[email protected]", "[email protected]"]
  1271. const result = Config.deduplicatePlugins(plugins)
  1272. expect(result).toEqual(["[email protected]", "[email protected]", "[email protected]"])
  1273. })
  1274. test("local plugin directory overrides global opencode.json plugin", async () => {
  1275. await using tmp = await tmpdir({
  1276. init: async (dir) => {
  1277. const projectDir = path.join(dir, "project")
  1278. const opencodeDir = path.join(projectDir, ".opencode")
  1279. const pluginDir = path.join(opencodeDir, "plugin")
  1280. await fs.mkdir(pluginDir, { recursive: true })
  1281. await Bun.write(
  1282. path.join(dir, "opencode.json"),
  1283. JSON.stringify({
  1284. $schema: "https://opencode.ai/config.json",
  1285. plugin: ["[email protected]"],
  1286. }),
  1287. )
  1288. await Bun.write(path.join(pluginDir, "my-plugin.js"), "export default {}")
  1289. },
  1290. })
  1291. await Instance.provide({
  1292. directory: path.join(tmp.path, "project"),
  1293. fn: async () => {
  1294. const config = await Config.get()
  1295. const plugins = config.plugin ?? []
  1296. const myPlugins = plugins.filter((p) => Config.getPluginName(p) === "my-plugin")
  1297. expect(myPlugins.length).toBe(1)
  1298. expect(myPlugins[0].startsWith("file://")).toBe(true)
  1299. },
  1300. })
  1301. })
  1302. })