chatccc 0.2.197 → 0.2.199
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/agent-prompts/cursor_specific.md +13 -13
- package/bin/cccagent.mjs +17 -17
- package/config.sample.json +27 -27
- package/package.json +2 -1
- package/src/__tests__/agent-reload-config-rpc.test.ts +99 -99
- package/src/__tests__/builtin-chat-session.test.ts +277 -277
- package/src/__tests__/builtin-cli-json.test.ts +39 -39
- package/src/__tests__/builtin-config.test.ts +33 -33
- package/src/__tests__/builtin-context.test.ts +163 -163
- package/src/__tests__/builtin-file-tools.test.ts +224 -224
- package/src/__tests__/builtin-session-select.test.ts +116 -116
- package/src/__tests__/builtin-sigint.test.ts +56 -56
- package/src/__tests__/cards.test.ts +109 -109
- package/src/__tests__/ccc-adapter.test.ts +114 -114
- package/src/__tests__/chatgpt-subscription-rpc.test.ts +89 -89
- package/src/__tests__/chatgpt-subscription.test.ts +135 -135
- package/src/__tests__/chrome-devtools-guard.test.ts +165 -165
- package/src/__tests__/claude-raw-stream-log.test.ts +87 -87
- package/src/__tests__/codex-raw-stream-log.test.ts +163 -120
- package/src/__tests__/config-reload.test.ts +10 -10
- package/src/__tests__/config-sample.test.ts +18 -18
- package/src/__tests__/cursor-adapter.test.ts +114 -1
- package/src/__tests__/feishu-avatar.test.ts +40 -40
- package/src/__tests__/jsonl-stream.test.ts +79 -0
- package/src/__tests__/orchestrator.test.ts +200 -200
- package/src/__tests__/raw-stream-log.test.ts +106 -106
- package/src/__tests__/session.test.ts +40 -40
- package/src/__tests__/sim-platform.test.ts +12 -12
- package/src/__tests__/web-ui.test.ts +209 -209
- package/src/adapters/ccc-adapter.ts +121 -121
- package/src/adapters/claude-adapter.ts +603 -603
- package/src/adapters/codex-adapter.ts +380 -392
- package/src/adapters/cursor-adapter.ts +56 -30
- package/src/adapters/jsonl-stream.ts +157 -0
- package/src/adapters/raw-stream-log.ts +124 -124
- package/src/agent-reload-config-rpc.ts +34 -34
- package/src/builtin/cli.ts +473 -473
- package/src/builtin/context.ts +323 -323
- package/src/builtin/file-tools.ts +1072 -1072
- package/src/builtin/index.ts +404 -404
- package/src/builtin/session-select.ts +48 -48
- package/src/builtin/sigint.ts +50 -50
- package/src/cards.ts +195 -195
- package/src/chatgpt-subscription-rpc.ts +27 -27
- package/src/chatgpt-subscription.ts +299 -299
- package/src/chrome-devtools-guard.ts +318 -318
- package/src/config.ts +125 -125
- package/src/feishu-api.ts +49 -49
- package/src/orchestrator.ts +179 -179
- package/src/runtime-reload.ts +34 -34
- package/src/session.ts +141 -141
- package/src/web-ui.ts +205 -205
|
@@ -1,392 +1,380 @@
|
|
|
1
|
-
// =============================================================================
|
|
2
|
-
// codex-adapter.ts — OpenAI Codex CLI 适配器
|
|
3
|
-
// =============================================================================
|
|
4
|
-
// 通过 codex exec --json 与 Codex CLI 交互。
|
|
5
|
-
// - createSession: 生成 UUID sessionId,记录 cwd,不创建 Codex 线程(延迟到首次 prompt)
|
|
6
|
-
// - prompt: 首次调用用 codex exec 创建线程,后续用 codex exec resume 恢复
|
|
7
|
-
// - getSessionInfo: 从持久化映射读取 cwd / threadId
|
|
8
|
-
// =============================================================================
|
|
9
|
-
|
|
10
|
-
import { spawn, type ChildProcess } from "node:child_process";
|
|
11
|
-
import { existsSync, readFileSync } from "node:fs";
|
|
12
|
-
import { dirname, join } from "node:path";
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
} from "./adapter-interface.ts";
|
|
25
|
-
import {
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
} from "./
|
|
30
|
-
import {
|
|
31
|
-
import {
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
} from "./
|
|
36
|
-
|
|
37
|
-
// ---------------------------------------------------------------------------
|
|
38
|
-
// 特殊注入提示
|
|
39
|
-
// ---------------------------------------------------------------------------
|
|
40
|
-
|
|
41
|
-
const PROJECT_ROOT = dirname(dirname(dirname(fileURLToPath(import.meta.url))));
|
|
42
|
-
const CODEX_SPECIFIC_PROMPT_PATH = join(
|
|
43
|
-
PROJECT_ROOT,
|
|
44
|
-
"agent-prompts",
|
|
45
|
-
"codex_specific.md",
|
|
46
|
-
);
|
|
47
|
-
|
|
48
|
-
function readCodexSpecificInjectionPrompt(): string | null {
|
|
49
|
-
try {
|
|
50
|
-
if (!existsSync(CODEX_SPECIFIC_PROMPT_PATH)) return null;
|
|
51
|
-
const prompt = readFileSync(CODEX_SPECIFIC_PROMPT_PATH, "utf-8").trim();
|
|
52
|
-
return prompt.length > 0 ? prompt : null;
|
|
53
|
-
} catch {
|
|
54
|
-
return null;
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
function buildCodexPromptText(userText: string): string {
|
|
59
|
-
const prompt = readCodexSpecificInjectionPrompt();
|
|
60
|
-
if (!prompt) return userText;
|
|
61
|
-
|
|
62
|
-
return [
|
|
63
|
-
"[ChatCCC Codex-specific injection prompt]",
|
|
64
|
-
prompt,
|
|
65
|
-
"[/ChatCCC Codex-specific injection prompt]",
|
|
66
|
-
"",
|
|
67
|
-
userText,
|
|
68
|
-
].join("\n");
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
// ---------------------------------------------------------------------------
|
|
72
|
-
// 命令与参数
|
|
73
|
-
// ---------------------------------------------------------------------------
|
|
74
|
-
|
|
75
|
-
/** 可通过 config.json codex.path 自定义 Codex 可执行文件路径 */
|
|
76
|
-
function detectCodexCommand(): string {
|
|
77
|
-
return config.codex.path || "codex";
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
/** exec 模式共用参数:JSONL 输出、绕过沙盒和确认、跳过 git 仓库检查 */
|
|
81
|
-
const CODEX_BASE_ARGS = [
|
|
82
|
-
"exec",
|
|
83
|
-
"--json",
|
|
84
|
-
"--dangerously-bypass-approvals-and-sandbox",
|
|
85
|
-
"--skip-git-repo-check",
|
|
86
|
-
];
|
|
87
|
-
|
|
88
|
-
/** codex 模型;留空("")表示不传 --model,由 codex config.toml 决定 */
|
|
89
|
-
function resolveCodexModel(): string | null {
|
|
90
|
-
const m = config.codex.model;
|
|
91
|
-
return m.trim() !== "" ? m : null;
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
/** codex 努力程度(映射为 -c model_reasoning_effort=<value>);留空表示不传 */
|
|
95
|
-
function resolveCodexEffort(): string | null {
|
|
96
|
-
const e = config.codex.effort;
|
|
97
|
-
return e.trim() !== "" ? e : null;
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
// ---------------------------------------------------------------------------
|
|
101
|
-
// 类型:Codex JSONL 消息行
|
|
102
|
-
// ---------------------------------------------------------------------------
|
|
103
|
-
|
|
104
|
-
interface CodexItem {
|
|
105
|
-
id?: string;
|
|
106
|
-
type?: string;
|
|
107
|
-
text?: string;
|
|
108
|
-
command?: string;
|
|
109
|
-
aggregated_output?: string;
|
|
110
|
-
exit_code?: number | null;
|
|
111
|
-
status?: string;
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
interface CodexEvent {
|
|
115
|
-
type: string;
|
|
116
|
-
thread_id?: string;
|
|
117
|
-
item?: CodexItem;
|
|
118
|
-
usage?: {
|
|
119
|
-
input_tokens?: number;
|
|
120
|
-
cached_input_tokens?: number;
|
|
121
|
-
output_tokens?: number;
|
|
122
|
-
reasoning_output_tokens?: number;
|
|
123
|
-
};
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
// ---------------------------------------------------------------------------
|
|
127
|
-
// normalizeCodexMessage — Codex 事件 → UnifiedStreamMessage | null
|
|
128
|
-
// ---------------------------------------------------------------------------
|
|
129
|
-
|
|
130
|
-
export function normalizeCodexMessage(
|
|
131
|
-
msg: CodexEvent,
|
|
132
|
-
): UnifiedStreamMessage | null {
|
|
133
|
-
// agent_message 文本回复
|
|
134
|
-
if (
|
|
135
|
-
msg.type === "item.completed" &&
|
|
136
|
-
msg.item?.type === "agent_message" &&
|
|
137
|
-
msg.item.text
|
|
138
|
-
) {
|
|
139
|
-
return {
|
|
140
|
-
type: "assistant",
|
|
141
|
-
blocks: [{ type: "text", text: msg.item.text }],
|
|
142
|
-
};
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
// command_execution 工具调用开始
|
|
146
|
-
if (
|
|
147
|
-
msg.type === "item.started" &&
|
|
148
|
-
msg.item?.type === "command_execution" &&
|
|
149
|
-
msg.item.command
|
|
150
|
-
) {
|
|
151
|
-
return {
|
|
152
|
-
type: "assistant",
|
|
153
|
-
blocks: [
|
|
154
|
-
{
|
|
155
|
-
type: "tool_use",
|
|
156
|
-
name: "Bash",
|
|
157
|
-
input: { command: msg.item.command },
|
|
158
|
-
},
|
|
159
|
-
],
|
|
160
|
-
};
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
// command_execution 工具调用完成
|
|
164
|
-
if (
|
|
165
|
-
msg.type === "item.completed" &&
|
|
166
|
-
msg.item?.type === "command_execution"
|
|
167
|
-
) {
|
|
168
|
-
const exitCode = msg.item.exit_code;
|
|
169
|
-
return {
|
|
170
|
-
type: "assistant",
|
|
171
|
-
blocks: [
|
|
172
|
-
{
|
|
173
|
-
type: "tool_result",
|
|
174
|
-
tool_use_id: msg.item.id ?? "",
|
|
175
|
-
content: msg.item.aggregated_output ?? "",
|
|
176
|
-
is_error: exitCode != null && exitCode !== 0 ? true : undefined,
|
|
177
|
-
},
|
|
178
|
-
],
|
|
179
|
-
};
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
// thread.started / turn.started / turn.completed → 不映射为用户可见消息
|
|
183
|
-
return null;
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
// ---------------------------------------------------------------------------
|
|
187
|
-
// 子进程辅助函数
|
|
188
|
-
// ---------------------------------------------------------------------------
|
|
189
|
-
|
|
190
|
-
function spawnCodex(
|
|
191
|
-
args: string[],
|
|
192
|
-
cwd?: string,
|
|
193
|
-
stdinText?: string,
|
|
194
|
-
modelOverride?: string,
|
|
195
|
-
effortOverride?: string,
|
|
196
|
-
): ChildProcess {
|
|
197
|
-
const allArgs = [...args];
|
|
198
|
-
const model = modelOverride ?? resolveCodexModel();
|
|
199
|
-
if (model) {
|
|
200
|
-
// 把 -m 插在 exec 后面、其他参数前面
|
|
201
|
-
const execIdx = allArgs.indexOf("exec");
|
|
202
|
-
allArgs.splice(execIdx + 1, 0, "-m", model);
|
|
203
|
-
}
|
|
204
|
-
const effort = effortOverride ?? resolveCodexEffort();
|
|
205
|
-
if (effort) {
|
|
206
|
-
allArgs.push("-c", `model_reasoning_effort="${effort}"`);
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
const proc = spawn(detectCodexCommand(), allArgs, {
|
|
210
|
-
cwd,
|
|
211
|
-
stdio: [stdinText !== undefined ? "pipe" : "ignore", "pipe", "pipe"],
|
|
212
|
-
windowsHide: true,
|
|
213
|
-
shell: true,
|
|
214
|
-
});
|
|
215
|
-
|
|
216
|
-
let stderr = "";
|
|
217
|
-
proc.stderr!.on("data", (chunk: Buffer) => {
|
|
218
|
-
stderr += chunk.toString();
|
|
219
|
-
});
|
|
220
|
-
proc.on("close", (code) => {
|
|
221
|
-
if (code !== 0 && stderr.trim()) {
|
|
222
|
-
console.error(
|
|
223
|
-
`[Codex stderr] exit=${code}: ${stderr.trim().slice(0, 2000)}`,
|
|
224
|
-
);
|
|
225
|
-
}
|
|
226
|
-
});
|
|
227
|
-
|
|
228
|
-
if (stdinText !== undefined) {
|
|
229
|
-
proc.stdin!.write(stdinText);
|
|
230
|
-
proc.stdin!.end();
|
|
231
|
-
}
|
|
232
|
-
return proc;
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
async function* readJsonLines(
|
|
236
|
-
proc: ChildProcess,
|
|
237
|
-
signal?: AbortSignal,
|
|
238
|
-
rawLog?: RawStreamLogHandle | null,
|
|
239
|
-
): AsyncGenerator<CodexEvent> {
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
const
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
}
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
effort?: string;
|
|
382
|
-
}
|
|
383
|
-
|
|
384
|
-
export function createCodexAdapter(
|
|
385
|
-
options: CreateCodexAdapterOptions = {},
|
|
386
|
-
): ToolAdapter {
|
|
387
|
-
return new CodexAdapter(
|
|
388
|
-
options.metaStore ?? defaultCodexSessionMetaStore,
|
|
389
|
-
options.model,
|
|
390
|
-
options.effort,
|
|
391
|
-
);
|
|
392
|
-
}
|
|
1
|
+
// =============================================================================
|
|
2
|
+
// codex-adapter.ts — OpenAI Codex CLI 适配器
|
|
3
|
+
// =============================================================================
|
|
4
|
+
// 通过 codex exec --json 与 Codex CLI 交互。
|
|
5
|
+
// - createSession: 生成 UUID sessionId,记录 cwd,不创建 Codex 线程(延迟到首次 prompt)
|
|
6
|
+
// - prompt: 首次调用用 codex exec 创建线程,后续用 codex exec resume 恢复
|
|
7
|
+
// - getSessionInfo: 从持久化映射读取 cwd / threadId
|
|
8
|
+
// =============================================================================
|
|
9
|
+
|
|
10
|
+
import { spawn, type ChildProcess } from "node:child_process";
|
|
11
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
12
|
+
import { dirname, join } from "node:path";
|
|
13
|
+
import { randomUUID } from "node:crypto";
|
|
14
|
+
import { fileURLToPath } from "node:url";
|
|
15
|
+
|
|
16
|
+
import type {
|
|
17
|
+
ToolAdapter,
|
|
18
|
+
ToolPromptOptions,
|
|
19
|
+
UnifiedBlock,
|
|
20
|
+
UnifiedStreamMessage,
|
|
21
|
+
CreateSessionResult,
|
|
22
|
+
SessionInfo,
|
|
23
|
+
} from "./adapter-interface.ts";
|
|
24
|
+
import { parseUserCommand } from "./adapter-interface.ts";
|
|
25
|
+
import {
|
|
26
|
+
defaultCodexSessionMetaStore,
|
|
27
|
+
type CodexSessionMetaStore,
|
|
28
|
+
} from "./codex-session-meta-store.ts";
|
|
29
|
+
import { killProcessTree } from "./proc-tree-kill.ts";
|
|
30
|
+
import { config, RAW_STREAM_LOGS_DIR } from "../config.ts";
|
|
31
|
+
import {
|
|
32
|
+
createRawStreamLog,
|
|
33
|
+
type RawStreamLogHandle,
|
|
34
|
+
} from "./raw-stream-log.ts";
|
|
35
|
+
import { readJsonLinesWithBadJsonIdleWatchdog } from "./jsonl-stream.ts";
|
|
36
|
+
|
|
37
|
+
// ---------------------------------------------------------------------------
|
|
38
|
+
// 特殊注入提示
|
|
39
|
+
// ---------------------------------------------------------------------------
|
|
40
|
+
|
|
41
|
+
const PROJECT_ROOT = dirname(dirname(dirname(fileURLToPath(import.meta.url))));
|
|
42
|
+
const CODEX_SPECIFIC_PROMPT_PATH = join(
|
|
43
|
+
PROJECT_ROOT,
|
|
44
|
+
"agent-prompts",
|
|
45
|
+
"codex_specific.md",
|
|
46
|
+
);
|
|
47
|
+
|
|
48
|
+
function readCodexSpecificInjectionPrompt(): string | null {
|
|
49
|
+
try {
|
|
50
|
+
if (!existsSync(CODEX_SPECIFIC_PROMPT_PATH)) return null;
|
|
51
|
+
const prompt = readFileSync(CODEX_SPECIFIC_PROMPT_PATH, "utf-8").trim();
|
|
52
|
+
return prompt.length > 0 ? prompt : null;
|
|
53
|
+
} catch {
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function buildCodexPromptText(userText: string): string {
|
|
59
|
+
const prompt = readCodexSpecificInjectionPrompt();
|
|
60
|
+
if (!prompt) return userText;
|
|
61
|
+
|
|
62
|
+
return [
|
|
63
|
+
"[ChatCCC Codex-specific injection prompt]",
|
|
64
|
+
prompt,
|
|
65
|
+
"[/ChatCCC Codex-specific injection prompt]",
|
|
66
|
+
"",
|
|
67
|
+
userText,
|
|
68
|
+
].join("\n");
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// ---------------------------------------------------------------------------
|
|
72
|
+
// 命令与参数
|
|
73
|
+
// ---------------------------------------------------------------------------
|
|
74
|
+
|
|
75
|
+
/** 可通过 config.json codex.path 自定义 Codex 可执行文件路径 */
|
|
76
|
+
function detectCodexCommand(): string {
|
|
77
|
+
return config.codex.path || "codex";
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** exec 模式共用参数:JSONL 输出、绕过沙盒和确认、跳过 git 仓库检查 */
|
|
81
|
+
const CODEX_BASE_ARGS = [
|
|
82
|
+
"exec",
|
|
83
|
+
"--json",
|
|
84
|
+
"--dangerously-bypass-approvals-and-sandbox",
|
|
85
|
+
"--skip-git-repo-check",
|
|
86
|
+
];
|
|
87
|
+
|
|
88
|
+
/** codex 模型;留空("")表示不传 --model,由 codex config.toml 决定 */
|
|
89
|
+
function resolveCodexModel(): string | null {
|
|
90
|
+
const m = config.codex.model;
|
|
91
|
+
return m.trim() !== "" ? m : null;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** codex 努力程度(映射为 -c model_reasoning_effort=<value>);留空表示不传 */
|
|
95
|
+
function resolveCodexEffort(): string | null {
|
|
96
|
+
const e = config.codex.effort;
|
|
97
|
+
return e.trim() !== "" ? e : null;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// ---------------------------------------------------------------------------
|
|
101
|
+
// 类型:Codex JSONL 消息行
|
|
102
|
+
// ---------------------------------------------------------------------------
|
|
103
|
+
|
|
104
|
+
interface CodexItem {
|
|
105
|
+
id?: string;
|
|
106
|
+
type?: string;
|
|
107
|
+
text?: string;
|
|
108
|
+
command?: string;
|
|
109
|
+
aggregated_output?: string;
|
|
110
|
+
exit_code?: number | null;
|
|
111
|
+
status?: string;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
interface CodexEvent {
|
|
115
|
+
type: string;
|
|
116
|
+
thread_id?: string;
|
|
117
|
+
item?: CodexItem;
|
|
118
|
+
usage?: {
|
|
119
|
+
input_tokens?: number;
|
|
120
|
+
cached_input_tokens?: number;
|
|
121
|
+
output_tokens?: number;
|
|
122
|
+
reasoning_output_tokens?: number;
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// ---------------------------------------------------------------------------
|
|
127
|
+
// normalizeCodexMessage — Codex 事件 → UnifiedStreamMessage | null
|
|
128
|
+
// ---------------------------------------------------------------------------
|
|
129
|
+
|
|
130
|
+
export function normalizeCodexMessage(
|
|
131
|
+
msg: CodexEvent,
|
|
132
|
+
): UnifiedStreamMessage | null {
|
|
133
|
+
// agent_message 文本回复
|
|
134
|
+
if (
|
|
135
|
+
msg.type === "item.completed" &&
|
|
136
|
+
msg.item?.type === "agent_message" &&
|
|
137
|
+
msg.item.text
|
|
138
|
+
) {
|
|
139
|
+
return {
|
|
140
|
+
type: "assistant",
|
|
141
|
+
blocks: [{ type: "text", text: msg.item.text }],
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// command_execution 工具调用开始
|
|
146
|
+
if (
|
|
147
|
+
msg.type === "item.started" &&
|
|
148
|
+
msg.item?.type === "command_execution" &&
|
|
149
|
+
msg.item.command
|
|
150
|
+
) {
|
|
151
|
+
return {
|
|
152
|
+
type: "assistant",
|
|
153
|
+
blocks: [
|
|
154
|
+
{
|
|
155
|
+
type: "tool_use",
|
|
156
|
+
name: "Bash",
|
|
157
|
+
input: { command: msg.item.command },
|
|
158
|
+
},
|
|
159
|
+
],
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// command_execution 工具调用完成
|
|
164
|
+
if (
|
|
165
|
+
msg.type === "item.completed" &&
|
|
166
|
+
msg.item?.type === "command_execution"
|
|
167
|
+
) {
|
|
168
|
+
const exitCode = msg.item.exit_code;
|
|
169
|
+
return {
|
|
170
|
+
type: "assistant",
|
|
171
|
+
blocks: [
|
|
172
|
+
{
|
|
173
|
+
type: "tool_result",
|
|
174
|
+
tool_use_id: msg.item.id ?? "",
|
|
175
|
+
content: msg.item.aggregated_output ?? "",
|
|
176
|
+
is_error: exitCode != null && exitCode !== 0 ? true : undefined,
|
|
177
|
+
},
|
|
178
|
+
],
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// thread.started / turn.started / turn.completed → 不映射为用户可见消息
|
|
183
|
+
return null;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// ---------------------------------------------------------------------------
|
|
187
|
+
// 子进程辅助函数
|
|
188
|
+
// ---------------------------------------------------------------------------
|
|
189
|
+
|
|
190
|
+
function spawnCodex(
|
|
191
|
+
args: string[],
|
|
192
|
+
cwd?: string,
|
|
193
|
+
stdinText?: string,
|
|
194
|
+
modelOverride?: string,
|
|
195
|
+
effortOverride?: string,
|
|
196
|
+
): ChildProcess {
|
|
197
|
+
const allArgs = [...args];
|
|
198
|
+
const model = modelOverride ?? resolveCodexModel();
|
|
199
|
+
if (model) {
|
|
200
|
+
// 把 -m 插在 exec 后面、其他参数前面
|
|
201
|
+
const execIdx = allArgs.indexOf("exec");
|
|
202
|
+
allArgs.splice(execIdx + 1, 0, "-m", model);
|
|
203
|
+
}
|
|
204
|
+
const effort = effortOverride ?? resolveCodexEffort();
|
|
205
|
+
if (effort) {
|
|
206
|
+
allArgs.push("-c", `model_reasoning_effort="${effort}"`);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
const proc = spawn(detectCodexCommand(), allArgs, {
|
|
210
|
+
cwd,
|
|
211
|
+
stdio: [stdinText !== undefined ? "pipe" : "ignore", "pipe", "pipe"],
|
|
212
|
+
windowsHide: true,
|
|
213
|
+
shell: true,
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
let stderr = "";
|
|
217
|
+
proc.stderr!.on("data", (chunk: Buffer) => {
|
|
218
|
+
stderr += chunk.toString();
|
|
219
|
+
});
|
|
220
|
+
proc.on("close", (code) => {
|
|
221
|
+
if (code !== 0 && stderr.trim()) {
|
|
222
|
+
console.error(
|
|
223
|
+
`[Codex stderr] exit=${code}: ${stderr.trim().slice(0, 2000)}`,
|
|
224
|
+
);
|
|
225
|
+
}
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
if (stdinText !== undefined) {
|
|
229
|
+
proc.stdin!.write(stdinText);
|
|
230
|
+
proc.stdin!.end();
|
|
231
|
+
}
|
|
232
|
+
return proc;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
async function* readJsonLines(
|
|
236
|
+
proc: ChildProcess,
|
|
237
|
+
signal?: AbortSignal,
|
|
238
|
+
rawLog?: RawStreamLogHandle | null,
|
|
239
|
+
): AsyncGenerator<CodexEvent> {
|
|
240
|
+
yield* readJsonLinesWithBadJsonIdleWatchdog<CodexEvent>({
|
|
241
|
+
input: proc.stdout!,
|
|
242
|
+
tool: "codex",
|
|
243
|
+
tag: "codex",
|
|
244
|
+
signal,
|
|
245
|
+
rawLog,
|
|
246
|
+
parse: (line) => JSON.parse(line) as CodexEvent,
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// ---------------------------------------------------------------------------
|
|
251
|
+
// 适配器实现
|
|
252
|
+
// ---------------------------------------------------------------------------
|
|
253
|
+
|
|
254
|
+
class CodexAdapter implements ToolAdapter {
|
|
255
|
+
readonly displayName = "Codex";
|
|
256
|
+
readonly sessionDescPrefix = "Codex Session:";
|
|
257
|
+
private metaStore: CodexSessionMetaStore;
|
|
258
|
+
private modelOverride: string | undefined;
|
|
259
|
+
private effortOverride: string | undefined;
|
|
260
|
+
|
|
261
|
+
constructor(metaStore: CodexSessionMetaStore, modelOverride?: string, effortOverride?: string) {
|
|
262
|
+
this.metaStore = metaStore;
|
|
263
|
+
this.modelOverride = modelOverride;
|
|
264
|
+
this.effortOverride = effortOverride;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// createSession: 生成 sessionId,记录 cwd,不创建 Codex 线程(延迟到首次 prompt)
|
|
268
|
+
async createSession(cwd: string): Promise<CreateSessionResult> {
|
|
269
|
+
const sessionId = randomUUID();
|
|
270
|
+
await this.metaStore.set(sessionId, { cwd });
|
|
271
|
+
return { sessionId };
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
async *prompt(
|
|
275
|
+
sessionId: string,
|
|
276
|
+
userText: string,
|
|
277
|
+
cwd: string,
|
|
278
|
+
signal?: AbortSignal,
|
|
279
|
+
options?: ToolPromptOptions,
|
|
280
|
+
): AsyncIterable<UnifiedStreamMessage> {
|
|
281
|
+
let meta = await this.metaStore.get(sessionId);
|
|
282
|
+
const threadId = meta?.threadId;
|
|
283
|
+
const isFirstPrompt = !threadId;
|
|
284
|
+
|
|
285
|
+
// 首次 prompt: codex exec 创建新线程
|
|
286
|
+
// 后续 prompt: codex exec resume 恢复已有线程(resume 不接受 -C,cwd 继承自原线程)
|
|
287
|
+
const cmd = parseUserCommand(userText);
|
|
288
|
+
const baseArgs = cmd.mode
|
|
289
|
+
? ["exec", "--json", "--sandbox", "read-only", "--skip-git-repo-check"]
|
|
290
|
+
: CODEX_BASE_ARGS;
|
|
291
|
+
const args = isFirstPrompt
|
|
292
|
+
? [...baseArgs, "-C", cwd, "-"]
|
|
293
|
+
: [...baseArgs, "resume", threadId, "-"];
|
|
294
|
+
|
|
295
|
+
const proc = spawnCodex(args, cwd, buildCodexPromptText(userText), this.modelOverride, this.effortOverride);
|
|
296
|
+
if (proc.pid !== undefined) options?.onProcessStart?.({ pid: proc.pid });
|
|
297
|
+
|
|
298
|
+
const rawLogConfig = config.rawStreamLogs.codex;
|
|
299
|
+
let rawLog: RawStreamLogHandle | null = null;
|
|
300
|
+
try {
|
|
301
|
+
rawLog = await createRawStreamLog({
|
|
302
|
+
enabled: rawLogConfig.enabled,
|
|
303
|
+
rootDir: RAW_STREAM_LOGS_DIR,
|
|
304
|
+
tool: "codex",
|
|
305
|
+
sessionId,
|
|
306
|
+
label: "prompt",
|
|
307
|
+
maxBytesPerTurn: rawLogConfig.maxBytesPerTurn,
|
|
308
|
+
retentionDays: rawLogConfig.retentionDays,
|
|
309
|
+
});
|
|
310
|
+
} catch (err) {
|
|
311
|
+
console.error(`[Codex raw stream log] create failed: ${(err as Error).message}`);
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
// 关键:spawn 用了 shell:true,proc.pid 指向的是壳进程(cmd.exe / sh)。
|
|
315
|
+
// 真正干活的是壳的孙子 codex.exe。普通 proc.kill() 在 Windows 上只杀第一层,
|
|
316
|
+
// 会留下幽灵 node + codex.exe 继续烧 token、stream-state 永远停在 running。
|
|
317
|
+
// 因此 abort 与 finally 都必须用 killProcessTree 整棵进程树一起收尸。
|
|
318
|
+
const onAbort = () => { void killProcessTree(proc.pid); };
|
|
319
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
320
|
+
let completed = false;
|
|
321
|
+
|
|
322
|
+
try {
|
|
323
|
+
for await (const raw of readJsonLines(proc, signal, rawLog)) {
|
|
324
|
+
if (signal?.aborted) break;
|
|
325
|
+
if (raw.type === "turn.completed") completed = true;
|
|
326
|
+
|
|
327
|
+
if (
|
|
328
|
+
isFirstPrompt &&
|
|
329
|
+
raw.type === "thread.started" &&
|
|
330
|
+
raw.thread_id
|
|
331
|
+
) {
|
|
332
|
+
void this.metaStore
|
|
333
|
+
.setThreadId(sessionId, raw.thread_id)
|
|
334
|
+
.catch(() => {});
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
const normalized = normalizeCodexMessage(raw);
|
|
338
|
+
if (normalized) yield normalized;
|
|
339
|
+
}
|
|
340
|
+
} finally {
|
|
341
|
+
signal?.removeEventListener("abort", onAbort);
|
|
342
|
+
await killProcessTree(proc.pid);
|
|
343
|
+
await rawLog?.close({ keep: rawLogConfig.keepCompleted || signal?.aborted === true || !completed });
|
|
344
|
+
if (proc.pid !== undefined) options?.onProcessExit?.({ pid: proc.pid });
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
async getSessionInfo(
|
|
349
|
+
sessionId: string,
|
|
350
|
+
): Promise<SessionInfo | undefined> {
|
|
351
|
+
const meta = await this.metaStore.get(sessionId);
|
|
352
|
+
if (!meta) return undefined;
|
|
353
|
+
return { sessionId, cwd: meta.cwd };
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
async closeSession(_sessionId: string): Promise<void> {
|
|
357
|
+
// no-op:子进程由 prompt 的 finally 自动 kill
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
// ---------------------------------------------------------------------------
|
|
362
|
+
// 工厂函数
|
|
363
|
+
// ---------------------------------------------------------------------------
|
|
364
|
+
|
|
365
|
+
export interface CreateCodexAdapterOptions {
|
|
366
|
+
metaStore?: CodexSessionMetaStore;
|
|
367
|
+
/** per-session 模型覆盖(/model 命令);传了就用,不传走全局 codex.model */
|
|
368
|
+
model?: string;
|
|
369
|
+
effort?: string;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
export function createCodexAdapter(
|
|
373
|
+
options: CreateCodexAdapterOptions = {},
|
|
374
|
+
): ToolAdapter {
|
|
375
|
+
return new CodexAdapter(
|
|
376
|
+
options.metaStore ?? defaultCodexSessionMetaStore,
|
|
377
|
+
options.model,
|
|
378
|
+
options.effort,
|
|
379
|
+
);
|
|
380
|
+
}
|