-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathplugin.js
More file actions
545 lines (545 loc) · 23.2 KB
/
Copy pathplugin.js
File metadata and controls
545 lines (545 loc) · 23.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
const CURSOR_PROVIDER_ID = "cursor";
// Local proxy server that translates OpenAI-compatible HTTP to cursor-agent CLI.
const CURSOR_PROXY_HOST = "127.0.0.1";
const CURSOR_PROXY_DEFAULT_PORT = 32123;
const CURSOR_PROXY_DEFAULT_BASE_URL = `http://${CURSOR_PROXY_HOST}:${CURSOR_PROXY_DEFAULT_PORT}/v1`;
function openAIError(status, message, details) {
const body = {
error: {
message: details ? `${message}\n${details}` : message,
type: "cursor_agent_error",
param: null,
code: null,
},
};
return new Response(JSON.stringify(body), {
status,
headers: { "Content-Type": "application/json" },
});
}
function normalizeCursorAgentModel(model) {
if (!model)
return "auto";
const aliases = {
"gpt-5": "gpt-5.2",
"sonnet-4": "sonnet-4.5",
};
return aliases[model] || model;
}
function summarizeTool(tool) {
const name = tool?.function?.name || "unknown";
const description = tool?.function?.description || "";
const params = tool?.function?.parameters;
let paramsSummary = "";
if (params && typeof params === "object") {
const props = params.properties && typeof params.properties === "object" ? Object.keys(params.properties) : [];
const required = Array.isArray(params.required) ? params.required : [];
paramsSummary = `args: { ${props.join(", ")} } required: [${required.join(", ")}]`;
}
return `- ${name}${description ? `: ${description}` : ""}${paramsSummary ? ` (${paramsSummary})` : ""}`;
}
function extractPromptFromChatCompletions(body) {
const model = typeof body?.model === "string" ? body.model : undefined;
const stream = body?.stream === true;
const tools = Array.isArray(body?.tools) ? body.tools : [];
const messages = Array.isArray(body?.messages) ? body.messages : [];
const lines = [];
for (const message of messages) {
const role = typeof message.role === "string" ? message.role : "user";
if (role === "tool") {
const name = typeof message.name === "string" ? message.name : "tool";
const toolCallId = typeof message.tool_call_id === "string" ? message.tool_call_id : "";
const content = typeof message.content === "string" ? message.content : JSON.stringify(message.content ?? "");
lines.push(`TOOL RESULT (${name}${toolCallId ? `, id=${toolCallId}` : ""}): ${content}`);
continue;
}
if (role === "assistant" && Array.isArray(message.tool_calls)) {
lines.push(`ASSISTANT TOOL_CALLS: ${JSON.stringify(message.tool_calls)}`);
continue;
}
const content = message.content;
if (typeof content === "string") {
lines.push(`${role.toUpperCase()}: ${content}`);
continue;
}
if (Array.isArray(content)) {
const textParts = content
.map((part) => {
if (part && typeof part === "object" && part.type === "text" && typeof part.text === "string") {
return part.text;
}
return "";
})
.filter(Boolean);
if (textParts.length) {
lines.push(`${role.toUpperCase()}: ${textParts.join("\n")}`);
}
continue;
}
}
return { prompt: lines.join("\n\n"), model, stream, tools };
}
function parseToolCallPlan(output) {
const start = output.indexOf("{");
const end = output.lastIndexOf("}");
if (start === -1 || end === -1 || end <= start)
return null;
const jsonText = output.slice(start, end + 1);
try {
const parsed = JSON.parse(jsonText);
if (parsed && parsed.action === "final" && typeof parsed.content === "string") {
return { action: "final", content: parsed.content };
}
if (parsed && parsed.action === "tool_call" && Array.isArray(parsed.tool_calls)) {
return {
action: "tool_call",
tool_calls: parsed.tool_calls
.filter((t) => t && typeof t.name === "string")
.map((t) => ({ name: t.name, arguments: t.arguments ?? {} })),
};
}
return null;
}
catch {
return null;
}
}
function buildToolCallingPrompt(conversation, tools, workspaceDirectory) {
const toolList = tools.length ? tools.map(summarizeTool).join("\n") : "(none)";
return [
"You are a tool-calling assistant running inside OpenCode.",
`Workspace directory: ${workspaceDirectory}`,
"",
"Available tools:",
toolList,
"",
"STRICT OUTPUT:",
"- Output MUST be exactly one JSON object and nothing else.",
"- If you output anything outside JSON, your answer is discarded.",
"",
"RESPONSE FORMAT:",
"- Call tool(s):",
'{"action":"tool_call","tool_calls":[{"name":"list","arguments":{"path":"/ABSOLUTE/PATH"}}]}',
"- Final answer:",
'{"action":"final","content":"..."}',
"",
"Task:",
conversation,
].join("\n");
}
function buildCursorSpawnEnv(source) {
const whitelist = [
"PATH",
"HOME",
"SHELL",
"USER",
"LOGNAME",
"LANG",
"LC_ALL",
"LC_CTYPE",
"TERM",
"TMPDIR",
"XDG_RUNTIME_DIR",
"DISPLAY",
];
const output = {};
for (const key of whitelist) {
const value = source[key];
if (typeof value !== "string" || value.length === 0)
continue;
if (value.length > 4096)
continue;
output[key] = value;
}
if (!output.PATH) {
output.PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
}
if (!output.HOME && typeof source.HOME === "string" && source.HOME.length > 0) {
output.HOME = source.HOME;
}
return output;
}
function createChatCompletionResponse(model, content) {
return {
id: `cursor-agent-${Date.now()}`,
object: "chat.completion",
created: Math.floor(Date.now() / 1000),
model,
choices: [
{
index: 0,
message: { role: "assistant", content },
finish_reason: "stop",
},
],
};
}
function createChatCompletionChunk(id, created, model, deltaContent, done = false) {
return {
id,
object: "chat.completion.chunk",
created,
model,
choices: [
{
index: 0,
delta: deltaContent ? { content: deltaContent } : {},
finish_reason: done ? "stop" : null,
},
],
};
}
function getGlobalKey() {
return "__opencode_cursor_proxy_server__";
}
async function ensureCursorProxyServer(workspaceDirectory) {
const key = getGlobalKey();
const g = globalThis;
const existingBaseURL = g[key]?.baseURL;
if (typeof existingBaseURL === "string" && existingBaseURL.length > 0) {
return existingBaseURL;
}
// Mark as starting to avoid duplicate starts in-process.
g[key] = { baseURL: "" };
const handler = async (req) => {
try {
const url = new URL(req.url);
if (url.pathname === "/health") {
return new Response(JSON.stringify({ ok: true }), {
status: 200,
headers: { "Content-Type": "application/json" },
});
}
if (url.pathname !== "/v1/chat/completions" && url.pathname !== "/chat/completions") {
return openAIError(404, `Unsupported path: ${url.pathname}`);
}
const body = await req.json().catch(() => ({}));
const { prompt, model, stream, tools } = extractPromptFromChatCompletions(body);
let selectedModel = normalizeCursorAgentModel(model);
// When tool-calling is enabled and model is "auto", pick a strict model.
if (tools.length && selectedModel === "auto") {
selectedModel = "sonnet-4.5-thinking";
}
const effectivePrompt = tools.length ? buildToolCallingPrompt(prompt, tools, workspaceDirectory) : prompt;
const bunAny = globalThis;
if (!bunAny.Bun?.spawn) {
return openAIError(500, "This provider requires Bun runtime.");
}
const baseCmd = [
"cursor-agent",
"--print",
"--trust",
"--output-format",
"text",
"--workspace",
workspaceDirectory,
"--model",
selectedModel,
];
const spawnEnv = buildCursorSpawnEnv(bunAny.Bun.env);
const spawnWithStdin = () => {
const child = bunAny.Bun.spawn({
cmd: baseCmd,
stdin: "pipe",
stdout: "pipe",
stderr: "pipe",
env: spawnEnv,
});
return {
child,
writeInput: async () => {
if (!child.stdin) {
return;
}
try {
await child.stdin.write(effectivePrompt);
}
finally {
await child.stdin.end();
}
},
};
};
let child;
let writeInput;
({ child, writeInput } = spawnWithStdin());
if (!stream) {
const [stdoutText, stderrText] = await Promise.all([
writeInput(),
new Response(child.stdout).text(),
new Response(child.stderr).text(),
]).then(([, stdout, stderr]) => [stdout, stderr]);
const stdout = (stdoutText || "").trim();
const stderr = (stderrText || "").trim();
// If tools were requested and we can parse a plan, treat it as success even if exitCode != 0.
const plan = tools.length ? parseToolCallPlan(stdout) : null;
if (plan?.action === "tool_call") {
const toolCalls = plan.tool_calls.map((tc, i) => ({
id: `call_${Date.now()}_${i}`,
type: "function",
function: {
name: tc.name,
arguments: JSON.stringify(tc.arguments ?? {}),
},
}));
const payload = {
id: `cursor-agent-${Date.now()}`,
object: "chat.completion",
created: Math.floor(Date.now() / 1000),
model: selectedModel,
choices: [
{
index: 0,
message: {
role: "assistant",
content: "",
tool_calls: toolCalls,
},
finish_reason: "tool_calls",
},
],
};
return new Response(JSON.stringify(payload), {
status: 200,
headers: { "Content-Type": "application/json" },
});
}
if (plan?.action === "final") {
const payload = createChatCompletionResponse(selectedModel, plan.content);
return new Response(JSON.stringify(payload), {
status: 200,
headers: { "Content-Type": "application/json" },
});
}
// cursor-agent sometimes returns non-zero even with usable stdout.
// Treat stdout as success unless we have explicit stderr.
if (child.exitCode !== 0 && stderr.length > 0) {
return openAIError(401, "cursor-agent failed.", stderr);
}
const payload = createChatCompletionResponse(selectedModel, stdout || stderr);
return new Response(JSON.stringify(payload), {
status: 200,
headers: { "Content-Type": "application/json" },
});
}
// Streaming.
const encoder = new TextEncoder();
const id = `cursor-agent-${Date.now()}`;
const created = Math.floor(Date.now() / 1000);
const sse = new ReadableStream({
async start(controller) {
let closed = false;
try {
// Tool-calling + streaming: buffer stdout to decide whether to emit tool_calls.
if (tools.length) {
// Keep the SSE connection alive while cursor-agent thinks.
const heartbeat = () => {
if (closed)
return;
try {
const pingChunk = createChatCompletionChunk(id, created, selectedModel, "", false);
controller.enqueue(encoder.encode(`data: ${JSON.stringify(pingChunk)}\n\n`));
}
catch {
// ignore
}
};
heartbeat();
const interval = setInterval(heartbeat, 1000);
const [stdoutText, stderrText] = await Promise.all([
writeInput(),
new Response(child.stdout).text(),
new Response(child.stderr).text(),
]).then(([, stdout, stderr]) => [stdout, stderr]).finally(() => {
clearInterval(interval);
});
const stdout = (stdoutText || "").trim();
const stderr = (stderrText || "").trim();
const plan = parseToolCallPlan(stdout);
if (plan?.action === "tool_call") {
const toolCalls = plan.tool_calls.map((tc, i) => ({
index: i,
id: `call_${Date.now()}_${i}`,
type: "function",
function: {
name: tc.name,
arguments: JSON.stringify(tc.arguments ?? {}),
},
}));
const chunk = {
id,
object: "chat.completion.chunk",
created,
model: selectedModel,
choices: [
{
index: 0,
delta: {
role: "assistant",
tool_calls: toolCalls,
},
finish_reason: "tool_calls",
},
],
};
controller.enqueue(encoder.encode(`data: ${JSON.stringify(chunk)}\n\n`));
controller.enqueue(encoder.encode("data: [DONE]\n\n"));
return;
}
const content = plan?.action === "final" ? plan.content : stdout;
if (child.exitCode !== 0 && !plan) {
// Don't fail hard if stdout is usable; emit it as final content.
const msg = stdout || stderr;
const finalChunk = createChatCompletionChunk(id, created, selectedModel, msg, true);
controller.enqueue(encoder.encode(`data: ${JSON.stringify(finalChunk)}\n\n`));
controller.enqueue(encoder.encode("data: [DONE]\n\n"));
return;
}
const finalChunk = createChatCompletionChunk(id, created, selectedModel, content, true);
controller.enqueue(encoder.encode(`data: ${JSON.stringify(finalChunk)}\n\n`));
controller.enqueue(encoder.encode("data: [DONE]\n\n"));
return;
}
// No tools: stream stdout as text deltas.
await writeInput();
const decoder = new TextDecoder();
const reader = child.stdout.getReader();
while (true) {
const { value, done } = await reader.read();
if (done)
break;
if (!value || value.length === 0)
continue;
const text = decoder.decode(value, { stream: true });
if (!text)
continue;
const chunk = createChatCompletionChunk(id, created, selectedModel, text, false);
controller.enqueue(encoder.encode(`data: ${JSON.stringify(chunk)}\n\n`));
}
if (child.exitCode !== 0) {
const stderrText = await new Response(child.stderr).text();
const msg = `cursor-agent failed: ${(stderrText || "").trim()}`;
const errChunk = createChatCompletionChunk(id, created, selectedModel, msg, true);
controller.enqueue(encoder.encode(`data: ${JSON.stringify(errChunk)}\n\n`));
controller.enqueue(encoder.encode("data: [DONE]\n\n"));
return;
}
const doneChunk = createChatCompletionChunk(id, created, selectedModel, "", true);
controller.enqueue(encoder.encode(`data: ${JSON.stringify(doneChunk)}\n\n`));
controller.enqueue(encoder.encode("data: [DONE]\n\n"));
}
finally {
closed = true;
controller.close();
}
},
});
return new Response(sse, {
status: 200,
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
},
});
}
catch (error) {
const message = error instanceof Error ? error.message : String(error);
return openAIError(500, "Proxy error", message);
}
};
const bunAny = globalThis;
if (typeof bunAny.Bun !== "undefined" && typeof bunAny.Bun.serve === "function") {
// If another process already started a proxy on the default port, reuse it.
try {
const res = await fetch(`http://${CURSOR_PROXY_HOST}:${CURSOR_PROXY_DEFAULT_PORT}/health`).catch(() => null);
if (res && res.ok) {
g[key].baseURL = CURSOR_PROXY_DEFAULT_BASE_URL;
return CURSOR_PROXY_DEFAULT_BASE_URL;
}
}
catch {
// ignore
}
const startServer = (port) => {
return bunAny.Bun.serve({
hostname: CURSOR_PROXY_HOST,
port,
fetch: handler,
});
};
try {
const server = startServer(CURSOR_PROXY_DEFAULT_PORT);
const baseURL = `http://${CURSOR_PROXY_HOST}:${server.port}/v1`;
g[key].baseURL = baseURL;
return baseURL;
}
catch (error) {
const code = error?.code;
if (code !== "EADDRINUSE") {
throw error;
}
// Something is already bound to the default port. Only reuse it if it looks like our proxy.
try {
const res = await fetch(`http://${CURSOR_PROXY_HOST}:${CURSOR_PROXY_DEFAULT_PORT}/health`).catch(() => null);
if (res && res.ok) {
g[key].baseURL = CURSOR_PROXY_DEFAULT_BASE_URL;
return CURSOR_PROXY_DEFAULT_BASE_URL;
}
}
catch {
// ignore
}
// Fallback: start on a random free port.
const server = startServer(0);
const baseURL = `http://${CURSOR_PROXY_HOST}:${server.port}/v1`;
g[key].baseURL = baseURL;
return baseURL;
}
}
throw new Error("Cursor proxy server requires Bun runtime");
}
export const CursorAuthPlugin = async ({ $, directory }) => {
const proxyBaseURL = await ensureCursorProxyServer(directory);
return {
auth: {
provider: CURSOR_PROVIDER_ID,
async loader(_getAuth) {
return {};
},
methods: [
{
label: "Login via cursor-agent (opens browser)",
type: "api",
authorize: async () => {
const check = await $ `cursor-agent --version`.quiet().nothrow();
if (check.exitCode !== 0) {
return { type: "failed" };
}
const whoami = await $ `cursor-agent whoami`.quiet().nothrow();
const whoamiText = whoami.text();
if (whoamiText.includes("Not logged in")) {
const login = await $ `cursor-agent login`.nothrow();
if (login.exitCode !== 0) {
return { type: "failed" };
}
}
return {
type: "success",
key: "cursor-agent",
};
},
},
],
},
async "chat.params"(input, output) {
if (input.model.providerID !== CURSOR_PROVIDER_ID) {
return;
}
// Always point to the actual proxy base URL (may be dynamically allocated).
output.options.baseURL = proxyBaseURL;
output.options.apiKey = output.options.apiKey || "cursor-agent";
},
};
};
//# sourceMappingURL=plugin.js.map