config.test.ts 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383
  1. import { test, expect, describe, mock, afterEach, beforeEach, spyOn } from "bun:test"
  2. import { Deferred, Effect, Fiber, Layer, Option } from "effect"
  3. import { NodeFileSystem, NodePath } from "@effect/platform-node"
  4. import { Config } from "../../src/config/config"
  5. import { Instance } from "../../src/project/instance"
  6. import { Auth } from "../../src/auth"
  7. import { AccessToken, Account, AccountID, OrgID } from "../../src/account"
  8. import { AppFileSystem } from "../../src/filesystem"
  9. import { provideTmpdirInstance } from "../fixture/fixture"
  10. import { tmpdir, tmpdirScoped } from "../fixture/fixture"
  11. import * as CrossSpawnSpawner from "../../src/effect/cross-spawn-spawner"
  12. import { testEffect } from "../lib/effect"
  13. /** Infra layer that provides FileSystem, Path, ChildProcessSpawner for test fixtures */
  14. const infra = CrossSpawnSpawner.defaultLayer.pipe(
  15. Layer.provideMerge(Layer.mergeAll(NodeFileSystem.layer, NodePath.layer)),
  16. )
  17. import path from "path"
  18. import fs from "fs/promises"
  19. import { pathToFileURL } from "url"
  20. import { Global } from "../../src/global"
  21. import { ProjectID } from "../../src/project/schema"
  22. import { Filesystem } from "../../src/util/filesystem"
  23. import * as Network from "../../src/util/network"
  24. import { Npm } from "../../src/npm"
  25. const emptyAccount = Layer.mock(Account.Service)({
  26. active: () => Effect.succeed(Option.none()),
  27. activeOrg: () => Effect.succeed(Option.none()),
  28. })
  29. const emptyAuth = Layer.mock(Auth.Service)({
  30. all: () => Effect.succeed({}),
  31. })
  32. const it = testEffect(
  33. Config.layer.pipe(
  34. Layer.provide(AppFileSystem.defaultLayer),
  35. Layer.provide(emptyAuth),
  36. Layer.provide(emptyAccount),
  37. Layer.provideMerge(infra),
  38. ),
  39. )
  40. const installDeps = (dir: string, input?: Config.InstallInput) =>
  41. Config.Service.use((svc) => svc.installDependencies(dir, input))
  42. // Get managed config directory from environment (set in preload.ts)
  43. const managedConfigDir = process.env.OPENCODE_TEST_MANAGED_CONFIG_DIR!
  44. beforeEach(async () => {
  45. await Config.invalidate(true)
  46. })
  47. afterEach(async () => {
  48. await fs.rm(managedConfigDir, { force: true, recursive: true }).catch(() => {})
  49. await Config.invalidate(true)
  50. })
  51. async function writeManagedSettings(settings: object, filename = "opencode.json") {
  52. await fs.mkdir(managedConfigDir, { recursive: true })
  53. await Filesystem.write(path.join(managedConfigDir, filename), JSON.stringify(settings))
  54. }
  55. async function writeConfig(dir: string, config: object, name = "opencode.json") {
  56. await Filesystem.write(path.join(dir, name), JSON.stringify(config))
  57. }
  58. async function check(map: (dir: string) => string) {
  59. if (process.platform !== "win32") return
  60. await using globalTmp = await tmpdir()
  61. await using tmp = await tmpdir({ git: true, config: { snapshot: true } })
  62. const prev = Global.Path.config
  63. ;(Global.Path as { config: string }).config = globalTmp.path
  64. await Config.invalidate()
  65. try {
  66. await writeConfig(globalTmp.path, {
  67. $schema: "https://opencode.ai/config.json",
  68. snapshot: false,
  69. })
  70. await Instance.provide({
  71. directory: map(tmp.path),
  72. fn: async () => {
  73. const cfg = await Config.get()
  74. expect(cfg.snapshot).toBe(true)
  75. expect(Instance.directory).toBe(Filesystem.resolve(tmp.path))
  76. expect(Instance.project.id).not.toBe(ProjectID.global)
  77. },
  78. })
  79. } finally {
  80. await Instance.disposeAll()
  81. ;(Global.Path as { config: string }).config = prev
  82. await Config.invalidate()
  83. }
  84. }
  85. test("loads config with defaults when no files exist", async () => {
  86. await using tmp = await tmpdir()
  87. await Instance.provide({
  88. directory: tmp.path,
  89. fn: async () => {
  90. const config = await Config.get()
  91. expect(config.username).toBeDefined()
  92. },
  93. })
  94. })
  95. test("loads JSON config file", async () => {
  96. await using tmp = await tmpdir({
  97. init: async (dir) => {
  98. await writeConfig(dir, {
  99. $schema: "https://opencode.ai/config.json",
  100. model: "test/model",
  101. username: "testuser",
  102. })
  103. },
  104. })
  105. await Instance.provide({
  106. directory: tmp.path,
  107. fn: async () => {
  108. const config = await Config.get()
  109. expect(config.model).toBe("test/model")
  110. expect(config.username).toBe("testuser")
  111. },
  112. })
  113. })
  114. test("loads project config from Git Bash and MSYS2 paths on Windows", async () => {
  115. // Git Bash and MSYS2 both use /<drive>/... paths on Windows.
  116. await check((dir) => {
  117. const drive = dir[0].toLowerCase()
  118. const rest = dir.slice(2).replaceAll("\\", "/")
  119. return `/${drive}${rest}`
  120. })
  121. })
  122. test("loads project config from Cygwin paths on Windows", async () => {
  123. await check((dir) => {
  124. const drive = dir[0].toLowerCase()
  125. const rest = dir.slice(2).replaceAll("\\", "/")
  126. return `/cygdrive/${drive}${rest}`
  127. })
  128. })
  129. test("ignores legacy tui keys in opencode config", async () => {
  130. await using tmp = await tmpdir({
  131. init: async (dir) => {
  132. await writeConfig(dir, {
  133. $schema: "https://opencode.ai/config.json",
  134. model: "test/model",
  135. theme: "legacy",
  136. tui: { scroll_speed: 4 },
  137. })
  138. },
  139. })
  140. await Instance.provide({
  141. directory: tmp.path,
  142. fn: async () => {
  143. const config = await Config.get()
  144. expect(config.model).toBe("test/model")
  145. expect((config as Record<string, unknown>).theme).toBeUndefined()
  146. expect((config as Record<string, unknown>).tui).toBeUndefined()
  147. },
  148. })
  149. })
  150. test("loads JSONC config file", async () => {
  151. await using tmp = await tmpdir({
  152. init: async (dir) => {
  153. await Filesystem.write(
  154. path.join(dir, "opencode.jsonc"),
  155. `{
  156. // This is a comment
  157. "$schema": "https://opencode.ai/config.json",
  158. "model": "test/model",
  159. "username": "testuser"
  160. }`,
  161. )
  162. },
  163. })
  164. await Instance.provide({
  165. directory: tmp.path,
  166. fn: async () => {
  167. const config = await Config.get()
  168. expect(config.model).toBe("test/model")
  169. expect(config.username).toBe("testuser")
  170. },
  171. })
  172. })
  173. test("jsonc overrides json in the same directory", async () => {
  174. await using tmp = await tmpdir({
  175. init: async (dir) => {
  176. await writeConfig(
  177. dir,
  178. {
  179. $schema: "https://opencode.ai/config.json",
  180. model: "base",
  181. username: "base",
  182. },
  183. "opencode.jsonc",
  184. )
  185. await writeConfig(dir, {
  186. $schema: "https://opencode.ai/config.json",
  187. model: "override",
  188. })
  189. },
  190. })
  191. await Instance.provide({
  192. directory: tmp.path,
  193. fn: async () => {
  194. const config = await Config.get()
  195. expect(config.model).toBe("base")
  196. expect(config.username).toBe("base")
  197. },
  198. })
  199. })
  200. test("handles environment variable substitution", async () => {
  201. const originalEnv = process.env["TEST_VAR"]
  202. process.env["TEST_VAR"] = "test-user"
  203. try {
  204. await using tmp = await tmpdir({
  205. init: async (dir) => {
  206. await writeConfig(dir, {
  207. $schema: "https://opencode.ai/config.json",
  208. username: "{env:TEST_VAR}",
  209. })
  210. },
  211. })
  212. await Instance.provide({
  213. directory: tmp.path,
  214. fn: async () => {
  215. const config = await Config.get()
  216. expect(config.username).toBe("test-user")
  217. },
  218. })
  219. } finally {
  220. if (originalEnv !== undefined) {
  221. process.env["TEST_VAR"] = originalEnv
  222. } else {
  223. delete process.env["TEST_VAR"]
  224. }
  225. }
  226. })
  227. test("preserves env variables when adding $schema to config", async () => {
  228. const originalEnv = process.env["PRESERVE_VAR"]
  229. process.env["PRESERVE_VAR"] = "secret_value"
  230. try {
  231. await using tmp = await tmpdir({
  232. init: async (dir) => {
  233. // Config without $schema - should trigger auto-add
  234. await Filesystem.write(
  235. path.join(dir, "opencode.json"),
  236. JSON.stringify({
  237. username: "{env:PRESERVE_VAR}",
  238. }),
  239. )
  240. },
  241. })
  242. await Instance.provide({
  243. directory: tmp.path,
  244. fn: async () => {
  245. const config = await Config.get()
  246. expect(config.username).toBe("secret_value")
  247. // Read the file to verify the env variable was preserved
  248. const content = await Filesystem.readText(path.join(tmp.path, "opencode.json"))
  249. expect(content).toContain("{env:PRESERVE_VAR}")
  250. expect(content).not.toContain("secret_value")
  251. expect(content).toContain("$schema")
  252. },
  253. })
  254. } finally {
  255. if (originalEnv !== undefined) {
  256. process.env["PRESERVE_VAR"] = originalEnv
  257. } else {
  258. delete process.env["PRESERVE_VAR"]
  259. }
  260. }
  261. })
  262. test("resolves env templates in account config with account token", async () => {
  263. const originalControlToken = process.env["OPENCODE_CONSOLE_TOKEN"]
  264. const fakeAccount = Layer.mock(Account.Service)({
  265. active: () =>
  266. Effect.succeed(
  267. Option.some({
  268. id: AccountID.make("account-1"),
  269. email: "user@example.com",
  270. url: "https://control.example.com",
  271. active_org_id: OrgID.make("org-1"),
  272. }),
  273. ),
  274. activeOrg: () =>
  275. Effect.succeed(
  276. Option.some({
  277. account: {
  278. id: AccountID.make("account-1"),
  279. email: "user@example.com",
  280. url: "https://control.example.com",
  281. active_org_id: OrgID.make("org-1"),
  282. },
  283. org: {
  284. id: OrgID.make("org-1"),
  285. name: "Example Org",
  286. },
  287. }),
  288. ),
  289. config: () =>
  290. Effect.succeed(
  291. Option.some({
  292. provider: { opencode: { options: { apiKey: "{env:OPENCODE_CONSOLE_TOKEN}" } } },
  293. }),
  294. ),
  295. token: () => Effect.succeed(Option.some(AccessToken.make("st_test_token"))),
  296. })
  297. const layer = Config.layer.pipe(
  298. Layer.provide(AppFileSystem.defaultLayer),
  299. Layer.provide(emptyAuth),
  300. Layer.provide(fakeAccount),
  301. Layer.provideMerge(infra),
  302. )
  303. try {
  304. await provideTmpdirInstance(() =>
  305. Config.Service.use((svc) =>
  306. Effect.gen(function* () {
  307. const config = yield* svc.get()
  308. expect(config.provider?.["opencode"]?.options?.apiKey).toBe("st_test_token")
  309. }),
  310. ),
  311. ).pipe(Effect.scoped, Effect.provide(layer), Effect.runPromise)
  312. } finally {
  313. if (originalControlToken !== undefined) {
  314. process.env["OPENCODE_CONSOLE_TOKEN"] = originalControlToken
  315. } else {
  316. delete process.env["OPENCODE_CONSOLE_TOKEN"]
  317. }
  318. }
  319. })
  320. test("handles file inclusion substitution", async () => {
  321. await using tmp = await tmpdir({
  322. init: async (dir) => {
  323. await Filesystem.write(path.join(dir, "included.txt"), "test-user")
  324. await writeConfig(dir, {
  325. $schema: "https://opencode.ai/config.json",
  326. username: "{file:included.txt}",
  327. })
  328. },
  329. })
  330. await Instance.provide({
  331. directory: tmp.path,
  332. fn: async () => {
  333. const config = await Config.get()
  334. expect(config.username).toBe("test-user")
  335. },
  336. })
  337. })
  338. test("handles file inclusion with replacement tokens", async () => {
  339. await using tmp = await tmpdir({
  340. init: async (dir) => {
  341. await Filesystem.write(path.join(dir, "included.md"), "const out = await Bun.$`echo hi`")
  342. await writeConfig(dir, {
  343. $schema: "https://opencode.ai/config.json",
  344. username: "{file:included.md}",
  345. })
  346. },
  347. })
  348. await Instance.provide({
  349. directory: tmp.path,
  350. fn: async () => {
  351. const config = await Config.get()
  352. expect(config.username).toBe("const out = await Bun.$`echo hi`")
  353. },
  354. })
  355. })
  356. test("validates config schema and throws on invalid fields", async () => {
  357. await using tmp = await tmpdir({
  358. init: async (dir) => {
  359. await writeConfig(dir, {
  360. $schema: "https://opencode.ai/config.json",
  361. invalid_field: "should cause error",
  362. })
  363. },
  364. })
  365. await Instance.provide({
  366. directory: tmp.path,
  367. fn: async () => {
  368. // Strict schema should throw an error for invalid fields
  369. await expect(Config.get()).rejects.toThrow()
  370. },
  371. })
  372. })
  373. test("throws error for invalid JSON", async () => {
  374. await using tmp = await tmpdir({
  375. init: async (dir) => {
  376. await Filesystem.write(path.join(dir, "opencode.json"), "{ invalid json }")
  377. },
  378. })
  379. await Instance.provide({
  380. directory: tmp.path,
  381. fn: async () => {
  382. await expect(Config.get()).rejects.toThrow()
  383. },
  384. })
  385. })
  386. test("handles agent configuration", async () => {
  387. await using tmp = await tmpdir({
  388. init: async (dir) => {
  389. await writeConfig(dir, {
  390. $schema: "https://opencode.ai/config.json",
  391. agent: {
  392. test_agent: {
  393. model: "test/model",
  394. temperature: 0.7,
  395. description: "test agent",
  396. },
  397. },
  398. })
  399. },
  400. })
  401. await Instance.provide({
  402. directory: tmp.path,
  403. fn: async () => {
  404. const config = await Config.get()
  405. expect(config.agent?.["test_agent"]).toEqual(
  406. expect.objectContaining({
  407. model: "test/model",
  408. temperature: 0.7,
  409. description: "test agent",
  410. }),
  411. )
  412. },
  413. })
  414. })
  415. test("treats agent variant as model-scoped setting (not provider option)", async () => {
  416. await using tmp = await tmpdir({
  417. init: async (dir) => {
  418. await writeConfig(dir, {
  419. $schema: "https://opencode.ai/config.json",
  420. agent: {
  421. test_agent: {
  422. model: "openai/gpt-5.2",
  423. variant: "xhigh",
  424. max_tokens: 123,
  425. },
  426. },
  427. })
  428. },
  429. })
  430. await Instance.provide({
  431. directory: tmp.path,
  432. fn: async () => {
  433. const config = await Config.get()
  434. const agent = config.agent?.["test_agent"]
  435. expect(agent?.variant).toBe("xhigh")
  436. expect(agent?.options).toMatchObject({
  437. max_tokens: 123,
  438. })
  439. expect(agent?.options).not.toHaveProperty("variant")
  440. },
  441. })
  442. })
  443. test("handles command configuration", async () => {
  444. await using tmp = await tmpdir({
  445. init: async (dir) => {
  446. await writeConfig(dir, {
  447. $schema: "https://opencode.ai/config.json",
  448. command: {
  449. test_command: {
  450. template: "test template",
  451. description: "test command",
  452. agent: "test_agent",
  453. },
  454. },
  455. })
  456. },
  457. })
  458. await Instance.provide({
  459. directory: tmp.path,
  460. fn: async () => {
  461. const config = await Config.get()
  462. expect(config.command?.["test_command"]).toEqual({
  463. template: "test template",
  464. description: "test command",
  465. agent: "test_agent",
  466. })
  467. },
  468. })
  469. })
  470. test("migrates autoshare to share field", async () => {
  471. await using tmp = await tmpdir({
  472. init: async (dir) => {
  473. await Filesystem.write(
  474. path.join(dir, "opencode.json"),
  475. JSON.stringify({
  476. $schema: "https://opencode.ai/config.json",
  477. autoshare: true,
  478. }),
  479. )
  480. },
  481. })
  482. await Instance.provide({
  483. directory: tmp.path,
  484. fn: async () => {
  485. const config = await Config.get()
  486. expect(config.share).toBe("auto")
  487. expect(config.autoshare).toBe(true)
  488. },
  489. })
  490. })
  491. test("migrates mode field to agent field", async () => {
  492. await using tmp = await tmpdir({
  493. init: async (dir) => {
  494. await Filesystem.write(
  495. path.join(dir, "opencode.json"),
  496. JSON.stringify({
  497. $schema: "https://opencode.ai/config.json",
  498. mode: {
  499. test_mode: {
  500. model: "test/model",
  501. temperature: 0.5,
  502. },
  503. },
  504. }),
  505. )
  506. },
  507. })
  508. await Instance.provide({
  509. directory: tmp.path,
  510. fn: async () => {
  511. const config = await Config.get()
  512. expect(config.agent?.["test_mode"]).toEqual({
  513. model: "test/model",
  514. temperature: 0.5,
  515. mode: "primary",
  516. options: {},
  517. permission: {},
  518. })
  519. },
  520. })
  521. })
  522. test("loads config from .opencode directory", async () => {
  523. await using tmp = await tmpdir({
  524. init: async (dir) => {
  525. const opencodeDir = path.join(dir, ".opencode")
  526. await fs.mkdir(opencodeDir, { recursive: true })
  527. const agentDir = path.join(opencodeDir, "agent")
  528. await fs.mkdir(agentDir, { recursive: true })
  529. await Filesystem.write(
  530. path.join(agentDir, "test.md"),
  531. `---
  532. model: test/model
  533. ---
  534. Test agent prompt`,
  535. )
  536. },
  537. })
  538. await Instance.provide({
  539. directory: tmp.path,
  540. fn: async () => {
  541. const config = await Config.get()
  542. expect(config.agent?.["test"]).toEqual(
  543. expect.objectContaining({
  544. name: "test",
  545. model: "test/model",
  546. prompt: "Test agent prompt",
  547. }),
  548. )
  549. },
  550. })
  551. })
  552. test("loads agents from .opencode/agents (plural)", async () => {
  553. await using tmp = await tmpdir({
  554. init: async (dir) => {
  555. const opencodeDir = path.join(dir, ".opencode")
  556. await fs.mkdir(opencodeDir, { recursive: true })
  557. const agentsDir = path.join(opencodeDir, "agents")
  558. await fs.mkdir(path.join(agentsDir, "nested"), { recursive: true })
  559. await Filesystem.write(
  560. path.join(agentsDir, "helper.md"),
  561. `---
  562. model: test/model
  563. mode: subagent
  564. ---
  565. Helper agent prompt`,
  566. )
  567. await Filesystem.write(
  568. path.join(agentsDir, "nested", "child.md"),
  569. `---
  570. model: test/model
  571. mode: subagent
  572. ---
  573. Nested agent prompt`,
  574. )
  575. },
  576. })
  577. await Instance.provide({
  578. directory: tmp.path,
  579. fn: async () => {
  580. const config = await Config.get()
  581. expect(config.agent?.["helper"]).toMatchObject({
  582. name: "helper",
  583. model: "test/model",
  584. mode: "subagent",
  585. prompt: "Helper agent prompt",
  586. })
  587. expect(config.agent?.["nested/child"]).toMatchObject({
  588. name: "nested/child",
  589. model: "test/model",
  590. mode: "subagent",
  591. prompt: "Nested agent prompt",
  592. })
  593. },
  594. })
  595. })
  596. test("loads commands from .opencode/command (singular)", async () => {
  597. await using tmp = await tmpdir({
  598. init: async (dir) => {
  599. const opencodeDir = path.join(dir, ".opencode")
  600. await fs.mkdir(opencodeDir, { recursive: true })
  601. const commandDir = path.join(opencodeDir, "command")
  602. await fs.mkdir(path.join(commandDir, "nested"), { recursive: true })
  603. await Filesystem.write(
  604. path.join(commandDir, "hello.md"),
  605. `---
  606. description: Test command
  607. ---
  608. Hello from singular command`,
  609. )
  610. await Filesystem.write(
  611. path.join(commandDir, "nested", "child.md"),
  612. `---
  613. description: Nested command
  614. ---
  615. Nested command template`,
  616. )
  617. },
  618. })
  619. await Instance.provide({
  620. directory: tmp.path,
  621. fn: async () => {
  622. const config = await Config.get()
  623. expect(config.command?.["hello"]).toEqual({
  624. description: "Test command",
  625. template: "Hello from singular command",
  626. })
  627. expect(config.command?.["nested/child"]).toEqual({
  628. description: "Nested command",
  629. template: "Nested command template",
  630. })
  631. },
  632. })
  633. })
  634. test("loads commands from .opencode/commands (plural)", async () => {
  635. await using tmp = await tmpdir({
  636. init: async (dir) => {
  637. const opencodeDir = path.join(dir, ".opencode")
  638. await fs.mkdir(opencodeDir, { recursive: true })
  639. const commandsDir = path.join(opencodeDir, "commands")
  640. await fs.mkdir(path.join(commandsDir, "nested"), { recursive: true })
  641. await Filesystem.write(
  642. path.join(commandsDir, "hello.md"),
  643. `---
  644. description: Test command
  645. ---
  646. Hello from plural commands`,
  647. )
  648. await Filesystem.write(
  649. path.join(commandsDir, "nested", "child.md"),
  650. `---
  651. description: Nested command
  652. ---
  653. Nested command template`,
  654. )
  655. },
  656. })
  657. await Instance.provide({
  658. directory: tmp.path,
  659. fn: async () => {
  660. const config = await Config.get()
  661. expect(config.command?.["hello"]).toEqual({
  662. description: "Test command",
  663. template: "Hello from plural commands",
  664. })
  665. expect(config.command?.["nested/child"]).toEqual({
  666. description: "Nested command",
  667. template: "Nested command template",
  668. })
  669. },
  670. })
  671. })
  672. test("updates config and writes to file", async () => {
  673. await using tmp = await tmpdir()
  674. await Instance.provide({
  675. directory: tmp.path,
  676. fn: async () => {
  677. const newConfig = { model: "updated/model" }
  678. await Config.update(newConfig as any)
  679. const writtenConfig = await Filesystem.readJson(path.join(tmp.path, "config.json"))
  680. expect(writtenConfig.model).toBe("updated/model")
  681. },
  682. })
  683. })
  684. test("gets config directories", async () => {
  685. await using tmp = await tmpdir()
  686. await Instance.provide({
  687. directory: tmp.path,
  688. fn: async () => {
  689. const dirs = await Config.directories()
  690. expect(dirs.length).toBeGreaterThanOrEqual(1)
  691. },
  692. })
  693. })
  694. test("does not try to install dependencies in read-only OPENCODE_CONFIG_DIR", async () => {
  695. if (process.platform === "win32") return
  696. await using tmp = await tmpdir<string>({
  697. init: async (dir) => {
  698. const ro = path.join(dir, "readonly")
  699. await fs.mkdir(ro, { recursive: true })
  700. await fs.chmod(ro, 0o555)
  701. return ro
  702. },
  703. dispose: async (dir) => {
  704. const ro = path.join(dir, "readonly")
  705. await fs.chmod(ro, 0o755).catch(() => {})
  706. return ro
  707. },
  708. })
  709. const prev = process.env.OPENCODE_CONFIG_DIR
  710. process.env.OPENCODE_CONFIG_DIR = tmp.extra
  711. try {
  712. await Instance.provide({
  713. directory: tmp.path,
  714. fn: async () => {
  715. await Config.get()
  716. },
  717. })
  718. } finally {
  719. if (prev === undefined) delete process.env.OPENCODE_CONFIG_DIR
  720. else process.env.OPENCODE_CONFIG_DIR = prev
  721. }
  722. })
  723. test("installs dependencies in writable OPENCODE_CONFIG_DIR", async () => {
  724. await using tmp = await tmpdir<string>({
  725. init: async (dir) => {
  726. const cfg = path.join(dir, "configdir")
  727. await fs.mkdir(cfg, { recursive: true })
  728. return cfg
  729. },
  730. })
  731. const prev = process.env.OPENCODE_CONFIG_DIR
  732. process.env.OPENCODE_CONFIG_DIR = tmp.extra
  733. const online = spyOn(Network, "online").mockReturnValue(false)
  734. const install = spyOn(Npm, "install").mockImplementation(async (dir: string) => {
  735. const mod = path.join(dir, "node_modules", "@opencode-ai", "plugin")
  736. await fs.mkdir(mod, { recursive: true })
  737. await Filesystem.write(
  738. path.join(mod, "package.json"),
  739. JSON.stringify({ name: "@opencode-ai/plugin", version: "1.0.0" }),
  740. )
  741. })
  742. try {
  743. await Instance.provide({
  744. directory: tmp.path,
  745. fn: async () => {
  746. await Config.get()
  747. await Config.waitForDependencies()
  748. },
  749. })
  750. expect(await Filesystem.exists(path.join(tmp.extra, "package.json"))).toBe(true)
  751. expect(await Filesystem.exists(path.join(tmp.extra, ".gitignore"))).toBe(true)
  752. expect(await Filesystem.readText(path.join(tmp.extra, ".gitignore"))).toContain("package-lock.json")
  753. } finally {
  754. online.mockRestore()
  755. install.mockRestore()
  756. if (prev === undefined) delete process.env.OPENCODE_CONFIG_DIR
  757. else process.env.OPENCODE_CONFIG_DIR = prev
  758. }
  759. })
  760. it.live("dedupes concurrent config dependency installs for the same dir", () =>
  761. Effect.gen(function* () {
  762. const tmp = yield* tmpdirScoped()
  763. const dir = path.join(tmp, "a")
  764. yield* Effect.promise(() => fs.mkdir(dir, { recursive: true }))
  765. let calls = 0
  766. const online = spyOn(Network, "online").mockReturnValue(false)
  767. const ready = Deferred.makeUnsafe<void>()
  768. const blocked = Deferred.makeUnsafe<void>()
  769. const hold = Deferred.makeUnsafe<void>()
  770. const target = path.normalize(dir)
  771. const run = spyOn(Npm, "install").mockImplementation(async (d: string) => {
  772. if (path.normalize(d) !== target) return
  773. calls += 1
  774. Deferred.doneUnsafe(ready, Effect.void)
  775. await Effect.runPromise(Deferred.await(hold))
  776. const mod = path.join(d, "node_modules", "@opencode-ai", "plugin")
  777. await fs.mkdir(mod, { recursive: true })
  778. await Filesystem.write(
  779. path.join(mod, "package.json"),
  780. JSON.stringify({ name: "@opencode-ai/plugin", version: "1.0.0" }),
  781. )
  782. })
  783. yield* Effect.addFinalizer(() =>
  784. Effect.sync(() => {
  785. online.mockRestore()
  786. run.mockRestore()
  787. }),
  788. )
  789. const first = yield* installDeps(dir).pipe(Effect.forkScoped)
  790. yield* Deferred.await(ready)
  791. let done = false
  792. const second = yield* installDeps(dir, {
  793. waitTick: () => {
  794. Deferred.doneUnsafe(blocked, Effect.void)
  795. },
  796. }).pipe(
  797. Effect.tap(() =>
  798. Effect.sync(() => {
  799. done = true
  800. }),
  801. ),
  802. Effect.forkScoped,
  803. )
  804. yield* Deferred.await(blocked)
  805. expect(done).toBe(false)
  806. yield* Deferred.succeed(hold, void 0)
  807. yield* Fiber.join(first)
  808. yield* Fiber.join(second)
  809. expect(calls).toBe(1)
  810. expect(yield* Effect.promise(() => Filesystem.exists(path.join(dir, "package.json")))).toBe(true)
  811. }),
  812. )
  813. it.live("serializes config dependency installs across dirs", () =>
  814. Effect.gen(function* () {
  815. if (process.platform !== "win32") return
  816. const tmp = yield* tmpdirScoped()
  817. const a = path.join(tmp, "a")
  818. const b = path.join(tmp, "b")
  819. yield* Effect.promise(() => fs.mkdir(a, { recursive: true }))
  820. yield* Effect.promise(() => fs.mkdir(b, { recursive: true }))
  821. let calls = 0
  822. let open = 0
  823. let peak = 0
  824. const ready = Deferred.makeUnsafe<void>()
  825. const blocked = Deferred.makeUnsafe<void>()
  826. const hold = Deferred.makeUnsafe<void>()
  827. const online = spyOn(Network, "online").mockReturnValue(false)
  828. const run = spyOn(Npm, "install").mockImplementation(async (dir: string) => {
  829. const cwd = path.normalize(dir)
  830. const hit = cwd === path.normalize(a) || cwd === path.normalize(b)
  831. if (hit) {
  832. calls += 1
  833. open += 1
  834. peak = Math.max(peak, open)
  835. if (calls === 1) {
  836. Deferred.doneUnsafe(ready, Effect.void)
  837. await Effect.runPromise(Deferred.await(hold))
  838. }
  839. }
  840. const mod = path.join(cwd, "node_modules", "@opencode-ai", "plugin")
  841. await fs.mkdir(mod, { recursive: true })
  842. await Filesystem.write(
  843. path.join(mod, "package.json"),
  844. JSON.stringify({ name: "@opencode-ai/plugin", version: "1.0.0" }),
  845. )
  846. if (hit) {
  847. open -= 1
  848. }
  849. })
  850. yield* Effect.addFinalizer(() =>
  851. Effect.sync(() => {
  852. online.mockRestore()
  853. run.mockRestore()
  854. }),
  855. )
  856. const first = yield* installDeps(a).pipe(Effect.forkScoped)
  857. yield* Deferred.await(ready)
  858. const second = yield* installDeps(b, {
  859. waitTick: () => {
  860. Deferred.doneUnsafe(blocked, Effect.void)
  861. },
  862. }).pipe(Effect.forkScoped)
  863. yield* Deferred.await(blocked)
  864. expect(peak).toBe(1)
  865. yield* Deferred.succeed(hold, void 0)
  866. yield* Fiber.join(first)
  867. yield* Fiber.join(second)
  868. expect(calls).toBe(2)
  869. expect(peak).toBe(1)
  870. }),
  871. )
  872. test("resolves scoped npm plugins in config", async () => {
  873. await using tmp = await tmpdir({
  874. init: async (dir) => {
  875. const pluginDir = path.join(dir, "node_modules", "@scope", "plugin")
  876. await fs.mkdir(pluginDir, { recursive: true })
  877. await Filesystem.write(
  878. path.join(dir, "package.json"),
  879. JSON.stringify({ name: "config-fixture", version: "1.0.0", type: "module" }, null, 2),
  880. )
  881. await Filesystem.write(
  882. path.join(pluginDir, "package.json"),
  883. JSON.stringify(
  884. {
  885. name: "@scope/plugin",
  886. version: "1.0.0",
  887. type: "module",
  888. main: "./index.js",
  889. },
  890. null,
  891. 2,
  892. ),
  893. )
  894. await Filesystem.write(path.join(pluginDir, "index.js"), "export default {}\n")
  895. await Filesystem.write(
  896. path.join(dir, "opencode.json"),
  897. JSON.stringify({ $schema: "https://opencode.ai/config.json", plugin: ["@scope/plugin"] }, null, 2),
  898. )
  899. },
  900. })
  901. await Instance.provide({
  902. directory: tmp.path,
  903. fn: async () => {
  904. const config = await Config.get()
  905. const pluginEntries = config.plugin ?? []
  906. expect(pluginEntries).toContain("@scope/plugin")
  907. },
  908. })
  909. })
  910. test("merges plugin arrays from global and local configs", async () => {
  911. await using tmp = await tmpdir({
  912. init: async (dir) => {
  913. // Create a nested project structure with local .opencode config
  914. const projectDir = path.join(dir, "project")
  915. const opencodeDir = path.join(projectDir, ".opencode")
  916. await fs.mkdir(opencodeDir, { recursive: true })
  917. // Global config with plugins
  918. await Filesystem.write(
  919. path.join(dir, "opencode.json"),
  920. JSON.stringify({
  921. $schema: "https://opencode.ai/config.json",
  922. plugin: ["global-plugin-1", "global-plugin-2"],
  923. }),
  924. )
  925. // Local .opencode config with different plugins
  926. await Filesystem.write(
  927. path.join(opencodeDir, "opencode.json"),
  928. JSON.stringify({
  929. $schema: "https://opencode.ai/config.json",
  930. plugin: ["local-plugin-1"],
  931. }),
  932. )
  933. },
  934. })
  935. await Instance.provide({
  936. directory: path.join(tmp.path, "project"),
  937. fn: async () => {
  938. const config = await Config.get()
  939. const plugins = config.plugin ?? []
  940. // Should contain both global and local plugins
  941. expect(plugins.some((p) => p.includes("global-plugin-1"))).toBe(true)
  942. expect(plugins.some((p) => p.includes("global-plugin-2"))).toBe(true)
  943. expect(plugins.some((p) => p.includes("local-plugin-1"))).toBe(true)
  944. // Should have all 3 plugins (not replaced, but merged)
  945. const pluginNames = plugins.filter((p) => p.includes("global-plugin") || p.includes("local-plugin"))
  946. expect(pluginNames.length).toBeGreaterThanOrEqual(3)
  947. },
  948. })
  949. })
  950. test("does not error when only custom agent is a subagent", async () => {
  951. await using tmp = await tmpdir({
  952. init: async (dir) => {
  953. const opencodeDir = path.join(dir, ".opencode")
  954. await fs.mkdir(opencodeDir, { recursive: true })
  955. const agentDir = path.join(opencodeDir, "agent")
  956. await fs.mkdir(agentDir, { recursive: true })
  957. await Filesystem.write(
  958. path.join(agentDir, "helper.md"),
  959. `---
  960. model: test/model
  961. mode: subagent
  962. ---
  963. Helper subagent prompt`,
  964. )
  965. },
  966. })
  967. await Instance.provide({
  968. directory: tmp.path,
  969. fn: async () => {
  970. const config = await Config.get()
  971. expect(config.agent?.["helper"]).toMatchObject({
  972. name: "helper",
  973. model: "test/model",
  974. mode: "subagent",
  975. prompt: "Helper subagent prompt",
  976. })
  977. },
  978. })
  979. })
  980. test("merges instructions arrays from global and local configs", async () => {
  981. await using tmp = await tmpdir({
  982. init: async (dir) => {
  983. const projectDir = path.join(dir, "project")
  984. const opencodeDir = path.join(projectDir, ".opencode")
  985. await fs.mkdir(opencodeDir, { recursive: true })
  986. await Filesystem.write(
  987. path.join(dir, "opencode.json"),
  988. JSON.stringify({
  989. $schema: "https://opencode.ai/config.json",
  990. instructions: ["global-instructions.md", "shared-rules.md"],
  991. }),
  992. )
  993. await Filesystem.write(
  994. path.join(opencodeDir, "opencode.json"),
  995. JSON.stringify({
  996. $schema: "https://opencode.ai/config.json",
  997. instructions: ["local-instructions.md"],
  998. }),
  999. )
  1000. },
  1001. })
  1002. await Instance.provide({
  1003. directory: path.join(tmp.path, "project"),
  1004. fn: async () => {
  1005. const config = await Config.get()
  1006. const instructions = config.instructions ?? []
  1007. expect(instructions).toContain("global-instructions.md")
  1008. expect(instructions).toContain("shared-rules.md")
  1009. expect(instructions).toContain("local-instructions.md")
  1010. expect(instructions.length).toBe(3)
  1011. },
  1012. })
  1013. })
  1014. test("deduplicates duplicate instructions from global and local configs", async () => {
  1015. await using tmp = await tmpdir({
  1016. init: async (dir) => {
  1017. const projectDir = path.join(dir, "project")
  1018. const opencodeDir = path.join(projectDir, ".opencode")
  1019. await fs.mkdir(opencodeDir, { recursive: true })
  1020. await Filesystem.write(
  1021. path.join(dir, "opencode.json"),
  1022. JSON.stringify({
  1023. $schema: "https://opencode.ai/config.json",
  1024. instructions: ["duplicate.md", "global-only.md"],
  1025. }),
  1026. )
  1027. await Filesystem.write(
  1028. path.join(opencodeDir, "opencode.json"),
  1029. JSON.stringify({
  1030. $schema: "https://opencode.ai/config.json",
  1031. instructions: ["duplicate.md", "local-only.md"],
  1032. }),
  1033. )
  1034. },
  1035. })
  1036. await Instance.provide({
  1037. directory: path.join(tmp.path, "project"),
  1038. fn: async () => {
  1039. const config = await Config.get()
  1040. const instructions = config.instructions ?? []
  1041. expect(instructions).toContain("global-only.md")
  1042. expect(instructions).toContain("local-only.md")
  1043. expect(instructions).toContain("duplicate.md")
  1044. const duplicates = instructions.filter((i) => i === "duplicate.md")
  1045. expect(duplicates.length).toBe(1)
  1046. expect(instructions.length).toBe(3)
  1047. },
  1048. })
  1049. })
  1050. test("deduplicates duplicate plugins from global and local configs", async () => {
  1051. await using tmp = await tmpdir({
  1052. init: async (dir) => {
  1053. // Create a nested project structure with local .opencode config
  1054. const projectDir = path.join(dir, "project")
  1055. const opencodeDir = path.join(projectDir, ".opencode")
  1056. await fs.mkdir(opencodeDir, { recursive: true })
  1057. // Global config with plugins
  1058. await Filesystem.write(
  1059. path.join(dir, "opencode.json"),
  1060. JSON.stringify({
  1061. $schema: "https://opencode.ai/config.json",
  1062. plugin: ["duplicate-plugin", "global-plugin-1"],
  1063. }),
  1064. )
  1065. // Local .opencode config with some overlapping plugins
  1066. await Filesystem.write(
  1067. path.join(opencodeDir, "opencode.json"),
  1068. JSON.stringify({
  1069. $schema: "https://opencode.ai/config.json",
  1070. plugin: ["duplicate-plugin", "local-plugin-1"],
  1071. }),
  1072. )
  1073. },
  1074. })
  1075. await Instance.provide({
  1076. directory: path.join(tmp.path, "project"),
  1077. fn: async () => {
  1078. const config = await Config.get()
  1079. const plugins = config.plugin ?? []
  1080. // Should contain all unique plugins
  1081. expect(plugins.some((p) => p.includes("global-plugin-1"))).toBe(true)
  1082. expect(plugins.some((p) => p.includes("local-plugin-1"))).toBe(true)
  1083. expect(plugins.some((p) => p.includes("duplicate-plugin"))).toBe(true)
  1084. // Should deduplicate the duplicate plugin
  1085. const duplicatePlugins = plugins.filter((p) => p.includes("duplicate-plugin"))
  1086. expect(duplicatePlugins.length).toBe(1)
  1087. // Should have exactly 3 unique plugins
  1088. const pluginNames = plugins.filter(
  1089. (p) => p.includes("global-plugin") || p.includes("local-plugin") || p.includes("duplicate-plugin"),
  1090. )
  1091. expect(pluginNames.length).toBe(3)
  1092. },
  1093. })
  1094. })
  1095. test("keeps plugin origins aligned with merged plugin list", async () => {
  1096. await using tmp = await tmpdir({
  1097. init: async (dir) => {
  1098. const project = path.join(dir, "project")
  1099. const local = path.join(project, ".opencode")
  1100. await fs.mkdir(local, { recursive: true })
  1101. await Filesystem.write(
  1102. path.join(dir, "opencode.json"),
  1103. JSON.stringify({
  1104. $schema: "https://opencode.ai/config.json",
  1105. plugin: [["shared-plugin@1.0.0", { source: "global" }], "global-only@1.0.0"],
  1106. }),
  1107. )
  1108. await Filesystem.write(
  1109. path.join(local, "opencode.json"),
  1110. JSON.stringify({
  1111. $schema: "https://opencode.ai/config.json",
  1112. plugin: [["shared-plugin@2.0.0", { source: "local" }], "local-only@1.0.0"],
  1113. }),
  1114. )
  1115. },
  1116. })
  1117. await Instance.provide({
  1118. directory: path.join(tmp.path, "project"),
  1119. fn: async () => {
  1120. const cfg = await Config.get()
  1121. const plugins = cfg.plugin ?? []
  1122. const origins = cfg.plugin_origins ?? []
  1123. const names = plugins.map((item) => Config.pluginSpecifier(item))
  1124. expect(names).toContain("shared-plugin@2.0.0")
  1125. expect(names).not.toContain("shared-plugin@1.0.0")
  1126. expect(names).toContain("global-only@1.0.0")
  1127. expect(names).toContain("local-only@1.0.0")
  1128. expect(origins.map((item) => item.spec)).toEqual(plugins)
  1129. const hit = origins.find((item) => Config.pluginSpecifier(item.spec) === "shared-plugin@2.0.0")
  1130. expect(hit?.scope).toBe("local")
  1131. },
  1132. })
  1133. })
  1134. // Legacy tools migration tests
  1135. test("migrates legacy tools config to permissions - allow", async () => {
  1136. await using tmp = await tmpdir({
  1137. init: async (dir) => {
  1138. await Filesystem.write(
  1139. path.join(dir, "opencode.json"),
  1140. JSON.stringify({
  1141. $schema: "https://opencode.ai/config.json",
  1142. agent: {
  1143. test: {
  1144. tools: {
  1145. bash: true,
  1146. read: true,
  1147. },
  1148. },
  1149. },
  1150. }),
  1151. )
  1152. },
  1153. })
  1154. await Instance.provide({
  1155. directory: tmp.path,
  1156. fn: async () => {
  1157. const config = await Config.get()
  1158. expect(config.agent?.["test"]?.permission).toEqual({
  1159. bash: "allow",
  1160. read: "allow",
  1161. })
  1162. },
  1163. })
  1164. })
  1165. test("migrates legacy tools config to permissions - deny", async () => {
  1166. await using tmp = await tmpdir({
  1167. init: async (dir) => {
  1168. await Filesystem.write(
  1169. path.join(dir, "opencode.json"),
  1170. JSON.stringify({
  1171. $schema: "https://opencode.ai/config.json",
  1172. agent: {
  1173. test: {
  1174. tools: {
  1175. bash: false,
  1176. webfetch: false,
  1177. },
  1178. },
  1179. },
  1180. }),
  1181. )
  1182. },
  1183. })
  1184. await Instance.provide({
  1185. directory: tmp.path,
  1186. fn: async () => {
  1187. const config = await Config.get()
  1188. expect(config.agent?.["test"]?.permission).toEqual({
  1189. bash: "deny",
  1190. webfetch: "deny",
  1191. })
  1192. },
  1193. })
  1194. })
  1195. test("migrates legacy write tool to edit permission", async () => {
  1196. await using tmp = await tmpdir({
  1197. init: async (dir) => {
  1198. await Filesystem.write(
  1199. path.join(dir, "opencode.json"),
  1200. JSON.stringify({
  1201. $schema: "https://opencode.ai/config.json",
  1202. agent: {
  1203. test: {
  1204. tools: {
  1205. write: true,
  1206. },
  1207. },
  1208. },
  1209. }),
  1210. )
  1211. },
  1212. })
  1213. await Instance.provide({
  1214. directory: tmp.path,
  1215. fn: async () => {
  1216. const config = await Config.get()
  1217. expect(config.agent?.["test"]?.permission).toEqual({
  1218. edit: "allow",
  1219. })
  1220. },
  1221. })
  1222. })
  1223. // Managed settings tests
  1224. // Note: preload.ts sets OPENCODE_TEST_MANAGED_CONFIG which Global.Path.managedConfig uses
  1225. test("managed settings override user settings", async () => {
  1226. await using tmp = await tmpdir({
  1227. init: async (dir) => {
  1228. await writeConfig(dir, {
  1229. $schema: "https://opencode.ai/config.json",
  1230. model: "user/model",
  1231. share: "auto",
  1232. username: "testuser",
  1233. })
  1234. },
  1235. })
  1236. await writeManagedSettings({
  1237. $schema: "https://opencode.ai/config.json",
  1238. model: "managed/model",
  1239. share: "disabled",
  1240. })
  1241. await Instance.provide({
  1242. directory: tmp.path,
  1243. fn: async () => {
  1244. const config = await Config.get()
  1245. expect(config.model).toBe("managed/model")
  1246. expect(config.share).toBe("disabled")
  1247. expect(config.username).toBe("testuser")
  1248. },
  1249. })
  1250. })
  1251. test("managed settings override project settings", async () => {
  1252. await using tmp = await tmpdir({
  1253. init: async (dir) => {
  1254. await writeConfig(dir, {
  1255. $schema: "https://opencode.ai/config.json",
  1256. autoupdate: true,
  1257. disabled_providers: [],
  1258. })
  1259. },
  1260. })
  1261. await writeManagedSettings({
  1262. $schema: "https://opencode.ai/config.json",
  1263. autoupdate: false,
  1264. disabled_providers: ["openai"],
  1265. })
  1266. await Instance.provide({
  1267. directory: tmp.path,
  1268. fn: async () => {
  1269. const config = await Config.get()
  1270. expect(config.autoupdate).toBe(false)
  1271. expect(config.disabled_providers).toEqual(["openai"])
  1272. },
  1273. })
  1274. })
  1275. test("missing managed settings file is not an error", async () => {
  1276. await using tmp = await tmpdir({
  1277. init: async (dir) => {
  1278. await writeConfig(dir, {
  1279. $schema: "https://opencode.ai/config.json",
  1280. model: "user/model",
  1281. })
  1282. },
  1283. })
  1284. await Instance.provide({
  1285. directory: tmp.path,
  1286. fn: async () => {
  1287. const config = await Config.get()
  1288. expect(config.model).toBe("user/model")
  1289. },
  1290. })
  1291. })
  1292. test("migrates legacy edit tool to edit permission", async () => {
  1293. await using tmp = await tmpdir({
  1294. init: async (dir) => {
  1295. await Filesystem.write(
  1296. path.join(dir, "opencode.json"),
  1297. JSON.stringify({
  1298. $schema: "https://opencode.ai/config.json",
  1299. agent: {
  1300. test: {
  1301. tools: {
  1302. edit: false,
  1303. },
  1304. },
  1305. },
  1306. }),
  1307. )
  1308. },
  1309. })
  1310. await Instance.provide({
  1311. directory: tmp.path,
  1312. fn: async () => {
  1313. const config = await Config.get()
  1314. expect(config.agent?.["test"]?.permission).toEqual({
  1315. edit: "deny",
  1316. })
  1317. },
  1318. })
  1319. })
  1320. test("migrates legacy patch tool to edit permission", async () => {
  1321. await using tmp = await tmpdir({
  1322. init: async (dir) => {
  1323. await Filesystem.write(
  1324. path.join(dir, "opencode.json"),
  1325. JSON.stringify({
  1326. $schema: "https://opencode.ai/config.json",
  1327. agent: {
  1328. test: {
  1329. tools: {
  1330. patch: true,
  1331. },
  1332. },
  1333. },
  1334. }),
  1335. )
  1336. },
  1337. })
  1338. await Instance.provide({
  1339. directory: tmp.path,
  1340. fn: async () => {
  1341. const config = await Config.get()
  1342. expect(config.agent?.["test"]?.permission).toEqual({
  1343. edit: "allow",
  1344. })
  1345. },
  1346. })
  1347. })
  1348. test("migrates legacy multiedit tool to edit permission", async () => {
  1349. await using tmp = await tmpdir({
  1350. init: async (dir) => {
  1351. await Filesystem.write(
  1352. path.join(dir, "opencode.json"),
  1353. JSON.stringify({
  1354. $schema: "https://opencode.ai/config.json",
  1355. agent: {
  1356. test: {
  1357. tools: {
  1358. multiedit: false,
  1359. },
  1360. },
  1361. },
  1362. }),
  1363. )
  1364. },
  1365. })
  1366. await Instance.provide({
  1367. directory: tmp.path,
  1368. fn: async () => {
  1369. const config = await Config.get()
  1370. expect(config.agent?.["test"]?.permission).toEqual({
  1371. edit: "deny",
  1372. })
  1373. },
  1374. })
  1375. })
  1376. test("migrates mixed legacy tools config", async () => {
  1377. await using tmp = await tmpdir({
  1378. init: async (dir) => {
  1379. await Filesystem.write(
  1380. path.join(dir, "opencode.json"),
  1381. JSON.stringify({
  1382. $schema: "https://opencode.ai/config.json",
  1383. agent: {
  1384. test: {
  1385. tools: {
  1386. bash: true,
  1387. write: true,
  1388. read: false,
  1389. webfetch: true,
  1390. },
  1391. },
  1392. },
  1393. }),
  1394. )
  1395. },
  1396. })
  1397. await Instance.provide({
  1398. directory: tmp.path,
  1399. fn: async () => {
  1400. const config = await Config.get()
  1401. expect(config.agent?.["test"]?.permission).toEqual({
  1402. bash: "allow",
  1403. edit: "allow",
  1404. read: "deny",
  1405. webfetch: "allow",
  1406. })
  1407. },
  1408. })
  1409. })
  1410. test("merges legacy tools with existing permission config", async () => {
  1411. await using tmp = await tmpdir({
  1412. init: async (dir) => {
  1413. await Filesystem.write(
  1414. path.join(dir, "opencode.json"),
  1415. JSON.stringify({
  1416. $schema: "https://opencode.ai/config.json",
  1417. agent: {
  1418. test: {
  1419. permission: {
  1420. glob: "allow",
  1421. },
  1422. tools: {
  1423. bash: true,
  1424. },
  1425. },
  1426. },
  1427. }),
  1428. )
  1429. },
  1430. })
  1431. await Instance.provide({
  1432. directory: tmp.path,
  1433. fn: async () => {
  1434. const config = await Config.get()
  1435. expect(config.agent?.["test"]?.permission).toEqual({
  1436. glob: "allow",
  1437. bash: "allow",
  1438. })
  1439. },
  1440. })
  1441. })
  1442. test("permission config preserves key order", async () => {
  1443. await using tmp = await tmpdir({
  1444. init: async (dir) => {
  1445. await Filesystem.write(
  1446. path.join(dir, "opencode.json"),
  1447. JSON.stringify({
  1448. $schema: "https://opencode.ai/config.json",
  1449. permission: {
  1450. "*": "deny",
  1451. edit: "ask",
  1452. write: "ask",
  1453. external_directory: "ask",
  1454. read: "allow",
  1455. todowrite: "allow",
  1456. "thoughts_*": "allow",
  1457. "reasoning_model_*": "allow",
  1458. "tools_*": "allow",
  1459. "pr_comments_*": "allow",
  1460. },
  1461. }),
  1462. )
  1463. },
  1464. })
  1465. await Instance.provide({
  1466. directory: tmp.path,
  1467. fn: async () => {
  1468. const config = await Config.get()
  1469. expect(Object.keys(config.permission!)).toEqual([
  1470. "*",
  1471. "edit",
  1472. "write",
  1473. "external_directory",
  1474. "read",
  1475. "todowrite",
  1476. "thoughts_*",
  1477. "reasoning_model_*",
  1478. "tools_*",
  1479. "pr_comments_*",
  1480. ])
  1481. },
  1482. })
  1483. })
  1484. // MCP config merging tests
  1485. test("project config can override MCP server enabled status", async () => {
  1486. await using tmp = await tmpdir({
  1487. init: async (dir) => {
  1488. // Simulates a base config (like from remote .well-known) with disabled MCP
  1489. await Filesystem.write(
  1490. path.join(dir, "opencode.json"),
  1491. JSON.stringify({
  1492. $schema: "https://opencode.ai/config.json",
  1493. mcp: {
  1494. jira: {
  1495. type: "remote",
  1496. url: "https://jira.example.com/mcp",
  1497. enabled: false,
  1498. },
  1499. wiki: {
  1500. type: "remote",
  1501. url: "https://wiki.example.com/mcp",
  1502. enabled: false,
  1503. },
  1504. },
  1505. }),
  1506. )
  1507. // Project config enables just jira
  1508. await Filesystem.write(
  1509. path.join(dir, "opencode.jsonc"),
  1510. JSON.stringify({
  1511. $schema: "https://opencode.ai/config.json",
  1512. mcp: {
  1513. jira: {
  1514. type: "remote",
  1515. url: "https://jira.example.com/mcp",
  1516. enabled: true,
  1517. },
  1518. },
  1519. }),
  1520. )
  1521. },
  1522. })
  1523. await Instance.provide({
  1524. directory: tmp.path,
  1525. fn: async () => {
  1526. const config = await Config.get()
  1527. // jira should be enabled (overridden by project config)
  1528. expect(config.mcp?.jira).toEqual({
  1529. type: "remote",
  1530. url: "https://jira.example.com/mcp",
  1531. enabled: true,
  1532. })
  1533. // wiki should still be disabled (not overridden)
  1534. expect(config.mcp?.wiki).toEqual({
  1535. type: "remote",
  1536. url: "https://wiki.example.com/mcp",
  1537. enabled: false,
  1538. })
  1539. },
  1540. })
  1541. })
  1542. test("MCP config deep merges preserving base config properties", async () => {
  1543. await using tmp = await tmpdir({
  1544. init: async (dir) => {
  1545. // Base config with full MCP definition
  1546. await Filesystem.write(
  1547. path.join(dir, "opencode.json"),
  1548. JSON.stringify({
  1549. $schema: "https://opencode.ai/config.json",
  1550. mcp: {
  1551. myserver: {
  1552. type: "remote",
  1553. url: "https://myserver.example.com/mcp",
  1554. enabled: false,
  1555. headers: {
  1556. "X-Custom-Header": "value",
  1557. },
  1558. },
  1559. },
  1560. }),
  1561. )
  1562. // Override just enables it, should preserve other properties
  1563. await Filesystem.write(
  1564. path.join(dir, "opencode.jsonc"),
  1565. JSON.stringify({
  1566. $schema: "https://opencode.ai/config.json",
  1567. mcp: {
  1568. myserver: {
  1569. type: "remote",
  1570. url: "https://myserver.example.com/mcp",
  1571. enabled: true,
  1572. },
  1573. },
  1574. }),
  1575. )
  1576. },
  1577. })
  1578. await Instance.provide({
  1579. directory: tmp.path,
  1580. fn: async () => {
  1581. const config = await Config.get()
  1582. expect(config.mcp?.myserver).toEqual({
  1583. type: "remote",
  1584. url: "https://myserver.example.com/mcp",
  1585. enabled: true,
  1586. headers: {
  1587. "X-Custom-Header": "value",
  1588. },
  1589. })
  1590. },
  1591. })
  1592. })
  1593. test("local .opencode config can override MCP from project config", async () => {
  1594. await using tmp = await tmpdir({
  1595. init: async (dir) => {
  1596. // Project config with disabled MCP
  1597. await Filesystem.write(
  1598. path.join(dir, "opencode.json"),
  1599. JSON.stringify({
  1600. $schema: "https://opencode.ai/config.json",
  1601. mcp: {
  1602. docs: {
  1603. type: "remote",
  1604. url: "https://docs.example.com/mcp",
  1605. enabled: false,
  1606. },
  1607. },
  1608. }),
  1609. )
  1610. // Local .opencode directory config enables it
  1611. const opencodeDir = path.join(dir, ".opencode")
  1612. await fs.mkdir(opencodeDir, { recursive: true })
  1613. await Filesystem.write(
  1614. path.join(opencodeDir, "opencode.json"),
  1615. JSON.stringify({
  1616. $schema: "https://opencode.ai/config.json",
  1617. mcp: {
  1618. docs: {
  1619. type: "remote",
  1620. url: "https://docs.example.com/mcp",
  1621. enabled: true,
  1622. },
  1623. },
  1624. }),
  1625. )
  1626. },
  1627. })
  1628. await Instance.provide({
  1629. directory: tmp.path,
  1630. fn: async () => {
  1631. const config = await Config.get()
  1632. expect(config.mcp?.docs?.enabled).toBe(true)
  1633. },
  1634. })
  1635. })
  1636. test("project config overrides remote well-known config", async () => {
  1637. const originalFetch = globalThis.fetch
  1638. let fetchedUrl: string | undefined
  1639. globalThis.fetch = mock((url: string | URL | Request) => {
  1640. const urlStr = url.toString()
  1641. if (urlStr.includes(".well-known/opencode")) {
  1642. fetchedUrl = urlStr
  1643. return Promise.resolve(
  1644. new Response(
  1645. JSON.stringify({
  1646. config: {
  1647. mcp: { jira: { type: "remote", url: "https://jira.example.com/mcp", enabled: false } },
  1648. },
  1649. }),
  1650. { status: 200 },
  1651. ),
  1652. )
  1653. }
  1654. return originalFetch(url)
  1655. }) as unknown as typeof fetch
  1656. const fakeAuth = Layer.mock(Auth.Service)({
  1657. all: () =>
  1658. Effect.succeed({
  1659. "https://example.com": new Auth.WellKnown({ type: "wellknown", key: "TEST_TOKEN", token: "test-token" }),
  1660. }),
  1661. })
  1662. const layer = Config.layer.pipe(
  1663. Layer.provide(AppFileSystem.defaultLayer),
  1664. Layer.provide(fakeAuth),
  1665. Layer.provide(emptyAccount),
  1666. Layer.provideMerge(infra),
  1667. )
  1668. try {
  1669. await provideTmpdirInstance(
  1670. () =>
  1671. Config.Service.use((svc) =>
  1672. Effect.gen(function* () {
  1673. const config = yield* svc.get()
  1674. expect(fetchedUrl).toBe("https://example.com/.well-known/opencode")
  1675. expect(config.mcp?.jira?.enabled).toBe(true)
  1676. }),
  1677. ),
  1678. {
  1679. git: true,
  1680. config: { mcp: { jira: { type: "remote", url: "https://jira.example.com/mcp", enabled: true } } },
  1681. },
  1682. ).pipe(Effect.scoped, Effect.provide(layer), Effect.runPromise)
  1683. } finally {
  1684. globalThis.fetch = originalFetch
  1685. }
  1686. })
  1687. test("wellknown URL with trailing slash is normalized", async () => {
  1688. const originalFetch = globalThis.fetch
  1689. let fetchedUrl: string | undefined
  1690. globalThis.fetch = mock((url: string | URL | Request) => {
  1691. const urlStr = url.toString()
  1692. if (urlStr.includes(".well-known/opencode")) {
  1693. fetchedUrl = urlStr
  1694. return Promise.resolve(
  1695. new Response(
  1696. JSON.stringify({
  1697. config: {
  1698. mcp: { slack: { type: "remote", url: "https://slack.example.com/mcp", enabled: true } },
  1699. },
  1700. }),
  1701. { status: 200 },
  1702. ),
  1703. )
  1704. }
  1705. return originalFetch(url)
  1706. }) as unknown as typeof fetch
  1707. const fakeAuth = Layer.mock(Auth.Service)({
  1708. all: () =>
  1709. Effect.succeed({
  1710. "https://example.com/": new Auth.WellKnown({ type: "wellknown", key: "TEST_TOKEN", token: "test-token" }),
  1711. }),
  1712. })
  1713. const layer = Config.layer.pipe(
  1714. Layer.provide(AppFileSystem.defaultLayer),
  1715. Layer.provide(fakeAuth),
  1716. Layer.provide(emptyAccount),
  1717. Layer.provideMerge(infra),
  1718. )
  1719. try {
  1720. await provideTmpdirInstance(
  1721. () =>
  1722. Config.Service.use((svc) =>
  1723. Effect.gen(function* () {
  1724. yield* svc.get()
  1725. expect(fetchedUrl).toBe("https://example.com/.well-known/opencode")
  1726. }),
  1727. ),
  1728. { git: true },
  1729. ).pipe(Effect.scoped, Effect.provide(layer), Effect.runPromise)
  1730. } finally {
  1731. globalThis.fetch = originalFetch
  1732. }
  1733. })
  1734. describe("resolvePluginSpec", () => {
  1735. test("keeps package specs unchanged", async () => {
  1736. await using tmp = await tmpdir()
  1737. const file = path.join(tmp.path, "opencode.json")
  1738. expect(await Config.resolvePluginSpec("oh-my-opencode@2.4.3", file)).toBe("oh-my-opencode@2.4.3")
  1739. expect(await Config.resolvePluginSpec("@scope/pkg", file)).toBe("@scope/pkg")
  1740. })
  1741. test("resolves windows-style relative plugin directory specs", async () => {
  1742. if (process.platform !== "win32") return
  1743. await using tmp = await tmpdir({
  1744. init: async (dir) => {
  1745. const plugin = path.join(dir, "plugin")
  1746. await fs.mkdir(plugin, { recursive: true })
  1747. await Filesystem.write(path.join(plugin, "index.ts"), "export default {}")
  1748. },
  1749. })
  1750. const file = path.join(tmp.path, "opencode.json")
  1751. const hit = await Config.resolvePluginSpec(".\\plugin", file)
  1752. expect(Config.pluginSpecifier(hit)).toBe(pathToFileURL(path.join(tmp.path, "plugin", "index.ts")).href)
  1753. })
  1754. test("resolves relative file plugin paths to file urls", async () => {
  1755. await using tmp = await tmpdir({
  1756. init: async (dir) => {
  1757. await Filesystem.write(path.join(dir, "plugin.ts"), "export default {}")
  1758. },
  1759. })
  1760. const file = path.join(tmp.path, "opencode.json")
  1761. const hit = await Config.resolvePluginSpec("./plugin.ts", file)
  1762. expect(Config.pluginSpecifier(hit)).toBe(pathToFileURL(path.join(tmp.path, "plugin.ts")).href)
  1763. })
  1764. test("resolves plugin directory paths to directory urls", async () => {
  1765. await using tmp = await tmpdir({
  1766. init: async (dir) => {
  1767. const plugin = path.join(dir, "plugin")
  1768. await fs.mkdir(plugin, { recursive: true })
  1769. await Filesystem.writeJson(path.join(plugin, "package.json"), {
  1770. name: "demo-plugin",
  1771. type: "module",
  1772. main: "./index.ts",
  1773. })
  1774. await Filesystem.write(path.join(plugin, "index.ts"), "export default {}")
  1775. },
  1776. })
  1777. const file = path.join(tmp.path, "opencode.json")
  1778. const hit = await Config.resolvePluginSpec("./plugin", file)
  1779. expect(Config.pluginSpecifier(hit)).toBe(pathToFileURL(path.join(tmp.path, "plugin")).href)
  1780. })
  1781. test("resolves plugin directories without package.json to index.ts", async () => {
  1782. await using tmp = await tmpdir({
  1783. init: async (dir) => {
  1784. const plugin = path.join(dir, "plugin")
  1785. await fs.mkdir(plugin, { recursive: true })
  1786. await Filesystem.write(path.join(plugin, "index.ts"), "export default {}")
  1787. },
  1788. })
  1789. const file = path.join(tmp.path, "opencode.json")
  1790. const hit = await Config.resolvePluginSpec("./plugin", file)
  1791. expect(Config.pluginSpecifier(hit)).toBe(pathToFileURL(path.join(tmp.path, "plugin", "index.ts")).href)
  1792. })
  1793. })
  1794. describe("deduplicatePluginOrigins", () => {
  1795. const dedupe = (plugins: Config.PluginSpec[]) =>
  1796. Config.deduplicatePluginOrigins(
  1797. plugins.map((spec) => ({
  1798. spec,
  1799. source: "",
  1800. scope: "global" as const,
  1801. })),
  1802. ).map((item) => item.spec)
  1803. test("removes duplicates keeping higher priority (later entries)", () => {
  1804. const plugins = ["global-plugin@1.0.0", "shared-plugin@1.0.0", "local-plugin@2.0.0", "shared-plugin@2.0.0"]
  1805. const result = dedupe(plugins)
  1806. expect(result).toContain("global-plugin@1.0.0")
  1807. expect(result).toContain("local-plugin@2.0.0")
  1808. expect(result).toContain("shared-plugin@2.0.0")
  1809. expect(result).not.toContain("shared-plugin@1.0.0")
  1810. expect(result.length).toBe(3)
  1811. })
  1812. test("keeps path plugins separate from package plugins", () => {
  1813. const plugins = ["oh-my-opencode@2.4.3", "file:///project/.opencode/plugin/oh-my-opencode.js"]
  1814. const result = dedupe(plugins)
  1815. expect(result).toEqual(plugins)
  1816. })
  1817. test("deduplicates direct path plugins by exact spec", () => {
  1818. const plugins = ["file:///project/.opencode/plugin/demo.ts", "file:///project/.opencode/plugin/demo.ts"]
  1819. const result = dedupe(plugins)
  1820. expect(result).toEqual(["file:///project/.opencode/plugin/demo.ts"])
  1821. })
  1822. test("preserves order of remaining plugins", () => {
  1823. const plugins = ["a-plugin@1.0.0", "b-plugin@1.0.0", "c-plugin@1.0.0"]
  1824. const result = dedupe(plugins)
  1825. expect(result).toEqual(["a-plugin@1.0.0", "b-plugin@1.0.0", "c-plugin@1.0.0"])
  1826. })
  1827. test("loads auto-discovered local plugins as file urls", async () => {
  1828. await using tmp = await tmpdir({
  1829. init: async (dir) => {
  1830. const projectDir = path.join(dir, "project")
  1831. const opencodeDir = path.join(projectDir, ".opencode")
  1832. const pluginDir = path.join(opencodeDir, "plugin")
  1833. await fs.mkdir(pluginDir, { recursive: true })
  1834. await Filesystem.write(
  1835. path.join(dir, "opencode.json"),
  1836. JSON.stringify({
  1837. $schema: "https://opencode.ai/config.json",
  1838. plugin: ["my-plugin@1.0.0"],
  1839. }),
  1840. )
  1841. await Filesystem.write(path.join(pluginDir, "my-plugin.js"), "export default {}")
  1842. },
  1843. })
  1844. await Instance.provide({
  1845. directory: path.join(tmp.path, "project"),
  1846. fn: async () => {
  1847. const config = await Config.get()
  1848. const plugins = config.plugin ?? []
  1849. expect(plugins.some((p) => Config.pluginSpecifier(p) === "my-plugin@1.0.0")).toBe(true)
  1850. expect(plugins.some((p) => Config.pluginSpecifier(p).startsWith("file://"))).toBe(true)
  1851. },
  1852. })
  1853. })
  1854. })
  1855. describe("OPENCODE_DISABLE_PROJECT_CONFIG", () => {
  1856. test("skips project config files when flag is set", async () => {
  1857. const originalEnv = process.env["OPENCODE_DISABLE_PROJECT_CONFIG"]
  1858. process.env["OPENCODE_DISABLE_PROJECT_CONFIG"] = "true"
  1859. try {
  1860. await using tmp = await tmpdir({
  1861. init: async (dir) => {
  1862. // Create a project config that would normally be loaded
  1863. await Filesystem.write(
  1864. path.join(dir, "opencode.json"),
  1865. JSON.stringify({
  1866. $schema: "https://opencode.ai/config.json",
  1867. model: "project/model",
  1868. username: "project-user",
  1869. }),
  1870. )
  1871. },
  1872. })
  1873. await Instance.provide({
  1874. directory: tmp.path,
  1875. fn: async () => {
  1876. const config = await Config.get()
  1877. // Project config should NOT be loaded - model should be default, not "project/model"
  1878. expect(config.model).not.toBe("project/model")
  1879. expect(config.username).not.toBe("project-user")
  1880. },
  1881. })
  1882. } finally {
  1883. if (originalEnv === undefined) {
  1884. delete process.env["OPENCODE_DISABLE_PROJECT_CONFIG"]
  1885. } else {
  1886. process.env["OPENCODE_DISABLE_PROJECT_CONFIG"] = originalEnv
  1887. }
  1888. }
  1889. })
  1890. test("skips project .opencode/ directories when flag is set", async () => {
  1891. const originalEnv = process.env["OPENCODE_DISABLE_PROJECT_CONFIG"]
  1892. process.env["OPENCODE_DISABLE_PROJECT_CONFIG"] = "true"
  1893. try {
  1894. await using tmp = await tmpdir({
  1895. init: async (dir) => {
  1896. // Create a .opencode directory with a command
  1897. const opencodeDir = path.join(dir, ".opencode", "command")
  1898. await fs.mkdir(opencodeDir, { recursive: true })
  1899. await Filesystem.write(path.join(opencodeDir, "test-cmd.md"), "# Test Command\nThis is a test command.")
  1900. },
  1901. })
  1902. await Instance.provide({
  1903. directory: tmp.path,
  1904. fn: async () => {
  1905. const directories = await Config.directories()
  1906. // Project .opencode should NOT be in directories list
  1907. const hasProjectOpencode = directories.some((d) => d.startsWith(tmp.path))
  1908. expect(hasProjectOpencode).toBe(false)
  1909. },
  1910. })
  1911. } finally {
  1912. if (originalEnv === undefined) {
  1913. delete process.env["OPENCODE_DISABLE_PROJECT_CONFIG"]
  1914. } else {
  1915. process.env["OPENCODE_DISABLE_PROJECT_CONFIG"] = originalEnv
  1916. }
  1917. }
  1918. })
  1919. test("still loads global config when flag is set", async () => {
  1920. const originalEnv = process.env["OPENCODE_DISABLE_PROJECT_CONFIG"]
  1921. process.env["OPENCODE_DISABLE_PROJECT_CONFIG"] = "true"
  1922. try {
  1923. await using tmp = await tmpdir()
  1924. await Instance.provide({
  1925. directory: tmp.path,
  1926. fn: async () => {
  1927. // Should still get default config (from global or defaults)
  1928. const config = await Config.get()
  1929. expect(config).toBeDefined()
  1930. expect(config.username).toBeDefined()
  1931. },
  1932. })
  1933. } finally {
  1934. if (originalEnv === undefined) {
  1935. delete process.env["OPENCODE_DISABLE_PROJECT_CONFIG"]
  1936. } else {
  1937. process.env["OPENCODE_DISABLE_PROJECT_CONFIG"] = originalEnv
  1938. }
  1939. }
  1940. })
  1941. test("skips relative instructions with warning when flag is set but no config dir", async () => {
  1942. const originalDisable = process.env["OPENCODE_DISABLE_PROJECT_CONFIG"]
  1943. const originalConfigDir = process.env["OPENCODE_CONFIG_DIR"]
  1944. try {
  1945. // Ensure no config dir is set
  1946. delete process.env["OPENCODE_CONFIG_DIR"]
  1947. process.env["OPENCODE_DISABLE_PROJECT_CONFIG"] = "true"
  1948. await using tmp = await tmpdir({
  1949. init: async (dir) => {
  1950. // Create a config with relative instruction path
  1951. await Filesystem.write(
  1952. path.join(dir, "opencode.json"),
  1953. JSON.stringify({
  1954. $schema: "https://opencode.ai/config.json",
  1955. instructions: ["./CUSTOM.md"],
  1956. }),
  1957. )
  1958. // Create the instruction file (should be skipped)
  1959. await Filesystem.write(path.join(dir, "CUSTOM.md"), "# Custom Instructions")
  1960. },
  1961. })
  1962. await Instance.provide({
  1963. directory: tmp.path,
  1964. fn: async () => {
  1965. // The relative instruction should be skipped without error
  1966. // We're mainly verifying this doesn't throw and the config loads
  1967. const config = await Config.get()
  1968. expect(config).toBeDefined()
  1969. // The instruction should have been skipped (warning logged)
  1970. // We can't easily test the warning was logged, but we verify
  1971. // the relative path didn't cause an error
  1972. },
  1973. })
  1974. } finally {
  1975. if (originalDisable === undefined) {
  1976. delete process.env["OPENCODE_DISABLE_PROJECT_CONFIG"]
  1977. } else {
  1978. process.env["OPENCODE_DISABLE_PROJECT_CONFIG"] = originalDisable
  1979. }
  1980. if (originalConfigDir === undefined) {
  1981. delete process.env["OPENCODE_CONFIG_DIR"]
  1982. } else {
  1983. process.env["OPENCODE_CONFIG_DIR"] = originalConfigDir
  1984. }
  1985. }
  1986. })
  1987. test("OPENCODE_CONFIG_DIR still works when flag is set", async () => {
  1988. const originalDisable = process.env["OPENCODE_DISABLE_PROJECT_CONFIG"]
  1989. const originalConfigDir = process.env["OPENCODE_CONFIG_DIR"]
  1990. try {
  1991. await using configDirTmp = await tmpdir({
  1992. init: async (dir) => {
  1993. // Create config in the custom config dir
  1994. await Filesystem.write(
  1995. path.join(dir, "opencode.json"),
  1996. JSON.stringify({
  1997. $schema: "https://opencode.ai/config.json",
  1998. model: "configdir/model",
  1999. }),
  2000. )
  2001. },
  2002. })
  2003. await using projectTmp = await tmpdir({
  2004. init: async (dir) => {
  2005. // Create config in project (should be ignored)
  2006. await Filesystem.write(
  2007. path.join(dir, "opencode.json"),
  2008. JSON.stringify({
  2009. $schema: "https://opencode.ai/config.json",
  2010. model: "project/model",
  2011. }),
  2012. )
  2013. },
  2014. })
  2015. process.env["OPENCODE_DISABLE_PROJECT_CONFIG"] = "true"
  2016. process.env["OPENCODE_CONFIG_DIR"] = configDirTmp.path
  2017. await Instance.provide({
  2018. directory: projectTmp.path,
  2019. fn: async () => {
  2020. const config = await Config.get()
  2021. // Should load from OPENCODE_CONFIG_DIR, not project
  2022. expect(config.model).toBe("configdir/model")
  2023. },
  2024. })
  2025. } finally {
  2026. if (originalDisable === undefined) {
  2027. delete process.env["OPENCODE_DISABLE_PROJECT_CONFIG"]
  2028. } else {
  2029. process.env["OPENCODE_DISABLE_PROJECT_CONFIG"] = originalDisable
  2030. }
  2031. if (originalConfigDir === undefined) {
  2032. delete process.env["OPENCODE_CONFIG_DIR"]
  2033. } else {
  2034. process.env["OPENCODE_CONFIG_DIR"] = originalConfigDir
  2035. }
  2036. }
  2037. })
  2038. })
  2039. describe("OPENCODE_CONFIG_CONTENT token substitution", () => {
  2040. test("substitutes {env:} tokens in OPENCODE_CONFIG_CONTENT", async () => {
  2041. const originalEnv = process.env["OPENCODE_CONFIG_CONTENT"]
  2042. const originalTestVar = process.env["TEST_CONFIG_VAR"]
  2043. process.env["TEST_CONFIG_VAR"] = "test_api_key_12345"
  2044. process.env["OPENCODE_CONFIG_CONTENT"] = JSON.stringify({
  2045. $schema: "https://opencode.ai/config.json",
  2046. username: "{env:TEST_CONFIG_VAR}",
  2047. })
  2048. try {
  2049. await using tmp = await tmpdir()
  2050. await Instance.provide({
  2051. directory: tmp.path,
  2052. fn: async () => {
  2053. const config = await Config.get()
  2054. expect(config.username).toBe("test_api_key_12345")
  2055. },
  2056. })
  2057. } finally {
  2058. if (originalEnv !== undefined) {
  2059. process.env["OPENCODE_CONFIG_CONTENT"] = originalEnv
  2060. } else {
  2061. delete process.env["OPENCODE_CONFIG_CONTENT"]
  2062. }
  2063. if (originalTestVar !== undefined) {
  2064. process.env["TEST_CONFIG_VAR"] = originalTestVar
  2065. } else {
  2066. delete process.env["TEST_CONFIG_VAR"]
  2067. }
  2068. }
  2069. })
  2070. test("substitutes {file:} tokens in OPENCODE_CONFIG_CONTENT", async () => {
  2071. const originalEnv = process.env["OPENCODE_CONFIG_CONTENT"]
  2072. try {
  2073. await using tmp = await tmpdir({
  2074. init: async (dir) => {
  2075. await Filesystem.write(path.join(dir, "api_key.txt"), "secret_key_from_file")
  2076. process.env["OPENCODE_CONFIG_CONTENT"] = JSON.stringify({
  2077. $schema: "https://opencode.ai/config.json",
  2078. username: "{file:./api_key.txt}",
  2079. })
  2080. },
  2081. })
  2082. await Instance.provide({
  2083. directory: tmp.path,
  2084. fn: async () => {
  2085. const config = await Config.get()
  2086. expect(config.username).toBe("secret_key_from_file")
  2087. },
  2088. })
  2089. } finally {
  2090. if (originalEnv !== undefined) {
  2091. process.env["OPENCODE_CONFIG_CONTENT"] = originalEnv
  2092. } else {
  2093. delete process.env["OPENCODE_CONFIG_CONTENT"]
  2094. }
  2095. }
  2096. })
  2097. })
  2098. // parseManagedPlist unit tests — pure function, no OS interaction
  2099. test("parseManagedPlist strips MDM metadata keys", async () => {
  2100. const config = await Config.parseManagedPlist(
  2101. JSON.stringify({
  2102. PayloadDisplayName: "OpenCode Managed",
  2103. PayloadIdentifier: "ai.opencode.managed.test",
  2104. PayloadType: "ai.opencode.managed",
  2105. PayloadUUID: "AAAA-BBBB-CCCC",
  2106. PayloadVersion: 1,
  2107. _manualProfile: true,
  2108. share: "disabled",
  2109. model: "mdm/model",
  2110. }),
  2111. "test:mobileconfig",
  2112. )
  2113. expect(config.share).toBe("disabled")
  2114. expect(config.model).toBe("mdm/model")
  2115. // MDM keys must not leak into the parsed config
  2116. expect((config as any).PayloadUUID).toBeUndefined()
  2117. expect((config as any).PayloadType).toBeUndefined()
  2118. expect((config as any)._manualProfile).toBeUndefined()
  2119. })
  2120. test("parseManagedPlist parses server settings", async () => {
  2121. const config = await Config.parseManagedPlist(
  2122. JSON.stringify({
  2123. $schema: "https://opencode.ai/config.json",
  2124. server: { hostname: "127.0.0.1", mdns: false },
  2125. autoupdate: true,
  2126. }),
  2127. "test:mobileconfig",
  2128. )
  2129. expect(config.server?.hostname).toBe("127.0.0.1")
  2130. expect(config.server?.mdns).toBe(false)
  2131. expect(config.autoupdate).toBe(true)
  2132. })
  2133. test("parseManagedPlist parses permission rules", async () => {
  2134. const config = await Config.parseManagedPlist(
  2135. JSON.stringify({
  2136. $schema: "https://opencode.ai/config.json",
  2137. permission: {
  2138. "*": "ask",
  2139. bash: { "*": "ask", "rm -rf *": "deny", "curl *": "deny" },
  2140. grep: "allow",
  2141. glob: "allow",
  2142. webfetch: "ask",
  2143. "~/.ssh/*": "deny",
  2144. },
  2145. }),
  2146. "test:mobileconfig",
  2147. )
  2148. expect(config.permission?.["*"]).toBe("ask")
  2149. expect(config.permission?.grep).toBe("allow")
  2150. expect(config.permission?.webfetch).toBe("ask")
  2151. expect(config.permission?.["~/.ssh/*"]).toBe("deny")
  2152. const bash = config.permission?.bash as Record<string, string>
  2153. expect(bash?.["rm -rf *"]).toBe("deny")
  2154. expect(bash?.["curl *"]).toBe("deny")
  2155. })
  2156. test("parseManagedPlist parses enabled_providers", async () => {
  2157. const config = await Config.parseManagedPlist(
  2158. JSON.stringify({
  2159. $schema: "https://opencode.ai/config.json",
  2160. enabled_providers: ["anthropic", "google"],
  2161. }),
  2162. "test:mobileconfig",
  2163. )
  2164. expect(config.enabled_providers).toEqual(["anthropic", "google"])
  2165. })
  2166. test("parseManagedPlist handles empty config", async () => {
  2167. const config = await Config.parseManagedPlist(
  2168. JSON.stringify({ $schema: "https://opencode.ai/config.json" }),
  2169. "test:mobileconfig",
  2170. )
  2171. expect(config.$schema).toBe("https://opencode.ai/config.json")
  2172. })