Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(plugin): decouple capabilities from install approval
liugaowei348dacc1d73b
diff --git a/apps/desktop/help-knowledge/plugins.md b/apps/desktop/help-knowledge/plugins.mdindex e7bea4032d..67a52b94a1 100644--- a/apps/desktop/help-knowledge/plugins.md+++ b/apps/desktop/help-knowledge/plugins.md@@ -22,13 +22,15 @@ Plugins (internally "意识" / Ghost) extend what the agents can do — they add**Enabling and disabling:**-- **Enable / disable (globally)** from the plugin's detail page. Disabling puts its tools and panel to sleep but keeps the plugin installed — its layout slot is remembered and restored when you re-enable it.+- **Enable / disable (globally)** from the plugin's detail page. Disabling puts its tools and panel to sleep but keeps the plugin installed — its layout position is remembered and restored when you re-enable it.- **Disable for one working directory only** — a plugin can be turned off just for a specific project. In that project's sessions it behaves as if it isn't installed (its tools and `$command` are unavailable there); everywhere else it stays on.**Installing:**- Install from the marketplace, or add a `.cindy` file manually (drag it in / pick it from disk).-- Every install or update shows a **permission confirmation dialog** that lists exactly what the plugin can access (network domains, credentials it needs, tools, `$command`, panel). Nothing runs until you accept — and freshly installed plugins start **disabled** until you turn them on.+- Choosing Install, dragging a package, or picking one from disk installs and enables the selected plugin directly. Installation does not add a permission or version-confirmation step; review its declared capabilities on the plugin detail page.+- The server selects the release appropriate for this Cindy version before marketplace delivery. Desktop does not apply a second `minCindyVersion` gate; custom marketplaces and local `.cindy` packages follow the same install policy.+- Updates from stable marketplace sources are applied automatically when the plugin is idle. Failed attempts retry later; you can still click Update to retry immediately.**Using a plugin with `$command`:**@@ -37,8 +39,9 @@ Plugins (internally "意识" / Ghost) extend what the agents can do — they add**The permission / sandbox model (why plugins are safe):**-- A plugin's sandbox has **no filesystem, no network, and no direct system access** by default. It can only ask the host to do things it declared up front in its manifest, and the host enforces each one.-- **Network** access is limited to a domain allowlist the plugin declares; the host proxies every request. Credentials never enter the sandbox — the host injects them only into the declared requests.+- A plugin's sandbox has **no direct filesystem, network, or system access**. The host mediates every operation and enforces its actual execution context.+- Autonomous/background plugin behavior must stay within the capabilities and scopes declared directly in its manifest. Whether an in-flight plugin tool runs is decided by the existing Agent authorization flow; network and working-directory operations bind to that call, while bundled code and CLIs continue to use the existing Node worker. Plugin authors do not need a client change or a manifest Slot to pre-register a specific command, host, or path.+- **Autonomous network** access is limited to a domain allowlist the plugin declares; the host proxies every request. Credentials never enter the sandbox — the host injects them only into declared requests whose target matches that declaration.- Because of this, a plugin **can't see your files** on its own. A file reaches a plugin only when you or the agent explicitly hand one over (an image attachment, or a directory the host passes through after an ownership check).**Configuring a plugin's account / API key:**diff --git a/apps/desktop/src/main/__tests__/installedGhostManifest.test.ts b/apps/desktop/src/main/__tests__/installedGhostManifest.test.tsindex 204ed9ab88..e8c7257046 100644--- a/apps/desktop/src/main/__tests__/installedGhostManifest.test.ts+++ b/apps/desktop/src/main/__tests__/installedGhostManifest.test.ts@@ -55,7 +55,7 @@ afterEach(() => {});describe('installed ghost manifest compatibility', () => {- it('keeps valid Manual manifests strict and does not strip them', () => {+ it('keeps valid Manual manifests while normalizing legacy slots', () => {const raw = {...manifest(),manual: {@@ -65,7 +65,20 @@ describe('installed ghost manifest compatibility', () => {const parsed = parseInstalledGhostManifest(raw);- expect(parsed).toEqual({ ok: true, manifest: raw, legacyManualIgnored: false });+ expect(parsed).toEqual({+ ok: true,+ manifest: {+ schemaVersion: 2,+ id: 'legacy-plugin',+ name: 'Legacy plugin',+ version: '1.0.0',+ kind: 'chip',+ entry: 'main.js',+ tools: [{ name: 'run', description: 'Run the plugin' }],+ manual: raw.manual,+ },+ legacyManualIgnored: false,+ });});it.each([diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 30a80bb1e6..4f9ce797e5 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -1922,7 +1922,7 @@ function isIOSSimulatorPluginActive(ghosts = getGhostManager().list()): booleanreturn ghosts.some((ghost) =>ghost.enabled === true &&- ghost.manifest.slots.includes('ios-simulator') &&+ ghost.manifest.iosSimulator === true &&isGhostAvailableForActiveSession(ghost.manifest.id),);}@@ -3095,6 +3095,7 @@ app.on('browser-window-focus', (_event, win) => {const focusedAppContent = isAppContentWindow(win);syncAppFocusState(focusedAppContent);if (focusedAppContent) {+ syncPluginMarketForActiveOwner(30_000);// OAuth and system settings may complete outside Cindy. Focus is a// metadata-only fallback wake-up: each pending plugin is re-assessed, but// no stored value crosses the change bus.@@ -3721,6 +3722,32 @@ const createWindow = () => {let disposeSkillhubAutoSyncAuthListener: (() => void) | null = null;let disposeProviderAccessAuthListener: (() => void) | null = null;+let pluginMarketSyncInFlightScope: string | null = null;+let lastPluginMarketSyncScope: string | null = null;+let lastPluginMarketSyncAt = 0;+let pluginMarketPeriodicSyncTimer: ReturnType<typeof setInterval> | null = null;+const PLUGIN_MARKET_PERIODIC_SYNC_MS = 30 * 60 * 1000;++/** Run market discovery and automatic updates for the current stable owner. */+function syncPluginMarketForActiveOwner(minIntervalMs = 0): void {+ const session = getActiveAppSession();+ if (!session.dataOwnerId || isAppSessionBoundaryPending()) return;+ const scope = activeOwnerScopeKey();+ if (scope === pluginMarketSyncInFlightScope) return;+ const now = Date.now();+ if (+ scope === lastPluginMarketSyncScope &&+ now - lastPluginMarketSyncAt < minIntervalMs+ ) {+ return;+ }+ pluginMarketSyncInFlightScope = scope;+ lastPluginMarketSyncScope = scope;+ lastPluginMarketSyncAt = now;+ void syncDefaultMarketPlugins().finally(() => {+ if (pluginMarketSyncInFlightScope === scope) pluginMarketSyncInFlightScope = null;+ });+}function parseOptionalDeviceLinkDeviceId(value: unknown): string | null | undefined {if (value === undefined) return undefined;@@ -5952,6 +5979,11 @@ const registerIpcHandlers = () => {// 默认插件同步不能依赖用户先打开插件页。启动时本地 owner 已经稳定则立刻// 复用市场快照;云端登录/切号的通知可能早于 owner boundary 释放,因此// 延迟到当前调用栈结束后再按已提交的新 owner 补跑一次。+ pluginMarketPeriodicSyncTimer ??= setInterval(+ () => syncPluginMarketForActiveOwner(PLUGIN_MARKET_PERIODIC_SYNC_MS),+ PLUGIN_MARKET_PERIODIC_SYNC_MS,+ );+ pluginMarketPeriodicSyncTimer.unref();// ── Dialog: 目录选择器(v0.6 新增,与旧 show-open-directory-dialog 并存) ──ipcMain.handle('dialog:show-open-directory',@@ -8058,6 +8090,7 @@ app.on('ready', async () => {powerMonitor.on('resume', () => {authManager.handleResume();handleProviderModelSystemResume();+ syncPluginMarketForActiveOwner(30_000);// device-link:睡醒立即重连 relay,不干等退避计时器 + 心跳判死(最坏合计 ~75s)。handleDeviceLinkSystemResume();});@@ -8101,6 +8134,14 @@ app.on('ready', async () => {// 下方 shutdown-maker 关 session 触发的 markSessionTurnEnded 会把"退出时还在飞// 的 turn"伪装成正常收尾,重启后中断卡不出现(只剩硬崩溃能触发)。sync 阶段先于// async 的 shutdown-maker,顺序有保证。+onQuit(+ 'plugin-market-periodic-sync',+ () => {+ if (pluginMarketPeriodicSyncTimer) clearInterval(pluginMarketPeriodicSyncTimer);+ pluginMarketPeriodicSyncTimer = null;+ },+ 'sync',+);onQuit('session-active-turn-freeze',() => {diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.tsindex fd72105c8a..044f8c2bd3 100644--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts@@ -11,14 +11,12 @@ import {GHOST_LOCALE_MAX_BYTES,GHOST_ICON_MAX_BYTES,GHOST_INSTALL_MANIFEST_MAX_BYTES,- GHOST_SLOTS,GHOST_MANUAL_ENTRY_FILE,GHOST_MANUAL_MD_MAX_BYTES,GHOST_SKILL_MD_MAX_BYTES,ghostLocalePathFor,ghostInstallApprovalToken,ghostIconMimeType,- isBrokerEligibleGhostId,isValidGhostId,resolveGhostManifestLocale,validateGhostManifest,@@ -45,7 +43,6 @@ import { readBoundedFileNoFollowSync } from '../utils/readBoundedFile.js';import { checkSkillMdConsistency } from './skillSlot.js';import {createGhostInstallReceipt,- effectiveInstallOrigin,GhostInstallReceiptStore,hashApprovedSkillContent,readLegacyInstallTrust,@@ -192,7 +189,8 @@ export interface GhostManagerOptions {getLocale?: () => string;/*** `approveTrustedBundledInstall` 的 builtin-only 边界:id 是否对应一颗随包种子。- * 该入口不经用户确认就铸出批准,因此 id 与 source 都必须由生产接线明确放行。+ * 该入口不经用户安装动作就固化验证记录,因此 id 与 source 都必须由+ * 生产接线明确放行。*/isTrustedBundledId?: (id: string) => boolean;/**@@ -260,14 +258,6 @@ export interface GhostUninstallOptions {recordBuiltinTombstone?: boolean;}-interface InstalledReapprovalProjection {- manifest: GhostManifest;- trust: GhostTrustInfo;- localeResources: Record<string, GhostManifestLocaleResource>;- iconDataUrl?: string;- skillContentSha256: Record<string, string>;-}-export interface LegacyGhostApprovalProjection {manifest: GhostManifest;enabled: boolean;@@ -447,24 +437,6 @@ export async function readLegacyGhostApprovalProjection(return { projection, sha256: hashLegacyGhostApprovalProjection(projection) };}-function hashInstalledReapprovalProjection(- projection: InstalledReapprovalProjection,-): string {- return crypto- .createHash('sha256')- .update(- JSON.stringify({- version: 1,- manifest: projection.manifest,- trust: projection.trust,- localeResources: projection.localeResources,- iconDataUrl: projection.iconDataUrl ?? null,- skillContentSha256: projection.skillContentSha256,- }),- )- .digest('hex');-}-/*** `runExclusiveMutation` 回调内唯一可用的嵌套 mutation capability。* capability 在回调结束后立即失效,避免调用者绕过串行 lane 或复用旧 owner 上下文。@@ -491,9 +463,8 @@ export interface GhostExclusiveMutation {/*** 区分“包本身坏了”和“包使用了更新版 Cindy 才认识的契约”。*- * 这里只收窄识别两个可证明是 Host 版本差异的形状:未来 schemaVersion,或- * 字符串形态的未知 capability slot。其它畸形输入仍交给完整 manifest 校验,- * 不能借友好提示放松安装安全边界。+ * 这里只识别未来 schemaVersion。v3 未知顶层字段由 manifest 校验器保留但+ * 不解释;v2 未知 slot 则单独保留供兼容诊断,两者都不拒绝整份插件。*/export function ghostManifestHostUnsupportedReason(raw: unknown): string | null {if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;@@ -501,16 +472,11 @@ export function ghostManifestHostUnsupportedReason(raw: unknown): string | nullif (typeof record.schemaVersion === 'number' &&Number.isInteger(record.schemaVersion) &&- record.schemaVersion > 2+ record.schemaVersion > 3) {return `插件使用了更新的清单格式(schemaVersion ${record.schemaVersion})`;}- if (!Array.isArray(record.slots)) return null;- const supported = new Set<string>([...GHOST_SLOTS, 'model']);- const unknown = [- ...new Set(record.slots.filter((slot): slot is string => typeof slot === 'string')),- ].filter((slot) => !supported.has(slot));- return unknown.length > 0 ? `插件需要当前 Cindy 尚不支持的能力:${unknown.join(' / ')}` : null;+ return null;}/**@@ -518,8 +484,8 @@ export function ghostManifestHostUnsupportedReason(raw: unknown): string | null* receipt 才是 manifest / trust / enabled / revision 的授权事实。** 设计要点:- * - **目录只证明在装**:list() 实扫内容目录,但批准状态来自安装根之外的- * receipt;旧安装没有 receipt 时保持不可运行,更新需完整重新确认;+ * - **目录只证明在装**:list() 实扫内容目录,但可运行的安装验证状态来自+ * 安装根之外的 receipt;旧安装优先自动迁移,无法恢复时保持不可运行并引导重新安装;* - **装载先落 staging 再切正式**(对齐 skillhub/installService 的做法):* 解压全程发生在 `.cindy-installing-*` 临时目录,校验全过才 rename 到* rootDir/<id>,任何一步失败都不会留下半截安装;@@ -705,7 +671,7 @@ export class GhostManager {* 清标记,标记带本次 `packageSha256`。恢复时同步读 receipt,`receipt.packageSha256 ===* marker.packageSha256` 即"已提交":* - install 未提交 → finalDir 是不完整安装,删掉(否则迁移会把它当 legacy 收编,而- * 崩溃窗口内 manifest 可能已被同权限进程改写 = 用户确认 A 却授权 B);已提交 → 保留;+ * 崩溃窗口内 manifest 可能已被同权限进程改写 = 检查 A 却固化 B);已提交 → 保留;* - update 未提交 → 回滚到 backup(旧字节+旧 receipt 自洽);已提交 → 回收陈旧 backup。* 这修掉了"final 在位就删 backup"把"新字节+旧 receipt"固化成"按旧批准跑新代码"的洞。*@@ -1017,11 +983,12 @@ export class GhostManager {/*** 从 `.cindy` 包的内存投影算技能字节指纹(P0-8)。*- * 批准基线必须取自**用户确认过、且不可再被本机进程改写**的来源。旧写法在+ * 固化基线必须取自**合法安装事务已校验、且不可再被本机进程改写**+ * 的来源。旧写法在* staging→final 发布之后才从 finalDir 首读 —— publish 与首次 hash 之间被换掉的* SKILL.md 正文/辅助文件会同时成为 receipt 指纹与快照,后续校验全自洽,篡改被* 洗成批准事实。包投影(JSZip 内存条目)在 inspect 时已被 packageSha256 钉住、- * 与用户确认的是同一份字节;据它算指纹后,发布后的目录漂移会在快照落盘对账时+ * 与安装入口校验的是同一份字节;据它算指纹后,发布后的目录漂移会在快照落盘对账时* 如实 fail closed(拒装),而不是被钉进批准。*/private async hashSkillContentFromPackage(@@ -1055,21 +1022,6 @@ export class GhostManager {return this.receiptStore.rootDir();}- /**- * Authorization-time install origin. Missing / unreadable receipts are- * `manual` — same fail-closed as today, never a privilege upgrade.- */- readEffectiveInstallOrigin(id: string): 'manual' | 'agent-forge' {- this.ensureCurrentOwnerContextSync();- try {- const approval = this.readApproval(id);- if (approval.state !== 'approved') return 'manual';- return effectiveInstallOrigin(approval.receipt);- } catch {- return 'manual';- }- }-/*** Host-owned evidence for reconnecting an installation to retained source metadata.* A pending package mutation or an invalid approval fails closed. Legacy provenance@@ -1260,16 +1212,16 @@ export class GhostManager {/*** 一次性 legacy backfill 迁移(docs/dev-rules/plugin-security-and-authoring.md 第 5 节* 红线的落地)。#1080 把授权事实从可变安装目录搬到 Host receipt,升级前装的插件没有- * receipt —— 若不迁移,它们会一律落到 `legacy-unapproved`、被列停用、要用户逐个重新- * 确认(这正是 #1080 被回滚的原因)。这里从旧的三份事实源(`ghost.json` /+ * receipt —— 若不迁移,它们会一律落到 `legacy-unapproved`、被列停用、要用户逐个+ * 重新安装(这正是 #1080 被回滚的原因)。这里从旧的三份事实源(`ghost.json` /* `.cindy-trust.json` / `.disabled`)重建等价 receipt,让存量插件升级后**无感可用**。** 三条不变量:* - **全局一次性**:状态根有迁移 ledger 即视为已迁过,此后缺 receipt 一律 fail closed,* 不再迁。理由见 `GhostLegacyMigrationLedger` 头注释(否则删 receipt 就能骗一次* "从可变安装目录重建授权")。- * - **不扩权、不等于新确认**:receipt 权限集 = 当前 `ghost.json` 声明,等价于旧模型- * 无条件授权的那一组;此后任何 manifest/权限变化照旧走完整确认(update 流程不变)。+ * - **不扩权**:receipt 中的 manifest = 当前 `ghost.json` 声明,只重建旧安装已有的+ * 等价运行事实;此后 manifest 变化只能由新的合法安装/更新事务固化。* - **只写状态根、绝不动安装目录**:三份旧文件原样保留,因此回滚到旧客户端时它照旧* 从安装目录判定启停,不会错位(§5 兜底第 4 条 回滚余地)。*@@ -1388,7 +1340,7 @@ export class GhostManager {// 暂时读不动批准事实不等于 legacy。尤其不能把它放进普通 pendingIds:// 若 receipt 随后消失,续跑会把可变安装目录误当成旧授权事实重新铸批准。// 记为确定性 fail-closed 审计项;原 receipt 恢复可读时仍自然生效,真的丢失- // 则只能走完整重新批准,不能自动 backfill。+ // 则只能通过新的合法安装/更新事务恢复,不能自动 backfill。result.failed.push(id);pendingForRetry.delete(id);unreadableReceiptIds.push(id);@@ -1400,7 +1352,7 @@ export class GhostManager {}// 有未清的事务标记 = 一次装入/更新崩在半途、启动恢复还没收干净(通常恢复已在// 构造期把它清掉,这里兜住"恢复删 finalDir 失败"的残留)。绝不迁移这种目录 ——- // 它的字节来源不是"用户确认过的旧安装",而是一次未完成事务的中间态。+ // 它的字节来源不是已完成的旧安装,而是一次未完成事务的中间态。if (this.hasPendingMutationJournal(id)) {result.skipped.push(id);blockedByPendingJournal.push(id);@@ -1476,7 +1428,7 @@ export class GhostManager {// - 带 errno 的环境错(EACCES/ENOSPC/EBUSY…,状态根写不动、文件被占等)是// **瞬时**故障,不属于 §5 的"旧事实读不出/自相矛盾" —— 记 retryPending,// 台账停在 in-progress,下次启动自动续跑;写进 completed 的 failedIds 会把- // 一次环境抖动永久封成"需要人工重新确认"。+ // 一次环境抖动永久封成"需要用户重新安装"。// - 无 errno 的校验错(manifest 不合法、技能目录含链接、locale 装入后损坏)// 与 ENOENT(声明的文件缺失 = 内容状态,不是抖动)是**确定性**内容无效,// 记 failed、fail closed,走每插件恢复 UI。@@ -1554,7 +1506,8 @@ export class GhostManager {*//*** 有未清事务标记 = 一次装入/更新崩在半途、启动恢复还没收干净。任何会**写 receipt**- * 的入口(主迁移、legacy backfill、用户重新确认)都必须让路:绝不对一次未完成事务的+ * 的入口(主迁移、legacy backfill、新的安装/更新事务)都必须让路:绝不对一次+ * 未完成事务的* 中间态字节铸出批准 —— 否则 journal 之后的恢复会回滚字节却留下这份 receipt/技能快照,* 形成永不自愈的错位授权(约束 B-2/B-5/I-1)。journal 由启动恢复负责收敛,收敛后这些* 入口自然放行;若恢复被卡死,退出通道由批量恢复入口负责(见约束文档 §8 已知项),@@ -1668,7 +1621,7 @@ export class GhostManager {pendingForRetry.delete(id);} catch (err) {// 与主迁移循环同一分类:瞬时 IO 抖动不记 failed(否则写进 completed 台账就- // 把一次环境抖动永久封成"需要人工重新确认"),只记日志、留待下次恢复触发重试;+ // 把一次环境抖动永久封成"需要用户重新安装"),只记日志、留待下次恢复触发重试;// 确定性内容无效才 fail closed。if (isTransientBackfillError(err)) {retryIds.push(id);@@ -1785,327 +1738,6 @@ export class GhostManager {return true;}- /**- * 「从已装目录重新确认」第一步:只读出确认卡需要的事实,零副作用。- *- * 这是本地包批准丢失(一次性迁移之后 receipt 又损坏/被删)时的第三条恢复路径 ——- * 不用用户翻出原始 `.cindy` 文件,也不自动放行:字节从已装目录读,权限清单在确认卡- * 上**全量**展示(无批准基线,全部按新增项列),用户逐条看过点确认才开 receipt。- * 本地 `.cindy` 的运行字节本来就一直从这个可变目录现读(§7 登记),两条恢复路径的- * 差别只是字节来源,授权边界同样是那张确认卡。- *- * `manifestSha256` 是「确认卡展示的」与「confirm 时批准的」之间的字节绑定:renderer- * 原样回传,confirm 侧重读重算,对不上即拒 —— 与更新流程的 `expectedPackageSha256`- * 同形,防确认间隙里 ghost.json 被换(#636 的同类窗口)。- *- * 随包插件一律拒:它们的批准由 provisioning 与种子逐字节对账后自动补,重启即恢复,- * 不走人工确认(也不能走 —— 这条路的 trust 封顶在非官方档)。- */- async inspectInstalledReapproval(id: string): Promise<- | {- manifest: GhostManifest;- trust: GhostTrustInfo;- manifestSha256: string;- approvalProjectionSha256: string;- /** `.disabled` 镜像的读数:确认卡"立即开启"勾选的默认值,不重置用户停用偏好。 */- localeResources: Record<string, GhostManifestLocaleResource>;- iconDataUrl?: string;- skillContentSha256: Record<string, string>;- previouslyEnabled: boolean;- }- | { rejection: InstallRejection }- > {- this.ensureCurrentOwnerContextSync();- if (!isValidGhostId(id) || this.options.isTrustedBundledId?.(id)) {- return { rejection: { code: 'file-invalid', reason: '该插件不支持从安装目录重新确认' } };- }- if (this.readApproval(id).state === 'approved') {- return { rejection: { code: 'state-changed', reason: '插件批准状态已恢复,无需重新确认' } };- }- // 有未清事务标记时绝不铸批准:否则启动恢复回滚字节后会留下这份 receipt/技能快照,- // 形成永不自愈的错位授权(B-2/B-5/I-1)。确认第二步会经此再查一次(持互斥锁,- // 与 install/update 不交错),所以只在这里设闸即可覆盖 inspect 与 confirm 两步。- if (this.hasPendingMutationJournal(id)) {- return {- rejection: {- code: 'state-changed',- reason: '插件有未完成的安装/更新事务正在恢复,请重启应用完成恢复后再重新确认',- },- };- }- const dir = path.join(this.contentRootDir(), id);- try {- if (classifyGhostDirEntrySync(dir) !== 'directory') {- return { rejection: { code: 'not-installed', reason: `意识 ${id} 未装入` } };- }- } catch {- return { rejection: { code: 'not-installed', reason: `意识 ${id} 未装入` } };- }- let rawBytes: Buffer;- try {- const manifestPath = resolveGhostContentPathSync(dir, GHOST_MANIFEST_FILE, {- expect: 'file',- label: 'installed manifest',- });- const bytes = readBoundedFileNoFollowSync(manifestPath, GHOST_MANIFEST_MAX_BYTES, {- containWithin: fs.realpathSync(dir),- });- if (bytes === null) throw new Error('manifest is missing or oversized');- rawBytes = bytes;- } catch (err) {- return {- rejection: {- code: 'not-installed',- reason: `安装目录里读不到清单:${err instanceof Error ? err.message : String(err)}`,- },- };- }- let parsed: unknown;- try {- parsed = JSON.parse(rawBytes.toString('utf8'));- } catch (err) {- return {- rejection: {- code: 'file-invalid',- reason: `清单不是合法 JSON:${err instanceof Error ? err.message : String(err)}`,- },- };- }- const validated = validateGhostManifest(parsed);- if (!validated.ok) return { rejection: { code: 'file-invalid', reason: validated.reason } };- if (validated.manifest.id !== id) {- return { rejection: { code: 'file-invalid', reason: '清单 id 与安装目录不一致' } };- }- // tokenBroker 门控与装入侧同一条规则。官方前缀命中照旧放行;其余问- // 生产接线的 first-party 判据(含 receipt 装入来源)。- const brokerAuthorized =- this.options.isTokenBrokerAuthorized?.(validated.manifest) ?? isBrokerEligibleGhostId(id);- if (- !brokerAuthorized &&- (validated.manifest.network?.secrets ?? []).some((s) => s.oauth?.tokenBroker !== undefined)- ) {- return {- rejection: {- code: 'file-invalid',- reason: `id "${id}" 声明了 oauth.tokenBroker——当前安装来源或组织身份无权使用授权 broker`,- },- };- }- let localeResources: Record<string, GhostManifestLocaleResource>;- let skillContentSha256: Record<string, string>;- let trust: GhostTrustInfo;- try {- trust = readLegacyInstallTrust(dir) ?? {- level: 'unverified',- publisherSigned: false,- publisherVerified: false,- reviewed: false,- };- } catch (err) {- return {- rejection: {- code: 'file-invalid',- reason: `安装目录信任数据不可读: ${err instanceof Error ? err.message : String(err)}`,- },- };- }- try {- localeResources = this.readApprovedLocaleResources(dir, validated.manifest);- skillContentSha256 = await hashApprovedSkillContent(validated.manifest, dir);- } catch (err) {- return {- rejection: {- code: 'file-invalid',- reason: `安装目录批准内容不可读或不一致: ${err instanceof Error ? err.message : String(err)}`,- },- };- }- const iconDataUrl = this.readInstalledIconDataUrl(dir, validated.manifest) ?? undefined;- const projection: InstalledReapprovalProjection = {- manifest: validated.manifest,- trust,- localeResources,- ...(iconDataUrl !== undefined ? { iconDataUrl } : {}),- skillContentSha256,- };- return {- manifest: projection.manifest,- trust: projection.trust,- localeResources: projection.localeResources,- ...(projection.iconDataUrl !== undefined ? { iconDataUrl: projection.iconDataUrl } : {}),- skillContentSha256: projection.skillContentSha256,- manifestSha256: crypto.createHash('sha256').update(rawBytes).digest('hex'),- approvalProjectionSha256: hashInstalledReapprovalProjection(projection),- previouslyEnabled: !this.isDisabledMarkerPresentSync(dir),- };- }-- /**- * 「从已装目录重新确认」第二步:用户在确认卡上点了同意,据此开 receipt。- *- * 与迁移(`backfillLegacyApproval`)的本质区别:**这是一次真实的用户确认**(用户- * 刚看完全量权限清单),不受迁移 ledger 一次性门约束,来源记 `user-reapproval`。- * 与迁移的共同点:trust 走同一个封顶读取器、技能字节现算钉指纹、只写状态根。- */- async reapproveInstalled(- id: string,- opts: {- enable: boolean;- expectedManifestSha256: string;- expectedApprovalProjectionSha256: string;- expectedInstalledApproval: string;- },- ): Promise<{ ghost: InstalledGhost } | { rejection: InstallRejection }> {- return this.runExclusiveMutation(() => this.reapproveInstalledUnlocked(id, opts));- }-- private async reapproveInstalledUnlocked(- id: string,- opts: {- enable: boolean;- expectedManifestSha256: string;- expectedApprovalProjectionSha256: string;- expectedInstalledApproval: string;- },- ): Promise<{ ghost: InstalledGhost } | { rejection: InstallRejection }> {- // 确认期间批准状态不得变过:与更新流程同款前置条件(token 由 Main 现读比对)。- const currentToken = ghostInstallApprovalToken(- this.list().find((g) => g.manifest.id === id)?.approval,- );- if (currentToken !== opts.expectedInstalledApproval || currentToken.startsWith('approved')) {- return {- rejection: { code: 'state-changed', reason: '插件批准状态在确认后发生了变化,请重新确认' },- };- }- // 重走只读检查(含随包拒收/清单校验),并绑定确认卡展示时的清单字节。- const inspected = await this.inspectInstalledReapproval(id);- if ('rejection' in inspected) return inspected;- if (inspected.manifestSha256 !== opts.expectedManifestSha256) {- return {- rejection: { code: 'state-changed', reason: '插件清单在确认后发生了变化,请重新确认' },- };- }- if (inspected.approvalProjectionSha256 !== opts.expectedApprovalProjectionSha256) {- return {- rejection: {- code: 'state-changed',- reason: '安装目录批准内容在确认后发生了变化,请重新确认',- },- };- }- // 指令查重与装入/更新同一条规则(豁免自己):重新确认不是给撞名指令开的后门。- if (inspected.manifest.command !== undefined) {- const commandFold = inspected.manifest.command.toLowerCase();- const holder = this.list().find(- (g) =>- g.manifest.id !== id &&- g.manifest.command !== undefined &&- g.manifest.command.toLowerCase() === commandFold,- );- if (holder) {- return {- rejection: {- code: 'command-conflict',- reason: `指令 /${inspected.manifest.command} 已被已装意识「${holder.manifest.name}」(${holder.manifest.id})占用`,- },- };- }- }- const contentRoot = this.contentRootDir();- const dir = path.join(contentRoot, id);- if (!this.isRealDirChild(contentRoot, id)) {- return {- rejection: { code: 'state-changed', reason: '插件安装目录在确认后发生了变化,请重新确认' },- };- }- const marker = path.join(dir, DISABLED_MARKER_FILE);- let markerExisted = false;- try {- try {- if (classifyGhostDirEntrySync(marker) !== 'file') {- throw new Error('ghost disabled marker is not a regular file');- }- markerExisted = true;- } catch (error) {- if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;- }- // 先提交兼容镜像,再提交权威 receipt。否则 marker 失败会留下“返回成功但实际- // 启停态与 receipt 矛盾”的部分成功。没有状态变化时不触碰 marker。- if (opts.enable) {- if (markerExisted) await fs.promises.rm(marker, { force: true });- } else if (!markerExisted) {- await fs.promises.writeFile(marker, '', { flag: 'wx' });- }- } catch (err) {- return {- rejection: {- code: 'io',- reason: `启停标记写入失败:${err instanceof Error ? err.message : String(err)}`,- },- };- }- try {- const localeResources = inspected.localeResources;- const iconDataUrl = inspected.iconDataUrl;- const skillContentSha256 = inspected.skillContentSha256;- await this.receiptStore.write(- createGhostInstallReceipt({- manifest: inspected.manifest,- localeResources,- enabled: opts.enable,- trust: inspected.trust,- skillContentSha256,- ...(iconDataUrl !== undefined ? { iconDataUrl } : {}),- }),- { skillSourceDir: dir },- );- } catch (err) {- const markerChanged = opts.enable ? markerExisted : !markerExisted;- if (markerChanged) {- try {- if (!this.isRealDirChild(contentRoot, id)) {- throw new Error('ghost install directory changed before marker rollback');- }- if (markerExisted) {- try {- if (classifyGhostDirEntrySync(marker) !== 'file') {- throw new Error('ghost disabled marker is not a regular file');- }- } catch (markerError) {- if ((markerError as NodeJS.ErrnoException).code !== 'ENOENT') throw markerError;- await fs.promises.writeFile(marker, '', { flag: 'wx' });- }- } else {- await fs.promises.rm(marker, { force: true });- }- } catch (rollbackErr) {- (this.options.log?.error ?? this.options.log?.warn)?.call(- this.options.log,- 'ghost reapproval receipt failed and marker rollback also failed',- {- id,- error: rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr),- },- );- }- }- return {- rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) },- };- }- this.untrustedApprovals.delete(this.isolationKey(id));- this.options.log?.info('ghost reapproved from installed dir', {- id,- enabled: opts.enable,- trustLevel: inspected.trust.level,- origin: 'user-reapproval',- });- const ghost = this.list().find((g) => g.manifest.id === id);- if (!ghost) return { rejection: { code: 'io', reason: '重新确认后读不到插件清单' } };- this.options.onChanged?.(this.list());- return { ghost };- }-/** 扫描已装意识(同步 —— renderer 首帧 sendSync 拉取,目录极小不卡启动)。 */list(): InstalledGhost[] {this.ensureCurrentOwnerContextSync();@@ -2319,8 +1951,8 @@ export class GhostManager {* 启用 / 停用一张意识。停用不删任何东西,只把批准 receipt 的 enabled 翻过来* (安装目录里的 `.disabled` 只作为旧版本兼容镜像同步维护)。幂等。*- * 两个方向不对称:**启用需要有效批准状态**(无批准的存量安装必须先重新确认- * 权限),**停用必须永远能成功** —— 停用是安全的收敛方向,不能因为技能快照+ * 两个方向不对称:**启用需要有效安装验证状态**(无法自动恢复时先重新安装),+ * **停用必须永远能成功** —— 停用是安全的收敛方向,不能因为技能快照* 被外部删掉之类的环境问题把插件卡在"既不能用也不能关"。*/async setEnabled(@@ -2356,7 +1988,7 @@ export class GhostManager {return {rejection: {code: 'approval-required',- reason: `插件 ${id} 缺少有效的安装批准状态,请重新选择安装包并确认权限`,+ reason: `插件 ${id} 缺少有效的安装验证记录,请重新安装`,},};}@@ -2485,14 +2117,16 @@ export class GhostManager {/*** 只验不装:读 .cindy → 解包 → 校验清单,返回清单(含 icon data URL),- * 零副作用。「装意识前弹确认」(README 安全原则)的数据来源 —— 三个装入- * 入口(设置页 / 拖入 / 双击)都先 inspect 给用户看明白,确认后才 install。+ * 零副作用。设置页 / 拖入 / 双击三个装入入口都先 inspect,校验通过后+ * 才 install;能力知情面由安装后的插件详情统一展示。*/async inspect(lizFilePath: string): Promise<| {manifest: GhostManifest;/** 包内原始清单,仅供 Main 安全比较。 */canonicalManifest: GhostManifest;+ /** v2 声明但当前 Host 未映射的 slot;只用于兼容诊断。 */+ unsupportedLegacySlots: string[];trust: GhostTrustInfo;packageSha256: string;iconDataUrl?: string;@@ -2504,6 +2138,7 @@ export class GhostManager {return {manifest: parsed.manifest,canonicalManifest: parsed.canonicalManifest,+ unsupportedLegacySlots: parsed.unsupportedLegacySlots,trust: parsed.trust,packageSha256: parsed.packageSha256,...(parsed.iconDataUrl !== undefined ? { iconDataUrl: parsed.iconDataUrl } : {}),@@ -2519,6 +2154,7 @@ export class GhostManager {approvedManifest: GhostManifest;canonicalManifest: GhostManifest;localeResources: Record<string, GhostManifestLocaleResource>;+ unsupportedLegacySlots: string[];trust: GhostTrustInfo;packageSha256: string;iconDataUrl?: string;@@ -2735,8 +2371,8 @@ export class GhostManager {? MAX_NODE_UNCOMPRESSED_BYTES: MAX_BASIC_UNCOMPRESSED_BYTES;try {- // inspect 阶段先用流式解压把总量算清。这样恶意压缩包不能等到确认后,- // 或借签名/图标读取,在“检查上限之前”先撑出一个超大内存块。+ // inspect 阶段先用流式解压把总量算清。这样恶意压缩包不能借+ // 签名/图标读取,在“检查上限之前”先撑出一个超大内存块。await assertZipUncompressedLimit(allEntries, maxUncompressedBytes);} catch (err) {return {@@ -2786,8 +2422,8 @@ export class GhostManager {iconDataUrl = buildIconDataUrl(v.manifest.icon, iconData) ?? undefined;}- // 5) skill 槽:声明的每个技能目录必须真有 SKILL.md,且 frontmatter 与清单- // 声明逐字一致——确认框展示的必须就是 Agent 实际读到的,装入前把账算清。+ // 5) skill 能力:声明的每个技能目录必须真有 SKILL.md,且 frontmatter 与清单+ // 声明逐字一致——安装事务校验的必须就是 Agent 实际读到的,装入前把账算清。// 对未本地化的 v.manifest 校验即可:skill 字段不在本地化白名单// (GhostManifestLocaleResource)内,localizedManifest 与之恒等。for (const skillItem of v.manifest.skill?.items ?? []) {@@ -2903,6 +2539,7 @@ export class GhostManager {approvedManifest: v.manifest,canonicalManifest: v.manifest,localeResources,+ unsupportedLegacySlots: v.unsupportedLegacySlots,trust: signature.trust,packageSha256: crypto.createHash('sha256').update(buf).digest('hex'),...(iconDataUrl !== undefined ? { iconDataUrl } : {}),@@ -2917,7 +2554,6 @@ export class GhostManager {initiallyEnabled?: boolean;expectedPackageSha256?: string;trustOverride?: GhostHostTrustOverride;- installOrigin?: string;},) {return this.runExclusiveMutation(() => this.installUnlocked(lizFilePath, opts));@@ -2929,11 +2565,9 @@ export class GhostManager {initiallyEnabled?: boolean;expectedPackageSha256?: string;trustOverride?: GhostHostTrustOverride;- installOrigin?: string;},): Promise<{ ghost: InstalledGhost } | { rejection: InstallRejection }> {- // 装入初始启用态由 UI 层决定(装入确认框勾选,默认沉睡);缺省 true- // 保持既有调用方(测试等)语义不变。+ // 装入初始启用态由调用方决定;缺省 true 保持既有调用方语义不变。const initiallyEnabled = opts?.initiallyEnabled ?? true;// 1–3) 读文件 / 解包 / 校验清单(与 inspect 共用)const parsed = await this.parse(lizFilePath);@@ -2945,7 +2579,7 @@ export class GhostManager {return {rejection: {code: 'file-invalid',- reason: '插件文件在确认后发生了变化,请重新选择并确认',+ reason: '插件文件在检查后发生了变化,请重新选择',},};}@@ -3037,7 +2671,6 @@ export class GhostManager {packageSha256,revision: receiptRevision,...(iconDataUrl !== undefined ? { iconDataUrl } : {}),- ...(opts?.installOrigin !== undefined ? { installOrigin: opts.installOrigin } : {}),});await this.receiptStore.write(receipt, { skillSourceDir: finalDir });let tombstoneClearPending = false;@@ -3135,7 +2768,6 @@ export class GhostManager {expectedInstalledApproval: string;expectedPackageSha256?: string;trustOverride?: GhostHostTrustOverride;- installOrigin?: string;beforePackageCommit?: () => GhostPackageCommitPreparation | void;/** 目录换位完成后、任何通知或运行时收尾前触发。 */onPackagePlaced?: () => void;@@ -3150,7 +2782,6 @@ export class GhostManager {expectedInstalledApproval: string;expectedPackageSha256?: string;trustOverride?: GhostHostTrustOverride;- installOrigin?: string;/** 新目录已换位、旧目录仍可回滚时执行;抛错会恢复旧版本。 */beforePackageCommit?: () => GhostPackageCommitPreparation | void;/** 目录换位完成后、任何通知或运行时收尾前触发。 */@@ -3166,7 +2797,7 @@ export class GhostManager {return {rejection: {code: 'file-invalid',- reason: '插件文件在确认后发生了变化,请重新选择并确认',+ reason: '插件文件在检查后发生了变化,请重新选择',},};}@@ -3196,12 +2827,12 @@ export class GhostManager {return {rejection: {code: 'state-changed',- reason: '插件批准状态在确认后发生了变化,请重新检查权限',+ reason: '插件安装状态在检查后发生了变化,请重试',},};}- // 延续当前唤醒/沉睡状态。旧安装尚无 receipt 时只在完整重新确认后- // 采用原 `.disabled` 镜像;损坏 receipt 一律保持停用。+ // 延续当前唤醒/沉睡状态。旧安装尚无 receipt 时,重新安装仍采用原+ // `.disabled` 镜像;损坏 receipt 一律保持停用。const enabled =approvalResult.state === 'approved'? // 读时合并后的有效值:receipt 可能因状态根短暂不可写而停在陈旧的 enabled=true,@@ -3374,7 +3005,6 @@ export class GhostManager {packageSha256,revision: receiptRevision,...(iconDataUrl !== undefined ? { iconDataUrl } : {}),- ...(opts.installOrigin !== undefined ? { installOrigin: opts.installOrigin } : {}),});await this.receiptStore.write(receipt, { skillSourceDir: finalDir });} catch (err) {@@ -3472,14 +3102,14 @@ export class GhostManager {}/**- * 随包种子已经由 provisioning 层逐字节对账后,为其建立 Host 批准状态。- * 该入口不得用于市场包或任意本地目录;它不替代用户安装确认。id 必须落在注入的+ * 随包种子已经由 provisioning 层逐字节对账后,为其建立 Host 安装验证状态。+ * 该入口不得用于市场包或任意本地目录;id 必须落在注入的* 随包种子清单里(`isTrustedBundledId`)。** `markerEnabled` 是安装目录 `.disabled` 兼容镜像的读数,**只往停用方向合并,* 不往启用方向翻**:receipt 才是授权事实,镜像文件可被外部因素移除(AV 隔离* 恢复/同步冲突解析/手动清理),拿它覆写 receipt 会让用户显式停用的插件在下一轮- * 对账被静默重新启用 —— 无确认、无审计,且带 skill 槽的插件会随之重新挂进全局+ * 对账被静默重新启用 —— 无用户操作、无审计,且带 skill 能力的插件会随之重新挂进全局* 技能链。反方向(镜像说停用、receipt 说启用)必须照办:停用是安全方向,而且* 旧客户端只会写镜像文件。重新启用只有用户显式 `setEnabled(true)` 一条路。*/@@ -3636,11 +3266,14 @@ export class GhostManager {) {throw new Error('approveTrustedBundledInstall source manifest does not match approval');}- const localeResources = this.readApprovedLocaleResources(sourceDir, manifest);- const iconDataUrl = this.readInstalledIconDataUrl(sourceDir, manifest) ?? undefined;+ // v2 作者清单仍带 slots,进入运行时后则会被投影成直接能力字段。批准链只比较、+ // 持久化规范化结果,避免同一份 v2 清单因作者格式和运行时格式不同而被误判为扩权。+ const approvedManifest = expectedManifest.manifest;+ const localeResources = this.readApprovedLocaleResources(sourceDir, approvedManifest);+ const iconDataUrl = this.readInstalledIconDataUrl(sourceDir, approvedManifest) ?? undefined;const packageSha256 = await hashApprovedDirectory(sourceDir);- const skillContentSha256 = await hashApprovedSkillContent(manifest, sourceDir);- const pendingPublish = this.receiptStore.readPendingMutationSync(manifest.id);+ const skillContentSha256 = await hashApprovedSkillContent(approvedManifest, sourceDir);+ const pendingPublish = this.receiptStore.readPendingMutationSync(approvedManifest.id);if (pendingPublish.state === 'invalid' || pendingPublish.state === 'unreadable') {throw new Error(`builtin seed publish journal is ${pendingPublish.state}`);}@@ -3655,11 +3288,12 @@ export class GhostManager {throw new Error('builtin seed publish journal does not match immutable source');}const trust = CINDY_OFFICIAL_GHOST_TRUST;- const current = this.readApproval(manifest.id);+ const current = this.readApproval(approvedManifest.id);// priorEnabled 直接读盘上的 receipt 而不是 readApproval 的投影:进程内隔离态的// receipt 不可作授权事实,但"曾经停用"这个位只用于往下拉,是 fail closed 方向,// 采纳它只会更保守 —— 否则"隔离 + 镜像同时丢失"的组合会让自愈把插件带回启用。- const persisted = current.state === 'approved' ? current : this.receiptStore.read(manifest.id);+ const persisted =+ current.state === 'approved' ? current : this.receiptStore.read(approvedManifest.id);const priorEnabled = persisted.state === 'approved' ? persisted.receipt.enabled : undefined;const enabled = priorEnabled === undefined ? markerEnabled : markerEnabled && priorEnabled;if (enabled !== markerEnabled) {@@ -3669,14 +3303,14 @@ export class GhostManager {this.writeDisabledMarkerSync(dir);} catch (err) {this.options.log?.warn('ghost disabled mirror rewrite failed', {- id: manifest.id,+ id: approvedManifest.id,error: err instanceof Error ? err.message : String(err),});}}if (current.state === 'approved' &&- isDeepStrictEqual(current.receipt.manifest, manifest) &&+ isDeepStrictEqual(current.receipt.manifest, approvedManifest) &&isDeepStrictEqual(current.receipt.localeResources, localeResources) &&isDeepStrictEqual(current.receipt.trust, trust) &&isDeepStrictEqual(current.receipt.skillContentSha256, skillContentSha256) &&@@ -3689,45 +3323,51 @@ export class GhostManager {// normal receipt writer when the derived snapshot is unhealthy so the// immutable bundled seed can rebuild it without user action.const snapshotHealthy =- (manifest.skill?.items.length ?? 0) === 0 ||+ (approvedManifest.skill?.items.length ?? 0) === 0 ||(await this.receiptStore.skillSnapshotMatchesReceipt(current.receipt,- this.receiptStore.skillSnapshotRoot(manifest.id, current.receipt.revision),+ this.receiptStore.skillSnapshotRoot(approvedManifest.id, current.receipt.revision),));if (!snapshotHealthy) {// Snapshot repair must persist the same one-way disabled merge as the// healthy-snapshot path. Otherwise deleting the compatibility marker// after this early return could silently re-enable the plugin.- await this.receiptStore.write({- ...current.receipt,- enabled,- }, { skillSourceDir: sourceDir });- await this.finishTrustedBundledPublish(manifest.id, pendingPublish);- this.untrustedApprovals.delete(this.isolationKey(manifest.id));+ await this.receiptStore.write(+ {+ ...current.receipt,+ enabled,+ },+ { skillSourceDir: sourceDir },+ );+ await this.finishTrustedBundledPublish(approvedManifest.id, pendingPublish);+ this.untrustedApprovals.delete(this.isolationKey(approvedManifest.id));return true;}if (current.receipt.enabled !== enabled) {- await this.receiptStore.write({- ...current.receipt,- enabled,- }, { skillSourceDir: sourceDir });- await this.finishTrustedBundledPublish(manifest.id, pendingPublish);- this.untrustedApprovals.delete(this.isolationKey(manifest.id));+ await this.receiptStore.write(+ {+ ...current.receipt,+ enabled,+ },+ { skillSourceDir: sourceDir },+ );+ await this.finishTrustedBundledPublish(approvedManifest.id, pendingPublish);+ this.untrustedApprovals.delete(this.isolationKey(approvedManifest.id));return true;}- await this.finishTrustedBundledPublish(manifest.id, pendingPublish);+ await this.finishTrustedBundledPublish(approvedManifest.id, pendingPublish);// Receipt already matches the immutable seed — no write needed,// but the process-internal untrusted approval quarantine from// publishTrustedBundledSeed must still be cleared. The other// two branches (full write and enabled toggle) both clear it;// without it here, the no-op path leaves the plugin quarantined// until the next restart (P1, PRRT_kwDOTgdRUs6YcxiH).- this.untrustedApprovals.delete(this.isolationKey(manifest.id));+ this.untrustedApprovals.delete(this.isolationKey(approvedManifest.id));return false;}await this.receiptStore.write(createGhostInstallReceipt({- manifest,+ manifest: approvedManifest,localeResources,enabled,trust,@@ -3737,8 +3377,8 @@ export class GhostManager {}),{ skillSourceDir: sourceDir },);- await this.finishTrustedBundledPublish(manifest.id, pendingPublish);- this.untrustedApprovals.delete(this.isolationKey(manifest.id));+ await this.finishTrustedBundledPublish(approvedManifest.id, pendingPublish);+ this.untrustedApprovals.delete(this.isolationKey(approvedManifest.id));return true;}diff --git a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.tsindex 840820cb57..83c1d444af 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts@@ -8,6 +8,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import {GHOST_SKILL_MD_MAX_BYTES,+ ghostManifestToAuthorFormat,ghostInstallApprovalToken,validateGhostManifest,type InstalledGhost,@@ -975,307 +976,6 @@ describe('GhostManager · 迁移崩溃安全(in-progress 状态机)与隔离命});});-describe('GhostManager · 从已装目录重新确认(本地包第三条恢复路径)', () => {- it('批准丢失后不用原始 .cindy:inspect 出全量清单,确认后开 receipt、恢复可用', async () => {- // 场景:迁移已跑过(ledger 在),之后 receipt 又被删 —— 一次性门不再迁移,- // 本地包用户没有市场路线;第三条路必须能不找文件恢复。- await writeLegacyInstall('hello', goodManifest());- await manager.migrateLegacyApprovalsOnce();- await fs.promises.rm(path.join(workDir, 'ghosts-install-state', 'hello.json'));- expect(manager.list()[0].approval.state).toBe('legacy-unapproved');-- const inspected = await manager.inspectInstalledReapproval('hello');- if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));- expect(inspected.manifest.id).toBe('hello');- expect(inspected.manifestSha256).toMatch(/^[a-f0-9]{64}$/);-- const result = await manager.reapproveInstalled('hello', {- enable: true,- expectedManifestSha256: inspected.manifestSha256,- expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,- expectedInstalledApproval: 'legacy-unapproved',- });- if ('rejection' in result) throw new Error(JSON.stringify(result.rejection));- expect(manager.list()[0]).toMatchObject({ enabled: true, approval: { state: 'approved' } });- // 启停镜像同步维护(回滚到旧客户端不错位)。- expect(fs.existsSync(path.join(rootDir, 'hello', '.disabled'))).toBe(false);- });-- it('带 setup.kv 的旧安装可从已装目录重新确认并恢复可用', async () => {- await writeLegacyInstall('hello', setupKvManifest(), {- files: { 'settings.html': '<!doctype html>' },- });- const inspected = await manager.inspectInstalledReapproval('hello');- if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));-- const result = await manager.reapproveInstalled('hello', {- enable: true,- expectedManifestSha256: inspected.manifestSha256,- expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,- expectedInstalledApproval: 'legacy-unapproved',- });-- if ('rejection' in result) throw new Error(JSON.stringify(result.rejection));- expect(manager.list()[0]).toMatchObject({- enabled: true,- approval: { state: 'approved' },- manifest: {- setup: {- requires: [- { anyOf: [{ kind: 'kv', key: 'repoDir', label: '本机 cindy 项目目录' }] },- ],- },- },- });- });-- it('重新确认要求立即启用时,删除停用镜像失败必须拒绝且不提交批准', async () => {- await writeLegacyInstall('hello', goodManifest(), { disabled: true });- const inspected = await manager.inspectInstalledReapproval('hello');- if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));- const marker = path.join(rootDir, 'hello', '.disabled');- const realRm = fs.promises.rm;- const rmSpy = vi.spyOn(fs.promises, 'rm').mockImplementation(async (target, options) => {- if (path.resolve(String(target)) === path.resolve(marker)) {- throw Object.assign(new Error('EACCES: marker locked'), { code: 'EACCES' });- }- return realRm(target, options);- });- try {- const result = await manager.reapproveInstalled('hello', {- enable: true,- expectedManifestSha256: inspected.manifestSha256,- expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,- expectedInstalledApproval: 'legacy-unapproved',- });- expect('rejection' in result && result.rejection.code).toBe('io');- expect(manager.list()[0]).toMatchObject({- enabled: false,- approval: { state: 'legacy-unapproved' },- });- expect(fs.existsSync(marker)).toBe(true);- } finally {- rmSpy.mockRestore();- }- });-- it('重新确认要求立即启用时,receipt 提交失败必须恢复原停用镜像', async () => {- await writeLegacyInstall('hello', goodManifest(), { disabled: true });- const inspected = await manager.inspectInstalledReapproval('hello');- if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));- const marker = path.join(rootDir, 'hello', '.disabled');- const realRename = fs.promises.rename;- const renameSpy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {- if (String(to).endsWith('hello.json')) throw new Error('state root unwritable');- return realRename(from, to);- });- try {- const result = await manager.reapproveInstalled('hello', {- enable: true,- expectedManifestSha256: inspected.manifestSha256,- expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,- expectedInstalledApproval: 'legacy-unapproved',- });- expect('rejection' in result && result.rejection.code).toBe('io');- expect(manager.list()[0]).toMatchObject({- enabled: false,- approval: { state: 'legacy-unapproved' },- });- expect(fs.existsSync(marker)).toBe(true);- } finally {- renameSpy.mockRestore();- }- });-- it('重新确认不跟随确认后被换成 junction 的安装目录写删停用镜像', async () => {- await writeLegacyInstall('hello', goodManifest(), { disabled: true });- const inspected = await manager.inspectInstalledReapproval('hello');- if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));- const dir = path.join(rootDir, 'hello');- const outside = fs.realpathSync.native(- await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-reapprove-outside-')),- );- const outsideMarker = path.join(outside, '.disabled');- await fs.promises.writeFile(outsideMarker, 'sentinel');- const probe = path.join(workDir, 'reapprove-junction-probe');- try {- await fs.promises.symlink(outside, probe, process.platform === 'win32' ? 'junction' : 'dir');- await fs.promises.rm(probe, { force: true });- } catch {- await fs.promises.rm(outside, { recursive: true, force: true });- return;- }- const realInspect = manager.inspectInstalledReapproval.bind(manager);- const inspectSpy = vi.spyOn(manager, 'inspectInstalledReapproval').mockImplementation(async (ghostId) => {- const result = await realInspect(ghostId);- await fs.promises.rm(dir, { recursive: true, force: true });- await fs.promises.symlink(outside, dir, process.platform === 'win32' ? 'junction' : 'dir');- return result;- });- try {- const result = await manager.reapproveInstalled('hello', {- enable: true,- expectedManifestSha256: inspected.manifestSha256,- expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,- expectedInstalledApproval: 'legacy-unapproved',- });- expect('rejection' in result && result.rejection.code).toBe('state-changed');- expect(await fs.promises.readFile(outsideMarker, 'utf8')).toBe('sentinel');- expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(false);- } finally {- inspectSpy.mockRestore();- await fs.promises.rm(outside, { recursive: true, force: true });- }- });-- it('重新确认 receipt 失败回滚前目录被换成 junction 时不得写入外部目标', async () => {- await writeLegacyInstall('hello', goodManifest(), { disabled: true });- const inspected = await manager.inspectInstalledReapproval('hello');- if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));- const dir = path.join(rootDir, 'hello');- const displaced = path.join(rootDir, 'hello-displaced');- const outside = fs.realpathSync.native(- await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-reapprove-rollback-')),- );- let linkCreated = false;- const realRename = fs.promises.rename;- const renameSpy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {- if (String(to).endsWith('hello.json')) {- await realRename(dir, displaced);- try {- await fs.promises.symlink(outside, dir, process.platform === 'win32' ? 'junction' : 'dir');- linkCreated = true;- } catch {- await realRename(displaced, dir);- }- throw new Error('state root unwritable');- }- return realRename(from, to);- });- try {- const result = await manager.reapproveInstalled('hello', {- enable: true,- expectedManifestSha256: inspected.manifestSha256,- expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,- expectedInstalledApproval: 'legacy-unapproved',- });- expect('rejection' in result && result.rejection.code).toBe('io');- if (linkCreated) expect(fs.existsSync(path.join(outside, '.disabled'))).toBe(false);- } finally {- renameSpy.mockRestore();- await fs.promises.rm(outside, { recursive: true, force: true });- }- });-- it('确认间隙 ghost.json 被换 → 拒(确认卡展示的与批准的必须是同一份字节)', async () => {- await writeLegacyInstall('hello', goodManifest());- const inspected = await manager.inspectInstalledReapproval('hello');- if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));-- // 攻击窗口:用户看的是权限集 A,confirm 落地前清单被换成声明更多权限的 B。- await fs.promises.writeFile(- path.join(rootDir, 'hello', 'ghost.json'),- JSON.stringify({ ...goodManifest(), name: 'Changed after review' }),- );- const result = await manager.reapproveInstalled('hello', {- enable: true,- expectedManifestSha256: inspected.manifestSha256,- expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,- expectedInstalledApproval: 'legacy-unapproved',- });- expect('rejection' in result && result.rejection.code).toBe('state-changed');- expect(manager.list()[0].approval.state).toBe('legacy-unapproved');- });-- it.each(['skill', 'locale', 'icon', 'trust'] as const)(- '确认间隙 %s 批准投影被换 → 拒绝重新确认',- async (kind) => {- const manifest = {- ...goodManifest(),- author: 'Original author',- icon: 'assets/icon.png',- locales: { en: 'locales/en.json' },- slots: ['tool', 'skill'],- skill: { items: [{ dir: 'skills/demo', name: 'demo', description: 'Demo skill' }] },- };- await writeLegacyInstall('hello', manifest, {- files: {- 'assets/icon.png': 'ORIGINAL ICON',- 'locales/en.json': JSON.stringify({ name: 'Original name' }),- 'skills/demo/SKILL.md':- '---\nname: demo\ndescription: Demo skill\n---\n\nOriginal instructions\n',- },- });- const inspected = await manager.inspectInstalledReapproval('hello');- if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));-- if (kind === 'skill') {- await fs.promises.writeFile(- path.join(rootDir, 'hello', 'skills', 'demo', 'SKILL.md'),- '---\nname: demo\ndescription: Demo skill\n---\n\nReplaced instructions\n',- );- } else if (kind === 'locale') {- await fs.promises.writeFile(- path.join(rootDir, 'hello', 'locales', 'en.json'),- JSON.stringify({ name: 'Replaced name' }),- );- } else if (kind === 'icon') {- await fs.promises.writeFile(path.join(rootDir, 'hello', 'assets', 'icon.png'), 'REPLACED ICON');- } else {- await fs.promises.writeFile(- path.join(rootDir, 'hello', '.cindy-trust.json'),- JSON.stringify({- level: 'verified-publisher',- publisherSigned: true,- publisherVerified: true,- reviewed: true,- publisherName: 'Different publisher',- }),- );- }-- const result = await manager.reapproveInstalled('hello', {- enable: true,- expectedManifestSha256: inspected.manifestSha256,- expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,- expectedInstalledApproval: 'legacy-unapproved',- });- expect('rejection' in result && result.rejection.code).toBe('state-changed');- expect(manager.list()[0].approval.state).toBe('legacy-unapproved');- },- );-- it('随包插件拒走人工重新确认(由启动对账自动补批准)', async () => {- const guarded = new GhostManager({- getRootDir: () => rootDir,- getLocale: () => hostLocale,- isTrustedBundledId: (id) => id === 'hello',- });- await writeLegacyInstall('hello', goodManifest());- const inspected = await guarded.inspectInstalledReapproval('hello');- expect('rejection' in inspected && inspected.rejection.code).toBe('file-invalid');- });-- it('已是 approved 的插件拒重复确认(不给覆盖既有批准开口子)', async () => {- await manager.install(await makeCindy('a.cindy', goodManifest()));- const inspected = await manager.inspectInstalledReapproval('hello');- expect('rejection' in inspected && inspected.rejection.code).toBe('state-changed');- });-- it('信任镜像自称 cindy-official 一律封顶拒收(非随包目录不可能合法持有官方档)', async () => {- await writeLegacyInstall('hello', goodManifest(), {- trust: {- level: 'cindy-official',- publisherSigned: true,- publisherVerified: true,- reviewed: true,- },- });- const inspected = await manager.inspectInstalledReapproval('hello');- if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));- expect(inspected.trust.level).toBe('unverified');- });-});describe('GhostManager · review 第 6 轮回归(P0/P1 修复钉住)', () => {it('P0-3:停用在 receipt 写失败时仍然生效,且跨实例(重启)持久', async () => {@@ -1790,59 +1490,6 @@ describe('GhostManager · review 第 6 轮回归(P0/P1 修复钉住)', () => {);});- it('P1-6:重新确认拒绝与已装插件撞名的指令', async () => {- await manager.install(- await makeCindy('holder.cindy', chipManifestWithCommand('holder', 'draw')),- );- await writeLegacyInstall('clasher', chipManifestWithCommand('clasher', 'Draw'));- const inspected = await manager.inspectInstalledReapproval('clasher');- if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));- const result = await manager.reapproveInstalled('clasher', {- enable: true,- expectedManifestSha256: inspected.manifestSha256,- expectedApprovalProjectionSha256: inspected.approvalProjectionSha256,- expectedInstalledApproval: 'legacy-unapproved',- });- expect('rejection' in result && result.rejection.code).toBe('command-conflict');- });-- it('P1-6:声明 tokenBroker 的目录拒走已装目录重新确认', async () => {- const brokerNetwork = {- hosts: ['api.example.com', 'accounts.example.com'],- secrets: [- {- key: 'token',- label: 'Account',- source: 'oauth' as const,- inject: { header: 'Authorization', format: 'Bearer {value}' },- oauth: {- authorizeUrl: 'https://accounts.example.com/authorize',- tokenUrl: 'https://accounts.example.com/token',- clientId: 'broker-client',- tokenBroker: 'github',- },- },- ],- };- await writeLegacyInstall('brokered', {- ...goodManifest('brokered'),- slots: ['tool', 'network'],- settingsHtml: 'settings.html',- network: brokerNetwork,- });- const inspected = await manager.inspectInstalledReapproval('brokered');- expect('rejection' in inspected && inspected.rejection.code).toBe('file-invalid');- if ('rejection' in inspected) {- expect(inspected.rejection.reason).toMatch(/tokenBroker/);- }- });-- it('P1-7:重新确认的启停默认值取镜像读数,不重置用户停用偏好', async () => {- await writeLegacyInstall('hello', goodManifest(), { disabled: true });- const inspected = await manager.inspectInstalledReapproval('hello');- if ('rejection' in inspected) throw new Error(JSON.stringify(inspected.rejection));- expect(inspected.previouslyEnabled).toBe(false);- });it('P1-9:更新失败且旧目录滚不回时如实报 rollbackFailed,不假装旧版本还在', async () => {await manager.install(await makeCindy('a.cindy', goodManifest()));@@ -3302,7 +2949,7 @@ describe('GhostManager · Host approval receipt', () => {const writeBundledSource = async (manifest: InstalledGhost['manifest'],files: Record<string, string> = { 'main.js': '// bundled seed' },- sourceManifest: unknown = manifest,+ sourceManifest: unknown = ghostManifestToAuthorFormat(manifest),): Promise<{ sourceDir: string }> => {const sourceDir = path.join(workDir, 'bundled-seeds', manifest.id);await fs.promises.rm(sourceDir, { recursive: true, force: true });@@ -4105,7 +3752,10 @@ describe('GhostManager · Host approval receipt', () => {const sourceDir = path.join(workDir, 'bundled-seeds', approvedManifest.id);trustedBundledIds.add(approvedManifest.id);await fs.promises.mkdir(sourceDir, { recursive: true });- await fs.promises.writeFile(path.join(sourceDir, 'ghost.json'), JSON.stringify(approvedManifest));+ await fs.promises.writeFile(+ path.join(sourceDir, 'ghost.json'),+ JSON.stringify(ghostManifestToAuthorFormat(approvedManifest)),+ );await fs.promises.writeFile(path.join(sourceDir, 'main.js'), 'immutable bundled bytes');await fs.promises.writeFile(path.join(rootDir, approvedManifest.id, 'main.js'), 'mutable bytes');@@ -4654,10 +4304,10 @@ describe('GhostManager · inspect(只验不装)', () => {expect((result as { rejection: { code: string } }).rejection.code).toBe('file-invalid');});- it('未来 schema 或未知字符串 capability → 插件合法但当前 Host 不支持', async () => {+ it('未来 schema 拒绝;未知 v2 slot 仅单独报告,不进入运行时模型', async () => {const futureSchema = await makeCindy('future-schema.cindy', {...goodManifest(),- schemaVersion: 3,+ schemaVersion: 4,});await expectRejection(await manager.inspect(futureSchema), 'host-unsupported');@@ -4665,7 +4315,11 @@ describe('GhostManager · inspect(只验不装)', () => {...goodManifest(),slots: ['tool', 'future-host-capability'],});- await expectRejection(await manager.inspect(futureCapability), 'host-unsupported');+ const inspected = await manager.inspect(futureCapability);+ expect('rejection' in inspected).toBe(false);+ if ('rejection' in inspected) return;+ expect(inspected.manifest).not.toHaveProperty('slots');+ expect(inspected.unsupportedLegacySlots).toEqual(['future-host-capability']);});it('slot 形状畸形仍按非法文件拒绝,友好提示不放松安全校验', async () => {diff --git a/apps/desktop/src/main/cindy-brain/__tests__/agentSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/agentSlot.test.tsindex 04ac88af3a..fe5fc929ef 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/agentSlot.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/agentSlot.test.ts@@ -27,8 +27,9 @@ function fakeGhost(version: '1.2.3',kind: 'chip',entry: 'main.js',- slots: agentSlot ? ['agent'] : ['card'],- ...(options.background ? { agent: { background: true } } : {}),+ ...(agentSlot+ ? { agent: options.background ? { background: true } : {} }+ : { card: {} }),},dir: `/fake/${id}`,enabled: options.enabled ?? true,@@ -74,7 +75,7 @@ function makeSlot(options: {}describe('agentSlot · 清单与模板守门', () => {- it('未申请 agent 槽或插件停用时拒绝', async () => {+ it('未申请 agent 能力或插件停用时拒绝', async () => {const runner = acceptedRunner();const noSlot = makeSlot({ ghosts: [fakeGhost('alpha', { agentSlot: false })], runner });const disabled = makeSlot({ ghosts: [fakeGhost('alpha', { enabled: false })], runner });diff --git a/apps/desktop/src/main/cindy-brain/__tests__/badgeSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/badgeSlot.test.tsindex f11ecaec60..efb3060054 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/badgeSlot.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/badgeSlot.test.ts@@ -15,10 +15,9 @@ import {} from '../../../shared/ghost';function fakeGhost(- overrides: { enabled?: boolean; slots?: string[]; badge?: boolean } = {},+ overrides: { enabled?: boolean; notify?: boolean; badge?: boolean } = {},): InstalledGhost {const badge = overrides.badge ?? true;- const slots = overrides.slots ?? ['panel', 'notify'];return {manifest: {schemaVersion: 2,@@ -27,7 +26,9 @@ function fakeGhost(version: '1.0.0',kind: 'chip',entry: 'main.js',- slots: badge ? [...slots, 'badge'] : slots,+ panel: { html: 'panel.html' },+ ...(overrides.notify === false ? {} : { notify: true }),+ ...(badge ? { badge: true } : {}),},dir: '/fake/brain/inbox',enabled: overrides.enabled ?? true,@@ -62,7 +63,7 @@ describe('GhostBadgeSlot', () => {});});- it('资格只看 badge 卡槽:没声明就拒(存量只有 notify 槽的老包不白捡这档能力)', () => {+ it('资格只看 badge 声明:没声明就拒(存量只有 notify 的老包不白捡这档能力)', () => {const noDecl = makeSlot(fakeGhost({ badge: false }));const r = noDecl.slot.handleBadge('inbox', { unread: true });expect(r).toMatchObject({ ok: false });@@ -70,8 +71,8 @@ describe('GhostBadgeSlot', () => {expect(noDecl.mark).not.toHaveBeenCalled();});- it('不要求 notify 槽:只声明 panel + badge 的意识照样能点亮(两档权限并列)', () => {- const { slot, mark } = makeSlot(fakeGhost({ slots: ['panel'] }), { now: () => 1 });+ it('不要求 notify:只声明 panel + badge 的意识照样能点亮(两档权限并列)', () => {+ const { slot, mark } = makeSlot(fakeGhost({ notify: false }), { now: () => 1 });expect(slot.handleBadge('inbox', { unread: true, summary: '新内容' })).toEqual({ ok: true });expect(mark).toHaveBeenCalledWith('inbox', '新内容', 1);});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/cardActionDispatch.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/cardActionDispatch.test.tsindex a9c1d5d01d..18bc8c7542 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/cardActionDispatch.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/cardActionDispatch.test.ts@@ -9,7 +9,7 @@ import { describe, it, expect, vi } from 'vitest';import { GhostCardActionDispatcher, type CardActionDispatchDeps } from '../cardActionDispatch';import type { InstalledGhost } from '../../../shared/ghost';-function fakeGhost(overrides: { enabled?: boolean; slots?: string[] } = {}): InstalledGhost {+function fakeGhost(overrides: { enabled?: boolean; card?: boolean } = {}): InstalledGhost {return {manifest: {schemaVersion: 2,@@ -18,7 +18,7 @@ function fakeGhost(overrides: { enabled?: boolean; slots?: string[] } = {}): Insversion: '1.0.0',kind: 'chip',entry: 'main.js',- slots: overrides.slots ?? ['tool', 'card', 'network'],+ ...(overrides.card === false ? {} : { card: {} }),},dir: '/fake/cindy-mivo',enabled: overrides.enabled ?? true,@@ -204,7 +204,7 @@ describe('cardActionDispatch · 资格审 + 投递', () => {const gone = makeDispatcher({ getGhost: () => null });expect((await gone.dispatcher.dispatch(CALL_ID, CUSTOM_ID)).ok).toBe(false);- const noSlot = makeDispatcher({ getGhost: () => fakeGhost({ slots: ['tool'] }) });+ const noSlot = makeDispatcher({ getGhost: () => fakeGhost({ card: false }) });const r = await noSlot.dispatcher.dispatch(CALL_ID, CUSTOM_ID);expect(r.ok).toBe(false);if (!r.ok) expect(r.reason).toBe('no-card-slot');diff --git a/apps/desktop/src/main/cindy-brain/__tests__/cindySlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/cindySlot.test.tsindex 3959aa4bc5..c7e1e34e2c 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/cindySlot.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/cindySlot.test.ts@@ -21,7 +21,7 @@ import type { InstalledGhost } from '../../../shared/ghost';function fakeGhost(overrides: {enabled?: boolean;- slots?: string[];+ cindy?: boolean;model?: {image?: string[];video?: string[];@@ -41,10 +41,9 @@ function fakeGhost(version: '1.0.0',kind: 'chip',entry: 'main.js',- slots: overrides.slots ?? ['tool', 'cindy', 'panel'],tools: [{ name: 'gen_image', description: '生成图片' }],// null = 模拟老包缺详单;undefined = 默认全能力(image + video + media)。- ...(overrides.model === null+ ...(overrides.cindy === false || overrides.model === null? {}: {cindy:@@ -403,7 +402,7 @@ describe('Cindy Web Search', () => {const searchWeb = vi.fn();for (const getGhost of [() => fakeGhost({ enabled: false, model: { search: ['web'] } }),- () => fakeGhost({ slots: ['tool'], model: { search: ['web'] } }),+ () => fakeGhost({ cindy: false, model: { search: ['web'] } }),() => fakeGhost(),]) {const denied = makeSlot({ getGhost, searchWeb });@@ -998,11 +997,11 @@ describe('能力粒度资格审(model 详单)', () => {expect(editImage).not.toHaveBeenCalled();});- it('老包缺详单 = 零能力,一切代办拒且提示更新声明', async () => {+ it('老包缺详单 = 零能力,一切代办拒且明确未声明 cindy 能力', async () => {const { slot, generateImage } = makeSlot({ getGhost: () => fakeGhost({ model: null }) });const r = await slot.handleModelRequest('art', REQ);expect(r).toMatchObject({ ok: false });- expect((r as { message: string }).message).toContain('更新');+ expect((r as { message: string }).message).toContain('未声明 cindy 能力');expect(generateImage).not.toHaveBeenCalled();});});@@ -1015,8 +1014,8 @@ describe('资格审', () => {expect(await asleep.slot.handleModelRequest('art', REQ)).toMatchObject({ ok: false });});- it('身份卡未声明 cindy 卡槽 → 结构上无此器官,拒', async () => {- const { slot, generateImage } = makeSlot({ getGhost: () => fakeGhost({ slots: ['tool', 'panel'] }) });+ it('身份卡未声明 cindy 能力 → 结构上无此器官,拒', async () => {+ const { slot, generateImage } = makeSlot({ getGhost: () => fakeGhost({ cindy: false }) });const r = await slot.handleModelRequest('art', REQ);expect(r).toMatchObject({ ok: false });expect((r as { message: string }).message).toContain('cindy');@@ -1619,7 +1618,7 @@ describe('寄存(deposit_media / release_media)', () => {expect(noMedia.depositMedia).not.toHaveBeenCalled();const noSlot = makeSlot({- getGhost: () => fakeGhost({ slots: ['tool'], model: null }),+ getGhost: () => fakeGhost({ model: null }),} as Partial<CindySlotDeps>);expect(await noSlot.slot.handleModelRequest('art', depositReq(b64(PNG)))).toMatchObject({ok: false,diff --git a/apps/desktop/src/main/cindy-brain/__tests__/confirmSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/confirmSlot.test.tsindex fd6bb551c4..650ea30b86 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/confirmSlot.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/confirmSlot.test.ts@@ -13,7 +13,7 @@ import {type GhostConfirmShowParams,} from '../confirmSlot';-function confirmGhost(options: { slots?: string[]; enabled?: boolean; icon?: string } = {}): InstalledGhost {+function confirmGhost(options: { confirm?: boolean; enabled?: boolean; icon?: string } = {}): InstalledGhost {return {manifest: {schemaVersion: 2,@@ -22,7 +22,7 @@ function confirmGhost(options: { slots?: string[]; enabled?: boolean; icon?: strversion: '1.0.0',kind: 'chip',entry: 'main.js',- slots: options.slots ?? ['confirm'],+ ...(options.confirm === false ? {} : { confirm: true }),},dir: '/fake/confirm-ghost',enabled: options.enabled ?? true,@@ -58,8 +58,8 @@ function firstShown(mock: ReturnType<typeof showConfirmMock>): GhostConfirmShowPconst OK_BODY = { body: '把项目目录切到 fix/xxx 分支?' };describe('confirmSlot · 资格审与载荷校验', () => {- it('未声明 confirm 槽 / 未启用 一律 PERMISSION_DENIED', async () => {- const noSlot = makeSlot({ getGhost: () => confirmGhost({ slots: ['tool'] }) });+ it('未声明 confirm 能力 / 未启用 一律 PERMISSION_DENIED', async () => {+ const noSlot = makeSlot({ getGhost: () => confirmGhost({ confirm: false }) });expect(await noSlot.slot.handleRequest('confirm-ghost', OK_BODY)).toMatchObject({ok: false,errorCode: 'PERMISSION_DENIED',diff --git a/apps/desktop/src/main/cindy-brain/__tests__/connectionAudienceResolver.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/connectionAudienceResolver.test.tsindex 753a6bc864..ac5741103d 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/connectionAudienceResolver.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/connectionAudienceResolver.test.ts@@ -17,7 +17,6 @@ const manifest: GhostManifest = {version: '1.0.0',kind: 'chip' as const,entry: 'index.js',- slots: ['network'],network: {hosts: ['service-a.x.test'],secrets: [@@ -87,22 +86,6 @@ describe('installed Plugin Connection audience resolver', () => {});});- it('keeps legacy organization-market OIDC independent from receipt package SHA', () => {- const resolver = loadConnectionAudienceResolver({- ...resolverOptions(),- readApprovedPackageSha256: () => null,- });-- // This is the intentional compatibility boundary: Broker now requires the- // package hash, but the existing market OIDC path remains manifest-bound.- expect(resolver.resolve('plugin-a', identity)).toEqual({- membershipId: 'membership-1',- audience: 'org-example:plugin-a',- pluginSlug: 'plugin-a',- allowedHosts: ['service-a.x.test'],- });- });-it('requires a current organization market installation record', () => {const resolver = loadConnectionAudienceResolver(resolverOptions(manifest, { ...marketInstallation, source: 'local-market' }),@@ -172,59 +155,6 @@ describe('installed Plugin Connection audience resolver', () => {).toBeNull();});- it('resolves a forge-installed org-prefix plugin before consulting the market ledger', () => {- const forgeManifest: GhostManifest = { ...manifest, id: 'acme-tool' };- const resolver = loadConnectionAudienceResolver({- ...resolverOptions(forgeManifest, null),- readInstallOrigin: () => 'agent-forge',- readApprovedPackageSha256: () => 'a'.repeat(64),- lookupOrganizationPrefix: () => ({ kind: 'known', pluginPrefix: 'acme' }),- });- expect(resolver.resolve('acme-tool', identity)).toEqual({- membershipId: 'membership-1',- audience: 'org-example:acme-tool',- pluginSlug: 'acme-tool',- allowedHosts: ['service-a.x.test'],- });- });-- it('does not give forge OIDC to a personal identity or a missing orgSlug', () => {- const forgeManifest: GhostManifest = { ...manifest, id: 'acme-tool' };- const resolver = loadConnectionAudienceResolver({- ...resolverOptions(forgeManifest, null),- readInstallOrigin: () => 'agent-forge',- readApprovedPackageSha256: () => 'a'.repeat(64),- lookupOrganizationPrefix: () => ({ kind: 'known', pluginPrefix: 'acme' }),- });- expect(- resolver.resolve('acme-tool', {- membershipId: 'membership-1',- membershipKind: 'personal',- orgId: null,- orgSlug: null,- }),- ).toBeNull();- expect(- resolver.resolve('acme-tool', {- membershipId: 'membership-1',- membershipKind: 'org',- orgId: 'org-id-1',- orgSlug: null,- }),- ).toBeNull();- });-- it('does not give forge OIDC to a manual install of the same org-prefix id', () => {- const forgeManifest: GhostManifest = { ...manifest, id: 'acme-tool' };- const resolver = loadConnectionAudienceResolver({- ...resolverOptions(forgeManifest, null),- readInstallOrigin: () => 'manual',- readApprovedPackageSha256: () => 'a'.repeat(64),- lookupOrganizationPrefix: () => ({ kind: 'known', pluginPrefix: 'acme' }),- });- expect(resolver.resolve('acme-tool', identity)).toBeNull();- });-it('requires the managed secret target to match a declared exact host', () => {const resolver = loadConnectionAudienceResolver({...resolverOptions(),diff --git a/apps/desktop/src/main/cindy-brain/__tests__/errandSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/errandSlot.test.tsindex 00fb4e9e2f..ea4b2e8c38 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/errandSlot.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/errandSlot.test.ts@@ -21,7 +21,11 @@ import {} from '../../../shared/ghost';function fakeGhost(- overrides: { enabled?: boolean; slots?: string[]; agent?: Record<string, unknown> | null } = {},+ overrides: {+ enabled?: boolean;+ agentCapability?: boolean;+ agent?: Record<string, unknown> | null;+ } = {},): InstalledGhost {return {manifest: {@@ -31,8 +35,9 @@ function fakeGhost(version: '1.0.0',kind: 'chip',entry: 'main.js',- slots: overrides.slots ?? ['tool', 'agent'],- ...(overrides.agent === null ? {} : { agent: overrides.agent ?? { errand: true } }),+ ...(overrides.agentCapability === false || overrides.agent === null+ ? {}+ : { agent: overrides.agent ?? { errand: true } }),},dir: '/fake/brain/helper',enabled: overrides.enabled ?? true,@@ -68,9 +73,9 @@ function makeSlot(overrides: Partial<GhostErrandSlotDeps> = {}): {const RUN = { type: 'agent-errand-request', kind: 'run', task: '总结 README' };describe('资格审', () => {- it('未声明 agent 槽 / 未声明 errand / 未启用 → PERMISSION_DENIED', async () => {+ it('未声明 agent 能力 / 未声明 errand / 未启用 → PERMISSION_DENIED', async () => {for (const ghost of [- fakeGhost({ slots: ['tool'] }),+ fakeGhost({ agentCapability: false }),fakeGhost({ agent: null }),fakeGhost({ agent: { background: true } }),fakeGhost({ enabled: false }),diff --git a/apps/desktop/src/main/cindy-brain/__tests__/filoGoogleClientConfig.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/filoGoogleClientConfig.test.tsindex 4d6b2ceaf7..87648fa8d7 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/filoGoogleClientConfig.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/filoGoogleClientConfig.test.ts@@ -11,7 +11,6 @@ function manifest(oauth: Record<string, unknown> = {}): GhostManifest {version: '1.0.0',kind: 'chip',entry: 'main.js',- slots: ['network'],network: {hosts: ['accounts.google.com'],secrets: [{diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forge.oauth.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forge.oauth.test.tsindex 15925ef35b..54b7b3ab80 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.oauth.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.oauth.test.ts@@ -32,22 +32,20 @@ describe('FORGE_GUIDE · oauth 凭证章节', () => {expect(FORGE_GUIDE).toContain('`/secrets`、`/oauth`、`/wake`');});- it('redirectPort 与 tokenBroker 三路资格在场(§2 样例 + §4.7 说明 + 拒装原因)', () => {+ it('redirectPort 与 tokenBroker 两路资格在场(§2 样例 + §4.7 说明 + 拒装原因)', () => {for (const marker of ['"redirectPort"','"tokenBroker"','redirectPort 不是 1024–65535 整数','tokenBroker 没同时声明 redirectPort','或与 clientSecret 同时声明',- '三路资格',+ '两路资格','静态官方前缀照旧放行','服务端 organization market 包已安装','organizationId 与当前组织一致','release sha256 与批准 receipt 的 packageSha256 相等',- 'installOrigin 为 `agent-forge`',- '不接受手动装入、个人身份或别的组织前缀',+ '不接受本地装入、个人身份或别的组织前缀','只给 Broker 与 oidc-token,不给宿主原语',- 'packageSha256 来源指纹','总长不得超过 64 字符',]) {expect(FORGE_GUIDE).toContain(marker);diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.tsindex 5087888e62..02a17c7b98 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts@@ -659,8 +659,17 @@ describe('packGhostDir', () => {});try {const packed = await packGhostDir(dir);- expect(packed).toMatchObject({ ok: true, manifest: GOOD_MANIFEST });+ expect(packed).toMatchObject({+ ok: true,+ manifest: {+ schemaVersion: 2,+ id: GOOD_MANIFEST.id,+ version: GOOD_MANIFEST.version,+ tools: GOOD_MANIFEST.tools,+ },+ });if (!packed.ok) return;+ expect('slots' in packed.manifest).toBe(false);const zip = await JSZip.loadAsync(await fs.promises.readFile(packed.cindyPath));const manifest = await zip.file('ghost.json')?.async('string');expect(manifest).toContain('"id":"demo"');@@ -1302,8 +1311,11 @@ describe('scaffoldGhostDir', () => {// 骨架默认带占位图标(#809):清单声明 + 文件真实存在且是 PNG。const manifestJson = JSON.parse(await fs.promises.readFile(path.join(dir, 'ghost.json'), 'utf8'),- ) as { icon?: string };+ ) as Record<string, unknown>;expect(manifestJson.icon).toBe('assets/icon.png');+ expect(manifestJson.schemaVersion).toBe(3);+ expect(manifestJson.minCindyVersion).toBe('0.1.61');+ expect(manifestJson).not.toHaveProperty('slots');const iconBytes = await fs.promises.readFile(path.join(dir, 'assets/icon.png'));expect(iconBytes.subarray(0, 8)).toEqual(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),@@ -1485,13 +1497,18 @@ describe('FORGE_GUIDE', () => {expect(FORGE_GUIDE).toContain('仅企业组织成员可用,个人账号不可用');});- it('开场白必读口径与 createPrompt 一致:三章且卡槽总览带真实章号', () => {+ 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 成功就自动调用本工具');+ expect(FORGE_GUIDE).toContain('同版本也可覆盖');+ expect(FORGE_GUIDE).toContain('两种入口走同一安装/更新事务');+ });++ it('开场白要求读完沙箱红线与打包测试两章', () => {// 聊天里直接说"帮我做个插件"的路径只看到手册,看不到 createPrompt;// 两处必读口径分叉会让不同入口的 agent 走出不同的阅读深度。- // "卡槽总览"必须带章号(§2):章节匹配只认章号或标题子串,agent 照抄- // 文案字样调 section 会取章失败(PR #3023 review)。- expect(FORGE_GUIDE).toContain('至少读完 §2 卡槽总览、"沙箱红线"与"打包与测试"三章');- expect(FORGE_GUIDE).not.toContain('至少读完"沙箱红线"与"打包与测试"两章');+ expect(FORGE_GUIDE).toContain('至少读完"沙箱红线"与"打包与测试"两章');+ expect(FORGE_GUIDE).not.toContain('卡槽总览');});it('documents installed-directory isolation and the structured refusal', () => {@@ -1534,7 +1551,7 @@ describe('FORGE_GUIDE', () => {it('skill 迁移精确映射召回元数据、正文与容器目录', () => {const skillSection = FORGE_GUIDE.slice(- FORGE_GUIDE.indexOf('## 4.16 捆绑 Agent Skills(skill 槽)'),+ FORGE_GUIDE.indexOf('## 4.16 捆绑 Agent Skills(skill 能力)'),FORGE_GUIDE.indexOf('## 4.17'),);for (const marker of [@@ -1552,9 +1569,8 @@ describe('FORGE_GUIDE', () => {it('manual 发布契约按顺序锁定 Cindy 版本门槛与旧客户端回退', () => {expect(FORGE_GUIDE).toContain(- '虽能安装但缺少新版宿主能力、导致插件无法按\n设计正常工作时,必须填写最早可正常工作的正式版本',+ 'Desktop 信任来源已经完成的版本选择,不再按 `minCindyVersion` 追加筛选或确认弹窗',);- expect(FORGE_GUIDE).toContain('`manual` / `ghost_manual` 属于后者');const manualSection = FORGE_GUIDE.slice(FORGE_GUIDE.indexOf('## 3.6 manual:按需披露复杂工作流与分层资料'),@@ -1680,7 +1696,7 @@ describe('FORGE_GUIDE', () => {'cindy-request','card-update',"type: 'notify'",- 'notify 槽',+ 'notify 能力','will-user-message','will-assistant-message','同轮插话(steer)时是当前运行中 turn 的模型 id',@@ -1688,7 +1704,7 @@ describe('FORGE_GUIDE', () => {'data-ghost-action','data-ghost-prompt','card-action',- 'agent 槽',+ 'agent 能力','cindy.agent.run','{{user_message}}','userActionToken',@@ -1715,8 +1731,8 @@ describe('FORGE_GUIDE', () => {'cindy.agent.errand','queryErrand','"errand": true',+ 'node 能力','userActionToken',- 'node 槽','cindy.node.request','json-rpc-stdio','mcp-stdio',@@ -1743,7 +1759,7 @@ describe('FORGE_GUIDE', () => {'翻译错位仍是硬错误','clientIdAlternatives','cindy.fetch',- 'network 槽',+ 'network 能力','媒体上传','凭证明文永不进沙箱','/secrets',@@ -1776,6 +1792,7 @@ describe('FORGE_GUIDE', () => {'沙箱红线','ghost_forge_scaffold','ghost_forge_pack',+ 'ghost_forge_install','cindy-signatures.json','发布者签名','Cindy 审核签名',@@ -1793,15 +1810,15 @@ describe('FORGE_GUIDE', () => {'secret:brave_api_key','Node 凭证同样可参与 setup.requires',// 2026-07-23 通用能力四件套:会话上下文 / node 多入口 / 目录选择 / 面板预览。- '会话上下文(session-context 槽)',+ '会话上下文(sessionContext 能力)','workdir_is_local','workdir_is_read_only','node.entries','node.secretBindings','request.cindy.secrets',- '目录选择(pick 槽)',+ '目录选择(pick 能力)','cindy.pick',- '面板预览(preview 槽)',+ '面板预览(preview 能力)','cindy.preview','preview.hosts',// 2026-07-23 长任务续命:maxTotalMs 沉默窗口语义。@@ -1824,30 +1841,29 @@ describe('FORGE_GUIDE', () => {'在独立窗口中打开','minimize','最小化面板',- // 2026-07-25 skill 槽:随包捆绑 Agent Skills,声明一致性 + 全局作用域披露。- // 卡槽总数标记随 main-view 槽合入更新为二十个。- '二十个卡槽',- '捆绑 Agent Skills(skill 槽)',+ // Manifest v3:直接字段声明能力;未知字段保留但不授权。+ 'v3 直接用顶层字段声明插件贡献项与自主 Host 能力',+ 'v2 的 `slots` 只用于存量包兼容',+ 'v3 未识别的顶层字段会原样保留',+ '捆绑 Agent Skills(skill 能力)','skill.items','SKILL.md','~/.agents/skills','逐字一致','不受插件沙箱约束',- // 2026-07-25 工作区会话(workspace 槽):目录亲选/确认卡授权,判重复用,- // 空会话入口落侧边栏;§2 卡槽清单与 §4.17 章节同步。- '创建工作区会话(workspace 槽)',+ // 工作区会话(workspace):目录亲选/确认卡授权,判重复用。+ '创建工作区会话(workspace 能力)','cindy.workspace',"kind: 'ensure-session'",// 2026-08-06 iOS Simulator 插件能力:只读脱敏状态与 Host 面板入口。- '内置 iOS 模拟器(ios-simulator 槽)',+ '内置 iOS 模拟器(iosSimulator 能力)','cindy.iosSimulator.request','caps.capabilities.pluginVideo === false','caps.capabilities.pluginInput === false',- '声明 `ios-simulator` 时必须同时声明 `minCindyVersion`',- // 2026-08-21 一级插件主视图:独立 slot、最低版本、locale 与沙箱边界。- '一级主视图(main-view 槽)',+ '如果插件整体离开 `iosSimulator` 就无法完成任何工作',+ // 一级插件主视图:v3 直接字段、locale 与沙箱边界。+ '一级主视图(mainView 能力)','"mainView": { "title": "工作台", "icon": "puzzle", "html": "main-view.html" }',- '声明 main-view 时 minCindyVersion 必填','`mainView.title`','`mainView.icon`','`puzzle`、`globe`、`code`、`folder`、`database`、`chart-column`',@@ -1893,9 +1909,9 @@ describe('FORGE_GUIDE', () => {'设计小结','源码会放在工作目录的哪个文件夹','让用户知情即可',- // 2026-07-31 确认弹窗(confirm 槽):主机同款确认框 + 真实点击回执;- // §2 卡槽清单、§4.9 的"不是确认框"指向、§4.18 章节三处同步。- '确认弹窗(confirm 槽)',+ // 2026-07-31 确认弹窗(confirm 能力):主机同款确认框 + 真实点击回执;+ // §2 能力清单、§4.9 的"不是确认框"指向、§4.18 章节三处同步。+ '确认弹窗(confirm 能力)','cindy.confirm','只代表问到了,答案看','全局同时只有一个确认框',@@ -1934,7 +1950,7 @@ describe('FORGE_GUIDE', () => {'xdt_image_urls','selectedImageUrl','icon_source: selectedImageUrl',- 'pack 也会自动回退默认图标',+ '两种工具都会回退默认图标','pack 会保留原图标和原签名','跳过与使用默认是同一个选择','不要用 AI 仿制商标',@@ -1945,7 +1961,7 @@ describe('FORGE_GUIDE', () => {});});-describe('packGhostDir · skill 槽', () => {+describe('packGhostDir · skill 能力', () => {const SKILL_MANIFEST = {...GOOD_MANIFEST,id: 'skilled',diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forgePackConsume.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forgePackConsume.test.tsdeleted file mode 100644index 3398f5fef3..0000000000--- a/apps/desktop/src/main/cindy-brain/__tests__/forgePackConsume.test.ts+++ /dev/null@@ -1,356 +0,0 @@-import fs from 'node:fs';-import os from 'node:os';-import path from 'node:path';-import { afterEach, describe, expect, it } from 'vitest';--import type { ActiveAppSession } from '../../appSessionState.js';-import {- abandonForgePackInstall,- consumeForgePackAtInspect,- consumeForgePackAtInstall,-} from '../forgePackConsume.js';-import {- createForgePackStagingController,- sha256Hex,-} from '../forgePackStaging.js';--const OWNER: ActiveAppSession = {- mode: 'cloud',- dataOwnerId: 'user-a',- generation: 1,-};--const OTHER: ActiveAppSession = {- mode: 'cloud',- dataOwnerId: 'user-b',- generation: 2,-};--let tempDir: string | null = null;--afterEach(() => {- if (tempDir) {- fs.rmSync(tempDir, { recursive: true, force: true });- tempDir = null;- }-});--function makeController() {- tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-forge-consume-'));- let n = 0;- return createForgePackStagingController({- getTempDir: () => tempDir!,- randomId: () => `id-${n++}`,- scheduleTimeout: () => ({ cancel() {} }),- });-}--describe('consumeForgePackAtInspect / consumeForgePackAtInstall', () => {- it('accepts matching hash and manifest id, then refuses a second inspect', () => {- const controller = makeController();- const buf = Buffer.from('pkg-bytes');- const staged = controller.stage({- buf,- manifestId: 'demo',- owner: OWNER,- operationKind: 'install',- });- const first = consumeForgePackAtInspect(controller, {- filePath: staged.stagingPath,- packageSha256: sha256Hex(buf),- manifestId: 'demo',- currentOwner: OWNER,- boundaryPending: false,- });- expect(first.kind).toBe('accepted');- const second = consumeForgePackAtInspect(controller, {- filePath: staged.stagingPath,- packageSha256: sha256Hex(buf),- manifestId: 'demo',- currentOwner: OWNER,- boundaryPending: false,- });- expect(second).toEqual({ kind: 'rejected', reason: 'ticket-replay' });- });-- it('invalidates the ticket when inspect hash or manifest id mismatches', () => {- const controller = makeController();- const buf = Buffer.from('pkg-bytes');- const staged = controller.stage({- buf,- manifestId: 'demo',- owner: OWNER,- operationKind: 'install',- });- const rejected = consumeForgePackAtInspect(controller, {- filePath: staged.stagingPath,- packageSha256: 'b'.repeat(64),- manifestId: 'demo',- currentOwner: OWNER,- boundaryPending: false,- });- expect(rejected).toEqual({ kind: 'rejected', reason: 'ticket-binding-mismatch' });- expect(fs.existsSync(staged.stagingPath)).toBe(false);- expect(- consumeForgePackAtInspect(controller, {- filePath: staged.stagingPath,- packageSha256: sha256Hex(buf),- manifestId: 'demo',- currentOwner: OWNER,- boundaryPending: false,- }),- ).toEqual({ kind: 'not-forge' });- });-- it('refuses inspect while the session boundary is pending without consuming the ticket', () => {- const controller = makeController();- const buf = Buffer.from('pkg-bytes');- const staged = controller.stage({- buf,- manifestId: 'demo',- owner: OWNER,- operationKind: 'install',- });- expect(- consumeForgePackAtInspect(controller, {- filePath: staged.stagingPath,- packageSha256: sha256Hex(buf),- manifestId: 'demo',- currentOwner: OWNER,- boundaryPending: true,- }),- ).toEqual({ kind: 'rejected', reason: 'session-boundary-pending' });- expect(fs.existsSync(staged.stagingPath)).toBe(true);- expect(- consumeForgePackAtInspect(controller, {- filePath: staged.stagingPath,- packageSha256: sha256Hex(buf),- manifestId: 'demo',- currentOwner: OWNER,- boundaryPending: false,- }).kind,- ).toBe('accepted');- });-- it('refuses install while the session boundary is pending without consuming the continuation', () => {- const controller = makeController();- const buf = Buffer.from('pkg-bytes');- const staged = controller.stage({- buf,- manifestId: 'demo',- owner: OWNER,- operationKind: 'install',- });- const inspected = consumeForgePackAtInspect(controller, {- filePath: staged.stagingPath,- packageSha256: sha256Hex(buf),- manifestId: 'demo',- currentOwner: OWNER,- boundaryPending: false,- });- expect(inspected.kind).toBe('accepted');- if (inspected.kind !== 'accepted') return;- expect(- consumeForgePackAtInstall(controller, {- packTicket: inspected.packTicket,- packageSha256: sha256Hex(buf),- manifestId: 'demo',- currentOwner: OWNER,- boundaryPending: true,- }),- ).toEqual({ kind: 'rejected', reason: 'session-boundary-pending' });- expect(- consumeForgePackAtInstall(controller, {- packTicket: inspected.packTicket,- packageSha256: sha256Hex(buf),- manifestId: 'demo',- currentOwner: OWNER,- boundaryPending: false,- }).kind,- ).toBe('agent-forge');- });-- it('lets install proceed as update even when the pack ticket said install', () => {- const controller = makeController();- const buf = Buffer.from('pkg-bytes');- const staged = controller.stage({- buf,- manifestId: 'demo',- owner: OWNER,- operationKind: 'install',- });- const inspected = consumeForgePackAtInspect(controller, {- filePath: staged.stagingPath,- packageSha256: sha256Hex(buf),- manifestId: 'demo',- currentOwner: OWNER,- boundaryPending: false,- });- expect(inspected.kind).toBe('accepted');- if (inspected.kind !== 'accepted') return;- const installed = consumeForgePackAtInstall(controller, {- packTicket: inspected.packTicket,- packageSha256: sha256Hex(buf),- manifestId: 'demo',- currentOwner: OWNER,- boundaryPending: false,- });- expect(installed.kind).toBe('agent-forge');- if (installed.kind !== 'agent-forge') return;- expect(installed.ticket.operationKind).toBe('install');- expect(installed.ticket.manifestId).toBe('demo');- });-- it('treats a missing pack ticket as manual and refuses replay of a consumed continuation', () => {- const controller = makeController();- expect(- consumeForgePackAtInstall(controller, {- packTicket: undefined,- packageSha256: 'a'.repeat(64),- manifestId: 'demo',- currentOwner: OWNER,- boundaryPending: false,- }),- ).toEqual({ kind: 'manual' });-- const buf = Buffer.from('pkg-bytes');- const staged = controller.stage({- buf,- manifestId: 'demo',- owner: OWNER,- operationKind: 'update',- });- const inspected = consumeForgePackAtInspect(controller, {- filePath: staged.stagingPath,- packageSha256: sha256Hex(buf),- manifestId: 'demo',- currentOwner: OWNER,- boundaryPending: false,- });- expect(inspected.kind).toBe('accepted');- if (inspected.kind !== 'accepted') return;- expect(- consumeForgePackAtInstall(controller, {- packTicket: inspected.packTicket,- packageSha256: sha256Hex(buf),- manifestId: 'demo',- currentOwner: OWNER,- boundaryPending: false,- }).kind,- ).toBe('agent-forge');- expect(- consumeForgePackAtInstall(controller, {- packTicket: inspected.packTicket,- packageSha256: sha256Hex(buf),- manifestId: 'demo',- currentOwner: OWNER,- boundaryPending: false,- }),- ).toEqual({ kind: 'rejected', reason: 'ticket-replay' });- });-- it('refuses inspect continuation when the process freezes past the pack hard deadline', () => {- const t1 = 1_700_000_000_000;- const ttlMs = 10 * 60 * 1000;- tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-forge-consume-'));- let afterStage = false;- let inspectNowCalls = 0;- let n = 0;- const controller = createForgePackStagingController({- getTempDir: () => tempDir!,- ttlMs,- randomId: () => `id-${n++}`,- scheduleTimeout: () => ({ cancel() {} }),- now: () => {- if (!afterStage) return t1;- inspectNowCalls += 1;- // First now() is the pack expiry check (still live). Later now() is- // issueInstallContinuation after a 30-minute freeze.- return inspectNowCalls === 1 ? t1 + ttlMs - 1_000 : t1 + ttlMs - 1_000 + 30 * 60 * 1000;- },- });- const buf = Buffer.from('pkg-bytes');- const staged = controller.stage({- buf,- manifestId: 'demo',- owner: OWNER,- operationKind: 'install',- });- afterStage = true;- expect(- consumeForgePackAtInspect(controller, {- filePath: staged.stagingPath,- packageSha256: sha256Hex(buf),- manifestId: 'demo',- currentOwner: OWNER,- boundaryPending: false,- }),- ).toEqual({ kind: 'rejected', reason: 'ticket-expired' });- expect(fs.existsSync(staged.stagingPath)).toBe(false);- expect(inspectNowCalls).toBeGreaterThanOrEqual(2);- });-- it('cleans staging on cancel, success, and reject', () => {- const controller = makeController();- const buf = Buffer.from('pkg-bytes');- const cancelStaged = controller.stage({- buf,- manifestId: 'demo',- owner: OWNER,- operationKind: 'install',- });- const cancelInspect = consumeForgePackAtInspect(controller, {- filePath: cancelStaged.stagingPath,- packageSha256: sha256Hex(buf),- manifestId: 'demo',- currentOwner: OWNER,- boundaryPending: false,- });- expect(cancelInspect.kind).toBe('accepted');- if (cancelInspect.kind !== 'accepted') return;- abandonForgePackInstall(controller, cancelInspect.packTicket);- expect(fs.existsSync(cancelStaged.stagingPath)).toBe(false);-- const successStaged = controller.stage({- buf,- manifestId: 'demo',- owner: OWNER,- operationKind: 'install',- });- const successInspect = consumeForgePackAtInspect(controller, {- filePath: successStaged.stagingPath,- packageSha256: sha256Hex(buf),- manifestId: 'demo',- currentOwner: OWNER,- boundaryPending: false,- });- expect(successInspect.kind).toBe('accepted');- if (successInspect.kind !== 'accepted') return;- const successInstall = consumeForgePackAtInstall(controller, {- packTicket: successInspect.packTicket,- packageSha256: sha256Hex(buf),- manifestId: 'demo',- currentOwner: OWNER,- boundaryPending: false,- });- expect(successInstall.kind).toBe('agent-forge');- if (successInstall.kind !== 'agent-forge') return;- controller.releaseStaging(successInstall.ticket.stagingPath);- expect(fs.existsSync(successStaged.stagingPath)).toBe(false);-- const rejectStaged = controller.stage({- buf,- manifestId: 'demo',- owner: OWNER,- operationKind: 'install',- });- consumeForgePackAtInspect(controller, {- filePath: rejectStaged.stagingPath,- packageSha256: sha256Hex(buf),- manifestId: 'other',- currentOwner: OTHER,- boundaryPending: false,- });- expect(fs.existsSync(rejectStaged.stagingPath)).toBe(false);- });-});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forgePackStaging.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forgePackStaging.test.tsindex fb1cc8077c..fe0d3937da 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/forgePackStaging.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/forgePackStaging.test.ts@@ -395,60 +395,6 @@ describe('createForgePackStagingController', () => {expect(sawLeaseAfterPin).toBe(true);});- it('does not mint a continuation that outlives the pack hard deadline after a freeze', () => {- const t1 = 1_700_000_000_000;- let clock = t1;- const ttlMs = 10 * 60 * 1000;- const issued = controller({- now: () => clock,- ttlMs,- randomId: (() => {- let n = 0;- return () =>- ['task-cont-freeze', 'ticket-cont-freeze', 'cont-freeze'][n++] ?? `extra-${n}`;- })(),- });- const staged = issued.stage({- buf: Buffer.from('continuation-freeze'),- manifestId: 'demo',- owner: OWNER_A,- operationKind: 'install',- });- clock = t1 + ttlMs - 1_000;- const ticket = issued.consumeMatchingStagingPath(staged.stagingPath);- expect(ticket).not.toBeNull();- expect(ticket?.packExpiresAt).toBe(t1 + ttlMs);- clock = t1 + ttlMs - 1_000 + 30 * 60 * 1000;- expect(issued.issueInstallContinuation(ticket!)).toBeNull();- expect(fs.existsSync(staged.stagingPath)).toBe(false);- });-- it('does not delete staging if the continuation timeout fires before the ticket is registered', () => {- const issued = controller({- scheduleTimeout: (_ms, callback) => {- callback();- return { cancel() {} };- },- randomId: (() => {- let n = 0;- return () =>- ['task-sync-timeout', 'ticket-sync-timeout', 'cont-sync-timeout'][n++] ?? `extra-${n}`;- })(),- });- const staged = issued.stage({- buf: Buffer.from('sync-timeout'),- manifestId: 'demo',- owner: OWNER_A,- operationKind: 'install',- });- const ticket = issued.consumeMatchingStagingPath(staged.stagingPath);- expect(ticket).not.toBeNull();- const continuation = issued.issueInstallContinuation(ticket!);- expect(continuation).toBe('cont-sync-timeout');- expect(fs.existsSync(staged.stagingPath)).toBe(true);- expect(issued.consumeInstallContinuation(continuation!)).toEqual(ticket);- });-it('writes the one-shot lease marker after hashing, not when the package file is created', () => {const dir = makeTempDir();const originalCreateHash = crypto.createHash;diff --git a/apps/desktop/src/main/cindy-brain/__tests__/fsSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/fsSlot.test.tsindex 3f804ce7af..69793e8857 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/fsSlot.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/fsSlot.test.ts@@ -13,7 +13,7 @@ import { GHOST_FS_WRITE_MAX_BYTES, type InstalledGhost } from '../../../shared/gconst GHOST_ID = 'test-ghost';-function makeGhost(slots: string[]): InstalledGhost {+function makeGhost(fsCapability: boolean): InstalledGhost {return {manifest: {schemaVersion: 2,@@ -22,7 +22,7 @@ function makeGhost(slots: string[]): InstalledGhost {version: '1.0.0',kind: 'chip',entry: 'main.js',- slots: slots as InstalledGhost['manifest']['slots'],+ ...(fsCapability ? { fs: true } : {}),},dir: '/tmp/fake-install-dir',enabled: true,@@ -31,7 +31,7 @@ function makeGhost(slots: string[]): InstalledGhost {}interface HarnessOverrides {- slots?: string[];+ fs?: boolean;session?: FsSessionSnapshot | null;confirm?: (sessionId: string) => Promise<{ confirmed: boolean }>;saveWrite?: FsSlotDeps['writeSaveDeposit'];@@ -60,7 +60,7 @@ function makeHarness(dataRoot: string, overrides: HarnessOverrides = {}) {}: null;const deps: FsSlotDeps = {- getGhost: (id) => (id === GHOST_ID ? makeGhost(overrides.slots ?? ['fs']) : null),+ getGhost: (id) => (id === GHOST_ID ? makeGhost(overrides.fs ?? true) : null),dataRootDir: () => dataRoot,callInfo: entryFor,inFlightCallInfo: (callId) => (overrides.inFlight === false ? null : entryFor(callId)),@@ -133,8 +133,8 @@ describe('GhostFsSlot', () => {await fs.promises.rm(tmpRoot, { recursive: true, force: true });});- it('未声明 fs 卡槽一律拒', async () => {- const { slot } = makeHarness(dataRoot, { slots: ['tool'] });+ it('未声明 fs 能力一律拒', async () => {+ const { slot } = makeHarness(dataRoot, { fs: false });const r = await slot.handleFsRequest(GHOST_ID, {type: 'fs-request', op: 'write', root: 'data', path: 'a.txt', content: 'hi',});@@ -142,6 +142,47 @@ describe('GhostFsSlot', () => {expect((r as { message: string }).message).toContain('fs');});+ it('未声明 fs 时,Agent 在途调用仍可按会话权限写 workdir', async () => {+ const { slot } = makeHarness(dataRoot, {+ fs: false,+ session: {+ workingDir: workdir,+ permissionMode: 'acceptEdits',+ planModeEnabled: false,+ remoteHostId: null,+ },+ });+ const r = await slot.handleFsRequest(GHOST_ID, {+ type: 'fs-request',+ op: 'write',+ root: 'workdir',+ path: 'agent/output.txt',+ content: 'ok',+ callId: 'call-1',+ });+ expect(r).toMatchObject({ ok: true, op: 'write' });+ expect(await fs.promises.readFile(path.join(workdir, 'agent/output.txt'), 'utf8')).toBe('ok');+ });++ it('未声明 fs 时,脚本通道不能复用 Agent 的 workdir 授权', async () => {+ const { slot } = makeHarness(dataRoot, {+ fs: false,+ callSessionId: null,+ callScriptWorkdir: workdir,+ callChannel: 'script',+ });+ expect(+ await slot.handleFsRequest(GHOST_ID, {+ type: 'fs-request',+ op: 'write',+ root: 'workdir',+ path: 'script/output.txt',+ content: 'blocked',+ callId: 'call-1',+ }),+ ).toMatchObject({ ok: false });+ });+it('未知 op / root 拒', async () => {const { slot } = makeHarness(dataRoot);expect(await slot.handleFsRequest(GHOST_ID, { type: 'fs-request', op: 'chmod', root: 'data' })).toMatchObject({ ok: false });diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyFacts.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyFacts.test.tsindex a6de2547f6..28e5dbb335 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyFacts.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyFacts.test.ts@@ -60,7 +60,6 @@ function loader(overrides: Partial<LoadGhostFirstPartyFactsLoaderOptions> = {})readMarketInstallation: () => null,readApprovedPackageSha256: () => null,lookupOrganizationPrefix: () => ({ kind: 'absent' }),- readInstallOrigin: () => 'manual',...overrides,});}@@ -83,7 +82,6 @@ describe('loadGhostFirstPartyFactsLoader', () => {builtin: true,marketRecord: null,currentOrganization: null,- installOrigin: 'manual',});expect(resolveGhostFirstPartyPrivilege(loaded.facts)).toEqual({brokerEligible: true,@@ -165,7 +163,6 @@ describe('loadGhostFirstPartyFactsLoader', () => {builtin: false,marketRecord: null,currentOrganization: null,- installOrigin: 'manual',},});});@@ -213,7 +210,6 @@ describe('loadGhostFirstPartyFactsLoader', () => {builtin: false,marketRecord: null,currentOrganization: { organizationId: 'org-a', pluginPrefix: 'acme' },- installOrigin: 'manual',},});});@@ -239,7 +235,6 @@ describe('loadGhostFirstPartyFactsLoader', () => {approvedPackageSha256: MARKET_ROW.sha256,},currentOrganization: { organizationId: 'org-a', pluginPrefix: null },- installOrigin: 'manual',},});});@@ -290,7 +285,6 @@ describe('loadGhostFirstPartyFactsLoader', () => {inspectedPackageSha256,),currentOrganization: { organizationId: 'org-a', pluginPrefix: 'acme' },- installOrigin: 'manual' as const,},});@@ -301,14 +295,12 @@ describe('loadGhostFirstPartyFactsLoader', () => {expect(authorizeGhostTokenBroker('acme-tool', installLoad('b'.repeat(64)))).toBe(false);});- it('treats a missing receipt as manual so builtin official plugins stay unchanged', () => {+ it('keeps builtin official plugins unchanged without receipt-origin facts', () => {const loaded = loader({readInstalledBuiltin: (ghostId) => ghostId === 'xd-feishu',- readInstallOrigin: () => 'manual',}).load('xd-feishu', 'runtime', PERSONAL);expect(loaded.kind).toBe('ready');if (loaded.kind !== 'ready') return;- expect(loaded.facts.installOrigin).toBe('manual');expect(resolveGhostFirstPartyPrivilege(loaded.facts)).toEqual({brokerEligible: true,hostPrimitiveEligible: true,@@ -316,25 +308,4 @@ describe('loadGhostFirstPartyFactsLoader', () => {});});- it('copies installOrigin from the receipt reader and treats a read failure as manual', () => {- const forged = loader({- readInstallOrigin: () => 'agent-forge',- lookupOrganizationPrefix: () => ({ kind: 'known', pluginPrefix: 'acme' }),- }).load('acme-feishu', 'runtime', ORG_A);- expect(forged).toMatchObject({- kind: 'ready',- facts: { installOrigin: 'agent-forge' },- });-- const unread = loader({- readInstallOrigin: () => {- throw new Error('EACCES');- },- lookupOrganizationPrefix: () => ({ kind: 'known', pluginPrefix: 'acme' }),- }).load('acme-feishu', 'runtime', ORG_A);- expect(unread).toMatchObject({- kind: 'ready',- facts: { installOrigin: 'manual' },- });- });});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyPrivilege.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyPrivilege.test.tsindex ebe7012237..f94565bd5d 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyPrivilege.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyPrivilege.test.ts@@ -30,7 +30,6 @@ function facts(partial: Partial<GhostFirstPartyFacts> & Pick<GhostFirstPartyFactbuiltin: false,marketRecord: null,currentOrganization: null,- installOrigin: 'manual',...partial,};}@@ -294,28 +293,7 @@ describe('resolveGhostFirstPartyPrivilege', () => {});});- it('gives a forge-built local package broker when the id matches the current org prefix, not a manual install', () => {- const shared = {- ghostId: 'acme-feishu',- currentOrganization: CURRENT_ORG,- } as const;- expect(- resolveGhostFirstPartyPrivilege(facts({ ...shared, installOrigin: 'agent-forge' })),- ).toEqual({- brokerEligible: true,- hostPrimitiveEligible: false,- basis: 'local-current-org-prefix',- });- expect(- resolveGhostFirstPartyPrivilege(facts({ ...shared, installOrigin: 'manual' })),- ).toEqual({- brokerEligible: false,- hostPrimitiveEligible: false,- basis: 'denied-unknown-origin',- });- });-- it('does not raise a custom-market package to broker unless it was forge-installed', () => {+ it('does not raise a custom-market package to broker', () => {expect(resolveGhostFirstPartyPrivilege(facts({@@ -326,7 +304,6 @@ describe('resolveGhostFirstPartyPrivilege', () => {source: 'local-market',}),currentOrganization: CURRENT_ORG,- installOrigin: 'manual',}),),).toEqual({@@ -358,8 +335,7 @@ describe('resolveGhostFirstPartyPrivilege', () => {basis: 'denied-unknown-origin',});}- // 作者自测:从未发布过的 id 没有台账行。手动装仍 deny;只有 forge 装入- // 才走兜底放 Broker(见「forge-built local package」那条对照用例)。+ // 作者自测:从未发布过的 id 没有台账行,本地装入仍然 deny。});it('keeps official-prefix broker even when facts are unavailable, and asks the resolver otherwise', () => {@@ -377,20 +353,6 @@ describe('resolveGhostFirstPartyPrivilege', () => {facts: facts({ghostId: 'acme-feishu',currentOrganization: CURRENT_ORG,- installOrigin: 'agent-forge',- }),- },- ),- ).toBe(true);- expect(- authorizeGhostTokenBroker(- 'acme-feishu',- {- kind: 'ready',- facts: facts({- ghostId: 'acme-feishu',- currentOrganization: CURRENT_ORG,- installOrigin: 'manual',}),},),@@ -402,7 +364,6 @@ describe('resolveGhostFirstPartyPrivilege', () => {ghostId: 'acme-feishu',marketRecord: market({ scope: 'organization', organizationId: 'org-acme' }),currentOrganization: CURRENT_ORG,- installOrigin: 'manual',});expect(authorizeGhostTokenBroker('acme-feishu', { kind: 'ready', facts: pendingOrgMarket })).toBe(true,@@ -415,7 +376,6 @@ describe('resolveGhostFirstPartyPrivilege', () => {builtin: false,marketRecord: null,currentOrganization: null,- installOrigin: 'manual',}),}),).toBe(true);diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostHostSetupRequirements.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostHostSetupRequirements.test.tsindex 4e56fa2fe9..7403180722 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostHostSetupRequirements.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostHostSetupRequirements.test.ts@@ -12,7 +12,6 @@ function manifest(id: string, cindy = false): GhostManifest {version: '1',kind: 'chip',entry: 'main.js',- slots: cindy ? ['tool', 'cindy'] : ['tool'],tools: [{ name: 'run', description: 'run' }],...(cindy ? { cindy: { image: ['generate' as const] } } : {}),};diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.tsindex c79714b498..e5855a743f 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.ts@@ -4,11 +4,10 @@ import path from 'node:path';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { validateGhostManifest, type GhostManifest } from '../../../shared/ghost';+import { validateGhostManifest } from '../../../shared/ghost';import {createGhostInstallReceipt,- effectiveInstallOrigin,type GhostInstallReceipt,GhostInstallReceiptStore,} from '../ghostInstallReceipt';@@ -299,184 +298,3 @@ describe('GhostInstallReceiptStore cleanup', () => {expect(fs.existsSync(path.join(parent, 'stale'))).toBe(true);});});--describe('GhostInstallReceipt installOrigin', () => {- function input(installOrigin?: string) {- const manifest: GhostManifest = {- schemaVersion: 2,- id: 'hello',- name: 'Hello',- version: '1.0.0',- kind: 'chip',- entry: 'main.js',- slots: ['tool'],- tools: [{ name: 'do_thing', description: 'Do something' }],- };- return {- manifest,- localeResources: {},- enabled: true,- trust: {- level: 'unverified' as const,- publisherSigned: false,- publisherVerified: false,- reviewed: false,- },- skillContentSha256: {},- ...(installOrigin !== undefined ? { installOrigin } : {}),- };- }-- it('treats a v2 receipt without installOrigin as approved manual', () => {- const receipt = createGhostInstallReceipt(input());- expect(receipt.schemaVersion).toBe(2);- expect(receipt.installOrigin).toBeUndefined();- expect(effectiveInstallOrigin(receipt)).toBe('manual');- expect(JSON.stringify(receipt)).not.toContain('installOrigin');- });-- it('keeps an unknown bounded origin and does not use it for authorization', () => {- const receipt = createGhostInstallReceipt(input('future-origin'));- expect(receipt.installOrigin).toBe('future-origin');- expect(effectiveInstallOrigin(receipt)).toBe('manual');- const rewritten = createGhostInstallReceipt({- ...input(),- enabled: false,- installOrigin: receipt.installOrigin,- });- expect(rewritten.installOrigin).toBe('future-origin');- expect(rewritten.enabled).toBe(false);- expect(effectiveInstallOrigin(rewritten)).toBe('manual');- });-- it('writes this-operation origin instead of inheriting the previous receipt', () => {- expect(createGhostInstallReceipt(input('manual')).installOrigin).toBe('manual');- expect(createGhostInstallReceipt(input('agent-forge')).installOrigin).toBe('agent-forge');- expect(createGhostInstallReceipt(input()).installOrigin).toBeUndefined();- expect(effectiveInstallOrigin(createGhostInstallReceipt(input()))).toBe('manual');- });-- it('reads a v2 disk receipt without installOrigin as approved manual', async () => {- const workDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-receipt-origin-'));- try {- const rawState = path.join(workDir, 'state');- await fs.promises.mkdir(rawState);- const stateRoot = await fs.promises.realpath(rawState);- const store = new GhostInstallReceiptStore(() => stateRoot, async ({ parentDir, targetName, operation }) => {- if (operation === 'remove') {- await fs.promises.rm(path.join(parentDir, targetName), { recursive: true, force: true });- }- });- const legacyV2 = {- schemaVersion: 2,- id: 'hello',- revision: '00000000-0000-4000-8000-000000000001',- manifest: {- schemaVersion: 2,- id: 'hello',- name: 'Hello',- version: '1.0.0',- kind: 'chip',- entry: 'main.js',- slots: ['tool'],- tools: [{ name: 'do_thing', description: 'Do something' }],- },- localeResources: {},- enabled: true,- trust: {- level: 'unverified',- publisherSigned: false,- publisherVerified: false,- reviewed: false,- },- skillContentSha256: {},- };- expect(JSON.stringify(legacyV2)).not.toContain('installOrigin');- await fs.promises.writeFile(- path.join(stateRoot, 'hello.json'),- `${JSON.stringify(legacyV2, null, 2)}\n`,- 'utf8',- );- const read = store.read('hello');- expect(read.state).toBe('approved');- if (read.state !== 'approved') return;- expect(read.receipt.schemaVersion).toBe(2);- expect(read.receipt.installOrigin).toBeUndefined();- expect(effectiveInstallOrigin(read.receipt)).toBe('manual');-- await store.write(createGhostInstallReceipt(input('agent-forge')));- const written = store.read('hello');- expect(written.state).toBe('approved');- if (written.state !== 'approved') return;- expect(written.receipt.installOrigin).toBe('agent-forge');- } finally {- await fs.promises.rm(workDir, { recursive: true, force: true });- }- });-- it('rejects writer values the parser would not read back', () => {- expect(() => createGhostInstallReceipt(input(''))).toThrow('installOrigin');- expect(() => createGhostInstallReceipt(input('x'.repeat(65)))).toThrow('installOrigin');- expect(() => createGhostInstallReceipt(input('Bad_Origin'))).toThrow('installOrigin');- expect(createGhostInstallReceipt(input('future-origin')).installOrigin).toBe('future-origin');- });-- it('reads unknown-but-bounded origins as approved manual and malformed origins as invalid', async () => {- const workDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-receipt-origin-parse-'));- try {- const rawState = path.join(workDir, 'state');- await fs.promises.mkdir(rawState);- const stateRoot = await fs.promises.realpath(rawState);- const store = new GhostInstallReceiptStore(() => stateRoot, async ({ parentDir, targetName, operation }) => {- if (operation === 'remove') {- await fs.promises.rm(path.join(parentDir, targetName), { recursive: true, force: true });- }- });- const base = {- schemaVersion: 2,- id: 'hello',- revision: '00000000-0000-4000-8000-000000000001',- manifest: {- schemaVersion: 2,- id: 'hello',- name: 'Hello',- version: '1.0.0',- kind: 'chip',- entry: 'main.js',- slots: ['tool'],- tools: [{ name: 'do_thing', description: 'Do something' }],- },- localeResources: {},- enabled: true,- trust: {- level: 'unverified',- publisherSigned: false,- publisherVerified: false,- reviewed: false,- },- skillContentSha256: {},- };- await fs.promises.writeFile(- path.join(stateRoot, 'hello.json'),- `${JSON.stringify({ ...base, installOrigin: 'future-origin' }, null, 2)}\n`,- 'utf8',- );- const unknown = store.read('hello');- expect(unknown.state).toBe('approved');- if (unknown.state !== 'approved') return;- expect(unknown.receipt.installOrigin).toBe('future-origin');- expect(effectiveInstallOrigin(unknown.receipt)).toBe('manual');-- for (const installOrigin of [{ kind: 'agent-forge' }, '', 'x'.repeat(65), 'Bad Origin']) {- await fs.promises.writeFile(- path.join(stateRoot, 'hello.json'),- `${JSON.stringify({ ...base, installOrigin }, null, 2)}\n`,- 'utf8',- );- expect(store.read('hello').state, String(installOrigin)).toBe('invalid');- }- } finally {- await fs.promises.rm(workDir, { recursive: true, force: true });- }- });-});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostIpcMutationLease.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostIpcMutationLease.test.tsindex b27e084fdf..f206877f0c 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostIpcMutationLease.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostIpcMutationLease.test.ts@@ -53,22 +53,6 @@ describe('ghost 写路径 IPC 的 owner 租约(源码契约)', () => {});}- it('ghosts:reapprove-installed 持租约,owner 以 inspect 时点的一次性票据为准(更强于 handler 内 capture)', () => {- // 第 8 轮 P0-2:owner 在 confirm 入口才 capture 绑不住"读事实那一刻"——确认卡- // 停留期间切号,A 看的确认可以给 B 的同 id 目录铸批准。现在 inspect 发一次性- // 票据(钉 owner + id + manifestSha256),confirm 原子消费并以**票据里的 owner**- // 起租约:generation 不等直接拒。handler 内不该再出现 captureGhostMutationOwner- // (那会退化回"用确认时刻的 owner",正是要消掉的形态)。- const block = handlerBlock(source, 'ghosts:reapprove-installed');- expect(block).toContain('reapproveTickets.consume(');- expect(block).toContain('beginGhostMutation(ticket.owner)');- expect(block).not.toContain('captureGhostMutationOwner()');- // inspect 侧必须在读事实之前捕获 owner 并发票。- const inspectBlock = handlerBlock(source, 'ghosts:reapprove-inspect');- expect(inspectBlock).toContain('captureGhostMutationOwner()');- expect(inspectBlock).toContain('reapproveTickets.issue(');- });-it('ghosts:uninstall 经 uninstallGhostAndCleanup 持租约(入口同步取,无异步窗口故无需 capture)', () => {const block = handlerBlock(source, 'ghosts:uninstall');expect(block).toContain('uninstallGhostAndCleanup(');diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostIpcSenderTrust.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostIpcSenderTrust.test.tsindex a771cadad2..8138fffd1d 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostIpcSenderTrust.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostIpcSenderTrust.test.ts@@ -27,8 +27,6 @@ const TRUSTED_SENDER_CHANNELS = ['ghosts:export','ghosts:set-enabled','ghosts:restore-builtin',- 'ghosts:reapprove-inspect',- 'ghosts:reapprove-installed',] as const;function handlerBlock(source: string, channel: string): string {diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthScopeStaleness.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthScopeStaleness.test.tsindex 04bb93a1cd..b87cfbc13d 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthScopeStaleness.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthScopeStaleness.test.ts@@ -13,7 +13,6 @@ const MANIFEST: GhostManifest = {version: '2.3.0',kind: 'chip',entry: 'main.js',- slots: ['network'],network: {hosts: ['open.feishu.cn'],secrets: [diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupCoordinator.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupCoordinator.test.tsindex 1ce78468a8..168972d132 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupCoordinator.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupCoordinator.test.ts@@ -1281,12 +1281,15 @@ describe('GhostSetupCoordinator', () => {const changeBus = new GhostSetupChangeBus();const bridge = new GhostSetupInteractionBridge({ broadcast: vi.fn() });const ghost = {+ dir: '/plugins/gmail',enabled: true,manifest: {+ schemaVersion: 3,id: 'gmail',name: 'Gmail',+ version: '1.0.0',kind: 'chip',- slots: ['tool'],+ entry: 'main.js',tools: [{ name: 'search', description: 'Search' }],},} as InstalledGhost;diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupInlineExecutor.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupInlineExecutor.test.tsindex cba1402976..e49cb35c9d 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupInlineExecutor.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupInlineExecutor.test.ts@@ -32,7 +32,6 @@ function manifest(source?: 'user' | 'oauth' | 'login-email' | 'gh-cli' | 'oidc-tversion: '1.0.0',kind: 'chip',entry: 'main.js',- slots: ['tool', 'network'],tools: [{ name: 'call', description: 'Call' }],network: {hosts: ['api.example.com'],@@ -107,7 +106,6 @@ describe('executeGhostSetupInlineSubmission', () => {const nodeManifest: GhostManifest = {...manifest(),settingsHtml: 'settings.html',- slots: ['tool', 'network', 'node'],node: {entry: 'node/worker.cjs',protocol: 'json-rpc-stdio',diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupManifestTracker.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupManifestTracker.test.tsindex 6089550963..69ef8a3610 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupManifestTracker.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostSetupManifestTracker.test.ts@@ -19,7 +19,6 @@ function ghost(version: '1',kind: 'chip',entry: 'main.js',- slots: ['tool'],tools: (options.tools ?? ['run']).map((name) => ({name,description: name,diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostTokenBrokerInstallError.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostTokenBrokerInstallError.test.tsindex 0bce7c443d..5ab1974e5a 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostTokenBrokerInstallError.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostTokenBrokerInstallError.test.ts@@ -3,22 +3,10 @@ import { describe, expect, it } from 'vitest';import { ghostTokenBrokerInstallError } from '../ghostTokenBrokerInstallError.js';describe('ghostTokenBrokerInstallError', () => {- it('keeps manual install and unknown runtime facts on distinct actionable codes', () => {- expect(ghostTokenBrokerInstallError('manual')).toMatchObject({- code: 'GHOST_BROKER_MANUAL_INSTALL_NOT_AUTHORIZED',- reason: expect.stringContaining('手动装入'),- });- expect(ghostTokenBrokerInstallError('agent-forge')).toMatchObject({- code: 'GHOST_BROKER_NOT_AUTHORIZED',- reason: expect.stringContaining('组织身份'),- });+ it('returns the actionable local-install authorization error', () => {expect(ghostTokenBrokerInstallError()).toMatchObject({- code: 'GHOST_BROKER_NOT_AUTHORIZED',+ code: 'GHOST_BROKER_MANUAL_INSTALL_NOT_AUTHORIZED',+ reason: expect.stringContaining('本地装入'),});- // Distinct literal codes prevent Renderer copy from guessing the reason- // from Main's localized message or remapping all GHOST_FILE_INVALID errors.- expect(ghostTokenBrokerInstallError('manual').code).not.toBe(- ghostTokenBrokerInstallError().code,- );});});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostUnreadProjection.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostUnreadProjection.test.tsindex 6f8a584049..f028cf2608 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostUnreadProjection.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostUnreadProjection.test.ts@@ -15,7 +15,7 @@ import type { InstalledGhost } from '../../../shared/ghost';function ghost(id: string,- opts: { enabled?: boolean; slots?: string[]; badge?: boolean } = {},+ opts: { enabled?: boolean; notify?: boolean; badge?: boolean } = {},): InstalledGhost {const badge = opts.badge ?? true;return {@@ -26,7 +26,9 @@ function ghost(version: '1.0.0',kind: 'chip',entry: 'main.js',- slots: badge ? [...(opts.slots ?? ['panel', 'notify']), 'badge'] : (opts.slots ?? ['panel', 'notify']),+ panel: { html: 'panel.html' },+ ...(opts.notify === false ? {} : { notify: true }),+ ...(badge ? { badge: true } : {}),},dir: `/fake/${id}`,@@ -39,8 +41,8 @@ describe('ghostUnreadProjection', () => {expect(ghostDeclaresBadge(ghost('a'))).toBe(true);expect(ghostDeclaresBadge(ghost('a', { enabled: false }))).toBe(true);expect(ghostDeclaresBadge(ghost('a', { badge: false }))).toBe(false);- // 没有 notify 槽照样算数——绿点与 toast 是并列的两档权限。- expect(ghostDeclaresBadge(ghost('a', { slots: ['panel'] }))).toBe(true);+ // 没有 notify 能力照样算数——绿点与 toast 是并列的两档权限。+ expect(ghostDeclaresBadge(ghost('a', { notify: false }))).toBe(true);expect(ghostDeclaresBadge(null)).toBe(false);});@@ -60,8 +62,8 @@ describe('ghostUnreadProjection', () => {const entries = [{ ghostId: 'revoked' }, { ghostId: 'noslot' }, { ghostId: 'gone' }, { ghostId: 'ok' }];const ids = selectRevokedGhostUnreadIds(entries, [ghost('revoked', { badge: false }),- // 只丢了 notify 槽但 badge 还在 → **不算**撤销(两档权限彼此独立)。- ghost('noslot', { slots: ['panel'] }),+ // 只丢了 notify 但 badge 还在 → **不算**撤销(两档权限彼此独立)。+ ghost('noslot', { notify: false }),ghost('ok'),]);expect(ids.sort()).toEqual(['gone', 'revoked']);diff --git a/apps/desktop/src/main/cindy-brain/__tests__/iosSimulatorPluginGate.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/iosSimulatorPluginGate.test.tsindex 9ba00e2dd5..d1b9e7230c 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/iosSimulatorPluginGate.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/iosSimulatorPluginGate.test.ts@@ -3,10 +3,10 @@ import { describe, expect, it } from 'vitest';import type { InstalledGhost } from '../../../shared/ghost.js';import { resolveIOSSimulatorPluginAccess } from '../iosSimulatorPluginGate.js';-function ghost(id: string, enabled: boolean, slots: string[] = ['ios-simulator']): InstalledGhost {+function ghost(id: string, enabled: boolean, hasCapability = true): InstalledGhost {return {enabled,- manifest: { id, name: id, slots },+ manifest: { id, name: id, ...(hasCapability ? { iosSimulator: true } : {}) },} as unknown as InstalledGhost;}@@ -61,7 +61,7 @@ describe('iOS Simulator plugin Host gate', () => {});it('does not treat an unrelated enabled plugin as a capability provider', () => {- expect(resolve([ghost('ordinary-plugin', true, ['skill'])])).toMatchObject({+ expect(resolve([ghost('ordinary-plugin', true, false)])).toMatchObject({allowed: false,errorCode: 'IOS_SIMULATOR_PLUGIN_REQUIRED',});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/iosSimulatorSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/iosSimulatorSlot.test.tsindex 2716ab1861..cd1dd5125e 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/iosSimulatorSlot.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/iosSimulatorSlot.test.ts@@ -9,7 +9,7 @@ import {type IOSSimulatorSlotFocusContext,} from '../iosSimulatorSlot';-function simulatorGhost(options: { enabled?: boolean; slots?: string[] } = {}): InstalledGhost {+function simulatorGhost(options: { enabled?: boolean; iosSimulator?: boolean } = {}): InstalledGhost {return {manifest: {schemaVersion: 2,@@ -18,7 +18,7 @@ function simulatorGhost(options: { enabled?: boolean; slots?: string[] } = {}):version: '1.0.0',kind: 'chip',entry: 'main.js',- slots: options.slots ?? ['ios-simulator'],+ ...(options.iosSimulator === false ? {} : { iosSimulator: true }),},dir: '/fake/ios-simulator',enabled: options.enabled ?? true,@@ -101,8 +101,8 @@ function makeSlot(overrides: Partial<IOSSimulatorSlotDeps> = {}) {}describe('GhostIOSSimulatorSlot', () => {- it('requires the explicit slot and an enabled plugin', async () => {- const noSlot = makeSlot({ getGhost: () => simulatorGhost({ slots: ['panel'] }) });+ it('requires the explicit capability and an enabled plugin', async () => {+ const noSlot = makeSlot({ getGhost: () => simulatorGhost({ iosSimulator: false }) });await expect(noSlot.slot.handleRequest('ios-simulator', { kind: 'status' }),).resolves.toMatchObject({ ok: false, errorCode: 'PERMISSION_DENIED' });diff --git a/apps/desktop/src/main/cindy-brain/__tests__/librarySlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/librarySlot.test.tsindex 199ac47572..2e94e4ba78 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/librarySlot.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/librarySlot.test.ts@@ -1,5 +1,5 @@/**- * librarySlot 单测:资格审(未声明/停用拒)、管道级全链路(open/status/write/+ * library 能力单测:资格审(未声明/停用拒)、管道级全链路(open/status/write/* read/rename/delete)、db 子集(经进程内 core)、binding 漂移 → unavailable、* owner scope 切换后旧会话作废且写入落新根。注入 deps + tmpdir,零 Electron。*/@@ -19,16 +19,17 @@ import type { InstalledGhost } from '../../../shared/ghost.js';const Ctor = Database as unknown as SqliteDatabaseConstructor;const GHOST_ID = 'mivo-canvas';-function makeGhost(slots: string[], enabled = true): InstalledGhost {+function makeGhost(library: boolean, enabled = true): InstalledGhost {return {manifest: {- schemaVersion: 2,+ schemaVersion: 3,+ minCindyVersion: '0.1.61',id: GHOST_ID,name: '测试意识',version: '1.0.0',kind: 'chip',entry: 'main.js',- slots: slots as InstalledGhost['manifest']['slots'],+ ...(library ? { library: true } : {}),},dir: '/tmp/fake-install-dir',enabled,@@ -51,7 +52,7 @@ describe('GhostLibrarySlot', () => {bindingFile = path.join(tmp, 'owners', 'a', 'libraries-binding.json');candidate = path.join(tmp, 'picked');await fs.promises.mkdir(candidate, { recursive: true });- ghost = makeGhost(['library']);+ ghost = makeGhost(true);const deps: GhostLibrarySlotDeps = {getGhost: (id) => (id === GHOST_ID ? ghost : null),bindingStore: new LibraryBindingStore({@@ -80,15 +81,15 @@ describe('GhostLibrarySlot', () => {await fs.promises.rm(tmp, { recursive: true, force: true });});- it('资格审:未声明 library 槽/停用 → NOT_DECLARED', async () => {- ghost = makeGhost(['fs']);+ it('资格审:未声明 library 能力/停用 → NOT_DECLARED', async () => {+ ghost = 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');- ghost = makeGhost(['library'], false);+ ghost = makeGhost(true, false);const r2 = await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });expect(r2.ok).toBe(false);- ghost = makeGhost(['library']);+ ghost = makeGhost(true);});it('管道级全链路:open/status/write/read/rename/delete(默认根)', async () => {diff --git a/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.tsindex c6b6c9dc4d..c3c21de54a 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts@@ -81,51 +81,59 @@ describe('market Ghost session boundary', () => {"ipcMain.handle('ghosts:pick-file'",updateStart,);- const body = source.slice(updateStart, updateEnd);+ const updateBody = source.slice(updateStart, updateEnd);+ const helperStart = source.indexOf('async function updateLocalGhostPackageLocked(');+ const helperEnd = source.indexOf(+ '\n}\n\n/**\n * Forge 的显式安装入口。',+ helperStart,+ );+ const helperBody = source.slice(helperStart, helperEnd);- const ledgerReadIndex = body.indexOf(+ const ledgerReadIndex = helperBody.indexOf('marketLedger.installationForGhost(inspected.manifest.id)',);- const captureIndex = body.indexOf('const mutationOwner = captureGhostMutationOwner();');- const ledgerBindIndex = body.indexOf('const marketLedger = getPluginMarketLedger().bind(');- const inspectIndex = body.indexOf('await manager.inspect(lizFilePath)');- const leaseIndex = body.indexOf('const releaseMutation = beginGhostMutation(mutationOwner);');- const detachDecisionIndex = body.indexOf(+ const captureIndex = updateBody.indexOf('const mutationOwner = captureGhostMutationOwner();');+ const inspectIndex = updateBody.indexOf('await manager.inspect(lizFilePath)');+ const leaseIndex = updateBody.indexOf('const releaseMutation = beginGhostMutation(mutationOwner);');+ const helperCallIndex = updateBody.indexOf('updateLocalGhostPackageLocked(');+ const ledgerBindIndex = helperBody.indexOf('const marketLedger = getPluginMarketLedger().bind(');+ const detachDecisionIndex = helperBody.indexOf('const detachMarketRecord = Boolean(marketRecord?.installed)',);- const runtimeStopIndex = body.indexOf('runtime.stop(inspected.manifest.id)');- const stopAndWaitIndex = body.indexOf(+ const runtimeStopIndex = helperBody.indexOf('runtime.stop(inspected.manifest.id)');+ const stopAndWaitIndex = helperBody.indexOf('await getGhostNodeRuntimeBroker().stopAndWait(inspected.manifest.id);',);- const oauthLockIndex = body.indexOf(+ const oauthLockIndex = helperBody.indexOf('result = await withActiveOwnerGhostOauthMutationLock(inspected.manifest.id',);- const managerUpdateIndex = body.indexOf('manager.update(lizFilePath,');- const detachIndex = body.indexOf(+ const managerUpdateIndex = helperBody.indexOf('manager.update(cindyFilePath,');+ const detachIndex = helperBody.indexOf('marketLedger.markRemoved(inspected.manifest.id, marketInstallSubject)',);expect(captureIndex).toBeGreaterThan(-1);- expect(ledgerBindIndex).toBeGreaterThan(captureIndex);- expect(ledgerBindIndex).toBeLessThan(inspectIndex);+ expect(captureIndex).toBeLessThan(inspectIndex);expect(leaseIndex).toBeGreaterThan(inspectIndex);- expect(ledgerReadIndex).toBeGreaterThan(leaseIndex);+ expect(helperCallIndex).toBeGreaterThan(leaseIndex);+ expect(ledgerBindIndex).toBeGreaterThan(-1);+ expect(runtimeStopIndex).toBeGreaterThan(ledgerBindIndex);+ expect(ledgerReadIndex).toBeGreaterThan(stopAndWaitIndex);expect(detachDecisionIndex).toBeGreaterThan(ledgerReadIndex);- expect(runtimeStopIndex).toBeGreaterThan(leaseIndex);expect(stopAndWaitIndex).toBeGreaterThan(runtimeStopIndex);// 只有确认旧进程退出,才切断旧市场的自动更新路由;等待失败时保留原路由,// 也不会尝试恢复第二份 resident 进程。expect(detachIndex).toBeGreaterThan(stopAndWaitIndex);expect(oauthLockIndex).toBeGreaterThan(detachIndex);expect(managerUpdateIndex).toBeGreaterThan(oauthLockIndex);- expect(body).toContain('marketLedger.isDefaultInstallSuppressed(');- expect(body).toContain('marketLedger.restoreInstallation(');- expect(body).toContain('suppressed: marketRecordWasSuppressed');- expect(body).toContain('onPackagePlaced: () => {');- expect(body).toContain('packagePlaced = true;');- expect(body).toContain('if (!packagePlaced) {\n restoreMarketRecord();');- expect(body).toContain('releaseMutation();');- expect(body).not.toContain('GHOST_SOURCE_CONFLICT');+ expect(helperBody).toContain('marketLedger.isDefaultInstallSuppressed(');+ expect(helperBody).toContain('marketLedger.restoreInstallation(');+ expect(helperBody).toContain('suppressed: marketRecordWasSuppressed');+ expect(helperBody).toContain('onPackagePlaced: () => {');+ expect(helperBody).toContain('packagePlaced = true;');+ expect(helperBody).toContain('if (!packagePlaced) {\n restoreMarketRecord();');+ expect(updateBody).toContain('releaseMutation();');+ expect(helperBody).not.toContain('GHOST_SOURCE_CONFLICT');});it('runs the final market callback before both initial install and update placement', () => {@@ -166,16 +174,22 @@ describe('market Ghost session boundary', () => {it('releases the mutation lease for shutdown failures and restores only after confirmed shutdown', () => {const updateStart = source.indexOf("ipcMain.handle('ghosts:update'");const updateEnd = source.indexOf("ipcMain.handle('ghosts:pick-file'", updateStart);- const body = source.slice(updateStart, updateEnd);+ const updateBody = source.slice(updateStart, updateEnd);+ const helperStart = source.indexOf('async function updateLocalGhostPackageLocked(');+ const helperEnd = source.indexOf(+ '\n}\n\n/**\n * Forge 的显式安装入口。',+ helperStart,+ );+ const helperBody = source.slice(helperStart, helperEnd);- const waitIndex = body.indexOf(+ const waitIndex = helperBody.indexOf('await getGhostNodeRuntimeBroker().stopAndWait(inspected.manifest.id);',);- const oauthLockIndex = body.indexOf(+ const oauthLockIndex = helperBody.indexOf('result = await withActiveOwnerGhostOauthMutationLock(inspected.manifest.id',);- const updateIndex = body.indexOf('manager.update(lizFilePath');- const restoreIndex = body.indexOf(+ const updateIndex = helperBody.indexOf('manager.update(cindyFilePath');+ const restoreIndex = helperBody.indexOf('if (previousGhost) spawnIfResident(previousGhost);',);@@ -188,13 +202,9 @@ describe('market Ghost session boundary', () => {// spawnIfResident is in the market-provenance catch block, after// stopAndWait (rollback if provenance check fails).expect(restoreIndex).toBeGreaterThan(waitIndex);- expect(body).toContain('finally {\n releaseMutation();');- const leaseReleaseIndex = body.indexOf('finally {\n releaseMutation();');- const stagingReleaseIndex = body.indexOf('releaseForgePackStaging(');- expect(leaseReleaseIndex).toBeGreaterThan(-1);- expect(stagingReleaseIndex).toBeGreaterThan(leaseReleaseIndex);- expect(body).toContain("throwIpcError('INTERNAL', 'Unable to verify the installed Plugin source');");- expect(body).toContain("throwIpcError('INTERNAL', 'Unable to detach the installed Plugin source');");+ expect(updateBody).toContain('finally {\n releaseMutation();');+ expect(helperBody).toContain("throwIpcError('INTERNAL', 'Unable to verify the installed Plugin source');");+ expect(helperBody).toContain("throwIpcError('INTERNAL', 'Unable to detach the installed Plugin source');");});it('Ghost 媒体在途守卫只依赖当前进程的 AppSession owner 边界', () => {diff --git a/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.connection.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.connection.test.tsindex f7bd5e29d4..3c07f9e410 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.connection.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.connection.test.ts@@ -38,7 +38,6 @@ function ghost(version: '1.0.0',kind: 'chip',entry: 'main.js',- slots: ['tool', 'network'],tools: [{ name: 'whoami_a', description: 'Show identity' }],network,},diff --git a/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.file.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.file.test.tsindex ba63d8170f..bb490a88e1 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.file.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.file.test.ts@@ -21,7 +21,6 @@ function fileGhost(): InstalledGhost {version: '1.0.0',kind: 'chip',entry: 'main.js',- slots: ['tool', 'network'],tools: [{ name: 't', description: 'x' }],network,},diff --git a/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.oauth.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.oauth.test.tsindex d99298dc6a..bfaac1e86c 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.oauth.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.oauth.test.ts@@ -35,7 +35,6 @@ function oauthGhost(): InstalledGhost {version: '1.0.0',kind: 'chip',entry: 'main.js',- slots: ['tool', 'network'],tools: [{ name: 't', description: 'x' }],network,},diff --git a/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.test.tsindex 1cd6992e54..9e8f383b0f 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/networkSlot.test.ts@@ -23,7 +23,6 @@ function fakeGhost(overrides: {id?: string;enabled?: boolean;- slots?: string[];trust?: InstalledGhost['trust'];/** null = 有槽无详单(老包语义);undefined = 默认 brave+tavily 双域名。 */network?: GhostNetworkNeeds | null;@@ -52,7 +51,6 @@ function fakeGhost(version: '1.0.0',kind: 'chip',entry: 'main.js',- slots: overrides.slots ?? ['tool', 'network'],tools: [{ name: 'search_web', description: '搜索' }],...(overrides.network === null ? {} : { network: overrides.network ?? defaultNetwork }),},@@ -182,24 +180,64 @@ describe('networkSlot · 载荷与 URL 校验', () => {});});-describe('networkSlot · 资格审(槽 + 详单双闸)', () => {- it('意识不存在/停用/未声明 network 槽/有槽无详单一律拒', async () => {+describe('networkSlot · 能力资格审', () => {+ it('意识不存在/停用/未声明 network.hosts 一律拒', async () => {const gone = makeSlot({ getGhost: () => null });expect((await gone.slot.handleFetchRequest('web-search', { url: BRAVE_URL })).ok).toBe(false);const disabled = makeSlot({ getGhost: () => fakeGhost({ enabled: false }) });expect((await disabled.slot.handleFetchRequest('web-search', { url: BRAVE_URL })).ok).toBe(false);- const noSlot = makeSlot({ getGhost: () => fakeGhost({ slots: ['tool'], network: null }) });+ const noSlot = makeSlot({ getGhost: () => fakeGhost({ network: null }) });const r1 = await noSlot.slot.handleFetchRequest('web-search', { url: BRAVE_URL });expect(r1.ok).toBe(false);- if (!r1.ok) expect(r1.message).toContain('network 卡槽');+ if (!r1.ok) expect(r1.message).toContain('network.hosts');const noNeeds = makeSlot({ getGhost: () => fakeGhost({ network: null }) });const r2 = await noNeeds.slot.handleFetchRequest('web-search', { url: BRAVE_URL });expect(r2.ok).toBe(false);if (!r2.ok) expect(r2.message).toContain('network.hosts');});++ it('Agent 在途调用可访问未预声明域名,同一 callId 不属于本插件则拒绝', async () => {+ const allowed = makeSlot({+ getGhost: () => fakeGhost({ network: null }),+ inFlightCallInfo: (callId) =>+ callId === 'call-agent'+ ? { ghostId: 'web-search', sessionId: 'session-1', channel: 'session' }+ : null,+ });+ expect(+ await allowed.slot.handleFetchRequest('web-search', {+ url: 'https://example.com/data',+ callId: 'call-agent',+ }),+ ).toMatchObject({ ok: true });++ const wrongOwner = makeSlot({+ getGhost: () => fakeGhost({ network: null }),+ inFlightCallInfo: () => ({ ghostId: 'another-plugin', sessionId: 'session-1', channel: 'session' }),+ });+ expect(+ await wrongOwner.slot.handleFetchRequest('web-search', {+ url: 'https://example.com/data',+ callId: 'call-agent',+ }),+ ).toMatchObject({ ok: false });+ });++ it('脚本/后台通道不能冒充 Agent 授权访问未声明域名', async () => {+ const { slot } = makeSlot({+ getGhost: () => fakeGhost({ network: null }),+ inFlightCallInfo: () => ({ ghostId: 'web-search', sessionId: null, channel: 'script' }),+ });+ expect(+ await slot.handleFetchRequest('web-search', {+ url: 'https://example.com/data',+ callId: 'call-script',+ }),+ ).toMatchObject({ ok: false });+ });});describe('networkSlot · headers 消毒与凭证注入', () => {diff --git a/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.tsindex 5ae07915be..a92ae310e4 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.ts@@ -73,7 +73,6 @@ function fakeGhost(version: '1.0.0',kind: 'chip',entry: 'main.js',- slots: ['node'],node: {entry: 'node/worker.cjs',protocol: options.protocol ?? 'json-rpc-stdio',@@ -898,7 +897,7 @@ describe('nodeRuntimeBroker · 意外死亡诊断(2026-07-26)', () => {describe('nodeRuntimeBroker · 权限与协议', () => {it('没声明 node 槽时拒绝且不启动进程', async () => {const ghost = fakeGhost();- ghost.manifest.slots = ['card'];+ delete ghost.manifest.node;const spawnProcess = vi.fn();const broker = new GhostNodeRuntimeBroker({ getGhost: () => ghost, spawnProcess });diff --git a/apps/desktop/src/main/cindy-brain/__tests__/notifySlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/notifySlot.test.tsindex e53bcd6ae1..85326c4b29 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/notifySlot.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/notifySlot.test.ts@@ -1,7 +1,7 @@/*** notifySlot.test.ts — 系统提示槽单测(纯 DI,无 Electron)。- * 覆盖:happy path(广播带主机填的身份三件套)、卡槽资格审(未声明 notify- * 槽即拒)、沉睡拒、载荷校验(text 形状/空/超长、tone 白名单)、净化+ * 覆盖:happy path(广播带主机填的身份三件套)、能力资格审(未声明 notify+ * 即拒)、沉睡拒、载荷校验(text 形状/空/超长、tone 白名单)、净化* (控制字符剥除、\r\n 归一)、每意识限速(注入时钟直测)。*/@@ -12,7 +12,7 @@ import { GHOST_NOTIFY_MIN_INTERVAL_MS } from '../../../shared/ghost';import type { InstalledGhost } from '../../../shared/ghost';function fakeGhost(- overrides: { enabled?: boolean; slots?: string[]; iconDataUrl?: string } = {},+ overrides: { enabled?: boolean; notify?: boolean; iconDataUrl?: string } = {},): InstalledGhost {return {manifest: {@@ -22,7 +22,7 @@ function fakeGhost(version: '1.0.0',kind: 'chip',entry: 'main.js',- slots: overrides.slots ?? ['tool', 'notify'],+ ...(overrides.notify === false ? {} : { notify: true }),},dir: '/fake/brain/weather',enabled: overrides.enabled ?? true,@@ -63,8 +63,8 @@ describe('GhostNotifySlot', () => {expect(broadcast).toHaveBeenCalledWith({ ghostId: 'weather', name: '天气', text: 'hi', tone: 'info' });});- it('未声明 notify 槽即拒(slots 是白名单)', () => {- const { slot, broadcast } = makeSlot(fakeGhost({ slots: ['tool'] }));+ it('未声明 notify 能力即拒', () => {+ const { slot, broadcast } = makeSlot(fakeGhost({ notify: false }));const r = slot.handleNotify('weather', { type: 'notify', text: 'hi' });expect(r.ok).toBe(false);expect(broadcast).not.toHaveBeenCalled();diff --git a/apps/desktop/src/main/cindy-brain/__tests__/openFileInstall.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/openFileInstall.test.tsdeleted file mode 100644index 6a3b4c0e72..0000000000--- a/apps/desktop/src/main/cindy-brain/__tests__/openFileInstall.test.ts+++ /dev/null@@ -1,99 +0,0 @@-/**- * openFileInstall.test.ts —— 待装转交缓冲的不变量。- *- * 钉住的核心不变量:**装入来源(origin)与待装路径同存同取。**- *- * 为什么值得一条专门的测试:来源决定确认框是否展示「这次是 Agent 发起的」红色- * 横幅并加重确认,是一条安全事实。第一版实现把它只挂在 `ghosts:install-requested`- * 广播 payload 上,而广播是易失通道——macOS 关窗后应用不退出,scheduler 拉起的- * agent 仍能调 `ghost_forge_pack`,此刻 `getAllWindows()` 为空、广播无人接收,- * 但路径仍留在缓冲里等 renderer 挂载后自取。那一取就把 origin 丢了,- * Agent 发起的装入被显示成手动。**丢失方向恰好是最危险的那个**,所以这里用- * 「零窗口」这个具体场景把两者的绑定钉死。- */--import path from 'node:path';-import { fileURLToPath } from 'node:url';--import { describe, it, expect, vi, beforeEach } from 'vitest';--const windows: { isDestroyed: () => boolean; webContents: { send: (ch: string) => void } }[] = [];-const sent: string[] = [];--vi.mock('electron', () => ({- BrowserWindow: { getAllWindows: () => windows },-}));-vi.mock('../logger.js', () => ({- createLogger: () => ({ info: () => {}, warn: () => {}, error: () => {} }),-}));--const { handleIncomingCindyFile, takePendingCindyInstall } = await import('../openFileInstall');-const { MANUAL_GHOST_INSTALL_ORIGIN } = await import('../../../shared/ghostInstallOrigin');--const AGENT_ORIGIN = {- kind: 'agent-forge' as const,- sessionTitle: '处理外部文档',- sourceRelPath: 'plugins/evil',-};--/** 用本文件自身当"存在且可读的普通文件",避免造临时目录。 */-const REAL_FILE = fileURLToPath(import.meta.url);--beforeEach(() => {- windows.length = 0;- sent.length = 0;- takePendingCindyInstall(); // 清干净上一条用例可能留下的缓冲-});--function addWindow(): void {- windows.push({- isDestroyed: () => false,- webContents: { send: (ch: string) => sent.push(ch) },- });-}--describe('openFileInstall · origin 与路径同存同取', () => {- it('零窗口(macOS 关窗后 agent 转交):广播没人收,但 origin 仍能被取到', async () => {- await handleIncomingCindyFile(REAL_FILE, 'ghost-forge', AGENT_ORIGIN);- expect(sent).toEqual([]); // 没有窗口 → 广播确实丢了-- const pending = takePendingCindyInstall();- expect(pending?.filePath).toBe(REAL_FILE);- expect(pending?.origin).toEqual(AGENT_ORIGIN); // ← 丢广播不等于丢来源- });-- it('有窗口:广播只是通知,不携带任何事实', async () => {- addWindow();- await handleIncomingCindyFile(REAL_FILE, 'ghost-forge', AGENT_ORIGIN);- // send 只带 channel,没有第二个参数——事实的唯一来源是缓冲。- expect(sent).toEqual(['ghosts:install-requested']);- expect(takePendingCindyInstall()?.origin).toEqual(AGENT_ORIGIN);- });-- it('手动入口(双击 / open-file)不传 origin 时缺省 manual', async () => {- await handleIncomingCindyFile(REAL_FILE, 'open-file');- expect(takePendingCindyInstall()?.origin).toEqual(MANUAL_GHOST_INSTALL_ORIGIN);- });-- it('取即清空:同一条待装项不会被消费两次', async () => {- await handleIncomingCindyFile(REAL_FILE, 'ghost-forge', AGENT_ORIGIN);- expect(takePendingCindyInstall()).not.toBeNull();- expect(takePendingCindyInstall()).toBeNull();- });-- it('只保留最新一条,且换条时来源随之更新(不会残留上一条的 agent 来源)', async () => {- await handleIncomingCindyFile(REAL_FILE, 'ghost-forge', AGENT_ORIGIN);- await handleIncomingCindyFile(REAL_FILE, 'open-file');- expect(takePendingCindyInstall()?.origin).toEqual(MANUAL_GHOST_INSTALL_ORIGIN);- });-- it('路径不存在:不写缓冲、不广播(容错口径与 open-folder 一致)', async () => {- addWindow();- await handleIncomingCindyFile(- path.join(path.dirname(REAL_FILE), 'definitely-not-here.cindy'),- 'open-file',- );- expect(sent).toEqual([]);- expect(takePendingCindyInstall()).toBeNull();- });-});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/packagePermissionReview.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/packagePermissionReview.test.tsdeleted file mode 100644index d3a40b9adf..0000000000--- a/apps/desktop/src/main/cindy-brain/__tests__/packagePermissionReview.test.ts+++ /dev/null@@ -1,314 +0,0 @@-import { describe, expect, it } from 'vitest';--import type { GhostManifest } from '../../../shared/ghost';-import {- marketPackageHostReviewDiff,- marketPackageManualSummaryChanged,- marketPackageNeedsHostReview,- marketPackageOauthIdentityChanged,-} from '../packagePermissionReview';--describe('marketPackageNeedsHostReview', () => {- it('skips Host when the user already reviewed every permission in the real package', () => {- expect(- marketPackageNeedsHostReview({- mode: 'manual',- builtinOauthClientChanged: false,- addedCount: null,- unreviewedCount: 0,- extrasVersusReviewedCount: 0,- }),- ).toBe(false);- });-- it('reviews Host when the real package adds permissions the preview missed', () => {- expect(- marketPackageNeedsHostReview({- mode: 'manual',- builtinOauthClientChanged: false,- addedCount: null,- unreviewedCount: 0,- extrasVersusReviewedCount: 1,- }),- ).toBe(true);- });-- it('reviews a first manual install when no preview confirmation was supplied', () => {- expect(- marketPackageNeedsHostReview({- mode: 'manual',- builtinOauthClientChanged: false,- addedCount: null,- unreviewedCount: 0,- extrasVersusReviewedCount: null,- }),- ).toBe(true);- });-- it('skips a same-permission manual update when no preview confirmation was supplied', () => {- expect(- marketPackageNeedsHostReview({- mode: 'manual',- builtinOauthClientChanged: false,- addedCount: 0,- unreviewedCount: 0,- extrasVersusReviewedCount: null,- }),- ).toBe(false);- });-- it('always reviews when the built-in OAuth client changed', () => {- expect(- marketPackageNeedsHostReview({- mode: 'manual',- builtinOauthClientChanged: true,- addedCount: 0,- unreviewedCount: 0,- extrasVersusReviewedCount: 0,- }),- ).toBe(true);- });-- it('reviews when only the bundled manual summary changed', () => {- expect(- marketPackageNeedsHostReview({- mode: 'manual',- builtinOauthClientChanged: false,- manualSummaryChanged: true,- addedCount: 0,- unreviewedCount: 0,- extrasVersusReviewedCount: 0,- }),- ).toBe(true);- });-});--function oauthManifest(clientId: string): GhostManifest {- return {- schemaVersion: 2,- id: 'oauth-plugin',- name: 'OAuth Plugin',- version: '1.0.0',- kind: 'chip',- entry: 'main.js',- slots: ['network'],- network: {- hosts: ['api.example.com'],- secrets: [- {- key: 'account',- label: 'Account',- source: 'oauth',- inject: { header: 'Authorization', format: 'Bearer {value}' },- oauth: {- authorizeUrl: 'https://accounts.example.com/authorize',- tokenUrl: 'https://accounts.example.com/token',- clientId,- },- },- ],- },- };-}--describe('marketPackageOauthIdentityChanged', () => {- it('detects a clientId mismatch between the reviewed catalog and the real package', () => {- expect(- marketPackageOauthIdentityChanged(- oauthManifest('preview-client'),- oauthManifest('real-client'),- oauthManifest('real-client'),- ),- ).toBe(true);- });-- it('detects a clientId mismatch between the installed baseline and the real package', () => {- expect(- marketPackageOauthIdentityChanged(- oauthManifest('old-client'),- oauthManifest('old-client'),- oauthManifest('new-client'),- ),- ).toBe(true);- });-- it('stays quiet when reviewed, installed, and real package share the same client', () => {- expect(- marketPackageOauthIdentityChanged(- oauthManifest('same-client'),- oauthManifest('same-client'),- oauthManifest('same-client'),- ),- ).toBe(false);- });-- it('reviews when the catalog omitted clientId but the real package introduces one', () => {- expect(- marketPackageOauthIdentityChanged(- oauthManifest(''),- oauthManifest('real-client'),- oauthManifest('real-client'),- ),- ).toBe(true);- expect(- marketPackageOauthIdentityChanged(oauthManifest(''), null, oauthManifest('real-client')),- ).toBe(true);- });-- it('does not treat an installed empty clientId gaining a default as a migration', () => {- expect(- marketPackageOauthIdentityChanged(- oauthManifest('real-client'),- oauthManifest(''),- oauthManifest('real-client'),- ),- ).toBe(false);- });-- it('reviews when a reviewed tokenBroker slot becomes a direct clientId', () => {- expect(- marketPackageOauthIdentityChanged(- oauthBrokerManifest(),- oauthBrokerManifest(),- oauthManifest('direct-client'),- ),- ).toBe(true);- expect(- marketPackageOauthIdentityChanged(oauthBrokerManifest(), null, oauthManifest('direct-client')),- ).toBe(true);- });-- it('reviews when a reviewed direct clientId becomes a tokenBroker', () => {- expect(- marketPackageOauthIdentityChanged(- oauthManifest('direct-client'),- oauthManifest('direct-client'),- oauthBrokerManifest(),- ),- ).toBe(true);- });-});--function oauthBrokerManifest(): GhostManifest {- const manifest = oauthManifest('broker-client');- const secret = manifest.network?.secrets?.[0];- if (secret?.oauth) {- secret.oauth.tokenBroker = 'cindy';- }- return manifest;-}--function manualManifest(items: Array<{ name: string; dir: string; description: string }>): GhostManifest {- return {- schemaVersion: 2,- id: 'manual-plugin',- name: 'Manual Plugin',- version: '1.0.0',- kind: 'chip',- entry: 'main.js',- slots: ['notify'],- ...(items.length > 0 ? { manual: { items } } : {}),- };-}--describe('marketPackageManualSummaryChanged', () => {- const guide = {- name: 'getting-started',- dir: 'manual/getting-started',- description: 'Start here',- };-- it('stays quiet when reviewed and real package share the same manuals', () => {- expect(marketPackageManualSummaryChanged(manualManifest([guide]), manualManifest([guide]))).toBe(- false,- );- });-- it('detects a count change between the reviewed catalog and the real package', () => {- expect(marketPackageManualSummaryChanged(manualManifest([]), manualManifest([guide]))).toBe(- true,- );- });-- it('detects a swapped manual identity even when the count stays the same', () => {- expect(- marketPackageManualSummaryChanged(- manualManifest([guide]),- manualManifest([- { name: 'ops', dir: 'manual/ops', description: 'Operations' },- ]),- ),- ).toBe(true);- });-- it('does not invent a reviewed baseline when the caller omitted the catalog', () => {- expect(marketPackageManualSummaryChanged(undefined, manualManifest([guide]))).toBe(false);- });-- it('does not treat a newline inside one description as two manuals', () => {- expect(- marketPackageManualSummaryChanged(- manualManifest([- { name: 'a', dir: 'x', description: 'd\nb\0y\0e' },- ]),- manualManifest([- { name: 'a', dir: 'x', description: 'd' },- { name: 'b', dir: 'y', description: 'e' },- ]),- ),- ).toBe(true);- });-});--const emptyDiff = {- added: [],- removed: [],- unchanged: [],- builtinOauthClientChanged: false,-};--describe('marketPackageHostReviewDiff', () => {- it('does not synthesize an empty update diff on first install', () => {- expect(- marketPackageHostReviewDiff({- permissionDiff: null,- extrasVersusReviewedCount: 1,- builtinOauthClientChanged: true,- manualSummaryChanged: false,- }),- ).toBeNull();- });-- it('uses the full package card when extras exist even if the installed diff is empty', () => {- expect(- marketPackageHostReviewDiff({- permissionDiff: emptyDiff,- extrasVersusReviewedCount: 2,- builtinOauthClientChanged: false,- manualSummaryChanged: false,- }),- ).toBeNull();- });-- it('uses the full package card when only the manual summary changed', () => {- expect(- marketPackageHostReviewDiff({- permissionDiff: emptyDiff,- extrasVersusReviewedCount: 0,- builtinOauthClientChanged: false,- manualSummaryChanged: true,- }),- ).toBeNull();- });-- it('keeps an update diff when only the OAuth identity changed', () => {- expect(- marketPackageHostReviewDiff({- permissionDiff: emptyDiff,- extrasVersusReviewedCount: 0,- builtinOauthClientChanged: true,- manualSummaryChanged: false,- }),- ).toEqual({ ...emptyDiff, builtinOauthClientChanged: true });- });-});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/pickSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/pickSlot.test.tsindex ef85ad22c5..5e0084e394 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/pickSlot.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/pickSlot.test.ts@@ -5,7 +5,7 @@ import { describe, expect, it, vi } from 'vitest';import type { InstalledGhost } from '../../../shared/ghost';import { GhostPickSlot, type PickSlotDeps } from '../pickSlot';-function pickGhost(options: { slots?: string[]; enabled?: boolean } = {}): InstalledGhost {+function pickGhost(options: { pick?: boolean; node?: boolean; enabled?: boolean } = {}): InstalledGhost {return {manifest: {schemaVersion: 2,@@ -14,8 +14,8 @@ function pickGhost(options: { slots?: string[]; enabled?: boolean } = {}): Instaversion: '1.0.0',kind: 'chip',entry: 'main.js',- slots: options.slots ?? ['pick', 'node'],- ...(options.slots?.includes('node') ?? true+ ...(options.pick === false ? {} : { pick: true }),+ ...(options.node !== false? { node: { entry: 'node/worker.cjs', protocol: 'json-rpc-stdio' } }: {}),},@@ -40,8 +40,8 @@ function makeSlot(overrides: Partial<PickSlotDeps> = {}) {}describe('pickSlot · 资格审与载荷校验', () => {- it('未声明 pick 槽 / 未启用 一律 PERMISSION_DENIED', async () => {- const noSlot = makeSlot({ getGhost: () => pickGhost({ slots: ['node'] }) });+ it('未声明 pick 能力 / 未启用 一律 PERMISSION_DENIED', async () => {+ const noSlot = makeSlot({ getGhost: () => pickGhost({ pick: false }) });expect(await noSlot.slot.handleRequest('pick-ghost', { mode: 'directory' })).toMatchObject({ok: false,errorCode: 'PERMISSION_DENIED',@@ -68,8 +68,8 @@ describe('pickSlot · 资格审与载荷校验', () => {).toMatchObject({ ok: false, errorCode: 'INVALID_REQUEST' });});- it('未声明 node 槽的插件必须 deposit:true,否则选完什么都拿不到 = 拒单', async () => {- const { slot } = makeSlot({ getGhost: () => pickGhost({ slots: ['pick'] }) });+ it('未声明 node 能力的插件必须 deposit:true,否则选完什么都拿不到 = 拒单', async () => {+ const { slot } = makeSlot({ getGhost: () => pickGhost({ node: false }) });expect(await slot.handleRequest('pick-ghost', { mode: 'directory' })).toMatchObject({ok: false,errorCode: 'INVALID_REQUEST',@@ -103,7 +103,7 @@ describe('pickSlot · 授权 = 用户亲选', () => {expect(nodeOnly).toMatchObject({ ok: true, path: '/Users/me/projects' });expect((nodeOnly as { dir_deposit?: unknown }).dir_deposit).toBeUndefined();- const depositOnly = makeSlot({ getGhost: () => pickGhost({ slots: ['pick'] }) });+ const depositOnly = makeSlot({ getGhost: () => pickGhost({ node: false }) });const r = await depositOnly.slot.handleRequest('pick-ghost', {mode: 'directory',deposit: true,diff --git a/apps/desktop/src/main/cindy-brain/__tests__/pipeDispatcher.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/pipeDispatcher.test.tsindex 8ffaca156d..962570041e 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/pipeDispatcher.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/pipeDispatcher.test.ts@@ -19,7 +19,6 @@ function fakeGhost(overrides: Partial<InstalledGhost> = {}): InstalledGhost {version: '1.0.0',kind: 'chip',entry: 'main.js',- slots: ['tool', 'model', 'panel'],tools: [{ name: 'gen_image', description: '生成图片' }],},dir: '/fake/brain/art',diff --git a/apps/desktop/src/main/cindy-brain/__tests__/previewSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/previewSlot.test.tsindex cafc83d82e..ea3c14d07f 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/previewSlot.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/previewSlot.test.ts@@ -6,9 +6,8 @@ import type { InstalledGhost } from '../../../shared/ghost';import { GhostPreviewSlot, type PreviewSlotDeps } from '../previewSlot';function previewGhost(- options: { hosts?: string[]; slots?: string[]; enabled?: boolean } = {},+ options: { hosts?: string[]; preview?: boolean; enabled?: boolean } = {},): InstalledGhost {- const slots = options.slots ?? ['preview'];return {manifest: {schemaVersion: 2,@@ -17,8 +16,7 @@ function previewGhost(version: '1.0.0',kind: 'chip',entry: 'main.js',- slots,- ...(slots.includes('preview')+ ...(options.preview !== false? { preview: { hosts: options.hosts ?? ['*.example.dev', 'localhost'] } }: {}),},@@ -45,8 +43,8 @@ function makeSlot(overrides: Partial<PreviewSlotDeps> = {}) {}describe('previewSlot · 资格审与 URL 守门', () => {- it('未声明 preview 槽 / 未启用 一律 PERMISSION_DENIED', () => {- const noSlot = makeSlot({ getGhost: () => previewGhost({ slots: ['panel'] }) });+ it('未声明 preview 能力 / 未启用 一律 PERMISSION_DENIED', () => {+ const noSlot = makeSlot({ getGhost: () => previewGhost({ preview: false }) });expect(noSlot.slot.handleRequest('preview-ghost', { url: 'https://a.example.dev/' }),).toMatchObject({ ok: false, errorCode: 'PERMISSION_DENIED' });diff --git a/apps/desktop/src/main/cindy-brain/__tests__/scheduleSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/scheduleSlot.test.tsindex 4ddf7f4fb0..a5fe550edd 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/scheduleSlot.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/scheduleSlot.test.ts@@ -18,13 +18,12 @@ import { GhostScheduleSlot, isMainShellWindowUrl, type ScheduleSlotDeps } from 'function scheduleGhost(options: {- slots?: string[];+ agent?: boolean;schedule?: boolean;enabled?: boolean;background?: boolean;} = {},): InstalledGhost {- const slots = options.slots ?? ['agent', 'tool'];const agentNeeds = {...(options.background === true ? { background: true } : {}),...(options.schedule !== false ? { schedule: true } : {}),@@ -37,8 +36,7 @@ function scheduleGhost(version: '1.0.0',kind: 'chip',entry: 'main.js',- slots,- ...(Object.keys(agentNeeds).length > 0 ? { agent: agentNeeds } : {}),+ ...(options.agent === false ? {} : { agent: agentNeeds }),},dir: '/fake/sched-ghost',enabled: options.enabled ?? true,@@ -70,7 +68,7 @@ const validReq = {};describe('GhostScheduleSlot 资格审', () => {- it('声明了 agent 槽 + schedule:true 才放行', () => {+ it('声明了 agent.schedule:true 才放行', () => {const { slot, pushes } = makeSlot();expect(slot.handleRequest('sched-ghost', validReq)).toEqual({ ok: true });expect(pushes).toHaveLength(1);@@ -92,7 +90,7 @@ describe('GhostScheduleSlot 资格审', () => {});});- it('有 agent 槽但没有 schedule 加档 → PERMISSION_DENIED(仅 background 不够)', () => {+ it('有 agent 能力但没有 schedule 加档 → PERMISSION_DENIED(仅 background 不够)', () => {const { slot } = makeSlot({getGhost: () => scheduleGhost({ schedule: false, background: true }),});@@ -102,8 +100,8 @@ describe('GhostScheduleSlot 资格审', () => {});});- it('写了 schedule 但 slots 没有 agent → PERMISSION_DENIED', () => {- const { slot } = makeSlot({ getGhost: () => scheduleGhost({ slots: ['tool'] }) });+ it('未声明 agent 能力 → PERMISSION_DENIED', () => {+ const { slot } = makeSlot({ getGhost: () => scheduleGhost({ agent: false }) });expect(slot.handleRequest('sched-ghost', validReq)).toMatchObject({ok: false,errorCode: 'PERMISSION_DENIED',diff --git a/apps/desktop/src/main/cindy-brain/__tests__/skillSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/skillSlot.test.tsindex a262ab701c..5f755786c0 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/skillSlot.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/skillSlot.test.ts@@ -70,7 +70,6 @@ function ghost(version: '1.0.0',kind: 'chip',entry: 'main.js',- slots: ['skill'],skill: {items: skills.map((s) => ({ ...s, description: s.description ?? '说明' })),},@@ -662,13 +661,13 @@ describe('skillSlot · 全链路(打包 → 装入 → 对账 → 双端可见)'await write('ghost.json',JSON.stringify({- schemaVersion: 2,+ schemaVersion: 3,+ minCindyVersion: '0.1.61',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: '演示技能' }] },}),diff --git a/apps/desktop/src/main/cindy-brain/__tests__/subscriptionGateway.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/subscriptionGateway.test.tsindex d3fab2010b..3cd9d698ca 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/subscriptionGateway.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/subscriptionGateway.test.ts@@ -265,7 +265,6 @@ function ghost(version: '1.0.0',kind: 'chip',entry: 'main.js',- slots: ['subscribe'],...(subscribe ? { subscribe } : {}),},dir: `/fake/${id}`,diff --git a/apps/desktop/src/main/cindy-brain/__tests__/workspaceSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/workspaceSlot.test.tsindex bb4da7bab9..02c52c6cea 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/workspaceSlot.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/workspaceSlot.test.ts@@ -9,7 +9,7 @@ import {type WorkspaceSlotDeps,} from '../workspaceSlot';-function workspaceGhost(options: { slots?: string[]; enabled?: boolean } = {}): InstalledGhost {+function workspaceGhost(options: { workspace?: boolean; enabled?: boolean } = {}): InstalledGhost {return {manifest: {schemaVersion: 2,@@ -18,7 +18,7 @@ function workspaceGhost(options: { slots?: string[]; enabled?: boolean } = {}):version: '1.0.0',kind: 'chip',entry: 'main.js',- slots: options.slots ?? ['workspace'],+ ...(options.workspace === false ? {} : { workspace: true }),},dir: '/fake/ws-ghost',enabled: options.enabled ?? true,@@ -67,8 +67,8 @@ const DIR_REQ = {} as const;describe('workspaceSlot · 资格审与载荷校验', () => {- it('未声明 workspace 槽 / 未启用 一律 PERMISSION_DENIED', async () => {- const noSlot = makeSlot({ getGhost: () => workspaceGhost({ slots: ['pick'] }) });+ it('未声明 workspace 能力 / 未启用 一律 PERMISSION_DENIED', async () => {+ const noSlot = makeSlot({ getGhost: () => workspaceGhost({ workspace: false }) });expect(await noSlot.slot.handleRequest('ws-ghost', PICK_REQ)).toMatchObject({ok: false,errorCode: 'PERMISSION_DENIED',diff --git a/apps/desktop/src/main/cindy-brain/agentSlot.ts b/apps/desktop/src/main/cindy-brain/agentSlot.tsindex 1d3d5d9011..2195e4005b 100644--- a/apps/desktop/src/main/cindy-brain/agentSlot.ts+++ b/apps/desktop/src/main/cindy-brain/agentSlot.ts@@ -130,7 +130,7 @@ export class GhostAgentSlot {issueUserActionToken(ghostId: string, sessionId: string | null): string | null {if (!sessionId) return null;const ghost = this.deps.getGhost(ghostId);- if (!ghost?.enabled || !ghost.manifest.slots.includes('agent')) return null;+ if (!ghost?.enabled || !ghost.manifest.agent) return null;this.sweepExpiredGrants();while (this.grants.size >= MAX_LIVE_TOKENS) {@@ -169,7 +169,7 @@ export class GhostAgentSlot {/** 处理电子脑的 agent-request;所有失败都折叠成结构化返回。 */async handleRequest(ghostId: string, payload: unknown): Promise<GhostPipeAgentResult> {const ghost = this.deps.getGhost(ghostId);- if (!ghost?.enabled || !ghost.manifest.slots.includes('agent')) {+ if (!ghost?.enabled || !ghost.manifest.agent) {return {ok: false,errorCode: 'PERMISSION_DENIED',diff --git a/apps/desktop/src/main/cindy-brain/badgeSlot.ts b/apps/desktop/src/main/cindy-brain/badgeSlot.tsindex 1ae228d474..9089019009 100644--- a/apps/desktop/src/main/cindy-brain/badgeSlot.ts+++ b/apps/desktop/src/main/cindy-brain/badgeSlot.ts@@ -7,7 +7,8 @@* - 资格审只看 `badge` 卡槽——它与 `notify` 卡槽**并列**,不要求也不捆绑* notify(绿点比 toast 克制,只想点绿点的意识不该被迫连"能弹全屏顶部提示"* 一起申请)。装入时 validateGhostManifest 已强制 badge 必须同时声明 panel,- * 这里不重复判;`slots` 是硬白名单,老包不可能带这个槽,天然拒绝;+ * 这里不重复判;`badge` 引入前的旧版校验会拒绝未知 slot,所以更早安装的+ * 老包不可能带这个槽;当前运行时仍以 Manifest 声明作为强制边界;* - 意识只供**纯文本** summary:与 notify 共用 sanitizeGhostNoticeText 剥控制* 字符,换行坍缩成空格(摘要占卡片一行,换行没有正当用途),超限拒收——* 不静默截断,作者需要知道自己超了;@@ -72,10 +73,10 @@ export class GhostBadgeSlot {if (!ghost || !ghost.enabled) {return { ok: false, message: '意识不在可用状态' };}- if (!ghost.manifest.slots?.includes('badge')) {+ if (ghost.manifest.badge !== true) {return {ok: false,- message: '本意识未声明 badge 卡槽,无权点亮未读角标(需在 ghost.json 的 slots 里加 "badge" 并重新装入)',+ message: '本意识未声明 badge 能力,无权点亮未读角标(需在 ghost.json 中声明 "badge": true 并重新装入)',};}diff --git a/apps/desktop/src/main/cindy-brain/cardActionDispatch.ts b/apps/desktop/src/main/cindy-brain/cardActionDispatch.tsindex b408a92b02..bac969b3a4 100644--- a/apps/desktop/src/main/cindy-brain/cardActionDispatch.ts+++ b/apps/desktop/src/main/cindy-brain/cardActionDispatch.ts@@ -137,9 +137,9 @@ export class GhostCardActionDispatcher {this.deps.log?.warn('card-action rejected: ghost unavailable', { ghostId, callId });return { ok: false, reason: 'ghost-unavailable' };}- if (!ghost.manifest.slots?.includes('card')) {- // 卡片是它发的却没 card 槽 = 不该发生;保险起见拒。- this.deps.log?.warn('card-action rejected: no card slot', { ghostId, callId });+ if (!ghost.manifest.card) {+ // 卡片是它发的却没声明 card 能力 = 不该发生;保险起见拒。+ this.deps.log?.warn('card-action rejected: no card capability', { ghostId, callId });return { ok: false, reason: 'no-card-slot' };}diff --git a/apps/desktop/src/main/cindy-brain/cindySlot.ts b/apps/desktop/src/main/cindy-brain/cindySlot.tsindex 0556c202c6..e6926324b1 100644--- a/apps/desktop/src/main/cindy-brain/cindySlot.ts+++ b/apps/desktop/src/main/cindy-brain/cindySlot.ts@@ -816,8 +816,8 @@ export class GhostCindySlot {if (!ghost || !ghost.enabled) {return { ok: false, message: '意识不在可用状态' };}- if (!ghost.manifest.slots?.includes('cindy')) {- return { ok: false, message: '本意识未声明 cindy 卡槽,无权请 Cindy 代办' };+ if (!ghost.manifest.cindy) {+ return { ok: false, message: '本意识未声明 cindy 能力,无权请 Cindy 代办' };}// 能力粒度资格审:详单里没申请的动作点不了(缺详单 = 零能力,提示作者补声明)。const declaredActions: readonly string[] = ghost.manifest.cindy?.[info.category] ?? [];@@ -1277,8 +1277,8 @@ export class GhostCindySlot {if (!ghost || !ghost.enabled) {return { ok: false, message: '意识不在可用状态' };}- if (!ghost.manifest.slots?.includes('cindy')) {- return { ok: false, message: '本意识未声明 cindy 卡槽,无权请 Cindy 代办' };+ if (!ghost.manifest.cindy) {+ return { ok: false, message: '本意识未声明 cindy 能力,无权请 Cindy 代办' };}const declared: readonly string[] = ghost.manifest.cindy?.media ?? [];if (!declared.includes('deposit')) {@@ -1308,10 +1308,10 @@ export class GhostCindySlot {errorCode: 'PERMISSION_DENIED',};}- if (!ghost.manifest.slots?.includes('cindy')) {+ if (!ghost.manifest.cindy) {return {ok: false,- message: '本意识未声明 cindy 卡槽,无权请 Cindy 搜索',+ message: '本意识未声明 cindy 能力,无权请 Cindy 搜索',errorCode: 'PERMISSION_DENIED',};}@@ -1518,10 +1518,10 @@ export class GhostCindySlot {if (!ghost || !ghost.enabled) {return { ok: false, message: '意识不在可用状态', errorCode: 'PERMISSION_DENIED' };}- if (!ghost.manifest.slots?.includes('cindy')) {+ if (!ghost.manifest.cindy) {return {ok: false,- message: '本意识未声明 cindy 卡槽,无权请 Cindy 代办',+ message: '本意识未声明 cindy 能力,无权请 Cindy 代办',errorCode: 'PERMISSION_DENIED',};}@@ -1694,10 +1694,10 @@ export class GhostCindySlot {if (!ghost || !ghost.enabled) {return { ok: false, message: '意识不在可用状态', errorCode: 'PERMISSION_DENIED' };}- if (!ghost.manifest.slots?.includes('cindy')) {+ if (!ghost.manifest.cindy) {return {ok: false,- message: '本意识未声明 cindy 卡槽,无权请 Cindy 代办',+ message: '本意识未声明 cindy 能力,无权请 Cindy 代办',errorCode: 'PERMISSION_DENIED',};}@@ -2213,8 +2213,8 @@ export class GhostCindySlot {if (!ghost || !ghost.enabled) {return { ok: false, message: '意识不在可用状态' };}- if (!ghost.manifest.slots?.includes('cindy')) {- return { ok: false, message: '本意识未声明 cindy 卡槽,无权请 Cindy 代办' };+ if (!ghost.manifest.cindy) {+ return { ok: false, message: '本意识未声明 cindy 能力,无权请 Cindy 代办' };}if (typeof p.jobId !== 'string' || p.jobId.length === 0 || p.jobId.length > MAX_JOB_ID_LEN) {return { ok: false, message: 'jobId 不合法(mode:submit 受理时返回的任务号)' };diff --git a/apps/desktop/src/main/cindy-brain/confirmSlot.ts b/apps/desktop/src/main/cindy-brain/confirmSlot.tsindex 689ca338f4..6e7e7a3620 100644--- a/apps/desktop/src/main/cindy-brain/confirmSlot.ts+++ b/apps/desktop/src/main/cindy-brain/confirmSlot.ts@@ -102,8 +102,8 @@ export class GhostConfirmSlot {async handleRequest(ghostId: string, payload: unknown): Promise<GhostPipeConfirmResult> {const ghost = this.deps.getGhost(ghostId);- if (!ghost?.enabled || !ghost.manifest.slots.includes('confirm')) {- return fail('PERMISSION_DENIED', '插件未申请确认弹窗权限(confirm 槽),或当前未启用');+ if (!ghost?.enabled || ghost.manifest.confirm !== true) {+ return fail('PERMISSION_DENIED', '插件未申请确认弹窗权限(confirm),或当前未启用');}if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {return fail('INVALID_REQUEST', 'confirm-request 载荷必须是对象');diff --git a/apps/desktop/src/main/cindy-brain/connectionAudienceResolver.ts b/apps/desktop/src/main/cindy-brain/connectionAudienceResolver.tsindex 5ad8544154..993879af46 100644--- a/apps/desktop/src/main/cindy-brain/connectionAudienceResolver.ts+++ b/apps/desktop/src/main/cindy-brain/connectionAudienceResolver.ts@@ -7,7 +7,6 @@ import { isValidGhostId, isValidGhostNetworkHostPattern } from '../../shared/ghoimport type { GhostManifest } from '../../shared/ghost.js';import type { PluginMarketInstallationRecord } from '../plugin-market/ledger.js';import { PLUGIN_MEMBER_PUBLISHER_GHOST_ID } from '../plugin-publisher/types.js';-import { PLUGIN_PREFIX_PATTERN } from '@cindy/plugin-protocol';export interface ConnectionAudienceIdentity {membershipId: string;@@ -59,11 +58,6 @@ export interface LoadConnectionAudienceResolverOptions {readInstalledManifest(ghostId: string): GhostManifest | null;readInstalledManifestDigest(ghostId: string): string | null;readMarketInstallation(ghostId: string): PluginMarketInstallationRecord | null;- readApprovedPackageSha256?(ghostId: string): string | null;- readInstallOrigin?(ghostId: string): 'manual' | 'agent-forge';- lookupOrganizationPrefix?(- orgId: string,- ): { kind: 'known'; pluginPrefix: string | null } | { kind: 'absent' } | { kind: 'unavailable' };log?: {info: (msg: string, meta?: Record<string, unknown>) => void;warn: (msg: string, meta?: Record<string, unknown>) => void;@@ -119,39 +113,6 @@ export function loadConnectionAudienceResolver(};};- const readManifest = (): GhostManifest | null => {- try {- return options.readInstalledManifest(ghostId);- } catch {- return null;- }- };-- // Forge branch before market-record: a forge package has no ledger row.- // Personal identity / missing orgSlug already rejected above.- const forgeOrigin = options.readInstallOrigin?.(ghostId);- if (forgeOrigin === 'agent-forge') {- const prefixLookup = identity.orgId- ? options.lookupOrganizationPrefix?.(identity.orgId)- : undefined;- const prefix =- prefixLookup && prefixLookup.kind === 'known' ? prefixLookup.pluginPrefix : null;- if (- prefix &&- PLUGIN_PREFIX_PATTERN.test(prefix) &&- ghostId.startsWith(`${prefix}-`)- ) {- const approvedSha = options.readApprovedPackageSha256?.(ghostId) ?? null;- if (!approvedSha || !/^[a-f0-9]{64}$/.test(approvedSha)) {- return reject('forge-package-sha-missing');- }- const manifest = readManifest();- if (!manifest) return reject('plugin-not-installed');- if (manifest.id !== ghostId) return reject('plugin-id-mismatch');- return finish(manifest);- }- }-let installation: PluginMarketInstallationRecord | null = null;try {installation = options.readMarketInstallation(ghostId);diff --git a/apps/desktop/src/main/cindy-brain/errandSlot.ts b/apps/desktop/src/main/cindy-brain/errandSlot.tsindex b091c7d76d..0f08b88882 100644--- a/apps/desktop/src/main/cindy-brain/errandSlot.ts+++ b/apps/desktop/src/main/cindy-brain/errandSlot.ts@@ -5,7 +5,7 @@* 插件**专属 errand 会话**里的 agent 跑一轮,把最终回复文字取回给插件。** 安全边界(全部由本层与注入 runner 的主机代码强制,prompt 不构成边界):- * - 插件必须声明 `agent` 槽 + `agent.errand: true`(装入确认高风险单列);+ * - 插件必须声明 `agent` 槽 + `agent.errand: true`(插件详情高风险能力单列);* - 任务文本只进普通 user 消息,绝不进 system prompt;* - errand 会话的 agent/模型/权限档/工作目录由用户配置(runner 侧解析;* 权限档默认 plan 只读,协议层就没有 bypassPermissions)。唯一例外:@@ -201,7 +201,7 @@ export class GhostErrandSlot {async handleRequest(ghostId: string, payload: unknown): Promise<GhostPipeAgentErrandResult> {this.sweepJobs();const ghost = this.deps.getGhost(ghostId);- if (!ghost?.enabled || !ghost.manifest.slots.includes('agent') || ghost.manifest.agent?.errand !== true) {+ if (!ghost?.enabled || ghost.manifest.agent?.errand !== true) {return fail('PERMISSION_DENIED', '插件未申请「派活取件」权限(身份卡 agent.errand),或当前未启用');}if (!isPlainObject(payload) || payload.type !== 'agent-errand-request') {diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.tsindex 331ed7ad6a..fc1f4be01a 100644--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@ -7,11 +7,11 @@* - packGhostDir:源码目录 → 校验(与装入同一套 validateGhostManifest)→* 打包 .cindy 到源码目录自身(id-version.cindy,同名覆盖;shouldSkip 跳过* *.cindy 防套娃),并同时返回内存里的 `buf`。作者副本给人拿走;安装链路- * 必须用 `buf` 直写 Host staging,不能从源码目录回读。装入确认弹窗由- * 调用方(mcp-integrations 接线)经双击转交通道触发,本文件不碰 UI。+ * 必须用 `buf` 直写 Host staging,不能从源码目录回读。打包与发布编排由+ * 调用方(mcp-integrations 接线)处理,本文件不碰 UI。*- * 安全边界:agent 能写意识源码(它本来就有文件工具),但打包必须过校验、- * 装入必须过用户确认框(默认沉睡)——与手动拖 .cindy 完全同一条门。+ * 安全边界:agent 能写意识源码(它本来就有文件工具),但打包与装入都必须过+ * 同一套清单/真实包校验;安装动作本身不另设能力确认弹窗。*/import fs from 'node:fs';@@ -33,6 +33,7 @@ import {GHOST_MANUAL_ENTRY_FILE,GHOST_MANUAL_MD_MAX_BYTES,GHOST_MANIFEST_FILE,+ GHOST_MANIFEST_V3_MIN_CINDY_VERSION,GHOST_MANIFEST_SUMMARY_MAX_CHARS,GHOST_SKILL_MD_MAX_BYTES,validateGhostManifest,@@ -236,7 +237,8 @@ export type ForgeScaffoldWriter = (/** 生成插件清单;先走正式校验,再允许任何文件落盘。 */function scaffoldManifest(input: ForgeScaffoldInput): Record<string, unknown> {const common = {- schemaVersion: 2,+ schemaVersion: 3,+ minCindyVersion: GHOST_MANIFEST_V3_MIN_CINDY_VERSION,id: input.id,name: input.name,description: input.description?.trim() || `${input.name} 插件`,@@ -249,7 +251,8 @@ function scaffoldManifest(input: ForgeScaffoldInput): Record<string, unknown> {if (input.template === 'agent-action') {return {...common,- slots: ['tool', 'card', 'agent'],+ card: {},+ agent: {},tools: [{name: 'show_agent_actions',@@ -262,7 +265,6 @@ function scaffoldManifest(input: ForgeScaffoldInput): Record<string, unknown> {if (input.template === 'node-json-rpc') {return {...common,- slots: ['tool', 'node'],tools: [{name: 'node_echo',@@ -285,7 +287,6 @@ function scaffoldManifest(input: ForgeScaffoldInput): Record<string, unknown> {if (input.template === 'node-mcp') {return {...common,- slots: ['tool', 'node'],tools: [{name: 'echo_via_mcp',@@ -307,7 +308,6 @@ function scaffoldManifest(input: ForgeScaffoldInput): Record<string, unknown> {}return {...common,- slots: ['tool'],tools: [{name: 'hello',@@ -731,7 +731,7 @@ export async function scaffoldGhostDir(files: Object.keys(files).sort(),nextSteps: ['按需要修改 ghost.json、main.js 和 worker 源码。',- '调用 ghost_forge_pack 打包并让用户确认安装。',+ '调用 ghost_forge_pack 校验并生成 .cindy;打包本身不会安装插件。','Node 模板不允许在安装或首次运行时执行 npm install、npx 或 postinstall。',],};@@ -787,7 +787,7 @@ async function buildGhostPackage(// 1) 清单先行:与装入侧同一套校验,错在打包期就报清楚。// 读到的**原始字节**要留作不可变快照:后面生成 zip 时逐文件重新读盘,若// ghost.json 在"这里校验"与"写入 zip"之间被并发改写(保 id/version、加权限- // 声明),返回的 manifest 与包里那份就会分叉——安装侧拿返回值做审阅比对,+ // 声明),返回的 manifest 与包里那份就会分叉——安装侧校验的是旧清单,// 装进去的却是改过的包。快照写入让"校验的 = 返回的 = 包里的"三者恒等。// 与市场发现/安装层同一把闸(单句柄限量读,拒符号链接):打包输入目录是// 用户可写的活目录,按路径无界 readFile 会跟随链接读到目录外、或被超大@@ -887,7 +887,7 @@ async function buildGhostPackage(}}- // 3.5) skill 槽:SKILL.md frontmatter 与清单声明必须逐字一致。与装入侧+ // 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');@@ -1397,8 +1397,7 @@ export async function packGhostDir(/*** **作者期严格校验**(只在 packGhostDir 这条打包出口上跑,不进任何安装路径)。*- * 未读角标现在由 `badge` **卡槽**声明。槽名走硬白名单,写错直接被- * validateGhostManifest 拒掉,所以本身不需要额外把关。真正会静默失败的是另一种:+ * 未读角标由顶层 `badge: true` 声明。真正会静默失败的是另一种:* 作者(或 agent)照着**早期示例**写成顶层 `notify: { badge: ... }` —— 那个字段* 从来没被登记过,校验器一律忽略,于是包打出来了、装进去了、运行期每次发 badge* 都被拒,作者却以为自己声明过(codex review)。@@ -1415,7 +1414,7 @@ function firstGhostAuthoringIssue(raw: Record<string, unknown>): string | null {!Array.isArray(notifyRaw) &&'badge' in (notifyRaw as Record<string, unknown>)) {- return '未读角标已改为独立卡槽:请把 notify.badge 删掉,改成在 slots 里声明 "badge"(并同时声明 "panel")';+ return '未读角标已改为独立能力:请把 notify.badge 删掉,改成顶层 "badge": true(并同时声明 panel)';}return null;}@@ -1457,8 +1456,26 @@ export const FORGE_GUIDE = `# 意识(Ghost)编写手册意识是 Cindy 的第三方能力包,文件形态是 \`.cindy\`(zip 包)。装入后可给主机叠加:AI 可调用的工具、常驻界面面板、模型代办能力。本手册教你(agent)替用户写一个意识。**流程:先取手册目录 → 按 §0 用提问卡片和用户对齐设计 → 按需用 section-读透相关章(动手前至少读完 §2 卡槽总览、"沙箱红线"与"打包与测试"三章) → 在工作目录写源码文件 →-ghost_forge_pack 打包 → 用户在弹窗上确认装入;需要发布时改用 publish intent 取得一次性票据。**+读透相关章(动手前至少读完"沙箱红线"与"打包与测试"两章) → 在工作目录写源码文件 →+ghost_forge_pack 校验并生成 .cindy 产物;需要发布时改用 publish intent 取得一次性票据。**++**安装与更新契约**:用户导入本地 \`.cindy\`、点击市场安装,或插件命中+服务端 \`defaultInstall\`,都是明确的安装依据;+Cindy 校验真实包后直接安装并启用,不再追加能力确认弹窗。市场安装会绑定所选来源,+此后的新版本由 Cindy 静默更新并保留当前启用状态;本地 \`.cindy\` 不自动猜测更新来源,+需要用户再次导入新版包。插件自主 Host 能力仍必须完整声明,插件详情会如实展示,Host 运行时按声明+强制守门;市场下载包若超出该版本市场清单声明的能力,会作为包内容不一致被拒绝。++**先判断谁执行,再声明能力**:++- 当前 Agent 调用你的 tool 时,是否执行由 Cindy 现有 Agent 授权系统决定。+ 普通 HTTPS 请求和当前 workdir 文件操作把主机下发的 \`msg.callId\` 原样带给+ \`cindy.fetch\` 或 \`cindy.fs\`;CLI 继续使用既有随包 Node 工作进程,+ 不新增另一套 Host 执行协议。具体 CLI、域名或路径不需要先注册成客户端 Slot。+- 只有 Panel、订阅、常驻进程、后台任务等**脱离当前 Agent tool-call**+ 仍要自主使用 Host 能力时,才声明 \`network\`、\`fs\`、\`node\` 等对应字段。+ 真正需要 Cindy 尚未实现的 Host 服务(例如新的内置设备面)时,才需要客户端+ 实现并提高 \`minCindyVersion\`。从零开始时优先调用 \`ghost_forge_scaffold\` 生成一份不会覆盖现有文件的骨架,再在骨架上修改。可选模板:\`plain\`(普通沙箱工具)、\`agent-action\`(卡片点击后让 Agent@@ -1477,19 +1494,20 @@ ghost_forge_pack 打包 → 用户在弹窗上确认装入;需要发布时改值得主动摆出来让用户选的"隐藏"设计选项(详见对应章节):-- **界面形态**:无界面(纯工具)/ 聊天卡片(card 槽,§4.5)/ Cindy 一级主视图- (main-view 槽,§4.20)/ 停靠面板(panel.position left,§5)/ 插件页内独占面板- (position "tab",从插件页「使用」打开、离开即关,§5)。+- **界面形态**:无界面(纯工具)/ 聊天卡片(card 能力,§4.5)/ Cindy 一级主视图+ (mainView 能力,§4.20)/ 停靠面板(panel.position+ left,§5)/ 插件页内独占面板(position "tab",从插件页「使用」打开、离开即关,§5)。- **唤起方式**:只靠 AI 按 whenToUse 自动想起,还是同时声明 \`command\` 点名词让用户显式点名(推荐,§2)。- **启动模式**:on-demand 按需拉起(缺省,推荐)/ resident 常驻(仅订阅型、要秒响应的场景,§2)。-- **后台能力**:要不要旁听事件(subscribe 槽,§4.6)、发系统提示(notify 槽,§4.9)、留一条持久- 未读绿点(badge 槽,§4.9.1)、- 动手前弹确认框征求同意(confirm 槽,§4.18)。-- **联网与凭证**:要不要 network 槽白名单联网(§4.7);要用户填 key 就需要 setup+- **后台能力**:要不要旁听事件(subscribe,§4.6)、发系统提示(notify,§4.9)、留一条持久+ 未读绿点(badge,§4.9.1)、+ 动手前弹确认框征求同意(confirm,§4.18)。+- **自主联网与凭证**:脱离当前 Agent 调用时要不要用 network 白名单联网(§4.7);+ 要用户填 key 就需要 setup就绪声明与 settingsHtml 设置区(§4.7、§4.8)。-- **运行形态**:纯沙箱 main.js 够用,还是要随包 Node 进程装依赖跑重活(node 槽,§4.12)。+- **运行形态**:纯沙箱 main.js 够用,还是要随包 Node 进程装依赖跑重活(node,§4.12)。- **媒体能力**:要不要基于 Cindy Core 的图片/视频模型封装上层能力;插件负责场景、配置和结果呈现,生成请求由当前 Agent 调用 Core media 工具(§2、§4.0.4)。@@ -1513,7 +1531,7 @@ my-ghost/│ ├── ja.json│ └── ko.json├── node/-│ └── worker.cjs ← 可选:随包 Node/stdio MCP 入口(声明 node 槽时必须,见 §4.12)+│ └── worker.cjs ← 可选:随包 Node/stdio MCP 入口(声明 node 时必须,见 §4.12)├── panel.html ← 面板界面(声明了 panel.html 时必须)├── panel.css├── panel.js@@ -1524,9 +1542,9 @@ my-ghost/想看**真实完整范例**,浏览官方插件源码仓\`github.com/makecindy/cindy-official-plugins\`:仓库根下每个**含 ghost.json 的一级目录**(cindy-art、cindy-github、cindy-web-search……)都是一个已上架插件的-全部源码,各槽(卡槽/+全部源码,各类能力(聊天卡片/面板/网络/设置页)都有现成写法可对照;\`.tests\`、\`docs\` 等无 ghost.json 的-目录是仓库自身的基础设施,不是插件。需要理解宿主侧能力实现(某个槽的代发+目录是仓库自身的基础设施,不是插件。需要理解宿主侧能力实现(某项能力的代发细节、校验器行为)时可参考主仓 \`github.com/makecindy/cindy\`(插件基座在\`apps/desktop/src/main/cindy-brain/\`),但**API 契约一律以本手册为准**——线上 main 分支可能领先或落后用户当前安装的主机版本,照 main 写码可能装进@@ -1536,10 +1554,10 @@ my-ghost/\`\`\`json{- "schemaVersion": 2,+ "schemaVersion": 3,"id": "my-ghost", // 小写字母/数字/连字符,1–32 位,全局唯一"name": "我的意识", // 展示名- "description": "一句话说清这段意识是干嘛的(给人看:装入确认框/详情页)", // 1–${GHOST_MANIFEST_SUMMARY_MAX_CHARS} 字+ "description": "一句话说清这段意识是干嘛的(给人看:插件详情页)", // 1–${GHOST_MANIFEST_SUMMARY_MAX_CHARS} 字"whenToUse": "需要生成图片、插画、配图、修图、P 图、改图时找我", // 1–${GHOST_MANIFEST_SUMMARY_MAX_CHARS} 字,给模型看:进 agent 会话的意识花名册,是"用户不点名时 AI 能不能想起你"的关键。写成场景枚举,可反复调优;花名册会折叠连续空白,异常数据会截断;缺省时花名册回落用 description"icon": "assets/icon.png", // 建议:插件图标(包内相对路径;扩展名限 png/jpg/jpeg/webp/gif,不收 svg——svg 可携带脚本,虽经 <img> 渲染不执行,仍不给这个面)。不配则面板与消息身份头显示默认拼图占位符;官方插件仓惯例放 assets/icon.png"locales": { // 可选:插件只跟随宿主语言;不支持/缺失语言固定回退 en@@ -1549,21 +1567,20 @@ my-ghost/"ko": "locales/ko.json"},"version": "1.0.0",- "minCindyVersion": "1.2.3", // 可选:安装所需最低 Cindy 正式版本(SemVer)。不写=兼容所有版本;只在确实使用了新版宿主能力时声明+ "minCindyVersion": "0.1.61", // v3 必填:首个支持本清单的 Cindy 正式版本(SemVer)"entry": "main.js", // 电子脑入口(kind 字段已无需填写:意识只有芯片一种形态,缺省即 chip;写了也只认 "chip")- "launch": "on-demand", // 可选:电子脑启动模式。on-demand(缺省)=被需要才拉起;resident=唤醒即常驻(确认框会如实标注"常驻运行",绝大多数意识不需要,仅订阅型/需秒响应的场景用)- "slots": ["tool", "cindy", "panel"], // 能力白名单,没声明的槽运行时不存在+ "launch": "on-demand", // 可选:电子脑启动模式。on-demand(缺省)=被需要才拉起;resident=唤醒即常驻(详情页会如实标注"常驻运行",绝大多数意识不需要,仅订阅型/需秒响应的场景用)"command": "画图", // 推荐:用户 $画图 显式点名(与已装意识查重,冲突拒装)。// 注意:不声明 command 时,插件页"使用"按钮将处于禁用状态——用户无法通过插件页// 一键启用/唤起插件,也不能用 $command 显式点名;但 AI 的工具发现与调用不受影响// (仅检查插件启用状态与 tools 声明)。除非你的插件完全靠 panel 或 subscribe 驱动,// 否则请始终声明一个 command。"tools": [ /* 见 §3 */ ],- "cindy": { "image": ["generate", "edit"] }, // 声明了 cindy 槽时必写:能力详单,见下+ "cindy": { "image": ["generate", "edit"] }, // 直接声明能力及详单,见下// 类目按需申请:image / video 的动作是 "generate" | "edit";media 只有// "deposit"(把你手里的媒体字节寄存进总仓换指纹,见 §4.0.1);// text 只有 "oneshot";search 只有 "web"(Cindy 托管公网搜索)。每条都会- // 在装入确认框里单独列给用户看。+ // 在插件详情的能力清单里单独列给用户看。"panel": { "title": "面板标题", "html": "panel.html", "position": "left","minWidth": 240, "defaultFraction": 0.24,"systemButtons": { "maximize": false } },@@ -1578,22 +1595,24 @@ my-ghost/// 窗口中打开)、minimize(最小化面板;恢复入口由用户偏好决定为浮动气泡或// 左侧栏)。标题条本体恒由主机绘制、// 关不掉;未知键拒装;position:"tab" 时声明本字段拒装- // 一级主视图是独立能力,见 §4.20。使用时在 slots 加 "main-view",并声明:+ // 一级主视图是独立能力,见 §4.20。使用时直接声明:// "mainView": { "title": "工作台", "icon": "puzzle", "html": "main-view.html" }- // 声明 main-view 时 minCindyVersion 必填。"settingsHtml": "settings.html", // 可选:设置页「自定义设置区」自绘界面(见 §4.8;声明了用户填的凭证时仍必填,用于长期管理/替换/清除;调用前缺失时主机也会在统一 Setup 卡内联收单,见 §4.7)"settingsHeight": 360 // 可选:固定高度 px(160–800);缺省 = 随内容自适应(矮内容真收矮,高至 800);内容会动态增减时才声明,避免抖动}\`\`\`-不要为“当前开发环境版本”机械填写 \`minCindyVersion\`。旧插件和不依赖新版宿主能力的-插件应省略它;当更早版本无法正确安装,或虽能安装但缺少新版宿主能力、导致插件无法按-设计正常工作时,必须填写最早可正常工作的正式版本。\`manual\` / \`ghost_manual\` 属于后者。+\`schemaVersion: 3\` 必须填写 \`minCindyVersion\`。它写首个能解析该清单的 Cindy+正式版本;当前 v3 起点是 \`0.1.61\`。不要为了使用某项既有能力随意抬高版本。+官方市场会优先向旧客户端投影最近的兼容历史版本,没有兼容版本时不展示该插件。+Desktop 信任来源已经完成的版本选择,不再按 \`minCindyVersion\` 追加筛选或确认弹窗;+用户主动导入的本地包、以及用户添加的自定义市场也遵循同一安装策略。这个字段仍必须+准确填写:它供发布服务选择兼容 release,也记录插件真实依赖的首个 Host 版本。### whenToUse:只写发现线索,不写使用规则在作者契约里,\`whenToUse\` 是专门给模型做插件发现与判断的唯一字段;-\`description\` 给人看(装入确认框/详情页),不要拿它兼任模型路由说明。+\`description\` 给人看(插件详情页),不要拿它兼任模型路由说明。\`whenToUse\` 最多 ${GHOST_MANIFEST_SUMMARY_MAX_CHARS} 字符,花名册会完整展示有效内容,折叠连续空白并对异常数据做防御性截断。花名册命中已知 \`ghost_id\` 时用\`ghost_info\` 精准现查单条;未命中或需要全量实时回查时用 \`ghost_list\`。两者都返回完整\`CindyGhostInfo\`,取得信息后再按任务交叉读取 Manual 与插件工具目录,信息足够即可调用。@@ -1683,38 +1702,33 @@ key、未知字段、原清单没有的条目、类型或长度不合格、文node secretBindings key、setup kv key——都不能使用 \`__proto__\`、\`constructor\` 或\`prototype\`;这些名称是宿主保留键,打包时会直接拒绝。-二十个卡槽:\`tool\`(注册工具给 AI)、\`cindy\`(请 Cindy 本体代办:出图/改图/快问快答,-见 §4 与 §4.0.2)、\`agent\`(让-当前 Agent 开始一个普通用户回合,或派活取回结果,见 §4.11 / §4.11.1)、-\`main-view\`(Cindy 一级侧边栏入口与完整页面,见 §4.20)、\`panel\`(常驻面板)、-\`card\`(聊天卡片:自绘工具调用的过程与结果,见 §4.5)、\`subscribe\`(旁听会话-事件 + 拦截用户消息,见 §4.6)、\`network\`(访问自带服务的域名白名单 HTTP,主机代发,-见 §4.7)、\`notify\`(弹系统轻提示,主机画壳带你的身份头,见 §4.9)、\`badge\`-(在插件入口留一颗持久的未读绿点,与 notify 并列、互不为前置,见 §4.9.1)、\`confirm\`(弹主机-同款确认框征求用户同意并拿回真实点击,见 §4.18)、\`fs\`(请主机-代写文件:私有数据目录/会话工作目录/过户目录三档,见 §4.10)、\`library\`-(持久作品库:用户作品级存储,不受 fs 配额约束、卸载不删,含受控 SQLite,-见 §4.10.1)、\`node\`(运行随包-Node 工作进程或 stdio MCP,见 §4.12)、\`session-context\`(派活时主机把当前会话的-可信 session_id / workdir / 只读状态注入 args,见 §4.13)、\`pick\`(请主机弹系统选文件夹窗口,-用户亲选即授权,见 §4.14)、\`preview\`(请主机在右侧栏内置浏览器打开白名单网站的-预览标签,见 §4.15)、\`skill\`(捆绑 Agent Skills:随包 SKILL.md 技能,启用后-Claude Code 与 Codex 都能发现,见 §4.16)、\`workspace\`(请主机为项目目录在-侧边栏创建/复用会话入口,见 §4.17)、\`ios-simulator\`(读取当前台前任务的-公开 iOS 模拟器状态并打开 Host 内置控制面板,见 §4.19)。--**agent 能力详单**:在 \`slots\` 加 \`"agent"\`,默认只允许在用户真实点击你的-聊天卡片后发起一次 Agent 回合;这一档不写配套字段。若确实需要没有当次点击也能-自动发起,额外写 \`"agent": { "background": true }\`。后台档会在装入确认框单独-显示为更高风险权限,而且仍只能使用用户曾通过点击卡片与你建立关联的会话。+v3 直接用顶层字段声明插件贡献项与自主 Host 能力,不再有 \`slots\`。带详单的字段是 \`tools\`、\`cindy\`、+\`agent\`、\`panel\`、\`mainView\`、\`card\`、\`subscribe\`、\`network\`、\`node\`、\`preview\`、+\`skill\`;布尔能力写成字面量 \`true\`:\`notify\`、\`badge\`、\`confirm\`、\`fs\`、+\`library\`、\`sessionContext\`、\`pick\`、\`workspace\`、\`iosSimulator\`。不用的字段直接省略,+不能写 \`false\`。\`card: {}\` 与 \`agent: {}\` 分别表示基础聊天卡片能力和用户点击后+发起 Agent 回合;其它对象型能力必须包含该能力真正需要的详单。++v3 未识别的顶层字段会原样保留,但旧版 Cindy 不展示、不给这个未知 Host 能力、也不因此阻止安装。+当未来 Cindy 识别该字段后,它才会进入正常的能力展示与运行时守门。插件若依赖新能力,+应同时把 \`minCindyVersion\` 提高到首个支持版本;仅由插件包自己完成的逻辑不要发明+Host 能力字段。v2 的 \`slots\` 只用于存量包兼容,新插件不得再写。+当前 Agent tool-call 内,插件工具是否执行由外层 \`ghost_call\` 的 Agent 授权决定;+普通网络和 workdir 文件操作按上文的 \`callId\` 绑定复用 Agent 授权。CLI 继续由+已声明运行形态的 Node 工作进程执行,不新增未知 Host 能力或具体命令登记。++**agent 能力详单**:写 \`"agent": {}\` 时,默认只允许在用户真实点击你的+聊天卡片后发起一次 Agent 回合。若确实需要没有当次点击也能自动发起,写+\`"agent": { "background": true }\`。后台档会在插件详情中单独显示为更高风险能力,+而且仍只能使用用户曾通过点击卡片与你建立关联的会话。要把任务交给 Agent 干并**取回结果**(而不是发进用户的会话),另写-\`"agent": { "errand": true }\`(可与 background 并存),见 §4.11.1;同样是装入-确认框单列的高风险档。+\`"agent": { "errand": true }\`(可与 background 并存),见 §4.11.1;同样是详情页+单列的高风险档。要请用户新建一条**自动化**(让插件里的内容定期自己刷新),另写\`"agent": { "schedule": true }\`(可与前两项并存),见 §4.11.2。它只能打开预填好的-创建面板,任务由用户选好模型后亲手保存才存在;装入确认框单列一档。+创建面板,任务由用户选好模型后亲手保存才存在;详情页单列一档。-**node 工作进程详单**(声明 node 槽时必写,详见 §4.12):+**node 工作进程详单**(声明 node 时必写,详见 §4.12):\`\`\`json"node": {@@ -1723,10 +1737,10 @@ Claude Code 与 Codex 都能发现,见 §4.16)、\`workspace\`(请主机为项"lifecycle": "on-demand", // 可选:on-demand(缺省)/resident(常驻,单列高风险权限)"idleTimeoutSeconds": 120, // 可选:按需档空闲关闭时间,30–3600;resident 禁写"entries": ["node/build.cjs"], // 可选 ≤4 条:额外工作进程入口(每入口一个独立进程,调用时用 entry 指名,见 §4.12.1;不能与 entry / 浏览器沙箱 entry / 彼此重复)- "childSpawn": true, // 可选:worker 可请宿主代启申报入口的原样 stdio 子进程(见 §4.12.4;装入确认框单列一行)+ "childSpawn": true, // 可选:worker 可请宿主代启申报入口的原样 stdio 子进程(见 §4.12.4;详情页单列一行)"secretBindings": [{ // 可选 1–4 条:safeStorage 持久化凭证按方法临时注入 Worker"key": "mail_code", // 插件内唯一,小写字母开头,1–32 位小写/数字/下划线;禁用宿主保留键(见 §2.1)- "label": "邮箱授权码", // 安装确认与设置页展示名+ "label": "邮箱授权码", // 详情页与设置页展示名"methods": ["mail/action"], // 只在这些 JSON-RPC 方法中注入,每条 1–128 位"entry": "node/worker.cjs", // 可选:逐字命中 node.entry/entries;缺省仅主入口"hint": "请填写服务商授权码", // 可选 ≤200 字@@ -1741,22 +1755,22 @@ node 详单**不接受** \`command\` / \`args\` / \`shell\` / \`env\` 或其它——正式包关闭了 RunAsNode,那样生出来的不是 Node;要多进程就把入口申报进\`entries\`,由主机代开。-**preview 详单**(声明 preview 槽时必写,详见 §4.15):+**preview 详单**(声明 preview 时必写,详见 §4.15):\`\`\`json"preview": {- "hosts": ["*.example.dev", "localhost"] // 1–4 条;语法同 network.hosts;能在右侧栏打开的预览网站白名单,装入确认框逐条展示+ "hosts": ["*.example.dev", "localhost"] // 1–4 条;语法同 network.hosts;能在右侧栏打开的预览网站白名单,详情页逐条展示}\`\`\`-**skill 详单**(声明 skill 槽时必写,详见 §4.16):+**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 字+ "description": "……" // 硬规则:与 SKILL.md frontmatter description 逐字一致(详情页展示的就是 Agent 读到的),1–1024 字}]}\`\`\`@@ -1782,18 +1796,18 @@ node 详单**不接受** \`command\` / \`args\` / \`shell\` / \`env\` 或其它媒体字节存进媒体库,§4.0.1)、\`text\`(\`oneshot\`=快问快答,§4.0.2)、\`embed\`(\`text\`=文本转向量,§4.0.3)、\`search\`(\`web\`=Cindy 托管公网搜索,见 §4 的 \`search_web\` 段)。-详单里没申请的动作,运行时点单直接被拒;声明了 cindy 槽却漏写详单 = 零能力,-别漏。\`search.web\` 只能由真实 tool-call 触发,还必须同时声明 \`tool\` 槽和-至少一个工具。(旧名 model 槽/字段仍兼容,但新意识一律用 cindy。)+详单里没申请的动作,运行时点单直接被拒。\`search.web\` 只能由真实 tool-call+触发,还必须同时声明至少一个 \`tools\` 条目。旧 v2 包的 model slot/字段仍兼容,+但新意识一律使用 v3 的 \`cindy\` 字段。-**network 详单**(声明了 network 槽时必写,详见 §4.7):+**network 详单**(声明 network 时必写,详见 §4.7):\`\`\`json"network": {- "hosts": ["api.example.com", "*.weather.com"], // 1–8 条;小写域名至少两段;通配只允许最左 "*.";装入确认框逐条展示给用户+ "hosts": ["api.example.com", "*.weather.com"], // 1–8 条;小写域名至少两段;通配只允许最左 "*.";详情页逐条展示给用户"secrets": [{ // 可选 0–4 条:需要用户填的凭证(你只声明名字和注入位置,值用户填、主机保管)"key": "api_token", // 小写字母开头,小写/数字/下划线,1–32;禁用宿主保留键(见 §2.1)- "label": "Example API Token", // 给用户看的名称(设置页/确认框)+ "label": "Example API Token", // 给用户看的名称(设置页/详情页)"source": "user", // 可选:凭证值来源。"user"(缺省)=用户可在调用前的主机 Setup 卡内填写,也可在你的 settingsHtml 里长期管理/替换/清除(当前仍要求同时声明 settingsHtml,见 §4.7);"login-email"=主机登录邮箱自动派生(用户不填;声明它时不允许再写 url,见 §4.7);"oauth"=主机托管 OAuth 授权,值 = 授权换来的 access token(必须同时声明 oauth 详单,见 §4.7 与下方 oauth 字段);"gh-cli"=仅官方 cindy-github 可用,优先复用本机 gh 登录、不可用时回落同 key 的设置页 PAT;"oidc-token"=主机为当前企业 Membership 按需签发短时 Connection JWT(插件不可读取,必须显式限制 inject.hosts,固定 Authorization: Bearer {value},见 §4.7)"hint": "在控制台生成后粘贴", // 可选提示(主机 Setup 卡与 settingsHtml 都会用到)"url": "https://example.com/settings/keys", // 可选:控制台/申请地址(仅 https)。调用前缺凭证时,主机 Setup 卡会在输入框旁展示本地化的「获取凭证」入口;settingsHtml 也可用 <a href> 逐字引用它,点击经主机转系统浏览器打开(见 §4.8「外链」)@@ -1815,19 +1829,19 @@ node 详单**不接受** \`command\` / \`args\` / \`shell\` / \`env\` 或其它"clientId": "xxx.apps.example.com", // 可选:内置 OAuth 客户端 ID(用户零配置开箱即用;用户在设置页自填的覆盖内置,清除自填即回落)"clientIdAlternatives": ["xxx-global.apps.example.com"], // 可选 ≤8 条:仅 tokenBroker 模式;意识按 app-context 选 App 时,connect 只接受默认值或这里声明的公开 ID"clientSecret": "xxx", // 可选(须与 clientId 成对):内置 client 的 secret;桌面应用的 client 凭证本非机密,纯 PKCE 服务商可省略- "scopes": ["read.a", "write.b"], // 可选 ≤256 条:申请的权限范围(确认框逐条展示给用户)+ "scopes": ["read.a", "write.b"], // 可选 ≤256 条:申请的权限范围(详情页逐条展示给用户)"scopeDelimiter": ",", // 可选:authorize URL 的 scope 拼接分隔符;缺省空格(OAuth 标准),Slack 这类逗号分隔的服务商声明 ","(目前只认这一个值)"pkce": true, // 可选:PKCE(S256)开关,缺省 true"extraAuthorizeParams": { "access_type": "offline", "prompt": "consent" }, // 可选 ≤8 条:服务商特有授权参数(协议保留参数禁写)"identity": { "url": "https://api.example.com/userinfo", "labelPath": "email", "displayTemplate": "{team} · {user}", "avatarPath": "data.avatar_thumb" }, // 可选:授权后拉一次身份端点给账号打标签(设置页"已连接为 xxx";url 域名须命中 hosts)。labelPath 应指向**唯一且稳定**字段(如邮箱 / user_id)——它是重复授权时的同身份合并判定键,选 name 这类可重名可改名字段会误合并。displayTemplate 可选:人类可读展示名模板,\`{点分路径}\` 占位符从同一份身份响应取值(至少一个占位符,≤200 字符),任一占位符取不到值整体降级为空、回落显示 labelPath 的值——labelPath 的稳定字段不可读(如 Slack 的 user_id)时声明它,设置页与账号工具展示的就是渲染后的名字(邮箱这类本身可读的服务商不需要)。avatarPath 可选:头像 URL 在身份响应里的点分路径(如飞书的 "data.avatar_thumb")——主机取 https 地址后**不带凭证**下载小图(仅 png/jpeg/webp/gif、≤256KB)转 data URL 存库,\`/oauth\` 回查里以 account.avatarDataUrl 给你的 settingsHtml 展示(<img> 直接用)。**下载仅对第一方官方意识生效**(头像地址不受 hosts 白名单约束,第三方声明合法但恒降级 null)——所以页面必须能没头像也好看(如回落姓名首字圆片)"redirectPort": 53682, // 可选:loopback 回调固定端口(1024–65535);声明 tokenBroker 时必填。服务商要求回调 URI 与注册值精确匹配(如 Atlassian)时声明,回调恒为 http://127.0.0.1:<端口>/callback;非 broker 模式缺省 = 随机端口(Google 等允许任意 loopback 端口的服务商不用声明)- "tokenBroker": "jira", // 可选:三路资格:静态官方前缀照旧放行;当前组织的服务端 organization market 包已安装、source 为 market、organizationId 与当前组织一致、id 命中本组织已登记前缀且 release sha256 与批准 receipt 的 packageSha256 相等;或当前组织身份下经 ghost forge 装入(receipt.installOrigin 为 agent-forge)且 id 命中本组织已登记前缀。后两条新增基座不接受手动装入、个人身份或别的组织前缀,且只给 Broker 与 oidc-token,不给宿主原语。声明时必须同时声明 redirectPort;code/refresh 交换经 Cindy 服务端 broker 完成(client secret 在服务端,不随包分发),与 clientSecret 互斥;设置页不再支持自填 client+ "tokenBroker": "jira", // 可选:两路资格:静态官方前缀照旧放行;或当前组织的服务端 organization market 包已安装、source 为 market、organizationId 与当前组织一致、id 命中本组织已登记前缀且 release sha256 与批准 receipt 的 packageSha256 相等。组织市场基座不接受本地装入、个人身份或别的组织前缀,且只给 Broker 与 oidc-token,不给宿主原语。声明时必须同时声明 redirectPort;code/refresh 交换经 Cindy 服务端 broker 完成(client secret 在服务端,不随包分发),与 clientSecret 互斥;设置页不再支持自填 client"brokerBounce": { "path": "/example/bounce", "callbackPath": "/example/callback" } // 可选:双地址弹跳回调(服务商后台只收 https redirect、不收 http loopback 时用)。必须与 tokenBroker、redirectPort 同时声明;报给服务商的 redirect_uri = broker 服务基地址 + path(主机运行时拼,清单不落域名),浏览器授权后由弹跳路由 302 回 http://127.0.0.1:<redirectPort><callbackPath>}}],"connections": [{ // 可选 0–2 条:多连接声明——"地址 + 凭证成对多条"(自建实例场景如 GitLab,详见 §4.7「多连接」)。声明了 connections 时 hosts 可缺省/为空(静态域名与动态连接至少有其一);声明 connections 必须同时声明 settingsHtml"key": "gitlab", // 小写字母开头,小写/数字/下划线,1–32;禁用宿主保留键;与 secrets[].key 共用命名空间,撞名拒装- "label": "GitLab 实例", // 给用户看的连接类型名(1–64 字;确认框与设置页展示)+ "label": "GitLab 实例", // 给用户看的连接类型名(1–64 字;详情页与设置页展示)"hint": "填实例域名与 Personal Access Token", // 可选 ≤200 字提示(建议写进你的 settingsHtml 文案)"inject": { "header": "Private-Token", "format": "{value}" }, // 凭证注入形态(规则同 secrets 的 inject);**不允许**声明 inject.hosts——凭证恒只注入对应连接自身的地址,写了拒装"maxConnections": 4 // 可选:每种连接可添加的地址数上限(1–8 整数,缺省 8)@@ -1899,7 +1913,7 @@ Composer 的 \`@\` 面板只展示已安装且可用的插件入口;插件作**直接声明(默认,绝大多数意识用这个)**:每个工具在 tools 里逐条声明(§3 的写法)。适用:工具是"意图级"的——一个工具对应用户会说的一句话(如"生成音乐"、"部署站点"),数量一只手到一打(主机硬上限 16 项,超了直接拒装)。收益全在明处:模型通过-\`ghost_info\` 拿到插件详情后,靠各工具 description 选择具体能力;装入弹窗把每个工具+\`ghost_info\` 拿到插件详情后,靠各工具 description 选择具体能力;详情页把每个工具如实列给用户;工具名不存在主机直接拦。**两段式目录(大工具面专用)**:要包的能力是"端点级"的几十上百个操作(典型:给一个@@ -1939,7 +1953,7 @@ tools**——本插件的 \`ghost_info\` 单条详情会被撑大,不知道装\`list_tools(category)\` 的提示;收到不合法的 args 时,失败结果必须附该工具正确的参数 schema **和本次自纠必需的规则**(规则正文或能在本结果中解析的引用)——AI 会照着自纠重试,比干巴巴报错省一轮追问;-- 权限透明的代价自己补:装入弹窗只会逐条列出 list_tools / call_tool 两个元工具,用户+- 能力透明的代价自己补:插件详情只会逐条列出 list_tools / call_tool 两个元工具,用户看不出背后有多少操作。把给人看的能力范围如实写进 ghost.json 的 description,再把模型应在什么场景发现你的场景枚举写进 whenToUse,别让人或模型装完才发现。@@ -2019,7 +2033,7 @@ cindy.send({ type: 'tool-result', callId: msg.callId, ok: true, result: {// kind: 'music', // 'music'(完整卡:封面/tags/歌词/进度条)| 'sound_effect'(精简卡)// title: '歌名', cover_url: 'cindy-media://….jpg', tags: '风格描述',// lyrics: '歌词', duration_seconds: 176, suno_id: '…' }] // 除 url 外全可选- // → 聊天气泡渲染成音频播放器卡。声明了 card 槽的意识也可把播放器直接画进+ // → 聊天气泡渲染成音频播放器卡。声明了 card 能力的意识也可把播放器直接画进// 自己的卡(§4.5 data-ghost-audio 插槽),那时结果多带 xdt_audio_in_card: true// + xdt_anchor_card_id(主机验证卡里真含插槽才压基座的重复播放器;// xdt_audio_tracks 仍要发——手机端靠它)。@@ -2057,7 +2071,7 @@ cindy.send({// 长任务续命(超时窗口默认 330s,从派发起算绝对上限 30 分钟):// - 经 cindy-request 请主机代办且带 callId 的署名单(出图/视频)在途时,// 主机**自动**替这份卷续命,你不用做任何事;-// - 自己经 network 槽轮询外部长任务时,期间定期(建议 ≤60s 一次)发心跳:+// - 自己经 network 能力轮询外部长任务时,期间定期(建议 ≤60s 一次)发心跳:// cindy.send({ type: 'tool-progress', callId: msg.callId });// 每次心跳把窗口重新续满一个 330s 档;callId 不是派给你的会被静默丢弃。// - 预计超过 30 分钟天花板的超长任务,不要吊着一次 tool-call 等:视频代办用@@ -2066,7 +2080,7 @@ cindy.send({// 以下 gen_image / edit_image / gen_video / edit_video 是存量插件兼容接口。// 新插件不要从沙箱或面板直接发媒体生成请求;按 §4.0.4 让当前 Agent 使用// Cindy Core media 工具。非媒体的 cindy-request 能力继续按各自章节使用。-// 存量 Cindy 代办(需声明 cindy 槽 + 能力详单;主机出图、落仓、记账):+// 存量 Cindy 代办(需声明 cindy 顶层字段 + 能力详单;主机出图、落仓、记账):// 由 tool-call 触发的代办**务必带上收到的 callId**(归因号:让用户在日志/账单里// 对上"哪次调用花的钱");面板交互等自发代办可不带。const r = await cindy.send({ type: 'cindy-request', kind: 'gen_image', prompt: '一只猫', callId: msg.callId });@@ -2181,7 +2195,7 @@ const search = await cindy.send({寄存把这些字节存进总仓、记到你名下,换回指纹;从此它与你生成的图**同权**。\`\`\`js-// 需声明:"slots": [..., "cindy"], "cindy": { "media": ["deposit"] }+// 需声明:"cindy": { "media": ["deposit"] }const r = await cindy.send({type: 'cindy-request',kind: 'deposit_media',@@ -2216,7 +2230,7 @@ await cindy.send({ type: 'cindy-request', kind: 'release_media', hash: r.hash })自己在面板里用 \`cindy-ghost://<id>/media/<指纹><后缀>\` 渲染,或做成卡片;- **生命周期**:寄存物跨会话持久(删会话不陪葬),用户卸载你的插件时一并清理。-用户装你的插件时,确认框会单独出现一行「可将它手中的图片、视频或音频存入你的+插件详情的能力清单会单独出现一行「可将它手中的图片、视频或音频存入你的媒体库」并写明上限——这是唯一一条"不花钱就能写用户媒体库"的能力,所以要用户单独点头。别为了省事把它当默认能力申请:不做面板素材加工的插件不要声明。@@ -2226,7 +2240,7 @@ await cindy.send({ type: 'cindy-request', kind: 'release_media', hash: r.hash })任何工具时,不要发起 Agent 回合——用快问快答,几秒到几十秒出结果,便宜得多:\`\`\`js-// 需声明:"slots": [..., "cindy"], "cindy": { "text": ["oneshot"] }+// 需声明:"cindy": { "text": ["oneshot"] }// 可选偏好:"cindy": { "text": ["oneshot"], "oneshotModel": "codex/gpt-5.5" }const r = await cindy.send({type: 'cindy-request',@@ -2259,7 +2273,7 @@ const r = await cindy.send({\`errorCode:'BAD_MODEL_OUTPUT'\`(message 带原始输出开头供排查)。字段结构在 prompt 里自己描述,主机不做逐字段 schema 校验;- prompt ≤32768 字符;同步返回,没有异步单;每插件在途上限与媒体代办共用- (用户可配);装入确认框会单列一行「可向 Cindy 的快速通道提问」。+ (用户可配);详情页会单列一行「可向 Cindy 的快速通道提问」。### 4.0.3 文本转向量:把文字算成向量做语义检索(embed_text)@@ -2267,7 +2281,7 @@ const r = await cindy.send({Agent 做检索增强)时,用这个能力把文字算成向量:\`\`\`js-// 需声明:"slots": [..., "cindy"], "cindy": { "embed": ["text"] }+// 需声明:"cindy": { "embed": ["text"] }// 1) 入库:把你的内容算成向量,自己存起来const requestedDim = undefined; // 传 dimensions 时改成具体数字;不传就是 undefined@@ -2366,7 +2380,7 @@ const r = await cindy.send({\`'INTERNAL'\` = 主机侧故障,重试与否你自己判断;- 单次请求有 60 秒时间预算(含主机侧重试),到点即中断并返回 \`'TIMEOUT'\` ——不会让你的 \`await\` 永久悬着;-- 同步返回,没有异步单;每插件在途上限与媒体代办共用;装入确认框会单列一行+- 同步返回,没有异步单;每插件在途上限与媒体代办共用;详情页会单列一行「可把文字送去算成向量」并写明单次条数上限。## 4.0.4 媒体模型配置与调用边界@@ -2376,7 +2390,7 @@ const r = await cindy.send({1. 插件设置页 / panel 按类型读取当前可用模型,用来保存插件自己的模型选择;2. 当前 Agent 执行插件能力时,使用永久注册的 Cindy Core \`media\` 工具发起调用。-设置页 / panel 没有 preload 桥,直接走同源只读端点。插件必须声明 \`cindy\` 槽,+设置页 / panel 没有 preload 桥,直接走同源只读端点。插件必须声明 \`cindy\` 顶层字段,并在 \`cindy.image\` 或 \`cindy.video\` 中声明至少一个动作:\`\`\`js@@ -2453,7 +2467,7 @@ ghost_call({Host 不理解“画廊”或其它插件业务,也不会因为一次 \`media\` 成功自动唤醒、回调任意插件。-## 4.1 宿主公开上下文(request,无需卡槽)+## 4.1 宿主公开上下文(request,无需额外能力声明)电子脑需要按宿主构建身份或当前语言选择公开配置/界面文案时,走只读 request。当前只暴露\`region: 'cn' | 'global'\` 与 \`locale: 'zh-CN' | 'en' | 'ja' | 'ko'\`,@@ -2485,9 +2499,30 @@ region 只适合选择**已在 manifest 声明过**的公开配置。例如 brok(当前为 \`zh-TW\`)会在插件边界固定映射为 \`en\`,保证按旧四语契约编写的存量插件无需改代码;插件自身不支持该 locale 时也必须选英文资源。-## 4.5 聊天卡片(card 槽,海报模式)+## 4.2 Agent 在途网络与 workdir 操作-声明 \`"slots": [..., "card"]\` 即可,无配套清单字段。作用:你的工具调用在聊天流里+当 \`onHostMessage\` 收到 \`tool-call\` 时,主机下发的 \`msg.callId\` 是本次+Agent 调用的严格在途凭证。它已绑定真实插件和当前会话,外层+\`ghost_call\` 由 Cindy 现有 Agent 授权系统处理。因此本次调用里的普通+HTTPS 和 workdir 写入不需要再声明 \`network\` 或 \`fs\`。++对应 tool 的 \`description\` 必须写清实际会执行的命令类别、联网目标/用途和+文件副作用;这段描述就是 Agent 与用户决定是否调用该插件工具时看到的授权契约,+不能用「处理数据」之类模糊文案隐藏真实操作。++\`callId\` 必须在交卷前使用;不得持久化、不得交给 Panel,也不能用在订阅、+后台或 scheduler 调用。主机会反查这些条件,不信任插件自报。++普通 HTTPS 使用 \`cindy.fetch({ callId: msg.callId, ... })\`,workdir 写入使用+\`cindy.fs({ root:'workdir', callId: msg.callId, ... })\`;具体参数见 §4.7 和 §4.10。++CLI 执行机制不在本次协议中另开通道:需要随包代码或 CLI 时继续使用 §4.12+的 Node 工作进程。顶层 \`node\` 字段描述插件的运行形态;具体命令不需要客户端+预登记,当前工具是否运行仍由外层 \`ghost_call\` 的 Agent 授权决定。++## 4.5 聊天卡片(card 能力,海报模式)++声明 \`"card": {}\` 即可。作用:你的工具调用在聊天流里不再渲染成通用图卡,而是你自己排版的卡片(过程 + 结果都归你画)。不发供片 =聊天照旧渲染默认卡,卡片是**每次调用的可选项**。@@ -2590,7 +2625,7 @@ cindy.onHostMessage(async function (msg) {**跨调用画卡**(如轮询流画回首轮卡位)还需同时回锚 \`xdt_anchor_card_id\`= 持卡调用的 callId,桌面凭锚取卡验证含图后才压基座,锚不上会双渲染。-**交互卡的 card-action 处理**(声明了 card 槽即可收;点击触发你的动作、会花配额):+**交互卡的 card-action 处理**(声明了 card 能力即可收;点击触发你的动作、会花配额):\`\`\`jscindy.onHostMessage(async function (msg) {@@ -2600,11 +2635,11 @@ cindy.onHostMessage(async function (msg) {// msg.actionId = 你在 data-ghost-action 里写的动作 id;// msg.prompt = 用户输入的文字(仅 data-ghost-prompt 类按钮有,非空才带);// msg.spawnCallId = 主机铸的**衍生卡位**:画到它 = 原卡下方长出新卡。- // 声明 agent 槽后还会收到 msg.sessionId 与 msg.userActionToken;后者是+ // 声明 agent 后还会收到 msg.sessionId 与 msg.userActionToken;后者是// 绑定本插件+本会话、两分钟有效且只能使用一次的 Agent 通行票(见 §4.11)。cindy.send({ type: 'card-update', callId: msg.spawnCallId, v: 2, state: 'working', // 过程态:会话侧栏保持运行呼吸html: '<div style="padding:12px">⏳ 生成中…</div>', height: 110 });- const r = await doSomething(msg.actionId, msg.prompt); // 干活(可调你自己的工具/network 槽)+ const r = await doSomething(msg.actionId, msg.prompt); // 干活(可调你自己的工具/network 能力)cindy.send({ type: 'card-update', callId: msg.spawnCallId, v: 2, state: 'done', // 终版:熄灭呼吸html: renderCard(r), height: 340 });return;@@ -2651,13 +2686,13 @@ cindy.onHostMessage(async function (msg) {校验);锚不上(卡已被清理等)自动回退到轮询位置渲染,不影响交卷。该字段是渲染层配对令牌,AI 会被统一提示忽略它,你不用在 guidance 里解释。-## 4.6 订阅:旁听事件 + 钩子处理消息(subscribe 槽)+## 4.6 订阅:旁听事件 + 钩子处理消息(subscribe 能力)一种事件模型,两个类型:- **监听(\`did-\`)** = 纯数据通知,事后告诉你发生了什么,你改变不了流程——适合做统计面板、成本记账、工作流水、"跟随用户正在看的会话"联动等纯观察型能力;- **钩子(\`will-\`)** = 主机在对话流的关键点**停下来把数据交给你,做完再继续**。- 裁决窗口内你可以做**任何**你权限内的事(经 network 槽调自己的服务、经 cindy 槽+ 裁决窗口内你可以做**任何**你权限内的事(经 network 调自己的服务、经 cindy请主机代办、任意本地计算、跨会话攒状态),最后用一个收敛动作收尾。两个钩点,一进一出:- \`will-user-message\`(入口):用户消息发给 AI **之前**交到你手上,动作@@ -2674,7 +2709,6 @@ cindy.onHostMessage(async function (msg) {声明:\`\`\`json-"slots": [..., "subscribe"],"subscribe": {"topics": ["turn", "session", "activity"], // did- 旁听(元数据,不含消息内容)"hooks": ["will-user-message", "will-assistant-message"] // will- 拦截(声明任一必须 launch:"resident")@@ -2726,7 +2760,7 @@ cindy.onHostMessage(function (msg) {// ── will-user-message 钩子:3 秒内必须回裁决,否则主机按放行处理 ──// 语义 = "主机停下来交给你做,做完继续":你可以在这窗口里做任何事(记账、- // 经 network 槽过合规接口…),然后用三种动作之一收尾:+ // 经 network 过合规接口…),然后用三种动作之一收尾:if (msg.name === 'will-user-message') {// msg.data = { sessionId, text, model? };新 turn 时 model 是本轮已选模型 id,// 同轮插话(steer)时是当前运行中 turn 的模型 id。@@ -2772,8 +2806,8 @@ cindy.onHostMessage(function (msg) {"在忙 / 在等审批"。收到 \`dropped\` 时把状态清空、以此后到达的事件为准;- **钩子超时 = 放行**:\`will-\` 裁决必须 3 秒内回,超时主机按 allow 放行(聊天绝不因你卡死);连续 3 次超时/崩溃,主机**熔断**你的钩子能力(降级为只旁听 + 提示- 用户),旁听不受影响。要过外部合规接口就在窗口内 \`await cindy.fetch\`(network- 槽),但整段必须 3 秒内出裁决;+ 用户),旁听不受影响。要过外部合规接口就在窗口内 \`await cindy.fetch\`(network),+ 但整段必须 3 秒内出裁决;- **三种动作**:\`allow\`(原样继续)/ \`block\`(打回,reason ≤200 字符,显示在被拦气泡)/ \`rewrite\`(改写正文再继续,\`text\` ≤16000 字符替换即将落库/显示/交给agent 的正文)。多个钩子意识按装入序串行,**链式变换**(前一个改写的输出是后@@ -2793,7 +2827,7 @@ cindy.onHostMessage(function (msg) {- **没有绕过通道(v1)**:被拦消息用户只能编辑后重发,重发仍会经你再审。即便如此也别把拦截当硬性管控设计(意识是工具不是管理员):reason 要引导用户怎么改,而不是单纯说不;-- **权限最重**:声明 hooks 在装入确认框里是最重的一条(「可读取、拦截或改写你+- **权限最重**:声明 hooks 在插件详情里是最重的一条(「可读取、拦截或改写你发出的消息」),用户会看得很清楚,只在真需要时申请。## 4.6.1 出口钩子 will-assistant-message(对 AI 回复做任意后处理)@@ -2820,7 +2854,7 @@ cindy.onHostMessage(async function (msg) {body: JSON.stringify({ text: msg.data.text }) });// ① rewrite:用改写正文替换回复(静默换文本,≤16000 字符)。cindy.send({ type:'event-verdict', hookId: msg.hookId, action:'rewrite', text: polished.body });- // ② 或 render:自绘卡片替换气泡(html 规则同 §4.5 card 槽:纯 HTML+CSS、零脚本、+ // ② 或 render:自绘卡片替换气泡(html 规则同 §4.5 card 能力:纯 HTML+CSS、零脚本、// 图片仅本意识 cindy-media 地址;height 初始估计;主机净化 + clamp)。// cindy.send({ type:'event-verdict', hookId: msg.hookId, action:'render',// html: '<div style="padding:12px">…</div>', height: 200 });@@ -2830,7 +2864,7 @@ cindy.onHostMessage(async function (msg) {\`\`\`硬规则:-- **render 的 html 与 card 槽(§4.5)同一套净化**:纯 HTML+CSS、零脚本、图片只认你+- **render 的 html 与 card 能力(§4.5)同一套净化**:纯 HTML+CSS、零脚本、图片只认你名下的 \`cindy-media://\` 地址、体积/height 同限、可用主机主题 \`var(--xxx)\`;不合规被净化器拒则回退原文;- **原文始终保留("查看原文")**:render 时 AI 原文仍落库,主机在卡片旁画一个@@ -2838,25 +2872,32 @@ cindy.onHostMessage(async function (msg) {- **多个出口钩子意识**按装入序**串行链式**:rewrite 叠加(前一个改写的输出是后一个的输入),**render 最后一个胜出**;- **处理期间那条消息挂"意识处理中"轻指示**(主机画),完成/超时清掉;-- **权限档**:声明 \`will-assistant-message\` 在装入确认框里单列一条(「可读取并重写+- **权限档**:声明 \`will-assistant-message\` 在插件详情里单列一条(「可读取并重写AI 的回复」),比入口钩子更敏感(能看到 AI 完整输出),只在真需要时申请。-## 4.7 网络代发(network 槽)+## 4.7 网络代发(network 能力)++\`cindy.fetch\` 有两个清晰的运行边界:++- 当前 Agent tool-call 内:传 \`callId: msg.callId\`,可访问未预声明的普通+ HTTPS 地址,无需 \`network\` 字段。主机仍强制 URL、SSRF、超时、体积与+ 重定向守门,但不会向未声明 host 注入任何 Host 托管凭证。+- 脱离当前 Agent 调用的自主联网:声明 \`network\` 详单(§2),只能访问+ **白名单内的域名**。需要主机保险库凭证、OAuth 或动态连接时也必须+ 显式声明,只有命中声明 host 才会注入。-声明 \`"slots": [..., "network"]\` + network 详单(§2)后,电子脑可用 \`cindy.fetch\`-访问**白名单内的域名**——沙箱本身仍然零直连,请求由主机代发:主机校验域名、-注入凭证、执行 HTTP、把响应给你。规则:+沙箱本身两种情况都零直连,请求统一由主机代发。规则:\`\`\`jsconst r = await cindy.fetch({- url: 'https://api.example.com/v1/search?q=hello', // 仅 https、默认端口;host 必须命中详单白名单+ url: 'https://api.example.com/v1/search?q=hello', // 仅 https、默认端口method: 'GET', // 可选:GET(缺省)/ POST / PUT / PATCH / DELETEheaders: { Accept: 'application/json' }, // 可选;Host/Cookie/Authorization 等由主机管,写了也不生效body: '{"q":"hello"}', // 可选:仅 POST / PUT / PATCH / DELETE,≤256KB 文本timeoutMs: 30000, // 可选:文本模式 1s–60s 缺省 30s;媒体模式 1s–300s 缺省 120sas: 'text', // 可选:'text'(缺省)/ 'media'(响应是媒体,主机落仓,见下)label: '', // 可选:仅媒体模式,入账备注/画廊 caption(≤200 字符)- callId: msg.callId // tool-call 触发的请求务必带上(归因,同 cindy-request)+ callId: msg.callId // Agent tool-call 内务必带上,同时作为严格在途授权绑定});// 文本成功:{ ok:true, status: 200, headers: { 'content-type': … }, body: '<响应文本>', truncated? }// 注意 4xx/5xx 也是 ok:true(代发成功,对方说不行)——自己看 status 分支。@@ -2882,7 +2923,7 @@ const r = await cindy.fetch({不要试图让用户把 key 发进聊天,更不要把 key 硬编码在源码里。这里说的是 \`network.secrets\` 的浏览器沙箱/HTTP 代发语义;确需本地协议时,\`node.secretBindings\` 是唯一允许把对应凭证交给 Node Worker 的显式例外,-并会在安装权限清单单独披露(见 §4.12.1)。+并会在插件详情的能力清单单独披露(见 §4.12.1)。**调用前缺失的普通 user Secret 由主机统一 Setup 卡收单**:主机只根据你声明的\`label\` / \`hint\` 生成密码输入,不把值交给 Agent 或你的代码;提交后直接写保险库并@@ -2901,7 +2942,7 @@ BroadcastChannel、日志或任何自存路径(review 必查)。凭证只会注\`inject.hosts\` 声明的域名请求,重定向出域也不会跟着走。用户没填时 cindy.fetch返回结构化错误,把 message 原样告诉用户即可(里面带了去哪填的指引)。无论走 Setup 卡还是 settingsHtml,入库成功时主机会自动弹一条「凭证已保存」的系统提示(带你的身份头,-文案跟随用户语言;无需声明 notify 槽)——设置页里画个就地的轻反馈即可,+文案跟随用户语言;无需声明 notify)——设置页里画个就地的轻反馈即可,不用自己想办法做全局提示。(历史字段 \`input\` 已退役:遗留 \`"input":"ghost"\` 可被接受并忽略,\`"input":"host"\` 直接拒——删掉该字段即可。)@@ -2910,13 +2951,13 @@ BroadcastChannel、日志或任何自存路径(review 必查)。凭证只会注鉴权"的第一方服务(如 pages_<邮箱> 形态的 token)。凭证声明 \`"source": "login-email"\`后,值不再由用户填——主机在每次请求时现读当前登录账号的邮箱,按 \`inject.format\`模板派生(如 \`"format": "pages_{value}"\` 得到 \`pages_<邮箱>\`)注入请求头;它没有-任何输入动作,装入确认框如实告知"将使用你的登录邮箱"。+任何输入动作,插件详情会如实告知"将使用你的登录邮箱"。未登录 / 登录态没有邮箱时 cindy.fetch 返回带重登指引的结构化错误,把 message 原样告诉用户即可。注意:声明了 login-email 就不要再写 \`url\`(没有"前往控制台"可去)也不要配 \`exchange\`(登录邮箱不外送交换端点),两者校验都会拒。你的 settingsHtml可经 \`fetch('/secrets')\` 查回该凭证的 \`{ key, saved, identity }\`(identity =当前登录邮箱,拿来只读展示"用的是哪个身份";未登录时 saved:false 无 identity,-照"请重新登录"画)——确认框已如实披露,除展示外别拿它做别的;对该 key 的+照"请重新登录"画)——详情页已如实披露,除展示外别拿它做别的;对该 key 的PUT/DELETE 一律 405(派生身份不可配置)。**GitHub CLI 优先凭证(source:"gh-cli",保留能力)**:仅官方 \`cindy-github\`@@ -2930,16 +2971,13 @@ PAT;页面可据此展示“已检测到 gh,可直接使用”,但不能\`Authorization: Bearer {value}\`,不允许 exchange,也不要放进 \`setup.requires\`。**Cindy 企业身份断言(source:"oidc-token",可选)**:适用于接入 Cindy Connection-Auth 的企业服务。主机只在当前登录账号属于组织 Membership,并且满足下面两条基座-之一时,按需向 auth-server 换取短时 Connection JWT:-1. 当前组织的 Plugin Market organization 安装记录(source 必须是服务端 \`market\`),- 安装 manifest digest 未被篡改,并声明了目标服务域名;或-2. **组织身份 + 本组织已登记前缀 + 插件 id 命中 \`<前缀>-\` + 经 ghost forge 装入- (receipt 为 agent-forge) + 批准记录中保有有效的 packageSha256 来源指纹**。+Auth 的企业服务。主机只在当前登录账号属于组织 Membership、且该插件拥有当前组织的+Plugin Market organization 安装记录(source 必须是服务端 \`market\`)、安装 manifest+digest 未被篡改并声明了目标服务域名时,按需向 auth-server 换取短时 Connection JWT。audience 与组织身份由主机推导,插件清单和运行时代码都不能选择、读取或保存audience/token;audience 固定为 \`\${orgSlug}:\${ghostId}\`,总长不得超过 64 字符。-这两条组织基座都不适用于个人身份或手动装入;其中 forge 基座还要求命中当前组织-前缀。它们只给 Broker 与 oidc-token,不给宿主原语。该凭证必须固定声明+该组织市场基座不适用于个人身份或本地装入,只给 Broker 与 oidc-token、不给宿主原语。+该凭证必须固定声明\`"inject": { "header": "Authorization", "format": "Bearer {value}", "hosts": [...] }\`,且 \`hosts\` 必须是非空的显式子集,只允许把断言发给列出的企业服务域名。\`oidc-token\` 的 \`inject.hosts\` 只接受精确域名,不允许 \`*.example.com\` 通配;Host@@ -2974,7 +3012,7 @@ settingsHtml 里自填**(用户用自己注册的 OAuth 应用,配额风控归要如实提示。settingsHtml 里经 \`/oauth\` 协议通道完成收单与连接:\`\`\`js-// 状态回查(哪些 oauth 凭证槽、client 配没配、连了哪些账号;零令牌字节):+// 状态回查(哪些 oauth 凭证项、client 配没配、连了哪些账号;零令牌字节):const list = await (await fetch('/oauth')).json();// → [{ key:'acct', clientConfigured:true, clientCustom:false, accounts:[{ id, label, status:'connected'|'expired', isDefault, createdAt, avatarDataUrl, scopeStale }] }]// avatarDataUrl = 头像 data URL(声明了 identity.avatarPath 且主机下载成功才有,否则 null;<img src> 直接用)@@ -2992,7 +3030,7 @@ const r = await (await fetch('/oauth/acct/connect', connectInit)).json();// NETWORK = 客户端无法连接授权服务,提示用户检查网络后重试;// SERVICE_UNAVAILABLE = broker 路由缺失或服务端 5xx,提示用户稍后重试。// 授权成功时主机会自动弹「授权成功,已连接 xxx」的系统提示(带你的身份头,-// 无需声明 notify 槽);设置页只管刷新自己的账号列表。+// 无需声明 notify);设置页只管刷新自己的账号列表。// 断开账号 / 设默认账号:await fetch('/oauth/acct/accounts/<accountId>', { method:'DELETE' }); // 204(幂等)await fetch('/oauth/acct/default', { method:'POST', body: JSON.stringify({ accountId }) }); // 204@@ -3003,13 +3041,13 @@ await fetch('/oauth/acct/default', { method:'POST', body: JSON.stringify({ accouawait fetch('/oauth/acct/insufficient-scopes', { method:'POST', body: JSON.stringify({ scopes:['write.b'] }) }); // 204\`\`\`-多账号:每个 oauth 凭证槽最多 8 个账号;cindy.fetch 可带 \`authAccount: '<账号id>'\`+多账号:每个 oauth 凭证项最多 8 个账号;cindy.fetch 可带 \`authAccount: '<账号id>'\`指定用哪个账号的令牌(缺省 = 默认账号)。同一身份重复授权 = 重连:授权回来的身份标签(identity.labelPath 的值)与已连账号相同时,主机覆盖那条的令牌并复活状态,不新增占位——账号 id 稳定,你缓存的 authAccount 不会因用户重连而失效。声明了identity.displayTemplate 时,\`/oauth\` 回查与连接结果里 account.label 给的是渲染后的展示名(合并判定仍按 labelPath 的稳定值,展示名变了不会堆出新账号行)。规则:authorizeUrl / tokenUrl / identity.url-的域名都必须命中 hosts 白名单(装入确认框会展示"将引导你在 <授权域名> 完成授权"+的域名都必须命中 hosts 白名单(插件详情会展示"将引导你在 <授权域名> 完成授权"+ scopes 全量清单,用户知情放行);oauth 与 exchange 互斥;声明 oauth 凭证必须同时声明 settingsHtml(没人收 client 凭证就没人能连接)。账号授权失效(AUTH_EXPIRED)时 cindy.fetch 返回带指引的结构化错误,原样转告用户去设置页重新连接即可。@@ -3021,12 +3059,11 @@ identity.displayTemplate 时,\`/oauth\` 回查与连接结果里 account.label即可;第一方官方内置意识会先自动结束占用进程并重试,第三方意识不享受此回收——请选一个不易撞车的端口)。声明 \`tokenBroker\` 时必须提供;非 broker 模式下,Google 这类允许任意 loopback 端口的服务商不用声明。-- \`tokenBroker\`:资格有三路:①静态官方前缀命中,照旧放行;②当前组织的服务端+- \`tokenBroker\`:资格有两路:①静态官方前缀命中,照旧放行;②当前组织的服务端organization market 包已安装、source 为 \`market\`、organizationId 与当前组织一致,- id 命中本组织已登记前缀,且 release sha256 与批准 receipt 的 packageSha256 相等;- ③当前组织身份下经 ghost forge 装入(receipt 的- installOrigin 为 \`agent-forge\`),且 id 命中本组织已登记前缀。第 2、3 条新增基座- 不接受手动装入、个人身份或别的组织前缀,且只给 Broker 与 oidc-token,不给宿主原语。+ id 命中本组织已登记前缀,且 release sha256 与批准 receipt 的 packageSha256 相等。+ 组织市场基座不接受本地装入、个人身份或别的组织前缀,且只给 Broker 与+ oidc-token,不给宿主原语。code/refresh 交换改经 Cindy 服务端 broker 完成,client secret 由服务端持有、不随包分发,且要求用户已登录 Cindy。声明它时必须同时声明 redirectPort,并与 clientSecret互斥;PKCE 缺省开(verifier@@ -3164,7 +3201,7 @@ await fetch('/connections/gitlab/default', { method: 'POST', body: JSON.stringif上限:connections 声明 ≤2 条;每条声明下用户可添加 ≤8 条连接(作者可用maxConnections 收紧到 1–8);token ≤4096 字符。新连接添加成功时主机会自动-弹「连接地址已添加」的系统提示(带你的身份头,无需声明 notify 槽)。+弹「连接地址已添加」的系统提示(带你的身份头,无需声明 notify)。其它硬边界:每意识同时在途 4 个请求;媒体取件/上传共用全局串行闸,同时只处理一单(忙时返回结构化"正忙",稍后重试即可);重定向最多 3 跳且逐跳重验@@ -3264,15 +3301,15 @@ $('#save').onclick = async () => {这个事件,也不需要你写任何完成回调;\`/oauth\`、\`/kv\`、\`/secrets\`、\`/connections\` 保存成功后,主机会重新读取真实状态并自动更新卡片、继续原工具调用。-## 4.9 系统提示(notify 槽)+## 4.9 系统提示(notify 能力)-声明 \`"slots": [..., "notify"]\` 后,电子脑可以请主机在屏幕顶部弹一条轻提示(toast)+声明 \`"notify": true\` 后,电子脑可以请主机在屏幕顶部弹一条轻提示(toast)——适合"没有在途调用、面板也没开着,但有事想轻声告诉用户"的场景:分钟级长任务完成了、授权快过期了、旁听到值得提醒的事。\`\`\`jsconst r = await cindy.send({ type: 'notify', text: '视频已生成,点面板查看', tone: 'success' });-// r = { ok: true } 或 { ok: false, message: '原因'(被限速/超长/未声明槽等) }+// r = { ok: true } 或 { ok: false, message: '原因'(被限速/超长/未声明能力等) }\`\`\`规则(都由主机强制,写错拿到的是结构化拒绝):@@ -3286,20 +3323,20 @@ const r = await cindy.send({ type: 'notify', text: '视频已生成,点面板查- **身份头主机画**:提示上自动带你的图标和名字,冒充不了主机通知、也冒充不了别的意识;正文里不用再自报家门;- 提示自动消失、无按钮、无回执——**不是确认框**。要用户点「同意/取消」并把答案交回- 给你,用 §4.18 的 confirm 槽(主机同款确认框);要在聊天流里放按钮用交互卡+ 给你,用 §4.18 的 confirm 能力(主机同款确认框);要在聊天流里放按钮用交互卡(§4.5 的 data-ghost-action)。-### 4.9.1 未读角标(badge 槽 —— 与 notify 槽并列的独立一档)+### 4.9.1 未读角标(badge —— 与 notify 并列的独立一档)toast 是"说一句就走",错过就没了。要留下一条**持久**的"我这儿有新内容"——用户没去看就一直亮着——在身份卡里加一档:\`\`\`json-{ "slots": ["panel", "badge"] }+{ "panel": { "title": "最新内容", "html": "panel.html" }, "badge": true }\`\`\`-\`badge\` 与 \`notify\` 是**并列的两档权限**,谁也不是谁的前置。只想安静点个绿点就-别申请 \`notify\` 槽——多要一档"能弹全屏顶部提示"的权限,用户装的时候只会更犹豫。+\`badge\` 与 \`notify\` 是**并列的两档能力**,谁也不是谁的前置。只想安静点个绿点就+别申请 \`notify\`——不要让能力清单比实际需求更重。两个都要就两个都声明。\`\`\`js@@ -3313,8 +3350,8 @@ await cindy.send({ type: 'badge', unread: false });- **必须同时声明 \`panel\`**,装入时校验,漏了整个包装不进去。这是本档唯一的门槛:未读点承诺"点开能看到内容",没有面板的意识点亮了也无处可点,给了就是骗点击;-- 装入确认框里**单列一项**权限,已装插件加这一档会触发扩权重新确认——常驻的- 注意力入口值这一次打断;+- 插件详情里**单列一项**能力;市场更新新增这一档时会随新版清单展示,Host 只按+ 实际声明兑现;- \`summary\`(可选):**纯文本**,≤80 字符,换行会被坍缩成空格,超长直接拒(\`ok:false\`,不静默截断);净化后为空按"没给摘要"处理,点照亮;- **限速**只挡点亮方向:同一意识两次点亮最小间隔 500 毫秒;\`unread:false\` 的@@ -3326,11 +3363,16 @@ await cindy.send({ type: 'badge', unread: false });- 角标**不出声、不震动、不进系统通知中心**——它只是屏幕内的一颗点;- 状态跨重启存活,按账号隔离(账号 A 的未读不会在账号 B 的界面上亮)。-## 4.10 写文件(fs 槽)+## 4.10 写文件(fs 能力)-声明 \`"slots": [..., "fs"]\` 后,电子脑可以请主机代写文件(创建/覆盖)。沙箱本身-仍然没有文件系统——字节永远由主机落盘,这个槽是"申请主机代写"的资格。装入-确认框会如实展示"可写入文件",没声明就调用只会拿到结构化拒绝。+沙箱本身没有文件系统,字节始终由主机落盘。三档目的地的声明边界不同:++- \`root:'workdir'\`:当前 Agent tool-call 内传 \`callId: msg.callId\` 即可按会话+ permission mode 写入,不需要 \`"fs": true\`。+- \`root:'save'\`:授权是主 Agent 发放的限时、限次、绑定插件票据,不需要+ \`"fs": true\`。+- \`root:'data'\`:这是插件脱离当前 Agent 调用仍可持久读写的私有目录,+ 属于自主 Host 能力;使用它才声明 \`"fs": true\`,并在插件详情如实展示。\`\`\`js// 写自己的私有数据目录(免确认;适合缓存、大结果落盘、跨生命周期状态)@@ -3383,9 +3425,9 @@ await cindy.fs({ op: 'write', root: 'data', path: 'a.txt', content: 'hi' });想拿二进制回传 \`encoding:'base64'\`);单次写入上限 16MB,超了拆多个文件;- 符号链接一律不穿透:目标是 symlink、或路径经 symlink 逃出根目录,直接拒。-### 4.10.1 持久作品库(library 槽)+### 4.10.1 持久作品库(library 能力)-声明 \`"slots": [..., "library"]\` 后,你获得一个**用户作品级**的持久存储区——+声明 \`"library": true\` 后,你获得一个**用户作品级**的持久存储区——和 fs 槽的私有储物柜(256MB 配额、卸载即回收)是两个语义:Library 不受配额约束(只受磁盘水位约束),**卸载插件不删数据**(用户必须在 Cindy 设置里单独确认才删除)。适合画布、素材库、项目文件这类"用户会心疼"的数据。@@ -3451,9 +3493,9 @@ await cindy.library({ op: 'db.check', dbPath: 'library.sqlite' }); // quick_ch\`write\`/\`writeCommit\`/\`read\` 都回 \`sha256\`(宿主对实字节计算)——外自称的哈希只当对账参考,不是凭证。-## 4.11 发起 Agent 新回合(agent 槽)+## 4.11 发起 Agent 新回合(agent 能力)-这个槽让你的 \`main.js\` 把一段文字作为**普通用户消息**交给 Cindy Agent,适合+这个能力让你的 \`main.js\` 把一段文字作为**普通用户消息**交给 Cindy Agent,适合“用户在插件卡片上点继续,然后 Agent 接着做”的流程。它不是系统提示词,也不会修改该会话里其它插件或 Agent 的长期规则。@@ -3513,7 +3555,7 @@ await cindy.agent.run({\`agent.run\` 把回合发进**用户的会话**,结果是给用户看的;派活(errand)相反:任务在**你的专属 errand 会话**里跑,Agent 的最终回复文字交回**你**手里继续用。-需声明 \`"slots": [..., "agent"]\` + \`"agent": { "errand": true }\`(装入确认高风险单列)。+需声明 \`"agent": { "errand": true }\`(插件详情高风险单列)。\`\`\`js// 提交(默认异步:先拿单号,再轮询取件——Agent 干活是分钟级的):@@ -3549,7 +3591,7 @@ const q = await cindy.agent.queryErrand({ jobId: r.jobId });权限档;- 目录有一个受控例外:run 请求可带 \`workingDir\`(绝对路径)**转述**一个目录,让 errand 会话建在项目里(Agent 能看到代码)。这不是授权——主机只认用户- 此前在 pick 槽(§4.14)系统选目录窗口里**亲手选过**的目录(主机自己记的+ 此前用 pick 能力(§4.14)在系统选目录窗口里**亲手选过**的目录(主机自己记的台账),别的路径一律 \`INVALID_REQUEST\`,此时应引导用户去你的设置页重新选一次目录;用户在「AI 代办」卡里配置了目录时,以用户配置优先、本字段忽略;- 每插件同时 1 单在途、相邻提交至少隔 10 秒;结果超过 64K 字符会截断(尾部带@@ -3584,10 +3626,11 @@ const q = await cindy.agent.queryErrand({ jobId: r.jobId });7. 用户回来点开面板,看到刷新后的内容。所以你需要的是三样东西的组合:\`agent.schedule\` 加档(第 2 步)+ 一个 \`tool\`(第 5 步)-+ \`badge\` 槽(第 6 步)。三者缺一,回路就断在那里。++ \`badge\` 能力(第 6 步)。三者缺一,回路就断在那里。-需声明 \`"slots": [..., "agent", "tool", "badge"]\` + \`"agent": { "schedule": true }\`-(装入确认里单列一档,文案会告诉用户"任务由你亲手保存、跑起来会产生模型费用")。+需声明至少一个 \`tools\` 条目、\`"agent": { "schedule": true }\`、\`"badge": true\`+以及 badge 所需的 \`panel\`(插件详情里单列一档,文案会告诉用户+"任务由你亲手保存、跑起来会产生模型费用")。\`\`\`js// 用户在面板上点了「提醒我」之后:@@ -3637,9 +3680,14 @@ const r = await cindy.agent.requestSchedule({什么时候**不该**用它:一次性的、当场就要结果的事,用快问快答(§4.0.2)或派活取件(§4.11.1)。这个加档是给"长期定期刷新"用的,每条任务都会反复产生模型费用。-## 4.12 随包 Node 工作进程与 stdio MCP(node 槽)+## 4.12 随包 Node 工作进程与 stdio MCP(node 能力)++插件需要随包代码、CLI、JS 依赖、可复用 worker 状态或 stdio MCP 时,使用顶层+\`node\` 字段描述现有 Node 工作进程。这里不再有 \`node\` Slot,也不要求客户端+预登记某个具体 CLI;Agent 发起插件工具调用时,是否运行由外层 \`ghost_call\`+的既有授权系统决定。-\`main.js\` 永远还是浏览器沙箱代码。声明 node 槽后,主机额外为**这一段意识**按需+\`main.js\` 永远还是浏览器沙箱代码。声明 node 后,主机额外为**这一段意识**按需启动一个独立 Node 进程;同一插件的多个会话复用它,不同插件绝不共用进程。通信链固定为:\`\`\`@@ -3648,7 +3696,8 @@ Node worker ↔ JSON-RPC stdio ↔ 你的 main.js ↔ Cindy 主机能力Node 不能直接拿到 \`cindy\`、Electron IPC 或 Agent 会话。它向主机发反向 JSON-RPC请求时,主机会固定返回 \`-32601\`;需要 Cindy 能力时,Node 先把数据回给 \`main.js\`,-再由 \`main.js\` 调自己已声明的 cindy / agent / network / fs 等槽,主机照常逐项验权。+再由 \`main.js\` 调 Cindy 通道。插件自主调用继续按 manifest 验权;当前+Agent tool-call 内的网络与 workdir 操作按 §4.2 复用 Agent 授权。### 4.12.1 自定义 Node 服务(JSON-RPC stdio)@@ -3726,7 +3775,7 @@ const authorizationCode = request.cindy.secrets.mail_code;\`GET /secrets\` 的 saved 状态引导用户;- 宿主不会直接把明文交给 \`main.js\`、Agent 参数或写入宿主日志;但 Worker收到明文后可以主动回传、落盘或写日志,浏览器侧代码和 Agent 也可能因此间接- 获得它。安装/更新权限清单会逐条披露此风险,只安装可信来源插件;+ 获得它。插件详情的能力清单会逐条披露此风险,只安装可信来源插件;- Worker 用完不要缓存、落盘、回传或写日志;每次请求都以\`request.cindy.secrets\` 的当次值为准;- \`node.secretBindings\` 与 \`network.secrets\` / \`network.connections\`@@ -3795,7 +3844,7 @@ const called = await cindy.node.request({\`\`\`MCP server 的 sampling / elicitation / roots 等 server→client 反向请求第一版不开放;需要-这类能力时仍按“结果回 main.js,再由 main.js 申请 Cindy 槽”的链路设计。+这类能力时仍按“结果回 main.js,再由 main.js 申请 Cindy 能力”的链路设计。### 4.12.3 打包和生命周期红线@@ -3805,15 +3854,14 @@ MCP server 的 sampling / elicitation / roots 等 server→client 反向请求- Forge 会跳过 \`node_modules\`,推荐用 esbuild/rollup 预打包成 \`worker.cjs\`。Node 包最多 2048 个文件、解压后 256MB、.cindy 128MB;超限直接拒绝;- \`on-demand\` 首次 \`cindy.node.request\` 才启动,缺省空闲 120 秒关闭;停用、更新、- 卸载、退出 Cindy 都立即关闭。\`resident\` 会随插件启用一直运行,安装确认里单独显示;+ 卸载、退出 Cindy 都立即关闭。\`resident\` 会随插件启用一直运行,详情页单独显示;- 每个插件最多 32 条在途请求;单次 params 256KB、单行 stdout 1MB。单次请求缺省30 秒、上限 120 秒;长任务用 maxTotalMs 开启"有动静就续期",绝对上限 15 分钟(见 §4.12.1)。进程崩溃只影响自己,所有在途请求收到结构化失败,下次请求可重新启动;- **最重要的安全事实**:Node 进程不是浏览器沙箱,它拥有当前登录系统账号能拿到的- 本机权限,能读写文件、联网、起别的进程。安装时先展示权限清单,真正写盘前还会- 由 Cindy 主进程弹出一次系统级强风险确认;- 不需要本机能力的插件不要申请 node 槽。+ 本机权限,能读写文件、联网、起别的进程。Cindy 会在插件详情中显著展示这项能力,+ 但安装不会追加确认弹窗;不需要本机能力的插件不要声明 node,用户也只应安装可信来源。### 4.12.4 宿主代启子进程(childSpawn)@@ -3858,10 +3906,10 @@ const maker = require('@taptap/maker'); // 之后它的自启动全部走了正但**只适合文本/协议流**,别拿它传大文件;- 级联生死:worker 退出/被停/插件停用,子进程一并收掉,不留孤儿。-## 4.13 会话上下文(session-context 槽)+## 4.13 会话上下文(sessionContext 能力)围着用户项目干活的插件(构建/检查/同步类)需要知道"现在是哪个会话、项目在哪个-文件夹"。声明 \`session-context\` 槽后,agent 派活(tool-call)时主机把**宿主铸造**+文件夹"。声明 \`"sessionContext": true\` 后,agent 派活(tool-call)时主机把**宿主铸造**的上下文注入 \`args.session_context\`:\`\`\`js@@ -3885,23 +3933,23 @@ cindy.onHostMessage(async (msg) => {目录可能存在,写下去就是事故;- \`workdir_is_read_only\` 来自宿主对会话 permission / plan 状态的统一裁决;为 \`true\` 时只允许检查、列举等只读操作,不得初始化、构建或以其它方式修改 workdir;-- 这只是"位置信息",不是文件访问权:读写仍走 fs 槽 / node 槽各自的守门;-- 未声明本槽的插件,args 里永远没有 \`session_context\` 字段。+- 这只是"位置信息",不是文件访问权:读写仍走 fs / node 各自的守门;+- 未声明本能力的插件,args 里永远没有 \`session_context\` 字段。-## 4.14 目录选择(pick 槽)+## 4.14 目录选择(pick 能力)-需要用户交一个文件夹进来(导入/同步/部署源)时,声明 \`pick\` 槽,经管子请主机+需要用户交一个文件夹进来(导入/同步/部署源)时,声明 \`"pick": true\`,经管子请主机弹**系统级**选文件夹窗口——用户亲手选中即授权,取消则你什么都拿不到:\`\`\`jsconst picked = await cindy.pick({mode: 'directory',title: '选择要同步的项目父目录', // 净化后随插件名一起展示(≤80 字)- deposit: true // 需要过户票据(上传用)时带;声明了 node 槽可省+ deposit: true // 需要过户票据(上传用)时带;声明了 node 可省});if (picked.ok) {// picked.name —— 所选目录名(展示用)- // picked.path —— 绝对路径,仅声明了 node 槽的插件有(交给 Node 侧干活)+ // picked.path —— 绝对路径,仅声明了 node 的插件有(交给 Node 侧干活)// picked.dir_deposit —— 过户票据(同 ghost_call dir 通道;deposit:true 才有)}\`\`\`@@ -3911,18 +3959,18 @@ if (picked.ok) {- 对话框由主机拼装并带你的插件名,\`title\` 只是用途说明片段,伪装不了主机文案;- 同一插件两次请求最小间隔 3 秒、全局同时只有一个选择框(超了回 RATE_LIMITED /BUSY);用户取消回 CANCELLED——**尊重取消,不要循环重弹**,那是骚扰;-- 未声明 node 槽的插件必须 \`deposit: true\`(没有票据你什么都拿不到,请求会被拒);+- 未声明 node 的插件必须 \`deposit: true\`(没有票据你什么都拿不到,请求会被拒);票据收集有上限(500 文件/单文件 50MB/总 500MB),超限会签发失败;-- \`path\` 只发给声明了 node 槽的插件:Node 侧本就有用户级本机权限,给路径不扩权,+- \`path\` 只发给声明了 node 的插件:Node 侧本就有用户级本机权限,给路径不扩权,价值是把"用户选了哪个目录"这一事实可信地交过去;- 用户每次亲选成功,主机自己也会记一笔「亲选目录台账」(每插件最近 8 条)——派活(§4.11.1)的 \`workingDir\` 转述只对台账里的目录放行。台账建立在真实点选上,你存在 /kv 里的路径不算数。-## 4.15 面板预览(preview 槽)+## 4.15 面板预览(preview 能力)-部署预览、本地 dev server、控制台面板这类"给用户看个网页"的需求,声明 \`preview\`-槽 + \`preview.hosts\` 白名单(见 §2),运行期请主机在右侧栏内置浏览器开标签:+部署预览、本地 dev server、控制台面板这类"给用户看个网页"的需求,声明+\`preview.hosts\` 白名单(见 §2),运行期请主机在右侧栏内置浏览器开标签:\`\`\`jsconst opened = await cindy.preview({@@ -3936,16 +3984,16 @@ if (!opened.ok) console.warn(opened.errorCode, opened.message);- URL 必须命中装入时钉死的 \`preview.hosts\` 白名单:只收 https(http 仅限localhost / 127.0.0.1 本地开发),不收 URL 内嵌凭证;范围外回 URL_NOT_ALLOWED,- **改白名单只能发新版本重新过装入确认**;+ **改白名单只能发新版本;市场安装会自动更新,本地包需重新导入新版**;- 同一插件两次打开最小间隔 5 秒(RATE_LIMITED)——预览是"结果亮相",不是刷屏通道;- 每次打开,宿主都会弹带你身份头的提示("xxx 打开了一个预览页面"),用户永远知道页面是谁开的;- 标签开在用户自己的右侧栏浏览器里,关不关、看不看由用户决定。-## 4.16 捆绑 Agent Skills(skill 槽)+## 4.16 捆绑 Agent Skills(skill 能力)-插件随包 Skill **当前已停止新增,未来计划全部废弃**。新插件不要声明 \`skill\` 槽+插件随包 Skill **当前已停止新增,未来计划全部废弃**。新插件不要声明 \`skill\` 字段或新增 \`skill.items\`。迁移时按职责映射,不是按篇幅搬运:- Skill frontmatter 的 \`name + description\` 所承担的身份/召回作用,对标系统提示词区@@ -3976,7 +4024,7 @@ my-ghost/SKILL.md 硬规则(打包与装入双侧强制,任一不满足直接拒):- frontmatter 的 \`name\` / \`description\` 必须与 \`skill.items\` 声明**逐字一致**- ——装入确认框展示的是清单声明,Agent 读到的是 SKILL.md,两者必须是同一份事实;+ ——插件详情展示的是清单声明,Agent 读到的是 SKILL.md,两者必须是同一份事实;- \`name\`:小写字母/数字加单连字符分段(禁首尾/连续连字符),≤64 字符;- SKILL.md 单文件 ≤64KB;items 最多 4 条。@@ -4003,16 +4051,16 @@ SKILL.md 硬规则(打包与装入双侧强制,任一不满足直接拒):信任与作用域(如实告知用户,也请作者自重):- 技能指令由**主 Agent 以用户全部权限执行**,对所有项目、所有会话生效,- **不受插件沙箱约束**——这是二十个卡槽里信任面最高的能力,装入确认框会把+ **不受插件沙箱约束**——这是插件能力里信任面最高的一档,插件详情会把每个技能置顶逐条列出;- 技能跟随插件的**全局**启用状态:仅在某个工作目录停用插件**不会**隐藏技能,只有全局停用或卸载才撤链(本期只有全局作用域);- \`skill.items\` 的字段不参与 locales 本地化(必须与 SKILL.md 逐字一致,而SKILL.md 只有一份)。-## 4.17 创建工作区会话(workspace 槽)+## 4.17 创建工作区会话(workspace 能力)需要把某个项目目录变成侧边栏里的会话入口("打开项目"/仓库列表这类场景)时,-声明 \`workspace\` 槽,经管子请主机**确保**该目录下存在一个会话:目录下已有+声明 \`"workspace": true\`,经管子请主机**确保**该目录下存在一个会话:目录下已有active 会话直接复用(created:false),没有才创建一个空会话,创建/命中后显示在侧边栏对应工作区分组里。@@ -4056,11 +4104,11 @@ const ensured = await cindy.workspace({- 同一插件两次请求最小间隔 3 秒、全局同时只有一个窗口/确认卡在场(RATE_LIMITED /BUSY);- 创建的是**空会话**:不拉起 agent、不发消息、不自动开始任何任务;要让 Agent- 立即干活请配合 agent 槽(§4.11)。+ 立即干活请配合 agent 能力(§4.11)。-## 4.18 确认弹窗(confirm 槽)+## 4.18 确认弹窗(confirm 能力)-动手之前要用户点头(切分支、覆盖文件、发不可撤回的东西)时,声明 \`confirm\` 槽,+动手之前要用户点头(切分支、覆盖文件、发不可撤回的东西)时,声明 \`"confirm": true\`,经管子请主机弹一个**和 Cindy 自己一模一样**的确认框,并拿回用户的真实点击:\`\`\`js@@ -4101,19 +4149,18 @@ if (r.ok && r.confirmed) {工作区干不干净)确认前后都要自己再查一遍**——用户点确认和你真动手之间,世界可能已经变了。-## 4.19 内置 iOS 模拟器(ios-simulator 槽)+## 4.19 内置 iOS 模拟器(iosSimulator 能力)-要给插件提供内置 iOS 模拟器的状态入口或工作流面板时,声明 \`ios-simulator\` 槽。+要给插件提供内置 iOS 模拟器的状态入口或工作流面板时,声明 \`"iosSimulator": true\`。电子脑只能读取**当前台前任务**的公开状态,并请求主机打开 Cindy 自己的模拟器面板:-标准产品形态只需 \`skill + ios-simulator\`:Host 会在任务右侧栏提供手动入口,+标准产品形态只需 \`skill + iosSimulator\`:Host 会在任务右侧栏提供手动入口,Agent 通过 Skill 调 Host MCP。不要为了重复同一状态再声明 \`panel\`;插件停靠面板的关闭语义是停用整份插件,不适合作为模拟器 viewer 的替身。只有确实存在 Host viewer 没有的独立工作流 UI 时才额外声明 panel。-声明 \`ios-simulator\` 时必须同时声明 \`minCindyVersion\`,取首次提供该 Host 能力的 Cindy-正式版本。它用于让旧版 Host 把插件识别为“需要更新 Cindy”,而不是“插件非法”;不要填写-当前开发环境版本,也不要用它替代下面的运行时 capability 检查。+如果插件整体离开 \`iosSimulator\` 就无法完成任何工作,应把 \`minCindyVersion\` 提高到首次+满足整体使用要求的 Cindy 正式版本。不要用最低版本替代下面的运行时 capability 检查。\`\`\`jsconst caps = await cindy.iosSimulator.request({ kind: 'capabilities' });@@ -4142,31 +4189,30 @@ const opened = await cindy.iosSimulator.request({或跨任务 instanceId 都会拒绝。切到非任务页、远程/SSH 任务或任务失效时 fail closed;- \`status\` 只返回环境是否就绪、可用设备数量、公开实例状态和当前 stream/input 路线。它不续租、不启动 driver,也不返回 UDID、路径、授权、诊断或 ownership 信息;-- 本槽不是模拟器运行时:WDA、Native Sidecar、H.264、Native HID、生命周期、恢复与+- 本能力不是模拟器运行时:WDA、Native Sidecar、H.264、Native HID、生命周期、恢复与fallback 仍由 Cindy Host 独占。插件拿不到视频帧、viewer lease、触控入口、进程句柄、artifact 路径或 Xcode 私有诊断;- \`open-panel\` 只打开/聚焦 Host 既有面板。没有绑定实例时可省略 instanceId,让用户在 Host 面板里选择设备;连续请求会限速;-- panel.html 保持零桥。面板要使用本槽时,按 §5 先 \`/wake\`,再用同源+- panel.html 保持零桥。面板要使用本能力时,按 §5 先 \`/wake\`,再用同源BroadcastChannel 把请求交给 main.js,由 main.js 调 \`cindy.iosSimulator.request\`;- 插件 Skill 选择内嵌路线后,Agent 构建、安装、启动与 UI 操作调用 Host 注册的\`cindy_ios_simulator\` MCP,不要重复打包一份 WDA/Sidecar。内嵌能力不存在或不可用时,Skill 可以按用户目标与普通权限规则改走外部 Xcode、Simulator.app、\`simctl\` 或Computer Use;Host 不会把这些外部操作自动转换为内嵌调用;-- 本能力仅存在于带该槽的 Cindy Desktop。当前 Host 遇到未来 schema 或未知 capability- slot 时会把包识别为“需要更新 Cindy”,而不是误报插件非法。已发布的旧 Host 无法追改;+- 本能力仅存在于支持并授权 \`iosSimulator\` 字段的 Cindy Desktop。未知 v3 顶层字段会被+ 保留,但不会因此获得 Host 权限;依赖新字段的插件必须用 \`minCindyVersion\` 标明最低版本。Skill 在 MCP 不存在时必须说明内嵌路线不可用;如果用户目标不依赖 Cindy viewer,可以继续使用正常的外部工具链,否则再引导用户升级 Cindy。-## 4.20 一级主视图(main-view 槽)+## 4.20 一级主视图(mainView 能力)-插件需要一个从 Cindy 一级侧边栏进入的完整页面时,声明独立的 \`main-view\` 槽。下例-\`1.2.3\` 只演示 SemVer 格式,不代表 main-view 的首发版本已经裁决:+插件需要一个从 Cindy 一级侧边栏进入的完整页面时,直接声明 \`mainView\`:\`\`\`json{- "minCindyVersion": "1.2.3",- "slots": ["main-view"],+ "schemaVersion": 3,+ "minCindyVersion": "0.1.61","mainView": {"title": "工作台","icon": "puzzle",@@ -4182,14 +4228,12 @@ const opened = await cindy.iosSimulator.request({替代或修改根级 \`icon\` 品牌图片。可用值与 Cindy 系统图标名完全一致:\`puzzle\`、\`globe\`、\`code\`、\`folder\`、\`database\`、\`chart-column\`、\`image\`、\`message-circle\`、\`calendar-days\`;不接受别名、任意图标名或图片路径;-- \`main-view\` 与 \`panel\` 是两种独立权限。可以让两者指向同一 HTML,但必须分别- 申请 slot;主视图不接受 position、宽度或 systemButtons;-- 声明该槽必须同时声明 \`minCindyVersion\`,填写首个正式提供 main-view Host 能力的- Cindy 版本。不要填写当前 \`0.0.0\` 开发版本,也不要在正式发布版本尚未裁决时猜测;+- \`mainView\` 与 \`panel\` 是两种独立 UI 贡献项。可以让两者指向同一 HTML,但必须分别+ 声明;主视图不接受 position、宽度或 systemButtons;- 插件批准并启用后,入口默认显示。用户可以在插件详情关闭“显示在侧边栏”;这只隐藏导航入口,不停用插件,也不关闭 tool、network、panel 或后台能力;- 主视图与 panel 共用同一 Ghost WebView 沙箱:零 Node、零通用 preload、每插件专属- partition、CSP 和导航守门不变。\`main-view\` 本身不附赠联网、文件、凭证或其它能力;+ partition、CSP 和导航守门不变。\`mainView\` 本身不附赠联网、文件、凭证或其它能力;- 页面需要电子脑逻辑时仍先 \`fetch('/wake')\`,通信和媒体协议与 §5 完全相同。插件停用、卸载或失去批准后,Host 会卸载页面并退出该路由。@@ -4200,8 +4244,9 @@ const opened = await cindy.iosSimulator.request({用户想放右边可自己拖拽换位);\`"tab"\` = **插件页内的独占面板**——由插件页自己承载(不进右侧栏页签容器):用户在插件页点你这张卡的「使用」按钮打开,同一时刻至多一个,**用户离开插件页即关闭卸载**(面板收束,2026-08-02 定案:- 插件面板不再常驻右侧栏干扰其它会话)。装入时勾选「立即开启并打开面板」会- 在装完后进入插件页并打开你的面板;不勾选则由用户之后自己从插件页点「使用」。+ 插件面板不再常驻右侧栏干扰其它会话)。从插件页导入 tab 型插件后,宿主会+ 直接启用并打开它的面板;从拖入或双击等其它入口安装后,用户可再从+ 插件页点「使用」打开。停用/卸载插件同样立即关闭面板。页签形态没有拖缝宽度语义,声明 \`minWidth\` /\`defaultFraction\` 会被拒装。两种形态的面板代码完全一样(同一 panel.html,供片/主题/媒体规则不变),只是宿主容器不同;此形态请把界面做成自适应宽度,@@ -4254,13 +4299,14 @@ const opened = await cindy.iosSimulator.request({## 6. 沙箱红线(平台结构保证,写了也没用)- **本节说的是 main.js 浏览器电子脑**:它无文件系统、无 Node API、默认无网络——- 即使另申请 node 槽,Node 也在独立进程里,只能经 §4.12 的 stdio 与 main.js 交换数据,+ 即使另声明 node,Node 也在独立进程里,只能经 §4.12 的 stdio 与 main.js 交换数据,不会把 require/process 等能力注入 main.js。想用 AI/出图走 cindy-request 求主机代办,- 想访问自带服务走 network 槽经主机代发(仅限详单白名单域名,见 §4.7),想落盘- 走 fs 槽请主机代写(仅限三档目的地,见 §4.10),沙箱内直连(fetch/XHR/- WebSocket)与直接读写磁盘永远不存在,声明了槽也一样——槽给的是"请主机- 代办"的资格,不是能力本身;-- 保险库里的凭证明文永不进沙箱:network 槽的 key 由主机保管注入,你的代码+ 随包代码与 CLI 走 §4.12 的 Node 工作进程,网络走 \`cindy.fetch\`,落盘走 \`cindy.fs\`;+ 是否需要 manifest 声明取决于是 Agent 在途调用还是插件自主调用,见 §4.2、+ §4.7 和 §4.10。沙箱内直连(fetch/XHR/+ WebSocket)与直接读写磁盘永远不存在,声明字段给的是"请主机代办"的资格,+ 不是能力本身;+- 保险库里的凭证明文永不进沙箱:network 的 key 由主机保管注入,你的代码读不回(主机 Setup 卡直接交保险库;settingsHtml 收单时明文只在录入瞬间路过你的页面,经 /secrets 交给主机即焚,之后同样拿不到;状态回查最多附尾 4 位指纹,重建不出值);@@ -4287,13 +4333,15 @@ const opened = await cindy.iosSimulator.request({Create a polished square app icon for a Cindy plugin named "{{name}}". Purpose: {{one-sentence purpose}}. Show one clear, original visual metaphor for that purpose. Use a clean geometric composition, a restrained natural color palette, high contrast, and a centered subject with generous safe padding so it remains readable at 32–48 px. Use one symbol only on a simple solid or transparent background. No text, letters, numbers, UI mockups, scenes, baked-in rounded corners, trademarks, copied brand shapes, watermarks, heavy gradients, inner shadows, or photorealism. Output a 1024×1024 PNG.\`\`\`- 只尝试一次。图片能力不可用、超时或失败时不要重试,直接调用- \`ghost_forge_pack({ dir })\`,保留占位图/宿主默认图标继续打包,不让图标阻塞用户。+ 只尝试一次。图片能力不可用、超时或失败时不要重试,保留占位图/宿主默认图标继续。+ 缺省调用 \`ghost_forge_pack({ dir })\`;只有用户已明确要求当前 Agent 直接安装时,才改调+ \`ghost_forge_install({ dir })\`,不要让图标阻塞用户。生成成功后,从图片工具结果的 \`xdt_image_url\` 取单张地址;如果结果只有\`xdt_image_urls\`,取数组第一项(例如 \`const selectedImageUrl = result.xdt_image_url ?? result.xdt_image_urls?.[0]\`)。- 仅当它是 \`cindy-media://\` 地址时,才把它原样交给- \`ghost_forge_pack({ dir, icon_source: selectedImageUrl })\`;主机会转成 1024×1024 PNG 并- 嵌入安装包。icon_source 处理失败时 pack 也会自动回退默认图标,不要再发起第二次生成。+ 仅当它是 \`cindy-media://\` 地址时,才把它原样交给本次要调用的终点工具:缺省为+ \`ghost_forge_pack({ dir, icon_source: selectedImageUrl })\`;用户已明确要求直接安装时为+ \`ghost_forge_install({ dir, icon_source: selectedImageUrl })\`。主机会转成 1024×1024 PNG+ 并嵌入安装包;处理失败时两种工具都会回退默认图标,不要再发起第二次生成。如果源码根目录已有 \`cindy-signatures.json\`,pack 会保留原图标和原签名,不做 AI图标覆盖;任何文件变更都必须交给发布流水线重新签名,不能静默降级信任等级。- **上传图片**:让用户提供图片,保存到 \`assets/icon.png\`,并同步把@@ -4314,17 +4362,19 @@ const opened = await cindy.iosSimulator.request({**Forge 源码必须是当前会话工作目录里的独立作者目录**。已安装插件目录以及Host 管理的状态目录都不是源码区,禁止直接修改、打包或用路径别名绕过;若要继续开发已有插件,先把源码复制/迁出到工作目录中的新目录,再从该副本制作;-2. 调 \`ghost_forge_pack({ dir: '<绝对路径>' })\`——校验 + 打包 + 弹装入确认框;+2. 调 \`ghost_forge_pack({ dir: '<绝对路径>' })\`——只做校验和打包,不安装或更新插件;产物落在源码目录里(\`<id>-<version>.cindy\`,同版本覆盖,下次打包自动跳过);macOS / Linux 源文件的普通 Unix 权限会原样进入包(特殊位会剥除),所以随包本机可执行程序必须在打包前就设好执行位(例如 \`chmod 755 path/to/program\`),不要靠文件扩展名或 \`bin/\` 目录让宿主猜测;若返回 \`SOURCE_IS_INSTALLED_PLUGIN\`,不要重试或换大小写、软链接、junction 绕过,按上一步迁出源码后再打包;也可能返回 \`SOURCE_OUTSIDE_WORKDIR\`(源码不在会话工作目录内);-3. **告知用户去点弹窗**(装入默认沉睡,提醒用户勾"立即开启"或到主界面侧边栏「插件」中唤醒);-4. 改代码后重新 pack:同 id 会弹"更新 vX → vY",唤醒状态与面板位置自动保留- (记得 bump ghost.json 的 version);-5. 验证:让用户 \`$<command> <内容>\` 试一单,看聊天图卡/面板是否符合预期。+3. 用户明确要求当前 Agent 安装或更新这份源码时,调用+ \`ghost_forge_install({ dir: '<绝对路径>' })\`。它会重新校验并打包当前源码,再把这次+ 产生的确切包直接安装;首次安装会启用,同 id 已安装时原位更新并保留启用状态、配置、+ 数据与面板位置,同版本也可覆盖。不要因为 scaffold 或 pack 成功就自动调用本工具。+ 用户也可以自己导入上一步的 \`.cindy\`,两种入口走同一安装/更新事务;+4. 安装后再让用户 \`$<command> <内容>\` 试一单,看聊天图卡/面板是否符合预期。企业组织成员需要发布时,调用 \`ghost_forge_pack({ dir: '<绝对路径>', intent: 'publish' })\`。该意图不会弹装入确认,也不会返回可供自行拼接的 Host 路径;它只返回绑定本次包 id 与@@ -4336,7 +4386,7 @@ const opened = await cindy.iosSimulator.request({## 8. 发布签名与审核-\`ghost_forge_pack\` 默认只负责本地制作和试装,生成的是**未签名包**。未签名不等于+\`ghost_forge_pack\` 默认只负责本地校验和打包,生成的是**未签名包**。未签名不等于一定有问题,用户仍可安装,但界面会明确显示“未验证”。正式对外发布时由商店或发布流水线在包根加入 \`cindy-signatures.json\`,不要让当前对话里的 Agent 代管正式私钥。@@ -4382,20 +4432,19 @@ const opened = await cindy.iosSimulator.request({- \`id\` 不合法(大写/下划线/超长)· 声明了 command 但没有 tools · command 与已装意识撞名· **未声明 command**:不拒装,但插件页"使用"按钮禁用,用户无法通过插件页一键启用或用 $command 点名;AI 工具调用不受影响(见 §2 说明)-- 声明了 tool 槽但缺 tools(或反之)· panel.html 声明了但 slots 没有 "panel"-- mainView 与 main-view 槽没有成对、mainView.html 文件缺失/路径不安全、icon 不在系统- 图标白名单、含未知字段,或声明 main-view 时漏了 minCindyVersion+- \`tools\` 为空 · panel 详单缺少实际形态(既没有 html,也不是有效的 tab/停靠配置)+- mainView.html 文件缺失/路径不安全、icon 不在系统图标白名单,或 mainView 含未知字段- settingsHtml 路径不合法/文件不在包里 · settingsHeight 越界(160–800)或没配 settingsHtml 单独声明- panel.systemButtons 格式错(不是对象、未知键、值非布尔,或 position:"tab" 时声明——插件页内面板没有标准头)-- keywords(已废弃字段,旧包兼容保留,新意识别写)有单字词 · kind 写了但不是 "chip"(可省略) · schemaVersion 不是 2-- cindy 详单格式错(未知类目/动作、空数组、有详单但 slots 没有 "cindy")-- agent 详单格式错(有详单但 slots 没有 "agent",或 background / errand / schedule 都不是 true;只需点击触发时应省略 agent 字段)-- node 详单格式错(槽/详单不成对、entry 不是包内 CommonJS .js/.cjs、protocol 不在 json-rpc-stdio / mcp-stdio、+- keywords(已废弃字段,旧包兼容保留,新意识别写)有单字词 · kind 写了但不是 "chip"(可省略) · schemaVersion 不是 3 · 缺 minCindyVersion+- cindy 详单格式错(未知类目/动作、空数组)+- agent 详单格式错(background / errand / schedule 存在但不是 true;基础点击触发请写 \`agent: {}\`)+- node 详单格式错(entry 不是包内 CommonJS .js/.cjs、protocol 不在 json-rpc-stdio / mcp-stdio、写了 command/args/shell/env、resident 又写 idleTimeoutSeconds)- id 用了 \`cindy-\` / \`filo-\` / \`xd-\` 前缀(官方保留,正式版用户通道拒装;给自己的意识换个前缀)- network 详单格式错(hosts 缺失/裸 TLD/IP/带端口/通配不在最左、secret 缺 inject、inject.format 没有 {value} 占位、inject.header 用了 Host/Cookie 等协议关键头、- inject.hosts 不是 hosts 声明条目的子集、有详单但 slots 没有 "network"、+ inject.hosts 不是 hosts 声明条目的子集、secret.source 不是 "user"/"login-email"/"oauth"/"gh-cli"/"oidc-token"、source:"login-email" 或 source:"oidc-token" 声明了 url 或 exchange、source:"gh-cli" 不是官方 cindy-github、注入形态不是 api.github.com 的diff --git a/apps/desktop/src/main/cindy-brain/forgePackConsume.ts b/apps/desktop/src/main/cindy-brain/forgePackConsume.tsdeleted file mode 100644index 0904a53c9e..0000000000--- a/apps/desktop/src/main/cindy-brain/forgePackConsume.ts+++ /dev/null@@ -1,103 +0,0 @@-/**- * Consume a forge-pack integrity ticket at inspect / install.- *- * Pack tickets are one-shot: the first inspect attempt consumes them.- * A matching hash + manifest.id issues an install continuation; mismatch- * deletes staging immediately. Renderer only ever sees the continuation- * token — never origin. No ticket ⇒ receipt origin is `manual`.- *- * `operationKind` on the pack ticket is a hint, not a reject condition.- * Real install-vs-update classification happens after the install lock.- */-import type { ActiveAppSession } from '../appSessionState.js';-import type { ForgePackIntegrityTicket, ForgePackStagingController } from './forgePackStaging.js';--export type ForgePackInspectConsume =- | { kind: 'not-forge' }- | { kind: 'accepted'; packTicket: string }- | { kind: 'rejected'; reason: string };--export type ForgePackInstallConsume =- | { kind: 'manual' }- | { kind: 'agent-forge'; ticket: ForgePackIntegrityTicket }- | { kind: 'rejected'; reason: string };--function sameOwner(a: ActiveAppSession, b: ActiveAppSession): boolean {- return a.mode === b.mode && a.dataOwnerId === b.dataOwnerId && a.generation === b.generation;-}--export function consumeForgePackAtInspect(- controller: ForgePackStagingController,- input: {- filePath: string;- packageSha256: string;- manifestId: string;- currentOwner: ActiveAppSession;- boundaryPending: boolean;- },-): ForgePackInspectConsume {- if (input.boundaryPending) {- // Short account-switch window: do not consume the pack ticket. The user- // can retry inspect on the same staging file after the owner is stable.- const existing = controller.peekMatchingStagingPath(input.filePath);- if (!existing && !controller.wasStagingPathConsumed(input.filePath)) {- return { kind: 'not-forge' };- }- return { kind: 'rejected', reason: 'session-boundary-pending' };- }- if (controller.wasStagingPathConsumed(input.filePath)) {- return { kind: 'rejected', reason: 'ticket-replay' };- }- const ticket = controller.consumeMatchingStagingPath(input.filePath);- if (!ticket) return { kind: 'not-forge' };- if (!sameOwner(ticket.owner, input.currentOwner)) {- controller.releaseStaging(ticket.stagingPath);- return { kind: 'rejected', reason: 'owner-mismatch' };- }- if (ticket.packageSha256 !== input.packageSha256 || ticket.manifestId !== input.manifestId) {- controller.releaseStaging(ticket.stagingPath);- return { kind: 'rejected', reason: 'ticket-binding-mismatch' };- }- const packTicket = controller.issueInstallContinuation(ticket);- if (!packTicket) {- return { kind: 'rejected', reason: 'ticket-expired' };- }- return { kind: 'accepted', packTicket };-}--export function consumeForgePackAtInstall(- controller: ForgePackStagingController,- input: {- packTicket: string | undefined;- packageSha256: string;- manifestId: string;- currentOwner: ActiveAppSession;- boundaryPending: boolean;- },-): ForgePackInstallConsume {- if (!input.packTicket) return { kind: 'manual' };- if (input.boundaryPending) {- // Caller should only reach here without a stable mutation lease. Do not- // consume the continuation — the same owner can retry after the window.- return { kind: 'rejected', reason: 'session-boundary-pending' };- }- const ticket = controller.consumeInstallContinuation(input.packTicket);- if (!ticket) return { kind: 'rejected', reason: 'ticket-replay' };- if (!sameOwner(ticket.owner, input.currentOwner)) {- controller.releaseStaging(ticket.stagingPath);- return { kind: 'rejected', reason: 'owner-mismatch' };- }- if (ticket.packageSha256 !== input.packageSha256 || ticket.manifestId !== input.manifestId) {- controller.releaseStaging(ticket.stagingPath);- return { kind: 'rejected', reason: 'ticket-binding-mismatch' };- }- return { kind: 'agent-forge', ticket };-}--export function abandonForgePackInstall(- controller: ForgePackStagingController,- packTicket: string,-): void {- const ticket = controller.consumeInstallContinuation(packTicket);- if (ticket) controller.releaseStaging(ticket.stagingPath);-}diff --git a/apps/desktop/src/main/cindy-brain/forgePackStaging.ts b/apps/desktop/src/main/cindy-brain/forgePackStaging.tsindex 464b096d06..75ef2bd110 100644--- a/apps/desktop/src/main/cindy-brain/forgePackStaging.ts+++ b/apps/desktop/src/main/cindy-brain/forgePackStaging.ts@@ -1,10 +1,9 @@/*** Forge pack 产物的 Host 侧 staging 与一次性完整 ticket。*- * 被注入的 agent 能在用户确认前改写 workdir 里的 `.cindy`。安装链路因此- * 绝不能从那条路径回读:必须把内存里的 `built.buf` 直接写进 Host 生成的- * staging。本模块只负责直写、加固、签发与失效;inspect / install 消费- * ticket 是下一步,这里不做。+ * 被注入的 agent 能改写 workdir 里的 `.cindy`。发布链路因此不能从那条+ * 路径回读:必须把内存里的 `built.buf` 直接写进 Host 生成的 staging。+ * 本模块只负责直写、加固、签发与失效;发布消费由独立模块完成。** 不在 import 时创建目录或写文件。*/@@ -18,11 +17,11 @@ export const FORGE_PACK_TICKET_TTL_MS = 10 * 60 * 1000;/** Extra grace so a long confirm wait plus clock skew is not swept as stale. */export const FORGE_PACK_STAGING_SWEEP_GRACE_MS = 60 * 1000;/**- * Cross-instance sweep threshold: pack TTL + continuation TTL + grace.- * Another Cindy process sharing OS temp must not delete a live confirm wait.+ * Cross-instance sweep threshold: pack TTL + grace.+ * Another Cindy process sharing OS temp must not delete a live publish wait.*/export const FORGE_PACK_STAGING_SWEEP_MAX_AGE_MS =- FORGE_PACK_TICKET_TTL_MS + FORGE_PACK_TICKET_TTL_MS + FORGE_PACK_STAGING_SWEEP_GRACE_MS;+ FORGE_PACK_TICKET_TTL_MS + FORGE_PACK_STAGING_SWEEP_GRACE_MS;const FORGE_PACK_LEASE_MARKER = '.cindy-forge-lease';export type ForgePackOperationKind = 'install' | 'update';@@ -43,11 +42,7 @@ export interface ForgePackIntegrityTicket {stagingPath: string;packageSha256: string;manifestId: string;- /**- * Wall-clock pack expiry pinned before the lease marker. Continuation must- * inherit `packExpiresAt + ttl` as a hard cap and must not re-base from- * issue-time `now()`.- */+ /** Wall-clock pack expiry pinned before the lease marker. */packExpiresAt: number;}@@ -74,16 +69,6 @@ export interface ForgePackStagingController {* cannot be replayed, but install still needs the bytes.*/consume(token: string): ForgePackIntegrityTicket | null;- consumeMatchingStagingPath(stagingPath: string): ForgePackIntegrityTicket | null;- peekMatchingStagingPath(stagingPath: string): ForgePackIntegrityTicket | null;- wasStagingPathConsumed(stagingPath: string): boolean;- /**- * After inspect consumes the pack ticket, issue a one-shot install continuation.- * Returns null (and deletes staging) when `now()` is already past the inherited- * hard deadline — never mint a ticket younger than the lease marker.- */- issueInstallContinuation(ticket: ForgePackIntegrityTicket): string | null;- consumeInstallContinuation(token: string): ForgePackIntegrityTicket | null;invalidate(token: string): boolean;releaseStaging(stagingPath: string): void;invalidateMismatchedOwners(current: ActiveAppSession): void;@@ -211,8 +196,8 @@ function forgePackLeaseAgeMs(taskDir: string, nowMs: number): number | null {* Restart / crash recovery: drop leftover Host staging dirs under tempRoot.* Only enumerates direct children that match `cindy-forge-<v4 UUID>`. Symlinks* and non-directories are skipped; real parent must still be tempRoot.- * Only dirs older than pack TTL + continuation TTL + grace are removed, so a- * sibling Cindy process waiting on confirm is not deleted.+ * Only dirs older than pack TTL + grace are removed, so a sibling Cindy+ * process waiting to publish is not deleted.*/export function sweepStaleForgePackStagingDirs(tempRoot: string,@@ -273,12 +258,6 @@ export function createForgePackStagingController(timeout: { cancel(): void };};const tickets = new Map<string, Entry>();- const installContinuations = new Map<string, Entry>();- const consumedStagingPaths = new Set<string>();-- const forgetConsumedPath = (stagingPath: string): void => {- consumedStagingPaths.delete(path.resolve(stagingPath));- };const drop = (token: string, removeFiles: boolean): boolean => {const entry = tickets.get(token);@@ -286,7 +265,6 @@ export function createForgePackStagingController(tickets.delete(token);entry.timeout.cancel();if (removeFiles) {- forgetConsumedPath(entry.ticket.stagingPath);rmTaskDir(path.dirname(entry.ticket.stagingPath));}return true;@@ -363,90 +341,11 @@ export function createForgePackStagingController(return entry.ticket;},- consumeMatchingStagingPath(stagingPath) {- const target = path.resolve(stagingPath);- for (const [token, entry] of tickets) {- if (path.resolve(entry.ticket.stagingPath) === target) {- tickets.delete(token);- entry.timeout.cancel();- consumedStagingPaths.add(target);- if (entry.expiresAt <= now()) {- consumedStagingPaths.delete(target);- rmTaskDir(path.dirname(entry.ticket.stagingPath));- return null;- }- return entry.ticket;- }- }- return null;- },-- peekMatchingStagingPath(stagingPath) {- const target = path.resolve(stagingPath);- for (const [token, entry] of tickets) {- if (path.resolve(entry.ticket.stagingPath) !== target) continue;- if (entry.expiresAt <= now()) {- drop(token, true);- return null;- }- return entry.ticket;- }- return null;- },-- wasStagingPathConsumed(stagingPath) {- return consumedStagingPaths.has(path.resolve(stagingPath));- },-- issueInstallContinuation(ticket) {- const issueNow = now();- const hardDeadline = ticket.packExpiresAt + ttlMs;- if (issueNow >= hardDeadline) {- forgetConsumedPath(ticket.stagingPath);- rmTaskDir(path.dirname(ticket.stagingPath));- return null;- }- const expiresAt = Math.min(issueNow + ttlMs, hardDeadline);- const token = randomId();- const timeout = scheduleTimeout(Math.max(0, expiresAt - issueNow), () => {- const entry = installContinuations.get(token);- if (!entry) return;- installContinuations.delete(token);- entry.timeout.cancel();- forgetConsumedPath(ticket.stagingPath);- rmTaskDir(path.dirname(ticket.stagingPath));- });- installContinuations.set(token, { ticket, expiresAt, timeout });- return token;- },-- consumeInstallContinuation(token) {- const entry = installContinuations.get(token);- if (!entry) return null;- installContinuations.delete(token);- entry.timeout.cancel();- if (entry.expiresAt <= now()) {- forgetConsumedPath(entry.ticket.stagingPath);- rmTaskDir(path.dirname(entry.ticket.stagingPath));- return null;- }- return entry.ticket;- },-invalidate(token) {- const continuation = installContinuations.get(token);- if (continuation) {- installContinuations.delete(token);- continuation.timeout.cancel();- forgetConsumedPath(continuation.ticket.stagingPath);- rmTaskDir(path.dirname(continuation.ticket.stagingPath));- return true;- }return drop(token, true);},releaseStaging(stagingPath) {- forgetConsumedPath(stagingPath);rmTaskDir(path.dirname(stagingPath));},@@ -454,25 +353,10 @@ export function createForgePackStagingController(for (const [token, entry] of [...tickets]) {if (!isSameOwner(entry.ticket.owner, current)) drop(token, true);}- for (const [token, entry] of [...installContinuations]) {- if (!isSameOwner(entry.ticket.owner, current)) {- installContinuations.delete(token);- entry.timeout.cancel();- forgetConsumedPath(entry.ticket.stagingPath);- rmTaskDir(path.dirname(entry.ticket.stagingPath));- }- }},invalidateAll() {for (const token of [...tickets.keys()]) drop(token, true);- for (const [token, entry] of [...installContinuations]) {- installContinuations.delete(token);- entry.timeout.cancel();- forgetConsumedPath(entry.ticket.stagingPath);- rmTaskDir(path.dirname(entry.ticket.stagingPath));- }- consumedStagingPaths.clear();},};}@@ -568,24 +452,6 @@ export function consumeForgePackTicket(token: string): ForgePackIntegrityTicketreturn getController().consume(token);}-export function consumeForgePackTicketForStagingPath(- stagingPath: string,-): ForgePackIntegrityTicket | null {- return getController().consumeMatchingStagingPath(stagingPath);-}--export function issueForgePackInstallContinuation(- ticket: ForgePackIntegrityTicket,-): string | null {- return getController().issueInstallContinuation(ticket);-}--export function consumeForgePackInstallContinuation(- token: string,-): ForgePackIntegrityTicket | null {- return getController().consumeInstallContinuation(token);-}-export function invalidateForgePackTicket(token: string): boolean {return productionController?.invalidate(token) ?? false;}diff --git a/apps/desktop/src/main/cindy-brain/fsSlot.ts b/apps/desktop/src/main/cindy-brain/fsSlot.tsindex b0a1e3bd38..2f573caf76 100644--- a/apps/desktop/src/main/cindy-brain/fsSlot.ts+++ b/apps/desktop/src/main/cindy-brain/fsSlot.ts@@ -1,15 +1,16 @@/**- * fsSlot.ts — fs 槽代写文件(2026-07-14,与 Lizi 定案)。+ * fsSlot.ts — 插件沙箱的主机文件操作边界(2026-07-14,与 Lizi 定案)。* ---------------------------------------------------------------------------* 意识没有文件系统(沙箱红线不破),想落盘只能经管子请主机代写:** 电子脑 cindy.send({type:'fs-request', op, root, path?, content?, …})- * → 资格审(声明了 'fs' 卡槽?)- * → 按 root 三档守门:+ * → 按执行上下文与 root 三档守门:* 'data' 私有数据目录 userData/ghost-fs/<ghostId>——自己的储物柜,- * 免确认;全 op(write/read/list/delete);配额封顶;卸载回收。+ * 要求插件自主 fs 声明;免确认;全 op(write/read/list/delete);+ * 配额封顶;卸载回收。* 'workdir' 当前会话工作目录——仅 write;必须带 callId(主机凭- * cardService 反查 session,不信意识自报);**跟随会话+ * cardService 严格反查当前 Agent 调用与 session,不信意识+ * 自报);当前 Agent 调用无需插件自主 fs 声明;**跟随会话* permission 模式**(映射表见 workdirWriteVerdict:免批模式* 直写、逐条模式弹 fs_write 确认卡、plan 拒);远程工作区* (remoteHostId 非空)明确拒——路径在远端机器,本地代写@@ -24,7 +25,7 @@* 反查走**严格在途**查询(inFlightCallInfo,与 workspace* 槽同一判据):交卷即失效,不享卡片供片的宽限窗——目录* 授权上下文必须用完即废。- * 'save' 主 agent 过户的 save 票据目录——仅 write;复用+ * 'save' 主 agent 过户的 save 票据目录——仅 write;票据自身授权;复用* saveDeposit 票据库的 TTL/次数/字节预算与文件名消毒去重* (与 fetch as:'file' 下载落盘同一本账)。* → 主机代写/代读,只回结构化 GhostPipeFsResult(永不 reject)。@@ -298,15 +299,28 @@ export class GhostFsSlot {private async dispatch(ghostId: string, payload: unknown): Promise<GhostPipeFsResult> {const ghost = this.deps.getGhost(ghostId);if (!ghost) return fail('意识未装入');- if (!ghost.manifest.slots.includes('fs')) {- return fail('未声明 "fs" 卡槽——想写文件先在 ghost.json 的 slots 里声明 "fs"(装入确认时会向用户如实展示)');- }const req = (payload ?? {}) as Record<string, unknown>;const op = req.op as GhostFsOp;const root = req.root as GhostFsRoot;if (!GHOST_FS_OPS.includes(op)) return fail(`op 必须是 ${GHOST_FS_OPS.join(' / ')}`);if (!GHOST_FS_ROOTS.includes(root)) return fail(`root 必须是 ${GHOST_FS_ROOTS.join(' / ')}`);+ // data 是插件自己的持久私有存储,继续要求 manifest.fs。workdir+ // 只有能严格证明处于当前 Agent ghost_call 内才可复用会话文件+ // 授权;save 则以 Agent 发放的限时、绑定插件的票据作为授权。+ if (ghost.manifest.fs !== true) {+ const callId = typeof req.callId === 'string' ? req.callId : null;+ const callInfo = callId ? this.deps.inFlightCallInfo(callId) : null;+ const agentMediatedWorkdir =+ root === 'workdir'+ && callInfo?.ghostId === ghostId+ && callInfo.channel === 'session'+ && callInfo.sessionId !== null;+ if (!agentMediatedWorkdir && root !== 'save') {+ return fail('本操作不在当前 Agent 授权调用中,且插件未声明自主 fs 能力');+ }+ }+if (root === 'data') return this.handleData(ghostId, op, req);if (op !== 'write') return fail(`root:"${root}" 只支持 op:"write"(read/list/delete 仅限私有目录 root:"data")`);if (root === 'save') return this.handleSaveWrite(ghostId, req);diff --git a/apps/desktop/src/main/cindy-brain/ghostFirstPartyFacts.ts b/apps/desktop/src/main/cindy-brain/ghostFirstPartyFacts.tsindex c9f3d6c183..eb64dfc401 100644--- a/apps/desktop/src/main/cindy-brain/ghostFirstPartyFacts.ts+++ b/apps/desktop/src/main/cindy-brain/ghostFirstPartyFacts.ts@@ -63,8 +63,6 @@ export interface LoadGhostFirstPartyFactsLoaderOptions {/** Missing or legacy package evidence must return null. */readApprovedPackageSha256(ghostId: string): string | null;lookupOrganizationPrefix(orgId: string): OrganizationPrefixLookup;- /** Missing / unreadable receipts must return `manual`. */- readInstallOrigin(ghostId: string): 'manual' | 'agent-forge';}function actionFor(purpose: GhostFirstPartyFactsPurpose): GhostFirstPartyFactsUnavailableAction {@@ -103,7 +101,6 @@ export function bindPendingMarketRecordToInspectedPackage(}export type GhostFirstPartyFactsOverrides = {- installOrigin?: 'manual' | 'agent-forge';marketRecord?: GhostFirstPartyMarketRecord | null;};@@ -116,7 +113,6 @@ export function applyGhostFirstPartyFactsOverrides(kind: 'ready',facts: {...load.facts,- ...(overrides.installOrigin !== undefined ? { installOrigin: overrides.installOrigin } : {}),...(overrides.marketRecord !== undefined ? { marketRecord: overrides.marketRecord } : {}),},};@@ -156,13 +152,6 @@ export function loadGhostFirstPartyFactsLoader(marketRecord = null;}- let installOrigin: 'manual' | 'agent-forge' = 'manual';- try {- installOrigin = options.readInstallOrigin(ghostId);- } catch {- installOrigin = 'manual';- }-if (identity.membershipKind !== 'org' || !identity.orgId) {return {kind: 'ready',@@ -171,7 +160,6 @@ export function loadGhostFirstPartyFactsLoader(builtin,marketRecord,currentOrganization: null,- installOrigin,},};}@@ -193,7 +181,7 @@ export function loadGhostFirstPartyFactsLoader(*/const builtinOnlyFacts = (): GhostFirstPartyFactsLoad => ({kind: 'ready',- facts: { ghostId, builtin, marketRecord, currentOrganization: null, installOrigin },+ facts: { ghostId, builtin, marketRecord, currentOrganization: null },});let lookup: OrganizationPrefixLookup;@@ -215,7 +203,6 @@ export function loadGhostFirstPartyFactsLoader(organizationId: identity.orgId,pluginPrefix: lookup.pluginPrefix,},- installOrigin,},};}diff --git a/apps/desktop/src/main/cindy-brain/ghostFirstPartyPrivilege.ts b/apps/desktop/src/main/cindy-brain/ghostFirstPartyPrivilege.tsindex f25e6186b3..ed9f79aa7c 100644--- a/apps/desktop/src/main/cindy-brain/ghostFirstPartyPrivilege.ts+++ b/apps/desktop/src/main/cindy-brain/ghostFirstPartyPrivilege.ts@@ -47,7 +47,6 @@ export type GhostFirstPartyBasis =| 'builtin-official'| 'market-public'| 'market-organization-current'- | 'local-current-org-prefix'| 'denied-alias'| 'denied-foreign-org'| 'denied-unknown-origin';@@ -80,12 +79,6 @@ export interface GhostFirstPartyFacts {builtin: boolean;marketRecord: GhostFirstPartyMarketRecord | null;currentOrganization: GhostFirstPartyCurrentOrganization | null;- /**- * Authorization-time install origin from `effectiveInstallOrigin(receipt)`.- * Missing / unreadable receipts are `manual` (fail-closed, equals today).- * Local org-prefix packages only receive Broker when this is `agent-forge`.- */- installOrigin: 'manual' | 'agent-forge';}function matchesCurrentOrgPrefix(@@ -192,26 +185,9 @@ export function resolveGhostFirstPartyPrivilege(facts: GhostFirstPartyFacts): Gh}return allow('market-organization-current', false);}- if (- (record.source === 'git-market' || record.source === 'local-market') &&- matchesCurrentOrgPrefix(facts.ghostId, facts.currentOrganization)- ) {- // Custom-market rows are not a forge install. Granting Broker here would- // silently raise privilege for packages that today's install gate rejects.- return facts.installOrigin === 'agent-forge'- ? allow('local-current-org-prefix', false)- : deny('denied-unknown-origin');- }return deny('denied-unknown-origin');}- if (- facts.installOrigin === 'agent-forge' &&- matchesCurrentOrgPrefix(facts.ghostId, facts.currentOrganization)- ) {- return allow('local-current-org-prefix', false);- }-return deny('denied-unknown-origin');}diff --git a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.tsindex 98c94a8863..a36e417c84 100644--- a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts+++ b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts@@ -66,13 +66,7 @@ export interface GhostInstallReceipt {*/packageSha256?: string;/**- * 本次装入/更新操作的来源。可选;缺失按 `manual` 读。- * 不要改成必填、不要升 schemaVersion、不要批量重写旧 receipt。- * 未知值只在授权判断时降级为 manual,不写回磁盘。- */- installOrigin?: string;- /**- * 按 skill item 目录钉住的批准字节指纹(`item.dir` → sha256)。声明了 skill 槽+ * 按 skill item 目录钉住的固化字节指纹(`item.dir` → sha256)。声明了 skill 能力* 时逐项必填,没声明时是空对象。** 这一项**是运行期判据**,与只作审计用的 `packageSha256` 不同:快照缺失需要从@@ -100,7 +94,7 @@ export type GhostInstallReceiptRecoveryReadResult =* receipt 的迁移"——此后任何缺失 receipt 都按删除/损坏 fail closed,不再触发迁移。** 它是迁移的**全局一次性门**(见 `GhostManager.migrateLegacyApprovalsOnce`):没有- * 这道门,删掉某个 receipt 就能骗一次"从当前可变安装目录重建授权",而安装目录可被+ * 这道门,删掉某个 receipt 就能骗一次"从当前可变安装目录重建验证状态",而安装目录可被* 同权限进程改写。ledger 门是充分守卫——能删 ledger 的进程本就能直接往状态根写一份* 结构合法的伪造 receipt(§7 已登记"状态根无写保护"缺口),迁移路径严格弱于它。*/@@ -108,11 +102,11 @@ export interface GhostLegacyMigrationLedger {version: 1;/** 迁移完成时刻(ISO)。仅审计,不参与判定。 */migratedAt: string;- /** 实际 backfill 出 receipt 的 id 清单,便于事后分辨"用户确认过"与"迁移来的"。 */+ /** 实际 backfill 出 receipt 的 id 清单,便于事后分辨"正常安装写入"与"迁移来的"。 */migratedIds: string[];/*** 迁移读不出核心事实而 fail closed 的 id(坏 manifest / 技能目录含链接等)。- * 记进台账供支持排查与 UI 提示;这些 id 走每插件的重新确认恢复入口。+ * 记进台账供支持排查与 UI 提示;这些 id 走每插件的重新安装恢复入口。*/failedIds?: string[];/**@@ -141,7 +135,7 @@ export interface GhostLegacyMigrationLedger {* 还没写」这段崩溃窗口:* - install:崩溃留下"有 finalDir、无 receipt、无 ledger"的目录,与 legacy 安装无法* 区分 —— 全新 owner 首个安装崩在这里,下轮迁移会把它(含崩溃窗口内被同权限进程- * 改写的 manifest)当存量批准掉,用户确认的是 A、被授权的是 B。+ * 改写的 manifest)当存量安装收编,检查的是 A、最后固化的是 B。* - update:`final→backup`、`staging→final`、写 receipt 三步;第二三步之间崩溃留下* "新字节 + 旧 receipt",恢复器旧逻辑(final 在位就删 backup)会把它固化成"按旧批准* 跑新代码"。@@ -886,7 +880,7 @@ export class GhostInstallReceiptStore {** 只在新 receipt 已经原子提交之后跑:此刻旧 revision 已不是批准事实,留着* 就是每次更新泄漏一份完整拷贝。共享技能根里指向旧 revision 的链接会因此- * 短暂断链,直到下一轮对账重指——对越出沙箱的 skill 槽来说,短暂"技能不可+ * 短暂断链,直到下一轮对账重指——对越出沙箱的 skill 能力来说,短暂"技能不可* 用"是正确的收敛方向,留着旧批准版本继续生效不是。** best-effort:批准事实已经落盘,回收失败只记为待清理状态,不回滚安装。@@ -994,9 +988,8 @@ function classifyCleanupEntrySync(absPath: string): CleanupEntryKind {* 迁移失败:旧模型读的也是同一个文件,缺了同样显示不出 verified,不比旧模型少展示什么。** `cindy-official` 一律**封顶拒收**(按镜像损坏处理):官方档只该由 provisioning 在与- * 随包种子逐字节对账后授予,而本函数的两个调用方(legacy 迁移 / 从已装目录重新确认)都- * 只服务非随包插件 —— 非随包目录里出现官方档镜像本身就不可信,照抄会让确认卡/列表把- * 一个可变目录里的插件展示成「Cindy 官方」。+ * 随包种子逐字节对账后授予,而本函数仅供 legacy 迁移非随包插件使用。非随包目录里+ * 出现官方档镜像本身就不可信,照抄会让列表把一个可变目录里的插件展示成「Cindy 官方」。*/export function readLegacyInstallTrust(dir: string): GhostTrustInfo | null {const file = path.join(dir, '.cindy-trust.json');@@ -1027,11 +1020,7 @@ export function createGhostInstallReceipt(input: {packageSha256?: string;revision?: string;iconDataUrl?: string;- installOrigin?: string;}): GhostInstallReceipt {- if (input.installOrigin !== undefined && !isPersistableInstallOrigin(input.installOrigin)) {- throw new Error('receipt installOrigin 不合法');- }return {schemaVersion: RECEIPT_SCHEMA_VERSION,id: input.manifest.id,@@ -1043,28 +1032,9 @@ export function createGhostInstallReceipt(input: {skillContentSha256: input.skillContentSha256,...(input.packageSha256 ? { packageSha256: input.packageSha256 } : {}),...(input.iconDataUrl ? { iconDataUrl: input.iconDataUrl } : {}),- ...(input.installOrigin !== undefined ? { installOrigin: input.installOrigin } : {}),};}-const MAX_INSTALL_ORIGIN_CHARS = 64;-const INSTALL_ORIGIN_PATTERN = /^[a-z0-9-]+$/;--function isPersistableInstallOrigin(value: string): boolean {- return (- value.length > 0 &&- value.length <= MAX_INSTALL_ORIGIN_CHARS &&- INSTALL_ORIGIN_PATTERN.test(value)- );-}--/** Authorization-time view: missing or unknown → manual. Never write this back. */-export function effectiveInstallOrigin(- receipt: Pick<GhostInstallReceipt, 'installOrigin'>,-): 'manual' | 'agent-forge' {- return receipt.installOrigin === 'agent-forge' ? 'agent-forge' : 'manual';-}-/*** 逐 skill item 目录算规范化内容指纹(排序后的相对路径 + 字节)。*@@ -1194,16 +1164,6 @@ function validateReceipt(if (!validated.ok) return { ok: false, reason: `receipt locale 不合法:${localePath}` };localeResources[localePath] = validated.resource;}- let installOrigin: string | undefined;- if (value.installOrigin !== undefined) {- if (typeof value.installOrigin !== 'string') {- return { ok: false, reason: 'receipt installOrigin 不合法' };- }- if (!isPersistableInstallOrigin(value.installOrigin)) {- return { ok: false, reason: 'receipt installOrigin 不合法' };- }- installOrigin = value.installOrigin;- }return {ok: true,receipt: {@@ -1217,7 +1177,6 @@ function validateReceipt(skillContentSha256,...(typeof value.packageSha256 === 'string' ? { packageSha256: value.packageSha256 } : {}),...(typeof value.iconDataUrl === 'string' ? { iconDataUrl: value.iconDataUrl } : {}),- ...(installOrigin !== undefined ? { installOrigin } : {}),},};}diff --git a/apps/desktop/src/main/cindy-brain/ghostOauthFlow.ts b/apps/desktop/src/main/cindy-brain/ghostOauthFlow.tsindex d3a2ad86ab..343d724b47 100644--- a/apps/desktop/src/main/cindy-brain/ghostOauthFlow.ts+++ b/apps/desktop/src/main/cindy-brain/ghostOauthFlow.ts@@ -4,7 +4,7 @@* 设计定案(2026-07-13 与 Lizi):平台不预设 provider 名单——意识在 ghost.json* 里声明"去哪授权、要什么 scope"(authorizeUrl / tokenUrl / scopes / pkce),* clientId / clientSecret 由用户在意识设置页自填(input:'ghost' 只写通道同款- * 纪律),装入确认框全量展示,用户知情自担。+ * 纪律),插件详情全量展示。** 本模块声明化的是**参数**,不是**代码**:授权流程本身(拉浏览器、loopback* 回调、state / PKCE 校验、code 换 token、refresh)永远是这份主机可信代码在@@ -98,8 +98,8 @@ export interface GhostOauthClientConfig {*/callbackPath?: string;/**- * 可选:该插件 manifest 的 network.hosts 白名单(装入确认框展示、用户同意- * 过的域名面;含最左通配)。跨源 code 投递的允许来源 = authorizeUrl/tokenUrl+ * 可选:该插件 manifest 的 network.hosts 白名单(插件详情展示的域名面;+ * 含最左通配)。跨源 code 投递的允许来源 = authorizeUrl/tokenUrl* 的 origin + 本白名单命中的 https origin——xAI 这类「授权端点在 auth.x.ai、* consent 页从 accounts.x.ai 投递」的服务商,把投递域声明进 hosts 即可,* 不引入白名单之外的新信任面。@@ -120,8 +120,8 @@ const RESERVED_AUTHORIZE_PARAMS: ReadonlySet<string> = new Set(// 把同一机制移植进通用引擎。//// 通用引擎不能绑死某个服务商:允许来源从该插件声明的 authorizeUrl / tokenUrl 的-// origin 派生,并叠加 manifest network.hosts 白名单命中的 https origin(装入确认框-// 展示、用户同意过的域名面)——xAI 这类「授权端点在 auth.x.ai、consent 页从+// origin 派生,并叠加 manifest network.hosts 白名单命中的 https origin(插件详情+// 展示的域名面)——xAI 这类「授权端点在 auth.x.ai、consent 页从// accounts.x.ai 投递」的服务商,把投递域声明进 hosts 即被覆盖;任意其它网站的// 预检拿不到 CORS 头。真实性校验仍靠 state(+PKCE),与 302 回调同一套。diff --git a/apps/desktop/src/main/cindy-brain/ghostTokenBrokerInstallError.ts b/apps/desktop/src/main/cindy-brain/ghostTokenBrokerInstallError.tsindex 5274ff7ae0..001ec1a6e2 100644--- a/apps/desktop/src/main/cindy-brain/ghostTokenBrokerInstallError.ts+++ b/apps/desktop/src/main/cindy-brain/ghostTokenBrokerInstallError.ts@@ -3,23 +3,15 @@ import type { IpcErrorCode } from '../../shared/ipc-errors.js';export interface GhostTokenBrokerInstallError {code: Extract<IpcErrorCode,- 'GHOST_BROKER_MANUAL_INSTALL_NOT_AUTHORIZED' | 'GHOST_BROKER_NOT_AUTHORIZED'+ 'GHOST_BROKER_MANUAL_INSTALL_NOT_AUTHORIZED'>;reason: string;}/** Copy classification only; authorization remains owned by the caller. */-export function ghostTokenBrokerInstallError(- installOrigin?: 'manual' | 'agent-forge',-): GhostTokenBrokerInstallError {- return installOrigin === 'manual'- ? {- code: 'GHOST_BROKER_MANUAL_INSTALL_NOT_AUTHORIZED',- reason:- '手动装入的 .cindy 不能使用授权 broker;请改从组织插件市场安装,或让插件作者在组织身份下使用 ghost_forge_pack 构建',- }- : {- code: 'GHOST_BROKER_NOT_AUTHORIZED',- reason: '当前安装来源或组织身份无权使用授权 broker',- };+export function ghostTokenBrokerInstallError(): GhostTokenBrokerInstallError {+ return {+ code: 'GHOST_BROKER_MANUAL_INSTALL_NOT_AUTHORIZED',+ reason: '本地装入的 .cindy 不能使用授权 broker;请改从组织插件市场安装',+ };}diff --git a/apps/desktop/src/main/cindy-brain/ghostUnreadProjection.ts b/apps/desktop/src/main/cindy-brain/ghostUnreadProjection.tsindex 85e359b198..4db90175af 100644--- a/apps/desktop/src/main/cindy-brain/ghostUnreadProjection.ts+++ b/apps/desktop/src/main/cindy-brain/ghostUnreadProjection.ts@@ -16,10 +16,10 @@ import type { InstalledGhost } from '../../shared/ghost.js';/*** 该意识当前是否还持有未读角标能力(资格,与启用与否无关)。- * 只看 `badge` 卡槽:它与 `notify` 卡槽是并列的两档权限,不互为前置。+ * 只看 `badge` 直接声明:它与 `notify` 是并列的两档权限,不互为前置。*/export function ghostDeclaresBadge(ghost: InstalledGhost | null | undefined): boolean {- return ghost?.manifest.slots?.includes('badge') === true;+ return ghost?.manifest.badge === true;}/** 该意识的未读现在该不该出现在界面上(资格 + 已启用)。 */diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex 842dea66ac..f61740cb41 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -25,18 +25,15 @@ import {GHOST_MEDIA_CAPABILITIES,GHOST_NETWORK_MAX_CONNECTIONS_PER_DECL,GHOST_NOTIFY_MIN_INTERVAL_MS,+ ghostInstallApprovalToken,isGhostInstallApprovalToken,- diffGhostPermissionItems,ghostAppContextLocale,- ghostPermissionBaselineKey,unreviewedGhostPermissionItems,ghostWebviewEntryPaths,isCindyAccountGhostId,isBrokerEligibleGhostId,isOfficialGhostId,isUserInstallReservedGhostId,- ghostPermissionItems,- ghostPermissionProjectionFingerprint,isValidGhostId,layoutWithGhostPanel,type GhostHostNoticeKey,@@ -54,10 +51,6 @@ import {type InstalledGhost,type GhostLibraryOverview,} from '../../shared/ghost.js';-import type {- PluginMarketItemSource,- PluginMarketPackageReviewFacts,-} from '../../shared/pluginMarket.js';import { getAppCapabilities } from '../appCapabilities.js';import { withGhostSkillProjectionReconcile } from '../authBoundaryQuarantine.js';import {@@ -79,27 +72,12 @@ import {} from './GhostManager.js';import { exportGhostPackage } from './exportGhostPackage.js';import { GhostMutationCoordinator } from './ghostMutationCoordinator.js';-import { createOneShotTicketStore } from './oneShotTickets.js';import { shouldRejectReservedGhostIds } from './reservedGhostIdGate.js';import {bindForgePackStagingTempDir,- getForgePackStagingControllerIfConfigured,invalidateForgePackTicketsForOwner,- releaseForgePackStaging,} from './forgePackStaging.js';-import {- abandonForgePackInstall,- consumeForgePackAtInspect,- consumeForgePackAtInstall,-} from './forgePackConsume.js';import { withGhostInstallLock } from './ghostInstallLock.js';-import {- GhostPackagePermissionReviewRequiredError,- marketPackageHostReviewDiff,- marketPackageManualSummaryChanged,- marketPackageNeedsHostReview,- marketPackageOauthIdentityChanged,-} from './packagePermissionReview.js';import {clearBuiltinTombstone,listEligibleBuiltinCommands,@@ -128,7 +106,6 @@ import {type GhostRepoRootCacheEntry,} from './repoRoot.js';import { takePendingCindyInstall } from './openFileInstall.js';-import { MANUAL_GHOST_INSTALL_ORIGIN } from '../../shared/ghostInstallOrigin.js';import { GhostRuntime } from './runtime/GhostRuntime.js';import {electronSandboxAdapter,@@ -1744,7 +1721,7 @@ export function getGhostCardService(): GhostCardService {cardServiceSingleton = new GhostCardService({hasCardSlot: (ghostId) => {const g = findAvailableGhost(ghostId);- return !!g && g.enabled && g.manifest.slots.includes('card');+ return !!g && g.enabled && g.manifest.card !== undefined;},sanitize: sanitizeGhostCardHtml,persist: (row) => upsertGhostCard(row),@@ -2578,13 +2555,6 @@ function getConnectionAudienceResolver(): ConnectionAudienceResolver {.find((candidate) => candidate.manifest.id === ghostId)?.manifest ?? null,readInstalledManifestDigest: readInstalledGhostManifestDigest,readMarketInstallation: (ghostId) => getPluginMarketLedger().installationForGhost(ghostId),- readApprovedPackageSha256: (ghostId) =>- getGhostManager().approvedInstallEvidence(ghostId)?.packageSha256 ?? null,- readInstallOrigin: (ghostId) => getGhostManager().readEffectiveInstallOrigin(ghostId),- lookupOrganizationPrefix: (orgId) =>- createOrganizationPrefixStore(- ownerScopedUserDataPath('plugin-market', 'organization.v1.json'),- ).lookup(orgId),log,});}@@ -2616,7 +2586,6 @@ function getGhostFirstPartyFactsLoader(): GhostFirstPartyFactsLoader {createOrganizationPrefixStore(ownerScopedUserDataPath('plugin-market', 'organization.v1.json'),).lookup(orgId),- readInstallOrigin: (ghostId) => getGhostManager().readEffectiveInstallOrigin(ghostId),});}return ghostFirstPartyFactsLoaderSingleton;@@ -3608,7 +3577,7 @@ async function getGhostConfigurableMediaModels(return { ok: false, errorCode: 'NOT_AVAILABLE', message: '插件当前不可用' };}const declared = ghost.manifest.cindy?.[type] ?? [];- if (!ghost.manifest.slots?.includes('cindy') || declared.length === 0) {+ if (declared.length === 0) {return {ok: false,errorCode: 'PERMISSION_DENIED',@@ -3701,7 +3670,7 @@ function getGhostConfiguredMediaModel(return { ok: false, errorCode: 'NOT_AVAILABLE', message: '插件当前不可用' };}const declared = ghost.manifest.cindy?.[type] ?? [];- if (!ghost.manifest.slots?.includes('cindy') || !declared.includes(action)) {+ if (!declared.includes(action)) {return {ok: false,errorCode: 'PERMISSION_DENIED',@@ -4848,6 +4817,7 @@ export function getGhostNetworkSlot(): GhostNetworkSlot {const ghost = findAvailableGhost(id);return ghost ? { ...ghost, manifest: withRuntimeFiloGoogleClient(ghost.manifest) } : null;},+ inFlightCallInfo: (callId) => getGhostCardService().inFlightCallInfoOf(callId),readSecret: (ghostId, secretKey) => readGhostSecret(ghostId, secretKey),readGhCliToken: () => getSharedGhCliTokenSource().readToken(),// source:'login-email' 凭证的值来源:现读登录态(切号/登出下一单即生效)。@@ -5002,7 +4972,7 @@ export function getGhostFsSlot(): GhostFsSlot {let librarySlotSingleton: GhostLibrarySlot | null = null;/**- * library 槽单例(持久作品库,2026-08-20):与 fs 槽同款懒取现查——根目录经+ * library 能力单例(持久作品库,2026-08-20):与 fs 能力同款懒取现查——根目录经* binding store 解析(默认 = ownerScopedUserDataPath('libraries', id);自定义* 位置带漂移判定),owner scope 每请求比对(切换后旧会话作废重解)。SQL 执行* 在 per-plugin worker(语句门见 libraryDbCore);本进程只组包与映射结果。@@ -5122,7 +5092,7 @@ async function relocateGhostLibraryTo(*/export async function getGhostLibraryOverview(ghostId: string): Promise<GhostLibraryOverview> {const ghost = findAvailableGhost(ghostId);- const supported = ghost?.manifest.slots.includes('library') === true;+ const supported = ghost?.manifest.library === true;const store = getGhostLibraryBindingStore();const binding = await store.getBinding(ghostId);const resolution = await store.resolveLibraryRoot(ghostId);@@ -5205,7 +5175,7 @@ export async function deleteGhostLibraryForActiveOwner(ghostId: string): Promiselet libraryBindingStoreSingleton: LibraryBindingStore | null = null;-/** library 槽的 binding store(单例:读-改-写互斥要落在同一实例链上)。 */+/** library 能力的 binding store(单例:读-改-写互斥要落在同一实例链上)。 */export function getGhostLibraryBindingStore(): LibraryBindingStore {if (!libraryBindingStoreSingleton) {libraryBindingStoreSingleton = new LibraryBindingStore({@@ -5271,7 +5241,7 @@ function rejectUnauthorizedTokenBroker();if (!brokered) return;if (isGhostTokenBrokerAuthorized(manifest.id, 'install', overrides)) return;- const authorizationError = ghostTokenBrokerInstallError(overrides?.installOrigin);+ const authorizationError = ghostTokenBrokerInstallError();throwIpcError(authorizationError.code,`id "${manifest.id}" 声明了 oauth.tokenBroker——${authorizationError.reason}`,@@ -5320,14 +5290,6 @@ function throwUninstallError(rejection: UninstallRejection): never {}}-function assertGhostSupportsCurrentCindy(manifest: GhostManifest): void {- if (supportsCindyVersion(app.getVersion(), manifest.minCindyVersion)) return;- throwIpcError(- 'GHOST_FILE_INVALID',- `该插件需要 Cindy ${manifest.minCindyVersion} 或更高版本`,- );-}-/*** 装入 + 停靠(共享主体):ghosts:install(显式路径)、* ghosts:install-via-dialog(系统文件选择框)与双击 .cindy@@ -5347,7 +5309,6 @@ export async function installAndDock(enable?: boolean;expectedPackageSha256?: string;trustOverride?: GhostHostTrustOverride;- installOrigin?: string;},): Promise<InstalledGhost> {return withGhostInstallLock(opts.ghostId, () => installAndDockLocked(manager, lizFilePath, opts));@@ -5361,18 +5322,16 @@ async function installAndDockLocked(enable?: boolean;expectedPackageSha256?: string;trustOverride?: GhostHostTrustOverride;- installOrigin?: string;},): Promise<InstalledGhost> {- // 默认沉睡(2026-07-09 Lizi 定案):装入 ≠ 授权运行,用户在确认框显式勾选- // "立即开启"才带电;沉睡态面板不渲染、总机不列、沙箱不拉起。+ // 初始启用态由入口显式传入;当前用户导入与市场首装都传 true,覆盖更新+ // 则走 manager.update 延续既有状态。保留 false 缺省以兼容内部受控调用方。const result = await manager.install(lizFilePath, {initiallyEnabled: opts.enable ?? false,...(opts.expectedPackageSha256? { expectedPackageSha256: opts.expectedPackageSha256 }: {}),...(opts.trustOverride ? { trustOverride: opts.trustOverride } : {}),- ...(opts.installOrigin !== undefined ? { installOrigin: opts.installOrigin } : {}),});if ('rejection' in result) throwInstallError(result.rejection);// 纵深防御:调用方给错 id 意味着刚才那把锁上在了错误的键上(等于没上锁)。@@ -5405,6 +5364,200 @@ async function installAndDockLocked(return result.ghost;}+type InspectedGhostPackage = Exclude<+ Awaited<ReturnType<GhostManager['inspect']>>,+ { rejection: InstallRejection }+>;++/**+ * 本地包原位更新的共享事务。调用方必须已经持有 owner lease 和对应 ghostId+ * 的安装锁;Renderer 导入与 Forge 显式安装共用,避免两条路径在运行时、OAuth、+ * 市场来源解绑和失败恢复上产生漂移。+ */+async function updateLocalGhostPackageLocked(+ manager: GhostManager,+ cindyFilePath: string,+ inspected: InspectedGhostPackage,+ expectedPackageSha256: string,+ expectedInstalledApproval: string,+ mutationOwner: ActiveAppSession,+): Promise<InstalledGhost> {+ const runtime = getGhostRuntime();+ const marketLedger = getPluginMarketLedger().bind(+ ownerScopedUserDataPath('plugin-market', 'ledger.v1.json'),+ );+ const previousGhost = manager.list().find((g) => g.manifest.id === inspected.manifest.id);+ runtime.stop(inspected.manifest.id);+ // 等待失败表示旧进程仍可能存活;此时不能恢复 resident,否则会产生+ // 两份后台进程。仅在确认退出后的更新阶段失败时恢复旧版本。+ await getGhostNodeRuntimeBroker().stopAndWait(inspected.manifest.id);+ let marketRecord: PluginMarketInstallationRecord | null;+ let marketInstallSubject: string | null = null;+ let marketRecordWasSuppressed = false;+ try {+ marketRecord = marketLedger.installationForGhost(inspected.manifest.id);+ if (+ marketRecord?.installed &&+ (marketRecord.source === 'market' || marketRecord.source === 'legacy-adopted')+ ) {+ marketInstallSubject = getCurrentUserId() ?? mutationOwner.dataOwnerId;+ marketRecordWasSuppressed = marketInstallSubject+ ? marketLedger.isDefaultInstallSuppressed(marketInstallSubject, marketRecord.pluginId)+ : false;+ }+ } catch (error) {+ if (previousGhost) spawnIfResident(previousGhost);+ log.warn('failed to verify Plugin provenance before local update', {+ ghostId: inspected.manifest.id,+ error: error instanceof Error ? error.message : String(error),+ });+ throwIpcError('INTERNAL', 'Unable to verify the installed Plugin source');+ }+ // 用户已明确选择了这份本地真实包:同 id 可以原位替换,市场来源不是永久所有权。+ // 替换前先切断旧市场更新路由;落位失败再恢复,不清理按 ghostId 保存的用户状态。+ const detachMarketRecord = Boolean(marketRecord?.installed);+ const restoreMarketRecord = (): void => {+ if (!detachMarketRecord || !marketRecord) return;+ try {+ marketLedger.restoreInstallation(+ marketRecord,+ marketInstallSubject+ ? {+ userId: marketInstallSubject,+ suppressed: marketRecordWasSuppressed,+ }+ : undefined,+ );+ } catch (error) {+ // 恢复失败时保持路由失效是安全降级:不能让旧市场自动覆盖用户明确选择的本地包。+ log.error('failed to restore Plugin market provenance after local update failure', {+ ghostId: inspected.manifest.id,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ };+ if (detachMarketRecord) {+ try {+ // 先持久化切断自动更新路由,再改真实包。账本不可写时不触碰包。+ marketLedger.markRemoved(inspected.manifest.id, marketInstallSubject);+ } catch (error) {+ restoreMarketRecord();+ if (previousGhost) spawnIfResident(previousGhost);+ log.warn('failed to detach Plugin market provenance before local update', {+ ghostId: inspected.manifest.id,+ error: error instanceof Error ? error.message : String(error),+ });+ throwIpcError('INTERNAL', 'Unable to detach the installed Plugin source');+ }+ }+ getGhostAgentSlot().clearGhost(inspected.manifest.id);+ getGhostErrandSlot().clearGhost(inspected.manifest.id);+ let result: Awaited<ReturnType<typeof manager.update>>;+ let packagePlaced = false;+ try {+ result = await withActiveOwnerGhostOauthMutationLock(inspected.manifest.id, () =>+ manager.update(cindyFilePath, {+ expectedPackageSha256,+ expectedInstalledApproval,+ ...(previousGhost+ ? {+ beforePackageCommit: () =>+ getGhostOauthAccountManager().prepareAccountsForChangedClients(+ withRuntimeFiloGoogleClient(previousGhost.manifest),+ withRuntimeFiloGoogleClient(inspected.canonicalManifest),+ ),+ }+ : {}),+ onPackagePlaced: () => {+ packagePlaced = true;+ },+ }),+ );+ } catch (err) {+ if (!packagePlaced) {+ restoreMarketRecord();+ if (previousGhost) spawnIfResident(previousGhost);+ throw err;+ }+ const placed = manager.list().find((ghost) => ghost.manifest.id === inspected.manifest.id);+ if (!placed) throw err;+ log.warn('local ghost post-placement notification failed', {+ ghostId: inspected.manifest.id,+ error: err instanceof Error ? err.message : String(err),+ });+ result = { ghost: placed };+ }+ if ('rejection' in result) {+ // 回滚失败时安装目录可能已是新字节或缺失,不能恢复旧 runtime 或旧市场来源路由。+ if (!(result.rejection.code === 'io' && result.rejection.rollbackFailed)) {+ restoreMarketRecord();+ if (previousGhost) spawnIfResident(previousGhost);+ }+ throwInstallError(result.rejection);+ }+ runtime.resetFuse(inspected.manifest.id);+ const store = getLayoutStore();+ const docked = layoutWithGhostPanel(store.getLayout(), result.ghost.manifest);+ if (docked) {+ const applied = store.setLayout(docked);+ if ('rejection' in applied) {+ log.warn('ghost panel dock rejected', {+ id: result.ghost.manifest.id,+ reason: applied.rejection,+ });+ }+ }+ spawnIfResident(result.ghost);+ return result.ghost;+}++/**+ * Forge 的显式安装入口。调用方在打包前已经取得 owner lease,并把它持有到本函数+ * 返回;这里复核精确包哈希,再与 Renderer 本地导入共用相同安装/更新事务。+ */+export async function installOrUpdateLocalGhostPackageFromForge(+ cindyFilePath: string,+ expected: { ghostId: string; packageSha256: string },+): Promise<{ ghost: InstalledGhost; action: 'installed' | 'updated' }> {+ const manager = getGhostManager();+ const inspected = await manager.inspect(cindyFilePath);+ if ('rejection' in inspected) throwInstallError(inspected.rejection);+ if (+ inspected.manifest.id !== expected.ghostId ||+ inspected.packageSha256 !== expected.packageSha256+ ) {+ throwIpcError('GHOST_FILE_INVALID', '插件文件在打包后发生了变化,请重新安装');+ }+ rejectReservedGhostId(inspected.manifest.id);+ rejectBrokerWithoutDeclaredRedirectPort(inspected.manifest);+ rejectUnauthorizedTokenBroker(inspected.manifest);++ return withGhostInstallLock(inspected.manifest.id, async () => {+ const installed = manager.list().find((ghost) => ghost.manifest.id === inspected.manifest.id);+ if (!installed) {+ return {+ ghost: await installAndDockLocked(manager, cindyFilePath, {+ ghostId: inspected.manifest.id,+ enable: true,+ expectedPackageSha256: expected.packageSha256,+ }),+ action: 'installed',+ };+ }+ return {+ ghost: await updateLocalGhostPackageLocked(+ manager,+ cindyFilePath,+ inspected,+ expected.packageSha256,+ ghostInstallApprovalToken(installed.approval),+ getActiveAppSession(),+ ),+ action: 'updated',+ };+ });+}+/*** Plugin 市场专用装入入口。市场包已由 plugin-server 绑定到稳定 Plugin ID,* 因而允许官方保留前缀;本地文件入口仍继续走 rejectReservedGhostId。@@ -5418,13 +5571,9 @@ export async function installOrUpdateMarketGhostPackage(/** receipt 模型并发护栏:更新分支比对 receipt 派生 token(与 main 硬化叠加,决策 A)。 */expectedInstalledApproval?: string;/**- * 用户已确认的 reviewedManifest 是权限上限:真实包没有超出则不再弹 Host。- * 没有这份上限时,手动首装仍确认真实包,同来源更新仅在相对已装基线扩权时确认。- * 默认安装(cap)只把目录 manifest 当作 fail-closed 上限,目录本身不记作批准。+ * 市场发现层已经公开的 Manifest。真实包可以缩小能力,但不能携带发现层+ * 没有声明的 Host 能力;超出时按包内容不一致拒绝,不转成用户授权弹窗。*/- permissionPolicy?:- | { mode: 'manual'; sourceType: PluginMarketItemSource }- | { mode: 'cap'; manifest: GhostManifest; sourceType: PluginMarketItemSource };/*** Organization server-market packages pass this Host-built fact because the* ledger row is written after install/update. Official-prefix ids never@@ -5433,13 +5582,7 @@ export async function installOrUpdateMarketGhostPackage(* defaultInstall, and source replacement.*/pendingMarketRecord?: GhostFirstPartyPendingMarketRecord;- /** 安装锁内从当前已落位包读取的 canonical 权限基线。 */- permissionBaselineManifest?: GhostManifest;- /** 用户已在页面确认过的权限清单;真实包未超出则跳过 Host。 */- reviewedManifest?: GhostManifest;- /** 用户确认过的真实下载包 SHA 与确认时的已装权限基线。 */- approvedPackageSha256?: string;- reviewedBaseline?: string;+ manifestCap?: GhostManifest;beforeCommitInLock?: () => void;/** 新包已经原子换位;后续异常不能再按落位失败回滚来源路由。 */onPackagePlacedInLock?: () => void;@@ -5461,15 +5604,9 @@ async function installOrUpdateMarketGhostPackageLocked(ghostId: string;version: string;expectedInstalledApproval?: string;- permissionPolicy?:- | { mode: 'manual'; sourceType: PluginMarketItemSource }- | { mode: 'cap'; manifest: GhostManifest; sourceType: PluginMarketItemSource };/** Same Host-built org server-market fact as the exported entry; not first-install only. */pendingMarketRecord?: GhostFirstPartyPendingMarketRecord;- permissionBaselineManifest?: GhostManifest;- reviewedManifest?: GhostManifest;- approvedPackageSha256?: string;- reviewedBaseline?: string;+ manifestCap?: GhostManifest;beforeCommitInLock?: () => void;/** 新包已经原子换位;后续异常不能再按落位失败回滚来源路由。 */onPackagePlacedInLock?: () => void;@@ -5482,7 +5619,6 @@ async function installOrUpdateMarketGhostPackageLocked(const manager = getGhostManager();const inspected = await manager.inspect(cindyFilePath);if ('rejection' in inspected) throwInstallError(inspected.rejection);- assertGhostSupportsCurrentCindy(inspected.canonicalManifest);// Publisher identity slugs stay reserved even on the market path.// Official reserved prefixes from shared/ghost.ts remain exempt here; publisher slugs do not.rejectReservedPublisherSlug(inspected.canonicalManifest.id);@@ -5497,105 +5633,24 @@ async function installOrUpdateMarketGhostPackageLocked(? 'cindy-official': undefined;requireGhostAvailableForActiveSession(expected.ghostId);- /**- * 「审阅过的」与「真要装的」权限必须一致(2026-08-03,codex review P1)。- *- * 装入确认框渲染的是**来源方给的 manifest**(服务端市场 = release manifest,- * 自定义市场 = 抓到的 ghost.json),而真正落地的是 `.cindy` 包里的 ghost.json。- * 两者本该同一份,但来源方的投影层可能与客户端的清单契约漂移——`cindy-protocol`- * 那份平行校验器就已经缺了 `confirm` 槽;新登记的槽(如 `badge`)在它眼里是- * 未知槽名,投影时会被丢掉或整份拒绝。结果:确认框漏列该项权限,包却原样带着- * 它装进来,用户**从没审过就多出一个常驻能力面**。- *- * 这里按权限项逐项比对。包里多出来的权限先暂停落位,由 Renderer 按真实包- * 重新展示;用户批准后携带包 SHA 和已装权限基线重试。- * 卡点落在 inspect 之后、任何落地动作之前,所以等待复核时磁盘上什么都没动。- * (token broker 授权校验由下方 rejectUnauthorizedTokenBroker(canonicalManifest) 统一执行,- * 原 receipt 分支在此处的硬中止已被本可恢复复核取代,见约束文档 §11 整合任务①。)- */+ // 市场投影只作为真实包的能力上限,避免分发内容与目录声明漂移;+ // 安装动作本身不承担能力授权,也不会因此追加权限确认弹窗。const installed = manager.list().find((ghost) => ghost.manifest.id === expected.ghostId);- if (expected.permissionPolicy) {- const baselineManifest = expected.permissionBaselineManifest ?? null;- const installedBaseline = baselineManifest- ? ghostPermissionBaselineKey(baselineManifest)- : null;- // 批准始终绑定 Main 实际检查过的包 SHA 与本地已装权限基线。- if (- expected.approvedPackageSha256 !== undefined &&- (expected.approvedPackageSha256 !== inspected.packageSha256 ||- (expected.reviewedBaseline ?? null) !== installedBaseline)- ) {- throwIpcError(- 'PRECONDITION_FAILED',- 'Downloaded Plugin package changed after permission review',- );- }- const permissionDiff = baselineManifest- ? diffGhostPermissionItems(baselineManifest, inspected.canonicalManifest)- : null;- const unreviewed =- expected.permissionPolicy.mode === 'cap'- ? unreviewedGhostPermissionItems(- expected.permissionPolicy.manifest,- baselineManifest ?? undefined,- inspected.canonicalManifest,- )- : [];- const extrasVersusReviewed = expected.reviewedManifest- ? unreviewedGhostPermissionItems(- expected.reviewedManifest,- baselineManifest ?? undefined,- inspected.canonicalManifest,- )- : null;- const builtinOauthClientChanged = marketPackageOauthIdentityChanged(- expected.reviewedManifest,- baselineManifest,- inspected.canonicalManifest,- );- const manualSummaryChanged = marketPackageManualSummaryChanged(- expected.reviewedManifest,+ if (expected.manifestCap) {+ const undeclaredCapabilities = unreviewedGhostPermissionItems(+ expected.manifestCap,+ undefined,inspected.canonicalManifest,);- const needsReview = marketPackageNeedsHostReview({- mode: expected.permissionPolicy.mode,- builtinOauthClientChanged,- manualSummaryChanged,- addedCount: permissionDiff === null ? null : permissionDiff.added.length,- unreviewedCount: unreviewed.length,- extrasVersusReviewedCount:- extrasVersusReviewed === null ? null : extrasVersusReviewed.length,- });- if (needsReview && expected.approvedPackageSha256 === undefined) {- const reviewKeys =- extrasVersusReviewed !== null- ? extrasVersusReviewed.map((item) => item.key)- : expected.permissionPolicy.mode === 'manual'- ? (permissionDiff?.added.map((item) => item.key) ?? [])- : unreviewed.map((item) => item.key);- const reviewDiff = marketPackageHostReviewDiff({- permissionDiff,- extrasVersusReviewedCount:- extrasVersusReviewed === null ? null : extrasVersusReviewed.length,- builtinOauthClientChanged,- manualSummaryChanged,- });- const review: PluginMarketPackageReviewFacts = {- manifest: inspected.manifest,- permissionDiff: reviewDiff,- isUpdate: installed !== undefined,- packageSha256: inspected.packageSha256,- installedBaseline,- sourceType: expected.permissionPolicy.sourceType,- builtinOauthClientChanged,- };- log.info('market package requires permission review', {+ if (undeclaredCapabilities.length > 0) {+ log.warn('market package exceeds catalog manifest capabilities', {ghostId: expected.ghostId,- mode: expected.permissionPolicy.mode,- keys: reviewKeys,- builtinOauthClientChanged,+ keys: undeclaredCapabilities.map((item) => item.key),});- throw new GhostPackagePermissionReviewRequiredError(review);+ throwIpcError(+ 'GHOST_FILE_INVALID',+ 'Downloaded Plugin package capabilities exceed the market manifest',+ );}}rejectUnauthorizedTokenBroker(@@ -5610,21 +5665,18 @@ async function installOrUpdateMarketGhostPackageLocked(: undefined,);- // Node 高风险条目由 renderer 装入确认卡权限清单如实展示;- // 2026-07-24 Lizi 定案:不再有 Main 侧原生二次确认弹窗(PR #333,本处为其- // 漏删的市场安装路径调用点,一并对齐)。+ // Manifest 能力只用于 Host 注册、校验和运行时守门。用户点击安装后不再+ // 经过插件级权限确认;真实包仍必须通过上面的市场声明上限与 Host 校验。// Hold the owner-stability lease only for the actual Ghost filesystem// mutation.releaseMutation = beginGhostMutation(mutationOwner);if (!installed) {- // 2026-07-26 定案:市场首装一律装完即开(defaultInstall 与手动安装归一),- // 用户不必再手动点一次开关。市场包走官方分发链路(服务端校验 + sha256- // 校验下载),且确认框如实展示权限清单,确认安装即授权运行;本地 .cindy- // 文件装入的初始启用态仍由确认框勾选决定(勾选默认开启,main 侧- // installAndDock 缺省不启用,授权判断始终来自 UI 显式值)。+ // 市场首装一律装完即开(defaultInstall 与手动安装归一),用户不必再手动+ // 点一次开关。市场包走服务端校验 + sha256 下载校验,并受目录 manifest+ // 能力上限约束;本地 .cindy 由明确的文件选择、拖入或双击动作直接装入。// expectedPackageSha256 把"检查过的字节"与"落位的字节"钉死为同一份:// inspect 与 install 各自重读磁盘,临时 .cindy 在两读之间被替换时,- // 所有前置校验(保留前缀/审阅比对/签名/解压上限)都会作用在旧字节上。+ // 所有前置校验(保留前缀/能力上限/签名/解压上限)都会作用在旧字节上。// 本地 .cindy 装入通道已强制此对账,市场通道同一口径。expected.beforeCommitInLock?.();return installAndDock(manager, cindyFilePath, {@@ -5991,7 +6043,7 @@ export function registerGhostIpc(): void {.map((s) => s.key).concat(nodeSecretDecls.map((s) => s.key));// login-email 派生身份:GET 状态回查附 identity(= 当前登录邮箱,设置页- // 只读展示"用的是哪个身份")。回给意识不算新增泄露面——装入确认框已+ // 只读展示"用的是哪个身份")。回给意识不算新增泄露面——插件详情已// 披露"将使用你的登录邮箱",且注入时它自己的服务端本就可见。写/删 405。const identitySecretKeys = networkSecretDecls.filter((s) => s.source === 'login-email')@@ -6439,7 +6491,7 @@ export function registerGhostIpc(): void {if (type === 'fs-request') {return getGhostFsSlot().handleFsRequest(id, payload);}- // library-request = library 槽持久作品库(资格审/binding 根解析/owner scope+ // library-request = library 持久作品库(资格审/binding 根解析/owner scope// 复核/SQL 语句门在 librarySlot;结果结构化 errorCode,永不 reject)。if (type === 'library-request') {return getGhostLibrarySlot().handleLibraryRequest(id, payload);@@ -6956,13 +7008,13 @@ export function registerGhostIpc(): void {if (typeof lizFilePath !== 'string' || lizFilePath.trim().length === 0) {throwIpcError('INVALID_PARAMS', 'lizFilePath must be a non-empty string');}- const installOpts = opts as {- enable?: unknown;- expectedPackageSha256?: unknown;- packTicket?: unknown;- } | undefined;+ const installOpts = opts as+ | {+ enable?: unknown;+ expectedPackageSha256?: unknown;+ }+ | undefined;const expectedPackageSha256 = installOpts?.expectedPackageSha256;- const packTicket = typeof installOpts?.packTicket === 'string' ? installOpts.packTicket : undefined;if (typeof expectedPackageSha256 !== 'string' ||!/^[a-f0-9]{64}$/.test(expectedPackageSha256)@@ -6971,57 +7023,27 @@ export function registerGhostIpc(): void {}const probe = await manager.inspect(lizFilePath);if ('rejection' in probe) throwInstallError(probe.rejection);- assertGhostSupportsCurrentCindy(probe.canonicalManifest);if (probe.packageSha256 !== expectedPackageSha256) {- throwIpcError('GHOST_FILE_INVALID', '插件文件在确认后发生了变化,请重新选择并确认');+ throwIpcError('GHOST_FILE_INVALID', '插件文件在检查后发生了变化,请重新选择');}rejectReservedGhostId(probe.manifest.id);- // Node 高风险提示在 renderer 装入确认卡的权限清单里如实展示;- // 2026-07-24 Lizi 定案:不再追加 Main 原生二次确认弹窗。+ rejectBrokerWithoutDeclaredRedirectPort(probe.manifest);+ rejectUnauthorizedTokenBroker(probe.manifest);+ // Node 等高风险能力在插件详情中如实展示;安装事务不追加能力确认弹窗。const enable = installOpts?.enable === true;// owner 租约在锁外整段持有(防中途 owner 切换把落位写进新 owner);按 ghostId 的// 互斥锁由 installAndDock 自动获取(卡点),这里传 id 即可。二者语义不同,叠加保留。const releaseMutation = beginGhostMutation(mutationOwner);- let forgeInstall: ReturnType<typeof consumeForgePackAtInstall> = { kind: 'manual' };try {- const forgeController = getForgePackStagingControllerIfConfigured();- if (packTicket && !forgeController) {- throwIpcError('GHOST_FILE_INVALID', '插件打包凭证已失效,请重新打包并确认');- }- forgeInstall = forgeController- ? consumeForgePackAtInstall(forgeController, {- packTicket,- packageSha256: probe.packageSha256,- manifestId: probe.manifest.id,- currentOwner: mutationOwner,- boundaryPending: isAppSessionBoundaryPending(),- })- : ({ kind: 'manual' } as const);- if (forgeInstall.kind === 'rejected') {- if (forgeInstall.reason === 'session-boundary-pending') {- throwIpcError('PRECONDITION_FAILED', '账号切换中,请稍后再试');- }- throwIpcError('GHOST_FILE_INVALID', '插件打包凭证已失效,请重新打包并确认');- }- const installOrigin = forgeInstall.kind === 'agent-forge' ? 'agent-forge' : 'manual';- rejectUnauthorizedTokenBroker(probe.manifest, { installOrigin });return {ghost: await installAndDock(manager, lizFilePath, {ghostId: probe.manifest.id,enable,expectedPackageSha256,- installOrigin,}),};} finally {releaseMutation();- if (forgeInstall.kind === 'agent-forge') {- try {- releaseForgePackStaging(forgeInstall.ticket.stagingPath);- } catch {- // Staging cleanup must not leak the owner mutation lease.- }- }}});@@ -7039,12 +7061,10 @@ export function registerGhostIpc(): void {| {expectedPackageSha256?: unknown;expectedInstalledApproval?: unknown;- packTicket?: unknown;}| undefined;const expectedPackageSha256 = updateOptions?.expectedPackageSha256;const expectedInstalledApproval = updateOptions?.expectedInstalledApproval;- const packTicket = typeof updateOptions?.packTicket === 'string' ? updateOptions.packTicket : undefined;if (typeof expectedPackageSha256 !== 'string' ||!/^[a-f0-9]{64}$/.test(expectedPackageSha256)@@ -7057,199 +7077,39 @@ export function registerGhostIpc(): void {'expectedInstalledApproval must come from ghosts:list',);}- const marketLedger = getPluginMarketLedger().bind(- ownerScopedUserDataPath('plugin-market', 'ledger.v1.json'),- );const inspected = await manager.inspect(lizFilePath);if ('rejection' in inspected) throwInstallError(inspected.rejection);- assertGhostSupportsCurrentCindy(inspected.canonicalManifest);if (inspected.packageSha256 !== expectedPackageSha256) {- throwIpcError('GHOST_FILE_INVALID', '插件文件在确认后发生了变化,请重新选择并确认');+ throwIpcError('GHOST_FILE_INVALID', '插件文件在检查后发生了变化,请重新选择');}rejectReservedGhostId(inspected.manifest.id);+ rejectBrokerWithoutDeclaredRedirectPort(inspected.manifest);+ rejectUnauthorizedTokenBroker(inspected.manifest);// 从熄灯到换版收尾整段持 owner 租约:熄灯之后每一步都在改"当前 owner"的插件世界,// 中途 owner 切换落定会把后半段(update 落盘/停靠/点火)写进新 owner。租约在锁外,// 与市场/本地装入/卸载共用的按 ghostId 互斥叠加(二者语义不同,决策 A 都保留)。// 锁序不变量(违反即死锁):owner lease → per-id lock。const releaseMutation = beginGhostMutation(mutationOwner);- let forgeUpdate: ReturnType<typeof consumeForgePackAtInstall> = { kind: 'manual' };try {- const forgeUpdateController = getForgePackStagingControllerIfConfigured();- if (packTicket && !forgeUpdateController) {- throwIpcError('GHOST_FILE_INVALID', '插件打包凭证已失效,请重新打包并确认');- }- forgeUpdate = forgeUpdateController- ? consumeForgePackAtInstall(forgeUpdateController, {- packTicket,- packageSha256: inspected.packageSha256,- manifestId: inspected.manifest.id,- currentOwner: mutationOwner,- boundaryPending: isAppSessionBoundaryPending(),- })- : ({ kind: 'manual' } as const);- if (forgeUpdate.kind === 'rejected') {- if (forgeUpdate.reason === 'session-boundary-pending') {- throwIpcError('PRECONDITION_FAILED', '账号切换中,请稍后再试');- }- throwIpcError('GHOST_FILE_INVALID', '插件打包凭证已失效,请重新打包并确认');- }- const updateOrigin = forgeUpdate.kind === 'agent-forge' ? 'agent-forge' : 'manual';- rejectUnauthorizedTokenBroker(inspected.manifest, { installOrigin: updateOrigin });- return await withGhostInstallLock(inspected.manifest.id, async () => {- const previousGhost = manager.list().find((g) => g.manifest.id === inspected.manifest.id);- runtime.stop(inspected.manifest.id);- // 等待失败表示旧进程仍可能存活;此时不能恢复 resident,否则会产生- // 两份后台进程。仅在确认退出后的更新阶段失败时恢复旧版本。- await getGhostNodeRuntimeBroker().stopAndWait(inspected.manifest.id);- let marketRecord: PluginMarketInstallationRecord | null;- let marketInstallSubject: string | null = null;- let marketRecordWasSuppressed = false;- try {- marketRecord = marketLedger.installationForGhost(inspected.manifest.id);- if (- marketRecord?.installed &&- (marketRecord.source === 'market' || marketRecord.source === 'legacy-adopted')- ) {- marketInstallSubject = getCurrentUserId() ?? mutationOwner.dataOwnerId;- marketRecordWasSuppressed = marketInstallSubject- ? marketLedger.isDefaultInstallSuppressed(- marketInstallSubject,- marketRecord.pluginId,- )- : false;- }- } catch (error) {- if (previousGhost) spawnIfResident(previousGhost);- log.warn('failed to verify Plugin provenance before local update', {- ghostId: inspected.manifest.id,- error: error instanceof Error ? error.message : String(error),- });- throwIpcError('INTERNAL', 'Unable to verify the installed Plugin source');- }- // 用户已在本地包确认流程中明确选择了这份真实包:同 id 可以原位替换,- // 市场来源不是永久所有权。替换前先切断旧市场更新路由;落位失败再恢复,- // 全程不清理 Secret、KV、偏好或其它按 ghostId 保存的用户状态。- const detachMarketRecord = Boolean(marketRecord?.installed);- const restoreMarketRecord = (): void => {- if (!detachMarketRecord || !marketRecord) return;- try {- marketLedger.restoreInstallation(- marketRecord,- marketInstallSubject- ? {- userId: marketInstallSubject,- suppressed: marketRecordWasSuppressed,- }- : undefined,- );- } catch (error) {- // 恢复失败时保持路由失效是安全降级:不能让旧市场自动覆盖用户- // 明确选择的本地包。用户仍可从任一市场显式替换同 ID 插件。- log.error('failed to restore Plugin market provenance after local update failure', {- ghostId: inspected.manifest.id,- error: error instanceof Error ? error.message : String(error),- });- }- };- if (detachMarketRecord) {- try {- // 先持久化切断自动更新路由,再改真实包。账本不可写时不触碰包,- // 避免同 manifest 的本地代码被旧市场静默覆盖。- marketLedger.markRemoved(inspected.manifest.id, marketInstallSubject);- } catch (error) {- restoreMarketRecord();- if (previousGhost) spawnIfResident(previousGhost);- log.warn('failed to detach Plugin market provenance before local update', {- ghostId: inspected.manifest.id,- error: error instanceof Error ? error.message : String(error),- });- throwIpcError('INTERNAL', 'Unable to detach the installed Plugin source');- }- }- getGhostAgentSlot().clearGhost(inspected.manifest.id);- getGhostErrandSlot().clearGhost(inspected.manifest.id);- let result: Awaited<ReturnType<typeof manager.update>>;- let packagePlaced = false;- try {- result = await withActiveOwnerGhostOauthMutationLock(inspected.manifest.id, () =>- manager.update(lizFilePath, {- expectedPackageSha256,- expectedInstalledApproval,- installOrigin: updateOrigin,- ...(previousGhost- ? {- beforePackageCommit: () =>- getGhostOauthAccountManager().prepareAccountsForChangedClients(- withRuntimeFiloGoogleClient(previousGhost.manifest),- withRuntimeFiloGoogleClient(inspected.canonicalManifest),- ),- }- : {}),- onPackagePlaced: () => {- packagePlaced = true;- },- }),- );- } catch (err) {- if (!packagePlaced) {- restoreMarketRecord();- // 更新失败:恢复旧版本的常驻 Node 工作进程(如果是 resident 且已启用)- if (previousGhost) spawnIfResident(previousGhost);- throw err;- }- const placed = manager.list().find((ghost) => ghost.manifest.id === inspected.manifest.id);- if (!placed) throw err;- log.warn('local ghost post-placement notification failed', {- ghostId: inspected.manifest.id,- error: err instanceof Error ? err.message : String(err),- });- result = { ghost: placed };- }- if ('rejection' in result) {- // 回滚失败 = 安装目录可能已是新字节或缺失,"旧版本还在"不成立,- // 不得按旧 InstalledGhost 重启运行时(P1:那会拿旧批准跑未知字节)。- // 同样不得恢复旧市场来源路由——那会把不一致的字节绑定回原来源,- // 未来市场版本对账可能按旧 provenance 操作错位插件- // (P1, PRRT_kwDOTgdRUs6YcG8r)。- if (!(result.rejection.code === 'io' && result.rejection.rollbackFailed)) {- restoreMarketRecord();- }- if (previousGhost &&- !(result.rejection.code === 'io' && result.rejection.rollbackFailed)) {- spawnIfResident(previousGhost);- }- throwInstallError(result.rejection);- }- runtime.resetFuse(inspected.manifest.id); // 换了代码,给新版本干净的熔断记账- const store = getLayoutStore();- const docked = layoutWithGhostPanel(store.getLayout(), result.ghost.manifest);- if (docked) {- const applied = store.setLayout(docked);- if ('rejection' in applied) {- log.warn('ghost panel dock rejected', {- id: result.ghost.manifest.id,- reason: applied.rejection,- });- }- }- spawnIfResident(result.ghost); // 常驻意识:换完代码立即用新版本点火- return { ghost: result.ghost };- });+ return {+ ghost: await withGhostInstallLock(inspected.manifest.id, () =>+ updateLocalGhostPackageLocked(+ manager,+ lizFilePath,+ inspected,+ expectedPackageSha256,+ expectedInstalledApproval,+ mutationOwner,+ ),+ ),+ };} finally {releaseMutation();- if (forgeUpdate.kind === 'agent-forge') {- try {- releaseForgePackStaging(forgeUpdate.ticket.stagingPath);- } catch {- // Staging cleanup must not leak the owner mutation lease.- }- }}});// 设置页「装入意识…」第一步:系统文件选择框(按 .cindy 过滤),只选不装。- // 后续 inspect → 确认弹窗 → install 由 renderer 编排(三个装入入口共用- // "先验明正身再确认"的契约)。取消选择返回 { canceled: true },不算错误。+ // 后续 inspect → install 由 renderer 编排;取消选择返回 { canceled: true },不算错误。ipcMain.handle('ghosts:pick-file', async (event) => {assertTrustedAppRendererEvent(event);const win = BrowserWindow.fromWebContents(event.sender);@@ -7263,142 +7123,13 @@ export function registerGhostIpc(): void {});// 双击 .cindy 的待装路径:renderer 在 install-requested 信号或挂载时原子- // 取走(取即清空),随后走与按钮/拖入完全相同的确认装入编排。+ // 取走(取即清空),随后走与按钮/拖入完全相同的装入编排。ipcMain.handle('ghosts:take-pending-install', (event) => {assertTrustedAppRendererEvent(event);- // 路径与来源一起返回:来源是确认框加重展示的依据,不能走比路径更易失的- // 通道(理由见 openFileInstall.ts 头注释)。- const pending = takePendingCindyInstall();- return {- filePath: pending?.filePath ?? null,- origin: pending?.origin ?? MANUAL_GHOST_INSTALL_ORIGIN,- };+ return { filePath: takePendingCindyInstall() };});- // 本地包第三条恢复路径第一步:从**已装目录**读出确认卡事实,零副作用。- // 批准丢失(迁移后 receipt 又损坏/被删)时不用用户翻出原始 .cindy —— 字节从安装- // 目录读,权限清单全量展示,确认后由 ghosts:reapprove-installed 开 receipt。- // inspect 时点的 owner 与事实用一次性票据钉死,confirm 原子消费(P0-2):只回传- // manifestSha256 绑不住 owner —— 多账号下确认卡停留期间切号,A 看的确认可以给 B- // 的同 id 目录铸批准。票据 Host 进程内持有,renderer 只透传 opaque token。- const reapproveTickets = createOneShotTicketStore<{- owner: ActiveAppSession;- id: string;- manifestSha256: string;- approvalProjectionSha256: string;- }>({ ttlMs: 10 * 60 * 1000, maxEntries: 64 });- ipcMain.handle('ghosts:reapprove-inspect', async (event, id: unknown) => {- assertTrustedAppRendererEvent(event);- if (typeof id !== 'string' || id.trim().length === 0) {- throwIpcError('INVALID_PARAMS', 'id must be a non-empty string');- }- requireGhostAvailableForActiveSession(id);- rejectReservedGhostId(id);- // owner 在读事实**之前**捕获(边界期直接抛):票据钉的是"这份事实属于哪个 owner"。- const owner = captureGhostMutationOwner();- const result = await manager.inspectInstalledReapproval(id);- if ('rejection' in result) throwInstallError(result.rejection);- rejectUnauthorizedTokenBroker(result.manifest);- const inspectTicket = reapproveTickets.issue({- owner,- id,- manifestSha256: result.manifestSha256,- approvalProjectionSha256: result.approvalProjectionSha256,- });- return {- manifest: result.manifest,- trust: result.trust,- manifestSha256: result.manifestSha256,- approvalProjectionSha256: result.approvalProjectionSha256,- previouslyEnabled: result.previouslyEnabled,- inspectTicket,- };- });-- // 第三条恢复路径第二步:用户点过确认卡后开 receipt。expectedManifestSha256 绑定- // 「确认卡展示的」与「此刻批准的」清单字节(与更新流程 expectedPackageSha256 同形),- // expectedInstalledApproval 防确认期间批准状态被并发改写。- ipcMain.handle('ghosts:reapprove-installed', async (event, id: unknown, opts: unknown) => {- assertTrustedAppRendererEvent(event);- if (typeof id !== 'string' || id.trim().length === 0) {- throwIpcError('INVALID_PARAMS', 'id must be a non-empty string');- }- requireGhostAvailableForActiveSession(id);- // 与本地装入同一道门:官方保留前缀不走用户通道(真随包 id 已被 manager 的- // 种子清单检查拒掉,这里拦的是冒充官方前缀的目录)。- rejectReservedGhostId(id);- const options = opts as- | {- enable?: unknown;- expectedManifestSha256?: unknown;- expectedApprovalProjectionSha256?: unknown;- expectedInstalledApproval?: unknown;- inspectTicket?: unknown;- }- | undefined;- if (typeof options?.enable !== 'boolean') {- throwIpcError('INVALID_PARAMS', 'enable must be a boolean');- }- if (- typeof options.expectedManifestSha256 !== 'string' ||- !/^[a-f0-9]{64}$/.test(options.expectedManifestSha256)- ) {- throwIpcError('INVALID_PARAMS', 'expectedManifestSha256 must come from ghosts:reapprove-inspect');- }- if (- typeof options.expectedApprovalProjectionSha256 !== 'string' ||- !/^[a-f0-9]{64}$/.test(options.expectedApprovalProjectionSha256)- ) {- throwIpcError(- 'INVALID_PARAMS',- 'expectedApprovalProjectionSha256 must come from ghosts:reapprove-inspect',- );- }- if (!isGhostInstallApprovalToken(options.expectedInstalledApproval)) {- throwIpcError('INVALID_PARAMS', 'expectedInstalledApproval must come from ghosts:list');- }- if (typeof options.inspectTicket !== 'string' || options.inspectTicket.length === 0) {- throwIpcError('INVALID_PARAMS', 'inspectTicket must come from ghosts:reapprove-inspect');- }- // 原子消费票据:重放/过期/跨票一律 PRECONDITION_FAILED,让 UI 重开确认卡。- const ticket = reapproveTickets.consume(options.inspectTicket);- if (- !ticket ||- ticket.id !== id ||- ticket.manifestSha256 !== options.expectedManifestSha256 ||- ticket.approvalProjectionSha256 !== options.expectedApprovalProjectionSha256- ) {- throwIpcError('PRECONDITION_FAILED', '确认卡已过期或与检查时不一致,请重新打开确认');- }- // 开 receipt 是 owner 绑定的状态根写路径:租约以**票据里 inspect 时点的 owner**- // 为期望值 —— 确认卡停留期间切了号,generation 不等直接拒,A 的确认给不了 B。- const releaseMutation = beginGhostMutation(ticket.owner);- try {- const result = await manager.reapproveInstalled(id, {- enable: options.enable,- expectedManifestSha256: options.expectedManifestSha256,- expectedApprovalProjectionSha256: options.expectedApprovalProjectionSha256,- expectedInstalledApproval: options.expectedInstalledApproval,- });- if ('rejection' in result) throwInstallError(result.rejection);- // 与装入/更新同款收尾:面板停靠(已有位置则 no-op)+ 常驻点火。- // 必须在 owner 租约内执行 —— 否则账号切换后 dock/spawn 会写到新 owner。- const store = getLayoutStore();- const docked = layoutWithGhostPanel(store.getLayout(), result.ghost.manifest);- if (docked) {- const applied = store.setLayout(docked);- if ('rejection' in applied) {- log.warn('ghost panel dock rejected', { id: result.ghost.manifest.id, reason: applied.rejection });- }- }- spawnIfResident(result.ghost);- return { ghost: result.ghost };- } finally {- releaseMutation();- }- });-- // 只验不装:读出 .cindy 的清单给确认弹窗展示,零副作用。+ // 只验不装:读出 .cindy 的真实清单,供兼容性判断与安装摘要使用,零副作用。ipcMain.handle('ghosts:inspect', async (event, lizFilePath: unknown) => {assertTrustedAppRendererEvent(event);if (typeof lizFilePath !== 'string' || lizFilePath.trim().length === 0) {@@ -7406,51 +7137,19 @@ export function registerGhostIpc(): void {}const result = await manager.inspect(lizFilePath);if ('rejection' in result) throwInstallError(result.rejection);- assertGhostSupportsCurrentCindy(result.canonicalManifest);- // 官方前缀在 inspect 就拒(确认弹窗都不该弹出来),install/update 双保险再拦。+ // 官方前缀在 inspect 就拒,install/update 双保险再拦。rejectReservedGhostId(result.manifest.id);- let packTicket: string | undefined;- const inspectController = getForgePackStagingControllerIfConfigured();- const peekTicket = inspectController?.peekMatchingStagingPath(lizFilePath) ?? null;rejectBrokerWithoutDeclaredRedirectPort(result.manifest);- rejectUnauthorizedTokenBroker(result.manifest, {- installOrigin: peekTicket ? 'agent-forge' : 'manual',- });- const forgeInspect = inspectController- ? consumeForgePackAtInspect(inspectController, {- filePath: lizFilePath,- packageSha256: result.packageSha256,- manifestId: result.manifest.id,- currentOwner: getActiveAppSession(),- boundaryPending: isAppSessionBoundaryPending(),- })- : ({ kind: 'not-forge' } as const);- if (forgeInspect.kind === 'rejected') {- if (forgeInspect.reason === 'session-boundary-pending') {- throwIpcError('PRECONDITION_FAILED', '账号切换中,请稍后再试');- }- throwIpcError('GHOST_FILE_INVALID', '插件打包凭证已失效,请重新打包并确认');- }- if (forgeInspect.kind === 'accepted') packTicket = forgeInspect.packTicket;+ rejectUnauthorizedTokenBroker(result.manifest);return {manifest: result.manifest,trust: result.trust,packageSha256: result.packageSha256,+ unsupportedSlots: result.unsupportedLegacySlots,...(result.iconDataUrl !== undefined ? { iconDataUrl: result.iconDataUrl } : {}),- ...(packTicket ? { packTicket } : {}),};});- ipcMain.handle('ghosts:abandon-pack-ticket', async (event, packTicket: unknown) => {- assertTrustedAppRendererEvent(event);- if (typeof packTicket !== 'string' || packTicket.length === 0) {- throwIpcError('INVALID_PARAMS', 'packTicket must be a non-empty string');- }- const controller = getForgePackStagingControllerIfConfigured();- if (controller) abandonForgePackInstall(controller, packTicket);- return { ok: true };- });-ipcMain.handle('ghosts:uninstall', async (event, id: unknown) => {// 卸载会停运行时、撤 receipt 批准、清凭证/KV/ghost-fs 并删安装目录 —— 与// install/update/set-enabled/export 同级的高权限写路径,来源判定必须由 Main@@ -7490,15 +7189,13 @@ export function registerGhostIpc(): void {const probe = await manager.inspect(filePath);if ('rejection' in probe) return false;// tokenBroker 门控(同 rejectUnauthorizedTokenBroker):官方前缀照旧;- // 其余问已装 receipt 的装入来源与当前组织身份。+ // 其余问已装的市场来源与当前组织身份。const brokered = (probe.manifest.network?.secrets ?? []).some((s) => s.oauth?.tokenBroker !== undefined,);if (brokered &&- !isGhostTokenBrokerAuthorized(probe.manifest.id, 'install', {- installOrigin: manager.readEffectiveInstallOrigin(probe.manifest.id),- })+ !isGhostTokenBrokerAuthorized(probe.manifest.id, 'install')) {return false;}diff --git a/apps/desktop/src/main/cindy-brain/iosSimulatorPluginGate.ts b/apps/desktop/src/main/cindy-brain/iosSimulatorPluginGate.tsindex d8d3b78d94..f91b8098bb 100644--- a/apps/desktop/src/main/cindy-brain/iosSimulatorPluginGate.ts+++ b/apps/desktop/src/main/cindy-brain/iosSimulatorPluginGate.ts@@ -35,7 +35,7 @@ export function resolveIOSSimulatorPluginAccess(workingDir: string | null,deps: IOSSimulatorPluginGateDeps,): IOSSimulatorMcpAccessDecision {- const candidates = ghosts.filter((ghost) => ghost.manifest.slots.includes('ios-simulator'));+ const candidates = ghosts.filter((ghost) => ghost.manifest.iosSimulator === true);if (candidates.length === 0) {return {allowed: false,diff --git a/apps/desktop/src/main/cindy-brain/iosSimulatorSlot.ts b/apps/desktop/src/main/cindy-brain/iosSimulatorSlot.tsindex c527442b99..1f124aebc9 100644--- a/apps/desktop/src/main/cindy-brain/iosSimulatorSlot.ts+++ b/apps/desktop/src/main/cindy-brain/iosSimulatorSlot.ts@@ -109,10 +109,10 @@ export class GhostIOSSimulatorSlot {async handleRequest(ghostId: string, payload: unknown): Promise<GhostPipeIOSSimulatorResult> {const ghost = this.deps.getGhost(ghostId);- if (!ghost?.enabled || !ghost.manifest.slots.includes('ios-simulator')) {+ if (!ghost?.enabled || ghost.manifest.iosSimulator !== true) {return fail('PERMISSION_DENIED',- '插件未申请内置 iOS 模拟器权限(ios-simulator 槽),或当前未启用',+ '插件未申请内置 iOS 模拟器权限(iosSimulator),或当前未启用',);}if (!isRecord(payload) || typeof payload.kind !== 'string') {diff --git a/apps/desktop/src/main/cindy-brain/librarySlot.ts b/apps/desktop/src/main/cindy-brain/librarySlot.tsindex cbe7beb826..4547a94934 100644--- a/apps/desktop/src/main/cindy-brain/librarySlot.ts+++ b/apps/desktop/src/main/cindy-brain/librarySlot.ts@@ -1,5 +1,5 @@/**- * librarySlot.ts — library 槽:持久作品库的协议分派层(2026-08-20)。+ * librarySlot.ts — library 持久作品库的协议分派层(2026-08-20)。* ---------------------------------------------------------------------------* 与 fsSlot 平级,信任边界同源:* - ghostId 一律 webContents 反查(IPC 层),槽内 getGhost 再核资格@@ -92,7 +92,7 @@ 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" 能力');}const req = (payload ?? {}) as Record<string, unknown>;const op = req.op as string;@@ -147,18 +147,18 @@ export class GhostLibrarySlot {* 普通文件的绝对路径,或 null(折叠 404)。经 binding 现解 + vault 路径纪律,* 与 read 同源校验——面板与电子脑看到同一个库。*/- /** 资格审:装入 + 启用 + 声明 library 槽(dispatch 与面板投影共用)。 */+ /** 资格审:装入 + 启用 + 声明 library 能力(dispatch 与面板投影共用)。 */private checkEligibility(ghostId: string): boolean {const ghost = this.deps.getGhost(ghostId);if (!ghost) return false;if (ghost.enabled === false) return false;- return ghost.manifest.slots.includes('library');+ return ghost.manifest.library === true;}/*** 面板投影(cindy-ghost://<id>/library/<relPath>)的宿主侧解析:返回已存在* 普通文件的绝对路径,或 null(折叠 404)。资格审与 dispatch 同源——插件- * 停用或更新后移除 slot 时投影一并熄灭(review:面板路由不复查授权)。+ * 停用或更新后移除能力时投影一并熄灭(review:面板路由不复查授权)。*/async resolvePanelFilePath(ghostId: string, relPath: string): Promise<string | null> {try {diff --git a/apps/desktop/src/main/cindy-brain/librarySqlService.ts b/apps/desktop/src/main/cindy-brain/librarySqlService.tsindex 99512b73ed..e74275cdc7 100644--- a/apps/desktop/src/main/cindy-brain/librarySqlService.ts+++ b/apps/desktop/src/main/cindy-brain/librarySqlService.ts@@ -1,7 +1,7 @@/*** librarySqlService.ts — 主进程侧的插件 Library SQLite RPC 服务。* ---------------------------------------------------------------------------- * 每个声明 library 槽的插件一个 LibrarySqlService 实例(槽层在 commit 4 装配):+ * 每个声明 library 能力的插件一个 LibrarySqlService 实例(分派层装配):* - 语句门在**发送前**执行(main 侧第一道,worker 内 core 复读第二道);* - worker 经 worker_threads 拉起(脚本 = 构建产出的 libraryDbWorker.js,* 与 main 输出同目录;better-sqlite3 模块路径由调用方注入,解析方式与diff --git a/apps/desktop/src/main/cindy-brain/networkSlot.ts b/apps/desktop/src/main/cindy-brain/networkSlot.tsindex 3d6f7f7acd..b8a71aa021 100644--- a/apps/desktop/src/main/cindy-brain/networkSlot.ts+++ b/apps/desktop/src/main/cindy-brain/networkSlot.ts@@ -1,17 +1,19 @@/**- * networkSlot.ts — network 槽代理 fetch(docs/dev-rules/plugin-security-and-authoring.md)。+ * networkSlot.ts — 插件沙箱的主机代理 fetch 边界+ * (docs/dev-rules/plugin-security-and-authoring.md)。* ---------------------------------------------------------------------------- * 意识自带服务的出网通道。沙箱本身保持零直连(electronSandboxAdapter 的- * onBeforeRequest 断网闸不放开),意识想访问自己声明的域名只能经管子上行:+ * 沙箱本身保持零直连(electronSandboxAdapter 的 onBeforeRequest 断网闸+ * 不放开),所有请求都只能经管子上行。授权分两类:当前 Agent tool-call+ * 凭严格在途 callId 复用 Agent 授权;插件自主调用按 network 详单守门。** 电子脑 cindy.send({type:'fetch-request', url, method?, headers?, body?, …})- * → 资格审(声明了 'network' 卡槽 + 详单?)- * → URL 硬校验(仅 https 默认端口;host 命中 network.hosts 白名单)+ * → 调用上下文审(Agent 在途,或已声明自主 network 详单)+ * → URL 硬校验(仅 https 默认端口;自主调用 host 必须命中白名单)* → 意识自带 headers 消毒(协议关键头/凭证类头一律剥除)* → 凭证注入(保险库现读明文,按 secret.inject 声明拼进请求头——* key 只流向它声明的域名;意识代码从头到尾摸不到凭证字节;* 声明了 exchange 的凭证先照单换令牌:缓存 + 单飞 + 401 作废重换)- * → 主机真实 HTTP(注入的 fetchImpl;超时 clamp;重定向逐跳重验白名单)+ * → 主机真实 HTTP(注入的 fetchImpl;超时 clamp;重定向逐跳重验同一边界)* → 响应文本化(体积上限截断;响应头只回白名单字段)* → 只回结构化 GhostPipeFetchResult(永不 reject)*@@ -62,6 +64,16 @@ import {export interface NetworkSlotDeps {getGhost(id: string): InstalledGhost | null;+ /**+ * callId → 严格在途的 Agent 调用上下文。只有 channel:'session'、+ * sessionId 存在且 ghostId 匹配时,才能复用外层 ghost_call 已经+ * 通过的 Cindy Agent 授权;面板、订阅、后台与脚本通道都不在此列。+ */+ inFlightCallInfo?(callId: string): {+ ghostId: string;+ sessionId: string | null;+ channel: 'session' | 'script';+ } | null;/*** 读某意识某条凭证的明文(safeStorage 现读,不缓存——用户改了 key 下一单* 即生效);未配置 / 读失败返回 null。@@ -771,7 +783,8 @@ export class GhostNetworkSlot {if (p.callId !== undefined && (typeof p.callId !== 'string' || p.callId.length === 0 || p.callId.length > MAX_CALL_ID_LEN)) {return { ok: false, message: 'callId 不合法(1–128 字符的字符串,或不传)' };}- const callId = (p.callId as string | undefined) ?? 'unattributed';+ const requestCallId = p.callId as string | undefined;+ const callId = requestCallId ?? 'unattributed';let body: string | Uint8Array | undefined;if (p.body !== undefined) {if (typeof p.body !== 'string') return { ok: false, message: 'body 必须是字符串' };@@ -1006,22 +1019,28 @@ export class GhostNetworkSlot {if ('error' in parsed) return { ok: false, message: parsed.error };const url = parsed.url;- // ── 资格审:意识在场 + 槽 + 详单 ─────────────────────────────────+ // ── 资格审:意识在场 + 能力详单 ───────────────────────────────────const ghost = this.deps.getGhost(ghostId);if (!ghost || !ghost.enabled) {return { ok: false, message: '意识不在可用状态' };}- if (!ghost.manifest.slots?.includes('network')) {- return { ok: false, message: '本意识未声明 network 卡槽,无权出网' };- }const net = ghost.manifest.network;+ const callInfo = requestCallId+ ? this.deps.inFlightCallInfo?.(requestCallId) ?? null+ : null;+ const agentMediated =+ callInfo?.ghostId === ghostId+ && callInfo.channel === 'session'+ && callInfo.sessionId !== null;// 静态 hosts 与动态连接地址(network.connections,用户在设置页添加、// 逐条过主机受信确认)至少有其一,才算"声明过白名单"。const connectionDecls = net?.connections ?? [];- if (!net || (net.hosts.length === 0 && connectionDecls.length === 0)) {+ if ((!net || (net.hosts.length === 0 && connectionDecls.length === 0)) && !agentMediated) {return { ok: false, message: '本意识未声明域名白名单(身份卡缺 network.hosts),请意识作者更新声明' };}- const ghCliSecrets = net.secrets?.filter((secret) => secret.source === 'gh-cli') ?? [];+ const declaredHosts = net?.hosts ?? [];+ const declaredSecrets = net?.secrets ?? [];+ const ghCliSecrets = declaredSecrets.filter((secret) => secret.source === 'gh-cli');if (ghCliSecrets.length > 0 &&(ghost.manifest.id !== 'cindy-github' || !isCindyOfficialTrustInfo(ghost.trust))@@ -1032,12 +1051,15 @@ export class GhostNetworkSlot {// 重定向逐跳都用同一份快照,避免跳转中途清单变化产生放行摇摆。const connectionHosts =connectionDecls.length > 0 ? (this.deps.connections?.hostsFor(ghostId) ?? []) : [];- // 白名单判定:静态条目走通配语义,连接地址只精确匹配(不吃通配)。- const hostAllowed = (hostname: string): boolean =>- net.hosts.some((pattern) => ghostNetworkHostMatches(pattern, hostname)) ||+ // 自主调用仍只能访问 manifest 声明的地址。Agent 在途调用已经+ // 通过外层 ghost_call 的 Cindy 授权,因此可以访问未预声明的普通+ // 地址;但只有真正命中 manifest 详单的 host 才可获得 Host 托管凭证。+ const hostDeclared = (hostname: string): boolean =>+ declaredHosts.some((pattern) => ghostNetworkHostMatches(pattern, hostname)) ||connectionHosts.includes(hostname);+ const hostAllowed = (hostname: string): boolean => agentMediated || hostDeclared(hostname);if (!hostAllowed(url.hostname)) {- const declared = [...net.hosts, ...connectionHosts];+ const declared = [...declaredHosts, ...connectionHosts];return {ok: false,message:@@ -1049,7 +1071,18 @@ export class GhostNetworkSlot {// ── 凭证注入:命中本次目标域名的每条声明凭证,保险库现读明文拼头// (交换型凭证在此换取/取缓存令牌)。未配置的凭证快速失败(带清晰// 指引),不发一个注定 401 的请求。- const inject0 = await this.injectSecrets(ghostId, net.secrets ?? [], connectionDecls, url.hostname, net.hosts, requestHeaders, authAccount);+ // 即使目标是 Agent 临时放行的未声明 host,也必须走一遍+ // injectSecrets:它会删掉上一跳/插件伪造的凭证头,只是不会注入+ // 任何未命中 manifest 详单的 Host 托管凭证。+ const inject0 = await this.injectSecrets(+ ghostId,+ declaredSecrets,+ connectionDecls,+ url.hostname,+ declaredHosts,+ requestHeaders,+ authAccount,+ );if (inject0.error) return { ok: false, message: inject0.error };let usedExchange = inject0.usedExchange;const oauthInjected = new Map(inject0.oauthInjected);@@ -1113,7 +1146,7 @@ export class GhostNetworkSlot {const originalRequestMethod = method;for (let attempt = 0; attempt < 2; attempt++) {if (attempt > 0) {- this.invalidateExchangedTokens(ghostId, net.secrets ?? []);+ this.invalidateExchangedTokens(ghostId, declaredSecrets);for (const [secretKey, accountId] of oauthInjected) {this.deps.oauthTokens?.invalidateAccessToken(ghostId, secretKey, accountId);}@@ -1123,7 +1156,15 @@ export class GhostNetworkSlot {audience: input.audience,});}- const reInject = await this.injectSecrets(ghostId, net.secrets ?? [], connectionDecls, url.hostname, net.hosts, requestHeaders, authAccount);+ const reInject = await this.injectSecrets(+ ghostId,+ declaredSecrets,+ connectionDecls,+ url.hostname,+ declaredHosts,+ requestHeaders,+ authAccount,+ );if (reInject.error) return { ok: false, message: reInject.error };initialConnectionInjected = new Map(reInject.connectionInjected);for (const [k, v] of reInject.oauthInjected) oauthInjected.set(k, v);@@ -1148,7 +1189,15 @@ export class GhostNetworkSlot {if (hop > 0) {// 换了域名的跳转:上一跳注入的凭证不能跟着走,按新 host 重算// (injectSecrets 开头会先把所有声明凭证头的大小写变体删干净)。- const hopInject = await this.injectSecrets(ghostId, net.secrets ?? [], connectionDecls, currentUrl.hostname, net.hosts, hopHeaders, authAccount);+ const hopInject = await this.injectSecrets(+ ghostId,+ declaredSecrets,+ connectionDecls,+ currentUrl.hostname,+ declaredHosts,+ hopHeaders,+ authAccount,+ );if (hopInject.error) return { ok: false, message: hopInject.error };currentConnectionInjected = hopInject.connectionInjected;usedExchange ||= hopInject.usedExchange;diff --git a/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts b/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.tsindex cddfb2e5d1..ee734ad7ff 100644--- a/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts+++ b/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts@@ -486,7 +486,7 @@ export class GhostNodeRuntimeBroker {/** main.js 的 node-request 入口。 */async handleRequest(ghostId: string, payload: unknown): Promise<GhostPipeNodeResult> {const ghost = this.deps.getGhost(ghostId);- if (!ghost?.enabled || !ghost.manifest.slots.includes('node') || !ghost.manifest.node) {+ if (!ghost?.enabled || !ghost.manifest.node) {return errorResult('PERMISSION_DENIED', '插件未申请本地 Node 权限,或当前未启用');}// getGhost 确认插件当前已启用——这是按需插件的"后更新/重启边界",diff --git a/apps/desktop/src/main/cindy-brain/nodeRuntimeWorkerProcess.ts b/apps/desktop/src/main/cindy-brain/nodeRuntimeWorkerProcess.tsindex b608a1857c..092380b171 100644--- a/apps/desktop/src/main/cindy-brain/nodeRuntimeWorkerProcess.ts+++ b/apps/desktop/src/main/cindy-brain/nodeRuntimeWorkerProcess.ts@@ -17,8 +17,7 @@* [node, entryPath, ...args],让 Maker 这类库以为自己被 node 正常启动。** 插件代码拥有当前系统用户级本机权限。这里提供的是进程隔离与通信收口,不是- * OS 沙箱;授权入口是装入确认卡的权限清单(2026-07-24 起不再有 Main 原生- * 二次确认弹窗)。+ * OS 沙箱;能力在插件详情中披露,运行期由 Main 按 manifest 严格守门。*/import { EventEmitter } from 'node:events';diff --git a/apps/desktop/src/main/cindy-brain/notifySlot.ts b/apps/desktop/src/main/cindy-brain/notifySlot.tsindex 3674d3d121..8240711f40 100644--- a/apps/desktop/src/main/cindy-brain/notifySlot.ts+++ b/apps/desktop/src/main/cindy-brain/notifySlot.ts@@ -75,8 +75,8 @@ export class GhostNotifySlot {if (!ghost || !ghost.enabled) {return { ok: false, message: '意识不在可用状态' };}- if (!ghost.manifest.slots?.includes('notify')) {- return { ok: false, message: '本意识未声明 notify 卡槽,无权弹系统提示' };+ if (ghost.manifest.notify !== true) {+ return { ok: false, message: '本意识未声明 notify 能力,无权弹系统提示' };}if (typeof p?.text !== 'string') {diff --git a/apps/desktop/src/main/cindy-brain/openFileInstall.ts b/apps/desktop/src/main/cindy-brain/openFileInstall.tsindex fd3a96e554..eb44d1df9e 100644--- a/apps/desktop/src/main/cindy-brain/openFileInstall.ts+++ b/apps/desktop/src/main/cindy-brain/openFileInstall.ts@@ -3,83 +3,47 @@ import fs from 'node:fs';import { BrowserWindow } from 'electron';import { createLogger } from '../logger.js';-import {- MANUAL_GHOST_INSTALL_ORIGIN,- type GhostInstallOrigin,-} from '../../shared/ghostInstallOrigin.js';/*** 双击 .cindy 文件的转交通道。*- * 主进程**不在这里装、也不在这里弹窗**:三个装入入口(设置页 / 拖入 / 双击)- * 统一走 renderer 的同一套编排(installFlow:inspect 验明正身 → 应用内确认- * 弹窗 → install),双击只是把文件路径递进去 —— 用户看到的确认框永远是同- * 一个。+ * 主进程**不在这里装**:三个装入入口(设置页 / 拖入 / 双击)统一走+ * renderer 的同一套一键编排(installFlow:inspect 验明正身 → install),+ * 双击只负责把文件路径递进去。** 转交模型(对齐 deepLink 的 pending buffer 成熟套路):- * - 收到路径与来源 → 一起存入 pending(仅保留最新一条;双击语义上就是"装这一个")- * → 广播信号 ghosts:install-requested(**纯通知,不带事实**);+ * - 收到路径 → 存入 pending(仅保留最新一条;双击语义上就是"装这一个")+ * → 广播信号 ghosts:install-requested;* - renderer(GlobalDropImportListener)在信号或自身挂载时调* ghosts:take-pending-install 原子取走并消费 —— 冷启动双击时* renderer 尚未挂载,pending 缓冲天然覆盖,不丢意图、不重复消费。*- * **来源标记(origin)**:装入确认框要区分"用户亲手发起"和"Agent 单方面发起"- * (`ghost_forge_pack` 转交)。来源是主机侧结论,绝不能走 agent 可控通道 ——- * 它由本模块填写,agent 只能触发转交、碰不到这个值。- *- * **origin 必须与路径同存同取,不能只挂在广播 payload 上。** 广播是易失通道:- * macOS 关窗后应用不退出,scheduler 拉起的 agent 照样能调 `ghost_forge_pack`,- * 此时没有任何窗口接收广播,而路径仍在缓冲里等着 renderer 挂载后自取 ——- * 若 origin 只在 payload 里,这一取就把它丢了,Agent 发起的装入会被显示成手动,- * 来源横幅与手输 id 全部失效。**丢失方向恰好是最危险的那个**,所以两者绑在一起。- ** 入口(与 deepLink / open-folder 的结构对齐):* - Windows 冷启动:文件路径在 process.argv(bootstrap 扫描);* - Windows 已运行:单例锁转 second-instance,路径在其 argv;- * - macOS:Finder 经 CFBundleDocumentTypes 关联走 open-file 事件;- * - Agent:`ghost_forge_pack` 打包成功后经本通道转交(source='ghost-forge',- * 带 agent-forge origin)。+ * - macOS:Finder 经 CFBundleDocumentTypes 关联走 open-file 事件。*/const log = createLogger('ghosts:open-file');-let pendingCindyInstall: { filePath: string; origin: GhostInstallOrigin } | null = null;+let pendingCindyInstall: string | null = null;-/**- * renderer 原子取走待装路径与来源(取即清空;无则 null)。IPC handler 消费。- *- * 来源与路径**必须一起存、一起取**:两者存在不同强度的通道里就会丢。- * 反例(已修):把 origin 只挂在 `ghosts:install-requested` 广播 payload 上时,- * macOS 关窗后应用不退出,scheduler 拉起的 agent 照样能调 `ghost_forge_pack`——- * 此刻 `getAllWindows()` 为空,广播无人接收,路径仍留在缓冲里;用户之后开窗,- * renderer 挂载自取,origin 已经丢了 → Agent 发起的装入被显示成手动,- * 红色来源横幅与手输 id 全部失效。**恰好是最危险的丢失方向。**- */-export function takePendingCindyInstall(): { filePath: string; origin: GhostInstallOrigin } | null {- const pending = pendingCindyInstall;+/** renderer 原子取走待装路径(取即清空;无则 null)。IPC handler 消费。 */+export function takePendingCindyInstall(): string | null {+ const path = pendingCindyInstall;pendingCindyInstall = null;- return pending;+ return path;}-export async function handleIncomingCindyFile(- filePath: string,- source: string,- /**- * 主机侧填写的来源标记;缺省 = 手动入口(双击 / open-file)。只有 forge 转交- * 路径会传 agent-forge origin。绝不接受来自 agent 或 renderer 的值。- */- origin: GhostInstallOrigin = MANUAL_GHOST_INSTALL_ORIGIN,-): Promise<void> {- log.info('incoming .cindy file', { filePath, source, originKind: origin.kind });+export async function handleIncomingCindyFile(filePath: string, source: string): Promise<void> {+ log.info('incoming .cindy file', { filePath, source });try {if (!(await fs.promises.stat(filePath)).isFile()) return;} catch {return; // 路径不存在 / 不可读 → 静默忽略(与 open-folder 的容错口径一致)}- pendingCindyInstall = { filePath, origin };- // 广播只是"来取货"的通知,不携带任何事实:唯一真相是上面那个缓冲,- // renderer 一律经 ghosts:take-pending-install 取路径与来源。没有窗口时- // (冷启动 / macOS 关窗后应用仍在跑)广播丢掉也不影响正确性。+ pendingCindyInstall = filePath;+ // 已运行的窗口立即收到信号;冷启动时没有窗口,renderer 挂载后主动来取。BrowserWindow.getAllWindows().forEach((window) => {if (window.isDestroyed()) return;window.webContents.send('ghosts:install-requested');diff --git a/apps/desktop/src/main/cindy-brain/packagePermissionReview.ts b/apps/desktop/src/main/cindy-brain/packagePermissionReview.tsdeleted file mode 100644index 5c8c4bca5a..0000000000--- a/apps/desktop/src/main/cindy-brain/packagePermissionReview.ts+++ /dev/null@@ -1,141 +0,0 @@-import {- type GhostManifest,- type GhostSecretDecl,- type GhostPermissionDiff,-} from '../../shared/ghost.js';-import type { PluginMarketPackageReviewFacts } from '../../shared/pluginMarket.js';--/** 真实安装包需要用户复核时,交给 PluginMarketService 转成可恢复结果。 */-export class GhostPackagePermissionReviewRequiredError extends Error {- constructor(readonly review: PluginMarketPackageReviewFacts) {- super('The downloaded Plugin package requires permission review');- }-}--/**- * 下载后是否还要弹窗口级 Host 权限卡。- * 用户已经确认过的清单(reviewed)当作上限:真实包没有超出部分就不再弹;- * 没有这份上限时,手动首装仍审真实包,更新只在相对已装基线扩权时审。- */-export function marketPackageNeedsHostReview(input: {- mode: 'manual' | 'cap';- builtinOauthClientChanged: boolean;- /** 已审预览与真实包的随包手册摘要不一致。 */- manualSummaryChanged?: boolean;- /** null = 没有已装批准基线。 */- addedCount: number | null;- unreviewedCount: number;- /** null = 调用方没有把用户已确认的清单传来。 */- extrasVersusReviewedCount: number | null;-}): boolean {- if (input.builtinOauthClientChanged) return true;- if (input.manualSummaryChanged) return true;- if (input.extrasVersusReviewedCount !== null) {- return input.extrasVersusReviewedCount > 0;- }- if (input.mode === 'manual') {- return input.addedCount === null || input.addedCount > 0;- }- return input.unreviewedCount > 0;-}--/**- * 内置 OAuth clientId 是否相对用户已确认的清单或已装基线发生了变化。- * 权限投影不含 clientId,必须单独比;已装基线与预览清单都要比真实包。- */-export function marketPackageOauthIdentityChanged(- reviewed: GhostManifest | undefined,- installedBaseline: GhostManifest | null,- actual: GhostManifest,-): boolean {- // 已装基线空 clientId→默认值不算迁移(令牌仍有效)。已审预览则相反。- if (- installedBaseline &&- oauthIdentitiesChanged(installedBaseline, actual, { emptyDirectToConcreteCounts: false })- ) {- return true;- }- if (!reviewed) return false;- return oauthIdentitiesChanged(reviewed, actual, { emptyDirectToConcreteCounts: true });-}--/**- * Host 卡要展示触发复核的全部事实。没有已装基线、真实包相对已审清单多了权限、- * 或手册摘要变了时,回 null,让界面改走完整真实包清单,不要合成「权限无变化」。- */-export function marketPackageHostReviewDiff(input: {- permissionDiff: GhostPermissionDiff | null;- extrasVersusReviewedCount: number | null;- builtinOauthClientChanged: boolean;- manualSummaryChanged: boolean;-}): GhostPermissionDiff | null {- const extrasExist = (input.extrasVersusReviewedCount ?? 0) > 0;- if (input.permissionDiff === null || extrasExist || input.manualSummaryChanged) {- return null;- }- return {- ...input.permissionDiff,- builtinOauthClientChanged:- input.permissionDiff.builtinOauthClientChanged || input.builtinOauthClientChanged,- };-}--/**- * 已审预览与真实包的随包手册是否不一致。- * 页面确认只展示手册条数与条目身份;真实包改了这些事实就必须再审。- */-export function marketPackageManualSummaryChanged(- reviewed: GhostManifest | undefined,- actual: GhostManifest,-): boolean {- if (!reviewed) return false;- return manualSummaryKey(reviewed) !== manualSummaryKey(actual);-}--function manualSummaryKey(manifest: GhostManifest): string {- const items = (manifest.manual?.items ?? []).map((item) => ({- name: item.name,- dir: item.dir,- description: item.description,- }));- items.sort((left, right) => {- if (left.name !== right.name) return left.name < right.name ? -1 : 1;- if (left.dir !== right.dir) return left.dir < right.dir ? -1 : 1;- return 0;- });- return JSON.stringify(items);-}--function oauthIdentityKey(secret: GhostSecretDecl): string | null {- if (secret.source !== 'oauth' || !secret.oauth) return null;- if (secret.oauth.tokenBroker) return `broker:${secret.oauth.tokenBroker}`;- return `direct:${secret.oauth.clientId?.trim() || ''}`;-}--function oauthIdentitiesChanged(- previousManifest: GhostManifest,- actual: GhostManifest,- options: { emptyDirectToConcreteCounts: boolean },-): boolean {- if (previousManifest.id !== actual.id) return false;- const previousByKey = new Map(- (previousManifest.network?.secrets ?? []).map((secret) => [secret.key, secret]),- );- for (const current of actual.network?.secrets ?? []) {- const currentIdentity = oauthIdentityKey(current);- if (!currentIdentity) continue;- const previous = previousByKey.get(current.key);- if (!previous) continue;- const previousIdentity = oauthIdentityKey(previous);- if (!previousIdentity || previousIdentity === currentIdentity) continue;- if (- !options.emptyDirectToConcreteCounts &&- previousIdentity === 'direct:' &&- currentIdentity.startsWith('direct:')- ) {- continue;- }- return true;- }- return false;-}diff --git a/apps/desktop/src/main/cindy-brain/pickSlot.ts b/apps/desktop/src/main/cindy-brain/pickSlot.tsindex 6bead2e807..d57b37cecd 100644--- a/apps/desktop/src/main/cindy-brain/pickSlot.ts+++ b/apps/desktop/src/main/cindy-brain/pickSlot.ts@@ -75,8 +75,8 @@ export class GhostPickSlot {async handleRequest(ghostId: string, payload: unknown): Promise<GhostPipePickResult> {const ghost = this.deps.getGhost(ghostId);- if (!ghost?.enabled || !ghost.manifest.slots.includes('pick')) {- return fail('PERMISSION_DENIED', '插件未申请目录选择权限(pick 槽),或当前未启用');+ if (!ghost?.enabled || ghost.manifest.pick !== true) {+ return fail('PERMISSION_DENIED', '插件未申请目录选择权限(pick),或当前未启用');}if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {return fail('INVALID_REQUEST', 'pick-request 载荷必须是对象');@@ -92,7 +92,7 @@ export class GhostPickSlot {return fail('INVALID_REQUEST', 'deposit 必须是布尔值');}const wantDeposit = request.deposit === true;- const hasNode = ghost.manifest.slots.includes('node');+ const hasNode = ghost.manifest.node !== undefined;if (!hasNode && !wantDeposit) {return fail('INVALID_REQUEST',diff --git a/apps/desktop/src/main/cindy-brain/previewSlot.ts b/apps/desktop/src/main/cindy-brain/previewSlot.tsindex 201d6b5316..334ba79796 100644--- a/apps/desktop/src/main/cindy-brain/previewSlot.ts+++ b/apps/desktop/src/main/cindy-brain/previewSlot.ts@@ -71,8 +71,8 @@ export class GhostPreviewSlot {handleRequest(ghostId: string, payload: unknown): GhostPipePreviewResult {const ghost = this.deps.getGhost(ghostId);- if (!ghost?.enabled || !ghost.manifest.slots.includes('preview')) {- return fail('PERMISSION_DENIED', '插件未申请面板预览权限(preview 槽),或当前未启用');+ if (!ghost?.enabled || !ghost.manifest.preview) {+ return fail('PERMISSION_DENIED', '插件未申请面板预览权限(preview),或当前未启用');}if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {return fail('INVALID_REQUEST', 'preview-request 载荷必须是对象');diff --git a/apps/desktop/src/main/cindy-brain/runtime/__tests__/GhostRuntime.test.ts b/apps/desktop/src/main/cindy-brain/runtime/__tests__/GhostRuntime.test.tsindex c72faaa2df..3ce7dd08b4 100644--- a/apps/desktop/src/main/cindy-brain/runtime/__tests__/GhostRuntime.test.ts+++ b/apps/desktop/src/main/cindy-brain/runtime/__tests__/GhostRuntime.test.ts@@ -32,7 +32,6 @@ function chipGhost(id = 'demo'): InstalledGhost {version: '1.0.0',kind: 'chip',entry: 'main.js',- slots: ['cindy'],},dir: `/fake/brain/${id}`,enabled: true,diff --git a/apps/desktop/src/main/cindy-brain/runtime/ghostSecretsEndpoint.ts b/apps/desktop/src/main/cindy-brain/runtime/ghostSecretsEndpoint.tsindex 4509021fe3..64f8befda1 100644--- a/apps/desktop/src/main/cindy-brain/runtime/ghostSecretsEndpoint.ts+++ b/apps/desktop/src/main/cindy-brain/runtime/ghostSecretsEndpoint.ts@@ -12,8 +12,8 @@* 是哪个 key——值太短不产指纹时缺省;老键由保险库真身首查懒回填,见* readGhostSecretTailFromIo);* - login-email 派生:{ key, saved, identity? }(identity = 当前登录邮箱,- * 供设置页只读展示"用的是哪个身份"。回给意识不算新增泄露面:装入确认- * 框已披露"将使用你的登录邮箱",且该凭证每次代发都注给它自己的服务端。+ * 供设置页只读展示"用的是哪个身份"。回给意识不算新增泄露面:插件详情+ * 已披露"将使用你的登录邮箱",且该凭证每次代发都注给它自己的服务端。* 未登录/登录态缺邮箱 → saved:false 无 identity,页面照"请重新登录"画);* - gh-cli 优先 + PAT 备用:{ key, saved, tail?, hostSource:'gh-cli',* hostAvailable }。saved/tail 只描述保险库里的备用 PAT;hostAvailablediff --git a/apps/desktop/src/main/cindy-brain/scheduleSlot.ts b/apps/desktop/src/main/cindy-brain/scheduleSlot.tsindex 3e9626e07b..0d96e6399c 100644--- a/apps/desktop/src/main/cindy-brain/scheduleSlot.ts+++ b/apps/desktop/src/main/cindy-brain/scheduleSlot.ts@@ -142,7 +142,6 @@ export class GhostScheduleSlot {const ghost = this.deps.getGhost(ghostId);if (!ghost?.enabled ||- !ghost.manifest.slots.includes('agent') ||ghost.manifest.agent?.schedule !== true) {return fail(diff --git a/apps/desktop/src/main/cindy-brain/skillSlot.ts b/apps/desktop/src/main/cindy-brain/skillSlot.tsindex 3bf1c73330..00f6593212 100644--- a/apps/desktop/src/main/cindy-brain/skillSlot.ts+++ b/apps/desktop/src/main/cindy-brain/skillSlot.ts@@ -78,10 +78,10 @@ export function checkSkillMdConsistency(content: string, item: GhostSkillItem):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 读到的)`;+ return `SKILL.md frontmatter name ${JSON.stringify(fmName)} 与清单声明 ${JSON.stringify(item.name)} 不一致(插件详情展示的必须就是 Agent 读到的)`;}if (fmDescription !== item.description) {- return 'SKILL.md frontmatter description 与清单声明不一致(装入确认框展示的必须就是 Agent 读到的)';+ return 'SKILL.md frontmatter description 与清单声明不一致(插件详情展示的必须就是 Agent 读到的)';}return null;}@@ -350,7 +350,6 @@ export async function reconcileGhostSkillLinks(g.enabled &&g.approval.state === 'approved' &&Boolean(g.approvedSkillRoot) &&- g.manifest.slots.includes('skill') &&g.manifest.skill,).sort((a, b) => a.manifest.id.localeCompare(b.manifest.id));diff --git a/apps/desktop/src/main/cindy-brain/subscriptionGateway.ts b/apps/desktop/src/main/cindy-brain/subscriptionGateway.tsindex aa0071bd83..afcb2c58e6 100644--- a/apps/desktop/src/main/cindy-brain/subscriptionGateway.ts+++ b/apps/desktop/src/main/cindy-brain/subscriptionGateway.ts@@ -196,7 +196,6 @@ export class GhostSubscriptionGateway {): void {for (const ghost of this.deps.listGhosts()) {if (!ghost.enabled) continue;- if (!ghost.manifest.slots.includes('subscribe')) continue;if (!ghost.manifest.subscribe?.topics?.includes(topic)) continue;this.dispatchTo(ghost, topic, name, data);}diff --git a/apps/desktop/src/main/cindy-brain/workspaceSlot.ts b/apps/desktop/src/main/cindy-brain/workspaceSlot.tsindex f57f851826..87def065a9 100644--- a/apps/desktop/src/main/cindy-brain/workspaceSlot.ts+++ b/apps/desktop/src/main/cindy-brain/workspaceSlot.ts@@ -114,8 +114,8 @@ export class GhostWorkspaceSlot {async handleRequest(ghostId: string, payload: unknown): Promise<GhostPipeWorkspaceResult> {const ghost = this.deps.getGhost(ghostId);- if (!ghost?.enabled || !ghost.manifest.slots.includes('workspace')) {- return fail('PERMISSION_DENIED', '插件未申请工作区会话权限(workspace 槽),或当前未启用');+ if (!ghost?.enabled || ghost.manifest.workspace !== true) {+ return fail('PERMISSION_DENIED', '插件未申请工作区会话权限(workspace),或当前未启用');}if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {return fail('INVALID_REQUEST', 'workspace-request 载荷必须是对象');diff --git a/apps/desktop/src/main/ghost-panel-window/__tests__/controller.test.ts b/apps/desktop/src/main/ghost-panel-window/__tests__/controller.test.tsindex 74fccc6c3d..7d7de9f92d 100644--- a/apps/desktop/src/main/ghost-panel-window/__tests__/controller.test.ts+++ b/apps/desktop/src/main/ghost-panel-window/__tests__/controller.test.ts@@ -97,7 +97,6 @@ function ghost(id: string, opts: { enabled?: boolean; position?: 'left' | 'tab'version: '1.0.0',kind: 'chip',entry: 'main.js',- slots: ['panel'],panel: {html: 'panel.html',...(opts.position !== undefined ? { position: opts.position } : {}),diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.tsindex 43be0247ac..bdb294e0f3 100644--- a/apps/desktop/src/main/localDb/ipc/sessions.ts+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts@@ -698,30 +698,6 @@ export async function getSessionFsSnapshot(id: string): Promise<{}}-/**- * 按 session id 查任务标题(装入确认框的 Agent 来源横幅用:告诉用户"这次装入是- * 哪个任务里的 Agent 发起的")。纯展示用途,失败 swallow 返 null —— 拿不到标题- * 只是横幅少一行,不阻断装入编排。- */-export async function getSessionTitle(id: string): Promise<string | null> {- try {- const db = getDbClient().drizzle;- const [row] = await db- .select({ title: sessions.title })- .from(sessions)- .where(eq(sessions.id, id))- .limit(1);- const title = row?.title?.trim();- return title ? title : null;- } catch (err) {- log.warn('getSessionTitle failed', {- sessionId: id,- err: err instanceof Error ? err.message : String(err),- });- return null;- }-}-/*** 内部 API:标记用户显式发送时间。*diff --git a/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts b/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.tsindex fa8ad576f2..ce8fa7c1c6 100644--- a/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts+++ b/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts@@ -100,7 +100,7 @@ export const HELP_KNOWLEDGE: HelpKnowledgeDoc[] = [title: "Plugins (extending what the agents can do)",summary: "What plugins are, how to browse / install / enable / disable them, per-working-directory control, the permission model, and invoking one with a $command.",tab: "ghosts",- content: "Plugins (internally \"意识\" / Ghost) extend what the agents can do — they add AI-callable tools, dockable UI panels, and \"ask Cindy to make it\" media generation. Each plugin is a self-contained `.cindy` capability pack that runs in its own isolated sandbox.\n\n**The Plugins page:**\n\n- Open it from the **Plugins** entry in the left sidebar.\n- Browse by origin: **all / built-in / team-shared / external**. The team-shared (enterprise) group only shows if your account belongs to an organization.\n- Each plugin has a detail page — that's where you enable it, connect an account / enter an API key, and read what it can do.\n\n**Built-in plugins that ship with the app:**\n\n- **Cindy Art** (`$cindy-art`) — generate and edit images and short videos.\n- **Cindy Web Search** (`$cindy-web-search`) — public web search (add your own Brave or Tavily key on its detail page).\n- **Cindy Mermaid** (`$cindy-mermaid`) — build / repair Mermaid diagrams.\n- **Cindy GitHub** (`$cindy-github`) / **Cindy GitLab** (`$cindy-gitlab`) — read / write issues, PRs / MRs, reviews, CI, releases.\n- **Filo Google** (`$filo-google`) — Gmail / Calendar / Drive / Sheets.\n\n**Enabling and disabling:**\n\n- **Enable / disable (globally)** from the plugin's detail page. Disabling puts its tools and panel to sleep but keeps the plugin installed — its layout slot is remembered and restored when you re-enable it.\n- **Disable for one working directory only** — a plugin can be turned off just for a specific project. In that project's sessions it behaves as if it isn't installed (its tools and `$command` are unavailable there); everywhere else it stays on.\n\n**Installing:**\n\n- Install from the marketplace, or add a `.cindy` file manually (drag it in / pick it from disk).\n- Every install or update shows a **permission confirmation dialog** that lists exactly what the plugin can access (network domains, credentials it needs, tools, `$command`, panel). Nothing runs until you accept — and freshly installed plugins start **disabled** until you turn them on.\n\n**Using a plugin with `$command`:**\n\n- Type its command at the **start** of a message — e.g. `$cindy-art a poster for…`. Only enabled plugins that declare that command match.\n- You don't have to use `$command`: the agents can also pick an enabled plugin's tools on their own when a task calls for it.\n\n**The permission / sandbox model (why plugins are safe):**\n\n- A plugin's sandbox has **no filesystem, no network, and no direct system access** by default. It can only ask the host to do things it declared up front in its manifest, and the host enforces each one.\n- **Network** access is limited to a domain allowlist the plugin declares; the host proxies every request. Credentials never enter the sandbox — the host injects them only into the declared requests.\n- Because of this, a plugin **can't see your files** on its own. A file reaches a plugin only when you or the agent explicitly hand one over (an image attachment, or a directory the host passes through after an ownership check).\n\n**Configuring a plugin's account / API key:**\n\n- Do it on the plugin's **detail page**. Plugins that use a key (web-search, GitHub/GitLab tokens) have a field there; the value goes straight into the host's encrypted store and can't be read back.\n- Plugins that use OAuth (for example Filo Google) show a **Connect account** button instead.\n\n**Notes:**\n\n- Enabling or disabling a plugin takes effect on the **next** agent query, not retroactively in the current turn.\n- Skills (`/` slash commands) and Plugins (`$` commands) are two tabs of the same management surface — see the Skills topic for skills.",+ content: "Plugins (internally \"意识\" / Ghost) extend what the agents can do — they add AI-callable tools, dockable UI panels, and \"ask Cindy to make it\" media generation. Each plugin is a self-contained `.cindy` capability pack that runs in its own isolated sandbox.\n\n**The Plugins page:**\n\n- Open it from the **Plugins** entry in the left sidebar.\n- Browse by origin: **all / built-in / team-shared / external**. The team-shared (enterprise) group only shows if your account belongs to an organization.\n- Each plugin has a detail page — that's where you enable it, connect an account / enter an API key, and read what it can do.\n\n**Built-in plugins that ship with the app:**\n\n- **Cindy Art** (`$cindy-art`) — generate and edit images and short videos.\n- **Cindy Web Search** (`$cindy-web-search`) — public web search (add your own Brave or Tavily key on its detail page).\n- **Cindy Mermaid** (`$cindy-mermaid`) — build / repair Mermaid diagrams.\n- **Cindy GitHub** (`$cindy-github`) / **Cindy GitLab** (`$cindy-gitlab`) — read / write issues, PRs / MRs, reviews, CI, releases.\n- **Filo Google** (`$filo-google`) — Gmail / Calendar / Drive / Sheets.\n\n**Enabling and disabling:**\n\n- **Enable / disable (globally)** from the plugin's detail page. Disabling puts its tools and panel to sleep but keeps the plugin installed — its layout position is remembered and restored when you re-enable it.\n- **Disable for one working directory only** — a plugin can be turned off just for a specific project. In that project's sessions it behaves as if it isn't installed (its tools and `$command` are unavailable there); everywhere else it stays on.\n\n**Installing:**\n\n- Install from the marketplace, or add a `.cindy` file manually (drag it in / pick it from disk).\n- Choosing Install, dragging a package, or picking one from disk installs and enables the selected plugin directly. Installation does not add a permission or version-confirmation step; review its declared capabilities on the plugin detail page.\n- The server selects the release appropriate for this Cindy version before marketplace delivery. Desktop does not apply a second `minCindyVersion` gate; custom marketplaces and local `.cindy` packages follow the same install policy.\n- Updates from stable marketplace sources are applied automatically when the plugin is idle. Failed attempts retry later; you can still click Update to retry immediately.\n\n**Using a plugin with `$command`:**\n\n- Type its command at the **start** of a message — e.g. `$cindy-art a poster for…`. Only enabled plugins that declare that command match.\n- You don't have to use `$command`: the agents can also pick an enabled plugin's tools on their own when a task calls for it.\n\n**The permission / sandbox model (why plugins are safe):**\n\n- A plugin's sandbox has **no direct filesystem, network, or system access**. The host mediates every operation and enforces its actual execution context.\n- Autonomous/background plugin behavior must stay within the capabilities and scopes declared directly in its manifest. Whether an in-flight plugin tool runs is decided by the existing Agent authorization flow; network and working-directory operations bind to that call, while bundled code and CLIs continue to use the existing Node worker. Plugin authors do not need a client change or a manifest Slot to pre-register a specific command, host, or path.\n- **Autonomous network** access is limited to a domain allowlist the plugin declares; the host proxies every request. Credentials never enter the sandbox — the host injects them only into declared requests whose target matches that declaration.\n- Because of this, a plugin **can't see your files** on its own. A file reaches a plugin only when you or the agent explicitly hand one over (an image attachment, or a directory the host passes through after an ownership check).\n\n**Configuring a plugin's account / API key:**\n\n- Do it on the plugin's **detail page**. Plugins that use a key (web-search, GitHub/GitLab tokens) have a field there; the value goes straight into the host's encrypted store and can't be read back.\n- Plugins that use OAuth (for example Filo Google) show a **Connect account** button instead.\n\n**Notes:**\n\n- Enabling or disabling a plugin takes effect on the **next** agent query, not retroactively in the current turn.\n- Skills (`/` slash commands) and Plugins (`$` commands) are two tabs of the same management surface — see the Skills topic for skills.",},{id: "providers",diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.tsindex 8d41eef66d..d9ba2c3671 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts@@ -29,9 +29,11 @@ const outsideDir = path.join(tmpUserData, 'outside');const logWarnMock = vi.fn();const logInfoMock = vi.fn();const grantAttachmentsMock = vi.fn();-const { packGhostDirMock } = vi.hoisted(() => ({ packGhostDirMock: vi.fn() }));-const { handleIncomingCindyFileMock, completeForgePackStagingMock } = vi.hoisted(() => ({- handleIncomingCindyFileMock: vi.fn(async () => undefined),+const { packGhostDirMock, forgeInstallPackageMock } = vi.hoisted(() => ({+ packGhostDirMock: vi.fn(),+ forgeInstallPackageMock: vi.fn(),+}));+const { completeForgePackStagingMock } = vi.hoisted(() => ({completeForgePackStagingMock: vi.fn(() => ({ticket: 'publish-token-1',installPath: '/host/staging/demo.cindy',@@ -169,6 +171,7 @@ vi.mock('../../cindy-brain/index.js', () => ({listMock().find((ghost: any) => ghost.manifest?.id === id) ?? null,captureGhostMutationOwnerForMcp: captureMutationOwnerMock,acquireGhostMutationLeaseForMcp: acquireMutationLeaseMock,+ installOrUpdateLocalGhostPackageFromForge: forgeInstallPackageMock,getGhostPipeDispatcher: () => ({ callGhostTool: dispatchMock }),getGhostCardService: () => ({ registerCall: () => {}, finalizeCall: () => null }),getGhostSetupAssessment: setupAssessmentMock,@@ -213,12 +216,8 @@ vi.mock('../../cindy-brain/forgePackStaging.js', () => ({invalidateForgePackTicket: vi.fn(),releaseForgePackStaging: releaseForgePackStagingMock,}));-vi.mock('../../cindy-brain/openFileInstall.js', () => ({- handleIncomingCindyFile: handleIncomingCindyFileMock,-}));vi.mock('../../localDb/ipc/sessions.js', () => ({getSessionFsSnapshot: sessionSnapshotMock,- getSessionTitle: vi.fn(async () => 'Test session'),}));vi.mock('../../plugin-publisher/host.js', () => ({currentPublisherIdentity: currentPublisherIdentityMock,@@ -247,7 +246,7 @@ import type { LiziMcpSessionContext } from '@cindy/mcps';function chipGhost(id: string,- slots: string[] = ['tool'],+ capabilities: string[] = ['tool'],extra: Record<string, unknown> = {},): unknown {return {@@ -256,8 +255,9 @@ function chipGhost(id,name: `Ghost ${id}`,kind: 'chip',- slots,tools: [{ name: 'run', description: 'd' }],+ ...(capabilities.includes('panel') ? { panel: { html: 'panel.html' } } : {}),+ ...(capabilities.includes('session-context') ? { sessionContext: true } : {}),...extra,},};@@ -410,7 +410,14 @@ beforeEach(() => {errorCode: 'MANIFEST_INVALID',message: 'stop after gate assertion',});- handleIncomingCindyFileMock.mockClear();+ forgeInstallPackageMock.mockReset();+ forgeInstallPackageMock.mockResolvedValue({+ action: 'installed',+ ghost: {+ enabled: true,+ manifest: { id: 'demo', name: 'Demo', version: '1.0.0' },+ },+ });completeForgePackStagingMock.mockClear();publishTicketConsumeMock.mockReset();publishTicketConsumeMock.mockReturnValue({@@ -423,7 +430,12 @@ beforeEach(() => {});releaseForgePackStagingMock.mockClear();startPluginPublishMock.mockClear();- currentPublisherIdentityMock.mockClear();+ currentPublisherIdentityMock.mockReset();+ currentPublisherIdentityMock.mockReturnValue({+ membershipId: 'member-1',+ orgSlug: 'acme',+ orgName: 'Acme',+ });appSessionBoundaryPendingMock.mockReset();appSessionBoundaryPendingMock.mockReturnValue(false);clearAllPrefs();@@ -447,7 +459,7 @@ describe('Forge session workdir gate', () => {});});- it('keeps default intent on the install-confirm path without exposing a publish token', async () => {+ it('keeps default intent as pure packaging without exposing a publish token', async () => {packGhostDirMock.mockResolvedValueOnce({ok: true,buf: Buffer.from('packed'),@@ -455,18 +467,44 @@ describe('Forge session workdir gate', () => {manifest: { id: 'demo', name: 'Demo', version: '1.0.0' },});const result = await makeDeps().forgePack({ dir: path.join(WORKDIR, 'plugin-src') });- expect(result).toMatchObject({ ok: true, cindyPath: 'demo-1.0.0.cindy' });- if (!result.ok) throw new Error('default install pack unexpectedly failed');+ expect(result).toMatchObject({+ ok: true,+ cindyPath: path.join(WORKDIR, 'plugin-src', 'demo-1.0.0.cindy'),+ });+ if (!result.ok) throw new Error('default pack unexpectedly failed');expect(result).not.toHaveProperty('publishToken');- expect(result.note).toContain("若接下来要发布到组织市场,请用 intent='publish' 重新打包");- expect(handleIncomingCindyFileMock).toHaveBeenCalledWith(- '/host/staging/demo.cindy',- 'ghost-forge',- expect.objectContaining({ kind: 'agent-forge' }),- );+ expect(result.note).toContain('本工具不会安装或更新插件');+ expect(completeForgePackStagingMock).not.toHaveBeenCalled();});- it('does not suggest organization publishing to a personal account after default install pack', async () => {+ it('installs only through the explicit Forge install method and binds the packed bytes', async () => {+ const bytes = Buffer.from('packed');+ const cindyPath = path.join(WORKDIR, 'plugin-src', 'demo-1.0.0.cindy');+ packGhostDirMock.mockResolvedValueOnce({+ ok: true,+ buf: bytes,+ cindyPath,+ manifest: { id: 'demo', name: 'Demo', version: '1.0.0' },+ });++ const result = await makeDeps().forgeInstall({+ dir: path.join(WORKDIR, 'plugin-src'),+ });++ expect(forgeInstallPackageMock).toHaveBeenCalledWith(cindyPath, {+ ghostId: 'demo',+ packageSha256: createHash('sha256').update(bytes).digest('hex'),+ });+ expect(result).toMatchObject({+ ok: true,+ action: 'installed',+ id: 'demo',+ enabled: true,+ });+ expect(completeForgePackStagingMock).not.toHaveBeenCalled();+ });++ it('does not suggest organization publishing to a personal account after default pack', async () => {currentPublisherIdentityMock.mockReturnValueOnce(null);packGhostDirMock.mockResolvedValueOnce({ok: true,@@ -479,18 +517,13 @@ describe('Forge session workdir gate', () => {// Excludes showing an unusable publish next step to personal accounts.expect(result.ok).toBe(true);- if (!result.ok) throw new Error('personal install pack unexpectedly failed');+ if (!result.ok) throw new Error('personal pack unexpectedly failed');expect(result.note).not.toContain("intent='publish'");- // Excludes changing the default intent while adding the conditional note.+ // Default packaging remains independent from publisher identity.expect(result).not.toHaveProperty('publishToken');- expect(handleIncomingCindyFileMock).toHaveBeenCalledWith(- '/host/staging/demo.cindy',- 'ghost-forge',- expect.objectContaining({ kind: 'agent-forge' }),- );});- it('returns the one-shot token for publish intent without opening install confirmation', async () => {+ it('returns the one-shot token for publish intent', async () => {packGhostDirMock.mockResolvedValueOnce({ok: true,buf: Buffer.from('packed'),@@ -502,7 +535,6 @@ describe('Forge session workdir gate', () => {intent: 'publish',});expect(result).toMatchObject({ ok: true, publishToken: 'publish-token-1' });- expect(handleIncomingCindyFileMock).not.toHaveBeenCalled();});it('consumes the publish token and binds publisher input to ticket id, SHA and cleanup', async () => {diff --git a/apps/desktop/src/main/mcp-integrations/ghost.ts b/apps/desktop/src/main/mcp-integrations/ghost.tsindex 5f8332a2d4..c0cf8a7fbb 100644--- a/apps/desktop/src/main/mcp-integrations/ghost.ts+++ b/apps/desktop/src/main/mcp-integrations/ghost.ts@@ -10,9 +10,9 @@* 装/卸/唤醒/沉睡对新老会话"下一次查询即生效";* - callGhostTool:透传给管子派发器(pipeDispatcher),资格审/按需拉起/* 配对超时/崩溃收卷全在那边,错误码两侧同构直接原样交回;- * - forgeGuide / forgeScaffold / forgePack:意识锻造(agent 帮用户做意识)——- * 手册、骨架与打包真身在 cindy-brain/forge.ts。缺省打包经双击转交- * 通道弹装入确认框;publish intent 改签一次性发布票据。+ * - forgeGuide / forgeScaffold / forgePack / forgeInstall:意识锻造(agent 帮用户做意识)——+ * 手册、骨架与打包真身在 cindy-brain/forge.ts;pack 始终只产出文件,只有显式+ * forgeInstall 才复用本地包事务安装/更新,publish intent 改签一次性发布票据。** cindy-tools 是意识系统工具集,包内零 Electron* 依赖,全部能力经本文件注入(设计规范规则 2)。@@ -24,6 +24,7 @@ import { createHash, randomUUID } from 'node:crypto';import { buildGhostRosterPrompt } from 'cindy-tools';import type {+ CindyForgeInstallResult,CindyForgePackResult,CindyForgePublishResult,CindyForgePublishStatusResult,@@ -54,7 +55,7 @@ import {} from '../cindy-brain/ghostGrantConfirmBridge.js';import { classifyLocalAttachmentPath } from '../cindy-brain/ghostLocalPathGrant.js';import { toolNotFoundMessage } from '../cindy-brain/pipeDispatcher.js';-import { getSessionFsSnapshot, getSessionTitle } from '../localDb/ipc/sessions.js';+import { getSessionFsSnapshot } from '../localDb/ipc/sessions.js';import { getActiveAppSession, isAppSessionBoundaryPending } from '../appSessionState.js';import {deriveGhostSessionContext,@@ -72,6 +73,7 @@ import {ghostForgeForbiddenRootDirs,captureGhostMutationOwnerForMcp,acquireGhostMutationLeaseForMcp,+ installOrUpdateLocalGhostPackageFromForge,isGhostAvailableForActiveSession,} from '../cindy-brain/index.js';import { writeForgeScaffoldWithStableParent } from '../cindy-brain/forgeScaffoldCapability.js';@@ -83,7 +85,6 @@ import { FORGE_GUIDE, packGhostDir, scaffoldGhostDir } from '../cindy-brain/forgimport {completeForgePackStaging,getForgePackStagingController,- invalidateForgePackTicket,releaseForgePackStaging,} from '../cindy-brain/forgePackStaging.js';import { consumeForgePackForPublish } from '../cindy-brain/forgePackPublishConsume.js';@@ -93,8 +94,6 @@ import {startPluginPublish,} from '../plugin-publisher/host.js';import { workdirWriteVerdict } from '../cindy-brain/fsSlot.js';-import { handleIncomingCindyFile } from '../cindy-brain/openFileInstall.js';-import type { GhostInstallOrigin } from '../../shared/ghostInstallOrigin.js';import * as blobStore from '../cindy-media/blobStore.js';import { commitMessageMediaRefs } from '../cindy-media/chatAttachments.js';import { callCindyMedia } from '../cindy-media/invocationService.js';@@ -106,6 +105,7 @@ import { createForgeIconConverter } from './forgeIconConversion.js';import { forkForgeIconConversionHost } from './forgeIconConversionHost.js';import { t } from '../i18n.js';import { createLogger } from '../logger.js';+import { isIpcError } from '../../shared/ipc-errors.js';const log = createLogger('mcp/cindy');const MAX_FORGE_ICON_SOURCE_BYTES = 25 * 1024 * 1024;@@ -116,6 +116,54 @@ const convertForgeIconToPng = createForgeIconConverter({fork: forkForgeIconConversionHost,});+/** pack 与显式 install 共用同一套可选 AI 图标叠加,避免二次打包丢失图标。 */+async function packForgeSource(+ dir: string,+ sessionWorkdir: string,+ iconSource?: string,+) {+ let iconPng: Buffer | undefined;+ let iconNote = '';+ if (iconSource !== undefined) {+ try {+ const resolved = blobStore.resolveSafe(iconSource);+ if (!resolved.mimeType.startsWith('image/')) {+ throw new Error('icon_source 不是图片');+ }+ const stat = await fs.promises.stat(resolved.absPath);+ if (!stat.isFile() || stat.size <= 0 || stat.size > MAX_FORGE_ICON_SOURCE_BYTES) {+ throw new Error(`icon_source 体积必须在 1–${MAX_FORGE_ICON_SOURCE_BYTES} 字节之间`);+ }+ iconPng = await convertForgeIconToPng(resolved.absPath);+ iconNote = 'AI 图标已嵌入安装包。';+ } catch (err) {+ iconNote = 'AI 图标处理失败,已保留默认图标。';+ log.warn('ghost forge icon fallback', {+ dir,+ error: err instanceof Error ? err.message : String(err),+ });+ }+ }+ const packOptions = {+ sessionWorkdir,+ forbiddenRootDirs: ghostForgeForbiddenRootDirs(),+ };+ let packed = await packGhostDir(dir, iconPng ? { ...packOptions, iconPng } : packOptions);+ // icon overlay 的任何失败都不是打包门槛:用原源码再打一次。若原源码+ // 本身也不合法,则返回原本就会出现的结构化错误。+ if (!packed.ok && iconPng) {+ const fallbackPacked = await packGhostDir(dir, packOptions);+ if (fallbackPacked.ok) {+ packed = fallbackPacked;+ iconNote = 'AI 图标处理失败,已保留默认图标。';+ } else {+ return { ok: false as const, result: fallbackPacked };+ }+ }+ if (!packed.ok) return { ok: false as const, result: packed };+ return { ok: true as const, packed, iconNote };+}+/* ────────────────────────────────────────────────────────────────────────* workdir 外过户确认:* - 过户对象在会话 workdir 内 → 自动放行(与目录过户同信任等级);@@ -1590,15 +1638,15 @@ export function getCindyGhostsMcpDeps(message: t('newChat.pluginSetup.assessmentReadFailed'),};}- // Session-context slot: use the revalidated manifest to decide injection.+ // Session-context capability: use the revalidated manifest to decide injection.// Re-read manifest after the async buildGhostSessionContext to guard against- // a same-ID plugin replacement removing the slot during the await.- if (preDispatch.manifest.slots?.includes('session-context')) {+ // a same-ID plugin replacement removing the declaration during the await.+ if (preDispatch.manifest.sessionContext === true) {const ctx = await buildGhostSessionContext(sessionIdForConfirm, sessionWorkdir);const postCtxManifest = getGhostManager().list().find((g) => g.manifest.id === ghostId)?.manifest;- if (postCtxManifest?.slots?.includes('session-context')) {+ if (postCtxManifest?.sessionContext === true) {mergedArgs = { ...mergedArgs, session_context: ctx };}}@@ -1721,95 +1769,33 @@ export function getCindyGhostsMcpDeps(return result;});},- async forgePack({ dir, iconSource, intent = 'install' }): Promise<CindyForgePackResult> {+ async forgePack({ dir, iconSource, intent }): Promise<CindyForgePackResult> {return withForgeOwnerLease(async () => {const gate = await getForgeSessionFsGate(resolveSessionContext());if (!gate.ok) return gate;- let iconPng: Buffer | undefined;- let iconNote = '';- if (iconSource !== undefined) {+ const attempt = await packForgeSource(dir, gate.workingDir, iconSource);+ if (!attempt.ok) return attempt.result;+ const { packed, iconNote } = attempt;+ if (intent === 'publish') {+ const alreadyInstalled = getGhostManager()+ .list()+ .some((ghost) => ghost.manifest.id === packed.manifest.id);+ let staged;try {- const resolved = blobStore.resolveSafe(iconSource);- if (!resolved.mimeType.startsWith('image/')) {- throw new Error('icon_source 不是图片');- }- const stat = await fs.promises.stat(resolved.absPath);- if (!stat.isFile() || stat.size <= 0 || stat.size > MAX_FORGE_ICON_SOURCE_BYTES) {- throw new Error(`icon_source 体积必须在 1–${MAX_FORGE_ICON_SOURCE_BYTES} 字节之间`);- }- iconPng = await convertForgeIconToPng(resolved.absPath);- iconNote = 'AI 图标已嵌入安装包。';- } catch (err) {- iconNote = 'AI 图标处理失败,已保留默认图标并继续打包。';- log.warn('ghost forge icon fallback', {- dir,- error: err instanceof Error ? err.message : String(err),+ staged = completeForgePackStaging({+ buf: packed.buf,+ manifestId: packed.manifest.id,+ owner: captureGhostMutationOwnerForMcp(),+ operationKind: alreadyInstalled ? 'update' : 'install',+ authorCindyPath: packed.cindyPath,});+ } catch (err) {+ return {+ ok: false,+ errorCode: 'INTERNAL',+ message: err instanceof Error ? err.message : String(err),+ };}- }-- const packOptions = {- sessionWorkdir: gate.workingDir,- forbiddenRootDirs: ghostForgeForbiddenRootDirs(),- };- let packed = await packGhostDir(dir, iconPng ? { ...packOptions, iconPng } : packOptions);- // icon overlay 的任何失败都不是打包门槛:用原源码再打一次。若原源码- // 本身也不合法,则返回原本就会出现的结构化错误。- if (!packed.ok && iconPng) {- const fallbackPacked = await packGhostDir(dir, packOptions);- if (fallbackPacked.ok) {- packed = fallbackPacked;- iconNote = 'AI 图标处理失败,已保留默认图标并继续打包。';- } else {- return fallbackPacked;- }- }- if (!packed.ok) return packed;- // Agent 来源标记:这次装入是 Agent 调 ghost_forge_pack 发起的,不是用户- // 亲手点的。标题与源码相对路径都由主机侧算(agent 改不了),供确认框如实- // 展示"哪个任务里的 Agent 发起 + 打包了工作目录里的哪个源码目录"。- // 相对路径:forge 已强制源码在会话工作目录内,故 path.relative 可靠;- // 若源码目录恰是工作目录本身(relative='')回落目录名,不给空串。- const forgeSessionId = resolveSessionContext()?.sessionId;- const sessionTitle = forgeSessionId- ? (await getSessionTitle(forgeSessionId)) ?? undefined- : undefined;- const relFromWorkdir = path.relative(gate.workingDir, dir);- const sourceRelPath =- relFromWorkdir && !relFromWorkdir.startsWith('..')- ? relFromWorkdir- : path.basename(dir);- const origin: GhostInstallOrigin = {- kind: 'agent-forge',- ...(sessionTitle ? { sessionTitle } : {}),- ...(sourceRelPath ? { sourceRelPath } : {}),- };- const owner = captureGhostMutationOwnerForMcp();- const alreadyInstalled = getGhostManager()- .list()- .some((ghost) => ghost.manifest.id === packed.manifest.id);- let staged;- try {- // 安装链路只认这份内存字节直写的 staging。workdir 里的 .cindy 只是- // 作者副本;agent 换掉它不能改确认框将要检查的包。- // operationKind 只是打包时点的提示/审计,不是不可变拒绝条件:- // 打包到消费之间同 id 可能被另一入口装上或卸掉,真实分类在消费- // 入口持锁后重做,允许与票里的值不同。- staged = completeForgePackStaging({- buf: packed.buf,- manifestId: packed.manifest.id,- owner,- operationKind: alreadyInstalled ? 'update' : 'install',- authorCindyPath: packed.cindyPath,- });- } catch (err) {- return {- ok: false,- errorCode: 'INTERNAL',- message: err instanceof Error ? err.message : String(err),- };- }- if (intent === 'publish') {log.info('ghost forge packed for publish', { dir, id: packed.manifest.id });return {ok: true,@@ -1821,36 +1807,57 @@ export function getCindyGhostsMcpDeps(note: `${iconNote}已打包为待发布产物。仅企业组织成员可用 ghost_forge_publish 提交;个人账号不可用。`,};}+ log.info('ghost forge packed', { dir, cindyPath: packed.cindyPath, id: packed.manifest.id });+ return {+ ok: true,+ cindyPath: packed.cindyPath,+ id: packed.manifest.id,+ name: packed.manifest.name,+ version: packed.manifest.version,+ note: `${iconNote}已完成校验和打包;本工具不会安装或更新插件。`,+ };+ });+ },+ async forgeInstall({ dir, iconSource }): Promise<CindyForgeInstallResult> {+ return withForgeOwnerLease(async () => {+ const gate = await getForgeSessionFsGate(resolveSessionContext());+ if (!gate.ok) return gate;+ const attempt = await packForgeSource(dir, gate.workingDir, iconSource);+ if (!attempt.ok) return attempt.result;+ const { packed, iconNote } = attempt;try {- // 与双击 .cindy 同一条转交通道:renderer 弹标准确认框(同 id 已装则- // 自动转"更新 vX → vY"),用户点头才真装。lease 持到转交完成。带上 agent- // 来源,确认框据此展示来源横幅 + 分级加重(高危需手输 id 确认)。- // 交给这条通道的必须是 staging,不能是 workdir 产物。- await handleIncomingCindyFile(staged.installPath, 'ghost-forge', origin);+ const installed = await installOrUpdateLocalGhostPackageFromForge(+ packed.cindyPath,+ {+ ghostId: packed.manifest.id,+ packageSha256: createHash('sha256').update(packed.buf).digest('hex'),+ },+ );+ log.info('ghost forge install completed', {+ dir,+ id: installed.ghost.manifest.id,+ version: installed.ghost.manifest.version,+ action: installed.action,+ });+ return {+ ok: true,+ action: installed.action,+ id: installed.ghost.manifest.id,+ name: installed.ghost.manifest.name,+ version: installed.ghost.manifest.version,+ enabled: installed.ghost.enabled,+ note:+ installed.action === 'installed'+ ? `${iconNote}插件已完成校验、打包和安装,并已启用。`+ : `${iconNote}插件已完成校验、打包和原位更新;原有启用状态、配置与数据保持不变。`,+ };} catch (err) {- invalidateForgePackTicket(staged.ticket);return {ok: false,- errorCode: 'INTERNAL',+ errorCode: isIpcError(err) ? err.code : 'INTERNAL',message: err instanceof Error ? err.message : String(err),};}- log.info('ghost forge packed', { dir, id: packed.manifest.id });- const publishHint = currentPublisherIdentity()- ? "若接下来要发布到组织市场,请用 intent='publish' 重新打包。"- : '';- return {- ok: true,- // 给 agent 的只是作者副本文件名提示,不可用于访问;staging 路径不下发。- cindyPath: staged.agentCindyPath,- id: packed.manifest.id,- name: packed.manifest.name,- version: packed.manifest.version,- // 不在这里说明确认框的加重形式(如"需手输 id"):本 note 会回到 agent,- // 被注入的 agent 读到就能照着编引导话术,帮用户"过掉"那一步。- // 告知"必须在应用内确认才会安装"已足够让作者知道下一步做什么。- note: `${iconNote}已打包并弹出装入/更新确认框,请提示用户:只有在应用内确认后插件才会真正安装。${publishHint}`,- };});},async forgePublish({ token }): Promise<CindyForgePublishResult> {@@ -1875,7 +1882,7 @@ export function getCindyGhostsMcpDeps(? '账号切换中,请稍后重试': consumed.reason === 'owner-mismatch'? '发布票据无效、已过期或已被使用,请重新打包'- : "发布票据无效、已过期或已被使用。发布票据只能由 ghost_forge_pack(intent='publish') 签发;若刚才是按缺省 install 打的包,请用 intent='publish' 重新打一次。",+ : "发布票据无效、已过期或已被使用。发布票据只能由 ghost_forge_pack(intent='publish') 签发;若刚才使用的是缺省的纯打包模式,请用 intent='publish' 重新打一次。",};}const ticket = consumed.ticket;diff --git a/apps/desktop/src/main/plugin-market/__tests__/install-manifest-read.test.ts b/apps/desktop/src/main/plugin-market/__tests__/install-manifest-read.test.tsindex 1ac6b70f5a..22f4f3cd68 100644--- a/apps/desktop/src/main/plugin-market/__tests__/install-manifest-read.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/install-manifest-read.test.ts@@ -15,6 +15,7 @@ vi.mock('electron', () => ({}));const brain = vi.hoisted(() => ({+ inspect: vi.fn(),installOrUpdateMarketGhostPackage: vi.fn(async (filePath: string, options: unknown) => {if (filePath.length === 0 || options === undefined) throw new Error('invalid install call');@@ -23,13 +24,19 @@ const brain = vi.hoisted(() => ({),rejectReservedGhostIdForCustomMarket: vi.fn(),packGhostDirToFile: vi.fn(- async (_pluginDir: string, _tempPath: string, _expectedRoot: string) => ({- ok: true as const,- manifest: {},- }),+ async (pluginDir: string, tempPath: string, expectedRoot: string) => {+ void pluginDir;+ void tempPath;+ void expectedRoot;+ return {+ ok: true as const,+ manifest: {},+ };+ },),}));vi.mock('../../cindy-brain/index.js', () => ({+ getGhostManager: () => ({ inspect: brain.inspect }),installOrUpdateMarketGhostPackage: brain.installOrUpdateMarketGhostPackage,rejectReservedGhostIdForCustomMarket: brain.rejectReservedGhostIdForCustomMarket,}));@@ -41,16 +48,15 @@ vi.mock('../../logger.js', () => ({ createLogger: () => logger }));import type { GhostManifest } from '../../../shared/ghost.js';import { installCustomMarketPlugin } from '../install';-import { GhostPackagePermissionReviewRequiredError } from '../../cindy-brain/packagePermissionReview';const GOOD_MANIFEST: GhostManifest = {- schemaVersion: 2,+ schemaVersion: 3,+ minCindyVersion: '0.1.61',id: 'demo',name: '演示插件',version: '1.0.0',kind: 'chip',entry: 'main.js',- slots: ['tool'],tools: [{ name: 'do_thing', description: '做点事' }],};const GOOD_IDENTITY = {@@ -73,6 +79,19 @@ beforeEach(async () => {dir: path.join(workDir, 'installed'),enabled: true,} as never);+ brain.inspect.mockReset();+ brain.inspect.mockResolvedValue({+ manifest: GOOD_MANIFEST,+ canonicalManifest: GOOD_MANIFEST,+ unsupportedLegacySlots: [],+ trust: {+ level: 'unverified',+ publisherSigned: false,+ publisherVerified: false,+ reviewed: false,+ },+ packageSha256: 'a'.repeat(64),+ });logger.warn.mockClear();});@@ -95,7 +114,6 @@ describe('installCustomMarketPlugin · 身份卡读取闸', () => {installCustomMarketPlugin({pluginDir,...GOOD_IDENTITY,- sourceType: 'local-market',}),).rejects.toMatchObject({ code: 'GHOST_FILE_INVALID' });expect(brain.packGhostDirToFile).not.toHaveBeenCalled();@@ -116,7 +134,6 @@ describe('installCustomMarketPlugin · 身份卡读取闸', () => {installCustomMarketPlugin({pluginDir,...GOOD_IDENTITY,- sourceType: 'local-market',}),).rejects.toMatchObject({ code: 'GHOST_FILE_INVALID' });expect(brain.packGhostDirToFile).not.toHaveBeenCalled();@@ -134,7 +151,6 @@ describe('installCustomMarketPlugin · 身份卡读取闸', () => {installCustomMarketPlugin({pluginDir: await fs.promises.realpath(pluginDir),...GOOD_IDENTITY,- sourceType: 'local-market',}),).rejects.toMatchObject({code: 'PRECONDITION_FAILED',@@ -165,7 +181,6 @@ describe('installCustomMarketPlugin · 身份卡读取闸', () => {await installCustomMarketPlugin({pluginDir: canonical,...GOOD_IDENTITY,- sourceType: 'local-market',});expect(brain.packGhostDirToFile).toHaveBeenCalledWith(@@ -175,75 +190,43 @@ describe('installCustomMarketPlugin · 身份卡读取闸', () => {);});- it('首装确认与提交复用同一个真实临时包', async () => {- const pluginDir = path.join(workDir, 'plugin-review');+ it('真实临时包只提交一次,并以发现清单作为能力上限', async () => {+ const pluginDir = path.join(workDir, 'plugin-commit');await fs.promises.mkdir(pluginDir, { recursive: true });await fs.promises.writeFile(path.join(pluginDir, 'ghost.json'),JSON.stringify(GOOD_MANIFEST),);const canonical = await fs.promises.realpath(pluginDir);- const review = {- manifest: GOOD_MANIFEST,- permissionDiff: null,- isUpdate: false,- packageSha256: 'a'.repeat(64),- installedBaseline: null,- sourceType: 'local-market' as const,- };brain.packGhostDirToFile.mockImplementationOnce(async (_pluginDir, tempPath) => {await fs.promises.writeFile(tempPath, 'verified-package');return { ok: true as const, manifest: GOOD_MANIFEST };});- let resolveCommit!: () => void;- const allowCommit = new Promise<void>((resolve) => {- resolveCommit = resolve;- });- let resolveCommitStarted!: () => void;- const commitStarted = new Promise<void>((resolve) => {- resolveCommitStarted = resolve;+ let committedTempPath = '';+ brain.installOrUpdateMarketGhostPackage.mockImplementationOnce(async (tempPath: string) => {+ committedTempPath = tempPath;+ expect(fs.existsSync(tempPath)).toBe(true);+ return {+ manifest: GOOD_MANIFEST,+ dir: path.join(workDir, 'installed'),+ enabled: true,+ } as never;});- let reviewedTempPath = '';- brain.installOrUpdateMarketGhostPackage- .mockRejectedValueOnce(new GhostPackagePermissionReviewRequiredError(review))- .mockImplementationOnce(async (tempPath: string) => {- reviewedTempPath = tempPath;- resolveCommitStarted();- await allowCommit;- expect(fs.existsSync(tempPath)).toBe(true);- return {- manifest: GOOD_MANIFEST,- dir: path.join(workDir, 'installed'),- enabled: true,- } as never;- });- const reviewer = vi.fn(async () => true);const afterCommit = vi.fn(async () => undefined);- const installing = installCustomMarketPlugin({+ await installCustomMarketPlugin({pluginDir: canonical,...GOOD_IDENTITY,- sourceType: 'local-market',- reviewPackagePermissions: reviewer,afterCommit,});- await commitStarted;- await new Promise<void>((resolve) => setImmediate(resolve));- expect(fs.existsSync(reviewedTempPath)).toBe(true);- resolveCommit();- await installing;- expect(reviewer).toHaveBeenCalledWith(review);- expect(brain.installOrUpdateMarketGhostPackage).toHaveBeenCalledTimes(2);- const [reviewPath] = brain.installOrUpdateMarketGhostPackage.mock.calls[0] ?? [];- const [commitPath, commitOptions] =- brain.installOrUpdateMarketGhostPackage.mock.calls[1] ?? [];- expect(commitPath).toBe(reviewPath);+ expect(brain.installOrUpdateMarketGhostPackage).toHaveBeenCalledTimes(1);+ const [commitPath, commitOptions] = brain.installOrUpdateMarketGhostPackage.mock.calls[0] ?? [];+ expect(commitPath).toBe(committedTempPath);expect(commitOptions).toMatchObject({ghostId: GOOD_IDENTITY.expectedGhostId,version: GOOD_IDENTITY.expectedVersion,- approvedPackageSha256: review.packageSha256,- permissionPolicy: { mode: 'manual', sourceType: 'local-market' },+ manifestCap: GOOD_MANIFEST,});expect(afterCommit).toHaveBeenCalledWith(expect.objectContaining({ manifest: GOOD_MANIFEST }),@@ -252,58 +235,24 @@ describe('installCustomMarketPlugin · 身份卡读取闸', () => {expect(fs.existsSync(String(commitPath))).toBe(false);});- it('同来源无扩权更新直接提交,不制造额外确认状态', async () => {- const pluginDir = path.join(workDir, 'plugin-update');+ it('提交失败后清理临时包', async () => {+ const pluginDir = path.join(workDir, 'plugin-failure');await fs.promises.mkdir(pluginDir, { recursive: true });await fs.promises.writeFile(path.join(pluginDir, 'ghost.json'),JSON.stringify(GOOD_MANIFEST),);- const reviewer = vi.fn(async () => true);-- await installCustomMarketPlugin({- pluginDir: await fs.promises.realpath(pluginDir),- ...GOOD_IDENTITY,- sourceType: 'local-market',- permissionBaselineManifest: GOOD_MANIFEST,- reviewPackagePermissions: reviewer,- });-- expect(brain.installOrUpdateMarketGhostPackage).toHaveBeenCalledTimes(1);- expect(reviewer).not.toHaveBeenCalled();- });-- it('用户关闭真实包确认后立即取消并清理临时包', async () => {- const pluginDir = path.join(workDir, 'plugin-cancel');- await fs.promises.mkdir(pluginDir, { recursive: true });- await fs.promises.writeFile(- path.join(pluginDir, 'ghost.json'),- JSON.stringify(GOOD_MANIFEST),- );- const review = {- manifest: GOOD_MANIFEST,- permissionDiff: null,- isUpdate: false,- packageSha256: 'b'.repeat(64),- installedBaseline: null,- sourceType: 'local-market' as const,- };- brain.installOrUpdateMarketGhostPackage.mockRejectedValueOnce(- new GhostPackagePermissionReviewRequiredError(review),- );- const reviewer = vi.fn(async () => false);+ brain.installOrUpdateMarketGhostPackage.mockRejectedValueOnce(new Error('commit failed'));const afterCommit = vi.fn(async () => undefined);- const result = await installCustomMarketPlugin({- pluginDir: await fs.promises.realpath(pluginDir),- ...GOOD_IDENTITY,- sourceType: 'local-market',- reviewPackagePermissions: reviewer,- afterCommit,- });+ await expect(+ installCustomMarketPlugin({+ pluginDir: await fs.promises.realpath(pluginDir),+ ...GOOD_IDENTITY,+ afterCommit,+ }),+ ).rejects.toThrow('commit failed');- expect(result).toBeNull();- expect(reviewer).toHaveBeenCalledWith(review);expect(brain.installOrUpdateMarketGhostPackage).toHaveBeenCalledTimes(1);expect(afterCommit).not.toHaveBeenCalled();const [tempPath] = brain.installOrUpdateMarketGhostPackage.mock.calls[0] ?? [];@@ -340,7 +289,6 @@ describe('installCustomMarketPlugin · 身份卡读取闸', () => {installCustomMarketPlugin({pluginDir: discovered, // 传发现时的规范路径...GOOD_IDENTITY,- sourceType: 'local-market',}),).rejects.toMatchObject({code: 'GHOST_FILE_INVALID',@@ -363,7 +311,6 @@ describe('installCustomMarketPlugin · 身份卡读取闸', () => {installCustomMarketPlugin({pluginDir: await fs.promises.realpath(pluginDir),...GOOD_IDENTITY,- sourceType: 'local-market',}),).rejects.toMatchObject({code: 'GHOST_FILE_INVALID',diff --git a/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts b/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.tsindex db8d64a347..d35ecbc109 100644--- a/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts@@ -37,7 +37,7 @@ describe('Plugin Market IPC error boundary', () => {expect(body).toContain('if (isIpcError(error)) throw error;');expect(body).toContain("throwIpcError('INTERNAL', 'Plugin market operation failed');");- expect(registerSource.match(/return invokePluginMarket\(/g)?.length).toBe(13);+ expect(registerSource.match(/return invokePluginMarket\(/g)?.length).toBe(12);});it('validates local icon keys with the same reserved-prefix contract as the service', () => {@@ -54,6 +54,16 @@ describe('Plugin Market IPC error boundary', () => {);});+ it('forwards the validated selected-manifest facts without a compatibility override', () => {+ const start = registerSource.indexOf("ipcMain.handle(\n 'plugin-market:install'");+ const end = registerSource.indexOf("ipcMain.handle('plugin-market:uninstall'", start);+ const body = registerSource.slice(start, end);++ expect(body).not.toContain('allowHostIncompatible');+ expect(body).toContain('requireObject(obj.expectedManifest)');+ expect(body).toContain('...(expectedManifest !== undefined ? { expectedManifest } : {})');+ });+it('guards removal notice consumption and signals trusted app windows only', () => {const consumeStart = registerSource.indexOf("ipcMain.handle('plugin-market:consume-removal-notice'",@@ -88,7 +98,7 @@ describe('Plugin Market IPC error boundary', () => {expect(serviceSource).toContain("throwIpcError('PERMISSION_DENIED'");});- it('runs default plugin reconciliation on cold start and stable owner changes', () => {+ it('runs plugin reconciliation on cold start, foreground, resume and stable owner changes', () => {const syncStart = registerSource.indexOf('export async function syncDefaultMarketPlugins(): Promise<DefaultMarketPluginSyncOutcome>',);@@ -98,7 +108,7 @@ describe('Plugin Market IPC error boundary', () => {expect(syncBody).toContain('onDefaultReconciliationOutcome: (outcome) => {');expect(syncBody).toContain("reconciliationOutcome ?? 'completed'");expect(syncBody).toContain('defaultMarketPluginSyncOutcome(');- expect(syncBody).toContain("log.warn('default plugin startup sync failed'");+ expect(syncBody).toContain("log.warn('default plugin startup sync incomplete'");expect(syncBody).toContain("return 'failed';");const outcomeStart = registerSource.indexOf(@@ -119,20 +129,16 @@ describe('Plugin Market IPC error boundary', () => {const snapshotBody = registerSource.slice(snapshotStart, snapshotEnd);expect(snapshotBody).toContain('finally {');expect(snapshotBody).toContain('signalRemovalNoticeAvailable();');- expect(snapshotBody).toContain('signalUpgradeNoticeAvailable();');expect(serviceSource).toContain("onDefaultReconciliationOutcome?: (outcome: 'completed' | 'failed') => void;");expect(serviceSource).toContain("const outcome = completed ? 'completed' : 'failed';");expect(serviceSource).toContain('options.onDefaultReconciliationOutcome?.(outcome);');expect(serviceSource).toContain('if (!(await this.applyDefaultInstalls(plugins, owner, ledger))) completed = false;');- expect(serviceSource).toContain('if (!(await this.applyDefaultUpgrades(plugins, owner, ledger))) completed = false;');+ expect(serviceSource).toContain('await this.applyAutomaticUpgrades(plugins, customDiscovery.entries, owner, ledger)');expect(serviceSource).toContain('if (error instanceof SilentUpgradeBusyError) {');- expect(registerSource).toContain('deferDefaultReconciliation: true');- expect(registerSource).toContain('onDeferredReconciliationSettled: () => {');- expect(ghostPluginPageSource).toContain(- 'window.electronAPI.pluginMarket.onUpgradeNoticeAvailable(() => {',- );+ expect(registerSource).toContain('deferReconciliation: true');+ expect(ghostPluginPageSource).toContain('const installedGhostMarketKey = useMemo(');expect(ghostPluginPageSource).toContain('void refreshMarket(true).catch(() => undefined);');const ownerTaskStart = bootstrapSource.indexOf(@@ -168,5 +174,19 @@ describe('Plugin Market IPC error boundary', () => {expect(authManagerSource).not.toContain("await ensureStableOwnerPostCommit('owner-commit');");expect(bootstrapSource).not.toContain('disposePluginMarketAuthListener');expect(bootstrapSource).not.toContain('syncDefaultPluginsForActiveOwner');++ const ownerSyncStart = bootstrapSource.indexOf(+ 'function syncPluginMarketForActiveOwner(minIntervalMs = 0): void',+ );+ const ownerSyncEnd = bootstrapSource.indexOf('\n}\n\nfunction parseOptionalDeviceLinkDeviceId', ownerSyncStart);+ const ownerSyncBody = bootstrapSource.slice(ownerSyncStart, ownerSyncEnd);+ expect(ownerSyncBody).toContain(+ 'if (!session.dataOwnerId || isAppSessionBoundaryPending()) return;',+ );+ expect(ownerSyncBody).toContain('if (scope === pluginMarketSyncInFlightScope) return;');+ expect(ownerSyncBody).toContain('void syncDefaultMarketPlugins().finally(() => {');+ expect(ownerSyncBody).toContain('pluginMarketSyncInFlightScope = null;');+ expect(bootstrapSource).toContain('PLUGIN_MARKET_PERIODIC_SYNC_MS = 30 * 60 * 1000');+ expect(bootstrapSource).toContain('syncPluginMarketForActiveOwner(30_000);');});});diff --git a/apps/desktop/src/main/plugin-market/__tests__/packagePermissionReviewBridge.test.ts b/apps/desktop/src/main/plugin-market/__tests__/packagePermissionReviewBridge.test.tsdeleted file mode 100644index 8d0caa424b..0000000000--- a/apps/desktop/src/main/plugin-market/__tests__/packagePermissionReviewBridge.test.ts+++ /dev/null@@ -1,57 +0,0 @@-import { describe, expect, it } from 'vitest';--import type { PluginMarketPackageReviewFacts } from '../../../shared/pluginMarket';-import { PluginMarketPackagePermissionReviewBridge } from '../packagePermissionReviewBridge';--const facts: PluginMarketPackageReviewFacts = {- manifest: {- schemaVersion: 2,- id: 'cindy-test',- name: 'Test Plugin',- version: '1.0.0',- kind: 'chip',- entry: 'main.js',- slots: ['notify'],- },- permissionDiff: null,- isUpdate: true,- packageSha256: 'a'.repeat(64),- installedBaseline: null,- sourceType: 'server',- builtinOauthClientChanged: false,-};-const ownerStamp = { dataOwnerId: 'owner-a', ownerGeneration: 7 };--describe('PluginMarketPackagePermissionReviewBridge', () => {- it('only accepts the answer from the requesting window and hides approval bindings', async () => {- const bridge = new PluginMarketPackagePermissionReviewBridge();- let request: Parameters<Parameters<typeof bridge.request>[3]>[0] | undefined;- const decision = bridge.request(7, facts, ownerStamp, (next) => {- request = next;- return true;- });-- expect(request).not.toHaveProperty('packageSha256');- expect(request).not.toHaveProperty('installedBaseline');- // 更新语义独立于权限基线:旧安装基线不可读时 diff 可以为 null。- expect(request).toMatchObject({ isUpdate: true, permissionDiff: null, ownerStamp });- expect(bridge.resolve(8, request!.requestId, true)).toBe(false);- expect(bridge.resolve(7, request!.requestId, true)).toBe(true);- await expect(decision).resolves.toBe(true);- });-- it('cancels every pending decision when its requester window is destroyed', async () => {- const bridge = new PluginMarketPackagePermissionReviewBridge();- const decision = bridge.request(7, facts, ownerStamp, () => true);-- bridge.cancelRequester(7);-- await expect(decision).resolves.toBe(false);- });-- it('cancels immediately when the request cannot be delivered', async () => {- const bridge = new PluginMarketPackagePermissionReviewBridge();-- await expect(bridge.request(7, facts, ownerStamp, () => false)).resolves.toBe(false);- });-});diff --git a/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.tsindex f05e5ecb8c..1bba03ca53 100644--- a/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts@@ -4,6 +4,7 @@ import path from 'node:path';import { fileURLToPath } from 'node:url';import { afterEach, describe, expect, it, vi } from 'vitest';+import JSZip from 'jszip';const runtime = vi.hoisted(() => ({ghosts: [] as Array<{@@ -26,9 +27,13 @@ const runtime = vi.hoisted(() => ({| { state: 'invalid' };}>),install: vi.fn(),+ inspect: vi.fn(),uninstall: vi.fn(),builtinRemoved: new Set<string>(),accountGhostAvailable: true,+ pendingCalls: false,+ runningErrand: false,+ cindyWork: false,boundaryPending: false,pluginApiBaseUrl: 'https://plugin.test.invalid' as string | null,session: {@@ -76,9 +81,13 @@ vi.mock('../../cindy-brain/index.js', () => ({revision: '00000000-0000-4000-8000-000000000001',},})),+ inspect: runtime.inspect,}),isGhostAvailableForActiveSession: vi.fn(() => runtime.accountGhostAvailable),installOrUpdateMarketGhostPackage: runtime.install,+ hasPendingGhostCalls: vi.fn(() => runtime.pendingCalls),+ hasRunningGhostErrand: vi.fn(() => runtime.runningErrand),+ hasRunningGhostCindyWork: vi.fn(() => runtime.cindyWork),rejectReservedGhostIdForCustomMarket: vi.fn(),isBuiltinGhostRemovedByUser: (id: string) => runtime.builtinRemoved.has(id),uninstallGhostAndCleanup: runtime.uninstall,@@ -87,9 +96,10 @@ vi.mock('../download.js', () => ({downloadVerifiedPlugin: vi.fn(async () => undefined),}));+import { downloadVerifiedPlugin } from '../download.js';import type { VisiblePluginDetail, VisiblePluginSummary } from '@cindy/plugin-protocol';-import { GHOST_ICON_MAX_BYTES, ghostPermissionBaselineKey, type GhostManifest } from '../../../shared/ghost';+import { GHOST_ICON_MAX_BYTES, type GhostManifest } from '../../../shared/ghost';import {customMarketPluginId,customMarketReleaseId,@@ -97,8 +107,6 @@ import {pluginMarketCustomIconProjectionToken,pluginMarketCustomIconSourceToken,} from '../../../shared/pluginMarket';-import type { MarketSourceConfig } from '../../../shared/pluginMarket';-import { GhostPackagePermissionReviewRequiredError } from '../../cindy-brain/packagePermissionReview';import {PluginMarketLedger,ghostManifestDigest,@@ -117,18 +125,24 @@ afterEach(() => {runtime.ghosts = [];runtime.listSequence = null;runtime.install.mockReset();+ runtime.inspect.mockReset();runtime.uninstall.mockReset();runtime.builtinRemoved.clear();runtime.accountGhostAvailable = true;+ runtime.pendingCalls = false;+ runtime.runningErrand = false;+ runtime.cindyWork = false;runtime.boundaryPending = false;runtime.pluginApiBaseUrl = 'https://plugin.test.invalid';runtime.session = { mode: 'cloud', dataOwnerId: 'user-1', generation: 1 };+ vi.mocked(downloadVerifiedPlugin).mockReset();for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true });});function ghostManifest(id: string, version = '1.0.0', overrides: Record<string, unknown> = {}) {return {- schemaVersion: 2 as const,+ schemaVersion: 3 as const,+ minCindyVersion: '0.1.61',id,name: `Plugin ${id}`,description: 'Custom market plugin',@@ -136,7 +150,7 @@ function ghostManifest(id: string, version = '1.0.0', overrides: Record<string,version,kind: 'chip' as const,entry: 'main.js',- slots: ['notify' as const],+ notify: true as const,...overrides,};}@@ -247,6 +261,35 @@ function harness(items: VisiblePluginSummary[], marketDirs: Array<{ name: string}),download: vi.fn(),};+ vi.mocked(downloadVerifiedPlugin).mockImplementation(async (_url, _expected, targetPath) => {+ const item = items[0];+ if (!item) throw new Error('missing server Plugin fixture');+ const zip = new JSZip();+ zip.file('ghost.json', JSON.stringify(ghostManifest(item.ghostId, item.currentRelease.version)));+ zip.file('main.js', '// server package fixture');+ await fs.promises.writeFile(targetPath, await zip.generateAsync({ type: 'nodebuffer' }), {+ flag: 'wx',+ mode: 0o600,+ });+ });+ runtime.inspect.mockImplementation(async (filePath: string) => {+ const zip = await JSZip.loadAsync(await fs.promises.readFile(filePath));+ const manifestEntry = zip.file('ghost.json');+ if (!manifestEntry) throw new Error('missing ghost.json in test package');+ const inspectedManifest = JSON.parse(await manifestEntry.async('text')) as GhostManifest;+ return {+ manifest: inspectedManifest,+ canonicalManifest: inspectedManifest,+ unsupportedLegacySlots: [],+ trust: {+ level: 'unverified',+ publisherSigned: false,+ publisherVerified: false,+ reviewed: false,+ },+ packageSha256: 'a'.repeat(64),+ };+ });return {api,ledger,@@ -364,7 +407,7 @@ describe('PluginMarketService 自定义市场聚合', () => {expect(h.ledger.isDefaultInstallSuppressed('user-1', pluginId)).toBe(false);});- it('does not expose custom market releases that require a newer Cindy version', async () => {+ it('keeps custom releases visible without a client min-version filter', async () => {const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));roots.push(root);const dir = writeLocalMarket(root, 'team-lib', [@@ -379,7 +422,7 @@ describe('PluginMarketService 自定义市场聚合', () => {const snapshot = await h.service.snapshot();- expect(snapshot.items.map((item) => item.ghostId)).toEqual(['compatible']);+ expect(snapshot.items.map((item) => item.ghostId)).toEqual(['compatible', 'requires-newer']);});it('strips bidi/control chars from custom plugin name/description/author in snapshot', async () => {@@ -456,7 +499,7 @@ describe('PluginMarketService 自定义市场聚合', () => {);});- it('reports update-available when the marketplace version moved past the install', async () => {+ it('silently updates a tracked custom plugin when the marketplace version advances', async () => {const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));roots.push(root);const dir = writeLocalMarket(root, 'team-lib', [@@ -493,13 +536,19 @@ describe('PluginMarketService 自定义市场聚合', () => {sourceKey: marketSourceKey({ type: 'local', path: dir }),manifestDigest: ghostManifestDigest(ghostManifest('alpha', '1.0.0')),});+ runtime.install.mockImplementationOnce(async () => {+ const upgraded = installedGhost(root, 'alpha', '2.0.0');+ runtime.ghosts = [upgraded];+ return upgraded;+ });const snapshot = await h.service.snapshot();expect(snapshot.items[0]).toMatchObject({- installState: 'update-available',+ installState: 'installed',version: '2.0.0',enabled: true,});+ expect(runtime.install).toHaveBeenCalledTimes(1);});});@@ -1093,6 +1142,68 @@ describe('PluginMarketService 自定义市场 snapshot 账户作用域', () => {});describe('PluginMarketService 自定义市场 detail/install', () => {+ it('installs a custom market package without a client version gate', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = writeLocalMarket(root, 'team-lib', [+ {+ rel: 'plugins/requires-newer',+ id: 'requires-newer',+ minCindyVersion: '2.0.0',+ },+ ]);+ const h = harness([], [{ name: 'team-lib', dir }]);+ const pluginId = customMarketPluginId('team-lib', 'requires-newer');++ const selected = await h.service.detail(pluginId);+ expect(selected).toMatchObject({+ pluginId,+ manifest: { id: 'requires-newer', minCindyVersion: '2.0.0' },+ });+ const releaseId = customMarketReleaseId('team-lib', 'requires-newer', '1.0.0');+ runtime.install.mockResolvedValue(installedGhost(root, 'requires-newer'));+ await expect(+ h.service.install(pluginId, {+ expectedReleaseId: releaseId,+ expectedManifest: selected.manifest,+ }),+ ).resolves.toMatchObject({ ghost: { manifest: { id: 'requires-newer' } } });+ expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({+ ghostId: 'requires-newer',+ });+ });++ it('does not turn custom package min-version drift into a confirmation flow', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);+ const h = harness([], [{ name: 'team-lib', dir }]);+ const pluginId = customMarketPluginId('team-lib', 'alpha');+ const selected = await h.service.detail(pluginId);+ const actualManifest = ghostManifest('alpha', '1.0.0', { minCindyVersion: '2.0.0' });+ runtime.inspect.mockResolvedValueOnce({+ manifest: actualManifest,+ canonicalManifest: actualManifest,+ unsupportedLegacySlots: [],+ trust: {+ level: 'unverified',+ publisherSigned: false,+ publisherVerified: false,+ reviewed: false,+ },+ packageSha256: 'a'.repeat(64),+ });+ runtime.install.mockResolvedValue(installedGhost(root, 'alpha'));++ await expect(+ h.service.install(pluginId, {+ expectedReleaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),+ expectedManifest: selected.manifest,+ }),+ ).resolves.toMatchObject({ ghost: { manifest: { id: 'alpha' } } });+ expect(runtime.install).toHaveBeenCalledTimes(1);+ });+it('returns the validated manifest for custom plugin detail', async () => {const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));roots.push(root);@@ -1144,74 +1255,6 @@ describe('PluginMarketService 自定义市场 detail/install', () => {});});- it('requires full review for an unapproved custom update and carries its receipt token to commit', async () => {- const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));- roots.push(root);- const dir = writeLocalMarket(root, 'team-lib', [- { rel: 'plugins/alpha', id: 'alpha', version: '2.0.0' },- ]);- const h = harness([], [{ name: 'team-lib', dir }]);- const installedManifest = ghostManifest('alpha', '1.0.0');- const installedDir = path.join(root, 'installed-alpha');- fs.mkdirSync(installedDir, { recursive: true });- fs.writeFileSync(path.join(installedDir, 'ghost.json'), JSON.stringify(installedManifest));- runtime.ghosts = [- {- manifest: installedManifest,- dir: installedDir,- enabled: true,- approval: { state: 'legacy-unapproved' },- },- ];- h.ledger.upsertInstallation({- pluginId: customMarketPluginId('team-lib', 'alpha'),- ghostId: 'alpha',- releaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),- version: '1.0.0',- sha256: 'custom-unverified',- scope: 'public',- organizationId: null,- source: 'local-market',- installed: true,- updatedAt: '2026-08-01T00:00:00.000Z',- sourceKey: marketSourceKey({ type: 'local', path: dir }),- manifestDigest: ghostManifestDigest(installedManifest),- });- runtime.install.mockResolvedValue({- manifest: ghostManifest('alpha', '2.0.0'),- dir: installedDir,- enabled: true,- });- const pluginId = customMarketPluginId('team-lib', 'alpha');- const reviewed = await h.service.detail(pluginId);-- await expect(- h.service.install(pluginId, {- expectedReleaseId: reviewed.releaseId,- expectedManifest: reviewed.manifest,- expectedInstalledApproval: 'legacy-unapproved',- }),- ).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });- expect(runtime.install).not.toHaveBeenCalled();-- await h.service.install(pluginId, {- expectedReleaseId: reviewed.releaseId,- expectedManifest: reviewed.manifest,- expectedInstalledApproval: 'legacy-unapproved',- allowPermissionExpansion: true,- reviewedBaseline: ghostPermissionBaselineKey(installedManifest as GhostManifest),- });- expect(runtime.install).toHaveBeenCalledWith(- expect.any(String),- expect.objectContaining({ expectedInstalledApproval: 'legacy-unapproved' }),- );- // 非 approved 安装无批准基线:目标包全部权限都必须重新确认,- // 不让可变安装目录的 ghost.json 冒充权限基线。- expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty(- 'permissionBaselineManifest',- );- });-it('rejects a custom update when the receipt changes during packaging', async () => {const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));roots.push(root);@@ -1287,55 +1330,51 @@ describe('PluginMarketService 自定义市场 detail/install', () => {expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({ghostId: 'cindy-github',version: '1.0.0',- permissionPolicy: { mode: 'manual', sourceType: 'local-market' },+ manifestCap: ghostManifest('cindy-github'),});expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty('officialCindyGithub');});- it('rejects install when the reviewed release no longer matches', async () => {+ it('rejects install when the selected release no longer matches', async () => {const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));roots.push(root);const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);const h = harness([], [{ name: 'team-lib', dir }]);- await h.service.detail(customMarketPluginId('team-lib', 'alpha'));+ const detail = await h.service.detail(customMarketPluginId('team-lib', 'alpha'));await expect(h.service.install(customMarketPluginId('team-lib', 'alpha'), {expectedReleaseId: 'custom:stale',+ expectedManifest: detail.manifest,}),).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });expect(runtime.install).not.toHaveBeenCalled();});- it('uses the packaged manifest when the catalog preview changed before install', async () => {+ it('requires every custom install to bind the selected manifest', async () => {const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));roots.push(root);const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);const h = harness([], [{ name: 'team-lib', dir }]);const detail = await h.service.detail(customMarketPluginId('team-lib', 'alpha'));- // 用户审阅之后,本地 ghost.json 保持 id/version 不变但新增权限声明。- const ghostFile = path.join(dir, 'plugins', 'alpha', 'ghost.json');- const tampered = { ...ghostManifest('alpha'), description: 'tampered after review' };- fs.writeFileSync(ghostFile, JSON.stringify(tampered));- runtime.install.mockResolvedValue(installedGhost(root, 'alpha'));await expect(h.service.install(customMarketPluginId('team-lib', 'alpha'), {expectedReleaseId: detail.releaseId,}),- ).resolves.toMatchObject({ ghost: { manifest: { id: 'alpha' } } });- expect(runtime.install).toHaveBeenCalledTimes(1);+ ).rejects.toMatchObject({ code: 'INVALID_PARAMS' });+ expect(runtime.install).not.toHaveBeenCalled();});- it('rejects install when the manifest changed after permission review', async () => {+ it('rejects install when the manifest changed after selection', async () => {const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));roots.push(root);const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);const h = harness([], [{ name: 'team-lib', dir }]);const detail = await h.service.detail(customMarketPluginId('team-lib', 'alpha'));- // 用户审阅之后,本地 ghost.json 保持 id/version 不变但新增权限声明。+ // 用户选择之后,本地 ghost.json 保持 id/version 不变但内容发生变化。const ghostFile = path.join(dir, 'plugins', 'alpha', 'ghost.json');const tampered = { ...ghostManifest('alpha'), description: 'tampered after review' };fs.writeFileSync(ghostFile, JSON.stringify(tampered));@@ -1357,7 +1396,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {const detail = await h.service.detail(customMarketPluginId('team-lib', 'alpha'));// 打包(异步)完成后、装出前,会话已漂移到 user-2:beforeCommit 必须拒绝,- // 不得把 user-1 审阅的插件装进 user-2 的运行时。+ // 不得把 user-1 选择的插件装进 user-2 的运行时。h.api.listAll.mockImplementation(async () => {runtime.session = { mode: 'cloud', dataOwnerId: 'user-2', generation: 2 };return { plugins: [], removals: [] };@@ -1365,6 +1404,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {// 打包前的 discover/校验按 user-1 完成;在 install 入口后切换会话。const installPromise = h.service.install(customMarketPluginId('team-lib', 'alpha'), {expectedReleaseId: detail.releaseId,+ expectedManifest: detail.manifest,});runtime.session = { mode: 'cloud', dataOwnerId: 'user-2', generation: 2 };await expect(installPromise).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });@@ -1372,36 +1412,6 @@ describe('PluginMarketService 自定义市场 detail/install', () => {runtime.session = { mode: 'cloud', dataOwnerId: 'user-1', generation: 1 };});- it('does not expose custom package review facts after the active owner changes', async () => {- const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));- roots.push(root);- const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);- const h = harness([], [{ name: 'team-lib', dir }]);- const detail = await h.service.detail(customMarketPluginId('team-lib', 'alpha'));- runtime.install.mockImplementationOnce(async () => {- runtime.session = { mode: 'cloud', dataOwnerId: 'user-2', generation: 2 };- throw new GhostPackagePermissionReviewRequiredError({- manifest: ghostManifest('alpha', '1.0.0', { slots: ['notify', 'fs'] }),- permissionDiff: null,- isUpdate: false,- packageSha256: 'a'.repeat(64),- installedBaseline: null,- sourceType: 'local-market',- });- });- const confirmReview = vi.fn(async () => true);-- await expect(- h.service.install(- customMarketPluginId('team-lib', 'alpha'),- { expectedReleaseId: detail.releaseId },- confirmReview,- ),- ).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });- expect(confirmReview).not.toHaveBeenCalled();- runtime.session = { mode: 'cloud', dataOwnerId: 'user-1', generation: 1 };- });-it('rejects install when the plugin is uninstalled during packaging (runtime 复核)', async () => {// F1:审阅时 alpha 已装(existing 存在),打包窗口内本地页把它卸载。// beforeCommit 的 runtime 复核必须发现 existing→缺失并拒,避免"更新"被@@ -1442,6 +1452,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {await expect(h.service.install(pluginId, {expectedReleaseId: reviewed.releaseId,+ expectedManifest: reviewed.manifest,}),).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });expect(runtime.install).not.toHaveBeenCalled();@@ -1581,7 +1592,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {}),).resolves.toMatchObject({ ghost: { manifest: { id: 'alpha' } } });expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({- permissionBaselineManifest: current.manifest,+ manifestCap: ghostManifest('alpha'),});expect(h.ledger.installationForGhost('alpha')).toMatchObject({pluginId: customMarketPluginId('team-lib', 'alpha'),@@ -1842,7 +1853,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {}),).resolves.toMatchObject({ ghost: { manifest: { version: '2.0.0' } } });expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({- permissionBaselineManifest: current.manifest,+ manifestCap: ghostManifest('alpha', '2.0.0'),});expect(h.ledger.installationForGhost('alpha')).toMatchObject({sourceKey: marketSourceKey({ type: 'local', path: dirB }),@@ -1938,12 +1949,11 @@ describe('PluginMarketService 自定义市场 detail/install', () => {expectedReleaseId: customMarketReleaseId("team-lib", "alpha", "2.0.0"),expectedManifest: detail.manifest,expectedInstalledApproval: APPROVED_INSTALL_TOKEN,- allowPermissionExpansion: true,allowSourceReplacement: true,}),).resolves.toMatchObject({ ghost: { manifest: { version: '2.0.0' } } });expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({- permissionBaselineManifest: replacedManifest,+ manifestCap: ghostManifest('alpha', '2.0.0'),});expect(h.ledger.installationForGhost('alpha')).toMatchObject({sourceKey: marketSourceKey({ type: 'local', path: dir }),@@ -2137,9 +2147,9 @@ describe('PluginMarketService 自定义市场 detail/install', () => {allowSourceReplacement: true,}),).resolves.toMatchObject({ ghost: { manifest: { id: 'server-plugin' } } });- expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty(- 'permissionBaselineManifest',- );+ expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({+ manifestCap: ghostManifest('server-plugin'),+ });expect(h.ledger.installationForGhost('server-plugin')).toMatchObject({pluginId: item.id,source: 'market',@@ -2177,7 +2187,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {}),).resolves.toMatchObject({ ghost: { manifest: { id: 'alpha' } } });expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({- permissionBaselineManifest: ghostManifest('alpha'),+ manifestCap: ghostManifest('alpha'),});expect(h.ledger.installationForGhost('alpha')).toMatchObject({pluginId: customMarketPluginId('team-lib', 'alpha'),diff --git a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service.test.tsindex 9a550ebacf..25b37179e3 100644--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts@@ -5,13 +5,10 @@ import path from 'node:path';import { afterEach, describe, expect, it, vi } from 'vitest';import {- diffGhostPermissionItems,- ghostPermissionBaselineKey,validateGhostManifest,type GhostInstallApproval,type GhostManifest,} from '../../../shared/ghost.js';-const runtime = vi.hoisted(() => ({ghosts: [] as Array<{manifest: Record<string, unknown>;@@ -20,6 +17,8 @@ const runtime = vi.hoisted(() => ({approval?: GhostInstallApproval;}>,install: vi.fn(),+ inspect: vi.fn(),+ inspectedManifest: null as Record<string, unknown> | null,uninstall: vi.fn(),builtinRemoved: new Set<string>(),accountGhostAvailable: true,@@ -75,6 +74,7 @@ vi.mock('../../cindy-brain/index.js', () => ({},})),approvedInstallEvidence: runtime.approvedInstallEvidence,+ inspect: runtime.inspect,}),isGhostAvailableForActiveSession: vi.fn(() => runtime.accountGhostAvailable),installOrUpdateMarketGhostPackage: runtime.install,@@ -95,7 +95,6 @@ import type {} from '@cindy/plugin-protocol';import { withGhostInstallLock } from '../../cindy-brain/ghostInstallLock';-import { GhostPackagePermissionReviewRequiredError } from '../../cindy-brain/packagePermissionReview';import {PluginMarketLedger,ghostManifestDigest,@@ -122,6 +121,8 @@ function deferred(): { promise: Promise<void>; resolve: () => void } {afterEach(() => {runtime.ghosts = [];runtime.install.mockReset();+ runtime.inspect.mockReset();+ runtime.inspectedManifest = null;runtime.uninstall.mockReset();runtime.builtinRemoved.clear();runtime.accountGhostAvailable = true;@@ -143,10 +144,11 @@ afterEach(() => {function manifest(id = 'cindy-test',version = '1.0.0',- slots: ['notify'] | ['notify', 'fs'] = ['notify'],+ capabilities: readonly ('notify' | 'fs' | 'workspace')[] = ['notify'],) {return {- schemaVersion: 2 as const,+ schemaVersion: 3 as const,+ minCindyVersion: '0.1.61',id,name: 'Test Plugin',description: 'Test description',@@ -154,7 +156,9 @@ function manifest(version,kind: 'chip' as const,entry: 'main.js',- slots,+ notify: true as const,+ ...(capabilities.includes('fs') ? { fs: true as const } : {}),+ ...(capabilities.includes('workspace') ? { workspace: true as const } : {}),};}@@ -171,7 +175,6 @@ function setupKvManifest(id = 'cindy-test', version = '1.0.0') {function setupSecretManifest(id = 'cindy-test', version = '1.0.0') {return {...manifest(id, version),- slots: ['notify', 'network'],settingsHtml: 'settings.html',network: {hosts: ['api.example.com'],@@ -190,7 +193,6 @@ function setupSecretManifest(id = 'cindy-test', version = '1.0.0') {function brokerManifestWithoutPort(id = 'cindy-test', version = '1.0.0') {return {...manifest(id, version),- slots: ['network'],settingsHtml: 'settings.html',network: {hosts: ['accounts.example.com'],@@ -288,11 +290,13 @@ function harness(items: VisiblePluginSummary[], removals: PluginRemovalNotice[]detail: vi.fn(async (pluginId: string): Promise<VisiblePluginDetail> => {const item = items.find((candidate) => candidate.id === pluginId);if (!item) throw new Error('not found');+ const detailedManifest = manifest(item.ghostId, item.currentRelease.version);+ runtime.inspectedManifest = detailedManifest;return {...item,currentRelease: {...item.currentRelease,- manifest: manifest(item.ghostId, item.currentRelease.version),+ manifest: detailedManifest,},} satisfies VisiblePluginDetail;}),@@ -303,6 +307,21 @@ function harness(items: VisiblePluginSummary[], removals: PluginRemovalNotice[]sizeBytes: 42,})),};+ runtime.inspect.mockImplementation(async () => {+ const inspectedManifest = runtime.inspectedManifest ?? manifest(items[0]?.ghostId);+ return {+ manifest: inspectedManifest,+ canonicalManifest: inspectedManifest,+ unsupportedLegacySlots: [],+ trust: {+ level: 'unverified',+ publisherSigned: false,+ publisherVerified: false,+ reviewed: false,+ },+ packageSha256: 'a'.repeat(64),+ };+ });return {api,ledger,@@ -962,11 +981,7 @@ describe('PluginMarketService migration and defaultInstall', () => {expect.objectContaining({ghostId: 'cindy-test',version: '1.0.0',- permissionPolicy: {- mode: 'cap',- manifest: manifest(),- sourceType: 'server',- },+ manifestCap: manifest(),beforeCommitInLock: expect.any(Function),}),);@@ -981,7 +996,7 @@ describe('PluginMarketService migration and defaultInstall', () => {});});- it('installs a default package whose permission cap contains normalized setup requirements', async () => {+ it('installs a default package whose manifest cap contains normalized setup requirements', async () => {const item = summary({ defaultInstall: true });const rawManifest = setupKvManifest();const approvedManifest = normalizedManifest(rawManifest);@@ -1006,11 +1021,7 @@ describe('PluginMarketService migration and defaultInstall', () => {expect(runtime.install).toHaveBeenCalledWith(expect.stringMatching(/\.cindy$/),expect.objectContaining({- permissionPolicy: {- mode: 'cap',- manifest: approvedManifest,- sourceType: 'server',- },+ manifestCap: approvedManifest,}),);});@@ -1021,7 +1032,6 @@ describe('PluginMarketService migration and defaultInstall', () => {roots.push(installDir);fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(manifest()));const downloadGate = deferred();- const reconciliationSettled = deferred();const h = harness([item]);h.api.download.mockImplementationOnce(async () => {await downloadGate.promise;@@ -1039,27 +1049,20 @@ describe('PluginMarketService migration and defaultInstall', () => {});const snapshot = await h.service.snapshot({- deferDefaultReconciliation: true,- onDeferredReconciliationSettled: reconciliationSettled.resolve,+ deferReconciliation: true,});expect(snapshot.items[0]?.installState).toBe('not-installed');await vi.waitFor(() => expect(h.api.download).toHaveBeenCalledOnce());downloadGate.resolve();- await reconciliationSettled.promise;- expect(runtime.install).toHaveBeenCalledOnce();+ await vi.waitFor(() => expect(runtime.install).toHaveBeenCalledOnce());});- it('does not auto-install a default package with permissions absent from its catalog manifest', async () => {+ it('does not auto-install a package rejected for exceeding its catalog manifest', async () => {const item = summary({ defaultInstall: true });runtime.install.mockRejectedValueOnce(- new GhostPackagePermissionReviewRequiredError({- manifest: manifest(item.ghostId, item.currentRelease.version, ['notify', 'fs']),- permissionDiff: null,- isUpdate: false,- packageSha256: item.currentRelease.sha256,- installedBaseline: null,- sourceType: 'server',+ Object.assign(new Error('package capabilities exceed market manifest'), {+ code: 'GHOST_FILE_INVALID',}),);const h = harness([item]);@@ -1069,11 +1072,7 @@ describe('PluginMarketService migration and defaultInstall', () => {expect(runtime.install).toHaveBeenCalledWith(expect.stringMatching(/\.cindy$/),expect.objectContaining({- permissionPolicy: {- mode: 'cap',- manifest: manifest(),- sourceType: 'server',- },+ manifestCap: manifest(),}),);expect(snapshot.items[0]?.installState).toBe('not-installed');@@ -1105,7 +1104,7 @@ describe('PluginMarketService migration and defaultInstall', () => {expect(h.ledger.installationForGhost(item.ghostId)?.manifestDigest).toBeUndefined();});- it('rejects an incompatible official Plugin detail', async () => {+ it('preserves the server-selected release without a client version filter', async () => {const item = summary();const incompatibleManifest = { ...manifest(), minCindyVersion: '2.0.0' };const h = harness([item]);@@ -1117,14 +1116,16 @@ describe('PluginMarketService migration and defaultInstall', () => {},} satisfies VisiblePluginDetail);- await expect(h.service.detail(item.id)).rejects.toThrow('[NOT_FOUND]');+ await expect(h.service.detail(item.id)).resolves.toMatchObject({+ manifest: { minCindyVersion: '2.0.0' },+ });});- it('rejects an incompatible official Plugin before download', async () => {+ it('installs the server-selected release without a client compatibility override', async () => {const item = summary();const incompatibleManifest = { ...manifest(), minCindyVersion: '2.0.0' };const h = harness([item]);- h.api.detail.mockResolvedValueOnce({+ h.api.detail.mockResolvedValue({...item,currentRelease: {...item.currentRelease,@@ -1132,13 +1133,48 @@ describe('PluginMarketService migration and defaultInstall', () => {},} satisfies VisiblePluginDetail);+ runtime.install.mockResolvedValue({+ manifest: incompatibleManifest,+ dir: '/userData/cindy-brain/cindy-test',+ enabled: true,+ });await expect(h.service.install(item.id, {expectedReleaseId: item.currentRelease.id,}),- ).rejects.toThrow('[NOT_FOUND]');- expect(h.api.download).not.toHaveBeenCalled();- expect(runtime.install).not.toHaveBeenCalled();+ ).resolves.toMatchObject({ ghost: { manifest: { id: 'cindy-test' } } });+ expect(runtime.install).toHaveBeenCalledWith(expect.stringMatching(/\.cindy$/), {+ ghostId: 'cindy-test',+ version: '1.0.0',+ manifestCap: incompatibleManifest,+ });+ });++ it('does not turn a downloaded package min-version drift into a confirmation flow', async () => {+ const item = summary();+ const h = harness([item]);+ const actualManifest = { ...manifest(), minCindyVersion: '2.0.0' };+ runtime.inspect.mockResolvedValueOnce({+ manifest: actualManifest,+ canonicalManifest: actualManifest,+ unsupportedLegacySlots: [],+ trust: {+ level: 'unverified',+ publisherSigned: false,+ publisherVerified: false,+ reviewed: false,+ },+ packageSha256: 'a'.repeat(64),+ });+ runtime.install.mockResolvedValue({+ manifest: actualManifest,+ dir: '/userData/cindy-brain/cindy-test',+ enabled: true,+ });+ await expect(+ h.service.install(item.id, reviewedInstallOptions(item)),+ ).resolves.toMatchObject({ ghost: { manifest: { id: 'cindy-test' } } });+ expect(runtime.install).toHaveBeenCalledTimes(1);});it('keeps a no-port broker release visible in detail but rejects market installation before download', async () => {@@ -1179,15 +1215,11 @@ describe('PluginMarketService migration and defaultInstall', () => {const { ghost } = await h.service.install(item.id, reviewedInstallOptions(item));- expect(runtime.install).toHaveBeenCalledWith(- expect.stringMatching(/\.cindy$/),- expect.objectContaining({- ghostId: 'cindy-test',- version: '1.0.0',- permissionPolicy: { mode: 'manual', sourceType: 'server' },- reviewedManifest: expect.objectContaining({ id: 'cindy-test' }),- }),- );+ expect(runtime.install).toHaveBeenCalledWith(expect.stringMatching(/\.cindy$/), {+ ghostId: 'cindy-test',+ version: '1.0.0',+ manifestCap: manifest(),+ });// 安装入口用目录 summary 做 detail 身份绑定(防止把 A 的确认导向 B 的内容),// 因此手动安装也会先取一次目录,但不做任何 listAll 之外的多余请求。expect(h.api.listAll).toHaveBeenCalledTimes(1);@@ -1271,25 +1303,24 @@ describe('PluginMarketService migration and defaultInstall', () => {...item,currentRelease: { ...item.currentRelease, manifest: rawManifest },} as unknown as VisiblePluginDetail);+ runtime.inspectedManifest = reviewedManifest;runtime.install.mockResolvedValue({manifest: reviewedManifest,dir: '/userData/cindy-brain/cindy-test',enabled: true,});- await expect(- h.service.install(item.id, {- ...reviewedInstallOptions(item),- expectedManifest: reviewedManifest,- }),- ).resolves.toMatchObject({+ await expect(h.service.install(item.id, reviewedInstallOptions(item))).resolves.toMatchObject({ghost: {manifest: {setup: { requires: [{ anyOf: [{ kind: 'secret', key: 'api_key' }] }] },},},});- expect(runtime.install).toHaveBeenCalledOnce();+ expect(runtime.install).toHaveBeenCalledWith(+ expect.stringMatching(/\.cindy$/),+ expect.objectContaining({ manifestCap: reviewedManifest }),+ );});it('installs the explicitly selected official entry when another entry shares its ghostId', async () => {@@ -1335,14 +1366,11 @@ describe('PluginMarketService migration and defaultInstall', () => {});const ordinaryHarness = harness([ordinary]);await ordinaryHarness.service.install(ordinary.id, reviewedInstallOptions(ordinary));- expect(runtime.install.mock.calls[0]?.[1]).toEqual(- expect.objectContaining({- ghostId: 'cindy-test',- version: '1.0.0',- permissionPolicy: { mode: 'manual', sourceType: 'server' },- reviewedManifest: expect.objectContaining({ id: 'cindy-test' }),- }),- );+ expect(runtime.install.mock.calls[0]?.[1]).toEqual({+ ghostId: 'cindy-test',+ version: '1.0.0',+ manifestCap: manifest(),+ });});it('旧 source:market + manifestDigest 安装会回填 cindy-github 官方 trust', async () => {@@ -1584,7 +1612,7 @@ describe('PluginMarketService migration and defaultInstall', () => {});});- it('keeps the server manifest out of the manual package permission boundary', async () => {+ it('passes the selected server manifest as the downloaded package capability cap', async () => {const item = summary();runtime.install.mockResolvedValue({manifest: manifest(),@@ -1596,90 +1624,11 @@ describe('PluginMarketService migration and defaultInstall', () => {await h.service.install(item.id, reviewedInstallOptions(item));expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({- permissionPolicy: { mode: 'manual', sourceType: 'server' },- reviewedManifest: expect.objectContaining({ id: item.ghostId }),- });- expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty('permissionBaselineManifest');- });-- it('pauses one install transaction for package review and reuses the download', async () => {- const item = summary();- const review = {- manifest: manifest('cindy-test', '1.0.0', ['notify', 'fs']),- permissionDiff: null,- isUpdate: false,- packageSha256: 'a'.repeat(64),- installedBaseline: null,- sourceType: 'server' as const,- };- const commitStarted = deferred();- const allowCommit = deferred();- let reviewedTempPath = '';- runtime.install- .mockImplementationOnce(async (tempPath: string) => {- fs.writeFileSync(tempPath, 'verified-package');- throw new GhostPackagePermissionReviewRequiredError(review);- })- .mockImplementationOnce(async (tempPath: string) => {- reviewedTempPath = tempPath;- commitStarted.resolve();- await allowCommit.promise;- expect(fs.existsSync(tempPath)).toBe(true);- return {- manifest: manifest(),- dir: '/userData/cindy-brain/cindy-test',- enabled: true,- };- });- const h = harness([item]);- const confirmReview = vi.fn(async () => true);-- const installing = h.service.install(item.id, reviewedInstallOptions(item), confirmReview);- await commitStarted.promise;- await new Promise<void>((resolve) => setImmediate(resolve));- expect(fs.existsSync(reviewedTempPath)).toBe(true);- allowCommit.resolve();- await expect(installing).resolves.toMatchObject({- ghost: { manifest: { id: item.ghostId } },- });- expect(confirmReview).toHaveBeenCalledWith(review);- expect(h.api.download).toHaveBeenCalledTimes(1);- expect(runtime.install).toHaveBeenLastCalledWith(- expect.stringMatching(/\.cindy$/),- expect.objectContaining({- permissionPolicy: { mode: 'manual', sourceType: 'server' },- approvedPackageSha256: review.packageSha256,- }),- );- });-- it('does not return package review details after the active owner changes', async () => {- const item = summary();- const review = {- manifest: manifest('cindy-test', '1.0.0', ['notify', 'fs']),- permissionDiff: null,- isUpdate: false,- packageSha256: 'a'.repeat(64),- installedBaseline: null,- sourceType: 'server' as const,- };- runtime.install.mockImplementationOnce(async () => {- runtime.session = {- mode: 'cloud',- dataOwnerId: 'user-2',- generation: 2,- };- throw new GhostPackagePermissionReviewRequiredError(review);+ manifestCap: manifest(),});- const h = harness([item]);-- await expect(h.service.install(item.id, reviewedInstallOptions(item))).rejects.toThrow(- '[PRECONDITION_FAILED]',- );- expect(h.ledger.installationForGhost(item.ghostId)).toBeNull();});- it('uses a digest-matched installed manifest as the approved receipt baseline', async () => {+ it('uses the selected release manifest as the update package capability cap', async () => {const item = summary({currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },});@@ -1721,11 +1670,8 @@ describe('PluginMarketService migration and defaultInstall', () => {});expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({- permissionBaselineManifest: expect.objectContaining({ id: installed.id }),+ manifestCap: manifest(item.ghostId, '2.0.0'),});- expect(runtime.install.mock.calls[0]?.[1]?.permissionBaselineManifest).not.toHaveProperty(- 'manual',- );});it('keeps a stale official record out of automatic updates but allows explicit replacement', async () => {@@ -1790,7 +1736,9 @@ describe('PluginMarketService migration and defaultInstall', () => {).resolves.toMatchObject({ghost: { manifest: { version: '2.0.0' } },});- expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty('permissionBaselineManifest');+ expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({+ manifestCap: manifest(item.ghostId, '2.0.0'),+ });expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({pluginId: item.id,source: 'market',@@ -1799,7 +1747,7 @@ describe('PluginMarketService migration and defaultInstall', () => {});});- it('does not trust a mutable install manifest as the permission baseline without a matching ledger digest', async () => {+ it('uses the selected release manifest as the cap for a legacy-record update', async () => {const item = summary({currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },});@@ -1826,7 +1774,9 @@ describe('PluginMarketService migration and defaultInstall', () => {expectedInstalledApproval: APPROVED_INSTALL_TOKEN,});- expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty('permissionBaselineManifest');+ expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({+ manifestCap: manifest(item.ghostId, '2.0.0'),+ });});it('installs and enables a public defaultInstall package in local mode', async () => {@@ -1854,11 +1804,7 @@ describe('PluginMarketService migration and defaultInstall', () => {expect.objectContaining({ghostId: item.ghostId,version: item.currentRelease.version,- permissionPolicy: {- mode: 'cap',- manifest: manifest(),- sourceType: 'server',- },+ manifestCap: manifest(),beforeCommitInLock: expect.any(Function),}),);@@ -1907,7 +1853,6 @@ describe('PluginMarketService migration and defaultInstall', () => {// 必须跳过,交给重新确认/恢复流程。runtime.install 不应被调用。expect(runtime.install).not.toHaveBeenCalled();expect(snapshot.items[0]).toMatchObject({ installState: 'update-available' });- expect(h.service.consumeUpgradeNotice()).toBeNull();},);@@ -1947,23 +1892,13 @@ describe('PluginMarketService migration and defaultInstall', () => {expect.objectContaining({ghostId: item.ghostId,version: '2.0.0',- permissionPolicy: {- mode: 'cap',- manifest: upgraded,- sourceType: 'server',- },+ manifestCap: upgraded,}),);expect(snapshot.items[0]).toMatchObject({ installState: 'installed', enabled: false });- expect(h.service.consumeUpgradeNotice()).toEqual({- count: 1,- name: 'Test Plugin',- permissions: null,- hasPermissionExpansion: false,- });});- it('silently upgrades a default package whose reviewed manifest contains normalized setup', async () => {+ it('silently upgrades a default package whose manifest cap contains normalized setup', async () => {const item = summary({scope: 'organization',organizationId: 'org-1',@@ -1992,6 +1927,7 @@ describe('PluginMarketService migration and defaultInstall', () => {...item,currentRelease: { ...item.currentRelease, manifest: rawManifest },} as unknown as VisiblePluginDetail);+ runtime.inspectedManifest = upgradedManifest;runtime.install.mockImplementationOnce(async () => {const ghost = { manifest: { ...upgradedManifest }, dir: installDir, enabled: true };runtime.ghosts = [ghost];@@ -2004,16 +1940,12 @@ describe('PluginMarketService migration and defaultInstall', () => {expect(runtime.install).toHaveBeenCalledWith(expect.stringMatching(/\.cindy$/),expect.objectContaining({- permissionPolicy: {- mode: 'cap',- manifest: upgradedManifest,- sourceType: 'server',- },+ manifestCap: upgradedManifest,}),);});- it('integration: snapshot upgrades an organization defaultInstall release and consumes its notice', async () => {+ it('integration: snapshot upgrades an organization defaultInstall release', async () => {const item = summary({scope: 'organization',organizationId: 'org-1',@@ -2052,13 +1984,6 @@ describe('PluginMarketService migration and defaultInstall', () => {expect(h.api.detail).toHaveBeenCalledWith(item.id);expect(h.api.download).toHaveBeenCalledWith(item.id, 'release-2');expect(runtime.install).toHaveBeenCalledTimes(1);- expect(h.service.consumeUpgradeNotice()).toEqual({- count: 1,- name: 'Test Plugin',- permissions: null,- hasPermissionExpansion: false,- });- expect(h.service.consumeUpgradeNotice()).toBeNull();});it('skips a queued duplicate snapshot after the first upgrade reconciles the release', async () => {@@ -2094,16 +2019,9 @@ describe('PluginMarketService migration and defaultInstall', () => {expect(h.api.download).toHaveBeenCalledTimes(1);expect(runtime.install).toHaveBeenCalledTimes(1);- expect(h.service.consumeUpgradeNotice()).toEqual({- count: 1,- name: 'Test Plugin',- permissions: null,- hasPermissionExpansion: false,- });- expect(h.service.consumeUpgradeNotice()).toBeNull();});- it('silently upgrades organization plugins that expand catalog permissions and reports the new permissions', async () => {+ it('silently upgrades plugins whose market manifest expands capabilities', async () => {const item = summary({scope: 'organization',organizationId: 'org-1',@@ -2127,6 +2045,7 @@ describe('PluginMarketService migration and defaultInstall', () => {...item,currentRelease: { ...item.currentRelease, manifest: expanded },} as never);+ runtime.inspectedManifest = expanded;const upgraded = manifest(item.ghostId, '2.0.0', ['notify', 'fs']);runtime.install.mockImplementationOnce(async () => {@@ -2137,15 +2056,9 @@ describe('PluginMarketService migration and defaultInstall', () => {items: [{ installState: 'installed', version: '2.0.0' }],});expect(runtime.install).toHaveBeenCalledTimes(1);- expect(h.service.consumeUpgradeNotice()).toEqual({- count: 1,- name: 'Test Plugin',- permissions: [{ key: 'fs', labelKey: 'fsWrite' }],- hasPermissionExpansion: true,- });});- it('skips organization upgrades when the downloaded package drifts to extra permissions', async () => {+ it('backs off a failed automatic release and retries a newer release immediately', async () => {const item = summary({scope: 'organization',organizationId: 'org-1',@@ -2165,27 +2078,33 @@ describe('PluginMarketService migration and defaultInstall', () => {manifestDigest: ghostManifestDigest(oldManifest),});runtime.install.mockRejectedValueOnce(- new GhostPackagePermissionReviewRequiredError({- manifest: manifest(item.ghostId, '2.0.0', ['notify', 'fs']),- permissionDiff: diffGhostPermissionItems(- oldManifest,- manifest(item.ghostId, '2.0.0', ['notify', 'fs']),- ),- isUpdate: true,- packageSha256: item.currentRelease.sha256,- installedBaseline: ghostPermissionBaselineKey(oldManifest),- sourceType: 'server',+ Object.assign(new Error('package capabilities exceed market manifest'), {+ code: 'GHOST_FILE_INVALID',}),);+ await expect(h.service.snapshot()).resolves.toMatchObject({+ items: [{ installState: 'update-available' }],+ });await expect(h.service.snapshot()).resolves.toMatchObject({items: [{ installState: 'update-available' }],});expect(runtime.install).toHaveBeenCalledTimes(1);- expect(h.service.consumeUpgradeNotice()).toBeNull();++ Object.assign(item.currentRelease, { id: 'release-3', version: '3.0.0' });+ const upgraded = manifest(item.ghostId, '3.0.0');+ runtime.install.mockImplementationOnce(async () => {+ const ghost = { manifest: upgraded, dir: installDir, enabled: true };+ runtime.ghosts = [ghost];+ return ghost;+ });+ await expect(h.service.snapshot()).resolves.toMatchObject({+ items: [{ installState: 'installed', version: '3.0.0' }],+ });+ expect(runtime.install).toHaveBeenCalledTimes(2);});- it('abandons a silent upgrade before download when the installed permission baseline changes', async () => {+ it('abandons a silent upgrade before download when the installed route digest changes', async () => {const item = summary({scope: 'organization',organizationId: 'org-1',@@ -2219,10 +2138,9 @@ describe('PluginMarketService migration and defaultInstall', () => {items: [{ installState: 'conflict' }],});expect(runtime.install).not.toHaveBeenCalled();- expect(h.service.consumeUpgradeNotice()).toBeNull();});- it('abandons a silent upgrade when the installed permission baseline changes during download', async () => {+ it('abandons a silent upgrade when the installed route digest changes during download', async () => {const item = summary({scope: 'organization',organizationId: 'org-1',@@ -2265,7 +2183,6 @@ describe('PluginMarketService migration and defaultInstall', () => {items: [{ installState: 'conflict' }],});expect(runtime.install).not.toHaveBeenCalled();- expect(h.service.consumeUpgradeNotice()).toBeNull();});it.each(['pendingCalls', 'runningErrand', 'cindyWork'] as const)(@@ -2301,16 +2218,10 @@ describe('PluginMarketService migration and defaultInstall', () => {runtime[signal] = false;await h.service.snapshot();expect(runtime.install).toHaveBeenCalledTimes(1);- expect(h.service.consumeUpgradeNotice()).toEqual({- count: 1,- name: 'Test Plugin',- permissions: null,- hasPermissionExpansion: false,- });},);- it('skips organization upgrades that require a newer Cindy version', async () => {+ it('does not re-check the server-selected organization upgrade against the client version', async () => {const item = summary({scope: 'organization',organizationId: 'org-1',@@ -2334,11 +2245,14 @@ describe('PluginMarketService migration and defaultInstall', () => {...item,currentRelease: { ...item.currentRelease, manifest: incompatible },} as never);-- await expect(h.service.snapshot()).resolves.toMatchObject({- items: [{ installState: 'update-available' }],+ runtime.inspectedManifest = incompatible;+ runtime.install.mockImplementation(async () => {+ runtime.ghosts = [{ manifest: incompatible, dir: installDir, enabled: true }];+ return runtime.ghosts[0];});- expect(runtime.install).not.toHaveBeenCalled();++ await h.service.snapshot();+ expect(runtime.install).toHaveBeenCalledTimes(1);});it('continues upgrading other organization plugins when one upgrade fails', async () => {@@ -2398,15 +2312,9 @@ describe('PluginMarketService migration and defaultInstall', () => {await expect(h.service.snapshot()).resolves.toMatchObject({ unavailableReason: null });expect(runtime.install).toHaveBeenCalledTimes(2);- expect(h.service.consumeUpgradeNotice()).toEqual({- count: 1,- name: 'Second Plugin',- permissions: null,- hasPermissionExpansion: false,- });});- it('does not silently update public or non-defaultInstall plugins', async () => {+ it('silently updates public and non-defaultInstall plugins from their recorded source', async () => {const publicItem = summary({defaultInstall: true,currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },@@ -2443,13 +2351,19 @@ describe('PluginMarketService migration and defaultInstall', () => {version: '1.0.0',manifestDigest: ghostManifestDigest(secondManifest),});+ runtime.install.mockImplementation(async (_file, expected) => {+ const dir = expected.ghostId === publicItem.ghostId ? firstDir : secondDir;+ const upgraded = manifest(expected.ghostId, '2.0.0');+ const ghost = { manifest: upgraded, dir, enabled: true };+ runtime.ghosts = runtime.ghosts.map((candidate) =>+ candidate.manifest.id === expected.ghostId ? ghost : candidate,+ );+ return ghost;+ });const snapshot = await h.service.snapshot();- expect(runtime.install).not.toHaveBeenCalled();- expect(snapshot.items.map((entry) => entry.installState)).toEqual([- 'update-available',- 'update-available',- ]);+ expect(runtime.install).toHaveBeenCalledTimes(2);+ expect(snapshot.items.map((entry) => entry.installState)).toEqual(['installed', 'installed']);});it('rejects a no-port broker auto-upgrade without disturbing the installed legacy version', async () => {@@ -2487,119 +2401,6 @@ describe('PluginMarketService migration and defaultInstall', () => {expect(runtime.install).not.toHaveBeenCalled();});- it('aggregates upgrade notices and filters directional controls from a single name', async () => {- const item = summary({- scope: 'organization',- organizationId: 'org-1',- defaultInstall: true,- currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },- });- const oldManifest = manifest(item.ghostId, '1.0.0');- const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-upgrade-'));- roots.push(installDir);- fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(oldManifest));- runtime.ghosts = [{ manifest: oldManifest, dir: installDir, enabled: true }];- const h = harness([item]);- h.ledger.upsertInstallation({- ...recordForTest(item),- releaseId: 'release-1',- version: '1.0.0',- manifestDigest: ghostManifestDigest(oldManifest),- });- const upgraded = { ...manifest(item.ghostId, '2.0.0'), name: '\u202eSecret Plugin' };- h.api.detail.mockResolvedValueOnce({- ...item,- currentRelease: { ...item.currentRelease, manifest: upgraded },- } as never);- runtime.install.mockResolvedValueOnce({ manifest: upgraded, dir: installDir, enabled: true });-- await h.service.snapshot();- expect(h.service.consumeUpgradeNotice()).toEqual({- count: 1,- name: 'Secret Plugin',- permissions: null,- hasPermissionExpansion: false,- });- expect(h.service.consumeUpgradeNotice()).toBeNull();- });-- it('aggregates multiple upgrades and flags permission expansion without listing names', async () => {- const first = summary({- scope: 'organization',- organizationId: 'org-1',- defaultInstall: true,- currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },- });- const second = summary({- id: `c${'b'.repeat(24)}`,- ghostId: 'cindy-second',- name: 'Second Plugin',- scope: 'organization',- organizationId: 'org-1',- defaultInstall: true,- currentRelease: { ...summary().currentRelease, id: 'release-2b', version: '2.0.0' },- });- const firstDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-upgrade-'));- const secondDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-upgrade-'));- roots.push(firstDir, secondDir);- const firstManifest = manifest(first.ghostId, '1.0.0');- const secondManifest = manifest(second.ghostId, '1.0.0');- fs.writeFileSync(path.join(firstDir, 'ghost.json'), JSON.stringify(firstManifest));- fs.writeFileSync(path.join(secondDir, 'ghost.json'), JSON.stringify(secondManifest));- runtime.ghosts = [- { manifest: firstManifest, dir: firstDir, enabled: true },- { manifest: secondManifest, dir: secondDir, enabled: true },- ];- const h = harness([first, second]);- h.ledger.upsertInstallation({- ...recordForTest(first),- releaseId: 'release-1',- version: '1.0.0',- manifestDigest: ghostManifestDigest(firstManifest),- });- h.ledger.upsertInstallation({- ...recordForTest(second),- releaseId: 'release-1b',- version: '1.0.0',- manifestDigest: ghostManifestDigest(secondManifest),- });- h.api.detail.mockImplementation(async (id) => {- const plugin = id === first.id ? first : second;- const nextManifest =- id === first.id- ? manifest(plugin.ghostId, '2.0.0', ['notify', 'fs'])- : manifest(plugin.ghostId, '2.0.0');- return {- ...plugin,- currentRelease: { ...plugin.currentRelease, manifest: nextManifest },- } as never;- });- runtime.install.mockImplementation(async (_file, expected) => {- const dir = expected.ghostId === first.ghostId ? firstDir : secondDir;- const upgraded = {- ...manifest(- expected.ghostId,- '2.0.0',- expected.ghostId === first.ghostId ? ['notify', 'fs'] : ['notify'],- ),- name: expected.ghostId === second.ghostId ? 'Second Plugin' : 'Test Plugin',- };- const ghost = { manifest: upgraded, dir, enabled: true };- runtime.ghosts = runtime.ghosts.map((candidate) =>- candidate.manifest.id === expected.ghostId ? ghost : candidate,- );- return ghost;- });-- await h.service.snapshot();- expect(h.service.consumeUpgradeNotice()).toEqual({- count: 2,- name: null,- permissions: null,- hasPermissionExpansion: true,- });- });-it('installs a public market plugin in account-free local mode', async () => {runtime.session = {mode: 'local',@@ -3166,7 +2967,9 @@ describe('PluginMarketService migration and defaultInstall', () => {).resolves.toMatchObject({ghost: { manifest: { id: item.ghostId } },});- expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty('permissionBaselineManifest');+ expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({+ manifestCap: manifest(),+ });expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({pluginId: item.id,source: 'market',@@ -3200,260 +3003,7 @@ describe('PluginMarketService migration and defaultInstall', () => {expect(h.ledger.installationForGhost(item.ghostId)).toBeNull();});- it('continues the same update transaction after real-package approval', async () => {- const item = summary({- currentRelease: {- ...summary().currentRelease,- id: 'release-2',- version: '2.0.0',- },- });- runtime.ghosts = [- {- manifest: manifest(),- dir: '/userData/cindy-brain/cindy-test',- enabled: true,- },- ];- const targetManifest = manifest('cindy-test', '2.0.0', ['notify', 'fs']);- const review = {- manifest: targetManifest,- permissionDiff: diffGhostPermissionItems(manifest(), targetManifest),- isUpdate: true,- packageSha256: 'a'.repeat(64),- installedBaseline: ghostPermissionBaselineKey(manifest()),- sourceType: 'server' as const,- };- runtime.install- .mockRejectedValueOnce(new GhostPackagePermissionReviewRequiredError(review))- .mockResolvedValueOnce({- manifest: review.manifest,- dir: '/userData/cindy-brain/cindy-test',- enabled: true,- });- const h = harness([item]);- h.ledger.upsertInstallation({- ...recordForTest(item),- releaseId: 'release-1',- version: '1.0.0',- });- await expect(h.service.install(item.id, reviewedInstallOptions(item))).rejects.toThrow(- '[PRECONDITION_FAILED]',- );- expect(runtime.install).not.toHaveBeenCalled();-- const confirmReview = vi.fn(async () => true);- await expect(- h.service.install(- item.id,- {- ...reviewedInstallOptions(item),- expectedInstalledApproval: APPROVED_INSTALL_TOKEN,- },- confirmReview,- ),- ).resolves.toMatchObject({- ghost: { manifest: { version: '2.0.0' } },- });- expect(confirmReview).toHaveBeenCalledWith(review);- expect(h.api.download).toHaveBeenCalledTimes(1);- expect(runtime.install).toHaveBeenCalledTimes(2);- });-- it.each(['legacy-unapproved', 'invalid'] as const)(- 'requires a full Host-side review before a %s install can be re-approved',- async (approvalState) => {- const item = summary({- currentRelease: {- ...summary().currentRelease,- id: 'release-2',- version: '2.0.0',- },- });- const installedManifest = manifest('cindy-test', '1.0.0', ['notify']);- const installedDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-installed-ghost-'));- roots.push(installedDir);- fs.writeFileSync(path.join(installedDir, 'ghost.json'), JSON.stringify(installedManifest));- runtime.ghosts = [- {- manifest: installedManifest,- dir: installedDir,- enabled: true,- approval: { state: approvalState },- },- ];- runtime.install.mockResolvedValue({- manifest: manifest('cindy-test', '2.0.0', ['notify']),- dir: '/userData/cindy-brain/cindy-test',- enabled: true,- });- const h = harness([item]);- h.ledger.upsertInstallation({- ...recordForTest(item),- releaseId: 'release-1',- version: '1.0.0',- manifestDigest: ghostManifestDigest(installedManifest),- });- h.api.detail.mockResolvedValue(detail(item, ['notify']));-- await expect(- h.service.install(item.id, {- ...reviewedInstallOptions(item),- expectedInstalledApproval: approvalState,- }),- ).rejects.toThrow('[PRECONDITION_FAILED]');- expect(runtime.install).not.toHaveBeenCalled();-- await expect(- h.service.install(item.id, {- ...reviewedInstallOptions(item),- expectedInstalledApproval: approvalState,- allowPermissionExpansion: true,- reviewedBaseline: ghostPermissionBaselineKey(installedManifest),- }),- ).resolves.toMatchObject({ ghost: { manifest: { version: '2.0.0' } } });- expect(runtime.install).toHaveBeenCalledWith(- expect.any(String),- expect.objectContaining({ expectedInstalledApproval: approvalState }),- );- expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty('permissionBaselineManifest');- },- );-- it('re-checks the reviewed baseline inside the install lock before honouring an expansion', async () => {- const item = summary({- currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },- });- const reviewedInstalled = manifest('cindy-test', '1.0.0', ['notify', 'fs']);- const targetManifest = manifest('cindy-test', '2.0.0', ['notify', 'fs']);- runtime.ghosts = [- {- manifest: manifest(),- dir: '/userData/cindy-brain/cindy-test',- enabled: true,- },- ];- runtime.install.mockResolvedValue({- manifest: targetManifest,- dir: '/userData/cindy-brain/cindy-test',- enabled: true,- });- const h = harness([item]);- h.ledger.upsertInstallation({- ...recordForTest(item),- releaseId: 'release-1',- version: '1.0.0',- });- h.api.detail.mockResolvedValue(detail(item, ['notify', 'fs']));- const options = {- ...reviewedInstallOptions(item),- expectedManifest: targetManifest,- expectedInstalledApproval: APPROVED_INSTALL_TOKEN,- allowPermissionExpansion: true,- };-- await expect(- h.service.install(item.id, {- ...options,- reviewedBaseline: ghostPermissionBaselineKey(reviewedInstalled),- }),- ).rejects.toThrow('[PRECONDITION_FAILED]');- expect(runtime.install).not.toHaveBeenCalled();-- await expect(- h.service.install(item.id, {- ...options,- reviewedBaseline: ghostPermissionBaselineKey(manifest()),- }),- ).resolves.toMatchObject({ ghost: { manifest: { version: '2.0.0' } } });- expect(runtime.install).toHaveBeenCalledTimes(1);- });-- it('re-checks the baseline inside the install lock when the download window is raced', async () => {- const item = summary({- currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },- });- const reviewedInstalled = manifest('cindy-test', '1.0.0', ['notify', 'fs']);- const targetManifest = manifest('cindy-test', '2.0.0', ['notify', 'fs']);- runtime.ghosts = [- { manifest: reviewedInstalled, dir: '/userData/cindy-brain/cindy-test', enabled: true },- ];- runtime.install.mockResolvedValue({- manifest: targetManifest,- dir: '/userData/cindy-brain/cindy-test',- enabled: true,- });- const downloadMock = vi.mocked((await import('../download.js')).downloadVerifiedPlugin);- downloadMock.mockImplementationOnce(async () => {- runtime.ghosts = [- { manifest: manifest(), dir: '/userData/cindy-brain/cindy-test', enabled: true },- ];- });- const h = harness([item]);- h.ledger.upsertInstallation({- ...recordForTest(item),- releaseId: 'release-1',- version: '1.0.0',- });- h.api.detail.mockResolvedValue(detail(item, ['notify', 'fs']));-- await expect(- h.service.install(item.id, {- ...reviewedInstallOptions(item),- expectedManifest: targetManifest,- expectedInstalledApproval: APPROVED_INSTALL_TOKEN,- allowPermissionExpansion: true,- reviewedBaseline: ghostPermissionBaselineKey(reviewedInstalled),- }),- ).rejects.toThrow('[PRECONDITION_FAILED]');- expect(runtime.install).not.toHaveBeenCalled();- });-- it('cancels the current transaction when real-package approval is declined', async () => {- const item = summary({- currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },- });- runtime.ghosts = [- {- manifest: manifest(),- dir: '/userData/cindy-brain/cindy-test',- enabled: true,- },- ];- const review = {- manifest: manifest('cindy-test', '2.0.0', ['notify', 'fs']),- permissionDiff: diffGhostPermissionItems(- manifest(),- manifest('cindy-test', '2.0.0', ['notify', 'fs']),- ),- isUpdate: true,- packageSha256: 'a'.repeat(64),- installedBaseline: ghostPermissionBaselineKey(manifest()),- sourceType: 'server' as const,- };- runtime.install.mockRejectedValueOnce(new GhostPackagePermissionReviewRequiredError(review));- const h = harness([item]);- h.ledger.upsertInstallation({- ...recordForTest(item),- releaseId: 'release-1',- version: '1.0.0',- });-- await expect(- h.service.install(- item.id,- {- ...reviewedInstallOptions(item),- expectedInstalledApproval: APPROVED_INSTALL_TOKEN,- },- async () => false,- ),- ).resolves.toEqual({ cancelled: true });- expect(h.api.download).toHaveBeenCalledTimes(1);- expect(runtime.install).toHaveBeenCalledTimes(1);- });-- it('rejects a stale installed manifest as the permission baseline after download when the ledger digest no longer matches', async () => {+ it('keeps the selected release manifest as the cap when the installed snapshot changes', async () => {const item = summary({currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },});@@ -3482,19 +3032,19 @@ describe('PluginMarketService migration and defaultInstall', () => {releaseId: 'release-1',version: '1.0.0',});- // 下载窗口期目标包相对"当前实际已装"多出 fs,且这条基线在本次安装前从没被- // 审阅过:合并后的 Main 侧扩权闸要求显式 allowPermissionExpansion 才放行,- // 同时权限基线必须取下载后重读的真实运行包(不是审阅时刻的 runtime manifest)。+ // 下载窗口期目标包相对“当前实际已装”多出 fs;安装事务仍以选中 release 的+ // manifest 为能力上限,不再为能力变化增加另一层用户审批。await expect(h.service.install(item.id, {...reviewedInstallOptions(item),expectedInstalledApproval: APPROVED_INSTALL_TOKEN,- allowPermissionExpansion: true,}),).resolves.toMatchObject({ghost: { manifest: { version: '2.0.0' } },});- expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty('permissionBaselineManifest');+ expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({+ manifestCap: manifest('cindy-test', '2.0.0'),+ });});it('rejects an update when the installed target disappears during download', async () => {@@ -3571,7 +3121,7 @@ describe('PluginMarketService migration and defaultInstall', () => {expect(runtime.install).not.toHaveBeenCalled();});- it('rejects when the market release changes after renderer review', async () => {+ it('rejects when the market release changes after renderer selection', async () => {const reviewed = summary();const replacement = summary({currentRelease: {diff --git a/apps/desktop/src/main/plugin-market/install.ts b/apps/desktop/src/main/plugin-market/install.tsindex e5d14cd445..40b6fe0953 100644--- a/apps/desktop/src/main/plugin-market/install.ts+++ b/apps/desktop/src/main/plugin-market/install.ts@@ -15,19 +15,17 @@ import crypto from 'node:crypto';import { app } from 'electron';import {+ unreviewedGhostPermissionItems,validateGhostManifest,type GhostManifest,type InstalledGhost,} from '../../shared/ghost.js';-import type {- PluginMarketItemSource,- PluginMarketPackageReviewFacts,-} from '../../shared/pluginMarket.js';import {+ getGhostManager,installOrUpdateMarketGhostPackage,rejectReservedGhostIdForCustomMarket,} from '../cindy-brain/index.js';-import { GhostPackagePermissionReviewRequiredError } from '../cindy-brain/packagePermissionReview.js';+import type { PluginMarketInstallResult } from '../../shared/pluginMarket.js';import { packGhostDirToFile } from '../cindy-brain/forge.js';import { createLogger } from '../logger.js';import { isIpcError } from '../../shared/ipc-errors.js';@@ -41,8 +39,8 @@ import {/*** 把插件目录装成运行中的 Ghost。*- * Renderer 不再批准发现阶段的目录 manifest。这里先安全打包,再让 Main- * 从实际 `.cindy` 解析 canonical manifest;确认和落位始终绑定同一个临时包。+ * 这里先安全打包,再让 Main 从实际 `.cindy` 解析 canonical manifest;+ * 校验和落位始终绑定同一个临时包。*/const log = createLogger('plugin-market-install');@@ -59,19 +57,14 @@ function sanitizeInstallDetail(message: string): string {export async function installCustomMarketPlugin(input: {pluginDir: string;expected?: GhostManifest;- /** 更新时把审阅所绑定的 Host receipt token 贯穿到最终安装出口。 */+ /** 更新时把发起操作时读取的 Host receipt token 贯穿到最终安装出口。 */expectedInstalledApproval?: string;expectedGhostId: string;expectedVersion: string;- sourceType: Extract<PluginMarketItemSource, 'git-market' | 'local-market'>;- permissionBaselineManifest?: PluginMarketPackageReviewFacts['manifest'];- reviewPackagePermissions?: (- facts: PluginMarketPackageReviewFacts,- ) => Promise<boolean>;/*** 打包完成后、实际改动 Ghost 运行时之前调用的校验钩(可异步)。- * 自定义市场按调用方捕获的账户审阅 manifest;打包是异步的,装出前必须- * 重新确认会话未漂移,避免把 A 审阅的插件装进当前账户 B 的运行时。+ * 调用方按当前账户捕获市场 manifest;打包是异步的,装出前必须重新确认+ * 会话未漂移,避免把账户 A 选择的插件装进当前账户 B 的运行时。* 这里同时复核当前账号、所选来源和运行时已安装插件事实。*/beforeCommit?: () => void | Promise<void>;@@ -97,9 +90,9 @@ export async function installCustomMarketPlugin(input: {*/afterCommit?: (installed: InstalledGhost,- packagedManifest: PluginMarketPackageReviewFacts['manifest'],+ packagedManifest: GhostManifest,) => Promise<void>;-}): Promise<InstalledGhost | null> {+}): Promise<PluginMarketInstallResult> {// input.pluginDir 是发现层已 realpath、且已校验落在市场根内的规范路径。// 发现之后、打包之前,若插件目录或其某个父目录被换成指向市场外的符号链接,// 重新 realpath 会解析到别处——只要外部目录留着同样的 ghost.json,清单摘要@@ -176,27 +169,39 @@ export async function installCustomMarketPlugin(input: {);}// 唯一防篡改防线:比对实际打进包的 manifest,而非打包前磁盘上的 ghost.json。- // 堵住"前置比对通过后、打包读取文件前"目录被改(保持 id/version 却新增- // 权限声明)的窗口——装的就是 packed.manifest,必须以它为准。- // expected 只在校验流程显式提供了用户审阅过的清单时做防篡改比对;- // 来源隔离路径(permissionPolicy)由 expectedGhostId/expectedVersion +- // permissionBaselineManifest 在装出前复核。+ // 堵住前置比对通过后目录被改的窗口;expected 存在时还要与调用方选中的+ // 市场条目完全一致。if (input.expected !== undefined &&JSON.stringify(packed.manifest) !== JSON.stringify(input.expected)) {throwIpcError('PRECONDITION_FAILED',- 'Plugin changed after permission review',+ 'Plugin changed after selection',);}- const permissionPolicy = { mode: 'manual' as const, sourceType: input.sourceType };- // 装出前最后防线:打包期间账号、所选来源或运行时插件状态都可能已变化。- // 复核与落位必须在同一把锁内完成,否则复核结论会在落位前过期。- const commit = async (- approval?: Pick<PluginMarketPackageReviewFacts, 'packageSha256' | 'installedBaseline'>,- ): Promise<InstalledGhost> => {- const run = async (): Promise<InstalledGhost> => {+ const inspected = await getGhostManager().inspect(tempPath);+ if (!('rejection' in inspected)) {+ if (+ inspected.canonicalManifest.id !== input.expectedGhostId ||+ inspected.canonicalManifest.version !== input.expectedVersion+ ) {+ throwIpcError('GHOST_FILE_INVALID', 'The packaged Plugin identity changed');+ }+ const extraCapabilities = unreviewedGhostPermissionItems(+ validated.manifest,+ undefined,+ inspected.canonicalManifest,+ );+ if (extraCapabilities.length > 0) {+ throwIpcError(+ 'GHOST_FILE_INVALID',+ 'The packaged Plugin capabilities exceed the selected market manifest',+ );+ }+ }+ const commit = async (): Promise<PluginMarketInstallResult> => {+ const run = async (): Promise<PluginMarketInstallResult> => {await input.beforeCommit?.();// 自定义来源已经把 Renderer 审阅的本地清单与实际打包清单逐字节绑定,// 不再进入官方市场“下载真实包后复核”的分支。@@ -205,22 +210,12 @@ export async function installCustomMarketPlugin(input: {// 打包前活目录里的值,否则目录在打包窗口变化时会把另一个插件装入。ghostId: input.expectedGhostId,version: input.expectedVersion,- permissionPolicy,- ...(input.permissionBaselineManifest- ? { permissionBaselineManifest: input.permissionBaselineManifest }- : {}),- ...(input.expected ? { reviewedManifest: input.expected } : {}),+ // 发现时读到的规范化 Manifest 是这次安装允许的能力上限。打包窗口+ // 中目录若发生能力扩张,Host 会按真实包不一致直接拒绝。+ manifestCap: validated.manifest,...(input.expectedInstalledApproval? { expectedInstalledApproval: input.expectedInstalledApproval }: {}),- ...(approval- ? {- approvedPackageSha256: approval.packageSha256,- ...(approval.installedBaseline !== null- ? { reviewedBaseline: approval.installedBaseline }- : {}),- }- : {}),...(input.beforePackagePlacement? { beforeCommitInLock: input.beforePackagePlacement }: {}),@@ -230,25 +225,11 @@ export async function installCustomMarketPlugin(input: {});// 溯源写入与落位同锁(见 afterCommit 注释)。await input.afterCommit?.(installed, packed.manifest);- return installed;+ return { ghost: installed };};return input.withCommitLock ? input.withCommitLock(run) : run();};-- let review: PluginMarketPackageReviewFacts;- try {- // 首装或扩权会在任何运行时写入前暂停;无扩权更新则在同一锁内直接落位。- return await commit();- } catch (error) {- if (!(error instanceof GhostPackagePermissionReviewRequiredError)) throw error;- review = error.review;- }- const approved = await input.reviewPackagePermissions?.(review);- if (approved !== true) return null;-- // 确认返回后重新取得来源/ghost 锁,复核来源、当前安装基线与真实包 SHA。- // 确认期间不持锁,取消或窗口销毁可立即结束并清理临时包。- return await commit(review);+ return await commit();} finally {await fs.promises.rm(tempPath, { force: true }).catch(() => undefined);}diff --git a/apps/desktop/src/main/plugin-market/packagePermissionReviewBridge.ts b/apps/desktop/src/main/plugin-market/packagePermissionReviewBridge.tsdeleted file mode 100644index 126ce60947..0000000000--- a/apps/desktop/src/main/plugin-market/packagePermissionReviewBridge.ts+++ /dev/null@@ -1,70 +0,0 @@-/**- * 市场真实包权限确认的 Main ↔ Renderer 往返桥。- *- * 它只保存“当前窗口对当前弹框的回答”,不保存包路径、安装状态或批准记录。- * 安装事务本身仍停在 service.install() 的调用栈里;确认、取消或窗口销毁后,- * promise 立即结算,service 的 finally 负责删除临时包。- */--import { randomUUID } from 'node:crypto';--import type {- PluginMarketPackageReviewFacts,- PluginMarketPackageReviewRequest,-} from '../../shared/pluginMarket.js';-import type { DataOwnerPushStamp } from '../../shared/dataOwnerPush.js';--interface PendingReview {- requesterId: number;- resolve: (confirmed: boolean) => void;-}--export class PluginMarketPackagePermissionReviewBridge {- private readonly pending = new Map<string, PendingReview>();-- request(- requesterId: number,- facts: PluginMarketPackageReviewFacts,- ownerStamp: DataOwnerPushStamp,- send: (request: PluginMarketPackageReviewRequest) => boolean,- ): Promise<boolean> {- const requestId = randomUUID();- return new Promise<boolean>((resolve) => {- this.pending.set(requestId, { requesterId, resolve });- let delivered = false;- try {- delivered = send({- requestId,- ownerStamp,- manifest: facts.manifest,- permissionDiff: facts.permissionDiff,- isUpdate: facts.isUpdate,- sourceType: facts.sourceType,- builtinOauthClientChanged: facts.builtinOauthClientChanged,- });- } finally {- if (!delivered) this.settle(requestId, false);- }- });- }-- resolve(requesterId: number, requestId: string, confirmed: unknown): boolean {- const pending = this.pending.get(requestId);- if (!pending || pending.requesterId !== requesterId) return false;- this.settle(requestId, confirmed === true);- return true;- }-- cancelRequester(requesterId: number): void {- for (const [requestId, pending] of this.pending) {- if (pending.requesterId === requesterId) this.settle(requestId, false);- }- }-- private settle(requestId: string, confirmed: boolean): void {- const pending = this.pending.get(requestId);- if (!pending) return;- this.pending.delete(requestId);- pending.resolve(confirmed);- }-}diff --git a/apps/desktop/src/main/plugin-market/registerIpc.ts b/apps/desktop/src/main/plugin-market/registerIpc.tsindex f8f98c8611..3a4d26bb77 100644--- a/apps/desktop/src/main/plugin-market/registerIpc.ts+++ b/apps/desktop/src/main/plugin-market/registerIpc.ts@@ -1,14 +1,16 @@import os from 'node:os';-import { ipcMain, type WebContents } from 'electron';+import { ipcMain } from 'electron';import { isIpcError } from '../../shared/ipc-errors.js';-import { isGhostInstallApprovalToken, type GhostManifest } from '../../shared/ghost.js';+import {+ isGhostInstallApprovalToken,+ type GhostManifest,+} from '../../shared/ghost.js';import {isPluginMarketCustomIconKey,type PluginMarketSnapshot,} from '../../shared/pluginMarket.js';-import { getActiveDataOwnerPushStamp } from '../appSessionState.js';import {sendToTrustedAppWindows,setGhostUninstallLedgerPreparer,@@ -18,7 +20,6 @@ import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.jsimport { requireObject, requireString, throwIpcError } from '../utils/ipcValidate.js';import { parseMarketSource } from './sources/parse.js';import { LocalIconRequestGate } from './localIconRequestGate.js';-import { PluginMarketPackagePermissionReviewBridge } from './packagePermissionReviewBridge.js';import {PluginMarketService,type PluginMarketSnapshotOptions,@@ -28,10 +29,6 @@ const log = createLogger('plugin-market-ipc');let registered = false;let serviceSingleton: PluginMarketService | null = null;const REMOVAL_NOTICE_AVAILABLE_CHANNEL = 'plugin-market:removal-notice-available';-const UPGRADE_NOTICE_AVAILABLE_CHANNEL = 'plugin-market:upgrade-notice-available';-const PACKAGE_PERMISSION_REVIEW_CHANNEL = 'plugin-market:package-permission-review';-const trackedReviewRequesters = new WeakSet<WebContents>();-const packagePermissionReviewBridge = new PluginMarketPackagePermissionReviewBridge();const localIconRequestGate = new LocalIconRequestGate();function service(): PluginMarketService {@@ -44,11 +41,6 @@ function signalRemovalNoticeAvailable(): void {sendToTrustedAppWindows(REMOVAL_NOTICE_AVAILABLE_CHANNEL, undefined);}-function signalUpgradeNoticeAvailable(): void {- if (!service().hasPendingUpgradeNotice()) return;- sendToTrustedAppWindows(UPGRADE_NOTICE_AVAILABLE_CHANNEL, undefined);-}-async function snapshotAndSignalRemovalNotice(options?: PluginMarketSnapshotOptions) {try {return await service().snapshot(options);@@ -56,14 +48,13 @@ async function snapshotAndSignalRemovalNotice(options?: PluginMarketSnapshotOpti// 清理已成功但后续默认安装等步骤失败时,pending 仍必须通知 Renderer;// snapshot 的原始异常继续向上抛,不把通知信号伪装成整轮成功。signalRemovalNoticeAvailable();- signalUpgradeNoticeAvailable();}}/*** Reuse the market snapshot reconciliation outside the Plugins page so- * default-install plugins are provisioned as soon as an app owner is ready.- * The Plugins page keeps the same call as a later retry path.+ * default-install plugins are provisioned and stable-source updates are applied+ * as soon as an app owner is ready. The Plugins page remains a later retry path.*/export type DefaultMarketPluginSyncOutcome = 'completed' | 'deferred' | 'failed';@@ -105,7 +96,7 @@ export async function syncDefaultMarketPlugins(): Promise<DefaultMarketPluginSyn}return outcome;} catch (error) {- log.warn('default plugin startup sync failed', {+ log.warn('Plugin market background sync failed', {error: error instanceof Error ? error.message : String(error),});return 'failed';@@ -129,21 +120,6 @@ async function invokePluginMarket<T>(operation: () => Promise<T>): Promise<T> {}}-function trackPackageReviewRequester(contents: WebContents): void {- if (trackedReviewRequesters.has(contents)) return;- trackedReviewRequesters.add(contents);- const requesterId = contents.id;- const cancelPending = () => packagePermissionReviewBridge.cancelRequester(requesterId);- contents.once('destroyed', cancelPending);- contents.on('render-process-gone', cancelPending);- contents.on(- 'did-start-navigation',- (_event, _url, isSameDocument, isMainFrame) => {- if (isMainFrame && !isSameDocument) cancelPending();- },- );-}-/** 注册 renderer 可用的只读市场与显式安装/卸载写路径。 */export function registerPluginMarketIpc(): void {if (registered) return;@@ -155,11 +131,7 @@ export function registerPluginMarketIpc(): void {assertTrustedAppRendererEvent(event);return invokePluginMarket(() =>snapshotAndSignalRemovalNotice({- deferDefaultReconciliation: true,- onDeferredReconciliationSettled: () => {- signalRemovalNoticeAvailable();- signalUpgradeNoticeAvailable();- },+ deferReconciliation: true,}),);});@@ -167,10 +139,6 @@ export function registerPluginMarketIpc(): void {assertTrustedAppRendererEvent(event);return invokePluginMarket(async () => service().consumeRemovalNotice());});- ipcMain.handle('plugin-market:consume-upgrade-notice', (event) => {- assertTrustedAppRendererEvent(event);- return invokePluginMarket(async () => service().consumeUpgradeNotice());- });ipcMain.handle('plugin-market:detail', (event, pluginId: unknown) => {assertTrustedAppRendererEvent(event);return invokePluginMarket(() =>@@ -203,20 +171,21 @@ export function registerPluginMarketIpc(): void {'plugin-market:install',(event, pluginId: unknown, options: unknown) => {assertTrustedAppRendererEvent(event);- trackPackageReviewRequester(event.sender);const obj =typeof options === 'object' && options !== null? (options as {expectedReleaseId?: unknown;expectedInstalledApproval?: unknown;expectedManifest?: unknown;- allowPermissionExpansion?: unknown;- reviewedBaseline?: unknown;allowSourceReplacement?: unknown;}): null;const expectedReleaseId = requireString(obj?.expectedReleaseId, 'expectedReleaseId');const expectedInstalledApproval = obj?.expectedInstalledApproval;+ const expectedManifest =+ obj?.expectedManifest === undefined+ ? undefined+ : (requireObject(obj.expectedManifest) as unknown as GhostManifest);if (expectedInstalledApproval !== undefined &&!isGhostInstallApprovalToken(expectedInstalledApproval)@@ -226,11 +195,6 @@ export function registerPluginMarketIpc(): void {'expectedInstalledApproval must come from ghosts:list',);}- const expectedManifest = requireObject(obj?.expectedManifest);- const allowPermissionExpansion = obj?.allowPermissionExpansion === true;- // 扩权批准的审阅基线:只收字符串,野值按缺席处理(缺席 = 保持旧行为)。- const reviewedBaseline =- typeof obj?.reviewedBaseline === 'string' ? obj.reviewedBaseline : undefined;const allowSourceReplacement = obj?.allowSourceReplacement;if (typeof allowSourceReplacement !== 'boolean') {throwIpcError('INVALID_PARAMS', 'allowSourceReplacement must be a boolean');@@ -240,44 +204,16 @@ export function registerPluginMarketIpc(): void {requireString(pluginId, 'pluginId'),{expectedReleaseId,- expectedManifest: expectedManifest as unknown as GhostManifest,...(expectedInstalledApproval !== undefined? { expectedInstalledApproval }: {}),- allowPermissionExpansion,- ...(reviewedBaseline !== undefined ? { reviewedBaseline } : {}),+ ...(expectedManifest !== undefined ? { expectedManifest } : {}),allowSourceReplacement,},- (facts) =>- packagePermissionReviewBridge.request(- event.sender.id,- facts,- getActiveDataOwnerPushStamp(),- (request) => {- if (event.sender.isDestroyed()) return false;- event.sender.send(PACKAGE_PERMISSION_REVIEW_CHANNEL, request);- return true;- },- ),),);},);- ipcMain.handle('plugin-market:resolve-package-permission-review', (event, raw: unknown) => {- assertTrustedAppRendererEvent(event);- const payload = requireObject(raw);- const requestId = requireString(payload.requestId, 'requestId');- if (requestId.length > 128) {- throwIpcError('INVALID_PARAMS', 'requestId is too long');- }- return {- handled: packagePermissionReviewBridge.resolve(- event.sender.id,- requestId,- payload.confirmed,- ),- };- });ipcMain.handle('plugin-market:uninstall', (event, pluginId: unknown) => {assertTrustedAppRendererEvent(event);return invokePluginMarket(() =>diff --git a/apps/desktop/src/main/plugin-market/service.ts b/apps/desktop/src/main/plugin-market/service.tsindex e3df0b4191..15a693e29a 100644--- a/apps/desktop/src/main/plugin-market/service.ts+++ b/apps/desktop/src/main/plugin-market/service.ts@@ -4,7 +4,6 @@ import crypto from 'node:crypto';import {isValidPluginResourceId,- supportsCindyVersion,type PluginCurrentOrganization,type PluginRemovalNotice,type VisiblePluginDetail,@@ -13,17 +12,14 @@ import {import { app, dialog } from 'electron';import {- diffGhostPermissionItems,- diffInstalledGhostPermissionItems,GHOST_ICON_MAX_BYTES,ghostInstallApprovalToken,- ghostPermissionBaselineKey,ghostIconMimeType,isSafeGhostRelativePath,isOfficialGhostId,isValidGhostId,+ unreviewedGhostPermissionItems,validateGhostManifest,- validateNormalizedGhostManifest,type GhostManifest,type InstalledGhost,} from '../../shared/ghost.js';@@ -37,11 +33,8 @@ import type {PluginMarketItem,PluginMarketLocalIconRequest,PluginMarketLocalIconResult,- PluginMarketPackageReviewFacts,PluginMarketSnapshot,PluginRemovalUserNotice,- PluginUpgradePermissionNotice,- PluginUpgradeUserNotice,} from '../../shared/pluginMarket.js';import {customMarketPluginId,@@ -80,7 +73,6 @@ import {import { readInstalledGhostManifest } from '../installedGhostManifest.js';import { withGhostInstallLock } from '../cindy-brain/ghostInstallLock.js';import { ghostBrokerRedirectPortInstallError } from '../cindy-brain/ghostBrokerRedirectPort.js';-import { GhostPackagePermissionReviewRequiredError } from '../cindy-brain/packagePermissionReview.js';import { PluginMarketApi } from './api.js';import { createOrganizationPrefixStore } from './organizationPrefixStore.js';import { downloadVerifiedPlugin } from './download.js';@@ -97,11 +89,8 @@ import { MarketSourceStore } from './sources/store.js';const log = createLogger('plugin-market');-type PackagePermissionReviewer = (facts: PluginMarketPackageReviewFacts) => Promise<boolean>;-class SilentUpgradeBusyError extends Error {}class SilentDefaultInstallCancelledError extends Error {}-class SilentUpgradeStaleBaselineError extends Error {}/*** 来源增删改的互斥键。自定义市场安装的提交段也要拿这把锁,保证所选来源从@@ -120,19 +109,8 @@ class SilentUpgradeStaleBaselineError extends Error {}const SOURCE_MUTATION_KEY = 'market-sources';const CUSTOM_ICON_PROJECTION_TOKEN_RE = /^[a-f0-9]{16}$/;const CUSTOM_MARKET_SNAPSHOT_TIMEOUT_MS = 3_000;--function assertReviewedBaselineFresh(- installed: GhostManifest,- reviewedBaseline: string | undefined,-): void {- if (reviewedBaseline === undefined) return;- if (ghostPermissionBaselineKey(installed) !== reviewedBaseline) {- throwIpcError(- 'PRECONDITION_FAILED',- 'Installed Plugin permissions changed after review; re-review required',- );- }-}+const AUTOMATIC_UPGRADE_RETRY_BASE_MS = 5 * 60 * 1_000;+const AUTOMATIC_UPGRADE_RETRY_MAX_MS = 6 * 60 * 60 * 1_000;function captureMarketOwner(): ActiveAppSession {const session = getActiveAppSession();@@ -268,8 +246,12 @@ function ghostIdCounts(plugins: readonly VisiblePluginSummary[]): Map<string, nureturn counts;}-function manifestSupportsCurrentCindy(manifest: GhostManifest): boolean {- return supportsCindyVersion(app.getVersion(), manifest.minCindyVersion);+function isGhostBusy(ghostId: string): boolean {+ return (+ hasPendingGhostCalls(ghostId) ||+ hasRunningGhostErrand(ghostId) ||+ hasRunningGhostCindyWork(ghostId)+ );}/** 自定义市场发现到的单个插件条目(快照投影的原料)。 */@@ -291,8 +273,8 @@ interface CustomMarketDiscoveryProgress {}export interface PluginMarketSnapshotOptions {- /** Renderer 目录请求先返回;默认安装/升级在同一 owner 上后台补做。 */- deferDefaultReconciliation?: boolean;+ /** Renderer 目录请求先返回;默认安装和稳定来源升级在同一 owner 上后台补做。 */+ deferReconciliation?: boolean;/** 延后对账完成(成功或失败)后通知 IPC 层刷新一次性提示。 */onDeferredReconciliationSettled?: () => void;/** Main-only completion signal; it is not part of the Renderer snapshot. */@@ -521,10 +503,6 @@ function removalNoticeKey(owner: ActiveAppSession): string {return `${owner.mode}:${owner.dataOwnerId}`;}-function upgradeNoticeKey(owner: ActiveAppSession): string {- return `${owner.mode}:${owner.dataOwnerId}`;-}-/*** Plugin 市场的 main 端协调器。远程不可用时不碰本地目录;安装写路径必须依次* 通过 protocol parser、下载大小/SHA 校验、Ghost runtime validator 和原子换目录。@@ -533,7 +511,14 @@ export class PluginMarketService {private readonly mutations = new Map<string, Promise<unknown>>();private ledgerMutation: Promise<void> = Promise.resolve();private readonly pendingRemovalNotices = new Map<string, PluginRemovalUserNotice>();- private readonly pendingUpgradeNotices = new Map<string, PluginUpgradeUserNotice>();+ /**+ * 自动更新失败只在当前进程内按 owner + 来源路由 + release 退避。新版 release+ * 立即解除,重启也自然清空;不新增持久队列或用户可配置状态。+ */+ private readonly automaticUpgradeRetries = new Map<+ string,+ { releaseKey: string; failures: number; retryAfter: number }+ >();/*** Renderer 把 customIconKey 当不可变缓存 generation。每次重新投影市场都换代,* 使低精度文件系统上的同长度、同 stat 原地改写也会在刷新后重新按需读取。@@ -552,6 +537,42 @@ export class PluginMarketService {),) {}+ private automaticUpgradeRetryKey(+ owner: ActiveAppSession,+ source: 'server' | 'custom',+ pluginId: string,+ ): string {+ return [owner.mode, owner.dataOwnerId, source, pluginId].join('\u0000');+ }++ private shouldDeferAutomaticUpgrade(retryKey: string, releaseKey: string): boolean {+ const state = this.automaticUpgradeRetries.get(retryKey);+ if (!state) return false;+ if (state.releaseKey !== releaseKey) {+ this.automaticUpgradeRetries.delete(retryKey);+ return false;+ }+ return Date.now() < state.retryAfter;+ }++ private recordAutomaticUpgradeFailure(retryKey: string, releaseKey: string) {+ const previous = this.automaticUpgradeRetries.get(retryKey);+ const failures = previous?.releaseKey === releaseKey ? previous.failures + 1 : 1;+ const delay = Math.min(+ AUTOMATIC_UPGRADE_RETRY_BASE_MS * 2 ** Math.min(failures - 1, 16),+ AUTOMATIC_UPGRADE_RETRY_MAX_MS,+ );+ const state = { releaseKey, failures, retryAfter: Date.now() + delay };+ this.automaticUpgradeRetries.set(retryKey, state);+ return state;+ }++ private clearAutomaticUpgradeFailure(retryKey: string, releaseKey: string): void {+ if (this.automaticUpgradeRetries.get(retryKey)?.releaseKey === releaseKey) {+ this.automaticUpgradeRetries.delete(retryKey);+ }+ }+async snapshot(options: PluginMarketSnapshotOptions = {}): Promise<PluginMarketSnapshot> {// 自定义市场项完全来自本地数据,不依赖服务端与登录态;服务端不可用时// 仍然返回,unavailableReason 只表达服务端部分的不可用。@@ -590,15 +611,50 @@ export class PluginMarketService {iconProjectionGeneration,customSourceNames,);- if (!getClientEndpoint('pluginApiBaseUrl')) {- const customDiscovery = await customDiscoveryPromise;+ const customOnlySnapshot = async (+ customDiscovery: CustomMarketDiscovery,+ unavailableReason: string | null,+ ): Promise<PluginMarketSnapshot> => {requireSameMarketOwner(owner);- return {- items: this.projectCustomItems(customDiscovery.entries),- unavailableReason: customSourceNames.length > 0 ? null : 'not-configured',+ const ledger = this.ledgerForOwner(owner);+ await this.ledgerMutation;+ const reconcileCustomUpdates = async (): Promise<'completed' | 'failed'> => {+ const completed = await this.applyAutomaticUpgrades(+ [],+ customDiscovery.entries,+ owner,+ ledger,+ );+ const outcome = completed ? 'completed' : 'failed';+ options.onDefaultReconciliationOutcome?.(outcome);+ return outcome;+ };+ if (!options.deferReconciliation) await reconcileCustomUpdates();+ requireSameMarketOwner(owner);+ const snapshot: PluginMarketSnapshot = {+ items: this.projectCustomItems(customDiscovery.entries, this.localInstallSnapshot(ledger)),+ unavailableReason,customSourceNames,unavailableCustomSourceNames: customDiscovery.unavailableSourceNames,};+ if (options.deferReconciliation) {+ void Promise.resolve()+ .then(reconcileCustomUpdates)+ .catch((error) => {+ log.warn('deferred custom Plugin update reconciliation failed', {+ error: error instanceof Error ? error.message : String(error),+ });+ })+ .finally(options.onDeferredReconciliationSettled);+ }+ return snapshot;+ };+ if (!getClientEndpoint('pluginApiBaseUrl')) {+ const customDiscovery = await customDiscoveryPromise;+ return customOnlySnapshot(+ customDiscovery,+ customSourceNames.length > 0 ? null : 'not-configured',+ );}let plugins: VisiblePluginSummary[];let removals: PluginRemovalNotice[];@@ -618,13 +674,10 @@ export class PluginMarketService {// 本函数捕获 owner 后的每个 return 出口都必须先过 generation 校验:// listAll 失败(常因切号)时,不能把按旧账号发现的自定义项返回给当前会话。customDiscovery = await customDiscoveryPromise;- requireSameMarketOwner(owner);- return {- items: this.projectCustomItems(customDiscovery.entries),- unavailableReason: error instanceof Error ? error.message : String(error),- customSourceNames,- unavailableCustomSourceNames: customDiscovery.unavailableSourceNames,- };+ return customOnlySnapshot(+ customDiscovery,+ error instanceof Error ? error.message : String(error),+ );}requireSameMarketOwner(owner);@@ -641,7 +694,7 @@ export class PluginMarketService {// before its ledger write. Wait for queued ledger mutations before deciding// whether a default plugin should be installed again.await this.ledgerMutation;- const reconcileDefaults = async (): Promise<'completed' | 'failed'> => {+ const reconcileMarketInstallations = async (): Promise<'completed' | 'failed'> => {// 自定义来源只影响自己的目录发现;暂时不可读的来源不能阻塞官方默认安装。// 已经落地的同 id 插件仍由 applyDefaultInstalls → installDetail 的本地事实检查保护。let completed = true;@@ -654,10 +707,12 @@ export class PluginMarketService {});}try {- if (!(await this.applyDefaultUpgrades(plugins, owner, ledger))) completed = false;+ if (!(await this.applyAutomaticUpgrades(plugins, customDiscovery.entries, owner, ledger))) {+ completed = false;+ }} catch (error) {completed = false;- log.warn('default plugin upgrade reconciliation failed', {+ log.warn('automatic plugin upgrade reconciliation failed', {error: error instanceof Error ? error.message : String(error),});}@@ -665,7 +720,7 @@ export class PluginMarketService {options.onDefaultReconciliationOutcome?.(outcome);return outcome;};- if (!options.deferDefaultReconciliation) await reconcileDefaults();+ if (!options.deferReconciliation) await reconcileMarketInstallations();requireSameMarketOwner(owner);const local = this.localInstallSnapshot(ledger);const serverItems = plugins.map((plugin) => this.toItem(plugin, local));@@ -679,12 +734,12 @@ export class PluginMarketService {customSourceNames,unavailableCustomSourceNames: customDiscovery.unavailableSourceNames,};- if (options.deferDefaultReconciliation) {+ if (options.deferReconciliation) {// 目录展示不等待默认插件下载;对账仍复用原有串行锁和 owner 校验。void Promise.resolve()- .then(reconcileDefaults)+ .then(reconcileMarketInstallations).catch((error) => {- log.warn('deferred default plugin reconciliation failed', {+ log.warn('deferred Plugin market reconciliation failed', {error: error instanceof Error ? error.message : String(error),});})@@ -736,9 +791,6 @@ export class PluginMarketService {if (!compatible.ok) {throwIpcError('GHOST_FILE_INVALID', 'This Plugin manifest is not supported');}- if (!manifestSupportsCurrentCindy(compatible.manifest)) {- throwIpcError('NOT_FOUND', 'This Plugin is unavailable for this Cindy version');- }return {...this.toItem(plugin, EMPTY_LOCAL_INSTALL_SNAPSHOT),manifest: compatible.manifest,@@ -762,22 +814,6 @@ export class PluginMarketService {}}- consumeUpgradeNotice(): PluginUpgradeUserNotice | null {- const key = upgradeNoticeKey(captureMarketOwner());- const notice = this.pendingUpgradeNotices.get(key) ?? null;- if (notice) this.pendingUpgradeNotices.delete(key);- return notice;- }-- hasPendingUpgradeNotice(): boolean {- if (this.pendingUpgradeNotices.size === 0) return false;- try {- return this.pendingUpgradeNotices.has(upgradeNoticeKey(captureMarketOwner()));- } catch {- return false;- }- }-async detail(pluginId: string): Promise<PluginMarketDetail> {// 自定义市场插件走本地发现,不要求服务端可用,也不受 CUID 形状约束。const customRef = parseCustomMarketPluginId(pluginId);@@ -812,9 +848,6 @@ export class PluginMarketService {if (!compatible.ok) {throwIpcError('GHOST_FILE_INVALID', 'This Plugin manifest is not supported');}- if (!manifestSupportsCurrentCindy(compatible.manifest)) {- throwIpcError('NOT_FOUND', 'This Plugin is unavailable for this Cindy version');- }return {...this.toItem(plugin, this.localInstallSnapshot(this.ledgerForOwner(owner))),manifest: compatible.manifest,@@ -976,11 +1009,10 @@ export class PluginMarketService {async install(pluginId: string,options: PluginMarketInstallOptions,- reviewPackagePermissions?: PackagePermissionReviewer,): Promise<PluginMarketInstallResult> {const customRef = parseCustomMarketPluginId(pluginId);if (customRef) {- return this.customInstall(customRef, options, reviewPackagePermissions);+ return this.customInstall(customRef, options);}if (!isValidPluginResourceId(pluginId)) {throwIpcError('INVALID_PARAMS', 'Invalid Plugin ID');@@ -1017,56 +1049,22 @@ export class PluginMarketService {if (!compatible.ok) {throwIpcError('GHOST_FILE_INVALID', 'This Plugin manifest is not supported');}- if (!manifestSupportsCurrentCindy(compatible.manifest)) {- throwIpcError('NOT_FOUND', 'This Plugin is unavailable for this Cindy version');- }- // 用户审阅过的清单必须与市场当前返回的清单有相同的权限面:- // 同 releaseId 下市场在审阅→安装之间换 manifest 时,新增的权限- // 用户从没见过,不能当作"已审阅"递进安装。与自定义来源路径- // install.ts:184-191 的打包前比对同向(但此处比对的是预览清单而非- // 实际打包字节,名字/版本/作者差异不在此处检测)。- let reviewedManifest: GhostManifest | undefined;- if (options.expectedManifest !== undefined) {- const reviewed = validateNormalizedGhostManifest(options.expectedManifest);- // 畸形 payload 会造成 ghostPermissionBaselineKey crash(slots.includes- // 等字段解引用),先验证再比对。验证失败时直接拒——审阅过的清单连基本- // 结构都不对,不能信任。- if (!reviewed.ok) {- throwIpcError('PRECONDITION_FAILED', reviewed.reason);- }- if (- ghostPermissionBaselineKey(compatible.manifest) !==- ghostPermissionBaselineKey(reviewed.manifest)- ) {- throwIpcError('PRECONDITION_FAILED', 'Plugin manifest changed after permission review');- }- // 用户实际点过确认的那份清单才是已审上限。同 release 下服务端把- // OAuth clientId 换掉时,权限投影不变,不能把重新拉取的清单当成已审。- reviewedManifest = reviewed.manifest;- }const existing = getGhostManager().list().find((ghost) => ghost.manifest.id === plugin.ghostId);- const ghost = await this.installDetail(+ return this.installDetail(plugin,{expectedInstalled: Boolean(existing),- ...(reviewedManifest ? { reviewedManifest } : {}),...(options.expectedInstalledApproval !== undefined? { expectedInstalledApproval: options.expectedInstalledApproval }: {}),- allowPermissionExpansion: options.allowPermissionExpansion === true,- ...(options.reviewedBaseline !== undefined- ? { reviewedBaseline: options.reviewedBaseline }- : {}),- permissionPolicy: { mode: 'manual', sourceType: 'server' },- reviewPackagePermissions,+ manifestCap: compatible.manifest,allowSourceReplacement: options.allowSourceReplacement === true,},owner,ledger,);- return ghost ? { ghost } : { cancelled: true };});}@@ -1217,9 +1215,6 @@ export class PluginMarketService {if (!plugin) {throwIpcError('NOT_FOUND', 'The Plugin is no longer listed by this marketplace');}- if (!manifestSupportsCurrentCindy(plugin.manifest)) {- throwIpcError('NOT_FOUND', 'This Plugin is unavailable for this Cindy version');- }return {...this.customToItem({@@ -1243,7 +1238,7 @@ export class PluginMarketService {/*** 自定义市场插件安装/更新。与服务端 installDetail 同一组防线:* release 一致性(重发现后比对 expectedReleaseId)、冲突先装先得、- * 权限扩张显式确认;打包与装入复用 installOrUpdateMarketGhostPackage。+ * 市场 Manifest 能力上限;打包与装入复用 installOrUpdateMarketGhostPackage。** 全程在 `withDiscoveredSource` 租约内执行:`plugin.dir` 指向 Git 源的缓存版本* 目录,打包要逐文件读它。租约必须一直持到打包结束,否则并发刷新的清理能在@@ -1252,8 +1247,14 @@ export class PluginMarketService {private async customInstall(ref: { marketName: string; ghostId: string },options: PluginMarketInstallOptions,- reviewPackagePermissions?: PackagePermissionReviewer,+ automatic = false,): Promise<PluginMarketInstallResult> {+ if (options.expectedManifest === undefined) {+ throwIpcError(+ 'INVALID_PARAMS',+ 'Custom Plugin install must be bound to the selected manifest',+ );+ }const owner = captureMarketOwner();const ledger = this.ledgerForOwner(owner);const manager = this.sourceManagerForOwner(owner);@@ -1270,9 +1271,6 @@ export class PluginMarketService {if (!plugin) {throwIpcError('NOT_FOUND', 'The Plugin is no longer listed by this marketplace');}- if (!manifestSupportsCurrentCindy(plugin.manifest)) {- throwIpcError('NOT_FOUND', 'This Plugin is unavailable for this Cindy version');- }const pluginId = customMarketPluginId(ref.marketName, plugin.ghostId);const releaseId = customMarketReleaseId(ref.marketName, plugin.ghostId, plugin.version);if (releaseId !== options.expectedReleaseId) {@@ -1282,7 +1280,7 @@ export class PluginMarketService {.list().find((ghost) => ghost.manifest.id === plugin.ghostId);const sourceKey = marketSourceKey(discovered.config.source);- // 审阅时刻的已装内容摘要:确认等待和打包窗口内不能换掉当前包。+ // 选择时刻的已装内容摘要:打包窗口内不能换掉当前包。const reviewInstalledDigest = existing? installedGhostRawManifestDigest(existing.dir): null;@@ -1298,7 +1296,7 @@ export class PluginMarketService {if (existing && !matchesSelectedRoute && options.allowSourceReplacement !== true) {throwIpcError('ALREADY_EXISTS', 'A local Plugin already uses this Plugin ID');}- const assertCustomReviewApproved = (installedNow: InstalledGhost | null): void => {+ const assertCustomApprovalStateUnchanged = (installedNow: InstalledGhost | null): void => {if (!installedNow) return;if (options.expectedInstalledApproval === undefined) {throwIpcError(@@ -1311,48 +1309,27 @@ export class PluginMarketService {) {throwIpcError('PRECONDITION_FAILED',- 'Plugin approval state changed after permission review',+ 'Plugin approval state changed during the update',);}- const requiresFullReview =- installedNow.approval.state !== 'approved' ||- diffInstalledGhostPermissionItems(installedNow, plugin.manifest).added.length > 0;- if (!requiresFullReview) return;- if (options.allowPermissionExpansion !== true) {- throwIpcError('PRECONDITION_FAILED', 'Plugin permissions changed and require review');- }- assertReviewedBaselineFresh(installedNow.manifest, options.reviewedBaseline);};- // 无有效 receipt 时不信现场 manifest:目标包全部权限都必须重新确认。- assertCustomReviewApproved(existing ?? null);+ assertCustomApprovalStateUnchanged(existing ?? null);// 来源只决定后台更新路由,不是 ghostId 的永久所有权。只有详情页明确- // 选择“替换”才允许原地切换来源;普通更新和“全部更新”必须保持当前路由。- // 权限基线始终取当前真实安装,避免换源绕过扩权确认。- // 只在已批准安装时给出基线:非 approved 的安装无批准基线,- // 目标包全部权限都必须重新确认,与官方市场路径 (commitDownloadedPackage) 一致。- const permissionBaselineManifest =- existing && existing.approval.state === 'approved'- ? installedGhostRawManifest(existing.dir)- : null;+ // 选择“替换”才允许原地切换来源;自动更新和手动重试必须保持当前路由。let replacedRoute: PluginMarketInstallationRecord | null = null;let replacedRouteWasSuppressed = false;let packageLanded = false;requireSameMarketOwner(owner);- const ghost = await installCustomMarketPlugin({+ const installResult = await installCustomMarketPlugin({pluginDir: plugin.dir,expected: options.expectedManifest,expectedGhostId: plugin.ghostId,expectedVersion: plugin.version,- sourceType: discovered.config.source.type === 'git' ? 'git-market' : 'local-market',- reviewPackagePermissions: async (facts) => {- requireSameMarketOwner(owner);- const approved = await reviewPackagePermissions?.(facts);- requireSameMarketOwner(owner);- return approved === true;- },- ...(permissionBaselineManifest ? { permissionBaselineManifest } : {}),beforeCommit: async () => {requireSameMarketOwner(owner);+ if (automatic && isGhostBusy(plugin.ghostId)) {+ throw new SilentUpgradeBusyError('Plugin is busy');+ }// 所选来源必须**仍然存在且仍是同一个来源**:移除来源会先拿// SOURCE_MUTATION_KEY 删掉配置,租约只保住了目录字节;没有这道核对,// 安装会把一个已经没有对应来源的包装进运行时并写下孤儿账本记录。@@ -1367,8 +1344,8 @@ export class PluginMarketService {// 当前已装目标也要复核:打包窗口(秒到分钟级)内,// 本地插件页可以卸载同 id 插件(那条路径不持本服务的互斥锁)——不查// 会把"更新"降级成"首装+带电启用";反向地,窗口内新装入的同 id- // 本地 .cindy 会被更新分支静默覆盖,还绕过了审阅时跳过的权限 diff。- // 判据与审阅时刻同一份:在场状态一致 + 已装内容摘要未变。+ // 本地 .cindy 会被更新分支静默覆盖。判据与选择时刻同一份:+ // 在场状态一致 + 已装内容摘要未变。const current = getGhostManager().list().find((ghost) => ghost.manifest.id === plugin.ghostId);@@ -1383,12 +1360,14 @@ export class PluginMarketService {if (current && installedGhostRawManifestDigest(current.dir) !== reviewInstalledDigest) {throwIpcError('PRECONDITION_FAILED', 'Installed Plugin changed during the install');}- // raw manifest 摘要不含 Host receipt;内容未变但批准态失效同样必须拒绝- // 旧确认,并在下一轮按无批准基线展示全部权限。- assertCustomReviewApproved(current ?? null);+ // raw manifest 摘要不含 Host receipt;内容未变但批准态变化也必须拒绝。+ assertCustomApprovalStateUnchanged(current ?? null);},expectedInstalledApproval: options.expectedInstalledApproval,beforePackagePlacement: () => {+ if (automatic && isGhostBusy(plugin.ghostId)) {+ throw new SilentUpgradeBusyError('Plugin is busy');+ }const record = ledger.installationForGhost(plugin.ghostId);const routeStillMatches = Boolean(existing &&@@ -1413,7 +1392,7 @@ export class PluginMarketService {onPackagePlaced: () => {packageLanded = true;},- // 复核与落位的双重互斥:+ // 来源复核与落位的双重互斥:// - SOURCE_MUTATION_KEY:beforeCommit 返回后包检查还要跑一段,期间不能// 让来源被增删,否则复核结论在落位前过期。// - withGhostInstallLock(ghostId):与本地 .cindy 装入/更新/卸载共用同一@@ -1462,7 +1441,7 @@ export class PluginMarketService {}throw error;});- return ghost ? { ghost } : { cancelled: true };+ return installResult;});});}@@ -1556,7 +1535,6 @@ export class PluginMarketService {}const sourceEntries: CustomMarketEntry[] = [];for (const plugin of result.marketplace.plugins) {- if (!manifestSupportsCurrentCindy(plugin.manifest)) continue;sourceEntries.push({config,plugin,@@ -1682,34 +1660,19 @@ export class PluginMarketService {private async installDetail(plugin: VisiblePluginDetail,options: {- /** 手动安装时已向用户展示;默认安装时作为自动授权的目录权限上限。 */- reviewedManifest?: GhostManifest;- allowPermissionExpansion?: boolean;/** receipt 模型的并发护栏:比对 receipt 派生 token,状态变更即拒(与 main 硬化叠加)。 */expectedInstalledApproval?: string;- /** 安装前权限确认所依据的已装权限指纹。 */- reviewedBaseline?: string;- /** 手动安装确认真实包;默认安装只使用目录 manifest 作为 fail-closed 上限。 */- permissionPolicy?:- | { mode: 'manual'; sourceType: PluginMarketItem['sourceType'] }- | {- mode: 'cap';- manifest: GhostManifest;- sourceType: PluginMarketItem['sourceType'];- };- /** 真实包需要确认时,在当前安装事务内立即询问发起窗口。 */- reviewPackagePermissions?: PackagePermissionReviewer;+ /** 市场目录公开 Manifest 是真实下载包允许的 Host 能力上限。 */+ manifestCap?: GhostManifest;/** 用户明确点击安装时,允许所选市场包原地替换其它来源的同 id 插件。 */allowSourceReplacement?: boolean;- /** 静默升级时基线不匹配是否按陈旧基线拒绝(不静默覆盖用户已审阅的基线)。 */- silentBaselineMismatch?: boolean;beforeCommitInLock?: () => void;- /** 确认操作时的安装意图;下载窗口期目标被另一窗口卸载时拒绝滑入首装。 */+ /** 发起操作时的安装意图;下载窗口期目标被另一窗口卸载时拒绝滑入首装。 */expectedInstalled: boolean;} = { expectedInstalled: false },owner = captureMarketOwner(),ledger = this.ledgerForOwner(owner),- ): Promise<InstalledGhost | null> {+ ): Promise<PluginMarketInstallResult> {requireSameMarketOwner(owner);if (owner.mode === 'local' && plugin.scope !== 'public') {throwIpcError('PERMISSION_DENIED', 'Local mode can only access public Plugins');@@ -1733,10 +1696,7 @@ export class PluginMarketService {) {throwIpcError('ALREADY_EXISTS', 'A local Plugin already uses this Plugin ID');}- // 受体并发护栏(TOCTOU):仅当调用方**显式**带来了确认时捕获的批准令牌才核对。- // 令牌是更新/恢复入口在渲染确认框那一刻钉下的当前受体;它对不上 = 确认往返- // 窗口里批准被换过,拒绝用旧同意批新包。自动播种/迁移/首装(不带令牌)不受此闸,- // 各自的 expectedInstalled / 所有权 / reviewedBaseline 门负责它们的关切。+ // 更新必须用发起时的 receipt token 绑定当前受体;首装没有既有 token。if (existing) {if (options.expectedInstalledApproval === undefined) {throwIpcError(@@ -1745,33 +1705,14 @@ export class PluginMarketService {);}if (ghostInstallApprovalToken(existing.approval) !== options.expectedInstalledApproval) {- throwIpcError(- 'PRECONDITION_FAILED',- 'Plugin approval state changed after permission review',- );+ throwIpcError('PRECONDITION_FAILED', 'Plugin approval state changed during the update');}}- const reviewedManifest = options.reviewedManifest- ? validateNormalizedGhostManifest(options.reviewedManifest)- : null;- if (reviewedManifest && !reviewedManifest.ok) {- throwIpcError('GHOST_FILE_INVALID', 'This Plugin manifest is not supported');- }- const permissionCap =- options.permissionPolicy?.mode === 'cap'- ? validateNormalizedGhostManifest(options.permissionPolicy.manifest)- : null;- if (permissionCap && !permissionCap.ok) {- throwIpcError('GHOST_FILE_INVALID', 'This Plugin manifest is not supported');- }- this.assertServerPreviewExpansionApproved(- existing ?? null,- reviewedManifest?.manifest,- options.allowPermissionExpansion,- options.reviewedBaseline,- options.silentBaselineMismatch,- );+ // manifestCap 只来自上游同一条安装链路已经通过 validateGhostManifest 的+ // 规范化结果。v2 的内部模型会移除 slots,再把它当原始 ghost.json 二次校验+ // 会误判为非法;这里直接把已验证的能力上限交给真实包一致性校验。+ const manifestCap = options.manifestCap ?? null;const download = await this.api.download(plugin.id, plugin.currentRelease.id);requireSameMarketOwner(owner);if (@@ -1792,98 +1733,56 @@ export class PluginMarketService {try {await downloadVerifiedPlugin(download.url, download, tempPath);requireSameMarketOwner(owner);- try {- return await this.commitDownloadedPackage(- tempPath,- plugin,- {- expectedInstalled: options.expectedInstalled,- ...(options.expectedInstalledApproval !== undefined- ? { expectedInstalledApproval: options.expectedInstalledApproval }- : {}),- ...(reviewedManifest?.ok ? { reviewedManifest: reviewedManifest.manifest } : {}),- allowPermissionExpansion: options.allowPermissionExpansion,- reviewedBaseline: options.reviewedBaseline,- silentBaselineMismatch: options.silentBaselineMismatch,- ...(options.permissionPolicy- ? {- permissionPolicy:- options.permissionPolicy.mode === 'cap' && permissionCap?.ok- ? {- ...options.permissionPolicy,- manifest: permissionCap.manifest,- }- : options.permissionPolicy,- }- : {}),- allowSourceReplacement: options.allowSourceReplacement,- beforeCommitInLock: options.beforeCommitInLock,- },- owner,- ledger,- );- } catch (error) {- if (!(error instanceof GhostPackagePermissionReviewRequiredError)) throw error;- requireSameMarketOwner(owner);- const approved = await options.reviewPackagePermissions?.(error.review);- requireSameMarketOwner(owner);- if (approved !== true) return null;- return await this.commitDownloadedPackage(- tempPath,- plugin,- {- expectedInstalled: options.expectedInstalled,- ...(options.expectedInstalledApproval !== undefined- ? { expectedInstalledApproval: options.expectedInstalledApproval }- : {}),- ...(reviewedManifest?.ok ? { reviewedManifest: reviewedManifest.manifest } : {}),- allowPermissionExpansion: options.allowPermissionExpansion,- reviewedBaseline: options.reviewedBaseline,- silentBaselineMismatch: options.silentBaselineMismatch,- ...(options.permissionPolicy- ? {- permissionPolicy:- options.permissionPolicy.mode === 'cap' && permissionCap?.ok- ? {- ...options.permissionPolicy,- manifest: permissionCap.manifest,- }- : options.permissionPolicy,- }- : {}),- approvedPackageSha256: error.review.packageSha256,- approvedPackageBaseline: error.review.installedBaseline,- allowSourceReplacement: options.allowSourceReplacement,- beforeCommitInLock: options.beforeCommitInLock,- },- owner,- ledger,- );+ const inspected = await getGhostManager().inspect(tempPath);+ if (!('rejection' in inspected)) {+ if (+ inspected.canonicalManifest.id !== plugin.ghostId ||+ inspected.canonicalManifest.version !== plugin.currentRelease.version+ ) {+ throwIpcError('GHOST_FILE_INVALID', 'Downloaded Plugin package identity changed');+ }+ if (manifestCap) {+ const extraCapabilities = unreviewedGhostPermissionItems(+ manifestCap,+ undefined,+ inspected.canonicalManifest,+ );+ if (extraCapabilities.length > 0) {+ throwIpcError(+ 'GHOST_FILE_INVALID',+ 'Downloaded Plugin package capabilities exceed the market manifest',+ );+ }+ }}+ const ghost = await this.commitDownloadedPackage(+ tempPath,+ plugin,+ {+ expectedInstalled: options.expectedInstalled,+ ...(options.expectedInstalledApproval !== undefined+ ? { expectedInstalledApproval: options.expectedInstalledApproval }+ : {}),+ ...(manifestCap ? { manifestCap } : {}),+ allowSourceReplacement: options.allowSourceReplacement,+ beforeCommitInLock: options.beforeCommitInLock,+ },+ owner,+ ledger,+ );+ return { ghost };} finally {await fs.promises.rm(tempPath, { force: true }).catch(() => undefined);}}- /** 把已验证临时包提交到运行时;确认前后复用同一文件。 */+ /** 把已验证临时包提交到运行时;校验与落位复用同一文件。 */private async commitDownloadedPackage(tempPath: string,plugin: VisiblePluginSummary | VisiblePluginDetail,options: {- permissionPolicy?:- | { mode: 'manual'; sourceType: PluginMarketItem['sourceType'] }- | {- mode: 'cap';- manifest: GhostManifest;- sourceType: PluginMarketItem['sourceType'];- };- approvedPackageSha256?: string;- approvedPackageBaseline?: string | null;expectedInstalledApproval?: string;- reviewedManifest?: GhostManifest;- allowPermissionExpansion?: boolean;- reviewedBaseline?: string;- silentBaselineMismatch?: boolean;+ manifestCap?: GhostManifest;allowSourceReplacement?: boolean;beforeCommitInLock?: () => void;expectedInstalled: boolean;@@ -1928,31 +1827,6 @@ export class PluginMarketService {}}requireSameMarketOwner(owner);- this.assertServerPreviewExpansionApproved(- installedNow ?? null,- options.reviewedManifest,- options.allowPermissionExpansion,- options.reviewedBaseline,- options.silentBaselineMismatch,- );- const installedRawManifest = installedNow- ? installedGhostRawManifest(installedNow.dir)- : null;- // 权限基线只在已批准安装时给出:非 approved (legacy-unapproved/invalid)- // 无批准基线,目标包全部权限都必须重新确认,不能让旧确认带出的基线被- // 当成"已审阅过"。approved 安装的基线取当前真实运行包(不是 ledger 摘要),- // 更新路由由上方 serverRecordMatchesInstalledGhost 单独判断。- // 经来源账本摘要认证的已装清单;缺失时不得回退到可变运行时清单。- // currentRecordNow 是 provenance ledger 的记录(允许 source replacement 时不比对- // pluginId,但不影响摘要链——来源可以不同,安装目录的字节身份仍需与已记录摘要一致)。- const permissionBaselineManifest =- installedNow?.approval.state === 'approved' &&- installedRawManifest &&- currentRecordNow?.installed &&- (currentRecordNow.source === 'market' || currentRecordNow.source === 'legacy-adopted') &&- currentRecordNow.manifestDigest === ghostManifestDigest(installedRawManifest)- ? installedRawManifest- : null;const replacingSource = Boolean(installedNow &&options.allowSourceReplacement &&@@ -1987,24 +1861,10 @@ export class PluginMarketService {},}: {}),- ...(options.permissionPolicy- ? {- permissionPolicy: options.permissionPolicy,- ...(permissionBaselineManifest ? { permissionBaselineManifest } : {}),- ...(options.reviewedManifest ? { reviewedManifest: options.reviewedManifest } : {}),- }- : {}),- ...(options.approvedPackageSha256 !== undefined- ? {- approvedPackageSha256: options.approvedPackageSha256,- ...(options.approvedPackageBaseline !== null- ? { reviewedBaseline: options.approvedPackageBaseline }- : {}),- }- : {}),...(options.expectedInstalledApproval !== undefined? { expectedInstalledApproval: options.expectedInstalledApproval }: {}),+ ...(options.manifestCap ? { manifestCap: options.manifestCap } : {}),...(options.beforeCommitInLock || replacingSource? { beforeCommitInLock: detachPreviousRoute }: {}),@@ -2033,31 +1893,6 @@ export class PluginMarketService {});}- private assertServerPreviewExpansionApproved(- installed: InstalledGhost | null,- reviewedManifest: GhostManifest | undefined,- allowPermissionExpansion: boolean | undefined,- reviewedBaseline: string | undefined,- silentBaselineMismatch = false,- ): void {- if (!installed || !reviewedManifest) return;- const requiresFullReview =- installed.approval.state !== 'approved' ||- diffInstalledGhostPermissionItems(installed, reviewedManifest).added.length > 0;- if (!requiresFullReview) return;- if (allowPermissionExpansion !== true) {- throwIpcError('PRECONDITION_FAILED', 'Plugin permissions changed and require review');- }- if (- silentBaselineMismatch &&- reviewedBaseline !== undefined &&- ghostPermissionBaselineKey(installed.manifest) !== reviewedBaseline- ) {- throw new SilentUpgradeStaleBaselineError('Installed Plugin permissions changed');- }- assertReviewedBaselineFresh(installed.manifest, reviewedBaseline);- }-private requireConfigured(): void {if (!getClientEndpoint('pluginApiBaseUrl')) {throwIpcError('UNSUPPORTED_CAPABILITY', 'Plugin market is not configured');@@ -2473,8 +2308,8 @@ export class PluginMarketService {const detail = await this.api.detail(summary.id);requireSameMarketOwner(owner);assertDetailMatchesSummary(summary, detail);- const permissionCap = validateGhostManifest(detail.currentRelease.manifest);- if (!permissionCap.ok) {+ const manifestCap = validateGhostManifest(detail.currentRelease.manifest);+ if (!manifestCap.ok) {throwIpcError('GHOST_FILE_INVALID', 'This Plugin manifest is not supported');}// 装完即开语义已收敛进市场安装入口本身,这里无需再显式声明。@@ -2482,14 +2317,8 @@ export class PluginMarketService {detail,{expectedInstalled: false,- // 默认安装没有用户发起窗口:目录 manifest 是自动安装可接受的权限- // 上限;真实包若额外扩权,installDetail 会安全取消并等待用户之后- // 从详情页手动安装、在原请求窗口完成确认。- permissionPolicy: {- mode: 'cap',- manifest: permissionCap.manifest,- sourceType: 'server',- },+ // 目录 Manifest 是真实包允许的能力上限;超出时按包内容不一致拒绝。+ manifestCap: manifestCap.manifest,// 下载期间用户可能从本地插件页完成显式卸载。最终落位前在// ghostId 锁内重读卸载意图,不能让旧 snapshot 把插件装回来。beforeCommitInLock: () => {@@ -2528,43 +2357,38 @@ export class PluginMarketService {return completed;}- private async applyDefaultUpgrades(+ private async applyAutomaticUpgrades(plugins: readonly VisiblePluginSummary[],+ customEntries: readonly CustomMarketEntry[],owner: ActiveAppSession,ledger: PluginMarketLedger,): Promise<boolean> {let reconciled = true;- const local = this.localInstallSnapshot(ledger);- const completed: Array<{- name: string | null;- permissions: PluginUpgradePermissionNotice[];- }> = [];+ let local = this.localInstallSnapshot(ledger);for (const summary of plugins) {- if (!summary.defaultInstall || summary.scope !== 'organization') continue;- if (this.toItem(summary, local).installState !== 'update-available') continue;+ const retryKey = this.automaticUpgradeRetryKey(owner, 'server', summary.id);+ const releaseKey = summary.currentRelease.id;+ const record = local.installations[summary.ghostId];if (- hasPendingGhostCalls(summary.ghostId) ||- hasRunningGhostErrand(summary.ghostId) ||- hasRunningGhostCindyWork(summary.ghostId)+ record?.source !== 'market' ||+ this.toItem(summary, local).installState !== 'update-available' ||+ isGhostBusy(summary.ghostId) ||+ this.shouldDeferAutomaticUpgrade(retryKey, releaseKey)) {- reconciled = false;continue;}try {await this.withMutation(summary.id, async () => {requireSameMarketOwner(owner);- if (- hasPendingGhostCalls(summary.ghostId) ||- hasRunningGhostErrand(summary.ghostId) ||- hasRunningGhostCindyWork(summary.ghostId)- ) {+ if (isGhostBusy(summary.ghostId)) {throw new SilentUpgradeBusyError('Plugin is busy');}const freshLocal = this.localInstallSnapshot(ledger);- if (this.toItem(summary, freshLocal).installState !== 'update-available') {- log.debug?.('default plugin upgrade already reconciled', {- pluginId: summary.id,- });+ if (+ freshLocal.installations[summary.ghostId]?.source !== 'market' ||+ this.toItem(summary, freshLocal).installState !== 'update-available'+ ) {+ log.debug?.('Plugin update already reconciled', { pluginId: summary.id });return;}const freshInstalled = freshLocal.ghostsById.get(summary.ghostId);@@ -2574,53 +2398,31 @@ export class PluginMarketService {});return;}- // A legacy-unapproved or invalid install has no approved baseline: a- // silent default upgrade would let Main mint a fresh approved receipt- // without the full permission review the user must confirm. Skip the- // silent upgrade and leave the plugin in its current state so it goes- // through the reapproval/recovery flow instead.+ // 无有效 receipt 的安装不能被后台更新静默恢复为已批准;保留现状,+ // 等待用户从明确的手动安装/更新入口重新落位。if (freshInstalled.approval.state !== 'approved') {- log.warn('default plugin upgrade skipped for unapproved install', {+ log.warn('automatic Plugin update skipped for unapproved install', {pluginId: summary.id,ghostId: summary.ghostId,approvalState: freshInstalled.approval.state,});return;}- const reviewedBaseline = ghostPermissionBaselineKey(freshInstalled.manifest);const detail = await this.api.detail(summary.id);requireSameMarketOwner(owner);assertDetailMatchesSummary(summary, detail);- const reviewedManifest = validateGhostManifest(detail.currentRelease.manifest);- if (!reviewedManifest.ok)+ const manifestCap = validateGhostManifest(detail.currentRelease.manifest);+ if (!manifestCap.ok) {throwIpcError('GHOST_FILE_INVALID', 'This Plugin manifest is not supported');- if (!manifestSupportsCurrentCindy(reviewedManifest.manifest)) {- log.warn('default plugin upgrade skipped for Cindy version', {- pluginId: summary.id,- minCindyVersion: reviewedManifest.manifest.minCindyVersion,- });- return;}- const installed = await this.installDetail(+ await this.installDetail(detail,{expectedInstalled: true,- reviewedManifest: reviewedManifest.manifest,- allowPermissionExpansion: true,- reviewedBaseline,expectedInstalledApproval: ghostInstallApprovalToken(freshInstalled.approval),- silentBaselineMismatch: true,- permissionPolicy: {- mode: 'cap',- manifest: reviewedManifest.manifest,- sourceType: 'server',- },+ manifestCap: manifestCap.manifest,beforeCommitInLock: () => {- if (- hasPendingGhostCalls(summary.ghostId) ||- hasRunningGhostErrand(summary.ghostId) ||- hasRunningGhostCindyWork(summary.ghostId)- ) {+ if (isGhostBusy(summary.ghostId)) {throw new SilentUpgradeBusyError('Plugin is busy');}},@@ -2628,47 +2430,69 @@ export class PluginMarketService {owner,ledger,);- if (installed) {- const addedPermissions = freshInstalled- ? diffGhostPermissionItems(freshInstalled.manifest, installed.manifest).added.map(- ({ key, labelKey, labelArgs }) => ({- key,- labelKey,- ...(labelArgs ? { labelArgs } : {}),- }),- )- : [];- completed.push({- name: stripDirectionalControls(installed.manifest.name) || null,- permissions: addedPermissions,- });- }});+ local = this.localInstallSnapshot(ledger);+ this.clearAutomaticUpgradeFailure(retryKey, releaseKey);} catch (error) {if (error instanceof SilentUpgradeBusyError) {reconciled = false;} else {reconciled = false;- log.warn('default plugin upgrade failed', {+ const retry = this.recordAutomaticUpgradeFailure(retryKey, releaseKey);+ log.warn('automatic Plugin update failed', {pluginId: summary.id,+ releaseId: releaseKey,+ failures: retry.failures,+ retryAfter: new Date(retry.retryAfter).toISOString(),error: error instanceof Error ? error.message : String(error),});}}}- if (completed.length > 0) {- const key = upgradeNoticeKey(owner);- const count = (this.pendingUpgradeNotices.get(key)?.count ?? 0) + completed.length;- const hasPermissionExpansion =- (this.pendingUpgradeNotices.get(key)?.hasPermissionExpansion ?? false) ||- completed.some((entry) => entry.permissions.length > 0);- this.pendingUpgradeNotices.set(key, {- count,- name: count === 1 ? (completed[0]?.name ?? null) : null,- permissions:- count === 1 && completed[0]?.permissions.length ? completed[0].permissions : null,- hasPermissionExpansion,- });++ for (const entry of customEntries) {+ const projected = this.customToItem(entry, local);+ const retryKey = this.automaticUpgradeRetryKey(owner, 'custom', projected.pluginId);+ const releaseKey = projected.releaseId;+ const installed = local.ghostsById.get(projected.ghostId);+ if (+ projected.installState !== 'update-available' ||+ isGhostBusy(projected.ghostId) ||+ installed?.approval.state !== 'approved' ||+ this.shouldDeferAutomaticUpgrade(retryKey, releaseKey)+ ) {+ continue;+ }+ try {+ requireSameMarketOwner(owner);+ await this.customInstall(+ { marketName: entry.config.name, ghostId: entry.plugin.ghostId },+ {+ expectedReleaseId: projected.releaseId,+ expectedManifest: entry.plugin.manifest,+ expectedInstalledApproval: ghostInstallApprovalToken(installed.approval),+ allowSourceReplacement: false,+ },+ true,+ );+ local = this.localInstallSnapshot(ledger);+ this.clearAutomaticUpgradeFailure(retryKey, releaseKey);+ } catch (error) {+ if (error instanceof SilentUpgradeBusyError) {+ reconciled = false;+ } else {+ reconciled = false;+ const retry = this.recordAutomaticUpgradeFailure(retryKey, releaseKey);+ log.warn('automatic custom Plugin update failed', {+ pluginId: projected.pluginId,+ market: entry.config.name,+ releaseId: releaseKey,+ failures: retry.failures,+ retryAfter: new Date(retry.retryAfter).toISOString(),+ error: error instanceof Error ? error.message : String(error),+ });+ }+ }}return reconciled;}diff --git a/apps/desktop/src/main/scheduler-host/__tests__/scriptCapabilityBroker.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/scriptCapabilityBroker.test.tsindex e924b61083..cb76020b8f 100644--- a/apps/desktop/src/main/scheduler-host/__tests__/scriptCapabilityBroker.test.ts+++ b/apps/desktop/src/main/scheduler-host/__tests__/scriptCapabilityBroker.test.ts@@ -807,7 +807,7 @@ function makeInstalledGhost(id: string): InstalledGhost {version: '1.0.0',kind: 'chip',entry: 'main.js',- slots: ['fs'],+ fs: true,tools: [{ name: 'jira_issues', description: 'jira' }],} as InstalledGhost['manifest'],dir: '/tmp/fake-install-dir',diff --git a/apps/desktop/src/main/smoke/pluginStorageSmoke.ts b/apps/desktop/src/main/smoke/pluginStorageSmoke.tsindex f0b7a1a203..c2367d9fec 100644--- a/apps/desktop/src/main/smoke/pluginStorageSmoke.ts+++ b/apps/desktop/src/main/smoke/pluginStorageSmoke.ts@@ -76,7 +76,8 @@ export async function runPluginStorageSmoke(ownerId: string): Promise<PluginStorfs.writeFileSync(path.join(ghostDir, 'ghost.json'),`${JSON.stringify({- schemaVersion: 2,+ schemaVersion: 3,+ minCindyVersion: '0.1.61',id: GHOST_ID,name: 'Plugin storage smoke',description: 'Packaged smoke fixture',@@ -84,7 +85,7 @@ export async function runPluginStorageSmoke(ownerId: string): Promise<PluginStorversion: '1.0.0',kind: 'chip',entry: 'main.js',- slots: ['notify'],+ notify: true,})}\n`,);fs.writeFileSync(path.join(ghostDir, 'main.js'), '// packaged plugin storage smoke\n');diff --git a/apps/desktop/src/preload/ghostPreload.ts b/apps/desktop/src/preload/ghostPreload.tsindex 7eef6376c7..7124d038b2 100644--- a/apps/desktop/src/preload/ghostPreload.ts+++ b/apps/desktop/src/preload/ghostPreload.ts@@ -10,18 +10,19 @@ import { contextBridge, ipcRenderer } from 'electron';* 暴露面刻意极小(管子三口 + network 一口):* - ping():握手/自检,回自己的意识 id;* - onHostMessage(cb):订阅主机下行(工具调用派发等,后续切片投递);- * - send(payload):上行投递(工具结果/面板推送申请等;主机按 slots 白名单- * 与消息类型路由,未开闸的类型一律拒);- * - request(req):读取宿主只读信息的便捷口——就是- * send({type:'host-request',…req}) 的语法糖;支持 app-context 与当前插件已- * 声明的 Cindy 媒体能力选型,不返回其它插件配置、凭证或 endpoint。- * - fetch(req):network 槽代理 HTTP 的便捷口——就是 send({type:'fetch-request',- * …req}) 的语法糖,零新通道零新权限(白名单/凭证注入全在主机侧守门)。- * - fs(req):fs 槽代写文件的便捷口——send({type:'fs-request', …req}) 的- * 语法糖,同样零新通道零新权限(三档守门全在主机侧 fsSlot)。- * - library(req):library 槽持久作品库的便捷口——send({type:'library-request',- * …req}) 的语法糖;资格审/binding 根解析/owner scope 复核/SQL 语句门全在- * 主机侧 librarySlot,失败回结构化 errorCode(永不 reject)。+ * - send(payload):上行投递(工具结果/Host 请求等);主机按消息类型、+ * 调用上下文与插件自主能力声明守门,未开闸的类型一律拒;+ * - request(req):读取宿主公开上下文的便捷口——就是+ * send({type:'host-request',…req}) 的语法糖;目前只支持 app-context(region),+ * 不含用户数据与凭证,也不扩张其它主机能力。+ * - fetch(req):主机代理 HTTP 的便捷口——就是 send({type:'fetch-request',+ * …req}) 的语法糖。Agent 在途调用凭 callId 复用 Agent 授权;自主调用+ * 按 network 声明守门,托管凭证始终只按声明注入。+ * - fs(req):主机文件操作的便捷口——send({type:'fs-request', …req}) 的+ * 语法糖。workdir 写入可复用 Agent 在途授权,data 私有目录按 fs 声明守门。+ * - library(req):持久作品库的便捷口——send({type:'library-request', …req})+ * 的语法糖;资格审、binding 根解析、owner scope 复核与 SQL 语句门都在+ * 主机侧 librarySlot,失败返回结构化 errorCode。* - agent.errand(req) / agent.queryErrand(req):派活取件便捷口——* send({type:'agent-errand-request', kind:'run'/'query', …req}) 的语法糖;* - agent.run(req):Agent 新回合的便捷口——send({type:'agent-request',diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 1c3990861b..6224215c15 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -14,7 +14,6 @@ import {SIDEBAR_PROJECT_ORDER_CHANGED_CHANNEL,type SyncedProjectOrderSnapshot,} from '../shared/projectOrderSettings';-import type { GhostInstallOrigin } from '../shared/ghostInstallOrigin';import type { SessionDragPreviewPalette } from '../shared/sessionDragPreview';import {AGENT_ISLAND_GET_DISPLAY_OPTIONS_CHANNEL,@@ -474,12 +473,6 @@ const fanOutCorruptionRestored = createIpcFanOut('local-db:corruption-restored')const fanOutPluginRemovalNoticeAvailable = createIpcFanOut('plugin-market:removal-notice-available',);-const fanOutPluginUpgradeNoticeAvailable = createIpcFanOut(- 'plugin-market:upgrade-notice-available',-);-const fanOutPluginMarketPackagePermissionReview = createIpcFanOut(- 'plugin-market:package-permission-review',-);// #37: release 端检测到 schema drift 时一次性 toast 提示开发者切回 dev 自动修复const fanOutSchemaDriftWarning = createIpcFanOut('local-db:schema-drift-warning');const fanOutProjectAliasesChanged = createIpcFanOut('local-db:project-aliases:changed');@@ -589,7 +582,7 @@ const fanOutPluginPublisherConfirm = createIpcFanOut('plugin-publisher:confirm')const fanOutGhostSetupNavigate = createIpcFanOut('maker:plugin-setup:navigate');// Plugin 顶部已安装快捷行的最近使用顺序,多窗口同步。const fanOutGhostRecentUsageChanged = createIpcFanOut('ghosts:recent-usage-changed');-// 双击 .cindy 转交信号(main 缓存路径,renderer 收信号后来取,统一走应用内确认流程)。+// 双击 .cindy 转交信号(main 缓存路径,renderer 收信号后来取,统一走一键安装流程)。const fanOutGhostInstallRequested = createIpcFanOut('ghosts:install-requested');// 意识运行时状态广播(crashed/fused → 面板原地错误接管态)。const fanOutGhostRuntimeChanged = createIpcFanOut('ghosts:runtime-changed');@@ -1123,14 +1116,13 @@ contextBridge.exposeInMainWorld('electronAPI', {setupStatus: (id: string): Promise<unknown> => ipcRenderer.invoke('ghosts:setup-status', id),install: (lizFilePath: string,- opts: { enable?: boolean; expectedPackageSha256: string; packTicket?: string },+ opts: { enable?: boolean; expectedPackageSha256: string },): Promise<{ ghost: unknown }> => ipcRenderer.invoke('ghosts:install', lizFilePath, opts),update: (lizFilePath: string,opts: {expectedPackageSha256: string;expectedInstalledApproval: string;- packTicket?: string;},): Promise<{ ghost: unknown }> => ipcRenderer.invoke('ghosts:update', lizFilePath, opts),cindyPrefsSync: (@@ -1195,33 +1187,9 @@ contextBridge.exposeInMainWorld('electronAPI', {manifest: unknown;trust: unknown;packageSha256: string;+ unsupportedSlots: string[];iconDataUrl?: string;- packTicket?: string;}> => ipcRenderer.invoke('ghosts:inspect', lizFilePath),- abandonPackTicket: (packTicket: string): Promise<{ ok: true }> =>- ipcRenderer.invoke('ghosts:abandon-pack-ticket', packTicket),- /** 本地包第三条恢复路径:从已装目录读确认卡事实(零副作用)。 */- reapproveInspect: (- id: string,- ): Promise<{- manifest: unknown;- trust: unknown;- manifestSha256: string;- approvalProjectionSha256: string;- previouslyEnabled: boolean;- inspectTicket: string;- }> => ipcRenderer.invoke('ghosts:reapprove-inspect', id),- /** 确认卡点过同意后开 receipt;sha + 一次性票据绑定确认时的事实与 owner。 */- reapproveInstalled: (- id: string,- opts: {- enable: boolean;- expectedManifestSha256: string;- expectedApprovalProjectionSha256: string;- expectedInstalledApproval: string;- inspectTicket: string;- },- ): Promise<{ ghost: unknown }> => ipcRenderer.invoke('ghosts:reapprove-installed', id, opts),uninstall: (id: string): Promise<{ ok: true }> => ipcRenderer.invoke('ghosts:uninstall', id),/** 详情页「导出 .cindy」:main 打包安装目录 → 系统保存对话框落盘。 */export: (@@ -1239,10 +1207,8 @@ contextBridge.exposeInMainWorld('electronAPI', {disabled: boolean,): Promise<{ disabled: string[] }> =>ipcRenderer.invoke('ghosts:workdir-prefs:set', workdir, id, disabled),- takePendingInstall: (): Promise<{- filePath: string | null;- origin: GhostInstallOrigin;- }> => ipcRenderer.invoke('ghosts:take-pending-install'),+ takePendingInstall: (): Promise<{ filePath: string | null }> =>+ ipcRenderer.invoke('ghosts:take-pending-install'),onChanged: fanOutGhostsChanged,onSetupNavigate: (callback: (@@ -1388,25 +1354,12 @@ contextBridge.exposeInMainWorld('electronAPI', {options: import('../shared/pluginMarket').PluginMarketInstallOptions,): Promise<import('../shared/pluginMarket').PluginMarketInstallResult> =>ipcRenderer.invoke('plugin-market:install', pluginId, options),- onPackagePermissionReview: fanOutPluginMarketPackagePermissionReview,- resolvePackagePermissionReview: (- requestId: string,- confirmed: boolean,- ): Promise<{ handled: boolean }> =>- ipcRenderer.invoke('plugin-market:resolve-package-permission-review', {- requestId,- confirmed,- }),uninstall: (pluginId: string): Promise<{ ok: true }> =>ipcRenderer.invoke('plugin-market:uninstall', pluginId),consumeRemovalNotice: (): Promise<import('../shared/pluginMarket').PluginRemovalUserNotice | null> => ipcRenderer.invoke('plugin-market:consume-removal-notice'),onRemovalNoticeAvailable: fanOutPluginRemovalNoticeAvailable,- consumeUpgradeNotice: (): Promise<- import('../shared/pluginMarket').PluginUpgradeUserNotice | null- > => ipcRenderer.invoke('plugin-market:consume-upgrade-notice'),- onUpgradeNoticeAvailable: fanOutPluginUpgradeNoticeAvailable,listSources: (): Promise<import('../shared/pluginMarket').MarketSourceSummary[]> =>ipcRenderer.invoke('plugin-market:list-sources'),pickLocalSource: (diff --git a/apps/desktop/src/renderer/App.tsx b/apps/desktop/src/renderer/App.tsxindex 8e9ad311c8..c2e2b5e9e9 100644--- a/apps/desktop/src/renderer/App.tsx+++ b/apps/desktop/src/renderer/App.tsx@@ -27,7 +27,6 @@ import { ConfirmDialogProvider } from '@/components/ui/confirm-dialog-provider';import { FindInPageBar } from '@/components/find-in-page/FindInPageBar';import { ProjectAutomationNotifyBridge } from '@/features/scheduler/components/ProjectAutomationNotifyBridge';import { GhostConfirmDialogHost } from '@/cindy-brain/GhostConfirmDialogHost';-import { PluginMarketPermissionReviewHost } from '@/features/plugin/PluginMarketPermissionReviewHost';import { PluginPublisherConfirmHost } from '@/features/plugin/PluginPublisherConfirmHost';import { makerChatStore } from '@/lib/makerChatStore';import {@@ -373,7 +372,6 @@ export function App() {内(要 useConfirmDialog);main 只投单个窗口,所以每个窗口都挂、谁收到谁弹,不按窗口类型 gate。 */}<GhostConfirmDialogHost />- <PluginMarketPermissionReviewHost /><PluginPublisherConfirmHost /><OwnerScopedRouter /></EnvCheckGuard>diff --git a/apps/desktop/src/renderer/__tests__/composerHostCapability.test.ts b/apps/desktop/src/renderer/__tests__/composerHostCapability.test.tsindex 2758893846..5a82f0eb41 100644--- a/apps/desktop/src/renderer/__tests__/composerHostCapability.test.ts+++ b/apps/desktop/src/renderer/__tests__/composerHostCapability.test.ts@@ -28,7 +28,7 @@ function capabilityGhost(): InstalledGhost {version: '0.2.0',kind: 'chip',entry: 'main.js',- slots: ['ios-simulator'],+ iosSimulator: true,},dir: '/tmp/ios-simulator',enabled: true,diff --git a/apps/desktop/src/renderer/__tests__/ghostCommand.test.ts b/apps/desktop/src/renderer/__tests__/ghostCommand.test.tsindex dfe9844fe3..1e02bf8b97 100644--- a/apps/desktop/src/renderer/__tests__/ghostCommand.test.ts+++ b/apps/desktop/src/renderer/__tests__/ghostCommand.test.ts@@ -26,7 +26,6 @@ function ghost(command: string | undefined, enabled = true): InstalledGhost {version: '1.0.0',kind: 'chip',entry: 'main.js',- slots: ['tool', 'model'],tools: [{ name: 'gen_image', description: 'x' }],...(command !== undefined ? { command } : {}),},diff --git a/apps/desktop/src/renderer/__tests__/ghostCommandDecoration.test.ts b/apps/desktop/src/renderer/__tests__/ghostCommandDecoration.test.tsindex fa98706fa4..ced4acc8e9 100644--- a/apps/desktop/src/renderer/__tests__/ghostCommandDecoration.test.ts+++ b/apps/desktop/src/renderer/__tests__/ghostCommandDecoration.test.ts@@ -58,7 +58,6 @@ function makeGhost(version: '1.0.0',kind: 'chip',entry: 'main.js',- slots: ['tool'],command,};return {diff --git a/apps/desktop/src/renderer/__tests__/ghostComposerPlacement.test.ts b/apps/desktop/src/renderer/__tests__/ghostComposerPlacement.test.tsindex 87ff46e293..3840631fbd 100644--- a/apps/desktop/src/renderer/__tests__/ghostComposerPlacement.test.ts+++ b/apps/desktop/src/renderer/__tests__/ghostComposerPlacement.test.ts@@ -30,7 +30,6 @@ function ghost(command: string, id = command, enabled = true): InstalledGhost {version: '1.0.0',kind: 'chip',entry: 'main.js',- slots: ['tool'],tools: [{ name: 'run', description: 'Run.' }],command,},@@ -49,7 +48,7 @@ function hostCapabilityGhost(id = 'ios-simulator'): InstalledGhost {version: '1.0.0',kind: 'chip',entry: 'main.js',- slots: ['ios-simulator'],+ iosSimulator: true,},dir: `/tmp/${id}`,enabled: true,diff --git a/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx b/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsxdeleted file mode 100644index 54cbbdd9bb..0000000000--- a/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx+++ /dev/null@@ -1,588 +0,0 @@-/**- * 装入/更新确认框的逐项权限清单(docs/dev-rules/plugin-security-and-authoring.md)。- *- * 纯展示组件:条目由 shared/ghost.ts 的 ghostPermissionItems /- * diffGhostPermissionItems 静态推导(装入前无需运行意识代码),这里只负责- * 翻译与排版。装入分支渲染全量清单;更新分支只高亮权限 diff(新增/移除),- * 不变项折叠成一行计数——权限没变的更新不该让用户重读一遍清单。- */-import {- AppWindow,- Bell,- BellDot,- BadgeCheck,- Bot,- BookOpen,- ChevronDown,- Cpu,- FileCode2,- FilePen,- FolderOpen,- FolderPlus,- Globe,- GraduationCap,- KeyRound,- LayoutTemplate,- Library,- MapPin,- Megaphone,- MessageCircleQuestion,- PanelLeft,- PanelRight,- Sparkles,- ShieldAlert,- Smartphone,- Terminal,- Wrench,- type LucideIcon,-} from 'lucide-react';-import { useState, type ReactNode } from 'react';-import { useTranslation } from 'react-i18next';--import { cn } from '@/lib/utils';-import type { GhostPermissionDiff, GhostPermissionItem, GhostTrustInfo } from '../../shared/ghost';--const KIND_ICON: Record<GhostPermissionItem['kind'], LucideIcon> = {- cindy: Sparkles, // 与详情页「Cindy 能力」区同款图标- agent: Bot,- node: Cpu,- tool: Wrench,- command: Terminal,- panel: PanelRight,- 'main-view': AppWindow,- code: FileCode2,- subscribe: Bell,- card: LayoutTemplate,- network: Globe,- notify: Megaphone,- confirm: MessageCircleQuestion,- fs: FilePen,- library: Library,- 'session-context': MapPin,- pick: FolderOpen,- preview: AppWindow,- skill: GraduationCap,- workspace: FolderPlus,- 'ios-simulator': Smartphone,-};--function itemIcon(item: GhostPermissionItem): LucideIcon {- if (item.labelKey === 'panelLeft') return PanelLeft;- // 未读角标与一次性提示同属 notify kind,但一个是常驻注意力入口、一个是弹完就走- // (两者是并列的两档权限,可以只申请其中一项),同时出现时同图标读起来像重复项,- // 给角标换一枚带点的铃铛以示区分。- if (item.labelKey === 'badge') return BellDot;- // network 槽的凭证条目换钥匙图标(与域名条目区分:一个是"去哪",一个是"带什么")。- if (- item.labelKey === 'networkSecret' ||- item.labelKey === 'networkSecretOauth' ||- item.labelKey === 'networkSecretGhCli' ||- item.labelKey === 'networkSecretOrganizationIdentity' ||- item.labelKey === 'nodeSecret'- )- return KeyRound;- return KIND_ICON[item.kind];-}--function PermRow({- item,- badge,-}: {- item: GhostPermissionItem;- badge?: 'added' | 'removed' | 'updated';-}) {- const { t } = useTranslation();- const Icon = itemIcon(item);- // 主机固定说明(detailKey)与作者自由文本(detail)可以并存(oauth 凭证:- // 说明 + scopes 原文清单)——都在时两行都渲染,不许作者文本顶掉主机说明。- // detailArgs 只喂说明行(与 labelArgs 分开:说明里的插值是主机政策数字,- // 如寄存字节上限,由常量单源注入,免得上限改了四份 locale 的数字对不上)。- const hostDetail = item.detailKey- ? t(`settings.ghosts.perm.${item.detailKey}`, item.detailArgs)- : undefined;- const authorDetail = item.detail;- return (- <div className={cn('flex items-start gap-2 py-1', badge === 'removed' && 'opacity-60')}>- <span className="mt-[2px] shrink-0 text-[var(--text-tertiary)]">- <Icon size={14} />- </span>- <div className="min-w-0 flex-1">- <div- className={cn(- // labelArgs 含作者可控 token(域名/工具名等无空格长串),同 hostDetail- // 一样必须可断行,否则顶破固定宽度的安装确认弹窗。- 'break-words text-13 leading-[1.5] text-[var(--confirm-desc)]',- badge === 'removed' && 'line-through',- )}- >- {t(`settings.ghosts.perm.${item.labelKey}`, item.labelArgs)}- </div>- {hostDetail && (- <div className="break-words text-12 leading-[1.5] text-[var(--text-tertiary)]">- {hostDetail}- </div>- )}- {authorDetail && (- // 作者文本按原样换行展示(scopes 一行一条等,知情面不做加工)。- <div className="whitespace-pre-line break-words text-12 leading-[1.5] text-[var(--text-tertiary)]">- {authorDetail}- </div>- )}- </div>- {badge && (- // diff 语义豁免色(docs/design-rules/cindy-design-system.md §2 / 规则 16):权限新增/移除就是一次 diff,- // 用 GitHub diff 红绿 token,跨主题一致;「更新」(同 key 说明变化)既不是纯增也不是纯减,- // 用中性 chip,不占用 diff 色。徽章是 chrome,select-none。- <span- className={cn(- 'mt-[2px] shrink-0 select-none rounded px-1.5 py-px text-11 font-medium',- badge === 'added' && 'bg-[var(--diff-add-bg)] text-[var(--diff-add-fg)]',- badge === 'removed' && 'bg-[var(--diff-del-bg)] text-[var(--diff-del-fg)]',- badge === 'updated' && 'bg-[var(--surface-chip)] text-[var(--text-secondary)]',- )}- >- {t(`settings.ghosts.perm.${badge}`)}- </span>- )}- </div>- );-}--/**- * 全量权限行(无标题):装入确认框与详情页「权限」卡共用同一渲染,- * 保证"事前看到的"和"事后查到的"逐像素一致,不出两套口径。- */-export function GhostPermissionRows({ items }: { items: GhostPermissionItem[] }) {- if (items.length === 0) return null;- return (- <div>- {items.map((item) => (- <PermRow key={item.key} item={item} />- ))}- </div>- );-}--/**- * 工具说明由意识作者自由填写,往往是整段接口文档。确认框只先报工具数量,- * 用户主动展开后再显示原文,避免常规工具把真正需要留意的权限挤出屏幕。- *- * 装入(全量清单)与更新(权限 diff)共用这一个折叠壳:标题 key 与计数由调用方给,- * 行本身作为 children 传入 —— 更新分支的行带 added/removed 徽章,装入分支不带。- */-function GhostToolPermissionGroup({- titleKey,- count,- children,-}: {- titleKey: 'toolsGroup' | 'toolsDiffGroup';- count: number;- children: ReactNode;-}) {- const { t } = useTranslation();- const [expanded, setExpanded] = useState(false);-- return (- <div className="my-1 rounded-xl border border-[var(--border-default)]">- <button- type="button"- aria-expanded={expanded}- onClick={() => setExpanded((value) => !value)}- className="flex w-full items-center gap-2 px-3 py-2.5 text-left text-13 text-[var(--confirm-desc)]"- >- <Wrench size={14} className="shrink-0 text-[var(--text-tertiary)]" />- <span className="flex-1">{t(`settings.ghosts.perm.${titleKey}`)}</span>- <span className="rounded-full bg-[var(--surface-chip)] px-2 py-0.5 text-11 text-[var(--text-secondary)]">- {t('settings.ghosts.perm.itemCount', { count })}- </span>- <ChevronDown- size={14}- className={cn(- 'shrink-0 text-[var(--text-tertiary)] transition-transform',- expanded && 'rotate-180',- )}- />- </button>- {expanded && (- <div className="border-t border-[var(--border-default)] px-3 py-2">{children}</div>- )}- </div>- );-}--/** 装入确认:全量逐项清单;工具长说明默认折叠,其余权限仍直接展示。 */-export function GhostPermissionList({ items }: { items: GhostPermissionItem[] }) {- const { t } = useTranslation();- if (items.length === 0) return null;- const firstToolIndex = items.findIndex((item) => item.kind === 'tool');- const toolItems = items.filter((item) => item.kind === 'tool');- const beforeTools =- firstToolIndex < 0- ? items- : items.slice(0, firstToolIndex).filter((item) => item.kind !== 'tool');- const afterTools =- firstToolIndex < 0 ? [] : items.slice(firstToolIndex).filter((item) => item.kind !== 'tool');-- return (- <div>- <div className="mb-1 flex items-center justify-between gap-3 text-12 font-medium text-[var(--text-tertiary)]">- <span>{t('settings.ghosts.perm.grantsTitle')}</span>- <span>{t('settings.ghosts.perm.itemCount', { count: items.length })}</span>- </div>- <GhostPermissionRows items={beforeTools} />- {toolItems.length > 0 && (- <GhostToolPermissionGroup titleKey="toolsGroup" count={toolItems.length}>- <GhostPermissionRows items={toolItems} />- </GhostToolPermissionGroup>- )}- <GhostPermissionRows items={afterTools} />- </div>- );-}--/** 主机验出的包来源/签名摘要;不读取作者可伪造的 ghost.json 文案。 */-export function GhostTrustSummary({ trust }: { trust: GhostTrustInfo }) {- const { t } = useTranslation();- const trusted = trust.level !== 'unverified';- const Icon = trusted ? BadgeCheck : ShieldAlert;- const labelKey =- trust.level === 'cindy-official'- ? 'official'- : trust.level === 'reviewed'- ? 'reviewed'- : trust.level === 'verified-publisher'- ? 'verifiedPublisher'- : trust.publisherSigned- ? 'signedUnverified'- : 'unsigned';- return (- <div className="mt-3 flex items-start gap-2 rounded-xl border border-[var(--border-default)] p-3">- <Icon size={16} className="mt-0.5 shrink-0 text-[var(--text-secondary)]" aria-hidden="true" />- <div className="min-w-0">- <p className="break-words text-13 font-medium leading-5 text-[var(--confirm-desc)]">- {t(`settings.ghosts.trust.${labelKey}`, {- publisher: trust.publisherName ?? t('settings.ghosts.trust.unknownPublisher'),- })}- </p>- <p className="text-12 leading-[1.5] text-[var(--text-tertiary)]">- {t(- trust.unknownReviewer- ? 'settings.ghosts.trust.unknownReviewerDetail'- : `settings.ghosts.trust.${labelKey}Detail`,- )}- </p>- </div>- </div>- );-}--export function GhostOauthClientChangedAlert({ className }: { className?: string }) {- const { t } = useTranslation();- return (- <div- role="alert"- className={cn(- 'flex items-start gap-2 rounded-lg bg-[var(--warning-bg-soft)] px-3 py-2 text-13 leading-5 text-[var(--text-secondary)]',- className,- )}- >- <ShieldAlert- size={16}- className="mt-0.5 shrink-0 text-[var(--warning-fg)]"- aria-hidden="true"- />- <span>{t('settings.ghosts.updateConfirm.oauthClientChanged')}</span>- </div>- );-}--/**- * Agent 发起装入时展示的来源信息(2026-08)。- *- * 目的:让用户在"刚让 Agent 干了一堆事、没有'我没让它装插件'清晰记忆"的状态下,- * 仍能一眼判断"这次不是我点的"。因此第一句直接点破发起者,再给出任务标题与源码- * 相对路径这两个**主机可核实**的事实作为判断依据(不是"可能有风险"的空话)。- *- * 用 warning 族语义 token(非 destructive 红):平常的手动安装框保持中性、不显示- * 本横幅,危险的那次才多出这一块——对比度本身就是信号,不靠"更醒目的红"训练- * 用户无脑点(那正是 https 证书警告的失败模式)。- *- * 高危档才追加 hazard 点破行;中危档只展示来源事实。是否 firstInstall / 展示哪些- * hazard 由调用方(installFlow)按风险分档决定,本组件只如实渲染。- */-export interface GhostAgentOriginInfo {- sessionTitle?: string;- sourceRelPath?: string;- /** 该 id 此前从未安装过(仅新装分支为 true;更新分支恒 false)。 */- firstInstall: boolean;- /** 高危点破(仅高危档传入 true;中危/低危全 false → 不出 callout)。 */- hazards: { skill: boolean; node: boolean; credential: boolean };- /** 凭证外发对象域名(credential 点破用;credential 为 true 时非空)。 */- credentialHosts: string[];-}--export function GhostAgentOriginBanner({ info }: { info: GhostAgentOriginInfo }) {- const { t } = useTranslation();- const title = info.sessionTitle?.trim();- const path = info.sourceRelPath?.trim();- const contextKey =- title && path ? 'context' : title ? 'contextNoPath' : path ? 'contextNoTitle' : 'contextBare';- return (- <div- role="alert"- className="flex items-start gap-2 rounded-xl bg-[var(--warning-bg-soft)] px-3 py-2.5"- >- <ShieldAlert- size={16}- className="mt-0.5 shrink-0 text-[var(--warning-fg)]"- aria-hidden="true"- />- <div className="min-w-0 flex-1 space-y-1">- <p className="text-13 font-medium leading-[1.5] text-[var(--confirm-desc)]">- {t('settings.ghosts.installConfirm.agentBanner.title')}- </p>- <p className="break-words text-12 leading-[1.5] text-[var(--text-secondary)]">- {t(`settings.ghosts.installConfirm.agentBanner.${contextKey}`, {- title: title ?? '',- path: path ?? '',- })}- </p>- <p className="text-12 leading-[1.5] text-[var(--text-secondary)]">- {t('settings.ghosts.installConfirm.agentBanner.advice')}- </p>- {info.firstInstall && (- <p className="text-12 leading-[1.5] text-[var(--text-tertiary)]">- {t('settings.ghosts.installConfirm.agentBanner.firstInstall')}- </p>- )}- {info.hazards.skill && (- <p className="text-12 font-medium leading-[1.5] text-[var(--warning-fg)]">- {t('settings.ghosts.installConfirm.agentBanner.hazardSkill')}- </p>- )}- {info.hazards.node && (- <p className="text-12 font-medium leading-[1.5] text-[var(--warning-fg)]">- {t('settings.ghosts.installConfirm.agentBanner.hazardNode')}- </p>- )}- {info.hazards.credential && (- <p className="break-words text-12 font-medium leading-[1.5] text-[var(--warning-fg)]">- {t('settings.ghosts.installConfirm.agentBanner.hazardCredential', {- hosts: info.credentialHosts.join('、'),- })}- </p>- )}- </div>- </div>- );-}--export function GhostManualSummary({ count }: { count: number }) {- const { t } = useTranslation();- if (count <= 0) return null;- return (- <div className="mt-3 flex items-center gap-2 text-12 leading-[1.5] text-[var(--text-tertiary)]">- <BookOpen size={14} className="shrink-0" aria-hidden="true" />- <span>{t('settings.ghosts.installConfirm.manualCount', { count })}</span>- </div>- );-}--/**- * 安装确认的紧凑内容区:简介可折叠,作者/版本单列。- * 安全相关权限不做总折叠,避免为了短而牺牲知情确认。- *- * 限高与滚动不在这里:共享 ConfirmDialog 已经持有 max-h-[85vh] + 内部滚动区,- * 并在弹窗出现/内容变高时闪一下滚动条。本组件曾自带 min(56vh, 520px) 滚动容器,- * 那会与共享层套成两层限高(2026-07-27 收口删除)——只留一个滚动主体,- * "还能往下看"这件事才有唯一口径。- */-export function GhostInstallReview({- description,- meta,- trust,- items,- manualCount = 0,- extra,- agentOrigin,- enableNotice,-}: {- description?: string;- meta: string;- trust: GhostTrustInfo;- items: GhostPermissionItem[];- manualCount?: number;- /** 追加内容(如 library 槽的存储位置行),渲染在权限清单下方。 */- extra?: ReactNode;- /** Agent 发起装入时的来源信息;手动入口不传 → 不展示来源横幅。 */- agentOrigin?: GhostAgentOriginInfo;- /**- * 启用结果说明(重新确认权限路径用):替代已删除的"立即开启"勾选框,如实- * 陈述确认后是保持沉睡还是保持启用,不再让用户在没有判断依据的勾选框上选。- */- enableNotice?: string;-}) {- const { t } = useTranslation();- const [descriptionExpanded, setDescriptionExpanded] = useState(false);- const canCollapseDescription = Boolean(- description && (description.length > 160 || description.includes('\n')),- );-- return (- <div>- {agentOrigin && (- <div className="mb-3">- <GhostAgentOriginBanner info={agentOrigin} />- </div>- )}- {description && (- <div>- <p- className={cn(- 'whitespace-pre-line break-words text-13 leading-[1.55] text-[var(--confirm-desc)]',- canCollapseDescription && !descriptionExpanded && 'line-clamp-3',- )}- >- {description}- </p>- {canCollapseDescription && (- <button- type="button"- aria-expanded={descriptionExpanded}- onClick={() => setDescriptionExpanded((value) => !value)}- className="mt-1 rounded-full text-12 text-[var(--text-secondary)] hover:text-[var(--text-primary)]"- >- {t(- descriptionExpanded- ? 'settings.ghosts.installConfirm.collapseDescription'- : 'settings.ghosts.installConfirm.expandDescription',- )}- </button>- )}- </div>- )}- <p className={cn('text-12 leading-[1.5] text-[var(--text-tertiary)]', description && 'mt-2')}>- {meta}- </p>- <GhostTrustSummary trust={trust} />- <GhostManualSummary count={manualCount} />- <div className="mt-3 border-t border-[var(--border-default)] pt-3">- <GhostPermissionList items={items} />- </div>- {extra ? <div className="mt-3">{extra}</div> : null}- {enableNotice && (- <p className="mt-3 text-12 leading-[1.5] text-[var(--text-tertiary)]">{enableNotice}</p>- )}- </div>- );-}--/**- * 更新确认:只展示权限变化(新增/移除),不变项折叠成一行计数。- *- * 工具行再折一层。原因是 diffGhostPermissionItems 会比对同一 key 的 detail:- * 作者只重写了工具说明,也算「移除旧行 + 新增新行」,N 个工具就产出 2N 行、- * 每行一整段接口文档。真正该被看见的权限变化(新增网络域名、新增凭证等)会被- * 顶到滚动区最上面、需要滚过一屏文档。所以 kind === 'tool' 的变化收进折叠组- * 只报数量,非 tool 的敏感变化仍旧直接亮出来。- */-export function GhostPermissionDiffView({ diff }: { diff: GhostPermissionDiff }) {- const { t } = useTranslation();- const changed = diff.added.length > 0 || diff.removed.length > 0;- if (!changed) {- return (- <div className="text-12 text-[var(--text-tertiary)]">- {t('settings.ghosts.perm.noChange')}- </div>- );- }- const isTool = (item: GhostPermissionItem) => item.kind === 'tool';- // 同 key 同时出现在 added 与 removed = 内容变化(工具说明重写、固定说明- // detailKey/detailArgs 随声明变化——如新增 network 槽后 code 的说明换版本)。- // 渲染成「移除+新增」两条会误读成权限被撤销又重加;配对成一条「更新」行,- // 仍然亮在第一屏(说明变化也是权限面变化,要知情),但语义如实。- const removedSensitiveByKey = new Map(- diff.removed.filter((item) => !isTool(item)).map((item) => [item.key, item] as const),- );- const updatedSensitive: GhostPermissionItem[] = [];- const addedSensitive: GhostPermissionItem[] = [];- for (const item of diff.added) {- if (isTool(item)) continue;- if (removedSensitiveByKey.delete(item.key)) updatedSensitive.push(item);- else addedSensitive.push(item);- }- const removedSensitive = [...removedSensitiveByKey.values()];- const addedTools = diff.added.filter(isTool);- const removedTools = diff.removed.filter(isTool);- const toolChangeCount = addedTools.length + removedTools.length;- return (- <div>- {addedSensitive.map((item) => (- <PermRow key={`added:${item.key}`} item={item} badge="added" />- ))}- {updatedSensitive.map((item) => (- <PermRow key={`updated:${item.key}`} item={item} badge="updated" />- ))}- {removedSensitive.map((item) => (- <PermRow key={`removed:${item.key}`} item={item} badge="removed" />- ))}- {toolChangeCount > 0 && (- <GhostToolPermissionGroup titleKey="toolsDiffGroup" count={toolChangeCount}>- {addedTools.map((item) => (- <PermRow key={`added:${item.key}`} item={item} badge="added" />- ))}- {removedTools.map((item) => (- <PermRow key={`removed:${item.key}`} item={item} badge="removed" />- ))}- </GhostToolPermissionGroup>- )}- {diff.unchanged.length > 0 && (- <div className="mt-1 text-12 text-[var(--text-tertiary)]">- {t('settings.ghosts.perm.unchanged', { count: diff.unchanged.length })}- </div>- )}- </div>- );-}--/**- * 更新确认的内容区:来源/签名摘要(可选)+ 权限 diff。- *- * 更新确认有两个入口 —— 本地 .cindy 换版走 installFlow.confirmAndRunUpdate,- * 市场更新走 GhostPluginPage.handleMarketUpdate。此前两边各写一遍 content,- * 市场那条还漏了 trust 卡。收成一个组件后,内容层的调整(如上面的工具折叠)- * 只改一处,不会再出现"第三个入口又漏一次"。- *- * trust 可选:市场路径当前拿不到与本地包同口径的 GhostTrustInfo,不传即不渲染- * 来源卡 —— 不许诺自己没验过的来源,也不拿假数据占位。- */-export function GhostUpdateReview({- trust,- diff,- manualCount = 0,- agentOrigin,-}: {- trust?: GhostTrustInfo;- diff: GhostPermissionDiff;- manualCount?: number;- /** Agent 发起的更新时的来源信息;手动更新不传 → 不展示来源横幅。 */- agentOrigin?: GhostAgentOriginInfo;-}) {- return (- <div>- {agentOrigin && (- <div className="mb-3">- <GhostAgentOriginBanner info={agentOrigin} />- </div>- )}- {trust && <GhostTrustSummary trust={trust} />}- {diff.builtinOauthClientChanged ? (- <GhostOauthClientChangedAlert className={trust ? 'mt-3' : undefined} />- ) : null}- <GhostManualSummary count={manualCount} />- <div className={cn((trust || diff.builtinOauthClientChanged || manualCount > 0) && 'mt-3')}>- <GhostPermissionDiffView diff={diff} />- </div>- </div>- );-}diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPanelBubbleLayer.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPanelBubbleLayer.test.tsxindex 6c890fefaf..b5f2b39a09 100644--- a/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPanelBubbleLayer.test.tsx+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPanelBubbleLayer.test.tsx@@ -37,7 +37,6 @@ function ghost(id: string, enabled = true): InstalledGhost {version: '1.0.0',kind: 'chip',entry: 'main.js',- slots: ['panel'],panel: { title: `${id} 面板`, html: 'panel.html' },};return {diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPermissionList.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPermissionList.test.tsxdeleted file mode 100644index 05abe8e781..0000000000--- a/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPermissionList.test.tsx+++ /dev/null@@ -1,301 +0,0 @@-// @vitest-environment jsdom-/**- * GhostPermissionList.test.tsx — 装入/更新确认框权限清单组件。- * 条目推导已在 shared/__tests__/ghost.test.ts 锁死,这里只验展示契约:- * 装入清单逐项渲染(含作者自由文本 detail 与主机固定说明 detailKey)、- * 更新 diff 只亮变化项 + 不变折叠、权限无变化的收敛文案。- */-import { cleanup, fireEvent, render, screen } from '@testing-library/react';-import { afterEach, describe, expect, it, vi } from 'vitest';--import type { GhostManifest } from '../../../shared/ghost';-import { diffGhostPermissionItems, ghostPermissionItems } from '../../../shared/ghost';-import {- GhostInstallReview,- GhostManualSummary,- GhostPermissionDiffView,- GhostPermissionList,- GhostUpdateReview,-} from '../GhostPermissionList';--// 仓库同款 i18n mock:t 返回 key 本身(带参时拼上参数便于断言)。-vi.mock('react-i18next', () => ({- useTranslation: () => ({- t: (key: string, args?: Record<string, unknown>) =>- args && Object.keys(args).length > 0 ? `${key}:${JSON.stringify(args)}` : key,- }),-}));--afterEach(cleanup);--const chip = (): GhostManifest => ({- schemaVersion: 2,- id: 'art-like',- name: '画图',- version: '1.0.0',- kind: 'chip',- entry: 'main.js',- slots: ['panel', 'cindy', 'tool'],- cindy: { image: ['generate', 'edit'] },- tools: [{ name: 'gen_image', description: '根据描述出图' }],- command: '画图',- panel: { title: '画廊', html: 'panel.html' },-});--describe('GhostPermissionList(装入全量清单)', () => {- it('随包手册是独立信息行,正数显示,零篇不占位', () => {- const { rerender } = render(<GhostManualSummary count={2} />);- expect(screen.getByText(/installConfirm\.manualCount:.*"count":2/)).toBeTruthy();- rerender(<GhostManualSummary count={0} />);- expect(screen.queryByText(/installConfirm\.manualCount/)).toBeNull();- });-- it('常规权限直接展示,工具长说明默认折叠并可按需展开', () => {- render(<GhostPermissionList items={ghostPermissionItems(chip())} />);- expect(screen.getByText('settings.ghosts.perm.grantsTitle')).toBeTruthy();- expect(screen.getByText('settings.ghosts.perm.cindyImageGenerate')).toBeTruthy();- expect(screen.getByText('settings.ghosts.perm.cindyImageEdit')).toBeTruthy();- expect(screen.getByText('settings.ghosts.perm.toolsGroup')).toBeTruthy();- expect(screen.queryByText(/perm\.tool:.*gen_image/)).toBeNull();- expect(screen.queryByText('根据描述出图')).toBeNull();- const toolsTrigger = screen.getByRole('button', { expanded: false });- fireEvent.click(toolsTrigger);- expect(screen.getByRole('button', { expanded: true })).toBeTruthy();- expect(screen.getByText(/perm\.tool:.*gen_image/)).toBeTruthy();- expect(screen.getByText('根据描述出图')).toBeTruthy(); // 作者自由文本如实展示- expect(screen.getByText(/perm\.command:.*画图/)).toBeTruthy();- expect(screen.getByText(/perm\.panelLeft:.*画廊/)).toBeTruthy();- expect(screen.getByText('settings.ghosts.perm.code')).toBeTruthy();- expect(screen.getByText('settings.ghosts.perm.codeDetail')).toBeTruthy(); // 主机固定说明走 i18n- });-- it('安装简介过长时默认收起,可展开完整原文', () => {- const description = '这是很长的意识介绍。'.repeat(20);- const { container } = render(- <GhostInstallReview- description={description}- meta="作者 Cindy · 版本 1.0.0"- trust={{- level: 'unverified',- publisherSigned: false,- publisherVerified: false,- reviewed: false,- }}- items={[]}- />,- );- // 限高与滚动由共享 ConfirmDialog 持有,本组件不许再自套一层滚动容器- // (两层限高 → "到底了没有"取决于谁先触底)。- const root = container.firstElementChild as HTMLElement;- expect(root.classList.contains('overflow-y-auto')).toBe(false);- expect(root.style.maxHeight).toBe('');- const trigger = screen.getByRole('button', { expanded: false });- expect(trigger.textContent).toBe('settings.ghosts.installConfirm.expandDescription');- fireEvent.click(trigger);- expect(screen.getByRole('button', { expanded: true }).textContent).toBe(- 'settings.ghosts.installConfirm.collapseDescription',- );- expect(screen.getByText('作者 Cindy · 版本 1.0.0')).toBeTruthy();- });-- it('空清单渲染为空(不出孤零零的标题)', () => {- const { container } = render(<GhostPermissionList items={[]} />);- expect(container.innerHTML).toBe('');- });-- it('ios-simulator 槽如实披露 Host-owned 控制边界', () => {- const simulator: GhostManifest = {- ...chip(),- slots: [...chip().slots, 'ios-simulator'],- };- render(<GhostPermissionList items={ghostPermissionItems(simulator)} />);- expect(screen.getByText('settings.ghosts.perm.iosSimulator')).toBeTruthy();- expect(screen.getByText('settings.ghosts.perm.iosSimulatorDetail')).toBeTruthy();- });-- it('network 槽:域名/凭证逐条渲染,code 沙箱说明切分档版', () => {- const net: GhostManifest = {- ...chip(),- slots: [...chip().slots, 'network'],- network: {- hosts: ['api.search.brave.com', '*.tavily.com'],- secrets: [- {- key: 'brave_api_key',- label: 'Brave Key',- inject: { header: 'X-Subscription-Token', format: '{value}' },- },- ],- },- };- render(<GhostPermissionList items={ghostPermissionItems(net)} />);- expect(screen.getByText(/perm\.networkHost:.*api\.search\.brave\.com/)).toBeTruthy();- expect(screen.getByText(/perm\.networkHost:.*\*\.tavily\.com/)).toBeTruthy();- expect(screen.getByText(/perm\.networkSecret:.*Brave Key/)).toBeTruthy();- // user 凭证只剩意识收单档(宿主凭证渲染 2026-07-13 退役)。- expect(screen.getByText('settings.ghosts.perm.networkSecretGhostInputDetail')).toBeTruthy();- // "无网络访问"的旧说明对 network 意识是假话,必须换分档版。- expect(screen.getByText('settings.ghosts.perm.codeDetailNetwork')).toBeTruthy();- expect(screen.queryByText('settings.ghosts.perm.codeDetail')).toBeNull();- });-- it('Cindy Web Search 能力在安装权限清单中单独披露', () => {- const search: GhostManifest = {- ...chip(),- cindy: { search: ['web'] },- };- render(<GhostPermissionList items={ghostPermissionItems(search)} />);- expect(screen.getByText('settings.ghosts.perm.cindySearchWeb')).toBeTruthy();- expect(screen.getByText('settings.ghosts.perm.cindySearchWebDetail')).toBeTruthy();- });-- it('Node 持久凭证单独披露明文注入范围', () => {- const node: GhostManifest = {- ...chip(),- slots: [...chip().slots, 'node'],- settingsHtml: 'settings.html',- node: {- entry: 'worker.cjs',- protocol: 'json-rpc-stdio',- secretBindings: [- {- key: 'mail_authorization_code',- label: '邮箱授权码',- methods: ['account/connect', 'mail/action'],- },- ],- },- };- render(<GhostPermissionList items={ghostPermissionItems(node)} />);- expect(screen.getByText(/perm\.nodeSecret:.*邮箱授权码/)).toBeTruthy();- expect(screen.getByText('settings.ghosts.perm.nodeSecretDetail')).toBeTruthy();- expect(screen.getByText(/account\/connect\s+mail\/action/)).toBeTruthy();- });-});--describe('GhostPermissionDiffView(更新权限 diff)', () => {- it('只亮变化项:非工具变化直接带徽章,工具变化折叠计数,不变项折叠成计数行', () => {- const next: GhostManifest = {- ...chip(),- version: '2.0.0',- cindy: { image: ['generate'] }, // 移除 edit- tools: [...(chip().tools ?? []), { name: 'style_image', description: '风格化' }], // 新增- };- render(<GhostPermissionDiffView diff={diffGhostPermissionItems(chip(), next)} />);- // 非工具的敏感变化直接亮出来。- expect(screen.getByText('settings.ghosts.perm.cindyImageEdit')).toBeTruthy();- expect(screen.getByText('settings.ghosts.perm.removed')).toBeTruthy();- // 工具变化只报数量,原文要展开才看;新增徽章跟着行进折叠区。- expect(screen.getByText('settings.ghosts.perm.toolsDiffGroup')).toBeTruthy();- expect(screen.getByText(/perm\.itemCount:.*"count":1/)).toBeTruthy();- expect(screen.queryByText(/perm\.tool:.*style_image/)).toBeNull();- expect(screen.queryByText('settings.ghosts.perm.added')).toBeNull();- fireEvent.click(screen.getByRole('button', { expanded: false }));- expect(screen.getByText(/perm\.tool:.*style_image/)).toBeTruthy();- expect(screen.getByText('settings.ghosts.perm.added')).toBeTruthy();- expect(screen.getByText(/perm\.unchanged:.*"count":5/)).toBeTruthy();- // 不变项本体不渲染(折叠):cindyImageGenerate 不该出现在行里。- expect(screen.queryByText('settings.ghosts.perm.cindyImageGenerate')).toBeNull();- });-- it('只改了工具说明时,2N 条工具行全部收进折叠区,不挤走真正的权限变化', () => {- const prev: GhostManifest = {- ...chip(),- tools: [- { name: 'gen_image', description: '旧说明 A' },- { name: 'style_image', description: '旧说明 B' },- ],- };- const next: GhostManifest = {- ...prev,- version: '2.0.0',- // 工具说明重写 → diff 记成「移除旧行 + 新增新行」,2 个工具产出 4 行。- tools: [- { name: 'gen_image', description: '新说明 A(整段接口文档)' },- { name: 'style_image', description: '新说明 B(整段接口文档)' },- ],- slots: [...prev.slots, 'network'],- network: { hosts: ['api.example.com'] },- };- render(<GhostPermissionDiffView diff={diffGhostPermissionItems(prev, next)} />);- // 真正的权限变化(新增网络域名)仍在折叠区之外,第一屏就能看到。- expect(screen.getByText(/perm\.networkHost:.*api\.example\.com/)).toBeTruthy();- expect(screen.getByText('settings.ghosts.perm.added')).toBeTruthy();- // 新增 network 槽后 code 项的主机固定说明换版本(codeDetail → codeDetailNetwork):- // 指纹含 detailKey 后这算权限面变化,但同 key 配对成一条「更新」行,- // 不渲染成「移除+新增」两条误导用户。- expect(screen.getByText('settings.ghosts.perm.updated')).toBeTruthy();- expect(screen.getByText('settings.ghosts.perm.code')).toBeTruthy();- expect(screen.getByText('settings.ghosts.perm.codeDetailNetwork')).toBeTruthy();- expect(screen.queryByText('settings.ghosts.perm.removed')).toBeNull();- // 4 条工具行收进一个折叠组,原文默认不渲染。- expect(screen.getByText(/perm\.itemCount:.*"count":4/)).toBeTruthy();- expect(screen.queryByText('新说明 A(整段接口文档)')).toBeNull();- expect(screen.queryByText('旧说明 B')).toBeNull();- fireEvent.click(screen.getByRole('button', { expanded: false }));- expect(screen.getByText('新说明 A(整段接口文档)')).toBeTruthy();- expect(screen.getByText('旧说明 B')).toBeTruthy();- });-- it('权限无变化 → 单行收敛文案,无任何条目', () => {- render(- <GhostPermissionDiffView- diff={diffGhostPermissionItems(chip(), { ...chip(), version: '1.0.1' })}- />,- );- expect(screen.getByText('settings.ghosts.perm.noChange')).toBeTruthy();- expect(screen.queryByText('settings.ghosts.perm.added')).toBeNull();- expect(screen.queryByText('settings.ghosts.perm.unchanged', { exact: false })).toBeNull();- });-});--describe('GhostUpdateReview(更新确认内容区,两个入口共用)', () => {- const next = (): GhostManifest => ({- ...chip(),- version: '2.0.0',- slots: [...chip().slots, 'network'],- network: { hosts: ['api.example.com'] },- });-- it('传了 trust 就渲染来源卡,并与 diff 同时展示', () => {- render(- <GhostUpdateReview- trust={{- level: 'unverified',- publisherSigned: false,- publisherVerified: false,- reviewed: false,- }}- diff={diffGhostPermissionItems(chip(), next())}- manualCount={2}- />,- );- expect(screen.getByText(/trust\.unsigned:/)).toBeTruthy(); // 带 publisher 参数的标题行- expect(screen.getByText('settings.ghosts.trust.unsignedDetail')).toBeTruthy();- expect(screen.getByText(/perm\.networkHost:.*api\.example\.com/)).toBeTruthy();- expect(screen.getByText(/installConfirm\.manualCount:.*"count":2/)).toBeTruthy();- });-- it('没有可展示的来源事实时不渲染来源卡,也不拿假数据占位', () => {- render(<GhostUpdateReview diff={diffGhostPermissionItems(chip(), next())} />);- expect(screen.queryByText(/trust\.unsigned/)).toBeNull();- expect(screen.queryByText(/trust\.unknownPublisher/)).toBeNull();- expect(screen.getByText(/perm\.networkHost:.*api\.example\.com/)).toBeTruthy();- });-- it('内置 OAuth clientId 变化时提示更新后需要重新连接', () => {- const diff = diffGhostPermissionItems(chip(), next());- render(<GhostUpdateReview diff={{ ...diff, builtinOauthClientChanged: true }} />);- expect(screen.getByRole('alert').textContent).toBe(- 'settings.ghosts.updateConfirm.oauthClientChanged',- );- });-- it('不自套限高滚动区(高度归共享 ConfirmDialog)', () => {- const { container } = render(- <GhostUpdateReview diff={diffGhostPermissionItems(chip(), next())} />,- );- const scrollers = container.querySelectorAll('.overflow-y-auto');- expect(scrollers.length).toBe(0);- });-});diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostInstallRisk.test.ts b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostInstallRisk.test.tsdeleted file mode 100644index 03d3a1f08c..0000000000--- a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostInstallRisk.test.ts+++ /dev/null@@ -1,69 +0,0 @@-import { describe, expect, it } from 'vitest';--import { assessGhostInstallRisk } from '../ghostInstallRisk';-import type { GhostPermissionItem } from '../../../shared/ghost';--/** 只给分档器关心的 key/labelArgs;其余字段占位,分档不看它们。 */-function item(key: string, labelArgs?: Record<string, string>): GhostPermissionItem {- return { key, kind: 'tool', labelKey: 'tool', ...(labelArgs ? { labelArgs } : {}) };-}--describe('assessGhostInstallRisk · 分档', () => {- it('skill / node / 凭证 / agent 后台 / agent 派活 都是高危', () => {- for (const key of [- 'skill:my-skill',- 'node:execute',- 'node:secret:k:main.js:call',- 'network:secret:token',- 'agent:background',- 'agent:errand',- ]) {- expect(assessGhostInstallRisk([item(key)]).tier).toBe('high');- }- });-- it('oauth 凭证(network:secret: 前缀)判高危', () => {- // ghostPermissionItems 里 oauth 凭证 key = `network:secret:<key>`。- expect(assessGhostInstallRisk([item('network:secret:jira')]).tier).toBe('high');- });-- it('fs / 出网域名 / 自动化 是中危', () => {- for (const key of ['fs', 'network:host:api.example.com', 'agent:schedule']) {- expect(assessGhostInstallRisk([item(key)]).tier).toBe('mid');- }- });-- it('纯沙箱工具 / 卡片 / 面板 / 聊天指令是低危', () => {- const low = [item('tool:hello'), item('card'), item('panel'), item('command:foo')];- expect(assessGhostInstallRisk(low).tier).toBe('low');- });-- it('高危优先于中危:同时有 fs 与 node 时整体判高危', () => {- expect(assessGhostInstallRisk([item('fs'), item('node:execute')]).tier).toBe('high');- });-- it('中危优先于低危:同时有 tool 与 fs 时整体判中危', () => {- expect(assessGhostInstallRisk([item('tool:x'), item('fs')]).tier).toBe('mid');- });-- it('命中标记与出网域名如实汇总', () => {- const assessment = assessGhostInstallRisk([- item('skill:s'),- item('network:secret:tok'),- item('network:host:a.example.com', { host: 'a.example.com' }),- item('network:host:b.example.com', { host: 'b.example.com' }),- ]);- expect(assessment.tier).toBe('high');- expect(assessment.hazards.skill).toBe(true);- expect(assessment.hazards.secret).toBe(true);- expect(assessment.hazards.node).toBe(false);- expect(assessment.networkHosts).toEqual(['a.example.com', 'b.example.com']);- });-- it('空清单为低危,无命中,无域名', () => {- const assessment = assessGhostInstallRisk([]);- expect(assessment.tier).toBe('low');- expect(assessment.networkHosts).toEqual([]);- expect(Object.values(assessment.hazards).every((v) => v === false)).toBe(true);- });-});diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPanels.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPanels.test.tsxindex f12391eab3..1b53dee7b7 100644--- a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPanels.test.tsx+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPanels.test.tsx@@ -45,7 +45,6 @@ function ghost(id: string, panel?: GhostManifest['panel'] | null, enabled = trueversion: '1.0.0',kind: 'chip',entry: 'main.js',- slots: panel === null ? ['tool'] : ['panel'],...(panel === null ? {} : { panel: panel ?? { title: id, html: 'panel.html' } }),};return {diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPluginViewModel.test.ts b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPluginViewModel.test.tsindex 4c83b39813..51cc0fa894 100644--- a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPluginViewModel.test.ts+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPluginViewModel.test.ts@@ -33,7 +33,7 @@ function manifest(overrides: Partial<GhostManifest> = {}): GhostManifest {whenToUse: 'When the user needs media generation.',kind: 'chip',entry: 'main.js',- slots: ['tool', 'network', 'card'],+ card: {},tools: [{ name: 'submit_gen_image', description: 'Generate an image.' },{ name: 'download_file', description: 'Download a file.' },@@ -238,12 +238,12 @@ describe('ghostPluginViewModel', () => {});});- it('projects the iOS Simulator slot as an explicit Host capability action', () => {+ it('projects the iOS Simulator declaration as an explicit Host capability action', () => {const item = toGhostPluginListItem(installed({manifest: manifest({command: undefined,- slots: ['skill', 'ios-simulator'],+ iosSimulator: true,tools: undefined,network: undefined,}),@@ -371,7 +371,7 @@ describe('ghostPluginViewModel', () => {it('derives detail permissions and runtime declarations from the manifest', () => {const detail = toGhostPluginDetail(installed());- expect(detail.contents).toEqual(['code', 'slotTool', 'slotNetwork', 'slotCard']);+ expect(detail.contents).toEqual(['code', 'slotTool', 'slotCard', 'slotNetwork']);expect(detail.tools.map((tool) => tool.name)).toEqual(['submit_gen_image', 'download_file']);expect(detail.panelMinWidth).toBeNull();expect(detail.installDir).toBe('/tmp/cindy-brain/xd-mivo');@@ -397,7 +397,7 @@ describe('ghostPluginViewModel', () => {tools: undefined,network: undefined,command: undefined,- slots: ['tool'],+ card: undefined,}),}),);@@ -413,7 +413,6 @@ describe('ghostPluginViewModel', () => {const detail = toGhostPluginDetail(installed({manifest: manifest({- slots: ['panel', 'cindy'],panel: { html: 'panel.html', minWidth: 360 },cindy: { image: ['generate', 'edit'], video: ['generate'] },}),diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/installErrorKey.test.ts b/apps/desktop/src/renderer/cindy-brain/__tests__/installErrorKey.test.tsindex 6ec7412f22..3b73725df7 100644--- a/apps/desktop/src/renderer/cindy-brain/__tests__/installErrorKey.test.ts+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/installErrorKey.test.ts@@ -10,15 +10,15 @@ describe('ghostInstallErrorKey', () => {'settings.ghosts.errors.hostUnsupported',);expect(ghostInstallErrorKey('GHOST_FILE_INVALID')).toBe('settings.ghosts.errors.fileInvalid');+ expect(ghostInstallErrorKey('PRECONDITION_FAILED')).toBe(+ 'settings.ghosts.errors.generic',+ );});it('maps Broker authorization failures without changing generic invalid-file copy', () => {expect(ghostInstallErrorKey('GHOST_BROKER_MANUAL_INSTALL_NOT_AUTHORIZED')).toBe('settings.ghosts.errors.brokerManualInstallNotAuthorized',);- expect(ghostInstallErrorKey('GHOST_BROKER_NOT_AUTHORIZED')).toBe(- 'settings.ghosts.errors.brokerNotAuthorized',- );expect(ghostInstallErrorKey('GHOST_BROKER_REDIRECT_PORT_REQUIRED')).toBe('settings.ghosts.errors.brokerRedirectPortRequired',);@@ -28,16 +28,13 @@ describe('ghostInstallErrorKey', () => {});it.each(['zh-CN', 'en', 'ja', 'ko', 'zh-TW'])(- 'keeps both Broker authorization reasons actionable in %s',+ 'keeps the local-install Broker authorization reason actionable in %s',(locale) => {- for (const code of [- 'GHOST_BROKER_MANUAL_INSTALL_NOT_AUTHORIZED',- 'GHOST_BROKER_NOT_AUTHORIZED',- ]) {- const message = i18n.getFixedT(locale)(ghostInstallErrorKey(code)).toString();- expect(message).toContain('ghost_forge_pack');- expect(message).not.toBe(i18n.getFixedT(locale)('settings.ghosts.errors.fileInvalid'));- }+ const message = i18n+ .getFixedT(locale)(ghostInstallErrorKey('GHOST_BROKER_MANUAL_INSTALL_NOT_AUTHORIZED'))+ .toString();+ expect(message).not.toContain('ghost_forge_pack');+ expect(message).not.toBe(i18n.getFixedT(locale)('settings.ghosts.errors.fileInvalid'));},);@@ -85,29 +82,28 @@ describe('ghostInstallErrorKey', () => {);it.each([- { locale: 'zh-CN', fragments: ['拖入', '选择文件', 'ghost_forge_pack', '自定义插件市场'] },+ { locale: 'zh-CN', fragments: ['拖入', '选择文件', '自定义插件市场'] },{locale: 'en',fragments: ['dragging in a package','choosing a file',- 'ghost_forge_pack','custom plugin marketplace',],},{locale: 'ja',- fragments: ['ドラッグ', 'ファイル選択', 'ghost_forge_pack', 'カスタムプラグインマーケット'],+ fragments: ['ドラッグ', 'ファイル選択', 'カスタムプラグインマーケット'],},{locale: 'ko',- fragments: ['끌어다 놓기', '파일 선택', 'ghost_forge_pack', '사용자 지정 플러그인 마켓'],+ fragments: ['끌어다 놓기', '파일 선택', '사용자 지정 플러그인 마켓'],},{locale: 'zh-TW',- fragments: ['拖入', '選取檔案', 'ghost_forge_pack', '自訂插件市場'],+ fragments: ['拖入', '選取檔案', '自訂插件市場'],},- ])('keeps all four user install channels in the $locale marketplace guide', ({ locale, fragments }) => {+ ])('keeps all three user install channels in the $locale marketplace guide', ({ locale, fragments }) => {const rawMessage = i18n.getResource(locale,'common',@@ -117,6 +113,7 @@ describe('ghostInstallErrorKey', () => {// 只钉四个必要语义点,排除说明被重新写窄成仅禁止某一个装入来源。expect(rawMessage).toEqual(expect.any(String));for (const fragment of fragments) expect(rawMessage).toContain(fragment);+ expect(rawMessage).not.toContain('ghost_forge_pack');});it.each([diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/installFlow.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/installFlow.test.tsxindex 7419e31df0..92bf87b1fd 100644--- a/apps/desktop/src/renderer/cindy-brain/__tests__/installFlow.test.tsx+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/installFlow.test.tsx@@ -1,110 +1,72 @@-/** installFlow.test — 装入确认卡权限清单确认后直接交给 Main 落盘(无二次弹窗)。 */+/** installFlow.test — 用户明确选择本地包后直接安装/更新,不追加权限确认。 */import { afterEach, describe, expect, it, vi } from 'vitest';import { toast } from '@/lib/toast';-import { confirmAndInstallGhost } from '../installFlow';-import type { InstalledGhost } from '../../../shared/ghost';+import { installGhostFromFile } from '../installFlow';vi.mock('@/lib/toast', () => ({toast: { success: vi.fn(), error: vi.fn() },}));-// node 环境无 window:logger 桩掉。-vi.mock('@/lib/logger', () => ({- createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),-}));const baseManifest = {- schemaVersion: 2 as const,+ schemaVersion: 3 as const,id: 'node-ghost',name: 'Node Ghost',version: '1.0.0',+ minCindyVersion: '1.0.0',kind: 'chip' as const,entry: 'main.js',- slots: ['node'] as const,- node: { entry: 'node/worker.cjs', protocol: 'json-rpc-stdio' as const },+ capabilities: [{ type: 'node-runtime' as const, entry: 'node/worker.cjs' }],};-function setupWindow(- manifest: object,- installResult: { ghost: { manifest: object } } = { ghost: { manifest } },- installedGhosts: InstalledGhost[] = [],-) {- const install = vi.fn(async () => installResult);- const update = vi.fn(async () => installResult);- const electronAPI = {- ghosts: {- inspect: vi.fn(async () => ({- manifest,- packageSha256: 'a'.repeat(64),- trust: {- level: 'unverified',- publisherSigned: false,- publisherVerified: false,- reviewed: false,+function setupWindow(manifest: object, installed: object[] = []) {+ const install = vi.fn(async () => ({+ ghost: { manifest, dir: '/tmp/installed', enabled: true },+ }));+ const update = vi.fn(async () => ({+ ghost: { manifest, dir: '/tmp/installed', enabled: true },+ }));+ Object.defineProperty(globalThis, 'window', {+ value: {+ electronAPI: {+ appVersion: '1.0.0',+ ghosts: {+ inspect: vi.fn(async () => ({+ manifest,+ packageSha256: 'a'.repeat(64),+ unsupportedSlots: [],+ trust: {+ level: 'unverified',+ publisherSigned: false,+ publisherVerified: false,+ reviewed: false,+ },+ })),+ listSync: vi.fn(() => ({ ghosts: installed })),+ install,+ update,},- })),- listSync: vi.fn(() => ({ ghosts: installedGhosts })),- install,- update,- abandonPackTicket: vi.fn(async () => ({ ok: true })),+ },},- };- Object.defineProperty(globalThis, 'window', {- value: { electronAPI },configurable: true,});return { install, update };}-function deps(confirm: (options: unknown) => Promise<boolean>) {- return {- t: ((key: string) => key) as never,- confirm,- };-}--/** agent-forge 来源:触发来源横幅与高危加重。 */-const AGENT_ORIGIN = {- kind: 'agent-forge' as const,- sessionTitle: '处理外部文档',- sourceRelPath: 'plugins/evil',-};-afterEach(() => {vi.clearAllMocks();- vi.restoreAllMocks();Reflect.deleteProperty(globalThis, 'window');});-describe('installFlow · 装入确认', () => {- it('带 manual 的包把篇数传给装入确认信息行', async () => {- const manifest = {- ...baseManifest,- manual: {- items: [- { dir: 'manual/ops', name: 'ops', description: '操作手册' },- { dir: 'manual/faq', name: 'faq', description: '常见问题' },- ],- },- };- setupWindow(manifest);- const confirm = vi.fn(async (_options: unknown) => true);- await confirmAndInstallGhost('/tmp/manual.cindy', deps(confirm));- const options = confirm.mock.calls[0]?.[0] as {- content?: { props?: { manualCount?: number } };- };- expect(options.content?.props?.manualCount).toBe(2);- });-- it('新装一律直接生效(勾选框已删):install 带 enable:true', async () => {+describe('installFlow · 本地包安装', () => {+ it('直接启用安装,并把真实包摘要交给 Main', async () => {const { install } = setupWindow(baseManifest);- const confirm = vi.fn(async (_options: unknown) => true);- await confirmAndInstallGhost('/tmp/node.cindy', deps(confirm));+ await installGhostFromFile('/tmp/node.cindy', {+ t: ((key: string) => key) as never,+ });- // confirm 是唯一确认层(权限清单含 Node 高风险行);无勾选框、装入即生效。- expect(confirm).toHaveBeenCalledTimes(1);expect(install).toHaveBeenCalledWith('/tmp/node.cindy', {enable: true,expectedPackageSha256: 'a'.repeat(64),@@ -112,178 +74,62 @@ describe('installFlow · 装入确认', () => {expect(toast.success).toHaveBeenCalledTimes(1);});- it('手动来源不加来源横幅、不加手输 id 闸', async () => {- const { install } = setupWindow(baseManifest);- const confirm = vi.fn(async (_options: unknown) => true);-- // 不传 origin = 手动入口(拖入/双击/设置页选文件)。- await confirmAndInstallGhost('/tmp/plain.cindy', deps(confirm));-- const options = confirm.mock.calls[0]?.[0] as {- content?: { props?: { agentOrigin?: unknown } };- requireTypedConfirmation?: unknown;- };- expect(options.content?.props?.agentOrigin).toBeUndefined();- expect(options.requireTypedConfirmation).toBeUndefined();- expect(install).toHaveBeenCalledTimes(1);- });-});--describe('installFlow · Agent 发起分级加重', () => {- it('高危(node)+ Agent 发起 → 手输插件 id 才能确认,横幅点破 node', async () => {- setupWindow(baseManifest);- const confirm = vi.fn(async (_options: unknown) => true);-- await confirmAndInstallGhost('/tmp/node.cindy', deps(confirm), AGENT_ORIGIN);-- const options = confirm.mock.calls[0]?.[0] as {- content?: { props?: { agentOrigin?: { firstInstall: boolean; hazards: { node: boolean } } } };- requireTypedConfirmation?: { expected: string };- };- // 手输 id 闸:目标串 = 插件 id。- expect(options.requireTypedConfirmation?.expected).toBe('node-ghost');- // 来源横幅:首次安装 + node 高危点破。- expect(options.content?.props?.agentOrigin?.firstInstall).toBe(true);- expect(options.content?.props?.agentOrigin?.hazards.node).toBe(true);- });-- it('低危(card)+ Agent 发起 → 只加来源横幅,不加手输 id 闸', async () => {- const manifest = { ...baseManifest, slots: ['card'], node: undefined };- setupWindow(manifest);- const confirm = vi.fn(async (_options: unknown) => true);-- await confirmAndInstallGhost('/tmp/card.cindy', deps(confirm), AGENT_ORIGIN);-- const options = confirm.mock.calls[0]?.[0] as {- content?: { props?: { agentOrigin?: { hazards: { node: boolean; skill: boolean } } } };- requireTypedConfirmation?: unknown;+ it('tab 型插件安装后由具备宿主的入口直接打开面板', async () => {+ const manifest = {+ ...baseManifest,+ id: 'tab-demo',+ panel: { html: 'panel.html', position: 'tab' as const },};- expect(options.requireTypedConfirmation).toBeUndefined();- // 横幅仍在(来源事实),但无高危点破。- expect(options.content?.props?.agentOrigin).toBeDefined();- expect(options.content?.props?.agentOrigin?.hazards.node).toBe(false);- expect(options.content?.props?.agentOrigin?.hazards.skill).toBe(false);- });-- it('用户取消手输 id(confirm 返回 false)→ 不落盘', async () => {- const { install } = setupWindow(baseManifest);- const confirm = vi.fn(async (_options: unknown) => false);+ const { install } = setupWindow(manifest);+ const openPluginPanel = vi.fn();- await confirmAndInstallGhost('/tmp/node.cindy', deps(confirm), AGENT_ORIGIN);+ await installGhostFromFile('/tmp/tab.cindy', {+ t: ((key: string) => key) as never,+ openPluginPanel,+ });- expect(install).not.toHaveBeenCalled();+ expect(install).toHaveBeenCalledWith('/tmp/tab.cindy', {+ enable: true,+ expectedPackageSha256: 'a'.repeat(64),+ });+ expect(openPluginPanel).toHaveBeenCalledWith('tab-demo');});-});-describe('installFlow · approved update binding', () => {- function installed(- approval: InstalledGhost['approval'],- ): InstalledGhost {- return {- manifest: {- ...baseManifest,- version: '0.9.0',- slots: ['card'],- node: undefined,+ it('同 id 已安装时直接原位更新,并绑定当前安装 receipt', async () => {+ const installed = {+ manifest: { ...baseManifest, version: '0.9.0' },+ dir: '/tmp/installed',+ enabled: false,+ approval: {+ state: 'approved',+ revision: '00000000-0000-4000-8000-000000000001',},- dir: '/brain/node-ghost',- enabled: true,- approval,};- }+ const { install, update } = setupWindow(baseManifest, [installed]);- it('passes the reviewed approved revision to Main', async () => {- const current = installed({- state: 'approved',- revision: '00000000-0000-4000-8000-000000000001',+ await installGhostFromFile('/tmp/node.cindy', {+ t: ((key: string) => key) as never,});- const { update } = setupWindow(baseManifest, undefined, [current]);- const confirm = vi.fn(async (_options: unknown) => true);-- await confirmAndInstallGhost('/tmp/node-update.cindy', deps(confirm));- expect(update).toHaveBeenCalledWith('/tmp/node-update.cindy', {+ expect(install).not.toHaveBeenCalled();+ expect(update).toHaveBeenCalledWith('/tmp/node.cindy', {expectedPackageSha256: 'a'.repeat(64),- expectedInstalledApproval:- 'approved:00000000-0000-4000-8000-000000000001',+ expectedInstalledApproval: 'approved:00000000-0000-4000-8000-000000000001',});});- it('treats every target permission as added when no approved baseline exists', async () => {- const current = installed({ state: 'legacy-unapproved' });- const { update } = setupWindow(baseManifest, undefined, [current]);- const confirm = vi.fn(async (_options: unknown) => true);-- await confirmAndInstallGhost('/tmp/legacy-update.cindy', deps(confirm));-- const review = (confirm.mock.calls[0]![0] as {- content: { props: { diff: { added: unknown[]; unchanged: unknown[] } } };- }).content;- expect(review.props.diff.added.length).toBeGreaterThan(0);- expect(review.props.diff.unchanged).toEqual([]);- expect(update).toHaveBeenCalledWith(- '/tmp/legacy-update.cindy',- expect.objectContaining({- expectedInstalledApproval: 'legacy-unapproved',- }),- );- });-});+ it('本地包不由客户端按 minCindyVersion 二次拦截', async () => {+ const incompatibleManifest = { ...baseManifest, minCindyVersion: '2.0.0' };+ const { install } = setupWindow(incompatibleManifest);-describe('installFlow · tab 型插件装入即开面板', () => {- const tabManifest = {- schemaVersion: 2 as const,- id: 'tab-demo-a',- name: '页签演示 A',- version: '1.0.0',- kind: 'chip' as const,- entry: 'main.js',- slots: ['panel'] as const,- panel: { html: 'panel.html', position: 'tab' as const },- };-- function tabDeps(openPluginPanel?: (ghostId: string) => void) {- return {+ await installGhostFromFile('/tmp/node.cindy', {t: ((key: string) => key) as never,- confirm: vi.fn(async (_options: unknown) => true),- ...(openPluginPanel ? { openPluginPanel } : {}),- };- }-- it('tab 清单 → enable 装入(勾选框已删)并原地打开插件页面板', async () => {- const { install } = setupWindow(tabManifest);- const openPluginPanel = vi.fn();-- await confirmAndInstallGhost('/tmp/tab.cindy', tabDeps(openPluginPanel));-- expect(install).toHaveBeenCalledWith('/tmp/tab.cindy', {- enable: true,- expectedPackageSha256: 'a'.repeat(64),});- expect(openPluginPanel).toHaveBeenCalledWith('tab-demo-a');- expect(toast.success).toHaveBeenCalledTimes(1);- });-- it('入口未提供 openPluginPanel → 装入即生效但不许诺打开', async () => {- const { install } = setupWindow(tabManifest);-- await confirmAndInstallGhost('/tmp/tab.cindy', tabDeps());- expect(install).toHaveBeenCalledWith('/tmp/tab.cindy', {+ expect(install).toHaveBeenCalledWith('/tmp/node.cindy', {enable: true,expectedPackageSha256: 'a'.repeat(64),});- });-- it('停靠形态(position: left)只带电,不打开面板', async () => {- setupWindow({- ...tabManifest,- panel: { html: 'panel.html', position: 'left' as const },- });- const openPluginPanel = vi.fn();-- await confirmAndInstallGhost('/tmp/dock.cindy', tabDeps(openPluginPanel));-- expect(openPluginPanel).not.toHaveBeenCalled();+ expect(toast.success).toHaveBeenCalledTimes(1);});});diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/useInstalledGhosts.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/useInstalledGhosts.test.tsxindex 63e2682822..62780ad74e 100644--- a/apps/desktop/src/renderer/cindy-brain/__tests__/useInstalledGhosts.test.tsx+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/useInstalledGhosts.test.tsx@@ -26,7 +26,6 @@ const ghost = (id: string, name = id): InstalledGhost => ({version: '1.0.0',kind: 'chip',entry: 'main.js',- slots: ['tool'],},dir: `/brain/${id}`,enabled: true,diff --git a/apps/desktop/src/renderer/cindy-brain/ghostInstallRisk.ts b/apps/desktop/src/renderer/cindy-brain/ghostInstallRisk.tsdeleted file mode 100644index 88cc20ae2c..0000000000--- a/apps/desktop/src/renderer/cindy-brain/ghostInstallRisk.ts+++ /dev/null@@ -1,88 +0,0 @@-/**- * 装入确认框的风险分档(纯函数,无 React、无 i18n)。- *- * 只在 **Agent 单方面发起** 装入时改变确认框行为——手动入口不受影响。分档决定- * 是否加重(高危:手输插件 id 才能确认;中危:只加来源横幅)。判据一律按- * `ghostPermissionItems` 产出的权限项 **key** 归类,与用户在确认框里实际看到的- * 逐项清单同源——不另立一套"作者声明"口径,避免"分档看到的"与"清单展示的"分叉。- *- * 分档(2026-08 产品拍板):- * - 高危:skill(技能指令以用户全部权限执行、跨项目)/ node(本机执行,浏览器- * 沙箱管不住)/ network.secrets 任意来源(含 oauth,能把用户凭证发往声明域名)/- * agent.background(后台自动触发)/ agent.errand(替它干活并取走结果)。- * - 中危:fs(写文件——最危险那档写会话工作目录已受会话 permission 模式约束,- * 免批模式下 Agent 本就能直写,插件多这能力不改变攻击面)/ network.hosts(出网- * 域名)/ agent.schedule(能反复弹自动化面板、烧模型额度,但须用户在面板上- * 亲手保存才生效)。- * - 低危:纯沙箱 tool / card / panel 及其它未列入的能力。- */-import type { GhostPermissionItem } from '../../shared/ghost';--export type GhostRiskTier = 'high' | 'mid' | 'low';--export interface GhostRiskAssessment {- tier: GhostRiskTier;- /** 高危能力命中标记(来源横幅据此点破最该被看见的那一两条)。 */- hazards: {- skill: boolean;- node: boolean;- /** 声明了需要凭证(network.secrets 任意来源,含 oauth / 组织身份)。 */- secret: boolean;- agentBackground: boolean;- agentErrand: boolean;- };- /** 声明的出网域名(凭证外发对象;凭证点破文案用)。 */- networkHosts: string[];-}--/** 单条权限项的风险档(按 key 归类,与清单展示同源)。 */-function itemRiskTier(item: GhostPermissionItem): GhostRiskTier {- const key = item.key;- if (- key.startsWith('skill:') ||- key.startsWith('node:') ||- key.startsWith('network:secret:') ||- key === 'agent:background' ||- key === 'agent:errand'- ) {- return 'high';- }- if (key === 'fs' || key.startsWith('network:host:') || key === 'agent:schedule') {- return 'mid';- }- return 'low';-}--/**- * 汇总一份权限清单的整体风险档 + 高危命中标记 + 出网域名。- * 传全量清单 = 新装分档;传更新 diff 的新增项 = 更新扩权分档(tier !== 'low'- * 即"新增了高危或中危能力")。- */-export function assessGhostInstallRisk(items: GhostPermissionItem[]): GhostRiskAssessment {- const hazards = {- skill: false,- node: false,- secret: false,- agentBackground: false,- agentErrand: false,- };- const networkHosts: string[] = [];- let hasHigh = false;- let hasMid = false;- for (const item of items) {- const tier = itemRiskTier(item);- if (tier === 'high') hasHigh = true;- else if (tier === 'mid') hasMid = true;- if (item.key.startsWith('skill:')) hazards.skill = true;- else if (item.key.startsWith('node:')) hazards.node = true;- else if (item.key.startsWith('network:secret:')) hazards.secret = true;- else if (item.key === 'agent:background') hazards.agentBackground = true;- else if (item.key === 'agent:errand') hazards.agentErrand = true;- if (item.key.startsWith('network:host:')) {- const host = item.labelArgs?.host;- if (host) networkHosts.push(host);- }- }- const tier: GhostRiskTier = hasHigh ? 'high' : hasMid ? 'mid' : 'low';- return { tier, hazards, networkHosts };-}diff --git a/apps/desktop/src/renderer/cindy-brain/ghostMainViews.ts b/apps/desktop/src/renderer/cindy-brain/ghostMainViews.tsindex 7cdde0998b..e68c60c259 100644--- a/apps/desktop/src/renderer/cindy-brain/ghostMainViews.ts+++ b/apps/desktop/src/renderer/cindy-brain/ghostMainViews.ts@@ -25,7 +25,7 @@ export interface GhostMainViewProjection {}function mainViewDeclared(ghost: InstalledGhost): boolean {- return ghost.manifest.slots.includes('main-view') && ghost.manifest.mainView !== undefined;+ return ghost.manifest.mainView !== undefined;}export function projectGhostMainViews(diff --git a/apps/desktop/src/renderer/cindy-brain/installErrorKey.ts b/apps/desktop/src/renderer/cindy-brain/installErrorKey.tsindex 8513bf3b99..6dd8832d10 100644--- a/apps/desktop/src/renderer/cindy-brain/installErrorKey.ts+++ b/apps/desktop/src/renderer/cindy-brain/installErrorKey.ts@@ -17,16 +17,10 @@ export function ghostInstallErrorKey(code: string | undefined): string {return 'settings.ghosts.errors.idReserved';case 'GHOST_BROKER_MANUAL_INSTALL_NOT_AUTHORIZED':return 'settings.ghosts.errors.brokerManualInstallNotAuthorized';- case 'GHOST_BROKER_NOT_AUTHORIZED':- return 'settings.ghosts.errors.brokerNotAuthorized';case 'GHOST_BROKER_REDIRECT_PORT_REQUIRED':return 'settings.ghosts.errors.brokerRedirectPortRequired';case 'NOT_FOUND':return 'settings.ghosts.errors.sourceMissing';- // 批准状态相关的前置条件失败在这条链路上只有一种下一步动作:重新确认权限。- // 缺少批准记录(启用存量安装)与批准态在确认后变化(更新)都归到这里。- case 'PRECONDITION_FAILED':- return 'settings.ghosts.errors.approvalRequired';default:return 'settings.ghosts.errors.generic';}diff --git a/apps/desktop/src/renderer/cindy-brain/installFlow.tsx b/apps/desktop/src/renderer/cindy-brain/installFlow.tsxindex bcf1229051..7987292cf1 100644--- a/apps/desktop/src/renderer/cindy-brain/installFlow.tsx+++ b/apps/desktop/src/renderer/cindy-brain/installFlow.tsx@@ -1,123 +1,36 @@import type { TFunction } from 'i18next';-import { useState, type ReactNode } from 'react';-import { useTranslation } from 'react-i18next';-import { createLogger } from '@/lib/logger';import { toast } from '@/lib/toast';import { extractIpcError } from '@/utils/ipcError';import {- diffInstalledGhostPermissionItems,ghostInstallApprovalToken,- ghostPermissionItems,type GhostManifest,- type GhostTrustInfo,type InstalledGhost,} from '../../shared/ghost';-import {- GhostInstallReview,- GhostUpdateReview,- type GhostAgentOriginInfo,-} from './GhostPermissionList';-import { assessGhostInstallRisk, type GhostRiskAssessment } from './ghostInstallRisk';import { ghostInstallErrorKey } from './installErrorKey';-import { isAgentForgeOrigin, type GhostInstallOrigin } from '../../shared/ghostInstallOrigin';/**- * 装入/更新意识的统一编排:inspect(验明正身)→ Renderer 权限清单 →- * install / update。Node 高风险条目在权限清单里如实展示- * (2026-07-24 起不再有 Main 原生二次确认弹窗)。- *- * 「装意识前弹确认」是 README 定下的安全原则:确认框展示的是**意识自称的身份**- * (名字/版本/形态/是否带面板),不是文件名 —— 文件名可以随便改,身份卡不会陪它演。- * 设置页按钮 / 窗口拖入 / 双击 .cindy 三个入口共用本流程 —— 双击由 main 侧- * 转交路径进来(main/cindy-brain/openFileInstall.ts,pending buffer +- * GlobalDropImportListener 消费),确认弹窗永远是应用内这同一个。- *- * 确认框正文是逐项权限清单:由身份卡静态推导(ghostPermissionItems),- * Cindy 代办按类目、工具逐个、指令/面板/可执行代码各一项,如实展示无黑话。- *- * 同 id 已装 → 自动转「更新」分支:确认框展示版本变化(vX → vY)+ 权限 diff- * (只高亮新增/移除,不变项折叠计数),无"立即开启"勾选(更新延续当前唤醒- * 状态,不偷偷点亮也不偷偷熄灯)。- *- * 「安装后立即生效」勾选框已删除(2026-08 产品拍板):它是弱信号——把决定权推给- * 用户却不给判断依据。新装一律直接生效,高危插件改由**手输插件 id** 这道强确认- * 把关;低危插件本就该直接可用。- *- * **来源分级加重**:装入由 Agent 单方面发起(`ghost_forge_pack` 转交,origin =- * agent-forge)时,确认框展示来源横幅;高危档(skill/node/凭证/agent 后台/派活)- * 额外要求用户手输插件 id 才能确认。手动入口(拖入/双击/设置页选文件)不加横幅、- * 不加重——亲手选文件本身就是意图表达。判据见 ghostInstallRisk.assessGhostInstallRisk。+ * 本地 .cindy 的统一一键安装/更新编排:inspect 验证真实包后直接交给 Main+ * 落位。文件选择、拖入和双击都是用户明确安装动作,不再追加插件权限确认层。+ * 同 id 已安装时转为原位更新;更新继续由 Main 延续当前启用状态。*/-const installFlowLog = createLogger('ghost-install-flow');-interface InstallFlowDeps {t: TFunction;/**- * ui/confirm-dialog-provider 的 confirm(装入 / 更新 / 重新确认统一走它,无勾选)。- * requireTypedConfirmation:高危 Agent 发起时要求手输插件 id 才解锁主按钮。- */- confirm: (options: {- title: string;- description?: string;- content?: ReactNode;- maxWidth?: number;- confirmText?: string;- cancelText?: string;- requireTypedConfirmation?: { expected: string; label: string; placeholder?: string };- }) => Promise<boolean>;- /**- * 打开插件页内的页签面板(面板收束后 tab 型插件的唯一宿主)。tab 型插件装入- * 即生效后消费:插件页原地开面板,其它入口导航到 /plugins?panel=<id>。- * 不传 = 该入口不许诺"打开"。+ * 打开插件页内的页签面板(面板收束后 tab 型插件的唯一宿主)。只在+ * 「tab 型插件安装后」消费:插件页原地开面板,其它入口+ * 导航到 /plugins?panel=<id>。不传 = 该入口不许诺"打开"。*/openPluginPanel?: (ghostId: string) => void;}-/**- * Agent 发起时构造来源横幅信息(手动入口返回 undefined → 不展示横幅)。- * hazards 只含高危标记(skill/node/凭证);中危/低危不会点亮任何 callout。- * hazardsFrom 决定"点破哪些":新装看全量清单,更新只看本次新增项。- * allHosts = 插件(更新后)能出网的全部域名,凭证 callout 据此列出外发对象。- */-function agentOriginInfoFrom(- origin: GhostInstallOrigin | undefined,- firstInstall: boolean,- hazardsFrom: GhostRiskAssessment,- allHosts: string[],-): GhostAgentOriginInfo | undefined {- if (!isAgentForgeOrigin(origin)) return undefined;- return {- ...(origin.sessionTitle ? { sessionTitle: origin.sessionTitle } : {}),- ...(origin.sourceRelPath ? { sourceRelPath: origin.sourceRelPath } : {}),- firstInstall,- hazards: {- skill: hazardsFrom.hazards.skill,- node: hazardsFrom.hazards.node,- credential: hazardsFrom.hazards.secret && allHosts.length > 0,- },- credentialHosts: allHosts,- };+/** 安装事务失败统一走 toast。 */+async function showInstallError(error: unknown, deps: InstallFlowDeps): Promise<void> {+ const code = extractIpcError(error)?.code;+ toast.error(deps.t(ghostInstallErrorKey(code)));}-/** 高危 Agent 发起时的「手输插件 id」闸参数(否则 undefined = 不加重)。 */-function typedIdConfirmation(- t: TFunction,- ghostId: string,- required: boolean,-): { expected: string; label: string; placeholder?: string } | undefined {- if (!required) return undefined;- return {- expected: ghostId,- label: t('settings.ghosts.installConfirm.typedIdLabel', { id: ghostId }),- placeholder: ghostId,- };-}--/** 意识装入/更新确认框统一宽度:权限清单是富内容,默认 400px 折行到累。 */-const GHOST_CONFIRM_MAX_WIDTH = 520;-/** 同 id 已装清单查询(sendSync,极小)。 */function findInstalled(id: string): InstalledGhost | null {try {@@ -128,55 +41,18 @@ function findInstalled(id: string): InstalledGhost | null {}}-/** 确认 + 原位更新(installed 是当前已装版本,manifest 是新文件的身份卡)。 */-async function confirmAndRunUpdate(+/** 原位更新;Main 负责校验包摘要并延续启用状态。 */+async function runUpdate(lizFilePath: string,- manifest: GhostManifest,- trust: GhostTrustInfo,packageSha256: string,installed: InstalledGhost,deps: InstallFlowDeps,- origin?: GhostInstallOrigin,- packTicket?: string,): Promise<void> {- const { t, confirm } = deps;- // 权限 diff:只把新增/移除的权限亮给用户,不变项折叠计数。- const diff = diffInstalledGhostPermissionItems(installed, manifest);- // Agent 发起的更新:新增项含高危/中危能力(tier !== 'low')即要求手输 id ——- // 堵"注入者篡改作者正在开发的同 id 插件、借版本升级夹带权限"。横幅点破的- // hazard 只看本次新增项(hazardsFrom = 新增),但凭证外发域名列出更新后的全量。- const addedRisk = assessGhostInstallRisk(diff.added);- const allHosts = assessGhostInstallRisk(ghostPermissionItems(manifest)).networkHosts;- const agentOrigin = agentOriginInfoFrom(origin, false, addedRisk, allHosts);- const escalate = isAgentForgeOrigin(origin) && addedRisk.tier !== 'low';- const ok = await confirm({- title: t('settings.ghosts.updateConfirm.title', { name: manifest.name }),- description: t('settings.ghosts.updateConfirm.body', {- from: installed.manifest.version,- to: manifest.version,- }),- content: (- <GhostUpdateReview- trust={trust}- diff={diff}- manualCount={manifest.manual?.items.length ?? 0}- agentOrigin={agentOrigin}- />- ),- maxWidth: GHOST_CONFIRM_MAX_WIDTH,- confirmText: t('settings.ghosts.updateConfirm.confirm'),- cancelText: t('settings.ghosts.updateConfirm.cancel'),- requireTypedConfirmation: typedIdConfirmation(t, manifest.id, escalate),- });- if (!ok) {- if (packTicket) await window.electronAPI.ghosts.abandonPackTicket(packTicket);- return;- }+ const { t } = deps;try {const { ghost } = await window.electronAPI.ghosts.update(lizFilePath, {expectedPackageSha256: packageSha256,expectedInstalledApproval: ghostInstallApprovalToken(installed.approval),- ...(packTicket ? { packTicket } : {}),});toast.success(t('settings.ghosts.toast.updated', {@@ -185,233 +61,56 @@ async function confirmAndRunUpdate(}),);} catch (err) {- toast.error(t(ghostInstallErrorKey(extractIpcError(err)?.code)));+ await showInstallError(err, deps);}}-export async function confirmAndInstallGhost(+export async function installGhostFromFile(lizFilePath: string,deps: InstallFlowDeps,- /**- * 主机侧填写的来源;缺省 = 手动(拖入/双击/设置页选文件),不加横幅、不加重。- * agent-forge = Agent 单方面发起,展示来源横幅;高危档追加手输 id 闸。- */- origin?: GhostInstallOrigin,): Promise<void> {- const { t, confirm } = deps;+ const { t } = deps;- // 1) 只验不装,拿身份卡;坏文件在这一步就被拒,不会弹确认。+ // 1) 只验不装,拿身份卡;坏文件在这一步就被拒,不会产生安装副作用。let manifest: GhostManifest;- let trust: GhostTrustInfo;let packageSha256: string;- let packTicket: string | undefined;try {const inspected = await window.electronAPI.ghosts.inspect(lizFilePath);manifest = inspected.manifest;- trust = inspected.trust;packageSha256 = inspected.packageSha256;- packTicket = inspected.packTicket;} catch (err) {- toast.error(t(ghostInstallErrorKey(extractIpcError(err)?.code)));+ await showInstallError(err, deps);return;}// 1.5) 同 id 已装 → 转更新分支(拖入/双击/装入按钮选到新版包时不再报- // "已经注入",直接给换版确认)。origin 透传:Agent 发起的更新也要能加重。+ // "已经注入",直接原位更新)。const installed = findInstalled(manifest.id);if (installed) {- await confirmAndRunUpdate(- lizFilePath,- manifest,- trust,- packageSha256,- installed,- deps,- origin,- packTicket,- );+ await runUpdate(lizFilePath, packageSha256, installed, deps);return;}- // 2) 确认弹窗:自我介绍、作者/版本、权限清单分层展示。- // 作者自由填写的工具长说明默认折叠;敏感权限仍直接展示。详情区限高滚动,- // 不再让内容把整个弹窗撑出屏幕。- // 身份卡自称的作者也如实展示(有才显示,避免"作者 ·"空段)。- const factsLine = manifest.author- ? t('settings.ghosts.installConfirm.metaWithAuthor', {- author: manifest.author,- version: manifest.version,- })- : t('settings.ghosts.installConfirm.meta', { version: manifest.version });- // 新装一律直接生效(2026-08 拍板删「立即开启」勾选):高危靠手输 id 把关,低危- // 本该直接可用。tab 型插件(panel.position:'tab')在入口能开面板时,生效后原地- // 打开插件页面板;入口给不出面板宿主就不许诺"打开"。+ // 安装动作本身已经由用户通过文件选择/拖入/双击明确发起。安装后默认启用;+ // tab 型插件在入口能提供页面板宿主时直接打开。const willOpenPanel = manifest.panel?.position === 'tab' && deps.openPluginPanel !== undefined;- // library 槽(持久作品库):装入确认里提供「存储位置」行——默认预选系统- // 管理位置(不点更改 = 零额外步骤),点「更改…」由宿主弹原生选择器并做- // 候选校验;装入成功后才落 binding(取消装入不留孤儿 binding)。- const libraryChoice: { candidate: string | null; warnings: string[] } = {- candidate: null,- warnings: [],- };- const librarySlots = manifest.slots.includes('library');- const items = ghostPermissionItems(manifest);- const risk = assessGhostInstallRisk(items);- // 新装是该 id 首次安装(installed 已在上面判空);Agent 发起才构造横幅。- const agentOrigin = agentOriginInfoFrom(origin, true, risk, risk.networkHosts);- // 高危 + Agent 发起 → 手输插件 id 才能确认(每个新插件 id 一生只打一次:- // 第二次起走更新分支,权限没变只显示小框)。- const requireTypedId = isAgentForgeOrigin(origin) && risk.tier === 'high';- const ok = await confirm({- title: t('settings.ghosts.installConfirm.title', { name: manifest.name }),- content: (- <GhostInstallReview- description={manifest.description}- meta={factsLine}- trust={trust}- items={items}- manualCount={manifest.manual?.items.length ?? 0}- extra={- librarySlots ? (- <LibraryInstallLocationRow ghostId={manifest.id} choice={libraryChoice} />- ) : undefined- }- agentOrigin={agentOrigin}- />- ),- maxWidth: GHOST_CONFIRM_MAX_WIDTH,- confirmText: t('settings.ghosts.installConfirm.confirm'),- cancelText: t('settings.ghosts.installConfirm.cancel'),- requireTypedConfirmation: typedIdConfirmation(t, manifest.id, requireTypedId),- });- if (!ok) {- if (packTicket) await window.electronAPI.ghosts.abandonPackTicket(packTicket);- return;- }-- // 2.5) 用户在确认框里选了自定义位置 → **装入前**先落 binding(keyed by- // ghostId,与安装顺序无关):否则「立即开启」的常驻插件会在 install 返回- // 前被拉起、以默认根开库(review:spawn 早于 bind)。装入失败会留一份无- // 数据的 binding,行为等价「记住位置」,下次装同 id 直接用上。- if (librarySlots && libraryChoice.candidate) {- const bound = await window.electronAPI.ghosts.libraryBind(manifest.id, libraryChoice.candidate);- if (!bound.ok) {- toast.error(`${t('settings.ghosts.library.bindAfterInstallFailed')}:${bound.message ?? ''}`);- } else if (bound.warnings && bound.warnings.length > 0) {- toast.warning(t('settings.ghosts.library.cloudWarningToast'));- }- }-- // 3) 真装(main 侧同一主体:来源校验 + 落盘 + 停靠)。Node 高风险提示- // 已在上面的权限清单里如实展示,不再有 Main 原生二次确认。装入即生效。try {const { ghost } = await window.electronAPI.ghosts.install(lizFilePath, {enable: true,expectedPackageSha256: packageSha256,- ...(packTicket ? { packTicket } : {}),});toast.success(t('settings.ghosts.toast.installed', { name: ghost.manifest.name }));if (willOpenPanel) {- // 进入插件页并打开该插件的页签面板。deps.openPluginPanel?.(ghost.manifest.id);}} catch (err) {- toast.error(t(ghostInstallErrorKey(extractIpcError(err)?.code)));- }-}--/**- * 「重新确认权限」的本地包路线:**从已装目录**读出全量权限清单 → 确认 → 开 receipt。- * 不用用户翻出原始 `.cindy` 文件(#1243 验收:本地包不存在不可恢复状态)。- *- * 授权边界仍是这张确认卡:无批准基线,权限**全量**按新增项展示(GhostInstallReview),- * 与"重新选包"路线看到的是同一张卡,差别只是字节从安装目录读。清单字节以- * manifestSha256 绑定到 confirm(确认间隙 ghost.json 被换 → main 拒 state-changed)。- *- * 安装目录读不出/清单不合法时回退到「重新选包」路线 —— 目录坏了才需要用户找文件,- * 目录完好时一次点击即恢复。- */-export async function reapproveInstalledGhost(- ghostId: string,- deps: InstallFlowDeps,-): Promise<void> {- const { t, confirm } = deps;- const installed = findInstalled(ghostId);- if (!installed) {- toast.error(t('settings.ghosts.errors.generic'));- return;- }- let manifest: GhostManifest;- let trust: GhostTrustInfo;- let manifestSha256: string;- let approvalProjectionSha256: string;- let previouslyEnabled: boolean;- let inspectTicket: string;- try {- const inspected = await window.electronAPI.ghosts.reapproveInspect(ghostId);- manifest = inspected.manifest;- trust = inspected.trust;- manifestSha256 = inspected.manifestSha256;- approvalProjectionSha256 = inspected.approvalProjectionSha256;- previouslyEnabled = inspected.previouslyEnabled;- inspectTicket = inspected.inspectTicket;- } catch (err) {- // 安装目录读不出清单 = 只剩"重新选包"一条路;如实降级,不吞掉恢复机会。- installFlowLog.warn('reapprove-inspect failed; falling back to file picker', {- ghostId,- err,- });- await pickAndUpdateGhost(ghostId, deps);- return;- }- const factsLine = manifest.author- ? t('settings.ghosts.installConfirm.metaWithAuthor', {- author: manifest.author,- version: manifest.version,- })- : t('settings.ghosts.installConfirm.meta', { version: manifest.version });- // 「保持之前启用状态」不再做成勾选框(勾选框是弱信号)——它本质是"保持现状"- // 而非"让用户选":之前主动停用的插件,恢复权限后不该被顺手点亮。改成一句如实- // 说明(保持启用 / 保持沉睡),启用值直接取升级前偏好。- const enable = previouslyEnabled;- const ok = await confirm({- title: t('settings.ghosts.reapproveConfirm.title', { name: manifest.name }),- description: t('settings.ghosts.reapproveConfirm.body'),- content: (- <GhostInstallReview- description={manifest.description}- meta={factsLine}- trust={trust}- items={ghostPermissionItems(manifest)}- enableNotice={t(- previouslyEnabled- ? 'settings.ghosts.reapproveConfirm.enableNoticeEnabled'- : 'settings.ghosts.reapproveConfirm.enableNoticeAsleep',- )}- />- ),- maxWidth: GHOST_CONFIRM_MAX_WIDTH,- confirmText: t('settings.ghosts.reapproveConfirm.confirm'),- cancelText: t('settings.ghosts.installConfirm.cancel'),- });- if (!ok) return;- try {- const { ghost } = await window.electronAPI.ghosts.reapproveInstalled(ghostId, {- enable,- expectedManifestSha256: manifestSha256,- expectedApprovalProjectionSha256: approvalProjectionSha256,- expectedInstalledApproval: ghostInstallApprovalToken(installed.approval),- inspectTicket,- });- toast.success(t('settings.ghosts.toast.reapproved', { name: ghost.manifest.name }));- } catch (err) {- toast.error(t(ghostInstallErrorKey(extractIpcError(err)?.code)));+ await showInstallError(err, deps);}}/*** 单意识详情页的「更新版本…」:选文件 → 验身 → 必须与当前意识同 id- * (选错别的意识的包直接拒,不做"顺手装成新意识"的隐式行为)→ 确认 → 更新。+ * (选错别的意识的包直接拒,不做"顺手装成新意识"的隐式行为)→ 更新。*/export async function pickAndUpdateGhost(expectedId: string, deps: InstallFlowDeps): Promise<void> {const { t } = deps;@@ -419,21 +118,16 @@ export async function pickAndUpdateGhost(expectedId: string, deps: InstallFlowDeif (!picked || 'canceled' in picked) return;let manifest: GhostManifest;- let trust: GhostTrustInfo;let packageSha256: string;- let packTicket: string | undefined;try {const inspected = await window.electronAPI.ghosts.inspect(picked.filePath);manifest = inspected.manifest;- trust = inspected.trust;packageSha256 = inspected.packageSha256;- packTicket = inspected.packTicket;} catch (err) {- toast.error(t(ghostInstallErrorKey(extractIpcError(err)?.code)));+ await showInstallError(err, deps);return;}if (manifest.id !== expectedId) {- if (packTicket) await window.electronAPI.ghosts.abandonPackTicket(packTicket);toast.error(t('settings.ghosts.errors.updateIdMismatch', { id: manifest.id, expected: expectedId }),);@@ -441,78 +135,9 @@ export async function pickAndUpdateGhost(expectedId: string, deps: InstallFlowDe}const installed = findInstalled(expectedId);if (!installed) {- if (packTicket) await window.electronAPI.ghosts.abandonPackTicket(packTicket);// 详情页开着的意识刚被别处抽离——极端竞态,按通用错误提示。toast.error(t('settings.ghosts.errors.generic'));return;}- await confirmAndRunUpdate(- picked.filePath,- manifest,- trust,- packageSha256,- installed,- deps,- undefined,- packTicket,- );-}--/**- * 装入确认框里的「存储位置」行(library 槽专用):默认预选系统管理位置,- * 点「更改…」由宿主弹原生选择器(插件无权发起)并做候选校验(可写探针/- * 受管根排斥/网络盘拒/云盘警告)。选择结果写回外层 choice 对象(ReactNode- * content 与外层 async 流程之间的通信桥),装入成功后才落 binding。- */-function LibraryInstallLocationRow({- ghostId,- choice,-}: {- ghostId: string;- choice: { candidate: string | null; warnings: string[] };-}): ReactNode {- const { t } = useTranslation();- const [candidate, setCandidate] = useState<string | null>(choice.candidate);- const [warnings, setWarnings] = useState<string[]>(choice.warnings);- const pick = async () => {- const picked = await window.electronAPI.ghosts.libraryPickLocation(ghostId);- if (!picked.ok) {- if (!picked.cancelled) {- toast.error(picked.message ?? t('settings.ghosts.library.pickFailed'));- }- return;- }- choice.candidate = picked.candidate ?? null;- choice.warnings = picked.warnings ?? [];- setCandidate(choice.candidate);- setWarnings(choice.warnings);- };- return (- <div className="rounded-xl border border-[var(--border-default)] bg-[var(--surface)] p-3">- <div className="flex items-center justify-between gap-3">- <div className="min-w-0">- <p className="text-13 font-medium leading-5 text-[var(--text-primary)]">- {t('settings.ghosts.library.installLocationLabel')}- </p>- <p className="mt-0.5 break-all text-12 leading-[1.5] text-[var(--text-secondary)]">- {candidate- ? `${t('settings.ghosts.library.installLocationPickedPrefix')} ${candidate}`- : t('settings.ghosts.library.installLocationDefault')}- </p>- </div>- <button- type="button"- onClick={() => void pick()}- className="shrink-0 rounded-lg text-13 font-medium text-[var(--accent)] transition-opacity hover:opacity-80 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"- >- {t('settings.ghosts.library.installLocationChange')}- </button>- </div>- {warnings.map((warning) => (- <p key={warning} className="mt-2 text-12 leading-[1.5] text-[var(--warning-fg)]">- {warning}- </p>- ))}- </div>- );+ await runUpdate(picked.filePath, packageSha256, installed, deps);}diff --git a/apps/desktop/src/renderer/components/layout/GlobalDropImportListener.tsx b/apps/desktop/src/renderer/components/layout/GlobalDropImportListener.tsxindex f22eb9c4df..97b8b1fc9e 100644--- a/apps/desktop/src/renderer/components/layout/GlobalDropImportListener.tsx+++ b/apps/desktop/src/renderer/components/layout/GlobalDropImportListener.tsx@@ -12,7 +12,7 @@* 执行路由,但**不 stopPropagation**:事件继续传到内层,内层 handler 自查* 标记(lib/globalDropIntercept.ts)后清理自己的拖拽 UI 状态再 return,* 避免"悬停识别不到 → 内层遮罩已亮 → drop 被吞 → 计数不归零遮罩卡死"。- * - 路由:.cindy → inspect 验明正身 → 确认弹窗 → 装入 + 停靠,与设置页+ * - 路由:.cindy → inspect 验明正身 → 装入 + 停靠,与设置页* 「注入意识…」同一编排(renderer/cindy-brain/installFlow.ts);* .cshare(含旧 .xdtshare)→ 经 main 的 classify-path 验明后打开会话导入向导。*@@ -33,8 +33,7 @@ import { useCallback, useEffect, useRef, useState } from 'react';import { useNavigate } from 'react-router-dom';import { useTranslation } from 'react-i18next';-import { confirmAndInstallGhost } from '@/cindy-brain/installFlow';-import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';+import { installGhostFromFile } from '@/cindy-brain/installFlow';import {classifyGlobalDropPath,markGlobalDropIntercepted,@@ -61,34 +60,30 @@ export function GlobalDropImportListener({const interceptRef = useRef(false);const navigate = useNavigate();const { t } = useTranslation();- const { confirm } = useConfirmDialog();- // 装入 tab 型插件勾选「立即开启并打开面板」的兑现:面板收束后页签面板+ // 装入 tab 型插件后直接打开面板:面板收束后页签面板// 只住在插件页,从任意视图导航过去并经 ?panel= 深链打开。const openPluginPanel = useCallback((ghostId: string) => navigate(`/plugins?panel=${encodeURIComponent(ghostId)}`),[navigate],);- // 双击 .cindy / forge 转交的消费:挂载时取一次(冷启动双击 / 关窗期间转交的,- // main 已缓存)+ 订阅通知(已运行时双击 / forge 转交)。取到路径即走与按钮/拖入- // 完全相同的确认装入编排。- //- // 来源与路径**一起从 takePendingInstall 取**,不从通知 payload 拿:通知是易失的- // (没有窗口时直接丢),而 forge 转交在 macOS 关窗后仍可能发生,来源丢了就会把- // Agent 发起的装入显示成手动 —— 恰好是最危险的方向。理由全文见 main 侧- // openFileInstall.ts 的头注释。+ // 双击 .cindy 的转交消费:挂载时取一次(冷启动双击,main 已缓存)+ 订阅+ // 信号(已运行时双击)。取到路径即走与按钮/拖入完全相同的装入编排。useEffect(() => {const consumePending = async () => {- const { filePath, origin } = await window.electronAPI.ghosts.takePendingInstall();+ const { filePath } = await window.electronAPI.ghosts.takePendingInstall();if (filePath) {- await confirmAndInstallGhost(filePath, { t, confirm, openPluginPanel }, origin);+ await installGhostFromFile(filePath, {+ t,+ openPluginPanel,+ });}};void consumePending().catch((err) => log.warn('consume pending cindy install failed', err));return window.electronAPI.ghosts.onInstallRequested(() => {void consumePending().catch((err) => log.warn('consume pending cindy install failed', err));});- }, [confirm, openPluginPanel, t]);+ }, [openPluginPanel, t]);useEffect(() => {// 悬停识别:单文件且 MIME 命中才给遮罩。@@ -147,9 +142,11 @@ export function GlobalDropImportListener({e.preventDefault();markGlobalDropIntercepted(e);if (kind === 'cindy') {- // 验明正身 → 确认弹窗 → 装入的编排在 installFlow(与设置页装入按钮同契约)。- // 拖入是用户亲手操作 → 手动来源(不传 origin),不加横幅、不加重。- void confirmAndInstallGhost(path, { t, confirm, openPluginPanel });+ // 验明正身 → 装入的编排在 installFlow(与设置页装入按钮同契约)。+ void installGhostFromFile(path, {+ t,+ openPluginPanel,+ });return;}void window.electronAPI.localDb.sessionSharediff --git a/apps/desktop/src/renderer/components/layout/MainLayout.tsx b/apps/desktop/src/renderer/components/layout/MainLayout.tsxindex 6a6233f925..70bb822017 100644--- a/apps/desktop/src/renderer/components/layout/MainLayout.tsx+++ b/apps/desktop/src/renderer/components/layout/MainLayout.tsx@@ -79,7 +79,6 @@ import { useCorruptionRestoredToast } from '@/hooks/useCorruptionRestoredToast';import { useSchemaDriftWarningToast } from '@/hooks/useSchemaDriftWarningToast';import { useVoiceInputShortcutRecoveryToast } from '@/hooks/useVoiceInputShortcutRecoveryToast';import { usePluginRemovalNoticeToast } from '@/hooks/usePluginRemovalNoticeToast';-import { usePluginUpgradeNoticeToast } from '@/hooks/usePluginUpgradeNoticeToast';import { requestProjectFocus } from '@/state/pendingProjectFocus';import { patchDraft } from '@/state/newMakerDraft';import { cn } from '@/lib/utils';@@ -477,7 +476,6 @@ export function MainLayout() {useVoiceInputShortcutRecoveryToast();// 冷启动市场对账可能早于 Renderer 挂载;Main pending + 常驻 consume 保证清理不静默。usePluginRemovalNoticeToast();- usePluginUpgradeNoticeToast();// device-link 跨设备远程控制:同账号在线 + 开了被控的设备,其项目自动并入侧边栏useDeviceLinkRemoteProjects();diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsxindex c61b752cec..f88865e764 100644--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx@@ -2888,49 +2888,52 @@ export function ChatInput({);// 统一建议面板的插件条目(旧 `+` 菜单口径的并集):可用项可选,无指令或// Host 入口或未生效项保留展示但置灰(entry 级 disabled + 原因)。- const pluginSuggestions = useMemo<ComposerPluginSuggestion[]>(() => {- // device-link 会话的插件运行在被控端;控制端清单既不代表远端已安装- // 状态,选择后也无法用本地 InstalledGhost 解析并插入命令。fail-closed:- // 仅 deviceLinkDeviceId === null(已确认本机)才展示;undefined(所有权- // 尚未解析)与 string(远程)一律隐藏,避免 bootstrap/重连窗口期把控制端- // 本地插件项泄漏进可能落为远程的会话。- if (deviceLinkDeviceId !== null) return [];- return pluginsForMenu.map((ghost) => {- const hasCommand = !!ghost.manifest.command;- const hostCapability = remoteHostId ? null : hostCapabilityForGhost(ghost);- const hasComposerEntry = hasCommand || hostCapability !== null;- const selectable = pluginAvailableIds.has(ghost.manifest.id) && hasComposerEntry;- const entryKey = ghost.manifest.command ?? hostCapability ?? '';- return {- item: {- type: 'plugin-command' as const,- name: ghost.manifest.name,- relPath:- ghost.manifest.command ??- (hostCapability- ? `cindy://host-capability/${hostCapability}`- : `cindy://plugin/${ghost.manifest.id}`),- pluginId: ghost.manifest.id,- ...(ghost.iconDataUrl ? { iconDataUrl: ghost.iconDataUrl } : {}),- sourceLabel: entryKey,- _nameLower: `${ghost.manifest.name} ${entryKey}`.toLowerCase(),- _relPathLower: `${entryKey} ${ghost.manifest.id}`.toLowerCase(),- },- ...(selectable- ? {}- : {- disabled: true,- disabledReason: t(- !pluginAvailableIds.has(ghost.manifest.id)- ? 'extraDirs.pluginDisabled'- : ghost.manifest.slots.includes('skill')- ? 'extraDirs.pluginAgentInvoked'- : 'extraDirs.pluginNoCommand',- ),- }),- };- });- }, [deviceLinkDeviceId, pluginsForMenu, pluginAvailableIds, remoteHostId, t]);+ const pluginSuggestions = useMemo<ComposerPluginSuggestion[]>(+ () => {+ // device-link 会话的插件运行在被控端;控制端清单既不代表远端已安装+ // 状态,选择后也无法用本地 InstalledGhost 解析并插入命令。fail-closed:+ // 仅 deviceLinkDeviceId === null(已确认本机)才展示;undefined(所有权+ // 尚未解析)与 string(远程)一律隐藏,避免 bootstrap/重连窗口期把控制端+ // 本地插件项泄漏进可能落为远程的会话。+ if (deviceLinkDeviceId !== null) return [];+ return pluginsForMenu.map((ghost) => {+ const hasCommand = !!ghost.manifest.command;+ const hostCapability = remoteHostId ? null : hostCapabilityForGhost(ghost);+ const hasComposerEntry = hasCommand || hostCapability !== null;+ const selectable = pluginAvailableIds.has(ghost.manifest.id) && hasComposerEntry;+ const entryKey = ghost.manifest.command ?? hostCapability ?? '';+ return {+ item: {+ type: 'plugin-command' as const,+ name: ghost.manifest.name,+ relPath:+ ghost.manifest.command ??+ (hostCapability+ ? `cindy://host-capability/${hostCapability}`+ : `cindy://plugin/${ghost.manifest.id}`),+ pluginId: ghost.manifest.id,+ ...(ghost.iconDataUrl ? { iconDataUrl: ghost.iconDataUrl } : {}),+ sourceLabel: entryKey,+ _nameLower: `${ghost.manifest.name} ${entryKey}`.toLowerCase(),+ _relPathLower: `${entryKey} ${ghost.manifest.id}`.toLowerCase(),+ },+ ...(selectable+ ? {}+ : {+ disabled: true,+ disabledReason: t(+ !pluginAvailableIds.has(ghost.manifest.id)+ ? 'extraDirs.pluginDisabled'+ : ghost.manifest.skill+ ? 'extraDirs.pluginAgentInvoked'+ : 'extraDirs.pluginNoCommand',+ ),+ }),+ };+ });+ },+ [deviceLinkDeviceId, pluginsForMenu, pluginAvailableIds, remoteHostId, t],+ );useEffect(() => {setGhostCommandRoster(editor, ghostsForCommand);}, [editor, ghostsForCommand]);diff --git a/apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx b/apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsxindex 398fc88661..cb493d9c94 100644--- a/apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx+++ b/apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx@@ -2,7 +2,7 @@* Full access 升级确认弹窗的富内容区(ChatInput 切换权限档时经 useConfirmDialog 弹出)。** 把原先一整段权限说明拆成逐类可扫读的清单(文件 / 终端命令 / 网络),行结构与- * 装入确认的权限清单(cindy-brain/GhostPermissionList.tsx)同构;标题/说明的+ * 与插件详情页的能力清单同构;标题/说明的* 文字色阶改用 --text-primary / --text-secondary(原因见行内注释)。文案在* newChat.chatInput.fullAccessConfirmation.*,此处只负责排版。*/@@ -37,7 +37,7 @@ export function FullAccessConfirmContent() {/><div className="min-w-0">{/* 标题/说明用 --text-primary / --text-secondary:两档在明暗两模式都有- 色阶差。不沿用 GhostPermissionList 的 --confirm-desc / --text-tertiary+ 色阶差。不沿用插件详情的 --confirm-desc / --text-tertiary—— 那对 token 在 Dark 下同为 #737373,两级层级会塌成同色,只剩字号差(2026-08 产品门 review 定的取舍)。 */}<p className="break-words text-13 font-medium leading-5 text-[var(--text-primary)]">diff --git a/apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts b/apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.tsindex 1c35c6b6e5..90e71fc96d 100644--- a/apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts+++ b/apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts@@ -25,7 +25,7 @@ export interface HostCapabilityChipMatch {}export function hostCapabilityForGhost(ghost: InstalledGhost): ComposerHostCapability | null {- return ghost.manifest.slots.includes(IOS_SIMULATOR_HOST_CAPABILITY)+ return ghost.manifest.iosSimulator === true? IOS_SIMULATOR_HOST_CAPABILITY: null;}diff --git a/apps/desktop/src/renderer/components/ui/confirm-dialog-provider.tsx b/apps/desktop/src/renderer/components/ui/confirm-dialog-provider.tsxindex 8299a7c049..f4321b2fd6 100644--- a/apps/desktop/src/renderer/components/ui/confirm-dialog-provider.tsx+++ b/apps/desktop/src/renderer/components/ui/confirm-dialog-provider.tsx@@ -35,15 +35,6 @@ export interface ConfirmOptions {* 破坏性确认(删除/重置等)请保持默认。*/autoFocusConfirm?: boolean;- /**- * 高危确认的「手输一致才放行」闸(见 ConfirmDialogProps.requireTypedConfirmation)。- * 设了就要求用户逐字打出 expected 才解锁主按钮;有它时焦点自动落到输入框。- */- requireTypedConfirmation?: {- expected: string;- label: string;- placeholder?: string;- };}const DONT_SHOW_AGAIN_PREFIX = 'confirm-dialog.skip:';@@ -291,7 +282,6 @@ export function ConfirmDialogProvider({ children }: { children: ReactNode }) {showCancel={currentItem.options.showCancel}tertiaryText={currentItem.options.tertiaryText}autoFocusConfirm={currentItem.options.autoFocusConfirm}- requireTypedConfirmation={currentItem.options.requireTypedConfirmation}dontShowAgainLabel={currentItem.options.dontShowAgainKey? currentItem.options.dontShowAgainLabel ?? '下次不再提示'diff --git a/apps/desktop/src/renderer/components/ui/confirm-dialog.tsx b/apps/desktop/src/renderer/components/ui/confirm-dialog.tsxindex 01668b46e0..d6aa561a76 100644--- a/apps/desktop/src/renderer/components/ui/confirm-dialog.tsx+++ b/apps/desktop/src/renderer/components/ui/confirm-dialog.tsx@@ -24,7 +24,7 @@ export interface ConfirmDialogProps {*/content?: ReactNode;/**- * 弹窗最大宽度(px),缺省 400。带富内容清单的弹窗(如意识装入确认)+ * 弹窗最大宽度(px),缺省 400。带富内容清单的弹窗* 用默认宽会折行到累,可适度放宽;普通二选一确认别动它。*/maxWidth?: number;@@ -38,8 +38,7 @@ export interface ConfirmDialogProps {dontShowAgainLabel?: string;/*** 复选框初始勾选态,缺省 false。"下次不再提示"类弹窗保持缺省;- * 业务复选框(confirmWithCheckbox)按调用方语义决定,如装意识的- * "立即开启"默认勾选。+ * 业务复选框(confirmWithCheckbox)按调用方语义决定初始状态。*/checkboxDefaultChecked?: boolean;/**@@ -50,20 +49,6 @@ export interface ConfirmDialogProps {autoFocusConfirm?: boolean;/** Disable the primary action until caller-owned validation has passed. */confirmDisabled?: boolean;- /**- * 高危确认的「手输一致才放行」闸(如 Agent 发起装入高危插件时手打插件 id)。- * 设了就在按钮上方渲染一个输入框,用户必须逐字打出 `expected` 才解锁主按钮 ——- * 这是比勾选框更强的确认:它逼用户对着确认框里的那个 id 亲手核对一遍,而不是- * 无脑点。输入状态由本组件持有(每次打开复位),不外泄给调用方。- */- requireTypedConfirmation?: {- /** 必须逐字打出的目标串(如插件 id)。 */- expected: string;- /** 输入框上方的说明,通常含 expected 的插值。 */- label: string;- /** 输入框 placeholder(缺省用 expected)。 */- placeholder?: string;- };/** 嵌套在其它 Dialog 内时提升层级;普通确认继续使用默认层级。 */zIndex?: number;/** Destructive actions use the semantic destructive theme tokens. */@@ -110,7 +95,6 @@ export function ConfirmDialog({checkboxDefaultChecked = false,autoFocusConfirm,confirmDisabled = false,- requireTypedConfirmation,confirmVariant = 'default',confirmIcon,describeContent = false,@@ -130,16 +114,7 @@ export function ConfirmDialog({useEffect(() => {if (open) setDontShowAgain(checkboxDefaultChecked);}, [open, checkboxDefaultChecked]);- // 手输确认串:每次打开复位为空,逐字打出 expected 前主按钮保持禁用。- const [typedConfirmation, setTypedConfirmation] = useState('');- useEffect(() => {- if (open) setTypedConfirmation('');- }, [open]);- const typedConfirmationSatisfied =- !requireTypedConfirmation || typedConfirmation.trim() === requireTypedConfirmation.expected;- const confirmBlocked = loading || confirmDisabled || !typedConfirmationSatisfied;const confirmBtnRef = useRef<HTMLButtonElement>(null);- const typedConfirmationRef = useRef<HTMLInputElement>(null);const scrollRef = useRef<HTMLDivElement>(null);// 滚动条 thumb 默认透明(globals.css),不滚不 hover 就看不见"下面还有内容"。// 授权确认场景里这不是观感问题:权限清单被折在视口下面而用户不知道,等于@@ -209,21 +184,14 @@ export function ConfirmDialog({if (loading) e.preventDefault();}}onOpenAutoFocus={- requireTypedConfirmation+ autoFocusConfirm? (e) => {- // 有手输闸时把焦点交给输入框:用户一开就在核对/输入 id,- // 而不是停在一个当前还被禁用的主按钮上。+ // Radix 默认聚焦第一个可聚焦元素 / Cancel —— 这里覆盖,+ // 把焦点交给主按钮,避免"取消"天然带 focus ring。e.preventDefault();- typedConfirmationRef.current?.focus();+ confirmBtnRef.current?.focus();}- : autoFocusConfirm- ? (e) => {- // Radix 默认聚焦第一个可聚焦元素 / Cancel —— 这里覆盖,- // 把焦点交给主按钮,避免"取消"天然带 focus ring。- e.preventDefault();- confirmBtnRef.current?.focus();- }- : undefined+ : undefined}><AlertDialog.Title@@ -237,7 +205,7 @@ export function ConfirmDialog({{(description || content) && (// 富内容 / 长正文可能超过视口高度:包一层限高滚动区,让标题与底部按钮// 固定、中间内容纵向滚动,避免整个弹窗被撑出屏幕后无法滚动到被裁掉的内容- // (典型:插件更新确认框的权限变更清单)。+ // (典型:带分组和折叠区的长确认内容)。<divref={scrollRef}id={describeContent && content ? bodyId : undefined}@@ -277,50 +245,11 @@ export function ConfirmDialog({{dontShowAgainLabel}</label>)}- {requireTypedConfirmation && (- <div className="mt-4 shrink-0">- <label- htmlFor={`${bodyId}-typed`}- className="block text-13 leading-[1.5] text-[var(--confirm-desc)]"- >- {requireTypedConfirmation.label}- </label>- <input- ref={typedConfirmationRef}- id={`${bodyId}-typed`}- type="text"- autoComplete="off"- autoCorrect="off"- autoCapitalize="off"- spellCheck={false}- value={typedConfirmation}- disabled={loading}- onChange={(e) => setTypedConfirmation(e.target.value)}- onKeyDown={(e) => {- // Enter 在闸满足时等同点主按钮;未满足则吞掉,不误触。- if (e.key === 'Enter' && typedConfirmationSatisfied && !loading) {- e.preventDefault();- onConfirm?.({ dontShowAgain });- }- }}- placeholder={- requireTypedConfirmation.placeholder ?? requireTypedConfirmation.expected- }- className={cn(- 'mt-1.5 h-9 w-full rounded-lg border px-3 text-13',- 'border-[var(--settings-input-border)] bg-[var(--settings-input-bg)]',- 'text-[var(--settings-input-text)] placeholder:text-[var(--text-placeholder)]',- 'outline-none focus:ring-2 focus:ring-[var(--focus-ring-soft)]',- 'disabled:cursor-not-allowed disabled:opacity-60',- )}- />- </div>- )}<div className="mt-6 flex shrink-0 justify-end gap-2.5"><AlertDialog.Action asChild><buttonref={confirmBtnRef}- disabled={confirmBlocked}+ disabled={loading || confirmDisabled}aria-busy={loading || undefined}aria-label={resolvedConfirmText}onClick={() => onConfirm?.({ dontShowAgain })}@@ -337,9 +266,7 @@ export function ConfirmDialog({loading &&confirmVariant === 'destructive' &&'cursor-default opacity-80 active:scale-100 hover:opacity-80',- !loading &&- (confirmDisabled || !typedConfirmationSatisfied) &&- 'cursor-not-allowed opacity-50 active:scale-100',+ confirmDisabled && 'cursor-not-allowed opacity-50 active:scale-100',)}>{loading ? (diff --git a/apps/desktop/src/renderer/features/plugin/GhostLibrarySection.tsx b/apps/desktop/src/renderer/features/plugin/GhostLibrarySection.tsxindex 40f5df3087..afd8ed55ba 100644--- a/apps/desktop/src/renderer/features/plugin/GhostLibrarySection.tsx+++ b/apps/desktop/src/renderer/features/plugin/GhostLibrarySection.tsx@@ -1,7 +1,7 @@/*** GhostLibrarySection — 插件详情页的「持久作品库」设置区(2026-08-20)。* ---------------------------------------------------------------------------- * 只在 manifest 声明 library 槽时渲染。职责:+ * 只在 manifest 声明 library 能力时渲染。职责:* - 展示位置(默认/自定义)、占用、磁盘余量、状态横幅(漂移/只读/orphaned);* - 更改位置(宿主弹原生选择器 → 候选校验 → 确认 → 迁移状态机);* - 恢复默认位置(反向迁移 + 撤销 binding);漂移时的「解除位置记录」恢复;@@ -36,11 +36,11 @@ function formatBytes(bytes: number): string {}/**- * 外层:未声明 library 槽直接不挂载内层(内层用了 useConfirmDialog,测试环境+ * 外层:未声明 library 能力直接不挂载内层(内层用了 useConfirmDialog,测试环境* 无 Provider——不声明就不进 hook,老用例零影响)。*/-export function GhostLibrarySection({ ghostId, slots }: { ghostId: string; slots: readonly string[] }) {- if (!slots.includes('library')) return null;+export function GhostLibrarySection({ ghostId, enabled }: { ghostId: string; enabled: boolean }) {+ if (!enabled) return null;return <GhostLibrarySectionInner ghostId={ghostId} />;}diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsxindex e1803d48c8..c876bf71e7 100644--- a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx@@ -90,8 +90,8 @@ interface GhostPluginDetailViewProps {/** 头部更新 CTA:市场有新版本时走市场更新确认流。 */onUpdate: () => void;/**- * 缺少批准状态时的恢复入口(重新走一次完整权限确认)。可选:仅插件页宿主注入;- * 未注入时按钮不出现,门控见下方 `needsReapproval && !detail.builtin && onReapprove`。+ * 安装记录缺失或损坏时的恢复入口。可选:仅插件页宿主注入;未注入时按钮不出现,+ * 门控见下方 `needsReapproval && !detail.builtin && onReapprove`。*/onReapprove?: () => void;/** ⋮ 菜单的兜底路径:从本地 .cindy 文件更新。 */@@ -179,8 +179,8 @@ export function GhostPluginDetailView({const [descriptionExpanded, setDescriptionExpanded] = useState(false);const [descriptionOverflows, setDescriptionOverflows] = useState(false);const descriptionRef = useRef<HTMLParagraphElement>(null);- // 未批准的安装不可运行:enabled 直接门控为 false(说明现状 + 给恢复入口,不让它- // 看起来只是"被关掉了"),再喂既有 primaryAction/primaryEnabled。+ // 安装记录不完整时不可运行:enabled 直接门控为 false(说明现状 + 给恢复入口,不让它+ // 看起来只是"被关掉了"),再喂 main 改版的 primaryAction/primaryEnabled。const needsReapproval = detail.approvalState !== 'approved';const enabled = (enabledOverride ?? detail.enabled) && !needsReapproval;const primaryAction = ghostPrimaryAction(detail);@@ -355,12 +355,13 @@ export function GhostPluginDetailView({{/* 启用开关带明确文字(设计定稿):状态一目了然,点文字同样可切换。 */}<buttontype="button"+ role="switch"onClick={() => {// 未批准的安装不可切换启用(点了 Main 也会拒);与 updateBusy 同级门控。if (!toggleDisabled && !needsReapproval) onToggle(!enabled);}}disabled={toggleDisabled || needsReapproval}- aria-pressed={enabled}+ aria-checked={enabled}aria-label={t('settings.ghosts.enableAria', { name: detail.name })}className={cn('flex shrink-0 items-center gap-2 rounded-full py-1 pl-3 pr-1 transition-colors duration-150',@@ -380,13 +381,24 @@ export function GhostPluginDetailView({: 'settings.ghosts.detail.disabledLabel',)}</span>- <Switch- checked={enabled}- disabled={toggleDisabled || needsReapproval}+ <spanaria-hidden="true"- tabIndex={-1}- className="pointer-events-none"- />+ className={cn(+ 'inline-flex h-5 w-9 shrink-0 items-center rounded-full border-2 border-transparent transition-colors',+ enabled+ ? 'bg-[var(--switch-track-on)]'+ : 'bg-[var(--switch-track-off)]',+ )}+ >+ <span+ className={cn(+ 'block h-4 w-4 rounded-full ring-0 transition-transform',+ enabled+ ? 'translate-x-4 bg-background'+ : 'translate-x-0 bg-[var(--switch-thumb-off)]',+ )}+ />+ </span></button><DropdownMenu><DropdownMenuTrigger asChild>@@ -567,7 +579,7 @@ export function GhostPluginDetailView({{detail.permissions.length > 0 ? <PermissionSummary items={detail.permissions} /> : null}- <GhostLibrarySection ghostId={detail.id} slots={ghost?.manifest.slots ?? []} />+ <GhostLibrarySection ghostId={detail.id} enabled={ghost?.manifest.library === true} /><DetailsSection detail={detail} panelStatus={panelStatus} /></article>diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsxindex c66a08710e..7f5244b102 100644--- a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx@@ -56,16 +56,7 @@ import {} from '@/lib/composerDraftStore';import { resetDraftWorkspaceTargets } from '@/state/newMakerDraft';import { ghostInstallErrorKey } from '@/cindy-brain/installErrorKey';-import {- confirmAndInstallGhost,- pickAndUpdateGhost,- reapproveInstalledGhost,-} from '@/cindy-brain/installFlow';-import {- GhostManualSummary,- GhostPermissionList,- GhostUpdateReview,-} from '@/cindy-brain/GhostPermissionList';+import { installGhostFromFile, pickAndUpdateGhost } from '@/cindy-brain/installFlow';import { Spinner } from '@/components/ui/spinner';import { cn } from '@/lib/utils';import { AttentionDot } from '@/components/sidebar/AttentionDot';@@ -78,11 +69,8 @@ import { getLastWorkingDir, subscribeToLastWorkingDir } from '@/state/lastWorkinimport { findSplitChildByPanelKind } from '../../../shared/layoutTree';import { resolveSystemLocale } from '../../../shared/locale';import {- diffInstalledGhostPermissionItems,ghostInstallApprovalToken,ghostPanelKind,- ghostPermissionBaselineKey,- ghostPermissionItems,isOfficialGhostId,type GhostSetupStatus,type InstalledGhost,@@ -109,11 +97,9 @@ import {import { MyPublishesSection } from './MyPublishesSection';import { ignoredRoundStorageKey, isBatchFinished, updateRoundKey } from './lib/updateAllModel';import {- approveUpdateExpansion,getUpdateAllBatchState,reconcileUpdateAllBatch,setUpdateAllBatchHooks,- skipUpdateExpansion,startUpdateAllBatch,subscribeUpdateAllBatch,} from './lib/updateAllController';@@ -137,8 +123,6 @@ import { GhostPluginIcon } from './GhostPluginIcon';import { MarketPluginDetailView } from './MarketPluginDetailView';import { PluginScopePicker, usePluginRecentWorkdirs } from './PluginScopePicker';import {- // 受体模型的两条纯推导:reapprove 路由判定 + 「市场复核目标是否命中已装」。- // main 的卡片改版不再走 catalogItems 交织,orderPluginCatalogItems 已无引用故不引入。canOfferMarketInstall,ghostReapprovalRoute,marketReviewTargetsInstalledGhost,@@ -371,25 +355,7 @@ export const __installedPluginLayoutForTests = {InstalledPluginDisclosure,};-export function diffMarketUpdatePermissionItems(- installed: InstalledGhost,- next: PluginMarketDetail['manifest'],-) {- return diffInstalledGhostPermissionItems(installed, next);-}--export function marketUpdateAllowsPermissionExpansion(- installed: InstalledGhost,- addedPermissionCount: number,-): boolean {- return installed.approval.state !== 'approved' || addedPermissionCount > 0;-}--/**- * 市场装入成功后是否打开已装详情(同时收起市场详情)。- * 首装:装完即开(2026-07-26)。更新/替换:留在当前页——列表就留列表,- * 市场详情就刷新详情,方便连续更新,也不把替换用户从原详情踢回列表。- */+/** 市场首装成功后打开已装详情;更新或来源替换继续停留在当前页面。 */export function shouldOpenInstalledDetailAfterMarketSuccess(isUpdate: boolean): boolean {return !isUpdate;}@@ -422,14 +388,23 @@ export function GhostPluginPage({const navigate = useNavigate();const [searchParams, setSearchParams] = useSearchParams();const { confirm } = useConfirmDialog();+ const showPluginMarketActionError = useCallback(+ async (error: unknown) => {+ toast.error(t(pluginMarketErrorKey(error)));+ },+ [t],+ );const { user, mode, dataOwnerId } = useAuth();const showEnterprise = user?.membershipKind === 'org';const ghosts = useInstalledGhosts();useMainViewVisibilityRevision();- const installedGhostIds = useMemo(() => ghosts.map((ghost) => ghost.manifest.id), [ghosts]);- const installedGhostIdsKey = useMemo(- () => [...installedGhostIds].sort().join('\0'),- [installedGhostIds],+ const installedGhostMarketKey = useMemo(+ () =>+ ghosts+ .map((ghost) => `${ghost.manifest.id}\0${ghost.manifest.version}`)+ .sort()+ .join('\0'),+ [ghosts],);const installedGhostLocationsKey = ghosts.map((ghost) => `${ghost.manifest.id}\0${ghost.dir}`)@@ -475,7 +450,7 @@ export function GhostPluginPage({const marketRefreshRequestRef = useRef(0);const lastMarketRefreshAtRef = useRef(0);const marketDetailRequestRef = useRef(0);- const installedGhostIdsKeyRef = useRef(installedGhostIdsKey);+ const installedGhostMarketKeyRef = useRef(installedGhostMarketKey);const legacyRecoveryStatusRequestRef = useRef(0);const legacyRecoveryRetryRequestRef = useRef(0);const [legacyRecoveryStatus, setLegacyRecoveryStatus] =@@ -521,21 +496,12 @@ export function GhostPluginPage({}, [refreshMarket, mode, dataOwnerId]);const refreshMarketOnForeground = useCallback(() => refreshMarket(true), [refreshMarket]);usePluginMarketForegroundRefresh(refreshMarketOnForeground, lastMarketRefreshAtRef);- useEffect(- () =>- window.electronAPI.pluginMarket.onUpgradeNoticeAvailable(() => {- // 默认插件升级在初始快照返回后异步落位;原位升级不会改变已装 ID,- // 复用现有完成通知刷新目录,避免继续展示旧 release 的更新入口。- void refreshMarket(true).catch(() => undefined);- }),- [refreshMarket],- );useEffect(() => {- if (installedGhostIdsKeyRef.current === installedGhostIdsKey) return;- installedGhostIdsKeyRef.current = installedGhostIdsKey;- // 已装集合变化(装/卸)时刷新市场;排序是反应式的,没有快照需要维护。+ if (installedGhostMarketKeyRef.current === installedGhostMarketKey) return;+ installedGhostMarketKeyRef.current = installedGhostMarketKey;+ // 已装集合或版本变化(装/卸/后台更新)时刷新市场;排序是反应式的。void refreshMarket(true).catch(() => undefined);- }, [installedGhostIdsKey, refreshMarket]);+ }, [installedGhostMarketKey, refreshMarket]);const activeSessionWorkingDir = useSyncExternalStore(subscribeToLastWorkingDir,getLastWorkingDir,@@ -795,7 +761,7 @@ export function GhostPluginPage({);const hiddenInstalledCount = Math.max(0, displayInstalledItems.length - visibleInstalledCount);- // ── 更新横幅与批量更新(设计定稿:全部更新;扩权单独确认,绝不静默放行)──+ // ── 更新横幅与批量更新:作为自动更新失败/忙碌跳过后的手动重试入口 ──const updatableInstalledItems = useMemo(() => installedItems.filter((item) => item.marketUpdate !== null),[installedItems],@@ -811,7 +777,7 @@ export function GhostPluginPage({}, [currentRoundKey, ignoredRoundKey]);// 批次状态住在模块级控制器里(生命周期长于本页:关弹窗离开 /plugins- // 后批次继续跑),页面只订阅快照。权限确认由统一安装事务负责。+ // 后批次继续跑),页面只订阅快照。真实包校验与落位由统一安装事务负责。const updateBatch = useSyncExternalStore(subscribeUpdateAllBatch, getUpdateAllBatchState);const updateRows = updateBatch.rows;const batchRunning = updateBatch.running;@@ -927,31 +893,29 @@ export function GhostPluginPage({[t],);- /** 下载真实包;权限卡已在页面确认,Host 只在真实包超出已审清单时再弹。 */- const installReviewedMarketPackage = useCallback(+ /** Main 在同一次 install IPC 事务内校验真实包与市场声明的能力上限。 */+ const installMarketPackage = useCallback(async (input: {pluginId: string;options: PluginMarketInstallOptions;+ isStillActive: () => boolean;}): Promise<InstalledGhost | null> => {const result = await window.electronAPI.pluginMarket.install(input.pluginId, input.options);- return result.ghost ?? null;+ if (!input.isStillActive()) return null;+ return result.ghost;},[],);- // 市场更新流程由列表卡片和详情页共用:先按市场清单立刻弹出确认,下载发生在- // 用户点确认之后。真实包若没有超出已确认的权限,窗口级 Host 不再复弹。- //- // 同版本的 `installed` 也走这里:缺少批准状态的存量安装靠"用市场包重装同一- // release"恢复,此时权限 diff 会把目标包的全部权限当新增项逐条列出。- // 原位更新不切换来源(#2043):点击后详情若已不再是 update-available 则如实- // 提示状态变化,install 一律 allowSourceReplacement: false。+ // 目录详情用于发现与能力展示;点击更新后由 Main 下载并校验真实包后直接落位。const handleMarketUpdate = useCallback(async (ghostId: string) => {const marketItem = marketByGhostId.get(ghostId);- if (!marketItem) return;const installedGhost = ghosts.find((ghost) => ghost.manifest.id === ghostId) ?? null;- if (!marketReviewTargetsInstalledGhost(marketItem, installedGhost?.approval.state)) {+ if (+ !marketItem ||+ !marketReviewTargetsInstalledGhost(marketItem, installedGhost?.approval.state)+ ) {return;}if (!installedGhost) {@@ -965,49 +929,21 @@ export function GhostPluginPage({try {const next = await window.electronAPI.pluginMarket.detail(marketItem.pluginId);if (!isMarketBusyLeaseActive(marketBusyLease)) return;- // 来源隔离 + 状态新鲜度(#2043):重取详情后若已不再是可更新/可重审的- // 目标(conflict 换源、已装已批准等),如实提示状态变化并刷新,不静默继续。- // `installed` 且未批准的同版本恢复仍放行(见 marketReviewTargetsInstalledGhost)。- if (- next.installState !== 'update-available' &&- !marketReviewTargetsInstalledGhost(next, installedGhost?.approval.state)- ) {+ if (!marketReviewTargetsInstalledGhost(next, installedGhost.approval.state)) {toast.error(t('settings.ghosts.market.errors.stateChanged'));await refreshMarket();return;}- const diff = diffMarketUpdatePermissionItems(installedGhost, next.manifest);const options: PluginMarketInstallOptions = {expectedReleaseId: next.releaseId,expectedManifest: next.manifest,expectedInstalledApproval: ghostInstallApprovalToken(installedGhost.approval),- allowPermissionExpansion: marketUpdateAllowsPermissionExpansion(- installedGhost,- diff.added.length,- ),- ...(installedGhost- ? { reviewedBaseline: ghostPermissionBaselineKey(installedGhost.manifest) }- : {}),- // 原位更新不切换来源(#2043):只有冲突替换显式走 runMarketInstallFlow。allowSourceReplacement: false,};- const approved = await confirm({- title: t('settings.ghosts.updateConfirm.title', { name: next.name }),- description: t('settings.ghosts.updateConfirm.body', {- from: installedGhost?.manifest.version ?? next.version,- to: next.version,- }),- content: (- <GhostUpdateReview diff={diff} manualCount={next.manifest.manual?.items.length ?? 0} />- ),- maxWidth: 520,- confirmText: t('settings.ghosts.updateConfirm.confirm'),- cancelText: t('settings.ghosts.updateConfirm.cancel'),- });- if (!approved || !isMarketBusyLeaseActive(marketBusyLease)) return;- const ghost = await installReviewedMarketPackage({+ const ghost = await installMarketPackage({pluginId: next.pluginId,options,+ isStillActive: () => isMarketBusyLeaseActive(marketBusyLease),});if (!ghost || !isMarketBusyLeaseActive(marketBusyLease)) return;toast.success(@@ -1020,7 +956,7 @@ export function GhostPluginPage({await refreshMarket();} catch (error) {if (isMarketBusyLeaseActive(marketBusyLease)) {- toast.error(t(pluginMarketErrorKey(error)));+ await showPluginMarketActionError(error);}} finally {releaseMarketBusy(marketBusyLease);@@ -1030,10 +966,11 @@ export function GhostPluginPage({acquireMarketBusy,ghosts,isMarketBusyLeaseActive,- installReviewedMarketPackage,+ installMarketPackage,marketByGhostId,refreshMarket,releaseMarketBusy,+ showPluginMarketActionError,t,],);@@ -1044,37 +981,37 @@ export function GhostPluginPage({await handleMarketUpdate(selectedDetail.id);return;}- await pickAndUpdateGhost(selectedDetail.id, { t, confirm });- }, [confirm, handleMarketUpdate, selectedDetail, selectedMarketUpdate, t]);+ await pickAndUpdateGhost(selectedDetail.id, { t });+ }, [handleMarketUpdate, selectedDetail, selectedMarketUpdate, t]);/**- * 缺少批准状态时的恢复入口。市场自有的包重走市场安装确认(重新下载 + 逐项- * 权限确认);本地包让用户重新选一次 `.cindy`。两条路都落到同一套权限确认,- * 不存在"点一下就悄悄恢复运行"的分支。+ * 安装验证记录缺失或损坏时,用户主动选择重新落位同一来源的真实包。+ * 市场包重装当前 release;本地包重新选择 `.cindy`。两条路都只恢复+ * 完整安装记录,不新增能力确认。*/- const handleReapprove = useCallback(+ const handleRecoverInstall = useCallback(async (ghostId: string) => {- // 随包插件不走人工重新确认(入口已隐藏,这里是防御):批准由启动对账自动补。- if (ghosts.find((g) => g.manifest.id === ghostId)?.builtin) return;+ if (ghosts.find((ghost) => ghost.manifest.id === ghostId)?.builtin) return;if (ghostReapprovalRoute(marketByGhostId.get(ghostId)) === 'market') {await handleMarketUpdate(ghostId);return;}- // 本地包路线:从已装目录读全量权限清单确认后开 receipt,不用用户翻出原始- // .cindy 文件;目录读不出时该流程内部自动回退到"重新选包"。- await reapproveInstalledGhost(ghostId, { t, confirm });+ await pickAndUpdateGhost(ghostId, { t });},- [confirm, ghosts, handleMarketUpdate, marketByGhostId, t],+ [ghosts, handleMarketUpdate, marketByGhostId, t],);const handleUpdateFromFile = useCallback(async () => {if (!selectedDetail) return;- await pickAndUpdateGhost(selectedDetail.id, { t, confirm });- }, [confirm, selectedDetail, t]);+ await pickAndUpdateGhost(selectedDetail.id, { t });+ }, [selectedDetail, t]);- // 控制器在挂载期借用本页的市场刷新;卸载后批次继续跑,重新进页全量刷新。+ // 控制器在挂载期借用本页的市场刷新。useEffect(- () => setUpdateAllBatchHooks({ refreshMarket: () => refreshMarket() }),+ () =>+ setUpdateAllBatchHooks({+ refreshMarket: () => refreshMarket(),+ }),[refreshMarket],);const handleUpdateAll = useCallback(() => {@@ -1111,17 +1048,15 @@ export function GhostPluginPage({const handleInstall = useCallback(async () => {const picked = await window.electronAPI.ghosts.pickFile().catch(() => null);if (!picked || 'canceled' in picked) return;- // 设置页选文件是用户亲手操作 → 手动来源(不传 origin),不加横幅、不加重。- await confirmAndInstallGhost(picked.filePath, {+ await installGhostFromFile(picked.filePath, {t,- confirm,- // 已在插件页:tab 型插件装入即生效后原地开面板。+ // 已在插件页:tab 型插件安装后原地打开面板。openPluginPanel: (ghostId) => {setSelectedId(null);setOpenPanelId(ghostId);},});- }, [confirm, t]);+ }, [t]);const handleRetryLegacyRecovery = useCallback(async () => {legacyRecoveryStatusRequestRef.current += 1;@@ -1175,7 +1110,7 @@ export function GhostPluginPage({async (id: string, displayName: string) => {const ghost = ghosts.find((candidate) => candidate.manifest.id === id);if (!ghost) return;- const opensIOSSimulator = ghost.manifest.slots.includes('ios-simulator');+ const opensIOSSimulator = ghost.manifest.iosSimulator === true;if (!ghost.manifest.command && !opensIOSSimulator) return;const usesHostCapabilityEntry = !ghost.manifest.command && opensIOSSimulator;// 使用前置门:点击时现查配置就绪度(main 侧确定性判定),未就绪先@@ -1391,63 +1326,20 @@ export function GhostPluginPage({await refreshMarket();return;}- const diff = isUpdate- ? diffMarketUpdatePermissionItems(installedGhost!, marketDetail.manifest)- : null;+ if (!isMarketBusyLeaseActive(marketBusyLease)) return;const options: PluginMarketInstallOptions = {expectedReleaseId: marketDetail.releaseId,expectedManifest: marketDetail.manifest,...(isUpdate && installedGhost? { expectedInstalledApproval: ghostInstallApprovalToken(installedGhost.approval) }: {}),- ...(isUpdate && (diff!.added.length > 0 || installedGhost?.approval.state !== 'approved')- ? {- allowPermissionExpansion: true,- ...(installedGhost- ? { reviewedBaseline: ghostPermissionBaselineKey(installedGhost.manifest) }- : {}),- }- : {}),// 来源隔离(#2043):仅用户显式选择的冲突替换允许切换来源;更新与原位安装不切换。allowSourceReplacement: marketDetail.installState === 'conflict',};- const confirmed = await confirm({- title: isUpdate- ? t('settings.ghosts.updateConfirm.title', { name: marketDetail.name })- : t('settings.ghosts.market.installConfirmTitle', {- name: marketDetail.name,- }),- description: isUpdate- ? t('settings.ghosts.market.updateConfirmDescription')- : t(- marketDetail.sourceType === 'server'- ? 'settings.ghosts.market.installConfirmDescription'- : 'settings.ghosts.market.customInstallConfirmDescription',- ),- content: isUpdate ? (- <GhostUpdateReview- diff={diff!}- manualCount={marketDetail.manifest.manual?.items.length ?? 0}- />- ) : (- <div>- <GhostManualSummary count={marketDetail.manifest.manual?.items.length ?? 0} />- <GhostPermissionList items={ghostPermissionItems(marketDetail.manifest)} />- </div>- ),- maxWidth: 520,- confirmText: isUpdate- ? t('settings.ghosts.updateConfirm.confirm')- : t('settings.ghosts.market.install'),- cancelText: isUpdate- ? t('settings.ghosts.updateConfirm.cancel')- : t('settings.ghosts.installConfirm.cancel'),- autoFocusConfirm: true,- });- if (!confirmed || !isMarketBusyLeaseActive(marketBusyLease)) return;- const ghost = await installReviewedMarketPackage({+ const ghost = await installMarketPackage({pluginId: marketDetail.pluginId,options,+ isStillActive: () => isMarketBusyLeaseActive(marketBusyLease),});if (!ghost || !isMarketBusyLeaseActive(marketBusyLease)) return;// 市场首装装完即开(2026-07-26 定案),toast 用"已安装";更新路径如实@@ -1473,7 +1365,7 @@ export function GhostPluginPage({await refreshMarket();} catch (error) {if (isMarketBusyLeaseActive(marketBusyLease)) {- toast.error(t(pluginMarketErrorKey(error)));+ await showPluginMarketActionError(error);}} finally {releaseMarketBusy(marketBusyLease);@@ -1483,10 +1375,11 @@ export function GhostPluginPage({acquireMarketBusy,ghosts,isMarketBusyLeaseActive,- installReviewedMarketPackage,+ installMarketPackage,refreshMarket,refreshVisibleMarketDetail,releaseMarketBusy,+ showPluginMarketActionError,t,],);@@ -1573,9 +1466,7 @@ export function GhostPluginPage({onMainViewSidebarVisibleChange={handleMainViewSidebarVisibleChange}onUpdate={() => void handleUpdate()}onUpdateFromFile={() => void handleUpdateFromFile()}- // 受体模型的 §5 恢复入口:缺批准的安装在详情页重新确认(市场包重装 /- // 本地包读目录权限确认),详情视图据 needsReapproval 门控运行按钮。- onReapprove={() => void handleReapprove(selectedDetail.id)}+ onReapprove={() => void handleRecoverInstall(selectedDetail.id)}updateVersion={selectedMarketUpdate?.version}updateBusy={(selectedMarketUpdate !== null && marketBusyId !== null) || batchRunning}onUninstall={() => void handleUninstall()}@@ -1956,8 +1847,6 @@ export function GhostPluginPage({open={updateDialogOpen}rows={updateRows}iconByGhostId={new Map(ghosts.map((ghost) => [ghost.manifest.id, ghost.iconDataUrl]))}- onApprove={(pluginId) => void approveUpdateExpansion(pluginId)}- onSkip={skipUpdateExpansion}onClose={() => setUpdateDialogOpen(false)}/>) : null}diff --git a/apps/desktop/src/renderer/features/plugin/PluginMarketPermissionReviewHost.tsx b/apps/desktop/src/renderer/features/plugin/PluginMarketPermissionReviewHost.tsxdeleted file mode 100644index acc3522e57..0000000000--- a/apps/desktop/src/renderer/features/plugin/PluginMarketPermissionReviewHost.tsx+++ /dev/null@@ -1,108 +0,0 @@-import { useEffect } from 'react';-import { useTranslation } from 'react-i18next';--import {- GhostManualSummary,- GhostOauthClientChangedAlert,- GhostPermissionList,- GhostUpdateReview,-} from '@/cindy-brain/GhostPermissionList';-import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';-import { isDataOwnerPushStampCurrent } from '@/contexts/dataOwnerGeneration';-import { ghostPermissionItems } from '../../../shared/ghost';--/**- * 市场安装事务的真实包权限确认入口。- *- * Main 下载并检查真实包后把事务暂停在调用栈内,只向发起窗口投递这一张确认卡。- * 无论确认、取消、Esc、遮罩关闭还是渲染异常,finally 都会把答案回给 Main;- * Main 随后继续安装或取消事务,并在自己的 finally 中删除临时包。- */-export function PluginMarketPermissionReviewHost() {- const { t } = useTranslation();- const { confirm } = useConfirmDialog();-- useEffect(() => {- return window.electronAPI.pluginMarket.onPackagePermissionReview((review) => {- if (!review || typeof review.requestId !== 'string') return;- void (async () => {- let confirmed = false;- let unsubscribeAuth: () => void = () => undefined;- try {- // 先核对 Main 投递时的 owner stamp,再读取或渲染任何私有包事实。- if (!isDataOwnerPushStampCurrent(review.ownerStamp)) return;- const ownerStamp = review.ownerStamp;- const abort = new AbortController();- unsubscribeAuth = window.electronAPI.onAuthStateChange((state) => {- if (- state.dataOwnerId !== ownerStamp.dataOwnerId ||- state.ownerGeneration !== ownerStamp.ownerGeneration- ) {- abort.abort();- }- });- // 订阅前后无 await,但 AuthContext 可能已先消费同一 auth push;再核对一次- // 可同时覆盖回调顺序差异和未来同步 listener 实现。- if (!isDataOwnerPushStampCurrent(ownerStamp)) abort.abort();- const isUpdate = review.isUpdate;- confirmed = await confirm(- {- title: isUpdate- ? t('settings.ghosts.updateConfirm.title', { name: review.manifest.name })- : t('settings.ghosts.market.installConfirmTitle', {- name: review.manifest.name,- }),- description: isUpdate- ? t('settings.ghosts.market.updateConfirmDescription')- : t(- review.sourceType === 'server'- ? 'settings.ghosts.market.installConfirmDescription'- : 'settings.ghosts.market.customInstallConfirmDescription',- ),- content: review.permissionDiff ? (- <GhostUpdateReview- diff={{- ...review.permissionDiff,- builtinOauthClientChanged:- review.permissionDiff.builtinOauthClientChanged ||- review.builtinOauthClientChanged === true,- }}- manualCount={review.manifest.manual?.items.length ?? 0}- />- ) : (- <div>- {review.builtinOauthClientChanged === true ? (- <GhostOauthClientChangedAlert />- ) : null}- <GhostManualSummary count={review.manifest.manual?.items.length ?? 0} />- <GhostPermissionList items={ghostPermissionItems(review.manifest)} />- </div>- ),- maxWidth: 520,- confirmText: isUpdate- ? t('settings.ghosts.updateConfirm.confirm')- : t('settings.ghosts.market.install'),- cancelText: isUpdate- ? t('settings.ghosts.updateConfirm.cancel')- : t('settings.ghosts.installConfirm.cancel'),- autoFocusConfirm: true,- },- abort.signal,- );- } finally {- unsubscribeAuth();- try {- await window.electronAPI.pluginMarket.resolvePackagePermissionReview(- review.requestId,- confirmed,- );- } catch {- // 窗口销毁时 Main 会把等待中的事务按取消结算。- }- }- })();- });- }, [confirm, t]);-- return null;-}diff --git a/apps/desktop/src/renderer/features/plugin/UpdateAllDialog.tsx b/apps/desktop/src/renderer/features/plugin/UpdateAllDialog.tsxindex 638d1fd441..2e6cd20a70 100644--- a/apps/desktop/src/renderer/features/plugin/UpdateAllDialog.tsx+++ b/apps/desktop/src/renderer/features/plugin/UpdateAllDialog.tsx@@ -1,20 +1,18 @@/**- * Batch plugin update dialog: auto rows stream through, permission- * expansions wait for explicit per-row consent.+ * Batch plugin update dialog: rows stream through the unified Main install+ * transaction and only expose progress here.** Inputs: live batch rows owned by the Plugin page runner plus row actions.* Outputs: progress presentation only; no IPC and no batch policy here.* [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md*/-import { useState } from 'react';import * as Dialog from '@radix-ui/react-dialog';import { Check, X } from 'lucide-react';import { useTranslation } from 'react-i18next';import { WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';import { Spinner } from '@/components/ui/spinner';-import { GhostPermissionDiffView } from '@/cindy-brain/GhostPermissionList';import { cn } from '@/lib/utils';import { GhostPluginIcon } from './GhostPluginIcon';import { isBatchFinished, type UpdateAllRow } from './lib/updateAllModel';@@ -23,8 +21,6 @@ interface UpdateAllDialogProps {open: boolean;rows: readonly UpdateAllRow[];iconByGhostId: ReadonlyMap<string, string | undefined>;- onApprove: (pluginId: string) => void;- onSkip: (pluginId: string) => void;/** 关弹窗;批量运行器继续在页面组件里跑(「后台继续」语义)。 */onClose: () => void;}@@ -73,12 +69,9 @@ export function UpdateAllDialog({open,rows,iconByGhostId,- onApprove,- onSkip,onClose,}: UpdateAllDialogProps) {const { t } = useTranslation();- const [expandedId, setExpandedId] = useState<string | null>(null);const finished = isBatchFinished(rows);return (<Dialog.Root open={open} onOpenChange={(next) => (next ? undefined : onClose())}>@@ -108,106 +101,33 @@ export function UpdateAllDialog({</Dialog.Close></div><div className="overflow-y-auto px-6 py-2">- {rows.map((row) => {- const expanded = row.status === 'needs-confirm' && expandedId === row.pluginId;- return (- <div- key={row.pluginId}- className="border-b-[0.5px] border-[var(--border-default)] py-3.5 last:border-b-0"- >- <div className="flex items-center gap-3">- <GhostPluginIcon- iconDataUrl={iconByGhostId.get(row.ghostId)}- iconId={row.ghostId}- iconName={row.name}- size="menu"- />- <div className="min-w-0 flex-1">- <p className="truncate text-13 font-medium leading-5">{row.name}</p>- <p className="text-11 text-[var(--text-tertiary)]">- {t('settings.ghosts.updateAll.versionRange', {- from: row.fromVersion,- to: row.toVersion,- })}- {row.status === 'needs-confirm' ? (- <>- {' · '}- <span className="text-[var(--text-primary)]">- {t(- row.staleReview- ? 'settings.ghosts.updateAll.reviewOutdated'- : 'settings.ghosts.updateAll.permissionChanged',- )}- </span>- </>- ) : null}- </p>- </div>- <div className="flex shrink-0 items-center gap-2">- {row.status === 'needs-confirm' && row.staleReview ? (- // 旧差异已随外部更新失效:点这里让控制器重新取详情重算,- // 权限没扩张就直接更新,仍有扩张则回到逐项审阅。- <button- type="button"- onClick={() => onApprove(row.pluginId)}- className={cn(- 'inline-flex h-7 items-center rounded-full border border-[var(--border-default)] px-3 text-12 font-medium text-[var(--text-primary)]',- 'transition-colors duration-150 hover:bg-[var(--surface-hover-soft)]',- 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',- )}- >- {t('settings.ghosts.updateAll.rereview')}- </button>- ) : row.status === 'needs-confirm' ? (- <button- type="button"- aria-expanded={expanded}- onClick={() =>- setExpandedId((current) =>- current === row.pluginId ? null : row.pluginId,- )- }- className={cn(- 'inline-flex h-7 items-center rounded-full border border-[var(--border-default)] px-3 text-12 font-medium text-[var(--text-primary)]',- 'transition-colors duration-150 hover:bg-[var(--surface-hover-soft)]',- 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',- )}- >- {t(- expanded- ? 'settings.ghosts.updateAll.collapseDiff'- : 'settings.ghosts.updateAll.reviewDiff',- )}- </button>- ) : (- <RowStatus row={row} />- )}- </div>+ {rows.map((row) => (+ <div+ key={row.pluginId}+ className="border-b-[0.5px] border-[var(--border-default)] py-3.5 last:border-b-0"+ >+ <div className="flex items-center gap-3">+ <GhostPluginIcon+ iconDataUrl={iconByGhostId.get(row.ghostId)}+ iconId={row.ghostId}+ iconName={row.name}+ size="menu"+ />+ <div className="min-w-0 flex-1">+ <p className="truncate text-13 font-medium leading-5">{row.name}</p>+ <p className="text-11 text-[var(--text-tertiary)]">+ {t('settings.ghosts.updateAll.versionRange', {+ from: row.fromVersion,+ to: row.toVersion,+ })}+ </p>+ </div>+ <div className="flex shrink-0 items-center gap-2">+ <RowStatus row={row} /></div>- {expanded && row.permissionDiff ? (- <div className="ml-9 mt-3 rounded-lg border-[0.5px] border-[var(--border-default)] bg-[var(--surface)] px-4 py-3">- <GhostPermissionDiffView diff={row.permissionDiff} />- <div className="mt-3 flex items-center gap-2">- <button- type="button"- onClick={() => onApprove(row.pluginId)}- className="inline-flex h-8 items-center rounded-full bg-[var(--accent-cta-bg)] px-4 text-12 font-medium text-[var(--accent-pure-cta-fg)] transition-transform duration-150 hover:bg-[var(--accent-hover)] active:scale-[0.98] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"- >- {t('settings.ghosts.updateAll.approve')}- </button>- <button- type="button"- onClick={() => onSkip(row.pluginId)}- className="inline-flex h-8 items-center rounded-full border border-[var(--border-default)] px-4 text-12 font-medium text-[var(--text-primary)] transition-colors duration-150 hover:bg-[var(--surface-hover-soft)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"- >- {t('settings.ghosts.updateAll.skip')}- </button>- </div>- </div>- ) : null}</div>- );- })}+ </div>+ ))}</div><div className="flex items-center justify-end gap-2 border-t-[0.5px] border-[var(--border-default)] px-6 py-4"><buttondiff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsxindex 2ebfbecbec..6ddf4988ce 100644--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx@@ -29,10 +29,8 @@ vi.mock('@/contexts/AuthContext', () => ({import {__installedPluginLayoutForTests,- diffMarketUpdatePermissionItems,GhostPluginCard,LegacyGhostRecoveryNotice,- marketUpdateAllowsPermissionExpansion,MarketPluginCard,MyPublishesSectionVisibilityGate,SHOW_MY_PUBLISHES_SECTION,@@ -43,7 +41,6 @@ import {__resetGhostUnreadForTest,} from '@/cindy-brain/ghostUnreadStore';import type { GhostPluginListItem } from '../lib/ghostPluginViewModel';-import type { InstalledGhost } from '../../../../shared/ghost';import type { PluginMarketItem } from '../../../../shared/pluginMarket';const {@@ -154,58 +151,6 @@ describe('MyPublishesSectionVisibilityGate', () => {});});-describe('diffMarketUpdatePermissionItems', () => {- it.each(['legacy-unapproved', 'invalid'] as const)(- 'reviews every target permission for a %s install',- (approvalState) => {- const manifest = {- schemaVersion: 2 as const,- id: 'legacy-plugin',- name: 'Legacy Plugin',- description: 'Legacy approval regression fixture',- author: 'Cindy',- version: '1.0.0',- kind: 'chip' as const,- entry: 'main.js',- slots: ['notify'] as ['notify'],- };- const installed = {- manifest,- dir: 'C:\\plugins\\legacy-plugin',- enabled: false,- approval: { state: approvalState },- };- const next = {- ...manifest,- version: '2.0.0',- slots: ['notify', 'fs'] as ['notify', 'fs'],- };-- const diff = diffMarketUpdatePermissionItems(installed, next);- expect(diff.added.map((item) => item.key)).toEqual(expect.arrayContaining(['notify', 'fs']));- expect(diff.removed).toEqual([]);- expect(diff.unchanged).toEqual([]);- },- );-});--describe('marketUpdateAllowsPermissionExpansion', () => {- const installed = (approvalState: 'approved' | 'legacy-unapproved' | 'invalid') =>- ({ approval: { state: approvalState } }) as InstalledGhost;-- it.each(['legacy-unapproved', 'invalid'] as const)(- 'allows the full reapproval of a no-permission %s install',- (approvalState) => {- expect(marketUpdateAllowsPermissionExpansion(installed(approvalState), 0)).toBe(true);- },- );-- it('only allows approved installs when the reviewed diff adds permissions', () => {- expect(marketUpdateAllowsPermissionExpansion(installed('approved'), 0)).toBe(false);- expect(marketUpdateAllowsPermissionExpansion(installed('approved'), 1)).toBe(true);- });-});-describe('shouldOpenInstalledDetailAfterMarketSuccess', () => {it('opens the installed detail after a first-time market install', () => {expect(shouldOpenInstalledDetailAfterMarketSuccess(false)).toBe(true);diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCreatePrompt.test.ts b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCreatePrompt.test.tsindex cfb6fbcc39..2e2c9cb89e 100644--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCreatePrompt.test.ts+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCreatePrompt.test.ts@@ -18,16 +18,16 @@ const zhCommon = JSON.parse(};describe('Ghost Plugin creation prompt', () => {- it('reads the forge guide before designing, packing, and installing', () => {+ it('reads the forge guide before designing and keeps packing separate from installation', () => {const prompt = zhCommon.settings.ghosts.page.createPrompt;expect(prompt).toContain('先从提问开始');expect(prompt.indexOf('ghost_forge_guide')).toBeGreaterThanOrEqual(0);expect(prompt.indexOf('ghost_forge_guide')).toBeLessThan(prompt.indexOf('ghost_forge_pack'));- // 用真实章号指向卡槽总览:agent 可能照抄文案字样调 ghost_forge_guide 的- // section 取章,而章节匹配只认章号或标题子串,"卡槽总览"不是任何标题的子串。- expect(prompt).toContain('第 2 章卡槽总览');- expect(prompt).toContain('打包并安装插件');+ expect(prompt).toContain('能力总览');+ expect(prompt).toContain('生成 .cindy 产物');+ expect(prompt).toContain('不要声称已经安装');+ expect(prompt).not.toContain('打包并安装插件');});it('asks with option cards and surfaces hidden design choices (guide §0)', () => {@@ -52,8 +52,8 @@ describe('Ghost Plugin creation prompt', () => {expect(prompt).toContain('未读角标');expect(prompt).toContain('随包 Node 进程');expect(prompt).toContain('媒体能力');- // 必读章节含 §2 卡槽总览:18 个槽的全局视野是"按需读相关章节"的前提。- expect(prompt).toContain('卡槽总览');- expect(prompt).toContain('第 2 章');+ // 必读内容保持能力全局视野,但不再把能力模型表达成 slot。+ expect(prompt).toContain('能力总览');+ expect(prompt).not.toContain('卡槽总览');});});diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsxindex 615dc79982..de3d726f62 100644--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx@@ -256,7 +256,6 @@ describe('Ghost plugin detail sections', () => {version: detail.version,kind: 'chip',entry: 'main.js',- slots: [],settingsHtml: 'settings.html',},dir: detail.installDir ?? '/tmp/plugin',@@ -477,8 +476,8 @@ describe('Ghost plugin detail sections', () => {).disabled,).toBe(true);- // 启用开关(改版为带 aria-pressed 的按钮,非原生 switch)缺批准时禁用,点了不触发 onToggle。- const toggle = screen.getByRole('button', {+ // 启用区域是单个 switch 按钮;点文字或轨道都由同一交互处理。+ const toggle = screen.getByRole('switch', {name: 'settings.ghosts.enableAria',}) as HTMLButtonElement;expect(toggle.disabled).toBe(true);diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/MarketPluginDetailView.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/MarketPluginDetailView.test.tsxindex 591ae914d8..a08921f45d 100644--- a/apps/desktop/src/renderer/features/plugin/__tests__/MarketPluginDetailView.test.tsx+++ b/apps/desktop/src/renderer/features/plugin/__tests__/MarketPluginDetailView.test.tsx@@ -23,7 +23,7 @@ const manifest: GhostManifest = {version: '1.3.11',kind: 'chip',entry: 'main.js',- slots: ['notify'],+ notify: true,};const detail: PluginMarketDetail = {diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/PluginMarketPermissionReviewHost.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/PluginMarketPermissionReviewHost.test.tsxdeleted file mode 100644index 71eb5c3483..0000000000--- a/apps/desktop/src/renderer/features/plugin/__tests__/PluginMarketPermissionReviewHost.test.tsx+++ /dev/null@@ -1,214 +0,0 @@-// @vitest-environment jsdom--import { act, cleanup, render, screen, waitFor } from '@testing-library/react';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--import { ConfirmDialogProvider } from '@/components/ui/confirm-dialog-provider';-import {- __testing as dataOwnerGenerationTesting,- setDataOwnerGeneration,-} from '@/contexts/dataOwnerGeneration';-import type { PluginMarketPackageReviewRequest } from '../../../../shared/pluginMarket';-import { PluginMarketPermissionReviewHost } from '../PluginMarketPermissionReviewHost';--vi.mock('react-i18next', () => ({- useTranslation: () => ({- t: (key: string, args?: Record<string, unknown>) =>- key === 'settings.ghosts.installConfirm.manualCount'- ? `${key}:${String(args?.count)}`- : key,- }),-}));--describe('PluginMarketPermissionReviewHost', () => {- let reviewListener: ((review: PluginMarketPackageReviewRequest) => void) | undefined;- let authListener: ((state: AuthStateChangePayload) => void) | undefined;- const resolveReview = vi.fn(async () => ({ handled: true }));-- beforeEach(() => {- dataOwnerGenerationTesting.reset();- setDataOwnerGeneration('owner-a', 1);- resolveReview.mockClear();- (window as unknown as { electronAPI: Partial<Window['electronAPI']> }).electronAPI = {- onAuthStateChange: (listener) => {- authListener = listener;- return () => {- authListener = undefined;- };- },- pluginMarket: {- onPackagePermissionReview: (- listener: (review: PluginMarketPackageReviewRequest) => void,- ) => {- reviewListener = listener;- return () => {- reviewListener = undefined;- };- },- resolvePackagePermissionReview: resolveReview,- } as unknown as Window['electronAPI']['pluginMarket'],- };- });-- afterEach(() => {- cleanup();- dataOwnerGenerationTesting.reset();- delete (window as unknown as { electronAPI?: unknown }).electronAPI;- reviewListener = undefined;- authListener = undefined;- });-- it('closes a delivered private review and cancels it when the data owner changes', async () => {- render(- <ConfirmDialogProvider>- <PluginMarketPermissionReviewHost />- </ConfirmDialogProvider>,- );-- act(() => {- reviewListener?.({- requestId: 'review-a',- ownerStamp: { dataOwnerId: 'owner-a', ownerGeneration: 1 },- builtinOauthClientChanged: false,- manifest: {- schemaVersion: 2,- id: 'private-plugin',- name: 'Private Plugin',- version: '1.0.0',- kind: 'chip',- entry: 'main.js',- slots: ['tool'],- },- permissionDiff: null,- isUpdate: false,- sourceType: 'server',- });- });- await screen.findByText('settings.ghosts.market.installConfirmTitle');-- act(() => {- setDataOwnerGeneration('owner-b', 2);- authListener?.({- user: null,- mode: 'signed-out',- dataOwnerId: 'owner-b',- ownerGeneration: 2,- canEnterApp: false,- isAuthenticated: false,- isCanary: false,- deviceId: 'device',- hasAccountDeletionReceipt: false,- accountDeletionRestored: false,- });- });-- await waitFor(() => {- expect(screen.queryByText('settings.ghosts.market.installConfirmTitle')).toBeNull();- expect(resolveReview).toHaveBeenCalledWith('review-a', false);- });- });-- it('never shows a review whose Main delivery owner is already stale', async () => {- render(- <ConfirmDialogProvider>- <PluginMarketPermissionReviewHost />- </ConfirmDialogProvider>,- );- setDataOwnerGeneration('owner-b', 2);-- act(() => {- reviewListener?.({- requestId: 'stale-review',- ownerStamp: { dataOwnerId: 'owner-a', ownerGeneration: 1 },- builtinOauthClientChanged: false,- manifest: {- schemaVersion: 2,- id: 'private-plugin',- name: 'Private Plugin',- version: '1.0.0',- kind: 'chip',- entry: 'main.js',- slots: ['tool'],- },- permissionDiff: null,- isUpdate: false,- sourceType: 'server',- });- });-- await waitFor(() => {- expect(resolveReview).toHaveBeenCalledWith('stale-review', false);- });- expect(screen.queryByText('settings.ghosts.market.installConfirmTitle')).toBeNull();- });-- it('shows the real package manual count for an update without treating it as a permission item', async () => {- render(- <ConfirmDialogProvider>- <PluginMarketPermissionReviewHost />- </ConfirmDialogProvider>,- );-- act(() => {- reviewListener?.({- requestId: 'manual-update',- ownerStamp: { dataOwnerId: 'owner-a', ownerGeneration: 1 },- manifest: {- schemaVersion: 2,- id: 'manual-plugin',- name: 'Manual Plugin',- version: '2.0.0',- kind: 'chip',- entry: 'main.js',- slots: ['tool'],- manual: {- items: [- { dir: 'manual/ops', name: 'ops', description: 'Operations' },- { dir: 'manual/faq', name: 'faq', description: 'FAQ' },- ],- },- },- permissionDiff: { added: [], removed: [], unchanged: [], builtinOauthClientChanged: false },- isUpdate: true,- sourceType: 'server',- builtinOauthClientChanged: false,- });- });-- expect(await screen.findByText('settings.ghosts.installConfirm.manualCount:2')).toBeTruthy();- expect(screen.getByText('settings.ghosts.updateConfirm.title')).toBeTruthy();- });-- it('shows the OAuth identity warning on a first-install full permission card', async () => {- render(- <ConfirmDialogProvider>- <PluginMarketPermissionReviewHost />- </ConfirmDialogProvider>,- );-- act(() => {- reviewListener?.({- requestId: 'first-install-oauth',- ownerStamp: { dataOwnerId: 'owner-a', ownerGeneration: 1 },- builtinOauthClientChanged: true,- manifest: {- schemaVersion: 2,- id: 'oauth-plugin',- name: 'OAuth Plugin',- version: '1.0.0',- kind: 'chip',- entry: 'main.js',- slots: ['network'],- },- permissionDiff: null,- isUpdate: false,- sourceType: 'server',- });- });-- expect(- await screen.findByText('settings.ghosts.updateConfirm.oauthClientChanged'),- ).toBeTruthy();- expect(screen.getByText('settings.ghosts.market.installConfirmTitle')).toBeTruthy();- });-});diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/marketInstallConfirmation.test.ts b/apps/desktop/src/renderer/features/plugin/__tests__/marketInstallConfirmation.test.tsindex e8ccce858c..b524fd5ecd 100644--- a/apps/desktop/src/renderer/features/plugin/__tests__/marketInstallConfirmation.test.ts+++ b/apps/desktop/src/renderer/features/plugin/__tests__/marketInstallConfirmation.test.ts@@ -3,26 +3,19 @@ import { resolve } from 'node:path';import { describe, expect, it } from 'vitest';-/**- * Clicking install/update must open the catalog permission card immediately.- * The post-download Host card is only for permissions the preview missed.- */-describe('market install confirmation', () => {+describe('market install flow', () => {const pageSource = readFileSync(resolve(__dirname, '../GhostPluginPage.tsx'),'utf8',).replace(/\r\n/g, '\n');- it('shows an immediate catalog permission card before download', () => {- expect(pageSource).toContain('<GhostUpdateReview');- expect(pageSource).toContain('manualCount={next.manifest.manual?.items.length ?? 0}');+ it('starts a compatible install without a capability confirmation card', () => {+ expect(pageSource).not.toContain('<GhostUpdateReview');+ expect(pageSource).not.toContain('<GhostManualSummary');+ expect(pageSource).not.toContain('<GhostPermissionList');+ expect(pageSource).toContain('installMarketPackage');expect(pageSource).toContain(- 'manualCount={marketDetail.manifest.manual?.items.length ?? 0}',- );- expect(pageSource).toContain('<GhostManualSummary');- expect(pageSource).toContain('<GhostPermissionList');- expect(pageSource).toContain(- '下载真实包;权限卡已在页面确认,Host 只在真实包超出已审清单时再弹',+ '目录详情用于发现与能力展示;点击更新后由 Main 下载并校验真实包后直接落位',);});diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/updateAllController.test.ts b/apps/desktop/src/renderer/features/plugin/__tests__/updateAllController.test.tsindex c006edd8ed..f7117dcc99 100644--- a/apps/desktop/src/renderer/features/plugin/__tests__/updateAllController.test.ts+++ b/apps/desktop/src/renderer/features/plugin/__tests__/updateAllController.test.ts@@ -1,13 +1,7 @@/**- * Regression coverage for the module-level update-all batch controller.- *- * Two feature sets are exercised together:- * - needs-confirm approval binding: rows whose approval is missing/invalid or- * whose target expands permissions stop for explicit review (approve/skip),- * including receipt/baseline drift recovery and batch state surviving unmount.- * - source isolation (#2043): the batch only updates `update-available`- * packages, never replaces a source, and auto-installs carry- * `allowSourceReplacement: false`.+ * Regression coverage for the module-level update-all controller.+ * Every row delegates validation and atomic placement to Main; this module owns+ * progress only.* [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md* @vitest-environment jsdom*/@@ -39,14 +33,10 @@ import {setDataOwnerGeneration,} from '@/contexts/dataOwnerGeneration';import { toast } from '@/lib/toast';-import {- type GhostInstallApproval,- type GhostManifest,-} from '../../../../shared/ghost';+import type { GhostInstallApproval, GhostManifest } from '../../../../shared/ghost';import type { PluginMarketDetail, PluginMarketItem } from '../../../../shared/pluginMarket';import {__resetUpdateAllBatchForTest,- approveUpdateExpansion,getUpdateAllBatchState,reconcileUpdateAllBatch,setUpdateAllBatchHooks,@@ -58,7 +48,6 @@ function manifest(overrides: Partial<GhostManifest> = {}): GhostManifest {id: 'ghost-a',name: 'Ghost A',version: '1.1.0',- slots: [],...overrides,} as GhostManifest;}@@ -99,25 +88,6 @@ const detailMock = vi.fn<(pluginId: string) => Promise<PluginMarketDetail>>();const installMock = vi.fn();const DEFAULT_APPROVAL_TOKEN = 'approved:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';-function stubDetail(overrides: {- manifest: GhostManifest;- sourceType: PluginMarketDetail['sourceType'];-}): void {- detailMock.mockResolvedValue({- ...marketItem({ sourceType: overrides.sourceType }),- manifest: overrides.manifest,- readme: null,- } as unknown as PluginMarketDetail);-}--async function waitForSettledBatch(): Promise<void> {- await vi.waitFor(() => {- const state = getUpdateAllBatchState();- expect(state.running).toBe(false);- expect(state.rows?.some((row) => row.status === 'pending')).toBe(false);- });-}-async function waitForFinishedBatch(): Promise<void> {await vi.waitFor(() => {const current = getUpdateAllBatchState();@@ -139,23 +109,13 @@ beforeEach(() => {installMock.mockResolvedValue({ ghost: { manifest: manifest() } });vi.mocked(toast.success).mockClear();(window as unknown as { electronAPI: unknown }).electronAPI = {+ appVersion: '1.0.0',pluginMarket: { detail: detailMock, install: installMock },};});describe('updateAllController', () => {- it('skips rows whose plugin was uninstalled mid-batch instead of reinstalling', async () => {- installedGhosts = [];- stubDetail({ manifest: manifest({}), sourceType: 'server' });-- startUpdateAllBatch([marketItem({})]);- await waitForSettledBatch();-- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('skipped');- expect(installMock).not.toHaveBeenCalled();- });-- it('serially delegates every row with only its current release precondition', async () => {+ it('serially delegates every row with its release and installed receipt preconditions', async () => {installedGhosts.push({ manifest: manifest({ id: 'ghost-b', version: '2.0.0' }) });detailMock.mockImplementation(async (pluginId) =>pluginId === 'plugin-a'@@ -179,14 +139,13 @@ describe('updateAllController', () => {]);await waitForFinishedBatch();- // 自动安装路径同时绑定批准基线、回传审阅清单并携带来源隔离标志。expect(installMock.mock.calls).toEqual([['plugin-a',{expectedReleaseId: 'release-2',+ expectedManifest: manifest(),expectedInstalledApproval: DEFAULT_APPROVAL_TOKEN,- expectedManifest: expect.anything(),allowSourceReplacement: false,},],@@ -194,181 +153,13 @@ describe('updateAllController', () => {'plugin-b',{expectedReleaseId: 'release-b2',+ expectedManifest: manifest({ id: 'ghost-b', version: '2.1.0' }),expectedInstalledApproval: DEFAULT_APPROVAL_TOKEN,- expectedManifest: expect.anything(),allowSourceReplacement: false,},],]);- expect(getUpdateAllBatchState().rows?.map((row) => row.status)).toEqual([- 'done',- 'done',- ]);- });-- it('binds an automatic update to the installed receipt approval revision', async () => {- const revision = '11111111-1111-4111-8111-111111111111';- installedGhosts = [- {- manifest: manifest({ version: '1.0.0' }),- approval: { state: 'approved', revision },- },- ];- const targetManifest = manifest({});- stubDetail({ manifest: targetManifest, sourceType: 'server' });-- startUpdateAllBatch([marketItem({})]);- await waitForSettledBatch();-- expect(installMock).toHaveBeenCalledWith('plugin-a', {- expectedReleaseId: 'release-2',- expectedInstalledApproval: `approved:${revision}`,- expectedManifest: targetManifest,- allowSourceReplacement: false,- });- });-- it.each(['legacy-unapproved', 'invalid'] as const)(- 'requires a full permission review for a %s install even when its live manifest matches',- async (approvalState) => {- const samePermissions = manifest({- version: '1.0.0',- network: { hosts: ['api.example.com'] },- });- installedGhosts = [{ manifest: samePermissions, approval: { state: approvalState } }];- const targetManifest = manifest({ network: { hosts: ['api.example.com'] } });- stubDetail({- manifest: targetManifest,- sourceType: 'server',- });-- startUpdateAllBatch([marketItem({})]);- await waitForSettledBatch();-- const held = getUpdateAllBatchState().rows?.[0];- expect(held).toMatchObject({- status: 'needs-confirm',- reviewedApproval: approvalState,- });- expect(held?.permissionDiff?.added.some((item) => item.kind === 'network')).toBe(true);- expect(held?.permissionDiff?.unchanged).toEqual([]);- expect(installMock).not.toHaveBeenCalled();-- await approveUpdateExpansion('plugin-a');- expect(installMock).toHaveBeenCalledWith('plugin-a', {- expectedReleaseId: 'release-2',- expectedInstalledApproval: approvalState,- expectedManifest: targetManifest,- allowPermissionExpansion: true,- allowSourceReplacement: false,- reviewedBaseline: expect.any(String),- });- },- );-- it('requires an explicit confirmation for an unapproved plugin with no optional capabilities', async () => {- installedGhosts = [- {- manifest: manifest({ version: '1.0.0' }),- approval: { state: 'legacy-unapproved' },- },- ];- stubDetail({ manifest: manifest({}), sourceType: 'server' });-- startUpdateAllBatch([marketItem({})]);- await waitForSettledBatch();-- expect(getUpdateAllBatchState().rows?.[0]).toMatchObject({- status: 'needs-confirm',- reviewedApproval: 'legacy-unapproved',- permissionDiff: { removed: [], unchanged: [] },- });- expect(getUpdateAllBatchState().rows?.[0]?.permissionDiff?.added).toEqual([- expect.objectContaining({ kind: 'code' }),- ]);- expect(installMock).not.toHaveBeenCalled();- });-- it('invalidates an approved review when its receipt becomes invalid before confirmation', async () => {- const revision = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';- installedGhosts = [- {- manifest: manifest({ version: '1.0.0' }),- approval: { state: 'approved', revision },- },- ];- const targetManifest = manifest({ network: { hosts: ['api.example.com'] } });- stubDetail({- manifest: targetManifest,- sourceType: 'server',- });- startUpdateAllBatch([marketItem({})]);- await waitForSettledBatch();-- installedGhosts = [- {- manifest: manifest({ version: '1.0.0' }),- approval: { state: 'invalid' },- },- ];- await approveUpdateExpansion('plugin-a');-- const rereview = getUpdateAllBatchState().rows?.[0];- expect(rereview).toMatchObject({- status: 'needs-confirm',- staleReview: false,- reviewedApproval: 'invalid',- });- expect(rereview?.permissionDiff?.added.some((item) => item.kind === 'network')).toBe(true);- expect(installMock).not.toHaveBeenCalled();-- await approveUpdateExpansion('plugin-a');- expect(installMock).toHaveBeenCalledWith('plugin-a', {- expectedReleaseId: 'release-2',- expectedInstalledApproval: 'invalid',- expectedManifest: targetManifest,- allowPermissionExpansion: true,- allowSourceReplacement: false,- reviewedBaseline: expect.any(String),- });- });-- it('holds server preview permission expansion for approval', async () => {- const targetManifest = manifest({ network: { hosts: ['api.example.com'] } });- stubDetail({ manifest: targetManifest, sourceType: 'server' });-- startUpdateAllBatch([marketItem({})]);- await waitForSettledBatch();- expect(getUpdateAllBatchState().rows?.[0]).toMatchObject({- status: 'needs-confirm',- releaseId: 'release-2',- expectedManifest: targetManifest,- });-- await approveUpdateExpansion('plugin-a');- expect(installMock).toHaveBeenLastCalledWith(- 'plugin-a',- expect.objectContaining({ expectedManifest: targetManifest }),- );- });-- it('marks a transaction cancelled in Main as skipped', async () => {- stubDetail({ manifest: manifest({}), sourceType: 'server' });- installMock.mockResolvedValueOnce({ cancelled: true } as never);-- startUpdateAllBatch([marketItem({})]);- await waitForSettledBatch();-- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('skipped');- });-- it('marks a Main-side permission cancellation as skipped', async () => {- installMock.mockResolvedValueOnce({ cancelled: true });-- startUpdateAllBatch([marketItem()]);- await waitForFinishedBatch();-- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('skipped');+ expect(getUpdateAllBatchState().rows?.map((row) => row.status)).toEqual(['done', 'done']);});it('skips a plugin removed before its row starts', async () => {@@ -391,232 +182,6 @@ describe('updateAllController', () => {expect(installMock).not.toHaveBeenCalled();});- it('passes the reviewed manifest back when approving a non-server expansion', async () => {- const nextManifest = manifest({ network: { hosts: ['api.example.com'] } });- stubDetail({ manifest: nextManifest, sourceType: 'git-market' });-- startUpdateAllBatch([marketItem({ sourceType: 'git-market' })]);- await waitForSettledBatch();-- const held = getUpdateAllBatchState().rows?.[0];- expect(held?.status).toBe('needs-confirm');- expect(held?.expectedManifest).toBe(nextManifest);-- await approveUpdateExpansion('plugin-a');- expect(installMock).toHaveBeenCalledWith('plugin-a', {- expectedReleaseId: 'release-2',- expectedInstalledApproval: DEFAULT_APPROVAL_TOKEN,- expectedManifest: nextManifest,- allowPermissionExpansion: true,- allowSourceReplacement: false,- reviewedBaseline: expect.any(String),- });- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');- });-- it('passes expectedManifest when approving a server-source expansion', async () => {- const revision = '22222222-2222-4222-8222-222222222222';- installedGhosts = [- {- manifest: manifest({ version: '1.0.0' }),- approval: { state: 'approved', revision },- },- ];- const targetManifest = manifest({ network: { hosts: ['api.example.com'] } });- stubDetail({- manifest: targetManifest,- sourceType: 'server',- });-- startUpdateAllBatch([marketItem({})]);- await waitForSettledBatch();- await approveUpdateExpansion('plugin-a');-- expect(installMock).toHaveBeenCalledWith('plugin-a', {- expectedReleaseId: 'release-2',- expectedInstalledApproval: `approved:${revision}`,- expectedManifest: targetManifest,- allowPermissionExpansion: true,- allowSourceReplacement: false,- reviewedBaseline: expect.any(String),- });- });-- it('turns approval into a skip when the plugin was uninstalled while waiting', async () => {- stubDetail({- manifest: manifest({ network: { hosts: ['api.example.com'] } }),- sourceType: 'server',- });-- startUpdateAllBatch([marketItem({})]);- await waitForSettledBatch();-- installedGhosts = [];- await approveUpdateExpansion('plugin-a');-- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('skipped');- expect(installMock).not.toHaveBeenCalled();- });-- it('recomputes the diff when an external update replaced the permission baseline', async () => {- stubDetail({- manifest: manifest({ network: { hosts: ['api.example.com'] } }),- sourceType: 'server',- });- startUpdateAllBatch([marketItem({})]);- await waitForSettledBatch();- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('needs-confirm');-- // 「从文件更新」把插件装成了第三个版本,且它已自带原先要审的 network 权限:- // 审阅过的 diff 与 allowPermissionExpansion 都不再对应现实。- installedGhosts = [- {- manifest: manifest({ version: '1.0.5', network: { hosts: ['api.example.com'] } }),- approval: {- state: 'approved',- revision: '33333333-3333-4333-8333-333333333333',- },- },- ];- reconcileUpdateAllBatch();- const held = getUpdateAllBatchState().rows?.[0];- expect(held).toMatchObject({ status: 'needs-confirm', staleReview: true, fromVersion: '1.0.5' });- expect(held?.permissionDiff).toBeUndefined();-- await approveUpdateExpansion('plugin-a');- // 相对当前已装 manifest 已无扩权 → 按普通更新安装,不带 allowPermissionExpansion。- expect(installMock).toHaveBeenCalledWith('plugin-a', {- expectedReleaseId: 'release-2',- expectedInstalledApproval: 'approved:33333333-3333-4333-8333-333333333333',- expectedManifest: expect.any(Object),- allowSourceReplacement: false,- });- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');- });-- it('keeps the row held for re-review when the recomputed diff still expands permissions', async () => {- stubDetail({- manifest: manifest({ network: { hosts: ['api.example.com'] } }),- sourceType: 'server',- });- startUpdateAllBatch([marketItem({})]);- await waitForSettledBatch();-- // 外部装成第三个版本且权限面变了(多了 fs),但仍不含目标版本要新增的- // network —— 基线失效触发重算,重算结果依旧是扩权。- installedGhosts = [{ manifest: manifest({ version: '1.0.5', slots: ['fs'] }) }];- reconcileUpdateAllBatch();- await approveUpdateExpansion('plugin-a');-- const row = getUpdateAllBatchState().rows?.[0];- expect(row).toMatchObject({ status: 'needs-confirm', staleReview: false, fromVersion: '1.0.5' });- expect(row?.permissionDiff?.added.length).toBeGreaterThan(0);- // 重算后仍是扩权:停在当前批次等待用户重新确认,不提前调用安装。- expect(installMock).not.toHaveBeenCalled();- });-- it('recomputes on baseline drift even before reconcile flagged the row', async () => {- stubDetail({- manifest: manifest({ network: { hosts: ['api.example.com'] } }),- sourceType: 'server',- });- startUpdateAllBatch([marketItem({})]);- await waitForSettledBatch();-- // 外部更新已落地但 reconcile 还没跑(竞态窗口):版本比较必须兜住,- // 不得拿旧 diff 换来的 allowPermissionExpansion 安装。- installedGhosts = [- { manifest: manifest({ version: '1.0.5', network: { hosts: ['api.example.com'] } }) },- ];- await approveUpdateExpansion('plugin-a');-- expect(installMock).toHaveBeenCalledWith('plugin-a', {- expectedReleaseId: 'release-2',- expectedInstalledApproval: DEFAULT_APPROVAL_TOKEN,- expectedManifest: expect.any(Object),- allowSourceReplacement: false,- });- });-- it('invalidates the review when a same-version manifest swap widened permissions', async () => {- stubDetail({- manifest: manifest({ network: { hosts: ['api.example.com'] } }),- sourceType: 'server',- });- startUpdateAllBatch([marketItem({})]);- await waitForSettledBatch();- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('needs-confirm');-- // 「从文件更新」换入**同版本**但权限更宽的 manifest:版本号完全看不出来,- // 沿用旧审阅会把 fs 这条从未审阅的权限一并放行。- installedGhosts = [{ manifest: manifest({ version: '1.0.0', slots: ['fs'] }) }];- reconcileUpdateAllBatch();- const held = getUpdateAllBatchState().rows?.[0];- expect(held).toMatchObject({ status: 'needs-confirm', staleReview: true });- expect(held?.permissionDiff).toBeUndefined();-- await approveUpdateExpansion('plugin-a');- // 相对新基线仍是扩权 → 回到预览权限确认,绝不沿用旧批准或提前安装。- expect(installMock).not.toHaveBeenCalled();- expect(getUpdateAllBatchState().rows?.[0]).toMatchObject({- status: 'needs-confirm',- staleReview: false,- });- });-- it('keeps the review valid when only the version moved but permissions are identical', async () => {- stubDetail({- manifest: manifest({ network: { hosts: ['api.example.com'] } }),- sourceType: 'server',- });- startUpdateAllBatch([marketItem({})]);- await waitForSettledBatch();-- // 权限面完全没变,只是版本号动了:审阅结论仍然成立,不该逼用户重审。- installedGhosts = [{ manifest: manifest({ version: '1.0.4' }) }];- reconcileUpdateAllBatch();- const kept = getUpdateAllBatchState().rows?.[0];- expect(kept).toMatchObject({ status: 'needs-confirm', fromVersion: '1.0.4' });- expect(kept?.staleReview).toBeFalsy();- expect(kept?.permissionDiff?.added.length).toBeGreaterThan(0);-- await approveUpdateExpansion('plugin-a');- expect(installMock).toHaveBeenCalledWith('plugin-a', {- expectedReleaseId: 'release-2',- expectedInstalledApproval: DEFAULT_APPROVAL_TOKEN,- expectedManifest: expect.any(Object),- allowPermissionExpansion: true,- allowSourceReplacement: false,- reviewedBaseline: expect.any(String),- });- });-- it('voids the batch when the data owner changes during the detail round-trip', async () => {- let releaseDetail: (() => void) | undefined;- detailMock.mockImplementation(- () =>- new Promise((resolve) => {- releaseDetail = () => {- setDataOwnerGeneration('owner-b');- resolve({- ...marketItem({}),- manifest: manifest({}),- readme: null,- } as unknown as PluginMarketDetail);- };- }),- );-- startUpdateAllBatch([marketItem({})]);- await vi.waitFor(() => expect(releaseDetail).toBeDefined());- releaseDetail?.();- await vi.waitFor(() => expect(getUpdateAllBatchState().running).toBe(false));-- // 旧账号发起的批次在身份切换后整体作废,不得写入新账号数据。- expect(getUpdateAllBatchState().rows).toBeNull();- expect(installMock).not.toHaveBeenCalled();- });-it('skips a queued update that changed to a source conflict before its turn', async () => {installedGhosts.push({ manifest: manifest({ id: 'ghost-b', version: '2.0.0' }) });let resolveFirstInstall: (() => void) | undefined;@@ -636,10 +201,7 @@ describe('updateAllController', () => {}),);- startUpdateAllBatch([- marketItem(),- marketItem({ pluginId: 'plugin-b', ghostId: 'ghost-b' }),- ]);+ startUpdateAllBatch([marketItem(), marketItem({ pluginId: 'plugin-b', ghostId: 'ghost-b' })]);await vi.waitFor(() => expect(resolveFirstInstall).toBeDefined());resolveFirstInstall?.();await waitForFinishedBatch();@@ -660,6 +222,21 @@ describe('updateAllController', () => {});});+ it('does not re-check the server-selected release against the client version', async () => {+ detailMock.mockResolvedValueOnce(+ detail({ manifest: manifest({ minCindyVersion: '99.0.0' }) }),+ );++ startUpdateAllBatch([marketItem()]);+ await waitForFinishedBatch();++ expect(installMock).toHaveBeenCalledWith(+ 'plugin-a',+ expect.objectContaining({ expectedReleaseId: 'release-2' }),+ );+ expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');+ });+it('voids the whole batch when its data owner changes during detail loading', async () => {let resolveDetail: ((value: PluginMarketDetail) => void) | undefined;detailMock.mockImplementationOnce(@@ -692,12 +269,8 @@ describe('updateAllController', () => {await vi.waitFor(() => expect(resolveRefresh).toBeDefined());expect(getUpdateAllBatchState().running).toBe(true);- startUpdateAllBatch([- marketItem({ pluginId: 'plugin-b', ghostId: 'ghost-b' }),- ]);- expect(getUpdateAllBatchState().rows?.map((row) => row.pluginId)).toEqual([- 'plugin-a',- ]);+ startUpdateAllBatch([marketItem({ pluginId: 'plugin-b', ghostId: 'ghost-b' })]);+ expect(getUpdateAllBatchState().rows?.map((row) => row.pluginId)).toEqual(['plugin-a']);resolveRefresh?.();await waitForFinishedBatch();@@ -714,15 +287,10 @@ describe('updateAllController', () => {}),);detailMock.mockImplementation(async (pluginId) =>- pluginId === 'plugin-a'- ? detail()- : detail({ pluginId: 'plugin-b', ghostId: 'ghost-b' }),+ pluginId === 'plugin-a' ? detail() : detail({ pluginId: 'plugin-b', ghostId: 'ghost-b' }),);- startUpdateAllBatch([- marketItem(),- marketItem({ pluginId: 'plugin-b', ghostId: 'ghost-b' }),- ]);+ startUpdateAllBatch([marketItem(), marketItem({ pluginId: 'plugin-b', ghostId: 'ghost-b' })]);await vi.waitFor(() => expect(resolveInstall).toBeDefined());installedGhosts = [{ manifest: manifest({ version: '1.0.0' }) }];reconcileUpdateAllBatch();@@ -732,669 +300,4 @@ describe('updateAllController', () => {await waitForFinishedBatch();expect(installMock).toHaveBeenCalledTimes(1);});-- it('reconcile settles held rows updated externally and voids stale-owner batches', async () => {- stubDetail({- manifest: manifest({ network: { hosts: ['api.example.com'] } }),- sourceType: 'server',- });- startUpdateAllBatch([marketItem({})]);- await waitForSettledBatch();- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('needs-confirm');-- // 目标 release 已落账(市场快照报 installed)→ 待确认行收束为完成。- installedGhosts = [{ manifest: manifest({ version: '1.1.0' }) }];- reconcileUpdateAllBatch([marketItem({ installState: 'installed' })]);- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');- expect(installMock).not.toHaveBeenCalled();-- // 账号切换后对账直接作废整批。- startUpdateAllBatch([]);- setDataOwnerGeneration('owner-b');- reconcileUpdateAllBatch();- expect(getUpdateAllBatchState().rows).toBeNull();- });-- it('does not settle as done when a same-version foreign release was installed', async () => {- stubDetail({- manifest: manifest({ network: { hosts: ['api.example.com'] } }),- sourceType: 'server',- });- startUpdateAllBatch([marketItem({})]);- await waitForSettledBatch();-- // 「从文件更新」装了同版本但**不是目标 release** 的包:版本号看着到位,- // 但 main 侧 record.releaseId 对不上,市场仍报 update-available。- installedGhosts = [{ manifest: manifest({ version: '1.1.0' }) }];- reconcileUpdateAllBatch([marketItem({ installState: 'update-available' })]);- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('needs-confirm');-- await approveUpdateExpansion('plugin-a');- // 目标 release 仍未落账 → 必须真正安装,不得凭版本号收成完成。- expect(installMock).toHaveBeenCalledWith('plugin-a', {- expectedReleaseId: 'release-2',- expectedInstalledApproval: DEFAULT_APPROVAL_TOKEN,- expectedManifest: expect.any(Object),- allowPermissionExpansion: true,- allowSourceReplacement: false,- reviewedBaseline: expect.any(String),- });- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');- });-- it('re-reads the installed manifest after detail() instead of trusting the pre-await snapshot', async () => {- // 审阅基线:已装带 network,目标包在此之上多出 fs → 用户审的是 fs 这一条。- installedGhosts = [- { manifest: manifest({ version: '1.0.0', network: { hosts: ['api.example.com'] } }) },- ];- stubDetail({- manifest: manifest({ network: { hosts: ['api.example.com'] }, slots: ['fs'] }),- sourceType: 'server',- });- startUpdateAllBatch([marketItem({})]);- await waitForSettledBatch();- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('needs-confirm');-- // detail() 往返期间「从文件更新」把已装换成**不带 network** 的包:此刻目标包- // 相对当前已装多出 network + fs,而 network 用户从没审过。批准必须以- // detail 之后的事实判断,拿 await 前捕获的快照会直接放行。- detailMock.mockImplementation(async () => {- installedGhosts = [{ manifest: manifest({ version: '1.0.0' }) }];- return {- ...marketItem({}),- manifest: manifest({ network: { hosts: ['api.example.com'] }, slots: ['fs'] }),- readme: null,- } as unknown as PluginMarketDetail;- });-- await approveUpdateExpansion('plugin-a');- expect(installMock).not.toHaveBeenCalled();- const row = getUpdateAllBatchState().rows?.[0];- expect(row?.status).toBe('needs-confirm');- // 新差异按当前事实重算,把没审过的 network 也摆出来。- expect(row?.permissionDiff?.added.length).toBeGreaterThan(1);- });-- it('returns a Main-side baseline rejection to re-review instead of a terminal failure', async () => {- stubDetail({- manifest: manifest({ network: { hosts: ['api.example.com'] } }),- sourceType: 'server',- });- startUpdateAllBatch([marketItem({})]);- await waitForSettledBatch();-- // Main 在安装锁内用当前已装 manifest 复核后否决了这次批准。- installMock.mockRejectedValueOnce(- Object.assign(new Error('[PRECONDITION_FAILED] baseline changed'), {- message: 'Error invoking remote method: Error: [PRECONDITION_FAILED] baseline changed',- }),- );-- await approveUpdateExpansion('plugin-a');- const row = getUpdateAllBatchState().rows?.[0];- // 「事实已变,请重新审阅」而不是「更新失败」——终态失败会让用户失去入口。- // 手里的 detail 已被 Main 否决,不能拿它出确认内容:丢弃旧差异 + 标记过期,- // 下次批准重新取详情。- expect(row?.status).toBe('needs-confirm');- expect(row?.staleReview).toBe(true);- expect(row?.permissionDiff).toBeUndefined();- expect(row?.errorText).toBeUndefined();- });-- it('holds running through the post-approval refresh so no second batch can start', async () => {- stubDetail({- manifest: manifest({ network: { hosts: ['api.example.com'] } }),- sourceType: 'server',- });- startUpdateAllBatch([marketItem({})]);- await waitForSettledBatch();- expect(getUpdateAllBatchState().running).toBe(false);-- let releaseRefresh: (() => void) | undefined;- setUpdateAllBatchHooks({- refreshMarket: () =>- new Promise<void>((resolve) => {- releaseRefresh = resolve;- }),- });-- const approving = approveUpdateExpansion('plugin-a');- await vi.waitFor(() => expect(releaseRefresh).toBeDefined());- // 刷新还没回来:页面手里仍是旧的 update-available 快照,必须挡住第二批。- expect(getUpdateAllBatchState().running).toBe(true);- startUpdateAllBatch([marketItem({ pluginId: 'plugin-b', ghostId: 'ghost-b' })]);- expect(getUpdateAllBatchState().rows?.map((row) => row.pluginId)).toEqual(['plugin-a']);-- releaseRefresh?.();- await approving;- expect(getUpdateAllBatchState().running).toBe(false);- });-- it('serialises concurrent approvals and only settles after the last one', async () => {- const expanding = manifest({ network: { hosts: ['api.example.com'] } });- detailMock.mockImplementation(async (pluginId) =>- ({- ...marketItem({ pluginId, ghostId: pluginId === 'plugin-a' ? 'ghost-a' : 'ghost-b' }),- manifest: expanding,- readme: null,- }) as unknown as PluginMarketDetail,- );- installedGhosts = [- { manifest: manifest({ version: '1.0.0' }) },- { manifest: manifest({ id: 'ghost-b', version: '1.0.0' }) },- ];- startUpdateAllBatch([- marketItem({}),- marketItem({ pluginId: 'plugin-b', ghostId: 'ghost-b' }),- ]);- await waitForSettledBatch();- expect(- getUpdateAllBatchState().rows?.every((row) => row.status === 'needs-confirm'),- ).toBe(true);-- // 两次安装都卡住,用来观察是否并发。- const installGate: Array<() => void> = [];- let concurrentPeak = 0;- let active = 0;- installMock.mockImplementation(- () =>- new Promise((resolve) => {- active += 1;- concurrentPeak = Math.max(concurrentPeak, active);- installGate.push(() => {- active -= 1;- resolve({ ghost: { manifest: expanding } } as never);- });- }),- );- let refreshCalls = 0;- setUpdateAllBatchHooks({- refreshMarket: async () => {- refreshCalls += 1;- },- });-- // 用户连点两个「同意」。- const first = approveUpdateExpansion('plugin-a');- const second = approveUpdateExpansion('plugin-b');-- await vi.waitFor(() => expect(installGate.length).toBe(1));- // 串行:第二个必须排队,不能与第一个同时在装。- expect(concurrentPeak).toBe(1);- expect(getUpdateAllBatchState().running).toBe(true);-- installGate[0]?.();- await first;- // 第一个结束时还有在途批准 → 不许提前释放闸门、不许提前报完成。- expect(getUpdateAllBatchState().running).toBe(true);- expect(refreshCalls).toBe(0);-- await vi.waitFor(() => expect(installGate.length).toBe(2));- installGate[1]?.();- await second;-- // 最后一个结束才收尾:刷新一次、释放 running、报一次完成。- expect(concurrentPeak).toBe(1);- expect(getUpdateAllBatchState().running).toBe(false);- expect(refreshCalls).toBe(1);- expect(vi.mocked(toast.success)).toHaveBeenCalledTimes(1);- });-- it('skips a row whose target release was already installed by the single-item flow', async () => {- // 用户在批次启动前用卡片的单项更新装了同一个 release;本批次拿的是那之前的- // 市场快照,仍标 update-available。runner 取详情后必须发现已落账并跳过。- detailMock.mockResolvedValue({- ...marketItem({ installState: 'installed' }),- manifest: manifest({ version: '1.1.0' }),- readme: null,- } as unknown as PluginMarketDetail);-- startUpdateAllBatch([marketItem({})]);- await waitForSettledBatch();-- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');- expect(installMock).not.toHaveBeenCalled();- });-- it('holds a runner row for re-review instead of failing it on PRECONDITION_FAILED', async () => {- stubDetail({ manifest: manifest({}), sourceType: 'git-market' });- installMock.mockRejectedValueOnce(- Object.assign(new Error('precondition'), {- message: 'Error invoking remote method: Error: [PRECONDITION_FAILED] release changed',- }),- );-- startUpdateAllBatch([marketItem({ sourceType: 'git-market' })]);- await waitForSettledBatch();-- const row = getUpdateAllBatchState().rows?.[0];- // 自动安装路径遇到前置条件变化 → 可恢复的待重审,不是终态失败。- expect(row).toMatchObject({ status: 'needs-confirm', staleReview: true });- expect(row?.errorText).toBeUndefined();- expect(row?.permissionDiff).toBeUndefined();- });-- it('lets a held runner row be re-reviewed and approved through to completion', async () => {- stubDetail({ manifest: manifest({}), sourceType: 'git-market' });- installMock.mockRejectedValueOnce(- Object.assign(new Error('precondition'), {- message: 'Error invoking remote method: Error: [PRECONDITION_FAILED] release changed',- }),- );-- startUpdateAllBatch([marketItem({ sourceType: 'git-market' })]);- await waitForSettledBatch();-- const held = getUpdateAllBatchState().rows?.[0];- expect(held).toMatchObject({ status: 'needs-confirm', staleReview: true });- // 关键:待重审行必须带着目标 release,否则 approve 的入口守卫会直接返回,- // 用户点「重新审阅」毫无反应,该项在本批次里永远走不下去。- expect(held?.releaseId).toBe('release-2');-- // 点「重新审阅」→ 重取详情、按当前事实重算(已无扩权)→ 装上收尾。- await approveUpdateExpansion('plugin-a');-- expect(installMock).toHaveBeenLastCalledWith('plugin-a', {- expectedReleaseId: 'release-2',- expectedInstalledApproval: DEFAULT_APPROVAL_TOKEN,- expectedManifest: expect.anything(),- allowSourceReplacement: false,- });- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');- });-- it('fails instead of holding when there is no target release to re-review', async () => {- // detail 拿得到、但 install 前置条件失败且行上没有 releaseId 的极端情形:- // 用 detail 报 installed 之外的路径构造——这里直接验证 hold 的防御分支,- // 保证不会产出「点不动的 needs-confirm 死行」。- detailMock.mockResolvedValue({- ...marketItem({ releaseId: '' }),- manifest: manifest({}),- readme: null,- } as unknown as PluginMarketDetail);- installMock.mockRejectedValueOnce(- Object.assign(new Error('precondition'), {- message: 'Error invoking remote method: Error: [PRECONDITION_FAILED] gone',- }),- );-- startUpdateAllBatch([marketItem({ releaseId: '' })]);- await waitForSettledBatch();-- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('failed');- });-- it('still fails the row on non-precondition install errors', async () => {- stubDetail({ manifest: manifest({}), sourceType: 'server' });- installMock.mockRejectedValueOnce(new Error('network down'));-- startUpdateAllBatch([marketItem({})]);- await waitForSettledBatch();-- // 真失败仍然是失败:不能把所有错误都变成"再审一次"。- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('failed');- });-- it('re-reviews instead of failing when a custom source swaps the manifest under the plain update path', async () => {- // 自定义市场源:审阅基线含 network,目标包在此之上多出 fs。- installedGhosts = [- { manifest: manifest({ version: '1.0.0', network: { hosts: ['api.example.com'] } }) },- ];- stubDetail({- manifest: manifest({ network: { hosts: ['api.example.com'] }, slots: ['fs'] }),- sourceType: 'git-market',- });- startUpdateAllBatch([marketItem({ sourceType: 'git-market' })]);- await waitForSettledBatch();- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('needs-confirm');-- // 批准时外部把已装换成同样带 fs 的包 → 重算后已无扩权,走普通更新分支;- // 但市场源又以同版本改了 manifest,Main 因 expectedManifest 不匹配拒绝。- detailMock.mockImplementation(async () => {- installedGhosts = [- {- manifest: manifest({- version: '1.0.0',- network: { hosts: ['api.example.com'] },- slots: ['fs'],- }),- },- ];- return {- ...marketItem({ sourceType: 'git-market' }),- manifest: manifest({ network: { hosts: ['api.example.com'] }, slots: ['fs'] }),- readme: null,- } as unknown as PluginMarketDetail;- });- installMock.mockRejectedValueOnce(- Object.assign(new Error('precondition'), {- message: 'Error invoking remote method: Error: [PRECONDITION_FAILED] manifest changed',- }),- );-- await approveUpdateExpansion('plugin-a');-- const row = getUpdateAllBatchState().rows?.[0];- // 并发事实变化 → 回到重新审阅,不是终态失败(否则用户失去本项入口)。- expect(row?.status).toBe('needs-confirm');- expect(row?.errorText).toBeUndefined();- });-- it('drops the stale detail when a same-release manifest swap rejects the approval', async () => {- const reviewedManifest = manifest({ network: { hosts: ['api.example.com'] } });- stubDetail({ manifest: reviewedManifest, sourceType: 'git-market' });- startUpdateAllBatch([marketItem({ sourceType: 'git-market' })]);- await waitForSettledBatch();- expect(getUpdateAllBatchState().rows?.[0]).toMatchObject({- status: 'needs-confirm',- expectedManifest: reviewedManifest,- });-- // 竞态:detail() 返回的仍是审阅时那份(所以 renderer 侧判定审阅有效),- // 但在 install 到达 Main 之前,自定义源在**同一 releaseId 下**换了 manifest,- // Main 因 expectedManifest 对不上拒绝。此刻手里这份 detail 已经不对了。- const swappedManifest = manifest({- network: { hosts: ['api.example.com', 'evil.example.com'] },- });- installMock.mockRejectedValueOnce(- Object.assign(new Error('precondition'), {- message: 'Error invoking remote method: Error: [PRECONDITION_FAILED] manifest changed',- }),- );-- await approveUpdateExpansion('plugin-a');-- const held = getUpdateAllBatchState().rows?.[0];- // 旧差异与旧 manifest 必须丢弃并标记过期,否则下次批准会再提交同一份- // 过期的 expectedManifest,循环失败。- expect(held).toMatchObject({ status: 'needs-confirm', staleReview: true });- expect(held?.permissionDiff).toBeUndefined();- expect(held?.expectedManifest).toBeUndefined();-- // 再次批准:此时详情已能取到源上的新 manifest → 相对当前已装仍是扩权 →- // 用**新** manifest 重新出确认内容。- detailMock.mockResolvedValue({- ...marketItem({ sourceType: 'git-market' }),- manifest: swappedManifest,- readme: null,- } as unknown as PluginMarketDetail);- await approveUpdateExpansion('plugin-a');- const rereviewed = getUpdateAllBatchState().rows?.[0];- expect(rereviewed).toMatchObject({ status: 'needs-confirm', staleReview: false });- expect(rereviewed?.expectedManifest).toBe(swappedManifest);-- // 用户同意新差异 → 带新 manifest 装上,推进到完成,不再循环。- await approveUpdateExpansion('plugin-a');- expect(installMock).toHaveBeenLastCalledWith('plugin-a', {- expectedReleaseId: 'release-2',- expectedInstalledApproval: DEFAULT_APPROVAL_TOKEN,- expectedManifest: swappedManifest,- allowPermissionExpansion: true,- allowSourceReplacement: false,- reviewedBaseline: expect.any(String),- });- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');- });-- it('never treats a missing expectedManifest as a valid review for custom sources', async () => {- const reviewed = manifest({ network: { hosts: ['api.example.com'] } });- stubDetail({ manifest: reviewed, sourceType: 'git-market' });- startUpdateAllBatch([marketItem({ sourceType: 'git-market' })]);- await waitForSettledBatch();-- // 第一次批准被 Main 拒 → 行被清成 expectedManifest: undefined + staleReview。- installMock.mockRejectedValueOnce(- Object.assign(new Error('precondition'), {- message: 'Error invoking remote method: Error: [PRECONDITION_FAILED] manifest changed',- }),- );- await approveUpdateExpansion('plugin-a');- expect(getUpdateAllBatchState().rows?.[0]?.expectedManifest).toBeUndefined();-- // 重新审阅 → 再批准,全程必须带上当前 expectedManifest。缺失被短路成- // 「审阅仍有效」的话,这里会不带该字段安装,主进程直接 INVALID_PARAMS。- await approveUpdateExpansion('plugin-a');- await approveUpdateExpansion('plugin-a');-- expect(installMock).toHaveBeenLastCalledWith(- 'plugin-a',- expect.objectContaining({ expectedManifest: reviewed }),- );- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');- });-- it('voids an approval whose detail returned after the account switched', async () => {- stubDetail({- manifest: manifest({ network: { hosts: ['api.example.com'] } }),- sourceType: 'server',- });- startUpdateAllBatch([marketItem({})]);- await waitForSettledBatch();-- // 详情请求停在半空,期间切到账号 B(页面的作废 effect 还没跑,代际未变)。- let releaseDetail: (() => void) | undefined;- detailMock.mockImplementation(- () =>- new Promise((resolve) => {- releaseDetail = () => {- setDataOwnerGeneration('owner-b');- resolve({- ...marketItem({}),- manifest: manifest({ network: { hosts: ['api.example.com'] } }),- readme: null,- } as unknown as PluginMarketDetail);- };- }),- );- const approval = approveUpdateExpansion('plugin-a');- await vi.waitFor(() => expect(releaseDetail).toBeDefined());-- // 账号 B 装着同 id 的插件:旧批准绝不能读它的 manifest、更不能装它。- installedGhosts = [{ manifest: manifest({ version: '2.0.0' }) }];- releaseDetail?.();- await approval;-- expect(installMock).not.toHaveBeenCalled();- expect(getUpdateAllBatchState().rows).toBeNull();- });-- it('does not make a new generation approval wait behind the previous one', async () => {- const expanding = manifest({ network: { hosts: ['api.example.com'] } });- detailMock.mockImplementation(async (pluginId) =>- ({- ...marketItem({ pluginId, ghostId: pluginId === 'plugin-a' ? 'ghost-a' : 'ghost-b' }),- manifest: expanding,- readme: null,- }) as unknown as PluginMarketDetail,- );- installedGhosts = [{ manifest: manifest({ version: '1.0.0' }) }];- startUpdateAllBatch([marketItem({})]);- await waitForSettledBatch();-- // 账号 A 的批准卡在安装里(永不 resolve)。- const stuck: Array<() => void> = [];- installMock.mockImplementation(- () =>- new Promise((resolve) => {- stuck.push(() => resolve({ ghost: { manifest: expanding } } as never));- }),- );- const oldApproval = approveUpdateExpansion('plugin-a');- await vi.waitFor(() => expect(stuck.length).toBe(1));-- // 切账号 → 新批次(新代际)。- setDataOwnerGeneration('owner-b');- reconcileUpdateAllBatch();- installedGhosts = [{ manifest: manifest({ id: 'ghost-b', version: '1.0.0' }) }];- startUpdateAllBatch([marketItem({ pluginId: 'plugin-b', ghostId: 'ghost-b' })]);- await waitForSettledBatch();- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('needs-confirm');-- // 新代际的批准不该排在账号 A 那个仍然卡着的安装后面:它必须立刻开跑。- const newApproval = approveUpdateExpansion('plugin-b');- await vi.waitFor(() => expect(stuck.length).toBe(2));-- stuck[1]?.();- await newApproval;- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');-- // 收尾:放行旧代际那个安装,它轮到时因代际失效不会改写当前批次。- stuck[0]?.();- await oldApproval;- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');- });-- it('never rebinds a queued approval onto the batch that replaced it', async () => {- const expanding = manifest({ network: { hosts: ['api.example.com'] } });- detailMock.mockImplementation(async (pluginId) =>- ({- ...marketItem({ pluginId, ghostId: pluginId === 'plugin-a' ? 'ghost-a' : 'ghost-b' }),- manifest: expanding,- readme: null,- }) as unknown as PluginMarketDetail,- );- installedGhosts = [- { manifest: manifest({ version: '1.0.0' }) },- { manifest: manifest({ id: 'ghost-b', version: '1.0.0' }) },- ];- startUpdateAllBatch([- marketItem({}),- marketItem({ pluginId: 'plugin-b', ghostId: 'ghost-b' }),- ]);- await waitForSettledBatch();-- // 首项安装卡住,第二项的批准排在队列里等。- const gate: Array<() => void> = [];- installMock.mockImplementation(- () =>- new Promise((resolve) => {- gate.push(() => resolve({ ghost: { manifest: expanding } } as never));- }),- );- const first = approveUpdateExpansion('plugin-a');- const queued = approveUpdateExpansion('plugin-b');- await vi.waitFor(() => expect(gate.length).toBe(1));-- // 安装进行中切换账号 + 新账号启动自己的批次(同样含 plugin-b 待确认项)。- setDataOwnerGeneration('owner-b');- reconcileUpdateAllBatch();- installedGhosts = [{ manifest: manifest({ id: 'ghost-b', version: '1.0.0' }) }];- startUpdateAllBatch([marketItem({ pluginId: 'plugin-b', ghostId: 'ghost-b' })]);- await waitForSettledBatch();- const newBatchRow = getUpdateAllBatchState().rows?.[0];- expect(newBatchRow).toMatchObject({ pluginId: 'plugin-b', status: 'needs-confirm' });-- const installsBeforeDrain = installMock.mock.calls.length;- // 旧队列项这时才轮到执行:它属于上一个代际/账号,必须整体作废,- // 绝不能改绑到新批次里同 pluginId 的待确认项上并直接安装。- gate[0]?.();- await first;- await queued;-- expect(installMock.mock.calls.length).toBe(installsBeforeDrain);- // 新批次的待确认项原封不动,仍等用户在新账号下自己批准。- expect(getUpdateAllBatchState().rows?.[0]).toMatchObject({- pluginId: 'plugin-b',- status: 'needs-confirm',- });- });-- it('never lets a superseded runner write into the batch that replaced it', async () => {- // 账号 A 的 detail() 停在半空。- let releaseDetail: ((value: PluginMarketDetail) => void) | undefined;- detailMock.mockImplementation(- () =>- new Promise<PluginMarketDetail>((resolve) => {- releaseDetail = resolve;- }),- );- startUpdateAllBatch([marketItem({})]);- await vi.waitFor(() => expect(releaseDetail).toBeDefined());-- // 切到账号 B 并启动 B 自己的批次(旧批次已被作废 + 代际接管)。- setDataOwnerGeneration('owner-b');- reconcileUpdateAllBatch();- expect(getUpdateAllBatchState().rows).toBeNull();- detailMock.mockResolvedValue({- ...marketItem({ pluginId: 'plugin-b', ghostId: 'ghost-b' }),- manifest: manifest({ id: 'ghost-b' }),- readme: null,- } as unknown as PluginMarketDetail);- installedGhosts = [{ manifest: manifest({ id: 'ghost-b', version: '1.0.0' }) }];- startUpdateAllBatch([marketItem({ pluginId: 'plugin-b', ghostId: 'ghost-b' })]);-- // A 的请求这时才失败返回:不得把失败写进 B、不得消费 B 的 pending 行、- // 不得提前清掉 B 的 running。- releaseDetail?.(undefined as unknown as PluginMarketDetail);- await waitForSettledBatch();-- const rows = getUpdateAllBatchState().rows ?? [];- expect(rows.map((row) => row.pluginId)).toEqual(['plugin-b']);- expect(rows[0]?.status).not.toBe('failed');- expect(installMock).toHaveBeenCalledWith('plugin-b', expect.objectContaining({}));- });-- it('settles without reinstalling once the target release is actually on record', async () => {- stubDetail({- manifest: manifest({ network: { hosts: ['api.example.com'] } }),- sourceType: 'server',- });- startUpdateAllBatch([marketItem({})]);- await waitForSettledBatch();-- // 目标 release 已落账:detail 报 installed,批准直接收束不重复下载。- installedGhosts = [{ manifest: manifest({ version: '1.1.0' }) }];- detailMock.mockResolvedValue({- ...marketItem({ installState: 'installed' }),- manifest: manifest({ version: '1.1.0', network: { hosts: ['api.example.com'] } }),- readme: null,- } as unknown as PluginMarketDetail);-- // 已落账的早退分支同样要走统一收尾:刷新市场快照 + 完成 toast,- // 不留旧快照和悬空的未完成提示。- const refreshMarket = vi.fn(async () => undefined);- setUpdateAllBatchHooks({ refreshMarket });-- await approveUpdateExpansion('plugin-a');- expect(installMock).not.toHaveBeenCalled();- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');- expect(refreshMarket).toHaveBeenCalledTimes(1);- expect(toast.success).toHaveBeenCalledWith('settings.ghosts.updateAll.doneToast');- });-- it('holds running until the post-batch refresh settles so no second batch overlaps', async () => {- let releaseRefresh: (() => void) | undefined;- setUpdateAllBatchHooks({- refreshMarket: () =>- new Promise<void>((resolve) => {- releaseRefresh = resolve;- }),- });- stubDetail({ manifest: manifest({}), sourceType: 'server' });-- startUpdateAllBatch([marketItem({})]);- await vi.waitFor(() => expect(releaseRefresh).toBeDefined());-- // 刷新还没回来:running 必须仍为 true,旧 runner 的收尾不能让第二批插进来。- expect(getUpdateAllBatchState().running).toBe(true);- startUpdateAllBatch([marketItem({ pluginId: 'plugin-b', ghostId: 'ghost-b' })]);- expect(getUpdateAllBatchState().rows?.map((row) => row.pluginId)).toEqual(['plugin-a']);-- releaseRefresh?.();- await vi.waitFor(() => expect(getUpdateAllBatchState().running).toBe(false));- });-- it('keeps pending confirmations readable after the page unsubscribes (unmount)', async () => {- stubDetail({- manifest: manifest({ network: { hosts: ['api.example.com'] } }),- sourceType: 'server',- });-- startUpdateAllBatch([marketItem({})]);- await waitForSettledBatch();-- // 模块级状态与页面订阅无关:卸载(无订阅者)后快照仍保留待确认行,- // 重新进页可以直接恢复批准/跳过入口。- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('needs-confirm');- });});diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/updateAllModel.test.ts b/apps/desktop/src/renderer/features/plugin/__tests__/updateAllModel.test.tsindex 4a42ab80f4..a3b3e1f0cf 100644--- a/apps/desktop/src/renderer/features/plugin/__tests__/updateAllModel.test.ts+++ b/apps/desktop/src/renderer/features/plugin/__tests__/updateAllModel.test.ts@@ -80,16 +80,14 @@ describe('batch transitions', () => {expect(next[1].status).toBe('pending');});- it('finishes only after every row reaches a terminal state, including needs-confirm', () => {+ it('finishes only after every row reaches a terminal state', () => {let next = updateRow(rows, 'p1', { status: 'done' });next = updateRow(next, 'p2', { status: 'installing' });- expect(isBatchFinished(next)).toBe(false);-- next = updateRow(next, 'p2', { status: 'needs-confirm' });- expect(isBatchSettled(next)).toBe(true);+ expect(isBatchSettled(next)).toBe(false);expect(isBatchFinished(next)).toBe(false);next = updateRow(next, 'p2', { status: 'skipped' });+ expect(isBatchSettled(next)).toBe(true);expect(isBatchFinished(next)).toBe(true);expect(batchSummary(next)).toEqual({ done: 1, skipped: 1, failed: 0 });});diff --git a/apps/desktop/src/renderer/features/plugin/lib/__tests__/pluginMarketErrorKey.test.ts b/apps/desktop/src/renderer/features/plugin/lib/__tests__/pluginMarketErrorKey.test.tsindex 49704a6352..64e14ca399 100644--- a/apps/desktop/src/renderer/features/plugin/lib/__tests__/pluginMarketErrorKey.test.ts+++ b/apps/desktop/src/renderer/features/plugin/lib/__tests__/pluginMarketErrorKey.test.ts@@ -24,6 +24,12 @@ describe('pluginMarketErrorKey', () => {);});+ it('reuses the existing Cindy compatibility reminder', () => {+ expect(pluginMarketErrorKey(serializedIpcError('GHOST_HOST_UNSUPPORTED'))).toBe(+ 'settings.ghosts.errors.hostUnsupported',+ );+ });+it('never exposes a plain main-process error message', () => {expect(pluginMarketErrorKey(new Error('不应显示给 renderer 的内部错误'))).toBe('settings.ghosts.market.errors.generic',diff --git a/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts b/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.tsindex 62f883d6a1..b9c82a7340 100644--- a/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts+++ b/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts@@ -36,11 +36,11 @@ export interface GhostPluginListItem {enabled: boolean;canUse: boolean;/**- * Host 是否持有一次明确的安装/更新确认。非 `approved` 的安装不可运行,列表与- * 详情都必须如实说明并给出重新确认入口,而不是让它看起来只是"被关掉了"。+ * Host 是否持有完整、可验证的安装记录。非 `approved` 的安装不可运行,列表与+ * 详情都必须如实说明并给出恢复入口,而不是让它看起来只是“被关掉了”。*/approvalState: GhostInstallApproval['state'];- /** 随包内置插件(main 按种子清单投影)。批准态异常时文案与恢复入口都不同。 */+ /** 随包内置插件(main 按种子清单投影)。安装记录异常时文案与恢复入口都不同。 */builtin: boolean;/** 声明了插件页内独占面板(panel.position:'tab'),主动作为「使用」(打开面板)。 */tabPanel: boolean;@@ -279,9 +279,9 @@ export function toGhostPluginListItem(approvalState: ghost.approval.state,builtin: ghost.builtin === true,tabPanel: manifest.panel?.position === 'tab',- hasMainView: manifest.slots.includes('main-view') && manifest.mainView !== undefined,+ hasMainView: manifest.mainView !== undefined,mainViewTitle: manifest.mainView ? (manifest.mainView.title ?? manifest.name) : null,- hostCapability: manifest.slots.includes('ios-simulator') ? 'ios-simulator' : null,+ hostCapability: manifest.iosSimulator === true ? 'ios-simulator' : null,oauthAuthorizationExpired: ghost.oauthAuthorizationExpired !== undefined,trust: ghost.trust ?? {level: 'unverified',diff --git a/apps/desktop/src/renderer/features/plugin/lib/pluginMarketErrorKey.ts b/apps/desktop/src/renderer/features/plugin/lib/pluginMarketErrorKey.tsindex 738f1ecf07..6b4f1a51b5 100644--- a/apps/desktop/src/renderer/features/plugin/lib/pluginMarketErrorKey.ts+++ b/apps/desktop/src/renderer/features/plugin/lib/pluginMarketErrorKey.ts@@ -21,6 +21,8 @@ export function pluginMarketErrorKey(error: unknown): string {return 'settings.ghosts.errors.idReserved';case 'GHOST_BROKER_REDIRECT_PORT_REQUIRED':return 'settings.ghosts.market.errors.brokerRedirectPortRequired';+ case 'GHOST_HOST_UNSUPPORTED':+ return 'settings.ghosts.errors.hostUnsupported';default:return 'settings.ghosts.market.errors.generic';}diff --git a/apps/desktop/src/renderer/features/plugin/lib/pluginMarketPresentation.ts b/apps/desktop/src/renderer/features/plugin/lib/pluginMarketPresentation.tsindex d0345c1a15..5ab6714c02 100644--- a/apps/desktop/src/renderer/features/plugin/lib/pluginMarketPresentation.ts+++ b/apps/desktop/src/renderer/features/plugin/lib/pluginMarketPresentation.ts@@ -44,9 +44,9 @@ export function pluginUpdateForInstalledVersion(* Whether the market install flow may run against an already-installed Plugin.** A pending release is the usual case. The same release is also allowed when the- * install carries no Host approval: re-installing that exact release is how such- * an install gets reviewed again, and the flow shows every permission as newly- * requested. An approved install at the current release has nothing to review.+ * installation record is incomplete: reinstalling that exact release restores+ * the Host receipt without adding a capability-confirmation step. A verified+ * install at the current release has nothing to recover.*/export function marketReviewTargetsInstalledGhost(item: Pick<PluginMarketItem, 'installState'> | null | undefined,@@ -61,10 +61,10 @@ export function marketReviewTargetsInstalledGhost(}/**- * Where an unapproved install gets reviewed again. Market-owned installs replay- * the market confirmation; anything else needs the user to point at a `.cindy`- * package. Both routes end in the same permission confirmation — there is no- * path that restores an install without one.+ * Where an unverifiable install is recovered. Market-owned installs redownload+ * the bound release; anything else needs the user to point at a `.cindy` package.+ * Both routes revalidate real bytes and restore the installation record without+ * creating a separate capability authorization flow.*/export function ghostReapprovalRoute(item: Pick<PluginMarketItem, 'installState'> | null | undefined,diff --git a/apps/desktop/src/renderer/features/plugin/lib/updateAllController.ts b/apps/desktop/src/renderer/features/plugin/lib/updateAllController.tsindex 99da22dbbd..209ac3ffe0 100644--- a/apps/desktop/src/renderer/features/plugin/lib/updateAllController.ts+++ b/apps/desktop/src/renderer/features/plugin/lib/updateAllController.ts@@ -1,38 +1,21 @@/*** Window-level controller for the "update all plugins" batch flow.*- * Inputs: the market update snapshot plus user approve/skip actions.- * Outputs: a subscribable batch snapshot for the Plugin page and the- * serial install IPC calls.- *- * 为什么在组件外:批次可以在用户关掉弹窗、离开 /plugins 后继续跑- * (「后台继续」语义),待确认的扩权项也必须在回到插件页后仍然保留- * 批准/跳过入口——状态生命周期必须长于页面组件,所以照- * useInstalledGhosts 的先例做成模块级单例 store。真实包复核返回期间若- * 已装权限基线漂移,保留目标 release 并退回可恢复的重新审阅状态。- *- * 来源隔离(#2043):批次只原位更新 `update-available` 的市场包;conflict /- * 其它来源状态不在这里静默替换来源,install 一律 `allowSourceReplacement: false`。+ * The controller owns only batch progress and serial execution. Main validates+ * every downloaded package against its market manifest before atomic placement.* [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md*/import { i18n } from '@/i18n';import { toast } from '@/lib/toast';-import { extractIpcError } from '@/utils/ipcError';import { readInstalledGhostsSnapshot } from '@/cindy-brain/useInstalledGhosts';import {getDataOwnerGeneration,isDataOwnerGenerationCurrent,type DataOwnerGeneration,} from '@/contexts/dataOwnerGeneration';-import {- diffInstalledGhostPermissionItems,- ghostInstallApprovalToken,- ghostPermissionBaselineKey,- type GhostManifest,- type InstalledGhost,-} from '../../../../shared/ghost';import type { PluginMarketItem } from '../../../../shared/pluginMarket';+import { ghostInstallApprovalToken } from '../../../../shared/ghost';import { pluginMarketErrorKey } from './pluginMarketErrorKey';import {batchSummary,@@ -43,132 +26,49 @@ import {} from './updateAllModel';export interface UpdateAllBatchState {- /** null = 从未启动过批次;数组引用随每次行迁移变化(快照语义)。 */rows: UpdateAllRow[] | null;running: boolean;}interface UpdateAllBatchHooks {- /** 批次推进后的市场快照刷新;页面卸载期间缺席,重新进页会全量刷新。 */+ /** 页面存在时刷新市场;页面卸载期间缺席,重新进入会全量刷新。 */refreshMarket?: () => Promise<void>;}let state: UpdateAllBatchState = { rows: null, running: false };let finishToastShown = false;let hooks: UpdateAllBatchHooks = {};-/** 批次启动时的账号世代:身份切换后旧批次整体作废,绝不跨账号安装。 */let batchOwner: DataOwnerGeneration | null = null;-/**- * 批次代际。每次启动新批次或作废旧批次都自增,异步流程在启动时捕获它,- * 之后每个写入点都先核对——**光靠账号世代不够**:同一账号内旧批次被作废、- * 新批次接管时账号没变,旧 runner 的迟到写入照样会污染新批次(把上一批的- * 失败写进新批次、继续消费新批次的 pending 行、提前清掉新批次的 running)。- * 代际失效的 runner 只能停下,不得改写、不得收尾、不得触发任何副作用。- */let batchGeneration = 0;-/**- * 在途批准的串行队列,**按代际隔离**。- *- * 同一代际内必须排队而非并发:并发安装同一批次的多个 release 会互相踩市场- * 刷新与已装清单快照,收尾也会被任一单项提前释放。- *- * 但队列不能全局共用一条链:账号/模式切换后新批次的批准会排在旧代际那个- * 慢 install() 后面干等——代际校验只能在轮到执行时把旧项丢掉,解不掉前面的- * 等待。各代际各排各的,新身份点批准立即开始;旧代际的项轮到时照样因代际- * 失效而不执行安装。条目在该代际无在途时回收(见 releaseApproval)。- */-const approvalQueueByGeneration = new Map<number, Promise<unknown>>();-/**- * 在途批准计数**按代际分桶**。全局单计数不够:旧代际的在途项会把新批次的- * 收尾计数拖住(减到 0 时代际已不匹配、跳过收尾,新批次就永远不释放 running)。- * 每个代际只对自己的桶负责。- */-const inflightByGeneration = new Map<number, number>();const listeners = new Set<() => void>();-function retainApproval(generation: number): void {- inflightByGeneration.set(generation, (inflightByGeneration.get(generation) ?? 0) + 1);-}--/** 归还一个在途名额;返回该代际是否已无在途(= 轮到收尾)。 */-function releaseApproval(generation: number): boolean {- const next = (inflightByGeneration.get(generation) ?? 1) - 1;- if (next <= 0) {- inflightByGeneration.delete(generation);- // 该代际不再有批准在途,它的队列链也没人接了——一并清掉,免得- // 长会话里每换一次账号/批次都留下一条永不回收的 promise 链。- approvalQueueByGeneration.delete(generation);- return true;- }- inflightByGeneration.set(generation, next);- return false;-}-function emit(next: UpdateAllBatchState): void {state = next;listeners.forEach((listener) => listener());}-/** 开启新代际(旧代际的异步流程随即失效),返回新代际号。 */function beginGeneration(): number {batchGeneration += 1;return batchGeneration;}-/** 该代际是否仍是当前批次(代际未被接管 + 账号未切换)。 */+function batchOwnerCurrent(): boolean {+ return batchOwner !== null && isDataOwnerGenerationCurrent(batchOwner);+}+function isGenerationCurrent(generation: number): boolean {- return (- batchGeneration === generation &&- batchOwner !== null &&- isDataOwnerGenerationCurrent(batchOwner)- );+ return generation === batchGeneration && batchOwnerCurrent();}function patchRow(generation: number, pluginId: string, patch: Partial<UpdateAllRow>): void {- // 代际已失效(批次被作废或被新批次接管)时,迟到的行迁移直接丢弃。if (!isGenerationCurrent(generation) || state.rows === null) return;emit({ ...state, rows: updateRow(state.rows, pluginId, patch) });}-function batchOwnerCurrent(): boolean {- return batchOwner !== null && isDataOwnerGenerationCurrent(batchOwner);-}--/**- * 把一行退回「待重新审阅」——前置条件变化的统一收敛(runner 与批准共用)。- *- * 清掉旧的 permissionDiff 并打 staleReview:弹窗据此显示「权限差异已过期 /- * 重新审阅」,用户点一下就走 approve 按当前事实重取详情、重算差异,- * 无扩权直接装、仍扩权则逐项审。可恢复,不必关弹窗重启整批。- */-function holdRowForReReview(- generation: number,- pluginId: string,- patch: Partial<UpdateAllRow> = {},-): void {- const releaseId = patch.releaseId ?? state.rows?.find((r) => r.pluginId === pluginId)?.releaseId;- if (!releaseId) {- // 没有目标 release 就没有可重审的对象:approveUpdateExpansion 的入口守卫- // 要求 row.releaseId 存在,少了它这行会变成点「重新审阅」也没反应的死行。- // 与其静默卡住,不如如实落失败(errorText 留空 = 弹窗显示通用失败文案)。- patchRow(generation, pluginId, { status: 'failed' });- return;- }- patchRow(generation, pluginId, {- status: 'needs-confirm',- staleReview: true,- permissionDiff: undefined,- reviewedApproval: undefined,- ...patch,- releaseId,- });-}--/** 账号/模式切换后作废整个批次(旧代际的 runner 在下一个检查点自行退出)。 */function voidStaleBatch(): void {batchOwner = null;- beginGeneration(); // 让在飞的 runner / approve 立即失效。- finishToastShown = true; // 作废批次不再补发完成 toast。+ beginGeneration();+ finishToastShown = true;emit({ rows: null, running: false });}@@ -183,7 +83,6 @@ export function getUpdateAllBatchState(): UpdateAllBatchState {return state;}-/** 页面挂载期注册环境回调;返回的清理函数在卸载时注销。 */export function setUpdateAllBatchHooks(next: UpdateAllBatchHooks): () => void {hooks = next;return () => {@@ -191,23 +90,16 @@ export function setUpdateAllBatchHooks(next: UpdateAllBatchHooks): () => void {};}-function installedGhostOf(ghostId: string): InstalledGhost | null {- return readInstalledGhostsSnapshot().find((ghost) => ghost.manifest.id === ghostId) ?? null;-}-async function refreshMarketIfMounted(): Promise<void> {try {await hooks.refreshMarket?.();} catch {- // 快照刷新失败不影响批次结果;下次进页会重新拉取。+ // 批次结果不依赖刷新成功;重新进入页面会再取完整快照。}}function maybeFinishToast(): void {const rows = state.rows;- // 还有批准在途时不报完成:它们的行此刻是 installing,提前报会把"没装完"- // 说成"已完成"。最后一个在途批准的收尾会再来一次。- if ((inflightByGeneration.get(batchGeneration) ?? 0) > 0) return;if (!rows || rows.length === 0 || !isBatchFinished(rows) || finishToastShown) return;finishToastShown = true;const summary = batchSummary(rows);@@ -219,7 +111,6 @@ function maybeFinishToast(): void {);}-/** 启动新批次(运行中调用是 no-op;是否复用未完成批次由页面判断)。 */export function startUpdateAllBatch(marketUpdates: readonly PluginMarketItem[]): void {if (state.running) return;const installedVersionById = new Map(@@ -232,108 +123,64 @@ export function startUpdateAllBatch(marketUpdates: readonly PluginMarketItem[]):void runQueue(generation);}-/**- * 批量 runner:串行走「取详情 → 权限 diff → 无扩权直接装 / 有扩权停待确认」。- * 全程以启动时捕获的 `generation` 为准:任一 await 之后代际若已失效- * (批次被作废或被新批次接管),立即停手——不写状态、不消费队列、不收尾。- *- * 来源隔离(#2043):非 `update-available` 的详情(conflict / 其它状态)不在- * 批量里静默替换来源,按跳过收束;自动安装路径一律 `allowSourceReplacement: false`。- */+/** 串行执行,每个 install() 自己在 Main 中下载、校验并提交同一真实包。 */async function runQueue(generation: number): Promise<void> {if (state.running || !isGenerationCurrent(generation)) return;emit({ ...state, running: true });try {for (;;) {- if (batchGeneration !== generation) return; // 已被新批次接管:静默让位。+ if (generation !== batchGeneration) return;if (!batchOwnerCurrent()) {voidStaleBatch();return;}- const next = (state.rows ?? []).find((row) => row.status === 'pending');+ const next = state.rows?.find((row) => row.status === 'pending');if (!next) break;patchRow(generation, next.pluginId, { status: 'installing' });- // detail 提到 try 外:install 抛前置条件失败时,catch 要靠它把目标 release- // 写回待重审行——runApprovalBody 的入口守卫要求 row.releaseId 存在,- // 缺了它用户点「重新审阅」会直接 return,该项在本批次里静默卡死。- let detail: Awaited<ReturnType<typeof window.electronAPI.pluginMarket.detail>> | null = null;try {- detail = await window.electronAPI.pluginMarket.detail(next.pluginId);- // detail 往返期间可能切换账号或换批次:install 会以当前账号执行,- // 旧批次绝不能把上一轮的更新落到新账号/新批次上。- if (batchGeneration !== generation) return;+ const detail = await window.electronAPI.pluginMarket.detail(next.pluginId);+ if (generation !== batchGeneration) return;if (!batchOwnerCurrent()) {voidStaleBatch();return;}if (detail.installState === 'installed') {- // 目标 release 已经落账——典型是用户在批次启动前后用卡片上的单项更新- // 装了同一个 release,而本批次拿的是那之前的市场快照。直接收束,- // 不重复下载安装同一份包。patchRow(generation, next.pluginId, { status: 'done' });continue;}- // 来源隔离(#2043):批量更新只原位替换 update-available 的市场包;- // conflict / 其它来源状态不在这里静默切换来源,按跳过收束。if (detail.installState !== 'update-available') {patchRow(generation, next.pluginId, { status: 'skipped' });continue;}- const installedGhost = installedGhostOf(next.ghostId);- if (!installedGhost) {- // 批量期间插件已被卸载:绝不拿市场 manifest 兜底继续安装- // (那会把用户刚卸载的插件重新装回来),该行按跳过收束。+ const installed = readInstalledGhostsSnapshot().find(+ (ghost) => ghost.manifest.id === next.ghostId,+ );+ if (!installed) {patchRow(generation, next.pluginId, { status: 'skipped' });continue;}- const installedManifest = installedGhost.manifest;- const reviewedApproval = ghostInstallApprovalToken(installedGhost.approval);- const diff = diffInstalledGhostPermissionItems(installedGhost, detail.manifest);- if (installedGhost.approval.state !== 'approved' || diff.added.length > 0) {- // 扩权不自动放行;没有有效 receipt 时也不存在可沿用的批准基线,- // 即使目标包没有权限项仍要停下来完成一次明确确认。- patchRow(generation, next.pluginId, {- status: 'needs-confirm',- releaseId: detail.releaseId,- permissionDiff: diff,- // 审阅基线绑定权限指纹而非版本号:同版本换 manifest 也能识别。- reviewedBaseline: ghostPermissionBaselineKey(installedManifest),- reviewedApproval,- expectedManifest: detail.manifest,- });- continue;- }patchRow(generation, next.pluginId, {- fromVersion: installedManifest.version,+ fromVersion: installed.manifest.version,toVersion: detail.version,});- const result = await window.electronAPI.pluginMarket.install(next.pluginId, {+ await window.electronAPI.pluginMarket.install(next.pluginId, {expectedReleaseId: detail.releaseId,- expectedInstalledApproval: reviewedApproval,expectedManifest: detail.manifest,+ expectedInstalledApproval: ghostInstallApprovalToken(installed.approval),allowSourceReplacement: false,});- if (result.cancelled) {- patchRow(generation, next.pluginId, { status: 'skipped' });- continue;+ if (generation !== batchGeneration) return;+ if (!batchOwnerCurrent()) {+ voidStaleBatch();+ return;}patchRow(generation, next.pluginId, { status: 'done' });} catch (error) {- if (batchGeneration !== generation) return;- // 前置条件变化(基线复核否决 / release 变了 / 自定义源换了 manifest)- // 不是「更新失败」而是「事实已变,请重新审阅」。落成终态 failed 会让- // 这一项彻底没有入口,用户只能关掉弹窗重启整批。改为可恢复的待重审:- // 弹窗显示「权限差异已过期 / 重新审阅」,点一下就按当前事实重算。- // detail 为 null 说明连详情都没取到,没有可写回的 release,此时重审也- // 无从下手,按失败处理更诚实。- if (extractIpcError(error)?.code === 'PRECONDITION_FAILED' && detail !== null) {- holdRowForReReview(generation, next.pluginId, {- releaseId: detail.releaseId,- toVersion: detail.version,- });- continue;+ if (generation !== batchGeneration) return;+ if (!batchOwnerCurrent()) {+ voidStaleBatch();+ return;}- // 失败也只写回自己的批次:代际失效时这条错误属于已作废的批次。patchRow(generation, next.pluginId, {status: 'failed',errorText: i18n.t(pluginMarketErrorKey(error)),@@ -345,265 +192,19 @@ async function runQueue(generation: number): Promise<void> {}}-/**- * 批次收尾(所有返回路径共用):刷新市场快照 → 放开 running → 补完成 toast。- *- * running 必须**撑到刷新结束**才落下:刷新期间市场快照还是旧的,若此时放开- * running,页面拿旧快照就能启动第二批,而本 runner 的收尾还会写到新批次上。- * 代际失效时整个收尾跳过——旧 runner 不得清掉当前批次的 running、也不得- * 触发当前批次的完成提示。- */async function settleBatchTail(generation: number): Promise<void> {- if (batchGeneration !== generation) return;+ if (generation !== batchGeneration) return;await refreshMarketIfMounted();- if (batchGeneration !== generation) return;- if (state.running) emit({ ...state, running: false });- maybeFinishToast();-}--/**- * 用户在弹窗里同意某个扩权项后继续安装。- *- * 多个待确认项连点时**串行执行**:后一个排在前一个之后,不并发装。- * running 由在途计数统一管理——第一个入队时点亮,最后一个结束时才收尾释放,- * 中途任何单项都不许提前把闸门放开(否则页面拿旧快照可重复启动)。- */-export function approveUpdateExpansion(pluginId: string): Promise<void> {- // **入队时**捕获代际与账号归属:用户点的是"此刻这个批次里的这一项"。- // 若等排到自己时才读当前批次,账号切换 / 新批次接管后,这次旧点击就会- // 重新绑定到新批次里同 pluginId 的待确认项上——等于未经批准放行新账号- // 或新 release 的扩权。代际不符一律丢弃,绝不改绑。- const generation = batchGeneration;- const owner = batchOwner;- retainApproval(generation);- // 队列**按代际隔离**:全局单链下,账号切换后新批次的批准会排在旧代际那个- // 慢 install() 后面干等——代际校验只能在轮到执行时把旧项丢掉,解不掉前面的- // 等待。各代际各排各的,新账号点批准立即开始;旧代际的项轮到时仍会因代际- // 失效而不执行安装。- const previous = approvalQueueByGeneration.get(generation) ?? Promise.resolve();- const run = previous.then(() => runApproval(pluginId, generation, owner));- // 队列本身吞掉失败,后续批准不因前一个抛错而卡死;错误仍由 runApproval- // 内部落到对应行的 failed 状态。- approvalQueueByGeneration.set(generation, run.catch(() => undefined));- return run;-}--async function runApproval(- pluginId: string,- generation: number,- owner: DataOwnerGeneration | null,-): Promise<void> {- try {- // 排队期间批次被作废/接管,或账号已切换 → 这次批准属于过去,直接作废。- if (batchGeneration !== generation) return;- if (owner === null || !isDataOwnerGenerationCurrent(owner)) {- voidStaleBatch();- return;- }- await runApprovalBody(pluginId, generation);- } finally {- // 只有**本代际**最后一个在途批准才收尾:刷新市场快照 → 释放 running →- // 补完成提示。早于这一刻释放,后续排队中的批准就会在闸门已开的状态下继续装。- // settleBatchTail 自己再校验一次代际,失效时不碰当前批次。- if (releaseApproval(generation)) await settleBatchTail(generation);- }-}--async function runApprovalBody(pluginId: string, generation: number): Promise<void> {- if (!batchOwnerCurrent()) {- voidStaleBatch();- return;- }- if (batchGeneration !== generation) return;- const row = state.rows?.find((candidate) => candidate.pluginId === pluginId);- // 排在前面的批准可能已经把本行推进过(重复点同一项),只处理仍待确认的。- if (!row || row.status !== 'needs-confirm' || !row.releaseId) return;- if (installedGhostOf(row.ghostId) === null) {- // 待确认期间插件被卸载:同意也不重装,按跳过收束。- patchRow(generation, pluginId, { status: 'skipped' });- return;- }- // 批准也是批次在推进:running 从这里一直撑到**最后一个**在途批准收尾结束,- // 期间页面拿的是旧的 update-available 快照,不能让它启动第二批重复安装。- patchRow(generation, pluginId, { status: 'installing' });- if (!state.running) emit({ ...state, running: true });- try {- // 一律重取详情。它同时给出三件事,缺一不可:- // 1. installState —— **目标 release 是否真的落账**的权威判据。main 侧- // 只有 record.releaseId === 目标 release 且所有权归本插件时才报- // 'installed'(plugin-market/service.ts),所以「从文件装了同版本- // 但不同 release」不会被误判成完成;版本号比对做不到这点。- // 2. 最新 releaseId / manifest —— 并发防护与非 server 源的 reviewed manifest。- // 3. 当前 manifest —— 与已装 manifest 重算权限差异。- const detail = await window.electronAPI.pluginMarket.detail(pluginId);- // detail 往返期间批次可能已被作废/接管:此后一律不再写状态、不再安装。- // 与 runQueue 同一套**双重**校验:代际管「同账号内换批次」,owner 管- // 「账号刚切走但页面的作废 effect 还没跑」那个窗口——只看代际的话,- // 这段时间里旧批准会读到新账号的已装 manifest 并安装新账号的同 id 插件。- if (batchGeneration !== generation) return;- if (!batchOwnerCurrent()) {- voidStaleBatch();- return;- }- // **detail 之后重读已装 manifest**:这段往返里「从文件更新」等路径可能整体- // 换掉它,拿 await 之前的快照判断 = 拿过期事实做安全决策。- const installedGhost = installedGhostOf(row.ghostId);- if (installedGhost === null) {- patchRow(generation, pluginId, { status: 'skipped' });- return;- }- const installed = installedGhost.manifest;- if (detail.installState === 'installed') {- // 目标 release 已由别的路径装上:直接收束,不重复下载安装。- // (return 后仍走 finally 的统一收尾——刷新市场快照 + 完成 toast。)- patchRow(generation, pluginId, { status: 'done', fromVersion: installed.version });- return;- }- /** 相对**当前**事实回到逐项审阅(不是终态失败:用户还能重新决定)。 */- const holdForReReview = (): void => {- patchRow(generation, pluginId, {- status: 'needs-confirm',- fromVersion: installed.version,- toVersion: detail.version,- releaseId: detail.releaseId,- permissionDiff: diffInstalledGhostPermissionItems(installedGhost, detail.manifest),- staleReview: false,- reviewedBaseline: ghostPermissionBaselineKey(installed),- reviewedApproval: ghostInstallApprovalToken(installedGhost.approval),- expectedManifest: detail.manifest,- });- };- // 用户审阅的是「审阅当时的已装权限面 → 那一刻的目标 release」。三个前提- // 任一变了,那份 diff 与它换来的 allowPermissionExpansion 就不再对应现实:- // - staleReview:reconcile 已发现基线被换掉;- // - 权限指纹变化(以刚重读的 installed 为准):ghosts.update() 允许**同版本- // 整体替换 manifest**,同版本换入更宽的声明时版本比较完全看不出来;- // - 目标 release 变化:市场在等待期间发了新版,审的不是这一版。- // - 目标 manifest 变化:自定义市场源可以在**同一 releaseId 下**改 manifest,- // 只比 releaseId 看不出来。- // 所有来源都必须留有 expectedManifest 且与当前详情逐份一致才算有效:- // 缺失不能短路成「有效」——那样下一次批准会不带 expectedManifest 去装,- // 主进程对这类来源直接 INVALID_PARAMS,行落成 failed(前一轮把被拒的行- // 清成 expectedManifest: undefined,正好会踩中)。- const manifestStillMatches =- row.expectedManifest !== undefined &&- JSON.stringify(row.expectedManifest) === JSON.stringify(detail.manifest);- const reviewedApproval = row.reviewedApproval;- const reviewStillValid =- row.staleReview !== true &&- reviewedApproval !== undefined &&- ghostPermissionBaselineKey(installed) === row.reviewedBaseline &&- ghostInstallApprovalToken(installedGhost.approval) === reviewedApproval &&- detail.releaseId === row.releaseId &&- manifestStillMatches;- /**- * 安装并接住「前置条件失败」。Main 的 PRECONDITION_FAILED 覆盖一组- * **并发事实变化**:安装锁内的基线复核否决、release 变了、自定义市场源- * 在 detail() 之后以同版本改了 manifest(expectedManifest 对不上)。- * 这些都是「事实已变,请重新审阅」而不是「更新失败」——终态 failed 会让- * 用户彻底失去这一项的入口,只能重启整批。所以一律回到 needs-confirm。- * 返回 true = 真的装上了;false = 已按重审/让位处理完,调用方直接收手。- */- const installOrHoldForReReview = async (- options: Parameters<typeof window.electronAPI.pluginMarket.install>[1],- ): Promise<boolean> => {- try {- const result = await window.electronAPI.pluginMarket.install(pluginId, options);- if (result.cancelled) {- patchRow(generation, pluginId, { status: 'skipped' });- return false;- }- return true;- } catch (error) {- if (batchGeneration !== generation) return false;- if (extractIpcError(error)?.code === 'PRECONDITION_FAILED') {- // 注意**不能**用 holdForReReview():那会拿手里这份 detail 重算差异并- // 把 staleReview 置 false。可安装被拒恰恰说明这份 detail 已经不对了- // (典型是自定义源在同 releaseId 下换了 manifest),照它生成确认内容,- // 下次批准还会提交同一份过期的 expectedManifest,陷入循环失败。- // 丢掉旧差异、标记过期,等下次批准重新取详情。- holdRowForReReview(generation, pluginId, {- releaseId: detail.releaseId,- toVersion: detail.version,- fromVersion: installed.version,- expectedManifest: undefined,- });- return false;- }- throw error;- }- };- if (reviewStillValid && row.expectedManifest !== undefined) {- const didInstall = await installOrHoldForReReview({- expectedReleaseId: row.releaseId,- expectedInstalledApproval: reviewedApproval,- expectedManifest: row.expectedManifest,- allowPermissionExpansion: true,- allowSourceReplacement: false,- // 审阅基线随批准回传:Main 在安装锁内用当时的已装 manifest 复核,- // renderer 这边的检查挡不住 IPC 往返窗口内的替换。- ...(row.reviewedBaseline !== undefined- ? { reviewedBaseline: row.reviewedBaseline }- : {}),- });- if (!didInstall) return;- patchRow(generation, pluginId, { status: 'done' });- } else if (- installedGhost.approval.state !== 'approved' ||- diffInstalledGhostPermissionItems(installedGhost, detail.manifest).added.length > 0- ) {- // 相对新事实仍是扩权,或当前已没有有效批准基线:回到完整审阅,- // 绝不拿旧批准静默放行。- holdForReReview();- return;- } else {- // 重算后已无扩权,按普通更新装。这条同样要接住并发变化:自定义市场源- // 在 detail() 返回后以同版本改 manifest 时,Main 会因 expectedManifest- // 不匹配拒绝,不能把它落成终态失败。- const ok = await installOrHoldForReReview({- expectedReleaseId: detail.releaseId,- expectedInstalledApproval: ghostInstallApprovalToken(installedGhost.approval),- expectedManifest: detail.manifest,- allowSourceReplacement: false,- });- if (!ok) return;- patchRow(generation, pluginId, { status: 'done', fromVersion: installed.version });- }- } catch (error) {- patchRow(generation, pluginId, {- status: 'failed',- errorText: i18n.t(pluginMarketErrorKey(error)),- });- }- // 收尾统一由 runApproval 在**最后一个**在途批准结束时做(见那里的 finally):- // 每项各自收尾会让前一项提前释放 running,后面排队的批准就在开着的闸门下跑。-}--/** 用户在弹窗里跳过某个扩权项。 */-export function skipUpdateExpansion(pluginId: string): void {+ if (generation !== batchGeneration) return;if (!batchOwnerCurrent()) {voidStaleBatch();return;}- const row = state.rows?.find((candidate) => candidate.pluginId === pluginId);- if (!row || row.status !== 'needs-confirm') return;- patchRow(batchGeneration, pluginId, { status: 'skipped' });+ if (state.running) emit({ ...state, running: false });maybeFinishToast();}-/**- * 与外部事实对账:账号切换 → 整批作废;待确认行或尚未开始的行被卸载 → 跳过、- * **目标 release 已落账**(市场快照报 'installed')→ 记为完成、- * 权限基线被换掉(含同版本替换 manifest)→ 旧 permissionDiff 已不对应- * 现实,清掉并标记待重审(真正的重算在 approve 时做,那里能取详情)。- *- * `pending` 行按来源事实收束(来源隔离,#2043):市场快照不再报- * `update-available`(conflict 等)→ 跳过,不再静默切换来源。- *- * 完成判据只认市场快照的 installState,不认版本号:同版本不同 release- * (从文件装入)在版本比对下无法区分,会把没装上目标 release 的行误收成完成。- * 页面在已装清单、市场快照或身份变化时调用,并把当前市场快照传进来。- */+/** 页面外的已装/市场事实变化只用于收束尚未开始的行。 */export function reconcileUpdateAllBatch(marketItems: readonly PluginMarketItem[] = []): void {if (state.rows === null) return;if (!batchOwnerCurrent()) {@@ -619,69 +220,34 @@ export function reconcileUpdateAllBatch(marketItems: readonly PluginMarketItem[]let rows = state.rows;let changed = false;for (const row of state.rows) {- if (row.status === 'pending') {- const installed = installedById.get(row.ghostId);- if (!installed) {- rows = updateRow(rows, row.pluginId, { status: 'skipped' });- changed = true;- } else if (installStateByPluginId.get(row.pluginId) === 'installed') {- // 目标 release 已落账:无需再装。- rows = updateRow(rows, row.pluginId, { status: 'done' });- changed = true;- } else if (- installStateByPluginId.has(row.pluginId) &&- installStateByPluginId.get(row.pluginId) !== 'update-available'- ) {- // 来源隔离:来源已变化(conflict 等),不静默替换,按跳过收束。- rows = updateRow(rows, row.pluginId, { status: 'skipped' });- changed = true;- } else if (installed.version !== row.fromVersion) {- rows = updateRow(rows, row.pluginId, { fromVersion: installed.version });- changed = true;- }- } else if (row.status === 'needs-confirm') {- const installedGhost = installedGhostOf(row.ghostId);- if (installedGhost === null) {- rows = updateRow(rows, row.pluginId, { status: 'skipped' });- changed = true;- } else if (installStateByPluginId.get(row.pluginId) === 'installed') {- // 目标 release 已落账(main 侧 record.releaseId 对上):无需再装。- rows = updateRow(rows, row.pluginId, { status: 'done' });- changed = true;- } else if (- ghostPermissionBaselineKey(installedGhost.manifest) !== row.reviewedBaseline ||- ghostInstallApprovalToken(installedGhost.approval) !== row.reviewedApproval- ) {- // 权限基线或批准态变了(含 approved receipt 失效):旧审阅作废。- rows = updateRow(rows, row.pluginId, {- fromVersion: installedGhost.manifest.version,- permissionDiff: undefined,- staleReview: true,- reviewedApproval: undefined,- });- changed = true;- } else if (installedGhost.manifest.version !== row.fromVersion) {- // 权限面没变、只是版本号变了:审阅结论仍然成立,同步展示用版本即可。- rows = updateRow(rows, row.pluginId, { fromVersion: installedGhost.manifest.version });- changed = true;- }+ if (row.status !== 'pending') continue;+ const installed = installedById.get(row.ghostId);+ if (!installed) {+ rows = updateRow(rows, row.pluginId, { status: 'skipped' });+ changed = true;+ } else if (installStateByPluginId.get(row.pluginId) === 'installed') {+ rows = updateRow(rows, row.pluginId, { status: 'done' });+ changed = true;+ } else if (+ installStateByPluginId.has(row.pluginId) &&+ installStateByPluginId.get(row.pluginId) !== 'update-available'+ ) {+ rows = updateRow(rows, row.pluginId, { status: 'skipped' });+ changed = true;+ } else if (installed.version !== row.fromVersion) {+ rows = updateRow(rows, row.pluginId, { fromVersion: installed.version });+ changed = true;}}- if (changed) {- emit({ ...state, rows });- maybeFinishToast();- }+ if (changed) emit({ ...state, rows });}-/** 仅测试用:清空模块级批次状态与回调注册。 */+/** 仅测试用:清空模块级批次状态。 */export function __resetUpdateAllBatchForTest(): void {state = { rows: null, running: false };finishToastShown = false;hooks = {};batchOwner = null;- // 递增而非归零:上个用例遗留的在飞 runner 认的是旧代际,归零会让它复活。beginGeneration();- approvalQueueByGeneration.clear();- inflightByGeneration.clear();listeners.clear();}diff --git a/apps/desktop/src/renderer/features/plugin/lib/updateAllModel.ts b/apps/desktop/src/renderer/features/plugin/lib/updateAllModel.tsindex c8dd1eb764..5bf72dbffd 100644--- a/apps/desktop/src/renderer/features/plugin/lib/updateAllModel.ts+++ b/apps/desktop/src/renderer/features/plugin/lib/updateAllModel.ts@@ -7,18 +7,16 @@* [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md*/-import type { GhostManifest, GhostPermissionDiff } from '../../../../shared/ghost';import type { PluginMarketItem } from '../../../../shared/pluginMarket';/**- * 批量更新策略(设计定稿):权限无变化的自动串行完成;权限有扩张的- * 停在 `needs-confirm`,由用户逐项同意或跳过,绝不自动放行扩权。+ * 批量更新只维护执行进度。真实包由统一安装事务校验并落位,+ * 本模型不再保存目录 manifest、能力基线或另一套更新状态。*/export type UpdateAllRowStatus =| 'pending'| 'installing'| 'done'- | 'needs-confirm'| 'skipped'| 'failed';@@ -29,32 +27,6 @@ export interface UpdateAllRow {fromVersion: string;toVersion: string;status: UpdateAllRowStatus;- /** 目标 release(needs-confirm 时由运行器填充,approve 用它做并发防护)。 */- releaseId?: string;- /** 扩权详情(status 为 needs-confirm 时由运行器填充)。 */- permissionDiff?: GhostPermissionDiff;- /**- * 待确认期间插件被外部路径(从文件更新等)换掉了权限基线:审阅过的- * 权限差异已不对应现实,弹窗提示"需要重新审阅",按钮点下去先重算再决定。- */- staleReview?: boolean;- /**- * 审阅所依据的**已装 manifest 权限指纹**(不是版本号)。- * `ghosts.update()` 允许同版本整体替换 manifest,所以版本号不是可靠的- * 审阅基线。Renderer 先检查、Main 在安装锁内复核。- */- reviewedBaseline?: string;- /**- * 审阅时 Host 下发的批准态 token。manifest 权限指纹相同也不代表授权事实- * 相同:approved receipt 失效成 invalid / legacy-unapproved 后,旧的局部 diff- * 必须作废并按“无批准基线”重新展示全部权限。- */- reviewedApproval?: string;- /**- * 审阅时取得的 manifest:主进程强制要求安装时传回同一份清单,- * approve 必须原样带上,否则 INVALID_PARAMS。- */- expectedManifest?: GhostManifest;/** status 为 failed 时的用户可读错误(已经过 i18n 映射)。 */errorText?: string;}@@ -90,9 +62,9 @@ export function isBatchSettled(rows: readonly UpdateAllRow[]): boolean {return rows.every((row) => row.status !== 'pending' && row.status !== 'installing');}-/** 批次是否完全结束:连待确认的扩权行都已被用户处理。 */+/** 批次是否完全结束。 */export function isBatchFinished(rows: readonly UpdateAllRow[]): boolean {- return isBatchSettled(rows) && rows.every((row) => row.status !== 'needs-confirm');+ return isBatchSettled(rows);}/** 完成摘要:成功 / 跳过 / 失败计数,供收尾 toast 使用。 */diff --git a/apps/desktop/src/renderer/features/right-sidebar/__tests__/iosSimulatorPluginAvailability.test.ts b/apps/desktop/src/renderer/features/right-sidebar/__tests__/iosSimulatorPluginAvailability.test.tsindex 004eff213c..7b1a169df7 100644--- a/apps/desktop/src/renderer/features/right-sidebar/__tests__/iosSimulatorPluginAvailability.test.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/__tests__/iosSimulatorPluginAvailability.test.ts@@ -10,10 +10,10 @@ import {} from '../iosSimulatorPluginAvailability';import type { TabState } from '../types';-function ghost(id: string, enabled: boolean, slots: string[]): InstalledGhost {+function ghost(id: string, enabled: boolean, hasCapability: boolean): InstalledGhost {return {enabled,- manifest: { id, slots },+ manifest: { id, ...(hasCapability ? { iosSimulator: true } : {}) },} as unknown as InstalledGhost;}@@ -33,16 +33,14 @@ const TABS_WITH_SUBAGENTS: TabState[] = [describe('iOS Simulator plugin availability', () => {it('requires an enabled plugin with the capability slot', () => {expect(isIOSSimulatorPluginAvailable([])).toBe(false);- expect(isIOSSimulatorPluginAvailable([ghost('ios-simulator', false, ['ios-simulator'])])).toBe(+ expect(isIOSSimulatorPluginAvailable([ghost('ios-simulator', false, true)])).toBe(false,);- expect(isIOSSimulatorPluginAvailable([ghost('ios-simulator', true, ['panel'])])).toBe(false);- expect(isIOSSimulatorPluginAvailable([ghost('another-plugin', true, ['ios-simulator'])])).toBe(+ expect(isIOSSimulatorPluginAvailable([ghost('ios-simulator', true, false)])).toBe(false);+ expect(isIOSSimulatorPluginAvailable([ghost('another-plugin', true, true)])).toBe(true,);- expect(- isIOSSimulatorPluginAvailable([ghost('ios-simulator', true, ['panel', 'ios-simulator'])]),- ).toBe(true);+ expect(isIOSSimulatorPluginAvailable([ghost('ios-simulator', true, true)])).toBe(true);});it('hides persisted simulator tabs and selects a visible active fallback', () => {diff --git a/apps/desktop/src/renderer/features/right-sidebar/iosSimulatorPluginAvailability.ts b/apps/desktop/src/renderer/features/right-sidebar/iosSimulatorPluginAvailability.tsindex de51f49ca5..17965f77d0 100644--- a/apps/desktop/src/renderer/features/right-sidebar/iosSimulatorPluginAvailability.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/iosSimulatorPluginAvailability.ts@@ -10,7 +10,7 @@ import type { TabState } from './types';*/export function isIOSSimulatorPluginAvailable(ghosts: readonly InstalledGhost[]): boolean {return ghosts.some(- ({ enabled, manifest }) => enabled === true && manifest.slots.includes('ios-simulator'),+ ({ enabled, manifest }) => enabled === true && manifest.iosSimulator === true,);}diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/iosSimulatorFocusBridge.test.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/iosSimulatorFocusBridge.test.tsindex 6a3f2d02fd..2a8d3cb42a 100644--- a/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/iosSimulatorFocusBridge.test.ts+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/__tests__/iosSimulatorFocusBridge.test.ts@@ -13,7 +13,7 @@ let focusListener:null;let installedGhosts: Array<{enabled: boolean;- manifest: { id: string; slots: string[] };+ manifest: { id: string; iosSimulator?: true };}> = [];vi.mock('@/lib/secondaryWindow', () => ({ isSecondaryWindow: () => false }));@@ -45,7 +45,7 @@ describe('iOS Simulator focus bridge', () => {installedGhosts = [{enabled: true,- manifest: { id: 'ios-simulator', slots: ['ios-simulator'] },+ manifest: { id: 'ios-simulator', iosSimulator: true },},];focusListener = null;@@ -80,7 +80,7 @@ describe('iOS Simulator focus bridge', () => {installedGhosts = [{enabled: false,- manifest: { id: 'ios-simulator', slots: ['ios-simulator'] },+ manifest: { id: 'ios-simulator', iosSimulator: true },},];focusListener?.({ sessionId: 'session-a', instanceId: 'instance-a' });diff --git a/apps/desktop/src/renderer/hooks/__tests__/usePluginUpgradeNoticeToast.test.tsx b/apps/desktop/src/renderer/hooks/__tests__/usePluginUpgradeNoticeToast.test.tsxdeleted file mode 100644index 5d5df5206c..0000000000--- a/apps/desktop/src/renderer/hooks/__tests__/usePluginUpgradeNoticeToast.test.tsx+++ /dev/null@@ -1,115 +0,0 @@-// @vitest-environment jsdom--import { act, cleanup, renderHook, waitFor } from '@testing-library/react';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--const mocks = vi.hoisted(() => ({- listener: undefined as (() => void) | undefined,- secondary: false,- consume: vi.fn(),- subscribe: vi.fn(),- unsubscribe: vi.fn(),- toastInfo: vi.fn(),- translate: vi.fn((key: string) => key),- language: 'en',- warn: vi.fn(),-}));--vi.mock('@/i18n', () => ({ i18n: { t: mocks.translate, language: mocks.language } }));-vi.mock('@/lib/secondaryWindow', () => ({ isSecondaryWindow: () => mocks.secondary }));-vi.mock('@/lib/toast', () => ({ toast: { info: mocks.toastInfo } }));-vi.mock('@/lib/logger', () => ({ createLogger: () => ({ warn: mocks.warn }) }));--import { usePluginUpgradeNoticeToast } from '../usePluginUpgradeNoticeToast';--describe('usePluginUpgradeNoticeToast', () => {- beforeEach(() => {- vi.clearAllMocks();- mocks.listener = undefined;- mocks.secondary = false;- mocks.consume.mockResolvedValue(null);- mocks.subscribe.mockImplementation((listener: () => void) => {- mocks.listener = listener;- return mocks.unsubscribe;- });- (window as unknown as { electronAPI: { pluginMarket: unknown } }).electronAPI = {- pluginMarket: {- consumeUpgradeNotice: mocks.consume,- onUpgradeNoticeAvailable: mocks.subscribe,- },- };- });- afterEach(() => cleanup());-- it('single notice includes plugin name', async () => {- mocks.consume.mockResolvedValueOnce({- count: 1,- name: 'Team Plugin',- permissions: null,- hasPermissionExpansion: false,- });- renderHook(() => usePluginUpgradeNoticeToast());- await waitFor(() => expect(mocks.toastInfo).toHaveBeenCalledTimes(1));- expect(mocks.translate).toHaveBeenCalledWith('settings.ghosts.market.upgradeNotice.single', {- name: 'Team Plugin',- });- });-- it('multiple notice reports count and consumes push signals', async () => {- renderHook(() => usePluginUpgradeNoticeToast());- await waitFor(() => expect(mocks.consume).toHaveBeenCalledTimes(1));- mocks.consume.mockResolvedValueOnce({- count: 2,- name: null,- permissions: null,- hasPermissionExpansion: false,- });- act(() => mocks.listener?.());- await waitFor(() => expect(mocks.translate).toHaveBeenCalledWith(- 'settings.ghosts.market.upgradeNotice.multiple',- { count: 2 },- ));- });-- it('single expansion notice translates and names new permissions', async () => {- mocks.translate.mockImplementation((key: string, args?: Record<string, string>) =>- args ? `${key}:${JSON.stringify(args)}` : key,- );- mocks.consume.mockResolvedValueOnce({- count: 1,- name: 'Team Plugin',- permissions: [- { key: 'networkHost:api.example.com', labelKey: 'networkHost', labelArgs: { host: 'api.example.com' } },- { key: 'fs', labelKey: 'fsWrite' },- ],- hasPermissionExpansion: true,- });- renderHook(() => usePluginUpgradeNoticeToast());- await waitFor(() => expect(mocks.toastInfo).toHaveBeenCalledTimes(1));- expect(mocks.translate).toHaveBeenCalledWith('settings.ghosts.perm.networkHost', {- host: 'api.example.com',- });- expect(mocks.translate).toHaveBeenCalledWith(- 'settings.ghosts.market.upgradeNotice.singleWithPermissions',- expect.objectContaining({- name: 'Team Plugin',- permissions: expect.stringContaining(', '),- }),- );- });-- it('multiple expansion notice uses aggregated copy', async () => {- mocks.consume.mockResolvedValueOnce({- count: 2,- name: null,- permissions: null,- hasPermissionExpansion: true,- });- renderHook(() => usePluginUpgradeNoticeToast());- await waitFor(() => expect(mocks.toastInfo).toHaveBeenCalledTimes(1));- expect(mocks.translate).toHaveBeenCalledWith(- 'settings.ghosts.market.upgradeNotice.multipleWithPermissions',- { count: 2 },- );- });-});diff --git a/apps/desktop/src/renderer/hooks/usePluginUpgradeNoticeToast.ts b/apps/desktop/src/renderer/hooks/usePluginUpgradeNoticeToast.tsdeleted file mode 100644index b8fb8e5d28..0000000000--- a/apps/desktop/src/renderer/hooks/usePluginUpgradeNoticeToast.ts+++ /dev/null@@ -1,53 +0,0 @@-import { useEffect } from 'react';--import { i18n } from '@/i18n';-import { createLogger } from '@/lib/logger';-import { isSecondaryWindow } from '@/lib/secondaryWindow';-import { toast } from '@/lib/toast';--const log = createLogger('usePluginUpgradeNoticeToast');--export function usePluginUpgradeNoticeToast(): void {- useEffect(() => {- if (isSecondaryWindow()) return undefined;- let cancelled = false;- const showIfPending = async (): Promise<void> => {- try {- const notice = await window.electronAPI.pluginMarket.consumeUpgradeNotice();- if (cancelled || !notice) return;- const permissions = notice.permissions- ? new Intl.ListFormat(i18n.language, {- type: 'conjunction',- style: 'narrow',- }).format(notice.permissions.map((permission) =>- i18n.t(`settings.ghosts.perm.${permission.labelKey}`, permission.labelArgs),- ))- : undefined;- const message =- notice.count === 1 && notice.name- ? notice.hasPermissionExpansion && permissions- ? i18n.t('settings.ghosts.market.upgradeNotice.singleWithPermissions', {- name: notice.name,- permissions,- })- : i18n.t('settings.ghosts.market.upgradeNotice.single', { name: notice.name })- : notice.hasPermissionExpansion- ? i18n.t('settings.ghosts.market.upgradeNotice.multipleWithPermissions', {- count: notice.count,- })- : i18n.t('settings.ghosts.market.upgradeNotice.multiple', { count: notice.count });- toast.info(message, { duration: 8000 });- } catch (error) {- log.warn('failed to consume plugin upgrade notice:', error);- }- };- const unsubscribe = window.electronAPI.pluginMarket.onUpgradeNoticeAvailable(() => {- void showIfPending();- });- void showIfPending();- return () => {- cancelled = true;- unsubscribe();- };- }, []);-}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex ea36369272..03658134d6 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -4119,7 +4119,7 @@"updateTo": "Update to v{{version}}","updateAria": "Update {{name}} to v{{version}}","createWithCindy": "Create with Cindy",- "createPrompt": "I want to create a Cindy plugin. First call ghost_forge_guide to get the handbook's table of contents, read chapter 0 (design alignment) first, then read the relevant chapters via the section parameter (at minimum chapter 2 for the slot overview, plus the sandbox red-lines and packaging chapters) before writing any code; do not start implementing yet. Begin by asking questions: prefer option-based question cards, one key decision per card with your recommended choice marked, and proactively surface design options I may not know about — such as the UI form (docked panel, panel inside the Plugins page, chat card, or no UI), a $ command word, launch mode, background abilities (event listening, in-app toast notifications, unread badges, confirmation dialogs), network access, whether a settings page is needed, whether a bundled Node process should do heavy lifting, and whether image/video media abilities are needed. Step by step, confirm the problem to solve, target users, interaction flow, required tools and connections, permission boundaries, and acceptance criteria. After I confirm the design, implement and validate it according to the specification, then call ghost_forge_pack to package and install the plugin.",+ "createPrompt": "I want to create a Cindy plugin. First call ghost_forge_guide to get the handbook's table of contents, read chapter 0 (design alignment) first, then read the relevant chapters via the section parameter (at minimum the capability overview, sandbox red-lines, and packaging chapters) before writing any code; do not start implementing yet. Begin by asking questions: prefer option-based question cards, one key decision per card with your recommended choice marked, and proactively surface design options I may not know about — such as the UI form (docked panel, panel inside the Plugins page, chat card, or no UI), a $ command word, launch mode, background abilities (event listening, in-app toast notifications, unread badges, confirmation dialogs), network access, whether a settings page is needed, whether a bundled Node process should do heavy lifting, and whether image/video media abilities are needed. Step by step, confirm the problem to solve, target users, interaction flow, required tools and connections, permission boundaries, and acceptance criteria. After I confirm the design, implement and validate it according to the specification, then call ghost_forge_pack to validate and produce the .cindy package; do not claim that it was installed.","filterAll": "All","filtersAria": "Filter plugins by source","origin": {@@ -4163,14 +4163,6 @@"customSourcesUnavailable": "These custom marketplaces are temporarily unavailable: {{names}}. Other marketplaces are unaffected.","authenticationRequired": "Sign in to Cindy to view the plugin market.","notConfigured": "The plugin market is not configured for this environment. Installed plugins remain available.",- "upgradeNotice": {- "single": "Automatically updated organization plugin “{{name}}”.",- "multiple_one": "Automatically updated {{count}} organization plugin.",- "multiple_other": "Automatically updated {{count}} organization plugins.",- "singleWithPermissions": "Automatically updated organization plugin “{{name}}”; new permissions: {{permissions}}.",- "multipleWithPermissions_one": "Automatically updated {{count}} organization plugin; it includes new permissions.",- "multipleWithPermissions_other": "Automatically updated {{count}} organization plugins; some plugins include new permissions."- },"removalNotice": {"single": "The organization removed the plugin “{{name}}”. Its local copy and data on this device have been cleaned up.","multiple_one": "The organization removed {{count}} plugin. Its local copy and data on this device have been cleaned up.",@@ -4191,10 +4183,6 @@"securityDescription": "Cindy verifies package size and SHA-256 in the main process, validates the plugin manifest, then installs atomically. First-time installs are enabled automatically and can be disabled anytime on the Plugins page; updates keep the current enabled state.","customSecurityDescription": "This plugin comes from a custom marketplace you added and has not been verified by the Cindy server. Its manifest is validated in the main process before install. First-time installs are enabled automatically and can be disabled anytime on the Plugins page.","noPermissions": "This plugin declares no additional capabilities.",- "installConfirmTitle": "Install “{{name}}”?",- "installConfirmDescription": "The package will be verified for integrity and manifest compatibility. The plugin is enabled automatically after install; you can disable it or adjust its setup anytime.",- "customInstallConfirmDescription": "This plugin comes from a custom marketplace and has not been verified for integrity by the server; its manifest will be validated before install. The plugin is enabled automatically after install; you can disable it or adjust its setup anytime.",- "updateConfirmDescription": "The package will be verified for integrity and manifest compatibility, then replace the installed version. Its current enabled state stays unchanged.","sources": {"addMarketplace": "Add Plugin Marketplace…","dialogTitle": "Add Plugin Marketplace",@@ -4252,7 +4240,7 @@"authTitle": "Private Repositories","authBody": "Authentication relies entirely on your system Git configuration — Cindy never stores Git credentials. SSH: a working key must be configured on this machine; if the organization enforces SAML SSO, authorize the key for that organization via Configure SSO in your GitHub SSH key settings. HTTPS: use a Personal Access Token stored by the system credential helper.","rulesTitle": "Install Rules",- "rulesBody": "Plugin ids are globally unique, first come first served — conflicts with installed plugins are called out explicitly. Plugins using the officially reserved prefixes {{reservedGhostIdPrefixes}} cannot be installed by dragging in a package, choosing a file, transferring from ghost_forge_pack, or using a custom plugin marketplace. Before install, every permission the plugin declares is shown for review; confirming completes the install and enables the plugin.",+ "rulesBody": "Plugin ids are globally unique, first come first served — conflicts with installed plugins are called out explicitly. Plugins whose ids use the official reserved prefixes ({{reservedGhostIdPrefixes}}) cannot be installed by dragging in a package, choosing a file, or using a custom plugin marketplace. Declared permissions are shown on the detail page; clicking Install completes installation and enables the plugin without another permission confirmation dialog.","copy": "Copy guide","copied": "Guide copied to clipboard.","copyFailed": "Copy failed. Please try again."@@ -4263,13 +4251,13 @@"conflictDescription": "This plugin identifier is already in use and cannot be installed right now"},"reapproval": {- "badge": "Permission review needed",- "action": "Review Permissions",- "actionAria": "Review permissions for plugin {{name}}",- "noticeTitle": "Permission review needed",- "bodyLegacy": "Cindy has no record of a permission review for this plugin, so it stays disabled. Choose Review Permissions to go through what it asks for and confirm it again.",- "bodyInvalid": "The permission review record for this plugin is damaged, so it stays disabled. Choose Review Permissions to go through what it asks for and confirm it again.",- "bodyBuiltinRestart": "Something went wrong with this built-in plugin's approval record. Restart Cindy to recover automatically — no other action needed."+ "badge": "Installation recovery needed",+ "action": "Reinstall",+ "actionAria": "Reinstall plugin {{name}}",+ "noticeTitle": "Installation recovery needed",+ "bodyLegacy": "Cindy cannot verify this plugin's complete installation record, so the plugin is paused. Reinstall the marketplace release or select the matching .cindy package again.",+ "bodyInvalid": "This plugin's installation verification record is damaged, so the plugin is paused. Reinstall the marketplace release or select the matching .cindy package again.",+ "bodyBuiltinRestart": "Something went wrong with this built-in plugin's installation verification record. Restart Cindy to recover automatically — no other action is needed."},"install": "Install Plugin…","empty": "No plugins installed yet",@@ -4338,26 +4326,11 @@},"installConfirm": {"title": "Install plugin “{{name}}”?",- "confirm": "Install plugin",- "cancel": "Cancel","meta": "Version {{version}}. Installs locally and can be uninstalled anytime.","metaWithAuthor": "By {{author}} · Version {{version}}. Installs locally and can be uninstalled anytime.","manualCount": "Bundled manuals: {{count}}","expandDescription": "Show Full Description",- "collapseDescription": "Hide Full Description",- "typedIdLabel": "Type the plugin id \"{{id}}\" to confirm installation",- "agentBanner": {- "title": "An Agent started this install — you didn't click it.",- "context": "It packaged the plugin source under {{path}} while working on the task \"{{title}}\".",- "contextNoPath": "It packaged a plugin source directory while working on the task \"{{title}}\".",- "contextNoTitle": "It packaged the plugin source under {{path}}.",- "contextBare": "It packaged a plugin source directory.",- "advice": "If you didn't ask it to make a plugin in this task, cancel — and look back at what external content this task just read.",- "firstInstall": "This plugin id has never been installed before.",- "hazardSkill": "It ships skill instructions the AI runs with all your permissions, outside the plugin sandbox, across all your projects.",- "hazardNode": "It can run programs on your computer, outside the browser sandbox.",- "hazardCredential": "It will send the credentials you enter on its settings page to {{hosts}}."- }+ "collapseDescription": "Hide Full Description"},"trust": {"official": "Official Cindy plugin",@@ -4480,13 +4453,11 @@},"errors": {"fileInvalid": "Not a valid .cindy plugin file",- "hostUnsupported": "This plugin needs Cindy capabilities that this version does not provide. Update Cindy, then install it again.",+ "hostUnsupported": "This Cindy version cannot read this plugin's manifest format.","alreadyInstalled": "This plugin is already installed",- "approvalRequired": "This plugin's permissions must be reviewed again before continuing.","commandConflict": "Its command conflicts with an installed plugin. Uninstall the other one or rename the command.",- "idReserved": "{{reservedGhostIdPrefixes}} are reserved for official plugins and can’t be installed by dragging in a package, choosing a file, transferring from ghost_forge_pack, or using a custom plugin marketplace. Install the corresponding official plugin from the Cindy plugin market",- "brokerManualInstallNotAuthorized": "A manually installed .cindy package is not authorized to use the authorization broker. Install it from your organization’s plugin market, or ask the author to build it with ghost_forge_pack while signed in to the organization.",- "brokerNotAuthorized": "This installation source or organization identity is not authorized to use the authorization broker. Install it from your organization’s plugin market, or ask the author to build it with ghost_forge_pack while signed in to the organization.",+ "idReserved": "{{reservedGhostIdPrefixes}} are reserved for official plugins and can’t be installed by dragging in a package, choosing a file, or using a custom plugin marketplace. Install the corresponding official plugin from the Cindy plugin market",+ "brokerManualInstallNotAuthorized": "A locally installed .cindy package is not authorized to use the authorization broker. Install it from your organization’s plugin market.","brokerRedirectPortRequired": "This plugin declares an authorization broker but does not declare redirectPort in the same OAuth configuration. Ask the author to add the field so the final authorization hop can return to the local listening port.","sourceMissing": "The selected file could not be found","generic": "Operation failed. Please try again.",@@ -4653,13 +4624,6 @@"confirm": "Update","cancel": "Cancel"},- "reapproveConfirm": {- "title": "Re-approve permissions for \"{{name}}\"?",- "body": "Review the permissions below to re-approve this installed plugin — no install file needed.",- "confirm": "Approve & Restore",- "enableNoticeEnabled": "Keeps its current enabled state after you confirm.",- "enableNoticeAsleep": "Stays asleep after you confirm (not enabled automatically); you can enable it here later."- },"pick": {"dialogTitle": "Choose a folder","dialogMessage": "Plugin “{{name}}” is asking you to choose a folder"@@ -4677,7 +4641,7 @@"updateAll": {"title": "Update all · {{count}} plugins","collapseDiff": "Collapse",- "description": "Regular updates finish automatically; verified packages that request new permissions need per-item approval.",+ "description": "Updates normally run silently. Use this dialog to retry updates that were skipped or failed.","versionRange": "v{{from}} → v{{to}}","statusPending": "Queued","statusInstalling": "Updating…",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 587e0da2d0..6c023641f3 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -4118,7 +4118,7 @@"updateTo": "v{{version}} に更新","updateAria": "{{name}} を v{{version}} に更新","createWithCindy": "Cindy で作成",- "createPrompt": "Cindy プラグインを作成したいです。まず ghost_forge_guide を呼び出してハンドブックの目次を取得し、最初に第 0 章「設計のすり合わせ」を読み、その後 section パラメータで関連する章(少なくともスロット一覧を含む第 2 章、サンドボックスの禁止事項、パッケージ化の 3 章)を読み込んでから着手してください。すぐに実装を始めないでください。質問から始めてください:選択肢付きの質問カードを優先し、1 枚のカードでは 1 つの重要な判断に絞り、あなたのおすすめを明示した上で、私が気づきにくい設計オプション(UI 形態:ドッキングパネル / プラグインページ内のパネル / チャットカード / UI なし、$ 呼び出しコマンド、起動モード、バックグラウンド能力:イベント傍受・アプリ内トースト通知・未読バッジ・確認ダイアログ、ネットワーク接続の要否、設定ページの要否、Node プロセス同梱での重い処理の要否、画像・動画などのメディア能力の要否など)を積極的に提示して選ばせてください。解決する課題、対象ユーザー、操作フロー、必要なツールと接続、権限の境界、受け入れ条件を段階的に確認してください。設計を確認した後、仕様に沿って実装と検証を行い、最後に ghost_forge_pack を呼び出してプラグインをパッケージ化し、インストールしてください。",+ "createPrompt": "Cindy プラグインを作成したいです。まず ghost_forge_guide を呼び出してハンドブックの目次を取得し、最初に第 0 章「設計のすり合わせ」を読み、その後 section パラメータで関連する章(少なくともサンドボックスの禁止事項とパッケージ化の章)を読み込んでから着手してください。すぐに実装を始めないでください。質問から始めてください:選択肢付きの質問カードを優先し、1 枚のカードでは 1 つの重要な判断に絞り、あなたのおすすめを明示した上で、私が気づきにくい設計オプション(UI 形態:ドッキングパネル / プラグインページ内のパネル / チャットカード / UI なし、$ 呼び出しコマンド、起動モード、ネットワーク接続の要否、設定ページの要否など)を積極的に提示して選ばせてください。解決する課題、対象ユーザー、操作フロー、必要なツールと接続、権限の境界、受け入れ条件を段階的に確認してください。設計を確認した後、仕様に沿って実装と検証を行い、最後に ghost_forge_pack を呼び出して .cindy パッケージを検証・生成し、インストール済みとは説明しないでください。","filterAll": "すべて","filtersAria": "提供元でプラグインを絞り込む","origin": {@@ -4162,14 +4162,6 @@"customSourcesUnavailable": "次のカスタムマーケットは一時的に利用できません:{{names}}。他のマーケットには影響しません。","authenticationRequired": "プラグインマーケットを表示するには Cindy にログインしてください。","notConfigured": "この環境ではプラグインマーケットが設定されていません。インストール済みプラグインは引き続き利用できます。",- "upgradeNotice": {- "single": "組織のプラグイン「{{name}}」を自動更新しました。",- "multiple_one": "組織の {{count}} 個のプラグインを自動更新しました。",- "multiple_other": "組織の {{count}} 個のプラグインを自動更新しました。",- "singleWithPermissions": "組織のプラグイン「{{name}}」を自動更新しました。新しい権限:{{permissions}}",- "multipleWithPermissions_one": "組織の {{count}} 個のプラグインを自動更新しました。新しい権限が追加されました。",- "multipleWithPermissions_other": "組織の {{count}} 個のプラグインを自動更新しました。新しい権限が追加されたプラグインがあります。"- },"removalNotice": {"single": "プラグイン「{{name}}」は組織によって削除され、このデバイス上のローカルコピーとデータはクリーンアップされました。","multiple_one": "{{count}} 件のプラグインが組織によって削除され、このデバイス上のローカルコピーとデータはクリーンアップされました。",@@ -4190,10 +4182,6 @@"securityDescription": "メインプロセスでサイズと SHA-256、プラグインマニフェストを検証してからアトミックにインストールします。初回インストール後は自動的に有効になり、プラグインページからいつでも無効化できます。更新では現在の有効/無効の状態が維持されます。","customSecurityDescription": "このプラグインは追加したカスタムマーケット由来で、Cindy サーバーによる整合性検証は行われていません。インストール前にメインプロセスでマニフェストを検証します。初回インストール後は自動で有効になり、プラグインページでいつでも無効化できます。","noPermissions": "このプラグインは追加機能を宣言していません。",- "installConfirmTitle": "「{{name}}」をインストールしますか?",- "installConfirmDescription": "パッケージの整合性とマニフェスト互換性を確認してからインストールします。インストール完了後は自動的に有効になり、いつでも無効化や設定の変更ができます。",- "customInstallConfirmDescription": "カスタムマーケット由来のプラグインのため、サーバーによる整合性検証は行われません。インストール前にマニフェストを検証します。インストール後は自動で有効になり、プラグインページでいつでも無効化・設定変更ができます。",- "updateConfirmDescription": "パッケージの整合性とマニフェスト互換性を確認してから、既存のバージョンを置き換えます。現在の有効/無効の状態は変わりません。","sources": {"addMarketplace": "プラグインマーケットを追加…","dialogTitle": "プラグインマーケットを追加",@@ -4251,7 +4239,7 @@"authTitle": "プライベートリポジトリ","authBody": "認証はすべてシステムの Git 設定に依存し、Cindy は Git の認証情報を一切保存しません。SSH の場合: 利用可能な key がマシンに設定されている必要があります。組織が SAML SSO を強制している場合は、GitHub の SSH key 設定で Configure SSO からその組織に key を承認してください。HTTPS の場合: Personal Access Token を使用し、システムの credential helper に保存します。","rulesTitle": "インストールルール",- "rulesBody": "プラグイン id はグローバルに一意で先着順です。インストール済みプラグインとの競合は明示されます。公式予約プレフィックス {{reservedGhostIdPrefixes}} を使うプラグインは、ドラッグ、ファイル選択、ghost_forge_pack からの受け渡し、カスタムプラグインマーケットからはインストールできません。インストール前にプラグインが宣言する権限をすべて表示し、確認するとインストールが完了して自動的に有効になります。",+ "rulesBody": "プラグイン id はグローバルに一意で先着順です。インストール済みプラグインとの競合は明示されます。id に公式予約プレフィックス({{reservedGhostIdPrefixes}})を使うプラグインは、ドラッグ、ファイル選択、カスタムプラグインマーケットからインストールできません。宣言された権限は詳細ページに表示されます。インストールをクリックすると、追加の権限確認ダイアログなしでインストールが完了し、自動的に有効になります。","copy": "ガイドをコピー","copied": "ガイドをクリップボードにコピーしました。","copyFailed": "コピーに失敗しました。もう一度お試しください。"@@ -4262,13 +4250,13 @@"conflictDescription": "このプラグイン識別子は既に使用されており、現在インストールできません"},"reapproval": {- "badge": "権限の再確認が必要",- "action": "権限を再確認",- "actionAria": "プラグイン「{{name}}」の権限を再確認",- "noticeTitle": "権限の再確認が必要",- "bodyLegacy": "このプラグインの権限確認の記録が Cindy にないため、無効のままにしています。「権限を再確認」から要求される権限を確認し、あらためて許可してください。",- "bodyInvalid": "このプラグインの権限確認の記録が壊れているため、無効のままにしています。「権限を再確認」から要求される権限を確認し、あらためて許可してください。",- "bodyBuiltinRestart": "この内蔵プラグインの承認記録に問題が発生しました。Cindy を再起動すると自動的に復元されます。他の操作は不要です。"+ "badge": "インストールの復旧が必要",+ "action": "再インストール",+ "actionAria": "プラグイン「{{name}}」を再インストール",+ "noticeTitle": "インストールの復旧が必要",+ "bodyLegacy": "このプラグインの完全なインストール記録を Cindy が検証できないため、実行を停止しています。元のマーケット版を再インストールするか、対応する .cindy パッケージをもう一度選択してください。",+ "bodyInvalid": "このプラグインのインストール検証記録が破損しているため、実行を停止しています。元のマーケット版を再インストールするか、対応する .cindy パッケージをもう一度選択してください。",+ "bodyBuiltinRestart": "この内蔵プラグインのインストール検証記録に問題が発生しました。Cindy を再起動すると自動的に復旧します。他の操作は不要です。"},"install": "プラグインをインストール…","empty": "まだプラグインがインストールされていません",@@ -4337,26 +4325,11 @@},"installConfirm": {"title": "プラグイン「{{name}}」をインストールしますか?",- "confirm": "プラグインをインストール",- "cancel": "キャンセル","meta": "バージョン {{version}}。ローカルにインストールされ、いつでもアンインストールできます。","metaWithAuthor": "作者 {{author}} · バージョン {{version}}。ローカルにインストールされ、いつでもアンインストールできます。","manualCount": "同梱マニュアル {{count}} 件","expandDescription": "紹介全文を表示",- "collapseDescription": "紹介を折りたたむ",- "typedIdLabel": "プラグイン id「{{id}}」を入力してインストールを確認",- "agentBanner": {- "title": "このインストールは Agent が開始しました。あなたが押したものではありません。",- "context": "タスク「{{title}}」の作業中に、{{path}} 配下のプラグインソースをパッケージしました。",- "contextNoPath": "タスク「{{title}}」の作業中に、プラグインのソースディレクトリをパッケージしました。",- "contextNoTitle": "{{path}} 配下のプラグインソースをパッケージしました。",- "contextBare": "プラグインのソースディレクトリをパッケージしました。",- "advice": "このタスクでプラグイン作成を頼んでいないなら、キャンセルしてください —— そのうえで、このタスクが直前に読み込んだ外部コンテンツを見直してください。",- "firstInstall": "このプラグイン id はこれまで一度もインストールされていません。",- "hazardSkill": "スキル指示を含みます。AI はそれをあなたの全権限で実行し、プラグインのサンドボックス外で、すべてのプロジェクトに対して有効になります。",- "hazardNode": "ブラウザのサンドボックス外で、あなたのコンピュータ上でプログラムを実行できます。",- "hazardCredential": "設定ページで入力した認証情報を {{hosts}} に送信します。"- }+ "collapseDescription": "紹介を折りたたむ"},"trust": {"official": "Cindy 公式プラグイン",@@ -4479,13 +4452,11 @@},"errors": {"fileInvalid": "有効な .cindy プラグインファイルではありません",- "hostUnsupported": "このプラグインには、現在のバージョンでは提供されていない Cindy の機能が必要です。Cindy を更新してから、もう一度インストールしてください。",+ "hostUnsupported": "この Cindy バージョンでは、プラグインのマニフェスト形式を読み取れません。","alreadyInstalled": "このプラグインは既にインストールされています",- "approvalRequired": "続けるには、このプラグインの権限を再確認する必要があります","commandConflict": "コマンドがインストール済みのプラグインと重複しています。先に相手をアンインストールするか、コマンド名を変更してください。",- "idReserved": "{{reservedGhostIdPrefixes}} は公式プラグイン用の予約済みプレフィックスです。ドラッグ、ファイル選択、ghost_forge_pack からの受け渡し、カスタムプラグインマーケットからはインストールできません。対応する公式プラグインは Cindy プラグインマーケットからインストールしてください",- "brokerManualInstallNotAuthorized": "手動でインストールした .cindy は認可 broker を使用できません。組織のプラグインマーケットからインストールするか、作者に組織アカウントで ghost_forge_pack を使ってビルドするよう依頼してください。",- "brokerNotAuthorized": "現在のインストール元または組織アカウントには、認可 broker を使用する権限がありません。組織のプラグインマーケットからインストールするか、作者に組織アカウントで ghost_forge_pack を使ってビルドするよう依頼してください。",+ "idReserved": "{{reservedGhostIdPrefixes}} は公式プラグイン用の予約済みプレフィックスです。ドラッグ、ファイル選択、カスタムプラグインマーケットからはインストールできません。対応する公式プラグインは Cindy プラグインマーケットからインストールしてください",+ "brokerManualInstallNotAuthorized": "ローカルでインストールした .cindy は認可 broker を使用できません。組織のプラグインマーケットからインストールしてください。","brokerRedirectPortRequired": "このプラグインは認可 broker を宣言していますが、同じ OAuth 設定に redirectPort がありません。認可の最後の転送先をローカルの待受ポートに戻せるよう、作者にこのフィールドの追加を依頼してください。","sourceMissing": "選択したファイルが見つかりません","generic": "操作に失敗しました。もう一度お試しください",@@ -4652,13 +4623,6 @@"confirm": "更新","cancel": "キャンセル"},- "reapproveConfirm": {- "title": "「{{name}}」の権限を再確認しますか?",- "body": "以下の権限を確認して、このインストール済みプラグインをあらためて許可します。インストールファイルは不要です。",- "confirm": "確認して復元",- "enableNoticeEnabled": "確認後も現在の有効状態を維持します。",- "enableNoticeAsleep": "確認後もスリープ状態のままにします(自動では有効化しません)。あとでここから手動で有効化できます。"- },"pick": {"dialogTitle": "フォルダを選択","dialogMessage": "プラグイン「{{name}}」がフォルダの選択を求めています"@@ -4676,7 +4640,7 @@"updateAll": {"title": "すべて更新 · {{count}} 件","collapseDiff": "折りたたむ",- "description": "通常の更新は自動で完了し、検証済みの実パッケージが新しい権限を要求する場合のみ個別に確認します。",+ "description": "更新は通常サイレントに実行されます。この画面では、スキップまたは失敗した更新を再試行できます。","versionRange": "v{{from}} → v{{to}}","statusPending": "待機中","statusInstalling": "更新中…",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 04bdc004ef..8a5238a5fc 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -4118,7 +4118,7 @@"updateTo": "v{{version}}(으)로 업데이트","updateAria": "{{name}}을(를) v{{version}}(으)로 업데이트","createWithCindy": "Cindy로 만들기",- "createPrompt": "Cindy 플러그인을 만들고 싶습니다. 먼저 ghost_forge_guide를 호출해 핸드북 목차를 받고, 우선 0장 「설계 맞추기」를 읽은 뒤 section 매개변수로 관련 장(최소한 슬롯 총람이 담긴 2장, 샌드박스 금지선, 패키징 세 장)을 읽고 나서 작업을 시작하세요. 바로 구현을 시작하지 마세요. 질문부터 시작하세요: 선택지가 있는 질문 카드를 우선 사용하고, 카드 한 장에는 핵심 결정 하나만 담아 추천안을 표시하며, 제가 모를 수 있는 설계 옵션(UI 형태: 도킹 패널 / 플러그인 페이지 내 패널 / 채팅 카드 / UI 없음, $ 호출 명령어, 시작 모드, 백그라운드 능력: 이벤트 수신 · 앱 내 토스트 알림 · 읽지 않음 배지 · 확인 대화상자, 네트워크 사용 여부, 설정 페이지 필요 여부, Node 프로세스 동반 여부, 이미지·동영상 등 미디어 능력 필요 여부 등)을 먼저 보여 주고 고르게 해 주세요. 해결할 문제, 대상 사용자, 상호작용 흐름, 필요한 도구와 연결, 권한 경계, 완료 기준을 단계적으로 확인해 주세요. 설계를 확인한 뒤 규격에 따라 구현하고 검증한 다음, 마지막으로 ghost_forge_pack을 호출해 플러그인을 패키징하고 설치해 주세요.",+ "createPrompt": "Cindy 플러그인을 만들고 싶습니다. 먼저 ghost_forge_guide를 호출해 핸드북 목차를 받고, 우선 0장 「설계 맞추기」를 읽은 뒤 section 매개변수로 관련 장(최소한 샌드박스 금지선과 패키징 장)을 읽고 나서 작업을 시작하세요. 바로 구현을 시작하지 마세요. 질문부터 시작하세요: 선택지가 있는 질문 카드를 우선 사용하고, 카드 한 장에는 핵심 결정 하나만 담아 추천안을 표시하며, 제가 모를 수 있는 설계 옵션(UI 형태: 도킹 패널 / 플러그인 페이지 내 패널 / 채팅 카드 / UI 없음, $ 호출 명령어, 시작 모드, 네트워크 사용 여부, 설정 페이지 필요 여부 등)을 먼저 보여 주고 고르게 해 주세요. 해결할 문제, 대상 사용자, 상호작용 흐름, 필요한 도구와 연결, 권한 경계, 완료 기준을 단계적으로 확인해 주세요. 설계를 확인한 뒤 규격에 따라 구현하고 검증한 다음, 마지막으로 ghost_forge_pack을 호출해 .cindy 패키지를 검증하고 생성하며, 설치된 것으로 안내하지 마세요.","filterAll": "전체","filtersAria": "출처별 플러그인 필터","origin": {@@ -4162,14 +4162,6 @@"customSourcesUnavailable": "다음 사용자 지정 마켓을 일시적으로 사용할 수 없습니다: {{names}}. 다른 마켓에는 영향을 주지 않습니다.","authenticationRequired": "플러그인 마켓을 보려면 Cindy에 로그인하세요.","notConfigured": "이 환경에는 플러그인 마켓이 구성되지 않았습니다. 설치된 플러그인은 계속 사용할 수 있습니다.",- "upgradeNotice": {- "single": "조직 플러그인 ‘{{name}}’을(를) 자동으로 업데이트했습니다.",- "multiple_one": "조직 플러그인 {{count}}개를 자동으로 업데이트했습니다.",- "multiple_other": "조직 플러그인 {{count}}개를 자동으로 업데이트했습니다.",- "singleWithPermissions": "조직 플러그인 ‘{{name}}’을(를) 자동으로 업데이트했습니다. 새 권한: {{permissions}}",- "multipleWithPermissions_one": "조직 플러그인 {{count}}개를 자동으로 업데이트했습니다. 새 권한이 추가되었습니다.",- "multipleWithPermissions_other": "조직 플러그인 {{count}}개를 자동으로 업데이트했습니다. 일부 플러그인에 새 권한이 추가되었습니다."- },"removalNotice": {"single": "플러그인 “{{name}}”: 조직에서 제거했으며 이 기기의 로컬 사본과 데이터도 정리했습니다.","multiple_one": "{{count}}개의 플러그인이 조직에서 제거되었습니다. 이 기기의 로컬 사본과 데이터가 정리되었습니다.",@@ -4190,10 +4182,6 @@"securityDescription": "메인 프로세스에서 크기와 SHA-256 및 플러그인 매니페스트를 검증한 뒤 원자적으로 설치합니다. 최초 설치 후 자동으로 활성화되며 플러그인 페이지에서 언제든지 비활성화할 수 있습니다. 업데이트 시 현재 활성화 상태가 유지됩니다.","customSecurityDescription": "이 플러그인은 추가한 사용자 지정 마켓에서 제공되며 Cindy 서버의 무결성 검증을 거치지 않았습니다. 설치 전에 메인 프로세스에서 매니페스트를 검증합니다. 처음 설치하면 자동으로 활성화되며 플러그인 페이지에서 언제든 비활성화할 수 있습니다.","noPermissions": "이 플러그인은 추가 기능을 선언하지 않았습니다.",- "installConfirmTitle": "‘{{name}}’을(를) 설치할까요?",- "installConfirmDescription": "패키지 무결성과 매니페스트 호환성을 확인한 뒤 설치합니다. 설치가 완료되면 자동으로 활성화되며, 언제든지 비활성화하거나 설정을 변경할 수 있습니다.",- "customInstallConfirmDescription": "사용자 지정 마켓의 플러그인으로 서버 무결성 검증을 거치지 않았으며, 설치 전에 매니페스트를 검증합니다. 설치 후 플러그인이 자동으로 활성화되며 언제든 비활성화하거나 설정을 변경할 수 있습니다.",- "updateConfirmDescription": "패키지 무결성과 매니페스트 호환성을 확인한 뒤 기존 버전을 교체합니다. 현재 활성화 상태는 그대로 유지됩니다.","sources": {"addMarketplace": "플러그인 마켓 추가…","dialogTitle": "플러그인 마켓 추가",@@ -4251,7 +4239,7 @@"authTitle": "비공개 리포지토리","authBody": "인증은 전적으로 시스템 Git 구성에 의존하며 Cindy는 Git 자격 증명을 저장하지 않습니다. SSH: 이 머신에 사용 가능한 key가 구성되어 있어야 합니다. 조직이 SAML SSO를 강제하는 경우 GitHub SSH key 설정에서 Configure SSO로 해당 조직에 key를 승인해야 합니다. HTTPS: Personal Access Token을 사용하고 시스템 credential helper에 저장합니다.","rulesTitle": "설치 규칙",- "rulesBody": "플러그인 id는 전역적으로 고유하며 선착순입니다. 설치된 플러그인과의 충돌은 명확히 표시됩니다. 공식 예약 접두사 {{reservedGhostIdPrefixes}}를 사용하는 플러그인은 끌어다 놓기, 파일 선택, ghost_forge_pack 전달 또는 사용자 지정 플러그인 마켓으로는 설치할 수 없습니다. 설치 전에 플러그인이 선언한 권한을 모두 보여주며, 확인하면 설치가 완료되고 자동으로 활성화됩니다.",+ "rulesBody": "플러그인 id는 전역적으로 고유하며 선착순입니다. 설치된 플러그인과의 충돌은 명확히 표시됩니다. id에 공식 예약 접두사({{reservedGhostIdPrefixes}})를 사용하는 플러그인은 끌어다 놓기, 파일 선택 또는 사용자 지정 플러그인 마켓으로 설치할 수 없습니다. 선언된 권한은 상세 페이지에 표시됩니다. 설치를 클릭하면 별도의 권한 확인 대화상자 없이 설치가 완료되고 자동으로 활성화됩니다.","copy": "가이드 복사","copied": "가이드를 클립보드에 복사했습니다.","copyFailed": "복사에 실패했습니다. 다시 시도하세요."@@ -4262,13 +4250,13 @@"conflictDescription": "이 플러그인 식별자는 이미 사용 중이므로 현재 설치할 수 없습니다"},"reapproval": {- "badge": "권한 재확인 필요",- "action": "권한 다시 확인",- "actionAria": "플러그인 {{name}}의 권한 다시 확인",- "noticeTitle": "권한 재확인 필요",- "bodyLegacy": "Cindy에 이 플러그인의 권한 확인 기록이 없어 사용 중지한 상태입니다. [권한 다시 확인]에서 요청하는 권한을 확인하고 다시 허용해 주세요.",- "bodyInvalid": "이 플러그인의 권한 확인 기록이 손상되어 사용 중지한 상태입니다. [권한 다시 확인]에서 요청하는 권한을 확인하고 다시 허용해 주세요.",- "bodyBuiltinRestart": "이 내장 플러그인의 승인 기록에 문제가 발생했습니다. Cindy를 다시 시작하면 자동으로 복구되며, 다른 조치는 필요하지 않습니다."+ "badge": "설치 복구 필요",+ "action": "다시 설치",+ "actionAria": "플러그인 {{name}} 다시 설치",+ "noticeTitle": "설치 복구 필요",+ "bodyLegacy": "Cindy가 이 플러그인의 전체 설치 기록을 확인할 수 없어 실행을 중지했습니다. 원래 마켓 버전을 다시 설치하거나 해당 .cindy 패키지를 다시 선택해 주세요.",+ "bodyInvalid": "이 플러그인의 설치 확인 기록이 손상되어 실행을 중지했습니다. 원래 마켓 버전을 다시 설치하거나 해당 .cindy 패키지를 다시 선택해 주세요.",+ "bodyBuiltinRestart": "이 내장 플러그인의 설치 확인 기록에 문제가 발생했습니다. Cindy를 다시 시작하면 자동으로 복구되며 다른 조치는 필요하지 않습니다."},"install": "플러그인 설치…","empty": "아직 설치된 플러그인이 없습니다",@@ -4337,26 +4325,11 @@},"installConfirm": {"title": "플러그인 \"{{name}}\"을(를) 설치할까요?",- "confirm": "플러그인 설치",- "cancel": "취소","meta": "버전 {{version}}. 로컬에 설치되며 언제든 제거할 수 있습니다.","metaWithAuthor": "제작자 {{author}} · 버전 {{version}}. 로컬에 설치되며 언제든 제거할 수 있습니다.","manualCount": "번들 매뉴얼 {{count}}개","expandDescription": "전체 소개 보기",- "collapseDescription": "소개 접기",- "typedIdLabel": "플러그인 id \"{{id}}\"을(를) 입력하여 설치를 확인하세요",- "agentBanner": {- "title": "이 설치는 Agent가 시작한 것입니다 — 당신이 누른 것이 아닙니다.",- "context": "작업 \"{{title}}\"을(를) 진행하던 중 {{path}} 아래의 플러그인 소스를 패키징했습니다.",- "contextNoPath": "작업 \"{{title}}\"을(를) 진행하던 중 플러그인 소스 디렉터리를 패키징했습니다.",- "contextNoTitle": "{{path}} 아래의 플러그인 소스를 패키징했습니다.",- "contextBare": "플러그인 소스 디렉터리를 패키징했습니다.",- "advice": "이 작업에서 플러그인 제작을 요청하지 않았다면 취소하세요 —— 그리고 이 작업이 방금 읽은 외부 콘텐츠를 다시 살펴보세요.",- "firstInstall": "이 플러그인 id는 이전에 설치된 적이 없습니다.",- "hazardSkill": "스킬 지시가 포함되어 있습니다. AI는 이를 당신의 모든 권한으로, 플러그인 샌드박스 밖에서, 모든 프로젝트에 대해 실행합니다.",- "hazardNode": "브라우저 샌드박스 밖에서 당신의 컴퓨터에서 프로그램을 실행할 수 있습니다.",- "hazardCredential": "설정 페이지에 입력한 자격 증명을 {{hosts}}(으)로 보냅니다."- }+ "collapseDescription": "소개 접기"},"trust": {"official": "Cindy 공식 플러그인",@@ -4479,13 +4452,11 @@},"errors": {"fileInvalid": "유효한 .cindy 플러그인 파일이 아닙니다",- "hostUnsupported": "이 플러그인에는 현재 버전에서 제공하지 않는 Cindy 기능이 필요합니다. Cindy를 업데이트한 후 다시 설치하세요.",+ "hostUnsupported": "이 Cindy 버전에서는 플러그인의 매니페스트 형식을 읽을 수 없습니다.","alreadyInstalled": "이 플러그인은 이미 설치되어 있습니다",- "approvalRequired": "계속하려면 이 플러그인의 권한을 다시 확인해야 합니다","commandConflict": "명령어가 설치된 플러그인과 충돌합니다. 먼저 상대를 제거하거나 명령어 이름을 변경하세요.",- "idReserved": "{{reservedGhostIdPrefixes}}는 공식 플러그인용 예약 접두사입니다. 끌어다 놓기, 파일 선택, ghost_forge_pack 전달 또는 사용자 지정 플러그인 마켓으로는 설치할 수 없습니다. 해당 공식 플러그인은 Cindy 플러그인 마켓에서 설치하세요",- "brokerManualInstallNotAuthorized": "수동으로 설치한 .cindy는 인증 broker를 사용할 수 없습니다. 조직 플러그인 마켓에서 설치하거나, 작성자에게 조직 계정으로 ghost_forge_pack을 사용해 빌드하도록 요청하세요.",- "brokerNotAuthorized": "현재 설치 출처 또는 조직 계정에는 인증 broker 사용 권한이 없습니다. 조직 플러그인 마켓에서 설치하거나, 작성자에게 조직 계정으로 ghost_forge_pack을 사용해 빌드하도록 요청하세요.",+ "idReserved": "{{reservedGhostIdPrefixes}}는 공식 플러그인용 예약 접두사입니다. 끌어다 놓기, 파일 선택 또는 사용자 지정 플러그인 마켓으로는 설치할 수 없습니다. 해당 공식 플러그인은 Cindy 플러그인 마켓에서 설치하세요",+ "brokerManualInstallNotAuthorized": "로컬로 설치한 .cindy는 인증 broker를 사용할 수 없습니다. 조직 플러그인 마켓에서 설치하세요.","brokerRedirectPortRequired": "이 플러그인은 인증 broker를 선언했지만 같은 OAuth 설정에 redirectPort를 선언하지 않았습니다. 인증의 마지막 단계가 로컬 수신 포트로 돌아올 수 있도록 작성자에게 이 필드를 추가해 달라고 요청하세요.","sourceMissing": "선택한 파일을 찾을 수 없습니다","generic": "작업에 실패했습니다. 다시 시도해 주세요",@@ -4652,13 +4623,6 @@"confirm": "업데이트","cancel": "취소"},- "reapproveConfirm": {- "title": "\"{{name}}\" 권한을 다시 확인할까요?",- "body": "아래 권한을 확인하면 설치된 플러그인이 다시 승인됩니다. 설치 파일은 필요하지 않습니다.",- "confirm": "확인 후 복원",- "enableNoticeEnabled": "확인 후 현재 활성화 상태를 유지합니다.",- "enableNoticeAsleep": "확인 후 휴면 상태를 유지합니다(자동으로 활성화되지 않음). 나중에 여기에서 수동으로 활성화할 수 있습니다."- },"pick": {"dialogTitle": "폴더 선택","dialogMessage": "플러그인 \"{{name}}\"이(가) 폴더 선택을 요청합니다"@@ -4676,7 +4640,7 @@"updateAll": {"title": "모두 업데이트 · {{count}}개","collapseDiff": "접기",- "description": "일반 업데이트는 자동으로 완료되며, 검증된 실제 패키지가 새 권한을 요청할 때만 개별 확인합니다.",+ "description": "업데이트는 보통 알림 없이 실행됩니다. 이 화면에서 건너뛰거나 실패한 업데이트를 다시 시도할 수 있습니다.","versionRange": "v{{from}} → v{{to}}","statusPending": "대기 중","statusInstalling": "업데이트 중…",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 098fcf9d4e..3ba540c462 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -4110,7 +4110,7 @@"updateTo": "更新到 v{{version}}","updateAria": "将 {{name}} 更新到 v{{version}}","createWithCindy": "使用 Cindy 创建",- "createPrompt": "我要创建一个 Cindy 插件。请先调用 ghost_forge_guide 获取手册目录,先读第 0 章「设计对齐」,再用 section 参数读透相关章节(动手前至少读完第 2 章卡槽总览、沙箱红线与打包流程三章),不要直接开始实现。先从提问开始:优先用带选项的提问卡片,每张卡片聚焦一个关键决策并标注你的推荐项,把我可能不知道的设计选项主动摆出来让我选——比如界面形态(停靠面板、插件页内面板、对话卡片还是无界面)、$ 点名词、启动模式、后台能力(旁听事件、应用内轻提示、未读角标、确认弹窗)、是否联网、是否需要设置页、要不要随包 Node 进程跑重活、要不要图片视频等媒体能力;并逐步确认插件要解决的问题、目标用户、交互流程、所需工具与连接、权限边界和验收标准。设计确认后,再按规范实现并自检;最后调用 ghost_forge_pack 打包并安装插件。",+ "createPrompt": "我要创建一个 Cindy 插件。请先调用 ghost_forge_guide 获取手册目录,先读第 0 章「设计对齐」,再用 section 参数读透相关章节(动手前至少读完能力总览、沙箱红线与打包流程),不要直接开始实现。先从提问开始:优先用带选项的提问卡片,每张卡片聚焦一个关键决策并标注你的推荐项,把我可能不知道的设计选项主动摆出来让我选——比如界面形态(停靠面板、插件页内面板、对话卡片还是无界面)、$ 点名词、启动模式、后台能力(旁听事件、应用内轻提示、未读角标、确认弹窗)、是否联网、是否需要设置页、要不要随包 Node 进程跑重活、要不要图片视频等媒体能力;并逐步确认插件要解决的问题、目标用户、交互流程、所需工具与连接、权限边界和验收标准。设计确认后,再按规范实现并自检;最后调用 ghost_forge_pack 校验并生成 .cindy 产物,不要声称已经安装。","filterAll": "全部","filtersAria": "按来源筛选插件","origin": {@@ -4154,14 +4154,6 @@"customSourcesUnavailable": "以下自定义市场暂时不可用:{{names}}。其他市场不受影响。","authenticationRequired": "登录 Cindy 后才能查看插件市场。","notConfigured": "当前环境未配置插件市场;已安装插件仍可正常管理和使用。",- "upgradeNotice": {- "single": "已自动更新企业插件“{{name}}”",- "multiple_one": "已自动更新 {{count}} 个企业插件",- "multiple_other": "已自动更新 {{count}} 个企业插件",- "singleWithPermissions": "已自动更新企业插件“{{name}}”,新增权限:{{permissions}}",- "multipleWithPermissions_one": "已自动更新 {{count}} 个企业插件,其中有插件新增了权限",- "multipleWithPermissions_other": "已自动更新 {{count}} 个企业插件,其中有插件新增了权限"- },"removalNotice": {"single": "插件“{{name}}”已被组织移除,本机副本与数据已清理","multiple_one": "{{count}} 个插件已被组织移除,本机副本与数据已清理",@@ -4182,10 +4174,6 @@"securityDescription": "安装包会在主进程中校验大小与 SHA-256,再经 Cindy 插件清单校验后原子安装。首次安装完成后即自动开启,可随时在插件页停用;更新会保留当前生效状态。","customSecurityDescription": "该插件来自你添加的自定义市场,未经 Cindy 服务端完整性校验。安装前会在主进程校验插件清单;首次安装完成后即自动开启,可随时在插件页停用。","noPermissions": "此插件未声明额外能力。",- "installConfirmTitle": "安装「{{name}}」?",- "installConfirmDescription": "安装包将经过完整性与清单校验。安装完成后插件将自动开启,你可以随时在插件页停用或调整配置。",- "customInstallConfirmDescription": "插件来自自定义市场,未经服务端完整性校验,安装前将校验插件清单。安装完成后插件将自动开启,你可以随时在插件页停用或调整配置。",- "updateConfirmDescription": "安装包将经过完整性与清单校验,并替换现有版本。当前生效状态保持不变。","sources": {"addMarketplace": "添加插件市场…","dialogTitle": "添加插件市场",@@ -4243,7 +4231,7 @@"authTitle": "私有仓库","authBody": "认证完全依赖系统的 Git 配置,Cindy 不保存任何 Git 凭证。SSH 方式:本机已配置可用的 key;若组织开启了 SAML SSO,还需在 GitHub 的 SSH key 设置里为该组织点 Configure SSO 授权。HTTPS 方式:使用 Personal Access Token,并由系统 credential helper 保存。","rulesTitle": "安装规则",- "rulesBody": "插件 id 全局唯一、先装先得——与已安装插件冲突时会明确提示。id 使用官方保留前缀({{reservedGhostIdPrefixes}})的插件,不能通过拖入、选择文件、ghost_forge_pack 转交或自定义插件市场装入。安装前会逐项展示插件声明的权限,确认后即完成安装并自动开启。",+ "rulesBody": "插件 id 全局唯一、先装先得——与已安装插件冲突时会明确提示。id 使用官方保留前缀({{reservedGhostIdPrefixes}})的插件,不能通过拖入、选择文件或自定义插件市场装入。插件声明的权限会在详情页展示;点击安装后直接完成安装并自动开启,不再额外弹窗确认权限。","copy": "复制指南","copied": "指南已复制到剪贴板。","copyFailed": "复制失败,请重试。"@@ -4254,13 +4242,13 @@"conflictDescription": "插件标识已被占用,当前无法安装"},"reapproval": {- "badge": "需要重新确认权限",- "action": "重新确认权限",- "actionAria": "重新确认插件「{{name}}」的权限",- "noticeTitle": "需要重新确认权限",- "bodyLegacy": "Cindy 没有这个插件的权限确认记录,所以先把它停用了。点「重新确认权限」重新过一遍它要的权限,确认后即可继续使用。",- "bodyInvalid": "这个插件的权限确认记录已损坏,所以先把它停用了。点「重新确认权限」重新过一遍它要的权限,确认后即可继续使用。",- "bodyBuiltinRestart": "这个内置插件的权限记录出了点问题。重启 Cindy 即可自动恢复,无需其他操作。"+ "badge": "需要恢复安装",+ "action": "重新安装",+ "actionAria": "重新安装插件「{{name}}」",+ "noticeTitle": "需要恢复安装",+ "bodyLegacy": "Cindy 无法验证这个插件的完整安装记录,因此已暂停运行。请重新安装原市场版本,或重新选择对应的 .cindy 包。",+ "bodyInvalid": "这个插件的安装验证记录已损坏,因此已暂停运行。请重新安装原市场版本,或重新选择对应的 .cindy 包。",+ "bodyBuiltinRestart": "这个内置插件的安装验证记录出了问题。重启 Cindy 即可自动恢复,无需其他操作。"},"install": "安装插件…","empty": "还没有安装任何插件",@@ -4329,26 +4317,11 @@},"installConfirm": {"title": "安装插件「{{name}}」?",- "confirm": "安装插件",- "cancel": "取消","meta": "版本 {{version}}。将安装到本机,可随时卸载。","metaWithAuthor": "作者 {{author}} · 版本 {{version}}。将安装到本机,可随时卸载。","manualCount": "随包手册 {{count}} 篇","expandDescription": "展开完整介绍",- "collapseDescription": "收起介绍",- "typedIdLabel": "输入插件 id「{{id}}」以确认安装",- "agentBanner": {- "title": "这次安装是 Agent 发起的,不是你点的。",- "context": "它在任务「{{title}}」里打包了 {{path}} 下的插件源码。",- "contextNoPath": "它在任务「{{title}}」里打包了一个插件源码目录。",- "contextNoTitle": "它打包了 {{path}} 下的插件源码。",- "contextBare": "它打包了一个插件源码目录。",- "advice": "如果你没在这个任务里要求做插件,请取消 —— 并回头看看这个任务刚才读过哪些外部内容。",- "firstInstall": "这个插件 id 此前从未安装过。",- "hazardSkill": "它带了技能指令,AI 会以你的全部权限执行,不受插件沙箱限制,而且对你所有项目生效。",- "hazardNode": "它可以在你的电脑上运行程序,不受浏览器沙箱限制。",- "hazardCredential": "它会把你在它设置页填的凭证发给 {{hosts}}。"- }+ "collapseDescription": "收起介绍"},"trust": {"official": "Cindy 官方插件",@@ -4471,13 +4444,11 @@},"errors": {"fileInvalid": "不是合法的 .cindy 插件文件",- "hostUnsupported": "这个插件需要当前版本尚未提供的 Cindy 能力。请先升级 Cindy,再重新安装。",+ "hostUnsupported": "当前 Cindy 无法识别此插件的清单格式。","alreadyInstalled": "这个插件已经安装",- "approvalRequired": "需要重新确认这个插件的权限后才能继续","commandConflict": "它的指令和已装插件撞名了,先卸载占用方或让作者改名",- "idReserved": "{{reservedGhostIdPrefixes}} 是官方插件保留前缀,不能通过拖入、选择文件、ghost_forge_pack 转交或自定义插件市场装入;请从 Cindy 插件市场安装对应的官方插件",- "brokerManualInstallNotAuthorized": "手动装入的 .cindy 不能使用授权 broker;请改从组织插件市场安装,或让作者在组织身份下使用 ghost_forge_pack 构建",- "brokerNotAuthorized": "当前安装来源或组织身份无权使用授权 broker;请从组织插件市场安装,或让作者在组织身份下使用 ghost_forge_pack 构建",+ "idReserved": "{{reservedGhostIdPrefixes}} 是官方插件保留前缀,不能通过拖入、选择文件或自定义插件市场装入;请从 Cindy 插件市场安装对应的官方插件",+ "brokerManualInstallNotAuthorized": "本地装入的 .cindy 不能使用授权 broker;请改从组织插件市场安装","brokerRedirectPortRequired": "这个插件声明了授权 broker,但没有在同一项 OAuth 配置中声明 redirectPort。请让作者补上该字段,确保授权最后一跳能回到本机监听端口。","sourceMissing": "找不到所选文件","generic": "操作失败,请稍后重试",@@ -4644,13 +4615,6 @@"confirm": "更新","cancel": "取消"},- "reapproveConfirm": {- "title": "重新确认「{{name}}」的权限?",- "body": "按下方清单重新授权这个已安装的插件,无需重新提供安装包文件。",- "confirm": "确认并恢复",- "enableNoticeEnabled": "确认后保持当前启用状态。",- "enableNoticeAsleep": "确认后保持沉睡(不自动启用);你可以稍后在这里手动启用。"- },"pick": {"dialogTitle": "选择文件夹","dialogMessage": "插件「{{name}}」请求你选择一个文件夹"@@ -4668,7 +4632,7 @@"updateAll": {"title": "全部更新 · {{count}} 个插件","collapseDiff": "收起",- "description": "普通更新会自动完成;真实包请求新增权限时需要逐项确认。",+ "description": "更新通常会静默完成;这里用于重试因忙碌跳过或执行失败的更新。","versionRange": "v{{from}} → v{{to}}","statusPending": "排队中","statusInstalling": "更新中…",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 0aa9f5e0b3..d148827ac1 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -4110,7 +4110,7 @@"updateTo": "更新到 v{{version}}","updateAria": "將 {{name}} 更新到 v{{version}}","createWithCindy": "使用 Cindy 建立",- "createPrompt": "我要建立一個 Cindy 插件。請先呼叫 ghost_forge_guide 獲取手冊目錄,先讀第 0 章「設計對齊」,再用 section 引數讀透相關章節(動手前至少讀完第 2 章卡槽總覽、沙箱紅線與打包流程三章),不要直接開始實現。先從提問開始:優先用帶選項的提問卡片,每張卡片聚焦一個關鍵決策並標註你的推薦項,把我可能不知道的設計選項主動擺出來讓我選——比如介面形態(停靠面板、插件頁內面板、對話卡片還是無介面)、$ 點名詞、啟動模式、後台能力(旁聽事件、應用內輕提示、未讀角標、確認彈窗)、是否聯網、是否需要設定頁、要不要隨包 Node 行程跑重活、要不要圖片影片等媒體能力;並逐步確認插件要解決的問題、目標使用者、互動流程、所需工具與連線、權限邊界和驗收標準。設計確認後,再按規範實現並自檢;最後呼叫 ghost_forge_pack 打包並安裝插件。",+ "createPrompt": "我要建立一個 Cindy 插件。請先呼叫 ghost_forge_guide 獲取手冊目錄,先讀第 0 章「設計對齊」,再用 section 引數讀透相關章節(動手前至少讀完能力總覽、沙箱紅線與打包流程),不要直接開始實現。先從提問開始:優先用帶選項的提問卡片,每張卡片聚焦一個關鍵決策並標註你的推薦項,把我可能不知道的設計選項主動擺出來讓我選——比如介面形態(停靠面板、插件頁內面板、對話卡片還是無介面)、$ 點名詞、啟動模式、後台能力(旁聽事件、應用內輕提示、未讀角標、確認彈窗)、是否聯網、是否需要設定頁、要不要隨包 Node 行程跑重活、要不要圖片影片等媒體能力;並逐步確認插件要解決的問題、目標使用者、互動流程、所需工具與連線、權限邊界和驗收標準。設計確認後,再按規範實現並自檢;最後呼叫 ghost_forge_pack 校驗並產生 .cindy 產物,不要聲稱已安裝。","filterAll": "全部","filtersAria": "按來源篩選插件","origin": {@@ -4153,14 +4153,6 @@"unavailable": "插件市場暫時不可用;已安裝插件仍可正常管理和使用。","authenticationRequired": "登入 Cindy 後才能檢視插件市場。","notConfigured": "當前環境未配置插件市場;已安裝插件仍可正常管理和使用。",- "upgradeNotice": {- "single": "已自動更新企業插件「{{name}}」",- "multiple_one": "已自動更新 {{count}} 個企業插件",- "multiple_other": "已自動更新 {{count}} 個企業插件",- "singleWithPermissions": "已自動更新企業插件「{{name}}」,新增權限:{{permissions}}",- "multipleWithPermissions_one": "已自動更新 {{count}} 個企業插件,其中有插件新增了權限",- "multipleWithPermissions_other": "已自動更新 {{count}} 個企業插件,其中有插件新增了權限"- },"removalNotice": {"single": "插件“{{name}}”已被組織移除,本機副本與資料已清理","multiple_one": "{{count}} 個插件已被組織移除,本機副本與資料已清理",@@ -4181,10 +4173,6 @@"securityDescription": "安裝包會在主處理程序中校驗大小與 SHA-256,再經 Cindy 插件清單校驗後原子安裝。首次安裝完成後即自動開啟,可隨時在插件頁停用;更新會保留當前生效狀態。","customSecurityDescription": "該插件來自你新增的自定義市場,未經 Cindy 服務端完整性校驗。安裝前會在主處理程序校驗插件清單;首次安裝完成後即自動開啟,可隨時在插件頁停用。","noPermissions": "此插件未宣告額外能力。",- "installConfirmTitle": "安裝「{{name}}」?",- "installConfirmDescription": "安裝包將經過完整性與清單校驗。安裝完成後插件將自動開啟,你可以隨時在插件頁停用或調整配置。",- "customInstallConfirmDescription": "插件來自自定義市場,未經服務端完整性校驗,安裝前將校驗插件清單。安裝完成後插件將自動開啟,你可以隨時在插件頁停用或調整配置。",- "updateConfirmDescription": "安裝包將經過完整性與清單校驗,並替換現有版本。當前生效狀態保持不變。","sources": {"addMarketplace": "新增插件市場…","dialogTitle": "新增插件市場",@@ -4242,7 +4230,7 @@"authTitle": "私有倉庫","authBody": "認證完全依賴系統的 Git 配置,Cindy 不儲存任何 Git 憑證。SSH 方式:本機已配置可用的 key;若組織開啟了 SAML SSO,還需在 GitHub 的 SSH key 設定裡為該組織點 Configure SSO 授權。HTTPS 方式:使用 Personal Access Token,並由系統 credential helper 儲存。","rulesTitle": "安裝規則",- "rulesBody": "插件 id 全域性唯一、先裝先得——與已安裝插件衝突時會明確提示。id 使用官方保留字首({{reservedGhostIdPrefixes}})的插件,無法透過拖入、選取檔案、ghost_forge_pack 轉交或自訂插件市場安裝。安裝前會逐項展示插件宣告的權限,確認後即完成安裝並自動開啟。",+ "rulesBody": "插件 id 全域性唯一、先裝先得——與已安裝插件衝突時會明確提示。id 使用官方保留字首({{reservedGhostIdPrefixes}})的插件,無法透過拖入、選取檔案或自訂插件市場安裝。插件宣告的權限會在詳情頁展示;點擊安裝後直接完成安裝並自動開啟,不再額外彈窗確認權限。","copy": "複製指南","copied": "指南已複製到剪貼簿。","copyFailed": "複製失敗,請重試。"@@ -4257,13 +4245,13 @@"empty": "還沒有安裝任何插件","emptyHint": "可從插件市場安裝,或點選右上角匯入 .cindy 檔案","reapproval": {- "badge": "需要重新確認權限",- "action": "重新確認權限",- "actionAria": "重新確認插件「{{name}}」的權限",- "noticeTitle": "需要重新確認權限",- "bodyLegacy": "Cindy 沒有這個插件的權限確認記錄,所以先將它停用。點「重新確認權限」重新檢視它要求的權限,確認後即可繼續使用。",- "bodyInvalid": "這個插件的權限確認記錄已損壞,所以先將它停用。點「重新確認權限」重新檢視它要求的權限,確認後即可繼續使用。",- "bodyBuiltinRestart": "這個內建插件的權限記錄出了問題。重新啟動 Cindy 即可自動恢復,不需要其他操作。"+ "badge": "需要恢復安裝",+ "action": "重新安裝",+ "actionAria": "重新安裝插件「{{name}}」",+ "noticeTitle": "需要恢復安裝",+ "bodyLegacy": "Cindy 無法驗證這個插件的完整安裝記錄,因此已暫停執行。請重新安裝原市場版本,或重新選擇對應的 .cindy 套件。",+ "bodyInvalid": "這個插件的安裝驗證記錄已損壞,因此已暫停執行。請重新安裝原市場版本,或重新選擇對應的 .cindy 套件。",+ "bodyBuiltinRestart": "這個內建插件的安裝驗證記錄出了問題。重新啟動 Cindy 即可自動恢復,不需要其他操作。"},"legacyRecovery": {"title": "舊版本插件正在等待恢復",@@ -4329,26 +4317,11 @@},"installConfirm": {"title": "安裝插件「{{name}}」?",- "confirm": "安裝插件",- "cancel": "取消","meta": "版本 {{version}}。將安裝到本機,可隨時解除安裝。","metaWithAuthor": "作者 {{author}} · 版本 {{version}}。將安裝到本機,可隨時解除安裝。","manualCount": "隨包手冊 {{count}} 篇","expandDescription": "展開完整介紹",- "collapseDescription": "收起介紹",- "typedIdLabel": "輸入插件 id「{{id}}」以確認安裝",- "agentBanner": {- "title": "這次安裝是 Agent 發起的,不是你點的。",- "context": "它在任務「{{title}}」裡打包了 {{path}} 下的插件原始碼。",- "contextNoPath": "它在任務「{{title}}」裡打包了一個插件原始碼目錄。",- "contextNoTitle": "它打包了 {{path}} 下的插件原始碼。",- "contextBare": "它打包了一個插件原始碼目錄。",- "advice": "如果你沒在這個任務裡要求做插件,請取消 —— 並回頭看看這個任務剛才讀過哪些外部內容。",- "firstInstall": "這個插件 id 此前從未安裝過。",- "hazardSkill": "它帶了技能指令,AI 會以你的全部權限執行,不受插件沙箱限制,而且對你所有專案生效。",- "hazardNode": "它可以在你的電腦上執行程式,不受瀏覽器沙箱限制。",- "hazardCredential": "它會把你在它設定頁填的憑證發給 {{hosts}}。"- }+ "collapseDescription": "收起介紹"},"trust": {"official": "Cindy 官方插件",@@ -4471,13 +4444,11 @@},"errors": {"fileInvalid": "不是合法的 .cindy 插件檔案",- "hostUnsupported": "這個插件需要目前版本尚未提供的 Cindy 能力。請先更新 Cindy,再重新安裝。",+ "hostUnsupported": "目前 Cindy 無法識別此插件的清單格式。","alreadyInstalled": "這個插件已經安裝",- "approvalRequired": "繼續前需要重新確認這個插件的權限","commandConflict": "它的指令和已裝插件撞名了,先解除安裝佔用方或讓作者改名",- "idReserved": "{{reservedGhostIdPrefixes}} 是官方插件保留字首,無法透過拖入、選取檔案、ghost_forge_pack 轉交或自訂插件市場安裝;請從 Cindy 插件市場安裝對應的官方插件",- "brokerManualInstallNotAuthorized": "手動安裝的 .cindy 無法使用授權 broker;請改從組織插件市場安裝,或請作者以組織身分使用 ghost_forge_pack 建置",- "brokerNotAuthorized": "目前的安裝來源或組織身分無權使用授權 broker;請從組織插件市場安裝,或請作者以組織身分使用 ghost_forge_pack 建置",+ "idReserved": "{{reservedGhostIdPrefixes}} 是官方插件保留字首,無法透過拖入、選取檔案或自訂插件市場安裝;請從 Cindy 插件市場安裝對應的官方插件",+ "brokerManualInstallNotAuthorized": "本機安裝的 .cindy 無法使用授權 broker;請改從組織插件市場安裝","brokerRedirectPortRequired": "這個插件宣告了授權 broker,但沒有在同一項 OAuth 設定中宣告 redirectPort。請讓作者補上該欄位,確保授權最後一跳能回到本機監聽連接埠。","sourceMissing": "找不到所選檔案","generic": "操作失敗,請稍後重試",@@ -4637,13 +4608,6 @@"bindAfterInstallFailed": "自訂儲存位置設定失敗,已回退預設位置","cancel": "取消"},- "reapproveConfirm": {- "title": "重新確認「{{name}}」的權限?",- "body": "按下方清單重新授權這個已安裝的插件,不需要重新提供安裝包檔案。",- "confirm": "確認並恢復",- "enableNoticeEnabled": "確認後保持目前啟用狀態。",- "enableNoticeAsleep": "確認後保持沉睡(不自動啟用);你可以稍後在這裡手動啟用。"- },"updateConfirm": {"title": "更新插件「{{name}}」?","body": "版本 {{from}} → {{to}}。將替換現有版本;生效狀態與面板位置保持不變。",@@ -4668,7 +4632,7 @@"updateAll": {"title": "全部更新 · {{count}} 個插件","collapseDiff": "收起",- "description": "權限無變化的更新會自動完成;涉及權限變更的需要你逐項確認。",+ "description": "更新通常會靜默完成;這裡用於重試因忙碌跳過或執行失敗的更新。","versionRange": "v{{from}} → v{{to}}","statusPending": "排隊中","statusInstalling": "更新中…",diff --git a/apps/desktop/src/renderer/lib/__tests__/ghostPanelBubbleState.test.ts b/apps/desktop/src/renderer/lib/__tests__/ghostPanelBubbleState.test.tsindex 74514b92c6..81b9078c54 100644--- a/apps/desktop/src/renderer/lib/__tests__/ghostPanelBubbleState.test.ts+++ b/apps/desktop/src/renderer/lib/__tests__/ghostPanelBubbleState.test.ts@@ -26,7 +26,6 @@ function ghost(version: '1.0.0',kind: 'chip',entry: 'main.js',- slots: opts.panel === false ? ['tool'] : ['panel'],...(opts.panel === false? {}: {diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex e0b5d6f118..e4d82d52d6 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -1242,8 +1242,8 @@ interface ElectronAPI {onRecentUsageChanged: (callback: (payload: { ids: string[] }) => void) => () => void;install: (lizFilePath: string,- /** enable:装入后立即开启(确认框勾选决定;缺省沉睡)。 */- opts: { enable?: boolean; expectedPackageSha256: string; packTicket?: string },+ /** enable:装入后立即开启;缺省沉睡。 */+ opts: { enable?: boolean; expectedPackageSha256: string },) => Promise<{ ghost: import('../shared/ghost').InstalledGhost }>;/** 原位更新(同 id 换版):唤醒状态与面板位置延续,沙箱熄灯待重拉。 */update: (@@ -1251,7 +1251,6 @@ interface ElectronAPI {opts: {expectedPackageSha256: string;expectedInstalledApproval: string;- packTicket?: string;},) => Promise<{ ghost: import('../shared/ghost').InstalledGhost }>;/**@@ -1311,44 +1310,16 @@ interface ElectronAPI {) => Promise<{ config: Record<string, unknown> }>;/** 系统文件选择框(.cindy 过滤),只选不装;取消返回 { canceled: true }。 */pickFile: () => Promise<{ canceled: true } | { filePath: string }>;- /** 只验不装:读出清单、签名信任等级与 icon data URL,供确认弹窗展示。 */+ /** 只验不装:读出清单、签名信任等级与 icon data URL,供安装编排使用。 */inspect: (lizFilePath: string) => Promise<{manifest: import('../shared/ghost').GhostManifest;trust: import('../shared/ghost').GhostTrustInfo;/** 本次检查的整包指纹;安装/更新时回传,防止确认后文件被替换。 */packageSha256: string;+ /** v2 清单中无法映射的历史 slot;仅用于兼容诊断,不阻塞安装。 */+ unsupportedSlots: string[];iconDataUrl?: string;- /** Host 一次性打包凭证。有则回传给 install/update;无则按手动装入。 */- packTicket?: string;}>;- /** 用户取消确认框时丢掉 inspect 签发的一次性打包凭证并清理 staging。 */- abandonPackTicket: (packTicket: string) => Promise<{ ok: true }>;- /** 本地包第三条恢复路径第一步:从已装目录读确认卡事实,零副作用。 */- reapproveInspect: (- id: string,- ) => Promise<{- manifest: import('../shared/ghost').GhostManifest;- trust: import('../shared/ghost').GhostTrustInfo;- /** 确认卡展示时的清单字节指纹;确认时回传,防确认间隙清单被换。 */- manifestSha256: string;- /** 确认卡展示时的完整批准投影指纹;覆盖技能、locale、icon、trust。 */- approvalProjectionSha256: string;- /** 升级前的启停偏好(.disabled 镜像读数):确认卡勾选默认值。 */- previouslyEnabled: boolean;- /** 一次性票据(Host 进程内钉住 inspect 时点的 owner 与事实,confirm 原子消费)。 */- inspectTicket: string;- }>;- /** 第三条恢复路径第二步:用户点过确认卡后开 receipt。 */- reapproveInstalled: (- id: string,- opts: {- enable: boolean;- expectedManifestSha256: string;- expectedApprovalProjectionSha256: string;- expectedInstalledApproval: string;- inspectTicket: string;- },- ) => Promise<{ ghost: import('../shared/ghost').InstalledGhost }>;uninstall: (id: string) => Promise<{ ok: true }>;/** 详情页「导出 .cindy」:打包安装目录 → 保存对话框落盘。 */export: (@@ -1364,14 +1335,8 @@ interface ElectronAPI {id: string,disabled: boolean,) => Promise<{ disabled: string[] }>;- /**- * 双击 .cindy / forge 转交的待装路径与来源,原子取走(取即清空;无则 null)。- * 来源由主机填写、与路径同存同取,agent 不可伪造;没有待装项时返回 manual。- */- takePendingInstall: () => Promise<{- filePath: string | null;- origin: import('../shared/ghostInstallOrigin').GhostInstallOrigin;- }>;+ /** 双击 .cindy 的待装路径,原子取走(取即清空;无则 null)。 */+ takePendingInstall: () => Promise<{ filePath: string | null }>;onChanged: (callback: (payload: { ghosts: import('../shared/ghost').InstalledGhost[] }) => void,) => () => void;@@ -1383,11 +1348,7 @@ interface ElectronAPI {| { sessionId: string; target: 'client_settings' },) => void,) => () => void;- /**- * 双击 .cindy / forge 转交的"来取货"通知,**不携带任何事实**:收到后调- * takePendingInstall 取路径与来源。事实只放在 main 的 pending 缓冲里,- * 没有窗口时(冷启动 / macOS 关窗后应用仍在跑)本通知丢掉也不影响正确性。- */+ /** 双击 .cindy 转交信号:收到后调 takePendingInstall 取路径走一键装入流程。 */onInstallRequested: (callback: () => void) => () => void;/** 运行时状态广播:crashed / fused 时面板原地显示错误接管态。 */onRuntimeChanged: (@@ -1626,24 +1587,11 @@ interface ElectronAPI {pluginId: string,options: import('../shared/pluginMarket').PluginMarketInstallOptions,) => Promise<import('../shared/pluginMarket').PluginMarketInstallResult>;- onPackagePermissionReview: (- callback: (- request: import('../shared/pluginMarket').PluginMarketPackageReviewRequest,- ) => void,- ) => () => void;- resolvePackagePermissionReview: (- requestId: string,- confirmed: boolean,- ) => Promise<{ handled: boolean }>;uninstall: (pluginId: string) => Promise<{ ok: true }>;consumeRemovalNotice: () => Promise<import('../shared/pluginMarket').PluginRemovalUserNotice | null>;onRemovalNoticeAvailable: (callback: () => void) => () => void;- consumeUpgradeNotice: () => Promise<- import('../shared/pluginMarket').PluginUpgradeUserNotice | null- >;- onUpgradeNoticeAvailable: (callback: () => void) => () => void;listSources: () => Promise<import('../shared/pluginMarket').MarketSourceSummary[]>;pickLocalSource: (defaultPath?: string,diff --git a/apps/desktop/src/shared/__tests__/ghost.test.ts b/apps/desktop/src/shared/__tests__/ghost.test.tsindex cc28c96230..24847e6ecb 100644--- a/apps/desktop/src/shared/__tests__/ghost.test.ts+++ b/apps/desktop/src/shared/__tests__/ghost.test.ts@@ -6,7 +6,6 @@ import {GHOST_CINDY_EMBED_MAX_TEXTS,GHOST_MANIFEST_SUMMARY_MAX_CHARS,GHOST_MAIN_VIEW_ICONS,- GHOST_SLOTS,changedBuiltinOauthClientSecretKeys,deriveGhostSessionContext,diffGhostPermissionItems,@@ -122,7 +121,7 @@ describe('ghost · id 规则', () => {const base = validateGhostManifest(goodManifest());expect(base.ok && ghostContentKeys(base.manifest)).toEqual(['panel', 'code']);const chip = validateGhostManifest(goodChipManifest());- expect(chip.ok && ghostContentKeys(chip.manifest)).toEqual(['panel', 'code', 'slotCindy']);+ expect(chip.ok && ghostContentKeys(chip.manifest)).toEqual(['panel', 'code']);const noPanel: Record<string, unknown> = {...goodManifest(),slots: ['tool'],@@ -148,7 +147,9 @@ describe('ghost · 清单校验', () => {const v = validateGhostManifest({ ...goodManifest(), unknownField: 'ignored' });expect(v.ok).toBe(true);const manifest = (v as { ok: true; manifest: GhostManifest }).manifest;- expect(manifest).toEqual(goodManifest()); // 未知字段被丢弃+ const expected = goodManifest();+ delete expected.slots;+ expect(manifest).toEqual(expected); // 未知字段与 v2 slots 被丢弃});it('panel 可省略(slots 不含 panel 时)', () => {@@ -983,6 +984,82 @@ describe('ghost · 清单校验', () => {});});+describe('ghost · Manifest v3 直接能力声明', () => {+ it('规范化为无 slots 的运行时模型,并保留但不授权未知顶层字段', () => {+ const result = validateGhostManifest({+ schemaVersion: 3,+ minCindyVersion: '0.1.61',+ id: 'direct-helper',+ name: 'Direct Helper',+ version: '1.0.0',+ entry: 'main.js',+ tools: [{ name: 'help', description: '提供帮助' }],+ card: {},+ agent: {},+ notify: true,+ library: true,+ futureCapability: { mode: 'example' },+ });+ expect(result.ok).toBe(true);+ if (!result.ok) return;+ expect(result.manifest).not.toHaveProperty('slots');+ expect(result.manifest.card).toEqual({});+ expect(result.manifest.agent).toEqual({});+ expect(result.manifest.notify).toBe(true);+ expect(result.manifest.library).toBe(true);+ expect(ghostPermissionItems(result.manifest).map((item) => item.key)).toContain('library');+ expect(result.manifest.futureCapability).toEqual({ mode: 'example' });+ expect(result.unsupportedLegacySlots).toEqual([]);+ expect(ghostPermissionItems(result.manifest).map((item) => item.key)).not.toContain(+ 'futureCapability',+ );+ });++ it('拒绝 v3 slots、缺 minCindyVersion 和 false 布尔能力', () => {+ const base = {+ schemaVersion: 3,+ minCindyVersion: '0.1.61',+ id: 'direct-helper',+ name: 'Direct Helper',+ version: '1.0.0',+ entry: 'main.js',+ };+ expect(validateGhostManifest({ ...base, slots: [] }).ok).toBe(false);+ expect(validateGhostManifest({ ...base, minCindyVersion: undefined }).ok).toBe(false);+ expect(validateGhostManifest({ ...base, minCindyVersion: '0.1.60' }).ok).toBe(false);+ expect(validateGhostManifest({ ...base, notify: false }).ok).toBe(false);+ });++ it('v2 与等价 v3 使用同一权限基线,移除 slots 本身不构成扩权', () => {+ const common = {+ id: 'equivalent-helper',+ name: 'Equivalent Helper',+ version: '1.0.0',+ entry: 'main.js',+ tools: [{ name: 'help', description: '提供帮助' }],+ };+ const legacy = validateGhostManifest({+ ...common,+ schemaVersion: 2,+ slots: ['tool', 'card', 'notify', 'library'],+ });+ const direct = validateGhostManifest({+ ...common,+ schemaVersion: 3,+ minCindyVersion: '0.1.61',+ card: {},+ notify: true,+ library: true,+ });+ expect(legacy.ok && direct.ok).toBe(true);+ if (!legacy.ok || !direct.ok) return;+ expect(ghostPermissionBaselineKey(legacy.manifest)).toBe(+ ghostPermissionBaselineKey(direct.manifest),+ );+ expect(diffGhostPermissionItems(legacy.manifest, direct.manifest).added).toEqual([]);+ });+});+describe('ghost · 芯片型清单(schemaVersion 2)', () => {it('全字段合法芯片清单通过', () => {const v = validateGhostManifest(goodChipManifest());@@ -990,7 +1067,7 @@ describe('ghost · 芯片型清单(schemaVersion 2)', () => {const manifest = (v as { ok: true; manifest: GhostManifest }).manifest;expect(manifest.kind).toBe('chip');expect(manifest.entry).toBe('main.js');- expect(manifest.slots).toEqual(['panel', 'cindy']); // 'model' 旧名归一化+ expect(manifest).not.toHaveProperty('slots');expect(manifest.panel?.html).toBe('panel.html');});@@ -1004,12 +1081,21 @@ describe('ghost · 芯片型清单(schemaVersion 2)', () => {expect(validateGhostManifest({ ...goodChipManifest(), entry: 'src/main.js' }).ok).toBe(true);});- it('slots 必填非空、只认已知卡槽、不许重复', () => {+ it('v2 slots 必须是数组;允许空值与未知声明,但重复仍拒绝', () => {expect(validateGhostManifest({ ...goodChipManifest(), slots: undefined }).ok).toBe(false);- expect(validateGhostManifest({ ...goodChipManifest(), slots: [] }).ok).toBe(false);expect(- validateGhostManifest({ ...goodChipManifest(), slots: ['panel', 'filesystem'] }).ok,- ).toBe(false);+ validateGhostManifest({+ ...goodChipManifest(),+ slots: [],+ panel: undefined,+ }).ok,+ ).toBe(true);+ const unknown = validateGhostManifest({+ ...goodChipManifest(),+ slots: ['panel', 'filesystem'],+ });+ expect(unknown.ok).toBe(true);+ if (unknown.ok) expect(unknown.unsupportedLegacySlots).toEqual(['filesystem']);expect(validateGhostManifest({ ...goodChipManifest(), slots: ['model', 'model'] }).ok).toBe(false,);@@ -1027,7 +1113,7 @@ describe('ghost · 芯片型清单(schemaVersion 2)', () => {});expect(userActionOnly.ok).toBe(true);if (!userActionOnly.ok) return;- expect(userActionOnly.manifest.agent).toBeUndefined();+ expect(userActionOnly.manifest.agent).toEqual({});expect(ghostContentKeys(userActionOnly.manifest)).toContain('slotAgent');expect(ghostPermissionItems(userActionOnly.manifest)).toEqual(expect.arrayContaining([@@ -1236,7 +1322,7 @@ describe('ghost · 芯片型清单(schemaVersion 2)', () => {);});- it('node 清单拒绝任意命令字段、越界配置和槽/详单不成对', () => {+ it('node 清单拒绝任意命令字段、越界配置和无槽详单;空槽按零能力兼容', () => {const withNode = (node: unknown, slots: string[] = ['panel', 'node']) =>validateGhostManifest({ ...goodChipManifest(), slots, node });expect(withNode({ entry: 'node/a.cjs', protocol: 'json-rpc-stdio' }).ok).toBe(true);@@ -1259,9 +1345,12 @@ describe('ghost · 芯片型清单(schemaVersion 2)', () => {}).ok,).toBe(false);expect(withNode({ entry: 'node/a.cjs', protocol: 'json-rpc-stdio' }, ['panel']).ok).toBe(false);- expect(validateGhostManifest({ ...goodChipManifest(), slots: ['panel', 'node'] }).ok).toBe(- false,- );+ const emptyNode = validateGhostManifest({+ ...goodChipManifest(),+ slots: ['panel', 'node'],+ });+ expect(emptyNode.ok).toBe(true);+ if (emptyNode.ok) expect(emptyNode.manifest.node).toBeUndefined();});it('node.secretBindings 逐方法声明保险库凭证并生成单独权限项', () => {@@ -1412,13 +1501,14 @@ describe('ghost · 芯片型清单(schemaVersion 2)', () => {).toBe(false);});- it('工具声明(卡槽②)与 tool 槽成对;名/描述/条数校验', () => {+ it('工具详单必须有 tool 槽;空槽按零能力兼容;名/描述/条数校验', () => {const withTools = (slots: string[], tools: unknown) =>validateGhostManifest({ ...goodChipManifest(), slots, tools });- // 成对:有 tool 槽必须有 tools,反之亦然- expect(validateGhostManifest({ ...goodChipManifest(), slots: ['panel', 'tool'] }).ok).toBe(- false,- );+ // 旧包只写 tool 槽但没有详单,可以安装,运行时不获得工具能力。+ const emptyTool = validateGhostManifest({ ...goodChipManifest(), slots: ['panel', 'tool'] });+ expect(emptyTool.ok).toBe(true);+ if (emptyTool.ok) expect(emptyTool.manifest.tools).toBeUndefined();+ // 有详单仍必须有对应槽。expect(withTools(['panel'], [{ name: 'x', description: 'y' }]).ok).toBe(false);// 合法expect(withTools(['panel', 'tool'], [{ name: 'gen_image', description: '生成图片' }]).ok).toBe(@@ -1483,16 +1573,15 @@ describe('ghost · 芯片型清单(schemaVersion 2)', () => {}});- it('@ 资源入口复用 tool 槽,不新增硬白名单 slot', () => {- expect(GHOST_SLOTS).not.toContain('at-resource');- expect(- validateGhostManifest({- ...goodChipManifest(),- slots: ['panel', 'tool', 'at-resource'],- tools: [{ name: 'search_issues', description: '只读搜索议题' }],- atResourceProvider: { tool: 'search_issues' },- }).ok,- ).toBe(false);+ it('@ 资源入口复用 tools;同名未知 v2 slot 只提示、不授权', () => {+ const result = validateGhostManifest({+ ...goodChipManifest(),+ slots: ['panel', 'tool', 'at-resource'],+ tools: [{ name: 'search_issues', description: '只读搜索议题' }],+ atResourceProvider: { tool: 'search_issues' },+ });+ expect(result.ok).toBe(true);+ if (result.ok) expect(result.unsupportedLegacySlots).toEqual(['at-resource']);});it('@ 资源入口复用原工具执行权,但作为新增调用入口单独披露', () => {@@ -1613,7 +1702,7 @@ describe('ghost · 芯片型清单(schemaVersion 2)', () => {expect(validateGhostManifest(noHtml).ok).toBe(false);});- it('mainView 与 main-view 槽严格成对,并强制最低 Cindy 版本', () => {+ it('v2 mainView 与 main-view 槽严格成对,最低版本保持可选', () => {expect(GHOST_MAIN_VIEW_ICONS).toEqual(['puzzle','globe',@@ -1644,8 +1733,8 @@ describe('ghost · 芯片型清单(schemaVersion 2)', () => {...goodChipManifest(),slots: ['panel', 'main-view'],mainView: { html: 'main-view.html' },- }),- ).toMatchObject({ ok: false, reason: expect.stringContaining('minCindyVersion') });+ }).ok,+ ).toBe(true);expect(validateGhostManifest({...goodChipManifest(),@@ -2079,12 +2168,12 @@ describe('ghost · model → cindy 旧名兼容(2026-07-11 更名)', () => {model: { image: ['generate'] },});expect(v.ok, JSON.stringify(v)).toBe(true);- expect(v.ok && v.manifest.slots).toEqual(['panel', 'cindy']);+ expect(v.ok && v.manifest).not.toHaveProperty('slots');expect(v.ok && v.manifest.cindy).toEqual({ image: ['generate'] });expect(v.ok && (v.manifest as unknown as Record<string, unknown>).model).toBeUndefined();});- it("新旧名并存时以 cindy 为准;'model' 与 'cindy' 同列 slots 视为重复", () => {+ it("新旧字段并存时以 cindy 为准;无详单的 model/cindy 槽同时丢弃", () => {const both = validateGhostManifest({...goodChipManifest(),slots: ['panel', 'cindy'],@@ -2097,7 +2186,8 @@ describe('ghost · model → cindy 旧名兼容(2026-07-11 更名)', () => {...goodChipManifest(),slots: ['panel', 'model', 'cindy'],});- expect(dup.ok).toBe(false);+ expect(dup.ok).toBe(true);+ if (dup.ok) expect(dup.manifest.cindy).toBeUndefined();});});@@ -2495,13 +2585,12 @@ describe('ghost · 逐项权限清单', () => {expect(d.builtinOauthClientChanged).toBe(false);});- it('diff:新增 main-view 作为独立权限进入更新确认', () => {+ it('diff:新增 mainView 作为独立能力进入差异结果', () => {const previous = fullChip();const next: GhostManifest = {...previous,version: '2.0.0',minCindyVersion: '1.2.3',- slots: [...previous.slots, 'main-view'],mainView: { title: '工作台', html: 'main-view.html' },};@@ -3389,12 +3478,18 @@ describe('ghost · network 详单校验', () => {}});- it('badge 槽是**可证明**的新声明:老包不可能带它(未知槽名一律拒装)', () => {- // slots 是硬白名单,当年装老包的客户端遇到未登记的 'badge' 会直接拒绝整份清单。- // 所以「清单里有 badge 槽」⇒「这份清单是本能力上线之后写的」,严格校验才安全。- const r = validateGhostManifest({ ...goodManifest(), slots: ['panel', 'not-a-real-slot'] });- expect(r.ok).toBe(false);- if (!r.ok) expect(r.reason).toContain('未知卡槽');+ it('格式合法的未知 v2 slot 只作为安装提示,不进入运行时或权限', () => {+ const r = validateGhostManifest({+ ...goodManifest(),+ slots: ['panel', 'tool', 'not-a-real-slot'],+ });+ expect(r.ok).toBe(true);+ if (!r.ok) return;+ expect(r.manifest).not.toHaveProperty('slots');+ expect(r.unsupportedLegacySlots).toEqual(['not-a-real-slot']);+ expect(ghostPermissionItems(r.manifest).map((item) => item.key)).not.toContain(+ 'not-a-real-slot',+ );});it('来源投影丢掉 badge 槽时,包里的 badge 必须被识别成「未审权限」', () => {@@ -3846,10 +3941,12 @@ describe('ghost · 2026-07-23 通用能力四件套(session-context / pick / preexpect(withNode({ ...nodeBase, entries: ['../evil.cjs'] }).ok).toBe(false);});- it('preview 槽与详单严格成对;hosts 语法同 network 白名单', () => {+ it('preview 详单必须有槽;空槽按零能力兼容;hosts 语法同 network 白名单', () => {const base = goodChipManifest();- // 有槽必有详单- expect(validateGhostManifest({ ...base, slots: ['panel', 'preview'] }).ok).toBe(false);+ // 旧包空槽可以安装,但不产生 preview 能力。+ const emptyPreview = validateGhostManifest({ ...base, slots: ['panel', 'preview'] });+ expect(emptyPreview.ok).toBe(true);+ if (emptyPreview.ok) expect(emptyPreview.manifest.preview).toBeUndefined();// 有详单必有槽expect(validateGhostManifest({ ...base, preview: { hosts: ['example.com'] } }).ok).toBe(false);const good = validateGhostManifest({@@ -3928,13 +4025,13 @@ describe('ghost · 2026-07-23 通用能力四件套(session-context / pick / pre);});- it('ios-simulator 槽必须声明最低 Cindy 版本', () => {+ it('v2 ios-simulator 槽不强制补写最低 Cindy 版本', () => {const r = validateGhostManifest({...goodChipManifest(),slots: ['panel', 'ios-simulator'],});- expect(r.ok).toBe(false);- if (!r.ok) expect(r.reason).toContain('minCindyVersion');+ expect(r.ok).toBe(true);+ if (r.ok) expect(r.manifest.iosSimulator).toBe(true);});it('ghostPreviewUrlAllowed:https + 白名单命中放行;http 仅 loopback;凭证/越界/畸形拒', () => {@@ -4131,11 +4228,14 @@ describe('ghost · skill 槽(捆绑 Agent Skills,2026-07-25)', () => {validateGhostManifest({ ...goodChipManifest(), slots, skill });const goodItems = [{ dir: 'skills/foo', name: 'foo', description: '教 Agent 用 foo' }];- it('槽与详单严格成对;合法声明原样收录', () => {- // 有槽必有详单- expect(validateGhostManifest({ ...goodChipManifest(), slots: ['panel', 'skill'] }).ok).toBe(- false,- );+ it('skill 详单必须有槽;空槽按零能力兼容;合法声明原样收录', () => {+ // 旧包空槽可以安装,但不产生 skill 能力。+ const emptySkill = validateGhostManifest({+ ...goodChipManifest(),+ slots: ['panel', 'skill'],+ });+ expect(emptySkill.ok).toBe(true);+ if (emptySkill.ok) expect(emptySkill.manifest.skill).toBeUndefined();// 有详单必有槽expect(validateGhostManifest({ ...goodChipManifest(), skill: { items: goodItems } }).ok).toBe(false,diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.tsindex 040453b923..3fba76473d 100644--- a/apps/desktop/src/shared/ghost.ts+++ b/apps/desktop/src/shared/ghost.ts@@ -1,7 +1,9 @@import {GHOST_LOCALES,+ GHOST_MANIFEST_V3_MIN_CINDY_VERSION,GHOST_MANIFEST_SUMMARY_MAX_CHARS,GHOST_OAUTH_SCOPES_MAX,+ compareCindyVersions,isValidCindyVersion,type GhostLocale,type GhostManifestLocales,@@ -16,8 +18,9 @@ import type { IOSSimulatorPublicInstance, IOSSimulatorPublicRouteStatus } from '** 跨模块安全与布局不变量见 docs/dev-rules/architecture-invariants.md / docs/dev-rules/plugin-security-and-authoring.md:* - `.cindy` 是一个 zip 压缩包,根部放一份 `ghost.json` 清单(身份卡);- * - 意识只有一种形态(2026-07-12 Lizi 定案):`kind: 'chip'`、schemaVersion 2,- * 带代码,跑在独立沙箱进程,slots 白名单声明能力,注入必弹权限清单。+ * - 意识只有一种形态(2026-07-12 Lizi 定案):`kind: 'chip'`,带代码并运行在+ * 独立沙箱进程。schemaVersion 3 由直接字段声明能力;schemaVersion 2 的+ * `slots` 只在解析边界兼容,进入运行时前会规范化掉。* 早期无代码的声明型(declaration, v1)已* 整体移除——Lizi 确认无存量包,不留兼容层(对齐 07-08"无曾用名兼容"* 先例);原规划的"经验"档(提示词层)同日取消,场景由 Skill 体系覆盖;@@ -40,7 +43,7 @@ export const GHOST_MANIFEST_MAX_BYTES = 256 * 1024;export const GHOST_INSTALL_MANIFEST_MAX_BYTES = 256 * 1024;/** ghost.json 的 description / whenToUse 字符上限,正本在 plugin-protocol。 */-export { GHOST_MANIFEST_SUMMARY_MAX_CHARS };+export { GHOST_MANIFEST_SUMMARY_MAX_CHARS, GHOST_MANIFEST_V3_MIN_CINDY_VERSION };/** 意识文件扩展名。 */export const CINDY_FILE_EXT = '.cindy';@@ -77,8 +80,8 @@ 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)。- * 数量随迭代增长,以本数组为准——正文不再写死个数。+ * schemaVersion 2 能力名清单,仅用于兼容旧包+ * (docs/dev-rules/plugin-security-and-authoring.md)。* 'cindy' = 请 Cindy 本体代办(借主机自带 AI 能力干活;2026-07-11 Lizi 定案* 由 'model' 更名——本质是 Cindy 在干活,与选模型无关;旧名在校验层作* 静默别名兼容,已装老包不消失)。@@ -127,7 +130,7 @@ const GHOST_ID_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;* 指令由主 Agent 以**用户全部权限**执行、对所有项目与会话生效、不受插件沙箱* 约束,也不随"某工作目录停用本插件"而隐藏——仅全局停用/卸载才撤链。因此* manifest 全声明式(items 的 name/description 必须与 SKILL.md frontmatter 逐字- * 一致,打包与装入双侧强制),装入确认框逐条列出并置于清单最上部。+ * 一致,打包与装入双侧强制),插件详情逐条列出并置于能力清单最上部。* 'workspace' = 工作区会话(2026-07-25):插件请主机在指定本机项目目录下确保* 存在一个会话入口并显示在侧边栏——目录下已有 active 会话即复用,没有才创建* 空 draft 会话(不拉起 agent 进程)。目录授权两条路:系统选文件夹窗口亲选@@ -138,8 +141,12 @@ const GHOST_ID_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;* 脱敏状态摘要并请求 Host 打开既有模拟器面板。视频帧、输入、viewer lease、* UDID、Sidecar 路径/进程与任意 sessionId 均不跨插件边界;实际 WDA / Native* 路由、生命周期、恢复与 fallback 仍完全由 Host 管理。+ *+ * 以下名称只用于 schemaVersion 2 的兼容解析。schemaVersion 3 已移除 slots,+ * 运行时统一使用 GhostManifest 上的直接字段;未知 v2 slot 只用于兼容诊断,+ * 不会被猜测为某个能力,也不会阻止安装。*/-export const GHOST_SLOTS = [+const LEGACY_GHOST_SLOTS = ['subscribe','tool','card',@@ -161,12 +168,15 @@ export const GHOST_SLOTS = ['workspace','ios-simulator',] as const;-export type GhostSlot = (typeof GHOST_SLOTS)[number];+type LegacyGhostSlot = string;++/** v2 slot 只在兼容解析入口出现;这里只限制可安全显示和传输的名称形状。 */+const GHOST_SLOT_NAME_RE = /^[a-z][a-z0-9._:-]{0,127}$/;/*** Card 槽能力详单。card 槽默认仅允许渲染静态/交互卡片(含按钮动作);* externalLinks: true 额外允许卡片声明 data-ghost-link 外链,点击经宿主- * 确认框后 openExternal——这是独立加档权限,装入确认时单列。+ * 确认框后 openExternal——这是独立加档权限,插件详情中单列。*/export interface GhostCardNeeds {externalLinks?: boolean;@@ -177,11 +187,11 @@ export interface GhostCardNeeds {** 申请 `agent` 槽默认只允许消费宿主在真实用户点击插件卡片时签发的* 一次性通行票。`background: true` 额外允许插件在没有当次点击票据时,- * 对已经由用户建立过关联的会话发起回合;这是更高一档权限,安装时单列。+ * 对已经由用户建立过关联的会话发起回合;这是更高一档权限,插件详情中单列。** `errand: true` = 派活取件(2026-07-31 开闸):允许插件把任务交给 Cindy* agent 在**插件专属 errand 会话**里跑一轮,并把最终回复文字取回。与- * background 同为高风险加档,安装时单列。安全边界(全部主机代码强制):+ * background 同为高风险加档,插件详情中单列。安全边界(全部主机代码强制):* - 任务文本只进普通 user 消息,绝不进 system prompt(与 agent-request 同纪律);* - errand 会话默认跑在专属对话目录、权限档默认 plan(只读);用户可在* 设置里按插件放开到 acceptEdits/auto,**永不提供 bypassPermissions**@@ -204,7 +214,7 @@ export interface GhostAgentNeeds {* 没有任何直接建任务的通道(scheduleSlot 只广播,不碰 storage;有测试钉住)。* - 落成的任务是一条**普通 agent 自动化**:执行者是 AI 会话,不是插件。插件在* 其中的角色是「被这条任务调用的目标」,靠已有的 tool 槽 + ghost_call 被叫到。- * - 因此它**会消耗用户的模型额度** —— 装入确认必须说出口。+ * - 因此它**会消耗用户的模型额度** —— 插件详情必须说清楚。** 为什么挂在 agent 详单而不是新开一个 slot:* 语义上它就是「让 agent 定期替我干活」,属 agent 槽;而判据的可证明性与新 slot@@ -220,7 +230,7 @@ export interface GhostAgentNeeds {export const GHOST_NODE_PROTOCOLS = ['json-rpc-stdio', 'mcp-stdio'] as const;export type GhostNodeProtocol = (typeof GHOST_NODE_PROTOCOLS)[number];-/** Node 工作进程生命周期;常驻档会在安装确认中单列高风险权限。 */+/** Node 工作进程生命周期;常驻档会在插件详情中单列高风险能力。 */export const GHOST_NODE_LIFECYCLES = ['on-demand', 'resident'] as const;export type GhostNodeLifecycle = (typeof GHOST_NODE_LIFECYCLES)[number];@@ -246,7 +256,7 @@ export function isGhostNodeMcpReservedMethod(method: string): boolean {export interface GhostNodeSecretBinding {/** 凭证键(插件内唯一):小写字母开头,允许小写/数字/下划线,1–32。 */key: string;- /** 给用户看的名称(安装确认与设置状态使用)。 */+ /** 给用户看的名称(插件详情与设置状态使用)。 */label: string;/** 允许注入的 JSON-RPC 方法白名单(1–16 条)。 */methods: string[];@@ -282,13 +292,13 @@ export interface GhostNodeNeeds {* (spawnEntry)请求宿主再启动一个**已申报入口**(entry / entries 之内)的* 原样 stdio 子进程,并把子进程 stdio 字节中继回 worker。给 Maker Runtime* 这类"自己 spawn process.execPath"的库改道用——正式包关 RunAsNode,- * 那条路生出来的不是 Node。默认关;开了会在装入确认框单列一行。+ * 那条路生出来的不是 Node。默认关;开了会在插件详情单列一行。* 权限本质不变:仍只能跑包内申报过的 JS,node 槽本就是用户级执行权。*/childSpawn?: boolean;/*** 由主机 safeStorage 持久化、按声明的方法临时注入 Worker 的凭证。- * 这是 Node 高风险能力的一部分,安装权限清单会逐条披露。+ * 这是 Node 高风险能力的一部分,插件详情会逐条披露。*/secretBindings?: GhostNodeSecretBinding[];}@@ -481,7 +491,7 @@ export type GhostModelVideoAction = (typeof GHOST_MODEL_VIDEO_ACTIONS)[number];* 为什么单独成一档能力(而非跟着 image.edit 白送):它是本槽唯一**不经模型、* 不花钱**的入仓通道。声明了 network 槽的意识本就能从白名单域拉字节入仓* (as:'media'),寄存把同样的"写你的媒体库"能力给了没有 network 槽的意识,- * 因此必须在装入确认框里单独露出、由用户单独点头。+ * 因此必须在插件详情里作为独立能力露出,并由运行期 Host 严格守门。** 同一能力键同时授权 `release_media`(撤回自己寄存的那条引用):配额有上限,* 没有撤回口的配额等于"用满即永久坏掉",不成立。撤回只删本意识的寄存引用,@@ -535,7 +545,7 @@ export type GhostCindySearchAction = (typeof GHOST_CINDY_SEARCH_ACTIONS)[number]* 向主机点哪几类代办"——类目与动作之外只有**意图级**字段(oneshotModel 偏好,* 2026-08-05 起),**不构成任何硬依赖**(选型权在主机的解析表:调用时显式点名 >* 用户在详情页的钉档(意识专属覆盖)> 意识声明的偏好模型 > 用户能力偏好 >- * 出厂默认;意识只表达意图,永不腐烂)。装入确认框与代办资格审共同消费。+ * 出厂默认;意识只表达意图,永不腐烂)。插件详情与代办资格审共同消费。*/export interface GhostCindyNeeds {/** 图像类:generate=出图,edit=改图(改图仅限本意识名下媒体)。 */@@ -733,8 +743,8 @@ export const GHOST_OAUTH_RESERVED_AUTHORIZE_PARAMS: readonly string[] = [/*** OAuth 凭证声明(source: 'oauth',2026-07-13 与 Lizi 定案"通用声明式"):* 平台不预设 provider 名单——意识声明"去哪授权、要什么 scope",clientId /- * clientSecret 由用户在意识设置页自填(经 /oauth 只写通道入库),装入确认框- * 全量展示授权域名与 scopes,用户知情自担。声明化的是**参数**不是**代码**:+ * clientSecret 由用户在意识设置页自填(经 /oauth 只写通道入库),插件详情+ * 全量展示授权域名与 scopes。声明化的是**参数**不是**代码**:* 授权流程(拉浏览器、loopback 回调、state/PKCE 校验、code 换 token、刷新)* 永远由主机可信代码执行(cindy-brain/ghostOauthFlow.ts),意识无从插手,* access / refresh token 与 client 凭证全程不进沙箱,注入按 inject 声明由@@ -882,7 +892,7 @@ export type GhostSecretSource = (typeof GHOST_SECRET_SOURCES)[number];export interface GhostSecretDecl {/** 凭证键(意识内唯一):小写字母开头,允许小写/数字/下划线,1–32。 */key: string;- /** 给用户看的名称(装入确认框展示)。 */+ /** 给用户看的名称(插件详情展示)。 */label: string;/** 凭证值来源;缺省 'user'(校验归一化:'user' 不落清单)。 */source?: GhostSecretSource;@@ -982,7 +992,7 @@ export const GHOST_SCHEDULE_DRAFT_MIN_INTERVAL_SUGGESTION_MS = 30 * 60_000;* preview 槽详单(与 slots 含 'preview' 严格成对——有槽必有详单:范围是* 本能力的全部知情面,不允许"先装后说")。hosts 语法与 network 域名白名单* 一致(支持 `*.` 单层前缀通配),另特批 loopback 单段名(本地 dev server- * 是预览的正当主场,network 语法"至少两段"表达不了它)。装入确认框逐条展示。+ * 是预览的正当主场,network 语法"至少两段"表达不了它)。插件详情逐条展示。*/export interface GhostPreviewNeeds {hosts: string[];@@ -1018,13 +1028,13 @@ export const GHOST_MANUAL_MD_MAX_BYTES = 64 * 1024;/** manual:一级索引说明的字符上限。 */export const GHOST_MANUAL_DESCRIPTION_MAX_CHARS = GHOST_MANIFEST_SUMMARY_MAX_CHARS;-/** skill 槽单条技能声明(全声明式:确认框展示的就是这里的字段)。 */+/** skill 槽单条技能声明(全声明式:插件详情展示的就是这里的字段)。 */export interface GhostSkillItem {/** 包内技能目录(安全相对路径,目录内必须有 SKILL.md)。 */dir: string;/*** 技能名。必须与 SKILL.md frontmatter 的 name 逐字一致(打包与装入双侧- * 强制)——确认框里用户看到的,必须就是 Agent 实际读到的。+ * 强制)——详情里用户看到的,必须就是 Agent 实际读到的。*/name: string;/** 技能说明。必须与 SKILL.md frontmatter 的 description 逐字一致(同上)。 */@@ -1033,7 +1043,7 @@ export interface GhostSkillItem {/*** skill 槽详单(与 slots 含 'skill' 严格成对——有槽必有详单:捆绑了什么技能- * 是本能力的全部知情面,不允许"先装后说")。装入确认框逐条展示。+ * 是本能力的全部知情面,不允许隐藏声明)。插件详情逐条展示。*/export interface GhostSkillNeeds {items: GhostSkillItem[];@@ -1349,8 +1359,8 @@ export function isGhostSetupErrorCode(value: unknown): value is GhostSetupErrorC/** ghost.json 清单(不变量由 validateGhostManifest 保证)。 */export interface GhostManifest {- /** 清单格式版本,恒 2(v1 声明型已于 2026-07-12 移除,无存量不留兼容)。 */- schemaVersion: 2;+ /** 原始清单格式版本;v2 已在解析边界投影成与 v3 相同的直接字段。 */+ schemaVersion: 2 | 3;/** 唯一标识,同时是安装目录名与 panelKind 后缀。 */id: string;/** 展示名。 */@@ -1373,7 +1383,7 @@ export interface GhostManifest {resolvedLocale?: SupportedLocale;/*** 意识自我介绍(1–300 字,仅展示用):这段意识是干嘛- * 的、给谁用。装入确认框与详情页展示;与 tools[].description(给 AI 看的+ * 的、给谁用。插件详情页展示;与 tools[].description(给 AI 看的* 工具说明)职责不同,后者不因本字段缺省而顶上。*/description?: string;@@ -1399,9 +1409,9 @@ export interface GhostManifest {entry: string;/** 电子脑启动模式;缺省 = 'on-demand'(被需要才拉起)。 */launch?: GhostLaunchMode;- /** Agent 新回合能力详单;须与 slots 中的 `agent` 成对。 */+ /** Agent 新回合能力;空对象表示只允许真实用户点击触发。 */agent?: GhostAgentNeeds;- /** 随包本地 Node 工作进程详单;须与 slots 中的 `node` 成对。 */+ /** 随包本地 Node 工作进程声明。 */node?: GhostNodeNeeds;/*** 设置页「自定义设置区」界面入口(可选;安装目录内相对路径,意识自绘)。@@ -1417,39 +1427,35 @@ export interface GhostManifest {* 页用它避免抖动)。须与 settingsHtml 成对声明。*/settingsHeight?: number;- /** 能力白名单(没声明的槽,运行时接口不存在)。 */- slots: GhostSlot[];/**- * card 槽能力详单(与 slots 含 'card' 成对;缺省 = 仅渲染,无外链)。+ * 卡片能力;空对象表示基础卡片渲染。* externalLinks: true 时卡片内可声明 data-ghost-link,点击经宿主确认框后打开浏览器。*/card?: GhostCardNeeds;- /** 注册给 agent 的工具声明(与 slots 含 'tool' 成对)。 */+ /** 注册给 agent 的工具声明;字段本身就是能力声明。 */tools?: GhostToolDecl[];/** `@` 面板入口由已安装插件的 command 提供;不支持资源搜索字段。 *//**- * cindy 槽能力详单(与 slots 含 'cindy' 成对;缺省 = 零能力,任何代办- * 都会被拒并提示作者补声明)。清单里的旧字段名 model 在校验层作别名- * 收入本字段。+ * Cindy 代办能力及范围。v2 清单里的旧字段名 model 在兼容校验层收入本字段。*/cindy?: GhostCindyNeeds;/**- * 订阅槽详单(与 slots 含 'subscribe' 成对;缺省 = 零事件)。+ * 订阅能力与事件范围。* hooks 非空时 launch 必须为 'resident'(校验强制)。*/subscribe?: GhostSubscribeNeeds;/**- * network 槽详单(与 slots 含 'network' 成对;缺省 = 零能力)。- * 域名白名单 + 凭证声明,装入确认框逐项展示,运行期主机代发并守门。+ * 网络能力与范围。+ * 域名白名单 + 凭证声明,插件详情逐项展示,运行期主机代发并守门。*/network?: GhostNetworkNeeds;/**- * preview 槽详单(与 slots 含 'preview' 严格成对):可在右侧栏内置浏览器+ * 预览能力:可在右侧栏内置浏览器* 打开预览标签页的域名白名单。*/preview?: GhostPreviewNeeds;/**- * skill 槽详单(与 slots 含 'skill' 严格成对):随包捆绑的 Agent Skills 清单。+ * 随包捆绑的 Agent Skills 清单。* 启用时主机链接进共享技能根,Claude Code 与 Codex 双端可见;字段不参与* 本地化(必须与 SKILL.md 逐字一致,见 GhostSkillItem)。*/@@ -1480,8 +1486,21 @@ export interface GhostManifest {keywords?: string[];/** 面板声明;没有面板的意识(如纯工具意识)可省略。 */panel?: GhostPanelDecl;- /** 应用级主视图声明;须与 slots 中的 `main-view` 成对。 */+ /** 应用级主视图声明;v3 直接声明,v2 与 `main-view` slot 成对。 */mainView?: GhostMainViewDecl;+ /** 无配置的 Host 能力只接受字面量 true;不需要时省略。 */+ notify?: true;+ badge?: true;+ confirm?: true;+ fs?: true;+ /** 持久作品库;卸载不删数据,位置和删除由 Host 设置页管理。 */+ library?: true;+ sessionContext?: true;+ pick?: true;+ workspace?: true;+ iosSimulator?: true;+ /** v3 未知字段为前向兼容原样保留,但 Host 不解释也不授权。 */+ [key: string]: unknown;}/**@@ -1519,21 +1538,21 @@ export interface GhostManifestLocaleResource {export const GHOST_LOCALE_MAX_BYTES = 64 * 1024;/**- * Host 对插件安装状态的批准结论。+ * Host 对插件安装记录完整性的验证结论。*- * `approved` 的 revision 由 Main 在一次完整安装/更新确认事务中生成;另外两态- * 都不构成运行授权,更新 UI 必须把目标包的全部权限按新增项重新展示。+ * `approved` 的 revision 由 Main 在真实包通过校验并原子落位后生成,不表示用户+ * 另行批准了插件能力;另外两态都不能运行,需要通过市场或 `.cindy` 重新安装。*/export type GhostInstallApproval ={ state: 'approved'; revision: string } | { state: 'legacy-unapproved' } | { state: 'invalid' };-/** 把批准态投影成跨进程更新事务使用的稳定 token。 */+/** 把安装验证态投影成跨进程更新事务使用的稳定 token。 */export function ghostInstallApprovalToken(approval: GhostInstallApproval | undefined): string {if (approval?.state === 'approved') return `approved:${approval.revision}`;return approval?.state ?? 'legacy-unapproved';}-/** 更新 IPC 只接受 Host 列表曾下发过的批准态 token。 */+/** 更新 IPC 只接受 Host 列表曾下发过的安装验证 token。 */export function isGhostInstallApprovalToken(value: unknown): value is string {return (value === 'legacy-unapproved' ||@@ -1618,25 +1637,22 @@ export function ghostContentKeys(manifest: GhostManifest): string[] {if (manifest.panel) keys.push('panel');if (manifest.settingsHtml) keys.push('settingsUi');keys.push('code');- for (const slot of manifest.slots) {- if (slot === 'cindy') keys.push('slotCindy');- else if (slot === 'agent') keys.push('slotAgent');- else if (slot === 'node') keys.push('slotNode');- else if (slot === 'tool') keys.push('slotTool');- else if (slot === 'subscribe') keys.push('slotSubscribe');- else if (slot === 'card') keys.push('slotCard');- else if (slot === 'network') keys.push('slotNetwork');- else if (slot === 'notify') keys.push('slotNotify');- else if (slot === 'badge') keys.push('slotBadge');- else if (slot === 'confirm') keys.push('slotConfirm');- else if (slot === 'fs') keys.push('slotFs');- else if (slot === 'library') keys.push('slotLibrary');- // skill 是信任面最高的内容(给主 Agent 灌指令),详情页必须如实露出。- else if (slot === 'skill') keys.push('slotSkill');- else if (slot === 'workspace') keys.push('slotWorkspace');- else if (slot === 'ios-simulator') keys.push('slotIOSSimulator');- // 'panel' 槽已由 manifest.panel 覆盖,不重复- }+ if (manifest.cindy) keys.push('slotCindy');+ if (manifest.agent) keys.push('slotAgent');+ if (manifest.node) keys.push('slotNode');+ if (manifest.tools) keys.push('slotTool');+ if (manifest.subscribe) keys.push('slotSubscribe');+ if (manifest.card) keys.push('slotCard');+ if (manifest.network) keys.push('slotNetwork');+ if (manifest.notify === true) keys.push('slotNotify');+ if (manifest.badge === true) keys.push('slotBadge');+ if (manifest.confirm === true) keys.push('slotConfirm');+ if (manifest.fs === true) keys.push('slotFs');+ if (manifest.library === true) keys.push('slotLibrary');+ // skill 是信任面最高的内容(给主 Agent 灌指令),详情页必须如实露出。+ if (manifest.skill) keys.push('slotSkill');+ if (manifest.workspace === true) keys.push('slotWorkspace');+ if (manifest.iosSimulator === true) keys.push('slotIOSSimulator');return keys;}@@ -1715,7 +1731,7 @@ export function isCindyAccountGhostId(id: string): boolean {}/**- * 装入确认框的单项权限。+ * 插件详情页的单项能力说明。* 纯数据描述:renderer 拼 `settings.ghosts.perm.<labelKey>` 翻译,`detail` 是* 作者自由文本(如工具描述)如实展示不翻译,`detailKey` 是主机固定说明的* i18n 后缀(如可执行代码的沙箱说明)——两者互斥。@@ -1776,8 +1792,8 @@ const GHOST_CINDY_PERM_LABEL: Record<string, string> = {/*** cindy 详单能力键 → 主机固定补充说明的 labelKey(可选;没有条目就不带 detail)。- * 寄存是唯一"写你的媒体库"的能力,上限必须在确认框里如实写出来(媒体规则:- * 装入确认要展示持久媒体占用上限)。+ * 寄存是唯一"写你的媒体库"的能力,上限必须在详情里如实写出来(媒体规则:+ * 能力说明要展示持久媒体占用上限)。*/const GHOST_CINDY_PERM_DETAIL: Record<string, string> = {'media.deposit': 'cindyMediaDepositDetail',@@ -1801,7 +1817,7 @@ function formatGhostQuotaSize(bytes: number): string {}/**- * 从身份卡静态推导逐项权限清单(装入前无需运行任何意识代码)。+ * 从身份卡静态推导插件详情使用的逐项能力说明。* 顺序即展示顺序:Cindy 代办 → 注册工具 → 聊天指令 → 面板 → 订阅/卡片 →* 可执行代码(先能力后载体,与权限展示契约一致)。*/@@ -1866,7 +1882,7 @@ export function ghostPermissionItems(manifest: GhostManifest): GhostPermissionItkind: 'cindy',labelKey,...(detailKey ? { detailKey } : {}),- // 寄存上限由常量单源插值进确认框说明(媒体规则要求装入确认展示+ // 寄存上限由常量单源插值进详情说明(媒体规则要求能力说明展示// 持久媒体占用上限);改常量四份 locale 自动跟随。...(cap === 'media.deposit'? { detailArgs: { quota: formatGhostQuotaSize(GHOST_CINDY_DEPOSIT_QUOTA_BYTES) } }@@ -1893,7 +1909,7 @@ export function ghostPermissionItems(manifest: GhostManifest): GhostPermissionIt});}// agent 槽:真人点击触发是基础档;后台自动触发另列一项高风险权限。- if (manifest.slots.includes('agent')) {+ if (manifest.agent) {items.push({key: 'agent:user-action',kind: 'agent',@@ -1934,7 +1950,7 @@ export function ghostPermissionItems(manifest: GhostManifest): GhostPermissionIt}// Node 是本机用户级执行权,不与浏览器沙箱的 `code` 混称。基础执行与// 常驻分别列出,用户能看懂“能运行”与“会一直运行”是两件事。- if (manifest.slots.includes('node') && manifest.node) {+ if (manifest.node) {items.unshift({key: 'node:execute',kind: 'node',@@ -2057,12 +2073,12 @@ export function ghostPermissionItems(manifest: GhostManifest): GhostPermissionIt// fs 槽:写文件是仅次于出网的敏感能力,紧随 network 之后展示。三档目的地// 与确认规则由 detailKey 的固定说明一次讲清(私有目录免确认/工作目录跟随// 会话权限/其它目录逐次确认),让用户装入前就知道边界在哪。- if (manifest.slots.includes('fs')) {+ if (manifest.fs === true) {items.push({ key: 'fs', kind: 'fs', labelKey: 'fsWrite', detailKey: 'fsWriteDetail' });}- // library 槽:持久作品库(用户数据语义,不是临时缓存)。装入时必须讲清+ // library 能力:持久作品库(用户数据语义,不是临时缓存)。详情页必须讲清// 三件事:卸载不删、删除走独立确认、数据库只收参数化语句。- if (manifest.slots.includes('library')) {+ if (manifest.library === true) {items.push({key: 'library',kind: 'library',@@ -2072,12 +2088,12 @@ export function ghostPermissionItems(manifest: GhostManifest): GhostPermissionIt}// pick 槽:能弹系统选文件夹窗口。授权动作是用户亲手选中,装入时只告知// "它会来要"。- if (manifest.slots.includes('pick')) {+ if (manifest.pick === true) {items.push({ key: 'pick', kind: 'pick', labelKey: 'pick', detailKey: 'pickDetail' });}// workspace 槽:能为指定项目目录创建/复用侧边栏会话入口。授权动作是用户// 亲选目录或点确认卡,装入时只告知"它会来要"。- if (manifest.slots.includes('workspace')) {+ if (manifest.workspace === true) {items.push({key: 'workspace',kind: 'workspace',@@ -2086,7 +2102,7 @@ export function ghostPermissionItems(manifest: GhostManifest): GhostPermissionIt});}// 内置模拟器槽只给脱敏状态与 Host 面板入口;视频、输入和进程控制都不授权。- if (manifest.slots.includes('ios-simulator')) {+ if (manifest.iosSimulator === true) {items.push({key: 'ios-simulator',kind: 'ios-simulator',@@ -2096,7 +2112,7 @@ export function ghostPermissionItems(manifest: GhostManifest): GhostPermissionIt}// session-context 槽:派活时可获知当前会话的项目目录位置(路径信息,// 非文件访问权;node 槽的执行权另行单列)。- if (manifest.slots.includes('session-context')) {+ if (manifest.sessionContext === true) {items.push({key: 'session-context',kind: 'session-context',@@ -2106,7 +2122,7 @@ export function ghostPermissionItems(manifest: GhostManifest): GhostPermissionIt}// preview 槽:白名单域名如实逐行列出(detail 原样展示作者声明,同 oauth// scopes 风格),用户装入前就看到"它能打开谁的页面"。- if (manifest.slots.includes('preview') && manifest.preview) {+ if (manifest.preview) {items.push({key: 'preview',kind: 'preview',@@ -2150,8 +2166,7 @@ export function ghostPermissionItems(manifest: GhostManifest): GhostPermissionItdetailKey: 'mainViewDetail',});}- for (const slot of manifest.slots) {- if (slot === 'subscribe') {+ if (manifest.subscribe) {// 订阅两档分列:旁听(元数据)常规位;拦截是全部槽里权限最重的一档,// unshift 排到清单最顶(敏感项排最上)。const topics = manifest.subscribe?.topics;@@ -2203,33 +2218,34 @@ export function ghostPermissionItems(manifest: GhostManifest): GhostPermissionIt}items.unshift(...hookItems);}- // 有槽无详单 = 零事件,没有可告知的权限,不列。- } else if (slot === 'card') {- items.push({ key: 'card', kind: 'card', labelKey: 'card' });- if (manifest.card?.externalLinks) {- items.push({- key: 'card:external-link',- kind: 'card',- labelKey: 'cardExternalLink',- detailKey: 'cardExternalLinkDetail',- });- }- } else if (slot === 'notify') {- items.push({ key: 'notify', kind: 'notify', labelKey: 'notify', detailKey: 'notifyDetail' });+ // v2 有槽无详单已在归一化时丢弃,因此这里不存在零事件能力。+ }+ if (manifest.card) {+ items.push({ key: 'card', kind: 'card', labelKey: 'card' });+ if (manifest.card.externalLinks) {+ items.push({+ key: 'card:external-link',+ kind: 'card',+ labelKey: 'cardExternalLink',+ detailKey: 'cardExternalLinkDetail',+ });}}+ if (manifest.notify === true) {+ items.push({ key: 'notify', kind: 'notify', labelKey: 'notify', detailKey: 'notifyDetail' });+ }// 未读角标:与 notify 槽**并列**的独立一档(不是它的子项)——绿点比 toast 克制,// 只想安静点个绿点的意识不该被迫连"能弹全屏顶部提示"一起申请。// key 独立还有一层必要性(同 subscribe 的 activity topic 判例):// diffGhostPermissionItems 按 key + detail 比对,若并进某个固定 key,已装插件// 新增这一档时 added 为空,plugin-market 的扩权确认就不会拦——用户会在毫不// 知情的情况下多给出一个常驻的注意力入口。- if (manifest.slots.includes('badge')) {+ if (manifest.badge === true) {items.push({ key: 'badge', kind: 'notify', labelKey: 'badge', detailKey: 'badgeDetail' });}// confirm 槽:能请主机弹一个二选一确认框(会打断操作)。装入时如实告知"它会来问",// 决定权仍在用户的点击上——detailKey 的固定说明把这层讲清。- if (manifest.slots.includes('confirm')) {+ if (manifest.confirm === true) {items.push({key: 'confirm',kind: 'confirm',@@ -2252,8 +2268,8 @@ export function ghostPermissionItems(manifest: GhostManifest): GhostPermissionIt// - 声明了 network 槽时不能宣称"无网络访问";// - 默认:纯沙箱、无文件无网络。let codeDetailKey: string;- if (manifest.slots.includes('node')) codeDetailKey = 'codeDetailWithNode';- else if (manifest.slots.includes('network')) codeDetailKey = 'codeDetailNetwork';+ if (manifest.node) codeDetailKey = 'codeDetailWithNode';+ else if (manifest.network) codeDetailKey = 'codeDetailNetwork';else codeDetailKey = 'codeDetail';items.push({key: 'code',@@ -2420,27 +2436,26 @@ export function diffInstalledGhostPermissionItems(};}-/**- * 返回未被发布清单或已批准旧版本覆盖的包权限。- *- * 第二个来源用于兼容旧市场元数据:旧详情投影可能漏掉已存在的权限,- * 但这些权限此前已经被用户批准,更新时应继续保留。- *- * 注(receipt 模型整合):receipt 模型下"已批准的旧版本清单"即 receipt 的 manifest,- * 由整合任务①在 packagePermissionReview 落点用 receipt 已批准 manifest 作 baseline;- * 保留本函数以支持 main 现有 market 调用点,不额外引入 previouslyInstalled 认证路径。- */+/** 返回真实包中超出市场声明与既有安装基线的 Host 能力。 */export function unreviewedGhostPermissionItems(reviewed: GhostManifest,previouslyInstalled: GhostManifest | undefined,actual: GhostManifest,): GhostPermissionItem[] {- const approved = new Set(ghostPermissionItems(reviewed).map(ghostPermissionProjectionKey));- for (const item of ghostPermissionItems(previouslyInstalled ?? reviewed)) {+ const reviewedItems = ghostPermissionItems(reviewed);+ const previousItems = ghostPermissionItems(previouslyInstalled ?? reviewed);+ const approved = new Set(reviewedItems.map(ghostPermissionProjectionKey));+ const approvedKeys = new Set(reviewedItems.map((item) => item.key));+ for (const item of previousItems) {approved.add(ghostPermissionProjectionKey(item));+ approvedKeys.add(item.key);}return ghostPermissionItems(actual).filter(- (item) => !approved.has(ghostPermissionProjectionKey(item)),+ (item) =>+ !approved.has(ghostPermissionProjectionKey(item)) &&+ // code 的 detailKey 只是在复述已单列的 network/node 等能力。实际包少一项+ // 能力时文案会降档,但不能因此把“更少能力”反判为扩权。+ !(item.key === 'code' && approvedKeys.has(item.key)),);}@@ -2554,7 +2569,8 @@ export function layoutWithGhostPanel(layout: Layout, manifest: GhostManifest): L}export type ManifestValidation =- { ok: true; manifest: GhostManifest } | { ok: false; reason: string };+ | { ok: true; manifest: GhostManifest; unsupportedLegacySlots: string[] }+ | { ok: false; reason: string };const GHOST_MANIFEST_RESERVED_RECORD_KEYS = new Set(['__proto__', 'constructor', 'prototype']);@@ -2566,6 +2582,196 @@ function isPlainObject(v: unknown): v is Record<string, unknown> {return typeof v === 'object' && v !== null && !Array.isArray(v);}+const GHOST_MANIFEST_KNOWN_TOP_LEVEL_FIELDS = new Set([+ 'schemaVersion',+ 'id',+ 'name',+ 'version',+ 'minCindyVersion',+ 'author',+ 'locales',+ 'resolvedLocale',+ 'description',+ 'whenToUse',+ 'icon',+ 'kind',+ 'entry',+ 'launch',+ 'agent',+ 'node',+ 'settingsHtml',+ 'settingsHeight',+ 'slots',+ 'card',+ 'tools',+ 'cindy',+ 'model',+ 'subscribe',+ 'network',+ 'preview',+ 'skill',+ 'setup',+ 'command',+ 'keywords',+ 'panel',+ 'mainView',+ 'notify',+ 'badge',+ 'confirm',+ 'fs',+ 'library',+ 'sessionContext',+ 'pick',+ 'workspace',+ 'iosSimulator',+]);++const V3_BOOLEAN_CAPABILITY_FIELDS = [+ 'notify',+ 'badge',+ 'confirm',+ 'fs',+ 'library',+ 'sessionContext',+ 'pick',+ 'workspace',+ 'iosSimulator',+] as const;++const V3_DECLARATION_TO_LEGACY_SLOT = [+ ['tools', 'tool'],+ ['card', 'card'],+ ['panel', 'panel'],+ ['mainView', 'main-view'],+ ['subscribe', 'subscribe'],+ ['skill', 'skill'],+ ['cindy', 'cindy'],+ ['agent', 'agent'],+ ['node', 'node'],+ ['network', 'network'],+ ['preview', 'preview'],+] as const;++const V3_BOOLEAN_TO_LEGACY_SLOT: Record<(typeof V3_BOOLEAN_CAPABILITY_FIELDS)[number], string> = {+ notify: 'notify',+ badge: 'badge',+ confirm: 'confirm',+ fs: 'fs',+ library: 'library',+ sessionContext: 'session-context',+ pick: 'pick',+ workspace: 'workspace',+ iosSimulator: 'ios-simulator',+};++type PreparedGhostManifest = {+ raw: Record<string, unknown>;+ schemaVersion: 2 | 3;+ unsupportedLegacySlots: string[];+ v3BaseCard: boolean;+ v3BaseAgent: boolean;+ unknownV3Fields: Record<string, unknown>;+};++function prepareGhostManifestForValidation(+ value: unknown,+): { ok: true; prepared: PreparedGhostManifest } | { ok: false; reason: string } {+ if (!isPlainObject(value)) return { ok: false, reason: '清单不是对象' };+ if (value.schemaVersion !== 2 && value.schemaVersion !== 3) {+ return {+ ok: false,+ reason: `schemaVersion 必须是 2 或 3,得到 ${JSON.stringify(value.schemaVersion)}(v1 声明型已于 2026-07-12 移除)`,+ };+ }++ if (value.schemaVersion === 2) {+ const sourceSlots = Array.isArray(value.slots) ? value.slots : [];+ const unsupportedLegacySlots = sourceSlots.flatMap((slot) => {+ const normalized = slot === 'model' ? 'cindy' : slot;+ return typeof normalized === 'string'+ && !(LEGACY_GHOST_SLOTS as readonly string[]).includes(normalized)+ ? [normalized]+ : [];+ });+ return {+ ok: true,+ prepared: {+ raw: Array.isArray(value.slots)+ ? { ...value, slots: dropEmptyLegacyCapabilitySlots(value, sourceSlots) }+ : value,+ schemaVersion: 2,+ unsupportedLegacySlots,+ v3BaseCard: false,+ v3BaseAgent: false,+ unknownV3Fields: {},+ },+ };+ }++ if (value.slots !== undefined) {+ return { ok: false, reason: 'schemaVersion 3 不再支持 slots;请直接声明对应能力字段' };+ }+ if (value.minCindyVersion === undefined) {+ return { ok: false, reason: 'schemaVersion 3 必须声明 minCindyVersion' };+ }+ for (const field of V3_BOOLEAN_CAPABILITY_FIELDS) {+ if (value[field] !== undefined && value[field] !== true) {+ return { ok: false, reason: `${field} 出现时必须是 true;不需要时请省略` };+ }+ }++ const syntheticSlots: string[] = [];+ for (const [field, slot] of V3_DECLARATION_TO_LEGACY_SLOT) {+ if (value[field] !== undefined) syntheticSlots.push(slot);+ }+ for (const field of V3_BOOLEAN_CAPABILITY_FIELDS) {+ if (value[field] === true) syntheticSlots.push(V3_BOOLEAN_TO_LEGACY_SLOT[field]);+ }+ const v3BaseCard = isPlainObject(value.card) && Object.keys(value.card).length === 0;+ const v3BaseAgent = isPlainObject(value.agent) && Object.keys(value.agent).length === 0;+ const raw: Record<string, unknown> = {+ ...value,+ slots: syntheticSlots,+ ...(v3BaseCard ? { card: undefined } : {}),+ ...(v3BaseAgent ? { agent: undefined } : {}),+ };+ const unknownV3Fields = Object.fromEntries(+ Object.entries(value).filter(+ ([key]) => key === 'model' || !GHOST_MANIFEST_KNOWN_TOP_LEVEL_FIELDS.has(key),+ ),+ );+ return {+ ok: true,+ prepared: {+ raw,+ schemaVersion: 3,+ unsupportedLegacySlots: [],+ v3BaseCard,+ v3BaseAgent,+ unknownV3Fields,+ },+ };+}++/** v2 允许历史上只有名字、没有实际能力详单的 slot;它们不进入运行时模型。 */+function dropEmptyLegacyCapabilitySlots(+ value: Record<string, unknown>,+ slots: unknown[],+): unknown[] {+ return slots.filter((slot) => {+ const normalized = slot === 'model' ? 'cindy' : slot;+ if (normalized === 'tool') return value.tools !== undefined;+ if (normalized === 'panel') return value.panel !== undefined;+ if (normalized === 'cindy') return value.cindy !== undefined || value.model !== undefined;+ if (normalized === 'subscribe') return value.subscribe !== undefined;+ if (normalized === 'node') return value.node !== undefined;+ if (normalized === 'network') return value.network !== undefined;+ if (normalized === 'preview') return value.preview !== undefined;+ if (normalized === 'skill') return value.skill !== undefined;+ return true;+ });+}+/** 当前宿主语言在插件未提供时固定回退英文。 */export function ghostLocalePathFor(manifest: GhostManifest,@@ -3206,18 +3412,14 @@ export function resolveGhostManifestLocale(}/**- * 校验一份解析后的 ghost.json。宽进严出:忽略未知字段(向前兼容),- * 已知字段全部严格检查;任何不合格都给出人类可读 reason。+ * 校验一份解析后的 ghost.json。已知字段严格检查;v2 未知字段忽略,v3 未知+ * 顶层字段原样保留但不解释、不展示、不授权。任何已知字段不合格都给出 reason。*/-export function validateGhostManifest(raw: unknown): ManifestValidation {- if (!isPlainObject(raw)) return { ok: false, reason: '清单不是对象' };-- if (raw.schemaVersion !== 2) {- return {- ok: false,- reason: `schemaVersion 必须是 2,得到 ${JSON.stringify(raw.schemaVersion)}(v1 声明型已于 2026-07-12 移除)`,- };- }+export function validateGhostManifest(value: unknown): ManifestValidation {+ const preparation = prepareGhostManifestForValidation(value);+ if (!preparation.ok) return preparation;+ const prepared = preparation.prepared;+ const raw = prepared.raw;if (!isValidGhostId(raw.id)) {return { ok: false, reason: 'id 必须是 1–32 位小写字母/数字/连字符(不能以连字符开头)' };}@@ -3234,6 +3436,15 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {if (raw.minCindyVersion !== undefined && !isValidCindyVersion(raw.minCindyVersion)) {return { ok: false, reason: 'minCindyVersion 必须是合法的 SemVer 字符串' };}+ if (+ prepared.schemaVersion === 3 &&+ compareCindyVersions(raw.minCindyVersion as string, GHOST_MANIFEST_V3_MIN_CINDY_VERSION) === -1+ ) {+ return {+ ok: false,+ reason: `schemaVersion 3 的 minCindyVersion 不能低于 ${GHOST_MANIFEST_V3_MIN_CINDY_VERSION}`,+ };+ }// kind 可省略(2026-07-12 晚定案:单形态后字段纯冗余,缺省即 chip);// 写了就必须是 chip——写错值仍拒,不静默纠正(规则 9)。if (raw.kind !== undefined && raw.kind !== 'chip') {@@ -3532,35 +3743,23 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {return { ok: false, reason: 'settingsHeight 必须是 160–800 之间的数字' };}}- if (!Array.isArray(raw.slots) || raw.slots.length === 0) {- return { ok: false, reason: '必须声明 slots(非空数组,能力白名单)' };+ if (!Array.isArray(raw.slots)) {+ return { ok: false, reason: 'schemaVersion 2 的 slots 必须是数组' };}- const slots: GhostSlot[] = [];+ const slots: LegacyGhostSlot[] = [];for (const s of raw.slots) {// 旧名兼容:'model' 静默归一化为 'cindy'(2026-07-11 更名,已装老包不消失)。const name = s === 'model' ? 'cindy' : s;- if (typeof name !== 'string' || !(GHOST_SLOTS as readonly string[]).includes(name)) {+ if (typeof name !== 'string' || !GHOST_SLOT_NAME_RE.test(name)) {return {ok: false,- reason: `slots 含未知卡槽 ${JSON.stringify(s)}(可用:${GHOST_SLOTS.join(' / ')})`,+ reason: `slots 含格式非法的卡槽名称 ${JSON.stringify(s)}`,};}- if (slots.includes(name as GhostSlot)) {+ if (slots.includes(name)) {return { ok: false, reason: `slots 含重复卡槽 ${JSON.stringify(s)}` };}- slots.push(name as GhostSlot);- }- // Host-native capabilities cannot be safely ignored by an older Cindy.- // Require an explicit installation/enablement floor for deterministic UX.- if (- (slots.includes('ios-simulator') || slots.includes('main-view')) &&- raw.minCindyVersion === undefined- ) {- const slot = slots.includes('main-view') ? 'main-view' : 'ios-simulator';- return {- ok: false,- reason: `slots 声明了 ${JSON.stringify(slot)} 时必须同时声明 minCindyVersion`,- };+ slots.push(name);}// 声明了面板却没申请 panel 槽(或反之有槽无面板)都是清单自相矛盾。if (panel !== undefined && !slots.includes('panel')) {@@ -3606,9 +3805,9 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {* 纯工具型 / 对话型意识没有可打开的界面,点亮了也无处可点,给了就是骗点击。** **为什么用一个新 slot 而不是 `notify` 下的子字段**(2026-08-03,codex review P1):- * `slots` 是硬白名单——未登记的槽名一律拒装。所以任何**已经装在用户机器上**的- * 老包都不可能带 `badge` 槽:当初装它的客户端会直接拒绝那份清单。这让「新声明」- * 与「老包的同名自定义字段」成为**可证明**可分,而不是靠概率赌。+ * `badge` 引入时 `slots` 还是协议硬白名单,未登记的槽名会被旧客户端拒装。+ * 所以在它引入之前已经装在用户机器上的老包不可能带 `badge` 槽;这让当时的+ * 「新声明」与「老包的同名自定义字段」可证明地区分开,而不是靠概率赌。** 早前的方案把它放在顶层 `notify` 对象里。那个字段在本改动前完全未登记、会被* 校验器静默忽略,于是两头堵:严格校验会让写过同名字段的老包升级后消失(§5 红线),@@ -3688,7 +3887,8 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {// cindy 槽能力详单:与 slots 含 'cindy' 成对(有详单必有槽;有槽无详单// 允许装入但运行时零能力——老包不消失,只是代办被拒并提示作者更新)。// 字段旧名 model 作别名收入(两个都写以 cindy 为准)。- const cindyRaw = raw.cindy !== undefined ? raw.cindy : raw.model;+ const cindyRaw =+ raw.cindy !== undefined ? raw.cindy : prepared.schemaVersion === 2 ? raw.model : undefined;let cindy: GhostCindyNeeds | undefined;if (cindyRaw !== undefined) {if (!isPlainObject(cindyRaw)) {@@ -4102,7 +4302,7 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {// preview 槽详单:与 slots 含 'preview' **严格成对**(有槽必有详单——域名// 范围是本能力的全部知情面,不允许"先装后说");域名语法与 network 白名单- // 同一套(装入确认框逐条展示)。+ // 同一套(插件详情逐条展示)。let preview: GhostPreviewNeeds | undefined;if (raw.preview !== undefined) {if (!isPlainObject(raw.preview)) {@@ -5474,7 +5674,8 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {return {ok: true,manifest: {- schemaVersion: 2,+ ...prepared.unknownV3Fields,+ schemaVersion: prepared.schemaVersion,id: raw.id,name: raw.name,version: raw.version,@@ -5491,23 +5692,36 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {...(raw.launch !== undefined ? { launch: raw.launch as GhostLaunchMode } : {}),...(raw.settingsHtml !== undefined ? { settingsHtml: raw.settingsHtml as string } : {}),...(raw.settingsHeight !== undefined ? { settingsHeight: raw.settingsHeight as number } : {}),- slots,...(tools !== undefined ? { tools } : {}),- ...(card !== undefined ? { card } : {}),+ ...(card !== undefined || prepared.v3BaseCard || slots.includes('card')+ ? { card: card ?? {} }+ : {}),...(cindy !== undefined ? { cindy } : {}),- ...(agent !== undefined ? { agent } : {}),+ ...(agent !== undefined || prepared.v3BaseAgent || slots.includes('agent')+ ? { agent: agent ?? {} }+ : {}),...(node !== undefined ? { node } : {}),...(subscribe !== undefined ? { subscribe } : {}),...(network !== undefined ? { network } : {}),...(preview !== undefined ? { preview } : {}),...(skill !== undefined ? { skill } : {}),...(manual !== undefined ? { manual } : {}),+ ...(slots.includes('notify') ? { notify: true as const } : {}),+ ...(slots.includes('badge') ? { badge: true as const } : {}),+ ...(slots.includes('confirm') ? { confirm: true as const } : {}),+ ...(slots.includes('fs') ? { fs: true as const } : {}),+ ...(slots.includes('library') ? { library: true as const } : {}),+ ...(slots.includes('session-context') ? { sessionContext: true as const } : {}),+ ...(slots.includes('pick') ? { pick: true as const } : {}),+ ...(slots.includes('workspace') ? { workspace: true as const } : {}),+ ...(slots.includes('ios-simulator') ? { iosSimulator: true as const } : {}),...(setup !== undefined ? { setup } : {}),...(raw.command !== undefined ? { command: raw.command as string } : {}),...(keywords !== undefined ? { keywords } : {}),...(panel !== undefined ? { panel } : {}),...(mainView !== undefined ? { mainView } : {}),},+ unsupportedLegacySlots: prepared.unsupportedLegacySlots,};}@@ -5523,7 +5737,8 @@ export function validateNormalizedGhostManifest(raw: unknown): ManifestValidatio// Durable Host state is written in author format so released clients can read it// after a rollback. Still accept normalized snapshots produced by affected dev// builds and passed between current Host code paths.- const authorResult = validateGhostManifest(raw);+ const authorInput = isPlainObject(raw) ? withLegacyAuthorSlots(raw) : raw;+ const authorResult = validateGhostManifest(authorInput);if (authorResult.ok || !isPlainObject(raw) || raw.setup === undefined) return authorResult;if (!isPlainObject(raw.setup) || !Array.isArray(raw.setup.requires)) {return { ok: false, reason: '标准化清单 setup 必须是带 requires 数组的对象' };@@ -5555,7 +5770,20 @@ export function validateNormalizedGhostManifest(raw: unknown): ManifestValidatiorequires.push({ anyOf });}- return validateGhostManifest({ ...raw, setup: { requires } });+ return validateGhostManifest({ ...withLegacyAuthorSlots(raw), setup: { requires } });+}++/** 把无 slots 的 v2 运行时投影还原成旧客户端能读取的作者清单。 */+function withLegacyAuthorSlots(raw: Record<string, unknown>): Record<string, unknown> {+ if (raw.schemaVersion !== 2 || Array.isArray(raw.slots)) return raw;+ const slots: string[] = [];+ for (const [field, slot] of V3_DECLARATION_TO_LEGACY_SLOT) {+ if (raw[field] !== undefined) slots.push(slot);+ }+ for (const field of V3_BOOLEAN_CAPABILITY_FIELDS) {+ if (raw[field] === true) slots.push(V3_BOOLEAN_TO_LEGACY_SLOT[field]);+ }+ return { ...raw, slots };}/**@@ -5565,9 +5793,10 @@ export function validateNormalizedGhostManifest(raw: unknown): ManifestValidatio* validateGhostManifest,因此不能把内部 `{ kind, key }` setup 形态写盘。*/export function ghostManifestToAuthorFormat(manifest: GhostManifest): Record<string, unknown> {- if (manifest.setup === undefined) return { ...manifest };+ const authorManifest = withLegacyAuthorSlots(manifest);+ if (manifest.setup === undefined) return { ...authorManifest };return {- ...manifest,+ ...authorManifest,setup: {requires: manifest.setup.requires.map((group) => ({anyOf: group.anyOf.map((requirement) => {@@ -5596,8 +5825,9 @@ export function ghostManifestToAuthorFormat(manifest: GhostManifest): Record<str* 无需另配对)。gen_image / edit_image / gen_video / edit_video /* deposit_media / release_media / oneshot_text / embed_text;须声明* 'cindy' 卡槽与能力详单。- * - fetch-request:network 槽代理 HTTP(invoke 返回值即响应,无需另配对)。- * 须声明 'network' 卡槽与域名详单;凭证由主机注入,意识永不经手。+ * - fetch-request:主机代理 HTTP(invoke 返回值即响应,无需另配对)。+ * 当前 Agent tool-call 带严格在途 callId 时复用 Agent 授权;其它调用+ * 须声明 network 域名详单。凭证只按声明注入,意识永不经手。* - pick-request:pick 槽——请主机弹系统级选文件夹窗口(用户亲选即授权)。* - preview-request:preview 槽——请主机在右侧栏内置浏览器开预览标签页* (URL 必须命中身份卡 preview.hosts 白名单)。@@ -5648,8 +5878,8 @@ export const GHOST_PIPE_CALL_MAX_TOTAL_MS = 30 * 60_000;export type GhostAppRegion = 'cn' | 'global';/**- * 上行:读取宿主只读信息。`cindy.request(...)` 是 preload 提供的语法糖,- * 底层仍走同一根 ghost-pipe 与主机白名单。+ * 上行:读取宿主公开上下文。`cindy.request({kind:'app-context'})` 是 preload+ * 提供的语法糖,底层仍走同一根 ghost-pipe 与主机公开上下文校验。*/export type GhostPipeHostRequest =| {@@ -5719,7 +5949,7 @@ export type GhostPipeAgentResult =/* ── agent 槽·派活取件(errand,2026-07-31 开闸)──────────────────────────* 与 agent-request(把回合发进用户会话,结果给用户看)相对:errand 把任务* 交给插件**专属 errand 会话**里的 agent 跑一轮,最终回复文字取回给插件。- * 须声明 'agent' 卡槽 + `agent.errand: true`(装入确认高风险单列)。+ * 须声明 'agent' 卡槽 + `agent.errand: true`(插件详情高风险能力单列)。* agent/模型/effort/fast/供应商/权限档/工作目录由用户在插件详情页配置* (缺省跟随新建草稿偏好;权限档默认 plan 只读,永不提供 bypassPermissions,* 2026-07-31 Lizi 定案);任务文本只进普通 user 消息,绝不进 system prompt。 */@@ -5961,7 +6191,7 @@ export interface GhostPipePickRequest {deposit?: boolean;}-/** pick 槽结构化返回。path 仅在插件声明了 node 槽时提供(见 GHOST_SLOTS 注释)。 */+/** pick 能力结构化返回。path 仅在插件声明了 node 能力时提供。 */export type GhostPipePickResult =| {ok: true;@@ -7460,7 +7690,7 @@ export type GhostPipeEventPush =* - 'allow':原样放行(意识可在窗口内做纯副作用:记账/日志,不改消息);* - 'rewrite':放行**改写后的正文**——`text`(≤GHOST_HOOK_REWRITE_MAX_CHARS,* 超长截断)替换即将落库/显示的消息正文;**静默替换**(气泡直接显示改写版,- * 无标记无弹窗),提示词优化/合规改写走这条——装入确认框已如实披露「可改写」;+ * 无标记无弹窗),提示词优化/合规改写走这条——插件详情已如实披露「可改写」;* - 'block'(仅 will-user-message):打回不继续,`reason`(≤200 字符)显示在被拦* 气泡的主机脚标上;* - 'render'(仅 will-assistant-message):自绘结果卡片替换 AI 气泡——`html`@@ -7484,10 +7714,11 @@ export interface GhostPipeEventVerdict {height?: number;}-/* ── network 槽:代理 fetch 协议(2026-07-12)──────────────────────────- * 意识 cindy.send({type:'fetch-request',…}) → 主机白名单校验 + 凭证注入 +- * 真实 HTTP → invoke resolve 值即 GhostPipeFetchResult。硬边界都在主机侧- * 代码强制(规则 9),常量在此与手册/校验共用一份。 */+/* ── 主机代理 fetch 协议(2026-07-12)────────────────────────────────+ * 意识 cindy.send({type:'fetch-request',…}) → 主机调用上下文/白名单校验 ++ * 按声明注入凭证 + 真实 HTTP → invoke resolve 值即 GhostPipeFetchResult。+ * Agent 在途调用凭严格 callId 复用 Agent 授权;自主调用仍按 network+ * 详单守门。硬边界都在主机侧代码强制,常量在此与手册/校验共用一份。 *//** 代理 fetch 允许的方法(REST 查询/提交/删除;body 仍仅 POST 允许)。 */// PUT / PATCH 于 2026-07-13 随 oauth 凭证形态一并放行(Google Calendar 更新、@@ -7580,16 +7811,16 @@ export const GHOST_FETCH_FILE_MAX_BYTES = 256 * 1024 * 1024;/** 意识建议文件名的长度上限(超限拒;消毒后仍以主机为准)。 */export const GHOST_FETCH_FILE_NAME_MAX_CHARS = 128;-/* ── fs 槽(写文件,2026-07-14):字节由主机代写,沙箱仍零 fs ──────────- * 意识 cindy.send({type:'fs-request', op, root, …}) → 资格审(声明了 'fs'- * 卡槽?)→ 按 root 分档守门 → 主机代写/代读 → 结构化 GhostPipeFsResult。+/* ── 主机文件操作(2026-07-14):字节由主机代办,沙箱仍零 fs ──────────+ * 意识 cindy.send({type:'fs-request', op, root, …}) → 按执行上下文与 root+ * 分档守门 → 主机代写/代读 → 结构化 GhostPipeFsResult。* 三个 root:- * - 'data' 私有数据目录(userData/ghost-fs/<ghostId>);全 op,免确认,- * 配额封顶,卸载随包回收。老 MCP out_file 泄洪的意识世界等价物。- * - 'workdir' 当前会话工作目录;仅 write,须带 callId(反查 session),- * 跟随会话 permission 模式(见 fsSlot 的映射表),远程工作区拒。+ * - 'data' 插件自主私有数据目录(userData/ghost-fs/<ghostId>);要求 fs:true,+ * 全 op,免确认,配额封顶,卸载随包回收。+ * - 'workdir' 当前会话工作目录;仅 write,须带 callId(反查 session),当前+ * Agent 调用无需 fs:true,并跟随会话 permission 模式;远程工作区拒。* - 'save' 主 agent 过户的 save 票据目录;仅 write,复用 saveDeposit- * 的 TTL/次数/字节预算与文件名消毒(与 as:'file' 下载同一本账)。+ * 的 TTL/次数/字节预算与文件名消毒;票据自身就是授权,无需 fs:true。*/export const GHOST_FS_ROOTS = ['data', 'workdir', 'save'] as const;export type GhostFsRoot = (typeof GHOST_FS_ROOTS)[number];@@ -7609,7 +7840,7 @@ export const GHOST_FS_DATA_MAX_FILES = 2000;/** list 返回条数上限(超出截断并标 truncated)。 */export const GHOST_FS_LIST_MAX_ENTRIES = 2000;-/** 上行:fs 槽写文件请求。 */+/** 上行:主机文件操作请求。 */export interface GhostPipeFsRequest {type: 'fs-request';/** 操作:write=创建/覆盖,read/list/delete 仅 root:'data'。 */@@ -7629,7 +7860,7 @@ export interface GhostPipeFsRequest {encoding?: 'utf8' | 'base64';/** save 票据(root:'save' 必填;来自 ghost_call 顶层 save_dir 过户)。 */token?: string;- /** 归因号(root:'workdir' 必填:主机凭它反查 session 与权限;其余可选)。 */+ /** 归因号(root:'workdir' 必填:主机凭它反查严格在途 Agent 调用、session 与权限;其余可选)。 */callId?: string;}@@ -7661,10 +7892,10 @@ export type GhostPipeFsResult =| { ok: true; op: 'delete'; path: string; /** false = 本来就不存在(幂等)。 */ existed: boolean }| { ok: false; message: string };-/* ── library 槽:持久作品库(2026-08-20;详见 docs/dev-rules/plugin-library-storage.md)── */+/* ── library 能力:持久作品库(2026-08-20;详见 docs/dev-rules/plugin-library-storage.md)── *//**- * library 槽操作集。文件操作与 fs:data 同为"主机代劳 + 相对路径",差异在:+ * library 能力操作集。文件操作与 fs:data 同为"主机代劳 + 相对路径",差异在:* 无 256MiB/2000 文件配额(受磁盘保留水位与软水位约束)、写入原子化* (staging+fsync+rename+identity 复验)、大文件走分块流、结构化错误码、* 卸载不删。SQLite 子集(op:'db.*')只收参数化单语句,事务/迁移/备份由@@ -7694,7 +7925,7 @@ export const GHOST_LIBRARY_OPS = [] as const;export type GhostLibraryOp = (typeof GHOST_LIBRARY_OPS)[number];-/** 上行:library 槽请求(cindy.library(req) ≡ send({type:'library-request', …req}))。 */+/** 上行:library 请求(cindy.library(req) ≡ send({type:'library-request', …req}))。 */export interface GhostPipeLibraryRequest {type: 'library-request';op: GhostLibraryOp;@@ -7733,7 +7964,7 @@ export interface GhostPipeLibraryRequest {}/**- * library 槽返回:成功形态按 op 分流(文件操作带宿主实算 sha256——未来+ * library 返回:成功形态按 op 分流(文件操作带宿主实算 sha256——未来* 网络同步的素材完整性地基);失败**结构化**(errorCode + 人话 message,* 修掉 fs 槽无错误码的缺口),对沙箱永不 reject。*/@@ -7791,7 +8022,7 @@ export type GhostPipeLibraryResult =/** Library 概览(ghosts:library-overview IPC 载荷;设置页插件详情消费)。 */export interface GhostLibraryOverview {- /** 插件是否声明了 library 槽(未声明时设置页不渲染该区)。 */+ /** 插件是否声明了 library 能力(未声明时设置页不渲染该区)。 */supported: boolean;state: 'ready' | 'readonly' | 'unavailable';reason: string | null;@@ -7807,10 +8038,13 @@ export interface GhostLibraryOverview {orphaned: boolean;}-/** 上行:network 槽代理 fetch 请求。 */+/** 上行:主机代理 fetch 请求。 */export interface GhostPipeFetchRequest {type: 'fetch-request';- /** 目标地址:仅 https、默认端口,host 必须命中 network.hosts 白名单。 */+ /**+ * 目标地址:仅 https、默认端口。自主调用的 host 必须命中 network.hosts;+ * 当前 Agent tool-call 可凭严格在途 callId 访问普通未声明 host。+ */url: string;/** 缺省 GET。 */method?: GhostFetchMethod;@@ -7871,7 +8105,10 @@ export interface GhostPipeFetchRequest {* 非 oauth 凭证忽略本字段。*/authAccount?: string;- /** 归因号(同 cindy-request:tool-call 的 callId 原样带上,日志对账)。 */+ /**+ * tool-call 的 callId 原样带上。当前 Agent 调用时既用于日志归因,也用于+ * 复用 Agent 授权;自主调用可省略并按 network 声明守门。+ */callId?: string;}diff --git a/apps/desktop/src/shared/ghostInstallOrigin.ts b/apps/desktop/src/shared/ghostInstallOrigin.tsdeleted file mode 100644index 4839c606e7..0000000000--- a/apps/desktop/src/shared/ghostInstallOrigin.ts+++ /dev/null@@ -1,38 +0,0 @@-/**- * 装入确认框的「发起来源」——主机侧填写、agent 不可伪造。- *- * 为什么需要它:插件装入有四个入口(设置页选文件 / 窗口拖入 / 双击 .cindy /- * `ghost_forge_pack` 打包转交),前三个都是用户亲手操作、意图明确;唯独 forge- * 转交是 **Agent 单方面调工具发起的**——注入攻击可以让 Agent 在处理外部内容时- * 偷偷打包并弹装入框,而用户此刻刚让 Agent 干了一堆事,没有"我没让它装插件"的- * 清晰记忆。确认框必须能如实告诉用户"这次是 Agent 发起的,不是你点的",用户才有- * 判断依据。- *- * 该结论只能由主机产生:forge 转交路径在 main 侧记下来源,经既有的- * `ghosts:install-requested` 广播 payload 送到 renderer(不经 agent 可控通道)。- * 手动入口一律 `manual`,不加任何提示——亲手选文件本身就是意图表达。- */-export type GhostInstallOrigin =- | { kind: 'manual' }- | {- /**- * Agent 经 `ghost_forge_pack` 打包并转交装入。字段都由主机填:sessionTitle- * 取自会话行(agent 改不了),sourceRelPath 是源码目录相对会话工作目录的- * 路径(forge 打包已强制源码必须在工作目录内,故该路径可靠)。- */- kind: 'agent-forge';- /** 发起该次打包的任务标题(查不到时缺省,不编造)。 */- sessionTitle?: string;- /** 被打包的插件源码目录,相对当前会话工作目录。 */- sourceRelPath?: string;- };--/** 手动入口的缺省来源(拖入 / 双击 / 设置页选文件共用)。 */-export const MANUAL_GHOST_INSTALL_ORIGIN: GhostInstallOrigin = { kind: 'manual' };--/** 是否为 Agent 单方面发起(确认框据此决定是否展示来源横幅)。 */-export function isAgentForgeOrigin(- origin: GhostInstallOrigin | null | undefined,-): origin is Extract<GhostInstallOrigin, { kind: 'agent-forge' }> {- return origin?.kind === 'agent-forge';-}diff --git a/apps/desktop/src/shared/ipc-errors.ts b/apps/desktop/src/shared/ipc-errors.tsindex 57a6373b3b..ed6cfffb3c 100644--- a/apps/desktop/src/shared/ipc-errors.ts+++ b/apps/desktop/src/shared/ipc-errors.ts@@ -176,11 +176,10 @@ export type IpcErrorCode =| 'TERMINAL_ALREADY_DISPOSED' // 在已 dispose 的 session 上调 restart 等操作// 意识(.cindy 装入)| 'GHOST_FILE_INVALID' // 不是合法 zip / 缺 ghost.json / 清单不合格 / 超限- | 'GHOST_HOST_UNSUPPORTED' // 插件包合法,但当前 Cindy 不认识其 schema / capability slot+ | 'GHOST_HOST_UNSUPPORTED' // 插件包使用了当前 Cindy 不认识的未来 schema| 'GHOST_COMMAND_CONFLICT' // 显式指令与已装意识撞名(装入拒绝)| 'GHOST_ID_RESERVED' // id 属 shared/ghost.ts 登记的官方保留前缀,用户通道拒装(防抢注蹭凭证别名)- | 'GHOST_BROKER_MANUAL_INSTALL_NOT_AUTHORIZED' // 手动 .cindy 来源无权使用授权 broker- | 'GHOST_BROKER_NOT_AUTHORIZED' // 当前来源或组织身份无权使用授权 broker+ | 'GHOST_BROKER_MANUAL_INSTALL_NOT_AUTHORIZED' // 本地 .cindy 来源无权使用授权 broker| 'GHOST_BROKER_REDIRECT_PORT_REQUIRED' // 新包声明授权 broker 时缺少本机回跳端口// 自定义插件市场源(Git / 本地文件夹)| 'MARKET_SOURCE_INVALID' // 来源格式非法 / 本地路径不是目录 / 参数组合不允许@@ -381,7 +380,6 @@ const IPC_ERROR_CODES: ReadonlySet<IpcErrorCode> = new Set<IpcErrorCode>(['GHOST_COMMAND_CONFLICT','GHOST_ID_RESERVED','GHOST_BROKER_MANUAL_INSTALL_NOT_AUTHORIZED',- 'GHOST_BROKER_NOT_AUTHORIZED','GHOST_BROKER_REDIRECT_PORT_REQUIRED','MARKET_SOURCE_INVALID','MARKET_GIT_UNAVAILABLE',diff --git a/apps/desktop/src/shared/pluginMarket.ts b/apps/desktop/src/shared/pluginMarket.tsindex 459d9cc2ba..a1df4b9128 100644--- a/apps/desktop/src/shared/pluginMarket.ts+++ b/apps/desktop/src/shared/pluginMarket.ts@@ -1,6 +1,5 @@-import type { GhostManifest, GhostPermissionDiff, InstalledGhost } from './ghost';+import type { GhostManifest, InstalledGhost } from './ghost';import type { PluginIconMetadata } from '@cindy/plugin-protocol';-import type { DataOwnerPushStamp } from './dataOwnerPush';export type PluginMarketScope = 'public' | 'organization' | 'personal';export type PluginMarketInstallState =@@ -56,22 +55,6 @@ export interface PluginRemovalUserNotice {name: string | null;}-export interface PluginUpgradePermissionNotice {- /** Shared permission item identity; Renderer resolves labelKey through i18n. */- key: string;- labelKey: string;- labelArgs?: Record<string, string>;-}--export interface PluginUpgradeUserNotice {- count: number;- name: string | null;- /** Added permissions for the sole upgraded plugin; null for multi-plugin batches. */- permissions: PluginUpgradePermissionNotice[] | null;- /** Whether any upgrade in the aggregate added permissions. */- hasPermissionExpansion: boolean;-}-/** 详情携带安装前展示给用户的 manifest;官方来自 release,自定义来自本地发现。 */export interface PluginMarketDetail extends PluginMarketItem {manifest: GhostManifest;@@ -110,57 +93,23 @@ export type PluginMarketLocalIconResult =| (PluginMarketLocalIconRequest & { status: 'loaded'; dataUrl: string })| (PluginMarketLocalIconRequest & { status: 'missing' | 'retryable' });-/** Main 从已验证真实包中提取的权限复核事实。 */-export interface PluginMarketPackageReviewFacts {- /** 已按当前界面语言本地化,仅用于展示;安全指纹由 Main 基于原始清单计算。 */- manifest: GhostManifest;- /** Main 基于当前已装原始清单与真实包原始清单算出的权限差异;无可靠基线时为 null。 */- permissionDiff: GhostPermissionDiff | null;- /** Main 根据安装锁内的实际落位状态判定;不从 permissionDiff 间接推断。 */- isUpdate: boolean;- packageSha256: string;- /** 产生复核结果时的可靠已装权限基线;null 也可能是旧安装基线不可读。 */- installedBaseline: string | null;- /** 只用于让确认卡如实说明包来自官方还是用户添加的市场。 */- sourceType: PluginMarketItemSource;- /** 与 permissionDiff 独立:完整权限卡也要能展示 OAuth 身份变化。 */- builtinOauthClientChanged?: boolean;-}--/** Main 在安装事务内请求当前窗口立即确认真实包权限;不暴露内部批准绑定。 */-export interface PluginMarketPackageReviewRequest {- requestId: string;- /** Main 投递这份私有包事实时的账号代际;Renderer 必须匹配后才可展示。 */- ownerStamp: DataOwnerPushStamp;- manifest: GhostManifest;- permissionDiff: GhostPermissionDiff | null;- isUpdate: boolean;- sourceType: PluginMarketItemSource;- /** 与 permissionDiff 独立:完整权限卡也要能展示 OAuth 身份变化。 */- builtinOauthClientChanged?: boolean;-}-export interface PluginMarketInstallOptions {/** 用户点击时看到的目标 release;Main 会在下载前重新核对。 */expectedReleaseId: string;- /** 安装前展示给用户的完整清单;Main 会与当前来源事实重新核对。 */+ /** 自定义来源详情读取时的完整清单;Main 会在打包前重新核对。 */expectedManifest?: GhostManifest;- /** 仅用于自定义市场确认其本地真实 manifest 的扩权。 */- allowPermissionExpansion?: boolean;- /** 用户审阅目标权限时的已装权限基线。 */- reviewedBaseline?: string;/**- * receipt 模型的并发护栏:receipt 派生 token。确认与落位之间批准状态若变化即拒绝。+ * receipt 模型的并发护栏:receipt 派生 token。读取与落位之间安装状态若变化即拒绝。*/expectedInstalledApproval?: string;/** 仅详情页上用户明确点击“替换”时为 true;更新和批量更新不得切换来源。 */allowSourceReplacement?: boolean;}-/** 安装成功,或用户在事务内取消真实包权限确认。 */-export type PluginMarketInstallResult =- | { ghost: InstalledGhost; cancelled?: never }- | { ghost?: never; cancelled: true };+/** 市场安装成功后返回已落位插件。 */+export interface PluginMarketInstallResult {+ ghost: InstalledGhost;+}/* ------------------------------------------------------------------------ *//* 自定义市场源(Git / 本地文件夹) */diff --git a/docs/README.md b/docs/README.mdindex 4c71a149dc..9cc95804fe 100644--- a/docs/README.md+++ b/docs/README.md@@ -21,7 +21,7 @@| [mobile-development.md](./dev-rules/mobile-development.md) | Mobile 开发规则 | authoritative | Mobile 模拟器、验证与专项入口 | — || [orca-team-architecture.md](./dev-rules/orca-team-architecture.md) | 契约/规范 | authoritative | `apps/desktop` 的 `maker-ipc/orca*` 服务 + `mcp-integrations` codex MCP、`packages/lizi-mcps` 的 `orca`、`packages/orca-workflow`、`packages/maker-core` 的 codex MCP context | — || [maker-core-and-agent-behavior.md](./dev-rules/maker-core-and-agent-behavior.md) | maker-core 规则 | authoritative | `packages/maker-core` 的 Agent 编排、prompt 组装、translator、model 映射、缓存率/性能/准确性指标与 system prompt 门禁 | — |-| [plugin-security-and-authoring.md](./dev-rules/plugin-security-and-authoring.md) | 插件安全规则 | authoritative | 插件(`.cindy`)运行时沙箱、权限 slot、网络/凭证/资源交接、存量插件向下兼容与无感升级、作者契约与编写手册同步 | — |+| [plugin-security-and-authoring.md](./dev-rules/plugin-security-and-authoring.md) | 插件安全规则 | authoritative | 插件(`.cindy`)运行时沙箱、直接能力声明、网络/凭证/资源交接、存量插件向下兼容与无感升级、作者契约与编写手册同步 | — || [cindy-updater.md](./dev-rules/cindy-updater.md) | 更新器规则 | authoritative | 客户端自动更新链路(`cindy-updater` + Electron 更新服务)的 owner 确认门禁 | — || [engineering-conventions.md](./dev-rules/engineering-conventions.md) | 通用工程规范 | authoritative | Desktop 日志、IPC 错误协议、main 侧测试、跨平台双端兼容与 UI 文案 i18n | — || [log-upload-and-redaction.md](./dev-rules/log-upload-and-redaction.md) | 日志上报规则 | authoritative | 客户端日志采集/脱敏/上报:记录边界不变量、来源白名单方向、标记代次与原子清除、区域绑定与崩溃时序 | — |diff --git a/docs/dev-rules/media-storage-and-protocols.md b/docs/dev-rules/media-storage-and-protocols.mdindex a534180a48..f9d308cf20 100644--- a/docs/dev-rules/media-storage-and-protocols.md+++ b/docs/dev-rules/media-storage-and-protocols.md@@ -74,7 +74,7 @@以下缺口在触及相关链路时必须一并修复,或在 PR 中保留明确的正式跟踪,不得静默丢弃:- 插件持久引用的 per-插件 字节配额只覆盖 **寄存**(`ghost-deposit`,cindy 槽- `deposit_media`):上限 `GHOST_CINDY_DEPOSIT_QUOTA_BYTES`,安装确认框逐项展示该上限,+ `deposit_media`):上限 `GHOST_CINDY_DEPOSIT_QUOTA_BYTES`,插件详情逐项展示该上限,释放口是 `release_media`,卸载插件时按 refKind 清理。**画廊(`ghost-gallery`:模型代办产物与 network `as:'media'` 下载)仍无字节配额、仍不随卸载回收** —— 这两条是存量语义,改动它们属于产品决策,触及时另行拍板,不得当作已完成。diff --git a/docs/dev-rules/plugin-library-storage.md b/docs/dev-rules/plugin-library-storage.mdindex 6bbe4e6a62..bd5aca2cf1 100644--- a/docs/dev-rules/plugin-library-storage.md+++ b/docs/dev-rules/plugin-library-storage.md@@ -1,15 +1,15 @@-# 插件持久 Library(library 槽)+# 插件持久 Library 能力> **状态**:权威开发规则(authoritative)-> **读取时机**:新增或修改 library 槽(持久作品库)、binding / 目录选择、迁移、+> **读取时机**:新增或修改 library 能力(持久作品库)、binding / 目录选择、迁移、> 回收站删除、SQLite 语句门、面板 `/library/` 投影,或任何触碰> `libraries/` / `libraries-binding.json` / `libraries-trash/` 落盘布局的改动之前-library 槽给插件一个**用户作品级**的持久存储区,与 fs 槽私有储物柜+`library: true` 给插件一个**用户作品级**的持久存储区,与 `fs: true` 私有储物柜(256MiB/2000 文件配额、卸载即回收)是两个语义:不受配额约束(只受磁盘保留水位与软水位约束)、**卸载插件不删数据**、删除必须走设置页独立确认。完整产品-语义与裁决记录见方案文档(2026-08-20 定案:装入时可选目录 + 随时安全迁移并入-首期)。+语义与裁决记录见方案文档。安装直接使用系统管理的默认位置,不增加安装确认步骤;+用户可在插件详情页随时安全迁移。## 事实来源@@ -75,8 +75,7 @@ backups)对插件不可达——路径语法段首不许点,协议层天然`/media/` 长缓存刻意不同)。10. **known limitation(如实告知,不假装覆盖)**:Windows 上 binding 的文件identity(st_ino)多为 0,「同路径删后重建」检不出(POSIX 可检出);映射- 网络盘符检测需要 Win32 API,v1 只拒 UNC 路径;市场装入确认框的「存储位置」- 行尚未接入(装后可从设置页迁移)。+ 网络盘符检测需要 Win32 API,v1 只拒 UNC 路径。## Review 清单diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.mdindex fb73a8cb12..46a6b125a5 100644--- a/docs/dev-rules/plugin-security-and-authoring.md+++ b/docs/dev-rules/plugin-security-and-authoring.md@@ -1,7 +1,7 @@# 插件运行时安全与作者契约> **状态**:权威开发规则(authoritative)-> **读取时机**:新增或修改插件(`.cindy`)的运行时、沙箱、权限、能力 slot、面板供片、+> **读取时机**:新增或修改插件(`.cindy`)的运行时、沙箱、权限、能力声明、面板供片、> 网络/凭证/文件交接,插件作者可见的身份卡、管子协议、打包与编写手册,或批准状态、> 安装布局、指纹格式等**存量安装读得到的任何东西**之前@@ -24,19 +24,19 @@## 事实来源-| 内容 | 权威来源 |-| ----------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| 编写手册(作者唯一教材,现拿现读) | `apps/desktop/src/main/cindy-brain/forge.ts` 的 `FORGE_GUIDE`,经 `ghost_forge_guide` 工具下发 |-| `ghost.json` 身份卡字段与校验 | `packages/plugin-protocol/src/manifest.ts` 是跨消费者协议正本;`apps/desktop/src/shared/ghost.ts` 是 Desktop 运行时 validator。除下文登记的 Desktop-only 能力外,两端必须同步维护 |-| 管子协议类型 | `apps/desktop/src/shared/ghost.ts`(`cindy.send` / `cindy.onHostMessage` 类型) |-| 打包限制 | `apps/desktop/src/main/cindy-brain/forge.ts` 的 `packGhostDir` |-| 运行时、沙箱进程与生命周期 | `apps/desktop/src/main/cindy-brain/runtime/GhostRuntime.ts`、`GhostManager.ts` |-| 安装批准事实(receipt / 技能快照 / revision) | `apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts`,批准态投影见 `shared/ghost.ts` 的 `GhostInstallApproval` |-| 能力 slot(网络/通知/确认/文件系统/技能/宿主等) | `apps/desktop/src/main/cindy-brain/networkSlot.ts`、`notifySlot.ts`、`badgeSlot.ts`(未读角标,落盘账本 `ghostUnreadStore.ts`)、`confirmSlot.ts`(往返桥 `ghostConfirmDialogBridge.ts`,renderer 落地 `cindy-brain/GhostConfirmDialogHost.tsx`)、`fsSlot.ts`、`cindySlot.ts`、`skillSlot.ts`、`agentSlot.ts`、`errandSlot.ts`(派活执行链在 `maker-ipc/ghostErrandRunner.ts`,每插件配置在 `errandPrefsStore.ts`)、`iosSimulatorSlot.ts`(当前台前任务的公开状态与 Host viewer 入口);library 槽(持久作品库:文件层/SQLite 语句门/binding/迁移/回收站)见 [`plugin-library-storage.md`](plugin-library-storage.md),主实现在 `libraryVault.ts`、`librarySlot.ts`、`libraryDbCore.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` |-| 行为与安全不变量 | `apps/desktop/src/main/cindy-brain/__tests__/`、`forge.test.ts` |+| 内容 | 权威来源 |+| ---------------------------------------------------- | -------- |+| 编写手册(作者唯一教材,现拿现读) | `apps/desktop/src/main/cindy-brain/forge.ts` 的 `FORGE_GUIDE`,经 `ghost_forge_guide` 工具下发 |+| `ghost.json` 身份卡字段与校验 | `packages/plugin-protocol/src/manifest.ts` 是跨消费者协议正本;`apps/desktop/src/shared/ghost.ts` 是 Desktop 运行时 validator。除下文登记的 Desktop-only 能力外,两端必须同步维护 |+| 管子协议类型 | `apps/desktop/src/shared/ghost.ts`(`cindy.send` / `cindy.onHostMessage` 类型) |+| 打包限制 | `apps/desktop/src/main/cindy-brain/forge.ts` 的 `packGhostDir` |+| 运行时、沙箱进程与生命周期 | `apps/desktop/src/main/cindy-brain/runtime/GhostRuntime.ts`、`GhostManager.ts` |+| 安装事务状态、内容摘要与技能快照 receipt | `apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts`,状态投影见 `shared/ghost.ts` 的 `GhostInstallApproval` |+| 能力实现(网络/通知/确认/文件系统/技能/宿主等) | `networkSlot.ts`、`notifySlot.ts`、`badgeSlot.ts`、`confirmSlot.ts`、`fsSlot.ts`、`cindySlot.ts`、`skillSlot.ts`、`agentSlot.ts`、`errandSlot.ts`、`iosSimulatorSlot.ts`;持久作品库见 [`plugin-library-storage.md`](plugin-library-storage.md),主实现在 `libraryVault.ts`、`librarySlot.ts`、`libraryDbCore.ts` |+| 面板供片、注入主题 token 与协议 | `apps/desktop/src/renderer/cindy-brain/ghostPanelTheme.ts`、`cindy-ghost://` 分支 |+| 插件详情能力说明 UI | `apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx` |+| 远程/手机版能力准入白名单 | `packages/device-link/src/allowlist.ts` |+| 行为与安全不变量 | `apps/desktop/src/main/cindy-brain/__tests__/`、`forge.test.ts` |文档与实现冲突时以代码为准,但必须在同一改动内同步修正本文与手册。@@ -48,6 +48,39 @@- `cindy-` / `filo-` / `xd-` 是官方保留 id 前缀,第三方插件不得占用;前缀正本见`apps/desktop/src/shared/ghost.ts` 的 `GHOST_OFFICIAL_ID_PREFIXES`。+### 1.1 Manifest v3 直接能力声明++- 新插件统一使用 `schemaVersion: 3`,并填写不低于 `0.1.61` 的 `minCindyVersion`。+ v3 **没有** `slots`;+ `tools`、`card`、`panel`、`mainView`、`subscribe`、`skill`、`cindy`、`agent`、`node`、`network`、+ `preview` 等顶层字段本身就是插件贡献项或自主 Host 能力的直接声明。+- 无配置的布尔能力只接受字面量 `true`:`notify`、`badge`、`confirm`、`fs`、`library`、+ `sessionContext`、`pick`、`workspace`、`iosSimulator`。不用就省略,写 `false` 是无效清单。+- `card: {}` 与 `agent: {}` 分别表示基础卡片能力和由真实用户点击触发 Agent 回合;+ 其它对象型能力必须至少包含一项真实能力,不能用空对象占位。+- v3 未识别的顶层字段必须原样保留,但当前 Host 不展示、不授权、也不因此阻止安装。+ 未来 Host 识别该字段后,才按正常的能力展示和运行时守门链路启用。不能把+ 未知字段猜成现有权限,也不能让它意外获得能力。+- **Agent 在途调用不需要重复登记具体操作。** 插件工具是否执行由当前+ `ghost_call` 的 Cindy Agent 授权决定;普通网络和当前工作目录操作使用主机+ 下发且仍在途的 `callId`。随包代码与 CLI 继续使用已有 Node 工作进程,顶层+ `node` 字段只声明这一运行形态,不预登记具体命令。不得为具体 CLI、域名或路径+ 新增 Slot、manifest 字段或客户端特例。只有插件要在 Panel、订阅、常驻进程、+ 后台任务等**脱离当前 Agent 调用**的场景自主使用 Host 能力时,才需要+ 对应直接字段。需要 Cindy 尚未实现的真正新 Host 服务时,才提高+ `minCindyVersion` 并增加客户端实现。+- `schemaVersion: 2` 只作存量兼容。Desktop 在验证边界把已知 `slots` 显式映射为同名的+ v3 直接字段;运行时只消费规范化后的直接字段。未知但格式合法的 v2 slot 不阻止安装,+ 运行时也不授予任何能力。未来支持必须新增明确映射,不得按名称猜测。+- v2 的空 `slots` 和历史零能力声明可继续安装,规范化时直接丢弃。v2 → v3 更新按规范化+ 后的直接能力比较;只删除 `slots`、能力等价时不算新增权限。+- 安装/更新与能力授权解耦:用户导入 `.cindy`、明确要求当前 Agent 通过 Forge 安装、+ 点击市场安装或命中服务端+ `defaultInstall` 即构成安装依据,真实包校验通过后直接安装并启用,不追加能力确认弹窗。+ 插件自主 Host 能力仍须在 manifest 如实声明、在插件详情展示,并由 Host+ 运行时强制守门;动态资源与 Agent 在途操作不重复建权限实体,继续复用 Cindy 既有+ Agent 授权系统,不新增 grant/申请状态机。+## 2. 运行时沙箱与进程隔离- 每个运行中的插件使用独立 Electron 沙箱进程与专属 session partition。沙箱禁止直接访问@@ -60,57 +93,69 @@## 3. 权限即授权边界-- 所有能力必须先在 manifest 声明 slot,通过同一套校验,并在注入/更新确认框中逐项- 如实展示,再由 host 代码强制授权。**prompt 不构成安全边界**,前端展示与确认框文案- 也不构成授权。-- 新增或修改 slot 时,除同步编写手册与校验(下节 6)外,还必须同步 shared 类型、- preload/host handler、权限 UI(`GhostPermissionList.tsx`)、错误边界和测试。-- **授权事实由 Host receipt 持有,不由安装目录持有。** 一次明确的安装/更新确认写出- 一份 receipt(`ghostInstallReceipt.ts`),落在**安装根之外**的 owner-scoped 状态根里,- 钉住这次批准过的 manifest、trust、启停态和一个随机 `revision`;`GhostManager.list()`- 只从 receipt 取这些字段,安装目录里的 `ghost.json` / `.cindy-trust.json` / `.disabled`- 退化为旧版本兼容镜像。**唯一的非对称例外是启停态**:`.disabled` 镜像在读取时只往- 停用方向合并(`enabled = receipt.enabled && !镜像存在`)——停用必须永远能成功,状态根- 不可写时镜像是 `setEnabled(false)` 唯一还能落笔的地方,只读 receipt 会让那次停用在- 重启后静默复活;镜像**不能**把插件往启用方向翻,重新启用只有 `setEnabled(true)` 成功- 写 receipt 一条路。理由是可变安装目录曾经就是授权事实本身:就地改写- `ghost.json` 能让权限 diff 显示"无新增",未确认的 slot 因此拿到运行授权。- - 没有 receipt(旧安装)或 receipt 损坏 = **不构成运行授权**:一律按停用列出、- 不许启用、不参与技能落链。但"不构成运行授权"只是**当下状态**,不等于"该由用户- 重装":这两种情况都必须先走第 5 节的存量迁移(能从旧版授权事实重建出等价 receipt- 就自动重建,用户无感),**只有迁移读不出或自相矛盾时**才落到一次完整重新确认- (`diffInstalledGhostPermissionItems` 在无批准基线时把候选包的**全部**权限当新增项- 展示)。UI 必须如实说出这个状态并给出恢复入口,不能让它看起来只是"被用户关掉了",- 也不能只留"去市场重装"这一条出路。- - 通往"不构成运行授权"的还有第三条路:**撤销陈旧批准失败时的进程内隔离**。撤销的- 契约是"返回后该插件一定不再被授权运行",所以删不掉 receipt(状态根不可写——与写- 批准失败同一个成因,指望再往状态根写点什么表达"已失效"并不可靠)时退回内存标记,- 由读批准状态的**唯一入口**统一投影成 `invalid`。读批准状态的所有消费方都必须走- 那个入口:各自直接读 receipt 会让隔离在某条路径上失效。撤销同时要熄灯运行中的- 实例(runtime / node broker / agent slot 三连),否则"不再被授权运行"对已经跑起来- 的进程不成立。下一轮启动对账成功即自愈。- - 跨进程更新事务用 `ghostInstallApprovalToken()` 把批准态投影成 token:Renderer 把- 确认时看到的 token 回传,Main 重新读状态比对,不一致就拒(`state-changed`)。- token 是前置条件不是凭证——真值一律由 Main 现读。- - receipt 保证的是**授权事实**,**不是安装内容此后一直没被改过**:逻辑页代码仍从可变- 安装目录加载。`packageSha256` 是批准时点的来源指纹;组织市场 Broker 会把它与 ledger- 的 Release sha256 比对,但运行时不会重算可变安装目录的整包字节(见第 7 节)。-- **Forge 的源码区与 Host 受管根互斥。** `ghost_forge_scaffold` / `ghost_forge_pack` 的目标- 必须是当前会话工作目录里的独立作者目录;命中安装根或批准状态根一律拒- (pack 返回 `SOURCE_IS_INSTALLED_PLUGIN`)。判定按 realpath 比对受管根,同时挡住大小写- 折叠与软链/junction 别名。理由不是洁癖:在已安装目录里就地制作"更新包"会让版本与- 权限 diff 以被改过的现场为基线,把未经确认的 manifest 送进运行时授权。-- `skill` 槽是唯一**越出沙箱**的能力:技能指令由主 Agent 以用户全部权限执行、全局+- 先判断**谁在执行**,再判断授权边界:+ - 当前 Agent 在途 `ghost_call` 是否执行插件工具,由该会话既有的 Agent 授权决定。+ 普通网络和工作目录操作以 Host 下发的严格在途 `callId` 绑定会话;随包代码与+ CLI 仍由已有 Node 工作进程执行,不新增 Host 进程协议或具体命令登记。+ - 插件脱离当前 Agent 调用的自主 Host 能力,必须先在 manifest 以对应顶层字段+ 直接声明,通过校验,在插件详情中如实展示,再由 Host 代码强制守门。+- Agent 调用必须同时满足:`callId` 尚在途、绑定同一插件、绑定本地会话。已交卷、+ 他插件、scheduler 脚本、Panel 和后台调用都不得借此绕过自主能力声明。+- 安装/更新不以弹窗点击作为能力授权事实;+ **prompt 和前端展示都不构成安全边界**。+- 新增或修改能力声明时,除同步编写手册与校验(下节 6)外,还必须同步 shared 类型、+ preload/host handler、详情能力 UI(`GhostPluginDetailView.tsx`)、错误边界和测试。++### 3.1 安装与自动更新++- 首次安装只来自四种明确依据:用户导入本地 `.cindy`、明确要求当前 Agent 调用+ `ghost_forge_install`、用户点击某个市场条目的安装,或服务端为当前 owner 下发+ `defaultInstall`。安装成功默认启用;插件声明哪些能力不改变+ 安装动作是否需要确认,因为安装不设能力确认弹窗。+- 市场安装账本是后续更新来源的唯一事实:服务端市场按 `pluginId + releaseId` 路由,+ 自定义市场还必须匹配 `sourceKey`;已装目录的 canonical manifest digest 必须与账本一致。+ 任何同 id 来源冲突或目录漂移都不得被自动覆盖,只能由用户显式选择替换来源。+- 所有仍匹配稳定来源的已装插件都静默自动更新,不限 public/organization、也不限+ `defaultInstall`。更新保持现有启用状态,不弹成功 toast;插件正有调用、派活或 Cindy+ 工作时跳过,下一轮重试。服务端市场按客户端版本投影最近发布、曾上架且仍有效的兼容+ Release;current 不兼容时回退兼容历史版本,没有兼容版本时不展示。Desktop 信任该投影,+ 不再用 `minCindyVersion` 二次筛选、跳过或弹兼容性确认。自定义市场和本地 `.cindy` 采用+ 同一安装策略:`minCindyVersion` 是发布/发现元数据,不是客户端安装授权或确认闸门。+ 真实包身份、Release 摘要、能力上限、Manifest schema 与当前 Host 是否能解析仍按各自+ 安全边界校验,不能把包内容异常降级成“仍要安装”。+- 自动对账在 owner 稳定后的启动/登录切换、应用回前台、系统唤醒和 30 分钟周期触发。+ 不新增持久化任务队列或“是否自动更新”设置;卸载写下的 opt-out 继续阻止默认安装复活。+- 同一 release 自动更新失败后,在当前进程内按 owner、来源路由和 release 做指数退避+ (5 分钟起、最长 6 小时),日志记录失败次数与下次重试时间;来源发布新 release 时立即+ 解除。忙碌跳过不记失败,用户手动重试不受退避限制。+- 服务端包必须通过 release SHA/大小校验,真实包能力不得超出该 release 的市场 manifest;+ 自定义市场以发现并规范化的 manifest 为能力上限。能力上限内的新版声明可静默更新,超出+ 则按包内容不一致拒绝并留待来源修复,不转成用户审批流程。+- 本地 `.cindy` 没有稳定来源,不自动更新;用户再次导入同 id 新包时直接原位更新,由 Main+ 保持当前启用状态。+- Host receipt 是安装事务和运行完整性的状态记录,不是一次交互式“能力授权”。合法的安装/更新+ 事务直接写入 receipt,钉住 canonical manifest、trust、启停态与随机 `revision`;+ `ghostInstallApprovalToken()` 只是 Renderer 与 Main 之间防止并发漂移的前置条件,不是权限凭证。+ 没有或损坏 receipt 的存量安装优先走自动迁移/对账,不能改成逐插件能力确认弹窗。+- receipt 不等于“安装目录从此不可变”的证明:普通 `packageSha256` 仍是安装时点来源指纹;+ 真正越出沙箱的技能继续使用 receipt 绑定的字节指纹与 Host 状态根快照。不要把审计字段误写成+ 全量运行时内容校验,也不要因取消能力确认弹窗而删除现有完整性守门。+- **Forge 的源码区与 Host 受管根互斥。** `ghost_forge_scaffold` / `ghost_forge_pack` /+ `ghost_forge_install` 的目标+ 必须是当前会话工作目录里的独立作者目录;命中安装根或状态根一律拒绝,并按 realpath+ 挡住大小写折叠与软链/junction 别名。`ghost_forge_pack` 只负责校验与打包;只有用户明确+ 要求后调用独立的 `ghost_forge_install` 才安装或更新,不因 scaffold/pack 成功而隐式安装。+- `skill` 是唯一**越出沙箱**的能力:技能指令由主 Agent 以用户全部权限执行、全局生效、不随 workdir 级停用隐藏。其安全边界是**声明一致性**(manifest 里的name/description 必须与 SKILL.md frontmatter 逐字一致,`skillSlot.ts` 的- `checkSkillMdConsistency` 是唯一裁判,打包与装入、以及批准快照三侧共用;注意它**只**+ `checkSkillMdConsistency` 是唯一裁判,打包与装入、以及 Host 固化快照三侧共用;注意它**只**校验 frontmatter 的 name/description,正文与辅助文件不在它的判据里)+- **批准快照与字节指纹**(确认时把技能目录逐字节拷进+ **Host 固化快照与字节指纹**(安装/更新事务提交时把技能目录逐字节拷进`<状态根>/skill-snapshots/<id>/<revision>`,只收普通文件,同时把逐 item 的内容指纹钉进 receipt 的 `skillContentSha256`——装入/更新时该指纹取自 **`.cindy` 包的内存投影**(inspect 时已被 `packageSha256` 钉住的那份字节),不从已发布的可变安装目录首读:publish 与首次 hash 之间被换的字节应当在快照对账时被拒,而不是被首读钉成- 批准基线;确认框看到的 SKILL.md 必须就是 Agent 之后+ 固化基线;安装事务校验的 SKILL.md 必须就是 Agent 之后读到的那份,所以共享技能根的链接指快照而不是可被改写的 `cindy-brain/<id>/<dir>`。快照缺失需要从安装目录重建时,**顺序本身就是安全性质**:先把字节复制进状态根的临时目录,再对**临时目录里那份即将成为快照的字节**做全部权威校验(尺寸上限 →@@ -121,8 +166,9 @@权威路径上真正生效,且不为一份注定被拒的字节先付一整趟读取成本。指纹计算一律流式喂入、不整份读进内存(技能目录里除 SKILL.md 之外的文件没有尺寸上限,整份读会被一个塞进来的超大辅助文件撑爆)。只靠 `checkSkillMdConsistency` 拦不住"frontmatter 不动、改写正文或塞- 辅助文件",那会把一份没人确认过的指令在一次启用里固化成已批准快照并全局挂链。- 对不上一律拒、退回完整重新确认,不许就地自愈成新批准;`skillContentSha256` 因此是+ 辅助文件",那会把一份未经合法安装/更新事务校验的指令在一次启用里固化成+ 宿主快照并全局挂链。对不上一律 fail closed,要求重新安装合法包,不许就地自愈成新固化状态;+ `skillContentSha256` 因此是**运行期判据**,与只作审计用的 `packageSha256` 不同,且必填——留"字段缺失就跳过校验"的可选口子等于给漂移开一条绕过路径)+ **链接对账**(`reconcileGhostSkillLinks` 只增删"目标落在安装根或批准状态根内的 symlink/junction",绝不触碰真实目录与外来链接;@@ -151,10 +197,10 @@`cindy-ghost-content-v2` + UTF-8 路径长度前缀 + 每文件摘要),不得恢复成`path + NUL + bytes + NUL`;文件内容本身允许包含 NUL,分隔符编码会产生不同文件树的等摘要。该编码升级同步 bump `GhostInstallReceipt` schema;旧 receipt 必须- fail closed 并重新确认,不能拿旧摘要继续授权。**编码 bump 属于第 5 节的存量兼容+ fail closed 并按第 5 节迁移,不能拿旧摘要继续授权。**编码 bump 属于第 5 节的存量兼容场景**:先按**旧编码**核对旧摘要与当前安装字节,对得上就原地重算成新编码并升级- receipt(安全水位与旧版本已提供的保证等价),只有对不上(真漂移)才 fail closed 到- 重新确认——不得把一次纯格式升级直接变成全体用户重新确认。+ receipt(安全水位与旧版本已提供的保证等价),只有对不上(真漂移)才 fail closed 并+ 要求重新安装合法包——不得把一次纯格式升级直接变成全体用户的重新安装操作。- 同理,"源目录与受管根的包含关系"必须**双向**判(既不能落在受管根内,也不能是受管根的祖先):单向判定下只要在 owner 数据目录里放一个 `ghost.json`,递归打包就会把已安装插件字节、批准 receipt 与技能快照打进 `.cindy`。@@ -163,7 +209,10 @@## 4. 网络、凭证与资源交接-- network 只允许 manifest 白名单域名;凭证由主机保险库注入,**无明文读回**给沙箱。+- 自主 network 只允许 manifest 白名单域名;凭证由主机保险库注入,**无明文读回**+ 给沙箱。Agent 在途调用可凭严格 `callId` 访问未预声明的普通 HTTPS 地址,仍须通过+ 主机 URL、SSRF、超时、体积与重定向守门。此途径不注入任何未在 manifest 中声明且+ 未命中目标 host 的托管凭证。- `source: "gh-cli"` 是只为官方 `cindy-github` 保留的宿主凭证来源:Host 优先读取本机 `gh auth token`,不可用时才回落到同 key 经 `/secrets` 保存的 PAT。两种 token均只在 Main 的 networkSlot 内存中注入 `api.github.com` 的@@ -222,7 +271,7 @@记忆。附件自动交接必须写独立 `ghost-tool-grant`,不得写 `ghost-grant`;这是回退兼容边界——旧客户端只认识后者,降级时必须 fail closed,不能把新版自动交接误读成人工永久授权。热切回其它档位后新请求必须恢复确认。此旁路**不适用于** workspace 创建、插件- Setup/安装/更新、OAuth、Secret/凭证或其它确认边界。+ Setup、OAuth、Secret/凭证或其它运行时确认边界,也不改变第 3.1 节的安装/更新策略。`dir`/`save_dir` 批准的是裁决时解析到的 canonical realpath 快照;出票必须使用该规范路径并在票据库内重新解析核对,路径映射已变化时拒绝并要求重新确认。出票后真正读/写时仍须再次核对根与目标真身;保存文件必须排他创建且不跟随最终 symlink,不能让短命票据留下消费期@@ -242,7 +291,7 @@`args.attachments`,绝不把本地绝对路径暴露给插件。插件自行保存业务状态和更新 UI。Host 不自动回调插件,也不得新增画廊等插件业务语义。- 面板供片与注入的主题 token 只用 `ghostPanelTheme.ts` 白名单内的值,不扩大暴露面。-- `ios-simulator` 槽只允许读取 Host 当前台前任务的公开模拟器状态,并请求打开既有+- `iosSimulator` 能力只允许读取 Host 当前台前任务的公开模拟器状态,并请求打开既有Host viewer。请求协议不得出现插件自报 `sessionId`,可选 `instanceId` 必须重新匹配当前任务的公开实例。视频帧、viewer lease、触控、Sidecar/Helper、artifact 路径、进程句柄和私有诊断都不得跨进插件沙箱;Agent 侧构建/安装/控制继续走 Host 注册的@@ -252,34 +301,35 @@## 5. 存量插件兼容:升级必须无感(红线)-**红线**:插件系统的任何改动,都不得让用户本地**已安装、已批准、已启用**的插件在升级-后变得不可用,也不得要求用户重新安装、重新确认权限、重新配置凭证或重新落一次技能。+**红线**:插件系统的任何改动,都不得让用户本地**已安装、已启用**的插件在 Cindy 升级+后变得不可用,也不得要求用户重新安装、额外确认、重新配置凭证或重新落一次技能。升级后的默认结果只有一个:用户什么都不做,插件照旧能用。- **判据是用户视角的可用性,不是代码路径没报错。** 插件还在列表里但被标成「已停用」- 「失效」「需重新确认」「需重新安装」,或者启用按钮点不动、技能链断了、面板打不开、+ 「失效」「需恢复安装」,或者启用按钮点不动、技能链断了、面板打不开、已配置的凭证要重填 —— 都算不可用。「fail closed 得很干净」不是通过条件。-- **触及范围**(改这些就命中本节,逐条按"老数据怎么办"设计):批准 receipt 的- schema/字段必填性/落盘位置、指纹与摘要编码、`validateGhostManifest` 的校验规则、- slot 名称与参数形态、技能快照布局与链接命名、安装根与状态根路径、`.cindy` 包格式、+- **触及范围**(改这些就命中本节,逐条按"老数据怎么办"设计):宿主侧批准状态记录+ (receipt 一类)的 schema/字段必填性/落盘位置、指纹与摘要编码、+ `validateGhostManifest` 的校验规则、能力字段与参数形态、技能快照布局与链接命名、+ 安装根与状态根路径、`.cindy` 包格式、管子协议消息形态、随包种子与内置插件 id/前缀、市场侧的 id 与版本口径。- **新增校验或新增必填字段,默认必须自带迁移(backfill),不是自带拒绝。** 老数据缺新字段是**升级前的正常历史状态,不是攻击证据**,不得按篡改处理。迁移的判据是"能不能- 从旧版本自己的授权事实重建出等价物":- - 例:receipt 机制上线前的安装,授权事实就在安装目录的 `ghost.json` /+ 从旧版本自己的安装验证事实重建出等价物":+ - 例:receipt 机制上线前的安装,等价事实就在安装目录的 `ghost.json` /`.cindy-trust.json` / `.disabled` 三份文件里(第 3 节所说的"旧版本兼容镜像")。宿主必须能一次性读它们 backfill 出等价 receipt,用户无感。- **迁移不得成为扩权或降级通道**,这是它与安全不变量共存的前提:迁移只在该 id- **从未有过 receipt**(或 receipt 已判损坏)时发生,权限集原样取旧记录、不做并集、- 不吞新增 slot;迁移出的授权**只等价于旧版本已经给出的授权,不等价于一次新的用户- 确认**,因此此后任何 manifest/权限变化照旧走完整确认;迁移来源必须记进日志,- 便于事后分辨"用户确认过"与"宿主迁移来的"。+ **从未有过 receipt**(或 receipt 已判损坏)时发生,manifest 及运行事实原样取旧记录、+ 不做并集、不吞新增能力;迁移只重建旧版本已有的等价安装验证状态,之后的+ manifest 变化只能由新的合法安装/更新事务固化;迁移来源必须记进日志,便于事后分辨+ “正常安装写入”与“宿主迁移来的”。- 迁移**读不出**(文件缺失、格式坏)或**自相矛盾**(镜像与内容互斥)时才 failclosed,落到下面的兜底义务。- **receipt schema/指纹编码 bump 必须走「按旧编码核对 → 原地升级」,不是 fail closed- 到重新确认。** 纯格式变更时旧 receipt 的授权事实没有消失:先用旧编码核对旧摘要与当前+ 到用户重新安装。** 纯格式变更时旧 receipt 的安装验证事实没有消失:先用旧编码核对旧摘要与当前安装字节,对得上就原地重算成新编码并升级 receipt,只有真漂移才 fail closed。一次内部- 格式变更不得变成全体用户重新确认。历史注:v1→v2(NUL framing 修复)没有专门的 v1+ 格式变更不得变成全体用户重新安装。历史注:v1→v2(NUL framing 修复)没有专门的 v1读取器,因为 v1 receipt 从未随任何构建发布、全网不存在;同时一次性 legacy 迁移会把「已判损坏」的 receipt 从安装目录 backfill 治愈,效果上覆盖了该场景(有回归用例钉住)。**从 v2 起的任何 bump 都必须实现原地升级器**,不得再引用本注作为豁免。@@ -290,7 +340,7 @@提供**一次性批量恢复入口**;不得只留"去市场逐个重装",也不得让它看起来像是用户自己关掉的(与第 3 节的 UI 义务同一条)。3. **不丢用户本地状态**:恢复过程不得清掉已保存的凭证/Secret、KV、per-plugin 偏好、- errand 配置、面板状态。恢复的是授权,不是用户的配置。+ errand 配置、面板状态。恢复的是安装验证记录,不是用户的配置。4. **留回滚余地**:新版本写出的状态被旧版本读到时不得当成损坏——未知字段忽略而不是判 `invalid`,否则用户一旦回退旧版就再炸一次。- **测试门槛**:命中本节的 PR 必须有"从旧状态升级"的自动化用例——fixture 造出老布局@@ -299,6 +349,16 @@- **PR 约束**:命中本节的 PR,Description 必须写明「存量插件影响:无」或「有 + 迁移与提示方案」,并说明上面的升级用例跑在哪。会让存量插件失效的改动与 mobile 冷更同级:需仓库把关人针对该影响明确确认后才能合并,提交者身份不构成例外。漏迁移 = P0。+- **插件基座改动一律走白名单确认门。** 「基座」= 所有已装插件共同踩着的那一层:运行时与+ 沙箱、来源/信任 receipt、能力声明、打包与内容判据、manifest 契约、装入与能力说明 UI、已装+ 列表投影(`main/cindy-brain/`、`main/plugin-market/`、`main/mcp-integrations/ghost.ts`、+ `shared/ghost.ts`、`packages/cindy-tools` 的 ghost 部分,以及 renderer 侧的+ `installFlow.tsx`/`installErrorKey.ts`/`GhostPluginDetailView.tsx`/`useInstalledGhosts.ts`/+ `runtimeStates.ts`/`features/plugin/lib/ghostPluginViewModel.ts`/+ `features/plugin/lib/pluginMarketPresentation.ts`)。命中即需放行人在 PR 上明确+ Approve 才能合并,**不看 diff 大小,也不因为「是 bugfix/纯技术改动」就放过**——#1080+ 正是以 `fix` 身份、按纯技术改动被放过的。这条与本节前面的义务是一套:门只保证「有人+ 看过存量影响」,看什么按上面逐条对。纯粹改插件面板视觉、纯文案/locale 不算基座。- **历史教训(本节的由来)**:2026-07-31 合入的批准 receipt 改造(`ghostInstallReceipt.ts`)把"无 receipt = 不构成运行授权"一次性作用到全部存量安装,只给随包内置插件留了自动补批准的路,市场与本地安装没有 backfill 路径,结果升级后用户@@ -312,26 +372,28 @@**手册过期 = AI 按旧规则写出过不了校验的插件包**(校验拒装只是兜底,用户体验是“AI反复打包反复被拒”)。+`ghost_forge_pack` 的边界严格止于校验和生成 `.cindy` 产物;打包成功不构成安装依据,+不得顺带安装、更新或启用插件。安装由用户导入本地包、明确要求当前 Agent 调用独立的+`ghost_forge_install`、点击市场安装或服务端 `defaultInstall` 明确触发;Forge 安装与本地+导入必须复用同一套 Main 安装/更新事务。+凡改动**插件作者可见的契约**,同一改动内必须同步更新手册对应章节:- (a) `ghost.json` 身份卡字段或校验规则(`shared/ghost.ts` 的 `validateGhostManifest`);- (b) 管子协议(`cindy.send` / `cindy.onHostMessage` 的消息形态,`shared/ghost.ts` 管子类型);-- (c) 模型能力 slot 的 kind/参数/模型白名单;+- (c) Cindy 模型代办能力的 kind/参数/模型白名单;- (d) 面板供片协议与注入的主题 token(`cindy-ghost://` 分支、`ghostPanelTheme.ts` 白名单);- (e) 打包限制(`forge.ts` 的 `packGhostDir`)。+- (f) 安装、来源绑定、自动更新与能力展示的用户可见行为。-其中 `ghost.json` 属于 Ghost manifest 协议。新增或修改字段、slot 或枚举时,至少同步:+其中 `ghost.json` 属于 Ghost manifest 协议。新增或修改字段、v2 兼容映射或枚举时,至少同步:1. 协议正本 `packages/plugin-protocol/src/manifest.ts` 及其测试;2. Desktop 完整镜像 `apps/desktop/src/shared/ghost.ts` 及其测试;3. 作者文档 `FORGE_GUIDE` 的对应章节及 Forge 测试。-当前 `GHOST_SLOTS` 槽位集合中唯一登记的 Desktop-only 例外,是尚未进入跨消费者发布契约-的 `library` 槽;在其首个正式支持版本确定并完成分发端兼容设计前,不得仅为同步数组而把-它加入 `packages/plugin-protocol`。这里的「唯一」只描述槽位集合,不表示两套 validator 的-其它历史字段语义已经完全同构;`main-view` 不属于该槽位例外,两端必须保持一致。--`main-view` 的现行协议在 `FORGE_GUIDE` §4.20:`mainView.icon` 只接受 Cindy 系统线性图标+`mainView` 的现行协议在 `FORGE_GUIDE` §4.20;v2 的 `main-view` 只保留输入兼容。+`mainView.icon` 只接受 Cindy 系统线性图标`puzzle`、`globe`、`code`、`folder`、`database`、`chart-column`、`image`、`message-circle`、`calendar-days`,缺省回退 `puzzle`。枚举值直接等于图标名,不设别名;该字段只控制主视图侧边栏入口,不替代或修改根级 `icon` 品牌图片协议。后续扩展该枚举时也@@ -347,60 +409,16 @@以下缺口在触及相关链路时必须一并修复,或在 PR 中保留明确的正式跟踪,不得静默丢弃:-- **【已修复|第 5 节红线迁移】存量安装的 receipt backfill。** receipt 机制上线前装的- 插件没有 receipt,`GhostManager.migrateLegacyApprovalsOnce()` 在每轮对账前跑一次(首次- 之后凭迁移 ledger 瞬时 no-op),从旧的三份事实源(`ghost.json` / `.cindy-trust.json` /- `.disabled`)重建等价 receipt,让市场与本地安装升级后无感可用;随包内置插件仍走- provisioning 的 `approveTrustedBundledInstall`(有权威字节可比,是更强的迁移形态),不- 重复迁移。三条不变量:**全局一次性且崩溃安全**(ledger 是 in-progress→completed 两态状态机:- 首个 backfill 动笔前先原子落 `in-progress` 并钉死本轮 `pendingIds`,全部处理完才原子- 改写成 `completed`;`completed`/存在但读不出 = 门关死,此后缺 receipt 一律 fail closed- ——否则删 receipt 就能骗一次"从可变安装目录重建授权";`in-progress` = 上一轮中途崩溃,- 续跑**只认清单内的 id**,迁移窗口期间新装再删 receipt 的 id 骗不到重铸;receipt 首写- 在 receipt rename 生效**之前**先补落 completed 台账,且落账失败就拒绝本次批准;它只在- "完全没有台账"时动笔,不覆盖 in-progress。该门是充分- 守卫,因为能删/改 ledger 的进程本就能直接写伪造 receipt,见下「批准状态根无写保护」)、**不扩权**(权限集原样取当前 `ghost.json`,等价于旧模型无条件- 授权的那一组,此后任何 manifest/权限变化照旧走完整确认)、**只写状态根不动安装目录**- (三份旧文件原样保留,回滚到旧客户端时仍按安装目录判定,符合第 5 节兜底第 4 条)。核心- 授权事实读不出(manifest 不合法、技能目录含链接、声明的 locale 装入后损坏)才对该插件- fail closed、走恢复 UI;trust 镜像缺失降级为 `unverified`;旧目录无法反推出原始 `.cindy`- 整包的 `packageSha256`,故省略(组织市场 Broker 因此 fail closed,既有市场 OIDC 不变)。- 改动装入/迁移链路时保持这些不变量,尤其不得把迁移改成"每次缺 receipt 就补"- (那就是把授权事实重新交给可变安装目录,等于回到 #636)。迁移之后批准再丢失的恢复- 路径:市场包走市场重装确认;本地包走「从已装目录重新确认」(`ghosts:reapprove-inspect`- → 确认卡全量权限清单 → `ghosts:reapprove-installed`,清单字节以 manifestSha256 绑定- 确认间隙,trust 走与迁移同一个封顶读取器,装入侧的指令查重/tokenBroker/保留前缀- 门禁照走)—— 不要求用户重新提供原始 `.cindy`,不存在不可恢复状态;随包插件不走人工- 确认,由启动对账自动补(UI 提示「重启应用即恢复」)。一次性门的完整判据:ledger- `completed`(或存在但读不出)永久关门;`in-progress` 只按动笔前钉死的 `pendingIds`- 续跑;无 ledger 时先扫描完整安装根,不能因某一个有效 receipt 提前关门——曾短暂合入- 后回滚的 #1080 可能留下「部分有效 receipt + 其余 legacy 安装 + 无 ledger」的历史 mixed- 状态,提前关门会让其余插件永久失效。新代码必须在**首次写任何 receipt 前**先原子落- completed ledger,落账失败则 receipt 不得生效(否则「新装 receipt 后、下一轮对账前」- 删 receipt 可骗一次按已扩权 manifest 的重铸);legacy migration/recovery 已先落- in-progress,因此首份 backfill receipt 不会覆盖迁移清单。- 安装根为空/未诞生时**不落 ledger**——门要留给 owner 命名空间 legacy 恢复流程随后搬入- 的旧目录;恢复流程对刚搬入的 id 走 `backfillRecoveredLegacyGhosts` 旁路(信任级与首轮- 迁移等同,只作用于恢复流程自己搬动的 id)。安装根读失败(非 ENOENT)整轮放弃且不落- ledger,下次启动重试。迁移失败的 id 记进 ledger 的 `failedIds` 供排查,逐个走上面的- 恢复入口。整轮对账(迁移+播种+批准写入)与「从已装目录重新确认」都必须持- GhostMutationCoordinator 的 owner 租约——状态根路径是每次调用现解析的,不持租约时- 异步 hash/copy 中途账号切换落定,写入会漏进新 owner 的状态根。-- **manifest 枚举扩展在客户端降级方向不兼容(#1283 披露)。** `validateGhostManifest()`- 对 `slots` / `subscribe.topics` 的未知枚举值、以及 `schemaVersion` 不等于 2,都是整份- 判无效(`return { ok: false }`);而 `GhostManager.list()` 每次调用都重新校验已装目录,- 无效即 `continue` 跳过。所以用户把客户端**降级**到某个枚举值引入之前的版本后,声明了该值- 的插件会从已装列表**整个消失**(不是能力降级)——界面上看不到、无从修复,已存凭证与偏好- 变成孤儿。这不是某次扩展的疏漏:校验器只在**字段**级向前兼容(「宽进严出:忽略未知字段」),- 不在**取值**级向前兼容,历史上每次新增卡槽都有同样特征。已发布的旧版无法追改,唯一可行- 方向是让**新版**把未知枚举值降级为「忽略 + warn」而非整份拒绝,使此后的扩展天然降级安全- (救不了「从引入版降到引入前」那一段,任何方案都救不了)。改动方向本身要过第 5 节红线- 评估:放宽校验等于让主机接受读不全的权限声明,不能顺手做。**触及 `validateGhostManifest()`- 的枚举白名单、或 `GhostManager.list()` 的跳过逻辑时必须一并考虑。**- 新版 Host 的本地装入/更新/inspect 已先识别“未来 `schemaVersion`”与“形状合法但未知的- 字符串 slot”,并以 `GHOST_HOST_UNSUPPORTED` 引导升级,不再把这两类新能力包误报为非法。- 这只改善新版 Host 的错误分类,不改变严格校验,也无法追改已经发布的旧 Host;已装插件在- 客户端降级后从列表消失的兼容缺口仍然存在。+- **存量安装的 receipt backfill 必须无感。** `GhostManager.migrateLegacyApprovalsOnce()` 在对账前+ 从旧安装事实重建等价的安装状态记录;迁移必须崩溃安全、不扩张 manifest 能力、只写状态根,+ 并受 owner 租约保护。能自动重建时不得要求用户重新安装或确认能力;确实无法重建时应进入统一的+ legacy recovery 状态并保留凭证与偏好,不能伪装成普通停用,也不能把能力审批弹窗当恢复方案。+- **manifest 扩展的降级兼容(#1283)。** v3 通过“未知顶层字段原样保留,但当前 Host+ 不展示、不授权、不阻止安装”解决向前兼容;能力一旦被 Host 支持,必须成为明确的直接字段+ 和权限映射。v2 仅保留输入兼容:未知但格式合法的 slot 允许安装、运行时不提供能力。+ 不得恢复独立的 Host slot 支持表或按名字猜测映射。`subscribe.topics` 等带具体+ 运行语义的子枚举仍严格校验;`schemaVersion > 3` 仍以 `GHOST_HOST_UNSUPPORTED` 拒绝,避免+ 当前 Host 误读整体结构变化。已经发布的旧 Host 无法追改,降到 v3 改造前仍可能拒绝新清单。- `networkSlot.ts` 的 `as: 'media'` 不能只信任 Content-Type(GLB 常见`application/octet-stream`),需要安全的 magic-byte/扩展名嗅探。- SSH 远程场景必须让 `LiziMcpSessionContext` 携带 remote 标识;目录过户不得回退读取本机@@ -420,7 +438,7 @@快照前核一次、复制到临时目录后核一次、`rename` 就位后再核一次(`skillSnapshotMatchesReceipt`是唯一判据)。因此"复制完到 rename 之间被改写"与"快照事后被就地改写"都会在下一次写批准事实时暴露:对不上就删掉重建,重建仍要过安装目录的字节校验,安装字节也漂移- 时一律拒绝并退回完整重新确认。+ 时一律拒绝并要求重新安装合法包。- **仍未关闭(消费侧瞬时窗口)**:启动/装卸/启停广播触发技能对账时,Host 会在建立或保留共享链接前重新核对整棵批准快照;但这次核对之后、主 Agent 顺着共享技能链接读取之前,快照仍可被同权限进程改写。Agent 的读取路径不在宿主控制内,宿主不做逐次@@ -451,42 +469,26 @@ topic 路由;产品层多端语义见1. 沙箱是否保持进程隔离、专属 partition、无 Node/宿主 FS/网络直连?身份是否由主机反查而非信任 sender 自报?-2. 新能力是否先在 manifest 声明 slot、走同一套校验、在确认框如实展示后才由 host 授权?-3. 运行授权是否只取自 Host receipt,而不是可变安装目录?无批准/损坏批准是否 fail- closed(列为停用、不许启用、不落技能链),且 UI 如实说明并给出重新确认入口?停用- 方向是否无论环境如何都能成功?改了技能落链或快照时 `approvalStateRoot` 是否仍必填?- 任何"从安装目录取字节"的路径(快照重建等)是否都复现了装入侧的门槛——字节指纹逐项- 对上、SKILL.md 定长后再读?失败时是拒绝并退回重新确认,而不是就地自愈成新批准?-4. 网络是否限白名单域名、凭证无明文读回?附件/媒体/目录是否经归属校验的- grant/deposit/ledger 交接,未暴露宿主绝对路径?+2. 是否先按执行者分清边界:当前 Agent 在途的通用操作是否严格绑定同插件、同会话、+ 未交卷的 `callId` 并复用 Agent 授权;插件自主 Host 能力是否以 manifest 直接字段声明、+ 在详情如实展示并由 Host 守门?是否误把安装弹窗或前端展示当成授权事实?+3. receipt 是否仍只由 Main 的合法安装/更新/迁移事务写入?跨进程更新是否回传+ `ghostInstallApprovalToken()` 并在锁内重读比对?缺失或损坏状态是否优先无感迁移,+ 而不是重新引入能力确认?停用方向是否始终可成功?技能快照与字节指纹是否仍受保护?+4. Agent 在途网络是否仍通过 URL/SSRF/重定向等 Host 守门,自主网络是否限 manifest+ 白名单,托管凭证是否只向声明且命中的 host 注入、无明文读回?附件/媒体/目录是否经+ 归属校验的 grant/deposit/ledger 交接,未暴露宿主绝对路径?5. 内联凭证是否只走 trusted Desktop 专用 IPC,未登记 device-link?Main 是否重新校验- sender、request、revision、action、精确字段集合与 manifest 绑定,且没有把 Renderer- 字段 id 直接当作 Secret key/路径?保险库写失败是否不 emit,写成功后是否仍重新- assessment,而不是把“提交完成”当作 ready?-6. Forge(scaffold/pack)是否排除了 Host 受管根(安装根 + 批准状态根),且按 realpath- **双向**判定(源目录既不在受管根内、也不是它的祖先)、挡住大小写与软链/junction- 别名?递归收集是否不跟随链接进受管根?-6.5. 新增的"读插件内容目录"代码是否走 `ghostContentTree.ts` 取判据(`lstat` 分类 +- 相对路径逐段解析 + 统一指纹格式),而不是就地 `readdir` + `isDirectory()` 或 `stat`- 直读?策略差异(点开头条目算不算内容、非普通条目 throw 还是 flag)是否以显式参数- 表达而不是复制一份实现?-6.5a. **新增的路径式 worker(skill snapshot、Forge scaffold 等)是否采用- 「操作前检查(fast fail)→ 原子操作 → 操作后复验 → identity-guarded cleanup」- 模式,而不是仅靠操作前检查判定安全?** 操作后复验是否落在原子操作**之后**、- 无 TOCTOU 间隙的位置(如 `rename` 之后立刻 `lstat` + identity compare,而不是- 在 `rename` 之前加更多 `lstat`)?pre-check 与 rename 之间的间隙是 Node.js 未暴露- `renameat` 等 fd-relative 原语的硬边界,不可消除——因此安全判定必须在操作之后做。- cleanup 时是否按 `dev`/`ino` identity 守卫而非仅按 pathname 删除?-6.6. **存量插件升级后还能不能用(第 5 节红线)**:本次是否改了 receipt schema/必填- 字段/落盘位置、指纹或摘要编码、manifest 校验、slot 形态、快照与链接命名、安装根或- 状态根路径、`.cindy` 包格式、管子协议、内置 id?命中就逐条问:用户升级后**什么都不做**- 时,已装、已批准、已启用的插件是否照旧可用?新增的必填字段/新校验是否自带从旧版- 授权事实的 backfill,而不是把"老数据缺字段"当篡改直接 fail closed?迁移是否只在- "从未有过 receipt/已判损坏"时发生、权限集原样不扩权、来源有日志?自动做不到时是否- 有明确提示 + 一次性批量恢复入口(不是"去市场逐个重装")、且不清掉用户已存的凭证与- 偏好?新状态被旧版本读到是否不判损坏(可回滚)?是否有基于旧布局 fixture 的升级用例,- 而不是只测全新安装?让存量插件失效且无迁移 = P0,需把关人对该影响明确确认。-7. 改动是否命中作者可见契约(身份卡/管子/模型 slot/面板供片/打包)?命中就必须+ sender、request、revision、action、精确字段集合与 manifest 绑定?+6. Forge(scaffold/pack/install)是否排除了 Host 受管根,按 realpath 双向判定并挡住+ 大小写与软链/junction 别名?`ghost_forge_pack` 是否仍然只产出 `.cindy`,没有隐式安装;+ `ghost_forge_install` 是否只在用户明确要求时调用并复用本地安装/更新事务?+6.5. 新增的“读插件内容目录”代码是否走 `ghostContentTree.ts` 的统一分类、逐段路径解析和+ 指纹格式,而不是就地复制一份 `readdir`/`stat` 实现?+6.6. **存量插件升级后还能不能用(第 5 节红线)**:改动安装状态记录、manifest、能力字段、+ 快照、安装根、包格式或管子协议时,是否提供无感 backfill,保留已装、启停、凭证与偏好,+ 并覆盖旧布局 fixture?让存量插件失效且无迁移 = P0。+7. 改动是否命中作者可见契约(身份卡/管子/模型代办能力/面板供片/打包)?命中就必须同步 `FORGE_GUIDE` 并在 PR 说明;漏同步 = P1。8. 第 7 节的已知缺口是否被触及?触及是否一并修复或留了正式跟踪?9. 新增 IPC/推送是否需要远程/手机版?需要就登记 device-link 白名单与 topic 路由。diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 75cf04160c..ac2da48128 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -41,26 +41,22 @@- 插件运行时保留,用户通过 SkillHub 或手动安装 `.cindy` 包;没有任何插件时启动和开发不应因此失败。- 不要重新引入预装/播种机制或私有种子 submodule;需要推荐插件时走 SkillHub 的- 分发与安装确认流程。+ 分发与用户主动安装流程。## 3. Ghost manifest 与 Cindy 专属界面能力-- `ghost.json` 的跨消费者字段、slot 与枚举属于 Ghost manifest 协议,客户端正本位于+- `ghost.json` 的跨消费者字段、v2 兼容映射与枚举属于 Ghost manifest 协议,客户端正本位于`packages/plugin-protocol/src/manifest.ts`;Desktop 在`apps/desktop/src/shared/ghost.ts` 维护运行时 validator。除明确登记的 Desktop-only能力外,两份实现及相同的有效/无效 fixture 必须同步,作者契约同时写入`FORGE_GUIDE`。-- 当前 `GHOST_SLOTS` 槽位集合中唯一登记的 Desktop-only 例外,是尚未进入跨消费者发布- 契约的 `library` 槽;在其首个正式支持版本确定并完成分发端兼容设计前,不得把它加入- `packages/plugin-protocol`。这里的「唯一」只描述槽位集合,不表示两套 validator 的其它- 历史字段语义已经完全同构;`main-view` 是跨消费者字段,不属于该槽位例外。-- `main-view` / `mainView` 是通用的 Cindy Host 界面能力,不是 `xd-sites` 专用 API,协议中- 不出现 `xd-sites` 的端点、OIDC 流程或业务模型。具体插件可在它已获批准的其它 slot 内调用- 自己的服务,基座只负责声明校验、授权、导航和沙箱承载。+- `mainView` 是通用的 Cindy Host 界面能力,不是 `xd-sites` 专用 API;v2 的 `main-view`+ 只保留输入兼容。协议中不出现 `xd-sites` 的端点、OIDC 流程或业务模型。具体插件可通过+ 其它已声明且经运行时守门的能力调用自己的服务,基座只负责声明校验、导航和沙箱承载。- `mainView.icon` 是主视图入口的 Host 系统图标枚举,只作用于该入口;根级 `icon` 仍是插件品牌图片协议。字段白名单、默认回退与完整枚举见 `FORGE_GUIDE` §4.20,不能用图片路径或未声明别名绕过枚举。-- 如果 Plugin Market/服务端仓会解析或严格校验新增的 manifest slot/枚举,发布使用新能力+- 如果 Plugin Market/服务端仓会解析或严格校验新增的 manifest 字段/枚举,发布使用新能力的插件前必须同步其本地 `plugin-protocol` 实现;这不要求 Cindy 客户端运行时依赖服务端,也不改变两仓独立发布边界。diff --git a/docs/ios-simulator-release-guide.md b/docs/ios-simulator-release-guide.mdindex 8348afea9d..82713e818d 100644--- a/docs/ios-simulator-release-guide.md+++ b/docs/ios-simulator-release-guide.md@@ -79,5 +79,7 @@ Helper 发生任何代码变化后,必须重新执行完整的 Cindy.app 打## 插件发布顺序如果同时发布 iOS 模拟器官方插件,应先发布包含 Host 能力和 Helper 的 Cindy 版本;验证成功后,-再把插件的 `minCindyVersion` 设置为这个实际发布版本并发布插件。这样旧版 Cindy 用户会收到明确的-升级提示,而不会安装一个 Host 尚不支持的插件版本。+再把插件的 `minCindyVersion` 设置为这个实际发布版本并发布插件。官方市场会继续给旧版 Cindy+投影最近的兼容历史版本;没有兼容版本时不展示该插件。用户若通过本地包或自定义市场主动安装+其它版本,Desktop 不再按 `minCindyVersion` 二次拦截或弹确认;当前 Host 尚未提供的能力在运行时+仍不可用,因此插件必须正确处理 Host 能力缺失。diff --git a/packages/cindy-tools/src/__tests__/ghostMcp.test.ts b/packages/cindy-tools/src/__tests__/ghostMcp.test.tsindex 8c60e43d3a..588176996d 100644--- a/packages/cindy-tools/src/__tests__/ghostMcp.test.ts+++ b/packages/cindy-tools/src/__tests__/ghostMcp.test.ts@@ -7,6 +7,7 @@ import {ghostForgePublishInputSchema,ghostSetupPlanInputSchema,handleForgeGuide,+ handleForgeInstall,handleForgePack,handleForgePublish,handleForgePublishStatus,@@ -71,7 +72,16 @@ function fakeDeps(id: "x",name: "X",version: "1.0.0",- note: "pending confirm",+ note: "packed",+ }),+ forgeInstall: async () => ({+ ok: true,+ action: "installed",+ id: "x",+ name: "X",+ version: "1.0.0",+ enabled: true,+ note: "installed",}),forgePublish: async () => ({ok: true,@@ -1172,6 +1182,7 @@ describe("cindy_ghosts · server 构建", () => {expect(Object.keys(server._registeredTools).sort()).toEqual(["ghost_call","ghost_forge_guide",+ "ghost_forge_install","ghost_forge_pack","ghost_forge_publish","ghost_forge_publish_status",@@ -1477,7 +1488,7 @@ describe("cindy_ghosts · ghost_forge(锻造)", () => {const requests: Array<{dir: string;iconSource?: string;- intent?: "install" | "publish";+ intent?: "publish";}> = [];const deps = fakeDeps({forgePack: async (request) => {@@ -1510,6 +1521,58 @@ describe("cindy_ghosts · ghost_forge(锻造)", () => {]);});+ it("forge_install 透传源码目录与可选图标并返回真实安装动作;失败标 isError", async () => {+ const requests: Array<{ dir: string; iconSource?: string }> = [];+ const installed = await handleForgeInstall(+ fakeDeps({+ forgeInstall: async (request) => {+ requests.push(request);+ return {+ ok: true,+ action: "updated",+ id: "my-ghost",+ name: "My Ghost",+ version: "1.0.0",+ enabled: false,+ note: "updated",+ };+ },+ }),+ {+ dir: "/src/my-ghost",+ icon_source: `cindy-media://blobs/${"a".repeat(64)}.png`,+ },+ );+ expect(parsePayload(installed)).toMatchObject({+ ok: true,+ action: "updated",+ id: "my-ghost",+ enabled: false,+ });+ expect(requests).toEqual([+ {+ dir: "/src/my-ghost",+ iconSource: `cindy-media://blobs/${"a".repeat(64)}.png`,+ },+ ]);++ const failed = await handleForgeInstall(+ fakeDeps({+ forgeInstall: async () => ({+ ok: false,+ errorCode: "GHOST_FILE_INVALID",+ message: "invalid package",+ }),+ }),+ { dir: "/src/bad" },+ );+ expect(failed.isError).toBe(true);+ expect(parsePayload(failed)).toMatchObject({+ ok: false,+ errorCode: "GHOST_FILE_INVALID",+ });+ });+it("forge_publish 只透传 opaque token 并立即返回 transferId;失败标 isError", async () => {const requests: Array<{ token: string }> = [];const okResult = await handleForgePublish(fakeDeps(), {@@ -1614,20 +1677,23 @@ describe("cindy_ghosts · ghost_forge(锻造)", () => {expect(description).toContain("xdt_image_url");expect(description).toContain("xdt_image_urls");expect(description).toContain("icon_source");+ expect(description).toContain("缺省只打包并返回产物路径");expect(description).toContain("intent=publish");expect(description).toContain("intent=publish 仅企业组织成员可用");- expect(description).toContain("个人账号不可用,请用缺省的 install");+ expect(description).toContain("个人账号仍可使用缺省的纯打包模式");const intentDescription =server._registeredTools.ghost_forge_pack?.inputSchema?.shape?.intent?.description ?? "";// Excludes documenting the organization restriction only in the tool summary// while the registered intent parameter still advertises publish to everyone.expect(intentDescription).toContain("publish 仅企业组织成员可用");- expect(intentDescription).toContain("个人账号不可用,请用缺省的 install");+ expect(intentDescription).toContain("个人账号仍可使用缺省的纯打包模式");const publishDescription = server._registeredTools.ghost_forge_publish?.description ?? "";expect(publishDescription).toContain("publishToken");expect(publishDescription).toContain("仅企业组织成员可用");expect(publishDescription).toContain("个人账号不可用");+ expect(description).toContain("不安装或更新插件");+ expect(description).not.toContain("确认框");});it("forge_publish_status 在上传成功后收口,不守着轮询人工审核", () => {diff --git a/packages/cindy-tools/src/ghost/mcpServer.ts b/packages/cindy-tools/src/ghost/mcpServer.tsindex 95737e9934..3bbc6f1ec0 100644--- a/packages/cindy-tools/src/ghost/mcpServer.ts+++ b/packages/cindy-tools/src/ghost/mcpServer.ts@@ -67,13 +67,16 @@ const D_GHOST_CALL = ["call_tool 两个工具,具体操作(如 create_pull_request_review)不是顶层 tool,必须经 call_tool",'下发——ghost_call({ghost_id, tool:"call_tool", args:{name:"<操作名>", args:{...}}});',"把操作名当 tool 直接调会返回 TOOL_NOT_FOUND,此时按上述形态改写重试,不要判定插件无此能力。",- "执行发生在该插件的独立沙箱中(无文件/网络访问,用 AI 走主机统一通道)。",- "用户媒体或当前 Agent / Core 工具刚生成的媒体要交给插件处理、收录时,把其地址放进顶层 attachments",+ "执行发生在该插件的独立沙箱中;插件不能直接访问 Host 文件、网络或进程。",+ "当前 Agent 调用链内,插件可以凭主机下发的 callId 经 cindy.fs / cindy.fetch",+ "请求工作目录文件或 HTTPS 能力;随包代码与 CLI 继续走插件已有的 Node 工作进程。",+ "插件工具是否执行由 ghost_call 的现有 Agent 授权决定,不另设进程执行通道。",+ "用户的图片/媒体文件要交给插件处理时,把其地址放进顶层 attachments","(不是塞进 args):主机会把图过户给该插件并以指纹注入 args.attachments,插件","声明的工具若接受媒体输入即可使用。生成结果仍由 Agent 显式交给插件,Host 不自动回调插件。","要把一个本地目录或单个文件交给插件上传(如部署构建产物)时,把其**绝对路径**放进","顶层 dir(不是塞进 args):主机会收集文件并以",- "一次性票据注入 args.dir_deposit,插件凭票上传——这是插件触碰用户目录的唯一通道。",+ "一次性票据注入 args.dir_deposit,供需要把选定目录或单文件整体交给插件的工具上传。","过户钳制(attachments / dir / save_dir 通用):路径在当前会话工作目录内直接放行;","工作目录外若是本地 Full Access(bypassPermissions)会话则自动过户、不弹卡;其它权限档及","远程会话仍向用户弹确认卡,被拒绝/超时后不要重试,转告用户即可。Full Access 自动交接",@@ -105,13 +108,13 @@ const D_MEDIA = [const D_GHOST_FORGE_GUIDE = ["获取《插件(Ghost)编写手册》——为用户制作/修改插件(.cindy 能力包)前必读。",- "手册随主机版本走,包含:设计对齐提问清单、ghost.json 身份卡全字段、全部卡槽、",+ "手册随主机版本走,包含:设计对齐提问清单、ghost.json 身份卡全字段、直接能力声明、","管子 API(cindy.send)、面板与主题、沙箱红线、打包与测试流程。整本超出单次工具",'结果上限,分章取用:不传参数返回目录,传 section(章号如 "4.7" 或章标题关键词如','"network")返回单章正文。用户说"帮我做一个 XX 插件 / 改一下某插件"时,先取目录、',"先按第 0 章「设计对齐」用带选项的提问卡片和用户确认界面形态(停靠面板/插件页内","面板/纯工具)等关键决策,再按需读相关章;新插件可用 ghost_forge_scaffold 生成骨架,",- "修改完成后再用 ghost_forge_pack 打包装入。",+ "修改完成后缺省用 ghost_forge_pack 校验并生成 .cindy 产物;只有用户明确要求直接安装或更新时,才调用独立的 ghost_forge_install。本工具自身不安装插件。",].join("\n");const D_GHOST_FORGE_SCAFFOLD = [@@ -122,14 +125,24 @@ const D_GHOST_FORGE_SCAFFOLD = [].join("\n");const D_GHOST_FORGE_PACK = [- "把一个插件源码目录校验并打包成 .cindy。缺省 intent=install,随后主机会弹出装入确认框",- '(同 id 已装则显示"更新 vX → vY");intent=publish 时不装入,只返回一次性 publishToken。',- "intent=publish 仅企业组织成员可用;个人账号不可用,请用缺省的 install。",+ "把一个插件源码目录校验并打包成 .cindy。只生成产物,不安装或更新插件。",+ "缺省只打包并返回产物路径;intent=publish 时额外返回一次性 publishToken。",+ "intent=publish 仅企业组织成员可用;个人账号仍可使用缺省的纯打包模式。","dir 传源码目录的绝对路径(目录里须有 ghost.json;打包自动跳过 .git / node_modules /","隐藏文件 / *.cindy)。仅当用户明确选择 AI 生成图标时,可把图片工具结果的","xdt_image_url 取单张地址;若只有 xdt_image_urls 则取数组第一项,再把得到的 cindy-media:// 地址传给 icon_source;主机会 best-effort 嵌入,失败保留默认图标继续打包。","失败返回结构化错误(MANIFEST_INVALID 等,message 带具体原因),",- "按 message 修正源码后重新打包即可。install 打包成功 ≠ 已装入:告知用户去点确认框;publish 不会触发装入。",+ "按 message 修正源码后重新打包即可。成功只表示 cindyPath 对应的产物已经生成;",+ "只有用户明确发起安装后,插件才会进入 Cindy。publish 同样不会触发装入。",+].join("\n");++const D_GHOST_FORGE_INSTALL = [+ "把当前源码目录重新校验、打包,并立即安装到 Cindy;同 id 已安装时原位更新。",+ "只有用户明确要求安装或更新当前插件时才调用。不要因为 scaffold 或 pack 成功就自动调用。",+ "首次安装后直接启用;更新保留原有启用状态、配置、数据与面板位置,同版本也可覆盖。",+ "dir 传当前会话工作目录内的插件源码目录绝对路径。成功返回本次真实执行的是 installed 还是 updated;",+ "仅当用户明确选择 AI 生成图标时,可像 ghost_forge_pack 一样传 icon_source。",+ "失败返回打包校验或 Host 安装事务的结构化错误。ghost_forge_pack 始终只打包,不受本工具影响。",].join("\n");const D_GHOST_FORGE_PUBLISH = [@@ -1039,7 +1052,7 @@ export async function handleForgeScaffold(/** ghost_forge_pack 的 handler 主体(导出供单测)。 */export async function handleForgePack(deps: CindyGhostsMcpDeps,- input: { dir: string; icon_source?: string; intent?: "install" | "publish" },+ input: { dir: string; icon_source?: string; intent?: "publish" },): Promise<McpTextResult> {try {const result = await deps.forgePack({@@ -1067,6 +1080,36 @@ export async function handleForgePack(}}+/** ghost_forge_install 的 handler 主体(导出供单测)。 */+export async function handleForgeInstall(+ deps: CindyGhostsMcpDeps,+ input: { dir: string; icon_source?: string },+): Promise<McpTextResult> {+ try {+ const result = await deps.forgeInstall({+ dir: input.dir,+ ...(input.icon_source !== undefined ? { iconSource: input.icon_source } : {}),+ });+ if (!result.ok) {+ deps.logger?.warn("ghost_forge_install rejected", {+ dir: input.dir,+ errorCode: result.errorCode,+ });+ return textResult(result, true);+ }+ return textResult(result);+ } catch (err) {+ return textResult(+ {+ ok: false,+ errorCode: "INTERNAL",+ message: err instanceof Error ? err.message : String(err),+ },+ true,+ );+ }+}+/** ghost_forge_publish 的 handler 主体(导出供单测)。 */export async function handleForgePublish(deps: CindyGhostsMcpDeps,@@ -1295,15 +1338,30 @@ export function createCindyGhostsMcpServer("可选;仅当用户明确选择 AI 生成图标时,传图片工具结果的 xdt_image_url,或 xdt_image_urls 数组第一项(cindy-media:// 地址);失败会保留默认图标继续打包",),intent: z- .enum(["install", "publish"])+ .enum(["publish"]).optional().describe(- "缺省 install:弹装入确认;publish:不装入,返回一次性发布票据。publish 仅企业组织成员可用;个人账号不可用,请用缺省的 install",+ "缺省不传:只打包并返回产物路径;publish:额外返回一次性发布票据。publish 仅企业组织成员可用,个人账号仍可使用缺省的纯打包模式",),},async (input) => handleForgePack(deps, input),);+ server.tool(+ "ghost_forge_install",+ D_GHOST_FORGE_INSTALL,+ {+ dir: z.string().describe("插件源码目录的绝对路径(目录里须有 ghost.json)"),+ icon_source: z+ .string()+ .optional()+ .describe(+ "可选;仅当用户明确选择 AI 生成图标时,传图片工具结果的 cindy-media:// 地址;失败会保留默认图标继续安装",+ ),+ },+ async (input) => handleForgeInstall(deps, input),+ );+server.registerTool("ghost_forge_publish",{diff --git a/packages/cindy-tools/src/index.ts b/packages/cindy-tools/src/index.tsindex 7ff7b3cff7..4a3b557837 100644--- a/packages/cindy-tools/src/index.ts+++ b/packages/cindy-tools/src/index.ts@@ -2,6 +2,7 @@ export {buildGhostRosterPrompt,createCindyGhostsMcpServer,handleForgeGuide,+ handleForgeInstall,handleForgePack,handleForgePublish,handleForgePublishStatus,@@ -16,6 +17,7 @@ export {export type {CindyForgePackErrorCode,CindyForgePackResult,+ CindyForgeInstallResult,CindyForgePublishErrorCode,CindyForgePublishResult,CindyForgePublishStatusResult,diff --git a/packages/cindy-tools/src/types.ts b/packages/cindy-tools/src/types.tsindex 3938dd0979..e3612fe21e 100644--- a/packages/cindy-tools/src/types.ts+++ b/packages/cindy-tools/src/types.ts@@ -245,11 +245,28 @@ export type CindyForgePackResult =version: string;/** 仅 intent=publish 返回;一次性、不可解析的 Host 发布票据。 */publishToken?: string;- /** 下一步说明:install 等用户确认,publish 提示消费一次性票据。 */+ /** 打包结果说明;成功仅表示产物已生成,不表示已经安装。 */note: string;}| { ok: false; errorCode: CindyForgePackErrorCode; message: string };+/** ghost_forge_install 会先走 Forge 打包校验,再复用 Host 的本地安装/更新事务。 */+export type CindyForgeInstallResult =+ | {+ ok: true;+ action: 'installed' | 'updated';+ id: string;+ name: string;+ version: string;+ enabled: boolean;+ note: string;+ }+ | {+ ok: false;+ errorCode: CindyForgePackErrorCode | (string & {});+ message: string;+ };+/** ghost_forge_publish 立即返回时的失败分类。传输开始后的失败走 status.errorCode。 */export type CindyForgePublishErrorCode =| 'NOT_ORG_MEMBER'@@ -431,18 +448,23 @@ export interface CindyGhostsMcpDeps {description?: string;}): Promise<CindyForgeScaffoldResult>;/**- * 把一个源码目录校验 + 打包成 .cindy。缺省弹出与拖入/双击完全相同的- * 装入确认框;publish 意图只签发一次性发布票据,不触发装入。+ * 把一个源码目录校验并打包成 .cindy。只生成产物,不安装或更新插件;+ * publish 意图额外签发一次性发布票据。*/forgePack(request: {dir: string;- intent?: 'install' | 'publish';+ intent?: 'publish';/*** 用户明确选择 AI 图标后,由图片工具返回的 cindy-media 地址。Host* best-effort 把它嵌入包内;失败保留源码里的默认图标,不阻塞打包。*/iconSource?: string;}): Promise<CindyForgePackResult>;+ /**+ * 重新校验并打包源码目录,然后把这次产生的确切包安装或原位更新。+ * 只有显式调用本工具才安装;forgePack 本身始终保持纯打包。+ */+ forgeInstall(request: { dir: string; iconSource?: string }): Promise<CindyForgeInstallResult>;/*** 消费 forgePack(intent=publish) 签发的一次性票据,把该次打包的确切字节* 提交到当前组织发布。立即返回 transferId / uploadId,传输在后台跑。diff --git a/packages/plugin-protocol/src/__tests__/delivery.test.ts b/packages/plugin-protocol/src/__tests__/delivery.test.tsindex ae8a44bfa5..db12284218 100644--- a/packages/plugin-protocol/src/__tests__/delivery.test.ts+++ b/packages/plugin-protocol/src/__tests__/delivery.test.ts@@ -6,10 +6,8 @@ import {parsePluginDownloadResponse,PluginProtocolError,} from '../delivery.js';-import { GHOST_MANIFEST_SCHEMA_VERSION } from '../manifest.js';-const validManifest = {- schemaVersion: GHOST_MANIFEST_SCHEMA_VERSION,+ schemaVersion: 2,id: 'acme-helper',name: 'Acme Helper',version: '1.0.0',@@ -223,6 +221,36 @@ describe('plugin delivery contract', () => {expect(response.plugin.currentRelease.manifest.minCindyVersion).toBe('1.2.3');});+ it('preserves unknown slot declarations for the client capability check', () => {+ const manifest = {+ ...validManifest,+ slots: ['tool', 'vendor-runtime'],+ } as const;+ const response = parseGetPluginResponse({+ schemaVersion: PLUGIN_API_SCHEMA_VERSION,+ plugin: {+ id: pluginId,+ ghostId: manifest.id,+ name: manifest.name,+ description: null,+ author: null,+ scope: 'public',+ organizationId: null,+ defaultInstall: false,+ currentRelease: {+ id: 'release-vendor-runtime',+ version: manifest.version,+ sha256: 'a'.repeat(64),+ sizeBytes: 1024,+ publishedAt: '2026-07-19T00:00:00.000Z',+ manifest,+ },+ },+ });++ expect(response.plugin.currentRelease.manifest.slots).toEqual(['tool', 'vendor-runtime']);+ });+it('allows oidc-token only in organization Plugin details', () => {const plugin = {id: pluginId,diff --git a/packages/plugin-protocol/src/__tests__/manifest.test.ts b/packages/plugin-protocol/src/__tests__/manifest.test.tsindex 92d1096f55..39fc1f1784 100644--- a/packages/plugin-protocol/src/__tests__/manifest.test.ts+++ b/packages/plugin-protocol/src/__tests__/manifest.test.ts@@ -8,7 +8,7 @@ import {GHOST_MANIFEST_SCHEMA_VERSION,GHOST_MAIN_VIEW_ICONS,GHOST_OAUTH_SCOPES_MAX,- GHOST_SLOTS,+ LEGACY_GHOST_SLOTS,compareCindyVersions,ghostManifestUsesOidcToken,isSafeGhostRelativePath,@@ -20,7 +20,7 @@ import {} from '../manifest.js';const validManifest = {- schemaVersion: GHOST_MANIFEST_SCHEMA_VERSION,+ schemaVersion: 2,id: 'acme-helper',name: 'Acme Helper',version: '1.0.0',@@ -31,8 +31,8 @@ const validManifest = {} as const;describe('Ghost manifest contract', () => {- it('keeps host-owned application slots in the public contract', () => {- expect(GHOST_SLOTS).toContain('main-view');+ it('keeps main-view in the v2 compatibility contract', () => {+ expect(LEGACY_GHOST_SLOTS).toContain('main-view');expect(GHOST_MAIN_VIEW_ICONS).toEqual(['puzzle','globe',@@ -46,6 +46,68 @@ describe('Ghost manifest contract', () => {]);});+ it('uses Manifest v3 for new plugins and keeps v2 as input compatibility', () => {+ expect(GHOST_MANIFEST_SCHEMA_VERSION).toBe(3);+ const result = validateGhostManifest({+ schemaVersion: GHOST_MANIFEST_SCHEMA_VERSION,+ minCindyVersion: '0.1.61',+ id: 'direct-helper',+ name: 'Direct Helper',+ version: '1.0.0',+ entry: 'index.js',+ tools: [{ name: 'help', description: 'Help with direct capabilities' }],+ card: {},+ agent: {},+ notify: true,+ futureCapability: { mode: 'example' },+ });+ expect(result.ok).toBe(true);+ if (!result.ok) return;+ expect(result.manifest).not.toHaveProperty('slots');+ expect(result.manifest.card).toEqual({});+ expect(result.manifest.agent).toEqual({});+ expect(result.manifest.notify).toBe(true);+ expect(result.manifest.futureCapability).toEqual({ mode: 'example' });++ expect(validateGhostManifest({ ...validManifest, schemaVersion: 3 }).ok).toBe(false);+ expect(+ validateGhostManifest({+ ...validManifest,+ schemaVersion: 3,+ minCindyVersion: '0.1.61',+ }).ok,+ ).toBe(false);+ expect(+ validateGhostManifest({+ ...validManifest,+ schemaVersion: 3,+ minCindyVersion: '0.1.61',+ slots: undefined,+ notify: false,+ }).ok,+ ).toBe(false);+ expect(+ validateGhostManifest({+ schemaVersion: 3,+ minCindyVersion: '0.1.60',+ id: 'too-old-v3',+ name: 'Too Old v3',+ version: '1.0.0',+ entry: 'index.js',+ }).ok,+ ).toBe(false);+ });++ it('accepts empty and zero-power v2 slots and drops the latter', () => {+ expect(validateGhostManifest({ ...validManifest, slots: [], tools: undefined })).toMatchObject({+ ok: true,+ manifest: { slots: [] },+ });+ expect(+ validateGhostManifest({ ...validManifest, slots: ['tool', 'network'], tools: undefined }),+ ).toMatchObject({ ok: true, manifest: { slots: [] } });+ });+it('exports the manual authoring limits', () => {expect(GHOST_MANUAL_MAX_ITEMS).toBe(8);expect(GHOST_MANUAL_ENTRY_FILE).toBe('MANUAL.md');@@ -691,6 +753,7 @@ describe('Ghost manifest contract', () => {it('normalizes a representative full capability manifest', () => {const result = validateGhostManifest({schemaVersion: GHOST_MANIFEST_SCHEMA_VERSION,+ minCindyVersion: '0.1.61',id: 'full-helper',name: 'Full Helper',version: '2.0.0',@@ -702,7 +765,10 @@ describe('Ghost manifest contract', () => {launch: 'resident',settingsHtml: 'settings.html',settingsHeight: 320,- slots: ['subscribe', 'tool', 'card', 'panel', 'cindy', 'network', 'notify', 'fs'],+ card: {},+ notify: true,+ fs: true,+ library: true,tools: [{name: 'run_helper',@@ -745,17 +811,12 @@ describe('Ghost manifest contract', () => {expect(result.ok).toBe(true);if (!result.ok) return;expect(result.manifest.kind).toBe('chip');- expect(result.manifest.slots).toEqual([- 'subscribe',- 'tool',- 'card',- 'panel',- 'cindy',- 'network',- 'notify',- 'fs',- ]);- expect(result.manifest).not.toHaveProperty('unknownField');+ expect(result.manifest).not.toHaveProperty('slots');+ expect(result.manifest.card).toEqual({});+ expect(result.manifest.notify).toBe(true);+ expect(result.manifest.fs).toBe(true);+ expect(result.manifest.library).toBe(true);+ expect(result.manifest.unknownField).toBe('ignored');});it('accepts Desktop-supported badge and confirm slots while requiring a badge panel', () => {@@ -780,6 +841,7 @@ describe('Ghost manifest contract', () => {it('accepts the taptap-maker style manifest with node/session-context/pick/preview slots', () => {const result = validateGhostManifest({schemaVersion: GHOST_MANIFEST_SCHEMA_VERSION,+ minCindyVersion: '0.1.61',id: 'taptap-maker',name: 'TapTap Maker',version: '2.0.0',@@ -788,8 +850,10 @@ describe('Ghost manifest contract', () => {entry: 'main.js',settingsHtml: 'settings.html',settingsHeight: 760,- slots: ['tool', 'card', 'node', 'session-context', 'pick', 'preview', 'workspace'],card: { externalLinks: true },+ sessionContext: true,+ pick: true,+ workspace: true,node: {entry: 'node/maker-mcp.cjs',entries: ['node/account.cjs', 'node/maker-child.cjs'],@@ -805,15 +869,10 @@ describe('Ghost manifest contract', () => {expect(result.ok).toBe(true);if (!result.ok) return;- expect(result.manifest.slots).toEqual([- 'tool',- 'card',- 'node',- 'session-context',- 'pick',- 'preview',- 'workspace',- ]);+ expect(result.manifest).not.toHaveProperty('slots');+ expect(result.manifest.sessionContext).toBe(true);+ expect(result.manifest.pick).toBe(true);+ expect(result.manifest.workspace).toBe(true);expect(result.manifest.node).toEqual({entry: 'node/maker-mcp.cjs',protocol: 'mcp-stdio',@@ -826,12 +885,11 @@ describe('Ghost manifest contract', () => {expect(result.manifest.card).toEqual({ externalLinks: true });});- it('round-trips the Host-owned ios-simulator slot with an explicit Cindy version floor', () => {+ it('keeps minCindyVersion optional for Host-owned slots', () => {const manifest = {...validManifest,id: 'simulator-workflow',name: 'Simulator Workflow',- minCindyVersion: '1.2.3',slots: ['ios-simulator'],tools: undefined,} as const;@@ -841,30 +899,40 @@ describe('Ghost manifest contract', () => {expect(result).toEqual({ ok: true, manifest });});- it('rejects ios-simulator manifests that cannot be version-gated for older Hosts', () => {+ it('preserves well-formed unknown slots and rejects unsafe slot names', () => {const manifest = {...validManifest,- slots: ['ios-simulator'],+ slots: ['future-host-capability'],tools: undefined,};- expect(validateGhostManifest(manifest)).toMatchObject({- ok: false,- reason: expect.stringContaining('minCindyVersion'),- });- expect(- validateGhostManifest({- ...manifest,- minCindyVersion: '1.2.3',- slots: ['ios-simulator-control'],- }),- ).toMatchObject({- ok: false,- reason: expect.stringContaining('未知卡槽'),- });+ expect(validateGhostManifest(manifest)).toEqual({ ok: true, manifest });+ for (const slot of ['FutureCapability', 'future capability', 'future/capability', '']) {+ expect(validateGhostManifest({ ...manifest, slots: [slot] })).toMatchObject({+ ok: false,+ reason: expect.stringContaining('格式非法'),+ });+ }});- it('round-trips a strict main-view declaration and requires a Cindy version floor', () => {+ it('accepts direct v3 mainView and round-trips v2 main-view compatibility', () => {+ const direct = {+ schemaVersion: 3,+ minCindyVersion: '0.1.61',+ id: 'direct-main-view',+ name: 'Direct Main View',+ version: '1.0.0',+ entry: 'index.js',+ mainView: {+ title: 'Workspace',+ icon: 'globe',+ html: 'ui/main-view.html',+ },+ } as const;+ const directResult = validateGhostManifest(direct);+ expect(directResult).toMatchObject({ ok: true, manifest: { mainView: direct.mainView } });+ if (directResult.ok) expect(directResult.manifest).not.toHaveProperty('slots');+const manifest = {...validManifest,minCindyVersion: '1.2.3',@@ -884,20 +952,17 @@ describe('Ghost manifest contract', () => {const withoutMin = { ...manifest } as Record<string, unknown>;delete withoutMin.minCindyVersion;- expect(validateGhostManifest(withoutMin)).toMatchObject({- ok: false,- reason: expect.stringContaining('minCindyVersion'),- });+ expect(validateGhostManifest(withoutMin)).toEqual({ ok: true, manifest: withoutMin });});- it('keeps main-view slot/detail paired and rejects unsafe or unknown fields', () => {- const base = {+ it('keeps v2 main-view paired and rejects unsafe or unknown mainView fields', () => {+ const legacyBase = {...validManifest,minCindyVersion: '1.2.3',slots: ['main-view'],tools: undefined,};- expect(validateGhostManifest(base)).toMatchObject({+ expect(validateGhostManifest(legacyBase)).toMatchObject({ok: false,reason: expect.stringContaining('mainView'),});@@ -911,6 +976,14 @@ describe('Ghost manifest contract', () => {ok: false,reason: expect.stringContaining('main-view'),});+ const base = {+ schemaVersion: 3,+ minCindyVersion: '0.1.61',+ id: 'invalid-main-view',+ name: 'Invalid Main View',+ version: '1.0.0',+ entry: 'index.js',+ } as const;expect(validateGhostManifest({ ...base, mainView: { html: '../escape.html' } }).ok).toBe(false);expect(validateGhostManifest({@@ -941,14 +1014,14 @@ describe('Ghost manifest contract', () => {});});- it('enforces node slot / detail pairing and entry discipline', () => {+ it('drops an empty legacy node slot and enforces entry discipline', () => {const base = {...validManifest,slots: ['tool', 'node'],};expect(validateGhostManifest(base)).toMatchObject({- ok: false,- reason: expect.stringContaining('缺少 node 工作进程详单'),+ ok: true,+ manifest: { slots: ['tool'] },});const withNode = (node: Record<string, unknown>) => validateGhostManifest({ ...base, node });expect(withNode({ entry: 'node/a.cjs', protocol: 'mcp-stdio', command: 'sh' })).toMatchObject({@@ -1214,11 +1287,11 @@ describe('Ghost manifest contract', () => {).toMatchObject({ ok: false, reason: expect.stringContaining('1–4 条') });});- it('enforces preview slot / hosts pairing and pattern rules', () => {+ it('drops an empty legacy preview slot and enforces hosts and pattern rules', () => {const base = { ...validManifest, slots: ['tool', 'preview'] };expect(validateGhostManifest(base)).toMatchObject({- ok: false,- reason: expect.stringContaining('缺少 preview 详单'),+ ok: true,+ manifest: { slots: ['tool'] },});expect(validateGhostManifest({ ...base, preview: { hosts: [] } }).ok).toBe(false);expect(@@ -1249,13 +1322,12 @@ describe('Ghost manifest contract', () => {expect(loopback.ok).toBe(true);});- it('enforces skill slot / items pairing and shape rules', () => {+ it('drops an empty legacy skill slot and enforces item shape rules', () => {const base = { ...validManifest, slots: ['tool', 'skill'] };const goodItems = [{ dir: 'skills/foo', name: 'foo', description: '教 Agent 用 foo' }];- // 有槽必有详单;有详单必有槽expect(validateGhostManifest(base)).toMatchObject({- ok: false,- reason: expect.stringContaining('缺少 skill 详单'),+ ok: true,+ manifest: { slots: ['tool'] },});expect(validateGhostManifest({ ...validManifest, skill: { items: goodItems } })).toMatchObject({ok: false,@@ -1650,7 +1722,7 @@ describe('Ghost manifest contract', () => {describe('cindy 详单:media/text/embed/search 类目与 oneshotModel 校验', () => {const base = {- schemaVersion: GHOST_MANIFEST_SCHEMA_VERSION,+ schemaVersion: 2,id: 'cindy-full',name: 'Cindy Full',version: '1.0.0',diff --git a/packages/plugin-protocol/src/manifest.ts b/packages/plugin-protocol/src/manifest.tsindex e796fa9b63..b64b4dae7f 100644--- a/packages/plugin-protocol/src/manifest.ts+++ b/packages/plugin-protocol/src/manifest.ts@@ -4,8 +4,10 @@ export const GHOST_MANIFEST_FILE = 'ghost.json';/** 意识文件扩展名。 */export const CINDY_FILE_EXT = '.cindy';-/** ghost.json 格式版本;与 Plugin HTTP API envelope 版本独立演进。 */-export const GHOST_MANIFEST_SCHEMA_VERSION = 2 as const;+/** 新建 ghost.json 使用的格式版本;与 Plugin HTTP API envelope 版本独立演进。 */+export const GHOST_MANIFEST_SCHEMA_VERSION = 3 as const;+/** 首个支持 Manifest v3 的 Cindy 正式版本;v3 清单不得声明更低的兼容下限。 */+export const GHOST_MANIFEST_V3_MIN_CINDY_VERSION = '0.1.61';/** ghost.json 的 description / whenToUse 字符上限。 */export const GHOST_MANIFEST_SUMMARY_MAX_CHARS = 300;@@ -36,7 +38,7 @@ function isWindowsReservedName(name: string): boolean {}/**- * 卡槽清单(意识能力的全部出口)。+ * schemaVersion 2 能力名清单,仅用于兼容旧包。* 'cindy' = 请 Cindy 本体代办(借主机自带 AI 能力干活;2026-07-11 定案* 由 'model' 更名——本质是 Cindy 在干活,与选模型无关;旧名在校验层作* 静默别名兼容,已装老包不消失)。@@ -71,7 +73,7 @@ function isWindowsReservedName(name: string): boolean {* 指令由主 Agent 以**用户全部权限**执行、对所有项目与会话生效、不受插件沙箱* 约束,也不随"某工作目录停用本插件"而隐藏——仅全局停用/卸载才撤链。因此* manifest 全声明式(items 的 name/description 必须与 SKILL.md frontmatter 逐字- * 一致,打包与装入双侧强制),装入确认框逐条列出并置于清单最上部。+ * 一致,打包与装入双侧强制),插件详情逐条列出并置于能力清单最上部。* 'workspace' = 工作区会话(2026-07-25):插件请主机在指定本机项目目录下确保* 存在一个会话入口并显示在侧边栏——目录下已有 active 会话即复用,没有才创建* 空 draft 会话(不拉起 agent 进程)。目录授权两条路:系统选文件夹窗口亲选@@ -81,8 +83,12 @@ function isWindowsReservedName(name: string): boolean {* 'ios-simulator' = Host 托管的内嵌 iOS 模拟器入口:插件只能读取当前任务的* 脱敏状态并请求 Host 打开控制面板。视频帧、输入、设备标识、Native Helper、* 生命周期与恢复均不跨插件边界,仍由 Cindy Host 独占管理。+ *+ * 以下名称只用于 schemaVersion 2 的兼容校验。schemaVersion 3 使用顶层直接+ * 字段声明能力,不再提供 slots。未知 v2 slot 会被保留供兼容诊断,但不会+ * 被猜测成某个 Host 能力,也不会阻止安装。*/-export const GHOST_SLOTS = [+export const LEGACY_GHOST_SLOTS = ['subscribe','tool','card',@@ -96,6 +102,7 @@ export const GHOST_SLOTS = ['badge','confirm','fs',+ 'library','session-context','pick','preview',@@ -103,7 +110,10 @@ export const GHOST_SLOTS = ['workspace','ios-simulator',] as const;-export type GhostSlot = (typeof GHOST_SLOTS)[number];+type LegacyGhostSlot = string;++/** v2 slot 只约束可安全展示/传输的形状。 */+const GHOST_SLOT_NAME_RE = /^[a-z][a-z0-9._:-]{0,127}$/;/*** 电子脑启动模式(2026-07-12):@@ -183,7 +193,7 @@ export interface GhostToolDecl {/*** Card 槽能力详单。card 槽默认仅允许渲染静态/交互卡片(含按钮动作);* externalLinks: true 额外允许卡片声明 data-ghost-link 外链,点击经宿主- * 确认框后 openExternal——这是独立加档权限,装入确认时单列。+ * 确认框后 openExternal——这是独立加档权限,插件详情中单列。*/export interface GhostCardNeeds {externalLinks?: boolean;@@ -192,8 +202,8 @@ export interface GhostCardNeeds {/*** Agent 新回合能力详单。*- * 申请 `agent` 槽默认只允许消费宿主在真实用户点击插件卡片时签发的- * 一次性通行票。三个可选加档均由 Desktop 独立展示并授权。+ * 声明 `agent` 默认只允许消费宿主在真实用户点击插件卡片时签发的+ * 一次性通行票;可选加档由 Desktop 如实展示,并由 Host 在运行时守门。*/export interface GhostAgentNeeds {background?: boolean;@@ -205,7 +215,7 @@ export interface GhostAgentNeeds {export const GHOST_NODE_PROTOCOLS = ['json-rpc-stdio', 'mcp-stdio'] as const;export type GhostNodeProtocol = (typeof GHOST_NODE_PROTOCOLS)[number];-/** Node 工作进程生命周期;常驻档会在安装确认中单列高风险权限。 */+/** Node 工作进程生命周期;常驻档会在插件详情中单列高风险权限。 */export const GHOST_NODE_LIFECYCLES = ['on-demand', 'resident'] as const;export type GhostNodeLifecycle = (typeof GHOST_NODE_LIFECYCLES)[number];@@ -231,7 +241,7 @@ export function isGhostNodeMcpReservedMethod(method: string): boolean {export interface GhostNodeSecretBinding {/** 凭证键(插件内唯一):小写字母开头,允许小写/数字/下划线,1–32。 */key: string;- /** 给用户看的名称(安装确认与设置状态使用)。 */+ /** 给用户看的名称(插件详情与设置状态使用)。 */label: string;/** 允许注入的 JSON-RPC 方法白名单(1–16 条)。 */methods: string[];@@ -267,13 +277,13 @@ export interface GhostNodeNeeds {* (spawnEntry)请求宿主再启动一个**已申报入口**(entry / entries 之内)的* 原样 stdio 子进程,并把子进程 stdio 字节中继回 worker。给 Maker Runtime* 这类"自己 spawn process.execPath"的库改道用——正式包关 RunAsNode,- * 那条路生出来的不是 Node。默认关;开了会在装入确认框单列一行。+ * 那条路生出来的不是 Node。默认关;开了会在插件详情中单列一行。* 权限本质不变:仍只能跑包内申报过的 JS,node 槽本就是用户级执行权。*/childSpawn?: boolean;/*** 由主机 safeStorage 持久化、按声明的方法临时注入 Worker 的凭证。- * 这是 Node 高风险能力的一部分,安装权限清单会逐条披露。+ * 这是 Node 高风险能力的一部分,插件详情会逐条披露。*/secretBindings?: GhostNodeSecretBinding[];}@@ -323,7 +333,7 @@ export type GhostCindySearchAction = (typeof GHOST_CINDY_SEARCH_ACTIONS)[number]* cindy 槽能力详单(卡槽⑤配套,原名模型槽,2026-07-11 设计定案):声明"这个意识被允许* 向主机点哪几类代办"——只有类目与动作,**不含任何具体模型/供应商信息*** (选型权在主机的解析表:调用时显式点名 > 意识专属覆盖 > 用户能力偏好 >- * 出厂默认;意识只表达意图,永不腐烂)。装入确认框与代办资格审共同消费。+ * 出厂默认;意识只表达意图,永不腐烂)。插件详情与代办资格审共同消费。*/export interface GhostCindyNeeds {/** 图像类:generate=出图,edit=改图(改图仅限本意识名下媒体)。 */@@ -511,7 +521,7 @@ export const GHOST_OAUTH_RESERVED_AUTHORIZE_PARAMS: readonly string[] = [/*** OAuth 凭证声明(source: 'oauth',2026-07-13 定案"通用声明式"):* 平台不预设 provider 名单——意识声明"去哪授权、要什么 scope",clientId /- * clientSecret 由用户在意识设置页自填(经 /oauth 只写通道入库),装入确认框+ * clientSecret 由用户在意识设置页自填(经 /oauth 只写通道入库),插件详情* 全量展示授权域名与 scopes,用户知情自担。声明化的是**参数**不是**代码**:* 授权流程(拉浏览器、loopback 回调、state/PKCE 校验、code 换 token、刷新)* 永远由主机可信代码执行,意识无从插手,@@ -580,8 +590,9 @@ export interface GhostSecretOauthDecl {* 可选:服务端 token broker 的 provider slug(2026-07-14 增补)。* 声明后 code 换 token 与 refresh 不直连 tokenUrl,改经主机* 调服务端的授权 broker(带登录 JWT;client secret 在服务端,不随包- * 分发)。与 clientSecret 互斥。静态官方前缀照旧放行;其余资格由装入来源与- * 当前组织事实共同判定。校验层保持纯函数不感知装入语境,门控在装入闸与连接闸。+ * 分发)。与 clientSecret 互斥。静态官方前缀照旧放行;其余资格由可信组织市场+ * 来源、批准包字节与当前组织事实共同判定。校验层保持纯函数不感知装入语境,+ * 门控在装入闸与连接闸。*/tokenBroker?: string;/**@@ -647,7 +658,7 @@ export type GhostSecretSource = (typeof GHOST_SECRET_SOURCES)[number];* 凭证收单(2026-07-13 两次定案,当天收敛):user 凭证的收单**一律**由意识* settingsHtml 自绘——经协议 `/secrets` 只写通道一次性入库,存入后意识拿不回* 明文,保管(safeStorage)与注入(主机代发时)由主机独占。安全模型弱化点- * 仅一处:录入瞬间明文经过意识页面(用户主动敲进它的输入框),装入确认框+ * 仅一处:录入瞬间明文经过意识页面(用户主动敲进它的输入框),插件详情* 如实告知。**宿主渲染凭证输入行已整体退役**(基座不再为意识特设凭证 UI,* 定案):清单里遗留的 `input: "ghost"` 接受并忽略(与现状同义),* `input: "host"` 直接拒绝;声明 user 凭证必须同时声明 settingsHtml。@@ -657,7 +668,7 @@ export type GhostSecretSource = (typeof GHOST_SECRET_SOURCES)[number];export interface GhostSecretDecl {/** 凭证键(意识内唯一):小写字母开头,允许小写/数字/下划线,1–32。 */key: string;- /** 给用户看的名称(装入确认框展示)。 */+ /** 给用户看的名称(插件详情展示)。 */label: string;/** 凭证值来源;缺省 'user'(校验归一化:'user' 不落清单)。 */source?: GhostSecretSource;@@ -751,7 +762,7 @@ export const GHOST_PREVIEW_MAX_HOSTS = 4;* preview 槽详单(与 slots 含 'preview' 严格成对——有槽必有详单:范围是* 本能力的全部知情面,不允许"先装后说")。hosts 语法与 network 域名白名单* 一致(支持 `*.` 单层前缀通配),另特批 loopback 单段名(本地 dev server- * 是预览的正当主场,network 语法"至少两段"表达不了它)。装入确认框逐条展示。+ * 是预览的正当主场,network 语法"至少两段"表达不了它)。插件详情逐条展示。*/export interface GhostPreviewNeeds {hosts: string[];@@ -787,13 +798,13 @@ export const GHOST_MANUAL_MD_MAX_BYTES = 64 * 1024;/** manual:一级索引说明的字符上限。 */export const GHOST_MANUAL_DESCRIPTION_MAX_CHARS = GHOST_MANIFEST_SUMMARY_MAX_CHARS;-/** skill 槽单条技能声明(全声明式:确认框展示的就是这里的字段)。 */+/** skill 槽单条技能声明(全声明式:插件详情展示的就是这里的字段)。 */export interface GhostSkillItem {/** 包内技能目录(安全相对路径,目录内必须有 SKILL.md)。 */dir: string;/*** 技能名。必须与 SKILL.md frontmatter 的 name 逐字一致(打包与装入双侧- * 强制)——确认框里用户看到的,必须就是 Agent 实际读到的。+ * 强制)——详情里用户看到的,必须就是 Agent 实际读到的。*/name: string;/** 技能说明。必须与 SKILL.md frontmatter 的 description 逐字一致(同上)。 */@@ -802,7 +813,7 @@ export interface GhostSkillItem {/*** skill 槽详单(与 slots 含 'skill' 严格成对——有槽必有详单:捆绑了什么技能- * 是本能力的全部知情面,不允许"先装后说")。装入确认框逐条展示。+ * 是本能力的全部知情面,不允许隐瞒)。插件详情逐条展示。*/export interface GhostSkillNeeds {items: GhostSkillItem[];@@ -823,10 +834,10 @@ export interface GhostManualNeeds {items: GhostManualItem[];}-/** ghost.json 清单(不变量由 validateGhostManifest 保证)。 */+/** 已校验的 ghost.json 协议文档;Desktop 会再投影成无 slots 的运行时模型。 */export interface GhostManifest {- /** 清单格式版本,恒 2(v1 声明型已于 2026-07-12 移除,无存量不留兼容)。 */- schemaVersion: typeof GHOST_MANIFEST_SCHEMA_VERSION;+ /** v2 仅作存量兼容;新插件使用 v3。 */+ schemaVersion: 2 | typeof GHOST_MANIFEST_SCHEMA_VERSION;/** 唯一标识,同时是安装目录名与 panelKind 后缀。 */id: string;/** 展示名。 */@@ -847,7 +858,7 @@ export interface GhostManifest {locales?: GhostManifestLocales;/*** 意识自我介绍(1–300 字,仅展示用):这段意识是干嘛- * 的、给谁用。装入确认框与详情页展示;与 tools[].description(给 AI 看的+ * 的、给谁用。插件详情页展示;与 tools[].description(给 AI 看的* 工具说明)职责不同,后者不因本字段缺省而顶上。*/description?: string;@@ -873,9 +884,9 @@ export interface GhostManifest {entry: string;/** 电子脑启动模式;缺省 = 'on-demand'(被需要才拉起)。 */launch?: GhostLaunchMode;- /** Agent 新回合能力详单;须与 slots 中的 `agent` 成对。 */+ /** Agent 新回合能力;v3 空对象表示仅允许真实用户点击触发。 */agent?: GhostAgentNeeds;- /** 随包本地 Node 工作进程详单;须与 slots 中的 `node` 成对(有槽必有详单)。 */+ /** 随包本地 Node 工作进程能力。 */node?: GhostNodeNeeds;/*** 设置页「自定义设置区」界面入口(可选;安装目录内相对路径,意识自绘)。@@ -891,29 +902,27 @@ export interface GhostManifest {* 页用它避免抖动)。须与 settingsHtml 成对声明。*/settingsHeight?: number;- /** 能力白名单(没声明的槽,运行时接口不存在)。 */- slots: GhostSlot[];+ /** 仅 schemaVersion 2 存在的兼容声明。 */+ slots?: LegacyGhostSlot[];/**- * card 槽能力详单(与 slots 含 'card' 成对;缺省 = 仅渲染,无外链)。+ * card 能力;v3 空对象表示仅渲染、无外链。* externalLinks: true 时卡片内可声明 data-ghost-link,点击经宿主确认框后打开浏览器。*/card?: GhostCardNeeds;- /** 注册给 agent 的工具声明(与 slots 含 'tool' 成对)。 */+ /** 注册给 agent 的工具声明;字段本身就是能力声明。 */tools?: GhostToolDecl[];/**- * cindy 槽能力详单(与 slots 含 'cindy' 成对;缺省 = 零能力,任何代办- * 都会被拒并提示作者补声明)。清单里的旧字段名 model 在校验层作别名- * 收入本字段。+ * Cindy 代办能力。v2 的旧字段名 model 在兼容校验层收入本字段。*/cindy?: GhostCindyNeeds;/**- * 订阅槽详单(与 slots 含 'subscribe' 成对;缺省 = 零事件)。+ * 订阅能力与事件范围。* hooks 非空时 launch 必须为 'resident'(校验强制)。*/subscribe?: GhostSubscribeNeeds;/**- * network 槽详单(与 slots 含 'network' 成对;缺省 = 零能力)。- * 域名白名单 + 凭证声明,装入确认框逐项展示,运行期主机代发并守门。+ * network 能力与访问范围。+ * 域名白名单 + 凭证声明由插件详情逐项展示,运行期主机代发并守门。*/network?: GhostNetworkNeeds;/**@@ -931,24 +940,37 @@ export interface GhostManifest {keywords?: string[];/** 面板声明;没有面板的意识(如纯工具意识)可省略。 */panel?: GhostPanelDecl;- /** 应用级主视图声明;须与 slots 中的 `main-view` 成对。 */+ /** 应用级主视图声明;v3 直接声明,v2 与 `main-view` slot 成对。 */mainView?: GhostMainViewDecl;/**- * preview 槽详单(与 slots 含 'preview' 严格成对):可在右侧栏内置浏览器+ * preview 能力详单;v2 与 'preview' slot 成对。可在右侧栏内置浏览器* 打开预览标签页的域名白名单。*/preview?: GhostPreviewNeeds;/**- * skill 槽详单(与 slots 含 'skill' 严格成对):随包捆绑的 Agent Skills 清单。+ * skill 能力详单;v2 与 'skill' slot 成对。随包捆绑的 Agent Skills 清单。* 启用时主机链接进共享技能根,Claude Code 与 Codex 双端可见;字段不参与* 本地化(必须与 SKILL.md 逐字一致,见 GhostSkillItem)。*/skill?: GhostSkillNeeds;+ /** 无配置的 Host 能力在 v3 中只接受字面量 true;不需要时省略。 */+ notify?: true;+ badge?: true;+ confirm?: true;+ fs?: true;+ /** 持久作品库;卸载不删数据,位置和删除由 Host 设置页管理。 */+ library?: true;+ sessionContext?: true;+ pick?: true;+ workspace?: true;+ iosSimulator?: true;/*** 随包渐进披露手册。它不是能力 slot 或授权项;Host 只把索引投影给模型,* 正文经 ghost_manual 按需读取。旧客户端忽略这一可选顶层字段。*/manual?: GhostManualNeeds;+ /** v3 未知顶层字段原样保留,但 Host 不解释、不展示、不授权。 */+ [key: string]: unknown;}/** 判断已校验的 manifest 是否请求 Host 托管的企业身份凭证。 */@@ -962,7 +984,7 @@ export function isValidGhostId(id: unknown): id is string {}/**- * 装入确认框的单项权限(逐项权限清单)。+ * 插件详情与不兼容安装提醒共用的单项能力说明。* 纯数据描述:renderer 拼 `settings.ghosts.perm.<labelKey>` 翻译,`detail` 是* 作者自由文本(如工具描述)如实展示不翻译,`detailKey` 是主机固定说明的* i18n 后缀(如可执行代码的沙箱说明)——两者互斥。@@ -1089,21 +1111,188 @@ function isPlainObject(v: unknown): v is Record<string, unknown> {return typeof v === 'object' && v !== null && !Array.isArray(v);}-/**- * 校验一份 JSON.parse 后的未知 `ghost.json` 值。宽进严出:忽略未知字段- * (向前兼容),已知字段全部严格检查;任何不合格都返回人类可读 reason,- * 不抛异常。成功结果是只包含协议已知字段的规范化 `GhostManifest`,并补齐- * `kind` 等有缺省语义的字段。- */-export function validateGhostManifest(raw: unknown): ManifestValidation {- if (!isPlainObject(raw)) return { ok: false, reason: '清单不是对象' };+const GHOST_MANIFEST_KNOWN_TOP_LEVEL_FIELDS = new Set([+ 'schemaVersion',+ 'id',+ 'name',+ 'version',+ 'minCindyVersion',+ 'author',+ 'locales',+ 'description',+ 'whenToUse',+ 'icon',+ 'kind',+ 'entry',+ 'launch',+ 'agent',+ 'node',+ 'settingsHtml',+ 'settingsHeight',+ 'slots',+ 'card',+ 'tools',+ 'cindy',+ 'model',+ 'subscribe',+ 'network',+ 'command',+ 'keywords',+ 'panel',+ 'mainView',+ 'preview',+ 'skill',+ 'manual',+ 'notify',+ 'badge',+ 'confirm',+ 'fs',+ 'library',+ 'sessionContext',+ 'pick',+ 'workspace',+ 'iosSimulator',+]);++const V3_BOOLEAN_CAPABILITY_FIELDS = [+ 'notify',+ 'badge',+ 'confirm',+ 'fs',+ 'library',+ 'sessionContext',+ 'pick',+ 'workspace',+ 'iosSimulator',+] as const;++const V3_DECLARATION_TO_LEGACY_SLOT = [+ ['tools', 'tool'],+ ['card', 'card'],+ ['panel', 'panel'],+ ['mainView', 'main-view'],+ ['subscribe', 'subscribe'],+ ['skill', 'skill'],+ ['cindy', 'cindy'],+ ['agent', 'agent'],+ ['node', 'node'],+ ['network', 'network'],+ ['preview', 'preview'],+] as const;++const V3_BOOLEAN_TO_LEGACY_SLOT: Record<(typeof V3_BOOLEAN_CAPABILITY_FIELDS)[number], string> = {+ notify: 'notify',+ badge: 'badge',+ confirm: 'confirm',+ fs: 'fs',+ library: 'library',+ sessionContext: 'session-context',+ pick: 'pick',+ workspace: 'workspace',+ iosSimulator: 'ios-simulator',+};- if (raw.schemaVersion !== GHOST_MANIFEST_SCHEMA_VERSION) {+type PreparedGhostManifest = {+ raw: Record<string, unknown>;+ schemaVersion: 2 | 3;+ v3BaseCard: boolean;+ v3BaseAgent: boolean;+ unknownV3Fields: Record<string, unknown>;+};++function prepareGhostManifestForValidation(+ value: unknown,+): { ok: true; prepared: PreparedGhostManifest } | { ok: false; reason: string } {+ if (!isPlainObject(value)) return { ok: false, reason: '清单不是对象' };+ if (value.schemaVersion !== 2 && value.schemaVersion !== 3) {return {ok: false,- reason: `schemaVersion 必须是 ${GHOST_MANIFEST_SCHEMA_VERSION},得到 ${JSON.stringify(raw.schemaVersion)}(v1 声明型已于 2026-07-12 移除)`,+ reason: `schemaVersion 必须是 2 或 3,得到 ${JSON.stringify(value.schemaVersion)}(v1 声明型已于 2026-07-12 移除)`,};}+ if (value.schemaVersion === 2) {+ return {+ ok: true,+ prepared: {+ raw: Array.isArray(value.slots)+ ? { ...value, slots: dropEmptyLegacyCapabilitySlots(value, value.slots) }+ : value,+ schemaVersion: 2,+ v3BaseCard: false,+ v3BaseAgent: false,+ unknownV3Fields: {},+ },+ };+ }+ if (value.slots !== undefined) {+ return { ok: false, reason: 'schemaVersion 3 不再支持 slots;请直接声明对应能力字段' };+ }+ if (value.minCindyVersion === undefined) {+ return { ok: false, reason: 'schemaVersion 3 必须声明 minCindyVersion' };+ }+ for (const field of V3_BOOLEAN_CAPABILITY_FIELDS) {+ if (value[field] !== undefined && value[field] !== true) {+ return { ok: false, reason: `${field} 出现时必须是 true;不需要时请省略` };+ }+ }+ const syntheticSlots: string[] = [];+ for (const [field, slot] of V3_DECLARATION_TO_LEGACY_SLOT) {+ if (value[field] !== undefined) syntheticSlots.push(slot);+ }+ for (const field of V3_BOOLEAN_CAPABILITY_FIELDS) {+ if (value[field] === true) syntheticSlots.push(V3_BOOLEAN_TO_LEGACY_SLOT[field]);+ }+ const v3BaseCard = isPlainObject(value.card) && Object.keys(value.card).length === 0;+ const v3BaseAgent = isPlainObject(value.agent) && Object.keys(value.agent).length === 0;+ return {+ ok: true,+ prepared: {+ raw: {+ ...value,+ slots: syntheticSlots,+ ...(v3BaseCard ? { card: undefined } : {}),+ ...(v3BaseAgent ? { agent: undefined } : {}),+ },+ schemaVersion: 3,+ v3BaseCard,+ v3BaseAgent,+ unknownV3Fields: Object.fromEntries(+ Object.entries(value).filter(+ ([key]) => key === 'model' || !GHOST_MANIFEST_KNOWN_TOP_LEVEL_FIELDS.has(key),+ ),+ ),+ },+ };+}++/** v2 允许历史上只有名字、没有实际能力详单的 slot;校验结果会将其丢弃。 */+function dropEmptyLegacyCapabilitySlots(+ value: Record<string, unknown>,+ slots: unknown[],+): unknown[] {+ return slots.filter((slot) => {+ const normalized = slot === 'model' ? 'cindy' : slot;+ if (normalized === 'tool') return value.tools !== undefined;+ if (normalized === 'panel') return value.panel !== undefined;+ if (normalized === 'cindy') return value.cindy !== undefined || value.model !== undefined;+ if (normalized === 'subscribe') return value.subscribe !== undefined;+ if (normalized === 'node') return value.node !== undefined;+ if (normalized === 'network') return value.network !== undefined;+ if (normalized === 'preview') return value.preview !== undefined;+ if (normalized === 'skill') return value.skill !== undefined;+ return true;+ });+}++/**+ * 校验一份 JSON.parse 后的未知 `ghost.json` 值。已知字段严格检查;v2 未知+ * 字段忽略,v3 未知顶层字段原样保留但不解释、不授权。+ */+export function validateGhostManifest(value: unknown): ManifestValidation {+ const preparation = prepareGhostManifestForValidation(value);+ if (!preparation.ok) return preparation;+ const prepared = preparation.prepared;+ const raw = prepared.raw;if (!isValidGhostId(raw.id)) {return {ok: false,@@ -1126,6 +1315,15 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {) {return { ok: false, reason: 'minCindyVersion 必须是合法的 SemVer 字符串' };}+ if (+ prepared.schemaVersion === 3 &&+ compareCindyVersions(raw.minCindyVersion as string, GHOST_MANIFEST_V3_MIN_CINDY_VERSION) === -1+ ) {+ return {+ ok: false,+ reason: `schemaVersion 3 的 minCindyVersion 不能低于 ${GHOST_MANIFEST_V3_MIN_CINDY_VERSION}`,+ };+ }// kind 可省略(2026-07-12 晚定案:单形态后字段纯冗余,缺省即 chip);// 写了就必须是 chip——写错值仍拒,不静默纠正(规则 9)。if (raw.kind !== undefined && raw.kind !== 'chip') {@@ -1433,36 +1631,23 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {return { ok: false, reason: 'settingsHeight 必须是 160–800 之间的数字' };}}- if (!Array.isArray(raw.slots) || raw.slots.length === 0) {- return { ok: false, reason: '必须声明 slots(非空数组,能力白名单)' };+ if (!Array.isArray(raw.slots)) {+ return { ok: false, reason: 'schemaVersion 2 的 slots 必须是数组' };}- const slots: GhostSlot[] = [];+ const slots: LegacyGhostSlot[] = [];for (const s of raw.slots) {// 旧名兼容:'model' 静默归一化为 'cindy'(2026-07-11 更名,已装老包不消失)。const name = s === 'model' ? 'cindy' : s;- if (typeof name !== 'string' || !(GHOST_SLOTS as readonly string[]).includes(name)) {+ if (typeof name !== 'string' || !GHOST_SLOT_NAME_RE.test(name)) {return {ok: false,- reason: `slots 含未知卡槽 ${JSON.stringify(s)}(可用:${GHOST_SLOTS.join(' / ')})`,+ reason: `slots 含格式非法的卡槽名称 ${JSON.stringify(s)}`,};}- if (slots.includes(name as GhostSlot)) {+ if (slots.includes(name)) {return { ok: false, reason: `slots 含重复卡槽 ${JSON.stringify(s)}` };}- slots.push(name as GhostSlot);- }- // 该槽依赖新增的 Host 原生能力,旧 Cindy 不可能安全降级为“只装插件但忽略- // 模拟器”。强制声明最低版本,让 Plugin Server 在目录/详情/下载三条路径上- // 都不向旧客户端交付这份 Release。- if (- (slots.includes('ios-simulator') || slots.includes('main-view')) &&- raw.minCindyVersion === undefined- ) {- const slot = slots.includes('main-view') ? 'main-view' : 'ios-simulator';- return {- ok: false,- reason: `slots 声明了 ${JSON.stringify(slot)} 时必须同时声明 minCindyVersion`,- };+ slots.push(name);}// 声明了面板却没申请 panel 槽(或反之有槽无面板)都是清单自相矛盾。if (panel !== undefined && !slots.includes('panel')) {@@ -1589,7 +1774,8 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {// cindy 槽能力详单:与 slots 含 'cindy' 成对(有详单必有槽;有槽无详单// 允许装入但运行时零能力——老包不消失,只是代办被拒并提示作者更新)。// 字段旧名 model 作别名收入(两个都写以 cindy 为准)。- const cindyRaw = raw.cindy !== undefined ? raw.cindy : raw.model;+ const cindyRaw =+ raw.cindy !== undefined ? raw.cindy : prepared.schemaVersion === 2 ? raw.model : undefined;let cindy: GhostCindyNeeds | undefined;if (cindyRaw !== undefined) {if (!isPlainObject(cindyRaw)) {@@ -2721,7 +2907,7 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {};}- // agent 槽能力详单:缺省 = 仅点击票据;三个加档由 Desktop 独立展示并授权。+ // agent 能力详单:缺省 = 仅点击票据;可选加档由 Desktop 展示并由 Host 守门。let agent: GhostAgentNeeds | undefined;if (raw.agent !== undefined) {if (!isPlainObject(raw.agent)) {@@ -3097,7 +3283,7 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {// preview 槽详单:与 slots 含 'preview' **严格成对**(有槽必有详单——域名// 范围是本能力的全部知情面,不允许"先装后说");域名语法与 network 白名单- // 同一套(装入确认框逐条展示)。+ // 同一套(插件详情逐条展示)。let preview: GhostPreviewNeeds | undefined;if (raw.preview !== undefined) {if (!isPlainObject(raw.preview)) {@@ -3434,7 +3620,8 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {return {ok: true,manifest: {- schemaVersion: GHOST_MANIFEST_SCHEMA_VERSION,+ ...prepared.unknownV3Fields,+ schemaVersion: prepared.schemaVersion,id: raw.id,name: raw.name,version: raw.version,@@ -3449,12 +3636,18 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {...(raw.icon !== undefined ? { icon: raw.icon as string } : {}),entry: raw.entry,...(raw.launch !== undefined ? { launch: raw.launch as GhostLaunchMode } : {}),- ...(agent !== undefined ? { agent } : {}),+ ...(agent !== undefined || prepared.v3BaseAgent+ ? { agent: agent ?? {} }+ : {}),...(node !== undefined ? { node } : {}),...(raw.settingsHtml !== undefined ? { settingsHtml: raw.settingsHtml as string } : {}),...(raw.settingsHeight !== undefined ? { settingsHeight: raw.settingsHeight as number } : {}),- slots,- ...(card !== undefined ? { card } : {}),+ ...(prepared.schemaVersion === 2 ? { slots } : {}),+ ...(card !== undefined+ || prepared.v3BaseCard+ || (prepared.schemaVersion === 3 && slots.includes('card'))+ ? { card: card ?? {} }+ : {}),...(tools !== undefined ? { tools } : {}),...(cindy !== undefined ? { cindy } : {}),...(subscribe !== undefined ? { subscribe } : {}),@@ -3465,6 +3658,23 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {...(mainView !== undefined ? { mainView } : {}),...(preview !== undefined ? { preview } : {}),...(skill !== undefined ? { skill } : {}),+ ...(prepared.schemaVersion === 3 && slots.includes('notify') ? { notify: true as const } : {}),+ ...(prepared.schemaVersion === 3 && slots.includes('badge') ? { badge: true as const } : {}),+ ...(prepared.schemaVersion === 3 && slots.includes('confirm') ? { confirm: true as const } : {}),+ ...(prepared.schemaVersion === 3 && slots.includes('fs') ? { fs: true as const } : {}),+ ...(prepared.schemaVersion === 3 && slots.includes('library')+ ? { library: true as const }+ : {}),+ ...(prepared.schemaVersion === 3 && slots.includes('session-context')+ ? { sessionContext: true as const }+ : {}),+ ...(prepared.schemaVersion === 3 && slots.includes('pick') ? { pick: true as const } : {}),+ ...(prepared.schemaVersion === 3 && slots.includes('workspace')+ ? { workspace: true as const }+ : {}),+ ...(prepared.schemaVersion === 3 && slots.includes('ios-simulator')+ ? { iosSimulator: true as const }+ : {}),...(manual !== undefined ? { manual } : {}),},};