config.test.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  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 { ConfigMigrateV1 } from "@opencode-ai/core/v1/config/migrate"
  8. import { FSUtil } from "@opencode-ai/core/fs-util"
  9. import { Global } from "@opencode-ai/core/global"
  10. import { Location } from "@opencode-ai/core/location"
  11. import { Policy } from "@opencode-ai/core/policy"
  12. import { Project } from "@opencode-ai/core/project"
  13. import { AbsolutePath } from "@opencode-ai/core/schema"
  14. import { location } from "../fixture/location"
  15. import { tmpdir } from "../fixture/tmpdir"
  16. import { testEffect } from "../lib/effect"
  17. const it = testEffect(Layer.empty)
  18. function testLayer(
  19. directory: string,
  20. globalDirectory = path.join(directory, "global"),
  21. projectDirectory = directory,
  22. vcs?: Project.Vcs,
  23. ) {
  24. return Config.locationLayer.pipe(
  25. Layer.provide(FSUtil.defaultLayer),
  26. Layer.provide(Global.layerWith({ config: globalDirectory })),
  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.effect("detects v1 configuration from any v1-only top-level key", () =>
  54. Effect.sync(() => {
  55. expect(ConfigMigrateV1.isV1({ snapshot: false })).toBe(true)
  56. expect(ConfigMigrateV1.isV1({ snapshot: false, agents: {} })).toBe(true)
  57. expect(ConfigMigrateV1.isV1({ shell: "/bin/zsh", model: "anthropic/claude" })).toBe(false)
  58. }),
  59. )
  60. it.live("returns an empty configuration when directory files do not exist", () =>
  61. Effect.acquireRelease(
  62. Effect.promise(() => tmpdir()),
  63. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  64. ).pipe(
  65. Effect.flatMap((tmp) =>
  66. Effect.gen(function* () {
  67. const config = yield* Config.Service
  68. const documents = yield* config.get()
  69. expect(documents).toEqual([])
  70. }).pipe(Effect.provide(testLayer(tmp.path))),
  71. ),
  72. ),
  73. )
  74. it.live("loads JSON and JSONC files from lowest to highest priority", () =>
  75. Effect.acquireRelease(
  76. Effect.promise(() => tmpdir()),
  77. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  78. ).pipe(
  79. Effect.flatMap((tmp) =>
  80. Effect.gen(function* () {
  81. yield* Effect.promise(() =>
  82. Promise.all([
  83. fs.writeFile(
  84. path.join(tmp.path, "config.json"),
  85. JSON.stringify({ $schema: "base", providers: { base: provider } }),
  86. ),
  87. fs.writeFile(
  88. path.join(tmp.path, "opencode.json"),
  89. JSON.stringify({ $schema: "middle", providers: { middle: provider } }),
  90. ),
  91. fs.writeFile(
  92. path.join(tmp.path, "opencode.jsonc"),
  93. `{
  94. // Later global files override scalar fields while retaining providers.
  95. "$schema": "last",
  96. "providers": { "last": ${JSON.stringify(provider)} },
  97. }`,
  98. ),
  99. ]),
  100. )
  101. return yield* Effect.gen(function* () {
  102. const config = yield* Config.Service
  103. const documents = yield* config.get()
  104. expect(documents).toHaveLength(3)
  105. expect(documents.map((document) => document.source.type)).toEqual(["file", "file", "file"])
  106. expect(documents.map((document) => document.info.$schema)).toEqual(["base", "middle", "last"])
  107. expect(documents[0]).toBeInstanceOf(Config.Loaded)
  108. expect(documents[0]?.source.type === "file" ? documents[0].source.path : undefined).toBe(
  109. path.join(tmp.path, "config.json"),
  110. )
  111. expect(documents[2]?.info.providers?.last).toBeInstanceOf(ConfigProvider.Info)
  112. yield* Effect.promise(() =>
  113. fs.writeFile(path.join(tmp.path, "opencode.jsonc"), JSON.stringify({ $schema: "changed" })),
  114. )
  115. expect((yield* config.get()).map((document) => document.info.$schema)).toEqual(["base", "middle", "last"])
  116. }).pipe(Effect.provide(testLayer(tmp.path)))
  117. }),
  118. ),
  119. ),
  120. )
  121. it.live("accepts $schema metadata without writing it into config files", () =>
  122. Effect.acquireRelease(
  123. Effect.promise(() => tmpdir()),
  124. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  125. ).pipe(
  126. Effect.flatMap((tmp) =>
  127. Effect.gen(function* () {
  128. const file = path.join(tmp.path, "opencode.json")
  129. const contents = JSON.stringify({
  130. shell: "/bin/zsh",
  131. experimental: { policies: [{ effect: "deny", action: "provider.use", resource: "openai" }] },
  132. providers: { local: provider },
  133. })
  134. yield* Effect.promise(() => fs.writeFile(file, contents))
  135. return yield* Effect.gen(function* () {
  136. const config = yield* Config.Service
  137. const documents = yield* config.get()
  138. expect(documents[0]?.info.$schema).toBeUndefined()
  139. expect(documents[0]?.info.shell).toBe("/bin/zsh")
  140. expect(documents[0]?.info.experimental?.policies?.[0]).toEqual({
  141. effect: "deny",
  142. action: "provider.use",
  143. resource: "openai",
  144. })
  145. expect(yield* Effect.promise(() => fs.readFile(file, "utf8"))).toBe(contents)
  146. }).pipe(Effect.provide(testLayer(tmp.path)))
  147. }),
  148. ),
  149. ),
  150. )
  151. it.live("loads supported scalar and resource configuration", () =>
  152. Effect.acquireRelease(
  153. Effect.promise(() => tmpdir()),
  154. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  155. ).pipe(
  156. Effect.flatMap((tmp) =>
  157. Effect.gen(function* () {
  158. yield* Effect.promise(() =>
  159. fs.writeFile(
  160. path.join(tmp.path, "opencode.json"),
  161. JSON.stringify({
  162. shell: "/bin/bash",
  163. model: "anthropic/claude",
  164. autoupdate: "notify",
  165. share: "disabled",
  166. enterprise: { url: "https://share.example.com" },
  167. username: "test-user",
  168. permissions: [
  169. { action: "bash", resource: "*", effect: "ask" },
  170. { action: "bash", resource: "git status", effect: "allow" },
  171. ],
  172. agents: {
  173. reviewer: {
  174. model: "openrouter/openai/gpt-5",
  175. variant: "high",
  176. options: {
  177. headers: { "x-agent": "reviewer" },
  178. aisdk: { request: { reasoningEffort: "high" } },
  179. },
  180. description: "Review changes for correctness",
  181. system: "Find regressions.",
  182. mode: "subagent",
  183. hidden: false,
  184. color: "warning",
  185. steps: 12,
  186. disabled: false,
  187. permissions: [{ action: "edit", resource: "*", effect: "deny" }],
  188. },
  189. },
  190. snapshots: false,
  191. watcher: { ignore: ["node_modules/**", "dist/**", ".git"] },
  192. formatter: {
  193. prettier: { disabled: true },
  194. custom: { command: ["custom-fmt", "$FILE"], extensions: [".foo"] },
  195. },
  196. lsp: { typescript: { disabled: true }, custom: { command: ["custom-lsp"], extensions: [".foo"] } },
  197. attachments: {
  198. image: { auto_resize: false, max_width: 1200, max_height: 900, max_base64_bytes: 1048576 },
  199. },
  200. tool_output: { max_lines: 1000, max_bytes: 32768 },
  201. mcp: {
  202. timeout: 5000,
  203. servers: {
  204. local: {
  205. type: "local",
  206. command: ["node", "./mcp/server.js"],
  207. environment: { API_KEY: "secret" },
  208. disabled: false,
  209. timeout: 10000,
  210. },
  211. remote: {
  212. type: "remote",
  213. url: "https://mcp.example.com/mcp",
  214. headers: { Authorization: "Bearer token" },
  215. oauth: { client_id: "client", scope: "read write", callback_port: 19876 },
  216. disabled: true,
  217. },
  218. },
  219. },
  220. compaction: {
  221. auto: true,
  222. prune: false,
  223. keep: { turns: 3, tokens: 2000 },
  224. buffer: 10000,
  225. },
  226. skills: ["./skills", "~/shared-skills", "https://example.com/.well-known/skills/"],
  227. instructions: ["CONTRIBUTING.md", ".cursor/rules/*.md", "https://example.com/shared-rules.md"],
  228. references: {
  229. local: { path: "../library" },
  230. sdk: { repository: "github.com/example/sdk", branch: "main" },
  231. shorthand: "github.com/example/docs",
  232. },
  233. plugins: [
  234. "opencode-helicone-session",
  235. { package: "@my-org/audit-plugin", options: { endpoint: "https://audit.example.com" } },
  236. ],
  237. }),
  238. ),
  239. )
  240. return yield* Effect.gen(function* () {
  241. const config = yield* Config.Service
  242. const documents = yield* config.get()
  243. expect(documents).toHaveLength(1)
  244. expect(documents[0]?.info.shell).toBe("/bin/bash")
  245. expect(documents[0]?.info.model).toBe("anthropic/claude")
  246. expect(documents[0]?.info.autoupdate).toBe("notify")
  247. expect(documents[0]?.info.share).toBe("disabled")
  248. expect(documents[0]?.info.enterprise).toEqual({ url: "https://share.example.com" })
  249. expect(documents[0]?.info.username).toBe("test-user")
  250. expect(documents[0]?.info.permissions).toEqual([
  251. { action: "bash", resource: "*", effect: "ask" },
  252. { action: "bash", resource: "git status", effect: "allow" },
  253. ])
  254. expect(documents[0]?.info.agents?.reviewer).toEqual({
  255. model: "openrouter/openai/gpt-5",
  256. variant: "high",
  257. options: {
  258. headers: { "x-agent": "reviewer" },
  259. aisdk: { request: { reasoningEffort: "high" } },
  260. },
  261. description: "Review changes for correctness",
  262. system: "Find regressions.",
  263. mode: "subagent",
  264. hidden: false,
  265. color: "warning",
  266. steps: 12,
  267. disabled: false,
  268. permissions: [{ action: "edit", resource: "*", effect: "deny" }],
  269. })
  270. expect(documents[0]?.info.snapshots).toBe(false)
  271. expect(documents[0]?.info.watcher).toEqual({ ignore: ["node_modules/**", "dist/**", ".git"] })
  272. expect(documents[0]?.info.formatter).toEqual({
  273. prettier: { disabled: true },
  274. custom: { command: ["custom-fmt", "$FILE"], extensions: [".foo"] },
  275. })
  276. expect(documents[0]?.info.lsp).toEqual({
  277. typescript: { disabled: true },
  278. custom: { command: ["custom-lsp"], extensions: [".foo"] },
  279. })
  280. expect(documents[0]?.info.attachments).toEqual({
  281. image: { auto_resize: false, max_width: 1200, max_height: 900, max_base64_bytes: 1048576 },
  282. })
  283. expect(documents[0]?.info.tool_output).toEqual({ max_lines: 1000, max_bytes: 32768 })
  284. expect(documents[0]?.info.mcp).toEqual({
  285. timeout: 5000,
  286. servers: {
  287. local: {
  288. type: "local",
  289. command: ["node", "./mcp/server.js"],
  290. environment: { API_KEY: "secret" },
  291. disabled: false,
  292. timeout: 10000,
  293. },
  294. remote: {
  295. type: "remote",
  296. url: "https://mcp.example.com/mcp",
  297. headers: { Authorization: "Bearer token" },
  298. oauth: { client_id: "client", scope: "read write", callback_port: 19876 },
  299. disabled: true,
  300. },
  301. },
  302. })
  303. expect(documents[0]?.info.compaction).toEqual({
  304. auto: true,
  305. prune: false,
  306. keep: { turns: 3, tokens: 2000 },
  307. buffer: 10000,
  308. })
  309. expect(documents[0]?.info.skills).toEqual([
  310. "./skills",
  311. "~/shared-skills",
  312. "https://example.com/.well-known/skills/",
  313. ])
  314. expect(documents[0]?.info.instructions).toEqual([
  315. "CONTRIBUTING.md",
  316. ".cursor/rules/*.md",
  317. "https://example.com/shared-rules.md",
  318. ])
  319. expect(documents[0]?.info.references).toEqual({
  320. local: { path: "../library" },
  321. sdk: { repository: "github.com/example/sdk", branch: "main" },
  322. shorthand: "github.com/example/docs",
  323. })
  324. expect(documents[0]?.info.plugins).toEqual([
  325. "opencode-helicone-session",
  326. { package: "@my-org/audit-plugin", options: { endpoint: "https://audit.example.com" } },
  327. ])
  328. }).pipe(Effect.provide(testLayer(tmp.path)))
  329. }),
  330. ),
  331. ),
  332. )
  333. it.live("migrates v1 configuration when a v1-only key is present", () =>
  334. Effect.acquireRelease(
  335. Effect.promise(() => tmpdir()),
  336. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  337. ).pipe(
  338. Effect.flatMap((tmp) =>
  339. Effect.gen(function* () {
  340. yield* Effect.promise(() =>
  341. fs.writeFile(
  342. path.join(tmp.path, "opencode.json"),
  343. JSON.stringify({
  344. shell: "/bin/zsh",
  345. snapshot: false,
  346. autoshare: true,
  347. permission: {
  348. bash: "ask",
  349. edit: { "*.md": "allow", "*": "deny" },
  350. },
  351. agent: {
  352. reviewer: {
  353. prompt: "Review changes.",
  354. disable: true,
  355. temperature: 0.2,
  356. permission: { read: "allow" },
  357. },
  358. },
  359. plugin: [
  360. "opencode-helicone-session",
  361. ["@my-org/audit-plugin", { endpoint: "https://audit.example.com" }],
  362. ],
  363. skills: { paths: ["./skills"], urls: ["https://example.com/.well-known/skills/"] },
  364. reference: { docs: { path: "../docs" } },
  365. attachment: { image: { auto_resize: false, max_width: 1200 } },
  366. compaction: { auto: true, tail_turns: 3, preserve_recent_tokens: 2000, reserved: 10000 },
  367. experimental: { mcp_timeout: 5000 },
  368. mcp: {
  369. local: { type: "local", command: ["node", "server.js"], enabled: false },
  370. remote: {
  371. type: "remote",
  372. url: "https://mcp.example.com",
  373. oauth: { clientId: "client", callbackPort: 19876 },
  374. },
  375. },
  376. }),
  377. ),
  378. )
  379. return yield* Effect.gen(function* () {
  380. const config = yield* Config.Service
  381. const documents = yield* config.get()
  382. expect(documents).toHaveLength(1)
  383. expect(documents[0]?.info).toBeInstanceOf(Config.Info)
  384. expect(documents[0]?.info.shell).toBe("/bin/zsh")
  385. expect(documents[0]?.info.snapshots).toBe(false)
  386. expect(documents[0]?.info.share).toBe("auto")
  387. expect(documents[0]?.info.permissions).toEqual([
  388. { action: "bash", resource: "*", effect: "ask" },
  389. { action: "edit", resource: "*.md", effect: "allow" },
  390. { action: "edit", resource: "*", effect: "deny" },
  391. ])
  392. expect(documents[0]?.info.agents?.reviewer).toMatchObject({
  393. system: "Review changes.",
  394. disabled: true,
  395. options: { body: { temperature: 0.2 } },
  396. permissions: [{ action: "read", resource: "*", effect: "allow" }],
  397. })
  398. expect(documents[0]?.info.plugins).toEqual([
  399. "opencode-helicone-session",
  400. { package: "@my-org/audit-plugin", options: { endpoint: "https://audit.example.com" } },
  401. ])
  402. expect(documents[0]?.info.skills).toEqual(["./skills", "https://example.com/.well-known/skills/"])
  403. expect(documents[0]?.info.references).toEqual({ docs: { path: "../docs" } })
  404. expect(documents[0]?.info.attachments).toEqual({ image: { auto_resize: false, max_width: 1200 } })
  405. expect(documents[0]?.info.compaction).toEqual({
  406. auto: true,
  407. prune: undefined,
  408. keep: { turns: 3, tokens: 2000 },
  409. buffer: 10000,
  410. })
  411. expect(documents[0]?.info.mcp).toMatchObject({
  412. timeout: 5000,
  413. servers: {
  414. local: { type: "local", command: ["node", "server.js"], disabled: true },
  415. remote: {
  416. type: "remote",
  417. url: "https://mcp.example.com",
  418. oauth: { client_id: "client", callback_port: 19876 },
  419. },
  420. },
  421. })
  422. }).pipe(Effect.provide(testLayer(tmp.path)))
  423. }),
  424. ),
  425. ),
  426. )
  427. it.live("ignores invalid files while loading valid config values", () =>
  428. Effect.acquireRelease(
  429. Effect.promise(() => tmpdir()),
  430. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  431. ).pipe(
  432. Effect.flatMap((tmp) =>
  433. Effect.gen(function* () {
  434. yield* Effect.promise(() =>
  435. Promise.all([
  436. fs.writeFile(path.join(tmp.path, "config.json"), JSON.stringify({ $schema: "base" })),
  437. fs.writeFile(path.join(tmp.path, "opencode.json"), "{ invalid"),
  438. fs.writeFile(path.join(tmp.path, "opencode.jsonc"), JSON.stringify({ providers: { invalid: true } })),
  439. ]),
  440. )
  441. return yield* Effect.gen(function* () {
  442. const config = yield* Config.Service
  443. const documents = yield* config.get()
  444. expect(documents.map((document) => document.info.$schema)).toEqual(["base"])
  445. }).pipe(Effect.provide(testLayer(tmp.path)))
  446. }),
  447. ),
  448. ),
  449. )
  450. it.live("loads policy statements in reverse config order", () =>
  451. Effect.acquireRelease(
  452. Effect.promise(() => tmpdir()),
  453. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  454. ).pipe(
  455. Effect.flatMap((tmp) => {
  456. const global = path.join(tmp.path, "global")
  457. return Effect.gen(function* () {
  458. yield* Effect.promise(async () => {
  459. await fs.mkdir(global, { recursive: true })
  460. await fs.writeFile(
  461. path.join(global, "opencode.json"),
  462. JSON.stringify({
  463. experimental: { policies: [{ effect: "deny", action: "provider.use", resource: "openai" }] },
  464. }),
  465. )
  466. await fs.writeFile(
  467. path.join(tmp.path, "opencode.json"),
  468. JSON.stringify({
  469. experimental: { policies: [{ effect: "allow", action: "provider.use", resource: "openai" }] },
  470. }),
  471. )
  472. })
  473. return yield* Effect.gen(function* () {
  474. const policy = yield* Policy.Service
  475. expect(yield* policy.evaluate("provider.use", "openai", "allow")).toBe("deny")
  476. }).pipe(Effect.provide(testLayer(tmp.path, global)))
  477. })
  478. }),
  479. ),
  480. )
  481. it.live("loads global, ancestor, and .opencode configuration up to the project boundary", () =>
  482. Effect.acquireRelease(
  483. Effect.promise(() => tmpdir()),
  484. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  485. ).pipe(
  486. Effect.flatMap((tmp) => {
  487. const global = path.join(tmp.path, "global")
  488. const root = path.join(tmp.path, "repo")
  489. const parent = path.join(root, "packages")
  490. const directory = path.join(parent, "app")
  491. return Effect.gen(function* () {
  492. yield* Effect.promise(async () => {
  493. await fs.mkdir(global, { recursive: true })
  494. await fs.mkdir(directory, { recursive: true })
  495. await fs.mkdir(path.join(root, ".opencode"), { recursive: true })
  496. await fs.mkdir(path.join(directory, ".opencode"), { recursive: true })
  497. await Promise.all([
  498. fs.writeFile(path.join(tmp.path, "opencode.json"), JSON.stringify({ $schema: "outside" })),
  499. fs.writeFile(path.join(global, "opencode.json"), JSON.stringify({ $schema: "global" })),
  500. fs.writeFile(path.join(root, "opencode.json"), JSON.stringify({ $schema: "root" })),
  501. fs.writeFile(path.join(parent, "opencode.jsonc"), JSON.stringify({ $schema: "parent" })),
  502. fs.writeFile(path.join(directory, "config.json"), JSON.stringify({ $schema: "directory" })),
  503. fs.writeFile(path.join(root, ".opencode", "opencode.json"), JSON.stringify({ $schema: "root-dot" })),
  504. fs.writeFile(
  505. path.join(directory, ".opencode", "opencode.jsonc"),
  506. JSON.stringify({ $schema: "directory-dot" }),
  507. ),
  508. ])
  509. })
  510. return yield* Effect.gen(function* () {
  511. const config = yield* Config.Service
  512. const directories = yield* config.directories()
  513. const documents = yield* config.get()
  514. expect(directories).toEqual([
  515. AbsolutePath.make(global),
  516. AbsolutePath.make(path.join(root, ".opencode")),
  517. AbsolutePath.make(path.join(directory, ".opencode")),
  518. ])
  519. expect(documents.map((document) => document.info.$schema)).toEqual([
  520. "global",
  521. "root",
  522. "parent",
  523. "directory",
  524. "root-dot",
  525. "directory-dot",
  526. ])
  527. }).pipe(
  528. Effect.provide(
  529. testLayer(directory, global, root, {
  530. type: "git",
  531. store: AbsolutePath.make(path.join(root, ".git")),
  532. }),
  533. ),
  534. )
  535. })
  536. }),
  537. ),
  538. )
  539. })