Skip to content

Commit 2b12521

Browse files
authored
Merge pull request lidge-jun#1900 from yansigit/fix/cursor-wave1-dx
fix(cursor): nested tools, clean EOF, GetUsableModels probe, cmd/command
2 parents 2a9f083 + 1824a01 commit 2b12521

10 files changed

Lines changed: 402 additions & 14 deletions

‎src/adapters/cursor/live-models.ts‎

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ import { GetUsableModelsResponseSchema } from "./gen/agent_pb";
1919
const CURSOR_GET_USABLE_MODELS_PATH = "/agent.v1.AgentService/GetUsableModels";
2020
const CURSOR_DISCOVERY_CLIENT_VERSION = "cli-2026.02.13-41ac335";
2121
const CURSOR_MODEL_DISCOVERY_MAX_BYTES = 4 * 1024 * 1024;
22+
type CursorUsableModelsFetcher = (opts: CursorUsableModelsOptions) => Promise<CursorUsableModelsResult>;
23+
let cursorUsableModelsFetcherForTests: CursorUsableModelsFetcher | null = null;
2224

2325
export interface CursorUsableModelsOptions {
2426
apiKey: string;
@@ -31,6 +33,11 @@ export type CursorUsableModelsResult =
3133
| { ok: true; models: string[] }
3234
| { ok: false; error: "auth" | "http" | "transport" | "timeout" | "decode" | "empty" | "too_large"; detail?: string };
3335

36+
/** Test-only seam for management connectivity probes; production callers retain the HTTP/2 path. */
37+
export function setFetchCursorUsableModelsForTests(next: CursorUsableModelsFetcher | null): void {
38+
cursorUsableModelsFetcherForTests = next;
39+
}
40+
3441
const RETRYABLE_DISCOVERY_ERRORS = new Set(["timeout", "transport"]);
3542
const DISCOVERY_RETRY_TIMEOUT_MS = 3_000;
3643

@@ -42,10 +49,37 @@ const DISCOVERY_RETRY_TIMEOUT_MS = 3_000;
4249
* devlog 260723_cursor_context_continuity/030).
4350
*/
4451
export async function fetchCursorUsableModels(opts: CursorUsableModelsOptions): Promise<CursorUsableModelsResult> {
45-
const first = await fetchCursorUsableModelsOnce(opts);
52+
if (cursorUsableModelsFetcherForTests) return cursorUsableModelsFetcherForTests(opts);
53+
const resolved = resolveCursorDiscoveryBaseUrl(opts.baseUrl ?? "https://api2.cursor.sh");
54+
if (!resolved.ok) return resolved;
55+
const first = await fetchCursorUsableModelsOnce({ ...opts, baseUrl: resolved.baseUrl });
4656
if (first.ok || !RETRYABLE_DISCOVERY_ERRORS.has(first.error)) return first;
4757
await new Promise(resolve => setTimeout(resolve, 250 + Math.floor(Math.random() * 250)));
48-
return fetchCursorUsableModelsOnce({ ...opts, timeoutMs: Math.min(opts.timeoutMs ?? 8000, DISCOVERY_RETRY_TIMEOUT_MS) });
58+
return fetchCursorUsableModelsOnce({
59+
...opts,
60+
baseUrl: resolved.baseUrl,
61+
timeoutMs: Math.min(opts.timeoutMs ?? 8000, DISCOVERY_RETRY_TIMEOUT_MS),
62+
});
63+
}
64+
65+
function resolveCursorDiscoveryBaseUrl(raw: string): { ok: true; baseUrl: string } | Extract<CursorUsableModelsResult, { ok: false }> {
66+
const baseUrl = raw.replace(/\/+$/, "");
67+
let parsed: URL;
68+
try {
69+
parsed = new URL(baseUrl);
70+
} catch {
71+
return { ok: false, error: "transport", detail: "Cursor discovery URL is invalid" };
72+
}
73+
if (parsed.protocol === "https:") return { ok: true, baseUrl };
74+
// Local h2c fixtures (and an operator loopback proxy) never leave the machine.
75+
// Anything else with a Bearer token must be HTTPS, matching providerOutbound POST.
76+
if (parsed.protocol === "http:") {
77+
const host = parsed.hostname.replace(/^\[|\]$/g, "").toLowerCase();
78+
if (host === "127.0.0.1" || host === "::1" || host === "localhost" || host.endsWith(".localhost")) {
79+
return { ok: true, baseUrl };
80+
}
81+
}
82+
return { ok: false, error: "transport", detail: "Cursor discovery URL must use HTTPS" };
4983
}
5084

5185
async function fetchCursorUsableModelsOnce(opts: CursorUsableModelsOptions): Promise<CursorUsableModelsResult> {

‎src/adapters/cursor/live-transport.ts‎

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -428,6 +428,7 @@ class LiveCursorTransport implements CursorTransport {
428428
// close; safe to read after a stream failure because open() owns the only writer before run().
429429
private turnStartedAt = 0;
430430
private framesReceived = 0;
431+
private sawAssistantText = false;
431432
private firstFrameAt?: number;
432433
private firstFrameLogged = false;
433434
/** Stable session identifier sent as x-session-id; mirrors IDE session semantics. */
@@ -769,6 +770,7 @@ class LiveCursorTransport implements CursorTransport {
769770
): void {
770771
this.turnStartedAt = Date.now();
771772
this.framesReceived = 0;
773+
this.sawAssistantText = false;
772774
this.firstFrameAt = undefined;
773775
this.firstFrameLogged = false;
774776
const dialHost = cursorHostLabel(this.input.provider.baseUrl || "https://api2.cursor.sh");
@@ -1026,6 +1028,25 @@ class LiveCursorTransport implements CursorTransport {
10261028
settler.settleFail(new Error("Cursor stream ended before any response frame (unexpected EOF)"));
10271029
return;
10281030
}
1031+
if (state.terminated || this.expectedClose) {
1032+
releaseBacklogLease();
1033+
settler.settleFinish();
1034+
return;
1035+
}
1036+
// Open tools fail-closed as a truncation *event* (finalizeTurnEvents), not a thrown
1037+
// transport error. settleFail here would hide that typed message as adapter_eof.
1038+
if (state.openToolCalls.size > 0) {
1039+
for (const event of finalizeTurnEvents(state)) push(event);
1040+
releaseBacklogLease();
1041+
settler.settleFinish();
1042+
return;
1043+
}
1044+
if (this.framesReceived > 0 && this.sawAssistantText) {
1045+
for (const event of finalizeTurnEvents(state)) push(event);
1046+
releaseBacklogLease();
1047+
settler.settleFinish();
1048+
return;
1049+
}
10291050
releaseBacklogLease();
10301051
settler.settleFinish();
10311052
}, (err) => {
@@ -1087,7 +1108,10 @@ class LiveCursorTransport implements CursorTransport {
10871108
debugProviderDiagnostic("cursor", "interaction-query", { id: query.id, queryCase: query.query.case ?? "unknown", reply: plan.replyCase });
10881109
this.stream.write(encodeClientMessage({ message: { case: "interactionResponse", value: plan.response } }));
10891110
if (!state.terminated) {
1090-
if (plan.planText) push({ type: "text", text: plan.planText });
1111+
if (plan.planText) {
1112+
this.sawAssistantText = true;
1113+
push({ type: "text", text: plan.planText });
1114+
}
10911115
push({ type: "heartbeat" });
10921116
}
10931117
return;
@@ -1100,6 +1124,7 @@ class LiveCursorTransport implements CursorTransport {
11001124
const awaitedNativeArgsBeforeMapping = update?.case === "toolCallCompleted"
11011125
&& state.openToolCalls.get(update.value.callId)?.awaitingNativeArgs === true;
11021126
const mapped = mapCursorProtobufServerMessage(message, state);
1127+
if (mapped.some(event => event.type === "text")) this.sawAssistantText = true;
11031128
const beganAwaitingNativeClientToolArgs = update?.case === "toolCallCompleted"
11041129
&& !awaitedNativeArgsBeforeMapping
11051130
&& state.openToolCalls.get(update.value.callId)?.awaitingNativeArgs === true;

‎src/adapters/cursor/tool-definitions.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -525,7 +525,12 @@ export function nonEmptyShellBridgeCommandFromArgs(
525525
}
526526
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return undefined;
527527
const record = parsed as Record<string, unknown>;
528-
for (const key of shellBridgeRequiredCommandKeys(toolName, schema)) {
528+
const requiredKeys = shellBridgeRequiredCommandKeys(toolName, schema);
529+
const candidateKeys = new Set<"cmd" | "command">([
530+
...requiredKeys,
531+
requiredKeys.includes("cmd") ? "command" : "cmd",
532+
]);
533+
for (const key of candidateKeys) {
529534
const value = record[key];
530535
if (typeof value === "string" && value.trim().length > 0) return value.trim();
531536
}

‎src/responses/parser.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,10 @@ function buildTools(tools: unknown[] | undefined): OcxTool[] | undefined {
171171
};
172172
for (const t of tools) {
173173
if (!isObj(t)) continue;
174+
if (t.type === "function" && isObj(t.function) && typeof t.function.name === "string" && t.function.name.length > 0) {
175+
pushFn(t.function as Record<string, unknown>);
176+
continue;
177+
}
174178
if (t.type === "function" && typeof t.name === "string") {
175179
pushFn(t);
176180
} else if (t.type === "namespace" && Array.isArray(t.tools)) {

‎src/server/management/provider-routes.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ import { replaceProviderAccountSet } from "../../oauth/store";
3333
import { providerDestinationResolvedError } from "../../lib/destination-policy";
3434
import { reconcileLiveStateStores } from "../../lib/state-store-registrations";
3535
import { ProviderOutboundPolicyError, providerOutboundGet, providerOutboundPost, providerRedirectError } from "../../lib/provider-outbound";
36+
import { fetchCursorUsableModels } from "../../adapters/cursor/live-models";
3637
import { parseAntigravityAvailableModels } from "../../providers/antigravity-models";
3738
import { enrichProviderFromCatalog, listKeyLoginProviders } from "../../oauth/key-providers";
3839
import { deriveProviderPresets } from "../../providers/derive";
@@ -732,6 +733,27 @@ export async function handleProviderRoutes(ctx: ManagementContext): Promise<Resp
732733
if (prov.authMode === "oauth" && !apiKey) {
733734
return jsonResponse({ ok: false, latencyMs: 0, error: "static catalog only — upstream not verified (not logged in)" });
734735
}
736+
if (prov.adapter === "cursor") {
737+
const started = Date.now();
738+
const live = await fetchCursorUsableModels({
739+
apiKey: apiKey ?? "",
740+
baseUrl: prov.baseUrl,
741+
});
742+
const latencyMs = Date.now() - started;
743+
if (!live.ok) {
744+
return jsonResponse({
745+
ok: false,
746+
latencyMs,
747+
error: `cursor discovery ${live.error}${live.detail ? `: ${live.detail}` : ""}`,
748+
});
749+
}
750+
return jsonResponse({
751+
ok: true,
752+
latencyMs,
753+
models: live.models.length,
754+
message: `Connected. ${live.models.length} models.`,
755+
});
756+
}
735757
const project = prov.project ?? snapshot?.projectId;
736758
if (antigravity && !project) {
737759
return jsonResponse({ ok: false, latencyMs: 0, error: "Antigravity project unavailable — re-run `ocx login google-antigravity`" });

0 commit comments

Comments
 (0)