@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/README.md
CHANGED
|
@@ -49,6 +49,23 @@ Codex Agent:Codex 插件提供的入口运行 codex-acp,报告子 Agent、
|
|
|
49
49
|
- 令牌只走账号桥与 app-server 之间的私有管道,不经 ACP,不进会话记录。连接显式指定了自己的 Codex 程序(`CODEX_PATH`)时不接账号桥。
|
|
50
50
|
交令牌(`chatgptAuthTokens`)是 app-server 的实验接口:升级 codex-acp 或 Codex 时复核登录、`account/read` 的身份核对、续期请求与轮次边界。
|
|
51
51
|
|
|
52
|
+
## 空间集中托管
|
|
53
|
+
|
|
54
|
+
设置「账号托管」(`codex.accountHosting`,`local` / `host` / `remote`,默认 `local`)和「指定托管机」(`codex.accountHost`)。一个空间里只让一台机器当托管机(`host`),别的机器设成 `remote`,它们的 Codex 会话用托管机上的账号,不用各自登录。
|
|
55
|
+
|
|
56
|
+
- **`local`(默认)**:不变。各机器用自己的 Codex 登录,开了「多账号」时用本机管理的账号。
|
|
57
|
+
- **`host`(托管机)**:视同开了「多账号」(不用再勾),账号都存在这台机器上。托管机集中登录,独占账号的 `refresh_token`:续期只在这里、按账号串行进行,各机器领到的只是短期 `access_token`。
|
|
58
|
+
资源页统一报额度:「Codex」里是托管机的账号,额度经常驻模块读取并缓存(同一账号的读取合并、Codex 子进程有并发上限,慢查询不挡领令牌),页面上注明「本机托管的账号已向空间共享」;模块没运行(独立运行命令)时退回直接读取。在资源页切换、添加、移除账号和使用完全重置后,会通知常驻模块清掉缓存、更新托管记录的状态;模块没运行时忽略这条通知。托管机自己的会话也走同一个账号池,与其他机器共用按代续期和并发优先级。
|
|
59
|
+
- **`remote`(消费机)**:自动发现空间里的托管机(空间里有多台时在「指定托管机」填机器 ID 或机器名)。会话仍由本机的 codex-acp 与 Codex 运行,原生 WS、提示缓存与 `service_tier` 都照旧,只是登录用的令牌向托管机领,经账号桥(`agent/accounts.mjs`)交给 Codex。
|
|
60
|
+
本机登录被隔离:Codex 在插件状态目录里私有的 `remote-home`(`0700`,每次启动先删掉里面的 `auth.json`)运行,去掉 `OPENAI_API_KEY`、`CODEX_API_KEY`、`CODEX_ACCESS_TOKEN`,凭据存储强制为文件,不读本机的 `~/.codex/auth.json`、钥匙串和环境变量里的凭据。托管机选好的账号交给 Codex 之前,`account/read`、开启、恢复、分叉线程与开始一轮都不放行;ACP 自己的登录与登出始终拒绝。
|
|
61
|
+
托管机离线、没选账号、账号失效或没有指定的托管机时,直接在那一轮报错,原因写明,**不退回本机登录**。资源页只剩一条空的「Codex」,提示在托管机管理或切换账号;本机的登录入口与动作(`sign-in`、`act`、`cli.mjs login`)都拒绝,写「当前机器已启用 Codex 空间集中托管,请在托管机管理或切换账号」。
|
|
62
|
+
- **按代续期**:每份令牌带一个不含秘密的代号(`generation`)。Codex 令牌被拒要续期时,桥把它正在用的代号作为 `rejectedGeneration` 交给托管机:托管机若已经续过,直接给新的一份,不再续第二次;几台机器同时撞到同一份旧令牌,托管机只续一次。令牌的字段只有 `accessToken`、`chatgptAccountId` 和可选的 `chatgptPlanType`,代号与到期时间不交给 Codex。
|
|
63
|
+
- **限流上报**:会话里 Codex 报账号被限流(429)或额度用完时,桥把这一事实(账号 ID、种类、等待时长或恢复时刻,不含错误原文)尽力告诉托管机,托管机记下这个账号的冷却,各机器经池的状态都看得到(不会据此自动换号);上报失败不影响会话。
|
|
64
|
+
|
|
65
|
+
**跨机通道与安全边界**(协议 `codex/account-pool@1`):托管机每台发布一条记录,只说是否就绪、账号数、是否已选,没有邮箱、账号名与令牌。
|
|
66
|
+
短期 `access_token` 只经一次一答的流 `coda.stream`(`tokens`)传递,不进 `coda.call`、`coda.query`、记录或 SQLite,应答带 `no-store`;非密状态(池的状态、各账号的冷却)经 `coda.query`,限流上报经 `coda.call`,两者都只收 Codex 插件自己的来访。
|
|
67
|
+
本机的 agent 与资源脚本不直接连托管机,也不读账号文件,只经本机常驻模块的私有 Unix socket(`agent-socket`,0600、目录 0700)问;socket 里的每一行都不打印。
|
|
68
|
+
|
|
52
69
|
「模型服务」设置、异步消息与提问见仓库根 README 的「模型服务」「Codex 异步消息与提问」。
|
|
53
70
|
|
|
54
71
|
回执 `usage` 的模型身份(Coda 的 docs/plugins.md「Coda 的用量记录」):codex-acp 向 Codex 派发模型请求时,补丁把当时实际派发的型号绑在会话上;这一轮是服务里的模型时,`usage` 顶层带 `service`(由注入地址 `…/resources/<接口种类>/<UUID><路径>` 得到的 `coda://<接口种类>/<UUID>`)与 `asked`(发给服务的裸模型 ID)。地址不是这个形状、Codex 自己的模型、以及没有派发模型请求的 prompt(如切换模型后执行 `/status`)都不带;每个 prompt 开始时清掉上一轮的绑定。`/review`、`/goal` 这类由 codex-acp 另行派发轮次的命令,在注入服务上运行时的轮次目前不带 `service`、`asked`,用量退回按执行配置的模型 ID 记,数不会错也不会丢,只是暂时归不到服务那一行。不报 `served`。
|
package/agent/accounts.mjs
CHANGED
|
@@ -1,30 +1,77 @@
|
|
|
1
|
-
// The account bridge: what codex-acp runs as its Codex (`CODEX_PATH`, set by entry.mjs) when
|
|
2
|
-
// `codex.multipleAccounts`)
|
|
3
|
-
//
|
|
4
|
-
// the session's journal.
|
|
1
|
+
// The account bridge: what codex-acp runs as its Codex (`CODEX_PATH`, set by entry.mjs) when the accounts are managed: 「多账号」
|
|
2
|
+
// (the setting `codex.multipleAccounts`) or the space's hosting (`codex.accountHosting`, host or remote). Between codex-acp and the
|
|
3
|
+
// real app-server, it signs the app-server in to the managed account chosen (the source), by handing it that account's tokens; they
|
|
4
|
+
// stay on this private pipe, below ACP and the session's journal. The source is this machine's managed accounts (scripts/manager.mjs)
|
|
5
|
+
// in local mode, the account service of this machine (lib/ipc.mjs) in host mode (the managed accounts when that is not running),
|
|
6
|
+
// and in remote mode only that service, which takes them from the space's centre: then Codex is cut off from every login of this
|
|
7
|
+
// machine (`strict`): nothing goes to the app-server before the centre's account is signed in, and ACP cannot sign in or out.
|
|
8
|
+
// Elsewhere a source that says nothing is chosen (`null`) leaves Codex on this machine's own login.
|
|
5
9
|
// The choice takes effect where nothing is under way: as a session starts and between turns (the native thread and turn
|
|
6
10
|
// entry points ask the source each time). A turn whose account cannot be taken fails and says why, rather than going out
|
|
7
11
|
// on the one before; one under way finishes on the account it began with.
|
|
8
|
-
import {
|
|
12
|
+
import { chmodSync, lstatSync, mkdirSync, rmSync } from 'node:fs';
|
|
13
|
+
import { join, resolve } from 'node:path';
|
|
9
14
|
import { fileURLToPath } from 'node:url';
|
|
10
15
|
import { AppServer } from '../scripts/app-server.mjs';
|
|
11
|
-
import {
|
|
16
|
+
import { accountEnv, fileCredentials } from '../scripts/codex.mjs';
|
|
17
|
+
import { chosen, leaseTokens, rpcTokens } from '../scripts/manager.mjs';
|
|
18
|
+
import { isHostMode, isRemoteMode } from '../lib/config.mjs';
|
|
19
|
+
import { faultOf } from '../lib/errors.mjs';
|
|
20
|
+
import { createIpcAccountSource, isDown } from '../lib/ipc.mjs';
|
|
12
21
|
import { readLines } from './lines.mjs';
|
|
13
22
|
|
|
14
23
|
// The managed accounts, read anew each time they are asked, so a switch on the resources page reaches the session at its
|
|
15
|
-
// next boundary. `refresh: true` asks for a rejected access token to be renewed, even before its expiry
|
|
16
|
-
|
|
24
|
+
// next boundary. `refresh: true` asks for a rejected access token to be renewed, even before its expiry; `rejectedGeneration` names
|
|
25
|
+
// the one that was rejected, so that a renewal already made is not made again.
|
|
26
|
+
const managed = { selected: () => chosen(), tokens: (account, { refresh = false, rejectedGeneration } = {}) => leaseTokens(account, undefined, { refresh, rejectedGeneration }), close() {} };
|
|
27
|
+
// The centre's own machine: its account service, and where that is not running (no module yet), the managed accounts as in local mode.
|
|
28
|
+
function hosted(env) {
|
|
29
|
+
const service = createIpcAccountSource(env.CODA_PLUGIN_STATE);
|
|
30
|
+
const asked = async (ask, fallback) => { try { return await ask(); } catch (error) { if (isDown(error)) return fallback(); throw error; } };
|
|
31
|
+
return { selected: () => asked(() => service.selected(), () => managed.selected()), tokens: (account, options) => asked(() => service.tokens(account, options), () => managed.tokens(account, options)),
|
|
32
|
+
reportFault: info => service.reportFault(info), close() {} };
|
|
33
|
+
}
|
|
34
|
+
const sourceOf = env => isRemoteMode(env) ? createIpcAccountSource(env.CODA_PLUGIN_STATE) : isHostMode(env) ? hosted(env) : managed;
|
|
35
|
+
// What a source gives for tokens: a lease (`{ tokens, generation, expiresAt }`), or the tokens alone.
|
|
36
|
+
const leased = value => value?.tokens && typeof value.tokens === 'object' ? value : { tokens: value };
|
|
37
|
+
// Whether two choices are the same account: its ID, and the instance of it (an account removed and signed in again is another).
|
|
38
|
+
const same = (a, b) => a?.id === b?.id && (a?.instanceId ?? null) === (b?.instanceId ?? null);
|
|
39
|
+
// The native entry points that set the model to work: each takes the chosen account first, as a turn does.
|
|
40
|
+
const TURNS = ['turn/start', 'review/start', 'thread/compact/start', 'thread/goal/set'];
|
|
41
|
+
|
|
42
|
+
// A consumer's Codex home: a private directory of its own, kept between runs, in which nothing of a login stays.
|
|
43
|
+
function remoteHome(env) {
|
|
44
|
+
if (!env.CODA_PLUGIN_STATE) throw new Error('Coda 没有提供插件状态目录');
|
|
45
|
+
const home = join(env.CODA_PLUGIN_STATE, 'remote-home');
|
|
46
|
+
mkdirSync(home, { recursive: true, mode: 0o700 });
|
|
47
|
+
if (!lstatSync(home).isDirectory() || lstatSync(home).isSymbolicLink()) throw new Error('托管用的 Codex 目录不可用');
|
|
48
|
+
chmodSync(home, 0o700);
|
|
49
|
+
rmSync(join(home, 'auth.json'), { force: true });
|
|
50
|
+
return home;
|
|
51
|
+
}
|
|
17
52
|
|
|
18
53
|
class AccountError extends Error {}
|
|
19
|
-
const failed = (account, error) => new AccountError(`没能换到所选的 Codex 账号${account ? ` ${account.name}` : ''}:${error?.message || '凭据不可用'}。去「资源」重新选择或登录`);
|
|
20
54
|
|
|
21
|
-
export function startAccountBridge({ source =
|
|
55
|
+
export function startAccountBridge({ env = process.env, source = sourceOf(env), strict = isRemoteMode(env), makeServer = options => new AppServer(options), input = process.stdin,
|
|
22
56
|
output = value => process.stdout.write(`${JSON.stringify(value)}\n`) } = {}) {
|
|
23
|
-
let initialized = false, initializeId, applied = null, accountId = null, problem = null, queue = Promise.resolve(), closing = false;
|
|
57
|
+
let initialized = false, initializeId, applied = null, appliedGeneration = null, accountId = null, problem = null, queue = Promise.resolve(), closing = false;
|
|
58
|
+
const home = strict ? remoteHome(env) : null;
|
|
59
|
+
const failed = (account, error) => new AccountError(strict
|
|
60
|
+
? `没能从托管机取得所选的 Codex 账号${account ? ` ${account.name}` : ''}:${error?.message || '凭据不可用'}`
|
|
61
|
+
: `没能换到所选的 Codex 账号${account ? ` ${account.name}` : ''}:${error?.message || '凭据不可用'}。去「资源」重新选择或登录`);
|
|
62
|
+
// A limit or an exhausted quota that Codex said of the account in use, told to the source without a word of what was said.
|
|
63
|
+
function reportLimit(message) {
|
|
64
|
+
if (!applied || !source.reportFault) return;
|
|
65
|
+
const told = message.error ?? (message.method === 'error' ? message.params?.error : message.method === 'turn/completed' ? message.params?.turn?.error : null);
|
|
66
|
+
if (!told || typeof told !== 'object') return;
|
|
67
|
+
const fault = faultOf({ message: told.message, data: message.error ? told.data : told });
|
|
68
|
+
if (fault?.code !== 'rate_limited' && fault?.code !== 'quota_exhausted') return;
|
|
69
|
+
void (async () => { try { await source.reportFault({ accountId: applied.id, kind: fault.code, retryAfterMs: fault.retryAfterMs, resetAt: fault.resetAt }); } catch {} })();
|
|
70
|
+
}
|
|
24
71
|
const active = new Map(), starting = new Map();
|
|
25
72
|
const schedule = work => { const next = queue.then(work); queue = next.catch(() => {}); return next; };
|
|
26
73
|
async function login(tokens) {
|
|
27
|
-
await server.request('account/login/start', { type: 'chatgptAuthTokens', ...tokens });
|
|
74
|
+
await server.request('account/login/start', { type: 'chatgptAuthTokens', ...rpcTokens(tokens) });
|
|
28
75
|
const { account, workspaceRouting } = await server.request('account/read', { refreshToken: false });
|
|
29
76
|
if (account?.type !== 'chatgpt' || workspaceRouting?.chatgptAccountId !== tokens.chatgptAccountId) throw new Error('Codex 登录后的账号与所选的不符');
|
|
30
77
|
}
|
|
@@ -32,17 +79,20 @@ export function startAccountBridge({ source = managed, makeServer = options => n
|
|
|
32
79
|
async function synchronize() {
|
|
33
80
|
if (!initialized || closing) return null;
|
|
34
81
|
let selected;
|
|
35
|
-
try {
|
|
36
|
-
|
|
82
|
+
try {
|
|
83
|
+
selected = await source.selected();
|
|
84
|
+
if (strict && !selected) throw new Error('托管机还没有选定可用的账号:请在托管机的「资源」添加或选择一个账号');
|
|
85
|
+
} catch (error) { problem = failed(null, error); throw problem; }
|
|
86
|
+
if (!selected || same(selected, applied)) { problem = null; return selected; }
|
|
37
87
|
if (active.size || starting.size) return selected;
|
|
38
88
|
try {
|
|
39
|
-
const tokens = await source.tokens(selected.id);
|
|
89
|
+
const { tokens, generation } = leased(await source.tokens(selected.id));
|
|
40
90
|
// Closed while they were read, the server is gone: a request made of it now would wait out its timeout for nobody.
|
|
41
91
|
if (closing) return selected;
|
|
42
92
|
// Once login begins a failed one means the actual account is unknown.
|
|
43
|
-
applied = null; accountId = null;
|
|
93
|
+
applied = null; accountId = null; appliedGeneration = null;
|
|
44
94
|
await login(tokens);
|
|
45
|
-
applied = selected; accountId = tokens.chatgptAccountId; problem = null;
|
|
95
|
+
applied = selected; accountId = tokens.chatgptAccountId; appliedGeneration = generation ?? null; problem = null;
|
|
46
96
|
return selected;
|
|
47
97
|
} catch (error) { problem = failed(selected, error); throw problem; }
|
|
48
98
|
}
|
|
@@ -59,10 +109,11 @@ export function startAccountBridge({ source = managed, makeServer = options => n
|
|
|
59
109
|
void (async () => {
|
|
60
110
|
try {
|
|
61
111
|
if (!account || (message.params?.previousAccountId && message.params.previousAccountId !== accountId)) throw new Error('当前没有 Coda 交给 Codex 的账号');
|
|
62
|
-
const tokens = await source.tokens(account.id, { refresh: true });
|
|
112
|
+
const { tokens, generation } = leased(await source.tokens(account.id, { refresh: true, ...(appliedGeneration ? { rejectedGeneration: appliedGeneration } : {}) }));
|
|
63
113
|
if (closing) return;
|
|
64
114
|
if (tokens.chatgptAccountId !== accountId) throw new Error('账号来源给的凭据属于另一个账号');
|
|
65
|
-
|
|
115
|
+
if (applied === account) appliedGeneration = generation ?? null;
|
|
116
|
+
server.send({ id: message.id, result: rpcTokens(tokens) });
|
|
66
117
|
} catch (error) { if (!closing) server.send({ id: message.id, error: { code: -32000, message: failed(account, error).message } }); }
|
|
67
118
|
})(); return;
|
|
68
119
|
}
|
|
@@ -82,8 +133,9 @@ export function startAccountBridge({ source = managed, makeServer = options => n
|
|
|
82
133
|
if (active.get(threadId) === turn.id) active.delete(threadId);
|
|
83
134
|
void schedule(synchronize).catch(() => {});
|
|
84
135
|
}
|
|
136
|
+
reportLimit(message);
|
|
85
137
|
output(message);
|
|
86
|
-
} });
|
|
138
|
+
}, ...(home ? { env: accountEnv(home, env), cwd: home, args: fileCredentials } : {}) });
|
|
87
139
|
const reader = readLines(input);
|
|
88
140
|
reader.on('line', line => {
|
|
89
141
|
let message; try { message = JSON.parse(line); } catch { return; }
|
|
@@ -95,18 +147,19 @@ export function startAccountBridge({ source = managed, makeServer = options => n
|
|
|
95
147
|
message.params.capabilities = { ...message.params.capabilities, experimentalApi: true };
|
|
96
148
|
}
|
|
97
149
|
if (message.method === 'initialized') return;
|
|
98
|
-
// Account reads during ACP startup and all native thread and turn entry points
|
|
99
|
-
// one that could not be taken never sends on the one before.
|
|
100
|
-
if (['account/read', 'thread/start', 'thread/resume', 'thread/fork',
|
|
150
|
+
// Account reads during ACP startup and all native thread and turn entry points (a review, a compaction and a goal too)
|
|
151
|
+
// take the chosen account; one that could not be taken never sends on the one before.
|
|
152
|
+
if (['account/read', 'thread/start', 'thread/resume', 'thread/fork', ...TURNS].includes(message.method)) {
|
|
101
153
|
const selected = await synchronize();
|
|
102
154
|
if (closing) return;
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
}
|
|
155
|
+
// Nothing reaches Codex before the centre's account is signed in: its own login is not to answer.
|
|
156
|
+
if (strict && (problem || !applied)) throw problem ?? failed(selected);
|
|
157
|
+
if (TURNS.includes(message.method) && selected && (problem || !applied || (!same(applied, selected) && !active.size && !starting.size))) throw problem ?? failed(selected);
|
|
158
|
+
if (message.method === 'turn/start') starting.set(message.id, { threadId: message.params.threadId, completed: new Set() });
|
|
107
159
|
}
|
|
108
160
|
// ACP's own login and logout would overwrite what the source gave, or this machine's login under it.
|
|
109
|
-
if (applied && ['account/login/start', 'account/logout'].includes(message.method))
|
|
161
|
+
if ((applied || strict) && ['account/login/start', 'account/logout'].includes(message.method))
|
|
162
|
+
throw new AccountError(strict ? 'Coda 已启用 Codex 空间集中托管,登录、退出和切换账号都在托管机的「资源」里管理' : 'Coda 正在为 Codex 选用账号,在「资源」里切换');
|
|
110
163
|
server.send(message);
|
|
111
164
|
}).catch(error => {
|
|
112
165
|
if (message.id != null) output({ id: message.id, error: { code: -32000, message: error instanceof AccountError ? error.message : failed(null, error).message } });
|
package/agent/entry.mjs
CHANGED
|
@@ -12,7 +12,7 @@ import { createHash } from 'node:crypto';
|
|
|
12
12
|
import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
13
13
|
import { join } from 'node:path';
|
|
14
14
|
import { fileURLToPath } from 'node:url';
|
|
15
|
-
import {
|
|
15
|
+
import { isRemoteMode, usesAccountBridge } from '../lib/config.mjs';
|
|
16
16
|
import { readLines } from './lines.mjs';
|
|
17
17
|
import { orderedCodexTitles } from './titles.mjs';
|
|
18
18
|
import { continuedCodexSubagents } from './subagents.mjs';
|
|
@@ -39,6 +39,11 @@ import { CodexUnrecognized, listenUnrecognized, reportedCodexUnrecognized } from
|
|
|
39
39
|
const env = process.env;
|
|
40
40
|
// Coda owns the permission boundary. An explicit launch mode or later ACP selection still wins.
|
|
41
41
|
env.INITIAL_AGENT_MODE ??= 'agent-full-access';
|
|
42
|
+
// A consumer of the space's hosting runs no Codex of its own: one given by `CODEX_PATH` would go round the centre's account.
|
|
43
|
+
if (isRemoteMode(env) && env.CODEX_PATH) {
|
|
44
|
+
process.stderr.write('远端集中托管模式不支持自定义 CODEX_PATH,请移除该环境变量后重试\n');
|
|
45
|
+
process.exit(1);
|
|
46
|
+
}
|
|
42
47
|
// The Codex this session runs, as the handshake's `agentInfo` names it (Coda's protocol「Agent 版本」): the connection's own
|
|
43
48
|
// program when it sets one, else the plugin's locked @openai/codex.
|
|
44
49
|
const own = env.CODEX_PATH;
|
|
@@ -46,10 +51,10 @@ function codexVersion() {
|
|
|
46
51
|
if (own) return /\d+\.\d+\.\d+[\w.+-]*/.exec(spawnSync(own, ['--version'], { encoding: 'utf8', timeout: 3000 }).stdout ?? '')?.[0] ?? null;
|
|
47
52
|
try { return JSON.parse(readFileSync(createRequire(import.meta.url).resolve('@openai/codex/package.json'), 'utf8')).version; } catch { return null; }
|
|
48
53
|
}
|
|
49
|
-
// With「多账号」on (the setting `codex.multipleAccounts`) the managed account chosen is the one (accounts.mjs): codex-acp then
|
|
54
|
+
// With「多账号」on (the setting `codex.multipleAccounts`) or the accounts hosted by the space (`codex.accountHosting`, host or remote) the managed account chosen is the one (accounts.mjs): codex-acp then
|
|
50
55
|
// runs the account bridge as its Codex, through a small program written into this plugin's state, named for what it runs. A Codex
|
|
51
56
|
// program of the connection's own (`CODEX_PATH`) keeps its own login.
|
|
52
|
-
if (!env.CODEX_PATH &&
|
|
57
|
+
if (!env.CODEX_PATH && usesAccountBridge(env) && env.CODA_PLUGIN_STATE) {
|
|
53
58
|
const quote = value => `'${value.replaceAll("'", "'\\''")}'`;
|
|
54
59
|
const program = `#!/bin/sh\nexec ${quote(process.execPath)} ${quote(fileURLToPath(new URL('./accounts.mjs', import.meta.url)))} "$@"\n`;
|
|
55
60
|
const shim = join(env.CODA_PLUGIN_STATE, `account-bridge-${createHash('sha256').update(program).digest('hex').slice(0, 12)}`);
|
package/agent/errors.mjs
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { providerQuota, quotaReset, resetText, suggestedWait } from '../lib/errors.mjs';
|
|
2
|
+
|
|
1
3
|
// codex-acp puts model-service errors in data.message, SDK-wrapped exceptions in data.details, and some configuration
|
|
2
4
|
// errors in a string data payload. Explain them in ACP's standard message so clients need not know those private shapes.
|
|
3
5
|
export function explainCodexError(message) {
|
|
@@ -15,33 +17,6 @@ export function explainCodexError(message) {
|
|
|
15
17
|
return explained === error.message ? message : { ...message, error: { ...error, message: explained } };
|
|
16
18
|
}
|
|
17
19
|
|
|
18
|
-
// Only absolute reset times from the failed request are evidence. The account-wide rateLimits/read can contain several
|
|
19
|
-
// model pools, without identifying which one blocked this turn; do not schedule a retry from an unrelated window.
|
|
20
|
-
const resetText = /\b(try again at |resets (?:at )?)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z)\b/gi;
|
|
21
|
-
function quotaReset(error, data) {
|
|
22
|
-
for (const text of [data.additionalDetails, data.message, data.details, error.message]) {
|
|
23
|
-
if (typeof text !== 'string') continue;
|
|
24
|
-
let body; try { body = JSON.parse(text); } catch {}
|
|
25
|
-
// An HTTP failure quotes the response body inside its own sentence: `unexpected status 429 Too Many Requests: {…}, url: …`.
|
|
26
|
-
const seconds = body ? body.error?.resets_at : Number(text.match(/"resets_at"\s*:\s*(\d{1,12})\b/)?.[1]);
|
|
27
|
-
if (Number.isSafeInteger(seconds) && seconds > 0 && seconds <= 253402300799)
|
|
28
|
-
return new Date(seconds * 1000).toISOString();
|
|
29
|
-
const time = [...text.matchAll(resetText)][0]?.[2];
|
|
30
|
-
if (time && Number.isFinite(Date.parse(time)) && new Date(time).toISOString().slice(0, 19) === time.slice(0, 19))
|
|
31
|
-
return new Date(time).toISOString();
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
// A 429 that Codex reports as a plain HTTP failure carries the provider's response body in its message. Only the provider's
|
|
36
|
-
// own quota codes and wording establish exhaustion; any other 429 is a rate limit, whose "try again in 1.5s" is the wait.
|
|
37
|
-
const providerQuota = /\b(?:insufficient_quota|quota_exceeded|usage_limit_reached)\b|exceeded your current quota|hit your usage limit/i;
|
|
38
|
-
function suggestedWait(text) {
|
|
39
|
-
const spoken = text.match(/try again in ((?:\d+(?:\.\d+)?(?:ms|h|m|s))+)/i)?.[1];
|
|
40
|
-
if (!spoken) return;
|
|
41
|
-
const unit = { h: 3_600_000, m: 60_000, s: 1000, ms: 1 };
|
|
42
|
-
return Math.round([...spoken.matchAll(/(\d+(?:\.\d+)?)(ms|h|m|s)/g)].reduce((sum, [, n, u]) => sum + n * unit[u], 0));
|
|
43
|
-
}
|
|
44
|
-
|
|
45
20
|
// The ChatGPT login gone (docs/agent-protocol.md「需要重新登录」): Codex's own words when refreshing the access token fails for good
|
|
46
21
|
// (its refresh token expired, was already used or revoked, or the account was logged out or switched). Its `unauthorized` kind and a
|
|
47
22
|
// bare 401 or 403 also cover a wrong API key or a missing permission, which logging in again does not mend, so they stay unmarked.
|
package/lib/config.mjs
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// The account-hosting settings of the plugin, as Coda hands them to its processes (`CODA_PLUGIN_SETTINGS`, JSON):
|
|
2
|
+
// `codex.accountHosting` ('local' | 'host' | 'remote'), `codex.accountHost` and `codex.multipleAccounts`.
|
|
3
|
+
function settings(env) {
|
|
4
|
+
try {
|
|
5
|
+
const value = JSON.parse(env.CODA_PLUGIN_SETTINGS || '{}');
|
|
6
|
+
return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
|
|
7
|
+
} catch { return {}; }
|
|
8
|
+
}
|
|
9
|
+
export const hostingMode = (env = process.env) => {
|
|
10
|
+
const mode = settings(env)['codex.accountHosting'];
|
|
11
|
+
return mode === 'host' || mode === 'remote' ? mode : 'local';
|
|
12
|
+
};
|
|
13
|
+
export const accountHost = (env = process.env) => {
|
|
14
|
+
const host = settings(env)['codex.accountHost'];
|
|
15
|
+
return typeof host === 'string' ? host.trim() : '';
|
|
16
|
+
};
|
|
17
|
+
export const multipleAccounts = (env = process.env) => settings(env)['codex.multipleAccounts'] === true;
|
|
18
|
+
// What a consumer of the space's hosting says to a login or an action meant for this machine's own accounts.
|
|
19
|
+
export const remoteRefusal = '当前机器已启用 Codex 空间集中托管,请在托管机管理或切换账号';
|
|
20
|
+
export const isHostMode = (env = process.env) => hostingMode(env) === 'host';
|
|
21
|
+
export const isRemoteMode = (env = process.env) => hostingMode(env) === 'remote';
|
|
22
|
+
// Whether the managed accounts are kept on this machine, and whether sessions take their tokens from the account bridge.
|
|
23
|
+
export const usesManagedStore = (env = process.env) => isHostMode(env) || (hostingMode(env) === 'local' && multipleAccounts(env));
|
|
24
|
+
export const usesAccountBridge = (env = process.env) => hostingMode(env) !== 'local' || multipleAccounts(env);
|
package/lib/errors.mjs
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// The four kinds of failure of a managed account, each with a `code` that survives serialization between processes and
|
|
2
|
+
// machines. Only `SignInAgain` is cured by signing in again; the others say the login is fine but the account or Codex is
|
|
3
|
+
// not available right now. What is said of a failure is fixed by its kind: what the service wrote is only read to tell the kind,
|
|
4
|
+
// and is never kept in an error, so that nothing in it (a token, say) can travel on.
|
|
5
|
+
// Only absolute reset times from the failed request are evidence. The account-wide rateLimits/read can contain several
|
|
6
|
+
// model pools, without identifying which one blocked this turn; do not schedule a retry from an unrelated window.
|
|
7
|
+
export const resetText = /\b(try again at |resets (?:at )?)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z)\b/gi;
|
|
8
|
+
export function quotaReset(error, data) {
|
|
9
|
+
for (const text of [data.additionalDetails, data.message, data.details, error.message]) {
|
|
10
|
+
if (typeof text !== 'string') continue;
|
|
11
|
+
let body; try { body = JSON.parse(text); } catch {}
|
|
12
|
+
// An HTTP failure quotes the response body inside its own sentence: `unexpected status 429 Too Many Requests: {…}, url: …`.
|
|
13
|
+
const seconds = body ? body.error?.resets_at : Number(text.match(/"resets_at"\s*:\s*(\d{1,12})\b/)?.[1]);
|
|
14
|
+
if (Number.isSafeInteger(seconds) && seconds > 0 && seconds <= 253402300799)
|
|
15
|
+
return new Date(seconds * 1000).toISOString();
|
|
16
|
+
const time = [...text.matchAll(resetText)][0]?.[2];
|
|
17
|
+
if (time && Number.isFinite(Date.parse(time)) && new Date(time).toISOString().slice(0, 19) === time.slice(0, 19))
|
|
18
|
+
return new Date(time).toISOString();
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// A 429 that Codex reports as a plain HTTP failure carries the provider's response body in its message. Only the provider's
|
|
23
|
+
// own quota codes and wording establish exhaustion; any other 429 is a rate limit, whose "try again in 1.5s" is the wait.
|
|
24
|
+
export const providerQuota = /\b(?:insufficient_quota|quota_exceeded|usage_limit_reached)\b|exceeded your current quota|hit your usage limit/i;
|
|
25
|
+
export function suggestedWait(text) {
|
|
26
|
+
const spoken = text.match(/try again in ((?:\d+(?:\.\d+)?(?:ms|h|m|s))+)/i)?.[1];
|
|
27
|
+
if (!spoken) return;
|
|
28
|
+
const unit = { h: 3_600_000, m: 60_000, s: 1000, ms: 1 };
|
|
29
|
+
return Math.round([...spoken.matchAll(/(\d+(?:\.\d+)?)(ms|h|m|s)/g)].reduce((sum, [, n, u]) => sum + n * unit[u], 0));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const ISO = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/;
|
|
33
|
+
export class Fault extends Error {
|
|
34
|
+
constructor(message, { retryAfterMs, resetAt } = {}) {
|
|
35
|
+
super(message ?? new.target.text);
|
|
36
|
+
if (Number.isFinite(retryAfterMs) && retryAfterMs > 0) this.retryAfterMs = Math.round(retryAfterMs);
|
|
37
|
+
if (typeof resetAt === 'string' && ISO.test(resetAt) && Number.isFinite(Date.parse(resetAt))) this.resetAt = new Date(resetAt).toISOString();
|
|
38
|
+
}
|
|
39
|
+
toJSON() { return { code: this.code, message: this.constructor.text, retryAfterMs: this.retryAfterMs, resetAt: this.resetAt }; }
|
|
40
|
+
}
|
|
41
|
+
// A failure that only signing in again cures, of a managed account: its login missing, expired, unreadable or another's.
|
|
42
|
+
export class SignInAgain extends Fault { static text = '账号登录已失效,请在「资源」重新登录该账号'; code = 'sign_in_again'; }
|
|
43
|
+
// A momentary rate limit (429).
|
|
44
|
+
export class RateLimitError extends Fault { static text = '该账号暂时被限流,请稍后再试'; code = 'rate_limited'; }
|
|
45
|
+
// A long window's quota used up; `resetAt` is when it comes back, an ISO time.
|
|
46
|
+
export class QuotaExhaustedError extends Fault { static text = '该账号的额度已用完'; code = 'quota_exhausted'; }
|
|
47
|
+
// Codex or the network temporarily failing: a timeout, an exit, a connection error, a 5xx, or anything not recognized.
|
|
48
|
+
export class TransientError extends Fault { static text = 'Codex 暂时不可用,请稍后再试'; code = 'transient'; }
|
|
49
|
+
|
|
50
|
+
const kinds = { sign_in_again: SignInAgain, rate_limited: RateLimitError, quota_exhausted: QuotaExhaustedError, transient: TransientError };
|
|
51
|
+
export const faultFromJSON = ({ code, retryAfterMs, resetAt } = {}) => kinds[code] ? new kinds[code](undefined, { retryAfterMs, resetAt }) : null;
|
|
52
|
+
|
|
53
|
+
// What a failure said, whole: its message, and what a reply of Codex's app-server kept of it (scripts/app-server.mjs).
|
|
54
|
+
const data = error => error?.data && typeof error.data === 'object' && !Array.isArray(error.data) ? error.data : {};
|
|
55
|
+
const said = error => [error?.message, error?.raw, data(error).message, data(error).details, data(error).additionalDetails, error?.data]
|
|
56
|
+
.filter(text => typeof text === 'string').join('\n');
|
|
57
|
+
|
|
58
|
+
// The HTTP status of a failure, as it is given as such: on the error, in its data, or in the data's Codex error info.
|
|
59
|
+
const statusOf = error => {
|
|
60
|
+
const info = data(error).codexErrorInfo, nested = info && typeof info === 'object' ? info.httpStatusCode ?? Object.values(info)[0]?.httpStatusCode : undefined;
|
|
61
|
+
return [error?.status, data(error).httpStatusCode, nested].find(Number.isInteger);
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
// Whether what Codex said is that its login is gone, expired or revoked, or its file unreadable, or a managed account's login is
|
|
65
|
+
// no good: what signing in again cures. Any other failure of a reading (the network, a timeout, a server's error, Codex itself,
|
|
66
|
+
// a store that cannot be read) is not, and is left to fail the command. An HTTP status given as such decides; only without one are the
|
|
67
|
+
// words read, and a 401 in them only as a status ("Requested 401 tokens" is none).
|
|
68
|
+
export const needsSignIn = error => {
|
|
69
|
+
if (error instanceof SignInAgain) return true;
|
|
70
|
+
const status = statusOf(error);
|
|
71
|
+
if (status !== undefined) return status === 401;
|
|
72
|
+
return /authentication required|not (logged|signed) in|unauthori[sz]ed|\b(?:status(?: code)?:? ?|http ?)401\b|\b401\s+unauthori[sz]ed\b|refresh_token_(reused|expired|invalidated)|token[^.]*\b(expired|invalid|revoked)\b|auth\.json|failed to (load|read) auth/i.test(said(error));
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
const exhausted = /usage limit|quota exceeded/i;
|
|
76
|
+
const limited = /\b429\b|rate.?limit|too many requests/i;
|
|
77
|
+
const transient = /Codex 没有答复|Codex 提前退出了|\b(?:status(?: code)?:? ?|http ?)5\d\d\b|\b5\d\d (?:[A-Z]|error)|service unavailable|bad gateway|gateway time-?out|internal server error|overloaded|\b(ETIMEDOUT|ECONNRESET|ECONNREFUSED|ENOTFOUND|EAI_AGAIN|EPIPE)\b|fetch failed|network|timed? ?out|socket hang up/i;
|
|
78
|
+
|
|
79
|
+
// What kind of failure `error` is, as one of the four classes; null when it is none of them. An HTTP status given as such decides
|
|
80
|
+
// first (a 429 is a quota only in the quota's words), and any other status is none of the four, whatever its words; without one,
|
|
81
|
+
// a sign-in failure comes first, then the quota's words before the 429 that carries them, then a temporary failure.
|
|
82
|
+
export function faultOf(error) {
|
|
83
|
+
if (error instanceof Fault) return error;
|
|
84
|
+
const text = said(error), status = statusOf(error);
|
|
85
|
+
const quota = data(error).codexErrorInfo === 'usageLimitExceeded' || providerQuota.test(text) || exhausted.test(text);
|
|
86
|
+
const exhaustedNow = () => new QuotaExhaustedError(undefined, { resetAt: quotaReset({ message: text }, data(error)) });
|
|
87
|
+
const limitedNow = () => new RateLimitError(undefined, { retryAfterMs: suggestedWait(text) });
|
|
88
|
+
if (status === 401) return new SignInAgain();
|
|
89
|
+
if (status === 429) return quota ? exhaustedNow() : limitedNow();
|
|
90
|
+
if (status >= 500 && status <= 599) return new TransientError();
|
|
91
|
+
if (status !== undefined) return data(error).codexErrorInfo === 'usageLimitExceeded' ? exhaustedNow() : null;
|
|
92
|
+
if (needsSignIn(error)) return new SignInAgain();
|
|
93
|
+
if (quota) return exhaustedNow();
|
|
94
|
+
if (limited.test(text)) return limitedNow();
|
|
95
|
+
if (transient.test(text)) return new TransientError();
|
|
96
|
+
return null;
|
|
97
|
+
}
|
package/lib/hub.mjs
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
// The hosting centre (`codex.accountHosting` = host): this machine keeps the managed accounts and gives the rest of the space, and
|
|
2
|
+
// its own sessions, short-lived tokens of the chosen one. One record of `codex/account-pool@1` says only whether the centre is
|
|
3
|
+
// ready; the tokens leave through the stream `tokens` alone, one request and one answer, never through a call, a query or a record.
|
|
4
|
+
// The pool (lib/pool.mjs) serves every asker: a renewal asked for on a rejected generation is made once, and a cooldown reported
|
|
5
|
+
// from one machine holds for all. What reads (`chosen`, `list`, `leaseTokens`, `withManagedAccount`) is handed in for the tests.
|
|
6
|
+
import * as manager from '../scripts/manager.mjs';
|
|
7
|
+
import { AccountPool } from './pool.mjs';
|
|
8
|
+
import { Fault, TransientError } from './errors.mjs';
|
|
9
|
+
import { KEY, KIND, MAX_BODY, NoAccount, PLUGIN, asFault, said, statusOf } from './wire.mjs';
|
|
10
|
+
|
|
11
|
+
const NOT_HOSTED = '这台机器未开启 Codex 空间集中托管';
|
|
12
|
+
const HEADERS = { 'content-type': 'application/json', 'cache-control': 'no-store' };
|
|
13
|
+
const reply = (status, body) => new Response(JSON.stringify(body), { status, headers: HEADERS });
|
|
14
|
+
const refuse = (status, code, message) => reply(status, { error: { code, message } });
|
|
15
|
+
|
|
16
|
+
export class CodexHub {
|
|
17
|
+
constructor(coda, { at, chosen = manager.chosen, list = manager.list, peekAccounts = manager.peekAccounts, selection = manager.selection, leaseTokens = manager.leaseTokens,
|
|
18
|
+
withManagedAccount = manager.withManagedAccount, ...poolOptions } = {}) {
|
|
19
|
+
this.coda = coda;
|
|
20
|
+
this.at = at ?? manager.paths({ ...process.env, CODA_PLUGIN_STATE: coda.plugin.state });
|
|
21
|
+
this.chosen = chosen; this.list = list; this.peekAccounts = peekAccounts; this.selection = selection;
|
|
22
|
+
this.pool = new AccountPool({ at: this.at, leaseTokens,
|
|
23
|
+
readQuota: (account, here) => withManagedAccount(account, server => server.request('account/rateLimits/read'), here), ...poolOptions });
|
|
24
|
+
this.published = null; this.recorded = false; this.running = false; this.syncing = Promise.resolve();
|
|
25
|
+
}
|
|
26
|
+
async start() {
|
|
27
|
+
const { coda } = this;
|
|
28
|
+
// From here a record of ours may be there (an earlier run's, or the one about to be written), until it is deleted.
|
|
29
|
+
this.running = true; this.recorded = true;
|
|
30
|
+
await this.syncStatus();
|
|
31
|
+
}
|
|
32
|
+
// No account chosen (or the chosen one gone) is `NoAccount`; a store that cannot be read is not that, and says nothing of itself.
|
|
33
|
+
async selected() {
|
|
34
|
+
try { return await this.chosen(this.at); }
|
|
35
|
+
catch (error) { throw error instanceof Fault ? error : error instanceof manager.NoSelection ? new NoAccount() : new TransientError(); }
|
|
36
|
+
}
|
|
37
|
+
// Only what Codex takes leaves, whatever the manager's lease held.
|
|
38
|
+
async lease(account, options) {
|
|
39
|
+
const { tokens, generation, expiresAt } = await this.pool.lease(account, options);
|
|
40
|
+
return { tokens: manager.rpcTokens(tokens), generation, expiresAt };
|
|
41
|
+
}
|
|
42
|
+
quota(account, options) { return this.pool.quota(account, options); }
|
|
43
|
+
async invalidateQuota(account) { this.pool.invalidateQuota(account); await this.syncStatus(); }
|
|
44
|
+
async forget(account) { this.pool.forget(account); await this.syncStatus(); }
|
|
45
|
+
// What the pool refuses (an account or a kind not named, a time out of range) is said as it says it.
|
|
46
|
+
reportFault(info) {
|
|
47
|
+
try { return this.pool.reportFault(info); } catch (error) { throw said(error.message, 'invalid_input'); }
|
|
48
|
+
}
|
|
49
|
+
// What the record says: whether the accounts can be read, how many there are, whether one is chosen. No email, no name, no token.
|
|
50
|
+
// Reading them may import this machine's own Codex login (the manager's `list`): only starting and a told change do that.
|
|
51
|
+
// A store that cannot be read, the accounts or the selection, is not ready.
|
|
52
|
+
async summary() {
|
|
53
|
+
let accounts, id;
|
|
54
|
+
try { accounts = await this.list(this.at); id = this.selection(this.at); } catch { return { ready: false, accountCount: 0, hasSelection: false }; }
|
|
55
|
+
return { ready: true, accountCount: accounts.length, hasSelection: accounts.some(account => account.identity === id) };
|
|
56
|
+
}
|
|
57
|
+
// Writes the record when what it says changed.
|
|
58
|
+
async #publish(status) {
|
|
59
|
+
const text = JSON.stringify(status);
|
|
60
|
+
if (!this.running || text === this.published) return;
|
|
61
|
+
await this.coda.replace(KIND, [{ key: KEY, spec: {}, status }]);
|
|
62
|
+
this.published = text;
|
|
63
|
+
}
|
|
64
|
+
// One at a time, each reading the accounts when its turn comes: a slow write of an earlier one never lands over a later one's.
|
|
65
|
+
syncStatus() {
|
|
66
|
+
const done = this.syncing.then(async () => {
|
|
67
|
+
const status = await this.summary();
|
|
68
|
+
await this.#publish(status);
|
|
69
|
+
return status;
|
|
70
|
+
});
|
|
71
|
+
this.syncing = done.catch(() => {});
|
|
72
|
+
return done;
|
|
73
|
+
}
|
|
74
|
+
// A query only reads: what is already stored here (nothing is imported or written, the record is left as it is) and the pool's
|
|
75
|
+
// memory. Of the chosen account only its ID is said, never the name, which may be an email.
|
|
76
|
+
status() {
|
|
77
|
+
let accounts, id;
|
|
78
|
+
try { accounts = this.peekAccounts(this.at); id = this.selection(this.at); }
|
|
79
|
+
catch { return { ready: false, accountCount: 0, hasSelection: false, selected: null, pool: this.pool.statusSnapshot() }; }
|
|
80
|
+
const selected = accounts.some(account => account.identity === id) ? { id } : null;
|
|
81
|
+
return { ready: true, accountCount: accounts.length, hasSelection: selected !== null, selected, pool: this.pool.statusSnapshot() };
|
|
82
|
+
}
|
|
83
|
+
// The whole body, up to the limit: null when it is longer (what is read of it is let go).
|
|
84
|
+
async #body(request) {
|
|
85
|
+
const chunks = [];
|
|
86
|
+
let size = 0;
|
|
87
|
+
for await (const chunk of request.body ?? []) {
|
|
88
|
+
size += chunk.length;
|
|
89
|
+
if (size > MAX_BODY) return null;
|
|
90
|
+
chunks.push(chunk);
|
|
91
|
+
}
|
|
92
|
+
return Buffer.concat(chunks).toString('utf8');
|
|
93
|
+
}
|
|
94
|
+
// One request, one answer. The body is read whole before anything is said (a stream is one way at a time).
|
|
95
|
+
async tokens(request) {
|
|
96
|
+
const text = await this.#body(request);
|
|
97
|
+
// The request body may take a while: by now this machine may no longer be the centre.
|
|
98
|
+
if (!this.running) throw this.coda.error('not_found', NOT_HOSTED, { effects: 'none' });
|
|
99
|
+
if (text === null) return refuse(413, 'too_large', `请求超过 ${MAX_BODY} 字节`);
|
|
100
|
+
let input;
|
|
101
|
+
try { input = JSON.parse(text); } catch { return refuse(400, 'invalid_input', '请求不是 JSON'); }
|
|
102
|
+
try {
|
|
103
|
+
if (input?.op === 'selected') return reply(200, { selected: await this.selected() });
|
|
104
|
+
const { account, refresh, rejectedGeneration } = input ?? {};
|
|
105
|
+
if (input?.op !== 'tokens' || typeof account !== 'string' || !account || account.length > 256
|
|
106
|
+
|| (rejectedGeneration !== undefined && (typeof rejectedGeneration !== 'string' || rejectedGeneration.length > 64))) return refuse(400, 'invalid_input', '请求的 op 或参数不对');
|
|
107
|
+
return reply(200, await this.lease(account, { refresh: Boolean(refresh), rejectedGeneration }));
|
|
108
|
+
} catch (error) {
|
|
109
|
+
const fault = asFault(error);
|
|
110
|
+
return reply(statusOf(fault), { error: fault.toJSON() });
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
// Not serving any more as soon as it is told to stop; the record is withdrawn after what is under way ends (it publishes nothing
|
|
114
|
+
// now), so that no write comes after it. A record that could not be withdrawn is kept for the next try.
|
|
115
|
+
async stop() {
|
|
116
|
+
this.running = false;
|
|
117
|
+
await this.syncing;
|
|
118
|
+
if (this.recorded) {
|
|
119
|
+
await this.coda.delete({ kind: KIND, key: KEY });
|
|
120
|
+
this.recorded = false; this.published = null;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// The handlers and the stream of `codex/account-pool@1`, which the manifest declares whatever the mode: they are registered once,
|
|
126
|
+
// for as long as the module lives, and answer for the centre that `current()` gives while it runs. Any other mode, or a centre
|
|
127
|
+
// not started or already stopping, says so; only this plugin's own other half is answered in either case: the Codex plugin of a
|
|
128
|
+
// backend of the space (a machine named, no client, no friend). Coda names no caller of a `safe` query (`status`), having checked
|
|
129
|
+
// its permission already: one that names none is let through there, and only there.
|
|
130
|
+
export async function serveAccountPool(coda, current) {
|
|
131
|
+
const centre = (caller, { safe = false } = {}) => {
|
|
132
|
+
const own = caller?.plugin === PLUGIN && typeof caller.machine === 'string' && caller.machine.length > 0 && !caller.friend && caller.role !== 'client';
|
|
133
|
+
if (!own && !(safe && caller === undefined)) throw coda.error('forbidden', '托管中心只收 Codex 插件自己的来访', { effects: 'none' });
|
|
134
|
+
const hub = current();
|
|
135
|
+
if (!hub?.running) throw coda.error('not_found', NOT_HOSTED, { effects: 'none' });
|
|
136
|
+
return hub;
|
|
137
|
+
};
|
|
138
|
+
// Every one is withdrawn and waited for, whatever the others did; the first failure is thrown after all.
|
|
139
|
+
const withdraw = async list => {
|
|
140
|
+
const failed = [];
|
|
141
|
+
for (const one of list) try { await one.dispose(); } catch (error) { failed.push(error); }
|
|
142
|
+
if (failed.length) throw failed[0];
|
|
143
|
+
};
|
|
144
|
+
const served = [];
|
|
145
|
+
try {
|
|
146
|
+
served.push(await coda.stream(KIND, 'tokens', (request, ctx) => centre(ctx?.caller).tokens(request)));
|
|
147
|
+
served.push(coda.handle(KIND, 'status', (input, ctx) => centre(ctx?.caller, { safe: true }).status()));
|
|
148
|
+
served.push(coda.handle(KIND, 'report-fault', (input, ctx) => centre(ctx?.caller).reportFault(input)));
|
|
149
|
+
} catch (error) { await withdraw(served).catch(() => {}); throw error; }
|
|
150
|
+
return { dispose: () => withdraw(served) };
|
|
151
|
+
}
|