chatccc 0.2.199 → 0.2.200
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.
- package/README.md +1 -1
- package/agent-prompts/claude_specific.md +45 -45
- package/agent-prompts/codex_specific.md +2 -2
- package/agent-prompts/cursor_specific.md +13 -13
- package/bin/cccagent.mjs +17 -17
- package/config.sample.json +27 -27
- package/im-skills/feishu-skill/receive-send-file.md +63 -63
- package/im-skills/feishu-skill/receive-send-image.md +24 -24
- package/im-skills/feishu-skill/skill.md +3 -3
- package/im-skills/wechat-file-skill/receive-send-file.md +38 -38
- package/im-skills/wechat-file-skill/send-file.mjs +83 -83
- package/im-skills/wechat-file-skill/skill.md +10 -10
- package/im-skills/wechat-image-skill/skill.md +10 -10
- package/im-skills/wechat-video-skill/receive-send-video.md +38 -38
- package/im-skills/wechat-video-skill/send-video.mjs +79 -79
- package/im-skills/wechat-video-skill/skill.md +10 -10
- package/package.json +1 -1
- package/scripts/postinstall-sharp-check.mjs +58 -58
- package/src/__tests__/agent-delegate-task-rpc.test.ts +165 -165
- package/src/__tests__/agent-reload-config-rpc.test.ts +99 -99
- package/src/__tests__/builtin-chat-session.test.ts +277 -277
- package/src/__tests__/builtin-cli-json.test.ts +39 -39
- package/src/__tests__/builtin-config.test.ts +33 -33
- package/src/__tests__/builtin-context.test.ts +163 -163
- package/src/__tests__/builtin-file-tools.test.ts +224 -224
- package/src/__tests__/builtin-session-select.test.ts +116 -116
- package/src/__tests__/builtin-sigint.test.ts +56 -56
- package/src/__tests__/card-plain-text.test.ts +5 -5
- package/src/__tests__/cardkit.test.ts +60 -60
- package/src/__tests__/cards.test.ts +109 -109
- package/src/__tests__/ccc-adapter.test.ts +114 -114
- package/src/__tests__/chatgpt-subscription-rpc.test.ts +89 -89
- package/src/__tests__/chatgpt-subscription.test.ts +135 -135
- package/src/__tests__/chrome-devtools-guard.test.ts +165 -165
- package/src/__tests__/claude-adapter.test.ts +592 -592
- package/src/__tests__/claude-raw-stream-log.test.ts +87 -87
- package/src/__tests__/codex-raw-stream-log.test.ts +163 -163
- package/src/__tests__/codex-reset-actions.test.ts +146 -146
- package/src/__tests__/config-reload.test.ts +10 -10
- package/src/__tests__/config-sample.test.ts +18 -18
- package/src/__tests__/feishu-api.test.ts +60 -60
- package/src/__tests__/feishu-avatar.test.ts +87 -45
- package/src/__tests__/feishu-platform.test.ts +22 -22
- package/src/__tests__/format-message.test.ts +47 -47
- package/src/__tests__/jsonl-stream.test.ts +79 -79
- package/src/__tests__/orchestrator.test.ts +227 -202
- package/src/__tests__/privacy.test.ts +198 -198
- package/src/__tests__/raw-stream-log.test.ts +106 -106
- package/src/__tests__/session.test.ts +40 -40
- package/src/__tests__/shared-prefix.test.ts +36 -36
- package/src/__tests__/sim-platform.test.ts +12 -12
- package/src/__tests__/stream-state.test.ts +42 -42
- package/src/__tests__/web-ui.test.ts +209 -209
- package/src/adapters/ccc-adapter.ts +121 -121
- package/src/adapters/claude-adapter.ts +603 -603
- package/src/adapters/claude-session-meta-store.ts +120 -120
- package/src/adapters/codex-adapter.ts +380 -380
- package/src/adapters/jsonl-stream.ts +157 -157
- package/src/adapters/raw-stream-log.ts +124 -124
- package/src/adapters/resource-monitor.ts +140 -140
- package/src/agent-delegate-task-rpc.ts +153 -153
- package/src/agent-delegate-task.ts +81 -81
- package/src/agent-reload-config-rpc.ts +34 -34
- package/src/agent-stop-stuck.ts +129 -129
- package/src/builtin/cli.ts +473 -473
- package/src/builtin/context.ts +323 -323
- package/src/builtin/file-tools.ts +1072 -1072
- package/src/builtin/index.ts +404 -404
- package/src/builtin/session-select.ts +48 -48
- package/src/builtin/sigint.ts +50 -50
- package/src/cards.ts +195 -195
- package/src/chatgpt-subscription-rpc.ts +27 -27
- package/src/chatgpt-subscription.ts +299 -299
- package/src/chrome-devtools-guard.ts +318 -318
- package/src/codex-reset-actions.ts +184 -184
- package/src/config.ts +125 -125
- package/src/feishu-api.ts +86 -63
- package/src/feishu-platform.ts +20 -20
- package/src/format-message.ts +293 -293
- package/src/litellm-proxy.ts +374 -374
- package/src/orchestrator.ts +183 -183
- package/src/privacy.ts +118 -118
- package/src/runtime-reload.ts +34 -34
- package/src/session-chat-binding.ts +6 -6
- package/src/session-name.ts +8 -8
- package/src/session.ts +141 -141
- package/src/shared-prefix.ts +29 -29
- package/src/sim-platform.ts +20 -20
- package/src/turn-cards.ts +117 -117
- package/src/web-ui.ts +205 -205
|
@@ -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,153 +1,153 @@
|
|
|
1
|
-
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
-
import { resolve } from "node:path";
|
|
3
|
-
|
|
4
|
-
import { resolveDefaultAgentTool } from "./config.ts";
|
|
5
|
-
import { readUtf8JsonBody } from "./agent-rpc-body.ts";
|
|
6
|
-
import { delegateAgentTask } from "./agent-delegate-task.ts";
|
|
7
|
-
import type { PlatformAdapter } from "./platform-adapter.ts";
|
|
8
|
-
import { applySharedPrefix } from "./shared-prefix.ts";
|
|
9
|
-
|
|
10
|
-
export const AGENT_DELEGATE_TASK_PATH = "/api/agent/delegate-task";
|
|
11
|
-
|
|
12
|
-
const MAX_REQUEST_BYTES = 128 * 1024;
|
|
13
|
-
const VALID_TOOLS = new Set(["claude", "cursor", "codex"]);
|
|
14
|
-
|
|
15
|
-
interface AgentDelegateTaskPayload {
|
|
16
|
-
tool?: unknown;
|
|
17
|
-
cwd?: unknown;
|
|
18
|
-
prompt?: unknown;
|
|
19
|
-
text?: unknown;
|
|
20
|
-
message?: unknown;
|
|
21
|
-
open_id?: unknown;
|
|
22
|
-
open_ids?: unknown;
|
|
23
|
-
openIds?: unknown;
|
|
24
|
-
chat_name?: unknown;
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
function jsonReply(res: ServerResponse, status: number, data: unknown): void {
|
|
28
|
-
res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
|
|
29
|
-
res.end(JSON.stringify(data));
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
function stringValue(value: unknown): string {
|
|
33
|
-
return typeof value === "string" ? value.trim() : "";
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
function normalizeOpenIds(payload: AgentDelegateTaskPayload): string[] {
|
|
37
|
-
const explicitOpenId = stringValue(payload.open_id);
|
|
38
|
-
if (explicitOpenId) return [explicitOpenId];
|
|
39
|
-
|
|
40
|
-
const rawOpenIds = Array.isArray(payload.open_ids) ? payload.open_ids : payload.openIds;
|
|
41
|
-
if (!Array.isArray(rawOpenIds)) return [];
|
|
42
|
-
return rawOpenIds
|
|
43
|
-
.filter((item): item is string => typeof item === "string")
|
|
44
|
-
.map((item) => item.trim())
|
|
45
|
-
.filter(Boolean);
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
function promptFromPayload(payload: AgentDelegateTaskPayload): string {
|
|
49
|
-
return stringValue(payload.prompt) || stringValue(payload.text) || stringValue(payload.message);
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
function validateTool(rawTool: unknown): string {
|
|
53
|
-
const tool = stringValue(rawTool).toLowerCase() || resolveDefaultAgentTool();
|
|
54
|
-
if (!VALID_TOOLS.has(tool)) throw new Error(`unsupported tool: ${tool}`);
|
|
55
|
-
return tool;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
function validateCwd(rawCwd: unknown): string {
|
|
59
|
-
const cwd = stringValue(rawCwd);
|
|
60
|
-
if (!cwd) throw new Error("cwd must be a non-empty string");
|
|
61
|
-
return resolve(cwd);
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
export async function handleAgentDelegateTaskRequest(
|
|
65
|
-
req: IncomingMessage,
|
|
66
|
-
res: ServerResponse,
|
|
67
|
-
platform: PlatformAdapter,
|
|
68
|
-
): Promise<boolean> {
|
|
69
|
-
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
70
|
-
if (url.pathname !== AGENT_DELEGATE_TASK_PATH) return false;
|
|
71
|
-
|
|
72
|
-
if (req.method !== "POST") {
|
|
73
|
-
jsonReply(res, 405, { ok: false, error: "Method not allowed" });
|
|
74
|
-
return true;
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
if (platform.kind !== "feishu") {
|
|
78
|
-
jsonReply(res, 409, { ok: false, error: "This endpoint currently only supports Feishu." });
|
|
79
|
-
return true;
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
let payload: AgentDelegateTaskPayload;
|
|
83
|
-
try {
|
|
84
|
-
payload = await readUtf8JsonBody(req, MAX_REQUEST_BYTES);
|
|
85
|
-
} catch (err) {
|
|
86
|
-
jsonReply(res, 400, { ok: false, error: (err as Error).message || "Invalid JSON" });
|
|
87
|
-
return true;
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
let tool: string;
|
|
91
|
-
let cwd: string;
|
|
92
|
-
let promptText: string;
|
|
93
|
-
let promptNamePrefix: string;
|
|
94
|
-
let openIds: string[];
|
|
95
|
-
try {
|
|
96
|
-
tool = validateTool(payload.tool);
|
|
97
|
-
cwd = validateCwd(payload.cwd);
|
|
98
|
-
const rawPrompt = promptFromPayload(payload);
|
|
99
|
-
if (!rawPrompt) throw new Error("prompt must be a non-empty string");
|
|
100
|
-
const sharedPrefix = applySharedPrefix(rawPrompt);
|
|
101
|
-
promptText = sharedPrefix.text;
|
|
102
|
-
promptNamePrefix = sharedPrefix.body || rawPrompt;
|
|
103
|
-
openIds = normalizeOpenIds(payload);
|
|
104
|
-
if (openIds.length === 0) throw new Error("open_id or openIds must include at least one user");
|
|
105
|
-
} catch (err) {
|
|
106
|
-
jsonReply(res, 400, { ok: false, error: (err as Error).message });
|
|
107
|
-
return true;
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
try {
|
|
111
|
-
const result = await delegateAgentTask({
|
|
112
|
-
platform,
|
|
113
|
-
tool,
|
|
114
|
-
cwd,
|
|
115
|
-
promptText,
|
|
116
|
-
openIds,
|
|
117
|
-
chatNamePrefix: stringValue(payload.chat_name) || promptNamePrefix.slice(0, 10),
|
|
118
|
-
});
|
|
119
|
-
jsonReply(res, 200, {
|
|
120
|
-
ok: true,
|
|
121
|
-
chat_id: result.chatId,
|
|
122
|
-
session_id: result.sessionId,
|
|
123
|
-
tool: result.tool,
|
|
124
|
-
cwd: result.cwd,
|
|
125
|
-
});
|
|
126
|
-
} catch (err) {
|
|
127
|
-
jsonReply(res, 500, { ok: false, error: (err as Error).message });
|
|
128
|
-
}
|
|
129
|
-
return true;
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
export function buildAgentDelegateTaskCapabilityPrompt(input: { url: string; cwd?: string }): string {
|
|
133
|
-
const lines = [
|
|
134
|
-
"[ChatCCC local capability: delegate task]",
|
|
135
|
-
"You can create a separate Feishu ChatCCC agent session and assign its first task by calling this local endpoint.",
|
|
136
|
-
"",
|
|
137
|
-
`POST ${input.url}`,
|
|
138
|
-
"Content-Type: application/json; charset=utf-8",
|
|
139
|
-
"",
|
|
140
|
-
'Body: {"tool":"codex|claude|cursor","cwd":"absolute working directory","open_id":"Feishu open_id to invite","prompt":"first task text"}',
|
|
141
|
-
"",
|
|
142
|
-
"Rules:",
|
|
143
|
-
"- Use this only when the user asks you to start a separate delegated conversation/session.",
|
|
144
|
-
"- Pass cwd explicitly as an absolute local path.",
|
|
145
|
-
"- Pass tool explicitly when the user specified a target agent.",
|
|
146
|
-
"- Use open_id for one user or open_ids/openIds for multiple users.",
|
|
147
|
-
"- The prompt is sent through the normal ChatCCC prompt path, so project prompt injection and IM skills still apply.",
|
|
148
|
-
"- Request body must be UTF-8 encoded JSON bytes. Do not call Feishu Open Platform directly.",
|
|
149
|
-
"[/ChatCCC local capability: delegate task]",
|
|
150
|
-
];
|
|
151
|
-
if (input.cwd) lines.splice(2, 0, `Current working directory: ${input.cwd}`);
|
|
152
|
-
return lines.join("\n");
|
|
153
|
-
}
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
+
import { resolve } from "node:path";
|
|
3
|
+
|
|
4
|
+
import { resolveDefaultAgentTool } from "./config.ts";
|
|
5
|
+
import { readUtf8JsonBody } from "./agent-rpc-body.ts";
|
|
6
|
+
import { delegateAgentTask } from "./agent-delegate-task.ts";
|
|
7
|
+
import type { PlatformAdapter } from "./platform-adapter.ts";
|
|
8
|
+
import { applySharedPrefix } from "./shared-prefix.ts";
|
|
9
|
+
|
|
10
|
+
export const AGENT_DELEGATE_TASK_PATH = "/api/agent/delegate-task";
|
|
11
|
+
|
|
12
|
+
const MAX_REQUEST_BYTES = 128 * 1024;
|
|
13
|
+
const VALID_TOOLS = new Set(["claude", "cursor", "codex"]);
|
|
14
|
+
|
|
15
|
+
interface AgentDelegateTaskPayload {
|
|
16
|
+
tool?: unknown;
|
|
17
|
+
cwd?: unknown;
|
|
18
|
+
prompt?: unknown;
|
|
19
|
+
text?: unknown;
|
|
20
|
+
message?: unknown;
|
|
21
|
+
open_id?: unknown;
|
|
22
|
+
open_ids?: unknown;
|
|
23
|
+
openIds?: unknown;
|
|
24
|
+
chat_name?: unknown;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function jsonReply(res: ServerResponse, status: number, data: unknown): void {
|
|
28
|
+
res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
|
|
29
|
+
res.end(JSON.stringify(data));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function stringValue(value: unknown): string {
|
|
33
|
+
return typeof value === "string" ? value.trim() : "";
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function normalizeOpenIds(payload: AgentDelegateTaskPayload): string[] {
|
|
37
|
+
const explicitOpenId = stringValue(payload.open_id);
|
|
38
|
+
if (explicitOpenId) return [explicitOpenId];
|
|
39
|
+
|
|
40
|
+
const rawOpenIds = Array.isArray(payload.open_ids) ? payload.open_ids : payload.openIds;
|
|
41
|
+
if (!Array.isArray(rawOpenIds)) return [];
|
|
42
|
+
return rawOpenIds
|
|
43
|
+
.filter((item): item is string => typeof item === "string")
|
|
44
|
+
.map((item) => item.trim())
|
|
45
|
+
.filter(Boolean);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function promptFromPayload(payload: AgentDelegateTaskPayload): string {
|
|
49
|
+
return stringValue(payload.prompt) || stringValue(payload.text) || stringValue(payload.message);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function validateTool(rawTool: unknown): string {
|
|
53
|
+
const tool = stringValue(rawTool).toLowerCase() || resolveDefaultAgentTool();
|
|
54
|
+
if (!VALID_TOOLS.has(tool)) throw new Error(`unsupported tool: ${tool}`);
|
|
55
|
+
return tool;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function validateCwd(rawCwd: unknown): string {
|
|
59
|
+
const cwd = stringValue(rawCwd);
|
|
60
|
+
if (!cwd) throw new Error("cwd must be a non-empty string");
|
|
61
|
+
return resolve(cwd);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export async function handleAgentDelegateTaskRequest(
|
|
65
|
+
req: IncomingMessage,
|
|
66
|
+
res: ServerResponse,
|
|
67
|
+
platform: PlatformAdapter,
|
|
68
|
+
): Promise<boolean> {
|
|
69
|
+
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
70
|
+
if (url.pathname !== AGENT_DELEGATE_TASK_PATH) return false;
|
|
71
|
+
|
|
72
|
+
if (req.method !== "POST") {
|
|
73
|
+
jsonReply(res, 405, { ok: false, error: "Method not allowed" });
|
|
74
|
+
return true;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
if (platform.kind !== "feishu") {
|
|
78
|
+
jsonReply(res, 409, { ok: false, error: "This endpoint currently only supports Feishu." });
|
|
79
|
+
return true;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
let payload: AgentDelegateTaskPayload;
|
|
83
|
+
try {
|
|
84
|
+
payload = await readUtf8JsonBody(req, MAX_REQUEST_BYTES);
|
|
85
|
+
} catch (err) {
|
|
86
|
+
jsonReply(res, 400, { ok: false, error: (err as Error).message || "Invalid JSON" });
|
|
87
|
+
return true;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
let tool: string;
|
|
91
|
+
let cwd: string;
|
|
92
|
+
let promptText: string;
|
|
93
|
+
let promptNamePrefix: string;
|
|
94
|
+
let openIds: string[];
|
|
95
|
+
try {
|
|
96
|
+
tool = validateTool(payload.tool);
|
|
97
|
+
cwd = validateCwd(payload.cwd);
|
|
98
|
+
const rawPrompt = promptFromPayload(payload);
|
|
99
|
+
if (!rawPrompt) throw new Error("prompt must be a non-empty string");
|
|
100
|
+
const sharedPrefix = applySharedPrefix(rawPrompt);
|
|
101
|
+
promptText = sharedPrefix.text;
|
|
102
|
+
promptNamePrefix = sharedPrefix.body || rawPrompt;
|
|
103
|
+
openIds = normalizeOpenIds(payload);
|
|
104
|
+
if (openIds.length === 0) throw new Error("open_id or openIds must include at least one user");
|
|
105
|
+
} catch (err) {
|
|
106
|
+
jsonReply(res, 400, { ok: false, error: (err as Error).message });
|
|
107
|
+
return true;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
try {
|
|
111
|
+
const result = await delegateAgentTask({
|
|
112
|
+
platform,
|
|
113
|
+
tool,
|
|
114
|
+
cwd,
|
|
115
|
+
promptText,
|
|
116
|
+
openIds,
|
|
117
|
+
chatNamePrefix: stringValue(payload.chat_name) || promptNamePrefix.slice(0, 10),
|
|
118
|
+
});
|
|
119
|
+
jsonReply(res, 200, {
|
|
120
|
+
ok: true,
|
|
121
|
+
chat_id: result.chatId,
|
|
122
|
+
session_id: result.sessionId,
|
|
123
|
+
tool: result.tool,
|
|
124
|
+
cwd: result.cwd,
|
|
125
|
+
});
|
|
126
|
+
} catch (err) {
|
|
127
|
+
jsonReply(res, 500, { ok: false, error: (err as Error).message });
|
|
128
|
+
}
|
|
129
|
+
return true;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export function buildAgentDelegateTaskCapabilityPrompt(input: { url: string; cwd?: string }): string {
|
|
133
|
+
const lines = [
|
|
134
|
+
"[ChatCCC local capability: delegate task]",
|
|
135
|
+
"You can create a separate Feishu ChatCCC agent session and assign its first task by calling this local endpoint.",
|
|
136
|
+
"",
|
|
137
|
+
`POST ${input.url}`,
|
|
138
|
+
"Content-Type: application/json; charset=utf-8",
|
|
139
|
+
"",
|
|
140
|
+
'Body: {"tool":"codex|claude|cursor","cwd":"absolute working directory","open_id":"Feishu open_id to invite","prompt":"first task text"}',
|
|
141
|
+
"",
|
|
142
|
+
"Rules:",
|
|
143
|
+
"- Use this only when the user asks you to start a separate delegated conversation/session.",
|
|
144
|
+
"- Pass cwd explicitly as an absolute local path.",
|
|
145
|
+
"- Pass tool explicitly when the user specified a target agent.",
|
|
146
|
+
"- Use open_id for one user or open_ids/openIds for multiple users.",
|
|
147
|
+
"- The prompt is sent through the normal ChatCCC prompt path, so project prompt injection and IM skills still apply.",
|
|
148
|
+
"- Request body must be UTF-8 encoded JSON bytes. Do not call Feishu Open Platform directly.",
|
|
149
|
+
"[/ChatCCC local capability: delegate task]",
|
|
150
|
+
];
|
|
151
|
+
if (input.cwd) lines.splice(2, 0, `Current working directory: ${input.cwd}`);
|
|
152
|
+
return lines.join("\n");
|
|
153
|
+
}
|