@stablekernel/opencode-cursor 0.4.7-next.0 → 0.5.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.
- package/CHANGELOG.md +50 -0
- package/README.md +55 -16
- package/dist/{chunk-SVIXYMHP.js → chunk-LAOFD3JB.js} +487 -292
- package/dist/chunk-LAOFD3JB.js.map +1 -0
- package/dist/plugin/index.js +28 -4
- package/dist/plugin/index.js.map +1 -1
- package/dist/provider/index.d.ts +12 -0
- package/dist/provider/index.js +205 -23
- package/dist/provider/index.js.map +1 -1
- package/dist/sidecar/agent-host.d.ts +9 -2
- package/dist/sidecar/agent-host.js +7 -1
- package/dist/sidecar/agent-host.js.map +1 -1
- package/package.json +6 -5
- package/dist/chunk-SVIXYMHP.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/api-key.ts","../src/provider/agent-backend.ts","../src/cursor-runtime.ts","../src/provider/sidecar-client.ts","../src/provider/system-rule.ts","../src/provider/error-classify.ts","../src/provider/agent-events.ts","../src/provider/controls.ts","../src/provider/session-store.ts","../src/provider/session-pool.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\n\n/** Environment variable the Cursor SDK itself reads as a fallback. */\nexport const CURSOR_API_KEY_ENV_VAR = \"CURSOR_API_KEY\";\n\n/**\n * Values that are *not* real keys but rather instructions to read the key from\n * the environment. opencode config commonly stores literal `{env:...}` style\n * placeholders, and users sometimes paste the variable name itself.\n */\nconst PLACEHOLDERS = new Set<string>([\n CURSOR_API_KEY_ENV_VAR,\n `$${CURSOR_API_KEY_ENV_VAR}`,\n `\\${${CURSOR_API_KEY_ENV_VAR}}`,\n]);\n\n/**\n * Resolve a usable Cursor API key.\n *\n * Resolution order: an explicit, non-placeholder candidate (e.g. from opencode\n * auth storage or provider options) wins; otherwise fall back to the\n * `CURSOR_API_KEY` environment variable. Returns `undefined` when no key is\n * available so callers can present a clear \"needs auth\" path.\n *\n * The key is never logged or persisted by this module.\n */\nexport function resolveCursorApiKey(candidate?: string | null): string | undefined {\n const trimmed = candidate?.trim();\n if (trimmed && !PLACEHOLDERS.has(trimmed)) return trimmed;\n const fromEnv = process.env[CURSOR_API_KEY_ENV_VAR]?.trim();\n return fromEnv ? fromEnv : undefined;\n}\n\n/**\n * Produce a short, non-reversible fingerprint of an API key. Used purely to key\n * the on-disk model cache so the cache invalidates when the key changes. The\n * raw key is never written to disk.\n */\nexport function fingerprintApiKey(apiKey: string): string {\n return createHash(\"sha256\").update(apiKey).digest(\"hex\").slice(0, 16);\n}\n","/**\n * Selects where Cursor agents run — three transports:\n *\n * - \"http1\": in-process via `@cursor/sdk` with\n * `Cursor.configure({ local: { useHttp1ForAgent: true } })` — HTTP/1.1 + SSE,\n * the Bun-safe path (Bun's `node:http2` bug kills Cursor's streaming RPC with\n * NGHTTP2_FRAME_SIZE_ERROR; see oven-sh/bun#31499).\n * - \"http2-direct\": in-process via `@cursor/sdk` default HTTP/2 transport\n * (Node — the normal path for tests, scripts, and any non-Bun host).\n * - \"sidecar\": a spawned Node child hosting the SDK (the historical Bun\n * workaround; see src/sidecar/agent-host.mjs).\n *\n * Resolution order: provider option (`transport`) -> OPENCODE_CURSOR_TRANSPORT\n * -> legacy OPENCODE_CURSOR_SIDECAR (1=sidecar, 0=http2-direct) -> default\n * (Bun: DEFAULT_BUN_TRANSPORT, post-gate \"http1\"; Node: http2-direct).\n */\nimport { execSync } from \"node:child_process\";\nimport { existsSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport { loadCursorSdk } from \"../cursor-runtime.js\";\nimport { SidecarClient, type AgentLike } from \"./sidecar-client.js\";\n\nexport type { AgentLike, AgentRunLike, AgentSendOptions } from \"./sidecar-client.js\";\n\nexport type TransportKind = \"http1\" | \"http2-direct\" | \"sidecar\";\nexport type BackendKind = \"in-process\" | \"sidecar\";\n\n/**\n * Bun default. Post-evidence-gate this is \"http1\" (Task 5/6 matrix green;\n * TTFT ≤ 1.5× sidecar). Sidecar remains via OPENCODE_CURSOR_TRANSPORT=sidecar.\n */\nexport const DEFAULT_BUN_TRANSPORT: TransportKind = \"http1\";\n\nlet preferredTransport: TransportKind | undefined;\n\n/** Provider-option override (createCursor({transport})); beats env. Process-global. */\nexport function setPreferredTransport(t: TransportKind | undefined): void {\n preferredTransport = t;\n}\n\nfunction isTransportKind(v: string | undefined): v is TransportKind {\n return v === \"http1\" || v === \"http2-direct\" || v === \"sidecar\";\n}\n\nexport interface AgentBackend {\n kind: BackendKind;\n createAgent(options: unknown): Promise<AgentLike>;\n resumeAgent(agentId: string, options: unknown): Promise<AgentLike>;\n}\n\nexport interface BackendEnvironment {\n isBun: boolean;\n /** Resolved node executable, or undefined when not on PATH. */\n nodePath: string | undefined;\n}\n\n/**\n * Where Cursor agents run. Resolution: provider option -> OPENCODE_CURSOR_TRANSPORT\n * -> legacy OPENCODE_CURSOR_SIDECAR (1=sidecar, 0=http2-direct) -> default\n * (Bun: DEFAULT_BUN_TRANSPORT; Node: http2-direct, today's in-process path).\n */\nexport function resolveTransport(env: BackendEnvironment): TransportKind {\n const requested =\n preferredTransport ??\n (isTransportKind(process.env[\"OPENCODE_CURSOR_TRANSPORT\"])\n ? (process.env[\"OPENCODE_CURSOR_TRANSPORT\"] as TransportKind)\n : undefined);\n if (requested) {\n if (requested === \"sidecar\" && !env.nodePath) {\n return env.isBun ? \"http1\" : \"http2-direct\";\n }\n return requested;\n }\n const legacy = process.env[\"OPENCODE_CURSOR_SIDECAR\"];\n if (legacy === \"1\" || legacy === \"true\") {\n return env.nodePath ? \"sidecar\" : env.isBun ? \"http1\" : \"http2-direct\";\n }\n if (legacy === \"0\" || legacy === \"false\") return env.isBun ? \"http1\" : \"http2-direct\";\n return env.isBun ? DEFAULT_BUN_TRANSPORT : \"http2-direct\";\n}\n\nfunction detectNode(): string | undefined {\n try {\n const out = execSync(process.platform === \"win32\" ? \"where node\" : \"command -v node\", {\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n }).trim();\n return out.split(\"\\n\")[0] || undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction detectEnvironment(): BackendEnvironment {\n const isBun = typeof (globalThis as { Bun?: unknown }).Bun !== \"undefined\";\n // Only pay the PATH lookup when the answer can matter.\n const needsNode = isBun || process.env[\"OPENCODE_CURSOR_SIDECAR\"] === \"1\";\n return { isBun, nodePath: needsNode ? detectNode() : process.execPath };\n}\n\nlet http1Configured = false;\n\n/** Idempotent: enable the SDK's HTTP/1.1 agent transport (Bun-sanctioned path). */\nasync function ensureHttp1Configured(): Promise<void> {\n if (http1Configured) return;\n const { Cursor } = await loadCursorSdk();\n Cursor.configure({ local: { useHttp1ForAgent: true } });\n http1Configured = true;\n}\n\nfunction inProcessBackend(useHttp1: boolean): AgentBackend {\n return {\n kind: \"in-process\",\n createAgent: async (options) => {\n const { Agent } = await loadCursorSdk();\n if (useHttp1) await ensureHttp1Configured();\n return (await Agent.create(options as never)) as unknown as AgentLike;\n },\n resumeAgent: async (agentId, options) => {\n const { Agent } = await loadCursorSdk();\n if (useHttp1) await ensureHttp1Configured();\n return (await Agent.resume(agentId, options as never)) as unknown as AgentLike;\n },\n };\n}\n\n/**\n * Locate the sidecar script across layouts: tsup may place this module in\n * dist/provider/index.js or hoist it into a root-level dist/chunk-*.js, and in\n * dev/tests it runs straight from src/. Try each known relative position.\n */\nexport function resolveSidecarScript(): string | undefined {\n const candidates = [\n \"./sidecar/agent-host.js\", // importer is a chunk at dist root\n \"../sidecar/agent-host.js\", // importer is dist/provider/index.js\n \"../sidecar/agent-host.mjs\", // importer is src/provider/*.ts (dev/tests)\n ];\n for (const candidate of candidates) {\n const path = fileURLToPath(new URL(candidate, import.meta.url));\n if (existsSync(path)) return path;\n }\n return undefined;\n}\n\nfunction sidecarBackend(nodePath: string, scriptPath: string): AgentBackend {\n const client = new SidecarClient({ scriptPath, nodePath });\n return {\n kind: \"sidecar\",\n createAgent: (options) => client.createAgent(options),\n resumeAgent: (agentId, options) => client.resumeAgent(agentId, options),\n };\n}\n\nlet cached: AgentBackend | undefined;\n\n/** Resolve (and cache) the agent backend for this process. */\nexport function loadAgentBackend(): AgentBackend {\n if (!cached) {\n const env = detectEnvironment();\n const transport = resolveTransport(env);\n const scriptPath = transport === \"sidecar\" ? resolveSidecarScript() : undefined;\n if (transport === \"sidecar\" && (!env.nodePath || !scriptPath)) {\n // Explicit sidecar request we can't satisfy: fall back loudly.\n console.error(\n \"[opencode-cursor] Node sidecar requested but unavailable \" +\n `(node: ${env.nodePath ?? \"not found\"}, script: ${scriptPath ?? \"not found\"}); ` +\n \"falling back to in-process HTTP/1.1 transport.\",\n );\n cached = inProcessBackend(true);\n return cached;\n }\n if (transport === \"http2-direct\" && env.isBun) {\n console.error(\n \"[opencode-cursor] http2-direct under Bun: Cursor streams may fail \" +\n \"(Bun node:http2 incompatibility, oven-sh/bun#31499). \" +\n \"Set OPENCODE_CURSOR_TRANSPORT=http1 (recommended) or sidecar.\",\n );\n }\n cached =\n transport === \"sidecar\" && env.nodePath && scriptPath\n ? sidecarBackend(env.nodePath, scriptPath)\n : inProcessBackend(transport === \"http1\");\n }\n return cached;\n}\n\n/** Test hook. */\nexport function resetAgentBackend(): void {\n cached = undefined;\n}\n","/**\n * Lazy loader for the official Cursor SDK (`@cursor/sdk`).\n *\n * The SDK is heavy and only needed once a Cursor model is actually used or\n * models are discovered, so it is imported on demand. A failed import (e.g. the\n * dependency is missing) degrades gracefully into a clear error instead of\n * crashing opencode at startup.\n */\nexport type CursorSdkModule = typeof import(\"@cursor/sdk\");\n\nlet cached: Promise<CursorSdkModule> | undefined;\n\nexport async function loadCursorSdk(): Promise<CursorSdkModule> {\n if (!cached) {\n cached = import(\"@cursor/sdk\").catch((err: unknown) => {\n // Allow a later retry if the failure was transient.\n cached = undefined;\n const detail = err instanceof Error ? err.message : String(err);\n throw new Error(\n `[opencode-cursor] Failed to load \"@cursor/sdk\". Make sure it is installed ` +\n `(\\`npm install @cursor/sdk\\`). Original error: ${detail}`,\n );\n });\n }\n return cached;\n}\n","/**\n * Client half of the Node sidecar (see src/sidecar/agent-host.mjs for the\n * protocol and the why). Spawns one Node child per client and multiplexes\n * agent create/resume/send/cancel/close requests over JSON-lines stdio,\n * exposing agents through the same minimal surface the provider already\n * consumes ({@link AgentLike}), so session-pool/agent-events need no\n * sidecar-specific logic.\n */\nimport { spawn, type ChildProcessByStdio } from \"node:child_process\";\nimport { createInterface, type Interface } from \"node:readline\";\nimport type { Readable, Writable } from \"node:stream\";\n\n/** Minimal run surface the provider consumes (subset of the SDK's Run). */\nexport interface AgentRunLike {\n wait(): Promise<{ status: string; result?: string }>;\n cancel(): void | Promise<void>;\n}\n\nexport interface AgentSendOptions {\n mode?: string;\n onDelta?: (input: { update: Record<string, unknown> & { type: string } }) => void;\n local?: { force?: boolean };\n idempotencyKey?: string;\n}\n\n/** Minimal agent surface the provider consumes (subset of the SDK's SDKAgent). */\nexport interface AgentLike {\n agentId: string;\n send(message: unknown, options?: AgentSendOptions): Promise<AgentRunLike>;\n close(): void;\n}\n\nexport interface SidecarClientOptions {\n /** Path to the agent-host script. */\n scriptPath: string;\n /** Node executable; default \"node\" from PATH. */\n nodePath?: string;\n /** Extra environment for the child (merged over process.env). */\n env?: Record<string, string>;\n /** Mirror child stderr to this process (debug aid). */\n debug?: boolean;\n}\n\ninterface Pending {\n resolve: (msg: Record<string, unknown>) => void;\n reject: (err: Error) => void;\n /** Streaming hooks for \"send\" requests. */\n onUpdate?: (update: Record<string, unknown> & { type: string }) => void;\n onResult?: (result: { status: string; result?: string }) => void;\n onStreamError?: (err: Error) => void;\n}\n\nfunction reviveError(error: unknown): Error {\n const e = (error ?? {}) as {\n name?: string;\n message?: string;\n status?: number;\n code?: string;\n isRetryable?: boolean;\n helpUrl?: string;\n };\n const err = new Error(e.message ?? \"sidecar error\");\n if (e.name) err.name = e.name;\n if (e.status !== undefined) (err as { status?: number }).status = e.status;\n if (e.code !== undefined) (err as { code?: string }).code = e.code;\n if (e.isRetryable !== undefined) (err as { isRetryable?: boolean }).isRetryable = e.isRetryable;\n if (e.helpUrl !== undefined) (err as { helpUrl?: string }).helpUrl = e.helpUrl;\n return err;\n}\n\nexport class SidecarClient {\n private readonly options: SidecarClientOptions;\n private child: ChildProcessByStdio<Writable, Readable, Readable> | undefined;\n private reader: Interface | undefined;\n private readonly pending = new Map<number, Pending>();\n private nextId = 1;\n private disposed = false;\n\n constructor(options: SidecarClientOptions) {\n this.options = options;\n }\n\n /** Spawn (or reuse) the child process. */\n private ensureChild(): ChildProcessByStdio<Writable, Readable, Readable> {\n if (this.disposed) throw new Error(\"cursor sidecar client disposed\");\n if (this.child) return this.child;\n\n const child = spawn(this.options.nodePath ?? \"node\", [this.options.scriptPath], {\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n env: { ...process.env, ...this.options.env },\n });\n this.child = child;\n\n this.reader = createInterface({ input: child.stdout });\n this.reader.on(\"line\", (line) => this.handleLine(line));\n child.stderr.on(\"data\", (chunk: Buffer) => {\n if (this.options.debug || process.env[\"OPENCODE_CURSOR_DEBUG\"]) {\n process.stderr.write(`[cursor:sidecar] ${chunk}`);\n }\n });\n child.on(\"exit\", (code) => {\n this.failAll(new Error(`cursor sidecar exited (code ${code ?? \"unknown\"})`));\n this.child = undefined;\n this.reader?.close();\n this.reader = undefined;\n });\n child.on(\"error\", (err) => {\n this.failAll(new Error(`cursor sidecar failed to start: ${err.message}`));\n this.child = undefined;\n });\n this.updateRefs();\n return child;\n }\n\n /**\n * Keep the child (and its pipes) from holding the parent's event loop open\n * while idle, but ref it whenever a reply is outstanding so the loop can't\n * exit mid-request. Without this, any process that uses the provider and\n * never dispose()s — scripts, tests, opencode itself on shutdown — hangs.\n */\n private updateRefs(): void {\n const child = this.child;\n if (!child) return;\n const refable = [child, child.stdin, child.stdout, child.stderr] as Array<{\n ref?: () => void;\n unref?: () => void;\n }>;\n if (this.pending.size > 0) {\n for (const target of refable) target.ref?.();\n } else {\n for (const target of refable) target.unref?.();\n }\n }\n\n private failAll(err: Error): void {\n for (const pending of this.pending.values()) {\n pending.onStreamError?.(err);\n pending.reject(err);\n }\n this.pending.clear();\n this.updateRefs();\n }\n\n private handleLine(line: string): void {\n if (!line.trim()) return;\n let msg: Record<string, unknown>;\n try {\n msg = JSON.parse(line) as Record<string, unknown>;\n } catch {\n return; // ignore non-protocol noise on stdout\n }\n const id = msg[\"id\"];\n if (typeof id !== \"number\") return;\n const pending = this.pending.get(id);\n if (!pending) return;\n\n const ev = msg[\"ev\"];\n if (ev === \"update\") {\n pending.onUpdate?.(msg[\"update\"] as Record<string, unknown> & { type: string });\n return;\n }\n if (ev === \"result\") {\n this.pending.delete(id);\n this.updateRefs();\n pending.onResult?.(msg[\"result\"] as { status: string; result?: string });\n return;\n }\n if (ev === \"error\") {\n this.pending.delete(id);\n this.updateRefs();\n pending.onStreamError?.(reviveError(msg[\"error\"]));\n return;\n }\n\n if (msg[\"ok\"] === true) {\n // \"send\" acks stay pending for their streaming terminal event.\n if (!pending.onResult) {\n this.pending.delete(id);\n this.updateRefs();\n }\n pending.resolve(msg);\n } else {\n this.pending.delete(id);\n this.updateRefs();\n pending.reject(reviveError(msg[\"error\"]));\n }\n }\n\n private request(\n payload: Record<string, unknown>,\n hooks?: Pick<Pending, \"onUpdate\" | \"onResult\" | \"onStreamError\">,\n ): Promise<Record<string, unknown>> {\n const child = this.ensureChild();\n const id = this.nextId++;\n return new Promise<Record<string, unknown>>((resolve, reject) => {\n this.pending.set(id, { resolve, reject, ...hooks });\n this.updateRefs();\n child.stdin.write(`${JSON.stringify({ id, ...payload })}\\n`, (err) => {\n if (err) {\n this.pending.delete(id);\n this.updateRefs();\n reject(err);\n }\n });\n });\n }\n\n async createAgent(options: unknown): Promise<AgentLike> {\n const res = await this.request({ op: \"create\", options });\n return this.wrapAgent(String(res[\"agentId\"]));\n }\n\n async resumeAgent(agentId: string, options: unknown): Promise<AgentLike> {\n const res = await this.request({ op: \"resume\", agentId, options });\n return this.wrapAgent(String(res[\"agentId\"]));\n }\n\n private wrapAgent(agentId: string): AgentLike {\n return {\n agentId,\n send: (message, options) => this.sendTurn(agentId, message, options),\n close: () => {\n void this.request({ op: \"close\", agentId }).catch(() => {\n // best effort, mirrors SDKAgent.close()\n });\n },\n };\n }\n\n private async sendTurn(\n agentId: string,\n message: unknown,\n options?: AgentSendOptions,\n ): Promise<AgentRunLike> {\n let settle!: {\n resolve: (r: { status: string; result?: string }) => void;\n reject: (e: Error) => void;\n };\n const waited = new Promise<{ status: string; result?: string }>((resolve, reject) => {\n settle = { resolve, reject };\n });\n // Avoid unhandled-rejection noise when the consumer never calls wait().\n waited.catch(() => {});\n\n let sendId: number | undefined;\n const ack = this.request(\n {\n op: \"send\",\n agentId,\n message,\n ...(options?.mode ? { mode: options.mode } : {}),\n ...(options?.local?.force ? { force: true } : {}),\n ...(options?.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {}),\n },\n {\n onUpdate: (update) => options?.onDelta?.({ update }),\n onResult: (result) => settle.resolve(result),\n onStreamError: (err) => settle.reject(err),\n },\n );\n // The request id is allocated synchronously inside request(); capture it\n // for cancel by reading the id we just used.\n sendId = this.nextId - 1;\n\n await ack;\n return {\n wait: () => waited,\n cancel: async () => {\n if (sendId === undefined) return;\n await this.request({ op: \"cancel\", sendId }).catch(() => {});\n },\n };\n }\n\n /** Kill the child and reject anything in flight. */\n dispose(): void {\n this.disposed = true;\n this.failAll(new Error(\"cursor sidecar client disposed\"));\n this.reader?.close();\n this.reader = undefined;\n this.child?.kill();\n this.child = undefined;\n }\n}\n","import {\n\tmkdirSync,\n\twriteFileSync,\n\treadFileSync,\n\texistsSync,\n\trmSync,\n} from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { LanguageModelV3Prompt } from \"@ai-sdk/provider\";\nimport type { SettingSource } from \"@cursor/sdk\";\nimport type { SystemPromptMode } from \"./message-map.js\";\n\n/** Location of the generated rule, relative to the agent's cwd. */\nconst RULES_DIR = join(\".cursor\", \"rules\");\nconst RULE_FILE = \"opencode.mdc\";\nconst IGNORE_FILE = \".gitignore\";\n\n/**\n * Frontmatter sentinel marking the rule as generated by this plugin. Only\n * files carrying it are ever overwritten or deleted, so a user-owned\n * `.cursor/rules/opencode.mdc` is never clobbered.\n */\nconst SENTINEL = \"generated: opencode-cursor\";\n\n/** Concatenate every system-message body from an AI-SDK prompt (trimmed). */\nexport function extractSystemText(prompt: LanguageModelV3Prompt): string {\n\tconst parts: string[] = [];\n\tfor (const message of prompt) {\n\t\tif (message.role === \"system\") parts.push(message.content);\n\t}\n\treturn parts.join(\"\\n\\n\").trim();\n}\n\n/** Outcome of a {@link writeSystemRule} attempt. */\nexport type SystemRuleWrite =\n\t/** Rule file created or updated. */\n\t| \"written\"\n\t/** Existing generated rule already has this content; write skipped. */\n\t| \"unchanged\"\n\t/** No system text to deliver; nothing written. */\n\t| \"empty\"\n\t/** A user-owned (sentinel-less) opencode.mdc exists; left untouched. */\n\t| \"blocked\";\n\n/** True when the file carries the generated-by sentinel in its frontmatter. */\nfunction isGenerated(content: string): boolean {\n\tif (!content.startsWith(\"---\")) return false;\n\tconst end = content.indexOf(\"\\n---\", 3);\n\tconst frontmatter = end === -1 ? content : content.slice(0, end);\n\treturn frontmatter.split(/\\r?\\n/).includes(SENTINEL);\n}\n\n/**\n * Write opencode's system prompt to `<cwd>/.cursor/rules/opencode.mdc` as an\n * always-applied Cursor project rule. Cursor loads this through its authoritative\n * rules channel (`settingSources` including \"project\"), so opencode's controlling\n * instructions reach the agent without being flattened into the untrusted\n * user-message transcript (which injection-hardened models reject).\n *\n * The file carries a generated-by sentinel; a pre-existing sentinel-less file\n * is treated as user-owned and never overwritten (\"blocked\"). An existing\n * generated rule with identical content is left as-is (\"unchanged\") to keep\n * sync fs writes off the stream hot path. May throw on fs errors (read-only\n * checkout etc.) — callers should degrade gracefully.\n */\nexport function writeSystemRule(\n\tcwd: string,\n\tsystemText: string,\n): SystemRuleWrite {\n\tif (!systemText) return \"empty\";\n\tconst dir = join(cwd, RULES_DIR);\n\tconst path = join(dir, RULE_FILE);\n\tconst body = `---\\nalwaysApply: true\\n${SENTINEL}\\n---\\n\\n${systemText}\\n`;\n\tconst existing = existsSync(path) ? readFileSync(path, \"utf8\") : undefined;\n\tif (existing !== undefined) {\n\t\tif (!isGenerated(existing)) return \"blocked\";\n\t\tif (existing === body) return \"unchanged\";\n\t}\n\tmkdirSync(dir, { recursive: true });\n\twriteFileSync(path, body, \"utf8\");\n\tensureGitIgnored(dir);\n\treturn \"written\";\n}\n\n/**\n * Keep the generated rule out of git via `.cursor/rules/.gitignore` (which\n * also ignores itself so it doesn't pollute `git status`).\n */\nfunction ensureGitIgnored(dir: string): void {\n\tconst path = join(dir, IGNORE_FILE);\n\tconst existing = existsSync(path) ? readFileSync(path, \"utf8\") : \"\";\n\tconst lines = existing.split(/\\r?\\n/);\n\tconst missing = [RULE_FILE, IGNORE_FILE].filter(\n\t\t(entry) => !lines.includes(entry),\n\t);\n\tif (missing.length === 0) return;\n\tconst prefix =\n\t\texisting && !existing.endsWith(\"\\n\") ? `${existing}\\n` : existing;\n\twriteFileSync(path, `${prefix}${missing.join(\"\\n\")}\\n`, \"utf8\");\n}\n\n/**\n * Remove the generated rule (best-effort); used on plugin dispose. Only\n * deletes files carrying the generated-by sentinel — a user-owned\n * opencode.mdc is left in place.\n */\nexport function removeSystemRule(cwd: string): void {\n\ttry {\n\t\tconst path = join(cwd, RULES_DIR, RULE_FILE);\n\t\tif (isGenerated(readFileSync(path, \"utf8\"))) rmSync(path);\n\t} catch {\n\t\t// best effort — already gone or never written\n\t}\n}\n\n/** How the system prompt will be delivered for this turn. */\nexport interface SystemDelivery {\n\tmode: SystemPromptMode;\n\tsettingSources: SettingSource[] | undefined;\n}\n\n/**\n * Decide how opencode's system prompt reaches the Cursor agent for one turn.\n *\n * In \"rules\" mode this writes the rule file and enables the `project`\n * settings layer — but ONLY when the user did not explicitly configure\n * `settingSources` without \"project\" (a deliberate hardening opt-out: the\n * project layer also loads the repo's `.cursor/mcp.json`, hooks, and other\n * rules). On an opt-out, a failed write (read-only checkout etc.), or a\n * user-owned rule file, it degrades to inline \"message\" delivery for the\n * turn and reports the reason via `warn`. Never throws.\n */\nexport function resolveSystemDelivery(options: {\n\tmode: SystemPromptMode;\n\tsettingSources: SettingSource[] | undefined;\n\tcwd: string;\n\tsystemText: string;\n\twarn: (message: string) => void;\n}): SystemDelivery {\n\tconst { mode, settingSources, cwd, systemText, warn } = options;\n\tif (mode !== \"rules\") return { mode, settingSources };\n\tif (settingSources && !settingSources.includes(\"project\")) {\n\t\twarn(\n\t\t\t'systemPrompt \"rules\" needs the \"project\" settings layer, but settingSources was explicitly configured without it; delivering the system prompt inline (\"message\" mode) instead. Add \"project\" to settingSources or set systemPrompt: \"message\" to silence this.',\n\t\t);\n\t\treturn { mode: \"message\", settingSources };\n\t}\n\tlet result: SystemRuleWrite;\n\ttry {\n\t\tresult = writeSystemRule(cwd, systemText);\n\t} catch (error) {\n\t\twarn(\n\t\t\t`failed to write .cursor/rules/${RULE_FILE} (${error instanceof Error ? error.message : String(error)}); delivering the system prompt inline (\"message\" mode) for this turn.`,\n\t\t);\n\t\treturn { mode: \"message\", settingSources };\n\t}\n\tif (result === \"blocked\") {\n\t\twarn(\n\t\t\t`.cursor/rules/${RULE_FILE} exists but was not generated by opencode-cursor; leaving it untouched and delivering the system prompt inline (\"message\" mode).`,\n\t\t);\n\t\treturn { mode: \"message\", settingSources };\n\t}\n\tif (result === \"empty\") return { mode, settingSources };\n\treturn { mode, settingSources: settingSources ?? [\"project\"] };\n}\n","/**\n * Classify errors from the Cursor SDK into recovery actions. Works off plain\n * {name, message, status?, code?, isRetryable?, helpUrl?} shape ONLY — errors\n * that cross the Node sidecar arrive as re-hydrated plain Errors (never SDK\n * instances), so `instanceof` discrimination is impossible on the Bun side and\n * forbidden here.\n */\nexport type CursorErrorKind =\n\t| \"agent-not-found\"\n\t| \"agent-busy\"\n\t| \"rate-limit\"\n\t| \"network\"\n\t| \"auth\"\n\t| \"config\"\n\t| \"unknown\";\n\nexport interface ClassifiedError {\n\tkind: CursorErrorKind;\n\t/** Safe to retry the same operation (bounded by the caller). */\n\tretryable: boolean;\n\tstatus?: number;\n\thelpUrl?: string;\n\tmessage: string;\n}\n\nexport function classifyError(err: unknown): ClassifiedError {\n\tconst e = (err ?? {}) as {\n\t\tname?: string;\n\t\tmessage?: string;\n\t\tstatus?: unknown;\n\t\tcode?: unknown;\n\t\tisRetryable?: unknown;\n\t\thelpUrl?: unknown;\n\t};\n\tconst name = typeof e.name === \"string\" ? e.name : \"Error\";\n\tconst message = typeof e.message === \"string\" ? e.message : String(err);\n\tconst status = typeof e.status === \"number\" ? e.status : undefined;\n\tconst code = typeof e.code === \"string\" ? e.code : undefined;\n\tconst helpUrl = typeof e.helpUrl === \"string\" ? e.helpUrl : undefined;\n\tconst base = { ...(status !== undefined ? { status } : {}), ...(helpUrl ? { helpUrl } : {}), message };\n\n\tswitch (name) {\n\t\tcase \"AgentNotFoundError\":\n\t\t\treturn { kind: \"agent-not-found\", retryable: false, ...base };\n\t\tcase \"AgentBusyError\":\n\t\t\treturn { kind: \"agent-busy\", retryable: false, ...base };\n\t\tcase \"RateLimitError\":\n\t\t\treturn { kind: \"rate-limit\", retryable: true, ...base };\n\t\tcase \"NetworkError\":\n\t\t\treturn { kind: \"network\", retryable: true, ...base };\n\t\tcase \"AuthenticationError\":\n\t\t\treturn { kind: \"auth\", retryable: false, ...base };\n\t\tcase \"ConfigurationError\":\n\t\tcase \"IntegrationNotConnectedError\":\n\t\tcase \"UnsupportedRunOperationError\":\n\t\t\treturn { kind: \"config\", retryable: false, ...base };\n\t}\n\n\t// Transports/serializers that lose the class name but keep status/code.\n\tif (status === 401) return { kind: \"auth\", retryable: false, ...base };\n\tif (status === 429) return { kind: \"rate-limit\", retryable: true, ...base };\n\tif (status === 409) return { kind: \"agent-busy\", retryable: false, ...base };\n\tif (status === 503 || status === 504) return { kind: \"network\", retryable: true, ...base };\n\tif (code === \"agent_not_found\") return { kind: \"agent-not-found\", retryable: false, ...base };\n\n\treturn { kind: \"unknown\", retryable: e.isRetryable === true, ...base };\n}\n","import type { AgentModeOption, SDKUserMessage } from \"@cursor/sdk\";\nimport type { AgentLike, AgentRunLike, AgentSendOptions } from \"./agent-backend.js\";\nimport { classifyError } from \"./error-classify.js\";\n\n/** Token usage as reported by Cursor's `turn-ended` update. */\nexport interface CursorUsage {\n inputTokens: number;\n outputTokens: number;\n cacheReadTokens: number;\n cacheWriteTokens: number;\n}\n\n/** Normalized events bridged from the Cursor SDK's push callbacks. */\nexport type CursorEvent =\n | { type: \"text-delta\"; text: string }\n | { type: \"reasoning-delta\"; text: string }\n | { type: \"tool-input-partial\"; id: string; name: string; input: unknown }\n | { type: \"tool-call\"; id: string; name: string; input: unknown }\n | { type: \"tool-result\"; id: string; name: string; result: unknown; isError: boolean }\n | { type: \"usage\"; usage: CursorUsage }\n | { type: \"reasoning-complete\"; durationMs?: number }\n | { type: \"compaction\" }\n | { type: \"finish\"; text?: string };\n\nexport interface StreamAgentTurnOptions {\n mode: AgentModeOption;\n abortSignal?: AbortSignal;\n /** Dedupe key forwarded to every (re)send of this turn. */\n idempotencyKey?: string;\n /**\n * Usage accumulated by preceding silent replay turns. When set, yielded\n * `usage` events carry `usageBase + turn-ended` sums so the visible turn's\n * reported usage includes everything spent replaying earlier messages.\n */\n usageBase?: CursorUsage;\n}\n\n/** Sum two usage reports (either may be absent). */\nexport function addUsage(a?: CursorUsage, b?: CursorUsage): CursorUsage | undefined {\n if (!a) return b;\n if (!b) return a;\n return {\n inputTokens: a.inputTokens + b.inputTokens,\n outputTokens: a.outputTokens + b.outputTokens,\n cacheReadTokens: a.cacheReadTokens + b.cacheReadTokens,\n cacheWriteTokens: a.cacheWriteTokens + b.cacheWriteTokens,\n };\n}\n\n/**\n * Human-readable name for a Cursor tool call. Most Cursor tools carry their\n * name in `toolCall.type` (shell/read/edit/…), but an MCP tool call has\n * `type: \"mcp\"` with the real tool in `args.toolName` (and server in\n * `args.providerIdentifier`) — surface that instead of the literal \"mcp\".\n */\nfunction toolDisplayName(toolCall: ({ type?: string } & Record<string, any>) | undefined): string {\n if (!toolCall) return \"tool\";\n if (toolCall.type === \"mcp\") {\n const name = toolCall.args?.toolName;\n const server = toolCall.args?.providerIdentifier;\n if (name) return server ? `${server}/${name}` : String(name);\n return \"mcp\";\n }\n return toolCall.type ?? \"tool\";\n}\n\n/**\n * Stream a single turn on an already-acquired Cursor agent and yield normalized\n * events. The agent's lifecycle (create/resume/close) is owned by the caller\n * (see session-pool.ts) so it can be reused across turns. The SDK streams via\n * `onDelta` callbacks; we bridge those into a pull-based async generator so both\n * `doStream` and `doGenerate` can consume them.\n */\nexport async function* streamAgentTurn(\n agent: AgentLike,\n message: SDKUserMessage,\n options: StreamAgentTurnOptions,\n): AsyncGenerator<CursorEvent> {\n const queue: CursorEvent[] = [];\n let wake: (() => void) | undefined;\n let finished = false;\n let failure: unknown;\n\n // Opt-in stderr tracing of what the live agent emits (set OPENCODE_CURSOR_DEBUG=1).\n const debug = process.env.OPENCODE_CURSOR_DEBUG === \"1\";\n const counts: Record<string, number> = {};\n\n // Stall watchdog: if no event arrives within stallMs, cancel the wedged run\n // and force-resend once (pre-first-event only). `0` disables.\n const stallMs = Number(process.env.OPENCODE_CURSOR_STALL_MS ?? 60_000);\n let stallTimer: ReturnType<typeof setTimeout> | undefined;\n let forced = false;\n let anyEvent = false;\n\n const push = (event: CursorEvent) => {\n anyEvent = true;\n queue.push(event);\n wake?.();\n wake = undefined;\n armWatchdog();\n };\n\n const armWatchdog = () => {\n if (stallMs <= 0 || finished) return;\n if (stallTimer) clearTimeout(stallTimer);\n stallTimer = setTimeout(() => {\n void onStall();\n }, stallMs);\n stallTimer.unref?.();\n };\n\n const onDelta = ({ update }: { update: { type: string } & Record<string, any> }) => {\n if (debug) counts[update.type] = (counts[update.type] ?? 0) + 1;\n switch (update.type) {\n case \"text-delta\":\n push({ type: \"text-delta\", text: update.text });\n break;\n case \"thinking-delta\":\n push({ type: \"reasoning-delta\", text: update.text });\n break;\n case \"thinking-completed\":\n push({ type: \"reasoning-complete\", durationMs: update.thinkingDurationMs as number | undefined });\n break;\n case \"summary-started\":\n case \"summary\":\n case \"summary-completed\":\n push({ type: \"compaction\" });\n break;\n case \"partial-tool-call\":\n push({\n type: \"tool-input-partial\",\n id: String(update.callId),\n name: toolDisplayName(update.toolCall),\n input: update.toolCall?.args ?? {},\n });\n break;\n case \"tool-call-started\":\n push({\n type: \"tool-call\",\n id: String(update.callId),\n name: toolDisplayName(update.toolCall),\n input: update.toolCall?.args ?? {},\n });\n break;\n case \"tool-call-completed\": {\n const tool = update.toolCall ?? {};\n const result = tool.result;\n // MCP failures often arrive as {status:\"success\", value:{isError:true}}\n // (the MCP-protocol error flag), not as a top-level status error.\n const mcpError = tool.type === \"mcp\" && result?.value?.isError === true;\n push({\n type: \"tool-result\",\n id: String(update.callId),\n name: toolDisplayName(tool),\n result: result ?? null,\n isError: result?.status === \"error\" || mcpError,\n });\n break;\n }\n case \"turn-ended\":\n if (update.usage) {\n const summed = addUsage(options.usageBase, update.usage as CursorUsage);\n if (summed) push({ type: \"usage\", usage: summed });\n }\n break;\n }\n };\n\n const runHolder: { run?: AgentRunLike } = {};\n const onAbort = () => {\n // Clear the stall timer so an armed watchdog can't fire a force-resend of\n // an aborted turn (abort during the pre-first-event wait would otherwise\n // still trip onStall).\n if (stallTimer) clearTimeout(stallTimer);\n stallTimer = undefined;\n void Promise.resolve(runHolder.run?.cancel()).catch(() => {});\n };\n options.abortSignal?.addEventListener(\"abort\", onAbort);\n\n // Kick off the turn. Resolve text from run.wait() for models that don't emit\n // incremental text deltas. `runGen` disambiguates run invocations: when the\n // watchdog cancels a wedged run and starts a fresh one, the stale run's\n // completion handlers must NOT finish the stream (a new run is in flight).\n let runGen = 0;\n const startRun = (force: boolean): void => {\n const gen = ++runGen;\n void sendWithRecovery(\n agent,\n message,\n {\n mode: options.mode,\n onDelta,\n ...(options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {}),\n ...(force ? { local: { force: true } } : {}),\n },\n debug,\n )\n .then(async (run) => {\n runHolder.run = run;\n // The signal may have fired while send() was in flight (before runHolder\n // was populated, so onAbort had nothing to cancel); cancel now.\n if (options.abortSignal?.aborted) void Promise.resolve(run.cancel()).catch(() => {});\n const result = await run.wait();\n if (debug) {\n console.error(\n `[cursor:debug] updates=${JSON.stringify(counts)} status=${result.status} resultLen=${(result.result ?? \"\").length}`,\n );\n }\n // Superseded by a watchdog force-resend: this run is abandoned.\n if (gen !== runGen || finished) return;\n if (result.status === \"error\") {\n // Surface the failure instead of finishing silently — a silent stop\n // leaves opencode showing dangling tool calls with no explanation.\n throw new Error(\n `Cursor run ended with status \"error\"${result.result ? `: ${result.result}` : \"\"}`,\n );\n }\n // A cancelled run finishes without fabricating final text.\n push({ type: \"finish\", ...(result.status === \"cancelled\" ? {} : { text: result.result }) });\n })\n .catch((err) => {\n if (gen !== runGen) return;\n failure = err;\n if (debug) console.error(`[cursor:debug] send failed: ${err instanceof Error ? err.message : String(err)}`);\n })\n .finally(() => {\n // Only the live run finishes the stream; a superseded (cancelled-for-\n // resend) run leaves `finished` untouched so the resend can complete.\n if (gen !== runGen) return;\n finished = true;\n if (stallTimer) clearTimeout(stallTimer);\n wake?.();\n wake = undefined;\n });\n };\n\n const onStall = async (): Promise<void> => {\n if (finished) return;\n // The turn was aborted: don't resend or surface a spurious stall error.\n if (options.abortSignal?.aborted) return;\n const failTerminal = async (message: string): Promise<void> => {\n // Cancel the wedged server run (best-effort) so it isn't orphaned in a\n // RUNNING state, then surface the stall as a terminal failure.\n try {\n await runHolder.run?.cancel();\n } catch {\n /* best effort */\n }\n failure = new Error(message);\n finished = true;\n if (stallTimer) clearTimeout(stallTimer);\n stallTimer = undefined;\n wake?.();\n wake = undefined;\n };\n if (anyEvent) {\n // A stall AFTER partial output is terminal: force-resending would\n // re-emit the already-yielded prefix. Cancel the wedged run and surface\n // the stall instead.\n await failTerminal(`Cursor run stalled (no events for ${stallMs}ms)`);\n return;\n }\n if (forced) {\n await failTerminal(`Cursor run stalled twice (no events for ${stallMs}ms)`);\n return;\n }\n forced = true;\n if (debug) console.error(\"[cursor:debug] stream stalled; cancelling and resending with local.force\");\n try {\n await runHolder.run?.cancel();\n } catch {\n /* best effort */\n }\n armWatchdog();\n startRun(true);\n };\n\n armWatchdog();\n startRun(false);\n\n try {\n while (true) {\n if (queue.length > 0) {\n yield queue.shift()!;\n continue;\n }\n if (finished) break;\n await new Promise<void>((resolve) => {\n wake = resolve;\n });\n }\n // Drain anything queued right before completion.\n while (queue.length > 0) yield queue.shift()!;\n if (failure) throw failure;\n } finally {\n if (stallTimer) clearTimeout(stallTimer);\n options.abortSignal?.removeEventListener(\"abort\", onAbort);\n }\n}\n\nconst sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\n\n/** Bounded backoff for retryable send failures (ms per attempt). */\nconst RETRY_BACKOFF_MS = [500, 1500] as const;\n\n/**\n * Send a message on an agent with typed recovery (see error-classify.ts):\n * - agent-busy: a previous crash left a persisted run wedged — resend once\n * with `local.force` to expire it (SDK-documented recovery).\n * - rate-limit / network: bounded exponential backoff on the SAME agent; the\n * shared idempotencyKey makes the resend a server-side dedupe, not a dup.\n * - everything else: rethrow (auth/config fail fast upstream; unknown is\n * handled by the caller's fresh-replay path).\n */\nexport async function sendWithRecovery(\n agent: AgentLike,\n message: SDKUserMessage,\n sendOptions: AgentSendOptions,\n debug: boolean,\n): Promise<AgentRunLike> {\n for (let attempt = 0; ; attempt++) {\n try {\n return await agent.send(message, sendOptions);\n } catch (err) {\n const classified = classifyError(err);\n if (classified.kind === \"agent-busy\") {\n if (debug) console.error(\"[cursor:debug] agent busy; retrying send with local.force\");\n return agent.send(message, { ...sendOptions, local: { force: true } });\n }\n if (\n (classified.kind === \"rate-limit\" || classified.kind === \"network\") &&\n attempt < RETRY_BACKOFF_MS.length\n ) {\n if (debug)\n console.error(\n `[cursor:debug] ${classified.kind}; retrying send in ${RETRY_BACKOFF_MS[attempt]}ms`,\n );\n await sleep(RETRY_BACKOFF_MS[attempt]!);\n continue;\n }\n throw err;\n }\n }\n}\n\n/**\n * Send a single turn on an already-acquired agent WITHOUT streaming anything\n * back. Used to replay the leading messages of a multi-message interjection\n * (two-or-more user messages queued while the agent was busy): messages\n * `1..N-1` are sent silently and awaited, and only the final message streams\n * via {@link streamAgentTurn}. This mirrors opencode's own model, where\n * interjected messages fold into a single visible turn.\n *\n * Honors `options.abortSignal`: an abort cancels the in-flight run so the\n * caller can stop before sending the next queued message.\n *\n * Known trade-offs of silent turns being FULL agent runs:\n * - Tool invisibility: the agent may execute tools (shell, edits, MCP) during\n * a silent turn with zero streamed output or tool display — the user sees\n * nothing until the final message streams. Accepted because interjections\n * are typically short course-corrections, and opencode itself folds\n * interjected messages into one visible turn.\n * - Serial latency: each silent turn is awaited to completion before the next\n * send, so an N-message interjection costs N sequential agent runs.\n *\n * Concatenating the queued messages into one Cursor message was rejected for\n * message fidelity: each interjection must land as a distinct user turn in the\n * agent's conversation memory (mirroring opencode's transcript), so the model\n * sees the same message boundaries the user created and later fingerprint\n * classification stays aligned turn-for-turn.\n */\nexport async function sendAgentTurnSilently(\n agent: AgentLike,\n message: SDKUserMessage,\n options: StreamAgentTurnOptions,\n): Promise<CursorUsage | undefined> {\n // Already aborted: don't start a turn just to cancel it.\n if (options.abortSignal?.aborted) return undefined;\n const debug = process.env.OPENCODE_CURSOR_DEBUG === \"1\";\n const runHolder: { run?: AgentRunLike } = {};\n // Capture only the turn-ended usage; a silent turn streams nothing else.\n let usage: CursorUsage | undefined;\n const onDelta = ({ update }: { update: { type: string } & Record<string, any> }) => {\n if (update.type === \"turn-ended\" && update.usage) usage = update.usage as CursorUsage;\n };\n const onAbort = () => {\n void Promise.resolve(runHolder.run?.cancel()).catch(() => {});\n };\n options.abortSignal?.addEventListener(\"abort\", onAbort);\n try {\n const run = await sendWithRecovery(\n agent,\n message,\n { mode: options.mode, onDelta, ...(options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {}) },\n debug,\n );\n runHolder.run = run;\n // The signal may have fired while send() was in flight (before runHolder\n // was populated, so onAbort had nothing to cancel); cancel now.\n if (options.abortSignal?.aborted) void Promise.resolve(run.cancel()).catch(() => {});\n const result = await run.wait();\n if (result.status !== \"finished\") {\n // Our own abort cancelled the run mid-flight: expected, not a failure.\n // The caller's abort check stops the multi-send sequence and drops the\n // session record, so this partial turn is never counted as delivered.\n if (options.abortSignal?.aborted) return undefined;\n // Anything else (\"error\", an external \"cancelled\", unknown states) means\n // the message was NOT delivered; treating it as success would leave the\n // session record claiming the agent saw a message it never received.\n throw new Error(\n `Cursor run ended with status \"${result.status}\"${result.result ? `: ${result.result}` : \"\"}`,\n );\n }\n return usage;\n } finally {\n options.abortSignal?.removeEventListener(\"abort\", onAbort);\n }\n}\n","import type { AgentModeOption, ModelSelection } from \"@cursor/sdk\";\n\n/** Per-model static control defaults (from provider/model config options). */\nexport interface StaticControls {\n mode: AgentModeOption;\n /** Default Cursor model params (id -> value), e.g. { thinking: \"high\" }. */\n params?: Record<string, string>;\n /**\n * Per-model floor params, applied UNDER {@link params} and per-request options\n * (an explicit param always wins). Pins Cursor's boolean toggles, e.g.\n * `{ fast: \"false\" }`, when a turn arrives with no params of its own.\n */\n defaults?: Record<string, string>;\n}\n\nexport interface ResolvedControls {\n mode: AgentModeOption;\n modelSelection: ModelSelection;\n}\n\n/**\n * Build a Cursor `ModelSelection` from a model id and an optional map of model\n * params (e.g. `{ thinking: \"high\" }`). Shared by the provider control\n * resolution and the cloud/delegate tools so param handling stays consistent.\n */\nexport function buildModelSelection(\n modelId: string,\n params?: Record<string, string>,\n): ModelSelection {\n const paramList = Object.entries(params ?? {}).map(([id, value]) => ({ id, value }));\n return paramList.length > 0 ? { id: modelId, params: paramList } : { id: modelId };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isMode(value: unknown): value is AgentModeOption {\n return value === \"agent\" || value === \"plan\";\n}\n\n/**\n * Resolve the per-turn Cursor controls from static config plus opencode's\n * per-request `providerOptions.cursor` (which carries merged model `options` and\n * the selected model `variant`). Per-request values win over static defaults.\n *\n * Recognized keys in `providerOptions.cursor`:\n * - `mode`: \"agent\" | \"plan\"\n * - `params`: Record<string,string> of Cursor model params (e.g. { thinking: \"high\" })\n * - `thinking`: string convenience, mapped to the `thinking` param if not already set\n */\nexport function resolveControls(\n modelId: string,\n staticControls: StaticControls,\n providerOptions: Record<string, unknown> | undefined,\n): ResolvedControls {\n const po = providerOptions ?? {};\n\n const mode: AgentModeOption = isMode(po[\"mode\"]) ? po[\"mode\"] : staticControls.mode;\n\n const params: Record<string, string> = {\n ...(staticControls.defaults ?? {}),\n ...(staticControls.params ?? {}),\n };\n if (isRecord(po[\"params\"])) {\n for (const [key, value] of Object.entries(po[\"params\"])) {\n if (value != null) params[key] = String(value);\n }\n }\n if (typeof po[\"thinking\"] === \"string\" && params[\"thinking\"] === undefined) {\n params[\"thinking\"] = po[\"thinking\"];\n }\n\n return { mode, modelSelection: buildModelSelection(modelId, params) };\n}\n","import { mkdirSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { homedir, tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { TranscriptRecord } from \"./transcript-fingerprint.js\";\n\n/**\n * Best-effort disk persistence for the session pool's fingerprint records, so\n * `session: \"auto\"` survives opencode restarts: the pool can re-resume a\n * session's Cursor agent (whose conversation lives in Cursor's own checkpoint\n * store) instead of paying a cache-cold full-transcript replay.\n *\n * Follows the model-cache pattern: JSON under `~/.cache/opencode-cursor/`,\n * never throws, treats the file as an optimization only. Multiple opencode\n * processes write last-wins on the whole file — a lost record costs exactly\n * one self-healing full replay, which is the same as not having the store.\n */\n\n/** A record persists this long after its last turn before being pruned. */\nconst ENTRY_TTL_MS = 7 * 24 * 60 * 60 * 1000;\n/** Cap stored sessions (most recently used win) to bound file growth. */\nconst MAX_ENTRIES = 200;\n\nexport interface StoredSessionRecord extends TranscriptRecord {\n\tupdatedAt: number;\n}\n\ninterface StoreEnvelope {\n\tsessions: Record<string, StoredSessionRecord>;\n}\n\nfunction storeDir(): string {\n\tconst base =\n\t\tprocess.env.XDG_CACHE_HOME?.trim() ||\n\t\t(homedir() ? join(homedir(), \".cache\") : tmpdir());\n\treturn join(base, \"opencode-cursor\");\n}\n\nfunction storeFile(): string {\n\treturn join(storeDir(), \"session-pool.json\");\n}\n\nfunction isStoredRecord(value: unknown): value is StoredSessionRecord {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tconst v = value as Record<string, unknown>;\n\treturn (\n\t\ttypeof v[\"agentId\"] === \"string\" &&\n\t\ttypeof v[\"systemHash\"] === \"string\" &&\n\t\tArray.isArray(v[\"userHashes\"]) &&\n\t\t(v[\"userHashes\"] as unknown[]).every((h) => typeof h === \"string\") &&\n\t\ttypeof v[\"updatedAt\"] === \"number\"\n\t);\n}\n\n/** Load persisted records, dropping expired/corrupt entries. Never throws. */\nexport function loadSessionRecords(\n\tnow = Date.now(),\n): Map<string, StoredSessionRecord> {\n\tconst out = new Map<string, StoredSessionRecord>();\n\ttry {\n\t\tconst parsed = JSON.parse(\n\t\t\treadFileSync(storeFile(), \"utf8\"),\n\t\t) as StoreEnvelope;\n\t\tif (typeof parsed?.sessions !== \"object\" || parsed.sessions === null)\n\t\t\treturn out;\n\t\tfor (const [key, value] of Object.entries(parsed.sessions)) {\n\t\t\tif (!isStoredRecord(value)) continue;\n\t\t\tif (now - value.updatedAt > ENTRY_TTL_MS) continue;\n\t\t\tout.set(key, value);\n\t\t}\n\t} catch {\n\t\t// Missing/corrupt store: start empty.\n\t}\n\treturn out;\n}\n\n/** Persist records (pruned to TTL + entry cap). Best-effort; never throws. */\nexport function saveSessionRecords(\n\trecords: ReadonlyMap<string, StoredSessionRecord>,\n\tnow = Date.now(),\n): void {\n\ttry {\n\t\tconst live = [...records.entries()]\n\t\t\t.filter(([, r]) => now - r.updatedAt <= ENTRY_TTL_MS)\n\t\t\t.sort(([, a], [, b]) => b.updatedAt - a.updatedAt)\n\t\t\t.slice(0, MAX_ENTRIES);\n\t\tmkdirSync(storeDir(), { recursive: true });\n\t\tconst envelope: StoreEnvelope = { sessions: Object.fromEntries(live) };\n\t\twriteFileSync(storeFile(), JSON.stringify(envelope), \"utf8\");\n\t} catch {\n\t\t// Persistence is an optimization; ignore write failures.\n\t}\n}\n\n/** Delete the store file (test/diagnostic helper). Never throws. */\nexport function deleteSessionStore(): void {\n\ttry {\n\t\trmSync(storeFile(), { force: true });\n\t} catch {\n\t\t// best effort\n\t}\n}\n","import type {\n\tAgentDefinition,\n\tAgentModeOption,\n\tMcpServerConfig,\n\tModelSelection,\n\tSettingSource,\n} from \"@cursor/sdk\";\nimport { loadAgentBackend, type AgentLike } from \"./agent-backend.js\";\nimport {\n\tdeleteSessionStore,\n\tloadSessionRecords,\n\tsaveSessionRecords,\n\ttype StoredSessionRecord,\n} from \"./session-store.js\";\nimport type { TranscriptRecord } from \"./transcript-fingerprint.js\";\n\n/** sessionID -> fingerprint record, so a session reuses one Cursor agent across turns. */\nconst pool = new Map<string, StoredSessionRecord>();\n\n/**\n * Lazily merge disk-persisted records into the in-memory pool (memory wins),\n * so `session: \"auto\"` resumes a session's Cursor agent even after an opencode\n * restart. The agent's conversation itself lives in Cursor's checkpoint store;\n * this only restores our agentId + fingerprint bookkeeping.\n */\nlet hydrated = false;\nfunction hydrate(): void {\n\tif (hydrated) return;\n\thydrated = true;\n\tfor (const [key, record] of loadSessionRecords()) {\n\t\tif (!pool.has(key)) pool.set(key, record);\n\t}\n}\n\n/** Read the fingerprint record pooled for a session (undefined if none). */\nexport function getSessionRecord(\n\tsessionID: string,\n): TranscriptRecord | undefined {\n\thydrate();\n\treturn pool.get(sessionID);\n}\n\n/**\n * Drop a session's pooled record so the NEXT turn classifies as \"new\" (fresh\n * agent + full transcript replay). Called when a multi-message replay fails or\n * aborts mid-sequence: the record was written optimistically with the full new\n * fingerprint before delivery, so leaving it in place would let a later\n * \"continuation\" resume on top of messages the agent never received.\n */\nexport function dropSessionRecord(sessionID: string): void {\n\thydrate();\n\tif (pool.delete(sessionID)) saveSessionRecords(pool);\n}\n\n/** Test/diagnostic helpers. */\nexport function getPooledAgentId(sessionID: string): string | undefined {\n\thydrate();\n\treturn pool.get(sessionID)?.agentId;\n}\nexport function clearAgentPool(): void {\n\tpool.clear();\n\thydrated = true; // don't re-hydrate stale disk state into a cleared pool\n\tdeleteSessionStore();\n}\n/** Test hook: drop in-memory state only, as if the process restarted. */\nexport function resetSessionPoolMemory(): void {\n\tpool.clear();\n\thydrated = false;\n}\n\nexport interface AcquireAgentParams {\n\tapiKey: string;\n\tmodelSelection: ModelSelection;\n\tmode: AgentModeOption;\n\t/** SDK `local.cwd` accepts a single root or several (multi-root workspace). */\n\tcwd: string | string[];\n\tsettingSources?: SettingSource[];\n\tsandbox?: boolean;\n\tautoReview?: boolean;\n\tmcpServers?: Record<string, McpServerConfig>;\n\tagents?: Record<string, AgentDefinition>;\n\tname?: string;\n\t/**\n\t * Resume this Cursor agent before falling back to a fresh create. Set for a\n\t * fingerprinted \"continuation\" (the pooled agentId) or an explicit\n\t * `providerOptions.cursor.agentId`. A failed resume degrades to create.\n\t */\n\tresumeAgentId?: string;\n\t/**\n\t * Pool the resulting agent under this opencode session id. When set, the\n\t * agent persists across turns (release() does not close it) and `record` is\n\t * stored for the next turn's classification. When undefined, no pooling and\n\t * the agent is closed on release.\n\t */\n\tpoolKey?: string;\n\t/** Fingerprint of the current prompt, stored when `poolKey` is set. */\n\trecord?: { systemHash: string; userHashes: string[]; mcpHash?: string };\n}\n\nexport interface AcquiredAgent {\n\tagent: AgentLike;\n\t/** True when an existing agent was resumed (send only the new turn). */\n\tresumed: boolean;\n\t/** Close the agent unless it's pooled (pooled agents persist for the next turn). */\n\trelease: () => void;\n}\n\n/**\n * Get an agent to run a turn. Attempts a resume of `resumeAgentId` when given,\n * otherwise creates a fresh agent; a failed resume degrades to a fresh create\n * (so a stale/expired pool entry becomes a correct full-transcript turn rather\n * than an error). When `poolKey` is set, the resulting agent + `record` are\n * pooled for the session and survive `release()`.\n */\nexport async function acquireAgent(\n\tparams: AcquireAgentParams,\n): Promise<AcquiredAgent> {\n\tconst backend = loadAgentBackend();\n\n\tconst createOptions = {\n\t\tapiKey: params.apiKey,\n\t\tmodel: params.modelSelection,\n\t\tmode: params.mode,\n\t\tlocal: {\n\t\t\tcwd: params.cwd,\n\t\t\t...(params.settingSources\n\t\t\t\t? { settingSources: params.settingSources }\n\t\t\t\t: {}),\n\t\t\t...(params.sandbox !== undefined\n\t\t\t\t? { sandboxOptions: { enabled: params.sandbox } }\n\t\t\t\t: {}),\n\t\t\t...(params.autoReview !== undefined\n\t\t\t\t? { autoReview: params.autoReview }\n\t\t\t\t: {}),\n\t\t},\n\t\t...(params.mcpServers ? { mcpServers: params.mcpServers } : {}),\n\t\t...(params.agents ? { agents: params.agents } : {}),\n\t\t...(params.name ? { name: params.name } : {}),\n\t};\n\n\tlet agent: AgentLike | undefined;\n\tlet resumed = false;\n\tif (params.resumeAgentId) {\n\t\ttry {\n\t\t\tagent = await backend.resumeAgent(params.resumeAgentId, createOptions);\n\t\t\tresumed = true;\n\t\t} catch {\n\t\t\t// Stale/expired id: fall through to a fresh create (full replay).\n\t\t}\n\t}\n\tif (!agent) {\n\t\tagent = await backend.createAgent(createOptions);\n\t}\n\n\tconst pooling = params.poolKey !== undefined;\n\tif (pooling && params.record) {\n\t\thydrate();\n\t\tpool.set(params.poolKey!, {\n\t\t\tagentId: agent.agentId,\n\t\t\tsystemHash: params.record.systemHash,\n\t\t\tuserHashes: params.record.userHashes,\n\t\t\t...(params.record.mcpHash !== undefined\n\t\t\t\t? { mcpHash: params.record.mcpHash }\n\t\t\t\t: {}),\n\t\t\tupdatedAt: Date.now(),\n\t\t});\n\t\t// Persist so session reuse survives opencode restarts (best-effort).\n\t\tsaveSessionRecords(pool);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,EAAE,MAAM,OAAO,KAAK,IAAI,CAAC;AAAA,EAC5C;AAEA,MAAI;AACJ,MAAI,UAAU;AACd,MAAI,OAAO,eAAe;AACzB,QAAI;AACH,cAAQ,MAAM,QAAQ,YAAY,OAAO,eAAe,aAAa;AACrE,gBAAU;AAAA,IACX,QAAQ;AAAA,IAER;AAAA,EACD;AACA,MAAI,CAAC,OAAO;AACX,YAAQ,MAAM,QAAQ,YAAY,aAAa;AAAA,EAChD;AAEA,QAAM,UAAU,OAAO,YAAY;AACnC,MAAI,WAAW,OAAO,QAAQ;AAC7B,YAAQ;AACR,SAAK,IAAI,OAAO,SAAU;AAAA,MACzB,SAAS,MAAM;AAAA,MACf,YAAY,OAAO,OAAO;AAAA,MAC1B,YAAY,OAAO,OAAO;AAAA,MAC1B,GAAI,OAAO,OAAO,YAAY,SAC3B,EAAE,SAAS,OAAO,OAAO,QAAQ,IACjC,CAAC;AAAA,MACJ,WAAW,KAAK,IAAI;AAAA,IACrB,CAAC;AAED,uBAAmB,IAAI;AAAA,EACxB;AAEA,QAAM,UAAU,MAAM;AACrB,QAAI,CAAC,SAAS;AACb,UAAI;AACH,cAAO,MAAM;AAAA,MACd,QAAQ;AAAA,MAER;AAAA,IACD;AAAA,EACD;AAEA,SAAO,EAAE,OAAO,SAAS,QAAQ;AAClC;","names":["cached","existsSync","message","mkdirSync","readFileSync","rmSync","writeFileSync","join"]}
|
package/dist/plugin/index.js
CHANGED
|
@@ -7,7 +7,7 @@ import {
|
|
|
7
7
|
resolveControls,
|
|
8
8
|
resolveCursorApiKey,
|
|
9
9
|
streamAgentTurn
|
|
10
|
-
} from "../chunk-
|
|
10
|
+
} from "../chunk-LAOFD3JB.js";
|
|
11
11
|
|
|
12
12
|
// src/model-cache.ts
|
|
13
13
|
import { mkdirSync, readFileSync, writeFileSync } from "fs";
|
|
@@ -91,9 +91,26 @@ function defaultModelParams(item) {
|
|
|
91
91
|
}
|
|
92
92
|
return out;
|
|
93
93
|
}
|
|
94
|
+
function variantKey(displayName) {
|
|
95
|
+
return displayName.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "") || "variant";
|
|
96
|
+
}
|
|
94
97
|
function buildModelVariants(item) {
|
|
95
|
-
const out = {};
|
|
96
98
|
const defaults = defaultModelParams(item);
|
|
99
|
+
const sdkVariants = item.variants ?? [];
|
|
100
|
+
if (sdkVariants.length > 0) {
|
|
101
|
+
const out2 = {};
|
|
102
|
+
for (const v of sdkVariants) {
|
|
103
|
+
if (v.isDefault === true) continue;
|
|
104
|
+
const params = { ...defaults };
|
|
105
|
+
for (const p of v.params ?? []) params[p.id] = p.value;
|
|
106
|
+
const key = variantKey(v.displayName);
|
|
107
|
+
let candidate = key;
|
|
108
|
+
for (let n = 2; out2[candidate] !== void 0; n++) candidate = `${key}-${n}`;
|
|
109
|
+
out2[candidate] = { params };
|
|
110
|
+
}
|
|
111
|
+
return out2;
|
|
112
|
+
}
|
|
113
|
+
const out = {};
|
|
97
114
|
const hasEffortEnum = (item.parameters ?? []).some(
|
|
98
115
|
(p) => REASONING_PARAM.test(p.id) && !isBooleanParam(paramValues(p)) && paramValues(p).length > 0
|
|
99
116
|
);
|
|
@@ -401,6 +418,8 @@ async function runDelegate(params) {
|
|
|
401
418
|
case "reasoning-delta":
|
|
402
419
|
reasoning.push(event.text);
|
|
403
420
|
break;
|
|
421
|
+
case "tool-input-partial":
|
|
422
|
+
break;
|
|
404
423
|
case "tool-call":
|
|
405
424
|
toolActivity.push({ name: event.name, isError: false });
|
|
406
425
|
break;
|
|
@@ -411,6 +430,9 @@ async function runDelegate(params) {
|
|
|
411
430
|
case "usage":
|
|
412
431
|
usage = event.usage;
|
|
413
432
|
break;
|
|
433
|
+
case "reasoning-complete":
|
|
434
|
+
case "compaction":
|
|
435
|
+
break;
|
|
414
436
|
case "finish":
|
|
415
437
|
if (event.text && text.length === 0) text.push(event.text);
|
|
416
438
|
break;
|
|
@@ -512,6 +534,7 @@ function buildCursorTools(deps) {
|
|
|
512
534
|
mode: s.enum(["agent", "plan"]).optional().describe("Conversation mode."),
|
|
513
535
|
thinking: s.string().optional().describe("Thinking level, e.g. 'high'."),
|
|
514
536
|
cwd: s.string().optional().describe("Working directory (defaults to the session directory)."),
|
|
537
|
+
additionalCwds: s.array(s.string()).optional().describe("Extra workspace roots; combined with cwd into a multi-root agent workspace."),
|
|
515
538
|
sandbox: s.boolean().optional().describe("Run the agent's tools in Cursor's sandbox."),
|
|
516
539
|
agentId: s.string().optional().describe("Resume a specific Cursor agent id instead of starting fresh.")
|
|
517
540
|
},
|
|
@@ -527,11 +550,12 @@ function buildCursorTools(deps) {
|
|
|
527
550
|
}
|
|
528
551
|
let result;
|
|
529
552
|
try {
|
|
553
|
+
const baseCwd = args.cwd ?? context.directory ?? deps.defaultCwd();
|
|
530
554
|
result = await runDelegate({
|
|
531
555
|
apiKey,
|
|
532
556
|
prompt: args.prompt,
|
|
533
557
|
model: args.model,
|
|
534
|
-
cwd: args.
|
|
558
|
+
cwd: args.additionalCwds?.length ? [baseCwd, ...args.additionalCwds] : baseCwd,
|
|
535
559
|
...args.mode ? { mode: args.mode } : {},
|
|
536
560
|
...args.thinking ? { thinking: args.thinking } : {},
|
|
537
561
|
...args.sandbox !== void 0 ? { sandbox: args.sandbox } : {},
|
|
@@ -598,7 +622,7 @@ function writeCache(latest) {
|
|
|
598
622
|
}
|
|
599
623
|
}
|
|
600
624
|
function getLocalVersion() {
|
|
601
|
-
if (true) return "0.
|
|
625
|
+
if (true) return "0.5.0";
|
|
602
626
|
try {
|
|
603
627
|
const require2 = createRequire(import.meta.url);
|
|
604
628
|
const pkg = require2("../package.json");
|