@coda-console/codex 1.10.0 → 1.12.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 +1 -1
- package/agent/account-source.mjs +2 -2
- package/agent/entry.mjs +21 -9
- package/agent/known-tools.json +38 -0
- package/agent/questions.mjs +149 -0
- package/agent/registry.json +130 -0
- package/agent/unrecognized.mjs +158 -0
- package/package.json +4 -4
- package/scripts/quota.mjs +29 -34
- package/scripts/reset.mjs +3 -3
- package/scripts/resources.mjs +7 -0
- package/scripts/panel.mjs +0 -7
package/README.md
CHANGED
package/agent/account-source.mjs
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
// `refresh: true` asks the owner to renew a rejected access token, even before its expiry.
|
|
6
6
|
// Either may answer `{ "id", "error": { "message" } }`. A source taking full ownership reports an error until an account
|
|
7
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
|
|
8
|
+
// An installed source owns the account's resources and handles `--login` for Codex's existing login entry.
|
|
9
9
|
import { spawn } from 'node:child_process';
|
|
10
10
|
import { dirname } from 'node:path';
|
|
11
11
|
import { readLines } from './lines.mjs';
|
|
@@ -28,7 +28,7 @@ export class AccountSource {
|
|
|
28
28
|
}
|
|
29
29
|
start() {
|
|
30
30
|
const { command } = this.source;
|
|
31
|
-
// As a
|
|
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
32
|
const child = spawn('/bin/sh', ['-c', command], { env: sourceEnv(this.source, this.env),
|
|
33
33
|
stdio: ['pipe', 'pipe', 'ignore'] });
|
|
34
34
|
child.stdin.on('error', () => {});
|
package/agent/entry.mjs
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
// The Codex agent as Coda starts it (the plugin's `contributes.agents`): the locked codex-acp, run in this process with Coda's
|
|
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
|
-
// and a steer that finds no turn going is answered `promptRequired` (steering.mjs);
|
|
5
|
-
//
|
|
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
|
|
6
|
+
// 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
|
|
6
7
|
// which Codex program runs, through the account bridge when another plugin chooses the account (accounts.mjs).
|
|
7
8
|
import { createRequire, registerHooks } from 'node:module';
|
|
8
9
|
import { spawnSync } from 'node:child_process';
|
|
@@ -27,6 +28,8 @@ import { explainCodexError, reportedCodexFailures } from './errors.mjs';
|
|
|
27
28
|
import { reportedCodexSleeps } from './sleep.mjs';
|
|
28
29
|
import { codexDisplayNames } from './display.mjs';
|
|
29
30
|
import { trustedCodaMcpRequests } from './mcp-policy.mjs';
|
|
31
|
+
import { CodexQuestions, shownCodexAsyncMessages } from './questions.mjs';
|
|
32
|
+
import { CodexUnrecognized, listenUnrecognized, reportedCodexUnrecognized } from './unrecognized.mjs';
|
|
30
33
|
|
|
31
34
|
const env = process.env;
|
|
32
35
|
// Coda owns the permission boundary. An explicit launch mode or later ACP selection still wins.
|
|
@@ -51,14 +54,23 @@ if (!env.CODEX_PATH && accountSource(env) && env.CODA_PLUGIN_STATE) {
|
|
|
51
54
|
|
|
52
55
|
const version = codexVersion();
|
|
53
56
|
const waits = new CodexWaits({ agentInfo: version ? { name: 'codex', version } : null }), parse = line => { try { return JSON.parse(line); } catch { return null; } };
|
|
54
|
-
const reviews = new CodexReviews(),
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
const message = parse(line);
|
|
58
|
-
if (!message || typeof message !== 'object') return;
|
|
57
|
+
const reviews = new CodexReviews(), questions = new CodexQuestions(), unrecognized = new CodexUnrecognized();
|
|
58
|
+
const say = message => process.stdout.write(`${JSON.stringify(message)}\n`);
|
|
59
|
+
const toCodex = message => {
|
|
59
60
|
const { agent, coda } = waits.fromCoda(message);
|
|
60
61
|
for (const each of agent) input.write(`${JSON.stringify(each)}\n`);
|
|
61
62
|
for (const each of coda) say(each);
|
|
63
|
+
};
|
|
64
|
+
const pass = ({ agent, coda }) => { for (const each of agent) toCodex(each); for (const each of coda) say(codexDisplayNames(explainCodexError(each))); };
|
|
65
|
+
listen(line => {
|
|
66
|
+
for (const message of waits.fromAgent(parse(line))) for (const told of unrecognized.fromAgent(message)) for (const each of reviews.fromAgent(told)) pass(questions.fromAgent(each));
|
|
67
|
+
});
|
|
68
|
+
listenUnrecognized(report => { for (const each of unrecognized.report({ ...report, sessionId: report.sessionId ?? waits.root })) say(each); });
|
|
69
|
+
readLines(process.stdin).on('line', line => {
|
|
70
|
+
const message = parse(line);
|
|
71
|
+
if (!message || typeof message !== 'object') return;
|
|
72
|
+
unrecognized.fromCoda(message);
|
|
73
|
+
pass(questions.fromCoda(message));
|
|
62
74
|
}).on('close', () => input.end());
|
|
63
75
|
|
|
64
76
|
// codex-acp as Node finds it from here (its package names dist/index.js as its main): the plugin's own dependency.
|
|
@@ -66,7 +78,7 @@ const adapter = new URL(import.meta.resolve('@agentclientprotocol/codex-acp'));
|
|
|
66
78
|
registerHooks({ load(url, context, nextLoad) {
|
|
67
79
|
const loaded = nextLoad(url, context);
|
|
68
80
|
if (url !== adapter.href) return loaded;
|
|
69
|
-
return { ...loaded, source: reportedCodexSleeps(reportedCodexFailures(codexOptionsAsShown(relayedCodexStreams(orderedCodexTitles(followCodexProcessExit(continuedCodexSubagents(
|
|
70
|
-
promptRequiredCodexSteering(instructedCodexThreads(servedCodexModels(networkedCodexDevelopment(trustedCodaMcpRequests(Buffer.from(loaded.source).toString('utf8'))))))))))))) };
|
|
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'))))))))))))))) };
|
|
71
83
|
} });
|
|
72
84
|
await import(adapter.href);
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
{
|
|
2
|
+
"functions.exec": "代码模式的入口,里面调的工具各自报成 item",
|
|
3
|
+
"functions.wait": "代码模式里等 exec 的结果",
|
|
4
|
+
"functions.exec_command": "命令,作为 commandExecution",
|
|
5
|
+
"functions.write_stdin": "写给命令的输入,作为 commandExecution",
|
|
6
|
+
"functions.request_permissions": "申请权限,作为审批卡片",
|
|
7
|
+
"functions.apply_patch": "改文件,作为 fileChange",
|
|
8
|
+
"functions.update_plan": "计划,作为 plan 更新",
|
|
9
|
+
"functions.view_image": "看图片,作为 imageView",
|
|
10
|
+
"functions.tool_search": "找延后加载的工具",
|
|
11
|
+
"functions.request_user_input": "提问,作为 item/tool/requestUserInput 的卡片",
|
|
12
|
+
"functions.request_user_input_async": "已适配:异步提问,作为这一轮的表单卡片(questions.mjs)",
|
|
13
|
+
"functions.send_user_message_async": "已适配:异步消息,照全文显示(questions.mjs)",
|
|
14
|
+
"functions.send_message_to_user_async": "已适配:同 send_user_message_async,Codex 处理它的名字",
|
|
15
|
+
"functions.list_mcp_resources": "读 MCP 资源,作为工具调用",
|
|
16
|
+
"functions.list_mcp_resource_templates": "读 MCP 资源,作为工具调用",
|
|
17
|
+
"functions.read_mcp_resource": "读 MCP 资源,作为工具调用",
|
|
18
|
+
"functions.list_available_plugins_to_install": "列出可装的 Codex 插件",
|
|
19
|
+
"functions.request_plugin_install": "装 Codex 插件",
|
|
20
|
+
"functions.get_context_remaining": "查剩下的上下文",
|
|
21
|
+
"functions.new_context": "换新的上下文窗口,作为压缩上下文",
|
|
22
|
+
"functions.wait_for_environment": "等远端执行环境",
|
|
23
|
+
"clock.sleep": "主动等待,作为等待项(sleep.mjs)",
|
|
24
|
+
"clock.curr_time": "读时间",
|
|
25
|
+
"collaboration.spawn_agent": "子 Agent,作为 subAgentActivity",
|
|
26
|
+
"collaboration.send_message": "子 Agent,作为 subAgentActivity",
|
|
27
|
+
"collaboration.followup_task": "子 Agent,作为 subAgentActivity(subagents.mjs)",
|
|
28
|
+
"collaboration.interrupt_agent": "子 Agent,作为 subAgentActivity",
|
|
29
|
+
"collaboration.list_agents": "子 Agent,作为 subAgentActivity",
|
|
30
|
+
"collaboration.wait_agent": "子 Agent,作为 subAgentActivity",
|
|
31
|
+
"multi_agent_v1.spawn_agent": "旧式子 Agent,作为 collabAgentToolCall",
|
|
32
|
+
"multi_agent_v1.send_input": "旧式子 Agent,作为 collabAgentToolCall",
|
|
33
|
+
"multi_agent_v1.wait_agent": "旧式子 Agent,作为 collabAgentToolCall",
|
|
34
|
+
"multi_agent_v1.resume_agent": "旧式子 Agent,作为 collabAgentToolCall",
|
|
35
|
+
"multi_agent_v1.close_agent": "旧式子 Agent,作为 collabAgentToolCall",
|
|
36
|
+
"web_search": "OpenAI 托管的联网搜索,作为 webSearch",
|
|
37
|
+
"image_generation": "OpenAI 托管的生成图片,作为 imageGeneration"
|
|
38
|
+
}
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
// Codex's messages to the user beside a turn (`send_user_message_async`, `request_user_input_async`, which OpenAI's model
|
|
2
|
+
// catalogue gives the model whatever Codex runs): each is a completed agentMessage with `delivery: "async"`, and `questions`
|
|
3
|
+
// when it asks, said without deltas. codex-acp 1.12.0 shows an agent message only from its deltas; the patch here says the
|
|
4
|
+
// text of one it streamed nothing of, with its questions under `_meta.coda.asyncQuestions` (through unrecognized.mjs, which
|
|
5
|
+
// says the text of any other such message too). Codex's turn goes on without
|
|
6
|
+
// the answer, which reaches it as a later user message. CodexQuestions asks Coda one form per call, the way Claude's
|
|
7
|
+
// AskUserQuestion is asked (docs/agent-protocol.md「Claude 的提问」), and keeps Coda's turn going until every card of it has
|
|
8
|
+
// its answer: given to Codex by steering while codex-acp's prompt runs, else as a prompt of the entry's own, whose output
|
|
9
|
+
// and end are the same Coda turn's. Fails loudly once the adapter changes.
|
|
10
|
+
const record = value => value && typeof value === 'object' && !Array.isArray(value);
|
|
11
|
+
const none = { agent: [], coda: [] };
|
|
12
|
+
export const OTHER = 'coda:other';
|
|
13
|
+
// The ids of what the entry asks itself, of Coda (the cards) and of codex-acp (steering, prompts).
|
|
14
|
+
const OWN = 'coda-codex-question:';
|
|
15
|
+
const own = message => !('method' in message) && typeof message.id === 'string' && message.id.startsWith(OWN);
|
|
16
|
+
|
|
17
|
+
// The update said of a completed agent message: none unless it is async; its text unless that was streamed.
|
|
18
|
+
export function codexAsyncMessage(item, streamed) {
|
|
19
|
+
const questions = item.questions?.length ? item.questions : null;
|
|
20
|
+
if (item.delivery !== 'async' || (streamed && !questions)) return null;
|
|
21
|
+
return { sessionUpdate: 'agent_message_chunk', messageId: item.id, content: { type: 'text', text: streamed ? '' : item.text },
|
|
22
|
+
...(questions ? { _meta: { coda: { asyncQuestions: questions } } } : {}) };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const patches = [
|
|
26
|
+
[' agentMessagePhases = /* @__PURE__ */ new Map();\n', before => `${before} codaStreamedMessages = /* @__PURE__ */ new Set();\n`],
|
|
27
|
+
[' async createTextEvent(event) {\n', before => `${before} this.codaStreamedMessages.add(event.itemId);\n`],
|
|
28
|
+
[` return this.subagents.legacyCollaborationCompleted(event.item);
|
|
29
|
+
case "agentMessage":
|
|
30
|
+
this.rememberAgentMessagePhase(event.item);
|
|
31
|
+
return null;`, before => before.replace('return null;', 'return codexAgentMessage(event.item, this.codaStreamedMessages.delete(event.item.id));')],
|
|
32
|
+
];
|
|
33
|
+
export function shownCodexAsyncMessages(source) {
|
|
34
|
+
for (const [before, after] of patches) {
|
|
35
|
+
if (source.split(before).length !== 2) throw new Error('codex-acp async message patch no longer matches the locked adapter');
|
|
36
|
+
source = source.replace(before, after(before));
|
|
37
|
+
}
|
|
38
|
+
return `import { codexAgentMessage } from ${JSON.stringify(new URL('./unrecognized.mjs', import.meta.url).href)};\n${source.replace(/^#![^\n]*\n/, '')}`;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// One call's questions as a form: question i is the required field `q{i}`, its options a choice with one more for an answer
|
|
42
|
+
// written in `q{i}_other`; without options it is text.
|
|
43
|
+
export function questionForm(sessionId, questions) {
|
|
44
|
+
const properties = {};
|
|
45
|
+
questions.forEach((q, i) => {
|
|
46
|
+
if (!q.options?.length) { properties[`q${i}`] = { type: 'string', title: q.title }; return; }
|
|
47
|
+
properties[`q${i}`] = { type: 'string', title: q.title,
|
|
48
|
+
oneOf: [...q.options.map(option => ({ const: option, title: option })), { const: OTHER, title: '其他(写在下面)' }] };
|
|
49
|
+
properties[`q${i}_other`] = { type: 'string', title: '其他' };
|
|
50
|
+
});
|
|
51
|
+
return { sessionId, mode: 'form', message: 'Codex 需要你的回答', requestedSchema: { type: 'object', properties, required: questions.map((_, i) => `q${i}`) } };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// What the user said to a card, as the message Codex is told, a line a question.
|
|
55
|
+
export function answerText(questions, response) {
|
|
56
|
+
const content = response?.action === 'accept' && record(response.content) ? response.content : null;
|
|
57
|
+
return questions.map((q, i) => {
|
|
58
|
+
if (!content) return `用户没有回答「${q.title}」`;
|
|
59
|
+
const value = content[`q${i}`], other = String(content[`q${i}_other`] ?? '').trim();
|
|
60
|
+
return `回答你的提问「${q.title}」:${value === OTHER ? other || '其他' : value}`;
|
|
61
|
+
}).join('\n');
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export class CodexQuestions {
|
|
65
|
+
constructor() {
|
|
66
|
+
// Coda's turn: its prompt, the codex-acp prompt running in it, its cards and steering in flight by id, the answers
|
|
67
|
+
// waiting for codex-acp's prompt to end, codex-acp's last reply, and whether a cancel withdrew what it waited for.
|
|
68
|
+
this.turn = null; this.next = 0;
|
|
69
|
+
}
|
|
70
|
+
// What Coda says: `agent`, what codex-acp is told; `coda`, what Coda is told here.
|
|
71
|
+
fromCoda(message) {
|
|
72
|
+
const turn = this.turn;
|
|
73
|
+
if (message.method === 'session/prompt') {
|
|
74
|
+
this.turn = { id: message.id, sessionId: message.params?.sessionId, running: message.id, cards: new Map(), steers: new Map(), queued: [], reply: null, cancelled: false };
|
|
75
|
+
return { agent: [message], coda: [] };
|
|
76
|
+
}
|
|
77
|
+
if (own(message)) {
|
|
78
|
+
const questions = turn?.cards.get(message.id);
|
|
79
|
+
if (!questions) return none;
|
|
80
|
+
turn.cards.delete(message.id);
|
|
81
|
+
return this.deliver(answerText(questions, message.result));
|
|
82
|
+
}
|
|
83
|
+
if (!turn) return { agent: [message], coda: [] };
|
|
84
|
+
// Unanswered cards are withdrawn; the turn ends once codex-acp's prompt does, or now when none runs, as cancelled when
|
|
85
|
+
// it waited for any.
|
|
86
|
+
if (message.method === 'session/cancel') {
|
|
87
|
+
const withdrawn = [...turn.cards.keys()].map(id => ({ jsonrpc: '2.0', method: '$/cancel_request', params: { id } }));
|
|
88
|
+
turn.cancelled ||= turn.cards.size + turn.steers.size + turn.queued.length > 0;
|
|
89
|
+
turn.cards.clear(); turn.steers.clear(); turn.queued = [];
|
|
90
|
+
if (turn.running) return { agent: [message], coda: withdrawn };
|
|
91
|
+
this.turn = null;
|
|
92
|
+
return { agent: [message], coda: [...withdrawn, { jsonrpc: '2.0', id: turn.id, result: { stopReason: 'cancelled' } }] };
|
|
93
|
+
}
|
|
94
|
+
// Codex has stopped while its cards wait: the message runs as the turn's next prompt.
|
|
95
|
+
if (message.method === '_session/steering' && !turn.running) {
|
|
96
|
+
return { agent: [this.prompt(message.params.prompt)], coda: [{ jsonrpc: '2.0', id: message.id, result: { outcome: 'injected' } }] };
|
|
97
|
+
}
|
|
98
|
+
return { agent: [message], coda: [] };
|
|
99
|
+
}
|
|
100
|
+
// What codex-acp says, as said to Coda.
|
|
101
|
+
fromAgent(message) {
|
|
102
|
+
const turn = this.turn;
|
|
103
|
+
if ('id' in message && !('method' in message)) {
|
|
104
|
+
if (turn && message.id === turn.running) { turn.running = null; turn.reply = message; return this.settle(); }
|
|
105
|
+
if (turn?.steers.has(message.id)) {
|
|
106
|
+
const text = turn.steers.get(message.id);
|
|
107
|
+
turn.steers.delete(message.id);
|
|
108
|
+
if (message.result?.outcome !== 'injected') turn.queued.push(text);
|
|
109
|
+
return this.settle();
|
|
110
|
+
}
|
|
111
|
+
return own(message) ? none : { agent: [], coda: [message] };
|
|
112
|
+
}
|
|
113
|
+
const u = message.params?.update, questions = u?._meta?.coda?.asyncQuestions;
|
|
114
|
+
if (message.method !== 'session/update' || !questions) return { agent: [], coda: [message] };
|
|
115
|
+
const { _meta, ...update } = u;
|
|
116
|
+
const said = update.content.text ? [{ ...message, params: { ...message.params, update } }] : [];
|
|
117
|
+
if (!turn) return { agent: [], coda: said };
|
|
118
|
+
const id = `${OWN}${this.next++}`;
|
|
119
|
+
turn.cards.set(id, questions);
|
|
120
|
+
return { agent: [], coda: [...said, { jsonrpc: '2.0', id, method: 'elicitation/create', params: questionForm(turn.sessionId, questions) }] };
|
|
121
|
+
}
|
|
122
|
+
// An answer goes into the running prompt's turn, else runs as the next prompt.
|
|
123
|
+
deliver(text) {
|
|
124
|
+
const turn = this.turn;
|
|
125
|
+
if (!turn.running) { turn.queued.push(text); return this.settle(); }
|
|
126
|
+
const id = `${OWN}${this.next++}`;
|
|
127
|
+
turn.steers.set(id, text);
|
|
128
|
+
return { agent: [{ jsonrpc: '2.0', id, method: '_session/steering',
|
|
129
|
+
params: { sessionId: turn.sessionId, prompt: [{ type: 'text', text }], _meta: { steering: { idleBehavior: 'promptRequired' } } } }], coda: [] };
|
|
130
|
+
}
|
|
131
|
+
// With no prompt running: the answers waiting run as one; else Coda's turn ends with the last reply once nothing waits.
|
|
132
|
+
settle() {
|
|
133
|
+
const turn = this.turn;
|
|
134
|
+
if (turn.running) return none;
|
|
135
|
+
if (turn.queued.length) {
|
|
136
|
+
const text = turn.queued.join('\n');
|
|
137
|
+
turn.queued = [];
|
|
138
|
+
return { agent: [this.prompt([{ type: 'text', text }])], coda: [] };
|
|
139
|
+
}
|
|
140
|
+
if (turn.cards.size || turn.steers.size) return none;
|
|
141
|
+
this.turn = null;
|
|
142
|
+
return { agent: [], coda: [turn.cancelled ? { jsonrpc: '2.0', id: turn.id, result: { stopReason: 'cancelled' } } : { ...turn.reply, id: turn.id }] };
|
|
143
|
+
}
|
|
144
|
+
prompt(prompt) {
|
|
145
|
+
const id = `${OWN}${this.next++}`;
|
|
146
|
+
this.turn.running = id;
|
|
147
|
+
return { jsonrpc: '2.0', id, method: 'session/prompt', params: { sessionId: this.turn.sessionId, prompt } };
|
|
148
|
+
}
|
|
149
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
{
|
|
2
|
+
"item:userMessage": { "shown": false, "why": "用户自己发的消息,Coda 已经显示;codex-acp 忽略" },
|
|
3
|
+
"item:hookPrompt": { "shown": false, "why": "hook 注入给模型的提示,不是给用户看的;codex-acp 忽略" },
|
|
4
|
+
"item:agentMessage": { "shown": true, "why": "回复:增量逐段转;没收到增量的照完成时的全文显示(unrecognized.mjs)" },
|
|
5
|
+
"item:functionCallOutput": { "shown": false, "why": "工具的原始输出,随各自的工具调用显示;codex-acp 忽略" },
|
|
6
|
+
"item:plan": { "shown": true, "why": "计划,作为 plan 更新" },
|
|
7
|
+
"item:reasoning": { "shown": true, "why": "思考:增量,或完成时的摘要" },
|
|
8
|
+
"item:commandExecution": { "shown": true, "why": "命令,作为工具调用;转入后台的另报等待项(waits.mjs)" },
|
|
9
|
+
"item:fileChange": { "shown": true, "why": "改文件,作为带 diff 的工具调用" },
|
|
10
|
+
"item:mcpToolCall": { "shown": true, "why": "MCP 工具,作为工具调用" },
|
|
11
|
+
"item:dynamicToolCall": { "shown": true, "why": "动态工具,作为工具调用" },
|
|
12
|
+
"item:collabAgentToolCall": { "shown": true, "why": "旧式的子 Agent 协作,作为子 Agent" },
|
|
13
|
+
"item:subAgentActivity": { "shown": true, "why": "子 Agent 的活动,作为子 Agent" },
|
|
14
|
+
"item:webSearch": { "shown": true, "why": "联网搜索,作为工具调用" },
|
|
15
|
+
"item:imageView": { "shown": true, "why": "看图片,作为工具调用" },
|
|
16
|
+
"item:sleep": { "shown": true, "why": "clock.sleep,入口报成等待项(sleep.mjs)" },
|
|
17
|
+
"item:imageGeneration": { "shown": true, "why": "生成图片,作为工具调用" },
|
|
18
|
+
"item:enteredReviewMode": { "shown": false, "why": "/review 开始的标记,没有内容;结果在 exitedReviewMode" },
|
|
19
|
+
"item:exitedReviewMode": { "shown": true, "why": "/review 的结果" },
|
|
20
|
+
"item:contextCompaction": { "shown": true, "why": "压缩上下文,作为工具调用" },
|
|
21
|
+
|
|
22
|
+
"item:agentMessage.id": { "shown": true, "why": "作为 messageId" },
|
|
23
|
+
"item:agentMessage.text": { "shown": true, "why": "正文" },
|
|
24
|
+
"item:agentMessage.phase": { "shown": true, "why": "随增量作为 _meta.codex.phase,取值见下" },
|
|
25
|
+
"item:agentMessage.memoryCitation": { "shown": false, "why": "记忆的出处,codex-acp 不显示" },
|
|
26
|
+
"item:agentMessage.delivery": { "shown": true, "why": "送达方式,取值见下;没有就是逐段发增量的普通回复" },
|
|
27
|
+
"item:agentMessage.questions": { "shown": true, "why": "异步提问,作为这一轮的表单卡片(questions.mjs)" },
|
|
28
|
+
"item:agentMessage.delivery=async": { "shown": true, "why": "send_user_message_async、request_user_input_async:不发增量,照全文显示(questions.mjs)" },
|
|
29
|
+
"item:agentMessage.phase=commentary": { "shown": true, "why": "过程中的说明,随增量转" },
|
|
30
|
+
"item:agentMessage.phase=partial_answer": { "shown": true, "why": "部分回答,随增量转" },
|
|
31
|
+
"item:agentMessage.phase=final_answer": { "shown": true, "why": "最终回答,随增量转" },
|
|
32
|
+
|
|
33
|
+
"notification:error": { "shown": true, "why": "失败,作为这一轮的错误或会话的失败" },
|
|
34
|
+
"notification:thread/started": { "shown": false, "why": "线程由 thread/start、thread/resume 的答复建立;codex-acp 忽略" },
|
|
35
|
+
"notification:thread/status/changed": { "shown": true, "why": "线程状态,作为 session_info_update 的 _meta.codex" },
|
|
36
|
+
"notification:thread/readState/changed": { "shown": false, "why": "Codex 应用的已读状态,与会话内容无关;codex-acp 不处理" },
|
|
37
|
+
"notification:thread/archived": { "shown": true, "why": "作为 session_info_update 的 _meta.codex" },
|
|
38
|
+
"notification:thread/deleted": { "shown": false, "why": "删除由客户端发起;codex-acp 忽略" },
|
|
39
|
+
"notification:thread/unarchived": { "shown": true, "why": "作为 session_info_update 的 _meta.codex" },
|
|
40
|
+
"notification:thread/closed": { "shown": true, "why": "作为 session_info_update 的 _meta.codex" },
|
|
41
|
+
"notification:thread/reverted": { "shown": false, "why": "回退由客户端发起;codex-acp 忽略" },
|
|
42
|
+
"notification:skills/changed": { "shown": false, "why": "codex-acp 每轮开始前自己刷新 skills;忽略" },
|
|
43
|
+
"notification:thread/name/updated": { "shown": true, "why": "会话标题" },
|
|
44
|
+
"notification:thread/attachment/updated": { "shown": false, "why": "Codex 应用的线程附件;codex-acp 不处理" },
|
|
45
|
+
"notification:thread/goal/updated": { "shown": true, "why": "目标" },
|
|
46
|
+
"notification:thread/prediction/updated": { "shown": false, "why": "Codex 应用的预测;codex-acp 不处理" },
|
|
47
|
+
"notification:thread/goal/cleared": { "shown": true, "why": "目标" },
|
|
48
|
+
"notification:thread/queue/changed": { "shown": false, "why": "排队的消息由 Coda 自己管;codex-acp 忽略" },
|
|
49
|
+
"notification:project/changed": { "shown": false, "why": "Codex 应用的项目;codex-acp 忽略" },
|
|
50
|
+
"notification:thread/project/updated": { "shown": false, "why": "Codex 应用的项目;codex-acp 忽略" },
|
|
51
|
+
"notification:thread/environment/connected": { "shown": false, "why": "远端执行环境;codex-acp 忽略" },
|
|
52
|
+
"notification:thread/environment/disconnected": { "shown": false, "why": "远端执行环境;codex-acp 忽略" },
|
|
53
|
+
"notification:thread/settings/updated": { "shown": false, "why": "codex-acp 记下线程设置(协作模式),不显示" },
|
|
54
|
+
"notification:thread/tokenUsage/updated": { "shown": true, "why": "用量,作为 usage_update" },
|
|
55
|
+
"notification:turn/started": { "shown": false, "why": "codex-acp 记下当前的轮次" },
|
|
56
|
+
"notification:hook/started": { "shown": false, "why": "hook 的运行;codex-acp 忽略" },
|
|
57
|
+
"notification:turn/completed": { "shown": true, "why": "这一轮结束,作为 session/prompt 的答复" },
|
|
58
|
+
"notification:hook/completed": { "shown": false, "why": "hook 的运行;codex-acp 忽略" },
|
|
59
|
+
"notification:turn/diff/updated": { "shown": true, "why": "这一轮的文件改动报告" },
|
|
60
|
+
"notification:turn/plan/updated": { "shown": true, "why": "计划" },
|
|
61
|
+
"notification:item/started": { "shown": true, "why": "按 item 类型,见 item:*" },
|
|
62
|
+
"notification:item/autoApprovalReview/started": { "shown": true, "why": "自动审核,归到它审的调用(reviews.mjs)" },
|
|
63
|
+
"notification:item/autoApprovalReview/completed": { "shown": true, "why": "自动审核,归到它审的调用(reviews.mjs)" },
|
|
64
|
+
"notification:autoApprovalReview/strictReviewRequired": { "shown": false, "why": "codex-acp 忽略" },
|
|
65
|
+
"notification:item/completed": { "shown": true, "why": "按 item 类型,见 item:*" },
|
|
66
|
+
"notification:item/agentMessage/delta": { "shown": true, "why": "回复的增量" },
|
|
67
|
+
"notification:item/plan/delta": { "shown": true, "why": "计划的增量" },
|
|
68
|
+
"notification:command/exec/outputDelta": { "shown": false, "why": "codex-acp 不用 command/exec" },
|
|
69
|
+
"notification:process/outputDelta": { "shown": false, "why": "codex-acp 不用 process/spawn" },
|
|
70
|
+
"notification:process/exited": { "shown": false, "why": "codex-acp 不用 process/spawn" },
|
|
71
|
+
"notification:item/commandExecution/outputDelta": { "shown": true, "why": "命令的输出" },
|
|
72
|
+
"notification:item/commandExecution/terminalInteraction": { "shown": true, "why": "写给命令的输入" },
|
|
73
|
+
"notification:item/fileChange/outputDelta": { "shown": false, "why": "已弃用的 apply_patch 输出;改动在 item 完成时报" },
|
|
74
|
+
"notification:item/fileChange/patchUpdated": { "shown": false, "why": "改动在 item 开始与完成时报;codex-acp 忽略" },
|
|
75
|
+
"notification:serverRequest/resolved": { "shown": false, "why": "codex-acp 用来清掉失效的审批状态" },
|
|
76
|
+
"notification:item/mcpToolCall/progress": { "shown": true, "why": "MCP 工具的进度" },
|
|
77
|
+
"notification:mcpServer/oauthLogin/completed": { "shown": false, "why": "MCP 登录流程内部等它" },
|
|
78
|
+
"notification:mcpServer/startupStatus/updated": { "shown": false, "why": "codex-acp 等 MCP 启动时用" },
|
|
79
|
+
"notification:mcpServer/event/stream/notification": { "shown": false, "why": "codex-acp 忽略" },
|
|
80
|
+
"notification:account/updated": { "shown": false, "why": "codex-acp 刷新账号状态" },
|
|
81
|
+
"notification:account/gatewayOAuth/changed": { "shown": false, "why": "网关的登录;codex-acp 不处理" },
|
|
82
|
+
"notification:account/rateLimits/updated": { "shown": true, "why": "额度,随 session/prompt 答复的 _meta" },
|
|
83
|
+
"notification:app/list/updated": { "shown": false, "why": "ChatGPT 应用列表;codex-acp 忽略" },
|
|
84
|
+
"notification:remoteControl/status/changed": { "shown": false, "why": "远程控制;codex-acp 忽略" },
|
|
85
|
+
"notification:externalAgentConfig/import/progress": { "shown": false, "why": "导入别的 Agent 的设置;codex-acp 忽略" },
|
|
86
|
+
"notification:externalAgentConfig/import/completed": { "shown": false, "why": "导入别的 Agent 的设置;codex-acp 忽略" },
|
|
87
|
+
"notification:fs/changed": { "shown": false, "why": "文件监视;codex-acp 忽略" },
|
|
88
|
+
"notification:item/reasoning/summaryTextDelta": { "shown": true, "why": "思考" },
|
|
89
|
+
"notification:item/reasoning/summaryPartAdded": { "shown": true, "why": "思考的分段" },
|
|
90
|
+
"notification:item/reasoning/textDelta": { "shown": true, "why": "思考" },
|
|
91
|
+
"notification:thread/compacted": { "shown": true, "why": "压缩上下文(旧通知)" },
|
|
92
|
+
"notification:model/rerouted": { "shown": true, "why": "换了模型,作为思考" },
|
|
93
|
+
"notification:model/verification": { "shown": false, "why": "codex-acp 忽略" },
|
|
94
|
+
"notification:modelProvider/authRecoveryStarted": { "shown": false, "why": "模型服务的登录恢复;codex-acp 忽略" },
|
|
95
|
+
"notification:modelProvider/authRecoveryCompleted": { "shown": false, "why": "模型服务的登录恢复;codex-acp 忽略" },
|
|
96
|
+
"notification:turn/moderationMetadata": { "shown": false, "why": "codex-acp 忽略" },
|
|
97
|
+
"notification:model/safetyBuffering/updated": { "shown": false, "why": "codex-acp 忽略" },
|
|
98
|
+
"notification:warning": { "shown": true, "why": "警告" },
|
|
99
|
+
"notification:guardianWarning": { "shown": false, "why": "自动审核的警告;codex-acp 忽略" },
|
|
100
|
+
"notification:deprecationNotice": { "shown": true, "why": "弃用提示" },
|
|
101
|
+
"notification:configWarning": { "shown": true, "why": "配置的警告" },
|
|
102
|
+
"notification:fuzzyFileSearch/sessionUpdated": { "shown": true, "why": "找文件,作为工具调用" },
|
|
103
|
+
"notification:fuzzyFileSearch/sessionCompleted": { "shown": true, "why": "找文件,作为工具调用" },
|
|
104
|
+
"notification:thread/realtime/started": { "shown": false, "why": "实时语音;codex-acp 忽略" },
|
|
105
|
+
"notification:thread/realtime/itemAdded": { "shown": false, "why": "实时语音;codex-acp 忽略" },
|
|
106
|
+
"notification:thread/realtime/item/started": { "shown": false, "why": "实时语音;codex-acp 忽略" },
|
|
107
|
+
"notification:thread/realtime/item/transcript/delta": { "shown": false, "why": "实时语音;codex-acp 忽略" },
|
|
108
|
+
"notification:thread/realtime/item/completed": { "shown": false, "why": "实时语音;codex-acp 忽略" },
|
|
109
|
+
"notification:thread/realtime/transcript/delta": { "shown": false, "why": "实时语音;codex-acp 忽略" },
|
|
110
|
+
"notification:thread/realtime/transcript/done": { "shown": false, "why": "实时语音;codex-acp 忽略" },
|
|
111
|
+
"notification:thread/realtime/outputAudio/delta": { "shown": false, "why": "实时语音;codex-acp 忽略" },
|
|
112
|
+
"notification:thread/realtime/sdp": { "shown": false, "why": "实时语音;codex-acp 忽略" },
|
|
113
|
+
"notification:thread/realtime/error": { "shown": false, "why": "实时语音;codex-acp 忽略" },
|
|
114
|
+
"notification:thread/realtime/closed": { "shown": false, "why": "实时语音;codex-acp 忽略" },
|
|
115
|
+
"notification:windows/worldWritableWarning": { "shown": false, "why": "Windows 沙箱;codex-acp 忽略" },
|
|
116
|
+
"notification:windowsSandbox/setupCompleted": { "shown": false, "why": "Windows 沙箱;codex-acp 忽略" },
|
|
117
|
+
"notification:account/login/completed": { "shown": false, "why": "登录流程内部等它" },
|
|
118
|
+
|
|
119
|
+
"request:item/commandExecution/requestApproval": { "shown": true, "why": "命令的审批卡片" },
|
|
120
|
+
"request:item/fileChange/requestApproval": { "shown": true, "why": "改文件的审批卡片" },
|
|
121
|
+
"request:item/tool/requestUserInput": { "shown": true, "why": "request_user_input 的提问卡片" },
|
|
122
|
+
"request:mcpServer/elicitation/request": { "shown": true, "why": "MCP 的表单或审批卡片" },
|
|
123
|
+
"request:item/permissions/requestApproval": { "shown": true, "why": "申请权限的审批卡片" },
|
|
124
|
+
"request:item/tool/call": { "shown": false, "why": "codex-acp 不登记动态工具,Codex 不会发;发了回 MethodNotFound" },
|
|
125
|
+
"request:account/chatgptAuthTokens/refresh": { "shown": false, "why": "账号桥接(accounts.mjs)自己答,到不了 codex-acp;没接账号来源时 Codex 不发" },
|
|
126
|
+
"request:attestation/generate": { "shown": false, "why": "codex-acp 不处理,回 MethodNotFound" },
|
|
127
|
+
"request:currentTime/read": { "shown": false, "why": "codex-acp 不处理,回 MethodNotFound" },
|
|
128
|
+
"request:applyPatchApproval": { "shown": false, "why": "旧接口开的轮次才用;codex-acp 只用 turn/start" },
|
|
129
|
+
"request:execCommandApproval": { "shown": false, "why": "旧接口开的轮次才用;codex-acp 只用 turn/start" }
|
|
130
|
+
}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
// What of Codex the entry has not adapted, told to Coda as `_coda/unrecognized` (docs/agent-protocol.md「没适配的东西」) when
|
|
2
|
+
// Coda takes it (`_meta.coda.unrecognized` of its capabilities), once a session and name. Everything the locked Codex's
|
|
3
|
+
// app-server can say (its item types, the fields of an agent message and the values of those that change what it means, its
|
|
4
|
+
// notifications and requests) is in registry.json, each shown to Coda or not, and why; scripts/check-codex-protocol.mjs fails
|
|
5
|
+
// an upgrade of Codex until what the new one adds is there. At run time the patched codex-acp tells what reaches it
|
|
6
|
+
// unregistered: an item, its text shown when it has some; an agent message whose text came without deltas, shown from its text;
|
|
7
|
+
// a notification; a request, refused as before. Once a turn of a thread it opened has ended, the native tools Codex gave the
|
|
8
|
+
// model (`additional_tools` in the thread's rollout) are checked against known-tools.json, the user's MCP tools aside, until
|
|
9
|
+
// they are found. Fails loudly once the adapter changes.
|
|
10
|
+
import { readFileSync } from 'node:fs';
|
|
11
|
+
import { readFile } from 'node:fs/promises';
|
|
12
|
+
import { codexAsyncMessage } from './questions.mjs';
|
|
13
|
+
|
|
14
|
+
const json = name => JSON.parse(readFileSync(new URL(name, import.meta.url), 'utf8'));
|
|
15
|
+
const registry = json('./registry.json'), known = json('./known-tools.json');
|
|
16
|
+
|
|
17
|
+
const record = value => value && typeof value === 'object' && !Array.isArray(value);
|
|
18
|
+
const registered = name => Object.hasOwn(registry, name);
|
|
19
|
+
// The fields of an agent message whose values are registered one by one.
|
|
20
|
+
export const VALUED = ['delivery', 'phase'];
|
|
21
|
+
// An agent message's text shown though nothing of it came as deltas, for no reason registered.
|
|
22
|
+
const UNSTREAMED = 'item:agentMessage.unstreamed';
|
|
23
|
+
|
|
24
|
+
// What codex-acp tells here rides on the update it says (`_meta.coda.unrecognized`), alone on a session_info_update when there
|
|
25
|
+
// is none; what it cannot say of a session reaches the entry's listener.
|
|
26
|
+
const told = (update, reports) => ({ ...update, _meta: { ...update._meta, coda: { ...update._meta?.coda, unrecognized: reports } } });
|
|
27
|
+
const output = (name, lost, detail) => ({ kind: 'output', name, lost, ...(detail ? { detail } : {}) });
|
|
28
|
+
let heard = () => {};
|
|
29
|
+
export const listenUnrecognized = listener => { heard = listener; };
|
|
30
|
+
|
|
31
|
+
// An item of a type codex-acp does not handle, as it completes: its text, if it has any, said as the agent's.
|
|
32
|
+
export function codexUnrecognizedItem(item) {
|
|
33
|
+
const name = `item:${item.type}`;
|
|
34
|
+
if (registered(name)) return null;
|
|
35
|
+
const text = [item.text, item.message, item.summary].find(value => typeof value === 'string' && value.trim());
|
|
36
|
+
if (!text) return told({ sessionUpdate: 'session_info_update' }, [output(name, true, `Codex 发来一项「${item.type}」,入口还不认识,没有显示`)]);
|
|
37
|
+
return told({ sessionUpdate: 'agent_message_chunk', messageId: item.id, content: { type: 'text', text } }, [output(name, false)]);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// A completed agent message, after its deltas (`streamed`): an async one as questions.mjs says it; another whose text came
|
|
41
|
+
// without deltas said from its text; what of it is unregistered, told.
|
|
42
|
+
export function codexAgentMessage(item, streamed) {
|
|
43
|
+
const names = [
|
|
44
|
+
...Object.keys(item).filter(field => field !== 'type' && item[field] != null && !registered(`item:agentMessage.${field}`)).map(field => `item:agentMessage.${field}`),
|
|
45
|
+
...VALUED.filter(field => typeof item[field] === 'string').map(field => `item:agentMessage.${field}=${item[field]}`).filter(name => !registered(name)),
|
|
46
|
+
];
|
|
47
|
+
const async = codexAsyncMessage(item, streamed);
|
|
48
|
+
if (async || streamed || !item.text) {
|
|
49
|
+
return names.length ? told(async ?? { sessionUpdate: 'session_info_update' }, names.map(name => output(name, false))) : async;
|
|
50
|
+
}
|
|
51
|
+
return told({ sessionUpdate: 'agent_message_chunk', messageId: item.id, content: { type: 'text', text: item.text } },
|
|
52
|
+
(names.length ? names : [UNSTREAMED]).map(name => output(name, false)));
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// A notification codex-acp does not handle.
|
|
56
|
+
export function codexUnrecognizedNotification(method) {
|
|
57
|
+
const name = `notification:${method}`;
|
|
58
|
+
return registered(name) ? null : told({ sessionUpdate: 'session_info_update' }, [output(name, false)]);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// A request of Codex codex-acp has no handler for, still refused: of the thread it names, else of the session.
|
|
62
|
+
export function codexUnrecognizedRequest(method, params) {
|
|
63
|
+
const name = `request:${method}`;
|
|
64
|
+
if (registered(name)) return;
|
|
65
|
+
heard({ sessionId: typeof params?.threadId === 'string' ? params.threadId : null,
|
|
66
|
+
...output(name, true, `Codex 请求了「${method}」,入口还不认识,回了不支持`) });
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Where the rollout of each thread codex-acp started or resumed is (thread/start, thread/resume, as answered), and the threads
|
|
70
|
+
// whose tools have been read or are being read.
|
|
71
|
+
const rollouts = new Map(), read = new Set();
|
|
72
|
+
export function codexThread(response) {
|
|
73
|
+
if (typeof response?.thread?.path === 'string') rollouts.set(response.thread.id, response.thread.path);
|
|
74
|
+
return response;
|
|
75
|
+
}
|
|
76
|
+
export function codexTurnCompleted(threadId) {
|
|
77
|
+
const path = rollouts.get(threadId);
|
|
78
|
+
if (!path || read.has(threadId)) return;
|
|
79
|
+
read.add(threadId);
|
|
80
|
+
readFile(path, 'utf8').then(text => {
|
|
81
|
+
const tools = rolloutTools(text);
|
|
82
|
+
if (!tools) { read.delete(threadId); return; }
|
|
83
|
+
for (const tool of tools) if (!Object.hasOwn(known, tool)) heard({ sessionId: threadId, kind: 'tool', name: `tool:${tool}`, lost: false });
|
|
84
|
+
}, () => read.delete(threadId));
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// The native tools a rollout gave the model, `namespace.name` (Codex's own namespace for one outside any is `functions`; a
|
|
88
|
+
// hosted tool, which has no name, by its type); none before it gave any. MCP tools (`mcp__<server>`) are the user's.
|
|
89
|
+
export function rolloutTools(text) {
|
|
90
|
+
let tools = null;
|
|
91
|
+
for (const line of text.split('\n')) {
|
|
92
|
+
if (!line.includes('"additional_tools"')) continue;
|
|
93
|
+
let entry; try { entry = JSON.parse(line); } catch { continue; }
|
|
94
|
+
if (entry.type !== 'response_item' || entry.payload?.type !== 'additional_tools' || !Array.isArray(entry.payload.tools)) continue;
|
|
95
|
+
tools ??= new Set();
|
|
96
|
+
for (const tool of entry.payload.tools) {
|
|
97
|
+
if (tool.type !== 'namespace') tools.add(tool.name ? `functions.${tool.name}` : tool.type);
|
|
98
|
+
else if (!tool.name.startsWith('mcp__')) for (const each of tool.tools ?? []) tools.add(`${tool.name}.${each.name}`);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
return tools;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const patches = [
|
|
105
|
+
// Each item type codex-acp knows has its case; one it does not falls through.
|
|
106
|
+
[' case "enteredReviewMode":\n return null;\n }\n }\n rememberAgentMessagePhase(item) {',
|
|
107
|
+
before => before.replace(' }\n }', ' default:\n return codexUnrecognizedItem(event.item);\n }\n }')],
|
|
108
|
+
[' case "autoApprovalReview/strictReviewRequired":\n return null;\n }\n }\n createCodexSessionInfoUpdate(codexMetadata) {',
|
|
109
|
+
before => before.replace(' }\n }', ' default:\n return codexUnrecognizedNotification(notification.method);\n }\n }')],
|
|
110
|
+
[' case "turn/completed":\n await this.flushPendingPlanUpdates();\n', before => `${before} codexTurnCompleted(notification.params.threadId);\n`],
|
|
111
|
+
// vscode-jsonrpc refuses a request nobody handles with MethodNotFound: so does this handler of the rest.
|
|
112
|
+
[' return await handler.handleUserInput(params);\n });\n }\n', before => before.replace(' });\n }\n', ` });
|
|
113
|
+
this.connection.onRequest((method, params) => {
|
|
114
|
+
codexUnrecognizedRequest(method, params);
|
|
115
|
+
throw new import_node2.ResponseError(import_node2.ErrorCodes.MethodNotFound, \`Unhandled method \${method}\`);
|
|
116
|
+
});
|
|
117
|
+
}\n`)],
|
|
118
|
+
...['thread/start', 'thread/resume'].map(method => [` return await this.sendRequest({ method: "${method}", params });`,
|
|
119
|
+
before => before.replace('await this.sendRequest', 'codexThread(await this.sendRequest').replace(');', '));')]),
|
|
120
|
+
];
|
|
121
|
+
export function reportedCodexUnrecognized(source) {
|
|
122
|
+
for (const [before, after] of patches) {
|
|
123
|
+
if (source.split(before).length !== 2) throw new Error('codex-acp unrecognized output patch no longer matches the locked adapter');
|
|
124
|
+
source = source.replace(before, after(before));
|
|
125
|
+
}
|
|
126
|
+
return `import { codexUnrecognizedItem, codexUnrecognizedNotification, codexUnrecognizedRequest, codexThread, codexTurnCompleted } from ${JSON.stringify(import.meta.url)};\n${source.replace(/^#![^\n]*\n/, '')}`;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export class CodexUnrecognized {
|
|
130
|
+
constructor() {
|
|
131
|
+
// Whether Coda takes reports, and what it has been told, by session and name.
|
|
132
|
+
this.taken = false; this.said = new Set();
|
|
133
|
+
}
|
|
134
|
+
// What Coda says: its handshake says whether it takes them.
|
|
135
|
+
fromCoda(message) {
|
|
136
|
+
if (message.method === 'initialize') this.taken = record(message.params?.clientCapabilities?._meta?.coda?.unrecognized);
|
|
137
|
+
}
|
|
138
|
+
// A report, as said to Coda: once, and only to a Coda that takes them.
|
|
139
|
+
report({ sessionId, kind, name, lost, detail }) {
|
|
140
|
+
name = name.slice(0, 200);
|
|
141
|
+
const key = `${sessionId}\n${name}`;
|
|
142
|
+
if (!this.taken || !sessionId || this.said.has(key)) return [];
|
|
143
|
+
this.said.add(key);
|
|
144
|
+
return [{ jsonrpc: '2.0', method: '_coda/unrecognized', params: { sessionId, kind, name, lost, ...(detail ? { detail: detail.slice(0, 2000) } : {}) } }];
|
|
145
|
+
}
|
|
146
|
+
// What codex-acp says, without what it tells here, which follows it.
|
|
147
|
+
fromAgent(message) {
|
|
148
|
+
const u = message?.params?.update, reports = u?._meta?.coda?.unrecognized;
|
|
149
|
+
if (message?.method !== 'session/update' || !Array.isArray(reports)) return [message];
|
|
150
|
+
const { unrecognized, ...coda } = u._meta.coda, { coda: _, ...meta } = u._meta;
|
|
151
|
+
if (Object.keys(coda).length) meta.coda = coda;
|
|
152
|
+
const { _meta, ...update } = u;
|
|
153
|
+
if (Object.keys(meta).length) update._meta = meta;
|
|
154
|
+
const reported = reports.flatMap(each => this.report({ sessionId: message.params.sessionId, ...each }));
|
|
155
|
+
if (update.sessionUpdate === 'session_info_update' && !update._meta) return reported;
|
|
156
|
+
return [{ ...message, params: { ...message.params, update } }, ...reported];
|
|
157
|
+
}
|
|
158
|
+
}
|
package/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"id": "codex",
|
|
4
4
|
"displayName": "Codex",
|
|
5
5
|
"description": "用 OpenAI Codex 跑会话",
|
|
6
|
-
"version": "1.
|
|
6
|
+
"version": "1.12.0",
|
|
7
7
|
"categories": [
|
|
8
8
|
"Agent"
|
|
9
9
|
],
|
|
@@ -59,11 +59,11 @@
|
|
|
59
59
|
}
|
|
60
60
|
}
|
|
61
61
|
},
|
|
62
|
-
"
|
|
62
|
+
"resources": [
|
|
63
63
|
{
|
|
64
64
|
"id": "login",
|
|
65
65
|
"title": "Codex",
|
|
66
|
-
"command": "node \"$CODA_PLUGIN_PATH/scripts/
|
|
66
|
+
"command": "node \"$CODA_PLUGIN_PATH/scripts/resources.mjs\"",
|
|
67
67
|
"maxAge": "PT0S",
|
|
68
68
|
"actions": {
|
|
69
69
|
"reset": {
|
|
@@ -79,7 +79,7 @@
|
|
|
79
79
|
],
|
|
80
80
|
"extensionPoints": {
|
|
81
81
|
"account-source": {
|
|
82
|
-
"description": "Codex 的账号与登录入口:来源给出当前账号和令牌,响应 --login
|
|
82
|
+
"description": "Codex 的账号与登录入口:来源给出当前账号和令牌,响应 --login,并提供账号与额度资源;接入后 Codex 自带的那一行不再显示。"
|
|
83
83
|
}
|
|
84
84
|
}
|
|
85
85
|
},
|
package/scripts/quota.mjs
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
2
|
|
|
3
|
-
// What the
|
|
4
|
-
// `account/read` and `account/rateLimits/read`. Kept apart from the commands so the tests can hand it answers.
|
|
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.
|
|
5
5
|
|
|
6
|
-
const
|
|
6
|
+
const VALUES = 8;
|
|
7
7
|
const line = (value, max = 80) => typeof value === 'string' ? [...value.replace(/\s+/g, ' ').trim()].slice(0, max).join('') : '';
|
|
8
|
-
// The account a
|
|
9
|
-
//
|
|
10
|
-
//
|
|
11
|
-
//
|
|
8
|
+
// The account a resource is, compared across machines by Coda's group view (its `identity`): who signed in and in which
|
|
9
|
+
// ChatGPT workspace, as the quota is one person's in one workspace (one email may sign in to several, and a workspace has
|
|
10
|
+
// many members). A hash of the email and of the workspace's account ID hashed as codex-account keeps it; none where Codex
|
|
11
|
+
// does not say both.
|
|
12
12
|
const hash = text => createHash('sha256').update(text).digest('hex');
|
|
13
13
|
const identity = (account, workspace) => {
|
|
14
14
|
const email = line(account.email, 320).toLowerCase();
|
|
@@ -19,7 +19,8 @@ const unixTime = value => typeof value === 'number' && Number.isFinite(new Date(
|
|
|
19
19
|
// docs/agent-protocol.md「文字里的时刻」).
|
|
20
20
|
const mark = seconds => `<t:${unixTime(seconds)}>`;
|
|
21
21
|
|
|
22
|
-
// A
|
|
22
|
+
// A value per window of each limit, of what is left and when it resets; unknown is said as unknown, never a zero. A limit's
|
|
23
|
+
// name is said only when there are several.
|
|
23
24
|
export function windows(result) {
|
|
24
25
|
const byID = result?.rateLimitsByLimitId ? Object.values(result.rateLimitsByLimitId) : [];
|
|
25
26
|
const limits = (byID.length ? byID : [result?.rateLimits]).filter(Boolean);
|
|
@@ -29,9 +30,9 @@ export function windows(result) {
|
|
|
29
30
|
const duration = minutes === 300 ? '5 小时' : minutes === 10080 ? '7 天' : Number.isSafeInteger(minutes) && minutes > 0 ? `${minutes} 分钟` : '额度';
|
|
30
31
|
const used = typeof w.usedPercent === 'number' && w.usedPercent >= 0 && w.usedPercent <= 100 ? w.usedPercent : null;
|
|
31
32
|
const left = used === null ? null : Math.round(100 - used), resets = unixTime(w.resetsAt);
|
|
32
|
-
return [{
|
|
33
|
-
...(left === null ? {} : { value: `剩余 ${left}%`, fraction: left / 100 }),
|
|
34
|
-
...(resets ? { time: resets
|
|
33
|
+
return [{ label: `${limits.length > 1 ? `${line(limit.limitName ?? limit.limitId, 40) || '额度'} · ` : ''}${duration}`,
|
|
34
|
+
...(left === null ? { value: '—' } : { value: `剩余 ${left}%`, fraction: left / 100 }),
|
|
35
|
+
...(resets ? { time: resets } : {}) }];
|
|
35
36
|
}));
|
|
36
37
|
}
|
|
37
38
|
|
|
@@ -45,39 +46,33 @@ export function credits(result) {
|
|
|
45
46
|
return { count: summary.availableCount, listed };
|
|
46
47
|
}
|
|
47
48
|
|
|
48
|
-
// The login
|
|
49
|
-
//
|
|
50
|
-
export function
|
|
49
|
+
// The login as a resource: its windows, then its full resets left, timed by the one to expire first; its button for a full
|
|
50
|
+
// reset (that one, named in its question).
|
|
51
|
+
export function resource(account, result, workspace) {
|
|
51
52
|
const name = line(account.email) || '本机登录';
|
|
52
|
-
const
|
|
53
|
+
const values = windows(result), resets = credits(result), actions = [];
|
|
53
54
|
if (resets) {
|
|
54
|
-
const first = resets.listed[0];
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
items.push({ type: 'stat', label: '完全重置', value: `剩余 ${resets.count} 次` }, ...lines.slice(0, Math.max(0, room)));
|
|
58
|
-
if (first && resets.count > 0) items.unshift({ type: 'button', label: '使用完全重置', action: 'reset', args: { creditId: first.id },
|
|
55
|
+
const first = resets.listed[0], expires = first?.expiresAt == null ? null : unixTime(first.expiresAt);
|
|
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 },
|
|
59
58
|
confirm: `使用 ${line(name, 60)} 的完全重置?\n用最早到期的那一次(${first.expiresAt == null ? '不会过期' : `${mark(first.expiresAt)} 到期`})。成功后消耗 1 次,无法撤销。` });
|
|
60
59
|
}
|
|
61
|
-
|
|
62
|
-
|
|
60
|
+
return { name, ...identity(account, workspace), values: values.slice(0, VALUES),
|
|
61
|
+
...(values.length ? {} : { error: '暂时无法获取额度:Codex 没有给出额度窗口' }), ...(actions.length ? { actions } : {}) };
|
|
63
62
|
}
|
|
64
63
|
|
|
65
|
-
// The
|
|
66
|
-
// on
|
|
67
|
-
export async function
|
|
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.
|
|
66
|
+
export async function resources(server) {
|
|
68
67
|
const { account, workspaceRouting } = await server.request('account/read', { refreshToken: false });
|
|
69
68
|
const workspace = workspaceRouting?.chatgptAccountId;
|
|
70
|
-
if (!account) return {
|
|
71
|
-
if (account.type !== 'chatgpt') return {
|
|
72
|
-
items: [{ type: 'markdown', text: '不是用 ChatGPT 账号登录的,没有额度可显示' }] }] };
|
|
69
|
+
if (!account) return { resources: [] };
|
|
70
|
+
if (account.type !== 'chatgpt') return { resources: [{ name: '本机登录', values: [{ value: '不是 ChatGPT 登录,没有额度' }] }] };
|
|
73
71
|
let result;
|
|
74
72
|
try { result = await server.request('account/rateLimits/read'); }
|
|
75
|
-
catch (error) {
|
|
76
|
-
|
|
77
|
-
items: [{ type: 'error', text: `暂时无法获取额度:${error.message}` }] }] };
|
|
78
|
-
}
|
|
79
|
-
return { items: [card(account, result, workspace)] };
|
|
73
|
+
catch (error) { return { resources: [{ name: line(account.email) || '本机登录', ...identity(account, workspace), error: line(`暂时无法获取额度:${error.message}`) }] }; }
|
|
74
|
+
return { resources: [resource(account, result, workspace)] };
|
|
80
75
|
}
|
|
81
76
|
|
|
82
|
-
// What a full reset came to, as one line
|
|
77
|
+
// What a full reset came to, as one line on the row when it did not reset anything.
|
|
83
78
|
export const outcomes = { nothingToReset: '当前额度无需重置', alreadyRedeemed: '这次重置已被使用', noCredit: '这次重置已不可用' };
|
package/scripts/reset.mjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
// The
|
|
2
|
-
// Anything but a reset is said in one line and fails the action, so
|
|
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
3
|
import { randomUUID } from 'node:crypto';
|
|
4
4
|
import { withAppServer } from './app-server.mjs';
|
|
5
5
|
import { outcomes } from './quota.mjs';
|
|
6
6
|
import { accountSource } from '../agent/account-source.mjs';
|
|
7
7
|
|
|
8
|
-
if (accountSource()) { console.error('
|
|
8
|
+
if (accountSource()) { console.error('额度已由账号插件接管,请在账号插件的那一行使用完全重置'); process.exit(1); }
|
|
9
9
|
|
|
10
10
|
const { creditId } = JSON.parse(process.env.CODA_PANEL_ARGS || '{}');
|
|
11
11
|
if (typeof creditId !== 'string' || !creditId) { console.error('没有指明用哪一次完全重置'); process.exit(1); }
|
|
@@ -0,0 +1,7 @@
|
|
|
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); }
|
package/scripts/panel.mjs
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
// An account source owns its quota panel. Without one, show Codex's own login as before.
|
|
2
|
-
import { withAppServer } from './app-server.mjs';
|
|
3
|
-
import { panel } from './quota.mjs';
|
|
4
|
-
import { accountSource } from '../agent/account-source.mjs';
|
|
5
|
-
|
|
6
|
-
try { console.log(JSON.stringify(accountSource() ? { items: [] } : await withAppServer(panel))); }
|
|
7
|
-
catch (error) { console.error(error.message); process.exit(1); }
|