mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-26 23:28:43 +00:00
2113 lines
89 KiB
TypeScript
2113 lines
89 KiB
TypeScript
import path from "path"
|
|
import fs from "fs/promises"
|
|
import { describe, expect, test } from "bun:test"
|
|
import { Arbitrary, Effect, Fiber, Layer, Logger, Schema, Stream, Tracer } from "effect"
|
|
import { Config } from "@opencode/core/config"
|
|
import { ConfigDiscovery } from "@opencode/core/config/discovery"
|
|
import { ConfigIntegration } from "@opencode/core/config/integration"
|
|
import { Directory, Document, type Entry, Event, Info } from "@opencode/schema/config"
|
|
import { ConfigModel } from "@opencode/schema/config/model"
|
|
import { ConfigProvider } from "@opencode/schema/config/provider"
|
|
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
|
|
import { makeGlobalNode } from "@opencode/util/effect/app-node"
|
|
import { LayerNode } from "@opencode/util/effect/layer-node"
|
|
import { Credential } from "@opencode/core/credential"
|
|
import { ConfigV1 } from "../fixture/v1-config/config"
|
|
import { ConfigPermissionV1 } from "@opencode/core/v1/config/permission"
|
|
import { ConfigNormalize } from "@opencode/core/config/normalize"
|
|
import { ConfigVariable } from "@opencode/core/config/variable"
|
|
import { FSUtil } from "@opencode/util/fs-util"
|
|
import { Watcher } from "@opencode/core/filesystem/watcher"
|
|
import { Bus } from "@opencode/core/bus"
|
|
import { Global } from "@opencode/util/global"
|
|
import { Location } from "@opencode/core/location"
|
|
import { Project } from "@opencode/core/project"
|
|
import { Provider } from "@opencode/core/provider"
|
|
import { AbsolutePath } from "@opencode/core/schema"
|
|
import { WellKnown } from "@opencode/core/wellknown"
|
|
import { KV } from "@opencode/core/kv"
|
|
import { ManagedPolicy } from "@opencode/core/managed-policy"
|
|
import { Wildcard } from "@opencode/core/util/wildcard"
|
|
import { Integration } from "@opencode/schema/integration"
|
|
import { emptyCredentialNode, emptyWellknownNode } from "../fixture/config-nodes"
|
|
import { withEnv } from "../fixture/env"
|
|
import { location } from "../fixture/location"
|
|
import { tmpdir, withTempDir } from "../fixture/tmpdir"
|
|
import { testEffect } from "../lib/effect"
|
|
|
|
const it = testEffect(Layer.empty)
|
|
const itWithPermissions = process.platform === "win32" || process.getuid?.() === 0 ? it.live.skip : it.live
|
|
const selection = Schema.decodeUnknownSync(ConfigModel.Selection)
|
|
const decodeInfo = Schema.decodeUnknownSync(Info, { errors: "all", onExcessProperty: "ignore" })
|
|
const encodeInfo = Schema.encodeSync(Info)
|
|
|
|
function migrateV1(input: unknown) {
|
|
const result = ConfigNormalize.normalize(input)
|
|
if (result.type !== "normalized") throw new Error("expected normalized config")
|
|
return encodeInfo(decodeInfo(result.encoded))
|
|
}
|
|
|
|
function inFixture(root: string, target: string) {
|
|
const relative = path.relative(root, target)
|
|
return relative === "" || (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))
|
|
}
|
|
|
|
function testLayer(
|
|
directory: string,
|
|
globalDirectory = path.join(directory, "global"),
|
|
projectDirectory = directory,
|
|
vcs?: Project.Vcs,
|
|
watcher: Layer.Layer<Watcher.Service | Watcher.Test> = Watcher.testLayer,
|
|
credentialNode = emptyCredentialNode,
|
|
wellknownNode = emptyWellknownNode,
|
|
options?: Config.Options,
|
|
) {
|
|
const locationLayer = Layer.succeed(
|
|
Location.Service,
|
|
Location.Service.of(
|
|
location(
|
|
{ directory: AbsolutePath.make(directory) },
|
|
{ projectDirectory: AbsolutePath.make(projectDirectory), vcs },
|
|
),
|
|
),
|
|
)
|
|
const built = AppNodeBuilder.build(LayerNode.group([Config.node, Bus.node]), [
|
|
Config.node.replace(Config.configured({ system: false, ...options })),
|
|
Location.node.replace(locationLayer),
|
|
Global.node.replace(Global.layerWith({ config: globalDirectory, home: path.join(globalDirectory, "home") })),
|
|
Credential.node.replace(credentialNode),
|
|
WellKnown.node.replace(wellknownNode),
|
|
Watcher.node.replace(watcher),
|
|
])
|
|
// Merge the watcher layer by reference so Watcher.Test resolves to the same
|
|
// memoized instance the built graph uses.
|
|
return Layer.mergeAll(built, watcher)
|
|
}
|
|
|
|
const tool = (effect: "allow" | "deny") => ({ action: "tool.use", resource: "shell:*", effect })
|
|
|
|
const provider = {
|
|
package: "native",
|
|
settings: {},
|
|
headers: {},
|
|
body: {},
|
|
models: {},
|
|
}
|
|
|
|
describe("Config", () => {
|
|
it.live("excludes home-level claude and agents directories when global is disabled", () =>
|
|
Effect.acquireDisposable(Effect.promise(() => tmpdir())).pipe(
|
|
Effect.flatMap((tmp) => {
|
|
const global = path.join(tmp.path, "global")
|
|
const home = path.join(global, "home")
|
|
const project = path.join(home, "project")
|
|
return Effect.promise(() =>
|
|
Promise.all([
|
|
fs.mkdir(project, { recursive: true }),
|
|
fs.mkdir(path.join(home, ".claude"), { recursive: true }),
|
|
fs.mkdir(path.join(home, ".agents"), { recursive: true }),
|
|
]),
|
|
).pipe(
|
|
Effect.andThen(
|
|
Effect.gen(function* () {
|
|
// The fixture is real: with global enabled the walk finds both.
|
|
const config = yield* Config.Service
|
|
const compatibility = yield* config.compatibility!()
|
|
expect([...compatibility.claude, ...compatibility.agents]).toHaveLength(2)
|
|
}).pipe(Effect.provide(testLayer(project, global))),
|
|
),
|
|
Effect.andThen(
|
|
// Home-level directories are global config however the walk
|
|
// reaches them, so global: false excludes them even with the
|
|
// project walk enabled.
|
|
Effect.gen(function* () {
|
|
const config = yield* Config.Service
|
|
expect(yield* config.compatibility!()).toEqual({ claude: [], agents: [] })
|
|
const watcher = yield* Watcher.Test
|
|
expect(
|
|
(yield* watcher.subscriptions()).filter((watch) => watch.type === "entries" && watch.path === home),
|
|
).toEqual([])
|
|
}).pipe(
|
|
Effect.provide(
|
|
testLayer(project, global, project, undefined, undefined, undefined, undefined, { global: false }),
|
|
),
|
|
),
|
|
),
|
|
)
|
|
}),
|
|
),
|
|
)
|
|
|
|
it.live("excludes claude directories when claude is disabled", () =>
|
|
Effect.acquireDisposable(Effect.promise(() => tmpdir())).pipe(
|
|
Effect.flatMap((tmp) => {
|
|
const global = path.join(tmp.path, "global")
|
|
const home = path.join(global, "home")
|
|
const project = path.join(tmp.path, "project")
|
|
return Effect.promise(() =>
|
|
Promise.all([
|
|
fs.mkdir(path.join(home, ".claude"), { recursive: true }),
|
|
fs.mkdir(path.join(home, ".agents"), { recursive: true }),
|
|
fs.mkdir(path.join(project, ".claude"), { recursive: true }),
|
|
fs.mkdir(path.join(project, ".agents"), { recursive: true }),
|
|
]),
|
|
).pipe(
|
|
Effect.andThen(
|
|
// Fixture control: both global and project claude dirs are found by default.
|
|
Effect.gen(function* () {
|
|
const config = yield* Config.Service
|
|
const compatibility = yield* config.compatibility!()
|
|
expect(compatibility.claude.filter((item) => inFixture(tmp.path, item))).toEqual([
|
|
AbsolutePath.make(path.join(home, ".claude")),
|
|
AbsolutePath.make(path.join(project, ".claude")),
|
|
])
|
|
}).pipe(Effect.provide(testLayer(project, global))),
|
|
),
|
|
Effect.andThen(
|
|
Effect.gen(function* () {
|
|
const config = yield* Config.Service
|
|
const compatibility = yield* config.compatibility!()
|
|
expect(compatibility.claude).toEqual([])
|
|
expect(compatibility.agents.filter((item) => inFixture(tmp.path, item))).toEqual([
|
|
AbsolutePath.make(path.join(home, ".agents")),
|
|
AbsolutePath.make(path.join(project, ".agents")),
|
|
])
|
|
}).pipe(
|
|
Effect.provide(
|
|
testLayer(project, global, project, undefined, undefined, undefined, undefined, { claude: false }),
|
|
),
|
|
),
|
|
),
|
|
)
|
|
}),
|
|
),
|
|
)
|
|
|
|
it.live("excludes global config reached through the project walk when global is disabled", () =>
|
|
Effect.acquireDisposable(Effect.promise(() => tmpdir())).pipe(
|
|
Effect.flatMap((tmp) => {
|
|
// The location sits BENEATH the global config dir, so the upward walk
|
|
// reaches the global opencode.json as a direct file.
|
|
const global = path.join(tmp.path, "global")
|
|
const project = path.join(global, "plugins", "demo")
|
|
return Effect.promise(async () => {
|
|
await fs.mkdir(project, { recursive: true })
|
|
await fs.writeFile(path.join(global, "opencode.json"), JSON.stringify({ shell: "global-sentinel" }))
|
|
}).pipe(
|
|
Effect.andThen(
|
|
// Fixture control: with global enabled the file loads.
|
|
Effect.gen(function* () {
|
|
const config = yield* Config.Service
|
|
expect(Config.latest(yield* config.entries(), "shell")).toBe("global-sentinel")
|
|
}).pipe(Effect.provide(testLayer(project, global))),
|
|
),
|
|
Effect.andThen(
|
|
Effect.gen(function* () {
|
|
const config = yield* Config.Service
|
|
expect(Config.latest(yield* config.entries(), "shell")).toBeUndefined()
|
|
}).pipe(
|
|
Effect.provide(
|
|
testLayer(project, global, project, undefined, undefined, undefined, undefined, { global: false }),
|
|
),
|
|
),
|
|
),
|
|
)
|
|
}),
|
|
),
|
|
)
|
|
|
|
// Filesystem sandboxes deny reads outside the project. Simulate a denied discovery root with a
|
|
// symlink into an unsearchable directory, which makes realpath fail with EACCES.
|
|
itWithPermissions("treats unreadable discovery roots as absent", () =>
|
|
Effect.acquireDisposable(Effect.promise(() => tmpdir())).pipe(
|
|
Effect.flatMap((tmp) => {
|
|
const global = path.join(tmp.path, "global")
|
|
const home = path.join(global, "home")
|
|
const project = path.join(home, "project")
|
|
const locked = path.join(tmp.path, "locked")
|
|
return Effect.promise(async () => {
|
|
await fs.mkdir(path.join(locked, "agents"), { recursive: true })
|
|
await fs.mkdir(project, { recursive: true })
|
|
await fs.writeFile(path.join(project, "opencode.json"), JSON.stringify({ shell: "project" }))
|
|
await fs.symlink(path.join(locked, "agents"), path.join(home, ".agents"))
|
|
await fs.symlink(path.join(locked, "agents"), path.join(project, ".opencode"))
|
|
await fs.chmod(locked, 0o000)
|
|
}).pipe(
|
|
Effect.andThen(Effect.addFinalizer(() => Effect.promise(() => fs.chmod(locked, 0o755)))),
|
|
Effect.andThen(
|
|
Effect.gen(function* () {
|
|
const config = yield* Config.Service
|
|
const entries = yield* config.entries()
|
|
expect(entries.flatMap((entry) => (entry.type === "document" ? [entry.info.shell] : []))).toEqual([
|
|
"project",
|
|
])
|
|
}).pipe(Effect.provide(testLayer(project, global))),
|
|
),
|
|
Effect.scoped,
|
|
)
|
|
}),
|
|
),
|
|
)
|
|
|
|
it.live("discovers the global config directory once when the project walk reaches it", () =>
|
|
Effect.acquireDisposable(Effect.promise(() => tmpdir())).pipe(
|
|
Effect.flatMap((tmp) => {
|
|
// The global config dir is the project's own .opencode (as isolated
|
|
// hosts pin OPENCODE_CONFIG_DIR), and the location is the project under
|
|
// a symlinked spelling, so the walk reaches the same directory under a
|
|
// different string than the global root.
|
|
const real = path.join(tmp.path, "real")
|
|
const link = path.join(tmp.path, "link")
|
|
const global = AbsolutePath.make(path.join(real, ".opencode"))
|
|
const once = Effect.gen(function* () {
|
|
const config = yield* Config.Service
|
|
const watcher = yield* Watcher.Test
|
|
const entries = yield* config.entries()
|
|
expect(entries.flatMap((entry) => (entry.type === "directory" ? [entry.path] : []))).toEqual([global])
|
|
expect(entries.flatMap((entry) => (entry.type === "document" ? [entry.info.shell] : []))).toEqual(["global"])
|
|
expect(
|
|
(yield* watcher.subscriptions())
|
|
.filter((subscription) => subscription.type === "directory")
|
|
.map((subscription) => subscription.path),
|
|
).toEqual([global])
|
|
expect(
|
|
(yield* watcher.subscriptions()).filter((subscription) =>
|
|
subscription.path.includes(`${path.sep}.opencode${path.sep}`),
|
|
),
|
|
).toEqual([])
|
|
})
|
|
return Effect.promise(async () => {
|
|
await fs.mkdir(global, { recursive: true })
|
|
await fs.writeFile(path.join(global, "opencode.json"), JSON.stringify({ shell: "global" }))
|
|
await fs.symlink(real, link, process.platform === "win32" ? "junction" : undefined)
|
|
}).pipe(
|
|
Effect.andThen(once.pipe(Effect.provide(testLayer(link, global, real)))),
|
|
// Same spelling on both sides: still exactly once.
|
|
Effect.andThen(once.pipe(Effect.provide(testLayer(real, global, real)))),
|
|
)
|
|
}),
|
|
),
|
|
)
|
|
|
|
it.live("loads system configuration at highest priority", () =>
|
|
Effect.acquireDisposable(Effect.promise(() => tmpdir())).pipe(
|
|
Effect.flatMap((tmp) => {
|
|
const system = path.join(tmp.path, "system")
|
|
const global = path.join(tmp.path, "global")
|
|
const project = path.join(tmp.path, "project")
|
|
return Effect.promise(async () => {
|
|
await fs.mkdir(system, { recursive: true })
|
|
await fs.mkdir(global, { recursive: true })
|
|
await fs.mkdir(project, { recursive: true })
|
|
await fs.writeFile(
|
|
path.join(system, "opencode.json"),
|
|
JSON.stringify({ shell: "system", username: "system-user", experimental: { policies: [tool("deny")] } }),
|
|
)
|
|
await fs.writeFile(path.join(global, "opencode.json"), JSON.stringify({ shell: "global" }))
|
|
await fs.writeFile(
|
|
path.join(project, "opencode.json"),
|
|
JSON.stringify({ shell: "project", experimental: { policies: [tool("allow")] } }),
|
|
)
|
|
}).pipe(
|
|
Effect.andThen(
|
|
Effect.gen(function* () {
|
|
const config = yield* Config.Service
|
|
const entries = yield* config.entries()
|
|
expect(
|
|
entries.flatMap((entry) => (entry.type === "document" && entry.info.shell ? [entry.info.shell] : [])),
|
|
).toEqual(["global", "project", "system"])
|
|
expect(entries.flatMap((entry) => (entry.type === "directory" ? [entry.path] : []))).toEqual([
|
|
AbsolutePath.make(global),
|
|
AbsolutePath.make(system),
|
|
])
|
|
expect(Config.latest(entries, "shell")).toBe("system")
|
|
expect(Config.latest(entries, "username")).toBe("system-user")
|
|
expect(ManagedPolicy.decision(ManagedPolicy.statements(entries), "tool.use", "shell:ls")).toBe("deny")
|
|
}).pipe(
|
|
Effect.provide(
|
|
testLayer(project, global, project, undefined, undefined, emptyCredentialNode, emptyWellknownNode, {
|
|
system,
|
|
}),
|
|
),
|
|
),
|
|
),
|
|
Effect.andThen(
|
|
Effect.gen(function* () {
|
|
const config = yield* Config.Service
|
|
const entries = yield* config.entries()
|
|
expect(
|
|
entries.flatMap((entry) => (entry.type === "document" && entry.info.shell ? [entry.info.shell] : [])),
|
|
).toEqual(["global", "project"])
|
|
}).pipe(
|
|
Effect.provide(
|
|
testLayer(project, global, project, undefined, undefined, emptyCredentialNode, emptyWellknownNode, {
|
|
system: false,
|
|
}),
|
|
),
|
|
),
|
|
),
|
|
)
|
|
}),
|
|
),
|
|
)
|
|
|
|
test("resolves the system configuration directory per platform", () => {
|
|
expect(ConfigDiscovery.systemDirectory("darwin", {})).toBe(
|
|
AbsolutePath.make("/Library/Application Support/opencode"),
|
|
)
|
|
expect(ConfigDiscovery.systemDirectory("linux", {})).toBe(AbsolutePath.make("/etc/opencode"))
|
|
expect(ConfigDiscovery.systemDirectory("win32", { ProgramData: "D:\\ProgramData" })).toBe(
|
|
AbsolutePath.make(path.join("D:\\ProgramData", "opencode")),
|
|
)
|
|
expect(ConfigDiscovery.systemDirectory("win32", {})).toBe(
|
|
AbsolutePath.make(path.join("C:\\ProgramData", "opencode")),
|
|
)
|
|
})
|
|
|
|
test("strips MDM payload metadata from managed preferences", () => {
|
|
expect(
|
|
JSON.parse(
|
|
ConfigDiscovery.stripPreferenceMetadata(
|
|
JSON.stringify({
|
|
PayloadDisplayName: "OpenCode",
|
|
PayloadIdentifier: "ai.opencode.managed",
|
|
PayloadType: "ai.opencode.managed",
|
|
PayloadUUID: "00000000-0000-0000-0000-000000000000",
|
|
PayloadVersion: 1,
|
|
_manualProfile: true,
|
|
share: "disabled",
|
|
}),
|
|
),
|
|
),
|
|
).toEqual({ share: "disabled" })
|
|
})
|
|
|
|
it.live("loads explicit file and content overrides in priority order", () =>
|
|
Effect.acquireDisposable(Effect.promise(() => tmpdir())).pipe(
|
|
Effect.flatMap((tmp) => {
|
|
const global = path.join(tmp.path, "global")
|
|
const project = path.join(tmp.path, "project")
|
|
const explicit = path.join(tmp.path, "custom.json")
|
|
return Effect.promise(async () => {
|
|
await fs.mkdir(global, { recursive: true })
|
|
await fs.mkdir(project, { recursive: true })
|
|
await fs.writeFile(path.join(global, "opencode.json"), JSON.stringify({ shell: "global" }))
|
|
await fs.writeFile(explicit, JSON.stringify({ shell: "explicit" }))
|
|
await fs.writeFile(path.join(project, "opencode.json"), JSON.stringify({ shell: "project" }))
|
|
}).pipe(
|
|
Effect.andThen(
|
|
Effect.gen(function* () {
|
|
const config = yield* Config.Service
|
|
const entries = yield* config.entries()
|
|
expect(
|
|
entries.flatMap((entry) => (entry.type === "document" && entry.info.shell ? [entry.info.shell] : [])),
|
|
).toEqual(["global", "explicit", "project", "content"])
|
|
expect(Config.latest(entries, "shell")).toBe("content")
|
|
}).pipe(
|
|
Effect.provide(
|
|
testLayer(project, global, project, undefined, undefined, emptyCredentialNode, emptyWellknownNode, {
|
|
file: explicit,
|
|
content: JSON.stringify({ shell: "content" }),
|
|
}),
|
|
),
|
|
),
|
|
),
|
|
)
|
|
}),
|
|
),
|
|
)
|
|
|
|
it.live("layers integration documents below remote and user config and reloads when they change", () =>
|
|
withTempDir((tmp) =>
|
|
Effect.gen(function* () {
|
|
const global = path.join(tmp.path, "global")
|
|
const project = path.join(tmp.path, "project")
|
|
const named = (name: string) => ({ providers: { remote: { name } } })
|
|
yield* Effect.promise(async () => {
|
|
await fs.mkdir(global, { recursive: true })
|
|
await fs.mkdir(project, { recursive: true })
|
|
await fs.writeFile(path.join(global, "opencode.json"), JSON.stringify(named("global")))
|
|
await fs.writeFile(path.join(project, "opencode.json"), JSON.stringify(named("project")))
|
|
})
|
|
const integrationID = Integration.ID.make("https://example.com")
|
|
const credentialNode = makeGlobalNode({
|
|
service: Credential.Service,
|
|
layer: Layer.mock(Credential.Service)({
|
|
list: () =>
|
|
Effect.succeed([
|
|
new Credential.Info({
|
|
id: Credential.ID.create(),
|
|
integrationID,
|
|
label: "default",
|
|
value: Credential.Key.make({ type: "key", key: "secret" }),
|
|
}),
|
|
]),
|
|
}),
|
|
deps: [],
|
|
})
|
|
const entry: WellKnown.Entry = {
|
|
origin: "https://example.com",
|
|
integrationID,
|
|
manifest: { auth: { command: ["login"], env: "TOKEN" } },
|
|
}
|
|
const wellknownNode = makeGlobalNode({
|
|
service: WellKnown.Service,
|
|
layer: Layer.mock(WellKnown.Service)({
|
|
entries: () => Effect.succeed([entry]),
|
|
snapshot: () => [entry],
|
|
resolve: () => Effect.succeed([named("wellknown")]),
|
|
}),
|
|
deps: [],
|
|
})
|
|
const names = (entries: readonly Entry[]) =>
|
|
entries.flatMap((entry) => (entry.type === "document" ? [entry.info.providers?.remote?.name] : []))
|
|
|
|
return yield* Effect.gen(function* () {
|
|
const config = yield* Config.Service
|
|
const bus = yield* Bus.Service
|
|
const updated = Effect.fnUntraced(function* (change: Effect.Effect<void>) {
|
|
const event = yield* bus
|
|
.subscribe(Event.Updated)
|
|
.pipe(Stream.take(1), Stream.runCollect, Effect.forkScoped({ startImmediately: true }))
|
|
yield* change
|
|
expect(yield* Fiber.join(event)).toHaveLength(1)
|
|
return names(yield* config.entries())
|
|
})
|
|
const integration = Integration.ID.make("opencode")
|
|
expect(names(yield* config.entries())).toEqual(["wellknown", "global", "project"])
|
|
expect(
|
|
yield* updated(
|
|
config.integration!(
|
|
integration,
|
|
ConfigIntegration.make({
|
|
integrationID: integration,
|
|
connection: { type: "env", name: "OPENCODE_API_KEY" },
|
|
info: decodeInfo(named("console")),
|
|
}),
|
|
),
|
|
),
|
|
).toEqual(["console", "wellknown", "global", "project"])
|
|
expect(yield* updated(config.integration!(integration, undefined))).toEqual([
|
|
"wellknown",
|
|
"global",
|
|
"project",
|
|
])
|
|
}).pipe(
|
|
Effect.provide(testLayer(project, global, project, undefined, undefined, credentialNode, wellknownNode)),
|
|
)
|
|
}),
|
|
),
|
|
)
|
|
|
|
it.live("ranks integration policies below managed policies and above user and project policies", () =>
|
|
Effect.acquireDisposable(Effect.promise(() => tmpdir())).pipe(
|
|
Effect.flatMap((tmp) => {
|
|
const system = path.join(tmp.path, "system")
|
|
const global = path.join(tmp.path, "global")
|
|
const project = path.join(tmp.path, "project")
|
|
const shell = (resource: string, effect: "allow" | "deny") => ({ action: "tool.use", resource, effect })
|
|
const write = (directory: string, policies: unknown[]) =>
|
|
fs
|
|
.mkdir(directory, { recursive: true })
|
|
.then(() => fs.writeFile(path.join(directory, "opencode.json"), JSON.stringify({ policies })))
|
|
return Effect.promise(() =>
|
|
Promise.all([
|
|
write(system, [shell("shell:rm*", "deny")]),
|
|
write(global, [shell("shell:*", "allow")]),
|
|
write(project, [shell("shell:*", "allow")]),
|
|
]),
|
|
).pipe(
|
|
Effect.andThen(
|
|
Effect.gen(function* () {
|
|
const config = yield* Config.Service
|
|
const integration = Integration.ID.make("opencode")
|
|
yield* config.integration!(
|
|
integration,
|
|
ConfigIntegration.make({
|
|
integrationID: integration,
|
|
connection: { type: "env", name: "OPENCODE_API_KEY" },
|
|
organization: "Acme",
|
|
info: decodeInfo({ policies: [shell("shell:rm*", "allow"), shell("shell:*", "deny")] }),
|
|
}),
|
|
)
|
|
const statements = ManagedPolicy.statements(yield* config.entries())
|
|
const deciding = (resource: string) =>
|
|
statements.findLast(
|
|
(policy) => policy.action === "tool.use" && Wildcard.match(resource, policy.resource),
|
|
)
|
|
expect(deciding("shell:rm -rf")).toMatchObject({
|
|
effect: "deny",
|
|
message: "Blocked by configuration policy",
|
|
})
|
|
expect(deciding("shell:ls")).toMatchObject({ effect: "deny", message: "Blocked by Acme's policy" })
|
|
}).pipe(
|
|
Effect.provide(
|
|
testLayer(project, global, project, undefined, undefined, emptyCredentialNode, emptyWellknownNode, {
|
|
system,
|
|
}),
|
|
),
|
|
),
|
|
),
|
|
)
|
|
}),
|
|
),
|
|
)
|
|
|
|
it.live("keeps only the policies of documents from integrations managed policy denies", () =>
|
|
Effect.acquireDisposable(Effect.promise(() => tmpdir())).pipe(
|
|
Effect.flatMap((tmp) => {
|
|
const system = path.join(tmp.path, "system")
|
|
const global = path.join(tmp.path, "global")
|
|
const project = path.join(tmp.path, "project")
|
|
const allowed = "org_allowed"
|
|
const opencode = Integration.ID.make("opencode")
|
|
const origin = "https://ai.acme.com"
|
|
const credentialID = Credential.ID.create()
|
|
let org = "org_personal"
|
|
const credentialNode = makeGlobalNode({
|
|
service: Credential.Service,
|
|
layer: Layer.mock(Credential.Service)({
|
|
list: (integrationID) =>
|
|
Effect.succeed([
|
|
new Credential.Info({
|
|
id: Credential.ID.create(),
|
|
integrationID,
|
|
label: "default",
|
|
value: Credential.Key.make({ type: "key", key: "secret" }),
|
|
}),
|
|
]),
|
|
get: (id) =>
|
|
Effect.succeed(
|
|
new Credential.Info({
|
|
id,
|
|
integrationID: opencode,
|
|
label: "Console",
|
|
value: Credential.Key.make({ type: "key", key: "secret", metadata: { orgID: org } }),
|
|
}),
|
|
),
|
|
}),
|
|
deps: [],
|
|
})
|
|
const entry: WellKnown.Entry = {
|
|
origin,
|
|
integrationID: Integration.ID.make(origin),
|
|
manifest: { auth: { command: ["login"], env: "TOKEN" } },
|
|
}
|
|
const wellknownNode = makeGlobalNode({
|
|
service: WellKnown.Service,
|
|
layer: Layer.mock(WellKnown.Service)({
|
|
entries: () => Effect.succeed([entry]),
|
|
snapshot: () => [entry],
|
|
resolve: () =>
|
|
Effect.succeed([
|
|
{
|
|
mcp: { servers: { wiki: { type: "remote", url: "https://wiki.acme.com/mcp" } } },
|
|
policies: [{ action: "tool.use", resource: "shell:rm*", effect: "deny" }],
|
|
},
|
|
]),
|
|
}),
|
|
deps: [],
|
|
})
|
|
const supplied = (entries: readonly Entry[]) =>
|
|
entries.flatMap((entry) =>
|
|
entry.type === "document" && !entry.path
|
|
? [{ servers: Object.keys(entry.info.mcp?.servers ?? {}), policies: entry.info.policies?.length ?? 0 }]
|
|
: [],
|
|
)
|
|
return Effect.promise(() =>
|
|
fs.mkdir(system, { recursive: true }).then(() =>
|
|
fs.writeFile(
|
|
path.join(system, "opencode.json"),
|
|
JSON.stringify({
|
|
policies: [
|
|
{ action: "integration.use", resource: "*", effect: "deny" },
|
|
{ action: "integration.use", resource: `opencode#${allowed}`, effect: "allow" },
|
|
],
|
|
}),
|
|
),
|
|
),
|
|
).pipe(
|
|
Effect.andThen(
|
|
Effect.gen(function* () {
|
|
const config = yield* Config.Service
|
|
const install = () =>
|
|
config.integration!(
|
|
opencode,
|
|
ConfigIntegration.make({
|
|
integrationID: opencode,
|
|
connection: { type: "credential", id: credentialID, label: "Console", method: "key" },
|
|
organization: org,
|
|
info: decodeInfo({
|
|
mcp: { servers: { docs: { type: "remote", url: "https://docs.acme.com/mcp" } } },
|
|
policies: [{ action: "mcp.use", resource: "github", effect: "deny" }],
|
|
}),
|
|
}),
|
|
)
|
|
yield* install()
|
|
// The personal account's servers and the denied well-known origin's config are gone; their policies stay.
|
|
expect(supplied(yield* config.entries())).toEqual([
|
|
{ servers: [], policies: 1 },
|
|
{ servers: [], policies: 1 },
|
|
])
|
|
org = allowed
|
|
yield* config.integration!(opencode, undefined)
|
|
yield* install()
|
|
expect(supplied(yield* config.entries())).toEqual([
|
|
{ servers: ["docs"], policies: 1 },
|
|
{ servers: [], policies: 1 },
|
|
])
|
|
}).pipe(
|
|
Effect.provide(
|
|
testLayer(project, global, project, undefined, undefined, credentialNode, wellknownNode, {
|
|
system,
|
|
}),
|
|
),
|
|
),
|
|
),
|
|
)
|
|
}),
|
|
),
|
|
)
|
|
|
|
it.live("skips project configuration when project discovery is disabled", () =>
|
|
Effect.acquireDisposable(Effect.promise(() => tmpdir())).pipe(
|
|
Effect.flatMap((tmp) => {
|
|
const global = path.join(tmp.path, "global")
|
|
const project = path.join(tmp.path, "project")
|
|
return Effect.promise(async () => {
|
|
await fs.mkdir(global, { recursive: true })
|
|
await fs.mkdir(project, { recursive: true })
|
|
await fs.writeFile(path.join(global, "opencode.json"), JSON.stringify({ shell: "global" }))
|
|
await fs.writeFile(path.join(project, "opencode.json"), JSON.stringify({ shell: "project" }))
|
|
}).pipe(
|
|
Effect.andThen(
|
|
Effect.gen(function* () {
|
|
const config = yield* Config.Service
|
|
expect(Config.latest(yield* config.entries(), "shell")).toBe("global")
|
|
const watcher = yield* Watcher.Test
|
|
expect((yield* watcher.subscriptions()).map((subscription) => subscription.path)).toEqual([global])
|
|
}).pipe(
|
|
Effect.provide(
|
|
testLayer(project, global, project, undefined, undefined, emptyCredentialNode, emptyWellknownNode, {
|
|
project: false,
|
|
}),
|
|
),
|
|
),
|
|
),
|
|
)
|
|
}),
|
|
),
|
|
)
|
|
|
|
it.live("reloads file substitutions when their source changes", () =>
|
|
Effect.acquireDisposable(Effect.promise(() => tmpdir())).pipe(
|
|
Effect.flatMap((tmp) =>
|
|
Effect.gen(function* () {
|
|
const global = path.join(tmp.path, "global")
|
|
const project = path.join(tmp.path, "project")
|
|
const file = path.join(global, "opencode.json")
|
|
const source = path.join(global, "shell.txt")
|
|
yield* Effect.promise(async () => {
|
|
await fs.mkdir(global, { recursive: true })
|
|
await fs.mkdir(project, { recursive: true })
|
|
await fs.writeFile(source, "first")
|
|
await fs.writeFile(file, JSON.stringify({ shell: "{file:shell.txt}" }))
|
|
})
|
|
return yield* Effect.gen(function* () {
|
|
const config = yield* Config.Service
|
|
const bus = yield* Bus.Service
|
|
const watcher = yield* Watcher.Test
|
|
const changed = yield* bus
|
|
.subscribe(Event.Updated)
|
|
.pipe(Stream.take(1), Stream.runCollect, Effect.forkScoped)
|
|
yield* Effect.sleep("10 millis")
|
|
|
|
yield* Effect.promise(() => fs.writeFile(source, "second"))
|
|
yield* watcher.emit({ type: "update", path: source })
|
|
|
|
expect(yield* Fiber.join(changed)).toHaveLength(1)
|
|
expect(Config.latest(yield* config.entries(), "shell")).toBe("second")
|
|
}).pipe(Effect.provide(testLayer(project, global, project, undefined, Watcher.testLayer)))
|
|
}),
|
|
),
|
|
),
|
|
)
|
|
|
|
it.live("excludes missing files under symlinked global roots when global is disabled", () =>
|
|
Effect.acquireDisposable(Effect.promise(() => tmpdir())).pipe(
|
|
Effect.flatMap((tmp) => {
|
|
const global = path.join(tmp.path, "global")
|
|
const link = path.join(tmp.path, "link")
|
|
const project = path.join(link, "plugins", "demo")
|
|
return Effect.promise(async () => {
|
|
await fs.mkdir(path.join(global, "plugins", "demo"), { recursive: true })
|
|
await fs.symlink(global, link, process.platform === "win32" ? "junction" : undefined)
|
|
}).pipe(
|
|
Effect.andThen(
|
|
Effect.gen(function* () {
|
|
const watcher = yield* Watcher.Test
|
|
const subscriptions = yield* watcher.subscriptions()
|
|
expect(subscriptions.length).toBeGreaterThan(0)
|
|
expect(
|
|
subscriptions.filter((item) => inFixture(global, item.path) || inFixture(link, item.path)),
|
|
).toEqual([])
|
|
}).pipe(
|
|
Effect.provide(
|
|
testLayer(project, global, project, undefined, undefined, undefined, undefined, { global: false }),
|
|
),
|
|
),
|
|
),
|
|
)
|
|
}),
|
|
),
|
|
)
|
|
|
|
it.live("exposes filesystem updates under config roots through changes", () =>
|
|
Effect.acquireDisposable(Effect.promise(() => tmpdir())).pipe(
|
|
Effect.flatMap((tmp) =>
|
|
Effect.gen(function* () {
|
|
const global = path.join(tmp.path, "global")
|
|
const project = path.join(tmp.path, "project")
|
|
yield* Effect.promise(async () => {
|
|
await fs.mkdir(path.join(global, "commands"), { recursive: true })
|
|
await fs.mkdir(project, { recursive: true })
|
|
})
|
|
return yield* Effect.gen(function* () {
|
|
const config = yield* Config.Service
|
|
const watcher = yield* Watcher.Test
|
|
const received = yield* config
|
|
.changes()
|
|
.pipe(Stream.take(1), Stream.runCollect, Effect.forkScoped({ startImmediately: true }))
|
|
yield* Effect.sleep("10 millis")
|
|
|
|
const file = path.join(global, "commands", "review.md")
|
|
yield* watcher.emit({ type: "update", path: file })
|
|
|
|
const collected = yield* Fiber.join(received).pipe(Effect.timeout("1 second"))
|
|
expect(Array.from(collected)).toEqual([{ type: "update", path: file }])
|
|
}).pipe(Effect.provide(testLayer(project, global, project, undefined, Watcher.testLayer)))
|
|
}),
|
|
),
|
|
),
|
|
)
|
|
|
|
const countReloads = () => {
|
|
const counter = { reloads: 0 }
|
|
let finished = () => {}
|
|
const first = new Promise<void>((resolve) => (finished = resolve))
|
|
const tracer = Tracer.make({
|
|
span: (options) => {
|
|
const span = Tracer.nativeTracer.span(options)
|
|
if (options.name !== "Config.reload") return span
|
|
counter.reloads++
|
|
const end = span.end.bind(span)
|
|
span.end = (time, exit) => {
|
|
end(time, exit)
|
|
finished()
|
|
}
|
|
return span
|
|
},
|
|
})
|
|
// The watches' readiness reload; later counts only see what the test triggers.
|
|
const settled = Effect.promise(() => first).pipe(Effect.timeout("3 seconds"))
|
|
return { counter, tracer, settled }
|
|
}
|
|
|
|
it.live("does not reload when an unrelated file under a config root changes", () =>
|
|
Effect.acquireDisposable(Effect.promise(() => tmpdir())).pipe(
|
|
Effect.flatMap((tmp) =>
|
|
Effect.gen(function* () {
|
|
const global = path.join(tmp.path, "global")
|
|
const project = path.join(tmp.path, "project")
|
|
const file = path.join(global, "opencode.json")
|
|
yield* Effect.promise(async () => {
|
|
await fs.mkdir(path.join(global, "skills", "demo"), { recursive: true })
|
|
await fs.mkdir(project, { recursive: true })
|
|
await fs.writeFile(file, JSON.stringify({ shell: "one" }))
|
|
})
|
|
const { counter, tracer, settled } = countReloads()
|
|
return yield* Effect.gen(function* () {
|
|
const config = yield* Config.Service
|
|
const watcher = yield* Watcher.Test
|
|
const changes = yield* config
|
|
.changes()
|
|
.pipe(Stream.take(2), Stream.runCollect, Effect.forkScoped({ startImmediately: true }))
|
|
yield* settled
|
|
const before = counter.reloads
|
|
|
|
// The config file changed on disk, but only unrelated paths report updates.
|
|
yield* Effect.promise(() => fs.writeFile(file, JSON.stringify({ shell: "two" })))
|
|
yield* watcher.emit({ type: "update", path: path.join(global, "skills", "demo", "SKILL.md") })
|
|
yield* watcher.emit({ type: "update", path: path.join(global, "opencode.json.bak") })
|
|
expect(Array.from(yield* Fiber.join(changes)).map((update) => update.path)).toEqual([
|
|
path.join(global, "skills", "demo", "SKILL.md"),
|
|
path.join(global, "opencode.json.bak"),
|
|
])
|
|
// Outlasts the 100 ms reload debounce; proving no reload needs a wait.
|
|
yield* Effect.sleep("250 millis")
|
|
expect(counter.reloads).toBe(before)
|
|
expect(Config.latest(yield* config.entries(), "shell")).toBe("one")
|
|
}).pipe(
|
|
Effect.provide(testLayer(project, global, project, undefined, Watcher.testLayer)),
|
|
Effect.withTracer(tracer),
|
|
)
|
|
}),
|
|
),
|
|
),
|
|
)
|
|
|
|
const nextUpdate = Bus.Service.use((bus) =>
|
|
bus.subscribe(Event.Updated).pipe(Stream.take(1), Stream.runDrain, Effect.forkScoped({ startImmediately: true })),
|
|
)
|
|
|
|
it.live("reloads canonical events for a symlinked global root, even after removal", () =>
|
|
withTempDir((tmp) =>
|
|
Effect.gen(function* () {
|
|
const real = path.join(tmp.path, "real")
|
|
const link = path.join(tmp.path, "link")
|
|
const file = path.join(real, process.platform === "linux" ? "opencode.json" : "OpenCode.JSON")
|
|
yield* Effect.promise(async () => {
|
|
await fs.mkdir(real)
|
|
await fs.symlink(real, link, "junction")
|
|
})
|
|
// Parcel delivers events for the underlying directory rather than the symlink spelling.
|
|
const canonical = Layer.effect(
|
|
Watcher.Service,
|
|
Watcher.Test.use((watcher) =>
|
|
Effect.succeed(
|
|
Watcher.Service.of({
|
|
subscribe: (target, ready) =>
|
|
watcher.subscribe(target.path === link ? { ...target, path: real } : target, ready),
|
|
}),
|
|
),
|
|
),
|
|
).pipe(Layer.provideMerge(Watcher.testLayer))
|
|
const { tracer, settled } = countReloads()
|
|
return yield* Effect.gen(function* () {
|
|
const config = yield* Config.Service
|
|
const watcher = yield* Watcher.Test
|
|
yield* settled
|
|
const created = yield* nextUpdate
|
|
yield* Effect.promise(() => fs.writeFile(file, JSON.stringify({ shell: "one" })))
|
|
yield* watcher.emit({ type: "create", path: file })
|
|
yield* Fiber.join(created).pipe(Effect.timeout("3 seconds"))
|
|
expect(Config.latest(yield* config.entries(), "shell")).toBe("one")
|
|
|
|
const deleted = yield* nextUpdate
|
|
yield* Effect.promise(() => fs.rename(real, path.join(tmp.path, "moved")))
|
|
yield* watcher.emit({ type: "delete", path: real })
|
|
yield* Fiber.join(deleted).pipe(Effect.timeout("3 seconds"))
|
|
expect(Config.latest(yield* config.entries(), "shell")).toBeUndefined()
|
|
}).pipe(Effect.provide(testLayer(tmp.path, link, tmp.path, undefined, canonical)), Effect.withTracer(tracer))
|
|
}),
|
|
),
|
|
)
|
|
|
|
for (const source of ["file", "content"] as const) {
|
|
it.live(`reloads ${source} config when its symlink target changes under a watched root`, () =>
|
|
withTempDir((tmp) =>
|
|
Effect.gen(function* () {
|
|
const global = path.join(tmp.path, "global")
|
|
const alias = path.join(tmp.path, "alias")
|
|
const file = path.join(global, "work.json")
|
|
const write = (shell: string) => fs.writeFile(file, source === "file" ? JSON.stringify({ shell }) : shell)
|
|
yield* Effect.promise(async () => {
|
|
await fs.mkdir(global)
|
|
await fs.symlink(global, alias, "junction")
|
|
await write("one")
|
|
})
|
|
const options =
|
|
source === "file"
|
|
? { file: path.join(alias, "work.json") }
|
|
: {
|
|
content: JSON.stringify({ shell: "{file:alias/work.json}" }),
|
|
}
|
|
const { tracer, settled } = countReloads()
|
|
return yield* Effect.gen(function* () {
|
|
const config = yield* Config.Service
|
|
const watcher = yield* Watcher.Test
|
|
yield* settled
|
|
expect(Config.latest(yield* config.entries(), "shell")).toBe("one")
|
|
const changed = yield* nextUpdate
|
|
yield* Effect.promise(() => write("two"))
|
|
yield* watcher.emit({ type: "update", path: file })
|
|
yield* Fiber.join(changed).pipe(Effect.timeout("3 seconds"))
|
|
expect(Config.latest(yield* config.entries(), "shell")).toBe("two")
|
|
}).pipe(
|
|
Effect.provide(testLayer(tmp.path, global, tmp.path, undefined, undefined, undefined, undefined, options)),
|
|
Effect.withTracer(tracer),
|
|
)
|
|
}),
|
|
),
|
|
)
|
|
}
|
|
|
|
// Real watcher on purpose: the regression this pins (a deleted config file's
|
|
// watch being torn down, making recreation invisible) only reproduces with
|
|
// path-faithful event delivery.
|
|
it.live("keeps watching a deleted config file so recreating it reloads", () =>
|
|
Effect.acquireDisposable(Effect.promise(() => tmpdir())).pipe(
|
|
Effect.flatMap((tmp) =>
|
|
Effect.gen(function* () {
|
|
const global = path.join(tmp.path, "global")
|
|
const project = path.join(tmp.path, "project")
|
|
const file = path.join(project, "opencode.json")
|
|
yield* Effect.promise(async () => {
|
|
await fs.mkdir(global, { recursive: true })
|
|
await fs.mkdir(project, { recursive: true })
|
|
await fs.writeFile(file, JSON.stringify({ shell: "one" }))
|
|
})
|
|
return yield* Effect.gen(function* () {
|
|
const config = yield* Config.Service
|
|
const bus = yield* Bus.Service
|
|
expect(Config.latest(yield* config.entries(), "shell")).toBe("one")
|
|
yield* Effect.sleep("10 millis")
|
|
|
|
const removed = yield* bus
|
|
.subscribe(Event.Updated)
|
|
.pipe(Stream.take(1), Stream.runDrain, Effect.forkScoped({ startImmediately: true }))
|
|
yield* Effect.promise(() => fs.rm(file))
|
|
yield* Fiber.join(removed).pipe(Effect.timeout("5 seconds"))
|
|
expect(Config.latest(yield* config.entries(), "shell")).toBeUndefined()
|
|
|
|
const recreated = yield* bus
|
|
.subscribe(Event.Updated)
|
|
.pipe(Stream.take(1), Stream.runDrain, Effect.forkScoped({ startImmediately: true }))
|
|
yield* Effect.promise(() => fs.writeFile(file, JSON.stringify({ shell: "two" })))
|
|
yield* Fiber.join(recreated).pipe(Effect.timeout("5 seconds"))
|
|
expect(Config.latest(yield* config.entries(), "shell")).toBe("two")
|
|
}).pipe(
|
|
Effect.provide(
|
|
AppNodeBuilder.build(LayerNode.group([Config.node, Bus.node]), [
|
|
Config.node.replace(Config.configured({ system: false })),
|
|
Location.node.replace(
|
|
Layer.succeed(
|
|
Location.Service,
|
|
Location.Service.of(location({ directory: AbsolutePath.make(project) })),
|
|
),
|
|
),
|
|
Global.node.replace(Global.layerWith({ config: global, home: path.join(global, "home") })),
|
|
Credential.node.replace(emptyCredentialNode),
|
|
WellKnown.node.replace(emptyWellknownNode),
|
|
]),
|
|
),
|
|
)
|
|
}),
|
|
),
|
|
),
|
|
)
|
|
|
|
test("returns the latest defined scalar from priority-ordered documents", () => {
|
|
const entries = [
|
|
new Document({
|
|
type: "document",
|
|
info: new Info({ model: selection("openrouter/openai/gpt-5") }),
|
|
}),
|
|
new Directory({ type: "directory", path: AbsolutePath.make("/skills") }),
|
|
new Document({ type: "document", info: new Info({}) }),
|
|
new Document({
|
|
type: "document",
|
|
info: new Info({ model: selection("openrouter/openai/gpt-5.5") }),
|
|
}),
|
|
]
|
|
|
|
expect(Config.latest(entries, "model")).toEqual(selection("openrouter/openai/gpt-5.5"))
|
|
expect(Config.latest(entries, "default_agent")).toBeUndefined()
|
|
})
|
|
|
|
it.live("tolerates unavailable authenticated wellknown config and reloads it later", () =>
|
|
withTempDir((tmp) =>
|
|
Effect.gen(function* () {
|
|
const global = path.join(tmp.path, "global")
|
|
const project = path.join(tmp.path, "project")
|
|
yield* Effect.promise(async () => {
|
|
await fs.mkdir(global, { recursive: true })
|
|
await fs.mkdir(project, { recursive: true })
|
|
await fs.writeFile(path.join(global, "opencode.json"), JSON.stringify({ shell: "global" }))
|
|
await fs.writeFile(path.join(project, "opencode.json"), JSON.stringify({ shell: "project" }))
|
|
})
|
|
|
|
const integrationID = Integration.ID.make("https://example.com")
|
|
let available = false
|
|
let key = "secret"
|
|
const credentialNode = makeGlobalNode({
|
|
service: Credential.Service,
|
|
layer: Layer.succeed(
|
|
Credential.Service,
|
|
Credential.Service.of({
|
|
refresh: () => Effect.die("unused Credential.refresh"),
|
|
all: () => Effect.die("unused Credential.all"),
|
|
list: () =>
|
|
Effect.succeed([
|
|
new Credential.Info({
|
|
id: Credential.ID.create(),
|
|
integrationID,
|
|
label: "default",
|
|
value: Credential.Key.make({ type: "key", key }),
|
|
}),
|
|
]),
|
|
get: () => Effect.die("unused Credential.get"),
|
|
create: () => Effect.die("unused Credential.create"),
|
|
activate: () => Effect.die("unused Credential.activate"),
|
|
update: () => Effect.die("unused Credential.update"),
|
|
remove: () => Effect.die("unused Credential.remove"),
|
|
}),
|
|
),
|
|
deps: [],
|
|
})
|
|
const entry: WellKnown.Entry = {
|
|
origin: "https://example.com",
|
|
integrationID,
|
|
manifest: { auth: { command: ["login"], env: "TOKEN" } },
|
|
}
|
|
const wellknownNode = makeGlobalNode({
|
|
service: WellKnown.Service,
|
|
layer: Layer.succeed(
|
|
WellKnown.Service,
|
|
WellKnown.Service.of({
|
|
entries: () => Effect.succeed([entry]),
|
|
snapshot: () => [entry],
|
|
refresh: () => Effect.succeed(false),
|
|
add: () => Effect.die("unused Wellknown.add"),
|
|
remove: () => Effect.die("unused Wellknown.remove"),
|
|
resolve: (_entry, variables) =>
|
|
available ? Effect.succeed([{ shell: variables.TOKEN }]) : Effect.fail(new Error("expired credential")),
|
|
cached: () => Effect.succeed([]),
|
|
clearCached: () => Effect.void,
|
|
}),
|
|
),
|
|
deps: [],
|
|
})
|
|
|
|
return yield* Effect.gen(function* () {
|
|
const config = yield* Config.Service
|
|
const bus = yield* Bus.Service
|
|
const initial = yield* config.entries()
|
|
expect(Config.latest(initial, "shell")).toBe("project")
|
|
expect(
|
|
initial.flatMap((entry) => (entry.type === "document" && entry.info.shell ? [entry.info.shell] : [])),
|
|
).toEqual(["global", "project"])
|
|
const updated = yield* bus.subscribe(Event.Updated).pipe(Stream.take(1), Stream.runCollect, Effect.forkScoped)
|
|
yield* Effect.yieldNow
|
|
available = true
|
|
key = "next"
|
|
yield* bus.publish(
|
|
Credential.Event.Switched,
|
|
{ credentialID: Credential.ID.create(), integrationID },
|
|
{ global: true },
|
|
)
|
|
expect(yield* Fiber.join(updated)).toHaveLength(1)
|
|
const refreshed = yield* config.entries()
|
|
expect(Config.latest(refreshed, "shell")).toBe("project")
|
|
expect(
|
|
refreshed.flatMap((entry) => (entry.type === "document" && entry.info.shell ? [entry.info.shell] : [])),
|
|
).toEqual(["next", "global", "project"])
|
|
}).pipe(
|
|
Effect.provide(testLayer(project, global, project, undefined, undefined, credentialNode, wellknownNode)),
|
|
)
|
|
}),
|
|
),
|
|
)
|
|
|
|
it.live("keeps the last resolved wellknown config across failures and restarts while a credential exists", () =>
|
|
withTempDir((tmp) => {
|
|
let manifestStatus = 200
|
|
let configStatus = 200
|
|
let requests = 0
|
|
let key: string | undefined = "secret"
|
|
const server = Bun.serve({
|
|
port: 0,
|
|
fetch(request) {
|
|
const url = new URL(request.url)
|
|
if (url.pathname === "/.well-known/opencode") {
|
|
if (manifestStatus !== 200) return new Response("Unavailable", { status: manifestStatus })
|
|
return Response.json({
|
|
auth: { command: ["login"], env: "TOKEN" },
|
|
remote_config: { url: `${url.origin}/config`, headers: { authorization: "Bearer {env:TOKEN}" } },
|
|
})
|
|
}
|
|
requests++
|
|
if (configStatus !== 200) return new Response("Unavailable", { status: configStatus })
|
|
return Response.json({
|
|
config: {
|
|
enabled_providers: ["remote"],
|
|
provider: { remote: { npm: "@ai-sdk/openai-compatible", models: { chat: {} } } },
|
|
},
|
|
})
|
|
},
|
|
})
|
|
const origin = server.url.origin
|
|
const integrationID = Integration.ID.make(origin)
|
|
const credentialNode = makeGlobalNode({
|
|
service: Credential.Service,
|
|
layer: Layer.mock(Credential.Service)({
|
|
list: () =>
|
|
Effect.succeed(
|
|
key === undefined
|
|
? []
|
|
: [
|
|
new Credential.Info({
|
|
id: Credential.ID.create(),
|
|
integrationID,
|
|
label: "default",
|
|
value: Credential.Key.make({ type: "key", key }),
|
|
}),
|
|
],
|
|
),
|
|
}),
|
|
deps: [],
|
|
})
|
|
const global = path.join(tmp.path, "global")
|
|
const project = path.join(tmp.path, "project")
|
|
const remote = (entries: readonly Entry[]) => ({
|
|
provider: Config.latest(entries, "providers")?.remote?.package,
|
|
policies: Config.latest(entries, "policies"),
|
|
})
|
|
const loaded = {
|
|
provider: "aisdk:@ai-sdk/openai-compatible",
|
|
policies: [
|
|
{ action: "provider.use", resource: "*", effect: "deny" },
|
|
{ action: "provider.use", resource: "remote", effect: "allow" },
|
|
],
|
|
} as const
|
|
const removed = { provider: undefined, policies: undefined }
|
|
return Effect.gen(function* () {
|
|
yield* Effect.promise(() => fs.mkdir(project, { recursive: true }))
|
|
const kv = Layer.succeedContext(yield* Layer.build(LayerNode.compile(KV.node)))
|
|
// Each build is a fresh process sharing one persisted KV store.
|
|
const instance = () =>
|
|
AppNodeBuilder.build(LayerNode.group([Config.node, Bus.node, WellKnown.node]), [
|
|
Config.node.replace(Config.configured({ system: false })),
|
|
Location.node.replace(
|
|
Layer.succeed(Location.Service, Location.Service.of(location({ directory: AbsolutePath.make(project) }))),
|
|
),
|
|
Global.node.replace(Global.layerWith({ config: global, home: path.join(global, "home") })),
|
|
Credential.node.replace(credentialNode),
|
|
KV.node.replace(kv),
|
|
Watcher.node.replace(Watcher.testLayer),
|
|
])
|
|
const services = Effect.gen(function* () {
|
|
const config = yield* Config.Service
|
|
const bus = yield* Bus.Service
|
|
// Each reload also rewrites a local file so Config publishes an update to wait on.
|
|
const reload = Effect.fnUntraced(function* (shell: string, trigger: Effect.Effect<unknown, Error>) {
|
|
const updated = yield* bus
|
|
.subscribe(Event.Updated)
|
|
.pipe(Stream.take(1), Stream.runCollect, Effect.forkScoped({ startImmediately: true }))
|
|
yield* Effect.promise(() => fs.writeFile(path.join(project, "opencode.json"), JSON.stringify({ shell })))
|
|
yield* trigger
|
|
yield* Fiber.join(updated)
|
|
return remote(yield* config.entries())
|
|
})
|
|
const switched = bus.publish(
|
|
Credential.Event.Switched,
|
|
{ credentialID: Credential.ID.create(), integrationID },
|
|
{ global: true },
|
|
)
|
|
return { config, bus, wellknown: yield* WellKnown.Service, reload, switched }
|
|
})
|
|
|
|
yield* Effect.gen(function* () {
|
|
const warm = yield* services
|
|
expect(yield* warm.reload("initial", warm.wellknown.add(origin))).toEqual(loaded)
|
|
|
|
configStatus = 503
|
|
const before = requests
|
|
expect(yield* warm.reload("unavailable", warm.switched)).toEqual(loaded)
|
|
expect(requests).toBeGreaterThan(before)
|
|
|
|
key = undefined
|
|
expect(yield* warm.reload("logged-out", warm.switched)).toEqual(removed)
|
|
|
|
// Logging out drops the saved config, so logging back in while the remote is down supplies nothing.
|
|
key = "secret"
|
|
expect(yield* warm.reload("logged-in-unavailable", warm.switched)).toEqual(removed)
|
|
configStatus = 200
|
|
expect(yield* warm.reload("logged-in", warm.switched)).toEqual(loaded)
|
|
configStatus = 503
|
|
|
|
manifestStatus = 503
|
|
const updated = yield* warm.bus
|
|
.subscribe(WellKnown.Event.Updated)
|
|
.pipe(Stream.take(1), Stream.runCollect, Effect.forkScoped({ startImmediately: true }))
|
|
expect(yield* warm.wellknown.refresh()).toBe(false)
|
|
yield* Effect.sleep("50 millis")
|
|
expect(updated.pollUnsafe()).toBeUndefined()
|
|
}).pipe(Effect.scoped, Effect.provide(instance()))
|
|
|
|
yield* Effect.gen(function* () {
|
|
const cold = yield* services
|
|
expect(remote(yield* cold.config.entries())).toEqual(loaded)
|
|
// The wellknown plugin loads these entries at startup and dies if they fail.
|
|
expect(yield* cold.wellknown.entries()).toHaveLength(1)
|
|
expect(yield* cold.reload("removed", cold.wellknown.remove(origin))).toEqual(removed)
|
|
manifestStatus = 200
|
|
expect(yield* cold.reload("re-added", cold.wellknown.add(origin))).toEqual(removed)
|
|
}).pipe(Effect.scoped, Effect.provide(instance()))
|
|
}).pipe(Effect.ensuring(Effect.promise(() => server.stop(true))))
|
|
}),
|
|
)
|
|
|
|
it.live("logs redacted source-aware diagnostics for every config source", () => {
|
|
const output: Array<Record<string, unknown>> = []
|
|
const logger = Logger.map(Logger.formatStructured, (entry) => {
|
|
if (!Array.isArray(entry.message) || entry.message[0] !== "configuration normalization diagnostic") return
|
|
const details = entry.message[1]
|
|
if (typeof details === "object" && details !== null) output.push(details as Record<string, unknown>)
|
|
})
|
|
return withTempDir((tmp) =>
|
|
Effect.gen(function* () {
|
|
const global = path.join(tmp.path, "global")
|
|
const project = path.join(tmp.path, "project")
|
|
const malformed = path.join(tmp.path, "malformed.json")
|
|
yield* Effect.promise(async () => {
|
|
await fs.mkdir(global, { recursive: true })
|
|
await fs.mkdir(project, { recursive: true })
|
|
await fs.writeFile(path.join(global, "opencode.json"), "null")
|
|
await fs.writeFile(path.join(project, "opencode.json"), "")
|
|
await fs.writeFile(malformed, '{ "credential": "file-secret"')
|
|
})
|
|
const integrationID = Integration.ID.make("https://invalid.example.com")
|
|
const entry: WellKnown.Entry = {
|
|
origin: "https://invalid.example.com",
|
|
integrationID,
|
|
manifest: { auth: { command: ["login"], env: "TOKEN" } },
|
|
}
|
|
const credentialNode = makeGlobalNode({
|
|
service: Credential.Service,
|
|
layer: Layer.succeed(
|
|
Credential.Service,
|
|
Credential.Service.of({
|
|
refresh: () => Effect.die("unused Credential.refresh"),
|
|
all: () => Effect.die("unused Credential.all"),
|
|
list: () =>
|
|
Effect.succeed([
|
|
new Credential.Info({
|
|
id: Credential.ID.create(),
|
|
integrationID,
|
|
label: "default",
|
|
value: Credential.Key.make({ type: "key", key: "wellknown-secret" }),
|
|
}),
|
|
]),
|
|
get: () => Effect.die("unused Credential.get"),
|
|
create: () => Effect.die("unused Credential.create"),
|
|
activate: () => Effect.die("unused Credential.activate"),
|
|
update: () => Effect.die("unused Credential.update"),
|
|
remove: () => Effect.die("unused Credential.remove"),
|
|
}),
|
|
),
|
|
deps: [],
|
|
})
|
|
const wellknownNode = makeGlobalNode({
|
|
service: WellKnown.Service,
|
|
layer: Layer.succeed(
|
|
WellKnown.Service,
|
|
WellKnown.Service.of({
|
|
entries: () => Effect.succeed([entry]),
|
|
snapshot: () => [entry],
|
|
refresh: () => Effect.succeed(false),
|
|
add: () => Effect.die("unused Wellknown.add"),
|
|
remove: () => Effect.die("unused Wellknown.remove"),
|
|
// Exercise the loader boundary against a malformed implementation response.
|
|
resolve: () => Effect.succeed([null as unknown as WellKnown.Config]),
|
|
cached: () => Effect.succeed([]),
|
|
clearCached: () => Effect.void,
|
|
}),
|
|
),
|
|
deps: [],
|
|
})
|
|
|
|
yield* Config.Service.use((config) => config.entries()).pipe(
|
|
Effect.provide(
|
|
testLayer(project, global, project, undefined, undefined, credentialNode, wellknownNode, {
|
|
file: malformed,
|
|
content: "",
|
|
}),
|
|
),
|
|
)
|
|
|
|
expect(output.map((item) => `${item.source}:${item.path}:${item.kind}`).toSorted()).toEqual(
|
|
[
|
|
`${path.join(global, "opencode.json")}:$:invalid`,
|
|
`${path.join(project, "opencode.json")}:$:invalid`,
|
|
`${malformed}:$:invalid`,
|
|
"https://invalid.example.com:$:invalid",
|
|
"OPENCODE_CONFIG_CONTENT:$:invalid",
|
|
].toSorted(),
|
|
)
|
|
expect(JSON.stringify(output)).not.toContain("secret")
|
|
}),
|
|
).pipe(Effect.provide(Logger.layer([logger])))
|
|
})
|
|
|
|
test("migrates arbitrary v1 configuration into valid v2 configuration", () => {
|
|
const json = Schema.fromJsonString(Schema.toCodecJson(ConfigV1.Info))
|
|
const result = Effect.runSync(
|
|
Arbitrary.checkEffect(
|
|
Arbitrary.schema(ConfigV1.Info),
|
|
(info) => {
|
|
migrateV1(JSON.parse(Schema.encodeUnknownSync(json)(info)))
|
|
return true
|
|
},
|
|
{ runs: 100 },
|
|
),
|
|
)
|
|
expect(Arbitrary.formatCheckFailure(result)).toBeUndefined()
|
|
}, 30_000)
|
|
|
|
// Effect leaves decoded key order unspecified, but these maps' order is user-visible: agents cycle
|
|
// in this order, the first matching formatter wins, and providers fold aliases in sequence.
|
|
test("decodes configuration maps in source order", () => {
|
|
const keys = ["zeta", "build", "alpha", "plan", "mid"]
|
|
const map = <A>(value: A) => Object.fromEntries(keys.map((key) => [key, value]))
|
|
const info = Schema.decodeUnknownSync(Info)(
|
|
migrateV1({
|
|
agents: map({}),
|
|
formatter: map({ command: ["fmt"], extensions: [".ts"] }),
|
|
providers: map({}),
|
|
commands: map({ template: "run" }),
|
|
}),
|
|
{ errors: "all", onExcessProperty: "ignore" },
|
|
)
|
|
expect(Object.keys(info.agents ?? {})).toEqual(keys)
|
|
expect(Object.keys(typeof info.formatter === "object" ? info.formatter : {})).toEqual(keys)
|
|
expect(Object.keys(info.providers ?? {})).toEqual(keys)
|
|
expect(Object.keys(info.commands ?? {})).toEqual(keys)
|
|
})
|
|
|
|
test("decodes v1 permissions in source order at every level", () => {
|
|
const decode = Schema.decodeUnknownSync(ConfigPermissionV1.Info)
|
|
expect(decode({ "*": "allow", custom: "deny", bash: { "git *": "ask", "*": "deny" }, edit: "deny" })).toEqual([
|
|
["*", "allow"],
|
|
["custom", "deny"],
|
|
[
|
|
"bash",
|
|
[
|
|
["git *", "ask"],
|
|
["*", "deny"],
|
|
],
|
|
],
|
|
["edit", "deny"],
|
|
])
|
|
expect(decode("ask")).toEqual([["*", "ask"]])
|
|
for (const invalid of [["allow"], { bash: ["allow"] }, { question: { "*": "allow" } }, { read: null }])
|
|
expect(() => decode(invalid)).toThrow()
|
|
})
|
|
|
|
test("migrates the v1 experimental subagent depth", () => {
|
|
expect(migrateV1({ experimental: { subagent_depth: 2 } }).experimental?.subagent_depth).toBe(2)
|
|
})
|
|
|
|
test("migrates the v1 update policy", () => {
|
|
expect(migrateV1({ autoupdate: false }).update).toBe("disable")
|
|
expect(migrateV1({ autoupdate: "notify" }).update).toBe("notify")
|
|
expect(migrateV1({ autoupdate: true }).update).toBe("auto")
|
|
expect(migrateV1({}).update).toBeUndefined()
|
|
})
|
|
|
|
test("normalizes the native auto update policy", () => {
|
|
expect(ConfigNormalize.normalize({ update: "auto" })).toEqual({
|
|
type: "normalized",
|
|
encoded: { update: "auto" },
|
|
diagnostics: [],
|
|
})
|
|
})
|
|
|
|
test("migrates v1 provider setup options into AISDK settings", () => {
|
|
const migrated = migrateV1({
|
|
provider: {
|
|
bedrock: {
|
|
npm: "@ai-sdk/amazon-bedrock",
|
|
models: { claude: { provider: { npm: "@ai-sdk/anthropic" } } },
|
|
options: {
|
|
headers: { "x-test": "1" },
|
|
body: { trace: true },
|
|
region: "us-east-1",
|
|
profile: "dev",
|
|
},
|
|
},
|
|
},
|
|
})
|
|
|
|
expect(migrated.providers?.bedrock).toMatchObject({
|
|
package: Provider.aisdk("@ai-sdk/amazon-bedrock"),
|
|
models: { claude: { package: Provider.aisdk("@ai-sdk/anthropic") } },
|
|
settings: { region: "us-east-1", profile: "dev" },
|
|
headers: { "x-test": "1" },
|
|
body: { trace: true },
|
|
})
|
|
})
|
|
|
|
test("renames old provider IDs while migrating v1 configuration", () => {
|
|
const migrated = migrateV1({
|
|
model: "azure-cognitive-services/deployment",
|
|
enabled_providers: ["google-vertex-anthropic"],
|
|
disabled_providers: ["azure-cognitive-services"],
|
|
agent: {
|
|
reviewer: { model: "google-vertex-anthropic/claude-sonnet" },
|
|
},
|
|
command: {
|
|
review: { template: "Review", model: "azure-cognitive-services/deployment" },
|
|
},
|
|
provider: {
|
|
"azure-cognitive-services": {
|
|
npm: "@ai-sdk/azure",
|
|
env: ["AZURE_COGNITIVE_SERVICES_RESOURCE_NAME", "AZURE_COGNITIVE_SERVICES_API_KEY"],
|
|
models: { deployment: {} },
|
|
},
|
|
"google-vertex-anthropic": {
|
|
npm: "@ai-sdk/google-vertex/anthropic",
|
|
options: { project: "test-project", location: "us-central1" },
|
|
models: { "claude-sonnet": {} },
|
|
},
|
|
},
|
|
})
|
|
|
|
expect(migrated.model).toEqual({ providerID: "azure", model: "deployment" })
|
|
expect(migrated.agents?.reviewer?.model).toEqual({ providerID: "google-vertex", model: "claude-sonnet" })
|
|
expect(migrated.commands?.review?.model).toEqual({ providerID: "azure", model: "deployment" })
|
|
expect(migrated.policies).toEqual([
|
|
{ action: "provider.use", resource: "*", effect: "deny" },
|
|
{ action: "provider.use", resource: "google-vertex", effect: "allow" },
|
|
{ action: "provider.use", resource: "azure", effect: "deny" },
|
|
])
|
|
expect(migrated.providers?.azure).toMatchObject({
|
|
env: ["AZURE_COGNITIVE_SERVICES_API_KEY"],
|
|
package: Provider.aisdk("@ai-sdk/azure"),
|
|
models: { deployment: {} },
|
|
})
|
|
expect(migrated.providers?.["azure-cognitive-services"]).toBeUndefined()
|
|
expect(migrated.providers?.["google-vertex"]).toMatchObject({
|
|
settings: { project: "test-project", location: "us-central1" },
|
|
models: {
|
|
"claude-sonnet": { package: Provider.aisdk("@ai-sdk/google-vertex/anthropic") },
|
|
},
|
|
})
|
|
expect(migrated.providers?.["google-vertex"]).not.toHaveProperty("package")
|
|
expect(migrated.providers?.["google-vertex-anthropic"]).toBeUndefined()
|
|
})
|
|
|
|
test("preserves the generated base URL for v1 Azure OpenAI-compatible providers", () => {
|
|
const migrated = migrateV1({
|
|
provider: {
|
|
"azure-cognitive-services": {
|
|
npm: "@ai-sdk/openai-compatible",
|
|
env: ["AZURE_COGNITIVE_SERVICES_RESOURCE_NAME", "AZURE_COGNITIVE_SERVICES_API_KEY"],
|
|
},
|
|
},
|
|
})
|
|
|
|
expect(migrated.providers?.azure).toMatchObject({
|
|
env: ["AZURE_COGNITIVE_SERVICES_API_KEY"],
|
|
package: Provider.aisdk("@ai-sdk/openai-compatible"),
|
|
settings: {
|
|
baseURL: "https://${AZURE_COGNITIVE_SERVICES_RESOURCE_NAME}.cognitiveservices.azure.com/openai",
|
|
},
|
|
})
|
|
})
|
|
|
|
test("ignores old provider IDs when the current provider ID is configured", () => {
|
|
const migrated = migrateV1({
|
|
provider: {
|
|
azure: { models: { current: {} } },
|
|
"azure-cognitive-services": { models: { legacy: {} } },
|
|
"google-vertex": { models: { gemini: {} } },
|
|
"google-vertex-anthropic": { models: { claude: {} } },
|
|
},
|
|
})
|
|
|
|
expect(migrated.providers?.azure?.models).toEqual({ current: expect.anything() })
|
|
expect(migrated.providers?.["google-vertex"]?.models).toEqual({ gemini: expect.anything() })
|
|
})
|
|
|
|
test("preserves the built-in package for v1 Vertex Anthropic custom models", () => {
|
|
const migrated = migrateV1({
|
|
provider: {
|
|
"google-vertex-anthropic": {
|
|
models: { claude: {} },
|
|
},
|
|
},
|
|
})
|
|
|
|
expect(migrated.providers?.["google-vertex"]?.package).toBeUndefined()
|
|
expect(migrated.providers?.["google-vertex"]?.models?.claude?.package).toBe(
|
|
Provider.aisdk("@ai-sdk/google-vertex/anthropic"),
|
|
)
|
|
})
|
|
|
|
test("migrates v1 interleaved fields to compatibility", () => {
|
|
const migrated = migrateV1({
|
|
provider: {
|
|
custom: {
|
|
models: {
|
|
object: { interleaved: { field: "vendor_reasoning" } },
|
|
string: { interleaved: "reasoning_text" },
|
|
boolean: { interleaved: true },
|
|
},
|
|
},
|
|
},
|
|
})
|
|
|
|
expect(migrated.providers?.custom?.models?.object?.compatibility).toEqual({
|
|
reasoningField: "vendor_reasoning",
|
|
})
|
|
expect(migrated.providers?.custom?.models?.string?.compatibility).toEqual({ reasoningField: "reasoning_text" })
|
|
expect(migrated.providers?.custom?.models?.boolean?.compatibility).toBeUndefined()
|
|
})
|
|
|
|
for (const subtask of [true, false]) {
|
|
test(`migrates v1 command configuration with subtask: ${subtask}`, () => {
|
|
expect(
|
|
migrateV1({
|
|
command: {
|
|
review: {
|
|
template: "Review changes",
|
|
description: "Review code",
|
|
agent: "reviewer",
|
|
model: "anthropic/claude",
|
|
variant: "high",
|
|
subtask,
|
|
},
|
|
},
|
|
}).commands,
|
|
).toEqual({
|
|
review: {
|
|
template: "Review changes",
|
|
description: "Review code",
|
|
agent: "reviewer",
|
|
model: { providerID: "anthropic", model: "claude", variant: "high" },
|
|
subagent: subtask,
|
|
},
|
|
})
|
|
})
|
|
}
|
|
|
|
test("normalizes renamed permission actions when migrating v1 permissions", () => {
|
|
expect(
|
|
migrateV1({
|
|
permission: {
|
|
task: "ask",
|
|
bash: { "git status": "allow", "*": "deny" },
|
|
write: "deny",
|
|
apply_patch: "deny",
|
|
read: "allow",
|
|
},
|
|
}).permissions,
|
|
).toEqual([
|
|
{ action: "subagent", resource: "*", effect: "ask" },
|
|
{ action: "shell", resource: "git status", effect: "allow" },
|
|
{ action: "shell", resource: "*", effect: "deny" },
|
|
{ action: "edit", resource: "*", effect: "deny" },
|
|
{ action: "edit", resource: "*", effect: "deny" },
|
|
{ action: "read", resource: "*", effect: "allow" },
|
|
])
|
|
})
|
|
|
|
it.live("returns an empty configuration when directory files do not exist", () =>
|
|
Effect.acquireDisposable(Effect.promise(() => tmpdir())).pipe(
|
|
Effect.flatMap((tmp) =>
|
|
Effect.gen(function* () {
|
|
const config = yield* Config.Service
|
|
const entries = (yield* config.entries()).filter((entry) => !entry.path || inFixture(tmp.path, entry.path))
|
|
|
|
expect(entries).toEqual([
|
|
new Directory({ type: "directory", path: AbsolutePath.make(path.join(tmp.path, "global")) }),
|
|
])
|
|
}).pipe(Effect.provide(testLayer(tmp.path))),
|
|
),
|
|
),
|
|
)
|
|
|
|
it.live("does not recursively watch ecosystem config roots", () =>
|
|
Effect.acquireDisposable(Effect.promise(() => tmpdir())).pipe(
|
|
Effect.flatMap((tmp) =>
|
|
Effect.gen(function* () {
|
|
yield* Effect.promise(() =>
|
|
Promise.all([
|
|
fs.mkdir(path.join(tmp.path, ".claude", "skills"), { recursive: true }),
|
|
fs.mkdir(path.join(tmp.path, ".agents"), { recursive: true }),
|
|
]),
|
|
)
|
|
return yield* Effect.gen(function* () {
|
|
const config = yield* Config.Service
|
|
const watcher = yield* Watcher.Test
|
|
yield* config.entries()
|
|
|
|
expect((yield* watcher.subscriptions()).filter((item) => inFixture(tmp.path, item.path))).toEqual([
|
|
{
|
|
type: "directory",
|
|
path: AbsolutePath.make(path.join(tmp.path, "global")),
|
|
ignore: FSUtil.ignoreGlobs.toSorted(),
|
|
},
|
|
{
|
|
type: "entries",
|
|
path: tmp.path,
|
|
names: [".agents", ".claude", ".opencode", "opencode.json", "opencode.jsonc"],
|
|
},
|
|
])
|
|
}).pipe(Effect.provide(testLayer(tmp.path, undefined, undefined, undefined, Watcher.testLayer)))
|
|
}),
|
|
),
|
|
),
|
|
)
|
|
|
|
it.live("loads opencode JSON and JSONC files from lowest to highest priority", () =>
|
|
Effect.acquireDisposable(Effect.promise(() => tmpdir())).pipe(
|
|
Effect.flatMap((tmp) =>
|
|
Effect.gen(function* () {
|
|
yield* Effect.promise(() =>
|
|
Promise.all([
|
|
fs.writeFile(
|
|
path.join(tmp.path, "opencode.json"),
|
|
JSON.stringify({ $schema: "base", providers: { base: provider } }),
|
|
),
|
|
fs.writeFile(
|
|
path.join(tmp.path, "opencode.jsonc"),
|
|
`{
|
|
// Later global files override scalar fields while retaining providers.
|
|
"$schema": "last",
|
|
"providers": { "last": ${JSON.stringify(provider)} },
|
|
}`,
|
|
),
|
|
]),
|
|
)
|
|
return yield* Effect.gen(function* () {
|
|
const config = yield* Config.Service
|
|
const documents = (yield* config.entries()).filter((entry) => entry.type === "document")
|
|
|
|
expect(documents).toHaveLength(2)
|
|
expect(documents.map((document) => document.type)).toEqual(["document", "document"])
|
|
expect(documents.map((document) => document.info.$schema)).toEqual(["base", "last"])
|
|
expect(documents[0]).toBeInstanceOf(Document)
|
|
expect(documents[0]?.path).toBe(AbsolutePath.make(path.join(tmp.path, "opencode.json")))
|
|
expect(documents[1]?.info.providers?.last).toBeInstanceOf(ConfigProvider.Info)
|
|
|
|
yield* Effect.promise(() =>
|
|
fs.writeFile(path.join(tmp.path, "opencode.jsonc"), JSON.stringify({ $schema: "changed" })),
|
|
)
|
|
expect(
|
|
(yield* config.entries())
|
|
.filter((entry) => entry.type === "document")
|
|
.map((document) => document.info.$schema),
|
|
).toEqual(["base", "last"])
|
|
}).pipe(Effect.provide(testLayer(tmp.path)))
|
|
}),
|
|
),
|
|
),
|
|
)
|
|
|
|
it.live("substitutes environment variables and relative file contents", () =>
|
|
withEnv(
|
|
{
|
|
OPENCODE_TEST_FLAG: "false",
|
|
OPENCODE_TEST_MCP_TOKEN: String.raw`C:\Users\new\"secret"`,
|
|
OPENCODE_TEST_MISSING: undefined,
|
|
},
|
|
() =>
|
|
withTempDir((tmp) =>
|
|
Effect.gen(function* () {
|
|
yield* Effect.promise(() =>
|
|
Promise.all([
|
|
fs.writeFile(path.join(tmp.path, "token.txt"), 'file\n"token"\n'),
|
|
fs.writeFile(
|
|
path.join(tmp.path, "opencode.jsonc"),
|
|
`{
|
|
// Ignored reference: {file:.}
|
|
"username": "user-{env:OPENCODE_TEST_MISSING}",
|
|
"snapshots": {env:OPENCODE_TEST_FLAG},
|
|
"mcp": {
|
|
"servers": {
|
|
"remote": {
|
|
"type": "remote",
|
|
"url": "https://example.com/mcp",
|
|
"headers": {
|
|
"Authorization": "Bearer {env:OPENCODE_TEST_MCP_TOKEN}",
|
|
"X-Token": "{file:token.txt}",
|
|
"X-Missing": "Bearer {file:~/.opencode-test-missing/key}",
|
|
"X-Folder": "{file:.}"
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}`,
|
|
),
|
|
]),
|
|
)
|
|
|
|
return yield* Effect.gen(function* () {
|
|
const config = yield* Config.Service
|
|
const document = (yield* config.entries()).find((entry) => entry.type === "document")
|
|
expect(document?.info.username).toBe("user-")
|
|
expect(document?.info.snapshots).toBe(false)
|
|
const remote = document?.info.mcp?.servers?.remote
|
|
expect(remote?.type).toBe("remote")
|
|
if (remote?.type !== "remote") return
|
|
expect(remote.headers).toEqual({
|
|
Authorization: String.raw`Bearer C:\Users\new\"secret"`,
|
|
"X-Token": 'file\n"token"',
|
|
"X-Missing": "Bearer ",
|
|
"X-Folder": "",
|
|
})
|
|
}).pipe(Effect.provide(testLayer(tmp.path)))
|
|
}),
|
|
),
|
|
),
|
|
)
|
|
|
|
it.effect("keeps env values unescaped when the config already parses", () =>
|
|
Effect.gen(function* () {
|
|
const text = yield* ConfigVariable.substitute({
|
|
type: "virtual",
|
|
source: "test",
|
|
dir: "/",
|
|
text: '{ "quoted": "{env:QUOTED}", "fragment": {env:FRAGMENT} }',
|
|
env: { QUOTED: String.raw`a\"b`, FRAGMENT: '{"k":"v"}' },
|
|
})
|
|
expect(JSON.parse(text)).toEqual({ quoted: 'a"b', fragment: { k: "v" } })
|
|
}).pipe(Effect.provide(AppNodeBuilder.build(FSUtil.node))),
|
|
)
|
|
|
|
it.live("does not load legacy config.json files", () =>
|
|
Effect.acquireDisposable(Effect.promise(() => tmpdir())).pipe(
|
|
Effect.flatMap((tmp) =>
|
|
Effect.gen(function* () {
|
|
yield* Effect.promise(() =>
|
|
fs.writeFile(path.join(tmp.path, "config.json"), JSON.stringify({ $schema: "legacy" })),
|
|
)
|
|
|
|
return yield* Effect.gen(function* () {
|
|
const config = yield* Config.Service
|
|
const documents = (yield* config.entries()).filter((entry) => entry.type === "document")
|
|
|
|
expect(documents).toHaveLength(0)
|
|
}).pipe(Effect.provide(testLayer(tmp.path)))
|
|
}),
|
|
),
|
|
),
|
|
)
|
|
|
|
it.live("accepts $schema metadata without writing it into config files", () =>
|
|
Effect.acquireDisposable(Effect.promise(() => tmpdir())).pipe(
|
|
Effect.flatMap((tmp) =>
|
|
Effect.gen(function* () {
|
|
const file = path.join(tmp.path, "opencode.json")
|
|
const contents = JSON.stringify({
|
|
shell: "/bin/zsh",
|
|
providers: { local: provider },
|
|
})
|
|
yield* Effect.promise(() => fs.writeFile(file, contents))
|
|
|
|
return yield* Effect.gen(function* () {
|
|
const config = yield* Config.Service
|
|
const documents = (yield* config.entries()).filter((entry) => entry.type === "document")
|
|
|
|
expect(documents[0]?.info.$schema).toBeUndefined()
|
|
expect(documents[0]?.info.shell).toBe("/bin/zsh")
|
|
expect(yield* Effect.promise(() => fs.readFile(file, "utf8"))).toBe(contents)
|
|
}).pipe(Effect.provide(testLayer(tmp.path)))
|
|
}),
|
|
),
|
|
),
|
|
)
|
|
|
|
it.live("migrates v1 configuration when a v1-only key is present", () =>
|
|
Effect.acquireDisposable(Effect.promise(() => tmpdir())).pipe(
|
|
Effect.flatMap((tmp) =>
|
|
Effect.gen(function* () {
|
|
yield* Effect.promise(() =>
|
|
fs.writeFile(
|
|
path.join(tmp.path, "opencode.json"),
|
|
JSON.stringify({
|
|
shell: "/bin/zsh",
|
|
default_agent: "reviewer",
|
|
autoupdate: false,
|
|
snapshot: false,
|
|
autoshare: true,
|
|
permission: {
|
|
bash: "ask",
|
|
edit: { "*.md": "allow", "*": "deny" },
|
|
question: "deny",
|
|
webfetch: { "*": "ask", "https://en.wikipedia.org/*": "allow" },
|
|
},
|
|
agent: {
|
|
reviewer: {
|
|
prompt: "Review changes.",
|
|
disable: true,
|
|
temperature: 0.2,
|
|
permission: { read: "allow" },
|
|
},
|
|
},
|
|
skills: { paths: ["./skills"], urls: ["https://example.com/.well-known/skills/"] },
|
|
references: {
|
|
docs: { path: "../docs", description: "Use for product documentation", hidden: true },
|
|
},
|
|
attachment: { image: { auto_resize: false, max_width: 1200 } },
|
|
provider: {
|
|
custom: {
|
|
options: { apiKey: "secret" },
|
|
models: {
|
|
model: {
|
|
options: { reasoningEffort: "high" },
|
|
variants: { fast: { temperature: 0.2 } },
|
|
},
|
|
},
|
|
},
|
|
openai: {
|
|
npm: "@ai-sdk/openai",
|
|
options: { apiKey: "secret", organization: "org" },
|
|
models: {
|
|
model: {
|
|
options: { temperature: 0.3, reasoningEffort: "high", serviceTier: "priority" },
|
|
variants: { high: { reasoningEffort: "high", reasoningSummary: "auto" } },
|
|
},
|
|
},
|
|
},
|
|
anthropic: {
|
|
npm: "@ai-sdk/anthropic",
|
|
models: {
|
|
model: {
|
|
options: {
|
|
effort: "high",
|
|
taskBudget: 4096,
|
|
metadata: { userId: "user-1" },
|
|
},
|
|
},
|
|
},
|
|
},
|
|
litellm: {
|
|
npm: "@ai-sdk/openai-compatible",
|
|
options: { baseURL: "https://litellm.example/v1" },
|
|
models: {
|
|
"glm-5.3-flashx": {
|
|
options: { reasoningEffort: "high", allowed_openai_params: ["reasoning_effort"] },
|
|
variants: { thinking: { chat_template_kwargs: { enable_thinking: true } } },
|
|
},
|
|
},
|
|
},
|
|
},
|
|
compaction: { auto: true, tail_turns: 3, preserve_recent_tokens: 2000, reserved: 10000 },
|
|
experimental: { mcp_timeout: 5000 },
|
|
mcp: {
|
|
local: { type: "local", command: ["node", "server.js"], enabled: false, timeout: 10000 },
|
|
remote: {
|
|
type: "remote",
|
|
url: "https://mcp.example.com",
|
|
oauth: { clientId: "client", callbackPort: 19876 },
|
|
timeout: 20000,
|
|
},
|
|
},
|
|
}),
|
|
),
|
|
)
|
|
|
|
return yield* Effect.gen(function* () {
|
|
const config = yield* Config.Service
|
|
const documents = (yield* config.entries()).filter((entry) => entry.type === "document")
|
|
|
|
expect(documents).toHaveLength(1)
|
|
expect(documents[0]?.info).toBeInstanceOf(Info)
|
|
expect(documents[0]?.info.shell).toBe("/bin/zsh")
|
|
expect(documents[0]?.info.default_agent).toBe("reviewer")
|
|
expect(documents[0]?.info.update).toBe("disable")
|
|
expect(documents[0]?.info.snapshots).toBe(false)
|
|
expect(documents[0]?.info.share).toBe("auto")
|
|
expect(documents[0]?.info.permissions).toEqual([
|
|
{ action: "shell", resource: "*", effect: "ask" },
|
|
{ action: "edit", resource: "*.md", effect: "allow" },
|
|
{ action: "edit", resource: "*", effect: "deny" },
|
|
{ action: "question", resource: "*", effect: "deny" },
|
|
{ action: "webfetch", resource: "*", effect: "ask" },
|
|
{ action: "webfetch", resource: "https://en.wikipedia.org/*", effect: "allow" },
|
|
])
|
|
expect(documents[0]?.info.agents?.reviewer).toMatchObject({
|
|
system: "Review changes.",
|
|
disabled: true,
|
|
request: { body: { temperature: 0.2 } },
|
|
permissions: [{ action: "read", resource: "*", effect: "allow" }],
|
|
})
|
|
expect(documents[0]?.info.skills).toEqual(["./skills", "https://example.com/.well-known/skills/"])
|
|
expect(documents[0]?.info.references).toEqual({
|
|
docs: { path: "../docs", description: "Use for product documentation", hidden: true },
|
|
})
|
|
expect(documents[0]?.info.media).toEqual({ image: { auto_resize: false, max_width: 1200 } })
|
|
expect(documents[0]?.info.providers?.custom).toMatchObject({
|
|
settings: { apiKey: "secret" },
|
|
models: {
|
|
model: {
|
|
settings: { reasoningEffort: "high" },
|
|
variants: [{ id: "fast", settings: { temperature: 0.2 } }],
|
|
},
|
|
},
|
|
})
|
|
expect(documents[0]?.info.providers?.openai).toMatchObject({
|
|
package: Provider.aisdk("@ai-sdk/openai"),
|
|
settings: { apiKey: "secret", organization: "org" },
|
|
models: {
|
|
model: {
|
|
settings: { temperature: 0.3, reasoningEffort: "high", serviceTier: "priority" },
|
|
variants: [{ id: "high", settings: { reasoningEffort: "high", reasoningSummary: "auto" } }],
|
|
},
|
|
},
|
|
})
|
|
expect(documents[0]?.info.providers?.anthropic).toMatchObject({
|
|
package: Provider.aisdk("@ai-sdk/anthropic"),
|
|
models: {
|
|
model: {
|
|
settings: {
|
|
effort: "high",
|
|
taskBudget: 4096,
|
|
metadata: { userId: "user-1" },
|
|
},
|
|
},
|
|
},
|
|
})
|
|
expect(documents[0]?.info.providers?.litellm?.models?.["glm-5.3-flashx"]).toMatchObject({
|
|
settings: { reasoningEffort: "high" },
|
|
body: { allowed_openai_params: ["reasoning_effort"] },
|
|
variants: [{ id: "thinking", settings: {}, body: { chat_template_kwargs: { enable_thinking: true } } }],
|
|
})
|
|
expect(documents[0]?.info.compaction).toEqual({
|
|
auto: true,
|
|
keep: { tokens: 2000 },
|
|
buffer: 10000,
|
|
})
|
|
expect(documents[0]?.info.mcp).toMatchObject({
|
|
timeout: { catalog: 5000, execution: 5000 },
|
|
servers: {
|
|
local: {
|
|
type: "local",
|
|
command: ["node", "server.js"],
|
|
disabled: true,
|
|
timeout: { startup: 10000, catalog: 10000, execution: 10000 },
|
|
},
|
|
remote: {
|
|
type: "remote",
|
|
url: "https://mcp.example.com",
|
|
oauth: { client_id: "client", callback_port: 19876 },
|
|
timeout: { startup: 20000, catalog: 20000, execution: 20000 },
|
|
},
|
|
},
|
|
})
|
|
}).pipe(Effect.provide(testLayer(tmp.path)))
|
|
}),
|
|
),
|
|
),
|
|
)
|
|
|
|
it.live("ignores an invalid file while loading valid config values", () =>
|
|
Effect.acquireDisposable(Effect.promise(() => tmpdir())).pipe(
|
|
Effect.flatMap((tmp) =>
|
|
Effect.gen(function* () {
|
|
yield* Effect.promise(() =>
|
|
Promise.all([
|
|
fs.writeFile(path.join(tmp.path, "opencode.json"), JSON.stringify({ $schema: "base" })),
|
|
fs.writeFile(path.join(tmp.path, "opencode.jsonc"), "{ invalid"),
|
|
]),
|
|
)
|
|
return yield* Effect.gen(function* () {
|
|
const config = yield* Config.Service
|
|
const watcher = yield* Watcher.Test
|
|
const documents = (yield* config.entries()).filter((entry) => entry.type === "document")
|
|
|
|
expect(documents.map((document) => document.info.$schema)).toEqual(["base"])
|
|
expect(yield* watcher.subscriptions()).toContainEqual({
|
|
path: tmp.path,
|
|
type: "entries",
|
|
names: [".agents", ".claude", ".opencode", "opencode.json", "opencode.jsonc"],
|
|
})
|
|
}).pipe(Effect.provide(testLayer(tmp.path)))
|
|
}),
|
|
),
|
|
),
|
|
)
|
|
|
|
it.live("loads global and ancestor configuration across the project boundary", () =>
|
|
Effect.acquireDisposable(Effect.promise(() => tmpdir())).pipe(
|
|
Effect.flatMap((tmp) => {
|
|
const global = path.join(tmp.path, "global")
|
|
const root = path.join(tmp.path, "repo")
|
|
const parent = path.join(root, "packages")
|
|
const directory = path.join(parent, "app")
|
|
const globalAgents = path.join(global, "home", ".agents")
|
|
const globalClaude = path.join(global, "home", ".claude")
|
|
return Effect.gen(function* () {
|
|
yield* Effect.promise(async () => {
|
|
await fs.mkdir(global, { recursive: true })
|
|
await fs.mkdir(globalAgents, { recursive: true })
|
|
await fs.mkdir(globalClaude, { recursive: true })
|
|
await fs.mkdir(directory, { recursive: true })
|
|
await fs.mkdir(path.join(root, ".agents"), { recursive: true })
|
|
await fs.mkdir(path.join(root, ".claude"), { recursive: true })
|
|
await fs.mkdir(path.join(root, ".opencode"), { recursive: true })
|
|
await fs.mkdir(path.join(directory, ".agents"), { recursive: true })
|
|
await fs.mkdir(path.join(directory, ".claude"), { recursive: true })
|
|
await fs.mkdir(path.join(directory, ".opencode"), { recursive: true })
|
|
await Promise.all([
|
|
fs.writeFile(path.join(tmp.path, "opencode.json"), JSON.stringify({ $schema: "outside" })),
|
|
fs.writeFile(path.join(global, "opencode.json"), JSON.stringify({ $schema: "global" })),
|
|
fs.writeFile(path.join(root, "opencode.json"), JSON.stringify({ $schema: "root" })),
|
|
fs.writeFile(path.join(parent, "opencode.jsonc"), JSON.stringify({ $schema: "parent" })),
|
|
fs.writeFile(path.join(directory, "opencode.json"), JSON.stringify({ $schema: "directory" })),
|
|
fs.writeFile(path.join(root, ".opencode", "opencode.json"), JSON.stringify({ $schema: "root-dot" })),
|
|
fs.writeFile(
|
|
path.join(directory, ".opencode", "opencode.jsonc"),
|
|
JSON.stringify({ $schema: "directory-dot" }),
|
|
),
|
|
])
|
|
})
|
|
|
|
return yield* Effect.gen(function* () {
|
|
const config = yield* Config.Service
|
|
const entries = (yield* config.entries()).filter((entry) => !entry.path || inFixture(tmp.path, entry.path))
|
|
const documents = entries.filter((entry) => entry.type === "document")
|
|
const compatibility = yield* config.compatibility!()
|
|
|
|
expect(entries.filter((entry) => entry.type === "directory").map((entry) => entry.path)).toEqual([
|
|
AbsolutePath.make(global),
|
|
AbsolutePath.make(path.join(root, ".opencode")),
|
|
AbsolutePath.make(path.join(directory, ".opencode")),
|
|
])
|
|
expect(compatibility.agents.filter((path) => inFixture(tmp.path, path))).toEqual([
|
|
AbsolutePath.make(globalAgents),
|
|
AbsolutePath.make(path.join(root, ".agents")),
|
|
AbsolutePath.make(path.join(directory, ".agents")),
|
|
])
|
|
expect(compatibility.claude.filter((path) => inFixture(tmp.path, path))).toEqual([
|
|
AbsolutePath.make(globalClaude),
|
|
AbsolutePath.make(path.join(root, ".claude")),
|
|
AbsolutePath.make(path.join(directory, ".claude")),
|
|
])
|
|
expect(documents.map((document) => document.info.$schema)).toEqual([
|
|
"global",
|
|
"outside",
|
|
"root",
|
|
"parent",
|
|
"directory",
|
|
"root-dot",
|
|
"directory-dot",
|
|
])
|
|
expect(entries.map((entry) => (entry.type === "document" ? entry.info.$schema : entry.path))).toEqual([
|
|
"global",
|
|
AbsolutePath.make(global),
|
|
"outside",
|
|
"root",
|
|
"parent",
|
|
"directory",
|
|
"root-dot",
|
|
AbsolutePath.make(path.join(root, ".opencode")),
|
|
"directory-dot",
|
|
AbsolutePath.make(path.join(directory, ".opencode")),
|
|
])
|
|
}).pipe(
|
|
Effect.provide(
|
|
testLayer(directory, global, root, {
|
|
type: "git",
|
|
store: AbsolutePath.make(path.join(root, ".git")),
|
|
}),
|
|
),
|
|
)
|
|
})
|
|
}),
|
|
),
|
|
)
|
|
})
|