config.test.ts 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773
  1. import path from "path"
  2. import fs from "fs/promises"
  3. import { describe, expect } from "bun:test"
  4. import { Effect, Layer, Schema } from "effect"
  5. import { FastCheck } from "effect/testing"
  6. import { Config } from "@opencode-ai/core/config"
  7. import { ConfigProvider } from "@opencode-ai/core/config/provider"
  8. import { ConfigMigrateV1 } from "@opencode-ai/core/v1/config/migrate"
  9. import { ConfigV1 } from "@opencode-ai/core/v1/config/config"
  10. import { FSUtil } from "@opencode-ai/core/fs-util"
  11. import { Global } from "@opencode-ai/core/global"
  12. import { Location } from "@opencode-ai/core/location"
  13. import { Policy } from "@opencode-ai/core/policy"
  14. import { Project } from "@opencode-ai/core/project"
  15. import { AbsolutePath } from "@opencode-ai/core/schema"
  16. import { location } from "../fixture/location"
  17. import { tmpdir } from "../fixture/tmpdir"
  18. import { testEffect } from "../lib/effect"
  19. const it = testEffect(Layer.empty)
  20. function testLayer(
  21. directory: string,
  22. globalDirectory = path.join(directory, "global"),
  23. projectDirectory = directory,
  24. vcs?: Project.Vcs,
  25. ) {
  26. return Config.locationLayer.pipe(
  27. Layer.provide(FSUtil.defaultLayer),
  28. Layer.provide(Global.layerWith({ config: globalDirectory })),
  29. Layer.provide(
  30. Layer.succeed(
  31. Location.Service,
  32. Location.Service.of(
  33. location(
  34. { directory: AbsolutePath.make(directory) },
  35. { projectDirectory: AbsolutePath.make(projectDirectory), vcs },
  36. ),
  37. ),
  38. ),
  39. ),
  40. )
  41. }
  42. const provider = {
  43. api: { type: "native", settings: {} },
  44. request: {
  45. headers: {},
  46. body: {},
  47. },
  48. models: {},
  49. }
  50. describe("Config", () => {
  51. it.effect("returns the latest defined scalar from priority-ordered documents", () =>
  52. Effect.sync(() => {
  53. const entries = [
  54. new Config.Document({ type: "document", info: new Config.Info({ model: "openrouter/openai/gpt-5" }) }),
  55. new Config.Directory({ type: "directory", path: AbsolutePath.make("/skills") }),
  56. new Config.Document({ type: "document", info: new Config.Info({}) }),
  57. new Config.Document({ type: "document", info: new Config.Info({ model: "openrouter/openai/gpt-5.5" }) }),
  58. ]
  59. expect(Config.latest(entries, "model")).toBe("openrouter/openai/gpt-5.5")
  60. expect(Config.latest(entries, "default_agent")).toBeUndefined()
  61. }),
  62. )
  63. it.effect("detects v1 configuration from any v1-only top-level key", () =>
  64. Effect.sync(() => {
  65. expect(ConfigMigrateV1.isV1({ snapshot: false })).toBe(true)
  66. expect(ConfigMigrateV1.isV1({ snapshot: false, agents: {} })).toBe(true)
  67. expect(ConfigMigrateV1.isV1({ reference: {} })).toBe(true)
  68. expect(ConfigMigrateV1.isV1({ shell: "/bin/zsh", model: "anthropic/claude" })).toBe(false)
  69. expect(ConfigMigrateV1.isV1({ references: {} })).toBe(false)
  70. }),
  71. )
  72. it.effect("migrates arbitrary v1 configuration into valid v2 configuration", () =>
  73. Effect.sync(() => {
  74. FastCheck.assert(
  75. FastCheck.property(Schema.toArbitrary(ConfigV1.Info), (info) => {
  76. Schema.decodeUnknownSync(Config.Info)(ConfigMigrateV1.migrate(info), { errors: "all" })
  77. }),
  78. { numRuns: 100 },
  79. )
  80. }),
  81. )
  82. it.effect("migrates v1 provider setup options into AISDK settings", () =>
  83. Effect.sync(() => {
  84. const migrated = ConfigMigrateV1.migrate({
  85. provider: {
  86. bedrock: {
  87. npm: "@ai-sdk/amazon-bedrock",
  88. options: {
  89. headers: { "x-test": "1" },
  90. body: { trace: true },
  91. region: "us-east-1",
  92. profile: "dev",
  93. },
  94. },
  95. },
  96. })
  97. expect(migrated.providers?.bedrock?.api).toEqual({
  98. type: "aisdk",
  99. package: "@ai-sdk/amazon-bedrock",
  100. url: undefined,
  101. settings: { region: "us-east-1", profile: "dev" },
  102. })
  103. expect(migrated.providers?.bedrock?.request).toEqual({
  104. headers: { "x-test": "1" },
  105. body: { trace: true },
  106. })
  107. }),
  108. )
  109. it.effect("migrates v1 command configuration", () =>
  110. Effect.sync(() => {
  111. expect(
  112. ConfigMigrateV1.migrate({
  113. command: {
  114. review: {
  115. template: "Review changes",
  116. description: "Review code",
  117. agent: "reviewer",
  118. model: "anthropic/claude",
  119. variant: "high",
  120. subtask: true,
  121. },
  122. },
  123. }).commands,
  124. ).toEqual({
  125. review: {
  126. template: "Review changes",
  127. description: "Review code",
  128. agent: "reviewer",
  129. model: "anthropic/claude",
  130. variant: "high",
  131. subtask: true,
  132. },
  133. })
  134. }),
  135. )
  136. it.live("returns an empty configuration when directory files do not exist", () =>
  137. Effect.acquireRelease(
  138. Effect.promise(() => tmpdir()),
  139. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  140. ).pipe(
  141. Effect.flatMap((tmp) =>
  142. Effect.gen(function* () {
  143. const config = yield* Config.Service
  144. const entries = yield* config.entries()
  145. expect(entries).toEqual([
  146. new Config.Directory({ type: "directory", path: AbsolutePath.make(path.join(tmp.path, "global")) }),
  147. ])
  148. }).pipe(Effect.provide(testLayer(tmp.path))),
  149. ),
  150. ),
  151. )
  152. it.live("loads JSON and JSONC files from lowest to highest priority", () =>
  153. Effect.acquireRelease(
  154. Effect.promise(() => tmpdir()),
  155. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  156. ).pipe(
  157. Effect.flatMap((tmp) =>
  158. Effect.gen(function* () {
  159. yield* Effect.promise(() =>
  160. Promise.all([
  161. fs.writeFile(
  162. path.join(tmp.path, "config.json"),
  163. JSON.stringify({ $schema: "base", providers: { base: provider } }),
  164. ),
  165. fs.writeFile(
  166. path.join(tmp.path, "opencode.json"),
  167. JSON.stringify({ $schema: "middle", providers: { middle: provider } }),
  168. ),
  169. fs.writeFile(
  170. path.join(tmp.path, "opencode.jsonc"),
  171. `{
  172. // Later global files override scalar fields while retaining providers.
  173. "$schema": "last",
  174. "providers": { "last": ${JSON.stringify(provider)} },
  175. }`,
  176. ),
  177. ]),
  178. )
  179. return yield* Effect.gen(function* () {
  180. const config = yield* Config.Service
  181. const documents = (yield* config.entries()).filter((entry) => entry.type === "document")
  182. expect(documents).toHaveLength(3)
  183. expect(documents.map((document) => document.type)).toEqual(["document", "document", "document"])
  184. expect(documents.map((document) => document.info.$schema)).toEqual(["base", "middle", "last"])
  185. expect(documents[0]).toBeInstanceOf(Config.Document)
  186. expect(documents[0]?.path).toBe(path.join(tmp.path, "config.json"))
  187. expect(documents[2]?.info.providers?.last).toBeInstanceOf(ConfigProvider.Info)
  188. yield* Effect.promise(() =>
  189. fs.writeFile(path.join(tmp.path, "opencode.jsonc"), JSON.stringify({ $schema: "changed" })),
  190. )
  191. expect(
  192. (yield* config.entries())
  193. .filter((entry) => entry.type === "document")
  194. .map((document) => document.info.$schema),
  195. ).toEqual(["base", "middle", "last"])
  196. }).pipe(Effect.provide(testLayer(tmp.path)))
  197. }),
  198. ),
  199. ),
  200. )
  201. it.live("accepts $schema metadata without writing it into config files", () =>
  202. Effect.acquireRelease(
  203. Effect.promise(() => tmpdir()),
  204. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  205. ).pipe(
  206. Effect.flatMap((tmp) =>
  207. Effect.gen(function* () {
  208. const file = path.join(tmp.path, "opencode.json")
  209. const contents = JSON.stringify({
  210. shell: "/bin/zsh",
  211. experimental: { policies: [{ effect: "deny", action: "provider.use", resource: "openai" }] },
  212. providers: { local: provider },
  213. })
  214. yield* Effect.promise(() => fs.writeFile(file, contents))
  215. return yield* Effect.gen(function* () {
  216. const config = yield* Config.Service
  217. const documents = (yield* config.entries()).filter((entry) => entry.type === "document")
  218. expect(documents[0]?.info.$schema).toBeUndefined()
  219. expect(documents[0]?.info.shell).toBe("/bin/zsh")
  220. expect(documents[0]?.info.experimental?.policies?.[0]).toEqual({
  221. effect: "deny",
  222. action: "provider.use",
  223. resource: "openai",
  224. })
  225. expect(yield* Effect.promise(() => fs.readFile(file, "utf8"))).toBe(contents)
  226. }).pipe(Effect.provide(testLayer(tmp.path)))
  227. }),
  228. ),
  229. ),
  230. )
  231. it.live("loads supported scalar and resource configuration", () =>
  232. Effect.acquireRelease(
  233. Effect.promise(() => tmpdir()),
  234. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  235. ).pipe(
  236. Effect.flatMap((tmp) =>
  237. Effect.gen(function* () {
  238. yield* Effect.promise(() =>
  239. fs.writeFile(
  240. path.join(tmp.path, "opencode.json"),
  241. JSON.stringify({
  242. shell: "/bin/bash",
  243. model: "anthropic/claude",
  244. default_agent: "reviewer",
  245. autoupdate: "notify",
  246. share: "disabled",
  247. enterprise: { url: "https://share.example.com" },
  248. username: "test-user",
  249. permissions: [
  250. { action: "bash", resource: "*", effect: "ask" },
  251. { action: "bash", resource: "git status", effect: "allow" },
  252. ],
  253. agents: {
  254. reviewer: {
  255. model: "openrouter/openai/gpt-5",
  256. variant: "high",
  257. request: {
  258. headers: { "x-agent": "reviewer" },
  259. body: { 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. },
  271. snapshots: false,
  272. watcher: { ignore: ["node_modules/**", "dist/**", ".git"] },
  273. formatter: {
  274. prettier: { disabled: true },
  275. custom: { command: ["custom-fmt", "$FILE"], extensions: [".foo"] },
  276. },
  277. lsp: { typescript: { disabled: true }, custom: { command: ["custom-lsp"], extensions: [".foo"] } },
  278. attachments: {
  279. image: { auto_resize: false, max_width: 1200, max_height: 900, max_base64_bytes: 1048576 },
  280. },
  281. tool_output: { max_lines: 1000, max_bytes: 32768 },
  282. mcp: {
  283. timeout: 5000,
  284. servers: {
  285. local: {
  286. type: "local",
  287. command: ["node", "./mcp/server.js"],
  288. environment: { API_KEY: "secret" },
  289. disabled: false,
  290. timeout: 10000,
  291. },
  292. remote: {
  293. type: "remote",
  294. url: "https://mcp.example.com/mcp",
  295. headers: { Authorization: "Bearer token" },
  296. oauth: { client_id: "client", scope: "read write", callback_port: 19876 },
  297. disabled: true,
  298. },
  299. },
  300. },
  301. compaction: {
  302. auto: true,
  303. prune: false,
  304. keep: { tokens: 2000 },
  305. buffer: 10000,
  306. },
  307. skills: ["./skills", "~/shared-skills", "https://example.com/.well-known/skills/"],
  308. instructions: ["CONTRIBUTING.md", ".cursor/rules/*.md", "https://example.com/shared-rules.md"],
  309. references: {
  310. local: { path: "../library" },
  311. sdk: { repository: "github.com/example/sdk", branch: "main" },
  312. shorthand: "github.com/example/docs",
  313. },
  314. plugins: [
  315. "opencode-helicone-session",
  316. { package: "@my-org/audit-plugin", options: { endpoint: "https://audit.example.com" } },
  317. ],
  318. }),
  319. ),
  320. )
  321. return yield* Effect.gen(function* () {
  322. const config = yield* Config.Service
  323. const documents = (yield* config.entries()).filter((entry) => entry.type === "document")
  324. expect(documents).toHaveLength(1)
  325. expect(documents[0]?.info.shell).toBe("/bin/bash")
  326. expect(documents[0]?.info.model).toBe("anthropic/claude")
  327. expect(documents[0]?.info.default_agent).toBe("reviewer")
  328. expect(documents[0]?.info.autoupdate).toBe("notify")
  329. expect(documents[0]?.info.share).toBe("disabled")
  330. expect(documents[0]?.info.enterprise).toEqual({ url: "https://share.example.com" })
  331. expect(documents[0]?.info.username).toBe("test-user")
  332. expect(documents[0]?.info.permissions).toEqual([
  333. { action: "bash", resource: "*", effect: "ask" },
  334. { action: "bash", resource: "git status", effect: "allow" },
  335. ])
  336. const reviewer = documents[0]?.info.agents?.reviewer
  337. expect(reviewer?.model).toBe("openrouter/openai/gpt-5")
  338. expect(reviewer?.variant).toBe("high")
  339. expect(reviewer?.request).toEqual({
  340. headers: { "x-agent": "reviewer" },
  341. body: { reasoningEffort: "high" },
  342. })
  343. expect(reviewer?.description).toBe("Review changes for correctness")
  344. expect(reviewer?.system).toBe("Find regressions.")
  345. expect(reviewer?.mode).toBe("subagent")
  346. expect(reviewer?.hidden).toBe(false)
  347. expect(reviewer?.color).toBe("warning")
  348. expect(reviewer?.steps).toBe(12)
  349. expect(reviewer?.disabled).toBe(false)
  350. expect(reviewer?.permissions).toEqual([{ action: "edit", resource: "*", effect: "deny" }])
  351. expect(documents[0]?.info.snapshots).toBe(false)
  352. expect(documents[0]?.info.watcher).toEqual({ ignore: ["node_modules/**", "dist/**", ".git"] })
  353. expect(documents[0]?.info.formatter).toEqual({
  354. prettier: { disabled: true },
  355. custom: { command: ["custom-fmt", "$FILE"], extensions: [".foo"] },
  356. })
  357. expect(documents[0]?.info.lsp).toEqual({
  358. typescript: { disabled: true },
  359. custom: { command: ["custom-lsp"], extensions: [".foo"] },
  360. })
  361. expect(documents[0]?.info.attachments).toEqual({
  362. image: { auto_resize: false, max_width: 1200, max_height: 900, max_base64_bytes: 1048576 },
  363. })
  364. expect(documents[0]?.info.tool_output).toEqual({ max_lines: 1000, max_bytes: 32768 })
  365. expect(documents[0]?.info.mcp).toEqual({
  366. timeout: 5000,
  367. servers: {
  368. local: {
  369. type: "local",
  370. command: ["node", "./mcp/server.js"],
  371. environment: { API_KEY: "secret" },
  372. disabled: false,
  373. timeout: 10000,
  374. },
  375. remote: {
  376. type: "remote",
  377. url: "https://mcp.example.com/mcp",
  378. headers: { Authorization: "Bearer token" },
  379. oauth: { client_id: "client", scope: "read write", callback_port: 19876 },
  380. disabled: true,
  381. },
  382. },
  383. })
  384. expect(documents[0]?.info.compaction).toEqual({
  385. auto: true,
  386. prune: false,
  387. keep: { tokens: 2000 },
  388. buffer: 10000,
  389. })
  390. expect(documents[0]?.info.skills).toEqual([
  391. "./skills",
  392. "~/shared-skills",
  393. "https://example.com/.well-known/skills/",
  394. ])
  395. expect(documents[0]?.info.instructions).toEqual([
  396. "CONTRIBUTING.md",
  397. ".cursor/rules/*.md",
  398. "https://example.com/shared-rules.md",
  399. ])
  400. expect(documents[0]?.info.references).toEqual({
  401. local: { path: "../library" },
  402. sdk: { repository: "github.com/example/sdk", branch: "main" },
  403. shorthand: "github.com/example/docs",
  404. })
  405. expect(documents[0]?.info.plugins).toEqual([
  406. "opencode-helicone-session",
  407. { package: "@my-org/audit-plugin", options: { endpoint: "https://audit.example.com" } },
  408. ])
  409. }).pipe(Effect.provide(testLayer(tmp.path)))
  410. }),
  411. ),
  412. ),
  413. )
  414. it.live("migrates the deprecated reference key into references", () =>
  415. Effect.acquireRelease(
  416. Effect.promise(() => tmpdir()),
  417. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  418. ).pipe(
  419. Effect.flatMap((tmp) =>
  420. Effect.gen(function* () {
  421. yield* Effect.promise(() =>
  422. fs.writeFile(
  423. path.join(tmp.path, "opencode.json"),
  424. JSON.stringify({
  425. reference: {
  426. local: { path: "../library" },
  427. sdk: { repository: "github.com/example/sdk", branch: "main" },
  428. shorthand: "github.com/example/docs",
  429. },
  430. }),
  431. ),
  432. )
  433. return yield* Effect.gen(function* () {
  434. const config = yield* Config.Service
  435. const documents = (yield* config.entries()).filter((entry) => entry.type === "document")
  436. expect(documents).toHaveLength(1)
  437. expect(documents[0]?.info.references).toEqual({
  438. local: { path: "../library" },
  439. sdk: { repository: "github.com/example/sdk", branch: "main" },
  440. shorthand: "github.com/example/docs",
  441. })
  442. }).pipe(Effect.provide(testLayer(tmp.path)))
  443. }),
  444. ),
  445. ),
  446. )
  447. it.live("migrates v1 configuration when a v1-only key is present", () =>
  448. Effect.acquireRelease(
  449. Effect.promise(() => tmpdir()),
  450. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  451. ).pipe(
  452. Effect.flatMap((tmp) =>
  453. Effect.gen(function* () {
  454. yield* Effect.promise(() =>
  455. fs.writeFile(
  456. path.join(tmp.path, "opencode.json"),
  457. JSON.stringify({
  458. shell: "/bin/zsh",
  459. default_agent: "reviewer",
  460. snapshot: false,
  461. autoshare: true,
  462. permission: {
  463. bash: "ask",
  464. edit: { "*.md": "allow", "*": "deny" },
  465. question: "deny",
  466. },
  467. agent: {
  468. reviewer: {
  469. prompt: "Review changes.",
  470. disable: true,
  471. temperature: 0.2,
  472. permission: { read: "allow" },
  473. },
  474. },
  475. plugin: [
  476. "opencode-helicone-session",
  477. ["@my-org/audit-plugin", { endpoint: "https://audit.example.com" }],
  478. ],
  479. skills: { paths: ["./skills"], urls: ["https://example.com/.well-known/skills/"] },
  480. references: {
  481. docs: { path: "../docs", description: "Use for product documentation", hidden: true },
  482. },
  483. attachment: { image: { auto_resize: false, max_width: 1200 } },
  484. provider: {
  485. custom: {
  486. options: { apiKey: "secret" },
  487. models: {
  488. model: {
  489. options: { reasoningEffort: "high" },
  490. variants: { fast: { temperature: 0.2 } },
  491. },
  492. },
  493. },
  494. openai: {
  495. npm: "@ai-sdk/openai",
  496. options: { apiKey: "secret", organization: "org" },
  497. models: {
  498. model: {
  499. options: { temperature: 0.3, reasoningEffort: "high", serviceTier: "priority" },
  500. variants: { high: { reasoningEffort: "high", reasoningSummary: "auto" } },
  501. },
  502. },
  503. },
  504. anthropic: {
  505. npm: "@ai-sdk/anthropic",
  506. models: {
  507. model: {
  508. options: {
  509. effort: "high",
  510. taskBudget: 4096,
  511. metadata: { userId: "user-1" },
  512. },
  513. },
  514. },
  515. },
  516. },
  517. compaction: { auto: true, tail_turns: 3, preserve_recent_tokens: 2000, reserved: 10000 },
  518. experimental: { mcp_timeout: 5000 },
  519. mcp: {
  520. local: { type: "local", command: ["node", "server.js"], enabled: false },
  521. remote: {
  522. type: "remote",
  523. url: "https://mcp.example.com",
  524. oauth: { clientId: "client", callbackPort: 19876 },
  525. },
  526. },
  527. }),
  528. ),
  529. )
  530. return yield* Effect.gen(function* () {
  531. const config = yield* Config.Service
  532. const documents = (yield* config.entries()).filter((entry) => entry.type === "document")
  533. expect(documents).toHaveLength(1)
  534. expect(documents[0]?.info).toBeInstanceOf(Config.Info)
  535. expect(documents[0]?.info.shell).toBe("/bin/zsh")
  536. expect(documents[0]?.info.default_agent).toBe("reviewer")
  537. expect(documents[0]?.info.snapshots).toBe(false)
  538. expect(documents[0]?.info.share).toBe("auto")
  539. expect(documents[0]?.info.permissions).toEqual([
  540. { action: "bash", resource: "*", effect: "ask" },
  541. { action: "edit", resource: "*.md", effect: "allow" },
  542. { action: "edit", resource: "*", effect: "deny" },
  543. { action: "question", resource: "*", effect: "deny" },
  544. ])
  545. expect(documents[0]?.info.agents?.reviewer).toMatchObject({
  546. system: "Review changes.",
  547. disabled: true,
  548. request: { body: { temperature: 0.2 } },
  549. permissions: [{ action: "read", resource: "*", effect: "allow" }],
  550. })
  551. expect(documents[0]?.info.plugins).toEqual([
  552. "opencode-helicone-session",
  553. { package: "@my-org/audit-plugin", options: { endpoint: "https://audit.example.com" } },
  554. ])
  555. expect(documents[0]?.info.skills).toEqual(["./skills", "https://example.com/.well-known/skills/"])
  556. expect(documents[0]?.info.references).toEqual({
  557. docs: { path: "../docs", description: "Use for product documentation", hidden: true },
  558. })
  559. expect(documents[0]?.info.attachments).toEqual({ image: { auto_resize: false, max_width: 1200 } })
  560. expect(documents[0]?.info.providers?.custom).toMatchObject({
  561. request: { body: { apiKey: "secret" } },
  562. models: {
  563. model: {
  564. request: { body: { reasoningEffort: "high" } },
  565. variants: [{ id: "fast", body: { temperature: 0.2 } }],
  566. },
  567. },
  568. })
  569. expect(documents[0]?.info.providers?.openai).toMatchObject({
  570. api: { settings: {} },
  571. request: { headers: { Authorization: "Bearer secret", "OpenAI-Organization": "org" } },
  572. models: {
  573. model: {
  574. request: {
  575. body: { temperature: 0.3, reasoningEffort: "high", serviceTier: "priority" },
  576. },
  577. variants: [{ id: "high", body: { reasoningEffort: "high", reasoningSummary: "auto" } }],
  578. },
  579. },
  580. })
  581. expect(documents[0]?.info.providers?.anthropic).toMatchObject({
  582. models: {
  583. model: {
  584. request: {
  585. body: {
  586. output_config: { effort: "high", task_budget: 4096 },
  587. metadata: { user_id: "user-1" },
  588. },
  589. },
  590. },
  591. },
  592. })
  593. expect(documents[0]?.info.compaction).toEqual({
  594. auto: true,
  595. prune: undefined,
  596. keep: { tokens: 2000 },
  597. buffer: 10000,
  598. })
  599. expect(documents[0]?.info.mcp).toMatchObject({
  600. timeout: 5000,
  601. servers: {
  602. local: { type: "local", command: ["node", "server.js"], disabled: true },
  603. remote: {
  604. type: "remote",
  605. url: "https://mcp.example.com",
  606. oauth: { client_id: "client", callback_port: 19876 },
  607. },
  608. },
  609. })
  610. }).pipe(Effect.provide(testLayer(tmp.path)))
  611. }),
  612. ),
  613. ),
  614. )
  615. it.live("ignores invalid files while loading valid config values", () =>
  616. Effect.acquireRelease(
  617. Effect.promise(() => tmpdir()),
  618. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  619. ).pipe(
  620. Effect.flatMap((tmp) =>
  621. Effect.gen(function* () {
  622. yield* Effect.promise(() =>
  623. Promise.all([
  624. fs.writeFile(path.join(tmp.path, "config.json"), JSON.stringify({ $schema: "base" })),
  625. fs.writeFile(path.join(tmp.path, "opencode.json"), "{ invalid"),
  626. fs.writeFile(path.join(tmp.path, "opencode.jsonc"), JSON.stringify({ providers: { invalid: true } })),
  627. ]),
  628. )
  629. return yield* Effect.gen(function* () {
  630. const config = yield* Config.Service
  631. const documents = (yield* config.entries()).filter((entry) => entry.type === "document")
  632. expect(documents.map((document) => document.info.$schema)).toEqual(["base"])
  633. }).pipe(Effect.provide(testLayer(tmp.path)))
  634. }),
  635. ),
  636. ),
  637. )
  638. it.live("loads policy statements in reverse config order", () =>
  639. Effect.acquireRelease(
  640. Effect.promise(() => tmpdir()),
  641. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  642. ).pipe(
  643. Effect.flatMap((tmp) => {
  644. const global = path.join(tmp.path, "global")
  645. return Effect.gen(function* () {
  646. yield* Effect.promise(async () => {
  647. await fs.mkdir(global, { recursive: true })
  648. await fs.writeFile(
  649. path.join(global, "opencode.json"),
  650. JSON.stringify({
  651. experimental: { policies: [{ effect: "deny", action: "provider.use", resource: "openai" }] },
  652. }),
  653. )
  654. await fs.writeFile(
  655. path.join(tmp.path, "opencode.json"),
  656. JSON.stringify({
  657. experimental: { policies: [{ effect: "allow", action: "provider.use", resource: "openai" }] },
  658. }),
  659. )
  660. })
  661. return yield* Effect.gen(function* () {
  662. const policy = yield* Policy.Service
  663. expect(yield* policy.evaluate("provider.use", "openai", "allow")).toBe("deny")
  664. }).pipe(Effect.provide(testLayer(tmp.path, global)))
  665. })
  666. }),
  667. ),
  668. )
  669. it.live("loads global, ancestor, and .opencode configuration up to the project boundary", () =>
  670. Effect.acquireRelease(
  671. Effect.promise(() => tmpdir()),
  672. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
  673. ).pipe(
  674. Effect.flatMap((tmp) => {
  675. const global = path.join(tmp.path, "global")
  676. const root = path.join(tmp.path, "repo")
  677. const parent = path.join(root, "packages")
  678. const directory = path.join(parent, "app")
  679. return Effect.gen(function* () {
  680. yield* Effect.promise(async () => {
  681. await fs.mkdir(global, { recursive: true })
  682. await fs.mkdir(directory, { recursive: true })
  683. await fs.mkdir(path.join(root, ".opencode"), { recursive: true })
  684. await fs.mkdir(path.join(directory, ".opencode"), { recursive: true })
  685. await Promise.all([
  686. fs.writeFile(path.join(tmp.path, "opencode.json"), JSON.stringify({ $schema: "outside" })),
  687. fs.writeFile(path.join(global, "opencode.json"), JSON.stringify({ $schema: "global" })),
  688. fs.writeFile(path.join(root, "opencode.json"), JSON.stringify({ $schema: "root" })),
  689. fs.writeFile(path.join(parent, "opencode.jsonc"), JSON.stringify({ $schema: "parent" })),
  690. fs.writeFile(path.join(directory, "config.json"), JSON.stringify({ $schema: "directory" })),
  691. fs.writeFile(path.join(root, ".opencode", "opencode.json"), JSON.stringify({ $schema: "root-dot" })),
  692. fs.writeFile(
  693. path.join(directory, ".opencode", "opencode.jsonc"),
  694. JSON.stringify({ $schema: "directory-dot" }),
  695. ),
  696. ])
  697. })
  698. return yield* Effect.gen(function* () {
  699. const config = yield* Config.Service
  700. const entries = yield* config.entries()
  701. const documents = entries.filter((entry) => entry.type === "document")
  702. expect(entries.filter((entry) => entry.type === "directory").map((entry) => entry.path)).toEqual([
  703. AbsolutePath.make(global),
  704. AbsolutePath.make(path.join(root, ".opencode")),
  705. AbsolutePath.make(path.join(directory, ".opencode")),
  706. ])
  707. expect(documents.map((document) => document.info.$schema)).toEqual([
  708. "global",
  709. "root",
  710. "parent",
  711. "directory",
  712. "root-dot",
  713. "directory-dot",
  714. ])
  715. expect(entries.map((entry) => (entry.type === "document" ? entry.info.$schema : entry.path))).toEqual([
  716. "global",
  717. AbsolutePath.make(global),
  718. "root",
  719. "parent",
  720. "directory",
  721. "root-dot",
  722. AbsolutePath.make(path.join(root, ".opencode")),
  723. "directory-dot",
  724. AbsolutePath.make(path.join(directory, ".opencode")),
  725. ])
  726. }).pipe(
  727. Effect.provide(
  728. testLayer(directory, global, root, {
  729. type: "git",
  730. store: AbsolutePath.make(path.join(root, ".git")),
  731. }),
  732. ),
  733. )
  734. })
  735. }),
  736. ),
  737. )
  738. })