cursor-opencode-provider 0.2.9 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +139 -10
  2. package/dist/agent-url.js +2 -0
  3. package/dist/auth.d.ts +7 -0
  4. package/dist/auth.js +9 -0
  5. package/dist/compaction-marker.d.ts +14 -0
  6. package/dist/compaction-marker.js +36 -0
  7. package/dist/context/env.js +6 -2
  8. package/dist/context/paths.js +3 -2
  9. package/dist/index.d.ts +1 -3
  10. package/dist/index.js +2 -8
  11. package/dist/language-model.js +51 -35
  12. package/dist/model-config.d.ts +15 -0
  13. package/dist/model-config.js +206 -0
  14. package/dist/opencode2/catalog.d.ts +33 -0
  15. package/dist/opencode2/catalog.js +85 -0
  16. package/dist/opencode2/integration.d.ts +23 -0
  17. package/dist/opencode2/integration.js +124 -0
  18. package/dist/opencode2/types.d.ts +316 -0
  19. package/dist/opencode2/types.js +18 -0
  20. package/dist/plugin-core.d.ts +27 -0
  21. package/dist/plugin-core.js +31 -0
  22. package/dist/plugin-opencode2.d.ts +3 -0
  23. package/dist/plugin-opencode2.js +293 -0
  24. package/dist/plugin-v2.d.ts +7 -0
  25. package/dist/plugin-v2.js +1 -15
  26. package/dist/plugin.d.ts +1 -15
  27. package/dist/plugin.js +11 -191
  28. package/dist/protocol/apply-patch.d.ts +109 -0
  29. package/dist/protocol/apply-patch.js +163 -0
  30. package/dist/protocol/messages.d.ts +10 -0
  31. package/dist/protocol/messages.js +83 -1
  32. package/dist/protocol/tools.d.ts +24 -1
  33. package/dist/protocol/tools.js +262 -19
  34. package/dist/session-directory.d.ts +17 -0
  35. package/dist/session-directory.js +35 -0
  36. package/dist/session.d.ts +13 -1
  37. package/dist/session.js +70 -1
  38. package/dist/shell-timeout.d.ts +3 -1
  39. package/dist/shell-timeout.js +12 -4
  40. package/dist/usage.d.ts +30 -0
  41. package/dist/usage.js +77 -0
  42. package/dist/web-search-tool.d.ts +33 -0
  43. package/dist/web-search-tool.js +22 -0
  44. package/dist/web-tools.d.ts +9 -25
  45. package/dist/web-tools.js +34 -36
  46. package/package.json +14 -9
package/README.md CHANGED
@@ -29,9 +29,9 @@ OpenCode driving a Cursor-routed Grok model through this provider:
29
29
 
30
30
  ## Installation
31
31
 
32
- ### From npm (after publish)
32
+ ### From npm
33
33
 
34
- Add the package name to OpenCode config. OpenCode installs npm plugins with Bun at startup (cached under `~/.cache/opencode/node_modules/`):
34
+ Add the package to OpenCode config. OpenCode installs npm plugins with Bun at startup (cached under `~/.cache/opencode/node_modules/`):
35
35
 
36
36
  ```json
37
37
  {
@@ -47,7 +47,14 @@ Add the package name to OpenCode config. OpenCode installs npm plugins with Bun
47
47
  }
48
48
  ```
49
49
 
50
- Pin a version if you want: `"cursor-opencode-provider@0.2.9"`.
50
+ Pin a version if you want: `"cursor-opencode-provider@0.3.1"`.
51
+
52
+ You can also install it yourself first:
53
+
54
+ ```bash
55
+ npm install cursor-opencode-provider
56
+ # or: bun add cursor-opencode-provider
57
+ ```
51
58
 
52
59
  ### From a local clone
53
60
 
@@ -58,7 +65,7 @@ bun install
58
65
  bun run build
59
66
  ```
60
67
 
61
- Point config at the built files with absolute `file://` URLs:
68
+ Point classic OpenCode config at the built files with absolute `file://` URLs:
62
69
 
63
70
  ```json
64
71
  {
@@ -73,6 +80,8 @@ Point config at the built files with absolute `file://` URLs:
73
80
  }
74
81
  ```
75
82
 
83
+ For **OpenCode 2.0** local development, prefer the plugin path plus `CURSOR_OPENCODE2_DEV_ENTRY` — see [OpenCode 2.0 beta](#opencode-20-beta-opencode2).
84
+
76
85
  ## OpenCode setup
77
86
 
78
87
  If the `cursor` provider block is omitted, the classic plugin auto-registers it on startup (as **Cursor Integration**) using this package's entry. Model entries come from the local cache, which is filled after auth and again on startup when the cache is empty but credentials remain.
@@ -89,6 +98,108 @@ Local clone equivalent: `"file:///absolute/path/to/cursor-opencode-provider/dist
89
98
 
90
99
  That entry registers the provider via `ctx.aisdk.sdk` / `ctx.aisdk.language`. Keep the classic `plugin` entry for auth.
91
100
 
101
+ ### OpenCode 2.0 beta (`opencode2`)
102
+
103
+ OpenCode 2.0 uses a different plugin API from the 1.18 `/v2/promise` one above — they
104
+ are source-incompatible, so this package ships a **separate** entrypoint for it.
105
+ Everything is registered by that one plugin. You do **not** need a `providers` entry,
106
+ and there is no `enabled` flag. Do not also load `./plugin/v2` or the classic `plugin`
107
+ entry under `opencode2`; they target the older APIs.
108
+
109
+ Authenticate with `/connect` inside `opencode2`, choose **Cursor**, then either
110
+ browser login or an API key. `CURSOR_API_KEY` is also picked up automatically.
111
+
112
+ #### From npm
113
+
114
+ ```json
115
+ {
116
+ "plugins": ["cursor-opencode-provider/plugin/opencode2"]
117
+ }
118
+ ```
119
+
120
+ Pin a version if you want: `"cursor-opencode-provider@0.3.1/plugin/opencode2"`.
121
+
122
+ OpenCode 2.0 installs the published package into its host cache and loads the AI SDK
123
+ entry from there (`aisdk:cursor-opencode-provider`). No extra env vars are required.
124
+
125
+ #### From a local clone (`CURSOR_OPENCODE2_DEV_ENTRY`)
126
+
127
+ Loading only the local plugin file is not enough for end-to-end local testing: OpenCode
128
+ 2.0's catalog still resolves the AI SDK package through `npm install` into
129
+ `<host-cache>/packages/…` unless you override it. Point
130
+ `CURSOR_OPENCODE2_DEV_ENTRY` at the built provider entry (`dist/index.js`, which exports
131
+ `createCursor`) so the host imports that file directly.
132
+
133
+ ```bash
134
+ cd /absolute/path/to/cursor-opencode-provider
135
+ bun install && bun run build
136
+
137
+ export CURSOR_OPENCODE2_DEV_ENTRY=/absolute/path/to/cursor-opencode-provider/dist/index.js
138
+ # optional while debugging:
139
+ # export CURSOR_PROVIDER_DEBUG=1
140
+ ```
141
+
142
+ Example OpenCode 2.0 config (for example `~/.config/opencode/opencode.json` or a
143
+ project `opencode.json`) that loads the built local plugin:
144
+
145
+ ```json
146
+ {
147
+ "plugins": [
148
+ "/absolute/path/to/cursor-opencode-provider/dist/plugin-opencode2.js"
149
+ ]
150
+ }
151
+ ```
152
+
153
+ Equivalent forms for the same plugin entry:
154
+
155
+ - `"file:///absolute/path/to/cursor-opencode-provider/dist/plugin-opencode2.js"`
156
+ - `"../cursor-opencode-provider/dist/plugin-opencode2.js"` (relative to the config file; must start with `./` or `../`)
157
+
158
+ You can also drop a symlink into `.opencode/plugins/` (or `~/.config/opencode/plugins/`),
159
+ which OpenCode scans automatically:
160
+
161
+ ```bash
162
+ mkdir -p .opencode/plugins
163
+ ln -s /absolute/path/to/cursor-opencode-provider/dist/plugin-opencode2.js \
164
+ .opencode/plugins/cursor.js
165
+ ```
166
+
167
+ Important for local 2.0 development:
168
+
169
+ - **Export the env var before starting the daemon.** `opencode2 serve --service` inherits
170
+ env only at start time. After changing `CURSOR_OPENCODE2_DEV_ENTRY` or rebuilding
171
+ `dist/`, restart the service:
172
+
173
+ ```bash
174
+ opencode2 service stop
175
+ export CURSOR_OPENCODE2_DEV_ENTRY=/absolute/path/to/cursor-opencode-provider/dist/index.js
176
+ opencode2 service start
177
+ ```
178
+
179
+ `opencode2 service set` does **not** accept arbitrary env var names.
180
+ - **Unset `CURSOR_OPENCODE2_DEV_ENTRY` in production** so the catalog uses the published
181
+ `aisdk:cursor-opencode-provider` package again.
182
+ - **OpenCode does not install dependencies for local plugin files.** Keep the clone's
183
+ `bun install` intact and load the plugin from inside the clone (a copied-out file will
184
+ not resolve `protobufjs`).
185
+ - **Rebuild after every change** (`bun run build`). The daemon reads `dist/`, not `src/`.
186
+
187
+ Feature parity with the classic plugin, and the two places 2.0 differs:
188
+
189
+ | Classic plugin | OpenCode 2.0 plugin |
190
+ |---|---|
191
+ | `config` hook registers provider + models | `ctx.catalog.transform` |
192
+ | `auth` hook (OAuth + API key) | `ctx.integration.transform` + `/connect` |
193
+ | `tool` hook (`custom_websearch`) | `ctx.tool.transform` |
194
+ | `event` hook (session activity) | `ctx.event.subscribe` |
195
+ | `tool.execute.before` / `.after` | `ctx.tool.hook(...)` |
196
+ | `shell.env` injects the timeout wrapper | **No `shell.env` in 2.0** — the bash command is rewritten to call the wrapper file instead (same behavior, different mechanism) |
197
+ | `chat.params` flags compaction turns | **No `chat.params` in 2.0** — the compaction agent is detected in `ctx.session.hook("context")` and correlated by session id |
198
+
199
+ > **Beta.** OpenCode 2.0 and its plugin API are both beta and still changing. This
200
+ > entrypoint is built against `@opencode-ai/plugin@next` (`0.0.0-next-16281`) and is
201
+ > guarded by a compile-time conformance check, but expect churn.
202
+
92
203
  ### Authenticate
93
204
 
94
205
  ```bash
@@ -100,7 +211,7 @@ Choose the **cursor** provider, then one of:
100
211
  | Method | Description |
101
212
  |--------|-------------|
102
213
  | **Cursor account (browser login)** | PKCE OAuth — opens cursor.com to sign in |
103
- | **API key** | Paste a key from [cursor.com/settings](https://cursor.com/settings) (`sk-...`) |
214
+ | **API key** | Paste a key from [cursor.com/settings](https://cursor.com/settings) (`crsr_...`) |
104
215
 
105
216
  After login, the plugin fetches your available models and writes them to `<host-cache>/cursor-models.json` (default `~/.cache/opencode/`). On later startups, a missing, empty, expired, or old-schema cache is refreshed during config load when Cursor auth is available; an existing stale cache remains usable if refresh fails.
106
217
 
@@ -177,7 +288,7 @@ const model = cursor.languageModel("composer-2.5")
177
288
  // model implements AI SDK LanguageModelV3 (doStream / doGenerate)
178
289
  ```
179
290
 
180
- Pass either `accessToken` (JWT from OAuth or key exchange) or `apiKey` (raw `sk-...` key). Optional: `apiBaseURL`, `agentBaseURL`, `cacheDir`, `headers`, `telemetryEnabled`, `retry`, and `continuation`. `cacheDir` pins the host cache root for model/version caches and Cursor project metadata; when omitted, the provider uses OCP `@opencode-compat/profile` detect (if installed) or the local MiMo/Kilo/OpenCode heuristic described in [Paths](#paths-host-cache). Transient failures resume from the latest checkpoint produced by that Run, matching Cursor CLI; without an eligible checkpoint, retries remain limited to replay-safe attempts so completed text or tool work is not duplicated. Pending-tool inactivity is renewed by OpenCode activity from the session or its descendants. The older `baseURL` option is still accepted as a legacy alias for `agentBaseURL`.
291
+ Pass either `accessToken` (JWT from OAuth or key exchange) or `apiKey` (raw `crsr_...` key). Optional: `apiBaseURL`, `agentBaseURL`, `cacheDir`, `headers`, `telemetryEnabled`, `retry`, and `continuation`. `cacheDir` pins the host cache root for model/version caches and Cursor project metadata; when omitted, the provider uses OCP `@opencode-compat/profile` detect (if installed) or the local MiMo/Kilo/OpenCode heuristic described in [Paths](#paths-host-cache). Transient failures resume from the latest checkpoint produced by that Run, matching Cursor CLI; without an eligible checkpoint, retries remain limited to replay-safe attempts so completed text or tool work is not duplicated. Pending-tool inactivity is renewed by OpenCode activity from the session or its descendants. The older `baseURL` option is still accepted as a legacy alias for `agentBaseURL`.
181
292
 
182
293
  ## Environment variables
183
294
 
@@ -188,6 +299,7 @@ Pass either `accessToken` (JWT from OAuth or key exchange) or `apiKey` (raw `sk-
188
299
  | `CURSOR_GET_SERVER_CONFIG_TELEMETRY` | Set to `1` or `true` to opt the `GetServerConfig` lookup into telemetry in OpenCode/plugin usage |
189
300
  | `CURSOR_PROVIDER_DEBUG` | Set to `1` or `true` to enable wire-level debug logging |
190
301
  | `CURSOR_PROVIDER_DEBUG_FILE` | Debug log path (default: `debug-<pid>.log` under `$TMPDIR/cursor-provider-logs-<uid>/`) |
302
+ | `CURSOR_OPENCODE2_DEV_ENTRY` | **Local OpenCode 2.0 only.** Absolute path to a built entry file (usually `dist/index.js`). Rewrites the catalog's AI SDK package to `aisdk:file://…` so the daemon imports your local build instead of `npm install`-ing the published package. Export it **before** `opencode2 service start`, then restart after rebuilds. Unset in production. |
191
303
  | `XDG_CACHE_HOME` | Base for host cache dirs (`$XDG_CACHE_HOME/opencode/`, `…/mimocode/`, or `…/kilo/`) when no explicit `cacheDir` / OCP detect override |
192
304
  | `MIMOCODE_HOME` | When set, host cache is `$MIMOCODE_HOME/cache` (MiMo) |
193
305
  | `KILO_CONFIG_DIR` | When set, host cache is `$XDG_CACHE_HOME/kilo` |
@@ -220,7 +332,11 @@ OpenCode
220
332
  | Module | Role |
221
333
  |--------|------|
222
334
  | `src/plugin.ts` | Classic OpenCode hooks: provider registration, OAuth, API key exchange, token refresh |
223
- | `src/plugin-v2.ts` | OpenCode Effect/Promise v2 plugin (`ctx.aisdk.*`); load via `./plugin/v2` only |
335
+ | `src/plugin-v2.ts` | OpenCode 1.18 Effect/Promise v2 plugin (`ctx.aisdk.*`); load via `./plugin/v2` only |
336
+ | `src/plugin-opencode2.ts` | OpenCode 2.0 beta plugin (catalog, integration, tools, aisdk); load via `./plugin/opencode2` only |
337
+ | `src/opencode2/` | 2.0-only catalog mapping, integration/auth, and local API types |
338
+ | `src/plugin-core.ts` | Host-neutral SDK factory, package matching, API base/telemetry resolution |
339
+ | `src/model-config.ts` | Cursor model → OpenCode model mapping shared by every plugin surface |
224
340
  | `src/index.ts` | `createCursor` factory; default export is `CursorPlugin` |
225
341
  | `src/language-model.ts` | AI SDK `LanguageModelV3` adapter (`doStream`, `doGenerate`) |
226
342
  | `src/session.ts` | Held-open agent Run session and pending exec correlation |
@@ -234,10 +350,18 @@ OpenCode
234
350
 
235
351
  ### Injected system guidance
236
352
 
237
- The provider adds OpenCode-specific system guidance to normal tool-capable conversations, including tool availability, canonical workspace-path grounding, and preferring `edit` / `write` over shell-based file mutation when those tools are available. Compaction keeps its dedicated prompt unchanged.
353
+ The provider adds OpenCode-specific system guidance to normal tool-capable conversations, including tool availability, canonical workspace-path grounding, and preferring `edit` / `write` (or `apply_patch`, when the host advertises that instead) over shell-based file mutation when those tools are available. Compaction keeps its dedicated prompt unchanged.
238
354
 
239
355
  If this guidance causes issues, update `buildOpenCodeInteractionGuidance` in [`src/language-model.ts`](src/language-model.ts) and its focused coverage in [`test/prompt-history.test.ts`](test/prompt-history.test.ts).
240
356
 
357
+ ### `apply_patch` models (GPT-5 and friends)
358
+
359
+ OpenCode 1.x does not simply add `apply_patch` for GPT-series models — it **removes** `edit` and `write` from the tool catalog and advertises `apply_patch` in their place (`ToolRegistry.tools`; the model id must contain `gpt-` and neither `oss` nor `gpt-4`). Cursor keeps sending its native write/edit requests regardless, so without translation every file change on a `gpt-5*` model is refused as an unavailable tool.
360
+
361
+ The provider translates transparently: a native write becomes an `*** Add File:` patch, and a Pi edit becomes a minimal `*** Update File:` chunk widened to whole lines. This is keyed purely off what the host advertises — it is inert whenever `edit`/`write` are offered normally, and inert again when the host offers neither those nor `apply_patch`. An edit that cannot be expressed faithfully (target unreadable, or the text to replace is absent or ambiguous) is refused with a specific message rather than applied to the wrong region.
362
+
363
+ OpenCode 2.0 does not perform this substitution, so the path is 1.x-only in practice. See [`src/protocol/apply-patch.ts`](src/protocol/apply-patch.ts) for the upstream references.
364
+
241
365
  ### Native subagent routing
242
366
 
243
367
  The provider reads the permission-filtered subagent catalog from the current host `task` or `actor` definition and advertises those recipients to Cursor as custom subagents. Exact configured names are preserved; unknown future Cursor subtype strings fall back to `general`. If a complete catalog omits every compatible recipient, the request fails on Cursor's typed subagent channel instead of selecting an arbitrary specialist.
@@ -256,7 +380,8 @@ Kilo `scout` is reserved for external documentation, dependency repositories, an
256
380
  |-------------|--------|
257
381
  | `cursor-opencode-provider` | `createCursor`, `CursorPlugin` (named + default) |
258
382
  | `cursor-opencode-provider/plugin` | `CursorPlugin` (classic Hooks — auth) |
259
- | `cursor-opencode-provider/plugin/v2` | OpenCode Effect/Promise v2 plugin (`ctx.aisdk.*`) |
383
+ | `cursor-opencode-provider/plugin/v2` | OpenCode 1.18 Effect/Promise v2 plugin (`ctx.aisdk.*`) |
384
+ | `cursor-opencode-provider/plugin/opencode2` | OpenCode 2.0 beta plugin (self-registering: catalog + auth + tools) |
260
385
  | `cursor-opencode-provider/errors` | Structured provider error classes |
261
386
 
262
387
  The package root intentionally stays plugin-safe for OpenCode's classic loader. `CursorPluginV2` and non-plugin runtime APIs are **not** re-exported from the package root; load them through their dedicated subpaths.
@@ -265,8 +390,9 @@ The package root intentionally stays plugin-safe for OpenCode's classic loader.
265
390
 
266
391
  | Problem | What to try |
267
392
  |---------|-------------|
268
- | No Cursor models in the picker | Confirm Cursor auth (`opencode auth login` → **cursor**). Restart OpenCode — if auth is present and the cache is empty, models are fetched on startup. Confirm `provider.cursor.npm` is the package name (or a built `file://…/dist/index.js`). |
393
+ | No Cursor models in the picker | Confirm Cursor auth (`opencode auth login` → **cursor**, or `/connect` in `opencode2`). Restart OpenCode — if auth is present and the cache is empty, models are fetched on startup. Confirm `provider.cursor.npm` is the package name (or a built `file://…/dist/index.js`). |
269
394
  | Auth / 401 errors mid-session | Re-login. OAuth and exchanged API-key JWTs refresh automatically when near expiry; a revoked refresh token needs a fresh login. |
395
+ | Local OpenCode 2.0 still runs the published package | Set `CURSOR_OPENCODE2_DEV_ENTRY` to an absolute `…/dist/index.js` path **before** starting the daemon, rebuild (`bun run build`), then `opencode2 service stop && opencode2 service start`. Loading only `dist/plugin-opencode2.js` is not enough — without the env var, 2.0 still `npm install`s the published package into the host cache. |
270
396
  | “Too many connections from different devices” | Device IDs are derived from stable OS identifiers (same approach as the Cursor CLI). Avoid running multiple clients that invent different machine fingerprints for the same account. |
271
397
  | Empty or stale model list | Delete `<host-cache>/cursor-models.json` (default `~/.cache/opencode/`, or MiMo/Kilo host cache) and restart OpenCode. Existing Cursor auth is enough to refill the cache; re-login only if auth itself is broken. Cache TTL is 24h; a failed background refresh keeps serving the previous cache. |
272
398
  | Stream hangs or HTTP/2 errors | The provider keeps Cursor's Run open across OpenCode tool calls, rotates aged shared connections, resumes transient interruptions from the latest eligible Cursor checkpoint, and falls back to a fresh-history rebase only before stateful output when no checkpoint exists. Repeated interruption is surfaced as an error instead of a false successful stop; retry the turn after checking connectivity. With debug logging enabled, look for `Run interrupted`, `resuming … checkpoint`, or `rebasing fresh Run`. Restart OpenCode after rebuilding a local `file://` install. |
@@ -274,6 +400,7 @@ The package root intentionally stays plugin-safe for OpenCode's classic loader.
274
400
  | Visible `<shell_metadata>` timeout text | Rebuild and restart a local install. Cursor's shell timeout is carried on its exec request; the provider now removes OpenCode's internal timeout envelope before it is rendered or stored, then returns Cursor's typed timeout or background-handoff event instead of treating the text as successful stdout. |
275
401
  | `Unsupported Cursor exec variant …` | The error names the canonical Cursor CLI request field, its expected result field, and this provider's handling classification. `handling=unsupported` is a known Cursor-native capability without a safe OpenCode AI SDK bridge; `unknown request field` indicates new protocol drift; `handling=opencode-tool` or `provider-control` indicates a provider decoder/dispatch regression. Enable the debug log and report the full named error. |
276
402
  | Need wire-level logs | Set `CURSOR_PROVIDER_DEBUG=1` (optional `CURSOR_PROVIDER_DEBUG_FILE`; the default is `debug-<pid>.log` under `$TMPDIR/cursor-provider-logs-<uid>/`) and reproduce the issue. |
403
+ | Cache **write** tokens always show as `0` | Not a mapping bug in this provider. Cursor's `TurnEnded` protobuf includes `cache_write` (field 4) and this package forwards it as AI SDK `inputTokens.cacheWrite` / OpenCode `cache.write`. Real agent sessions send field 4 as `0` even when `cache_read` is large on later turns. With debug logging, confirm `turn_ended raw wire fields: … f4:wt0=0` and `v3CacheWrite=0 source=turn_ended`. Cache **read** counts from the same message do populate correctly. |
277
404
 
278
405
  ## Security
279
406
 
@@ -282,6 +409,7 @@ Project `instructions` may reference absolute or `~/` paths (OpenCode parity). S
282
409
  ## Known limitations
283
410
 
284
411
  - **Personal use / ToS** — this provider speaks Cursor’s private agent protocol (CLI-shaped client identity). Use only with an account you own; Cursor may change or restrict the API without notice.
412
+ - **`TurnEnded.cache_write` is unused by Cursor's agent** — usage comes from `interaction_update.turn_ended` (`input_tokens`, `output_tokens`, `cache_read`, `cache_write`, `reasoning_tokens`). The provider maps those 1:1 into AI SDK V3 nested usage. Captured live Runs consistently set `cache_write=0` on the wire while still reporting non-zero `cache_read` and `reasoning_tokens`; there is no alternate agent-stream field today that supplies write counts, so OpenCode/Kilo cannot show cache-write tokens for this provider until Cursor populates that counter.
285
413
  - **`request_context` from OpenCode** — each Run sends Cursor `RequestContext` built from OpenCode project context (workspace env, `AGENTS.md` / `instructions`, `.opencode` agents/skills/plugins, git, layout, plus `.claude`/`.agents` skill fallbacks). Its canonical root is also used by the [injected system guidance](#injected-system-guidance). Same discovery as OpenCode — including `.cursor/` paths only when listed in `instructions`. Cursor-only cloud/sandbox marketplace surfaces are omitted. `env.workspace_paths` / `process_working_directory` stay on the real git workspace; Cursor's metadata root (`project_folder`, MCP `workspace_project_dir`, terminals/transcripts) is advertised under `<host-cache>/projects/<slug>/` (default `~/.cache/opencode/projects/…`) so dumps like `agent-tools/` do not land in the repo. OpenCode remains the permission authority: its coarse allow/ask/deny configuration is not fabricated into Cursor's unrelated allow/block instruction-list messages.
286
414
  - **Configured MCP tools keep their upstream server id** — OpenCode builtins and plugin/custom tools are advertised under a synthetic `opencode` MCP server. Tools whose flattened name matches an MCP server in merged `opencode.json` configuration (`github_create_pull_request`, …) are grouped into that server's `mcp_descriptors` / `provider_identifier` (`github`, …). Unknown underscore-containing names stay under `opencode` rather than being guessed incorrectly. Cursor's MCP-state exec probe is answered from the same advertised descriptors before the actual tool request, using the full canonical tool-definition identity required by native `get_mcp_tools`; exec still reconstructs the full OpenCode tool id.
287
415
  - **Display completions are notifications, not execution requests** — Cursor `tool_call_*` frames use a typed `ToolCall` oneof. The provider decodes them for diagnostics but only mirrors finalized todo/plan state (`update_todos_tool_call` / `create_plan_tool_call`) into advertised OpenCode `todowrite`; the completed payload already contains the authoritative final list. Interactive, data-returning, and side-effecting completions are never replayed as new tools because their result could not be returned to Cursor. Exec-backed native subagent/Task and Pi read/bash/edit/write/grep/find/ls calls use their typed request/result fields instead. Unknown display variants are logged. All 37 Cursor CLI exec request/result pairs are inventoried by field and name; known-but-unsupported and future unknown exec variants fail explicitly rather than receiving a guessed response that could deadlock the Run.
@@ -292,6 +420,7 @@ Project `instructions` may reference absolute or `~/` paths (OpenCode parity). S
292
420
  - **Compaction resets Cursor conversation state** — the classic plugin marks OpenCode's `compaction` agent explicitly. On those turns the provider mints an isolated Cursor `conversation_id`, drops the prior checkpoint + KV blobs, preserves real tool outputs as OpenCode-host observations in the seed history, and re-advertises the session's last tool catalog while refusing execution during the summary itself. The first normal turn then rebases once more onto a fresh conversation seeded with OpenCode's compacted prompt and normal system instructions, so the summary-agent checkpoint cannot suppress later tool calls. Ordinary no-tool / `toolChoice:none` calls do not reset conversation state.
293
421
  - **Conversation bindings and compaction catalogs are bounded** — process-global per-session bindings, prior tool catalogs, and pending post-compaction rebases use a 256-session LRU bound. Evicting a conversation binding also drops its checkpoint and KV blobs.
294
422
  - **Interrupted Runs resume from checkpoints** — a remote EOF, Connect end-stream, or trailer error is never emitted as a successful `stop`. When the failed Run produced an eligible checkpoint, the provider opens a new RPC for the same conversation and sends that state with `ResumeAction`, so completed text and tool work are not replayed. Before any stateful output, an interruption without a checkpoint can still rebase from OpenCode history. Stateful interruptions without a checkpoint are surfaced because replay would be ambiguous; retry exhaustion remains explicit. A transport closure after `turn_ended` is treated as successful completion.
423
+ - **Large reads are capped at 50 KB by OpenCode, and the cap is reported** — OpenCode's `read` tool stops at `MAX_BYTES = 50 * 1024`, cutting on a whole-line boundary, and appends `(Output capped at 50 KB. Showing lines X-Y. Use offset=N to continue.)`. The provider strips that envelope before returning content to Cursor so the model cannot echo wrappers into a later write, but it re-states the cap: a capped native read appends a `[Partial read: …]` marker after the content, a capped MCP read gets a separate notice content item, and a Pi read carries structured `PiReadExecSuccess.truncation`. The structured `truncated` flag alone is not enough — verified against live `gpt-5.4-mini` and `grok-4.5` sessions, both of which asserted "highly confident" that partial content was the whole file until the textual marker was added. Deliberately paged reads (explicit `offset`/`limit`) are not marked. Without that signal the model treats a capped read as the whole file and rewrites it truncated, discarding everything past the cap. The cap is hardcoded in OpenCode's read tool — it is not the configurable `tool_output.max_bytes`, which governs `Truncate.Service` and not read's line accumulation — so the only lever is paging with `offset`. Prefer `edit` over whole-file `write` on files above 50 KB.
295
424
  - **No fallback models** — if Cursor’s `AvailableModels` API is unreachable and there is no local cache, the provider exposes no models.
296
425
 
297
426
  ## License
package/dist/agent-url.js CHANGED
@@ -21,6 +21,8 @@ function normalizeApiBaseURL(baseURL) {
21
21
  return new URL(baseURL).origin;
22
22
  }
23
23
  function resolveCacheKey(token, options) {
24
+ // codeql[js/insufficient-password-hash] -- The token is a high-entropy JWT/API key,
25
+ // and this digest is only an ephemeral memoization key, never a password verifier.
24
26
  const tokenHash = createHash("sha256").update(token).digest("hex").slice(0, 16);
25
27
  return `${tokenHash}|${normalizeApiBaseURL(options.apiBaseURL ?? options.baseURL)}|telem:${options.telemetryEnabled === true}`;
26
28
  }
package/dist/auth.d.ts CHANGED
@@ -32,6 +32,13 @@ export declare function clearBearerTokenCache(): void;
32
32
  * Resolve a Bearer JWT for Cursor API calls. Prefer an already-exchanged
33
33
  * `accessToken`; otherwise exchange (and cache) from `apiKey`, refreshing
34
34
  * when the cached JWT is near expiry.
35
+ *
36
+ * `apiKey` is only ever a raw exchangeable secret when it has Cursor's
37
+ * `crsr_` prefix. Callers that generically forward whatever credential value
38
+ * they hold — e.g. a host's package-agnostic "aisdk:" SDK loader, which
39
+ * doesn't distinguish our OAuth vs. API-key connection methods and may pass
40
+ * an already-issued JWT through the `apiKey` field — hand us a token that's
41
+ * already good to use as-is; POSTing it to the exchange endpoint 401s.
35
42
  */
36
43
  export declare function resolveBearerToken(input: {
37
44
  accessToken?: string;
package/dist/auth.js CHANGED
@@ -147,6 +147,13 @@ export function clearBearerTokenCache() {
147
147
  * Resolve a Bearer JWT for Cursor API calls. Prefer an already-exchanged
148
148
  * `accessToken`; otherwise exchange (and cache) from `apiKey`, refreshing
149
149
  * when the cached JWT is near expiry.
150
+ *
151
+ * `apiKey` is only ever a raw exchangeable secret when it has Cursor's
152
+ * `crsr_` prefix. Callers that generically forward whatever credential value
153
+ * they hold — e.g. a host's package-agnostic "aisdk:" SDK loader, which
154
+ * doesn't distinguish our OAuth vs. API-key connection methods and may pass
155
+ * an already-issued JWT through the `apiKey` field — hand us a token that's
156
+ * already good to use as-is; POSTing it to the exchange endpoint 401s.
150
157
  */
151
158
  export async function resolveBearerToken(input) {
152
159
  if (input.accessToken)
@@ -154,6 +161,8 @@ export async function resolveBearerToken(input) {
154
161
  if (!input.apiKey) {
155
162
  throw new Error("Cursor provider: no access token or API key provided");
156
163
  }
164
+ if (!input.apiKey.startsWith("crsr_"))
165
+ return input.apiKey;
157
166
  const baseUrl = input.baseUrl ?? API_BASE;
158
167
  const cached = _apiKeyTokenCache.get(input.apiKey);
159
168
  if (cached && !isExpiringSoon(cached.accessToken)) {
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Session-scoped compaction marker for the OpenCode 2.0 plugin.
3
+ *
4
+ * The classic plugin learns that a turn belongs to OpenCode's compaction agent
5
+ * via the `chat.params` hook and forwards it as a provider option. OpenCode 2.0
6
+ * removed `chat.params`; the only place the runtime names the owning agent is
7
+ * `session.hook("context")`, which fires before dispatch. We record the fact
8
+ * there and let the provider read it back by session id.
9
+ *
10
+ * Bounded so a long-lived server cannot accumulate ids for dead sessions.
11
+ */
12
+ export declare function markCompactionSession(sessionID: string, isCompaction: boolean): void;
13
+ export declare function isCompactionSession(sessionID: string | undefined): boolean;
14
+ export declare function clearCompactionSessions(): void;
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Session-scoped compaction marker for the OpenCode 2.0 plugin.
3
+ *
4
+ * The classic plugin learns that a turn belongs to OpenCode's compaction agent
5
+ * via the `chat.params` hook and forwards it as a provider option. OpenCode 2.0
6
+ * removed `chat.params`; the only place the runtime names the owning agent is
7
+ * `session.hook("context")`, which fires before dispatch. We record the fact
8
+ * there and let the provider read it back by session id.
9
+ *
10
+ * Bounded so a long-lived server cannot accumulate ids for dead sessions.
11
+ */
12
+ const MAX_TRACKED_SESSIONS = 256;
13
+ const compactionSessions = new Set();
14
+ export function markCompactionSession(sessionID, isCompaction) {
15
+ if (!sessionID)
16
+ return;
17
+ if (!isCompaction) {
18
+ compactionSessions.delete(sessionID);
19
+ return;
20
+ }
21
+ // Re-insert to keep insertion order meaningful for the eviction below.
22
+ compactionSessions.delete(sessionID);
23
+ compactionSessions.add(sessionID);
24
+ while (compactionSessions.size > MAX_TRACKED_SESSIONS) {
25
+ const oldest = compactionSessions.values().next().value;
26
+ if (oldest === undefined)
27
+ break;
28
+ compactionSessions.delete(oldest);
29
+ }
30
+ }
31
+ export function isCompactionSession(sessionID) {
32
+ return typeof sessionID === "string" && compactionSessions.has(sessionID);
33
+ }
34
+ export function clearCompactionSessions() {
35
+ compactionSessions.clear();
36
+ }
@@ -20,6 +20,10 @@ export function buildEnv(workspaceRoot) {
20
20
  // Cursor's project_folder is a metadata root (agent-tools, terminals, …),
21
21
  // not the git workspace. Keep dumps under OpenCode cache.
22
22
  const projectFolder = ensureOpencodeProjectDir(cwd);
23
+ // process_working_directory must match the workspace, not the host process
24
+ // cwd. OpenCode 2.0's daemon is long-lived and often started from $HOME, so
25
+ // process.cwd() would advertise the home folder to Cursor and the model would
26
+ // treat that as its shell cwd. workspace_paths already uses `cwd` above.
23
27
  const env = {
24
28
  os_version: osVersion,
25
29
  workspace_paths: [cwd],
@@ -30,8 +34,8 @@ export function buildEnv(workspaceRoot) {
30
34
  project_folder: projectFolder,
31
35
  terminals_folder: path.join(projectFolder, "terminals"),
32
36
  agent_transcripts_folder: path.join(projectFolder, "agent-transcripts"),
33
- process_working_directory: process.cwd(),
34
- is_working_dir_home_dir: path.resolve(process.cwd()) === path.resolve(home),
37
+ process_working_directory: cwd,
38
+ is_working_dir_home_dir: cwd === path.resolve(home),
35
39
  };
36
40
  trace(`buildEnv: workspace_paths=${JSON.stringify(env.workspace_paths)} ` +
37
41
  `project_folder=${env.project_folder} ` +
@@ -145,8 +145,9 @@ export function slugifyWorkspacePath(workspaceRoot) {
145
145
  const resolved = path.resolve(workspaceRoot);
146
146
  return resolved
147
147
  .replace(/[^a-zA-Z0-9]/g, "-")
148
- .replace(/-+/g, "-")
149
- .replace(/^-+|-+$/g, "");
148
+ .split("-")
149
+ .filter(Boolean)
150
+ .join("-");
150
151
  }
151
152
  /**
152
153
  * Cursor-style project metadata root for a workspace.
package/dist/index.d.ts CHANGED
@@ -34,9 +34,7 @@ export type CreateCursorOptions = {
34
34
  /** Fresh-turn retry policy. Defaults: 3 attempts, 500ms base, 8000ms cap. */
35
35
  retry?: CursorRetryOptions;
36
36
  };
37
- export declare function createCursor(options: CreateCursorOptions): {
38
- languageModel(modelId: string): import("@ai-sdk/provider").LanguageModelV3;
39
- };
37
+ export declare function createCursor(options: CreateCursorOptions): import("./plugin-core.js").CursorSdk;
40
38
  export { CursorPlugin };
41
39
  export type { CursorContinuationOptions, CursorContinuationPolicy } from "./session.js";
42
40
  export default CursorPlugin;
package/dist/index.js CHANGED
@@ -1,13 +1,7 @@
1
- import { CURSOR_PROVIDER_ID } from "./shared.js";
2
- import { createCursorLanguageModel } from "./language-model.js";
1
+ import { createSdk } from "./plugin-core.js";
3
2
  import { CursorPlugin } from "./plugin.js";
4
3
  export function createCursor(options) {
5
- const providerId = options.name || CURSOR_PROVIDER_ID;
6
- return {
7
- languageModel(modelId) {
8
- return createCursorLanguageModel(modelId, providerId, options);
9
- },
10
- };
4
+ return createSdk(options);
11
5
  }
12
6
  export { CursorPlugin };
13
7
  export default CursorPlugin;