xsai-codex 0.0.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/LICENSE.md +21 -0
- package/README.md +41 -0
- package/dist/index.d.ts +33 -0
- package/dist/index.js +168 -0
- package/package.json +50 -0
package/LICENSE.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Moeru AI
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# xsAI Codex
|
|
2
|
+
|
|
3
|
+
OpenAI Codex provider for xsAI.
|
|
4
|
+
|
|
5
|
+
Requires Baseline 2025 [`Uint8Array.fromBase64`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array/fromBase64) support.
|
|
6
|
+
|
|
7
|
+
## Usage
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { responses } from '@xsai-ext/responses'
|
|
11
|
+
import { authorizeCodexHeadless, createCodex } from 'xsai-codex'
|
|
12
|
+
|
|
13
|
+
const auth = await authorizeCodexHeadless({
|
|
14
|
+
onUserCode: ({ instructions }) => {
|
|
15
|
+
console.log(instructions)
|
|
16
|
+
},
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
const codex = await createCodex({ auth })
|
|
20
|
+
|
|
21
|
+
const result = responses({
|
|
22
|
+
...(await codex('gpt-5.5')),
|
|
23
|
+
input: 'Write a small TypeScript function.',
|
|
24
|
+
instructions: 'You\'re a helpful assistant.',
|
|
25
|
+
// maxOutputTokens: 0 // Codex doesn't support `maxOutputTokens`.
|
|
26
|
+
store: false, // `store` must be `false`.
|
|
27
|
+
})
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
### Example
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
git clone https://github.com/moeru-ai/xsai-codex
|
|
34
|
+
cd xsai-codex
|
|
35
|
+
pnpm i
|
|
36
|
+
pnpm dev
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## License
|
|
40
|
+
|
|
41
|
+
[MIT](LICENSE.md)
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { ResponsesOptions } from '@xsai-ext/responses';
|
|
2
|
+
|
|
3
|
+
type CodexModels = 'gpt-5.2' | 'gpt-5.3-codex' | 'gpt-5.4' | 'gpt-5.4-mini' | 'gpt-5.5';
|
|
4
|
+
|
|
5
|
+
interface CodexAuthTokens {
|
|
6
|
+
access: string;
|
|
7
|
+
accountId?: string;
|
|
8
|
+
expires: number;
|
|
9
|
+
refresh: string;
|
|
10
|
+
}
|
|
11
|
+
interface CodexHeadlessAuthorizeOptions {
|
|
12
|
+
onUserCode?: (info: CodexUserCodeInfo) => Promise<void> | void;
|
|
13
|
+
}
|
|
14
|
+
interface CodexUserCodeInfo {
|
|
15
|
+
instructions: string;
|
|
16
|
+
interval: number;
|
|
17
|
+
url: string;
|
|
18
|
+
userCode: string;
|
|
19
|
+
}
|
|
20
|
+
declare const authorizeCodexHeadless: (options?: CodexHeadlessAuthorizeOptions) => Promise<CodexAuthTokens>;
|
|
21
|
+
|
|
22
|
+
interface CreateCodexOptions {
|
|
23
|
+
auth: (() => CodexAuthTokens | Promise<CodexAuthTokens>) | CodexAuthTokens;
|
|
24
|
+
onAuthUpdate?: (auth: CodexAuthTokens) => Promise<void> | void;
|
|
25
|
+
originator?: string;
|
|
26
|
+
sessionId?: string;
|
|
27
|
+
userAgent?: string;
|
|
28
|
+
}
|
|
29
|
+
type CreateCodexResult = (model: CodexModels | (string & {})) => Promise<Pick<ResponsesOptions, 'apiKey' | 'baseURL' | 'headers' | 'model'>>;
|
|
30
|
+
declare const createCodex: (options: CreateCodexOptions) => Promise<CreateCodexResult>;
|
|
31
|
+
|
|
32
|
+
export { authorizeCodexHeadless, createCodex };
|
|
33
|
+
export type { CodexAuthTokens, CodexHeadlessAuthorizeOptions, CodexModels, CodexUserCodeInfo, CreateCodexOptions, CreateCodexResult };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
var version = "0.0.1";
|
|
2
|
+
|
|
3
|
+
const CODEX_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";
|
|
4
|
+
const CODEX_ISSUER = "https://auth.openai.com";
|
|
5
|
+
const CODEX_TOKEN_URL = `${CODEX_ISSUER}/oauth/token`;
|
|
6
|
+
const CODEX_DEVICE_AUTH_URL = `${CODEX_ISSUER}/api/accounts/deviceauth/usercode`;
|
|
7
|
+
const CODEX_DEVICE_TOKEN_URL = `${CODEX_ISSUER}/api/accounts/deviceauth/token`;
|
|
8
|
+
const CODEX_DEVICE_URL = `${CODEX_ISSUER}/codex/device`;
|
|
9
|
+
const CODEX_DEVICE_REDIRECT_URL = `${CODEX_ISSUER}/deviceauth/callback`;
|
|
10
|
+
const CODEX_OAUTH_POLLING_SAFETY_MARGIN_MS = 3e3;
|
|
11
|
+
const CODEX_TOKEN_REFRESH_MARGIN_MS = 6e4;
|
|
12
|
+
const CODEX_DUMMY_API_KEY = "codex-oauth";
|
|
13
|
+
const CODEX_DEFAULT_ORIGINATOR = "xsai-codex";
|
|
14
|
+
const CODEX_DEFAULT_USER_AGENT = `xsai-codex/${version}`;
|
|
15
|
+
const CODEX_BASE_URL = "https://chatgpt.com/backend-api/codex/";
|
|
16
|
+
|
|
17
|
+
const sleep = async (ms) => (
|
|
18
|
+
// eslint-disable-next-line @masknet/prefer-timer-id
|
|
19
|
+
new Promise((resolve) => setTimeout(resolve, ms))
|
|
20
|
+
);
|
|
21
|
+
const formatResponseError = async (message, response) => {
|
|
22
|
+
const body = await response.text().catch(() => "");
|
|
23
|
+
const details = body.trim().slice(0, 500);
|
|
24
|
+
return details.length > 0 ? `${message}: ${response.status} ${details}` : `${message}: ${response.status}`;
|
|
25
|
+
};
|
|
26
|
+
const jsonFetch = async (url, init, errorMessage) => {
|
|
27
|
+
const response = await fetch(url, init);
|
|
28
|
+
if (!response.ok) {
|
|
29
|
+
throw new Error(await formatResponseError(errorMessage, response));
|
|
30
|
+
}
|
|
31
|
+
return response.json();
|
|
32
|
+
};
|
|
33
|
+
const parseJwtClaims = (token) => {
|
|
34
|
+
const parts = token.split(".");
|
|
35
|
+
if (parts.length !== 3) {
|
|
36
|
+
return void 0;
|
|
37
|
+
}
|
|
38
|
+
try {
|
|
39
|
+
const payload = parts[1];
|
|
40
|
+
const bytes = Uint8Array.fromBase64(payload, { alphabet: "base64url" });
|
|
41
|
+
return JSON.parse(new TextDecoder().decode(bytes));
|
|
42
|
+
} catch {
|
|
43
|
+
return void 0;
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
const extractAccountIdFromClaims = (claims) => claims.chatgpt_account_id ?? claims["https://api.openai.com/auth"]?.chatgpt_account_id ?? claims.organizations?.[0]?.id;
|
|
47
|
+
const extractAccountId = (tokens) => {
|
|
48
|
+
if (tokens.id_token !== void 0 && tokens.id_token.length > 0) {
|
|
49
|
+
const claims2 = parseJwtClaims(tokens.id_token);
|
|
50
|
+
const accountId = claims2 === void 0 ? void 0 : extractAccountIdFromClaims(claims2);
|
|
51
|
+
if (accountId !== void 0 && accountId.length > 0) {
|
|
52
|
+
return accountId;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
const claims = parseJwtClaims(tokens.access_token);
|
|
56
|
+
return claims === void 0 ? void 0 : extractAccountIdFromClaims(claims);
|
|
57
|
+
};
|
|
58
|
+
const toCodexAuthTokens = (tokens, accountId = extractAccountId(tokens)) => ({
|
|
59
|
+
access: tokens.access_token,
|
|
60
|
+
expires: Date.now() + (tokens.expires_in ?? 3600) * 1e3,
|
|
61
|
+
refresh: tokens.refresh_token,
|
|
62
|
+
...accountId !== void 0 && accountId.length > 0 && { accountId }
|
|
63
|
+
});
|
|
64
|
+
const refreshCodexAccessToken = async (refreshToken) => {
|
|
65
|
+
const tokens = await jsonFetch(
|
|
66
|
+
CODEX_TOKEN_URL,
|
|
67
|
+
{
|
|
68
|
+
body: new URLSearchParams({
|
|
69
|
+
client_id: CODEX_CLIENT_ID,
|
|
70
|
+
grant_type: "refresh_token",
|
|
71
|
+
refresh_token: refreshToken
|
|
72
|
+
}).toString(),
|
|
73
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
74
|
+
method: "POST"
|
|
75
|
+
},
|
|
76
|
+
"Codex token refresh failed"
|
|
77
|
+
);
|
|
78
|
+
return toCodexAuthTokens(tokens);
|
|
79
|
+
};
|
|
80
|
+
const authorizeCodexHeadless = async (options = {}) => {
|
|
81
|
+
const deviceData = await jsonFetch(
|
|
82
|
+
CODEX_DEVICE_AUTH_URL,
|
|
83
|
+
{
|
|
84
|
+
body: JSON.stringify({ client_id: CODEX_CLIENT_ID }),
|
|
85
|
+
headers: {
|
|
86
|
+
"Content-Type": "application/json",
|
|
87
|
+
"User-Agent": CODEX_DEFAULT_USER_AGENT
|
|
88
|
+
},
|
|
89
|
+
method: "POST"
|
|
90
|
+
},
|
|
91
|
+
"Failed to initiate Codex device authorization"
|
|
92
|
+
);
|
|
93
|
+
const interval = Math.max(Number.parseInt(String(deviceData.interval ?? 5)), 1) * 1e3;
|
|
94
|
+
await options.onUserCode?.({
|
|
95
|
+
instructions: `Open ${CODEX_DEVICE_URL} and enter code: ${deviceData.user_code}`,
|
|
96
|
+
interval,
|
|
97
|
+
url: CODEX_DEVICE_URL,
|
|
98
|
+
userCode: deviceData.user_code
|
|
99
|
+
});
|
|
100
|
+
while (true) {
|
|
101
|
+
const response = await fetch(CODEX_DEVICE_TOKEN_URL, {
|
|
102
|
+
body: JSON.stringify({
|
|
103
|
+
device_auth_id: deviceData.device_auth_id,
|
|
104
|
+
user_code: deviceData.user_code
|
|
105
|
+
}),
|
|
106
|
+
headers: {
|
|
107
|
+
"Content-Type": "application/json",
|
|
108
|
+
"User-Agent": CODEX_DEFAULT_USER_AGENT
|
|
109
|
+
},
|
|
110
|
+
method: "POST"
|
|
111
|
+
});
|
|
112
|
+
if (response.ok) {
|
|
113
|
+
const deviceToken = await response.json();
|
|
114
|
+
const tokens = await jsonFetch(
|
|
115
|
+
CODEX_TOKEN_URL,
|
|
116
|
+
{
|
|
117
|
+
body: new URLSearchParams({
|
|
118
|
+
client_id: CODEX_CLIENT_ID,
|
|
119
|
+
code: deviceToken.authorization_code,
|
|
120
|
+
code_verifier: deviceToken.code_verifier,
|
|
121
|
+
grant_type: "authorization_code",
|
|
122
|
+
redirect_uri: CODEX_DEVICE_REDIRECT_URL
|
|
123
|
+
}).toString(),
|
|
124
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
125
|
+
method: "POST"
|
|
126
|
+
},
|
|
127
|
+
"Codex token exchange failed"
|
|
128
|
+
);
|
|
129
|
+
return toCodexAuthTokens(tokens);
|
|
130
|
+
}
|
|
131
|
+
if (response.status !== 403 && response.status !== 404) {
|
|
132
|
+
throw new Error(await formatResponseError("Codex device authorization failed", response));
|
|
133
|
+
}
|
|
134
|
+
await sleep(interval + CODEX_OAUTH_POLLING_SAFETY_MARGIN_MS);
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
const createCodex = async (options) => {
|
|
139
|
+
let currentAuth = typeof options.auth === "function" ? await options.auth() : options.auth;
|
|
140
|
+
const resolveAuth = async () => {
|
|
141
|
+
if (currentAuth.expires - CODEX_TOKEN_REFRESH_MARGIN_MS <= Date.now()) {
|
|
142
|
+
const refreshed = await refreshCodexAccessToken(currentAuth.refresh);
|
|
143
|
+
currentAuth = {
|
|
144
|
+
...refreshed,
|
|
145
|
+
accountId: refreshed.accountId ?? currentAuth.accountId
|
|
146
|
+
};
|
|
147
|
+
await options.onAuthUpdate?.(currentAuth);
|
|
148
|
+
}
|
|
149
|
+
return currentAuth;
|
|
150
|
+
};
|
|
151
|
+
return async (model) => {
|
|
152
|
+
const auth = await resolveAuth();
|
|
153
|
+
return {
|
|
154
|
+
apiKey: CODEX_DUMMY_API_KEY,
|
|
155
|
+
baseURL: CODEX_BASE_URL,
|
|
156
|
+
headers: {
|
|
157
|
+
"Authorization": `Bearer ${auth.access}`,
|
|
158
|
+
...auth.accountId !== void 0 && auth.accountId.length > 0 && { "ChatGPT-Account-Id": auth.accountId },
|
|
159
|
+
"originator": options.originator ?? CODEX_DEFAULT_ORIGINATOR,
|
|
160
|
+
"User-Agent": options.userAgent ?? CODEX_DEFAULT_USER_AGENT,
|
|
161
|
+
...options.sessionId !== void 0 && options.sessionId.length > 0 && { session_id: options.sessionId }
|
|
162
|
+
},
|
|
163
|
+
model
|
|
164
|
+
};
|
|
165
|
+
};
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
export { authorizeCodexHeadless, createCodex };
|
package/package.json
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "xsai-codex",
|
|
3
|
+
"type": "module",
|
|
4
|
+
"version": "0.0.1",
|
|
5
|
+
"description": "OpenAI Codex provider for xsAI.",
|
|
6
|
+
"author": "Moeru AI",
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"homepage": "https://github.com/moeru-ai/xsai-codex",
|
|
9
|
+
"repository": "github:moeru-ai/xsai-codex",
|
|
10
|
+
"bugs": "https://github.com/moeru-ai/xsai-codex/issues",
|
|
11
|
+
"keywords": [
|
|
12
|
+
"xsai",
|
|
13
|
+
"openai",
|
|
14
|
+
"codex"
|
|
15
|
+
],
|
|
16
|
+
"sideEffects": false,
|
|
17
|
+
"exports": {
|
|
18
|
+
".": {
|
|
19
|
+
"types": "./dist/index.d.ts",
|
|
20
|
+
"default": "./dist/index.js"
|
|
21
|
+
},
|
|
22
|
+
"./package.json": "./package.json"
|
|
23
|
+
},
|
|
24
|
+
"files": [
|
|
25
|
+
"dist"
|
|
26
|
+
],
|
|
27
|
+
"peerDependencies": {
|
|
28
|
+
"@xsai-ext/responses": "0.5.0-beta.3"
|
|
29
|
+
},
|
|
30
|
+
"devDependencies": {
|
|
31
|
+
"@antfu/eslint-config": "^8.2.0",
|
|
32
|
+
"@clack/prompts": "^1.3.0",
|
|
33
|
+
"@moeru/eslint-config": "0.1.0-beta.18",
|
|
34
|
+
"@moeru/tsconfig": "0.1.0-beta.18",
|
|
35
|
+
"@types/node": "^25.6.2",
|
|
36
|
+
"@xsai-ext/responses": "0.5.0-beta.3",
|
|
37
|
+
"bumpp": "^11.1.0",
|
|
38
|
+
"eslint": "^10.2.0",
|
|
39
|
+
"pkgroll": "^2.27.0",
|
|
40
|
+
"tsx": "^4.21.0"
|
|
41
|
+
},
|
|
42
|
+
"scripts": {
|
|
43
|
+
"build": "pkgroll",
|
|
44
|
+
"bump": "bumpp --no-push",
|
|
45
|
+
"dev": "tsx scripts/example.ts",
|
|
46
|
+
"lint": "eslint ."
|
|
47
|
+
},
|
|
48
|
+
"main": "./dist/index.js",
|
|
49
|
+
"types": "./dist/index.d.ts"
|
|
50
|
+
}
|