config.test.ts 18 KB

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