chatccc 0.2.243 → 0.2.245

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 (65) hide show
  1. package/README.md +6 -6
  2. package/bin/cccagent.mjs +17 -17
  3. package/deepccc-agent/README.md +14 -8
  4. package/deepccc-agent/bin/deepccc.mjs +26 -26
  5. package/deepccc-agent/os-prompts/darwin.md +8 -0
  6. package/deepccc-agent/os-prompts/linux.md +8 -0
  7. package/deepccc-agent/os-prompts/win32.md +9 -0
  8. package/deepccc-agent/package-lock.json +2 -2
  9. package/deepccc-agent/package.json +63 -62
  10. package/deepccc-agent/src/__tests__/chat-session.test.ts +682 -578
  11. package/deepccc-agent/src/__tests__/cli-json.test.ts +49 -49
  12. package/deepccc-agent/src/__tests__/config.test.ts +26 -26
  13. package/deepccc-agent/src/__tests__/context.test.ts +319 -319
  14. package/deepccc-agent/src/__tests__/file-tools.test.ts +240 -240
  15. package/deepccc-agent/src/__tests__/permissions.test.ts +195 -195
  16. package/deepccc-agent/src/__tests__/privacy.test.ts +8 -5
  17. package/deepccc-agent/src/__tests__/progress-reducer.test.ts +121 -121
  18. package/deepccc-agent/src/__tests__/session-search.test.ts +262 -262
  19. package/deepccc-agent/src/__tests__/session-select.test.ts +116 -116
  20. package/deepccc-agent/src/__tests__/sigint.test.ts +56 -56
  21. package/deepccc-agent/src/__tests__/skills.test.ts +284 -284
  22. package/deepccc-agent/src/__tests__/terminal-renderer.test.ts +247 -247
  23. package/deepccc-agent/src/__tests__/web-tools.test.ts +220 -220
  24. package/deepccc-agent/src/cli.ts +7 -6
  25. package/deepccc-agent/src/config.ts +88 -84
  26. package/deepccc-agent/src/context.ts +465 -465
  27. package/deepccc-agent/src/file-log.ts +38 -38
  28. package/deepccc-agent/src/index.ts +103 -36
  29. package/deepccc-agent/src/proc-tree-kill.ts +61 -61
  30. package/deepccc-agent/src/progress/cards-helpers.ts +76 -76
  31. package/deepccc-agent/src/progress/reducer.ts +113 -113
  32. package/deepccc-agent/src/progress/terminal-renderer.ts +294 -294
  33. package/deepccc-agent/src/progress/view.ts +77 -77
  34. package/deepccc-agent/src/raw-stream-log.ts +124 -124
  35. package/deepccc-agent/src/session-search.ts +370 -370
  36. package/deepccc-agent/src/session-select.ts +48 -48
  37. package/deepccc-agent/src/sigint.ts +50 -50
  38. package/deepccc-agent/src/skills.ts +205 -205
  39. package/deepccc-agent/src/web-tools.ts +313 -313
  40. package/deepccc-agent/tsconfig.build.json +13 -13
  41. package/deepccc-agent/tsconfig.json +13 -13
  42. package/deepccc-agent/vitest.config.ts +7 -7
  43. package/package.json +1 -1
  44. package/src/__tests__/builtin-chat-session.test.ts +522 -522
  45. package/src/__tests__/builtin-config.test.ts +26 -26
  46. package/src/__tests__/builtin-context.test.ts +319 -319
  47. package/src/__tests__/builtin-file-tools.test.ts +240 -240
  48. package/src/__tests__/builtin-permissions.test.ts +211 -211
  49. package/src/__tests__/builtin-session-search.test.ts +262 -262
  50. package/src/__tests__/builtin-session-select.test.ts +116 -116
  51. package/src/__tests__/builtin-sigint.test.ts +56 -56
  52. package/src/__tests__/builtin-skills.test.ts +284 -284
  53. package/src/__tests__/builtin-web-tools.test.ts +220 -220
  54. package/src/__tests__/ccc-adapter.test.ts +15 -0
  55. package/src/__tests__/config.test.ts +17 -17
  56. package/src/__tests__/progress-reducer.test.ts +121 -121
  57. package/src/__tests__/session-ccc-config.test.ts +45 -45
  58. package/src/__tests__/session.test.ts +369 -306
  59. package/src/adapters/adapter-interface.ts +8 -2
  60. package/src/adapters/ccc-adapter.ts +149 -145
  61. package/src/config-utils.ts +13 -13
  62. package/src/config.ts +13 -13
  63. package/src/progress/reducer.ts +113 -113
  64. package/src/session-chat-binding.ts +83 -83
  65. package/src/session.ts +323 -320
@@ -151,12 +151,18 @@ export interface ToolPromptOptions {
151
151
  // ToolAdapter — 统一的 AI 工具适配器接口
152
152
  // ---------------------------------------------------------------------------
153
153
 
154
- export interface ToolAdapter {
154
+ export interface ToolAdapter {
155
155
  /** 日志/展示用名称,如 "Claude" */
156
156
  readonly displayName: string;
157
157
 
158
158
  /** 群描述中会话 ID 的前缀,如 "Claude Session:" */
159
- readonly sessionDescPrefix: string;
159
+ readonly sessionDescPrefix: string;
160
+
161
+ /**
162
+ * Whether ChatCCC may infer a stalled response from unchanged streamed output.
163
+ * Defaults to true. Adapters that only emit output after a request completes must disable it.
164
+ */
165
+ readonly responseStallDetectionEnabled?: boolean;
160
166
 
161
167
  /**
162
168
  * 创建新会话,返回会话 ID。
@@ -1,145 +1,149 @@
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 { config as deepCccConfig } from "../../deepccc-agent/src/config.ts";
3
+ import {
4
+ getBuiltinContextSession,
5
+ newBuiltinSessionId,
6
+ normalizeBuiltinSessionId,
7
+ } from "../../deepccc-agent/src/context.ts";
8
+ import { config, CCC_SESSION_PREFIX } from "../config.ts";
9
+ import type {
10
+ CreateSessionResult,
11
+ SessionInfo,
12
+ ToolAdapter,
13
+ ToolPromptOptions,
14
+ UnifiedStreamMessage,
15
+ } from "./adapter-interface.ts";
16
+
17
+ export interface CccAdapterOptions extends ChatSessionConfig {
18
+ contextDir?: string;
19
+ compactAtTokens?: number;
20
+ keepRecentMessages?: number;
21
+ compactionTimeoutMs?: number;
22
+ maxSteps?: number;
23
+ }
24
+
25
+ function toChatSessionOptions(
26
+ sessionId: string,
27
+ cwd: string,
28
+ options: CccAdapterOptions,
29
+ ): ChatSessionOptions {
30
+ return {
31
+ cwd,
32
+ persist: true,
33
+ sessionId,
34
+ contextDir: options.contextDir,
35
+ compactAtTokens: options.compactAtTokens,
36
+ keepRecentMessages: options.keepRecentMessages,
37
+ compactionTimeoutMs: options.compactionTimeoutMs,
38
+ maxSteps: options.maxSteps,
39
+ // chatccc 无终端可交互,且对齐 claude/codex 适配器的 bypass 模式:
40
+ // 高危命令不询问,全部放行(与独立 deepccc CLI 的 ask 模式不同)
41
+ permissionMode: "bypass",
42
+ };
43
+ }
44
+
45
+ export function createCccAdapter(options: CccAdapterOptions = {}): ToolAdapter {
46
+ if (!options.apiKey?.trim()) {
47
+ throw new Error("ChatCCC 未配置 CCC Agent API Key。请先填写 ccc.DEEPSEEK_API_KEY 后再启用 CCC Agent。");
48
+ }
49
+
50
+ const chatConfig: ChatSessionConfig = {
51
+ apiKey: options.apiKey,
52
+ ...(options.baseURL !== undefined ? { baseURL: options.baseURL } : {}),
53
+ ...(options.model !== undefined ? { model: options.model } : {}),
54
+ ...(options.effort !== undefined ? { effort: options.effort } : {}),
55
+ };
56
+
57
+ return {
58
+ displayName: "CCC Agent",
59
+ sessionDescPrefix: CCC_SESSION_PREFIX,
60
+ // Non-streaming DeepCCC emits its reply only after the provider request finishes,
61
+ // so unchanged output cannot distinguish a slow request from a stalled response.
62
+ responseStallDetectionEnabled: deepCccConfig.streaming,
63
+
64
+ async createSession(cwd: string): Promise<CreateSessionResult> {
65
+ const sessionId = newBuiltinSessionId();
66
+ const session = new ChatSession(
67
+ chatConfig,
68
+ toChatSessionOptions(sessionId, cwd, options),
69
+ );
70
+ session.reset();
71
+ return { sessionId };
72
+ },
73
+
74
+ async *prompt(
75
+ sessionId: string,
76
+ userText: string,
77
+ cwd: string,
78
+ signal?: AbortSignal,
79
+ _promptOptions?: ToolPromptOptions,
80
+ ): AsyncIterable<UnifiedStreamMessage> {
81
+ const normalizedSessionId = normalizeBuiltinSessionId(sessionId);
82
+ const session = new ChatSession(
83
+ chatConfig,
84
+ toChatSessionOptions(normalizedSessionId, cwd, options),
85
+ );
86
+
87
+ for await (const event of session.chat(userText, signal)) {
88
+ if (event.type === "status") {
89
+ yield {
90
+ type: "assistant",
91
+ blocks: [{
92
+ type: "agent_status",
93
+ status: event.phase === "compacting" ? "compacting" : "responding",
94
+ }],
95
+ };
96
+ } else if (event.type === "text") {
97
+ yield {
98
+ type: "assistant",
99
+ blocks: [{ type: "text", text: event.text }],
100
+ };
101
+ } else if (event.type === "tool_use") {
102
+ yield {
103
+ type: "assistant",
104
+ blocks: [{
105
+ type: "tool_use",
106
+ id: event.id,
107
+ name: event.name,
108
+ input: event.input,
109
+ }],
110
+ };
111
+ } else if (event.type === "tool_result") {
112
+ yield {
113
+ type: "assistant",
114
+ blocks: [{
115
+ type: "tool_result",
116
+ tool_use_id: event.tool_use_id,
117
+ content: event.content,
118
+ is_error: event.is_error,
119
+ }],
120
+ };
121
+ } else if (event.type === "done" && !signal?.aborted) {
122
+ yield {
123
+ type: "assistant",
124
+ blocks: [],
125
+ isFinalResponse: true,
126
+ };
127
+ } else if (event.type === "error") {
128
+ throw new Error(event.message);
129
+ }
130
+ }
131
+ },
132
+
133
+ async getSessionInfo(sessionId: string): Promise<SessionInfo | undefined> {
134
+ const normalizedSessionId = normalizeBuiltinSessionId(sessionId);
135
+ const info = getBuiltinContextSession(normalizedSessionId, options.contextDir);
136
+ if (!info) return undefined;
137
+ return {
138
+ sessionId: info.sessionId,
139
+ cwd: info.cwd,
140
+ lastModified: info.updatedAt,
141
+ model: options.model ?? config.ccc.model,
142
+ };
143
+ },
144
+
145
+ async closeSession(_sessionId: string): Promise<void> {
146
+ // ChatSession uses one request-scoped stream per prompt. AbortSignal handles cancellation.
147
+ },
148
+ };
149
+ }
@@ -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
+ }