@daex-dev/sdk 0.7.1 → 0.8.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/LICENSE +21 -21
- package/README.md +479 -417
- package/dist/{client-C0KQKP8O.d.cts → client-DVZHOtg6.d.cts} +18 -4
- package/dist/{client-C0KQKP8O.d.ts → client-DVZHOtg6.d.ts} +18 -4
- package/dist/connect/browser.cjs +209 -0
- package/dist/connect/browser.d.cts +81 -0
- package/dist/connect/browser.d.ts +81 -0
- package/dist/connect/browser.js +183 -0
- package/dist/connect/index.cjs +1954 -0
- package/dist/connect/index.d.cts +433 -0
- package/dist/connect/index.d.ts +433 -0
- package/dist/connect/index.js +1888 -0
- package/dist/electron/index.d.cts +2 -2
- package/dist/electron/index.d.ts +2 -2
- package/dist/index.cjs +130 -80
- package/dist/index.d.cts +11 -8
- package/dist/index.d.ts +11 -8
- package/dist/index.js +130 -80
- package/dist/server.cjs +1 -1
- package/dist/server.d.cts +1 -1
- package/dist/server.d.ts +1 -1
- package/dist/server.js +1 -1
- package/dist/testing.d.cts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/types-DUGv-9QF.d.cts +166 -0
- package/dist/types-DUGv-9QF.d.ts +166 -0
- package/package.json +111 -93
|
@@ -0,0 +1,1888 @@
|
|
|
1
|
+
// src/connect/errors.ts
|
|
2
|
+
var CONNECT_ERROR_CODES = [
|
|
3
|
+
"not_signed_in",
|
|
4
|
+
"sign_in_required",
|
|
5
|
+
"sign_in_failed",
|
|
6
|
+
"sign_in_cancelled",
|
|
7
|
+
"plan_not_eligible",
|
|
8
|
+
"plan_usage_disabled",
|
|
9
|
+
"usage_limit",
|
|
10
|
+
"provider_unavailable",
|
|
11
|
+
"unsupported_request",
|
|
12
|
+
"provider_error",
|
|
13
|
+
"provider_sdk_missing",
|
|
14
|
+
"invalid_credential",
|
|
15
|
+
"invalid_request",
|
|
16
|
+
"cancelled"
|
|
17
|
+
];
|
|
18
|
+
var ConnectError = class extends Error {
|
|
19
|
+
code;
|
|
20
|
+
provider;
|
|
21
|
+
retryable;
|
|
22
|
+
manageUrl;
|
|
23
|
+
httpStatus;
|
|
24
|
+
providerCode;
|
|
25
|
+
requestId;
|
|
26
|
+
constructor(code, message, details = {}) {
|
|
27
|
+
super(message, details.cause === void 0 ? void 0 : { cause: details.cause });
|
|
28
|
+
this.name = "ConnectError";
|
|
29
|
+
this.code = code;
|
|
30
|
+
this.provider = details.provider;
|
|
31
|
+
this.retryable = details.retryable ?? false;
|
|
32
|
+
this.manageUrl = details.manageUrl;
|
|
33
|
+
this.httpStatus = details.httpStatus;
|
|
34
|
+
this.providerCode = details.providerCode;
|
|
35
|
+
this.requestId = details.requestId;
|
|
36
|
+
}
|
|
37
|
+
/** A plain, token-free object for an HTTP response body. */
|
|
38
|
+
toJSON() {
|
|
39
|
+
return {
|
|
40
|
+
code: this.code,
|
|
41
|
+
message: this.message,
|
|
42
|
+
...this.provider ? { provider: this.provider } : {},
|
|
43
|
+
retryable: this.retryable,
|
|
44
|
+
...this.manageUrl ? { manageUrl: this.manageUrl } : {},
|
|
45
|
+
...this.providerCode ? { providerCode: this.providerCode } : {},
|
|
46
|
+
...this.requestId ? { requestId: this.requestId } : {}
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
function cancelledError(provider) {
|
|
51
|
+
return new ConnectError("cancelled", "The request was cancelled.", { provider });
|
|
52
|
+
}
|
|
53
|
+
function isConnectError(value) {
|
|
54
|
+
return value instanceof ConnectError;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// src/connect/providers.ts
|
|
58
|
+
var CONNECT_PROVIDERS = [
|
|
59
|
+
{
|
|
60
|
+
id: "codex",
|
|
61
|
+
name: "ChatGPT",
|
|
62
|
+
buttonLabel: "Sign in with ChatGPT",
|
|
63
|
+
signIn: "oauth-loopback",
|
|
64
|
+
billing: "The user's ChatGPT Plus or Pro plan",
|
|
65
|
+
manageUrl: "https://chatgpt.com/settings/usage",
|
|
66
|
+
lifetime: "Renews itself; ends after 30 days without use"
|
|
67
|
+
},
|
|
68
|
+
{
|
|
69
|
+
id: "cursor",
|
|
70
|
+
name: "Cursor",
|
|
71
|
+
buttonLabel: "Sign in with Cursor",
|
|
72
|
+
signIn: "browser-poll",
|
|
73
|
+
billing: "The user's Cursor plan",
|
|
74
|
+
manageUrl: "https://cursor.com/dashboard",
|
|
75
|
+
lifetime: "90 days, then sign in again"
|
|
76
|
+
}
|
|
77
|
+
];
|
|
78
|
+
var CONNECT_PROVIDER_IDS = CONNECT_PROVIDERS.map((provider) => provider.id);
|
|
79
|
+
function isConnectProviderId(value) {
|
|
80
|
+
return typeof value === "string" && CONNECT_PROVIDER_IDS.includes(value);
|
|
81
|
+
}
|
|
82
|
+
function connectProvider(id) {
|
|
83
|
+
const found = CONNECT_PROVIDERS.find((provider) => provider.id === id);
|
|
84
|
+
if (!found) throw new ConnectError("invalid_request", `Unknown provider: ${String(id)}`);
|
|
85
|
+
return found;
|
|
86
|
+
}
|
|
87
|
+
function unknownProviderError() {
|
|
88
|
+
return new ConnectError("invalid_request", `provider must be one of: ${CONNECT_PROVIDER_IDS.join(", ")}.`);
|
|
89
|
+
}
|
|
90
|
+
function requestMessages(request) {
|
|
91
|
+
const messages = Array.isArray(request.messages) ? [...request.messages] : [];
|
|
92
|
+
if (typeof request.prompt === "string" && request.prompt.length > 0) {
|
|
93
|
+
messages.push({ role: "user", content: request.prompt });
|
|
94
|
+
}
|
|
95
|
+
if (messages.length === 0) {
|
|
96
|
+
throw new ConnectError("invalid_request", "Pass `prompt` or at least one message.");
|
|
97
|
+
}
|
|
98
|
+
for (const message of messages) {
|
|
99
|
+
const record2 = typeof message === "object" && message !== null ? message : {};
|
|
100
|
+
if (record2.role !== "user" && record2.role !== "assistant" || typeof record2.content !== "string") {
|
|
101
|
+
throw new ConnectError("invalid_request", 'Each message needs role "user" or "assistant" and string content.');
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return messages;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// src/connect/credentials.ts
|
|
108
|
+
function str(value) {
|
|
109
|
+
return typeof value === "string" && value.length > 0;
|
|
110
|
+
}
|
|
111
|
+
function parseConnectCredential(value) {
|
|
112
|
+
const fail = () => {
|
|
113
|
+
throw new ConnectError("invalid_credential", "The credential is malformed.");
|
|
114
|
+
};
|
|
115
|
+
if (typeof value !== "object" || value === null) return fail();
|
|
116
|
+
const record2 = value;
|
|
117
|
+
if (record2.version !== 1) return fail();
|
|
118
|
+
const signedOut = record2.signedOut === true;
|
|
119
|
+
if (record2.provider === "codex") {
|
|
120
|
+
if (!str(record2.clientId) || !str(record2.hostId) || !str(record2.accountId)) return fail();
|
|
121
|
+
if (!signedOut && (!str(record2.accessToken) || !str(record2.refreshToken))) return fail();
|
|
122
|
+
if (typeof record2.expiresAt !== "number" || typeof record2.savedAt !== "number") return fail();
|
|
123
|
+
if (!Array.isArray(record2.scopes) || !record2.scopes.every((scope) => typeof scope === "string")) return fail();
|
|
124
|
+
return {
|
|
125
|
+
version: 1,
|
|
126
|
+
provider: "codex",
|
|
127
|
+
clientId: record2.clientId,
|
|
128
|
+
hostId: record2.hostId,
|
|
129
|
+
accountId: record2.accountId,
|
|
130
|
+
...str(record2.email) ? { email: record2.email } : {},
|
|
131
|
+
idToken: typeof record2.idToken === "string" ? record2.idToken : "",
|
|
132
|
+
accessToken: typeof record2.accessToken === "string" ? record2.accessToken : "",
|
|
133
|
+
refreshToken: typeof record2.refreshToken === "string" ? record2.refreshToken : "",
|
|
134
|
+
scopes: record2.scopes,
|
|
135
|
+
expiresAt: record2.expiresAt,
|
|
136
|
+
savedAt: record2.savedAt,
|
|
137
|
+
planUsage: record2.planUsage === true,
|
|
138
|
+
...signedOut ? { signedOut: true } : {}
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
if (record2.provider === "cursor") {
|
|
142
|
+
if (!signedOut && !str(record2.apiKey)) return fail();
|
|
143
|
+
if (typeof record2.expiresAt !== "number" || typeof record2.savedAt !== "number") return fail();
|
|
144
|
+
return {
|
|
145
|
+
version: 1,
|
|
146
|
+
provider: "cursor",
|
|
147
|
+
apiKey: typeof record2.apiKey === "string" ? record2.apiKey : "",
|
|
148
|
+
...str(record2.email) ? { email: record2.email } : {},
|
|
149
|
+
expiresAt: record2.expiresAt,
|
|
150
|
+
savedAt: record2.savedAt,
|
|
151
|
+
...signedOut ? { signedOut: true } : {}
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
return fail();
|
|
155
|
+
}
|
|
156
|
+
function isCursorUsable(credential, now = Date.now()) {
|
|
157
|
+
return !credential.signedOut && credential.apiKey.length > 0 && credential.expiresAt > now;
|
|
158
|
+
}
|
|
159
|
+
function signInStatus(credential, provider, now = Date.now()) {
|
|
160
|
+
if (!credential) return { provider, signedIn: false };
|
|
161
|
+
const email = credential.email ? { email: credential.email } : {};
|
|
162
|
+
if (credential.provider === "codex") {
|
|
163
|
+
if (credential.signedOut) return { provider, signedIn: false, needsSignIn: true, ...email };
|
|
164
|
+
return { provider, signedIn: true, planUsage: credential.planUsage, ...email };
|
|
165
|
+
}
|
|
166
|
+
if (!isCursorUsable(credential, now)) return { provider, signedIn: false, needsSignIn: true, ...email };
|
|
167
|
+
return { provider, signedIn: true, expiresAt: credential.expiresAt, ...email };
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// src/connect/codexHttp.ts
|
|
171
|
+
var CODEX_API_BASE = "https://api.openai.com/v1";
|
|
172
|
+
async function codexFetch(url, init, options, what) {
|
|
173
|
+
const doFetch = options.fetch ?? fetch;
|
|
174
|
+
const signal = init.signal ?? options.signal;
|
|
175
|
+
try {
|
|
176
|
+
return await doFetch(url, { ...init, ...signal ? { signal } : {} });
|
|
177
|
+
} catch (cause) {
|
|
178
|
+
if (signal?.aborted) throw cancelledError("codex");
|
|
179
|
+
throw new ConnectError("provider_unavailable", `Could not reach ${what}.`, { provider: "codex", retryable: true, cause });
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
async function readJson(response) {
|
|
183
|
+
try {
|
|
184
|
+
const value = await response.json();
|
|
185
|
+
return typeof value === "object" && value !== null ? value : null;
|
|
186
|
+
} catch {
|
|
187
|
+
return null;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// src/connect/webCrypto.ts
|
|
192
|
+
var encoder = new TextEncoder();
|
|
193
|
+
var decoder = new TextDecoder();
|
|
194
|
+
function subtle() {
|
|
195
|
+
const value = globalThis.crypto?.subtle;
|
|
196
|
+
if (!value) throw new Error("Web Crypto (crypto.subtle) is not available in this runtime.");
|
|
197
|
+
return value;
|
|
198
|
+
}
|
|
199
|
+
function randomBytes(length) {
|
|
200
|
+
const bytes = new Uint8Array(length);
|
|
201
|
+
globalThis.crypto.getRandomValues(bytes);
|
|
202
|
+
return bytes;
|
|
203
|
+
}
|
|
204
|
+
function base64UrlEncode(bytes) {
|
|
205
|
+
let binary = "";
|
|
206
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
207
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
208
|
+
}
|
|
209
|
+
function base64UrlDecode(text2) {
|
|
210
|
+
const normalized = text2.replace(/-/g, "+").replace(/_/g, "/");
|
|
211
|
+
const padded = normalized + "=".repeat((4 - normalized.length % 4) % 4);
|
|
212
|
+
const binary = atob(padded);
|
|
213
|
+
const bytes = new Uint8Array(binary.length);
|
|
214
|
+
for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);
|
|
215
|
+
return bytes;
|
|
216
|
+
}
|
|
217
|
+
function randomToken(length = 32) {
|
|
218
|
+
return base64UrlEncode(randomBytes(length));
|
|
219
|
+
}
|
|
220
|
+
function utf8(text2) {
|
|
221
|
+
return encoder.encode(text2);
|
|
222
|
+
}
|
|
223
|
+
function fromUtf8(bytes) {
|
|
224
|
+
return decoder.decode(bytes);
|
|
225
|
+
}
|
|
226
|
+
async function sha256(input) {
|
|
227
|
+
const data = typeof input === "string" ? utf8(input) : input;
|
|
228
|
+
return new Uint8Array(await subtle().digest("SHA-256", data));
|
|
229
|
+
}
|
|
230
|
+
async function sha256Hex(input) {
|
|
231
|
+
const bytes = await sha256(input);
|
|
232
|
+
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
233
|
+
}
|
|
234
|
+
async function deriveAesKey(secret, info) {
|
|
235
|
+
const raw = typeof secret === "string" ? utf8(secret) : secret;
|
|
236
|
+
if (raw.byteLength < 32) {
|
|
237
|
+
throw new Error("The vault secret must be at least 32 bytes.");
|
|
238
|
+
}
|
|
239
|
+
const base = await subtle().importKey("raw", raw, "HKDF", false, ["deriveKey"]);
|
|
240
|
+
return subtle().deriveKey(
|
|
241
|
+
{ name: "HKDF", hash: "SHA-256", salt: utf8("daex-connect/v1"), info: utf8(info) },
|
|
242
|
+
base,
|
|
243
|
+
{ name: "AES-GCM", length: 256 },
|
|
244
|
+
false,
|
|
245
|
+
["encrypt", "decrypt"]
|
|
246
|
+
);
|
|
247
|
+
}
|
|
248
|
+
async function sealText(key, plaintext, aad) {
|
|
249
|
+
const iv = randomBytes(12);
|
|
250
|
+
const sealed = await subtle().encrypt({ name: "AES-GCM", iv, additionalData: utf8(aad) }, key, utf8(plaintext));
|
|
251
|
+
return `v1.${base64UrlEncode(iv)}.${base64UrlEncode(new Uint8Array(sealed))}`;
|
|
252
|
+
}
|
|
253
|
+
async function openText(key, sealed, aad) {
|
|
254
|
+
const [version, ivText, bodyText] = sealed.split(".");
|
|
255
|
+
if (version !== "v1" || !ivText || !bodyText) throw new Error("Unknown sealed value format.");
|
|
256
|
+
const plain = await subtle().decrypt(
|
|
257
|
+
{ name: "AES-GCM", iv: base64UrlDecode(ivText), additionalData: utf8(aad) },
|
|
258
|
+
key,
|
|
259
|
+
base64UrlDecode(bodyText)
|
|
260
|
+
);
|
|
261
|
+
return fromUtf8(new Uint8Array(plain));
|
|
262
|
+
}
|
|
263
|
+
function decodeJwtPayload(token) {
|
|
264
|
+
const part = token.split(".")[1];
|
|
265
|
+
if (!part) return null;
|
|
266
|
+
try {
|
|
267
|
+
const value = JSON.parse(fromUtf8(base64UrlDecode(part)));
|
|
268
|
+
return typeof value === "object" && value !== null ? value : null;
|
|
269
|
+
} catch {
|
|
270
|
+
return null;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// src/connect/codexAuth.ts
|
|
275
|
+
var AUTH_ISSUER = "https://auth.openai.com";
|
|
276
|
+
var AUTHORIZE_URL = `${AUTH_ISSUER}/api/accounts/authorize`;
|
|
277
|
+
var TOKEN_URL = `${AUTH_ISSUER}/api/accounts/oauth/token`;
|
|
278
|
+
var OPENID_CONFIGURATION_URL = `${AUTH_ISSUER}/.well-known/openid-configuration`;
|
|
279
|
+
var RESOURCE = CODEX_API_BASE;
|
|
280
|
+
var REGISTRATION_CLIENT_ID = "dynamic_agent_client";
|
|
281
|
+
var PLAN_USAGE_SCOPE = "chatgpt.tokens.use.direct";
|
|
282
|
+
var SCOPES = `openid profile email offline_access resource.invoke ${PLAN_USAGE_SCOPE}`;
|
|
283
|
+
var CODEX_DEFAULT_REDIRECT_URI = "http://127.0.0.1:1455/auth/callback";
|
|
284
|
+
var CODEX_SIGN_IN_TTL_MS = 10 * 60 * 1e3;
|
|
285
|
+
function newCodexHostId() {
|
|
286
|
+
return `urn:uuid:${globalThis.crypto.randomUUID()}`;
|
|
287
|
+
}
|
|
288
|
+
function assertLoopbackRedirect(redirectUri) {
|
|
289
|
+
let url;
|
|
290
|
+
try {
|
|
291
|
+
url = new URL(redirectUri);
|
|
292
|
+
} catch {
|
|
293
|
+
throw new ConnectError("invalid_request", "redirectUri is not a URL.", { provider: "codex" });
|
|
294
|
+
}
|
|
295
|
+
if (url.protocol !== "http:" || url.hostname !== "127.0.0.1" || url.pathname !== "/auth/callback" || !url.port) {
|
|
296
|
+
throw new ConnectError(
|
|
297
|
+
"invalid_request",
|
|
298
|
+
"redirectUri must be http://127.0.0.1:<port>/auth/callback.",
|
|
299
|
+
{ provider: "codex" }
|
|
300
|
+
);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
async function startCodexSignIn(options) {
|
|
304
|
+
const appName = options.appName?.trim();
|
|
305
|
+
if (!appName) throw new ConnectError("invalid_request", "appName is required.", { provider: "codex" });
|
|
306
|
+
if (!options.hostId?.trim()) throw new ConnectError("invalid_request", "hostId is required.", { provider: "codex" });
|
|
307
|
+
const redirectUri = options.redirectUri ?? CODEX_DEFAULT_REDIRECT_URI;
|
|
308
|
+
assertLoopbackRedirect(redirectUri);
|
|
309
|
+
const verifier = randomToken(48);
|
|
310
|
+
const challenge = base64UrlEncode(await sha256(verifier));
|
|
311
|
+
const state = randomToken(24);
|
|
312
|
+
const nonce = randomToken(24);
|
|
313
|
+
const reauth = options.reauth?.clientId ? options.reauth : void 0;
|
|
314
|
+
const params = new URLSearchParams();
|
|
315
|
+
params.set("client_id", reauth ? reauth.clientId : REGISTRATION_CLIENT_ID);
|
|
316
|
+
if (!reauth) params.set("agent_name_hint", appName);
|
|
317
|
+
params.set("ext_agent_host_id", options.hostId);
|
|
318
|
+
if (reauth?.idTokenHint) params.set("id_token_hint", reauth.idTokenHint);
|
|
319
|
+
if (reauth?.loginHint) params.set("login_hint", reauth.loginHint);
|
|
320
|
+
params.set("response_type", "code");
|
|
321
|
+
params.set("redirect_uri", redirectUri);
|
|
322
|
+
params.set("scope", SCOPES);
|
|
323
|
+
params.set("resource", RESOURCE);
|
|
324
|
+
params.set("state", state);
|
|
325
|
+
params.set("nonce", nonce);
|
|
326
|
+
params.set("code_challenge_method", "S256");
|
|
327
|
+
params.set("code_challenge", challenge);
|
|
328
|
+
return {
|
|
329
|
+
url: `${AUTHORIZE_URL}?${params.toString()}`,
|
|
330
|
+
pending: {
|
|
331
|
+
provider: "codex",
|
|
332
|
+
state,
|
|
333
|
+
nonce,
|
|
334
|
+
verifier,
|
|
335
|
+
redirectUri,
|
|
336
|
+
hostId: options.hostId,
|
|
337
|
+
...reauth ? { clientId: reauth.clientId } : {},
|
|
338
|
+
createdAt: options.now ?? Date.now()
|
|
339
|
+
}
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
function callbackParams(callback) {
|
|
343
|
+
if (callback instanceof URLSearchParams) return callback;
|
|
344
|
+
if (callback instanceof URL) return callback.searchParams;
|
|
345
|
+
const text2 = callback.trim();
|
|
346
|
+
if (!text2) throw new ConnectError("invalid_request", "The sign-in address is empty.", { provider: "codex" });
|
|
347
|
+
const query = text2.includes("?") ? text2.slice(text2.indexOf("?") + 1) : text2;
|
|
348
|
+
return new URLSearchParams(query.split("#")[0]);
|
|
349
|
+
}
|
|
350
|
+
function oauthErrorCode(body2) {
|
|
351
|
+
if (!body2) return void 0;
|
|
352
|
+
if (typeof body2.error === "string") return body2.error;
|
|
353
|
+
const nested = body2.error;
|
|
354
|
+
if (typeof nested === "object" && nested !== null) {
|
|
355
|
+
const code = nested.code;
|
|
356
|
+
if (typeof code === "string") return code;
|
|
357
|
+
}
|
|
358
|
+
return typeof body2.code === "string" ? body2.code : void 0;
|
|
359
|
+
}
|
|
360
|
+
var TERMINAL_REFRESH_ERRORS = /* @__PURE__ */ new Set([
|
|
361
|
+
"invalid_grant",
|
|
362
|
+
"invalid_refresh_token",
|
|
363
|
+
"token_expired",
|
|
364
|
+
"refresh_token_expired",
|
|
365
|
+
"refresh_token_invalidated",
|
|
366
|
+
"refresh_token_reused"
|
|
367
|
+
]);
|
|
368
|
+
async function postToken(form, options) {
|
|
369
|
+
const response = await codexFetch(
|
|
370
|
+
TOKEN_URL,
|
|
371
|
+
{
|
|
372
|
+
method: "POST",
|
|
373
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
|
|
374
|
+
body: form.toString()
|
|
375
|
+
},
|
|
376
|
+
options,
|
|
377
|
+
"OpenAI's sign-in service"
|
|
378
|
+
);
|
|
379
|
+
if (response.ok) {
|
|
380
|
+
const body3 = await readJson(response);
|
|
381
|
+
if (!body3) throw new ConnectError("provider_error", "OpenAI returned an unreadable token response.", { provider: "codex" });
|
|
382
|
+
return body3;
|
|
383
|
+
}
|
|
384
|
+
const body2 = await readJson(response);
|
|
385
|
+
const code = oauthErrorCode(body2);
|
|
386
|
+
if (code && TERMINAL_REFRESH_ERRORS.has(code)) {
|
|
387
|
+
throw new ConnectError("sign_in_required", "The ChatGPT sign-in is no longer valid. Sign in again.", {
|
|
388
|
+
provider: "codex",
|
|
389
|
+
httpStatus: response.status,
|
|
390
|
+
providerCode: code
|
|
391
|
+
});
|
|
392
|
+
}
|
|
393
|
+
if (response.status >= 500 || response.status === 429) {
|
|
394
|
+
throw new ConnectError("provider_unavailable", "OpenAI's sign-in service is unavailable. Try again shortly.", {
|
|
395
|
+
provider: "codex",
|
|
396
|
+
retryable: true,
|
|
397
|
+
httpStatus: response.status,
|
|
398
|
+
...code ? { providerCode: code } : {}
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
throw new ConnectError("provider_error", `OpenAI refused the token request${code ? ` (${code})` : ""}.`, {
|
|
402
|
+
provider: "codex",
|
|
403
|
+
httpStatus: response.status,
|
|
404
|
+
...code ? { providerCode: code } : {}
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
function scopesOf(value) {
|
|
408
|
+
return typeof value === "string" ? value.split(/\s+/).filter(Boolean) : [];
|
|
409
|
+
}
|
|
410
|
+
function expiresAtFrom(value, now) {
|
|
411
|
+
const seconds = typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 3600;
|
|
412
|
+
return now + seconds * 1e3;
|
|
413
|
+
}
|
|
414
|
+
function idTokenClaims(idToken, clientId, nonce) {
|
|
415
|
+
const claims = decodeJwtPayload(idToken);
|
|
416
|
+
const fail = (why) => {
|
|
417
|
+
throw new ConnectError("sign_in_failed", `OpenAI's sign-in could not be verified (${why}).`, { provider: "codex" });
|
|
418
|
+
};
|
|
419
|
+
if (!claims) return fail("no ID token");
|
|
420
|
+
const issuer = typeof claims.iss === "string" ? claims.iss.replace(/\/$/, "") : "";
|
|
421
|
+
if (issuer !== AUTH_ISSUER) return fail("issuer");
|
|
422
|
+
const audience = Array.isArray(claims.aud) ? claims.aud : [claims.aud];
|
|
423
|
+
if (!audience.includes(clientId)) return fail("audience");
|
|
424
|
+
if (nonce !== null && claims.nonce !== nonce) return fail("nonce");
|
|
425
|
+
if (typeof claims.sub !== "string" || !claims.sub) return fail("subject");
|
|
426
|
+
if (typeof claims.exp !== "number" || claims.exp * 1e3 < Date.now() - 6e4) return fail("expired");
|
|
427
|
+
return { sub: claims.sub, ...typeof claims.email === "string" && claims.email ? { email: claims.email } : {} };
|
|
428
|
+
}
|
|
429
|
+
async function completeCodexSignIn(pending, callback, options = {}) {
|
|
430
|
+
const now = options.now ?? Date.now();
|
|
431
|
+
if (now - pending.createdAt > CODEX_SIGN_IN_TTL_MS) {
|
|
432
|
+
throw new ConnectError("sign_in_failed", "This sign-in took too long. Start again.", { provider: "codex" });
|
|
433
|
+
}
|
|
434
|
+
const params = callbackParams(callback);
|
|
435
|
+
if (params.get("state") !== pending.state) {
|
|
436
|
+
throw new ConnectError("sign_in_failed", "The sign-in address does not belong to this sign-in.", { provider: "codex" });
|
|
437
|
+
}
|
|
438
|
+
const error = params.get("error");
|
|
439
|
+
if (error) {
|
|
440
|
+
throw new ConnectError(
|
|
441
|
+
error === "access_denied" ? "sign_in_cancelled" : "sign_in_failed",
|
|
442
|
+
error === "access_denied" ? "The sign-in was cancelled." : `OpenAI ended the sign-in (${error}).`,
|
|
443
|
+
{ provider: "codex", providerCode: error }
|
|
444
|
+
);
|
|
445
|
+
}
|
|
446
|
+
const code = params.get("code");
|
|
447
|
+
if (!code) throw new ConnectError("sign_in_failed", "The sign-in address has no code.", { provider: "codex" });
|
|
448
|
+
const returnedClientId = params.get("client_id") ?? void 0;
|
|
449
|
+
let clientId;
|
|
450
|
+
if (pending.clientId) {
|
|
451
|
+
if (returnedClientId && returnedClientId !== pending.clientId) {
|
|
452
|
+
throw new ConnectError("sign_in_failed", "OpenAI returned a different app registration.", { provider: "codex" });
|
|
453
|
+
}
|
|
454
|
+
clientId = pending.clientId;
|
|
455
|
+
} else {
|
|
456
|
+
if (!returnedClientId || returnedClientId === REGISTRATION_CLIENT_ID) {
|
|
457
|
+
throw new ConnectError("sign_in_failed", "OpenAI did not finish registering this app.", { provider: "codex" });
|
|
458
|
+
}
|
|
459
|
+
clientId = returnedClientId;
|
|
460
|
+
}
|
|
461
|
+
const form = new URLSearchParams({
|
|
462
|
+
grant_type: "authorization_code",
|
|
463
|
+
client_id: clientId,
|
|
464
|
+
code,
|
|
465
|
+
code_verifier: pending.verifier,
|
|
466
|
+
redirect_uri: pending.redirectUri,
|
|
467
|
+
resource: RESOURCE
|
|
468
|
+
});
|
|
469
|
+
let tokens;
|
|
470
|
+
try {
|
|
471
|
+
tokens = await postToken(form, options);
|
|
472
|
+
} catch (error2) {
|
|
473
|
+
if (error2 instanceof ConnectError && error2.code === "cancelled") {
|
|
474
|
+
throw new ConnectError("sign_in_cancelled", "The sign-in was cancelled.", { provider: "codex" });
|
|
475
|
+
}
|
|
476
|
+
if (error2 instanceof ConnectError && error2.code === "sign_in_required") {
|
|
477
|
+
throw new ConnectError("sign_in_failed", "The sign-in code was refused. Start again.", {
|
|
478
|
+
provider: "codex",
|
|
479
|
+
...error2.providerCode ? { providerCode: error2.providerCode } : {}
|
|
480
|
+
});
|
|
481
|
+
}
|
|
482
|
+
throw error2;
|
|
483
|
+
}
|
|
484
|
+
const savedAt = Date.now();
|
|
485
|
+
if (typeof tokens.access_token !== "string" || typeof tokens.refresh_token !== "string" || typeof tokens.id_token !== "string") {
|
|
486
|
+
throw new ConnectError("sign_in_failed", "OpenAI's token response is missing tokens.", { provider: "codex" });
|
|
487
|
+
}
|
|
488
|
+
const claims = idTokenClaims(tokens.id_token, clientId, pending.nonce);
|
|
489
|
+
const scopes = scopesOf(tokens.scope);
|
|
490
|
+
return {
|
|
491
|
+
version: 1,
|
|
492
|
+
provider: "codex",
|
|
493
|
+
clientId,
|
|
494
|
+
hostId: pending.hostId,
|
|
495
|
+
accountId: claims.sub,
|
|
496
|
+
...claims.email ? { email: claims.email } : {},
|
|
497
|
+
idToken: tokens.id_token,
|
|
498
|
+
accessToken: tokens.access_token,
|
|
499
|
+
refreshToken: tokens.refresh_token,
|
|
500
|
+
scopes,
|
|
501
|
+
expiresAt: expiresAtFrom(tokens.expires_in, savedAt),
|
|
502
|
+
savedAt,
|
|
503
|
+
planUsage: scopes.includes(PLAN_USAGE_SCOPE)
|
|
504
|
+
};
|
|
505
|
+
}
|
|
506
|
+
async function refreshCodexCredential(credential, options = {}) {
|
|
507
|
+
if (credential.signedOut || !credential.refreshToken) {
|
|
508
|
+
throw new ConnectError("sign_in_required", "The ChatGPT sign-in ended. Sign in again.", { provider: "codex" });
|
|
509
|
+
}
|
|
510
|
+
const form = new URLSearchParams({
|
|
511
|
+
grant_type: "refresh_token",
|
|
512
|
+
client_id: credential.clientId,
|
|
513
|
+
refresh_token: credential.refreshToken,
|
|
514
|
+
resource: RESOURCE
|
|
515
|
+
});
|
|
516
|
+
const tokens = await postToken(form, options);
|
|
517
|
+
const savedAt = Date.now();
|
|
518
|
+
if (typeof tokens.access_token !== "string" || typeof tokens.refresh_token !== "string") {
|
|
519
|
+
throw new ConnectError("provider_error", "OpenAI's refresh response is missing tokens.", { provider: "codex" });
|
|
520
|
+
}
|
|
521
|
+
const idToken = typeof tokens.id_token === "string" ? tokens.id_token : credential.idToken;
|
|
522
|
+
const scopes = tokens.scope === void 0 ? credential.scopes : scopesOf(tokens.scope);
|
|
523
|
+
return {
|
|
524
|
+
...credential,
|
|
525
|
+
idToken,
|
|
526
|
+
accessToken: tokens.access_token,
|
|
527
|
+
refreshToken: tokens.refresh_token,
|
|
528
|
+
scopes,
|
|
529
|
+
expiresAt: expiresAtFrom(tokens.expires_in, savedAt),
|
|
530
|
+
savedAt,
|
|
531
|
+
planUsage: scopes.includes(PLAN_USAGE_SCOPE)
|
|
532
|
+
};
|
|
533
|
+
}
|
|
534
|
+
var REVOKE_TRY_TIMEOUT_MS = 1e4;
|
|
535
|
+
async function revokeCodexCredential(credential, options = {}) {
|
|
536
|
+
if (!credential.refreshToken) return true;
|
|
537
|
+
const bounded = () => {
|
|
538
|
+
const timeout = AbortSignal.timeout(REVOKE_TRY_TIMEOUT_MS);
|
|
539
|
+
return { ...options, signal: options.signal ? AbortSignal.any([options.signal, timeout]) : timeout };
|
|
540
|
+
};
|
|
541
|
+
let endpoint;
|
|
542
|
+
try {
|
|
543
|
+
const discovery = await codexFetch(OPENID_CONFIGURATION_URL, {}, bounded(), "OpenAI's sign-in service");
|
|
544
|
+
const body2 = discovery.ok ? await readJson(discovery) : null;
|
|
545
|
+
endpoint = typeof body2?.revocation_endpoint === "string" ? body2.revocation_endpoint : void 0;
|
|
546
|
+
} catch {
|
|
547
|
+
return false;
|
|
548
|
+
}
|
|
549
|
+
if (!endpoint) return false;
|
|
550
|
+
const form = new URLSearchParams({ token: credential.refreshToken, token_type_hint: "refresh_token", client_id: credential.clientId }).toString();
|
|
551
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
552
|
+
if (options.signal?.aborted) return false;
|
|
553
|
+
if (attempt > 0) await new Promise((resolve) => setTimeout(resolve, 500 * 2 ** attempt));
|
|
554
|
+
try {
|
|
555
|
+
const response = await codexFetch(
|
|
556
|
+
endpoint,
|
|
557
|
+
{ method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: form },
|
|
558
|
+
bounded(),
|
|
559
|
+
"OpenAI's sign-in service"
|
|
560
|
+
);
|
|
561
|
+
if (response.ok) return true;
|
|
562
|
+
if (response.status < 500) return false;
|
|
563
|
+
} catch {
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
return false;
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
// src/connect/vault.ts
|
|
570
|
+
function memoryStorage() {
|
|
571
|
+
const rows = /* @__PURE__ */ new Map();
|
|
572
|
+
return {
|
|
573
|
+
async get(key) {
|
|
574
|
+
const row = rows.get(key);
|
|
575
|
+
if (!row) return null;
|
|
576
|
+
if (row.expiresAt !== null && row.expiresAt <= Date.now()) {
|
|
577
|
+
rows.delete(key);
|
|
578
|
+
return null;
|
|
579
|
+
}
|
|
580
|
+
return row.value;
|
|
581
|
+
},
|
|
582
|
+
async set(key, value, options) {
|
|
583
|
+
rows.set(key, { value, expiresAt: options?.ttlMs ? Date.now() + options.ttlMs : null });
|
|
584
|
+
},
|
|
585
|
+
async delete(key) {
|
|
586
|
+
rows.delete(key);
|
|
587
|
+
}
|
|
588
|
+
};
|
|
589
|
+
}
|
|
590
|
+
var PREFIX = "daex-connect/v1";
|
|
591
|
+
var REFRESH_TIMEOUT_MS = 3e4;
|
|
592
|
+
function createConnectVault(options) {
|
|
593
|
+
const { storage } = options;
|
|
594
|
+
const refreshAheadMs = options.refreshAheadMs ?? 5 * 60 * 1e3;
|
|
595
|
+
const keyPromise = deriveAesKey(options.secret, "vault");
|
|
596
|
+
const queues = /* @__PURE__ */ new Map();
|
|
597
|
+
const refreshing = /* @__PURE__ */ new Map();
|
|
598
|
+
const unsaved = /* @__PURE__ */ new Map();
|
|
599
|
+
const flushUnsaved = async (storageKey) => {
|
|
600
|
+
const pending = unsaved.get(storageKey);
|
|
601
|
+
if (!pending) return void 0;
|
|
602
|
+
let stored;
|
|
603
|
+
try {
|
|
604
|
+
stored = await read(storageKey);
|
|
605
|
+
} catch {
|
|
606
|
+
return pending.credential;
|
|
607
|
+
}
|
|
608
|
+
if (stored?.provider !== "codex" || stored.refreshToken !== pending.replaced) {
|
|
609
|
+
unsaved.delete(storageKey);
|
|
610
|
+
return void 0;
|
|
611
|
+
}
|
|
612
|
+
try {
|
|
613
|
+
await write(storageKey, pending.credential);
|
|
614
|
+
unsaved.delete(storageKey);
|
|
615
|
+
} catch {
|
|
616
|
+
}
|
|
617
|
+
return pending.credential;
|
|
618
|
+
};
|
|
619
|
+
const readCurrent = async (storageKey) => {
|
|
620
|
+
if (unsaved.has(storageKey)) {
|
|
621
|
+
const pending = await serial(storageKey, () => flushUnsaved(storageKey));
|
|
622
|
+
if (pending) return pending;
|
|
623
|
+
}
|
|
624
|
+
return read(storageKey);
|
|
625
|
+
};
|
|
626
|
+
const credentialKey = async (userId, provider) => {
|
|
627
|
+
if (typeof userId !== "string" || userId.length === 0) {
|
|
628
|
+
throw new ConnectError("invalid_request", "A user ID is required.");
|
|
629
|
+
}
|
|
630
|
+
return `${PREFIX}/cred/${provider}/${await sha256Hex(userId)}`;
|
|
631
|
+
};
|
|
632
|
+
const write = async (storageKey, credential) => {
|
|
633
|
+
await storage.set(storageKey, await sealText(await keyPromise, JSON.stringify(credential), storageKey));
|
|
634
|
+
};
|
|
635
|
+
const read = async (storageKey) => {
|
|
636
|
+
const sealed = await storage.get(storageKey);
|
|
637
|
+
if (!sealed) return null;
|
|
638
|
+
let plain;
|
|
639
|
+
try {
|
|
640
|
+
plain = await openText(await keyPromise, sealed, storageKey);
|
|
641
|
+
} catch (cause) {
|
|
642
|
+
throw new ConnectError("invalid_credential", "A stored sign-in could not be opened (wrong secret or a moved record).", { cause });
|
|
643
|
+
}
|
|
644
|
+
return parseConnectCredential(JSON.parse(plain));
|
|
645
|
+
};
|
|
646
|
+
const serial = (storageKey, fn) => {
|
|
647
|
+
const previous = queues.get(storageKey) ?? Promise.resolve();
|
|
648
|
+
const run = previous.catch(() => void 0).then(() => storage.lock ? storage.lock(`${storageKey}/lock`, fn) : fn());
|
|
649
|
+
const tail = run.catch(() => void 0);
|
|
650
|
+
queues.set(storageKey, tail);
|
|
651
|
+
void tail.then(() => {
|
|
652
|
+
if (queues.get(storageKey) === tail) queues.delete(storageKey);
|
|
653
|
+
});
|
|
654
|
+
return run;
|
|
655
|
+
};
|
|
656
|
+
const refreshCodex = (storageKey, force) => {
|
|
657
|
+
const pending = refreshing.get(storageKey);
|
|
658
|
+
if (pending) return pending;
|
|
659
|
+
const job = serial(storageKey, async () => {
|
|
660
|
+
const current = await flushUnsaved(storageKey) ?? await read(storageKey);
|
|
661
|
+
if (!current || current.provider !== "codex") {
|
|
662
|
+
throw new ConnectError("not_signed_in", "ChatGPT is not connected.", { provider: "codex" });
|
|
663
|
+
}
|
|
664
|
+
if (current.signedOut) {
|
|
665
|
+
throw new ConnectError("sign_in_required", "The ChatGPT sign-in ended. Sign in again.", { provider: "codex" });
|
|
666
|
+
}
|
|
667
|
+
const due = current.expiresAt - Date.now() <= refreshAheadMs;
|
|
668
|
+
if (!due && !force) return current;
|
|
669
|
+
try {
|
|
670
|
+
const timeout = AbortSignal.timeout(REFRESH_TIMEOUT_MS);
|
|
671
|
+
let next;
|
|
672
|
+
try {
|
|
673
|
+
next = await refreshCodexCredential(current, { fetch: options.fetch, signal: timeout });
|
|
674
|
+
} catch (error) {
|
|
675
|
+
if (!timeout.aborted) throw error;
|
|
676
|
+
throw new ConnectError("provider_unavailable", "OpenAI's sign-in service did not answer in time.", { provider: "codex", retryable: true, cause: error });
|
|
677
|
+
}
|
|
678
|
+
try {
|
|
679
|
+
await write(storageKey, next);
|
|
680
|
+
} catch {
|
|
681
|
+
unsaved.set(storageKey, { credential: next, replaced: unsaved.get(storageKey)?.replaced ?? current.refreshToken });
|
|
682
|
+
}
|
|
683
|
+
return next;
|
|
684
|
+
} catch (error) {
|
|
685
|
+
if (error instanceof ConnectError && error.code === "sign_in_required") {
|
|
686
|
+
const ended = { ...current, accessToken: "", refreshToken: "", signedOut: true };
|
|
687
|
+
await write(storageKey, ended);
|
|
688
|
+
}
|
|
689
|
+
throw error;
|
|
690
|
+
}
|
|
691
|
+
}).finally(() => refreshing.delete(storageKey));
|
|
692
|
+
refreshing.set(storageKey, job);
|
|
693
|
+
return job;
|
|
694
|
+
};
|
|
695
|
+
async function fresh(userId, provider, freshOptions) {
|
|
696
|
+
const storageKey = await credentialKey(userId, provider);
|
|
697
|
+
const credential = await readCurrent(storageKey);
|
|
698
|
+
if (!credential) {
|
|
699
|
+
throw new ConnectError("not_signed_in", `${connectProvider(provider).name} is not connected.`, { provider });
|
|
700
|
+
}
|
|
701
|
+
if (credential.signedOut) {
|
|
702
|
+
throw new ConnectError("sign_in_required", "This sign-in ended. Sign in again.", { provider });
|
|
703
|
+
}
|
|
704
|
+
if (credential.provider === "cursor") {
|
|
705
|
+
if (!isCursorUsable(credential)) {
|
|
706
|
+
throw new ConnectError("sign_in_required", "The Cursor sign-in expired. Sign in again.", { provider });
|
|
707
|
+
}
|
|
708
|
+
return credential;
|
|
709
|
+
}
|
|
710
|
+
const due = credential.expiresAt - Date.now() <= refreshAheadMs;
|
|
711
|
+
return due || freshOptions?.forceRefresh ? refreshCodex(storageKey, freshOptions?.forceRefresh === true) : credential;
|
|
712
|
+
}
|
|
713
|
+
const temporaryKey = (id) => `${PREFIX}/tmp/${id}`;
|
|
714
|
+
return {
|
|
715
|
+
async save(userId, credential) {
|
|
716
|
+
const parsed = parseConnectCredential(credential);
|
|
717
|
+
const storageKey = await credentialKey(userId, parsed.provider);
|
|
718
|
+
await serial(storageKey, async () => {
|
|
719
|
+
await write(storageKey, parsed);
|
|
720
|
+
unsaved.delete(storageKey);
|
|
721
|
+
});
|
|
722
|
+
},
|
|
723
|
+
async load(userId, provider) {
|
|
724
|
+
return readCurrent(await credentialKey(userId, provider));
|
|
725
|
+
},
|
|
726
|
+
async remove(userId, provider, removeOptions) {
|
|
727
|
+
const storageKey = await credentialKey(userId, provider);
|
|
728
|
+
const existing = await serial(storageKey, async () => {
|
|
729
|
+
let stored = null;
|
|
730
|
+
try {
|
|
731
|
+
stored = await read(storageKey);
|
|
732
|
+
} catch (error) {
|
|
733
|
+
if (!(error instanceof ConnectError && error.code === "invalid_credential")) throw error;
|
|
734
|
+
}
|
|
735
|
+
const retained = unsaved.get(storageKey);
|
|
736
|
+
const current = retained && stored?.provider === "codex" && stored.refreshToken === retained.replaced ? retained.credential : stored;
|
|
737
|
+
await storage.delete(storageKey);
|
|
738
|
+
unsaved.delete(storageKey);
|
|
739
|
+
return current;
|
|
740
|
+
});
|
|
741
|
+
if (existing?.provider === "codex" && removeOptions?.revoke !== false && existing.refreshToken) {
|
|
742
|
+
return { revoked: await revokeCodexCredential(existing, { fetch: options.fetch }) };
|
|
743
|
+
}
|
|
744
|
+
return { revoked: null };
|
|
745
|
+
},
|
|
746
|
+
async status(userId) {
|
|
747
|
+
const rows = [];
|
|
748
|
+
for (const provider of CONNECT_PROVIDERS) {
|
|
749
|
+
try {
|
|
750
|
+
rows.push(signInStatus(await readCurrent(await credentialKey(userId, provider.id)), provider.id));
|
|
751
|
+
} catch (error) {
|
|
752
|
+
if (!(error instanceof ConnectError && error.code === "invalid_credential")) throw error;
|
|
753
|
+
rows.push({ provider: provider.id, signedIn: false, needsSignIn: true });
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
return rows;
|
|
757
|
+
},
|
|
758
|
+
fresh,
|
|
759
|
+
async codexReauth(userId) {
|
|
760
|
+
const credential = await readCurrent(await credentialKey(userId, "codex")).catch(() => null);
|
|
761
|
+
if (!credential || credential.provider !== "codex") return void 0;
|
|
762
|
+
return {
|
|
763
|
+
clientId: credential.clientId,
|
|
764
|
+
...credential.idToken ? { idTokenHint: credential.idToken } : {},
|
|
765
|
+
...credential.email ? { loginHint: credential.email } : {}
|
|
766
|
+
};
|
|
767
|
+
},
|
|
768
|
+
async putTemporary(id, value, ttlMs) {
|
|
769
|
+
const storageKey = temporaryKey(id);
|
|
770
|
+
await storage.set(storageKey, await sealText(await keyPromise, JSON.stringify(value), storageKey), { ttlMs });
|
|
771
|
+
},
|
|
772
|
+
async readTemporary(id) {
|
|
773
|
+
const storageKey = temporaryKey(id);
|
|
774
|
+
const sealed = await storage.get(storageKey);
|
|
775
|
+
if (!sealed) return null;
|
|
776
|
+
try {
|
|
777
|
+
return JSON.parse(await openText(await keyPromise, sealed, storageKey));
|
|
778
|
+
} catch {
|
|
779
|
+
return null;
|
|
780
|
+
}
|
|
781
|
+
},
|
|
782
|
+
async deleteTemporary(id) {
|
|
783
|
+
await storage.delete(temporaryKey(id));
|
|
784
|
+
}
|
|
785
|
+
};
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
// src/connect/codexApi.ts
|
|
789
|
+
var USAGE_URL = connectProvider("codex").manageUrl;
|
|
790
|
+
var UNAVAILABLE = {
|
|
791
|
+
code: "provider_unavailable",
|
|
792
|
+
message: "ChatGPT plan usage is unavailable right now. Try again shortly.",
|
|
793
|
+
retryable: true
|
|
794
|
+
};
|
|
795
|
+
var ERROR_MAP = {
|
|
796
|
+
subscription_sharing_user_not_eligible: {
|
|
797
|
+
code: "plan_not_eligible",
|
|
798
|
+
message: "This ChatGPT plan can't be used in other apps. ChatGPT Plus or Pro is needed."
|
|
799
|
+
},
|
|
800
|
+
subscription_sharing_usage_limit_exceeded: {
|
|
801
|
+
code: "usage_limit",
|
|
802
|
+
message: "The ChatGPT plan's usage limit for this app is used up."
|
|
803
|
+
},
|
|
804
|
+
subscription_sharing_usage_unavailable: UNAVAILABLE,
|
|
805
|
+
subscription_sharing_user_unavailable: UNAVAILABLE,
|
|
806
|
+
subscription_sharing_unsupported_capability: {
|
|
807
|
+
code: "unsupported_request",
|
|
808
|
+
message: "ChatGPT plan usage does not support part of this request."
|
|
809
|
+
},
|
|
810
|
+
subscription_sharing_route_not_supported: {
|
|
811
|
+
code: "unsupported_request",
|
|
812
|
+
message: "ChatGPT plan usage does not support this endpoint."
|
|
813
|
+
},
|
|
814
|
+
subscription_sharing_invalid_user: {
|
|
815
|
+
code: "sign_in_required",
|
|
816
|
+
message: "OpenAI did not accept this ChatGPT sign-in."
|
|
817
|
+
}
|
|
818
|
+
};
|
|
819
|
+
function errorFromBody(status, body2, requestId) {
|
|
820
|
+
const nested = typeof body2?.error === "object" && body2.error !== null ? body2.error : null;
|
|
821
|
+
const providerCode = typeof nested?.code === "string" ? nested.code : void 0;
|
|
822
|
+
const param = typeof nested?.param === "string" ? nested.param : void 0;
|
|
823
|
+
const base = { provider: "codex", httpStatus: status, ...providerCode ? { providerCode } : {}, ...requestId ? { requestId } : {} };
|
|
824
|
+
const mapped = providerCode ? ERROR_MAP[providerCode] : void 0;
|
|
825
|
+
if (mapped) {
|
|
826
|
+
return new ConnectError(mapped.code, param ? `${mapped.message} (${param})` : mapped.message, {
|
|
827
|
+
...base,
|
|
828
|
+
retryable: mapped.retryable ?? false,
|
|
829
|
+
...mapped.code === "usage_limit" || mapped.code === "plan_not_eligible" ? { manageUrl: USAGE_URL } : {}
|
|
830
|
+
});
|
|
831
|
+
}
|
|
832
|
+
const detail = typeof body2?.detail === "string" ? body2.detail : typeof nested?.message === "string" ? nested.message : "";
|
|
833
|
+
if (status === 401) return new ConnectError("sign_in_required", "OpenAI did not accept this ChatGPT sign-in.", base);
|
|
834
|
+
if (status === 503 || status === 502 || status === 504 || status === 429) {
|
|
835
|
+
return new ConnectError("provider_unavailable", "ChatGPT is unavailable right now. Try again shortly.", { ...base, retryable: true });
|
|
836
|
+
}
|
|
837
|
+
return new ConnectError("provider_error", detail ? `ChatGPT refused the request: ${detail}` : `ChatGPT refused the request (HTTP ${status}).`, base);
|
|
838
|
+
}
|
|
839
|
+
function authHeaders(credential) {
|
|
840
|
+
if (credential.signedOut || !credential.accessToken) {
|
|
841
|
+
throw new ConnectError("sign_in_required", "The ChatGPT sign-in ended. Sign in again.", { provider: "codex" });
|
|
842
|
+
}
|
|
843
|
+
if (!credential.planUsage) {
|
|
844
|
+
throw new ConnectError("plan_usage_disabled", "The user signed in without allowing ChatGPT plan usage. Sign in again and allow it.", {
|
|
845
|
+
provider: "codex",
|
|
846
|
+
manageUrl: USAGE_URL
|
|
847
|
+
});
|
|
848
|
+
}
|
|
849
|
+
return { Authorization: `Bearer ${credential.accessToken}` };
|
|
850
|
+
}
|
|
851
|
+
async function listCodexModels(credential, options = {}) {
|
|
852
|
+
const response = await codexFetch(`${CODEX_API_BASE}/models`, { headers: { ...authHeaders(credential), Accept: "application/json" } }, options, "ChatGPT");
|
|
853
|
+
const body2 = await readJson(response);
|
|
854
|
+
if (!response.ok) throw errorFromBody(response.status, body2, response.headers.get("x-request-id") ?? void 0);
|
|
855
|
+
const rows = Array.isArray(body2?.models) ? body2.models : Array.isArray(body2?.data) ? body2.data : [];
|
|
856
|
+
const models = [];
|
|
857
|
+
for (const row of rows) {
|
|
858
|
+
if (typeof row !== "object" || row === null) continue;
|
|
859
|
+
const record2 = row;
|
|
860
|
+
if (record2.visibility !== void 0 && record2.visibility !== "list") continue;
|
|
861
|
+
const id = typeof record2.slug === "string" ? record2.slug : typeof record2.id === "string" ? record2.id : null;
|
|
862
|
+
if (!id) continue;
|
|
863
|
+
models.push({ id, name: typeof record2.display_name === "string" ? record2.display_name : id, raw: record2 });
|
|
864
|
+
}
|
|
865
|
+
return models;
|
|
866
|
+
}
|
|
867
|
+
var MAX_SSE_EVENT_CHARS = 4 * 1024 * 1024;
|
|
868
|
+
async function* readSse(body2) {
|
|
869
|
+
const reader = body2.getReader();
|
|
870
|
+
const decoder2 = new TextDecoder();
|
|
871
|
+
let buffer = "";
|
|
872
|
+
let finished = false;
|
|
873
|
+
try {
|
|
874
|
+
while (true) {
|
|
875
|
+
const { value, done } = await reader.read();
|
|
876
|
+
if (done) {
|
|
877
|
+
finished = true;
|
|
878
|
+
break;
|
|
879
|
+
}
|
|
880
|
+
buffer = (buffer + decoder2.decode(value, { stream: true })).replace(/\r\n/g, "\n");
|
|
881
|
+
let boundary = buffer.indexOf("\n\n");
|
|
882
|
+
while (boundary !== -1) {
|
|
883
|
+
const block = buffer.slice(0, boundary);
|
|
884
|
+
buffer = buffer.slice(boundary + 2);
|
|
885
|
+
const data = block.split("\n").filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trimStart()).join("\n");
|
|
886
|
+
if (data && data !== "[DONE]") {
|
|
887
|
+
try {
|
|
888
|
+
const parsed = JSON.parse(data);
|
|
889
|
+
if (typeof parsed === "object" && parsed !== null) yield parsed;
|
|
890
|
+
} catch {
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
boundary = buffer.indexOf("\n\n");
|
|
894
|
+
}
|
|
895
|
+
if (buffer.length > MAX_SSE_EVENT_CHARS) {
|
|
896
|
+
throw new ConnectError("provider_error", "ChatGPT sent an event too large to read.", { provider: "codex" });
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
} finally {
|
|
900
|
+
if (!finished) await reader.cancel().catch(() => void 0);
|
|
901
|
+
reader.releaseLock();
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
function responsesBody(request) {
|
|
905
|
+
const custom = request.codex ?? {};
|
|
906
|
+
const body2 = { model: request.model, store: false };
|
|
907
|
+
if (custom.input === void 0) {
|
|
908
|
+
body2.input = requestMessages(request).map((message) => ({ role: message.role, content: message.content }));
|
|
909
|
+
}
|
|
910
|
+
if (request.instructions) body2.instructions = request.instructions;
|
|
911
|
+
if (request.effort) body2.reasoning = { effort: request.effort };
|
|
912
|
+
if (request.responseFormat) {
|
|
913
|
+
const format = request.responseFormat;
|
|
914
|
+
body2.text = {
|
|
915
|
+
format: format.type === "json_schema" ? {
|
|
916
|
+
type: "json_schema",
|
|
917
|
+
name: format.name,
|
|
918
|
+
schema: format.schema,
|
|
919
|
+
...format.strict === void 0 ? {} : { strict: format.strict },
|
|
920
|
+
...format.description ? { description: format.description } : {}
|
|
921
|
+
} : { type: format.type }
|
|
922
|
+
};
|
|
923
|
+
}
|
|
924
|
+
return Object.assign(body2, custom, { stream: true });
|
|
925
|
+
}
|
|
926
|
+
async function* responseEvents(stream, request, requestId) {
|
|
927
|
+
const ids = requestId ? { requestId } : {};
|
|
928
|
+
let text2 = "";
|
|
929
|
+
for await (const event of readSse(stream)) {
|
|
930
|
+
const type = event.type;
|
|
931
|
+
if (request.rawEvents) yield { type: "raw", provider: "codex", event };
|
|
932
|
+
if (type === "response.output_text.delta" && typeof event.delta === "string") {
|
|
933
|
+
text2 += event.delta;
|
|
934
|
+
yield { type: "text", delta: event.delta };
|
|
935
|
+
} else if (type === "response.completed") {
|
|
936
|
+
const done = event.response;
|
|
937
|
+
const model = typeof done?.model === "string" ? done.model : request.model;
|
|
938
|
+
yield { type: "done", text: text2, model, ...done?.usage === void 0 ? {} : { usage: done.usage }, ...done ? { response: done } : {} };
|
|
939
|
+
return;
|
|
940
|
+
} else if (type === "response.failed" || type === "error") {
|
|
941
|
+
const failed = event.response ?? event;
|
|
942
|
+
throw errorFromBody(400, { error: failed.error ?? failed }, requestId);
|
|
943
|
+
} else if (type === "response.incomplete") {
|
|
944
|
+
const details = event.response?.incomplete_details;
|
|
945
|
+
const reason = typeof details?.reason === "string" ? details.reason : "unknown";
|
|
946
|
+
throw new ConnectError("provider_error", `ChatGPT stopped before finishing (${reason}).`, { provider: "codex", providerCode: reason, ...ids });
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
throw new ConnectError("provider_error", "ChatGPT's reply ended before it finished.", { provider: "codex", retryable: true, ...ids });
|
|
950
|
+
}
|
|
951
|
+
async function* streamCodexResponse(credential, request, options = {}) {
|
|
952
|
+
const body2 = responsesBody(request);
|
|
953
|
+
const signal = request.signal ?? options.signal;
|
|
954
|
+
if (signal?.aborted) throw cancelledError("codex");
|
|
955
|
+
const response = await codexFetch(
|
|
956
|
+
`${CODEX_API_BASE}/responses`,
|
|
957
|
+
{
|
|
958
|
+
method: "POST",
|
|
959
|
+
headers: { ...authHeaders(credential), "Content-Type": "application/json", Accept: "text/event-stream" },
|
|
960
|
+
body: JSON.stringify(body2),
|
|
961
|
+
...signal ? { signal } : {}
|
|
962
|
+
},
|
|
963
|
+
options,
|
|
964
|
+
"ChatGPT"
|
|
965
|
+
);
|
|
966
|
+
const requestId = response.headers.get("x-request-id") ?? void 0;
|
|
967
|
+
if (!response.ok || !response.body) {
|
|
968
|
+
throw errorFromBody(response.status, await readJson(response), requestId);
|
|
969
|
+
}
|
|
970
|
+
try {
|
|
971
|
+
yield* responseEvents(response.body, request, requestId);
|
|
972
|
+
} catch (error) {
|
|
973
|
+
if (signal?.aborted) throw cancelledError("codex");
|
|
974
|
+
throw error;
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
|
|
978
|
+
// src/connect/cursor.ts
|
|
979
|
+
var sdkPromise = null;
|
|
980
|
+
var sdkLoader = null;
|
|
981
|
+
function provideCursorSdk(loader) {
|
|
982
|
+
sdkLoader = loader;
|
|
983
|
+
sdkPromise = null;
|
|
984
|
+
}
|
|
985
|
+
async function loadCursorSdk() {
|
|
986
|
+
if (!sdkPromise) {
|
|
987
|
+
const specifier = "@cursor/sdk";
|
|
988
|
+
const load = sdkLoader ?? (() => import(specifier));
|
|
989
|
+
sdkPromise = load().catch((cause) => {
|
|
990
|
+
sdkPromise = null;
|
|
991
|
+
throw new ConnectError("provider_sdk_missing", "Install @cursor/sdk to use Cursor: npm install @cursor/sdk", {
|
|
992
|
+
provider: "cursor",
|
|
993
|
+
cause
|
|
994
|
+
});
|
|
995
|
+
});
|
|
996
|
+
}
|
|
997
|
+
return sdkPromise;
|
|
998
|
+
}
|
|
999
|
+
function mapCursorError(error) {
|
|
1000
|
+
if (error instanceof ConnectError) return error;
|
|
1001
|
+
const name = typeof error === "object" && error !== null && "name" in error ? String(error.name) : "";
|
|
1002
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1003
|
+
if (name === "AuthenticationError") {
|
|
1004
|
+
return new ConnectError("sign_in_required", "Cursor did not accept this sign-in. Sign in again.", { provider: "cursor", cause: error });
|
|
1005
|
+
}
|
|
1006
|
+
if (name === "RateLimitError") {
|
|
1007
|
+
return new ConnectError("usage_limit", "The Cursor plan's limit is reached for now.", {
|
|
1008
|
+
provider: "cursor",
|
|
1009
|
+
retryable: true,
|
|
1010
|
+
manageUrl: connectProvider("cursor").manageUrl,
|
|
1011
|
+
cause: error
|
|
1012
|
+
});
|
|
1013
|
+
}
|
|
1014
|
+
if (name === "NetworkError") {
|
|
1015
|
+
return new ConnectError("provider_unavailable", "Could not reach Cursor.", { provider: "cursor", retryable: true, cause: error });
|
|
1016
|
+
}
|
|
1017
|
+
return new ConnectError("provider_error", `Cursor failed: ${message}`, { provider: "cursor", cause: error });
|
|
1018
|
+
}
|
|
1019
|
+
async function signInWithCursor(options) {
|
|
1020
|
+
const appName = options.appName?.trim();
|
|
1021
|
+
if (!appName) throw new ConnectError("invalid_request", "appName is required.", { provider: "cursor" });
|
|
1022
|
+
const sdk = await loadCursorSdk();
|
|
1023
|
+
try {
|
|
1024
|
+
const result = await sdk.Cursor.auth.login({
|
|
1025
|
+
apiKeyName: appName,
|
|
1026
|
+
// Never write ~/.cursor/sdk/auth.json: the key belongs to the caller's store.
|
|
1027
|
+
store: null,
|
|
1028
|
+
openBrowser: options.openBrowser ?? false,
|
|
1029
|
+
onLoginUrl: options.onLoginUrl,
|
|
1030
|
+
...options.signal ? { signal: options.signal } : {},
|
|
1031
|
+
...options.keyTtlMs ? { apiKeyTtlMs: options.keyTtlMs } : {}
|
|
1032
|
+
});
|
|
1033
|
+
return {
|
|
1034
|
+
version: 1,
|
|
1035
|
+
provider: "cursor",
|
|
1036
|
+
apiKey: result.apiKey,
|
|
1037
|
+
...result.email ? { email: result.email } : {},
|
|
1038
|
+
expiresAt: result.apiKeyExpiresAtMs,
|
|
1039
|
+
savedAt: Date.now()
|
|
1040
|
+
};
|
|
1041
|
+
} catch (error) {
|
|
1042
|
+
if (options.signal?.aborted) {
|
|
1043
|
+
throw new ConnectError("sign_in_cancelled", "The sign-in was cancelled.", { provider: "cursor", cause: error });
|
|
1044
|
+
}
|
|
1045
|
+
const mapped = mapCursorError(error);
|
|
1046
|
+
if (mapped.code === "sign_in_required") {
|
|
1047
|
+
throw new ConnectError("sign_in_failed", "Cursor's sign-in did not finish.", { provider: "cursor", cause: error });
|
|
1048
|
+
}
|
|
1049
|
+
throw mapped;
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
function usableKey(credential) {
|
|
1053
|
+
if (!isCursorUsable(credential)) {
|
|
1054
|
+
throw new ConnectError("sign_in_required", "The Cursor sign-in ended. Sign in again.", { provider: "cursor" });
|
|
1055
|
+
}
|
|
1056
|
+
return credential.apiKey;
|
|
1057
|
+
}
|
|
1058
|
+
async function listCursorModels(credential) {
|
|
1059
|
+
const apiKey = usableKey(credential);
|
|
1060
|
+
const sdk = await loadCursorSdk();
|
|
1061
|
+
try {
|
|
1062
|
+
const rows = await cursorCatalog(sdk, apiKey);
|
|
1063
|
+
return rows.map((row) => ({ id: row.id, name: row.displayName || row.id, raw: row }));
|
|
1064
|
+
} catch (error) {
|
|
1065
|
+
throw mapCursorError(error);
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
var CURSOR_DEFAULT_MODEL = "default";
|
|
1069
|
+
var CATALOG_CACHE_MS = 10 * 60 * 1e3;
|
|
1070
|
+
var CATALOG_CACHE_MAX = 500;
|
|
1071
|
+
var catalogCache = /* @__PURE__ */ new Map();
|
|
1072
|
+
async function cursorCatalog(sdk, apiKey) {
|
|
1073
|
+
const cacheKey = await sha256Hex(apiKey);
|
|
1074
|
+
const now = Date.now();
|
|
1075
|
+
const cached = catalogCache.get(cacheKey);
|
|
1076
|
+
if (cached && now - cached.at < CATALOG_CACHE_MS) return cached.rows;
|
|
1077
|
+
const rows = await sdk.Cursor.models.list({ apiKey });
|
|
1078
|
+
for (const [key, entry] of catalogCache) {
|
|
1079
|
+
if (now - entry.at >= CATALOG_CACHE_MS) catalogCache.delete(key);
|
|
1080
|
+
}
|
|
1081
|
+
while (catalogCache.size >= CATALOG_CACHE_MAX) {
|
|
1082
|
+
const oldest = catalogCache.keys().next().value;
|
|
1083
|
+
if (oldest === void 0) break;
|
|
1084
|
+
catalogCache.delete(oldest);
|
|
1085
|
+
}
|
|
1086
|
+
catalogCache.set(cacheKey, { rows, at: now });
|
|
1087
|
+
return rows;
|
|
1088
|
+
}
|
|
1089
|
+
var EFFORT_PARAMETER_IDS = ["reasoning_effort", "effort"];
|
|
1090
|
+
async function cursorModelSelection(sdk, apiKey, request) {
|
|
1091
|
+
const wanted = request.model?.trim();
|
|
1092
|
+
const custom = request.cursor?.params ?? [];
|
|
1093
|
+
const isAuto = !wanted || wanted === CURSOR_DEFAULT_MODEL || wanted === "auto";
|
|
1094
|
+
let rows = [];
|
|
1095
|
+
if (!isAuto) {
|
|
1096
|
+
try {
|
|
1097
|
+
rows = await cursorCatalog(sdk, apiKey);
|
|
1098
|
+
} catch (cause) {
|
|
1099
|
+
const mapped = mapCursorError(cause);
|
|
1100
|
+
if (mapped.code === "sign_in_required" || mapped.code === "usage_limit") throw mapped;
|
|
1101
|
+
if (!custom.some((param) => param.id === "fast")) {
|
|
1102
|
+
throw new ConnectError("provider_unavailable", "Cursor's model list is unavailable, so the standard tier can't be confirmed. Try again shortly.", {
|
|
1103
|
+
provider: "cursor",
|
|
1104
|
+
retryable: true,
|
|
1105
|
+
cause
|
|
1106
|
+
});
|
|
1107
|
+
}
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
const row = isAuto ? void 0 : rows.find((entry) => entry.id === wanted || entry.aliases?.includes(wanted ?? ""));
|
|
1111
|
+
const params = /* @__PURE__ */ new Map();
|
|
1112
|
+
if (row?.parameters?.find((parameter) => parameter.id === "fast")?.values.some((entry) => entry.value === "false")) {
|
|
1113
|
+
params.set("fast", "false");
|
|
1114
|
+
}
|
|
1115
|
+
if (request.effort && row) {
|
|
1116
|
+
const effortParameter = row.parameters?.find((parameter) => EFFORT_PARAMETER_IDS.includes(parameter.id));
|
|
1117
|
+
if (effortParameter) params.set(effortParameter.id, request.effort);
|
|
1118
|
+
}
|
|
1119
|
+
for (const param of custom) params.set(param.id, param.value);
|
|
1120
|
+
const id = isAuto ? CURSOR_DEFAULT_MODEL : row?.id ?? wanted;
|
|
1121
|
+
return params.size > 0 ? { id, params: [...params].map(([key, value]) => ({ id: key, value })) } : { id };
|
|
1122
|
+
}
|
|
1123
|
+
function formatInstruction(format) {
|
|
1124
|
+
if (!format || format.type === "text") return void 0;
|
|
1125
|
+
if (format.type === "json_object") return "Reply with one JSON object and nothing else.";
|
|
1126
|
+
return `Reply with one JSON value that matches this JSON Schema, and nothing else:
|
|
1127
|
+
${JSON.stringify(format.schema)}`;
|
|
1128
|
+
}
|
|
1129
|
+
async function runFolder(sdk) {
|
|
1130
|
+
const [{ mkdtemp, readdir, rm }, os, path] = await Promise.all([
|
|
1131
|
+
import("fs/promises"),
|
|
1132
|
+
import("os"),
|
|
1133
|
+
import("path")
|
|
1134
|
+
]);
|
|
1135
|
+
const cwd = await mkdtemp(path.join(os.tmpdir(), "daexconnect"));
|
|
1136
|
+
const tag = path.basename(cwd);
|
|
1137
|
+
const store = new sdk.JsonlLocalAgentStore(path.join(cwd, "store"));
|
|
1138
|
+
return {
|
|
1139
|
+
cwd,
|
|
1140
|
+
store,
|
|
1141
|
+
async remove() {
|
|
1142
|
+
const options = { recursive: true, force: true, maxRetries: 5, retryDelay: 200 };
|
|
1143
|
+
const sweep = async () => {
|
|
1144
|
+
await rm(cwd, options).catch(() => void 0);
|
|
1145
|
+
const projectRoots = [
|
|
1146
|
+
process.env.CURSOR_CONFIG_DIR ? path.join(process.env.CURSOR_CONFIG_DIR, "projects") : null,
|
|
1147
|
+
path.join(os.homedir(), ".cursor", "projects")
|
|
1148
|
+
].filter((root) => Boolean(root));
|
|
1149
|
+
for (const root of projectRoots) {
|
|
1150
|
+
const entries = await readdir(root).catch(() => []);
|
|
1151
|
+
for (const entry of entries) {
|
|
1152
|
+
if (entry.endsWith(tag)) await rm(path.join(root, entry), options).catch(() => void 0);
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
};
|
|
1156
|
+
await sweep();
|
|
1157
|
+
setTimeout(() => void sweep(), 3e3).unref?.();
|
|
1158
|
+
}
|
|
1159
|
+
};
|
|
1160
|
+
}
|
|
1161
|
+
function cursorPrompt(instructions, messages) {
|
|
1162
|
+
const last = messages[messages.length - 1];
|
|
1163
|
+
const history = messages.slice(0, -1);
|
|
1164
|
+
const parts = [];
|
|
1165
|
+
if (instructions) parts.push(`<instructions>
|
|
1166
|
+
${instructions}
|
|
1167
|
+
</instructions>`);
|
|
1168
|
+
if (history.length > 0) {
|
|
1169
|
+
parts.push(
|
|
1170
|
+
`<conversation>
|
|
1171
|
+
${history.map((message) => `${message.role === "user" ? "User" : "Assistant"}: ${message.content}`).join("\n\n")}
|
|
1172
|
+
</conversation>`
|
|
1173
|
+
);
|
|
1174
|
+
}
|
|
1175
|
+
parts.push(last?.content ?? "");
|
|
1176
|
+
return parts.join("\n\n");
|
|
1177
|
+
}
|
|
1178
|
+
function assistantText(message) {
|
|
1179
|
+
if (typeof message !== "object" || message === null) return "";
|
|
1180
|
+
const record2 = message;
|
|
1181
|
+
if (record2.type !== "assistant" || !Array.isArray(record2.message?.content)) return "";
|
|
1182
|
+
return record2.message.content.map((block) => typeof block === "object" && block !== null && block.type === "text" ? String(block.text ?? "") : "").join("");
|
|
1183
|
+
}
|
|
1184
|
+
async function* streamCursorResponse(credential, request) {
|
|
1185
|
+
const apiKey = usableKey(credential);
|
|
1186
|
+
const messages = requestMessages(request);
|
|
1187
|
+
const sdk = await loadCursorSdk();
|
|
1188
|
+
let agent = null;
|
|
1189
|
+
let run = null;
|
|
1190
|
+
let folder = null;
|
|
1191
|
+
const onAbort = () => {
|
|
1192
|
+
void run?.cancel().catch(() => void 0);
|
|
1193
|
+
};
|
|
1194
|
+
request.signal?.addEventListener("abort", onAbort, { once: true });
|
|
1195
|
+
const stopIfCancelled = () => {
|
|
1196
|
+
if (request.signal?.aborted) throw cancelledError("cursor");
|
|
1197
|
+
};
|
|
1198
|
+
try {
|
|
1199
|
+
stopIfCancelled();
|
|
1200
|
+
const model = await cursorModelSelection(sdk, apiKey, request);
|
|
1201
|
+
stopIfCancelled();
|
|
1202
|
+
folder = await runFolder(sdk);
|
|
1203
|
+
const custom = request.cursor?.agent ?? {};
|
|
1204
|
+
const customLocal = typeof custom.local === "object" && custom.local !== null ? custom.local : {};
|
|
1205
|
+
agent = await sdk.Agent.create({
|
|
1206
|
+
apiKey,
|
|
1207
|
+
model,
|
|
1208
|
+
...custom,
|
|
1209
|
+
// The caller's local options win too; the private folder is only the default.
|
|
1210
|
+
local: { fs: sdk.tempFs(), cwd: folder.cwd, store: folder.store, ...customLocal }
|
|
1211
|
+
});
|
|
1212
|
+
const instructions = [request.instructions, formatInstruction(request.responseFormat)].filter(Boolean).join("\n\n") || void 0;
|
|
1213
|
+
run = await agent.send(cursorPrompt(instructions, messages), request.cursor?.send);
|
|
1214
|
+
if (request.signal?.aborted) {
|
|
1215
|
+
await run.cancel().catch(() => void 0);
|
|
1216
|
+
stopIfCancelled();
|
|
1217
|
+
}
|
|
1218
|
+
let text2 = "";
|
|
1219
|
+
for await (const message of run.stream()) {
|
|
1220
|
+
if (request.rawEvents) yield { type: "raw", provider: "cursor", event: message };
|
|
1221
|
+
const delta = assistantText(message);
|
|
1222
|
+
if (delta) {
|
|
1223
|
+
text2 += delta;
|
|
1224
|
+
yield { type: "text", delta };
|
|
1225
|
+
}
|
|
1226
|
+
}
|
|
1227
|
+
const result = await run.wait();
|
|
1228
|
+
if (result.status && result.status !== "finished") {
|
|
1229
|
+
if (result.status === "cancelled" || request.signal?.aborted) throw cancelledError("cursor");
|
|
1230
|
+
throw new ConnectError("provider_error", `Cursor's run ended as ${result.status}${result.error?.message ? `: ${result.error.message}` : ""}.`, {
|
|
1231
|
+
provider: "cursor",
|
|
1232
|
+
...result.error?.code ? { providerCode: result.error.code } : {}
|
|
1233
|
+
});
|
|
1234
|
+
}
|
|
1235
|
+
yield {
|
|
1236
|
+
type: "done",
|
|
1237
|
+
text: text2 || result.result || "",
|
|
1238
|
+
model: model.id,
|
|
1239
|
+
...result.usage === void 0 ? {} : { usage: result.usage },
|
|
1240
|
+
response: result
|
|
1241
|
+
};
|
|
1242
|
+
} catch (error) {
|
|
1243
|
+
if (request.signal?.aborted) throw cancelledError("cursor");
|
|
1244
|
+
throw mapCursorError(error);
|
|
1245
|
+
} finally {
|
|
1246
|
+
request.signal?.removeEventListener("abort", onAbort);
|
|
1247
|
+
agent?.close();
|
|
1248
|
+
await folder?.remove();
|
|
1249
|
+
}
|
|
1250
|
+
}
|
|
1251
|
+
|
|
1252
|
+
// src/connect/ai.ts
|
|
1253
|
+
var MODEL_CACHE_MS = 10 * 60 * 1e3;
|
|
1254
|
+
function createConnectAI(options) {
|
|
1255
|
+
const { vault } = options;
|
|
1256
|
+
const defaultModels = /* @__PURE__ */ new Map();
|
|
1257
|
+
const codexDefaultModel = async (credential, signal) => {
|
|
1258
|
+
const now = Date.now();
|
|
1259
|
+
const cacheKey = `${credential.clientId}:${credential.accountId}`;
|
|
1260
|
+
const cached = defaultModels.get(cacheKey);
|
|
1261
|
+
if (cached && now - cached.at < MODEL_CACHE_MS) return cached.model;
|
|
1262
|
+
if (signal?.aborted) throw cancelledError("codex");
|
|
1263
|
+
const models = await listCodexModels(credential, { fetch: options.fetch, ...signal ? { signal } : {} });
|
|
1264
|
+
const first = models[0]?.id;
|
|
1265
|
+
if (!first) throw new ConnectError("plan_not_eligible", "This ChatGPT plan has no models available to other apps.", { provider: "codex" });
|
|
1266
|
+
for (const [account, entry] of defaultModels) {
|
|
1267
|
+
if (now - entry.at >= MODEL_CACHE_MS) defaultModels.delete(account);
|
|
1268
|
+
}
|
|
1269
|
+
defaultModels.set(cacheKey, { model: first, at: now });
|
|
1270
|
+
return first;
|
|
1271
|
+
};
|
|
1272
|
+
async function* codexStream(userId, request) {
|
|
1273
|
+
let credential = await vault.fresh(userId, "codex");
|
|
1274
|
+
let retried = false;
|
|
1275
|
+
while (true) {
|
|
1276
|
+
let produced = false;
|
|
1277
|
+
try {
|
|
1278
|
+
const explicit = request.model ?? (typeof request.codex?.model === "string" ? request.codex.model : void 0);
|
|
1279
|
+
const model = explicit ?? await codexDefaultModel(credential, request.signal);
|
|
1280
|
+
for await (const event of streamCodexResponse(credential, { ...request, model }, { fetch: options.fetch })) {
|
|
1281
|
+
produced = true;
|
|
1282
|
+
yield event;
|
|
1283
|
+
}
|
|
1284
|
+
return;
|
|
1285
|
+
} catch (error) {
|
|
1286
|
+
const rejected = error instanceof ConnectError && error.code === "sign_in_required" && error.httpStatus === 401;
|
|
1287
|
+
if (!rejected || produced || retried) throw error;
|
|
1288
|
+
retried = true;
|
|
1289
|
+
const refreshed = await vault.fresh(userId, "codex", { forceRefresh: true });
|
|
1290
|
+
if (refreshed.clientId !== credential.clientId || refreshed.accountId !== credential.accountId) throw error;
|
|
1291
|
+
credential = refreshed;
|
|
1292
|
+
}
|
|
1293
|
+
}
|
|
1294
|
+
}
|
|
1295
|
+
async function* cursorStream(userId, request) {
|
|
1296
|
+
yield* streamCursorResponse(await vault.fresh(userId, "cursor"), request);
|
|
1297
|
+
}
|
|
1298
|
+
const streams = {
|
|
1299
|
+
codex: codexStream,
|
|
1300
|
+
cursor: cursorStream
|
|
1301
|
+
};
|
|
1302
|
+
const modelLists = {
|
|
1303
|
+
codex: async (userId) => listCodexModels(await vault.fresh(userId, "codex"), { fetch: options.fetch }),
|
|
1304
|
+
cursor: async (userId) => listCursorModels(await vault.fresh(userId, "cursor"))
|
|
1305
|
+
};
|
|
1306
|
+
return {
|
|
1307
|
+
respond(userId, request) {
|
|
1308
|
+
const stream = streams[request.provider];
|
|
1309
|
+
if (!stream) throw unknownProviderError();
|
|
1310
|
+
let used = false;
|
|
1311
|
+
const claim = () => {
|
|
1312
|
+
if (used) throw new ConnectError("invalid_request", "A response can be read once.");
|
|
1313
|
+
used = true;
|
|
1314
|
+
return stream(userId, request);
|
|
1315
|
+
};
|
|
1316
|
+
return {
|
|
1317
|
+
[Symbol.asyncIterator]: () => claim(),
|
|
1318
|
+
async text() {
|
|
1319
|
+
let text2 = "";
|
|
1320
|
+
for await (const event of claim()) {
|
|
1321
|
+
if (event.type === "text") text2 += event.delta;
|
|
1322
|
+
if (event.type === "done") return event.text || text2;
|
|
1323
|
+
}
|
|
1324
|
+
return text2;
|
|
1325
|
+
}
|
|
1326
|
+
};
|
|
1327
|
+
},
|
|
1328
|
+
async models(userId, provider) {
|
|
1329
|
+
const list = modelLists[provider];
|
|
1330
|
+
if (!list) throw unknownProviderError();
|
|
1331
|
+
return list(userId);
|
|
1332
|
+
}
|
|
1333
|
+
};
|
|
1334
|
+
}
|
|
1335
|
+
|
|
1336
|
+
// src/connect/cursorSignIns.ts
|
|
1337
|
+
var ATTEMPT_TTL_MS = 15 * 60 * 1e3;
|
|
1338
|
+
var URL_WAIT_MS = 30 * 1e3;
|
|
1339
|
+
var MAX_PER_USER = 3;
|
|
1340
|
+
var DONE_RECORD_TRIES = 3;
|
|
1341
|
+
function createCursorSignIns(options) {
|
|
1342
|
+
const { vault } = options;
|
|
1343
|
+
const running = /* @__PURE__ */ new Map();
|
|
1344
|
+
const stop = (signInId) => {
|
|
1345
|
+
running.get(signInId)?.abort.abort();
|
|
1346
|
+
running.delete(signInId);
|
|
1347
|
+
};
|
|
1348
|
+
const stateKey = (signInId) => `cursor-signin/${signInId}`;
|
|
1349
|
+
const generationKey = async (userId) => `cursor-generation/${await sha256Hex(userId)}`;
|
|
1350
|
+
const GENERATION_TTL_MS = 2 * ATTEMPT_TTL_MS;
|
|
1351
|
+
const INITIAL_GENERATION = "initial";
|
|
1352
|
+
const readGeneration = async (userId) => {
|
|
1353
|
+
const value = await vault.readTemporary(await generationKey(userId));
|
|
1354
|
+
return typeof value === "string" ? value : INITIAL_GENERATION;
|
|
1355
|
+
};
|
|
1356
|
+
const currentGeneration = async (userId) => {
|
|
1357
|
+
const generation = await readGeneration(userId);
|
|
1358
|
+
if (generation !== INITIAL_GENERATION) await vault.putTemporary(await generationKey(userId), generation, GENERATION_TTL_MS);
|
|
1359
|
+
return generation;
|
|
1360
|
+
};
|
|
1361
|
+
const makeRoom = (userId) => {
|
|
1362
|
+
const mine = [...running].filter(([, attempt]) => attempt.userId === userId);
|
|
1363
|
+
for (const [id] of mine.slice(0, Math.max(0, mine.length - MAX_PER_USER + 1))) stop(id);
|
|
1364
|
+
};
|
|
1365
|
+
const signedOutSince = async (userId, startedUnder) => await readGeneration(userId) !== startedUnder;
|
|
1366
|
+
return {
|
|
1367
|
+
async start(userId) {
|
|
1368
|
+
makeRoom(userId);
|
|
1369
|
+
const signInId = randomToken(18);
|
|
1370
|
+
const abort = new AbortController();
|
|
1371
|
+
const record2 = (value) => vault.putTemporary(stateKey(signInId), { userId, ...value }, ATTEMPT_TTL_MS);
|
|
1372
|
+
running.set(signInId, { userId, abort });
|
|
1373
|
+
let generation;
|
|
1374
|
+
try {
|
|
1375
|
+
generation = await currentGeneration(userId);
|
|
1376
|
+
await record2({ state: "pending" });
|
|
1377
|
+
} catch (error) {
|
|
1378
|
+
running.delete(signInId);
|
|
1379
|
+
throw error;
|
|
1380
|
+
}
|
|
1381
|
+
const expiry = setTimeout(() => stop(signInId), ATTEMPT_TTL_MS);
|
|
1382
|
+
if (typeof expiry === "object") expiry.unref?.();
|
|
1383
|
+
let resolveUrl = () => void 0;
|
|
1384
|
+
const urlReady = new Promise((resolve) => {
|
|
1385
|
+
resolveUrl = resolve;
|
|
1386
|
+
});
|
|
1387
|
+
const timer = setTimeout(() => resolveUrl(void 0), URL_WAIT_MS);
|
|
1388
|
+
let failure;
|
|
1389
|
+
const recordFailure = async (error) => {
|
|
1390
|
+
failure = error instanceof ConnectError ? error : new ConnectError("sign_in_failed", "Cursor's sign-in did not finish.", { provider: "cursor", cause: error });
|
|
1391
|
+
await record2({ state: "failed", error: failure.toJSON() }).catch(() => void 0);
|
|
1392
|
+
};
|
|
1393
|
+
void signInWithCursor({ appName: options.appName, signal: abort.signal, onLoginUrl: (url2) => resolveUrl(url2) }).then(async (credential) => {
|
|
1394
|
+
try {
|
|
1395
|
+
if (abort.signal.aborted || await signedOutSince(userId, generation)) {
|
|
1396
|
+
await recordFailure(new ConnectError("sign_in_cancelled", "The sign-in was cancelled.", { provider: "cursor" }));
|
|
1397
|
+
return;
|
|
1398
|
+
}
|
|
1399
|
+
await vault.save(userId, credential);
|
|
1400
|
+
} catch (error) {
|
|
1401
|
+
await recordFailure(error);
|
|
1402
|
+
return;
|
|
1403
|
+
}
|
|
1404
|
+
for (let attempt = 0; attempt < DONE_RECORD_TRIES; attempt += 1) {
|
|
1405
|
+
try {
|
|
1406
|
+
await record2({ state: "done" });
|
|
1407
|
+
return;
|
|
1408
|
+
} catch {
|
|
1409
|
+
}
|
|
1410
|
+
}
|
|
1411
|
+
}, recordFailure).catch(() => void 0).finally(() => {
|
|
1412
|
+
running.delete(signInId);
|
|
1413
|
+
clearTimeout(timer);
|
|
1414
|
+
clearTimeout(expiry);
|
|
1415
|
+
resolveUrl(void 0);
|
|
1416
|
+
});
|
|
1417
|
+
const url = await urlReady;
|
|
1418
|
+
clearTimeout(timer);
|
|
1419
|
+
if (!url) {
|
|
1420
|
+
stop(signInId);
|
|
1421
|
+
await vault.deleteTemporary(stateKey(signInId));
|
|
1422
|
+
throw failure ?? new ConnectError("provider_unavailable", "Cursor did not start a sign-in.", { provider: "cursor", retryable: true });
|
|
1423
|
+
}
|
|
1424
|
+
return { signInId, url };
|
|
1425
|
+
},
|
|
1426
|
+
async cancel(userId) {
|
|
1427
|
+
for (const [id, attempt] of running) if (attempt.userId === userId) stop(id);
|
|
1428
|
+
await vault.putTemporary(await generationKey(userId), randomToken(12), GENERATION_TTL_MS);
|
|
1429
|
+
},
|
|
1430
|
+
async status(userId, signInId) {
|
|
1431
|
+
const stored = await vault.readTemporary(stateKey(signInId));
|
|
1432
|
+
if (!stored || stored.userId !== userId) return null;
|
|
1433
|
+
return { state: stored.state, ...stored.error ? { error: stored.error } : {} };
|
|
1434
|
+
}
|
|
1435
|
+
};
|
|
1436
|
+
}
|
|
1437
|
+
|
|
1438
|
+
// src/connect/handler.ts
|
|
1439
|
+
function json(body2, status = 200) {
|
|
1440
|
+
return new Response(JSON.stringify(body2), { status, headers: { "Content-Type": "application/json", "Cache-Control": "no-store" } });
|
|
1441
|
+
}
|
|
1442
|
+
var ERROR_STATUS = {
|
|
1443
|
+
not_signed_in: 401,
|
|
1444
|
+
sign_in_required: 401,
|
|
1445
|
+
plan_not_eligible: 403,
|
|
1446
|
+
plan_usage_disabled: 403,
|
|
1447
|
+
usage_limit: 429,
|
|
1448
|
+
provider_unavailable: 503,
|
|
1449
|
+
invalid_request: 400,
|
|
1450
|
+
invalid_credential: 400,
|
|
1451
|
+
unsupported_request: 400,
|
|
1452
|
+
sign_in_failed: 400,
|
|
1453
|
+
sign_in_cancelled: 400,
|
|
1454
|
+
cancelled: 499
|
|
1455
|
+
};
|
|
1456
|
+
function publicError(error, exposeDetails) {
|
|
1457
|
+
const connectError = error instanceof ConnectError ? error : new ConnectError("provider_error", "Something went wrong.", { cause: error });
|
|
1458
|
+
const body2 = connectError.toJSON();
|
|
1459
|
+
return connectError.code === "provider_error" && !exposeDetails ? { ...body2, message: "The AI provider returned an error." } : body2;
|
|
1460
|
+
}
|
|
1461
|
+
function errorResponse(error, exposeDetails) {
|
|
1462
|
+
const code = error instanceof ConnectError ? error.code : "provider_error";
|
|
1463
|
+
return json({ error: publicError(error, exposeDetails) }, ERROR_STATUS[code] ?? 502);
|
|
1464
|
+
}
|
|
1465
|
+
var codexSignInKey = (signInId) => `codex-signin/${signInId}`;
|
|
1466
|
+
async function body(request) {
|
|
1467
|
+
try {
|
|
1468
|
+
const value = await request.json();
|
|
1469
|
+
return typeof value === "object" && value !== null ? value : {};
|
|
1470
|
+
} catch {
|
|
1471
|
+
return {};
|
|
1472
|
+
}
|
|
1473
|
+
}
|
|
1474
|
+
function record(value) {
|
|
1475
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
|
|
1476
|
+
}
|
|
1477
|
+
function text(value) {
|
|
1478
|
+
return typeof value === "string" && value ? value : void 0;
|
|
1479
|
+
}
|
|
1480
|
+
function requestFromBody(input, signal) {
|
|
1481
|
+
if (!isConnectProviderId(input.provider)) throw unknownProviderError();
|
|
1482
|
+
const format = record(input.responseFormat);
|
|
1483
|
+
const rawParams = record(input.cursor)?.params;
|
|
1484
|
+
const params = Array.isArray(rawParams) ? rawParams.map((param) => record(param)).filter((param) => typeof param?.id === "string" && typeof param?.value === "string").map((param) => ({ id: param.id, value: param.value })) : void 0;
|
|
1485
|
+
return {
|
|
1486
|
+
provider: input.provider,
|
|
1487
|
+
...text(input.model) ? { model: text(input.model) } : {},
|
|
1488
|
+
...text(input.instructions) ? { instructions: text(input.instructions) } : {},
|
|
1489
|
+
...typeof input.prompt === "string" ? { prompt: input.prompt } : {},
|
|
1490
|
+
...Array.isArray(input.messages) ? { messages: input.messages } : {},
|
|
1491
|
+
...text(input.effort) ? { effort: text(input.effort) } : {},
|
|
1492
|
+
...format && typeof format.type === "string" ? { responseFormat: format } : {},
|
|
1493
|
+
...input.rawEvents === true ? { rawEvents: true } : {},
|
|
1494
|
+
...params ? { cursor: { params } } : {},
|
|
1495
|
+
signal
|
|
1496
|
+
};
|
|
1497
|
+
}
|
|
1498
|
+
function donePayload(event, exposeDetails) {
|
|
1499
|
+
return {
|
|
1500
|
+
text: event?.text ?? "",
|
|
1501
|
+
...event?.model ? { model: event.model } : {},
|
|
1502
|
+
...event?.usage === void 0 ? {} : { usage: event.usage },
|
|
1503
|
+
...exposeDetails && event?.response !== void 0 ? { response: event.response } : {}
|
|
1504
|
+
};
|
|
1505
|
+
}
|
|
1506
|
+
async function respondJson(reply, exposeDetails) {
|
|
1507
|
+
let done;
|
|
1508
|
+
let streamed = "";
|
|
1509
|
+
for await (const event of reply) {
|
|
1510
|
+
if (event.type === "text") streamed += event.delta;
|
|
1511
|
+
if (event.type === "done") done = event;
|
|
1512
|
+
}
|
|
1513
|
+
return json(donePayload(done ? { ...done, text: done.text || streamed } : void 0, exposeDetails));
|
|
1514
|
+
}
|
|
1515
|
+
async function respondStream(reply, exposeDetails, stop) {
|
|
1516
|
+
const iterator = reply[Symbol.asyncIterator]();
|
|
1517
|
+
let pending = await iterator.next();
|
|
1518
|
+
const encoder2 = new TextEncoder();
|
|
1519
|
+
const frame = (event, data) => encoder2.encode(`event: ${event}
|
|
1520
|
+
data: ${JSON.stringify(data)}
|
|
1521
|
+
|
|
1522
|
+
`);
|
|
1523
|
+
let cancelled = false;
|
|
1524
|
+
const stream = new ReadableStream({
|
|
1525
|
+
async pull(controller) {
|
|
1526
|
+
try {
|
|
1527
|
+
while (!cancelled) {
|
|
1528
|
+
const result = pending ?? await iterator.next();
|
|
1529
|
+
pending = null;
|
|
1530
|
+
if (cancelled) return;
|
|
1531
|
+
if (result.done) {
|
|
1532
|
+
controller.close();
|
|
1533
|
+
return;
|
|
1534
|
+
}
|
|
1535
|
+
const event = result.value;
|
|
1536
|
+
if (event.type === "raw" && !exposeDetails) continue;
|
|
1537
|
+
controller.enqueue(
|
|
1538
|
+
event.type === "text" ? frame("text", { delta: event.delta }) : event.type === "done" ? frame("done", donePayload(event, exposeDetails)) : frame("raw", { provider: event.provider, event: event.event })
|
|
1539
|
+
);
|
|
1540
|
+
return;
|
|
1541
|
+
}
|
|
1542
|
+
} catch (error) {
|
|
1543
|
+
if (cancelled) return;
|
|
1544
|
+
controller.enqueue(frame("error", publicError(error, exposeDetails)));
|
|
1545
|
+
controller.close();
|
|
1546
|
+
}
|
|
1547
|
+
},
|
|
1548
|
+
async cancel() {
|
|
1549
|
+
cancelled = true;
|
|
1550
|
+
stop.abort();
|
|
1551
|
+
await iterator.return?.(void 0).catch(() => void 0);
|
|
1552
|
+
}
|
|
1553
|
+
});
|
|
1554
|
+
return new Response(stream, { headers: { "Content-Type": "text/event-stream; charset=utf-8", "Cache-Control": "no-store" } });
|
|
1555
|
+
}
|
|
1556
|
+
function createConnectHandler(options) {
|
|
1557
|
+
const basePath = (options.basePath ?? "/connect").replace(/\/$/, "");
|
|
1558
|
+
const ai = options.ai ?? createConnectAI({ vault: options.vault, fetch: options.fetch });
|
|
1559
|
+
const cursorSignIns = createCursorSignIns({ vault: options.vault, appName: options.appName });
|
|
1560
|
+
const exposeDetails = options.exposeProviderDetails === true;
|
|
1561
|
+
const routes = {
|
|
1562
|
+
"GET /providers": async ({ userId }) => {
|
|
1563
|
+
const statuses = await options.vault.status(userId);
|
|
1564
|
+
return json({
|
|
1565
|
+
providers: CONNECT_PROVIDERS.map((provider) => ({
|
|
1566
|
+
...provider,
|
|
1567
|
+
status: statuses.find((status) => status.provider === provider.id) ?? signInStatus(null, provider.id)
|
|
1568
|
+
}))
|
|
1569
|
+
});
|
|
1570
|
+
},
|
|
1571
|
+
"POST /codex/start": async ({ userId }) => {
|
|
1572
|
+
const reauth = await options.vault.codexReauth(userId);
|
|
1573
|
+
const { url, pending } = await startCodexSignIn({
|
|
1574
|
+
appName: options.appName,
|
|
1575
|
+
hostId: options.hostId,
|
|
1576
|
+
...options.codexRedirectUri ? { redirectUri: options.codexRedirectUri } : {},
|
|
1577
|
+
...reauth ? { reauth } : {}
|
|
1578
|
+
});
|
|
1579
|
+
const signInId = randomToken(18);
|
|
1580
|
+
await options.vault.putTemporary(codexSignInKey(signInId), { userId, pending }, CODEX_SIGN_IN_TTL_MS);
|
|
1581
|
+
return json({ signInId, url, redirectUri: pending.redirectUri });
|
|
1582
|
+
},
|
|
1583
|
+
"POST /codex/complete": async ({ userId, request }) => {
|
|
1584
|
+
const input = await body(request);
|
|
1585
|
+
if (typeof input.signInId !== "string" || typeof input.callbackUrl !== "string") {
|
|
1586
|
+
throw new ConnectError("invalid_request", "signInId and callbackUrl are required.", { provider: "codex" });
|
|
1587
|
+
}
|
|
1588
|
+
const saved = await options.vault.readTemporary(codexSignInKey(input.signInId));
|
|
1589
|
+
if (!saved || saved.userId !== userId) {
|
|
1590
|
+
throw new ConnectError("sign_in_failed", "This sign-in expired or belongs to someone else. Start again.", { provider: "codex" });
|
|
1591
|
+
}
|
|
1592
|
+
if (callbackParams(input.callbackUrl).get("state") !== saved.pending.state) {
|
|
1593
|
+
throw new ConnectError("sign_in_failed", "That address is from a different sign-in. Paste the address this sign-in ended on.", { provider: "codex" });
|
|
1594
|
+
}
|
|
1595
|
+
await options.vault.deleteTemporary(codexSignInKey(input.signInId));
|
|
1596
|
+
const credential = await completeCodexSignIn(saved.pending, input.callbackUrl, { fetch: options.fetch });
|
|
1597
|
+
await options.vault.save(userId, credential);
|
|
1598
|
+
return json({ status: signInStatus(credential, "codex") });
|
|
1599
|
+
},
|
|
1600
|
+
"POST /codex/import": async ({ userId, request }) => {
|
|
1601
|
+
const credential = parseConnectCredential((await body(request)).credential);
|
|
1602
|
+
if (credential.provider !== "codex") throw new ConnectError("invalid_request", "Only a ChatGPT credential can be imported here.");
|
|
1603
|
+
await options.vault.save(userId, credential);
|
|
1604
|
+
return json({ status: signInStatus(credential, "codex") });
|
|
1605
|
+
},
|
|
1606
|
+
"POST /cursor/start": async ({ userId }) => json(await cursorSignIns.start(userId)),
|
|
1607
|
+
"GET /cursor/status": async ({ userId, url }) => {
|
|
1608
|
+
const state = await cursorSignIns.status(userId, url.searchParams.get("signInId") ?? "");
|
|
1609
|
+
if (!state) return json({ state: "failed", error: { code: "sign_in_failed", message: "Unknown sign-in." } }, 404);
|
|
1610
|
+
return json(state);
|
|
1611
|
+
},
|
|
1612
|
+
"GET /models": async ({ userId, url }) => {
|
|
1613
|
+
const provider = url.searchParams.get("provider");
|
|
1614
|
+
if (!isConnectProviderId(provider)) throw unknownProviderError();
|
|
1615
|
+
return json({ models: await ai.models(userId, provider) });
|
|
1616
|
+
},
|
|
1617
|
+
"POST /respond": async ({ userId, request }) => {
|
|
1618
|
+
const input = await body(request);
|
|
1619
|
+
const stop = new AbortController();
|
|
1620
|
+
const transport = AbortSignal.any([request.signal, stop.signal]);
|
|
1621
|
+
let connectRequest = requestFromBody(input, transport);
|
|
1622
|
+
if (options.prepareRequest) {
|
|
1623
|
+
const shaped = await options.prepareRequest(connectRequest, { userId, body: input, httpRequest: request });
|
|
1624
|
+
const signal = shaped.signal && shaped.signal !== transport ? AbortSignal.any([transport, shaped.signal]) : transport;
|
|
1625
|
+
connectRequest = { ...shaped, signal };
|
|
1626
|
+
}
|
|
1627
|
+
const reply = ai.respond(userId, connectRequest);
|
|
1628
|
+
return (request.headers.get("accept") ?? "").includes("application/json") ? respondJson(reply, exposeDetails) : respondStream(reply, exposeDetails, stop);
|
|
1629
|
+
},
|
|
1630
|
+
...Object.fromEntries(
|
|
1631
|
+
CONNECT_PROVIDER_IDS.map((provider) => [
|
|
1632
|
+
`POST /${provider}/sign-out`,
|
|
1633
|
+
async ({ userId }) => {
|
|
1634
|
+
if (provider === "cursor") await cursorSignIns.cancel(userId);
|
|
1635
|
+
const { revoked } = await options.vault.remove(userId, provider);
|
|
1636
|
+
return json({ ok: true, revoked });
|
|
1637
|
+
}
|
|
1638
|
+
])
|
|
1639
|
+
)
|
|
1640
|
+
};
|
|
1641
|
+
const handler = async (request) => {
|
|
1642
|
+
const url = new URL(request.url);
|
|
1643
|
+
if (url.pathname !== basePath && !url.pathname.startsWith(`${basePath}/`)) return null;
|
|
1644
|
+
const method = request.method.toUpperCase();
|
|
1645
|
+
const route = routes[`${method} ${url.pathname.slice(basePath.length) || "/"}`];
|
|
1646
|
+
try {
|
|
1647
|
+
if (method === "POST" && !(request.headers.get("content-type") ?? "").toLowerCase().startsWith("application/json")) {
|
|
1648
|
+
return json({ error: { code: "invalid_request", message: "Send Content-Type: application/json." } }, 415);
|
|
1649
|
+
}
|
|
1650
|
+
const userId = await options.getUserId(request);
|
|
1651
|
+
if (!userId) return json({ error: { code: "unauthorized", message: "Sign in to the app first." } }, 401);
|
|
1652
|
+
if (!route) return json({ error: { code: "not_found", message: "Unknown connect route." } }, 404);
|
|
1653
|
+
return await route({ userId, request, url });
|
|
1654
|
+
} catch (error) {
|
|
1655
|
+
return errorResponse(error, exposeDetails);
|
|
1656
|
+
}
|
|
1657
|
+
};
|
|
1658
|
+
return Object.assign(handler, { basePath });
|
|
1659
|
+
}
|
|
1660
|
+
|
|
1661
|
+
// src/connect/nodeAdapter.ts
|
|
1662
|
+
import { once } from "events";
|
|
1663
|
+
var BodyTooLarge = class extends Error {
|
|
1664
|
+
};
|
|
1665
|
+
function readBody(req, maxBytes) {
|
|
1666
|
+
if (req.body !== void 0 && req.readableEnded) {
|
|
1667
|
+
if (typeof req.body === "string") return Promise.resolve(req.body);
|
|
1668
|
+
if (req.body instanceof Uint8Array) return Promise.resolve(req.body);
|
|
1669
|
+
return Promise.resolve(JSON.stringify(req.body));
|
|
1670
|
+
}
|
|
1671
|
+
return new Promise((resolve, reject) => {
|
|
1672
|
+
const chunks = [];
|
|
1673
|
+
let size = 0;
|
|
1674
|
+
let tooLarge = false;
|
|
1675
|
+
req.on("data", (chunk) => {
|
|
1676
|
+
if (tooLarge) return;
|
|
1677
|
+
const bytes = typeof chunk === "string" ? new TextEncoder().encode(chunk) : chunk;
|
|
1678
|
+
size += bytes.byteLength;
|
|
1679
|
+
if (size > maxBytes) {
|
|
1680
|
+
tooLarge = true;
|
|
1681
|
+
chunks.length = 0;
|
|
1682
|
+
reject(new BodyTooLarge());
|
|
1683
|
+
return;
|
|
1684
|
+
}
|
|
1685
|
+
chunks.push(bytes);
|
|
1686
|
+
});
|
|
1687
|
+
req.on("end", () => {
|
|
1688
|
+
if (tooLarge) return;
|
|
1689
|
+
const body2 = new Uint8Array(size);
|
|
1690
|
+
let offset = 0;
|
|
1691
|
+
for (const chunk of chunks) {
|
|
1692
|
+
body2.set(chunk, offset);
|
|
1693
|
+
offset += chunk.byteLength;
|
|
1694
|
+
}
|
|
1695
|
+
resolve(body2);
|
|
1696
|
+
});
|
|
1697
|
+
req.on("error", reject);
|
|
1698
|
+
});
|
|
1699
|
+
}
|
|
1700
|
+
function pathnameOf(path) {
|
|
1701
|
+
try {
|
|
1702
|
+
return new URL(path, "http://localhost").pathname;
|
|
1703
|
+
} catch {
|
|
1704
|
+
return null;
|
|
1705
|
+
}
|
|
1706
|
+
}
|
|
1707
|
+
function toNodeListener(handler, options = {}) {
|
|
1708
|
+
const maxBytes = options.maxBodyBytes ?? 1024 * 1024;
|
|
1709
|
+
return async (req, res, next) => {
|
|
1710
|
+
const pass = () => next ? next() : void res.writeHead(404).end();
|
|
1711
|
+
const inBase = (candidate) => {
|
|
1712
|
+
const pathname = candidate === void 0 ? null : pathnameOf(candidate);
|
|
1713
|
+
return pathname !== null && (pathname === handler.basePath || pathname.startsWith(`${handler.basePath}/`));
|
|
1714
|
+
};
|
|
1715
|
+
const path = [req.originalUrl, req.url].find(inBase);
|
|
1716
|
+
if (!path) {
|
|
1717
|
+
pass();
|
|
1718
|
+
return;
|
|
1719
|
+
}
|
|
1720
|
+
let reader = null;
|
|
1721
|
+
let finished = false;
|
|
1722
|
+
try {
|
|
1723
|
+
const host = req.headers.host ?? "localhost";
|
|
1724
|
+
const protocol = req.socket.encrypted ? "https" : "http";
|
|
1725
|
+
const headers = new Headers();
|
|
1726
|
+
for (const [name, value] of Object.entries(req.headers)) {
|
|
1727
|
+
if (Array.isArray(value)) value.forEach((item) => headers.append(name, item));
|
|
1728
|
+
else if (typeof value === "string") headers.set(name, value);
|
|
1729
|
+
}
|
|
1730
|
+
const abort = new AbortController();
|
|
1731
|
+
res.on("close", () => {
|
|
1732
|
+
if (res.writableFinished) return;
|
|
1733
|
+
abort.abort();
|
|
1734
|
+
void reader?.cancel().catch(() => void 0);
|
|
1735
|
+
});
|
|
1736
|
+
const method = req.method ?? "GET";
|
|
1737
|
+
const body2 = method === "GET" || method === "HEAD" ? void 0 : await readBody(req, maxBytes);
|
|
1738
|
+
const request = new Request(`${protocol}://${host}${path}`, {
|
|
1739
|
+
method,
|
|
1740
|
+
headers,
|
|
1741
|
+
signal: abort.signal,
|
|
1742
|
+
...body2 !== void 0 ? { body: body2 } : {}
|
|
1743
|
+
});
|
|
1744
|
+
const response = await handler(request);
|
|
1745
|
+
if (!response) {
|
|
1746
|
+
pass();
|
|
1747
|
+
return;
|
|
1748
|
+
}
|
|
1749
|
+
res.writeHead(response.status, Object.fromEntries(response.headers.entries()));
|
|
1750
|
+
if (!response.body) {
|
|
1751
|
+
res.end();
|
|
1752
|
+
return;
|
|
1753
|
+
}
|
|
1754
|
+
reader = response.body.getReader();
|
|
1755
|
+
while (!res.destroyed) {
|
|
1756
|
+
const { value, done } = await reader.read();
|
|
1757
|
+
if (done) {
|
|
1758
|
+
finished = true;
|
|
1759
|
+
break;
|
|
1760
|
+
}
|
|
1761
|
+
if (!res.write(value)) {
|
|
1762
|
+
const waiting = new AbortController();
|
|
1763
|
+
await Promise.race([once(res, "drain", { signal: waiting.signal }), once(res, "close", { signal: waiting.signal })]);
|
|
1764
|
+
waiting.abort();
|
|
1765
|
+
}
|
|
1766
|
+
}
|
|
1767
|
+
res.end();
|
|
1768
|
+
} catch (error) {
|
|
1769
|
+
if (error instanceof BodyTooLarge) {
|
|
1770
|
+
if (!res.headersSent) res.writeHead(413, { "Content-Type": "application/json", Connection: "close" });
|
|
1771
|
+
res.end(JSON.stringify({ error: { code: "invalid_request", message: "The request body is too large." } }));
|
|
1772
|
+
return;
|
|
1773
|
+
}
|
|
1774
|
+
if (next) next(error);
|
|
1775
|
+
else if (!res.headersSent) res.writeHead(500).end();
|
|
1776
|
+
else res.end();
|
|
1777
|
+
} finally {
|
|
1778
|
+
if (reader && !finished) await reader.cancel().catch(() => void 0);
|
|
1779
|
+
reader?.releaseLock();
|
|
1780
|
+
}
|
|
1781
|
+
};
|
|
1782
|
+
}
|
|
1783
|
+
|
|
1784
|
+
// src/connect/codexLoopback.ts
|
|
1785
|
+
var DONE_PAGE = `<!doctype html><meta charset="utf-8"><title>Signed in</title>
|
|
1786
|
+
<body style="font-family:system-ui;padding:3rem;text-align:center"><h1>You're signed in</h1><p>You can close this tab.</p></body>`;
|
|
1787
|
+
var FAILED_PAGE = `<!doctype html><meta charset="utf-8"><title>Sign-in failed</title>
|
|
1788
|
+
<body style="font-family:system-ui;padding:3rem;text-align:center"><h1>Sign-in didn't finish</h1><p>Go back to the app and try again.</p></body>`;
|
|
1789
|
+
async function signInWithCodexOnThisDevice(options) {
|
|
1790
|
+
const cancelled = () => new ConnectError("sign_in_cancelled", "The sign-in was cancelled.", { provider: "codex" });
|
|
1791
|
+
if (options.signal?.aborted) throw cancelled();
|
|
1792
|
+
const http = await import("http");
|
|
1793
|
+
const server = http.createServer();
|
|
1794
|
+
const listen = (port2) => new Promise((resolve, reject) => {
|
|
1795
|
+
const onError = (error) => {
|
|
1796
|
+
server.off("listening", onListening);
|
|
1797
|
+
reject(error);
|
|
1798
|
+
};
|
|
1799
|
+
const onListening = () => {
|
|
1800
|
+
server.off("error", onError);
|
|
1801
|
+
resolve(server.address().port);
|
|
1802
|
+
};
|
|
1803
|
+
server.once("error", onError);
|
|
1804
|
+
server.once("listening", onListening);
|
|
1805
|
+
server.listen(port2, "127.0.0.1");
|
|
1806
|
+
});
|
|
1807
|
+
let port;
|
|
1808
|
+
try {
|
|
1809
|
+
port = await listen(options.port ?? 1455);
|
|
1810
|
+
} catch {
|
|
1811
|
+
port = await listen(0);
|
|
1812
|
+
}
|
|
1813
|
+
try {
|
|
1814
|
+
const { url, pending } = await startCodexSignIn({ ...options, redirectUri: `http://127.0.0.1:${port}/auth/callback` });
|
|
1815
|
+
const callback = await new Promise((resolve, reject) => {
|
|
1816
|
+
const timeout = setTimeout(
|
|
1817
|
+
() => reject(new ConnectError("sign_in_failed", "The sign-in timed out.", { provider: "codex" })),
|
|
1818
|
+
options.timeoutMs ?? 10 * 60 * 1e3
|
|
1819
|
+
);
|
|
1820
|
+
timeout.unref?.();
|
|
1821
|
+
const onAbort = () => reject(cancelled());
|
|
1822
|
+
options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
1823
|
+
server.on("request", (req, res) => {
|
|
1824
|
+
let requestUrl;
|
|
1825
|
+
try {
|
|
1826
|
+
requestUrl = new URL(req.url ?? "/", `http://127.0.0.1:${port}`);
|
|
1827
|
+
} catch {
|
|
1828
|
+
res.writeHead(400).end();
|
|
1829
|
+
return;
|
|
1830
|
+
}
|
|
1831
|
+
if (requestUrl.pathname !== "/auth/callback") {
|
|
1832
|
+
res.writeHead(404).end();
|
|
1833
|
+
return;
|
|
1834
|
+
}
|
|
1835
|
+
if (requestUrl.searchParams.get("state") !== pending.state) {
|
|
1836
|
+
res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" }).end(FAILED_PAGE);
|
|
1837
|
+
return;
|
|
1838
|
+
}
|
|
1839
|
+
const ok = !requestUrl.searchParams.get("error") && requestUrl.searchParams.get("code");
|
|
1840
|
+
res.writeHead(ok ? 200 : 400, { "Content-Type": "text/html; charset=utf-8" }).end(ok ? DONE_PAGE : FAILED_PAGE);
|
|
1841
|
+
clearTimeout(timeout);
|
|
1842
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
1843
|
+
resolve(requestUrl);
|
|
1844
|
+
});
|
|
1845
|
+
options.onUrl?.(url);
|
|
1846
|
+
if (options.openBrowser) {
|
|
1847
|
+
void Promise.resolve(options.openBrowser(url)).catch(() => {
|
|
1848
|
+
});
|
|
1849
|
+
}
|
|
1850
|
+
});
|
|
1851
|
+
return await completeCodexSignIn(pending, callback, { fetch: options.fetch, signal: options.signal });
|
|
1852
|
+
} finally {
|
|
1853
|
+
server.close();
|
|
1854
|
+
server.closeAllConnections?.();
|
|
1855
|
+
}
|
|
1856
|
+
}
|
|
1857
|
+
export {
|
|
1858
|
+
CODEX_DEFAULT_REDIRECT_URI,
|
|
1859
|
+
CODEX_SIGN_IN_TTL_MS,
|
|
1860
|
+
CONNECT_ERROR_CODES,
|
|
1861
|
+
CONNECT_PROVIDERS,
|
|
1862
|
+
CONNECT_PROVIDER_IDS,
|
|
1863
|
+
ConnectError,
|
|
1864
|
+
cancelledError,
|
|
1865
|
+
completeCodexSignIn,
|
|
1866
|
+
connectProvider,
|
|
1867
|
+
createConnectAI,
|
|
1868
|
+
createConnectHandler,
|
|
1869
|
+
createConnectVault,
|
|
1870
|
+
isConnectError,
|
|
1871
|
+
isConnectProviderId,
|
|
1872
|
+
isCursorUsable,
|
|
1873
|
+
listCodexModels,
|
|
1874
|
+
listCursorModels,
|
|
1875
|
+
memoryStorage,
|
|
1876
|
+
newCodexHostId,
|
|
1877
|
+
parseConnectCredential,
|
|
1878
|
+
provideCursorSdk,
|
|
1879
|
+
refreshCodexCredential,
|
|
1880
|
+
revokeCodexCredential,
|
|
1881
|
+
signInStatus,
|
|
1882
|
+
signInWithCodexOnThisDevice,
|
|
1883
|
+
signInWithCursor,
|
|
1884
|
+
startCodexSignIn,
|
|
1885
|
+
streamCodexResponse,
|
|
1886
|
+
streamCursorResponse,
|
|
1887
|
+
toNodeListener
|
|
1888
|
+
};
|