Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
chore(plugins): 市场发现跳过插件条目时记录原因与位置 (#1524)
zhanghengxd69db93af4fac
diff --git a/apps/desktop/src/main/plugin-market/__tests__/sources-discover.test.ts b/apps/desktop/src/main/plugin-market/__tests__/sources-discover.test.tsindex 2774972c2e..f718e43eec 100644--- a/apps/desktop/src/main/plugin-market/__tests__/sources-discover.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/sources-discover.test.ts@@ -2,7 +2,20 @@ import fs from 'node:fs';import os from 'node:os';import path from 'node:path';-import { afterEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++// 跳过明细只落日志(不进返回值、不进 IPC),所以断言必须打在 logger 上。+const mocks = vi.hoisted(() => ({ warn: vi.fn() }));+vi.mock('../../logger.js', () => ({+ createLogger: () => ({+ trace: vi.fn(),+ debug: vi.fn(),+ info: vi.fn(),+ warn: mocks.warn,+ error: vi.fn(),+ fatal: vi.fn(),+ }),+}));import { discoverMarketplace } from '../sources/discover';@@ -23,6 +36,10 @@ const canSymlink = (() => {}})();+beforeEach(() => {+ mocks.warn.mockClear();+});+afterEach(() => {for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true });});@@ -57,6 +74,33 @@ function writeManifest(root: string, manifest: unknown, rel = '.agents/plugins/mfs.writeFileSync(file, typeof manifest === 'string' ? manifest : JSON.stringify(manifest));}+/** LF / CR / NEL / LINE SEPARATOR / PARAGRAPH SEPARATOR 的码位。 */+const LINE_BREAK_CODE_POINTS = [0x0a, 0x0d, 0x85, 0x2028, 0x2029];++/**+ * 读最后一次跳过日志。顺带锁住两件事:payload 是**字符串**、且是**单个物理行**。+ * main logger 走 util.format,传对象会被 util.inspect 按 breakLength 展开——实测+ * 1 条明细 15 个物理行、20 条 129 行,续行还丢掉时间戳/级别/scope。+ */+function lastSkipLog(): {+ market: string;+ declared: number;+ accepted: number;+ skippedCount: number;+ unreadableCount: number;+ entries: Array<{ index: number; path?: string; reason: string; errno?: string }>;+ detailsTruncated?: number;+} {+ const call = mocks.warn.mock.calls.at(-1);+ expect(call?.[0]).toBe('marketplace skipped plugin entries');+ const json = call?.[1];+ expect(typeof json).toBe('string');+ for (const cp of LINE_BREAK_CODE_POINTS) {+ expect(json as string).not.toContain(String.fromCharCode(cp));+ }+ return JSON.parse(json as string);+}+describe('discoverMarketplace', () => {it('discovers plugins from the primary manifest location', async () => {const root = makeRoot();@@ -396,4 +440,96 @@ describe('discoverMarketplace', () => {writeManifest(root2, { name: 'x', plugins: {} });expect((await discoverMarketplace(root2)).ok).toBe(false);});++ it('logs why an entry was skipped when the plugin directory has no ghost.json', async () => {+ const root = makeRoot();+ writeManifest(root, { name: 'sub-market', plugins: [{ source: './plugins/dep' }] });+ // Git submodule 未递归检出的形态:目录在,ghost.json 不在。市场 clone 不带+ // --recurse-submodules,所以这是"市场发现出 0 个插件"最常见的成因。+ fs.mkdirSync(path.join(root, 'plugins', 'dep'), { recursive: true });+ fs.writeFileSync(path.join(root, '.gitmodules'), '[submodule "plugins/dep"]');++ const result = await discoverMarketplace(root);++ // 既有事实不变:清单本身合法,来源照旧可用,条目静默跳过——没有任何错误码。+ expect(result.ok).toBe(true);+ if (!result.ok) return;+ expect(result.marketplace.plugins).toHaveLength(0);+ expect(result.marketplace.skippedCount).toBe(1);+ expect(result.marketplace.unreadableCount).toBe(0);+ // 唯一的新增:排查者能定位到是第几条、哪个路径、为什么。path 是清单自报的+ // repo-relative 路径原样回显(逻辑路径,不跟随宿主分隔符)。+ const logged = lastSkipLog();+ expect(logged.market).toBe('sub-market');+ expect(logged.declared).toBe(1);+ expect(logged.accepted).toBe(0);+ expect(logged.skippedCount).toBe(1);+ expect(logged.entries).toEqual([+ { index: 0, path: './plugins/dep', reason: 'manifest-missing', errno: 'ENOENT' },+ ]);+ });++ it('does not claim a bounded-read rejection is a non-regular file', async () => {+ const root = makeRoot();+ const bigDir = path.join(root, 'plugins', 'big');+ fs.mkdirSync(bigDir, { recursive: true });+ // 超过 GHOST_MANIFEST_MAX_BYTES:限量读取闸返回 null,与"非普通文件""根内复核+ // 不过"共用同一个信号。reason 因此不得对文件类型下断言,否则排障者会去查+ // symlink / 文件类型,而真因是体积。+ fs.writeFileSync(+ path.join(bigDir, 'ghost.json'),+ `{"schemaVersion":2,"id":"big","pad":"${'x'.repeat(600 * 1024)}"}`,+ );+ writeManifest(root, { name: 'sized-log', plugins: [{ source: 'plugins/big' }] });++ const result = await discoverMarketplace(root);++ expect(result.ok).toBe(true);+ if (!result.ok) return;+ expect(result.marketplace.skippedCount).toBe(1);+ expect(lastSkipLog().entries[0]?.reason).toBe('manifest-bounded-read-rejected');+ });++ it('strips unicode line separators from logged paths and market names', async () => {+ const root = makeRoot();+ // U+2028 / U+2029 / NEL 不在 C0 与双向控制符集合里,JSON.stringify 也不转义它们,+ // 查看器却按换行渲染 —— 不剥离就能把一行 warn 劈成攻击者控制的多行。+ const ls = String.fromCharCode(0x2028);+ const ps = String.fromCharCode(0x2029);+ const nel = String.fromCharCode(0x85);+ const hostileRel = `plugins/a${ls}fake-log-line${ps}b${nel}c`;+ // 市场名同源同险:它那道准入闸(FORBIDDEN_NAME_CHARS)不含这三个码位,所以带+ // 换行的名字能通过校验,日志侧必须自己消毒。+ const hostileName = `mkt${ls}fake-log-line`;+ writeManifest(root, { name: hostileName, plugins: [{ source: hostileRel }] });++ const result = await discoverMarketplace(root);++ expect(result.ok).toBe(true);+ if (!result.ok) return;+ expect(result.marketplace.skippedCount).toBe(1);+ // 准入判据未改:名字照旧被接受,只是进日志前被剥离。+ expect(result.marketplace.name).toBe(hostileName);+ const logged = lastSkipLog();+ expect(logged.entries[0]?.path).toBe('plugins/afake-log-linebc');+ expect(logged.market).toBe('mktfake-log-line');+ });++ it('caps skip details and reports how many were dropped', async () => {+ const root = makeRoot();+ // 损坏或恶意清单可有数百条非法条目;发现会被列表/快照/详情反复调用,明细必须限量。+ writeManifest(root, {+ name: 'noisy',+ plugins: Array.from({ length: 25 }, () => 'not-an-object'),+ });++ const result = await discoverMarketplace(root);++ expect(result.ok).toBe(true);+ if (!result.ok) return;+ expect(result.marketplace.skippedCount).toBe(25);+ const logged = lastSkipLog();+ expect(logged.entries).toHaveLength(20);+ expect(logged.detailsTruncated).toBe(5);+ });});diff --git a/apps/desktop/src/main/plugin-market/sources/discover.ts b/apps/desktop/src/main/plugin-market/sources/discover.tsindex 6d80c85dd4..e2c6994caa 100644--- a/apps/desktop/src/main/plugin-market/sources/discover.ts+++ b/apps/desktop/src/main/plugin-market/sources/discover.ts@@ -6,11 +6,15 @@* 清单里的描述性字段不作为事实来源——展示与安装一律以 ghost.json 为准。** 容错策略与 Codex 一致:单个插件条目非法只跳过并记日志,不让整个市场不可用。+ * 跳过在每次发现结束时汇总成**一个物理行**的 warn(条目下标 + 相对路径 + 原因 ++ * errno,payload 自行 JSON 序列化,理由见调用处)——跳过是逐条发生的,逐条打会被+ * 反复调用的发现路径放大成日志洪水。*/import fs from 'node:fs';import path from 'node:path';import { validateGhostManifest, type GhostManifest } from '../../../shared/ghost.js';+import { createLogger } from '../../logger.js';import {GHOST_MANIFEST_MAX_BYTES,readBoundedFileFollowLinks,@@ -18,6 +22,8 @@ import {} from '../../utils/readBoundedFile.js';import { redactAbsolutePaths } from './git.js';+const log = createLogger('plugin-market-discover');+/** 与 Codex 相同的清单位置,按优先级查找。 */export const MARKETPLACE_MANIFEST_PATHS = ['.agents/plugins/marketplace.json',@@ -42,6 +48,16 @@ const MARKETPLACE_MAX_PLUGIN_ENTRIES = 512;/** 市场名上限:进 store 持久化、进 pluginId、进 UI,不能不设边界。 */const MARKET_NAME_MAX_CHARS = 128;+/**+ * 单次发现最多记录多少条跳过明细。跳过是**逐条**发生的,而发现会被列表/快照/详情+ * 反复调用——不限量时一份数百条非法条目的清单每次都刷同样多的日志行。超出的条数在+ * 同一行里以 detailsTruncated 如实标注,不静默丢弃。+ */+const SKIP_LOG_DETAIL_LIMIT = 20;++/** 明细里相对路径的截断上限:清单自报的路径同样不受信,不能无界进日志。 */+const SKIP_LOG_TEXT_MAX_CHARS = 200;+/** 控制字符与双向文本控制符不允许出现在市场名里,防 UI 欺骗与日志注入。 */// eslint-disable-next-line no-control-regexconst FORBIDDEN_NAME_CHARS = /[\u0000-\u001f\u007f\u200e\u200f\u202a-\u202e\u2066-\u2069]/;@@ -147,8 +163,53 @@ function pluginEntryRelativePath(source: unknown): string | null {*/type PluginDirResolution =| { kind: 'ok'; plugin: DiscoveredMarketPlugin }- | { kind: 'invalid' }- | { kind: 'unreadable' };+ // 两种失败必须是**各自独立**的联合成员:合并成 kind: 'invalid' | 'unreadable'+ // 就不再是可辨识联合,调用方逐个排除 kind 后收窄不到 'ok'。+ | ({ kind: 'invalid' } & PluginSkipInfo)+ | ({ kind: 'unreadable' } & PluginSkipInfo);++/**+ * 跳过原因。**只用于日志**:计数与控制流仍只看 `kind`,这里的细分不参与任何判定,+ * 因此新增取值不影响调用方。+ *+ * 粒度按"排查时需要区分的事实"划分,几个关键区分:+ * - `dir-missing`(目录本身不存在)与 `manifest-missing`(目录在、`ghost.json` 不在)+ * 必须分开:后者是市场仓库把插件目录做成了 **Git submodule** 的典型表现——克隆不+ * 递归 submodule,留下的空目录会让整个市场发现出 0 个插件,而清单本身完全合法,+ * 没有任何错误码会被触发(见 sources/git.ts:无 --recurse-submodules)。只记+ * "invalid" 时排查者无从判断是哪一种。+ * - `manifest-symlink-rejected` 是 O_NOFOLLOW 拒掉符号链接的结果,属攻击面,不该+ * 与普通的读取失败混在一起。+ * - `manifest-unreadable` **只用于事实不明**(kind === 'unreadable':文件锁、权限、+ * 网络盘抖动)。永久性的打开失败(ENOTDIR / EISDIR 等)走 `manifest-open-failed`——+ * 否则新增的诊断会把结构损坏说成"暂时读不到",排障者按瞬时故障处理、干等恢复。+ * - `manifest-bounded-read-rejected` 是限量读取闸返回 null,**三种成因**:非普通+ * 文件、超过 GHOST_MANIFEST_MAX_BYTES、根内复核不过(Windows 无 O_NOFOLLOW 时+ * 的符号链接与 dev/ino 不匹配也在此)。闸只给"拒了"这一个信号,不带原因,所以+ * reason 名不对文件类型下断言;要细分得先改 readBoundedFile* 的返回契约,那会+ * 牵动发现/安装/打包三条共用链路,不属本次范围。+ */+type PluginSkipReason =+ | 'entry-not-object'+ | 'source-unsupported'+ | 'path-not-relative'+ | 'escapes-root'+ | 'dir-missing'+ | 'dir-unresolvable'+ | 'manifest-missing'+ | 'manifest-symlink-rejected'+ | 'manifest-bounded-read-rejected'+ | 'manifest-open-failed'+ | 'manifest-unreadable'+ | 'manifest-unparsable'+ | 'manifest-invalid'+ | 'duplicate-ghost-id';++interface PluginSkipInfo {+ reason: PluginSkipReason;+ /** 底层 errno(有则带上):同一 reason 下 EACCES 与 EIO 的处置完全不同。 */+ errno?: string;+}/*** 可重试的文件系统错误码 = 事实不明。@@ -176,17 +237,78 @@ function classifyFsFailure(error: unknown): 'invalid' | 'unreadable' {return code && TRANSIENT_FS_CODES.has(code) ? 'unreadable' : 'invalid';}+function errnoOf(error: unknown): string | undefined {+ const code = (error as NodeJS.ErrnoException | null)?.code;+ return typeof code === 'string' && code.length > 0 ? code : undefined;+}++/** ghost.json 读取失败的日志原因(仅日志,不参与判定)。 */+function manifestReadReason(+ kind: 'invalid' | 'unreadable',+ errno: string | undefined,+): PluginSkipReason {+ if (kind === 'unreadable') return 'manifest-unreadable';+ // 目录在、ghost.json 不在:submodule 未检出的典型形态(见 PluginSkipReason)。+ if (errno === 'ENOENT') return 'manifest-missing';+ // O_NOFOLLOW 平台对符号链接的拒绝。Windows 没有该 flag,回退闸走 lstat+dev/ino+ // 并**返回 null**(不抛),因此那边的符号链接落在 manifest-bounded-read-rejected。+ if (errno === 'ELOOP') return 'manifest-symlink-rejected';+ // 到这里 kind 必为 'invalid':是**永久**的打开失败(ENOTDIR / EISDIR / 无 errno 的+ // 异常等)。绝不能回落到 manifest-unreadable —— 那个 reason 专表事实不明。+ return 'manifest-open-failed';+}++/**+ * Unicode 换行类:NEL(U+0085)、LINE SEPARATOR(U+2028)、PARAGRAPH SEPARATOR(U+2029)。+ *+ * 它们不在 C0/DEL 与双向控制符集合里,但日志序列化(JSON.stringify 与 util.inspect+ * 都不转义这三个码位)会原样写出,查看器与终端普遍按换行渲染 —— 于是不受信路径能把+ * 一行 warn 劈成攻击者控制的多行,正是本消毒声称要挡住的东西。+ *+ * 只补在**日志剥离**侧,不动 FORBIDDEN_NAME_CHARS:那是市场名的准入判据,往里加字符+ * 会改变"哪些市场名被拒绝",属于内容判据变更(可能影响存量市场),不在本次范围内。+ */+const LOG_UNSAFE_LINE_BREAKS = '\\u0085\\u2028\\u2029';++/**+ * 把清单自报的相对路径写进日志前消毒:换行能伪造出额外的日志行,双向控制符能让路径+ * 显示成另一个位置。字符类取自 FORBIDDEN_NAME_CHARS(市场名那道校验闸)再并上 Unicode+ * 换行类,改为带 g 的**剥离**——与那道闸共用同一份来源,不各自抄一遍。市场名出现即拒,+ * 路径不能拒:它是跳过原因的关键线索。+ */+const LOG_UNSAFE_CHARS = new RegExp(+ `${FORBIDDEN_NAME_CHARS.source}|[${LOG_UNSAFE_LINE_BREAKS}]`,+ 'g',+);++/** 清单自报的任意文本(条目路径、市场名)进日志前一律过这里。 */+function logSafeText(value: string): string {+ return value.replace(LOG_UNSAFE_CHARS, '').slice(0, SKIP_LOG_TEXT_MAX_CHARS);+}++/** 把 classifyFsFailure 的结论装成解析结果:kind 是变量,联合成员要显式分流。 */+function skippedBy(+ kind: 'invalid' | 'unreadable',+ reason: PluginSkipReason,+ errno: string | undefined,+): PluginDirResolution {+ const info: PluginSkipInfo = { reason, ...(errno ? { errno } : {}) };+ return kind === 'invalid' ? { kind: 'invalid', ...info } : { kind: 'unreadable', ...info };+}+async function resolvePluginDir(marketRoot: string,relPath: string,): Promise<PluginDirResolution> {const trimmed = relPath.trim();if (!trimmed || path.isAbsolute(trimmed) || /^[A-Za-z]:/.test(trimmed)) {- return { kind: 'invalid' };+ return { kind: 'invalid', reason: 'path-not-relative' };}const dir = path.resolve(marketRoot, trimmed);const rootWithSep = marketRoot.endsWith(path.sep) ? marketRoot : `${marketRoot}${path.sep}`;- if (dir !== marketRoot && !dir.startsWith(rootWithSep)) return { kind: 'invalid' };+ if (dir !== marketRoot && !dir.startsWith(rootWithSep)) {+ return { kind: 'invalid', reason: 'escapes-root' };+ }let realRoot: string;let realDir: string;@@ -198,10 +320,20 @@ async function resolvePluginDir(fs.promises.realpath(dir),]);} catch (error) {- return { kind: classifyFsFailure(error) };+ const kind = classifyFsFailure(error);+ const errno = errnoOf(error);+ // ENOENT 是"清单指向的目录不存在"(市场删了插件却没更新 marketplace.json);+ // 其余(ELOOP/ENOTDIR/权限等)统一归为解析不了。+ return skippedBy(+ kind,+ kind === 'invalid' && errno === 'ENOENT' ? 'dir-missing' : 'dir-unresolvable',+ errno,+ );}const realRootWithSep = realRoot.endsWith(path.sep) ? realRoot : `${realRoot}${path.sep}`;- if (realDir !== realRoot && !realDir.startsWith(realRootWithSep)) return { kind: 'invalid' };+ if (realDir !== realRoot && !realDir.startsWith(realRootWithSep)) {+ return { kind: 'invalid', reason: 'escapes-root' };+ }let raw: unknown;try {@@ -216,15 +348,18 @@ async function resolvePluginDir(GHOST_MANIFEST_MAX_BYTES,realRoot,);- // null = 非普通文件 / 超限 / 根内复核不过:都是内容判据,属永久非法。- if (raw === null) return { kind: 'invalid' };+ // null = 非普通文件 / 超限 / 根内复核不过:都是内容判据,属永久非法。闸不区分+ // 三者,reason 也不下断言(见 PluginSkipReason)。+ if (raw === null) return { kind: 'invalid', reason: 'manifest-bounded-read-rejected' };} catch (error) {// JSON 解析失败是内容非法;fs 错误按可重试性分类。- if (error instanceof SyntaxError) return { kind: 'invalid' };- return { kind: classifyFsFailure(error) };+ if (error instanceof SyntaxError) return { kind: 'invalid', reason: 'manifest-unparsable' };+ const kind = classifyFsFailure(error);+ const errno = errnoOf(error);+ return skippedBy(kind, manifestReadReason(kind, errno), errno);}const validated = validateGhostManifest(raw);- if (!validated.ok) return { kind: 'invalid' };+ if (!validated.ok) return { kind: 'invalid', reason: 'manifest-invalid' };return {kind: 'ok',plugin: {@@ -332,14 +467,34 @@ export async function discoverMarketplace(marketRoot: string): Promise<DiscoverRconst seenGhostIds = new Set<string>();let skippedCount = 0;let unreadableCount = 0;- for (const entry of raw.plugins) {+ /**+ * 跳过明细,**只进日志**:计数与返回值不受影响。此前跳过是完全静默的——市场发现出+ * 0 个插件时,清单合法所以没有任何错误码,用户看到"0 个插件"、排查者连一行日志都+ * 没有。典型成因是插件目录被做成 Git submodule(克隆不递归,留下空目录)。+ */+ const skippedDetails: Array<{ index: number; path?: string } & PluginSkipInfo> = [];+ const noteSkip = (index: number, relPath: string | null, info: PluginSkipInfo): void => {+ if (skippedDetails.length >= SKIP_LOG_DETAIL_LIMIT) return;+ // 逐字段取,不展开 info:传进来的解析结论还带着 kind,展开会让日志字段随内部+ // 类型变化漂移。明细固定为 index / path / reason / errno。+ skippedDetails.push({+ index,+ ...(relPath === null ? {} : { path: logSafeText(relPath) }),+ reason: info.reason,+ ...(info.errno ? { errno: info.errno } : {}),+ });+ };+ for (const [index, entry] of raw.plugins.entries()) {if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {skippedCount += 1;+ noteSkip(index, null, { reason: 'entry-not-object' });continue;}const relPath = pluginEntryRelativePath((entry as Record<string, unknown>).source);if (!relPath) {skippedCount += 1;+ // 合法但 Phase 1 不支持的远程源(url / git-subdir / npm)也落这里。+ noteSkip(index, null, { reason: 'source-unsupported' });continue;}const resolved = await resolvePluginDir(marketRoot, relPath);@@ -347,15 +502,46 @@ export async function discoverMarketplace(marketRoot: string): Promise<DiscoverR// 事实不明:不能与"内容非法"共用静默跳过分支,否则调用方会把目录当完整,// 允许同 ghostId 的默认安装/手动安装在这个窗口里抢占所有权。unreadableCount += 1;+ noteSkip(index, relPath, resolved);continue;}- if (resolved.kind === 'invalid' || seenGhostIds.has(resolved.plugin.ghostId)) {+ if (resolved.kind === 'invalid') {skippedCount += 1;+ noteSkip(index, relPath, resolved);+ continue;+ }+ if (seenGhostIds.has(resolved.plugin.ghostId)) {+ skippedCount += 1;+ noteSkip(index, relPath, { reason: 'duplicate-ghost-id' });continue;}seenGhostIds.add(resolved.plugin.ghostId);plugins.push(resolved.plugin);}+ if (skippedCount > 0 || unreadableCount > 0) {+ const detailsTruncated = skippedCount + unreadableCount - skippedDetails.length;+ // payload 必须**自己**序列化成紧凑单行:main logger 走 util.format,对象参数会经+ // util.inspect 按 breakLength 展开 —— 实测 1 条明细写出 15 个物理行、20 条写出+ // 129 行,且续行不带时间戳/级别/scope。那既是本改动声称要避免的日志洪水,也会+ // 打断按行解析 main 日志的工具。字符串参数 util.format 直接拼接,恒为一行。+ //+ // 注意 JSON.stringify **不**转义 U+2028 / U+2029 / NEL(著名的 JSON-vs-JS 缺口),+ // 所以 market 与 path 仍各自过 logSafeText,不能指望这一层兜住。+ log.warn(+ 'marketplace skipped plugin entries',+ JSON.stringify({+ // name 与 path 同源(都来自不受信清单),消毒口径必须一致:市场名那道准入闸+ // 不含 Unicode 换行类,带这些码位的名字能通过校验再原样进日志。+ market: logSafeText(name),+ declared: raw.plugins.length,+ accepted: plugins.length,+ skippedCount,+ unreadableCount,+ entries: skippedDetails,+ ...(detailsTruncated > 0 ? { detailsTruncated } : {}),+ }),+ );+ }return {ok: true,