Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(cindy-tools): ghost_forge_guide 分章按需返回,修复整本必超结果上限 (#893)

张怡4b91f1754b51
diff --git a/packages/cindy-tools/src/__tests__/ghostMcp.test.ts b/packages/cindy-tools/src/__tests__/ghostMcp.test.ts
index a3adaee9b7..cd40a6be8f 100644
--- a/packages/cindy-tools/src/__tests__/ghostMcp.test.ts
+++ b/packages/cindy-tools/src/__tests__/ghostMcp.test.ts
@@ -903,12 +903,99 @@ describe("ghost_call · setup_plan MCP 边界", () => {
});
describe("cindy_ghosts · ghost_forge(锻造)", () => {
- it("forge_guide 原文返回手册(不 JSON 包裹,agent 直接读 markdown)", async () => {
+ it("forge_guide 无 ## 标题的短手册整本原样返回(退化路径,不 JSON 包裹)", async () => {
const result = await handleForgeGuide(fakeDeps());
expect(result.content[0].text).toBe("# 手册");
expect(result.isError).toBeUndefined();
});
+ it("forge_guide 退化手册 + 传 section 仍整本原样返回,不报未命中", async () => {
+ const result = await handleForgeGuide(fakeDeps(), { section: "4.7" });
+ expect(result.content[0].text).toBe("# 手册");
+ expect(result.isError).toBeUndefined();
+ });
+
+ it("forge_guide 空串/纯空白 section 视为未传,返回目录而非报错", async () => {
+ const blank = await handleForgeGuide(sectionedDeps(), { section: " " });
+ expect(blank.isError).toBeUndefined();
+ expect(blank.content[0].text).toContain("## 目录");
+ expect(blank.content[0].text).not.toContain("net-body");
+ });
+
+ // 分章手册:开场白 + 4 章,其中 4.6.1 也是 ## 级(与真实手册一致)
+ const SECTIONED_GUIDE = [
+ "# 手册",
+ "开场白一句。",
+ "## 1. 起步",
+ "one-body",
+ "## 4.6 订阅(subscribe 槽)",
+ "sub-body",
+ "## 4.6.1 出口钩子",
+ "hook-body",
+ "## 4.7 网络代发(network 槽)",
+ "net-body",
+ ].join("\n");
+ const sectionedDeps = () =>
+ fakeDeps({ forgeGuide: async () => SECTIONED_GUIDE });
+
+ it("forge_guide 无参返回目录:含开场白与全部章节标题,不含章节正文", async () => {
+ const result = await handleForgeGuide(sectionedDeps());
+ const text = result.content[0].text;
+ expect(result.isError).toBeUndefined();
+ expect(text).toContain("开场白一句。");
+ expect(text).toContain("## 目录");
+ expect(text).toContain("- 4.7 网络代发(network 槽)");
+ expect(text).toContain("- 4.6.1 出口钩子");
+ expect(text).not.toContain("net-body");
+ expect(text).not.toContain("one-body");
+ });
+
+ it("forge_guide 按章号取正文:含本章标题与正文,止于下一个 ## 标题", async () => {
+ const result = await handleForgeGuide(sectionedDeps(), { section: "4.6" });
+ const text = result.content[0].text;
+ expect(result.isError).toBeUndefined();
+ expect(text).toContain("## 4.6 订阅(subscribe 槽)");
+ expect(text).toContain("sub-body");
+ expect(text).not.toContain("hook-body");
+ });
+
+ it("forge_guide 按标题关键词取正文(大小写不敏感,唯一命中)", async () => {
+ const result = await handleForgeGuide(sectionedDeps(), {
+ section: "NETWORK",
+ });
+ expect(result.isError).toBeUndefined();
+ expect(result.content[0].text).toContain("net-body");
+ });
+
+ it("forge_guide 关键词命中多章标 isError 并列出歧义候选", async () => {
+ const result = await handleForgeGuide(sectionedDeps(), { section: "4.6" });
+ expect(result.isError).toBeUndefined(); // 章号精确匹配优先,不歧义
+ const ambiguous = await handleForgeGuide(sectionedDeps(), {
+ section: "钩子",
+ });
+ expect(ambiguous.isError).toBeUndefined(); // 唯一命中
+ const multi = await handleForgeGuide(sectionedDeps(), { section: "槽" });
+ expect(multi.isError).toBe(true);
+ expect(parsePayload(multi)).toMatchObject({
+ ok: false,
+ errorCode: "SECTION_NOT_FOUND",
+ });
+ expect((parsePayload(multi) as { message: string }).message).toContain(
+ "4.6 订阅(subscribe 槽)",
+ );
+ });
+
+ it("forge_guide 零命中标 isError 并列出全部可用章节", async () => {
+ const result = await handleForgeGuide(sectionedDeps(), {
+ section: "不存在的章",
+ });
+ expect(result.isError).toBe(true);
+ const payload = parsePayload(result) as { message: string };
+ expect(payload).toMatchObject({ ok: false, errorCode: "SECTION_NOT_FOUND" });
+ expect(payload.message).toContain("1. 起步");
+ expect(payload.message).toContain("4.7 网络代发(network 槽)");
+ });
+
it("forge_scaffold 透传模板和创建文件;目标存在时标 isError", async () => {
const okResult = await handleForgeScaffold(fakeDeps(), {
dir: "/src/my-ghost",
diff --git a/packages/cindy-tools/src/ghost/forgeGuideSections.ts b/packages/cindy-tools/src/ghost/forgeGuideSections.ts
new file mode 100644
index 0000000000..fb3a655eb8
--- /dev/null
+++ b/packages/cindy-tools/src/ghost/forgeGuideSections.ts
@@ -0,0 +1,105 @@
+/**
+ * ghost_forge_guide 的分章投递。
+ *
+ * 手册整本 ~120KB,必超单次 MCP 工具结果上限(见 #890),因此:
+ * 无参调用返回目录(开场白 + 全部章节标题 + 取章提示),传 section(章号或
+ * 标题关键词)返回单章正文。章 = 手册里的 `## ` 标题行,单章体量均在安全范围。
+ *
+ * 纯函数,不依赖 deps;对"没有任何 ## 标题"的退化输入按整本原样返回,
+ * 保持旧行为(短手册无需分章)。
+ */
+
+export interface ForgeGuideSectionHit {
+ ok: true;
+ text: string;
+}
+
+export interface ForgeGuideSectionMiss {
+ ok: false;
+ /** ambiguous=true 时是歧义候选,否则是全部可用章节标题 */
+ candidates: string[];
+ ambiguous: boolean;
+}
+
+export type ForgeGuideSectionResult = ForgeGuideSectionHit | ForgeGuideSectionMiss;
+
+const HEADER_PREFIX = "## ";
+
+/** 全部 `## ` 章节标题行(含前缀)。 */
+function headerLines(guide: string): string[] {
+ return guide.split("\n").filter((l) => l.startsWith(HEADER_PREFIX));
+}
+
+/** "## 4.7 网络代发(network 槽)" → "4.7";无章号返回 null。 */
+function headerNumber(header: string): string | null {
+ const m = header.match(/^## ([0-9]+(?:\.[0-9]+)*)\.?(?:\s|$)/);
+ return m ? m[1] : null;
+}
+
+/** 去掉 `## ` 前缀的标题文本,用于目录与错误提示。 */
+function headerTitle(header: string): string {
+ return header.slice(HEADER_PREFIX.length);
+}
+
+/** 目录:开场白 + 章节标题列表 + 取章提示。没有 ## 标题时整本原样返回。 */
+export function buildForgeGuideToc(guide: string): string {
+ const headers = headerLines(guide);
+ if (headers.length === 0) return guide;
+ const firstHeaderAt = guide.indexOf(`\n${HEADER_PREFIX}`);
+ const preamble = firstHeaderAt >= 0 ? guide.slice(0, firstHeaderAt).trimEnd() : "";
+ return [
+ ...(preamble ? [preamble, ""] : []),
+ "## 目录",
+ "",
+ ...headers.map((h) => `- ${headerTitle(h)}`),
+ "",
+ '整本手册超出单次工具结果上限,按需取章:再次调用并传 section,章号(如 {"section":"4.7"})或标题关键词(如 {"section":"network"})均可。',
+ ].join("\n");
+}
+
+/**
+ * 取单章正文:从命中的 `## ` 标题行(含)到下一个 `## ` 标题行(不含)。
+ * 匹配优先级:章号精确匹配(允许末尾多一个点) > 标题关键词包含(大小写不敏感)。
+ * 关键词命中多章返回歧义候选;零命中返回全部章节标题。
+ * 没有任何 `## ` 标题的退化手册无章可取,任何 query 都整本原样返回。
+ */
+export function extractForgeGuideSection(
+ guide: string,
+ query: string,
+): ForgeGuideSectionResult {
+ const lines = guide.split("\n");
+ const headerIdx: number[] = [];
+ lines.forEach((l, i) => {
+ if (l.startsWith(HEADER_PREFIX)) headerIdx.push(i);
+ });
+ if (headerIdx.length === 0) {
+ return { ok: true, text: guide };
+ }
+ const allTitles = headerIdx.map((i) => headerTitle(lines[i]));
+
+ const q = query.trim().replace(/\.$/, "");
+ if (!q) {
+ return { ok: false, candidates: allTitles, ambiguous: false };
+ }
+
+ const sliceAt = (pos: number): ForgeGuideSectionHit => {
+ const start = headerIdx[pos];
+ const end = pos + 1 < headerIdx.length ? headerIdx[pos + 1] : lines.length;
+ return { ok: true, text: lines.slice(start, end).join("\n").trimEnd() };
+ };
+
+ // 章号精确匹配
+ const byNumber = headerIdx.findIndex((i) => headerNumber(lines[i]) === q);
+ if (byNumber >= 0) return sliceAt(byNumber);
+
+ // 标题关键词包含
+ const ql = q.toLowerCase();
+ const byKeyword = headerIdx
+ .map((i, pos) => ({ pos, title: headerTitle(lines[i]) }))
+ .filter(({ title }) => title.toLowerCase().includes(ql));
+ if (byKeyword.length === 1) return sliceAt(byKeyword[0].pos);
+ if (byKeyword.length > 1) {
+ return { ok: false, candidates: byKeyword.map((k) => k.title), ambiguous: true };
+ }
+ return { ok: false, candidates: allTitles, ambiguous: false };
+}
diff --git a/packages/cindy-tools/src/ghost/mcpServer.ts b/packages/cindy-tools/src/ghost/mcpServer.ts
index 478308d729..f166347d35 100644
--- a/packages/cindy-tools/src/ghost/mcpServer.ts
+++ b/packages/cindy-tools/src/ghost/mcpServer.ts
@@ -9,6 +9,10 @@ import type {
CindyGhostSetupPlan,
CindyGhostsMcpDeps,
} from "../types.js";
+import {
+ buildForgeGuideToc,
+ extractForgeGuideSection,
+} from "./forgeGuideSections.js";
/**
* ghost 总机(docs/dev-rules/plugin-security-and-authoring.md 的网关模式):
@@ -57,9 +61,10 @@ const D_GHOST_CALL = [
const D_GHOST_FORGE_GUIDE = [
"获取《插件(Ghost)编写手册》——为用户制作/修改插件(.cindy 能力包)前必读。",
"手册随主机版本走,包含:ghost.json 身份卡全字段、十个卡槽、管子 API(cindy.send)、",
- '面板与主题、沙箱红线、打包与测试流程。用户说"帮我做一个 XX 插件 / 改一下某插件"时,',
- "先调本工具拿手册,新插件可用 ghost_forge_scaffold 生成骨架,修改完成后再用",
- "ghost_forge_pack 打包装入。",
+ "面板与主题、沙箱红线、打包与测试流程。整本超出单次工具结果上限,分章取用:",
+ '不传参数返回目录,传 section(章号如 "4.7" 或章标题关键词如 "network")返回单章正文。',
+ '用户说"帮我做一个 XX 插件 / 改一下某插件"时,先取目录、按需读相关章,',
+ "新插件可用 ghost_forge_scaffold 生成骨架,修改完成后再用 ghost_forge_pack 打包装入。",
].join("\n");
const D_GHOST_FORGE_SCAFFOLD = [
@@ -612,10 +617,29 @@ export async function handleGhostCall(
/** ghost_forge_guide 的 handler 主体(导出供单测)。 */
export async function handleForgeGuide(
deps: CindyGhostsMcpDeps,
+ input?: { section?: string },
): Promise<McpTextResult> {
try {
const guide = await deps.forgeGuide();
- return { content: [{ type: "text", text: guide }] };
+ // 空串/纯空白与未传等价:与工具描述"不传返回目录"一致
+ const section = input?.section?.trim();
+ if (!section) {
+ return { content: [{ type: "text", text: buildForgeGuideToc(guide) }] };
+ }
+ const hit = extractForgeGuideSection(guide, section);
+ if (hit.ok) {
+ return { content: [{ type: "text", text: hit.text }] };
+ }
+ return textResult(
+ {
+ ok: false,
+ errorCode: "SECTION_NOT_FOUND",
+ message: hit.ambiguous
+ ? `section "${section}" 命中多章,换更精确的章号:\n${hit.candidates.join("\n")}`
+ : `section "${section}" 未命中任何章节,可用章节:\n${hit.candidates.join("\n")}`,
+ },
+ true,
+ );
} catch (err) {
return textResult(
{
@@ -752,8 +776,16 @@ export function createCindyGhostsMcpServer(
handleGhostCall(deps, input, extractAgentToolUseId(extra)),
);
- server.tool("ghost_forge_guide", D_GHOST_FORGE_GUIDE, {}, async () =>
- handleForgeGuide(deps),
+ server.tool(
+ "ghost_forge_guide",
+ D_GHOST_FORGE_GUIDE,
+ {
+ section: z
+ .string()
+ .optional()
+ .describe('章号(如 "4.7")或章标题关键词(如 "network");不传返回目录'),
+ },
+ async (input) => handleForgeGuide(deps, input),
);
server.tool(