@coda-console/codex 1.13.0 → 1.14.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,3 +1,5 @@
1
1
  # Codex
2
2
 
3
3
  Codex Agent:Coda 自带的入口运行 codex-acp,报告子 Agent、后台命令与命令的自动审核。额度与登录由账号来源插件接管;未接入账号来源时,资源页的「Codex」显示 Codex 自己的登录与额度。
4
+
5
+ 实时的上下文压缩(自动或手动)作为 Coda 的「整理上下文」记录显示:开始报 `compaction_update` in_progress、完成报 completed,Coda 据此知道会话压缩过;回合失败或中断、压缩未完成时补报 failed,不再出「Compact conversation」工具卡。恢复会话时,历史里的压缩仍显示为「Compact conversation」工具卡,不上报,免得 Coda 把它当成新的压缩。
@@ -0,0 +1,39 @@
1
+ // Codex's context compaction is told to Coda as ACP `compaction_update` (Coda keeps one 「整理上下文」 record per compactionId and
2
+ // notes a compaction when one completes), not as codex-acp's tool card or its "context compacted" text. The locked Codex says
3
+ // a compaction as an item (`contextCompaction`, started and completed, its id the compactionId); the deprecated
4
+ // `thread/compacted` carries no item and only its turn, so the one of the two a turn's compaction came as is the one told:
5
+ // the other, if it comes too, is not, and a compaction is never counted twice. One started whose turn ends failed or
6
+ // interrupted without completing it is told `failed` then, so Coda's record does not stay in progress.
7
+ const turns = new WeakMap();
8
+
9
+ // `event` is the item event or the legacy notification's params; `status` the item's (`in_progress`, `completed`), none for the notification.
10
+ export function codexCompactionUpdate(handler, event, status) {
11
+ const source = event.item ? 'item' : 'legacy', last = turns.get(handler);
12
+ if (last?.turnId === event.turnId && last.source !== source) return null;
13
+ turns.set(handler, { turnId: event.turnId, source, open: status === 'in_progress' ? event.item.id : null });
14
+ return { sessionUpdate: 'compaction_update', compactionId: event.item?.id ?? `${event.turnId}:compacted`, status: status ?? 'completed' };
15
+ }
16
+
17
+ // The turn's end, as `turn/completed` says it.
18
+ export function codexCompactionEnded(handler, turn) {
19
+ const state = turns.get(handler), id = state?.open;
20
+ if (!id) return null;
21
+ state.open = null;
22
+ return turn.status === 'completed' ? null : { sessionUpdate: 'compaction_update', compactionId: id, status: 'failed', error: turn.error?.message ?? null };
23
+ }
24
+
25
+ export function reportedCodexCompactions(source) {
26
+ const patches = [
27
+ [' return createContextCompactionStartUpdate(event.item);', 'codexCompactionUpdate(this, event, "in_progress")'],
28
+ [' return createContextCompactionCompleteUpdate(event.item);', 'codexCompactionUpdate(this, event, "completed")'],
29
+ [' return this.createContextCompactedEvent();', 'codexCompactionUpdate(this, notification.params)'],
30
+ ];
31
+ for (const [before, call] of patches) {
32
+ if (source.split(before).length !== 2) throw new Error('codex-acp compaction patch no longer matches the locked adapter');
33
+ source = source.replace(before, ` return ${call};`);
34
+ }
35
+ const ended = ' this.sessionState.currentTurnId = null;\n return null;\n case "thread/tokenUsage/updated":';
36
+ if (source.split(ended).length !== 2) throw new Error('codex-acp compaction patch no longer matches the locked adapter');
37
+ source = source.replace(ended, ended.replace('return null;', 'return codexCompactionEnded(this, notification.params.turn);'));
38
+ return `import { codexCompactionUpdate, codexCompactionEnded } from ${JSON.stringify(import.meta.url)};\n${source.replace(/^#![^\n]*\n/, '')}`;
39
+ }
package/agent/entry.mjs CHANGED
@@ -2,7 +2,8 @@
2
2
  // patches, which fail the start once the adapter changes. Between it and Coda the entry speaks Coda's protocol for it
3
3
  // (waits.mjs, docs/agent-protocol.md), and of its own check of a call as that call's (reviews.mjs): its session instructions become the thread's developer instructions (instructions.mjs),
4
4
  // and a steer that finds no turn going is answered `promptRequired` (steering.mjs); Codex's async messages are shown and its
5
- // async questions asked as cards whose answers it is given within the same turn (questions.mjs); what of Codex is not adapted
5
+ // async questions asked as cards whose answers it is given within the same turn (questions.mjs); its context compactions told as
6
+ // `compaction_update` (compaction.mjs); what of Codex is not adapted
6
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
7
8
  // which Codex program runs, through the account bridge when another plugin chooses the account (accounts.mjs).
8
9
  import { createRequire, registerHooks } from 'node:module';
@@ -26,6 +27,7 @@ import { CodexWaits } from './waits.mjs';
26
27
  import { CodexReviews } from './reviews.mjs';
27
28
  import { explainCodexError, reportedCodexFailures } from './errors.mjs';
28
29
  import { reportedCodexSleeps } from './sleep.mjs';
30
+ import { reportedCodexCompactions } from './compaction.mjs';
29
31
  import { codexDisplayNames } from './display.mjs';
30
32
  import { trustedCodaMcpRequests } from './mcp-policy.mjs';
31
33
  import { CodexQuestions, shownCodexAsyncMessages } from './questions.mjs';
@@ -78,7 +80,7 @@ const adapter = new URL(import.meta.resolve('@agentclientprotocol/codex-acp'));
78
80
  registerHooks({ load(url, context, nextLoad) {
79
81
  const loaded = nextLoad(url, context);
80
82
  if (url !== adapter.href) return loaded;
81
- return { ...loaded, source: reportedCodexUnrecognized(shownCodexAsyncMessages(reportedCodexSleeps(reportedCodexFailures(codexOptionsAsShown(relayedCodexStreams(orderedCodexTitles(followCodexProcessExit(continuedCodexSubagents(
82
- promptRequiredCodexSteering(instructedCodexThreads(servedCodexModels(networkedCodexDevelopment(trustedCodaMcpRequests(Buffer.from(loaded.source).toString('utf8'))))))))))))))) };
83
+ return { ...loaded, source: reportedCodexUnrecognized(shownCodexAsyncMessages(reportedCodexCompactions(reportedCodexSleeps(reportedCodexFailures(codexOptionsAsShown(relayedCodexStreams(orderedCodexTitles(followCodexProcessExit(continuedCodexSubagents(
84
+ promptRequiredCodexSteering(instructedCodexThreads(servedCodexModels(networkedCodexDevelopment(trustedCodaMcpRequests(Buffer.from(loaded.source).toString('utf8')))))))))))))))) };
83
85
  } });
84
86
  await import(adapter.href);
package/agent/errors.mjs CHANGED
@@ -19,10 +19,11 @@ export function explainCodexError(message) {
19
19
  // model pools, without identifying which one blocked this turn; do not schedule a retry from an unrelated window.
20
20
  const resetText = /\b(try again at |resets (?:at )?)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z)\b/gi;
21
21
  function quotaReset(error, data) {
22
- for (const text of [data.additionalDetails, data.message, error.message]) {
22
+ for (const text of [data.additionalDetails, data.message, data.details, error.message]) {
23
23
  if (typeof text !== 'string') continue;
24
24
  let body; try { body = JSON.parse(text); } catch {}
25
- const seconds = body?.error?.resets_at;
25
+ // An HTTP failure quotes the response body inside its own sentence: `unexpected status 429 Too Many Requests: {…}, url: …`.
26
+ const seconds = body ? body.error?.resets_at : Number(text.match(/"resets_at"\s*:\s*(\d{1,12})\b/)?.[1]);
26
27
  if (Number.isSafeInteger(seconds) && seconds > 0 && seconds <= 253402300799)
27
28
  return new Date(seconds * 1000).toISOString();
28
29
  const time = [...text.matchAll(resetText)][0]?.[2];
@@ -31,19 +32,42 @@ function quotaReset(error, data) {
31
32
  }
32
33
  }
33
34
 
35
+ // A 429 that Codex reports as a plain HTTP failure carries the provider's response body in its message. Only the provider's
36
+ // own quota codes and wording establish exhaustion; any other 429 is a rate limit, whose "try again in 1.5s" is the wait.
37
+ const providerQuota = /\b(?:insufficient_quota|quota_exceeded|usage_limit_reached)\b|exceeded your current quota|hit your usage limit/i;
38
+ function suggestedWait(text) {
39
+ const spoken = text.match(/try again in ((?:\d+(?:\.\d+)?(?:ms|h|m|s))+)/i)?.[1];
40
+ if (!spoken) return;
41
+ const unit = { h: 3_600_000, m: 60_000, s: 1000, ms: 1 };
42
+ return Math.round([...spoken.matchAll(/(\d+(?:\.\d+)?)(ms|h|m|s)/g)].reduce((sum, [, n, u]) => sum + n * unit[u], 0));
43
+ }
44
+
45
+ // The ChatGPT login gone (docs/agent-protocol.md「需要重新登录」): Codex's own words when refreshing the access token fails for good
46
+ // (its refresh token expired, was already used or revoked, or the account was logged out or switched). Its `unauthorized` kind and a
47
+ // bare 401 or 403 also cover a wrong API key or a missing permission, which logging in again does not mend, so they stay unmarked.
48
+ const loginLost = /^Your access token could not be refreshed\b[^\n]*\bsign in again\b/;
49
+
34
50
  // Native service facts, not a retry policy: Coda decides when/how often to try again. Explicit permanent kinds win over
35
51
  // generic messages (in particular, quota failures also arrive as JSON-RPC Internal error).
36
52
  export function codexFailureData(error, input) {
37
53
  const data = error.data && typeof error.data === 'object' && !Array.isArray(error.data) ? error.data : {};
38
54
  const info = data.codexErrorInfo;
39
- if (info === 'usageLimitExceeded') {
40
- const resetAt = quotaReset(error, data);
41
- return { ...data, _meta: { ...data._meta, coda: { ...data._meta?.coda,
42
- failure: { kind: 'quota_exhausted', ...(resetAt ? { resetAt } : {}) } } } };
43
- }
55
+ const reported = failure => ({ ...data, _meta: { ...data._meta, coda: { ...data._meta?.coda, failure } } });
56
+ const quota = () => { const resetAt = quotaReset(error, data); return reported({ kind: 'quota_exhausted', ...(resetAt ? { resetAt } : {}) }); };
57
+ if (info === 'usageLimitExceeded') return quota();
44
58
  const message = typeof data.message === 'string' ? data.message : typeof data.details === 'string' ? data.details : typeof error.data === 'string' ? error.data : error.message;
45
59
  let provider; try { provider = JSON.parse(message); } catch {}
46
60
  const status = provider?.status ?? (info && typeof info === 'object' ? Object.values(info)[0]?.httpStatusCode : null);
61
+ if (loginLost.test(message?.trim()))
62
+ return { ...reported({ kind: 'auth_required', login: 'ChatGPT 账号' }), ...(data.message || data.details ? {} : { details: message }) };
63
+ const accepted = data._meta?.coda?.failure?.input === 'accepted' ? 'accepted' : input;
64
+ if (status === 429 && info && typeof info === 'object' && 'httpConnectionFailed' in info) {
65
+ const text = [data.additionalDetails, message].filter(value => typeof value === 'string').join('\n');
66
+ if (providerQuota.test(text)) return quota();
67
+ const retryAfterMs = suggestedWait(text);
68
+ return { ...reported({ kind: 'service_unavailable', input: accepted, ...(retryAfterMs == null ? {} : { retryAfterMs }) }),
69
+ ...(data.message || data.details ? {} : { details: error.message }) };
70
+ }
47
71
  const permanent = ['usageLimitExceeded', 'unauthorized', 'contextWindowExceeded', 'sessionBudgetExceeded',
48
72
  'cyberPolicy', 'misalignmentPolicyViolation', 'sandboxError', 'threadRollbackFailed'].includes(info) || [401, 403].includes(status);
49
73
  const unavailableModel = provider?.type === 'error' && status === 400 && provider.error?.type === 'invalid_request_error' &&
@@ -56,8 +80,7 @@ export function codexFailureData(error, input) {
56
80
  (info === 'other' && message === 'Selected model is at capacity. Please try a different model.') ||
57
81
  (info == null && error.code === -32603 && message?.trim() === 'Internal error'));
58
82
  if (!temporary) return data;
59
- return { ...data, ...(data.message || data.details ? {} : { details: error.message }),
60
- _meta: { ...data._meta, coda: { ...data._meta?.coda, failure: { kind: 'service_unavailable', input: data._meta?.coda?.failure?.input === 'accepted' ? 'accepted' : input } } } };
83
+ return { ...reported({ kind: 'service_unavailable', input: accepted }), ...(data.message || data.details ? {} : { details: error.message }) };
61
84
  }
62
85
 
63
86
  // codex-acp 1.12 only throws quota/auth failures for plain ACP clients; other failed native turns look successful.
@@ -17,7 +17,7 @@
17
17
  "item:imageGeneration": { "shown": true, "why": "生成图片,作为工具调用" },
18
18
  "item:enteredReviewMode": { "shown": false, "why": "/review 开始的标记,没有内容;结果在 exitedReviewMode" },
19
19
  "item:exitedReviewMode": { "shown": true, "why": "/review 的结果" },
20
- "item:contextCompaction": { "shown": true, "why": "压缩上下文,作为工具调用" },
20
+ "item:contextCompaction": { "shown": true, "why": "压缩上下文,作为 compaction_update(开始 in_progress、完成 completed),不再出工具卡(compaction.mjs)" },
21
21
 
22
22
  "item:agentMessage.id": { "shown": true, "why": "作为 messageId" },
23
23
  "item:agentMessage.text": { "shown": true, "why": "正文" },
@@ -88,7 +88,7 @@
88
88
  "notification:item/reasoning/summaryTextDelta": { "shown": true, "why": "思考" },
89
89
  "notification:item/reasoning/summaryPartAdded": { "shown": true, "why": "思考的分段" },
90
90
  "notification:item/reasoning/textDelta": { "shown": true, "why": "思考" },
91
- "notification:thread/compacted": { "shown": true, "why": "压缩上下文(旧通知)" },
91
+ "notification:thread/compacted": { "shown": true, "why": "压缩上下文(旧通知;与 item 同回合出现时只报其中先到的一个,compaction.mjs)" },
92
92
  "notification:model/rerouted": { "shown": true, "why": "换了模型,作为思考" },
93
93
  "notification:model/verification": { "shown": false, "why": "codex-acp 忽略" },
94
94
  "notification:modelProvider/authRecoveryStarted": { "shown": false, "why": "模型服务的登录恢复;codex-acp 忽略" },
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "id": "codex",
4
4
  "displayName": "Codex",
5
5
  "description": "用 OpenAI Codex 跑会话",
6
- "version": "1.13.0",
6
+ "version": "1.14.0",
7
7
  "categories": [
8
8
  "Agent"
9
9
  ],