chatccc 0.2.242 → 0.2.243

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 (56) hide show
  1. package/README.md +5 -5
  2. package/bin/cccagent.mjs +17 -17
  3. package/deepccc-agent/bin/deepccc.mjs +26 -26
  4. package/deepccc-agent/package.json +62 -62
  5. package/deepccc-agent/src/__tests__/chat-session.test.ts +578 -522
  6. package/deepccc-agent/src/__tests__/cli-json.test.ts +49 -49
  7. package/deepccc-agent/src/__tests__/config.test.ts +26 -26
  8. package/deepccc-agent/src/__tests__/context.test.ts +319 -319
  9. package/deepccc-agent/src/__tests__/file-tools.test.ts +240 -240
  10. package/deepccc-agent/src/__tests__/permissions.test.ts +195 -195
  11. package/deepccc-agent/src/__tests__/progress-reducer.test.ts +121 -121
  12. package/deepccc-agent/src/__tests__/session-search.test.ts +262 -262
  13. package/deepccc-agent/src/__tests__/session-select.test.ts +116 -116
  14. package/deepccc-agent/src/__tests__/sigint.test.ts +56 -56
  15. package/deepccc-agent/src/__tests__/skills.test.ts +284 -284
  16. package/deepccc-agent/src/__tests__/terminal-renderer.test.ts +247 -247
  17. package/deepccc-agent/src/__tests__/web-tools.test.ts +220 -220
  18. package/deepccc-agent/src/config.ts +84 -84
  19. package/deepccc-agent/src/context.ts +465 -465
  20. package/deepccc-agent/src/file-log.ts +38 -38
  21. package/deepccc-agent/src/index.ts +22 -0
  22. package/deepccc-agent/src/proc-tree-kill.ts +61 -61
  23. package/deepccc-agent/src/progress/cards-helpers.ts +76 -76
  24. package/deepccc-agent/src/progress/reducer.ts +113 -113
  25. package/deepccc-agent/src/progress/terminal-renderer.ts +294 -294
  26. package/deepccc-agent/src/progress/view.ts +77 -77
  27. package/deepccc-agent/src/raw-stream-log.ts +124 -124
  28. package/deepccc-agent/src/session-search.ts +370 -370
  29. package/deepccc-agent/src/session-select.ts +48 -48
  30. package/deepccc-agent/src/sigint.ts +50 -50
  31. package/deepccc-agent/src/skills.ts +205 -205
  32. package/deepccc-agent/src/web-tools.ts +313 -313
  33. package/deepccc-agent/tsconfig.build.json +13 -13
  34. package/deepccc-agent/tsconfig.json +13 -13
  35. package/deepccc-agent/vitest.config.ts +7 -7
  36. package/package.json +1 -1
  37. package/src/__tests__/builtin-chat-session.test.ts +522 -522
  38. package/src/__tests__/builtin-config.test.ts +26 -26
  39. package/src/__tests__/builtin-context.test.ts +319 -319
  40. package/src/__tests__/builtin-file-tools.test.ts +240 -240
  41. package/src/__tests__/builtin-permissions.test.ts +211 -211
  42. package/src/__tests__/builtin-session-search.test.ts +262 -262
  43. package/src/__tests__/builtin-session-select.test.ts +116 -116
  44. package/src/__tests__/builtin-sigint.test.ts +56 -56
  45. package/src/__tests__/builtin-skills.test.ts +284 -284
  46. package/src/__tests__/builtin-web-tools.test.ts +220 -220
  47. package/src/__tests__/config.test.ts +17 -17
  48. package/src/__tests__/progress-reducer.test.ts +121 -121
  49. package/src/__tests__/session-ccc-config.test.ts +45 -45
  50. package/src/__tests__/session.test.ts +298 -298
  51. package/src/adapters/ccc-adapter.ts +145 -145
  52. package/src/config-utils.ts +13 -13
  53. package/src/config.ts +13 -13
  54. package/src/progress/reducer.ts +113 -113
  55. package/src/session-chat-binding.ts +83 -83
  56. package/src/session.ts +311 -311
@@ -1,145 +1,145 @@
1
- import { ChatSession, type ChatSessionConfig, type ChatSessionOptions } from "../../deepccc-agent/src/index.ts";
2
- import {
3
- getBuiltinContextSession,
4
- newBuiltinSessionId,
5
- normalizeBuiltinSessionId,
6
- } from "../../deepccc-agent/src/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
- compactionTimeoutMs?: number;
21
- maxSteps?: number;
22
- }
23
-
24
- function toChatSessionOptions(
25
- sessionId: string,
26
- cwd: string,
27
- options: CccAdapterOptions,
28
- ): ChatSessionOptions {
29
- return {
30
- cwd,
31
- persist: true,
32
- sessionId,
33
- contextDir: options.contextDir,
34
- compactAtTokens: options.compactAtTokens,
35
- keepRecentMessages: options.keepRecentMessages,
36
- compactionTimeoutMs: options.compactionTimeoutMs,
37
- maxSteps: options.maxSteps,
38
- // chatccc 无终端可交互,且对齐 claude/codex 适配器的 bypass 模式:
39
- // 高危命令不询问,全部放行(与独立 deepccc CLI 的 ask 模式不同)
40
- permissionMode: "bypass",
41
- };
42
- }
43
-
44
- export function createCccAdapter(options: CccAdapterOptions = {}): ToolAdapter {
45
- if (!options.apiKey?.trim()) {
46
- throw new Error("ChatCCC 未配置 CCC Agent API Key。请先填写 ccc.DEEPSEEK_API_KEY 后再启用 CCC Agent。");
47
- }
48
-
49
- const chatConfig: ChatSessionConfig = {
50
- apiKey: options.apiKey,
51
- ...(options.baseURL !== undefined ? { baseURL: options.baseURL } : {}),
52
- ...(options.model !== undefined ? { model: options.model } : {}),
53
- ...(options.effort !== undefined ? { effort: options.effort } : {}),
54
- };
55
-
56
- return {
57
- displayName: "CCC Agent",
58
- sessionDescPrefix: CCC_SESSION_PREFIX,
59
-
60
- async createSession(cwd: string): Promise<CreateSessionResult> {
61
- const sessionId = newBuiltinSessionId();
62
- const session = new ChatSession(
63
- chatConfig,
64
- toChatSessionOptions(sessionId, cwd, options),
65
- );
66
- session.reset();
67
- return { sessionId };
68
- },
69
-
70
- async *prompt(
71
- sessionId: string,
72
- userText: string,
73
- cwd: string,
74
- signal?: AbortSignal,
75
- _promptOptions?: ToolPromptOptions,
76
- ): AsyncIterable<UnifiedStreamMessage> {
77
- const normalizedSessionId = normalizeBuiltinSessionId(sessionId);
78
- const session = new ChatSession(
79
- chatConfig,
80
- toChatSessionOptions(normalizedSessionId, cwd, options),
81
- );
82
-
83
- for await (const event of session.chat(userText, signal)) {
84
- if (event.type === "status") {
85
- yield {
86
- type: "assistant",
87
- blocks: [{
88
- type: "agent_status",
89
- status: event.phase === "compacting" ? "compacting" : "responding",
90
- }],
91
- };
92
- } else if (event.type === "text") {
93
- yield {
94
- type: "assistant",
95
- blocks: [{ type: "text", text: event.text }],
96
- };
97
- } else if (event.type === "tool_use") {
98
- yield {
99
- type: "assistant",
100
- blocks: [{
101
- type: "tool_use",
102
- id: event.id,
103
- name: event.name,
104
- input: event.input,
105
- }],
106
- };
107
- } else if (event.type === "tool_result") {
108
- yield {
109
- type: "assistant",
110
- blocks: [{
111
- type: "tool_result",
112
- tool_use_id: event.tool_use_id,
113
- content: event.content,
114
- is_error: event.is_error,
115
- }],
116
- };
117
- } else if (event.type === "done" && !signal?.aborted) {
118
- yield {
119
- type: "assistant",
120
- blocks: [],
121
- isFinalResponse: true,
122
- };
123
- } else if (event.type === "error") {
124
- throw new Error(event.message);
125
- }
126
- }
127
- },
128
-
129
- async getSessionInfo(sessionId: string): Promise<SessionInfo | undefined> {
130
- const normalizedSessionId = normalizeBuiltinSessionId(sessionId);
131
- const info = getBuiltinContextSession(normalizedSessionId, options.contextDir);
132
- if (!info) return undefined;
133
- return {
134
- sessionId: info.sessionId,
135
- cwd: info.cwd,
136
- lastModified: info.updatedAt,
137
- model: options.model ?? config.ccc.model,
138
- };
139
- },
140
-
141
- async closeSession(_sessionId: string): Promise<void> {
142
- // ChatSession uses one request-scoped stream per prompt. AbortSignal handles cancellation.
143
- },
144
- };
145
- }
1
+ import { ChatSession, type ChatSessionConfig, type ChatSessionOptions } from "../../deepccc-agent/src/index.ts";
2
+ import {
3
+ getBuiltinContextSession,
4
+ newBuiltinSessionId,
5
+ normalizeBuiltinSessionId,
6
+ } from "../../deepccc-agent/src/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
+ compactionTimeoutMs?: number;
21
+ maxSteps?: number;
22
+ }
23
+
24
+ function toChatSessionOptions(
25
+ sessionId: string,
26
+ cwd: string,
27
+ options: CccAdapterOptions,
28
+ ): ChatSessionOptions {
29
+ return {
30
+ cwd,
31
+ persist: true,
32
+ sessionId,
33
+ contextDir: options.contextDir,
34
+ compactAtTokens: options.compactAtTokens,
35
+ keepRecentMessages: options.keepRecentMessages,
36
+ compactionTimeoutMs: options.compactionTimeoutMs,
37
+ maxSteps: options.maxSteps,
38
+ // chatccc 无终端可交互,且对齐 claude/codex 适配器的 bypass 模式:
39
+ // 高危命令不询问,全部放行(与独立 deepccc CLI 的 ask 模式不同)
40
+ permissionMode: "bypass",
41
+ };
42
+ }
43
+
44
+ export function createCccAdapter(options: CccAdapterOptions = {}): ToolAdapter {
45
+ if (!options.apiKey?.trim()) {
46
+ throw new Error("ChatCCC 未配置 CCC Agent API Key。请先填写 ccc.DEEPSEEK_API_KEY 后再启用 CCC Agent。");
47
+ }
48
+
49
+ const chatConfig: ChatSessionConfig = {
50
+ apiKey: options.apiKey,
51
+ ...(options.baseURL !== undefined ? { baseURL: options.baseURL } : {}),
52
+ ...(options.model !== undefined ? { model: options.model } : {}),
53
+ ...(options.effort !== undefined ? { effort: options.effort } : {}),
54
+ };
55
+
56
+ return {
57
+ displayName: "CCC Agent",
58
+ sessionDescPrefix: CCC_SESSION_PREFIX,
59
+
60
+ async createSession(cwd: string): Promise<CreateSessionResult> {
61
+ const sessionId = newBuiltinSessionId();
62
+ const session = new ChatSession(
63
+ chatConfig,
64
+ toChatSessionOptions(sessionId, cwd, options),
65
+ );
66
+ session.reset();
67
+ return { sessionId };
68
+ },
69
+
70
+ async *prompt(
71
+ sessionId: string,
72
+ userText: string,
73
+ cwd: string,
74
+ signal?: AbortSignal,
75
+ _promptOptions?: ToolPromptOptions,
76
+ ): AsyncIterable<UnifiedStreamMessage> {
77
+ const normalizedSessionId = normalizeBuiltinSessionId(sessionId);
78
+ const session = new ChatSession(
79
+ chatConfig,
80
+ toChatSessionOptions(normalizedSessionId, cwd, options),
81
+ );
82
+
83
+ for await (const event of session.chat(userText, signal)) {
84
+ if (event.type === "status") {
85
+ yield {
86
+ type: "assistant",
87
+ blocks: [{
88
+ type: "agent_status",
89
+ status: event.phase === "compacting" ? "compacting" : "responding",
90
+ }],
91
+ };
92
+ } else if (event.type === "text") {
93
+ yield {
94
+ type: "assistant",
95
+ blocks: [{ type: "text", text: event.text }],
96
+ };
97
+ } else if (event.type === "tool_use") {
98
+ yield {
99
+ type: "assistant",
100
+ blocks: [{
101
+ type: "tool_use",
102
+ id: event.id,
103
+ name: event.name,
104
+ input: event.input,
105
+ }],
106
+ };
107
+ } else if (event.type === "tool_result") {
108
+ yield {
109
+ type: "assistant",
110
+ blocks: [{
111
+ type: "tool_result",
112
+ tool_use_id: event.tool_use_id,
113
+ content: event.content,
114
+ is_error: event.is_error,
115
+ }],
116
+ };
117
+ } else if (event.type === "done" && !signal?.aborted) {
118
+ yield {
119
+ type: "assistant",
120
+ blocks: [],
121
+ isFinalResponse: true,
122
+ };
123
+ } else if (event.type === "error") {
124
+ throw new Error(event.message);
125
+ }
126
+ }
127
+ },
128
+
129
+ async getSessionInfo(sessionId: string): Promise<SessionInfo | undefined> {
130
+ const normalizedSessionId = normalizeBuiltinSessionId(sessionId);
131
+ const info = getBuiltinContextSession(normalizedSessionId, options.contextDir);
132
+ if (!info) return undefined;
133
+ return {
134
+ sessionId: info.sessionId,
135
+ cwd: info.cwd,
136
+ lastModified: info.updatedAt,
137
+ model: options.model ?? config.ccc.model,
138
+ };
139
+ },
140
+
141
+ async closeSession(_sessionId: string): Promise<void> {
142
+ // ChatSession uses one request-scoped stream per prompt. AbortSignal handles cancellation.
143
+ },
144
+ };
145
+ }
@@ -20,7 +20,7 @@ import { join } from "node:path";
20
20
  * - `value` 去除空白后等于 `"default"`(不区分大小写)→ 视作 `""` 并 warn。
21
21
  * - 其余情况原样返回(不裁剪两端空白,留给具体调用方决定)。
22
22
  */
23
- export function normalizeOptionalConfigField(
23
+ export function normalizeOptionalConfigField(
24
24
  value: unknown,
25
25
  options: { label: string; fallback?: string },
26
26
  ): string {
@@ -33,18 +33,18 @@ export function normalizeOptionalConfigField(
33
33
  );
34
34
  return "";
35
35
  }
36
- return value;
37
- }
38
-
39
- /**
40
- * CCC Agent requires credentials owned by ChatCCC. An explicit enabled=true
41
- * must not make the agent selectable when that credential is absent.
42
- */
43
- export function resolveCccEnabled(rawEnabled: unknown, apiKey: unknown): boolean {
44
- const hasApiKey = typeof apiKey === "string" && apiKey.trim().length > 0;
45
- if (!hasApiKey) return false;
46
- return typeof rawEnabled === "boolean" ? rawEnabled : true;
47
- }
36
+ return value;
37
+ }
38
+
39
+ /**
40
+ * CCC Agent requires credentials owned by ChatCCC. An explicit enabled=true
41
+ * must not make the agent selectable when that credential is absent.
42
+ */
43
+ export function resolveCccEnabled(rawEnabled: unknown, apiKey: unknown): boolean {
44
+ const hasApiKey = typeof apiKey === "string" && apiKey.trim().length > 0;
45
+ if (!hasApiKey) return false;
46
+ return typeof rawEnabled === "boolean" ? rawEnabled : true;
47
+ }
48
48
 
49
49
  // ---------------------------------------------------------------------------
50
50
  // /git 超时配置相关
package/src/config.ts CHANGED
@@ -11,10 +11,10 @@ import {
11
11
  anthropicConfigDisplay,
12
12
  autoDetectCodexPath,
13
13
  autoDetectCursorPath,
14
- normalizeOptionalConfigField,
15
- readToolCliPath,
16
- resolveCccEnabled,
17
- } from "./config-utils.ts";
14
+ normalizeOptionalConfigField,
15
+ readToolCliPath,
16
+ resolveCccEnabled,
17
+ } from "./config-utils.ts";
18
18
 
19
19
  // 重新导出 config-utils 中的纯函数/常量,保持对外 API 不变
20
20
  // (历史上这些符号都从 ./config.ts 导入;新代码可直接从 ./config-utils.ts 导入以避免触发本文件的副作用)
@@ -23,11 +23,11 @@ export {
23
23
  MIN_GIT_TIMEOUT_SECONDS,
24
24
  MAX_GIT_TIMEOUT_SECONDS,
25
25
  parseGitTimeoutSeconds,
26
- normalizeOptionalConfigField,
27
- isAnthropicConfigEmpty,
28
- anthropicConfigDisplay,
29
- resolveCccEnabled,
30
- } from "./config-utils.ts";
26
+ normalizeOptionalConfigField,
27
+ isAnthropicConfigEmpty,
28
+ anthropicConfigDisplay,
29
+ resolveCccEnabled,
30
+ } from "./config-utils.ts";
31
31
  export type { ParsedGitTimeout } from "./config-utils.ts";
32
32
 
33
33
  // ---------------------------------------------------------------------------
@@ -597,10 +597,10 @@ function loadConfig(): AppConfig {
597
597
  );
598
598
  // 旧版 ccc 配置没有 enabled。只用 API Key 推断启用,避免 sample 中自带的
599
599
  // 默认 Base URL / model 让升级用户在未配置凭证时意外启用 CCC Agent。
600
- const claudeEnabled = resolveEnabled(claude.enabled, claudeNonEmpty);
601
- const cursorEnabled = resolveEnabled(cursorRaw.enabled, cursorNonEmpty);
602
- const codexEnabled = resolveEnabled(codexRaw.enabled, codexNonEmpty);
603
- const cccEnabled = resolveCccEnabled(cccRaw.enabled, cccRaw.DEEPSEEK_API_KEY);
600
+ const claudeEnabled = resolveEnabled(claude.enabled, claudeNonEmpty);
601
+ const cursorEnabled = resolveEnabled(cursorRaw.enabled, cursorNonEmpty);
602
+ const codexEnabled = resolveEnabled(codexRaw.enabled, codexNonEmpty);
603
+ const cccEnabled = resolveCccEnabled(cccRaw.enabled, cccRaw.DEEPSEEK_API_KEY);
604
604
  const chromeDevtoolsPort = Number(chromeDevtoolsRaw.port);
605
605
  const explicitDefaultTool: AgentTool | null =
606
606
  typeof claude.defaultAgent === "boolean" && claude.defaultAgent && claudeEnabled ? "claude" :
@@ -1,113 +1,113 @@
1
- /**
2
- * progress/reducer.ts — ChatEvent 事件流 → ProgressView 的增量合并
3
- *
4
- * 这是飞书与终端共享的唯一一份"事件 → 过程视图"公共逻辑:
5
- * 终端 REPL 直接消费 ChatSession.chat() 的事件流,逐条 reduce;
6
- * 飞书侧 display loop 若未来接入事件流,同样使用本 reducer,保证两端
7
- * 看到的过程状态(正文累积、工具调用、终态判定)完全一致。
8
- */
9
-
10
- import type { ChatEvent } from "../../deepccc-agent/src/index.ts";
11
- import {
12
- withProgressView,
13
- type ProgressToolCall,
14
- type ProgressView,
15
- } from "./view.ts";
16
-
17
- /** 工具调用 input 单行摘要(终端折叠行展示用) */
18
- export function summarizeToolInput(input: unknown, maxChars = 120): string {
19
- let raw: string;
20
- if (typeof input === "string") {
21
- raw = input;
22
- } else {
23
- try {
24
- raw = JSON.stringify(input);
25
- } catch {
26
- raw = String(input);
27
- }
28
- }
29
- const oneLine = raw.replace(/\s+/g, " ").trim();
30
- return oneLine.length > maxChars ? oneLine.slice(0, maxChars) + "…" : oneLine;
31
- }
32
-
33
- /** 工具结果单行摘要(成功/失败各取首行) */
34
- export function summarizeToolResult(content: unknown, maxChars = 120): string {
35
- let raw: string;
36
- if (typeof content === "string") {
37
- raw = content;
38
- } else if (content instanceof Error) {
39
- raw = content.message;
40
- } else {
41
- try {
42
- raw = JSON.stringify(content);
43
- } catch {
44
- raw = String(content);
45
- }
46
- }
47
- const firstLine = raw.split("\n")[0] ?? "";
48
- return firstLine.length > maxChars ? firstLine.slice(0, maxChars) + "…" : firstLine;
49
- }
50
-
51
- /**
52
- * 把一条 ChatEvent 合并进 ProgressView,返回新视图(不可变更新)。
53
- * 未识别的/不影响展示的事件(如 compact)返回原视图。
54
- */
55
- export function reduceProgress(prev: ProgressView, event: ChatEvent): ProgressView {
56
- switch (event.type) {
57
- case "status":
58
- return withProgressView(prev, {
59
- headerTitle: event.phase === "compacting" ? "压缩上下文中..." : "生成回复中...",
60
- });
61
-
62
- case "text":
63
- // accumulated 是全文累积,直接全量替换,天然幂等
64
- return withProgressView(prev, { text: event.accumulated });
65
-
66
- case "tool_use": {
67
- const tool: ProgressToolCall = {
68
- id: event.id ?? `tool-${prev.tools.length + 1}`,
69
- name: event.name,
70
- status: "running",
71
- detail: summarizeToolInput(event.input),
72
- };
73
- return withProgressView(prev, { tools: [...prev.tools, tool] });
74
- }
75
-
76
- case "tool_result": {
77
- const nextStatus = event.is_error ? ("error" as const) : ("ok" as const);
78
- const summary = summarizeToolResult(event.content);
79
- let matched = false;
80
- const tools = prev.tools.map((t) => {
81
- if (matched || t.id !== event.tool_use_id) return t;
82
- matched = true;
83
- return { ...t, status: nextStatus, summary };
84
- });
85
- if (!matched) {
86
- // id 缺失或失配:兜底更新最后一个 running 工具,避免状态悬挂
87
- const lastRunning = [...prev.tools].reverse().findIndex((t) => t.status === "running");
88
- if (lastRunning >= 0) {
89
- const idx = prev.tools.length - 1 - lastRunning;
90
- const updated = prev.tools.map((t, i) =>
91
- i === idx ? { ...t, status: nextStatus, summary } : t,
92
- );
93
- return withProgressView(prev, { tools: updated });
94
- }
95
- }
96
- return withProgressView(prev, { tools });
97
- }
98
-
99
- case "done":
100
- return withProgressView(prev, {
101
- status: "done",
102
- showStop: false,
103
- text: event.text,
104
- });
105
-
106
- case "error":
107
- return withProgressView(prev, { status: "error", showStop: false });
108
-
109
- case "compact":
110
- // 旧上下文压缩不影响当前过程展示
111
- return prev;
112
- }
113
- }
1
+ /**
2
+ * progress/reducer.ts — ChatEvent 事件流 → ProgressView 的增量合并
3
+ *
4
+ * 这是飞书与终端共享的唯一一份"事件 → 过程视图"公共逻辑:
5
+ * 终端 REPL 直接消费 ChatSession.chat() 的事件流,逐条 reduce;
6
+ * 飞书侧 display loop 若未来接入事件流,同样使用本 reducer,保证两端
7
+ * 看到的过程状态(正文累积、工具调用、终态判定)完全一致。
8
+ */
9
+
10
+ import type { ChatEvent } from "../../deepccc-agent/src/index.ts";
11
+ import {
12
+ withProgressView,
13
+ type ProgressToolCall,
14
+ type ProgressView,
15
+ } from "./view.ts";
16
+
17
+ /** 工具调用 input 单行摘要(终端折叠行展示用) */
18
+ export function summarizeToolInput(input: unknown, maxChars = 120): string {
19
+ let raw: string;
20
+ if (typeof input === "string") {
21
+ raw = input;
22
+ } else {
23
+ try {
24
+ raw = JSON.stringify(input);
25
+ } catch {
26
+ raw = String(input);
27
+ }
28
+ }
29
+ const oneLine = raw.replace(/\s+/g, " ").trim();
30
+ return oneLine.length > maxChars ? oneLine.slice(0, maxChars) + "…" : oneLine;
31
+ }
32
+
33
+ /** 工具结果单行摘要(成功/失败各取首行) */
34
+ export function summarizeToolResult(content: unknown, maxChars = 120): string {
35
+ let raw: string;
36
+ if (typeof content === "string") {
37
+ raw = content;
38
+ } else if (content instanceof Error) {
39
+ raw = content.message;
40
+ } else {
41
+ try {
42
+ raw = JSON.stringify(content);
43
+ } catch {
44
+ raw = String(content);
45
+ }
46
+ }
47
+ const firstLine = raw.split("\n")[0] ?? "";
48
+ return firstLine.length > maxChars ? firstLine.slice(0, maxChars) + "…" : firstLine;
49
+ }
50
+
51
+ /**
52
+ * 把一条 ChatEvent 合并进 ProgressView,返回新视图(不可变更新)。
53
+ * 未识别的/不影响展示的事件(如 compact)返回原视图。
54
+ */
55
+ export function reduceProgress(prev: ProgressView, event: ChatEvent): ProgressView {
56
+ switch (event.type) {
57
+ case "status":
58
+ return withProgressView(prev, {
59
+ headerTitle: event.phase === "compacting" ? "压缩上下文中..." : "生成回复中...",
60
+ });
61
+
62
+ case "text":
63
+ // accumulated 是全文累积,直接全量替换,天然幂等
64
+ return withProgressView(prev, { text: event.accumulated });
65
+
66
+ case "tool_use": {
67
+ const tool: ProgressToolCall = {
68
+ id: event.id ?? `tool-${prev.tools.length + 1}`,
69
+ name: event.name,
70
+ status: "running",
71
+ detail: summarizeToolInput(event.input),
72
+ };
73
+ return withProgressView(prev, { tools: [...prev.tools, tool] });
74
+ }
75
+
76
+ case "tool_result": {
77
+ const nextStatus = event.is_error ? ("error" as const) : ("ok" as const);
78
+ const summary = summarizeToolResult(event.content);
79
+ let matched = false;
80
+ const tools = prev.tools.map((t) => {
81
+ if (matched || t.id !== event.tool_use_id) return t;
82
+ matched = true;
83
+ return { ...t, status: nextStatus, summary };
84
+ });
85
+ if (!matched) {
86
+ // id 缺失或失配:兜底更新最后一个 running 工具,避免状态悬挂
87
+ const lastRunning = [...prev.tools].reverse().findIndex((t) => t.status === "running");
88
+ if (lastRunning >= 0) {
89
+ const idx = prev.tools.length - 1 - lastRunning;
90
+ const updated = prev.tools.map((t, i) =>
91
+ i === idx ? { ...t, status: nextStatus, summary } : t,
92
+ );
93
+ return withProgressView(prev, { tools: updated });
94
+ }
95
+ }
96
+ return withProgressView(prev, { tools });
97
+ }
98
+
99
+ case "done":
100
+ return withProgressView(prev, {
101
+ status: "done",
102
+ showStop: false,
103
+ text: event.text,
104
+ });
105
+
106
+ case "error":
107
+ return withProgressView(prev, { status: "error", showStop: false });
108
+
109
+ case "compact":
110
+ // 旧上下文压缩不影响当前过程展示
111
+ return prev;
112
+ }
113
+ }