@playwo/opencode-cursor-oauth 0.0.0-dev.0cb3e1517254

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/dist/models.js ADDED
@@ -0,0 +1,206 @@
1
+ import { create, fromBinary, toBinary } from "@bufbuild/protobuf";
2
+ import { z } from "zod";
3
+ import { errorDetails, logPluginError, logPluginWarn } from "./logger";
4
+ import { callCursorUnaryRpc } from "./proxy";
5
+ import { GetUsableModelsRequestSchema, GetUsableModelsResponseSchema, } from "./proto/agent_pb";
6
+ const GET_USABLE_MODELS_PATH = "/agent.v1.AgentService/GetUsableModels";
7
+ const MODEL_DISCOVERY_TIMEOUT_MS = 5_000;
8
+ const DEFAULT_CONTEXT_WINDOW = 200_000;
9
+ const DEFAULT_MAX_TOKENS = 64_000;
10
+ const CursorModelDetailsSchema = z.object({
11
+ modelId: z.string(),
12
+ displayName: z.string().optional().catch(undefined),
13
+ displayNameShort: z.string().optional().catch(undefined),
14
+ displayModelId: z.string().optional().catch(undefined),
15
+ aliases: z
16
+ .array(z.unknown())
17
+ .optional()
18
+ .catch([])
19
+ .transform((aliases) => (aliases ?? []).filter((alias) => typeof alias === "string")),
20
+ thinkingDetails: z.unknown().optional(),
21
+ });
22
+ export class CursorModelDiscoveryError extends Error {
23
+ constructor(message) {
24
+ super(message);
25
+ this.name = "CursorModelDiscoveryError";
26
+ }
27
+ }
28
+ async function fetchCursorUsableModels(apiKey) {
29
+ try {
30
+ const requestPayload = create(GetUsableModelsRequestSchema, {});
31
+ const requestBody = toBinary(GetUsableModelsRequestSchema, requestPayload);
32
+ const response = await callCursorUnaryRpc({
33
+ accessToken: apiKey,
34
+ rpcPath: GET_USABLE_MODELS_PATH,
35
+ requestBody,
36
+ timeoutMs: MODEL_DISCOVERY_TIMEOUT_MS,
37
+ });
38
+ if (response.timedOut) {
39
+ logPluginError("Cursor model discovery timed out", {
40
+ rpcPath: GET_USABLE_MODELS_PATH,
41
+ timeoutMs: MODEL_DISCOVERY_TIMEOUT_MS,
42
+ });
43
+ throw new CursorModelDiscoveryError(`Cursor model discovery timed out after ${MODEL_DISCOVERY_TIMEOUT_MS}ms.`);
44
+ }
45
+ if (response.exitCode !== 0) {
46
+ logPluginError("Cursor model discovery HTTP failure", {
47
+ rpcPath: GET_USABLE_MODELS_PATH,
48
+ exitCode: response.exitCode,
49
+ responseBody: response.body,
50
+ });
51
+ throw new CursorModelDiscoveryError(buildDiscoveryHttpError(response.exitCode, response.body));
52
+ }
53
+ if (response.body.length === 0) {
54
+ logPluginWarn("Cursor model discovery returned an empty response", {
55
+ rpcPath: GET_USABLE_MODELS_PATH,
56
+ });
57
+ throw new CursorModelDiscoveryError("Cursor model discovery returned an empty response.");
58
+ }
59
+ const decoded = decodeGetUsableModelsResponse(response.body);
60
+ if (!decoded) {
61
+ logPluginError("Cursor model discovery returned an unreadable response", {
62
+ rpcPath: GET_USABLE_MODELS_PATH,
63
+ responseBody: response.body,
64
+ });
65
+ throw new CursorModelDiscoveryError("Cursor model discovery returned an unreadable response.");
66
+ }
67
+ const models = normalizeCursorModels(decoded.models);
68
+ if (models.length === 0) {
69
+ throw new CursorModelDiscoveryError("Cursor model discovery returned no usable models.");
70
+ }
71
+ return models;
72
+ }
73
+ catch (error) {
74
+ if (error instanceof CursorModelDiscoveryError)
75
+ throw error;
76
+ logPluginError("Cursor model discovery crashed", {
77
+ rpcPath: GET_USABLE_MODELS_PATH,
78
+ ...errorDetails(error),
79
+ });
80
+ throw new CursorModelDiscoveryError("Cursor model discovery failed.");
81
+ }
82
+ }
83
+ let cachedModels = null;
84
+ export async function getCursorModels(apiKey) {
85
+ if (cachedModels)
86
+ return cachedModels;
87
+ const discovered = await fetchCursorUsableModels(apiKey);
88
+ cachedModels = discovered;
89
+ return cachedModels;
90
+ }
91
+ /** @internal Test-only. */
92
+ export function clearModelCache() {
93
+ cachedModels = null;
94
+ }
95
+ function buildDiscoveryHttpError(exitCode, body) {
96
+ const detail = extractDiscoveryErrorDetail(body);
97
+ const protocolHint = exitCode === 464
98
+ ? " Likely protocol mismatch: Cursor appears to expect an HTTP/2 Connect unary request."
99
+ : "";
100
+ if (!detail) {
101
+ return `Cursor model discovery failed with HTTP ${exitCode}.${protocolHint}`;
102
+ }
103
+ return `Cursor model discovery failed with HTTP ${exitCode}: ${detail}.${protocolHint}`;
104
+ }
105
+ function extractDiscoveryErrorDetail(body) {
106
+ if (body.length === 0)
107
+ return null;
108
+ const text = new TextDecoder().decode(body).trim();
109
+ if (!text)
110
+ return null;
111
+ try {
112
+ const parsed = JSON.parse(text);
113
+ const code = typeof parsed.code === "string" ? parsed.code : undefined;
114
+ const message = typeof parsed.message === "string" ? parsed.message : undefined;
115
+ if (message && code)
116
+ return `${message} (${code})`;
117
+ if (message)
118
+ return message;
119
+ if (code)
120
+ return code;
121
+ }
122
+ catch { }
123
+ return text.length > 200 ? `${text.slice(0, 197)}...` : text;
124
+ }
125
+ function decodeGetUsableModelsResponse(payload) {
126
+ try {
127
+ return fromBinary(GetUsableModelsResponseSchema, payload);
128
+ }
129
+ catch {
130
+ const framedBody = decodeConnectUnaryBody(payload);
131
+ if (!framedBody)
132
+ return null;
133
+ try {
134
+ return fromBinary(GetUsableModelsResponseSchema, framedBody);
135
+ }
136
+ catch {
137
+ return null;
138
+ }
139
+ }
140
+ }
141
+ function decodeConnectUnaryBody(payload) {
142
+ if (payload.length < 5)
143
+ return null;
144
+ let offset = 0;
145
+ while (offset + 5 <= payload.length) {
146
+ const flags = payload[offset];
147
+ const view = new DataView(payload.buffer, payload.byteOffset + offset, payload.byteLength - offset);
148
+ const messageLength = view.getUint32(1, false);
149
+ const frameEnd = offset + 5 + messageLength;
150
+ if (frameEnd > payload.length)
151
+ return null;
152
+ // Compression flag
153
+ if ((flags & 0b0000_0001) !== 0)
154
+ return null;
155
+ // End-of-stream flag — skip trailer frames
156
+ if ((flags & 0b0000_0010) === 0) {
157
+ return payload.subarray(offset + 5, frameEnd);
158
+ }
159
+ offset = frameEnd;
160
+ }
161
+ return null;
162
+ }
163
+ function normalizeCursorModels(models) {
164
+ if (models.length === 0)
165
+ return [];
166
+ const byId = new Map();
167
+ for (const model of models) {
168
+ const normalized = normalizeSingleModel(model);
169
+ if (normalized)
170
+ byId.set(normalized.id, normalized);
171
+ }
172
+ return [...byId.values()].sort((a, b) => a.id.localeCompare(b.id));
173
+ }
174
+ function normalizeSingleModel(model) {
175
+ const parsed = CursorModelDetailsSchema.safeParse(model);
176
+ if (!parsed.success)
177
+ return null;
178
+ const details = parsed.data;
179
+ const id = details.modelId.trim();
180
+ if (!id)
181
+ return null;
182
+ return {
183
+ id,
184
+ name: pickDisplayName(details, id),
185
+ reasoning: Boolean(details.thinkingDetails),
186
+ contextWindow: DEFAULT_CONTEXT_WINDOW,
187
+ maxTokens: DEFAULT_MAX_TOKENS,
188
+ };
189
+ }
190
+ function pickDisplayName(model, fallbackId) {
191
+ const candidates = [
192
+ model.displayName,
193
+ model.displayNameShort,
194
+ model.displayModelId,
195
+ ...model.aliases,
196
+ fallbackId,
197
+ ];
198
+ for (const candidate of candidates) {
199
+ if (typeof candidate !== "string")
200
+ continue;
201
+ const trimmed = candidate.trim();
202
+ if (trimmed)
203
+ return trimmed;
204
+ }
205
+ return fallbackId;
206
+ }
package/dist/pkce.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ export declare function generatePKCE(): Promise<{
2
+ verifier: string;
3
+ challenge: string;
4
+ }>;
package/dist/pkce.js ADDED
@@ -0,0 +1,9 @@
1
+ export async function generatePKCE() {
2
+ const verifierBytes = new Uint8Array(96);
3
+ crypto.getRandomValues(verifierBytes);
4
+ const verifier = Buffer.from(verifierBytes).toString("base64url");
5
+ const data = new TextEncoder().encode(verifier);
6
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
7
+ const challenge = Buffer.from(hashBuffer).toString("base64url");
8
+ return { verifier, challenge };
9
+ }