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(plugins): require explicit task capability approval and surface team errors

Dashb606fd3f7968
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.ts
index 3d3ea7e998..22f1379b61 100644
--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts
+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts
@@ -1805,6 +1805,7 @@ export class GhostManager {
dir,
enabled: this.effectiveEnabled(dir, receipt.enabled),
approval: { state: 'approved', revision: receipt.revision },
+ ...(receipt.taskCapabilityApproved === true ? { taskCapabilityApproved: true as const } : {}),
trust: receipt.trust,
...(receipt.manifest.skill?.items.length
? {
@@ -1979,6 +1980,20 @@ export class GhostManager {
return runtimeManifest;
}
+ /** Called only after Host permission UI confirms this exact installed revision. */
+ async approveTaskCapability(id: string, revision: string, isCurrent: () => boolean): Promise<boolean> {
+ return this.runExclusiveMutation(async () => {
+ const approval = this.readApproval(id);
+ if (!isCurrent() || approval.state !== 'approved' || approval.receipt.revision !== revision ||
+ approval.receipt.manifest.agent?.tasks !== true ||
+ !this.list().some(ghost => ghost.manifest.id === id && ghost.enabled)) return false;
+ if (approval.receipt.taskCapabilityApproved !== true) {
+ await this.receiptStore.write({ ...approval.receipt, taskCapabilityApproved: true });
+ }
+ return isCurrent();
+ });
+ }
+
/**
* 启用 / 停用一张意识。停用不删任何东西,只把批准 receipt 的 enabled 翻过来
* (安装目录里的 `.disabled` 只作为旧版本兼容镜像同步维护)。幂等。
@@ -2594,6 +2609,7 @@ export class GhostManager {
async install(
lizFilePath: string,
opts?: {
+ taskCapabilityApproved?: true;
initiallyEnabled?: boolean;
expectedPackageSha256?: string;
trustOverride?: GhostHostTrustOverride;
@@ -2608,6 +2624,7 @@ export class GhostManager {
private async installUnlocked(
lizFilePath: string,
opts?: {
+ taskCapabilityApproved?: true;
initiallyEnabled?: boolean;
expectedPackageSha256?: string;
trustOverride?: GhostHostTrustOverride;
@@ -2717,6 +2734,7 @@ export class GhostManager {
manifest: approvedManifest,
localeResources,
enabled: initiallyEnabled,
+ ...(opts?.taskCapabilityApproved === true && approvedManifest.agent?.tasks === true ? {taskCapabilityApproved:true as const} : {}),
trust,
// 指纹取自包投影而不是刚发布的 finalDir:发布后被换的字节应当在快照
// 对账时被拒,而不是被首读钉成批准基线(P0-8)。
@@ -2823,6 +2841,7 @@ export class GhostManager {
async update(
lizFilePath: string,
opts: {
+ taskCapabilityApproved?: true;
expectedInstalledApproval: string;
expectedPackageSha256?: string;
trustOverride?: GhostHostTrustOverride;
@@ -2838,6 +2857,7 @@ export class GhostManager {
private async updateUnlocked(
lizFilePath: string,
opts: {
+ taskCapabilityApproved?: true;
expectedInstalledApproval: string;
expectedPackageSha256?: string;
trustOverride?: GhostHostTrustOverride;
@@ -3058,6 +3078,8 @@ export class GhostManager {
manifest: approvedManifest,
localeResources,
enabled,
+ ...((opts.taskCapabilityApproved === true || (approvalResult.state === 'approved' && approvalResult.receipt.taskCapabilityApproved === true)) &&
+ approvedManifest.agent?.tasks === true ? { taskCapabilityApproved: true as const } : {}),
trust,
// 同 install:指纹取自包投影,发布后的目录漂移在快照对账时 fail closed(P0-8)。
skillContentSha256: await this.hashSkillContentFromPackage(
@@ -3437,6 +3459,8 @@ export class GhostManager {
trust,
skillContentSha256,
packageSha256,
+ ...(current.state === 'approved' && current.receipt.taskCapabilityApproved === true &&
+ approvedManifest.agent?.tasks === true ? { taskCapabilityApproved: true as const } : {}),
...(iconDataUrl !== undefined ? { iconDataUrl } : {}),
}),
{ skillSourceDir: sourceDir },
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 b93c8ca083..c27b73b1aa 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
@@ -308,6 +308,26 @@ describe('hashApprovedSkillContent · item.dir 路径段校验', () => {
});
describe('GhostManager · 存量插件一次性迁移(§5 升级无感)', () => {
+ it('keeps legacy tasks data inert, persists only explicit approval, and preserves it through enable and update', async () => {
+ const manifest = {...goodManifest(), slots:['tool','agent'], agent:{tasks:true}};
+ await writeLegacyInstall('hello', manifest);
+ await manager.migrateLegacyApprovalsOnce();
+ const old = manager.list()[0];
+ expect(old.enabled).toBe(true);
+ expect(old.taskCapabilityApproved).toBeUndefined();
+ if (old.approval.state !== 'approved') throw new Error('fixture not approved');
+ expect(await manager.approveTaskCapability('hello', 'stale', () => true)).toBe(false);
+ expect(await manager.approveTaskCapability('hello', old.approval.revision, () => false)).toBe(false);
+ expect(await manager.approveTaskCapability('hello', old.approval.revision, () => true)).toBe(true);
+ expect(manager.list()[0]).toMatchObject({enabled:true,taskCapabilityApproved:true,approval:old.approval});
+ await manager.setEnabled('hello', false);
+ expect(await manager.approveTaskCapability('hello', old.approval.revision, () => true)).toBe(false);
+ await manager.setEnabled('hello', true);
+ expect(manager.list()[0].taskCapabilityApproved).toBe(true);
+ const pkg = await makeCindy('tasks-update.cindy', {...manifest,version:'1.0.1'}, {'main.js':'// plugin'});
+ const updated = await manager.update(pkg, {expectedInstalledApproval:ghostInstallApprovalToken(old.approval)});
+ expect(updated).toHaveProperty('ghost.taskCapabilityApproved', true);
+ });
/** 带 skill 槽的旧布局清单 + 配套 SKILL.md(frontmatter 与声明逐字一致)。 */
const legacySkillManifest = (id = 'skilled'): Record<string, unknown> => ({
...goodManifest(id),
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 65b1c01b30..9706b8f8d7 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallConsent.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallConsent.test.ts
@@ -9,6 +9,7 @@ import {
import {
abortAllGhostInstallConsentPrompts,
assertGhostInstallConsent,
+ confirmedTaskCapability,
isGhostInstallConsentRequiredError,
obtainGhostInstallConsent,
trackGhostInstallConsentPrompt,
@@ -51,6 +52,20 @@ const userPrompt = (answer: boolean | Error) =>
});
const reviewedDigest = 'a'.repeat(64);
+it('records tasks only when that capability was included in explicit install/update consent', async () => {
+ const next = {...manifest(['api.weather.test']),agent:{tasks:true as const}};
+ const policy = {mode:'prompt' as const,prompt:userPrompt(true),initiator:'user' as const,origin:'market' as const};
+ const decision = await obtainGhostInstallConsent(policy,null,next,reviewedDigest);
+ assertGhostInstallConsent(decision,null,next,reviewedDigest);
+ expect(confirmedTaskCapability(decision,null,next)).toBe(true);
+ expect(confirmedTaskCapability({mode:'exempt',reason:'server-default-install'},null,next)).toBeUndefined();
+ expect(confirmedTaskCapability({mode:'unprompted'},null,next)).toBeUndefined();
+ const old = installed(next);
+ const expanded = {...next,network:{hosts:['api.weather.test','other.test']}};
+ const unrelated = await obtainGhostInstallConsent(policy,old,expanded,reviewedDigest);
+ assertGhostInstallConsent(unrelated,old,expanded,reviewedDigest);
+ expect(confirmedTaskCapability(unrelated,old,expanded)).toBeUndefined();
+});
const replacedDigest = 'b'.repeat(64);
describe('obtainGhostInstallConsent', () => {
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/taskCapability.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/taskCapability.test.ts
new file mode 100644
index 0000000000..d2416fed07
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/taskCapability.test.ts
@@ -0,0 +1,98 @@
+import { describe, expect, it, vi } from 'vitest';
+import { ensurePluginTaskApproval, hasPluginTaskApproval } from '../taskCapability.js';
+import { handlePluginTaskRequest } from '../taskSlot.js';
+import type { InstalledGhost } from '../../../shared/ghost.js';
+
+const legacy = () =>
+ ({
+ dir: '/unused-test-plugin',
+ enabled: true,
+ approval: { state: 'approved', revision: 'old' },
+ manifest: {
+ schemaVersion: 2,
+ kind: 'chip',
+ entry: 'main.js',
+ id: 'p',
+ name: 'Plugin',
+ version: '1.0.0',
+ agent: { tasks: true },
+ slots: ['agent'],
+ },
+ }) as InstalledGhost;
+
+describe('explicit task capability approval', () => {
+ it('does not treat a preserved unknown declaration as consent', async () => {
+ const ghost = legacy();
+ const handler = vi.fn();
+ expect(hasPluginTaskApproval(ghost)).toBe(false);
+ expect(
+ await handlePluginTaskRequest(
+ 'p',
+ { type: 'tasks-request', kind: 'list' },
+ {
+ getGhost: () => ghost,
+ isCurrent: () => true,
+ handler,
+ },
+ ),
+ ).toMatchObject({ ok: false, error: { code: 'PERMISSION_DENIED' } });
+ expect(handler).not.toHaveBeenCalled();
+ expect(ghost.enabled).toBe(true);
+ });
+ it.each(['deny', 'account-change', 'approve'] as const)(
+ 'handles %s without granting on stale or rejected consent',
+ async (scenario) => {
+ let active = true;
+ const ghost = legacy();
+ const approve = vi.fn(async (_id, revision, isCurrent) => {
+ expect(revision).toBe('old');
+ if (!isCurrent()) return false;
+ ghost.taskCapabilityApproved = true;
+ return true;
+ });
+ const confirm = vi.fn(async (facts) => {
+ expect(facts.added.map((item: { key: string }) => item.key)).toEqual(['agent:tasks']);
+ if (scenario === 'account-change') active = false;
+ return scenario !== 'deny';
+ });
+ const deps = { getGhost: () => ghost, isCurrent: () => active, confirm, approve };
+ expect(await ensurePluginTaskApproval('p', deps)).toBe(scenario === 'approve');
+ expect(approve).toHaveBeenCalledTimes(scenario === 'approve' ? 1 : 0);
+ if (scenario === 'approve') {
+ await ensurePluginTaskApproval('p', deps);
+ expect(confirm).toHaveBeenCalledTimes(1);
+ }
+ },
+ );
+ it('does not execute on unavailable UI or a failed receipt write', async () => {
+ const handler = vi.fn();
+ const ghost = legacy();
+ for (const confirm of [
+ async () => {
+ throw new Error('no UI');
+ },
+ async () => true,
+ ]) {
+ const result = await handlePluginTaskRequest(
+ 'p',
+ { type: 'tasks-request', kind: 'list' },
+ {
+ getGhost: () => ghost,
+ isCurrent: () => true,
+ handler,
+ ensureAuthorized: () =>
+ ensurePluginTaskApproval('p', {
+ getGhost: () => ghost,
+ isCurrent: () => true,
+ confirm,
+ approve: async () => {
+ throw new Error('disk failure');
+ },
+ }),
+ },
+ );
+ expect(result).toMatchObject({ ok: false, error: { code: 'PERMISSION_DENIED' } });
+ }
+ expect(handler).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/taskSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/taskSlot.test.ts
index 3ba34488e9..062ffa56f6 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/taskSlot.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/taskSlot.test.ts
@@ -3,7 +3,7 @@ import { handlePluginTaskRequest, validPluginTaskRequest } from '../taskSlot.js'
import type { InstalledGhost } from '../../../shared/ghost.js';
describe('plugin task pipe', () => {
- const ghost = { enabled: true, manifest: { agent: { tasks: true } } } as InstalledGhost;
+ const ghost = { enabled: true, taskCapabilityApproved: true, approval: {state:'approved', revision:'r'}, manifest: { agent: { tasks: true } } } as InstalledGhost;
it('requires its own declared capability; errand alone grants nothing', async () => {
const handler = vi.fn();
const result = await handlePluginTaskRequest(
@@ -83,4 +83,3 @@ it('allows an Auto request but never Full access', () => {
expect(validPluginTaskRequest({type:'tasks-request',kind:'requestWriteAccess',taskId:'own',mode:'auto'})).toBe(true);
expect(validPluginTaskRequest({type:'tasks-request',kind:'requestWriteAccess',taskId:'own',mode:'bypassPermissions'})).toBe(false);
});
-
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index d7f93d8d96..3fb1977361 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -3901,6 +3901,8 @@ const r = await cindy.agent.requestSchedule({
声明 \`"agent": { "tasks": true }\` 后,逻辑页可使用 \`cindy.tasks\`。它是独立权限,
旧 \`errand\` 声明不自动取得该权限;用户仍可在侧边栏查看和接手这些任务。
+安装时已明确展示并确认的任务能力不重复询问;否则首次使用时通过现有宿主权限界面确认并记录独立批准。旧版保存的未知字段不会自动授权。
+用户拒绝或确认界面不可用时返回 \`PERMISSION_DENIED\`,不影响插件其它功能;不得自动循环重试确认。
面板通过既有逻辑页通道调用,不获得新的 preload 或内部 IPC 权限。
先调用 \`capabilities()\` 获取实际支持操作。当前仅支持本插件创建的本机普通任务:
diff --git a/apps/desktop/src/main/cindy-brain/ghostInstallConsent.ts b/apps/desktop/src/main/cindy-brain/ghostInstallConsent.ts
index 8dd2ddc397..b115516d93 100644
--- a/apps/desktop/src/main/cindy-brain/ghostInstallConsent.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostInstallConsent.ts
@@ -49,6 +49,18 @@ export type GhostInstallConsentDecision =
const pendingPromptAborts = new Set<AbortController>();
+/** Use only after assertGhostInstallConsent binds the confirmed facts to this package/receiver. */
+export function confirmedTaskCapability(
+ decision: GhostInstallConsentDecision,
+ installed: InstalledGhost | null | undefined,
+ next: GhostManifest,
+): 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;
+}
+
/**
* 登记一次等待中的确认,账号边界时由 `abortAllGhostInstallConsentPrompts` 一并取消。
* 确认不得占用 owner 租约;取消是为了让等待中的安装调用尽快按用户取消收口。
diff --git a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
index 798605e257..d931871988 100644
--- a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
@@ -52,6 +52,8 @@ 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;
schemaVersion: typeof RECEIPT_SCHEMA_VERSION;
id: string;
revision: string;
@@ -1020,6 +1022,7 @@ export function readLegacyInstallTrust(dir: string): GhostTrustInfo | null {
}
export function createGhostInstallReceipt(input: {
+ taskCapabilityApproved?: true;
manifest: GhostManifest;
localeResources: Record<string, GhostManifestLocaleResource>;
enabled: boolean;
@@ -1043,6 +1046,7 @@ export function createGhostInstallReceipt(input: {
enabled: input.enabled,
trust: input.trust,
skillContentSha256: input.skillContentSha256,
+ ...(input.taskCapabilityApproved === true ? { taskCapabilityApproved: true as const } : {}),
...(input.packageSha256 ? { packageSha256: input.packageSha256 } : {}),
...(input.iconDataUrl ? { iconDataUrl: input.iconDataUrl } : {}),
...(input.installOrigin !== undefined ? { installOrigin: input.installOrigin } : {}),
@@ -1219,6 +1223,7 @@ function validateReceipt(
enabled: value.enabled,
trust,
skillContentSha256,
+ ...(value.taskCapabilityApproved === true ? { taskCapabilityApproved: 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 5064ac5fbd..eafe647ac4 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -2,6 +2,7 @@ import { getModelVisibilityOverride, waitForModelVisibilityMirror } from '../mak
import { projectGhostAgentModels } from './ghostAgentModels.js';
import { getDesktopProviderService } from '../maker-host/createDesktopProviderService.js';
import { handlePluginTaskRequest, type PluginTaskHandler } from './taskSlot.js';
+import { ensurePluginTaskApproval, hasPluginTaskApproval } from './taskCapability.js';
import { registerGhostCardRemoteProvider, persistGhostCardWithRemoteChange } from './cardRemoteResource.js';
import { openDeviceAuthorizationCard, openPluginAuthorizationCard } from '../plugin-oauth/deviceCard.js';
import { t as authorizationText } from '../i18n.js';
@@ -310,6 +311,7 @@ import {
import {
abortAllGhostInstallConsentPrompts,
assertGhostInstallConsent,
+ confirmedTaskCapability,
obtainGhostInstallConsent,
type GhostInstallConsentDecision,
type GhostInstallConsentPrompt,
@@ -1703,7 +1705,7 @@ export function setPluginTaskHandler(handler: PluginTaskHandler | null): void {
export function isPluginTaskAuthorized(id: string): boolean {
const ghost = findAvailableGhost(id);
- return ghost?.enabled === true && ghost.manifest.agent?.tasks === true;
+ return hasPluginTaskApproval(ghost);
}
let errandSlotSingleton: GhostErrandSlot | null = null;
@@ -5890,15 +5892,17 @@ async function installAndDockLocked(
): Promise<InstalledGhost> {
// 确认依据的 manifest 必须就是 expectedPackageSha256 钉住的那份包;锁内现读受体
// 复核,确认后同 id 被别处装上或包内容变化都不能沿用这次确认。
+ const installedBefore = manager.list().find((ghost) => ghost.manifest.id === opts.ghostId);
assertGhostInstallConsent(
opts.consent.decision,
- manager.list().find((ghost) => ghost.manifest.id === opts.ghostId),
+ installedBefore,
opts.consent.manifest,
opts.expectedPackageSha256,
);
// 初始启用态由入口显式传入;当前用户导入与市场首装都传 true,覆盖更新
// 则走 manager.update 延续既有状态。保留 false 缺省以兼容内部受控调用方。
const result = await manager.install(lizFilePath, {
+ taskCapabilityApproved: confirmedTaskCapability(opts.consent.decision, installedBefore, opts.consent.manifest),
initiallyEnabled: opts.enable ?? false,
expectedPackageSha256: opts.expectedPackageSha256,
...(opts.trustOverride ? { trustOverride: opts.trustOverride } : {}),
@@ -6020,6 +6024,7 @@ async function updateLocalGhostPackageLocked(
try {
result = await withActiveOwnerGhostOauthMutationLock(inspected.manifest.id, () =>
manager.update(cindyFilePath, {
+ taskCapabilityApproved: confirmedTaskCapability(consent, previousGhost, inspected.manifest),
expectedPackageSha256,
expectedInstalledApproval,
...(installOrigin ? { installOrigin } : {}),
@@ -6384,6 +6389,7 @@ async function installOrUpdateMarketGhostPackageLocked(
// the strict lock through package swap, receipt commit, and compensation.
result = await withActiveOwnerGhostOauthMutationLock(expected.ghostId, () =>
manager.update(cindyFilePath, {
+ taskCapabilityApproved: confirmedTaskCapability(expected.consent, installed, inspected.manifest),
expectedPackageSha256: inspected.packageSha256,
expectedInstalledApproval: expected.expectedInstalledApproval!,
...(trustOverride ? { trustOverride } : {}),
@@ -7191,9 +7197,24 @@ export function registerGhostIpc(): void {
// 的 runner(maker-ipc)。
if (type === 'tasks-request') {
const owner = getActiveDataOwnerPushStamp();
+ const manager = getGhostManager();
+ const isCurrent = () => {
+ const current = getActiveDataOwnerPushStamp();
+ return owner.dataOwnerId === current.dataOwnerId && owner.ownerGeneration === current.ownerGeneration &&
+ !event.sender.isDestroyed() && ghostIdForLogicWebContents(event.sender.id) === id;
+ };
return handlePluginTaskRequest(id, payload, {
getGhost: findAvailableGhost, handler: pluginTaskHandler,
- isCurrent: () => { const current = getActiveDataOwnerPushStamp(); return owner.dataOwnerId === current.dataOwnerId && owner.ownerGeneration === current.ownerGeneration; },
+ isCurrent,
+ ensureAuthorized: () => ensurePluginTaskApproval(id, {
+ getGhost: findAvailableGhost, isCurrent,
+ confirm: facts => {
+ const window = getDeepLinkMainWindow();
+ if (!window || !isTrustedAppRendererWindow(window)) return Promise.resolve(false);
+ return createWindowGhostInstallConsentPrompt(window.webContents)({ purpose: 'task-capability', initiator: 'user', origin: 'local-file', facts });
+ },
+ approve: (pluginId, revision, active) => manager.approveTaskCapability(pluginId, revision, active),
+ }),
});
}
if (type === 'agent-errand-request') {
diff --git a/apps/desktop/src/main/cindy-brain/taskCapability.ts b/apps/desktop/src/main/cindy-brain/taskCapability.ts
new file mode 100644
index 0000000000..7d8a2b15f1
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/taskCapability.ts
@@ -0,0 +1,49 @@
+import { ghostPermissionItems, type InstalledGhost } from '../../shared/ghost.js';
+import type { GhostInstallConsentFacts } from '../../shared/ghostInstallConsent.js';
+
+export function hasPluginTaskApproval(ghost: InstalledGhost | null | undefined): boolean {
+ return (
+ ghost?.enabled === true &&
+ ghost.manifest.agent?.tasks === true &&
+ ghost.approval?.state === 'approved' &&
+ ghost.taskCapabilityApproved === true
+ );
+}
+
+/** Reuse Host permission UI; no plugin-supplied confirmation or manifest flag is authority. */
+export async function ensurePluginTaskApproval(
+ id: string,
+ deps: {
+ getGhost(id: string): InstalledGhost | null;
+ isCurrent(): boolean;
+ confirm(facts: GhostInstallConsentFacts): Promise<boolean>;
+ approve(id: string, revision: string, isCurrent: () => boolean): Promise<boolean>;
+ },
+): Promise<boolean> {
+ const ghost = deps.getGhost(id);
+ if (!deps.isCurrent()) return false;
+ if (hasPluginTaskApproval(ghost)) return true;
+ if (
+ !ghost?.enabled ||
+ ghost.manifest.agent?.tasks !== true ||
+ ghost.approval?.state !== 'approved'
+ )
+ 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');
+ if (added.length !== 1) return false;
+ const confirmed = await deps.confirm({
+ kind: 'update',
+ ghostId: id,
+ name: ghost.manifest.name,
+ version: ghost.manifest.version,
+ previousVersion: ghost.manifest.version,
+ added,
+ removed: [],
+ unchangedCount: permissions.length - added.length,
+ builtinOauthClientChanged: false,
+ });
+ if (!confirmed || !deps.isCurrent()) return false;
+ return deps.approve(id, revision, deps.isCurrent);
+}
diff --git a/apps/desktop/src/main/cindy-brain/taskSlot.ts b/apps/desktop/src/main/cindy-brain/taskSlot.ts
index 6af1218463..b459e929f8 100644
--- a/apps/desktop/src/main/cindy-brain/taskSlot.ts
+++ b/apps/desktop/src/main/cindy-brain/taskSlot.ts
@@ -1,5 +1,6 @@
import type { InstalledGhost } from '../../shared/ghost.js';
import type { PluginTaskRequest, PluginTaskResult } from '../../shared/pluginTasks.js';
+import { hasPluginTaskApproval } from './taskCapability.js';
export const PLUGIN_TASK_OPERATIONS = [
'capabilities',
@@ -108,18 +109,21 @@ export async function handlePluginTaskRequest(
getGhost(id: string): InstalledGhost | null;
handler: PluginTaskHandler | null;
isCurrent: () => boolean;
+ ensureAuthorized?: () => Promise<boolean>;
},
): Promise<PluginTaskResult> {
const permitted = () =>
deps.isCurrent() &&
- deps.getGhost(pluginId)?.enabled === true &&
- deps.getGhost(pluginId)?.manifest.agent?.tasks === true;
+ hasPluginTaskApproval(deps.getGhost(pluginId));
const error = (code: string, message: string, retryable = false): PluginTaskResult => ({
ok: false,
error: { code, message, retryable },
});
- if (!permitted()) return error('PERMISSION_DENIED', 'Plugin task capability is unavailable');
if (!validPluginTaskRequest(value)) return error('INVALID_REQUEST', 'Invalid task request');
+ if (!permitted() && deps.ensureAuthorized) {
+ try { await deps.ensureAuthorized(); } catch { /* No UI or persistence failure grants nothing. */ }
+ }
+ if (!permitted()) return error('PERMISSION_DENIED', 'Plugin task capability is unavailable');
if (value.kind === 'capabilities')
return {
ok: true,
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskResult.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskResult.test.ts
new file mode 100644
index 0000000000..b710228039
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskResult.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, it } from 'vitest';
+import { assertPluginTaskResult } from '../pluginTaskService.js';
+import { handlePluginTaskRequest } from '../../cindy-brain/taskSlot.js';
+import type { InstalledGhost } from '../../../shared/ghost.js';
+
+describe('collaboration results across the plugin task pipe', () => {
+ it.each(['startTeam', 'releaseWorker'] as const)(
+ '%s rejects service failures without leaking diagnostics',
+ async (kind) => {
+ for (const code of ['PERMISSION_DENIED', 'CONFIRMATION_TIMEOUT', 'WORKER_BUSY', 'INTERNAL']) {
+ const result = await handlePluginTaskRequest(
+ 'plugin',
+ kind === 'startTeam'
+ ? { type: 'tasks-request', kind, taskId: 'task' }
+ : { type: 'tasks-request', kind, taskId: 'task', workerId: 'worker', completedAt: 100 },
+ {
+ getGhost: () =>
+ ({
+ enabled: true,
+ taskCapabilityApproved: true,
+ approval: { state: 'approved', revision: 'r' },
+ manifest: { agent: { tasks: true } },
+ }) as InstalledGhost,
+ isCurrent: () => true,
+ handler: async () => {
+ const serviceResult = {
+ ok: false,
+ errorCode: code,
+ message: '/private/internal-diagnostic',
+ };
+ assertPluginTaskResult(serviceResult, 'Collaboration operation failed');
+ return serviceResult;
+ },
+ },
+ );
+ expect(result).toEqual({
+ ok: false,
+ error: { code, message: 'Collaboration operation failed', retryable: false },
+ });
+ }
+ },
+ );
+ it('keeps successful result payloads unchanged and supplies a fallback failure code', () => {
+ expect(() => assertPluginTaskResult({ ok: true }, 'unused')).not.toThrow();
+ expect(() => assertPluginTaskResult({ ok: false }, 'Unavailable')).toThrow('Unavailable');
+ try {
+ assertPluginTaskResult({ ok: false }, 'Unavailable');
+ } catch (e) {
+ expect(e).toMatchObject({ name: 'PluginTaskError', code: 'HOST_NOT_READY' });
+ }
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/pluginTaskService.ts b/apps/desktop/src/main/maker-ipc/pluginTaskService.ts
index 7192a5517e..a61d806930 100644
--- a/apps/desktop/src/main/maker-ipc/pluginTaskService.ts
+++ b/apps/desktop/src/main/maker-ipc/pluginTaskService.ts
@@ -47,6 +47,10 @@ export class PluginTaskError extends Error {
this.name = 'PluginTaskError';
}
}
+/** Service failures must reject the public task API, without exposing internal diagnostics. */
+export function assertPluginTaskResult(result: { ok: boolean; errorCode?: string }, message: string): void {
+ if (!result.ok) throw new PluginTaskError(result.errorCode || 'HOST_NOT_READY', message);
+}
const fail = (code: string, message: string): never => {
throw new PluginTaskError(code, message);
};
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 2ca6b72a8a..bbf629ae3a 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -1,4 +1,4 @@
-import { createPluginTaskService, PluginTaskError, type PluginTaskService } from './pluginTaskService.js';
+import { assertPluginTaskResult, createPluginTaskService, PluginTaskError, type PluginTaskService } from './pluginTaskService.js';
import { resolvePluginWorkerDirectory } from './pluginWorkerDirectory.js';
import { pluginWorkerCompletedAt } from './pluginWorkerCompletion.js';
import { createPluginTaskStore } from './pluginTaskStore.js';
@@ -10325,6 +10325,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
});
if (epoch !== getCurrentDbClientSnapshot()) throw new PluginTaskError('PERMISSION_DENIED', 'Account changed');
await service.get(pluginId, task.taskId);
+ assertPluginTaskResult(result, 'Collaboration could not be started');
return result;
}
case 'setTeamPlan': {
@@ -10366,6 +10367,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
return {ok:true,workerId:record.id};
}
const result = await orcaTeamService.archiveWorker({callerLeadSessionId:request.taskId,workerId:record.id,onlyIfIdle:true,beforeArchive:validate});
+ assertPluginTaskResult(result, 'Worker could not be released');
if (result.ok && plan) await service.settleWorkerLabel(pluginId,request.taskId,record.label!);
return result;
}
diff --git a/apps/desktop/src/renderer/cindy-brain/GhostInstallConsentHost.tsx b/apps/desktop/src/renderer/cindy-brain/GhostInstallConsentHost.tsx
index 0e12cf1c60..4f9406724b 100644
--- a/apps/desktop/src/renderer/cindy-brain/GhostInstallConsentHost.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/GhostInstallConsentHost.tsx
@@ -101,7 +101,7 @@ function ConsentSection({ title, children }: { title: string; children: ReactNod
);
}
-export function GhostInstallConsentContent({ facts }: { facts: GhostInstallConsentFacts }) {
+export function GhostInstallConsentContent({ facts, capabilityOnly = false }: { facts: GhostInstallConsentFacts; capabilityOnly?: boolean }) {
const { t } = useTranslation();
if (facts.kind === 'install') {
return (
@@ -128,7 +128,7 @@ export function GhostInstallConsentContent({ facts }: { facts: GhostInstallConse
return (
<div>
<p className="text-13 leading-5 text-[var(--confirm-desc)]">
- {t('settings.ghosts.installConsent.updateDescription')}
+ {capabilityOnly ? null : t('settings.ghosts.installConsent.updateDescription')}
</p>
{facts.builtinOauthClientChanged ? (
<p className="mt-2 text-13 leading-5 text-[var(--confirm-desc)]">
@@ -201,15 +201,16 @@ export function GhostInstallConsentHost() {
// 账号已切换的旧请求不渲染任何插件事实,直接按取消回给 Main。
if (ownerStamp !== undefined && !isDataOwnerPushStampCurrent(ownerStamp)) return;
const { facts } = request;
+ const capabilityOnly = request.purpose === 'task-capability';
const source = ghostInstallConsentSourceLabel(t, request);
confirmed = await confirm(
{
title:
- facts.kind === 'install'
+ capabilityOnly ? facts.name : facts.kind === 'install'
? t('settings.ghosts.installConsent.installTitle', { name: facts.name })
: t('settings.ghosts.installConsent.updateTitle', { name: facts.name }),
description:
- facts.kind === 'install'
+ capabilityOnly ? t('settings.ghosts.installConsent.addedTitle') : facts.kind === 'install'
? t('settings.ghosts.installConsent.installMeta', {
version: facts.version,
source,
@@ -219,12 +220,12 @@ export function GhostInstallConsentHost() {
to: facts.version,
source,
}),
- content: <GhostInstallConsentContent facts={facts} />,
+ content: <GhostInstallConsentContent facts={facts} capabilityOnly={capabilityOnly} />,
maxWidth: 460,
contentSelectable: true,
describeContent: true,
confirmText:
- facts.kind === 'install'
+ capabilityOnly ? t('settings.ghosts.connections.confirmAllow') : facts.kind === 'install'
? t('settings.ghosts.installConsent.confirmInstall')
: t('settings.ghosts.installConsent.confirmUpdate'),
cancelText: t('settings.ghosts.installConsent.cancel'),
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/GhostInstallConsentHost.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/GhostInstallConsentHost.test.tsx
index b569f6c084..1c2f26d709 100644
--- a/apps/desktop/src/renderer/cindy-brain/__tests__/GhostInstallConsentHost.test.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/GhostInstallConsentHost.test.tsx
@@ -88,6 +88,24 @@ describe('GhostInstallConsentHost', () => {
expect(screen.getByText('settings.ghosts.installConsent.addedBadge')).toBeTruthy();
});
+ it('shows first-use capability consent without claiming a package update or source', async () => {
+ render(<GhostInstallConsentHost />);
+ await act(async () => push?.({
+ requestId:'tasks', purpose:'task-capability', initiator:'user', origin:'local-file',
+ facts:{kind:'update',ghostId:'p',name:'Plugin',version:'1',previousVersion:'1',
+ added:[{key:'agent:tasks',kind:'agent',labelKey:'agentTasks',detailKey:'agentTasksDetail'}],
+ removed:[],unchangedCount:2,builtinOauthClientChanged:false},
+ }));
+ const options = mocks.confirm.mock.calls[0][0];
+ expect(options.title).toBe('Plugin');
+ expect(options.description).toBe('settings.ghosts.installConsent.addedTitle');
+ expect(options.confirmText).toBe('settings.ghosts.connections.confirmAllow');
+ render(<>{options.content}</>);
+ expect(screen.getByText('settings.ghosts.perm.agentTasksDetail')).toBeTruthy();
+ expect(screen.queryByText('settings.ghosts.installConsent.updateDescription')).toBeNull();
+ await waitFor(()=>expect(resolveInstallConsent).toHaveBeenCalledWith('tasks',true));
+ });
+
it('answers cancel when Main dismisses the pending dialog', async () => {
let seenSignal: AbortSignal | undefined;
mocks.confirm.mockImplementation(
diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.ts
index ce2a6a9f2f..814a80597b 100644
--- a/apps/desktop/src/shared/ghost.ts
+++ b/apps/desktop/src/shared/ghost.ts
@@ -1601,6 +1601,8 @@ export function isGhostInstallApprovalToken(value: unknown): value is string {
/** 已装入主机的插件(批准清单 + 安装位置 + 启用态)。 */
export interface InstalledGhost {
+ /** Host receipt fact, not a manifest declaration. Missing means tasks need confirmation. */
+ taskCapabilityApproved?: true;
manifest: GhostManifest;
/** 安装目录绝对路径(userData/brain/<id>)。 */
dir: string;
diff --git a/apps/desktop/src/shared/ghostInstallConsent.ts b/apps/desktop/src/shared/ghostInstallConsent.ts
index 19c9d1c283..441cc568f3 100644
--- a/apps/desktop/src/shared/ghostInstallConsent.ts
+++ b/apps/desktop/src/shared/ghostInstallConsent.ts
@@ -58,6 +58,8 @@ export type GhostInstallConsentFacts =
/** Main 投给确认界面的一次确认请求。 */
export interface GhostInstallConsentRequest {
+ /** Host-only first-use capability confirmation; does not install/update a package. */
+ purpose?: 'task-capability';
requestId: string;
initiator: GhostInstallConsentInitiator;
origin: GhostInstallConsentOrigin;
diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.md
index c85edaa88a..a075bc6300 100644
--- a/docs/dev-rules/plugin-security-and-authoring.md
+++ b/docs/dev-rules/plugin-security-and-authoring.md
@@ -63,6 +63,10 @@
但当前 Host 不展示、不授权、也不因此阻止安装或发布。
未来 Host 识别该字段后,才按正常的能力展示和运行时守门链路启用。不能把
未知字段猜成现有权限,也不能让它意外获得能力。
+- `agent.tasks` 另需 Host receipt 的显式任务能力批准事实;旧 receipt 没有该事实时,
+ 只在首次任务能力调用通过既有宿主权限界面确认,原插件的启用态、其它能力、凭证和
+ 设置保持不变。拒绝、窗口不可用、账号或安装版本变化均不授予任务权限;同能力更新
+ 保留既有明确批准,移除该能力后不保留。清单或旧未知字段本身不能补写批准。
- **Agent 在途调用不需要重复登记具体操作。** 插件工具是否执行由当前
`ghost_call` 的 Cindy Agent 授权决定;普通网络和当前工作目录操作使用主机
下发且仍在途的 `callId`。随包代码与 CLI 继续使用已有 Node 工作进程,顶层