Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 38 additions & 19 deletions packages/core/src/integration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,12 @@ export interface Interface extends State.Transformable<Draft> {
readonly resolve: (
connection: IntegrationConnection.Info,
) => Effect.Effect<Credential.Value | undefined, AuthorizationError>
/** Resolves with a refresh implementation that may not be materialized in the registry yet. */
readonly resolveWithRefresh: (
connection: IntegrationConnection.Info,
methodID: MethodID,
refresh: NonNullable<OAuthImplementation["refresh"]>,
) => Effect.Effect<Credential.Value | undefined, AuthorizationError>
/** Runs a key method and stores the resulting credential. */
readonly key: (input: {
/** Integration receiving the credential. */
Expand Down Expand Up @@ -656,6 +662,34 @@ const layer = Layer.effect(
return CommandAttempt.make({ attemptID, time })
})

const resolveConnection = Effect.fnUntraced(function* (
connection: IntegrationConnection.Info,
fallback?: {
readonly methodID: MethodID
readonly refresh: NonNullable<OAuthImplementation["refresh"]>
},
) {
if (connection.type === "env") {
const key = process.env[connection.name]
return key ? Credential.Key.make({ type: "key", key }) : undefined
}
const credential = yield* credentials.get(connection.id)
if (!credential) return undefined
if (credential.value.type === "key") return credential.value
const implementation = state
.get()
.integrations.get(credential.integrationID)
?.implementations.get(credential.value.methodID)
const refresh =
implementation?.refresh ?? (fallback?.methodID === credential.value.methodID ? fallback.refresh : undefined)
if (!refresh) return credential.value
const now = yield* Clock.currentTimeMillis
if (credential.value.expires > now + Duration.toMillis(Duration.minutes(5))) return credential.value
const value = yield* authorize(refresh(credential.value))
yield* credentials.update(credential.id, { value })
return value
})

return Service.of({
transform: state.transform,
reload: state.reload,
Expand All @@ -675,25 +709,10 @@ const layer = Layer.effect(
const entry = state.get().integrations.get(id)
return resolveConnections(entry, yield* credentials.list(id))[0]
}),
resolve: Effect.fn("Integration.connection.resolve")(function* (connection) {
if (connection.type === "env") {
const key = process.env[connection.name]
return key ? Credential.Key.make({ type: "key", key }) : undefined
}
const credential = yield* credentials.get(connection.id)
if (!credential) return undefined
if (credential.value.type === "key") return credential.value
const implementation = state
.get()
.integrations.get(credential.integrationID)
?.implementations.get(credential.value.methodID)
if (!implementation?.refresh) return credential.value
const now = yield* Clock.currentTimeMillis
if (credential.value.expires > now + Duration.toMillis(Duration.minutes(5))) return credential.value
const value = yield* authorize(implementation.refresh(credential.value))
yield* credentials.update(credential.id, { value })
return value
}),
resolve: Effect.fn("Integration.connection.resolve")((connection) => resolveConnection(connection)),
resolveWithRefresh: Effect.fn("Integration.connection.resolveWithRefresh")((connection, methodID, refresh) =>
resolveConnection(connection, { methodID, refresh }),
),
key: Effect.fn("Integration.connection.key")(function* (input) {
const method = state
.get()
Expand Down
34 changes: 28 additions & 6 deletions packages/core/src/plugin/provider/opencode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Duration, Effect, Schema, Semaphore, Stream } from "effect"
import type { Scope } from "effect"
import type { IntegrationOAuthMethodRegistration } from "@opencode-ai/plugin/v2/effect/integration"
import { define } from "@opencode-ai/plugin/v2/effect/plugin"
import type { CredentialValue } from "@opencode-ai/sdk/v2/types"
import type { CredentialOAuth, CredentialValue } from "@opencode-ai/sdk/v2/types"
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http"
import { EventV2 } from "../../event"
import { Credential } from "../../credential"
Expand Down Expand Up @@ -79,24 +79,40 @@ function oauth(http: HttpClient.HttpClient) {
label: (credential) => {
return typeof credential.metadata?.orgName === "string" ? credential.metadata.orgName : undefined
},
} satisfies IntegrationOAuthMethodRegistration
} satisfies Integration.OAuthImplementation
}

export const OpencodePlugin = define<HttpClient.HttpClient | EventV2.Service | Scope.Scope>({
export const OpencodePlugin = define<HttpClient.HttpClient | EventV2.Service | Integration.Service | Scope.Scope>({
id: "opencode.provider.opencode",
effect: Effect.fn(function* (ctx) {
const events = yield* EventV2.Service
const http = yield* HttpClient.HttpClient
const integrations = yield* Integration.Service
const method = oauth(http)
const coreCredential = (credential: CredentialOAuth) =>
Credential.OAuth.make({ ...credential, methodID: Integration.MethodID.make(credential.methodID) })
const registration = {
...method,
refresh: (credential: CredentialOAuth) => method.refresh(coreCredential(credential)),
label: (credential: CredentialOAuth) => method.label(coreCredential(credential)),
} satisfies IntegrationOAuthMethodRegistration
const loading = Semaphore.makeUnsafe(1)
let connected = false
let remoteConfigRequired = false
let providers: typeof ConfigV1.Info.Type.provider | undefined

const load = Effect.fn("OpencodePlugin.load")(function* () {
const connection = yield* ctx.integration.connection.active("opencode")
const connection = yield* integrations.connection.active(Integration.ID.make("opencode"))
const credential = connection
? yield* ctx.integration.connection.resolve(connection).pipe(Effect.catch(() => Effect.succeed(undefined)))
? yield* integrations.connection
.resolveWithRefresh(connection, method.method.id, method.refresh)
.pipe(Effect.catch(() => Effect.succeed(undefined)))
: undefined
connected = connection !== undefined
// Console credentials require its provider overlay; only legacy Zen `sk-` keys may use the models.dev fallback.
remoteConfigRequired =
connection !== undefined &&
(credential === undefined || credential.type === "oauth" || credential.key.startsWith("oc_sk_"))
providers = credential
? yield* fetchProviders(http, credential).pipe(
Effect.catch((cause) =>
Expand All @@ -110,7 +126,7 @@ export const OpencodePlugin = define<HttpClient.HttpClient | EventV2.Service | S
draft.update("opencode", (integration) => {
integration.name = "OpenCode"
})
draft.method.update(oauth(http))
draft.method.update(registration)
draft.method.update({ integrationID: "opencode", method: { type: "key", label: "API key (service account)" } })
})

Expand Down Expand Up @@ -175,6 +191,12 @@ export const OpencodePlugin = define<HttpClient.HttpClient | EventV2.Service | S

const item = catalog.provider.get(ProviderV2.ID.opencode)
if (!item) return
if (remoteConfigRequired && providers?.[ProviderV2.ID.opencode] === undefined) {
catalog.provider.update(item.provider.id, (provider) => {
provider.disabled = true
})
return
}
const hasKey = Boolean(process.env.OPENCODE_API_KEY || connected || item.provider.settings?.apiKey)
catalog.provider.update(item.provider.id, (provider) => {
if (!hasKey) provider.settings = { ...provider.settings, apiKey: "public" }
Expand Down
1 change: 1 addition & 0 deletions packages/core/test/mcp.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,7 @@ function resourceMcpLayer(url: string, onFormCreated?: (form: Form.Info) => Effe
connection: {
active: unusedIntegration,
resolve: unusedIntegration,
resolveWithRefresh: unusedIntegration,
key: unusedIntegration,
update: unusedIntegration,
remove: unusedIntegration,
Expand Down
Loading
Loading