@coda-console/codex 1.14.4 → 1.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -8,20 +8,20 @@ Codex Agent:Codex 插件提供的入口运行 codex-acp,报告子 Agent、
8
8
 
9
9
  资源页上的资源类型「Codex」:这台机器上 Codex 自己的登录(本机登录)和它的额度。接了账号来源(见下)时它输出为空,「Codex」里是账号插件管理的账号。
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 账号安全设置或工作区权限里启用
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`,`codex-accounts` 随包带一份一字不差的(旁边的 `codex` 可能是没有它的旧版),改它要同步那一份;设备码登录要在 ChatGPT 账号安全设置或工作区权限里启用
22
22
  ([OpenAI 登录说明](https://learn.chatgpt.com/docs/auth))。重新登录替换 `CODEX_HOME` 当前的登录;多账号管理器的活动账号若也用这个目录,同样被替换,
23
23
  管理器那边读取时仍会核对账号身份。
24
- - **读取**:清单里 `maxAge` 是 `PT0S`,每次读取都重新查询,不复用上次的结果。Codex 本身启动不了或不答复时整块读取失败,保留上次结果并标明。
24
+ - **读取**:记录命令不定时(清单里没有 `every`),资源页打开、点「刷新」和每个操作之后才运行,每次都重新查询。Codex 本身启动不了或不答复时命令以非零退出,原因写在标准错误的最后一行。
25
25
 
26
26
  ## 扩展点「账号来源」
27
27
 
package/package.json CHANGED
@@ -3,7 +3,10 @@
3
3
  "id": "codex",
4
4
  "displayName": "Codex",
5
5
  "description": "用 OpenAI Codex 跑会话",
6
- "version": "1.14.4",
6
+ "version": "1.15.1",
7
+ "engines": {
8
+ "coda": 6
9
+ },
7
10
  "categories": [
8
11
  "Agent"
9
12
  ],
@@ -59,24 +62,21 @@
59
62
  }
60
63
  }
61
64
  },
62
- "resources": [
65
+ "protocolImplementations": [
63
66
  {
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": "接入账号插件后,登录会添加或更新插件管理的账号。"
67
+ "kind": "coda/resource@1",
68
+ "commands": {
69
+ "act": "scripts/act.mjs",
70
+ "sign-in": "scripts/sign-in.mjs"
77
71
  }
78
72
  }
79
73
  ],
74
+ "records": [
75
+ {
76
+ "kind": "coda/resource@1",
77
+ "command": "scripts/resource.mjs"
78
+ }
79
+ ],
80
80
  "extensionPoints": {
81
81
  "account-source": {
82
82
  "description": "Codex 的账号与登录入口:来源给出当前账号和令牌,响应 --login,并提供账号与额度资源;接入后 Codex 自带的那一行不再显示。"
@@ -0,0 +1,26 @@
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. Anything but what is asked for is said in one line and fails the action, so its row shows it.
4
+ import { randomUUID } from 'node:crypto';
5
+ import { readFileSync } from 'node:fs';
6
+ import { withAppServer } from './app-server.mjs';
7
+ import { outcomes } from './quota.mjs';
8
+ import { accountSource } from '../agent/account-source.mjs';
9
+
10
+ // The「使用完全重置」button: redeems exactly the credit its button named (without one Codex would pick for itself), once.
11
+ async function reset({ creditId }) {
12
+ if (accountSource()) throw new Error('额度已由账号插件接管,请在账号插件的那一行使用完全重置');
13
+ if (typeof creditId !== 'string' || !creditId) throw new Error('没有指明用哪一次完全重置');
14
+ let outcome;
15
+ try { ({ outcome } = await withAppServer(server => server.request('account/rateLimitResetCredit/consume', { creditId, idempotencyKey: randomUUID() }))); }
16
+ catch (error) { throw new Error(`使用结果未确认,请核对剩余次数:${error.message}`); }
17
+ if (outcome !== 'reset') throw new Error(outcomes[outcome] ?? '使用结果未确认,请核对剩余次数');
18
+ }
19
+
20
+ const actions = { reset };
21
+ const { action, args } = JSON.parse(readFileSync(0, 'utf8'));
22
+ try {
23
+ if (!Object.hasOwn(actions, action)) throw new Error(`不认识的动作:${action}`);
24
+ await actions[action](args);
25
+ console.log('{}');
26
+ } catch (error) { console.error(error.message); process.exitCode = 1; }
@@ -0,0 +1,48 @@
1
+ // A device-code login as the `sign-in` operation of `coda/resource@1` runs it, for the codex plugin and codex-accounts, which
2
+ // carries a copy of this file (the codex installed beside it may be older and have none; a test holds the two the same): the
3
+ // entry says how to start the CLI that prints the device link and code (`start()`, a 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
+ }
package/scripts/quota.mjs CHANGED
@@ -50,29 +50,41 @@ export function credits(result) {
50
50
  // reset (that one, named in its question).
51
51
  export function resource(account, result, workspace) {
52
52
  const name = line(account.email) || '本机登录';
53
- const values = windows(result), resets = credits(result), actions = [];
53
+ const values = windows(result), resets = credits(result), buttons = [];
54
54
  if (resets) {
55
55
  const first = resets.listed[0], expires = first?.expiresAt == null ? null : unixTime(first.expiresAt);
56
56
  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 },
57
+ if (first && resets.count > 0) buttons.push({ label: '使用完全重置', action: 'reset', args: { creditId: first.id },
58
58
  confirm: `使用 ${line(name, 60)} 的完全重置?\n用最早到期的那一次(${first.expiresAt == null ? '不会过期' : `${mark(first.expiresAt)} 到期`})。成功后消耗 1 次,无法撤销。` });
59
59
  }
60
- return { name, ...identity(account, workspace), values: values.slice(0, VALUES),
61
- ...(values.length ? {} : { error: '暂时无法获取额度:Codex 没有给出额度窗口' }), ...(actions.length ? { actions } : {}) };
60
+ if (!values.length) throw new Error('暂时无法获取额度:Codex 没有给出额度窗口');
61
+ return { name, ...identity(account, workspace), values: values.slice(0, VALUES), buttons };
62
62
  }
63
63
 
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.
64
+ // Whether what Codex said is that its login is gone, expired or revoked, or its file unreadable: what signing in again cures.
65
+ // Any other failure of a reading (the network, a timeout, a server's error, Codex itself) is not, and is left to fail the command.
66
+ export const needsSignIn = error => /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 ?? '');
67
+
68
+ // The resources: none without a login (the type is then offered under「添加资源」), the login for one. A login Codex says is no
69
+ // longer good is said on its row, which keeps「重新登录」 at hand; one not signed in with ChatGPT has no windows to read. A quota
70
+ // that cannot be read for any other reason throws.
66
71
  export async function resources(server) {
67
72
  const { account, workspaceRouting } = await server.request('account/read', { refreshToken: false });
68
73
  const workspace = workspaceRouting?.chatgptAccountId;
69
74
  if (!account) return { resources: [] };
70
- if (account.type !== 'chatgpt') return { resources: [{ name: '本机登录', values: [{ value: '不是 ChatGPT 登录,没有额度' }] }] };
75
+ if (account.type !== 'chatgpt') return { resources: [{ name: '本机登录', values: [{ value: '不是 ChatGPT 登录,没有额度' }], buttons: [] }] };
71
76
  let result;
72
77
  try { result = await server.request('account/rateLimits/read'); }
73
- catch (error) { return { resources: [{ name: line(account.email) || '本机登录', ...identity(account, workspace), error: line(`暂时无法获取额度:${error.message}`) }] }; }
78
+ catch (error) {
79
+ if (!needsSignIn(error)) throw error;
80
+ return { resources: [{ name: line(account.email) || '本机登录', ...identity(account, workspace), values: [], buttons: [], error: line(`登录已失效,请重新登录:${error.message}`) }] };
81
+ }
74
82
  return { resources: [resource(account, result, workspace)] };
75
83
  }
76
84
 
77
85
  // What a full reset came to, as one line on the row when it did not reset anything.
78
86
  export const outcomes = { nothingToReset: '当前额度无需重置', alreadyRedeemed: '这次重置已被使用', noCredit: '这次重置已不可用' };
87
+
88
+ // What the resources are when Codex says its login is no good (`needsSignIn`): the one row says so. The type's record is still
89
+ // written, so its sign-in stays offered.
90
+ export const unreadable = error => ({ resources: [{ name: '本机登录', values: [], buttons: [], error: line(`登录已失效,请重新登录:${error.message}`) }] });
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env node
2
+ // The `coda/resource@1` record of the「Codex」type, printed once. An account source owns the resources: without one, show
3
+ // Codex's own login as before. Signing in stays offered either way (the CLI comes with the plugin). A login Codex says is gone,
4
+ // expired or unreadable is one row saying so; any other failure to read (Codex not answering, the network, a server's error) fails
5
+ // the command (exit 1, the reason on the last line of its standard error), which keeps the record Coda has.
6
+ import { withAppServer } from './app-server.mjs';
7
+ import { needsSignIn, resources, unreadable } from './quota.mjs';
8
+ import { accountSource } from '../agent/account-source.mjs';
9
+
10
+ const read = accountSource() ? { resources: [] } : await withAppServer(resources).catch(error => {
11
+ if (needsSignIn(error)) return unreadable(error);
12
+ console.error(String(error.message).replace(/\s+/g, ' ').trim()); process.exit(1);
13
+ });
14
+ console.log(JSON.stringify([{ key: 'login', spec: { type: 'login', title: 'Codex', ...read,
15
+ signIn: { installed: true, installable: false, note: '接入账号插件后,登录会添加或更新插件管理的账号。' } } }]));
@@ -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: an account source, if there is one, takes the login over), 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'] }));
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); }