Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(plugins): 新增 skill 卡槽让插件捆绑 Agent Skills(Claude Code / Codex 双端生效) (#399)
Lizi43c234206ec8
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.tsindex 5973f11c54..24477e077e 100644--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts@@ -7,6 +7,7 @@ import JSZip from 'jszip';import {GHOST_MANIFEST_FILE,GHOST_LOCALE_MAX_BYTES,+ GHOST_SKILL_MD_MAX_BYTES,ghostLocalePathFor,ghostIconMimeType,isValidGhostId,@@ -24,6 +25,7 @@ import {type GhostTrustRegistry,} from './ghostSignature.js';import { isPathInsideDir } from './dirDeposit.js';+import { checkSkillMdConsistency } from './skillSlot.js';/** 普通沙箱插件维持小包上限;随包 Node/CLI 允许更大的预打包产物。 */const MAX_BASIC_CINDY_FILE_BYTES = 8 * 1024 * 1024;@@ -524,6 +526,41 @@ export class GhostManager {iconDataUrl = buildIconDataUrl(v.manifest.icon, iconData) ?? undefined;}+ // 5) skill 槽:声明的每个技能目录必须真有 SKILL.md,且 frontmatter 与清单+ // 声明逐字一致——确认框展示的必须就是 Agent 实际读到的,装入前把账算清。+ // 对未本地化的 v.manifest 校验即可:skill 字段不在本地化白名单+ // (GhostManifestLocaleResource)内,localizedManifest 与之恒等。+ for (const skillItem of v.manifest.skill?.items ?? []) {+ const relPath = `${skillItem.dir}/SKILL.md`;+ const skillEntry = zip.file(`${prefix}${relPath}`);+ if (!skillEntry) {+ return {+ rejection: { code: 'file-invalid', reason: `skill 条目声明了 ${skillItem.dir},但压缩包内缺少 ${relPath}` },+ };+ }+ let skillMd: Buffer;+ try {+ skillMd = await readZipEntryBufferWithLimit(+ skillEntry,+ GHOST_SKILL_MD_MAX_BYTES,+ `skill ${relPath}`,+ );+ } catch {+ return {+ rejection: {+ code: 'file-invalid',+ reason: `${relPath} 过大(上限 ${GHOST_SKILL_MD_MAX_BYTES} 字节)`,+ },+ };+ }+ const consistencyError = checkSkillMdConsistency(skillMd.toString('utf8'), skillItem);+ if (consistencyError) {+ return {+ rejection: { code: 'file-invalid', reason: `skill 条目 ${skillItem.dir}:${consistencyError}` },+ };+ }+ }+return {manifest: localizedManifest,trust: signature.trust,diff --git a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.tsindex c5e6ae326d..4de45e42a3 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts@@ -629,3 +629,65 @@ describe('GhostManager · update(原位换版)', () => {expect(manager.list().find((g) => g.manifest.id === 'hello')?.manifest.version).toBe('1.0.0');});});++describe('GhostManager · skill 槽装入校验(确认框看到的 = Agent 读到的)', () => {+ const skillManifest = (+ items: Array<Record<string, string>> = [+ { dir: 'skills/foo', name: 'foo', description: '教 Agent 用 foo' },+ ],+ ): Record<string, unknown> => ({+ ...goodManifest('skilled'),+ slots: ['tool', 'skill'],+ skill: { items },+ });+ const skillMd = (name: string, description: string, body = '正文'): string =>+ `---\nname: ${name}\ndescription: ${description}\n---\n\n${body}\n`;++ it('SKILL.md 在场且 frontmatter 与声明一致 → 装入,落盘为普通文件', async () => {+ const cindy = await makeCindy('skill-good.cindy', skillManifest(), {+ 'skills/foo/SKILL.md': skillMd('foo', '教 Agent 用 foo'),+ 'skills/foo/reference.md': '附带资料',+ });+ const result = await manager.install(cindy);+ expect('ghost' in result, JSON.stringify(result)).toBe(true);+ const landed = path.join(rootDir, 'skilled', 'skills', 'foo', 'SKILL.md');+ const st = await fs.promises.lstat(landed);+ expect(st.isFile()).toBe(true);+ expect(st.isSymbolicLink()).toBe(false);+ });++ it('声明的技能目录缺 SKILL.md → 拒装', async () => {+ const cindy = await makeCindy('skill-missing.cindy', skillManifest(), {+ 'skills/foo/notes.md': '没有 SKILL.md',+ });+ await expectRejection(await manager.install(cindy), 'file-invalid');+ });++ it('frontmatter name 与声明不一致 → 拒装', async () => {+ const cindy = await makeCindy('skill-name-drift.cindy', skillManifest(), {+ 'skills/foo/SKILL.md': skillMd('bar', '教 Agent 用 foo'),+ });+ await expectRejection(await manager.install(cindy), 'file-invalid');+ });++ it('frontmatter description 与声明不一致 → 拒装', async () => {+ const cindy = await makeCindy('skill-desc-drift.cindy', skillManifest(), {+ 'skills/foo/SKILL.md': skillMd('foo', '偷偷换一份说明'),+ });+ await expectRejection(await manager.install(cindy), 'file-invalid');+ });++ it('frontmatter 缺 description → 拒装', async () => {+ const cindy = await makeCindy('skill-no-desc.cindy', skillManifest(), {+ 'skills/foo/SKILL.md': '---\nname: foo\n---\n\n正文\n',+ });+ await expectRejection(await manager.install(cindy), 'file-invalid');+ });++ it('SKILL.md 超过字节上限 → 拒装', async () => {+ const cindy = await makeCindy('skill-huge.cindy', skillManifest(), {+ 'skills/foo/SKILL.md': skillMd('foo', '教 Agent 用 foo', 'x'.repeat(64 * 1024 + 1)),+ });+ await expectRejection(await manager.install(cindy), 'file-invalid');+ });+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.tsindex cc73bfc879..e5fadd1b69 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts@@ -463,8 +463,63 @@ describe('FORGE_GUIDE', () => {'在独立窗口中打开','minimize','最小化为浮动气泡',+ // 2026-07-25 skill 槽:随包捆绑 Agent Skills,声明一致性 + 全局作用域披露。+ '十四个卡槽',+ '捆绑 Agent Skills(skill 槽)',+ 'skill.items',+ 'SKILL.md',+ '~/.agents/skills',+ '逐字一致',+ '不受插件沙箱约束',]) {expect(FORGE_GUIDE).toContain(marker);}});});++describe('packGhostDir · skill 槽', () => {+ const SKILL_MANIFEST = {+ ...GOOD_MANIFEST,+ id: 'skilled',+ slots: ['tool', 'skill'],+ skill: { items: [{ dir: 'skills/foo', name: 'foo', description: '教 Agent 用 foo' }] },+ };+ const skillMd = (name: string, description: string) =>+ `---\nname: ${name}\ndescription: ${description}\n---\n\n正文\n`;++ it('happy path:SKILL.md 一致 → 打包,产物能被装入侧 inspect 认可', async () => {+ const dir = await makeSrcDir({+ 'ghost.json': JSON.stringify(SKILL_MANIFEST),+ 'main.js': '// brain',+ 'skills/foo/SKILL.md': skillMd('foo', '教 Agent 用 foo'),+ });+ const r = await packGhostDir(dir);+ expect(r.ok, JSON.stringify(r)).toBe(true);+ if (!r.ok) return;+ const manager = new GhostManager({ getRootDir: () => path.join(workDir, 'ghosts') });+ const inspected = await manager.inspect(r.cindyPath);+ expect(inspected).toMatchObject({+ manifest: { skill: { items: [{ dir: 'skills/foo', name: 'foo' }] } },+ });+ });++ it('声明的技能目录缺 SKILL.md → ENTRY_MISSING', async () => {+ const dir = await makeSrcDir({+ 'ghost.json': JSON.stringify(SKILL_MANIFEST),+ 'main.js': '// brain',+ 'skills/foo/notes.md': '不是 SKILL.md',+ });+ const r = await packGhostDir(dir);+ expect(r).toMatchObject({ ok: false, errorCode: 'ENTRY_MISSING' });+ });++ it('frontmatter 与清单声明漂移 → MANIFEST_INVALID(与装入侧同一契约)', async () => {+ const dir = await makeSrcDir({+ 'ghost.json': JSON.stringify(SKILL_MANIFEST),+ 'main.js': '// brain',+ 'skills/foo/SKILL.md': skillMd('foo', '偷偷换一份说明'),+ });+ const r = await packGhostDir(dir);+ expect(r).toMatchObject({ ok: false, errorCode: 'MANIFEST_INVALID' });+ });+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/skillSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/skillSlot.test.tsnew file mode 100644index 0000000000..753ee18550--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/skillSlot.test.ts@@ -0,0 +1,335 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import type { GhostManifest, InstalledGhost } from '../../../shared/ghost';+import { packGhostDir } from '../forge';+import { GhostManager } from '../GhostManager';+import {+ checkSkillMdConsistency,+ ghostSkillLinkName,+ reconcileGhostSkillLinks,+} from '../skillSlot';++/** 规则 23:测试路径一律 os.tmpdir;伪 home + 伪 brainRoot,互不污染。 */+let workDir: string;+let homeDir: string;+let brainRoot: string;++beforeEach(async () => {+ workDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-skill-slot-test-'));+ homeDir = path.join(workDir, 'home');+ brainRoot = path.join(workDir, 'owners', 'aaa', 'cindy-brain');+ await fs.promises.mkdir(homeDir, { recursive: true });+ await fs.promises.mkdir(brainRoot, { recursive: true });+});++afterEach(async () => {+ await fs.promises.rm(workDir, { recursive: true, force: true });+});++const sharedDir = () => path.join(homeDir, '.agents', 'skills');+const claudeDir = () => path.join(homeDir, '.claude', 'skills');++/** reconciler 只消费 manifest 数据,不跑校验——手工拼最小清单即可。 */+function ghost(+ id: string,+ skills: Array<{ dir: string; name: string; description?: string }>,+ opts: { enabled?: boolean } = {},+): InstalledGhost {+ const manifest = {+ schemaVersion: 2,+ id,+ name: id,+ version: '1.0.0',+ kind: 'chip',+ entry: 'main.js',+ slots: ['skill'],+ skill: {+ items: skills.map((s) => ({ ...s, description: s.description ?? '说明' })),+ },+ } as unknown as GhostManifest;+ return {+ manifest,+ dir: path.join(brainRoot, id),+ enabled: opts.enabled ?? true,+ };+}++/** 在 brainRoot 下造一个真实技能目录(含 SKILL.md)。 */+async function writeSkillDir(ghostId: string, rel: string, name = 'skill'): Promise<string> {+ const dir = path.join(brainRoot, ghostId, ...rel.split('/'));+ await fs.promises.mkdir(dir, { recursive: true });+ await fs.promises.writeFile(+ path.join(dir, 'SKILL.md'),+ `---\nname: ${name}\ndescription: 说明\n---\n\n正文\n`,+ );+ return dir;+}++function sameRealPath(a: string, b: string): boolean {+ const norm = (p: string) => {+ const real = fs.realpathSync(p);+ return process.platform === 'win32' ? real.toLowerCase() : real;+ };+ return norm(a) === norm(b);+}++describe('skillSlot · checkSkillMdConsistency', () => {+ const item = { dir: 'skills/foo', name: 'foo', description: '教 Agent 用 foo' };+ const md = (name: string, description: string) =>+ `---\nname: ${name}\ndescription: ${description}\n---\n\n正文\n`;++ it('逐字一致 → null;name/description 漂移 → 报错', () => {+ expect(checkSkillMdConsistency(md('foo', '教 Agent 用 foo'), item)).toBeNull();+ expect(checkSkillMdConsistency(md('bar', '教 Agent 用 foo'), item)).toContain('name');+ expect(checkSkillMdConsistency(md('foo', '换了说明'), item)).toContain('description');+ });++ it('frontmatter 缺字段/不可解析 → 报错', () => {+ expect(checkSkillMdConsistency('---\nname: foo\n---\n正文', item)).not.toBeNull();+ expect(checkSkillMdConsistency('没有 frontmatter', item)).not.toBeNull();+ expect(checkSkillMdConsistency('---\nname: [broken\n---\n', item)).not.toBeNull();+ });++ it('frontmatter 值两侧空白容忍(trim 后比对)', () => {+ expect(+ checkSkillMdConsistency(md(' foo ', ' 教 Agent 用 foo '), item),+ ).toBeNull();+ });+});++describe('skillSlot · reconcileGhostSkillLinks', () => {+ it('启用插件 → 建链进共享根并扇出 .claude;二次对账幂等', async () => {+ await writeSkillDir('my-ghost', 'skills/foo', 'foo');+ const ghosts = [ghost('my-ghost', [{ dir: 'skills/foo', name: 'foo' }])];++ const first = await reconcileGhostSkillLinks({ ghosts, brainRoot, homeDir });+ expect(first.changed).toBe(true);+ expect(first.warnings).toEqual([]);+ const linkName = ghostSkillLinkName('my-ghost', 'foo');+ const sharedLink = path.join(sharedDir(), linkName);+ const target = path.join(brainRoot, 'my-ghost', 'skills', 'foo');+ expect(sameRealPath(sharedLink, target)).toBe(true);+ // .claude 兼容扇出(经 prepareSharedGlobalSkillLinks)+ expect(sameRealPath(path.join(claudeDir(), linkName), target)).toBe(true);++ const second = await reconcileGhostSkillLinks({ ghosts, brainRoot, homeDir });+ expect(second.changed).toBe(false);+ expect(second.actions.filter((a) => a.op !== 'kept')).toEqual([]);+ });++ it('停用/卸载 → 撤链,.claude 悬空兼容链接一并回收', async () => {+ await writeSkillDir('my-ghost', 'skills/foo', 'foo');+ const enabled = [ghost('my-ghost', [{ dir: 'skills/foo', name: 'foo' }])];+ await reconcileGhostSkillLinks({ ghosts: enabled, brainRoot, homeDir });+ const linkName = ghostSkillLinkName('my-ghost', 'foo');++ // 停用:期望态清空 → 双侧链接消失+ const disabled = [ghost('my-ghost', [{ dir: 'skills/foo', name: 'foo' }], { enabled: false })];+ const result = await reconcileGhostSkillLinks({ ghosts: disabled, brainRoot, homeDir });+ expect(result.changed).toBe(true);+ expect(fs.existsSync(path.join(sharedDir(), linkName))).toBe(false);+ expect(fs.existsSync(path.join(claudeDir(), linkName))).toBe(false);++ // 卸载(清单里没有它)语义相同:再建再收敛一次验证+ await reconcileGhostSkillLinks({ ghosts: enabled, brainRoot, homeDir });+ const gone = await reconcileGhostSkillLinks({ ghosts: [], brainRoot, homeDir });+ expect(gone.changed).toBe(true);+ expect(fs.existsSync(path.join(sharedDir(), linkName))).toBe(false);+ });++ it('目标目录被删(异常残留)→ 断链回收', async () => {+ await writeSkillDir('my-ghost', 'skills/foo', 'foo');+ const ghosts = [ghost('my-ghost', [{ dir: 'skills/foo', name: 'foo' }])];+ await reconcileGhostSkillLinks({ ghosts, brainRoot, homeDir });+ // 模拟崩溃残留:插件目录整个没了,链接悬空+ await fs.promises.rm(path.join(brainRoot, 'my-ghost'), { recursive: true, force: true });+ const result = await reconcileGhostSkillLinks({ ghosts: [], brainRoot, homeDir });+ expect(fs.existsSync(path.join(sharedDir(), ghostSkillLinkName('my-ghost', 'foo')))).toBe(false);+ expect(result.changed).toBe(true);+ });++ it('技能改名/换目录 → 旧链撤、新链立', async () => {+ await writeSkillDir('my-ghost', 'skills/foo', 'foo');+ await reconcileGhostSkillLinks({+ ghosts: [ghost('my-ghost', [{ dir: 'skills/foo', name: 'foo' }])],+ brainRoot,+ homeDir,+ });+ await writeSkillDir('my-ghost', 'skills/bar', 'bar');+ const result = await reconcileGhostSkillLinks({+ ghosts: [ghost('my-ghost', [{ dir: 'skills/bar', name: 'bar' }])],+ brainRoot,+ homeDir,+ });+ expect(result.changed).toBe(true);+ expect(fs.existsSync(path.join(sharedDir(), ghostSkillLinkName('my-ghost', 'foo')))).toBe(false);+ expect(+ sameRealPath(+ path.join(sharedDir(), ghostSkillLinkName('my-ghost', 'bar')),+ path.join(brainRoot, 'my-ghost', 'skills', 'bar'),+ ),+ ).toBe(true);+ });++ it('真实目录占位 → 不覆盖 + warning(保护 SkillHub 实体技能与用户手放目录)', async () => {+ await writeSkillDir('my-ghost', 'skills/foo', 'foo');+ const linkName = ghostSkillLinkName('my-ghost', 'foo');+ const occupied = path.join(sharedDir(), linkName);+ await fs.promises.mkdir(occupied, { recursive: true });+ await fs.promises.writeFile(path.join(occupied, 'SKILL.md'), '---\nname: x\ndescription: y\n---\n');++ const result = await reconcileGhostSkillLinks({+ ghosts: [ghost('my-ghost', [{ dir: 'skills/foo', name: 'foo' }])],+ brainRoot,+ homeDir,+ });+ expect(result.warnings.some((w) => w.includes(linkName))).toBe(true);+ // 真实目录原样保留,不是链接+ const st = await fs.promises.lstat(occupied);+ expect(st.isDirectory()).toBe(true);+ expect(st.isSymbolicLink()).toBe(false);+ });++ it('外来链接(目标不在任何 cindy-brain 内)→ 活链断链都不碰', async () => {+ const foreignTarget = path.join(workDir, 'foreign-skill');+ await fs.promises.mkdir(foreignTarget, { recursive: true });+ await fs.promises.writeFile(+ path.join(foreignTarget, 'SKILL.md'),+ '---\nname: f\ndescription: d\n---\n',+ );+ await fs.promises.mkdir(sharedDir(), { recursive: true });+ const foreignLink = path.join(sharedDir(), 'user-made-link');+ await fs.promises.symlink(+ foreignTarget,+ foreignLink,+ process.platform === 'win32' ? 'junction' : 'dir',+ );++ await reconcileGhostSkillLinks({ ghosts: [], brainRoot, homeDir });+ expect(fs.existsSync(foreignLink)).toBe(true);++ // 变成断链(目标删除)也不碰:目标路径不含 cindy-brain 段+ await fs.promises.rm(foreignTarget, { recursive: true, force: true });+ await reconcileGhostSkillLinks({ ghosts: [], brainRoot, homeDir });+ expect(fs.lstatSync(foreignLink).isSymbolicLink()).toBe(true);+ });++ it('他 owner 的活链接不碰(多账号隔离);他 owner 的断链回收(防积尘)', async () => {+ // 另一个 owner 的 brainRoot 与真实技能+ const otherBrainRoot = path.join(workDir, 'owners', 'bbb', 'cindy-brain');+ const otherSkill = path.join(otherBrainRoot, 'other-ghost', 'skills', 'foo');+ await fs.promises.mkdir(otherSkill, { recursive: true });+ await fs.promises.writeFile(+ path.join(otherSkill, 'SKILL.md'),+ '---\nname: foo\ndescription: d\n---\n',+ );+ await fs.promises.mkdir(sharedDir(), { recursive: true });+ const liveLink = path.join(sharedDir(), 'other-ghost--foo');+ await fs.promises.symlink(+ otherSkill,+ liveLink,+ process.platform === 'win32' ? 'junction' : 'dir',+ );++ await reconcileGhostSkillLinks({ ghosts: [], brainRoot, homeDir });+ expect(fs.existsSync(liveLink)).toBe(true); // 活链保留++ await fs.promises.rm(path.join(otherBrainRoot, 'other-ghost'), { recursive: true, force: true });+ await reconcileGhostSkillLinks({ ghosts: [], brainRoot, homeDir });+ expect(fs.existsSync(liveLink)).toBe(false); // 断链回收(目标带 cindy-brain 段)+ });++ it('目标缺 SKILL.md(如更新备份窗口)→ skip + warning,不建半截链', async () => {+ const bare = path.join(brainRoot, 'my-ghost', 'skills', 'foo');+ await fs.promises.mkdir(bare, { recursive: true }); // 故意不放 SKILL.md+ const result = await reconcileGhostSkillLinks({+ ghosts: [ghost('my-ghost', [{ dir: 'skills/foo', name: 'foo' }])],+ brainRoot,+ homeDir,+ });+ expect(fs.existsSync(path.join(sharedDir(), ghostSkillLinkName('my-ghost', 'foo')))).toBe(false);+ expect(result.warnings.length).toBeGreaterThan(0);+ expect(result.actions.some((a) => a.op === 'skipped' && a.reason === 'target-missing-skill-md')).toBe(true);+ });++ it('撞名兜底:同一链接名两处声明 first-wins + warning(校验层已保证不可达,防御纵深)', async () => {+ await writeSkillDir('my-ghost', 'skills/a', 'dup');+ await writeSkillDir('my-ghost', 'skills/b', 'dup');+ // 手工拼重复 name 的清单(合法清单被校验层拒,这里直测 reconciler 兜底)+ const result = await reconcileGhostSkillLinks({+ ghosts: [+ ghost('my-ghost', [+ { dir: 'skills/a', name: 'dup' },+ { dir: 'skills/b', name: 'dup' },+ ]),+ ],+ brainRoot,+ homeDir,+ });+ expect(result.warnings.some((w) => w.includes('冲突'))).toBe(true);+ expect(+ sameRealPath(+ path.join(sharedDir(), ghostSkillLinkName('my-ghost', 'dup')),+ path.join(brainRoot, 'my-ghost', 'skills', 'a'),+ ),+ ).toBe(true);+ });+});++describe('skillSlot · 全链路(打包 → 装入 → 对账 → 双端可见)', () => {+ it('forge 打包的 skill 插件装入后,对账把技能链进 .agents 与 .claude;卸载即撤', async () => {+ // 1) 源码目录 → packGhostDir+ const srcDir = path.join(workDir, 'src');+ const write = async (rel: string, content: string) => {+ const abs = path.join(srcDir, rel);+ await fs.promises.mkdir(path.dirname(abs), { recursive: true });+ await fs.promises.writeFile(abs, content);+ };+ await write(+ 'ghost.json',+ JSON.stringify({+ schemaVersion: 2,+ id: 'e2e-ghost',+ name: '全链路演示',+ version: '1.0.0',+ kind: 'chip',+ entry: 'main.js',+ slots: ['tool', 'skill'],+ tools: [{ name: 'do_thing', description: '做点事' }],+ skill: { items: [{ dir: 'skills/demo', name: 'demo', description: '演示技能' }] },+ }),+ );+ await write('main.js', '// brain');+ await write('skills/demo/SKILL.md', '---\nname: demo\ndescription: 演示技能\n---\n\n用法正文\n');+ const packed = await packGhostDir(srcDir);+ expect(packed.ok, JSON.stringify(packed)).toBe(true);+ if (!packed.ok) return;++ // 2) 装入(与真实链路同一 GhostManager.install)+ const manager = new GhostManager({ getRootDir: () => brainRoot });+ const installed = await manager.install(packed.cindyPath);+ expect('ghost' in installed, JSON.stringify(installed)).toBe(true);++ // 3) 对账:共享根与 .claude 双端可见,realpath 落在安装目录+ await reconcileGhostSkillLinks({ ghosts: manager.list(), brainRoot, homeDir });+ const linkName = ghostSkillLinkName('e2e-ghost', 'demo');+ const target = path.join(brainRoot, 'e2e-ghost', 'skills', 'demo');+ expect(sameRealPath(path.join(sharedDir(), linkName), target)).toBe(true);+ expect(sameRealPath(path.join(claudeDir(), linkName), target)).toBe(true);+ // 链接指向的 SKILL.md 就是包里那份+ expect(+ await fs.promises.readFile(path.join(sharedDir(), linkName, 'SKILL.md'), 'utf8'),+ ).toContain('演示技能');++ // 4) 卸载 → 对账 → 双端链接消失+ const removed = await manager.uninstall('e2e-ghost');+ expect(removed).toMatchObject({ ok: true });+ await reconcileGhostSkillLinks({ ghosts: manager.list(), brainRoot, homeDir });+ expect(fs.existsSync(path.join(sharedDir(), linkName))).toBe(false);+ expect(fs.existsSync(path.join(claudeDir(), linkName))).toBe(false);+ });+});diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.tsindex e3f2206ab7..a34b8a9636 100644--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@ -20,10 +20,12 @@ import JSZip from 'jszip';import {GHOST_MANIFEST_FILE,+ GHOST_SKILL_MD_MAX_BYTES,validateGhostManifest,type GhostManifest,} from '../../shared/ghost.js';import { validateGhostLocaleResourcesInDirectory } from './ghostLocaleFiles.js';+import { checkSkillMdConsistency } from './skillSlot.js';/** 与 GhostManager 装入侧同一量级的上限(打包侧提前拦,fail fast)。 */const MAX_BASIC_FILES = 256;@@ -571,6 +573,7 @@ export async function packGhostDir(dir: string): Promise<ForgePackResult> {if (manifest.node?.entry) mustExist.push(manifest.node.entry);if (manifest.panel?.html) mustExist.push(manifest.panel.html);if (manifest.settingsHtml) mustExist.push(manifest.settingsHtml);+ for (const item of manifest.skill?.items ?? []) mustExist.push(`${item.dir}/SKILL.md`);for (const rel of mustExist) {try {const st = await fs.promises.stat(path.join(dir, rel));@@ -580,6 +583,37 @@ export async function packGhostDir(dir: string): Promise<ForgePackResult> {}}+ // 3.5) skill 槽:SKILL.md frontmatter 与清单声明必须逐字一致。与装入侧+ // (GhostManager.parse)共用同一裁判,避免"Forge 能打包、安装被拒"的漂移。+ for (const item of manifest.skill?.items ?? []) {+ const skillMdPath = path.join(dir, ...item.dir.split('/'), 'SKILL.md');+ let content: string;+ try {+ content = await fs.promises.readFile(skillMdPath, 'utf-8');+ } catch (err) {+ return {+ ok: false,+ errorCode: 'ENTRY_MISSING',+ message: `读取 ${item.dir}/SKILL.md 失败:${err instanceof Error ? err.message : String(err)}`,+ };+ }+ if (Buffer.byteLength(content, 'utf8') > GHOST_SKILL_MD_MAX_BYTES) {+ return {+ ok: false,+ errorCode: 'MANIFEST_INVALID',+ message: `${item.dir}/SKILL.md 过大(上限 ${GHOST_SKILL_MD_MAX_BYTES} 字节)`,+ };+ }+ const consistencyError = checkSkillMdConsistency(content, item);+ if (consistencyError) {+ return {+ ok: false,+ errorCode: 'MANIFEST_INVALID',+ message: `skill 条目 ${item.dir}:${consistencyError}`,+ };+ }+ }+// 4) 收集文件(递归,跳过开发残留),数量/体积设限。const files: Array<{ rel: string; abs: string }> = [];let totalBytes = 0;@@ -783,7 +817,7 @@ my-ghost/64KB 都会在 Forge 打包期、内置播种期与安装期拒绝。清单列表、详情页、Panel 标题、安装/配置提示和 Agent 工具目录都消费同一份本地化结果。-十三个卡槽:\`tool\`(注册工具给 AI)、\`cindy\`(请 Cindy 本体代办:出图/改图)、\`agent\`(让+十四个卡槽:\`tool\`(注册工具给 AI)、\`cindy\`(请 Cindy 本体代办:出图/改图)、\`agent\`(让当前 Agent 开始一个普通用户回合,见 §4.11)、\`panel\`(常驻面板)、\`card\`(聊天卡片:自绘工具调用的过程与结果,见 §4.5)、\`subscribe\`(旁听会话事件 + 拦截用户消息,见 §4.6)、\`network\`(访问自带服务的域名白名单 HTTP,主机代发,@@ -792,7 +826,8 @@ my-ghost/Node 工作进程或 stdio MCP,见 §4.12)、\`session-context\`(派活时主机把当前会话的可信 session_id / workdir 注入 args,见 §4.13)、\`pick\`(请主机弹系统选文件夹窗口,用户亲选即授权,见 §4.14)、\`preview\`(请主机在右侧栏内置浏览器打开白名单网站的-预览标签,见 §4.15)。+预览标签,见 §4.15)、\`skill\`(捆绑 Agent Skills:随包 SKILL.md 技能,启用后+Claude Code 与 Codex 都能发现,见 §4.16)。**agent 能力详单**:在 \`slots\` 加 \`"agent"\`,默认只允许在用户真实点击你的聊天卡片后发起一次 Agent 回合;这一档不写配套字段。若确实需要没有当次点击也能@@ -834,6 +869,18 @@ node 详单**不接受** \`command\` / \`args\` / \`shell\` / \`env\` 或其它}\`\`\`+**skill 详单**(声明 skill 槽时必写,详见 §4.16):++\`\`\`json+"skill": {+ "items": [{ // 1–4 条+ "dir": "skills/my-skill", // 包内技能目录,内必须有 SKILL.md+ "name": "my-skill", // 硬规则:与 SKILL.md frontmatter name 逐字一致;小写字母/数字加单连字符分段(禁首尾/连续连字符),≤64+ "description": "……" // 硬规则:与 SKILL.md frontmatter description 逐字一致(确认框展示的就是 Agent 读到的),1–1024 字+ }]+}+\`\`\`+**cindy 能力详单**:声明"这个意识被允许点主机代办菜单上的哪些菜"——只有类目和动作,**没有任何具体模型/供应商信息**(选型权在主机与用户,意识只表达意图)。类目与动作:\`image\`(\`generate\`=出图 / \`edit\`=改图)、\`video\`(\`generate\`=@@ -2220,6 +2267,43 @@ if (!opened.ok) console.warn(opened.errorCode, opened.message);知道页面是谁开的;- 标签开在用户自己的右侧栏浏览器里,关不关、看不看由用户决定。+## 4.16 捆绑 Agent Skills(skill 槽)++想让插件"自带一份教 Agent 怎么用好自己的说明书"(或任何领域技能),把技能目录+随包携带并声明 \`skill\` 槽 + \`skill.items\` 详单(见 §2)。装入且启用后,主机把+每个技能目录链接进共享技能根 \`~/.agents/skills/<插件id>--<技能name>\`(Windows 用+junction),Claude Code 与 Codex 都能自动发现——不复制字节,插件更新技能跟着更新,+停用/卸载即撤链。++目录形态(每条 item 一个目录,内必须有 SKILL.md):++\`\`\`+my-ghost/+ ghost.json+ main.js+ skills/+ my-skill/+ SKILL.md ← frontmatter 必须有 name + description+ reference.md ← 可选:技能附带的其它文件一并随链接可见+\`\`\`++SKILL.md 硬规则(打包与装入双侧强制,任一不满足直接拒):++- frontmatter 的 \`name\` / \`description\` 必须与 \`skill.items\` 声明**逐字一致**+ ——装入确认框展示的是清单声明,Agent 读到的是 SKILL.md,两者必须是同一份事实;+- \`name\`:小写字母/数字加单连字符分段(禁首尾/连续连字符),≤64 字符;+- SKILL.md 单文件 ≤64KB;items 最多 4 条。++信任与作用域(如实告知用户,也请作者自重):++- 技能指令由**主 Agent 以用户全部权限执行**,对所有项目、所有会话生效,+ **不受插件沙箱约束**——这是十四个卡槽里信任面最高的能力,装入确认框会把+ 每个技能置顶逐条列出;+- 技能跟随插件的**全局**启用状态:仅在某个工作目录停用插件**不会**隐藏技能,+ 只有全局停用或卸载才撤链(本期只有全局作用域);+- \`skill.items\` 的字段不参与 locales 本地化(必须与 SKILL.md 逐字一致,而+ SKILL.md 只有一份)。+## 5. 面板(panel.html/css/js)- 显示形态由 \`panel.position\` 决定:\`left\`(缺省)= 停靠主聊天窗左侧的常驻diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex 2c8c8296b5..58727f5011 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -71,6 +71,7 @@ import { GhostOauthAccountManager, type GhostOauthDecl } from './ghostOauthAccouimport { reclaimLoopbackPort } from './portReclaim.js';import { GhostConnectionManager } from './ghostConnections.js';import { getResolvedMainLocale, t } from '../i18n.js';+import { reconcileGhostSkillLinks } from './skillSlot.js';import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';import {FILO_GOOGLE_GHOST_ID,@@ -2033,6 +2034,9 @@ export function registerGhostIpc(): void {ipcRegistered = true;const manager = getGhostManager();const runtime = getGhostRuntime();+ // 启动即对账一次 skill 槽链接:上次会话崩溃/异常退出留下的悬空链接、+ // 换账号后的期望态变化,都在这里自愈(后续变更由 ghosts:changed 广播驱动)。+ scheduleGhostSkillReconcile();setGhostSandboxDevToolsDisabled(app.isPackaged);setGhostAppContextProvider(currentGhostAppContext);// 面板唤醒电子脑(cindy-ghost://<id>/wake 供片分支):面板零桥,唤醒经它@@ -3130,6 +3134,47 @@ function broadcastGhostsChanged(ghosts: InstalledGhost[]): void {});}}+ // skill 槽共享链接对账:装/卸/启停/换版全走本广播,一处挂接全覆盖。+ // 异步合并执行,不阻塞广播;用全量 list() 而非 per-session 过滤后的 visible+ // (链接对账关心"装了什么",与当前会话可见性无关)。+ scheduleGhostSkillReconcile();+}++// —— skill 槽链接对账调度:合并突发广播(in-flight + pending 双标志),+// 永不并发两趟 fs 对账;失败仅 warn,幂等设计靠下一次广播/启动自愈。+let skillReconcileInFlight = false;+let skillReconcilePending = false;+function scheduleGhostSkillReconcile(): void {+ skillReconcilePending = true;+ if (skillReconcileInFlight) return;+ skillReconcileInFlight = true;+ void (async () => {+ try {+ while (skillReconcilePending) {+ skillReconcilePending = false;+ try {+ const result = await reconcileGhostSkillLinks({+ ghosts: getGhostManager().list(),+ brainRoot: brainRootDir(),+ });+ if (result.warnings.length > 0) {+ log.warn('ghost skill reconcile warnings', { warnings: result.warnings });+ }+ if (result.changed) {+ log.info('ghost skill links reconciled', {+ actions: result.actions.filter((a) => a.op !== 'kept'),+ });+ }+ } catch (err) {+ log.warn('ghost skill reconcile failed', {+ error: err instanceof Error ? err.message : String(err),+ });+ }+ }+ } finally {+ skillReconcileInFlight = false;+ }+ })();}let ghostsChangedObserver: ((ghosts: InstalledGhost[]) => void) | null = null;diff --git a/apps/desktop/src/main/cindy-brain/skillSlot.ts b/apps/desktop/src/main/cindy-brain/skillSlot.tsnew file mode 100644index 0000000000..aa25aa7b2d--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/skillSlot.ts@@ -0,0 +1,276 @@+/**+ * skillSlot.ts —— skill 槽的两半:SKILL.md 一致性检查 + 共享技能根链接对账。+ *+ * 设计要点:+ * - **确认框看到的 = Agent 读到的**:manifest 里 skill.items 的 name/description+ * 必须与包内 SKILL.md frontmatter 逐字一致。`checkSkillMdConsistency` 是唯一+ * 裁判,打包(forge.packGhostDir)与装入(GhostManager.parse)两侧共用,+ * 杜绝两端契约漂移。+ * - **单一幂等 reconciler**:`reconcileGhostSkillLinks` 以"期望态 vs 实际态"+ * 对账,不做增量命令式挂链——install/update/启停/卸载全走同一条广播管线+ * 触发对账,崩溃残留(悬空链接)下一轮自动自愈。+ * - **链接不复制字节**:共享技能根 `~/.agents/skills/<id>--<name>` 是指向插件+ * 安装目录(brainRoot/<id>/<dir>)的 junction(win32)/dir symlink。更新插件+ * 时安装目录路径稳定,链接跨版本存活;卸载即断链,由对账回收。+ * - **绝不误伤**:只删"确认为 symlink/junction 且目标落在 cindy-brain 安装根"+ * 的条目。真实目录(SkillHub 实体技能、用户手放的技能)与外来链接一律不碰,+ * 占位冲突只 warn 不覆盖(同 shared-global-skills 的冲突哲学)。+ * - **`.claude` 扇出与回收都不归这里管**:对账后调 prepareSharedGlobalSkillLinks,+ * 它负责把 `.agents` 新条目 link 进 `.claude`;我们撤链后留下的 `.claude`+ * 悬空兼容链接目标指向 `.agents` 受管根,同样由它的 cleanupBrokenManagedLinks+ * 回收——职责分界干净:目标在 brainRoot 的链接归本文件,受管根内的归它。+ * - 多账号:brainRoot 是 owner-scoped,`~/.agents/skills` 是全局的。本函数只+ * 管理 realpath 落在**当前 brainRoot** 内的活链接;他 owner 的活链接不碰+ * (与 SkillHub 实体技能同一跨账号可见性现状)。悬空链接只要目标带+ * `cindy-brain` 路径段就回收(断链对所有消费方都是死重,跨 owner 清理防积尘)。+ */++import { promises as fsp } from 'node:fs';+import path from 'node:path';++import matter from 'gray-matter';++import type { GhostSkillItem, InstalledGhost } from '../../shared/ghost.js';+import { parseAndValidateFrontmatter } from '../skillhub/frontmatterValidation.js';+import {+ prepareSharedGlobalSkillLinks,+ sharedGlobalSkillsPaths,+} from '../maker-host/shared-global-skills.js';++/** 共享技能根里 ghost 技能的链接名。name 侧禁 `--`(GHOST_SKILL_NAME_RE),+ * 按"最后一个 `--`"拆分唯一,不同插件不可能撞名。 */+export function ghostSkillLinkName(ghostId: string, skillName: string): string {+ return `${ghostId}--${skillName}`;+}++/**+ * SKILL.md 与 manifest 声明的一致性裁判(纯函数)。+ * 返回错误原因(中文,给作者自纠),一致返回 null。+ */+export function checkSkillMdConsistency(content: string, item: GhostSkillItem): string | null {+ let data: Record<string, unknown>;+ try {+ data = (matter(content).data as Record<string, unknown>) ?? {};+ } catch {+ return 'SKILL.md frontmatter 无法解析(YAML 语法错误)';+ }+ const { issues } = parseAndValidateFrontmatter(content, 'skill');+ if (issues.length > 0) {+ return `SKILL.md frontmatter 不合格:${issues.map((i) => `${i.field}:${i.message}`).join('; ')}`;+ }+ const fmName = typeof data.name === 'string' ? data.name.trim() : '';+ const fmDescription = typeof data.description === 'string' ? data.description.trim() : '';+ if (fmName !== item.name) {+ return `SKILL.md frontmatter name ${JSON.stringify(fmName)} 与清单声明 ${JSON.stringify(item.name)} 不一致(装入确认框展示的必须就是 Agent 读到的)`;+ }+ if (fmDescription !== item.description) {+ return 'SKILL.md frontmatter description 与清单声明不一致(装入确认框展示的必须就是 Agent 读到的)';+ }+ return null;+}++export interface GhostSkillLinkAction {+ linkName: string;+ op: 'linked' | 'removed' | 'kept' | 'skipped';+ reason?: string;+}++export interface ReconcileGhostSkillLinksResult {+ changed: boolean;+ actions: GhostSkillLinkAction[];+ warnings: string[];+}++interface ReconcileOptions {+ ghosts: InstalledGhost[];+ /** 当前 owner 的插件安装根(userData/.../cindy-brain)。 */+ brainRoot: string;+ /** 覆盖 home 目录(仅测试)。 */+ homeDir?: string;+}++function normalizeForCompare(value: string): string {+ const resolved = path.resolve(value);+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved;+}++function isSameOrInside(child: string, parent: string): boolean {+ const rel = path.relative(parent, child);+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));+}++async function realPathOrNull(value: string): Promise<string | null> {+ try {+ return normalizeForCompare(await fsp.realpath(value));+ } catch {+ return null;+ }+}++/** 断链回收判据:链接名符合 `<id>--<name>` ghost 命名且目标路径带 `cindy-brain`+ * 段才视为 ghost 托管(跨 owner 通用)。两条同时满足才动手,避免误伤用户创建+ * 的恰巧含该路径段的外来链接。 */+function targetLooksGhostManaged(target: string, linkName: string): boolean {+ if (!linkName.includes('--')) return false;+ return target+ .split(/[\\/]/)+ .some((segment) => segment.toLowerCase() === 'cindy-brain');+}++/**+ * 共享技能根对账:期望态(启用且带 skill 槽的插件)vs 实际态(根下目标落在+ * brainRoot 的链接)。幂等、best-effort、不 throw;warnings 交调用方记日志。+ */+export async function reconcileGhostSkillLinks(+ opts: ReconcileOptions,+): Promise<ReconcileGhostSkillLinksResult> {+ const actions: GhostSkillLinkAction[] = [];+ const warnings: string[] = [];+ let changed = false;++ const { sharedSkillsDir } = sharedGlobalSkillsPaths(opts.homeDir);+ // realpath 兼容 brainRoot 或其祖先是 symlink 的场景(relocated home dir)——+ // 活链接 realpath 后必须与归一化的物理根比较才可靠。resolve 失败退化到词法。+ const brainRootCompare = (await realPathOrNull(opts.brainRoot)) ?? normalizeForCompare(opts.brainRoot);++ try {+ await fsp.mkdir(sharedSkillsDir, { recursive: true });+ } catch (err) {+ warnings.push(`无法创建共享技能根 ${sharedSkillsDir}:${(err as Error).message}`);+ return { changed, actions, warnings };+ }++ // —— 期望态:linkName → { target, item }。按 id+name 排序保证确定性;撞名+ // first-wins + warn 兜底(name 正则已保证结构上不可能,防御纵深)。+ const desired = new Map<string, { target: string; item: GhostSkillItem }>();+ const eligible = opts.ghosts+ .filter((g) => g.enabled && g.manifest.slots.includes('skill') && g.manifest.skill)+ .sort((a, b) => a.manifest.id.localeCompare(b.manifest.id));+ for (const ghost of eligible) {+ const sortedItems = [...(ghost.manifest.skill?.items ?? [])].sort((a, b) =>+ a.name.localeCompare(b.name),+ );+ for (const item of sortedItems) {+ const linkName = ghostSkillLinkName(ghost.manifest.id, item.name);+ if (desired.has(linkName)) {+ warnings.push(`技能链接名冲突 ${linkName},保留先到者`);+ continue;+ }+ desired.set(linkName, {+ target: path.join(opts.brainRoot, ghost.manifest.id, ...item.dir.split('/')),+ item,+ });+ }+ }++ // —— 实际态扫描:只认 symlink/junction 条目;真实目录绝不进入后续任何分支。+ let linkNames: string[];+ try {+ const entries = await fsp.readdir(sharedSkillsDir, { withFileTypes: true });+ linkNames = entries.filter((ent) => ent.isSymbolicLink()).map((ent) => ent.name);+ } catch (err) {+ warnings.push(`无法读取共享技能根 ${sharedSkillsDir}:${(err as Error).message}`);+ return { changed, actions, warnings };+ }++ const managedLive = new Map<string, string>(); // linkName → realpath(compare 形态)+ const toRemove: string[] = [];+ for (const entName of linkNames) {+ const linkPath = path.join(sharedSkillsDir, entName);+ const real = await realPathOrNull(linkPath);+ if (real !== null) {+ // 活链接:目标在当前 brainRoot 内才归我们管;他 owner / 外来链接不碰。+ if (!isSameOrInside(real, brainRootCompare)) continue;+ const want = desired.get(entName);+ if (want !== undefined && real === normalizeForCompare(want.target)) {+ managedLive.set(entName, real);+ } else {+ toRemove.push(entName);+ }+ continue;+ }+ // 断链:目标带 cindy-brain 段即回收(含他 owner 与登出态临时根的残留)。+ let rawTarget: string;+ try {+ rawTarget = await fsp.readlink(linkPath);+ } catch {+ continue;+ }+ const absTarget = path.isAbsolute(rawTarget)+ ? rawTarget+ : path.resolve(sharedSkillsDir, rawTarget);+ if (targetLooksGhostManaged(absTarget, entName)) toRemove.push(entName);+ }++ // —— 删除步:先撤旧再建新,防"改目标"落进冲突分支。+ for (const linkName of toRemove) {+ const linkPath = path.join(sharedSkillsDir, linkName);+ try {+ const stat = await fsp.lstat(linkPath);+ if (!stat.isSymbolicLink()) continue; // TOCTOU 防御:再确认一次才动手+ await fsp.rm(linkPath, { recursive: true, force: true });+ actions.push({ linkName, op: 'removed' });+ changed = true;+ } catch (err) {+ warnings.push(`移除技能链接 ${linkName} 失败:${(err as Error).message}`);+ }+ }++ // —— 创建步:目标须存在、含 SKILL.md 且内容与 manifest 一致(容忍更新备份+ // 窗口的瞬时缺失,skip+warn 等下一轮自愈);占位者非本 owner 托管链接不覆盖。+ for (const [linkName, { target, item }] of desired) {+ if (managedLive.has(linkName)) {+ actions.push({ linkName, op: 'kept' });+ continue;+ }+ const skillMdPath = path.join(target, 'SKILL.md');+ let skillMdContent: string;+ try {+ skillMdContent = await fsp.readFile(skillMdPath, 'utf8');+ } catch {+ actions.push({ linkName, op: 'skipped', reason: 'target-missing-skill-md' });+ warnings.push(`技能目录缺失或无 SKILL.md,暂不挂链:${target}`);+ continue;+ }+ const consistencyErr = checkSkillMdConsistency(skillMdContent, item);+ if (consistencyErr !== null) {+ actions.push({ linkName, op: 'skipped', reason: 'skill-md-inconsistent' });+ warnings.push(`${linkName} SKILL.md 一致性不通过,暂不挂链:${consistencyErr}`);+ continue;+ }+ const linkPath = path.join(sharedSkillsDir, linkName);+ try {+ await fsp.lstat(linkPath);+ // 走到这里 = 位置被占且不是删除步清掉的托管链接(真实目录/外来链接)。+ actions.push({ linkName, op: 'skipped', reason: 'occupied-by-unmanaged-entry' });+ warnings.push(`共享技能根 ${linkName} 被非托管条目占用,不覆盖`);+ continue;+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {+ warnings.push(`检查技能链接位 ${linkName} 失败:${(err as Error).message}`);+ continue;+ }+ }+ try {+ await fsp.symlink(target, linkPath, process.platform === 'win32' ? 'junction' : 'dir');+ actions.push({ linkName, op: 'linked' });+ changed = true;+ } catch (err) {+ warnings.push(`创建技能链接 ${linkName} 失败:${(err as Error).message}`);+ }+ }++ // —— 扇出:`.agents` 条目 → `.claude` 兼容链接;撤链留下的 `.claude` 悬空+ // 兼容链接(目标在受管根内)也由它回收。每次对账都跑(兼容链接可能独立+ // 缺失——canonical 正常但 .claude 侧被删或上次扇出失败);幂等、失败不阻断。+ try {+ const fanout = await prepareSharedGlobalSkillLinks(+ opts.homeDir !== undefined ? { homeDir: opts.homeDir } : {},+ );+ warnings.push(...fanout.warnings);+ } catch (err) {+ warnings.push(`共享技能链接扇出失败:${(err as Error).message}`);+ }++ return { changed, actions, warnings };+}diff --git a/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx b/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsxindex 1e1bf85046..240d80a756 100644--- a/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx+++ b/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx@@ -17,6 +17,7 @@ import {FilePen,FolderOpen,Globe,+ GraduationCap,KeyRound,LayoutTemplate,MapPin,@@ -56,6 +57,7 @@ const KIND_ICON: Record<GhostPermissionItem['kind'], LucideIcon> = {'session-context': MapPin,pick: FolderOpen,preview: AppWindow,+ skill: GraduationCap,};function itemIcon(item: GhostPermissionItem): LucideIcon {diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsxindex 8210921707..13cbf4f748 100644--- a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx@@ -19,6 +19,7 @@ import {FilePen,FolderOpen,Globe,+ GraduationCap,KeyRound,LayoutTemplate,MapPin,@@ -86,6 +87,7 @@ const PERMISSION_ICON: Record<GhostPermissionItem['kind'], LucideIcon> = {'session-context': MapPin,pick: FolderOpen,preview: AppWindow,+ skill: GraduationCap,};/** Chooses a visual affordance without changing the host-owned permission title or meaning. */diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex a1fd0e1e68..386d9a87ad 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -2427,7 +2427,9 @@"preview": "Can open preview pages from the sites below in the sidebar browser","previewDetail": "Only the sites listed below can be opened; every page it opens is attributed to this plugin.","nodeChildSpawn": "Its Node program can ask the host to start declared sub-processes from its package",- "nodeChildSpawnDetail": "Only JS files declared inside its own package can be started (same local permissions as the main program); arbitrary commands cannot be executed. Sub-processes are closed together when the plugin is disabled or exits."+ "nodeChildSpawnDetail": "Only JS files declared inside its own package can be started (same local permissions as the main program); arbitrary commands cannot be executed. Sub-processes are closed together when the plugin is disabled or exits.",+ "skill": "Adds the skill \"{{name}}\" to your AI assistants",+ "skillDetail": "A skill is an instruction file the AI loads and follows as its own, with your full permissions, in Claude Code and Codex, across every project — it is not confined to this plugin's sandbox. It stays available while the plugin is enabled and is removed when the plugin is disabled or uninstalled; turning the plugin off for a single folder does not hide it. The full skill text cannot be previewed here — only install plugins you trust."},"connections": {"confirmTitle": "Add connection address",@@ -2514,7 +2516,8 @@"slotCard": "Message cards","slotNetwork": "Network access","slotNotify": "System tips",- "slotFs": "File writing"+ "slotFs": "File writing",+ "slotSkill": "Agent skills"},"commandPaletteTag": "Plugin command","updateConfirm": {diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex a5303a8f74..e5739ef82a 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -2426,7 +2426,9 @@"preview": "以下のサイトのプレビューページをサイドバーのブラウザで開けます","previewDetail": "開けるのは下に列挙されたサイトだけです。ページを開くたびに、どのプラグインが開いたかが表示されます。","nodeChildSpawn": "Node プログラムは、パッケージ内で申告済みのサブプロセスの起動をホストに依頼できます",- "nodeChildSpawnDetail": "起動できるのは自身のパッケージ内で申告済みの JS ファイルだけです(メインプログラムと同じローカル権限)。任意のコマンドは実行できません。プラグインの無効化や終了時にはサブプロセスも一緒に閉じられます。"+ "nodeChildSpawnDetail": "起動できるのは自身のパッケージ内で申告済みの JS ファイルだけです(メインプログラムと同じローカル権限)。任意のコマンドは実行できません。プラグインの無効化や終了時にはサブプロセスも一緒に閉じられます。",+ "skill": "AI アシスタントにスキル「{{name}}」を追加します",+ "skillDetail": "スキルは AI が自分の指示として読み込んで実行する指示ファイルです。あなたの全権限で、Claude Code と Codex のすべてのプロジェクトに適用され、このプラグインのサンドボックスには制限されません。プラグインが有効な間は利用可能で、無効化またはアンインストールすると削除されます。特定のフォルダーだけでプラグインをオフにしても非表示にはなりません。ここではスキルの全文をプレビューできません——信頼できるプラグインのみをインストールしてください。"},"connections": {"confirmTitle": "接続先の追加",@@ -2513,7 +2515,8 @@"slotCard": "メッセージカード","slotNetwork": "ネットワークアクセス","slotNotify": "システム通知",- "slotFs": "ファイル書き込み"+ "slotFs": "ファイル書き込み",+ "slotSkill": "エージェントスキル"},"commandPaletteTag": "プラグインコマンド","updateConfirm": {diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex e092085a9a..ec3002592d 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -2426,7 +2426,9 @@"preview": "아래 사이트의 미리보기 페이지를 사이드바 브라우저에서 열 수 있습니다","previewDetail": "아래에 나열된 사이트만 열 수 있으며, 페이지를 열 때마다 어떤 플러그인이 열었는지 표시됩니다.","nodeChildSpawn": "Node 프로그램이 패키지에 신고된 하위 프로세스 시작을 호스트에 요청할 수 있습니다",- "nodeChildSpawnDetail": "자신의 패키지 안에 신고된 JS 파일만 시작할 수 있으며(메인 프로그램과 동일한 로컬 권한), 임의의 명령은 실행할 수 없습니다. 플러그인이 비활성화되거나 종료되면 하위 프로세스도 함께 종료됩니다."+ "nodeChildSpawnDetail": "자신의 패키지 안에 신고된 JS 파일만 시작할 수 있으며(메인 프로그램과 동일한 로컬 권한), 임의의 명령은 실행할 수 없습니다. 플러그인이 비활성화되거나 종료되면 하위 프로세스도 함께 종료됩니다.",+ "skill": "AI 어시스턴트에 스킬 \"{{name}}\"을(를) 추가합니다",+ "skillDetail": "스킬은 AI가 자신의 지시로 읽어들여 실행하는 지시 파일입니다. 사용자의 전체 권한으로 Claude Code와 Codex의 모든 프로젝트에 적용되며, 이 플러그인의 샌드박스에 제한되지 않습니다. 플러그인이 활성화된 동안 계속 사용 가능하며, 비활성화하거나 제거하면 삭제됩니다. 특정 폴더에서만 플러그인을 끄더라도 숨겨지지 않습니다. 여기서는 스킬 전문을 미리 볼 수 없습니다 — 신뢰할 수 있는 플러그인만 설치하세요."},"connections": {"confirmTitle": "연결 주소 추가",@@ -2513,7 +2515,8 @@"slotCard": "메시지 카드","slotNetwork": "네트워크 접근","slotNotify": "시스템 알림",- "slotFs": "파일 쓰기"+ "slotFs": "파일 쓰기",+ "slotSkill": "에이전트 스킬"},"commandPaletteTag": "플러그인 명령","updateConfirm": {diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex f8d9a74b07..95b58626fa 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -2426,7 +2426,9 @@"preview": "可在右侧栏浏览器中打开以下网站的预览页面","previewDetail": "只能打开下方列出的网站;每次打开都会提示是哪个插件打开的。","nodeChildSpawn": "Node 程序可请宿主再启动包内申报过的子进程",- "nodeChildSpawnDetail": "只能启动它自己包里申报过的 JS 文件(与主程序同样的本机权限),不能执行任意命令;插件停用或退出时子进程一并关闭。"+ "nodeChildSpawnDetail": "只能启动它自己包里申报过的 JS 文件(与主程序同样的本机权限),不能执行任意命令;插件停用或退出时子进程一并关闭。",+ "skill": "为 AI 助手添加技能「{{name}}」",+ "skillDetail": "技能是一份指令文件,AI 会把它当作自己的指令加载执行,拥有你的全部权限,对 Claude Code 与 Codex、所有项目都生效——不受本插件沙箱约束。插件启用期间持续可用,停用或卸载即移除;仅对某个文件夹关闭本插件不会隐藏它。此处无法预览技能全文——请只安装你信任的插件。"},"connections": {"confirmTitle": "添加连接地址",@@ -2513,7 +2515,8 @@"slotCard": "消息卡片","slotNetwork": "网络访问","slotNotify": "系统提示",- "slotFs": "写文件"+ "slotFs": "写文件",+ "slotSkill": "Agent 技能"},"commandPaletteTag": "插件指令","updateConfirm": {diff --git a/apps/desktop/src/shared/__tests__/ghost.test.ts b/apps/desktop/src/shared/__tests__/ghost.test.tsindex 9a84d891e1..4a1b909c3d 100644--- a/apps/desktop/src/shared/__tests__/ghost.test.ts+++ b/apps/desktop/src/shared/__tests__/ghost.test.ts@@ -2398,3 +2398,147 @@ describe('ghost · 宿主代启子进程(node.childSpawn,2026-07-23)', () => {).toBeNull();});});++describe('ghost · skill 槽(捆绑 Agent Skills,2026-07-25)', () => {+ const withSkill = (skill: unknown, slots: string[] = ['panel', 'skill']) =>+ validateGhostManifest({ ...goodChipManifest(), slots, skill });+ const goodItems = [+ { dir: 'skills/foo', name: 'foo', description: '教 Agent 用 foo' },+ ];++ it('槽与详单严格成对;合法声明原样收录', () => {+ // 有槽必有详单+ expect(validateGhostManifest({ ...goodChipManifest(), slots: ['panel', 'skill'] }).ok).toBe(false);+ // 有详单必有槽+ expect(+ validateGhostManifest({ ...goodChipManifest(), skill: { items: goodItems } }).ok,+ ).toBe(false);+ const good = withSkill({ items: goodItems });+ expect(good.ok).toBe(true);+ if (good.ok) expect(good.manifest.skill?.items).toEqual(goodItems);+ });++ it('items 形状:空/超限/非对象/自造字段一律拒', () => {+ expect(withSkill({ items: [] }).ok).toBe(false);+ expect(withSkill({}).ok).toBe(false);+ expect(withSkill({ items: goodItems, extra: 1 }).ok).toBe(false);+ expect(withSkill({ items: ['skills/foo'] }).ok).toBe(false);+ expect(+ withSkill({ items: [{ ...goodItems[0], scope: 'global' }] }).ok,+ ).toBe(false);+ const five = Array.from({ length: 5 }, (_, i) => ({+ dir: `skills/s${i}`,+ name: `s${i}`,+ description: 'x',+ }));+ expect(withSkill({ items: five }).ok).toBe(false);+ // 恰好 4 条放行+ expect(withSkill({ items: five.slice(0, 4) }).ok).toBe(true);+ });++ it('dir:必须是包内安全相对路径', () => {+ const item = (dir: string) => withSkill({ items: [{ dir, name: 'foo', description: 'x' }] });+ expect(item('../evil').ok).toBe(false);+ expect(item('/abs/path').ok).toBe(false);+ expect(item('skills\\foo').ok).toBe(false);+ expect(item('skills/./foo').ok).toBe(false);+ expect(item('').ok).toBe(false);+ expect(item('skills/foo').ok).toBe(true);+ });++ it('name:小写字母数字单连字符分段;禁首尾/连续连字符(链接名 <id>--<name> 的无歧义前提)', () => {+ const named = (name: string) => withSkill({ items: [{ dir: 'skills/foo', name, description: 'x' }] });+ expect(named('foo-bar').ok).toBe(true);+ expect(named('foo2').ok).toBe(true);+ expect(named('Foo').ok).toBe(false);+ expect(named('-foo').ok).toBe(false);+ expect(named('foo-').ok).toBe(false);+ expect(named('foo--bar').ok).toBe(false);+ expect(named('').ok).toBe(false);+ expect(named('a'.repeat(65)).ok).toBe(false);+ expect(named('a'.repeat(64)).ok).toBe(true);+ });++ it('description:1–1024 非空;name/dir 大小写折叠去重', () => {+ const desc = (description: unknown) =>+ withSkill({ items: [{ dir: 'skills/foo', name: 'foo', description }] });+ expect(desc('').ok).toBe(false);+ expect(desc(' ').ok).toBe(false);+ expect(desc('x'.repeat(1025)).ok).toBe(false);+ expect(desc('x'.repeat(1024)).ok).toBe(true);+ expect(desc(42).ok).toBe(false);+ // 重复 name(等值)拒+ expect(+ withSkill({+ items: [+ { dir: 'skills/a', name: 'foo', description: 'x' },+ { dir: 'skills/b', name: 'foo', description: 'y' },+ ],+ }).ok,+ ).toBe(false);+ // 重复 dir 大小写折叠拒(win32 文件系统折叠大小写)+ expect(+ withSkill({+ items: [+ { dir: 'skills/A', name: 'foo', description: 'x' },+ { dir: 'skills/a', name: 'bar', description: 'y' },+ ],+ }).ok,+ ).toBe(false);+ });++ it('权限清单:逐技能置顶展示,key 稳定,detail = 声明的 description;详情页内容含 slotSkill', () => {+ const r = withSkill({+ items: [+ { dir: 'skills/alpha', name: 'alpha', description: '技能 A' },+ { dir: 'skills/beta', name: 'beta', description: '技能 B' },+ ],+ });+ expect(r.ok).toBe(true);+ if (!r.ok) return;+ const items = ghostPermissionItems(r.manifest);+ // 置顶簇:两条 skill 项按声明顺序排在清单最前+ expect(items[0]).toMatchObject({+ key: 'skill:alpha',+ kind: 'skill',+ labelKey: 'skill',+ labelArgs: { name: 'alpha' },+ detailKey: 'skillDetail',+ detail: '技能 A',+ });+ expect(items[1]).toMatchObject({ key: 'skill:beta', detail: '技能 B' });+ expect(ghostContentKeys(r.manifest)).toContain('slotSkill');+ });++ it('更新 diff:技能增删可见,不变项不进 diff', () => {+ const v1 = withSkill({+ items: [{ dir: 'skills/alpha', name: 'alpha', description: '技能 A' }],+ });+ const v2 = withSkill({+ items: [+ { dir: 'skills/alpha', name: 'alpha', description: '技能 A' },+ { dir: 'skills/beta', name: 'beta', description: '技能 B' },+ ],+ });+ expect(v1.ok && v2.ok).toBe(true);+ if (!v1.ok || !v2.ok) return;+ const diff = diffGhostPermissionItems(v1.manifest, v2.manifest);+ expect(diff.added.map((i) => i.key)).toContain('skill:beta');+ expect(diff.removed.map((i) => i.key)).not.toContain('skill:alpha');+ });++ it('更新 diff:同名技能改 description 视为权限变更(added+removed)', () => {+ const v1 = withSkill({+ items: [{ dir: 'skills/alpha', name: 'alpha', description: '旧描述' }],+ });+ const v2 = withSkill({+ items: [{ dir: 'skills/alpha', name: 'alpha', description: '新描述' }],+ });+ expect(v1.ok && v2.ok).toBe(true);+ if (!v1.ok || !v2.ok) return;+ const diff = diffGhostPermissionItems(v1.manifest, v2.manifest);+ expect(diff.added.map((i) => i.key)).toContain('skill:alpha');+ expect(diff.removed.map((i) => i.key)).toContain('skill:alpha');+ expect(diff.unchanged.map((i) => i.key)).not.toContain('skill:alpha');+ });+});diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.tsindex c24a40c7b3..b0913a0fd5 100644--- a/apps/desktop/src/shared/ghost.ts+++ b/apps/desktop/src/shared/ghost.ts@@ -56,7 +56,7 @@ export function parseGhostPartition(partition: unknown): string | null {const GHOST_ID_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;/**- * 八个卡槽(意识能力的全部出口,docs/dev-rules/plugin-security-and-authoring.md)。+ * 十四个卡槽(意识能力的全部出口,docs/dev-rules/plugin-security-and-authoring.md)。* 'cindy' = 请 Cindy 本体代办(借主机自带 AI 能力干活;2026-07-11 Lizi 定案* 由 'model' 更名——本质是 Cindy 在干活,与选模型无关;旧名在校验层作* 静默别名兼容,已装老包不消失)。@@ -82,6 +82,13 @@ const GHOST_ID_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;* 'preview' = 面板预览(2026-07-23):插件经管子申请在右侧栏内置浏览器里打开* 一个网址标签页。网址范围装入时在 preview.hosts 白名单里定死(同 network* 域名白名单语法),运行期主机逐次校验,范围外一律拒——防钓鱼是结构性的。+ * 'skill' = 捆绑 Agent Skills(2026-07-25):插件随包携带 SKILL.md 技能目录,+ * 装入且启用后由主机链接进共享技能根 ~/.agents/skills/<id>--<name>(win32 用+ * junction),Claude Code 与 Codex 都能发现。信任面与其它槽完全不同量级:技能+ * 指令由主 Agent 以**用户全部权限**执行、对所有项目与会话生效、不受插件沙箱+ * 约束,也不随"某工作目录停用本插件"而隐藏——仅全局停用/卸载才撤链。因此+ * manifest 全声明式(items 的 name/description 必须与 SKILL.md frontmatter 逐字+ * 一致,打包与装入双侧强制),装入确认框逐条列出并置于清单最上部。*/export const GHOST_SLOTS = ['subscribe',@@ -97,6 +104,7 @@ export const GHOST_SLOTS = ['session-context','pick','preview',+ 'skill',] as const;export type GhostSlot = (typeof GHOST_SLOTS)[number];@@ -752,6 +760,41 @@ export const GHOST_PREVIEW_LOOPBACK_HOSTS: ReadonlySet<string> = new Set(['[::1]',]);+/** skill 槽:单插件最多捆绑的 Agent Skill 数(范围越小越好,同 preview 精神)。 */+export const GHOST_SKILL_MAX_ITEMS = 4;+/** skill 槽:SKILL.md 单文件字节上限。打包与装入两侧共用,避免契约漂移。 */+export const GHOST_SKILL_MD_MAX_BYTES = 64 * 1024;+/** skill 槽:技能 name 长度上限(链接目录名的一半,克制)。 */+export const GHOST_SKILL_NAME_MAX_CHARS = 64;+/**+ * skill 槽:技能 name 形状——小写字母/数字,连字符仅作单段分隔(禁首尾与连续+ * 连字符)。比 learn-host 的 SKILL_NAME_RE 更严:意识 id 允许含 `--`+ * (GHOST_ID_RE),共享技能根的链接名是 `<id>--<name>`,只有 name 侧禁 `--`,+ * 按"最后一个 `--`"拆分才唯一,不同插件才不可能撞出同一个链接名。+ */+export const GHOST_SKILL_NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;++/** skill 槽单条技能声明(全声明式:确认框展示的就是这里的字段)。 */+export interface GhostSkillItem {+ /** 包内技能目录(安全相对路径,目录内必须有 SKILL.md)。 */+ dir: string;+ /**+ * 技能名。必须与 SKILL.md frontmatter 的 name 逐字一致(打包与装入双侧+ * 强制)——确认框里用户看到的,必须就是 Agent 实际读到的。+ */+ name: string;+ /** 技能说明。必须与 SKILL.md frontmatter 的 description 逐字一致(同上)。 */+ description: string;+}++/**+ * skill 槽详单(与 slots 含 'skill' 严格成对——有槽必有详单:捆绑了什么技能+ * 是本能力的全部知情面,不允许"先装后说")。装入确认框逐条展示。+ */+export interface GhostSkillNeeds {+ items: GhostSkillItem[];+}+/*** preview 槽运行期 URL 守门(纯函数,主机侧调用):* - 只收 https;http 仅放行 loopback(localhost / 127.0.0.1 / [::1])——本地@@ -965,6 +1008,12 @@ export interface GhostManifest {* 打开预览标签页的域名白名单。*/preview?: GhostPreviewNeeds;+ /**+ * skill 槽详单(与 slots 含 'skill' 严格成对):随包捆绑的 Agent Skills 清单。+ * 启用时主机链接进共享技能根,Claude Code 与 Codex 双端可见;字段不参与+ * 本地化(必须与 SKILL.md 逐字一致,见 GhostSkillItem)。+ */+ skill?: GhostSkillNeeds;/*** 就绪声明(使用前置检查,见 GhostSetupDecl 块注释):作者声明「用之前* 必须配好什么」,宿主点「使用」时确定性检查并引导配置。缺省 = 启发式@@ -1082,6 +1131,8 @@ export function ghostContentKeys(manifest: GhostManifest): string[] {else if (slot === 'network') keys.push('slotNetwork');else if (slot === 'notify') keys.push('slotNotify');else if (slot === 'fs') keys.push('slotFs');+ // skill 是信任面最高的内容(给主 Agent 灌指令),详情页必须如实露出。+ else if (slot === 'skill') keys.push('slotSkill');// 'panel' 槽已由 manifest.panel 覆盖,不重复}return keys;@@ -1143,7 +1194,7 @@ export interface GhostPermissionItem {/** 稳定键:更新 diff 按它对齐(内容变化视为移除+新增,如面板换边)。 */key: string;/** 图标分组(renderer 按 kind 选图标)。 */- kind: 'cindy' | 'agent' | 'node' | 'tool' | 'command' | 'panel' | 'code' | 'subscribe' | 'card' | 'network' | 'notify' | 'fs' | 'session-context' | 'pick' | 'preview';+ kind: 'cindy' | 'agent' | 'node' | 'tool' | 'command' | 'panel' | 'code' | 'subscribe' | 'card' | 'network' | 'notify' | 'fs' | 'session-context' | 'pick' | 'preview' | 'skill';/** i18n key 后缀,消费方拼 `settings.ghosts.perm.<labelKey>`。 */labelKey: string;/** i18n 插值参数(工具名、指令名、面板标题等)。 */@@ -1247,6 +1298,20 @@ export function ghostPermissionItems(manifest: GhostManifest): GhostPermissionIt});}}+ // skill 槽:技能指令由主 Agent 以用户全部权限执行、全项目生效、不受沙箱+ // 约束——信任面仅次于拦截钩子,逐条 unshift 到清单上部(倒序遍历保持声明+ // 顺序)。key 用 name 稳定对齐更新 diff;detail = 作者声明的 description+ // 原样展示(装入/打包校验已保证与 SKILL.md 逐字一致)。+ for (const skillItem of [...(manifest.skill?.items ?? [])].reverse()) {+ items.unshift({+ key: `skill:${skillItem.name}`,+ kind: 'skill',+ labelKey: 'skill',+ labelArgs: { name: skillItem.name },+ detailKey: 'skillDetail',+ detail: skillItem.description,+ });+ }// 多连接声明:逐条列"可连接你添加的 <连接类型>"——地址是用户后来自己加的// (且每次新增都过主机受信确认弹窗),装入时只能告知形态,不能列出具体域名。for (const conn of manifest.network?.connections ?? []) {@@ -1437,11 +1502,27 @@ export function diffGhostPermissionItems(const nextItems = ghostPermissionItems(next);const prevKeys = new Set(prevItems.map((i) => i.key));const nextKeys = new Set(nextItems.map((i) => i.key));- return {- added: nextItems.filter((i) => !prevKeys.has(i.key)),- removed: prevItems.filter((i) => !nextKeys.has(i.key)),- unchanged: nextItems.filter((i) => prevKeys.has(i.key)),- };+ const prevDetailByKey = new Map(prevItems.map((i) => [i.key, i.detail ?? '']));+ const added: GhostPermissionItem[] = [];+ const removed: GhostPermissionItem[] = [];+ const unchanged: GhostPermissionItem[] = [];+ for (const item of nextItems) {+ if (!prevKeys.has(item.key)) {+ added.push(item);+ } else if ((item.detail ?? '') !== prevDetailByKey.get(item.key)) {+ added.push(item);+ } else {+ unchanged.push(item);+ }+ }+ for (const item of prevItems) {+ if (!nextKeys.has(item.key)) {+ removed.push(item);+ } else if ((item.detail ?? '') !== (nextItems.find((n) => n.key === item.key)?.detail ?? '')) {+ removed.push(item);+ }+ }+ return { added, removed, unchanged };}/**@@ -2734,6 +2815,79 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {return { ok: false, reason: 'slots 声明了 "preview" 但缺少 preview 详单(hosts 域名白名单必填)' };}+ // skill 槽详单:与 slots 含 'skill' **严格成对**(有槽必有详单——捆绑了什么+ // 技能是本能力的全部知情面)。name/description 与 SKILL.md 的逐字一致性在+ // 打包(packGhostDir)与装入(GhostManager.parse)两侧另行强制,这里只管+ // 声明本身的形状。name/dir 大小写折叠去重:win32 文件系统折叠大小写,+ // 共享技能根的链接名不允许折叠后相撞。+ let skill: GhostSkillNeeds | undefined;+ if (raw.skill !== undefined) {+ if (!isPlainObject(raw.skill)) {+ return { ok: false, reason: 'skill 详单必须是对象(如 { "items": [{ "dir": "skills/foo", "name": "foo", "description": "..." }] })' };+ }+ if (!slots.includes('skill')) {+ return { ok: false, reason: '声明了 skill 详单但 slots 未包含 "skill"' };+ }+ const skillRaw = raw.skill as Record<string, unknown>;+ const unknownSkillField = Object.keys(skillRaw).find((key) => key !== 'items');+ if (unknownSkillField !== undefined) {+ return { ok: false, reason: `skill 含不允许的字段 ${JSON.stringify(unknownSkillField)}` };+ }+ if (!Array.isArray(skillRaw.items) || skillRaw.items.length === 0) {+ return { ok: false, reason: 'skill.items 必须是非空数组(随包捆绑的技能清单)' };+ }+ if (skillRaw.items.length > GHOST_SKILL_MAX_ITEMS) {+ return { ok: false, reason: `skill.items 最多 ${GHOST_SKILL_MAX_ITEMS} 条` };+ }+ const skillItems: GhostSkillItem[] = [];+ const seenSkillNames = new Set<string>();+ const seenSkillDirs = new Set<string>();+ for (const item of skillRaw.items) {+ if (!isPlainObject(item)) {+ return { ok: false, reason: 'skill.items 每项必须是对象({ dir, name, description })' };+ }+ const itemRaw = item as Record<string, unknown>;+ const unknownItemField = Object.keys(itemRaw).find(+ (key) => key !== 'dir' && key !== 'name' && key !== 'description',+ );+ if (unknownItemField !== undefined) {+ return { ok: false, reason: `skill.items 条目含不允许的字段 ${JSON.stringify(unknownItemField)}` };+ }+ if (!isSafeGhostRelativePath(itemRaw.dir)) {+ return { ok: false, reason: `skill.items[].dir 必须是包内安全相对路径(如 "skills/foo"),得到 ${JSON.stringify(itemRaw.dir)}` };+ }+ if (+ typeof itemRaw.name !== 'string' ||+ itemRaw.name.length > GHOST_SKILL_NAME_MAX_CHARS ||+ !GHOST_SKILL_NAME_RE.test(itemRaw.name)+ ) {+ return { ok: false, reason: `skill.items[].name 必须是小写字母/数字加单连字符分段(禁首尾/连续连字符)、长度 1–${GHOST_SKILL_NAME_MAX_CHARS},得到 ${JSON.stringify(itemRaw.name)}` };+ }+ if (+ typeof itemRaw.description !== 'string' ||+ itemRaw.description.trim().length === 0 ||+ itemRaw.description.length > 1024+ ) {+ return { ok: false, reason: 'skill.items[].description 必须是 1–1024 字符的非空字符串' };+ }+ const nameFold = itemRaw.name.toLowerCase();+ if (seenSkillNames.has(nameFold)) {+ return { ok: false, reason: `skill.items 含重复 name ${JSON.stringify(itemRaw.name)}` };+ }+ seenSkillNames.add(nameFold);+ const dirFold = itemRaw.dir.toLowerCase();+ if (seenSkillDirs.has(dirFold)) {+ return { ok: false, reason: `skill.items 含重复 dir ${JSON.stringify(itemRaw.dir)}` };+ }+ seenSkillDirs.add(dirFold);+ skillItems.push({ dir: itemRaw.dir, name: itemRaw.name, description: itemRaw.description });+ }+ skill = { items: skillItems };+ }+ if (slots.includes('skill') && skill === undefined) {+ return { ok: false, reason: 'slots 声明了 "skill" 但缺少 skill 详单(items 技能清单必填)' };+ }+// 订阅槽详单(卡槽①):与 slots 含 'subscribe' 成对(有详单必有槽;有槽// 无详单允许装入但零事件,同 cindy 语义)。硬规则:声明了 hooks(拦截)// 必须 launch:'resident'——要挡路就得常驻在场,每条消息等冷启动不可接受。@@ -3605,6 +3759,7 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {...(subscribe !== undefined ? { subscribe } : {}),...(network !== undefined ? { network } : {}),...(preview !== undefined ? { preview } : {}),+ ...(skill !== undefined ? { skill } : {}),...(setup !== undefined ? { setup } : {}),...(raw.command !== undefined ? { command: raw.command as string } : {}),...(keywords !== undefined ? { keywords } : {}),diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.mdindex e860e366c1..729eee4447 100644--- a/docs/dev-rules/plugin-security-and-authoring.md+++ b/docs/dev-rules/plugin-security-and-authoring.md@@ -28,7 +28,7 @@| 身份卡字段与校验、管子协议类型 | `apps/desktop/src/shared/ghost.ts`(`validateGhostManifest`、`cindy.send` / `cindy.onHostMessage` 类型) || 打包限制 | `apps/desktop/src/main/cindy-brain/forge.ts` 的 `packGhostDir` || 运行时、沙箱进程与生命周期 | `apps/desktop/src/main/cindy-brain/runtime/GhostRuntime.ts`、`GhostManager.ts` |-| 能力 slot(网络/通知/文件系统/宿主等) | `apps/desktop/src/main/cindy-brain/networkSlot.ts`、`notifySlot.ts`、`fsSlot.ts`、`cindySlot.ts` |+| 能力 slot(网络/通知/文件系统/技能/宿主等) | `apps/desktop/src/main/cindy-brain/networkSlot.ts`、`notifySlot.ts`、`fsSlot.ts`、`cindySlot.ts`、`skillSlot.ts` || 面板供片、注入主题 token 与协议 | `apps/desktop/src/renderer/cindy-brain/ghostPanelTheme.ts`、`cindy-ghost://` 分支 || 权限注入/更新确认 UI | `apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx` || 远程/手机版能力准入白名单 | `packages/device-link/src/allowlist.ts` |@@ -60,6 +60,14 @@也不构成授权。- 新增或修改 slot 时,除同步编写手册与校验(下节 5)外,还必须同步 shared 类型、preload/host handler、权限 UI(`GhostPermissionList.tsx`)、错误边界和测试。+- `skill` 槽是唯一**越出沙箱**的能力:技能指令由主 Agent 以用户全部权限执行、全局+ 生效、不随 workdir 级停用隐藏。其安全边界是**声明一致性**(manifest 里的+ name/description 必须与 SKILL.md frontmatter 逐字一致,`skillSlot.ts` 的+ `checkSkillMdConsistency` 是唯一裁判,打包与装入两侧共用)+ **链接对账**+ (`reconcileGhostSkillLinks` 只增删"目标落在 cindy-brain 安装根内的+ symlink/junction",绝不触碰真实目录与外来链接;启用挂链、停用/卸载撤链、+ 断链自愈)。改动技能落链、命名(`<id>--<name>`,name 侧禁 `--`)或对账判据前,+ 必须先读 `skillSlot.ts` 头注释并保持上述不变量。## 4. 网络、凭证与资源交接@@ -96,6 +104,10 @@- `networkSlot.ts` 的 `as: 'media'` 不能只信任 Content-Type(GLB 常见`application/octet-stream`),需要安全的 magic-byte/扩展名嗅探。+- `skill` 槽尚未镜像进协议仓(`cindy-protocol/packages/plugin-protocol/src/manifest.ts`+ 的 `GHOST_SLOTS` 与校验器是桌面端的手工双份):本地/手动安装不受影响,但+ plugin-market 分发声明了 skill 槽的包会被服务端校验拒绝,需与 plugin-server+ 协调后升级 submodule 指针(见 `protocol-and-submodules.md`)。- SSH 远程场景必须让 `LiziMcpSessionContext` 携带 remote 标识;目录过户不得回退读取本机同名路径,无法证明来源时 **fail closed**。- 手机版仍需把历史 mivo 动作按钮降级为纯展示。