Skip to content

Commit 776c42a

Browse files
committed
refactor(core): load Console instructions and skills from their own endpoints
After a successful /api/v2/config response, the OpenCode Console plugin reads /api/v2/instructions and /api/v2/skills with the same credential instead of the non-standard `library` config key, and downloads skill bundles from /api/v2/skills/:slug. A non-2xx list counts as empty. The deny check now compares the layered Console document by content, since config keeps a deep-equal document it already holds, which made an instruction or skill edit wipe both.
1 parent f9c9234 commit 776c42a

3 files changed

Lines changed: 113 additions & 41 deletions

File tree

‎packages/core/src/config.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,8 @@ export const testLayer = (
105105
emitChange: (update) => PubSub.publish(updates, update).pipe(Effect.asVoid),
106106
integration: (integrationID, document) =>
107107
Ref.update(integrations, (current) => {
108+
// Like config, keeps the document it holds when handed a deep-equal one.
109+
if (isDeepStrictEqual(current.get(integrationID), document)) return current
108110
const next = new Map(current)
109111
next.delete(integrationID)
110112
return document ? next.set(integrationID, document) : next

‎packages/core/src/plugin/provider/opencode.ts‎

Lines changed: 46 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { isDeepStrictEqual } from "node:util"
12
import { Duration, Effect, Equal, FiberHandle, Option, Schema, Scope, Semaphore, Stream } from "effect"
23
import type { IntegrationOAuthMethodRegistration } from "@opencode/plugin/effect/integration"
34
import { define } from "@opencode/plugin/effect/plugin"
@@ -58,21 +59,18 @@ const SsoRequired = Schema.Struct({
5859
const InvalidGrant = Schema.Struct({ error: Schema.Literal("invalid_grant") })
5960
// Console's 401 when the session behind the access token was revoked or expired.
6061
const Unauthorized = Schema.Struct({ _tag: Schema.Literal("Unauthorized") })
61-
// The workspace Library: instructions arrive whole, skills as versions whose files download separately.
62-
const Library = Schema.Struct({
63-
instructions: Schema.Array(Schema.Struct({ id: Schema.String, content: Schema.String })).pipe(Schema.optional),
64-
skills: Schema.Array(Schema.Struct({ slug: Schema.String, version: Schema.String })).pipe(Schema.optional),
62+
// The workspace's instructions arrive whole, its skills as versions whose files download separately.
63+
const ConsoleInstructions = Schema.Struct({
64+
instructions: Schema.Array(Schema.Struct({ id: Schema.String, content: Schema.String })),
6565
})
66-
// `library` decodes where it's used, so a malformed one can't fail the config and drop its policies.
67-
const ConsoleConfig = Schema.Struct({
68-
...ConfigIntegration.Remote.fields,
69-
library: Schema.Unknown.pipe(Schema.optional),
66+
const ConsoleSkills = Schema.Struct({
67+
skills: Schema.Array(Schema.Struct({ slug: Schema.String, version: Schema.String })),
7068
})
7169
const SkillBundle = Schema.Struct({
7270
slug: Schema.String,
7371
files: Schema.Array(Schema.Struct({ path: Schema.String, content: Schema.String })),
7472
})
75-
type LibrarySkill = { readonly skill: Skill.Info; readonly files: Record<string, string> }
73+
type ConsoleSkill = { readonly skill: Skill.Info; readonly files: Record<string, string> }
7674
const signedOutMessage = "Reconnect OpenCode Console to continue"
7775
const ssoMessage = (organization: string | undefined) =>
7876
`Sign in with SSO again to use ${organization ?? "your OpenCode Console organization"}`
@@ -197,13 +195,13 @@ export const OpencodePlugin = define<
197195
type ActiveConnection = Effect.Success<ReturnType<typeof ctx.integration.connection.active>>
198196
let snapshot: {
199197
// The Console's regular OpenCode config, merged as an integration config layer.
200-
remote: typeof ConsoleConfig.Type | undefined
198+
remote: Effect.Success<ReturnType<typeof fetchConfig>>
201199
connection: ActiveConnection
202200
organization: string | undefined
203201
} = { remote: undefined, connection: undefined, organization: undefined }
204202
let instructions: InstructionDiscovery.File[] = []
205203
// Tagged with the account and workspace they were downloaded for, so a switch hides them right away.
206-
let librarySkills: { owner: string; items: LibrarySkill[] } = { owner: "", items: [] }
204+
let consoleSkills: { owner: string; items: ConsoleSkill[] } = { owner: "", items: [] }
207205
const owner = (from: typeof snapshot) =>
208206
`${IntegrationConnection.key(from.connection) ?? ""}:${from.organization ?? ""}`
209207
// A newer config's skill download replaces one still in flight.
@@ -290,31 +288,33 @@ export const OpencodePlugin = define<
290288
? { ...next.connection, id: Credential.ID.make(next.connection.id) }
291289
: next.connection,
292290
organization: next.organization,
293-
// `make` keeps only the standard config keys, so `library` stays here.
291+
// `make` keeps only the standard config keys, so instructions and skills stay here.
294292
info: next.remote,
295293
})
296294
yield* integrate(document)
297-
// Managed `integration.use: deny` makes config layer a policies-only copy, which withholds the Library too.
298-
yield* syncLibrary(next, document !== undefined && (!config.integration || integrated === document))
295+
// Managed `integration.use: deny` makes config layer a policies-only copy, which withholds instructions and
296+
// skills too. Config keeps the document it holds when handed a deep-equal one, so compare by content.
297+
yield* syncInstructionsAndSkills(
298+
next,
299+
document !== undefined && (!config.integration || isDeepStrictEqual(integrated, document)),
300+
)
299301
})
300-
const syncLibrary = (next: typeof snapshot, allowed: boolean) => {
301-
const library = allowed
302-
? Option.getOrUndefined(Schema.decodeUnknownOption(Library)(next.remote?.library))
303-
: undefined
304-
instructions = (library?.instructions ?? []).map(
302+
const syncInstructionsAndSkills = (next: typeof snapshot, allowed: boolean) => {
303+
const remote = allowed ? next.remote : undefined
304+
instructions = (remote?.instructions ?? []).map(
305305
(item) =>
306306
new InstructionDiscovery.File({ path: `OpenCode Console instruction ${item.id}`, content: item.content }),
307307
)
308-
if (!allowed) librarySkills = { owner: "", items: [] }
308+
if (!allowed) consoleSkills = { owner: "", items: [] }
309309
// Skills download in the background, so startup and config changes never wait on them. The current ones stay
310310
// until the download replaces them.
311311
return FiberHandle.run(
312312
skillDownload,
313-
loadSkills(next.connection, library?.skills ?? []).pipe(
313+
loadSkills(next.connection, remote?.skills ?? []).pipe(
314314
Effect.flatMap((loaded) => {
315315
// A failed load keeps the skills already shown.
316316
if (!loaded) return Effect.void
317-
librarySkills = { owner: owner(next), items: loaded }
317+
consoleSkills = { owner: owner(next), items: loaded }
318318
return skills.reload()
319319
}),
320320
),
@@ -450,8 +450,8 @@ export const OpencodePlugin = define<
450450
})
451451
yield* discovery.transform((editor) => instructions.forEach((file) => editor.add(file)))
452452
yield* skills.transform((editor) => {
453-
if (librarySkills.owner !== owner(snapshot)) return
454-
librarySkills.items.forEach((item) => editor.add(item.skill, item.files))
453+
if (consoleSkills.owner !== owner(snapshot)) return
454+
consoleSkills.items.forEach((item) => editor.add(item.skill, item.files))
455455
})
456456

457457
const apply = Effect.fn("OpencodePlugin.apply")(function* (next: typeof snapshot) {
@@ -544,7 +544,26 @@ function fetchConfig(http: HttpClient.HttpClient, value: Credential.Key | Creden
544544
})
545545
}
546546
const body = yield* HttpClientResponse.filterStatusOk(response).pipe(Effect.flatMap((ok) => ok.json))
547-
return yield* Schema.decodeUnknownEffect(ConsoleConfig)(body)
547+
const remote = yield* Schema.decodeUnknownEffect(ConfigIntegration.Remote)(body)
548+
// Instructions and skills have their own endpoints. A list Console doesn't give counts as empty.
549+
const list = <A>(path: string, schema: Schema.Decoder<A>) =>
550+
HttpClient.withScope(http)
551+
.execute(
552+
HttpClientRequest.get(`${ConsoleAccess.server(value)}${path}`).pipe(
553+
HttpClientRequest.acceptJson,
554+
HttpClientRequest.setHeaders(ConsoleAccess.headers(value)),
555+
),
556+
)
557+
.pipe(
558+
Effect.flatMap((response) =>
559+
response.status >= 300
560+
? Effect.succeed(undefined)
561+
: HttpClientResponse.schemaBodyJson(schema)(response).pipe(Effect.orElseSucceed(() => undefined)),
562+
),
563+
)
564+
const instructions = yield* list("/api/v2/instructions", ConsoleInstructions)
565+
const skills = yield* list("/api/v2/skills", ConsoleSkills)
566+
return { ...remote, instructions: instructions?.instructions ?? [], skills: skills?.skills ?? [] }
548567
}),
549568
),
550569
Effect.scoped,
@@ -663,7 +682,7 @@ function downloadSkill(http: HttpClient.HttpClient, server: string, slug: string
663682
if (!SkillDiscovery.isSafeSegment(slug)) return yield* Effect.fail(new Error(`unsafe skill slug: ${slug}`))
664683
const bundle = yield* follow(
665684
http,
666-
HttpClientRequest.get(`${server}/api/v2/library/skills/${encodeURIComponent(slug)}`).pipe(
685+
HttpClientRequest.get(`${server}/api/v2/skills/${encodeURIComponent(slug)}`).pipe(
667686
HttpClientRequest.acceptJson,
668687
HttpClientRequest.setHeaders(headers),
669688
),
@@ -680,7 +699,7 @@ function downloadSkill(http: HttpClient.HttpClient, server: string, slug: string
680699
files: Object.fromEntries(
681700
bundle.files.filter((file) => file.path !== "SKILL.md").map((file) => [file.path, file.content]),
682701
),
683-
} satisfies LibrarySkill
702+
} satisfies ConsoleSkill
684703
})
685704
}
686705

‎packages/core/test/plugin/provider-opencode.test.ts‎

Lines changed: 65 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import { ConfigPolicyPlugin } from "@opencode/core/config/plugin/policy"
1616
import { ConfigProviderPlugin } from "@opencode/core/config/plugin/provider"
1717
import { ConfigWebSearchPlugin } from "@opencode/core/config/plugin/websearch"
1818
import { Credential } from "@opencode/core/credential"
19+
import { InstructionDiscovery } from "@opencode/core/instruction-discovery"
1920
import { Integration } from "@opencode/core/integration"
2021
import { Model } from "@opencode/core/model"
2122
import { ModelResolver } from "@opencode/core/model-resolver"
@@ -358,9 +359,13 @@ describe("OpencodePlugin", () => {
358359
label: initial.label,
359360
}),
360361
).toEqual(stored.value)
361-
expect(requests).toEqual(["/auth/device/token", "/api/v2/config"])
362-
// The refresh and the config fetch both say which OpenCode is asking.
363-
expect(agents).toEqual(["opencode/beta/1.2.3/test", "opencode/beta/1.2.3/test"])
362+
expect(requests).toEqual([
363+
"/auth/device/token",
364+
"/api/v2/config",
365+
...(scenario.orgID === "org-missing" ? [] : ["/api/v2/instructions", "/api/v2/skills"]),
366+
])
367+
// The refresh and every Console fetch say which OpenCode is asking.
368+
expect(agents).toEqual(requests.map(() => "opencode/beta/1.2.3/test"))
364369
}).pipe(Effect.provideService(App.Metadata, App.make({ name: "test", version: "1.2.3", channel: "beta" }))),
365370
({ server }) => Effect.promise(() => server.stop(true)),
366371
),
@@ -410,6 +415,7 @@ describe("OpencodePlugin", () => {
410415
server: Bun.serve({
411416
port: 0,
412417
fetch: (request) => {
418+
if (new URL(request.url).pathname !== "/api/v2/config") return new Response(null, { status: 404 })
413419
authorization.push(request.headers.get("authorization"))
414420
requests.push(`${request.method} ${new URL(request.url).pathname}`)
415421
const origin = new URL(request.url).origin
@@ -695,7 +701,8 @@ describe("OpencodePlugin", () => {
695701
const state = { advertised: false, failing: false, requests: 0 }
696702
const server = Bun.serve({
697703
port: 0,
698-
fetch: () => {
704+
fetch: (request) => {
705+
if (new URL(request.url).pathname !== "/api/v2/config") return new Response(null, { status: 404 })
699706
state.requests++
700707
if (state.failing) return new Response("Unavailable", { status: 502 })
701708
return Response.json({
@@ -896,7 +903,8 @@ describe("OpencodePlugin", () => {
896903
const state = { sso: false, requests: 0 }
897904
const server = Bun.serve({
898905
port: 0,
899-
fetch: () => {
906+
fetch: (request) => {
907+
if (new URL(request.url).pathname !== "/api/v2/config") return new Response(null, { status: 404 })
900908
state.requests++
901909
if (state.sso)
902910
return Response.json(
@@ -1191,6 +1199,7 @@ describe("OpencodePlugin", () => {
11911199
port: 0,
11921200
fetch: async (request) => {
11931201
const path = new URL(request.url).pathname
1202+
if (path === "/api/v2/instructions" || path === "/api/v2/skills") return new Response(null, { status: 404 })
11941203
const body = request.method === "POST" ? await request.json() : undefined
11951204
requests.push({
11961205
method: request.method,
@@ -1385,6 +1394,8 @@ describe("OpencodePlugin", () => {
13851394
)
13861395
expect(requests).toEqual([
13871396
"https://opencode.ai/console/api/v2/config",
1397+
"https://opencode.ai/console/api/v2/instructions",
1398+
"https://opencode.ai/console/api/v2/skills",
13881399
"https://opencode.ai/console/api/websearch",
13891400
])
13901401
}),
@@ -1525,6 +1536,7 @@ describe("OpencodePlugin", () => {
15251536
if (url.pathname === "/api/v2/config") {
15261537
return Response.json({ providers: {}, websearch: { provider: "opencode" } })
15271538
}
1539+
if (url.pathname.startsWith("/api/v2/")) return new Response(null, { status: 404 })
15281540
return Response.redirect(`${url.origin}/loop`, 302)
15291541
},
15301542
})
@@ -1568,10 +1580,9 @@ describe("OpencodePlugin", () => {
15681580
authorization: request.headers.get("authorization"),
15691581
orgID: request.headers.get("x-org-id"),
15701582
})
1571-
if (url.pathname === "/api/v2/config") {
1572-
return Response.json({ providers: {}, library: { skills: [{ slug: "deploy", version: "1" }] } })
1573-
}
1574-
if (url.pathname === "/api/v2/library/skills/deploy") {
1583+
if (url.pathname === "/api/v2/config") return Response.json({ providers: {} })
1584+
if (url.pathname === "/api/v2/skills") return Response.json({ skills: [{ slug: "deploy", version: "1" }] })
1585+
if (url.pathname === "/api/v2/skills/deploy") {
15751586
// Skill archives come from presigned storage on its own host, where the signature covers the encoding.
15761587
const target = new URL("/archive/deploy.json?expires=1&sig=a%20b~c", url)
15771588
target.hostname = "127.0.0.1"
@@ -1598,7 +1609,7 @@ describe("OpencodePlugin", () => {
15981609

15991610
yield* eventually(skills.list(), (list) => list.some((skill) => skill.id === Skill.ID.make("deploy")))
16001611
expect(downloads).toContainEqual({
1601-
path: "/api/v2/library/skills/deploy",
1612+
path: "/api/v2/skills/deploy",
16021613
search: "",
16031614
authorization: "Bearer secret",
16041615
orgID: "org_test",
@@ -1614,6 +1625,47 @@ describe("OpencodePlugin", () => {
16141625
),
16151626
)
16161627

1628+
it.effect("keeps Console instructions and skills loaded when only the instructions change", () =>
1629+
Effect.gen(function* () {
1630+
const credentials = yield* Credential.Service
1631+
const discovery = yield* InstructionDiscovery.Service
1632+
const skills = yield* Skill.Service
1633+
const state = { instruction: "Use tabs." }
1634+
const server = {
1635+
fetch: (request: Request) => {
1636+
const path = new URL(request.url).pathname
1637+
if (path === "/api/v2/config") return Response.json({ providers: {} })
1638+
if (path === "/api/v2/instructions")
1639+
return Response.json({ instructions: [{ id: "style", content: state.instruction }] })
1640+
if (path === "/api/v2/skills") return Response.json({ skills: [{ slug: "deploy", version: "1" }] })
1641+
if (path === "/api/v2/skills/deploy") return Response.json(skillBundle)
1642+
return new Response(null, { status: 404 })
1643+
},
1644+
}
1645+
const loaded = Effect.all([discovery.list(), skills.get(Skill.ID.make("deploy"))]).pipe(
1646+
Effect.map(([files, skill]) => ({
1647+
instructions: Array.isArray(files)
1648+
? files.filter((file) => file.path.startsWith("OpenCode Console")).map((file) => file.content)
1649+
: [],
1650+
skill: skill?.description,
1651+
})),
1652+
)
1653+
yield* credentials.create({
1654+
integrationID: Integration.ID.make("opencode"),
1655+
value: Credential.Key.make({ type: "key", key: "secret", metadata: { server: "https://console.test" } }),
1656+
})
1657+
yield* addPlugin().pipe(inProcess(server))
1658+
yield* drain
1659+
expect(yield* loaded).toEqual({ instructions: ["Use tabs."], skill: "Deploys the service." })
1660+
1661+
// The config is unchanged, so config keeps the Console document it already holds.
1662+
state.instruction = "Use spaces."
1663+
yield* TestClock.adjust("1 minute")
1664+
yield* drain
1665+
expect(yield* loaded).toEqual({ instructions: ["Use spaces."], skill: "Deploys the service." })
1666+
}),
1667+
)
1668+
16171669
it.live("keeps credentials on a same-origin skill redirect", () =>
16181670
Effect.acquireUseRelease(
16191671
Effect.sync(() => {
@@ -1623,10 +1675,9 @@ describe("OpencodePlugin", () => {
16231675
fetch: (request) => {
16241676
const url = new URL(request.url)
16251677
downloads.push({ path: url.pathname, authorization: request.headers.get("authorization") })
1626-
if (url.pathname === "/api/v2/config") {
1627-
return Response.json({ providers: {}, library: { skills: [{ slug: "deploy", version: "1" }] } })
1628-
}
1629-
if (url.pathname === "/api/v2/library/skills/deploy")
1678+
if (url.pathname === "/api/v2/config") return Response.json({ providers: {} })
1679+
if (url.pathname === "/api/v2/skills") return Response.json({ skills: [{ slug: "deploy", version: "1" }] })
1680+
if (url.pathname === "/api/v2/skills/deploy")
16301681
return Response.redirect(`${url.origin}/assets/deploy.json`, 302)
16311682
return Response.json(skillBundle)
16321683
},

0 commit comments

Comments
 (0)