@coda-console/codex 2.1.2 → 2.3.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
@@ -48,4 +48,15 @@ Codex Agent:Codex 插件提供的入口运行 codex-acp,报告子 Agent、
48
48
  交令牌(`chatgptAuthTokens`)是 app-server 的实验接口:升级 codex-acp 或 Codex 时复核登录、`account/read` 的身份核对、续期请求与轮次边界。
49
49
 
50
50
  「模型服务」设置、异步消息与提问见仓库根 README 的「模型服务」「Codex 异步消息与提问」。
51
+
52
+ 回执 `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`。
53
+
54
+ **每轮的用量**(`agent/usage.mjs`):codex-acp 的回执原本只带 Codex 最近一次模型响应的用量(`last`),一轮调用模型多次时只剩最后一笔,实测少算约 14 倍(长轮可少 200 倍以上)。补丁改为取这一轮内各线程累计量(`total`)的增量,三种回执(正常、命令、取消)都一样:
55
+ - 每个线程各记它上次见到的累计量,增量是这次累计减上次;线程第一次出现时基准是 `total − last`,所以恢复后的第一轮不含线程历史。Codex 在线程恢复时会重放一条当前累计量(属于上一次运行的轮次,本进程没见过它的 `turn/started`),这种通知只更新基准、不计数。
56
+ - 累计量变小(Codex 在上下文用满时重设计数)时按那一笔响应自己的 `last` 算,不出负数。
57
+ - 换算同以前:未缓存输入是 `inputTokens − cachedInputTokens − cacheWriteInputTokens`(缓存读、缓存写都含在 Codex 的输入里),缓存读 `cachedReadTokens`,缓存写 `cachedWriteTokens`(Codex 0.169 起的 `cacheWriteInputTokens`,现在都转发),输出含思考,`thoughtTokens` 是其中的思考部分。上下文占用(`usage_update`)仍取 `last`,没动。
58
+ - 这一轮没有增长的回执(`/status` 这类不调用模型的命令)不带 `usage`,不再重复带出上一轮的计数;`/review`、`/goal` 这类发起模型请求的命令照增量算。
59
+ - 子 Agent(原生子线程)的用量计入派生它的那一轮:子线程的 `thread/tokenUsage/updated` 以子线程 ID 区分、各自记基准,子线程后来新增的轮也算。记账在 codex-acp 订阅器的通知入口,每条原始事件只经过一次,在按客户端能力分流之前:Coda 现在发给 Agent 的能力里没有 `subagents`,子线程事件在 codex-acp 里是当作会话自己的事件交出去的,声明了原生子会话能力的客户端则要先暂存、建好子会话后再处理一遍,两种都不会漏记或记两次。Codex 可能先给子线程投递初始输入、让它的轮开始,之后父线程才发出带子线程 ID 的派生通知,此时适配器还没有这个子线程的处理器、会把它的通知丢掉:补丁在丢掉之前留下子线程的轮开始与用量(每个线程只留首条与最新一条用量,增量够用),父线程派生通知到了、认下这个子线程时再归到这一轮,只记一次;一直没被认领的线程(如 Codex 自己的审核子线程)不计。回执在父轮的子 Agent 等完后才发;父轮回执发出之后子线程才产生的用量(取消、等待超时后仍在跑的)计入下一份回执,不丢、不重。
60
+ - 以错误结束的轮次,其回执不带用量(Coda 对错误回执不采集用量),这一轮已发生的消耗随下一份回执上报,总量对,只是记在下一轮名下。
61
+ - 子 Agent 用的模型与父线程不同时(派生时指定了 `model`,`collabAgentToolCall`/`subAgentActivity` 的 `model`),回执带 `breakdown`:父线程一项,子 Agent 的各一项,各项带自己的四项计数;父线程在服务上时(上一段的 `service`、`asked`)子 Agent 的项带同一个 `service` 与自己的 `asked`(线程只在一个服务上运行),否则是 `model`。派生时没指定模型的子 Agent 用父线程的模型,并入父线程那一项;父线程的型号不明(服务的模型没有绑定到,如 `/review` 轮次)时不带 `breakdown`,只带合计。
51
62
  异步提问被宿主当场拒绝(`decline` 带非空 `_meta.coda.reason`)时,交给 Codex 的是这段文字原文;不带 reason 的 `decline` 与 `cancel` 仍是「用户没有回答「<问题>」」。同步提问(`item/tool/requestUserInput`)由 codex-acp 回 `{ answers: {} }`,拿不到 reason。
package/agent/entry.mjs CHANGED
@@ -4,7 +4,7 @@
4
4
  // and a steer that finds no turn going is answered `promptRequired` (steering.mjs); Codex's async messages are shown and its
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
- // is told to Coda (unrecognized.mjs); the models of the model service chosen in Coda join Codex's own (providers.mjs). the session's own temporary directory is writable in its sandbox (session-tmp.mjs). What Coda wants of Codex beyond ACP is set here: the mode a session starts in, and
7
+ // is told to Coda (unrecognized.mjs); the models of the model service chosen in Coda join Codex's own (providers.mjs), and a prompt is answered with the usage of its whole turn, subagents' too (usage.mjs). the session's own temporary directory is writable in its sandbox (session-tmp.mjs). What Coda wants of Codex beyond ACP is set here: the mode a session starts in, and
8
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';
@@ -22,6 +22,7 @@ import { codexOptionsAsShown } from './options.mjs';
22
22
  import { instructedCodexThreads } from './instructions.mjs';
23
23
  import { promptRequiredCodexSteering } from './steering.mjs';
24
24
  import { servedCodexModels } from './providers.mjs';
25
+ import { countedCodexUsage } from './usage.mjs';
25
26
  import { input, listen, relayedCodexStreams } from './relay.mjs';
26
27
  import { CodexWaits } from './waits.mjs';
27
28
  import { CodexReviews } from './reviews.mjs';
@@ -91,6 +92,6 @@ registerHooks({ load(url, context, nextLoad) {
91
92
  const loaded = nextLoad(url, context);
92
93
  if (url !== adapter.href) return loaded;
93
94
  return { ...loaded, source: reportedCodexUnrecognized(shownCodexAsyncMessages(reportedCodexCompactions(reportedCodexSleeps(reportedCodexFailures(codexOptionsAsShown(relayedCodexStreams(orderedCodexTitles(followCodexProcessExit(continuedCodexSubagents(
94
- promptRequiredCodexSteering(instructedCodexThreads(servedCodexModels(networkedCodexDevelopment(writableCodexSessionTmp(trustedCodaMcpRequests(Buffer.from(loaded.source).toString('utf8'))))))))))))))))) };
95
+ promptRequiredCodexSteering(instructedCodexThreads(countedCodexUsage(servedCodexModels(networkedCodexDevelopment(writableCodexSessionTmp(trustedCodaMcpRequests(Buffer.from(loaded.source).toString('utf8')))))))))))))))))) };
95
96
  } });
96
97
  await import(adapter.href);
@@ -14,6 +14,15 @@ const log = text => process.stderr.write(`[codex-agent] ${text}\n`);
14
14
  const parse = text => { try { return JSON.parse(text || '{}'); } catch { return {}; } };
15
15
  const LIST_TIMEOUT = 8000;
16
16
 
17
+ // The resource reference (`coda://<接口种类>/<UUID>`) of the model service an address Coda injected is, from its
18
+ // `…/resources/<接口种类>/<UUID><路径>` (Coda's docs/plugins.md「模型服务」); null for an address of another shape.
19
+ export function serviceReference(url) {
20
+ let path;
21
+ try { path = new URL(url).pathname; } catch { return null; }
22
+ const found = /^\/resources\/(openai-completions|openai-responses|anthropic-messages|openai-speech)\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:\/|$)/i.exec(path);
23
+ return found ? `coda://${found[1]}/${found[2].toLowerCase()}` : null;
24
+ }
25
+
17
26
  // The services chosen, in the order chosen: each its address, title and key (read from the file Coda keeps it in). One not
18
27
  // on this machine, or speaking another API, is left out.
19
28
  export function chosenServices(env = process.env) {
@@ -76,10 +85,21 @@ export class ServiceModels {
76
85
  }
77
86
  // What a turn names to Codex: the service's own name for one of its models.
78
87
  wire(model) { return this.served(model)?.model ?? model; }
88
+ // The model a turn is sent on, bound to its session at that dispatch: the service its address says (as Coda injected it) and the model
89
+ // asked of it, as Coda's docs/plugins.md「Coda 的用量记录」 has them; none for a model of Codex's own or an address of another shape.
90
+ bind(sessionState, model) {
91
+ const served = this.served(model), service = served && serviceReference(this.services.find(s => s.ref === served.codaService)?.url);
92
+ sessionState.codaRequested = service ? { service, asked: served.model } : null;
93
+ }
94
+ // The `usage` a prompt answers with (usage.mjs), with what its turn was bound to. An answer of a prompt that sent no model request (a
95
+ // command such as `/status`) has none, and one whose turn was bound to nothing says nothing of any model.
96
+ usage(sessionState, usage) { return usage && sessionState.codaRequested ? { ...usage, ...sessionState.codaRequested } : usage; }
79
97
  // A stop that comes while a turn waits on the move has no turn of codex-acp's to interrupt yet: it is the waiting turn's,
80
98
  // which ends cancelled with its input not given (`route` says so).
81
99
  cancel(sessionId) { if (this.moving === sessionId) this.stopped = true; }
82
100
  async route(server, params) {
101
+ const state = server.sessions.get(params.sessionId);
102
+ if (state) state.codaRequested = null;
83
103
  this.moving = params.sessionId; this.stopped = false;
84
104
  try { await this.move(server, params); } finally { this.moving = null; }
85
105
  return this.stopped;
@@ -125,6 +145,9 @@ const patches = [
125
145
  // A stop while the session moves is the moving turn's.
126
146
  [' async cancel(params) {\n const sessionState = this.sessions.get(params.sessionId);',
127
147
  ' async cancel(params) {\n codaServices.cancel(params.sessionId);\n const sessionState = this.sessions.get(params.sessionId);', 1],
148
+ // The model a turn is sent on is bound to the session, and the usage a prompt answers with says it.
149
+ [' sessionState.lastTokenUsage = null;\n ensurePendingTurnStart();\n const sendPromptPromise', ' codaServices.bind(sessionState, modelId.model);\n sessionState.lastTokenUsage = null;\n ensurePendingTurnStart();\n const sendPromptPromise', 1],
150
+ ['this.buildPromptUsage(sessionState.lastTokenUsage)', 'codaServices.usage(sessionState, this.buildPromptUsage(sessionState.lastTokenUsage))', 4],
128
151
  [' model: modelId.model,\n serviceTier\n }, onTurnStarted);', ' model: codaServices.wire(modelId.model),\n serviceTier\n }, onTurnStarted);', 1],
129
152
  [' case "warning":\n return this.createWarningEvent(notification.params);',
130
153
  ' case "warning":\n if (codaServices.quiet(notification.params)) return null;\n return this.createWarningEvent(notification.params);', 1],
@@ -0,0 +1,122 @@
1
+ // What a prompt used, as `PromptResponse.usage` says it (Coda's per-turn token collection): the increase of the session's thread counts
2
+ // over the turn, not the last model response codex-acp answers with. Codex's `thread/tokenUsage/updated` carries `total` (the
3
+ // thread's count so far) and `last` (the latest response's alone), and codex-acp keeps both but answers with `last`, so a turn of several
4
+ // model calls told only the final one.
5
+ //
6
+ // Every thread of the session counts: the session's own and its subagents', each told as its thread says it, from the subscription's own
7
+ // handlers (the one place each event of a thread passes once, and before codex-acp parts the subagents' by what the client supports:
8
+ // without the capability they reach it as the session's own, and with it they are held back until their session is made and handled again).
9
+ // Per thread the increase is the total against the total last seen of it, so a notification seen twice, or the one
10
+ // codex-acp's `thread/resume` replays (below), adds nothing twice. What is counted is held until a prompt is answered and told then,
11
+ // so a subagent still running when its parent's turn is answered is told by the answer that comes after it.
12
+ // - Codex may start a subagent's turn before the parent tells of the subagent (its thread ID), when the subagent has no handler yet and
13
+ // the client drops what it says. The turn's start and its count are kept (the first and the latest of them, which is all the increase
14
+ // needs) until the parent tells of the thread, and counted then, in the session that tells of it; one never told of is never counted
15
+ // (a thread of Codex's own, as a reviewer's).
16
+ // - A thread not seen before starts from `total - last`, the count before its first response in this process.
17
+ // - Codex replays the thread's count when it is resumed (a session loaded, or moved to another model service): that notification is
18
+ // of the turn before, one this process saw no `turn/started` of, so it sets what was seen and counts nothing.
19
+ // - `total` falls when Codex resets the count as the context fills: what can be confirmed then is that response's own `last`,
20
+ // never a negative increase.
21
+ // A prompt that sent no model request (`/status`) has no increase and no usage. Cache writes are part of `input` in Codex's count as
22
+ // cache reads are: the uncached input leaves out both.
23
+ import { services } from './providers.mjs';
24
+
25
+ const FIELDS = ['inputTokens', 'cachedInputTokens', 'cacheWriteInputTokens', 'outputTokens', 'reasoningOutputTokens'];
26
+ const counts = value => Object.fromEntries(FIELDS.map(field => [field, Number.isSafeInteger(value?.[field]) && value[field] > 0 ? value[field] : 0]));
27
+ const sum = (a, b) => Object.fromEntries(FIELDS.map(field => [field, a[field] + b[field]]));
28
+ const none = value => FIELDS.every(field => value[field] === 0);
29
+ const bare = modelId => modelId?.replace(/\[[^\]]*\]$/, '');
30
+
31
+ // Codex's counts as Coda's four (thinking is in the output; `thoughtTokens` is only its part).
32
+ function told(value) {
33
+ const input = Math.max(0, value.inputTokens - value.cachedInputTokens - value.cacheWriteInputTokens);
34
+ return { inputTokens: input, outputTokens: value.outputTokens, cachedReadTokens: value.cachedInputTokens, cachedWriteTokens: value.cacheWriteInputTokens };
35
+ }
36
+
37
+ export class SessionUsage {
38
+ seen = new Map(); started = new Set(); spent = new Map(); models = new Map();
39
+ // What Codex tells of the session's threads, as codex-acp's event handler is given it.
40
+ notice({ method, params }) {
41
+ if (method === 'turn/started') this.started.add(params.turn.id);
42
+ else if (method === 'thread/tokenUsage/updated') this.count(params);
43
+ else if (method === 'item/started' || method === 'item/completed') {
44
+ // The model a subagent was spawned on, when the spawn says one; else it runs on its parent's.
45
+ const { item } = params, spawned = item.type === 'collabAgentToolCall' && item.tool === 'spawnAgent' ? item.receiverThreadIds : item.type === 'subAgentActivity' ? [item.agentThreadId] : [];
46
+ if (typeof item.model === 'string' && item.model) for (const threadId of spawned) this.models.set(threadId, item.model);
47
+ }
48
+ }
49
+ count({ threadId, turnId, tokenUsage }) {
50
+ const total = counts(tokenUsage.total), last = counts(tokenUsage.last), before = this.seen.get(threadId);
51
+ this.seen.set(threadId, total);
52
+ if (!this.started.has(turnId)) return;
53
+ const grown = before && FIELDS.every(field => total[field] >= before[field]);
54
+ const increase = !before ? last : grown ? Object.fromEntries(FIELDS.map(field => [field, total[field] - before[field]])) : last;
55
+ this.spent.set(threadId, sum(this.spent.get(threadId) ?? counts(), increase));
56
+ }
57
+ // The usage of what was counted since the last answer, or null where nothing was. `rootThreadId`: the session's own thread. `own`: its
58
+ // model as `{ model }` (Codex's) or `{ service, asked }` (a service's), null where that is not known.
59
+ take(rootThreadId, own) {
60
+ const spent = [...this.spent].filter(([, value]) => !none(value));
61
+ this.spent = new Map();
62
+ if (!spent.length) return null;
63
+ const all = spent.map(([, value]) => value).reduce(sum), four = told(all);
64
+ const ownModel = own?.asked ?? own?.model, buckets = new Map();
65
+ // Usage by model, where a subagent runs on another model than its parent: each bucket needs a name to be told, as the parent's
66
+ // is known, and a subagent's is on the parent's service when the parent is on one (a thread runs on one provider).
67
+ for (const [threadId, value] of spent) {
68
+ const asked = threadId === rootThreadId ? ownModel : this.models.get(threadId) ?? ownModel;
69
+ const label = !own ? null : asked === ownModel ? own : own.service ? { service: own.service, asked } : { model: asked };
70
+ const key = JSON.stringify(label), before = buckets.get(key);
71
+ buckets.set(key, { label, value: before ? sum(before.value, value) : value });
72
+ }
73
+ const named = [...buckets.values()];
74
+ return { totalTokens: four.inputTokens + four.outputTokens + four.cachedReadTokens + four.cachedWriteTokens, ...four, thoughtTokens: all.reasoningOutputTokens,
75
+ ...(named.length > 1 && named.every(({ label }) => label) ? { breakdown: named.map(({ label, value }) => ({ ...label, ...told(value) })) } : {}) };
76
+ }
77
+ }
78
+
79
+ const sessions = new Map(), held = new Map();
80
+ const of = rootThreadId => sessions.get(rootThreadId) ?? sessions.set(rootThreadId, new SessionUsage()).get(rootThreadId);
81
+ export const usage = {
82
+ notice: (rootThreadId, notification) => of(rootThreadId).notice(notification),
83
+ // What a thread with no handler says that counts: the start of a turn, and its count (the first and the latest).
84
+ held({ method, params }) {
85
+ if (method !== 'turn/started' && method !== 'thread/tokenUsage/updated') return;
86
+ const each = held.get(params.threadId) ?? held.set(params.threadId, { starts: [], first: null, last: null }).get(params.threadId);
87
+ if (method === 'turn/started') each.starts.push({ method, params });
88
+ else { each.first ??= { method, params }; each.last = { method, params }; }
89
+ },
90
+ // The session tells of the thread as its subagent: what was kept of it is counted as the thread's own events are.
91
+ claim(rootThreadId, threadId) {
92
+ const each = held.get(threadId);
93
+ held.delete(threadId);
94
+ if (each) for (const kept of new Set([...each.starts, each.first, each.last])) if (kept) of(rootThreadId).notice(kept);
95
+ },
96
+ // The usage a prompt of the session answers with. Its own model as it is told: the service and model asked of it when this prompt was
97
+ // bound to them (providers.mjs), else Codex's own model's name (none for a service's model that was not bound: unknown).
98
+ take(sessionState) {
99
+ const model = bare(sessionState.currentModelId), requested = sessionState.codaRequested;
100
+ return of(sessionState.sessionId).take(sessionState.sessionId, requested ?? (model && !services.served(model) ? { model } : null));
101
+ },
102
+ };
103
+
104
+ const patches = [
105
+ // Every notification of the session's threads, as the thread says it: the session's own, and each subagent's with its own thread ID.
106
+ [' this.discover(session, event);\n session.current.dispatch(event);', ' codaUsage.notice(subscription.rootSessionId, event);\n this.discover(session, event);\n session.current.dispatch(event);', 1],
107
+ [' if (eventThreadId !== childSessionId) return;\n this.discover(session, childEvent);', ' if (eventThreadId !== childSessionId) return;\n codaUsage.notice(session.current.rootSessionId, childEvent);\n this.discover(session, childEvent);', 1],
108
+ // A thread's notification with no handler is kept, not dropped, and counted once the session tells of the thread (a subagent's first turn may begin before that).
109
+ [' if (handler) {\n handler(notification);\n }\n return;', ' if (handler) {\n handler(notification);\n } else {\n codaUsage.held(notification);\n }\n return;', 1],
110
+ [' session.children.add(childSessionId);\n this.client.onServerNotification(childSessionId,', ' session.children.add(childSessionId);\n codaUsage.claim(session.current.rootSessionId, childSessionId);\n this.client.onServerNotification(childSessionId,', 1],
111
+ // A prompt is answered with what its turn used, whichever way it ends (a command, a turn, a stop, a failure the session records).
112
+ // Applies to the source providers.mjs patched: its answers are the ones that say the service and model.
113
+ ['this.buildPromptUsage(sessionState.lastTokenUsage)', 'codaUsage.take(sessionState)', 4],
114
+ ];
115
+ // Fails loudly once the locked adapter changes.
116
+ export function countedCodexUsage(source) {
117
+ for (const [before, after, count] of patches) {
118
+ if (source.split(before).length !== count + 1) throw new Error('codex-acp usage patch no longer matches the locked adapter');
119
+ source = source.replaceAll(before, after);
120
+ }
121
+ return `import { usage as codaUsage } from ${JSON.stringify(import.meta.url)};\n${source.replace(/^#![^\n]*\n/, '')}`;
122
+ }
package/package.json CHANGED
@@ -3,9 +3,9 @@
3
3
  "id": "codex",
4
4
  "displayName": "Codex",
5
5
  "description": "用 OpenAI Codex 跑会话",
6
- "version": "2.1.2",
6
+ "version": "2.3.1",
7
7
  "engines": {
8
- "coda": 6
8
+ "coda": 20
9
9
  },
10
10
  "categories": [
11
11
  "Agent"