Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(plugins): 支持同账号电脑间加密交换插件资料
zqchrisb87f64e128f2
diff --git a/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-files-and-library.md b/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-files-and-library.mdindex c01a812753..95be7a668f 100644--- a/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-files-and-library.md+++ b/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-files-and-library.md@@ -191,3 +191,23 @@ await cindy.library({`write`/`writeCommit`/`read` 都回 `sha256`(宿主对实字节计算)——外自称的哈希只当对账参考,不是凭证。++### 4.10.2 同账号电脑间的插件资料同步++声明 `"deviceSync": true`,使用 `cindy.deviceSync(req)`。这是通用加密传输,不是数据库自动同步;+合并、持久化、幂等和删除标记由插件负责。需要自动接收时声明 `"launch": "resident"`。+先检查 `typeof cindy.deviceSync === 'function'`,旧 Host 保留本地功能,不伪报已同步。++- `{op:'status'}` 返回 `{ok:true, version:1, online, peers:[{deviceId,deviceName}], maxBytes}`。+- `{op:'request', peer, data}` 向同一插件发一个有界 JSON 请求,成功返回 `{ok:true,data}`。+- 对端收到 `{type:'device-sync-request', requestId, peer, data}`;实际持久化后用+ `{op:'reply',requestId,data}` 回复。requestId 由 Host 生成并绑定对端、插件实例和批准版本。+- 单个加密前 envelope(含协议字段)最多 64 KiB,每个插件最多 2 个并发请求,整机 32 个,+ 30 秒无应用回执返回 `SYNC_RESULT_UNKNOWN`。它可能已经执行;先对账,只有幂等同步才可重发。+- `SYNC_CONNECTING` 表示密钥握手中,`SYNC_OFFLINE` 表示目前不可达;退出账号、停用、卸载或+ 替换插件使旧请求失效。未知错误保留本地资料,并展示可行动状态。+- 双方必须已登录同一账号、在线、是未撤权的电脑,并安装启用 namespace 已确认、声明该能力的+ 同一插件(namespace + id)。手机是执行电脑的控制端,不保存独立同步副本;共享任务访客和+ 供应商分享不能使用此通道。Node Worker 不获得账号凭证或设备密钥。+- Host 复用 owner-scoped safeStorage 的设备密钥和首次公钥固定机制,采用 X25519 / AES-GCM。+ Device Link relay 只搬运密文;离线没有云端存储,不承诺两台从不同时在线的电脑能够交换。diff --git a/apps/desktop/src/main/cindy-brain/__tests__/deviceSyncSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/deviceSyncSlot.test.tsnew file mode 100644index 0000000000..5f58dbb30d--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/deviceSyncSlot.test.ts@@ -0,0 +1,213 @@+import { afterEach, expect, it, vi } from 'vitest';+import { PluginDeviceSync } from '../deviceSyncSlot.js';+import { generateContactsSyncIdentity } from '../../contacts-sync/crypto.js';+import {+ ghostPermissionItems,+ validateGhostManifest,+ type InstalledGhost,+} from '../../../shared/ghost.js';+import { validateGhostManifest as validateProtocolManifest } from '../../../../../../packages/plugin-protocol/src/manifest.js';++// New generic plugin boundary: real handler/encryption, in-memory wire. Unit tier.+// Existing contacts tests cannot cover plugin namespace, owner/revision and permission isolation.+const cleanups: Array<() => void> = [];+afterEach(() => {+ for (const fn of cleanups.splice(0)) fn();+ vi.useRealTimers();+});+const manifest = {+ schemaVersion: 3,+ id: 'example-sync',+ name: 'Example',+ version: '1.0.0',+ minCindyVersion: '0.1.97',+ entry: 'main.js',+ deviceSync: true,+};+function pair() {+ vi.useFakeTimers();+ const frames: Array<{ from: string; to: string; data: unknown }> = [];+ const sides = new Map<string, ReturnType<typeof side>>();+ function side(id: string) {+ let scope = 'owner-a';+ const g = {+ manifest,+ enabled: true,+ namespace: null,+ namespaceState: 'confirmed',+ instanceKey: 'example-sync',+ approval: { state: 'approved', revision: '1' },+ } as InstalledGhost;+ const identity = generateContactsSyncIdentity(),+ pins = new Map<string, string>(),+ delivered: any[] = [];+ const blocked = new Set<string>();+ const svc = new PluginDeviceSync({+ scope: () => scope,+ keys: {+ prepare: async () => {},+ getIdentity: () => identity,+ getPeerPublicKey: (p) => pins.get(p) ?? null,+ pinPeerPublicKey: async (p, k) => {+ if (pins.has(p) && pins.get(p) !== k) throw Error('pin');+ const fresh = !pins.has(p);+ pins.set(p, k);+ return fresh;+ },+ },+ getGhost: (key) => (key === 'example-sync' ? g : null),+ listGhosts: () => [g],+ deliver: async (_ghost, msg) => {+ delivered.push(msg);+ return true;+ },+ });+ svc.connect({+ self: () => id,+ peers: () =>+ [...sides.keys()]+ .filter((x) => x !== id)+ .map((deviceId) => ({ deviceId, deviceName: deviceId })),+ allowed: (peer) => sides.has(peer) && peer !== id && !blocked.has(peer),+ send: (to, data) => {+ frames.push({ from: id, to, data });+ },+ });+ svc.setActive(true);+ cleanups.push(() => svc.reset());+ return {+ svc,+ g,+ delivered,+ blocked,+ setScope: (v: string) => {+ scope = v;+ },+ };+ }+ const a = side('a');+ sides.set('a', a);+ const b = side('b');+ sides.set('b', b);+ async function flush() {+ while (frames.length) {+ const f = frames.shift()!;+ await sides.get(f.to)!.svc.receive(f.from, f.data);+ }+ }+ async function ready() {+ expect(+ await a.svc.handle('example-sync', { op: 'request', peer: 'b', data: {} }),+ ).toMatchObject({ errorCode: 'SYNC_CONNECTING' });+ await flush();+ }+ return { a, b, frames, flush, ready };+}+it('declares the capability without changing legacy manifests and projects its permission', () => {+ for (const validate of [validateGhostManifest, validateProtocolManifest]) {+ expect(validate(manifest), JSON.stringify(validate(manifest))).toMatchObject({+ ok: true,+ manifest: { deviceSync: true },+ });+ expect(validate({ ...manifest, deviceSync: false }).ok).toBe(false);+ }+ expect(ghostPermissionItems(manifest as any)).toContainEqual(+ expect.objectContaining({ key: 'deviceSync' }),+ );+});+it('exchanges encrypted opaque data only with the same plugin, then confirms the reply', async () => {+ const { a, b, frames, flush, ready } = pair();+ await ready();+ const result = a.svc.handle('example-sync', {+ op: 'request',+ peer: 'b',+ data: { text: 'private example' },+ });+ await Promise.resolve();+ await Promise.resolve();+ expect(JSON.stringify(frames)).not.toContain('private example');+ await flush();+ expect(b.delivered).toHaveLength(1);+ expect(b.delivered[0].data).toEqual({ text: 'private example' });+ expect(+ await b.svc.handle('example-sync', {+ op: 'reply',+ requestId: b.delivered[0].requestId,+ data: { persisted: true },+ }),+ ).toEqual({ ok: true });+ await flush();+ expect(await result).toEqual({ ok: true, data: { persisted: true } });+});+it('does not deliver across namespaces, revocation, disable or owner switches', async () => {+ const { a, b, flush, ready } = pair();+ await ready();+ b.g.namespace = 'example-org';+ const request = a.svc.handle('example-sync', { op: 'request', peer: 'b', data: {} });+ await Promise.resolve();+ await Promise.resolve();+ await flush();+ expect(b.delivered).toHaveLength(0);+ await vi.advanceTimersByTimeAsync(30001);+ expect(await request).toMatchObject({ errorCode: 'SYNC_RESULT_UNKNOWN' });+ b.g.namespace = null;+ b.blocked.add('a');+ const second = a.svc.handle('example-sync', { op: 'request', peer: 'b', data: {} });+ await Promise.resolve();+ await Promise.resolve();+ await flush();+ expect(b.delivered).toHaveLength(0);+ a.svc.reset();+ expect(await second).toMatchObject({ errorCode: 'SYNC_RESULT_UNKNOWN' });+ b.g.enabled = false;+ expect(await b.svc.handle('example-sync', { op: 'status' })).toMatchObject({+ errorCode: 'SYNC_NOT_ALLOWED',+ });+ b.g.enabled = true;+ b.setScope('owner-b');+ expect(await b.svc.handle('example-sync', { op: 'status' })).toMatchObject({ online: false });+});+it('invalidates replies after plugin replacement and rejects ciphertext tampering', async () => {+ const { a, b, frames, flush, ready } = pair();+ await ready();+ const result = a.svc.handle('example-sync', { op: 'request', peer: 'b', data: {} });+ await Promise.resolve();+ await Promise.resolve();+ const f = structuredClone(frames[0]);+ (f.data as any).tag = 'AAAAAAAAAAAAAAAAAAAAAA==';+ await b.svc.receive('a', f.data);+ expect(b.delivered).toHaveLength(0);+ await flush();+ expect(b.delivered).toHaveLength(1);+ b.g.approval = { state: 'approved', revision: '2' };+ expect(+ await b.svc.handle('example-sync', {+ op: 'reply',+ requestId: b.delivered[0].requestId,+ data: {},+ }),+ ).toMatchObject({ errorCode: 'SYNC_REQUEST_EXPIRED' });+ a.svc.reset();+ expect(await result).toMatchObject({ errorCode: 'SYNC_RESULT_UNKNOWN' });+});++it('expires in-flight work on stop even when the same install immediately restarts', async () => {+ const { a, b, flush, ready } = pair();+ await ready();+ const result = a.svc.handle('example-sync', { op: 'request', peer: 'b', data: {} });+ await Promise.resolve();+ await Promise.resolve();+ await flush();+ expect(b.delivered).toHaveLength(1);+ b.svc.invalidate('example-sync');+ expect(+ await b.svc.handle('example-sync', {+ op: 'reply',+ requestId: b.delivered[0].requestId,+ data: {},+ }),+ ).toMatchObject({ errorCode: 'SYNC_REQUEST_EXPIRED' });+ a.svc.invalidate('example-sync');+ expect(await result).toMatchObject({ errorCode: 'SYNC_RESULT_UNKNOWN' });+ expect(await a.svc.handle('example-sync', { op: 'status' })).toMatchObject({ online: true });+});diff --git a/apps/desktop/src/main/cindy-brain/deviceSyncSlot.ts b/apps/desktop/src/main/cindy-brain/deviceSyncSlot.tsnew file mode 100644index 0000000000..b9ba34ce49--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/deviceSyncSlot.ts@@ -0,0 +1,353 @@+import { PLUGIN_SYNC_MAX_BYTES } from '@cindy/device-link';+export { PLUGIN_SYNC_CHANNEL } from '@cindy/device-link';+import { randomUUID } from 'node:crypto';+import type { InstalledGhost } from '../../shared/ghost.js';+import { ghostInstallApprovalToken } from '../../shared/ghost.js';+import { installedGhostStoragePart } from '../../shared/pluginIdentity.js';+import {+ encryptContactsSyncBytes,+ decryptContactsSyncBytes,+ isValidContactsSyncPublicKey,+} from '../contacts-sync/crypto.js';+import type { ContactsSyncKeyStore } from '../contacts-sync/keyStore.js';++/** Opaque, bounded RPC between the same plugin on authenticated owner desktops.+ * Persistence, merge rules and retry idempotency belong to the plugin. No model runs.+ * Transport/key dependencies are injected so account and revocation races are testable.+ */+const MAX_BYTES = PLUGIN_SYNC_MAX_BYTES;+const TIMEOUT_MS = 30_000;+type Identity = { namespace: string | null; id: string };+type Packet = {+ version: 1;+ kind: 'request' | 'response';+ id: string;+ plugin: Identity;+ data: unknown;+};+export interface PluginSyncTransport {+ self(): string | null;+ peers(): Array<{ deviceId: string; deviceName: string }>;+ allowed(peer: string): boolean;+ send(peer: string, frame: unknown): void;+}+interface Deps {+ scope(): string;+ keys: Pick<+ ContactsSyncKeyStore,+ 'prepare' | 'getIdentity' | 'getPeerPublicKey' | 'pinPeerPublicKey'+ >;+ getGhost(id: string): InstalledGhost | null;+ listGhosts(): InstalledGhost[];+ deliver(ghost: InstalledGhost, message: unknown, isCurrent: () => boolean): Promise<boolean>;+}+type Pending = {+ peer: string;+ plugin: Identity;+ instance: string;+ current(): boolean;+ finish(value: unknown): void;+ timer: ReturnType<typeof setTimeout>;+};+type Incoming = {+ peer: string;+ packet: Packet;+ instance: string;+ current(): boolean;+ timer: ReturnType<typeof setTimeout>;+};+const error = (code: string) => ({ ok: false, errorCode: code });+const record = (v: unknown): v is Record<string, unknown> =>+ !!v && typeof v === 'object' && !Array.isArray(v);+const same = (a: Identity, b: Identity) => a.id === b.id && a.namespace === b.namespace;+function identity(ghost: InstalledGhost | null): Identity | null {+ if (+ !ghost?.enabled ||+ ghost.approval.state !== 'approved' ||+ ghost.manifest.deviceSync !== true ||+ ghost.namespaceState !== 'confirmed' ||+ ghost.namespace === undefined+ )+ return null;+ return { id: ghost.manifest.id, namespace: ghost.namespace };+}++export class PluginDeviceSync {+ private transport: PluginSyncTransport | null = null;+ private active = false;+ private generation = 0;+ private scope = '';+ private readonly pending = new Map<string, Pending>();+ private readonly incoming = new Map<string, Incoming>();+ private readonly keyReplies = new Map<string, number>();+ private readonly receiving = new Set<string>();+ private readonly epochs = new Map<string, number>();+ constructor(private readonly deps: Deps) {}+ connect(transport: PluginSyncTransport): void {+ this.reset();+ this.transport = transport;+ }+ setActive(active: boolean): void {+ if (!active) this.reset();+ this.active = active;+ }+ reset(): void {+ this.generation++;+ this.active = false;+ for (const p of this.pending.values()) {+ clearTimeout(p.timer);+ p.finish(error('SYNC_RESULT_UNKNOWN'));+ }+ for (const p of this.incoming.values()) clearTimeout(p.timer);+ this.pending.clear();+ this.incoming.clear();+ this.keyReplies.clear();+ this.receiving.clear();+ this.scope = this.deps.scope();+ }+ invalidate(instance: string): void {+ this.epochs.set(instance, (this.epochs.get(instance) ?? 0) + 1);+ for (const [id, p] of this.pending)+ if (p.instance === instance) {+ clearTimeout(p.timer);+ this.pending.delete(id);+ p.finish(error('SYNC_RESULT_UNKNOWN'));+ }+ for (const [id, p] of this.incoming)+ if (p.instance === instance) {+ clearTimeout(p.timer);+ this.incoming.delete(id);+ }+ }+ private capture(instance: string): (() => boolean) | null {+ const ghost = this.deps.getGhost(instance);+ if (!identity(ghost)) return null;+ const epoch = this.epochs.get(instance) ?? 0;+ const plugin = identity(ghost)!;+ const approval = ghostInstallApprovalToken(ghost!.approval);+ const scope = this.deps.scope(),+ generation = this.generation;+ return () => {+ const current = this.deps.getGhost(instance);+ return (+ this.active &&+ generation === this.generation &&+ epoch === (this.epochs.get(instance) ?? 0) &&+ scope === this.deps.scope() &&+ !!identity(current) &&+ same(identity(current)!, plugin) &&+ ghostInstallApprovalToken(current!.approval) === approval+ );+ };+ }+ async handle(instance: string, raw: unknown): Promise<unknown> {+ if (this.scope !== this.deps.scope()) this.reset();+ const plugin = identity(this.deps.getGhost(instance));+ if (!plugin) return error('SYNC_NOT_ALLOWED');+ if (!record(raw)) return error('INVALID_PARAMS');+ if (raw.op === 'status')+ return {+ ok: true,+ version: 1,+ online: this.active,+ peers: this.active ? (this.transport?.peers() ?? []) : [],+ maxBytes: MAX_BYTES,+ };+ if (raw.op === 'reply') {+ const p = typeof raw.requestId === 'string' ? this.incoming.get(raw.requestId) : null;+ if (!p || p.instance !== instance) return error('SYNC_REQUEST_EXPIRED');+ this.incoming.delete(raw.requestId as string);+ clearTimeout(p.timer);+ if (!p.current() || !this.transport?.allowed(p.peer)) return error('SYNC_REQUEST_EXPIRED');+ try {+ this.send(p.peer, { ...p.packet, kind: 'response', data: raw.data });+ return { ok: true };+ } catch {+ return error('SYNC_RESULT_UNKNOWN');+ }+ }+ if (raw.op !== 'request' || typeof raw.peer !== 'string') return error('INVALID_PARAMS');+ const current = this.capture(instance),+ peer = raw.peer;+ if (!current?.() || !this.transport?.allowed(peer)) return error('SYNC_OFFLINE');+ if (+ this.pending.size >= 32 ||+ [...this.pending.values()].filter((p) => p.instance === instance).length >= 2+ )+ return error('SYNC_BUSY');+ try {+ await this.deps.keys.prepare();+ if (!current() || !this.transport?.allowed(peer)) return error('SYNC_OFFLINE');+ if (+ this.pending.size >= 32 ||+ [...this.pending.values()].filter((p) => p.instance === instance).length >= 2+ )+ return error('SYNC_BUSY');+ if (!this.deps.keys.getPeerPublicKey(peer)) {+ this.transport.send(peer, {+ version: 1,+ kind: 'key',+ publicKey: this.deps.keys.getIdentity().publicKey,+ });+ return error('SYNC_CONNECTING');+ }+ const id = randomUUID();+ return await new Promise((resolve) => {+ const timer = setTimeout(() => {+ this.pending.delete(id);+ resolve(error('SYNC_RESULT_UNKNOWN'));+ }, TIMEOUT_MS);+ timer.unref?.();+ this.pending.set(id, { peer, plugin, instance, current, finish: resolve, timer });+ try {+ this.send(peer, { version: 1, kind: 'request', id, plugin, data: raw.data });+ } catch {+ clearTimeout(timer);+ this.pending.delete(id);+ resolve(error('SYNC_RESULT_UNKNOWN'));+ }+ });+ } catch {+ return error('SYNC_SECURE_STORAGE_UNAVAILABLE');+ }+ }+ private send(peer: string, packet: Packet): void {+ const self = this.transport?.self(),+ key = this.deps.keys.getPeerPublicKey(peer);+ if (!self || !key || !this.active || !this.transport?.allowed(peer))+ throw new Error('unavailable');+ const bytes = Buffer.from(JSON.stringify(packet));+ if (bytes.length > MAX_BYTES) throw new Error('packet too large');+ // Domain bind this channel in authenticated transferId, separate from legacy contacts packets.+ const transferId = `plugin-sync:${randomUUID()}`;+ const enc = encryptContactsSyncBytes(bytes, this.deps.keys.getIdentity().privateKey, key, {+ srcDeviceId: self,+ dstDeviceId: peer,+ transferId,+ totalChunks: 1,+ });+ this.transport.send(peer, {+ version: 1,+ kind: 'data',+ transferId,+ iv: enc.iv,+ tag: enc.tag,+ data: enc.ciphertext.toString('base64'),+ });+ }+ async receive(peer: string, raw: unknown): Promise<void> {+ if (+ !this.active ||+ !this.transport?.allowed(peer) ||+ this.scope !== this.deps.scope() ||+ !record(raw) ||+ raw.version !== 1+ )+ return;+ if (this.receiving.has(peer) || this.receiving.size >= 32) return;+ const generation = this.generation,+ scope = this.deps.scope();+ const current = () =>+ this.active &&+ generation === this.generation &&+ scope === this.deps.scope() &&+ this.transport?.allowed(peer);+ this.receiving.add(peer);+ try {+ await this.deps.keys.prepare();+ if (!current()) return;+ if (raw.kind === 'key') {+ if (!isValidContactsSyncPublicKey(raw.publicKey)) return;+ await this.deps.keys.pinPeerPublicKey(peer, raw.publicKey);+ if (!current()) return;+ if (Date.now() - (this.keyReplies.get(peer) ?? 0) > 5000) {+ this.keyReplies.set(peer, Date.now());+ this.transport!.send(peer, {+ version: 1,+ kind: 'key',+ publicKey: this.deps.keys.getIdentity().publicKey,+ });+ }+ return;+ }+ const self = this.transport?.self(),+ key = this.deps.keys.getPeerPublicKey(peer);+ if (+ raw.kind !== 'data' ||+ !self ||+ !key ||+ typeof raw.transferId !== 'string' ||+ !/^plugin-sync:[a-f0-9-]{36}$/.test(raw.transferId) ||+ typeof raw.data !== 'string' ||+ raw.data.length > Math.ceil(MAX_BYTES / 3) * 4 ||+ typeof raw.iv !== 'string' ||+ typeof raw.tag !== 'string'+ )+ return;+ const bytes = decryptContactsSyncBytes(+ { ciphertext: Buffer.from(raw.data, 'base64'), iv: raw.iv, tag: raw.tag },+ this.deps.keys.getIdentity().privateKey,+ key,+ { srcDeviceId: peer, dstDeviceId: self, transferId: raw.transferId, totalChunks: 1 },+ );+ const p: unknown = JSON.parse(bytes.toString('utf8'));+ if (+ !record(p) ||+ p.version !== 1 ||+ typeof p.id !== 'string' ||+ !/^[a-f0-9-]{36}$/.test(p.id) ||+ !record(p.plugin) ||+ typeof p.plugin.id !== 'string' ||+ !(p.plugin.namespace === null || typeof p.plugin.namespace === 'string')+ )+ return;+ const packet = p as unknown as Packet;+ if (p.kind === 'response') {+ const pending = this.pending.get(p.id);+ if (+ !pending ||+ pending.peer !== peer ||+ !same(pending.plugin, packet.plugin) ||+ !pending.current()+ )+ return;+ this.pending.delete(p.id);+ clearTimeout(pending.timer);+ pending.finish({ ok: true, data: p.data });+ } else if (p.kind === 'request' && this.incoming.size < 32) {+ const ghost = this.deps.listGhosts().find((g) => {+ const i = identity(g);+ return i && same(i, packet.plugin);+ });+ if (!ghost) return;+ const instance = installedGhostStoragePart(ghost),+ valid = this.capture(instance);+ if (!valid?.()) return;+ const requestId = randomUUID();+ const timer = setTimeout(() => this.incoming.delete(requestId), TIMEOUT_MS);+ timer.unref?.();+ this.incoming.set(requestId, { peer, packet, instance, current: valid, timer });+ if (+ !(await this.deps.deliver(+ ghost,+ {+ type: 'device-sync-request',+ requestId,+ peer,+ data: p.data,+ },+ valid,+ )) ||+ !valid()+ ) {+ clearTimeout(timer);+ this.incoming.delete(requestId);+ }+ }+ } catch {+ /* Invalid/unauthenticated frames never surface their contents or mutate plugin data. */+ } finally {+ if (generation === this.generation) this.receiving.delete(peer);+ }+ }+}diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex afb56be366..503cc40efe 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -1,3 +1,5 @@+import { PluginDeviceSync } from './deviceSyncSlot.js';+import { contactsSyncKeyStore } from '../contacts-sync/keyStore.js';import { RemotePluginPreferences } from './remotePluginPreferences.js';import { readDeviceLinkSettings } from '../device-link/settings-store.js';import { isSharedTaskPeer, isProviderSharePeer } from '@cindy/device-link';@@ -1247,6 +1249,7 @@ export async function interruptGhostCallsForAccountBoundary(): Promise<void> {// Drain in-flight staging.release (tombstone/fsync) before tearing Library// sessions. Owner mutation leases stay held until each call unwinds; waiting// for idle first would let marker-window teardown race the lease.+ pluginDeviceSync.reset();await getGhostLibrarySlot().disposeAll();if (libraryExtraDirSync) {await libraryExtraDirSync(null).catch((error) => {@@ -2008,6 +2011,7 @@ export function getGhostRuntime(): GhostRuntime {const storagePart = isValidPluginInstallRelId(id) ? pluginInstallStoragePart(id) : id;log.info('ghost runtime state', { id, state });if (state !== 'running') disconnectRoutineSource(storagePart);+ if (['off', 'stopping', 'crashed', 'fused'].includes(state)) pluginDeviceSync.invalidate(storagePart);// 崩溃/熄灯时把该意识名下的在途工具调用收掉(结构化失败给 agent)。getGhostPipeDispatcher().onRuntimeState(storagePart, state);broadcastGhostRuntimeStates();@@ -2017,6 +2021,21 @@ export function getGhostRuntime(): GhostRuntime {return runtimeSingleton;}+export const pluginDeviceSync = new PluginDeviceSync({+ scope: activeOwnerScopeKey,+ keys: contactsSyncKeyStore,+ getGhost: findGhostForInstanceId,+ listGhosts: () => getGhostManager().list(),+ deliver: async (ghost, message, isCurrent) => {+ if (!isCurrent()) return false;+ const scope = activeOwnerScopeKey();+ const id = installedGhostStoragePart(ghost);+ const started = await getGhostRuntime().spawn(ghost);+ return started.ok && isCurrent() && scope === activeOwnerScopeKey() &&+ ghostInstallApprovalToken(findGhostForInstanceId(id)?.approval) === ghostInstallApprovalToken(ghost.approval) && sendToGhostLogic(id, message);+ },+});+let dispatcherSingleton: GhostPipeDispatcher | null = null;/**@@ -8591,6 +8610,7 @@ export function registerGhostIpc(): void {}// library-request = library 持久作品库(资格审/binding 根解析/owner scope// 复核/SQL 语句门在 librarySlot;结果结构化 errorCode,永不 reject)。+ if (type === 'device-sync-request') return pluginDeviceSync.handle(id, payload);if (type === 'library-request') {return getGhostLibrarySlot().handleLibraryRequest(id, payload);}diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.tsindex 0bf73e8d00..a8c53acda7 100644--- a/apps/desktop/src/main/device-link/index.ts+++ b/apps/desktop/src/main/device-link/index.ts@@ -1,3 +1,5 @@+import { pluginDeviceSync } from '../cindy-brain/index.js';+import { PLUGIN_SYNC_CHANNEL } from '../cindy-brain/deviceSyncSlot.js';/*** device-link host —— 跨设备远程控制的 main 进程接线层。*@@ -1059,6 +1061,10 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): v}return;}+ if (p?.channel === PLUGIN_SYNC_CHANNEL) {+ void pluginDeviceSync.receive(env.src, p.payload);+ return;+ }if (p?.channel === DL_CONTACTS_SYNC_CHANNEL) {if (shouldExchangeDictionaryWith({@@ -1124,6 +1130,15 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): v).map(([deviceId]) => deviceId),});+ pluginDeviceSync.connect({+ self: () => client?.getSelfDeviceId() ?? null,+ peers: () => [...presenceOnlineByDevice.entries()]+ .filter(([deviceId, online]) => !isScopedPeer(deviceId) && deviceId !== client?.getSelfDeviceId() && shouldExchangeDictionaryWith({ online, platform: getControllerPlatform(deviceId), revoked: isDeviceRevoked(deviceId) }))+ .map(([deviceId]) => ({ deviceId, deviceName: presenceNameByDevice.get(deviceId) ?? deviceId.slice(0, 8) })),+ allowed: deviceId => !isScopedPeer(deviceId) && deviceId !== client?.getSelfDeviceId() &&+ shouldExchangeDictionaryWith({ online: presenceOnlineByDevice.get(deviceId) === true, platform: getControllerPlatform(deviceId), revoked: isDeviceRevoked(deviceId) }),+ send: (deviceId, frame) => { if (!client) throw new Error('device link unavailable'); client.sendPush(deviceId, PLUGIN_SYNC_CHANNEL, frame); },+ });initContactsDeviceSync({getSelfDeviceId: () => client?.getSelfDeviceId() ?? null,listOnlineDesktopDevices: () =>@@ -1193,6 +1208,7 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): v// 接管后对本机仍在控制、且 link 未就绪的设备补发一次重建,避免启动竞态留下// 半开链路,不必等对端下一帧。setTimeout(retriggerReopenForControlledDevices, 250);+ pluginDeviceSync.setActive(true);setContactsDeviceLinkOwnerActive(true);refreshAppliedSettingsSnapshot();pollContactsDeviceSyncSettingChange();@@ -1358,6 +1374,7 @@ export function getMobileNotifyGeneration(): number {* 同进程换账号登录还会把上一账号的控制端串到新账号。*/function teardownActiveLink(): void {+ pluginDeviceSync.reset();invalidatePluginOauth();void stopSharedTaskRuntime().catch((error) => log.warn('sharedTask runtime teardown failed', error));stopProviderShareRuntime();diff --git a/apps/desktop/src/main/maker-host/built-in-skills.ts b/apps/desktop/src/main/maker-host/built-in-skills.tsindex debaa7d52d..671bb841f6 100644--- a/apps/desktop/src/main/maker-host/built-in-skills.ts+++ b/apps/desktop/src/main/maker-host/built-in-skills.ts@@ -25,7 +25,7 @@ const VERSIONS_DIRECTORY = '.versions';const ACTIVE_BUNDLE_LINK = '.active';const BUILT_IN_SKILL_MUTATION_WAIT_MS = 5_000;/** Increment whenever shipped built-in Skill bytes change between releases. */-export const BUILT_IN_SKILLS_BUNDLE_VERSION = 14;+export const BUILT_IN_SKILLS_BUNDLE_VERSION = 15;const PLUGIN_CREATOR_FIRST_BUNDLE_VERSION = 13;export interface BuiltInSkillDescriptor {diff --git a/apps/desktop/src/preload/ghostPreload.ts b/apps/desktop/src/preload/ghostPreload.tsindex e36e5e462c..0940b9ebdb 100644--- a/apps/desktop/src/preload/ghostPreload.ts+++ b/apps/desktop/src/preload/ghostPreload.ts@@ -65,6 +65,8 @@ contextBridge.exposeInMainWorld('cindy', {},fs: (req: Record<string, unknown>): Promise<unknown> =>ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'fs-request' }),+ deviceSync: (req: Record<string, unknown>): Promise<unknown> =>+ ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'device-sync-request' }),library: (req: Record<string, unknown>): Promise<unknown> =>ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'library-request' }),tasks: Object.fromEntries(diff --git a/apps/desktop/src/renderer/features/plugin/lib/permissionItemIcon.ts b/apps/desktop/src/renderer/features/plugin/lib/permissionItemIcon.tsindex 24665073f7..b8caa379b7 100644--- a/apps/desktop/src/renderer/features/plugin/lib/permissionItemIcon.ts+++ b/apps/desktop/src/renderer/features/plugin/lib/permissionItemIcon.ts@@ -18,6 +18,7 @@ const PERMISSION_ICON: Record<GhostPermissionItem['kind'], LucideIcon> = {confirm: MessageCircleQuestion,fs: FilePen,library: Library,+ deviceSync: Radio,'session-context': MapPin,pick: FolderOpen,preview: AppWindow,diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex f8ed7ee54f..10a0ce7060 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -6722,6 +6722,8 @@"confirmDetail": "Before acting it can open a dialog that looks like Cindy's own to ask you. The question comes from the plugin and the dialog is labeled with its name; only you can click confirm or cancel — the plugin cannot. At most one dialog at a time, and asking too often is blocked.","fsWrite": "Can write files (create / modify)","fsWriteDetail": "Its own private data folder is always writable. Writes into the current session's working directory follow the session's permission mode (auto-approve modes write directly; per-action modes ask you first). Any other folder always requires your confirmation. Files are always written by the host — the plugin itself never touches your file system.",+ "deviceSync": "Sync plugin data between your computers",+ "deviceSyncDetail": "Exchanges this plugin’s data with the same plugin on your other online computers signed in to the same Cindy account. Transfers are encrypted. The plugin controls merging and deletions; no credentials or other plugins’ data are shared.","libraryPersist": "Can use a durable library (large files and databases)","libraryPersistDetail": "It gets a Cindy-managed storage area for your work (canvases, images, databases) with no normal plugin data quota. All file and database operations are executed by the host; the plugin only uses relative paths inside its own library and cannot touch your other files. It can also ask Cindy to show a library file in Finder or Explorer, or open the system Save As dialog so you choose where a copy goes; cancelling Save As copies nothing. It can also write a PNG bitmap to the system clipboard with no confirmation dialog; this overwrites the current clipboard. Uninstalling the plugin does not delete this data; deletion requires separate confirmation in Cindy settings.","networkHost": "Accesses the network domain {{host}}",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 2bbcef9451..bed0dcd5bf 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -6691,6 +6691,8 @@"confirmDetail": "実行前に Cindy 自身と同じ確認ダイアログを開いて尋ねることができます。文面はプラグインが提供し、ダイアログにはその名前が表示されます。確認するかキャンセルするかはあなたがクリックして決め、プラグイン自身はクリックできません。同時に開けるのは 1 つまでで、頻繁な要求はブロックされます。","fsWrite": "ファイルを書き込めます(作成/変更)","fsWriteDetail": "専用データフォルダにはいつでも書き込めます。現在のセッションの作業ディレクトリへの書き込みはセッションの権限モードに従います(自動承認モードでは直接書き込み、逐次確認モードでは事前に承認を求めます)。それ以外のフォルダへの書き込みは毎回確認が必要です。ファイルは常にホストが代理で書き込み、プラグイン自体があなたのファイルシステムに直接アクセスすることはありません。",+ "deviceSync": "自分のパソコン間でプラグインのデータを同期",+ "deviceSyncDetail": "同じ Cindy アカウントでログインしているオンラインのパソコン上の同じプラグインと、データを暗号化して交換します。統合と削除はプラグインが処理し、認証情報や他のプラグインのデータは共有しません。","libraryPersist": "永続ライブラリを使用可能(大量のファイルとデータベース)","libraryPersistDetail": "Cindy が管理する独立した保存領域を取得し、作品データ(キャンバス、画像、データベースなど)を保存します。通常のプラグインデータ割り当ての制限を受けません。ファイルとデータベースの操作はすべてホストが代行実行し、プラグインはライブラリ内の相対パスのみを使用して、他のファイルに触れることはできません。ライブラリ内のファイルをシステムのフォルダで表示したり、システムの名前を付けて保存ダイアログを開いてコピー先を選ばせることもできます。キャンセルすれば何もコピーされません。確認ダイアログなしで PNG ビットマップをシステムクリップボードに書き込むこともでき、その場合は現在のクリップボード内容が上書きされます。プラグインをアンインストールしてもこのデータは削除されず、削除には Cindy 設定での個別確認が必要です。","networkHost": "ネットワークドメイン {{host}} にアクセス",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 07c396f021..5378d4da78 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -6691,6 +6691,8 @@"confirmDetail": "작업 전에 Cindy 자체와 동일한 확인 대화상자를 열어 물어볼 수 있습니다. 질문 내용은 플러그인이 제공하며 대화상자에는 그 이름이 표시됩니다. 확인이든 취소든 직접 클릭해야 하고 플러그인은 스스로 누를 수 없습니다. 동시에 하나만 열 수 있으며 너무 자주 요청하면 차단됩니다.","fsWrite": "파일을 쓸 수 있음(생성/수정)","fsWriteDetail": "전용 데이터 폴더에는 언제든지 쓸 수 있습니다. 현재 세션의 작업 디렉터리 쓰기는 세션의 권한 모드를 따릅니다(자동 승인 모드에서는 바로 쓰고, 개별 확인 모드에서는 먼저 승인을 요청합니다). 그 외 폴더에 쓰려면 매번 확인이 필요합니다. 파일은 항상 호스트가 대신 기록하며 플러그인 자체는 파일 시스템에 직접 접근할 수 없습니다.",+ "deviceSync": "내 컴퓨터 간 플러그인 데이터 동기화",+ "deviceSyncDetail": "같은 Cindy 계정으로 로그인한 온라인 컴퓨터의 동일한 플러그인과 데이터를 암호화하여 교환합니다. 병합과 삭제는 플러그인이 처리하며, 인증 정보나 다른 플러그인의 데이터는 공유하지 않습니다.","libraryPersist": "영구 라이브러리 사용 가능(대용량 파일 및 데이터베이스)","libraryPersistDetail": "Cindy가 관리하는 독립 저장 공간을 받아 작업 데이터(캔버스, 이미지, 데이터베이스 등)를 저장하며, 일반 플러그인 데이터 할당량 제한을 받지 않습니다. 파일과 데이터베이스 작업은 모두 호스트가 대신 실행하고 플러그인은 라이브러리 내 상대 경로만 사용하여 다른 파일에는 접근할 수 없습니다. 라이브러리 파일을 시스템 폴더에서 보여 주거나 시스템 다른 이름으로 저장 대화상자를 열어 복사 위치를 고르게 할 수도 있으며, 취소하면 아무 파일도 복사되지 않습니다. 확인 대화상자 없이 PNG 비트맵을 시스템 클립보드에 쓸 수도 있으며, 이때 현재 클립보드 내용이 덮어쓰입니다. 플러그인을 제거해도 이 데이터는 삭제되지 않으며, 삭제는 Cindy 설정에서 별도 확인이 필요합니다.","networkHost": "네트워크 도메인 {{host}}에 접근",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 58d65f4de5..6094950da1 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -6691,6 +6691,8 @@"confirmDetail": "它动手前可以弹一个和 Cindy 同款的确认框来问你,问句由它提供、框上会标注它的名字;同意还是取消都由你亲手点,它自己点不了。同时最多一个确认框,弹得太频会被拦下。","fsWrite": "可写入文件(创建/修改)","fsWriteDetail": "它自己的专属数据目录随时可写;当前任务的工作目录跟随任务的权限模式(免批模式直接写,逐条确认模式先征求你同意);其它目录每次都需要你确认。文件始终由主机代写,插件本身无法直接访问你的文件系统。",+ "deviceSync": "在你的电脑间同步插件资料",+ "deviceSyncDetail": "与登录同一 Cindy 账号的其他在线电脑上的同一插件加密交换资料。合并和删除由插件处理,不共享凭证或其他插件的资料。","libraryPersist": "可使用持久作品库(大量文件与数据库)","libraryPersistDetail": "它会获得一个由 Cindy 管理的独立存储区,用来保存你的作品数据(如画布、图片、数据库),不受普通插件数据配额限制。文件与数据库操作全部由主机代执行,插件只能使用库内相对路径,无法触碰你的其它文件。它还可以让 Cindy 在系统文件夹中显示库内文件,或弹出系统另存为窗口由你选择拷贝位置;取消则不会拷出任何文件。它还可以把 PNG 位图写入系统剪贴板;没有确认框,会覆盖当前剪贴板内容。卸载插件不会删除这些数据;删除必须在 Cindy 设置中单独确认。","networkHost": "访问网络域名 {{host}}",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 068c38a554..24dd7437c3 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -6691,6 +6691,8 @@"confirmDetail": "它動手前可以彈一個和 Cindy 同款的確認框來問你,問句由它提供、框上會標註它的名字;同意還是取消都由你親手點,它自己點不了。同時最多一個確認框,彈得太頻會被攔下。","fsWrite": "可寫入檔案(建立/修改)","fsWriteDetail": "它自己的專屬資料目錄隨時可寫;當前任務的工作目錄跟隨任務的權限模式(免批模式直接寫,逐條確認模式先徵求你同意);其它目錄每次都需要你確認。檔案始終由主機代寫,插件本身無法直接訪問你的檔案系統。",+ "deviceSync": "在你的電腦間同步插件資料",+ "deviceSyncDetail": "與登入同一 Cindy 帳號的其他線上電腦上的同一插件加密交換資料。合併和刪除由插件處理,不共用憑證或其他插件的資料。","libraryPersist": "可使用持久作品庫(大量檔案與資料庫)","libraryPersistDetail": "它會取得一個由 Cindy 管理的獨立儲存區,用來保存你的作品資料(如畫布、圖片、資料庫),不受一般插件資料配額限制。檔案與資料庫操作全部由主機代執行,插件只能使用庫內相對路徑,無法觸碰你的其它檔案。它還可以讓 Cindy 在系統資料夾中顯示庫內檔案,或彈出系統另存為視窗由你選擇拷貝位置;取消則不會拷出任何檔案。它還可以把 PNG 點陣圖寫入系統剪貼簿;沒有確認框,會覆蓋目前剪貼簿內容。解除安裝插件不會刪除這些資料;刪除必須在 Cindy 設定中單獨確認。","networkHost": "訪問網路域名 {{host}}",diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.tsindex 1524565e50..7fd543d434 100644--- a/apps/desktop/src/shared/ghost.ts+++ b/apps/desktop/src/shared/ghost.ts@@ -160,6 +160,7 @@ const LEGACY_GHOST_SLOTS = ['confirm','fs','library',+ 'device-sync','session-context','pick','preview',@@ -1567,6 +1568,8 @@ export interface GhostManifest {fs?: true;/** 持久作品库;卸载不删数据,位置和删除由 Host 设置页管理。 */library?: true;+ /** Encrypted opaque exchange with this plugin on same-account desktops. */+ deviceSync?: true;sessionContext?: true;pick?: true;workspace?: true;@@ -1856,6 +1859,7 @@ export interface GhostPermissionItem {| 'confirm'| 'fs'| 'library'+ | 'deviceSync'| 'session-context'| 'pick'| 'preview'@@ -2202,6 +2206,9 @@ export function ghostPermissionItems(manifest: GhostManifest): GhostPermissionIt// library 能力:持久作品库(用户数据语义,不是临时缓存)。详情页必须讲清// 卸载不删、删除走独立确认、会打开系统文件夹/另存为对话框,以及可把 PNG// 位图写入系统剪贴板(无确认框,会覆盖当前剪贴板)。+ if (manifest.deviceSync === true) {+ items.push({ key: 'deviceSync', kind: 'deviceSync', labelKey: 'deviceSync', detailKey: 'deviceSyncDetail' });+ }if (manifest.library === true) {items.push({key: 'library',@@ -3013,6 +3020,7 @@ const GHOST_MANIFEST_KNOWN_TOP_LEVEL_FIELDS = new Set(['confirm','fs','library',+ 'deviceSync','sessionContext','pick','workspace',@@ -3025,6 +3033,7 @@ const V3_BOOLEAN_CAPABILITY_FIELDS = ['confirm','fs','library',+ 'deviceSync','sessionContext','pick','workspace',@@ -3051,6 +3060,7 @@ const V3_BOOLEAN_TO_LEGACY_SLOT: Record<(typeof V3_BOOLEAN_CAPABILITY_FIELDS)[nuconfirm: 'confirm',fs: 'fs',library: 'library',+ deviceSync: 'device-sync',sessionContext: 'session-context',pick: 'pick',workspace: 'workspace',@@ -6072,6 +6082,7 @@ function validateGhostManifestInput(value: unknown, preserveHistoricalTasks: boo...(slots.includes('badge') ? { badge: true as const } : {}),...(slots.includes('confirm') ? { confirm: true as const } : {}),...(slots.includes('fs') ? { fs: true as const } : {}),+ ...(slots.includes('device-sync') ? { deviceSync: 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 } : {}),@@ -8419,6 +8430,12 @@ export function classifyGhostLibraryOperationSupport(return listed.has(operation) ? 'supported' : 'unsupported';}+/** Opaque encrypted RPC; plugin identity is always inferred from the sender. */+export type GhostPipeDeviceSyncRequest =+ | { type: 'device-sync-request'; op: 'status' }+ | { type: 'device-sync-request'; op: 'request'; peer: string; data: unknown }+ | { type: 'device-sync-request'; op: 'reply'; requestId: string; data: unknown };+/** 上行:library 请求(cindy.library(req) ≡ send({type:'library-request', …req}))。 */export interface GhostPipeLibraryRequest {type: 'library-request';diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.mdindex d12c88f962..4e52f9559a 100644--- a/docs/dev-rules/plugin-security-and-authoring.md+++ b/docs/dev-rules/plugin-security-and-authoring.md@@ -833,3 +833,13 @@ visible 复用当前账号模型选择器的用户开关与目录默认值;隐不暴露 ProviderView、auth、账号 identity 或 endpoint;响应 no-store、仅 GET、无参数,检查插件在装启用与 owner 归属,异步返回前复核。旧 Host 404 时插件应明确提示升级。此端点不覆盖远程 SSH 模型,执行前仍需核验真实路由。+++### 同账号插件资料同步++`deviceSync: true` 是独立自主能力;旧版插件的权限不变。Host 只允许 namespace 已确认、+已装启用且批准有效的同一插件在同账号未撤权电脑之间交换有界密文,业务合并与持久化+留在插件。每次请求和回执重新核验 owner、安装 revision、namespace 与 peer。+不向插件提供设备私钥、账号 token 或其他插件数据,不为通道增加远程 Renderer IPC。+接口和失败语义见 `FORGE_GUIDE` §4.10.2,协议与兼容边界见+[协议兼容](protocol-compatibility.md#插件资料设备同步)。diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex b823b7765c..8a2b5a9192 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -2731,3 +2731,17 @@ still use the same host-owned mail workflow as the chat card.都按当时的分类执行。不改 relay 帧、服务端 schema 或 Mobile 原生指纹。Cindy AI 设置卡片保留可选读取返回的 `unlimited` 状态,显示“未设置个人限额”;它不代表部门或企业没有限制。`invalidated` 清除该状态,有限额快照覆盖该状态,切换账号不复用上一账号结果。旧 `null` push 无法区分失效与不限额,本地卡片收到后通过既有可选读取核对;同一账号的多个组件共享在途读取,收到读取自身的广播时复用该请求,避免多窗口之间反复触发刷新。主进程跨窗口共享在途读取,已知不限额参与既有节流,重复不限额结果不重复广播。IPC payload 与远程消费者保持兼容。++## 插件资料设备同步++`device-link:plugin-sync:v1` 只在 Desktop Main 消费,wire 定义在+`packages/device-link/src/pluginSyncProtocol.ts`。同账号、未撤权的在线电脑交换已确认+namespace + id 下同一插件的有界 JSON 请求;`deviceSync: true` 是独立能力,权限区同步展示。+手机继续操作执行电脑上的插件,不建立独立副本;共享任务和供应商分享不准入。+旧客户端忽略新通道,插件探测 API 后保留本地功能;超时不代表未执行,不自动重试非幂等动作。+复用现有设备密钥库,AES-GCM AAD 使用 `plugin-sync:` transfer 标记与源/目标设备绑定。+每请求 64 KiB、每插件 2 个/全机 32 个在途、30 秒超时;应用持久化后才回复。+账号/owner、安装 revision、插件启停和撤权每次重新核验,旧请求失效只影响其调用,+不重连共享 relay。恢复由插件持久状态对账,不恢复失效请求。+实现与 unit 回归:`cindy-brain/deviceSyncSlot.ts` / `__tests__/deviceSyncSlot.test.ts`。+完整体验需要两台电脑都更新 Host 和插件;本地回归不能代替双机稳定版/Beta 实测。diff --git a/packages/device-link/src/index.ts b/packages/device-link/src/index.tsindex d8db527b1c..b96c95e092 100644--- a/packages/device-link/src/index.ts+++ b/packages/device-link/src/index.ts@@ -15,6 +15,7 @@ export * from "./invokeTransfer.js";export * from "./topics.js";export * from "./attachmentOssRef.js";export * from "./contactsSyncProtocol.js";+export * from "./pluginSyncProtocol.js";export * from "./discordSchedulerProtocol.js";export * from "./remoteResources.js";export * from "./remoteDesktop.js";diff --git a/packages/device-link/src/pluginSyncProtocol.ts b/packages/device-link/src/pluginSyncProtocol.tsnew file mode 100644index 0000000000..4d3c3db902--- /dev/null+++ b/packages/device-link/src/pluginSyncProtocol.ts@@ -0,0 +1,15 @@+/** Opaque same-account Desktop plugin exchange. Relay carries only key frames and ciphertext.+ * Older clients ignore this channel; absence of a reply never implies execution failure.+ */+export const PLUGIN_SYNC_CHANNEL = "device-link:plugin-sync:v1";+export const PLUGIN_SYNC_MAX_BYTES = 64 * 1024;+export type PluginSyncWireFrame =+ | { version: 1; kind: "key"; publicKey: string }+ | {+ version: 1;+ kind: "data";+ transferId: string;+ iv: string;+ tag: string;+ data: string;+ };diff --git a/packages/plugin-protocol/src/manifest.ts b/packages/plugin-protocol/src/manifest.tsindex fcaa12b0d1..543def33be 100644--- a/packages/plugin-protocol/src/manifest.ts+++ b/packages/plugin-protocol/src/manifest.ts@@ -101,6 +101,7 @@ export const LEGACY_GHOST_SLOTS = ['confirm','fs','library',+ 'device-sync','session-context','pick','preview',@@ -1003,6 +1004,8 @@ export interface GhostManifest {fs?: true;/** 持久作品库;卸载不删数据,位置和删除由 Host 设置页管理。 */library?: true;+ /** Encrypted opaque exchange with this plugin on same-account desktops. */+ deviceSync?: true;sessionContext?: true;pick?: true;workspace?: true;@@ -1210,6 +1213,7 @@ const GHOST_MANIFEST_KNOWN_TOP_LEVEL_FIELDS = new Set(['confirm','fs','library',+ 'deviceSync','sessionContext','pick','workspace',@@ -1222,6 +1226,7 @@ const V3_BOOLEAN_CAPABILITY_FIELDS = ['confirm','fs','library',+ 'deviceSync','sessionContext','pick','workspace',@@ -1248,6 +1253,7 @@ const V3_BOOLEAN_TO_LEGACY_SLOT: Record<(typeof V3_BOOLEAN_CAPABILITY_FIELDS)[nuconfirm: 'confirm',fs: 'fs',library: 'library',+ deviceSync: 'device-sync',sessionContext: 'session-context',pick: 'pick',workspace: 'workspace',@@ -3827,6 +3833,7 @@ export function validateGhostManifest(value: unknown): ManifestValidation {...(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 } : {}),+ ...(slots.includes('device-sync') ? { deviceSync: true as const } : {}),...(prepared.schemaVersion === 3 && slots.includes('library')? { library: true as const }: {}),