Skip to content

Commit 6c6ee89

Browse files
committed
fix(opencode2): support stable 2.0.x without ctx.catalog
Stable OpenCode 2.0 omits the unified catalog domain that the beta plugin required, so setup crashed on ctx.catalog.transform. Detect catalog when present (beta path unchanged) and otherwise sync discovered models into providers.cursor in OPENCODE_CONFIG_DIR so auth, aisdk hooks, and the model picker work on 2.0.5/2.0.6. Classic OC1 plugin entrypoints untouched.
1 parent 8255c94 commit 6c6ee89

6 files changed

Lines changed: 264 additions & 19 deletions

File tree

‎README.md‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,27 @@ Local clone equivalent: `"file:///absolute/path/to/cursor-opencode-provider/dist
128128

129129
That entry registers the provider via `ctx.aisdk.sdk` / `ctx.aisdk.language`. Keep the classic `plugin` entry for auth **and** plugin tools (notably `cursor_image_save` / `custom_websearch`): the 1.18 `/v2/promise` API has no `tool` domain, so a v2-only load silently disables Cursor image generation.
130130

131+
### OpenCode 2.0 stable (`2.0.5+`) — fork compat
132+
133+
Stable OpenCode 2.0 builds (e.g. `2.0.5` / `2.0.6`) expose `ctx.provider` /
134+
`ctx.model` but **not** `ctx.catalog`. This fork detects that and syncs
135+
discovered Cursor models into `providers.cursor` in
136+
`$OPENCODE_CONFIG_DIR/opencode.json(c)` so the picker still works, while
137+
keeping the beta `ctx.catalog.transform` path when catalog is present.
138+
139+
Load the OC2 entry via symlink (npm subpath resolution is unreliable on OC2):
140+
141+
```bash
142+
ln -sfn /path/to/cursor-opencode-provider/dist/plugin-opencode2.js \
143+
~/.config/opencode2/plugins/cursor.js
144+
# local aisdk build:
145+
export CURSOR_OPENCODE2_DEV_ENTRY=/path/to/cursor-opencode-provider/dist/index.js
146+
opencode2 service restart
147+
```
148+
149+
Classic OpenCode 1.x continues to use `"plugin": ["cursor-opencode-provider"]`
150+
(or `./plugin` / `./plugin/v2`) unchanged.
151+
131152
### OpenCode 2.0 beta (`opencode2`)
132153

133154
OpenCode 2.0 uses a different plugin API from the 1.18 `/v2/promise` one above — they

‎package.json‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,18 @@
11
{
22
"name": "cursor-opencode-provider",
3-
"version": "0.6.8",
3+
"version": "0.6.9",
44
"description": "Use Cursor subscription models from OpenCode via Cursor's Connect-RPC agent protocol",
55
"type": "module",
66
"license": "MIT",
77
"author": "oakimov",
88
"repository": {
99
"type": "git",
10-
"url": "git+https://github.com/oakimov/cursor-opencode-provider.git"
10+
"url": "git+https://github.com/ebysofyan/cursor-opencode-provider.git"
1111
},
1212
"bugs": {
13-
"url": "https://github.com/oakimov/cursor-opencode-provider/issues"
13+
"url": "https://github.com/ebysofyan/cursor-opencode-provider/issues"
1414
},
15-
"homepage": "https://github.com/oakimov/cursor-opencode-provider#readme",
15+
"homepage": "https://github.com/ebysofyan/cursor-opencode-provider#readme",
1616
"keywords": [
1717
"opencode",
1818
"opencode-plugin",

‎src/opencode2/config-catalog.ts‎

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
import { existsSync, readFileSync, writeFileSync } from "node:fs"
2+
import { homedir } from "node:os"
3+
import { join } from "node:path"
4+
import { CURSOR_PROVIDER_ID } from "../shared.js"
5+
import { CURSOR_WIRE_MODEL_ID_KEY, type ModelInfo } from "../models.js"
6+
import { modelsToConfig } from "../model-config.js"
7+
import { CURSOR_AISDK_PACKAGE, CURSOR_INTEGRATION_ID } from "./catalog.js"
8+
9+
/**
10+
* OpenCode 2.0.5 (stable) ships `ctx.provider` / `ctx.model` but **no**
11+
* `ctx.catalog`. Plugin transforms on those split domains do not flush into the
12+
* live model picker (draft mutations stay invisible to `list()`).
13+
*
14+
* Fallback: write discovered Cursor models into the user config document under
15+
* `providers.cursor` (OC2) or `provider.cursor` (legacy key), which 2.0.5 does
16+
* honor. Beta hosts with `ctx.catalog` never need this path.
17+
*/
18+
19+
export type ConfigCatalogSyncResult = {
20+
path: string
21+
modelCount: number
22+
changed: boolean
23+
}
24+
25+
function configDir(): string {
26+
return process.env.OPENCODE_CONFIG_DIR?.trim() || join(homedir(), ".config", "opencode")
27+
}
28+
29+
function resolveConfigPath(dir: string): string {
30+
const jsonc = join(dir, "opencode.jsonc")
31+
const json = join(dir, "opencode.json")
32+
if (existsSync(jsonc)) return jsonc
33+
if (existsSync(json)) return json
34+
return jsonc
35+
}
36+
37+
function stripJsonc(raw: string): string {
38+
// ponytail: cheap JSONC strip — enough for our generated/hand-edited configs.
39+
// Upgrade: real JSONC parser if users embed exotic comments inside strings.
40+
return raw
41+
.replace(/\/\*[\s\S]*?\*\//g, "")
42+
.replace(/^\s*\/\/.*$/gm, "")
43+
}
44+
45+
function modelsToProvidersEntry(models: ModelInfo[]): Record<string, unknown> {
46+
const config = modelsToConfig(models)
47+
const out: Record<string, unknown> = {}
48+
for (const [id, entry] of Object.entries(config)) {
49+
const options = (entry as any).options as Record<string, unknown> | undefined
50+
const wireId =
51+
typeof options?.[CURSOR_WIRE_MODEL_ID_KEY] === "string"
52+
? (options[CURSOR_WIRE_MODEL_ID_KEY] as string)
53+
: id
54+
const input = Array.isArray((entry as any).modalities?.input)
55+
? (entry as any).modalities.input.filter((m: unknown): m is string => typeof m === "string")
56+
: ["text"]
57+
const output = Array.isArray((entry as any).modalities?.output)
58+
? (entry as any).modalities.output.filter((m: unknown): m is string => typeof m === "string")
59+
: ["text"]
60+
out[id] = {
61+
name: (entry as any).name ?? id,
62+
modelID: wireId,
63+
capabilities: {
64+
tools: (entry as any).tool_call !== false,
65+
input,
66+
output,
67+
},
68+
limit: {
69+
context: (entry as any).limit?.context ?? 200_000,
70+
output: (entry as any).limit?.output ?? 8192,
71+
},
72+
status: "active",
73+
enabled: true,
74+
...(options ? { settings: { ...options } } : {}),
75+
}
76+
}
77+
return out
78+
}
79+
80+
/**
81+
* Upsert `providers.cursor` (preferred) with the AI SDK package + model map.
82+
* Returns whether the on-disk document changed.
83+
*/
84+
export function syncCursorProvidersConfig(models: ModelInfo[]): ConfigCatalogSyncResult {
85+
const dir = configDir()
86+
const path = resolveConfigPath(dir)
87+
let doc: Record<string, any> = {}
88+
if (existsSync(path)) {
89+
try {
90+
doc = JSON.parse(stripJsonc(readFileSync(path, "utf8")))
91+
} catch {
92+
doc = {}
93+
}
94+
}
95+
96+
const modelMap = modelsToProvidersEntry(models)
97+
const nextProvider = {
98+
name: "Cursor",
99+
package: CURSOR_AISDK_PACKAGE,
100+
integrationID: CURSOR_INTEGRATION_ID,
101+
models: modelMap,
102+
}
103+
104+
// Prefer OC2 `providers`; keep legacy `provider` in sync when already present.
105+
const prevProviders = doc.providers && typeof doc.providers === "object" ? doc.providers : {}
106+
const prevProvider = doc.provider && typeof doc.provider === "object" ? doc.provider : {}
107+
const prev = JSON.stringify(prevProviders[CURSOR_PROVIDER_ID] ?? prevProvider[CURSOR_PROVIDER_ID] ?? null)
108+
const next = JSON.stringify(nextProvider)
109+
if (prev === next) {
110+
return { path, modelCount: Object.keys(modelMap).length, changed: false }
111+
}
112+
113+
doc.providers = { ...prevProviders, [CURSOR_PROVIDER_ID]: nextProvider }
114+
if (doc.provider && typeof doc.provider === "object") {
115+
// Drop legacy npm-shaped block if we now own providers.cursor, to avoid
116+
// duplicate/conflicting Cursor entries.
117+
const { [CURSOR_PROVIDER_ID]: _drop, ...rest } = doc.provider as Record<string, unknown>
118+
doc.provider = rest
119+
if (Object.keys(doc.provider).length === 0) delete doc.provider
120+
}
121+
122+
writeFileSync(path, `${JSON.stringify(doc, null, 2)}\n`, "utf8")
123+
return { path, modelCount: Object.keys(modelMap).length, changed: true }
124+
}
125+
126+
export function hasCatalogDomain(ctx: { catalog?: { transform?: unknown; reload?: unknown } }): boolean {
127+
return typeof ctx.catalog?.transform === "function"
128+
}

‎src/opencode2/types.ts‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -325,12 +325,27 @@ export type PluginContext = {
325325
readonly app: App
326326
readonly options: Readonly<Record<string, any>>
327327
readonly aisdk: AISDKDomain
328-
readonly catalog: CatalogDomain
328+
/**
329+
* Present on OpenCode 2.0 beta builds that expose the unified catalog domain.
330+
* Stable 2.0.5 omits this — use config `providers.cursor` sync instead.
331+
*/
332+
readonly catalog?: CatalogDomain
329333
readonly event: EventDomain
330334
readonly integration: IntegrationDomain
331335
readonly session: SessionDomain
332336
readonly tool: ToolDomain
333-
readonly websearch: WebSearchDomain
337+
readonly websearch?: WebSearchDomain
338+
/** Split provider domain on stable 2.0.5 (transforms do not flush to picker). */
339+
readonly provider?: {
340+
readonly list: () => Promise<any> | any
341+
readonly reload?: () => Promise<void>
342+
readonly transform?: Transform<any>
343+
}
344+
readonly model?: {
345+
readonly list: () => Promise<any> | any
346+
readonly reload?: () => Promise<void>
347+
readonly transform?: Transform<any>
348+
}
334349
}
335350

336351
export type Cleanup = () => Promise<void> | void

‎src/plugin-opencode2.ts‎

Lines changed: 51 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import {
1919
sanitizeRegisteredCursorShellOutput,
2020
} from "./shell-timeout.js"
2121
import { applyCursorModels, applyCursorProvider } from "./opencode2/catalog.js"
22+
import { hasCatalogDomain, syncCursorProvidersConfig } from "./opencode2/config-catalog.js"
2223
import { applyCursorIntegration, resolveCursorAccessToken } from "./opencode2/integration.js"
2324
import { markCompactionSession } from "./compaction-marker.js"
2425
import { markSessionDirectory } from "./session-directory.js"
@@ -27,14 +28,21 @@ import type { CreateCursorOptions } from "./index.js"
2728
import type { Cleanup, PluginContext, Plugin2 } from "./opencode2/types.js"
2829

2930
/**
30-
* OpenCode 2.0 beta plugin.
31+
* OpenCode 2.0 plugin (beta catalog API + stable 2.0.5 compat).
3132
*
3233
* Separate from `plugin-v2.ts` on purpose: the OpenCode 1.18 `/v2/promise` API
3334
* and the 2.0 API are source-incompatible (hook signatures, OAuth value type,
3435
* provider schema), so they cannot share an entrypoint. Shared behavior lives in
3536
* `plugin-core.ts`, `model-config.ts`, and `opencode2/*`.
3637
*
38+
* Host matrix:
39+
* - OC2 **beta** with `ctx.catalog` → register provider/models via catalog.transform
40+
* - OC2 **stable 2.0.5** (no catalog) → auth + aisdk hooks still run; models are
41+
* synced into user config `providers.cursor` (see `config-catalog.ts`)
42+
* - OC1 → use classic `./plugin` or `./plugin/v2`, not this entry
43+
*
3744
* Load with: { "plugins": ["cursor-opencode-provider/plugin/opencode2"] }
45+
* or symlink `dist/plugin-opencode2.js` into `~/.config/opencode2/plugins/`.
3846
*/
3947

4048
async function loadModels(cacheDir: string, accessToken: string | undefined): Promise<ModelInfo[]> {
@@ -76,6 +84,7 @@ const plugin: Plugin2 = {
7684
}
7785

7886
let models: ModelInfo[] = []
87+
const useCatalog = hasCatalogDomain(ctx)
7988

8089
// ── Credentials ──────────────────────────────────────────────────────────
8190
await track(ctx.integration.transform(applyCursorIntegration))
@@ -100,15 +109,46 @@ const plugin: Plugin2 = {
100109
return token
101110
}
102111

103-
// ── Catalog ──────────────────────────────────────────────────────────────
104-
// Runs now with whatever models we have (likely none) and is replayed by the
105-
// host on every `catalog.reload()`, so the async fill below just re-triggers it.
106-
await track(
107-
ctx.catalog.transform((draft) => {
108-
applyCursorProvider(draft)
109-
applyCursorModels(draft, models)
110-
}),
111-
)
112+
// ── Catalog (beta) or config providers sync (stable 2.0.5) ───────────────
113+
// Beta: transform replays on catalog.reload().
114+
// Stable: no ctx.catalog — persist providers.cursor into OPENCODE_CONFIG_DIR.
115+
if (useCatalog && ctx.catalog) {
116+
await track(
117+
ctx.catalog.transform((draft) => {
118+
applyCursorProvider(draft)
119+
applyCursorModels(draft, models)
120+
}),
121+
)
122+
} else {
123+
// Seed from disk cache so picker is non-empty before /connect on repeat runs.
124+
// Do not write an empty providers.cursor block (would clobber a good config).
125+
try {
126+
const cached = await readCache(cacheDir)
127+
if (cached?.models?.length) {
128+
models = cached.models
129+
syncCursorProvidersConfig(models)
130+
}
131+
} catch {
132+
// Config write is best-effort; auth/aisdk still work without it.
133+
}
134+
}
135+
136+
const publishModels = async (next: ModelInfo[]): Promise<void> => {
137+
models = next
138+
if (useCatalog && ctx.catalog) {
139+
await ctx.catalog.reload().catch(() => {})
140+
return
141+
}
142+
try {
143+
const synced = syncCursorProvidersConfig(next)
144+
if (synced.changed) {
145+
await ctx.provider?.reload?.().catch(() => {})
146+
await ctx.model?.reload?.().catch(() => {})
147+
}
148+
} catch {
149+
// ignore — picker may need a service restart to pick up config
150+
}
151+
}
112152

113153
// ── AI SDK wiring ────────────────────────────────────────────────────────
114154
await track(
@@ -290,10 +330,8 @@ const plugin: Plugin2 = {
290330
const token = await accessToken()
291331
const discovered = await loadModels(cacheDir, token)
292332
if (!discovered.length) return
293-
models = discovered
294333
modelsLoaded = true
295-
// Replays the catalog transform above, this time with models.
296-
await ctx.catalog.reload().catch(() => {})
334+
await publishModels(discovered)
297335
if (token) {
298336
// Resolve the region-specific Run origin so the first turn doesn't
299337
// pay for GetServerConfig. Best effort: startSession surfaces real

‎test/config-catalog.test.ts‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import { describe, expect, test } from "bun:test"
2+
import { mkdtempSync, readFileSync, writeFileSync, rmSync } from "node:fs"
3+
import { tmpdir } from "node:os"
4+
import { join } from "node:path"
5+
import { syncCursorProvidersConfig } from "../src/opencode2/config-catalog.js"
6+
import type { ModelInfo } from "../src/models.js"
7+
8+
describe("syncCursorProvidersConfig", () => {
9+
test("writes providers.cursor for stable OC2 hosts", () => {
10+
const dir = mkdtempSync(join(tmpdir(), "cursor-oc2-cfg-"))
11+
const prev = process.env.OPENCODE_CONFIG_DIR
12+
process.env.OPENCODE_CONFIG_DIR = dir
13+
try {
14+
writeFileSync(
15+
join(dir, "opencode.jsonc"),
16+
JSON.stringify({ model: "openai/gpt-5.6-luna", plugin: ["oh-my-opencode-slim"] }, null, 2),
17+
)
18+
const models: ModelInfo[] = [
19+
{
20+
id: "composer-2.5",
21+
displayName: "Composer 2.5",
22+
supportsAgent: true,
23+
supportsImages: false,
24+
variants: [],
25+
},
26+
]
27+
const result = syncCursorProvidersConfig(models)
28+
expect(result.changed).toBe(true)
29+
expect(result.modelCount).toBeGreaterThan(0)
30+
const doc = JSON.parse(readFileSync(join(dir, "opencode.jsonc"), "utf8"))
31+
expect(doc.providers.cursor.package).toContain("aisdk:")
32+
expect(doc.providers.cursor.models["composer-2.5"]).toBeTruthy()
33+
expect(doc.providers.cursor.integrationID).toBe("cursor")
34+
35+
const again = syncCursorProvidersConfig(models)
36+
expect(again.changed).toBe(false)
37+
} finally {
38+
if (prev === undefined) delete process.env.OPENCODE_CONFIG_DIR
39+
else process.env.OPENCODE_CONFIG_DIR = prev
40+
rmSync(dir, { recursive: true, force: true })
41+
}
42+
})
43+
})

0 commit comments

Comments
 (0)