config.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. import path from "path"
  2. import fs from "fs/promises"
  3. import { describe, expect } from "bun:test"
  4. import { Effect, Layer } from "effect"
  5. import { Config } from "@opencode-ai/core/config"
  6. import { ConfigProvider } from "@opencode-ai/core/config/provider"
  7. import { AppFileSystem } from "@opencode-ai/core/filesystem"
  8. import { Global } from "@opencode-ai/core/global"
  9. import { Location } from "@opencode-ai/core/location"
  10. import { Policy } from "@opencode-ai/core/policy"
  11. import { Project } from "@opencode-ai/core/project"
  12. import { AbsolutePath } from "@opencode-ai/core/schema"
  13. import { location } from "../fixture/location"
  14. import { tmpdir } from "../fixture/tmpdir"
  15. import { testEffect } from "../lib/effect"
  16. const it = testEffect(Layer.empty)
  17. function testLayer(
  18. directory: string,
  19. globalDirectory = path.join(directory, "global"),
  20. projectDirectory = directory,
  21. vcs?: Project.Vcs,
  22. ) {
  23. return Config.locationLayer.pipe(
  24. Layer.provide(AppFileSystem.defaultLayer),
  25. Layer.provide(Global.layerWith({ config: globalDirectory })),
  26. Layer.provide(
  27. Layer.succeed(
  28. Location.Service,
  29. Location.Service.of(
  30. location(
  31. { directory: AbsolutePath.make(directory) },
  32. { projectDirectory: AbsolutePath.make(projectDirectory), vcs },
  33. ),
  34. ),
  35. ),
  36. ),
  37. )
  38. }
  39. const provider = {
  40. endpoint: { type: "unknown" },
  41. options: {
  42. headers: {},
  43. body: {},
  44. aisdk: {
  45. provider: {},
  46. request: {},
  47. },
  48. },
  49. models: {},
  50. }
  51. describe("Config", () => {
  52. it.live("returns an empty configuration when directory files do not exist", () =>
  53. Effect.acquireRelease(
  54. Effect.promise(() => tmpdir()),
  55. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  56. ).pipe(
  57. Effect.flatMap((tmp) =>
  58. Effect.gen(function* () {
  59. const config = yield* Config.Service
  60. const documents = yield* config.get()
  61. expect(documents).toEqual([])
  62. }).pipe(Effect.provide(testLayer(tmp.path))),
  63. ),
  64. ),
  65. )
  66. it.live("loads JSON and JSONC files from lowest to highest priority", () =>
  67. Effect.acquireRelease(
  68. Effect.promise(() => tmpdir()),
  69. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  70. ).pipe(
  71. Effect.flatMap((tmp) =>
  72. Effect.gen(function* () {
  73. yield* Effect.promise(() =>
  74. Promise.all([
  75. fs.writeFile(
  76. path.join(tmp.path, "config.json"),
  77. JSON.stringify({ $schema: "base", providers: { base: provider } }),
  78. ),
  79. fs.writeFile(
  80. path.join(tmp.path, "opencode.json"),
  81. JSON.stringify({ $schema: "middle", providers: { middle: provider } }),
  82. ),
  83. fs.writeFile(
  84. path.join(tmp.path, "opencode.jsonc"),
  85. `{
  86. // Later global files override scalar fields while retaining providers.
  87. "$schema": "last",
  88. "providers": { "last": ${JSON.stringify(provider)} },
  89. }`,
  90. ),
  91. ]),
  92. )
  93. return yield* Effect.gen(function* () {
  94. const config = yield* Config.Service
  95. const documents = yield* config.get()
  96. expect(documents).toHaveLength(3)
  97. expect(documents.map((document) => document.source.type)).toEqual(["file", "file", "file"])
  98. expect(documents.map((document) => document.info.$schema)).toEqual(["base", "middle", "last"])
  99. expect(documents[0]).toBeInstanceOf(Config.Loaded)
  100. expect(documents[0]?.source.type === "file" ? documents[0].source.path : undefined).toBe(
  101. path.join(tmp.path, "config.json"),
  102. )
  103. expect(documents[2]?.info.providers?.last).toBeInstanceOf(ConfigProvider.Info)
  104. yield* Effect.promise(() =>
  105. fs.writeFile(path.join(tmp.path, "opencode.jsonc"), JSON.stringify({ $schema: "changed" })),
  106. )
  107. expect((yield* config.get()).map((document) => document.info.$schema)).toEqual(["base", "middle", "last"])
  108. }).pipe(Effect.provide(testLayer(tmp.path)))
  109. }),
  110. ),
  111. ),
  112. )
  113. it.live("accepts $schema metadata without writing it into config files", () =>
  114. Effect.acquireRelease(
  115. Effect.promise(() => tmpdir()),
  116. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  117. ).pipe(
  118. Effect.flatMap((tmp) =>
  119. Effect.gen(function* () {
  120. const file = path.join(tmp.path, "opencode.json")
  121. const contents = JSON.stringify({
  122. shell: "/bin/zsh",
  123. experimental: { policies: [{ effect: "deny", action: "provider.use", resource: "openai" }] },
  124. providers: { local: provider },
  125. })
  126. yield* Effect.promise(() => fs.writeFile(file, contents))
  127. return yield* Effect.gen(function* () {
  128. const config = yield* Config.Service
  129. const documents = yield* config.get()
  130. expect(documents[0]?.info.$schema).toBeUndefined()
  131. expect(documents[0]?.info.shell).toBe("/bin/zsh")
  132. expect(documents[0]?.info.experimental?.policies?.[0]).toEqual({
  133. effect: "deny",
  134. action: "provider.use",
  135. resource: "openai",
  136. })
  137. expect(yield* Effect.promise(() => fs.readFile(file, "utf8"))).toBe(contents)
  138. }).pipe(Effect.provide(testLayer(tmp.path)))
  139. }),
  140. ),
  141. ),
  142. )
  143. it.live("loads supported scalar and resource configuration", () =>
  144. Effect.acquireRelease(
  145. Effect.promise(() => tmpdir()),
  146. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  147. ).pipe(
  148. Effect.flatMap((tmp) =>
  149. Effect.gen(function* () {
  150. yield* Effect.promise(() =>
  151. fs.writeFile(
  152. path.join(tmp.path, "opencode.json"),
  153. JSON.stringify({
  154. shell: "/bin/bash",
  155. model: "anthropic/claude",
  156. autoupdate: "notify",
  157. share: "disabled",
  158. enterprise: { url: "https://share.example.com" },
  159. username: "test-user",
  160. permissions: [
  161. { permission: "bash", pattern: "*", action: "ask" },
  162. { permission: "bash", pattern: "git status", action: "allow" },
  163. ],
  164. agents: {
  165. reviewer: {
  166. model: "openrouter/openai/gpt-5",
  167. variant: "high",
  168. options: {
  169. headers: { "x-agent": "reviewer" },
  170. aisdk: { request: { reasoningEffort: "high" } },
  171. },
  172. description: "Review changes for correctness",
  173. system: "Find regressions.",
  174. mode: "subagent",
  175. hidden: false,
  176. color: "warning",
  177. steps: 12,
  178. disabled: false,
  179. permissions: [{ permission: "edit", pattern: "*", action: "deny" }],
  180. },
  181. },
  182. snapshots: false,
  183. watcher: { ignore: ["node_modules/**", "dist/**", ".git"] },
  184. formatter: {
  185. prettier: { disabled: true },
  186. custom: { command: ["custom-fmt", "$FILE"], extensions: [".foo"] },
  187. },
  188. lsp: { typescript: { disabled: true }, custom: { command: ["custom-lsp"], extensions: [".foo"] } },
  189. attachments: {
  190. image: { auto_resize: false, max_width: 1200, max_height: 900, max_base64_bytes: 1048576 },
  191. },
  192. tool_output: { max_lines: 1000, max_bytes: 32768 },
  193. mcp: {
  194. timeout: 5000,
  195. servers: {
  196. local: {
  197. type: "local",
  198. command: ["node", "./mcp/server.js"],
  199. environment: { API_KEY: "secret" },
  200. disabled: false,
  201. timeout: 10000,
  202. },
  203. remote: {
  204. type: "remote",
  205. url: "https://mcp.example.com/mcp",
  206. headers: { Authorization: "Bearer token" },
  207. oauth: { client_id: "client", scope: "read write", callback_port: 19876 },
  208. disabled: true,
  209. },
  210. },
  211. },
  212. compaction: {
  213. auto: true,
  214. prune: false,
  215. keep: { turns: 3, tokens: 2000 },
  216. buffer: 10000,
  217. },
  218. skills: ["./skills", "~/shared-skills", "https://example.com/.well-known/skills/"],
  219. instructions: ["CONTRIBUTING.md", ".cursor/rules/*.md", "https://example.com/shared-rules.md"],
  220. references: {
  221. local: { path: "../library" },
  222. sdk: { repository: "github.com/example/sdk", branch: "main" },
  223. shorthand: "github.com/example/docs",
  224. },
  225. plugins: [
  226. "opencode-helicone-session",
  227. { package: "@my-org/audit-plugin", options: { endpoint: "https://audit.example.com" } },
  228. ],
  229. }),
  230. ),
  231. )
  232. return yield* Effect.gen(function* () {
  233. const config = yield* Config.Service
  234. const documents = yield* config.get()
  235. expect(documents).toHaveLength(1)
  236. expect(documents[0]?.info.shell).toBe("/bin/bash")
  237. expect(documents[0]?.info.model).toBe("anthropic/claude")
  238. expect(documents[0]?.info.autoupdate).toBe("notify")
  239. expect(documents[0]?.info.share).toBe("disabled")
  240. expect(documents[0]?.info.enterprise).toEqual({ url: "https://share.example.com" })
  241. expect(documents[0]?.info.username).toBe("test-user")
  242. expect(documents[0]?.info.permissions).toEqual([
  243. { permission: "bash", pattern: "*", action: "ask" },
  244. { permission: "bash", pattern: "git status", action: "allow" },
  245. ])
  246. expect(documents[0]?.info.agents?.reviewer).toEqual({
  247. model: "openrouter/openai/gpt-5",
  248. variant: "high",
  249. options: {
  250. headers: { "x-agent": "reviewer" },
  251. aisdk: { request: { reasoningEffort: "high" } },
  252. },
  253. description: "Review changes for correctness",
  254. system: "Find regressions.",
  255. mode: "subagent",
  256. hidden: false,
  257. color: "warning",
  258. steps: 12,
  259. disabled: false,
  260. permissions: [{ permission: "edit", pattern: "*", action: "deny" }],
  261. })
  262. expect(documents[0]?.info.snapshots).toBe(false)
  263. expect(documents[0]?.info.watcher).toEqual({ ignore: ["node_modules/**", "dist/**", ".git"] })
  264. expect(documents[0]?.info.formatter).toEqual({
  265. prettier: { disabled: true },
  266. custom: { command: ["custom-fmt", "$FILE"], extensions: [".foo"] },
  267. })
  268. expect(documents[0]?.info.lsp).toEqual({
  269. typescript: { disabled: true },
  270. custom: { command: ["custom-lsp"], extensions: [".foo"] },
  271. })
  272. expect(documents[0]?.info.attachments).toEqual({
  273. image: { auto_resize: false, max_width: 1200, max_height: 900, max_base64_bytes: 1048576 },
  274. })
  275. expect(documents[0]?.info.tool_output).toEqual({ max_lines: 1000, max_bytes: 32768 })
  276. expect(documents[0]?.info.mcp).toEqual({
  277. timeout: 5000,
  278. servers: {
  279. local: {
  280. type: "local",
  281. command: ["node", "./mcp/server.js"],
  282. environment: { API_KEY: "secret" },
  283. disabled: false,
  284. timeout: 10000,
  285. },
  286. remote: {
  287. type: "remote",
  288. url: "https://mcp.example.com/mcp",
  289. headers: { Authorization: "Bearer token" },
  290. oauth: { client_id: "client", scope: "read write", callback_port: 19876 },
  291. disabled: true,
  292. },
  293. },
  294. })
  295. expect(documents[0]?.info.compaction).toEqual({
  296. auto: true,
  297. prune: false,
  298. keep: { turns: 3, tokens: 2000 },
  299. buffer: 10000,
  300. })
  301. expect(documents[0]?.info.skills).toEqual([
  302. "./skills",
  303. "~/shared-skills",
  304. "https://example.com/.well-known/skills/",
  305. ])
  306. expect(documents[0]?.info.instructions).toEqual([
  307. "CONTRIBUTING.md",
  308. ".cursor/rules/*.md",
  309. "https://example.com/shared-rules.md",
  310. ])
  311. expect(documents[0]?.info.references).toEqual({
  312. local: { path: "../library" },
  313. sdk: { repository: "github.com/example/sdk", branch: "main" },
  314. shorthand: "github.com/example/docs",
  315. })
  316. expect(documents[0]?.info.plugins).toEqual([
  317. "opencode-helicone-session",
  318. { package: "@my-org/audit-plugin", options: { endpoint: "https://audit.example.com" } },
  319. ])
  320. }).pipe(Effect.provide(testLayer(tmp.path)))
  321. }),
  322. ),
  323. ),
  324. )
  325. it.live("ignores invalid files while loading valid config values", () =>
  326. Effect.acquireRelease(
  327. Effect.promise(() => tmpdir()),
  328. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  329. ).pipe(
  330. Effect.flatMap((tmp) =>
  331. Effect.gen(function* () {
  332. yield* Effect.promise(() =>
  333. Promise.all([
  334. fs.writeFile(path.join(tmp.path, "config.json"), JSON.stringify({ $schema: "base" })),
  335. fs.writeFile(path.join(tmp.path, "opencode.json"), "{ invalid"),
  336. fs.writeFile(path.join(tmp.path, "opencode.jsonc"), JSON.stringify({ providers: { invalid: true } })),
  337. ]),
  338. )
  339. return yield* Effect.gen(function* () {
  340. const config = yield* Config.Service
  341. const documents = yield* config.get()
  342. expect(documents.map((document) => document.info.$schema)).toEqual(["base"])
  343. }).pipe(Effect.provide(testLayer(tmp.path)))
  344. }),
  345. ),
  346. ),
  347. )
  348. it.live("loads policy statements in reverse config order", () =>
  349. Effect.acquireRelease(
  350. Effect.promise(() => tmpdir()),
  351. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  352. ).pipe(
  353. Effect.flatMap((tmp) => {
  354. const global = path.join(tmp.path, "global")
  355. return Effect.gen(function* () {
  356. yield* Effect.promise(async () => {
  357. await fs.mkdir(global, { recursive: true })
  358. await fs.writeFile(
  359. path.join(global, "opencode.json"),
  360. JSON.stringify({
  361. experimental: { policies: [{ effect: "deny", action: "provider.use", resource: "openai" }] },
  362. }),
  363. )
  364. await fs.writeFile(
  365. path.join(tmp.path, "opencode.json"),
  366. JSON.stringify({
  367. experimental: { policies: [{ effect: "allow", action: "provider.use", resource: "openai" }] },
  368. }),
  369. )
  370. })
  371. return yield* Effect.gen(function* () {
  372. const policy = yield* Policy.Service
  373. expect(yield* policy.evaluate("provider.use", "openai", "allow")).toBe("deny")
  374. }).pipe(Effect.provide(testLayer(tmp.path, global)))
  375. })
  376. }),
  377. ),
  378. )
  379. it.live("loads global, ancestor, and .opencode configuration up to the project boundary", () =>
  380. Effect.acquireRelease(
  381. Effect.promise(() => tmpdir()),
  382. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  383. ).pipe(
  384. Effect.flatMap((tmp) => {
  385. const global = path.join(tmp.path, "global")
  386. const root = path.join(tmp.path, "repo")
  387. const parent = path.join(root, "packages")
  388. const directory = path.join(parent, "app")
  389. return Effect.gen(function* () {
  390. yield* Effect.promise(async () => {
  391. await fs.mkdir(global, { recursive: true })
  392. await fs.mkdir(directory, { recursive: true })
  393. await fs.mkdir(path.join(root, ".opencode"), { recursive: true })
  394. await fs.mkdir(path.join(directory, ".opencode"), { recursive: true })
  395. await Promise.all([
  396. fs.writeFile(path.join(tmp.path, "opencode.json"), JSON.stringify({ $schema: "outside" })),
  397. fs.writeFile(path.join(global, "opencode.json"), JSON.stringify({ $schema: "global" })),
  398. fs.writeFile(path.join(root, "opencode.json"), JSON.stringify({ $schema: "root" })),
  399. fs.writeFile(path.join(parent, "opencode.jsonc"), JSON.stringify({ $schema: "parent" })),
  400. fs.writeFile(path.join(directory, "config.json"), JSON.stringify({ $schema: "directory" })),
  401. fs.writeFile(path.join(root, ".opencode", "opencode.json"), JSON.stringify({ $schema: "root-dot" })),
  402. fs.writeFile(
  403. path.join(directory, ".opencode", "opencode.jsonc"),
  404. JSON.stringify({ $schema: "directory-dot" }),
  405. ),
  406. ])
  407. })
  408. return yield* Effect.gen(function* () {
  409. const config = yield* Config.Service
  410. const directories = yield* config.directories()
  411. const documents = yield* config.get()
  412. expect(directories).toEqual([
  413. AbsolutePath.make(global),
  414. AbsolutePath.make(path.join(root, ".opencode")),
  415. AbsolutePath.make(path.join(directory, ".opencode")),
  416. ])
  417. expect(documents.map((document) => document.info.$schema)).toEqual([
  418. "global",
  419. "root",
  420. "parent",
  421. "directory",
  422. "root-dot",
  423. "directory-dot",
  424. ])
  425. }).pipe(
  426. Effect.provide(
  427. testLayer(directory, global, root, {
  428. type: "git",
  429. store: AbsolutePath.make(path.join(root, ".git")),
  430. }),
  431. ),
  432. )
  433. })
  434. }),
  435. ),
  436. )
  437. })