chatccc 0.2.175 → 0.2.176
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 +3 -3
- package/agent-prompts/claude_specific.md +45 -45
- package/agent-prompts/codex_specific.md +2 -2
- package/agent-prompts/cursor_specific.md +2 -2
- package/im-skills/feishu-skill/receive-send-file.md +63 -63
- package/im-skills/feishu-skill/receive-send-image.md +24 -24
- package/package.json +1 -1
- package/src/__tests__/cardkit.test.ts +60 -60
- package/src/__tests__/claude-adapter.test.ts +592 -592
- package/src/__tests__/config-reload.test.ts +18 -18
- package/src/__tests__/feishu-api.test.ts +60 -60
- package/src/__tests__/feishu-avatar.test.ts +129 -129
- package/src/__tests__/feishu-platform.test.ts +16 -16
- package/src/__tests__/format-message.test.ts +272 -272
- package/src/__tests__/orchestrator.test.ts +93 -93
- package/src/__tests__/privacy.test.ts +67 -12
- package/src/__tests__/web-ui.test.ts +92 -92
- package/src/adapters/claude-adapter.ts +566 -566
- package/src/adapters/claude-session-meta-store.ts +120 -120
- package/src/agent-stop-stuck.ts +129 -129
- package/src/cards.ts +4 -4
- package/src/feishu-api.ts +236 -236
- package/src/feishu-platform.ts +15 -15
- package/src/format-message.ts +213 -213
- package/src/litellm-proxy.ts +374 -374
- package/src/orchestrator.ts +112 -112
- package/src/privacy.ts +89 -39
- package/src/session-chat-binding.ts +6 -6
- package/src/sim-platform.ts +14 -14
- package/src/web-ui.ts +6 -6
|
@@ -1,120 +1,120 @@
|
|
|
1
|
-
// =============================================================================
|
|
2
|
-
// claude-session-meta-store.ts — Claude 会话 sessionId → meta 持久化映射
|
|
3
|
-
// =============================================================================
|
|
4
|
-
// 背景:Claude Agent SDK 的 getSessionInfo 可能因 cwd / 本地记录缺失而查不到。
|
|
5
|
-
// ChatCCC 额外维护 sessionId → { cwd, model } 映射作为展示与恢复兜底。
|
|
6
|
-
//
|
|
7
|
-
// 存储:
|
|
8
|
-
// 文件 state/claude-session-meta.json,结构:
|
|
9
|
-
// { "<sessionId>": { "cwd": "...", "model": "..." } }
|
|
10
|
-
//
|
|
11
|
-
// API 设计:
|
|
12
|
-
// set(sid, partial) → 部分合并写入;只更新非空字段,不会清空其他字段
|
|
13
|
-
// =============================================================================
|
|
14
|
-
|
|
15
|
-
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
16
|
-
import { dirname, join } from "node:path";
|
|
17
|
-
|
|
18
|
-
import { USER_DATA_DIR } from "../config.ts";
|
|
19
|
-
|
|
20
|
-
export const CLAUDE_SESSION_META_FILE = join(
|
|
21
|
-
USER_DATA_DIR,
|
|
22
|
-
"state",
|
|
23
|
-
"claude-session-meta.json",
|
|
24
|
-
);
|
|
25
|
-
|
|
26
|
-
export interface ClaudeSessionMeta {
|
|
27
|
-
cwd: string;
|
|
28
|
-
model?: string;
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
export interface ClaudeSessionMetaStore {
|
|
32
|
-
get(sessionId: string): Promise<ClaudeSessionMeta | undefined>;
|
|
33
|
-
set(sessionId: string, partial: Partial<ClaudeSessionMeta>): Promise<void>;
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
interface RawEntry {
|
|
37
|
-
cwd?: string;
|
|
38
|
-
model?: string;
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
function isNonEmptyString(v: unknown): v is string {
|
|
42
|
-
return typeof v === "string" && v.length > 0;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
function parseEntry(raw: unknown): RawEntry | null {
|
|
46
|
-
if (typeof raw === "string" && raw.length > 0) {
|
|
47
|
-
return { cwd: raw };
|
|
48
|
-
}
|
|
49
|
-
if (raw && typeof raw === "object" && !Array.isArray(raw)) {
|
|
50
|
-
const obj = raw as Record<string, unknown>;
|
|
51
|
-
const out: RawEntry = {};
|
|
52
|
-
if (isNonEmptyString(obj.cwd)) out.cwd = obj.cwd;
|
|
53
|
-
if (isNonEmptyString(obj.model)) out.model = obj.model;
|
|
54
|
-
return out;
|
|
55
|
-
}
|
|
56
|
-
return null;
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
export function createClaudeSessionMetaStore(
|
|
60
|
-
filePath: string = CLAUDE_SESSION_META_FILE,
|
|
61
|
-
): ClaudeSessionMetaStore {
|
|
62
|
-
let cache: Record<string, RawEntry> | null = null;
|
|
63
|
-
|
|
64
|
-
async function load(): Promise<Record<string, RawEntry>> {
|
|
65
|
-
if (cache) return cache;
|
|
66
|
-
try {
|
|
67
|
-
const raw = await readFile(filePath, "utf-8");
|
|
68
|
-
const parsed = JSON.parse(raw);
|
|
69
|
-
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
70
|
-
const out: Record<string, RawEntry> = {};
|
|
71
|
-
for (const [k, v] of Object.entries(parsed as Record<string, unknown>)) {
|
|
72
|
-
const entry = parseEntry(v);
|
|
73
|
-
if (entry) out[k] = entry;
|
|
74
|
-
}
|
|
75
|
-
cache = out;
|
|
76
|
-
return out;
|
|
77
|
-
}
|
|
78
|
-
} catch {
|
|
79
|
-
// 文件不存在 / JSON 损坏 → 视为空映射
|
|
80
|
-
}
|
|
81
|
-
cache = {};
|
|
82
|
-
return cache;
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
return {
|
|
86
|
-
async get(sessionId: string): Promise<ClaudeSessionMeta | undefined> {
|
|
87
|
-
const map = await load();
|
|
88
|
-
const entry = map[sessionId];
|
|
89
|
-
if (!entry || !isNonEmptyString(entry.cwd)) return undefined;
|
|
90
|
-
return entry.model
|
|
91
|
-
? { cwd: entry.cwd, model: entry.model }
|
|
92
|
-
: { cwd: entry.cwd };
|
|
93
|
-
},
|
|
94
|
-
|
|
95
|
-
async set(
|
|
96
|
-
sessionId: string,
|
|
97
|
-
partial: Partial<ClaudeSessionMeta>,
|
|
98
|
-
): Promise<void> {
|
|
99
|
-
const map = await load();
|
|
100
|
-
const existing = map[sessionId] ?? {};
|
|
101
|
-
const merged: RawEntry = { ...existing };
|
|
102
|
-
if (isNonEmptyString(partial.cwd)) merged.cwd = partial.cwd;
|
|
103
|
-
if (isNonEmptyString(partial.model)) merged.model = partial.model;
|
|
104
|
-
|
|
105
|
-
if (existing.cwd === merged.cwd && existing.model === merged.model) return;
|
|
106
|
-
|
|
107
|
-
map[sessionId] = merged;
|
|
108
|
-
try {
|
|
109
|
-
await mkdir(dirname(filePath), { recursive: true });
|
|
110
|
-
await writeFile(filePath, JSON.stringify(map, null, 2), "utf-8");
|
|
111
|
-
} catch (err) {
|
|
112
|
-
console.error(
|
|
113
|
-
`[claude-session-meta] failed to persist ${filePath}: ${(err as Error).message}`,
|
|
114
|
-
);
|
|
115
|
-
}
|
|
116
|
-
},
|
|
117
|
-
};
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
export const defaultClaudeSessionMetaStore = createClaudeSessionMetaStore();
|
|
1
|
+
// =============================================================================
|
|
2
|
+
// claude-session-meta-store.ts — Claude 会话 sessionId → meta 持久化映射
|
|
3
|
+
// =============================================================================
|
|
4
|
+
// 背景:Claude Agent SDK 的 getSessionInfo 可能因 cwd / 本地记录缺失而查不到。
|
|
5
|
+
// ChatCCC 额外维护 sessionId → { cwd, model } 映射作为展示与恢复兜底。
|
|
6
|
+
//
|
|
7
|
+
// 存储:
|
|
8
|
+
// 文件 state/claude-session-meta.json,结构:
|
|
9
|
+
// { "<sessionId>": { "cwd": "...", "model": "..." } }
|
|
10
|
+
//
|
|
11
|
+
// API 设计:
|
|
12
|
+
// set(sid, partial) → 部分合并写入;只更新非空字段,不会清空其他字段
|
|
13
|
+
// =============================================================================
|
|
14
|
+
|
|
15
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
16
|
+
import { dirname, join } from "node:path";
|
|
17
|
+
|
|
18
|
+
import { USER_DATA_DIR } from "../config.ts";
|
|
19
|
+
|
|
20
|
+
export const CLAUDE_SESSION_META_FILE = join(
|
|
21
|
+
USER_DATA_DIR,
|
|
22
|
+
"state",
|
|
23
|
+
"claude-session-meta.json",
|
|
24
|
+
);
|
|
25
|
+
|
|
26
|
+
export interface ClaudeSessionMeta {
|
|
27
|
+
cwd: string;
|
|
28
|
+
model?: string;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface ClaudeSessionMetaStore {
|
|
32
|
+
get(sessionId: string): Promise<ClaudeSessionMeta | undefined>;
|
|
33
|
+
set(sessionId: string, partial: Partial<ClaudeSessionMeta>): Promise<void>;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
interface RawEntry {
|
|
37
|
+
cwd?: string;
|
|
38
|
+
model?: string;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function isNonEmptyString(v: unknown): v is string {
|
|
42
|
+
return typeof v === "string" && v.length > 0;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function parseEntry(raw: unknown): RawEntry | null {
|
|
46
|
+
if (typeof raw === "string" && raw.length > 0) {
|
|
47
|
+
return { cwd: raw };
|
|
48
|
+
}
|
|
49
|
+
if (raw && typeof raw === "object" && !Array.isArray(raw)) {
|
|
50
|
+
const obj = raw as Record<string, unknown>;
|
|
51
|
+
const out: RawEntry = {};
|
|
52
|
+
if (isNonEmptyString(obj.cwd)) out.cwd = obj.cwd;
|
|
53
|
+
if (isNonEmptyString(obj.model)) out.model = obj.model;
|
|
54
|
+
return out;
|
|
55
|
+
}
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function createClaudeSessionMetaStore(
|
|
60
|
+
filePath: string = CLAUDE_SESSION_META_FILE,
|
|
61
|
+
): ClaudeSessionMetaStore {
|
|
62
|
+
let cache: Record<string, RawEntry> | null = null;
|
|
63
|
+
|
|
64
|
+
async function load(): Promise<Record<string, RawEntry>> {
|
|
65
|
+
if (cache) return cache;
|
|
66
|
+
try {
|
|
67
|
+
const raw = await readFile(filePath, "utf-8");
|
|
68
|
+
const parsed = JSON.parse(raw);
|
|
69
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
70
|
+
const out: Record<string, RawEntry> = {};
|
|
71
|
+
for (const [k, v] of Object.entries(parsed as Record<string, unknown>)) {
|
|
72
|
+
const entry = parseEntry(v);
|
|
73
|
+
if (entry) out[k] = entry;
|
|
74
|
+
}
|
|
75
|
+
cache = out;
|
|
76
|
+
return out;
|
|
77
|
+
}
|
|
78
|
+
} catch {
|
|
79
|
+
// 文件不存在 / JSON 损坏 → 视为空映射
|
|
80
|
+
}
|
|
81
|
+
cache = {};
|
|
82
|
+
return cache;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
return {
|
|
86
|
+
async get(sessionId: string): Promise<ClaudeSessionMeta | undefined> {
|
|
87
|
+
const map = await load();
|
|
88
|
+
const entry = map[sessionId];
|
|
89
|
+
if (!entry || !isNonEmptyString(entry.cwd)) return undefined;
|
|
90
|
+
return entry.model
|
|
91
|
+
? { cwd: entry.cwd, model: entry.model }
|
|
92
|
+
: { cwd: entry.cwd };
|
|
93
|
+
},
|
|
94
|
+
|
|
95
|
+
async set(
|
|
96
|
+
sessionId: string,
|
|
97
|
+
partial: Partial<ClaudeSessionMeta>,
|
|
98
|
+
): Promise<void> {
|
|
99
|
+
const map = await load();
|
|
100
|
+
const existing = map[sessionId] ?? {};
|
|
101
|
+
const merged: RawEntry = { ...existing };
|
|
102
|
+
if (isNonEmptyString(partial.cwd)) merged.cwd = partial.cwd;
|
|
103
|
+
if (isNonEmptyString(partial.model)) merged.model = partial.model;
|
|
104
|
+
|
|
105
|
+
if (existing.cwd === merged.cwd && existing.model === merged.model) return;
|
|
106
|
+
|
|
107
|
+
map[sessionId] = merged;
|
|
108
|
+
try {
|
|
109
|
+
await mkdir(dirname(filePath), { recursive: true });
|
|
110
|
+
await writeFile(filePath, JSON.stringify(map, null, 2), "utf-8");
|
|
111
|
+
} catch (err) {
|
|
112
|
+
console.error(
|
|
113
|
+
`[claude-session-meta] failed to persist ${filePath}: ${(err as Error).message}`,
|
|
114
|
+
);
|
|
115
|
+
}
|
|
116
|
+
},
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export const defaultClaudeSessionMetaStore = createClaudeSessionMetaStore();
|
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
|
+
}
|
package/src/cards.ts
CHANGED
|
@@ -133,10 +133,10 @@ export function buildHelpCard(
|
|
|
133
133
|
"发送 **/new cursor** 创建新 Cursor 会话",
|
|
134
134
|
"发送 **/new codex** 创建新 Codex 会话",
|
|
135
135
|
"发送 **/newh** 重置当前会话(沿用当前工作目录,不切换)",
|
|
136
|
-
"发送 **/plan** 以规划模式提问(只读,不执行写操作)",
|
|
137
|
-
"发送 **/ask** 以问答模式提问(只读,不执行写操作)",
|
|
138
|
-
"发送 **/usage** 查看 Codex 5h 和周用量",
|
|
139
|
-
"发送 **/restart** 重启 ChatCCC 进程",
|
|
136
|
+
"发送 **/plan** 以规划模式提问(只读,不执行写操作)",
|
|
137
|
+
"发送 **/ask** 以问答模式提问(只读,不执行写操作)",
|
|
138
|
+
"发送 **/usage** 查看 Codex 5h 和周用量",
|
|
139
|
+
"发送 **/restart** 重启 ChatCCC 进程",
|
|
140
140
|
"发送 **/updateg** 更新并重启(仅 npm 全局安装可用)",
|
|
141
141
|
].join("\n");
|
|
142
142
|
return JSON.stringify({
|