mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-21 04:12:08 +03:00
feat(core): merge Console config as a config layer (#57703)
This commit is contained in:
committed by
GitHub
Unverified
parent
32b57015e5
commit
a41d09bc78
@@ -17,6 +17,7 @@ import { ConfigVariable } from "./config/variable.js"
|
||||
import { ConfigNormalize } from "./config/normalize.js"
|
||||
import { ConfigDiscovery } from "./config/discovery.js"
|
||||
import { ConfigWatch } from "./config/watch.js"
|
||||
import { ConfigIntegration } from "./config/integration.js"
|
||||
import { WellKnown } from "./wellknown.js"
|
||||
import { AppProcess } from "@opencode/util/process"
|
||||
import { ChildProcess } from "effect/process"
|
||||
@@ -42,6 +43,15 @@ export interface Interface {
|
||||
readonly changes: () => Stream.Stream<Watcher.Update>
|
||||
/** Updates supported global config fields while preserving unrelated JSONC content. */
|
||||
readonly update?: (patch: Patch) => Effect.Effect<void, FSUtil.Error>
|
||||
/**
|
||||
* Replaces, or clears with `undefined`, the document an integration connection contributes. It loads right after
|
||||
* managed policies: its settings layer below remote, user, and project config, while its policies outrank theirs.
|
||||
* Changing it reloads config like any other source.
|
||||
*/
|
||||
readonly integration?: (
|
||||
integrationID: ConfigIntegration.Document["integrationID"],
|
||||
document: ConfigIntegration.Document | undefined,
|
||||
) => Effect.Effect<void>
|
||||
}
|
||||
|
||||
export const Options = Schema.Struct({
|
||||
@@ -79,13 +89,23 @@ export const testLayer = (
|
||||
Layer.effectContext(
|
||||
Effect.gen(function* () {
|
||||
const entries = yield* Ref.make(initial)
|
||||
const integrations = yield* Ref.make(new Map<string, ConfigIntegration.Document>())
|
||||
const updates = yield* PubSub.unbounded<Watcher.Update>()
|
||||
const service = Test.of({
|
||||
entries: () => Ref.get(entries),
|
||||
entries: () =>
|
||||
Effect.all([Ref.get(integrations), Ref.get(entries)]).pipe(
|
||||
Effect.map(([documents, entries]) => [...documents.values(), ...entries]),
|
||||
),
|
||||
compatibility: () => Effect.succeed(compatibility),
|
||||
changes: () => Stream.fromPubSub(updates),
|
||||
setEntries: (next) => Ref.set(entries, next),
|
||||
emitChange: (update) => PubSub.publish(updates, update).pipe(Effect.asVoid),
|
||||
integration: (integrationID, document) =>
|
||||
Ref.update(integrations, (current) => {
|
||||
const next = new Map(current)
|
||||
next.delete(integrationID)
|
||||
return document ? next.set(integrationID, document) : next
|
||||
}),
|
||||
})
|
||||
return Context.empty().pipe(Context.add(Service, service), Context.add(Test, service))
|
||||
}),
|
||||
@@ -103,6 +123,9 @@ export const layer = (options?: Options) =>
|
||||
const globalService = yield* Global.Service
|
||||
const wellknown = yield* WellKnown.Service
|
||||
const processes = yield* AppProcess.Service
|
||||
const integrations = new Map<string, ConfigIntegration.Document>()
|
||||
// Integrations set their documents from outside this layer, so their reloads run with its services.
|
||||
const context = yield* Effect.context<FSUtil.Service | Global.Service | Location.Service>()
|
||||
const reloadLock = Semaphore.makeUnsafe(1)
|
||||
const updateLock = Semaphore.makeUnsafe(1)
|
||||
const decodeOptions = { errors: "all", onExcessProperty: "ignore" } as const
|
||||
@@ -269,6 +292,8 @@ export const layer = (options?: Options) =>
|
||||
? new Document({ ...entry, info: new Info({ ...entry.info, policies: undefined }) })
|
||||
: entry,
|
||||
)
|
||||
// Integration documents load right after managed policies: every remote, user, and project layer overrides
|
||||
// their settings, and since policies evaluate earliest-loaded first, only managed policies outrank theirs.
|
||||
// Global entries sit below explicit and direct files; project directories rank above them.
|
||||
const globalSupplementary = sources.global ? yield* loadDirectory(sources.global).pipe(Effect.orDie) : []
|
||||
const projectSupplementary = yield* Effect.forEach(
|
||||
@@ -280,6 +305,7 @@ export const layer = (options?: Options) =>
|
||||
)
|
||||
return [
|
||||
...managedPolicies,
|
||||
...integrations.values(),
|
||||
...(yield* loadWellknown().pipe(Effect.orDie)),
|
||||
...globalSupplementary,
|
||||
...explicit,
|
||||
@@ -413,6 +439,15 @@ export const layer = (options?: Options) =>
|
||||
}),
|
||||
changes: () => Stream.fromPubSub(updates),
|
||||
update,
|
||||
integration: Effect.fn("Config.integration")(function* (integrationID, document) {
|
||||
if (isDeepStrictEqual(integrations.get(integrationID), document)) return
|
||||
integrations.delete(integrationID)
|
||||
if (document) integrations.set(integrationID, document)
|
||||
yield* reload().pipe(
|
||||
Effect.provide(context),
|
||||
Effect.catchCause((cause) => Effect.logError("failed to reload config", { cause })),
|
||||
)
|
||||
}),
|
||||
})
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
export * as ConfigIntegration from "./integration.js"
|
||||
|
||||
import { Option, Schema, SchemaGetter } from "effect"
|
||||
import { Config } from "@opencode/schema/config"
|
||||
import { ConfigMCP } from "@opencode/schema/config/mcp"
|
||||
import { ConfigPolicy } from "@opencode/schema/config/policy"
|
||||
import { ConfigProvider } from "@opencode/schema/config/provider"
|
||||
import { Connection } from "@opencode/schema/connection"
|
||||
import { IntegrationID } from "@opencode/schema/integration-id"
|
||||
|
||||
// Drop statements whose action or effect is a value this version does not know, so a newer remote source can
|
||||
// extend either enum. Malformed statements still fail validation.
|
||||
export const Policies = Schema.Array(Schema.Unknown).pipe(
|
||||
Schema.decodeTo(Schema.Unknown, {
|
||||
decode: SchemaGetter.transform((policies) =>
|
||||
policies.filter((policy) => {
|
||||
const action = Schema.decodeUnknownOption(Schema.Struct({ action: Schema.String }))(policy)
|
||||
if (Option.isSome(action) && !Schema.is(ConfigPolicy.Info.fields.action)(action.value.action)) return false
|
||||
const effect = Schema.decodeUnknownOption(Schema.Struct({ effect: Schema.String }))(policy)
|
||||
return Option.isNone(effect) || Schema.is(ConfigPolicy.Effect)(effect.value.effect)
|
||||
}),
|
||||
),
|
||||
encode: SchemaGetter.passthrough({ strict: false }),
|
||||
}),
|
||||
Schema.decodeTo(Schema.Array(ConfigPolicy.Info)),
|
||||
)
|
||||
|
||||
/**
|
||||
* The allow-listed keys of a remote config. Only these keys are read before decoding, so a newer remote source's
|
||||
* other keys, valid or not, can never reject the document.
|
||||
*/
|
||||
export const Remote = Schema.Struct({
|
||||
providers: Config.Info.fields.providers,
|
||||
mcp: Config.Info.fields.mcp,
|
||||
policies: Policies.pipe(Schema.optional),
|
||||
websearch: Config.Info.fields.websearch,
|
||||
})
|
||||
export type Remote = typeof Remote.Type
|
||||
|
||||
/**
|
||||
* A config document delivered by an integration connection, such as the OpenCode Console's config. Config loads it
|
||||
* right after managed policies, so user and project config override its settings while its policies outrank theirs.
|
||||
* Its providers authenticate with, and only exist for, that connection.
|
||||
*/
|
||||
export class Document extends Config.Document.extend<Document>("Config.IntegrationDocument")({
|
||||
integrationID: IntegrationID,
|
||||
connection: Connection.Info,
|
||||
/** Organization behind the connection, named in denials by the document's policies. */
|
||||
organization: Schema.optional(Schema.String),
|
||||
}) {}
|
||||
|
||||
/**
|
||||
* Builds an integration document from the allow-listed keys of a remote config: providers, remote MCP servers,
|
||||
* policies, and the web search selection. A remote source can never load plugins, run commands, or change any
|
||||
* other local behavior through config.
|
||||
*/
|
||||
export function make(input: {
|
||||
readonly integrationID: IntegrationID
|
||||
readonly connection: Connection.Info
|
||||
readonly organization?: string
|
||||
readonly info: Remote
|
||||
}) {
|
||||
const servers = input.info.mcp?.servers
|
||||
return new Document({
|
||||
type: "document",
|
||||
integrationID: input.integrationID,
|
||||
connection: input.connection,
|
||||
organization: input.organization,
|
||||
info: new Config.Info({
|
||||
providers:
|
||||
input.info.providers &&
|
||||
Object.fromEntries(
|
||||
Object.entries(input.info.providers).map(([id, provider]) => [
|
||||
id,
|
||||
new ConfigProvider.Info({
|
||||
...provider,
|
||||
// The connection supplies credentials; `env` would read local variables as this provider's key.
|
||||
env: undefined,
|
||||
settings: withoutCredentials(provider.settings),
|
||||
models:
|
||||
provider.models &&
|
||||
Object.fromEntries(
|
||||
Object.entries(provider.models).map(([modelID, model]) => [
|
||||
modelID,
|
||||
{
|
||||
...model,
|
||||
settings: withoutCredentials(model.settings),
|
||||
variants: model.variants?.map((variant) => ({
|
||||
...variant,
|
||||
settings: withoutCredentials(variant.settings),
|
||||
})),
|
||||
},
|
||||
]),
|
||||
),
|
||||
}),
|
||||
]),
|
||||
),
|
||||
// Local servers would run a command on this machine.
|
||||
mcp:
|
||||
servers &&
|
||||
new ConfigMCP.Info({
|
||||
servers: Object.fromEntries(Object.entries(servers).filter(([, server]) => server.type === "remote")),
|
||||
}),
|
||||
policies: input.info.policies,
|
||||
websearch: input.info.websearch,
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
function withoutCredentials<Value>(settings: Readonly<Record<string, Value>> | undefined) {
|
||||
return (
|
||||
settings &&
|
||||
Object.fromEntries(
|
||||
Object.entries(settings).filter(([key]) => !["apiKey", "authToken", "accessToken"].includes(key)),
|
||||
)
|
||||
)
|
||||
}
|
||||
@@ -21,8 +21,9 @@ export const Plugin = define({
|
||||
Stream.runForEach(() => reload),
|
||||
Effect.forkScoped({ startImmediately: true }),
|
||||
)
|
||||
// Authored documents reverse so user-global policy outranks repository policy; organization statements
|
||||
// from the connected Console follow every authored one and have the final say.
|
||||
// Documents reverse so earlier-loaded policy wins: managed policy, then a Console config document, then user
|
||||
// and project files. Statements from a Console serving the legacy format follow every document and have the
|
||||
// final say.
|
||||
const policies = () => ManagedPolicy.statements(loaded.entries, managed.current())
|
||||
const runSync = Effect.runSyncWith(yield* Effect.context())
|
||||
yield* ctx.provider.transform((providers) => {
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
export * as ConfigProviderPlugin from "./provider.js"
|
||||
|
||||
import type { ModelEditor } from "@opencode/plugin/effect/model"
|
||||
import type { ProviderEditor } from "@opencode/plugin/effect/provider"
|
||||
import { define } from "@opencode/plugin/effect/plugin"
|
||||
import { Document, type Entry } from "@opencode/schema/config"
|
||||
import { ConfigProvider } from "@opencode/schema/config/provider"
|
||||
@@ -9,6 +11,7 @@ import { Config } from "../../config.js"
|
||||
import { Model } from "../../model.js"
|
||||
import { Provider } from "../../provider.js"
|
||||
import { Variant } from "../../variant.js"
|
||||
import { ConfigIntegration } from "../integration.js"
|
||||
import { ConfigEntryObserver } from "./entry-observer.js"
|
||||
|
||||
export const Plugin = define({
|
||||
@@ -55,25 +58,7 @@ export const Plugin = define({
|
||||
const next: typeof sources.models = new Map()
|
||||
for (const [id, item] of configuredProviders(loaded.entries)) {
|
||||
const providerID = id
|
||||
const current = providers.get(providerID)
|
||||
const source = providers.get(item.canonical ?? current?.provider.canonical ?? providerID)
|
||||
const changed = item.canonical !== undefined && item.canonical !== current?.provider.canonical
|
||||
providers.update(providerID, (provider) => {
|
||||
if (changed && source && source.provider !== provider)
|
||||
Object.assign(provider, structuredClone(source.provider), {
|
||||
id: provider.id,
|
||||
integrationID: provider.integrationID,
|
||||
})
|
||||
provider.activation = "enabled"
|
||||
if (item.canonical !== undefined) provider.canonical = item.canonical
|
||||
if (item.name) provider.name = item.name
|
||||
if (item.package !== undefined) provider.package = item.package
|
||||
if (item.compatibility !== undefined)
|
||||
provider.compatibility = { ...provider.compatibility, ...item.compatibility }
|
||||
if (item.settings !== undefined) provider.settings = Provider.mergeOverlay(provider.settings, item.settings)
|
||||
if (item.headers !== undefined) provider.headers = Provider.mergeHeaders(provider.headers, item.headers)
|
||||
if (item.body !== undefined) provider.body = Provider.mergeOverlay(provider.body, item.body)
|
||||
})
|
||||
const { current, source, changed } = overlayProvider(providers, providerID, item)
|
||||
const definitions = new Map<string, { readonly inherit: boolean; readonly base?: Model.Info }>()
|
||||
for (const [id, config] of Object.entries(item.models ?? {})) {
|
||||
const base = source?.models.get(config.modelID ?? id) ?? source?.models.get(id)
|
||||
@@ -119,71 +104,26 @@ export const Plugin = define({
|
||||
for (const [id, config] of Object.entries(item.models ?? {})) {
|
||||
const source = definition.models.get(id)
|
||||
const inherit = source?.inherit || !models.get(providerID, id)
|
||||
models.update(providerID, id, (model) => {
|
||||
if (inherit && source?.base) {
|
||||
Object.assign(model, structuredClone(source.base))
|
||||
if (item.package !== undefined) model.package = undefined
|
||||
if (item.settings?.baseURL !== undefined && model.settings) delete model.settings.baseURL
|
||||
}
|
||||
if (config.family !== undefined) model.family = config.family
|
||||
if (config.name) model.name = config.name
|
||||
if (config.modelID !== undefined) model.modelID = config.modelID
|
||||
if (config.releaseDate !== undefined) model.time = { released: Date.parse(config.releaseDate) }
|
||||
if (config.compatibility !== undefined)
|
||||
model.compatibility = { ...model.compatibility, ...config.compatibility }
|
||||
if (config.package !== undefined) model.package = config.package
|
||||
if (config.settings !== undefined) model.settings = Provider.mergeOverlay(model.settings, config.settings)
|
||||
if (config.headers !== undefined) model.headers = Provider.mergeHeaders(model.headers, config.headers)
|
||||
if (config.body !== undefined) model.body = Provider.mergeOverlay(model.body, config.body)
|
||||
if (config.capabilities !== undefined)
|
||||
model.capabilities = Model.mergeCapabilities(config.capabilities, model.capabilities)
|
||||
if (config.limit !== undefined) model.limit = { ...model.limit, ...config.limit }
|
||||
})
|
||||
// Variants are spelled for the final package, which the update above normalizes from `aisdk:*`.
|
||||
models.update(providerID, id, (model) => {
|
||||
// Configured reasoning replaces the base variants; configured variants still overlay them below.
|
||||
if (config.capabilities?.reasoning !== undefined)
|
||||
model.variants = [
|
||||
...Variant.resolve(
|
||||
{ ...model, package: model.package ?? models.provider.get(providerID)?.provider.package },
|
||||
Variant.supports(config.capabilities.reasoning),
|
||||
),
|
||||
]
|
||||
if (config.variants !== undefined) {
|
||||
model.variants ??= []
|
||||
for (const variant of config.variants) {
|
||||
let existing = model.variants.find((item) => item.id === variant.id)
|
||||
if (!existing) {
|
||||
existing = { id: variant.id }
|
||||
model.variants.push(existing)
|
||||
}
|
||||
if (variant.settings !== undefined)
|
||||
existing.settings = Provider.mergeOverlay(existing.settings, variant.settings)
|
||||
if (variant.headers !== undefined)
|
||||
existing.headers = Provider.mergeHeaders(existing.headers, variant.headers)
|
||||
if (variant.body !== undefined) existing.body = Provider.mergeOverlay(existing.body, variant.body)
|
||||
}
|
||||
}
|
||||
if (config.cost !== undefined) {
|
||||
model.cost = (Array.isArray(config.cost) ? config.cost : [config.cost]).map((cost) => ({
|
||||
tier: cost.tier && { ...cost.tier },
|
||||
input: cost.input,
|
||||
output: cost.output,
|
||||
cache: {
|
||||
read: cost.cache?.read ?? Money.USDPerMillionTokens.zero,
|
||||
write: cost.cache?.write ?? Money.USDPerMillionTokens.zero,
|
||||
},
|
||||
}))
|
||||
}
|
||||
if (config.disabled !== undefined) model.enabled = !config.disabled
|
||||
})
|
||||
overlay(
|
||||
models,
|
||||
models.provider.get(providerID)?.provider.package,
|
||||
item,
|
||||
providerID,
|
||||
id,
|
||||
config,
|
||||
inherit && source?.base ? { base: source.base } : undefined,
|
||||
)
|
||||
// Inherited variants are spelled for the base model's package, so a package override needs fresh ones.
|
||||
// A base without variants has no reasoning support to respell.
|
||||
const repackaged =
|
||||
source?.base !== undefined &&
|
||||
source.base.variants.length > 0 &&
|
||||
models.get(providerID, id)?.package !== source.base.package
|
||||
if (config.variants === undefined && config.capabilities?.reasoning === undefined && (!source?.base || repackaged))
|
||||
if (
|
||||
config.variants === undefined &&
|
||||
config.capabilities?.reasoning === undefined &&
|
||||
(!source?.base || repackaged)
|
||||
)
|
||||
models.update(providerID, id, (model) => {
|
||||
model.variants = [
|
||||
...Variant.resolve({
|
||||
@@ -198,8 +138,133 @@ export const Plugin = define({
|
||||
}),
|
||||
})
|
||||
|
||||
// Integration documents are left out: their providers authenticate with the integration's connection, so they add no
|
||||
// integration or method, and the integration's own plugin applies them earlier in the provider chain (`integrate`).
|
||||
function configuredProviders(entries: readonly Entry[]) {
|
||||
return entries
|
||||
.filter((entry): entry is Document => entry.type === "document")
|
||||
.filter((entry): entry is Document => entry.type === "document" && !(entry instanceof ConfigIntegration.Document))
|
||||
.flatMap((file) => Object.entries(file.info.providers ?? {}))
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies an integration document's providers. The integration's plugin calls this at its own position in the
|
||||
* provider chain, so provider plugins registered after it treat these providers as configured ones rather than
|
||||
* as their canonical provider, while user and project config still overlay them in this plugin's late transform.
|
||||
*/
|
||||
export function integrate(providers: ProviderEditor, document: ConfigIntegration.Document) {
|
||||
for (const [providerID, item] of Object.entries(document.info.providers ?? {})) {
|
||||
const { source } = overlayProvider(providers, providerID, item, document.integrationID)
|
||||
// An integration lists the models it routes: each starts again from the catalog and takes the provider's
|
||||
// package and URL. Its models are complete here, so later model transforms and config apply on top.
|
||||
for (const [id, config] of Object.entries(item.models ?? {})) {
|
||||
overlay(providers.models, providers.get(providerID)?.provider.package, item, providerID, id, config, {
|
||||
base: source?.models.get(config.modelID ?? id) ?? source?.models.get(id),
|
||||
})
|
||||
}
|
||||
const configured = providers.get(providerID)
|
||||
// Bound to the connection so its providers disappear as soon as the account changes or signs out.
|
||||
if (configured)
|
||||
providers.add({
|
||||
info: configured.provider,
|
||||
models: Array.from(configured.models.values()),
|
||||
sourceConnection: document.connection,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/** Applies one configured provider, first copying its source when `canonical` points it at another provider. */
|
||||
function overlayProvider(
|
||||
providers: ProviderEditor,
|
||||
providerID: string,
|
||||
item: ConfigProvider.Info,
|
||||
integrationID?: ConfigIntegration.Document["integrationID"],
|
||||
) {
|
||||
const current = providers.get(providerID)
|
||||
const source = providers.get(item.canonical ?? current?.provider.canonical ?? providerID)
|
||||
const changed = item.canonical !== undefined && item.canonical !== current?.provider.canonical
|
||||
providers.update(providerID, (provider) => {
|
||||
if (changed && source && source.provider !== provider)
|
||||
Object.assign(provider, structuredClone(source.provider), {
|
||||
id: provider.id,
|
||||
integrationID: provider.integrationID,
|
||||
})
|
||||
if (integrationID) provider.integrationID = integrationID
|
||||
provider.activation = "enabled"
|
||||
if (item.canonical !== undefined) provider.canonical = item.canonical
|
||||
if (item.name) provider.name = item.name
|
||||
if (item.package !== undefined) provider.package = item.package
|
||||
if (item.compatibility !== undefined) provider.compatibility = { ...provider.compatibility, ...item.compatibility }
|
||||
if (item.settings !== undefined) provider.settings = Provider.mergeOverlay(provider.settings, item.settings)
|
||||
if (item.headers !== undefined) provider.headers = Provider.mergeHeaders(provider.headers, item.headers)
|
||||
if (item.body !== undefined) provider.body = Provider.mergeOverlay(provider.body, item.body)
|
||||
})
|
||||
return { current, source, changed }
|
||||
}
|
||||
|
||||
/** Applies one configured model, first resetting it to `inherit.base` when it starts again from the catalog. */
|
||||
function overlay(
|
||||
models: Pick<ModelEditor, "update">,
|
||||
providerPackage: string | undefined,
|
||||
item: ConfigProvider.Info,
|
||||
providerID: string,
|
||||
id: string,
|
||||
config: NonNullable<ConfigProvider.Info["models"]>[string],
|
||||
inherit: { readonly base: Model.Info | undefined } | undefined,
|
||||
) {
|
||||
models.update(providerID, id, (model) => {
|
||||
if (inherit) {
|
||||
if (inherit.base) Object.assign(model, structuredClone(inherit.base))
|
||||
if (item.package !== undefined) model.package = undefined
|
||||
if (item.settings?.baseURL !== undefined && model.settings) delete model.settings.baseURL
|
||||
}
|
||||
if (config.family !== undefined) model.family = config.family
|
||||
if (config.name) model.name = config.name
|
||||
if (config.modelID !== undefined) model.modelID = config.modelID
|
||||
if (config.releaseDate !== undefined) model.time = { released: Date.parse(config.releaseDate) }
|
||||
if (config.compatibility !== undefined) model.compatibility = { ...model.compatibility, ...config.compatibility }
|
||||
if (config.package !== undefined) model.package = config.package
|
||||
if (config.settings !== undefined) model.settings = Provider.mergeOverlay(model.settings, config.settings)
|
||||
if (config.headers !== undefined) model.headers = Provider.mergeHeaders(model.headers, config.headers)
|
||||
if (config.body !== undefined) model.body = Provider.mergeOverlay(model.body, config.body)
|
||||
if (config.capabilities !== undefined)
|
||||
model.capabilities = Model.mergeCapabilities(config.capabilities, model.capabilities)
|
||||
if (config.limit !== undefined) model.limit = { ...model.limit, ...config.limit }
|
||||
})
|
||||
// Variants are spelled for the final package, which the update above normalizes from `aisdk:*`.
|
||||
models.update(providerID, id, (model) => {
|
||||
// Configured reasoning replaces the base variants; configured variants still overlay them below.
|
||||
if (config.capabilities?.reasoning !== undefined)
|
||||
model.variants = [
|
||||
...Variant.resolve(
|
||||
{ ...model, package: model.package ?? providerPackage },
|
||||
Variant.supports(config.capabilities.reasoning),
|
||||
),
|
||||
]
|
||||
if (config.variants !== undefined) {
|
||||
model.variants ??= []
|
||||
for (const variant of config.variants) {
|
||||
let existing = model.variants.find((item) => item.id === variant.id)
|
||||
if (!existing) {
|
||||
existing = { id: variant.id }
|
||||
model.variants.push(existing)
|
||||
}
|
||||
if (variant.settings !== undefined)
|
||||
existing.settings = Provider.mergeOverlay(existing.settings, variant.settings)
|
||||
if (variant.headers !== undefined) existing.headers = Provider.mergeHeaders(existing.headers, variant.headers)
|
||||
if (variant.body !== undefined) existing.body = Provider.mergeOverlay(existing.body, variant.body)
|
||||
}
|
||||
}
|
||||
if (config.cost !== undefined) {
|
||||
model.cost = (Array.isArray(config.cost) ? config.cost : [config.cost]).map((cost) => ({
|
||||
tier: cost.tier && { ...cost.tier },
|
||||
input: cost.input,
|
||||
output: cost.output,
|
||||
cache: {
|
||||
read: cost.cache?.read ?? Money.USDPerMillionTokens.zero,
|
||||
write: cost.cache?.write ?? Money.USDPerMillionTokens.zero,
|
||||
},
|
||||
}))
|
||||
}
|
||||
if (config.disabled !== undefined) model.enabled = !config.disabled
|
||||
})
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ export * as ManagedPolicy from "./managed-policy.js"
|
||||
|
||||
import { Document, type Entry } from "@opencode/schema/config"
|
||||
import { isDeepStrictEqual } from "node:util"
|
||||
import { ConfigIntegration } from "./config/integration.js"
|
||||
import { Wildcard } from "./util/wildcard.js"
|
||||
import { ConfigPolicy } from "@opencode/schema/config/policy"
|
||||
import { Context, Effect, Layer, PubSub, Stream } from "effect"
|
||||
@@ -52,17 +53,24 @@ export function statements(entries: readonly Entry[], organization: State) {
|
||||
...entries
|
||||
.filter((entry): entry is Document => entry.type === "document")
|
||||
.toReversed()
|
||||
.flatMap((entry) => entry.info.policies ?? [])
|
||||
.map((policy) => ({ ...policy, message: "Blocked by configuration policy" })),
|
||||
...organization.statements.map((policy) => ({
|
||||
...policy,
|
||||
message: organization.organization
|
||||
? `Blocked by ${organization.organization}'s policy`
|
||||
: "Blocked by your organization's policy",
|
||||
})),
|
||||
.flatMap((entry) =>
|
||||
(entry.info.policies ?? []).map((policy) => ({
|
||||
...policy,
|
||||
// An integration document's policies are those of the organization behind its connection.
|
||||
message:
|
||||
entry instanceof ConfigIntegration.Document
|
||||
? blocked(entry.organization)
|
||||
: "Blocked by configuration policy",
|
||||
})),
|
||||
),
|
||||
...organization.statements.map((policy) => ({ ...policy, message: blocked(organization.organization) })),
|
||||
]
|
||||
}
|
||||
|
||||
function blocked(organization: string | undefined) {
|
||||
return organization ? `Blocked by ${organization}'s policy` : "Blocked by your organization's policy"
|
||||
}
|
||||
|
||||
export function decision(
|
||||
policies: readonly ConfigPolicy.Info[],
|
||||
action: ConfigPolicy.Info["action"],
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
export * as OpencodeLegacy from "./opencode-legacy.js"
|
||||
|
||||
// The OpenCode Console's original `/api/v2/config` response, which it serves without `$schema`. Unlike a regular
|
||||
// OpenCode config, the plugin applies it itself: providers, organization policy, web search, and MCP servers.
|
||||
// Delete this module and its uses in opencode.ts once every Console serves a regular OpenCode config.
|
||||
|
||||
import { Effect, Schema } from "effect"
|
||||
import type { Context } from "@opencode/plugin/effect/plugin"
|
||||
import type { WebSearchDefinition } from "@opencode/plugin/effect/websearch"
|
||||
import { ConfigProvider } from "@opencode/schema/config/provider"
|
||||
import { Mcp } from "@opencode/schema/mcp"
|
||||
import { Money } from "@opencode/schema/money"
|
||||
import { ConfigIntegration } from "../../config/integration.js"
|
||||
import { Integration } from "../../integration.js"
|
||||
import { Model } from "../../model.js"
|
||||
import { Provider } from "../../provider.js"
|
||||
import { Variant } from "../../variant.js"
|
||||
import { WebSearch } from "../../websearch.js"
|
||||
|
||||
export const Response = Schema.Struct({
|
||||
providers: Schema.Record(Schema.String, ConfigProvider.Info),
|
||||
websearch: Schema.Struct({
|
||||
providerID: WebSearch.ID,
|
||||
}).pipe(Schema.optional),
|
||||
// MCP servers by name, in the same shape as a remote server in local config. Only remote servers are
|
||||
// accepted so the Console can never make the client run a command. `auth: "console"` asks the client
|
||||
// to attach its own Console credential to that server's requests.
|
||||
mcp: Schema.Struct({
|
||||
servers: Schema.Record(
|
||||
Schema.String,
|
||||
Schema.Struct({ ...Mcp.RemoteConfig.fields, auth: Schema.Literal("console").pipe(Schema.optional) }),
|
||||
),
|
||||
}).pipe(Schema.optional),
|
||||
// Organization policy compiled for the authenticated caller; omitted when there is none.
|
||||
// `experimental.policies` remains accepted alongside top-level `policies`.
|
||||
policies: ConfigIntegration.Policies.pipe(Schema.optional),
|
||||
experimental: Schema.Struct({ policies: ConfigIntegration.Policies.pipe(Schema.optional) }).pipe(Schema.optional),
|
||||
})
|
||||
export type Response = typeof Response.Type
|
||||
|
||||
export interface Snapshot {
|
||||
readonly type: "legacy"
|
||||
readonly response: Response
|
||||
// Console MCP servers carry the credential in their headers, so a rotated token changes the snapshot.
|
||||
readonly mcp: { servers: NonNullable<Response["mcp"]>["servers"]; headers: Record<string, string> } | undefined
|
||||
}
|
||||
|
||||
/** The plugin's Console response in either format; this module only acts on the legacy one. */
|
||||
type Remote = Snapshot | { readonly type: "config" } | undefined
|
||||
|
||||
type Connection = NonNullable<Effect.Success<ReturnType<Context["integration"]["connection"]["active"]>>>
|
||||
|
||||
export function make(response: Response, headers: Record<string, string>): Snapshot {
|
||||
return { type: "legacy", response, mcp: response.mcp && { servers: response.mcp.servers, headers } }
|
||||
}
|
||||
|
||||
/** Organization policy statements, which the plugin hands to `ManagedPolicy` instead of config. */
|
||||
export function statements(snapshot: Snapshot) {
|
||||
return [...(snapshot.response.experimental?.policies ?? []), ...(snapshot.response.policies ?? [])]
|
||||
}
|
||||
|
||||
/** Providers the legacy response routes through the Console, so the plugin can explain their rejected inference. */
|
||||
export function providerIDs(remote: Remote) {
|
||||
return remote?.type === "legacy" ? Object.keys(remote.response.providers) : []
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers the transforms that apply a legacy snapshot: the Console's providers bound to its connection, its web
|
||||
* search provider as the default, and its MCP servers with the Console credential where they ask for it.
|
||||
*/
|
||||
export const register = Effect.fn("OpencodeLegacy.register")(function* (
|
||||
ctx: Context,
|
||||
current: () => { readonly remote: Remote; readonly connection: Connection | undefined },
|
||||
search: (providerID: WebSearch.ID, connection: Connection) => WebSearchDefinition,
|
||||
) {
|
||||
yield* ctx.provider.transform((providers) => {
|
||||
const snapshot = current()
|
||||
const remote = snapshot.remote?.type === "legacy" ? snapshot.remote : undefined
|
||||
for (const [providerID, item] of Object.entries(remote?.response.providers ?? {})) {
|
||||
const source = providers.get(item.canonical ?? providerID)
|
||||
providers.update(providerID, (provider) => {
|
||||
if (source && source.provider !== provider)
|
||||
Object.assign(provider, structuredClone(source.provider), { id: provider.id })
|
||||
provider.integrationID = Integration.ID.make("opencode")
|
||||
if (item.canonical !== undefined) provider.canonical = item.canonical
|
||||
if (item.name !== undefined) provider.name = item.name
|
||||
provider.package = item.package ?? provider.package
|
||||
provider.settings = Provider.mergeOverlay(
|
||||
withoutCredentials(provider.settings),
|
||||
withoutCredentials(item.settings),
|
||||
)
|
||||
provider.headers = Provider.mergeHeaders(provider.headers, item.headers)
|
||||
provider.body = Provider.mergeOverlay(provider.body, item.body)
|
||||
})
|
||||
|
||||
for (const [modelID, config] of Object.entries(item.models ?? {})) {
|
||||
const base = source?.models.get(config.modelID ?? modelID) ?? source?.models.get(modelID)
|
||||
providers.models.update(providerID, modelID, (model) => {
|
||||
Object.assign(model, structuredClone(base ?? model))
|
||||
if (config.family !== undefined) model.family = config.family
|
||||
if (config.name !== undefined) model.name = config.name
|
||||
if (config.modelID !== undefined) model.modelID = config.modelID
|
||||
if (config.releaseDate !== undefined) model.time = { released: Date.parse(config.releaseDate) }
|
||||
if (config.compatibility !== undefined)
|
||||
model.compatibility = { ...model.compatibility, ...config.compatibility }
|
||||
model.package = config.package ?? (item.package !== undefined ? undefined : model.package)
|
||||
if (item.settings?.baseURL !== undefined && model.settings) delete model.settings.baseURL
|
||||
if (config.capabilities !== undefined)
|
||||
model.capabilities = Model.mergeCapabilities(config.capabilities, model.capabilities)
|
||||
model.settings = Provider.mergeOverlay(
|
||||
withoutCredentials(model.settings),
|
||||
withoutCredentials(config.settings),
|
||||
)
|
||||
model.headers = Provider.mergeHeaders(model.headers, config.headers)
|
||||
model.body = Provider.mergeOverlay(model.body, config.body)
|
||||
if (config.limit !== undefined) model.limit = { ...model.limit, ...config.limit }
|
||||
})
|
||||
// Variants are spelled for the final package, which the update above normalizes from `aisdk:*`.
|
||||
providers.models.update(providerID, modelID, (model) => {
|
||||
// The Console's reasoning replaces the base variants; its variants still overlay them below.
|
||||
if (config.capabilities?.reasoning !== undefined)
|
||||
model.variants = [
|
||||
...Variant.resolve(
|
||||
{ ...model, package: model.package ?? providers.get(providerID)?.provider.package },
|
||||
Variant.supports(config.capabilities.reasoning),
|
||||
),
|
||||
]
|
||||
for (const variant of config.variants ?? []) {
|
||||
let existing = model.variants.find((item) => item.id === variant.id)
|
||||
if (!existing) {
|
||||
existing = { id: variant.id }
|
||||
model.variants.push(existing)
|
||||
}
|
||||
if (variant.settings !== undefined)
|
||||
existing.settings = Provider.mergeOverlay(existing.settings, withoutCredentials(variant.settings))
|
||||
if (variant.headers !== undefined)
|
||||
existing.headers = Provider.mergeHeaders(existing.headers, variant.headers)
|
||||
if (variant.body !== undefined) existing.body = Provider.mergeOverlay(existing.body, variant.body)
|
||||
}
|
||||
if (config.cost !== undefined)
|
||||
model.cost = (Array.isArray(config.cost) ? config.cost : [config.cost]).map((cost) => ({
|
||||
tier: cost.tier && { ...cost.tier },
|
||||
input: cost.input,
|
||||
output: cost.output,
|
||||
cache: {
|
||||
read: cost.cache?.read ?? Money.USDPerMillionTokens.zero,
|
||||
write: cost.cache?.write ?? Money.USDPerMillionTokens.zero,
|
||||
},
|
||||
}))
|
||||
model.enabled = !config.disabled
|
||||
})
|
||||
}
|
||||
const configured = providers.get(providerID)
|
||||
if (configured)
|
||||
providers.add({
|
||||
info: configured.provider,
|
||||
models: Array.from(configured.models.values()),
|
||||
sourceConnection: snapshot.connection,
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
yield* ctx.websearch.transform((editor) => {
|
||||
const snapshot = current()
|
||||
const descriptor = snapshot.remote?.type === "legacy" ? snapshot.remote.response.websearch : undefined
|
||||
const connection = snapshot.connection
|
||||
if (!descriptor || !connection) return
|
||||
editor.add(search(descriptor.providerID, connection))
|
||||
editor.default.set(descriptor.providerID)
|
||||
})
|
||||
|
||||
yield* ctx.mcp.transform((editor) => {
|
||||
const remote = current().remote
|
||||
const mcp = remote?.type === "legacy" ? remote.mcp : undefined
|
||||
if (!mcp) return
|
||||
for (const [name, server] of Object.entries(mcp.servers)) {
|
||||
// A server the user configured under the same name wins.
|
||||
if (editor.get(name)) continue
|
||||
const { auth, ...config } = server
|
||||
editor.set(name, auth === "console" ? { ...config, headers: { ...config.headers, ...mcp.headers } } : config)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
function withoutCredentials<Value>(body: Readonly<Record<string, Value>> | undefined) {
|
||||
return (
|
||||
body &&
|
||||
Object.fromEntries(Object.entries(body).filter(([key]) => !["apiKey", "authToken", "accessToken"].includes(key)))
|
||||
)
|
||||
}
|
||||
@@ -5,8 +5,8 @@ import {
|
||||
Equal,
|
||||
FiberHandle,
|
||||
Option,
|
||||
Predicate,
|
||||
Schema,
|
||||
SchemaGetter,
|
||||
Scope,
|
||||
Semaphore,
|
||||
Stream,
|
||||
@@ -17,58 +17,20 @@ import type { SessionHttpResponse } from "@opencode/plugin/effect/session"
|
||||
import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"
|
||||
import { App } from "../../app.js"
|
||||
import { Bus } from "../../bus.js"
|
||||
import { Config } from "../../config.js"
|
||||
import { ConfigIntegration } from "../../config/integration.js"
|
||||
import { ConfigProviderPlugin } from "../../config/plugin/provider.js"
|
||||
import { ConsoleAccess } from "../../console-access.js"
|
||||
import { Credential } from "../../credential.js"
|
||||
import { Integration } from "../../integration.js"
|
||||
import { IntegrationConnection } from "../../integration/connection.js"
|
||||
import { ManagedPolicy } from "../../managed-policy.js"
|
||||
import { Model } from "../../model.js"
|
||||
import { Provider } from "../../provider.js"
|
||||
import { Variant } from "../../variant.js"
|
||||
import { WebSearch } from "../../websearch.js"
|
||||
import { ConfigPolicy } from "@opencode/schema/config/policy"
|
||||
import { ConfigProvider } from "@opencode/schema/config/provider"
|
||||
import { Mcp } from "@opencode/schema/mcp"
|
||||
import { Money } from "@opencode/schema/money"
|
||||
import { OpencodeLegacy } from "./opencode-legacy.js"
|
||||
|
||||
const clientID = "opencode-cli"
|
||||
const methodID = Integration.MethodID.make("device")
|
||||
// Drop statements whose action or effect is a value this version does not know, so a newer Console can
|
||||
// extend either enum. Malformed statements still fail validation.
|
||||
const RemotePolicies = Schema.Array(Schema.Unknown).pipe(
|
||||
Schema.decodeTo(Schema.Unknown, {
|
||||
decode: SchemaGetter.transform((policies) =>
|
||||
policies.filter((policy) => {
|
||||
const action = Schema.decodeUnknownOption(Schema.Struct({ action: Schema.String }))(policy)
|
||||
if (Option.isSome(action) && !Schema.is(ConfigPolicy.Info.fields.action)(action.value.action)) return false
|
||||
const effect = Schema.decodeUnknownOption(Schema.Struct({ effect: Schema.String }))(policy)
|
||||
return Option.isNone(effect) || Schema.is(ConfigPolicy.Effect)(effect.value.effect)
|
||||
}),
|
||||
),
|
||||
encode: SchemaGetter.passthrough({ strict: false }),
|
||||
}),
|
||||
Schema.decodeTo(Schema.Array(ConfigPolicy.Info)),
|
||||
Schema.optional,
|
||||
)
|
||||
const RemoteResponse = Schema.Struct({
|
||||
providers: Schema.Record(Schema.String, ConfigProvider.Info),
|
||||
websearch: Schema.Struct({
|
||||
providerID: WebSearch.ID,
|
||||
}).pipe(Schema.optional),
|
||||
// MCP servers by name, in the same shape as a remote server in local config. Only remote servers are
|
||||
// accepted so the Console can never make the client run a command. `auth: "console"` asks the client
|
||||
// to attach its own Console credential to that server's requests.
|
||||
mcp: Schema.Struct({
|
||||
servers: Schema.Record(
|
||||
Schema.String,
|
||||
Schema.Struct({ ...Mcp.RemoteConfig.fields, auth: Schema.Literal("console").pipe(Schema.optional) }),
|
||||
),
|
||||
}).pipe(Schema.optional),
|
||||
// Organization policy compiled for the authenticated caller; omitted when there is none.
|
||||
// `experimental.policies` remains accepted alongside top-level `policies`.
|
||||
policies: RemotePolicies,
|
||||
experimental: Schema.Struct({ policies: RemotePolicies }).pipe(Schema.optional),
|
||||
})
|
||||
const Device = Schema.Struct({
|
||||
device_code: Schema.String,
|
||||
user_code: Schema.String,
|
||||
@@ -194,7 +156,9 @@ function oauth(http: HttpClient.HttpClient) {
|
||||
} satisfies IntegrationOAuthMethodRegistration
|
||||
}
|
||||
|
||||
export const OpencodePlugin = define<HttpClient.HttpClient | Bus.Service | ManagedPolicy.Service | Scope.Scope>({
|
||||
export const OpencodePlugin = define<
|
||||
HttpClient.HttpClient | Bus.Service | Config.Service | ManagedPolicy.Service | Scope.Scope
|
||||
>({
|
||||
id: "opencode.provider.opencode",
|
||||
effect: Effect.fn(function* (ctx) {
|
||||
const disableFree = ["1", "true"].includes(process.env.OPENCODE_DISABLE_FREE_MODELS?.toLowerCase() ?? "")
|
||||
@@ -204,18 +168,17 @@ export const OpencodePlugin = define<HttpClient.HttpClient | Bus.Service | Manag
|
||||
// and whether it evaluates the policies it is being sent.
|
||||
const http = HttpClient.mapRequest(client, HttpClientRequest.setHeader("User-Agent", App.useragent(ctx.app)))
|
||||
const managed = yield* ManagedPolicy.Service
|
||||
const config = yield* Config.Service
|
||||
const scope = yield* Scope.Scope
|
||||
const loading = Semaphore.makeUnsafe(1)
|
||||
type ActiveConnection = Effect.Success<ReturnType<typeof ctx.integration.connection.active>>
|
||||
let snapshot: {
|
||||
config: typeof RemoteResponse.Type | undefined
|
||||
// The Console response in one of its two formats: a regular OpenCode config, merged as an integration config
|
||||
// layer, or the legacy response, which OpencodeLegacy applies directly.
|
||||
remote: { type: "config"; info: ConfigIntegration.Remote } | OpencodeLegacy.Snapshot | undefined
|
||||
connection: ActiveConnection
|
||||
organization: string | undefined
|
||||
// Console MCP servers carry the credential in their headers, so a rotated token changes the snapshot.
|
||||
mcp:
|
||||
| { servers: NonNullable<typeof RemoteResponse.Type.mcp>["servers"]; headers: Record<string, string> }
|
||||
| undefined
|
||||
} = { config: undefined, connection: undefined, organization: undefined, mcp: undefined }
|
||||
} = { remote: undefined, connection: undefined, organization: undefined }
|
||||
// Status last reported for the active connection, so inference failures can name the fix.
|
||||
let reported: IntegrationConnection.Status | undefined
|
||||
let explainers: Effect.Success<ReturnType<typeof ctx.session.hook>>[] = []
|
||||
@@ -227,7 +190,7 @@ export const OpencodePlugin = define<HttpClient.HttpClient | Bus.Service | Manag
|
||||
const connection = yield* ctx.integration.connection.active("opencode")
|
||||
if (!connection) {
|
||||
reported = undefined
|
||||
return { config: undefined, connection, organization: undefined, mcp: undefined }
|
||||
return { remote: undefined, connection, organization: undefined }
|
||||
}
|
||||
const status = (status: IntegrationConnection.Status | undefined) => {
|
||||
reported = status
|
||||
@@ -236,13 +199,15 @@ export const OpencodePlugin = define<HttpClient.HttpClient | Bus.Service | Manag
|
||||
return yield* ctx.integration.connection.resolve(connection).pipe(
|
||||
Effect.flatMap((credential) => {
|
||||
if (!credential || credential.type === "external")
|
||||
return Effect.succeed({ config: undefined, connection, organization: undefined, mcp: undefined })
|
||||
return Effect.succeed({ remote: undefined, connection, organization: undefined })
|
||||
return fetchConfig(http, credential).pipe(
|
||||
Effect.map((config) => ({
|
||||
config,
|
||||
Effect.map((remote) => ({
|
||||
remote:
|
||||
remote?.type === "legacy"
|
||||
? OpencodeLegacy.make(remote.response, ConsoleAccess.headers(credential))
|
||||
: remote,
|
||||
connection,
|
||||
organization: organizationName(credential),
|
||||
mcp: config?.mcp && { servers: config.mcp.servers, headers: ConsoleAccess.headers(credential) },
|
||||
})),
|
||||
)
|
||||
}),
|
||||
@@ -256,18 +221,98 @@ export const OpencodePlugin = define<HttpClient.HttpClient | Bus.Service | Manag
|
||||
// A load that fails for the connection already in place keeps its last config: dropping it
|
||||
// would lift organization policy while personal credentials keep working.
|
||||
return IntegrationConnection.key(connection) === IntegrationConnection.key(snapshot.connection)
|
||||
? { config: snapshot.config, connection, organization: snapshot.organization, mcp: snapshot.mcp }
|
||||
: { config: undefined, connection, organization: undefined, mcp: undefined }
|
||||
? { remote: snapshot.remote, connection, organization: snapshot.organization }
|
||||
: { remote: undefined, connection, organization: undefined }
|
||||
}),
|
||||
),
|
||||
)
|
||||
})
|
||||
// Statements ride on the snapshot, so a credential switch, disconnect, or 404 replaces them too.
|
||||
const publish = (next: typeof snapshot) =>
|
||||
managed.set({
|
||||
statements: [...(next.config?.experimental?.policies ?? []), ...(next.config?.policies ?? [])],
|
||||
organization: next.organization,
|
||||
})
|
||||
// The Console document as config layered it. Its providers apply at this plugin's position in the provider chain,
|
||||
// where the legacy overlay applies, while the rest of the document merges through config.
|
||||
let integrated: ConfigIntegration.Document | undefined
|
||||
const integrate = Effect.fnUntraced(function* (document: ConfigIntegration.Document | undefined) {
|
||||
yield* config.integration?.(Integration.ID.make("opencode"), document) ?? Effect.void
|
||||
integrated = (yield* config.entries()).find(
|
||||
(entry): entry is ConfigIntegration.Document =>
|
||||
entry instanceof ConfigIntegration.Document && entry.integrationID === Integration.ID.make("opencode"),
|
||||
)
|
||||
})
|
||||
// Policies and providers ride on the snapshot, so a credential switch, disconnect, or 404 replaces them too.
|
||||
const publish = Effect.fnUntraced(function* (next: typeof snapshot) {
|
||||
switch (next.remote?.type) {
|
||||
// A regular config merges as one integration document, which config loads right after managed policies,
|
||||
// so its policies reach ManagedPolicy through config rather than as Console statements.
|
||||
case "config":
|
||||
yield* managed.set({ statements: [], organization: next.organization })
|
||||
return yield* integrate(
|
||||
next.connection &&
|
||||
ConfigIntegration.make({
|
||||
integrationID: Integration.ID.make("opencode"),
|
||||
connection:
|
||||
next.connection.type === "credential"
|
||||
? { ...next.connection, id: Credential.ID.make(next.connection.id) }
|
||||
: next.connection,
|
||||
organization: next.organization,
|
||||
info: next.remote.info,
|
||||
}),
|
||||
)
|
||||
case "legacy":
|
||||
yield* managed.set({ statements: OpencodeLegacy.statements(next.remote), organization: next.organization })
|
||||
return yield* integrate(undefined)
|
||||
default:
|
||||
yield* managed.set({ statements: [], organization: next.organization })
|
||||
return yield* integrate(undefined)
|
||||
}
|
||||
})
|
||||
const search = (providerID: WebSearch.ID, connection: NonNullable<ActiveConnection>) => ({
|
||||
id: providerID,
|
||||
name: "OpenCode Web Search",
|
||||
execute: (input: WebSearch.ProviderInput) =>
|
||||
Effect.gen(function* () {
|
||||
const active = yield* ctx.integration.connection.active("opencode")
|
||||
if (
|
||||
!active ||
|
||||
(connection.type === "credential"
|
||||
? active.type !== "credential" || active.id !== connection.id
|
||||
: active.type !== "env" || active.name !== connection.name)
|
||||
) {
|
||||
return yield* Effect.fail(new Error("OpenCode Console connection changed"))
|
||||
}
|
||||
const credential = yield* ctx.integration.connection.resolve(active)
|
||||
if (!credential || credential.type === "external")
|
||||
return yield* Effect.fail(new Error("OpenCode Console is not connected"))
|
||||
const metadata = credential.metadata
|
||||
const orgID = typeof metadata?.orgID === "string" ? metadata.orgID : undefined
|
||||
const token = credential.type === "oauth" ? credential.access : credential.key
|
||||
const server = yield* normalizeServer(ConsoleAccess.server(credential))
|
||||
const request = yield* HttpClientRequest.post(`${server}/api/websearch`).pipe(
|
||||
HttpClientRequest.acceptJson,
|
||||
HttpClientRequest.bearerToken(token),
|
||||
HttpClientRequest.setHeaders(orgID ? { "x-org-id": orgID } : {}),
|
||||
HttpClientRequest.schemaBodyJson(WebSearch.Input)({
|
||||
query: input.query,
|
||||
providerID,
|
||||
}),
|
||||
)
|
||||
const response = yield* HttpClient.withScope(HttpClient.filterStatusOk(http))
|
||||
.execute(request)
|
||||
.pipe(
|
||||
Effect.provideService(FetchHttpClient.RequestInit, { redirect: "error" }),
|
||||
Effect.flatMap(HttpClientResponse.schemaBodyJson(WebSearch.Response)),
|
||||
Effect.scoped,
|
||||
Effect.timeoutOrElse({
|
||||
duration: Duration.seconds(25),
|
||||
orElse: () => Effect.fail(new Error("OpenCode web search request timed out")),
|
||||
}),
|
||||
)
|
||||
if (response.providerID !== providerID) {
|
||||
return yield* Effect.fail(
|
||||
new Error(`OpenCode web search returned provider ${response.providerID} instead of ${providerID}`),
|
||||
)
|
||||
}
|
||||
return response.results
|
||||
}),
|
||||
})
|
||||
|
||||
yield* ctx.integration.transform((editor) => {
|
||||
editor.update("opencode", (integration) => {
|
||||
@@ -279,90 +324,11 @@ export const OpencodePlugin = define<HttpClient.HttpClient | Bus.Service | Manag
|
||||
|
||||
snapshot = yield* load()
|
||||
yield* publish(snapshot)
|
||||
yield* OpencodeLegacy.register(ctx, () => snapshot, search)
|
||||
yield* ctx.provider.transform((providers) => {
|
||||
if (integrated) ConfigProviderPlugin.integrate(providers, integrated)
|
||||
})
|
||||
yield* ctx.provider.transform((providers) => {
|
||||
for (const [providerID, item] of Object.entries(snapshot.config?.providers ?? {})) {
|
||||
const source = providers.get(item.canonical ?? providerID)
|
||||
providers.update(providerID, (provider) => {
|
||||
if (source && source.provider !== provider)
|
||||
Object.assign(provider, structuredClone(source.provider), { id: provider.id })
|
||||
provider.integrationID = Integration.ID.make("opencode")
|
||||
if (item.canonical !== undefined) provider.canonical = item.canonical
|
||||
if (item.name !== undefined) provider.name = item.name
|
||||
provider.package = item.package ?? provider.package
|
||||
provider.settings = Provider.mergeOverlay(
|
||||
withoutCredentials(provider.settings),
|
||||
withoutCredentials(item.settings),
|
||||
)
|
||||
provider.headers = Provider.mergeHeaders(provider.headers, item.headers)
|
||||
provider.body = Provider.mergeOverlay(provider.body, item.body)
|
||||
})
|
||||
|
||||
for (const [modelID, config] of Object.entries(item.models ?? {})) {
|
||||
const base = source?.models.get(config.modelID ?? modelID) ?? source?.models.get(modelID)
|
||||
providers.models.update(providerID, modelID, (model) => {
|
||||
Object.assign(model, structuredClone(base ?? model))
|
||||
if (config.family !== undefined) model.family = config.family
|
||||
if (config.name !== undefined) model.name = config.name
|
||||
if (config.modelID !== undefined) model.modelID = config.modelID
|
||||
if (config.releaseDate !== undefined) model.time = { released: Date.parse(config.releaseDate) }
|
||||
if (config.compatibility !== undefined)
|
||||
model.compatibility = { ...model.compatibility, ...config.compatibility }
|
||||
model.package = config.package ?? (item.package !== undefined ? undefined : model.package)
|
||||
if (item.settings?.baseURL !== undefined && model.settings) delete model.settings.baseURL
|
||||
if (config.capabilities !== undefined)
|
||||
model.capabilities = Model.mergeCapabilities(config.capabilities, model.capabilities)
|
||||
model.settings = Provider.mergeOverlay(
|
||||
withoutCredentials(model.settings),
|
||||
withoutCredentials(config.settings),
|
||||
)
|
||||
model.headers = Provider.mergeHeaders(model.headers, config.headers)
|
||||
model.body = Provider.mergeOverlay(model.body, config.body)
|
||||
if (config.limit !== undefined) model.limit = { ...model.limit, ...config.limit }
|
||||
})
|
||||
// Variants are spelled for the final package, which the update above normalizes from `aisdk:*`.
|
||||
providers.models.update(providerID, modelID, (model) => {
|
||||
// The Console's reasoning replaces the base variants; its variants still overlay them below.
|
||||
if (config.capabilities?.reasoning !== undefined)
|
||||
model.variants = [
|
||||
...Variant.resolve(
|
||||
{ ...model, package: model.package ?? providers.get(providerID)?.provider.package },
|
||||
Variant.supports(config.capabilities.reasoning),
|
||||
),
|
||||
]
|
||||
for (const variant of config.variants ?? []) {
|
||||
let existing = model.variants.find((item) => item.id === variant.id)
|
||||
if (!existing) {
|
||||
existing = { id: variant.id }
|
||||
model.variants.push(existing)
|
||||
}
|
||||
if (variant.settings !== undefined)
|
||||
existing.settings = Provider.mergeOverlay(existing.settings, withoutCredentials(variant.settings))
|
||||
if (variant.headers !== undefined)
|
||||
existing.headers = Provider.mergeHeaders(existing.headers, variant.headers)
|
||||
if (variant.body !== undefined) existing.body = Provider.mergeOverlay(existing.body, variant.body)
|
||||
}
|
||||
if (config.cost !== undefined)
|
||||
model.cost = (Array.isArray(config.cost) ? config.cost : [config.cost]).map((cost) => ({
|
||||
tier: cost.tier && { ...cost.tier },
|
||||
input: cost.input,
|
||||
output: cost.output,
|
||||
cache: {
|
||||
read: cost.cache?.read ?? Money.USDPerMillionTokens.zero,
|
||||
write: cost.cache?.write ?? Money.USDPerMillionTokens.zero,
|
||||
},
|
||||
}))
|
||||
model.enabled = !config.disabled
|
||||
})
|
||||
}
|
||||
const configured = providers.get(providerID)
|
||||
if (configured)
|
||||
providers.add({
|
||||
info: configured.provider,
|
||||
models: Array.from(configured.models.values()),
|
||||
sourceConnection: snapshot.connection,
|
||||
})
|
||||
}
|
||||
|
||||
const item = providers.get(Provider.ID.opencode)
|
||||
if (!item) return
|
||||
const hasKey = Boolean(process.env.OPENCODE_API_KEY || snapshot.connection || item.provider.settings?.apiKey)
|
||||
@@ -389,74 +355,11 @@ export const OpencodePlugin = define<HttpClient.HttpClient | Bus.Service | Manag
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
// Like any search plugin, the Console's provider is available whenever it is connected; the Console's config
|
||||
// selects it as the default through config, where the user's own selection wins.
|
||||
yield* ctx.websearch.transform((editor) => {
|
||||
const descriptor = snapshot.config?.websearch
|
||||
const connection = snapshot.connection
|
||||
if (!descriptor || !connection) return
|
||||
editor.add({
|
||||
id: descriptor.providerID,
|
||||
name: "OpenCode Web Search",
|
||||
execute: (input) =>
|
||||
Effect.gen(function* () {
|
||||
const active = yield* ctx.integration.connection.active("opencode")
|
||||
if (
|
||||
!active ||
|
||||
(connection.type === "credential"
|
||||
? active.type !== "credential" || active.id !== connection.id
|
||||
: active.type !== "env" || active.name !== connection.name)
|
||||
) {
|
||||
return yield* Effect.fail(new Error("OpenCode Console connection changed"))
|
||||
}
|
||||
const credential = yield* ctx.integration.connection.resolve(active)
|
||||
if (!credential || credential.type === "external")
|
||||
return yield* Effect.fail(new Error("OpenCode Console is not connected"))
|
||||
const metadata = credential.metadata
|
||||
const orgID = typeof metadata?.orgID === "string" ? metadata.orgID : undefined
|
||||
const token = credential.type === "oauth" ? credential.access : credential.key
|
||||
const server = yield* normalizeServer(ConsoleAccess.server(credential))
|
||||
const request = yield* HttpClientRequest.post(`${server}/api/websearch`).pipe(
|
||||
HttpClientRequest.acceptJson,
|
||||
HttpClientRequest.bearerToken(token),
|
||||
HttpClientRequest.setHeaders(orgID ? { "x-org-id": orgID } : {}),
|
||||
HttpClientRequest.schemaBodyJson(WebSearch.Input)({
|
||||
query: input.query,
|
||||
providerID: descriptor.providerID,
|
||||
}),
|
||||
)
|
||||
const response = yield* HttpClient.withScope(HttpClient.filterStatusOk(http))
|
||||
.execute(request)
|
||||
.pipe(
|
||||
Effect.provideService(FetchHttpClient.RequestInit, { redirect: "error" }),
|
||||
Effect.flatMap(HttpClientResponse.schemaBodyJson(WebSearch.Response)),
|
||||
Effect.scoped,
|
||||
Effect.timeoutOrElse({
|
||||
duration: Duration.seconds(25),
|
||||
orElse: () => Effect.fail(new Error("OpenCode web search request timed out")),
|
||||
}),
|
||||
)
|
||||
if (response.providerID !== descriptor.providerID) {
|
||||
return yield* Effect.fail(
|
||||
new Error(
|
||||
`OpenCode web search returned provider ${response.providerID} instead of ${descriptor.providerID}`,
|
||||
),
|
||||
)
|
||||
}
|
||||
return response.results
|
||||
}),
|
||||
})
|
||||
editor.default.set(descriptor.providerID)
|
||||
})
|
||||
|
||||
yield* ctx.mcp.transform((editor) => {
|
||||
const mcp = snapshot.mcp
|
||||
if (!mcp) return
|
||||
for (const [name, server] of Object.entries(mcp.servers)) {
|
||||
// A server the user configured under the same name wins.
|
||||
if (editor.get(name)) continue
|
||||
const { auth, ...config } = server
|
||||
editor.set(name, auth === "console" ? { ...config, headers: { ...config.headers, ...mcp.headers } } : config)
|
||||
}
|
||||
if (snapshot.remote?.type === "config" && snapshot.connection)
|
||||
editor.add(search(WebSearch.ID.make("opencode"), snapshot.connection))
|
||||
})
|
||||
|
||||
const apply = Effect.fn("OpencodePlugin.apply")(function* (next: typeof snapshot) {
|
||||
@@ -505,7 +408,14 @@ export const OpencodePlugin = define<HttpClient.HttpClient | Bus.Service | Manag
|
||||
const guard = Effect.fn("OpencodePlugin.guard")(function* (next: typeof snapshot) {
|
||||
yield* Effect.forEach(explainers, (registration) => registration.dispose, { discard: true })
|
||||
explainers = yield* Effect.forEach(
|
||||
next.connection ? new Set([Provider.ID.opencode, ...Object.keys(next.config?.providers ?? {})]) : [],
|
||||
next.connection
|
||||
? new Set([
|
||||
Provider.ID.opencode,
|
||||
...(next.remote?.type === "config"
|
||||
? Object.keys(next.remote.info.providers ?? {})
|
||||
: OpencodeLegacy.providerIDs(next.remote)),
|
||||
])
|
||||
: [],
|
||||
(providerID) => ctx.session.hook("http.response", explain, { providerID }).pipe(Scope.provide(scope)),
|
||||
)
|
||||
})
|
||||
@@ -555,9 +465,11 @@ function fetchConfig(http: HttpClient.HttpClient, value: Credential.Key | Creden
|
||||
url: yield* ssoUrl(ConsoleAccess.server(value), body.value.connectionId),
|
||||
})
|
||||
}
|
||||
return yield* HttpClientResponse.filterStatusOk(response).pipe(
|
||||
Effect.flatMap(HttpClientResponse.schemaBodyJson(RemoteResponse)),
|
||||
)
|
||||
const body = yield* HttpClientResponse.filterStatusOk(response).pipe(Effect.flatMap((ok) => ok.json))
|
||||
// A Console that serves a regular OpenCode config marks it with `$schema`; any other body is the legacy response.
|
||||
if (Predicate.hasProperty(body, "$schema"))
|
||||
return { type: "config" as const, info: yield* Schema.decodeUnknownEffect(ConfigIntegration.Remote)(body) }
|
||||
return { type: "legacy" as const, response: yield* Schema.decodeUnknownEffect(OpencodeLegacy.Response)(body) }
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
@@ -593,13 +505,6 @@ function organizationName(credential: Credential.Value) {
|
||||
return typeof credential.metadata?.orgName === "string" ? credential.metadata.orgName : undefined
|
||||
}
|
||||
|
||||
function withoutCredentials<Value>(body: Readonly<Record<string, Value>> | undefined) {
|
||||
return (
|
||||
body &&
|
||||
Object.fromEntries(Object.entries(body).filter(([key]) => !["apiKey", "authToken", "accessToken"].includes(key)))
|
||||
)
|
||||
}
|
||||
|
||||
function normalizeServer(input: unknown) {
|
||||
return Effect.try({
|
||||
try: () => {
|
||||
|
||||
@@ -4,6 +4,7 @@ import { describe, expect, test } from "bun:test"
|
||||
import { Arbitrary, Effect, Fiber, Layer, Logger, Schema, Stream } 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"
|
||||
@@ -26,6 +27,7 @@ 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 { location } from "../fixture/location"
|
||||
@@ -425,6 +427,145 @@ describe("Config", () => {
|
||||
),
|
||||
)
|
||||
|
||||
it.live("layers integration documents below remote and user config and reloads when they change", () =>
|
||||
Effect.acquireUseRelease(
|
||||
Effect.promise(() => tmpdir()),
|
||||
(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)),
|
||||
)
|
||||
}),
|
||||
(tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()),
|
||||
),
|
||||
)
|
||||
|
||||
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(), { statements: [] })
|
||||
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("skips project configuration when project discovery is disabled", () =>
|
||||
Effect.acquireDisposable(Effect.promise(() => tmpdir())).pipe(
|
||||
Effect.flatMap((tmp) => {
|
||||
|
||||
@@ -1,15 +1,20 @@
|
||||
import { describe, expect } from "bun:test"
|
||||
import { LLM } from "@opencode/ai/effect"
|
||||
import { LLMClient, RequestExecutor } from "@opencode/ai/route"
|
||||
import { Document, Event, Info } from "@opencode/schema/config"
|
||||
import { ConfigPolicy } from "@opencode/schema/config/policy"
|
||||
import { Money } from "@opencode/schema/money"
|
||||
import { Effect, Layer, Stream } from "effect"
|
||||
import { Effect, Layer, Schema, Stream } from "effect"
|
||||
import { TestClock } from "effect/testing"
|
||||
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"
|
||||
import { Agent } from "@opencode/core/agent"
|
||||
import { App } from "@opencode/core/app"
|
||||
import { Bus } from "@opencode/core/bus"
|
||||
import { Config } from "@opencode/core/config"
|
||||
import { ConfigIntegration } from "@opencode/core/config/integration"
|
||||
import { ConfigPolicyPlugin } from "@opencode/core/config/plugin/policy"
|
||||
import { ConfigProviderPlugin } from "@opencode/core/config/plugin/provider"
|
||||
import { ConfigWebSearchPlugin } from "@opencode/core/config/plugin/websearch"
|
||||
import { Credential } from "@opencode/core/credential"
|
||||
import { Integration } from "@opencode/core/integration"
|
||||
import { ManagedPolicy } from "@opencode/core/managed-policy"
|
||||
@@ -19,6 +24,7 @@ import { ModelResolver } from "@opencode/core/model-resolver"
|
||||
import { Plugin } from "@opencode/core/plugin"
|
||||
import { PluginHooks } from "@opencode/core/plugin/hooks"
|
||||
import { PluginHost } from "@opencode/core/plugin/host"
|
||||
import { OpenAIPlugin } from "@opencode/core/plugin/provider/openai"
|
||||
import { OpencodePlugin } from "@opencode/core/plugin/provider/opencode"
|
||||
import { Provider } from "@opencode/core/provider"
|
||||
import { Session } from "@opencode/core/session"
|
||||
@@ -2028,6 +2034,417 @@ describe("OpencodePlugin", () => {
|
||||
)
|
||||
})
|
||||
|
||||
// A Console that marks its response with `$schema` serves a regular OpenCode config, merged as an integration document.
|
||||
describe("OpencodePlugin with a Console config", () => {
|
||||
const $schema = "https://opencode.ai/config.json"
|
||||
const consoleDocument = (config: Config.Interface) =>
|
||||
config
|
||||
.entries()
|
||||
.pipe(
|
||||
Effect.map((entries) =>
|
||||
entries.find((entry): entry is ConfigIntegration.Document => entry instanceof ConfigIntegration.Document),
|
||||
),
|
||||
)
|
||||
const deny: ConfigPolicy.Info = { action: "tool.use", resource: "shell:*", effect: "deny" }
|
||||
|
||||
it.effect("merges a response with $schema as config and applies one without it as before", () =>
|
||||
Effect.acquireUseRelease(
|
||||
Effect.sync(() => {
|
||||
const state = { schema: true }
|
||||
const server = Bun.serve({
|
||||
port: 0,
|
||||
fetch: () =>
|
||||
Response.json({
|
||||
...(state.schema ? { $schema } : {}),
|
||||
providers: { remote: { name: "Remote" } },
|
||||
policies: [deny],
|
||||
}),
|
||||
})
|
||||
return { server, state }
|
||||
}),
|
||||
({ server, state }) =>
|
||||
Effect.gen(function* () {
|
||||
const credentials = yield* Credential.Service
|
||||
const config = yield* Config.Service
|
||||
const managed = yield* ManagedPolicy.Service
|
||||
const hooks = yield* PluginHooks.Service
|
||||
yield* credentials.create({
|
||||
integrationID: Integration.ID.make("opencode"),
|
||||
value: Credential.Key.make({
|
||||
type: "key",
|
||||
key: "secret",
|
||||
metadata: { server: server.url.origin, orgID: "org_acme", orgName: "Acme" },
|
||||
}),
|
||||
})
|
||||
const host = yield* PluginHost.make(yield* Plugin.Service)
|
||||
yield* OpencodePlugin.effect(host).pipe(inProcess(server))
|
||||
yield* ConfigPolicyPlugin.Plugin.effect(host)
|
||||
|
||||
const document = required(yield* consoleDocument(config))
|
||||
expect(document.info.providers?.remote?.name).toBe("Remote")
|
||||
expect(document.organization).toBe("Acme")
|
||||
expect(managed.current()).toEqual({ statements: [], organization: "Acme" })
|
||||
expect(
|
||||
yield* hooks.trigger("permission", "evaluate", {
|
||||
sessionID: Session.ID.make("ses_console_policy"),
|
||||
action: "shell",
|
||||
resources: ["ls"],
|
||||
effect: "allow",
|
||||
}),
|
||||
).toMatchObject({ effect: "deny", message: "Blocked by Acme's policy" })
|
||||
|
||||
state.schema = false
|
||||
yield* TestClock.adjust("1 minute")
|
||||
yield* drain
|
||||
expect(yield* consoleDocument(config)).toBeUndefined()
|
||||
expect(managed.current()).toEqual({ statements: [deny], organization: "Acme" })
|
||||
}),
|
||||
({ server }) => Effect.promise(() => server.stop(true)),
|
||||
),
|
||||
)
|
||||
|
||||
it.effect(
|
||||
"passes only providers, remote MCP servers, policies, and the web search selection, without credentials",
|
||||
() =>
|
||||
Effect.acquireUseRelease(
|
||||
Effect.sync(() =>
|
||||
Bun.serve({
|
||||
port: 0,
|
||||
fetch: () =>
|
||||
Response.json({
|
||||
$schema,
|
||||
providers: {
|
||||
remote: {
|
||||
env: ["REMOTE_API_KEY"],
|
||||
settings: { apiKey: "key", authToken: "auth", accessToken: "access", baseURL: "https://remote" },
|
||||
models: {
|
||||
chat: {
|
||||
settings: { apiKey: "key", temperature: 0.1 },
|
||||
variants: [{ id: "high", settings: { accessToken: "access", temperature: 0.2 } }],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
mcp: {
|
||||
servers: {
|
||||
remote: { type: "remote", url: "https://remote/mcp" },
|
||||
local: { type: "local", command: ["/tmp/console-mcp"] },
|
||||
},
|
||||
},
|
||||
policies: [deny],
|
||||
websearch: { provider: "opencode" },
|
||||
plugins: ["file:///tmp/console-plugin"],
|
||||
shell: "/tmp/console-shell",
|
||||
agents: { console: { prompt: "Console agent" } },
|
||||
commands: { console: { template: "Console command" } },
|
||||
permissions: [{ action: "shell", resource: "*", effect: "allow" }],
|
||||
formatter: { console: { command: ["/tmp/console-formatter"] } },
|
||||
instructions: ["/tmp/console-instructions.md"],
|
||||
}),
|
||||
}),
|
||||
),
|
||||
(server) =>
|
||||
Effect.gen(function* () {
|
||||
const credentials = yield* Credential.Service
|
||||
const config = yield* Config.Service
|
||||
yield* credentials.create({
|
||||
integrationID: Integration.ID.make("opencode"),
|
||||
value: Credential.Key.make({ type: "key", key: "secret", metadata: { server: server.url.origin } }),
|
||||
})
|
||||
yield* addPlugin().pipe(inProcess(server))
|
||||
|
||||
const info = required(yield* consoleDocument(config)).info
|
||||
expect(Object.keys(Schema.encodeSync(Info)(info)).toSorted()).toEqual([
|
||||
"mcp",
|
||||
"policies",
|
||||
"providers",
|
||||
"websearch",
|
||||
])
|
||||
expect(Object.keys(info.mcp?.servers ?? {})).toEqual(["remote"])
|
||||
const remote = required(info.providers?.remote)
|
||||
expect(remote.env).toBeUndefined()
|
||||
expect(remote.settings).toEqual({ baseURL: "https://remote" })
|
||||
expect(remote.models?.chat?.settings).toEqual({ temperature: 0.1 })
|
||||
expect(remote.models?.chat?.variants?.[0]?.settings).toEqual({ temperature: 0.2 })
|
||||
}),
|
||||
(server) => Effect.promise(() => server.stop(true)),
|
||||
),
|
||||
)
|
||||
|
||||
it.effect("keeps a newer Console config loadable despite values this version does not know", () =>
|
||||
Effect.acquireUseRelease(
|
||||
Effect.sync(() =>
|
||||
Bun.serve({
|
||||
port: 0,
|
||||
fetch: () =>
|
||||
Response.json({
|
||||
$schema,
|
||||
providers: { remote: { name: "Remote" } },
|
||||
policies: [{ action: "future.use", resource: "anything", effect: "deny" }, deny],
|
||||
shell: 123,
|
||||
future: { shape: 42 },
|
||||
}),
|
||||
}),
|
||||
),
|
||||
(server) =>
|
||||
Effect.gen(function* () {
|
||||
const credentials = yield* Credential.Service
|
||||
const config = yield* Config.Service
|
||||
yield* credentials.create({
|
||||
integrationID: Integration.ID.make("opencode"),
|
||||
value: Credential.Key.make({ type: "key", key: "secret", metadata: { server: server.url.origin } }),
|
||||
})
|
||||
yield* addPlugin().pipe(inProcess(server))
|
||||
|
||||
const info = required(yield* consoleDocument(config)).info
|
||||
expect(info.providers?.remote?.name).toBe("Remote")
|
||||
expect(info.policies).toEqual([deny])
|
||||
}),
|
||||
(server) => Effect.promise(() => server.stop(true)),
|
||||
),
|
||||
)
|
||||
|
||||
it.live("layers Console providers below user config, bound to the Console connection", () =>
|
||||
Effect.acquireUseRelease(
|
||||
Effect.sync(() =>
|
||||
Bun.serve({
|
||||
port: 0,
|
||||
fetch: (request) =>
|
||||
Response.json({
|
||||
$schema,
|
||||
providers: {
|
||||
remote: {
|
||||
name: "Console",
|
||||
package: "aisdk:@ai-sdk/openai-compatible",
|
||||
settings: { baseURL: `${new URL(request.url).origin}/v1`, apiKey: "console-key", custom: "console" },
|
||||
headers: { "x-org-id": "console", "x-console": "true" },
|
||||
models: {
|
||||
chat: { name: "Console Chat", settings: { temperature: 0.1 } },
|
||||
other: { name: "Console Other" },
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
}),
|
||||
),
|
||||
(server) =>
|
||||
Effect.gen(function* () {
|
||||
const credentials = yield* Credential.Service
|
||||
const providers = yield* Provider.Service
|
||||
const models = yield* Model.Service
|
||||
const config = yield* Config.Test
|
||||
yield* config.setEntries([
|
||||
new Document({
|
||||
type: "document",
|
||||
info: Schema.decodeUnknownSync(Info)({
|
||||
providers: {
|
||||
remote: {
|
||||
name: "Mine",
|
||||
settings: { apiKey: "my-key" },
|
||||
headers: { "x-org-id": "mine" },
|
||||
models: { chat: { name: "My Chat" } },
|
||||
},
|
||||
},
|
||||
}),
|
||||
}),
|
||||
])
|
||||
yield* credentials.create({
|
||||
integrationID: Integration.ID.make("opencode"),
|
||||
value: Credential.Key.make({ type: "key", key: "secret", metadata: { server: server.url.origin } }),
|
||||
})
|
||||
const host = yield* PluginHost.make(yield* Plugin.Service)
|
||||
yield* OpencodePlugin.effect(host)
|
||||
yield* ConfigProviderPlugin.Plugin.effect(host)
|
||||
|
||||
const provider = required(yield* providers.get(Provider.ID.make("remote")))
|
||||
expect(provider.name).toBe("Mine")
|
||||
expect(provider.integrationID).toBe(Integration.ID.make("opencode"))
|
||||
expect(provider.headers).toEqual({ "x-org-id": "mine", "x-console": "true" })
|
||||
expect(provider.settings).toEqual({
|
||||
baseURL: `${server.url.origin}/v1`,
|
||||
custom: "console",
|
||||
apiKey: "my-key",
|
||||
provider: "remote",
|
||||
})
|
||||
const chat = required(yield* models.get(Provider.ID.make("remote"), Model.ID.make("chat")))
|
||||
expect(chat.name).toBe("My Chat")
|
||||
expect(chat.settings).toMatchObject({ temperature: 0.1 })
|
||||
expect(required(yield* models.get(Provider.ID.make("remote"), Model.ID.make("other"))).name).toBe(
|
||||
"Console Other",
|
||||
)
|
||||
}),
|
||||
(server) => Effect.promise(() => server.stop(true)),
|
||||
),
|
||||
)
|
||||
|
||||
it.effect("applies Console providers before provider plugins tune their canonical provider", () =>
|
||||
Effect.acquireUseRelease(
|
||||
Effect.sync(() =>
|
||||
Bun.serve({
|
||||
port: 0,
|
||||
fetch: () =>
|
||||
Response.json({
|
||||
$schema,
|
||||
providers: { "console-openai": { canonical: "openai", name: "Console OpenAI" } },
|
||||
}),
|
||||
}),
|
||||
),
|
||||
(server) =>
|
||||
Effect.gen(function* () {
|
||||
const credentials = yield* Credential.Service
|
||||
const providers = yield* Provider.Service
|
||||
yield* providers.transform((catalog) =>
|
||||
catalog.update(Provider.ID.openai, (provider) => {
|
||||
provider.package = "aisdk:@ai-sdk/openai"
|
||||
}),
|
||||
)
|
||||
yield* credentials.create({
|
||||
integrationID: Integration.ID.make("opencode"),
|
||||
value: Credential.Key.make({ type: "key", key: "secret", metadata: { server: server.url.origin } }),
|
||||
})
|
||||
const host = yield* PluginHost.make(yield* Plugin.Service)
|
||||
// Registered in production order: the OpenCode and OpenAI provider plugins, then config in `post`.
|
||||
yield* OpencodePlugin.effect(host).pipe(inProcess(server))
|
||||
yield* OpenAIPlugin.effect(host)
|
||||
yield* ConfigProviderPlugin.Plugin.effect(host)
|
||||
|
||||
expect(required(yield* providers.get(Provider.ID.openai)).settings?.transport).toBe("websocket")
|
||||
const consoleOpenAI = required(yield* providers.get(Provider.ID.make("console-openai")))
|
||||
expect(consoleOpenAI.name).toBe("Console OpenAI")
|
||||
expect(consoleOpenAI.integrationID).toBe(Integration.ID.make("opencode"))
|
||||
expect(consoleOpenAI.settings?.transport).toBeUndefined()
|
||||
}),
|
||||
(server) => Effect.promise(() => server.stop(true)),
|
||||
),
|
||||
)
|
||||
|
||||
it.effect("registers Console web search without forcing it, so config selects it and user config wins", () =>
|
||||
Effect.acquireUseRelease(
|
||||
Effect.sync(() => {
|
||||
const state = { selected: false }
|
||||
const server = Bun.serve({
|
||||
port: 0,
|
||||
fetch: (request) => {
|
||||
if (new URL(request.url).pathname === "/api/websearch")
|
||||
return Response.json({ providerID: "opencode", results: [] })
|
||||
return Response.json({ $schema, ...(state.selected ? { websearch: { provider: "opencode" } } : {}) })
|
||||
},
|
||||
})
|
||||
return { server, state }
|
||||
}),
|
||||
({ server, state }) =>
|
||||
Effect.gen(function* () {
|
||||
const credentials = yield* Credential.Service
|
||||
const websearch = yield* WebSearch.Service
|
||||
const config = yield* Config.Test
|
||||
const bus = yield* Bus.Service
|
||||
const opencode = { id: WebSearch.ID.make("opencode"), name: "OpenCode Web Search" }
|
||||
// Config.testLayer does not announce integration changes the way config reloads do.
|
||||
const announced = (expected: typeof opencode | undefined) =>
|
||||
bus
|
||||
.publish(Event.Updated, {})
|
||||
.pipe(Effect.andThen(eventually(websearch.default(), (value) => value?.id === expected?.id)))
|
||||
yield* websearch.transform((editor) =>
|
||||
editor.add({ id: WebSearch.ID.make("mine"), name: "Mine", execute: () => Effect.succeed([]) }),
|
||||
)
|
||||
yield* credentials.create({
|
||||
integrationID: Integration.ID.make("opencode"),
|
||||
value: Credential.Key.make({ type: "key", key: "secret", metadata: { server: server.url.origin } }),
|
||||
})
|
||||
const host = yield* PluginHost.make(yield* Plugin.Service)
|
||||
yield* OpencodePlugin.effect(host).pipe(inProcess(server))
|
||||
yield* ConfigWebSearchPlugin.Plugin.effect(host)
|
||||
expect(yield* websearch.providers()).toContainEqual(opencode)
|
||||
expect(yield* websearch.default()).toBeUndefined()
|
||||
|
||||
state.selected = true
|
||||
yield* TestClock.adjust("1 minute")
|
||||
yield* drain
|
||||
expect(yield* announced(opencode)).toEqual(opencode)
|
||||
expect((yield* websearch.query({ query: "console" })).providerID).toBe(opencode.id)
|
||||
|
||||
yield* config.setEntries([
|
||||
new Document({
|
||||
type: "document",
|
||||
info: Schema.decodeUnknownSync(Info)({ websearch: { provider: "mine" } }),
|
||||
}),
|
||||
])
|
||||
expect(yield* announced({ id: WebSearch.ID.make("mine"), name: "Mine" })).toEqual({
|
||||
id: WebSearch.ID.make("mine"),
|
||||
name: "Mine",
|
||||
})
|
||||
}),
|
||||
({ server }) => Effect.promise(() => server.stop(true)),
|
||||
),
|
||||
)
|
||||
|
||||
it.effect("replaces the Console config on an account switch and clears it on sign-out", () =>
|
||||
Effect.acquireUseRelease(
|
||||
Effect.sync(() =>
|
||||
Bun.serve({
|
||||
port: 0,
|
||||
fetch: (request) => {
|
||||
const orgID = request.headers.get("x-org-id") ?? "none"
|
||||
return Response.json({
|
||||
$schema,
|
||||
providers: { [orgID]: {} },
|
||||
mcp: { servers: { [orgID]: { type: "remote", url: `https://${orgID}/mcp` } } },
|
||||
policies: [{ action: "tool.use", resource: `shell:${orgID}`, effect: "deny" }],
|
||||
websearch: { provider: "opencode" },
|
||||
})
|
||||
},
|
||||
}),
|
||||
),
|
||||
(server) =>
|
||||
Effect.gen(function* () {
|
||||
const credentials = yield* Credential.Service
|
||||
const config = yield* Config.Service
|
||||
const account = (orgID: string) =>
|
||||
credentials.create({
|
||||
integrationID: Integration.ID.make("opencode"),
|
||||
value: Credential.Key.make({
|
||||
type: "key",
|
||||
key: orgID,
|
||||
metadata: { server: server.url.origin, orgID, orgName: orgID },
|
||||
}),
|
||||
})
|
||||
const contents = consoleDocument(config).pipe(
|
||||
Effect.map(
|
||||
(document) =>
|
||||
document && {
|
||||
organization: document.organization,
|
||||
providers: Object.keys(document.info.providers ?? {}),
|
||||
mcp: Object.keys(document.info.mcp?.servers ?? {}),
|
||||
policies: document.info.policies?.map((policy) => policy.resource),
|
||||
websearch: document.info.websearch && String(document.info.websearch.provider),
|
||||
},
|
||||
),
|
||||
)
|
||||
const expected = (orgID: string) => ({
|
||||
organization: orgID,
|
||||
providers: [orgID],
|
||||
mcp: [orgID],
|
||||
policies: [`shell:${orgID}`],
|
||||
websearch: "opencode",
|
||||
})
|
||||
const alpha = yield* account("alpha")
|
||||
yield* addPlugin().pipe(inProcess(server))
|
||||
expect(yield* contents).toEqual(expected("alpha"))
|
||||
|
||||
const beta = yield* account("beta")
|
||||
expect(yield* eventually(contents, (value) => value?.organization === "beta")).toEqual(expected("beta"))
|
||||
|
||||
yield* credentials.remove(beta.id)
|
||||
expect(yield* eventually(contents, (value) => value?.organization === "alpha")).toEqual(expected("alpha"))
|
||||
|
||||
yield* credentials.remove(alpha.id)
|
||||
expect(yield* eventually(contents, (value) => value === undefined)).toBeUndefined()
|
||||
}),
|
||||
(server) => Effect.promise(() => server.stop(true)),
|
||||
),
|
||||
)
|
||||
})
|
||||
|
||||
for (const key of [undefined, "secret"]) {
|
||||
testEffect(Layer.empty).effect(
|
||||
`disabled free models with ${key ? "an API key" : "a Console login after startup"}`,
|
||||
|
||||
@@ -179,17 +179,21 @@ it was configured.
|
||||
|
||||
Ordinary settings let the nearest configuration win. Policies reverse that: statements
|
||||
from broader configuration are evaluated later, so they override narrower ones. Managed
|
||||
configuration and the connected Console always have the final say.
|
||||
configuration and the connected Console always outrank user and project files.
|
||||
|
||||
| Authority | Source |
|
||||
| ----------- | -------------------------------------------------------------------------------------------------------------- |
|
||||
| 1 (highest) | Connected OpenCode Console workspace |
|
||||
| 2 | macOS managed preferences (`/Library/Managed Preferences/ai.opencode.managed.plist`) |
|
||||
| 3 | System `opencode.json(c)` (`/Library/Application Support/opencode`, `/etc/opencode`, `%ProgramData%\opencode`) |
|
||||
| 1 (highest) | macOS managed preferences (`/Library/Managed Preferences/ai.opencode.managed.plist`) |
|
||||
| 2 | System `opencode.json(c)` (`/Library/Application Support/opencode`, `/etc/opencode`, `%ProgramData%\opencode`) |
|
||||
| 3 | Connected OpenCode Console workspace |
|
||||
| 4 | Global `~/.config/opencode/opencode.json(c)` |
|
||||
| 5 | Direct `opencode.json(c)`; outer directories beat inner ones |
|
||||
| 6 (lowest) | `.opencode/opencode.json(c)`; outer directories beat inner ones |
|
||||
|
||||
This order applies when the Console serves its workspace configuration in the current
|
||||
format. A Console that still serves the older format ranks first instead, above managed
|
||||
preferences and the system file; see [Console](#console).
|
||||
|
||||
A repository cannot re-enable a provider you deny globally:
|
||||
|
||||
```jsonc title="~/.config/opencode/opencode.jsonc"
|
||||
@@ -210,9 +214,14 @@ A repository cannot re-enable a provider you deny globally:
|
||||
|
||||
A workspace on the [OpenCode Console](/console) compiles its Providers and Tools
|
||||
policies into statements and returns them with the workspace configuration. OpenCode
|
||||
appends them after every authored statement, so they have the final say: an
|
||||
organization `deny` cannot be lifted by a repository or user `allow`, and an
|
||||
organization `allow` lifts a lower-authority `deny`.
|
||||
merges that configuration like a configuration file that ranks right below managed
|
||||
preferences and the system file, so an organization `deny` cannot be lifted by a
|
||||
repository or user `allow`, and an organization `allow` lifts a lower-authority `deny`.
|
||||
Managed preferences and the system file still override the workspace.
|
||||
|
||||
A Console that serves the older format instead has its statements appended after every
|
||||
authored statement, so they have the final say, over managed preferences and the system
|
||||
file too.
|
||||
|
||||
Denials from these statements name the workspace:
|
||||
|
||||
|
||||
Reference in New Issue
Block a user