Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
refactor(plugin): 解耦目标查询解析与投递并移除宿主选择器
liugaoweifa8ecb9adce2
diff --cc apps/desktop/src/main/cindy-brain/__tests__/pluginTargetSlot.test.tsindex 51c3da9c1f,0000000000..fd0b4e73e0mode 100644,000000..100644--- a/apps/desktop/src/main/cindy-brain/__tests__/pluginTargetSlot.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/pluginTargetSlot.test.ts@@@ -1,200 -1,0 +1,213 @@@- import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';- import type { PluginTargetPickerPush } from '../../../shared/pluginTargets.js';++import { beforeEach, describe, expect, it, vi } from 'vitest';+- const state = vi.hoisted(() => ({ bindings: {} as Record<string, unknown> }));++const state = vi.hoisted(() => ({ receipts: {} as Record<string, unknown> }));+vi.mock('../../appSessionState.js', () => ({+ activeOwnerScopeKey: () => 'owner',+ ownerScopedUserDataPath: () => '/not-written.json',+ getActiveDataOwnerPushStamp: () => ({ ownerGeneration: 1 }),+}));+vi.mock('../../maker-host/logger-adapter.js', () => ({+ desktopMakerLogger: { child: () => ({}) },+}));+vi.mock('../../maker-host/override-settings-file.js', () => ({+ createOverrideSettingsFile: () => ({+ invalidateIfChanged: () => {},+ read: () => state,+ updateAtomic: async (update: (input: { value: typeof state }) => Partial<typeof state>) =>+ Object.assign(state, update({ value: state })),+ }),+}));+import { PluginTargetSlot, type PluginTargetAdapter } from '../pluginTargetSlot.js';+- describe('user-selected plugin destinations', () => {- beforeEach(() => {- vi.useFakeTimers();- state.bindings = {};- });- afterEach(() => {- vi.useRealTimers();- });++function deferred<T>() {++ let resolve!: (value: T) => void;++ const promise = new Promise<T>((done) => { resolve = done; });++ return { promise, resolve };++}++++describe('plugin target queries and delivery', () => {++ beforeEach(() => { state.receipts = {}; });+ function fixture() {- let push: PluginTargetPickerPush | null = null;- const slot = new PluginTargetSlot({- name: () => 'Example plugin',- revision: () => 'approved-install',- open: (value) => {- push = value;- return { senderId: 7, close: vi.fn() };- },- });++ const slot = new PluginTargetSlot();+ const send = vi.fn<PluginTargetAdapter['send']>(async () => 'queue');- const create = vi.fn(async () => {});- const withdraw = vi.fn(async () => {});- slot.adapter = {- candidates: async () => [{ id: 'chosen', label: 'Chosen task', detail: '' }],- session: async () => 'chosen',- send,- create,- withdraw,- };++ const create = vi.fn<PluginTargetAdapter['create']>(async () => {});++ const withdraw = vi.fn<PluginTargetAdapter['withdraw']>(async () => {});++ const candidates = vi.fn<PluginTargetAdapter['candidates']>(async () => [++ { id: 'chosen', label: 'Chosen target', detail: '/workspace/example' },++ ]);++ slot.adapter = { candidates, session: async () => 'chosen', send, create, withdraw };+ const guard = vi.fn();+ const call = (payload: unknown, plugin = 'plugin') => slot.handle(plugin, payload, guard);- const pick = async (persistent = false, targetKind = 'task') => {- const result = call({ kind: 'pick', requestKey: 'select', targetKind, persistent });- await vi.advanceTimersByTimeAsync(0);- const request = push!;- expect(slot.resolve(request.requestId, 99, 'chosen')).toBe(false);- expect(slot.resolve(request.requestId, 7, 'chosen')).toBe(true);- return (await result) as { bindingId: string };- };- return { slot, call, pick, send, create, withdraw, getPush: () => push };++ const request = { kind: 'send', target: { kind: 'task', id: 'chosen' },++ requestKey: 'send', text: 'context' };++ return { slot, call, request, send, create, withdraw, candidates, guard };+ }- // Production entry: PluginTargetSlot.handle. Protects targets.send's delivery/default- // and idempotency contract; existing ownership cases do not cover this field. In-memory unit tier.++ // Production entry: PluginTargetSlot.handle, called by the authorized logic-page pipe.++ // Contract: query/resolve without UI, explicit target delivery, durable deduplication and cancellation.++ // In-memory unit tier; storage and runner adapters are mocked, not the public entry.++ it.each(['project', 'task', 'bot'])('queries and resolves %s metadata without changing delivery state', async (kind) => {++ const f = fixture();++ const target = { kind, id: 'chosen' };++ const view = { ...target, label: 'Chosen target', detail: '/workspace/example' };++ expect(await f.call({ kind: 'list', targetKind: kind })).toEqual({ targets: [view] });++ expect(await f.call({ kind: 'resolve', target })).toEqual(view);++ expect(state.receipts).toEqual({});++ expect(f.create).not.toHaveBeenCalled();++ expect(f.send).not.toHaveBeenCalled();++ });++ it('rejects a missing fixed target instead of selecting a substitute', async () => {++ const f = fixture();++ f.candidates.mockResolvedValue([{ id: 'other', label: 'Other target', detail: '' }]);++ await expect(f.call({ kind: 'resolve', target: f.request.target }))++ .rejects.toMatchObject({ code: 'TARGET_UNAVAILABLE' });++ await expect(f.call(f.request)).rejects.toMatchObject({ code: 'TARGET_UNAVAILABLE' });++ expect(f.send).not.toHaveBeenCalled();++ });++ it('creates in the specified project and passes its selected route', async () => {++ const f = fixture();++ const route = { agentKind: 'codex', providerId: 'provider', model: 'model', effort: '', fastMode: false };++ const result = await f.call({ ...f.request, target: { kind: 'project', id: 'chosen' }, route, title: 'New task' });++ expect(result).toMatchObject({ accepted: true, delivery: 'queue' });++ expect(f.create).toHaveBeenCalledWith('plugin', 'chosen', expect.any(String), 'New task', route, expect.any(Function));++ expect(f.send.mock.calls[0]?.[1]).toBe(f.create.mock.calls[0]?.[2]);++ });+ it('carries screenshot bytes once and rejects a changed attachment on the same receipt', async () => {- const f = fixture(), picked = await f.pick();++ const f = fixture();+ const base64 = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]).toString('base64');- const request = { kind: 'send', bindingId: picked.bindingId, requestKey: 'image', text: 'context',- attachments: [{ base64, name: 'window.png' }] };- await f.call(request);- await f.call(structuredClone(request));++ const request = { ...f.request, attachments: [{ base64, name: 'window.png' }] };++ await Promise.all([f.call(request), f.call(structuredClone(request))]);+ expect(f.send).toHaveBeenCalledOnce();+ expect(f.send.mock.calls[0]?.[7]?.[0]).toMatchObject({ mimeType: 'image/png', name: 'window.png' });+ await expect(f.call({ ...request, attachments: [{ base64, name: 'other.png' }] }))+ .rejects.toMatchObject({ code: 'REQUEST_KEY_CONFLICT' });++ expect(JSON.stringify(state)).not.toContain(base64);++ expect(JSON.stringify(state)).not.toContain('window.png');+ });+ it('rejects a forged media URL before creating or sending a target task', async () => {- const f = fixture(), picked = await f.pick(false, 'project');- await expect(f.call({ kind: 'send', bindingId: picked.bindingId, requestKey: 'image', text: 'context',- attachments: [{ url: 'cindy-media://blobs/foreign.png' }] })).rejects.toMatchObject({ code: 'INVALID_ATTACHMENTS' });++ const f = fixture();++ await expect(f.call({ ...f.request, target: { kind: 'project', id: 'chosen' },++ attachments: [{ url: 'cindy-media://blobs/foreign.png' }] }))++ .rejects.toMatchObject({ code: 'INVALID_ATTACHMENTS' });+ expect(f.create).not.toHaveBeenCalled();+ expect(f.send).not.toHaveBeenCalled();+ });+ it.each([undefined, 'queue', 'steer'] as const)('preserves requested delivery %s and reports actual delivery', async (delivery) => {- const f = fixture(), picked = await f.pick();- const request = { kind: 'send', bindingId: picked.bindingId, requestKey: 'send', text: 'context', delivery };++ const f = fixture();++ const request = { ...f.request, delivery };+ expect(await f.call(request)).toMatchObject({ accepted: true, delivery: 'queue' });+ expect(f.send.mock.calls[0]?.[6]).toBe(delivery ?? 'queue');- // A mode change cannot reuse an accepted request to inject the same content twice.+ await expect(f.call({ ...request, delivery: delivery === 'steer' ? 'queue' : 'steer' }))+ .rejects.toMatchObject({ code: 'REQUEST_KEY_CONFLICT' });+ expect(f.send).toHaveBeenCalledOnce();+ });- it('reports successful steering and treats omitted delivery as an explicit queue retry', async () => {- const f = fixture(), picked = await f.pick();++ it('reports steering and deduplicates an explicit queue retry', async () => {++ const f = fixture();+ f.send.mockResolvedValueOnce('steer');- expect(await f.call({ kind: 'send', bindingId: picked.bindingId, requestKey: 'steer', text: 'context', delivery: 'steer' }))++ expect(await f.call({ ...f.request, requestKey: 'steer', delivery: 'steer' }))+ .toMatchObject({ accepted: true, delivery: 'steer' });- const other = await f.pick();- const request = { kind: 'send', bindingId: other.bindingId, requestKey: 'queue', text: 'context' };- await f.call(request);- expect(await f.call({ ...request, delivery: 'queue' })).toMatchObject({ delivery: 'queue' });++ await f.call(f.request);++ expect(await f.call({ ...f.request, delivery: 'queue' })).toMatchObject({ delivery: 'queue' });+ expect(f.send).toHaveBeenCalledTimes(2);+ });- it.each(['invalid', 'project-steer'])('rejects %s before any target mutation', async (mode) => {- const f = fixture(), picked = await f.pick(false, mode === 'project-steer' ? 'project' : 'task');- await expect(f.call({ kind: 'send', bindingId: picked.bindingId, requestKey: 'send', text: 'context',- delivery: mode === 'project-steer' ? 'steer' : 'interrupt' }))- .rejects.toMatchObject({ code: 'INVALID_PARAMS' });++ it.each([++ { delivery: 'interrupt' },++ { target: { kind: 'project', id: 'chosen' }, delivery: 'steer' },++ { target: { kind: 'task', id: 'chosen' }, route: {} },++ { target: { kind: 'remote', id: 'chosen' } },++ ])('rejects invalid delivery parameters %j before mutation', async (invalid) => {++ const f = fixture();++ await expect(f.call({ ...f.request, ...invalid })).rejects.toMatchObject({ code: 'INVALID_PARAMS' });+ expect(f.send).not.toHaveBeenCalled();+ expect(f.create).not.toHaveBeenCalled();+ });- it('rejects a plugin-supplied task ID and does not expose a candidate list to the plugin', async () => {++ it('replays a completed receipt after Host restart without redelivery and isolates plugin keys', async () => {+ const f = fixture();- await expect(- f.call({ kind: 'send', bindingId: 'chosen', requestKey: 'a', text: 'context' }),- ).rejects.toMatchObject({ code: 'TARGET_UNAVAILABLE' });- const picked = await f.pick();- expect(picked).not.toHaveProperty('candidates');- expect(picked).not.toHaveProperty('targetId');++ const result = await f.call(f.request);++ const restarted = new PluginTargetSlot();++ restarted.adapter = f.slot.adapter;++ expect(await restarted.handle('plugin', f.request, f.guard)).toEqual(result);++ expect(f.send).toHaveBeenCalledOnce();++ await f.call(f.request, 'another-plugin');++ expect(f.send).toHaveBeenCalledTimes(2);++ await expect(f.call({ ...f.request, text: 'different' })).rejects.toMatchObject({ code: 'REQUEST_KEY_CONFLICT' });++ });++ it('does not retry an interrupted project creation after Host restart', async () => {++ const f = fixture();++ f.create.mockRejectedValueOnce(new Error('interrupted'));++ const request = { ...f.request, target: { kind: 'project', id: 'chosen' } };++ await expect(f.call(request)).rejects.toThrow('interrupted');++ const restarted = new PluginTargetSlot();++ restarted.adapter = f.slot.adapter;++ await expect(restarted.handle('plugin', request, f.guard)).rejects.toMatchObject({ code: 'DELIVERY_UNCERTAIN' });++ expect(f.create).toHaveBeenCalledOnce();+ expect(f.send).not.toHaveBeenCalled();+ });- it('cannot turn a one-time selection into a persistent binding or use it from another plugin', async () => {- const f = fixture(),- picked = await f.pick();- await expect(f.call({ kind: 'get', bindingId: picked.bindingId })).rejects.toMatchObject({- code: 'TARGET_UNAVAILABLE',- });- await expect(- f.call(- { kind: 'send', bindingId: picked.bindingId, requestKey: 'a', text: 'context' },- 'another',- ),- ).rejects.toMatchObject({ code: 'TARGET_UNAVAILABLE' });- });- it('requires fixed bindings to be resolved and rejects replay with a new key or changed text', async () => {- const f = fixture(),- saved = await f.pick(true);- await expect(- f.call({ kind: 'send', bindingId: saved.bindingId, requestKey: 'a', text: 'context' }),- ).rejects.toMatchObject({ code: 'TARGET_UNAVAILABLE' });- const handle = (await f.call({ kind: 'get', bindingId: saved.bindingId })) as {- bindingId: string;- };- const request = { kind: 'send', bindingId: handle.bindingId, requestKey: 'a', text: 'context' };- await Promise.all([f.call(request), f.call(request)]);- expect(f.send).toHaveBeenCalledTimes(1);- await expect(f.call({ ...request, requestKey: 'b', text: 'changed' })).rejects.toMatchObject({- code: 'DELIVERY_UNCERTAIN',- });- expect(f.create).not.toHaveBeenCalled();++ it('rejects late sends even when cancelled before send or Host restart', async () => {++ const f = fixture();++ await f.call({ kind: 'cancel', requestKey: f.request.requestKey });++ const restarted = new PluginTargetSlot();++ restarted.adapter = f.slot.adapter;++ await expect(restarted.handle('plugin', f.request, f.guard)).rejects.toMatchObject({ code: 'SUPERSEDED' });++ expect(f.send).not.toHaveBeenCalled();+ });- it('cancels a picker and rejects its late selection without delivering anything', async () => {++ it('cancels a send waiting for target discovery without creating or delivering', async () => {+ const f = fixture();- const selection = f.call({ kind: 'pick', requestKey: 'old', targetKind: 'task' });- const settled = expect(selection).rejects.toMatchObject({ code: 'SUPERSEDED' });- await vi.advanceTimersByTimeAsync(0);- const requestId = f.getPush()!.requestId;- await f.call({ kind: 'cancel', requestKey: 'old' });- expect(f.slot.resolve(requestId, 7, 'chosen')).toBe(false);- await settled;++ const waiting = deferred<Array<{ id: string; label: string; detail: string }>>();++ f.candidates.mockReturnValueOnce(waiting.promise);++ const send = f.call(f.request);++ const rejected = expect(send).rejects.toMatchObject({ code: 'SUPERSEDED' });++ await f.call({ kind: 'cancel', requestKey: f.request.requestKey });++ waiting.resolve([{ id: 'chosen', label: 'Chosen target', detail: '' }]);++ await rejected;+ expect(f.send).not.toHaveBeenCalled();++ expect(f.create).not.toHaveBeenCalled();+ });- it('fails closed when a fixed target disappears and does not choose a substitute', async () => {- const f = fixture(),- saved = await f.pick(true);- f.slot.adapter!.candidates = async () => [- { id: 'different', label: 'Another task', detail: '' },- ];- await expect(f.call({ kind: 'get', bindingId: saved.bindingId })).rejects.toMatchObject({- code: 'TARGET_UNAVAILABLE',++ it('withdraws only the input clientId reserved by this plugin request', async () => {++ const f = fixture();++ await f.call(f.request);++ const input = f.send.mock.calls[0]!;++ await f.call({ kind: 'cancel', requestKey: f.request.requestKey });++ expect(f.withdraw).toHaveBeenCalledWith(input[1], input[2], f.guard);++ await expect(f.call(f.request)).rejects.toMatchObject({ code: 'SUPERSEDED' });++ });++ it('keeps cancellation effective when the provider acknowledges after cancellation', async () => {++ const f = fixture();++ const entered = deferred<void>();++ const release = deferred<void>();++ f.send.mockImplementationOnce(async () => {++ entered.resolve();++ await release.promise;++ return 'queue';+ });++ const send = f.call(f.request);++ const rejected = expect(send).rejects.toMatchObject({ code: 'SUPERSEDED' });++ await entered.promise;++ await f.call({ kind: 'cancel', requestKey: f.request.requestKey });++ release.resolve();++ await rejected;++ const restarted = new PluginTargetSlot();++ restarted.adapter = f.slot.adapter;++ await expect(restarted.handle('plugin', f.request, f.guard)).rejects.toMatchObject({ code: 'SUPERSEDED' });++ expect(f.send).toHaveBeenCalledOnce();++ const input = f.send.mock.calls[0]!;++ expect(f.withdraw.mock.calls.every(([taskId, clientId]) => taskId === input[1] && clientId === input[2])).toBe(true);++ });++ it('rechecks authorization after asynchronous discovery', async () => {++ const f = fixture();++ f.candidates.mockImplementationOnce(async () => {++ f.guard.mockImplementation(() => { throw Object.assign(new Error('revoked'), { code: 'PERMISSION_DENIED' }); });++ return [{ id: 'chosen', label: 'Chosen target', detail: '' }];++ });++ await expect(f.call(f.request)).rejects.toMatchObject({ code: 'PERMISSION_DENIED' });+ expect(f.send).not.toHaveBeenCalled();+ expect(f.create).not.toHaveBeenCalled();++ expect(state.receipts).toEqual({});+ });- it('does not reopen an older picker after a slow candidate query finishes', async () => {- const f = fixture();- let releaseOld!: (value: Array<{ id: string; label: string; detail: string }>) => void;- f.slot.adapter!.candidates = vi- .fn()- .mockImplementationOnce(- () =>- new Promise((resolve) => {- releaseOld = resolve;- }),- )- .mockResolvedValue([{ id: 'chosen', label: 'Chosen task', detail: '' }]);- const old = f.call({ kind: 'pick', requestKey: 'slow', targetKind: 'task' });- const rejected = expect(old).rejects.toMatchObject({ code: 'SUPERSEDED' });- const current = f.call({ kind: 'pick', requestKey: 'current', targetKind: 'task' });- await vi.advanceTimersByTimeAsync(0);- const requestId = f.getPush()!.requestId;- releaseOld([{ id: 'chosen', label: 'Chosen task', detail: '' }]);- await rejected;- expect(f.getPush()!.requestId).toBe(requestId);- f.slot.resolve(requestId, 7, 'chosen');- await current;++ it('rechecks the canonical companion session immediately before delivery', async () => {++ const f = fixture();++ f.slot.adapter!.session = vi.fn().mockResolvedValueOnce('old-session').mockResolvedValue('new-session');++ await expect(f.call({ ...f.request, target: { kind: 'bot', id: 'chosen' } }))++ .rejects.toMatchObject({ code: 'TARGET_UNAVAILABLE' });+ expect(f.send).not.toHaveBeenCalled();+ });+});diff --cc apps/desktop/src/main/cindy-brain/forge.tsindex eec364eb35,82de4f26f8..a853b67d60--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@@ -3995,18 -4035,7 +4035,17 @@@ const r = await cindy.agent.requestSche用户拒绝或确认界面不可用时返回 \`PERMISSION_DENIED\`,不影响插件其它功能;不得自动循环重试确认。面板通过既有逻辑页通道调用,不获得新的 preload 或内部 IPC 权限。- 用户要把内容交给自己选定的项目、已有任务或伙伴时,使用独立的 \`cindy.targets\`(仅本机 Desktop 逻辑页,同样需要已批准的 \`agent.tasks\`)。先检查 \`typeof cindy.targets?.pick === 'function'\`;旧客户端没有此入口,不调用私有 IPC 或自动改投别处。-先调用 \`capabilities()\` 获取实际支持操作。当前仅支持本插件创建的本机普通任务:++插件需要向项目、已有任务或伙伴投递内容时,使用独立的 \`cindy.targets\`(仅本机 Desktop 逻辑页,同样需要已批准的 \`agent.tasks\`)。先检查 \`typeof cindy.targets?.list === 'function'\`;旧客户端没有此入口,不调用私有 IPC 或自动改投别处。Host 只提供查询、解析和投递;选择 UI、临时选择及固定目标配置由插件自己维护。+- - \`pick({requestKey,targetKind:'project'|'task'|'bot',persistent?:boolean})\`:由 Cindy 展示目标列表、搜索和插件身份。用户取消返回 \`{cancelled:true}\`;成功返回 \`{bindingId,kind,label}\`,不向插件返回整份候选或消息历史。- - 默认只用于本次:返回的 bindingId 是 5 分钟有效、只可用于一次投递的句柄。- - \`persistent:true\` 明确让用户绑定今后可直接投递的固定目标。把 bindingId 存入插件配置;该 ID 不能直接 send。每次触发先 \`get({bindingId})\` 复核目标并换取本次临时句柄,再 send;临时选择不改写固定绑定。- - \`send({bindingId,requestKey,text,title?,route?,delivery?,attachments?})\`:仅接受本次临时句柄。project 在选定目录中新建普通任务,可传统一目录的 route;task/bot 沿用接收方模型和权限,不接受 route。\`delivery\` 可选 \`queue | steer\`,缺省 queue;project 不接受 steer。steer 尝试同轮注入,不停止当前轮,空闲或插话暂不可用时入队。返回 \`{taskId,accepted:true,delivery:"queue"|"steer"}\` 表示实际接受路径,不表示执行完成。筛查拒绝返回 DELIVERY_REJECTED,不入队重试;ACK 未知返回 DELIVERY_UNCERTAIN,宿主保留保护性暂停队列,不能重发。不开放读取任意任务历史或改模。++- \`list({targetKind:'project'|'task'|'bot'})\`:返回 \`{targets:[{kind,id,label,detail}]}\`,只含本机可用目标的名称和目录/说明,不含消息历史。插件可自行搜索和展示列表,最近活动只用于排序。++- \`resolve({target:{kind,id}})\`:复核已保存或本次选择的目标,返回最新 \`{kind,id,label,detail}\`。只查询,不创建任务、不打开 UI、不保存绑定;固定目标失效返回 TARGET_UNAVAILABLE,不自动替换。插件可将 \`{kind,id}\` 存入自己的配置。project 的 id 是 Cindy 已有项目目录,task/bot 的 id 是任务/伙伴标识。++- \`send({target:{kind,id},requestKey,text,title?,route?,delivery?,attachments?})\`:直接指定目标,Host 当次复核。project 在目录中新建普通任务,可传统一模型目录的 route;task/bot 沿用接收方模型、权限、目录,不接受 route。\`delivery\` 为 \`queue | steer\`,缺省 queue;project 不接受 steer。steer 尝试同轮注入,不停止当前轮,空闲或插话暂不可用时入队。返回 \`{taskId,accepted:true,delivery:"queue"|"steer"}\` 表示实际接受路径,不表示执行完成。筛查拒绝返回 DELIVERY_REJECTED,不入队重试;ACK 未知返回 DELIVERY_UNCERTAIN,不得换键重发。不开放读取任意任务历史或改模。++- 同一次 send 重试沿用相同 requestKey、target、内容和 delivery(缺省与 queue 等价);同键参数变化返回 REQUEST_KEY_CONFLICT。Host 在执行前持久保留投递回执,重启后已接受的请求返回原结果,未确定结果的请求返回 DELIVERY_UNCERTAIN,不再次创建或投递。回执不保存正文或附件字节。不要通过更换 requestKey 绕过未知结果,应先让用户在 Cindy 检查。++- \`cancel({requestKey})\`:使本次请求及迟到的发送失效,仅撤回本插件该请求尚未执行的输入;不会停止接收方其他输入,也不保证撤销已经开始的工作。新操作使用新的 requestKey。+- \`tasks.send\` 和 \`targets.send\` 均支持可选 \`attachments:[{base64,name?}]\`:只接收插件提供的图片字节,不接受本机路径、URL、媒体 URI 或自报 MIME。Host 检测 PNG/JPEG/WebP,最多 4 张、合计 20 MiB。先检查 \`tasks.capabilities().messageAttachments.kinds\` 包含 image;旧客户端不支持时停止,不静默丢图或改投临时路径。截图进既有 cindy-media,作为消息附件展示并进入模型输入;不需要额外声明 media.deposit。附件内容及名称参与幂等签名,更换附件不能复用同键。- - 同一次 send 重试沿用相同 requestKey、句柄、内容和 delivery(缺省与 queue 等价);主机运行期间共享原投递结果。句柄用后不能换键再发;Host 重启后旧临时句柄失效。结果未知不得重新 get/pick 绕过后重发,应先让用户在 Cindy 检查。- - \`cancel({requestKey})\`:关闭该请求的选择器、使迟到选择失效,并仅撤回本插件尚未执行的输入;不会停止接收方其他输入,也不保证撤销已经开始的工作。- - 候选只包含本机可见、可用的项目、普通任务或有唯一 canonical 对话的活跃伙伴。最近活动只排序,不替用户选中;固定目标失效返回 TARGET_UNAVAILABLE,不自动降级。项目使用 Cindy 已有目录分组,不伪造 projectId。++- 目标只包含本机可见、可用的项目、普通任务或有唯一 canonical 对话的活跃伙伴;不提供 Mobile/device-link 透传。投递仍受当前插件启用、批准、账号和目标权限约束;插件内容不构成新真人授权。++原有 \`cindy.tasks\` 的归属限制不变。先调用 \`capabilities()\` 获取实际支持操作。当前仅支持本插件创建的本机普通任务:\`models\`、\`create\`、\`get\`、\`setModel\`、\`list\`、\`send\`、\`getRun\`、\`listRuns\`、\`readMessages\`、\`cancel\`、\`setHidden\`。可对自有任务调用 \`startTeam({taskId})\` 启用 Orca 主任务,并用 \`getTeam({taskId})\` 读取实际协同状态。协调主任务需经用户授权 Auto,Worker 自动沿用 Auto。这些任务及其 Worker 不提供 \`cindy_helper\` 的账号级历史或跨任务控制能力,\`cindy_memory.session_search\` 也拒绝历史检索;协调使用独立 Orca 工具,结果由插件通过 \`readMessages/getTeam\` 读取。旧 errand/workspace 不因来源标记受到限制;明确卸载撤销归属后,调用方已无正在执行的输入或已接受新真人输入时,保留的用户任务恢复普通 helper 与历史检索能力;仍执行旧插件输入时继续受限,自动回报和插件输入重试不构成真人接管。这不恢复插件控制权,也不保证停止已接受执行,不构成通用执行沙箱。diff --cc apps/desktop/src/main/cindy-brain/index.tsindex 818a3ddb49,483ee2019c..a7a2ce41a5--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@@ -72,8 -75,6 +75,7 @@@ import { getDesktopProviderService } frimport { PluginDownloadSlot } from './downloadSlot.js';import { createDownloader } from '../downloader/index.js';import { handlePluginTaskRequest, type PluginTaskHandler } from './taskSlot.js';+import { PluginTargetSlot, type PluginTargetAdapter } from './pluginTargetSlot.js';- import type { PluginTargetPickerPush } from '../../shared/pluginTargets.js';import { ensurePluginTaskApproval, hasPluginTaskApproval, PluginTaskApprovalGate } from './taskCapability.js';import {registerGhostCardRemoteProvider,@@@ -2094,22 -2098,6 +2099,9 @@@ export function setGhostSessionRevealergetGhostErrandSlot().setRevealSession(reveal);}- const pluginTargetSlot = new PluginTargetSlot({- name: id => findGhostForInstanceId(id)?.manifest.name ?? id,- revision: getPluginTaskInstallRevision,- open: (payload: PluginTargetPickerPush) => {- const window = getDeepLinkMainWindow();- if (!window || window.isDestroyed() || !isTrustedAppRendererWindow(window)) throw new Error('HOST_NOT_READY');- const owner = getActiveDataOwnerPushStamp();- window.show(); window.focus();- sendGhostWindowPush(window, 'ghosts:target-picker', payload, owner);- return { senderId: window.webContents.id, close: () => {- if (!window.isDestroyed()) sendGhostWindowPush(window, 'ghosts:target-picker-dismiss', { requestId: payload.requestId }, owner);- } };- },- });++const pluginTargetSlot = new PluginTargetSlot();+export function setPluginTargetAdapter(adapter: PluginTargetAdapter): void { pluginTargetSlot.adapter = adapter; }+let pluginTaskHandler: PluginTaskHandler | null = null;export function setPluginTaskHandler(handler: PluginTaskHandler | null): void { pluginTaskHandler = handler; }let pluginTaskUninstaller: ((pluginId: string, remove: () => Promise<void>) => Promise<void>) | null = null;diff --cc apps/desktop/src/main/cindy-brain/pluginTargetSlot.tsindex 573c1b668f,0000000000..45ae9501e3mode 100644,000000..100644--- a/apps/desktop/src/main/cindy-brain/pluginTargetSlot.ts+++ b/apps/desktop/src/main/cindy-brain/pluginTargetSlot.ts@@@ -1,381 -1,0 +1,233 @@@+import { createHash, randomUUID } from 'node:crypto';+import type {+ PluginTargetCandidate,+ PluginTargetDelivery,+ PluginTargetKind,- PluginTargetPickerPush,++ PluginTargetRef,+ PluginTargetRequest,+ PluginTargetView,+} from '../../shared/pluginTargets.js';+import type { PluginTaskRoute } from '../../shared/pluginTasks.js';+import {+ getActiveDataOwnerPushStamp,+ ownerScopedUserDataPath,+ activeOwnerScopeKey,+} from '../appSessionState.js';+import { createOverrideSettingsFile } from '../maker-host/override-settings-file.js';+import { desktopMakerLogger } from '../maker-host/logger-adapter.js';+import { parsePluginMessageAttachments, type PluginMessageImage } from '../cindy-media/pluginMessageAttachments.js';+- interface Binding extends PluginTargetView {- pluginId: string;- targetId: string;- }+interface Receipt {- pluginId: string;- requestKey: string;- hash: string;++ hash: string | null;+ clientId: string;+ taskId?: string;+ status: 'pending' | 'accepted' | 'cancelled';++ delivery?: PluginTargetDelivery;+}+interface Ledger {- bindings: Record<string, Binding>;++ receipts: Record<string, Receipt>;+}+export interface PluginTargetAdapter {+ candidates(kind: PluginTargetKind): Promise<PluginTargetCandidate[]>;+ create(+ pluginId: string,+ project: string,+ taskId: string,+ title: string,+ route: PluginTaskRoute | undefined,+ guard: () => void,+ ): Promise<void>;+ session(kind: 'task' | 'bot', id: string): Promise<string>;+ send(+ pluginId: string,+ taskId: string,+ clientId: string,+ text: string,+ guard: () => void,+ validateTarget: () => Promise<void>,+ delivery: PluginTargetDelivery,+ images?: PluginMessageImage[],+ ): Promise<PluginTargetDelivery>;+ withdraw(taskId: string, clientId: string, guard: () => void): Promise<void>;+}+const fail = (code: string): never => {+ throw Object.assign(new Error(code), { code });+};+const keyString = (value: unknown): value is string =>+ typeof value === 'string' && value.length > 0 && value.length <= 200 && !value.includes('\0');+const kinds = ['project', 'task', 'bot'];++const isTarget = (value: unknown): value is PluginTargetRef => {++ const target = value as PluginTargetRef | null;++ return !!target && kinds.includes(target.kind) && typeof target.id === 'string' &&++ target.id.length > 0 && target.id.length <= 4096 && !target.id.includes('\0');++};+const ledger = createOverrideSettingsFile<Ledger>({- filePath: () => ownerScopedUserDataPath('plugin-targets.json'),++ filePath: () => ownerScopedUserDataPath('plugin-target-deliveries.json'),+ scopeKey: activeOwnerScopeKey,- defaults: { bindings: {} },++ defaults: { receipts: {} },+ normalize: (raw) => {+ const value = raw as Ledger | null;- return {- bindings: value?.bindings && typeof value.bindings === 'object' ? value.bindings : {},- };++ return { receipts: value?.receipts && typeof value.receipts === 'object' ? value.receipts : {} };+ },- log: desktopMakerLogger.child('plugin-targets'),- label: 'plugin-targets',++ log: desktopMakerLogger.child('plugin-target-deliveries'),++ label: 'plugin-target-deliveries',+ preserveUnreadableFile: true,+ logLoadedValue: false,+ logReadErrorDetails: false,+});- /** User selection is the grant. No plugin-supplied task ID or project path is accepted. */++/** UI and fixed target configuration belong to plugins; the Host validates and delivers. */+export class PluginTargetSlot {+ adapter: PluginTargetAdapter | null = null;- private temporary = new Map<string, Binding & { expiresAt: number; consumedBy?: string }>();- private receipts = new Map<string, Receipt & { result?: Promise<unknown> }>();- private operations = new Map<string, { cancelled: boolean; expiresAt: number }>();- private activePicker = new Map<string, object>();- private picks = new Map<- string,- {- operation: string;- pluginId: string;- senderId: number;- options: PluginTargetCandidate[];- resolve: (id: string | null) => void;- close: () => void;- }- >();- constructor(- private readonly ui: {- open(payload: PluginTargetPickerPush): { senderId: number; close: () => void };- name(pluginId: string): string;- revision(pluginId: string): string | null;- },- ) {}- private scope(pluginId: string, key: string) {- return JSON.stringify([- activeOwnerScopeKey(),- getActiveDataOwnerPushStamp().ownerGeneration,- pluginId,- this.ui.revision(pluginId),- key,- ]);- }- private read() {++ private inFlight = new Map<string, { hash: string; result: Promise<unknown> }>();++ private cancelled = new Set<string>();++ private readReceipt(key: string): Receipt | undefined {+ ledger.invalidateIfChanged();- return ledger.read();- }- private binding(pluginId: string, id: string): Binding {- const binding = this.read().bindings[id];- if (!binding || binding.pluginId !== pluginId || !kinds.includes(binding.kind))- return fail('TARGET_UNAVAILABLE');- return binding;- }- resolve(requestId: string, senderId: number, id: unknown): boolean {- const pending = this.picks.get(requestId);- if (!pending || pending.senderId !== senderId) return false;- pending.resolve(- typeof id === 'string' && pending.options.some((item) => item.id === id) ? id : null,- );- return true;- }- private cancelPick(operation: string) {- for (const pending of this.picks.values())- if (pending.operation === operation) pending.resolve(null);++ return ledger.read().receipts[key];+ }+ async handle(pluginId: string, raw: unknown, authorized: () => void): Promise<unknown> {+ authorized();- for (const [key, binding] of this.temporary)- if (binding.expiresAt < Date.now()) this.temporary.delete(key);- for (const [key, operation] of this.operations)- if (operation.expiresAt < Date.now() && !this.receipts.has(key)) {- this.operations.delete(key);- this.receipts.delete(key);- }+ if (!this.adapter) return fail('HOST_NOT_READY');+ const adapter = this.adapter;+ const request = raw as PluginTargetRequest;- if (!request || !['pick', 'get', 'send', 'cancel'].includes(request.kind))++ if (!request || !['list', 'resolve', 'send', 'cancel'].includes(request.kind))+ return fail('INVALID_PARAMS');- if (request.kind === 'get') {- if (!keyString(request.bindingId)) return fail('INVALID_PARAMS');- const binding = this.binding(pluginId, request.bindingId);- const candidates = await adapter.candidates(binding.kind);++ const resolve = async (target: PluginTargetRef): Promise<PluginTargetView> => {++ const candidates = await adapter.candidates(target.kind);+ authorized();- const fresh = candidates.find((item) => item.id === binding.targetId);- if (!fresh) return fail('TARGET_UNAVAILABLE');- // Exchange a saved binding for a short-lived, one-use delivery handle.- // A Host restart loses handles, so an uncertain send cannot replay after restart.- const handle = {- ...binding,- bindingId: randomUUID(),- label: fresh.label.slice(0, 200),- expiresAt: Date.now() + 300000,- };- this.temporary.set(this.scope(pluginId, handle.bindingId), handle);- return { bindingId: handle.bindingId, kind: handle.kind, label: handle.label };++ const found = candidates.find((item) => item.id === target.id);++ if (!found) return fail('TARGET_UNAVAILABLE');++ return { kind: target.kind, id: found.id, label: found.label, detail: found.detail };++ };++ if (request.kind === 'list') {++ if (!kinds.includes(request.targetKind)) return fail('INVALID_PARAMS');++ const candidates = await adapter.candidates(request.targetKind);++ authorized();++ return { targets: candidates.map((item) => ({ ...item, kind: request.targetKind })) };++ }++ if (request.kind === 'resolve') {++ if (!isTarget(request.target)) return fail('INVALID_PARAMS');++ return resolve(request.target);+ }+ if (!keyString(request.requestKey)) return fail('INVALID_PARAMS');- const operationKey = this.scope(pluginId, request.requestKey);++ // Stable across Host restarts and plugin upgrades; owner isolation comes from the file path.++ const receiptKey = createHash('sha256').update(JSON.stringify([pluginId, request.requestKey])).digest('hex');++ const runtimeKey = JSON.stringify([++ activeOwnerScopeKey(), getActiveDataOwnerPushStamp().ownerGeneration, receiptKey,++ ]);+ if (request.kind === 'cancel') {- const operation = this.operations.get(operationKey) ?? {- cancelled: true,- expiresAt: Date.now() + 600000,- };- operation.cancelled = true;- this.operations.set(operationKey, operation);- this.cancelPick(operationKey);- const receipt = this.receipts.get(operationKey);- if (receipt?.taskId) {++ this.cancelled.add(runtimeKey);++ let previous: Receipt | undefined;++ await ledger.updateAtomic(({ value }) => {++ authorized();++ previous = value.receipts[receiptKey];++ return { receipts: { ...value.receipts, [receiptKey]: {++ ...(previous ?? { hash: null, clientId: randomUUID() }), status: 'cancelled',++ } } };++ });++ authorized();++ if (previous?.taskId) {+ // Withdraw only this plugin input. Never stop another user's running turn.- await adapter.withdraw(receipt.taskId, receipt.clientId, authorized);++ await adapter.withdraw(previous.taskId, previous.clientId, authorized);+ authorized();+ }- this.receipts.delete(operationKey);- return { cancelled: true, runningWorkMayHaveStarted: receipt?.status === 'accepted' };- }- let operation = this.operations.get(operationKey);- if (!operation) {- operation = { cancelled: false, expiresAt: Date.now() + 600000 };- this.operations.set(operationKey, operation);- }- const guard = () => {- authorized();- if (operation!.cancelled) fail('SUPERSEDED');- };- guard();- if (request.kind === 'pick') {- if (- !kinds.includes(request.targetKind) ||- (request.persistent !== undefined && typeof request.persistent !== 'boolean')- )- return fail('INVALID_PARAMS');- const marker = {};- this.activePicker.set(pluginId, marker);- const guardPicker = () => {- guard();- if (this.activePicker.get(pluginId) !== marker) fail('SUPERSEDED');- };- // A plugin gets at most one live picker; replacement also settles the old IPC.- for (const pending of this.picks.values())- if (pending.pluginId === pluginId) pending.resolve(null);- const candidates = await adapter.candidates(request.targetKind);- guardPicker();- const requestId = randomUUID();- const selected = await new Promise<string | null>((resolve, reject) => {- let ui: { senderId: number; close: () => void };- let timer: ReturnType<typeof setTimeout>;- let boundaryTimer: ReturnType<typeof setInterval>;- const finish = (id: string | null) => {- clearTimeout(timer);- clearInterval(boundaryTimer);- this.picks.delete(requestId);- ui?.close();- resolve(id);- };- try {- ui = this.ui.open({- requestId,- pluginName: this.ui.name(pluginId),- kind: request.targetKind,- persistent: request.persistent === true,- candidates,- });- this.picks.set(requestId, {- operation: operationKey,- pluginId,- senderId: ui.senderId,- options: candidates,- resolve: finish,- close: ui.close,- });- timer = setTimeout(() => finish(null), 120000);- boundaryTimer = setInterval(() => {- try {- guardPicker();- } catch {- finish(null);- }- }, 500);- } catch (error) {- reject(error);- }- });- guardPicker();- if (!selected) return { cancelled: true };- const candidate = candidates.find((item) => item.id === selected)!;- const binding: Binding = {- pluginId,- bindingId: randomUUID(),- kind: request.targetKind,- targetId: candidate.id,- label: candidate.label.slice(0, 200),- };- if (request.persistent) {- await ledger.updateAtomic(({ value }) => {- guardPicker();- return { bindings: { ...value.bindings, [binding.bindingId]: binding } };- });- guardPicker();- } else- this.temporary.set(this.scope(pluginId, binding.bindingId), {- ...binding,- expiresAt: Date.now() + 300000,- });- return { bindingId: binding.bindingId, kind: binding.kind, label: binding.label };++ return { cancelled: true, runningWorkMayHaveStarted: !!previous?.taskId };+ }+ if (- !keyString(request.bindingId) ||- typeof request.text !== 'string' ||- !request.text.trim() ||- request.text.length > 64000 ||++ !isTarget(request.target) ||++ typeof request.text !== 'string' || !request.text.trim() || request.text.length > 64000 ||+ (request.delivery !== undefined && !['queue', 'steer'].includes(request.delivery)) ||- (request.title !== undefined &&- (typeof request.title !== 'string' || request.title.length > 200))- )- return fail('INVALID_PARAMS');- // Saved IDs authorize resolution, not sending. Only a host-minted live handle sends.- const binding = this.temporary.get(this.scope(pluginId, request.bindingId));- if (!binding || binding.pluginId !== pluginId) return fail('TARGET_UNAVAILABLE');++ (request.title !== undefined && (typeof request.title !== 'string' || request.title.length > 200))++ ) return fail('INVALID_PARAMS');++ const target = request.target;+ const delivery = request.delivery ?? 'queue';- if (binding.kind === 'project' && delivery === 'steer') return fail('INVALID_PARAMS');++ if (target.kind === 'project' && delivery === 'steer') return fail('INVALID_PARAMS');+ if (request.route !== undefined) {+ const route = request.route;+ if (- !route ||- !['cc', 'codex', 'pi'].includes(route.agentKind) ||- !keyString(route.providerId) ||- typeof route.model !== 'string' ||- !route.model.trim() ||- route.model.length > 256 ||- typeof route.effort !== 'string' ||- route.effort.length > 32 ||++ target.kind !== 'project' || !route || !['cc', 'codex', 'pi'].includes(route.agentKind) ||++ !keyString(route.providerId) || typeof route.model !== 'string' || !route.model.trim() ||++ route.model.length > 256 || typeof route.effort !== 'string' || route.effort.length > 32 ||+ typeof route.fastMode !== 'boolean'- )- return fail('INVALID_PARAMS');++ ) return fail('INVALID_PARAMS');+ }- if (binding.kind !== 'project' && request.route !== undefined) return fail('INVALID_PARAMS');++ const route = request.route && {++ agentKind: request.route.agentKind, providerId: request.route.providerId,++ model: request.route.model, effort: request.route.effort, fastMode: request.route.fastMode,++ };+ const images = parsePluginMessageAttachments(request.attachments);- const candidates = await adapter.candidates(binding.kind);- guard();- if (!candidates.some((item) => item.id === binding.targetId)) return fail('TARGET_UNAVAILABLE');+ const hash = createHash('sha256')- .update(JSON.stringify([binding.bindingId, request.text, request.title, request.route, delivery,++ .update(JSON.stringify([target.kind, target.id, request.text, request.title, route, delivery,+ images.map(({ hash, name }) => [hash, name])]))+ .digest('hex');- const receipt: Receipt = {- pluginId,- requestKey: request.requestKey,- hash,- clientId: randomUUID(),- status: 'pending',++ const guard = () => {++ authorized();++ if (this.cancelled.has(runtimeKey) || this.readReceipt(receiptKey)?.status === 'cancelled')++ fail('SUPERSEDED');+ };- const previous = this.receipts.get(operationKey);- if (previous) {- if (previous.hash !== hash) return fail('REQUEST_KEY_CONFLICT');- if (previous.result) return previous.result;- return fail('DELIVERY_UNCERTAIN');++ guard();++ const pending = this.inFlight.get(runtimeKey);++ if (pending) {++ if (pending.hash !== hash) return fail('REQUEST_KEY_CONFLICT');++ return pending.result;+ }- // A one-use handle cannot become a second delivery by changing text or requestKey.- if (binding.consumedBy && binding.consumedBy !== operationKey)- return fail('DELIVERY_UNCERTAIN');- binding.consumedBy = operationKey;- const saved: Receipt & { result?: Promise<unknown> } = receipt;- this.receipts.set(operationKey, saved);+ const deliver = async () => {- receipt.taskId =- binding.kind === 'project'- ? randomUUID()- : await adapter.session(binding.kind, binding.targetId);++ const existing = this.readReceipt(receiptKey);++ if (existing) {++ if (existing.hash !== hash) return fail('REQUEST_KEY_CONFLICT');++ if (existing.status === 'accepted')++ return { taskId: existing.taskId, accepted: true, delivery: existing.delivery };++ return fail('DELIVERY_UNCERTAIN');++ }++ const candidate = await resolve(target);+ guard();- if (binding.kind === 'project')- await adapter.create(- pluginId,- binding.targetId,- receipt.taskId,- request.title || binding.label,- request.route,- guard,- );++ const receipt: Receipt = {++ hash, clientId: randomUUID(), status: 'pending',++ taskId: target.kind === 'project' ? randomUUID() : await adapter.session(target.kind, target.id),++ };++ guard();++ // Reserve before creating a task or delivering. An interrupted reservation never replays.++ await ledger.updateAtomic(({ value }) => {++ guard();++ const previous = value.receipts[receiptKey];++ if (previous) {++ if (previous.hash !== hash) fail('REQUEST_KEY_CONFLICT');++ fail('DELIVERY_UNCERTAIN');++ }++ return { receipts: { ...value.receipts, [receiptKey]: receipt } };++ });++ guard();++ const taskId = receipt.taskId!;++ const validateTarget = async () => {++ await resolve(target);++ guard();++ if (target.kind !== 'project' && (await adapter.session(target.kind, target.id)) !== taskId)++ fail('TARGET_UNAVAILABLE');++ guard();++ };++ await validateTarget();++ if (target.kind === 'project')++ await adapter.create(pluginId, target.id, taskId, request.title || candidate.label, route, guard);+ guard();+ const actualDelivery = await adapter.send(- pluginId,- receipt.taskId,- receipt.clientId,- request.text,- guard,- async () => {- const fresh = await adapter.candidates(binding.kind);- guard();- if (!fresh.some((item) => item.id === binding.targetId)) fail('TARGET_UNAVAILABLE');- if (- binding.kind !== 'project' &&- (await adapter.session(binding.kind, binding.targetId)) !== receipt.taskId- )- fail('TARGET_UNAVAILABLE');- guard();- },- delivery,- images,++ pluginId, taskId, receipt.clientId, request.text, guard, validateTarget, delivery, images,+ );- receipt.status = 'accepted';++ await ledger.updateAtomic(({ value }) => {++ authorized();++ const current = value.receipts[receiptKey];++ if (current?.status === 'cancelled') return {};++ return { receipts: { ...value.receipts, [receiptKey]: {++ ...receipt, status: 'accepted', delivery: actualDelivery,++ } } };++ });+ authorized();- if (operation.cancelled) await adapter.withdraw(receipt.taskId, receipt.clientId, authorized);- return { taskId: receipt.taskId, accepted: true, delivery: actualDelivery };++ if (this.cancelled.has(runtimeKey) || this.readReceipt(receiptKey)?.status === 'cancelled') {++ await adapter.withdraw(taskId, receipt.clientId, authorized);++ return fail('SUPERSEDED');++ }++ return { taskId, accepted: true, delivery: actualDelivery };+ };- saved.result = deliver().finally(() => {- if (operation!.cancelled) this.receipts.delete(operationKey);- });- return saved.result;++ const result = deliver().finally(() => this.inFlight.delete(runtimeKey));++ this.inFlight.set(runtimeKey, { hash, result });++ return result;+ }+}diff --cc apps/desktop/src/preload/ghostPreload.tsindex 47cfbd28c5,e36e5e462c..41ef872366--- a/apps/desktop/src/preload/ghostPreload.ts+++ b/apps/desktop/src/preload/ghostPreload.ts@@@ -67,13 -67,6 +67,13 @@@ contextBridge.exposeInMainWorld('cindy'ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'fs-request' }),library: (req: Record<string, unknown>): Promise<unknown> =>ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'library-request' }),- targets: Object.fromEntries(['pick', 'get', 'send', 'cancel'].map(kind => [kind,++ targets: Object.fromEntries(['list', 'resolve', 'send', 'cancel'].map(kind => [kind,+ async (req: Record<string, unknown> = {}): Promise<unknown> => {+ const result = await ipcRenderer.invoke('ghost-pipe:send', { ...req, type: 'targets-request', kind });+ if (result?.ok === true) return result.data;+ throw Object.assign(new Error(result?.error?.message ?? 'Target request failed'), { code: result?.error?.code ?? 'HOST_NOT_READY' });+ },+ ])),tasks: Object.fromEntries(['capabilities', 'models', 'setModel', 'requestWriteAccess', 'startTeam', 'getTeam', 'setTeamPlan', 'releaseWorker', 'create', 'list', 'get', 'send', 'getRun', 'listRuns', 'cancel', 'readMessages', 'setHidden'].map(kind => [kind, async (req: Record<string, unknown> = {}): Promise<unknown> => {diff --cc apps/desktop/src/shared/pluginTargets.tsindex 6c9a239141,0000000000..47e5169b2dmode 100644,000000..100644--- a/apps/desktop/src/shared/pluginTargets.ts+++ b/apps/desktop/src/shared/pluginTargets.ts@@@ -1,37 -1,0 +1,34 @@@+import type { PluginTaskRoute } from './pluginTasks.js';+import type { PluginMessageAttachment } from './pluginAttachments.js';++export type PluginTargetKind = 'project' | 'task' | 'bot';+export type PluginTargetDelivery = 'queue' | 'steer';- export interface PluginTargetView {- bindingId: string;++export interface PluginTargetRef {+ kind: PluginTargetKind;++ /** Project directory, task ID or companion ID from targets.list/resolve. */++ id: string;++}++export interface PluginTargetView extends PluginTargetRef {+ label: string;++ detail: string;+}- /** Only sent to Cindy's trusted desktop renderer, never to a plugin. */++/** Local target metadata; no messages or task history. */+export interface PluginTargetCandidate {+ id: string;+ label: string;+ detail: string;+}- export interface PluginTargetPickerPush {- requestId: string;- pluginName: string;- kind: PluginTargetKind;- persistent: boolean;- candidates: PluginTargetCandidate[];- }+export type PluginTargetRequest =- | { kind: 'pick'; requestKey: string; targetKind: PluginTargetKind; persistent?: boolean }- | { kind: 'get'; bindingId: string }++ | { kind: 'list'; targetKind: PluginTargetKind }++ | { kind: 'resolve'; target: PluginTargetRef }+ | {+ kind: 'send';+ requestKey: string;- bindingId: string;++ target: PluginTargetRef;+ text: string;+ attachments?: PluginMessageAttachment[];+ title?: string;+ route?: PluginTaskRoute;+ delivery?: PluginTargetDelivery;+ }+ | { kind: 'cancel'; requestKey: string };diff --cc docs/dev-rules/plugin-task-api-implementation.mdindex 51b84d4caf,264a3479c7..b9cad7b5dd--- a/docs/dev-rules/plugin-task-api-implementation.md+++ b/docs/dev-rules/plugin-task-api-implementation.md@@@ -328,38 -333,3 +333,48 @@@ Pi 子代理未成功投递的自动 al`auto-review-context.test.ts`、Pi/Claude Code 审批接线回归以及 `eval-auto-approval.mts` 的`delegated-*` 正反对照(后者需要真实审阅模型,当前拆分 PR 未运行付费验证)。主机身份校验是确定性边界,动作与任务是否相符仍由 Auto 审阅,不宣称题目目录是系统沙箱。+- ## 用户选择的投递目标(增量接口,尚未发布)-- `cindy.targets` 的作者契约见 `FORGE_GUIDE`,实现位于 `pluginTargetSlot.ts`、- `pluginTargetCandidates.ts` 和 `PluginTargetPickerHost.tsx`。保留 `cindy.tasks` 自有任务边界,- 不把它的 get/list/send 放宽成任意任务权限。新入口复用 `agent.tasks` 的启用、批准和逻辑页身份校验,- 还必须取得用户在宿主选择器里的具体目标选择;插件不能直接提交 taskId、botId 或项目路径作为授权。- 不改变现存插件、旧任务 API、默认设置卡或 manifest 字段。-- - 每次选择只产生临时句柄;固定选择落入 owner-scoped `plugin-targets.json`,只保存插件、目标标识和名称,不保存桌面内容或消息。- - `get` 将固定绑定换成本次短期句柄。发送消费临时句柄,相同请求共享同一 Promise,不能更换 requestKey 或正文使同一句柄重复创建/投递;Host 重启后句柄失效。未知结果由调用方保留为待检查,不自动重放。- - Picker 只投主窗口,绑定 webContents;回包必须来自受信宿主 Renderer。Owner stamp 在接收端校验,换账号清 UI;等待中还会复核原插件逻辑页、批准 revision 和 owner generation。- - 新项目任务沿用插件模型选择和受限的动手权限,使用现有 `createPluginTaskSession`;目录来自宿主已有项目列表。存量任务和伙伴保留其模型、权限、目录;伙伴只通过唯一 canonical 注册解析,不使用兼容镜像或伪造伙伴身份。- - `send` 的可选 `delivery` 为 `queue | steer`,缺省为 `queue`;project 仅接受 queue,新建任务不需要插话。delivery 参与请求幂等签名,缺省与显式 queue 等价,同键更换投递方式返回 REQUEST_KEY_CONFLICT。- - queue 走 `sendToSessionInternal` 与既有输入队列;steer 复用 `steerControlInput` 同轮注入,不停止或重启当前轮。空闲、框架不支持或当前输入边界不允许插话时走普通队列,保留 Stop/pause 边界。返回 `{taskId,accepted:true,delivery:'queue'|'steer'}`,delivery 表示实际接受路径,不表示 AI 已执行完成。- - main 盖 sourcePlugin 和 delegated-continuation 来源,沿用目标模型及权限。接受前、异步筛查后及 provider 派发前复核插件批准与目标。筛查拒绝返回 DELIVERY_REJECTED,不改走队列;ACK 未知保留宿主保护性暂停队列并返回 DELIVERY_UNCERTAIN,不再次排队。取消只按本插件 host-generated clientId 撤回排队输入,不停止整个会话或撤回已经接受的插话。- - 仅本机 Desktop,不新增 Mobile/device-link 透传,也不承诺跨平台原生触发。-- 此能力供声明了 `agent.tasks` 的插件使用;目标由用户选择,投递沿用既有插件授权和目标任务权限。- 静态检查不等于设置 UI、取材、伙伴实际执行的联调验收;不得把 accepted 当成完成。++## 通用投递目标(增量接口,尚未发布)++++`cindy.targets` 的作者契约见 `FORGE_GUIDE`,实现位于 `pluginTargetSlot.ts` 和++`pluginTargetCandidates.ts`。查询、解析和投递相互独立,没有宿主目标选择弹窗、Renderer 接线或新增 UI。++选择方式、固定目标及其配置由使用这些接口的插件维护;Host 不保存插件的固定目标绑定。++入口复用 `agent.tasks` 的启用、批准和逻辑页身份校验,保留 `cindy.tasks` 自有任务边界,++不放宽它的 get/list/send,不改变旧任务 API、默认设置卡或 manifest 字段。++++- `list({targetKind})` 返回 `{targets:[{kind,id,label,detail}]}`,仅返回本机可用目标元数据,不返回消息历史。++ 项目使用 Cindy 已有目录分组(id 为目录路径),普通任务和伙伴使用其 ID。最近活动只排序,插件自行展示和选择。++- `resolve({target:{kind,id}})` 返回最新目标元数据,供插件校验保存的固定目标;无写入、弹窗或隐式选中。++ `send` 同样重新校验目标,不要求先 list/resolve,也不接受任意不可用路径或目标;失效返回 TARGET_UNAVAILABLE,不降级改投。++- `send({target,requestKey,text,title?,route?,delivery?,attachments?})` 在指定项目中新建普通任务,或向指定普通任务/伙伴投递。++ 新任务使用现有 `createPluginTaskSession`,沿用插件模型选择和受限动手权限,可传统一模型目录的 route。++ 存量任务和伙伴保留其模型、权限、目录,不接受 route;伙伴通过唯一 canonical 注册解析,不使用兼容镜像或伪造伙伴身份。++- 同键并发发送共享同一 Promise。owner-scoped `plugin-target-deliveries.json` 只保存请求摘要、Host 生成的 taskId/clientId 和状态,++ 不保存正文、图片或插件固定配置。执行前原子预留回执;已接受请求可在重启后返回原结果,尚未确定的回执返回 DELIVERY_UNCERTAIN,++ 不自动重派。幂等键按插件和 requestKey 隔离,不因插件升级或 Host 重启更换身份;同键修改目标、正文、附件或 delivery 返回 REQUEST_KEY_CONFLICT。++- `delivery` 为 `queue | steer`,缺省 queue(与显式 queue 幂等签名一致);project 仅接受 queue。++ queue 走 `sendToSessionInternal` 与既有输入队列;steer 复用 `steerControlInput` 同轮注入,不停止或重启当前轮。++ 空闲、框架不支持或当前输入边界不允许插话时走普通队列,保留 Stop/pause 边界。++ 返回 `{taskId,accepted:true,delivery:'queue'|'steer'}` 表示实际接受路径,不表示 AI 已执行完成。++- main 盖 sourcePlugin 和 delegated-continuation 来源;入队前复核插件批准与目标,插话还在异步筛查后及 provider 派发前复核。++ 筛查拒绝返回 DELIVERY_REJECTED,不改走队列;ACK 未知保留宿主保护性暂停队列并返回 DELIVERY_UNCERTAIN,不再次排队。++ `cancel({requestKey})` 持久使迟到请求失效,只按本插件该请求的 clientId 撤回排队输入,不停止整个会话或撤回已经接受的插话。++- 仅本机 Desktop,不新增 Mobile/device-link 透传,也不承诺跨平台原生触发。异步请求持续复核原逻辑页、批准 revision 和 owner generation。++++此能力供声明了 `agent.tasks` 的插件使用;投递沿用既有插件授权和目标任务权限。++静态检查与单元测试不等于真实 AI 执行的联调验收,不得把 accepted 当成完成。++### 消息图片附件++`tasks.send` 与 `targets.send` 支持 `attachments?: Array<{base64:string,name?:string}>`。+插件先核对 `tasks.capabilities().messageAttachments`,无此能力时停止发送截图,不能静默丢图或回退文件路径。+只接受插件自己提供的字节;不接受 Host 路径、URL、其他会话的媒体 URI 或自报 MIME。+Host 校验规范 base64,嗅探 PNG/JPEG/WebP,最多 4 张、合计 20 MiB;附件字节指纹和名称参与幂等签名,回执不保存 base64。++`pluginMessageAttachments.ts` 复用 `ingestMedia` 和草稿/排队消息提交链路。入库前同步登记内容地址到现有回收器的活引用集合,+覆盖去重旧 blob 的入库、取消和派发在途窗口。调用方等待既有持久队列写入或插话落库后释放在途保护;+之后由内存队列、恢复快照和 `createMessage → commitMessageMediaRefs` 的会话附件引用保护。+失败或取消且未采用的图片不保留永久引用,由既有零引用缓冲与手动回收处理。无新目录、数据表、媒体协议或 media.deposit 授权。++queue 与 steer 都把托管 URL 写入 files、chatMessage.images 和持久消息信封;模型输入由既有附件装配器生成。+正文/附件来源仍是插件续行,不把截图变为新用户授权;目标、批准、owner 和取消闸保持不变。