chatccc 0.2.226 → 0.2.228

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/.agents/skills/create-chatccc-feishu-app/SKILL.md +85 -85
  2. package/.claude/skills/create-chatccc-feishu-app/SKILL.md +85 -85
  3. package/.cursor/skills/create-chatccc-feishu-app/SKILL.md +85 -85
  4. package/README.md +90 -90
  5. package/package.json +1 -1
  6. package/src/__tests__/agent-activity.test.ts +76 -76
  7. package/src/__tests__/builtin-chat-session.test.ts +350 -350
  8. package/src/__tests__/builtin-config.test.ts +26 -26
  9. package/src/__tests__/builtin-context.test.ts +163 -163
  10. package/src/__tests__/builtin-file-tools.test.ts +275 -275
  11. package/src/__tests__/builtin-permissions.test.ts +211 -211
  12. package/src/__tests__/builtin-session-select.test.ts +116 -116
  13. package/src/__tests__/builtin-skills.test.ts +252 -141
  14. package/src/__tests__/builtin-web-tools.test.ts +220 -0
  15. package/src/__tests__/card-action-routing.test.ts +18 -18
  16. package/src/__tests__/ccc-adapter.test.ts +136 -136
  17. package/src/__tests__/claude-adapter.test.ts +614 -614
  18. package/src/__tests__/codex-adapter.test.ts +58 -58
  19. package/src/__tests__/codex-raw-stream-log.test.ts +170 -170
  20. package/src/__tests__/cursor-adapter.test.ts +268 -268
  21. package/src/__tests__/feishu-avatar.test.ts +164 -164
  22. package/src/__tests__/feishu-message-ingress.test.ts +138 -138
  23. package/src/__tests__/package-files.test.ts +24 -24
  24. package/src/__tests__/progress-reducer.test.ts +110 -110
  25. package/src/__tests__/response-stall.test.ts +49 -49
  26. package/src/__tests__/sim-platform.test.ts +16 -16
  27. package/src/__tests__/startup-lifecycle.test.ts +231 -231
  28. package/src/__tests__/stop-session.test.ts +34 -34
  29. package/src/__tests__/terminal-renderer.test.ts +247 -247
  30. package/src/__tests__/update-command-guard.test.ts +144 -144
  31. package/src/__tests__/web-ui.test.ts +326 -326
  32. package/src/adapters/adapter-interface.ts +18 -18
  33. package/src/adapters/ccc-adapter.ts +131 -131
  34. package/src/adapters/claude-adapter.ts +620 -620
  35. package/src/adapters/codex-adapter.ts +426 -426
  36. package/src/adapters/cursor-adapter.ts +681 -681
  37. package/src/agent-activity.ts +170 -170
  38. package/src/agent-delegate-task.ts +91 -91
  39. package/src/builtin/cli.ts +61 -2
  40. package/src/builtin/config.ts +84 -84
  41. package/src/builtin/context.ts +323 -323
  42. package/src/builtin/file-log.ts +38 -38
  43. package/src/builtin/file-tools.ts +37 -0
  44. package/src/builtin/index.ts +44 -24
  45. package/src/builtin/proc-tree-kill.ts +61 -61
  46. package/src/builtin/progress/cards-helpers.ts +76 -76
  47. package/src/builtin/progress/reducer.ts +108 -108
  48. package/src/builtin/progress/terminal-renderer.ts +294 -294
  49. package/src/builtin/progress/view.ts +77 -77
  50. package/src/builtin/raw-stream-log.ts +124 -124
  51. package/src/builtin/session-select.ts +48 -48
  52. package/src/builtin/skills.ts +190 -108
  53. package/src/builtin/web-tools.ts +313 -0
  54. package/src/card-action-routing.ts +14 -14
  55. package/src/feishu-api.ts +193 -193
  56. package/src/feishu-message-ingress.ts +195 -195
  57. package/src/index.ts +306 -306
  58. package/src/orchestrator.ts +2388 -2388
  59. package/src/platform-adapter.ts +6 -6
  60. package/src/progress/reducer.ts +108 -108
  61. package/src/progress/terminal-renderer.ts +294 -294
  62. package/src/progress/view.ts +77 -77
  63. package/src/response-stall.ts +28 -28
  64. package/src/session-chat-binding.ts +82 -82
  65. package/src/startup-lifecycle.ts +250 -250
  66. package/src/stream-state.ts +18 -18
  67. package/src/update-command-guard.ts +165 -165
@@ -1,141 +1,252 @@
1
- import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
2
- import { tmpdir } from "node:os";
3
- import { join } from "node:path";
4
-
5
- import { afterEach, describe, expect, it } from "vitest";
6
-
7
- import {
8
- buildSkillsIndexPrompt,
9
- parseSkillFrontmatter,
10
- scanSkillsDirs,
11
- } from "../builtin/skills.ts";
12
-
13
- const tempDirs: string[] = [];
14
-
15
- async function makeTempDir(): Promise<string> {
16
- const dir = await mkdtemp(join(tmpdir(), "chatccc-skills-"));
17
- tempDirs.push(dir);
18
- return dir;
19
- }
20
-
21
- afterEach(async () => {
22
- await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
23
- });
24
-
25
- describe("parseSkillFrontmatter", () => {
26
- it("parses name and description from frontmatter", () => {
27
- const content = [
28
- "---",
29
- "name: feishu-doc-download-md",
30
- "description: 下载飞书文档为 Markdown",
31
- "---",
32
- "",
33
- "# 正文",
34
- ].join("\n");
35
- expect(parseSkillFrontmatter(content)).toEqual({
36
- name: "feishu-doc-download-md",
37
- description: "下载飞书文档为 Markdown",
38
- });
39
- });
40
-
41
- it("returns null when there is no frontmatter", () => {
42
- expect(parseSkillFrontmatter("# just a heading")).toBeNull();
43
- });
44
-
45
- it("tolerates missing description", () => {
46
- expect(parseSkillFrontmatter("---\nname: minimal-skill\n---\n\nbody")).toEqual({
47
- name: "minimal-skill",
48
- description: "",
49
- });
50
- });
51
-
52
- it("handles CRLF line endings", () => {
53
- const content = "---\r\nname: crlf-skill\r\ndescription: CRLF 描述\r\n---\r\n\r\nbody";
54
- expect(parseSkillFrontmatter(content)).toEqual({
55
- name: "crlf-skill",
56
- description: "CRLF 描述",
57
- });
58
- });
59
- });
60
-
61
- describe("scanSkillsDirs", () => {
62
- it("scans multiple dirs, skips hidden/system dirs, dedupes by name (later dir wins)", async () => {
63
- const dir = await makeTempDir();
64
- const userA = join(dir, "codex-skills");
65
- const userB = join(dir, "agents-skills");
66
- const project = join(dir, "project-codex");
67
- await mkdir(join(userA, "feishu-doc"), { recursive: true });
68
- await mkdir(join(userA, ".system"), { recursive: true });
69
- await mkdir(join(userA, "no-skill-dir"));
70
- await mkdir(join(userB, "feishu-doc"), { recursive: true });
71
- await mkdir(join(userB, "another"), { recursive: true });
72
- await mkdir(join(project, "feishu-doc"), { recursive: true });
73
-
74
- await writeFile(
75
- join(userA, "feishu-doc", "SKILL.md"),
76
- "---\nname: feishu-doc\ndescription: 用户级 A\n---\n",
77
- "utf8",
78
- );
79
- await writeFile(
80
- join(userA, ".system", "SKILL.md"),
81
- "---\nname: system-skill\ndescription: 内置\n---\n",
82
- "utf8",
83
- );
84
- await writeFile(
85
- join(userB, "feishu-doc", "SKILL.md"),
86
- "---\nname: feishu-doc\ndescription: 用户级 B\n---\n",
87
- "utf8",
88
- );
89
- await writeFile(
90
- join(userB, "another", "SKILL.md"),
91
- "---\nname: another\ndescription: 另一个\n---\n",
92
- "utf8",
93
- );
94
- await writeFile(
95
- join(project, "feishu-doc", "SKILL.md"),
96
- "---\nname: feishu-doc\ndescription: 项目级覆盖\n---\n",
97
- "utf8",
98
- );
99
-
100
- const skills = scanSkillsDirs([userA, userB, project]);
101
-
102
- // 去重:同名保留一个,后面的目录(项目级)覆盖前面的(用户级)
103
- expect(skills).toHaveLength(2);
104
- const byName = new Map(skills.map((s) => [s.name, s]));
105
- expect(byName.get("feishu-doc")?.description).toBe("项目级覆盖");
106
- expect(byName.get("feishu-doc")?.skillPath).toBe(join(project, "feishu-doc", "SKILL.md"));
107
- expect(byName.get("another")?.description).toBe("另一个");
108
- expect(byName.has("system-skill")).toBe(false); // 隐藏目录被排除
109
- });
110
-
111
- it("skips missing directories and dirs without SKILL.md", async () => {
112
- const dir = await makeTempDir();
113
- await mkdir(join(dir, "empty-dir"));
114
-
115
- const skills = scanSkillsDirs([join(dir, "missing-dir"), join(dir, "empty-dir")]);
116
-
117
- expect(skills).toEqual([]);
118
- });
119
- });
120
-
121
- describe("buildSkillsIndexPrompt", () => {
122
- it("renders a skill index with names, paths and descriptions", () => {
123
- const prompt = buildSkillsIndexPrompt([
124
- {
125
- name: "feishu-doc",
126
- description: "下载飞书文档",
127
- skillPath: "C:\\users\\x\\skills\\feishu-doc\\SKILL.md",
128
- },
129
- ]);
130
-
131
- expect(prompt).toContain("## Available Skills");
132
- expect(prompt).toContain("**feishu-doc**");
133
- expect(prompt).toContain("下载飞书文档");
134
- expect(prompt).toContain("C:\\users\\x\\skills\\feishu-doc\\SKILL.md");
135
- expect(prompt).toContain("read_file");
136
- });
137
-
138
- it("returns empty string for no skills", () => {
139
- expect(buildSkillsIndexPrompt([])).toBe("");
140
- });
141
- });
1
+ import { describe, it, expect, beforeEach, afterEach } from "vitest";
2
+ import { mkdtempSync, rmSync, writeFileSync, mkdirSync, utimesSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+
6
+ import {
7
+ parseSkillFrontmatter,
8
+ scanSkillsDirs,
9
+ buildDefaultSkillDirs,
10
+ buildSkillsIndexPrompt,
11
+ buildSkillTemplate,
12
+ type SkillDirSpec,
13
+ type SkillSource,
14
+ type SkillScope,
15
+ } from "../builtin/skills.ts";
16
+
17
+ let tempRoot: string;
18
+
19
+ beforeEach(() => {
20
+ tempRoot = mkdtempSync(join(tmpdir(), "deepccc-skills-"));
21
+ });
22
+
23
+ afterEach(() => {
24
+ try {
25
+ rmSync(tempRoot, { recursive: true, force: true });
26
+ } catch {}
27
+ });
28
+
29
+ function makeSkill(specDir: string, name: string, description: string): string {
30
+ const dir = join(specDir, name);
31
+ mkdirSync(dir, { recursive: true });
32
+ const skillPath = join(dir, "SKILL.md");
33
+ writeFileSync(skillPath, `---\nname: ${name}\ndescription: ${description}\n---\n\nbody\n`, "utf8");
34
+ return skillPath;
35
+ }
36
+
37
+ function spec(
38
+ dir: string,
39
+ source: SkillSource,
40
+ scope: SkillScope = "global",
41
+ ): SkillDirSpec {
42
+ return { dir, source, scope };
43
+ }
44
+
45
+ describe("parseSkillFrontmatter", () => {
46
+ it("parses name and description from frontmatter", () => {
47
+ const content = [
48
+ "---",
49
+ "name: feishu-doc-download-md",
50
+ "description: 涓嬭浇椋炰功鏂囨。涓?Markdown",
51
+ "---",
52
+ "",
53
+ "# 姝f枃",
54
+ ].join("\n");
55
+ expect(parseSkillFrontmatter(content)).toEqual({
56
+ name: "feishu-doc-download-md",
57
+ description: "涓嬭浇椋炰功鏂囨。涓?Markdown",
58
+ });
59
+ });
60
+
61
+ it("returns null when there is no frontmatter", () => {
62
+ expect(parseSkillFrontmatter("# just a heading")).toBeNull();
63
+ });
64
+
65
+ it("tolerates missing description", () => {
66
+ expect(parseSkillFrontmatter("---\nname: minimal-skill\n---\n\nbody")).toEqual({
67
+ name: "minimal-skill",
68
+ description: "",
69
+ });
70
+ });
71
+
72
+ it("handles CRLF line endings", () => {
73
+ const content = "---\r\nname: crlf-skill\r\ndescription: CRLF 鎻忚堪\r\n---\r\n\r\nbody";
74
+ expect(parseSkillFrontmatter(content)).toEqual({
75
+ name: "crlf-skill",
76
+ description: "CRLF 鎻忚堪",
77
+ });
78
+ });
79
+ });
80
+
81
+ describe("scanSkillsDirs priority matrix", () => {
82
+ it("codex wins over cursor, cursor wins over claude for same-name skills", async () => {
83
+ const claudeDir = join(tempRoot, "claude");
84
+ const cursorDir = join(tempRoot, "cursor");
85
+ const codexDir = join(tempRoot, "codex");
86
+ makeSkill(claudeDir, "dupe", "claude version");
87
+ makeSkill(cursorDir, "dupe", "cursor version");
88
+ makeSkill(codexDir, "dupe", "codex version");
89
+ makeSkill(codexDir, "only-codex", "codex only");
90
+
91
+ const skills = await scanSkillsDirs([
92
+ spec(claudeDir, "claude"),
93
+ spec(cursorDir, "cursor"),
94
+ spec(codexDir, "codex"),
95
+ ]);
96
+
97
+ const byName = new Map(skills.map((s) => [s.name, s]));
98
+ expect(byName.get("dupe")?.description).toBe("codex version");
99
+ expect(byName.get("dupe")?.source).toBe("codex");
100
+ expect(byName.get("dupe")?.skillPath).toContain(join("codex", "dupe"));
101
+ expect(byName.get("only-codex")?.source).toBe("codex");
102
+ });
103
+
104
+ it("project scope wins over global scope within the same source", async () => {
105
+ const globalCodex = join(tempRoot, "codex-global");
106
+ const projectCodex = join(tempRoot, "codex-project");
107
+ makeSkill(globalCodex, "dup", "global version");
108
+ makeSkill(projectCodex, "dup", "project version");
109
+
110
+ const skills = await scanSkillsDirs([
111
+ spec(globalCodex, "codex", "global"),
112
+ spec(projectCodex, "codex", "project"),
113
+ ]);
114
+
115
+ const byName = new Map(skills.map((s) => [s.name, s]));
116
+ expect(byName.get("dup")?.description).toBe("project version");
117
+ expect(byName.get("dup")?.scope).toBe("project");
118
+ });
119
+
120
+ it("deepccc source has the highest priority over codex", async () => {
121
+ const codexDir = join(tempRoot, "codex");
122
+ const deepcccDir = join(tempRoot, "deepccc");
123
+ makeSkill(codexDir, "dup", "from codex");
124
+ makeSkill(deepcccDir, "dup", "from deepccc");
125
+
126
+ const skills = await scanSkillsDirs([
127
+ spec(codexDir, "codex"),
128
+ spec(deepcccDir, "deepccc"),
129
+ ]);
130
+
131
+ expect(skills.find((s) => s.name === "dup")?.description).toBe("from deepccc");
132
+ expect(skills.find((s) => s.name === "dup")?.source).toBe("deepccc");
133
+ });
134
+
135
+ it("skips hidden dirs, dirs without SKILL.md, and missing dirs", async () => {
136
+ const dir = join(tempRoot, "src");
137
+ mkdirSync(join(dir, ".system"), { recursive: true });
138
+ writeFileSync(join(dir, ".system", "SKILL.md"), "---\nname: system-skill\ndescription: x\n---\n", "utf8");
139
+ mkdirSync(join(dir, "no-skill-dir"));
140
+
141
+ makeSkill(dir, "ok", "fine");
142
+ const skills = await scanSkillsDirs([
143
+ spec(join(tempRoot, "missing-dir"), "codex"),
144
+ spec(dir, "codex"),
145
+ ]);
146
+
147
+ expect(skills).toHaveLength(1);
148
+ expect(skills[0].name).toBe("ok");
149
+ });
150
+ });
151
+
152
+ describe("scanSkillsDirs hot reload (mtime cache)", () => {
153
+ it("re-reads a skill after its SKILL.md content changes", async () => {
154
+ const dir = join(tempRoot, "src");
155
+ const skillPath = makeSkill(dir, "live", "v1");
156
+
157
+ const first = await scanSkillsDirs([spec(dir, "deepccc")]);
158
+ expect(first.find((s) => s.name === "live")?.description).toBe("v1");
159
+
160
+ writeFileSync(skillPath, "---\nname: live\ndescription: v2\n---\n\nbody\n", "utf8");
161
+ utimesSync(skillPath, new Date(Date.now() + 3000), new Date(Date.now() + 3000)); // 寮哄埗 mtime 鍓嶈繘
162
+
163
+ const second = await scanSkillsDirs([spec(dir, "deepccc")]);
164
+ expect(second.find((s) => s.name === "live")?.description).toBe("v2");
165
+ });
166
+
167
+ it("new skill dirs are picked up on the next scan", async () => {
168
+ const dir = join(tempRoot, "src");
169
+ makeSkill(dir, "a", "A");
170
+
171
+ const first = await scanSkillsDirs([spec(dir, "deepccc")]);
172
+ expect(first).toHaveLength(1);
173
+
174
+ makeSkill(dir, "b", "B"); // 鏂版妧鑳斤紝鏃犻渶鏀?mtime锛堢洰褰曟灇涓炬瘡娆¢兘鍋氾級
175
+ const second = await scanSkillsDirs([spec(dir, "deepccc")]);
176
+ expect(second.map((s) => s.name).sort()).toEqual(["a", "b"]);
177
+ });
178
+
179
+ it("unchanged skills return identical results across scans", async () => {
180
+ const dir = join(tempRoot, "src");
181
+ makeSkill(dir, "a", "A");
182
+
183
+ const first = await scanSkillsDirs([spec(dir, "deepccc")]);
184
+ const second = await scanSkillsDirs([spec(dir, "deepccc")]);
185
+ expect(second).toEqual(first);
186
+ });
187
+ });
188
+
189
+ describe("buildDefaultSkillDirs", () => {
190
+ it("orders dirs low->high priority: claude < cursor < codex < deepccc, project after global", () => {
191
+ const dirs = buildDefaultSkillDirs("C:/proj");
192
+ expect(dirs.map((d) => `${d.source}:${d.scope}`)).toEqual([
193
+ "claude:global",
194
+ "claude:project",
195
+ "cursor:global",
196
+ "cursor:project",
197
+ "codex:global",
198
+ "codex:global",
199
+ "codex:project",
200
+ "deepccc:global",
201
+ "deepccc:project",
202
+ ]);
203
+ });
204
+
205
+ it("points codex global dirs at ~/.codex/skills and ~/.agents/skills", () => {
206
+ const dirs = buildDefaultSkillDirs("C:/proj").filter((d) => d.source === "codex" && d.scope === "global");
207
+ expect(dirs.map((d) => d.dir)).toEqual([
208
+ join(require("node:os").homedir(), ".codex", "skills"),
209
+ join(require("node:os").homedir(), ".agents", "skills"),
210
+ ]);
211
+ });
212
+ });
213
+
214
+ describe("buildSkillsIndexPrompt", () => {
215
+ it("renders index with source markers and the skill creation convention", () => {
216
+ const prompt = buildSkillsIndexPrompt([
217
+ {
218
+ name: "feishu-doc",
219
+ description: "涓嬭浇椋炰功鏂囨。",
220
+ skillPath: "C:/x/feishu-doc/SKILL.md",
221
+ source: "codex",
222
+ scope: "global",
223
+ },
224
+ ]);
225
+
226
+ expect(prompt).toContain("## Available Skills");
227
+ expect(prompt).toContain("**feishu-doc**");
228
+ expect(prompt).toContain("[codex:global]");
229
+ expect(prompt).toContain("## Creating Skills");
230
+ expect(prompt).toContain(".deepccc/skills");
231
+ expect(prompt).toContain("read_file");
232
+ });
233
+
234
+ it("returns empty string for no skills", () => {
235
+ expect(buildSkillsIndexPrompt([])).toBe("");
236
+ });
237
+ });
238
+
239
+ describe("buildSkillTemplate", () => {
240
+ it("renders a Codex-style SKILL.md with frontmatter", () => {
241
+ const tpl = buildSkillTemplate("my-skill", "does something");
242
+ expect(tpl.startsWith("---")).toBe(true);
243
+ expect(tpl).toContain("name: my-skill");
244
+ expect(tpl).toContain("description: does something");
245
+ expect(tpl).toContain("# my-skill");
246
+ });
247
+
248
+ it("defaults description to empty when omitted", () => {
249
+ const tpl = buildSkillTemplate("bare-skill", "");
250
+ expect(tpl).toContain("description: ");
251
+ });
252
+ });
@@ -0,0 +1,220 @@
1
+ import { describe, expect, it } from "vitest";
2
+
3
+ import {
4
+ decodeDdgHref,
5
+ extractHtmlTitle,
6
+ htmlToPlainText,
7
+ parseDuckDuckGoHtml,
8
+ webFetchForTool,
9
+ webSearchForTool,
10
+ type FetchLike,
11
+ } from "../builtin/web-tools.ts";
12
+
13
+ const DDG_HTML = `<!DOCTYPE html>
14
+ <html>
15
+ <head><title>Search results</title></head>
16
+ <body>
17
+ <div class="result results_links results_links_deep web-result">
18
+ <h2 class="result__title">
19
+ <a rel="nofollow" class="result__a" href="//duckduckgo.com/l/?uddg=https%3A%2F%2Fnodejs.org%2Fen%2Fdocs&rut=abc">Node.js <b>Docs</b></a>
20
+ </h2>
21
+ <a rel="nofollow" class="result__snippet" href="//duckduckgo.com/l/?uddg=...">Official documentation for Node.js &amp; npm.</a>
22
+ </div>
23
+ <div class="result">
24
+ <a rel="nofollow" class="result__a" href="https://example.com/page">Example &quot;quoted&quot; page</a>
25
+ <a rel="nofollow" class="result__snippet" href="https://example.com/page">A plain snippet without highlight.</a>
26
+ </div>
27
+ </body>
28
+ </html>`;
29
+
30
+ const WEB_FETCH_HTML = `<!DOCTYPE html>
31
+ <html><head><title>Fetch &amp; Me</title></head>
32
+ <body>
33
+ <style>.x { color: red }</style>
34
+ <script>alert("x")</script>
35
+ <h1>Hello World</h1>
36
+ <p>First paragraph with &amp; entity.</p>
37
+ <p>Second paragraph<br>with a break.</p>
38
+ <footer>bye</footer>
39
+ </body></html>`;
40
+
41
+ describe("parseDuckDuckGoHtml", () => {
42
+ it("extracts title, decoded url, and snippet per result", () => {
43
+ const results = parseDuckDuckGoHtml(DDG_HTML);
44
+ expect(results).toHaveLength(2);
45
+ expect(results[0]).toEqual({
46
+ title: "Node.js Docs",
47
+ url: "https://nodejs.org/en/docs",
48
+ snippet: "Official documentation for Node.js & npm.",
49
+ });
50
+ expect(results[1]).toEqual({
51
+ title: 'Example "quoted" page',
52
+ url: "https://example.com/page",
53
+ snippet: "A plain snippet without highlight.",
54
+ });
55
+ });
56
+
57
+ it("returns empty array for pages without results", () => {
58
+ expect(parseDuckDuckGoHtml("<html><body>no results here</body></html>")).toEqual([]);
59
+ });
60
+ });
61
+
62
+ describe("decodeDdgHref", () => {
63
+ it("decodes uddg redirect params and restores protocol", () => {
64
+ expect(
65
+ decodeDdgHref("//duckduckgo.com/l/?uddg=https%3A%2F%2Fnodejs.org%2Fen%2Fdocs&rut=abc"),
66
+ ).toBe("https://nodejs.org/en/docs");
67
+ });
68
+
69
+ it("passes through plain urls", () => {
70
+ expect(decodeDdgHref("https://example.com/a?b=1")).toBe("https://example.com/a?b=1");
71
+ });
72
+
73
+ it("returns input untouched when unparseable", () => {
74
+ expect(decodeDdgHref("not a url")).toBe("not a url");
75
+ });
76
+ });
77
+
78
+ describe("htmlToPlainText", () => {
79
+ it("strips scripts/styles, keeps block boundaries, decodes entities, compresses whitespace", () => {
80
+ const text = htmlToPlainText(WEB_FETCH_HTML);
81
+ expect(text).not.toContain("alert");
82
+ expect(text).not.toContain(".x {");
83
+ expect(text).toContain("Hello World");
84
+ expect(text).toContain("First paragraph with & entity.");
85
+ expect(text).toContain("Second paragraph\nwith a break.");
86
+ expect(text).toContain("bye");
87
+ // 段落间允许单个空行,但不得出现连续空行
88
+ expect(text).not.toContain("\n\n\n");
89
+ });
90
+ });
91
+
92
+ describe("extractHtmlTitle", () => {
93
+ it("extracts and decodes the title", () => {
94
+ expect(extractHtmlTitle(WEB_FETCH_HTML)).toBe("Fetch & Me");
95
+ });
96
+
97
+ it("returns empty string when no title", () => {
98
+ expect(extractHtmlTitle("<html><body>x</body></html>")).toBe("");
99
+ });
100
+ });
101
+
102
+ describe("webSearchForTool", () => {
103
+ function mockFetch(html: string, status = 200): FetchLike {
104
+ return async () =>
105
+ new Response(html, {
106
+ status,
107
+ headers: { "content-type": "text/html; charset=utf-8" },
108
+ });
109
+ }
110
+
111
+ it("returns parsed results from the search page", async () => {
112
+ const output = await webSearchForTool(
113
+ { query: "nodejs docs" },
114
+ { fetchImpl: mockFetch(DDG_HTML) },
115
+ );
116
+ expect(output.query).toBe("nodejs docs");
117
+ expect(output.results).toHaveLength(2);
118
+ expect(output.results[0].url).toBe("https://nodejs.org/en/docs");
119
+ expect(output.results[0].snippet).toContain("Node.js");
120
+ expect(typeof output.durationMs).toBe("number");
121
+ });
122
+
123
+ it("respects maxResults and caps at 10", async () => {
124
+ const html = Array.from({ length: 12 }, (_, i) => {
125
+ const title = `<a rel="nofollow" class="result__a" href="https://e.com/${i}">R${i}</a>`;
126
+ const snippet = `<a rel="nofollow" class="result__snippet" href="https://e.com/${i}">s${i}</a>`;
127
+ return `<div>${title}${snippet}</div>`;
128
+ }).join("");
129
+ const output = await webSearchForTool({ query: "many" }, { fetchImpl: mockFetch(html) });
130
+ expect(output.results).toHaveLength(5);
131
+ expect(output.truncated).toBe(true);
132
+
133
+ const output2 = await webSearchForTool({ query: "many", maxResults: 20 }, { fetchImpl: mockFetch(html) });
134
+ expect(output2.results).toHaveLength(10);
135
+ });
136
+
137
+ it("returns empty results (not an error) when the page has no matches", async () => {
138
+ const output = await webSearchForTool(
139
+ { query: "zzz-nothing" },
140
+ { fetchImpl: mockFetch("<html><body>no results</body></html>") },
141
+ );
142
+ expect(output.results).toEqual([]);
143
+ expect(output.truncated).toBe(false);
144
+ });
145
+
146
+ it("throws on empty query", async () => {
147
+ await expect(webSearchForTool({ query: " " }, { fetchImpl: mockFetch("") })).rejects.toThrow(
148
+ "query is required",
149
+ );
150
+ });
151
+
152
+ it("throws on non-2xx response", async () => {
153
+ await expect(
154
+ webSearchForTool({ query: "x" }, { fetchImpl: mockFetch("blocked", 429) }),
155
+ ).rejects.toThrow("HTTP 429");
156
+ });
157
+ });
158
+
159
+ describe("webFetchForTool", () => {
160
+ function mockFetch(html: string, status = 200, contentType = "text/html; charset=utf-8"): FetchLike {
161
+ return async () =>
162
+ new Response(html, {
163
+ status,
164
+ headers: { "content-type": contentType },
165
+ });
166
+ }
167
+
168
+ it("fetches and converts html to plain text with title", async () => {
169
+ const output = await webFetchForTool(
170
+ { url: "https://example.com/page" },
171
+ { fetchImpl: mockFetch(WEB_FETCH_HTML) },
172
+ );
173
+ expect(output.title).toBe("Fetch & Me");
174
+ expect(output.text).toContain("Hello World");
175
+ expect(output.text).toContain("Second paragraph\nwith a break.");
176
+ expect(output.text).not.toContain("alert");
177
+ expect(output.contentType).toContain("text/html");
178
+ expect(output.chars).toBe(output.text.length);
179
+ expect(output.truncated).toBe(false);
180
+ });
181
+
182
+ it("truncates text beyond maxChars", async () => {
183
+ const output = await webFetchForTool(
184
+ { url: "https://example.com/long", maxChars: 10 },
185
+ { fetchImpl: mockFetch("<p>hello world and more</p>") },
186
+ );
187
+ expect(output.text).toBe("hello worl");
188
+ expect(output.truncated).toBe(true);
189
+ expect(output.chars).toBe(10);
190
+ });
191
+
192
+ it("truncates oversized response bodies", async () => {
193
+ const big = `<!DOCTYPE html><html><body><p>${"a".repeat(600 * 1024)}</p></body></html>`;
194
+ const output = await webFetchForTool(
195
+ { url: "https://example.com/big" },
196
+ { fetchImpl: mockFetch(big) },
197
+ );
198
+ expect(output.truncated).toBe(true);
199
+ expect(output.text.length).toBeLessThan(600 * 1024);
200
+ });
201
+
202
+ it("rejects non-http(s) protocols", async () => {
203
+ await expect(
204
+ webFetchForTool({ url: "file:///etc/passwd" }, { fetchImpl: mockFetch("") }),
205
+ ).rejects.toThrow("unsupported protocol");
206
+ });
207
+
208
+ it("rejects invalid urls", async () => {
209
+ await expect(
210
+ webFetchForTool({ url: "not a url" }, { fetchImpl: mockFetch("") }),
211
+ ).rejects.toThrow("invalid URL");
212
+ });
213
+
214
+ it("throws on missing url and non-2xx", async () => {
215
+ await expect(webFetchForTool({ url: " " })).rejects.toThrow("url is required");
216
+ await expect(
217
+ webFetchForTool({ url: "https://example.com/404" }, { fetchImpl: mockFetch("nf", 404) }),
218
+ ).rejects.toThrow("HTTP 404");
219
+ });
220
+ });
@@ -1,18 +1,18 @@
1
- import { describe, expect, it } from "vitest";
2
-
3
- import { resolveFeishuCardActionChatType } from "../card-action-routing.ts";
4
-
5
- describe("resolveFeishuCardActionChatType", () => {
6
- it("keeps card commands in a persisted private chat on the p2p route", () => {
7
- expect(resolveFeishuCardActionChatType("private-chat", {
8
- "private-chat": { chatType: "p2p" },
9
- })).toBe("p2p");
10
- });
11
-
12
- it("defaults unknown and group chats to the group route", () => {
13
- expect(resolveFeishuCardActionChatType("group-chat", {
14
- "group-chat": { chatType: "group" },
15
- })).toBe("group");
16
- expect(resolveFeishuCardActionChatType("unknown-chat", {})).toBe("group");
17
- });
18
- });
1
+ import { describe, expect, it } from "vitest";
2
+
3
+ import { resolveFeishuCardActionChatType } from "../card-action-routing.ts";
4
+
5
+ describe("resolveFeishuCardActionChatType", () => {
6
+ it("keeps card commands in a persisted private chat on the p2p route", () => {
7
+ expect(resolveFeishuCardActionChatType("private-chat", {
8
+ "private-chat": { chatType: "p2p" },
9
+ })).toBe("p2p");
10
+ });
11
+
12
+ it("defaults unknown and group chats to the group route", () => {
13
+ expect(resolveFeishuCardActionChatType("group-chat", {
14
+ "group-chat": { chatType: "group" },
15
+ })).toBe("group");
16
+ expect(resolveFeishuCardActionChatType("unknown-chat", {})).toBe("group");
17
+ });
18
+ });