@shuind/dsh-codex-connect 0.0.0-stage → 0.2.1
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/INSTALL.md +349 -0
- package/LICENSE +202 -0
- package/MIGRATION.md +101 -0
- package/NOTICE +26 -0
- package/README.md +71 -2
- package/VERSIONING.md +69 -0
- package/cordis.patch.yml +9 -0
- package/docs/README.zh.md +3 -0
- package/docs/assets/composer-capabilities.jpg +0 -0
- package/docs/assets/en/hero.jpg +0 -0
- package/docs/assets/en/image-generation.png +0 -0
- package/docs/assets/en/model-selector.jpg +0 -0
- package/docs/assets/en/oauth-status.jpg +0 -0
- package/docs/assets/en/plugin-configuration.jpg +0 -0
- package/docs/assets/en/plugin-entry.jpg +0 -0
- package/docs/assets/hero.jpg +0 -0
- package/docs/assets/model-selector.jpg +0 -0
- package/docs/assets/oauth-status.jpg +0 -0
- package/docs/assets/plugin-configuration.jpg +0 -0
- package/docs/assets/zh/hero.jpg +0 -0
- package/docs/assets/zh/image-generation.png +0 -0
- package/docs/assets/zh/model-selector.jpg +0 -0
- package/docs/assets/zh/oauth-status.jpg +0 -0
- package/docs/assets/zh/plugin-configuration.jpg +0 -0
- package/docs/assets/zh/plugin-entry.jpg +0 -0
- package/docs/design.md +61 -0
- package/docs/design.zh.md +39 -0
- package/docs/licenses/pi-ai-oauth.txt +21 -0
- package/docs/licenses/standalone-cli.txt +115 -0
- package/docs/preflight-activity.md +42 -0
- package/docs/preflight-activity.zh.md +42 -0
- package/docs/quota-tool.md +46 -0
- package/docs/reference.md +240 -0
- package/docs/reference.zh.md +240 -0
- package/docs/skills/codex-quota-awareness/SKILL.md +12 -0
- package/lib/bin.js +2442 -0
- package/lib/client.js +6752 -0
- package/lib/index.d.ts +631 -0
- package/lib/index.js +7162 -0
- package/lib/models-DUIoH1lI.js +1763 -0
- package/lib/openai-codex-responses-CzSuDkhU.js +3452 -0
- package/package.json +234 -4
package/lib/bin.js
ADDED
|
@@ -0,0 +1,2442 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { g as lazyApi, i as createProvider, r as createModels, y as __require } from "./models-DUIoH1lI.js";
|
|
3
|
+
import { spawn } from "node:child_process";
|
|
4
|
+
import { realpathSync } from "node:fs";
|
|
5
|
+
import { createInterface } from "node:readline/promises";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
8
|
+
import { lstat, mkdir, open, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
|
|
9
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
10
|
+
import { setTimeout as setTimeout$1 } from "node:timers/promises";
|
|
11
|
+
import { homedir } from "node:os";
|
|
12
|
+
import { Buffer as Buffer$1 } from "node:buffer";
|
|
13
|
+
const PUBLIC_MESSAGES = /* @__PURE__ */ new Set([
|
|
14
|
+
...Object.values({
|
|
15
|
+
MISSING_CREDENTIAL: "OpenAI Codex request account is unavailable. Please select an account or sign in again.",
|
|
16
|
+
AUTH_FAILED: "OpenAI Codex operation failed. Please try again.",
|
|
17
|
+
REAUTH_REQUIRED: "OpenAI Codex authorization must be renewed",
|
|
18
|
+
ABORTED: "OpenAI Codex request cancelled."
|
|
19
|
+
}),
|
|
20
|
+
"ChatGPT authorization expired. Please sign in again.",
|
|
21
|
+
"OpenAI Codex sign-in cancelled",
|
|
22
|
+
"OpenAI Codex plugin disposed",
|
|
23
|
+
"openai-codex: account not found",
|
|
24
|
+
"openai-codex: replacement account not found",
|
|
25
|
+
"openai-codex: removing the active account requires replacementAccountKey",
|
|
26
|
+
"openai-codex: replacementAccountKey is only valid when removing the active account"
|
|
27
|
+
]);
|
|
28
|
+
/** Return a bounded diagnostic from a closed vocabulary, never upstream response text. */
|
|
29
|
+
function publicAuthError(error) {
|
|
30
|
+
const message = error instanceof Error ? error.message : "";
|
|
31
|
+
if (PUBLIC_MESSAGES.has(message)) return message;
|
|
32
|
+
if (/^OpenAI Codex usage request failed with HTTP [1-5][0-9]{2}$/u.test(message)) return message;
|
|
33
|
+
return "OpenAI Codex operation failed. Please try again.";
|
|
34
|
+
}
|
|
35
|
+
// node_modules/.pnpm/@earendil-works+pi-ai@1.6.0_@aws-sdk+credential-provider-node@3.972.98_@smithy+signatur_3204f39f3ad26528ec3165fb3f7546e0/node_modules/@earendil-works/pi-ai/dist/auth/helpers.js
|
|
36
|
+
/**
|
|
37
|
+
* Wraps a dynamically imported `OAuthAuth` so provider definitions can
|
|
38
|
+
* advertise OAuth without importing the implementation. The flow loads on
|
|
39
|
+
* first `login`/`refresh`/`toAuth` call; callers keep Node-only flow code out
|
|
40
|
+
* of bundles by loading through a bundler-opaque dynamic import (variable
|
|
41
|
+
* specifier, see the bedrock lazy wrapper).
|
|
42
|
+
*/
|
|
43
|
+
function lazyOAuth(input) {
|
|
44
|
+
let promise;
|
|
45
|
+
const loaded = () => {
|
|
46
|
+
promise ??= input.load();
|
|
47
|
+
return promise;
|
|
48
|
+
};
|
|
49
|
+
return {
|
|
50
|
+
name: input.name,
|
|
51
|
+
isSubscription: input.isSubscription,
|
|
52
|
+
loginLabel: input.loginLabel,
|
|
53
|
+
login: async (interaction, options) => (await loaded()).login(interaction, options),
|
|
54
|
+
refresh: async (credential, signal) => (await loaded()).refresh(credential, signal),
|
|
55
|
+
toAuth: async (credential) => (await loaded()).toAuth(credential)
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
// node_modules/.pnpm/@earendil-works+pi-ai@1.6.0_@aws-sdk+credential-provider-node@3.972.98_@smithy+signatur_3204f39f3ad26528ec3165fb3f7546e0/node_modules/@earendil-works/pi-ai/dist/api/openai-codex-responses.lazy.js
|
|
59
|
+
const openAICodexResponsesApi = () => lazyApi(() => import("./openai-codex-responses-CzSuDkhU.js"));
|
|
60
|
+
// node_modules/.pnpm/@earendil-works+pi-ai@1.6.0_@aws-sdk+credential-provider-node@3.972.98_@smithy+signatur_3204f39f3ad26528ec3165fb3f7546e0/node_modules/@earendil-works/pi-ai/dist/auth/oauth/load.js
|
|
61
|
+
var __rewriteRelativeImportExtension = function(path, preserveJsx) {
|
|
62
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function(m, tsx, d, ext, cm) {
|
|
63
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : d + ext + "." + cm.toLowerCase() + "js";
|
|
64
|
+
});
|
|
65
|
+
return path;
|
|
66
|
+
};
|
|
67
|
+
/**
|
|
68
|
+
* Loads an OAuth flow module through a variable specifier so bundlers cannot
|
|
69
|
+
* follow the import into Node-only flow code (`node:http` callback servers,
|
|
70
|
+
* `node:crypto` PKCE). The `.ts`/`.js` rewrite keeps the trick working from
|
|
71
|
+
* both source and built output. The specifier is resolved against this
|
|
72
|
+
* module's URL, not left relative: a bundler inlining this file (Chord's
|
|
73
|
+
* worker base) keeps the variable import, which would otherwise resolve
|
|
74
|
+
* against the bundle's location.
|
|
75
|
+
*/
|
|
76
|
+
const importOAuthModule = (specifier) => {
|
|
77
|
+
const runtimeSpecifier = import.meta.url.endsWith(".js") ? specifier.replace(/\.ts$/, ".js") : specifier;
|
|
78
|
+
return import(__rewriteRelativeImportExtension(new URL(runtimeSpecifier, import.meta.url).href));
|
|
79
|
+
};
|
|
80
|
+
const loadOpenAICodexOAuth = async () => {
|
|
81
|
+
return (await importOAuthModule("./openai-codex.ts")).openaiCodexOAuth;
|
|
82
|
+
};
|
|
83
|
+
// node_modules/.pnpm/@earendil-works+pi-ai@1.6.0_@aws-sdk+credential-provider-node@3.972.98_@smithy+signatur_3204f39f3ad26528ec3165fb3f7546e0/node_modules/@earendil-works/pi-ai/dist/providers/data/openai-codex.json
|
|
84
|
+
var openai_codex_default = { "openai-codex-responses": {
|
|
85
|
+
"chat:gpt-5.6-luna": {
|
|
86
|
+
"id": "gpt-5.6-luna",
|
|
87
|
+
"name": "GPT-5.6 Luna",
|
|
88
|
+
"api": "openai-codex-responses",
|
|
89
|
+
"provider": "openai-codex",
|
|
90
|
+
"baseUrl": "https://chatgpt.com/backend-api",
|
|
91
|
+
"reasoning": true,
|
|
92
|
+
"input": ["text", "image"],
|
|
93
|
+
"cost": {
|
|
94
|
+
"input": .2,
|
|
95
|
+
"output": 1.2,
|
|
96
|
+
"cacheRead": .02,
|
|
97
|
+
"cacheWrite": .25,
|
|
98
|
+
"tiers": [{
|
|
99
|
+
"inputTokensAbove": 272e3,
|
|
100
|
+
"input": .4,
|
|
101
|
+
"output": 1.8,
|
|
102
|
+
"cacheRead": .04,
|
|
103
|
+
"cacheWrite": .5
|
|
104
|
+
}]
|
|
105
|
+
},
|
|
106
|
+
"contextWindow": 272e3,
|
|
107
|
+
"maxTokens": 128e3,
|
|
108
|
+
"thinkingLevelMap": {
|
|
109
|
+
"xhigh": "xhigh",
|
|
110
|
+
"max": "max",
|
|
111
|
+
"minimal": "low"
|
|
112
|
+
},
|
|
113
|
+
"compat": {
|
|
114
|
+
"supportsOpenAIGrammarTools": true,
|
|
115
|
+
"supportsAdditionalTools": true,
|
|
116
|
+
"supportsToolSearch": true,
|
|
117
|
+
"supportsMidConvoSystemMessages": true
|
|
118
|
+
},
|
|
119
|
+
"inputLimits": { "images": { "resize": {
|
|
120
|
+
"maxWidth": 2e3,
|
|
121
|
+
"maxHeight": 2e3,
|
|
122
|
+
"maxBytes": 4718592,
|
|
123
|
+
"jpegQuality": 80
|
|
124
|
+
} } },
|
|
125
|
+
"type": "chat"
|
|
126
|
+
},
|
|
127
|
+
"chat:gpt-5.6-sol": {
|
|
128
|
+
"id": "gpt-5.6-sol",
|
|
129
|
+
"name": "GPT-5.6 Sol",
|
|
130
|
+
"api": "openai-codex-responses",
|
|
131
|
+
"provider": "openai-codex",
|
|
132
|
+
"baseUrl": "https://chatgpt.com/backend-api",
|
|
133
|
+
"reasoning": true,
|
|
134
|
+
"input": ["text", "image"],
|
|
135
|
+
"cost": {
|
|
136
|
+
"input": 4,
|
|
137
|
+
"output": 20,
|
|
138
|
+
"cacheRead": .4,
|
|
139
|
+
"cacheWrite": 5,
|
|
140
|
+
"tiers": [{
|
|
141
|
+
"inputTokensAbove": 272e3,
|
|
142
|
+
"input": 8,
|
|
143
|
+
"output": 30,
|
|
144
|
+
"cacheRead": .8,
|
|
145
|
+
"cacheWrite": 10
|
|
146
|
+
}]
|
|
147
|
+
},
|
|
148
|
+
"contextWindow": 272e3,
|
|
149
|
+
"maxTokens": 128e3,
|
|
150
|
+
"thinkingLevelMap": {
|
|
151
|
+
"xhigh": "xhigh",
|
|
152
|
+
"max": "max",
|
|
153
|
+
"minimal": "low"
|
|
154
|
+
},
|
|
155
|
+
"compat": {
|
|
156
|
+
"supportsOpenAIGrammarTools": true,
|
|
157
|
+
"supportsAdditionalTools": true,
|
|
158
|
+
"supportsToolSearch": true,
|
|
159
|
+
"supportsMidConvoSystemMessages": true
|
|
160
|
+
},
|
|
161
|
+
"inputLimits": { "images": { "resize": {
|
|
162
|
+
"maxWidth": 2e3,
|
|
163
|
+
"maxHeight": 2e3,
|
|
164
|
+
"maxBytes": 4718592,
|
|
165
|
+
"jpegQuality": 80
|
|
166
|
+
} } },
|
|
167
|
+
"type": "chat"
|
|
168
|
+
},
|
|
169
|
+
"chat:gpt-5.6-terra": {
|
|
170
|
+
"id": "gpt-5.6-terra",
|
|
171
|
+
"name": "GPT-5.6 Terra",
|
|
172
|
+
"api": "openai-codex-responses",
|
|
173
|
+
"provider": "openai-codex",
|
|
174
|
+
"baseUrl": "https://chatgpt.com/backend-api",
|
|
175
|
+
"reasoning": true,
|
|
176
|
+
"input": ["text", "image"],
|
|
177
|
+
"cost": {
|
|
178
|
+
"input": 2,
|
|
179
|
+
"output": 12,
|
|
180
|
+
"cacheRead": .2,
|
|
181
|
+
"cacheWrite": 2.5,
|
|
182
|
+
"tiers": [{
|
|
183
|
+
"inputTokensAbove": 272e3,
|
|
184
|
+
"input": 4,
|
|
185
|
+
"output": 18,
|
|
186
|
+
"cacheRead": .4,
|
|
187
|
+
"cacheWrite": 5
|
|
188
|
+
}]
|
|
189
|
+
},
|
|
190
|
+
"contextWindow": 272e3,
|
|
191
|
+
"maxTokens": 128e3,
|
|
192
|
+
"thinkingLevelMap": {
|
|
193
|
+
"xhigh": "xhigh",
|
|
194
|
+
"max": "max",
|
|
195
|
+
"minimal": "low"
|
|
196
|
+
},
|
|
197
|
+
"compat": {
|
|
198
|
+
"supportsOpenAIGrammarTools": true,
|
|
199
|
+
"supportsAdditionalTools": true,
|
|
200
|
+
"supportsToolSearch": true,
|
|
201
|
+
"supportsMidConvoSystemMessages": true
|
|
202
|
+
},
|
|
203
|
+
"inputLimits": { "images": { "resize": {
|
|
204
|
+
"maxWidth": 2e3,
|
|
205
|
+
"maxHeight": 2e3,
|
|
206
|
+
"maxBytes": 4718592,
|
|
207
|
+
"jpegQuality": 80
|
|
208
|
+
} } },
|
|
209
|
+
"type": "chat"
|
|
210
|
+
},
|
|
211
|
+
"chat:gpt-6-astra": {
|
|
212
|
+
"id": "gpt-6-astra",
|
|
213
|
+
"name": "GPT-6 Astra",
|
|
214
|
+
"api": "openai-codex-responses",
|
|
215
|
+
"provider": "openai-codex",
|
|
216
|
+
"baseUrl": "https://chatgpt.com/backend-api",
|
|
217
|
+
"reasoning": true,
|
|
218
|
+
"input": ["text", "image"],
|
|
219
|
+
"cost": {
|
|
220
|
+
"input": 10,
|
|
221
|
+
"output": 50,
|
|
222
|
+
"cacheRead": 1,
|
|
223
|
+
"cacheWrite": 12.5,
|
|
224
|
+
"tiers": [{
|
|
225
|
+
"inputTokensAbove": 272e3,
|
|
226
|
+
"input": 20,
|
|
227
|
+
"output": 75,
|
|
228
|
+
"cacheRead": 2,
|
|
229
|
+
"cacheWrite": 25
|
|
230
|
+
}]
|
|
231
|
+
},
|
|
232
|
+
"contextWindow": 272e3,
|
|
233
|
+
"maxTokens": 128e3,
|
|
234
|
+
"thinkingLevelMap": {
|
|
235
|
+
"off": null,
|
|
236
|
+
"minimal": "low",
|
|
237
|
+
"low": "low",
|
|
238
|
+
"medium": "medium",
|
|
239
|
+
"high": "high",
|
|
240
|
+
"xhigh": "xhigh",
|
|
241
|
+
"max": "max"
|
|
242
|
+
},
|
|
243
|
+
"compat": {
|
|
244
|
+
"supportsOpenAIGrammarTools": true,
|
|
245
|
+
"supportsAdditionalTools": true,
|
|
246
|
+
"supportsToolSearch": true,
|
|
247
|
+
"supportsMidConvoSystemMessages": true,
|
|
248
|
+
"supportsMidConvoEffort": true
|
|
249
|
+
},
|
|
250
|
+
"inputLimits": { "images": { "resize": {
|
|
251
|
+
"maxWidth": 2e3,
|
|
252
|
+
"maxHeight": 2e3,
|
|
253
|
+
"maxBytes": 4718592,
|
|
254
|
+
"jpegQuality": 80
|
|
255
|
+
} } },
|
|
256
|
+
"type": "chat"
|
|
257
|
+
},
|
|
258
|
+
"chat:gpt-6-luna": {
|
|
259
|
+
"id": "gpt-6-luna",
|
|
260
|
+
"name": "GPT-6 Luna",
|
|
261
|
+
"api": "openai-codex-responses",
|
|
262
|
+
"provider": "openai-codex",
|
|
263
|
+
"baseUrl": "https://chatgpt.com/backend-api",
|
|
264
|
+
"reasoning": true,
|
|
265
|
+
"input": ["text", "image"],
|
|
266
|
+
"cost": {
|
|
267
|
+
"input": .1,
|
|
268
|
+
"output": .5,
|
|
269
|
+
"cacheRead": .01,
|
|
270
|
+
"cacheWrite": .125,
|
|
271
|
+
"tiers": [{
|
|
272
|
+
"inputTokensAbove": 272e3,
|
|
273
|
+
"input": .2,
|
|
274
|
+
"output": .75,
|
|
275
|
+
"cacheRead": .02,
|
|
276
|
+
"cacheWrite": .25
|
|
277
|
+
}]
|
|
278
|
+
},
|
|
279
|
+
"contextWindow": 272e3,
|
|
280
|
+
"maxTokens": 128e3,
|
|
281
|
+
"thinkingLevelMap": {
|
|
282
|
+
"off": "none",
|
|
283
|
+
"minimal": "low",
|
|
284
|
+
"low": "low",
|
|
285
|
+
"medium": "medium",
|
|
286
|
+
"high": "high",
|
|
287
|
+
"xhigh": "xhigh",
|
|
288
|
+
"max": "max"
|
|
289
|
+
},
|
|
290
|
+
"compat": {
|
|
291
|
+
"supportsOpenAIGrammarTools": true,
|
|
292
|
+
"supportsAdditionalTools": true,
|
|
293
|
+
"supportsToolSearch": true,
|
|
294
|
+
"supportsMidConvoSystemMessages": true,
|
|
295
|
+
"supportsMidConvoEffort": true
|
|
296
|
+
},
|
|
297
|
+
"inputLimits": { "images": { "resize": {
|
|
298
|
+
"maxWidth": 2e3,
|
|
299
|
+
"maxHeight": 2e3,
|
|
300
|
+
"maxBytes": 4718592,
|
|
301
|
+
"jpegQuality": 80
|
|
302
|
+
} } },
|
|
303
|
+
"type": "chat"
|
|
304
|
+
},
|
|
305
|
+
"chat:gpt-6-sol": {
|
|
306
|
+
"id": "gpt-6-sol",
|
|
307
|
+
"name": "GPT-6 Sol",
|
|
308
|
+
"api": "openai-codex-responses",
|
|
309
|
+
"provider": "openai-codex",
|
|
310
|
+
"baseUrl": "https://chatgpt.com/backend-api",
|
|
311
|
+
"reasoning": true,
|
|
312
|
+
"input": ["text", "image"],
|
|
313
|
+
"cost": {
|
|
314
|
+
"input": 2,
|
|
315
|
+
"output": 10,
|
|
316
|
+
"cacheRead": .2,
|
|
317
|
+
"cacheWrite": 2.5,
|
|
318
|
+
"tiers": [{
|
|
319
|
+
"inputTokensAbove": 272e3,
|
|
320
|
+
"input": 4,
|
|
321
|
+
"output": 15,
|
|
322
|
+
"cacheRead": .4,
|
|
323
|
+
"cacheWrite": 5
|
|
324
|
+
}]
|
|
325
|
+
},
|
|
326
|
+
"contextWindow": 272e3,
|
|
327
|
+
"maxTokens": 128e3,
|
|
328
|
+
"thinkingLevelMap": {
|
|
329
|
+
"off": "none",
|
|
330
|
+
"minimal": "low",
|
|
331
|
+
"low": "low",
|
|
332
|
+
"medium": "medium",
|
|
333
|
+
"high": "high",
|
|
334
|
+
"xhigh": "xhigh",
|
|
335
|
+
"max": "max"
|
|
336
|
+
},
|
|
337
|
+
"compat": {
|
|
338
|
+
"supportsOpenAIGrammarTools": true,
|
|
339
|
+
"supportsAdditionalTools": true,
|
|
340
|
+
"supportsToolSearch": true,
|
|
341
|
+
"supportsMidConvoSystemMessages": true,
|
|
342
|
+
"supportsMidConvoEffort": true
|
|
343
|
+
},
|
|
344
|
+
"inputLimits": { "images": { "resize": {
|
|
345
|
+
"maxWidth": 2e3,
|
|
346
|
+
"maxHeight": 2e3,
|
|
347
|
+
"maxBytes": 4718592,
|
|
348
|
+
"jpegQuality": 80
|
|
349
|
+
} } },
|
|
350
|
+
"type": "chat"
|
|
351
|
+
},
|
|
352
|
+
"chat:gpt-6.1-sol": {
|
|
353
|
+
"id": "gpt-6.1-sol",
|
|
354
|
+
"name": "GPT-6.1 Sol",
|
|
355
|
+
"api": "openai-codex-responses",
|
|
356
|
+
"provider": "openai-codex",
|
|
357
|
+
"baseUrl": "https://chatgpt.com/backend-api",
|
|
358
|
+
"reasoning": true,
|
|
359
|
+
"input": ["text", "image"],
|
|
360
|
+
"cost": {
|
|
361
|
+
"input": 2,
|
|
362
|
+
"output": 10,
|
|
363
|
+
"cacheRead": .1,
|
|
364
|
+
"cacheWrite": 2.5,
|
|
365
|
+
"tiers": [{
|
|
366
|
+
"inputTokensAbove": 272e3,
|
|
367
|
+
"input": 4,
|
|
368
|
+
"output": 15,
|
|
369
|
+
"cacheRead": .2,
|
|
370
|
+
"cacheWrite": 5
|
|
371
|
+
}]
|
|
372
|
+
},
|
|
373
|
+
"contextWindow": 5e5,
|
|
374
|
+
"maxTokens": 128e3,
|
|
375
|
+
"thinkingLevelMap": {
|
|
376
|
+
"off": null,
|
|
377
|
+
"minimal": "low",
|
|
378
|
+
"low": "low",
|
|
379
|
+
"medium": "medium",
|
|
380
|
+
"high": "high",
|
|
381
|
+
"xhigh": "xhigh",
|
|
382
|
+
"max": "max"
|
|
383
|
+
},
|
|
384
|
+
"compat": {
|
|
385
|
+
"supportsOpenAIGrammarTools": true,
|
|
386
|
+
"supportsAdditionalTools": true,
|
|
387
|
+
"supportsToolSearch": true,
|
|
388
|
+
"supportsMidConvoSystemMessages": true,
|
|
389
|
+
"supportsMidConvoEffort": true
|
|
390
|
+
},
|
|
391
|
+
"inputLimits": { "images": { "resize": {
|
|
392
|
+
"maxWidth": 2e3,
|
|
393
|
+
"maxHeight": 2e3,
|
|
394
|
+
"maxBytes": 4718592,
|
|
395
|
+
"jpegQuality": 80
|
|
396
|
+
} } },
|
|
397
|
+
"type": "chat"
|
|
398
|
+
},
|
|
399
|
+
"chat:gpt-6.1-terra": {
|
|
400
|
+
"id": "gpt-6.1-terra",
|
|
401
|
+
"name": "GPT-6.1 Terra",
|
|
402
|
+
"api": "openai-codex-responses",
|
|
403
|
+
"provider": "openai-codex",
|
|
404
|
+
"baseUrl": "https://chatgpt.com/backend-api",
|
|
405
|
+
"reasoning": true,
|
|
406
|
+
"input": ["text", "image"],
|
|
407
|
+
"cost": {
|
|
408
|
+
"input": 1,
|
|
409
|
+
"output": 5,
|
|
410
|
+
"cacheRead": .05,
|
|
411
|
+
"cacheWrite": 1.25,
|
|
412
|
+
"tiers": [{
|
|
413
|
+
"inputTokensAbove": 272e3,
|
|
414
|
+
"input": 2,
|
|
415
|
+
"output": 7.5,
|
|
416
|
+
"cacheRead": .1,
|
|
417
|
+
"cacheWrite": 2.5
|
|
418
|
+
}]
|
|
419
|
+
},
|
|
420
|
+
"contextWindow": 5e5,
|
|
421
|
+
"maxTokens": 128e3,
|
|
422
|
+
"thinkingLevelMap": {
|
|
423
|
+
"off": "none",
|
|
424
|
+
"minimal": "low",
|
|
425
|
+
"low": "low",
|
|
426
|
+
"medium": "medium",
|
|
427
|
+
"high": "high",
|
|
428
|
+
"xhigh": "xhigh",
|
|
429
|
+
"max": "max"
|
|
430
|
+
},
|
|
431
|
+
"compat": {
|
|
432
|
+
"supportsOpenAIGrammarTools": true,
|
|
433
|
+
"supportsAdditionalTools": true,
|
|
434
|
+
"supportsToolSearch": true,
|
|
435
|
+
"supportsMidConvoSystemMessages": true,
|
|
436
|
+
"supportsMidConvoEffort": true
|
|
437
|
+
},
|
|
438
|
+
"inputLimits": { "images": { "resize": {
|
|
439
|
+
"maxWidth": 2e3,
|
|
440
|
+
"maxHeight": 2e3,
|
|
441
|
+
"maxBytes": 4718592,
|
|
442
|
+
"jpegQuality": 80
|
|
443
|
+
} } },
|
|
444
|
+
"type": "chat"
|
|
445
|
+
},
|
|
446
|
+
"chat:gpt-6.2-astra": {
|
|
447
|
+
"id": "gpt-6.2-astra",
|
|
448
|
+
"name": "GPT-6.2 Astra",
|
|
449
|
+
"api": "openai-codex-responses",
|
|
450
|
+
"provider": "openai-codex",
|
|
451
|
+
"baseUrl": "https://chatgpt.com/backend-api",
|
|
452
|
+
"reasoning": true,
|
|
453
|
+
"input": ["text", "image"],
|
|
454
|
+
"cost": {
|
|
455
|
+
"input": 8,
|
|
456
|
+
"output": 40,
|
|
457
|
+
"cacheRead": .4,
|
|
458
|
+
"cacheWrite": 10,
|
|
459
|
+
"tiers": [{
|
|
460
|
+
"inputTokensAbove": 272e3,
|
|
461
|
+
"input": 16,
|
|
462
|
+
"output": 60,
|
|
463
|
+
"cacheRead": .8,
|
|
464
|
+
"cacheWrite": 20
|
|
465
|
+
}]
|
|
466
|
+
},
|
|
467
|
+
"contextWindow": 272e3,
|
|
468
|
+
"maxTokens": 128e3,
|
|
469
|
+
"thinkingLevelMap": {
|
|
470
|
+
"off": null,
|
|
471
|
+
"minimal": "low",
|
|
472
|
+
"low": "low",
|
|
473
|
+
"medium": "medium",
|
|
474
|
+
"high": "high",
|
|
475
|
+
"xhigh": "xhigh",
|
|
476
|
+
"max": "max"
|
|
477
|
+
},
|
|
478
|
+
"compat": {
|
|
479
|
+
"supportsOpenAIGrammarTools": true,
|
|
480
|
+
"supportsAdditionalTools": true,
|
|
481
|
+
"supportsToolSearch": true,
|
|
482
|
+
"supportsMidConvoSystemMessages": true,
|
|
483
|
+
"supportsMidConvoEffort": true
|
|
484
|
+
},
|
|
485
|
+
"inputLimits": { "images": { "resize": {
|
|
486
|
+
"maxWidth": 2e3,
|
|
487
|
+
"maxHeight": 2e3,
|
|
488
|
+
"maxBytes": 4718592,
|
|
489
|
+
"jpegQuality": 80
|
|
490
|
+
} } },
|
|
491
|
+
"type": "chat"
|
|
492
|
+
},
|
|
493
|
+
"chat:gpt-6.2-sol": {
|
|
494
|
+
"id": "gpt-6.2-sol",
|
|
495
|
+
"name": "GPT-6.2 Sol",
|
|
496
|
+
"api": "openai-codex-responses",
|
|
497
|
+
"provider": "openai-codex",
|
|
498
|
+
"baseUrl": "https://chatgpt.com/backend-api",
|
|
499
|
+
"reasoning": true,
|
|
500
|
+
"input": ["text", "image"],
|
|
501
|
+
"cost": {
|
|
502
|
+
"input": 2,
|
|
503
|
+
"output": 10,
|
|
504
|
+
"cacheRead": .1,
|
|
505
|
+
"cacheWrite": 2.5,
|
|
506
|
+
"tiers": [{
|
|
507
|
+
"inputTokensAbove": 272e3,
|
|
508
|
+
"input": 4,
|
|
509
|
+
"output": 15,
|
|
510
|
+
"cacheRead": .2,
|
|
511
|
+
"cacheWrite": 5
|
|
512
|
+
}]
|
|
513
|
+
},
|
|
514
|
+
"contextWindow": 5e5,
|
|
515
|
+
"maxTokens": 128e3,
|
|
516
|
+
"thinkingLevelMap": {
|
|
517
|
+
"off": null,
|
|
518
|
+
"minimal": "low",
|
|
519
|
+
"low": "low",
|
|
520
|
+
"medium": "medium",
|
|
521
|
+
"high": "high",
|
|
522
|
+
"xhigh": "xhigh",
|
|
523
|
+
"max": "max"
|
|
524
|
+
},
|
|
525
|
+
"compat": {
|
|
526
|
+
"supportsOpenAIGrammarTools": true,
|
|
527
|
+
"supportsAdditionalTools": true,
|
|
528
|
+
"supportsToolSearch": true,
|
|
529
|
+
"supportsMidConvoSystemMessages": true,
|
|
530
|
+
"supportsMidConvoEffort": true
|
|
531
|
+
},
|
|
532
|
+
"inputLimits": { "images": { "resize": {
|
|
533
|
+
"maxWidth": 2e3,
|
|
534
|
+
"maxHeight": 2e3,
|
|
535
|
+
"maxBytes": 4718592,
|
|
536
|
+
"jpegQuality": 80
|
|
537
|
+
} } },
|
|
538
|
+
"type": "chat"
|
|
539
|
+
}
|
|
540
|
+
} };
|
|
541
|
+
// node_modules/.pnpm/@earendil-works+pi-ai@1.6.0_@aws-sdk+credential-provider-node@3.972.98_@smithy+signatur_3204f39f3ad26528ec3165fb3f7546e0/node_modules/@earendil-works/pi-ai/dist/model-catalog.js
|
|
542
|
+
function flattenModelCatalog(groups, type) {
|
|
543
|
+
return Object.fromEntries(Object.values(groups).flatMap((models) => Object.values(models)).filter((model) => model.type === type).map((model) => [model.id, model]));
|
|
544
|
+
}
|
|
545
|
+
function flattenChatModelCatalog(_provider, groups) {
|
|
546
|
+
return flattenModelCatalog(groups, "chat");
|
|
547
|
+
}
|
|
548
|
+
function flattenImageModelCatalog(_provider, groups) {
|
|
549
|
+
return flattenModelCatalog(groups, "image");
|
|
550
|
+
}
|
|
551
|
+
function flattenClassifierModelCatalog(_provider, groups) {
|
|
552
|
+
return flattenModelCatalog(groups, "classifier");
|
|
553
|
+
}
|
|
554
|
+
// node_modules/.pnpm/@earendil-works+pi-ai@1.6.0_@aws-sdk+credential-provider-node@3.972.98_@smithy+signatur_3204f39f3ad26528ec3165fb3f7546e0/node_modules/@earendil-works/pi-ai/dist/providers/openai-codex.models.js
|
|
555
|
+
const OPENAI_CODEX_MODELS = flattenChatModelCatalog("openai-codex", openai_codex_default);
|
|
556
|
+
flattenImageModelCatalog("openai-codex", openai_codex_default);
|
|
557
|
+
flattenClassifierModelCatalog("openai-codex", openai_codex_default);
|
|
558
|
+
// node_modules/.pnpm/@earendil-works+pi-ai@1.6.0_@aws-sdk+credential-provider-node@3.972.98_@smithy+signatur_3204f39f3ad26528ec3165fb3f7546e0/node_modules/@earendil-works/pi-ai/dist/providers/openai-codex.js
|
|
559
|
+
function openaiCodexProvider() {
|
|
560
|
+
return createProvider({
|
|
561
|
+
id: "openai-codex",
|
|
562
|
+
name: "OpenAI Codex",
|
|
563
|
+
baseUrl: "https://chatgpt.com/backend-api",
|
|
564
|
+
auth: { oauth: lazyOAuth({
|
|
565
|
+
name: "OpenAI (ChatGPT Plus/Pro)",
|
|
566
|
+
isSubscription: true,
|
|
567
|
+
load: loadOpenAICodexOAuth
|
|
568
|
+
}) },
|
|
569
|
+
models: Object.values(OPENAI_CODEX_MODELS),
|
|
570
|
+
api: openAICodexResponsesApi()
|
|
571
|
+
});
|
|
572
|
+
}
|
|
573
|
+
// vendor/pi-ai-oauth/utils/provider-env.js
|
|
574
|
+
let procEnvCache = null;
|
|
575
|
+
/**
|
|
576
|
+
* Fallback for https://github.com/oven-sh/bun/issues/27802.
|
|
577
|
+
* Bun compiled binaries can expose an empty process.env inside Linux sandboxes
|
|
578
|
+
* even though /proc/self/environ contains the environment.
|
|
579
|
+
*
|
|
580
|
+
* This intentionally duplicates restoreSandboxEnv() in
|
|
581
|
+
* packages/coding-agent/src/bun/restore-sandbox-env.ts. The ai package can be
|
|
582
|
+
* used directly, without going through that entrypoint, so provider env lookup
|
|
583
|
+
* must not depend on process.env having been patched.
|
|
584
|
+
*/
|
|
585
|
+
function getBunSandboxEnvValue(name) {
|
|
586
|
+
if (typeof process === "undefined" || !process.versions?.bun || Object.keys(process.env).length > 0) return;
|
|
587
|
+
if (procEnvCache === null) {
|
|
588
|
+
procEnvCache = /* @__PURE__ */ new Map();
|
|
589
|
+
try {
|
|
590
|
+
const { readFileSync } = __require("node:fs");
|
|
591
|
+
const data = readFileSync("/proc/self/environ", "utf-8");
|
|
592
|
+
for (const entry of data.split("\0")) {
|
|
593
|
+
const idx = entry.indexOf("=");
|
|
594
|
+
if (idx > 0) procEnvCache.set(entry.slice(0, idx), entry.slice(idx + 1));
|
|
595
|
+
}
|
|
596
|
+
} catch {}
|
|
597
|
+
}
|
|
598
|
+
return procEnvCache.get(name);
|
|
599
|
+
}
|
|
600
|
+
/**
|
|
601
|
+
* Resolve a provider env value from scoped overrides, normal process.env, then
|
|
602
|
+
* the duplicated Bun sandbox fallback for direct pi-ai consumers.
|
|
603
|
+
*/
|
|
604
|
+
function getProviderEnvValue(name, env) {
|
|
605
|
+
return env?.[name] || (typeof process !== "undefined" ? process.env[name] : void 0) || getBunSandboxEnvValue(name) || void 0;
|
|
606
|
+
}
|
|
607
|
+
// vendor/pi-ai-oauth/auth/oauth/device-code.js
|
|
608
|
+
const CANCEL_MESSAGE = "Login cancelled";
|
|
609
|
+
const TIMEOUT_MESSAGE = "Device flow timed out";
|
|
610
|
+
const SLOW_DOWN_TIMEOUT_MESSAGE = "Device flow timed out after one or more slow_down responses. This is often caused by clock drift in WSL or VM environments. Please sync or restart the VM clock and try again.";
|
|
611
|
+
const MINIMUM_INTERVAL_MS = 1e3;
|
|
612
|
+
const DEFAULT_POLL_INTERVAL_SECONDS = 5;
|
|
613
|
+
const SLOW_DOWN_INTERVAL_INCREMENT_MS = 5e3;
|
|
614
|
+
function abortableSleep(ms, signal, cancelMessage) {
|
|
615
|
+
return new Promise((resolve, reject) => {
|
|
616
|
+
if (signal.aborted) {
|
|
617
|
+
reject(new Error(cancelMessage));
|
|
618
|
+
return;
|
|
619
|
+
}
|
|
620
|
+
const onAbort = () => {
|
|
621
|
+
clearTimeout(timeout);
|
|
622
|
+
reject(new Error(cancelMessage));
|
|
623
|
+
};
|
|
624
|
+
const timeout = setTimeout(() => {
|
|
625
|
+
signal.removeEventListener("abort", onAbort);
|
|
626
|
+
resolve();
|
|
627
|
+
}, ms);
|
|
628
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
629
|
+
});
|
|
630
|
+
}
|
|
631
|
+
async function pollOAuthDeviceCodeFlow(options) {
|
|
632
|
+
const deadline = typeof options.expiresInSeconds === "number" ? Date.now() + options.expiresInSeconds * 1e3 : Number.POSITIVE_INFINITY;
|
|
633
|
+
let intervalMs = Math.max(MINIMUM_INTERVAL_MS, Math.floor((options.intervalSeconds ?? DEFAULT_POLL_INTERVAL_SECONDS) * 1e3));
|
|
634
|
+
let slowDownResponses = 0;
|
|
635
|
+
if (options.waitBeforeFirstPoll) {
|
|
636
|
+
const remainingMs = deadline - Date.now();
|
|
637
|
+
if (remainingMs > 0) await abortableSleep(Math.min(intervalMs, remainingMs), options.signal, CANCEL_MESSAGE);
|
|
638
|
+
}
|
|
639
|
+
while (Date.now() < deadline) {
|
|
640
|
+
if (options.signal.aborted) throw new Error(CANCEL_MESSAGE);
|
|
641
|
+
const result = await options.poll();
|
|
642
|
+
if (result.status === "complete") return result.value;
|
|
643
|
+
if (result.status === "failed") throw new Error(result.message);
|
|
644
|
+
if (result.status === "slow_down") {
|
|
645
|
+
slowDownResponses += 1;
|
|
646
|
+
intervalMs = typeof result.intervalSeconds === "number" && Number.isFinite(result.intervalSeconds) && result.intervalSeconds > 0 ? Math.max(MINIMUM_INTERVAL_MS, Math.floor(result.intervalSeconds * 1e3)) : Math.max(MINIMUM_INTERVAL_MS, intervalMs + SLOW_DOWN_INTERVAL_INCREMENT_MS);
|
|
647
|
+
}
|
|
648
|
+
const remainingMs = deadline - Date.now();
|
|
649
|
+
if (remainingMs <= 0) break;
|
|
650
|
+
await abortableSleep(Math.min(intervalMs, remainingMs), options.signal, CANCEL_MESSAGE);
|
|
651
|
+
}
|
|
652
|
+
throw new Error(slowDownResponses > 0 ? SLOW_DOWN_TIMEOUT_MESSAGE : TIMEOUT_MESSAGE);
|
|
653
|
+
}
|
|
654
|
+
// vendor/pi-ai-oauth/auth/oauth/oauth-page.js
|
|
655
|
+
const LOGO_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 800" aria-hidden="true"><path fill="#fff" fill-rule="evenodd" d="M165.29 165.29 H517.36 V400 H400 V517.36 H282.65 V634.72 H165.29 Z M282.65 282.65 V400 H400 V282.65 Z"/><path fill="#fff" d="M517.36 400 H634.72 V634.72 H517.36 Z"/></svg>`;
|
|
656
|
+
function escapeHtml(value) {
|
|
657
|
+
return value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll("\"", """).replaceAll("'", "'");
|
|
658
|
+
}
|
|
659
|
+
function renderPage(options) {
|
|
660
|
+
const title = escapeHtml(options.title);
|
|
661
|
+
const heading = escapeHtml(options.heading);
|
|
662
|
+
const message = escapeHtml(options.message);
|
|
663
|
+
const details = options.details ? escapeHtml(options.details) : void 0;
|
|
664
|
+
return `<!doctype html>
|
|
665
|
+
<html lang="en">
|
|
666
|
+
<head>
|
|
667
|
+
<meta charset="utf-8" />
|
|
668
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
669
|
+
<title>${title}</title>
|
|
670
|
+
<style>
|
|
671
|
+
:root {
|
|
672
|
+
--text: #fafafa;
|
|
673
|
+
--text-dim: #a1a1aa;
|
|
674
|
+
--page-bg: #09090b;
|
|
675
|
+
--font-sans: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
|
|
676
|
+
--font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
|
|
677
|
+
}
|
|
678
|
+
* { box-sizing: border-box; }
|
|
679
|
+
html { color-scheme: dark; }
|
|
680
|
+
body {
|
|
681
|
+
margin: 0;
|
|
682
|
+
min-height: 100vh;
|
|
683
|
+
display: flex;
|
|
684
|
+
align-items: center;
|
|
685
|
+
justify-content: center;
|
|
686
|
+
padding: 24px;
|
|
687
|
+
background: var(--page-bg);
|
|
688
|
+
color: var(--text);
|
|
689
|
+
font-family: var(--font-sans);
|
|
690
|
+
text-align: center;
|
|
691
|
+
}
|
|
692
|
+
main {
|
|
693
|
+
width: 100%;
|
|
694
|
+
max-width: 560px;
|
|
695
|
+
display: flex;
|
|
696
|
+
flex-direction: column;
|
|
697
|
+
align-items: center;
|
|
698
|
+
justify-content: center;
|
|
699
|
+
}
|
|
700
|
+
.logo {
|
|
701
|
+
width: 72px;
|
|
702
|
+
height: 72px;
|
|
703
|
+
display: block;
|
|
704
|
+
margin-bottom: 24px;
|
|
705
|
+
}
|
|
706
|
+
h1 {
|
|
707
|
+
margin: 0 0 10px;
|
|
708
|
+
font-size: 28px;
|
|
709
|
+
line-height: 1.15;
|
|
710
|
+
font-weight: 650;
|
|
711
|
+
color: var(--text);
|
|
712
|
+
}
|
|
713
|
+
p {
|
|
714
|
+
margin: 0;
|
|
715
|
+
line-height: 1.7;
|
|
716
|
+
color: var(--text-dim);
|
|
717
|
+
font-size: 15px;
|
|
718
|
+
}
|
|
719
|
+
.details {
|
|
720
|
+
margin-top: 16px;
|
|
721
|
+
font-family: var(--font-mono);
|
|
722
|
+
font-size: 13px;
|
|
723
|
+
color: var(--text-dim);
|
|
724
|
+
white-space: pre-wrap;
|
|
725
|
+
word-break: break-word;
|
|
726
|
+
}
|
|
727
|
+
</style>
|
|
728
|
+
</head>
|
|
729
|
+
<body>
|
|
730
|
+
<main>
|
|
731
|
+
<div class="logo">${LOGO_SVG}</div>
|
|
732
|
+
<h1>${heading}</h1>
|
|
733
|
+
<p>${message}</p>
|
|
734
|
+
${details ? `<div class="details">${details}</div>` : ""}
|
|
735
|
+
</main>
|
|
736
|
+
</body>
|
|
737
|
+
</html>`;
|
|
738
|
+
}
|
|
739
|
+
function oauthSuccessHtml(message) {
|
|
740
|
+
return renderPage({
|
|
741
|
+
title: "Authentication successful",
|
|
742
|
+
heading: "Authentication successful",
|
|
743
|
+
message
|
|
744
|
+
});
|
|
745
|
+
}
|
|
746
|
+
function oauthErrorHtml(message, details) {
|
|
747
|
+
return renderPage({
|
|
748
|
+
title: "Authentication failed",
|
|
749
|
+
heading: "Authentication failed",
|
|
750
|
+
message,
|
|
751
|
+
details
|
|
752
|
+
});
|
|
753
|
+
}
|
|
754
|
+
// vendor/pi-ai-oauth/auth/oauth/pkce.js
|
|
755
|
+
/**
|
|
756
|
+
* PKCE utilities using Web Crypto API.
|
|
757
|
+
* Works in both Node.js 20+ and browsers.
|
|
758
|
+
*/
|
|
759
|
+
/**
|
|
760
|
+
* Encode bytes as base64url string.
|
|
761
|
+
*/
|
|
762
|
+
function base64urlEncode(bytes) {
|
|
763
|
+
let binary = "";
|
|
764
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
765
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
|
|
766
|
+
}
|
|
767
|
+
/**
|
|
768
|
+
* Generate PKCE code verifier and challenge.
|
|
769
|
+
* Uses Web Crypto API for cross-platform compatibility.
|
|
770
|
+
*/
|
|
771
|
+
async function generatePKCE() {
|
|
772
|
+
const verifierBytes = /* @__PURE__ */ new Uint8Array(32);
|
|
773
|
+
crypto.getRandomValues(verifierBytes);
|
|
774
|
+
const verifier = base64urlEncode(verifierBytes);
|
|
775
|
+
const data = new TextEncoder().encode(verifier);
|
|
776
|
+
const hashBuffer = await crypto.subtle.digest("SHA-256", data);
|
|
777
|
+
return {
|
|
778
|
+
verifier,
|
|
779
|
+
challenge: base64urlEncode(new Uint8Array(hashBuffer))
|
|
780
|
+
};
|
|
781
|
+
}
|
|
782
|
+
// vendor/pi-ai-oauth/auth/oauth/openai-codex.js
|
|
783
|
+
/**
|
|
784
|
+
* OpenAI Codex (ChatGPT OAuth) flow
|
|
785
|
+
*
|
|
786
|
+
* NOTE: This module uses Node.js crypto and http for the OAuth callback.
|
|
787
|
+
* It is only intended for CLI use, not browser environments.
|
|
788
|
+
*/
|
|
789
|
+
let _randomBytes = null;
|
|
790
|
+
let _http = null;
|
|
791
|
+
if (typeof process !== "undefined" && (process.versions?.node || process.versions?.bun)) {
|
|
792
|
+
import("node:crypto").then((m) => {
|
|
793
|
+
_randomBytes = m.randomBytes;
|
|
794
|
+
});
|
|
795
|
+
import("node:http").then((m) => {
|
|
796
|
+
_http = m;
|
|
797
|
+
});
|
|
798
|
+
}
|
|
799
|
+
const CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";
|
|
800
|
+
const AUTH_BASE_URL = "https://auth.openai.com";
|
|
801
|
+
const AUTHORIZE_URL = `${AUTH_BASE_URL}/oauth/authorize`;
|
|
802
|
+
const TOKEN_URL = `${AUTH_BASE_URL}/oauth/token`;
|
|
803
|
+
const REDIRECT_URI = "http://localhost:1455/auth/callback";
|
|
804
|
+
const DEVICE_USER_CODE_URL = `${AUTH_BASE_URL}/api/accounts/deviceauth/usercode`;
|
|
805
|
+
const DEVICE_TOKEN_URL = `${AUTH_BASE_URL}/api/accounts/deviceauth/token`;
|
|
806
|
+
const DEVICE_VERIFICATION_URI = `${AUTH_BASE_URL}/codex/device`;
|
|
807
|
+
const DEVICE_REDIRECT_URI = `${AUTH_BASE_URL}/deviceauth/callback`;
|
|
808
|
+
const DEVICE_CODE_TIMEOUT_SECONDS = 900;
|
|
809
|
+
const OPENAI_CODEX_BROWSER_LOGIN_METHOD = "browser";
|
|
810
|
+
const OPENAI_CODEX_DEVICE_CODE_LOGIN_METHOD = "device_code";
|
|
811
|
+
const SCOPE = "openid profile email offline_access";
|
|
812
|
+
const JWT_CLAIM_PATH = "https://api.openai.com/auth";
|
|
813
|
+
function getCallbackHost() {
|
|
814
|
+
return getProviderEnvValue("PI_OAUTH_CALLBACK_HOST") || "127.0.0.1";
|
|
815
|
+
}
|
|
816
|
+
function createState() {
|
|
817
|
+
if (!_randomBytes) throw new Error("OpenAI Codex OAuth is only available in Node.js environments");
|
|
818
|
+
return _randomBytes(16).toString("hex");
|
|
819
|
+
}
|
|
820
|
+
function parseAuthorizationInput(input) {
|
|
821
|
+
const value = input.trim();
|
|
822
|
+
if (!value) return {};
|
|
823
|
+
try {
|
|
824
|
+
const url = new URL(value);
|
|
825
|
+
return {
|
|
826
|
+
code: url.searchParams.get("code") ?? void 0,
|
|
827
|
+
state: url.searchParams.get("state") ?? void 0
|
|
828
|
+
};
|
|
829
|
+
} catch {}
|
|
830
|
+
if (value.includes("#")) {
|
|
831
|
+
const [code, state] = value.split("#", 2);
|
|
832
|
+
return {
|
|
833
|
+
code,
|
|
834
|
+
state
|
|
835
|
+
};
|
|
836
|
+
}
|
|
837
|
+
if (value.includes("code=")) {
|
|
838
|
+
const params = new URLSearchParams(value);
|
|
839
|
+
return {
|
|
840
|
+
code: params.get("code") ?? void 0,
|
|
841
|
+
state: params.get("state") ?? void 0
|
|
842
|
+
};
|
|
843
|
+
}
|
|
844
|
+
return { code: value };
|
|
845
|
+
}
|
|
846
|
+
function decodeJwt(token) {
|
|
847
|
+
try {
|
|
848
|
+
const parts = token.split(".");
|
|
849
|
+
if (parts.length !== 3) return null;
|
|
850
|
+
const payload = parts[1] ?? "";
|
|
851
|
+
if (!/^[A-Za-z0-9_-]+={0,2}$/.test(payload)) return null;
|
|
852
|
+
const binary = atob(payload.replace(/-/g, "+").replace(/_/g, "/"));
|
|
853
|
+
const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0));
|
|
854
|
+
const decoded = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
855
|
+
return JSON.parse(decoded);
|
|
856
|
+
} catch {
|
|
857
|
+
return null;
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
async function fetchWithLoginCancellation(input, init) {
|
|
861
|
+
try {
|
|
862
|
+
return await fetch(input, init);
|
|
863
|
+
} catch (error) {
|
|
864
|
+
if (init.signal?.aborted) throw new Error("Login cancelled");
|
|
865
|
+
throw error;
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
/** A structured refresh rejection, without response text or credential data. */
|
|
869
|
+
var OpenAICodexRefreshRejectedError = class extends Error {
|
|
870
|
+
constructor() {
|
|
871
|
+
super("OpenAI Codex refresh authorization was rejected");
|
|
872
|
+
this.name = "OpenAICodexRefreshRejectedError";
|
|
873
|
+
}
|
|
874
|
+
};
|
|
875
|
+
async function readTokenResponse(response, operation) {
|
|
876
|
+
if (!response.ok) {
|
|
877
|
+
const text = await response.text().catch(() => "");
|
|
878
|
+
if (operation === "refresh" && (response.status === 400 || response.status === 401)) {
|
|
879
|
+
let failure;
|
|
880
|
+
try {
|
|
881
|
+
failure = JSON.parse(text);
|
|
882
|
+
} catch {}
|
|
883
|
+
if (failure !== null && typeof failure === "object" && failure.error === "invalid_grant") throw new OpenAICodexRefreshRejectedError();
|
|
884
|
+
}
|
|
885
|
+
throw new Error(`OpenAI Codex token ${operation} failed (${response.status}): ${text || response.statusText}`);
|
|
886
|
+
}
|
|
887
|
+
const json = await response.json();
|
|
888
|
+
if (!json?.access_token || !json.refresh_token || typeof json.expires_in !== "number") throw new Error(`OpenAI Codex token ${operation} response missing fields: ${JSON.stringify(json)}`);
|
|
889
|
+
return {
|
|
890
|
+
access: json.access_token,
|
|
891
|
+
refresh: json.refresh_token,
|
|
892
|
+
expires: Date.now() + json.expires_in * 1e3
|
|
893
|
+
};
|
|
894
|
+
}
|
|
895
|
+
async function exchangeAuthorizationCode(code, verifier, redirectUri, signal) {
|
|
896
|
+
return readTokenResponse(await fetchWithLoginCancellation(TOKEN_URL, {
|
|
897
|
+
method: "POST",
|
|
898
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
899
|
+
body: new URLSearchParams({
|
|
900
|
+
grant_type: "authorization_code",
|
|
901
|
+
client_id: CLIENT_ID,
|
|
902
|
+
code,
|
|
903
|
+
code_verifier: verifier,
|
|
904
|
+
redirect_uri: redirectUri
|
|
905
|
+
}),
|
|
906
|
+
signal
|
|
907
|
+
}), "exchange");
|
|
908
|
+
}
|
|
909
|
+
async function refreshAccessToken(refreshToken, signal) {
|
|
910
|
+
let response;
|
|
911
|
+
try {
|
|
912
|
+
response = await fetch(TOKEN_URL, {
|
|
913
|
+
method: "POST",
|
|
914
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
915
|
+
body: new URLSearchParams({
|
|
916
|
+
grant_type: "refresh_token",
|
|
917
|
+
refresh_token: refreshToken,
|
|
918
|
+
client_id: CLIENT_ID
|
|
919
|
+
}),
|
|
920
|
+
signal
|
|
921
|
+
});
|
|
922
|
+
} catch (error) {
|
|
923
|
+
throw new Error(`OpenAI Codex token refresh error: ${error instanceof Error ? error.message : String(error)}`);
|
|
924
|
+
}
|
|
925
|
+
return readTokenResponse(response, "refresh");
|
|
926
|
+
}
|
|
927
|
+
async function startOpenAICodexDeviceAuth(signal) {
|
|
928
|
+
const response = await fetchWithLoginCancellation(DEVICE_USER_CODE_URL, {
|
|
929
|
+
method: "POST",
|
|
930
|
+
headers: { "Content-Type": "application/json" },
|
|
931
|
+
body: JSON.stringify({ client_id: CLIENT_ID }),
|
|
932
|
+
signal
|
|
933
|
+
});
|
|
934
|
+
if (!response.ok) {
|
|
935
|
+
if (response.status === 404) throw new Error("OpenAI Codex device code login is not enabled for this server. Use browser login or verify the server URL.");
|
|
936
|
+
const responseBody = await response.text().catch(() => "");
|
|
937
|
+
throw new Error(`OpenAI Codex device code request failed with status ${response.status}${responseBody ? `: ${responseBody}` : ""}`);
|
|
938
|
+
}
|
|
939
|
+
const json = await response.json();
|
|
940
|
+
const intervalSeconds = typeof json?.interval === "string" ? Number(json.interval.trim()) : json?.interval;
|
|
941
|
+
if (!json?.device_auth_id || !json.user_code || typeof intervalSeconds !== "number" || !Number.isFinite(intervalSeconds) || intervalSeconds < 0) throw new Error(`Invalid OpenAI Codex device code response: ${JSON.stringify(json)}`);
|
|
942
|
+
return {
|
|
943
|
+
deviceAuthId: json.device_auth_id,
|
|
944
|
+
userCode: json.user_code,
|
|
945
|
+
intervalSeconds
|
|
946
|
+
};
|
|
947
|
+
}
|
|
948
|
+
async function pollOpenAICodexDeviceAuth(device, signal) {
|
|
949
|
+
return pollOAuthDeviceCodeFlow({
|
|
950
|
+
intervalSeconds: device.intervalSeconds,
|
|
951
|
+
expiresInSeconds: DEVICE_CODE_TIMEOUT_SECONDS,
|
|
952
|
+
signal,
|
|
953
|
+
poll: async () => {
|
|
954
|
+
const response = await fetchWithLoginCancellation(DEVICE_TOKEN_URL, {
|
|
955
|
+
method: "POST",
|
|
956
|
+
headers: { "Content-Type": "application/json" },
|
|
957
|
+
body: JSON.stringify({
|
|
958
|
+
device_auth_id: device.deviceAuthId,
|
|
959
|
+
user_code: device.userCode
|
|
960
|
+
}),
|
|
961
|
+
signal
|
|
962
|
+
});
|
|
963
|
+
if (response.ok) {
|
|
964
|
+
const json = await response.json();
|
|
965
|
+
if (!json?.authorization_code || !json.code_verifier) return {
|
|
966
|
+
status: "failed",
|
|
967
|
+
message: `Invalid OpenAI Codex device auth token response: ${JSON.stringify(json)}`
|
|
968
|
+
};
|
|
969
|
+
return {
|
|
970
|
+
status: "complete",
|
|
971
|
+
value: {
|
|
972
|
+
authorizationCode: json.authorization_code,
|
|
973
|
+
codeVerifier: json.code_verifier
|
|
974
|
+
}
|
|
975
|
+
};
|
|
976
|
+
}
|
|
977
|
+
if (response.status === 403 || response.status === 404) return { status: "pending" };
|
|
978
|
+
const responseBody = await response.text().catch(() => "");
|
|
979
|
+
let errorCode;
|
|
980
|
+
try {
|
|
981
|
+
const error = JSON.parse(responseBody)?.error;
|
|
982
|
+
errorCode = typeof error === "object" ? error?.code : error;
|
|
983
|
+
} catch {}
|
|
984
|
+
if (errorCode === "deviceauth_authorization_pending") return { status: "pending" };
|
|
985
|
+
if (errorCode === "slow_down") return { status: "slow_down" };
|
|
986
|
+
return {
|
|
987
|
+
status: "failed",
|
|
988
|
+
message: `OpenAI Codex device auth failed with status ${response.status}${responseBody ? `: ${responseBody}` : ""}`
|
|
989
|
+
};
|
|
990
|
+
}
|
|
991
|
+
});
|
|
992
|
+
}
|
|
993
|
+
async function createAuthorizationFlow(originator = "pi") {
|
|
994
|
+
const { verifier, challenge } = await generatePKCE();
|
|
995
|
+
const state = createState();
|
|
996
|
+
const url = new URL(AUTHORIZE_URL);
|
|
997
|
+
url.searchParams.set("response_type", "code");
|
|
998
|
+
url.searchParams.set("client_id", CLIENT_ID);
|
|
999
|
+
url.searchParams.set("redirect_uri", REDIRECT_URI);
|
|
1000
|
+
url.searchParams.set("scope", SCOPE);
|
|
1001
|
+
url.searchParams.set("code_challenge", challenge);
|
|
1002
|
+
url.searchParams.set("code_challenge_method", "S256");
|
|
1003
|
+
url.searchParams.set("state", state);
|
|
1004
|
+
url.searchParams.set("id_token_add_organizations", "true");
|
|
1005
|
+
url.searchParams.set("codex_cli_simplified_flow", "true");
|
|
1006
|
+
url.searchParams.set("originator", originator);
|
|
1007
|
+
return {
|
|
1008
|
+
verifier,
|
|
1009
|
+
state,
|
|
1010
|
+
url: url.toString()
|
|
1011
|
+
};
|
|
1012
|
+
}
|
|
1013
|
+
function startLocalOAuthServer(state) {
|
|
1014
|
+
if (!_http) throw new Error("OpenAI Codex OAuth is only available in Node.js environments");
|
|
1015
|
+
let settleWait;
|
|
1016
|
+
const waitForCodePromise = new Promise((resolve) => {
|
|
1017
|
+
let settled = false;
|
|
1018
|
+
settleWait = (value) => {
|
|
1019
|
+
if (settled) return;
|
|
1020
|
+
settled = true;
|
|
1021
|
+
resolve(value);
|
|
1022
|
+
};
|
|
1023
|
+
});
|
|
1024
|
+
const server = _http.createServer((req, res) => {
|
|
1025
|
+
try {
|
|
1026
|
+
const url = new URL(req.url || "", "http://localhost");
|
|
1027
|
+
if (url.pathname !== "/auth/callback") {
|
|
1028
|
+
res.statusCode = 404;
|
|
1029
|
+
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
|
1030
|
+
res.end(oauthErrorHtml("Callback route not found."));
|
|
1031
|
+
return;
|
|
1032
|
+
}
|
|
1033
|
+
if (url.searchParams.get("state") !== state) {
|
|
1034
|
+
res.statusCode = 400;
|
|
1035
|
+
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
|
1036
|
+
res.end(oauthErrorHtml("State mismatch."));
|
|
1037
|
+
return;
|
|
1038
|
+
}
|
|
1039
|
+
const code = url.searchParams.get("code");
|
|
1040
|
+
if (!code) {
|
|
1041
|
+
res.statusCode = 400;
|
|
1042
|
+
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
|
1043
|
+
res.end(oauthErrorHtml("Missing authorization code."));
|
|
1044
|
+
return;
|
|
1045
|
+
}
|
|
1046
|
+
res.statusCode = 200;
|
|
1047
|
+
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
|
1048
|
+
res.end(oauthSuccessHtml("OpenAI authentication completed. You can close this window."));
|
|
1049
|
+
settleWait?.({ code });
|
|
1050
|
+
} catch {
|
|
1051
|
+
res.statusCode = 500;
|
|
1052
|
+
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
|
1053
|
+
res.end(oauthErrorHtml("Internal error while processing OAuth callback."));
|
|
1054
|
+
}
|
|
1055
|
+
});
|
|
1056
|
+
return new Promise((resolve) => {
|
|
1057
|
+
server.listen(1455, getCallbackHost(), () => {
|
|
1058
|
+
resolve({
|
|
1059
|
+
close: () => new Promise((resolve) => {
|
|
1060
|
+
server.close(() => resolve());
|
|
1061
|
+
server.closeAllConnections();
|
|
1062
|
+
}),
|
|
1063
|
+
cancelWait: () => {
|
|
1064
|
+
settleWait?.(null);
|
|
1065
|
+
},
|
|
1066
|
+
waitForCode: () => waitForCodePromise
|
|
1067
|
+
});
|
|
1068
|
+
}).on("error", (_err) => {
|
|
1069
|
+
settleWait?.(null);
|
|
1070
|
+
resolve({
|
|
1071
|
+
close: () => {
|
|
1072
|
+
try {
|
|
1073
|
+
server.close();
|
|
1074
|
+
} catch {}
|
|
1075
|
+
},
|
|
1076
|
+
cancelWait: () => {},
|
|
1077
|
+
waitForCode: async () => null
|
|
1078
|
+
});
|
|
1079
|
+
});
|
|
1080
|
+
});
|
|
1081
|
+
}
|
|
1082
|
+
function getAccountId(accessToken) {
|
|
1083
|
+
const accountId = (decodeJwt(accessToken)?.[JWT_CLAIM_PATH])?.chatgpt_account_id;
|
|
1084
|
+
return typeof accountId === "string" && accountId.length > 0 ? accountId : null;
|
|
1085
|
+
}
|
|
1086
|
+
function credentialsFromToken(token) {
|
|
1087
|
+
const accountId = getAccountId(token.access);
|
|
1088
|
+
if (!accountId) throw new Error("Failed to extract accountId from token");
|
|
1089
|
+
return {
|
|
1090
|
+
type: "oauth",
|
|
1091
|
+
access: token.access,
|
|
1092
|
+
refresh: token.refresh,
|
|
1093
|
+
expires: token.expires,
|
|
1094
|
+
accountId
|
|
1095
|
+
};
|
|
1096
|
+
}
|
|
1097
|
+
async function exchangeAuthorizationCodeForCredentials(code, verifier, redirectUri, signal) {
|
|
1098
|
+
return credentialsFromToken(await exchangeAuthorizationCode(code, verifier, redirectUri, signal));
|
|
1099
|
+
}
|
|
1100
|
+
async function loginOpenAICodexDeviceCode(interaction) {
|
|
1101
|
+
const device = await startOpenAICodexDeviceAuth(interaction.signal);
|
|
1102
|
+
interaction.notify({
|
|
1103
|
+
type: "device_code",
|
|
1104
|
+
userCode: device.userCode,
|
|
1105
|
+
verificationUri: DEVICE_VERIFICATION_URI,
|
|
1106
|
+
intervalSeconds: device.intervalSeconds,
|
|
1107
|
+
expiresInSeconds: DEVICE_CODE_TIMEOUT_SECONDS
|
|
1108
|
+
});
|
|
1109
|
+
const code = await pollOpenAICodexDeviceAuth(device, interaction.signal);
|
|
1110
|
+
return exchangeAuthorizationCodeForCredentials(code.authorizationCode, code.codeVerifier, DEVICE_REDIRECT_URI, interaction.signal);
|
|
1111
|
+
}
|
|
1112
|
+
async function loginOpenAICodex$1(interaction) {
|
|
1113
|
+
const { verifier, state, url } = await createAuthorizationFlow();
|
|
1114
|
+
const server = await startLocalOAuthServer(state);
|
|
1115
|
+
const manualAbort = new AbortController();
|
|
1116
|
+
const onAbort = () => server.cancelWait();
|
|
1117
|
+
interaction.signal.addEventListener("abort", onAbort, { once: true });
|
|
1118
|
+
if (interaction.signal.aborted) onAbort();
|
|
1119
|
+
let code;
|
|
1120
|
+
let manualCode;
|
|
1121
|
+
let manualError;
|
|
1122
|
+
interaction.notify({
|
|
1123
|
+
type: "auth_url",
|
|
1124
|
+
url,
|
|
1125
|
+
instructions: "A browser window should open. Complete login to finish."
|
|
1126
|
+
});
|
|
1127
|
+
try {
|
|
1128
|
+
const manualPromise = interaction.prompt({
|
|
1129
|
+
type: "manual_code",
|
|
1130
|
+
message: "Complete login in your browser, or paste the authorization code / redirect URL here:",
|
|
1131
|
+
placeholder: REDIRECT_URI,
|
|
1132
|
+
signal: manualAbort.signal
|
|
1133
|
+
}).then((input) => {
|
|
1134
|
+
manualCode = input;
|
|
1135
|
+
server.cancelWait();
|
|
1136
|
+
}).catch((error) => {
|
|
1137
|
+
manualError = error instanceof Error ? error : new Error(String(error));
|
|
1138
|
+
server.cancelWait();
|
|
1139
|
+
});
|
|
1140
|
+
const result = await server.waitForCode();
|
|
1141
|
+
if (manualError) throw manualError;
|
|
1142
|
+
if (result?.code) code = result.code;
|
|
1143
|
+
else if (manualCode) {
|
|
1144
|
+
const parsed = parseAuthorizationInput(manualCode);
|
|
1145
|
+
if (parsed.state && parsed.state !== state) throw new Error("State mismatch");
|
|
1146
|
+
code = parsed.code;
|
|
1147
|
+
}
|
|
1148
|
+
if (!code) {
|
|
1149
|
+
await manualPromise;
|
|
1150
|
+
if (manualError) throw manualError;
|
|
1151
|
+
if (manualCode) {
|
|
1152
|
+
const parsed = parseAuthorizationInput(manualCode);
|
|
1153
|
+
if (parsed.state && parsed.state !== state) throw new Error("State mismatch");
|
|
1154
|
+
code = parsed.code;
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
if (!code) throw new Error("Missing authorization code");
|
|
1158
|
+
return exchangeAuthorizationCodeForCredentials(code, verifier, REDIRECT_URI, interaction.signal);
|
|
1159
|
+
} finally {
|
|
1160
|
+
interaction.signal.removeEventListener("abort", onAbort);
|
|
1161
|
+
manualAbort.abort();
|
|
1162
|
+
await server.close();
|
|
1163
|
+
}
|
|
1164
|
+
}
|
|
1165
|
+
/**
|
|
1166
|
+
* Refresh OpenAI Codex OAuth token
|
|
1167
|
+
*/
|
|
1168
|
+
async function refreshOpenAICodexToken(refreshToken, signal) {
|
|
1169
|
+
return credentialsFromToken(await refreshAccessToken(refreshToken, signal));
|
|
1170
|
+
}
|
|
1171
|
+
const openaiCodexOAuth = {
|
|
1172
|
+
name: "OpenAI (ChatGPT Plus/Pro)",
|
|
1173
|
+
isSubscription: true,
|
|
1174
|
+
async login(interaction) {
|
|
1175
|
+
const method = await interaction.prompt({
|
|
1176
|
+
type: "select",
|
|
1177
|
+
message: "Select OpenAI Codex login method:",
|
|
1178
|
+
options: [{
|
|
1179
|
+
id: OPENAI_CODEX_BROWSER_LOGIN_METHOD,
|
|
1180
|
+
label: "Browser login (default)"
|
|
1181
|
+
}, {
|
|
1182
|
+
id: OPENAI_CODEX_DEVICE_CODE_LOGIN_METHOD,
|
|
1183
|
+
label: "Device code login (headless)"
|
|
1184
|
+
}]
|
|
1185
|
+
});
|
|
1186
|
+
if (method === OPENAI_CODEX_DEVICE_CODE_LOGIN_METHOD) return loginOpenAICodexDeviceCode(interaction);
|
|
1187
|
+
if (method !== OPENAI_CODEX_BROWSER_LOGIN_METHOD) throw new Error(`Unknown OpenAI Codex login method: ${method}`);
|
|
1188
|
+
return loginOpenAICodex$1(interaction);
|
|
1189
|
+
},
|
|
1190
|
+
refresh: (credential, signal) => refreshOpenAICodexToken(credential.refresh, signal),
|
|
1191
|
+
async toAuth(credential) {
|
|
1192
|
+
return { apiKey: credential.access };
|
|
1193
|
+
}
|
|
1194
|
+
};
|
|
1195
|
+
// node_modules/.pnpm/@deepseek-ai+dsh-atomic-write@0.2.2-rc.5_@deepseek-ai+cordis@4.1.0/node_modules/@deepseek-ai/dsh-atomic-write/lib/index.js
|
|
1196
|
+
/**
|
|
1197
|
+
* Zero-dependency atomic file replacement and writer coordination.
|
|
1198
|
+
* `writeFileAtomic` writes a random-suffix sibling with exclusive create and
|
|
1199
|
+
* the caller's permission bits, then renames it over the target, so readers
|
|
1200
|
+
* observe either the old or the new complete content and a replaced file ends
|
|
1201
|
+
* up with exactly the stated mode. `withFileLock` serializes cross-process
|
|
1202
|
+
* writers of one file through a `wx`-created `<file>.lock` sibling, so a
|
|
1203
|
+
* read-modify-write cycle can never resurrect a state another writer just
|
|
1204
|
+
* replaced; readers stay lock-free because the rename commit is atomic. A lock
|
|
1205
|
+
* whose recorded holder process no longer exists is taken over.
|
|
1206
|
+
* @module @deepseek-ai/dsh-atomic-write
|
|
1207
|
+
*/
|
|
1208
|
+
const WINDOWS_TRANSIENT_RENAME_ERRORS = /* @__PURE__ */ new Set([
|
|
1209
|
+
"EACCES",
|
|
1210
|
+
"EBUSY",
|
|
1211
|
+
"EPERM"
|
|
1212
|
+
]);
|
|
1213
|
+
const WINDOWS_RENAME_RETRY_INITIAL_MS = 20;
|
|
1214
|
+
const WINDOWS_RENAME_RETRY_MAX_MS = 200;
|
|
1215
|
+
const WINDOWS_RENAME_RETRY_LIMIT = 8;
|
|
1216
|
+
/** Whether Windows reported temporary interference with an atomic replacement. */
|
|
1217
|
+
function isTransientWindowsRenameError(error) {
|
|
1218
|
+
if (process.platform !== "win32") return false;
|
|
1219
|
+
return WINDOWS_TRANSIENT_RENAME_ERRORS.has(error?.code ?? "");
|
|
1220
|
+
}
|
|
1221
|
+
/** Replace the target after bounded retries for transient Windows interference. */
|
|
1222
|
+
async function renameAtomicTemp(temp, filename) {
|
|
1223
|
+
let delay = WINDOWS_RENAME_RETRY_INITIAL_MS;
|
|
1224
|
+
for (let retries = 0;; retries += 1) {
|
|
1225
|
+
try {
|
|
1226
|
+
await rename(temp, filename);
|
|
1227
|
+
return;
|
|
1228
|
+
} catch (error) {
|
|
1229
|
+
if (!isTransientWindowsRenameError(error)) throw error;
|
|
1230
|
+
if (retries >= WINDOWS_RENAME_RETRY_LIMIT) throw error;
|
|
1231
|
+
}
|
|
1232
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
1233
|
+
delay = Math.min(delay * 2, WINDOWS_RENAME_RETRY_MAX_MS);
|
|
1234
|
+
}
|
|
1235
|
+
}
|
|
1236
|
+
/**
|
|
1237
|
+
* Replace `filename` with `content` in one atomic step, creating parent
|
|
1238
|
+
* directories. The content is first written to a random-suffix sibling opened
|
|
1239
|
+
* with exclusive create (`wx`): the open refuses to follow a symlink planted
|
|
1240
|
+
* at the temp path, and the fresh inode carries `options.mode` through the
|
|
1241
|
+
* rename, so replacing a wider-permission file narrows it without a chmod
|
|
1242
|
+
* race. The rename also replaces a symlinked target itself instead of writing
|
|
1243
|
+
* through to its referent, and the same-directory sibling keeps the rename on
|
|
1244
|
+
* one filesystem. Windows replacement retries transient `EACCES`, `EBUSY`,
|
|
1245
|
+
* and `EPERM` failures for a bounded interval while the complete temp file
|
|
1246
|
+
* remains the rename source. On any remaining failure the temp file is
|
|
1247
|
+
* removed and the failure rethrown. Crash durability (fsync) is out of scope.
|
|
1248
|
+
* @param filename - final path receiving the content.
|
|
1249
|
+
* @param content - complete next file content.
|
|
1250
|
+
* @param options - permission bits for the replacement inode.
|
|
1251
|
+
*/
|
|
1252
|
+
async function writeFileAtomic(filename, content, options) {
|
|
1253
|
+
await mkdir(dirname(filename), {
|
|
1254
|
+
recursive: true,
|
|
1255
|
+
...options.dirMode === void 0 ? {} : { mode: options.dirMode }
|
|
1256
|
+
});
|
|
1257
|
+
const temp = `${filename}.${randomBytes(6).toString("hex")}.tmp`;
|
|
1258
|
+
try {
|
|
1259
|
+
await writeFile(temp, content, {
|
|
1260
|
+
mode: options.mode,
|
|
1261
|
+
flag: "wx"
|
|
1262
|
+
});
|
|
1263
|
+
await renameAtomicTemp(temp, filename);
|
|
1264
|
+
} catch (error) {
|
|
1265
|
+
await rm(temp, { force: true });
|
|
1266
|
+
throw error;
|
|
1267
|
+
}
|
|
1268
|
+
}
|
|
1269
|
+
/** Whether an exclusive create found an existing lock. */
|
|
1270
|
+
async function isLockContention(error, lockPath) {
|
|
1271
|
+
const code = error?.code;
|
|
1272
|
+
if (code === "EEXIST") return true;
|
|
1273
|
+
if (code !== "EPERM") return false;
|
|
1274
|
+
try {
|
|
1275
|
+
await lstat(lockPath);
|
|
1276
|
+
return true;
|
|
1277
|
+
} catch {
|
|
1278
|
+
return false;
|
|
1279
|
+
}
|
|
1280
|
+
}
|
|
1281
|
+
/** Whether the holder a `<pid>\n` record names is proven gone: a signal probe finds no such process. */
|
|
1282
|
+
function holderExited(record) {
|
|
1283
|
+
if (!/^\d+\n$/.test(record)) return false;
|
|
1284
|
+
const pid = Number(record.trim());
|
|
1285
|
+
if (pid === 0 || pid > 2147483647) return false;
|
|
1286
|
+
if (pid === process.pid) return false;
|
|
1287
|
+
try {
|
|
1288
|
+
process.kill(pid, 0);
|
|
1289
|
+
return false;
|
|
1290
|
+
} catch (error) {
|
|
1291
|
+
return error.code === "ESRCH";
|
|
1292
|
+
}
|
|
1293
|
+
}
|
|
1294
|
+
/** The lock file's content, or undefined when it cannot be read. */
|
|
1295
|
+
async function readLockRecord(lockPath) {
|
|
1296
|
+
try {
|
|
1297
|
+
return await readFile(lockPath, "utf8");
|
|
1298
|
+
} catch (error) {
|
|
1299
|
+
return;
|
|
1300
|
+
}
|
|
1301
|
+
}
|
|
1302
|
+
/**
|
|
1303
|
+
* Remove the lock when its recorded holder exited. Contenders that read the
|
|
1304
|
+
* same record serialize on a claim file named after it. Under the claim, the
|
|
1305
|
+
* claimant re-reads the lock and probes its PID again, and removes it only
|
|
1306
|
+
* when it still holds that record and that PID is still gone: the record's
|
|
1307
|
+
* holder can no longer release it, and no other contender can remove it
|
|
1308
|
+
* without the claim, so a removal never deletes a lock another contender
|
|
1309
|
+
* acquired after the dead holder's, including one whose holder reused the PID.
|
|
1310
|
+
* @returns Whether this call removed the dead holder's lock.
|
|
1311
|
+
*/
|
|
1312
|
+
async function takeOverExitedLock(lockPath) {
|
|
1313
|
+
const record = await readLockRecord(lockPath);
|
|
1314
|
+
if (record === void 0 || !holderExited(record)) return false;
|
|
1315
|
+
const claim = `${lockPath}.takeover-${createHash("sha256").update(record).digest("hex").slice(0, 16)}`;
|
|
1316
|
+
try {
|
|
1317
|
+
await writeFile(claim, `${process.pid}\n`, {
|
|
1318
|
+
mode: 384,
|
|
1319
|
+
flag: "wx"
|
|
1320
|
+
});
|
|
1321
|
+
} catch (error) {
|
|
1322
|
+
const code = error.code;
|
|
1323
|
+
if (code === "EEXIST" || code === "EPERM") return false;
|
|
1324
|
+
throw error;
|
|
1325
|
+
}
|
|
1326
|
+
try {
|
|
1327
|
+
if (await readLockRecord(lockPath) !== record || !holderExited(record)) return false;
|
|
1328
|
+
try {
|
|
1329
|
+
await rm(lockPath, { force: true });
|
|
1330
|
+
} catch (error) {
|
|
1331
|
+
return false;
|
|
1332
|
+
}
|
|
1333
|
+
return true;
|
|
1334
|
+
} finally {
|
|
1335
|
+
await rm(claim, { force: true }).catch((error) => {});
|
|
1336
|
+
}
|
|
1337
|
+
}
|
|
1338
|
+
/**
|
|
1339
|
+
* Retry cadence for a contended lock. These stay robustness invariants of the
|
|
1340
|
+
* cross-process write protocol rather than deployment tunables: they govern how
|
|
1341
|
+
* often a contender asks, which no caller has a reason to vary.
|
|
1342
|
+
*/
|
|
1343
|
+
const LOCK_RETRY_INITIAL_MS = 20;
|
|
1344
|
+
const LOCK_RETRY_MAX_MS = 200;
|
|
1345
|
+
/**
|
|
1346
|
+
* How long a contender waits when the caller states no limit — sized for the
|
|
1347
|
+
* render-and-rename cycle every call site had when this package was written.
|
|
1348
|
+
* Expiry fails the contender rather than guessing whether the existing lock
|
|
1349
|
+
* still has an owner. How long is *worth* waiting is a property of the
|
|
1350
|
+
* operation the lock holder runs, which is why {@link FileLockOptions.waitMs}
|
|
1351
|
+
* exists; the value here is the floor for an operation that does file work
|
|
1352
|
+
* alone.
|
|
1353
|
+
*/
|
|
1354
|
+
const DEFAULT_LOCK_WAIT_MS = 2e3;
|
|
1355
|
+
/**
|
|
1356
|
+
* Hold the cross-process writer lock for `filename` around one operation. The
|
|
1357
|
+
* lock is a `wx`-created sibling (`<filename>.lock`); paired with the
|
|
1358
|
+
* rename-based commit of {@link writeFileAtomic}, readers stay lock-free and
|
|
1359
|
+
* only writers contend. `EEXIST` is contention directly; an `EPERM` is
|
|
1360
|
+
* contention only when a fresh `lstat` confirms the lock path exists, covering
|
|
1361
|
+
* Windows exclusive-create behavior. Windows retries one unconfirmed EPERM
|
|
1362
|
+
* because the holder can release before the probe; a repeated unconfirmed
|
|
1363
|
+
* permission error is rethrown. The lock records its holder's PID. A contender
|
|
1364
|
+
* removes the lock and retries at once when no process with that PID exists
|
|
1365
|
+
* (`ESRCH`); any other lock, including one whose holder exists under another
|
|
1366
|
+
* user (`EPERM`) or whose record is incomplete, is waited for. Contention backs
|
|
1367
|
+
* off exponentially and times out after the deadline. A holder whose PID a
|
|
1368
|
+
* live process reused keeps its lock until an operator removes it. Takeover
|
|
1369
|
+
* proves only that the recorded process exited: an operation that starts other
|
|
1370
|
+
* writers must stop them with it or leave its successor a way to find them.
|
|
1371
|
+
* PIDs are compared on the contender's host, so writers on other hosts or in
|
|
1372
|
+
* other PID namespaces sharing the file are unsupported and could both hold
|
|
1373
|
+
* the lock. The parent directory must exist.
|
|
1374
|
+
* @param filename - the file whose writers this lock serializes.
|
|
1375
|
+
* @param operation - the read-render-commit cycle to run while holding the lock.
|
|
1376
|
+
* @param options - acquisition options; omitted waits {@link DEFAULT_LOCK_WAIT_MS}.
|
|
1377
|
+
* @returns the operation's result; the lock releases on both outcomes.
|
|
1378
|
+
*/
|
|
1379
|
+
async function withFileLock(filename, operation, options) {
|
|
1380
|
+
const lockPath = `${filename}.lock`;
|
|
1381
|
+
const deadline = Date.now() + (options?.waitMs ?? DEFAULT_LOCK_WAIT_MS);
|
|
1382
|
+
let delay = LOCK_RETRY_INITIAL_MS;
|
|
1383
|
+
let retriedUnconfirmedPermissionError = false;
|
|
1384
|
+
for (;;) {
|
|
1385
|
+
options?.signal?.throwIfAborted();
|
|
1386
|
+
try {
|
|
1387
|
+
await writeFile(lockPath, `${process.pid}\n`, {
|
|
1388
|
+
mode: 384,
|
|
1389
|
+
flag: "wx"
|
|
1390
|
+
});
|
|
1391
|
+
break;
|
|
1392
|
+
} catch (error) {
|
|
1393
|
+
if (!await isLockContention(error, lockPath)) {
|
|
1394
|
+
if (process.platform !== "win32" || error?.code !== "EPERM" || retriedUnconfirmedPermissionError) throw error;
|
|
1395
|
+
retriedUnconfirmedPermissionError = true;
|
|
1396
|
+
} else if (await takeOverExitedLock(lockPath)) continue;
|
|
1397
|
+
}
|
|
1398
|
+
if (Date.now() >= deadline) throw new Error(`atomic-write: timed out waiting for the writer lock at ${lockPath}`);
|
|
1399
|
+
await setTimeout$1(delay, void 0, { signal: options?.signal });
|
|
1400
|
+
delay = Math.min(delay * 2, LOCK_RETRY_MAX_MS);
|
|
1401
|
+
}
|
|
1402
|
+
try {
|
|
1403
|
+
options?.signal?.throwIfAborted();
|
|
1404
|
+
return await operation();
|
|
1405
|
+
} finally {
|
|
1406
|
+
await rm(lockPath, { force: true });
|
|
1407
|
+
}
|
|
1408
|
+
}
|
|
1409
|
+
// node_modules/.pnpm/@deepseek-ai+dsh-home-paths@0.2.2-rc.5_@deepseek-ai+cordis@4.1.0/node_modules/@deepseek-ai/dsh-home-paths/lib/index.js
|
|
1410
|
+
/**
|
|
1411
|
+
* Shared filesystem path helpers for DeepSeek Harness user data.
|
|
1412
|
+
*
|
|
1413
|
+
* @module @deepseek-ai/dsh-home-paths
|
|
1414
|
+
*/
|
|
1415
|
+
/** Directory name for the default DeepSeek Harness home under the OS home. */
|
|
1416
|
+
const DSH_HOME_DIR_NAME = ".dsh";
|
|
1417
|
+
/** Environment variable that overrides the default DeepSeek Harness home. */
|
|
1418
|
+
const DSH_HOME_ENV = "DSH_HOME";
|
|
1419
|
+
/**
|
|
1420
|
+
* Resolve the default DeepSeek Harness home using Node's platform path rules.
|
|
1421
|
+
* @returns the absolute default harness home path.
|
|
1422
|
+
*/
|
|
1423
|
+
function defaultDshHome() {
|
|
1424
|
+
return join(homedir(), DSH_HOME_DIR_NAME);
|
|
1425
|
+
}
|
|
1426
|
+
/**
|
|
1427
|
+
* Expand supported tilde prefixes against the operating-system home.
|
|
1428
|
+
* @param path - configured path that may begin with `~`, `~/`, or `~\`.
|
|
1429
|
+
* @returns the expanded path, or the original value when no supported prefix is present.
|
|
1430
|
+
*/
|
|
1431
|
+
function expandHomePath(path) {
|
|
1432
|
+
if (path === "~") return homedir();
|
|
1433
|
+
if (path.startsWith("~/") || path.startsWith("~\\")) return join(homedir(), path.slice(2));
|
|
1434
|
+
return path;
|
|
1435
|
+
}
|
|
1436
|
+
/**
|
|
1437
|
+
* Resolve one user-data root from an explicit path, an environment override, and a default.
|
|
1438
|
+
* @param configured - explicit path, which has highest precedence.
|
|
1439
|
+
* @param env - environment mapping to read.
|
|
1440
|
+
* @param envName - environment variable that overrides the default.
|
|
1441
|
+
* @param fallback - default root, used when neither the explicit path nor the environment provides one.
|
|
1442
|
+
* @returns the normalized absolute root.
|
|
1443
|
+
*/
|
|
1444
|
+
function resolveRoot(configured, env, envName, fallback) {
|
|
1445
|
+
const fromEnv = env[envName];
|
|
1446
|
+
return resolve(expandHomePath(configured ?? (fromEnv !== void 0 && fromEnv.trim().length > 0 ? fromEnv : fallback())));
|
|
1447
|
+
}
|
|
1448
|
+
/**
|
|
1449
|
+
* Resolve the single-root DeepSeek Harness home.
|
|
1450
|
+
*
|
|
1451
|
+
* Precedence, highest first: an explicit configured path, `$DSH_HOME`, then
|
|
1452
|
+
* `~/.dsh`. The harness keeps all user data under one root. An empty or
|
|
1453
|
+
* whitespace-only `$DSH_HOME` is treated as unset, so a blank override never
|
|
1454
|
+
* resolves the home to the current working directory.
|
|
1455
|
+
* @param configured - explicit harness-home override, which has highest precedence.
|
|
1456
|
+
* @param env - environment mapping used to read `DSH_HOME`.
|
|
1457
|
+
* @returns the normalized absolute harness home path.
|
|
1458
|
+
*/
|
|
1459
|
+
function resolveDshHome(configured, env = process.env) {
|
|
1460
|
+
return resolveRoot(configured, env, DSH_HOME_ENV, defaultDshHome);
|
|
1461
|
+
}
|
|
1462
|
+
// src/platform/auth/account-profile.ts
|
|
1463
|
+
/** Safe browser labels and composite identity derived locally from OpenAI Codex OAuth JWTs. */
|
|
1464
|
+
const AUTH_CLAIM = "https://api.openai.com/auth";
|
|
1465
|
+
const PROFILE_CLAIM = "https://api.openai.com/profile";
|
|
1466
|
+
const MAX_JWT_PAYLOAD_LENGTH = 65536;
|
|
1467
|
+
const MAX_LABEL_LENGTH = 128;
|
|
1468
|
+
const MAX_EMAIL_LENGTH = 320;
|
|
1469
|
+
const MAX_USER_ID_LENGTH = 256;
|
|
1470
|
+
function boundedText(value, maximum) {
|
|
1471
|
+
if (typeof value !== "string") return void 0;
|
|
1472
|
+
const normalized = value.replace(/[\u0000-\u001f\u007f]/gu, "").trim();
|
|
1473
|
+
return normalized.length > 0 && normalized.length <= maximum ? normalized : void 0;
|
|
1474
|
+
}
|
|
1475
|
+
function isRecord(value) {
|
|
1476
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1477
|
+
}
|
|
1478
|
+
function decodeJwtPayload(access) {
|
|
1479
|
+
const payload = access.split(".")[1];
|
|
1480
|
+
if (payload === void 0 || payload.length === 0 || payload.length > MAX_JWT_PAYLOAD_LENGTH) return void 0;
|
|
1481
|
+
try {
|
|
1482
|
+
const decoded = JSON.parse(Buffer$1.from(payload, "base64url").toString("utf8"));
|
|
1483
|
+
return isRecord(decoded) ? decoded : void 0;
|
|
1484
|
+
} catch {
|
|
1485
|
+
return;
|
|
1486
|
+
}
|
|
1487
|
+
}
|
|
1488
|
+
function maskEmail(email) {
|
|
1489
|
+
const separator = email.lastIndexOf("@");
|
|
1490
|
+
if (separator <= 0 || separator === email.length - 1) return "••••";
|
|
1491
|
+
const local = email.slice(0, separator);
|
|
1492
|
+
const domain = email.slice(separator + 1);
|
|
1493
|
+
return `${local.slice(0, Math.min(2, local.length))}••@${domain}`;
|
|
1494
|
+
}
|
|
1495
|
+
function formatPlanLabel(raw) {
|
|
1496
|
+
if (raw === void 0) return void 0;
|
|
1497
|
+
return {
|
|
1498
|
+
team: "Team",
|
|
1499
|
+
business: "Business",
|
|
1500
|
+
enterprise: "Enterprise",
|
|
1501
|
+
plus: "Plus",
|
|
1502
|
+
pro: "Pro",
|
|
1503
|
+
free: "Free",
|
|
1504
|
+
edu: "Edu"
|
|
1505
|
+
}[raw.toLowerCase()] ?? raw;
|
|
1506
|
+
}
|
|
1507
|
+
/**
|
|
1508
|
+
* Derive a stable per-(workspace, user) identity string from an OAuth credential.
|
|
1509
|
+
* ChatGPT Team/Business members share `chatgpt_account_id` (the workspace id),
|
|
1510
|
+
* so combining it with the JWT user identity keeps distinct members separate
|
|
1511
|
+
* while still allowing the same user to store multiple workspaces.
|
|
1512
|
+
*/
|
|
1513
|
+
function openAICodexCredentialIdentity(credential) {
|
|
1514
|
+
const payload = decodeJwtPayload(credential.access);
|
|
1515
|
+
if (payload === void 0) return credential.accountId;
|
|
1516
|
+
const auth = isRecord(payload[AUTH_CLAIM]) ? payload[AUTH_CLAIM] : void 0;
|
|
1517
|
+
const profile = isRecord(payload[PROFILE_CLAIM]) ? payload[PROFILE_CLAIM] : void 0;
|
|
1518
|
+
const userId = boundedText(auth?.["chatgpt_user_id"], MAX_USER_ID_LENGTH) ?? boundedText(auth?.["user_id"], MAX_USER_ID_LENGTH) ?? boundedText(payload["sub"], MAX_USER_ID_LENGTH) ?? boundedText(profile?.["email"], MAX_EMAIL_LENGTH)?.toLowerCase();
|
|
1519
|
+
return userId === void 0 ? credential.accountId : `${credential.accountId}\0${userId}`;
|
|
1520
|
+
}
|
|
1521
|
+
function decodeOauthProfile(access) {
|
|
1522
|
+
const payload = decodeJwtPayload(access);
|
|
1523
|
+
if (payload === void 0) return {};
|
|
1524
|
+
const auth = isRecord(payload[AUTH_CLAIM]) ? payload[AUTH_CLAIM] : void 0;
|
|
1525
|
+
const profile = isRecord(payload[PROFILE_CLAIM]) ? payload[PROFILE_CLAIM] : void 0;
|
|
1526
|
+
const name = boundedText(profile?.["name"], MAX_LABEL_LENGTH);
|
|
1527
|
+
const email = boundedText(profile?.["email"], MAX_EMAIL_LENGTH);
|
|
1528
|
+
const plan = formatPlanLabel(boundedText(auth?.["chatgpt_plan_type"], 32));
|
|
1529
|
+
return {
|
|
1530
|
+
...name === void 0 ? {} : { name },
|
|
1531
|
+
...email === void 0 ? {} : { email },
|
|
1532
|
+
...plan === void 0 ? {} : { plan }
|
|
1533
|
+
};
|
|
1534
|
+
}
|
|
1535
|
+
/** Resolve display-only labels without network access or provider account identifiers. */
|
|
1536
|
+
function resolveOpenAICodexAccountProfiles(credentials) {
|
|
1537
|
+
const base = credentials.map((credential, index) => {
|
|
1538
|
+
const oauth = decodeOauthProfile(credential.access);
|
|
1539
|
+
return {
|
|
1540
|
+
displayName: oauth.name ?? `ChatGPT account ${String(index + 1)}`,
|
|
1541
|
+
maskedEmail: oauth.email === void 0 ? void 0 : maskEmail(oauth.email),
|
|
1542
|
+
plan: oauth.plan,
|
|
1543
|
+
source: oauth.name === void 0 && oauth.email === void 0 ? "generated" : "oauth"
|
|
1544
|
+
};
|
|
1545
|
+
});
|
|
1546
|
+
const groupCounts = /* @__PURE__ */ new Map();
|
|
1547
|
+
for (const entry of base) {
|
|
1548
|
+
const groupKey = `${entry.displayName}\0${entry.maskedEmail ?? ""}`;
|
|
1549
|
+
groupCounts.set(groupKey, (groupCounts.get(groupKey) ?? 0) + 1);
|
|
1550
|
+
}
|
|
1551
|
+
const labeled = base.map((entry) => {
|
|
1552
|
+
const groupKey = `${entry.displayName}\0${entry.maskedEmail ?? ""}`;
|
|
1553
|
+
if ((groupCounts.get(groupKey) ?? 0) <= 1 || entry.plan === void 0) return entry;
|
|
1554
|
+
return {
|
|
1555
|
+
...entry,
|
|
1556
|
+
displayName: `${entry.displayName} (${entry.plan})`
|
|
1557
|
+
};
|
|
1558
|
+
});
|
|
1559
|
+
const finalCounts = /* @__PURE__ */ new Map();
|
|
1560
|
+
for (const entry of labeled) {
|
|
1561
|
+
const groupKey = `${entry.displayName}\0${entry.maskedEmail ?? ""}`;
|
|
1562
|
+
finalCounts.set(groupKey, (finalCounts.get(groupKey) ?? 0) + 1);
|
|
1563
|
+
}
|
|
1564
|
+
const seen = /* @__PURE__ */ new Map();
|
|
1565
|
+
return labeled.map((entry) => {
|
|
1566
|
+
const groupKey = `${entry.displayName}\0${entry.maskedEmail ?? ""}`;
|
|
1567
|
+
let displayName = entry.displayName;
|
|
1568
|
+
if ((finalCounts.get(groupKey) ?? 0) > 1) {
|
|
1569
|
+
const ordinal = (seen.get(groupKey) ?? 0) + 1;
|
|
1570
|
+
seen.set(groupKey, ordinal);
|
|
1571
|
+
displayName = `${displayName} #${String(ordinal)}`;
|
|
1572
|
+
}
|
|
1573
|
+
return {
|
|
1574
|
+
displayName,
|
|
1575
|
+
...entry.maskedEmail === void 0 ? {} : { maskedEmail: entry.maskedEmail },
|
|
1576
|
+
source: entry.source
|
|
1577
|
+
};
|
|
1578
|
+
});
|
|
1579
|
+
}
|
|
1580
|
+
// src/platform/auth/store.ts
|
|
1581
|
+
/**
|
|
1582
|
+
* Owner-only persistent OAuth credential storage for the OpenAI Codex bundle.
|
|
1583
|
+
* @module dsh-codex-connect/store
|
|
1584
|
+
*/
|
|
1585
|
+
/** Provider route and pi-ai provider id owned by this bundle. */
|
|
1586
|
+
const OPENAI_CODEX_PROVIDER = "openai-codex";
|
|
1587
|
+
/** Basename of the OAuth document inside the Harness home. */
|
|
1588
|
+
const OPENAI_CODEX_AUTH_FILENAME = ".openai-codex-auth.json";
|
|
1589
|
+
/** Current multi-account on-disk format. */
|
|
1590
|
+
const AUTH_FORMAT_VERSION = 2;
|
|
1591
|
+
/** Maximum serialized credential document size. */
|
|
1592
|
+
const OPENAI_CODEX_AUTH_DOCUMENT_LIMIT = 524288;
|
|
1593
|
+
/** Suffix used for the one-time version-1 rollback copy. */
|
|
1594
|
+
const OPENAI_CODEX_AUTH_V1_BACKUP_SUFFIX = ".v1-backup";
|
|
1595
|
+
const ACCOUNT_KEY_PATTERN = /^acct_[A-Za-z0-9_-]{43}$/u;
|
|
1596
|
+
function openAICodexAccountKey(identity) {
|
|
1597
|
+
return `acct_${createHash("sha256").update(identity).digest("base64url")}`;
|
|
1598
|
+
}
|
|
1599
|
+
/** Compute the browser-safe unique key for one stored credential (workspace + user). */
|
|
1600
|
+
function openAICodexCredentialKey(credential) {
|
|
1601
|
+
return openAICodexAccountKey(openAICodexCredentialIdentity(credential));
|
|
1602
|
+
}
|
|
1603
|
+
function accountSummaries(document) {
|
|
1604
|
+
if (document === void 0) return [];
|
|
1605
|
+
const credentials = documentCredentials(document);
|
|
1606
|
+
const profiles = resolveOpenAICodexAccountProfiles(credentials);
|
|
1607
|
+
const activeKey = openAICodexCredentialKey(activeCredential(document));
|
|
1608
|
+
return credentials.map((credential, index) => {
|
|
1609
|
+
const key = openAICodexCredentialKey(credential);
|
|
1610
|
+
return {
|
|
1611
|
+
accountKey: key,
|
|
1612
|
+
displayName: profiles[index].displayName,
|
|
1613
|
+
...profiles[index].maskedEmail === void 0 ? {} : { maskedEmail: profiles[index].maskedEmail },
|
|
1614
|
+
profileSource: profiles[index].source,
|
|
1615
|
+
active: key === activeKey
|
|
1616
|
+
};
|
|
1617
|
+
});
|
|
1618
|
+
}
|
|
1619
|
+
function isENOENT$1(error) {
|
|
1620
|
+
return error?.code === "ENOENT";
|
|
1621
|
+
}
|
|
1622
|
+
function assertOwnerOnly$1(filename, mode) {
|
|
1623
|
+
/* v8 ignore next -- native Windows coverage takes the mode-less branch */
|
|
1624
|
+
if (process.platform === "win32") return;
|
|
1625
|
+
/* v8 ignore start -- POSIX tests cover this branch; Windows cannot express it */
|
|
1626
|
+
if ((mode & 63) !== 0) throw new Error(`openai-codex: ${filename} is readable beyond its owner (mode ${(mode & 511).toString(8)}); run "chmod 600 ${filename}" before starting again`);
|
|
1627
|
+
/* v8 ignore stop */
|
|
1628
|
+
}
|
|
1629
|
+
/** Validate one OAuth credential without quoting token-bearing input. */
|
|
1630
|
+
function parseCredential(raw, filename) {
|
|
1631
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new Error(`openai-codex: ${filename} credential must be an object`);
|
|
1632
|
+
const credential = raw;
|
|
1633
|
+
if (Object.keys(credential).some((key) => ![
|
|
1634
|
+
"type",
|
|
1635
|
+
"access",
|
|
1636
|
+
"refresh",
|
|
1637
|
+
"expires",
|
|
1638
|
+
"accountId"
|
|
1639
|
+
].includes(key))) throw new Error(`openai-codex: ${filename} credential contains an unknown field`);
|
|
1640
|
+
if (credential["type"] !== "oauth") throw new Error(`openai-codex: ${filename} credential type must be oauth`);
|
|
1641
|
+
for (const key of [
|
|
1642
|
+
"access",
|
|
1643
|
+
"refresh",
|
|
1644
|
+
"accountId"
|
|
1645
|
+
]) if (typeof credential[key] !== "string" || credential[key].length === 0) throw new Error(`openai-codex: ${filename} credential ${key} must be a non-empty string`);
|
|
1646
|
+
if (typeof credential["expires"] !== "number" || !Number.isFinite(credential["expires"]) || credential["expires"] <= 0) throw new Error(`openai-codex: ${filename} credential expires must be a positive finite number`);
|
|
1647
|
+
return credential;
|
|
1648
|
+
}
|
|
1649
|
+
/** Validate the strict JSON document without quoting token-bearing input. */
|
|
1650
|
+
function parseDocument$1(text, filename) {
|
|
1651
|
+
let value;
|
|
1652
|
+
try {
|
|
1653
|
+
value = JSON.parse(text);
|
|
1654
|
+
} catch {
|
|
1655
|
+
throw new Error(`openai-codex: ${filename} is not valid JSON`);
|
|
1656
|
+
}
|
|
1657
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`openai-codex: ${filename} must contain an object`);
|
|
1658
|
+
const document = value;
|
|
1659
|
+
if (document["version"] === 1) {
|
|
1660
|
+
if (Object.keys(document).some((key) => key !== "version" && key !== "credential")) throw new Error(`openai-codex: ${filename} contains an unknown top-level field`);
|
|
1661
|
+
return {
|
|
1662
|
+
version: 1,
|
|
1663
|
+
credential: parseCredential(document["credential"], filename)
|
|
1664
|
+
};
|
|
1665
|
+
}
|
|
1666
|
+
if (document["version"] !== AUTH_FORMAT_VERSION) throw new Error(`openai-codex: ${filename} has unsupported auth format version ${String(document["version"])}`);
|
|
1667
|
+
if (Object.keys(document).some((key) => ![
|
|
1668
|
+
"version",
|
|
1669
|
+
"activeAccountId",
|
|
1670
|
+
"activeAccountKey",
|
|
1671
|
+
"credentials"
|
|
1672
|
+
].includes(key))) throw new Error(`openai-codex: ${filename} contains an unknown top-level field`);
|
|
1673
|
+
if (typeof document["activeAccountId"] !== "string" || document["activeAccountId"].length === 0) throw new Error(`openai-codex: ${filename} activeAccountId must be a non-empty string`);
|
|
1674
|
+
const rawActiveKey = document["activeAccountKey"];
|
|
1675
|
+
if (rawActiveKey !== void 0 && (typeof rawActiveKey !== "string" || !ACCOUNT_KEY_PATTERN.test(rawActiveKey))) throw new Error(`openai-codex: ${filename} activeAccountKey is invalid`);
|
|
1676
|
+
if (!Array.isArray(document["credentials"]) || document["credentials"].length === 0) throw new Error(`openai-codex: ${filename} credentials must be a non-empty array`);
|
|
1677
|
+
if (document["credentials"].length > 16) throw new Error(`openai-codex: ${filename} exceeds the ${String(16)} account limit`);
|
|
1678
|
+
const credentials = document["credentials"].map((raw) => parseCredential(raw, filename));
|
|
1679
|
+
const keys = credentials.map(openAICodexCredentialKey);
|
|
1680
|
+
if (new Set(keys).size !== credentials.length) throw new Error(`openai-codex: ${filename} contains duplicate account identities`);
|
|
1681
|
+
if (rawActiveKey !== void 0) {
|
|
1682
|
+
const active = credentials.find((credential, index) => keys[index] === rawActiveKey);
|
|
1683
|
+
if (active === void 0 || active.accountId !== document["activeAccountId"]) throw new Error(`openai-codex: ${filename} activeAccountKey does not identify a stored credential`);
|
|
1684
|
+
} else if (credentials.filter((credential) => credential.accountId === document["activeAccountId"]).length !== 1) throw new Error(`openai-codex: ${filename} activeAccountId does not uniquely identify a stored credential`);
|
|
1685
|
+
return {
|
|
1686
|
+
version: AUTH_FORMAT_VERSION,
|
|
1687
|
+
activeAccountId: document["activeAccountId"],
|
|
1688
|
+
...rawActiveKey === void 0 ? {} : { activeAccountKey: rawActiveKey },
|
|
1689
|
+
credentials
|
|
1690
|
+
};
|
|
1691
|
+
}
|
|
1692
|
+
function cloneCredential(credential) {
|
|
1693
|
+
return structuredClone(credential);
|
|
1694
|
+
}
|
|
1695
|
+
function documentCredentials(document) {
|
|
1696
|
+
return document.version === 1 ? [document.credential] : document.credentials;
|
|
1697
|
+
}
|
|
1698
|
+
function activeCredential(document) {
|
|
1699
|
+
if (document.version === 1) return document.credential;
|
|
1700
|
+
const active = document.activeAccountKey !== void 0 ? document.credentials.find((credential) => openAICodexCredentialKey(credential) === document.activeAccountKey) : document.credentials.find((credential) => credential.accountId === document.activeAccountId);
|
|
1701
|
+
if (active === void 0) throw new Error("openai-codex: active credential invariant failed");
|
|
1702
|
+
return active;
|
|
1703
|
+
}
|
|
1704
|
+
function makeV2Document(active, credentials) {
|
|
1705
|
+
return {
|
|
1706
|
+
version: AUTH_FORMAT_VERSION,
|
|
1707
|
+
activeAccountId: active.accountId,
|
|
1708
|
+
activeAccountKey: openAICodexCredentialKey(active),
|
|
1709
|
+
credentials: credentials.map(cloneCredential)
|
|
1710
|
+
};
|
|
1711
|
+
}
|
|
1712
|
+
function serializeDocument(document) {
|
|
1713
|
+
const text = `${JSON.stringify(document, null, 2)}\n`;
|
|
1714
|
+
if (Buffer.byteLength(text) > 524288) throw new Error(`openai-codex: credential document exceeds ${String(OPENAI_CODEX_AUTH_DOCUMENT_LIMIT)} bytes`);
|
|
1715
|
+
return text;
|
|
1716
|
+
}
|
|
1717
|
+
/** Resolve the default OAuth document path under `$DSH_HOME`. */
|
|
1718
|
+
function openAICodexAuthPath(dshHome) {
|
|
1719
|
+
return resolve(join(resolveDshHome(dshHome), OPENAI_CODEX_AUTH_FILENAME));
|
|
1720
|
+
}
|
|
1721
|
+
/** File-backed pi-ai store scoped to the single OpenAI Codex provider. */
|
|
1722
|
+
var OpenAICodexCredentialStore = class {
|
|
1723
|
+
/** Absolute credential document path. */
|
|
1724
|
+
filename;
|
|
1725
|
+
/** Owner-only version-1 rollback copy, created at the first migration write. */
|
|
1726
|
+
version1BackupFilename;
|
|
1727
|
+
constructor(filename = openAICodexAuthPath()) {
|
|
1728
|
+
this.filename = resolve(filename);
|
|
1729
|
+
this.version1BackupFilename = join(dirname(this.filename), `${basename(this.filename)}${OPENAI_CODEX_AUTH_V1_BACKUP_SUFFIX}`);
|
|
1730
|
+
}
|
|
1731
|
+
async readDocument() {
|
|
1732
|
+
return this.readDocumentAt(this.filename);
|
|
1733
|
+
}
|
|
1734
|
+
async readDocumentAt(filename) {
|
|
1735
|
+
let handle;
|
|
1736
|
+
try {
|
|
1737
|
+
handle = await open(filename, "r");
|
|
1738
|
+
} catch (error) {
|
|
1739
|
+
if (isENOENT$1(error)) return void 0;
|
|
1740
|
+
throw error;
|
|
1741
|
+
}
|
|
1742
|
+
try {
|
|
1743
|
+
const info = await handle.stat();
|
|
1744
|
+
if (!info.isFile()) throw new Error(`openai-codex: ${filename} must be a regular file`);
|
|
1745
|
+
assertOwnerOnly$1(filename, info.mode);
|
|
1746
|
+
if (info.size > 524288) throw new Error(`openai-codex: ${filename} exceeds ${String(OPENAI_CODEX_AUTH_DOCUMENT_LIMIT)} bytes`);
|
|
1747
|
+
return parseDocument$1(await handle.readFile("utf8"), filename);
|
|
1748
|
+
} finally {
|
|
1749
|
+
await handle.close();
|
|
1750
|
+
}
|
|
1751
|
+
}
|
|
1752
|
+
async writeDocument(document, previous) {
|
|
1753
|
+
const text = serializeDocument(document);
|
|
1754
|
+
if (previous?.version === 1) {
|
|
1755
|
+
const existingBackup = await this.readDocumentAt(this.version1BackupFilename);
|
|
1756
|
+
if (existingBackup === void 0) await writeFileAtomic(this.version1BackupFilename, serializeDocument(previous), {
|
|
1757
|
+
mode: 384,
|
|
1758
|
+
dirMode: 448
|
|
1759
|
+
});
|
|
1760
|
+
else if (existingBackup.version !== 1 || serializeDocument(existingBackup) !== serializeDocument(previous)) throw new Error(`openai-codex: ${this.version1BackupFilename} rollback copy does not match the current version 1 credential`);
|
|
1761
|
+
}
|
|
1762
|
+
await writeFileAtomic(this.filename, text, {
|
|
1763
|
+
mode: 384,
|
|
1764
|
+
dirMode: 448
|
|
1765
|
+
});
|
|
1766
|
+
}
|
|
1767
|
+
/** @inheritdoc */
|
|
1768
|
+
async read(providerId) {
|
|
1769
|
+
if (providerId !== "openai-codex") return void 0;
|
|
1770
|
+
const document = await this.readDocument();
|
|
1771
|
+
return document === void 0 ? void 0 : cloneCredential(activeCredential(document));
|
|
1772
|
+
}
|
|
1773
|
+
/**
|
|
1774
|
+
* Capture the current account for one request's complete auth resolution.
|
|
1775
|
+
* Refreshes through the returned store update only that captured account and
|
|
1776
|
+
* never change the user's current account selection.
|
|
1777
|
+
*/
|
|
1778
|
+
async captureActiveAccount() {
|
|
1779
|
+
const document = await this.readDocument();
|
|
1780
|
+
const captured = document === void 0 ? void 0 : cloneCredential(activeCredential(document));
|
|
1781
|
+
const capturedKey = captured === void 0 ? void 0 : openAICodexCredentialKey(captured);
|
|
1782
|
+
let requestCredential = captured;
|
|
1783
|
+
const snapshot = {
|
|
1784
|
+
accounts: async () => accountSummaries(document),
|
|
1785
|
+
captureActiveAccount: async () => snapshot,
|
|
1786
|
+
read: async (providerId) => providerId === "openai-codex" && requestCredential !== void 0 ? cloneCredential(requestCredential) : void 0,
|
|
1787
|
+
list: async () => requestCredential === void 0 ? [] : [{
|
|
1788
|
+
providerId: OPENAI_CODEX_PROVIDER,
|
|
1789
|
+
type: "oauth"
|
|
1790
|
+
}],
|
|
1791
|
+
modify: async (providerId, fn, options) => {
|
|
1792
|
+
options?.signal?.throwIfAborted();
|
|
1793
|
+
if (providerId !== "openai-codex") throw new Error(`openai-codex: captured credential store does not own provider "${providerId}"`);
|
|
1794
|
+
if (capturedKey === void 0) return void 0;
|
|
1795
|
+
requestCredential = await this.modifyCapturedAccount(capturedKey, fn, options);
|
|
1796
|
+
return requestCredential === void 0 ? void 0 : cloneCredential(requestCredential);
|
|
1797
|
+
},
|
|
1798
|
+
delete: async (providerId) => {
|
|
1799
|
+
if (providerId === "openai-codex") throw new Error("openai-codex: a captured request credential cannot log out");
|
|
1800
|
+
}
|
|
1801
|
+
};
|
|
1802
|
+
return snapshot;
|
|
1803
|
+
}
|
|
1804
|
+
async modifyCapturedAccount(capturedKey, fn, options) {
|
|
1805
|
+
await mkdir(dirname(this.filename), {
|
|
1806
|
+
recursive: true,
|
|
1807
|
+
mode: 448
|
|
1808
|
+
});
|
|
1809
|
+
return this.withWriterLock(async () => {
|
|
1810
|
+
const document = await this.readDocument();
|
|
1811
|
+
if (document === void 0) return void 0;
|
|
1812
|
+
const credentials = [...documentCredentials(document)];
|
|
1813
|
+
const capturedIndex = credentials.findIndex((credential) => openAICodexCredentialKey(credential) === capturedKey);
|
|
1814
|
+
if (capturedIndex < 0) return void 0;
|
|
1815
|
+
const current = cloneCredential(credentials[capturedIndex]);
|
|
1816
|
+
options?.signal?.throwIfAborted();
|
|
1817
|
+
const candidate = await fn(current);
|
|
1818
|
+
if (candidate === void 0) return current;
|
|
1819
|
+
const validated = parseCredential(candidate, this.filename);
|
|
1820
|
+
if (openAICodexCredentialKey(validated) !== capturedKey) throw new Error("openai-codex: a request credential refresh cannot change accountId");
|
|
1821
|
+
credentials[capturedIndex] = validated;
|
|
1822
|
+
const active = activeCredential(document);
|
|
1823
|
+
const nextActive = openAICodexCredentialKey(active) === capturedKey ? validated : active;
|
|
1824
|
+
await this.writeDocument(makeV2Document(nextActive, credentials), document);
|
|
1825
|
+
return cloneCredential(validated);
|
|
1826
|
+
});
|
|
1827
|
+
}
|
|
1828
|
+
/** @inheritdoc */
|
|
1829
|
+
async list() {
|
|
1830
|
+
return await this.readDocument() === void 0 ? [] : [{
|
|
1831
|
+
providerId: OPENAI_CODEX_PROVIDER,
|
|
1832
|
+
type: "oauth"
|
|
1833
|
+
}];
|
|
1834
|
+
}
|
|
1835
|
+
/** List browser-safe account summaries without exposing provider account ids. */
|
|
1836
|
+
async accounts() {
|
|
1837
|
+
return accountSummaries(await this.readDocument());
|
|
1838
|
+
}
|
|
1839
|
+
/** Resolve the account id stored with one exact access token. */
|
|
1840
|
+
async accountIdForAccess(access) {
|
|
1841
|
+
const document = await this.readDocument();
|
|
1842
|
+
if (document === void 0) return void 0;
|
|
1843
|
+
return documentCredentials(document).find((credential) => credential.access === access)?.accountId;
|
|
1844
|
+
}
|
|
1845
|
+
/** Select a stored account using its browser-safe key. */
|
|
1846
|
+
async activate(selectedAccountKey) {
|
|
1847
|
+
await mkdir(dirname(this.filename), {
|
|
1848
|
+
recursive: true,
|
|
1849
|
+
mode: 448
|
|
1850
|
+
});
|
|
1851
|
+
return this.withWriterLock(async () => {
|
|
1852
|
+
const document = await this.readDocument();
|
|
1853
|
+
if (document === void 0) throw new Error("openai-codex: account not found");
|
|
1854
|
+
const credentials = documentCredentials(document);
|
|
1855
|
+
const selected = credentials.find((credential) => openAICodexCredentialKey(credential) === selectedAccountKey);
|
|
1856
|
+
if (selected === void 0) throw new Error("openai-codex: account not found");
|
|
1857
|
+
await this.writeDocument(makeV2Document(selected, credentials), document);
|
|
1858
|
+
return cloneCredential(selected);
|
|
1859
|
+
});
|
|
1860
|
+
}
|
|
1861
|
+
/** Remove one account; active removal requires an explicit stored replacement. */
|
|
1862
|
+
async removeAccount(selectedAccountKey, replacementAccountKey) {
|
|
1863
|
+
await mkdir(dirname(this.filename), {
|
|
1864
|
+
recursive: true,
|
|
1865
|
+
mode: 448
|
|
1866
|
+
});
|
|
1867
|
+
await this.withWriterLock(async () => {
|
|
1868
|
+
const document = await this.readDocument();
|
|
1869
|
+
if (document === void 0) throw new Error("openai-codex: account not found");
|
|
1870
|
+
const credentials = [...documentCredentials(document)];
|
|
1871
|
+
const removeIndex = credentials.findIndex((credential) => openAICodexCredentialKey(credential) === selectedAccountKey);
|
|
1872
|
+
if (removeIndex < 0) throw new Error("openai-codex: account not found");
|
|
1873
|
+
const removed = credentials[removeIndex];
|
|
1874
|
+
const active = activeCredential(document);
|
|
1875
|
+
const remaining = credentials.filter((_, index) => index !== removeIndex);
|
|
1876
|
+
let nextActive = active;
|
|
1877
|
+
if (openAICodexCredentialKey(removed) === openAICodexCredentialKey(active) && remaining.length > 0) {
|
|
1878
|
+
if (replacementAccountKey === void 0) throw new Error("openai-codex: removing the active account requires replacementAccountKey");
|
|
1879
|
+
const replacement = remaining.find((credential) => openAICodexCredentialKey(credential) === replacementAccountKey);
|
|
1880
|
+
if (replacement === void 0) throw new Error("openai-codex: replacement account not found");
|
|
1881
|
+
nextActive = replacement;
|
|
1882
|
+
} else if (replacementAccountKey !== void 0) throw new Error("openai-codex: replacementAccountKey is only valid when removing the active account");
|
|
1883
|
+
await rm(this.version1BackupFilename, { force: true });
|
|
1884
|
+
if (remaining.length === 0) {
|
|
1885
|
+
await rm(this.filename, { force: true });
|
|
1886
|
+
return;
|
|
1887
|
+
}
|
|
1888
|
+
await this.writeDocument(makeV2Document(nextActive, remaining));
|
|
1889
|
+
});
|
|
1890
|
+
}
|
|
1891
|
+
/** @inheritdoc */
|
|
1892
|
+
async modify(providerId, fn, options) {
|
|
1893
|
+
options?.signal?.throwIfAborted();
|
|
1894
|
+
if (providerId !== "openai-codex") throw new Error(`openai-codex: credential store does not own provider "${providerId}"`);
|
|
1895
|
+
await mkdir(dirname(this.filename), {
|
|
1896
|
+
recursive: true,
|
|
1897
|
+
mode: 448
|
|
1898
|
+
});
|
|
1899
|
+
return this.withWriterLock(async () => {
|
|
1900
|
+
const currentDocument = await this.readDocument();
|
|
1901
|
+
const current = currentDocument === void 0 ? void 0 : cloneCredential(activeCredential(currentDocument));
|
|
1902
|
+
options?.signal?.throwIfAborted();
|
|
1903
|
+
const candidate = await fn(current);
|
|
1904
|
+
if (candidate === void 0) return current;
|
|
1905
|
+
const validated = parseCredential(candidate, this.filename);
|
|
1906
|
+
const validatedKey = openAICodexCredentialKey(validated);
|
|
1907
|
+
const credentials = currentDocument === void 0 ? [] : [...documentCredentials(currentDocument)];
|
|
1908
|
+
const existingIndex = credentials.findIndex((credential) => openAICodexCredentialKey(credential) === validatedKey);
|
|
1909
|
+
if (existingIndex >= 0) credentials[existingIndex] = validated;
|
|
1910
|
+
else credentials.push(validated);
|
|
1911
|
+
if (credentials.length > 16) throw new Error(`openai-codex: credential store accepts at most ${String(16)} accounts`);
|
|
1912
|
+
await this.writeDocument(makeV2Document(validated, credentials), currentDocument);
|
|
1913
|
+
return cloneCredential(validated);
|
|
1914
|
+
});
|
|
1915
|
+
}
|
|
1916
|
+
/** @inheritdoc */
|
|
1917
|
+
async delete(providerId) {
|
|
1918
|
+
if (providerId !== "openai-codex") return;
|
|
1919
|
+
await mkdir(dirname(this.filename), {
|
|
1920
|
+
recursive: true,
|
|
1921
|
+
mode: 448
|
|
1922
|
+
});
|
|
1923
|
+
await this.withWriterLock(async () => {
|
|
1924
|
+
await rm(this.filename, { force: true });
|
|
1925
|
+
await rm(this.version1BackupFilename, { force: true });
|
|
1926
|
+
});
|
|
1927
|
+
}
|
|
1928
|
+
/** Allow the provider's 15-second refresh plus bounded filesystem completion. */
|
|
1929
|
+
withWriterLock(operation) {
|
|
1930
|
+
return withFileLock(this.filename, operation, { waitMs: 2e4 });
|
|
1931
|
+
}
|
|
1932
|
+
};
|
|
1933
|
+
// src/platform/auth/oauth-client.ts
|
|
1934
|
+
/**
|
|
1935
|
+
* OpenAI Codex OAuth orchestration shared by the plugin and standalone launcher.
|
|
1936
|
+
* @module dsh-codex-connect/auth
|
|
1937
|
+
*/
|
|
1938
|
+
/**
|
|
1939
|
+
* Complete provider-native OAuth and persist the resulting credential.
|
|
1940
|
+
* @param interaction - terminal or UI callbacks for the provider flow.
|
|
1941
|
+
* @param store - credential store, defaulting under `$DSH_HOME`.
|
|
1942
|
+
*/
|
|
1943
|
+
async function loginOpenAICodex(interaction, store = new OpenAICodexCredentialStore()) {
|
|
1944
|
+
const models = createModels({ credentials: store });
|
|
1945
|
+
const provider = openaiCodexProvider();
|
|
1946
|
+
let login;
|
|
1947
|
+
models.setProvider({
|
|
1948
|
+
...provider,
|
|
1949
|
+
auth: {
|
|
1950
|
+
...provider.auth,
|
|
1951
|
+
oauth: {
|
|
1952
|
+
...openaiCodexOAuth,
|
|
1953
|
+
login: (callbacks) => {
|
|
1954
|
+
login = openaiCodexOAuth.login(callbacks);
|
|
1955
|
+
return login;
|
|
1956
|
+
}
|
|
1957
|
+
}
|
|
1958
|
+
}
|
|
1959
|
+
});
|
|
1960
|
+
try {
|
|
1961
|
+
await models.login(OPENAI_CODEX_PROVIDER, "oauth", interaction);
|
|
1962
|
+
} finally {
|
|
1963
|
+
await login?.catch(() => void 0);
|
|
1964
|
+
}
|
|
1965
|
+
}
|
|
1966
|
+
/**
|
|
1967
|
+
* Remove the stored OpenAI Codex credential.
|
|
1968
|
+
* @param store - credential store, defaulting under `$DSH_HOME`.
|
|
1969
|
+
*/
|
|
1970
|
+
async function logoutOpenAICodex(store = new OpenAICodexCredentialStore()) {
|
|
1971
|
+
await store.delete(OPENAI_CODEX_PROVIDER);
|
|
1972
|
+
}
|
|
1973
|
+
/**
|
|
1974
|
+
* Read non-secret OpenAI Codex login state without refreshing the token.
|
|
1975
|
+
* @param store - credential store, defaulting under `$DSH_HOME`.
|
|
1976
|
+
* @returns stored login state and expiry.
|
|
1977
|
+
*/
|
|
1978
|
+
async function openAICodexAuthStatus(store = new OpenAICodexCredentialStore()) {
|
|
1979
|
+
const credential = await store.read(OPENAI_CODEX_PROVIDER);
|
|
1980
|
+
return credential?.type === "oauth" ? {
|
|
1981
|
+
authenticated: true,
|
|
1982
|
+
expiresAt: new Date(credential.expires)
|
|
1983
|
+
} : { authenticated: false };
|
|
1984
|
+
}
|
|
1985
|
+
// src/platform/http/trusted-origins.ts
|
|
1986
|
+
/** Owner-only allowlist for browser origins that may reach the Web OAuth routes. */
|
|
1987
|
+
/** Basename of the DSH-home-scoped browser-origin allowlist. */
|
|
1988
|
+
const OPENAI_CODEX_TRUSTED_ORIGINS_FILENAME = ".openai-codex-trusted-origins.json";
|
|
1989
|
+
/** Only supported policy mode; a future mode must not be silently accepted. */
|
|
1990
|
+
const TRUSTED_ORIGINS_MODE = "allowlist";
|
|
1991
|
+
/** Whether a filesystem error reports an absent path. */
|
|
1992
|
+
function isENOENT(error) {
|
|
1993
|
+
return error?.code === "ENOENT";
|
|
1994
|
+
}
|
|
1995
|
+
/** Reject a sidecar readable by another POSIX user. */
|
|
1996
|
+
async function assertOwnerOnly(filename) {
|
|
1997
|
+
let metadata;
|
|
1998
|
+
try {
|
|
1999
|
+
metadata = await lstat(filename);
|
|
2000
|
+
} catch (error) {
|
|
2001
|
+
if (isENOENT(error)) return;
|
|
2002
|
+
throw error;
|
|
2003
|
+
}
|
|
2004
|
+
if (!metadata.isFile()) throw new Error(`openai-codex: ${filename} is not a regular file`);
|
|
2005
|
+
/* v8 ignore next -- native Windows coverage takes the mode-less branch */
|
|
2006
|
+
if (process.platform === "win32") return;
|
|
2007
|
+
/* v8 ignore start -- POSIX tests cover this branch; Windows cannot express it */
|
|
2008
|
+
if ((metadata.mode & 63) !== 0) throw new Error(`openai-codex: ${filename} is readable beyond its owner (mode ${(metadata.mode & 511).toString(8)}); run "chmod 600 ${filename}" before starting again`);
|
|
2009
|
+
/* v8 ignore stop */
|
|
2010
|
+
}
|
|
2011
|
+
/** Reject malformed input without echoing its contents into an error. */
|
|
2012
|
+
function parseDocument(text, filename) {
|
|
2013
|
+
let value;
|
|
2014
|
+
try {
|
|
2015
|
+
value = JSON.parse(text);
|
|
2016
|
+
} catch {
|
|
2017
|
+
throw new Error(`openai-codex: ${filename} is not valid JSON`);
|
|
2018
|
+
}
|
|
2019
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`openai-codex: ${filename} must contain an object`);
|
|
2020
|
+
const document = value;
|
|
2021
|
+
if (Object.keys(document).some((key) => ![
|
|
2022
|
+
"version",
|
|
2023
|
+
"mode",
|
|
2024
|
+
"origins"
|
|
2025
|
+
].includes(key))) throw new Error(`openai-codex: ${filename} contains an unknown top-level field`);
|
|
2026
|
+
if (document["version"] !== 1) throw new Error(`openai-codex: ${filename} has unsupported trusted-origins format version ${String(document["version"])}`);
|
|
2027
|
+
if (document["mode"] !== "allowlist") throw new Error(`openai-codex: ${filename} has unsupported trusted-origins mode`);
|
|
2028
|
+
const rawOrigins = document["origins"];
|
|
2029
|
+
if (!Array.isArray(rawOrigins)) throw new Error(`openai-codex: ${filename} origins must be an array`);
|
|
2030
|
+
const origins = /* @__PURE__ */ new Set();
|
|
2031
|
+
for (const rawOrigin of rawOrigins) {
|
|
2032
|
+
if (typeof rawOrigin !== "string") throw new Error(`openai-codex: ${filename} origins must contain strings`);
|
|
2033
|
+
try {
|
|
2034
|
+
origins.add(normalizeTrustedOrigin(rawOrigin));
|
|
2035
|
+
} catch {
|
|
2036
|
+
throw new Error(`openai-codex: ${filename} contains an invalid trusted origin`);
|
|
2037
|
+
}
|
|
2038
|
+
}
|
|
2039
|
+
return {
|
|
2040
|
+
version: 1,
|
|
2041
|
+
mode: TRUSTED_ORIGINS_MODE,
|
|
2042
|
+
origins: [...origins].sort()
|
|
2043
|
+
};
|
|
2044
|
+
}
|
|
2045
|
+
/**
|
|
2046
|
+
* Normalize one exact browser origin.
|
|
2047
|
+
*
|
|
2048
|
+
* Only HTTP(S) origins are accepted. Credentials, non-root paths, queries,
|
|
2049
|
+
* fragments, wildcards, and CIDR-looking host paths are rejected. WHATWG URL
|
|
2050
|
+
* normalization lowercases the scheme/host and removes default ports.
|
|
2051
|
+
*/
|
|
2052
|
+
function normalizeTrustedOrigin(rawOrigin) {
|
|
2053
|
+
if (typeof rawOrigin !== "string" || rawOrigin.length === 0 || rawOrigin.trim() !== rawOrigin) throw new Error("trusted origin must be a non-empty URL without surrounding whitespace");
|
|
2054
|
+
let origin;
|
|
2055
|
+
try {
|
|
2056
|
+
origin = new URL(rawOrigin);
|
|
2057
|
+
} catch {
|
|
2058
|
+
throw new Error("trusted origin must be a valid URL");
|
|
2059
|
+
}
|
|
2060
|
+
if (origin.protocol !== "http:" && origin.protocol !== "https:") throw new Error("trusted origin protocol must be http or https");
|
|
2061
|
+
if (origin.username !== "" || origin.password !== "") throw new Error("trusted origin must not contain credentials");
|
|
2062
|
+
if (origin.pathname !== "/" || origin.search !== "" || origin.hash !== "") throw new Error("trusted origin must not contain a path, query, or fragment");
|
|
2063
|
+
if (origin.hostname === "" || origin.hostname.includes("*")) throw new Error("trusted origin host must be exact");
|
|
2064
|
+
if (origin.pathname !== "/" || /(?:^|\/)\d+\/\d+$/u.test(rawOrigin)) throw new Error("trusted origin must not be a CIDR or path");
|
|
2065
|
+
if (origin.origin === "null") throw new Error("trusted origin must have an HTTP(S) host");
|
|
2066
|
+
return origin.origin;
|
|
2067
|
+
}
|
|
2068
|
+
/** Resolve the sidecar path under one DSH home. */
|
|
2069
|
+
function openAICodexTrustedOriginsPath(dshHome) {
|
|
2070
|
+
return resolve(join(resolveDshHome(dshHome), OPENAI_CODEX_TRUSTED_ORIGINS_FILENAME));
|
|
2071
|
+
}
|
|
2072
|
+
/** File-backed exact-origin allowlist. */
|
|
2073
|
+
var OpenAICodexTrustedOriginsStore = class {
|
|
2074
|
+
/** Absolute sidecar path. */
|
|
2075
|
+
filename;
|
|
2076
|
+
constructor(filename = openAICodexTrustedOriginsPath()) {
|
|
2077
|
+
this.filename = resolve(filename);
|
|
2078
|
+
}
|
|
2079
|
+
async readCurrent() {
|
|
2080
|
+
await assertOwnerOnly(this.filename);
|
|
2081
|
+
let text;
|
|
2082
|
+
try {
|
|
2083
|
+
text = await readFile(this.filename, "utf8");
|
|
2084
|
+
} catch (error) {
|
|
2085
|
+
if (isENOENT(error)) return {
|
|
2086
|
+
version: 1,
|
|
2087
|
+
mode: TRUSTED_ORIGINS_MODE,
|
|
2088
|
+
origins: []
|
|
2089
|
+
};
|
|
2090
|
+
throw error;
|
|
2091
|
+
}
|
|
2092
|
+
return parseDocument(text, this.filename);
|
|
2093
|
+
}
|
|
2094
|
+
/** Read the current canonical list without acquiring the writer lock. */
|
|
2095
|
+
async list() {
|
|
2096
|
+
return [...(await this.readCurrent()).origins];
|
|
2097
|
+
}
|
|
2098
|
+
/** Whether an exact normalized origin is currently trusted. */
|
|
2099
|
+
async has(origin) {
|
|
2100
|
+
const normalized = normalizeTrustedOrigin(origin);
|
|
2101
|
+
return (await this.readCurrent()).origins.includes(normalized);
|
|
2102
|
+
}
|
|
2103
|
+
/** Add one origin idempotently and return the resulting sorted list. */
|
|
2104
|
+
async trust(origin) {
|
|
2105
|
+
const normalized = normalizeTrustedOrigin(origin);
|
|
2106
|
+
await mkdir(dirname(this.filename), {
|
|
2107
|
+
recursive: true,
|
|
2108
|
+
mode: 448
|
|
2109
|
+
});
|
|
2110
|
+
return withFileLock(this.filename, async () => {
|
|
2111
|
+
const current = await this.readCurrent();
|
|
2112
|
+
if (current.origins.includes(normalized)) return [...current.origins];
|
|
2113
|
+
const next = {
|
|
2114
|
+
version: 1,
|
|
2115
|
+
mode: TRUSTED_ORIGINS_MODE,
|
|
2116
|
+
origins: [...current.origins, normalized].sort()
|
|
2117
|
+
};
|
|
2118
|
+
await writeFileAtomic(this.filename, `${JSON.stringify(next, null, 2)}\n`, {
|
|
2119
|
+
mode: 384,
|
|
2120
|
+
dirMode: 448
|
|
2121
|
+
});
|
|
2122
|
+
return [...next.origins];
|
|
2123
|
+
});
|
|
2124
|
+
}
|
|
2125
|
+
/** Remove one origin idempotently and return the resulting sorted list. */
|
|
2126
|
+
async untrust(origin) {
|
|
2127
|
+
const normalized = normalizeTrustedOrigin(origin);
|
|
2128
|
+
await mkdir(dirname(this.filename), {
|
|
2129
|
+
recursive: true,
|
|
2130
|
+
mode: 448
|
|
2131
|
+
});
|
|
2132
|
+
return withFileLock(this.filename, async () => {
|
|
2133
|
+
const current = await this.readCurrent();
|
|
2134
|
+
if (!current.origins.includes(normalized)) return [...current.origins];
|
|
2135
|
+
const next = {
|
|
2136
|
+
version: 1,
|
|
2137
|
+
mode: TRUSTED_ORIGINS_MODE,
|
|
2138
|
+
origins: current.origins.filter((candidate) => candidate !== normalized)
|
|
2139
|
+
};
|
|
2140
|
+
await writeFileAtomic(this.filename, `${JSON.stringify(next, null, 2)}\n`, {
|
|
2141
|
+
mode: 384,
|
|
2142
|
+
dirMode: 448
|
|
2143
|
+
});
|
|
2144
|
+
return [...next.origins];
|
|
2145
|
+
});
|
|
2146
|
+
}
|
|
2147
|
+
};
|
|
2148
|
+
// src/version.ts
|
|
2149
|
+
const CODEX_CONNECT_VERSION = "0.2.1";
|
|
2150
|
+
// src/platform/runtime/doctor.ts
|
|
2151
|
+
/** Lightweight, secret-free local diagnostics and duplicate-provider guidance. */
|
|
2152
|
+
const MAX_PATCH_BYTES = 524288;
|
|
2153
|
+
/** Actionable message for legacy/manual `openai-codex` adapter collisions. */
|
|
2154
|
+
function openAICodexConflictMessage() {
|
|
2155
|
+
return "Codex Connect cannot register provider \"openai-codex\" because another adapter already owns it. Remove or disable the legacy dsh-codex bundle or manual openai-codex provider row, then restart Harness.";
|
|
2156
|
+
}
|
|
2157
|
+
function hasLegacyPackagePatchEntry(content) {
|
|
2158
|
+
return content.split(/\r?\n(?=- )/u).some((block) => /^\s*-?\s*id:\s*["']?llm-openai-codex["']?\s*$/mu.test(block) && /^\s*-?\s*name:\s*["']?dsh-codex-connect["']?\s*$/mu.test(block));
|
|
2159
|
+
}
|
|
2160
|
+
async function findLegacyProfilePatches(dshHome) {
|
|
2161
|
+
const profilesDir = join(dshHome, "profiles");
|
|
2162
|
+
let entries;
|
|
2163
|
+
try {
|
|
2164
|
+
entries = await readdir(profilesDir, { withFileTypes: true });
|
|
2165
|
+
} catch {
|
|
2166
|
+
return [];
|
|
2167
|
+
}
|
|
2168
|
+
const matches = [];
|
|
2169
|
+
for (const entry of entries) {
|
|
2170
|
+
if (!entry.isDirectory()) continue;
|
|
2171
|
+
const patchPath = join(profilesDir, entry.name, "cordis.patch.yml");
|
|
2172
|
+
try {
|
|
2173
|
+
const info = await lstat(patchPath);
|
|
2174
|
+
if (!info.isFile() || info.size > MAX_PATCH_BYTES) continue;
|
|
2175
|
+
if (hasLegacyPackagePatchEntry(await readFile(patchPath, "utf8"))) matches.push(entry.name);
|
|
2176
|
+
} catch {
|
|
2177
|
+
continue;
|
|
2178
|
+
}
|
|
2179
|
+
}
|
|
2180
|
+
return matches.sort();
|
|
2181
|
+
}
|
|
2182
|
+
/** Inspect local OAuth file metadata without reading credential contents. */
|
|
2183
|
+
async function diagnoseOpenAICodex(options = {}) {
|
|
2184
|
+
const path = options.credentialPath ?? openAICodexAuthPath();
|
|
2185
|
+
const dshHome = options.dshHome ?? dirname(path);
|
|
2186
|
+
let state = "missing";
|
|
2187
|
+
let mode;
|
|
2188
|
+
try {
|
|
2189
|
+
const info = await lstat(path);
|
|
2190
|
+
if (!info.isFile()) state = "not-a-regular-file";
|
|
2191
|
+
else if (process.platform === "win32") state = "owner-only";
|
|
2192
|
+
else {
|
|
2193
|
+
mode = (info.mode & 511).toString(8).padStart(3, "0");
|
|
2194
|
+
state = (info.mode & 63) === 0 ? "owner-only" : "permissions-too-broad";
|
|
2195
|
+
}
|
|
2196
|
+
} catch (error) {
|
|
2197
|
+
state = error?.code === "ENOENT" ? "missing" : "unreadable-metadata";
|
|
2198
|
+
}
|
|
2199
|
+
const providerConflict = options.providerIds?.includes("openai-codex") ?? false;
|
|
2200
|
+
const legacyProfiles = await findLegacyProfilePatches(dshHome);
|
|
2201
|
+
const hints = [];
|
|
2202
|
+
if (state === "missing") hints.push("Sign in only when you are ready; installation does not start OAuth.");
|
|
2203
|
+
if (state === "permissions-too-broad") hints.push(`Restrict the OAuth file to its owner before use (current mode ${mode}).`);
|
|
2204
|
+
if (state === "not-a-regular-file") hints.push("Replace the OAuth path with an owner-only regular file created by Codex Connect login.");
|
|
2205
|
+
if (state === "unreadable-metadata") hints.push("Harness could not inspect the OAuth file metadata; check the parent directory and file ownership.");
|
|
2206
|
+
if (providerConflict) hints.push(openAICodexConflictMessage());
|
|
2207
|
+
for (const profile of legacyProfiles) hints.push(`Legacy package name "dsh-codex-connect" found for llm-openai-codex in profiles/${profile}/cordis.patch.yml; change name to "@shuind/dsh-codex-connect" (or remove the old entry) and restart DSH.`);
|
|
2208
|
+
return {
|
|
2209
|
+
package: "@shuind/dsh-codex-connect",
|
|
2210
|
+
version: CODEX_CONNECT_VERSION,
|
|
2211
|
+
node: process.version,
|
|
2212
|
+
credentialFile: {
|
|
2213
|
+
path,
|
|
2214
|
+
state,
|
|
2215
|
+
...mode === void 0 ? {} : { mode }
|
|
2216
|
+
},
|
|
2217
|
+
capabilities: {
|
|
2218
|
+
modelProvider: true,
|
|
2219
|
+
search: options.enableSearch === true,
|
|
2220
|
+
imageGeneration: options.enableImageGeneration === true,
|
|
2221
|
+
changesHarnessDefaultModel: false,
|
|
2222
|
+
changesHarnessSearchRoute: options.enableSearch === true
|
|
2223
|
+
},
|
|
2224
|
+
providerConflict,
|
|
2225
|
+
hints
|
|
2226
|
+
};
|
|
2227
|
+
}
|
|
2228
|
+
// src/bin.ts
|
|
2229
|
+
/** Standalone credential CLI for the optional OpenAI Codex bundle. */
|
|
2230
|
+
const JSON_SCHEMA_VERSION = 1;
|
|
2231
|
+
/** Open one trusted HTTPS URL with the platform browser, best effort. */
|
|
2232
|
+
function openBrowser(rawUrl) {
|
|
2233
|
+
const url = new URL(rawUrl);
|
|
2234
|
+
if (url.protocol !== "https:") throw new Error(`refusing to open non-HTTPS authorization URL from ${url.host}`);
|
|
2235
|
+
const command = process.platform === "win32" ? {
|
|
2236
|
+
file: "rundll32.exe",
|
|
2237
|
+
args: ["url.dll,FileProtocolHandler", url.href]
|
|
2238
|
+
} : process.platform === "darwin" ? {
|
|
2239
|
+
file: "open",
|
|
2240
|
+
args: [url.href]
|
|
2241
|
+
} : {
|
|
2242
|
+
file: "xdg-open",
|
|
2243
|
+
args: [url.href]
|
|
2244
|
+
};
|
|
2245
|
+
try {
|
|
2246
|
+
const child = spawn(command.file, command.args, {
|
|
2247
|
+
detached: true,
|
|
2248
|
+
stdio: "ignore",
|
|
2249
|
+
windowsHide: true
|
|
2250
|
+
});
|
|
2251
|
+
child.on("error", () => {});
|
|
2252
|
+
child.unref();
|
|
2253
|
+
} catch {}
|
|
2254
|
+
}
|
|
2255
|
+
/** Render one provider event without exposing stored credentials. */
|
|
2256
|
+
function notify(event, useBrowser) {
|
|
2257
|
+
switch (event.type) {
|
|
2258
|
+
case "auth_url":
|
|
2259
|
+
process.stdout.write(`Open this URL to sign in:\n${event.url}\n`);
|
|
2260
|
+
if (event.instructions !== void 0) process.stdout.write(`${event.instructions}\n`);
|
|
2261
|
+
if (useBrowser) openBrowser(event.url);
|
|
2262
|
+
break;
|
|
2263
|
+
case "device_code":
|
|
2264
|
+
process.stdout.write(`Open this URL to sign in:\n${event.verificationUri}\nEnter code: ${event.userCode}\n`);
|
|
2265
|
+
if (useBrowser) openBrowser(event.verificationUri);
|
|
2266
|
+
break;
|
|
2267
|
+
case "info":
|
|
2268
|
+
case "progress": process.stdout.write(`${event.message}\n`);
|
|
2269
|
+
}
|
|
2270
|
+
}
|
|
2271
|
+
/** Answer a provider auth prompt through the terminal. */
|
|
2272
|
+
async function answerPrompt(prompt, deviceCode, question) {
|
|
2273
|
+
if (prompt.type === "select") {
|
|
2274
|
+
const wanted = deviceCode ? "device_code" : "browser";
|
|
2275
|
+
if (!prompt.options.some((option) => option.id === wanted)) throw new Error(`OpenAI Codex login did not offer the requested ${wanted} method`);
|
|
2276
|
+
return wanted;
|
|
2277
|
+
}
|
|
2278
|
+
const suffix = prompt.placeholder === void 0 ? "" : ` (${prompt.placeholder})`;
|
|
2279
|
+
return question(`${prompt.message}${suffix}: `, { ...prompt.signal === void 0 ? {} : { signal: prompt.signal } });
|
|
2280
|
+
}
|
|
2281
|
+
/** Print the standalone command help. */
|
|
2282
|
+
function printHelp() {
|
|
2283
|
+
process.stdout.write([
|
|
2284
|
+
"Usage: dsh-codex-connect <doctor|login|logout|status> [--device-code|--json]",
|
|
2285
|
+
" dsh-codex-connect doctor [--json]",
|
|
2286
|
+
" dsh-codex-connect trust-origin <origin>",
|
|
2287
|
+
" dsh-codex-connect trusted-origins [--json]",
|
|
2288
|
+
" dsh-codex-connect untrust-origin <origin>",
|
|
2289
|
+
"",
|
|
2290
|
+
" doctor inspect secret-free local package and OAuth file metadata",
|
|
2291
|
+
" login sign in with a separate ChatGPT OAuth session",
|
|
2292
|
+
" logout remove the dsh credential without changing ~/.codex",
|
|
2293
|
+
" status report non-secret dsh credential state",
|
|
2294
|
+
" trust-origin allow one exact browser origin to reach Web OAuth routes",
|
|
2295
|
+
" trusted-origins list the currently allowed browser origins",
|
|
2296
|
+
" untrust-origin remove one exact browser origin from the allowlist",
|
|
2297
|
+
" --device-code use headless device-code login (login only)",
|
|
2298
|
+
" --json emit one JSON document (doctor/status/trusted-origins)",
|
|
2299
|
+
""
|
|
2300
|
+
].join("\n"));
|
|
2301
|
+
}
|
|
2302
|
+
function doctorExitCode(report) {
|
|
2303
|
+
return report.credentialFile.state === "permissions-too-broad" || report.credentialFile.state === "not-a-regular-file" || report.credentialFile.state === "unreadable-metadata" ? 1 : 0;
|
|
2304
|
+
}
|
|
2305
|
+
/** Project the diagnostic report without its absolute credential pathname. */
|
|
2306
|
+
function doctorJson(report) {
|
|
2307
|
+
return {
|
|
2308
|
+
schemaVersion: JSON_SCHEMA_VERSION,
|
|
2309
|
+
package: report.package,
|
|
2310
|
+
version: report.version,
|
|
2311
|
+
node: report.node,
|
|
2312
|
+
credentialFile: {
|
|
2313
|
+
state: report.credentialFile.state,
|
|
2314
|
+
...report.credentialFile.mode === void 0 ? {} : { mode: report.credentialFile.mode }
|
|
2315
|
+
},
|
|
2316
|
+
capabilities: report.capabilities,
|
|
2317
|
+
providerConflict: report.providerConflict,
|
|
2318
|
+
hints: report.hints
|
|
2319
|
+
};
|
|
2320
|
+
}
|
|
2321
|
+
function printJson(value) {
|
|
2322
|
+
process.stdout.write(`${JSON.stringify(value)}\n`);
|
|
2323
|
+
}
|
|
2324
|
+
/** Execute one boot-free credential command. */
|
|
2325
|
+
async function run(argv) {
|
|
2326
|
+
if (argv.length === 0 || argv[0] === "--help" || argv[0] === "-h") {
|
|
2327
|
+
printHelp();
|
|
2328
|
+
return 0;
|
|
2329
|
+
}
|
|
2330
|
+
const [rawAction, ...flags] = argv;
|
|
2331
|
+
if (![
|
|
2332
|
+
"doctor",
|
|
2333
|
+
"login",
|
|
2334
|
+
"logout",
|
|
2335
|
+
"status",
|
|
2336
|
+
"trust-origin",
|
|
2337
|
+
"trusted-origins",
|
|
2338
|
+
"untrust-origin"
|
|
2339
|
+
].includes(rawAction)) {
|
|
2340
|
+
process.stderr.write(`dsh-codex-connect: expected doctor, login, logout, status, trust-origin, trusted-origins, or untrust-origin; got ${JSON.stringify(rawAction)}\n`);
|
|
2341
|
+
return 1;
|
|
2342
|
+
}
|
|
2343
|
+
const action = rawAction;
|
|
2344
|
+
const originArgument = action === "trust-origin" || action === "untrust-origin" ? flags[0] : void 0;
|
|
2345
|
+
const optionFlags = action === "trust-origin" || action === "untrust-origin" ? flags.slice(1) : flags;
|
|
2346
|
+
const deviceCode = optionFlags.includes("--device-code");
|
|
2347
|
+
const jsonOutput = optionFlags.includes("--json");
|
|
2348
|
+
if (optionFlags.filter((flag) => flag !== "--device-code" && flag !== "--json").length > 0 || deviceCode && action !== "login" || jsonOutput && (action === "login" || action === "logout" || deviceCode) || (action === "trust-origin" || action === "untrust-origin") && (originArgument === void 0 || optionFlags.length !== 0)) {
|
|
2349
|
+
process.stderr.write(`dsh-codex-connect: invalid options for ${action}\n`);
|
|
2350
|
+
return 1;
|
|
2351
|
+
}
|
|
2352
|
+
try {
|
|
2353
|
+
switch (action) {
|
|
2354
|
+
case "doctor": {
|
|
2355
|
+
const report = await diagnoseOpenAICodex();
|
|
2356
|
+
if (jsonOutput) {
|
|
2357
|
+
printJson(doctorJson(report));
|
|
2358
|
+
return doctorExitCode(report);
|
|
2359
|
+
}
|
|
2360
|
+
process.stdout.write([
|
|
2361
|
+
`Codex Connect ${report.version} on ${report.node}`,
|
|
2362
|
+
`OAuth file metadata: ${report.credentialFile.state} (${report.credentialFile.path})`,
|
|
2363
|
+
`Optional capability defaults: search=${report.capabilities.search ? "enabled" : "disabled"}, imageGeneration=${report.capabilities.imageGeneration ? "enabled" : "disabled"}`,
|
|
2364
|
+
"Harness defaults: unchanged by this plugin",
|
|
2365
|
+
...report.hints.map((hint) => `Hint: ${hint}`),
|
|
2366
|
+
""
|
|
2367
|
+
].join("\n"));
|
|
2368
|
+
return doctorExitCode(report);
|
|
2369
|
+
}
|
|
2370
|
+
case "status": {
|
|
2371
|
+
const status = await openAICodexAuthStatus();
|
|
2372
|
+
if (jsonOutput) {
|
|
2373
|
+
printJson({
|
|
2374
|
+
schemaVersion: JSON_SCHEMA_VERSION,
|
|
2375
|
+
package: "@shuind/dsh-codex-connect",
|
|
2376
|
+
version: CODEX_CONNECT_VERSION,
|
|
2377
|
+
status: status.authenticated ? "signed-in" : "signed-out"
|
|
2378
|
+
});
|
|
2379
|
+
return status.authenticated ? 0 : 1;
|
|
2380
|
+
}
|
|
2381
|
+
if (!status.authenticated) {
|
|
2382
|
+
process.stdout.write("Codex Connect: signed out\n");
|
|
2383
|
+
return 1;
|
|
2384
|
+
}
|
|
2385
|
+
const expires = status.expiresAt;
|
|
2386
|
+
const suffix = expires === void 0 || Number.isNaN(expires.valueOf()) ? "" : `; access token expires ${expires.toISOString()} (refresh is automatic)`;
|
|
2387
|
+
process.stdout.write(`Codex Connect: signed in${suffix}\n`);
|
|
2388
|
+
return 0;
|
|
2389
|
+
}
|
|
2390
|
+
case "trusted-origins": {
|
|
2391
|
+
const origins = await new OpenAICodexTrustedOriginsStore().list();
|
|
2392
|
+
if (jsonOutput) printJson({
|
|
2393
|
+
schemaVersion: JSON_SCHEMA_VERSION,
|
|
2394
|
+
origins
|
|
2395
|
+
});
|
|
2396
|
+
else for (const origin of origins) process.stdout.write(`${origin}\n`);
|
|
2397
|
+
return 0;
|
|
2398
|
+
}
|
|
2399
|
+
case "trust-origin": {
|
|
2400
|
+
if (originArgument === void 0) return 1;
|
|
2401
|
+
const normalized = normalizeTrustedOrigin(originArgument);
|
|
2402
|
+
const origins = await new OpenAICodexTrustedOriginsStore().trust(originArgument);
|
|
2403
|
+
process.stdout.write(`Trusted browser origin: ${normalized}\n`);
|
|
2404
|
+
process.stdout.write(`Trusted origins: ${origins.join(", ") || "(none)"}\n`);
|
|
2405
|
+
return 0;
|
|
2406
|
+
}
|
|
2407
|
+
case "untrust-origin": {
|
|
2408
|
+
if (originArgument === void 0) return 1;
|
|
2409
|
+
const normalized = normalizeTrustedOrigin(originArgument);
|
|
2410
|
+
const origins = await new OpenAICodexTrustedOriginsStore().untrust(originArgument);
|
|
2411
|
+
process.stdout.write(`Untrusted browser origin: ${normalized}\n`);
|
|
2412
|
+
process.stdout.write(`Trusted origins: ${origins.join(", ") || "(none)"}\n`);
|
|
2413
|
+
return 0;
|
|
2414
|
+
}
|
|
2415
|
+
case "logout":
|
|
2416
|
+
await logoutOpenAICodex();
|
|
2417
|
+
process.stdout.write(`Codex Connect: signed out; removed ${openAICodexAuthPath()}\n`);
|
|
2418
|
+
return 0;
|
|
2419
|
+
case "login": {
|
|
2420
|
+
const readline = createInterface({
|
|
2421
|
+
input: process.stdin,
|
|
2422
|
+
output: process.stdout
|
|
2423
|
+
});
|
|
2424
|
+
try {
|
|
2425
|
+
await loginOpenAICodex({
|
|
2426
|
+
prompt: (prompt) => answerPrompt(prompt, deviceCode, (text, options) => readline.question(text, options)),
|
|
2427
|
+
notify: (event) => notify(event, true)
|
|
2428
|
+
});
|
|
2429
|
+
} finally {
|
|
2430
|
+
readline.close();
|
|
2431
|
+
}
|
|
2432
|
+
process.stdout.write(`Codex Connect: signed in; credentials saved to ${openAICodexAuthPath()}\n`);
|
|
2433
|
+
return 0;
|
|
2434
|
+
}
|
|
2435
|
+
}
|
|
2436
|
+
} catch (error) {
|
|
2437
|
+
process.stderr.write(`dsh-codex-connect: ${action} failed: ${publicAuthError(error)}\n`);
|
|
2438
|
+
return 1;
|
|
2439
|
+
}
|
|
2440
|
+
}
|
|
2441
|
+
if (process.argv[1] !== void 0 && fileURLToPath(import.meta.url) === realpathSync(process.argv[1])) process.exitCode = await run(process.argv.slice(2));
|
|
2442
|
+
export { run };
|