diff --git a/packages/core/src/plugin/provider/opencode.ts b/packages/core/src/plugin/provider/opencode.ts index 4d109608f7f..a4d4c0c652f 100644 --- a/packages/core/src/plugin/provider/opencode.ts +++ b/packages/core/src/plugin/provider/opencode.ts @@ -72,6 +72,10 @@ const SkillBundle = Schema.Struct({ files: Schema.Array(Schema.Struct({ path: Schema.String, content: Schema.String })), }) type ConsoleSkill = { readonly skill: Skill.Info; readonly files: Record } +type ConsoleConfig = NonNullable>> & { + readonly instructions: (typeof ConsoleInstructions.Type)["instructions"] + readonly skills: (typeof ConsoleSkills.Type)["skills"] +} const signedOutMessage = "Reconnect OpenCode Console to continue" const ssoMessage = (organization: string | undefined) => `Sign in with SSO again to use ${organization ?? "your OpenCode Console organization"}` @@ -196,7 +200,7 @@ export const OpencodePlugin = define< type ActiveConnection = Effect.Success> let snapshot: { // The Console's regular OpenCode config, merged as an integration config layer. - remote: Effect.Success> + remote: ConsoleConfig | undefined connection: ActiveConnection organization: string | undefined } = { remote: undefined, connection: undefined, organization: undefined } @@ -227,9 +231,16 @@ export const OpencodePlugin = define< Effect.flatMap((credential) => { if (!credential || credential.type === "external") return Effect.succeed({ remote: undefined, connection, organization: undefined }) + const workspace = workspaceKey(connection, credential) + // Each list has its own cache entry, so a failing or malformed one keeps its last copy, or none, and never + // holds back the config and its policies. `SharedCache` already logs the failure. + const list = (name: string, load: Effect.Effect, unknown>) => + cache + .get({ key: `opencode-console-${name}:${workspace}`, interval: maxAge, load }) + .pipe(Effect.orElseSucceed((): ReadonlyArray => [])) return cache .get({ - key: `opencode-console:${workspaceKey(connection, credential)}`, + key: `opencode-console:${workspace}`, interval: maxAge, // A sign-in error is Console's answer for this sign-in, so it is shared like a config rather than // replaced by the last config, as a network failure is. @@ -244,6 +255,27 @@ export const OpencodePlugin = define< Effect.flatMap((result) => "failed" in result ? Effect.fail(result.failed) : Effect.succeed(result.remote), ), + Effect.flatMap((remote) => + remote + ? Effect.all( + { + instructions: list( + "instructions", + fetchList(http, credential, "/api/v2/instructions", ConsoleInstructions).pipe( + Effect.map((body) => body?.instructions ?? []), + ), + ), + skills: list( + "skills", + fetchList(http, credential, "/api/v2/skills", ConsoleSkills).pipe( + Effect.map((body) => body?.skills ?? []), + ), + ), + }, + { concurrency: 2 }, + ).pipe(Effect.map((lists): ConsoleConfig => ({ ...remote, ...lists }))) + : Effect.succeed(undefined), + ), Effect.map((remote) => ({ remote, connection, @@ -568,38 +600,7 @@ function fetchConfig(http: HttpClient.HttpClient, value: Credential.Key | Creden } const watches = response.headers[OpencodeWatches.header] !== undefined const body = yield* HttpClientResponse.filterStatusOk(response).pipe(Effect.flatMap((ok) => ok.json)) - const remote = yield* Schema.decodeUnknownEffect(ConfigIntegration.Remote)(body) - // Instructions and skills have their own endpoints. A 404 (none in the workspace) or a 403 other than SSO - // (the sign-in may not read them) counts as empty; any other error fails the load, which keeps the last lists. - const list = (path: string, schema: Schema.Decoder) => - HttpClient.withScope(http) - .execute( - HttpClientRequest.get(`${ConsoleAccess.server(value)}${path}`).pipe( - HttpClientRequest.acceptJson, - HttpClientRequest.setHeaders(ConsoleAccess.headers(value)), - ), - ) - .pipe( - Effect.flatMap((response) => - Effect.gen(function* () { - if (response.status === 404) return undefined - if ( - response.status === 403 && - Option.isNone(yield* HttpClientResponse.schemaBodyJson(SsoRequired)(response).pipe(Effect.option)) - ) - return undefined - const ok = yield* HttpClientResponse.filterStatusOk(response) - return yield* HttpClientResponse.schemaBodyJson(schema)(ok).pipe( - Effect.orElseSucceed(() => undefined), - ) - }), - ), - ) - const [instructions, skills] = yield* Effect.all( - [list("/api/v2/instructions", ConsoleInstructions), list("/api/v2/skills", ConsoleSkills)], - { concurrency: 2 }, - ) - return { ...remote, instructions: instructions?.instructions ?? [], skills: skills?.skills ?? [], watches } + return { ...(yield* Schema.decodeUnknownEffect(ConfigIntegration.Remote)(body)), watches } }), ), Effect.scoped, @@ -609,6 +610,38 @@ function fetchConfig(http: HttpClient.HttpClient, value: Credential.Key | Creden ) } +// A 404 (none in the workspace) or a 403 other than SSO (the sign-in may not read them) is an empty list. Any other +// error, including a malformed body, fails so the caller keeps the last list. +function fetchList( + http: HttpClient.HttpClient, + value: Credential.Key | Credential.OAuth, + path: string, + schema: Schema.Decoder, +) { + return HttpClient.withScope(http) + .execute( + HttpClientRequest.get(`${ConsoleAccess.server(value)}${path}`).pipe( + HttpClientRequest.acceptJson, + HttpClientRequest.setHeaders(ConsoleAccess.headers(value)), + ), + ) + .pipe( + Effect.flatMap((response) => + Effect.gen(function* () { + if (response.status === 404) return undefined + if ( + response.status === 403 && + Option.isNone(yield* HttpClientResponse.schemaBodyJson(SsoRequired)(response).pipe(Effect.option)) + ) + return undefined + return yield* HttpClientResponse.schemaBodyJson(schema)(yield* HttpClientResponse.filterStatusOk(response)) + }), + ), + Effect.scoped, + Effect.timeout(Duration.seconds(5)), + ) +} + function ssoUrl(server: string, connectionID: string) { return normalizeServer(server).pipe( Effect.map((base) => { diff --git a/packages/core/test/plugin/provider-opencode.test.ts b/packages/core/test/plugin/provider-opencode.test.ts index 1650fa4ead4..f4de2a17230 100644 --- a/packages/core/test/plugin/provider-opencode.test.ts +++ b/packages/core/test/plugin/provider-opencode.test.ts @@ -1682,6 +1682,58 @@ describe("OpencodePlugin", () => { }), ) + it.effect("applies Console policies while its instructions and skills fail, and keeps a list over a malformed one", () => + Effect.gen(function* () { + const credentials = yield* Credential.Service + const config = yield* Config.Service + const discovery = yield* InstructionDiscovery.Service + const sudo: ConfigPolicy.Info = { action: "tool.use", resource: "shell:sudo *", effect: "deny" } + const state: { lists: "down" | "ok" | "malformed" } = { lists: "down" } + const server = { + fetch: (request: Request) => { + const path = new URL(request.url).pathname + if (path === "/api/v2/config") return Response.json({ providers: {}, policies: [sudo] }) + if (path !== "/api/v2/instructions" && path !== "/api/v2/skills") return new Response(null, { status: 404 }) + if (state.lists === "down") return new Response("Unavailable", { status: 503 }) + if (path === "/api/v2/skills") return Response.json({ skills: [] }) + if (state.lists === "malformed") return Response.json({ instructions: [{ id: "style" }] }) + return Response.json({ instructions: [{ id: "style", content: "Use tabs." }] }) + }, + } + const instructions = discovery + .list() + .pipe( + Effect.map((files) => + Array.isArray(files) + ? files.filter((file) => file.path.startsWith("OpenCode Console")).map((file) => file.content) + : [], + ), + ) + yield* credentials.create({ + integrationID: Integration.ID.make("opencode"), + value: Credential.Key.make({ type: "key", key: "secret", metadata: { server: "https://console.test" } }), + }) + + // Once the lists' retries run out, startup still applies the config's policies, just without the lists. + const started = yield* addPlugin().pipe(inProcess(server), Effect.forkChild({ startImmediately: true })) + yield* TestClock.adjust("10 seconds") + yield* Fiber.join(started) + expect(yield* consolePolicies(config)).toEqual([sudo]) + expect(yield* instructions).toEqual([]) + + state.lists = "ok" + yield* TestClock.adjust("1 minute") + yield* drain + expect(yield* instructions).toEqual(["Use tabs."]) + + state.lists = "malformed" + yield* TestClock.adjust("1 minute") + yield* drain + expect(yield* instructions).toEqual(["Use tabs."]) + expect(yield* consolePolicies(config)).toEqual([sudo]) + }), + ) + it.effect("requests Console instructions and skills together", () => Effect.gen(function* () { const credentials = yield* Credential.Service