@eum-agent/llm-provider-chatgpt 0.0.0-stage → 1.2.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/assets/NOTICE +28 -0
- package/assets/chatgpt.svg +1 -0
- package/dist/index.js +2338 -0
- package/package.json +42 -3
- package/README.md +0 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,2338 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
3
|
+
import { setImmediate, setTimeout } from "node:timers/promises";
|
|
4
|
+
import { createServer } from "node:http";
|
|
5
|
+
//#region src/failure.ts
|
|
6
|
+
var LoginFailure = class extends Error {
|
|
7
|
+
name = "LoginFailure";
|
|
8
|
+
code;
|
|
9
|
+
detail;
|
|
10
|
+
constructor(code, detail = null) {
|
|
11
|
+
super(detail === null ? `sign-in ${code}` : `sign-in ${code} (${detail})`);
|
|
12
|
+
this.code = code;
|
|
13
|
+
this.detail = detail;
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
//#endregion
|
|
17
|
+
//#region src/oauth.ts
|
|
18
|
+
const CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";
|
|
19
|
+
const ORIGINATOR = "yaoguang";
|
|
20
|
+
const CALLBACK_PATH = "/auth/callback";
|
|
21
|
+
const CODEX_CLIENT_VERSION = "1.0.0";
|
|
22
|
+
const ACCEPTED_EFFORTS = [
|
|
23
|
+
"none",
|
|
24
|
+
"minimal",
|
|
25
|
+
"low",
|
|
26
|
+
"medium",
|
|
27
|
+
"high",
|
|
28
|
+
"xhigh",
|
|
29
|
+
"max"
|
|
30
|
+
];
|
|
31
|
+
const SCOPE = "openid profile email offline_access";
|
|
32
|
+
const REQUEST_TIMEOUT_MS = 3e4;
|
|
33
|
+
const REFRESH_AHEAD_MS = 6e4;
|
|
34
|
+
const ENDPOINTS = {
|
|
35
|
+
issuer: "https://auth.openai.com",
|
|
36
|
+
codex: "https://chatgpt.com/backend-api/codex"
|
|
37
|
+
};
|
|
38
|
+
function pkce() {
|
|
39
|
+
const verifier = randomBytes(48).toString("base64url");
|
|
40
|
+
return {
|
|
41
|
+
verifier,
|
|
42
|
+
challenge: createHash("sha256").update(verifier).digest("base64url")
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
function newState() {
|
|
46
|
+
return randomBytes(32).toString("base64url");
|
|
47
|
+
}
|
|
48
|
+
function authorizeUrl(endpoints, redirectUri, codes, state) {
|
|
49
|
+
const params = new URLSearchParams({
|
|
50
|
+
response_type: "code",
|
|
51
|
+
client_id: CLIENT_ID,
|
|
52
|
+
redirect_uri: redirectUri,
|
|
53
|
+
scope: SCOPE,
|
|
54
|
+
code_challenge: codes.challenge,
|
|
55
|
+
code_challenge_method: "S256",
|
|
56
|
+
id_token_add_organizations: "true",
|
|
57
|
+
codex_cli_simplified_flow: "true",
|
|
58
|
+
state,
|
|
59
|
+
originator: ORIGINATOR
|
|
60
|
+
});
|
|
61
|
+
return `${endpoints.issuer}/oauth/authorize?${params.toString()}`;
|
|
62
|
+
}
|
|
63
|
+
function claimsOf(jwt) {
|
|
64
|
+
if (typeof jwt !== "string") return void 0;
|
|
65
|
+
const payload = jwt.split(".")[1];
|
|
66
|
+
if (payload === void 0) return void 0;
|
|
67
|
+
try {
|
|
68
|
+
const parsed = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
|
|
69
|
+
return typeof parsed === "object" && parsed !== null ? parsed : void 0;
|
|
70
|
+
} catch {
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
function authClaim(claims, key) {
|
|
75
|
+
const nested = claims?.["https://api.openai.com/auth"];
|
|
76
|
+
const value = (typeof nested === "object" && nested !== null ? nested[key] : void 0) ?? claims?.[key];
|
|
77
|
+
return typeof value === "string" && value !== "" ? value : void 0;
|
|
78
|
+
}
|
|
79
|
+
function accountLabel(email, accountId) {
|
|
80
|
+
return email ?? `\u00b7\u00b7\u00b7\u00b7${accountId.slice(-4)}`;
|
|
81
|
+
}
|
|
82
|
+
function storedFrom(body, now, before) {
|
|
83
|
+
const access = body.access_token;
|
|
84
|
+
const refresh = body.refresh_token ?? before?.refresh;
|
|
85
|
+
if (typeof access !== "string" || typeof refresh !== "string") return void 0;
|
|
86
|
+
const id = claimsOf(body.id_token);
|
|
87
|
+
const accessClaims = claimsOf(access);
|
|
88
|
+
const accountId = authClaim(id, "chatgpt_account_id") ?? authClaim(accessClaims, "chatgpt_account_id") ?? before?.accountId;
|
|
89
|
+
if (accountId === void 0) return void 0;
|
|
90
|
+
const email = typeof id?.email === "string" ? id.email : void 0;
|
|
91
|
+
const expiresIn = typeof body.expires_in === "number" ? body.expires_in : 3600;
|
|
92
|
+
const earliest = typeof body.earliest_refresh_at === "number" ? body.earliest_refresh_at * 1e3 : void 0;
|
|
93
|
+
const residency = authClaim(accessClaims, "chatgpt_compute_residency");
|
|
94
|
+
return {
|
|
95
|
+
access,
|
|
96
|
+
refresh,
|
|
97
|
+
expiresAt: String(now + expiresIn * 1e3),
|
|
98
|
+
...earliest === void 0 ? {} : { earliestRefreshAt: String(earliest) },
|
|
99
|
+
accountId,
|
|
100
|
+
account: email === void 0 && before !== void 0 ? before.account : accountLabel(email, accountId),
|
|
101
|
+
...residency === void 0 || residency === "no_constraint" ? {} : { residency }
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
function parseStored(credential) {
|
|
105
|
+
if (credential === void 0) return void 0;
|
|
106
|
+
try {
|
|
107
|
+
const parsed = JSON.parse(credential);
|
|
108
|
+
return typeof parsed.access === "string" && typeof parsed.refresh === "string" && typeof parsed.expiresAt === "string" && typeof parsed.accountId === "string" && typeof parsed.account === "string" ? parsed : void 0;
|
|
109
|
+
} catch {
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
function refreshAfterOf(tokens) {
|
|
114
|
+
const expiresAt = Number(tokens.expiresAt) - REFRESH_AHEAD_MS;
|
|
115
|
+
const earliest = tokens.earliestRefreshAt === void 0 ? expiresAt : Number(tokens.earliestRefreshAt);
|
|
116
|
+
return Math.min(expiresAt, earliest);
|
|
117
|
+
}
|
|
118
|
+
async function postForm(fetch, url, form, signal) {
|
|
119
|
+
return fetch(url, {
|
|
120
|
+
method: "POST",
|
|
121
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
122
|
+
body: new URLSearchParams(form).toString(),
|
|
123
|
+
signal: signal === void 0 ? AbortSignal.timeout(REQUEST_TIMEOUT_MS) : AbortSignal.any([signal, AbortSignal.timeout(REQUEST_TIMEOUT_MS)])
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
async function exchangeCode(fetch, endpoints, input, now, signal) {
|
|
127
|
+
let response;
|
|
128
|
+
try {
|
|
129
|
+
response = await postForm(fetch, `${endpoints.issuer}/oauth/token`, {
|
|
130
|
+
grant_type: "authorization_code",
|
|
131
|
+
code: input.code,
|
|
132
|
+
redirect_uri: input.redirectUri,
|
|
133
|
+
client_id: CLIENT_ID,
|
|
134
|
+
code_verifier: input.verifier
|
|
135
|
+
}, signal);
|
|
136
|
+
} catch {
|
|
137
|
+
throw new LoginFailure("exchange-failed", "unreachable");
|
|
138
|
+
}
|
|
139
|
+
if (!response.ok) throw new LoginFailure("exchange-failed", `HTTP ${String(response.status)}`);
|
|
140
|
+
const stored = storedFrom(await response.json().catch(() => ({})), now());
|
|
141
|
+
if (stored === void 0) throw new LoginFailure("exchange-failed", "unreadable answer");
|
|
142
|
+
return stored;
|
|
143
|
+
}
|
|
144
|
+
async function refreshTokens(fetch, endpoints, before, now, signal) {
|
|
145
|
+
let response;
|
|
146
|
+
try {
|
|
147
|
+
response = await postForm(fetch, `${endpoints.issuer}/oauth/token`, {
|
|
148
|
+
grant_type: "refresh_token",
|
|
149
|
+
refresh_token: before.refresh,
|
|
150
|
+
client_id: CLIENT_ID
|
|
151
|
+
}, signal);
|
|
152
|
+
} catch {
|
|
153
|
+
if (signal?.aborted) throw new LoginFailure("cancelled");
|
|
154
|
+
return {
|
|
155
|
+
kind: "failed",
|
|
156
|
+
detail: "unreachable"
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
if (response.status === 400 || response.status === 401) return { kind: "refused" };
|
|
160
|
+
if (!response.ok) return {
|
|
161
|
+
kind: "failed",
|
|
162
|
+
detail: `HTTP ${String(response.status)}`
|
|
163
|
+
};
|
|
164
|
+
const tokens = storedFrom(await response.json().catch(() => ({})), now(), before);
|
|
165
|
+
return tokens === void 0 ? {
|
|
166
|
+
kind: "failed",
|
|
167
|
+
detail: "unreadable answer"
|
|
168
|
+
} : {
|
|
169
|
+
kind: "ok",
|
|
170
|
+
tokens
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
//#endregion
|
|
174
|
+
//#region src/subscription-models.json
|
|
175
|
+
var verifiedAt$1 = "2026-10-29";
|
|
176
|
+
var models = [
|
|
177
|
+
{
|
|
178
|
+
"model": "gpt-6-astra",
|
|
179
|
+
"name": "GPT-6-Astra",
|
|
180
|
+
"context": 272e3,
|
|
181
|
+
"inputModalities": ["text", "image"],
|
|
182
|
+
"efforts": [
|
|
183
|
+
"low",
|
|
184
|
+
"medium",
|
|
185
|
+
"high",
|
|
186
|
+
"xhigh",
|
|
187
|
+
"max",
|
|
188
|
+
"ultra"
|
|
189
|
+
],
|
|
190
|
+
"family": "gpt-astra",
|
|
191
|
+
"releaseDate": "2026-09-03",
|
|
192
|
+
"releaseDateSource": "https://developers.openai.com/api/docs/changelog",
|
|
193
|
+
"supportsParallelToolCalls": true
|
|
194
|
+
},
|
|
195
|
+
{
|
|
196
|
+
"model": "gpt-6.1-sol",
|
|
197
|
+
"name": "GPT-6.1-Sol",
|
|
198
|
+
"context": 5e5,
|
|
199
|
+
"inputModalities": ["text", "image"],
|
|
200
|
+
"efforts": [
|
|
201
|
+
"low",
|
|
202
|
+
"medium",
|
|
203
|
+
"high",
|
|
204
|
+
"xhigh",
|
|
205
|
+
"max",
|
|
206
|
+
"ultra"
|
|
207
|
+
],
|
|
208
|
+
"contextSource": "https://developers.openai.com/api/docs/models/gpt-6.1-sol",
|
|
209
|
+
"bundledContext": 272e3,
|
|
210
|
+
"family": "gpt-sol",
|
|
211
|
+
"releaseDate": "2026-09-29",
|
|
212
|
+
"releaseDateSource": "https://developers.openai.com/api/docs/changelog",
|
|
213
|
+
"supportsParallelToolCalls": true
|
|
214
|
+
},
|
|
215
|
+
{
|
|
216
|
+
"model": "gpt-6.1-terra",
|
|
217
|
+
"name": "GPT-6.1 Terra",
|
|
218
|
+
"context": 5e5,
|
|
219
|
+
"inputModalities": ["text", "image"],
|
|
220
|
+
"efforts": [
|
|
221
|
+
"low",
|
|
222
|
+
"medium",
|
|
223
|
+
"high",
|
|
224
|
+
"xhigh",
|
|
225
|
+
"max",
|
|
226
|
+
"ultra"
|
|
227
|
+
],
|
|
228
|
+
"family": "gpt-terra",
|
|
229
|
+
"releaseDate": "2026-10-26",
|
|
230
|
+
"releaseDateSource": "https://developers.openai.com/api/docs/changelog",
|
|
231
|
+
"supportsParallelToolCalls": true
|
|
232
|
+
},
|
|
233
|
+
{
|
|
234
|
+
"model": "gpt-6-sol",
|
|
235
|
+
"name": "GPT-6-Sol",
|
|
236
|
+
"context": 272e3,
|
|
237
|
+
"inputModalities": ["text", "image"],
|
|
238
|
+
"efforts": [
|
|
239
|
+
"low",
|
|
240
|
+
"medium",
|
|
241
|
+
"high",
|
|
242
|
+
"xhigh",
|
|
243
|
+
"max",
|
|
244
|
+
"ultra"
|
|
245
|
+
],
|
|
246
|
+
"family": "gpt-sol",
|
|
247
|
+
"releaseDate": "2026-09-22",
|
|
248
|
+
"releaseDateSource": "https://developers.openai.com/api/docs/changelog",
|
|
249
|
+
"supportsParallelToolCalls": true
|
|
250
|
+
},
|
|
251
|
+
{
|
|
252
|
+
"model": "gpt-6-luna",
|
|
253
|
+
"name": "GPT-6-Luna",
|
|
254
|
+
"context": 272e3,
|
|
255
|
+
"inputModalities": ["text", "image"],
|
|
256
|
+
"efforts": [
|
|
257
|
+
"low",
|
|
258
|
+
"medium",
|
|
259
|
+
"high",
|
|
260
|
+
"xhigh",
|
|
261
|
+
"max"
|
|
262
|
+
],
|
|
263
|
+
"family": "gpt-luna",
|
|
264
|
+
"releaseDate": "2026-09-22",
|
|
265
|
+
"releaseDateSource": "https://developers.openai.com/api/docs/changelog",
|
|
266
|
+
"supportsParallelToolCalls": true
|
|
267
|
+
},
|
|
268
|
+
{
|
|
269
|
+
"model": "gpt-5.6-sol",
|
|
270
|
+
"name": "GPT-5.6-Sol",
|
|
271
|
+
"context": 272e3,
|
|
272
|
+
"inputModalities": ["text", "image"],
|
|
273
|
+
"efforts": [
|
|
274
|
+
"low",
|
|
275
|
+
"medium",
|
|
276
|
+
"high",
|
|
277
|
+
"xhigh",
|
|
278
|
+
"max",
|
|
279
|
+
"ultra"
|
|
280
|
+
],
|
|
281
|
+
"family": "gpt-sol",
|
|
282
|
+
"releaseDate": "2026-07-09",
|
|
283
|
+
"releaseDateSource": "https://developers.openai.com/api/docs/changelog",
|
|
284
|
+
"supportsParallelToolCalls": true
|
|
285
|
+
},
|
|
286
|
+
{
|
|
287
|
+
"model": "gpt-5.6-terra",
|
|
288
|
+
"name": "GPT-5.6-Terra",
|
|
289
|
+
"context": 272e3,
|
|
290
|
+
"inputModalities": ["text", "image"],
|
|
291
|
+
"efforts": [
|
|
292
|
+
"low",
|
|
293
|
+
"medium",
|
|
294
|
+
"high",
|
|
295
|
+
"xhigh",
|
|
296
|
+
"max",
|
|
297
|
+
"ultra"
|
|
298
|
+
],
|
|
299
|
+
"family": "gpt-terra",
|
|
300
|
+
"releaseDate": "2026-07-09",
|
|
301
|
+
"releaseDateSource": "https://developers.openai.com/api/docs/changelog",
|
|
302
|
+
"supportsParallelToolCalls": true
|
|
303
|
+
},
|
|
304
|
+
{
|
|
305
|
+
"model": "gpt-5.6-luna",
|
|
306
|
+
"name": "GPT-5.6-Luna",
|
|
307
|
+
"context": 272e3,
|
|
308
|
+
"inputModalities": ["text", "image"],
|
|
309
|
+
"efforts": [
|
|
310
|
+
"low",
|
|
311
|
+
"medium",
|
|
312
|
+
"high",
|
|
313
|
+
"xhigh",
|
|
314
|
+
"max"
|
|
315
|
+
],
|
|
316
|
+
"family": "gpt-luna",
|
|
317
|
+
"releaseDate": "2026-07-09",
|
|
318
|
+
"releaseDateSource": "https://developers.openai.com/api/docs/changelog",
|
|
319
|
+
"supportsParallelToolCalls": true
|
|
320
|
+
},
|
|
321
|
+
{
|
|
322
|
+
"model": "gpt-5.5",
|
|
323
|
+
"name": "GPT-5.5",
|
|
324
|
+
"context": 272e3,
|
|
325
|
+
"inputModalities": ["text", "image"],
|
|
326
|
+
"efforts": [
|
|
327
|
+
"low",
|
|
328
|
+
"medium",
|
|
329
|
+
"high",
|
|
330
|
+
"xhigh"
|
|
331
|
+
],
|
|
332
|
+
"family": "gpt",
|
|
333
|
+
"releaseDate": "2026-04-24",
|
|
334
|
+
"releaseDateSource": "https://developers.openai.com/api/docs/changelog",
|
|
335
|
+
"supportsParallelToolCalls": true
|
|
336
|
+
}
|
|
337
|
+
];
|
|
338
|
+
//#endregion
|
|
339
|
+
//#region src/facts.ts
|
|
340
|
+
const facts = {
|
|
341
|
+
outputLimit: { support: "unsupported" },
|
|
342
|
+
temperature: null,
|
|
343
|
+
thinkingSwitch: false,
|
|
344
|
+
limits: {
|
|
345
|
+
requestBytes: 50331648,
|
|
346
|
+
images: 100
|
|
347
|
+
}
|
|
348
|
+
};
|
|
349
|
+
const modelFacts = {
|
|
350
|
+
revisions: [],
|
|
351
|
+
presets: models.map((one) => ({
|
|
352
|
+
model: one.model,
|
|
353
|
+
entry: {
|
|
354
|
+
name: one.name,
|
|
355
|
+
family: one.family,
|
|
356
|
+
release_date: one.releaseDate,
|
|
357
|
+
chat: true,
|
|
358
|
+
tool_call: one.supportsParallelToolCalls,
|
|
359
|
+
reasoning: true,
|
|
360
|
+
reasoning_options: [{
|
|
361
|
+
type: "effort",
|
|
362
|
+
values: one.efforts.filter((effort) => ACCEPTED_EFFORTS.includes(effort))
|
|
363
|
+
}],
|
|
364
|
+
modalities: {
|
|
365
|
+
input: one.inputModalities,
|
|
366
|
+
output: ["text"]
|
|
367
|
+
},
|
|
368
|
+
limit: { context: one.context }
|
|
369
|
+
}
|
|
370
|
+
}))
|
|
371
|
+
};
|
|
372
|
+
//#endregion
|
|
373
|
+
//#region src/catalog.ts
|
|
374
|
+
const catalog = {
|
|
375
|
+
vendors: [{
|
|
376
|
+
kind: "vendor",
|
|
377
|
+
id: "chatgpt",
|
|
378
|
+
logo: "data:image/svg+xml,%3Csvg%20fill%3D%22currentColor%22%20fill-rule%3D%22evenodd%22%20height%3D%2224%22%20style%3D%22flex%3Anone%3Bline-height%3A1%22%20viewBox%3D%220%200%2024%2024%22%20width%3D%2224%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Ctitle%3EOpenAI%3C%2Ftitle%3E%3Cpath%20d%3D%22M9.205%208.658v-2.26c0-.19.072-.333.238-.428l4.543-2.616c.619-.357%201.356-.523%202.117-.523%202.854%200%204.662%202.212%204.662%204.566%200%20.167%200%20.357-.024.547l-4.71-2.759a.797.797%200%2000-.856%200l-5.97%203.473zm10.609%208.8V12.06c0-.333-.143-.57-.429-.737l-5.97-3.473%201.95-1.118a.433.433%200%2001.476%200l4.543%202.617c1.309.76%202.189%202.378%202.189%203.948%200%201.808-1.07%203.473-2.76%204.163zM7.802%2012.703l-1.95-1.142c-.167-.095-.239-.238-.239-.428V5.899c0-2.545%201.95-4.472%204.591-4.472%201%200%201.927.333%202.712.928L8.23%205.067c-.285.166-.428.404-.428.737v6.898zM12%2015.128l-2.795-1.57v-3.33L12%208.658l2.795%201.57v3.33L12%2015.128zm1.796%207.23c-1%200-1.927-.332-2.712-.927l4.686-2.712c.285-.166.428-.404.428-.737v-6.898l1.974%201.142c.167.095.238.238.238.428v5.233c0%202.545-1.974%204.472-4.614%204.472zm-5.637-5.303l-4.544-2.617c-1.308-.761-2.188-2.378-2.188-3.948A4.482%204.482%200%20014.21%206.327v5.423c0%20.333.143.571.428.738l5.947%203.449-1.95%201.118a.432.432%200%2001-.476%200zm-.262%203.9c-2.688%200-4.662-2.021-4.662-4.519%200-.19.024-.38.047-.57l4.686%202.71c.286.167.571.167.856%200l5.97-3.448v2.26c0%20.19-.07.333-.237.428l-4.543%202.616c-.619.357-1.356.523-2.117.523zm5.899%202.83a5.947%205.947%200%20005.827-4.756C22.287%2018.339%2024%2015.84%2024%2013.296c0-1.665-.713-3.282-1.998-4.448.119-.5.19-.999.19-1.498%200-3.401-2.759-5.947-5.946-5.947-.642%200-1.26.095-1.88.31A5.962%205.962%200%200010.205%200a5.947%205.947%200%2000-5.827%204.757C1.713%205.447%200%207.945%200%2010.49c0%201.666.713%203.283%201.998%204.448-.119.5-.19%201-.19%201.499%200%203.401%202.759%205.946%205.946%205.946.642%200%201.26-.095%201.88-.309a5.96%205.96%200%20004.162%201.713z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E",
|
|
379
|
+
name: "ChatGPT",
|
|
380
|
+
region: null,
|
|
381
|
+
market: "international",
|
|
382
|
+
catalogKey: "chatgpt",
|
|
383
|
+
canListModels: true,
|
|
384
|
+
endpoints: [{
|
|
385
|
+
type: "chatgpt",
|
|
386
|
+
endpointId: "subscription",
|
|
387
|
+
protocolIds: ["chatgpt-subscription"],
|
|
388
|
+
baseUrl: "https://chatgpt.com/backend-api/codex"
|
|
389
|
+
}]
|
|
390
|
+
}],
|
|
391
|
+
snapshot: {},
|
|
392
|
+
snapshotAt: Date.parse(verifiedAt$1)
|
|
393
|
+
};
|
|
394
|
+
//#endregion
|
|
395
|
+
//#region src/image-generation/model.ts
|
|
396
|
+
const IMAGE_MODEL = "gpt-image-2";
|
|
397
|
+
const IMAGE_PARAMS_SCHEMA = z.object({ transparent_background: z.boolean().default(false).meta({ presentation: { label: {
|
|
398
|
+
"en-US": "Transparent background",
|
|
399
|
+
"zh-CN": "\u900f\u660e\u80cc\u666f"
|
|
400
|
+
} } }) }).strict();
|
|
401
|
+
function imageModelOf(id) {
|
|
402
|
+
return {
|
|
403
|
+
id,
|
|
404
|
+
label: id,
|
|
405
|
+
outputKinds: ["image"],
|
|
406
|
+
operations: [{
|
|
407
|
+
id: "create",
|
|
408
|
+
inputKinds: [],
|
|
409
|
+
minInputs: 0,
|
|
410
|
+
maxInputs: 0,
|
|
411
|
+
paramsSchema: IMAGE_PARAMS_SCHEMA
|
|
412
|
+
}, {
|
|
413
|
+
id: "edit",
|
|
414
|
+
inputKinds: ["image"],
|
|
415
|
+
minInputs: 1,
|
|
416
|
+
maxInputs: 5,
|
|
417
|
+
paramsSchema: IMAGE_PARAMS_SCHEMA
|
|
418
|
+
}]
|
|
419
|
+
};
|
|
420
|
+
}
|
|
421
|
+
const IMAGE_GENERATION_MODELS = [
|
|
422
|
+
imageModelOf(IMAGE_MODEL),
|
|
423
|
+
imageModelOf("gpt-image-2.5-sunburst"),
|
|
424
|
+
imageModelOf("gpt-image-2.5-flare")
|
|
425
|
+
];
|
|
426
|
+
//#endregion
|
|
427
|
+
//#region src/image-generation/client.ts
|
|
428
|
+
const responseSchema = z.object({
|
|
429
|
+
data: z.array(z.unknown()).min(1),
|
|
430
|
+
background: z.enum(["opaque", "transparent"]).optional()
|
|
431
|
+
});
|
|
432
|
+
const usageSchema = z.object({
|
|
433
|
+
input_tokens: z.number().int().nonnegative().optional(),
|
|
434
|
+
output_tokens: z.number().int().nonnegative().optional(),
|
|
435
|
+
total_tokens: z.number().int().nonnegative().optional()
|
|
436
|
+
});
|
|
437
|
+
function usageOf(text) {
|
|
438
|
+
let raw;
|
|
439
|
+
try {
|
|
440
|
+
raw = JSON.parse(text)?.usage;
|
|
441
|
+
} catch {
|
|
442
|
+
return;
|
|
443
|
+
}
|
|
444
|
+
const parsed = usageSchema.safeParse(raw);
|
|
445
|
+
if (!parsed.success) return void 0;
|
|
446
|
+
const { input_tokens, output_tokens, total_tokens } = parsed.data;
|
|
447
|
+
const usage = {
|
|
448
|
+
...input_tokens === void 0 ? {} : { inputTokens: input_tokens },
|
|
449
|
+
...output_tokens === void 0 ? {} : { outputTokens: output_tokens },
|
|
450
|
+
...total_tokens === void 0 ? {} : { totalTokens: total_tokens }
|
|
451
|
+
};
|
|
452
|
+
return Object.keys(usage).length ? usage : void 0;
|
|
453
|
+
}
|
|
454
|
+
const itemSchema = z.object({ b64_json: z.string() });
|
|
455
|
+
const RESPONSE_LIMIT = 41943040;
|
|
456
|
+
const PNG_SIGNATURE = Buffer.from([
|
|
457
|
+
137,
|
|
458
|
+
80,
|
|
459
|
+
78,
|
|
460
|
+
71,
|
|
461
|
+
13,
|
|
462
|
+
10,
|
|
463
|
+
26,
|
|
464
|
+
10
|
|
465
|
+
]);
|
|
466
|
+
const errorSchema = z.object({ error: z.object({
|
|
467
|
+
type: z.string().optional(),
|
|
468
|
+
code: z.string().optional(),
|
|
469
|
+
limit_id: z.string().optional(),
|
|
470
|
+
resets_at: z.number().int().optional()
|
|
471
|
+
}) });
|
|
472
|
+
var ImageGenerationFailure = class extends Error {
|
|
473
|
+
name = "GenerationFailure";
|
|
474
|
+
code;
|
|
475
|
+
resultState;
|
|
476
|
+
status;
|
|
477
|
+
retryAt;
|
|
478
|
+
providerText;
|
|
479
|
+
constructor(code, message, resultState, metadata = {}) {
|
|
480
|
+
super(message);
|
|
481
|
+
this.code = code;
|
|
482
|
+
this.resultState = resultState;
|
|
483
|
+
this.status = metadata.status;
|
|
484
|
+
this.retryAt = metadata.retryAt;
|
|
485
|
+
this.providerText = metadata.providerText;
|
|
486
|
+
}
|
|
487
|
+
};
|
|
488
|
+
async function submitImage(options, submission, signal) {
|
|
489
|
+
if (signal.aborted) await withImageSignal(async () => {}, signal, "not-submitted");
|
|
490
|
+
let response;
|
|
491
|
+
try {
|
|
492
|
+
response = await withImageSignal(() => options.fetch(`${options.baseUrl.replace(/\/$/, "")}/images/${submission.operation === "create" ? "generations" : "edits"}`, {
|
|
493
|
+
method: "POST",
|
|
494
|
+
signal,
|
|
495
|
+
body: submission.body,
|
|
496
|
+
headers: {
|
|
497
|
+
"content-type": "application/json",
|
|
498
|
+
authorization: `Bearer ${submission.tokens.access}`,
|
|
499
|
+
...submission.tokens.accountId ? { "ChatGPT-Account-ID": submission.tokens.accountId } : {},
|
|
500
|
+
"x-codex-image-turn-id": submission.callId,
|
|
501
|
+
originator: ORIGINATOR,
|
|
502
|
+
"User-Agent": options.userAgent
|
|
503
|
+
}
|
|
504
|
+
}).then((response) => {
|
|
505
|
+
if (signal.aborted) response.body?.cancel().catch(() => {});
|
|
506
|
+
return response;
|
|
507
|
+
}), signal, "unknown");
|
|
508
|
+
} catch (error) {
|
|
509
|
+
if (error instanceof ImageGenerationFailure) throw error;
|
|
510
|
+
throw new ImageGenerationFailure("network", "ChatGPT image request failed; its remote result is unknown", "unknown");
|
|
511
|
+
}
|
|
512
|
+
submission.onSubmitted?.();
|
|
513
|
+
if (response.status === 401) {
|
|
514
|
+
response.body?.cancel().catch(() => {});
|
|
515
|
+
throw new ImageGenerationFailure("expired", "ChatGPT sign-in expired; sign in again in model settings (status 401)", "unknown", { status: 401 });
|
|
516
|
+
}
|
|
517
|
+
const text = await readResponse(response, signal);
|
|
518
|
+
if (!response.ok) {
|
|
519
|
+
let parsedError;
|
|
520
|
+
try {
|
|
521
|
+
const result = errorSchema.safeParse(JSON.parse(text));
|
|
522
|
+
if (result.success) parsedError = result.data;
|
|
523
|
+
} catch {}
|
|
524
|
+
const reportedCode = parsedError?.error.code ?? parsedError?.error.type;
|
|
525
|
+
const quota = reportedCode === "usage_limit_reached" || reportedCode === "insufficient_quota" || parsedError?.error.limit_id === "image_gen";
|
|
526
|
+
const code = response.status === 401 ? "expired" : response.status === 403 ? "forbidden" : response.status === 429 || quota ? "quota" : "provider";
|
|
527
|
+
const seconds = parsedError?.error.resets_at;
|
|
528
|
+
const retryAt = code === "quota" && seconds !== void 0 && seconds > 0 && seconds * 1e3 <= 864e13 ? seconds * 1e3 : void 0;
|
|
529
|
+
const message = code === "expired" ? "ChatGPT sign-in expired; sign in again in model settings" : code === "forbidden" ? "ChatGPT image generation is forbidden for this account" : code === "quota" ? parsedError?.error.limit_id === "image_gen" ? "ChatGPT image generation quota reached" : "ChatGPT quota reached" : "ChatGPT image generation failed";
|
|
530
|
+
let providerText = text;
|
|
531
|
+
for (const token of [submission.tokens.access, submission.tokens.refresh]) if (token) providerText = providerText.split(token).join("****");
|
|
532
|
+
throw new ImageGenerationFailure(code, `${message} (status ${response.status})`, "unknown", {
|
|
533
|
+
status: response.status,
|
|
534
|
+
...retryAt === void 0 ? {} : { retryAt },
|
|
535
|
+
providerText: providerText.slice(0, 512)
|
|
536
|
+
});
|
|
537
|
+
}
|
|
538
|
+
const usage = usageOf(text);
|
|
539
|
+
if (usage) submission.onUsage?.(usage);
|
|
540
|
+
let parsed;
|
|
541
|
+
let item;
|
|
542
|
+
try {
|
|
543
|
+
parsed = responseSchema.parse(JSON.parse(text));
|
|
544
|
+
item = itemSchema.parse(parsed.data[0]);
|
|
545
|
+
} catch {
|
|
546
|
+
throw new ImageGenerationFailure("invalid-output", "ChatGPT returned an invalid image response", "not-delivered");
|
|
547
|
+
}
|
|
548
|
+
const encoded = item.b64_json;
|
|
549
|
+
if (encoded.length > Math.ceil(20971520 / 3) * 4) throw new ImageGenerationFailure("too-large", "Generated PNG exceeds 20 MiB", "not-delivered");
|
|
550
|
+
if (!/^[A-Za-z0-9+/]*={0,2}$/.test(encoded) || encoded.length === 0 || encoded.length % 4 !== 0) throw new ImageGenerationFailure("invalid-output", "ChatGPT returned invalid image base64", "not-delivered");
|
|
551
|
+
const bytes = Buffer.from(encoded, "base64");
|
|
552
|
+
if (bytes.byteLength > 20971520) throw new ImageGenerationFailure("too-large", "Generated PNG exceeds 20 MiB", "not-delivered");
|
|
553
|
+
if (bytes.toString("base64") !== encoded || !bytes.subarray(0, 8).equals(PNG_SIGNATURE)) throw new ImageGenerationFailure("invalid-output", "ChatGPT did not return a valid PNG", "not-delivered");
|
|
554
|
+
return {
|
|
555
|
+
bytes,
|
|
556
|
+
...parsed.background === void 0 ? {} : { background: parsed.background }
|
|
557
|
+
};
|
|
558
|
+
}
|
|
559
|
+
async function readResponse(response, signal) {
|
|
560
|
+
const length = response.headers.get("content-length");
|
|
561
|
+
if (length !== null && Number(length) > RESPONSE_LIMIT) {
|
|
562
|
+
response.body?.cancel().catch(() => {});
|
|
563
|
+
throw new ImageGenerationFailure("too-large", "Image response exceeds 40 MiB", "not-delivered");
|
|
564
|
+
}
|
|
565
|
+
if (!response.body) return "";
|
|
566
|
+
const reader = response.body.getReader();
|
|
567
|
+
const cancel = () => {
|
|
568
|
+
reader.cancel().catch(() => {});
|
|
569
|
+
};
|
|
570
|
+
signal.addEventListener("abort", cancel, { once: true });
|
|
571
|
+
const chunks = [];
|
|
572
|
+
let size = 0;
|
|
573
|
+
try {
|
|
574
|
+
while (true) {
|
|
575
|
+
const next = await withImageSignal(() => reader.read(), signal, "unknown");
|
|
576
|
+
if (next.done) break;
|
|
577
|
+
size += next.value.byteLength;
|
|
578
|
+
if (size > RESPONSE_LIMIT) throw new ImageGenerationFailure("too-large", "Image response exceeds 40 MiB", "not-delivered");
|
|
579
|
+
chunks.push(Buffer.from(next.value));
|
|
580
|
+
}
|
|
581
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
582
|
+
} catch (error) {
|
|
583
|
+
reader.cancel().catch(() => {});
|
|
584
|
+
if (error instanceof ImageGenerationFailure) throw error;
|
|
585
|
+
throw new ImageGenerationFailure("network", "ChatGPT image response was interrupted; its remote result is unknown", "unknown");
|
|
586
|
+
} finally {
|
|
587
|
+
signal.removeEventListener("abort", cancel);
|
|
588
|
+
reader.releaseLock();
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
async function withImageSignal(work, signal, resultState) {
|
|
592
|
+
const aborted = () => new ImageGenerationFailure(signal.reason instanceof Error && signal.reason.name === "TimeoutError" ? "timeout" : "cancelled", signal.reason instanceof Error && signal.reason.name === "TimeoutError" ? "Image generation timed out" : "Image generation was cancelled", resultState);
|
|
593
|
+
if (signal.aborted) throw aborted();
|
|
594
|
+
let onAbort;
|
|
595
|
+
try {
|
|
596
|
+
return await new Promise((resolve, reject) => {
|
|
597
|
+
onAbort = () => reject(aborted());
|
|
598
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
599
|
+
work().then((value) => signal.aborted ? reject(aborted()) : resolve(value), reject);
|
|
600
|
+
});
|
|
601
|
+
} finally {
|
|
602
|
+
if (onAbort) signal.removeEventListener("abort", onAbort);
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
//#endregion
|
|
606
|
+
//#region src/image-generation/port.ts
|
|
607
|
+
function createImageGenerationPort(options) {
|
|
608
|
+
return { async generate(request, signal) {
|
|
609
|
+
await withImageSignal(async () => {}, signal, "not-submitted");
|
|
610
|
+
const operation = request.operation;
|
|
611
|
+
if (request.outputKind !== "image" || operation !== "create" && operation !== "edit") throw new ImageGenerationFailure("unsupported", "Unsupported image operation", "not-submitted");
|
|
612
|
+
if (operation === "create" && request.inputs.length !== 0 || operation === "edit" && (request.inputs.length < 1 || request.inputs.length > 5)) throw new ImageGenerationFailure("invalid-input", "Image edits require one to five references; creation requires none", "not-submitted");
|
|
613
|
+
const prompt = request.prompt.trim();
|
|
614
|
+
if ([...prompt].length < 1 || [...prompt].length > 32e3) throw new ImageGenerationFailure("invalid-input", "Image prompt must contain 1 to 32000 characters", "not-submitted");
|
|
615
|
+
const parsed = IMAGE_PARAMS_SCHEMA.safeParse(request.params);
|
|
616
|
+
if (!parsed.success) throw new ImageGenerationFailure("invalid-params", "Invalid image generation parameters", "not-submitted");
|
|
617
|
+
const params = parsed.data;
|
|
618
|
+
const login = options.login;
|
|
619
|
+
if (!login) throw new ImageGenerationFailure("not-signed-in", "Sign in to ChatGPT in model settings", "not-submitted");
|
|
620
|
+
let credential;
|
|
621
|
+
try {
|
|
622
|
+
credential = await withImageSignal(() => login.get(signal), signal, "not-submitted");
|
|
623
|
+
} catch (error) {
|
|
624
|
+
if (error instanceof ImageGenerationFailure) throw error;
|
|
625
|
+
throw new ImageGenerationFailure(typeof error === "object" && error !== null && "name" in error && error.name === "CredentialUnavailableError" ? "credential-unavailable" : "not-signed-in", "ChatGPT sign-in is unavailable; sign in again in model settings", "not-submitted");
|
|
626
|
+
}
|
|
627
|
+
const tokens = parseStored(credential.credential);
|
|
628
|
+
if (!tokens?.access.trim()) throw new ImageGenerationFailure("not-signed-in", "Sign in to ChatGPT in model settings", "not-submitted");
|
|
629
|
+
const images = [];
|
|
630
|
+
for (const input of request.inputs) {
|
|
631
|
+
if (![
|
|
632
|
+
"image/png",
|
|
633
|
+
"image/jpeg",
|
|
634
|
+
"image/webp",
|
|
635
|
+
"image/gif"
|
|
636
|
+
].includes(input.mediaType) || !Number.isSafeInteger(input.size) || input.size <= 0) throw new ImageGenerationFailure("invalid-input", "Unsupported reference image", "not-submitted");
|
|
637
|
+
if (input.size > 20971520) throw new ImageGenerationFailure("too-large", "Reference image exceeds 20 MiB", "not-submitted");
|
|
638
|
+
const chunks = [];
|
|
639
|
+
let length = 0;
|
|
640
|
+
const iterator = input.read(signal)[Symbol.asyncIterator]();
|
|
641
|
+
try {
|
|
642
|
+
while (true) {
|
|
643
|
+
const next = await withImageSignal(() => iterator.next(), signal, "not-submitted");
|
|
644
|
+
if (next.done) break;
|
|
645
|
+
const chunk = next.value;
|
|
646
|
+
length += chunk.byteLength;
|
|
647
|
+
if (length > 20971520) throw new ImageGenerationFailure("too-large", "Reference image exceeds 20 MiB", "not-submitted");
|
|
648
|
+
if (length > input.size) throw new ImageGenerationFailure("invalid-input", "Reference image size changed", "not-submitted");
|
|
649
|
+
chunks.push(Buffer.from(chunk));
|
|
650
|
+
}
|
|
651
|
+
} catch (error) {
|
|
652
|
+
if (error instanceof ImageGenerationFailure) throw error;
|
|
653
|
+
throw new ImageGenerationFailure("invalid-input", "Reference image could not be read", "not-submitted");
|
|
654
|
+
} finally {
|
|
655
|
+
iterator.return?.().catch(() => {});
|
|
656
|
+
}
|
|
657
|
+
if (length !== input.size) throw new ImageGenerationFailure("invalid-input", "Reference image size changed", "not-submitted");
|
|
658
|
+
images.push({ image_url: `data:${input.mediaType};base64,${Buffer.concat(chunks).toString("base64")}` });
|
|
659
|
+
}
|
|
660
|
+
const body = JSON.stringify({
|
|
661
|
+
model: options.model,
|
|
662
|
+
prompt,
|
|
663
|
+
background: params.transparent_background ? "transparent" : "opaque",
|
|
664
|
+
quality: "auto",
|
|
665
|
+
size: "auto",
|
|
666
|
+
...request.operation === "edit" ? { images } : {}
|
|
667
|
+
});
|
|
668
|
+
if (Buffer.byteLength(body, "utf8") > 50331648) throw new ImageGenerationFailure("too-large", "Encoded image request exceeds 48 MiB", "not-submitted");
|
|
669
|
+
const accounting = options.accountingDispatch?.attempt(0);
|
|
670
|
+
let outcome = "failed";
|
|
671
|
+
let submission = "unknown";
|
|
672
|
+
try {
|
|
673
|
+
let image;
|
|
674
|
+
try {
|
|
675
|
+
image = await submitImage(options, {
|
|
676
|
+
operation,
|
|
677
|
+
body,
|
|
678
|
+
callId: request.identity.callId,
|
|
679
|
+
tokens,
|
|
680
|
+
onSubmitted: () => {
|
|
681
|
+
submission = "submitted";
|
|
682
|
+
},
|
|
683
|
+
onUsage: (usage) => accounting?.report({
|
|
684
|
+
sequence: 1,
|
|
685
|
+
...usage
|
|
686
|
+
})
|
|
687
|
+
}, signal);
|
|
688
|
+
} catch (error) {
|
|
689
|
+
if (error instanceof ImageGenerationFailure && error.code === "expired") login.expire(credential.credential);
|
|
690
|
+
throw error;
|
|
691
|
+
}
|
|
692
|
+
const { bytes, background } = image;
|
|
693
|
+
const expectedBackground = params.transparent_background ? "transparent" : "opaque";
|
|
694
|
+
if (background !== void 0 && background !== expectedBackground) throw new ImageGenerationFailure("invalid-output", "ChatGPT did not satisfy the requested background", "not-delivered");
|
|
695
|
+
let info;
|
|
696
|
+
try {
|
|
697
|
+
info = await withImageSignal(() => options.imageInfo(bytes, signal), signal, "unknown");
|
|
698
|
+
} catch (error) {
|
|
699
|
+
if (error instanceof ImageGenerationFailure) throw error;
|
|
700
|
+
throw new ImageGenerationFailure("invalid-output", "ChatGPT returned an undecodable PNG", "not-delivered");
|
|
701
|
+
}
|
|
702
|
+
if (!Number.isSafeInteger(info.width) || !Number.isSafeInteger(info.height) || info.width <= 0 || info.height <= 0 || info.width > 1e4 || info.height > 1e4 || info.mediaType !== "image/png" || info.hasTransparentPixels !== params.transparent_background || params.transparent_background && !info.hasAlpha) throw new ImageGenerationFailure("invalid-output", "ChatGPT did not satisfy the requested background", "not-delivered");
|
|
703
|
+
outcome = "success";
|
|
704
|
+
return { assets: [{
|
|
705
|
+
mediaType: "image/png",
|
|
706
|
+
name: "generated-image.png",
|
|
707
|
+
body: (async function* () {
|
|
708
|
+
yield bytes;
|
|
709
|
+
})()
|
|
710
|
+
}] };
|
|
711
|
+
} finally {
|
|
712
|
+
accounting?.end({
|
|
713
|
+
outcome: signal.aborted ? "cancelled" : outcome,
|
|
714
|
+
submission
|
|
715
|
+
});
|
|
716
|
+
}
|
|
717
|
+
} };
|
|
718
|
+
}
|
|
719
|
+
//#endregion
|
|
720
|
+
//#region src/errors.ts
|
|
721
|
+
const failureKindOf = (status) => status === 413 ? "request-too-large" : void 0;
|
|
722
|
+
var ModelCallError = class extends Error {
|
|
723
|
+
failureCode;
|
|
724
|
+
status;
|
|
725
|
+
retryable;
|
|
726
|
+
authored = true;
|
|
727
|
+
providerText;
|
|
728
|
+
retryAfterMs;
|
|
729
|
+
code;
|
|
730
|
+
kind;
|
|
731
|
+
constructor(message, options) {
|
|
732
|
+
super(message);
|
|
733
|
+
this.name = "ModelCallError";
|
|
734
|
+
this.failureCode = options.failureCode;
|
|
735
|
+
this.status = options.status;
|
|
736
|
+
this.retryable = options.retryable;
|
|
737
|
+
this.providerText = options.providerText;
|
|
738
|
+
this.retryAfterMs = options.retryAfterMs;
|
|
739
|
+
this.code = options.code;
|
|
740
|
+
this.kind = failureKindOf(options.status);
|
|
741
|
+
}
|
|
742
|
+
};
|
|
743
|
+
const NOT_SIGNED_IN = "not signed in to ChatGPT; sign in again in settings";
|
|
744
|
+
const SIGN_IN_EXPIRED = "ChatGPT sign-in expired; sign in again in settings";
|
|
745
|
+
function notSignedIn() {
|
|
746
|
+
return new ModelCallError(NOT_SIGNED_IN, {
|
|
747
|
+
retryable: false,
|
|
748
|
+
failureCode: "authentication-required"
|
|
749
|
+
});
|
|
750
|
+
}
|
|
751
|
+
function signInExpired(status) {
|
|
752
|
+
return new ModelCallError(SIGN_IN_EXPIRED, {
|
|
753
|
+
failureCode: "authentication-expired",
|
|
754
|
+
...status === void 0 ? {} : { status },
|
|
755
|
+
retryable: false
|
|
756
|
+
});
|
|
757
|
+
}
|
|
758
|
+
const SAFE_CODES = /* @__PURE__ */ new Set([
|
|
759
|
+
"usage_not_included",
|
|
760
|
+
"usage_limit_reached",
|
|
761
|
+
"insufficient_quota",
|
|
762
|
+
"context_length_exceeded",
|
|
763
|
+
"rate_limit_exceeded",
|
|
764
|
+
"overloaded_error",
|
|
765
|
+
"api_error",
|
|
766
|
+
"rate_limit_error",
|
|
767
|
+
"cyber_policy",
|
|
768
|
+
"invalid_prompt",
|
|
769
|
+
"bio_policy",
|
|
770
|
+
"misalignment_policy_violation"
|
|
771
|
+
]);
|
|
772
|
+
function codeOf(body) {
|
|
773
|
+
const code = body.error?.code ?? body.error?.type;
|
|
774
|
+
return typeof code === "string" && SAFE_CODES.has(code) ? code : void 0;
|
|
775
|
+
}
|
|
776
|
+
function resetOf(body) {
|
|
777
|
+
const at = Number(body.error?.resets_at);
|
|
778
|
+
return Number.isFinite(at) && at > 0 ? `; resets ${(/* @__PURE__ */ new Date(at * 1e3)).toISOString()}` : "";
|
|
779
|
+
}
|
|
780
|
+
function toPortError(status, text) {
|
|
781
|
+
let body = {};
|
|
782
|
+
try {
|
|
783
|
+
const parsed = JSON.parse(text);
|
|
784
|
+
if (typeof parsed === "object" && parsed !== null) body = parsed;
|
|
785
|
+
} catch {}
|
|
786
|
+
const code = codeOf(body);
|
|
787
|
+
const detail = typeof body.detail === "string" ? body.detail : "";
|
|
788
|
+
const at = `(status ${String(status)})`;
|
|
789
|
+
if (code === "usage_not_included") return new ModelCallError(`your ChatGPT plan does not include Codex ${at}`, {
|
|
790
|
+
failureCode: "model-unavailable",
|
|
791
|
+
code,
|
|
792
|
+
status,
|
|
793
|
+
retryable: false
|
|
794
|
+
});
|
|
795
|
+
if (code === "usage_limit_reached" || code === "insufficient_quota") return new ModelCallError(`ChatGPT usage limit reached ${at}${resetOf(body)}`, {
|
|
796
|
+
failureCode: "quota-exceeded",
|
|
797
|
+
code,
|
|
798
|
+
status,
|
|
799
|
+
retryable: false
|
|
800
|
+
});
|
|
801
|
+
if (code === "context_length_exceeded") return new ModelCallError(`input exceeds the model's context window ${at}`, {
|
|
802
|
+
failureCode: "context-window-exceeded",
|
|
803
|
+
code,
|
|
804
|
+
status,
|
|
805
|
+
retryable: false
|
|
806
|
+
});
|
|
807
|
+
if (detail.includes("is not supported when using Codex with a ChatGPT account")) return new ModelCallError(`this model is not available with a ChatGPT subscription ${at}`, {
|
|
808
|
+
failureCode: "model-unavailable",
|
|
809
|
+
status,
|
|
810
|
+
retryable: false
|
|
811
|
+
});
|
|
812
|
+
return new ModelCallError(`ChatGPT API error (status ${String(status)}${code === void 0 ? "" : `, code ${code}`})`, {
|
|
813
|
+
status,
|
|
814
|
+
failureCode: status === 413 ? "request-too-large" : "http-error",
|
|
815
|
+
...code === void 0 ? {} : { code },
|
|
816
|
+
retryable: status === 429 || status >= 500,
|
|
817
|
+
...text.trim() === "" ? {} : { providerText: text }
|
|
818
|
+
});
|
|
819
|
+
}
|
|
820
|
+
function toCallError(error) {
|
|
821
|
+
if (error instanceof ModelCallError) return error;
|
|
822
|
+
const name = error instanceof Error ? error.name : "";
|
|
823
|
+
return new ModelCallError(`ChatGPT call failed${name === "" ? "" : ` (${name})`}`, { retryable: false });
|
|
824
|
+
}
|
|
825
|
+
const FINAL_CODES = /* @__PURE__ */ new Set([
|
|
826
|
+
"context_length_exceeded",
|
|
827
|
+
"insufficient_quota",
|
|
828
|
+
"usage_not_included",
|
|
829
|
+
"usage_limit_reached",
|
|
830
|
+
"cyber_policy",
|
|
831
|
+
"invalid_prompt",
|
|
832
|
+
"bio_policy",
|
|
833
|
+
"misalignment_policy_violation"
|
|
834
|
+
]);
|
|
835
|
+
function waitIn(message) {
|
|
836
|
+
if (typeof message !== "string") return void 0;
|
|
837
|
+
const match = /try again in\s*(\d+(?:\.\d+)?)\s*(s|ms|seconds?)\b/i.exec(message);
|
|
838
|
+
if (match === null) return void 0;
|
|
839
|
+
const value = Number(match[1]);
|
|
840
|
+
const milliseconds = match[2]?.toLowerCase() === "ms" ? value : value * 1e3;
|
|
841
|
+
return Number.isFinite(milliseconds) && milliseconds >= 0 ? milliseconds : void 0;
|
|
842
|
+
}
|
|
843
|
+
function toFailedError(failure) {
|
|
844
|
+
const code = typeof failure.code === "string" && SAFE_CODES.has(failure.code) ? failure.code : void 0;
|
|
845
|
+
const retryAfterMs = code === "rate_limit_exceeded" ? waitIn(failure.message) : void 0;
|
|
846
|
+
return new ModelCallError(`ChatGPT response failed${code === void 0 ? "" : ` (code ${code})`}`, {
|
|
847
|
+
failureCode: code === "context_length_exceeded" ? "context-window-exceeded" : code === "insufficient_quota" || code === "usage_limit_reached" ? "quota-exceeded" : code === "usage_not_included" ? "model-unavailable" : "provider-error",
|
|
848
|
+
retryable: code === void 0 || !FINAL_CODES.has(code),
|
|
849
|
+
...code === void 0 ? {} : { code },
|
|
850
|
+
...retryAfterMs === void 0 ? {} : { retryAfterMs }
|
|
851
|
+
});
|
|
852
|
+
}
|
|
853
|
+
function toModelFailure(error, failures, transportFailure) {
|
|
854
|
+
if (failures.owns(error)) return error;
|
|
855
|
+
if (!(error instanceof ModelCallError)) {
|
|
856
|
+
const transport = transportFailure?.(error);
|
|
857
|
+
if (transport !== void 0) return transport;
|
|
858
|
+
}
|
|
859
|
+
const converted = toCallError(error);
|
|
860
|
+
const known = error instanceof ModelCallError;
|
|
861
|
+
const code = converted.code;
|
|
862
|
+
const diagnosis = !known ? "unknown" : converted.failureCode ?? (converted.status === void 0 ? "response-invalid" : "http-error");
|
|
863
|
+
const providerCodes = /* @__PURE__ */ new Set([
|
|
864
|
+
"usage_not_included",
|
|
865
|
+
"usage_limit_reached",
|
|
866
|
+
"insufficient_quota",
|
|
867
|
+
"context_length_exceeded",
|
|
868
|
+
"rate_limit_exceeded",
|
|
869
|
+
"overloaded_error",
|
|
870
|
+
"api_error",
|
|
871
|
+
"rate_limit_error",
|
|
872
|
+
"cyber_policy",
|
|
873
|
+
"invalid_prompt",
|
|
874
|
+
"bio_policy",
|
|
875
|
+
"misalignment_policy_violation"
|
|
876
|
+
]);
|
|
877
|
+
const status = Number.isInteger(converted.status) && Number(converted.status) >= 100 && Number(converted.status) <= 599 ? converted.status : void 0;
|
|
878
|
+
return failures.create({
|
|
879
|
+
code: diagnosis,
|
|
880
|
+
stage: diagnosis === "unknown" ? "unknown" : diagnosis.startsWith("authentication") || diagnosis === "request-too-large" || diagnosis === "context-window-exceeded" ? "request" : status !== void 0 ? "transport" : diagnosis === "response-invalid" ? "response-validation" : "stream",
|
|
881
|
+
category: diagnosis === "unknown" ? "unknown" : diagnosis === "stream-interrupted" ? "network" : diagnosis === "response-invalid" ? "protocol" : diagnosis === "request-too-large" || diagnosis === "context-window-exceeded" ? "request-too-large" : "provider",
|
|
882
|
+
source: known ? "protocol" : "unknown",
|
|
883
|
+
retryable: converted.retryable,
|
|
884
|
+
...status === void 0 ? {} : { status },
|
|
885
|
+
...code !== void 0 && providerCodes.has(code) ? { providerCode: code } : {}
|
|
886
|
+
}, { cause: error });
|
|
887
|
+
}
|
|
888
|
+
//#endregion
|
|
889
|
+
//#region src/stream.ts
|
|
890
|
+
const EVENT_LIMIT = 8388608;
|
|
891
|
+
const SLAB_SIZE = 65536;
|
|
892
|
+
async function* sseEvents(body) {
|
|
893
|
+
const decoder = new TextDecoder();
|
|
894
|
+
let slabs = [];
|
|
895
|
+
let slab;
|
|
896
|
+
let used = 0;
|
|
897
|
+
let size = 0;
|
|
898
|
+
let suffix = 0;
|
|
899
|
+
let pendingDelimiter = 0;
|
|
900
|
+
let work = 0;
|
|
901
|
+
const oversized = () => new ModelCallError("SSE event exceeds 8 MiB", { retryable: false });
|
|
902
|
+
function completed(delimiter) {
|
|
903
|
+
const length = size - delimiter;
|
|
904
|
+
if (length > EVENT_LIMIT) throw oversized();
|
|
905
|
+
const block = decoder.decode(Buffer.concat(slabs, length));
|
|
906
|
+
slabs = [];
|
|
907
|
+
slab = void 0;
|
|
908
|
+
size = 0;
|
|
909
|
+
used = 0;
|
|
910
|
+
suffix = 0;
|
|
911
|
+
pendingDelimiter = 0;
|
|
912
|
+
const data = block.split(/\r\n|\n|\r/).filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trimStart()).join("\n");
|
|
913
|
+
if (data !== "" && data !== "[DONE]") try {
|
|
914
|
+
return JSON.parse(data);
|
|
915
|
+
} catch {}
|
|
916
|
+
}
|
|
917
|
+
for await (const bytes of body) {
|
|
918
|
+
work += 1;
|
|
919
|
+
if (work >= SLAB_SIZE) {
|
|
920
|
+
work = 0;
|
|
921
|
+
await setImmediate();
|
|
922
|
+
}
|
|
923
|
+
if (bytes.length === 0) continue;
|
|
924
|
+
if (pendingDelimiter !== 0) {
|
|
925
|
+
const event = completed(pendingDelimiter);
|
|
926
|
+
if (event !== void 0) yield event;
|
|
927
|
+
}
|
|
928
|
+
for (let index = 0; index < bytes.length; index += 1) {
|
|
929
|
+
if (size >= 8388612) throw oversized();
|
|
930
|
+
if (slab === void 0 || used === SLAB_SIZE) {
|
|
931
|
+
slab = Buffer.allocUnsafe(SLAB_SIZE);
|
|
932
|
+
slabs.push(slab);
|
|
933
|
+
used = 0;
|
|
934
|
+
}
|
|
935
|
+
const byte = bytes[index];
|
|
936
|
+
slab[used++] = byte;
|
|
937
|
+
size += 1;
|
|
938
|
+
suffix = (suffix << 8 | byte) >>> 0;
|
|
939
|
+
const delimiter = (suffix & 65535) === 2570 || (suffix & 65535) === 3341 ? 2 : suffix === 218762506 ? 4 : 0;
|
|
940
|
+
if (delimiter !== 0) {
|
|
941
|
+
if (byte === 13 && index === bytes.length - 1) pendingDelimiter = delimiter;
|
|
942
|
+
else {
|
|
943
|
+
const event = completed(delimiter);
|
|
944
|
+
if (event !== void 0) yield event;
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
work += 1;
|
|
948
|
+
if (work >= SLAB_SIZE) {
|
|
949
|
+
work = 0;
|
|
950
|
+
await setImmediate();
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
if (pendingDelimiter !== 0) {
|
|
955
|
+
const event = completed(pendingDelimiter);
|
|
956
|
+
if (event !== void 0) yield event;
|
|
957
|
+
} else if (size > EVENT_LIMIT) throw oversized();
|
|
958
|
+
}
|
|
959
|
+
const str = (value) => typeof value === "string" ? value : "";
|
|
960
|
+
const validCount = (value) => Number.isSafeInteger(value) && Number(value) >= 0;
|
|
961
|
+
const num = (value) => validCount(value) ? value : 0;
|
|
962
|
+
function unparseableCall(item) {
|
|
963
|
+
if (item.type !== "function_call") return void 0;
|
|
964
|
+
const id = str(item.call_id);
|
|
965
|
+
const name = str(item.name);
|
|
966
|
+
if (id.trim() === "" || name.trim() === "") return void 0;
|
|
967
|
+
try {
|
|
968
|
+
JSON.parse(str(item.arguments));
|
|
969
|
+
return;
|
|
970
|
+
} catch {
|
|
971
|
+
return {
|
|
972
|
+
id,
|
|
973
|
+
name
|
|
974
|
+
};
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
function partsOf(item, model) {
|
|
978
|
+
if (item.type === "reasoning") {
|
|
979
|
+
const text = (Array.isArray(item.summary) ? item.summary : []).map((one) => str(one.text)).join("\n\n");
|
|
980
|
+
const encrypted = str(item.encrypted_content);
|
|
981
|
+
return [{
|
|
982
|
+
type: "thinking",
|
|
983
|
+
text,
|
|
984
|
+
...encrypted === "" ? {} : {
|
|
985
|
+
signature: encrypted,
|
|
986
|
+
originModel: model
|
|
987
|
+
}
|
|
988
|
+
}];
|
|
989
|
+
}
|
|
990
|
+
if (item.type === "message") {
|
|
991
|
+
const text = (Array.isArray(item.content) ? item.content : []).map((one) => {
|
|
992
|
+
const part = one;
|
|
993
|
+
return part.type === "output_text" ? str(part.text) : part.type === "refusal" ? str(part.refusal) : "";
|
|
994
|
+
}).join("");
|
|
995
|
+
return text === "" ? [] : [{
|
|
996
|
+
type: "text",
|
|
997
|
+
text
|
|
998
|
+
}];
|
|
999
|
+
}
|
|
1000
|
+
if (item.type === "function_call") {
|
|
1001
|
+
const id = str(item.call_id);
|
|
1002
|
+
const name = str(item.name);
|
|
1003
|
+
if (id.trim() === "" || name.trim() === "") throw new ModelCallError("invalid model function_call: missing call_id or name", { retryable: false });
|
|
1004
|
+
let input;
|
|
1005
|
+
try {
|
|
1006
|
+
input = JSON.parse(str(item.arguments));
|
|
1007
|
+
} catch {
|
|
1008
|
+
throw new ModelCallError("invalid model function_call: arguments are not complete JSON", { retryable: false });
|
|
1009
|
+
}
|
|
1010
|
+
return [{
|
|
1011
|
+
type: "tool-use",
|
|
1012
|
+
id,
|
|
1013
|
+
name,
|
|
1014
|
+
input
|
|
1015
|
+
}];
|
|
1016
|
+
}
|
|
1017
|
+
return [];
|
|
1018
|
+
}
|
|
1019
|
+
const tokensOf = (text) => Math.ceil(Buffer.byteLength(text, "utf8") / 4);
|
|
1020
|
+
async function* mapResponsesStream(events, options) {
|
|
1021
|
+
let usageSequence = 0;
|
|
1022
|
+
let reported = {};
|
|
1023
|
+
const items = [];
|
|
1024
|
+
const callIds = /* @__PURE__ */ new Map();
|
|
1025
|
+
const pendingCalls = /* @__PURE__ */ new Map();
|
|
1026
|
+
let openThinking = "";
|
|
1027
|
+
let written = 0;
|
|
1028
|
+
let capped = false;
|
|
1029
|
+
let refused = false;
|
|
1030
|
+
let open = "";
|
|
1031
|
+
for await (const event of events) {
|
|
1032
|
+
const response = event.response;
|
|
1033
|
+
if (response?.usage && typeof response.usage === "object") {
|
|
1034
|
+
const usage = response.usage;
|
|
1035
|
+
const details = usage.input_tokens_details ?? {};
|
|
1036
|
+
reported = {
|
|
1037
|
+
...reported,
|
|
1038
|
+
...typeof usage.input_tokens === "number" ? { inputTokens: usage.input_tokens } : {},
|
|
1039
|
+
...typeof usage.output_tokens === "number" ? { outputTokens: usage.output_tokens } : {},
|
|
1040
|
+
...typeof usage.total_tokens === "number" ? { totalTokens: usage.total_tokens } : {},
|
|
1041
|
+
...typeof details.cached_tokens === "number" ? { cacheReadTokens: details.cached_tokens } : {}
|
|
1042
|
+
};
|
|
1043
|
+
options.usageReporter?.report({
|
|
1044
|
+
sequence: ++usageSequence,
|
|
1045
|
+
...reported
|
|
1046
|
+
});
|
|
1047
|
+
}
|
|
1048
|
+
switch (event.type) {
|
|
1049
|
+
case "response.output_text.delta":
|
|
1050
|
+
case "response.refusal.delta": {
|
|
1051
|
+
if (event.type === "response.refusal.delta") refused = true;
|
|
1052
|
+
const text = str(event.delta);
|
|
1053
|
+
if (text === "") break;
|
|
1054
|
+
yield {
|
|
1055
|
+
kind: "text-delta",
|
|
1056
|
+
text
|
|
1057
|
+
};
|
|
1058
|
+
open += text;
|
|
1059
|
+
written += tokensOf(text);
|
|
1060
|
+
if (options.outputCap !== void 0 && written >= options.outputCap) capped = true;
|
|
1061
|
+
break;
|
|
1062
|
+
}
|
|
1063
|
+
case "response.reasoning_summary_text.delta": {
|
|
1064
|
+
const text = str(event.delta);
|
|
1065
|
+
if (text !== "") {
|
|
1066
|
+
openThinking += text;
|
|
1067
|
+
yield {
|
|
1068
|
+
kind: "thinking-delta",
|
|
1069
|
+
text
|
|
1070
|
+
};
|
|
1071
|
+
}
|
|
1072
|
+
break;
|
|
1073
|
+
}
|
|
1074
|
+
case "response.output_item.added": {
|
|
1075
|
+
const item = event.item;
|
|
1076
|
+
if (item?.type === "function_call") {
|
|
1077
|
+
const callId = str(item.call_id);
|
|
1078
|
+
callIds.set(str(item.id), callId);
|
|
1079
|
+
pendingCalls.set(str(item.id), {
|
|
1080
|
+
id: callId,
|
|
1081
|
+
...str(item.name) === "" ? {} : { name: str(item.name) }
|
|
1082
|
+
});
|
|
1083
|
+
yield {
|
|
1084
|
+
kind: "tool-call-delta",
|
|
1085
|
+
id: callId,
|
|
1086
|
+
name: str(item.name),
|
|
1087
|
+
inputDelta: ""
|
|
1088
|
+
};
|
|
1089
|
+
}
|
|
1090
|
+
break;
|
|
1091
|
+
}
|
|
1092
|
+
case "response.function_call_arguments.delta": {
|
|
1093
|
+
const callId = callIds.get(str(event.item_id));
|
|
1094
|
+
if (callId !== void 0) yield {
|
|
1095
|
+
kind: "tool-call-delta",
|
|
1096
|
+
id: callId,
|
|
1097
|
+
inputDelta: str(event.delta)
|
|
1098
|
+
};
|
|
1099
|
+
break;
|
|
1100
|
+
}
|
|
1101
|
+
case "response.output_item.done": {
|
|
1102
|
+
const item = event.item;
|
|
1103
|
+
if (item !== void 0) items.push(item);
|
|
1104
|
+
if (item?.type === "function_call") {
|
|
1105
|
+
pendingCalls.delete(str(item.id));
|
|
1106
|
+
for (const [key, call] of pendingCalls) if (call.id === str(item.call_id)) pendingCalls.delete(key);
|
|
1107
|
+
}
|
|
1108
|
+
if (item?.type === "reasoning") openThinking = "";
|
|
1109
|
+
if (item?.type === "message" && Array.isArray(item.content)) refused ||= item.content.some((part) => part.type === "refusal");
|
|
1110
|
+
if (item?.type === "message") open = "";
|
|
1111
|
+
break;
|
|
1112
|
+
}
|
|
1113
|
+
case "response.completed":
|
|
1114
|
+
case "response.incomplete": {
|
|
1115
|
+
const response = event.response ?? {};
|
|
1116
|
+
const usage = response.usage ?? {};
|
|
1117
|
+
const details = usage.input_tokens_details ?? {};
|
|
1118
|
+
const cache = validCount(details.cached_tokens) && details.cached_tokens <= num(usage.input_tokens) ? { cacheReadTokens: details.cached_tokens } : {};
|
|
1119
|
+
const truncated = event.type === "response.incomplete" && response.incomplete_details?.reason === "max_output_tokens";
|
|
1120
|
+
if (event.type === "response.incomplete" && !truncated && !refused) throw new ModelCallError(`incomplete model reply (${event.type})`, { retryable: false });
|
|
1121
|
+
const incompleteToolCalls = [...pendingCalls.values()];
|
|
1122
|
+
const droppedToolCalls = [];
|
|
1123
|
+
const content = items.flatMap((item) => {
|
|
1124
|
+
const unparseable = unparseableCall(item);
|
|
1125
|
+
if (unparseable && !truncated) {
|
|
1126
|
+
droppedToolCalls.push(unparseable);
|
|
1127
|
+
return [];
|
|
1128
|
+
}
|
|
1129
|
+
try {
|
|
1130
|
+
return partsOf(item, options.model);
|
|
1131
|
+
} catch (error) {
|
|
1132
|
+
if (!truncated || item.type !== "function_call" || str(item.call_id) === "") throw error;
|
|
1133
|
+
incompleteToolCalls.push({
|
|
1134
|
+
id: str(item.call_id),
|
|
1135
|
+
...str(item.name) === "" ? {} : { name: str(item.name) }
|
|
1136
|
+
});
|
|
1137
|
+
return [];
|
|
1138
|
+
}
|
|
1139
|
+
});
|
|
1140
|
+
if (truncated && open !== "") content.push({
|
|
1141
|
+
type: "text",
|
|
1142
|
+
text: open
|
|
1143
|
+
});
|
|
1144
|
+
if (truncated && openThinking !== "") content.unshift({
|
|
1145
|
+
type: "thinking",
|
|
1146
|
+
text: openThinking
|
|
1147
|
+
});
|
|
1148
|
+
if (!truncated && !refused && droppedToolCalls.length === 0 && !content.some((part) => part.type === "text" || part.type === "tool-use")) throw new ModelCallError(`incomplete model reply (${event.type})`, {
|
|
1149
|
+
retryable: false,
|
|
1150
|
+
failureCode: "response-empty"
|
|
1151
|
+
});
|
|
1152
|
+
const finishReason = refused ? "refusal" : truncated ? "max-tokens" : droppedToolCalls.length > 0 || content.some((part) => part.type === "tool-use") ? "tool-calls" : "stop";
|
|
1153
|
+
yield {
|
|
1154
|
+
kind: "final",
|
|
1155
|
+
finishReason,
|
|
1156
|
+
...droppedToolCalls.length > 0 ? { droppedToolCalls } : {},
|
|
1157
|
+
...finishReason === "max-tokens" ? { outputTruncation: {
|
|
1158
|
+
incompleteToolCalls,
|
|
1159
|
+
...openThinking !== "" ? { incompleteThinking: true } : {}
|
|
1160
|
+
} } : {},
|
|
1161
|
+
usage: {
|
|
1162
|
+
inputTokens: num(usage.input_tokens),
|
|
1163
|
+
...validCount(usage.input_tokens) && (details.cached_tokens == null || validCount(details.cached_tokens) && details.cached_tokens <= usage.input_tokens) && (details.cache_write_tokens == null || validCount(details.cache_write_tokens) && details.cache_write_tokens <= usage.input_tokens) ? {} : { inputTokensReported: false },
|
|
1164
|
+
outputTokens: num(usage.output_tokens),
|
|
1165
|
+
...cache
|
|
1166
|
+
},
|
|
1167
|
+
message: {
|
|
1168
|
+
role: "assistant",
|
|
1169
|
+
content
|
|
1170
|
+
}
|
|
1171
|
+
};
|
|
1172
|
+
return;
|
|
1173
|
+
}
|
|
1174
|
+
case "response.failed":
|
|
1175
|
+
case "error": throw toFailedError(event.response?.error ?? event.error ?? event);
|
|
1176
|
+
}
|
|
1177
|
+
if (capped) {
|
|
1178
|
+
options.stop?.();
|
|
1179
|
+
const content = items.flatMap((item) => partsOf(item, options.model));
|
|
1180
|
+
if (open !== "") content.push({
|
|
1181
|
+
type: "text",
|
|
1182
|
+
text: open
|
|
1183
|
+
});
|
|
1184
|
+
if (openThinking !== "") content.unshift({
|
|
1185
|
+
type: "thinking",
|
|
1186
|
+
text: openThinking
|
|
1187
|
+
});
|
|
1188
|
+
yield {
|
|
1189
|
+
kind: "final",
|
|
1190
|
+
finishReason: "max-tokens",
|
|
1191
|
+
outputTruncation: {
|
|
1192
|
+
incompleteToolCalls: [...pendingCalls.values()],
|
|
1193
|
+
...openThinking !== "" ? { incompleteThinking: true } : {}
|
|
1194
|
+
},
|
|
1195
|
+
usage: {
|
|
1196
|
+
inputTokens: 0,
|
|
1197
|
+
outputTokens: written,
|
|
1198
|
+
inputTokensReported: false
|
|
1199
|
+
},
|
|
1200
|
+
message: {
|
|
1201
|
+
role: "assistant",
|
|
1202
|
+
content
|
|
1203
|
+
}
|
|
1204
|
+
};
|
|
1205
|
+
return;
|
|
1206
|
+
}
|
|
1207
|
+
}
|
|
1208
|
+
throw new ModelCallError("model stream interrupted", {
|
|
1209
|
+
retryable: true,
|
|
1210
|
+
failureCode: "stream-interrupted"
|
|
1211
|
+
});
|
|
1212
|
+
}
|
|
1213
|
+
//#endregion
|
|
1214
|
+
//#region src/port.ts
|
|
1215
|
+
function transportIdOf(request) {
|
|
1216
|
+
const identity = request.sessionId ?? request.callId;
|
|
1217
|
+
if (!identity || request.sessionId !== void 0 && request.callId !== void 0) throw new Error("a model request requires exactly one session or call identity");
|
|
1218
|
+
return identity;
|
|
1219
|
+
}
|
|
1220
|
+
function headersOf(tokens, sessionId, userAgent) {
|
|
1221
|
+
return {
|
|
1222
|
+
authorization: `Bearer ${tokens.access}`,
|
|
1223
|
+
"chatgpt-account-id": tokens.accountId,
|
|
1224
|
+
originator: ORIGINATOR,
|
|
1225
|
+
"user-agent": userAgent,
|
|
1226
|
+
"session-id": sessionId,
|
|
1227
|
+
"content-type": "application/json",
|
|
1228
|
+
accept: "text/event-stream",
|
|
1229
|
+
...tokens.residency === void 0 ? {} : { "x-openai-internal-codex-residency": tokens.residency }
|
|
1230
|
+
};
|
|
1231
|
+
}
|
|
1232
|
+
function createChatGPTPort(options) {
|
|
1233
|
+
function build(request) {
|
|
1234
|
+
const plan = options.params(request.params ?? {});
|
|
1235
|
+
const media = options.media?.(request.params ?? {}) ?? {
|
|
1236
|
+
acceptsImages: true,
|
|
1237
|
+
limits: void 0
|
|
1238
|
+
};
|
|
1239
|
+
const replay = options.support.planEffortCache({
|
|
1240
|
+
request,
|
|
1241
|
+
inspection: false,
|
|
1242
|
+
effort: plan.effort,
|
|
1243
|
+
capability: plan.thinking === false || plan.effort === "none" ? {
|
|
1244
|
+
status: "unsupported",
|
|
1245
|
+
reason: "reasoning-required"
|
|
1246
|
+
} : { status: "supported" },
|
|
1247
|
+
bindingFingerprint: options.support.inspectionFingerprint({
|
|
1248
|
+
connectionFingerprint: options.connectionFingerprint,
|
|
1249
|
+
providerId: options.providerId,
|
|
1250
|
+
endpoint: options.endpoints.codex,
|
|
1251
|
+
model: options.model,
|
|
1252
|
+
system: request.system,
|
|
1253
|
+
tools: request.tools,
|
|
1254
|
+
thinking: plan.thinking
|
|
1255
|
+
})
|
|
1256
|
+
});
|
|
1257
|
+
const mediaPlan = options.support.planMedia(request, media);
|
|
1258
|
+
const rendered = options.codec.render(request, {
|
|
1259
|
+
model: options.model,
|
|
1260
|
+
endpoint: options.providerId,
|
|
1261
|
+
effort: replay.baseEffort,
|
|
1262
|
+
effortUpdates: replay.updates,
|
|
1263
|
+
media
|
|
1264
|
+
}, mediaPlan);
|
|
1265
|
+
const receipts = new Map(replay.replaySources?.map((source) => [source.messageId, JSON.stringify(source.contribution)]));
|
|
1266
|
+
const replaySelections = options.support.prepareReplaySelections(request, ({ message, part }) => part ? options.codec.replayChoice(message, part, {
|
|
1267
|
+
model: options.model,
|
|
1268
|
+
endpoint: options.providerId
|
|
1269
|
+
}) : {
|
|
1270
|
+
mode: "effort-cache",
|
|
1271
|
+
textIncluded: false,
|
|
1272
|
+
selectedText: receipts.get(message.id),
|
|
1273
|
+
reason: "not-applicable"
|
|
1274
|
+
});
|
|
1275
|
+
const sessionId = transportIdOf(request);
|
|
1276
|
+
const body = options.support.freezePayload({
|
|
1277
|
+
...rendered,
|
|
1278
|
+
prompt_cache_key: sessionId
|
|
1279
|
+
});
|
|
1280
|
+
return {
|
|
1281
|
+
body,
|
|
1282
|
+
replaySelections,
|
|
1283
|
+
sessionId,
|
|
1284
|
+
replay: options.support.freezePayload(replay),
|
|
1285
|
+
fields: options.codec.semanticFields(body, mediaPlan),
|
|
1286
|
+
capacity: options.support.freezePayload(options.catalogue()?.limit ?? {}),
|
|
1287
|
+
request: {
|
|
1288
|
+
...request,
|
|
1289
|
+
params: options.support.freezePayload(request.params ?? {})
|
|
1290
|
+
},
|
|
1291
|
+
mediaPlan,
|
|
1292
|
+
mediaTokens: mediaPlan.tokens,
|
|
1293
|
+
hiddenInputTokens: options.codec.hiddenInputTokens(request, {
|
|
1294
|
+
model: options.model,
|
|
1295
|
+
endpoint: options.providerId
|
|
1296
|
+
}),
|
|
1297
|
+
fingerprint: options.support.freezePayload({
|
|
1298
|
+
rendering: "chatgpt-codex-responses-v2",
|
|
1299
|
+
endpoint: options.providerId,
|
|
1300
|
+
model: options.model,
|
|
1301
|
+
purpose: request.purpose,
|
|
1302
|
+
settings: { effort: body.reasoning?.effort }
|
|
1303
|
+
})
|
|
1304
|
+
};
|
|
1305
|
+
}
|
|
1306
|
+
async function send(body, sessionId, signal, prepared, reportProgress, dispatched) {
|
|
1307
|
+
const { tokens } = prepared;
|
|
1308
|
+
const pending = options.fetch(`${options.endpoints.codex}/responses`, {
|
|
1309
|
+
method: "POST",
|
|
1310
|
+
headers: headersOf(tokens, sessionId, options.userAgent),
|
|
1311
|
+
body: JSON.stringify(body),
|
|
1312
|
+
signal
|
|
1313
|
+
});
|
|
1314
|
+
dispatched();
|
|
1315
|
+
const response = await pending;
|
|
1316
|
+
return {
|
|
1317
|
+
response: options.support.observeResponseProgress(response, reportProgress),
|
|
1318
|
+
credential: prepared.credential
|
|
1319
|
+
};
|
|
1320
|
+
}
|
|
1321
|
+
return options.support.createPreparedPort({
|
|
1322
|
+
prepare: build,
|
|
1323
|
+
semantics(payload) {
|
|
1324
|
+
return {
|
|
1325
|
+
replaySelections: payload.replaySelections,
|
|
1326
|
+
mediaSelections: () => options.support.mediaSelections(payload.mediaPlan),
|
|
1327
|
+
format: "request-semantic-v1",
|
|
1328
|
+
protocolId: "chatgpt-subscription",
|
|
1329
|
+
adapterVersion: "1",
|
|
1330
|
+
rendererVersion: "chatgpt-codex-responses-v2",
|
|
1331
|
+
parameters: Object.freeze(Object.fromEntries(Object.entries(payload.body).filter(([key]) => ![
|
|
1332
|
+
"model",
|
|
1333
|
+
"input",
|
|
1334
|
+
"instructions",
|
|
1335
|
+
"tools",
|
|
1336
|
+
"stream",
|
|
1337
|
+
"store",
|
|
1338
|
+
"prompt_cache_key"
|
|
1339
|
+
].includes(key)))),
|
|
1340
|
+
toolDefinitions: payload.body.tools ?? Object.freeze([]),
|
|
1341
|
+
frames: () => options.support.semanticFrames(payload.body, {
|
|
1342
|
+
omitRoot: [
|
|
1343
|
+
"stream",
|
|
1344
|
+
"store",
|
|
1345
|
+
"prompt_cache_key"
|
|
1346
|
+
],
|
|
1347
|
+
fields: payload.fields
|
|
1348
|
+
})
|
|
1349
|
+
};
|
|
1350
|
+
},
|
|
1351
|
+
async inspect(payload, signal) {
|
|
1352
|
+
signal.throwIfAborted();
|
|
1353
|
+
const started = options.support.performance?.now();
|
|
1354
|
+
const { body, request, capacity, hiddenInputTokens, mediaTokens, fingerprint } = payload;
|
|
1355
|
+
options.support.performance?.observe({
|
|
1356
|
+
stage: "model.project",
|
|
1357
|
+
measurementPurpose: "request",
|
|
1358
|
+
durationMs: options.support.performance.now() - started,
|
|
1359
|
+
count: 1
|
|
1360
|
+
});
|
|
1361
|
+
const text = options.support.requestText("responses", body);
|
|
1362
|
+
const inspection = options.support.inspect({
|
|
1363
|
+
body,
|
|
1364
|
+
textTokens: 0,
|
|
1365
|
+
textBytes: Buffer.byteLength(text),
|
|
1366
|
+
tokenizer: "utf8-bytes-quarter-v1",
|
|
1367
|
+
hiddenInputTokens,
|
|
1368
|
+
request,
|
|
1369
|
+
capacity,
|
|
1370
|
+
outputReserve: capacity?.output ?? 0,
|
|
1371
|
+
outputReserveSource: "capacity",
|
|
1372
|
+
mediaTokens,
|
|
1373
|
+
fingerprint
|
|
1374
|
+
});
|
|
1375
|
+
const textTokens = await options.support.measureText(text, signal);
|
|
1376
|
+
signal.throwIfAborted();
|
|
1377
|
+
return {
|
|
1378
|
+
...inspection,
|
|
1379
|
+
inputTokens: inspection.inputTokens + textTokens
|
|
1380
|
+
};
|
|
1381
|
+
},
|
|
1382
|
+
stream(payload, signal, observer, scope) {
|
|
1383
|
+
signal.throwIfAborted();
|
|
1384
|
+
const login = options.login;
|
|
1385
|
+
const { body, request, sessionId, replay } = payload;
|
|
1386
|
+
const dispatchEffort = body.reasoning?.effort === "none" ? "none" : replay.effectiveEffort ?? body.reasoning?.effort;
|
|
1387
|
+
const cap = request.purpose === "summary" && request.summaryMaxTokens !== void 0 ? request.summaryMaxTokens : void 0;
|
|
1388
|
+
let prepared;
|
|
1389
|
+
return options.support.withChatAttempts({
|
|
1390
|
+
retainCleanup: scope.retainCleanup,
|
|
1391
|
+
accountingDispatch: options.accountingDispatch,
|
|
1392
|
+
beforeAttempt: async (attemptSignal, ordinal) => {
|
|
1393
|
+
await observer?.beforeAttempt?.(ordinal);
|
|
1394
|
+
if (login === void 0) throw notSignedIn();
|
|
1395
|
+
const envelope = await login.get(attemptSignal);
|
|
1396
|
+
const tokens = parseStored(envelope.credential);
|
|
1397
|
+
if (tokens === void 0) throw notSignedIn();
|
|
1398
|
+
prepared = {
|
|
1399
|
+
credential: envelope.credential,
|
|
1400
|
+
tokens
|
|
1401
|
+
};
|
|
1402
|
+
},
|
|
1403
|
+
signal,
|
|
1404
|
+
...options.maxRetries === void 0 ? {} : { maxRetries: options.maxRetries },
|
|
1405
|
+
...options.sleep === void 0 ? {} : { sleep: options.sleep },
|
|
1406
|
+
...options.idleMs === void 0 ? {} : { idleMs: options.idleMs },
|
|
1407
|
+
async *attempt(attemptSignal, reportProgress, attempt, usageReporter) {
|
|
1408
|
+
const observe = (event) => {
|
|
1409
|
+
try {
|
|
1410
|
+
observer?.observe?.(event);
|
|
1411
|
+
} catch {}
|
|
1412
|
+
};
|
|
1413
|
+
const attemptCount = attempt + 1;
|
|
1414
|
+
let outcome = "unknown";
|
|
1415
|
+
let timeout;
|
|
1416
|
+
let firstResponseFinished = false;
|
|
1417
|
+
const markDispatched = () => {
|
|
1418
|
+
try {
|
|
1419
|
+
observer?.dispatched({
|
|
1420
|
+
attempt,
|
|
1421
|
+
presentation: {
|
|
1422
|
+
schema: "chat.dispatch-settings.v1",
|
|
1423
|
+
data: {
|
|
1424
|
+
model: {
|
|
1425
|
+
availability: "resolved",
|
|
1426
|
+
value: body.model,
|
|
1427
|
+
origin: "protocol"
|
|
1428
|
+
},
|
|
1429
|
+
effort: dispatchEffort ? {
|
|
1430
|
+
availability: "resolved",
|
|
1431
|
+
value: dispatchEffort,
|
|
1432
|
+
origin: "protocol"
|
|
1433
|
+
} : { availability: "unreported" }
|
|
1434
|
+
}
|
|
1435
|
+
}
|
|
1436
|
+
});
|
|
1437
|
+
} catch {}
|
|
1438
|
+
};
|
|
1439
|
+
observe({
|
|
1440
|
+
stage: "attempt",
|
|
1441
|
+
phase: "start",
|
|
1442
|
+
attempt: attemptCount
|
|
1443
|
+
});
|
|
1444
|
+
observe({
|
|
1445
|
+
stage: "first-response",
|
|
1446
|
+
phase: "start",
|
|
1447
|
+
attempt: attemptCount
|
|
1448
|
+
});
|
|
1449
|
+
let responseBody;
|
|
1450
|
+
try {
|
|
1451
|
+
attemptSignal.throwIfAborted();
|
|
1452
|
+
if (login === void 0) throw notSignedIn();
|
|
1453
|
+
const { response, credential } = await send(body, sessionId, attemptSignal, prepared, reportProgress, markDispatched);
|
|
1454
|
+
responseBody = response.body;
|
|
1455
|
+
firstResponseFinished = true;
|
|
1456
|
+
observe({
|
|
1457
|
+
stage: "first-response",
|
|
1458
|
+
phase: "end",
|
|
1459
|
+
attempt: attemptCount,
|
|
1460
|
+
outcome: "ok"
|
|
1461
|
+
});
|
|
1462
|
+
if (response.status === 401) {
|
|
1463
|
+
await response.body?.cancel().catch(() => {});
|
|
1464
|
+
responseBody = void 0;
|
|
1465
|
+
login.expire(credential);
|
|
1466
|
+
throw signInExpired(401);
|
|
1467
|
+
}
|
|
1468
|
+
if (!response.ok || response.body === null) {
|
|
1469
|
+
const refusalText = await response.text().catch(() => "");
|
|
1470
|
+
responseBody = void 0;
|
|
1471
|
+
const refused = toPortError(response.status, refusalText);
|
|
1472
|
+
const wait = Number(response.headers.get("retry-after"));
|
|
1473
|
+
throw Number.isFinite(wait * 1e3) && wait > 0 && refused.retryable ? new ModelCallError(refused.message, {
|
|
1474
|
+
failureCode: refused.failureCode,
|
|
1475
|
+
code: refused.code,
|
|
1476
|
+
...refused.status === void 0 ? {} : { status: refused.status },
|
|
1477
|
+
retryable: true,
|
|
1478
|
+
retryAfterMs: wait * 1e3,
|
|
1479
|
+
...refused.providerText === void 0 ? {} : { providerText: refused.providerText }
|
|
1480
|
+
}) : refused;
|
|
1481
|
+
}
|
|
1482
|
+
attemptSignal.throwIfAborted();
|
|
1483
|
+
attemptSignal.throwIfAborted();
|
|
1484
|
+
const stream = response.body;
|
|
1485
|
+
const events = (async function* () {
|
|
1486
|
+
responseBody = void 0;
|
|
1487
|
+
yield* sseEvents(stream);
|
|
1488
|
+
})();
|
|
1489
|
+
for await (const chunk of mapResponsesStream(events, {
|
|
1490
|
+
usageReporter,
|
|
1491
|
+
model: options.model,
|
|
1492
|
+
...cap === void 0 ? {} : { outputCap: cap },
|
|
1493
|
+
stop: () => void events.return(void 0).catch(() => {})
|
|
1494
|
+
})) {
|
|
1495
|
+
if (chunk.kind === "final") outcome = "ok";
|
|
1496
|
+
yield chunk.kind === "final" && replay.replayData ? {
|
|
1497
|
+
...chunk,
|
|
1498
|
+
replayData: replay.replayData
|
|
1499
|
+
} : chunk;
|
|
1500
|
+
}
|
|
1501
|
+
} catch (error) {
|
|
1502
|
+
const reason = attemptSignal.aborted ? options.support.failures.verified(attemptSignal.reason) : void 0;
|
|
1503
|
+
if (reason?.code === "stream-idle-timeout") {
|
|
1504
|
+
outcome = "timeout";
|
|
1505
|
+
timeout = reason;
|
|
1506
|
+
} else outcome = attemptSignal.aborted ? "cancelled" : "error";
|
|
1507
|
+
throw error;
|
|
1508
|
+
} finally {
|
|
1509
|
+
if (responseBody) {
|
|
1510
|
+
const body = responseBody;
|
|
1511
|
+
scope.retainCleanup(async () => {
|
|
1512
|
+
await body.cancel();
|
|
1513
|
+
}).catch(() => {});
|
|
1514
|
+
}
|
|
1515
|
+
const end = {
|
|
1516
|
+
phase: "end",
|
|
1517
|
+
attempt: attemptCount,
|
|
1518
|
+
outcome,
|
|
1519
|
+
...timeout ? { failure: timeout } : {}
|
|
1520
|
+
};
|
|
1521
|
+
if (!firstResponseFinished) observe({
|
|
1522
|
+
stage: "first-response",
|
|
1523
|
+
...end
|
|
1524
|
+
});
|
|
1525
|
+
observe({
|
|
1526
|
+
stage: "attempt",
|
|
1527
|
+
...end
|
|
1528
|
+
});
|
|
1529
|
+
}
|
|
1530
|
+
},
|
|
1531
|
+
classify(error) {
|
|
1532
|
+
const failure = toModelFailure(error, options.support.failures, options.support.transportFailure);
|
|
1533
|
+
return {
|
|
1534
|
+
error: failure,
|
|
1535
|
+
retryable: failure.retryable === true,
|
|
1536
|
+
retryAfterMs: toCallError(error).retryAfterMs
|
|
1537
|
+
};
|
|
1538
|
+
}
|
|
1539
|
+
});
|
|
1540
|
+
}
|
|
1541
|
+
});
|
|
1542
|
+
}
|
|
1543
|
+
//#endregion
|
|
1544
|
+
//#region src/probe.ts
|
|
1545
|
+
function modalitiesOf(value) {
|
|
1546
|
+
return Array.isArray(value) && value.length > 0 && value.every((one) => typeof one === "string") ? [...value] : void 0;
|
|
1547
|
+
}
|
|
1548
|
+
function effortsOf(levels) {
|
|
1549
|
+
if (!Array.isArray(levels)) return void 0;
|
|
1550
|
+
const named = levels.map((one) => typeof one === "string" ? one : one?.effort).filter((one) => typeof one === "string");
|
|
1551
|
+
const accepted = ACCEPTED_EFFORTS.filter((effort) => named.includes(effort));
|
|
1552
|
+
return accepted.length === 0 ? void 0 : accepted;
|
|
1553
|
+
}
|
|
1554
|
+
function offerOf(model) {
|
|
1555
|
+
if (typeof model.slug !== "string" || model.visibility !== "list") return void 0;
|
|
1556
|
+
const efforts = effortsOf(model.supported_reasoning_levels);
|
|
1557
|
+
const input = modalitiesOf(model.input_modalities);
|
|
1558
|
+
const fallback = model.default_reasoning_level;
|
|
1559
|
+
const defaultEffort = typeof fallback === "string" && efforts?.includes(fallback) ? fallback : void 0;
|
|
1560
|
+
return {
|
|
1561
|
+
model: model.slug,
|
|
1562
|
+
...typeof model.display_name === "string" ? { name: model.display_name } : {},
|
|
1563
|
+
...Number.isInteger(model.context_window) && Number(model.context_window) > 0 ? { contextWindow: Number(model.context_window) } : {},
|
|
1564
|
+
...input === void 0 ? {} : { input },
|
|
1565
|
+
output: ["text"],
|
|
1566
|
+
...model.supports_parallel_tool_calls === true ? { toolCall: true } : {},
|
|
1567
|
+
...efforts === void 0 ? {} : { efforts },
|
|
1568
|
+
...defaultEffort === void 0 ? {} : { defaultEffort }
|
|
1569
|
+
};
|
|
1570
|
+
}
|
|
1571
|
+
function heldTokens(used, stored) {
|
|
1572
|
+
const now = parseStored(stored);
|
|
1573
|
+
return [
|
|
1574
|
+
used.access,
|
|
1575
|
+
used.refresh,
|
|
1576
|
+
now?.access,
|
|
1577
|
+
now?.refresh
|
|
1578
|
+
].filter((one) => one !== void 0 && one !== "");
|
|
1579
|
+
}
|
|
1580
|
+
const DEFAULT_RESPONSE_BYTES = 8388608;
|
|
1581
|
+
async function boundedText(response, maxBytes) {
|
|
1582
|
+
const exceeded = () => /* @__PURE__ */ new Error("the model listing exceeds its response byte ceiling");
|
|
1583
|
+
const declared = response.headers.get("content-length");
|
|
1584
|
+
if (declared !== null && /^\d+$/.test(declared) && Number(declared) > maxBytes) {
|
|
1585
|
+
await response.body?.cancel().catch(() => {});
|
|
1586
|
+
throw exceeded();
|
|
1587
|
+
}
|
|
1588
|
+
if (!response.body) return "";
|
|
1589
|
+
const reader = response.body.getReader();
|
|
1590
|
+
const decoder = new TextDecoder();
|
|
1591
|
+
let bytes = 0;
|
|
1592
|
+
let text = "";
|
|
1593
|
+
try {
|
|
1594
|
+
for (;;) {
|
|
1595
|
+
const next = await reader.read();
|
|
1596
|
+
if (next.done) return text + decoder.decode();
|
|
1597
|
+
bytes += next.value.byteLength;
|
|
1598
|
+
if (bytes > maxBytes) throw exceeded();
|
|
1599
|
+
text += decoder.decode(next.value, { stream: true });
|
|
1600
|
+
}
|
|
1601
|
+
} catch (error) {
|
|
1602
|
+
await reader.cancel().catch(() => {});
|
|
1603
|
+
throw error;
|
|
1604
|
+
} finally {
|
|
1605
|
+
reader.releaseLock();
|
|
1606
|
+
}
|
|
1607
|
+
}
|
|
1608
|
+
function createProbes(deps) {
|
|
1609
|
+
async function listModels(probe) {
|
|
1610
|
+
const login = probe.login;
|
|
1611
|
+
if (login === void 0) throw new Error("not signed in");
|
|
1612
|
+
const envelope = await login.get(probe.signal);
|
|
1613
|
+
const tokens = parseStored(envelope.credential);
|
|
1614
|
+
if (tokens === void 0) throw new Error("not signed in");
|
|
1615
|
+
const response = await deps.fetch(`${deps.endpoints.codex}/models?client_version=${CODEX_CLIENT_VERSION}`, {
|
|
1616
|
+
method: "GET",
|
|
1617
|
+
headers: {
|
|
1618
|
+
authorization: `Bearer ${tokens.access}`,
|
|
1619
|
+
"chatgpt-account-id": tokens.accountId,
|
|
1620
|
+
originator: ORIGINATOR,
|
|
1621
|
+
"user-agent": deps.userAgent,
|
|
1622
|
+
accept: "application/json"
|
|
1623
|
+
},
|
|
1624
|
+
signal: probe.signal
|
|
1625
|
+
});
|
|
1626
|
+
const limit = probe.maxResponseBytes ?? DEFAULT_RESPONSE_BYTES;
|
|
1627
|
+
if (!response.ok) {
|
|
1628
|
+
const body = await boundedText(response, limit).catch(() => "");
|
|
1629
|
+
const echoes = heldTokens(tokens, envelope.credential).some((token) => body.includes(token));
|
|
1630
|
+
throw Object.assign(new Error(body === "" || echoes ? response.statusText : body), { status: response.status });
|
|
1631
|
+
}
|
|
1632
|
+
const body = JSON.parse(await boundedText(response, limit));
|
|
1633
|
+
return (Array.isArray(body.models) ? body.models : []).map(offerOf).filter((one) => one !== void 0);
|
|
1634
|
+
}
|
|
1635
|
+
return {
|
|
1636
|
+
listModels,
|
|
1637
|
+
async testConnection(probe) {
|
|
1638
|
+
await listModels(probe);
|
|
1639
|
+
}
|
|
1640
|
+
};
|
|
1641
|
+
}
|
|
1642
|
+
//#endregion
|
|
1643
|
+
//#region src/support.ts
|
|
1644
|
+
function normalizeOffers(input) {
|
|
1645
|
+
return Object.fromEntries(input.offers.map((offer) => [offer.model, {
|
|
1646
|
+
id: offer.model,
|
|
1647
|
+
...offer.name === void 0 ? {} : { name: offer.name },
|
|
1648
|
+
...offer.chat === void 0 ? {} : { chat: offer.chat },
|
|
1649
|
+
...offer.reasoning === void 0 && !offer.efforts?.length ? {} : { reasoning: offer.efforts?.length ? true : offer.reasoning },
|
|
1650
|
+
...offer.efforts?.length ? { reasoning_options: [{
|
|
1651
|
+
type: "effort",
|
|
1652
|
+
values: [...offer.efforts]
|
|
1653
|
+
}] } : {},
|
|
1654
|
+
...offer.temperature === void 0 ? {} : { temperature: offer.temperature },
|
|
1655
|
+
...offer.toolCall === void 0 ? {} : { tool_call: offer.toolCall },
|
|
1656
|
+
...offer.input === void 0 ? {} : { attachment: offer.input.some((one) => one !== "text") },
|
|
1657
|
+
...offer.input === void 0 && offer.output === void 0 ? {} : { modalities: {
|
|
1658
|
+
...offer.input === void 0 ? {} : { input: [...offer.input] },
|
|
1659
|
+
...offer.output === void 0 ? {} : { output: [...offer.output] }
|
|
1660
|
+
} },
|
|
1661
|
+
...!offer.contextWindow && !offer.maxOutput ? {} : { limit: {
|
|
1662
|
+
...offer.contextWindow && offer.contextWindow > 0 ? { context: offer.contextWindow } : {},
|
|
1663
|
+
...offer.maxOutput && offer.maxOutput > 0 ? { output: offer.maxOutput } : {}
|
|
1664
|
+
} },
|
|
1665
|
+
...offer.releaseDate === void 0 ? {} : { release_date: offer.releaseDate }
|
|
1666
|
+
}]));
|
|
1667
|
+
}
|
|
1668
|
+
function lazySupport(read) {
|
|
1669
|
+
return new Proxy({}, { get(_target, key) {
|
|
1670
|
+
if (key === "normalizeListing") return normalizeOffers;
|
|
1671
|
+
const service = read();
|
|
1672
|
+
if (!service) throw new Error("Chat model support is unavailable");
|
|
1673
|
+
const value = Reflect.get(service, key);
|
|
1674
|
+
return typeof value === "function" ? value.bind(service) : value;
|
|
1675
|
+
} });
|
|
1676
|
+
}
|
|
1677
|
+
//#endregion
|
|
1678
|
+
//#region src/protocol.ts
|
|
1679
|
+
const USER_AGENT = "yaoguang";
|
|
1680
|
+
function chatgptProtocolType(support, fetch, codec, options = {}, imageInfo = (bytes, signal) => support.imageInfo(bytes, signal)) {
|
|
1681
|
+
const endpoints = options.endpoints ?? ENDPOINTS;
|
|
1682
|
+
const probes = createProbes({
|
|
1683
|
+
fetch,
|
|
1684
|
+
endpoints,
|
|
1685
|
+
userAgent: USER_AGENT
|
|
1686
|
+
});
|
|
1687
|
+
return {
|
|
1688
|
+
type: "chatgpt-subscription",
|
|
1689
|
+
label: "ChatGPT Subscription",
|
|
1690
|
+
logo: catalog.vendors[0]?.logo,
|
|
1691
|
+
fields: [],
|
|
1692
|
+
userConfigurable: false,
|
|
1693
|
+
optionsSchema: z.strictObject({}),
|
|
1694
|
+
facts,
|
|
1695
|
+
effortCacheCapability(input) {
|
|
1696
|
+
return input.params.thinking === false || input.params.effort === "none" ? {
|
|
1697
|
+
status: "unsupported",
|
|
1698
|
+
reason: "reasoning-required"
|
|
1699
|
+
} : { status: "supported" };
|
|
1700
|
+
},
|
|
1701
|
+
prepareParams: (input) => support.prepareParams(input, facts),
|
|
1702
|
+
adapters: {
|
|
1703
|
+
chat: {
|
|
1704
|
+
fileKinds: ["image"],
|
|
1705
|
+
supportsModel: (model) => !/^gpt-image(?:-|$)/.test(model),
|
|
1706
|
+
createPort: (call) => createChatGPTPort({
|
|
1707
|
+
accountingDispatch: call.accountingDispatch,
|
|
1708
|
+
fetch,
|
|
1709
|
+
codec,
|
|
1710
|
+
connectionFingerprint: call.connectionFingerprint,
|
|
1711
|
+
endpoints,
|
|
1712
|
+
model: call.model,
|
|
1713
|
+
providerId: call.providerId,
|
|
1714
|
+
login: call.login,
|
|
1715
|
+
support,
|
|
1716
|
+
userAgent: USER_AGENT,
|
|
1717
|
+
catalogue: () => support.catalogue(call.providerId, call.model),
|
|
1718
|
+
media: (stored) => support.mediaContextOf({
|
|
1719
|
+
entry: support.catalogue(call.providerId, call.model),
|
|
1720
|
+
stored,
|
|
1721
|
+
facts,
|
|
1722
|
+
endpoint: support.endpoint(call.providerId)
|
|
1723
|
+
}),
|
|
1724
|
+
params: (stored) => support.resolveParams({
|
|
1725
|
+
facts,
|
|
1726
|
+
model: call.model,
|
|
1727
|
+
endpoint: support.endpoint(call.providerId),
|
|
1728
|
+
entry: support.catalogue(call.providerId, call.model),
|
|
1729
|
+
stored
|
|
1730
|
+
}),
|
|
1731
|
+
...options.sleep === void 0 ? {} : { sleep: options.sleep }
|
|
1732
|
+
})
|
|
1733
|
+
},
|
|
1734
|
+
image: {
|
|
1735
|
+
models: (input) => [...IMAGE_GENERATION_MODELS, ...[...new Set(input.configuredModels.map((row) => row.id))].filter((id) => !IMAGE_GENERATION_MODELS.some((model) => model.id === id)).map(imageModelOf)],
|
|
1736
|
+
createPort: (call) => createImageGenerationPort({
|
|
1737
|
+
accountingDispatch: call.accountingDispatch,
|
|
1738
|
+
fetch,
|
|
1739
|
+
baseUrl: endpoints.codex,
|
|
1740
|
+
login: call.login,
|
|
1741
|
+
imageInfo,
|
|
1742
|
+
userAgent: USER_AGENT,
|
|
1743
|
+
model: call.model
|
|
1744
|
+
})
|
|
1745
|
+
}
|
|
1746
|
+
},
|
|
1747
|
+
normalizeListing: (input) => normalizeOffers(input),
|
|
1748
|
+
async listModels(probe) {
|
|
1749
|
+
const listed = await probes.listModels(probe);
|
|
1750
|
+
const isImage = (id) => IMAGE_GENERATION_MODELS.some((model) => model.id === id);
|
|
1751
|
+
const offers = listed.map(({ output, ...offer }) => isImage(offer.model) ? offer : {
|
|
1752
|
+
...offer,
|
|
1753
|
+
output
|
|
1754
|
+
});
|
|
1755
|
+
const ids = new Set(offers.map((offer) => offer.model));
|
|
1756
|
+
return { offers: [...offers, ...IMAGE_GENERATION_MODELS.filter((model) => !ids.has(model.id)).map((model) => ({
|
|
1757
|
+
model: model.id,
|
|
1758
|
+
name: model.label,
|
|
1759
|
+
input: ["text", "image"],
|
|
1760
|
+
output: [...model.outputKinds]
|
|
1761
|
+
}))] };
|
|
1762
|
+
},
|
|
1763
|
+
testConnection: (probe) => probes.testConnection(probe)
|
|
1764
|
+
};
|
|
1765
|
+
}
|
|
1766
|
+
//#endregion
|
|
1767
|
+
//#region src/callback.ts
|
|
1768
|
+
var CallbackPortInUse = class extends Error {
|
|
1769
|
+
constructor(port) {
|
|
1770
|
+
super(`port ${String(port)} is in use`);
|
|
1771
|
+
this.name = "CallbackPortInUse";
|
|
1772
|
+
}
|
|
1773
|
+
};
|
|
1774
|
+
function listen(port, host) {
|
|
1775
|
+
return new Promise((resolve, reject) => {
|
|
1776
|
+
const server = createServer();
|
|
1777
|
+
server.once("error", reject);
|
|
1778
|
+
server.listen({
|
|
1779
|
+
port,
|
|
1780
|
+
host,
|
|
1781
|
+
exclusive: true
|
|
1782
|
+
}, () => {
|
|
1783
|
+
server.off("error", reject);
|
|
1784
|
+
resolve(server);
|
|
1785
|
+
});
|
|
1786
|
+
});
|
|
1787
|
+
}
|
|
1788
|
+
function page(ok) {
|
|
1789
|
+
return `<!doctype html><html><head><meta charset="utf-8"><title>YaoGuang</title></head><body style="font-family:system-ui;margin:3rem"><p>${ok ? "Sign-in complete. You can close this page. \u767b\u5f55\u5b8c\u6210\uff0c\u53ef\u4ee5\u5173\u95ed\u6b64\u9875\u3002" : "Sign-in was not completed. You can close this page. \u767b\u5f55\u672a\u5b8c\u6210\uff0c\u53ef\u4ee5\u5173\u95ed\u6b64\u9875\u3002"}</p><script>setTimeout(function(){window.close()},300)<\/script></body></html>`;
|
|
1790
|
+
}
|
|
1791
|
+
function respond(res, status, ok) {
|
|
1792
|
+
res.writeHead(status, {
|
|
1793
|
+
"content-type": "text/html; charset=utf-8",
|
|
1794
|
+
"cache-control": "no-store"
|
|
1795
|
+
});
|
|
1796
|
+
res.end(page(ok));
|
|
1797
|
+
}
|
|
1798
|
+
async function openCallback(port, state) {
|
|
1799
|
+
const servers = [];
|
|
1800
|
+
let bound = port;
|
|
1801
|
+
try {
|
|
1802
|
+
const v4 = await listen(port, "127.0.0.1");
|
|
1803
|
+
servers.push(v4);
|
|
1804
|
+
bound = v4.address().port;
|
|
1805
|
+
try {
|
|
1806
|
+
servers.push(await listen(bound, "::1"));
|
|
1807
|
+
} catch (error) {
|
|
1808
|
+
const code = error.code;
|
|
1809
|
+
if (code !== "EADDRNOTAVAIL" && code !== "EAFNOSUPPORT") throw error;
|
|
1810
|
+
}
|
|
1811
|
+
} catch (error) {
|
|
1812
|
+
for (const server of servers) server.close();
|
|
1813
|
+
if (error.code === "EADDRINUSE") throw new CallbackPortInUse(bound);
|
|
1814
|
+
throw error;
|
|
1815
|
+
}
|
|
1816
|
+
let settle = () => {};
|
|
1817
|
+
const result = new Promise((resolve) => {
|
|
1818
|
+
settle = resolve;
|
|
1819
|
+
});
|
|
1820
|
+
let waiting;
|
|
1821
|
+
let taken = false;
|
|
1822
|
+
const handle = (req, res) => {
|
|
1823
|
+
const url = new URL(req.url ?? "/", `http://localhost:${String(bound)}`);
|
|
1824
|
+
if (req.method !== "GET" || url.pathname !== "/auth/callback") {
|
|
1825
|
+
res.writeHead(404).end();
|
|
1826
|
+
return;
|
|
1827
|
+
}
|
|
1828
|
+
if (url.searchParams.get("state") !== state || taken) {
|
|
1829
|
+
respond(res, 400, false);
|
|
1830
|
+
return;
|
|
1831
|
+
}
|
|
1832
|
+
taken = true;
|
|
1833
|
+
const error = url.searchParams.get("error");
|
|
1834
|
+
const code = url.searchParams.get("code");
|
|
1835
|
+
if (error !== null || code === null || code === "") {
|
|
1836
|
+
respond(res, 200, false);
|
|
1837
|
+
settle({
|
|
1838
|
+
kind: "error",
|
|
1839
|
+
error: error !== null && /^[a-z_]{1,64}$/.test(error) ? error : "error"
|
|
1840
|
+
});
|
|
1841
|
+
return;
|
|
1842
|
+
}
|
|
1843
|
+
waiting = res;
|
|
1844
|
+
settle({
|
|
1845
|
+
kind: "code",
|
|
1846
|
+
code
|
|
1847
|
+
});
|
|
1848
|
+
};
|
|
1849
|
+
for (const server of servers) server.on("request", handle);
|
|
1850
|
+
let closed = false;
|
|
1851
|
+
return {
|
|
1852
|
+
port: bound,
|
|
1853
|
+
result,
|
|
1854
|
+
finish(ok) {
|
|
1855
|
+
if (closed) return;
|
|
1856
|
+
closed = true;
|
|
1857
|
+
if (waiting !== void 0) respond(waiting, 200, ok);
|
|
1858
|
+
for (const server of servers) {
|
|
1859
|
+
server.close();
|
|
1860
|
+
server.closeAllConnections();
|
|
1861
|
+
}
|
|
1862
|
+
}
|
|
1863
|
+
};
|
|
1864
|
+
}
|
|
1865
|
+
//#endregion
|
|
1866
|
+
//#region src/login.ts
|
|
1867
|
+
function resultOf(tokens) {
|
|
1868
|
+
return {
|
|
1869
|
+
credential: JSON.stringify(tokens),
|
|
1870
|
+
account: tokens.account,
|
|
1871
|
+
refreshAfter: refreshAfterOf(tokens)
|
|
1872
|
+
};
|
|
1873
|
+
}
|
|
1874
|
+
function aborted(signal) {
|
|
1875
|
+
return new Promise((_, reject) => {
|
|
1876
|
+
const fail = () => reject(new LoginFailure("cancelled"));
|
|
1877
|
+
if (signal.aborted) fail();
|
|
1878
|
+
else signal.addEventListener("abort", fail, { once: true });
|
|
1879
|
+
});
|
|
1880
|
+
}
|
|
1881
|
+
function createLogin(deps) {
|
|
1882
|
+
let listening = false;
|
|
1883
|
+
async function browser(signal) {
|
|
1884
|
+
if (listening) throw new Error("another ChatGPT sign-in is in progress; finish or cancel it, or use device code sign-in");
|
|
1885
|
+
const codes = pkce();
|
|
1886
|
+
const state = newState();
|
|
1887
|
+
listening = true;
|
|
1888
|
+
let callback;
|
|
1889
|
+
try {
|
|
1890
|
+
callback = await openCallback(deps.callbackPort, state);
|
|
1891
|
+
} catch (error) {
|
|
1892
|
+
listening = false;
|
|
1893
|
+
if (error instanceof CallbackPortInUse) throw new Error(`port ${String(deps.callbackPort)} is in use (another ChatGPT sign-in, such as the Codex CLI, may be running); use device code sign-in instead`);
|
|
1894
|
+
throw error;
|
|
1895
|
+
}
|
|
1896
|
+
const redirectUri = `http://localhost:${String(callback.port)}${CALLBACK_PATH}`;
|
|
1897
|
+
const completion = (async () => {
|
|
1898
|
+
try {
|
|
1899
|
+
const answer = await Promise.race([callback.result, aborted(signal)]);
|
|
1900
|
+
if (answer.kind === "error") throw new LoginFailure("declined", answer.error);
|
|
1901
|
+
const tokens = await exchangeCode(deps.fetch, deps.endpoints, {
|
|
1902
|
+
code: answer.code,
|
|
1903
|
+
verifier: codes.verifier,
|
|
1904
|
+
redirectUri
|
|
1905
|
+
}, deps.now, signal);
|
|
1906
|
+
callback.finish(true);
|
|
1907
|
+
return resultOf(tokens);
|
|
1908
|
+
} catch (error) {
|
|
1909
|
+
callback.finish(false);
|
|
1910
|
+
throw error;
|
|
1911
|
+
} finally {
|
|
1912
|
+
listening = false;
|
|
1913
|
+
}
|
|
1914
|
+
})();
|
|
1915
|
+
completion.catch(() => {});
|
|
1916
|
+
return {
|
|
1917
|
+
url: authorizeUrl(deps.endpoints, redirectUri, codes, state),
|
|
1918
|
+
completion
|
|
1919
|
+
};
|
|
1920
|
+
}
|
|
1921
|
+
async function device(signal) {
|
|
1922
|
+
const headers = {
|
|
1923
|
+
"content-type": "application/json",
|
|
1924
|
+
"user-agent": deps.userAgent
|
|
1925
|
+
};
|
|
1926
|
+
let response;
|
|
1927
|
+
try {
|
|
1928
|
+
response = await deps.fetch(`${deps.endpoints.issuer}/api/accounts/deviceauth/usercode`, {
|
|
1929
|
+
method: "POST",
|
|
1930
|
+
headers,
|
|
1931
|
+
body: JSON.stringify({ client_id: CLIENT_ID }),
|
|
1932
|
+
signal
|
|
1933
|
+
});
|
|
1934
|
+
} catch {
|
|
1935
|
+
throw new Error("could not start device code sign-in (unreachable)");
|
|
1936
|
+
}
|
|
1937
|
+
if (!response.ok) throw new Error(`could not start device code sign-in (HTTP ${String(response.status)})`);
|
|
1938
|
+
const started = await response.json().catch(() => ({}));
|
|
1939
|
+
const deviceAuthId = started.device_auth_id;
|
|
1940
|
+
const userCode = started.user_code;
|
|
1941
|
+
if (typeof deviceAuthId !== "string" || typeof userCode !== "string") throw new Error("could not start device code sign-in (unreadable answer)");
|
|
1942
|
+
const named = Number(started.interval);
|
|
1943
|
+
const interval = (Number.isFinite(named) && named >= 0 ? named : 5) * 1e3 + deps.pollMarginMs;
|
|
1944
|
+
const completion = (async () => {
|
|
1945
|
+
for (;;) {
|
|
1946
|
+
await setTimeout(interval, void 0, { signal }).catch(() => {
|
|
1947
|
+
throw new LoginFailure("cancelled");
|
|
1948
|
+
});
|
|
1949
|
+
let poll;
|
|
1950
|
+
try {
|
|
1951
|
+
poll = await deps.fetch(`${deps.endpoints.issuer}/api/accounts/deviceauth/token`, {
|
|
1952
|
+
method: "POST",
|
|
1953
|
+
headers,
|
|
1954
|
+
body: JSON.stringify({
|
|
1955
|
+
device_auth_id: deviceAuthId,
|
|
1956
|
+
user_code: userCode
|
|
1957
|
+
}),
|
|
1958
|
+
signal
|
|
1959
|
+
});
|
|
1960
|
+
} catch {
|
|
1961
|
+
if (signal.aborted) throw new LoginFailure("cancelled");
|
|
1962
|
+
continue;
|
|
1963
|
+
}
|
|
1964
|
+
if (poll.status === 403 || poll.status === 404) continue;
|
|
1965
|
+
if (!poll.ok) throw new LoginFailure("device-failed", `HTTP ${String(poll.status)}`);
|
|
1966
|
+
const granted = await poll.json().catch(() => ({}));
|
|
1967
|
+
if (typeof granted.authorization_code !== "string" || typeof granted.code_verifier !== "string") throw new LoginFailure("device-failed", "unreadable answer");
|
|
1968
|
+
return resultOf(await exchangeCode(deps.fetch, deps.endpoints, {
|
|
1969
|
+
code: granted.authorization_code,
|
|
1970
|
+
verifier: granted.code_verifier,
|
|
1971
|
+
redirectUri: `${deps.endpoints.issuer}/deviceauth/callback`
|
|
1972
|
+
}, deps.now, signal));
|
|
1973
|
+
}
|
|
1974
|
+
})();
|
|
1975
|
+
completion.catch(() => {});
|
|
1976
|
+
return {
|
|
1977
|
+
url: `${deps.endpoints.issuer}/codex/device`,
|
|
1978
|
+
userCode,
|
|
1979
|
+
completion
|
|
1980
|
+
};
|
|
1981
|
+
}
|
|
1982
|
+
return {
|
|
1983
|
+
async refresh(credential, signal) {
|
|
1984
|
+
const before = parseStored(credential);
|
|
1985
|
+
if (before === void 0) throw new LoginFailure("expired");
|
|
1986
|
+
const outcome = await refreshTokens(deps.fetch, deps.endpoints, before, deps.now, signal);
|
|
1987
|
+
if (outcome.kind === "refused") throw new LoginFailure("expired");
|
|
1988
|
+
if (outcome.kind === "failed") throw new LoginFailure("exchange-failed", outcome.detail);
|
|
1989
|
+
return resultOf(outcome.tokens);
|
|
1990
|
+
},
|
|
1991
|
+
methods: [{
|
|
1992
|
+
id: "browser",
|
|
1993
|
+
label: "Sign in with a browser",
|
|
1994
|
+
kind: "browser"
|
|
1995
|
+
}, {
|
|
1996
|
+
id: "device",
|
|
1997
|
+
label: "Sign in with a device code",
|
|
1998
|
+
kind: "device"
|
|
1999
|
+
}],
|
|
2000
|
+
begin(method, signal) {
|
|
2001
|
+
if (method === "browser") return browser(signal);
|
|
2002
|
+
if (method === "device") return device(signal);
|
|
2003
|
+
return Promise.reject(/* @__PURE__ */ new Error(`no sign-in method "${method}"`));
|
|
2004
|
+
}
|
|
2005
|
+
};
|
|
2006
|
+
}
|
|
2007
|
+
//#endregion
|
|
2008
|
+
//#region src/resources.ts
|
|
2009
|
+
function failure(detail) {
|
|
2010
|
+
const code = detail === "Resource request failed" ? "source-failed" : "invalid-response";
|
|
2011
|
+
return Object.assign(new Error(code), {
|
|
2012
|
+
name: "ProviderResourceFailure",
|
|
2013
|
+
code,
|
|
2014
|
+
retryable: false
|
|
2015
|
+
});
|
|
2016
|
+
}
|
|
2017
|
+
const IMAGE_PREFIX = "additional-image_gen";
|
|
2018
|
+
const labels = (en, zh) => ({
|
|
2019
|
+
"en-US": en,
|
|
2020
|
+
"zh-CN": zh
|
|
2021
|
+
});
|
|
2022
|
+
function object(value) {
|
|
2023
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw failure("Invalid resource response");
|
|
2024
|
+
return value;
|
|
2025
|
+
}
|
|
2026
|
+
function decimal(value) {
|
|
2027
|
+
const text = typeof value === "number" && Number.isSafeInteger(value) ? String(value) : value;
|
|
2028
|
+
if (typeof text !== "string" || !/^(0|[1-9]\d*)(\.\d+)?$/.test(text)) throw failure("Invalid resource amount");
|
|
2029
|
+
const normalized = text.includes(".") ? text.replace(/0+$/, "").replace(/\.$/, "") : text;
|
|
2030
|
+
return normalized === "-0" ? "0" : normalized;
|
|
2031
|
+
}
|
|
2032
|
+
function date(value) {
|
|
2033
|
+
const ms = typeof value === "number" ? value * 1e3 : typeof value === "string" ? Date.parse(value) : NaN;
|
|
2034
|
+
return Number.isFinite(ms) ? new Date(ms).toISOString() : void 0;
|
|
2035
|
+
}
|
|
2036
|
+
const resourceCapability = {
|
|
2037
|
+
support: "supported",
|
|
2038
|
+
applicability: { kind: "fixed-endpoint" },
|
|
2039
|
+
sources: [{
|
|
2040
|
+
id: "usage",
|
|
2041
|
+
labels: labels("Usage", "\u7528\u91cf"),
|
|
2042
|
+
optional: false,
|
|
2043
|
+
requests: [{
|
|
2044
|
+
id: "usage",
|
|
2045
|
+
method: "GET",
|
|
2046
|
+
url: "https://chatgpt.com/backend-api/wham/usage"
|
|
2047
|
+
}],
|
|
2048
|
+
allowedHeaderNames: ["Authorization", "ChatGPT-Account-Id"]
|
|
2049
|
+
}, {
|
|
2050
|
+
id: "reset-details",
|
|
2051
|
+
labels: labels("Reset credit details", "\u91cd\u7f6e\u5238\u660e\u7ec6"),
|
|
2052
|
+
optional: true,
|
|
2053
|
+
requests: [{
|
|
2054
|
+
id: "reset-details",
|
|
2055
|
+
method: "GET",
|
|
2056
|
+
url: "https://chatgpt.com/backend-api/wham/rate-limit-reset-credits"
|
|
2057
|
+
}],
|
|
2058
|
+
allowedHeaderNames: ["Authorization", "ChatGPT-Account-Id"]
|
|
2059
|
+
}],
|
|
2060
|
+
presets: [
|
|
2061
|
+
{
|
|
2062
|
+
id: "subscription",
|
|
2063
|
+
labels: labels("Subscription", "\u8ba2\u9605\u989d\u5ea6"),
|
|
2064
|
+
sourceId: "usage",
|
|
2065
|
+
order: 0,
|
|
2066
|
+
recommended: true,
|
|
2067
|
+
format: "quota-windows",
|
|
2068
|
+
match: { group: "subscription-windows" }
|
|
2069
|
+
},
|
|
2070
|
+
{
|
|
2071
|
+
id: "credits",
|
|
2072
|
+
labels: labels("Credits", "\u79ef\u5206"),
|
|
2073
|
+
sourceId: "usage",
|
|
2074
|
+
order: 1,
|
|
2075
|
+
recommended: false,
|
|
2076
|
+
format: "amount",
|
|
2077
|
+
match: { resourceIds: ["credits"] }
|
|
2078
|
+
},
|
|
2079
|
+
{
|
|
2080
|
+
id: "reset-tickets",
|
|
2081
|
+
labels: labels("Reset credits", "\u91cd\u7f6e\u5238"),
|
|
2082
|
+
sourceId: "usage",
|
|
2083
|
+
order: 2,
|
|
2084
|
+
recommended: false,
|
|
2085
|
+
format: "entitlement-count",
|
|
2086
|
+
match: { resourceIds: ["reset-summary"] }
|
|
2087
|
+
}
|
|
2088
|
+
]
|
|
2089
|
+
};
|
|
2090
|
+
async function readResourceSource(input) {
|
|
2091
|
+
if (!["usage", "reset-details"].includes(input.sourceId) || input.endpointId !== "subscription") throw failure("Invalid resource source");
|
|
2092
|
+
if (!input.login) return {
|
|
2093
|
+
kind: "unavailable",
|
|
2094
|
+
reason: "auth-required"
|
|
2095
|
+
};
|
|
2096
|
+
const credential = await input.login.get(input.signal);
|
|
2097
|
+
const tokens = parseStored(credential.credential);
|
|
2098
|
+
if (!tokens) return {
|
|
2099
|
+
kind: "unavailable",
|
|
2100
|
+
reason: "auth-required"
|
|
2101
|
+
};
|
|
2102
|
+
const response = await input.queryJSON({
|
|
2103
|
+
requestId: input.sourceId,
|
|
2104
|
+
headers: {
|
|
2105
|
+
Authorization: `Bearer ${tokens.access}`,
|
|
2106
|
+
"ChatGPT-Account-Id": tokens.accountId
|
|
2107
|
+
}
|
|
2108
|
+
});
|
|
2109
|
+
if (response.status === 401) {
|
|
2110
|
+
input.login.expire(credential.credential);
|
|
2111
|
+
return {
|
|
2112
|
+
kind: "unavailable",
|
|
2113
|
+
reason: "auth-required"
|
|
2114
|
+
};
|
|
2115
|
+
}
|
|
2116
|
+
if (response.status === 403) return {
|
|
2117
|
+
kind: "unavailable",
|
|
2118
|
+
reason: "permission-denied"
|
|
2119
|
+
};
|
|
2120
|
+
if (response.status !== 200) throw failure("Resource request failed");
|
|
2121
|
+
return input.sourceId === "usage" ? usage(object(response.body)) : inventory(object(response.body));
|
|
2122
|
+
}
|
|
2123
|
+
function inventory(body) {
|
|
2124
|
+
if (!Array.isArray(body.credits)) throw failure("Invalid resource inventory");
|
|
2125
|
+
const entries = body.credits.slice(0, 100).map((value) => {
|
|
2126
|
+
const entry = object(value);
|
|
2127
|
+
if (typeof entry.id !== "string" || !/^[a-zA-Z0-9_-]{1,120}$/.test(entry.id)) throw failure("Invalid resource inventory");
|
|
2128
|
+
const expiry = date(entry.expires_at);
|
|
2129
|
+
const issued = date(entry.granted_at);
|
|
2130
|
+
return {
|
|
2131
|
+
id: entry.id,
|
|
2132
|
+
purpose: entry.reset_type === "primary" ? labels("Primary quota reset", "\u4e3b\u989d\u5ea6\u91cd\u7f6e") : labels("Quota reset", "\u989d\u5ea6\u91cd\u7f6e"),
|
|
2133
|
+
state: entry.status === "available" || entry.status === "used" || entry.status === "expired" ? entry.status : "unknown",
|
|
2134
|
+
...issued ? { issuedAt: issued } : {},
|
|
2135
|
+
expiry: expiry ? {
|
|
2136
|
+
kind: "at",
|
|
2137
|
+
at: expiry
|
|
2138
|
+
} : { kind: "unknown" }
|
|
2139
|
+
};
|
|
2140
|
+
});
|
|
2141
|
+
const count = body.available_count === void 0 ? String(body.credits.filter((value) => object(value).status === "available").length) : decimal(body.available_count);
|
|
2142
|
+
return {
|
|
2143
|
+
kind: "ready",
|
|
2144
|
+
resources: [{
|
|
2145
|
+
kind: "entitlement",
|
|
2146
|
+
id: "reset-inventory",
|
|
2147
|
+
group: "reset-tickets",
|
|
2148
|
+
labels: labels("Reset credit details", "\u91cd\u7f6e\u5238\u660e\u7ec6"),
|
|
2149
|
+
valueOrigin: body.available_count === void 0 ? "derived" : "reported",
|
|
2150
|
+
meaning: count === "0" ? "exhausted" : "available",
|
|
2151
|
+
availableCount: count,
|
|
2152
|
+
entries,
|
|
2153
|
+
entriesCompleteness: body.credits.length > 100 ? "limited" : "complete",
|
|
2154
|
+
relationships: [{
|
|
2155
|
+
kind: "details-of",
|
|
2156
|
+
resourceId: "reset-summary",
|
|
2157
|
+
unavailable: true
|
|
2158
|
+
}]
|
|
2159
|
+
}]
|
|
2160
|
+
};
|
|
2161
|
+
}
|
|
2162
|
+
function usage(body) {
|
|
2163
|
+
if (!("rate_limit" in body) && !("credits" in body) && !("rate_limit_reset_credits" in body)) throw failure("Invalid resource response");
|
|
2164
|
+
const resources = [];
|
|
2165
|
+
const rate = body.rate_limit == null ? {} : object(body.rate_limit);
|
|
2166
|
+
const rates = [{
|
|
2167
|
+
prefix: "subscription",
|
|
2168
|
+
group: "subscription-windows",
|
|
2169
|
+
rate
|
|
2170
|
+
}];
|
|
2171
|
+
if (body.code_review_rate_limit != null) rates.push({
|
|
2172
|
+
prefix: "code-review",
|
|
2173
|
+
group: "code-review-windows",
|
|
2174
|
+
rate: object(body.code_review_rate_limit)
|
|
2175
|
+
});
|
|
2176
|
+
if (body.additional_rate_limits != null) {
|
|
2177
|
+
if (!Array.isArray(body.additional_rate_limits)) throw failure("Invalid resource response");
|
|
2178
|
+
for (const value of body.additional_rate_limits) {
|
|
2179
|
+
const extra = object(value);
|
|
2180
|
+
const feature = extra.metered_feature;
|
|
2181
|
+
if (typeof feature !== "string" || !/^[a-zA-Z0-9_-]{1,60}$/.test(feature)) throw failure("Invalid resource scope");
|
|
2182
|
+
rates.push({
|
|
2183
|
+
prefix: `additional-${feature}`,
|
|
2184
|
+
group: "additional-windows",
|
|
2185
|
+
rate: object(extra.rate_limit)
|
|
2186
|
+
});
|
|
2187
|
+
}
|
|
2188
|
+
}
|
|
2189
|
+
for (const item of rates) for (const key of ["primary_window", "secondary_window"]) {
|
|
2190
|
+
if (item.rate[key] == null) continue;
|
|
2191
|
+
const window = object(item.rate[key]);
|
|
2192
|
+
const duration = window.limit_window_seconds;
|
|
2193
|
+
if (duration !== void 0 && (typeof duration !== "number" || !Number.isSafeInteger(duration) || duration <= 0)) throw failure("Invalid resource window");
|
|
2194
|
+
const percent = window.used_percent;
|
|
2195
|
+
if (percent !== void 0 && (typeof percent !== "number" || !Number.isFinite(percent) || percent < 0 || percent > 100)) throw failure("Invalid resource percentage");
|
|
2196
|
+
const reset = date(window.reset_at);
|
|
2197
|
+
resources.push({
|
|
2198
|
+
kind: "quota",
|
|
2199
|
+
id: `${item.prefix}-${duration ?? key}`,
|
|
2200
|
+
group: item.group,
|
|
2201
|
+
labels: item.prefix === "subscription" ? labels("Subscription quota", "\u8ba2\u9605\u989d\u5ea6") : item.prefix === "code-review" ? labels("Code review quota", "\u4ee3\u7801\u5ba1\u67e5\u989d\u5ea6") : item.prefix === IMAGE_PREFIX ? labels("Image generation quota", "\u751f\u56fe\u989d\u5ea6") : labels("Additional quota", "\u9644\u52a0\u989d\u5ea6"),
|
|
2202
|
+
...item.prefix.startsWith("additional-") ? { scope: { product: item.prefix.slice(11) } } : {},
|
|
2203
|
+
valueOrigin: "reported",
|
|
2204
|
+
meaning: percent === void 0 ? "unknown" : percent === 100 ? "exhausted" : "available",
|
|
2205
|
+
window: {
|
|
2206
|
+
...typeof duration === "number" ? { durationSeconds: duration } : {},
|
|
2207
|
+
reset: reset ? {
|
|
2208
|
+
kind: "fixed",
|
|
2209
|
+
at: reset
|
|
2210
|
+
} : { kind: "unknown" }
|
|
2211
|
+
},
|
|
2212
|
+
...typeof percent === "number" ? { usedPercent: percent } : {}
|
|
2213
|
+
});
|
|
2214
|
+
}
|
|
2215
|
+
if (body.credits != null) {
|
|
2216
|
+
const credit = object(body.credits);
|
|
2217
|
+
if (credit.balance != null) resources.push({
|
|
2218
|
+
kind: "balance",
|
|
2219
|
+
id: "credits",
|
|
2220
|
+
group: "credits",
|
|
2221
|
+
labels: labels("Credits", "\u79ef\u5206"),
|
|
2222
|
+
valueOrigin: "reported",
|
|
2223
|
+
meaning: credit.unlimited === true ? "unlimited" : Number(decimal(credit.balance)) === 0 ? "exhausted" : "available",
|
|
2224
|
+
remaining: {
|
|
2225
|
+
value: decimal(credit.balance),
|
|
2226
|
+
unit: {
|
|
2227
|
+
kind: "credit",
|
|
2228
|
+
namespace: "chatgpt",
|
|
2229
|
+
label: "Credits"
|
|
2230
|
+
}
|
|
2231
|
+
}
|
|
2232
|
+
});
|
|
2233
|
+
}
|
|
2234
|
+
if (body.rate_limit_reset_credits != null) {
|
|
2235
|
+
const summary = object(body.rate_limit_reset_credits);
|
|
2236
|
+
if (summary.available_count !== void 0) resources.push({
|
|
2237
|
+
kind: "entitlement",
|
|
2238
|
+
id: "reset-summary",
|
|
2239
|
+
group: "reset-tickets",
|
|
2240
|
+
labels: labels("Reset credits", "\u91cd\u7f6e\u5238"),
|
|
2241
|
+
valueOrigin: "reported",
|
|
2242
|
+
meaning: Number(decimal(summary.available_count)) === 0 ? "exhausted" : "available",
|
|
2243
|
+
availableCount: decimal(summary.available_count),
|
|
2244
|
+
...summary.applicable_available_count !== void 0 ? { applicableCount: decimal(summary.applicable_available_count) } : {}
|
|
2245
|
+
});
|
|
2246
|
+
}
|
|
2247
|
+
const plans = {
|
|
2248
|
+
pro: labels("Pro", "Pro"),
|
|
2249
|
+
plus: labels("Plus", "Plus"),
|
|
2250
|
+
free: labels("Free", "\u514d\u8d39"),
|
|
2251
|
+
team: labels("Team", "\u56e2\u961f"),
|
|
2252
|
+
business: labels("Business", "\u4f01\u4e1a"),
|
|
2253
|
+
enterprise: labels("Enterprise", "\u4f01\u4e1a")
|
|
2254
|
+
};
|
|
2255
|
+
const planId = typeof body.plan_type === "string" ? body.plan_type : "";
|
|
2256
|
+
const planLabels = Object.hasOwn(plans, planId) ? plans[planId] : void 0;
|
|
2257
|
+
const plan = planLabels ? {
|
|
2258
|
+
id: planId,
|
|
2259
|
+
labels: planLabels
|
|
2260
|
+
} : void 0;
|
|
2261
|
+
return {
|
|
2262
|
+
kind: "ready",
|
|
2263
|
+
resources,
|
|
2264
|
+
...plan ? { plan } : {},
|
|
2265
|
+
restrictions: [...typeof rate.allowed === "boolean" ? [{
|
|
2266
|
+
id: "usage-blocked",
|
|
2267
|
+
labels: labels("Usage blocked", "\u7528\u91cf\u53d7\u9650"),
|
|
2268
|
+
active: !rate.allowed && rate.limit_reached !== true
|
|
2269
|
+
}] : [], ...typeof rate.limit_reached === "boolean" ? [{
|
|
2270
|
+
id: "limit-reached",
|
|
2271
|
+
labels: labels("Limit reached", "\u5df2\u8fbe\u4e0a\u9650"),
|
|
2272
|
+
active: rate.limit_reached
|
|
2273
|
+
}] : []]
|
|
2274
|
+
};
|
|
2275
|
+
}
|
|
2276
|
+
//#endregion
|
|
2277
|
+
//#region src/type.ts
|
|
2278
|
+
const TYPE = "chatgpt";
|
|
2279
|
+
const LOGIN_FIELD = "account";
|
|
2280
|
+
function chatgptProviderType(fetch, options = {}) {
|
|
2281
|
+
return {
|
|
2282
|
+
type: TYPE,
|
|
2283
|
+
listingContractVersion: "subscription-capacity-v1",
|
|
2284
|
+
modelFacts,
|
|
2285
|
+
credentialPrincipal: (credential) => parseStored(credential)?.accountId,
|
|
2286
|
+
readResourceSource,
|
|
2287
|
+
label: "ChatGPT subscription",
|
|
2288
|
+
fields: [{
|
|
2289
|
+
key: LOGIN_FIELD,
|
|
2290
|
+
kind: "login",
|
|
2291
|
+
label: "ChatGPT account",
|
|
2292
|
+
required: true
|
|
2293
|
+
}],
|
|
2294
|
+
endpoints: [{
|
|
2295
|
+
id: "subscription",
|
|
2296
|
+
resourceCapability,
|
|
2297
|
+
label: "ChatGPT subscription",
|
|
2298
|
+
capabilities: {
|
|
2299
|
+
chat: {
|
|
2300
|
+
protocolIds: ["chatgpt-subscription"],
|
|
2301
|
+
defaultProtocolId: "chatgpt-subscription"
|
|
2302
|
+
},
|
|
2303
|
+
image: {
|
|
2304
|
+
protocolIds: ["chatgpt-subscription"],
|
|
2305
|
+
defaultProtocolId: "chatgpt-subscription"
|
|
2306
|
+
}
|
|
2307
|
+
}
|
|
2308
|
+
}],
|
|
2309
|
+
login: createLogin({
|
|
2310
|
+
fetch,
|
|
2311
|
+
endpoints: options.endpoints ?? ENDPOINTS,
|
|
2312
|
+
now: options.now ?? Date.now,
|
|
2313
|
+
callbackPort: options.callbackPort ?? 1455,
|
|
2314
|
+
pollMarginMs: options.pollMarginMs ?? 3e3,
|
|
2315
|
+
userAgent: "yaoguang"
|
|
2316
|
+
}),
|
|
2317
|
+
catalog
|
|
2318
|
+
};
|
|
2319
|
+
}
|
|
2320
|
+
//#endregion
|
|
2321
|
+
//#region src/index.ts
|
|
2322
|
+
const plugin = {
|
|
2323
|
+
name: "@eum-agent/llm-provider-chatgpt",
|
|
2324
|
+
requires: [
|
|
2325
|
+
"network",
|
|
2326
|
+
"openai-responses-codec",
|
|
2327
|
+
"file-media"
|
|
2328
|
+
],
|
|
2329
|
+
optionalServices: ["model-support"],
|
|
2330
|
+
apply(ctx) {
|
|
2331
|
+
const support = lazySupport(() => ctx.services.find("model-support"));
|
|
2332
|
+
const network = ctx.services.get("network");
|
|
2333
|
+
ctx.modelProtocols.register(chatgptProtocolType(support, network.fetch, ctx.services.get("openai-responses-codec"), {}, ctx.services.get("file-media").imageInfo));
|
|
2334
|
+
ctx.modelProviders.register(chatgptProviderType(network.fetch));
|
|
2335
|
+
}
|
|
2336
|
+
};
|
|
2337
|
+
//#endregion
|
|
2338
|
+
export { plugin as default };
|