chatccc 0.2.230 → 0.2.231

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 (116) hide show
  1. package/.agents/skills/create-chatccc-feishu-app/SKILL.md +85 -85
  2. package/.claude/skills/create-chatccc-feishu-app/SKILL.md +85 -85
  3. package/.cursor/skills/create-chatccc-feishu-app/SKILL.md +85 -85
  4. package/README.md +90 -90
  5. package/agent-prompts/claude_specific.md +45 -45
  6. package/agent-prompts/codex_specific.md +2 -2
  7. package/agent-prompts/cursor_specific.md +13 -13
  8. package/bin/cccagent.mjs +17 -17
  9. package/im-skills/feishu-skill/receive-send-file.md +63 -63
  10. package/im-skills/feishu-skill/receive-send-image.md +24 -24
  11. package/im-skills/feishu-skill/skill.md +3 -3
  12. package/im-skills/wechat-file-skill/receive-send-file.md +38 -38
  13. package/im-skills/wechat-file-skill/send-file.mjs +83 -83
  14. package/im-skills/wechat-file-skill/skill.md +10 -10
  15. package/im-skills/wechat-image-skill/skill.md +10 -10
  16. package/im-skills/wechat-video-skill/receive-send-video.md +38 -38
  17. package/im-skills/wechat-video-skill/send-video.mjs +79 -79
  18. package/im-skills/wechat-video-skill/skill.md +10 -10
  19. package/package.json +1 -1
  20. package/scripts/postinstall-sharp-check.mjs +58 -58
  21. package/src/__tests__/agent-activity.test.ts +86 -76
  22. package/src/__tests__/agent-delegate-task-rpc.test.ts +165 -165
  23. package/src/__tests__/agent-reload-config-rpc.test.ts +99 -99
  24. package/src/__tests__/builtin-chat-session.test.ts +65 -1
  25. package/src/__tests__/builtin-cli-json.test.ts +39 -39
  26. package/src/__tests__/builtin-config.test.ts +26 -26
  27. package/src/__tests__/builtin-context.test.ts +202 -163
  28. package/src/__tests__/builtin-permissions.test.ts +211 -211
  29. package/src/__tests__/builtin-session-select.test.ts +116 -116
  30. package/src/__tests__/builtin-sigint.test.ts +56 -56
  31. package/src/__tests__/builtin-web-tools.test.ts +220 -220
  32. package/src/__tests__/card-action-routing.test.ts +18 -18
  33. package/src/__tests__/cardkit.test.ts +60 -60
  34. package/src/__tests__/ccc-adapter.test.ts +170 -136
  35. package/src/__tests__/chatgpt-subscription-rpc.test.ts +89 -89
  36. package/src/__tests__/chatgpt-subscription.test.ts +135 -135
  37. package/src/__tests__/chrome-devtools-guard.test.ts +165 -165
  38. package/src/__tests__/claude-adapter.test.ts +614 -614
  39. package/src/__tests__/claude-raw-stream-log.test.ts +87 -87
  40. package/src/__tests__/codex-adapter.test.ts +58 -58
  41. package/src/__tests__/codex-raw-stream-log.test.ts +170 -170
  42. package/src/__tests__/codex-reset-actions.test.ts +146 -146
  43. package/src/__tests__/cursor-adapter.test.ts +268 -268
  44. package/src/__tests__/feishu-api.test.ts +60 -60
  45. package/src/__tests__/feishu-avatar.test.ts +164 -164
  46. package/src/__tests__/feishu-message-ingress.test.ts +138 -138
  47. package/src/__tests__/feishu-platform.test.ts +22 -22
  48. package/src/__tests__/format-message.test.ts +47 -47
  49. package/src/__tests__/jsonl-stream.test.ts +79 -79
  50. package/src/__tests__/package-files.test.ts +24 -24
  51. package/src/__tests__/privacy.test.ts +198 -198
  52. package/src/__tests__/progress-reducer.test.ts +121 -110
  53. package/src/__tests__/raw-stream-log.test.ts +106 -106
  54. package/src/__tests__/response-stall.test.ts +49 -49
  55. package/src/__tests__/session.test.ts +11 -16
  56. package/src/__tests__/shared-prefix.test.ts +36 -36
  57. package/src/__tests__/sim-platform.test.ts +16 -16
  58. package/src/__tests__/startup-lifecycle.test.ts +231 -231
  59. package/src/__tests__/stop-session.test.ts +34 -34
  60. package/src/__tests__/stream-state.test.ts +42 -42
  61. package/src/__tests__/terminal-renderer.test.ts +247 -247
  62. package/src/__tests__/update-command-guard.test.ts +144 -144
  63. package/src/__tests__/web-ui.test.ts +326 -326
  64. package/src/adapters/adapter-interface.ts +24 -18
  65. package/src/adapters/ccc-adapter.ts +141 -131
  66. package/src/adapters/claude-adapter.ts +620 -620
  67. package/src/adapters/claude-session-meta-store.ts +120 -120
  68. package/src/adapters/codex-adapter.ts +426 -426
  69. package/src/adapters/cursor-adapter.ts +681 -681
  70. package/src/adapters/jsonl-stream.ts +157 -157
  71. package/src/adapters/raw-stream-log.ts +124 -124
  72. package/src/adapters/resource-monitor.ts +140 -140
  73. package/src/agent-activity.ts +175 -170
  74. package/src/agent-delegate-task-rpc.ts +153 -153
  75. package/src/agent-delegate-task.ts +91 -91
  76. package/src/agent-reload-config-rpc.ts +34 -34
  77. package/src/agent-stop-stuck.ts +129 -129
  78. package/src/builtin/cli.ts +9 -2
  79. package/src/builtin/config.ts +84 -84
  80. package/src/builtin/context.ts +62 -4
  81. package/src/builtin/file-log.ts +38 -38
  82. package/src/builtin/index.ts +83 -19
  83. package/src/builtin/proc-tree-kill.ts +61 -61
  84. package/src/builtin/progress/cards-helpers.ts +76 -76
  85. package/src/builtin/progress/reducer.ts +113 -108
  86. package/src/builtin/progress/terminal-renderer.ts +294 -294
  87. package/src/builtin/progress/view.ts +77 -77
  88. package/src/builtin/raw-stream-log.ts +124 -124
  89. package/src/builtin/session-select.ts +48 -48
  90. package/src/builtin/sigint.ts +50 -50
  91. package/src/builtin/web-tools.ts +313 -313
  92. package/src/card-action-routing.ts +14 -14
  93. package/src/chatgpt-subscription-rpc.ts +27 -27
  94. package/src/chatgpt-subscription.ts +299 -299
  95. package/src/chrome-devtools-guard.ts +318 -318
  96. package/src/codex-reset-actions.ts +184 -184
  97. package/src/feishu-api.ts +193 -193
  98. package/src/feishu-message-ingress.ts +195 -195
  99. package/src/feishu-platform.ts +20 -20
  100. package/src/format-message.ts +293 -293
  101. package/src/litellm-proxy.ts +374 -374
  102. package/src/platform-adapter.ts +6 -6
  103. package/src/privacy.ts +118 -118
  104. package/src/progress/reducer.ts +113 -108
  105. package/src/progress/terminal-renderer.ts +294 -294
  106. package/src/progress/view.ts +77 -77
  107. package/src/response-stall.ts +28 -28
  108. package/src/runtime-reload.ts +34 -34
  109. package/src/session-chat-binding.ts +82 -82
  110. package/src/session-name.ts +8 -8
  111. package/src/session.ts +12 -11
  112. package/src/shared-prefix.ts +29 -29
  113. package/src/sim-platform.ts +20 -20
  114. package/src/startup-lifecycle.ts +250 -250
  115. package/src/turn-cards.ts +117 -117
  116. package/src/update-command-guard.ts +165 -165
@@ -1,141 +1,141 @@
1
- // =============================================================================
2
- // resource-monitor.ts — CLI 进程资源监控(CPU + 内存)
3
- // =============================================================================
4
- // 对所有 chatccc 启动的 CLI 进程持续监控 CPU 和内存占用。
5
- // 若连续 3 分钟两项指标均无变化,判定为僵死,发出 "stuck" 事件。
6
- // =============================================================================
7
-
8
- import { exec } from "node:child_process";
9
- import { EventEmitter } from "node:events";
10
-
11
- const CHECK_INTERVAL_MS = 30_000; // 30 秒检查一次
12
- const STUCK_THRESHOLD = 6; // 连续 6 次无变化 = 3 分钟
13
-
14
- interface ProcessSnapshot {
15
- cpu: number;
16
- memory: number;
17
- unchangedCount: number;
18
- }
19
-
20
- interface TrackedProcess {
21
- pid: number;
22
- sessionId: string;
23
- snapshot: ProcessSnapshot;
24
- }
25
-
26
- export const resourceMonitor = new EventEmitter();
27
-
28
- const tracked = new Map<number, TrackedProcess>();
29
-
30
- let timer: ReturnType<typeof setInterval> | null = null;
31
-
32
- function startIfNeeded(): void {
33
- if (timer) return;
34
- timer = setInterval(checkAll, CHECK_INTERVAL_MS);
35
- timer.unref?.();
36
- }
37
-
38
- function stopIfIdle(): void {
39
- if (tracked.size > 0) return;
40
- if (timer) { clearInterval(timer); timer = null; }
41
- }
42
-
43
- export function registerProcess(pid: number, sessionId: string): void {
44
- tracked.set(pid, { pid, sessionId, snapshot: { cpu: -1, memory: -1, unchangedCount: 0 } });
45
- startIfNeeded();
46
- }
47
-
48
- export function unregisterProcess(pid: number): void {
49
- tracked.delete(pid);
50
- stopIfIdle();
51
- }
52
-
53
- // ---------------------------------------------------------------------------
54
- // 批量查询进程指标(Windows PowerShell)
55
- // ---------------------------------------------------------------------------
56
-
57
- function execPowerShell(script: string, timeoutMs: number): Promise<string> {
58
- return new Promise((resolve, reject) => {
59
- exec(
60
- `powershell -NoProfile -Command "${script}"`,
61
- { timeout: timeoutMs, windowsHide: true },
62
- (err, stdout) => {
63
- if (err) reject(err);
64
- else resolve(stdout);
65
- },
66
- );
67
- });
68
- }
69
-
70
- async function getProcessMetrics(pids: number[]): Promise<Map<number, { cpu: number; memory: number }>> {
71
- const result = new Map<number, { cpu: number; memory: number }>();
72
- if (pids.length === 0) return result;
73
-
74
- const psScript = `Get-Process -Id ${pids.join(",")} -ErrorAction SilentlyContinue | ForEach-Object { "$($_.Id)|$($_.CPU)|$($_.WorkingSet64)" }`;
75
-
76
- try {
77
- const stdout = await execPowerShell(psScript, 10_000);
78
- for (const line of stdout.trim().split(/\r?\n/)) {
79
- const trimmed = line.trim();
80
- if (!trimmed) continue;
81
- const [idStr, cpuStr, memStr] = trimmed.split("|");
82
- const id = parseInt(idStr, 10);
83
- const cpu = parseFloat(cpuStr);
84
- const memory = parseInt(memStr, 10);
85
- if (!isNaN(id) && !isNaN(cpu) && !isNaN(memory)) {
86
- result.set(id, { cpu, memory });
87
- }
88
- }
89
- } catch {
90
- // PowerShell 查询失败时跳过本轮,下次重试
91
- }
92
-
93
- return result;
94
- }
95
-
96
- // ---------------------------------------------------------------------------
97
- // 定时检查
98
- // ---------------------------------------------------------------------------
99
-
100
- async function checkAll(): Promise<void> {
101
- if (tracked.size === 0) return;
102
-
103
- const pids = [...tracked.keys()];
104
- const metrics = await getProcessMetrics(pids);
105
-
106
- for (const [pid, tp] of tracked) {
107
- const m = metrics.get(pid);
108
- if (!m) {
109
- // 进程已不存在,停止追踪
110
- tracked.delete(pid);
111
- continue;
112
- }
113
-
114
- const prev = tp.snapshot;
115
- const cpuChanged = m.cpu !== prev.cpu;
116
- // 内存允许 ±1% 波动,避免正常抖动触发误判
117
- const memTolerance = prev.memory > 0 ? Math.max(prev.memory * 0.01, 1024 * 1024) : 1024 * 1024;
118
- const memChanged = Math.abs(m.memory - prev.memory) > memTolerance;
119
-
120
- if (!cpuChanged && !memChanged) {
121
- tp.snapshot.unchangedCount++;
122
- if (tp.snapshot.unchangedCount >= STUCK_THRESHOLD) {
123
- const idleMinutes = Math.round(
124
- (tp.snapshot.unchangedCount * CHECK_INTERVAL_MS) / 60_000,
125
- );
126
- resourceMonitor.emit("stuck", {
127
- pid: tp.pid,
128
- sessionId: tp.sessionId,
129
- idleMinutes,
130
- });
131
- tracked.delete(pid);
132
- }
133
- } else {
134
- tp.snapshot.unchangedCount = 0;
135
- }
136
- tp.snapshot.cpu = m.cpu;
137
- tp.snapshot.memory = m.memory;
138
- }
139
-
140
- stopIfIdle();
1
+ // =============================================================================
2
+ // resource-monitor.ts — CLI 进程资源监控(CPU + 内存)
3
+ // =============================================================================
4
+ // 对所有 chatccc 启动的 CLI 进程持续监控 CPU 和内存占用。
5
+ // 若连续 3 分钟两项指标均无变化,判定为僵死,发出 "stuck" 事件。
6
+ // =============================================================================
7
+
8
+ import { exec } from "node:child_process";
9
+ import { EventEmitter } from "node:events";
10
+
11
+ const CHECK_INTERVAL_MS = 30_000; // 30 秒检查一次
12
+ const STUCK_THRESHOLD = 6; // 连续 6 次无变化 = 3 分钟
13
+
14
+ interface ProcessSnapshot {
15
+ cpu: number;
16
+ memory: number;
17
+ unchangedCount: number;
18
+ }
19
+
20
+ interface TrackedProcess {
21
+ pid: number;
22
+ sessionId: string;
23
+ snapshot: ProcessSnapshot;
24
+ }
25
+
26
+ export const resourceMonitor = new EventEmitter();
27
+
28
+ const tracked = new Map<number, TrackedProcess>();
29
+
30
+ let timer: ReturnType<typeof setInterval> | null = null;
31
+
32
+ function startIfNeeded(): void {
33
+ if (timer) return;
34
+ timer = setInterval(checkAll, CHECK_INTERVAL_MS);
35
+ timer.unref?.();
36
+ }
37
+
38
+ function stopIfIdle(): void {
39
+ if (tracked.size > 0) return;
40
+ if (timer) { clearInterval(timer); timer = null; }
41
+ }
42
+
43
+ export function registerProcess(pid: number, sessionId: string): void {
44
+ tracked.set(pid, { pid, sessionId, snapshot: { cpu: -1, memory: -1, unchangedCount: 0 } });
45
+ startIfNeeded();
46
+ }
47
+
48
+ export function unregisterProcess(pid: number): void {
49
+ tracked.delete(pid);
50
+ stopIfIdle();
51
+ }
52
+
53
+ // ---------------------------------------------------------------------------
54
+ // 批量查询进程指标(Windows PowerShell)
55
+ // ---------------------------------------------------------------------------
56
+
57
+ function execPowerShell(script: string, timeoutMs: number): Promise<string> {
58
+ return new Promise((resolve, reject) => {
59
+ exec(
60
+ `powershell -NoProfile -Command "${script}"`,
61
+ { timeout: timeoutMs, windowsHide: true },
62
+ (err, stdout) => {
63
+ if (err) reject(err);
64
+ else resolve(stdout);
65
+ },
66
+ );
67
+ });
68
+ }
69
+
70
+ async function getProcessMetrics(pids: number[]): Promise<Map<number, { cpu: number; memory: number }>> {
71
+ const result = new Map<number, { cpu: number; memory: number }>();
72
+ if (pids.length === 0) return result;
73
+
74
+ const psScript = `Get-Process -Id ${pids.join(",")} -ErrorAction SilentlyContinue | ForEach-Object { "$($_.Id)|$($_.CPU)|$($_.WorkingSet64)" }`;
75
+
76
+ try {
77
+ const stdout = await execPowerShell(psScript, 10_000);
78
+ for (const line of stdout.trim().split(/\r?\n/)) {
79
+ const trimmed = line.trim();
80
+ if (!trimmed) continue;
81
+ const [idStr, cpuStr, memStr] = trimmed.split("|");
82
+ const id = parseInt(idStr, 10);
83
+ const cpu = parseFloat(cpuStr);
84
+ const memory = parseInt(memStr, 10);
85
+ if (!isNaN(id) && !isNaN(cpu) && !isNaN(memory)) {
86
+ result.set(id, { cpu, memory });
87
+ }
88
+ }
89
+ } catch {
90
+ // PowerShell 查询失败时跳过本轮,下次重试
91
+ }
92
+
93
+ return result;
94
+ }
95
+
96
+ // ---------------------------------------------------------------------------
97
+ // 定时检查
98
+ // ---------------------------------------------------------------------------
99
+
100
+ async function checkAll(): Promise<void> {
101
+ if (tracked.size === 0) return;
102
+
103
+ const pids = [...tracked.keys()];
104
+ const metrics = await getProcessMetrics(pids);
105
+
106
+ for (const [pid, tp] of tracked) {
107
+ const m = metrics.get(pid);
108
+ if (!m) {
109
+ // 进程已不存在,停止追踪
110
+ tracked.delete(pid);
111
+ continue;
112
+ }
113
+
114
+ const prev = tp.snapshot;
115
+ const cpuChanged = m.cpu !== prev.cpu;
116
+ // 内存允许 ±1% 波动,避免正常抖动触发误判
117
+ const memTolerance = prev.memory > 0 ? Math.max(prev.memory * 0.01, 1024 * 1024) : 1024 * 1024;
118
+ const memChanged = Math.abs(m.memory - prev.memory) > memTolerance;
119
+
120
+ if (!cpuChanged && !memChanged) {
121
+ tp.snapshot.unchangedCount++;
122
+ if (tp.snapshot.unchangedCount >= STUCK_THRESHOLD) {
123
+ const idleMinutes = Math.round(
124
+ (tp.snapshot.unchangedCount * CHECK_INTERVAL_MS) / 60_000,
125
+ );
126
+ resourceMonitor.emit("stuck", {
127
+ pid: tp.pid,
128
+ sessionId: tp.sessionId,
129
+ idleMinutes,
130
+ });
131
+ tracked.delete(pid);
132
+ }
133
+ } else {
134
+ tp.snapshot.unchangedCount = 0;
135
+ }
136
+ tp.snapshot.cpu = m.cpu;
137
+ tp.snapshot.memory = m.memory;
138
+ }
139
+
140
+ stopIfIdle();
141
141
  }
@@ -1,170 +1,175 @@
1
- import type { UnifiedBlock } from "./adapters/adapter-interface.ts";
2
-
3
- export type AgentActivityKind =
4
- | "starting"
5
- | "thinking"
6
- | "tool"
7
- | "processing"
8
- | "responding"
9
- | "searching"
10
- | "compacting";
11
-
12
- /** The user-visible activity of a running Agent turn. */
13
- export interface AgentActivity {
14
- kind: AgentActivityKind;
15
- /** Time when the current activity began, used for truthful elapsed time. */
16
- startedAt: number;
17
- toolName?: string;
18
- toolCount?: number;
19
- }
20
-
21
- interface ActiveTool {
22
- id: string;
23
- name: string;
24
- startedAt: number;
25
- }
26
-
27
- export interface AgentActivityTracker {
28
- activity: AgentActivity;
29
- activeTools: Map<string, ActiveTool>;
30
- nextAnonymousToolId: number;
31
- }
32
-
33
- export function createAgentActivityTracker(now = Date.now()): AgentActivityTracker {
34
- return {
35
- activity: { kind: "starting", startedAt: now },
36
- activeTools: new Map(),
37
- nextAnonymousToolId: 1,
38
- };
39
- }
40
-
41
- function sameVisibleActivity(left: AgentActivity, right: AgentActivity): boolean {
42
- return left.kind === right.kind
43
- && left.toolName === right.toolName
44
- && left.toolCount === right.toolCount;
45
- }
46
-
47
- function setActivity(tracker: AgentActivityTracker, next: AgentActivity): boolean {
48
- if (sameVisibleActivity(tracker.activity, next)) return false;
49
- tracker.activity = next;
50
- return true;
51
- }
52
-
53
- function refreshToolActivity(tracker: AgentActivityTracker): boolean {
54
- const tools = [...tracker.activeTools.values()];
55
- const first = tools[0];
56
- if (!first) return false;
57
- return setActivity(tracker, {
58
- kind: "tool",
59
- startedAt: first.startedAt,
60
- toolName: first.name,
61
- toolCount: tools.length,
62
- });
63
- }
64
-
65
- function removeCompletedTool(tracker: AgentActivityTracker, toolUseId: string): void {
66
- if (toolUseId && tracker.activeTools.delete(toolUseId)) return;
67
-
68
- // Older adapters did not always include a tool ID. Prefer an anonymous entry;
69
- // if there is only one active call, it is still safe to match that result.
70
- const anonymousId = [...tracker.activeTools.keys()].find((id) => id.startsWith("anonymous:"));
71
- if (anonymousId) {
72
- tracker.activeTools.delete(anonymousId);
73
- } else if (tracker.activeTools.size === 1) {
74
- const onlyId = tracker.activeTools.keys().next().value as string | undefined;
75
- if (onlyId) tracker.activeTools.delete(onlyId);
76
- }
77
- }
78
-
79
- /**
80
- * Applies one normalized Agent event and returns whether the persisted activity
81
- * changed. Tool activity takes precedence while a tool call is still active.
82
- */
83
- export function updateAgentActivity(
84
- tracker: AgentActivityTracker,
85
- block: UnifiedBlock,
86
- now = Date.now(),
87
- ): boolean {
88
- if (block.type === "tool_use") {
89
- const id = block.id || `anonymous:${tracker.nextAnonymousToolId++}`;
90
- const existing = tracker.activeTools.get(id);
91
- tracker.activeTools.set(id, {
92
- id,
93
- name: block.name || "未知工具",
94
- startedAt: existing?.startedAt ?? now,
95
- });
96
- return refreshToolActivity(tracker);
97
- }
98
-
99
- if (block.type === "tool_result") {
100
- removeCompletedTool(tracker, block.tool_use_id);
101
- if (tracker.activeTools.size > 0) return refreshToolActivity(tracker);
102
- return setActivity(tracker, { kind: "processing", startedAt: now });
103
- }
104
-
105
- if (tracker.activeTools.size > 0) return false;
106
-
107
- switch (block.type) {
108
- case "thinking":
109
- case "redacted_thinking":
110
- return setActivity(tracker, { kind: "thinking", startedAt: now });
111
- case "text":
112
- case "text_final":
113
- return setActivity(tracker, { kind: "responding", startedAt: now });
114
- case "search_result":
115
- return setActivity(tracker, { kind: "searching", startedAt: now });
116
- case "compact_boundary":
117
- return setActivity(tracker, { kind: "compacting", startedAt: now });
118
- }
119
- }
120
-
121
- function formatElapsed(startedAt: number, now: number): string {
122
- const totalSeconds = Math.max(0, Math.floor((now - startedAt) / 1000));
123
- if (totalSeconds < 60) return `${totalSeconds}秒`;
124
- const totalMinutes = Math.floor(totalSeconds / 60);
125
- const seconds = totalSeconds % 60;
126
- if (totalMinutes < 60) return `${totalMinutes}分${seconds}秒`;
127
- const hours = Math.floor(totalMinutes / 60);
128
- const minutes = totalMinutes % 60;
129
- return `${hours}小时${minutes}分`;
130
- }
131
-
132
- function displayToolName(name: string | undefined): string {
133
- const normalized = (name || "未知工具").replace(/\s+/g, " ").trim();
134
- return normalized.length > 24 ? `${normalized.slice(0, 23)}…` : normalized;
135
- }
136
-
137
- export function formatAgentActivityTitle(
138
- activity: AgentActivity | undefined,
139
- now = Date.now(),
140
- ): string {
141
- if (!activity) return "正在处理";
142
-
143
- let label: string;
144
- switch (activity.kind) {
145
- case "starting":
146
- label = "正在启动 Agent";
147
- break;
148
- case "thinking":
149
- label = "思考中";
150
- break;
151
- case "tool": {
152
- const count = Math.max(1, activity.toolCount ?? 1);
153
- label = `正在执行 ${displayToolName(activity.toolName)}${count > 1 ? ` 等 ${count} 项` : ""}`;
154
- break;
155
- }
156
- case "processing":
157
- label = "正在处理工具结果";
158
- break;
159
- case "responding":
160
- label = "正在生成回复";
161
- break;
162
- case "searching":
163
- label = "正在处理搜索结果";
164
- break;
165
- case "compacting":
166
- label = "正在整理上下文";
167
- break;
168
- }
169
- return `${label} · ${formatElapsed(activity.startedAt, now)}`;
170
- }
1
+ import type { UnifiedBlock } from "./adapters/adapter-interface.ts";
2
+
3
+ export type AgentActivityKind =
4
+ | "starting"
5
+ | "thinking"
6
+ | "tool"
7
+ | "processing"
8
+ | "responding"
9
+ | "searching"
10
+ | "compacting";
11
+
12
+ /** The user-visible activity of a running Agent turn. */
13
+ export interface AgentActivity {
14
+ kind: AgentActivityKind;
15
+ /** Time when the current activity began, used for truthful elapsed time. */
16
+ startedAt: number;
17
+ toolName?: string;
18
+ toolCount?: number;
19
+ }
20
+
21
+ interface ActiveTool {
22
+ id: string;
23
+ name: string;
24
+ startedAt: number;
25
+ }
26
+
27
+ export interface AgentActivityTracker {
28
+ activity: AgentActivity;
29
+ activeTools: Map<string, ActiveTool>;
30
+ nextAnonymousToolId: number;
31
+ }
32
+
33
+ export function createAgentActivityTracker(now = Date.now()): AgentActivityTracker {
34
+ return {
35
+ activity: { kind: "starting", startedAt: now },
36
+ activeTools: new Map(),
37
+ nextAnonymousToolId: 1,
38
+ };
39
+ }
40
+
41
+ function sameVisibleActivity(left: AgentActivity, right: AgentActivity): boolean {
42
+ return left.kind === right.kind
43
+ && left.toolName === right.toolName
44
+ && left.toolCount === right.toolCount;
45
+ }
46
+
47
+ function setActivity(tracker: AgentActivityTracker, next: AgentActivity): boolean {
48
+ if (sameVisibleActivity(tracker.activity, next)) return false;
49
+ tracker.activity = next;
50
+ return true;
51
+ }
52
+
53
+ function refreshToolActivity(tracker: AgentActivityTracker): boolean {
54
+ const tools = [...tracker.activeTools.values()];
55
+ const first = tools[0];
56
+ if (!first) return false;
57
+ return setActivity(tracker, {
58
+ kind: "tool",
59
+ startedAt: first.startedAt,
60
+ toolName: first.name,
61
+ toolCount: tools.length,
62
+ });
63
+ }
64
+
65
+ function removeCompletedTool(tracker: AgentActivityTracker, toolUseId: string): void {
66
+ if (toolUseId && tracker.activeTools.delete(toolUseId)) return;
67
+
68
+ // Older adapters did not always include a tool ID. Prefer an anonymous entry;
69
+ // if there is only one active call, it is still safe to match that result.
70
+ const anonymousId = [...tracker.activeTools.keys()].find((id) => id.startsWith("anonymous:"));
71
+ if (anonymousId) {
72
+ tracker.activeTools.delete(anonymousId);
73
+ } else if (tracker.activeTools.size === 1) {
74
+ const onlyId = tracker.activeTools.keys().next().value as string | undefined;
75
+ if (onlyId) tracker.activeTools.delete(onlyId);
76
+ }
77
+ }
78
+
79
+ /**
80
+ * Applies one normalized Agent event and returns whether the persisted activity
81
+ * changed. Tool activity takes precedence while a tool call is still active.
82
+ */
83
+ export function updateAgentActivity(
84
+ tracker: AgentActivityTracker,
85
+ block: UnifiedBlock,
86
+ now = Date.now(),
87
+ ): boolean {
88
+ if (block.type === "tool_use") {
89
+ const id = block.id || `anonymous:${tracker.nextAnonymousToolId++}`;
90
+ const existing = tracker.activeTools.get(id);
91
+ tracker.activeTools.set(id, {
92
+ id,
93
+ name: block.name || "未知工具",
94
+ startedAt: existing?.startedAt ?? now,
95
+ });
96
+ return refreshToolActivity(tracker);
97
+ }
98
+
99
+ if (block.type === "tool_result") {
100
+ removeCompletedTool(tracker, block.tool_use_id);
101
+ if (tracker.activeTools.size > 0) return refreshToolActivity(tracker);
102
+ return setActivity(tracker, { kind: "processing", startedAt: now });
103
+ }
104
+
105
+ if (tracker.activeTools.size > 0) return false;
106
+
107
+ switch (block.type) {
108
+ case "agent_status":
109
+ return setActivity(tracker, {
110
+ kind: block.status === "compacting" ? "compacting" : "responding",
111
+ startedAt: now,
112
+ });
113
+ case "thinking":
114
+ case "redacted_thinking":
115
+ return setActivity(tracker, { kind: "thinking", startedAt: now });
116
+ case "text":
117
+ case "text_final":
118
+ return setActivity(tracker, { kind: "responding", startedAt: now });
119
+ case "search_result":
120
+ return setActivity(tracker, { kind: "searching", startedAt: now });
121
+ case "compact_boundary":
122
+ return setActivity(tracker, { kind: "compacting", startedAt: now });
123
+ }
124
+ }
125
+
126
+ function formatElapsed(startedAt: number, now: number): string {
127
+ const totalSeconds = Math.max(0, Math.floor((now - startedAt) / 1000));
128
+ if (totalSeconds < 60) return `${totalSeconds}秒`;
129
+ const totalMinutes = Math.floor(totalSeconds / 60);
130
+ const seconds = totalSeconds % 60;
131
+ if (totalMinutes < 60) return `${totalMinutes}分${seconds}秒`;
132
+ const hours = Math.floor(totalMinutes / 60);
133
+ const minutes = totalMinutes % 60;
134
+ return `${hours}小时${minutes}分`;
135
+ }
136
+
137
+ function displayToolName(name: string | undefined): string {
138
+ const normalized = (name || "未知工具").replace(/\s+/g, " ").trim();
139
+ return normalized.length > 24 ? `${normalized.slice(0, 23)}…` : normalized;
140
+ }
141
+
142
+ export function formatAgentActivityTitle(
143
+ activity: AgentActivity | undefined,
144
+ now = Date.now(),
145
+ ): string {
146
+ if (!activity) return "正在处理";
147
+
148
+ let label: string;
149
+ switch (activity.kind) {
150
+ case "starting":
151
+ label = "正在启动 Agent";
152
+ break;
153
+ case "thinking":
154
+ label = "思考中";
155
+ break;
156
+ case "tool": {
157
+ const count = Math.max(1, activity.toolCount ?? 1);
158
+ label = `正在执行 ${displayToolName(activity.toolName)}${count > 1 ? ` 等 ${count} 项` : ""}`;
159
+ break;
160
+ }
161
+ case "processing":
162
+ label = "正在处理工具结果";
163
+ break;
164
+ case "responding":
165
+ label = "正在生成回复";
166
+ break;
167
+ case "searching":
168
+ label = "正在处理搜索结果";
169
+ break;
170
+ case "compacting":
171
+ label = "正在整理上下文";
172
+ break;
173
+ }
174
+ return `${label} · ${formatElapsed(activity.startedAt, now)}`;
175
+ }