Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
Merge main and set plugin download budget to two hours
Dash1f91e60ea5a6
diff --cc apps/desktop/src/main/cindy-brain/__tests__/downloadSlot.test.tsindex 6656f6f4e9,0000000000..f5ddc6dfe7mode 100644,000000..100644--- a/apps/desktop/src/main/cindy-brain/__tests__/downloadSlot.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/downloadSlot.test.ts@@@ -1,367 -1,0 +1,416 @@@+import { it, expect, vi } from 'vitest';+import fs from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+const guarded = vi.hoisted(() => ({ fetch: vi.fn() }));+vi.mock('../../maker-host/outbound-fetch.js', () => ({ guardedOutboundFetch: guarded.fetch }));+import { PluginDownloadSlot } from '../downloadSlot';+import { PluginDownloadCache } from '../downloadCache';+import type { InstalledGhost } from '../../../shared/ghost';++it('keeps display progress monotonic across restart retries and resets for a new request', async () => {++ const root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'download-progress-')));++ const events: any[] = [];++ const slot = new PluginDownloadSlot({++ root: (id) => path.join(root, id),++ scope: () => 'owner',++ send: (_, event) => events.push(event),++ getGhost: () =>++ ({++ enabled: true,++ approval: {},++ manifest: { node: {}, network: { hosts: ['github.com'] } },++ }) as unknown as InstalledGhost,++ download: async (o) => {++ expect(o.timeout?.totalMs).toBe(2 * 60 * 60 * 1000);++ for (const loaded of [0, 6, 0, 2, 8, 10]) {++ o.onProgress?.({ loaded, total: 10, percent: loaded * 10, speedBps: 2 });++ }++ await fs.writeFile(o.targetPath, '0123456789');++ return {++ path: o.targetPath,++ size: 10,++ sha256: o.sha256,++ fromCache: false,++ durationMs: 1,++ resumedFromBytes: 0,++ };++ },++ });++ try {++ for (const id of ['first', 'second']) {++ expect(++ await slot.handle('p', {++ kind: 'start',++ id,++ url: 'https://github.com/file',++ sha256: 'a'.repeat(64),++ bytes: 10,++ }),++ ).toMatchObject({ ok: true });++ const progress = events.filter((e) => e.data.id === id && e.data.phase === 'downloading');++ expect(progress.map((e) => e.data.loaded)).toEqual([0, 6, 6, 6, 8, 10]);++ expect(progress.map((e) => e.data.percent)).toEqual([0, 60, 60, 60, 80, 100]);++ expect(progress.every((e) => e.data.speedBps === 2)).toBe(true);++ }++ } finally {++ await fs.rm(root, { recursive: true, force: true });++ }++});+it('a destroyed caller cannot enter Node after a delayed lease, even if the plugin remains enabled', async () => {+ let finish!: () => void;+ const barrier = new Promise<void>((resolve) => {+ finish = resolve;+ });+ const release = vi.fn();+ const acquire = vi+ .spyOn(PluginDownloadCache.prototype, 'acquire')+ .mockImplementation(async () => {+ await barrier;+ return { path: '/fixture/artifact', release };+ });+ let active = true;+ const slot = new PluginDownloadSlot({+ root: () => '/fixture',+ scope: () => 'owner',+ send() {},+ getGhost: () => ({ enabled: true, approval: {}, manifest: { node: {} } }) as InstalledGhost,+ download: async () => {+ throw Error('unused');+ },+ });+ const run = vi.fn(async () => ({ ok: true }));+ try {+ const request = slot.withNodeDownloads(+ 'p',+ { downloadTokens: { archive: 'receipt' } },+ run,+ () => active,+ );+ expect(acquire).toHaveBeenCalledOnce();+ active = false; // runtime.stop destroys the caller before broker.stopAndWait.+ finish();+ expect(await request).toMatchObject({ ok: false });+ expect(run).not.toHaveBeenCalled();+ expect(release).toHaveBeenCalledOnce();+ expect(await slot.withNodeDownloads('p', {}, run, () => active)).toMatchObject({ ok: false });+ expect(run).not.toHaveBeenCalled();+ } finally {+ finish();+ acquire.mockRestore();+ }+});+it('shutdown drains cancelled downloads and rejects new downloads and Node handoffs', async () => {+ const root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'download-shutdown-')));+ let started!: () => void, finish!: () => void;+ const ready = new Promise<void>((resolve) => {+ started = resolve;+ });+ const drained = new Promise<void>((resolve) => {+ finish = resolve;+ });+ const slot = new PluginDownloadSlot({+ root: (id) => path.join(root, id),+ scope: () => 'anonymous',+ send() {},+ getGhost: () =>+ ({+ enabled: true,+ approval: {},+ manifest: { node: {}, network: { hosts: ['github.com'] } },+ }) as unknown as InstalledGhost,+ download: async (options) => {+ started();+ await new Promise<void>((resolve) =>+ options.signal!.addEventListener('abort', () => resolve(), { once: true }),+ );+ await drained;+ throw Error('aborted');+ },+ });+ const request = {+ kind: 'start',+ id: 'x',+ url: 'https://github.com/file',+ sha256: 'a'.repeat(64),+ bytes: 2,+ };+ try {+ const work = slot.handle('p', request);+ await ready;+ let stopped = false;+ const stop = slot.stopAndWait().then(() => {+ stopped = true;+ });+ await Promise.resolve();+ expect(stopped).toBe(false);+ expect(await slot.handle('p', { ...request, id: 'later' })).toMatchObject({ ok: false });+ expect(+ await slot.withNodeDownloads('p', {}, async () => {+ throw Error('must not run');+ }),+ ).toMatchObject({ ok: false });+ finish();+ await stop;+ await work;+ await slot.removePlugin('p');+ await expect(fs.stat(path.join(root, 'p'))).rejects.toMatchObject({ code: 'ENOENT' });+ } finally {+ finish();+ await fs.rm(root, { recursive: true, force: true });+ }+});+it('restricts redirects, rejects arbitrary paths and isolates owner delivery', async () => {+ const root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'plugin-download-test-')));+ let scope = 'a';+ const events: unknown[] = [];+ const ghost = {+ enabled: true,+ approval: { state: 'approved' },+ manifest: { node: {}, network: { hosts: ['github.com'] } },+ } as unknown as InstalledGhost;+ let calls = 0;+ const slot = new PluginDownloadSlot({+ root: (id) => path.join(root, id),+ scope: () => scope,+ getGhost: () => ghost,+ send: (_, e) => events.push(e),+ download: async (o) => {+ calls++;+ expect(o.isUrlAllowed!('https://evil.invalid/file')).toBe(false);+ expect(o.isUrlAllowed!('http://github.com/file')).toBe(false);+ expect(o.isUrlAllowed!('https://github.com/other')).toBe(true);+ expect(o.request).toBeTypeOf('function');+ o.onProgress?.({ loaded: 1, total: 2, percent: 50, speedBps: 1 });+ scope = 'b';+ return {+ path: o.targetPath,+ size: 2,+ sha256: o.sha256,+ fromCache: false,+ durationMs: 1,+ resumedFromBytes: 0,+ };+ },+ });+ const req = {+ kind: 'start',+ id: 'x',+ url: 'https://github.com/file',+ sha256: 'a'.repeat(64),+ bytes: 2,+ };+ try {+ expect(await slot.handle('p', { ...req, targetPath: '/tmp/arbitrary' })).toMatchObject({+ ok: false,+ });+ expect(calls).toBe(0);+ expect(await slot.handle('p', req)).toMatchObject({ ok: false });+ expect(calls).toBe(1);+ expect(events.filter((x: any) => x.data.phase === 'completed')).toHaveLength(0);+ } finally {+ await fs.rm(root, { recursive: true, force: true });+ }+});+it('cancel drains the matching request before acknowledging an immediate same-id retry', async () => {+ const root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'plugin-download-test-')));+ const ghost = {+ enabled: true,+ approval: {},+ manifest: { node: {}, network: { hosts: ['github.com'] } },+ } as unknown as InstalledGhost;+ let started!: () => void;+ const ready = new Promise<void>((r) => (started = r));+ let finish!: () => void;+ const cleanup = new Promise<void>((r) => (finish = r));+ let calls = 0;+ const slot = new PluginDownloadSlot({+ root: (id) => path.join(root, id),+ scope: () => 'a',+ getGhost: () => ghost,+ send: () => {},+ download: async (o) => {+ if (++calls === 1) {+ await new Promise<void>((resolve) => {+ started();+ o.signal!.addEventListener('abort', () => resolve());+ });+ await cleanup;+ throw Error('aborted');+ }+ await fs.writeFile(o.targetPath, 'ok');+ return {+ path: o.targetPath,+ size: 2,+ sha256: o.sha256,+ fromCache: false,+ durationMs: 1,+ resumedFromBytes: 0,+ };+ },+ });+ try {+ const request = {+ kind: 'start',+ id: 'x',+ url: 'https://github.com/file',+ sha256: 'a'.repeat(64),+ bytes: 2,+ };+ const work = slot.handle('p', request);+ await ready;+ let acknowledged = false;+ const cancel = slot.handle('p', { kind: 'cancel', id: 'x' }).then(() => {+ acknowledged = true;+ });+ await Promise.resolve();+ expect(acknowledged).toBe(false);+ finish();+ await cancel;+ expect(await work).toMatchObject({ ok: false, message: '下载已取消' });+ expect(await slot.handle('p', request)).toMatchObject({ ok: true });+ expect(calls).toBe(2);+ } finally {+ finish();+ await fs.rm(root, { recursive: true, force: true });+ }+});++it('hands opaque receipts only to the owning Node call and preserves legacy params', async () => {+ const root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'plugin-receipt-test-')));+ const alias = root + '-alias';+ const outside = root + '-outside';+ await fs.symlink(root, alias, process.platform === 'win32' ? 'junction' : 'dir');+ let scope = 'a';+ const ghost = {+ enabled: true,+ approval: { revision: 'a' },+ manifest: { node: {}, network: { hosts: ['github.com'] } },+ } as unknown as InstalledGhost;+ const slot = new PluginDownloadSlot({+ root: (id) => path.join(alias, id),+ scope: () => scope,+ getGhost: () => ghost,+ send: () => {},+ download: async (o) => {+ await fs.writeFile(o.targetPath, 'ok');+ return {+ path: o.targetPath,+ size: 2,+ sha256: o.sha256,+ fromCache: false,+ durationMs: 1,+ resumedFromBytes: 0,+ };+ },+ });+ const req = {+ kind: 'start',+ id: 'x',+ url: 'https://github.com/file',+ sha256: 'a'.repeat(64),+ bytes: 2,+ };+ try {+ const result = (await slot.handle('p', req)) as { ok: boolean; token: string };+ expect(result.ok).toBe(true);+ expect(result).not.toHaveProperty('path');+ let called = 0;+ const run = async (payload: any) => {+ called++;+ expect(await fs.readFile(payload.params.downloads.archive, 'utf8')).toBe('ok');+ return { ok: true };+ };+ const payload = {+ type: 'node-request',+ method: 'unpack',+ downloadTokens: { archive: result.token },+ params: {},+ };+ expect(await slot.withNodeDownloads('other', payload, run)).toMatchObject({+ ok: false,+ errorCode: 'INVALID_REQUEST',+ });+ expect(await slot.withNodeDownloads('p', payload, run)).toEqual({ ok: true });+ expect(called).toBe(1);+ expect(+ await slot.withNodeDownloads('p', { ...payload, params: { downloads: {} } }, run),+ ).toMatchObject({ ok: false });+ scope = 'b';+ expect(await slot.withNodeDownloads('p', payload, run)).toMatchObject({+ ok: false,+ errorCode: 'INVALID_REQUEST',+ });+ scope = 'a';+ ghost.approval = { ...ghost.approval, revision: 'b' } as InstalledGhost['approval'];+ expect(await slot.withNodeDownloads('p', payload, run)).toMatchObject({ ok: false });+ const legacy = { type: 'node-request', params: ['legacy'] };+ expect(await slot.withNodeDownloads('p', legacy, async (p) => p)).toBe(legacy);+ await slot.removePlugin('p');+ await expect(fs.stat(path.join(root, 'p'))).rejects.toMatchObject({ code: 'ENOENT' });+ scope = 'a';+ await fs.mkdir(outside);+ await fs.symlink(+ outside,+ path.join(root, 'p'),+ process.platform === 'win32' ? 'junction' : 'dir',+ );+ expect(await slot.handle('p', req)).toMatchObject({ ok: false });+ } finally {+ await fs.unlink(alias);+ await fs.rm(root, { recursive: true, force: true });+ await fs.rm(outside, { recursive: true, force: true });+ }+});++it('sends plugin downloads through the SSRF guard without credentials and stops for a revoked owner', async () => {+ const root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'plugin-download-test-')));+ let enabled = true;+ const ghost = {+ get enabled() {+ return enabled;+ },+ approval: {},+ manifest: { node: {}, network: { hosts: ['github.com'] } },+ } as unknown as InstalledGhost;+ const release = vi.fn(async () => {});+ const dispatchChecks: Array<() => void> = [];+ guarded.fetch.mockReset().mockImplementation(async (_url: string, _init: RequestInit, check: () => void) => {+ dispatchChecks.push(check);+ check();+ return { response: new Response('ok'), release };+ });+ const slot = new PluginDownloadSlot({+ root: (id) => path.join(root, id),+ scope: () => 'a',+ getGhost: () => ghost,+ send: () => {},+ download: async (o) => {+ const init = { method: 'GET', redirect: 'manual' as const };+ const sent = await o.request!('https://github.com/file', init);+ expect(sent).toMatchObject({ release });+ expect(guarded.fetch).toHaveBeenCalledWith(+ 'https://github.com/file',+ { ...init, credentials: 'omit' },+ expect.any(Function),+ );+ enabled = false;+ // Owner revoked between DNS resolution and dispatch: final, not a retryable NETWORK error.+ expect(() => dispatchChecks[0]()).toThrow(expect.objectContaining({ code: 'URL_POLICY' }));+ throw new Error('stop');+ },+ });+ try {+ expect(+ await slot.handle('p', {+ kind: 'start',+ id: 'g',+ url: 'https://github.com/file',+ sha256: 'a'.repeat(64),+ bytes: 2,+ }),+ ).toMatchObject({ ok: false });+ expect(guarded.fetch).toHaveBeenCalledOnce();+ } finally {+ await fs.rm(root, { recursive: true, force: true });+ }+});diff --cc apps/desktop/src/main/cindy-brain/downloadSlot.tsindex 0d09abaa76,0000000000..50f0f8bb9dmode 100644,000000..100644--- a/apps/desktop/src/main/cindy-brain/downloadSlot.ts+++ b/apps/desktop/src/main/cindy-brain/downloadSlot.ts@@@ -1,297 -1,0 +1,310 @@@+import { createHash } from 'node:crypto';+import fs from 'node:fs/promises';+import path from 'node:path';+import { ghostNetworkHostMatches, type InstalledGhost } from '../../shared/ghost.js';+import type { DownloadOptions, DownloadRequest, DownloadResult } from '../downloader/index.js';+import { DownloadError } from '../downloader/types.js';+import { guardedOutboundFetch } from '../maker-host/outbound-fetch.js';+import { PluginDownloadCache } from './downloadCache.js';++/** Verified public artifacts, in the requesting plugin's host-managed cache only. */+export interface PluginDownloadDeps {+ getGhost(id: string): InstalledGhost | null;+ root(id: string): string;+ scope(): string;+ send(id: string, event: unknown): void;+ download(options: DownloadOptions): Promise<DownloadResult>;+}+export class PluginDownloadSlot {+ private stopped = false;+ private cache = new PluginDownloadCache();+ private active = new Map<+ string,+ { controller: AbortController; promise: Promise<unknown>; fingerprint: string }+ >();+ constructor(private deps: PluginDownloadDeps) {}+ abortAll() {+ this.cache.revokeAll();+ for (const item of this.active.values()) item.controller.abort();+ }+ async stopAndWait() {+ this.stopped = true;+ this.abortAll();+ await Promise.allSettled([...this.active.values()].map((item) => item.promise));+ }+ async removePlugin(id: string, root = this.deps.root(id), scope = this.deps.scope()) {+ const work = [...this.active].filter(([key]) => {+ const parts = JSON.parse(key);+ return parts[0] === scope && parts[1] === id;+ });+ for (const [, item] of work) item.controller.abort();+ await Promise.allSettled(work.map(([, item]) => item.promise));+ try {+ const parent = await fs.realpath(path.dirname(root));+ await this.cache.removePlugin(path.join(parent, path.basename(root)));+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ }+ }+ async withNodeDownloads(+ id: string,+ payload: Record<string, unknown>,+ run: (payload: unknown) => Promise<unknown>,+ callerActive: () => boolean = () => true,+ ) {+ if (this.stopped || !callerActive())+ return { ok: false, errorCode: 'INVALID_REQUEST', message: '下载服务已停止' };+ if (payload.downloadTokens === undefined) return run(payload);+ const releases: Array<() => void> = [];+ try {+ const tokens = payload.downloadTokens;+ if (+ !tokens ||+ typeof tokens !== 'object' ||+ Array.isArray(tokens) ||+ Object.keys(tokens).length > 32+ )+ throw Error('Invalid download receipts');+ if (+ payload.params !== undefined &&+ (!payload.params ||+ typeof payload.params !== 'object' ||+ Array.isArray(payload.params) ||+ Object.hasOwn(payload.params, 'downloads'))+ )+ throw Error('Invalid download params');+ const scope = this.deps.scope(),+ ghost = this.deps.getGhost(id);+ if (!ghost?.enabled || !ghost.manifest.node) throw Error('Plugin unavailable');+ const approval = JSON.stringify(ghost.approval);+ const downloads: Record<string, string> = {};+ for (const [name, token] of Object.entries(tokens)) {+ if (+ !/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/.test(name) ||+ ['constructor', 'prototype', '__proto__'].includes(name) ||+ typeof token !== 'string'+ )+ throw Error('Invalid download receipt');+ const lease = await this.cache.acquire(token, scope, id, approval);+ releases.push(lease.release);+ downloads[name] = lease.path;+ }+ if (+ this.stopped ||+ !callerActive() ||+ this.deps.scope() !== scope ||+ !this.deps.getGhost(id)?.enabled ||+ JSON.stringify(this.deps.getGhost(id)?.approval) !== approval+ )+ throw Error('Plugin changed');+ const { downloadTokens: _tokens, ...request } = payload;+ return await run({+ ...request,+ params: { ...((payload.params as object) ?? {}), downloads },+ });+ } catch {+ return {+ ok: false,+ errorCode: 'INVALID_REQUEST',+ message: '下载凭据已失效,请重新获取文件后重试',+ };+ } finally {+ for (const release of releases) release();+ }+ }+ async handle(+ id: string,+ value: unknown,+ callerActive: () => boolean = () => true,+ ): Promise<unknown> {+ try {+ if (this.stopped) throw Error('Download service stopped');+ if (!value || typeof value !== 'object') throw Error('Invalid download request');+ const p = value as Record<string, unknown>;+ if (typeof p.id !== 'string' || !/^[\w-]{1,100}$/.test(p.id))+ throw Error('Invalid download id');+ const scope = this.deps.scope(),+ key = JSON.stringify([scope, id, p.id]);+ if (p.kind === 'cancel') {+ const item = this.active.get(key);+ item?.controller.abort();+ await item?.promise;+ return { ok: true };+ }+ if (+ p.kind !== 'start' ||+ Object.keys(p).some((k) => !['type', 'kind', 'id', 'url', 'sha256', 'bytes'].includes(k))+ )+ throw Error('Invalid download request');+ if (+ typeof p.url !== 'string' ||+ p.url.length > 8192 ||+ typeof p.sha256 !== 'string' ||+ !/^[a-f0-9]{64}$/.test(p.sha256) ||+ !Number.isSafeInteger(p.bytes) ||+ (p.bytes as number) < 1 ||+ (p.bytes as number) > 2 ** 31+ )+ throw Error('URL, SHA-256 and exact size (up to 2 GiB) are required');+ const ghost = this.deps.getGhost(id);+ if (!ghost?.enabled || !ghost.manifest.node || !ghost.manifest.network?.hosts.length)+ throw Error('Download requires node and network.hosts declarations');+ const approval = JSON.stringify(ghost.approval);+ const current = () =>+ !this.stopped &&+ callerActive() &&+ this.deps.scope() === scope &&+ this.deps.getGhost(id)?.enabled === true &&+ JSON.stringify(this.deps.getGhost(id)?.approval) === approval;+ const validateUrl = (raw: string) => {+ if (!current()) throw Error('Download owner or plugin changed');+ const u = new URL(raw);+ if (+ raw.length > 8192 ||+ /[\u0000-\u0020\u007f]/.test(raw) ||+ u.protocol !== 'https:' ||+ u.port ||+ u.username ||+ u.password ||+ !ghost.manifest.network!.hosts.some((h) => ghostNetworkHostMatches(h, u.hostname))+ )+ throw Error('Download URL is outside declared HTTPS hosts');+ };+ validateUrl(p.url);+ const isUrlAllowed = (raw: string) => {+ try {+ validateUrl(raw);+ return true;+ } catch {+ return false;+ }+ };+ const fingerprint = JSON.stringify([p.url, p.sha256, p.bytes]);+ const existing = this.active.get(key);+ if (existing) {+ if (existing.fingerprint !== fingerprint) throw Error('Download id already in use');+ return existing.promise;+ }+ if (this.active.size >= 8) throw Error('Too many active downloads');+ const controller = new AbortController();++ // Transport bytes may reset when a server ignores Range on retry. Keep++ // display progress stable without changing the bytes used for validation.++ let displayedLoaded = 0;+ const emit = (data: Record<string, unknown>) => {+ if (current())+ this.deps.send(id, {+ type: 'event',+ name: 'download-progress',+ data: { id: p.id, ...data },+ });+ };+ const promise = (async () => {+ // Distinct operations cannot share the first caller's signal or progress callback.+ const suppliedRoot = this.deps.root(id);+ // Host-selected ancestors may use aliases (e.g. /var on macOS). Resolve+ // only that trusted parent; plugin/artifact entries still reject symlinks.+ await fs.mkdir(path.dirname(suppliedRoot), { recursive: true });+ const root = path.join(+ await fs.realpath(path.dirname(suppliedRoot)),+ path.basename(suppliedRoot),+ ),+ dir = path.join(+ root,+ createHash('sha256')+ .update(JSON.stringify([scope, p.id, fingerprint]))+ .digest('hex'),+ );+ await this.cache.reserve(path.dirname(root), dir, p.bytes as number);+ try {+ if ((await fs.realpath(dir)) !== path.resolve(dir))+ throw Error('Download cache must not contain symbolic links');+ const targetPath = path.join(dir, 'artifact');+ for (const file of [targetPath, targetPath + '.part', targetPath + '.meta.json']) {+ try {+ if (!(await fs.lstat(file)).isFile()) throw Error('Unsafe download cache entry');+ } catch (e) {+ if ((e as NodeJS.ErrnoException).code !== 'ENOENT') throw e;+ }+ }+ if (!current() || controller.signal.aborted) throw Error('Download cancelled');+ emit({ phase: 'queued', loaded: 0, total: p.bytes, speedBps: 0 });+ const watch = setInterval(() => {+ if (!current()) controller.abort();+ }, 250);+ // Plugin-supplied URLs: one SSRF-guarded hop at a time (DNS pinning, HTTPS only,+ // no ambient cookies), re-checking the owner before every connection.+ const request: DownloadRequest = (url, init) =>+ guardedOutboundFetch(url, { ...init, credentials: 'omit' }, () => {+ controller.signal.throwIfAborted();+ // A revoked owner is final: do not let the downloader retry this hop.+ if (!isUrlAllowed(url))+ throw new DownloadError('URL_POLICY', 'Download URL is not allowed');+ });+ try {+ const result = await this.deps.download({+ url: p.url as string,+ targetPath,+ sha256: p.sha256 as string,+ expectedSize: p.bytes as number,+ maxBytes: p.bytes as number,++ timeout: { totalMs: 2 * 60 * 60 * 1000 },+ isUrlAllowed,+ request,+ signal: controller.signal,+ logger: { debug() {}, info() {}, warn() {}, error() {} },- onProgress: (e) => emit({ phase: 'downloading', ...e }),++ onProgress: (e) => {++ displayedLoaded = Math.max(displayedLoaded, Math.min(e.loaded, p.bytes as number));++ emit({++ phase: 'downloading',++ ...e,++ loaded: displayedLoaded,++ total: p.bytes,++ percent: (displayedLoaded / (p.bytes as number)) * 100,++ });++ },+ onVerifying: () =>+ emit({ phase: 'verifying', loaded: p.bytes, total: p.bytes, speedBps: 0 }),+ onRetry: (e) => emit({ phase: 'retrying', attempt: e.attempt, delayMs: e.delayMs }),+ });+ if (!current() || controller.signal.aborted) throw Error('Download cancelled');+ if (result.size !== p.bytes) throw Error('Downloaded size mismatch');+ const token = await this.cache.issue(dir, scope, id, approval);+ if (!current() || controller.signal.aborted) throw Error('Plugin changed');+ emit({+ phase: 'completed',+ loaded: result.size,+ total: result.size,+ speedBps: 0,+ fromCache: result.fromCache,+ });+ return {+ ok: true,+ token,+ bytes: result.size,+ sha256: result.sha256,+ fromCache: result.fromCache,+ };+ } finally {+ clearInterval(watch);+ }+ } finally {+ this.cache.release(dir);+ }+ })()+ .catch(() => {+ emit({ phase: controller.signal.aborted ? 'cancelled' : 'failed' });+ return {+ ok: false,+ message: controller.signal.aborted+ ? '下载已取消'+ : '下载失败,请重试(网络、权限或文件校验未通过)',+ };+ })+ .finally(() => this.active.delete(key));+ this.active.set(key, { controller, promise, fingerprint });+ return promise;+ } catch (e) {+ return { ok: false, message: (e as Error).message };+ }+ }+}diff --cc apps/desktop/src/main/cindy-brain/forge.tsindex 23011fd293,215bc6ea9f..5c7a3f3649--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@@ -3954,26 -3961,6 +3964,26 @@@ Node 请求及其子进程一并结束�或不启用开关都保持既有独立 RPC 生命周期,不自动弹授权卡、不回收后台进程;设置页等无 tool-call 的入口不能伪造或复用调用编号。+#### 下载公开大文件与进度++声明 node 和 network.hosts 后可用 cindy.downloads.start({id,url,sha256,bytes});+只接受声明的 HTTPS 主机(每次重定向复核),不发送 Cookie、凭证或自定义请求头。- SHA-256 和精确字节数必填,单文件最多 2 GiB。返回 {ok:true,token,bytes,sha256,fromCache},++SHA-256 和精确字节数必填,单文件最多 2 GiB。下载从获得队列槽位起最多 2 小时(含重试,不计排队),不改变 Node 调用期限。返回 {ok:true,token,bytes,sha256,fromCache},+没有宿主路径。取消用 cindy.downloads.cancel({id})。+订阅 onHostMessage 的 download-progress 事件:data 含 id、phase、loaded、total、speedBps;+phase 为 queued/downloading/verifying/retrying/completed/failed/cancelled,retrying 另含 attempt、delayMs。+无 loaded/total 时显示不确定进度,下载成功不等于解包成功。++将 token 放入 cindy.node.request 的 downloadTokens,例如 {archive: token};params 必须是对象且+不能自带 downloads。Host 校验同账号、同插件、批准身份与文件身份后,仅向 Node 注入+params.downloads.archive。Node 在本次 RPC 结束前读取或复制文件,不得把宿主路径回传面板或写进日志。+旧请求不带 downloadTokens 时保持原有 params 语义。旧宿主无 downloads 时提示升级。++下载队列与宿主更新隔离,传输逐块写盘并支持校验、重试与续传。每账号所有插件的缓存+合计最多 4 GiB(含在途预留及每项 64 KiB 管理空间);不淘汰正在下载或被 Node RPC 借用的文件,满额且无可回收项时失败。+缓存可被回收,重启后 token 失效,重新 start 可复用经校验的文件。卸载插件回收其下载缓存;+停用、账号切换或批准身份改变会拒绝旧凭据,不增加用户授权步骤。+#### Node Worker 的持久化凭证绑定本地 IMAP/SMTP 等协议确实需要 Worker 使用凭证明文时,在diff --cc apps/desktop/src/main/cindy-brain/index.tsindex b19b1eeecd,dcc0cf0477..8db98dd3c4--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@@ -1,5 -1,6 +1,8 @@@+ import { getModelVisibilityOverride, waitForModelVisibilityMirror } from '../maker-host/model-visibility-mirror.js';+ import { projectGhostAgentModels } from './ghostAgentModels.js';+ import { getDesktopProviderService } from '../maker-host/createDesktopProviderService.js';+import { PluginDownloadSlot } from './downloadSlot.js';+import { createDownloader } from '../downloader/index.js';import { registerGhostCardRemoteProvider, persistGhostCardWithRemoteChange } from './cardRemoteResource.js';import { openDeviceAuthorizationCard, openPluginAuthorizationCard } from '../plugin-oauth/deviceCard.js';import { t as authorizationText } from '../i18n.js';diff --cc apps/desktop/src/main/downloader/index.tsindex cea82c716c,8bc8772b98..2adf77088b--- a/apps/desktop/src/main/downloader/index.ts+++ b/apps/desktop/src/main/downloader/index.ts@@@ -8,7 -8,7 +8,8 @@@** Contract invariants (re-stated; full version in tech spec):* 1. download() resolves DownloadResult or rejects DownloadError, no other types.- * 2. Progress describes the current attempt (a fresh retry may restart at zero).- * 2. onProgress.loaded is monotonic non-decreasing within a single download.++ * 2. onProgress reports raw transport bytes; callers normalize display progress++ * across retries (a server may reject resume and restart from zero).* 3. resolve implies SHA256 already verified — no need to re-check.*/diff --cc apps/desktop/src/preload/preload.tsindex 99ae166aa0,eae807a9aa..69ed20eb88--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@@ -1,16 -1,9 +1,18 @@@+ import type { CompanionImportApi, CompanionImportSelection } from '@cindy/maker-shared/companion-import';+ import { TASK_MIGRATION_LOCAL_CHANNEL } from '@cindy/device-link';import type { WorktreeRecycleAction, WorktreeRecycleStatus } from '../shared/worktreeRecycle';-import { FAVORITE_HOST_READY, FAVORITE_HOST_REQUEST, FAVORITE_HOST_REPLY, FAVORITE_HOST_CHANGED, type ModelFavoritesHostApi } from '../shared/modelFavoritesSync';+import {+ FAVORITE_HOST_READY,+ FAVORITE_HOST_REQUEST,+ FAVORITE_HOST_REPLY,+ FAVORITE_HOST_CHANGED,+ type ModelFavoritesHostApi,+} from '../shared/modelFavoritesSync';import { invokeOpenPath } from './openPath';-import { COPY_PNG_TO_CLIPBOARD_CHANNEL, type CopyPngToClipboardParams } from '../shared/pngClipboard';+import {+ COPY_PNG_TO_CLIPBOARD_CHANNEL,+ type CopyPngToClipboardParams,+} from '../shared/pngClipboard';import type { ByokStatus } from '../shared/modelAccess.js';import type { LocalPluginOauthRequest, LocalPluginSecretRequest } from '../shared/pluginOauth';import { REMOTE_VIEWER } from '../shared/remoteDesktopViewer';@@@ -1047,23 -1031,23 +1050,29 @@@ type CindyMediaPreferenceKind =contextBridge.exposeInMainWorld('electronAPI', {modelFavoritesHost: {ready: () => ipcRenderer.send(FAVORITE_HOST_READY),- changed: stamp => ipcRenderer.send(FAVORITE_HOST_CHANGED, stamp),- reply: reply => ipcRenderer.send(FAVORITE_HOST_REPLY, reply),- onRequest: listener => {- const receive = (_event: Electron.IpcRendererEvent, request: Parameters<typeof listener>[0]) => listener(request);+ changed: (stamp) => ipcRenderer.send(FAVORITE_HOST_CHANGED, stamp),+ reply: (reply) => ipcRenderer.send(FAVORITE_HOST_REPLY, reply),+ onRequest: (listener) => {+ const receive = (+ _event: Electron.IpcRendererEvent,+ request: Parameters<typeof listener>[0],+ ) => listener(request);ipcRenderer.on(FAVORITE_HOST_REQUEST, receive);- return () => { ipcRenderer.removeListener(FAVORITE_HOST_REQUEST, receive); };+ return () => {+ ipcRenderer.removeListener(FAVORITE_HOST_REQUEST, receive);+ };},} satisfies ModelFavoritesHostApi,+ companionImport: {+ sources: () => ipcRenderer.invoke('companion-import', 'sources'),+ preview: (sourceId: string) => ipcRenderer.invoke('companion-import', 'preview', sourceId),+ start: (selection: CompanionImportSelection) => ipcRenderer.invoke('companion-import', 'start', selection),+ status: (requestId: string) => ipcRenderer.invoke('companion-import', 'status', requestId),+ } satisfies CompanionImportApi,routines: {list: (botId: string) => ipcRenderer.invoke('routines:list', botId),- save: (botId: string, input: RoutineInput, id?: string) => ipcRenderer.invoke('routines:save', botId, input, id),+ save: (botId: string, input: RoutineInput, id?: string) =>+ ipcRenderer.invoke('routines:save', botId, input, id),remove: (botId: string, id: string) => ipcRenderer.invoke('routines:remove', botId, id),runNow: (botId: string, id: string) => ipcRenderer.invoke('routines:run-now', botId, id),history: (botId: string, id: string) => ipcRenderer.invoke('routines:history', botId, id),diff --cc docs/dev-rules/plugin-download-api.mdindex 85251a6b53,0000000000..4903da9dc1mode 100644,000000..100644--- a/docs/dev-rules/plugin-download-api.md+++ b/docs/dev-rules/plugin-download-api.md@@@ -1,31 -1,0 +1,36 @@@+# 插件文件下载接口++逻辑页使用 `cindy.downloads.start({id,url,sha256,bytes})`,取消使用+`cindy.downloads.cancel({id})`。返回结构为+`{ok:true,token,bytes,sha256,fromCache}` 或 `{ok:false,message}`。++插件必须声明 node 与 network.hosts;仅允许已声明 HTTPS 主机,重定向每跳重新检查。+本接口用于匿名公开文件,不携带 Cookie、账号凭证或自定义请求头;带授权请求继续使用 fetch 槽。+SHA-256 与精确字节数必填,单文件最大 2 GiB。目标由宿主管理,不接受本机目标路径。+面板不获得宿主路径。通过 `node.request({downloadTokens:{archive:token},params:{...}})`+交接给同插件 Node,Host 校验账号、插件、批准身份和文件身份后注入 `params.downloads.archive`。+携带凭据时 params 必须为对象且不得自带 downloads;旧请求不受影响。+路径仅在本次 RPC 生命周期内有效,Node 须在返回前完成读取或复制,不得回传或记录路径。+缓存由账号、插件、请求身份隔离;id 相同且内容相同可复用经校验的文件。+每账号总预算 4 GiB(含在途预留及每项 64 KiB 管理空间),按最近使用回收;下载中和 Node 借用中的文件不淘汰。+缓存满且没有可回收空间时失败。卸载回收该插件缓存;重启后凭据失效,可重新 start 取凭据。+下载使用独立队列(`createDownloader()`),不占用宿主更新队列;传输复用统一下载器的逐块写盘+(写完一块才拉下一块)、重试与续传。插件提供的 URL 通过下载器的 `request` 注入点走+`guardedOutboundFetch`:单跳、DNS 固定、仅 HTTPS、不带 Cookie,每次连接前复核调用方与声明主机;+调用方失效属于终局拒绝(`URL_POLICY`),不按网络错误重试。++通过 onHostMessage 订阅:+`{type:'event',name:'download-progress',data:{id,phase,loaded,total,speedBps}}`。+phase 为 queued/downloading/verifying/retrying/completed/failed/cancelled。+retrying 附带 attempt、delayMs,completed 附带 fromCache。+校验、重试等阶段不保证具有 loaded/total;界面应使用不确定进度,不能伪造百分比。+下载完成仅表示文件校验完成,插件自己的解包/内容验证应另行展示。+++单次下载从获得队列槽位起最多运行 2 小时,包含传输和重试,不计排队等待。++超时后释放下载槽位并返回失败;此限制不改变 Node 调用期限。++下载中的 loaded/percent 为本次请求的显示高水位,续传重试从零开始时不倒退;++实际文件长度和 SHA-256 仍以真实传输结果校验,新请求从零开始。+++账号切换、插件批准身份改变或调用逻辑页销毁后中止下载,不向新账号发送进度。+旧宿主不存在 downloads 对象时,应提示升级;不能假装已接入进度。+现有 fetch、Node、Library 接口不变,存量插件无须迁移。