config.test.ts 31 KB

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