@coda-console/codex 1.14.4 → 2.0.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 CHANGED
@@ -1,48 +1,44 @@
1
1
  # Codex
2
2
 
3
- Codex Agent:Codex 插件提供的入口运行 codex-acp,报告子 Agent、后台命令与命令的自动审核。额度与登录由账号来源插件接管;未接入账号来源时,资源页的「Codex」显示 Codex 自己的登录与额度。
3
+ Codex Agent:Codex 插件提供的入口运行 codex-acp,报告子 Agent、后台命令与命令的自动审核。资源页的「Codex」显示 Codex 自己的登录与额度;打开设置「多账号」(`codex.multipleAccounts`,默认关)后改为插件管理的多个账号(见下)。
4
4
 
5
5
  实时的上下文压缩(自动或手动)作为 Coda 的「整理上下文」记录显示:开始报 `compaction_update` in_progress、完成报 completed,Coda 据此知道会话压缩过;回合失败或中断、压缩未完成时补报 failed,不再出「Compact conversation」工具卡。恢复会话时,历史里的压缩仍显示为「Compact conversation」工具卡,不上报,免得 Coda 把它当成新的压缩。
6
6
 
7
7
  ## 资源页:Codex 的登录与额度
8
8
 
9
- 资源页上的资源类型「Codex」:这台机器上 Codex 自己的登录(本机登录)和它的额度。接了账号来源(见下)时它输出为空,「Codex」里是账号插件管理的账号。
9
+ 资源页上的资源类型「Codex」:这台机器上 Codex 自己的登录(本机登录)和它的额度。打开「多账号」时它输出为空,「Codex」里是多账号管理的账号(类型 `accounts`,见下)。
10
10
 
11
- - **来源**:读取命令以插件依赖的 Codex CLI(`@openai/codex`,codex-acp 也用它)临时启动 `app-server`,问完即关;
11
+ - **来源**:记录命令 `scripts/resource.mjs` 以插件依赖的 Codex CLI(`@openai/codex`,codex-acp 也用它)临时启动 `app-server`,问完即关;
12
12
  `CODEX_HOME` 沿用后端的环境(不设就是 `~/.codex`),与 Codex 会话是同一个登录。账号问 `account/read`,额度问 `account/rateLimits/read`,
13
13
  令牌由 Codex 自己读取和续期,不经过脚本,也不进输出。凭据只在系统钥匙串里的登录同样认得。
14
14
  - **显示**:没有登录时输出为空,「Codex」出现在「添加资源」里。用 ChatGPT 账号登录时一个资源,名字是账号邮箱(套餐不显示):
15
15
  每个额度窗口一个读数(5 小时、7 天,时刻是重置时间;Codex 给出多组额度时读数名前加额度名,不知道比例的写「—」),
16
16
  然后「完全重置 剩余 N 次」(次数以 Codex 给的汇总为准),时刻是最早到期的那一次(没有到期时间的不写),合计至多 8 个读数。
17
- 用 API Key 等别的方式登录时那一行写「不是 ChatGPT 登录,没有额度」。读不到额度时那一行写「暂时无法获取额度」和 Codex 说的原因,「···」里的「重新登录」仍在。
17
+ 用 API Key 等别的方式登录时那一行写「不是 ChatGPT 登录,没有额度」。Codex 说登录没有了、过期或无效(认证文件读不了)时那一行写「登录已失效,请重新登录」和 Codex 说的原因,「···」里的「重新登录」仍在;别的读不到(网络、超时、服务端出错、Codex 没有给出任何额度窗口或重置次数)命令以非零退出,原因写在标准错误的最后一行,Coda 保留上一份记录,资源页显示「更新失败:原因」。
18
18
  - **身份**:额度是一个人在一个工作区的,身份是邮箱与工作区账号 ID 一起的哈希 `codex:<哈希>`;Codex 没给出邮箱或工作区时不带。
19
19
  - **完全重置**:有可用的那一次时,行尾有「使用完全重置」,总是用最早到期的那一次;确认框写账号与这一次的到期时间。
20
- 动作只兑换按钮指定的那一次(不让上游自己挑),没重置成(当前额度无需重置、这次已被使用或已不可用)时那一行写明。
21
- - **登录**:`signIn` 运行同一个 CLI 的 `codex login --device-auth`,设备码登录要在 ChatGPT 账号安全设置或工作区权限里启用
22
- ([OpenAI 登录说明](https://learn.chatgpt.com/docs/auth))。重新登录替换 `CODEX_HOME` 当前的登录;多账号管理器的活动账号若也用这个目录,同样被替换,
23
- 管理器那边读取时仍会核对账号身份。
24
- - **读取**:清单里 `maxAge` 是 `PT0S`,每次读取都重新查询,不复用上次的结果。Codex 本身启动不了或不答复时整块读取失败,保留上次结果并标明。
25
-
26
- ## 扩展点「账号来源」
27
-
28
- 扩展点 `account-source`:别的插件替 Codex 选账号(`codex-accounts` 就是)。没有插件接上时,Codex 用这台机器上自己的登录。
29
-
30
- - **对话**:会话的 Codex 进程启动接上的第一个来源的命令(`sh -c`,`PATH` 最前面是 Coda 的 Node,`CODA_PLUGIN_PATH`、`CODA_PLUGIN_STATE` 是来源插件的),
31
- 常驻,经标准输入输出一行一个 JSON 问它;来源退出了,下次问时再启动:
32
-
33
- | 问 | 答 |
34
- | --- | --- |
35
- | `{ "id", "method": "selected" }` | `{ "id", "result": { "account": { "id", "name" } } }`;`"account": null` 是不接管,保持 Codex 当前的登录 |
36
- | `{ "id", "method": "tokens", "params": { "account", "refresh"? } }` | `{ "id", "result": { "accessToken", "chatgptAccountId", "chatgptPlanType" } }` |
37
-
38
- 答不了时回 `{ "id", "error": { "message" } }`,原因写进那一轮的失败里;全权接管的来源在还没选账号时就回错误。
39
- `tokens` 的 `refresh` 可选:为 `true` 时要求来源续期,不能返回已被 Codex 拒绝的旧令牌,令牌还没到期也要续。
40
- - **什么时候换**:入口让 codex-acp 经账号桥(`agent/accounts.mjs`)运行 Codex:在开会话、恢复、分叉和每轮开始时问来源选的是谁。
41
- 回 `null` 就什么都不做,Codex 保持当前的登录;选中的 ID 与当前已应用的相同时不读令牌;换到另一个 ID(包括 `native`,它没有特殊处理)才向来源要这个账号的令牌,
42
- 经 app-server 的 `chatgptAuthTokens` 登录交给 Codex,再核对 Codex 登上的就是这个账号。
43
- 有轮次在跑时不换,等这一连接上的轮次都结束再换。Codex 要续期时(`account/chatgptAuthTokens/refresh`)入口问来源要这个账号的令牌,带 `refresh: true`;
44
- Codex 当前的账号不是交过去的那个、或来源给的令牌属于另一个账号,就拒绝。
45
- - **换不过去**:来源答不了、令牌不全或 Codex 登上的不是所选账号时,那一轮失败,写「没能换到所选的 Codex 账号 X:原因。去「资源」重新选择或登录」,
20
+ 动作(操作 `act` 的 `reset`,`scripts/act.mjs`)只兑换按钮指定的那一次(不让上游自己挑),没重置成(当前额度无需重置、这次已被使用或已不可用)时那一行写明。
21
+ - **登录**:操作 `sign-in`(`scripts/sign-in.mjs`)运行同一个 CLI 的 `codex login --device-auth`,把它打印的链接与设备码用 `coda progress` 报给 Coda(报完才算登录结束,报失败登录就失败),20 秒内没有链接就失败,原因是那时 CLI 说的最后一行(之后被结束时 CLI 说什么不改它,退出码 0 也不算成功);这套流程在 `scripts/device-login.mjs`;设备码登录要在 ChatGPT 账号安全设置或工作区权限里启用
22
+ ([OpenAI 登录说明](https://learn.chatgpt.com/docs/auth))。重新登录替换 `CODEX_HOME` 当前的登录。打开「多账号」时这个入口改为添加或更新多账号里的账号(`scripts/cli.mjs` 转给 `scripts/login.mjs`)。
23
+ - **读取**:记录命令不定时(清单里没有 `every`),资源页打开、点「刷新」和每个操作之后才运行,每次都重新查询。Codex 本身启动不了或不答复时命令以非零退出,原因写在标准错误的最后一行。
24
+
25
+ ## 多账号
26
+
27
+ 设置「多账号」(`codex.multipleAccounts`,开关,默认关)。关着时用这台机器上 Codex 自己的登录(上一节);打开后由插件管理多个账号:
28
+ 自动纳入已有登录,添加与移除账号、自动续期、查看额度和使用完全重置,所选账号在会话开始和两轮之间生效。账号的导入、添加与存放见仓库根 README 的「Codex 账号与额度」。
29
+
30
+ - **资源**:另一种资源类型 `accounts`,标题也叫「Codex」,每个账号一个资源,名字是别名(邮箱);本机登录那一种(`login`)这时输出为空,登录入口仍在。
31
+ 额度与完全重置的读数同本机登录;会话正在用的那个多一个读数「状态 · 正在使用」。某个账号的登录没有了、过期或无效时,只写在它自己那一行;别的读不到(网络、超时、服务端出错、Codex 没有给出某个账号的任何额度、账号列表读不了)命令以非零退出,原因写在标准错误的最后一行,Coda 保留上一份记录,资源页显示「更新失败:原因」。
32
+ 所选的账号不在插件里时另有一行「所选账号」写明。至多 40 个账号、合计不超过 60 KiB。旧登录导入失败时记录照写:一行「Codex 账号」写原因,登录入口照常在。记录命令同是 `scripts/resource.mjs`。
33
+ - **按钮**(在「···」里;操作 `act`,`scripts/act.mjs` 在开关打开时按 `{ action, args }` 分派 `select`、`reset`、`remove`):「切换使用」(先用这个账号核对一次,通过才记下;会话在下一个边界换过去)、
34
+ 「使用完全重置」(同本机登录,用这个账号的令牌)、「移除账号」(删掉插件保存的登录;移除的是正在用的,要再选或添加一个)。
35
+ - **身份**:知道邮箱的账号带与本机登录同一写法的身份(邮箱与工作区),同一账号在几台上、或与本机登录是同一个时,Coda 的资源页只显示一行。
36
+ - **登录**:操作 `sign-in` 运行 `scripts/cli.mjs login`,开关打开时它转给 `scripts/login.mjs`(Codex 的设备码登录,每次在私有目录里,登完核对才保存),设备码的上报与收尾同本机登录(`scripts/device-login.mjs`)。
37
+ - **会话**:入口让 codex-acp 经账号桥(`agent/accounts.mjs`)运行 Codex:在开会话、恢复、分叉和每轮开始时问账号管理(`scripts/manager.mjs`)选的是谁。
38
+ 选中的 ID 与当前已应用的相同时不读令牌;换到另一个才读这个账号的令牌,经 app-server 的 `chatgptAuthTokens` 登录交给 Codex,再核对 Codex 登上的就是这个账号。
39
+ 有轮次在跑时不换,等这一连接上的轮次都结束再换。Codex 要续期时(`account/chatgptAuthTokens/refresh`)入口为这个账号续期后再交;
40
+ Codex 当前的账号不是交过去的那个、或续期后的令牌属于另一个账号,就拒绝。
41
+ - **换不过去**:还没选账号、所选账号的登录不可用或 Codex 登上的不是所选账号时,那一轮失败,写「没能换到所选的 Codex 账号 X:原因。去「资源」重新选择或登录」,
46
42
  不用之前的账号发出去。已交了账号时,ACP 自己的登录、登出被拒绝,免得盖掉所选的账号。
47
43
  - 令牌只走账号桥与 app-server 之间的私有管道,不经 ACP,不进会话记录。连接显式指定了自己的 Codex 程序(`CODEX_PATH`)时不接账号桥。
48
44
  交令牌(`chatgptAuthTokens`)是 app-server 的实验接口:升级 codex-acp 或 Codex 时复核登录、`account/read` 的身份核对、续期请求与轮次边界。
@@ -1,20 +1,24 @@
1
- // The account bridge: what codex-acp runs as its Codex (`CODEX_PATH`, set by entry.mjs) when another plugin is plugged
2
- // into Codex's `account-source` point (account-source.mjs). Between codex-acp and the real app-server, it signs the
3
- // app-server in to the account the source has chosen, by handing it the source's tokens; they stay on this private pipe,
4
- // below ACP and the session's journal. Nothing chosen, Codex keeps this machine's own login.
1
+ // The account bridge: what codex-acp runs as its Codex (`CODEX_PATH`, set by entry.mjs) when「多账号」is on (the setting
2
+ // `codex.multipleAccounts`). Between codex-acp and the real app-server, it signs the app-server in to the managed account
3
+ // chosen (scripts/manager.mjs, the source), by handing it that account's tokens; they stay on this private pipe, below ACP and
4
+ // the session's journal. A source that says nothing is chosen (`null`) leaves Codex on this machine's own login.
5
5
  // The choice takes effect where nothing is under way: as a session starts and between turns (the native thread and turn
6
6
  // entry points ask the source each time). A turn whose account cannot be taken fails and says why, rather than going out
7
7
  // on the one before; one under way finishes on the account it began with.
8
8
  import { resolve } from 'node:path';
9
9
  import { fileURLToPath } from 'node:url';
10
10
  import { AppServer } from '../scripts/app-server.mjs';
11
- import { AccountSource, accountSource } from './account-source.mjs';
11
+ import { chosen, tokens } from '../scripts/manager.mjs';
12
12
  import { readLines } from './lines.mjs';
13
13
 
14
+ // 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
+ const managed = { selected: () => chosen(), tokens: (account, { refresh = false } = {}) => tokens(account, undefined, { refresh }), close() {} };
17
+
14
18
  class AccountError extends Error {}
15
19
  const failed = (account, error) => new AccountError(`没能换到所选的 Codex 账号${account ? ` ${account.name}` : ''}:${error?.message || '凭据不可用'}。去「资源」重新选择或登录`);
16
20
 
17
- export function startAccountBridge({ source = new AccountSource(accountSource()), makeServer = options => new AppServer(options), input = process.stdin,
21
+ export function startAccountBridge({ source = managed, makeServer = options => new AppServer(options), input = process.stdin,
18
22
  output = value => process.stdout.write(`${JSON.stringify(value)}\n`) } = {}) {
19
23
  let initialized = false, initializeId, applied = null, accountId = null, problem = null, queue = Promise.resolve(), closing = false;
20
24
  const active = new Map(), starting = new Map();
@@ -130,6 +134,9 @@ export function runAccountBridge(options) {
130
134
  if (result.error) process.stderr.write(`Codex 无法启动:${result.error.code || result.error.message}\n`);
131
135
  if (result.signal) {
132
136
  for (const signal of signals) process.off(signal, stop);
137
+ // The managed accounts' locks (proper-lockfile, through signal-exit) listen for it too and would end the process with
138
+ // the exit code instead; a lock left behind is taken over once stale.
139
+ process.removeAllListeners(result.signal);
133
140
  process.exitCode = 1;
134
141
  process.kill(process.pid, result.signal);
135
142
  } else process.exit(result.code ?? 1);
package/agent/entry.mjs CHANGED
@@ -5,14 +5,14 @@
5
5
  // async questions asked as cards whose answers it is given within the same turn (questions.mjs); its context compactions told as
6
6
  // `compaction_update` (compaction.mjs); what of Codex is not adapted
7
7
  // is told to Coda (unrecognized.mjs); the models of the model service chosen in Coda join Codex's own (providers.mjs). What Coda wants of Codex beyond ACP is set here: the mode a session starts in, and
8
- // which Codex program runs, through the account bridge when another plugin chooses the account (accounts.mjs).
8
+ // which Codex program runs, through the account bridge when「多账号」chooses the account (accounts.mjs).
9
9
  import { createRequire, registerHooks } from 'node:module';
10
10
  import { spawnSync } from 'node:child_process';
11
11
  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 { accountSource } from './account-source.mjs';
15
+ import { multipleAccounts } from '../scripts/manager.mjs';
16
16
  import { readLines } from './lines.mjs';
17
17
  import { orderedCodexTitles } from './titles.mjs';
18
18
  import { continuedCodexSubagents } from './subagents.mjs';
@@ -43,10 +43,10 @@ function codexVersion() {
43
43
  if (own) return /\d+\.\d+\.\d+[\w.+-]*/.exec(spawnSync(own, ['--version'], { encoding: 'utf8', timeout: 3000 }).stdout ?? '')?.[0] ?? null;
44
44
  try { return JSON.parse(readFileSync(createRequire(import.meta.url).resolve('@openai/codex/package.json'), 'utf8')).version; } catch { return null; }
45
45
  }
46
- // Another plugin plugged into Codex's `account-source` point chooses the account (accounts.mjs): codex-acp then runs the
47
- // account bridge as its Codex, through a small program written into this plugin's state, named for what it runs. A Codex
46
+ // With「多账号」on (the setting `codex.multipleAccounts`) the managed account chosen is the one (accounts.mjs): codex-acp then
47
+ // runs the account bridge as its Codex, through a small program written into this plugin's state, named for what it runs. A Codex
48
48
  // program of the connection's own (`CODEX_PATH`) keeps its own login.
49
- if (!env.CODEX_PATH && accountSource(env) && env.CODA_PLUGIN_STATE) {
49
+ if (!env.CODEX_PATH && multipleAccounts(env) && env.CODA_PLUGIN_STATE) {
50
50
  const quote = value => `'${value.replaceAll("'", "'\\''")}'`;
51
51
  const program = `#!/bin/sh\nexec ${quote(process.execPath)} ${quote(fileURLToPath(new URL('./accounts.mjs', import.meta.url)))} "$@"\n`;
52
52
  const shim = join(env.CODA_PLUGIN_STATE, `account-bridge-${createHash('sha256').update(program).digest('hex').slice(0, 12)}`);
package/package.json CHANGED
@@ -3,13 +3,17 @@
3
3
  "id": "codex",
4
4
  "displayName": "Codex",
5
5
  "description": "用 OpenAI Codex 跑会话",
6
- "version": "1.14.4",
6
+ "version": "2.0.0",
7
+ "engines": {
8
+ "coda": 6
9
+ },
7
10
  "categories": [
8
11
  "Agent"
9
12
  ],
10
13
  "dependencies": {
11
14
  "@agentclientprotocol/codex-acp": "1.12.0",
12
- "@openai/codex": "0.169.0"
15
+ "@openai/codex": "0.169.0",
16
+ "proper-lockfile": "4.1.2"
13
17
  },
14
18
  "overrides": {
15
19
  "@agentclientprotocol/codex-acp": {
@@ -56,32 +60,31 @@
56
60
  "title": "模型服务",
57
61
  "order": 1,
58
62
  "description": "勾选插件提供的模型服务(如 Magpie),每个服务各成一组,它列出的模型和 Codex 自己的模型一起出现在会话的模型里;选中哪个服务的模型,那个会话就走那个服务,Codex 自己的模型照旧。只列 OpenAI Responses 接口(openai-responses)的服务:Codex 不再支持 Chat Completions。"
63
+ },
64
+ "codex.multipleAccounts": {
65
+ "type": "boolean",
66
+ "title": "多账号",
67
+ "order": 2,
68
+ "default": false,
69
+ "description": "在 Coda 里管理多个 Codex 账号:资源页的「Codex」改为每个账号一行(首次打开时导入这台机器已有的 Codex 登录),可添加、切换、移除账号和使用完全重置;会话在开始和两轮之间换到所选的账号,令牌由插件续期。关着时用这台机器上 Codex 自己的登录。"
59
70
  }
60
71
  }
61
72
  },
62
- "resources": [
73
+ "protocolImplementations": [
63
74
  {
64
- "id": "login",
65
- "title": "Codex",
66
- "command": "node \"$CODA_PLUGIN_PATH/scripts/resources.mjs\"",
67
- "maxAge": "PT0S",
68
- "actions": {
69
- "reset": {
70
- "command": "node \"$CODA_PLUGIN_PATH/scripts/reset.mjs\"",
71
- "confirm": "使用一次完全重置?\n用最早到期的那一次。成功后消耗 1 次,无法撤销。"
72
- }
73
- },
74
- "signIn": {
75
- "command": "NO_COLOR=1 exec node \"$CODA_PLUGIN_PATH/scripts/cli.mjs\" login --device-auth",
76
- "note": "接入账号插件后,登录会添加或更新插件管理的账号。"
75
+ "kind": "coda/resource@1",
76
+ "commands": {
77
+ "act": "scripts/act.mjs",
78
+ "sign-in": "scripts/sign-in.mjs"
77
79
  }
78
80
  }
79
81
  ],
80
- "extensionPoints": {
81
- "account-source": {
82
- "description": "Codex 的账号与登录入口:来源给出当前账号和令牌,响应 --login,并提供账号与额度资源;接入后 Codex 自带的那一行不再显示。"
82
+ "records": [
83
+ {
84
+ "kind": "coda/resource@1",
85
+ "command": "scripts/resource.mjs"
83
86
  }
84
- }
87
+ ]
85
88
  },
86
89
  "license": "MIT",
87
90
  "repository": {
@@ -0,0 +1,51 @@
1
+ #!/usr/bin/env node
2
+ // The actions of the buttons on the「Codex」resources (the `act` operation of `coda/resource@1`), `{ action, args }` on standard
3
+ // input: a full reset of this machine's own login, or with「多账号」on (the setting `codex.multipleAccounts`), switching to, a full
4
+ // reset of and removing a managed account. Anything but what is asked for is said in one line and fails the action, so its row
5
+ // shows it.
6
+ import { randomUUID } from 'node:crypto';
7
+ import { readFileSync } from 'node:fs';
8
+ import { withAppServer } from './app-server.mjs';
9
+ import { withAccount } from './codex.mjs';
10
+ import { choose, multipleAccounts, remove, tokens, withManagedAccount } from './manager.mjs';
11
+ import { outcomes } from './quota.mjs';
12
+
13
+ // Redeems exactly the credit its button named (without one Codex would pick for itself), once, with the app-server `withServer`
14
+ // runs it against.
15
+ async function redeem(withServer, creditId) {
16
+ let outcome;
17
+ try { ({ outcome } = await withServer(server => server.request('account/rateLimitResetCredit/consume', { creditId, idempotencyKey: randomUUID() }))); }
18
+ catch (error) { throw new Error(`使用结果未确认,请核对剩余次数:${error.message}`); }
19
+ if (outcome !== 'reset') throw new Error(outcomes[outcome] ?? '使用结果未确认,请核对剩余次数');
20
+ }
21
+
22
+ // The「使用完全重置」button of this machine's own login. One that names a managed account is a row left from「多账号」on: its
23
+ // credit is that account's, never to be redeemed with this login.
24
+ async function reset({ account, creditId }) {
25
+ if (account !== undefined) throw new Error('多账号已关闭,这个账号的操作不可用');
26
+ if (typeof creditId !== 'string' || !creditId) throw new Error('没有指明用哪一次完全重置');
27
+ await redeem(withAppServer, creditId);
28
+ }
29
+
30
+ // The「切换使用」button checks the managed account before saving the choice. Sessions take it at their next boundary.
31
+ async function select({ account }) {
32
+ try {
33
+ if (typeof account !== 'string' || !account) throw new Error('没有指明切换到哪个账号');
34
+ await withAccount(await tokens(account), async () => {});
35
+ await choose(account);
36
+ } catch (error) { throw new Error(`切换失败:${error.message}`); }
37
+ }
38
+
39
+ // The「使用完全重置」button of a managed account.
40
+ async function resetManaged({ account, creditId }) {
41
+ if (typeof account !== 'string' || !account || typeof creditId !== 'string' || !creditId) throw new Error('没有指明用哪个账号的哪一次完全重置');
42
+ await redeem(work => withManagedAccount(account, work), creditId);
43
+ }
44
+
45
+ const actions = multipleAccounts() ? { select, reset: resetManaged, remove: ({ account }) => remove(account) } : { reset };
46
+ const { action, args } = JSON.parse(readFileSync(0, 'utf8'));
47
+ try {
48
+ if (!Object.hasOwn(actions, action)) throw new Error(`不认识的动作:${action}`);
49
+ await actions[action](args);
50
+ console.log('{}');
51
+ } catch (error) { console.error(error.message); process.exitCode = 1; }
@@ -1,15 +1,20 @@
1
1
  // A private connection to the Codex CLI's app-server, as this machine's Codex sessions are signed in: the plugin's own CLI
2
2
  // (its `@openai/codex` dependency, the one codex-acp runs) in its own home (`CODEX_HOME`, or ~/.codex).
3
3
  // Codex reads and renews that login itself; nothing of it passes through here, unless a login is handed to it (the account
4
- // bridge, agent/accounts.mjs, which also takes what Codex says and asks of its client: `onMessage`).
4
+ // bridge, agent/accounts.mjs, which also takes what Codex says and asks of its client: `onMessage`). With「多账号」on, a managed
5
+ // account's own home is given as `env` and `cwd`, and `args` add to `app-server` (scripts/codex.mjs).
5
6
  import { spawn } from 'node:child_process';
7
+ import { fileURLToPath } from 'node:url';
6
8
  import { readLines } from '../agent/lines.mjs';
7
9
 
10
+ // The plugin's own Codex CLI.
11
+ export const codexCli = () => fileURLToPath(import.meta.resolve('@openai/codex/bin/codex.js'));
12
+
8
13
  export class AppServer {
9
- constructor({ env = process.env, command = [process.execPath, new URL(import.meta.resolve('@openai/codex/bin/codex.js')).pathname, 'app-server'],
14
+ constructor({ env = process.env, cwd, args = [], command = [process.execPath, codexCli(), 'app-server', ...args],
10
15
  timeoutMs = 15_000, onMessage = null } = {}) {
11
16
  this.pending = new Map(); this.next = 0; this.timeoutMs = timeoutMs; this.onMessage = onMessage;
12
- this.child = spawn(command[0], command.slice(1), { env, stdio: ['pipe', 'pipe', 'ignore'] });
17
+ this.child = spawn(command[0], command.slice(1), { env, cwd, stdio: ['pipe', 'pipe', 'ignore'] });
13
18
  this.child.stdin.on('error', () => {});
14
19
  readLines(this.child.stdout).on('line', line => {
15
20
  let message; try { message = JSON.parse(line); } catch { return; }
package/scripts/cli.mjs CHANGED
@@ -1,11 +1,6 @@
1
- // Once an account source owns the accounts, even the pre-existing Codex login entry adds to its managed store.
2
- import { spawn } from 'node:child_process';
3
- import { accountSource, sourceEnv } from '../agent/account-source.mjs';
1
+ // The plugin's own Codex CLI, as the sign-in runs it. With「多账号」on (the setting `codex.multipleAccounts`), its login adds to
2
+ // or updates the managed accounts instead (login.mjs).
3
+ import { multipleAccounts } from './manager.mjs';
4
4
 
5
- const source = accountSource();
6
- if (source && process.argv[2] === 'login') {
7
- const child = spawn('/bin/sh', ['-c', `${source.command} --login`], { env: sourceEnv(source), stdio: 'inherit' });
8
- process.on('SIGTERM', () => child.kill('SIGTERM')); process.on('SIGINT', () => child.kill('SIGINT'));
9
- child.on('error', () => { console.error('无法启动账号插件的登录'); process.exitCode = 1; });
10
- child.on('close', code => { process.exitCode = code ?? 1; });
11
- } else await import('@openai/codex/bin/codex.js');
5
+ if (multipleAccounts() && process.argv[2] === 'login') await import('./login.mjs');
6
+ else await import('@openai/codex/bin/codex.js');
@@ -0,0 +1,30 @@
1
+ // Managed Codex homes and isolated checks that external tokens select the same identity as a session would use.
2
+ import { mkdtemp, rm } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { AppServer } from './app-server.mjs';
6
+
7
+ // Account operations never inherit a different account from API-key/token environment variables.
8
+ export function accountEnv(home, env = process.env) {
9
+ const result = { ...env, CODEX_HOME: home, NO_COLOR: '1' };
10
+ for (const key of ['OPENAI_API_KEY', 'CODEX_API_KEY', 'CODEX_ACCESS_TOKEN']) delete result[key];
11
+ return result;
12
+ }
13
+ export const fileCredentials = ['-c', 'cli_auth_credentials_store="file"'];
14
+ export async function withAccountHome(home, work, { env = process.env, makeServer = options => new AppServer(options) } = {}) {
15
+ const server = makeServer({ env: accountEnv(home, env), cwd: home, args: fileCredentials, timeoutMs: 6000 });
16
+ try { await server.initialize(); return await work(server); }
17
+ finally { await server.close(); }
18
+ }
19
+
20
+ export async function withAccount(tokens, work, { makeServer = options => new AppServer(options) } = {}) {
21
+ const home = await mkdtemp(join(tmpdir(), 'coda-codex-account-'));
22
+ const server = makeServer({ env: accountEnv(home), cwd: home, args: fileCredentials });
23
+ try {
24
+ await server.initialize();
25
+ await server.request('account/login/start', { type: 'chatgptAuthTokens', ...tokens });
26
+ const { account, workspaceRouting } = await server.request('account/read', { refreshToken: false });
27
+ if (account?.type !== 'chatgpt' || workspaceRouting?.chatgptAccountId !== tokens.chatgptAccountId) throw new Error('Codex 登录后的账号与所选的不符');
28
+ return await work(server);
29
+ } finally { await server.close(); await rm(home, { recursive: true, force: true }); }
30
+ }
@@ -0,0 +1,48 @@
1
+ // A device-code login as the `sign-in` operation of `coda/resource@1` runs it, for this machine's own login and, with「多账号」on,
2
+ // for a managed account (login.mjs): the entry says how to start the CLI that prints the device link and code (`start()`, a
3
+ // child process with its output piped),
4
+ // and this reports them (`coda progress`, awaited before the login is settled), gives the login 20 seconds to print them,
5
+ // ends it with its CLI, and settles it: `{}` when the CLI ended well and nothing failed, else one line, the first reason
6
+ // noted, else the last line the CLI said.
7
+ import { execFile } from 'node:child_process';
8
+ import { stripVTControlCharacters } from 'node:util';
9
+
10
+ // The device code a login prints: a verification URL that carries the code, or the code alone on a line after it. Only whole
11
+ // lines are read: output arrives in pieces, and a URL cut short would carry a code cut short.
12
+ export function deviceCode(text) {
13
+ const plain = stripVTControlCharacters(text.slice(0, text.lastIndexOf('\n') + 1));
14
+ const url = plain.match(/https:\/\/\S+/)?.[0] ?? null;
15
+ let code = null;
16
+ try { code = url && new URL(url).searchParams.get('user_code'); } catch { return null; }
17
+ code ||= plain.match(/^\s*([A-Z0-9]{4}-[A-Z0-9]{4,5})\s*$/m)?.[1] ?? null;
18
+ return url && code && /^[A-Z0-9]{4}-[A-Z0-9]{4,5}$/.test(code) ? { url, code } : null;
19
+ }
20
+ const lastLine = text => stripVTControlCharacters(text).split('\n').map(line => line.trim()).filter(Boolean).at(-1);
21
+ // Coda's own command: what it prints, or why it failed (its last line).
22
+ const coda = (...args) => new Promise((done, fail) => execFile('coda', args, (error, stdout, stderr) =>
23
+ error ? fail(new Error(stderr.trim().split('\n').at(-1) || error.message)) : done(stdout)));
24
+
25
+ export async function deviceLogin(start) {
26
+ const child = start();
27
+ let output = '', reported = false, reporting = Promise.resolve(), failed = null;
28
+ // The first reason stays: what the CLI says when it is ended for it (cancelled, say) is not the reason.
29
+ const fail = reason => { failed ??= reason; child.kill(); };
30
+ const silent = setTimeout(() => fail(lastLine(output) || '登录没有完成,请重新登录。'), 20_000);
31
+ const heard = chunk => {
32
+ output = (output + chunk).slice(-8000);
33
+ const found = !reported && deviceCode(output);
34
+ if (!found) return;
35
+ reported = true; clearTimeout(silent);
36
+ reporting = coda('progress', JSON.stringify(found)).catch(error => fail(error.message));
37
+ };
38
+ child.stdout.on('data', heard); child.stderr.on('data', heard);
39
+ child.on('error', () => { failed ??= '无法启动 Codex 登录'; });
40
+ // Coda ends the whole group: the CLI is ended with it, and waited for.
41
+ for (const signal of ['SIGTERM', 'SIGINT']) process.on(signal, () => child.kill(signal));
42
+ const code = await new Promise(resolve => child.on('close', resolve));
43
+ clearTimeout(silent);
44
+ await reporting;
45
+ if (code === 0 && !failed) { console.log('{}'); return; }
46
+ console.error(failed ?? lastLine(output) ?? '登录没有完成,请重新登录。');
47
+ process.exitCode = 1;
48
+ }
@@ -0,0 +1,31 @@
1
+ // With「多账号」on, Coda's login (the `sign-in` operation, sign-in.mjs, through cli.mjs) runs this. Codex prints the device
2
+ // link/code and owns OAuth. Each attempt has a private home; only a completed, checked login is committed to the managed accounts.
3
+ import { spawn } from 'node:child_process';
4
+ import { mkdtemp, rm } from 'node:fs/promises';
5
+ import { join } from 'node:path';
6
+ import { codexCli } from './app-server.mjs';
7
+ import { accountEnv, fileCredentials } from './codex.mjs';
8
+ import { paths, prepare, list, saveLogin } from './manager.mjs';
9
+
10
+ let home, child, cancelled = false;
11
+ const cancel = () => { cancelled = true; child?.kill('SIGTERM'); };
12
+ process.on('SIGTERM', cancel); process.on('SIGINT', cancel);
13
+ try {
14
+ const at = paths(); prepare(at); await list(at, { recoverImport: true });
15
+ home = await mkdtemp(join(at.state, 'login-'));
16
+ if (cancelled) throw new Error('登录已取消');
17
+ const env = accountEnv(home);
18
+ const code = await new Promise((resolve, reject) => {
19
+ child = spawn(process.execPath, [codexCli(), 'login', '--device-auth', ...fileCredentials], { env, cwd: home, stdio: ['ignore', 'pipe', 'pipe'] });
20
+ child.stdout.pipe(process.stdout); child.stderr.pipe(process.stderr);
21
+ child.once('error', () => reject(new Error('无法启动 Codex 登录')));
22
+ child.once('close', resolve);
23
+ });
24
+ child = null;
25
+ if (cancelled || code !== 0) throw new Error(cancelled ? '登录已取消' : '登录未完成,请重试');
26
+ await saveLogin(home, at, { isCancelled: () => cancelled });
27
+ } catch (error) { console.error(error.message); process.exitCode = 1; }
28
+ finally {
29
+ if (home) await rm(home, { recursive: true, force: true });
30
+ process.off('SIGTERM', cancel); process.off('SIGINT', cancel);
31
+ }
@@ -0,0 +1,195 @@
1
+ // The managed accounts of「多账号」(the setting `codex.multipleAccounts`). Each has a Codex home below CODA_PLUGIN_STATE/accounts;
2
+ // Codex performs OAuth and renews its auth.json there. Only access tokens leave this module, for the account bridge
3
+ // (agent/accounts.mjs). No external account manager or Python is needed.
4
+ import { createHash, randomUUID } from 'node:crypto';
5
+ import { chmodSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
6
+ import { homedir } from 'node:os';
7
+ import { join } from 'node:path';
8
+ import { withAccountHome } from './codex.mjs';
9
+ import { SignInAgain } from './quota.mjs';
10
+
11
+ const ID = /^[a-f0-9]{64}$/;
12
+ // Whether「多账号」is on: the plugin's settings as Coda hands them to its processes.
13
+ export function multipleAccounts(env = process.env) {
14
+ try { return JSON.parse(env.CODA_PLUGIN_SETTINGS || '{}')['codex.multipleAccounts'] === true; } catch { return false; }
15
+ }
16
+ export const identity = account => createHash('sha256').update(account).digest('hex');
17
+ export const paths = (env = process.env) => {
18
+ if (!env.CODA_PLUGIN_STATE) throw new Error('Coda 没有提供插件状态目录');
19
+ return { state: join(env.CODA_PLUGIN_STATE, 'accounts'), native: env.CODEX_HOME || join(homedir(), '.codex'), env };
20
+ };
21
+ const unavailable = '账号登录已失效,请在「资源」重新登录该账号';
22
+ const missing = '此账号尚未在插件中登录,请在「资源」重新登录';
23
+ function privateDir(dir) {
24
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
25
+ if (!lstatSync(dir).isDirectory() || lstatSync(dir).isSymbolicLink()) throw new Error('账号目录不可用');
26
+ chmodSync(dir, 0o700);
27
+ }
28
+ export function prepare(at = paths()) {
29
+ privateDir(at.state); privateDir(join(at.state, 'accounts')); privateDir(join(at.state, 'locks'));
30
+ }
31
+ function readJSON(file) {
32
+ const stat = lstatSync(file);
33
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 2 * 1024 * 1024) throw new Error('账号文件不可用');
34
+ return JSON.parse(readFileSync(file, 'utf8'));
35
+ }
36
+ function writeJSON(file, value) {
37
+ const temp = `${file}.${randomUUID()}`;
38
+ try { writeFileSync(temp, JSON.stringify(value), { mode: 0o600, flag: 'wx', flush: true }); renameSync(temp, file); }
39
+ finally { rmSync(temp, { force: true }); }
40
+ }
41
+ // All credential writers take the same per-account lock, including quota reads (Codex may refresh during them).
42
+ // Index changes take the store lock first. Locks have a heartbeat and recover after an abruptly ended process.
43
+ async function locked(key, at, work) {
44
+ prepare(at);
45
+ // Loaded when a lock is first taken: its exit handlers (signal-exit, on SIGTERM and SIGINT) stay out of the processes that
46
+ // only ask whether「多账号」is on (the agent's entry, the CLI).
47
+ const { default: lockfile } = await import('proper-lockfile');
48
+ let release;
49
+ try { release = await lockfile.lock(join(at.state, 'locks', key), { realpath: false, stale: 10_000,
50
+ retries: { retries: 20, minTimeout: 100, maxTimeout: 150, factor: 1 } }); }
51
+ catch { throw new Error('账号正在更新,请稍后重试'); }
52
+ try { return await work(); } finally { await release(); }
53
+ }
54
+ function stored(at) {
55
+ try {
56
+ 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')) throw Error();
58
+ return value.accounts;
59
+ } catch (error) { if (error.code === 'ENOENT') return null; throw new Error('读不了插件保存的账号列表'); }
60
+ }
61
+ // Import the existing Codex login once, as an ordinary managed account. A store, even an empty one, records that this
62
+ // has happened: removing the imported account must not make it reappear on the next reading.
63
+ export async function list(at = paths(), { recoverImport = false } = {}) {
64
+ const known = stored(at);
65
+ if (known !== null) return known;
66
+ return locked('store', at, async () => {
67
+ const existing = stored(at);
68
+ if (existing !== null) return existing;
69
+ const accounts = [];
70
+ let login;
71
+ try {
72
+ const auth = readJSON(join(at.native, 'auth.json'));
73
+ if (auth?.tokens?.access_token && auth.tokens.refresh_token) login = readAuth(at.native);
74
+ } catch (error) {
75
+ if (error.code !== 'ENOENT' && !recoverImport) throw new SignInAgain('无法导入已有 Codex 登录,请从「添加资源」登录 Codex');
76
+ }
77
+ if (login) {
78
+ const id = identity(login.tokens.chatgptAccountId);
79
+ let email;
80
+ try { email = JSON.parse(Buffer.from(login.auth.tokens.id_token.split('.')[1], 'base64url').toString('utf8')).email; } catch {}
81
+ const home = join(at.state, 'accounts', id);
82
+ 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 });
84
+ }
85
+ const chosen = selection(at);
86
+ // The old plugin's "native" choice becomes the imported identity, not a second kind of account.
87
+ if (chosen === null || chosen === 'native') writeJSON(join(at.state, 'selection.json'), { account: accounts[0]?.identity ?? null });
88
+ writeJSON(join(at.state, 'accounts.json'), { version: 1, accounts });
89
+ return accounts;
90
+ });
91
+ }
92
+ export function selection(at = paths()) {
93
+ try {
94
+ const selected = readJSON(join(at.state, 'selection.json')).account ?? null;
95
+ if (selected !== null && selected !== 'native' && !ID.test(selected)) throw Error();
96
+ return selected;
97
+ } catch (error) { if (error.code === 'ENOENT') return null; throw new Error('读不了所选的账号'); }
98
+ }
99
+ // The account sessions are to use, as the account bridge asks for it: an error until one is chosen and signed in here.
100
+ export async function chosen(at = paths()) {
101
+ const accounts = await list(at), account = selection(at);
102
+ if (account === null) throw new Error('请在「资源」添加或选择一个 Codex 账号');
103
+ const found = accounts.find(a => a.identity === account);
104
+ if (!found) throw new Error('所选账号尚未在插件中登录,请在「资源」重新登录该账号');
105
+ return { id: account, name: found.alias.slice(0, 80) };
106
+ }
107
+ export async function choose(account, at = paths()) {
108
+ await list(at);
109
+ return locked('store', at, async () => {
110
+ if (!(await list(at)).some(a => a.identity === account)) throw new SignInAgain(missing);
111
+ writeJSON(join(at.state, 'selection.json'), { account });
112
+ });
113
+ }
114
+ function homeFor(account, at) {
115
+ if (!ID.test(account)) throw new SignInAgain(missing);
116
+ const home = join(at.state, 'accounts', account);
117
+ try { if (!lstatSync(home).isDirectory() || lstatSync(home).isSymbolicLink()) throw Error(); }
118
+ catch { throw new SignInAgain(missing); }
119
+ return home;
120
+ }
121
+ export function readAuth(home, expected) {
122
+ try {
123
+ const auth = readJSON(join(home, 'auth.json')), accessToken = auth.tokens.access_token;
124
+ const claims = JSON.parse(Buffer.from(accessToken.split('.')[1], 'base64url').toString('utf8'));
125
+ const info = claims['https://api.openai.com/auth'], chatgptAccountId = info.chatgpt_account_id;
126
+ if (typeof chatgptAccountId !== 'string' || !chatgptAccountId || !Number.isFinite(claims.exp)
127
+ || (expected && identity(chatgptAccountId) !== expected)
128
+ || (auth.tokens.account_id && auth.tokens.account_id !== chatgptAccountId)) throw Error();
129
+ return { auth, expires: claims.exp * 1000, tokens: { accessToken, chatgptAccountId,
130
+ ...(typeof info.chatgpt_plan_type === 'string' ? { chatgptPlanType: info.chatgpt_plan_type } : {}) } };
131
+ } catch { throw new SignInAgain(unavailable); }
132
+ }
133
+ async function checked(server, expected, refreshToken = false) {
134
+ const result = await server.request('account/read', { refreshToken });
135
+ if (result.account?.type !== 'chatgpt' || identity(result.workspaceRouting?.chatgptAccountId ?? '') !== expected) throw new SignInAgain('Codex 登录后的账号与所选的不符');
136
+ return result.account;
137
+ }
138
+ // Quota/reset requests use this account's managed login, so Codex itself handles a 401 and persists renewed tokens.
139
+ export async function withManagedAccount(account, work, at = paths(), options) {
140
+ if (!(await list(at)).some(a => a.identity === account)) throw new SignInAgain(missing);
141
+ return locked(account, at, async () => {
142
+ const home = homeFor(account, at);
143
+ readAuth(home, account);
144
+ return withAccountHome(home, async server => { await checked(server, account); return work(server); }, { env: at.env, ...options });
145
+ });
146
+ }
147
+ // Refresh only when needed or explicitly requested after a rejected access token. Recheck under the lock so concurrent
148
+ // sessions do not refresh the same rotating refresh token at once. The full auth document never leaves this module.
149
+ export async function tokens(account, at = paths(), { refresh = false, ...options } = {}) {
150
+ if (!(await list(at)).some(a => a.identity === account)) throw new SignInAgain(missing);
151
+ return locked(account, at, async () => {
152
+ const home = homeFor(account, at), expected = account;
153
+ let current = readAuth(home, expected);
154
+ if (refresh || current.expires <= Date.now() + 60_000) {
155
+ try {
156
+ await withAccountHome(home, server => checked(server, identity(current.tokens.chatgptAccountId), true), { env: at.env, ...options });
157
+ current = readAuth(home, expected);
158
+ } catch { throw new SignInAgain(unavailable); }
159
+ }
160
+ if (current.expires <= Date.now() + 30_000) throw new SignInAgain(unavailable);
161
+ return current.tokens;
162
+ });
163
+ }
164
+ // Commit a completed device login. Logging in to an existing identity replaces its credentials; other accounts and
165
+ // their selection stay intact. Only the first account is selected automatically, unless a choice was already saved.
166
+ export async function saveLogin(home, at = paths(), { isCancelled = () => false, ...options } = {}) {
167
+ await list(at);
168
+ const initial = readAuth(home), id = identity(initial.tokens.chatgptAccountId);
169
+ 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, id), { env: at.env, ...options });
171
+ return locked('store', at, () => locked(id, at, async () => {
172
+ const accounts = await list(at), previous = accounts.find(a => a.identity === id);
173
+ if (isCancelled()) throw new Error('登录已取消');
174
+ const record = { identity: id, alias: account.email || previous?.alias || `账号 ${id.slice(0, 8)}`, plan: account.planType ?? null };
175
+ const target = join(at.state, 'accounts', id);
176
+ privateDir(target);
177
+ writeJSON(join(target, 'auth.json'), readAuth(home, id).auth);
178
+ writeJSON(join(at.state, 'accounts.json'), { version: 1, accounts: previous ? accounts.map(a => a.identity === id ? record : a) : [...accounts, record] });
179
+ if (!accounts.length && selection(at) === null) writeJSON(join(at.state, 'selection.json'), { account: id });
180
+ return record;
181
+ }));
182
+ }
183
+ export async function remove(account, at = paths()) {
184
+ if (!ID.test(account)) throw new Error('没有指明要移除的账号');
185
+ await list(at);
186
+ return locked('store', at, () => locked(account, at, async () => {
187
+ const accounts = await list(at);
188
+ if (!accounts.some(a => a.identity === account)) throw new SignInAgain(missing);
189
+ const home = join(at.state, 'accounts', account);
190
+ // Remove secrets before the index: a failed removal remains visible and can be retried.
191
+ rmSync(home, { recursive: true, force: true });
192
+ if (selection(at) === account) writeJSON(join(at.state, 'selection.json'), { account: null });
193
+ writeJSON(join(at.state, 'accounts.json'), { version: 1, accounts: accounts.filter(a => a.identity !== account) });
194
+ }));
195
+ }
package/scripts/quota.mjs CHANGED
@@ -1,9 +1,10 @@
1
1
  import { createHash } from 'node:crypto';
2
2
 
3
3
  // What the「Codex」resource type shows of a login (docs/plugins.md「内置插件:Codex」), from what Codex's app-server says of
4
- // it: `account/read` and `account/rateLimits/read`. Kept apart from the commands so the tests can hand it answers.
4
+ // it: `account/read` and `account/rateLimits/read`; with「多账号」on, of each managed account (manager.mjs). Kept apart from the
5
+ // commands so the tests can hand it answers.
5
6
 
6
- const VALUES = 8;
7
+ const VALUES = 8, ACCOUNTS = 40, BYTES = 60 * 1024;
7
8
  const line = (value, max = 80) => typeof value === 'string' ? [...value.replace(/\s+/g, ' ').trim()].slice(0, max).join('') : '';
8
9
  // The account a resource is, compared across machines by Coda's group view (its `identity`): who signed in and in which
9
10
  // ChatGPT workspace, as the quota is one person's in one workspace (one email may sign in to several, and a workspace has
@@ -50,29 +51,108 @@ export function credits(result) {
50
51
  // reset (that one, named in its question).
51
52
  export function resource(account, result, workspace) {
52
53
  const name = line(account.email) || '本机登录';
53
- const values = windows(result), resets = credits(result), actions = [];
54
+ const values = windows(result), resets = credits(result), buttons = [];
54
55
  if (resets) {
55
56
  const first = resets.listed[0], expires = first?.expiresAt == null ? null : unixTime(first.expiresAt);
56
57
  values.splice(VALUES - 1, Infinity, { label: '完全重置', value: `剩余 ${resets.count} 次`, ...(expires ? { time: expires } : {}) });
57
- if (first && resets.count > 0) actions.push({ label: '使用完全重置', action: 'reset', args: { creditId: first.id },
58
+ if (first && resets.count > 0) buttons.push({ label: '使用完全重置', action: 'reset', args: { creditId: first.id },
58
59
  confirm: `使用 ${line(name, 60)} 的完全重置?\n用最早到期的那一次(${first.expiresAt == null ? '不会过期' : `${mark(first.expiresAt)} 到期`})。成功后消耗 1 次,无法撤销。` });
59
60
  }
60
- return { name, ...identity(account, workspace), values: values.slice(0, VALUES),
61
- ...(values.length ? {} : { error: '暂时无法获取额度:Codex 没有给出额度窗口' }), ...(actions.length ? { actions } : {}) };
61
+ if (!values.length) throw new Error('暂时无法获取额度:Codex 没有给出额度窗口');
62
+ return { name, ...identity(account, workspace), values: values.slice(0, VALUES), buttons };
62
63
  }
63
64
 
64
- // The resources: none without a login (the type is then offered under「添加资源」), the login for one. Quota Codex cannot
65
- // read is said on its row, which keeps「重新登录」 at hand; one not signed in with ChatGPT has no windows to read.
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
+ // The resources: none without a login (the type is then offered under「添加资源」), the login for one. A login Codex says is no
74
+ // 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
+ // that cannot be read for any other reason throws.
66
76
  export async function resources(server) {
67
77
  const { account, workspaceRouting } = await server.request('account/read', { refreshToken: false });
68
78
  const workspace = workspaceRouting?.chatgptAccountId;
69
79
  if (!account) return { resources: [] };
70
- if (account.type !== 'chatgpt') return { resources: [{ name: '本机登录', values: [{ value: '不是 ChatGPT 登录,没有额度' }] }] };
80
+ if (account.type !== 'chatgpt') return { resources: [{ name: '本机登录', values: [{ value: '不是 ChatGPT 登录,没有额度' }], buttons: [] }] };
71
81
  let result;
72
82
  try { result = await server.request('account/rateLimits/read'); }
73
- catch (error) { return { resources: [{ name: line(account.email) || '本机登录', ...identity(account, workspace), error: line(`暂时无法获取额度:${error.message}`) }] }; }
83
+ catch (error) {
84
+ if (!needsSignIn(error)) throw error;
85
+ return { resources: [{ name: line(account.email) || '本机登录', ...identity(account, workspace), values: [], buttons: [], error: line(`登录已失效,请重新登录:${error.message}`) }] };
86
+ }
74
87
  return { resources: [resource(account, result, workspace)] };
75
88
  }
76
89
 
77
90
  // What a full reset came to, as one line on the row when it did not reset anything.
78
91
  export const outcomes = { nothingToReset: '当前额度无需重置', alreadyRedeemed: '这次重置已被使用', noCredit: '这次重置已不可用' };
92
+
93
+ // What the resources are when Codex says its login is no good (`needsSignIn`): the one row says so. The type's record is still
94
+ // written, so its sign-in stays offered.
95
+ export const unreadable = error => ({ resources: [{ name: '本机登录', values: [], buttons: [], error: line(`登录已失效,请重新登录:${error.message}`) }] });
96
+
97
+ // A managed account, from its quota (`result`) or why its login is no good (`error`, a line): the one sessions use says so first;
98
+ // its windows, then its full resets left, timed by the one to expire first; switching to it, a full reset (the one to
99
+ // expire first, named in its question) and removing it. The selection is a preference; running turns finish before
100
+ // adopting it.
101
+ export function managedResource(account, chosen, { result, error }) {
102
+ const name = line(account.alias), values = chosen ? [{ label: '状态', value: '正在使用' }] : [];
103
+ const buttons = chosen ? [] : [{ label: '切换使用', action: 'select', args: { account: account.identity } }];
104
+ if (!error) {
105
+ const known = values.length;
106
+ values.push(...windows(result));
107
+ const resets = credits(result);
108
+ if (resets) {
109
+ const first = resets.listed[0], expires = first?.expiresAt == null ? null : unixTime(first.expiresAt);
110
+ values.splice(VALUES - 1, Infinity, { label: '完全重置', value: `剩余 ${resets.count} 次`, ...(expires ? { time: expires } : {}) });
111
+ if (first && resets.count > 0) buttons.push({ label: '使用完全重置', action: 'reset', args: { account: account.identity, creditId: first.id },
112
+ confirm: `使用 ${line(name, 60)} 的完全重置?\n用最早到期的那一次(${first.expiresAt == null ? '不会过期' : `${mark(first.expiresAt)} 到期`})。成功后消耗 1 次,无法撤销。` });
113
+ }
114
+ if (values.length === known) throw new Error(`暂时无法获取额度:Codex 没有给出${line(name, 40)}的额度窗口`);
115
+ }
116
+ buttons.push({ label: '移除账号', action: 'remove', args: { account: account.identity },
117
+ confirm: `移除 ${line(name, 60)} 在插件中保存的登录?${chosen ? '\n移除后需要选择或添加账号才能继续会话。' : ''}` });
118
+ // Who it is and in which workspace, as this machine's own login says it (the manager's identity is the workspace's account ID
119
+ // hashed): Coda's group view shows the same one once. None when its email is not known.
120
+ const email = account.alias.includes('@') ? account.alias.trim().toLowerCase() : '';
121
+ return { name, ...(email ? { identity: `codex:${hash(`${email}\n${account.identity}`)}` } : {}),
122
+ values: values.slice(0, VALUES), ...(error ? { error: line(error) } : {}), buttons };
123
+ }
124
+
125
+ // The managed accounts' resources, each read by `read` (at most `at` at once). Empty on a new machine: Coda offers the type's
126
+ // signIn under「添加资源」. Existing accounts can be added to or signed in again from a row's「重新登录」. A selection of an account
127
+ // not signed in here is a row of its own, saying so.
128
+ export async function managedResources(accounts, chosen, read, { at = 4 } = {}) {
129
+ if (!accounts.length && chosen === null) return { resources: [] };
130
+ const shown = accounts.slice(0, ACCOUNTS), readings = new Array(shown.length);
131
+ let next = 0, failed;
132
+ await Promise.all(Array.from({ length: Math.min(at, shown.length) }, async () => {
133
+ for (let i; (i = next++) < shown.length;) {
134
+ const account = shown[i];
135
+ try { readings[i] = managedResource(account, chosen === account.identity, { result: await read(account) }); }
136
+ catch (error) {
137
+ if (!needsSignIn(error)) { failed ??= error; continue; }
138
+ readings[i] = managedResource(account, chosen === account.identity, { error: error instanceof SignInAgain ? error.message : `登录已失效,请重新登录:${error.message}` });
139
+ }
140
+ }
141
+ }));
142
+ // Every reading is ended first, so that none is left holding an account's lock.
143
+ if (failed) throw failed;
144
+ const out = chosen && !accounts.some(a => a.identity === chosen) ? [{ name: '所选账号', values: [], buttons: [], error: '尚未在插件中登录:重新登录它,或切换到其他账号' }] : [];
145
+ // The selected account when it is not signed in here comes first, as a row of its own; the record stays within 64 KiB, and
146
+ // rows past it are left out.
147
+ let bytes = Buffer.byteLength(JSON.stringify(out));
148
+ for (const each of readings) {
149
+ const size = Buffer.byteLength(JSON.stringify(each)) + 1;
150
+ if (bytes + size > BYTES) break;
151
+ out.push(each); bytes += size;
152
+ }
153
+ return { resources: out };
154
+ }
155
+
156
+ // What the managed accounts are when they cannot be read for want of a login (an old one that cannot be imported, say): the one
157
+ // row says why. The type's record is still written, so its sign-in stays offered, which is how to add an account without it.
158
+ export const managedUnreadable = error => ({ resources: [{ name: 'Codex 账号', values: [], buttons: [], error: line(error.message) }] });
@@ -0,0 +1,24 @@
1
+ #!/usr/bin/env node
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, while this machine's own login shows none. Signing in
4
+ // stays offered either way (the CLI comes with the plugin). A login that is gone, expired or unreadable is a row saying so; any
5
+ // other failure to read (Codex not answering, the network, a server's error, a damaged store) fails the command (exit 1, the
6
+ // reason on the last line of its standard error), which keeps the records Coda has.
7
+ import { withAppServer } from './app-server.mjs';
8
+ import { list, multipleAccounts, selection, withManagedAccount } from './manager.mjs';
9
+ import { managedResources, managedUnreadable, needsSignIn, resources, unreadable } from './quota.mjs';
10
+
11
+ const fail = error => { console.error(String(error.message).replace(/\s+/g, ' ').trim()); process.exit(1); };
12
+ const multiple = multipleAccounts();
13
+ const own = multiple ? { resources: [] } : await withAppServer(resources).catch(error => needsSignIn(error) ? unreadable(error) : fail(error));
14
+ const records = [{ key: 'login', spec: { type: 'login', title: 'Codex', ...own,
15
+ signIn: { installed: true, installable: false, note: '打开「多账号」后,登录会添加或更新多账号里的账号。' } } }];
16
+ if (multiple) {
17
+ const read = account => withManagedAccount(account.identity, server => server.request('account/rateLimits/read'));
18
+ let managed;
19
+ try { managed = await managedResources(await list(), selection(), read); }
20
+ catch (error) { managed = needsSignIn(error) ? managedUnreadable(error) : fail(error); }
21
+ records.push({ key: 'accounts', spec: { type: 'accounts', title: 'Codex', ...managed,
22
+ signIn: { installed: true, installable: false, note: '登录其他账号即可添加;登录已有账号会更新其凭据。首个账号会自动选用,之后在账号那一行的「···」里切换。' } } });
23
+ }
24
+ console.log(JSON.stringify(records));
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env node
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.
4
+ import { spawn } from 'node:child_process';
5
+ import { dirname, join } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { deviceLogin } from './device-login.mjs';
8
+
9
+ await deviceLogin(() => spawn(process.execPath, [join(dirname(fileURLToPath(import.meta.url)), 'cli.mjs'), 'login', '--device-auth'],
10
+ { env: { ...process.env, NO_COLOR: '1' }, stdio: ['ignore', 'pipe', 'pipe'] }));
@@ -1,71 +0,0 @@
1
- // The account source another plugin plugs into Codex (the `account-source` extension point, docs/plugins.md「内置插件:Codex」):
2
- // its command, started once and asked over its standard input and output, one JSON object a line.
3
- // → { "id": 1, "method": "selected" } ← { "id": 1, "result": { "account": { "id", "name" } | null } }
4
- // → { "id": 2, "method": "tokens", "params": { "account", "refresh"? } } ← { "id": 2, "result": { "accessToken", "chatgptAccountId", "chatgptPlanType" } }
5
- // `refresh: true` asks the owner to renew a rejected access token, even before its expiry.
6
- // Either may answer `{ "id", "error": { "message" } }`. A source taking full ownership reports an error until an account
7
- // is chosen; a legacy source's `null` leaves the underlying login as it is. A source that ends is started again when asked.
8
- // An installed source owns the account's resources and handles `--login` for Codex's existing login entry.
9
- import { spawn } from 'node:child_process';
10
- import { dirname } from 'node:path';
11
- import { readLines } from './lines.mjs';
12
-
13
- // What Coda hands this plugin's processes of the plugins plugged into its points (CODA_PLUGIN_EXTENSIONS): the first source.
14
- export function accountSource(env = process.env) {
15
- let points; try { points = JSON.parse(env.CODA_PLUGIN_EXTENSIONS || '{}'); } catch { return null; }
16
- return points?.['account-source']?.[0] ?? null;
17
- }
18
-
19
- export function sourceEnv(source, env = process.env) {
20
- return { ...env, CODA_PLUGIN_PATH: source.path, ...(source.state ? { CODA_PLUGIN_STATE: source.state } : {}),
21
- CODA_PLUGIN_DEPENDENCIES: JSON.stringify({ codex: env.CODA_PLUGIN_PATH }),
22
- PATH: [dirname(process.execPath), env.PATH].filter(Boolean).join(':') };
23
- }
24
-
25
- export class AccountSource {
26
- constructor(source, { env = process.env, timeoutMs = 10_000 } = {}) {
27
- this.source = source; this.env = env; this.timeoutMs = timeoutMs; this.next = 0; this.pending = new Map(); this.child = null; this.closed = false;
28
- }
29
- start() {
30
- const { command } = this.source;
31
- // As a resource type's command is run (docs/plugins.md「资源」): its plugin's directory and state, and this Node first on the PATH.
32
- const child = spawn('/bin/sh', ['-c', command], { env: sourceEnv(this.source, this.env),
33
- stdio: ['pipe', 'pipe', 'ignore'] });
34
- child.stdin.on('error', () => {});
35
- readLines(child.stdout).on('line', line => {
36
- let message; try { message = JSON.parse(line); } catch { return; }
37
- const waiter = this.pending.get(message?.id);
38
- if (!waiter) return;
39
- this.pending.delete(message.id); clearTimeout(waiter.timer);
40
- if (message.error) waiter.reject(new Error(typeof message.error.message === 'string' && message.error.message.trim() ? message.error.message.trim().slice(0, 200) : '账号来源拒绝了请求'));
41
- else waiter.resolve(message.result ?? {});
42
- });
43
- const ended = () => {
44
- if (this.child === child) this.child = null;
45
- for (const [id, waiter] of this.pending) if (waiter.child === child) { clearTimeout(waiter.timer); this.pending.delete(id); waiter.reject(new Error('账号来源提前退出了')); }
46
- };
47
- child.once('error', ended); child.once('exit', ended);
48
- return child;
49
- }
50
- request(method, params) {
51
- if (this.closed) return Promise.reject(new Error('账号来源已关闭'));
52
- const child = this.child ??= this.start(), id = ++this.next;
53
- return new Promise((resolve, reject) => {
54
- const timer = setTimeout(() => { this.pending.delete(id); reject(new Error('账号来源没有答复')); }, this.timeoutMs);
55
- this.pending.set(id, { resolve, reject, timer, child });
56
- child.stdin.write(`${JSON.stringify({ id, method, ...(params ? { params } : {}) })}\n`);
57
- });
58
- }
59
- async selected() {
60
- const { account } = await this.request('selected');
61
- if (account == null) return null;
62
- if (typeof account?.id !== 'string' || !account.id) throw new Error('账号来源给的账号无效');
63
- return { id: account.id, name: typeof account.name === 'string' && account.name ? account.name.slice(0, 80) : account.id };
64
- }
65
- async tokens(account, { refresh = false } = {}) {
66
- const tokens = await this.request('tokens', { account, ...(refresh ? { refresh: true } : {}) });
67
- if (typeof tokens.accessToken !== 'string' || typeof tokens.chatgptAccountId !== 'string') throw new Error('账号来源给的凭据不完整');
68
- return { accessToken: tokens.accessToken, chatgptAccountId: tokens.chatgptAccountId, ...(typeof tokens.chatgptPlanType === 'string' ? { chatgptPlanType: tokens.chatgptPlanType } : {}) };
69
- }
70
- close() { this.closed = true; this.child?.kill(); }
71
- }
package/scripts/reset.mjs DELETED
@@ -1,15 +0,0 @@
1
- // The「使用完全重置」button: redeems exactly the credit its button named (without one Codex would pick for itself), once.
2
- // Anything but a reset is said in one line and fails the action, so its row shows it.
3
- import { randomUUID } from 'node:crypto';
4
- import { withAppServer } from './app-server.mjs';
5
- import { outcomes } from './quota.mjs';
6
- import { accountSource } from '../agent/account-source.mjs';
7
-
8
- if (accountSource()) { console.error('额度已由账号插件接管,请在账号插件的那一行使用完全重置'); process.exit(1); }
9
-
10
- const { creditId } = JSON.parse(process.env.CODA_PANEL_ARGS || '{}');
11
- if (typeof creditId !== 'string' || !creditId) { console.error('没有指明用哪一次完全重置'); process.exit(1); }
12
- let outcome;
13
- try { ({ outcome } = await withAppServer(server => server.request('account/rateLimitResetCredit/consume', { creditId, idempotencyKey: randomUUID() }))); }
14
- catch (error) { console.error(`使用结果未确认,请核对剩余次数:${error.message}`); process.exit(1); }
15
- if (outcome !== 'reset') { console.error(outcomes[outcome] ?? '使用结果未确认,请核对剩余次数'); process.exit(1); }
@@ -1,7 +0,0 @@
1
- // An account source owns the「Codex」resources. Without one, show Codex's own login as before.
2
- import { withAppServer } from './app-server.mjs';
3
- import { resources } from './quota.mjs';
4
- import { accountSource } from '../agent/account-source.mjs';
5
-
6
- try { console.log(JSON.stringify(accountSource() ? { resources: [] } : await withAppServer(resources))); }
7
- catch (error) { console.error(error.message); process.exit(1); }