@coda-console/codex 2.4.0 → 2.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -0
- package/agent/accounts.mjs +81 -28
- package/agent/entry.mjs +8 -3
- package/agent/errors.mjs +2 -27
- package/lib/config.mjs +24 -0
- package/lib/errors.mjs +97 -0
- package/lib/hub.mjs +151 -0
- package/lib/ipc.mjs +125 -0
- package/lib/pool.mjs +125 -0
- package/lib/quota-summary.mjs +39 -0
- package/lib/remote.mjs +82 -0
- package/lib/wire.mjs +16 -0
- package/main.mjs +60 -0
- package/package.json +309 -2
- package/scripts/act.mjs +14 -5
- package/scripts/app-server.mjs +5 -1
- package/scripts/cli.mjs +5 -3
- package/scripts/login.mjs +5 -1
- package/scripts/manager.mjs +126 -47
- package/scripts/quota.mjs +9 -41
- package/scripts/resource.mjs +19 -5
- package/scripts/sign-in.mjs +5 -1
package/scripts/manager.mjs
CHANGED
|
@@ -6,18 +6,28 @@ import { chmodSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writ
|
|
|
6
6
|
import { homedir } from 'node:os';
|
|
7
7
|
import { join } from 'node:path';
|
|
8
8
|
import { withAccountHome } from './codex.mjs';
|
|
9
|
-
import {
|
|
9
|
+
import { multipleAccounts } from '../lib/config.mjs';
|
|
10
|
+
import { SignInAgain, TransientError, faultOf, needsSignIn } from '../lib/errors.mjs';
|
|
10
11
|
|
|
11
12
|
const ID = /^[a-f0-9]{64}$/;
|
|
12
13
|
// Whether「多账号」is on: the plugin's settings as Coda hands them to its processes.
|
|
13
|
-
export
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
14
|
+
export { multipleAccounts };
|
|
15
|
+
const sha = text => createHash('sha256').update(text).digest('hex');
|
|
16
|
+
// An account's identity as it was first made: the workspace's account ID hashed. A second user of the same workspace has one
|
|
17
|
+
// of their own (`userIdentity`), so that signing in never replaces another user's login.
|
|
18
|
+
export const identity = account => sha(account);
|
|
19
|
+
const userIdentity = (userKey, workspace) => sha(`${userKey}\n${workspace}`);
|
|
20
|
+
const normalEmail = value => typeof value === 'string' && value.trim() ? value.trim().toLowerCase() : undefined;
|
|
21
|
+
// A version of an access token that says nothing of it: who asked for a renewal because of a rejected token names this one.
|
|
22
|
+
export const tokenGeneration = accessToken => sha(accessToken).slice(0, 16);
|
|
17
23
|
export const paths = (env = process.env) => {
|
|
18
24
|
if (!env.CODA_PLUGIN_STATE) throw new Error('Coda 没有提供插件状态目录');
|
|
19
25
|
return { state: join(env.CODA_PLUGIN_STATE, 'accounts'), native: env.CODEX_HOME || join(homedir(), '.codex'), env };
|
|
20
26
|
};
|
|
27
|
+
// The store (accounts.json, selection.json) is there but cannot be read: not the same as no account chosen.
|
|
28
|
+
export class StoreError extends Error { code = 'store_unreadable'; }
|
|
29
|
+
// No account is chosen, or the chosen one is not signed in here: the store itself is fine.
|
|
30
|
+
export class NoSelection extends Error { code = 'no_selection'; }
|
|
21
31
|
const unavailable = '账号登录已失效,请在「资源」重新登录该账号';
|
|
22
32
|
const missing = '此账号尚未在插件中登录,请在「资源」重新登录';
|
|
23
33
|
function privateDir(dir) {
|
|
@@ -54,10 +64,13 @@ async function locked(key, at, work) {
|
|
|
54
64
|
function stored(at) {
|
|
55
65
|
try {
|
|
56
66
|
const value = readJSON(join(at.state, 'accounts.json'));
|
|
57
|
-
if (value.version !== 1 || !Array.isArray(value.accounts) || value.accounts.some(a => !ID.test(a?.identity) || typeof a.alias !== 'string'
|
|
67
|
+
if (value.version !== 1 || !Array.isArray(value.accounts) || value.accounts.some(a => !ID.test(a?.identity) || typeof a.alias !== 'string'
|
|
68
|
+
|| ['chatgptAccountId', 'email', 'userId', 'instanceId'].some(key => a[key] !== undefined && typeof a[key] !== 'string'))) throw Error();
|
|
58
69
|
return value.accounts;
|
|
59
|
-
} catch (error) { if (error.code === 'ENOENT') return null; throw new
|
|
70
|
+
} catch (error) { if (error.code === 'ENOENT') return null; throw new StoreError('读不了插件保存的账号列表'); }
|
|
60
71
|
}
|
|
72
|
+
// The accounts already stored here, read as they are: no import of this machine's own Codex login and nothing written (none yet: none).
|
|
73
|
+
export const peekAccounts = at => stored(at) ?? [];
|
|
61
74
|
// Import the existing Codex login once, as an ordinary managed account. A store, even an empty one, records that this
|
|
62
75
|
// has happened: removing the imported account must not make it reappear on the next reading.
|
|
63
76
|
export async function list(at = paths(), { recoverImport = false } = {}) {
|
|
@@ -80,7 +93,8 @@ export async function list(at = paths(), { recoverImport = false } = {}) {
|
|
|
80
93
|
try { email = JSON.parse(Buffer.from(login.auth.tokens.id_token.split('.')[1], 'base64url').toString('utf8')).email; } catch {}
|
|
81
94
|
const home = join(at.state, 'accounts', id);
|
|
82
95
|
privateDir(home); writeJSON(join(home, 'auth.json'), login.auth);
|
|
83
|
-
accounts.push({ identity: id, alias: typeof email === 'string' && email ? email : `账号 ${id.slice(0, 8)}`, plan: login.tokens.chatgptPlanType ?? null
|
|
96
|
+
accounts.push({ identity: id, alias: typeof email === 'string' && email ? email : `账号 ${id.slice(0, 8)}`, plan: login.tokens.chatgptPlanType ?? null,
|
|
97
|
+
...metadata({ chatgptAccountId: login.tokens.chatgptAccountId, email: login.email, userId: login.userId }), instanceId: randomUUID() });
|
|
84
98
|
}
|
|
85
99
|
const chosen = selection(at);
|
|
86
100
|
// The old plugin's "native" choice becomes the imported identity, not a second kind of account.
|
|
@@ -91,18 +105,21 @@ export async function list(at = paths(), { recoverImport = false } = {}) {
|
|
|
91
105
|
}
|
|
92
106
|
export function selection(at = paths()) {
|
|
93
107
|
try {
|
|
94
|
-
const
|
|
95
|
-
if (
|
|
108
|
+
const value = readJSON(join(at.state, 'selection.json'));
|
|
109
|
+
if (!value || typeof value !== 'object' || Array.isArray(value) || !Object.hasOwn(value, 'account')) throw Error();
|
|
110
|
+
const selected = value.account;
|
|
111
|
+
if (selected !== null && selected !== 'native' && !(typeof selected === 'string' && ID.test(selected))) throw Error();
|
|
96
112
|
return selected;
|
|
97
|
-
} catch (error) { if (error.code === 'ENOENT') return null; throw new
|
|
113
|
+
} catch (error) { if (error.code === 'ENOENT') return null; throw new StoreError('读不了所选的账号'); }
|
|
98
114
|
}
|
|
99
|
-
// The account sessions are to use, as the account bridge asks for it: an error until one is chosen and signed in here.
|
|
115
|
+
// The account sessions are to use, as the account bridge asks for it: an error until one is chosen and signed in here. Its
|
|
116
|
+
// `instanceId`, where the entry has one, tells it from an account of the same identity signed in after it was removed.
|
|
100
117
|
export async function chosen(at = paths()) {
|
|
101
118
|
const accounts = await list(at), account = selection(at);
|
|
102
|
-
if (account === null) throw new
|
|
119
|
+
if (account === null) throw new NoSelection('请在「资源」添加或选择一个 Codex 账号');
|
|
103
120
|
const found = accounts.find(a => a.identity === account);
|
|
104
|
-
if (!found) throw new
|
|
105
|
-
return { id: account, name: found.alias.slice(0, 80) };
|
|
121
|
+
if (!found) throw new NoSelection('所选账号尚未在插件中登录,请在「资源」重新登录该账号');
|
|
122
|
+
return { id: account, name: found.alias.slice(0, 80), ...(found.instanceId ? { instanceId: found.instanceId } : {}) };
|
|
106
123
|
}
|
|
107
124
|
export async function choose(account, at = paths()) {
|
|
108
125
|
await list(at);
|
|
@@ -118,67 +135,129 @@ function homeFor(account, at) {
|
|
|
118
135
|
catch { throw new SignInAgain(missing); }
|
|
119
136
|
return home;
|
|
120
137
|
}
|
|
138
|
+
// The optional facts an entry of the store keeps of who signed in, from a reading of their login.
|
|
139
|
+
const metadata = ({ chatgptAccountId, email, userId }) => ({ chatgptAccountId, ...(email ? { email } : {}), ...(userId ? { userId } : {}) });
|
|
140
|
+
// Whether a login (`actual`: chatgptAccountId, and email and userId where known) is the one `expected` describes: an account entry,
|
|
141
|
+
// or, as before, its identity alone. The workspace must be the same, and so must the user wherever both sides say who it is.
|
|
142
|
+
function matches(expected, actual) {
|
|
143
|
+
if (typeof expected === 'string') expected = { identity: expected };
|
|
144
|
+
if (expected.chatgptAccountId ? expected.chatgptAccountId !== actual.chatgptAccountId : identity(actual.chatgptAccountId) !== expected.identity) return false;
|
|
145
|
+
return !(expected.userId && actual.userId && expected.userId !== actual.userId) && !(expected.email && actual.email && expected.email !== actual.email);
|
|
146
|
+
}
|
|
121
147
|
export function readAuth(home, expected) {
|
|
122
148
|
try {
|
|
123
149
|
const auth = readJSON(join(home, 'auth.json')), accessToken = auth.tokens.access_token;
|
|
124
150
|
const claims = JSON.parse(Buffer.from(accessToken.split('.')[1], 'base64url').toString('utf8'));
|
|
125
151
|
const info = claims['https://api.openai.com/auth'], chatgptAccountId = info.chatgpt_account_id;
|
|
152
|
+
let email; try { email = normalEmail(JSON.parse(Buffer.from(auth.tokens.id_token.split('.')[1], 'base64url').toString('utf8')).email); } catch {}
|
|
153
|
+
const userId = typeof info.chatgpt_user_id === 'string' && info.chatgpt_user_id ? info.chatgpt_user_id : undefined;
|
|
126
154
|
if (typeof chatgptAccountId !== 'string' || !chatgptAccountId || !Number.isFinite(claims.exp)
|
|
127
|
-
|| (expected &&
|
|
155
|
+
|| (expected && !matches(expected, { chatgptAccountId, email, userId }))
|
|
128
156
|
|| (auth.tokens.account_id && auth.tokens.account_id !== chatgptAccountId)) throw Error();
|
|
129
|
-
return { auth, expires: claims.exp * 1000, tokens: { accessToken, chatgptAccountId,
|
|
157
|
+
return { auth, expires: claims.exp * 1000, email, userId, tokens: { accessToken, chatgptAccountId,
|
|
130
158
|
...(typeof info.chatgpt_plan_type === 'string' ? { chatgptPlanType: info.chatgpt_plan_type } : {}) } };
|
|
131
159
|
} catch { throw new SignInAgain(unavailable); }
|
|
132
160
|
}
|
|
161
|
+
// Whether Codex's account is the expected one: the workspace it routes to and, where it says, the email.
|
|
133
162
|
async function checked(server, expected, refreshToken = false) {
|
|
134
163
|
const result = await server.request('account/read', { refreshToken });
|
|
135
|
-
if (result.account?.type !== 'chatgpt' ||
|
|
164
|
+
if (result.account?.type !== 'chatgpt' || !matches(expected, { chatgptAccountId: result.workspaceRouting?.chatgptAccountId ?? '', email: normalEmail(result.account.email) }))
|
|
165
|
+
throw new SignInAgain('Codex 登录后的账号与所选的不符');
|
|
136
166
|
return result.account;
|
|
137
167
|
}
|
|
168
|
+
async function entryOf(account, at) {
|
|
169
|
+
const entry = (await list(at)).find(a => a.identity === account);
|
|
170
|
+
if (!entry) throw new SignInAgain(missing);
|
|
171
|
+
return entry;
|
|
172
|
+
}
|
|
138
173
|
// Quota/reset requests use this account's managed login, so Codex itself handles a 401 and persists renewed tokens.
|
|
139
174
|
export async function withManagedAccount(account, work, at = paths(), options) {
|
|
140
|
-
|
|
175
|
+
const entry = await entryOf(account, at);
|
|
141
176
|
return locked(account, at, async () => {
|
|
142
177
|
const home = homeFor(account, at);
|
|
143
|
-
readAuth(home,
|
|
144
|
-
return withAccountHome(home, async server => { await checked(server,
|
|
178
|
+
readAuth(home, entry);
|
|
179
|
+
return withAccountHome(home, async server => { await checked(server, entry); return work(server); }, { env: at.env, ...options });
|
|
145
180
|
});
|
|
146
181
|
}
|
|
147
|
-
//
|
|
148
|
-
//
|
|
149
|
-
|
|
150
|
-
|
|
182
|
+
// The failure of a renewal, as what it is: only a login Codex says is no good is `SignInAgain`; a limit, an exhausted quota, a
|
|
183
|
+
// timeout, the network or anything not recognized is said as it is, and is not the login.
|
|
184
|
+
const renewalFailure = error => needsSignIn(error) ? new SignInAgain(unavailable) : faultOf(error) ?? new TransientError();
|
|
185
|
+
// What the account bridge hands to Codex, and nothing else.
|
|
186
|
+
export const rpcTokens = ({ accessToken, chatgptAccountId, chatgptPlanType }) => ({ accessToken, chatgptAccountId, ...(chatgptPlanType ? { chatgptPlanType } : {}) });
|
|
187
|
+
// Renew only when needed or explicitly requested after a rejected access token. Recheck under the lock so concurrent sessions do not
|
|
188
|
+
// refresh the same rotating refresh token at once: a requester that names the generation it was rejected on (`rejectedGeneration`)
|
|
189
|
+
// is given the newer one when another has already renewed, and does not renew again. The full auth document never leaves this module.
|
|
190
|
+
// Returns the tokens with their generation and expiry (ms), which say nothing of the secrets. auth.json is only ever replaced whole
|
|
191
|
+
// (a rename), so tokens that need no renewal are read without the lock: a slow quota reading holding it does not hold them up.
|
|
192
|
+
export async function leaseTokens(account, at = paths(), { refresh = false, rejectedGeneration = null, ...options } = {}) {
|
|
193
|
+
const entry = await entryOf(account, at);
|
|
194
|
+
const stale = current => current.expires <= Date.now() + 60_000 || (refresh && (!rejectedGeneration || rejectedGeneration === tokenGeneration(current.tokens.accessToken)));
|
|
195
|
+
const leaseOf = current => ({ tokens: rpcTokens(current.tokens), generation: tokenGeneration(current.tokens.accessToken), expiresAt: current.expires });
|
|
196
|
+
try { const current = readAuth(homeFor(account, at), entry); if (!stale(current)) return leaseOf(current); } catch {}
|
|
151
197
|
return locked(account, at, async () => {
|
|
152
|
-
const home = homeFor(account, at)
|
|
153
|
-
let current = readAuth(home,
|
|
154
|
-
if (
|
|
198
|
+
const home = homeFor(account, at);
|
|
199
|
+
let current = readAuth(home, entry);
|
|
200
|
+
if (stale(current)) {
|
|
155
201
|
try {
|
|
156
|
-
await withAccountHome(home, server => checked(server,
|
|
157
|
-
current = readAuth(home,
|
|
158
|
-
} catch { throw
|
|
202
|
+
await withAccountHome(home, server => checked(server, { ...entry, chatgptAccountId: current.tokens.chatgptAccountId }, true), { env: at.env, ...options });
|
|
203
|
+
current = readAuth(home, entry);
|
|
204
|
+
} catch (error) { throw renewalFailure(error); }
|
|
159
205
|
}
|
|
160
206
|
if (current.expires <= Date.now() + 30_000) throw new SignInAgain(unavailable);
|
|
161
|
-
return current
|
|
207
|
+
return leaseOf(current);
|
|
162
208
|
});
|
|
163
209
|
}
|
|
164
|
-
|
|
165
|
-
//
|
|
210
|
+
export const tokens = async (account, at, options) => (await leaseTokens(account, at, options)).tokens;
|
|
211
|
+
// Who an entry is, as far as it says: its user ID and email, from the entry, its alias when that is an email, and its own login.
|
|
212
|
+
function knownUser(entry, at) {
|
|
213
|
+
let { userId, email } = entry;
|
|
214
|
+
email ??= entry.alias.includes('@') ? normalEmail(entry.alias) : undefined;
|
|
215
|
+
if (!userId || !email) {
|
|
216
|
+
try { const login = readAuth(join(at.state, 'accounts', entry.identity)); userId ??= login.userId; email ??= login.email; } catch {}
|
|
217
|
+
}
|
|
218
|
+
return { userId, email };
|
|
219
|
+
}
|
|
220
|
+
// The entry of the same user's earlier login in this workspace, or where there is none, the identity to give this one: the
|
|
221
|
+
// workspace's own for its first user, a user's own for the others, so that no one's login replaces another's. The same user is
|
|
222
|
+
// told by the user ID, else by the email (where the user IDs do not differ); users are different only when both sides say who
|
|
223
|
+
// they are and it is not the same. Where that cannot be told, nothing is written.
|
|
224
|
+
function locate(accounts, found, at) {
|
|
225
|
+
const sameWorkspace = accounts.filter(a => a.chatgptAccountId ? a.chatgptAccountId === found.chatgptAccountId : a.identity === identity(found.chatgptAccountId));
|
|
226
|
+
if (!sameWorkspace.length) return { id: identity(found.chatgptAccountId) };
|
|
227
|
+
const people = sameWorkspace.map(entry => ({ entry, ...knownUser(entry, at) }));
|
|
228
|
+
const byUser = found.userId && people.find(p => p.userId === found.userId);
|
|
229
|
+
const byEmail = byUser || !found.email ? [] : people.filter(p => p.email === found.email && !(p.userId && found.userId));
|
|
230
|
+
if (byEmail.length > 1) throw new Error('这个工作区里有多个账号使用同一个邮箱,无法确定是哪一个,请先在「资源」移除多余的账号后再登录');
|
|
231
|
+
const same = byUser || byEmail[0];
|
|
232
|
+
if (same) return { id: same.entry.identity, previous: same.entry };
|
|
233
|
+
if (people.some(p => !(p.userId && found.userId) && !(p.email && found.email))) throw new Error('这个工作区里已有的账号无法与这次登录的用户区分,请先在「资源」移除该账号后再登录');
|
|
234
|
+
return { id: userIdentity(found.userId ?? found.email, found.chatgptAccountId) };
|
|
235
|
+
}
|
|
236
|
+
// Commit a completed device login. Logging in again as the same user replaces their credentials; other accounts (also of the same
|
|
237
|
+
// workspace) and their selection stay intact. Only the first account is selected automatically, unless a choice was already saved.
|
|
166
238
|
export async function saveLogin(home, at = paths(), { isCancelled = () => false, ...options } = {}) {
|
|
167
239
|
await list(at);
|
|
168
|
-
const initial = readAuth(home),
|
|
240
|
+
const initial = readAuth(home), seen = { chatgptAccountId: initial.tokens.chatgptAccountId, email: initial.email, userId: initial.userId };
|
|
169
241
|
if (initial.expires <= Date.now() + 30_000 || !initial.auth.tokens.refresh_token) throw new SignInAgain(unavailable);
|
|
170
|
-
const account = await withAccountHome(home, server => checked(server,
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
const
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
242
|
+
const account = await withAccountHome(home, server => checked(server, seen), { env: at.env, ...options });
|
|
243
|
+
// The email Codex says is who signed in, when the token does not.
|
|
244
|
+
const found = { ...seen, email: seen.email ?? normalEmail(account.email) };
|
|
245
|
+
return locked('store', at, async () => {
|
|
246
|
+
const accounts = await list(at), { id, previous } = locate(accounts, found, at);
|
|
247
|
+
return locked(id, at, async () => {
|
|
248
|
+
if (isCancelled()) throw new Error('登录已取消');
|
|
249
|
+
const email = found.email ?? previous?.email, userId = found.userId ?? previous?.userId;
|
|
250
|
+
// A new entry is a new instance, even of an identity removed before; the same user's entry keeps its own.
|
|
251
|
+
const record = { identity: id, alias: account.email || previous?.alias || found.email || `账号 ${id.slice(0, 8)}`, plan: account.planType ?? null,
|
|
252
|
+
...metadata({ chatgptAccountId: found.chatgptAccountId, email, userId }), instanceId: previous?.instanceId ?? randomUUID() };
|
|
253
|
+
const target = join(at.state, 'accounts', id);
|
|
254
|
+
privateDir(target);
|
|
255
|
+
writeJSON(join(target, 'auth.json'), readAuth(home, found).auth);
|
|
256
|
+
writeJSON(join(at.state, 'accounts.json'), { version: 1, accounts: previous ? accounts.map(a => a.identity === id ? record : a) : [...accounts, record] });
|
|
257
|
+
if (!accounts.length && selection(at) === null) writeJSON(join(at.state, 'selection.json'), { account: id });
|
|
258
|
+
return record;
|
|
259
|
+
});
|
|
260
|
+
});
|
|
182
261
|
}
|
|
183
262
|
export async function remove(account, at = paths()) {
|
|
184
263
|
if (!ID.test(account)) throw new Error('没有指明要移除的账号');
|
package/scripts/quota.mjs
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
|
+
import { SignInAgain, needsSignIn } from '../lib/errors.mjs';
|
|
3
|
+
import { credits, line, unixTime, windows } from '../lib/quota-summary.mjs';
|
|
4
|
+
|
|
5
|
+
export { SignInAgain, needsSignIn, windows, credits };
|
|
2
6
|
|
|
3
7
|
// What the「Codex」resource type shows of a login (docs/plugins.md「内置插件:Codex」), from what Codex's app-server says of
|
|
4
8
|
// it: `account/read` and `account/rateLimits/read`; with「多账号」on, of each managed account (manager.mjs). Kept apart from the
|
|
5
9
|
// commands so the tests can hand it answers.
|
|
6
10
|
|
|
7
11
|
const VALUES = 8, ACCOUNTS = 40, BYTES = 60 * 1024;
|
|
8
|
-
const line = (value, max = 80) => typeof value === 'string' ? [...value.replace(/\s+/g, ' ').trim()].slice(0, max).join('') : '';
|
|
9
12
|
// The account a resource is, compared across machines by Coda's group view (its `identity`): who signed in and in which
|
|
10
13
|
// ChatGPT workspace, as the quota is one person's in one workspace (one email may sign in to several, and a workspace has
|
|
11
14
|
// many members). A hash of the email and of the workspace's account ID hashed as codex-account keeps it; none where Codex
|
|
@@ -15,38 +18,10 @@ const identity = (account, workspace) => {
|
|
|
15
18
|
const email = line(account.email, 320).toLowerCase();
|
|
16
19
|
return email && typeof workspace === 'string' && workspace ? { identity: `codex:${hash(`${email}\n${hash(workspace)}`)}` } : {};
|
|
17
20
|
};
|
|
18
|
-
const unixTime = value => typeof value === 'number' && Number.isFinite(new Date(value * 1000).getTime()) ? new Date(value * 1000).toISOString() : null;
|
|
19
21
|
// A credit's expiry in a figure's text: a time mark, which each client writes in its own time zone (Coda's
|
|
20
22
|
// docs/agent-protocol.md「文字里的时刻」).
|
|
21
23
|
const mark = seconds => `<t:${unixTime(seconds)}>`;
|
|
22
24
|
|
|
23
|
-
// A value per window of each limit, of what is left and when it resets; unknown is said as unknown, never a zero. A limit's
|
|
24
|
-
// name is said only when there are several.
|
|
25
|
-
export function windows(result) {
|
|
26
|
-
const byID = result?.rateLimitsByLimitId ? Object.values(result.rateLimitsByLimitId) : [];
|
|
27
|
-
const limits = (byID.length ? byID : [result?.rateLimits]).filter(Boolean);
|
|
28
|
-
return limits.flatMap(limit => ['primary', 'secondary'].flatMap(key => {
|
|
29
|
-
const w = limit[key]; if (!w) return [];
|
|
30
|
-
const minutes = w.windowDurationMins;
|
|
31
|
-
const duration = minutes === 300 ? '5 小时' : minutes === 10080 ? '7 天' : Number.isSafeInteger(minutes) && minutes > 0 ? `${minutes} 分钟` : '额度';
|
|
32
|
-
const used = typeof w.usedPercent === 'number' && w.usedPercent >= 0 && w.usedPercent <= 100 ? w.usedPercent : null;
|
|
33
|
-
const left = used === null ? null : Math.round(100 - used), resets = unixTime(w.resetsAt);
|
|
34
|
-
return [{ label: `${limits.length > 1 ? `${line(limit.limitName ?? limit.limitId, 40) || '额度'} · ` : ''}${duration}`,
|
|
35
|
-
...(left === null ? { value: '—' } : { value: `剩余 ${left}%`, fraction: left / 100 }),
|
|
36
|
-
...(resets ? { time: resets } : {}) }];
|
|
37
|
-
}));
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
// The full resets left: the count is Codex's word (its list of them may be capped or missing). Those listed are the
|
|
41
|
-
// available ones, earliest to expire first; one without an expiry never expires.
|
|
42
|
-
export function credits(result) {
|
|
43
|
-
const summary = result?.rateLimitResetCredits;
|
|
44
|
-
if (!Number.isSafeInteger(summary?.availableCount)) return null;
|
|
45
|
-
const listed = (summary.credits ?? []).filter(c => c?.status === 'available' && c.resetType === 'codexRateLimits' && typeof c.id === 'string' && c.id)
|
|
46
|
-
.sort((a, b) => (a.expiresAt ?? Infinity) - (b.expiresAt ?? Infinity));
|
|
47
|
-
return { count: summary.availableCount, listed };
|
|
48
|
-
}
|
|
49
|
-
|
|
50
25
|
// The login as a resource: its windows, then its full resets left, timed by the one to expire first; its button for a full
|
|
51
26
|
// reset (that one, named in its question).
|
|
52
27
|
export function resource(account, result, workspace) {
|
|
@@ -62,14 +37,6 @@ export function resource(account, result, workspace) {
|
|
|
62
37
|
return { name, ...identity(account, workspace), values: values.slice(0, VALUES), buttons };
|
|
63
38
|
}
|
|
64
39
|
|
|
65
|
-
// A failure that only signing in again cures, of a managed account: its login missing, expired, unreadable or another's (thrown
|
|
66
|
-
// by the manager as this).
|
|
67
|
-
export class SignInAgain extends Error {}
|
|
68
|
-
// Whether what Codex said is that its login is gone, expired or revoked, or its file unreadable, or a managed account's login is
|
|
69
|
-
// no good: what signing in again cures. Any other failure of a reading (the network, a timeout, a server's error, Codex itself,
|
|
70
|
-
// a store that cannot be read) is not, and is left to fail the command.
|
|
71
|
-
export const needsSignIn = error => error instanceof SignInAgain || /authentication required|not (logged|signed) in|unauthori[sz]ed|\b401\b|token[^.]*\b(expired|invalid|revoked)\b|auth\.json|failed to (load|read) auth/i.test(error?.message ?? '');
|
|
72
|
-
|
|
73
40
|
// The resources: none without a login (the type is then offered under「添加资源」), the login for one. A login Codex says is no
|
|
74
41
|
// longer good is said on its row, which keeps「重新登录」 at hand; one not signed in with ChatGPT has no windows to read. A quota
|
|
75
42
|
// that cannot be read for any other reason throws.
|
|
@@ -115,10 +82,11 @@ export function managedResource(account, chosen, { result, error }) {
|
|
|
115
82
|
}
|
|
116
83
|
buttons.push({ label: '移除账号', action: 'remove', args: { account: account.identity },
|
|
117
84
|
confirm: `移除 ${line(name, 60)} 在插件中保存的登录?${chosen ? '\n移除后需要选择或添加账号才能继续会话。' : ''}` });
|
|
118
|
-
// Who it is and in which workspace, as this machine's own login says it (the
|
|
119
|
-
//
|
|
120
|
-
const email = account.alias.includes('@') ? account.alias.trim().toLowerCase()
|
|
121
|
-
|
|
85
|
+
// Who it is and in which workspace, as this machine's own login says it (the workspace's account ID hashed; an entry from before
|
|
86
|
+
// the account ID was kept has it as its identity): Coda's group view shows the same one once. None when its email is not known.
|
|
87
|
+
const email = (account.email || (account.alias.includes('@') ? account.alias : '')).trim().toLowerCase();
|
|
88
|
+
const workspace = account.chatgptAccountId ? hash(account.chatgptAccountId) : account.identity;
|
|
89
|
+
return { name, ...(email ? { identity: `codex:${hash(`${email}\n${workspace}`)}` } : {}),
|
|
122
90
|
values: values.slice(0, VALUES), ...(error ? { error: line(error) } : {}), buttons };
|
|
123
91
|
}
|
|
124
92
|
|
package/scripts/resource.mjs
CHANGED
|
@@ -1,25 +1,39 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// The `coda/resource@1` records of the「Codex」type, printed once: this machine's own login, and with「多账号」on (the setting
|
|
3
|
-
// `codex.multipleAccounts`) the managed accounts, a type of their own,
|
|
3
|
+
// `codex.multipleAccounts`) or as the space's hosting centre (`codex.accountHosting` = host) the managed accounts, a type of their own,
|
|
4
|
+
// while this machine's own login shows none. A consumer of the centre (remote) shows no account of its own, and starts no Codex.
|
|
5
|
+
// A centre reads the quotas through its account service, which keeps them and spares the accounts a reading each time; where that
|
|
6
|
+
// is not running, it reads them itself. Signing in
|
|
4
7
|
// stays offered either way (the CLI comes with the plugin). A login that is gone, expired or unreadable is a row saying so; so is,
|
|
5
8
|
// with several accounts, one whose quota cannot be read while another's was. Any other failure to read (Codex not answering, the
|
|
6
9
|
// network, a server's error, a damaged store, no account's quota had) fails the command (exit 1, the reason on the last line of
|
|
7
10
|
// its standard error), which keeps the records Coda has.
|
|
8
11
|
import { withAppServer } from './app-server.mjs';
|
|
9
|
-
import {
|
|
12
|
+
import { isHostMode, isRemoteMode, usesManagedStore } from '../lib/config.mjs';
|
|
13
|
+
import { ipcRequest, isDown } from '../lib/ipc.mjs';
|
|
14
|
+
import { list, selection, withManagedAccount } from './manager.mjs';
|
|
10
15
|
import { managedResources, managedUnreadable, needsSignIn, resources, unreadable } from './quota.mjs';
|
|
11
16
|
|
|
12
17
|
const fail = error => { console.error(String(error.message).replace(/\s+/g, ' ').trim()); process.exit(1); };
|
|
13
|
-
|
|
18
|
+
if (isRemoteMode()) {
|
|
19
|
+
console.log(JSON.stringify([{ key: 'login', spec: { type: 'login', title: 'Codex', resources: [],
|
|
20
|
+
signIn: { installed: true, installable: false, note: '当前机器已启用 Codex 空间集中托管,请在托管机管理或切换账号。' } } }]));
|
|
21
|
+
process.exit(0);
|
|
22
|
+
}
|
|
23
|
+
const multiple = usesManagedStore(), host = isHostMode();
|
|
14
24
|
const own = multiple ? { resources: [] } : await withAppServer(resources).catch(error => needsSignIn(error) ? unreadable(error) : fail(error));
|
|
15
25
|
const records = [{ key: 'login', spec: { type: 'login', title: 'Codex', ...own,
|
|
16
26
|
signIn: { installed: true, installable: false, note: '打开「多账号」后,登录会添加或更新多账号里的账号。' } } }];
|
|
17
27
|
if (multiple) {
|
|
18
|
-
const
|
|
28
|
+
const readHere = account => withManagedAccount(account.identity, server => server.request('account/rateLimits/read'));
|
|
29
|
+
const read = host ? async account => {
|
|
30
|
+
try { return await ipcRequest(process.env.CODA_PLUGIN_STATE, { op: 'quota', account: account.identity }); }
|
|
31
|
+
catch (error) { if (isDown(error)) return readHere(account); throw error; }
|
|
32
|
+
} : readHere;
|
|
19
33
|
let managed;
|
|
20
34
|
try { managed = await managedResources(await list(), selection(), read); }
|
|
21
35
|
catch (error) { managed = needsSignIn(error) ? managedUnreadable(error) : fail(error); }
|
|
22
36
|
records.push({ key: 'accounts', spec: { type: 'accounts', title: 'Codex', ...managed,
|
|
23
|
-
signIn: { installed: true, installable: false, note: '
|
|
37
|
+
signIn: { installed: true, installable: false, note: `登录其他账号即可添加;登录已有账号会更新其凭据。首个账号会自动选用,之后在账号那一行的「···」里切换。${host ? '本机托管的账号已向空间共享。' : ''}` } } });
|
|
24
38
|
}
|
|
25
39
|
console.log(JSON.stringify(records));
|
package/scripts/sign-in.mjs
CHANGED
|
@@ -1,10 +1,14 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// The「Codex」resource type's sign-in (the `sign-in` operation of `coda/resource@1`): `codex login --device-auth` of the plugin's
|
|
3
|
-
// own CLI (scripts/cli.mjs: with「多账号」on, it adds or updates a managed account instead), uncoloured.
|
|
3
|
+
// own CLI (scripts/cli.mjs: with「多账号」on, it adds or updates a managed account instead), uncoloured. Not as a consumer of the
|
|
4
|
+
// space's hosting centre (`codex.accountHosting` = remote), whose accounts are the centre's.
|
|
4
5
|
import { spawn } from 'node:child_process';
|
|
5
6
|
import { dirname, join } from 'node:path';
|
|
6
7
|
import { fileURLToPath } from 'node:url';
|
|
8
|
+
import { isRemoteMode, remoteRefusal } from '../lib/config.mjs';
|
|
7
9
|
import { deviceLogin } from './device-login.mjs';
|
|
8
10
|
|
|
11
|
+
if (isRemoteMode()) { console.error(remoteRefusal); process.exit(1); }
|
|
12
|
+
|
|
9
13
|
await deviceLogin(() => spawn(process.execPath, [join(dirname(fileURLToPath(import.meta.url)), 'cli.mjs'), 'login', '--device-auth'],
|
|
10
14
|
{ env: { ...process.env, NO_COLOR: '1' }, stdio: ['ignore', 'pipe', 'pipe'] }));
|