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(library): 宿主只读 Library 操作能力合同 (#4000)

Praisedb09a43cf306
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
index 7f87090e02..e284fd82a1 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
@@ -1517,6 +1517,20 @@ describe('FORGE_GUIDE', () => {
expect(FORGE_GUIDE).toContain('`RATE_LIMITED`');
});
+ it('documents library capabilities as a sessionless support list with stable failure reasons', () => {
+ expect(FORGE_GUIDE).toContain("op: 'capabilities'");
+ expect(FORGE_GUIDE).toContain("operations:['clipboardWrite','saveAs']");
+ expect(FORGE_GUIDE).toContain('不等于此刻有窗口 / 已授权 / 库可用');
+ expect(FORGE_GUIDE).toContain('全部字符串');
+ expect(FORGE_GUIDE).toContain('数组内混入');
+ expect(FORGE_GUIDE).toContain('`IMPLEMENTATION_UNSUPPORTED`');
+ expect(FORGE_GUIDE).toContain('`NO_VISIBLE_WINDOW`');
+ expect(FORGE_GUIDE).toContain('`PERMISSION_DENIED`');
+ expect(FORGE_GUIDE).toContain('{ ok:false, errorCode, message, reason? }');
+ expect(FORGE_GUIDE).toContain('非法/越界 dbPath');
+ expect(FORGE_GUIDE).toContain("state:'unavailable'");
+ });
+
it('documents explicit Forge install without changing pack into an install action', () => {
expect(FORGE_GUIDE).toContain("ghost_forge_install({ dir: '<绝对路径>' })");
expect(FORGE_GUIDE).toContain('不要因为 scaffold 或 pack 成功就自动调用本工具');
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/librarySlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/librarySlot.test.ts
index 676a737330..982ecb7b3b 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/librarySlot.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/librarySlot.test.ts
@@ -20,7 +20,10 @@ import { LibraryBindingStore } from '../libraryBinding.js';
import { LibraryVault } from '../libraryVault.js';
import { createLibraryDbCore, type SqliteDatabaseConstructor } from '../libraryDbCore.js';
import { LibrarySqlService } from '../librarySqlService.js';
-import type { InstalledGhost } from '../../../shared/ghost.js';
+import {
+ classifyGhostLibraryOperationSupport,
+ type InstalledGhost,
+} from '../../../shared/ghost.js';
const Ctor = Database as unknown as SqliteDatabaseConstructor;
const GHOST_ID = 'mivo-canvas';
@@ -57,6 +60,10 @@ describe('GhostLibrarySlot', () => {
let showSaveDialog: ReturnType<typeof vi.fn>;
let writeClipboardPng: ReturnType<typeof vi.fn>;
let syncAgentReadonlyExtraDir: ReturnType<typeof vi.fn>;
+ let captureOwnerScope: ReturnType<typeof vi.fn>;
+ let resolveLibraryRoot: ReturnType<typeof vi.fn>;
+ let createVault: ReturnType<typeof vi.fn>;
+ let createSqlService: ReturnType<typeof vi.fn>;
let clock: number;
beforeEach(async () => {
@@ -73,18 +80,25 @@ describe('GhostLibrarySlot', () => {
getManagedRoots: () => [path.join(tmp, 'managed')],
getDefaultRoot: (id) => path.join(defaultRootBase, id),
});
+ captureOwnerScope = vi.fn(() => scopeKey);
+ const originalResolve = bindingStore.resolveLibraryRoot.bind(bindingStore);
+ resolveLibraryRoot = vi.fn((ghostId: string) => originalResolve(ghostId));
+ bindingStore.resolveLibraryRoot = ((ghostId: string) => resolveLibraryRoot(ghostId)) as LibraryBindingStore['resolveLibraryRoot'];
+ createVault = vi.fn((d) => new LibraryVault(d));
+ createSqlService = vi.fn((d) =>
+ new LibrarySqlService({
+ ...d,
+ createCore: (ctor) => createLibraryDbCore({ DatabaseCtor: ctor }),
+ inProcessCtor: Ctor,
+ }),
+ );
const deps: GhostLibrarySlotDeps = {
getGhost: (id) => ghosts.get(id) ?? null,
bindingStore,
getDefaultRoot: (id) => path.join(defaultRootBase, id),
- captureOwnerScope: () => scopeKey,
- createVault: (d) => new LibraryVault(d),
- createSqlService: (d) =>
- new LibrarySqlService({
- ...d,
- createCore: (ctor) => createLibraryDbCore({ DatabaseCtor: ctor }),
- inProcessCtor: Ctor,
- }),
+ captureOwnerScope: () => captureOwnerScope(),
+ createVault: (d) => createVault(d),
+ createSqlService: (d) => createSqlService(d),
getDiskFreeBytes: async () => 1024 ** 4,
workerScriptPath: () => path.join(tmp, 'unused-worker.js'),
betterSqliteModulePath: () => 'better-sqlite3',
@@ -110,13 +124,111 @@ describe('GhostLibrarySlot', () => {
ghosts.set(GHOST_ID, makeGhost(false));
const r = await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });
expect(r.ok).toBe(false);
- if (!r.ok) expect(r.errorCode).toBe('NOT_DECLARED');
+ if (!r.ok) {
+ expect(r.errorCode).toBe('NOT_DECLARED');
+ expect(r.reason).toBe('PERMISSION_DENIED');
+ }
ghosts.set(GHOST_ID, makeGhost(true, false));
const r2 = await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });
expect(r2.ok).toBe(false);
+ if (!r2.ok) {
+ expect(r2.errorCode).toBe('NOT_DECLARED');
+ expect(r2.reason).toBe('PERMISSION_DENIED');
+ }
+ const deniedCaps = await slot.handleLibraryRequest(GHOST_ID, { op: 'capabilities' });
+ expect(deniedCaps).toMatchObject({
+ ok: false,
+ errorCode: 'NOT_DECLARED',
+ reason: 'PERMISSION_DENIED',
+ });
+ expect(JSON.stringify(deniedCaps)).not.toContain(defaultRootBase);
+ expect(JSON.stringify(deniedCaps)).not.toContain('local:owner');
+ expect(captureOwnerScope).not.toHaveBeenCalled();
+ expect(resolveLibraryRoot).not.toHaveBeenCalled();
ghosts.set(GHOST_ID, makeGhost(true));
});
+ it('capabilities: 资格审后、会话创建前返回 v1 清单,首请求零副作用', async () => {
+ const sessionCount = () => (slot as unknown as { sessions: Map<string, unknown> }).sessions.size;
+ const vaultOpen = vi.spyOn(LibraryVault.prototype, 'open');
+ const vaultClear = vi.spyOn(LibraryVault.prototype, 'clearOrphaned');
+ const vaultWriteBegin = vi.spyOn(LibraryVault.prototype, 'writeBegin');
+ const vaultWriteAbort = vi.spyOn(LibraryVault.prototype, 'writeAbort');
+ try {
+ expect(sessionCount()).toBe(0);
+ const r = await slot.handleLibraryRequest(GHOST_ID, { op: 'capabilities' });
+ expect(r).toEqual({
+ ok: true,
+ op: 'capabilities',
+ capabilities: { version: 1, operations: ['clipboardWrite', 'saveAs'] },
+ });
+ expect(classifyGhostLibraryOperationSupport(r, 'clipboardWrite')).toBe('supported');
+ expect(classifyGhostLibraryOperationSupport(r, 'saveAs')).toBe('supported');
+ expect(classifyGhostLibraryOperationSupport(
+ { ok: true, op: 'capabilities', capabilities: { version: 1, operations: ['clipboardWrite', 'saveAs', 'futureOp'], extra: true } },
+ 'clipboardWrite',
+ )).toBe('supported');
+ expect(classifyGhostLibraryOperationSupport(
+ { ok: true, op: 'capabilities', capabilities: { version: 1, operations: ['saveAs'] } },
+ 'clipboardWrite',
+ )).toBe('unsupported');
+ expect(classifyGhostLibraryOperationSupport(
+ { ok: false, errorCode: 'PATH_INVALID', message: 'unknown op' },
+ 'clipboardWrite',
+ )).toBe('unknown');
+ expect(classifyGhostLibraryOperationSupport(
+ { ok: true, op: 'capabilities', capabilities: { version: 2, operations: ['clipboardWrite'] } },
+ 'clipboardWrite',
+ )).toBe('unknown');
+ expect(classifyGhostLibraryOperationSupport(
+ { ok: true, op: 'capabilities', capabilities: { operations: ['clipboardWrite'] } },
+ 'clipboardWrite',
+ )).toBe('unknown');
+ expect(classifyGhostLibraryOperationSupport(
+ { ok: true, op: 'capabilities', capabilities: { version: 1, operations: 'clipboardWrite' } },
+ 'clipboardWrite',
+ )).toBe('unknown');
+ const mixedTypes = {
+ ok: true,
+ op: 'capabilities',
+ capabilities: { version: 1, operations: ['saveAs', 123] },
+ };
+ expect(classifyGhostLibraryOperationSupport(mixedTypes, 'clipboardWrite')).toBe('unknown');
+ expect(classifyGhostLibraryOperationSupport(mixedTypes, 'saveAs')).toBe('unknown');
+ expect(classifyGhostLibraryOperationSupport(
+ { ok: true, op: 'capabilities', capabilities: { version: 1, operations: [123] } },
+ 'saveAs',
+ )).toBe('unknown');
+ expect(classifyGhostLibraryOperationSupport(
+ { ok: true, op: 'capabilities', capabilities: { version: 1, operations: ['clipboardWrite', null] } },
+ 'clipboardWrite',
+ )).toBe('unknown');
+ expect(sessionCount()).toBe(0);
+ expect(captureOwnerScope).not.toHaveBeenCalled();
+ expect(resolveLibraryRoot).not.toHaveBeenCalled();
+ expect(createVault).not.toHaveBeenCalled();
+ expect(createSqlService).not.toHaveBeenCalled();
+ expect(vaultOpen).not.toHaveBeenCalled();
+ expect(vaultClear).not.toHaveBeenCalled();
+ expect(vaultWriteBegin).not.toHaveBeenCalled();
+ expect(vaultWriteAbort).not.toHaveBeenCalled();
+ expect(syncAgentReadonlyExtraDir).not.toHaveBeenCalled();
+ expect(writeClipboardPng).not.toHaveBeenCalled();
+ expect(showSaveDialog).not.toHaveBeenCalled();
+ expect(showItemInFolder).not.toHaveBeenCalled();
+ expect(JSON.stringify(r)).not.toContain(defaultRootBase);
+ expect(JSON.stringify(r)).not.toContain(tmp);
+ expect(JSON.stringify(r)).not.toContain('local:owner');
+ const libraryRoot = path.join(defaultRootBase, GHOST_ID);
+ expect(fs.existsSync(libraryRoot)).toBe(false);
+ } finally {
+ vaultOpen.mockRestore();
+ vaultClear.mockRestore();
+ vaultWriteBegin.mockRestore();
+ vaultWriteAbort.mockRestore();
+ }
+ });
+
it('管道级全链路:open/status/write/read/rename/delete(默认根)', async () => {
const open = await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });
if (!open.ok || open.op !== 'open') throw new Error(JSON.stringify(open));
@@ -180,6 +292,41 @@ describe('GhostLibrarySlot', () => {
expect(backups.some((f) => f.startsWith('pre-migrate-'))).toBe(true);
});
+ it('dbPath 非法/越界 → PATH_INVALID + INVALID_REQUEST', async () => {
+ await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });
+ const missing = await slot.handleLibraryRequest(GHOST_ID, { op: 'db.open' });
+ expect(missing).toMatchObject({ ok: false, errorCode: 'PATH_INVALID', reason: 'INVALID_REQUEST' });
+ const escaped = await slot.handleLibraryRequest(GHOST_ID, {
+ op: 'db.open', dbPath: '../escape.sqlite',
+ });
+ expect(escaped).toMatchObject({ ok: false, errorCode: 'PATH_INVALID', reason: 'INVALID_REQUEST' });
+ });
+
+ it('open/status vault LIBRARY_UNAVAILABLE 透传稳定 reason', async () => {
+ const openSpy = vi.spyOn(LibraryVault.prototype, 'open').mockResolvedValue({
+ ok: false, errorCode: 'LIBRARY_UNAVAILABLE', message: 'Library 实例已作废',
+ });
+ try {
+ const r = await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });
+ expect(r).toMatchObject({
+ ok: false, errorCode: 'LIBRARY_UNAVAILABLE', reason: 'LIBRARY_UNAVAILABLE',
+ });
+ } finally {
+ openSpy.mockRestore();
+ }
+ const statusSpy = vi.spyOn(LibraryVault.prototype, 'status').mockResolvedValue({
+ ok: false, errorCode: 'LIBRARY_UNAVAILABLE', message: 'Library 根目录不可访问',
+ });
+ try {
+ const st = await slot.handleLibraryRequest(GHOST_ID, { op: 'status' });
+ expect(st).toMatchObject({
+ ok: false, errorCode: 'LIBRARY_UNAVAILABLE', reason: 'LIBRARY_UNAVAILABLE',
+ });
+ } finally {
+ statusSpy.mockRestore();
+ }
+ });
+
it('binding 漂移:目录删除 → open 报 unavailable(disk-missing),写拒', async () => {
const store = new LibraryBindingStore({
getFile: () => bindingFile,
@@ -199,7 +346,16 @@ describe('GhostLibrarySlot', () => {
expect(open2.reason).toBe('disk-missing');
const w = await slot.handleLibraryRequest(GHOST_ID, { op: 'write', path: 'a.txt', content: 'x' });
expect(w.ok).toBe(false);
- if (!w.ok) expect(w.errorCode).toBe('LIBRARY_UNAVAILABLE');
+ if (!w.ok) {
+ expect(w.errorCode).toBe('LIBRARY_UNAVAILABLE');
+ expect(w.reason).toBe('LIBRARY_UNAVAILABLE');
+ }
+ const capsWhileUnavailable = await slot.handleLibraryRequest(GHOST_ID, { op: 'capabilities' });
+ expect(capsWhileUnavailable).toEqual({
+ ok: true,
+ op: 'capabilities',
+ capabilities: { version: 1, operations: ['clipboardWrite', 'saveAs'] },
+ });
// 绝不落默认根冒充。
expect(fs.existsSync(path.join(defaultRootBase, GHOST_ID, 'a.txt'))).toBe(false);
});
@@ -423,7 +579,7 @@ describe('GhostLibrarySlot', () => {
await slot.disposeAll();
release();
const r = await pending;
- expect(r).toMatchObject({ ok: false, errorCode: 'LIBRARY_UNAVAILABLE' });
+ expect(r).toMatchObject({ ok: false, errorCode: 'LIBRARY_UNAVAILABLE', reason: 'CANCELLED' });
expect(fs.readFileSync(dest, 'utf8')).toBe('keep-me');
} finally {
spy.mockRestore();
@@ -453,7 +609,7 @@ describe('GhostLibrarySlot', () => {
await slot.disposeAll();
release({ canceled: false, filePath: dest });
const r = await pending;
- expect(r).toMatchObject({ ok: false, errorCode: 'LIBRARY_UNAVAILABLE' });
+ expect(r).toMatchObject({ ok: false, errorCode: 'LIBRARY_UNAVAILABLE', reason: 'CANCELLED' });
expect(fs.existsSync(dest)).toBe(false);
});
@@ -485,7 +641,7 @@ describe('GhostLibrarySlot', () => {
const r = await slot.handleLibraryRequest(GHOST_ID, {
op: 'clipboardWrite', content: '', encoding: 'base64',
});
- expect(r).toMatchObject({ ok: false, errorCode: 'PATH_INVALID' });
+ expect(r).toMatchObject({ ok: false, errorCode: 'PATH_INVALID', reason: 'INVALID_REQUEST' });
expect(writeClipboardPng).not.toHaveBeenCalled();
});
@@ -494,24 +650,24 @@ describe('GhostLibrarySlot', () => {
const utf8 = await slot.handleLibraryRequest(GHOST_ID, {
op: 'clipboardWrite', content: pngB64, encoding: 'utf8',
});
- expect(utf8).toMatchObject({ ok: false, errorCode: 'PATH_INVALID' });
+ expect(utf8).toMatchObject({ ok: false, errorCode: 'PATH_INVALID', reason: 'INVALID_REQUEST' });
const badB64 = await slot.handleLibraryRequest(GHOST_ID, {
op: 'clipboardWrite', content: '%%%not-base64%%%', encoding: 'base64',
});
- expect(badB64).toMatchObject({ ok: false, errorCode: 'PATH_INVALID' });
+ expect(badB64).toMatchObject({ ok: false, errorCode: 'PATH_INVALID', reason: 'INVALID_REQUEST' });
const jpeg = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46]).toString('base64');
const notPng = await slot.handleLibraryRequest(GHOST_ID, {
op: 'clipboardWrite', content: jpeg, encoding: 'base64',
});
- expect(notPng).toMatchObject({ ok: false, errorCode: 'PATH_INVALID' });
+ expect(notPng).toMatchObject({ ok: false, errorCode: 'PATH_INVALID', reason: 'INVALID_REQUEST' });
const padded = await slot.handleLibraryRequest(GHOST_ID, {
op: 'clipboardWrite', content: `${pngB64}=AAAA`, encoding: 'base64',
});
- expect(padded).toMatchObject({ ok: false, errorCode: 'PATH_INVALID' });
+ expect(padded).toMatchObject({ ok: false, errorCode: 'PATH_INVALID', reason: 'INVALID_REQUEST' });
const truncated = await slot.handleLibraryRequest(GHOST_ID, {
op: 'clipboardWrite', content: truncatedPng.toString('base64'), encoding: 'base64',
});
- expect(truncated).toMatchObject({ ok: false, errorCode: 'PATH_INVALID' });
+ expect(truncated).toMatchObject({ ok: false, errorCode: 'PATH_INVALID', reason: 'INVALID_REQUEST' });
// 插进 IDAT 数据区:IHDR 结束于 33,IDAT type 后是 offset 41。
const iendInIdat = Buffer.concat([
MIN_PNG.subarray(0, 41),
@@ -521,11 +677,11 @@ describe('GhostLibrarySlot', () => {
const embedded = await slot.handleLibraryRequest(GHOST_ID, {
op: 'clipboardWrite', content: iendInIdat.toString('base64'), encoding: 'base64',
});
- expect(embedded).toMatchObject({ ok: false, errorCode: 'PATH_INVALID' });
+ expect(embedded).toMatchObject({ ok: false, errorCode: 'PATH_INVALID', reason: 'INVALID_REQUEST' });
const trailing = await slot.handleLibraryRequest(GHOST_ID, {
op: 'clipboardWrite', content: Buffer.concat([MIN_PNG, Buffer.from([0x00])]).toString('base64'), encoding: 'base64',
});
- expect(trailing).toMatchObject({ ok: false, errorCode: 'PATH_INVALID' });
+ expect(trailing).toMatchObject({ ok: false, errorCode: 'PATH_INVALID', reason: 'INVALID_REQUEST' });
expect(writeClipboardPng).not.toHaveBeenCalled();
expect(showItemInFolder).not.toHaveBeenCalled();
expect(showSaveDialog).not.toHaveBeenCalled();
@@ -552,14 +708,58 @@ describe('GhostLibrarySlot', () => {
const r = await slot.handleLibraryRequest(GHOST_ID, {
op: 'clipboardWrite', content: pngB64, encoding: 'base64',
});
- expect(r).toMatchObject({ ok: false, errorCode: 'UNSUPPORTED' });
+ expect(r).toMatchObject({ ok: false, errorCode: 'UNSUPPORTED', reason: 'NO_VISIBLE_WINDOW' });
expect(writeClipboardPng).toHaveBeenCalledTimes(1);
});
+ it('clipboardWrite: 无 handler → UNSUPPORTED + IMPLEMENTATION_UNSUPPORTED,不等于旧宿主', async () => {
+ const noHandler = new GhostLibrarySlot({
+ getGhost: (id) => ghosts.get(id) ?? null,
+ bindingStore,
+ getDefaultRoot: (id) => path.join(defaultRootBase, id),
+ captureOwnerScope: () => captureOwnerScope(),
+ createVault: (d) => createVault(d),
+ createSqlService: (d) => createSqlService(d),
+ getDiskFreeBytes: async () => 1024 ** 4,
+ workerScriptPath: () => path.join(tmp, 'unused-worker.js'),
+ betterSqliteModulePath: () => 'better-sqlite3',
+ showSaveDialog: (...args: unknown[]) => showSaveDialog(...args),
+ now: () => clock,
+ });
+ try {
+ await noHandler.handleLibraryRequest(GHOST_ID, { op: 'open' });
+ const r = await noHandler.handleLibraryRequest(GHOST_ID, {
+ op: 'clipboardWrite', content: pngB64, encoding: 'base64',
+ });
+ expect(r).toMatchObject({
+ ok: false,
+ errorCode: 'UNSUPPORTED',
+ reason: 'IMPLEMENTATION_UNSUPPORTED',
+ });
+ const caps = await noHandler.handleLibraryRequest(GHOST_ID, { op: 'capabilities' });
+ expect(classifyGhostLibraryOperationSupport(caps, 'clipboardWrite')).toBe('supported');
+ } finally {
+ await noHandler.disposeAll();
+ }
+ });
+
+ it('saveAs: 无可见窗口 → INTERNAL + NO_VISIBLE_WINDOW,能力查询仍 supported', async () => {
+ await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });
+ await slot.handleLibraryRequest(GHOST_ID, { op: 'write', path: 'exports/a.psd', content: 'psd' });
+ clock += 4_000;
+ showSaveDialog.mockImplementationOnce(async () => {
+ throw new Error('没有可挂靠的宿主窗口');
+ });
+ const r = await slot.handleLibraryRequest(GHOST_ID, { op: 'saveAs', path: 'exports/a.psd' });
+ expect(r).toMatchObject({ ok: false, errorCode: 'INTERNAL', reason: 'NO_VISIBLE_WINDOW' });
+ const caps = await slot.handleLibraryRequest(GHOST_ID, { op: 'capabilities' });
+ expect(classifyGhostLibraryOperationSupport(caps, 'saveAs')).toBe('supported');
+ });
+
it('clipboardWrite: 未知 op 仍拒,不调用 writeClipboardPng', async () => {
await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });
const r = await slot.handleLibraryRequest(GHOST_ID, { op: 'clipboardPaste' });
- expect(r).toMatchObject({ ok: false, errorCode: 'PATH_INVALID' });
+ expect(r).toMatchObject({ ok: false, errorCode: 'PATH_INVALID', reason: 'INVALID_REQUEST' });
expect(writeClipboardPng).not.toHaveBeenCalled();
});
@@ -599,7 +799,7 @@ describe('GhostLibrarySlot', () => {
await slot.disposeAll();
release();
const r = await pending;
- expect(r).toMatchObject({ ok: false, errorCode: 'LIBRARY_UNAVAILABLE' });
+ expect(r).toMatchObject({ ok: false, errorCode: 'LIBRARY_UNAVAILABLE', reason: 'CANCELLED' });
expect(showSaveDialog).not.toHaveBeenCalled();
});
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index f0b93a68a1..e4bfada9ef 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -3464,6 +3464,12 @@ const st = await cindy.library({ op: 'status' });
// st = { ok:true, state:'ready', usedBytes, fileCount, diskFreeBytes,
// softLimitBytes, softLimitExceeded, location:'default'|'custom' }
+// 只读能力查询:资格审与 op 合法性之后、会话创建之前返回;不打开库、不弹窗
+const caps = await cindy.library({ op: 'capabilities' });
+// caps = { ok:true, op:'capabilities',
+// capabilities:{ version:1, operations:['clipboardWrite','saveAs'] } }
+// operations 只表示宿主实现了这些 op,不等于此刻有窗口 / 已授权 / 库可用
+
// 文件操作(全 Family;写入原子化,大文件走分块流)
await cindy.library({ op: 'write', path: 'canvases/c1/state.json', content: s });
await cindy.library({ op: 'read', path: 'canvases/c1/state.json', encoding: 'base64' });
@@ -3512,12 +3518,23 @@ await cindy.library({ op: 'db.check', dbPath: 'library.sqlite' }); // quick_ch
关键语义(全部由宿主强制):
-- **失败是结构化的**:\`{ ok:false, errorCode, message }\`,常用码
- \`LIBRARY_UNAVAILABLE\`(含 reason:binding-moved/disk-missing/corrupt)、
+- **失败是结构化的**:\`{ ok:false, errorCode, message, reason? }\`。旧
+ \`errorCode\` 保留;另加稳定 \`reason\` 供分类,不要解析人类 \`message\`。
+ 常用码 \`LIBRARY_UNAVAILABLE\`(含 open/status 的 binding-moved/disk-missing/corrupt)、
\`LIBRARY_READONLY\`、\`DISK_FULL\`、\`PATH_INVALID\`、\`NOT_FOUND\`、
\`ALREADY_EXISTS\`、\`TOO_LARGE\`、\`STREAM_INVALID\`、\`DB_STATEMENT_REJECTED\`、
\`DB_ROW_LIMIT\`(结果集超 2000 行,自己加 LIMIT)、\`DB_MIGRATION_CONFLICT\`、
- \`BUSY\`、\`RATE_LIMITED\`;
+ \`BUSY\`、\`RATE_LIMITED\`、\`UNSUPPORTED\`、\`NOT_DECLARED\`;
+ 稳定 \`reason\`:无 handler=\`IMPLEMENTATION_UNSUPPORTED\`,无窗口=\`NO_VISIBLE_WINDOW\`,
+ 权限=\`PERMISSION_DENIED\`,库不可用=\`LIBRARY_UNAVAILABLE\`(含 vault 透传的
+ open/status 失败),非法请求=\`INVALID_REQUEST\`(含非法/越界 dbPath 与未知 op),
+ 取消=\`CANCELLED\`;成功 open/status 的 \`state:'unavailable'\` 仍用结果体 reason
+ (如 disk-missing),不是失败 reason 枚举;查询/传输层本地分类 \`TIMEOUT\` / \`TRANSPORT_ERROR\`;
+- **capabilities**:先查 \`{ op:'capabilities' }\`。仅 \`version===1\` 且
+ \`operations\` 为**全部字符串**的数组才有效;额外字段忽略,未知 operation 忽略,
+ 已知项保留;有效 v1 清单缺少某项才是 unsupported。缺字段、错类型(含数组内混入
+ 非字符串)、\`version\` 非 1、或旧宿主 unknown-op 一律 unknown,不得把其中碰巧
+ 合法的项当成有效清单。查询本身不证明窗口/授权/库可用,也不要求旧插件重装;
- **reveal / saveAs**:只收库内相对路径。成功不回用户另存目标的绝对路径;
取消是 \`{ cancelled:true }\`。reveal 打开系统文件夹、saveAs 弹系统对话框
(跨平台标题带已核验插件名;macOS 另有正文),同插件 3 秒内连发 \`RATE_LIMITED\`;
diff --git a/apps/desktop/src/main/cindy-brain/librarySlot.ts b/apps/desktop/src/main/cindy-brain/librarySlot.ts
index 883d4722ac..9a59ff47ed 100644
--- a/apps/desktop/src/main/cindy-brain/librarySlot.ts
+++ b/apps/desktop/src/main/cindy-brain/librarySlot.ts
@@ -23,8 +23,10 @@ import * as path from 'node:path';
import { crc32 } from 'node:zlib';
import {
+ GHOST_LIBRARY_CAPABILITIES_V1,
GHOST_LIBRARY_OPS,
GHOST_PICK_MIN_INTERVAL_MS,
+ type GhostLibraryErrorReason,
type GhostPipeLibraryResult,
type InstalledGhost,
} from '../../shared/ghost.js';
@@ -186,7 +188,17 @@ export interface GhostLibrarySlotDeps {
): Promise<boolean | 'granted' | 'not-granted' | 'superseded' | void>;
}
-const fail = (errorCode: string, message: string): GhostPipeLibraryResult => ({ ok: false, errorCode, message });
+const fail = (
+ errorCode: string,
+ message: string,
+ reason?: GhostLibraryErrorReason,
+): GhostPipeLibraryResult => (reason ? { ok: false, errorCode, message, reason } : { ok: false, errorCode, message });
+
+const vaultFail = (r: { errorCode: string; message: string }): GhostPipeLibraryResult => (
+ r.errorCode === 'LIBRARY_UNAVAILABLE'
+ ? fail(r.errorCode, r.message, 'LIBRARY_UNAVAILABLE')
+ : { ok: false, errorCode: r.errorCode, message: r.message }
+);
export class GhostLibrarySlot {
private readonly sessions = new Map<string, GhostLibrarySession>();
@@ -231,12 +243,24 @@ export class GhostLibrarySlot {
private async dispatch(ghostId: string, payload: unknown): Promise<GhostPipeLibraryResult> {
if (!this.checkEligibility(ghostId)) {
- return fail('NOT_DECLARED', '插件未装入、已停用或未声明 "library" 能力');
+ return fail('NOT_DECLARED', '插件未装入、已停用或未声明 "library" 能力', 'PERMISSION_DENIED');
}
const req = (payload ?? {}) as Record<string, unknown>;
const op = req.op as string;
if (!GHOST_LIBRARY_OPS.includes(op as never)) {
- return fail('PATH_INVALID', `op 必须是 ${GHOST_LIBRARY_OPS.join(' / ')}`);
+ return fail('PATH_INVALID', `op 必须是 ${GHOST_LIBRARY_OPS.join(' / ')}`, 'INVALID_REQUEST');
+ }
+ // 只读能力查询:资格审与 op 合法性之后、会话创建之前返回。
+ // 不捕获 owner、不解析库根、不 open vault、不弹窗、不碰剪贴板。
+ if (op === 'capabilities') {
+ return {
+ ok: true,
+ op: 'capabilities',
+ capabilities: {
+ version: GHOST_LIBRARY_CAPABILITIES_V1.version,
+ operations: [...GHOST_LIBRARY_CAPABILITIES_V1.operations],
+ },
+ };
}
// 迁移期只读:写类操作在 copying 全程拒绝(读与状态查询照常)。
if (this.relocating.has(ghostId)) {
@@ -448,14 +472,14 @@ export class GhostLibrarySlot {
cancelledMessage: string,
): GhostPipeLibraryResult | null {
if (!this.checkEligibility(ghostId)) {
- return fail('NOT_DECLARED', '插件未装入、已停用或未声明 "library" 能力');
+ return fail('NOT_DECLARED', '插件未装入、已停用或未声明 "library" 能力', 'PERMISSION_DENIED');
}
if (this.deps.captureOwnerScope() !== session.ownerScopeKey) {
- return fail('LIBRARY_UNAVAILABLE', cancelledMessage);
+ return fail('LIBRARY_UNAVAILABLE', cancelledMessage, 'CANCELLED');
}
const live = this.sessions.get(ghostId);
if (!live || live !== session) {
- return fail('LIBRARY_UNAVAILABLE', cancelledMessage);
+ return fail('LIBRARY_UNAVAILABLE', cancelledMessage, 'CANCELLED');
}
return null;
}
@@ -463,9 +487,9 @@ export class GhostLibrarySlot {
/** dbPath 相对键 → 库内绝对路径;经 vault 收敛校验(库内 symlink 指根外拒)。 */
private async resolveDbPath(session: GhostLibrarySession, dbPath: unknown): Promise<{ abs: string } | GhostPipeLibraryResult> {
const reason = validateLibraryRelPath(dbPath);
- if (reason) return fail('PATH_INVALID', `dbPath 非法:${reason}`);
+ if (reason) return fail('PATH_INVALID', `dbPath 非法:${reason}`, 'INVALID_REQUEST');
const abs = await session.vault.resolveDbTarget(dbPath as string);
- if (abs === null) return fail('PATH_INVALID', 'dbPath 越界或目标不可用作数据库');
+ if (abs === null) return fail('PATH_INVALID', 'dbPath 越界或目标不可用作数据库', 'INVALID_REQUEST');
return { abs };
}
@@ -504,7 +528,11 @@ export class GhostLibrarySlot {
// 漂移占位会话:open/status 如实报 unavailable+reason,其余操作全拒
// (绝不当空库、绝不落默认根冒充)。
if (session.drift !== null && op !== 'open' && op !== 'status') {
- return fail('LIBRARY_UNAVAILABLE', `Library 不可用(${session.drift});请在 Cindy 设置中重新确认存储位置`);
+ return fail(
+ 'LIBRARY_UNAVAILABLE',
+ `Library 不可用(${session.drift});请在 Cindy 设置中重新确认存储位置`,
+ 'LIBRARY_UNAVAILABLE',
+ );
}
if (session.drift !== null) {
const drifted = {
@@ -517,7 +545,7 @@ export class GhostLibrarySlot {
switch (op) {
case 'open': {
const r = await vault.open();
- if (!r.ok) return { ok: false, errorCode: r.errorCode, message: r.message };
+ if (!r.ok) return vaultFail(r);
this.extraDirOpenerGhostId = ghostId;
await this.syncAgentReadonlyExtraDir(ghostId, vault.getRootDir());
const body = {
@@ -528,7 +556,7 @@ export class GhostLibrarySlot {
}
case 'status': {
const r = await vault.status();
- if (!r.ok) return { ok: false, errorCode: r.errorCode, message: r.message };
+ if (!r.ok) return vaultFail(r);
if (this.extraDirOpenerGhostId === ghostId) {
await this.syncAgentReadonlyExtraDir(ghostId, vault.getRootDir());
}
@@ -542,66 +570,68 @@ export class GhostLibrarySlot {
}
case 'read': {
const r = await vault.read({ path: req.path, encoding: req.encoding, offset: req.offset, length: req.length });
- if (!r.ok) return { ok: false, errorCode: r.errorCode, message: r.message };
+ if (!r.ok) return vaultFail(r);
return { ok: true, op: 'read', path: r.path, content: r.content, encoding: r.encoding, bytes: r.bytes, sha256: r.sha256 };
}
case 'write': {
const r = await vault.write({ path: req.path, content: req.content, encoding: req.encoding, ifNotExists: req.ifNotExists });
- if (!r.ok) return { ok: false, errorCode: r.errorCode, message: r.message };
+ if (!r.ok) return vaultFail(r);
return { ok: true, op: 'write', path: r.path, bytes: r.bytes, sha256: r.sha256 };
}
case 'writeBegin': {
const r = await vault.writeBegin({ path: req.path, totalBytes: req.totalBytes, sha256: req.sha256 });
- if (!r.ok) return { ok: false, errorCode: r.errorCode, message: r.message };
+ if (!r.ok) return vaultFail(r);
return { ok: true, op: 'writeBegin', streamId: r.streamId };
}
case 'writeChunk': {
const r = await vault.writeChunk({ streamId: req.streamId, seq: req.seq, content: req.content, encoding: req.encoding });
- if (!r.ok) return { ok: false, errorCode: r.errorCode, message: r.message };
+ if (!r.ok) return vaultFail(r);
return { ok: true, op: 'writeChunk', accepted: r.accepted };
}
case 'writeCommit': {
const r = await vault.writeCommit({ streamId: req.streamId });
- if (!r.ok) return { ok: false, errorCode: r.errorCode, message: r.message };
+ if (!r.ok) return vaultFail(r);
return { ok: true, op: 'writeCommit', path: r.path, bytes: r.bytes, sha256: r.sha256 };
}
case 'writeAbort': {
const r = await vault.writeAbort({ streamId: req.streamId });
- if (!r.ok) return { ok: false, errorCode: r.errorCode, message: r.message };
+ if (!r.ok) return vaultFail(r);
return { ok: true, op: 'writeAbort', aborted: r.aborted };
}
case 'list': {
const r = await vault.list({ path: req.path, recursive: req.recursive, cursor: req.cursor, limit: req.limit });
- if (!r.ok) return { ok: false, errorCode: r.errorCode, message: r.message };
+ if (!r.ok) return vaultFail(r);
return { ok: true, op: 'list', entries: r.entries, hasMore: r.hasMore, nextCursor: r.nextCursor };
}
case 'stat': {
const r = await vault.stat({ path: req.path });
- if (!r.ok) return { ok: false, errorCode: r.errorCode, message: r.message };
+ if (!r.ok) return vaultFail(r);
return { ok: true, op: 'stat', path: r.path, kind: r.kind, bytes: r.bytes, mtime: r.mtime };
}
case 'mkdir': {
const r = await vault.mkdir({ path: req.path });
- if (!r.ok) return { ok: false, errorCode: r.errorCode, message: r.message };
+ if (!r.ok) return vaultFail(r);
return { ok: true, op: 'mkdir', path: r.path, existed: r.existed };
}
case 'delete': {
const r = await vault.delete({ path: req.path, recursive: req.recursiveDelete });
- if (!r.ok) return { ok: false, errorCode: r.errorCode, message: r.message };
+ if (!r.ok) return vaultFail(r);
return { ok: true, op: 'delete', path: r.path, existed: r.existed };
}
case 'rename': {
const r = await vault.rename({ from: req.from, to: req.to, overwrite: req.overwrite });
- if (!r.ok) return { ok: false, errorCode: r.errorCode, message: r.message };
+ if (!r.ok) return vaultFail(r);
return { ok: true, op: 'rename', from: r.from, to: r.to };
}
case 'reveal': {
if (typeof req.path !== 'string' || !req.path) {
- return fail('PATH_INVALID', 'reveal 需要库内相对路径');
+ return fail('PATH_INVALID', 'reveal 需要库内相对路径', 'INVALID_REQUEST');
}
const abs = await vault.resolveExistingFile(req.path);
if (!abs) return fail('NOT_FOUND', `库内没有这个文件:${req.path}`);
- if (!this.deps.showItemInFolder) return fail('UNSUPPORTED', '当前宿主不能在文件夹中显示');
+ if (!this.deps.showItemInFolder) {
+ return fail('UNSUPPORTED', '当前宿主不能在文件夹中显示', 'IMPLEMENTATION_UNSUPPORTED');
+ }
// 骚扰钳制:限速按尝试记账(spam 顺延窗口),PATH_INVALID/NOT_FOUND/UNSUPPORTED 不记账。
const now = this.deps.now?.() ?? Date.now();
@@ -621,14 +651,18 @@ export class GhostLibrarySlot {
}
case 'saveAs': {
if (typeof req.path !== 'string' || !req.path) {
- return fail('PATH_INVALID', 'saveAs 需要库内相对路径');
+ return fail('PATH_INVALID', 'saveAs 需要库内相对路径', 'INVALID_REQUEST');
}
const relPath = req.path;
const abs = await vault.resolveExistingFile(relPath);
if (!abs) return fail('NOT_FOUND', `库内没有这个文件:${relPath}`);
- if (!this.deps.showSaveDialog) return fail('UNSUPPORTED', '当前宿主不能弹出另存为');
+ if (!this.deps.showSaveDialog) {
+ return fail('UNSUPPORTED', '当前宿主不能弹出另存为', 'IMPLEMENTATION_UNSUPPORTED');
+ }
const ghost = this.deps.getGhost(ghostId);
- if (!ghost) return fail('NOT_DECLARED', '插件未装入、已停用或未声明 "library" 能力');
+ if (!ghost) {
+ return fail('NOT_DECLARED', '插件未装入、已停用或未声明 "library" 能力', 'PERMISSION_DENIED');
+ }
// 骚扰钳制:限速按尝试记账(spam 顺延窗口),再看全局在场标记。
const now = this.deps.now?.() ?? Date.now();
@@ -651,10 +685,14 @@ export class GhostLibrarySlot {
ghostName: ghost.manifest.name,
});
} catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
this.deps.log?.warn('ghost library saveAs dialog failed', {
ghostId,
- err: error instanceof Error ? error.message : String(error),
+ err: message,
});
+ if (message === CLIPBOARD_NO_HOST_WINDOW) {
+ return fail('INTERNAL', '另存为窗口无法打开', 'NO_VISIBLE_WINDOW');
+ }
return fail('INTERNAL', '另存为窗口无法打开');
} finally {
this.saveAsDialogInFlight = false;
@@ -672,7 +710,7 @@ export class GhostLibrarySlot {
);
if (afterDialog) return afterDialog;
const live = this.sessions.get(ghostId);
- if (!live) return fail('LIBRARY_UNAVAILABLE', '账号已切换,另存为已取消');
+ if (!live) return fail('LIBRARY_UNAVAILABLE', '账号已切换,另存为已取消', 'CANCELLED');
const freshAbs = await live.vault.resolveExistingFile(relPath);
if (!freshAbs) return fail('NOT_FOUND', `库内没有这个文件:${relPath}`);
const dest = picked.filePath;
@@ -708,29 +746,29 @@ export class GhostLibrarySlot {
}
case 'clipboardWrite': {
if (req.encoding !== 'base64') {
- return fail('PATH_INVALID', 'clipboardWrite 只接受 encoding:"base64" 的 PNG 字节');
+ return fail('PATH_INVALID', 'clipboardWrite 只接受 encoding:"base64" 的 PNG 字节', 'INVALID_REQUEST');
}
if (typeof req.content !== 'string') {
- return fail('PATH_INVALID', 'clipboardWrite 需要 content(base64 PNG)');
+ return fail('PATH_INVALID', 'clipboardWrite 需要 content(base64 PNG)', 'INVALID_REQUEST');
}
if (req.content.length > (LIBRARY_CLIPBOARD_WRITE_MAX_BYTES * 4) / 3 + 8) {
return fail('TOO_LARGE', `clipboardWrite 内容超限(上限 ${LIBRARY_CLIPBOARD_WRITE_MAX_BYTES} 字节)`);
}
const pngBytes = decodeStrictBase64(req.content);
if (pngBytes === null) {
- return fail('PATH_INVALID', 'clipboardWrite content 不是合法 base64');
+ return fail('PATH_INVALID', 'clipboardWrite content 不是合法 base64', 'INVALID_REQUEST');
}
if (pngBytes.byteLength === 0) {
- return fail('PATH_INVALID', 'clipboardWrite 不能写入空字节');
+ return fail('PATH_INVALID', 'clipboardWrite 不能写入空字节', 'INVALID_REQUEST');
}
if (pngBytes.byteLength > LIBRARY_CLIPBOARD_WRITE_MAX_BYTES) {
return fail('TOO_LARGE', `clipboardWrite 内容超限(上限 ${LIBRARY_CLIPBOARD_WRITE_MAX_BYTES} 字节)`);
}
if (!isPngBuffer(pngBytes)) {
- return fail('PATH_INVALID', 'clipboardWrite 只接受 PNG 字节');
+ return fail('PATH_INVALID', 'clipboardWrite 只接受 PNG 字节', 'INVALID_REQUEST');
}
if (!this.deps.writeClipboardPng) {
- return fail('UNSUPPORTED', '当前宿主不能写入系统剪贴板');
+ return fail('UNSUPPORTED', '当前宿主不能写入系统剪贴板', 'IMPLEMENTATION_UNSUPPORTED');
}
const now = this.deps.now?.() ?? Date.now();
@@ -751,7 +789,11 @@ export class GhostLibrarySlot {
const message = error instanceof Error ? error.message : String(error);
this.deps.log?.warn('ghost library clipboardWrite failed', { ghostId, err: message });
if (message === CLIPBOARD_NO_HOST_WINDOW) {
- return fail('UNSUPPORTED', '当前没有可挂靠的宿主窗口,无法写入系统剪贴板');
+ return fail(
+ 'UNSUPPORTED',
+ '当前没有可挂靠的宿主窗口,无法写入系统剪贴板',
+ 'NO_VISIBLE_WINDOW',
+ );
}
return fail('INTERNAL', '写入系统剪贴板失败');
}
@@ -830,7 +872,7 @@ export class GhostLibrarySlot {
return this.dbResultToPipe(op, r);
}
default:
- return fail('PATH_INVALID', `未知 op:${op}`);
+ return fail('PATH_INVALID', `未知 op:${op}`, 'INVALID_REQUEST');
}
}
}
diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.ts
index 2e0521d224..f0216a23eb 100644
--- a/apps/desktop/src/shared/ghost.ts
+++ b/apps/desktop/src/shared/ghost.ts
@@ -8238,6 +8238,7 @@ export type GhostPipeFsResult =
export const GHOST_LIBRARY_OPS = [
'open',
'status',
+ 'capabilities',
'read',
'write',
'writeBegin',
@@ -8262,6 +8263,51 @@ export const GHOST_LIBRARY_OPS = [
] as const;
export type GhostLibraryOp = (typeof GHOST_LIBRARY_OPS)[number];
+/** v1 能力清单只表达宿主实现支持,不等于此刻有窗口 / 已授权 / 库可用。 */
+export const GHOST_LIBRARY_CAPABILITY_OPERATIONS = ['clipboardWrite', 'saveAs'] as const;
+export type GhostLibraryCapabilityOperation = (typeof GHOST_LIBRARY_CAPABILITY_OPERATIONS)[number];
+
+export const GHOST_LIBRARY_CAPABILITIES_V1 = {
+ version: 1 as const,
+ operations: GHOST_LIBRARY_CAPABILITY_OPERATIONS,
+};
+
+/** 宿主实际操作的稳定失败类别;TIMEOUT / TRANSPORT_ERROR 由插件查询层本地分类,不从 message 猜测。 */
+export const GHOST_LIBRARY_ERROR_REASONS = [
+ 'IMPLEMENTATION_UNSUPPORTED',
+ 'NO_VISIBLE_WINDOW',
+ 'PERMISSION_DENIED',
+ 'LIBRARY_UNAVAILABLE',
+ 'INVALID_REQUEST',
+ 'CANCELLED',
+] as const;
+export type GhostLibraryErrorReason = (typeof GHOST_LIBRARY_ERROR_REASONS)[number];
+
+/**
+ * 消费 capabilities 结果:仅 version=1 且 operations 为字符串数组才有效。
+ * 额外字段忽略,未知 operation 忽略,已知项保留;有效 v1 缺某项才是 unsupported;
+ * 缺字段 / 错类型 / version 非 1 / 旧宿主 unknown-op 一律 unknown。
+ */
+export function classifyGhostLibraryOperationSupport(
+ result: unknown,
+ operation: GhostLibraryCapabilityOperation,
+): 'supported' | 'unsupported' | 'unknown' {
+ if (!result || typeof result !== 'object' || Array.isArray(result)) return 'unknown';
+ const row = result as Record<string, unknown>;
+ if (row.ok !== true || row.op !== 'capabilities') return 'unknown';
+ const caps = row.capabilities;
+ if (!caps || typeof caps !== 'object' || Array.isArray(caps)) return 'unknown';
+ const body = caps as Record<string, unknown>;
+ if (body.version !== 1 || !Array.isArray(body.operations)) return 'unknown';
+ if (!body.operations.every((item) => typeof item === 'string')) return 'unknown';
+ const known = new Set<string>(GHOST_LIBRARY_CAPABILITY_OPERATIONS);
+ const listed = new Set<string>();
+ for (const item of body.operations) {
+ if (known.has(item)) listed.add(item);
+ }
+ return listed.has(operation) ? 'supported' : 'unsupported';
+}
+
/** 上行:library 请求(cindy.library(req) ≡ send({type:'library-request', …req}))。 */
export interface GhostPipeLibraryRequest {
type: 'library-request';
@@ -8366,7 +8412,16 @@ export type GhostPipeLibraryResult =
| { ok: true; op: 'saveAs'; cancelled: false; path: string; bytes: number }
/** clipboardWrite 成功:bytes 是写入系统剪贴板的 PNG 位图字节数,不是文件引用。 */
| { ok: true; op: 'clipboardWrite'; bytes: number }
- | { ok: false; errorCode: string; message: string };
+ /** capabilities:无会话只读查询;operations 只表示实现支持。 */
+ | {
+ ok: true;
+ op: 'capabilities';
+ capabilities: {
+ version: 1;
+ operations: GhostLibraryCapabilityOperation[];
+ };
+ }
+ | { ok: false; errorCode: string; message: string; reason?: GhostLibraryErrorReason };
/** Library 概览(ghosts:library-overview IPC 载荷;设置页插件详情消费)。 */
export interface GhostLibraryOverview {
diff --git a/docs/dev-rules/plugin-library-storage.md b/docs/dev-rules/plugin-library-storage.md
index 6d4841432a..4598faf687 100644
--- a/docs/dev-rules/plugin-library-storage.md
+++ b/docs/dev-rules/plugin-library-storage.md
@@ -86,6 +86,47 @@ backups)对插件不可达——路径语法段首不许点,协议层天然
不是 `<hash>.<ext>`。同目录 sidecar `meta.json` / `preview.webp` 禁止当像素。
16MiB 是 library 分块阈值(更大走 writeBegin),cindy-media 单件 50MiB、配额
1GiB。library 软水位 8GiB + 磁盘保留 1GiB + 5 万文件保险丝。
+13. **只读操作能力合同(capabilities)**:`{op:'capabilities'}` 在资格审与 op 合法性
+ 校验之后、会话创建之前返回,不捕获 owner、不解析库根、不 open vault、不弹窗、
+ 不碰剪贴板、不泄漏 owner 或绝对库路径。成功形态固定为
+ `{ok:true, op:'capabilities', capabilities:{version:1, operations:['clipboardWrite','saveAs']}}`。
+ `operations` 只表达**实现支持**,不等于此刻有窗口、已授权或库可用。
+ 消费规则:仅 `version===1` 且 `operations` 为字符串数组才有效;额外字段忽略,未知
+ operation 忽略,已知项保留;有效 v1 清单缺少某项才是 unsupported;缺字段、错类型、
+ `version` 非 1、或旧宿主 unknown-op 一律 unknown。旧插件无需重装或重授权。
+ 实际操作失败仍用旧 `errorCode`,另加稳定 `reason`:无 handler=`IMPLEMENTATION_UNSUPPORTED`,
+ 无窗口=`NO_VISIBLE_WINDOW`,权限=`PERMISSION_DENIED`,库不可用=`LIBRARY_UNAVAILABLE`
+ (含 vault 透传的 open/status 失败),非法请求=`INVALID_REQUEST`(含非法/越界
+ `dbPath` 与未知 op),取消=`CANCELLED`。成功 `open`/`status` 的 `state:'unavailable'`
+ 仍用结果体 `reason`(如 `disk-missing`),不是失败 `reason` 枚举。查询/传输层本地分类
+ `TIMEOUT` / `TRANSPORT_ERROR`。插件不得解析人类 `message` 猜类别。插件基座改动按仓库白名单人工
+ Approve 才能合并。合同示例:
+
+ ```ts
+ // 旧宿主 unknown-op:没有 capabilities,不得当成全部支持或版本过旧
+ classifyGhostLibraryOperationSupport(
+ { ok: false, errorCode: 'PATH_INVALID', message: 'op 必须是 open / status / …' },
+ 'clipboardWrite',
+ ) === 'unknown'
+
+ // 新版支持:只说明实现存在,不等于此刻有窗口 / 已授权 / 库可用
+ classifyGhostLibraryOperationSupport(
+ { ok: true, op: 'capabilities', capabilities: { version: 1, operations: ['clipboardWrite', 'saveAs'] } },
+ 'clipboardWrite',
+ ) === 'supported'
+
+ // 新版无窗口:旧 errorCode 仍是 UNSUPPORTED,reason 才区分窗口缺失
+ { ok: false, errorCode: 'UNSUPPORTED', reason: 'NO_VISIBLE_WINDOW' }
+
+ // 新版拒权:能力查询与实际操作都不得越过资格审
+ { ok: false, errorCode: 'NOT_DECLARED', reason: 'PERMISSION_DENIED' }
+
+ // 错类型:数组内混入非字符串,整体 unknown,不得把其中合法项当有效 v1
+ classifyGhostLibraryOperationSupport(
+ { ok: true, op: 'capabilities', capabilities: { version: 1, operations: ['saveAs', 123] } },
+ 'saveAs',
+ ) === 'unknown'
+ ```
## Review 清单
@@ -94,6 +135,7 @@ backups)对插件不可达——路径语法段首不许点,协议层天然
3. 生命周期挂点(uninstall/setEnabled/owner 边界)是否补了对应的 dispose?
4. i18n 五语与中文标点门禁、FORGE_GUIDE §4.10.1 是否同步?
5. 会话级 extraDirs 是否只读、静默、专用槽不占 EXTRA_DIRS_MAX=10?confirmed 是否只认 writeCommit ACK,有没有发明 `libraryConfirmed.ts`?
+6. capabilities 是否在会话创建前返回?是否把 PERMISSION / UNAVAILABLE / 无窗口误判成旧宿主?失败 `reason` 是否稳定、旧 `errorCode` 是否保留?
最小验证入口: