Skip to content

fix: resolve region-specific agentnUrl from GetServerConfig - #5

Merged
oakimov merged 3 commits into
oakimov:mainfrom
renaudcerrato:fix/resolve-agentn-url-from-server-config
Jul 16, 2026
Merged

oakimov merged 3 commits into
oakimov:mainfrom
renaudcerrato:fix/resolve-agentn-url-from-server-config

Conversation

@renaudcerrato

Copy link
Copy Markdown
Contributor

Context

The provider hardcoded the Run stream host as agentn.global.api5.cursor.sh (src/shared.ts). Cursor's server config now routes many accounts to a region-specific host (e.g. agentn.us.api5.cursor.sh). The global host silently rejects those accounts with HTTP 200 + an immediate stream close — no body, no trailers, no error event. The underlying message is "This region is not yet available for your team".

From the user's perspective this looks exactly like no response, no error — there is no way to diagnose or recover without changing the host.

Root cause

The Cursor CLI and IDE do not hardcode the agent host. They fetch it at runtime from aiserver.v1.ServerConfigService/GetServerConfig and read agentUrlConfig.agentnUrl. I confirmed this by reading the cached cursorai/serverConfig entry the IDE stores in state.vscdb, and by matching the service definition (typeName:"aiserver.v1.ServerConfigService", unary GetServerConfig) in the Cursor app bundle.

This provider was guessing a host that is no longer the one most accounts are routed to.

What changed

Resolve the Run stream origin the same way the CLI/IDE do, and cache it like the existing models cache:

  • src/transport/connect.ts — new fetchAgentUrl() unary RPC (Connect JSON, same header pattern as unaryAvailableModels) that returns agentUrlConfig.agentnUrl (falls back to agentUrl, then to the hardcoded CURSOR_AGENT_HOST if the field is missing).
  • src/agent-url.ts (new) — discoverAgentUrl() mirroring discoverModels(): fresh cache → return + fire-and-forget background refresh; stale/missing → await fetch + write; fetch fails → serve stale cache, else fall back to the hardcoded host. Never throws. Reuses MODEL_CACHE_TTL_MS (24h) — region routing is near-static, so no new TTL.
  • src/language-model.ts — startSession() resolves agentBaseUrl = options.baseURL ?? await resolveAgentUrl(token) before opening the bidi stream. resolveAgentUrl is memoized per process (_resolvedAgentUrl) so subsequent turns never hit GetServerConfig again and a mid-session region change can't break a held-open Run stream.
  • src/plugin.ts — auth.loader calls await discoverAgentUrl(accessToken, cacheDir).catch(() => {}) right after the existing discoverModels call, so the first turn never has to pay the resolution latency.
  • src/shared.ts — SERVER_CONFIG_PATH and AGENT_URL_CACHE_FILE constants.
  • README.md — documents the resolution flow, the new cache file, and adds a troubleshooting row for the silent 200 + close symptom.

Critical changes

  • New network call on login / first turn. GetServerConfig is a unary Connect RPC on the existing API host (api2.cursor.sh) using the same auth headers as AvailableModels. It adds one round-trip at startup (same cost as model discovery, which already happens there). On the direct-SDK path (createCursor() without the plugin) it happens on the first doStream.
  • Behavior preserved on failure. If GetServerConfig is unreachable, returns no agentUrlConfig, or the cache is missing, the provider falls back to https://agentn.global.api5.cursor.sh — identical to today's behavior. The fix only changes behavior when the endpoint is reachable.
  • Explicit baseURL override still wins. createCursor({ baseURL }) and CURSOR_API_BASE_URL are untouched; the resolution only fills the default when no override is set.
  • No mid-session migration. The URL is resolved once per process and pinned. If Cursor migrated your account to a new region mid-session, the held-open Run stream would continue against the old host until the next process restart — this is intentional (switching origins would break the in-flight bidi stream).

Expected behavior

Before After
Run stream to agentn.global.api5.cursor.sh → 200 + immediate close, no response, no error Run stream to the account's region-specific host (e.g. agentn.us.api5.cursor.sh) → full turn (text deltas, tool calls, turn_ended)
No way to diagnose (silent close, no error event) Debug log shows x-cursor-server-region: us-east-1; cache file shows the resolved URL

Verification

  • bun run typecheck ✅
  • bun run build ✅
  • bun test — 256 pass, 0 fail (249 existing + 7 new in test/agent-url.test.ts)
  • Live: reproduced the silent-close failure first (no baseURL override), then confirmed the fix produces a full turn. Debug log excerpt:
h2 response: status=200 ... "x-cursor-server-region":"us-east-1"
pump frame: ... interaction_update=text_delta
pump frame: ... interaction_update=turn_ended
h2 stream closed (status=200, err=none)

Cache file written: ~/.cache/opencode/cursor-agent-url.json → {"agentnUrl":"https://agentn.us.api5.cursor.sh","fetchedAt":...}

Notes

  • This is the same root cause and fix shape as the one the Cursor CLI itself relies on; it is not a reverse-engineered guess.
  • The GetServerConfig request body {"telem_enabled": true} is the minimal valid input (matches the CLI's GetServerConfigRequest field Resolve client version at runtime #1); the response field we read (agentUrlConfig.agentnUrl) is stable across the IDE and CLI clients.

renaudcerrato and others added 2 commits July 16, 2026 09:04
The provider hardcoded the Run stream host as agentn.global.api5.cursor.sh.
Cursor's server config now routes many accounts to a region-specific host
(e.g. agentn.us.api5.cursor.sh); the global host silently rejects them with
HTTP 200 + an immediate stream close (no body, no trailers) — the underlying
error is "This region is not yet available for your team". The result was no
response, no error, and no way to recover.

Resolve the host the same way the Cursor CLI and IDE do: fetch it from the
aiserver.v1.ServerConfigService/GetServerConfig unary RPC and read
agentUrlConfig.agentnUrl. Cache it under ~/.cache/opencode/cursor-agent-url.json
(24h TTL, same pattern as the models cache) and refresh on login + first turn.
Fall back to the hardcoded CURSOR_AGENT_HOST on any failure so behavior is
preserved when the endpoint is unreachable.

An explicit createCursor({ baseURL }) override still wins, and the URL is
memoized per process so a mid-session region change never breaks a held-open
Run stream.

Verified live: debug log shows x-cursor-server-region: us-east-1 and a full
text_delta + turn_ended turn against the resolved host.
Require allowlisted agentn hosts from GetServerConfig (or explicit override), keep the result in-process only, and fail clearly instead of falling back to agentn.global.
@oakimov

oakimov commented Jul 16, 2026

Copy link
Copy Markdown
Owner

Follow-up pushed (34df18a)

Hardening pass on top of the original GetServerConfig fix:

  • In-process memo only — drop on-disk cursor-agent-url.json; resolve once per process and reuse (no mid-session repoint of a held-open Run stream).
  • Fail closed — if GetServerConfig fails or returns a non-allowlisted host, the model call errors instead of soft-falling back to agentn.global.api5.cursor.sh.
  • Prod allowlist — Run hosts must be HTTPS agentn.*.api5.cursor.sh; local/staging/non-api5 overrides are rejected.
  • Split config — apiBaseURL (auth / models / GetServerConfig) vs agentBaseURL (explicit Run host); legacy baseURL kept as alias for agentBaseURL.
  • Telemetry opt-in — GetServerConfig sends { "telem_enabled": false } by default; opt in via telemetryEnabled: true or CURSOR_GET_SERVER_CONFIG_TELEMETRY=1.
  • Headers — custom createCursor({ headers }) apply to the bidi Run stream only; GetServerConfig uses buildBaseHeaders alone.
  • Docs/tests updated to match (README.md, test/agent-url.test.ts, test/connect-origin.test.ts, test/plugin.test.ts).

Cursor GetServerConfig returns more host shapes than agentn.*.api5
(agent.*, agent-gcpp-*, api5lat, …). Keep fail-closed for non-cursor.sh
origins without rejecting valid regional Run hosts.
@oakimov

oakimov commented Jul 16, 2026

Copy link
Copy Markdown
Owner

Follow-up pushed (bc632e1)

Widened the agent Run host allowlist after the hardening pass.

Why: GetServerConfig does not only return agentn.<region>.api5.cursor.sh. Live responses also use other Cursor host shapes (agent.*, agent-gcpp-*, api5lat, …), and those names can change. The previous regex was production-shaped but too narrow — a valid regional URL from Cursor would fail closed the same way a bad host does.

What changed:

  • Accept any HTTPS subdomain of cursor.sh (*.cursor.sh), still origin-only (path/query/fragment stripped).
  • Still reject non-cursor.sh hosts, plain http, apex cursor.sh, and lookalikes like cursor.sh.evil.com.
  • Fail-closed on lookup failure / invalid config is unchanged — we still never soft-fallback to agentn.global.
  • Docs + tests updated for the broader host set (agent-gcpp-*, api5lat, etc.).

This keeps the security intent (do not open Run against arbitrary origins) without boxing out legitimate Cursor-returned agent hosts.

@oakimov
oakimov merged commit 096593e into oakimov:main Jul 16, 2026
oakimov added a commit that referenced this pull request Aug 1, 2026
)

Two independent faults from issue #18.

Fault A — write/edit unavailable on GPT models.

OpenCode 1.x does not merely add `apply_patch` for GPT models, it removes
`edit` and `write` from the catalog in exchange (`ToolRegistry.tools`:
modelID contains "gpt-" and neither "oss" nor "gpt-4"). Cursor keeps sending
its native write/edit exec requests regardless, so every file change was
refused as an unavailable tool.

`remapEditToolsForCatalog` translates those requests into `apply_patch`
envelopes: a whole-file write becomes `*** Add File:` (which overwrites, per
opencode's own tests, so no diff is needed), and a substring edit is widened
to whole lines because apply_patch matches line sequences. Unreadable,
absent, ambiguous or overlapping edits are refused with a specific message
rather than patched into the wrong region.

Keyed only off the advertised tool set — never a model id or host version —
so it is inert on hosts that offer edit/write normally, and inert again on
OpenCode 2.0, which has no such substitution. Advertisement needed no change:
`opencode-apply_patch` was already forwarded to Cursor verbatim; only the
native exec channel was untranslated.

Fault B — large files silently truncated at ~50 KB.

The truncation is on the read, not the write. Opencode's read tool caps at
`MAX_BYTES = 50 * 1024`, cuts on a whole-line boundary, and appends a footer
saying so; `unwrapReadOutput` stripped that footer along with the envelope.
The model then treated a capped read as the complete file and rewrote it,
destroying everything past the cap.

The envelope is still stripped byte-for-byte — echoing wrappers into writes
remains the reason it exists — but the cap is now re-stated: native
`read_result` appends a `[Partial read: …]` marker, `mcp_result` gets a
separate notice item, and Pi reads carry structured
`PiReadExecSuccess.truncation`. Reads the caller bounded itself with an
explicit offset/limit are not marked.

The structured `truncated` flag was already being sent and is not sufficient
on its own: in live sessions both gpt-5.4-mini and grok-4.5 asserted "highly
confident" that partial content was the whole file until the textual marker
was added.

Also decodes `WriteArgs.file_bytes` (#5) and `encoding_hint` (#6), which the
schema omitted and an internal-keys filter discarded. Cursor's own executor
prefers bytes when non-empty, so a byte-encoded write would have decoded as
empty content.

Verified end-to-end against OpenCode 1.18.9 with cursor/gpt-5.4-mini and
cursor/grok-4.5.
nkoynov added a commit to nkoynov/cursor-opencode-provider that referenced this pull request Oct 5, 2026
When the model reads an image with OpenCode's `read` tool, OpenCode
answers with "Image read successfully" and moves the image into a
trailing `Attached media from tool result:` user message (third-party
providers are not on its media-in-tool-result allowlist). The provider
skipped that message when locating the live tool results and encoded the
read as text, so the model got only the placeholder and saw the image,
if at all, as a history image on the next user turn. Models then guessed
or fell back to decoding the file in the shell.

Cursor's own read executor answers an image file with its bytes in
`ReadSuccess.data` (oakimov#5, already declared in messages.ts) and no text.
Do the same on held-Run continuations: keep the media parts of the
trailing message (and a result's own `file-data` parts) and attribute
them in result order. One result takes all of them; with several, each
media read ("Image read successfully") takes one part, results OpenCode
replaced with "Media attached in the following user message." take the
rest, and media no placeholder settles rides on the last result, as host
notes already do. Decode them with the existing image-input helpers and
encode a successful `read_result` with `data` instead of `content`.
Delivered images are added to the session's sent history-image hashes so
the next fresh Run does not attach them again. Results without an image
field keep the existing history path; models without image support are
unchanged.
oakimov pushed a commit to nkoynov/cursor-opencode-provider that referenced this pull request Oct 7, 2026
When the model reads an image with OpenCode's `read` tool, OpenCode
answers with "Image read successfully" and moves the image into a
trailing `Attached media from tool result:` user message (third-party
providers are not on its media-in-tool-result allowlist). The provider
skipped that message when locating the live tool results and encoded the
read as text, so the model got only the placeholder and saw the image,
if at all, as a history image on the next user turn. Models then guessed
or fell back to decoding the file in the shell.

Cursor's own read executor answers an image file with its bytes in
`ReadSuccess.data` (oakimov#5, already declared in messages.ts) and no text.
Do the same on held-Run continuations: keep the media parts of the
trailing message (and a result's own `file-data` parts) and attribute
them in result order. One result takes all of them; with several, each
media read ("Image read successfully") takes one part, results OpenCode
replaced with "Media attached in the following user message." take the
rest, and media no placeholder settles rides on the last result, as host
notes already do. Decode them with the existing image-input helpers and
encode a successful `read_result` with `data` instead of `content`.
Delivered images are added to the session's sent history-image hashes so
the next fresh Run does not attach them again. Results without an image
field keep the existing history path; models without image support are
unchanged.
oakimov added a commit that referenced this pull request Oct 8, 2026
* fix: return images read on a held Run as ReadSuccess.data

When the model reads an image with OpenCode's `read` tool, OpenCode
answers with "Image read successfully" and moves the image into a
trailing `Attached media from tool result:` user message (third-party
providers are not on its media-in-tool-result allowlist). The provider
skipped that message when locating the live tool results and encoded the
read as text, so the model got only the placeholder and saw the image,
if at all, as a history image on the next user turn. Models then guessed
or fell back to decoding the file in the shell.

Cursor's own read executor answers an image file with its bytes in
`ReadSuccess.data` (#5, already declared in messages.ts) and no text.
Do the same on held-Run continuations: keep the media parts of the
trailing message (and a result's own `file-data` parts) and attribute
them in result order. One result takes all of them; with several, each
media read ("Image read successfully") takes one part, results OpenCode
replaced with "Media attached in the following user message." take the
rest, and media no placeholder settles rides on the last result, as host
notes already do. Decode them with the existing image-input helpers and
encode a successful `read_result` with `data` instead of `content`.
Delivered images are added to the session's sent history-image hashes so
the next fresh Run does not attach them again. Results without an image
field keep the existing history path; models without image support are
unchanged.

* fix: harden held-Run read images and result delivery

* fix: preserve recovery image and reopened Run identity

---------

Co-authored-by: oakimov <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants