@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/lib/ipc.mjs
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
// The private socket of this machine's Codex account service (the hub in host mode, the consumer in remote mode): the agent's
|
|
2
|
+
// bridge and the plugin's scripts ask it for the chosen account and its tokens, so that nothing but this process reads the managed
|
|
3
|
+
// accounts or talks to the centre. One JSON object a line each way. The socket is in a directory of its own (0700) and is 0600;
|
|
4
|
+
// `agent-socket` in the state directory says where it is, as a whole file at once. Nothing is printed of what passes.
|
|
5
|
+
import { randomBytes } from 'node:crypto';
|
|
6
|
+
import { chmod, mkdtemp, readFile, rename, rm, writeFile } from 'node:fs/promises';
|
|
7
|
+
import { createConnection, createServer } from 'node:net';
|
|
8
|
+
import { tmpdir } from 'node:os';
|
|
9
|
+
import { join } from 'node:path';
|
|
10
|
+
import { MAX_LINE, asFault, restoreFault, said } from './wire.mjs';
|
|
11
|
+
|
|
12
|
+
export const ADDRESS = 'agent-socket';
|
|
13
|
+
const DOWN = '这台机器的 Codex 账号服务没有运行:请在 Codex 插件设置里选择「账号托管」的模式';
|
|
14
|
+
const CUT = '这台机器的 Codex 账号服务中途断开了,请求可能已经送达';
|
|
15
|
+
// A request that found no service to ask (its socket is not there or not listening): nothing was sent, so what asked may be done
|
|
16
|
+
// another way. Not one that was sent and then cut off, timed out or badly answered: that may have been done.
|
|
17
|
+
export const isDown = error => error?.code === 'service_down';
|
|
18
|
+
const bad = () => said('请求不对', 'invalid_input');
|
|
19
|
+
|
|
20
|
+
export class AccountIpcServer {
|
|
21
|
+
// `target`: what answers: selected, lease, reportFault, status, and where it keeps them, quota, invalidateQuota, forget.
|
|
22
|
+
constructor(stateDir, target) { this.stateDir = stateDir; this.target = target; this.connections = new Set(); }
|
|
23
|
+
async start() {
|
|
24
|
+
this.dir = await mkdtemp(join(tmpdir(), 'coda-codex-'));
|
|
25
|
+
this.socket = join(this.dir, 'agent.sock');
|
|
26
|
+
this.server = createServer(connection => this.serve(connection));
|
|
27
|
+
await new Promise((resolve, reject) => { this.server.once('error', reject); this.server.listen(this.socket, resolve); });
|
|
28
|
+
await chmod(this.socket, 0o600);
|
|
29
|
+
// A whole file at once: a reader never sees half a path.
|
|
30
|
+
const address = join(this.stateDir, ADDRESS), written = `${address}.${randomBytes(6).toString('hex')}`;
|
|
31
|
+
await writeFile(written, this.socket, { mode: 0o600 });
|
|
32
|
+
await rename(written, address);
|
|
33
|
+
}
|
|
34
|
+
// The address file stays: the next generation of the module may have written its own already.
|
|
35
|
+
async stop() {
|
|
36
|
+
for (const connection of this.connections) connection.destroy();
|
|
37
|
+
if (this.server?.listening) await new Promise(resolve => this.server.close(resolve));
|
|
38
|
+
if (this.dir) await rm(this.dir, { recursive: true, force: true });
|
|
39
|
+
}
|
|
40
|
+
serve(connection) {
|
|
41
|
+
this.connections.add(connection);
|
|
42
|
+
connection.on('close', () => this.connections.delete(connection));
|
|
43
|
+
connection.on('error', () => {});
|
|
44
|
+
connection.setEncoding('utf8');
|
|
45
|
+
let buffer = '', queue = Promise.resolve(), over = false;
|
|
46
|
+
const write = answer => { if (connection.writable) connection.write(`${JSON.stringify(answer)}\n`); };
|
|
47
|
+
// A request past the limit, whole or in part, is not read, let alone done: what was asked before it is answered first, then
|
|
48
|
+
// this is said and the connection ends. The same whichever way the bytes came.
|
|
49
|
+
const refuse = () => {
|
|
50
|
+
over = true;
|
|
51
|
+
queue = queue.then(() => { write({ error: { code: 'too_large', message: '请求太长' } }); connection.end(); });
|
|
52
|
+
};
|
|
53
|
+
connection.on('data', data => {
|
|
54
|
+
if (over) return;
|
|
55
|
+
buffer += data;
|
|
56
|
+
for (let at; (at = buffer.indexOf('\n')) >= 0;) {
|
|
57
|
+
const line = buffer.slice(0, at);
|
|
58
|
+
buffer = buffer.slice(at + 1);
|
|
59
|
+
if (Buffer.byteLength(line) > MAX_LINE) return refuse();
|
|
60
|
+
queue = queue.then(async () => write(await this.answer(line)));
|
|
61
|
+
}
|
|
62
|
+
if (Buffer.byteLength(buffer) > MAX_LINE) refuse();
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
async answer(line) {
|
|
66
|
+
let request;
|
|
67
|
+
try { request = JSON.parse(line); } catch { return { error: { code: 'invalid_input', message: '请求不对' } }; }
|
|
68
|
+
try { return { result: await this.run(request) ?? null }; } catch (error) {
|
|
69
|
+
if (error?.safe) return { error: { code: error.code ?? 'unavailable', message: error.message } };
|
|
70
|
+
return { error: asFault(error).toJSON() };
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
async run({ op, account, refresh, rejectedGeneration, force, ...info } = {}) {
|
|
74
|
+
const { target } = this, need = method => { if (typeof target[method] !== 'function') throw said('这台机器的账号托管模式不支持这个操作', 'unsupported'); };
|
|
75
|
+
const plain = value => { if (typeof value !== 'string' || !value) throw bad(); return value; };
|
|
76
|
+
switch (op) {
|
|
77
|
+
case 'selected': return target.selected();
|
|
78
|
+
case 'lease': return target.lease(plain(account), { refresh: Boolean(refresh), rejectedGeneration });
|
|
79
|
+
case 'reportFault': return target.reportFault(info);
|
|
80
|
+
case 'status': return target.status();
|
|
81
|
+
case 'quota': need('quota'); return target.quota(plain(account), { force: Boolean(force) });
|
|
82
|
+
case 'invalidate': need('invalidateQuota'); return target.invalidateQuota(account === undefined ? undefined : plain(account));
|
|
83
|
+
case 'forget': need('forget'); return target.forget(plain(account));
|
|
84
|
+
default: throw bad();
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// One request and its answer, to the service of this machine; a failure comes back as the error it was (a `Fault` of its kind).
|
|
90
|
+
export async function ipcRequest(stateDir, payload, { timeoutMs = 60_000 } = {}) {
|
|
91
|
+
let socket;
|
|
92
|
+
try { socket = (await readFile(join(stateDir, ADDRESS), 'utf8')).trim(); } catch { throw said(DOWN, 'service_down'); }
|
|
93
|
+
const answer = await new Promise((resolve, reject) => {
|
|
94
|
+
const connection = createConnection(socket), timer = setTimeout(() => connection.destroy(new Error('超时')), timeoutMs);
|
|
95
|
+
let buffer = '', connected = false;
|
|
96
|
+
connection.setEncoding('utf8');
|
|
97
|
+
connection.on('connect', () => { connected = true; connection.write(`${JSON.stringify(payload)}\n`); });
|
|
98
|
+
connection.on('data', data => {
|
|
99
|
+
buffer += data;
|
|
100
|
+
const at = buffer.indexOf('\n');
|
|
101
|
+
if (at >= 0) { clearTimeout(timer); connection.end(); try { resolve(JSON.parse(buffer.slice(0, at))); } catch { reject(said(CUT)); } }
|
|
102
|
+
});
|
|
103
|
+
connection.on('error', error => { clearTimeout(timer); reject(error.message === '超时' ? said('这台机器的 Codex 账号服务没有及时回答') : connected ? said(CUT) : said(DOWN, 'service_down')); });
|
|
104
|
+
connection.on('close', () => { clearTimeout(timer); reject(connected ? said(CUT) : said(DOWN, 'service_down')); });
|
|
105
|
+
});
|
|
106
|
+
if (!answer.error) return answer.result;
|
|
107
|
+
throw restoreFault(answer.error) ?? said(typeof answer.error.message === 'string' ? answer.error.message : '账号服务出错', answer.error.code);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// Tells the service of this machine what changed, if it runs: the change is made either way, so a failure is not told.
|
|
111
|
+
export async function tell(stateDir, payload) {
|
|
112
|
+
try { await ipcRequest(stateDir, payload, { timeoutMs: 10_000 }); } catch {}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// The account source the agent's bridge takes (agent/accounts.mjs): the chosen account, and its lease of tokens (`{ tokens, generation,
|
|
116
|
+
// expiresAt }`), from the service of this machine.
|
|
117
|
+
export function createIpcAccountSource(stateDir, options) {
|
|
118
|
+
const ask = payload => ipcRequest(stateDir, payload, options);
|
|
119
|
+
return {
|
|
120
|
+
selected: () => ask({ op: 'selected' }),
|
|
121
|
+
tokens: (account, { refresh = false, rejectedGeneration } = {}) => ask({ op: 'lease', account, refresh, rejectedGeneration }),
|
|
122
|
+
reportFault: info => ask({ op: 'reportFault', ...info }),
|
|
123
|
+
close() {},
|
|
124
|
+
};
|
|
125
|
+
}
|
package/lib/pool.mjs
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
// The controller of a pool of managed accounts, for the machine that hosts them: how many Codex processes run at once (a token
|
|
2
|
+
// lease goes before a quota reading), each account's last quota reading (kept briefly and shared by those asking at once), and
|
|
3
|
+
// which accounts are cooling down after a rate limit or an exhausted quota. Nothing here holds a token: the snapshots say
|
|
4
|
+
// only what state an account is in, and of its last quota reading only what lib/quota-summary.mjs takes of it. What reads
|
|
5
|
+
// (`readQuota`, `leaseTokens`) and the clock (`now`) are handed in.
|
|
6
|
+
import { SignInAgain, TransientError, faultOf } from './errors.mjs';
|
|
7
|
+
import { summarizeQuota } from './quota-summary.mjs';
|
|
8
|
+
|
|
9
|
+
const KINDS = ['rate_limited', 'quota_exhausted'];
|
|
10
|
+
// The longest a service may ask to wait (30 days); a cooldown past what a time can say is no cooldown.
|
|
11
|
+
export const MAX_RETRY_AFTER_MS = 30 * 24 * 60 * 60 * 1000;
|
|
12
|
+
// A model's name is kept only when it is plain (and not shaped like a token); no free text of a caller or of the service is kept.
|
|
13
|
+
const MODEL = /^[\w.:/-]{1,64}$/;
|
|
14
|
+
const plainModel = model => typeof model === 'string' && MODEL.test(model) && model.split('.').length < 3;
|
|
15
|
+
// What crosses the pool's edge as a failure: one of the four kinds, made anew and said as the kind says it (whatever message the
|
|
16
|
+
// error had stays behind); anything unrecognized is temporary.
|
|
17
|
+
const fault = error => { const kind = faultOf(error) ?? new TransientError(); return new kind.constructor(undefined, { retryAfterMs: kind.retryAfterMs, resetAt: kind.resetAt }); };
|
|
18
|
+
|
|
19
|
+
export class AccountPool {
|
|
20
|
+
#at; #now; #readQuota; #leaseTokens; #max; #quotaSlots; #ttl; #rateMs; #exhaustedMs;
|
|
21
|
+
#high = []; #low = []; #running = 0; #quotaRunning = 0;
|
|
22
|
+
#quota = new Map(); #inflight = new Map(); #epoch = new Map(); #login = new Map(); #cooldowns = new Map();
|
|
23
|
+
// The generation of an account's state: what began before it changed (invalidation, forgetting) does not write back.
|
|
24
|
+
#generation(account) { return this.#epoch.get(account) ?? this.#epoch.set(account, 0).get(account); }
|
|
25
|
+
#bump(account) { this.#epoch.set(account, this.#generation(account) + 1); }
|
|
26
|
+
constructor({ at, now = Date.now, readQuota, leaseTokens, maxConcurrency = 2, quotaTtlMs = 30_000,
|
|
27
|
+
rateLimitCooldownMs = 60_000, exhaustedCooldownMs = 30 * 60_000 } = {}) {
|
|
28
|
+
this.#at = at; this.#now = now; this.#readQuota = readQuota; this.#leaseTokens = leaseTokens; this.#max = maxConcurrency;
|
|
29
|
+
// One slot stays for tokens while quota readings run, unless it is the only one.
|
|
30
|
+
this.#quotaSlots = Math.max(1, maxConcurrency - 1);
|
|
31
|
+
this.#ttl = quotaTtlMs; this.#rateMs = rateLimitCooldownMs; this.#exhaustedMs = exhaustedCooldownMs;
|
|
32
|
+
}
|
|
33
|
+
#run(queue, task, quota) {
|
|
34
|
+
return new Promise((resolve, reject) => { queue.push({ task, quota, resolve, reject }); this.#pump(); });
|
|
35
|
+
}
|
|
36
|
+
#pump() {
|
|
37
|
+
while (this.#running < this.#max) {
|
|
38
|
+
const job = this.#high.shift() ?? (this.#quotaRunning < this.#quotaSlots ? this.#low.shift() : undefined);
|
|
39
|
+
if (!job) return;
|
|
40
|
+
this.#running++; if (job.quota) this.#quotaRunning++;
|
|
41
|
+
Promise.resolve().then(job.task).then(job.resolve, job.reject).finally(() => {
|
|
42
|
+
this.#running--; if (job.quota) this.#quotaRunning--;
|
|
43
|
+
this.#pump();
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
#state(account) { return this.#login.get(account) ?? this.#login.set(account, { signedIn: null, fault: null }).get(account); }
|
|
48
|
+
// What an operation on an account found: signing in again is needed, or not; a temporary failure changes nothing about the login.
|
|
49
|
+
#settle(account, failure) {
|
|
50
|
+
const state = this.#state(account);
|
|
51
|
+
if (!failure) { state.signedIn = true; state.fault = null; return; }
|
|
52
|
+
if (failure instanceof SignInAgain) state.signedIn = false;
|
|
53
|
+
state.fault = failure.code;
|
|
54
|
+
}
|
|
55
|
+
// The tokens of an account, with their generation and expiry; ahead of every quota reading.
|
|
56
|
+
async lease(account, options) {
|
|
57
|
+
const epoch = this.#generation(account);
|
|
58
|
+
try {
|
|
59
|
+
const lease = await this.#run(this.#high, () => this.#leaseTokens(account, this.#at, options), false);
|
|
60
|
+
if (this.#generation(account) === epoch) this.#settle(account);
|
|
61
|
+
return lease;
|
|
62
|
+
} catch (error) {
|
|
63
|
+
const failure = fault(error);
|
|
64
|
+
if (this.#generation(account) === epoch) this.#settle(account, failure);
|
|
65
|
+
throw failure;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
// The account's quota, from a reading not older than the cache's time, or one under way, or a new one.
|
|
69
|
+
quota(account, { force = false } = {}) {
|
|
70
|
+
const cached = this.#quota.get(account);
|
|
71
|
+
if (!force && cached && this.#now() - cached.at < this.#ttl) return Promise.resolve(cached.result);
|
|
72
|
+
const reading = this.#inflight.get(account);
|
|
73
|
+
if (reading) return reading;
|
|
74
|
+
const epoch = this.#generation(account);
|
|
75
|
+
const started = this.#run(this.#low, () => this.#readQuota(account, this.#at), true).then(result => {
|
|
76
|
+
if (this.#generation(account) === epoch) { this.#quota.set(account, { result, at: this.#now() }); this.#settle(account); }
|
|
77
|
+
return result;
|
|
78
|
+
}, error => {
|
|
79
|
+
const failure = fault(error);
|
|
80
|
+
if (this.#generation(account) === epoch) this.#settle(account, failure);
|
|
81
|
+
throw failure;
|
|
82
|
+
}).finally(() => {
|
|
83
|
+
if (this.#inflight.get(account) === started) this.#inflight.delete(account);
|
|
84
|
+
});
|
|
85
|
+
this.#inflight.set(account, started);
|
|
86
|
+
return started;
|
|
87
|
+
}
|
|
88
|
+
// After a switch, reset, login or removal: the next reading is a new one, and one under way is not kept.
|
|
89
|
+
invalidateQuota(account) {
|
|
90
|
+
for (const key of account === undefined ? [...this.#epoch.keys(), ...this.#quota.keys(), ...this.#inflight.keys()] : [account]) {
|
|
91
|
+
this.#quota.delete(key); this.#inflight.delete(key); this.#bump(key);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
forget(account) { this.invalidateQuota(account); this.#login.delete(account); this.#cooldowns.delete(account); }
|
|
95
|
+
// An account turned away by the service: for a rate limit a short while, or what the service said; for an exhausted quota until
|
|
96
|
+
// it resets, or a long while. Only the kind, the times and a plain model name are kept.
|
|
97
|
+
reportFault({ accountId, kind, retryAfterMs, resetAt, model }) {
|
|
98
|
+
if (typeof accountId !== 'string' || !accountId || !KINDS.includes(kind)) throw new Error('没有指明哪个账号、哪一种故障');
|
|
99
|
+
const now = this.#now(), reset = resetAt === undefined ? NaN : new Date(resetAt).getTime();
|
|
100
|
+
const wait = kind === 'rate_limited' ? (Number.isFinite(retryAfterMs) && retryAfterMs > 0 ? retryAfterMs : this.#rateMs)
|
|
101
|
+
: Number.isFinite(reset) && reset > now ? reset - now : this.#exhaustedMs;
|
|
102
|
+
if ((retryAfterMs !== undefined && !(retryAfterMs <= MAX_RETRY_AFTER_MS)) || !Number.isFinite(new Date(now + wait).getTime())) throw new Error('冷却的时间超出范围');
|
|
103
|
+
const until = now + wait, known = this.#cooldowns.get(accountId);
|
|
104
|
+
if (known && known.until > until) return this.getCooldown(accountId);
|
|
105
|
+
this.#cooldowns.set(accountId, { kind, until, ...(plainModel(model) ? { model } : {}) });
|
|
106
|
+
return this.getCooldown(accountId);
|
|
107
|
+
}
|
|
108
|
+
getCooldown(accountId) {
|
|
109
|
+
const each = this.#cooldowns.get(accountId);
|
|
110
|
+
if (!each) return null;
|
|
111
|
+
const now = this.#now();
|
|
112
|
+
if (each.until <= now) { this.#cooldowns.delete(accountId); return null; }
|
|
113
|
+
const { until, ...rest } = each;
|
|
114
|
+
return { ...rest, until: new Date(until).toISOString(), remainingMs: until - now };
|
|
115
|
+
}
|
|
116
|
+
statusSnapshot() {
|
|
117
|
+
for (const account of [...this.#cooldowns.keys()]) this.getCooldown(account);
|
|
118
|
+
const ids = new Set([...this.#login.keys(), ...this.#cooldowns.keys(), ...this.#quota.keys()]);
|
|
119
|
+
return { accounts: [...ids].map(accountId => {
|
|
120
|
+
const state = this.#login.get(accountId) ?? { signedIn: null, fault: null }, cached = this.#quota.get(accountId);
|
|
121
|
+
return { accountId, signedIn: state.signedIn, fault: state.fault, quotaAt: cached ? new Date(cached.at).toISOString() : null,
|
|
122
|
+
quota: cached ? summarizeQuota(cached.result) : null, cooldown: this.getCooldown(accountId) };
|
|
123
|
+
}) };
|
|
124
|
+
}
|
|
125
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// What a reading of an account's quota (`account/rateLimits/read`) says, as far as it is shown: its windows and its full resets left.
|
|
2
|
+
// Only these fields are taken from Codex's answer, for the resources page (scripts/quota.mjs) and the centre's status (lib/pool.mjs).
|
|
3
|
+
|
|
4
|
+
export const line = (value, max = 80) => typeof value === 'string' ? [...value.replace(/\s+/g, ' ').trim()].slice(0, max).join('') : '';
|
|
5
|
+
export const unixTime = value => typeof value === 'number' && Number.isFinite(new Date(value * 1000).getTime()) ? new Date(value * 1000).toISOString() : null;
|
|
6
|
+
|
|
7
|
+
// 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
|
|
8
|
+
// name is said only when there are several: by default Codex's, else `name(limit, index)`.
|
|
9
|
+
export function windows(result, { name = limit => line(limit.limitName ?? limit.limitId, 40) || '额度' } = {}) {
|
|
10
|
+
const byID = result?.rateLimitsByLimitId ? Object.values(result.rateLimitsByLimitId) : [];
|
|
11
|
+
const limits = (byID.length ? byID : [result?.rateLimits]).filter(Boolean);
|
|
12
|
+
return limits.flatMap((limit, index) => ['primary', 'secondary'].flatMap(key => {
|
|
13
|
+
const w = limit[key]; if (!w) return [];
|
|
14
|
+
const minutes = w.windowDurationMins;
|
|
15
|
+
const duration = minutes === 300 ? '5 小时' : minutes === 10080 ? '7 天' : Number.isSafeInteger(minutes) && minutes > 0 ? `${minutes} 分钟` : '额度';
|
|
16
|
+
const used = typeof w.usedPercent === 'number' && w.usedPercent >= 0 && w.usedPercent <= 100 ? w.usedPercent : null;
|
|
17
|
+
const left = used === null ? null : Math.round(100 - used), resets = unixTime(w.resetsAt);
|
|
18
|
+
return [{ label: `${limits.length > 1 ? `${name(limit, index)} · ` : ''}${duration}`,
|
|
19
|
+
...(left === null ? { value: '—' } : { value: `剩余 ${left}%`, fraction: left / 100 }),
|
|
20
|
+
...(resets ? { time: resets } : {}) }];
|
|
21
|
+
}));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// The full resets left: the count is Codex's word (its list of them may be capped or missing). Those listed are the
|
|
25
|
+
// available ones, earliest to expire first; one without an expiry never expires.
|
|
26
|
+
export function credits(result) {
|
|
27
|
+
const summary = result?.rateLimitResetCredits;
|
|
28
|
+
if (!Number.isSafeInteger(summary?.availableCount)) return null;
|
|
29
|
+
const listed = (summary.credits ?? []).filter(c => c?.status === 'available' && c.resetType === 'codexRateLimits' && typeof c.id === 'string' && c.id)
|
|
30
|
+
.sort((a, b) => (a.expiresAt ?? Infinity) - (b.expiresAt ?? Infinity));
|
|
31
|
+
return { count: summary.availableCount, listed };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// A reading as the centre's status says it: the windows, and how many full resets are left and when the first of them expires.
|
|
35
|
+
// Nothing else of Codex's answer: not even a limit's name, which is free text (`额度 1`, `额度 2` in its place).
|
|
36
|
+
export function summarizeQuota(result) {
|
|
37
|
+
const resets = credits(result), first = resets?.listed[0], next = first?.expiresAt == null ? null : unixTime(first.expiresAt);
|
|
38
|
+
return { windows: windows(result, { name: (limit, index) => `额度 ${index + 1}` }), resets: resets ? { count: resets.count, ...(next ? { nextExpiresAt: next } : {}) } : null };
|
|
39
|
+
}
|
package/lib/remote.mjs
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// The consumer of a hosting centre (`codex.accountHosting` = remote): tokens and the chosen account come from the space's centre
|
|
2
|
+
// (lib/hub.mjs), over the stream `tokens`, one request and one answer. When the centre cannot be reached the error says so: a
|
|
3
|
+
// machine that uses hosted accounts never falls back to a login of its own.
|
|
4
|
+
import { KIND, restoreFault, said } from './wire.mjs';
|
|
5
|
+
|
|
6
|
+
export const TIMEOUT_MS = 15_000;
|
|
7
|
+
const text = value => typeof value === 'string' && value !== '';
|
|
8
|
+
// What a centre answers with, as far as this plugin takes it: anything else is another version of the plugin.
|
|
9
|
+
const isSelected = value => text(value?.selected?.id) && typeof value.selected.name === 'string';
|
|
10
|
+
const isLease = value => text(value?.tokens?.accessToken) && text(value.tokens.chatgptAccountId) && text(value.generation) && Number.isFinite(value.expiresAt);
|
|
11
|
+
// A record is told apart by its holder and its ID.
|
|
12
|
+
const slot = entry => `${entry.owner}\n${entry.id}`;
|
|
13
|
+
const CONTROL = ['accountId', 'kind', 'retryAfterMs', 'resetAt', 'model'];
|
|
14
|
+
|
|
15
|
+
export class CodexRemote {
|
|
16
|
+
constructor(coda, { host = '', timeoutMs = TIMEOUT_MS } = {}) {
|
|
17
|
+
this.coda = coda; this.host = host; this.timeoutMs = timeoutMs;
|
|
18
|
+
this.entries = new Map(); this.watcher = null;
|
|
19
|
+
}
|
|
20
|
+
async start() {
|
|
21
|
+
this.watcher = await this.coda.watch(KIND, ({ type, entry }) => {
|
|
22
|
+
if (type === 'DELETED') this.entries.delete(slot(entry)); else this.entries.set(slot(entry), entry);
|
|
23
|
+
});
|
|
24
|
+
for (const entry of await this.coda.list(KIND)) this.entries.set(slot(entry), entry);
|
|
25
|
+
}
|
|
26
|
+
stop() { this.watcher?.dispose(); this.watcher = null; this.entries.clear(); }
|
|
27
|
+
// The centre to use: the one named, or the only one there is. Our own record (if this machine is a centre too) is never one.
|
|
28
|
+
target() {
|
|
29
|
+
const centres = [...this.entries.values()].filter(entry => !entry.local);
|
|
30
|
+
if (!this.host) {
|
|
31
|
+
if (centres.length === 1) return centres[0];
|
|
32
|
+
throw said(centres.length ? '空间里有多台 Codex 托管机:请在设置「指定托管机」里填要用的那台的机器 ID 或机器名'
|
|
33
|
+
: '空间里没有在线的 Codex 托管机:请先在一台机器的设置里把「账号托管」设为 host');
|
|
34
|
+
}
|
|
35
|
+
const named = centres.filter(entry => entry.owner === this.host || entry.location === this.host);
|
|
36
|
+
if (named.length === 1) return named[0];
|
|
37
|
+
throw said(named.length ? `有多台托管机叫「${this.host}」:请在设置「指定托管机」里改填机器 ID`
|
|
38
|
+
: `指定的托管机「${this.host}」不在线,或没有开启 Codex 账号集中托管`);
|
|
39
|
+
}
|
|
40
|
+
// A centre that cannot be reached, said so, with no other login to take its place.
|
|
41
|
+
unreachable(target, error, timedOut) {
|
|
42
|
+
return said(`Codex 托管机「${target.location}」暂时连不上(${timedOut ? '超时' : error?.code ?? '连接中断'}):已设为使用空间托管,不会退回本机的 Codex 登录`);
|
|
43
|
+
}
|
|
44
|
+
async #ask(payload) {
|
|
45
|
+
const target = this.target(), stop = new AbortController(), timer = setTimeout(() => stop.abort(), this.timeoutMs);
|
|
46
|
+
let response, body;
|
|
47
|
+
try {
|
|
48
|
+
response = await this.coda.openStream({ kind: KIND, id: target.id }, 'tokens',
|
|
49
|
+
{ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(payload), signal: stop.signal });
|
|
50
|
+
body = await response.text();
|
|
51
|
+
} catch (error) { throw this.unreachable(target, error, stop.signal.aborted); } finally { clearTimeout(timer); }
|
|
52
|
+
let value;
|
|
53
|
+
try { value = JSON.parse(body); } catch {}
|
|
54
|
+
if (response.ok) {
|
|
55
|
+
if (value) return value;
|
|
56
|
+
throw said('Codex 托管机的回答读不懂:两台机器的 Codex 插件版本可能对不上');
|
|
57
|
+
}
|
|
58
|
+
const fault = restoreFault(value?.error);
|
|
59
|
+
if (fault) throw fault;
|
|
60
|
+
if (response.status >= 500) throw this.unreachable(target, { code: `HTTP ${response.status}` });
|
|
61
|
+
throw said(`Codex 托管机拒绝了请求(${value?.error?.code ?? `HTTP ${response.status}`}):两台机器的 Codex 插件版本可能对不上`);
|
|
62
|
+
}
|
|
63
|
+
async selected() {
|
|
64
|
+
const value = await this.#ask({ op: 'selected' });
|
|
65
|
+
if (!isSelected(value)) throw said('Codex 托管机的回答不对:两台机器的 Codex 插件版本可能对不上');
|
|
66
|
+
const { id, name, instanceId } = value.selected;
|
|
67
|
+
return { id, name, ...(text(instanceId) ? { instanceId } : {}) };
|
|
68
|
+
}
|
|
69
|
+
async lease(account, { refresh = false, rejectedGeneration } = {}) {
|
|
70
|
+
const value = await this.#ask({ op: 'tokens', account, refresh: Boolean(refresh), ...(rejectedGeneration ? { rejectedGeneration } : {}) });
|
|
71
|
+
if (!isLease(value)) throw said('Codex 托管机的回答不对:两台机器的 Codex 插件版本可能对不上');
|
|
72
|
+
const { accessToken, chatgptAccountId, chatgptPlanType } = value.tokens;
|
|
73
|
+
return { tokens: { accessToken, chatgptAccountId, ...(text(chatgptPlanType) ? { chatgptPlanType } : {}) }, generation: value.generation, expiresAt: value.expiresAt };
|
|
74
|
+
}
|
|
75
|
+
async #call(operation, input) {
|
|
76
|
+
const target = this.target();
|
|
77
|
+
try { return await this.coda[operation === 'status' ? 'query' : 'call']({ kind: KIND, id: target.id }, operation, input, { timeout: this.timeoutMs }); }
|
|
78
|
+
catch (error) { throw this.unreachable(target, error, error?.name === 'TimeoutError'); }
|
|
79
|
+
}
|
|
80
|
+
status() { return this.#call('status', {}); }
|
|
81
|
+
reportFault(info) { return this.#call('report-fault', Object.fromEntries(CONTROL.filter(key => info?.[key] !== undefined).map(key => [key, info[key]]))); }
|
|
82
|
+
}
|
package/lib/wire.mjs
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// What the hosting centre, its consumers and the local socket say to one another: the protocol's name, the one failure that
|
|
2
|
+
// is no kind of Fault of the login, and how a failure crosses an edge. The words of a failure are fixed by its kind; what the
|
|
3
|
+
// service or the network wrote is never carried on.
|
|
4
|
+
import { Fault, TransientError, faultFromJSON } from './errors.mjs';
|
|
5
|
+
|
|
6
|
+
export const KIND = 'codex/account-pool@1', KEY = 'pool', PLUGIN = 'codex';
|
|
7
|
+
// The most a request of the `tokens` stream may say, and the most a line of the local socket may be.
|
|
8
|
+
export const MAX_BODY = 16 * 1024, MAX_LINE = 64 * 1024;
|
|
9
|
+
// No account is chosen, or the chosen one is gone from the centre.
|
|
10
|
+
export class NoAccount extends Fault { static text = '托管机上没有可用的所选账号:请在托管机的「资源」添加、选择或重新登录一个 Codex 账号'; code = 'no_account'; }
|
|
11
|
+
export const restoreFault = error => error?.code === 'no_account' ? new NoAccount() : faultFromJSON(error ?? undefined);
|
|
12
|
+
// An error whose words are this plugin's own, safe to say to anyone who asked.
|
|
13
|
+
export const said = (message, code) => Object.assign(new Error(message), { safe: true, ...(code ? { code } : {}) });
|
|
14
|
+
export const asFault = error => error instanceof Fault ? error : new TransientError();
|
|
15
|
+
const STATUS = { sign_in_again: 401, no_account: 404, rate_limited: 429, quota_exhausted: 429, transient: 503 };
|
|
16
|
+
export const statusOf = fault => STATUS[fault.code] ?? 503;
|
package/main.mjs
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
// The resident part of the Codex plugin: what `codex.accountHosting` says this machine is. `host` keeps the managed accounts and
|
|
2
|
+
// serves them to the space (lib/hub.mjs); `remote` takes them from the space's centre (lib/remote.mjs); `local` (the default) runs
|
|
3
|
+
// nothing. Either way the agent and the scripts reach it through the private socket of lib/ipc.mjs. A change of the settings
|
|
4
|
+
// stops what ran and starts what is now asked for, one after another. The handlers of the centre's protocol are registered at
|
|
5
|
+
// once and kept to the end (the manifest declares them in every mode); only a running centre answers through them.
|
|
6
|
+
import { accountHost, hostingMode } from './lib/config.mjs';
|
|
7
|
+
import { CodexHub, serveAccountPool } from './lib/hub.mjs';
|
|
8
|
+
import { AccountIpcServer } from './lib/ipc.mjs';
|
|
9
|
+
import { CodexRemote } from './lib/remote.mjs';
|
|
10
|
+
import { KIND } from './lib/wire.mjs';
|
|
11
|
+
|
|
12
|
+
let running = null;
|
|
13
|
+
// `options.hub`, `options.remote`: what the centre and the consumer are given beyond the host's (for the tests).
|
|
14
|
+
export async function activate(coda, options = {}) {
|
|
15
|
+
let wanted = null, current = null, hub = null, queue = Promise.resolve(), closed = false, cold = true;
|
|
16
|
+
const asked = settings => {
|
|
17
|
+
const env = { CODA_PLUGIN_SETTINGS: JSON.stringify(settings) }, mode = hostingMode(env);
|
|
18
|
+
return { mode, host: mode === 'remote' ? accountHost(env) : '' };
|
|
19
|
+
};
|
|
20
|
+
async function apply(settings) {
|
|
21
|
+
const next = asked(settings), key = `${next.mode}\n${next.host}`;
|
|
22
|
+
if (key === wanted) return;
|
|
23
|
+
// What ran stays until it is stopped whole: a stop that failed is tried again by the next change.
|
|
24
|
+
if (current) { wanted = null; await current.stop(); current = null; hub = null; }
|
|
25
|
+
// A centre's record left by a run that ended without stopping it is not the centre's any more, unless this run is one.
|
|
26
|
+
if (cold && next.mode !== 'host') await coda.replace(KIND, []);
|
|
27
|
+
cold = false;
|
|
28
|
+
if (next.mode !== 'local') {
|
|
29
|
+
const service = next.mode === 'host' ? new CodexHub(coda, options.hub) : new CodexRemote(coda, { host: next.host, ...options.remote });
|
|
30
|
+
const ipc = new AccountIpcServer(coda.plugin.state, service);
|
|
31
|
+
try { await service.start(); await ipc.start(); }
|
|
32
|
+
catch (error) { await Promise.allSettled([ipc.stop(), service.stop()]); throw error; }
|
|
33
|
+
// Each is stopped whatever the other did; the first failure is thrown after both.
|
|
34
|
+
if (next.mode === 'host') hub = service;
|
|
35
|
+
current = { async stop() {
|
|
36
|
+
const failed = [];
|
|
37
|
+
for (const part of [ipc, service]) try { await part.stop(); } catch (error) { failed.push(error); }
|
|
38
|
+
if (failed.length) throw failed[0];
|
|
39
|
+
} };
|
|
40
|
+
}
|
|
41
|
+
wanted = key;
|
|
42
|
+
}
|
|
43
|
+
const served = await serveAccountPool(coda, () => hub);
|
|
44
|
+
const enqueue = settings => queue = queue.catch(() => {}).then(() => closed ? undefined : apply(settings));
|
|
45
|
+
const subscription = coda.settings.onChange(settings => enqueue(settings).catch(error => console.error(`codex:切换账号托管失败:${error.message}`)));
|
|
46
|
+
running = { async stop() {
|
|
47
|
+
closed = true; subscription.dispose();
|
|
48
|
+
await queue.catch(() => {});
|
|
49
|
+
// The handlers are withdrawn whatever the centre or the consumer did; the first failure is thrown after both.
|
|
50
|
+
const failed = [];
|
|
51
|
+
try { await current?.stop(); } catch (error) { failed.push(error); }
|
|
52
|
+
try { await served.dispose(); } catch (error) { failed.push(error); }
|
|
53
|
+
if (failed.length) throw failed[0];
|
|
54
|
+
} };
|
|
55
|
+
try { await enqueue(await coda.settings.get()); } catch (error) { await deactivate(); throw error; }
|
|
56
|
+
}
|
|
57
|
+
export async function deactivate() {
|
|
58
|
+
await running?.stop();
|
|
59
|
+
running = null;
|
|
60
|
+
}
|