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.
Files changed (52) hide show
  1. package/agent-prompts/cursor_specific.md +13 -13
  2. package/bin/cccagent.mjs +17 -17
  3. package/config.sample.json +27 -27
  4. package/package.json +2 -1
  5. package/src/__tests__/agent-reload-config-rpc.test.ts +99 -99
  6. package/src/__tests__/builtin-chat-session.test.ts +277 -277
  7. package/src/__tests__/builtin-cli-json.test.ts +39 -39
  8. package/src/__tests__/builtin-config.test.ts +33 -33
  9. package/src/__tests__/builtin-context.test.ts +163 -163
  10. package/src/__tests__/builtin-file-tools.test.ts +224 -224
  11. package/src/__tests__/builtin-session-select.test.ts +116 -116
  12. package/src/__tests__/builtin-sigint.test.ts +56 -56
  13. package/src/__tests__/cards.test.ts +109 -109
  14. package/src/__tests__/ccc-adapter.test.ts +114 -114
  15. package/src/__tests__/chatgpt-subscription-rpc.test.ts +89 -89
  16. package/src/__tests__/chatgpt-subscription.test.ts +135 -135
  17. package/src/__tests__/chrome-devtools-guard.test.ts +165 -165
  18. package/src/__tests__/claude-raw-stream-log.test.ts +87 -87
  19. package/src/__tests__/codex-raw-stream-log.test.ts +163 -120
  20. package/src/__tests__/config-reload.test.ts +10 -10
  21. package/src/__tests__/config-sample.test.ts +18 -18
  22. package/src/__tests__/cursor-adapter.test.ts +114 -1
  23. package/src/__tests__/feishu-avatar.test.ts +40 -40
  24. package/src/__tests__/jsonl-stream.test.ts +79 -0
  25. package/src/__tests__/orchestrator.test.ts +200 -200
  26. package/src/__tests__/raw-stream-log.test.ts +106 -106
  27. package/src/__tests__/session.test.ts +40 -40
  28. package/src/__tests__/sim-platform.test.ts +12 -12
  29. package/src/__tests__/web-ui.test.ts +209 -209
  30. package/src/adapters/ccc-adapter.ts +121 -121
  31. package/src/adapters/claude-adapter.ts +603 -603
  32. package/src/adapters/codex-adapter.ts +380 -392
  33. package/src/adapters/cursor-adapter.ts +56 -30
  34. package/src/adapters/jsonl-stream.ts +157 -0
  35. package/src/adapters/raw-stream-log.ts +124 -124
  36. package/src/agent-reload-config-rpc.ts +34 -34
  37. package/src/builtin/cli.ts +473 -473
  38. package/src/builtin/context.ts +323 -323
  39. package/src/builtin/file-tools.ts +1072 -1072
  40. package/src/builtin/index.ts +404 -404
  41. package/src/builtin/session-select.ts +48 -48
  42. package/src/builtin/sigint.ts +50 -50
  43. package/src/cards.ts +195 -195
  44. package/src/chatgpt-subscription-rpc.ts +27 -27
  45. package/src/chatgpt-subscription.ts +299 -299
  46. package/src/chrome-devtools-guard.ts +318 -318
  47. package/src/config.ts +125 -125
  48. package/src/feishu-api.ts +49 -49
  49. package/src/orchestrator.ts +179 -179
  50. package/src/runtime-reload.ts +34 -34
  51. package/src/session.ts +141 -141
  52. package/src/web-ui.ts +205 -205
@@ -1,209 +1,209 @@
1
- import { describe, it, expect } from "vitest";
2
- import {
3
- PAGE_HTML,
4
- chooseStartPath,
5
- getRestartRequiredReasons,
6
- unflattenConfig,
7
- } from "../web-ui.ts";
8
-
9
- describe("unflattenConfig", () => {
10
- it("maps Claude subagent model into claude.subagentModel", () => {
11
- expect(
12
- unflattenConfig({
13
- CHATCCC_ANTHROPIC_MODEL: "claude-sonnet-4-6",
14
- CHATCCC_ANTHROPIC_SUBAGENT_MODEL: "claude-haiku-4-5-20251001",
15
- }),
16
- ).toEqual({
17
- claude: {
18
- model: "claude-sonnet-4-6",
19
- subagentModel: "claude-haiku-4-5-20251001",
20
- },
21
- });
22
- });
23
-
24
- it("maps Claude apiKey and baseUrl into claude config", () => {
25
- expect(
26
- unflattenConfig({
27
- CHATCCC_ANTHROPIC_API_KEY: "sk-test-key",
28
- CHATCCC_ANTHROPIC_BASE_URL: "https://api.example.com",
29
- }),
30
- ).toEqual({
31
- claude: {
32
- apiKey: "sk-test-key",
33
- baseUrl: "https://api.example.com",
34
- },
35
- });
36
- });
37
-
38
- it("maps Cursor and Codex alternative models into agent config", () => {
39
- expect(
40
- unflattenConfig({
41
- CHATCCC_CURSOR_ALTERNATIVE_MODEL: "gpt-5.5-high",
42
- CHATCCC_CODEX_ALTERNATIVE_MODEL: "gpt-5.3-codex",
43
- }),
44
- ).toEqual({
45
- cursor: {
46
- alternativeModel: "gpt-5.5-high",
47
- },
48
- codex: {
49
- alternativeModel: "gpt-5.3-codex",
50
- },
51
- });
52
- });
53
-
54
- it("maps Chrome CDP guard fields into chromeDevtools config", () => {
55
- expect(
56
- unflattenConfig({
57
- CHATCCC_CHROME_DEVTOOLS_ENABLED: true,
58
- CHATCCC_CHROME_DEVTOOLS_PORT: "15166",
59
- CHATCCC_CHROME_DEVTOOLS_PATH: "C:/Program Files/Google/Chrome/Application/chrome.exe",
60
- }),
61
- ).toEqual({
62
- chromeDevtools: {
63
- enabled: true,
64
- port: 15166,
65
- chromePath: "C:/Program Files/Google/Chrome/Application/chrome.exe",
66
- },
67
- });
68
- });
69
- });
70
-
71
- describe("getRestartRequiredReasons", () => {
72
- const baseConfig = {
73
- feishu: { appId: "cli_old", appSecret: "secret_old" },
74
- platforms: {
75
- feishu: { enabled: true, platformType: "feishu" },
76
- ilink: { enabled: true, reuseTokenOnStart: true },
77
- },
78
- chromeDevtools: { enabled: false, port: 15166, chromePath: "" },
79
- port: 18080,
80
- claude: {
81
- enabled: true,
82
- defaultAgent: true,
83
- model: "",
84
- subagentModel: "",
85
- effort: "",
86
- apiKey: "",
87
- baseUrl: "",
88
- maxTurn: 0,
89
- },
90
- cursor: {
91
- enabled: true,
92
- defaultAgent: false,
93
- path: "",
94
- model: "",
95
- alternativeModel: "",
96
- avatarBatteryMode: "apiPercent",
97
- onDemandMonthlyBudget: 1000,
98
- },
99
- codex: {
100
- enabled: true,
101
- defaultAgent: false,
102
- path: "",
103
- model: "",
104
- alternativeModel: "",
105
- effort: "",
106
- },
107
- };
108
-
109
- it("does not require restart for agent and Chrome runtime settings", () => {
110
- expect(
111
- getRestartRequiredReasons(baseConfig, {
112
- ...baseConfig,
113
- chromeDevtools: { enabled: true, port: 15167, chromePath: "C:/Chrome/chrome.exe" },
114
- claude: { ...baseConfig.claude, model: "claude-sonnet", apiKey: "sk-test", maxTurn: 8 },
115
- cursor: { ...baseConfig.cursor, path: "C:/cursor-agent.cmd", model: "cursor-model" },
116
- codex: { ...baseConfig.codex, path: "C:/codex.cmd", model: "gpt-5.3-codex", effort: "high" },
117
- }),
118
- ).toEqual([]);
119
- });
120
-
121
- it("requires restart for port, Feishu credentials, platform type, and platform lifecycle", () => {
122
- expect(
123
- getRestartRequiredReasons(baseConfig, {
124
- ...baseConfig,
125
- feishu: { appId: "cli_new", appSecret: "secret_new" },
126
- platforms: {
127
- feishu: { enabled: false, platformType: "lark" },
128
- ilink: { enabled: false, reuseTokenOnStart: false },
129
- },
130
- port: 18081,
131
- }),
132
- ).toEqual([
133
- "port",
134
- "feishu.appId",
135
- "feishu.appSecret",
136
- "platforms.feishu.platformType",
137
- "platforms.feishu.enabled",
138
- "platforms.ilink.enabled",
139
- "platforms.ilink.reuseTokenOnStart",
140
- ]);
141
- });
142
- });
143
-
144
- describe("dashboard edit modal", () => {
145
- it("shows the edit modal and overlay when a section edit button is clicked", () => {
146
- expect(PAGE_HTML).toContain("function editSection(section)");
147
- expect(PAGE_HTML).toContain("document.getElementById('edit-modal').classList.remove('hidden');");
148
- expect(PAGE_HTML).toContain("document.getElementById('edit-overlay').classList.remove('hidden');");
149
- });
150
-
151
- it("uses plain alternative model labels for Cursor and Codex", () => {
152
- expect(PAGE_HTML).toContain("field-CHATCCC_CURSOR_ALTERNATIVE_MODEL");
153
- expect(PAGE_HTML).toContain("field-CHATCCC_CODEX_ALTERNATIVE_MODEL");
154
- expect(PAGE_HTML).toContain("备选模型");
155
- });
156
-
157
- it("shows config effect scope hints", () => {
158
- expect(PAGE_HTML).toContain("生效范围:保存后下一条消息或下个新会话生效");
159
- expect(PAGE_HTML).toContain("生效范围:飞书开关、App ID、App Secret 或平台类型变更需要重启 ChatCCC");
160
- });
161
- });
162
-
163
- // ---------------------------------------------------------------------------
164
- // chooseStartPath — /api/start 的路径选择
165
- // 关键护栏:
166
- // - setup 模式(hasInplaceActivateHook=true)下 isServiceRunning 永远为 true
167
- // (setup 进程自己占着 PID 文件),必须无条件走 inplace;否则用户点
168
- // "保存并启动"将永远拿到 "Service is already running"。
169
- // - dashboard 模式 + service 已运行(通常就是当前进程自己)→ "reload":
170
- // 用户点"保存并启动"想让新 config 生效,但服务正在跑——不真重启,仅
171
- // 调用 reloadConfigFromDisk() 刷新进程内 export let 常量。绝不能再
172
- // 返回"already running"挡用户路。
173
- // - dashboard 模式 + service 未运行 → spawn 一个新的(旧 service 退出后场景)。
174
- // ---------------------------------------------------------------------------
175
-
176
- describe("chooseStartPath", () => {
177
- it("setup 模式(注入 inplace hook)→ inplace(不管 PID 文件状态)", () => {
178
- expect(
179
- chooseStartPath({
180
- hasInplaceActivateHook: true,
181
- isServiceRunning: true,
182
- }),
183
- ).toBe("inplace");
184
- expect(
185
- chooseStartPath({
186
- hasInplaceActivateHook: true,
187
- isServiceRunning: false,
188
- }),
189
- ).toBe("inplace");
190
- });
191
-
192
- it("dashboard 模式 + service 已运行 → reload(仅刷新 config,不真重启)", () => {
193
- expect(
194
- chooseStartPath({
195
- hasInplaceActivateHook: false,
196
- isServiceRunning: true,
197
- }),
198
- ).toBe("reload");
199
- });
200
-
201
- it("dashboard 模式 + service 未运行 → spawn", () => {
202
- expect(
203
- chooseStartPath({
204
- hasInplaceActivateHook: false,
205
- isServiceRunning: false,
206
- }),
207
- ).toBe("spawn");
208
- });
209
- });
1
+ import { describe, it, expect } from "vitest";
2
+ import {
3
+ PAGE_HTML,
4
+ chooseStartPath,
5
+ getRestartRequiredReasons,
6
+ unflattenConfig,
7
+ } from "../web-ui.ts";
8
+
9
+ describe("unflattenConfig", () => {
10
+ it("maps Claude subagent model into claude.subagentModel", () => {
11
+ expect(
12
+ unflattenConfig({
13
+ CHATCCC_ANTHROPIC_MODEL: "claude-sonnet-4-6",
14
+ CHATCCC_ANTHROPIC_SUBAGENT_MODEL: "claude-haiku-4-5-20251001",
15
+ }),
16
+ ).toEqual({
17
+ claude: {
18
+ model: "claude-sonnet-4-6",
19
+ subagentModel: "claude-haiku-4-5-20251001",
20
+ },
21
+ });
22
+ });
23
+
24
+ it("maps Claude apiKey and baseUrl into claude config", () => {
25
+ expect(
26
+ unflattenConfig({
27
+ CHATCCC_ANTHROPIC_API_KEY: "sk-test-key",
28
+ CHATCCC_ANTHROPIC_BASE_URL: "https://api.example.com",
29
+ }),
30
+ ).toEqual({
31
+ claude: {
32
+ apiKey: "sk-test-key",
33
+ baseUrl: "https://api.example.com",
34
+ },
35
+ });
36
+ });
37
+
38
+ it("maps Cursor and Codex alternative models into agent config", () => {
39
+ expect(
40
+ unflattenConfig({
41
+ CHATCCC_CURSOR_ALTERNATIVE_MODEL: "gpt-5.5-high",
42
+ CHATCCC_CODEX_ALTERNATIVE_MODEL: "gpt-5.3-codex",
43
+ }),
44
+ ).toEqual({
45
+ cursor: {
46
+ alternativeModel: "gpt-5.5-high",
47
+ },
48
+ codex: {
49
+ alternativeModel: "gpt-5.3-codex",
50
+ },
51
+ });
52
+ });
53
+
54
+ it("maps Chrome CDP guard fields into chromeDevtools config", () => {
55
+ expect(
56
+ unflattenConfig({
57
+ CHATCCC_CHROME_DEVTOOLS_ENABLED: true,
58
+ CHATCCC_CHROME_DEVTOOLS_PORT: "15166",
59
+ CHATCCC_CHROME_DEVTOOLS_PATH: "C:/Program Files/Google/Chrome/Application/chrome.exe",
60
+ }),
61
+ ).toEqual({
62
+ chromeDevtools: {
63
+ enabled: true,
64
+ port: 15166,
65
+ chromePath: "C:/Program Files/Google/Chrome/Application/chrome.exe",
66
+ },
67
+ });
68
+ });
69
+ });
70
+
71
+ describe("getRestartRequiredReasons", () => {
72
+ const baseConfig = {
73
+ feishu: { appId: "cli_old", appSecret: "secret_old" },
74
+ platforms: {
75
+ feishu: { enabled: true, platformType: "feishu" },
76
+ ilink: { enabled: true, reuseTokenOnStart: true },
77
+ },
78
+ chromeDevtools: { enabled: false, port: 15166, chromePath: "" },
79
+ port: 18080,
80
+ claude: {
81
+ enabled: true,
82
+ defaultAgent: true,
83
+ model: "",
84
+ subagentModel: "",
85
+ effort: "",
86
+ apiKey: "",
87
+ baseUrl: "",
88
+ maxTurn: 0,
89
+ },
90
+ cursor: {
91
+ enabled: true,
92
+ defaultAgent: false,
93
+ path: "",
94
+ model: "",
95
+ alternativeModel: "",
96
+ avatarBatteryMode: "apiPercent",
97
+ onDemandMonthlyBudget: 1000,
98
+ },
99
+ codex: {
100
+ enabled: true,
101
+ defaultAgent: false,
102
+ path: "",
103
+ model: "",
104
+ alternativeModel: "",
105
+ effort: "",
106
+ },
107
+ };
108
+
109
+ it("does not require restart for agent and Chrome runtime settings", () => {
110
+ expect(
111
+ getRestartRequiredReasons(baseConfig, {
112
+ ...baseConfig,
113
+ chromeDevtools: { enabled: true, port: 15167, chromePath: "C:/Chrome/chrome.exe" },
114
+ claude: { ...baseConfig.claude, model: "claude-sonnet", apiKey: "sk-test", maxTurn: 8 },
115
+ cursor: { ...baseConfig.cursor, path: "C:/cursor-agent.cmd", model: "cursor-model" },
116
+ codex: { ...baseConfig.codex, path: "C:/codex.cmd", model: "gpt-5.3-codex", effort: "high" },
117
+ }),
118
+ ).toEqual([]);
119
+ });
120
+
121
+ it("requires restart for port, Feishu credentials, platform type, and platform lifecycle", () => {
122
+ expect(
123
+ getRestartRequiredReasons(baseConfig, {
124
+ ...baseConfig,
125
+ feishu: { appId: "cli_new", appSecret: "secret_new" },
126
+ platforms: {
127
+ feishu: { enabled: false, platformType: "lark" },
128
+ ilink: { enabled: false, reuseTokenOnStart: false },
129
+ },
130
+ port: 18081,
131
+ }),
132
+ ).toEqual([
133
+ "port",
134
+ "feishu.appId",
135
+ "feishu.appSecret",
136
+ "platforms.feishu.platformType",
137
+ "platforms.feishu.enabled",
138
+ "platforms.ilink.enabled",
139
+ "platforms.ilink.reuseTokenOnStart",
140
+ ]);
141
+ });
142
+ });
143
+
144
+ describe("dashboard edit modal", () => {
145
+ it("shows the edit modal and overlay when a section edit button is clicked", () => {
146
+ expect(PAGE_HTML).toContain("function editSection(section)");
147
+ expect(PAGE_HTML).toContain("document.getElementById('edit-modal').classList.remove('hidden');");
148
+ expect(PAGE_HTML).toContain("document.getElementById('edit-overlay').classList.remove('hidden');");
149
+ });
150
+
151
+ it("uses plain alternative model labels for Cursor and Codex", () => {
152
+ expect(PAGE_HTML).toContain("field-CHATCCC_CURSOR_ALTERNATIVE_MODEL");
153
+ expect(PAGE_HTML).toContain("field-CHATCCC_CODEX_ALTERNATIVE_MODEL");
154
+ expect(PAGE_HTML).toContain("备选模型");
155
+ });
156
+
157
+ it("shows config effect scope hints", () => {
158
+ expect(PAGE_HTML).toContain("生效范围:保存后下一条消息或下个新会话生效");
159
+ expect(PAGE_HTML).toContain("生效范围:飞书开关、App ID、App Secret 或平台类型变更需要重启 ChatCCC");
160
+ });
161
+ });
162
+
163
+ // ---------------------------------------------------------------------------
164
+ // chooseStartPath — /api/start 的路径选择
165
+ // 关键护栏:
166
+ // - setup 模式(hasInplaceActivateHook=true)下 isServiceRunning 永远为 true
167
+ // (setup 进程自己占着 PID 文件),必须无条件走 inplace;否则用户点
168
+ // "保存并启动"将永远拿到 "Service is already running"。
169
+ // - dashboard 模式 + service 已运行(通常就是当前进程自己)→ "reload":
170
+ // 用户点"保存并启动"想让新 config 生效,但服务正在跑——不真重启,仅
171
+ // 调用 reloadConfigFromDisk() 刷新进程内 export let 常量。绝不能再
172
+ // 返回"already running"挡用户路。
173
+ // - dashboard 模式 + service 未运行 → spawn 一个新的(旧 service 退出后场景)。
174
+ // ---------------------------------------------------------------------------
175
+
176
+ describe("chooseStartPath", () => {
177
+ it("setup 模式(注入 inplace hook)→ inplace(不管 PID 文件状态)", () => {
178
+ expect(
179
+ chooseStartPath({
180
+ hasInplaceActivateHook: true,
181
+ isServiceRunning: true,
182
+ }),
183
+ ).toBe("inplace");
184
+ expect(
185
+ chooseStartPath({
186
+ hasInplaceActivateHook: true,
187
+ isServiceRunning: false,
188
+ }),
189
+ ).toBe("inplace");
190
+ });
191
+
192
+ it("dashboard 模式 + service 已运行 → reload(仅刷新 config,不真重启)", () => {
193
+ expect(
194
+ chooseStartPath({
195
+ hasInplaceActivateHook: false,
196
+ isServiceRunning: true,
197
+ }),
198
+ ).toBe("reload");
199
+ });
200
+
201
+ it("dashboard 模式 + service 未运行 → spawn", () => {
202
+ expect(
203
+ chooseStartPath({
204
+ hasInplaceActivateHook: false,
205
+ isServiceRunning: false,
206
+ }),
207
+ ).toBe("spawn");
208
+ });
209
+ });
@@ -1,121 +1,121 @@
1
- import { ChatSession, type ChatSessionConfig, type ChatSessionOptions } from "../builtin/index.ts";
2
- import {
3
- getBuiltinContextSession,
4
- newBuiltinSessionId,
5
- normalizeBuiltinSessionId,
6
- } from "../builtin/context.ts";
7
- import { config, CCC_SESSION_PREFIX } from "../config.ts";
8
- import type {
9
- CreateSessionResult,
10
- SessionInfo,
11
- ToolAdapter,
12
- ToolPromptOptions,
13
- UnifiedStreamMessage,
14
- } from "./adapter-interface.ts";
15
-
16
- export interface CccAdapterOptions extends ChatSessionConfig {
17
- contextDir?: string;
18
- compactAtTokens?: number;
19
- keepRecentMessages?: number;
20
- maxSteps?: number;
21
- }
22
-
23
- function toChatSessionOptions(
24
- sessionId: string,
25
- cwd: string,
26
- options: CccAdapterOptions,
27
- ): ChatSessionOptions {
28
- return {
29
- cwd,
30
- persist: true,
31
- sessionId,
32
- contextDir: options.contextDir,
33
- compactAtTokens: options.compactAtTokens,
34
- keepRecentMessages: options.keepRecentMessages,
35
- maxSteps: options.maxSteps,
36
- };
37
- }
38
-
39
- export function createCccAdapter(options: CccAdapterOptions = {}): ToolAdapter {
40
- const chatConfig: ChatSessionConfig = {
41
- ...(options.apiKey !== undefined ? { apiKey: options.apiKey } : {}),
42
- ...(options.baseURL !== undefined ? { baseURL: options.baseURL } : {}),
43
- ...(options.model !== undefined ? { model: options.model } : {}),
44
- };
45
-
46
- return {
47
- displayName: "CCC Agent",
48
- sessionDescPrefix: CCC_SESSION_PREFIX,
49
-
50
- async createSession(cwd: string): Promise<CreateSessionResult> {
51
- const sessionId = newBuiltinSessionId();
52
- const session = new ChatSession(
53
- chatConfig,
54
- toChatSessionOptions(sessionId, cwd, options),
55
- );
56
- session.reset();
57
- return { sessionId };
58
- },
59
-
60
- async *prompt(
61
- sessionId: string,
62
- userText: string,
63
- cwd: string,
64
- signal?: AbortSignal,
65
- _promptOptions?: ToolPromptOptions,
66
- ): AsyncIterable<UnifiedStreamMessage> {
67
- const normalizedSessionId = normalizeBuiltinSessionId(sessionId);
68
- const session = new ChatSession(
69
- chatConfig,
70
- toChatSessionOptions(normalizedSessionId, cwd, options),
71
- );
72
-
73
- for await (const event of session.chat(userText, signal)) {
74
- if (event.type === "text") {
75
- yield {
76
- type: "assistant",
77
- blocks: [{ type: "text", text: event.text }],
78
- };
79
- } else if (event.type === "tool_use") {
80
- yield {
81
- type: "assistant",
82
- blocks: [{
83
- type: "tool_use",
84
- id: event.id,
85
- name: event.name,
86
- input: event.input,
87
- }],
88
- };
89
- } else if (event.type === "tool_result") {
90
- yield {
91
- type: "assistant",
92
- blocks: [{
93
- type: "tool_result",
94
- tool_use_id: event.tool_use_id,
95
- content: event.content,
96
- is_error: event.is_error,
97
- }],
98
- };
99
- } else if (event.type === "error") {
100
- throw new Error(event.message);
101
- }
102
- }
103
- },
104
-
105
- async getSessionInfo(sessionId: string): Promise<SessionInfo | undefined> {
106
- const normalizedSessionId = normalizeBuiltinSessionId(sessionId);
107
- const info = getBuiltinContextSession(normalizedSessionId, options.contextDir);
108
- if (!info) return undefined;
109
- return {
110
- sessionId: info.sessionId,
111
- cwd: info.cwd,
112
- lastModified: info.updatedAt,
113
- model: options.model ?? config.ccc.model,
114
- };
115
- },
116
-
117
- async closeSession(_sessionId: string): Promise<void> {
118
- // ChatSession uses one request-scoped stream per prompt. AbortSignal handles cancellation.
119
- },
120
- };
121
- }
1
+ import { ChatSession, type ChatSessionConfig, type ChatSessionOptions } from "../builtin/index.ts";
2
+ import {
3
+ getBuiltinContextSession,
4
+ newBuiltinSessionId,
5
+ normalizeBuiltinSessionId,
6
+ } from "../builtin/context.ts";
7
+ import { config, CCC_SESSION_PREFIX } from "../config.ts";
8
+ import type {
9
+ CreateSessionResult,
10
+ SessionInfo,
11
+ ToolAdapter,
12
+ ToolPromptOptions,
13
+ UnifiedStreamMessage,
14
+ } from "./adapter-interface.ts";
15
+
16
+ export interface CccAdapterOptions extends ChatSessionConfig {
17
+ contextDir?: string;
18
+ compactAtTokens?: number;
19
+ keepRecentMessages?: number;
20
+ maxSteps?: number;
21
+ }
22
+
23
+ function toChatSessionOptions(
24
+ sessionId: string,
25
+ cwd: string,
26
+ options: CccAdapterOptions,
27
+ ): ChatSessionOptions {
28
+ return {
29
+ cwd,
30
+ persist: true,
31
+ sessionId,
32
+ contextDir: options.contextDir,
33
+ compactAtTokens: options.compactAtTokens,
34
+ keepRecentMessages: options.keepRecentMessages,
35
+ maxSteps: options.maxSteps,
36
+ };
37
+ }
38
+
39
+ export function createCccAdapter(options: CccAdapterOptions = {}): ToolAdapter {
40
+ const chatConfig: ChatSessionConfig = {
41
+ ...(options.apiKey !== undefined ? { apiKey: options.apiKey } : {}),
42
+ ...(options.baseURL !== undefined ? { baseURL: options.baseURL } : {}),
43
+ ...(options.model !== undefined ? { model: options.model } : {}),
44
+ };
45
+
46
+ return {
47
+ displayName: "CCC Agent",
48
+ sessionDescPrefix: CCC_SESSION_PREFIX,
49
+
50
+ async createSession(cwd: string): Promise<CreateSessionResult> {
51
+ const sessionId = newBuiltinSessionId();
52
+ const session = new ChatSession(
53
+ chatConfig,
54
+ toChatSessionOptions(sessionId, cwd, options),
55
+ );
56
+ session.reset();
57
+ return { sessionId };
58
+ },
59
+
60
+ async *prompt(
61
+ sessionId: string,
62
+ userText: string,
63
+ cwd: string,
64
+ signal?: AbortSignal,
65
+ _promptOptions?: ToolPromptOptions,
66
+ ): AsyncIterable<UnifiedStreamMessage> {
67
+ const normalizedSessionId = normalizeBuiltinSessionId(sessionId);
68
+ const session = new ChatSession(
69
+ chatConfig,
70
+ toChatSessionOptions(normalizedSessionId, cwd, options),
71
+ );
72
+
73
+ for await (const event of session.chat(userText, signal)) {
74
+ if (event.type === "text") {
75
+ yield {
76
+ type: "assistant",
77
+ blocks: [{ type: "text", text: event.text }],
78
+ };
79
+ } else if (event.type === "tool_use") {
80
+ yield {
81
+ type: "assistant",
82
+ blocks: [{
83
+ type: "tool_use",
84
+ id: event.id,
85
+ name: event.name,
86
+ input: event.input,
87
+ }],
88
+ };
89
+ } else if (event.type === "tool_result") {
90
+ yield {
91
+ type: "assistant",
92
+ blocks: [{
93
+ type: "tool_result",
94
+ tool_use_id: event.tool_use_id,
95
+ content: event.content,
96
+ is_error: event.is_error,
97
+ }],
98
+ };
99
+ } else if (event.type === "error") {
100
+ throw new Error(event.message);
101
+ }
102
+ }
103
+ },
104
+
105
+ async getSessionInfo(sessionId: string): Promise<SessionInfo | undefined> {
106
+ const normalizedSessionId = normalizeBuiltinSessionId(sessionId);
107
+ const info = getBuiltinContextSession(normalizedSessionId, options.contextDir);
108
+ if (!info) return undefined;
109
+ return {
110
+ sessionId: info.sessionId,
111
+ cwd: info.cwd,
112
+ lastModified: info.updatedAt,
113
+ model: options.model ?? config.ccc.model,
114
+ };
115
+ },
116
+
117
+ async closeSession(_sessionId: string): Promise<void> {
118
+ // ChatSession uses one request-scoped stream per prompt. AbortSignal handles cancellation.
119
+ },
120
+ };
121
+ }