685 lines
28 KiB
TypeScript
685 lines
28 KiB
TypeScript
#!/usr/bin/env bun
|
|
/**
|
|
* claude-cursor — drop-in replacement for
|
|
* `claude -p <prompt> --output-format stream-json --verbose \
|
|
* --dangerously-skip-permissions [--add-dir X] [--session-id|--resume U]`
|
|
* that runs Cursor's `cursor-agent` instead of Claude Code, while emitting the
|
|
* SAME Claude stream-json line shape on stdout. Every downstream consumer in the
|
|
* satellite (session.log tailer, the STATUS/ASSESSMENT sentinel parser in the
|
|
* runners/evaluators, the client-side LogPanel, asking's event normaliser) reads
|
|
* that shape, so swapping the engine here keeps log-return and per-task
|
|
* association fully compatible.
|
|
*
|
|
* Why a translator is needed: cursor-agent's `--output-format stream-json` is
|
|
* close to Claude's but not identical. Notably it emits tool calls and thinking
|
|
* as their OWN top-level frames:
|
|
* {"type":"tool_call","subtype":"started","call_id","tool_call":{…}}
|
|
* {"type":"tool_call","subtype":"completed","call_id","tool_call":{…}}
|
|
* {"type":"thinking","subtype":"delta"|"completed","text"}
|
|
* whereas Claude (and thus our consumers) expect those FOLDED INTO message
|
|
* content: a `tool_use` block inside an `assistant` frame, a `tool_result` block
|
|
* inside a `user` frame, and a `thinking` block inside an `assistant` frame.
|
|
* This wrapper performs that folding. Text + result frames are already
|
|
* Claude-shaped and pass through (with session_id normalised).
|
|
*
|
|
* Arg mapping (claude → cursor):
|
|
* -p <prompt> positional prompt (cursor's -p is a bare
|
|
* --print boolean, so the prompt moves to a
|
|
* positional and --print is added)
|
|
* --output-format stream-json --output-format stream-json (kept)
|
|
* --verbose / --remote-control X dropped (no cursor equivalent)
|
|
* --dangerously-skip-permissions --force --trust --approve-mcps
|
|
* --add-dir X --add-dir X (same flag)
|
|
* --session-id U (first turn) create-chat → chatId, persist U→chatId,
|
|
* run --resume chatId
|
|
* --resume U (later turns) look up U→chatId, run --resume chatId
|
|
*
|
|
* The U→chatId map is a per-uuid sidecar file so the resumable asking session
|
|
* survives across the fresh process each turn spawns.
|
|
*
|
|
* Env knobs:
|
|
* CURSOR_BIN cursor-agent binary (default "cursor-agent")
|
|
* STREAMLINE_CURSOR_MODEL --model to pass (e.g. "claude-opus-4-8[context=1m]")
|
|
* CURSOR_BRIDGE_DIR where U→chatId sidecars live
|
|
* (default ~/.cursor-agent-bridge)
|
|
* CLAUDE_CURSOR_DEBUG=1 mirror raw cursor-agent stdout/stderr to stderr
|
|
*/
|
|
|
|
import { spawn, spawnSync, type Subprocess } from "bun";
|
|
import {
|
|
existsSync, mkdirSync, readFileSync, writeFileSync,
|
|
} from "node:fs";
|
|
import { homedir } from "node:os";
|
|
import path from "node:path";
|
|
import { randomUUID } from "node:crypto";
|
|
import { CursorCliDiagnosticBuffer, redactCursorCliDiagnostic } from "../satellite/src/security_telemetry/cursor_cli_diagnostics";
|
|
import { isCursorApiKeyMode } from "../satellite/src/security_telemetry/agent_account_gate";
|
|
import {
|
|
AGENT_SESSION_FILE_ENV,
|
|
AGENT_SESSION_KIND_ENV,
|
|
mappedAgentSessionIdFromEnv,
|
|
recordAgentSessionIdFromEnv,
|
|
} from "../shared/src/agent_session";
|
|
|
|
const CURSOR_BIN = process.env.CURSOR_BIN || "cursor-agent";
|
|
const CURSOR_MODEL = process.env.STREAMLINE_CURSOR_MODEL || "";
|
|
const BRIDGE_DIR = process.env.CURSOR_BRIDGE_DIR || path.join(homedir(), ".cursor-agent-bridge");
|
|
const DEBUG = process.env.CLAUDE_CURSOR_DEBUG === "1";
|
|
|
|
function dbg(msg: string) {
|
|
if (DEBUG) console.error(`[claude-cursor] ${msg}`);
|
|
}
|
|
|
|
// Same automation instruction the PTY wrapper injects, but prepended to the
|
|
// prompt (cursor-agent has no --append-system-prompt). Only used for headless
|
|
// runs; the human-in-the-loop asking session must NOT be told "nobody is
|
|
// watching", so we skip it there (see `isAsking`).
|
|
const AUTOMODE_SYSPROMPT = [
|
|
"本会话运行在无人值守的自动化流水线中,没有任何人类在观看或会作出回应。",
|
|
"绝对禁止以提问等待用户回复的方式中断任务;",
|
|
"如必须在多个方案中取舍,直接采用你推荐的(或第一个可行的)方案并继续执行,事后在输出中说明即可。",
|
|
"任务必须自主推进到完成。",
|
|
].join("");
|
|
|
|
// ── arg parsing ────────────────────────────────────────────────────────────
|
|
interface ParsedArgs {
|
|
prompt: string;
|
|
addDirs: string[];
|
|
sessionUuid: string | null; // --session-id (first turn of a resumable session)
|
|
resumeUuid: string | null; // --resume (later turns)
|
|
appendSys: string | null; // --append-system-prompt (folded into prompt)
|
|
model: string | null; // --model override from caller
|
|
}
|
|
|
|
function parseArgs(argv: string[]): ParsedArgs {
|
|
const addDirs: string[] = [];
|
|
let prompt: string | null = null;
|
|
let sessionUuid: string | null = null;
|
|
let resumeUuid: string | null = null;
|
|
let appendSys: string | null = null;
|
|
let model: string | null = null;
|
|
|
|
// claude flags whose VALUE we must consume but otherwise ignore for cursor.
|
|
const DROP_WITH_VALUE = new Set([
|
|
"--output-format", "--input-format", "--fallback-model",
|
|
"--max-budget-usd", "--json-schema", "--settings",
|
|
]);
|
|
const DROP_BARE = new Set([
|
|
"--verbose", "--print", "--include-partial-messages",
|
|
"--replay-user-messages", "--no-session-persistence",
|
|
"--dangerously-skip-permissions",
|
|
]);
|
|
|
|
for (let i = 0; i < argv.length; i++) {
|
|
const a = argv[i];
|
|
if (a === "-p" || a === "--print") {
|
|
const next = argv[i + 1];
|
|
if (next !== undefined && !next.startsWith("-")) { prompt = next; i++; }
|
|
continue;
|
|
}
|
|
if (a === "--add-dir") { const v = argv[++i]; if (v) addDirs.push(v); continue; }
|
|
if (a === "--session-id") { sessionUuid = argv[++i] ?? null; continue; }
|
|
if (a === "--resume") { resumeUuid = argv[++i] ?? null; continue; }
|
|
if (a === "--append-system-prompt") { appendSys = argv[++i] ?? null; continue; }
|
|
if (a === "--model") { model = argv[++i] ?? null; continue; }
|
|
if (a === "--remote-control") { i++; continue; }
|
|
if (DROP_BARE.has(a)) continue;
|
|
if (DROP_WITH_VALUE.has(a)) { i++; continue; }
|
|
if (DROP_WITH_VALUE.has(a.split("=")[0])) continue;
|
|
if (!a.startsWith("-") && prompt === null) { prompt = a; continue; }
|
|
// Anything else is an unknown flag: drop it rather than forward — cursor's
|
|
// commander aborts hard on unrecognised options.
|
|
dbg(`dropping unrecognised arg: ${a}`);
|
|
}
|
|
|
|
if (prompt === null) {
|
|
console.error("claude-cursor: no prompt found in args");
|
|
process.exit(2);
|
|
}
|
|
return { prompt, addDirs, sessionUuid, resumeUuid, appendSys, model };
|
|
}
|
|
|
|
// ── U→chatId session bridge ─────────────────────────────────────────────────
|
|
function sidecarPath(uuid: string): string {
|
|
return path.join(BRIDGE_DIR, `${uuid}.chat`);
|
|
}
|
|
function readChatId(uuid: string): string | null {
|
|
const managed = mappedAgentSessionIdFromEnv("cursor", uuid);
|
|
if (managed) return managed;
|
|
try {
|
|
const p = sidecarPath(uuid);
|
|
if (existsSync(p)) { const s = readFileSync(p, "utf8").trim(); if (s) return s; }
|
|
} catch { /* fall through */ }
|
|
return null;
|
|
}
|
|
function writeChatId(uuid: string, chatId: string): void {
|
|
recordAgentSessionIdFromEnv("cursor", chatId);
|
|
try {
|
|
mkdirSync(BRIDGE_DIR, { recursive: true });
|
|
writeFileSync(sidecarPath(uuid), chatId, "utf8");
|
|
} catch (e) { dbg(`could not persist chat id: ${(e as Error).message}`); }
|
|
}
|
|
|
|
/** `cursor-agent create-chat` prints a new empty chat's id. Parse it out. */
|
|
function createChat(): string | null {
|
|
try {
|
|
const p = spawnSync({ cmd: [CURSOR_BIN, "create-chat"], stdout: "pipe", stderr: "pipe" });
|
|
const out = (p.stdout?.toString() || "").trim();
|
|
if (!out) { dbg(`create-chat produced no output (stderr: ${p.stderr?.toString().trim()})`); return null; }
|
|
// Prefer a JSON payload if cursor ever wraps it; else take the last id-ish token.
|
|
try {
|
|
const j = JSON.parse(out) as Record<string, unknown>;
|
|
const id = (j.chatId || j.id || j.chat_id) as string | undefined;
|
|
if (id) return id;
|
|
} catch { /* not json */ }
|
|
const tokens = out.split(/\s+/).filter((t) => /^[\w-]{6,}$/.test(t));
|
|
return tokens.length ? tokens[tokens.length - 1] : out;
|
|
} catch (e) {
|
|
dbg(`create-chat failed: ${(e as Error).message}`);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/** Security must not wait indefinitely for a CLI that has already printed its ID. */
|
|
async function createSecurityChat(): Promise<string> {
|
|
const proc = spawn({ cmd: [CURSOR_BIN, "create-chat"], stdin: "ignore", stdout: "pipe", stderr: "pipe" });
|
|
const diagnostics = new CursorCliDiagnosticBuffer();
|
|
const stderrDone = (async () => {
|
|
const decoder = new TextDecoder();
|
|
for await (const chunk of proc.stderr) diagnostics.append(decoder.decode(chunk, { stream: true }));
|
|
diagnostics.append(decoder.decode());
|
|
})().catch(() => {});
|
|
let timedOut = false;
|
|
let timer: ReturnType<typeof setTimeout>;
|
|
const deadline = new Promise<never>((_, reject) => {
|
|
timer = setTimeout(() => {
|
|
timedOut = true;
|
|
try { proc.kill(); } catch { /* already exited */ }
|
|
reject(new Error("Cursor create-chat did not return a session ID within 30s"));
|
|
}, 30_000);
|
|
});
|
|
const reader = proc.stdout.getReader();
|
|
let id: string | null = null;
|
|
let output = "";
|
|
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
const parseId = (line: string): string | null => {
|
|
const text = line.trim();
|
|
if (uuid.test(text)) return text;
|
|
try {
|
|
const value = JSON.parse(text) as Record<string, unknown>;
|
|
const candidate = value.chatId ?? value.id ?? value.chat_id;
|
|
return typeof candidate === "string" && uuid.test(candidate) ? candidate : null;
|
|
} catch { return null; }
|
|
};
|
|
try {
|
|
const decoder = new TextDecoder();
|
|
while (!id) {
|
|
const { value, done } = await Promise.race([reader.read(), deadline]);
|
|
output += decoder.decode(value, { stream: !done });
|
|
if (output.length > 16_384) throw new Error("Cursor create-chat output exceeded the expected size");
|
|
let end: number;
|
|
while ((end = output.indexOf("\n")) >= 0) {
|
|
id = parseId(output.slice(0, end));
|
|
output = output.slice(end + 1);
|
|
if (id) break;
|
|
}
|
|
if (done) { id ||= parseId(output); break; }
|
|
}
|
|
if (id) {
|
|
// The CLI writes the ID before its cleanup. Give cleanup a moment, but
|
|
// don't let a retained Node handle block this task for an hour.
|
|
const code = await Promise.race([proc.exited, Bun.sleep(1_000).then(() => null)]);
|
|
if (code !== null && code !== 0) {
|
|
await Promise.race([stderrDone, Bun.sleep(1_000)]);
|
|
throw new Error(diagnostics.text() || `Cursor create-chat exited with code ${code}`);
|
|
}
|
|
if (code === null) { try { proc.kill(); } catch { /* already exited */ } }
|
|
}
|
|
const exitCode = await Promise.race([proc.exited, Bun.sleep(1_000).then(() => null)]);
|
|
if (exitCode === null) { try { proc.kill("SIGKILL"); } catch { /* already exited */ } await proc.exited; }
|
|
await Promise.race([stderrDone, Bun.sleep(1_000)]);
|
|
if (!id) throw new Error(diagnostics.text() || (timedOut
|
|
? "Cursor create-chat did not return a session ID within 30s"
|
|
: `Cursor create-chat did not return a valid session ID (exit ${exitCode ?? "unknown"})`));
|
|
return id;
|
|
} finally {
|
|
clearTimeout(timer!);
|
|
try { reader.releaseLock(); } catch { /* a timed-out read may still be pending */ }
|
|
if (proc.exitCode === null && proc.signalCode === null) {
|
|
try { proc.kill("SIGKILL"); } catch { /* already exited */ }
|
|
}
|
|
}
|
|
}
|
|
|
|
/** Resolve the cursor chat id to --resume for this run, honouring the asking
|
|
* session's own uuid. Returns null for a plain headless one-shot (fresh chat). */
|
|
async function resolveChatId(a: ParsedArgs): Promise<string | null> {
|
|
const create = () => isSecurityTask ? createSecurityChat() : Promise.resolve(createChat());
|
|
if (a.resumeUuid) {
|
|
const existing = readChatId(a.resumeUuid);
|
|
if (existing) return existing;
|
|
// Asked to resume a session we have no mapping for (e.g. bridge dir wiped):
|
|
// start a fresh chat and remember it so subsequent turns stay coherent.
|
|
dbg(`no chat id mapped for resume uuid ${a.resumeUuid}; creating a fresh chat`);
|
|
const created = await create();
|
|
if (created) writeChatId(a.resumeUuid, created);
|
|
return created;
|
|
}
|
|
if (a.sessionUuid) {
|
|
const created = await create();
|
|
if (created) writeChatId(a.sessionUuid, created);
|
|
return created;
|
|
}
|
|
// Headless runner calls have no stable outer uuid, but we still want an
|
|
// actual chat id so an idle-timeout restart can `--resume` the same session.
|
|
return create();
|
|
}
|
|
|
|
// ── Claude stream-json emission ─────────────────────────────────────────────
|
|
const t0 = Date.now();
|
|
function emit(obj: Record<string, unknown>) {
|
|
process.stdout.write(JSON.stringify(obj) + "\n");
|
|
}
|
|
|
|
const parsed = parseArgs(process.argv.slice(2));
|
|
const isManagedRun = Boolean(process.env[AGENT_SESSION_FILE_ENV]?.trim());
|
|
const isSecurityTask = process.env[AGENT_SESSION_KIND_ENV] === "security";
|
|
const isAsking = !isManagedRun && !!(parsed.sessionUuid || parsed.resumeUuid);
|
|
// Stable session id for every emitted frame: the caller's uuid when it has one
|
|
// (keeps a task's logs coherent across turns), else filled from cursor's init.
|
|
let outSid = parsed.resumeUuid || parsed.sessionUuid || "";
|
|
let emittedInit = false;
|
|
|
|
// ── cursor → claude frame translation ───────────────────────────────────────
|
|
// Cursor streams assistant text and thinking as deltas; buffer them and flush a
|
|
// single consolidated block so a STATUS sentinel can't be split across frames
|
|
// and the LogPanel shows whole messages (parity with `claude -p`).
|
|
let pendingText = "";
|
|
let pendingTextCall = "";
|
|
let pendingThink = "";
|
|
let numTurns = 0;
|
|
let finalized = false;
|
|
let sawResult = false;
|
|
let lastError = "";
|
|
|
|
function emitAssistantText(text: string) {
|
|
if (!text.trim()) return;
|
|
numTurns++;
|
|
emit({
|
|
type: "assistant",
|
|
message: { role: "assistant", content: [{ type: "text", text }] },
|
|
session_id: outSid,
|
|
parent_tool_use_id: null,
|
|
uuid: randomUUID(),
|
|
});
|
|
}
|
|
|
|
function flushText() {
|
|
if (!pendingText.trim()) { pendingText = ""; pendingTextCall = ""; return; }
|
|
emitAssistantText(pendingText);
|
|
pendingText = "";
|
|
pendingTextCall = "";
|
|
}
|
|
|
|
function flushThink() {
|
|
if (!pendingThink.trim()) { pendingThink = ""; return; }
|
|
emit({
|
|
type: "assistant",
|
|
message: { role: "assistant", content: [{ type: "thinking", thinking: pendingThink }] },
|
|
session_id: outSid,
|
|
parent_tool_use_id: null,
|
|
uuid: randomUUID(),
|
|
});
|
|
pendingThink = "";
|
|
}
|
|
|
|
// Cursor nests the real payload under a single kind-specific key, e.g.
|
|
// tool_call: { readToolCall: { args:{…}, result:{ success|error:{…} } },
|
|
// toolCallId, startedAtMs, completedAtMs }
|
|
// So we locate the `<kind>ToolCall` sub-object and read args/result from it.
|
|
const KIND_NAME: Record<string, string> = {
|
|
read: "Read", write: "Write", edit: "Edit", searchReplace: "Edit",
|
|
multiEdit: "MultiEdit", ls: "LS", list: "LS", grep: "Grep", glob: "Glob",
|
|
shell: "Bash", terminal: "Bash", runTerminalCommand: "Bash",
|
|
delete: "Delete", todoWrite: "TodoWrite", webSearch: "WebSearch",
|
|
fetch: "WebFetch", codebaseSearch: "Search",
|
|
};
|
|
function findKind(tc: Record<string, any>): { kind: string; inner: Record<string, any> } {
|
|
for (const [k, v] of Object.entries(tc)) {
|
|
if (k.endsWith("ToolCall") && v && typeof v === "object") {
|
|
return { kind: k.slice(0, -"ToolCall".length), inner: v as Record<string, any> };
|
|
}
|
|
}
|
|
return { kind: "", inner: {} };
|
|
}
|
|
function toolName(kind: string): string {
|
|
if (!kind) return "tool";
|
|
return KIND_NAME[kind] || (kind[0].toUpperCase() + kind.slice(1));
|
|
}
|
|
|
|
/** Map cursor's nested tool_call → Claude's {name, input}. LogPanel renders the
|
|
* name plus the input entries; the fix runner never parses these. */
|
|
function deriveToolUse(ev: any): { id: string; name: string; input: Record<string, unknown> } {
|
|
const tc = (ev.tool_call || {}) as Record<string, any>;
|
|
const id = String(ev.call_id ?? tc.toolCallId ?? randomUUID());
|
|
const { kind, inner } = findKind(tc);
|
|
const input = (inner.args && typeof inner.args === "object") ? inner.args
|
|
: (inner.rawArgs && typeof inner.rawArgs === "object") ? inner.rawArgs
|
|
: {};
|
|
return { id, name: toolName(kind), input };
|
|
}
|
|
|
|
/** Flatten cursor's tool result (result.success.* / result.error) into a
|
|
* readable string and derive the error flag from which branch is present. */
|
|
function deriveToolResult(ev: any): { id: string; content: string; isError: boolean } {
|
|
const tc = (ev.tool_call || {}) as Record<string, any>;
|
|
const id = String(ev.call_id ?? tc.toolCallId ?? "");
|
|
const { kind, inner } = findKind(tc);
|
|
const res = inner.result as Record<string, any> | undefined;
|
|
let isError = false;
|
|
let content = "";
|
|
if (res && typeof res === "object") {
|
|
if (res.error !== undefined || res.failure !== undefined) {
|
|
isError = true;
|
|
const e = res.error ?? res.failure;
|
|
content = typeof e === "string" ? e : (e?.message ?? JSON.stringify(e));
|
|
} else {
|
|
const ok = res.success ?? res;
|
|
content = typeof ok === "string" ? ok
|
|
: (ok?.content ?? ok?.output ?? ok?.stdout ?? ok?.text ?? "");
|
|
if (!content) content = JSON.stringify(ok);
|
|
}
|
|
}
|
|
if (content.length > 8000) content = content.slice(0, 8000) + "\n…(truncated)";
|
|
if (!content) content = `[${kind || "tool"} done]`;
|
|
return { id, content, isError };
|
|
}
|
|
|
|
type NormalizedUsage = {
|
|
input_tokens: number;
|
|
output_tokens: number;
|
|
cache_read_input_tokens: number;
|
|
cache_creation_input_tokens: number;
|
|
thinking_tokens: number;
|
|
};
|
|
|
|
/** cursor result.usage is camelCase; map to Claude's usage field names. */
|
|
function mapUsage(u: any): NormalizedUsage {
|
|
const g = (k: string) => (typeof u?.[k] === "number" ? u[k] : 0);
|
|
const tokenDetail = (...values: unknown[]) => {
|
|
const value = values.find((entry) => typeof entry === "number" && Number.isFinite(entry));
|
|
return typeof value === "number" ? value : 0;
|
|
};
|
|
return {
|
|
input_tokens: g("inputTokens"),
|
|
output_tokens: g("outputTokens"),
|
|
cache_read_input_tokens: g("cacheReadTokens"),
|
|
cache_creation_input_tokens: g("cacheWriteTokens"),
|
|
thinking_tokens: tokenDetail(
|
|
u?.thinkingTokens,
|
|
u?.thinking_tokens,
|
|
u?.reasoningTokens,
|
|
u?.reasoning_tokens,
|
|
u?.reasoningOutputTokens,
|
|
),
|
|
};
|
|
}
|
|
|
|
function onCursorEvent(ev: any) {
|
|
const type = ev?.type as string | undefined;
|
|
switch (type) {
|
|
case "system": {
|
|
if (ev.subtype === "init") {
|
|
if (!outSid) outSid = String(ev.session_id || randomUUID());
|
|
if (emittedInit) return;
|
|
emittedInit = true;
|
|
emit({
|
|
type: "system", subtype: "init",
|
|
cwd: ev.cwd ?? process.cwd(),
|
|
session_id: outSid,
|
|
tools: [], model: ev.model ?? parsed.model ?? CURSOR_MODEL ?? "",
|
|
permissionMode: "bypassPermissions",
|
|
apiKeySource: ev.apiKeySource ?? "none",
|
|
mcp_servers: [], slash_commands: [],
|
|
cursor_cli: true,
|
|
});
|
|
}
|
|
return;
|
|
}
|
|
case "user":
|
|
// Cursor echoes the initial prompt as a user frame; `claude -p` does not.
|
|
// Drop it for parity (the runners never want the prompt echoed back).
|
|
return;
|
|
case "assistant": {
|
|
const content = (ev.message?.content ?? []) as Array<Record<string, any>>;
|
|
const text = content.map((c) => (typeof c?.text === "string" ? c.text : "")).join("");
|
|
if (!text) return;
|
|
const call = String(ev.model_call_id ?? "");
|
|
if (pendingText && call && call !== pendingTextCall) flushText();
|
|
pendingTextCall = call;
|
|
pendingText += text;
|
|
return;
|
|
}
|
|
case "thinking": {
|
|
if (ev.subtype === "completed") { flushThink(); return; }
|
|
if (typeof ev.text === "string") pendingThink += ev.text;
|
|
return;
|
|
}
|
|
case "tool_call": {
|
|
// A tool call means the current text turn is over — flush it first so the
|
|
// assistant text and the tool_use land in transcript order.
|
|
flushText();
|
|
flushThink();
|
|
if (ev.subtype === "started") {
|
|
const { id, name, input } = deriveToolUse(ev);
|
|
emit({
|
|
type: "assistant",
|
|
message: { role: "assistant", content: [{ type: "tool_use", id, name, input }] },
|
|
session_id: outSid,
|
|
parent_tool_use_id: null,
|
|
uuid: randomUUID(),
|
|
});
|
|
} else if (ev.subtype === "completed") {
|
|
const { id, content, isError } = deriveToolResult(ev);
|
|
emit({
|
|
type: "user",
|
|
message: { role: "user", content: [{ type: "tool_result", tool_use_id: id, content, is_error: isError }] },
|
|
session_id: outSid,
|
|
parent_tool_use_id: null,
|
|
uuid: randomUUID(),
|
|
});
|
|
}
|
|
return;
|
|
}
|
|
case "result": {
|
|
flushText();
|
|
flushThink();
|
|
sawResult = true;
|
|
const isError = ev.is_error === true;
|
|
const rawResult = ev.result ?? "";
|
|
const resultText = isError && isSecurityTask && isCursorApiKeyMode("cursor") && (typeof rawResult === "object" || (ev.error && typeof ev.error === "object"))
|
|
? redactCursorCliDiagnostic(JSON.stringify({ result: rawResult, error: ev.error ?? null }) || "") : String(rawResult);
|
|
finalize(isError ? "error_during_execution" : "success", isError, resultText, Number(ev.duration_ms ?? (Date.now() - t0)), mapUsage(ev.usage));
|
|
return;
|
|
}
|
|
case "error": {
|
|
// Surface cursor's own error so upstream infra-error detection can see it.
|
|
const raw = ev.message ?? ev.error ?? ev.text ?? "unknown error";
|
|
const msg = isSecurityTask && isCursorApiKeyMode("cursor") && ev.error && typeof ev.error === "object"
|
|
? redactCursorCliDiagnostic(JSON.stringify({ message: ev.message ?? ev.text ?? null, error: ev.error }) || "") : String(raw);
|
|
lastError = msg;
|
|
flushText();
|
|
emit({
|
|
type: "assistant",
|
|
message: { role: "assistant", content: [{ type: "text", text: `API Error: ${msg}` }] },
|
|
session_id: outSid,
|
|
parent_tool_use_id: null,
|
|
uuid: randomUUID(),
|
|
});
|
|
return;
|
|
}
|
|
case "turn_ended": {
|
|
// Current Cursor CLI reports account exhaustion as a terminal
|
|
// `turn_ended/status:error` frame rather than `type:error` or `result`.
|
|
// Keep this compatibility change security-only so feature/bug retain the
|
|
// wrapper behaviour they had before security gained runner-owned retries.
|
|
if (!isSecurityTask || ev.status !== "error") return;
|
|
const raw = ev.error ?? ev.message ?? ev.text ?? "Cursor turn ended with an error";
|
|
const msg = typeof raw === "string" ? raw : JSON.stringify(raw);
|
|
lastError = msg;
|
|
flushText();
|
|
emit({
|
|
type: "assistant",
|
|
message: { role: "assistant", model: "<synthetic>", content: [{ type: "text", text: `API Error: ${msg}` }] },
|
|
session_id: outSid,
|
|
parent_tool_use_id: null,
|
|
uuid: randomUUID(),
|
|
});
|
|
return;
|
|
}
|
|
default:
|
|
dbg(`unhandled cursor frame type: ${type}`);
|
|
}
|
|
}
|
|
|
|
const ZERO_USAGE: NormalizedUsage = {
|
|
input_tokens: 0,
|
|
output_tokens: 0,
|
|
cache_creation_input_tokens: 0,
|
|
cache_read_input_tokens: 0,
|
|
thinking_tokens: 0,
|
|
};
|
|
function finalize(subtype: string, isError: boolean, result: string, durMs: number, usage: NormalizedUsage = ZERO_USAGE) {
|
|
if (finalized) return;
|
|
finalized = true;
|
|
emit({
|
|
type: "result",
|
|
subtype,
|
|
is_error: isError,
|
|
duration_ms: durMs,
|
|
duration_api_ms: durMs,
|
|
num_turns: numTurns,
|
|
result,
|
|
stop_reason: isError ? null : "end_turn",
|
|
session_id: outSid,
|
|
uuid: randomUUID(),
|
|
total_cost_usd: 0,
|
|
usage,
|
|
});
|
|
}
|
|
|
|
// ── spawn cursor-agent ──────────────────────────────────────────────────────
|
|
let chatId: string | null;
|
|
try {
|
|
chatId = await resolveChatId(parsed);
|
|
} catch (err) {
|
|
finalize("error_during_execution", true, redactCursorCliDiagnostic((err as Error).message), Date.now() - t0);
|
|
process.exit(1);
|
|
}
|
|
function buildInitialPrompt(): string {
|
|
const parts: string[] = [];
|
|
if (!isAsking) parts.push(AUTOMODE_SYSPROMPT);
|
|
if (parsed.appendSys) parts.push(parsed.appendSys);
|
|
parts.push(parsed.prompt);
|
|
return parts.join("\n\n");
|
|
}
|
|
|
|
function buildCursorArgs(promptText: string, resumeChatId: string | null): string[] {
|
|
const cursorArgs = [
|
|
"--print",
|
|
"--output-format", "stream-json",
|
|
"--force", "--trust", "--approve-mcps",
|
|
];
|
|
// Security's host already applies isolation; avoid nesting Cursor's sandbox.
|
|
if (isSecurityTask) cursorArgs.push("--sandbox", "disabled");
|
|
for (const d of parsed.addDirs) cursorArgs.push("--add-dir", d);
|
|
const model = parsed.model || CURSOR_MODEL;
|
|
if (model) cursorArgs.push("--model", model);
|
|
if (resumeChatId) cursorArgs.push("--resume", resumeChatId);
|
|
cursorArgs.push(promptText);
|
|
return cursorArgs;
|
|
}
|
|
|
|
let currentChild: Subprocess<"ignore", "pipe", "pipe"> | null = null;
|
|
function killTree() {
|
|
try { currentChild?.kill(); } catch { /* ignore */ }
|
|
}
|
|
|
|
for (const sig of ["SIGINT", "SIGTERM"] as const) {
|
|
process.on(sig, () => {
|
|
dbg(`got ${sig}; killing cursor-agent`);
|
|
finalize("error_during_execution", true, lastError || "", Date.now() - t0);
|
|
killTree();
|
|
process.exit(143);
|
|
});
|
|
}
|
|
|
|
async function runCursorChild(promptText: string, resumeChatId: string | null): Promise<number> {
|
|
const cursorArgs = buildCursorArgs(promptText, resumeChatId);
|
|
dbg(`spawning ${CURSOR_BIN} (chat=${resumeChatId ?? "fresh"}, asking=${isAsking}, prompt=${JSON.stringify(promptText)}) cwd=${process.cwd()}`);
|
|
|
|
const child: Subprocess<"ignore", "pipe", "pipe"> = spawn({
|
|
cmd: [CURSOR_BIN, ...cursorArgs],
|
|
cwd: process.cwd(),
|
|
stdin: "ignore",
|
|
stdout: "pipe",
|
|
stderr: "pipe",
|
|
});
|
|
currentChild = child;
|
|
// Security evaluate/run opt in explicitly. Feature, bugfix and asking retain
|
|
// their previous stderr/terminal behaviour, including DEBUG output.
|
|
const diagnostic = isSecurityTask ? new CursorCliDiagnosticBuffer() : null;
|
|
const handle = (line: string) => {
|
|
const s = line.trim();
|
|
if (!s) return;
|
|
if (s[0] !== "{") {
|
|
diagnostic?.append(`${s}\n`);
|
|
return;
|
|
}
|
|
if (DEBUG) process.stderr.write(`[cursor-raw] ${s}\n`);
|
|
let ev: any;
|
|
try { ev = JSON.parse(s); } catch { return; }
|
|
try { onCursorEvent(ev); } catch (e) { dbg(`translate error: ${(e as Error).message}`); }
|
|
};
|
|
const stderrTask = (async () => {
|
|
const dec = new TextDecoder();
|
|
for await (const chunk of child.stderr) {
|
|
if (diagnostic) diagnostic.append(dec.decode(chunk, { stream: true }));
|
|
else if (DEBUG) process.stderr.write(dec.decode(chunk));
|
|
}
|
|
if (diagnostic) diagnostic.append(dec.decode());
|
|
})().catch(() => {});
|
|
const stdoutTask = (async () => {
|
|
const dec = new TextDecoder();
|
|
let buf = "";
|
|
for await (const chunk of child.stdout) {
|
|
buf += dec.decode(chunk, { stream: true });
|
|
let nl: number;
|
|
while ((nl = buf.indexOf("\n")) >= 0) {
|
|
handle(buf.slice(0, nl));
|
|
buf = buf.slice(nl + 1);
|
|
}
|
|
}
|
|
if (buf.trim()) handle(buf);
|
|
})().catch((e) => dbg(`stdout reader error: ${(e as Error).message}`));
|
|
const code = await child.exited;
|
|
await Promise.allSettled([stderrTask, stdoutTask]);
|
|
if (diagnostic && !sawResult && (code !== 0 || (numTurns === 0 && !pendingText.trim())) && !lastError) {
|
|
lastError = diagnostic.text() || `Cursor CLI exited with code ${code} without a usable result`;
|
|
}
|
|
if (currentChild === child) currentChild = null;
|
|
return code;
|
|
}
|
|
|
|
const code = await runCursorChild(buildInitialPrompt(), chatId);
|
|
// Flush anything the stream reader left buffered, then guarantee a result frame
|
|
// so the caller's parser never hangs waiting for a terminal frame cursor didn't
|
|
// emit (crash / auth failure / empty run).
|
|
flushText();
|
|
flushThink();
|
|
if (!sawResult) {
|
|
const ok = !lastError && (numTurns > 0) && code === 0;
|
|
finalize(ok ? "success" : "error_during_execution", !ok, lastError || "", Date.now() - t0);
|
|
}
|
|
process.exit(sawResult ? 0 : (code || 1));
|