chatccc 0.2.286 → 0.2.288

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.
@@ -1,22 +1,25 @@
1
1
  // =============================================================================
2
- // codex-adapter.ts — OpenAI Codex CLI 适配器
2
+ // codex-adapter.ts — OpenAI Codex CLI 适配器(app-server 模式)
3
3
  // =============================================================================
4
- // 通过 codex exec --json Codex CLI 交互。
5
- // - createSession: 生成 UUID sessionId,记录 cwd,不创建 Codex 线程(延迟到首次 prompt)
6
- // - prompt: 首次调用用 codex exec 创建线程,后续用 codex exec resume 恢复
4
+ // 通过 codex app-server(WebSocket JSON-RPC)与 Codex CLI 交互。
5
+ // - createSession: 生成 UUID sessionId,记录 cwd,不创建线程(延迟到首次 prompt)
6
+ // - prompt: 首次 thread/start 创建持久化线程,后续 thread/resume 恢复;
7
+ // 运行中通过 turn/steer 在 item 边界注入新消息(协作式让位,对齐 ccc)
7
8
  // - getSessionInfo: 从持久化映射读取 cwd / threadId
9
+ //
10
+ // 权限语义与旧 exec 模式 `--dangerously-bypass-approvals-and-sandbox` 等价:
11
+ // approvalPolicy: "never" + sandbox: "danger-full-access"(demo 已实测零审批)。
12
+ // /plan、/ask 命令退化为只读沙箱(对应旧 exec 的 --sandbox read-only)。
8
13
  // =============================================================================
9
- import { spawn } from "node:child_process";
10
14
  import { createTurnCompletion } from "./turn-completion.js";
11
- import { cliProcessOptions, ensureCliSessionReleased, ownCliProcess } from "./managed-cli-process.js";
15
+ import { ensureCliSessionReleased } from "./managed-cli-process.js";
12
16
  import { existsSync, readFileSync } from "node:fs";
13
17
  import { join } from "node:path";
14
18
  import { randomUUID } from "node:crypto";
15
19
  import { parseUserCommand } from "./adapter-interface.js";
16
20
  import { defaultCodexSessionMetaStore, } from "./codex-session-meta-store.js";
17
- import { config, PROJECT_ROOT, RAW_STREAM_LOGS_DIR } from "../config.js";
18
- import { createRawStreamLog, } from "./raw-stream-log.js";
19
- import { readJsonLinesWithBadJsonIdleWatchdog } from "./jsonl-stream.js";
21
+ import { config, PROJECT_ROOT } from "../config.js";
22
+ import { AsyncQueue, CodexAppServerManager, JsonRpcClient, } from "./codex-app-server.js";
20
23
  // ---------------------------------------------------------------------------
21
24
  // 特殊注入提示
22
25
  // ---------------------------------------------------------------------------
@@ -51,160 +54,88 @@ function buildCodexPromptText(userText) {
51
54
  function detectCodexCommand() {
52
55
  return config.codex.path || "codex";
53
56
  }
54
- /** exec 模式共用参数:JSONL 输出、绕过沙盒和确认、跳过 git 仓库检查 */
55
- const CODEX_BASE_ARGS = [
56
- "exec",
57
- "--json",
58
- "--dangerously-bypass-approvals-and-sandbox",
59
- "--skip-git-repo-check",
60
- ];
61
- /** codex 模型;留空("")表示不传 --model,由 codex config.toml 决定 */
57
+ /** codex 模型;留空("")表示不传,由 codex config.toml 决定 */
62
58
  function resolveCodexModel() {
63
59
  const m = config.codex.model;
64
60
  return m.trim() !== "" ? m : null;
65
61
  }
66
- /** codex 努力程度(映射为 -c model_reasoning_effort=<value>);留空表示不传 */
62
+ /** codex 努力程度;留空表示不传 */
67
63
  function resolveCodexEffort() {
68
64
  const e = config.codex.effort;
69
65
  return e.trim() !== "" ? e : null;
70
66
  }
71
- // ---------------------------------------------------------------------------
72
- // normalizeCodexMessage — Codex 事件 → UnifiedStreamMessage | null
73
- // ---------------------------------------------------------------------------
74
- export function normalizeCodexMessage(msg) {
75
- if (msg.type === "error") {
76
- throw new Error(`Codex turn failed: ${msg.message?.trim() || "未提供错误详情"}`);
77
- }
78
- if (msg.type === "turn.failed") {
79
- const detail = typeof msg.error === "string" ? msg.error : msg.error?.message;
80
- throw new Error(`Codex turn failed: ${detail?.trim() || "unknown Codex error"}`);
67
+ function itemOf(params) {
68
+ return params.item;
69
+ }
70
+ export function normalizeCodexNotification(method, params) {
71
+ // error 通知:willRetry=false 是致命错误;willRetry=true 会自动重试,忽略
72
+ if (method === "error") {
73
+ const willRetry = params.willRetry;
74
+ const message = params.error?.message;
75
+ if (willRetry === false) {
76
+ throw new Error(`Codex turn failed: ${message?.trim() || "unknown Codex error"}`);
77
+ }
78
+ return null;
81
79
  }
82
- // agent_message 只是 Codex 的一条阶段性文本 item。即使内容看起来像完整答复,
83
- // 后面仍可能继续发出工具调用,因此不能用它关闭 response-stall watchdog。
84
- if (msg.type === "item.completed" &&
85
- msg.item?.type === "agent_message" &&
86
- msg.item.text) {
80
+ // agentMessage Codex 的一条阶段性文本 item(整段)。即使内容像完整答复,
81
+ // 后面仍可能继续工具调用,因此不能用它关闭 response-stall watchdog。
82
+ if (method === "item/completed" &&
83
+ itemOf(params)?.type === "agentMessage" &&
84
+ itemOf(params)?.text) {
87
85
  return {
88
86
  type: "assistant",
89
- blocks: [{ type: "text", text: msg.item.text }],
87
+ blocks: [{ type: "text", text: itemOf(params).text }],
90
88
  };
91
89
  }
92
- // turn.completed 是 Codex 对整轮完成的权威确认。正文已经由之前的
93
- // agent_message 累计,这里只发送空终态信号,避免重复追加最终文本。
94
- if (msg.type === "turn.completed") {
90
+ // turn/completed 是 Codex 对整轮完成的权威确认。正文已由 agentMessage 累计。
91
+ if (method === "turn/completed") {
92
+ const turn = params.turn;
93
+ if (turn?.status === "failed") {
94
+ throw new Error(`Codex turn failed: ${turn.error?.message?.trim() || "unknown Codex error"}`);
95
+ }
95
96
  return {
96
97
  type: "assistant",
97
98
  blocks: [],
98
99
  isFinalResponse: true,
99
100
  };
100
101
  }
101
- // command_execution 工具调用开始
102
- if (msg.type === "item.started" &&
103
- msg.item?.type === "command_execution" &&
104
- msg.item.command) {
102
+ // commandExecution 工具调用开始
103
+ if (method === "item/started" &&
104
+ itemOf(params)?.type === "commandExecution" &&
105
+ itemOf(params)?.command) {
106
+ const item = itemOf(params);
105
107
  return {
106
108
  type: "assistant",
107
109
  blocks: [
108
110
  {
109
111
  type: "tool_use",
110
- id: msg.item.id,
112
+ id: item.id,
111
113
  name: "Bash",
112
- input: { command: msg.item.command },
114
+ input: { command: item.command },
113
115
  },
114
116
  ],
115
117
  };
116
118
  }
117
- // command_execution 工具调用完成
118
- if (msg.type === "item.completed" &&
119
- msg.item?.type === "command_execution") {
120
- const exitCode = msg.item.exit_code;
119
+ // commandExecution 工具调用完成
120
+ if (method === "item/completed" && itemOf(params)?.type === "commandExecution") {
121
+ const item = itemOf(params);
122
+ const exitCode = item.exitCode;
121
123
  return {
122
124
  type: "assistant",
123
125
  blocks: [
124
126
  {
125
127
  type: "tool_result",
126
- tool_use_id: msg.item.id ?? "",
127
- content: msg.item.aggregated_output ?? "",
128
+ tool_use_id: item.id ?? "",
129
+ content: item.aggregatedOutput ?? "",
128
130
  is_error: exitCode != null && exitCode !== 0 ? true : undefined,
129
131
  },
130
132
  ],
131
133
  };
132
134
  }
133
- // thread.started / turn.started → 不映射为用户可见消息
135
+ // thread/started、turn/started、item/agentMessage/delta → 不映射为用户可见消息
134
136
  return null;
135
137
  }
136
138
  // ---------------------------------------------------------------------------
137
- // 子进程辅助函数
138
- // ---------------------------------------------------------------------------
139
- export function buildCodexInvocationArgs(args, modelOverride, effortOverride, fastModeOverride) {
140
- const allArgs = [...args];
141
- const model = modelOverride ?? resolveCodexModel();
142
- if (model) {
143
- // 把 -m 插在 exec 后面、其他参数前面
144
- const execIdx = allArgs.indexOf("exec");
145
- allArgs.splice(execIdx + 1, 0, "-m", model);
146
- }
147
- const effort = effortOverride ?? resolveCodexEffort();
148
- if (effort) {
149
- allArgs.push("-c", `model_reasoning_effort="${effort}"`);
150
- }
151
- const fastMode = fastModeOverride ?? config.codex.fastMode;
152
- allArgs.push("-c", `service_tier="${fastMode ? "fast" : "default"}"`);
153
- return allArgs;
154
- }
155
- function spawnCodex(args, cwd, stdinText, modelOverride, effortOverride, fastModeOverride) {
156
- const allArgs = buildCodexInvocationArgs(args, modelOverride, effortOverride, fastModeOverride);
157
- const proc = spawn(detectCodexCommand(), allArgs, {
158
- cwd,
159
- stdio: [stdinText !== undefined ? "pipe" : "ignore", "pipe", "pipe"],
160
- windowsHide: true,
161
- shell: true,
162
- ...cliProcessOptions(),
163
- });
164
- let stderr = "";
165
- let exitCode = null;
166
- let signal = null;
167
- let settleClose = () => { };
168
- const closed = new Promise(resolve => { settleClose = resolve; });
169
- proc.once("error", (error) => { stderr += `\n${error.message}`; settleClose(); });
170
- proc.stderr.on("data", (chunk) => {
171
- stderr += chunk.toString();
172
- });
173
- proc.on("close", (code, exitSignal) => {
174
- exitCode = code;
175
- signal = exitSignal;
176
- settleClose();
177
- if (code !== 0 && stderr.trim()) {
178
- console.error(`[Codex stderr] exit=${code}: ${stderr.trim().slice(0, 2000)}`);
179
- }
180
- });
181
- if (stdinText !== undefined) {
182
- proc.stdin.write(stdinText);
183
- proc.stdin.end();
184
- }
185
- return { proc, async failureDetail() {
186
- let timer;
187
- try {
188
- await Promise.race([closed, new Promise(resolve => { timer = setTimeout(resolve, 2_000); })]);
189
- return `exit=${exitCode ?? "unknown"}; signal=${signal ?? "none"}; ${stderr.trim() || "无 stderr 详情"}`;
190
- }
191
- finally {
192
- if (timer)
193
- clearTimeout(timer);
194
- }
195
- } };
196
- }
197
- async function* readJsonLines(proc, signal, rawLog) {
198
- yield* readJsonLinesWithBadJsonIdleWatchdog({
199
- input: proc.stdout,
200
- tool: "codex",
201
- tag: "codex",
202
- signal,
203
- rawLog,
204
- parse: (line) => JSON.parse(line),
205
- });
206
- }
207
- // ---------------------------------------------------------------------------
208
139
  // 适配器实现
209
140
  // ---------------------------------------------------------------------------
210
141
  class CodexAdapter {
@@ -220,7 +151,7 @@ class CodexAdapter {
220
151
  this.effortOverride = effortOverride;
221
152
  this.fastModeOverride = fastModeOverride;
222
153
  }
223
- // createSession: 生成 sessionId,记录 cwd,不创建 Codex 线程(延迟到首次 prompt)
154
+ // createSession: 生成 sessionId,记录 cwd,不创建线程(延迟到首次 prompt)
224
155
  async createSession(cwd) {
225
156
  const sessionId = randomUUID();
226
157
  await this.metaStore.set(sessionId, { cwd });
@@ -230,61 +161,143 @@ class CodexAdapter {
230
161
  if (signal?.aborted)
231
162
  return;
232
163
  await ensureCliSessionReleased(sessionId);
233
- let meta = await this.metaStore.get(sessionId);
164
+ const meta = await this.metaStore.get(sessionId);
234
165
  const threadId = meta?.threadId;
235
166
  const isFirstPrompt = !threadId;
236
- // 首次 prompt: codex exec 创建新线程
237
- // 后续 prompt: codex exec resume 恢复已有线程(resume 不接受 -C,cwd 继承自原线程)
238
167
  const cmd = parseUserCommand(userText);
239
- const baseArgs = cmd.mode
240
- ? ["exec", "--json", "--sandbox", "read-only", "--skip-git-repo-check"]
241
- : CODEX_BASE_ARGS;
242
- const args = isFirstPrompt
243
- ? [...baseArgs, "-C", cwd, "-"]
244
- : [...baseArgs, "resume", threadId, "-"];
245
- const handle = spawnCodex(args, cwd, buildCodexPromptText(userText), this.modelOverride, this.effortOverride, this.fastModeOverride);
246
- const proc = handle.proc;
247
- const ownership = ownCliProcess(sessionId, proc.pid);
248
- if (proc.pid !== undefined)
249
- options?.onProcessStart?.({ pid: proc.pid });
250
- const rawLogConfig = config.rawStreamLogs.codex;
251
- let rawLog = null;
252
- try {
253
- rawLog = await createRawStreamLog({
254
- enabled: rawLogConfig.enabled,
255
- rootDir: RAW_STREAM_LOGS_DIR,
256
- tool: "codex",
257
- sessionId,
258
- label: "prompt",
259
- maxBytesPerTurn: rawLogConfig.maxBytesPerTurn,
260
- retentionDays: rawLogConfig.retentionDays,
261
- });
262
- }
263
- catch (err) {
264
- console.error(`[Codex raw stream log] create failed: ${err.message}`);
265
- }
266
- // 关键:spawn 用了 shell:true,proc.pid 指向的是壳进程(cmd.exe / sh)。
267
- // 真正干活的是壳的孙子 codex.exe。普通 proc.kill() 在 Windows 上只杀第一层,
268
- // 会留下幽灵 node + codex.exe 继续烧 token、stream-state 永远停在 running。
269
- // 因此 abort finally 都必须用 killProcessTree 整棵进程树一起收尸。
270
- const onAbort = () => { void ownership.stop().catch(() => { }); };
168
+ const readOnly = cmd.mode !== null;
169
+ // thread/start 用字符串枚举;turn/start 用对象策略
170
+ const threadSandbox = readOnly ? "read-only" : "danger-full-access";
171
+ const turnSandboxPolicy = readOnly
172
+ ? { type: "readOnly", networkAccess: true }
173
+ : { type: "dangerFullAccess" };
174
+ const model = this.modelOverride ?? resolveCodexModel();
175
+ const effort = this.effortOverride ?? resolveCodexEffort();
176
+ const fastMode = this.fastModeOverride ?? config.codex.fastMode;
177
+ // 确保常驻 app-server 已启动,并建立本次 prompt 的 WebSocket 连接
178
+ const port = await CodexAppServerManager.get().ensureStarted(detectCodexCommand());
179
+ const client = await JsonRpcClient.connect(`ws://127.0.0.1:${port}`);
180
+ let threadIdResolved = threadId ?? null;
181
+ let currentTurnId = null;
182
+ const interruptAndClose = async () => {
183
+ if (threadIdResolved && currentTurnId) {
184
+ try {
185
+ await client.request("turn/interrupt", { threadId: threadIdResolved, turnId: currentTurnId }, 3000);
186
+ }
187
+ catch {
188
+ /* turn 可能已结束 */
189
+ }
190
+ }
191
+ client.close();
192
+ };
193
+ // 上层 stop-stuck-loop 强制关闭:打断当前 turn + 断开连接(不杀共享进程)
194
+ options?.onSessionCreated?.(() => {
195
+ void interruptAndClose().catch(() => { });
196
+ });
197
+ const onAbort = () => {
198
+ void interruptAndClose().catch(() => { });
199
+ };
271
200
  signal?.addEventListener("abort", onAbort, { once: true });
272
201
  let completed = false;
273
202
  const completion = createTurnCompletion("Codex");
274
203
  try {
275
- for await (const raw of readJsonLines(proc, signal, rawLog)) {
204
+ // 1. 握手
205
+ await client.request("initialize", {
206
+ clientInfo: { name: "chatccc-codex", title: null, version: "0.0.0" },
207
+ capabilities: null,
208
+ }, 60000);
209
+ // 2. 线程:首次 thread/start 创建持久化线程,后续 thread/resume 恢复
210
+ const threadParams = {
211
+ cwd,
212
+ approvalPolicy: "never",
213
+ sandbox: threadSandbox,
214
+ ...(model ? { model } : {}),
215
+ };
216
+ if (isFirstPrompt) {
217
+ const r = await client.request("thread/start", threadParams, 60000);
218
+ threadIdResolved = r.thread?.id;
219
+ if (threadIdResolved) {
220
+ void this.metaStore.setThreadId(sessionId, threadIdResolved).catch(() => { });
221
+ }
222
+ }
223
+ else {
224
+ try {
225
+ await client.request("thread/resume", { threadId: threadId, excludeTurns: true, ...threadParams }, 60000);
226
+ }
227
+ catch (err) {
228
+ // 存量 threadId 在磁盘上不可恢复(被清理/损坏)→ 回退到新建线程
229
+ console.warn(`[Codex] thread/resume 失败,回退到新线程: ${err.message}`);
230
+ const r = await client.request("thread/start", threadParams, 60000);
231
+ threadIdResolved = r.thread?.id;
232
+ if (threadIdResolved) {
233
+ void this.metaStore.setThreadId(sessionId, threadIdResolved).catch(() => { });
234
+ }
235
+ }
236
+ }
237
+ // 3. 启动 turn
238
+ const turnResp = await client.request("turn/start", {
239
+ threadId: threadIdResolved,
240
+ input: [
241
+ { type: "text", text: buildCodexPromptText(userText), text_elements: [] },
242
+ ],
243
+ approvalPolicy: "never",
244
+ sandboxPolicy: turnSandboxPolicy,
245
+ ...(model ? { model } : {}),
246
+ ...(effort ? { effort } : {}),
247
+ serviceTier: fastMode ? "fast" : "default",
248
+ }, 120000);
249
+ currentTurnId = turnResp.turn?.id;
250
+ // 4. 事件循环:WebSocket 通知 → async iterable
251
+ const queue = new AsyncQueue();
252
+ client.onNotification = (method, params) => {
253
+ queue.push({ method, params });
254
+ // turn/completed 与致命 error 都终止本轮事件流
255
+ if (method === "turn/completed" || (method === "error" && params.willRetry === false)) {
256
+ queue.end();
257
+ }
258
+ };
259
+ // approvalPolicy=never 下不应收到审批请求;fail-closed 暴露配置失效
260
+ client.onServerRequest = (method, _params, id) => {
261
+ console.error(`[Codex] 意外收到服务端请求(审批策略未生效?): ${method}`);
262
+ client.respondError(id, -32000, `unexpected server request: ${method}`);
263
+ };
264
+ client.onClose = () => {
265
+ queue.end();
266
+ };
267
+ // 5. 消费事件流,item 边界执行协作式注入
268
+ for await (const { method, params } of queue) {
276
269
  if (signal?.aborted)
277
270
  break;
278
- if (isFirstPrompt &&
279
- raw.type === "thread.started" &&
280
- raw.thread_id) {
281
- void this.metaStore
282
- .setThreadId(sessionId, raw.thread_id)
283
- .catch(() => { });
271
+ // 工具步骤边界 → 检查并吸收运行期注入(turn/steer)
272
+ if (method === "item/completed") {
273
+ const injected = options?.drainInput?.();
274
+ if (injected && threadIdResolved && currentTurnId) {
275
+ try {
276
+ const steerResp = await client.request("turn/steer", {
277
+ threadId: threadIdResolved,
278
+ input: [{ type: "text", text: injected, text_elements: [] }],
279
+ expectedTurnId: currentTurnId,
280
+ }, 30000);
281
+ currentTurnId = steerResp.turnId;
282
+ yield { type: "assistant", blocks: [{ type: "input_injected", text: injected }] };
283
+ }
284
+ catch (err) {
285
+ // steer 失败(turn 恰好已结束,expectedTurnId 前置条件不满足)
286
+ // → 退回注入队列,交由上层在整轮结束后作为新消息消费,避免丢消息。
287
+ console.error(`[Codex] turn/steer 失败,注入消息退回队列: ${err.message}`);
288
+ options?.onInjectionRejected?.();
289
+ }
290
+ }
284
291
  }
285
- const normalized = normalizeCodexMessage(raw);
292
+ // turn/started 确认当前活跃 turn id(turn/steer 后可能变化)
293
+ if (method === "turn/started") {
294
+ const turnId = params.turn?.id;
295
+ if (turnId)
296
+ currentTurnId = turnId;
297
+ }
298
+ const normalized = normalizeCodexNotification(method, params);
286
299
  completion.observe(normalized);
287
- if (raw.type === "turn.completed") {
300
+ if (method === "turn/completed") {
288
301
  completion.complete();
289
302
  completed = true;
290
303
  }
@@ -293,21 +306,13 @@ class CodexAdapter {
293
306
  if (completed)
294
307
  break;
295
308
  }
296
- if (!signal?.aborted && !completed)
297
- completion.assertComplete(await handle.failureDetail());
309
+ if (!signal?.aborted && !completed) {
310
+ completion.assertComplete("app-server 连接在 turn 完成前关闭");
311
+ }
298
312
  }
299
313
  finally {
300
314
  signal?.removeEventListener("abort", onAbort);
301
- let released = false;
302
- try {
303
- await ownership.stop();
304
- released = true;
305
- }
306
- finally {
307
- await rawLog?.close({ keep: !released || rawLogConfig.keepCompleted || signal?.aborted === true || !completed });
308
- if (released && proc.pid !== undefined)
309
- options?.onProcessExit?.({ pid: proc.pid });
310
- }
315
+ client.close();
311
316
  }
312
317
  }
313
318
  async getSessionInfo(sessionId) {
@@ -317,7 +322,7 @@ class CodexAdapter {
317
322
  return { sessionId, cwd: meta.cwd };
318
323
  }
319
324
  async closeSession(_sessionId) {
320
- // no-op:子进程由 prompt 的 finally 自动 kill
325
+ // no-op:WebSocket 连接由 prompt 的 finally 关闭;app-server 进程常驻复用
321
326
  }
322
327
  }
323
328
  export function createCodexAdapter(options = {}) {