cursor-opencode-provider 0.1.3 → 0.1.4

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.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Use [Cursor](https://cursor.com) subscription models from [OpenCode](https://opencode.ai) by speaking Cursor's Connect-RPC agent protocol.
4
4
 
5
- This project is a custom **AI SDK provider** (`LanguageModelV3`) plus an **OpenCode plugin** that handles authentication and model discovery. Instead of calling a generic chat-completions API, it encodes and decodes Cursor's protobuf agent protocol over HTTP/2 to `agentn.global.api5.cursor.sh`.
5
+ This project is a custom **AI SDK provider** (`LanguageModelV3`) plus an **OpenCode plugin** that handles authentication and model discovery. Instead of calling a generic chat-completions API, it encodes and decodes Cursor's protobuf agent protocol over HTTP/2 to Cursor's agent backend.
6
6
 
7
7
  > **Status:** Usable end-to-end in OpenCode (auth, models, streaming, tools). See [Known limitations](#known-limitations).
8
8
 
@@ -47,7 +47,7 @@ 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.1.3"`.
50
+ Pin a version if you want: `"cursor-opencode-provider@0.1.4"`.
51
51
 
52
52
  ### From a local clone
53
53
 
@@ -128,26 +128,30 @@ import { createCursor } from "cursor-opencode-provider"
128
128
  const cursor = createCursor({
129
129
  name: "cursor",
130
130
  accessToken: process.env.CURSOR_ACCESS_TOKEN,
131
+ // apiBaseURL: "https://api2.cursor.sh",
132
+ // agentBaseURL: "https://agentn.us.api5.cursor.sh", // explicit Run host override
133
+ // telemetryEnabled: true, // opt in to GetServerConfig telemetry
131
134
  })
132
135
 
133
136
  const model = cursor.languageModel("composer-2.5")
134
137
  // model implements AI SDK LanguageModelV3 (doStream / doGenerate)
135
138
  ```
136
139
 
137
- Pass either `accessToken` (JWT from OAuth or key exchange) or `apiKey` (raw `sk-...` key). Optional: `baseURL`, `headers`.
140
+ Pass either `accessToken` (JWT from OAuth or key exchange) or `apiKey` (raw `sk-...` key). Optional: `apiBaseURL`, `agentBaseURL`, `headers`, `telemetryEnabled`. The older `baseURL` option is still accepted as a legacy alias for `agentBaseURL`.
138
141
 
139
142
  ## Environment variables
140
143
 
141
144
  | Variable | Description |
142
145
  |----------|-------------|
143
146
  | `CURSOR_WEBSITE_URL` | Override OAuth login base URL (default `https://cursor.com`) |
144
- | `CURSOR_API_BASE_URL` | Override API base for auth and model discovery (default `https://api2.cursor.sh`) |
147
+ | `CURSOR_API_BASE_URL` | Override API base for auth, model discovery, and `GetServerConfig` agent URL resolution (default `https://api2.cursor.sh`) |
148
+ | `CURSOR_GET_SERVER_CONFIG_TELEMETRY` | Set to `1` or `true` to opt the `GetServerConfig` lookup into telemetry in OpenCode/plugin usage |
145
149
  | `CURSOR_PROVIDER_DEBUG` | Set to `1` or `true` to enable wire-level debug logging |
146
150
  | `CURSOR_PROVIDER_DEBUG_FILE` | Debug log path (default `/tmp/cursor-provider-debug.log`) |
147
151
  | `XDG_CACHE_HOME` | When set, model/version caches go under `$XDG_CACHE_HOME/opencode/` instead of `~/.cache/opencode/` |
148
152
  | `XDG_DATA_HOME` | When set, OpenCode `auth.json` is read from `$XDG_DATA_HOME/opencode/` instead of `~/.local/share/opencode/` |
149
153
 
150
- `createCursor({ baseURL })` also overrides the agent Run host (default `https://agentn.global.api5.cursor.sh`).
154
+ `createCursor({ agentBaseURL })` overrides the agent Run host. When unset, the provider resolves the host from Cursor's `GetServerConfig` API (`agentUrlConfig.agentnUrl`, region-specific — e.g. `agentn.us.api5.cursor.sh`, `agent-gcpp-uswest.api5.cursor.sh`) once per process and holds it in memory (never written to disk), so a held-open Run stream is never repointed mid-session. Explicit agent overrides and GetServerConfig results are validated as HTTPS `*.cursor.sh` hosts (Cursor's agent hostnames vary and may change); non-`cursor.sh` hosts are rejected. The lookup sends `{ "telem_enabled": false }` by default; set `telemetryEnabled: true` in provider config, or `CURSOR_GET_SERVER_CONFIG_TELEMETRY=1` for OpenCode/plugin usage, to opt in. If the lookup fails or does not return a valid Cursor agent host, the model call fails clearly instead of falling back to `agentn.global.api5.cursor.sh`.
151
155
 
152
156
  ## Development
153
157
 
@@ -167,7 +171,7 @@ OpenCode
167
171
  └── createCursor() → LanguageModelV3
168
172
  ├── session.ts held-open Run stream + exec bridge
169
173
  ├── protocol/ protobuf messages, framing, tools, thinking
170
- └── transport/ Connect-RPC over HTTP/2 to agentn.global.api5.cursor.sh
174
+ └── transport/ Connect-RPC over HTTP/2 to Cursor's agent backend
171
175
  ```
172
176
 
173
177
  | Module | Role |
@@ -179,6 +183,7 @@ OpenCode
179
183
  | `src/session.ts` | Held-open agent Run session and pending exec correlation |
180
184
  | `src/auth.ts` | PKCE OAuth, API key exchange, JWT refresh |
181
185
  | `src/models.ts` | `AvailableModels` fetch and `cursor-models.json` cache |
186
+ | `src/agent-url.ts` | `GetServerConfig` fetch + in-process memo (region-specific Run host) |
182
187
  | `src/transport/connect.ts` | HTTP/2 bidi stream and unary RPC calls |
183
188
  | `src/protocol/` | Protobuf encode/decode, checksum/device ids, tool-call mapping |
184
189
 
@@ -200,7 +205,8 @@ OpenCode
200
205
  | 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. |
201
206
  | “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. |
202
207
  | Empty or stale model list | Delete `~/.cache/opencode/cursor-models.json` (or under `$XDG_CACHE_HOME/opencode/`) 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. |
203
- | Stream hangs or HTTP/2 errors | Abort the turn and retry. The agent Run uses a bidirectional HTTP/2 stream to `agentn.global.api5.cursor.sh`; a dropped connection leaves the in-flight session unusable. |
208
+ | Stream hangs or HTTP/2 errors | Abort the turn and retry. The agent Run uses a bidirectional HTTP/2 stream; a dropped connection leaves the in-flight session unusable. |
209
+ | No response / silent 200 + close | The provider resolves the Run host from `GetServerConfig` (`agentUrlConfig.agentnUrl`). The URL is resolved once per process and not cached on disk. If resolution fails, the model call reports the endpoint-resolution error instead of falling back to `agentn.global.api5.cursor.sh`, which some accounts reject silently ("This region is not yet available for your team"). Set `CURSOR_PROVIDER_DEBUG=1` to confirm the resolved host in the debug log. |
204
210
  | Need wire-level logs | Set `CURSOR_PROVIDER_DEBUG=1` (optional `CURSOR_PROVIDER_DEBUG_FILE`, default `/tmp/cursor-provider-debug.log`) and reproduce the issue. |
205
211
 
206
212
  ## Known limitations
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Resolve the Run stream origin for this account via the `GetServerConfig`
3
+ * Connect RPC. Memoized for the process lifetime.
4
+ *
5
+ * - already resolved → return the memo (no fetch)
6
+ * - otherwise → fetch `agentUrlConfig.agentnUrl` (then `agentUrl`), memoize, return
7
+ * - fetch fails / no valid `agentUrlConfig` → throw (no global-host fallback)
8
+ *
9
+ * Concurrent callers share a single in-flight fetch.
10
+ */
11
+ export declare function resolveAgentUrl(token: string, options?: {
12
+ apiBaseURL?: string;
13
+ baseURL?: string;
14
+ telemetryEnabled?: boolean;
15
+ }): Promise<string>;
16
+ /** Reset the in-process memo. Tests only. */
17
+ export declare function resetAgentUrlCache(): void;
@@ -0,0 +1,74 @@
1
+ import { createHash } from "node:crypto";
2
+ import { fetchAgentUrl, trace } from "./transport/connect.js";
3
+ import { CURSOR_API_HOST } from "./shared.js";
4
+ const DEFAULT_API_BASE = `https://${CURSOR_API_HOST}`;
5
+ // In-process memo of the region-specific Run stream origin (agentnUrl). Resolved
6
+ // once per process — the auth loader warms it, and the first startSession reuses
7
+ // it — and held for the process lifetime. Region routing is near-static, and
8
+ // re-resolving mid-session would break a held-open bidi Run stream anyway.
9
+ //
10
+ // Unlike the models/version caches this is NOT persisted to disk. A wrong agent
11
+ // host is fatal and silent (HTTP 200 + immediate close, "This region is not
12
+ // available for your team"), so persisting it would risk pinning the process —
13
+ // or the next process — to a stale region or the legacy global host that some
14
+ // accounts reject. Resolving fresh per process is cheap (one unary RPC on the
15
+ // API host) and self-heals after a Cursor-side region migration on restart.
16
+ //
17
+ function normalizeApiBaseURL(baseURL) {
18
+ if (!baseURL)
19
+ return DEFAULT_API_BASE;
20
+ return new URL(baseURL).origin;
21
+ }
22
+ function resolveCacheKey(token, options) {
23
+ const tokenHash = createHash("sha256").update(token).digest("hex").slice(0, 16);
24
+ return `${tokenHash}|${normalizeApiBaseURL(options.apiBaseURL ?? options.baseURL)}|telem:${options.telemetryEnabled === true}`;
25
+ }
26
+ const _resolved = new Map();
27
+ // In-flight fetches share the same key as resolved URLs so concurrent callers dedup per account.
28
+ const _inflight = new Map();
29
+ /**
30
+ * Resolve the Run stream origin for this account via the `GetServerConfig`
31
+ * Connect RPC. Memoized for the process lifetime.
32
+ *
33
+ * - already resolved → return the memo (no fetch)
34
+ * - otherwise → fetch `agentUrlConfig.agentnUrl` (then `agentUrl`), memoize, return
35
+ * - fetch fails / no valid `agentUrlConfig` → throw (no global-host fallback)
36
+ *
37
+ * Concurrent callers share a single in-flight fetch.
38
+ */
39
+ export async function resolveAgentUrl(token, options = {}) {
40
+ const cacheKey = resolveCacheKey(token, options);
41
+ const memo = _resolved.get(cacheKey);
42
+ if (memo) {
43
+ trace(`agent-url: reuse in-process memo → ${memo}`);
44
+ return memo;
45
+ }
46
+ const inflight = _inflight.get(cacheKey);
47
+ if (inflight) {
48
+ trace("agent-url: awaiting in-flight GetServerConfig");
49
+ return inflight;
50
+ }
51
+ const promise = (async () => {
52
+ try {
53
+ const url = await fetchAgentUrl(token, options);
54
+ _resolved.set(cacheKey, url);
55
+ trace(`agent-url: resolved via GetServerConfig → ${url}`);
56
+ return url;
57
+ }
58
+ catch (err) {
59
+ const reason = err instanceof Error ? err.message : String(err);
60
+ trace(`agent-url: GetServerConfig failed (${reason}); no fallback agent host will be used`);
61
+ throw err;
62
+ }
63
+ finally {
64
+ _inflight.delete(cacheKey);
65
+ }
66
+ })();
67
+ _inflight.set(cacheKey, promise);
68
+ return promise;
69
+ }
70
+ /** Reset the in-process memo. Tests only. */
71
+ export function resetAgentUrlCache() {
72
+ _resolved.clear();
73
+ _inflight.clear();
74
+ }
@@ -7,7 +7,7 @@ function debugEnabled() {
7
7
  function debugAuthStore(message) {
8
8
  if (!debugEnabled())
9
9
  return;
10
- console.error(`[cursor-opencode-provider] auth-store: ${message}`);
10
+ console.debug(`[cursor-opencode-provider] auth-store: ${message}`);
11
11
  }
12
12
  /**
13
13
  * Read a provider's credentials from OpenCode's `auth.json` (XDG data dir).
package/dist/index.d.ts CHANGED
@@ -3,8 +3,15 @@ export type CreateCursorOptions = {
3
3
  name: string;
4
4
  accessToken?: string;
5
5
  apiKey?: string;
6
+ /** API base for auth, model discovery, and GetServerConfig. */
7
+ apiBaseURL?: string;
8
+ /** Explicit Cursor agent Run host override. */
9
+ agentBaseURL?: string;
10
+ /** @deprecated Use agentBaseURL. Kept as the legacy agent Run host override. */
6
11
  baseURL?: string;
7
12
  headers?: Record<string, string>;
13
+ /** Opt in to telemetry on the GetServerConfig endpoint lookup. Defaults to false. */
14
+ telemetryEnabled?: boolean;
8
15
  /** OpenCode project / worktree directory for request_context collectors. */
9
16
  workspaceRoot?: string;
10
17
  };
@@ -1,6 +1,6 @@
1
1
  import fs from "node:fs";
2
2
  import { createHash } from "node:crypto";
3
- import { bidiRunStream, trace } from "./transport/connect.js";
3
+ import { bidiRunStream, normalizeAgentRunOrigin, trace } from "./transport/connect.js";
4
4
  import { buildRunRequest, buildHeartbeat } from "./protocol/request.js";
5
5
  import { decodeFramePayload } from "./protocol/framing.js";
6
6
  import { decodeMessage } from "./protocol/messages.js";
@@ -12,6 +12,8 @@ import { sessionManager } from "./session.js";
12
12
  import { readCache, cacheFilePath, resolveVariantParameters } from "./models.js";
13
13
  import { buildRequestContext } from "./context/build.js";
14
14
  import { opencodeGlobalCacheDir } from "./context/paths.js";
15
+ import { resolveAgentUrl } from "./agent-url.js";
16
+ import { CURSOR_API_HOST } from "./shared.js";
15
17
  let _availableModels;
16
18
  // mtime of the cache file the last time we loaded it. Compared on each call
17
19
  // so discoverModels' background refresh is picked up without a process restart.
@@ -49,7 +51,7 @@ async function doStreamImpl(modelId, options, callOptions) {
49
51
  const token = await resolveBearerToken({
50
52
  accessToken: options.accessToken,
51
53
  apiKey: options.apiKey,
52
- baseUrl: options.baseURL,
54
+ baseUrl: resolveApiBaseURL(options),
53
55
  });
54
56
  const prompt = callOptions.prompt;
55
57
  // ── Continuation vs fresh turn ──
@@ -171,6 +173,14 @@ async function startSession(modelId, token, callOptions, options) {
171
173
  const systemPrompt = extractSystemPrompt(prompt);
172
174
  const tools = extractTools(callOptions);
173
175
  await loadAvailableModels();
176
+ // Resolve the region-specific Run stream origin once per process (memoized
177
+ // in agent-url.ts). Explicit agent host overrides skip GetServerConfig but
178
+ // still go through the Cursor agent-host allowlist.
179
+ const agentBaseUrl = resolveExplicitAgentBaseURL(options) ??
180
+ (await resolveAgentUrl(token, {
181
+ apiBaseURL: resolveApiBaseURL(options),
182
+ telemetryEnabled: resolveTelemetryEnabled(options),
183
+ }));
174
184
  const providerOptions = callOptions.providerOptions?.cursor;
175
185
  const reasoningEffort = providerOptions?.reasoningEffort;
176
186
  const maxMode = !!(providerOptions?.maxMode ?? false);
@@ -180,7 +190,7 @@ async function startSession(modelId, token, callOptions, options) {
180
190
  // that signal when a turn ends with tool-calls; the Cursor stream must stay
181
191
  // open until we write the exec results on the next doStream.
182
192
  const stream = await bidiRunStream(token, {
183
- baseURL: options.baseURL,
193
+ baseURL: agentBaseUrl,
184
194
  headers: options.headers,
185
195
  });
186
196
  // Build the tool descriptors once — advertised in AgentRunRequest #4 mcp_tools
@@ -321,6 +331,25 @@ async function loadAvailableModels() {
321
331
  }
322
332
  catch { /* ignore */ }
323
333
  }
334
+ function resolveApiBaseURL(options) {
335
+ return options.apiBaseURL ?? process.env.CURSOR_API_BASE_URL ?? `https://${CURSOR_API_HOST}`;
336
+ }
337
+ function resolveTelemetryEnabled(options) {
338
+ return options.telemetryEnabled ?? isTruthyEnv(process.env.CURSOR_GET_SERVER_CONFIG_TELEMETRY);
339
+ }
340
+ function resolveExplicitAgentBaseURL(options) {
341
+ const raw = options.agentBaseURL ?? options.baseURL;
342
+ if (!raw)
343
+ return undefined;
344
+ const normalized = normalizeAgentRunOrigin(raw);
345
+ if (!normalized) {
346
+ throw new Error("Invalid Cursor agent base URL override: expected https://*.cursor.sh");
347
+ }
348
+ return normalized;
349
+ }
350
+ function isTruthyEnv(value) {
351
+ return value === "1" || value === "true";
352
+ }
324
353
  /**
325
354
  * Read the held-open stream, emitting stream parts, until the turn boundary:
326
355
  * - a tool call (exec_server_message) → emit tool-call, finish "tool-calls",
package/dist/plugin.js CHANGED
@@ -3,6 +3,7 @@ import { pollForTokens, exchangeApiKey, refreshAccessToken, isExpiringSoon, gene
3
3
  import { readCache, discoverModels, isCacheFresh } from "./models.js";
4
4
  import { opencodeGlobalCacheDir } from "./context/paths.js";
5
5
  import { readStoredAuth } from "./context/auth-store.js";
6
+ import { resolveAgentUrl } from "./agent-url.js";
6
7
  const MODULE_URL = new URL("./index.js", import.meta.url).href;
7
8
  /**
8
9
  * Strip characters that break rendering in the OpenCode Desktop webview from a
@@ -93,8 +94,16 @@ function modelsToConfig(models) {
93
94
  }
94
95
  return out;
95
96
  }
97
+ function cursorApiBaseURL() {
98
+ return process.env.CURSOR_API_BASE_URL ?? `https://${CURSOR_API_HOST}`;
99
+ }
100
+ function cursorGetServerConfigTelemetryEnabled() {
101
+ return (process.env.CURSOR_GET_SERVER_CONFIG_TELEMETRY === "1" ||
102
+ process.env.CURSOR_GET_SERVER_CONFIG_TELEMETRY === "true");
103
+ }
96
104
  export async function CursorPlugin(input) {
97
105
  const cacheDir = opencodeGlobalCacheDir();
106
+ const apiBaseURL = cursorApiBaseURL();
98
107
  // Last access token successfully resolved in this plugin instance. Config's
99
108
  // loadModels can only read OpenCode's durable store (auth.json /
100
109
  // OPENCODE_AUTH_CONTENT); auth.loader gets live credentials via getAuth().
@@ -139,7 +148,7 @@ export async function CursorPlugin(input) {
139
148
  // it the same way as OAuth when it is expiring / already expired.
140
149
  if (refreshToken && isExpiringSoon(auth.key)) {
141
150
  try {
142
- const newTokens = await refreshAccessToken(refreshToken);
151
+ const newTokens = await refreshAccessToken(refreshToken, apiBaseURL);
143
152
  accessToken = newTokens.accessToken;
144
153
  await persistAuthBestEffort({
145
154
  type: "api",
@@ -166,7 +175,7 @@ export async function CursorPlugin(input) {
166
175
  if (!auth.refresh)
167
176
  return undefined;
168
177
  try {
169
- const newTokens = await refreshAccessToken(auth.refresh);
178
+ const newTokens = await refreshAccessToken(auth.refresh, apiBaseURL);
170
179
  // Preserve optional OAuth fields (v2 Auth / plugin may carry these).
171
180
  const extras = auth;
172
181
  // Use the new token even if persisting back to OpenCode fails.
@@ -197,7 +206,7 @@ export async function CursorPlugin(input) {
197
206
  const accessToken = await resolveAccessToken(auth);
198
207
  if (accessToken) {
199
208
  try {
200
- const models = await discoverModels(accessToken, cacheDir);
209
+ const models = await discoverModels(accessToken, cacheDir, { baseURL: apiBaseURL });
201
210
  return modelsToConfig(models);
202
211
  }
203
212
  catch {
@@ -280,7 +289,7 @@ export async function CursorPlugin(input) {
280
289
  if (!apiKey)
281
290
  return { type: "failed" };
282
291
  try {
283
- const result = await exchangeApiKey(apiKey);
292
+ const result = await exchangeApiKey(apiKey, apiBaseURL);
284
293
  return {
285
294
  type: "success",
286
295
  key: result.accessToken,
@@ -306,8 +315,16 @@ export async function CursorPlugin(input) {
306
315
  if (!cached || cached.models.length === 0 || !isCacheFresh(cached)) {
307
316
  // Await so an empty/missing cache is written before the loader returns
308
317
  // (fire-and-forget often loses the race on short-lived CLI commands).
309
- await discoverModels(accessToken, cacheDir).catch(() => { });
318
+ await discoverModels(accessToken, cacheDir, { baseURL: apiBaseURL }).catch(() => { });
310
319
  }
320
+ // Resolve the region-specific Run stream origin so the first turn
321
+ // does not spend time on GetServerConfig. Best-effort: a failure is
322
+ // surfaced by startSession, which can fail the actual model call with
323
+ // a clear endpoint-resolution error instead of using global fallback.
324
+ await resolveAgentUrl(accessToken, {
325
+ apiBaseURL,
326
+ telemetryEnabled: cursorGetServerConfigTelemetryEnabled(),
327
+ }).catch(() => { });
311
328
  }
312
329
  return {
313
330
  ...(accessToken ? { accessToken } : {}),
package/dist/shared.d.ts CHANGED
@@ -1,4 +1,3 @@
1
- export declare const CURSOR_AGENT_HOST = "agentn.global.api5.cursor.sh";
2
1
  export declare const CURSOR_API_HOST = "api2.cursor.sh";
3
2
  export declare const CURSOR_WEBSITE_HOST = "cursor.com";
4
3
  export declare const FALLBACK_CLIENT_VERSION = "cli-2026.07.09-a3815c0";
@@ -6,6 +5,7 @@ export declare const CURSOR_PROVIDER_ID = "cursor";
6
5
  export declare const TOKEN_EXPIRY_THRESHOLD_S = 300;
7
6
  export declare const RUN_PATH = "/agent.v1.AgentService/Run";
8
7
  export declare const AVAILABLE_MODELS_PATH = "/aiserver.v1.AiService/AvailableModels";
8
+ export declare const SERVER_CONFIG_PATH = "/aiserver.v1.ServerConfigService/GetServerConfig";
9
9
  export declare const MODEL_CACHE_FILE = "cursor-models.json";
10
10
  export declare const MODEL_CACHE_TTL_MS = 86400000;
11
11
  export declare const VERSION_CACHE_FILE = "cursor-client-version.json";
package/dist/shared.js CHANGED
@@ -1,4 +1,3 @@
1
- export const CURSOR_AGENT_HOST = "agentn.global.api5.cursor.sh";
2
1
  export const CURSOR_API_HOST = "api2.cursor.sh";
3
2
  export const CURSOR_WEBSITE_HOST = "cursor.com";
4
3
  export const FALLBACK_CLIENT_VERSION = "cli-2026.07.09-a3815c0";
@@ -6,6 +5,7 @@ export const CURSOR_PROVIDER_ID = "cursor";
6
5
  export const TOKEN_EXPIRY_THRESHOLD_S = 300;
7
6
  export const RUN_PATH = "/agent.v1.AgentService/Run";
8
7
  export const AVAILABLE_MODELS_PATH = "/aiserver.v1.AiService/AvailableModels";
8
+ export const SERVER_CONFIG_PATH = "/aiserver.v1.ServerConfigService/GetServerConfig";
9
9
  export const MODEL_CACHE_FILE = "cursor-models.json";
10
10
  export const MODEL_CACHE_TTL_MS = 86_400_000;
11
11
  export const VERSION_CACHE_FILE = "cursor-client-version.json";
@@ -1,9 +1,35 @@
1
1
  export declare function trace(msg: string): void;
2
2
  export declare function buildBaseHeaders(token: string, clientVersion: string, extra?: Record<string, string>): Record<string, string>;
3
3
  export declare function unaryAvailableModels(token: string, options?: {
4
+ apiBaseURL?: string;
4
5
  baseURL?: string;
5
6
  headers?: Record<string, string>;
6
7
  }): Promise<Record<string, unknown>>;
8
+ /**
9
+ * Cursor Run stream hosts from GetServerConfig / agentBaseURL.
10
+ * Any HTTPS subdomain of cursor.sh is accepted — hostnames vary
11
+ * (agentn.*, agent.*, agent-gcpp-*, api5 / api5lat, …) and may change.
12
+ */
13
+ export declare function isAllowedAgentHost(hostname: string): boolean;
14
+ /**
15
+ * Normalize a GetServerConfig agent URL to an https origin.
16
+ * Returns null for missing, malformed, non-https, or non-*.cursor.sh hosts.
17
+ */
18
+ export declare function normalizeAgentRunOrigin(raw: string | undefined): string | null;
19
+ /**
20
+ * Fetch the Cursor server config (a Connect unary RPC on the API host) and
21
+ * return the `agentUrlConfig.agentnUrl` field — the region-specific Run stream
22
+ * origin the server routes this account/team to (e.g. `agentn.us.api5.cursor.sh`).
23
+ *
24
+ * Region-routed accounts can be silently rejected by the wrong regional host, so
25
+ * this lookup fails closed instead of substituting any host on error. Any
26
+ * authoritative `*.cursor.sh` origin from GetServerConfig is accepted.
27
+ */
28
+ export declare function fetchAgentUrl(token: string, options?: {
29
+ apiBaseURL?: string;
30
+ baseURL?: string;
31
+ telemetryEnabled?: boolean;
32
+ }): Promise<string>;
7
33
  export type BidiStream = {
8
34
  write(msg: Uint8Array): void;
9
35
  end(): void;
@@ -14,10 +40,10 @@ export type BidiStream = {
14
40
  destroy(): void;
15
41
  };
16
42
  /** Resolve the HTTP/2 connect origin for a Run stream (exported for tests). */
17
- export declare function resolveAgentOrigin(baseURL?: string): string;
18
- export declare function bidiRunStream(token: string, options?: {
43
+ export declare function resolveAgentOrigin(baseURL: string): string;
44
+ export declare function bidiRunStream(token: string, options: {
19
45
  signal?: AbortSignal;
20
- baseURL?: string;
46
+ baseURL: string;
21
47
  headers?: Record<string, string>;
22
48
  }): Promise<BidiStream>;
23
49
  export declare function makeRequestId(): string;
@@ -1,4 +1,4 @@
1
- import { CURSOR_API_HOST, CURSOR_AGENT_HOST, CONNECT_PROTOCOL_VERSION } from "../shared.js";
1
+ import { CURSOR_API_HOST, CONNECT_PROTOCOL_VERSION, SERVER_CONFIG_PATH } from "../shared.js";
2
2
  import { encodeFrame, streamFrames } from "../protocol/framing.js";
3
3
  import { createCursorChecksumHeader } from "../protocol/checksum.js";
4
4
  import { getDeviceIds } from "../protocol/device-id.js";
@@ -6,7 +6,9 @@ import { resolveClientVersion } from "../protocol/client-version.js";
6
6
  import http2 from "node:http2";
7
7
  import fs from "node:fs";
8
8
  const API_BASE = `https://${CURSOR_API_HOST}`;
9
- const AGENT = CURSOR_AGENT_HOST;
9
+ function resolveApiBaseURL(options) {
10
+ return new URL(options.apiBaseURL ?? options.baseURL ?? API_BASE).origin;
11
+ }
10
12
  // Wire-level diagnostics. Opt in with CURSOR_PROVIDER_DEBUG=1 (or "true").
11
13
  // Writes to CURSOR_PROVIDER_DEBUG_FILE (default /tmp/cursor-provider-debug.log).
12
14
  // Truncated once per process. Captures h2 response status, parsed frames, and
@@ -43,7 +45,7 @@ export function buildBaseHeaders(token, clientVersion, extra) {
43
45
  }
44
46
  // ── Unary (AvailableModels) ──
45
47
  export async function unaryAvailableModels(token, options = {}) {
46
- const base = options.baseURL ?? API_BASE;
48
+ const base = resolveApiBaseURL(options);
47
49
  const url = `${base}/aiserver.v1.AiService/AvailableModels`;
48
50
  const clientVersion = await resolveClientVersion();
49
51
  const headers = buildBaseHeaders(token, clientVersion, options.headers);
@@ -62,6 +64,82 @@ export async function unaryAvailableModels(token, options = {}) {
62
64
  }
63
65
  return (await res.json());
64
66
  }
67
+ // ── Unary (GetServerConfig) ──
68
+ /**
69
+ * Cursor Run stream hosts from GetServerConfig / agentBaseURL.
70
+ * Any HTTPS subdomain of cursor.sh is accepted — hostnames vary
71
+ * (agentn.*, agent.*, agent-gcpp-*, api5 / api5lat, …) and may change.
72
+ */
73
+ export function isAllowedAgentHost(hostname) {
74
+ return /^([a-z0-9-]+\.)+cursor\.sh$/i.test(hostname);
75
+ }
76
+ /**
77
+ * Normalize a GetServerConfig agent URL to an https origin.
78
+ * Returns null for missing, malformed, non-https, or non-*.cursor.sh hosts.
79
+ */
80
+ export function normalizeAgentRunOrigin(raw) {
81
+ if (raw === undefined || raw === null)
82
+ return null;
83
+ const trimmed = String(raw).trim();
84
+ if (!trimmed)
85
+ return null;
86
+ try {
87
+ const withScheme = /^https?:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`;
88
+ const parsed = new URL(withScheme);
89
+ if (parsed.protocol !== "https:")
90
+ return null;
91
+ if (parsed.username || parsed.password)
92
+ return null;
93
+ if (!isAllowedAgentHost(parsed.hostname))
94
+ return null;
95
+ return parsed.origin;
96
+ }
97
+ catch {
98
+ return null;
99
+ }
100
+ }
101
+ /**
102
+ * Fetch the Cursor server config (a Connect unary RPC on the API host) and
103
+ * return the `agentUrlConfig.agentnUrl` field — the region-specific Run stream
104
+ * origin the server routes this account/team to (e.g. `agentn.us.api5.cursor.sh`).
105
+ *
106
+ * Region-routed accounts can be silently rejected by the wrong regional host, so
107
+ * this lookup fails closed instead of substituting any host on error. Any
108
+ * authoritative `*.cursor.sh` origin from GetServerConfig is accepted.
109
+ */
110
+ export async function fetchAgentUrl(token, options = {}) {
111
+ const base = resolveApiBaseURL(options);
112
+ const url = `${base}${SERVER_CONFIG_PATH}`;
113
+ const clientVersion = await resolveClientVersion();
114
+ // Match Cursor CLI: GetServerConfig uses base headers only — session headers belong on Run.
115
+ const headers = buildBaseHeaders(token, clientVersion);
116
+ trace(`GetServerConfig POST ${url}`);
117
+ const res = await fetch(url, {
118
+ method: "POST",
119
+ headers: {
120
+ ...headers,
121
+ "content-type": "application/json",
122
+ accept: "application/json",
123
+ },
124
+ body: JSON.stringify({ telem_enabled: options.telemetryEnabled ?? false }),
125
+ });
126
+ if (!res.ok) {
127
+ const text = await res.text().catch(() => "");
128
+ throw new Error(`GetServerConfig failed: ${res.status} ${res.statusText}${text ? ` - ${text.slice(0, 200)}` : ""}`);
129
+ }
130
+ const body = (await res.json());
131
+ const cfg = body.agentUrlConfig;
132
+ const raw = cfg?.agentnUrl || cfg?.agentUrl;
133
+ const normalized = normalizeAgentRunOrigin(raw);
134
+ trace(`GetServerConfig reply: agentnUrl=${cfg?.agentnUrl ?? "<missing>"} ` +
135
+ `agentUrl=${cfg?.agentUrl ?? "<missing>"} → ${normalized ?? "<invalid>"}`);
136
+ if (!normalized) {
137
+ throw new Error(raw
138
+ ? "GetServerConfig returned an invalid Cursor agent URL"
139
+ : "GetServerConfig response missing agentUrlConfig.agentnUrl");
140
+ }
141
+ return normalized;
142
+ }
65
143
  // Cache http2 sessions keyed by origin so a custom baseURL never reuses a
66
144
  // connection opened to the default agent host — and vice versa.
67
145
  const _http2Sessions = new Map();
@@ -73,8 +151,11 @@ const _http2Connecting = new Map();
73
151
  const CONNECT_TIMEOUT_MS = 15_000;
74
152
  /** Resolve the HTTP/2 connect origin for a Run stream (exported for tests). */
75
153
  export function resolveAgentOrigin(baseURL) {
76
- // baseURL may be https://host or https://host:port — http2.connect accepts both.
77
- return (baseURL ? new URL(baseURL) : new URL(`https://${AGENT}`)).origin;
154
+ const origin = normalizeAgentRunOrigin(baseURL);
155
+ if (!origin) {
156
+ throw new Error("Cursor Run stream requires an allowlisted Cursor agent base URL");
157
+ }
158
+ return origin;
78
159
  }
79
160
  function dropSession(origin, session) {
80
161
  if (_http2Sessions.get(origin) === session)
@@ -133,7 +214,7 @@ function getSession(baseURL) {
133
214
  _http2Connecting.set(origin, promise);
134
215
  return promise;
135
216
  }
136
- export async function bidiRunStream(token, options = {}) {
217
+ export async function bidiRunStream(token, options) {
137
218
  const [session, clientVersion] = await Promise.all([
138
219
  getSession(options.baseURL),
139
220
  resolveClientVersion(),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cursor-opencode-provider",
3
- "version": "0.1.3",
3
+ "version": "0.1.4",
4
4
  "description": "Use Cursor subscription models from OpenCode via Cursor's Connect-RPC agent protocol",
5
5
  "type": "module",
6
6
  "license": "MIT",