Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
refactor(plugin): simplify manual path handling
fmfsaisai374a8c3f4012
diff --git a/apps/desktop/src/main/cindy-brain/ghostManual.ts b/apps/desktop/src/main/cindy-brain/ghostManual.tsindex 64624a03d0..e7717c872c 100644--- a/apps/desktop/src/main/cindy-brain/ghostManual.ts+++ b/apps/desktop/src/main/cindy-brain/ghostManual.ts@@ -9,7 +9,10 @@ import {type GhostManualItem,type InstalledGhost,} from '../../shared/ghost.js';-import { readBoundedFileNoFollowWithSize } from '../utils/readBoundedFile.js';+import {+ isRealPathWithinRoot,+ readBoundedFileNoFollowWithStat,+} from '../utils/readBoundedFile.js';import {decodeGhostManualMarkdown,ghostManualLogicalPathForEntry,@@ -20,12 +23,6 @@ const MANUAL_CANDIDATE_MAX_ITEMS = 32;const MANUAL_CANDIDATE_MAX_BYTES = 4096;const MANUAL_SCAN_MAX_ENTRIES = 512;-function isWithinRoot(realPath: string, realRoot: string): boolean {- if (realPath === realRoot) return true;- const rootWithSep = realRoot.endsWith(path.sep) ? realRoot : `${realRoot}${path.sep}`;- return realPath.startsWith(rootWithSep);-}-function rootIndex(ghost: InstalledGhost): CindyGhostManualIndexItem[] {return (ghost.manifest.manual?.items ?? []).map(({ name, description }) => ({name,@@ -61,9 +58,13 @@ async function readManualFile(realUnitRoot: string,): Promise<{ ok: true; content: string } | { ok: false }> {try {- const read = await readBoundedFileNoFollowWithSize(absolutePath, GHOST_MANUAL_MD_MAX_BYTES, {- containWithin: realUnitRoot,- });+ const read = await readBoundedFileNoFollowWithStat(+ absolutePath,+ GHOST_MANUAL_MD_MAX_BYTES,+ {+ containWithin: realUnitRoot,+ },+ );if (read === null || read.bytes.byteLength !== read.expectedSize) return { ok: false };const decoded = decodeGhostManualMarkdown(read.bytes);return decoded.ok ? decoded : { ok: false };@@ -185,13 +186,40 @@ async function resolveUnitRoot(fs.promises.realpath(ghost.dir),fs.promises.realpath(unitRoot),]);- if (!isWithinRoot(realUnitRoot, realGhostRoot)) return null;+ if (!isRealPathWithinRoot(realUnitRoot, realGhostRoot)) return null;return { unitRoot, realUnitRoot };} catch {return null;}}+async function resolveManualEntry(+ ghost: InstalledGhost,+ item: GhostManualItem,+): Promise<+ | { ok: true; unitRoot: string; realUnitRoot: string; content: string }+ | { ok: false; result: CindyGhostManualResult }+> {+ const roots = await resolveUnitRoot(ghost, item);+ if (!roots) {+ return {+ ok: false,+ result: unavailable('插件声明的手册不可用;请更新或重装插件。'),+ };+ }+ const entry = await readManualFile(+ path.join(roots.unitRoot, GHOST_MANUAL_ENTRY_FILE),+ roots.realUnitRoot,+ );+ if (!entry.ok) {+ return {+ ok: false,+ result: unavailable('插件声明的手册入口不可用;请更新或重装插件。'),+ };+ }+ return { ok: true, ...roots, content: entry.content };+}+async function pathNotFoundWithUnitCandidates(message: string,item: GhostManualItem,@@ -249,49 +277,35 @@ export async function readInstalledGhostManual(if (!item) {return pathNotFound('手册路径不合法;请从返回索引选择可用路径。', index);}- const roots = await resolveUnitRoot(ghost, item);- if (!roots) return unavailable('插件声明的手册不可用;请更新或重装插件。');- const entry = await readManualFile(- path.join(roots.unitRoot, GHOST_MANUAL_ENTRY_FILE),- roots.realUnitRoot,- );- if (!entry.ok) return unavailable('插件声明的手册入口不可用;请更新或重装插件。');+ const resolved = await resolveManualEntry(ghost, item);+ if (!resolved.ok) return resolved.result;return pathNotFoundWithUnitCandidates('手册路径不合法;请从返回候选选择可用路径。',item,- roots.unitRoot,- roots.realUnitRoot,+ resolved.unitRoot,+ resolved.realUnitRoot,);}const item = ghost.manifest.manual?.items.find((candidate) => candidate.name === segments[0]);if (!item) {return pathNotFound('未找到该手册单元;请从返回索引选择可用路径。', index);}- const roots = await resolveUnitRoot(ghost, item);- if (!roots) {- return unavailable('插件声明的手册不可用;请更新或重装插件。');- }- const entry = await readManualFile(- path.join(roots.unitRoot, GHOST_MANUAL_ENTRY_FILE),- roots.realUnitRoot,- );- if (!entry.ok) {- return unavailable('插件声明的手册入口不可用;请更新或重装插件。');- }+ const resolved = await resolveManualEntry(ghost, item);+ if (!resolved.ok) return resolved.result;const relativeFile =segments.length === 1 ? GHOST_MANUAL_ENTRY_FILE : segments.slice(1).join('/');if (relativeFile === GHOST_MANUAL_ENTRY_FILE) {- return { ok: true, manual: [], content: entry.content };+ return { ok: true, manual: [], content: resolved.content };}if (ghostManualLogicalPathForEntry(item.name, relativeFile, 'file') === null) {return pathNotFoundWithUnitCandidates('手册路径未命中 Markdown 文件;请从返回候选选择。',item,- roots.unitRoot,- roots.realUnitRoot,+ resolved.unitRoot,+ resolved.realUnitRoot,);}- const parentState = await classifyRelativeParents(roots.unitRoot, relativeFile);+ const parentState = await classifyRelativeParents(resolved.unitRoot, relativeFile);if (parentState === 'unavailable') {return unavailable('插件声明的手册文件不可用;请更新或重装插件。');}@@ -299,11 +313,11 @@ export async function readInstalledGhostManual(return pathNotFoundWithUnitCandidates('未找到该手册文件;请从返回候选选择。',item,- roots.unitRoot,- roots.realUnitRoot,+ resolved.unitRoot,+ resolved.realUnitRoot,);}- const absolutePath = path.join(roots.unitRoot, ...relativeFile.split('/'));+ const absolutePath = path.join(resolved.unitRoot, ...relativeFile.split('/'));let exists: fs.Stats;try {exists = await fs.promises.lstat(absolutePath);@@ -314,8 +328,8 @@ export async function readInstalledGhostManual(return pathNotFoundWithUnitCandidates('未找到该手册文件;请从返回候选选择。',item,- roots.unitRoot,- roots.realUnitRoot,+ resolved.unitRoot,+ resolved.realUnitRoot,);}if (exists.isSymbolicLink()) {@@ -325,14 +339,14 @@ export async function readInstalledGhostManual(return pathNotFoundWithUnitCandidates('手册路径未命中 Markdown 文件;请从返回候选选择。',item,- roots.unitRoot,- roots.realUnitRoot,+ resolved.unitRoot,+ resolved.realUnitRoot,);}if (!exists.isFile()) {return unavailable('插件声明的手册文件不可用;请更新或重装插件。');}- const read = await readManualFile(absolutePath, roots.realUnitRoot);+ const read = await readManualFile(absolutePath, resolved.realUnitRoot);if (!read.ok) {return unavailable('插件声明的手册文件不可用;请更新或重装插件。');}diff --git a/apps/desktop/src/main/mcp-integrations/ghost.ts b/apps/desktop/src/main/mcp-integrations/ghost.tsindex a5cc554fd8..0bfe191c9a 100644--- a/apps/desktop/src/main/mcp-integrations/ghost.ts+++ b/apps/desktop/src/main/mcp-integrations/ghost.ts@@ -87,6 +87,8 @@ import { createLogger } from '../logger.js';const log = createLogger('mcp/cindy');const MAX_FORGE_ICON_SOURCE_BYTES = 25 * 1024 * 1024;+const GHOST_NO_TOOLS_MESSAGE =+ '该插件未声明任何可供调用的工具;不要重试,改用其它方式完成。';const convertForgeIconToPng = createForgeIconConverter({fork: forkForgeIconConversionHost,@@ -800,6 +802,10 @@ async function grantAttachmentUrls(params: {);}+function ghostHasTools(ghost: InstalledGhost): boolean {+ return (ghost.manifest.tools?.length ?? 0) > 0;+}+function visibleChipGhosts(workdir: string | null): InstalledGhost[] {return getGhostManager().list()@@ -808,7 +814,7 @@ function visibleChipGhosts(workdir: string | null): InstalledGhost[] {ghost.enabled &&isGhostAvailableForActiveSession(ghost.manifest.id) &&ghost.manifest.kind === 'chip' &&- (ghost.manifest.tools?.length ?? 0) > 0 &&+ ghostHasTools(ghost) &&!isGhostDisabledForWorkdir(ghost.manifest.id, workdir),);}@@ -936,7 +942,7 @@ export function getCindyGhostsMcpDeps(return {ok: false,errorCode: 'GHOST_NOT_FOUND',- message: '该插件未声明任何可供调用的工具;不要重试,改用其它方式完成。',+ message: GHOST_NO_TOOLS_MESSAGE,};},async readGhostManual({ ghostId, path: manualPath }) {@@ -951,13 +957,13 @@ export function getCindyGhostsMcpDeps(message: visibility.message,};}- if ((visibility.ghost.manifest.tools?.length ?? 0) === 0) {+ if (!ghostHasTools(visibility.ghost)) {return {ok: false,manual: [],content: '',errorCode: 'GHOST_NOT_FOUND',- message: '该插件未声明任何可供调用的工具;不要重试,改用其它方式完成。',+ message: GHOST_NO_TOOLS_MESSAGE,};}return readInstalledGhostManual(visibility.ghost, manualPath);diff --git a/apps/desktop/src/main/utils/readBoundedFile.ts b/apps/desktop/src/main/utils/readBoundedFile.tsindex bb7562cfa9..430e1c97df 100644--- a/apps/desktop/src/main/utils/readBoundedFile.ts+++ b/apps/desktop/src/main/utils/readBoundedFile.ts@@ -77,7 +77,7 @@ export class BoundedFileReadChangedError extends Error {}/** realpath 产物是否落在同为 realpath 产物的根内(含根本身)。 */-function isWithinRoot(realFilePath: string, realRoot: string): boolean {+export function isRealPathWithinRoot(realFilePath: string, realRoot: string): boolean {if (realFilePath === realRoot) return true;const rootWithSep = realRoot.endsWith(path.sep) ? realRoot : `${realRoot}${path.sep}`;return realFilePath.startsWith(rootWithSep);@@ -135,7 +135,7 @@ async function verifyStillWithinRoot(fs.promises.realpath(filePath),]);if (!sameInode(pathStat, handleStat)) return false;- return isWithinRoot(realFilePath, realRoot);+ return isRealPathWithinRoot(realFilePath, realRoot);} catch (error) {const code = (error as NodeJS.ErrnoException)?.code;if (code !== 'ENOENT' && code !== 'ENOTDIR' && code !== 'ELOOP') {@@ -220,17 +220,6 @@ export async function readBoundedFileNoFollowWithStat(}}-/**- * Manual 校验使用的兼容入口:保留同句柄 stat/稳定性复核,同时暴露读取前长度。- */-export async function readBoundedFileNoFollowWithSize(- filePath: string,- maxBytes: number,- options?: ReadBoundedFileOptions,-): Promise<BoundedFileRead | null> {- return readBoundedFileNoFollowWithStat(filePath, maxBytes, options);-}-export async function readBoundedFileNoFollow(filePath: string,maxBytes: number,@@ -292,7 +281,7 @@ export function readBoundedFileNoFollowSync(const pathStat = fs.statSync(filePath, { bigint: true });const realFilePath = fs.realpathSync(filePath);if (!sameInode(pathStat, stat)) return null;- if (!isWithinRoot(realFilePath, options.containWithin)) return null;+ if (!isRealPathWithinRoot(realFilePath, options.containWithin)) return null;} catch {return null;}