Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(plugin): 补齐目标授权与持久投递边界

liugaoweiec97ea68643b
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.ts
index b8572ed0ee..f8a056eb03 100644
--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts
+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts
@@ -2644,6 +2644,7 @@ export class GhostManager {
...(retirement ? { retirement } : {}),
approval: { state: 'approved', revision: receipt.revision },
...(receipt.taskCapabilityApproved === true ? { taskCapabilityApproved: true as const } : {}),
+ ...(receipt.targetCapabilityApproved === true ? { targetCapabilityApproved: true as const } : {}),
trust: receipt.trust,
...(!retired && receipt.manifest.skill?.items.length
? {
@@ -2834,18 +2835,20 @@ export class GhostManager {
}
/** Called only after Host permission UI confirms this exact installed revision. */
- async approveTaskCapability(id: string, revision: string, isCurrent: () => boolean): Promise<boolean> {
+ async approveTaskCapability(id: string, revision: string, isCurrent: () => boolean, capability: 'tasks' | 'targets' = 'tasks'): Promise<boolean> {
return this.runExclusiveMutation(async () => {
const relId = this.approvalRelIdFor(id);
if (!relId) return false;
const approval = this.readApproval(relId);
if (!isCurrent() || approval.state !== 'approved' || approval.receipt.revision !== revision ||
approval.receipt.manifest.agent?.tasks !== true ||
+ (capability === 'targets' && (approval.receipt.manifest.agent.targets !== true || approval.receipt.taskCapabilityApproved !== true)) ||
!findInstalledGhostByInstanceId(this.list(), id)?.enabled) return false;
- if (approval.receipt.taskCapabilityApproved !== true) {
+ const field = capability === 'targets' ? 'targetCapabilityApproved' : 'taskCapabilityApproved';
+ if (approval.receipt[field] !== true) {
const expired = new Error('Task capability approval owner changed');
try {
- await this.receiptStore.write({ ...approval.receipt, taskCapabilityApproved: true }, {
+ await this.receiptStore.write({ ...approval.receipt, [field]: true }, {
relId,
assertCurrent: () => { if (!isCurrent()) throw expired; },
});
@@ -3509,6 +3512,7 @@ export class GhostManager {
lizFilePath: string,
opts?: {
taskCapabilityApproved?: true;
+ targetCapabilityApproved?: true;
initiallyEnabled?: boolean;
expectedPackageSha256?: string;
trustOverride?: GhostHostTrustOverride;
@@ -3533,6 +3537,7 @@ export class GhostManager {
lizFilePath: string,
opts?: {
taskCapabilityApproved?: true;
+ targetCapabilityApproved?: true;
initiallyEnabled?: boolean;
expectedPackageSha256?: string;
trustOverride?: GhostHostTrustOverride;
@@ -3703,6 +3708,7 @@ export class GhostManager {
localeResources,
enabled: initiallyEnabled,
...(opts?.taskCapabilityApproved === true && approvedManifest.agent?.tasks === true ? {taskCapabilityApproved:true as const} : {}),
+ ...(opts?.targetCapabilityApproved === true && approvedManifest.agent?.tasks === true && approvedManifest.agent.targets === true ? {targetCapabilityApproved:true as const} : {}),
trust,
// 指纹取自包投影而不是刚发布的 finalDir:发布后被换的字节应当在快照
// 对账时被拒,而不是被首读钉成批准基线(P0-8)。
@@ -3825,6 +3831,7 @@ export class GhostManager {
lizFilePath: string,
opts: {
taskCapabilityApproved?: true;
+ targetCapabilityApproved?: true;
expectedInstalledApproval: string;
expectedPackageSha256?: string;
trustOverride?: GhostHostTrustOverride;
@@ -3843,6 +3850,7 @@ export class GhostManager {
lizFilePath: string,
opts: {
taskCapabilityApproved?: true;
+ targetCapabilityApproved?: true;
expectedInstalledApproval: string;
expectedPackageSha256?: string;
trustOverride?: GhostHostTrustOverride;
@@ -4088,6 +4096,8 @@ export class GhostManager {
enabled,
...((opts.taskCapabilityApproved === true || (archiveId === undefined && approvalResult.state === 'approved' && approvalResult.receipt.taskCapabilityApproved === true)) &&
approvedManifest.agent?.tasks === true ? { taskCapabilityApproved: true as const } : {}),
+ ...((opts.targetCapabilityApproved === true || (archiveId === undefined && approvalResult.state === 'approved' && approvalResult.receipt.targetCapabilityApproved === true)) &&
+ approvedManifest.agent?.tasks === true && approvedManifest.agent.targets === true ? { targetCapabilityApproved: true as const } : {}),
trust,
// 同 install:指纹取自包投影,发布后的目录漂移在快照对账时 fail closed(P0-8)。
skillContentSha256: await this.hashSkillContentFromPackage(
@@ -4495,6 +4505,8 @@ export class GhostManager {
packageSha256,
...(current.state === 'approved' && current.receipt.taskCapabilityApproved === true &&
approvedManifest.agent?.tasks === true ? { taskCapabilityApproved: true as const } : {}),
+ ...(current.state === 'approved' && current.receipt.targetCapabilityApproved === true &&
+ approvedManifest.agent?.tasks === true && approvedManifest.agent.targets === true ? { targetCapabilityApproved: true as const } : {}),
...(iconDataUrl !== undefined ? { iconDataUrl } : {}),
namespace: null,
}),
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
index 5b53a2ea12..9fc91f11f6 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
@@ -360,6 +360,30 @@ describe('GhostManager · 存量插件一次性迁移(§5 升级无感)', () =>
expect(manager.list().find(ghost => installedGhostStoragePart(ghost) !== instanceId)?.taskCapabilityApproved).toBeUndefined();
});
+ it('binds independent target consent to the approved instance and preserves it only for the same capability', async () => {
+ const manifest = { ...goodManifest(), slots: ['tool', 'agent'], agent: { tasks: true, targets: true } };
+ const pkg = await makeCindy('targets.cindy', manifest, { 'main.js': '// plugin' });
+ await manager.install(pkg, { taskCapabilityApproved: true });
+ await manager.install(pkg, { namespace: 'acme', taskCapabilityApproved: true });
+ const selected = manager.list().find(ghost => ghost.namespace === 'acme')!;
+ if (selected.approval.state !== 'approved') throw new Error('fixture not approved');
+ const instanceId = installedGhostStoragePart(selected);
+ expect(selected.targetCapabilityApproved).toBeUndefined();
+ expect(await manager.approveTaskCapability(instanceId, 'stale', () => true, 'targets')).toBe(false);
+ expect(await manager.approveTaskCapability(instanceId, selected.approval.revision, () => false, 'targets')).toBe(false);
+ expect(await manager.approveTaskCapability(instanceId, selected.approval.revision, () => true, 'targets')).toBe(true);
+ expect(manager.list().find(ghost => ghost.namespace === 'acme')?.targetCapabilityApproved).toBe(true);
+ expect(manager.list().find(ghost => ghost.namespace !== 'acme')?.targetCapabilityApproved).toBeUndefined();
+ const update = await makeCindy('targets-update.cindy', { ...manifest, version: '1.0.1' }, { 'main.js': '// update' });
+ const updated = await manager.update(update, { namespace: 'acme', expectedInstalledApproval: ghostInstallApprovalToken(selected.approval) });
+ expect(updated).toHaveProperty('ghost.targetCapabilityApproved', true);
+ if (!('ghost' in updated) || updated.ghost.approval.state !== 'approved') throw new Error('fixture update failed');
+ const removed = await makeCindy('targets-removed.cindy', { ...manifest, version: '1.0.2', agent: { tasks: true } }, { 'main.js': '// update' });
+ const result = await manager.update(removed, { namespace: 'acme', expectedInstalledApproval: ghostInstallApprovalToken(updated.ghost.approval) });
+ expect(result).toHaveProperty('ghost.taskCapabilityApproved', true);
+ expect(result).not.toHaveProperty('ghost.targetCapabilityApproved');
+ });
+
it.each(['future', { future: true }, ['future'], null, false])('keeps historical unknown tasks %j enabled without task approval', async (tasks) => {
await writeLegacyInstall('hello', {...goodManifest(), slots:['tool','agent'], agent:{tasks}});
await manager.migrateLegacyApprovalsOnce();
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallConsent.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallConsent.test.ts
index 9706b8f8d7..1a9ec0e3e4 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallConsent.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallConsent.test.ts
@@ -272,3 +272,22 @@ describe('pending consent prompts', () => {
expect(second.signal.aborted).toBe(false);
});
});
+
+it('records target consent only when the independent capability was shown', async () => {
+ const previous = { ...manifest(['api.weather.test']), agent: { tasks: true } };
+ const next = { ...previous, agent: { tasks: true, targets: true } };
+ const prompt = userPrompt(true);
+ const policy = { mode: 'prompt' as const, prompt, initiator: 'user' as const, origin: 'market' as const };
+ const before = installed(previous);
+ const decision = await obtainGhostInstallConsent(policy, before, next, reviewedDigest);
+ assertGhostInstallConsent(decision, before, next, reviewedDigest);
+ expect(prompt).toHaveBeenCalledWith(expect.objectContaining({ facts: expect.objectContaining({ added: [expect.objectContaining({ key: 'agent:targets' })] }) }));
+ expect(confirmedTaskCapability(decision, before, next, 'targets')).toBe(true);
+ expect(confirmedTaskCapability(decision, before, next)).toBeUndefined();
+ expect(confirmedTaskCapability({ mode: 'unprompted' }, before, next, 'targets')).toBeUndefined();
+ const alreadyDeclared = installed(next);
+ const expanded = { ...next, network: { hosts: ['api.weather.test', 'other.test'] } };
+ const unrelated = await obtainGhostInstallConsent(policy, alreadyDeclared, expanded, reviewedDigest);
+ assertGhostInstallConsent(unrelated, alreadyDeclared, expanded, reviewedDigest);
+ expect(confirmedTaskCapability(unrelated, alreadyDeclared, expanded, 'targets')).toBeUndefined();
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.ts
index df3c30c0ef..56c120a7a9 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.ts
@@ -224,6 +224,19 @@ describe('GhostInstallReceiptStore cleanup', () => {
expect(saved).toEqual(raw);
});
+ it('round trips independent target approval without inferring it from old tasks grants', async () => {
+ const receipt = createSetupReceipt();
+ receipt.manifest.agent = { tasks: true, targets: true };
+ receipt.taskCapabilityApproved = true;
+ await store.write(receipt);
+ const old = store.read('hello');
+ if (old.state !== 'approved') throw new Error('fixture not approved');
+ expect(old.receipt.targetCapabilityApproved).toBeUndefined();
+ await store.write({ ...old.receipt, targetCapabilityApproved: true });
+ const approved = store.read('hello');
+ expect(approved).toMatchObject({ state: 'approved', receipt: { taskCapabilityApproved: true, targetCapabilityApproved: true, revision: receipt.revision } });
+ });
+
it('writes setup in the author format accepted by the v0.1.48 receipt reader', async () => {
const receipt = createSetupReceipt();
await store.write(receipt);
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/pluginTargetSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/pluginTargetSlot.test.ts
index fd0b4e73e0..5b1fef2111 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/pluginTargetSlot.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/pluginTargetSlot.test.ts
@@ -1,23 +1,35 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
-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';
+import { PluginTargetSlot, type PluginTargetAdapter, type PluginTargetReceipt, type PluginTargetStore } from '../pluginTargetSlot.js';
+
+const receipts = new Map<string, PluginTargetReceipt>();
+const key = (pluginId: string, requestKey: string) => JSON.stringify([pluginId, requestKey]);
+const store: PluginTargetStore = {
+ get: async (pluginId, requestKey) => structuredClone(receipts.get(key(pluginId, requestKey))),
+ getById: async id => structuredClone([...receipts.values()].find(row => row.id === id)),
+ reserve: async receipt => {
+ const identity = key(receipt.pluginId, receipt.requestKey);
+ if (receipts.has(identity)) return false;
+ receipts.set(identity, structuredClone(receipt));
+ return true;
+ },
+ cancel: async (pluginId, requestKey) => {
+ const identity = key(pluginId, requestKey);
+ const receipt: PluginTargetReceipt = { ...(receipts.get(identity) ?? {
+ id: 'cancelled', pluginId, requestKey, hash: null,
+ }), status: 'cancelled' };
+ receipts.set(identity, receipt);
+ return structuredClone(receipt);
+ },
+ accept: async (id, delivery) => {
+ const receipt = [...receipts.values()].find(row => row.id === id)!;
+ if (receipt.status !== 'cancelled') Object.assign(receipt, { status: 'accepted', delivery });
+ },
+};
function deferred<T>() {
let resolve!: (value: T) => void;
@@ -26,7 +38,7 @@ function deferred<T>() {
}
describe('plugin target queries and delivery', () => {
- beforeEach(() => { state.receipts = {}; });
+ beforeEach(() => { receipts.clear(); });
function fixture() {
const slot = new PluginTargetSlot();
const send = vi.fn<PluginTargetAdapter['send']>(async () => 'queue');
@@ -35,12 +47,13 @@ describe('plugin target queries and delivery', () => {
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 approvalRevision = vi.fn<PluginTargetAdapter['approvalRevision']>(() => 'approved-install');
+ slot.adapter = { store: () => store, approvalRevision, candidates, session: async () => 'chosen', send, create, withdraw };
const guard = vi.fn();
const call = (payload: unknown, plugin = 'plugin') => slot.handle(plugin, payload, guard);
const request = { kind: 'send', target: { kind: 'task', id: 'chosen' },
requestKey: 'send', text: 'context' };
- return { slot, call, request, send, create, withdraw, candidates, guard };
+ return { slot, call, request, send, create, withdraw, candidates, guard, approvalRevision };
}
// Production entry: PluginTargetSlot.handle, called by the authorized logic-page pipe.
// Contract: query/resolve without UI, explicit target delivery, durable deduplication and cancellation.
@@ -51,7 +64,7 @@ describe('plugin target queries and delivery', () => {
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(receipts.size).toBe(0);
expect(f.create).not.toHaveBeenCalled();
expect(f.send).not.toHaveBeenCalled();
});
@@ -80,8 +93,8 @@ describe('plugin target queries and delivery', () => {
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');
+ expect(JSON.stringify([...receipts.values()])).not.toContain(base64);
+ expect(JSON.stringify([...receipts.values()])).not.toContain('window.png');
});
it('rejects a forged media URL before creating or sending a target task', async () => {
const f = fixture();
@@ -201,7 +214,7 @@ describe('plugin target queries and delivery', () => {
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({});
+ expect(receipts.size).toBe(0);
});
it('rechecks the canonical companion session immediately before delivery', async () => {
const f = fixture();
@@ -210,4 +223,34 @@ describe('plugin target queries and delivery', () => {
.rejects.toMatchObject({ code: 'TARGET_UNAVAILABLE' });
expect(f.send).not.toHaveBeenCalled();
});
+ // Production queue acceptance reuses this entry for live and restored snapshots.
+ // Regression: callbacks in memory disappear on restart; a saved clientId must still
+ // reject revocation/cancellation and canonical changes before the provider starts (unit).
+ it.each(['disabled', 'new approval', 'cancelled', 'missing target', 'canonical changed'] as const)(
+ 'rejects restored queued delivery when %s', async change => {
+ const f = fixture();
+ await f.call(f.request);
+ const [, taskId, clientId] = f.send.mock.calls[0]!;
+ if (change === 'disabled') f.approvalRevision.mockReturnValue(null);
+ if (change === 'new approval') f.approvalRevision.mockReturnValue('replacement-install');
+ if (change === 'cancelled') await f.call({ kind: 'cancel', requestKey: f.request.requestKey });
+ if (change === 'missing target') f.candidates.mockResolvedValue([]);
+ if (change === 'canonical changed') f.slot.adapter!.session = async () => 'new-session';
+ const restarted = new PluginTargetSlot();
+ restarted.adapter = f.slot.adapter;
+ await expect(restarted.assertQueuedDelivery(taskId, clientId)).rejects.toMatchObject({
+ code: change === 'missing target' || change === 'canonical changed' ? 'TARGET_UNAVAILABLE' : 'PERMISSION_DENIED',
+ });
+ },
+ );
+ it('accepts an authorized restored receipt without needing its original logic page', async () => {
+ const f = fixture();
+ await f.call(f.request);
+ const [, taskId, clientId] = f.send.mock.calls[0]!;
+ const restarted = new PluginTargetSlot();
+ restarted.adapter = f.slot.adapter;
+ await expect(restarted.assertQueuedDelivery(taskId, clientId)).resolves.toBeUndefined();
+ expect(f.send).toHaveBeenCalledOnce();
+ });
+
});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/taskCapability.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/taskCapability.test.ts
index 660bdda81f..2ecb8119a1 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/taskCapability.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/taskCapability.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it, vi } from 'vitest';
-import { ensurePluginTaskApproval, hasPluginTaskApproval, PluginTaskApprovalGate } from '../taskCapability.js';
+import { ensurePluginTaskApproval, hasPluginTaskApproval, hasPluginTargetApproval, PluginTaskApprovalGate } from '../taskCapability.js';
import { handlePluginTaskRequest } from '../taskSlot.js';
import type { InstalledGhost } from '../../../shared/ghost.js';
@@ -119,3 +119,38 @@ describe('explicit task capability approval', () => {
expect(handler).not.toHaveBeenCalled();
});
});
+
+// Missing independent consent is the minimal failing input; no provider or Desktop UI needed.
+it.each(['missing-declaration', 'old-receipt', 'deny', 'account-change', 'write-failure', 'approve'] as const)(
+ 'keeps target access separate from old tasks approval: %s', async scenario => {
+ const ghost = legacy();
+ ghost.taskCapabilityApproved = true;
+ if (scenario !== 'missing-declaration') ghost.manifest.agent!.targets = true;
+ let current = true;
+ const confirm = vi.fn(async facts => {
+ expect(facts.added.map((item: { key: string }) => item.key)).toEqual(['agent:targets']);
+ if (scenario === 'account-change') current = false;
+ return scenario !== 'deny';
+ });
+ const approve = vi.fn(async (_id, _revision, isCurrent) => {
+ if (scenario === 'write-failure') throw new Error('disk failure');
+ if (!isCurrent()) return false;
+ ghost.targetCapabilityApproved = true;
+ return true;
+ });
+ expect(hasPluginTargetApproval(ghost)).toBe(false);
+ expect(hasPluginTaskApproval(ghost)).toBe(true);
+ if (scenario !== 'old-receipt') {
+ const result = ensurePluginTaskApproval('p', { getGhost: () => ghost, isCurrent: () => current, confirm, approve }, 'targets');
+ if (scenario === 'write-failure') await expect(result).rejects.toThrow('disk failure');
+ else expect(await result).toBe(scenario === 'approve');
+ }
+ expect(hasPluginTargetApproval(ghost)).toBe(scenario === 'approve');
+ expect(hasPluginTaskApproval(ghost)).toBe(true);
+ if (scenario === 'missing-declaration' || scenario === 'old-receipt') expect(confirm).not.toHaveBeenCalled();
+ if (scenario === 'approve') {
+ await ensurePluginTaskApproval('p', { getGhost: () => ghost, isCurrent: () => current, confirm, approve }, 'targets');
+ expect(confirm).toHaveBeenCalledOnce();
+ }
+ },
+);
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index a853b67d60..ebd8780673 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -4035,7 +4035,7 @@ const r = await cindy.agent.requestSchedule({
用户拒绝或确认界面不可用时返回 \`PERMISSION_DENIED\`,不影响插件其它功能;不得自动循环重试确认。
面板通过既有逻辑页通道调用,不获得新的 preload 或内部 IPC 权限。
-插件需要向项目、已有任务或伙伴投递内容时,使用独立的 \`cindy.targets\`(仅本机 Desktop 逻辑页,同样需要已批准的 \`agent.tasks\`)。先检查 \`typeof cindy.targets?.list === 'function'\`;旧客户端没有此入口,不调用私有 IPC 或自动改投别处。Host 只提供查询、解析和投递;选择 UI、临时选择及固定目标配置由插件自己维护。
+插件需要向项目、已有任务或伙伴投递内容时,使用独立的 \`cindy.targets\`(仅本机 Desktop 逻辑页,需要同时声明并获批 \`agent.tasks: true\` 与独立的 \`agent.targets: true\`)。先检查 \`typeof cindy.targets?.list === 'function'\`;旧客户端没有此入口,不调用私有 IPC 或自动改投别处。Host 只提供查询、解析和投递;选择 UI、临时选择及固定目标配置由插件自己维护。独立权限 \`agent:targets\` 会在既有安装/更新确认中展示;旧 tasks 批准和历史未知字段不授予目标访问。缺新批准只阻止新接口,首次调用复用既有宿主确认,不影响旧插件能力。
- \`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 是任务/伙伴标识。
diff --git a/apps/desktop/src/main/cindy-brain/ghostInstallConsent.ts b/apps/desktop/src/main/cindy-brain/ghostInstallConsent.ts
index b115516d93..f6dc20e792 100644
--- a/apps/desktop/src/main/cindy-brain/ghostInstallConsent.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostInstallConsent.ts
@@ -54,11 +54,12 @@ export function confirmedTaskCapability(
decision: GhostInstallConsentDecision,
installed: InstalledGhost | null | undefined,
next: GhostManifest,
+ capability: 'tasks' | 'targets' = 'tasks',
): true | undefined {
if (decision.mode !== 'confirmed') return undefined;
const facts = evaluateGhostInstallConsent(installed, next);
const shown = facts?.kind === 'install' ? facts.permissions : facts?.added;
- return shown?.some(item => item.key === 'agent:tasks') ? true : undefined;
+ return shown?.some(item => item.key === `agent:${capability}`) ? true : undefined;
}
/**
diff --git a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
index 46fef52f75..7cd5bf97a0 100644
--- a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
@@ -96,6 +96,7 @@ const ICON_DATA_URL_RE = /^data:image\/(?:png|jpeg|webp|gif);base64,[A-Za-z0-9+/
export interface GhostInstallReceipt {
/** Explicit Host confirmation; absent on older receipts, never inferred from manifest. */
taskCapabilityApproved?: true;
+ targetCapabilityApproved?: true;
schemaVersion: typeof RECEIPT_SCHEMA_VERSION;
id: string;
/** Missing is a pre-namespace receipt. null is root; a string is an organization. */
@@ -1194,6 +1195,7 @@ export function readLegacyInstallTrust(dir: string): GhostTrustInfo | null {
export function createGhostInstallReceipt(input: {
taskCapabilityApproved?: true;
+ targetCapabilityApproved?: true;
manifest: GhostManifest;
localeResources: Record<string, GhostManifestLocaleResource>;
enabled: boolean;
@@ -1223,6 +1225,7 @@ export function createGhostInstallReceipt(input: {
trust: input.trust,
skillContentSha256: input.skillContentSha256,
...(input.taskCapabilityApproved === true ? { taskCapabilityApproved: true as const } : {}),
+ ...(input.targetCapabilityApproved === true ? { targetCapabilityApproved: true as const } : {}),
...(input.packageSha256 ? { packageSha256: input.packageSha256 } : {}),
...(input.iconDataUrl ? { iconDataUrl: input.iconDataUrl } : {}),
...(input.installOrigin !== undefined ? { installOrigin: input.installOrigin } : {}),
@@ -1419,6 +1422,7 @@ function validateReceipt(
trust,
skillContentSha256,
...(value.taskCapabilityApproved === true ? { taskCapabilityApproved: true as const } : {}),
+ ...(value.targetCapabilityApproved === true ? { targetCapabilityApproved: true as const } : {}),
...(typeof value.packageSha256 === 'string' ? { packageSha256: value.packageSha256 } : {}),
...(typeof value.iconDataUrl === 'string' ? { iconDataUrl: value.iconDataUrl } : {}),
...(installOrigin !== undefined ? { installOrigin } : {}),
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index a7a2ce41a5..8172a1a38f 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -76,7 +76,7 @@ import { 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 { ensurePluginTaskApproval, hasPluginTaskApproval, PluginTaskApprovalGate } from './taskCapability.js';
+import { ensurePluginTaskApproval, hasPluginTaskApproval, hasPluginTargetApproval, PluginTaskApprovalGate } from './taskCapability.js';
import {
registerGhostCardRemoteProvider,
persistGhostCardWithRemoteChange,
@@ -112,10 +112,10 @@ import { isDeepStrictEqual } from 'node:util';
import type { GhostInstallConsentFacts } from '../../shared/ghostInstallConsent.js';
const taskApprovalGate = new PluginTaskApprovalGate();
-function requestPluginTaskApproval(id: string, isCurrent: () => boolean, confirm: (facts: GhostInstallConsentFacts) => Promise<boolean>, explicit = false): Promise<boolean> {
+function requestPluginTaskApproval(id: string, isCurrent: () => boolean, confirm: (facts: GhostInstallConsentFacts) => Promise<boolean>, explicit = false, capability: 'tasks' | 'targets' = 'tasks'): Promise<boolean> {
const ghost = findGhostForInstanceId(id);
if (!isCurrent()) return Promise.resolve(false);
- if (hasPluginTaskApproval(ghost)) return Promise.resolve(true);
+ if ((capability === 'targets' ? hasPluginTargetApproval : hasPluginTaskApproval)(ghost)) return Promise.resolve(true);
const owner = getActiveDataOwnerPushStamp();
const manager = getGhostManager();
const revision = ghostInstallApprovalToken(ghost?.approval);
@@ -124,10 +124,10 @@ function requestPluginTaskApproval(id: string, isCurrent: () => boolean, confirm
return isCurrent() && owner.dataOwnerId === current.dataOwnerId && owner.ownerGeneration === current.ownerGeneration &&
ghostInstallApprovalToken(findGhostForInstanceId(id)?.approval) === revision;
};
- return taskApprovalGate.request(id, JSON.stringify([owner.dataOwnerId, owner.ownerGeneration, revision]), explicit, () => ensurePluginTaskApproval(id, {
+ return taskApprovalGate.request(`${capability}:${id}`, JSON.stringify([owner.dataOwnerId, owner.ownerGeneration, revision]), explicit, () => ensurePluginTaskApproval(id, {
getGhost: findGhostForInstanceId, isCurrent: active, confirm,
- approve: (pluginId, expected, current) => manager.approveTaskCapability(pluginId, expected, current),
- }));
+ approve: (pluginId, expected, current) => manager.approveTaskCapability(pluginId, expected, current, capability),
+ }, capability));
}
import { isValidPluginNamespace, supportsCindyVersion, PLUGIN_MEMBER_UPLOAD_MAX_ARCHIVE_BYTES } from '@cindy/plugin-protocol';
@@ -2101,6 +2101,9 @@ export function setGhostSessionRevealer(reveal: ((sessionId: string) => void) |
const pluginTargetSlot = new PluginTargetSlot();
export function setPluginTargetAdapter(adapter: PluginTargetAdapter): void { pluginTargetSlot.adapter = adapter; }
+export async function assertPluginTargetQueuedDelivery(taskId: string, clientId: string): Promise<void> {
+ await pluginTargetSlot.assertQueuedDelivery(taskId, clientId);
+}
let pluginTaskHandler: PluginTaskHandler | null = null;
export function setPluginTaskHandler(handler: PluginTaskHandler | null): void { pluginTaskHandler = handler; }
@@ -2125,6 +2128,11 @@ export function pluginTaskAuthorizationRevision(id: string): string | null {
? ghost.approval.revision : null;
}
+export function pluginTargetAuthorizationRevision(id: string): string | null {
+ const ghost = findGhostForInstanceId(id);
+ return hasPluginTargetApproval(ghost) ? pluginTaskAuthorizationRevision(id) : null;
+}
+
export function isPluginTaskAuthorized(id: string): boolean {
const ghost = findGhostForInstanceId(id);
return hasPluginTaskApproval(ghost);
@@ -6909,6 +6917,7 @@ async function installAndDockLocked(
// 则走 manager.update 延续既有状态。保留 false 缺省以兼容内部受控调用方。
const result = await manager.install(lizFilePath, {
taskCapabilityApproved: confirmedTaskCapability(opts.consent.decision, installedBefore, opts.consent.manifest),
+ targetCapabilityApproved: confirmedTaskCapability(opts.consent.decision, installedBefore, opts.consent.manifest, 'targets'),
initiallyEnabled: opts.enable ?? false,
expectedPackageSha256: opts.expectedPackageSha256,
...(opts.trustOverride ? { trustOverride: opts.trustOverride } : {}),
@@ -7100,6 +7109,7 @@ async function updateLocalGhostPackageLocked(
() =>
manager.update(cindyFilePath, {
taskCapabilityApproved: confirmedTaskCapability(consent, previousGhost, inspected.manifest),
+ targetCapabilityApproved: confirmedTaskCapability(consent, previousGhost, inspected.manifest, 'targets'),
expectedPackageSha256,
expectedInstalledApproval,
installOrigin: installOrigin ?? 'manual',
@@ -7569,6 +7579,7 @@ async function installOrUpdateMarketGhostPackageLocked(
result = await withActiveOwnerGhostOauthMutationLock(installedGhostStoragePart(installed), () =>
manager.update(cindyFilePath, {
taskCapabilityApproved: confirmedTaskCapability(expected.consent, installed, inspected.manifest),
+ targetCapabilityApproved: confirmedTaskCapability(expected.consent, installed, inspected.manifest, 'targets'),
expectedPackageSha256: inspected.packageSha256,
expectedInstalledApproval: expected.expectedInstalledApproval!,
...(expected.sourceChanged ? { sourceStateArchiveId: ghostSourceStateArchiveId(installed) } : {}),
@@ -8666,29 +8677,39 @@ export function registerGhostIpc(): void {
!event.sender.isDestroyed() && ghostIdForLogicWebContents(event.sender.id) === id && (!pageCurrent || pageCurrent());
};
if (type === 'targets-request' && pageId !== undefined) throw new Error('UNSUPPORTED_CAPABILITY');
+ if (type === 'targets-request' && findGhostForInstanceId(id)?.manifest.agent?.targets !== true) {
+ return { ok: false, error: { code: 'PERMISSION_DENIED', message: 'PERMISSION_DENIED', retryable: false } };
+ }
+ const confirmCapability = (facts: GhostInstallConsentFacts) => {
+ const pageId = (payload as { mobilePageId?: string }).mobilePageId;
+ if (pageId) {
+ const permissions = facts.kind === 'update' ? facts.added : facts.permissions;
+ const interpolate = (key: string, args: Record<string, string> = {}) => Object.entries(args).reduce((value, [name, replacement]) => value.replaceAll(`{{${name}}}`, replacement), t(key));
+ return showMobilePluginTaskPermission(id, pageId, {
+ title: t('settings.ghosts.installConsent.addedTitle'), message: '',
+ detail: permissions.map(item => [interpolate(`settings.ghosts.perm.${item.labelKey}`, item.labelArgs), item.detailKey ? interpolate(`settings.ghosts.perm.${item.detailKey}`, item.detailArgs) : item.detail].filter(Boolean).join('\n')).join('\n\n'),
+ allow: t('settings.ghosts.connections.confirmAllow'), cancel: t('settings.ghosts.installConsent.cancel'),
+ });
+ }
+ const window = getDeepLinkMainWindow();
+ if (!window || !isTrustedAppRendererWindow(window)) return Promise.resolve(false);
+ return createWindowGhostInstallConsentPrompt(window.webContents)({ purpose: 'task-capability', initiator: 'user', origin: 'local-file', facts });
+ };
const result = await handlePluginTaskRequest(id, type === 'targets-request' ? { type: 'tasks-request', kind: 'capabilities' } : payload, {
- getGhost: findGhostForInstanceId, handler: pluginTaskHandler,
- isCurrent,
- ensureAuthorized: () => requestPluginTaskApproval(id, isCurrent, facts => {
- const pageId = (payload as { mobilePageId?: string }).mobilePageId;
- if (pageId) {
- const permissions = facts.kind === 'update' ? facts.added : facts.permissions;
- const interpolate = (key: string, args: Record<string, string> = {}) => Object.entries(args).reduce((value, [name, replacement]) => value.replaceAll(`{{${name}}}`, replacement), t(key));
- return showMobilePluginTaskPermission(id, pageId, {
- title: t('settings.ghosts.installConsent.addedTitle'), message: '',
- detail: permissions.map(item => [interpolate(`settings.ghosts.perm.${item.labelKey}`, item.labelArgs), item.detailKey ? interpolate(`settings.ghosts.perm.${item.detailKey}`, item.detailArgs) : item.detail].filter(Boolean).join('\n')).join('\n\n'),
- allow: t('settings.ghosts.connections.confirmAllow'), cancel: t('settings.ghosts.installConsent.cancel'),
- });
- }
- const window = getDeepLinkMainWindow();
- if (!window || !isTrustedAppRendererWindow(window)) return Promise.resolve(false);
- return createWindowGhostInstallConsentPrompt(window.webContents)({ purpose: 'task-capability', initiator: 'user', origin: 'local-file', facts });
- }),
+ getGhost: findGhostForInstanceId, handler: pluginTaskHandler, isCurrent,
+ ensureAuthorized: () => requestPluginTaskApproval(id, isCurrent, confirmCapability),
});
if (type !== 'targets-request' || !result.ok) return result;
- const revision = pluginTaskAuthorizationRevision(id);
+ try {
+ if (!await requestPluginTaskApproval(id, isCurrent, confirmCapability, false, 'targets')) {
+ return { ok: false, error: { code: 'PERMISSION_DENIED', message: 'PERMISSION_DENIED', retryable: false } };
+ }
+ } catch {
+ return { ok: false, error: { code: 'PERMISSION_DENIED', message: 'PERMISSION_DENIED', retryable: false } };
+ }
+ const revision = pluginTargetAuthorizationRevision(id);
const assertAuthorized = () => {
- if (!isCurrent() || !revision || pluginTaskAuthorizationRevision(id) !== revision || !isPluginTaskAuthorized(id))
+ if (!isCurrent() || !revision || pluginTargetAuthorizationRevision(id) !== revision)
throw Object.assign(new Error('PERMISSION_DENIED'), { code: 'PERMISSION_DENIED' });
};
try { return { ok: true, data: await pluginTargetSlot.handle(id, payload, assertAuthorized) }; }
diff --git a/apps/desktop/src/main/cindy-brain/pluginTargetSlot.ts b/apps/desktop/src/main/cindy-brain/pluginTargetSlot.ts
index 45ae9501e3..2185a756ac 100644
--- a/apps/desktop/src/main/cindy-brain/pluginTargetSlot.ts
+++ b/apps/desktop/src/main/cindy-brain/pluginTargetSlot.ts
@@ -8,26 +8,30 @@ import type {
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 { getActiveDataOwnerPushStamp, activeOwnerScopeKey } from '../appSessionState.js';
import { parsePluginMessageAttachments, type PluginMessageImage } from '../cindy-media/pluginMessageAttachments.js';
-interface Receipt {
+export interface PluginTargetReceipt {
+ id: string;
+ pluginId: string;
+ requestKey: string;
hash: string | null;
- clientId: string;
taskId?: string;
+ target?: PluginTargetRef;
+ approvalRevision?: string;
status: 'pending' | 'accepted' | 'cancelled';
delivery?: PluginTargetDelivery;
}
-interface Ledger {
- receipts: Record<string, Receipt>;
+export interface PluginTargetStore {
+ get(pluginId: string, requestKey: string): Promise<PluginTargetReceipt | undefined>;
+ getById(id: string): Promise<PluginTargetReceipt | undefined>;
+ reserve(receipt: PluginTargetReceipt): Promise<boolean>;
+ cancel(pluginId: string, requestKey: string): Promise<PluginTargetReceipt>;
+ accept(id: string, delivery: PluginTargetDelivery): Promise<void>;
}
export interface PluginTargetAdapter {
+ store(): PluginTargetStore;
+ approvalRevision(pluginId: string): string | null;
candidates(kind: PluginTargetKind): Promise<PluginTargetCandidate[]>;
create(
pluginId: string,
@@ -61,28 +65,26 @@ const isTarget = (value: unknown): value is PluginTargetRef => {
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-target-deliveries.json'),
- scopeKey: activeOwnerScopeKey,
- defaults: { receipts: {} },
- normalize: (raw) => {
- const value = raw as Ledger | null;
- return { receipts: value?.receipts && typeof value.receipts === 'object' ? value.receipts : {} };
- },
- log: desktopMakerLogger.child('plugin-target-deliveries'),
- label: 'plugin-target-deliveries',
- preserveUnreadableFile: true,
- logLoadedValue: false,
- logReadErrorDetails: false,
-});
/** UI and fixed target configuration belong to plugins; the Host validates and delivers. */
export class PluginTargetSlot {
adapter: PluginTargetAdapter | null = null;
- 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().receipts[key];
+ private inFlight = new Map<string, { hash: string; cancelled: boolean; result?: Promise<unknown> }>();
+ /** Used by the existing queue acceptance boundary, including restored snapshots. */
+ async assertQueuedDelivery(taskId: string, clientId: string): Promise<void> {
+ if (!this.adapter) fail('HOST_NOT_READY');
+ const adapter = this.adapter!;
+ const store = adapter.store();
+ const receipt = await store.getById(clientId);
+ const assertReceipt = (current: PluginTargetReceipt | undefined) => {
+ if (!receipt?.target || !current || current.status === 'cancelled' || current.taskId !== taskId ||
+ current.hash !== receipt.hash || !current.approvalRevision ||
+ adapter.approvalRevision(current.pluginId) !== current.approvalRevision) fail('PERMISSION_DENIED');
+ };
+ assertReceipt(receipt);
+ const target = receipt!.target!;
+ if (!(await adapter.candidates(target.kind)).some(item => item.id === target.id)) fail('TARGET_UNAVAILABLE');
+ if (target.kind !== 'project' && await adapter.session(target.kind, target.id) !== taskId) fail('TARGET_UNAVAILABLE');
+ assertReceipt(await store.getById(clientId));
}
async handle(pluginId: string, raw: unknown, authorized: () => void): Promise<unknown> {
authorized();
@@ -109,28 +111,21 @@ export class PluginTargetSlot {
return resolve(request.target);
}
if (!keyString(request.requestKey)) return fail('INVALID_PARAMS');
- // 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 store = adapter.store();
const runtimeKey = JSON.stringify([
- activeOwnerScopeKey(), getActiveDataOwnerPushStamp().ownerGeneration, receiptKey,
+ activeOwnerScopeKey(), getActiveDataOwnerPushStamp().ownerGeneration, pluginId, request.requestKey,
]);
if (request.kind === 'cancel') {
- 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',
- } } };
- });
+ const pending = this.inFlight.get(runtimeKey);
+ if (pending) pending.cancelled = true;
+ const receipt = await store.cancel(pluginId, request.requestKey);
authorized();
- if (previous?.taskId) {
+ if (receipt.taskId) {
// Withdraw only this plugin input. Never stop another user's running turn.
- await adapter.withdraw(previous.taskId, previous.clientId, authorized);
+ await adapter.withdraw(receipt.taskId, receipt.id, authorized);
authorized();
}
- return { cancelled: true, runningWorkMayHaveStarted: !!previous?.taskId };
+ return { cancelled: true, runningWorkMayHaveStarted: !!receipt.taskId };
}
if (
!isTarget(request.target) ||
@@ -159,49 +154,46 @@ export class PluginTargetSlot {
.update(JSON.stringify([target.kind, target.id, request.text, request.title, route, delivery,
images.map(({ hash, name }) => [hash, name])]))
.digest('hex');
- const guard = () => {
- authorized();
- if (this.cancelled.has(runtimeKey) || this.readReceipt(receiptKey)?.status === 'cancelled')
- fail('SUPERSEDED');
- };
- guard();
const pending = this.inFlight.get(runtimeKey);
if (pending) {
+ if (pending.cancelled) return fail('SUPERSEDED');
if (pending.hash !== hash) return fail('REQUEST_KEY_CONFLICT');
- return pending.result;
+ return pending.result!;
}
+ const operation = { hash, cancelled: false, result: undefined as Promise<unknown> | undefined };
+ const guard = () => {
+ authorized();
+ if (operation.cancelled) fail('SUPERSEDED');
+ };
+ const replay = (previous: PluginTargetReceipt) => {
+ if (previous.status === 'cancelled') return fail('SUPERSEDED');
+ if (previous.hash !== hash) return fail('REQUEST_KEY_CONFLICT');
+ if (previous.status === 'accepted')
+ return { taskId: previous.taskId, accepted: true, delivery: previous.delivery };
+ return fail('DELIVERY_UNCERTAIN');
+ };
const deliver = async () => {
- 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 existing = await store.get(pluginId, request.requestKey);
+ guard();
+ if (existing) return replay(existing);
const candidate = await resolve(target);
guard();
- const receipt: Receipt = {
- hash, clientId: randomUUID(), status: 'pending',
+ const approvalRevision = adapter.approvalRevision(pluginId);
+ if (!approvalRevision) return fail('PERMISSION_DENIED');
+ const receipt: PluginTargetReceipt = {
+ id: `plugin-target:${randomUUID()}`, pluginId, requestKey: request.requestKey,
+ hash, target, approvalRevision, 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 } };
- });
+ // A per-key reservation uses the existing receipt DB, never a whole-history rewrite.
+ const reserved = await store.reserve(receipt);
guard();
+ if (!reserved) return replay((await store.get(pluginId, request.requestKey))!);
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');
+ await this.assertQueuedDelivery(taskId, receipt.id);
guard();
};
await validateTarget();
@@ -209,25 +201,21 @@ export class PluginTargetSlot {
await adapter.create(pluginId, target.id, taskId, request.title || candidate.label, route, guard);
guard();
const actualDelivery = await adapter.send(
- pluginId, taskId, receipt.clientId, request.text, guard, validateTarget, delivery, images,
+ pluginId, taskId, receipt.id, request.text, guard, validateTarget, delivery, images,
);
- 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 (this.cancelled.has(runtimeKey) || this.readReceipt(receiptKey)?.status === 'cancelled') {
- await adapter.withdraw(taskId, receipt.clientId, authorized);
+ await store.accept(receipt.id, actualDelivery);
+ authorized();
+ const current = await store.getById(receipt.id);
+ authorized();
+ if (operation.cancelled || current?.status === 'cancelled') {
+ await adapter.withdraw(taskId, receipt.id, authorized);
return fail('SUPERSEDED');
}
return { taskId, accepted: true, delivery: actualDelivery };
};
- const result = deliver().finally(() => this.inFlight.delete(runtimeKey));
- this.inFlight.set(runtimeKey, { hash, result });
- return result;
+ operation.result = deliver().finally(() => this.inFlight.delete(runtimeKey));
+ this.inFlight.set(runtimeKey, operation);
+ return operation.result;
}
}
diff --git a/apps/desktop/src/main/cindy-brain/remotePluginManagement.ts b/apps/desktop/src/main/cindy-brain/remotePluginManagement.ts
index 97da1af631..d6a9242206 100644
--- a/apps/desktop/src/main/cindy-brain/remotePluginManagement.ts
+++ b/apps/desktop/src/main/cindy-brain/remotePluginManagement.ts
@@ -106,6 +106,7 @@ export function projectManagedGhost(g: InstalledGhost): InstalledGhost {
builtin: g.builtin,
retirement: g.retirement,
taskCapabilityApproved: g.taskCapabilityApproved,
+ targetCapabilityApproved: g.targetCapabilityApproved,
oauthScopeStale: g.oauthScopeStale,
oauthAuthorizationExpired: g.oauthAuthorizationExpired,
};
diff --git a/apps/desktop/src/main/cindy-brain/taskCapability.ts b/apps/desktop/src/main/cindy-brain/taskCapability.ts
index 44f1c26ef2..8a79dba6c9 100644
--- a/apps/desktop/src/main/cindy-brain/taskCapability.ts
+++ b/apps/desktop/src/main/cindy-brain/taskCapability.ts
@@ -29,6 +29,10 @@ export function hasPluginTaskApproval(ghost: InstalledGhost | null | undefined):
);
}
+export function hasPluginTargetApproval(ghost: InstalledGhost | null | undefined): boolean {
+ return hasPluginTaskApproval(ghost) && ghost?.manifest.agent?.targets === true && ghost.targetCapabilityApproved === true;
+}
+
/** Reuse Host permission UI; no plugin-supplied confirmation or manifest flag is authority. */
export async function ensurePluginTaskApproval(
id: string,
@@ -38,19 +42,21 @@ export async function ensurePluginTaskApproval(
confirm(facts: GhostInstallConsentFacts): Promise<boolean>;
approve(id: string, revision: string, isCurrent: () => boolean): Promise<boolean>;
},
+ capability: 'tasks' | 'targets' = 'tasks',
): Promise<boolean> {
const ghost = deps.getGhost(id);
if (!deps.isCurrent()) return false;
- if (hasPluginTaskApproval(ghost)) return true;
+ if ((capability === 'targets' ? hasPluginTargetApproval : hasPluginTaskApproval)(ghost)) return true;
if (
!ghost?.enabled ||
ghost.manifest.agent?.tasks !== true ||
- ghost.approval?.state !== 'approved'
+ ghost.approval?.state !== 'approved' ||
+ (capability === 'targets' && (!hasPluginTaskApproval(ghost) || ghost.manifest.agent.targets !== true))
)
return false;
const revision = ghost.approval.revision;
const permissions = ghostPermissionItems(ghost.manifest).filter((item) => item.kind !== 'tool');
- const added = permissions.filter((item) => item.key === 'agent:tasks');
+ const added = permissions.filter((item) => item.key === `agent:${capability}`);
if (added.length !== 1) return false;
const confirmed = await deps.confirm({
kind: 'update',
diff --git a/apps/desktop/src/main/localDb/schema.ts b/apps/desktop/src/main/localDb/schema.ts
index 1a058a8c31..b4d0bdad74 100644
--- a/apps/desktop/src/main/localDb/schema.ts
+++ b/apps/desktop/src/main/localDb/schema.ts
@@ -2381,7 +2381,7 @@ export const sessionTaskTags = sqliteTable(
export const pluginTaskRequests = sqliteTable('plugin_task_requests', {
id: text('id').primaryKey(),
pluginId: text('plugin_id').notNull(),
- operation: text('operation', { enum: ['create', 'send'] }).notNull(),
+ operation: text('operation', { enum: ['create', 'send', 'target'] }).notNull(),
targetId: text('target_id').notNull(),
requestKey: text('request_key').notNull(),
fingerprint: text('fingerprint').notNull(),
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts
index 8dda3db472..846e8066aa 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts
@@ -166,6 +166,32 @@ function fixture() {
};
}
+// Targets create in a selected project through the same service, not directly through
+// session persistence. Without its create receipt, helper tools and uninstall lose ownership.
+// Minimal regression: a Host-supplied task ID + project, then get and uninstall (unit).
+it('retains task ownership and uninstall revocation for Host-selected project creation', async () => {
+ const f = fixture();
+ const context = { taskId: 'target-project-task', workingDir: '/selected-project', assertCurrent: vi.fn() };
+ const task = await f.service.create('p', { requestKey: 'target-create', title: 'Selected project' }, context);
+ expect(task.taskId).toBe(context.taskId);
+ expect(await f.service.get('p', context.taskId)).toMatchObject({ taskId: context.taskId });
+ expect(f.rows.get(context.taskId)).toMatchObject({ operation: 'create', pluginId: 'p' });
+ expect(vi.mocked(f.deps.createSession).mock.calls[0]?.[9]).toBe(context);
+ await f.service.withUninstall('p', async () => {});
+ await expect(f.service.get('p', context.taskId)).rejects.toMatchObject({ code: 'TASK_NOT_FOUND' });
+});
+it('rechecks Host target context after route resolution before persisting a task', async () => {
+ const f = fixture();
+ let current = true;
+ vi.mocked(f.deps.resolveRoute).mockImplementationOnce(async () => { current = false; return f.route; });
+ await expect(f.service.create('p', { requestKey: 'target-create', title: 'Selected project' }, {
+ taskId: 'target-project-task', workingDir: '/selected-project',
+ assertCurrent: () => { if (!current) throw new PluginTaskError('PERMISSION_DENIED', 'Target changed'); },
+ })).rejects.toMatchObject({ code: 'PERMISSION_DENIED' });
+ expect(f.tasks.size).toBe(0);
+ expect(f.rows.size).toBe(0);
+});
+
it('includes message images in owned-task replay identity without persisting screenshot bytes', async () => {
const f = fixture(), task = await f.create();
const base64 = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]).toString('base64');
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskStorePagination.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskStorePagination.test.ts
index 54238b2df1..7c6c93a162 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskStorePagination.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskStorePagination.test.ts
@@ -3,6 +3,7 @@ import { drizzle } from 'drizzle-orm/better-sqlite3';
import { expect, it } from 'vitest';
import type { DbClient } from '../../localDb/client/DbClient.js';
import { createPluginTaskStore } from '../pluginTaskStore.js';
+import { createPluginTargetStore } from '../pluginTargetStore.js';
import { createPluginTaskService } from '../pluginTaskService.js';
it.each(['absent', 'raw session', 'revoked', 'changed revision', 'other plugin', 'send'] as const)(
@@ -82,3 +83,48 @@ it('pages by creation time and ID without losing later records with smaller UUID
}
} finally { sqlite.close(); }
});
+
+// Production receipt store: indexed per-key SQLite writes must preserve cancellation
+// across restarts/late ACKs. Existing owned-task tests do not cover target reservations.
+// Minimal input: reserve one key, cancel, accept late, then reopen the store (unit, :memory:).
+it('retains target cancellation and request identities without replacing unrelated receipts', async () => {
+ const sqlite = new Database(':memory:');
+ try {
+ sqlite.exec(`CREATE TABLE plugin_task_requests(id TEXT PRIMARY KEY, plugin_id TEXT,
+ operation TEXT, target_id TEXT, request_key TEXT, fingerprint TEXT, payload TEXT,
+ revision INTEGER, created_at INTEGER);
+ CREATE UNIQUE INDEX plugin_task_request_key ON plugin_task_requests(plugin_id, operation, target_id, request_key)`);
+ const db = { drizzle: drizzle(sqlite) } as unknown as DbClient;
+ const store = createPluginTargetStore(db, () => {});
+ const receipt = { id: 'plugin-target:first', pluginId: 'p', requestKey: 'key', hash: 'hash',
+ status: 'pending' as const, taskId: 'task', target: { kind: 'task' as const, id: 'task' }, approvalRevision: 'approved' };
+ expect(await store.reserve(receipt)).toBe(true);
+ expect(await store.reserve({ ...receipt, id: 'plugin-target:duplicate' })).toBe(false);
+ const other = { ...receipt, id: 'plugin-target:other', pluginId: 'other-plugin' };
+ expect(await store.reserve(other)).toBe(true);
+ await store.accept(other.id, 'queue');
+ const before = sqlite.prepare('SELECT * FROM plugin_task_requests WHERE id = ?').get(other.id);
+ await store.cancel('p', 'key');
+ await store.accept(receipt.id, 'steer');
+ const restarted = createPluginTargetStore(db, () => {});
+ expect(await restarted.get('p', 'key')).toEqual({ ...receipt, status: 'cancelled' });
+ expect(await restarted.getById(other.id)).toMatchObject({ ...other, status: 'accepted', delivery: 'queue' });
+ expect(sqlite.prepare('SELECT * FROM plugin_task_requests WHERE id = ?').get(other.id)).toEqual(before);
+ // Cancel-before-send stays cancelled, and repeated cancellation retains the original identity.
+ const cancelled = await restarted.cancel('p', 'early');
+ expect(await restarted.cancel('p', 'early')).toEqual(cancelled);
+ expect(await restarted.reserve({ ...receipt, id: 'plugin-target:late', requestKey: 'early' })).toBe(false);
+ expect((await restarted.get('p', 'early'))?.status).toBe('cancelled');
+ } finally { sqlite.close(); }
+});
+it('rejects a target-store write against a stale account snapshot before mutation', async () => {
+ const sqlite = new Database(':memory:');
+ try {
+ const store = createPluginTargetStore({ drizzle: drizzle(sqlite) } as unknown as DbClient,
+ () => { throw new Error('Owner changed'); });
+ await expect(store.cancel('p', 'key')).rejects.toThrow('Owner changed');
+ await expect(store.reserve({ id: 'id', pluginId: 'p', requestKey: 'key', hash: 'hash', status: 'pending' }))
+ .rejects.toThrow('Owner changed');
+ // There is deliberately no table: a SQL operation would fail with a different error.
+ } finally { sqlite.close(); }
+});
diff --git a/apps/desktop/src/main/maker-ipc/pluginTargetStore.ts b/apps/desktop/src/main/maker-ipc/pluginTargetStore.ts
new file mode 100644
index 0000000000..e77c8ebf25
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/pluginTargetStore.ts
@@ -0,0 +1,53 @@
+import { randomUUID } from 'node:crypto';
+import { and, eq, sql } from 'drizzle-orm';
+import type { DbClient } from '../localDb/client/DbClient.js';
+import { pluginTaskRequests } from '../localDb/schema.js';
+import type { PluginTargetReceipt, PluginTargetStore } from '../cindy-brain/pluginTargetSlot.js';
+
+/** Reuse the receipt table and unique request index; target rows confer no task ownership. */
+export function createPluginTargetStore(db: DbClient, assertCurrent: () => void): PluginTargetStore {
+ const table = pluginTaskRequests;
+ const read = async (where: ReturnType<typeof and>) => {
+ assertCurrent();
+ const [row] = await db.drizzle.select().from(table)
+ .where(and(eq(table.operation, 'target'), where)).limit(1);
+ assertCurrent();
+ return row ? { ...JSON.parse(row.payload), id: row.id, pluginId: row.pluginId,
+ requestKey: row.requestKey } as PluginTargetReceipt : undefined;
+ };
+ const values = (receipt: PluginTargetReceipt) => ({
+ id: receipt.id, pluginId: receipt.pluginId, operation: 'target' as const,
+ targetId: '', requestKey: receipt.requestKey, fingerprint: receipt.hash ?? '',
+ payload: JSON.stringify(receipt), revision: 0, createdAt: Date.now(),
+ });
+ return {
+ get: (pluginId, key) => read(and(eq(table.pluginId, pluginId), eq(table.targetId, ''), eq(table.requestKey, key))),
+ getById: id => read(eq(table.id, id)),
+ reserve: async receipt => {
+ assertCurrent();
+ const inserted = await db.drizzle.insert(table).values(values(receipt))
+ .onConflictDoNothing().returning({ id: table.id });
+ assertCurrent();
+ return inserted.length > 0;
+ },
+ cancel: async (pluginId, requestKey) => {
+ assertCurrent();
+ const [row] = await db.drizzle.insert(table).values(values({
+ id: `plugin-target:${randomUUID()}`, pluginId, requestKey, hash: null, status: 'cancelled',
+ })).onConflictDoUpdate({
+ target: [table.pluginId, table.operation, table.targetId, table.requestKey],
+ set: { payload: sql`json_set(${table.payload}, '$.status', 'cancelled')`, revision: sql`${table.revision} + 1` },
+ }).returning();
+ assertCurrent();
+ return { ...JSON.parse(row!.payload), id: row!.id, pluginId, requestKey };
+ },
+ accept: async (id, delivery) => {
+ assertCurrent();
+ await db.drizzle.update(table).set({
+ payload: sql`json_set(${table.payload}, '$.status', 'accepted', '$.delivery', ${delivery})`,
+ revision: sql`${table.revision} + 1`,
+ }).where(and(eq(table.id, id), eq(table.operation, 'target'), sql`json_extract(${table.payload}, '$.status') != 'cancelled'`));
+ assertCurrent();
+ },
+ };
+}
diff --git a/apps/desktop/src/main/maker-ipc/pluginTaskService.ts b/apps/desktop/src/main/maker-ipc/pluginTaskService.ts
index c578a97c1f..8ddde2428b 100644
--- a/apps/desktop/src/main/maker-ipc/pluginTaskService.ts
+++ b/apps/desktop/src/main/maker-ipc/pluginTaskService.ts
@@ -14,7 +14,7 @@ import {
export interface PluginTaskReceipt {
id: string;
pluginId: string;
- operation: 'create' | 'send';
+ operation: 'create' | 'send' | 'target';
targetId: string;
requestKey: string;
fingerprint: string;
@@ -95,6 +95,12 @@ const hash = (data: unknown) => createHash('sha256').update(JSON.stringify(data,
? Object.fromEntries(Object.keys(value).sort().map(key => [key, value[key]]))
: value,
)).digest('hex');
+/** Main-only context; never populated from tasks.create's wire request. */
+export interface PluginTaskCreateContext {
+ taskId: string;
+ workingDir: string;
+ assertCurrent(): void;
+}
export interface PluginTaskServiceDeps {
store: PluginTaskStore;
/** Bound to the captured account/database epoch and plugin availability. */
@@ -115,6 +121,7 @@ export interface PluginTaskServiceDeps {
callId?: string,
/** Background task: the Session row is inserted with hidden_at set (never flashes into lists). */
hidden?: boolean,
+ targetContext?: PluginTaskCreateContext,
): Promise<void>;
/**
* Re-checks `agent.hiddenTasks` (with tasks) for this plugin; throws PERMISSION_DENIED.
@@ -302,14 +309,16 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {
create: (
pluginId: string,
request: { requestKey: string; title: string; route?: PluginTaskRoute; isolatedWorkspace?: boolean; callId?: string; hidden?: boolean },
+ targetContext?: PluginTaskCreateContext,
) =>
exclusive(async () => {
+ targetContext?.assertCurrent();
deps.assertAuthorized(pluginId);
const hidden = request.hidden === true;
if (hidden) assertHiddenTasksAllowed(pluginId);
// hidden:false is the default; only a background request changes the fingerprint,
// so existing visible receipts replay unchanged.
- const input = [request.title, request.route ?? null, ...(request.isolatedWorkspace ? [true] : []), ...(request.callId ? [{ callId: request.callId }] : []), ...(hidden ? [{ hidden: true }] : [])];
+ const input = [request.title, request.route ?? null, ...(request.isolatedWorkspace ? [true] : []), ...(request.callId ? [{ callId: request.callId }] : []), ...(hidden ? [{ hidden: true }] : []), ...(targetContext ? [{ workingDir: targetContext.workingDir }] : [])];
const fingerprint = hash(input);
let row = replay(
await deps.store.find(pluginId, 'create', '', request.requestKey),
@@ -323,7 +332,8 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {
}
const route = await deps.resolveRoute(pluginId, request.route, request.callId);
deps.assertCurrent();
- const taskId = id();
+ targetContext?.assertCurrent();
+ const taskId = targetContext?.taskId ?? id();
row = newReceipt(
pluginId,
'create',
@@ -339,7 +349,11 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {
deps.assertCurrent();
const onPersistenceStarted = () => { persistenceStarted = true; };
// Visible creation keeps its original call shape; only background tasks add the flag.
- if (hidden) {
+ if (targetContext) {
+ targetContext.assertCurrent();
+ await deps.createSession(pluginId, taskId, request.title, route, undefined, request.route,
+ onPersistenceStarted, undefined, undefined, targetContext);
+ } else if (hidden) {
assertHiddenTasksAllowed(pluginId);
await deps.createSession(pluginId, taskId, request.title, route, request.isolatedWorkspace, request.route,
onPersistenceStarted, request.callId, true);
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index b8900930fc..f4c0f9df06 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -15,8 +15,9 @@ import { isSessionHiddenSync } from '../localDb/hiddenSessionRegistry.js';
import { ghostDeclaresHiddenTasks } from '../../shared/ghost.js';
import { hasAcceptedUserTaskInput } from './pluginTaskInput.js';
import { controlOwnedSessionExecution, isSameSessionExecution, withdrawOwnedSessionInputs } from './sessionExecutionOwnership.js';
-import { showMobilePluginTaskPermission, setPluginTaskHandler, setPluginTargetAdapter, getPluginTaskSourceSessionId, setPluginTaskUninstaller, setPluginTaskRelocator, isPluginTaskAuthorized, getPluginTaskInstallRevision, pluginTaskAuthorizationRevision } from '../cindy-brain/index.js';
+import { showMobilePluginTaskPermission, setPluginTaskHandler, setPluginTargetAdapter, assertPluginTargetQueuedDelivery, getPluginTaskSourceSessionId, setPluginTaskUninstaller, setPluginTaskRelocator, pluginTargetAuthorizationRevision, isPluginTaskAuthorized, getPluginTaskInstallRevision, pluginTaskAuthorizationRevision } from '../cindy-brain/index.js';
import { listPluginTargetCandidates, resolvePluginTargetSession } from './pluginTargetCandidates.js';
+import { createPluginTargetStore } from './pluginTargetStore.js';
import { collectPluginAttachmentPayloadTexts, withPluginMessageAttachments } from '../cindy-media/pluginMessageAttachments.js';
import type { PluginTaskRoute, PluginTaskRequest } from '../../shared/pluginTasks.js';
import { createHash as pluginTaskConfigHash } from 'node:crypto';
@@ -12774,10 +12775,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
assertCurrent();
if (workers.length || reservations.length) throw new PluginTaskError('TASK_BUSY', 'Register the team plan before creating Workers');
},
- createSession: async (pluginId, taskId, title, route, isolatedWorkspace, requestedRoute, onPersistenceStarted, callId, hidden) => {
+ createSession: async (pluginId, taskId, title, route, isolatedWorkspace, requestedRoute, onPersistenceStarted, callId, hidden, targetContext) => {
assertPlugin(pluginId);
const cfg = readPluginTaskConfig(pluginId);
const configurationIsCurrent = () => {
+ targetContext?.assertCurrent();
const current = readPluginTaskConfig(pluginId);
return current.workingDir === cfg.workingDir && current.permissionMode === cfg.permissionMode
&& current.agentKind === cfg.agentKind && current.model === cfg.model
@@ -12790,7 +12792,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const currentRoute = await resolveRoute(pluginId, requestedRoute, callId);
if ((Object.keys(currentRoute) as Array<keyof PluginTaskRoute>).some(key => currentRoute[key] !== route[key]))
throw new PluginTaskError('ROUTE_UNAVAILABLE', 'Plugin task route changed');
- const workingDir = !isolatedWorkspace && cfg.workingDir
+ const workingDir = targetContext?.workingDir ?? (!isolatedWorkspace && cfg.workingDir
? await resolvePluginWorkerDirectory({
requested: cfg.workingDir, configuredDirectory: cfg.workingDir,
isPickedDirectory: () => false,
@@ -12799,7 +12801,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (!configurationIsCurrent()) throw new PluginTaskError('PERMISSION_DENIED', 'Plugin task configuration changed');
},
})
- : undefined;
+ : undefined);
assertPlugin(pluginId);
if (!configurationIsCurrent()) throw new PluginTaskError('PERMISSION_DENIED', 'Plugin task configuration changed');
await createPluginTaskSession({
@@ -12856,8 +12858,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const validate = async () => { assertPlugin(pluginId); await pluginTaskServiceForCurrentOwner!().assertDispatch(pluginId, taskId); assertPlugin(pluginId); };
return withPluginMessageAttachments(images, () => assertPlugin(pluginId), async files => {
await validate();
- const outcome = await sendToSessionInternal({ targetSessionId: taskId, clientId, message: text, files,
- autoReviewUserText: { kind: 'delegated-continuation' }, forceQueue: true,
+ const outcome = await sendToSessionInternal({ targetSessionId: taskId, clientId,
+ message: text, autoReviewUserText: { kind: 'delegated-continuation' }, forceQueue: true, files,
sourcePlugin: { pluginId, ...(pluginName ? { name: pluginName } : {}) },
authorizationGuard: { validate, assertCurrent: () => assertPlugin(pluginId) }, onAccepted: validate });
await awaitAgentInputQueueSnapshotPersistence(taskId);
@@ -13219,24 +13221,22 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
};
setPluginTaskHandler(handlePluginTask);
setPluginTargetAdapter({
+ store: () => {
+ const snapshot = getCurrentDbClientSnapshot();
+ if (!snapshot) throw new Error('HOST_NOT_READY');
+ return createPluginTargetStore(snapshot.client, () => {
+ if (getCurrentDbClientSnapshot() !== snapshot) throw new Error('PERMISSION_DENIED');
+ });
+ },
+ approvalRevision: pluginTargetAuthorizationRevision,
candidates: listPluginTargetCandidates,
session: resolvePluginTargetSession,
create: async (pluginId, project, taskId, title, route, guard) => {
guard();
- const snapshot = getCurrentDbClientSnapshot();
- const config = readPluginTaskConfig(pluginId);
- const configSnapshot = JSON.stringify(config);
- const guardCreate = () => { guard(); if (JSON.stringify(readPluginTaskConfig(pluginId)) !== configSnapshot) throw new Error('STALE_REVISION'); };
- const execution = await resolveSessionExecution({ ...config, ...route });
- guardCreate();
- await createPluginTaskSession({ ghostId: pluginId, sessionId: taskId, title,
- ...execution, agentKind: execution.agentKind === 'claude-code' ? 'cc' : execution.agentKind,
- permissionMode: clampPluginTaskPermissionMode(config.permissionMode), workingDir: project,
- shouldContinue: () => { guardCreate(); return getCurrentDbClientSnapshot() === snapshot; },
- notifySessionCreated: ({ sessionId, workdir }) => {
- notifyGhostSessionEvent('created', { sessionId, workdir }); broadcastSessionCreated(sessionId);
- },
- });
+ await pluginTaskServiceForCurrentOwner!().create(pluginId, {
+ requestKey: `target-project:${taskId}`, title, route,
+ }, { taskId, workingDir: project, assertCurrent: guard });
+ guard();
},
send: async (pluginId, taskId, clientId, text, guard, validateTarget, delivery, images = []) => {
guard();
@@ -18256,6 +18256,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
orcaInterAgentDispatcher.discardQueuedOrcaInterAgentAcceptedCallback(item.clientId);
},
onAcceptedQueuedMessage: async (sessionId, item, restoredFromSnapshot): Promise<void> => {
+ if (item.clientId.startsWith('plugin-target:')) {
+ try { await assertPluginTargetQueuedDelivery(sessionId, item.clientId); }
+ catch { throw new AcceptedCallbackDispatchCancelled('Plugin target delivery is no longer authorized'); }
+ }
if (restoredFromSnapshot && item.clientId.startsWith('bot-dm:')) {
if (!botDirectMessageServiceHolder) throw new AcceptedCallbackDispatchCancelled('Bot message recovery unavailable');
await botDirectMessageServiceHolder.assertRestoredQueuedDelivery(sessionId, item.clientId);
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 1fbc094d02..276c2b4bb7 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -6600,6 +6600,8 @@
"agentTasksRequest": "Review task permission",
"agentTasks": "Can create and manage its own Cindy tasks",
"agentTasksDetail": "Can send messages, read results and stop its own executions. Tasks remain visible to you. Uses this plugin’s AI settings and may incur model charges; does not grant access to other tasks.",
+ "agentTargets": "Can send messages to projects, existing tasks and companions",
+ "agentTargetsDetail": "Can view local project directories and task and companion names and IDs, create tasks in projects, and send text and images to existing tasks and companions. May trigger AI execution and model charges; does not grant access to other tasks’ history, settings or stop controls.",
"agentHiddenTasks": "Can create background tasks hidden from the task list",
"agentHiddenTasksDetail": "Tasks this plugin creates can stay out of the task list, search and notifications. You can always view, open or show them in the task list from Background Tasks on this plugin’s page; uninstalling the plugin shows them again.",
"agentErrand": "Create tasks, perform work, and read results",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index d207dea2c1..88c0f0d887 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -6569,6 +6569,8 @@
"agentTasksRequest": "セッション権限を確認",
"agentTasks": "このプラグインの Cindy セッションを作成・管理できます",
"agentTasksDetail": "メッセージの送信、結果の読み取り、自身の実行の停止ができます。セッションはユーザーに表示されます。プラグインの AI 設定を使用し、モデル料金が発生する場合があります。他のセッションへのアクセスは許可されません。",
+ "agentTargets": "プロジェクト、既存のセッション、パートナーにメッセージを送信できます",
+ "agentTargetsDetail": "ローカルのプロジェクトディレクトリ、セッションとパートナーの名前・IDを確認し、プロジェクト内にセッションを作成したり、既存のセッションとパートナーにテキストや画像を送信したりできます。AI の実行とモデル料金が発生する場合があります。他のセッションの履歴の読み取り、設定の変更、停止は許可されません。",
"agentHiddenTasks": "セッションリストに表示されないバックグラウンドセッションを作成できます",
"agentHiddenTasksDetail": "このプラグインが作成したセッションを、セッションリスト・検索・通知に表示しないようにできます。プラグイン詳細の「バックグラウンドセッション」からいつでも確認したり開いたり、セッションリストに表示したりできます。プラグインをアンインストールすると再び表示されます。",
"agentErrand": "タスクを作成し、作業を実行して結果を取得できます",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index ac78aa0502..ce7f122903 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -6569,6 +6569,8 @@
"agentTasksRequest": "세션 권한 확인",
"agentTasks": "이 플러그인의 Cindy 세션을 만들고 관리할 수 있음",
"agentTasksDetail": "메시지를 보내고 결과를 읽으며 자신의 실행을 중지할 수 있습니다. 세션은 사용자에게 표시됩니다. 플러그인의 AI 설정을 사용하며 모델 비용이 발생할 수 있습니다. 다른 세션에 대한 접근 권한은 부여하지 않습니다.",
+ "agentTargets": "프로젝트, 기존 세션 및 파트너에 메시지를 보낼 수 있음",
+ "agentTargetsDetail": "로컬 프로젝트 디렉터리와 세션 및 파트너의 이름과 ID를 확인하고, 프로젝트에 세션을 만들거나 기존 세션 및 파트너에 텍스트와 이미지를 보낼 수 있습니다. AI 실행과 모델 비용이 발생할 수 있으며, 다른 세션의 기록 읽기, 설정 변경 또는 중지 권한은 부여하지 않습니다.",
"agentHiddenTasks": "세션 목록에 표시되지 않는 백그라운드 세션을 만들 수 있음",
"agentHiddenTasksDetail": "이 플러그인이 만든 세션을 세션 목록, 검색, 알림에 표시하지 않을 수 있습니다. 플러그인 상세의 「백그라운드 세션」에서 언제든지 확인하고 열거나 세션 목록에 표시할 수 있으며, 플러그인을 제거하면 다시 표시됩니다.",
"agentErrand": "작업을 만들고 실행하며 결과를 읽을 수 있습니다",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 20e1a4429b..5f494e73f5 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -6569,6 +6569,8 @@
"agentTasksRequest": "确认任务权限",
"agentTasks": "可创建和管理本插件的 Cindy 任务",
"agentTasksDetail": "可发送消息、读取结果和停止本插件的执行,任务对你可见。沿用插件的 AI 配置,可能产生模型费用;不授予其他任务的访问权。",
+ "agentTargets": "可向项目、已有任务和伙伴投递消息",
+ "agentTargetsDetail": "可查看本机项目目录、任务和伙伴的名称与标识,在项目中新建任务或向已有任务、伙伴发送文字和图片。可能触发 AI 执行并产生模型费用;不授予其他任务的历史读取、设置修改或停止权限。",
"agentHiddenTasks": "可创建不显示在任务列表里的后台任务",
"agentHiddenTasksDetail": "本插件创建的任务可以不出现在任务列表、搜索和通知里。你可以随时在插件详情的「后台任务」中查看、打开,或显示到任务列表;卸载插件时这些任务会恢复显示。",
"agentErrand": "可以新建任务、执行工作并读取结果",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 9c7a51ad51..a1462d40f9 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -6569,6 +6569,8 @@
"agentTasksRequest": "確認任務權限",
"agentTasks": "可建立和管理本插件的 Cindy 任務",
"agentTasksDetail": "可傳送訊息、讀取結果和停止本插件的執行,任務對你可見。沿用插件的 AI 配置,可能產生模型費用;不授予其他任務的存取權。",
+ "agentTargets": "可向專案、現有任務和夥伴投遞訊息",
+ "agentTargetsDetail": "可查看本機專案目錄、任務和夥伴的名稱與識別碼,在專案中新建任務或向現有任務、夥伴傳送文字和圖片。可能觸發 AI 執行並產生模型費用;不授予其他任務的歷史讀取、設定修改或停止權限。",
"agentHiddenTasks": "可建立不顯示在任務列表裡的後臺任務",
"agentHiddenTasksDetail": "本插件建立的任務可以不出現在任務列表、搜尋和通知裡。你可以隨時在插件詳情的「後臺任務」中查看、開啟,或顯示到任務列表;解除安裝插件時這些任務會恢復顯示。",
"agentErrand": "可建立任務、執行工作並讀取結果",
diff --git a/apps/desktop/src/shared/__tests__/ghost.tasks.test.ts b/apps/desktop/src/shared/__tests__/ghost.tasks.test.ts
index 7232e8a173..5a7aad8d10 100644
--- a/apps/desktop/src/shared/__tests__/ghost.tasks.test.ts
+++ b/apps/desktop/src/shared/__tests__/ghost.tasks.test.ts
@@ -104,3 +104,20 @@ describe('background tasks declaration (agent.hiddenTasks)', () => {
expect(again.ok && again.manifest).toEqual(result.manifest);
});
});
+
+// A pre-existing tasks grant must not silently acquire cross-task/companion access.
+it('requires independent target permission and preserves inert historical declarations', () => {
+ const previous = validateGhostManifest({ ...base, agent: { tasks: true } });
+ const next = validateGhostManifest({ ...base, agent: { tasks: true, targets: true } });
+ if (!previous.ok || !next.ok) throw new Error('invalid fixture');
+ expect(diffGhostPermissionItems(previous.manifest, next.manifest).added.map(item => item.key)).toEqual(['agent:targets']);
+ for (const agent of [{ targets: true }, { tasks: true, targets: 'yes' }]) {
+ expect(validateGhostManifest({ ...base, agent }).ok).toBe(false);
+ const installed = validateInstalledGhostManifest({ ...base, agent });
+ if (!installed.ok) throw new Error('historical plugin disabled');
+ expect(installed.manifest.agent).toEqual(agent);
+ expect(ghostPermissionItems(installed.manifest).some(item => item.key === 'agent:targets')).toBe(false);
+ const again = validateNormalizedGhostManifest(ghostManifestToAuthorFormat(installed.manifest));
+ expect(again.ok && again.manifest).toEqual(installed.manifest);
+ }
+});
diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.ts
index 8b222faa57..01808dea65 100644
--- a/apps/desktop/src/shared/ghost.ts
+++ b/apps/desktop/src/shared/ghost.ts
@@ -205,6 +205,8 @@ export interface GhostAgentNeeds {
background?: boolean;
errand?: boolean;
tasks?: boolean;
+ /** 查询项目、任务、伙伴并投递消息;必须同时声明 tasks,需独立批准。 */
+ targets?: boolean;
/**
* hiddenTasks = 「可创建不显示在任务列表里的后台任务」(2026-10)。
*
@@ -1623,6 +1625,8 @@ export interface InstalledGhost {
retirement?: import('./featureRetirements').InstalledFeatureRetirement;
/** Host receipt fact, not a manifest declaration. Missing means tasks need confirmation. */
taskCapabilityApproved?: true;
+ /** Independent Host consent for cross-task/companion target access. */
+ targetCapabilityApproved?: true;
manifest: GhostManifest;
/** 安装目录绝对路径(userData/brain/<id> 或 userData/brain/_ns/<org>/<id>)。 */
dir: string;
@@ -2028,6 +2032,9 @@ export function ghostPermissionItems(manifest: GhostManifest): GhostPermissionIt
if (manifest.agent?.tasks === true) {
items.unshift({ key: 'agent:tasks', kind: 'agent', labelKey: 'agentTasks', detailKey: 'agentTasksDetail' });
}
+ if (manifest.agent?.tasks === true && manifest.agent.targets === true) {
+ items.unshift({ key: 'agent:targets', kind: 'agent', labelKey: 'agentTargets', detailKey: 'agentTargetsDetail' });
+ }
// 后台隐藏任务:独立 key 单列(理由同 schedule —— 并进 agent:tasks 会让更新里
// 新增 hiddenTasks 时 added 为空,扩权复核拦不住)。排在 agent:tasks 之后。
if (ghostDeclaresHiddenTasks(manifest)) {
@@ -4424,10 +4431,16 @@ function validateGhostManifestInput(value: unknown, preserveHistoricalTasks: boo
return { ok: false, reason: 'agent.hiddenTasks: true 需要同时声明 agent.tasks: true' };
}
}
+ if (!preserveHistoricalTasks && agentRaw.targets !== undefined) {
+ if (typeof agentRaw.targets !== 'boolean') return { ok: false, reason: 'agent.targets must be boolean' };
+ if (agentRaw.targets === true && agentRaw.tasks !== true) {
+ return { ok: false, reason: 'agent.targets: true 需要同时声明 agent.tasks: true' };
+ }
+ }
if (agentRaw.schedule !== undefined && typeof agentRaw.schedule !== 'boolean') {
return { ok: false, reason: 'agent.schedule 必须是布尔值' };
}
- if (agentRaw.background !== true && agentRaw.errand !== true && agentRaw.schedule !== true && agentRaw.tasks !== true && Object.keys(unknownDeclarationFields(agentRaw, preserveHistoricalTasks ? ['background', 'errand', 'schedule'] : ['background', 'errand', 'schedule', 'tasks', 'hiddenTasks'])).length === 0) {
+ if (agentRaw.background !== true && agentRaw.errand !== true && agentRaw.schedule !== true && agentRaw.tasks !== true && Object.keys(unknownDeclarationFields(agentRaw, preserveHistoricalTasks ? ['background', 'errand', 'schedule'] : ['background', 'errand', 'schedule', 'tasks', 'hiddenTasks', 'targets'])).length === 0) {
return {
ok: false,
reason:
@@ -4435,10 +4448,11 @@ function validateGhostManifestInput(value: unknown, preserveHistoricalTasks: boo
};
}
agent = {
- ...unknownDeclarationFields(agentRaw, preserveHistoricalTasks ? ['background', 'errand', 'schedule'] : ['background', 'errand', 'schedule', 'tasks', 'hiddenTasks']),
+ ...unknownDeclarationFields(agentRaw, preserveHistoricalTasks ? ['background', 'errand', 'schedule'] : ['background', 'errand', 'schedule', 'tasks', 'hiddenTasks', 'targets']),
...(agentRaw.background === true ? { background: true } : {}),
...(agentRaw.errand === true ? { errand: true } : {}),
...(agentRaw.tasks === true ? { tasks: true } : {}),
+ ...(agentRaw.tasks === true && agentRaw.targets === true ? { targets: true } : {}),
...(agentRaw.tasks === true && agentRaw.hiddenTasks === true ? { hiddenTasks: true } : {}),
...(agentRaw.schedule === true ? { schedule: true } : {}),
};
diff --git a/apps/desktop/src/shared/pluginTargets.ts b/apps/desktop/src/shared/pluginTargets.ts
index 47e5169b2d..02da32777f 100644
--- a/apps/desktop/src/shared/pluginTargets.ts
+++ b/apps/desktop/src/shared/pluginTargets.ts
@@ -1,6 +1,7 @@
import type { PluginTaskRoute } from './pluginTasks.js';
import type { PluginMessageAttachment } from './pluginAttachments.js';
+/** Requires agent.tasks + agent.targets and independent Host consent; does not read history. */
export type PluginTargetKind = 'project' | 'task' | 'bot';
export type PluginTargetDelivery = 'queue' | 'steer';
export interface PluginTargetRef {
diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.md
index 2a643ed028..43a656bf56 100644
--- a/docs/dev-rules/plugin-security-and-authoring.md
+++ b/docs/dev-rules/plugin-security-and-authoring.md
@@ -145,6 +145,10 @@ Library 请求同时绑定迁移代次和安装批准,根解析、排队及开
只在首次任务能力调用通过既有宿主权限界面确认,原插件的启用态、其它能力、凭证和
设置保持不变。拒绝、窗口不可用、账号或安装版本变化均不授予任务权限;同能力更新
保留既有明确批准,移除该能力后不保留。清单或旧未知字段本身不能补写批准。
+- `agent.targets` 必须与 `agent.tasks: true` 同时声明,独立列出 `agent:targets` 权限并要求 Host receipt 的 `targetCapabilityApproved` 显式批准。
+ 可查询本机项目、任务和伙伴的目标元数据,并投递文字/图片;不授予其他任务的历史读取、设置修改或停止权限。
+ 安装/更新复用既有权限确认;历史 tasks 批准和未知 targets 字段不能自动扩权,缺新批准时只阻止新目标接口,首次调用复用既有宿主确认。
+ 实现与作者契约见 [通用投递目标](plugin-task-api-implementation.md#通用投递目标增量接口尚未发布)。
- `agent.hiddenTasks`(后台任务)只在与 `agent.tasks: true` 同时声明时有效:新包缺 tasks 或非布尔
直接拒装;已安装快照里不成对的历史值原样保留但不授予。它单列为 `agent:hidden-tasks` 权限,
更新新增即「权限变多」;运行期由 taskSlot 与任务服务按身份卡双重守门。透明性兜底与多端口径见
diff --git a/docs/dev-rules/plugin-task-api-implementation.md b/docs/dev-rules/plugin-task-api-implementation.md
index b9cad7b5dd..1fd9cc651e 100644
--- a/docs/dev-rules/plugin-task-api-implementation.md
+++ b/docs/dev-rules/plugin-task-api-implementation.md
@@ -337,31 +337,32 @@ Pi 子代理未成功投递的自动 allow 再次投递前重走现有核验,
## 通用投递目标(增量接口,尚未发布)
`cindy.targets` 的作者契约见 `FORGE_GUIDE`,实现位于 `pluginTargetSlot.ts` 和
-`pluginTargetCandidates.ts`。查询、解析和投递相互独立,没有宿主目标选择弹窗、Renderer 接线或新增 UI。
+`pluginTargetCandidates.ts`。查询、解析和投递相互独立,没有宿主目标选择弹窗、Renderer 目标选择接线。权限说明复用既有安装/更新确认界面。
选择方式、固定目标及其配置由使用这些接口的插件维护;Host 不保存插件的固定目标绑定。
-入口复用 `agent.tasks` 的启用、批准和逻辑页身份校验,保留 `cindy.tasks` 自有任务边界,
-不放宽它的 get/list/send,不改变旧任务 API、默认设置卡或 manifest 字段。
+入口要求 `agent.tasks: true` 与独立的 `agent.targets: true`,后者单列为 `agent:targets` 权限,需 Host receipt 的 `targetCapabilityApproved` 明确批准事实。
+安装/更新确认只授予实际展示的新能力;旧 tasks 批准与历史未知字段不授予 targets。存量插件的原有能力不变,缺独立批准只阻止新接口;首次新接口调用复用既有宿主确认。
+保留 `cindy.tasks` 自有任务边界,不放宽它的 get/list/send,也不改变默认设置卡。
- `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。
+ 新任务经现有 `PluginTaskService.create` 登记归属后使用 `createPluginTaskSession`,沿用插件模型选择、受限动手权限及卸载撤销流程,可传统一模型目录的 route。
存量任务和伙伴保留其模型、权限、目录,不接受 route;伙伴通过唯一 canonical 注册解析,不使用兼容镜像或伪造伙伴身份。
-- 同键并发发送共享同一 Promise。owner-scoped `plugin-target-deliveries.json` 只保存请求摘要、Host 生成的 taskId/clientId 和状态,
+- 同键并发发送共享同一 Promise。回执复用当前账号 SQLite 的 `plugin_task_requests`,以 `operation=target` 按插件和请求键读写单行;只保存请求摘要、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 派发前复核。
+- main 盖 sourcePlugin 和 delegated-continuation 来源;入队前及实际受理时复核插件批准与目标。受理通过持久 clientId 查回执,重启恢复后仍检查当前批准修订、取消状态和伙伴 canonical 归属;失效以队列取消信号拦下派发。插话还在异步筛查后及 provider 派发前复核。
筛查拒绝返回 DELIVERY_REJECTED,不改走队列;ACK 未知保留宿主保护性暂停队列并返回 DELIVERY_UNCERTAIN,不再次排队。
`cancel({requestKey})` 持久使迟到请求失效,只按本插件该请求的 clientId 撤回排队输入,不停止整个会话或撤回已经接受的插话。
- 仅本机 Desktop,不新增 Mobile/device-link 透传,也不承诺跨平台原生触发。异步请求持续复核原逻辑页、批准 revision 和 owner generation。
-此能力供声明了 `agent.tasks` 的插件使用;投递沿用既有插件授权和目标任务权限。
+此能力供同时声明并获批 `agent.tasks` 与 `agent.targets` 的插件使用;投递沿用目标任务权限,不授予读取历史、修改配置或停止其他任务的权限。
静态检查与单元测试不等于真实 AI 执行的联调验收,不得把 accepted 当成完成。
### 消息图片附件
diff --git a/packages/plugin-protocol/src/__tests__/manifest.test.ts b/packages/plugin-protocol/src/__tests__/manifest.test.ts
index 25622ed536..570d427133 100644
--- a/packages/plugin-protocol/src/__tests__/manifest.test.ts
+++ b/packages/plugin-protocol/src/__tests__/manifest.test.ts
@@ -1903,3 +1903,14 @@ describe('agent.hiddenTasks declaration', () => {
expect(visible.ok && visible.manifest.agent).toEqual({ tasks: true });
});
});
+
+// New target access is not implied by the old plugin-owned tasks declaration.
+it('validates independent target access without dropping the tasks dependency', () => {
+ const base = { schemaVersion: 3, minCindyVersion: '0.1.0', id: 'target-test', name: 'Targets', version: '1.0.0', entry: 'main.js' };
+ const approved = validateGhostManifest({ ...base, agent: { tasks: true, targets: true } });
+ expect(approved.ok && approved.manifest.agent).toEqual({ tasks: true, targets: true });
+ expect(validateGhostManifest({ ...base, agent: { targets: true } }).ok).toBe(false);
+ expect(validateGhostManifest({ ...base, agent: { tasks: true, targets: 'yes' } }).ok).toBe(false);
+ const disabled = validateGhostManifest({ ...base, agent: { tasks: true, targets: false } });
+ expect(disabled.ok && disabled.manifest.agent).toEqual({ tasks: true });
+});
diff --git a/packages/plugin-protocol/src/manifest.ts b/packages/plugin-protocol/src/manifest.ts
index 10e4143bb0..6eb81adcab 100644
--- a/packages/plugin-protocol/src/manifest.ts
+++ b/packages/plugin-protocol/src/manifest.ts
@@ -207,6 +207,8 @@ export interface GhostAgentNeeds {
background?: boolean;
errand?: boolean;
tasks?: boolean;
+ /** 查询项目、任务、伙伴并投递消息;必须同时声明 tasks,需独立批准。 */
+ targets?: boolean;
/** 后台隐藏任务;必须与 `tasks: true` 同时声明。 */
hiddenTasks?: boolean;
schedule?: boolean;
@@ -2973,10 +2975,16 @@ export function validateGhostManifest(value: unknown): ManifestValidation {
if (agentRaw.hiddenTasks === true && agentRaw.tasks !== true) {
return { ok: false, reason: 'agent.hiddenTasks: true 需要同时声明 agent.tasks: true' };
}
+ if (agentRaw.targets !== undefined) {
+ if (typeof agentRaw.targets !== 'boolean') return { ok: false, reason: 'agent.targets must be boolean' };
+ if (agentRaw.targets === true && agentRaw.tasks !== true) {
+ return { ok: false, reason: 'agent.targets: true 需要同时声明 agent.tasks: true' };
+ }
+ }
if (agentRaw.schedule !== undefined && typeof agentRaw.schedule !== 'boolean') {
return { ok: false, reason: 'agent.schedule 必须是布尔值' };
}
- if (agentRaw.background !== true && agentRaw.errand !== true && agentRaw.schedule !== true && agentRaw.tasks !== true && Object.keys(unknownDeclarationFields(agentRaw, ['background', 'errand', 'schedule', 'tasks', 'hiddenTasks'])).length === 0) {
+ if (agentRaw.background !== true && agentRaw.errand !== true && agentRaw.schedule !== true && agentRaw.tasks !== true && Object.keys(unknownDeclarationFields(agentRaw, ['background', 'errand', 'schedule', 'tasks', 'hiddenTasks', 'targets'])).length === 0) {
return {
ok: false,
reason:
@@ -2984,10 +2992,11 @@ export function validateGhostManifest(value: unknown): ManifestValidation {
};
}
agent = {
- ...unknownDeclarationFields(agentRaw, ['background', 'errand', 'schedule', 'tasks', 'hiddenTasks']),
+ ...unknownDeclarationFields(agentRaw, ['background', 'errand', 'schedule', 'tasks', 'hiddenTasks', 'targets']),
...(agentRaw.background === true ? { background: true } : {}),
...(agentRaw.errand === true ? { errand: true } : {}),
...(agentRaw.tasks === true ? { tasks: true } : {}),
+ ...(agentRaw.tasks === true && agentRaw.targets === true ? { targets: true } : {}),
...(agentRaw.tasks === true && agentRaw.hiddenTasks === true ? { hiddenTasks: true } : {}),
...(agentRaw.schedule === true ? { schedule: true } : {}),
};