chatccc 0.2.135 → 0.2.137
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 +4 -4
- package/agent-prompts/claude_specific.md +53 -51
- package/agent-prompts/codex_specific.md +1 -0
- package/agent-prompts/cursor_specific.md +1 -0
- package/config.sample.json +1 -1
- package/package.json +1 -1
- package/src/__tests__/config-reload.test.ts +9 -9
- package/src/__tests__/feishu-platform.test.ts +4 -1
- package/src/__tests__/format-message.test.ts +273 -0
- package/src/adapters/claude-adapter.ts +1 -1
- package/src/adapters/codex-adapter.ts +38 -1
- package/src/adapters/cursor-adapter.ts +38 -1
- package/src/cards.ts +2 -0
- package/src/config.ts +4 -4
- package/src/feishu-api.ts +50 -0
- package/src/feishu-platform.ts +5 -0
- package/src/format-message.ts +214 -0
- package/src/index.ts +1 -78
- package/src/sim-platform.ts +5 -0
- package/src/web-ui.ts +6 -6
package/README.md
CHANGED
|
@@ -205,7 +205,7 @@ ChatCCC 只负责把聊天消息转给本地 AI 工具,不捆绑这些 CLI。
|
|
|
205
205
|
|
|
206
206
|
#### Claude Code
|
|
207
207
|
|
|
208
|
-
本机完成 Claude Code 登录后即可使用。ChatCCC 通过 Anthropic Claude Agent SDK 调用 Claude Code 能力,同时支持官方和第三方 Anthropic 兼容 API:使用官方服务无需额外配置,使用第三方 API 则填写 `claude.apiKey` 和 `claude.baseUrl`。`claude.model`、`claude.subagentModel`、`claude.effort`、`claude.apiKey`、`claude.baseUrl` 均为选填;`claude.maxTurn` 控制每次对话的最大轮数(默认
|
|
208
|
+
本机完成 Claude Code 登录后即可使用。ChatCCC 通过 Anthropic Claude Agent SDK 调用 Claude Code 能力,同时支持官方和第三方 Anthropic 兼容 API:使用官方服务无需额外配置,使用第三方 API 则填写 `claude.apiKey` 和 `claude.baseUrl`。`claude.model`、`claude.subagentModel`、`claude.effort`、`claude.apiKey`、`claude.baseUrl` 均为选填;`claude.maxTurn` 控制每次对话的最大轮数(默认 0,即无限制)。填写后会把对应配置传给 Claude Agent SDK;留空则以 `~/.claude/settings.json` 为准。
|
|
209
209
|
|
|
210
210
|
#### Cursor Agent CLI
|
|
211
211
|
|
|
@@ -283,9 +283,9 @@ Codex 的默认模型和推理强度可继续由 `~/.codex/config.toml` 管理
|
|
|
283
283
|
| `*.enabled` | 是否启用对应 AI Agent |
|
|
284
284
|
| `*.defaultAgent` | `/new` 未指定 Agent 时使用哪个工具 |
|
|
285
285
|
| `cursor.path` / `codex.path` | CLI 可执行文件路径;留空时自动探测或使用 PATH |
|
|
286
|
-
| `claude.model` / `claude.subagentModel` / `claude.effort` | 选填;设置后传给 Claude Agent SDK,留空以 `~/.claude/settings.json` 为准 |
|
|
287
|
-
| `claude.apiKey` / `claude.baseUrl` | 选填;设置后传给 Claude Agent SDK,留空以 `~/.claude/settings.json` 为准 |
|
|
288
|
-
| `claude.maxTurn` | 选填;Claude 最大对话轮数,默认
|
|
286
|
+
| `claude.model` / `claude.subagentModel` / `claude.effort` | 选填;设置后传给 Claude Agent SDK,留空以 `~/.claude/settings.json` 为准 |
|
|
287
|
+
| `claude.apiKey` / `claude.baseUrl` | 选填;设置后传给 Claude Agent SDK,留空以 `~/.claude/settings.json` 为准 |
|
|
288
|
+
| `claude.maxTurn` | 选填;Claude 最大对话轮数,默认 0(无限制),可在 Web UI 编辑 |
|
|
289
289
|
|
|
290
290
|
> 当前 ChatCCC 以 `bypassPermissions` 模式运行,会跳过 Agent 操作确认。请只在可信环境中使用。
|
|
291
291
|
|
|
@@ -1,53 +1,55 @@
|
|
|
1
|
-
# Claude-Specific Injection Prompt
|
|
2
|
-
|
|
1
|
+
# Claude-Specific Injection Prompt
|
|
2
|
+
|
|
3
3
|
Use this prompt as the Claude Agent SDK injection prompt for this project.
|
|
4
|
-
|
|
5
|
-
Project workspace:
|
|
6
|
-
|
|
7
|
-
```text
|
|
8
|
-
f:\users\weizhangjian\feishuclauderprivate
|
|
9
|
-
```
|
|
10
|
-
|
|
11
|
-
## Repeated Successful Command Guard
|
|
12
|
-
|
|
4
|
+
|
|
5
|
+
Project workspace:
|
|
6
|
+
|
|
7
|
+
```text
|
|
8
|
+
f:\users\weizhangjian\feishuclauderprivate
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Repeated Successful Command Guard
|
|
12
|
+
|
|
13
13
|
When working in this project through Claude Agent SDK, repeated successful shell commands are a completion signal, not a reason to keep using tools.
|
|
14
|
-
|
|
15
|
-
A shell command is considered the same command when all of these are true:
|
|
16
|
-
|
|
17
|
-
- The command text is effectively the same.
|
|
18
|
-
- The working directory is the same.
|
|
19
|
-
- The current task goal has not changed.
|
|
20
|
-
- There is no new user input that changes the task.
|
|
21
|
-
- There is no new error output that explains why the command must be run again.
|
|
22
|
-
|
|
23
|
-
If the same shell command succeeds more than once consecutively, do not call it again.
|
|
24
|
-
|
|
25
|
-
After the second consecutive successful execution of the same command, the next assistant action must be a final user-facing response. Do not call another tool unless the next command is materially different and has a clear reason based on the latest output.
|
|
26
|
-
|
|
27
|
-
This guard applies to all shell commands, including but not limited to:
|
|
28
|
-
|
|
29
|
-
- test commands
|
|
30
|
-
- build commands
|
|
31
|
-
- git commands
|
|
32
|
-
- install commands
|
|
33
|
-
- formatting commands
|
|
34
|
-
- project scripts
|
|
35
|
-
- status or inspection commands
|
|
36
|
-
|
|
37
|
-
Do not "verify one more time" by repeating the same successful command. If verification is needed, use a different command that checks a different fact, or explain the current result to the user.
|
|
38
|
-
|
|
39
|
-
If you notice that you are about to repeat a successful command with the same arguments, stop using tools and respond to the user with the current result.
|
|
40
|
-
|
|
41
|
-
If you produce or observe text like "I'm stuck in a loop", do not call any more tools. Immediately send the final user-facing response explaining:
|
|
42
|
-
|
|
43
|
-
- what has completed,
|
|
44
|
-
- what is still uncertain, if anything,
|
|
45
|
-
- and what the user can do next, if action is needed.
|
|
46
|
-
|
|
47
|
-
## Hard Stop Rule
|
|
48
|
-
|
|
49
|
-
Never execute the same successful shell command three times for the same task in this project.
|
|
50
|
-
|
|
51
|
-
If the same command has already succeeded twice in a row, the next assistant action must be a final response to the user, not another tool call.
|
|
52
|
-
|
|
53
|
-
Successful repeated command execution is a terminal condition. Prefer a concise final response over further tool calls.
|
|
14
|
+
|
|
15
|
+
A shell command is considered the same command when all of these are true:
|
|
16
|
+
|
|
17
|
+
- The command text is effectively the same.
|
|
18
|
+
- The working directory is the same.
|
|
19
|
+
- The current task goal has not changed.
|
|
20
|
+
- There is no new user input that changes the task.
|
|
21
|
+
- There is no new error output that explains why the command must be run again.
|
|
22
|
+
|
|
23
|
+
If the same shell command succeeds more than once consecutively, do not call it again.
|
|
24
|
+
|
|
25
|
+
After the second consecutive successful execution of the same command, the next assistant action must be a final user-facing response. Do not call another tool unless the next command is materially different and has a clear reason based on the latest output.
|
|
26
|
+
|
|
27
|
+
This guard applies to all shell commands, including but not limited to:
|
|
28
|
+
|
|
29
|
+
- test commands
|
|
30
|
+
- build commands
|
|
31
|
+
- git commands
|
|
32
|
+
- install commands
|
|
33
|
+
- formatting commands
|
|
34
|
+
- project scripts
|
|
35
|
+
- status or inspection commands
|
|
36
|
+
|
|
37
|
+
Do not "verify one more time" by repeating the same successful command. If verification is needed, use a different command that checks a different fact, or explain the current result to the user.
|
|
38
|
+
|
|
39
|
+
If you notice that you are about to repeat a successful command with the same arguments, stop using tools and respond to the user with the current result.
|
|
40
|
+
|
|
41
|
+
If you produce or observe text like "I'm stuck in a loop", do not call any more tools. Immediately send the final user-facing response explaining:
|
|
42
|
+
|
|
43
|
+
- what has completed,
|
|
44
|
+
- what is still uncertain, if anything,
|
|
45
|
+
- and what the user can do next, if action is needed.
|
|
46
|
+
|
|
47
|
+
## Hard Stop Rule
|
|
48
|
+
|
|
49
|
+
Never execute the same successful shell command three times for the same task in this project.
|
|
50
|
+
|
|
51
|
+
If the same command has already succeeded twice in a row, the next assistant action must be a final response to the user, not another tool call.
|
|
52
|
+
|
|
53
|
+
Successful repeated command execution is a terminal condition. Prefer a concise final response over further tool calls.
|
|
54
|
+
|
|
55
|
+
如果计划写好了等待你的审阅,将计划文件通过当前聊天软件发给用户
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
如果计划写好了等待你的审阅,将计划文件通过当前聊天软件发给用户
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
如果计划写好了等待你的审阅,将计划文件通过当前聊天软件发给用户
|
package/config.sample.json
CHANGED
package/package.json
CHANGED
|
@@ -47,10 +47,10 @@ const baseAppConfig: AppConfig = {
|
|
|
47
47
|
defaultAgent: true,
|
|
48
48
|
model: "initial-model",
|
|
49
49
|
subagentModel: "initial-subagent-model",
|
|
50
|
-
effort: "initial-effort",
|
|
51
|
-
apiKey: "",
|
|
52
|
-
baseUrl: "",
|
|
53
|
-
maxTurn:
|
|
50
|
+
effort: "initial-effort",
|
|
51
|
+
apiKey: "",
|
|
52
|
+
baseUrl: "",
|
|
53
|
+
maxTurn: 0,
|
|
54
54
|
},
|
|
55
55
|
cursor: { enabled: true, defaultAgent: false, path: "/initial/cursor", model: "initial-cursor-model" },
|
|
56
56
|
codex: { enabled: true, defaultAgent: false, path: "/initial/codex", model: "initial-codex-model", effort: "initial-codex-effort" },
|
|
@@ -89,11 +89,11 @@ describe("applyLoadedConfig — 刷新 export let 常量", () => {
|
|
|
89
89
|
defaultAgent: true,
|
|
90
90
|
model: "claude-sonnet-4-6",
|
|
91
91
|
subagentModel: "claude-haiku-4-5-20251001",
|
|
92
|
-
effort: "high",
|
|
93
|
-
apiKey: "sk-test",
|
|
94
|
-
baseUrl: "https://api.example.com",
|
|
95
|
-
maxTurn:
|
|
96
|
-
},
|
|
92
|
+
effort: "high",
|
|
93
|
+
apiKey: "sk-test",
|
|
94
|
+
baseUrl: "https://api.example.com",
|
|
95
|
+
maxTurn: 0,
|
|
96
|
+
},
|
|
97
97
|
});
|
|
98
98
|
|
|
99
99
|
expect(CLAUDE_MODEL).toBe("claude-sonnet-4-6");
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { describe, it, expect, beforeAll, afterAll } from "vitest";
|
|
2
|
-
import { getPlatform, setPlatform, getTenantAccessToken, getChatInfo, createGroupChat, updateChatInfo, sendTextReply, sendCardReply, sendRawCard, sendPostMessage, extractSessionInfo, formatDelayNotice, reportPermissionResults, verifyAllPermissions, addReaction, recallMessage, updateCardMessage, setChatAvatar, disbandChat, sendRestartCard } from "../feishu-platform.ts";
|
|
2
|
+
import { getPlatform, setPlatform, getTenantAccessToken, getChatInfo, createGroupChat, updateChatInfo, sendTextReply, sendCardReply, sendRawCard, sendPostMessage, extractSessionInfo, formatDelayNotice, reportPermissionResults, verifyAllPermissions, addReaction, recallMessage, updateCardMessage, setChatAvatar, disbandChat, sendRestartCard, getMergeForwardMessages } from "../feishu-platform.ts";
|
|
3
3
|
import type { FeishuPlatform } from "../feishu-platform.ts";
|
|
4
4
|
|
|
5
5
|
const realPlatform = getPlatform();
|
|
@@ -35,6 +35,7 @@ describe("feishu-platform", () => {
|
|
|
35
35
|
extractSessionId: realPlatform.extractSessionId,
|
|
36
36
|
formatDelayNotice: realPlatform.formatDelayNotice,
|
|
37
37
|
sendRestartCard: async () => {},
|
|
38
|
+
getMergeForwardMessages: async () => [],
|
|
38
39
|
};
|
|
39
40
|
|
|
40
41
|
setPlatform(mock);
|
|
@@ -45,6 +46,8 @@ describe("feishu-platform", () => {
|
|
|
45
46
|
expect(await getChatInfo("t", "mock_chat")).toEqual({ name: "x", description: "y" });
|
|
46
47
|
const perms = await verifyAllPermissions("t");
|
|
47
48
|
expect(perms).toEqual([]);
|
|
49
|
+
const mergeMsgs = await getMergeForwardMessages("t", "om_test");
|
|
50
|
+
expect(mergeMsgs).toEqual([]);
|
|
48
51
|
} finally {
|
|
49
52
|
// 恢复到真实实现,避免影响后续测试
|
|
50
53
|
setPlatform(realPlatform);
|
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
import { describe, it, expect, vi, beforeEach } from "vitest";
|
|
2
|
+
|
|
3
|
+
// Mock feishu-platform 以控制 API 行为
|
|
4
|
+
const mockGetTenantAccessToken = vi.fn();
|
|
5
|
+
const mockGetOrDownloadImage = vi.fn();
|
|
6
|
+
const mockGetMergeForwardMessages = vi.fn();
|
|
7
|
+
|
|
8
|
+
vi.mock("../feishu-platform.ts", () => ({
|
|
9
|
+
getTenantAccessToken: (...args: unknown[]) => mockGetTenantAccessToken(...args),
|
|
10
|
+
getOrDownloadImage: (...args: unknown[]) => mockGetOrDownloadImage(...args),
|
|
11
|
+
getMergeForwardMessages: (...args: unknown[]) => mockGetMergeForwardMessages(...args),
|
|
12
|
+
}));
|
|
13
|
+
|
|
14
|
+
import { formatMessageContent, formatPostContent, formatMergeForward } from "../format-message.ts";
|
|
15
|
+
|
|
16
|
+
describe("formatMessageContent", () => {
|
|
17
|
+
beforeEach(() => {
|
|
18
|
+
vi.clearAllMocks();
|
|
19
|
+
mockGetTenantAccessToken.mockResolvedValue("mock_token");
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
it("解析文本消息", async () => {
|
|
23
|
+
const result = await formatMessageContent({
|
|
24
|
+
message_type: "text",
|
|
25
|
+
content: JSON.stringify({ text: "hello world" }),
|
|
26
|
+
});
|
|
27
|
+
expect(result).toBe("hello world");
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
it("去除 HTML 标签", async () => {
|
|
31
|
+
const result = await formatMessageContent({
|
|
32
|
+
message_type: "text",
|
|
33
|
+
content: JSON.stringify({ text: "<p>你好</p><br/>世界" }),
|
|
34
|
+
});
|
|
35
|
+
expect(result).toBe("你好\n世界");
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
it("解析 post 消息", async () => {
|
|
39
|
+
const result = await formatMessageContent({
|
|
40
|
+
message_type: "post",
|
|
41
|
+
content: JSON.stringify({
|
|
42
|
+
content: [[{ tag: "text", text: "第一条消息" }]],
|
|
43
|
+
}),
|
|
44
|
+
});
|
|
45
|
+
expect(result).toBe("第一条消息");
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it("解析 post 中的代码块", async () => {
|
|
49
|
+
const result = await formatMessageContent({
|
|
50
|
+
message_type: "post",
|
|
51
|
+
content: JSON.stringify({
|
|
52
|
+
content: [[{ tag: "code_block", language: "ts", text: "const x = 1;" }]],
|
|
53
|
+
}),
|
|
54
|
+
});
|
|
55
|
+
expect(result).toBe("```ts\nconst x = 1;\n```");
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it("解析 media 类型返回元数据", async () => {
|
|
59
|
+
const result = await formatMessageContent({
|
|
60
|
+
message_id: "om_test",
|
|
61
|
+
message_type: "media",
|
|
62
|
+
content: JSON.stringify({ file_key: "fk_001", file_name: "test.mp4" }),
|
|
63
|
+
});
|
|
64
|
+
expect(result).toContain("[视频]");
|
|
65
|
+
expect(result).toContain("om_test");
|
|
66
|
+
expect(result).toContain("fk_001");
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it("解析 file 类型返回元数据", async () => {
|
|
70
|
+
const result = await formatMessageContent({
|
|
71
|
+
message_id: "om_test",
|
|
72
|
+
message_type: "file",
|
|
73
|
+
content: JSON.stringify({ file_key: "fk_001", file_name: "doc.pdf" }),
|
|
74
|
+
});
|
|
75
|
+
expect(result).toContain("[文件]");
|
|
76
|
+
expect(result).toContain("om_test");
|
|
77
|
+
expect(result).toContain("fk_001");
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
it("未知类型返回原始 JSON", async () => {
|
|
81
|
+
const result = await formatMessageContent({
|
|
82
|
+
message_type: "sticker",
|
|
83
|
+
content: JSON.stringify({ sticker_id: "stk_001" }),
|
|
84
|
+
});
|
|
85
|
+
expect(result).toBe(JSON.stringify({ sticker_id: "stk_001" }));
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
it("content 为空时返回空字符串", async () => {
|
|
89
|
+
const result = await formatMessageContent({
|
|
90
|
+
message_type: "text",
|
|
91
|
+
});
|
|
92
|
+
expect(result).toBe("");
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
it("content JSON 解析失败返回空字符串", async () => {
|
|
96
|
+
const result = await formatMessageContent({
|
|
97
|
+
message_type: "text",
|
|
98
|
+
content: "not valid json",
|
|
99
|
+
});
|
|
100
|
+
expect(result).toBe("");
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
it("merge_forward 的 content 为空时仍能走 API 路径", async () => {
|
|
104
|
+
mockGetMergeForwardMessages.mockResolvedValue([
|
|
105
|
+
{ message_id: "om_root" },
|
|
106
|
+
{
|
|
107
|
+
message_id: "om_1",
|
|
108
|
+
msg_type: "text",
|
|
109
|
+
body: { content: JSON.stringify({ text: "hello" }) },
|
|
110
|
+
sender: { id: "ou_001" },
|
|
111
|
+
upper_message_id: "om_root",
|
|
112
|
+
},
|
|
113
|
+
]);
|
|
114
|
+
|
|
115
|
+
const result = await formatMessageContent({
|
|
116
|
+
message_id: "om_mf",
|
|
117
|
+
message_type: "merge_forward",
|
|
118
|
+
content: "", // 空字符串
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
expect(result).toContain("[合并转发: 聊天记录]");
|
|
122
|
+
expect(result).toContain("hello");
|
|
123
|
+
});
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
describe("formatMergeForward", () => {
|
|
127
|
+
beforeEach(() => {
|
|
128
|
+
vi.clearAllMocks();
|
|
129
|
+
mockGetTenantAccessToken.mockResolvedValue("mock_token");
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
const preview = [
|
|
133
|
+
{
|
|
134
|
+
content: "第一条消息",
|
|
135
|
+
sender: { id: "ou_001", name: "张三", avatar_url: "" },
|
|
136
|
+
},
|
|
137
|
+
{
|
|
138
|
+
content: "第二条消息",
|
|
139
|
+
sender: { id: "ou_002", name: "李四", avatar_url: "" },
|
|
140
|
+
},
|
|
141
|
+
];
|
|
142
|
+
|
|
143
|
+
it("API 成功:格式化子消息列表", async () => {
|
|
144
|
+
mockGetMergeForwardMessages.mockResolvedValue([
|
|
145
|
+
// 第一个 item: 合并转发消息自身(无 upper_message_id),会被跳过
|
|
146
|
+
{ message_id: "om_root", msg_type: "merge_forward", body: { content: "{}" } },
|
|
147
|
+
{
|
|
148
|
+
message_id: "om_1",
|
|
149
|
+
msg_type: "text",
|
|
150
|
+
body: { content: JSON.stringify({ text: "你好" }) },
|
|
151
|
+
sender: { id: "ou_001" },
|
|
152
|
+
upper_message_id: "om_root",
|
|
153
|
+
},
|
|
154
|
+
{
|
|
155
|
+
message_id: "om_2",
|
|
156
|
+
msg_type: "text",
|
|
157
|
+
body: { content: JSON.stringify({ text: "在吗" }) },
|
|
158
|
+
sender: { id: "ou_002" },
|
|
159
|
+
upper_message_id: "om_root",
|
|
160
|
+
},
|
|
161
|
+
]);
|
|
162
|
+
|
|
163
|
+
const result = await formatMergeForward("om_mf", {
|
|
164
|
+
title: "聊天记录",
|
|
165
|
+
preview,
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
expect(result).toContain("[合并转发: 聊天记录]");
|
|
169
|
+
expect(result).toContain("张三: 你好");
|
|
170
|
+
expect(result).toContain("李四: 在吗");
|
|
171
|
+
expect(mockGetMergeForwardMessages).toHaveBeenCalledWith("mock_token", "om_mf");
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
it("API 成功:跳过 merge_forward 自身 item", async () => {
|
|
175
|
+
mockGetMergeForwardMessages.mockResolvedValue([
|
|
176
|
+
{ message_id: "om_root", msg_type: "merge_forward", body: { content: "{}" } },
|
|
177
|
+
]);
|
|
178
|
+
|
|
179
|
+
const result = await formatMergeForward("om_mf", {
|
|
180
|
+
title: "空聊天记录",
|
|
181
|
+
preview: [],
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
// API 返回了 items 但只有根消息本身(无子消息),应该降级到 preview(也为空)
|
|
185
|
+
// → 返回原始 JSON
|
|
186
|
+
expect(result).toBe(JSON.stringify({ title: "空聊天记录", preview: [] }));
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
it("API 失败:降级使用 preview", async () => {
|
|
190
|
+
mockGetMergeForwardMessages.mockRejectedValue(new Error("permission denied"));
|
|
191
|
+
|
|
192
|
+
const result = await formatMergeForward("om_mf", {
|
|
193
|
+
title: "聊天记录",
|
|
194
|
+
preview,
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
expect(result).toContain("[合并转发: 聊天记录]");
|
|
198
|
+
expect(result).toContain("张三: 第一条消息");
|
|
199
|
+
expect(result).toContain("李四: 第二条消息");
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
it("API 失败 + preview 为空:返回原始 JSON", async () => {
|
|
203
|
+
mockGetMergeForwardMessages.mockRejectedValue(new Error("permission denied"));
|
|
204
|
+
|
|
205
|
+
const result = await formatMergeForward("om_mf", {
|
|
206
|
+
title: "聊天记录",
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
expect(result).toBe(JSON.stringify({ title: "聊天记录" }));
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
it("chat_name 出现在标题中", async () => {
|
|
213
|
+
mockGetMergeForwardMessages.mockRejectedValue(new Error("no permission"));
|
|
214
|
+
|
|
215
|
+
const result = await formatMergeForward("om_mf", {
|
|
216
|
+
title: "聊天记录",
|
|
217
|
+
chat_name: "技术群",
|
|
218
|
+
preview,
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
expect(result).toContain("[合并转发: 聊天记录 (技术群)]");
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
it("发送者名称从 preview 映射到 API items", async () => {
|
|
225
|
+
// API 返回的 sender 只有 id 没有 name,应该从 preview 映射名称
|
|
226
|
+
mockGetMergeForwardMessages.mockResolvedValue([
|
|
227
|
+
{ message_id: "om_root" },
|
|
228
|
+
{
|
|
229
|
+
message_id: "om_1",
|
|
230
|
+
msg_type: "text",
|
|
231
|
+
body: { content: JSON.stringify({ text: "测试" }) },
|
|
232
|
+
sender: { id: "ou_001" }, // 只有 id,无 name
|
|
233
|
+
upper_message_id: "om_root",
|
|
234
|
+
},
|
|
235
|
+
]);
|
|
236
|
+
|
|
237
|
+
const result = await formatMergeForward("om_mf", {
|
|
238
|
+
title: "测试",
|
|
239
|
+
preview: [{ content: "", sender: { id: "ou_001", name: "张三" } }],
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
expect(result).toContain("张三: 测试");
|
|
243
|
+
});
|
|
244
|
+
|
|
245
|
+
it("preview 发送者为空时使用默认名称", async () => {
|
|
246
|
+
mockGetMergeForwardMessages.mockRejectedValue(new Error("fail"));
|
|
247
|
+
|
|
248
|
+
const result = await formatMergeForward("om_mf", {
|
|
249
|
+
title: "测试",
|
|
250
|
+
preview: [{ content: "消息内容" }],
|
|
251
|
+
});
|
|
252
|
+
|
|
253
|
+
expect(result).toContain("未知用户: 消息内容");
|
|
254
|
+
});
|
|
255
|
+
|
|
256
|
+
it("嵌套合并转发递归深度限制", async () => {
|
|
257
|
+
// MAX_DEPTH=3,从 depth=3 开始调用应立即返回
|
|
258
|
+
const result = await formatMergeForward("om_mf", {}, 3);
|
|
259
|
+
expect(result).toBe("[合并转发: 超出最大嵌套深度 3]");
|
|
260
|
+
});
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
describe("formatPostContent", () => {
|
|
264
|
+
it("返回空段落数组时为空字符串", () => {
|
|
265
|
+
const result = formatPostContent({});
|
|
266
|
+
expect(result).toBe("");
|
|
267
|
+
});
|
|
268
|
+
|
|
269
|
+
it("跳过非数组元素", () => {
|
|
270
|
+
const result = formatPostContent({ content: [null, undefined, "string"] });
|
|
271
|
+
expect(result).toBe("");
|
|
272
|
+
});
|
|
273
|
+
});
|
|
@@ -327,7 +327,7 @@ class ClaudeAdapter implements ToolAdapter {
|
|
|
327
327
|
this.baseUrl = options.baseUrl;
|
|
328
328
|
this.isEmpty = options.isEmpty;
|
|
329
329
|
this.metaStore = options.metaStore ?? defaultClaudeSessionMetaStore;
|
|
330
|
-
this.maxTurn = options.maxTurn ??
|
|
330
|
+
this.maxTurn = options.maxTurn ?? 0;
|
|
331
331
|
}
|
|
332
332
|
|
|
333
333
|
async createSession(cwd: string): Promise<CreateSessionResult> {
|
|
@@ -8,8 +8,11 @@
|
|
|
8
8
|
// =============================================================================
|
|
9
9
|
|
|
10
10
|
import { spawn, type ChildProcess } from "node:child_process";
|
|
11
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
12
|
+
import { dirname, join } from "node:path";
|
|
11
13
|
import { createInterface } from "node:readline";
|
|
12
14
|
import { randomUUID } from "node:crypto";
|
|
15
|
+
import { fileURLToPath } from "node:url";
|
|
13
16
|
|
|
14
17
|
import type {
|
|
15
18
|
ToolAdapter,
|
|
@@ -26,6 +29,40 @@ import {
|
|
|
26
29
|
import { killProcessTree } from "./proc-tree-kill.ts";
|
|
27
30
|
import { config } from "../config.ts";
|
|
28
31
|
|
|
32
|
+
// ---------------------------------------------------------------------------
|
|
33
|
+
// 特殊注入提示
|
|
34
|
+
// ---------------------------------------------------------------------------
|
|
35
|
+
|
|
36
|
+
const PROJECT_ROOT = dirname(dirname(dirname(fileURLToPath(import.meta.url))));
|
|
37
|
+
const CODEX_SPECIFIC_PROMPT_PATH = join(
|
|
38
|
+
PROJECT_ROOT,
|
|
39
|
+
"agent-prompts",
|
|
40
|
+
"codex_specific.md",
|
|
41
|
+
);
|
|
42
|
+
|
|
43
|
+
function readCodexSpecificInjectionPrompt(): string | null {
|
|
44
|
+
try {
|
|
45
|
+
if (!existsSync(CODEX_SPECIFIC_PROMPT_PATH)) return null;
|
|
46
|
+
const prompt = readFileSync(CODEX_SPECIFIC_PROMPT_PATH, "utf-8").trim();
|
|
47
|
+
return prompt.length > 0 ? prompt : null;
|
|
48
|
+
} catch {
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function buildCodexPromptText(userText: string): string {
|
|
54
|
+
const prompt = readCodexSpecificInjectionPrompt();
|
|
55
|
+
if (!prompt) return userText;
|
|
56
|
+
|
|
57
|
+
return [
|
|
58
|
+
"[ChatCCC Codex-specific injection prompt]",
|
|
59
|
+
prompt,
|
|
60
|
+
"[/ChatCCC Codex-specific injection prompt]",
|
|
61
|
+
"",
|
|
62
|
+
userText,
|
|
63
|
+
].join("\n");
|
|
64
|
+
}
|
|
65
|
+
|
|
29
66
|
// ---------------------------------------------------------------------------
|
|
30
67
|
// 命令与参数
|
|
31
68
|
// ---------------------------------------------------------------------------
|
|
@@ -254,7 +291,7 @@ class CodexAdapter implements ToolAdapter {
|
|
|
254
291
|
? [...CODEX_BASE_ARGS, "-C", cwd, "-"]
|
|
255
292
|
: [...CODEX_BASE_ARGS, "resume", threadId, "-"];
|
|
256
293
|
|
|
257
|
-
const proc = spawnCodex(args, cwd, userText, this.modelOverride);
|
|
294
|
+
const proc = spawnCodex(args, cwd, buildCodexPromptText(userText), this.modelOverride);
|
|
258
295
|
if (proc.pid !== undefined) options?.onProcessStart?.({ pid: proc.pid });
|
|
259
296
|
|
|
260
297
|
// 关键:spawn 用了 shell:true,proc.pid 指向的是壳进程(cmd.exe / sh)。
|
|
@@ -6,7 +6,10 @@
|
|
|
6
6
|
// =============================================================================
|
|
7
7
|
|
|
8
8
|
import { spawn, type ChildProcess } from "node:child_process";
|
|
9
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
10
|
+
import { dirname, join } from "node:path";
|
|
9
11
|
import { createInterface } from "node:readline";
|
|
12
|
+
import { fileURLToPath } from "node:url";
|
|
10
13
|
|
|
11
14
|
import type {
|
|
12
15
|
ToolAdapter,
|
|
@@ -23,6 +26,40 @@ import {
|
|
|
23
26
|
} from "./cursor-session-meta-store.ts";
|
|
24
27
|
import { killProcessTree } from "./proc-tree-kill.ts";
|
|
25
28
|
|
|
29
|
+
// ---------------------------------------------------------------------------
|
|
30
|
+
// 特殊注入提示
|
|
31
|
+
// ---------------------------------------------------------------------------
|
|
32
|
+
|
|
33
|
+
const PROJECT_ROOT = dirname(dirname(dirname(fileURLToPath(import.meta.url))));
|
|
34
|
+
const CURSOR_SPECIFIC_PROMPT_PATH = join(
|
|
35
|
+
PROJECT_ROOT,
|
|
36
|
+
"agent-prompts",
|
|
37
|
+
"cursor_specific.md",
|
|
38
|
+
);
|
|
39
|
+
|
|
40
|
+
function readCursorSpecificInjectionPrompt(): string | null {
|
|
41
|
+
try {
|
|
42
|
+
if (!existsSync(CURSOR_SPECIFIC_PROMPT_PATH)) return null;
|
|
43
|
+
const prompt = readFileSync(CURSOR_SPECIFIC_PROMPT_PATH, "utf-8").trim();
|
|
44
|
+
return prompt.length > 0 ? prompt : null;
|
|
45
|
+
} catch {
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function buildCursorPromptText(userText: string): string {
|
|
51
|
+
const prompt = readCursorSpecificInjectionPrompt();
|
|
52
|
+
if (!prompt) return userText;
|
|
53
|
+
|
|
54
|
+
return [
|
|
55
|
+
"[ChatCCC Cursor-specific injection prompt]",
|
|
56
|
+
prompt,
|
|
57
|
+
"[/ChatCCC Cursor-specific injection prompt]",
|
|
58
|
+
"",
|
|
59
|
+
userText,
|
|
60
|
+
].join("\n");
|
|
61
|
+
}
|
|
62
|
+
|
|
26
63
|
// ---------------------------------------------------------------------------
|
|
27
64
|
// 类型:Cursor JSONL 消息行
|
|
28
65
|
// ---------------------------------------------------------------------------
|
|
@@ -370,7 +407,7 @@ class CursorAdapter implements ToolAdapter {
|
|
|
370
407
|
options?: ToolPromptOptions,
|
|
371
408
|
): AsyncIterable<UnifiedStreamMessage> {
|
|
372
409
|
console.log(`[Cursor debug] prompt start: sessionId=${sessionId}, cwd=${cwd}, userTextLen=${userText.length}`);
|
|
373
|
-
const proc = spawnAgent(["--resume", sessionId], cwd, userText, this.modelOverride);
|
|
410
|
+
const proc = spawnAgent(["--resume", sessionId], cwd, buildCursorPromptText(userText), this.modelOverride);
|
|
374
411
|
this.activeProcs.add(proc);
|
|
375
412
|
if (proc.pid !== undefined) options?.onProcessStart?.({ pid: proc.pid });
|
|
376
413
|
|
package/src/cards.ts
CHANGED
|
@@ -131,6 +131,8 @@ export function buildHelpCard(
|
|
|
131
131
|
"发送 **/new cursor** 创建新 Cursor 会话",
|
|
132
132
|
"发送 **/new codex** 创建新 Codex 会话",
|
|
133
133
|
"发送 **/newh** 重置当前会话(沿用当前工作目录,不切换)",
|
|
134
|
+
"发送 **/plan** 以规划模式提问(只读,不执行写操作)",
|
|
135
|
+
"发送 **/ask** 以问答模式提问(只读,不执行写操作)",
|
|
134
136
|
].join("\n");
|
|
135
137
|
return JSON.stringify({
|
|
136
138
|
config: { wide_screen_mode: true },
|
package/src/config.ts
CHANGED
|
@@ -65,11 +65,11 @@ export interface ClaudeConfig {
|
|
|
65
65
|
model: string;
|
|
66
66
|
subagentModel: string;
|
|
67
67
|
effort: string;
|
|
68
|
-
/** Anthropic API Key(选填,留空则使用 Claude Code 默认认证) */
|
|
68
|
+
/** Anthropic API Key(选填,留空则使用 Claude Code 默认认证) */
|
|
69
69
|
apiKey: string;
|
|
70
70
|
/** Anthropic 兼容 API Base URL(选填,留空则使用默认端点) */
|
|
71
71
|
baseUrl: string;
|
|
72
|
-
/** Claude Agent SDK maxTurns 设置,默认
|
|
72
|
+
/** Claude Agent SDK maxTurns 设置,默认 0(无限制) */
|
|
73
73
|
maxTurn: number;
|
|
74
74
|
}
|
|
75
75
|
|
|
@@ -326,7 +326,7 @@ function loadConfig(): AppConfig {
|
|
|
326
326
|
port: 18080,
|
|
327
327
|
gitTimeoutSeconds: 180,
|
|
328
328
|
allowInterrupt: false,
|
|
329
|
-
claude: { enabled: false, defaultAgent: true, model: "", subagentModel: "", effort: "", apiKey: "", baseUrl: "", maxTurn:
|
|
329
|
+
claude: { enabled: false, defaultAgent: true, model: "", subagentModel: "", effort: "", apiKey: "", baseUrl: "", maxTurn: 0 },
|
|
330
330
|
cursor: { enabled: false, defaultAgent: false, path: "", model: "claude-opus-4-7-max" },
|
|
331
331
|
codex: { enabled: false, defaultAgent: false, path: "", model: "", effort: "" },
|
|
332
332
|
};
|
|
@@ -472,7 +472,7 @@ function loadConfig(): AppConfig {
|
|
|
472
472
|
baseUrl: normalizeOptionalConfigField(claude.baseUrl, { label: "claude.baseUrl" }),
|
|
473
473
|
maxTurn: typeof (claude as Record<string, unknown>).maxTurn === "number"
|
|
474
474
|
? (claude as Record<string, unknown>).maxTurn as number
|
|
475
|
-
:
|
|
475
|
+
: 0,
|
|
476
476
|
},
|
|
477
477
|
cursor: {
|
|
478
478
|
enabled: cursorEnabled,
|
package/src/feishu-api.ts
CHANGED
|
@@ -18,6 +18,19 @@ import {
|
|
|
18
18
|
toolDisplayName,
|
|
19
19
|
} from "./config.ts";
|
|
20
20
|
import { applyPrivacy } from "./privacy.ts";
|
|
21
|
+
|
|
22
|
+
// ---------------------------------------------------------------------------
|
|
23
|
+
// 合并转发消息类型
|
|
24
|
+
// ---------------------------------------------------------------------------
|
|
25
|
+
|
|
26
|
+
export interface FeishuMessageItem {
|
|
27
|
+
message_id?: string;
|
|
28
|
+
msg_type?: string;
|
|
29
|
+
body?: { content?: string };
|
|
30
|
+
sender?: { id?: string; id_type?: string };
|
|
31
|
+
create_time?: string;
|
|
32
|
+
upper_message_id?: string;
|
|
33
|
+
}
|
|
21
34
|
import { buildHelpCard } from "./cards.ts";
|
|
22
35
|
|
|
23
36
|
// ---------------------------------------------------------------------------
|
|
@@ -97,6 +110,12 @@ const REQUIRED_PERMISSIONS: PermissionDef[] = [
|
|
|
97
110
|
body: { direction: "vertical", elements: [{ tag: "markdown", content: " " }] },
|
|
98
111
|
}),
|
|
99
112
|
},
|
|
113
|
+
{
|
|
114
|
+
scope: "im:message:read",
|
|
115
|
+
description: "读取合并转发消息中的子消息列表",
|
|
116
|
+
method: "GET",
|
|
117
|
+
path: "/im/v1/messages/om_000000000000000000000000000000",
|
|
118
|
+
},
|
|
100
119
|
];
|
|
101
120
|
|
|
102
121
|
interface PermissionResult {
|
|
@@ -1046,3 +1065,34 @@ export async function sendPostMessage(
|
|
|
1046
1065
|
return false;
|
|
1047
1066
|
}
|
|
1048
1067
|
}
|
|
1068
|
+
|
|
1069
|
+
// ---------------------------------------------------------------------------
|
|
1070
|
+
// 合并转发消息
|
|
1071
|
+
// ---------------------------------------------------------------------------
|
|
1072
|
+
|
|
1073
|
+
/**
|
|
1074
|
+
* 获取合并转发消息中的子消息列表。
|
|
1075
|
+
*
|
|
1076
|
+
* 对合并转发消息调用 GET /im/v1/messages/{messageId} 时,
|
|
1077
|
+
* 返回 data.items[] 扁平的子消息列表,通过 upper_message_id 构建层级。
|
|
1078
|
+
* 第一个 item(无 upper_message_id)是合并转发消息自身。
|
|
1079
|
+
*
|
|
1080
|
+
* 权限要求: im:message:read
|
|
1081
|
+
*/
|
|
1082
|
+
export async function getMergeForwardMessages(
|
|
1083
|
+
token: string,
|
|
1084
|
+
messageId: string,
|
|
1085
|
+
): Promise<FeishuMessageItem[]> {
|
|
1086
|
+
const resp = await fetch(`${BASE_URL}/im/v1/messages/${messageId}`, {
|
|
1087
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
1088
|
+
});
|
|
1089
|
+
const json = (await resp.json()) as {
|
|
1090
|
+
code: number;
|
|
1091
|
+
msg?: string;
|
|
1092
|
+
data?: { items?: FeishuMessageItem[] };
|
|
1093
|
+
};
|
|
1094
|
+
if (json.code !== 0) {
|
|
1095
|
+
throw new Error(`getMergeForwardMessages [${json.code}] ${json.msg ?? ""}`);
|
|
1096
|
+
}
|
|
1097
|
+
return json.data?.items ?? [];
|
|
1098
|
+
}
|
package/src/feishu-platform.ts
CHANGED
|
@@ -37,6 +37,7 @@ export interface FeishuPlatform {
|
|
|
37
37
|
extractSessionId: typeof realApi.extractSessionId;
|
|
38
38
|
formatDelayNotice: typeof realApi.formatDelayNotice;
|
|
39
39
|
sendRestartCard: typeof realApi.sendRestartCard;
|
|
40
|
+
getMergeForwardMessages: typeof realApi.getMergeForwardMessages;
|
|
40
41
|
}
|
|
41
42
|
|
|
42
43
|
let _impl: FeishuPlatform = realApi;
|
|
@@ -141,4 +142,8 @@ export function sendPostMessage(...args: Parameters<typeof realApi.sendPostMessa
|
|
|
141
142
|
|
|
142
143
|
export function sendRestartCard(...args: Parameters<typeof realApi.sendRestartCard>): ReturnType<typeof realApi.sendRestartCard> {
|
|
143
144
|
return _impl.sendRestartCard(...args);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export function getMergeForwardMessages(...args: Parameters<typeof realApi.getMergeForwardMessages>): ReturnType<typeof realApi.getMergeForwardMessages> {
|
|
148
|
+
return _impl.getMergeForwardMessages(...args);
|
|
144
149
|
}
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* format-message.ts — 飞书消息内容格式化
|
|
3
|
+
*
|
|
4
|
+
* 从 index.ts 中提取,独立模块便于测试。
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { cardJsonToPlainText } from "./card-plain-text.ts";
|
|
8
|
+
import { ts } from "./config.ts";
|
|
9
|
+
import {
|
|
10
|
+
getTenantAccessToken,
|
|
11
|
+
getOrDownloadImage,
|
|
12
|
+
getMergeForwardMessages,
|
|
13
|
+
} from "./feishu-platform.ts";
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* 根据消息类型格式化消息内容为可读文本。
|
|
17
|
+
*/
|
|
18
|
+
export async function formatMessageContent(message: {
|
|
19
|
+
message_id?: string;
|
|
20
|
+
message_type?: string;
|
|
21
|
+
content?: string;
|
|
22
|
+
}): Promise<string> {
|
|
23
|
+
const contentStr = message.content ?? "{}";
|
|
24
|
+
let content: Record<string, unknown>;
|
|
25
|
+
try { content = JSON.parse(contentStr); } catch {
|
|
26
|
+
// merge_forward 消息的 content 可能为空字符串,但可通过 message_id 调 API 获取子消息
|
|
27
|
+
if (message.message_type === "merge_forward") {
|
|
28
|
+
content = {};
|
|
29
|
+
} else {
|
|
30
|
+
return "";
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
if (message.message_type === "text") {
|
|
35
|
+
let text = (content.text ?? "") as string;
|
|
36
|
+
text = text.replace(/<\/?p[^>]*>/gi, "");
|
|
37
|
+
text = text.replace(/<br\s*\/?>/gi, "\n");
|
|
38
|
+
text = text.replace(/ /gi, " ");
|
|
39
|
+
return text.trim();
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
if (message.message_type === "post") {
|
|
43
|
+
return formatPostContent(content);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
if (message.message_type === "image") {
|
|
47
|
+
const imageKey = content.image_key as string | undefined;
|
|
48
|
+
const messageId = message.message_id;
|
|
49
|
+
if (!imageKey || !messageId) return contentStr;
|
|
50
|
+
try {
|
|
51
|
+
const token = await getTenantAccessToken();
|
|
52
|
+
const localPath = await getOrDownloadImage(token, messageId, imageKey);
|
|
53
|
+
return `[图片] ${localPath}`;
|
|
54
|
+
} catch (err) {
|
|
55
|
+
console.error(
|
|
56
|
+
`[${ts()}] [IMAGE] download failed for ${imageKey}: ${(err as Error).message}`,
|
|
57
|
+
);
|
|
58
|
+
return `[图片: ${imageKey}]`;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
if (message.message_type === "media") {
|
|
63
|
+
const fileKey = content.file_key as string | undefined;
|
|
64
|
+
const fileName = (content.file_name as string) || "video.mp4";
|
|
65
|
+
const messageId = message.message_id;
|
|
66
|
+
if (!fileKey || !messageId) return contentStr;
|
|
67
|
+
return `[视频] message_id=${messageId} file_key=${fileKey} file_name=${fileName}`;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
if (message.message_type === "file") {
|
|
71
|
+
const fileKey = content.file_key as string | undefined;
|
|
72
|
+
const fileName = (content.file_name as string) || "download.bin";
|
|
73
|
+
const messageId = message.message_id;
|
|
74
|
+
if (!fileKey || !messageId) return contentStr;
|
|
75
|
+
return `[文件] message_id=${messageId} file_key=${fileKey} file_name=${fileName}`;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
if (message.message_type === "interactive") {
|
|
79
|
+
const raw = JSON.stringify(content);
|
|
80
|
+
const text = cardJsonToPlainText(raw);
|
|
81
|
+
if (text) return `[卡片] ${text}`;
|
|
82
|
+
return contentStr;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
if (message.message_type === "merge_forward") {
|
|
86
|
+
return formatMergeForward(message.message_id ?? "", content);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// 其他类型(audio, sticker 等)直接给原始 JSON
|
|
90
|
+
return contentStr;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function formatPostContent(content: Record<string, unknown>): string {
|
|
94
|
+
const paragraphs = content.content as unknown[][];
|
|
95
|
+
if (!Array.isArray(paragraphs)) return "";
|
|
96
|
+
|
|
97
|
+
const parts: string[] = [];
|
|
98
|
+
for (const line of paragraphs) {
|
|
99
|
+
if (!Array.isArray(line)) continue;
|
|
100
|
+
for (const elem of line) {
|
|
101
|
+
const el = elem as Record<string, unknown>;
|
|
102
|
+
if (!el || typeof el !== "object") continue;
|
|
103
|
+
const t = typeof el.text === "string" ? el.text : "";
|
|
104
|
+
|
|
105
|
+
if (el.tag === "code_block") {
|
|
106
|
+
const lang = typeof el.language === "string" ? el.language : "";
|
|
107
|
+
parts.push("```" + lang + "\n" + t + "\n```");
|
|
108
|
+
} else if (el.tag === "p" || el.tag === "text") {
|
|
109
|
+
if (t) parts.push(t);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
return parts.join("\n").trim();
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// ---------------------------------------------------------------------------
|
|
117
|
+
// 合并转发消息格式化
|
|
118
|
+
// ---------------------------------------------------------------------------
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* 格式化合并转发消息。
|
|
122
|
+
*
|
|
123
|
+
* 三阶段降级策略:
|
|
124
|
+
* 1. 调用 GET /im/v1/messages/{messageId} 获取完整子消息列表
|
|
125
|
+
* 2. API 失败时降级使用 content.preview 字段
|
|
126
|
+
* 3. preview 也为空时返回原始 JSON
|
|
127
|
+
*
|
|
128
|
+
* 递归深度限制 MAX_DEPTH=3,避免嵌套合并转发 API 爆炸。
|
|
129
|
+
*/
|
|
130
|
+
export async function formatMergeForward(
|
|
131
|
+
messageId: string,
|
|
132
|
+
content: Record<string, unknown>,
|
|
133
|
+
depth: number = 0,
|
|
134
|
+
): Promise<string> {
|
|
135
|
+
const MAX_DEPTH = 3;
|
|
136
|
+
if (depth >= MAX_DEPTH) {
|
|
137
|
+
return `[合并转发: 超出最大嵌套深度 ${MAX_DEPTH}]`;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const title = (content.title as string) || "聊天记录";
|
|
141
|
+
const chatName = (content.chat_name as string) || "";
|
|
142
|
+
const header = `[合并转发: ${title}${chatName ? ` (${chatName})` : ""}]`;
|
|
143
|
+
|
|
144
|
+
// 从 preview 构建 sender ID → name 映射表
|
|
145
|
+
const senderNameMap = new Map<string, string>();
|
|
146
|
+
const preview = content.preview;
|
|
147
|
+
if (Array.isArray(preview)) {
|
|
148
|
+
for (const entry of preview) {
|
|
149
|
+
const e = entry as Record<string, unknown>;
|
|
150
|
+
const s = e.sender as Record<string, unknown> | undefined;
|
|
151
|
+
if (s && typeof s.id === "string" && typeof s.name === "string") {
|
|
152
|
+
senderNameMap.set(s.id, s.name);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const lines: string[] = [];
|
|
158
|
+
let usedApi = false;
|
|
159
|
+
|
|
160
|
+
// Phase 1: 尝试通过 API 获取完整子消息列表
|
|
161
|
+
try {
|
|
162
|
+
const token = await getTenantAccessToken();
|
|
163
|
+
const items = await getMergeForwardMessages(token, messageId);
|
|
164
|
+
|
|
165
|
+
// 跳过第一个 item(合并转发消息自身,无 upper_message_id)
|
|
166
|
+
const subItems = items.filter((item) => item.upper_message_id);
|
|
167
|
+
|
|
168
|
+
if (subItems.length > 0) {
|
|
169
|
+
for (const item of subItems) {
|
|
170
|
+
const senderId = item.sender?.id ?? "unknown";
|
|
171
|
+
const senderName = senderNameMap.get(senderId) ?? senderId;
|
|
172
|
+
|
|
173
|
+
const subMsgType = item.msg_type ?? "";
|
|
174
|
+
const subContent = item.body?.content ?? "{}";
|
|
175
|
+
|
|
176
|
+
try {
|
|
177
|
+
const formatted = await formatMessageContent({
|
|
178
|
+
message_id: item.message_id,
|
|
179
|
+
message_type: subMsgType,
|
|
180
|
+
content: subContent,
|
|
181
|
+
});
|
|
182
|
+
lines.push(`${senderName}: ${formatted}`);
|
|
183
|
+
} catch {
|
|
184
|
+
lines.push(`${senderName}: ${subContent}`);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
usedApi = true;
|
|
188
|
+
}
|
|
189
|
+
} catch (err) {
|
|
190
|
+
console.error(
|
|
191
|
+
`[${ts()}] [MERGE_FORWARD] API 获取子消息失败 (${messageId}), 降级使用 preview: ${(err as Error).message}`,
|
|
192
|
+
);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// Phase 2: API 失败或返回空时降级使用 preview
|
|
196
|
+
if (!usedApi) {
|
|
197
|
+
if (Array.isArray(preview) && preview.length > 0) {
|
|
198
|
+
for (const entry of preview) {
|
|
199
|
+
const e = entry as Record<string, unknown>;
|
|
200
|
+
const s = e.sender as Record<string, unknown> | undefined;
|
|
201
|
+
const senderName = (s?.name as string) ?? "未知用户";
|
|
202
|
+
const text = (e.content as string) ?? "";
|
|
203
|
+
lines.push(`${senderName}: ${text}`);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// Phase 3: 没有任何内容时返回原始 JSON
|
|
209
|
+
if (lines.length === 0) {
|
|
210
|
+
return JSON.stringify(content);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
return header + "\n" + lines.join("\n");
|
|
214
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -69,7 +69,6 @@ import {
|
|
|
69
69
|
updateCardMessage,
|
|
70
70
|
updateChatInfo,
|
|
71
71
|
disbandChat,
|
|
72
|
-
getOrDownloadImage,
|
|
73
72
|
sendRestartCard,
|
|
74
73
|
verifyAllPermissions,
|
|
75
74
|
reportPermissionResults,
|
|
@@ -182,83 +181,7 @@ function getInnerEvent(data: Evt): InnerEvent {
|
|
|
182
181
|
return (data.event ?? data) as InnerEvent;
|
|
183
182
|
}
|
|
184
183
|
|
|
185
|
-
|
|
186
|
-
* 将飞书消息的原始 content JSON 结构转成可读文本,保留代码块等结构信息。
|
|
187
|
-
* 未知类型直接返回 JSON 原文,让 AI 自行理解。
|
|
188
|
-
*/
|
|
189
|
-
async function formatMessageContent(message: { message_id?: string; message_type?: string; content?: string }): Promise<string> {
|
|
190
|
-
const contentStr = message.content ?? "{}";
|
|
191
|
-
let content: Record<string, unknown>;
|
|
192
|
-
try { content = JSON.parse(contentStr); } catch { return ""; }
|
|
193
|
-
|
|
194
|
-
if (message.message_type === "text") {
|
|
195
|
-
let text = (content.text ?? "") as string;
|
|
196
|
-
text = text.replace(/<\/?p[^>]*>/gi, "");
|
|
197
|
-
text = text.replace(/<br\s*\/?>/gi, "\n");
|
|
198
|
-
text = text.replace(/ /gi, " ");
|
|
199
|
-
return text.trim();
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
if (message.message_type === "post") {
|
|
203
|
-
return formatPostContent(content);
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
if (message.message_type === "image") {
|
|
207
|
-
const imageKey = content.image_key as string | undefined;
|
|
208
|
-
const messageId = message.message_id;
|
|
209
|
-
if (!imageKey || !messageId) return contentStr;
|
|
210
|
-
try {
|
|
211
|
-
const token = await getTenantAccessToken();
|
|
212
|
-
const localPath = await getOrDownloadImage(token, messageId, imageKey);
|
|
213
|
-
return `[图片] ${localPath}`;
|
|
214
|
-
} catch (err) {
|
|
215
|
-
console.error(`[${ts()}] [IMAGE] download failed for ${imageKey}: ${(err as Error).message}`);
|
|
216
|
-
return `[图片: ${imageKey}]`;
|
|
217
|
-
}
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
if (message.message_type === "media") {
|
|
221
|
-
const fileKey = content.file_key as string | undefined;
|
|
222
|
-
const fileName = (content.file_name as string) || "video.mp4";
|
|
223
|
-
const messageId = message.message_id;
|
|
224
|
-
if (!fileKey || !messageId) return contentStr;
|
|
225
|
-
return `[视频] message_id=${messageId} file_key=${fileKey} file_name=${fileName}`;
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
if (message.message_type === "file") {
|
|
229
|
-
const fileKey = content.file_key as string | undefined;
|
|
230
|
-
const fileName = (content.file_name as string) || "download.bin";
|
|
231
|
-
const messageId = message.message_id;
|
|
232
|
-
if (!fileKey || !messageId) return contentStr;
|
|
233
|
-
return `[文件] message_id=${messageId} file_key=${fileKey} file_name=${fileName}`;
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
// 其他类型(audio, sticker 等)直接给原始 JSON
|
|
237
|
-
return contentStr;
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
function formatPostContent(content: Record<string, unknown>): string {
|
|
241
|
-
const paragraphs = content.content as unknown[][];
|
|
242
|
-
if (!Array.isArray(paragraphs)) return "";
|
|
243
|
-
|
|
244
|
-
const parts: string[] = [];
|
|
245
|
-
for (const line of paragraphs) {
|
|
246
|
-
if (!Array.isArray(line)) continue;
|
|
247
|
-
for (const elem of line) {
|
|
248
|
-
const el = elem as Record<string, unknown>;
|
|
249
|
-
if (!el || typeof el !== "object") continue;
|
|
250
|
-
const t = typeof el.text === "string" ? el.text : "";
|
|
251
|
-
|
|
252
|
-
if (el.tag === "code_block") {
|
|
253
|
-
const lang = typeof el.language === "string" ? el.language : "";
|
|
254
|
-
parts.push("```" + lang + "\n" + t + "\n```");
|
|
255
|
-
} else if (el.tag === "p" || el.tag === "text") {
|
|
256
|
-
if (t) parts.push(t);
|
|
257
|
-
}
|
|
258
|
-
}
|
|
259
|
-
}
|
|
260
|
-
return parts.join("\n").trim();
|
|
261
|
-
}
|
|
184
|
+
import { formatMessageContent } from "./format-message.ts";
|
|
262
185
|
|
|
263
186
|
// ---------------------------------------------------------------------------
|
|
264
187
|
// Card action helper: parse button click into text command
|
package/src/sim-platform.ts
CHANGED
|
@@ -153,6 +153,11 @@ export const SimulatedPlatform: FeishuPlatform = {
|
|
|
153
153
|
async sendRestartCard(_token) {
|
|
154
154
|
// 模拟模式不需要重启通知
|
|
155
155
|
},
|
|
156
|
+
|
|
157
|
+
async getMergeForwardMessages(_token, _messageId) {
|
|
158
|
+
// 模拟模式没有真实 API,返回空数组让调用方降级到 preview
|
|
159
|
+
return [];
|
|
160
|
+
},
|
|
156
161
|
};
|
|
157
162
|
|
|
158
163
|
/** 模拟模式下的默认 chat_id(重新导出以保持向后兼容) */
|
package/src/web-ui.ts
CHANGED
|
@@ -321,7 +321,7 @@ export function unflattenConfig(flat: Record<string, unknown>): Record<string, u
|
|
|
321
321
|
(result.claude as Record<string, unknown>).baseUrl = val;
|
|
322
322
|
} else if (key === "CHATCCC_ANTHROPIC_MAX_TURN") {
|
|
323
323
|
result.claude = result.claude || {};
|
|
324
|
-
(result.claude as Record<string, unknown>).maxTurn =
|
|
324
|
+
(result.claude as Record<string, unknown>).maxTurn = (function(v){ var n = parseInt(v, 10); return isNaN(n) ? 0 : n; })(val as string);
|
|
325
325
|
} else if (key === "CHATCCC_CLAUDE_ENABLED") {
|
|
326
326
|
result.claude = result.claude || {};
|
|
327
327
|
(result.claude as Record<string, unknown>).enabled = val === true || val === "true";
|
|
@@ -646,7 +646,7 @@ header .badge{font-size:13px;padding:4px 12px;border-radius:12px;font-weight:500
|
|
|
646
646
|
</div>
|
|
647
647
|
<div class="form-group">
|
|
648
648
|
<label>API Key(选填)</label>
|
|
649
|
-
<input type="password" id="field-CHATCCC_ANTHROPIC_API_KEY" placeholder="留空使用 Claude Code 默认认证">
|
|
649
|
+
<input type="password" id="field-CHATCCC_ANTHROPIC_API_KEY" placeholder="留空使用 Claude Code 默认认证">
|
|
650
650
|
</div>
|
|
651
651
|
<div class="form-group">
|
|
652
652
|
<label>Base URL(选填)</label>
|
|
@@ -788,7 +788,7 @@ header .badge{font-size:13px;padding:4px 12px;border-radius:12px;font-weight:500
|
|
|
788
788
|
<div class="config-row"><span class="key">Effort</span><span class="val" id="cfg-ANTHROPIC_EFFORT">-</span></div>
|
|
789
789
|
<div class="config-row"><span class="key">API Key</span><span class="val" id="cfg-ANTHROPIC_API_KEY">-</span></div>
|
|
790
790
|
<div class="config-row"><span class="key">Base URL</span><span class="val" id="cfg-ANTHROPIC_BASE_URL">-</span></div>
|
|
791
|
-
<div class="config-row"><span class="key">Max Turns</span><span class="val" id="cfg-ANTHROPIC_MAX_TURN">-</span></div>
|
|
791
|
+
<div class="config-row"><span class="key">Max Turns</span><span class="val" id="cfg-ANTHROPIC_MAX_TURN">-</span><span class="hint">(0=无限制)</span></div>
|
|
792
792
|
<label class="agent-default-row" style="margin-top:10px"><input type="checkbox" id="dash-default-claude" onchange="setDashboardDefaultAgent('claude', this.checked)"> 设为默认 Agent</label>
|
|
793
793
|
<button class="btn btn-outline" style="margin-top:8px" onclick="editSection('claude')">编辑</button>
|
|
794
794
|
</div>
|
|
@@ -1403,7 +1403,7 @@ function updateDashboardUI() {
|
|
|
1403
1403
|
document.getElementById('cfg-ANTHROPIC_EFFORT').textContent = (c.claude && c.claude.effort) || '(留空)';
|
|
1404
1404
|
document.getElementById('cfg-ANTHROPIC_API_KEY').textContent = (c.claude && c.claude.apiKey) ? '***已设置***' : '(留空)';
|
|
1405
1405
|
document.getElementById('cfg-ANTHROPIC_BASE_URL').textContent = (c.claude && c.claude.baseUrl) || '(留空)';
|
|
1406
|
-
document.getElementById('cfg-ANTHROPIC_MAX_TURN').textContent = (c.claude && c.claude.maxTurn != null) ? String(c.claude.maxTurn) : '
|
|
1406
|
+
document.getElementById('cfg-ANTHROPIC_MAX_TURN').textContent = (c.claude && c.claude.maxTurn != null) ? String(c.claude.maxTurn) : '0';
|
|
1407
1407
|
document.getElementById('cfg-CURSOR_PATH').textContent = (c.cursor && (c.cursor.path || c.cursor.command)) || '-';
|
|
1408
1408
|
document.getElementById('cfg-CURSOR_MODEL').textContent = (c.cursor && c.cursor.model) || '(留空)';
|
|
1409
1409
|
document.getElementById('cfg-CODEX_PATH').textContent = (c.codex && (c.codex.path || c.codex.command)) || 'codex';
|
|
@@ -1464,7 +1464,7 @@ function editSection(section) {
|
|
|
1464
1464
|
var labelMap = {
|
|
1465
1465
|
'CHATCCC_APP_ID': 'App ID', 'CHATCCC_APP_SECRET': 'App Secret',
|
|
1466
1466
|
'CHATCCC_ANTHROPIC_MODEL': '模型', 'CHATCCC_ANTHROPIC_SUBAGENT_MODEL': 'Subagent 模型', 'CHATCCC_ANTHROPIC_EFFORT': 'Effort',
|
|
1467
|
-
'CHATCCC_ANTHROPIC_API_KEY': 'API Key', 'CHATCCC_ANTHROPIC_BASE_URL': 'Base URL', 'CHATCCC_ANTHROPIC_MAX_TURN': 'Max Turns',
|
|
1467
|
+
'CHATCCC_ANTHROPIC_API_KEY': 'API Key', 'CHATCCC_ANTHROPIC_BASE_URL': 'Base URL', 'CHATCCC_ANTHROPIC_MAX_TURN': 'Max Turns (0=无限制)',
|
|
1468
1468
|
'CHATCCC_CURSOR_PATH': 'CLI 路径', 'CHATCCC_CURSOR_MODEL': '模型',
|
|
1469
1469
|
'CHATCCC_CODEX_PATH': 'CLI 路径', 'CHATCCC_CODEX_MODEL': '模型', 'CHATCCC_CODEX_EFFORT': 'Effort'
|
|
1470
1470
|
};
|
|
@@ -1482,7 +1482,7 @@ function editSection(section) {
|
|
|
1482
1482
|
else if (key === 'CHATCCC_ANTHROPIC_EFFORT') val = state.config.claude.effort || '';
|
|
1483
1483
|
else if (key === 'CHATCCC_ANTHROPIC_API_KEY') val = state.config.claude.apiKey || '';
|
|
1484
1484
|
else if (key === 'CHATCCC_ANTHROPIC_BASE_URL') val = state.config.claude.baseUrl || '';
|
|
1485
|
-
else if (key === 'CHATCCC_ANTHROPIC_MAX_TURN') val = (state.config.claude.maxTurn != null) ? String(state.config.claude.maxTurn) : '
|
|
1485
|
+
else if (key === 'CHATCCC_ANTHROPIC_MAX_TURN') val = (state.config.claude.maxTurn != null) ? String(state.config.claude.maxTurn) : '0';
|
|
1486
1486
|
} else if (section === 'cursor' && state.config.cursor) {
|
|
1487
1487
|
if (key === 'CHATCCC_CURSOR_PATH') val = state.config.cursor.path || state.config.cursor.command || '';
|
|
1488
1488
|
else if (key === 'CHATCCC_CURSOR_MODEL') val = state.config.cursor.model || '';
|