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,81 +1,81 @@
|
|
|
1
|
-
import { resolve } from "node:path";
|
|
2
|
-
|
|
3
|
-
import { sessionPrefixForTool, toolDisplayName, ts } from "./config.ts";
|
|
4
|
-
import { setDefaultCwd } from "./config.ts";
|
|
5
|
-
import type { PlatformAdapter } from "./platform-adapter.ts";
|
|
6
|
-
import { initClaudeSession, recordSessionRegistry, resumeAndPrompt, saveSessionTool } from "./session.ts";
|
|
7
|
-
import { bindChatToSession } from "./session-chat-binding.ts";
|
|
8
|
-
import { sessionChatName } from "./session-name.ts";
|
|
9
|
-
|
|
10
|
-
export interface DelegateAgentTaskInput {
|
|
11
|
-
platform: PlatformAdapter;
|
|
12
|
-
tool: string;
|
|
13
|
-
cwd: string;
|
|
14
|
-
promptText: string;
|
|
15
|
-
openIds: string[];
|
|
16
|
-
chatNamePrefix?: string;
|
|
17
|
-
msgTimestamp?: number;
|
|
18
|
-
traceId?: string;
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
export interface DelegateAgentTaskResult {
|
|
22
|
-
chatId: string;
|
|
23
|
-
sessionId: string;
|
|
24
|
-
tool: string;
|
|
25
|
-
cwd: string;
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
export async function delegateAgentTask(input: DelegateAgentTaskInput): Promise<DelegateAgentTaskResult> {
|
|
29
|
-
const cwd = resolve(input.cwd);
|
|
30
|
-
const toolLabel = toolDisplayName(input.tool);
|
|
31
|
-
const init = await initClaudeSession(input.tool, cwd);
|
|
32
|
-
const sessionId = init.sessionId;
|
|
33
|
-
const chatNamePrefix = input.chatNamePrefix?.trim() || input.promptText.slice(0, 10) || "新会话";
|
|
34
|
-
const chatName = sessionChatName(chatNamePrefix, cwd);
|
|
35
|
-
|
|
36
|
-
let chatId: string;
|
|
37
|
-
try {
|
|
38
|
-
chatId = await input.platform.createGroup(chatName, input.openIds);
|
|
39
|
-
await input.platform.updateChatInfo(chatId, chatName, `${sessionPrefixForTool(input.tool)} ${sessionId}`);
|
|
40
|
-
await setDefaultCwd(cwd, chatId);
|
|
41
|
-
bindChatToSession(sessionId, chatId);
|
|
42
|
-
await recordSessionRegistry({
|
|
43
|
-
chatId,
|
|
44
|
-
sessionId,
|
|
45
|
-
tool: input.tool,
|
|
46
|
-
chatName,
|
|
47
|
-
turnCount: 0,
|
|
48
|
-
startTime: Date.now(),
|
|
49
|
-
running: false,
|
|
50
|
-
});
|
|
51
|
-
await saveSessionTool(sessionId, input.tool, chatName);
|
|
52
|
-
} catch (err) {
|
|
53
|
-
console.error(`[${ts()}] [AGENT-DELEGATE-TASK] create group failed: ${(err as Error).message}`);
|
|
54
|
-
throw err;
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
await input.platform.sendCard(
|
|
58
|
-
chatId,
|
|
59
|
-
`${toolLabel} Session Ready`,
|
|
60
|
-
`已创建 **${toolLabel}** 会话群。\n\n` +
|
|
61
|
-
`**Session ID:** ${sessionId}\n` +
|
|
62
|
-
`**工作目录:** \`${cwd}\`\n\n` +
|
|
63
|
-
`下面会自动把任务作为第一句话发送给 ${toolLabel}。`,
|
|
64
|
-
"green",
|
|
65
|
-
).catch(() => {});
|
|
66
|
-
input.platform.setChatAvatar(chatId, input.tool, "new").catch(() => {});
|
|
67
|
-
|
|
68
|
-
await resumeAndPrompt(
|
|
69
|
-
sessionId,
|
|
70
|
-
input.promptText,
|
|
71
|
-
input.platform,
|
|
72
|
-
chatId,
|
|
73
|
-
input.msgTimestamp ?? Date.now(),
|
|
74
|
-
input.tool,
|
|
75
|
-
input.traceId,
|
|
76
|
-
);
|
|
77
|
-
|
|
78
|
-
console.log(`[${ts()}] [AGENT-DELEGATE-TASK] created ${toolLabel} session=${sessionId} chat=${chatId} cwd=${cwd}`);
|
|
79
|
-
return { chatId, sessionId, tool: input.tool, cwd };
|
|
80
|
-
}
|
|
81
|
-
|
|
1
|
+
import { resolve } from "node:path";
|
|
2
|
+
|
|
3
|
+
import { sessionPrefixForTool, toolDisplayName, ts } from "./config.ts";
|
|
4
|
+
import { setDefaultCwd } from "./config.ts";
|
|
5
|
+
import type { PlatformAdapter } from "./platform-adapter.ts";
|
|
6
|
+
import { initClaudeSession, recordSessionRegistry, resumeAndPrompt, saveSessionTool } from "./session.ts";
|
|
7
|
+
import { bindChatToSession } from "./session-chat-binding.ts";
|
|
8
|
+
import { sessionChatName } from "./session-name.ts";
|
|
9
|
+
|
|
10
|
+
export interface DelegateAgentTaskInput {
|
|
11
|
+
platform: PlatformAdapter;
|
|
12
|
+
tool: string;
|
|
13
|
+
cwd: string;
|
|
14
|
+
promptText: string;
|
|
15
|
+
openIds: string[];
|
|
16
|
+
chatNamePrefix?: string;
|
|
17
|
+
msgTimestamp?: number;
|
|
18
|
+
traceId?: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface DelegateAgentTaskResult {
|
|
22
|
+
chatId: string;
|
|
23
|
+
sessionId: string;
|
|
24
|
+
tool: string;
|
|
25
|
+
cwd: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export async function delegateAgentTask(input: DelegateAgentTaskInput): Promise<DelegateAgentTaskResult> {
|
|
29
|
+
const cwd = resolve(input.cwd);
|
|
30
|
+
const toolLabel = toolDisplayName(input.tool);
|
|
31
|
+
const init = await initClaudeSession(input.tool, cwd);
|
|
32
|
+
const sessionId = init.sessionId;
|
|
33
|
+
const chatNamePrefix = input.chatNamePrefix?.trim() || input.promptText.slice(0, 10) || "新会话";
|
|
34
|
+
const chatName = sessionChatName(chatNamePrefix, cwd);
|
|
35
|
+
|
|
36
|
+
let chatId: string;
|
|
37
|
+
try {
|
|
38
|
+
chatId = await input.platform.createGroup(chatName, input.openIds);
|
|
39
|
+
await input.platform.updateChatInfo(chatId, chatName, `${sessionPrefixForTool(input.tool)} ${sessionId}`);
|
|
40
|
+
await setDefaultCwd(cwd, chatId);
|
|
41
|
+
bindChatToSession(sessionId, chatId);
|
|
42
|
+
await recordSessionRegistry({
|
|
43
|
+
chatId,
|
|
44
|
+
sessionId,
|
|
45
|
+
tool: input.tool,
|
|
46
|
+
chatName,
|
|
47
|
+
turnCount: 0,
|
|
48
|
+
startTime: Date.now(),
|
|
49
|
+
running: false,
|
|
50
|
+
});
|
|
51
|
+
await saveSessionTool(sessionId, input.tool, chatName);
|
|
52
|
+
} catch (err) {
|
|
53
|
+
console.error(`[${ts()}] [AGENT-DELEGATE-TASK] create group failed: ${(err as Error).message}`);
|
|
54
|
+
throw err;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
await input.platform.sendCard(
|
|
58
|
+
chatId,
|
|
59
|
+
`${toolLabel} Session Ready`,
|
|
60
|
+
`已创建 **${toolLabel}** 会话群。\n\n` +
|
|
61
|
+
`**Session ID:** ${sessionId}\n` +
|
|
62
|
+
`**工作目录:** \`${cwd}\`\n\n` +
|
|
63
|
+
`下面会自动把任务作为第一句话发送给 ${toolLabel}。`,
|
|
64
|
+
"green",
|
|
65
|
+
).catch(() => {});
|
|
66
|
+
input.platform.setChatAvatar(chatId, input.tool, "new").catch(() => {});
|
|
67
|
+
|
|
68
|
+
await resumeAndPrompt(
|
|
69
|
+
sessionId,
|
|
70
|
+
input.promptText,
|
|
71
|
+
input.platform,
|
|
72
|
+
chatId,
|
|
73
|
+
input.msgTimestamp ?? Date.now(),
|
|
74
|
+
input.tool,
|
|
75
|
+
input.traceId,
|
|
76
|
+
);
|
|
77
|
+
|
|
78
|
+
console.log(`[${ts()}] [AGENT-DELEGATE-TASK] created ${toolLabel} session=${sessionId} chat=${chatId} cwd=${cwd}`);
|
|
79
|
+
return { chatId, sessionId, tool: input.tool, cwd };
|
|
80
|
+
}
|
|
81
|
+
|
|
@@ -1,34 +1,34 @@
|
|
|
1
|
-
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
-
|
|
3
|
-
import { reloadRuntimeConfig, type RuntimeReloadResult } from "./runtime-reload.ts";
|
|
4
|
-
|
|
5
|
-
export const AGENT_RELOAD_CONFIG_PATH = "/api/agent/reload-config";
|
|
6
|
-
|
|
7
|
-
type ReloadRuntimeConfig = (source: string) => RuntimeReloadResult | Promise<RuntimeReloadResult>;
|
|
8
|
-
|
|
9
|
-
function jsonReply(res: ServerResponse, status: number, data: unknown): void {
|
|
10
|
-
res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
|
|
11
|
-
res.end(JSON.stringify(data));
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
export async function handleAgentReloadConfigRequest(
|
|
15
|
-
req: IncomingMessage,
|
|
16
|
-
res: ServerResponse,
|
|
17
|
-
reload: ReloadRuntimeConfig = reloadRuntimeConfig,
|
|
18
|
-
): Promise<boolean> {
|
|
19
|
-
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
20
|
-
if (url.pathname !== AGENT_RELOAD_CONFIG_PATH) return false;
|
|
21
|
-
|
|
22
|
-
if (req.method !== "POST") {
|
|
23
|
-
jsonReply(res, 405, { ok: false, error: "Method not allowed" });
|
|
24
|
-
return true;
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
try {
|
|
28
|
-
const result = await reload("agent-reload-api");
|
|
29
|
-
jsonReply(res, 200, { ok: true, ...result });
|
|
30
|
-
} catch (err) {
|
|
31
|
-
jsonReply(res, 500, { ok: false, error: (err as Error).message });
|
|
32
|
-
}
|
|
33
|
-
return true;
|
|
34
|
-
}
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
+
|
|
3
|
+
import { reloadRuntimeConfig, type RuntimeReloadResult } from "./runtime-reload.ts";
|
|
4
|
+
|
|
5
|
+
export const AGENT_RELOAD_CONFIG_PATH = "/api/agent/reload-config";
|
|
6
|
+
|
|
7
|
+
type ReloadRuntimeConfig = (source: string) => RuntimeReloadResult | Promise<RuntimeReloadResult>;
|
|
8
|
+
|
|
9
|
+
function jsonReply(res: ServerResponse, status: number, data: unknown): void {
|
|
10
|
+
res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
|
|
11
|
+
res.end(JSON.stringify(data));
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export async function handleAgentReloadConfigRequest(
|
|
15
|
+
req: IncomingMessage,
|
|
16
|
+
res: ServerResponse,
|
|
17
|
+
reload: ReloadRuntimeConfig = reloadRuntimeConfig,
|
|
18
|
+
): Promise<boolean> {
|
|
19
|
+
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
20
|
+
if (url.pathname !== AGENT_RELOAD_CONFIG_PATH) return false;
|
|
21
|
+
|
|
22
|
+
if (req.method !== "POST") {
|
|
23
|
+
jsonReply(res, 405, { ok: false, error: "Method not allowed" });
|
|
24
|
+
return true;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
try {
|
|
28
|
+
const result = await reload("agent-reload-api");
|
|
29
|
+
jsonReply(res, 200, { ok: true, ...result });
|
|
30
|
+
} catch (err) {
|
|
31
|
+
jsonReply(res, 500, { ok: false, error: (err as Error).message });
|
|
32
|
+
}
|
|
33
|
+
return true;
|
|
34
|
+
}
|
package/src/agent-stop-stuck.ts
CHANGED
|
@@ -1,129 +1,129 @@
|
|
|
1
|
-
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
-
|
|
3
|
-
import { readUtf8JsonBody } from "./agent-rpc-body.ts";
|
|
4
|
-
import { activePrompts, getChatsForSession } from "./session-chat-binding.ts";
|
|
5
|
-
import { getPlatformForChat } from "./session.ts";
|
|
6
|
-
import { readStreamState, writeStreamState } from "./stream-state.ts";
|
|
7
|
-
import { ts } from "./config.ts";
|
|
8
|
-
|
|
9
|
-
export const AGENT_STOP_STUCK_PATH = "/api/agent/stop-stuck-loop";
|
|
10
|
-
|
|
11
|
-
const MAX_REQUEST_BYTES = 8 * 1024;
|
|
12
|
-
|
|
13
|
-
function jsonReply(res: ServerResponse, status: number, data: unknown): void {
|
|
14
|
-
res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
|
|
15
|
-
res.end(JSON.stringify(data));
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
/**
|
|
19
|
-
* 从原始 body 字节中用正则尽力提取 session_id。
|
|
20
|
-
* 兼容 JSON 编码异常(如 GBK 中文导致 JSON.parse 失败)的场景。
|
|
21
|
-
*/
|
|
22
|
-
function extractSessionIdFromRaw(buf: Buffer): string | null {
|
|
23
|
-
// 匹配 "session_id":"<uuid>" 或 "session_id": "<uuid>"
|
|
24
|
-
const match = buf.toString("latin1").match(/"session_id"\s*:\s*"([^"]+)"/);
|
|
25
|
-
return match?.[1] ?? null;
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
export async function handleAgentStopStuckRequest(
|
|
29
|
-
req: IncomingMessage,
|
|
30
|
-
res: ServerResponse,
|
|
31
|
-
): Promise<boolean> {
|
|
32
|
-
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
33
|
-
if (url.pathname !== AGENT_STOP_STUCK_PATH) return false;
|
|
34
|
-
|
|
35
|
-
if (req.method !== "POST") {
|
|
36
|
-
jsonReply(res, 405, { error: "Method not allowed, use POST" });
|
|
37
|
-
return true;
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
let body: { session_id?: string; final_reply?: string };
|
|
41
|
-
let rawBody: Buffer | null = null;
|
|
42
|
-
try {
|
|
43
|
-
body = await readUtf8JsonBody<{ session_id?: string; final_reply?: string }>(req, MAX_REQUEST_BYTES);
|
|
44
|
-
} catch (err) {
|
|
45
|
-
// JSON 解析失败时仍尝试从原始字节中提取 session_id 并强行停止
|
|
46
|
-
// 宁可输出乱码,也不能让 agent 持续循环
|
|
47
|
-
rawBody = (err as { rawBody?: Buffer }).rawBody as Buffer | undefined ?? null;
|
|
48
|
-
if (!rawBody) {
|
|
49
|
-
jsonReply(res, 400, { error: `Invalid request body: ${(err as Error).message}` });
|
|
50
|
-
return true;
|
|
51
|
-
}
|
|
52
|
-
const fallbackId = extractSessionIdFromRaw(rawBody);
|
|
53
|
-
if (!fallbackId) {
|
|
54
|
-
jsonReply(res, 400, { error: `Invalid request body: ${(err as Error).message}` });
|
|
55
|
-
return true;
|
|
56
|
-
}
|
|
57
|
-
body = { session_id: fallbackId };
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
const sessionId = typeof body?.session_id === "string" ? body.session_id.trim() : "";
|
|
61
|
-
if (!sessionId) {
|
|
62
|
-
jsonReply(res, 400, { error: "session_id is required" });
|
|
63
|
-
return true;
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
const prompt = activePrompts.get(sessionId);
|
|
67
|
-
if (!prompt) {
|
|
68
|
-
jsonReply(res, 404, { error: "Session not found or not running" });
|
|
69
|
-
return true;
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
// 先发"卡住"提示消息给所有绑定的群聊
|
|
73
|
-
const chats = getChatsForSession(sessionId);
|
|
74
|
-
for (const chatId of chats) {
|
|
75
|
-
const platform = getPlatformForChat(chatId);
|
|
76
|
-
if (platform) {
|
|
77
|
-
await platform.sendText(chatId, "⚠️ Agent 检测到自己陷入了循环,正在结束生成…").catch(() => {});
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
// 不丢弃缓存队列中的消息,让 runAgentSession 的 finally 块正常消费,
|
|
82
|
-
// 确保 stop-stuck-loop 结束后排队的消息仍能被正常处理。
|
|
83
|
-
|
|
84
|
-
const finalReply = typeof body?.final_reply === "string" ? body.final_reply.trim() : "";
|
|
85
|
-
|
|
86
|
-
// fire-and-forget:立即把 stream-state 标为 done(而非 stopped),
|
|
87
|
-
// 让 display loop 以"正常完成"而非"已停止"来渲染卡片和最终回复。
|
|
88
|
-
// 不设 prompt.stopped = true,这样 runAgentSession 的 finally 也会写 "done"。
|
|
89
|
-
void (async () => {
|
|
90
|
-
try {
|
|
91
|
-
const current = await readStreamState(sessionId);
|
|
92
|
-
if (!current) return;
|
|
93
|
-
if (current.status !== "running") return;
|
|
94
|
-
await writeStreamState({
|
|
95
|
-
...current,
|
|
96
|
-
status: "done",
|
|
97
|
-
stuckAt: Date.now(),
|
|
98
|
-
finalReply: finalReply ? current.finalReply + "\n\n" + finalReply : current.finalReply,
|
|
99
|
-
updatedAt: Date.now(),
|
|
100
|
-
});
|
|
101
|
-
} catch (err) {
|
|
102
|
-
console.warn(
|
|
103
|
-
`[${ts()}] [STUCK-LOOP] writeStreamState(done) failed for ${sessionId}: ${(err as Error).message}`,
|
|
104
|
-
);
|
|
105
|
-
}
|
|
106
|
-
})();
|
|
107
|
-
|
|
108
|
-
// 先关闭底层 SDK session,终止 CLI 子进程,然后再 abort 清理 adapter 层
|
|
109
|
-
prompt.closeSession?.();
|
|
110
|
-
|
|
111
|
-
// 强制杀死 CLI 子进程。controller.abort() 只在 for-await 收到下一条
|
|
112
|
-
// stream 消息时才被检测到——如果 agent 陷入无输出的计算循环,abort 信号
|
|
113
|
-
// 永远不会生效;SDK 的 session.close() 也不保证立即终止子进程。
|
|
114
|
-
if (prompt.processPid !== undefined) {
|
|
115
|
-
try {
|
|
116
|
-
process.kill(prompt.processPid);
|
|
117
|
-
} catch {
|
|
118
|
-
// 进程可能已退出,忽略错误
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
// 不设 stopped 标记 → finally block 写 "done" → 卡片正常结束
|
|
123
|
-
prompt.controller.abort();
|
|
124
|
-
|
|
125
|
-
console.log(`[${ts()}] [STUCK-LOOP] Session ${sessionId} aborted as done (agent detected stuck loop, final_reply=${finalReply ? "yes" : "no"})`);
|
|
126
|
-
|
|
127
|
-
jsonReply(res, 200, { ok: true });
|
|
128
|
-
return true;
|
|
129
|
-
}
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
+
|
|
3
|
+
import { readUtf8JsonBody } from "./agent-rpc-body.ts";
|
|
4
|
+
import { activePrompts, getChatsForSession } from "./session-chat-binding.ts";
|
|
5
|
+
import { getPlatformForChat } from "./session.ts";
|
|
6
|
+
import { readStreamState, writeStreamState } from "./stream-state.ts";
|
|
7
|
+
import { ts } from "./config.ts";
|
|
8
|
+
|
|
9
|
+
export const AGENT_STOP_STUCK_PATH = "/api/agent/stop-stuck-loop";
|
|
10
|
+
|
|
11
|
+
const MAX_REQUEST_BYTES = 8 * 1024;
|
|
12
|
+
|
|
13
|
+
function jsonReply(res: ServerResponse, status: number, data: unknown): void {
|
|
14
|
+
res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
|
|
15
|
+
res.end(JSON.stringify(data));
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* 从原始 body 字节中用正则尽力提取 session_id。
|
|
20
|
+
* 兼容 JSON 编码异常(如 GBK 中文导致 JSON.parse 失败)的场景。
|
|
21
|
+
*/
|
|
22
|
+
function extractSessionIdFromRaw(buf: Buffer): string | null {
|
|
23
|
+
// 匹配 "session_id":"<uuid>" 或 "session_id": "<uuid>"
|
|
24
|
+
const match = buf.toString("latin1").match(/"session_id"\s*:\s*"([^"]+)"/);
|
|
25
|
+
return match?.[1] ?? null;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export async function handleAgentStopStuckRequest(
|
|
29
|
+
req: IncomingMessage,
|
|
30
|
+
res: ServerResponse,
|
|
31
|
+
): Promise<boolean> {
|
|
32
|
+
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
33
|
+
if (url.pathname !== AGENT_STOP_STUCK_PATH) return false;
|
|
34
|
+
|
|
35
|
+
if (req.method !== "POST") {
|
|
36
|
+
jsonReply(res, 405, { error: "Method not allowed, use POST" });
|
|
37
|
+
return true;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
let body: { session_id?: string; final_reply?: string };
|
|
41
|
+
let rawBody: Buffer | null = null;
|
|
42
|
+
try {
|
|
43
|
+
body = await readUtf8JsonBody<{ session_id?: string; final_reply?: string }>(req, MAX_REQUEST_BYTES);
|
|
44
|
+
} catch (err) {
|
|
45
|
+
// JSON 解析失败时仍尝试从原始字节中提取 session_id 并强行停止
|
|
46
|
+
// 宁可输出乱码,也不能让 agent 持续循环
|
|
47
|
+
rawBody = (err as { rawBody?: Buffer }).rawBody as Buffer | undefined ?? null;
|
|
48
|
+
if (!rawBody) {
|
|
49
|
+
jsonReply(res, 400, { error: `Invalid request body: ${(err as Error).message}` });
|
|
50
|
+
return true;
|
|
51
|
+
}
|
|
52
|
+
const fallbackId = extractSessionIdFromRaw(rawBody);
|
|
53
|
+
if (!fallbackId) {
|
|
54
|
+
jsonReply(res, 400, { error: `Invalid request body: ${(err as Error).message}` });
|
|
55
|
+
return true;
|
|
56
|
+
}
|
|
57
|
+
body = { session_id: fallbackId };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const sessionId = typeof body?.session_id === "string" ? body.session_id.trim() : "";
|
|
61
|
+
if (!sessionId) {
|
|
62
|
+
jsonReply(res, 400, { error: "session_id is required" });
|
|
63
|
+
return true;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const prompt = activePrompts.get(sessionId);
|
|
67
|
+
if (!prompt) {
|
|
68
|
+
jsonReply(res, 404, { error: "Session not found or not running" });
|
|
69
|
+
return true;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// 先发"卡住"提示消息给所有绑定的群聊
|
|
73
|
+
const chats = getChatsForSession(sessionId);
|
|
74
|
+
for (const chatId of chats) {
|
|
75
|
+
const platform = getPlatformForChat(chatId);
|
|
76
|
+
if (platform) {
|
|
77
|
+
await platform.sendText(chatId, "⚠️ Agent 检测到自己陷入了循环,正在结束生成…").catch(() => {});
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// 不丢弃缓存队列中的消息,让 runAgentSession 的 finally 块正常消费,
|
|
82
|
+
// 确保 stop-stuck-loop 结束后排队的消息仍能被正常处理。
|
|
83
|
+
|
|
84
|
+
const finalReply = typeof body?.final_reply === "string" ? body.final_reply.trim() : "";
|
|
85
|
+
|
|
86
|
+
// fire-and-forget:立即把 stream-state 标为 done(而非 stopped),
|
|
87
|
+
// 让 display loop 以"正常完成"而非"已停止"来渲染卡片和最终回复。
|
|
88
|
+
// 不设 prompt.stopped = true,这样 runAgentSession 的 finally 也会写 "done"。
|
|
89
|
+
void (async () => {
|
|
90
|
+
try {
|
|
91
|
+
const current = await readStreamState(sessionId);
|
|
92
|
+
if (!current) return;
|
|
93
|
+
if (current.status !== "running") return;
|
|
94
|
+
await writeStreamState({
|
|
95
|
+
...current,
|
|
96
|
+
status: "done",
|
|
97
|
+
stuckAt: Date.now(),
|
|
98
|
+
finalReply: finalReply ? current.finalReply + "\n\n" + finalReply : current.finalReply,
|
|
99
|
+
updatedAt: Date.now(),
|
|
100
|
+
});
|
|
101
|
+
} catch (err) {
|
|
102
|
+
console.warn(
|
|
103
|
+
`[${ts()}] [STUCK-LOOP] writeStreamState(done) failed for ${sessionId}: ${(err as Error).message}`,
|
|
104
|
+
);
|
|
105
|
+
}
|
|
106
|
+
})();
|
|
107
|
+
|
|
108
|
+
// 先关闭底层 SDK session,终止 CLI 子进程,然后再 abort 清理 adapter 层
|
|
109
|
+
prompt.closeSession?.();
|
|
110
|
+
|
|
111
|
+
// 强制杀死 CLI 子进程。controller.abort() 只在 for-await 收到下一条
|
|
112
|
+
// stream 消息时才被检测到——如果 agent 陷入无输出的计算循环,abort 信号
|
|
113
|
+
// 永远不会生效;SDK 的 session.close() 也不保证立即终止子进程。
|
|
114
|
+
if (prompt.processPid !== undefined) {
|
|
115
|
+
try {
|
|
116
|
+
process.kill(prompt.processPid);
|
|
117
|
+
} catch {
|
|
118
|
+
// 进程可能已退出,忽略错误
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// 不设 stopped 标记 → finally block 写 "done" → 卡片正常结束
|
|
123
|
+
prompt.controller.abort();
|
|
124
|
+
|
|
125
|
+
console.log(`[${ts()}] [STUCK-LOOP] Session ${sessionId} aborted as done (agent detected stuck loop, final_reply=${finalReply ? "yes" : "no"})`);
|
|
126
|
+
|
|
127
|
+
jsonReply(res, 200, { ok: true });
|
|
128
|
+
return true;
|
|
129
|
+
}
|