@playwo/opencode-cursor-oauth 0.0.0-dev.c80ebcb27754 → 0.0.0-dev.da5538092563
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/README.md +32 -83
- package/dist/auth.js +27 -3
- package/dist/constants.d.ts +2 -0
- package/dist/constants.js +2 -0
- package/dist/cursor/bidi-session.d.ts +12 -0
- package/dist/cursor/bidi-session.js +164 -0
- package/dist/cursor/config.d.ts +4 -0
- package/dist/cursor/config.js +4 -0
- package/dist/cursor/connect-framing.d.ts +10 -0
- package/dist/cursor/connect-framing.js +80 -0
- package/dist/cursor/headers.d.ts +6 -0
- package/dist/cursor/headers.js +16 -0
- package/dist/cursor/index.d.ts +5 -0
- package/dist/cursor/index.js +5 -0
- package/dist/cursor/unary-rpc.d.ts +12 -0
- package/dist/cursor/unary-rpc.js +124 -0
- package/dist/index.d.ts +2 -14
- package/dist/index.js +2 -229
- package/dist/logger.d.ts +7 -0
- package/dist/logger.js +150 -0
- package/dist/models.d.ts +3 -0
- package/dist/models.js +80 -54
- package/dist/openai/index.d.ts +3 -0
- package/dist/openai/index.js +3 -0
- package/dist/openai/messages.d.ts +39 -0
- package/dist/openai/messages.js +228 -0
- package/dist/openai/tools.d.ts +7 -0
- package/dist/openai/tools.js +58 -0
- package/dist/openai/types.d.ts +41 -0
- package/dist/openai/types.js +1 -0
- package/dist/plugin/cursor-auth-plugin.d.ts +3 -0
- package/dist/plugin/cursor-auth-plugin.js +139 -0
- package/dist/proto/agent_pb.js +637 -319
- package/dist/provider/index.d.ts +2 -0
- package/dist/provider/index.js +2 -0
- package/dist/provider/model-cost.d.ts +9 -0
- package/dist/provider/model-cost.js +206 -0
- package/dist/provider/models.d.ts +8 -0
- package/dist/provider/models.js +86 -0
- package/dist/proxy/bridge-close-controller.d.ts +6 -0
- package/dist/proxy/bridge-close-controller.js +37 -0
- package/dist/proxy/bridge-non-streaming.d.ts +3 -0
- package/dist/proxy/bridge-non-streaming.js +123 -0
- package/dist/proxy/bridge-session.d.ts +5 -0
- package/dist/proxy/bridge-session.js +11 -0
- package/dist/proxy/bridge-streaming.d.ts +5 -0
- package/dist/proxy/bridge-streaming.js +409 -0
- package/dist/proxy/bridge.d.ts +3 -0
- package/dist/proxy/bridge.js +3 -0
- package/dist/proxy/chat-completion.d.ts +2 -0
- package/dist/proxy/chat-completion.js +153 -0
- package/dist/proxy/conversation-meta.d.ts +12 -0
- package/dist/proxy/conversation-meta.js +1 -0
- package/dist/proxy/conversation-state.d.ts +35 -0
- package/dist/proxy/conversation-state.js +95 -0
- package/dist/proxy/cursor-request.d.ts +6 -0
- package/dist/proxy/cursor-request.js +101 -0
- package/dist/proxy/index.d.ts +12 -0
- package/dist/proxy/index.js +12 -0
- package/dist/proxy/server.d.ts +6 -0
- package/dist/proxy/server.js +107 -0
- package/dist/proxy/sse.d.ts +5 -0
- package/dist/proxy/sse.js +5 -0
- package/dist/proxy/state-sync.d.ts +2 -0
- package/dist/proxy/state-sync.js +17 -0
- package/dist/proxy/stream-dispatch.d.ts +42 -0
- package/dist/proxy/stream-dispatch.js +641 -0
- package/dist/proxy/stream-state.d.ts +7 -0
- package/dist/proxy/stream-state.js +1 -0
- package/dist/proxy/title.d.ts +1 -0
- package/dist/proxy/title.js +103 -0
- package/dist/proxy/types.d.ts +32 -0
- package/dist/proxy/types.js +1 -0
- package/dist/proxy.d.ts +2 -19
- package/dist/proxy.js +2 -1221
- package/package.json +1 -2
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { OPENCODE_TITLE_REQUEST_MARKER } from "../constants";
|
|
3
|
+
/** Normalize OpenAI message content to a plain string. */
|
|
4
|
+
export function textContent(content) {
|
|
5
|
+
if (content == null)
|
|
6
|
+
return "";
|
|
7
|
+
if (typeof content === "string")
|
|
8
|
+
return content;
|
|
9
|
+
return content
|
|
10
|
+
.filter((p) => p.type === "text" && p.text)
|
|
11
|
+
.map((p) => p.text)
|
|
12
|
+
.join("\n");
|
|
13
|
+
}
|
|
14
|
+
export function parseMessages(messages) {
|
|
15
|
+
let systemPrompt = "You are a helpful assistant.";
|
|
16
|
+
// Collect system messages
|
|
17
|
+
const systemParts = messages
|
|
18
|
+
.filter((m) => m.role === "system")
|
|
19
|
+
.map((m) => textContent(m.content));
|
|
20
|
+
if (systemParts.length > 0) {
|
|
21
|
+
systemPrompt = systemParts.join("\n");
|
|
22
|
+
}
|
|
23
|
+
const nonSystem = messages.filter((m) => m.role !== "system");
|
|
24
|
+
const parsedTurns = [];
|
|
25
|
+
let currentTurn;
|
|
26
|
+
for (const msg of nonSystem) {
|
|
27
|
+
if (msg.role === "user") {
|
|
28
|
+
if (currentTurn)
|
|
29
|
+
parsedTurns.push(currentTurn);
|
|
30
|
+
currentTurn = {
|
|
31
|
+
userText: textContent(msg.content),
|
|
32
|
+
segments: [],
|
|
33
|
+
};
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
36
|
+
if (!currentTurn) {
|
|
37
|
+
currentTurn = { userText: "", segments: [] };
|
|
38
|
+
}
|
|
39
|
+
if (msg.role === "assistant") {
|
|
40
|
+
const text = textContent(msg.content);
|
|
41
|
+
if (text) {
|
|
42
|
+
currentTurn.segments.push({ kind: "assistantText", text });
|
|
43
|
+
}
|
|
44
|
+
if (msg.tool_calls?.length) {
|
|
45
|
+
currentTurn.segments.push({
|
|
46
|
+
kind: "assistantToolCalls",
|
|
47
|
+
toolCalls: msg.tool_calls,
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
if (msg.role === "tool") {
|
|
53
|
+
currentTurn.segments.push({
|
|
54
|
+
kind: "toolResult",
|
|
55
|
+
result: {
|
|
56
|
+
toolCallId: msg.tool_call_id ?? "",
|
|
57
|
+
content: textContent(msg.content),
|
|
58
|
+
},
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
if (currentTurn)
|
|
63
|
+
parsedTurns.push(currentTurn);
|
|
64
|
+
let userText = "";
|
|
65
|
+
let toolResults = [];
|
|
66
|
+
let pendingAssistantSummary = "";
|
|
67
|
+
let completedTurnStates = parsedTurns;
|
|
68
|
+
const lastTurn = parsedTurns.at(-1);
|
|
69
|
+
if (lastTurn) {
|
|
70
|
+
const trailingSegments = splitTrailingToolResults(lastTurn.segments);
|
|
71
|
+
const hasAssistantSummary = trailingSegments.base.length > 0;
|
|
72
|
+
if (trailingSegments.trailing.length > 0 && hasAssistantSummary) {
|
|
73
|
+
completedTurnStates = parsedTurns.slice(0, -1);
|
|
74
|
+
userText = lastTurn.userText;
|
|
75
|
+
toolResults = trailingSegments.trailing.map((segment) => segment.result);
|
|
76
|
+
pendingAssistantSummary = summarizeTurnSegments(trailingSegments.base);
|
|
77
|
+
}
|
|
78
|
+
else if (lastTurn.userText && lastTurn.segments.length === 0) {
|
|
79
|
+
completedTurnStates = parsedTurns.slice(0, -1);
|
|
80
|
+
userText = lastTurn.userText;
|
|
81
|
+
}
|
|
82
|
+
else if (lastTurn.userText && hasAssistantSummary) {
|
|
83
|
+
completedTurnStates = parsedTurns.slice(0, -1);
|
|
84
|
+
userText = lastTurn.userText;
|
|
85
|
+
pendingAssistantSummary = summarizeTurnSegments(lastTurn.segments);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
const turns = completedTurnStates
|
|
89
|
+
.map((turn) => ({
|
|
90
|
+
userText: turn.userText,
|
|
91
|
+
assistantText: summarizeTurnSegments(turn.segments),
|
|
92
|
+
}))
|
|
93
|
+
.filter((turn) => turn.userText || turn.assistantText);
|
|
94
|
+
return {
|
|
95
|
+
systemPrompt,
|
|
96
|
+
userText,
|
|
97
|
+
turns,
|
|
98
|
+
toolResults,
|
|
99
|
+
pendingAssistantSummary,
|
|
100
|
+
completedTurnsFingerprint: buildCompletedTurnsFingerprint(systemPrompt, turns),
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
function splitTrailingToolResults(segments) {
|
|
104
|
+
let index = segments.length;
|
|
105
|
+
while (index > 0 && segments[index - 1]?.kind === "toolResult") {
|
|
106
|
+
index -= 1;
|
|
107
|
+
}
|
|
108
|
+
return {
|
|
109
|
+
base: segments.slice(0, index),
|
|
110
|
+
trailing: segments
|
|
111
|
+
.slice(index)
|
|
112
|
+
.filter((segment) => segment.kind === "toolResult"),
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
function summarizeTurnSegments(segments) {
|
|
116
|
+
const parts = [];
|
|
117
|
+
for (const segment of segments) {
|
|
118
|
+
if (segment.kind === "assistantText") {
|
|
119
|
+
const trimmed = segment.text.trim();
|
|
120
|
+
if (trimmed)
|
|
121
|
+
parts.push(trimmed);
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
if (segment.kind === "assistantToolCalls") {
|
|
125
|
+
const summary = segment.toolCalls.map(formatToolCallSummary).join("\n\n");
|
|
126
|
+
if (summary)
|
|
127
|
+
parts.push(summary);
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
parts.push(formatToolResultSummary(segment.result));
|
|
131
|
+
}
|
|
132
|
+
return parts.join("\n\n").trim();
|
|
133
|
+
}
|
|
134
|
+
export function formatToolCallSummary(call) {
|
|
135
|
+
const args = call.function.arguments?.trim();
|
|
136
|
+
return args
|
|
137
|
+
? `[assistant requested tool ${call.function.name} id=${call.id}]\n${args}`
|
|
138
|
+
: `[assistant requested tool ${call.function.name} id=${call.id}]`;
|
|
139
|
+
}
|
|
140
|
+
export function formatToolResultSummary(result) {
|
|
141
|
+
const label = result.toolCallId
|
|
142
|
+
? `[tool result id=${result.toolCallId}]`
|
|
143
|
+
: "[tool result]";
|
|
144
|
+
const content = result.content.trim();
|
|
145
|
+
return content ? `${label}\n${content}` : label;
|
|
146
|
+
}
|
|
147
|
+
export function buildCompletedTurnsFingerprint(systemPrompt, turns) {
|
|
148
|
+
return createHash("sha256")
|
|
149
|
+
.update(JSON.stringify({ systemPrompt, turns }))
|
|
150
|
+
.digest("hex");
|
|
151
|
+
}
|
|
152
|
+
export function buildToolResumePrompt(userText, pendingAssistantSummary, toolResults) {
|
|
153
|
+
const parts = [userText.trim()];
|
|
154
|
+
if (pendingAssistantSummary.trim()) {
|
|
155
|
+
parts.push(`[previous assistant tool activity]\n${pendingAssistantSummary.trim()}`);
|
|
156
|
+
}
|
|
157
|
+
if (toolResults.length > 0) {
|
|
158
|
+
parts.push(toolResults.map(formatToolResultSummary).join("\n\n"));
|
|
159
|
+
}
|
|
160
|
+
return parts.filter(Boolean).join("\n\n");
|
|
161
|
+
}
|
|
162
|
+
export function buildInitialHandoffPrompt(userText, turns, pendingAssistantSummary, toolResults) {
|
|
163
|
+
const transcript = turns.map((turn, index) => {
|
|
164
|
+
const sections = [`Turn ${index + 1}`];
|
|
165
|
+
if (turn.userText.trim())
|
|
166
|
+
sections.push(`User: ${turn.userText.trim()}`);
|
|
167
|
+
if (turn.assistantText.trim())
|
|
168
|
+
sections.push(`Assistant: ${turn.assistantText.trim()}`);
|
|
169
|
+
return sections.join("\n");
|
|
170
|
+
});
|
|
171
|
+
const inProgress = buildToolResumePrompt("", pendingAssistantSummary, toolResults).trim();
|
|
172
|
+
const history = [
|
|
173
|
+
...transcript,
|
|
174
|
+
...(inProgress ? [`In-progress turn\n${inProgress}`] : []),
|
|
175
|
+
]
|
|
176
|
+
.join("\n\n")
|
|
177
|
+
.trim();
|
|
178
|
+
if (!history)
|
|
179
|
+
return userText;
|
|
180
|
+
return [
|
|
181
|
+
"[OpenCode session handoff]",
|
|
182
|
+
"You are continuing an existing session that previously ran on another provider/model.",
|
|
183
|
+
"Treat the transcript below as prior conversation history before answering the latest user message.",
|
|
184
|
+
"",
|
|
185
|
+
"<previous-session-transcript>",
|
|
186
|
+
history,
|
|
187
|
+
"</previous-session-transcript>",
|
|
188
|
+
"",
|
|
189
|
+
"Latest user message:",
|
|
190
|
+
userText.trim(),
|
|
191
|
+
]
|
|
192
|
+
.filter(Boolean)
|
|
193
|
+
.join("\n");
|
|
194
|
+
}
|
|
195
|
+
export function buildTitleSourceText(userText, turns, pendingAssistantSummary, toolResults) {
|
|
196
|
+
const history = turns
|
|
197
|
+
.map((turn) => [
|
|
198
|
+
isTitleRequestMarker(turn.userText) ? "" : turn.userText.trim(),
|
|
199
|
+
turn.assistantText.trim(),
|
|
200
|
+
]
|
|
201
|
+
.filter(Boolean)
|
|
202
|
+
.join("\n"))
|
|
203
|
+
.filter(Boolean);
|
|
204
|
+
if (pendingAssistantSummary.trim()) {
|
|
205
|
+
history.push(pendingAssistantSummary.trim());
|
|
206
|
+
}
|
|
207
|
+
if (toolResults.length > 0) {
|
|
208
|
+
history.push(toolResults.map(formatToolResultSummary).join("\n\n"));
|
|
209
|
+
}
|
|
210
|
+
if (userText.trim() && !isTitleRequestMarker(userText)) {
|
|
211
|
+
history.push(userText.trim());
|
|
212
|
+
}
|
|
213
|
+
return history.join("\n\n").trim();
|
|
214
|
+
}
|
|
215
|
+
export function detectTitleRequest(body) {
|
|
216
|
+
if ((body.tools?.length ?? 0) > 0) {
|
|
217
|
+
return { matched: false, reason: "tools-present" };
|
|
218
|
+
}
|
|
219
|
+
const firstNonSystem = body.messages.find((message) => message.role !== "system");
|
|
220
|
+
if (firstNonSystem?.role === "user" &&
|
|
221
|
+
isTitleRequestMarker(textContent(firstNonSystem.content))) {
|
|
222
|
+
return { matched: true, reason: "opencode-title-marker" };
|
|
223
|
+
}
|
|
224
|
+
return { matched: false, reason: "no-title-marker" };
|
|
225
|
+
}
|
|
226
|
+
function isTitleRequestMarker(text) {
|
|
227
|
+
return text.trim() === OPENCODE_TITLE_REQUEST_MARKER;
|
|
228
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { McpToolDefinition } from "../proto/agent_pb";
|
|
2
|
+
import type { OpenAIToolDef } from "./types";
|
|
3
|
+
export declare function selectToolsForChoice(tools: OpenAIToolDef[], toolChoice: unknown): OpenAIToolDef[];
|
|
4
|
+
/** Convert OpenAI tool definitions to Cursor's MCP tool protobuf format. */
|
|
5
|
+
export declare function buildMcpToolDefinitions(tools: OpenAIToolDef[]): McpToolDefinition[];
|
|
6
|
+
/** Decode a map of MCP arg values. */
|
|
7
|
+
export declare function decodeMcpArgsMap(args: Record<string, Uint8Array>): Record<string, unknown>;
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { create, fromBinary, fromJson, toBinary, toJson, } from "@bufbuild/protobuf";
|
|
2
|
+
import { ValueSchema } from "@bufbuild/protobuf/wkt";
|
|
3
|
+
import { McpToolDefinitionSchema } from "../proto/agent_pb";
|
|
4
|
+
export function selectToolsForChoice(tools, toolChoice) {
|
|
5
|
+
if (!tools.length)
|
|
6
|
+
return [];
|
|
7
|
+
if (toolChoice === undefined ||
|
|
8
|
+
toolChoice === null ||
|
|
9
|
+
toolChoice === "auto" ||
|
|
10
|
+
toolChoice === "required") {
|
|
11
|
+
return tools;
|
|
12
|
+
}
|
|
13
|
+
if (toolChoice === "none") {
|
|
14
|
+
return [];
|
|
15
|
+
}
|
|
16
|
+
if (typeof toolChoice === "object") {
|
|
17
|
+
const choice = toolChoice;
|
|
18
|
+
if (choice.type === "function" &&
|
|
19
|
+
typeof choice.function?.name === "string") {
|
|
20
|
+
return tools.filter((tool) => tool.function.name === choice.function.name);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return tools;
|
|
24
|
+
}
|
|
25
|
+
/** Convert OpenAI tool definitions to Cursor's MCP tool protobuf format. */
|
|
26
|
+
export function buildMcpToolDefinitions(tools) {
|
|
27
|
+
return tools.map((t) => {
|
|
28
|
+
const fn = t.function;
|
|
29
|
+
const jsonSchema = fn.parameters && typeof fn.parameters === "object"
|
|
30
|
+
? fn.parameters
|
|
31
|
+
: { type: "object", properties: {}, required: [] };
|
|
32
|
+
const inputSchema = toBinary(ValueSchema, fromJson(ValueSchema, jsonSchema));
|
|
33
|
+
return create(McpToolDefinitionSchema, {
|
|
34
|
+
name: fn.name,
|
|
35
|
+
description: fn.description || "",
|
|
36
|
+
providerIdentifier: "opencode",
|
|
37
|
+
toolName: fn.name,
|
|
38
|
+
inputSchema,
|
|
39
|
+
});
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
/** Decode a Cursor MCP arg value (protobuf Value bytes) to a JS value. */
|
|
43
|
+
function decodeMcpArgValue(value) {
|
|
44
|
+
try {
|
|
45
|
+
const parsed = fromBinary(ValueSchema, value);
|
|
46
|
+
return toJson(ValueSchema, parsed);
|
|
47
|
+
}
|
|
48
|
+
catch { }
|
|
49
|
+
return new TextDecoder().decode(value);
|
|
50
|
+
}
|
|
51
|
+
/** Decode a map of MCP arg values. */
|
|
52
|
+
export function decodeMcpArgsMap(args) {
|
|
53
|
+
const decoded = {};
|
|
54
|
+
for (const [key, value] of Object.entries(args)) {
|
|
55
|
+
decoded[key] = decodeMcpArgValue(value);
|
|
56
|
+
}
|
|
57
|
+
return decoded;
|
|
58
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
export interface OpenAIToolCall {
|
|
2
|
+
id: string;
|
|
3
|
+
type: "function";
|
|
4
|
+
function: {
|
|
5
|
+
name: string;
|
|
6
|
+
arguments: string;
|
|
7
|
+
};
|
|
8
|
+
}
|
|
9
|
+
/** A single element in an OpenAI multi-part content array. */
|
|
10
|
+
export interface ContentPart {
|
|
11
|
+
type: string;
|
|
12
|
+
text?: string;
|
|
13
|
+
}
|
|
14
|
+
export interface OpenAIMessage {
|
|
15
|
+
role: "system" | "user" | "assistant" | "tool";
|
|
16
|
+
content: string | null | ContentPart[];
|
|
17
|
+
tool_call_id?: string;
|
|
18
|
+
tool_calls?: OpenAIToolCall[];
|
|
19
|
+
}
|
|
20
|
+
export interface OpenAIToolDef {
|
|
21
|
+
type: "function";
|
|
22
|
+
function: {
|
|
23
|
+
name: string;
|
|
24
|
+
description?: string;
|
|
25
|
+
parameters?: Record<string, unknown>;
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
export interface ChatCompletionRequest {
|
|
29
|
+
model: string;
|
|
30
|
+
messages: OpenAIMessage[];
|
|
31
|
+
stream?: boolean;
|
|
32
|
+
temperature?: number;
|
|
33
|
+
max_tokens?: number;
|
|
34
|
+
max_completion_tokens?: number;
|
|
35
|
+
tools?: OpenAIToolDef[];
|
|
36
|
+
tool_choice?: unknown;
|
|
37
|
+
}
|
|
38
|
+
export interface ChatRequestContext {
|
|
39
|
+
sessionId?: string;
|
|
40
|
+
agentKey?: string;
|
|
41
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { generateCursorAuthParams, getTokenExpiry, pollCursorAuth, refreshCursorToken, } from "../auth";
|
|
2
|
+
import { CURSOR_PROVIDER_ID } from "../constants";
|
|
3
|
+
import { configurePluginLogger, errorDetails, logPluginError, logPluginWarn, } from "../logger";
|
|
4
|
+
import { getCursorModels } from "../models";
|
|
5
|
+
import { buildCursorProviderModels, buildDisabledProviderConfig, setProviderModels, stripAuthorizationHeader, } from "../provider/models";
|
|
6
|
+
import { startProxy, stopProxy } from "../proxy";
|
|
7
|
+
let lastModelDiscoveryError = null;
|
|
8
|
+
export const CursorAuthPlugin = async (input) => {
|
|
9
|
+
configurePluginLogger(input);
|
|
10
|
+
return {
|
|
11
|
+
auth: {
|
|
12
|
+
provider: CURSOR_PROVIDER_ID,
|
|
13
|
+
async loader(getAuth, provider) {
|
|
14
|
+
try {
|
|
15
|
+
const auth = await getAuth();
|
|
16
|
+
if (!auth || auth.type !== "oauth")
|
|
17
|
+
return {};
|
|
18
|
+
let accessToken = auth.access;
|
|
19
|
+
if (!accessToken || auth.expires < Date.now()) {
|
|
20
|
+
const refreshed = await refreshCursorToken(auth.refresh);
|
|
21
|
+
await input.client.auth.set({
|
|
22
|
+
path: { id: CURSOR_PROVIDER_ID },
|
|
23
|
+
body: {
|
|
24
|
+
type: "oauth",
|
|
25
|
+
refresh: refreshed.refresh,
|
|
26
|
+
access: refreshed.access,
|
|
27
|
+
expires: refreshed.expires,
|
|
28
|
+
},
|
|
29
|
+
});
|
|
30
|
+
accessToken = refreshed.access;
|
|
31
|
+
}
|
|
32
|
+
const models = await getCursorModels(accessToken);
|
|
33
|
+
lastModelDiscoveryError = null;
|
|
34
|
+
const port = await startProxy(async () => {
|
|
35
|
+
const currentAuth = await getAuth();
|
|
36
|
+
if (currentAuth.type !== "oauth") {
|
|
37
|
+
const authError = new Error("Cursor auth not configured");
|
|
38
|
+
logPluginError("Cursor proxy access token lookup failed", {
|
|
39
|
+
stage: "proxy_access_token",
|
|
40
|
+
...errorDetails(authError),
|
|
41
|
+
});
|
|
42
|
+
throw authError;
|
|
43
|
+
}
|
|
44
|
+
if (!currentAuth.access || currentAuth.expires < Date.now()) {
|
|
45
|
+
const refreshed = await refreshCursorToken(currentAuth.refresh);
|
|
46
|
+
await input.client.auth.set({
|
|
47
|
+
path: { id: CURSOR_PROVIDER_ID },
|
|
48
|
+
body: {
|
|
49
|
+
type: "oauth",
|
|
50
|
+
refresh: refreshed.refresh,
|
|
51
|
+
access: refreshed.access,
|
|
52
|
+
expires: refreshed.expires,
|
|
53
|
+
},
|
|
54
|
+
});
|
|
55
|
+
return refreshed.access;
|
|
56
|
+
}
|
|
57
|
+
return currentAuth.access;
|
|
58
|
+
}, models);
|
|
59
|
+
setProviderModels(provider, buildCursorProviderModels(models, port));
|
|
60
|
+
return {
|
|
61
|
+
baseURL: `http://localhost:${port}/v1`,
|
|
62
|
+
apiKey: "cursor-proxy",
|
|
63
|
+
async fetch(requestInput, init) {
|
|
64
|
+
return fetch(requestInput, stripAuthorizationHeader(init));
|
|
65
|
+
},
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
catch (error) {
|
|
69
|
+
const message = error instanceof Error
|
|
70
|
+
? error.message
|
|
71
|
+
: "Cursor model discovery failed.";
|
|
72
|
+
logPluginError("Cursor auth loader failed", {
|
|
73
|
+
stage: "loader",
|
|
74
|
+
providerID: CURSOR_PROVIDER_ID,
|
|
75
|
+
...errorDetails(error),
|
|
76
|
+
});
|
|
77
|
+
stopProxy();
|
|
78
|
+
setProviderModels(provider, {});
|
|
79
|
+
if (message !== lastModelDiscoveryError) {
|
|
80
|
+
lastModelDiscoveryError = message;
|
|
81
|
+
await showDiscoveryFailureToast(input, message);
|
|
82
|
+
}
|
|
83
|
+
return buildDisabledProviderConfig(message);
|
|
84
|
+
}
|
|
85
|
+
},
|
|
86
|
+
methods: [
|
|
87
|
+
{
|
|
88
|
+
type: "oauth",
|
|
89
|
+
label: "Login with Cursor",
|
|
90
|
+
async authorize() {
|
|
91
|
+
const { verifier, uuid, loginUrl } = await generateCursorAuthParams();
|
|
92
|
+
return {
|
|
93
|
+
url: loginUrl,
|
|
94
|
+
instructions: "Complete login in your browser. This window will close automatically.",
|
|
95
|
+
method: "auto",
|
|
96
|
+
async callback() {
|
|
97
|
+
const { accessToken, refreshToken } = await pollCursorAuth(uuid, verifier);
|
|
98
|
+
return {
|
|
99
|
+
type: "success",
|
|
100
|
+
refresh: refreshToken,
|
|
101
|
+
access: accessToken,
|
|
102
|
+
expires: getTokenExpiry(accessToken),
|
|
103
|
+
};
|
|
104
|
+
},
|
|
105
|
+
};
|
|
106
|
+
},
|
|
107
|
+
},
|
|
108
|
+
],
|
|
109
|
+
},
|
|
110
|
+
async "chat.headers"(incoming, output) {
|
|
111
|
+
if (incoming.model.providerID !== CURSOR_PROVIDER_ID)
|
|
112
|
+
return;
|
|
113
|
+
output.headers["x-session-id"] = incoming.sessionID;
|
|
114
|
+
if (incoming.agent) {
|
|
115
|
+
output.headers["x-opencode-agent"] = incoming.agent;
|
|
116
|
+
}
|
|
117
|
+
},
|
|
118
|
+
};
|
|
119
|
+
};
|
|
120
|
+
async function showDiscoveryFailureToast(input, message) {
|
|
121
|
+
try {
|
|
122
|
+
await input.client.tui.showToast({
|
|
123
|
+
body: {
|
|
124
|
+
title: "Cursor plugin disabled",
|
|
125
|
+
message,
|
|
126
|
+
variant: "error",
|
|
127
|
+
duration: 8_000,
|
|
128
|
+
},
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
catch (error) {
|
|
132
|
+
logPluginWarn("Failed to display Cursor plugin toast", {
|
|
133
|
+
title: "Cursor plugin disabled",
|
|
134
|
+
message,
|
|
135
|
+
...errorDetails(error),
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
export default CursorAuthPlugin;
|