chatccc 0.2.16 → 0.2.18

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,294 +1,295 @@
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 { createInterface } from "node:readline";
12
- import { randomUUID } from "node:crypto";
13
-
14
- import type {
15
- ToolAdapter,
16
- UnifiedBlock,
17
- UnifiedStreamMessage,
18
- CreateSessionResult,
19
- SessionInfo,
20
- } from "./adapter-interface.ts";
21
- import {
22
- defaultCodexSessionMetaStore,
23
- type CodexSessionMetaStore,
24
- } from "./codex-session-meta-store.ts";
25
-
26
- // ---------------------------------------------------------------------------
27
- // 命令与参数
28
- // ---------------------------------------------------------------------------
29
-
30
- /** 可通过 CHATCCC_CODEX_COMMAND 环境变量自定义 Codex 可执行文件路径 */
31
- function detectCodexCommand(): string {
32
- return process.env.CHATCCC_CODEX_COMMAND?.trim() || "codex";
33
- }
34
- const CODEX_COMMAND = detectCodexCommand();
35
-
36
- /** exec 模式共用参数:JSONL 输出、绕过沙盒和确认、跳过 git 仓库检查 */
37
- const CODEX_BASE_ARGS = [
38
- "exec",
39
- "--json",
40
- "--dangerously-bypass-approvals-and-sandbox",
41
- "--skip-git-repo-check",
42
- ];
43
-
44
- /** codex 模型 */
45
- function resolveCodexModel(): string | null {
46
- const m = process.env.CHATCCC_CODEX_MODEL?.trim();
47
- return m && m !== "default" ? m : null;
48
- }
49
-
50
- /** codex 努力程度(映射为 -c model_reasoning_effort=<value>) */
51
- function resolveCodexEffort(): string | null {
52
- const e = process.env.CHATCCC_CODEX_EFFORT?.trim();
53
- return e && e !== "default" ? e : null;
54
- }
55
-
56
- // ---------------------------------------------------------------------------
57
- // 类型:Codex JSONL 消息行
58
- // ---------------------------------------------------------------------------
59
-
60
- interface CodexItem {
61
- id?: string;
62
- type?: string;
63
- text?: string;
64
- command?: string;
65
- aggregated_output?: string;
66
- exit_code?: number | null;
67
- status?: string;
68
- }
69
-
70
- interface CodexEvent {
71
- type: string;
72
- thread_id?: string;
73
- item?: CodexItem;
74
- usage?: {
75
- input_tokens?: number;
76
- cached_input_tokens?: number;
77
- output_tokens?: number;
78
- reasoning_output_tokens?: number;
79
- };
80
- }
81
-
82
- // ---------------------------------------------------------------------------
83
- // normalizeCodexMessage — Codex 事件 → UnifiedStreamMessage | null
84
- // ---------------------------------------------------------------------------
85
-
86
- export function normalizeCodexMessage(
87
- msg: CodexEvent,
88
- ): UnifiedStreamMessage | null {
89
- // agent_message 文本回复
90
- if (
91
- msg.type === "item.completed" &&
92
- msg.item?.type === "agent_message" &&
93
- msg.item.text
94
- ) {
95
- return {
96
- type: "assistant",
97
- blocks: [{ type: "text", text: msg.item.text }],
98
- };
99
- }
100
-
101
- // command_execution 工具调用开始
102
- if (
103
- msg.type === "item.started" &&
104
- msg.item?.type === "command_execution" &&
105
- msg.item.command
106
- ) {
107
- return {
108
- type: "assistant",
109
- blocks: [
110
- {
111
- type: "tool_use",
112
- name: "Bash",
113
- input: { command: msg.item.command },
114
- },
115
- ],
116
- };
117
- }
118
-
119
- // command_execution 工具调用完成
120
- if (
121
- msg.type === "item.completed" &&
122
- msg.item?.type === "command_execution"
123
- ) {
124
- const exitCode = msg.item.exit_code;
125
- return {
126
- type: "assistant",
127
- blocks: [
128
- {
129
- type: "tool_result",
130
- tool_use_id: msg.item.id ?? "",
131
- content: msg.item.aggregated_output ?? "",
132
- is_error: exitCode != null && exitCode !== 0 ? true : undefined,
133
- },
134
- ],
135
- };
136
- }
137
-
138
- // thread.started / turn.started / turn.completed → 不映射为用户可见消息
139
- return null;
140
- }
141
-
142
- // ---------------------------------------------------------------------------
143
- // 子进程辅助函数
144
- // ---------------------------------------------------------------------------
145
-
146
- function spawnCodex(
147
- args: string[],
148
- cwd?: string,
149
- stdinText?: string,
150
- ): ChildProcess {
151
- const allArgs = [...args];
152
- const model = resolveCodexModel();
153
- if (model) {
154
- // -m 插在 exec 后面、其他参数前面
155
- const execIdx = allArgs.indexOf("exec");
156
- allArgs.splice(execIdx + 1, 0, "-m", model);
157
- }
158
- const effort = resolveCodexEffort();
159
- if (effort) {
160
- allArgs.push("-c", `model_reasoning_effort="${effort}"`);
161
- }
162
-
163
- const proc = spawn(CODEX_COMMAND, allArgs, {
164
- cwd,
165
- stdio: [stdinText !== undefined ? "pipe" : "ignore", "pipe", "pipe"],
166
- windowsHide: true,
167
- shell: true,
168
- });
169
-
170
- let stderr = "";
171
- proc.stderr!.on("data", (chunk: Buffer) => {
172
- stderr += chunk.toString();
173
- });
174
- proc.on("close", (code) => {
175
- if (code !== 0 && stderr.trim()) {
176
- console.error(
177
- `[Codex stderr] exit=${code}: ${stderr.trim().slice(0, 2000)}`,
178
- );
179
- }
180
- });
181
-
182
- if (stdinText !== undefined) {
183
- proc.stdin!.write(stdinText);
184
- proc.stdin!.end();
185
- }
186
- return proc;
187
- }
188
-
189
- async function* readJsonLines(
190
- proc: ChildProcess,
191
- signal?: AbortSignal,
192
- ): AsyncGenerator<CodexEvent> {
193
- const rl = createInterface({ input: proc.stdout!, crlfDelay: Infinity });
194
- for await (const line of rl) {
195
- if (signal?.aborted) break;
196
- const trimmed = line.trim();
197
- if (!trimmed) continue;
198
- try {
199
- yield JSON.parse(trimmed) as CodexEvent;
200
- } catch {
201
- // JSON 行静默跳过(如 "Reading prompt from stdin...")
202
- }
203
- }
204
- }
205
-
206
- // ---------------------------------------------------------------------------
207
- // 适配器实现
208
- // ---------------------------------------------------------------------------
209
-
210
- class CodexAdapter implements ToolAdapter {
211
- readonly displayName = "Codex";
212
- readonly sessionDescPrefix = "Codex Session:";
213
- private metaStore: CodexSessionMetaStore;
214
-
215
- constructor(metaStore: CodexSessionMetaStore) {
216
- this.metaStore = metaStore;
217
- }
218
-
219
- // createSession: 生成 sessionId,记录 cwd,不创建 Codex 线程(延迟到首次 prompt)
220
- async createSession(cwd: string): Promise<CreateSessionResult> {
221
- const sessionId = randomUUID();
222
- await this.metaStore.set(sessionId, { cwd });
223
- return { sessionId };
224
- }
225
-
226
- async *prompt(
227
- sessionId: string,
228
- userText: string,
229
- cwd: string,
230
- signal?: AbortSignal,
231
- ): AsyncIterable<UnifiedStreamMessage> {
232
- let meta = await this.metaStore.get(sessionId);
233
- const threadId = meta?.threadId;
234
- const isFirstPrompt = !threadId;
235
-
236
- // 首次 prompt: codex exec 创建新线程
237
- // 后续 prompt: codex exec resume 恢复已有线程(resume 不接受 -C,cwd 继承自原线程)
238
- const args = isFirstPrompt
239
- ? [...CODEX_BASE_ARGS, "-C", cwd, "-"]
240
- : [...CODEX_BASE_ARGS, "resume", threadId, "-"];
241
-
242
- const proc = spawnCodex(args, cwd, userText);
243
-
244
- try {
245
- for await (const raw of readJsonLines(proc, signal)) {
246
- if (signal?.aborted) break;
247
-
248
- // 首次 prompt 时从 thread.started 事件学习 threadId
249
- if (
250
- isFirstPrompt &&
251
- raw.type === "thread.started" &&
252
- raw.thread_id
253
- ) {
254
- void this.metaStore
255
- .setThreadId(sessionId, raw.thread_id)
256
- .catch(() => {});
257
- }
258
-
259
- const normalized = normalizeCodexMessage(raw);
260
- if (normalized) yield normalized;
261
- }
262
- } finally {
263
- proc.kill();
264
- }
265
- }
266
-
267
- async getSessionInfo(
268
- sessionId: string,
269
- ): Promise<SessionInfo | undefined> {
270
- const meta = await this.metaStore.get(sessionId);
271
- if (!meta) return undefined;
272
- return { sessionId, cwd: meta.cwd };
273
- }
274
-
275
- async closeSession(_sessionId: string): Promise<void> {
276
- // no-op:子进程由 prompt finally 自动 kill
277
- }
278
- }
279
-
280
- // ---------------------------------------------------------------------------
281
- // 工厂函数
282
- // ---------------------------------------------------------------------------
283
-
284
- export interface CreateCodexAdapterOptions {
285
- metaStore?: CodexSessionMetaStore;
286
- }
287
-
288
- export function createCodexAdapter(
289
- options: CreateCodexAdapterOptions = {},
290
- ): ToolAdapter {
291
- return new CodexAdapter(
292
- options.metaStore ?? defaultCodexSessionMetaStore,
293
- );
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 { createInterface } from "node:readline";
12
+ import { randomUUID } from "node:crypto";
13
+
14
+ import type {
15
+ ToolAdapter,
16
+ UnifiedBlock,
17
+ UnifiedStreamMessage,
18
+ CreateSessionResult,
19
+ SessionInfo,
20
+ } from "./adapter-interface.ts";
21
+ import {
22
+ defaultCodexSessionMetaStore,
23
+ type CodexSessionMetaStore,
24
+ } from "./codex-session-meta-store.ts";
25
+ import { config } from "../config.ts";
26
+
27
+ // ---------------------------------------------------------------------------
28
+ // 命令与参数
29
+ // ---------------------------------------------------------------------------
30
+
31
+ /** 可通过 config.json codex.path 自定义 Codex 可执行文件路径 */
32
+ function detectCodexCommand(): string {
33
+ return config.codex.path || "codex";
34
+ }
35
+ const CODEX_COMMAND = detectCodexCommand();
36
+
37
+ /** exec 模式共用参数:JSONL 输出、绕过沙盒和确认、跳过 git 仓库检查 */
38
+ const CODEX_BASE_ARGS = [
39
+ "exec",
40
+ "--json",
41
+ "--dangerously-bypass-approvals-and-sandbox",
42
+ "--skip-git-repo-check",
43
+ ];
44
+
45
+ /** codex 模型;留空("")表示不传 --model,由 codex config.toml 决定 */
46
+ function resolveCodexModel(): string | null {
47
+ const m = config.codex.model;
48
+ return m.trim() !== "" ? m : null;
49
+ }
50
+
51
+ /** codex 努力程度(映射为 -c model_reasoning_effort=<value>);留空表示不传 */
52
+ function resolveCodexEffort(): string | null {
53
+ const e = config.codex.effort;
54
+ return e.trim() !== "" ? e : null;
55
+ }
56
+
57
+ // ---------------------------------------------------------------------------
58
+ // 类型:Codex JSONL 消息行
59
+ // ---------------------------------------------------------------------------
60
+
61
+ interface CodexItem {
62
+ id?: string;
63
+ type?: string;
64
+ text?: string;
65
+ command?: string;
66
+ aggregated_output?: string;
67
+ exit_code?: number | null;
68
+ status?: string;
69
+ }
70
+
71
+ interface CodexEvent {
72
+ type: string;
73
+ thread_id?: string;
74
+ item?: CodexItem;
75
+ usage?: {
76
+ input_tokens?: number;
77
+ cached_input_tokens?: number;
78
+ output_tokens?: number;
79
+ reasoning_output_tokens?: number;
80
+ };
81
+ }
82
+
83
+ // ---------------------------------------------------------------------------
84
+ // normalizeCodexMessage — Codex 事件 → UnifiedStreamMessage | null
85
+ // ---------------------------------------------------------------------------
86
+
87
+ export function normalizeCodexMessage(
88
+ msg: CodexEvent,
89
+ ): UnifiedStreamMessage | null {
90
+ // agent_message 文本回复
91
+ if (
92
+ msg.type === "item.completed" &&
93
+ msg.item?.type === "agent_message" &&
94
+ msg.item.text
95
+ ) {
96
+ return {
97
+ type: "assistant",
98
+ blocks: [{ type: "text", text: msg.item.text }],
99
+ };
100
+ }
101
+
102
+ // command_execution 工具调用开始
103
+ if (
104
+ msg.type === "item.started" &&
105
+ msg.item?.type === "command_execution" &&
106
+ msg.item.command
107
+ ) {
108
+ return {
109
+ type: "assistant",
110
+ blocks: [
111
+ {
112
+ type: "tool_use",
113
+ name: "Bash",
114
+ input: { command: msg.item.command },
115
+ },
116
+ ],
117
+ };
118
+ }
119
+
120
+ // command_execution 工具调用完成
121
+ if (
122
+ msg.type === "item.completed" &&
123
+ msg.item?.type === "command_execution"
124
+ ) {
125
+ const exitCode = msg.item.exit_code;
126
+ return {
127
+ type: "assistant",
128
+ blocks: [
129
+ {
130
+ type: "tool_result",
131
+ tool_use_id: msg.item.id ?? "",
132
+ content: msg.item.aggregated_output ?? "",
133
+ is_error: exitCode != null && exitCode !== 0 ? true : undefined,
134
+ },
135
+ ],
136
+ };
137
+ }
138
+
139
+ // thread.started / turn.started / turn.completed → 不映射为用户可见消息
140
+ return null;
141
+ }
142
+
143
+ // ---------------------------------------------------------------------------
144
+ // 子进程辅助函数
145
+ // ---------------------------------------------------------------------------
146
+
147
+ function spawnCodex(
148
+ args: string[],
149
+ cwd?: string,
150
+ stdinText?: string,
151
+ ): ChildProcess {
152
+ const allArgs = [...args];
153
+ const model = resolveCodexModel();
154
+ if (model) {
155
+ // -m 插在 exec 后面、其他参数前面
156
+ const execIdx = allArgs.indexOf("exec");
157
+ allArgs.splice(execIdx + 1, 0, "-m", model);
158
+ }
159
+ const effort = resolveCodexEffort();
160
+ if (effort) {
161
+ allArgs.push("-c", `model_reasoning_effort="${effort}"`);
162
+ }
163
+
164
+ const proc = spawn(CODEX_COMMAND, allArgs, {
165
+ cwd,
166
+ stdio: [stdinText !== undefined ? "pipe" : "ignore", "pipe", "pipe"],
167
+ windowsHide: true,
168
+ shell: true,
169
+ });
170
+
171
+ let stderr = "";
172
+ proc.stderr!.on("data", (chunk: Buffer) => {
173
+ stderr += chunk.toString();
174
+ });
175
+ proc.on("close", (code) => {
176
+ if (code !== 0 && stderr.trim()) {
177
+ console.error(
178
+ `[Codex stderr] exit=${code}: ${stderr.trim().slice(0, 2000)}`,
179
+ );
180
+ }
181
+ });
182
+
183
+ if (stdinText !== undefined) {
184
+ proc.stdin!.write(stdinText);
185
+ proc.stdin!.end();
186
+ }
187
+ return proc;
188
+ }
189
+
190
+ async function* readJsonLines(
191
+ proc: ChildProcess,
192
+ signal?: AbortSignal,
193
+ ): AsyncGenerator<CodexEvent> {
194
+ const rl = createInterface({ input: proc.stdout!, crlfDelay: Infinity });
195
+ for await (const line of rl) {
196
+ if (signal?.aborted) break;
197
+ const trimmed = line.trim();
198
+ if (!trimmed) continue;
199
+ try {
200
+ yield JSON.parse(trimmed) as CodexEvent;
201
+ } catch {
202
+ // 非 JSON 行静默跳过(如 "Reading prompt from stdin...")
203
+ }
204
+ }
205
+ }
206
+
207
+ // ---------------------------------------------------------------------------
208
+ // 适配器实现
209
+ // ---------------------------------------------------------------------------
210
+
211
+ class CodexAdapter implements ToolAdapter {
212
+ readonly displayName = "Codex";
213
+ readonly sessionDescPrefix = "Codex Session:";
214
+ private metaStore: CodexSessionMetaStore;
215
+
216
+ constructor(metaStore: CodexSessionMetaStore) {
217
+ this.metaStore = metaStore;
218
+ }
219
+
220
+ // createSession: 生成 sessionId,记录 cwd,不创建 Codex 线程(延迟到首次 prompt)
221
+ async createSession(cwd: string): Promise<CreateSessionResult> {
222
+ const sessionId = randomUUID();
223
+ await this.metaStore.set(sessionId, { cwd });
224
+ return { sessionId };
225
+ }
226
+
227
+ async *prompt(
228
+ sessionId: string,
229
+ userText: string,
230
+ cwd: string,
231
+ signal?: AbortSignal,
232
+ ): AsyncIterable<UnifiedStreamMessage> {
233
+ let meta = await this.metaStore.get(sessionId);
234
+ const threadId = meta?.threadId;
235
+ const isFirstPrompt = !threadId;
236
+
237
+ // 首次 prompt: codex exec 创建新线程
238
+ // 后续 prompt: codex exec resume 恢复已有线程(resume 不接受 -C,cwd 继承自原线程)
239
+ const args = isFirstPrompt
240
+ ? [...CODEX_BASE_ARGS, "-C", cwd, "-"]
241
+ : [...CODEX_BASE_ARGS, "resume", threadId, "-"];
242
+
243
+ const proc = spawnCodex(args, cwd, userText);
244
+
245
+ try {
246
+ for await (const raw of readJsonLines(proc, signal)) {
247
+ if (signal?.aborted) break;
248
+
249
+ // 首次 prompt 时从 thread.started 事件学习 threadId
250
+ if (
251
+ isFirstPrompt &&
252
+ raw.type === "thread.started" &&
253
+ raw.thread_id
254
+ ) {
255
+ void this.metaStore
256
+ .setThreadId(sessionId, raw.thread_id)
257
+ .catch(() => {});
258
+ }
259
+
260
+ const normalized = normalizeCodexMessage(raw);
261
+ if (normalized) yield normalized;
262
+ }
263
+ } finally {
264
+ proc.kill();
265
+ }
266
+ }
267
+
268
+ async getSessionInfo(
269
+ sessionId: string,
270
+ ): Promise<SessionInfo | undefined> {
271
+ const meta = await this.metaStore.get(sessionId);
272
+ if (!meta) return undefined;
273
+ return { sessionId, cwd: meta.cwd };
274
+ }
275
+
276
+ async closeSession(_sessionId: string): Promise<void> {
277
+ // no-op:子进程由 prompt 的 finally 自动 kill
278
+ }
279
+ }
280
+
281
+ // ---------------------------------------------------------------------------
282
+ // 工厂函数
283
+ // ---------------------------------------------------------------------------
284
+
285
+ export interface CreateCodexAdapterOptions {
286
+ metaStore?: CodexSessionMetaStore;
287
+ }
288
+
289
+ export function createCodexAdapter(
290
+ options: CreateCodexAdapterOptions = {},
291
+ ): ToolAdapter {
292
+ return new CodexAdapter(
293
+ options.metaStore ?? defaultCodexSessionMetaStore,
294
+ );
294
295
  }
@@ -2,7 +2,7 @@
2
2
  // cursor-adapter.ts — Cursor Agent CLI 适配器
3
3
  // =============================================================================
4
4
  // 通过 agent -p --output-format stream-json 与 Cursor agent 交互。
5
- // 命令行可通过 CHATCCC_CURSOR_COMMAND / CHATCCC_CURSOR_ARGS 环境变量自定义。
5
+ // 命令行可通过 config.json cursor.path / cursor.model 自定义。
6
6
  // =============================================================================
7
7
 
8
8
  import { spawn, type ChildProcess } from "node:child_process";