cursor-opencode-provider 0.2.9 → 0.3.0

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 (42) hide show
  1. package/README.md +128 -8
  2. package/dist/auth.d.ts +7 -0
  3. package/dist/auth.js +9 -0
  4. package/dist/compaction-marker.d.ts +14 -0
  5. package/dist/compaction-marker.js +36 -0
  6. package/dist/context/env.js +6 -2
  7. package/dist/index.d.ts +1 -3
  8. package/dist/index.js +2 -8
  9. package/dist/language-model.js +37 -33
  10. package/dist/model-config.d.ts +15 -0
  11. package/dist/model-config.js +188 -0
  12. package/dist/opencode2/catalog.d.ts +33 -0
  13. package/dist/opencode2/catalog.js +85 -0
  14. package/dist/opencode2/integration.d.ts +23 -0
  15. package/dist/opencode2/integration.js +124 -0
  16. package/dist/opencode2/types.d.ts +316 -0
  17. package/dist/opencode2/types.js +18 -0
  18. package/dist/plugin-core.d.ts +27 -0
  19. package/dist/plugin-core.js +31 -0
  20. package/dist/plugin-opencode2.d.ts +3 -0
  21. package/dist/plugin-opencode2.js +293 -0
  22. package/dist/plugin-v2.d.ts +7 -0
  23. package/dist/plugin-v2.js +1 -15
  24. package/dist/plugin.d.ts +1 -15
  25. package/dist/plugin.js +11 -191
  26. package/dist/protocol/messages.d.ts +10 -0
  27. package/dist/protocol/messages.js +56 -0
  28. package/dist/protocol/tools.d.ts +8 -1
  29. package/dist/protocol/tools.js +9 -4
  30. package/dist/session-directory.d.ts +17 -0
  31. package/dist/session-directory.js +35 -0
  32. package/dist/session.d.ts +13 -1
  33. package/dist/session.js +70 -1
  34. package/dist/shell-timeout.d.ts +3 -1
  35. package/dist/shell-timeout.js +6 -2
  36. package/dist/usage.d.ts +30 -0
  37. package/dist/usage.js +77 -0
  38. package/dist/web-search-tool.d.ts +33 -0
  39. package/dist/web-search-tool.js +22 -0
  40. package/dist/web-tools.d.ts +9 -25
  41. package/dist/web-tools.js +34 -36
  42. package/package.json +8 -3
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
  {
@@ -49,6 +49,13 @@ Add the package name to OpenCode config. OpenCode installs npm plugins with Bun
49
49
 
50
50
  Pin a version if you want: `"cursor-opencode-provider@0.2.9"`.
51
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
+ ```
58
+
52
59
  ### From a local clone
53
60
 
54
61
  ```bash
@@ -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.2.9/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 |
@@ -256,7 +372,8 @@ Kilo `scout` is reserved for external documentation, dependency repositories, an
256
372
  |-------------|--------|
257
373
  | `cursor-opencode-provider` | `createCursor`, `CursorPlugin` (named + default) |
258
374
  | `cursor-opencode-provider/plugin` | `CursorPlugin` (classic Hooks — auth) |
259
- | `cursor-opencode-provider/plugin/v2` | OpenCode Effect/Promise v2 plugin (`ctx.aisdk.*`) |
375
+ | `cursor-opencode-provider/plugin/v2` | OpenCode 1.18 Effect/Promise v2 plugin (`ctx.aisdk.*`) |
376
+ | `cursor-opencode-provider/plugin/opencode2` | OpenCode 2.0 beta plugin (self-registering: catalog + auth + tools) |
260
377
  | `cursor-opencode-provider/errors` | Structured provider error classes |
261
378
 
262
379
  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 +382,9 @@ The package root intentionally stays plugin-safe for OpenCode's classic loader.
265
382
 
266
383
  | Problem | What to try |
267
384
  |---------|-------------|
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`). |
385
+ | 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
386
  | 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. |
387
+ | 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
388
  | “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
389
  | 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
390
  | 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 +392,7 @@ The package root intentionally stays plugin-safe for OpenCode's classic loader.
274
392
  | 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
393
  | `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
394
  | 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. |
395
+ | 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
396
 
278
397
  ## Security
279
398
 
@@ -282,6 +401,7 @@ Project `instructions` may reference absolute or `~/` paths (OpenCode parity). S
282
401
  ## Known limitations
283
402
 
284
403
  - **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.
404
+ - **`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
405
  - **`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
406
  - **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
407
  - **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.
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} ` +
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;
@@ -5,7 +5,7 @@ import { bidiRunStream, CursorRunInterruptedError, normalizeAgentRunOrigin, } fr
5
5
  import { trace, traceRequestContextPaths } from "./debug.js";
6
6
  import { buildRunRequest, buildHeartbeat } from "./protocol/request.js";
7
7
  import { decodeFramePayload } from "./protocol/framing.js";
8
- import { decodeMessage } from "./protocol/messages.js";
8
+ import { debugWalkTurnEnded, decodeMessage } from "./protocol/messages.js";
9
9
  import { parseExecServerMessage, buildToolCallPart, buildExecClientMessages, buildReadRejectionMessages, classifyMissingReadTarget, resolveReadTargetPath, parseExecIdFromToolCallId, detectExecVariantField, buildRequestContextResult, buildMcpStateResult, buildCustomWebToolAliases, extractHostSubagentCatalog, resolveCustomWebToolAlias, remapNativeSubagentForCatalog, CUSTOM_WEBFETCH_TOOL, CUSTOM_WEBSEARCH_TOOL, } from "./protocol/tools.js";
10
10
  import { describeCursorExecVariant } from "./protocol/exec-variants.js";
11
11
  import { advertisedToolNamesFromDescriptors, extractExecDisplayCallId, extractProtobufSubmessage, listProtobufFieldNumbers, parseDisplayToolCall, resolveBridgedOpenCodeToolCall, } from "./protocol/tool-call-bridge.js";
@@ -22,9 +22,12 @@ import { workspaceRootFromRequestContext } from "./context/env.js";
22
22
  import { opencodeGlobalCacheDir, setHostCacheDirOverride } from "./context/paths.js";
23
23
  import { resolveAgentUrl } from "./agent-url.js";
24
24
  import { CURSOR_API_HOST, CURSOR_COMPACTION_OPTION } from "./shared.js";
25
+ import { isCompactionSession } from "./compaction-marker.js";
26
+ import { getSessionDirectory } from "./session-directory.js";
25
27
  import { consumeCursorShellResult, registerCursorShellCall, } from "./shell-timeout.js";
26
28
  import { analyzeReplayFrame, AttemptReplaySafety } from "./replay-safety.js";
27
29
  import { readAllFieldsStrict } from "./protocol/struct.js";
30
+ import { buildLanguageModelV3UsageFromEstimate, buildLanguageModelV3UsageFromTurnEnded, turnEndedCounter, } from "./usage.js";
28
31
  let _availableModels;
29
32
  // mtime of the cache file the last time we loaded it. Compared on each call
30
33
  // so discoverModels' background refresh is picked up without a process restart.
@@ -275,7 +278,7 @@ export function createCursorLanguageModel(modelId, providerId, options) {
275
278
  };
276
279
  }
277
280
  async function doStreamImpl(modelId, options, callOptions) {
278
- // A raw `sk-...` API key must be exchanged for a JWT before it can be used
281
+ // A raw `crsr_...` API key must be exchanged for a JWT before it can be used
279
282
  // as a Bearer token (the plugin path does this in auth.ts). The accessToken
280
283
  // path is already a JWT from OAuth/key-exchange, so we use it as-is.
281
284
  // resolveBearerToken caches apiKey exchanges so we don't hit /auth/exchange
@@ -445,8 +448,10 @@ async function startSession(modelId, token, callOptions, options, startOptions)
445
448
  const sessionKey = opencodeSessionKey(callOptions);
446
449
  const providerOptions = callOptions.providerOptions?.cursor;
447
450
  // The classic plugin marks OpenCode's agent="compaction" through chat.params.
451
+ // OpenCode 2.0 removed that hook, so its plugin records the same fact against
452
+ // the session id from session.hook("context") instead; consult both.
448
453
  // Do not infer this from tools/toolChoice: standalone no-tool calls are valid.
449
- const isCompaction = providerOptions?.[CURSOR_COMPACTION_OPTION] === true;
454
+ const isCompaction = providerOptions?.[CURSOR_COMPACTION_OPTION] === true || isCompactionSession(sessionKey);
450
455
  const toolState = resolveTurnToolState({
451
456
  sessionKey,
452
457
  incomingTools,
@@ -482,7 +487,12 @@ async function startSession(modelId, token, callOptions, options, startOptions)
482
487
  const userText = recovery?.kind === "rebase"
483
488
  ? "Continue the interrupted turn from the conversation history above. Do not repeat completed work."
484
489
  : (extractUserText([...prompt].reverse().find((m) => m.role === "user")) || ".");
485
- const workspaceRoot = path.resolve(options.workspaceRoot || process.cwd());
490
+ // v1 sets `options.workspaceRoot` correctly per invocation (`input.directory`,
491
+ // one plugin instance per project). OpenCode 2.0 runs one daemon across many
492
+ // projects, so its static `options.workspaceRoot` is only a last-resort
493
+ // fallback; `getSessionDirectory` carries the real per-session directory
494
+ // recorded from `session.hook("context")` in `plugin-opencode2.ts`.
495
+ const workspaceRoot = path.resolve(getSessionDirectory(sessionKey) ?? (options.workspaceRoot || process.cwd()));
486
496
  const baseSystemPrompt = extractSystemPrompt(prompt);
487
497
  const interactionGuidance = buildOpenCodeInteractionGuidance(cursorTools, isCompaction, workspaceRoot);
488
498
  const systemPrompt = interactionGuidance
@@ -583,6 +593,7 @@ async function startSession(modelId, token, callOptions, options, startOptions)
583
593
  outputTokens: 0,
584
594
  cacheRead: 0,
585
595
  cacheWrite: 0,
596
+ reasoningTokens: 0,
586
597
  };
587
598
  trace(`outbound Run: model=${cursorModelId} opencodeModel=${modelId} conversationId=${conversationId} ` +
588
599
  `params=${JSON.stringify(parameterValues ?? [])} ` +
@@ -730,6 +741,7 @@ export function deliverContinuationResults(session, trailingToolResults) {
730
741
  toolName: pending.toolName ?? r.toolName,
731
742
  resultMetadata: pending.resultMetadata,
732
743
  shellOutcome: shellResult?.outcome,
744
+ workspaceRoot: workspaceRootFromRequestContext(session.requestContext),
733
745
  });
734
746
  }
735
747
  catch (error) {
@@ -916,6 +928,7 @@ export async function pump(session, controller, ids, abortSignal) {
916
928
  error: reason,
917
929
  toolName: parsed.toolName,
918
930
  resultMetadata: parsed.resultMetadata,
931
+ workspaceRoot: workspaceRootFromRequestContext(session.requestContext),
919
932
  })) {
920
933
  session.stream.write(frame);
921
934
  }
@@ -965,6 +978,7 @@ export async function pump(session, controller, ids, abortSignal) {
965
978
  output: "",
966
979
  toolName: parsed.toolName,
967
980
  resultMetadata: { path: requestedPath },
981
+ workspaceRoot,
968
982
  })) {
969
983
  session.stream.write(frame);
970
984
  }
@@ -1067,32 +1081,27 @@ export async function pump(session, controller, ids, abortSignal) {
1067
1081
  if (te) {
1068
1082
  // Authoritative TurnEnded counts — replace the running estimate.
1069
1083
  session.usageEstimate = {
1070
- inputTokens: Number(te.input_tokens ?? 0) || 0,
1071
- outputTokens: Number(te.output_tokens ?? 0) || 0,
1072
- cacheRead: Number(te.cache_read ?? 0) || 0,
1073
- cacheWrite: Number(te.cache_write ?? 0) || 0,
1084
+ inputTokens: turnEndedCounter(te, "input_tokens"),
1085
+ outputTokens: turnEndedCounter(te, "output_tokens"),
1086
+ cacheRead: turnEndedCounter(te, "cache_read"),
1087
+ cacheWrite: turnEndedCounter(te, "cache_write"),
1088
+ reasoningTokens: turnEndedCounter(te, "reasoning_tokens"),
1074
1089
  };
1075
1090
  }
1076
1091
  const est = session.usageEstimate;
1077
- const usage = {
1078
- inputTokens: {
1079
- total: promptTokens,
1080
- noCache: undefined,
1081
- cacheRead: 0,
1082
- cacheWrite: 0,
1083
- },
1084
- outputTokens: {
1085
- total: estimateTokens(requestUsage.outputChars),
1086
- text: undefined,
1087
- reasoning: undefined,
1088
- },
1089
- };
1092
+ const usage = te
1093
+ ? buildLanguageModelV3UsageFromTurnEnded(te)
1094
+ : buildLanguageModelV3UsageFromEstimate(est, promptTokens, requestUsage.outputChars, estimateTokens);
1090
1095
  const providerMetadata = te ? cursorTurnEndedProviderMetadata(te) : undefined;
1091
1096
  const reasonLabel = typeof reason === "object" && reason && "unified" in reason
1092
1097
  ? String(reason.unified ?? "unknown")
1093
1098
  : String(reason);
1099
+ const inTotal = usage.inputTokens?.total ?? 0;
1100
+ const outTotal = usage.outputTokens?.total ?? 0;
1094
1101
  trace(`finish: reason=${reasonLabel} ` +
1095
- `requestIn=${usage.inputTokens.total} requestOut=${usage.outputTokens.total} ` +
1102
+ `v3In=${inTotal} v3Out=${outTotal} ` +
1103
+ `v3CacheRead=${usage.inputTokens?.cacheRead ?? 0} v3CacheWrite=${usage.inputTokens?.cacheWrite ?? 0} ` +
1104
+ `v3Reasoning=${usage.outputTokens?.reasoning ?? 0} ` +
1096
1105
  `rawIn=${est.inputTokens} rawOut=${est.outputTokens} ` +
1097
1106
  `rawCacheRead=${est.cacheRead} rawCacheWrite=${est.cacheWrite} ` +
1098
1107
  `source=${te ? "turn_ended" : "estimate"}`);
@@ -1238,6 +1247,7 @@ export async function pump(session, controller, ids, abortSignal) {
1238
1247
  emitReasoning(iu.thinking_delta.text ?? "");
1239
1248
  }
1240
1249
  else if (iu?.turn_ended) {
1250
+ trace(`turn_ended raw wire fields: ${debugWalkTurnEnded(payload)}`);
1241
1251
  emitFinish(iu.turn_ended, { unified: "stop", raw: undefined });
1242
1252
  sessionManager.close(session);
1243
1253
  return;
@@ -1683,20 +1693,14 @@ export function estimatePromptTokens(prompt) {
1683
1693
  }
1684
1694
  /** Preserve cumulative Cursor counters as diagnostics, never as AI SDK request usage. */
1685
1695
  export function cursorTurnEndedProviderMetadata(te) {
1686
- const counter = (key) => {
1687
- const value = te[key];
1688
- return typeof value === "number" && Number.isFinite(value) && value >= 0
1689
- ? Math.trunc(value)
1690
- : 0;
1691
- };
1692
1696
  return {
1693
1697
  cursor: {
1694
1698
  usageVersion: 2,
1695
- inputTokensRaw: counter("input_tokens"),
1696
- outputTokensRaw: counter("output_tokens"),
1697
- cacheReadRaw: counter("cache_read"),
1698
- cacheWriteRaw: counter("cache_write"),
1699
- reasoningTokensRaw: counter("reasoning_tokens"),
1699
+ inputTokensRaw: turnEndedCounter(te, "input_tokens"),
1700
+ outputTokensRaw: turnEndedCounter(te, "output_tokens"),
1701
+ cacheReadRaw: turnEndedCounter(te, "cache_read"),
1702
+ cacheWriteRaw: turnEndedCounter(te, "cache_write"),
1703
+ reasoningTokensRaw: turnEndedCounter(te, "reasoning_tokens"),
1700
1704
  },
1701
1705
  };
1702
1706
  }
@@ -0,0 +1,15 @@
1
+ import { type ModelInfo } from "./models.js";
2
+ /**
3
+ * Display names shared by both a thinking and a non-thinking model. A thinking
4
+ * model with such a name needs a "Thinking" tag to disambiguate it from its
5
+ * non-thinking twin (Cursor's Claude/Fable/Sonnet families). Models whose names
6
+ * are already unique — including Cursor's GPT family, where the reasoning tier
7
+ * ("None"/"Low"/"High"…) is baked into the name — are excluded, so they aren't
8
+ * tagged redundantly.
9
+ */
10
+ export declare function thinkingSuffixBaseNames(models: ModelInfo[]): Set<string>;
11
+ export declare function modelInfoToConfig(mi: ModelInfo, options?: {
12
+ thinkingSuffix?: boolean;
13
+ contextTier?: "base" | "long";
14
+ }): Record<string, any>;
15
+ export declare function modelsToConfig(models: ModelInfo[]): Record<string, any>;