Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 重构 @ 插件入口并移除资源提供方 (#1670)
DavidShenXD694ae8607a1d
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.tsindex 735dc6e5bd..f6276bc7e5 100644--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts@@ -49,6 +49,7 @@ const TRUST_METADATA_FILE = '.cindy-trust.json';interface GhostInstalledHostMetadata {trust: GhostTrustInfo;+ /** Legacy receipt retained only for backward-compatible metadata reads. */approvedAtResourceProviderTool?: string;}@@ -144,17 +145,9 @@ export class GhostManager {continue;}const hostMetadata = this.readInstalledHostMetadata(dir);- // atResourceProvider 在旧版宿主里只是未知顶层元数据。只有新版宿主在- // install/update 审阅后写下的精确 receipt 才把它提升为运行时入口;旧安装- // 没 receipt 时 fail closed,但插件本体与已批准 tool 仍照旧可用。- const manifest =- v.manifest.atResourceProvider- && hostMetadata?.approvedAtResourceProviderTool !== v.manifest.atResourceProvider.tool- ? (() => {- const { atResourceProvider: _ignored, ...rest } = v.manifest;- return rest;- })()- : v.manifest;+ // 历史 manifest / receipt 中可能保留已移除的资源搜索元数据;它不参与当前+ // 运行时入口,插件本体与已批准的其它能力仍按现有授权照常可用。+ const manifest = v.manifest;// icon 读失败只降级为无图标(warn),不影响意识本体可用。const iconDataUrl = this.readInstalledIconDataUrl(dir, manifest);const localizedManifest = this.readInstalledLocalizedManifest(dir, manifest);@@ -686,9 +679,6 @@ export class GhostManager {? MAX_NODE_UNCOMPRESSED_BYTES: MAX_BASIC_UNCOMPRESSED_BYTES,trust,- ...(manifest.atResourceProvider- ? { approvedAtResourceProviderTool: manifest.atResourceProvider.tool }- : {}),});await fs.promises.rename(stagingDir, finalDir);} catch (err) {@@ -776,9 +766,6 @@ export class GhostManager {? MAX_NODE_UNCOMPRESSED_BYTES: MAX_BASIC_UNCOMPRESSED_BYTES,trust,- ...(manifest.atResourceProvider- ? { approvedAtResourceProviderTool: manifest.atResourceProvider.tool }- : {}),});} catch (err) {await fs.promises.rm(stagingDir, { recursive: true, force: true }).catch(() => {});@@ -825,7 +812,6 @@ export class GhostManager {disabled: boolean;maxUncompressedBytes: number;trust: GhostTrustInfo;- approvedAtResourceProviderTool?: string;},): Promise<void> {await fs.promises.mkdir(stagingDir, { recursive: true });@@ -854,9 +840,6 @@ export class GhostManager {path.join(stagingDir, TRUST_METADATA_FILE),`${JSON.stringify({...opts.trust,- ...(opts.approvedAtResourceProviderTool- ? { approvedAtResourceProvider: { tool: opts.approvedAtResourceProviderTool } }- : {}),}, null, 2)}\n`,);}diff --git a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.tsindex 2c152c3a5a..354e6f5898 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts@@ -240,25 +240,18 @@ describe('GhostManager · install', () => {it('@ 资源入口必须命中主机安装 receipt,旧安装元数据不会在升级后自动扩权', async () => {const cindy = await makeCindy('at-resource.cindy', atResourceManifest());const installed = await manager.install(cindy);- expect(installed).toMatchObject({- ghost: { manifest: { atResourceProvider: { tool: 'do_thing' } } },- });- expect(manager.list()[0].manifest.atResourceProvider).toEqual({ tool: 'do_thing' });const metadataPath = path.join(rootDir, 'hello', '.cindy-trust.json');const metadata = JSON.parse(await fs.promises.readFile(metadataPath, 'utf8')) as Record<string, unknown>;- expect(metadata.approvedAtResourceProvider).toEqual({ tool: 'do_thing' });delete metadata.approvedAtResourceProvider;await fs.promises.writeFile(metadataPath, `${JSON.stringify(metadata)}\n`);- expect(manager.list()[0].manifest.atResourceProvider).toBeUndefined();expect(manager.list()[0].manifest.tools).toEqual([{ name: 'do_thing', description: '做点事' },]);metadata.approvedAtResourceProvider = { tool: 'other_tool' };await fs.promises.writeFile(metadataPath, `${JSON.stringify(metadata)}\n`);- expect(manager.list()[0].manifest.atResourceProvider).toBeUndefined();});it('initiallyEnabled=false:装入即沉睡(.disabled 与目录同帧就位,首个广播就是沉睡态)', async () => {diff --git a/apps/desktop/src/main/cindy-brain/__tests__/atResourceProvider.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/atResourceProvider.test.tsdeleted file mode 100644index 7e526e911e..0000000000--- a/apps/desktop/src/main/cindy-brain/__tests__/atResourceProvider.test.ts+++ /dev/null@@ -1,183 +0,0 @@-import { describe, expect, it, vi } from 'vitest';--import type { InstalledGhost } from '../../../shared/ghost.js';-import {- GHOST_AT_RESOURCE_QUERY_TIMEOUT_MS,- GhostAtResourceQueryScheduler,- listGhostAtResourceProviders,- queryGhostAtResources,- resolveGhostAtResourceWorkingDir,- type GhostAtResourceProviderDeps,-} from '../atResourceProvider.js';--function ghost(overrides: Partial<InstalledGhost> = {}): InstalledGhost {- return {- dir: '/plugins/issues',- enabled: true,- manifest: {- schemaVersion: 2,- id: 'issues',- name: 'Issue Tracker',- version: '1.0.0',- kind: 'chip',- entry: 'main.js',- slots: ['tool'],- tools: [{ name: 'search_issues', description: 'Search issues without side effects' }],- atResourceProvider: { tool: 'search_issues' },- },- ...overrides,- };-}--function deps(overrides: Partial<GhostAtResourceProviderDeps> = {}): GhostAtResourceProviderDeps {- return {- listGhosts: () => [ghost()],- isAvailable: () => true,- isDisabledForWorkdir: () => false,- getSetupAssessment: () => ({ state: 'ready', revision: 1, groups: [] }),- callTool: vi.fn(async () => ({- ok: true as const,- result: {- items: [{ id: 'ISSUE-1', label: ' Fix\u202e\nlogin ', description: ' Open\tissue ' }],- },- })),- ...overrides,- };-}--describe('Plugin @ resource providers', () => {- it('uses authoritative local session scope and rejects draft paths', async () => {- const getSessionSnapshot = vi.fn(async (sessionId: string) => {- if (sessionId === 'local') return { workingDir: '/db/repo', remoteHostId: null };- if (sessionId === 'remote') return { workingDir: '/remote/repo', remoteHostId: 'host-1' };- return null;- });-- await expect(resolveGhostAtResourceWorkingDir({- sessionId: 'local',- workingDir: '/spoofed/repo',- }, getSessionSnapshot)).resolves.toEqual({ allowed: true, workingDir: '/db/repo' });- await expect(resolveGhostAtResourceWorkingDir({- sessionId: 'remote',- workingDir: '/spoofed/repo',- }, getSessionSnapshot)).resolves.toEqual({ allowed: false });- await expect(resolveGhostAtResourceWorkingDir({ sessionId: 'missing' }, getSessionSnapshot))- .resolves.toEqual({ allowed: false });- await expect(resolveGhostAtResourceWorkingDir({ workingDir: '/draft/repo' }, getSessionSnapshot))- .resolves.toEqual({ allowed: false });- await expect(resolveGhostAtResourceWorkingDir({}, getSessionSnapshot))- .resolves.toEqual({ allowed: false });- });-- it('lists eligible metadata without dispatching a tool', () => {- const harness = deps();- expect(listGhostAtResourceProviders(harness, '/repo')).toEqual([- { ghostId: 'issues', name: 'Issue Tracker' },- ]);- expect(harness.callTool).not.toHaveBeenCalled();- });-- it('fails closed when disabled, workdir-disabled or setup is not ready', async () => {- const disabled = deps({ listGhosts: () => [ghost({ enabled: false })] });- const workdirDisabled = deps({ isDisabledForWorkdir: () => true });- const setupRequired = deps({- getSetupAssessment: () => ({ state: 'required', revision: 1, groups: [] }),- });-- expect(listGhostAtResourceProviders(disabled)).toEqual([]);- expect(listGhostAtResourceProviders(workdirDisabled, '/repo')).toEqual([]);- await expect(queryGhostAtResources(setupRequired, { ghostId: 'issues' })).resolves- .toMatchObject({ success: false });- expect(setupRequired.callTool).not.toHaveBeenCalled();- });-- it('dispatches only the fixed query contract with a short host timeout', async () => {- const harness = deps();- const result = await queryGhostAtResources(harness, {- ghostId: 'issues',- query: ` login\n${'x'.repeat(200)}`,- limit: 100,- });-- expect(harness.callTool).toHaveBeenCalledWith({- ghostId: 'issues',- tool: 'search_issues',- args: { query: `login ${'x'.repeat(122)}`, limit: 20 },- timeoutMs: GHOST_AT_RESOURCE_QUERY_TIMEOUT_MS,- });- expect(result).toMatchObject({- success: true,- pluginName: 'Issue Tracker',- items: [{- id: 'ISSUE-1',- label: 'Fix login',- description: 'Open issue',- }],- });- expect(result.items[0]?.href).toBe(- 'cindy://plugin-resource/issues/search_issues/ISSUE-1',- );- });-- it('drops malformed, duplicate and excess result rows', async () => {- const harness = deps({- callTool: vi.fn(async () => ({- ok: true as const,- result: {- items: [- { id: 'A', label: 'First' },- { id: 'A', label: 'Duplicate' },- { id: 'BAD\u0000', label: 'Control' },- { id: 'B', label: '' },- { id: '😀'.repeat(128), label: 'Encoded href too long' },- { id: 'C', label: 'Third' },- ],- },- })),- });- const result = await queryGhostAtResources(harness, { ghostId: 'issues', limit: 2 });- expect(result.success && result.items.map((item) => item.id)).toEqual(['A', 'C']);- expect(result.truncated).toBe(true);- });-- it('allows one running query per Plugin and coalesces pending work to the latest query', async () => {- const deliveries: Array<(result: { ok: true; result: unknown }) => void> = [];- const callTool = vi.fn(() => new Promise<{ ok: true; result: unknown }>((resolve) => {- deliveries.push(resolve);- }));- const scheduler = new GhostAtResourceQueryScheduler(deps({ callTool }));-- const first = scheduler.query('window-1:session-1', { ghostId: 'issues', query: 'first' });- const superseded = scheduler.query('window-1:session-1', { ghostId: 'issues', query: 'second' });- const latest = scheduler.query('window-1:session-1', { ghostId: 'issues', query: 'latest' });- expect(callTool).toHaveBeenCalledTimes(1);- await expect(superseded).resolves.toMatchObject({- success: false,- error: 'Plugin resource search superseded',- });-- deliveries[0]({ ok: true, result: { items: [] } });- await expect(first).resolves.toMatchObject({ success: true });- await vi.waitFor(() => expect(callTool).toHaveBeenCalledTimes(2));- expect(callTool).toHaveBeenNthCalledWith(2, expect.objectContaining({- args: { query: 'latest', limit: 20 },- }));- deliveries[1]({ ok: true, result: { items: [] } });- await expect(latest).resolves.toMatchObject({ success: true });- });-- it('does not coalesce the same Plugin across window/task scopes', async () => {- const deliveries: Array<(result: { ok: true; result: unknown }) => void> = [];- const callTool = vi.fn(() => new Promise<{ ok: true; result: unknown }>((resolve) => {- deliveries.push(resolve);- }));- const scheduler = new GhostAtResourceQueryScheduler(deps({ callTool }));-- const first = scheduler.query('window-1:session-1', { ghostId: 'issues', query: 'one' });- const second = scheduler.query('window-2:session-2', { ghostId: 'issues', query: 'two' });- expect(callTool).toHaveBeenCalledTimes(2);- deliveries[0]({ ok: true, result: { items: [] } });- deliveries[1]({ ok: true, result: { items: [] } });- await expect(Promise.all([first, second])).resolves.toHaveLength(2);- });-});diff --git a/apps/desktop/src/main/cindy-brain/atResourceProvider.ts b/apps/desktop/src/main/cindy-brain/atResourceProvider.tsdeleted file mode 100644index cf9b150f37..0000000000--- a/apps/desktop/src/main/cindy-brain/atResourceProvider.ts+++ /dev/null@@ -1,276 +0,0 @@-import { buildPluginResourceReferenceHref } from '@cindy/maker-shared/agent-input-projection';--import type {- GhostSetupAssessment,- GhostToolCallResult,- InstalledGhost,-} from '../../shared/ghost.js';--const QUERY_MAX_CHARS = 128;-const RESULT_LIMIT_MAX = 20;-const RESULT_MAX_BYTES = 64 * 1024;-const PROVIDER_LIMIT_MAX = 40;-const RESOURCE_HREF_MAX_CHARS = 1_500;-export const GHOST_AT_RESOURCE_QUERY_TIMEOUT_MS = 4_000;--export interface GhostAtResourceProviderItem {- ghostId: string;- name: string;- description?: string;-}--export interface GhostAtResourceItem {- id: string;- label: string;- description?: string;- href: string;-}--export interface GhostAtResourceProviderDeps {- listGhosts(): InstalledGhost[];- isAvailable(ghostId: string): boolean;- isDisabledForWorkdir(ghostId: string, workingDir?: string): boolean;- getSetupAssessment(ghostId: string): GhostSetupAssessment;- callTool(request: {- ghostId: string;- tool: string;- args: Record<string, unknown>;- timeoutMs: number;- }): Promise<GhostToolCallResult>;-}--export type GhostAtResourceQueryResult =- | { success: true; pluginName: string; items: GhostAtResourceItem[]; truncated: boolean }- | { success: false; error: string; items: []; truncated: false };--interface ScheduledQuery {- request: Parameters<typeof queryGhostAtResources>[1];- resolve: (result: GhostAtResourceQueryResult) => void;-}--/** One running call plus one coalesced latest query per window/task/Plugin scope. */-export class GhostAtResourceQueryScheduler {- private readonly states = new Map<string, { pending?: ScheduledQuery }>();-- constructor(private readonly deps: GhostAtResourceProviderDeps) {}-- query(- scopeKey: string,- request: Parameters<typeof queryGhostAtResources>[1],- ): Promise<GhostAtResourceQueryResult> {- return new Promise((resolve) => {- const key = `${scopeKey}\u0000${request.ghostId}`;- const active = this.states.get(key);- if (active) {- active.pending?.resolve({- success: false,- error: 'Plugin resource search superseded',- items: [],- truncated: false,- });- active.pending = { request, resolve };- return;- }- const state: { pending?: ScheduledQuery } = {};- this.states.set(key, state);- void this.run(key, { request, resolve }, state);- });- }-- private async run(- key: string,- scheduled: ScheduledQuery,- state: { pending?: ScheduledQuery },- ): Promise<void> {- let result: GhostAtResourceQueryResult;- try {- result = await queryGhostAtResources(this.deps, scheduled.request);- } catch {- result = {- success: false,- error: 'Plugin resource search failed',- items: [],- truncated: false,- };- }- scheduled.resolve(result);- const next = state.pending;- if (next) {- state.pending = undefined;- void this.run(key, next, state);- return;- }- this.states.delete(key);- }-}--export interface GhostAtResourceSessionSnapshot {- workingDir?: string | null;- remoteHostId?: string | null;-}--/** Resolve Plugin execution scope without trusting a renderer-provided session workdir. */-export async function resolveGhostAtResourceWorkingDir(- raw: Record<string, unknown>,- getSessionSnapshot: (- sessionId: string,- ) => Promise<GhostAtResourceSessionSnapshot | null | undefined>,-): Promise<{ allowed: boolean; workingDir?: string }> {- if (typeof raw.sessionId === 'string' && raw.sessionId.length > 0) {- const snapshot = await getSessionSnapshot(raw.sessionId.slice(0, 256));- // Local Plugin tools never run on behalf of remote execution contexts.- if (!snapshot || snapshot.remoteHostId) return { allowed: false };- return {- allowed: true,- ...(snapshot.workingDir ? { workingDir: snapshot.workingDir } : {}),- };- }- // New-task drafts have no persisted session yet. The renderer's workingDir- // cannot be used as a Plugin policy scope because it is not authoritative.- return { allowed: false };-}--function oneLine(value: unknown, maxLength: number): string {- return typeof value === 'string'- ? value- .replace(/[\u0000-\u001f\u007f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g, ' ')- .replace(/\s+/g, ' ')- .trim()- .slice(0, maxLength)- : '';-}--function eligibleGhost(- deps: GhostAtResourceProviderDeps,- ghostId: string,- workingDir?: string,- candidate?: InstalledGhost,-): InstalledGhost | null {- if (!deps.isAvailable(ghostId)) return null;- const ghost = candidate?.manifest.id === ghostId- ? candidate- : deps.listGhosts().find((item) => item.manifest.id === ghostId);- if (- !ghost?.enabled- || !ghost.manifest.atResourceProvider- || deps.isDisabledForWorkdir(ghostId, workingDir)- ) return null;- const tool = ghost.manifest.atResourceProvider.tool;- if (!ghost.manifest.tools?.some((candidate) => candidate.name === tool)) return null;- try {- if (deps.getSetupAssessment(ghostId).state !== 'ready') return null;- } catch {- return null;- }- return ghost;-}--/** List metadata only. No Plugin tool runs until the user selects one provider. */-export function listGhostAtResourceProviders(- deps: GhostAtResourceProviderDeps,- workingDir?: string,-): GhostAtResourceProviderItem[] {- const items: GhostAtResourceProviderItem[] = [];- for (const ghost of deps.listGhosts()) {- if (items.length >= PROVIDER_LIMIT_MAX) break;- if (!eligibleGhost(deps, ghost.manifest.id, workingDir, ghost)) continue;- const name = oneLine(ghost.manifest.name, 128);- if (!name) continue;- const description = oneLine(ghost.manifest.description, 256);- items.push({- ghostId: ghost.manifest.id,- name,- ...(description ? { description } : {}),- });- }- return items;-}--export async function queryGhostAtResources(- deps: GhostAtResourceProviderDeps,- request: {- ghostId: string;- workingDir?: string;- query?: string;- limit?: number;- },-): Promise<GhostAtResourceQueryResult> {- const ghostId = oneLine(request.ghostId, 32);- const ghost = ghostId ? eligibleGhost(deps, ghostId, request.workingDir) : null;- if (!ghost) {- return { success: false, error: 'Plugin resource provider unavailable', items: [], truncated: false };- }-- const query = oneLine(request.query ?? '', QUERY_MAX_CHARS);- const limit = Number.isFinite(request.limit)- ? Math.max(1, Math.min(RESULT_LIMIT_MAX, Math.floor(request.limit as number)))- : RESULT_LIMIT_MAX;- const tool = ghost.manifest.atResourceProvider!.tool;- const result = await deps.callTool({- ghostId,- tool,- args: { query, limit },- timeoutMs: GHOST_AT_RESOURCE_QUERY_TIMEOUT_MS,- });- if (!result.ok) {- return {- success: false,- error: oneLine(result.message, 256) || 'Plugin resource search failed',- items: [],- truncated: false,- };- }-- if (!result.result || typeof result.result !== 'object' || Array.isArray(result.result)) {- return { success: false, error: 'Plugin returned an invalid resource list', items: [], truncated: false };- }- let encoded: string | undefined;- try {- encoded = JSON.stringify(result.result);- } catch {- return { success: false, error: 'Plugin returned an invalid resource list', items: [], truncated: false };- }- if (!encoded) {- return { success: false, error: 'Plugin returned an invalid resource list', items: [], truncated: false };- }- if (Buffer.byteLength(encoded, 'utf8') > RESULT_MAX_BYTES) {- return { success: false, error: 'Plugin resource list is too large', items: [], truncated: false };- }- const rawItems = (result.result as Record<string, unknown>).items;- if (!Array.isArray(rawItems)) {- return { success: false, error: 'Plugin returned an invalid resource list', items: [], truncated: false };- }-- const items: GhostAtResourceItem[] = [];- const seen = new Set<string>();- for (const rawItem of rawItems) {- if (items.length >= limit) break;- if (!rawItem || typeof rawItem !== 'object' || Array.isArray(rawItem)) continue;- const record = rawItem as Record<string, unknown>;- const id = typeof record.id === 'string' ? record.id : '';- const label = oneLine(record.label, 128);- if (- !id.trim()- || id.length > 256- || /[\u0000-\u001f\u007f\u2028\u2029]/.test(id)- || !label- || seen.has(id)- ) continue;- seen.add(id);- const description = oneLine(record.description, 256);- const href = buildPluginResourceReferenceHref({ ghostId, tool, resourceId: id });- if (href.length > RESOURCE_HREF_MAX_CHARS) continue;- items.push({- id,- label,- ...(description ? { description } : {}),- href,- });- }- return {- success: true,- pluginName: oneLine(ghost.manifest.name, 128) || ghostId,- items,- truncated: rawItems.length > items.length,- };-}diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.tsindex 0236e03583..afd672800b 100644--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@ -1064,7 +1064,6 @@ my-ghost/// (仅检查插件启用状态与 tools 声明)。除非你的插件完全靠 panel 或 subscribe 驱动,// 否则请始终声明一个 command。"tools": [ /* 见 §3 */ ],- "atResourceProvider": { "tool": "search_resources" }, // 可选:把一个已声明、无副作用的搜索工具接入 @,见 §3.1"cindy": { "image": ["generate", "edit"] }, // 声明了 cindy 槽时必写:能力详单,见下// 三个类目:image / video 的动作是 "generate" | "edit";media 的动作只有// "deposit"(把你手里的媒体字节寄存进总仓换指纹,见 §4.0.1)。按需申请,@@ -1328,41 +1327,10 @@ node 详单**不接受** \`command\` / \`args\` / \`shell\` / \`env\` 或其它写行为规则(如"用户原话透传,不要扩写"、"仅当用户显式说 X 才传 Y")——AI 会照做。这是你影响 AI 行为的**唯一合法通道**,不要试图在别处塞指令。-### 3.1 可选:接入 @ 业务资源搜索+### 3.1 @ 插件入口-插件可把一个**已经声明并经过权限确认**的工具接到 Composer 的 \`@\` 面板:--\`\`\`json-"atResourceProvider": { "tool": "search_resources" }-\`\`\`--本入口复用已有的 \`"tool"\` 槽,不新增 slot;\`tool\` 必须逐字引用 \`tools[].name\`。这不会增加-底层工具权限,但新增了一个明确的调用入口,因此会在安装/更新确认中单独披露。裸 \`@\` 只展示插件入口,-不会调用工具。用户明确选中你的插件后,宿主才只向这个工具发送:--\`\`\`json-{ "query": "用户输入", "limit": 20 }-\`\`\`--工具必须无副作用,并在 4 秒内返回固定摘要结构:--\`\`\`json-{- "items": [{- "id": "业务对象的不透明稳定 ID",- "label": "单行展示名",- "description": "可选的单行摘要"- }]-}-\`\`\`--同一个工具还必须支持把某条返回项的完整 \`id\` 作为 \`query\` 精确解析,并把-该对象放在结果首项;这样 Agent 收到不透明 ID 后可以按需读取最新信息。--最多返回 20 项;\`id\` 最长 256 字符,\`label\` 最长 128 字符,-\`description\` 最长 256 字符。不要返回正文、凭证、HTML、指令或自定义调用参数;-宿主只保留 ID 和可读摘要,并用固定格式投影给 Agent。插件 locale 不增加本字段的-翻译,入口展示名直接复用已本地化的插件 \`name\`。+Composer 的 \`@\` 面板只展示已安装且可用的插件入口;插件作者无需声明资源搜索字段。+历史的 \`manifest.atResourceProvider\` 已移除且不再生效,不能通过该字段接入资源搜索。## 3.5 工具面设计:直接声明,还是两段式目录diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex ae2aad951f..4d0ed9a6c8 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -138,12 +138,6 @@ import {} from './gitlabAccountsMigration.js';import { GHOST_SCHEME, ghostExternalLinkUrls, parseGhostPartition } from '../../shared/ghost.js';import { GhostPipeDispatcher } from './pipeDispatcher.js';-import {- GhostAtResourceQueryScheduler,- listGhostAtResourceProviders,- resolveGhostAtResourceWorkingDir,- type GhostAtResourceProviderDeps,-} from './atResourceProvider.js';import { GhostCardService, parseCardHeightReport } from './cardService.js';import { GhostCardActionDispatcher } from './cardActionDispatch.js';import { GhostSessionActivityTracker } from './ghostSessionActivity.js';@@ -4257,56 +4251,6 @@ export function registerGhostIpc(): void {event.returnValue = { ghosts: availableGhosts() };});- const atResourceProviderDeps: GhostAtResourceProviderDeps = {- listGhosts: () => manager.list(),- isAvailable: isGhostAvailableForActiveSession,- isDisabledForWorkdir: (ghostId, workingDir) =>- isGhostDisabledForWorkdir(ghostId, workingDir),- getSetupAssessment: getGhostSetupAssessment,- callTool: (request) => getGhostPipeDispatcher().callGhostTool(request),- };- const atResourceQueryScheduler = new GhostAtResourceQueryScheduler(atResourceProviderDeps);- ipcMain.handle('ghosts:at-resource-providers:list', async (event, raw: unknown) => {- assertTrustedAppRendererEvent(event);- const request = raw && typeof raw === 'object' && !Array.isArray(raw)- ? raw as Record<string, unknown>- : {};- const scope = await resolveGhostAtResourceWorkingDir(request, getSessionFsSnapshot);- return {- items: scope.allowed- ? listGhostAtResourceProviders(atResourceProviderDeps, scope.workingDir)- : [],- };- });- ipcMain.handle('ghosts:at-resources:query', async (event, raw: unknown) => {- assertTrustedAppRendererEvent(event);- if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {- throwIpcError('INVALID_PARAMS', 'Plugin resource query must be an object');- }- const request = raw as Record<string, unknown>;- if (typeof request.ghostId !== 'string') {- throwIpcError('INVALID_PARAMS', 'ghostId is required');- }- const scope = await resolveGhostAtResourceWorkingDir(request, getSessionFsSnapshot);- if (!scope.allowed) {- return {- success: false,- error: 'Plugin resource provider unavailable',- items: [],- truncated: false,- };- }- const requestScope = typeof request.sessionId === 'string' && request.sessionId.length > 0- ? `session:${request.sessionId.slice(0, 256)}`- : `draft:${scope.workingDir ?? ''}`;- return atResourceQueryScheduler.query(`${event.sender.id}:${requestScope}`, {- ghostId: request.ghostId,- ...(scope.workingDir ? { workingDir: scope.workingDir } : {}),- ...(typeof request.query === 'string' ? { query: request.query } : {}),- ...(typeof request.limit === 'number' ? { limit: request.limit } : {}),- });- });-// Plugin 页的已安装快捷行按最近成功使用排序。历史是主机 UI 状态,不写入// publisher-owned manifest;同步读保证列表首帧不先按扫描序再跳成最近序。ipcMain.on('ghosts:recent-usage', (event) => {diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 3137d40012..450df8a5ec 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -915,22 +915,6 @@ contextBridge.exposeInMainWorld('electronAPI', {/** 配置就绪检查(插件页「使用」前置门;main 现查凭证/账号/连接/kv)。 */setupStatus: (id: string): Promise<unknown> =>ipcRenderer.invoke('ghosts:setup-status', id),- listAtResourceProviders: (params: { sessionId?: string; workingDir?: string }): Promise<{- items: Array<{ ghostId: string; name: string; description?: string }>;- }> => ipcRenderer.invoke('ghosts:at-resource-providers:list', params),- queryAtResources: (params: {- ghostId: string;- sessionId?: string;- workingDir?: string;- query?: string;- limit?: number;- }): Promise<{- success: boolean;- error?: string;- pluginName?: string;- items: Array<{ id: string; label: string; description?: string; href: string }>;- truncated: boolean;- }> => ipcRenderer.invoke('ghosts:at-resources:query', params),install: (lizFilePath: string,opts: { enable?: boolean; expectedPackageSha256: string },diff --git a/apps/desktop/src/renderer/__tests__/atResourceService.test.ts b/apps/desktop/src/renderer/__tests__/atResourceService.test.tsindex 6e66d2ce49..e68cb5271a 100644--- a/apps/desktop/src/renderer/__tests__/atResourceService.test.ts+++ b/apps/desktop/src/renderer/__tests__/atResourceService.test.ts@@ -11,7 +11,6 @@ import {getAtDirectoryCompletionQuery,mergeAtResourceItems,scanAtResources,- scanPluginAtResources,} from '@/lib/atResourceService';function stubApi(options: {@@ -25,8 +24,6 @@ function stubApi(options: {workspaceError?: Error;contextError?: Error;taskError?: Error;- pluginProviders?: unknown;- pluginResources?: unknown;}) {vi.stubGlobal('window', {electronAPI: {@@ -60,14 +57,6 @@ function stubApi(options: {: vi.fn().mockResolvedValue(options.taskSearch),},},- ghosts: {- listAtResourceProviders: vi.fn().mockResolvedValue(- options.pluginProviders ?? { items: [] },- ),- queryAtResources: vi.fn().mockResolvedValue(- options.pluginResources ?? { success: true, items: [], truncated: false },- ),- },},});}@@ -93,20 +82,20 @@ describe('filterAtResources', () => {{ type: 'dir' as const, name: 'apps', relPath: 'apps' },{ type: 'session' as const, name: 'Release planning', relPath: 'cindy://session/1' },{ type: 'agent' as const, name: 'reviewer', relPath: '.claude/agents/reviewer.md' },- { type: 'plugin-provider' as const, name: 'Issues', relPath: 'issues' },+ { type: 'plugin-command' as const, name: 'Issues', relPath: 'issues' },];it('hides files and directories until the user types a query', () => {expect(filterAtResources(items, '').map((item) => item.type)).toEqual(['file-picker','agent',- 'plugin-provider',+ 'plugin-command',]);});it('keeps each empty-query source compact', () => {const providers = Array.from({ length: 5 }, (_, index) => ({- type: 'plugin-provider' as const,+ type: 'plugin-command' as const,name: `Provider ${index}`,relPath: `provider-${index}`,}));@@ -569,57 +558,4 @@ describe('scanAtResources context providers', () => {);});- it('lists Plugin entries without running them, then searches only the selected provider', async () => {- stubApi({- workspace: { success: true, items: [] },- pluginProviders: {- items: [{ ghostId: 'issues', name: 'Issue Tracker', description: 'Project issues' }],- },- pluginResources: {- success: true,- pluginName: 'Issue Tracker',- items: [{- id: 'ISSUE-1',- label: 'Fix login',- description: 'Open issue',- href: 'cindy://plugin-resource/issues/search_issues/ISSUE-1',- }],- truncated: false,- },- });-- const catalog = await scanAtResources(- 'D:\\repo',- 'codex',- 2000,- undefined,- undefined,- { sessionId: 'session-1' },- );- expect(catalog.items).toMatchObject([{- type: 'plugin-provider',- name: 'Issue Tracker',- pluginId: 'issues',- }]);- expect(window.electronAPI.ghosts.queryAtResources).not.toHaveBeenCalled();-- const searched = await scanPluginAtResources(- catalog.items[0],- 'login',- 'D:\\repo',- 'session-1',- );- expect(window.electronAPI.ghosts.queryAtResources).toHaveBeenCalledWith({- ghostId: 'issues',- sessionId: 'session-1',- workingDir: 'D:\\repo',- query: 'login',- limit: 20,- });- expect(searched.items).toMatchObject([{- type: 'plugin-resource',- name: 'Fix login',- sourceLabel: 'Issue Tracker',- }]);- });});diff --git a/apps/desktop/src/renderer/__tests__/chatInputGhostSnapshot.test.ts b/apps/desktop/src/renderer/__tests__/chatInputGhostSnapshot.test.tsindex 283659bc56..194948e434 100644--- a/apps/desktop/src/renderer/__tests__/chatInputGhostSnapshot.test.ts+++ b/apps/desktop/src/renderer/__tests__/chatInputGhostSnapshot.test.ts@@ -29,4 +29,13 @@ describe('ChatInput Ghost snapshot contract', () => {'const eligibleGhosts = filterGhostsForWorkdir(\n installedGhostsRef.current,\n workingDirRef.current,\n );',);});++ it('does not expose controller-local plugin rows in device-link sessions', () => {+ expect(source).toContain(+ 'if (deviceLinkDeviceId) return [];',+ );+ expect(source).toContain(+ '[deviceLinkDeviceId, pluginsForMenu, pluginAvailableIds]',+ );+ });});diff --git a/apps/desktop/src/renderer/__tests__/composerQuotePaletteBoundary.test.ts b/apps/desktop/src/renderer/__tests__/composerQuotePaletteBoundary.test.tsindex 1a606b1752..1d21100ca7 100644--- a/apps/desktop/src/renderer/__tests__/composerQuotePaletteBoundary.test.ts+++ b/apps/desktop/src/renderer/__tests__/composerQuotePaletteBoundary.test.ts@@ -18,17 +18,15 @@ describe('composer quote palette boundary wiring', () => {expect(triggerSource).toContain("textSoFar = ''; // chips reset the @ / slash run");});- it('keeps Plugin scope out of persisted composer text', () => {+ it('routes @ plugin selection through the shared command placement', () => {const source = readFileSync(resolve(process.cwd(), 'src/renderer/components/new-chat/ChatInput.tsx'),'utf8',);- expect(source).toContain('const activeAtScopeFrom = atPluginScope?.triggerFrom;');- expect(source).toContain('detectTrigger(editor, activeAtScopeFrom)');- expect(source).toContain("tr.replaceWith(from, to, editor.schema.text('@'));");- expect(source).not.toContain('editor.schema.text(`@${item.pluginId}:`)');- expect(source).toMatch(/if \(atPluginScope\) \{\r?\n\s+atScanSeqRef\.current \+= 1;/);+ expect(source).toContain("type: 'plugin-command'");+ expect(source).toContain('placeGhostAtComposerStart(editor, ghost, installedGhostsRef.current)');+ expect(source).not.toContain('scanPluginAtResources');});it('records a scheduled mention query before reserving its scan sequence', () => {diff --git a/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx b/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsxindex 4e02af88c5..ed11267e18 100644--- a/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx+++ b/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx@@ -27,7 +27,6 @@ import {MessageCircleQuestion,PanelLeft,PanelRight,- Plug,Sparkles,ShieldAlert,Terminal,@@ -49,7 +48,6 @@ const KIND_ICON: Record<GhostPermissionItem['kind'], LucideIcon> = {agent: Bot,node: Cpu,tool: Wrench,- 'at-resource': Plug,command: Terminal,panel: PanelRight,code: FileCode2,diff --git a/apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx b/apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsxindex f622660da3..5fe1d1a50d 100644--- a/apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx+++ b/apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx@@ -6,15 +6,15 @@* in `atResourceService.ts`; this component handles:* - focus-row tracking (↑↓ / hover)* - empty / loading / error states+ * - root-query sections for addable resources and installed plugins* - click-outside close*- * Per F2 spec: 480px width, 44px row height, no tabs, no group headers,- * agents and files share the same list.+ * Per F2 spec: 480px width and 44px row height. The root query uses compact+ * section labels to separate addable resources from installed plugins.*/import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import {- ArrowLeft,File as FileIcon,Folder as FolderIcon,Globe2,@@ -27,21 +27,26 @@ import {import { cn } from '@/lib/utils';import { Tip } from '@/components/ui/tooltip';+import { GhostPluginIcon } from '@/features/plugin/GhostPluginIcon';import {AT_FILE_PICKER_RESOURCE,- AT_MENTION_SEARCH_RESULT_LIMIT,filterAtResources,type AtResourceItem,} from '@/lib/atResourceService';const TOOLTIP_FALLBACK_H = 120;const VIEWPORT_PAD = 8;+const SECTION_HEADER_H = 24;type TooltipMeasure = {key: string | null;height: number;};+function isPluginItem(item: AtResourceItem): boolean {+ return item.type === 'plugin-command' || item.type === 'plugin-resource';+}+export type AtPanelState =| { kind: 'loading' }| { kind: 'error'; message: string }@@ -57,11 +62,8 @@ interface AtMentionPanelProps {onSelect: (item: AtResourceItem) => void;onClose: () => void;onRetry: () => void;- /** Selected Plugin provider; its query is scoped and never broadcast. */- scopedProviderName?: string;/** Whether the local task can launch the native file picker. */filePickerEnabled?: boolean;- onBack?: () => void;/** Panel max-height in px. Defaults to 400 (chat view); NewMaker passes a smaller value so the popover doesn't cover the logo. */maxHeight?: number;}@@ -74,9 +76,7 @@ export function AtMentionPanel({onSelect,onClose,onRetry,- scopedProviderName,filePickerEnabled = false,- onBack,maxHeight = 400,}: AtMentionPanelProps) {const { t } = useTranslation();@@ -93,14 +93,24 @@ export function AtMentionPanel({const filtered = useMemo(() => {if (state.kind !== 'ready') return [];- if (scopedProviderName) return state.items.slice(0, AT_MENTION_SEARCH_RESULT_LIMIT);const items = filePickerEnabled? [AT_FILE_PICKER_RESOURCE, ...state.items]: state.items;return filterAtResources(items, query);- }, [state, query, scopedProviderName, filePickerEnabled]);- const hasScope = !!scopedProviderName;- const isEmptyRootQuery = !hasScope && !query.trim();+ }, [state, query, filePickerEnabled]);+ const isEmptyRootQuery = !query.trim();+ const indexedFiltered = useMemo(+ () => filtered.map((item, index) => ({ item, index })),+ [filtered],+ );+ const addItems = isEmptyRootQuery+ ? indexedFiltered.filter(({ item }) => !isPluginItem(item))+ : [];+ const pluginItems = isEmptyRootQuery+ ? indexedFiltered.filter(({ item }) => isPluginItem(item))+ : [];+ const addSectionVisible = isEmptyRootQuery && addItems.length > 0;+ const pluginSectionVisible = isEmptyRootQuery && pluginItems.length > 0;useEffect(() => {if (filtered.length === 0) return;@@ -146,7 +156,11 @@ export function AtMentionPanel({const bottomBoundary = Math.min(panelRect.bottom, window.innerHeight - VIEWPORT_PAD);const maxTooltipHeight = Math.max(1, Math.min(maxHeight, bottomBoundary - VIEWPORT_PAD));const measuredHeight = Math.min(tooltipHeight, maxTooltipHeight);- const rawTop = (hasScope ? 46 : 6) + focusedIndex * 44 - panelScroll;+ const focusedIsPlugin = isEmptyRootQuery && !!focusedItem && isPluginItem(focusedItem);+ const sectionOffset = isEmptyRootQuery+ ? SECTION_HEADER_H + (focusedIsPlugin && addSectionVisible ? SECTION_HEADER_H : 0)+ : 0;+ const rawTop = 6 + sectionOffset + focusedIndex * 44 - panelScroll;const minTop = VIEWPORT_PAD - rootRect.top;const bottomBoundaryInRoot = bottomBoundary - rootRect.top;const top = Math.max(minTop, Math.min(rawTop, bottomBoundaryInRoot - measuredHeight));@@ -154,7 +168,16 @@ export function AtMentionPanel({top: Math.round(top),maxHeight: Math.round(maxTooltipHeight),});- }, [showTooltip, focusedIndex, panelScroll, maxHeight, tooltipHeight, hasScope]);+ }, [+ showTooltip,+ focusedIndex,+ focusedItem,+ panelScroll,+ maxHeight,+ tooltipHeight,+ isEmptyRootQuery,+ addSectionVisible,+ ]);const tooltipVisible = showTooltip && !!tooltipPos;useLayoutEffect(() => {@@ -188,8 +211,10 @@ export function AtMentionPanel({meta = item.description || t('newChat.atMention.desktopWindow');} else if (item.type === 'session') {meta = t('newChat.atMention.task');- } else if (item.type === 'plugin-provider') {- meta = t('newChat.atMention.pluginResources');+ } else if (item.type === 'plugin-command') {+ // Plugin rows follow the compact icon + name presentation used by the+ // installed-plugin menu; the command remains an internal selection key.+ meta = '';} else if (item.type === 'plugin-resource') {meta = item.sourceLabel || t('newChat.atMention.pluginResource');} else {@@ -213,7 +238,7 @@ export function AtMentionPanel({? Monitor: item.type === 'session'? History- : item.type === 'plugin-provider' || item.type === 'plugin-resource'+ : item.type === 'plugin-command' || item.type === 'plugin-resource'? Plug: FileIcon;@@ -234,7 +259,16 @@ export function AtMentionPanel({focused && 'bg-[var(--cmd-palette-item-hover)]',)}>- <Icon size={16} className="shrink-0 text-[var(--cmd-palette-item-icon)]" />+ {isPluginItem(item) ? (+ <GhostPluginIcon+ iconDataUrl={item.iconDataUrl}+ iconId={item.pluginId ?? item.relPath}+ iconName={item.type === 'plugin-resource' ? (item.sourceLabel ?? item.name) : item.name}+ size="menu"+ />+ ) : (+ <Icon size={16} className="shrink-0 text-[var(--cmd-palette-item-icon)]" />+ )}<spanclassName={cn('min-w-0 truncate text-[14px] font-medium',@@ -276,32 +310,6 @@ export function AtMentionPanel({)}style={{ boxShadow: 'var(--cmd-palette-shadow)', maxHeight }}>- {hasScope && (- <div className="sticky top-0 z-10 flex h-[40px] items-center gap-2 bg-[var(--cmd-palette-bg)] px-[4px]">- <button- type="button"- aria-label={t('newChat.atMention.backToAll')}- onMouseDown={(event) => {- event.preventDefault();- onBack?.();- }}- className={cn(- 'flex size-[32px] shrink-0 items-center justify-center rounded-[6px]',- 'text-[var(--cmd-palette-item-meta)] hover:bg-[var(--cmd-palette-item-hover)]',- )}- >- <ArrowLeft size={16} />- </button>- <span className="min-w-0 truncate text-[13px] font-medium text-[var(--cmd-palette-item-text)]">- {scopedProviderName}- </span>- {scopedProviderName && (- <span className="ml-auto shrink-0 text-[12px] text-[var(--cmd-palette-item-meta)]">- {t('newChat.atMention.pluginResources')}- </span>- )}- </div>- )}{state.kind === 'loading' && (<div className="space-y-[4px] p-[4px]">{[0, 1, 2].map((i) => (@@ -352,7 +360,34 @@ export function AtMentionPanel({)}{state.kind === 'ready' && filtered.length > 0 && (<>- {filtered.map((item, idx) => renderItemRow(item, idx))}+ {isEmptyRootQuery ? (+ <>+ {addSectionVisible && (+ <div+ className={cn(+ 'flex h-[24px] items-center px-[10px]',+ 'text-[12px] font-medium text-[var(--cmd-palette-item-meta)]',+ )}+ >+ {t('newChat.atMention.add')}+ </div>+ )}+ {addItems.map(({ item, index }) => renderItemRow(item, index))}+ {pluginSectionVisible && (+ <div+ className={cn(+ 'flex h-[24px] items-center px-[10px]',+ 'text-[12px] font-medium text-[var(--cmd-palette-item-meta)]',+ )}+ >+ {t('newChat.atMention.plugins')}+ </div>+ )}+ {pluginItems.map(({ item, index }) => renderItemRow(item, index))}+ </>+ ) : (+ filtered.map((item, idx) => renderItemRow(item, idx))+ )}{isEmptyRootQuery && (<divclassName={cn(diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsxindex d3cc90485a..308ec94c86 100644--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx@@ -189,19 +189,17 @@ import {import { QuickStartPillMark } from './QuickStartPillMark';import { ToolPayloadLightbox } from '@/components/chat/ToolPayloadLightbox';import { Fragment, Slice, type Node as ProseMirrorNode } from '@tiptap/pm/model';-import { Selection, TextSelection, type Transaction } from '@tiptap/pm/state';+import { Selection, TextSelection } from '@tiptap/pm/state';import * as sessionService from '@/lib/sessionService';import { getModelById } from '@/lib/modelDefinitions';import { loadAllCommands, filterSlashCommands, type UnifiedCommand } from '@/lib/slashCommands';import {AT_FILE_PICKER_RESOURCE,AT_MENTION_EMPTY_WORKSPACE_SCAN_CAP,- AT_MENTION_SEARCH_RESULT_LIMIT,createAtResourceFromNativePath,getAtDirectoryCompletionQuery,mergeAtResourceItems,scanAtResources,- scanPluginAtResources,filterAtResources,type AtResourceItem,} from '@/lib/atResourceService';@@ -763,7 +761,7 @@ type TriggerState = TriggerSlash | TriggerAt | { kind: 'none' };*/const GHOST_SIGIL_CHARS = ['$', '$', '¥', '¥'] as const;-function detectTrigger(editor: Editor, activeAtScopeFrom?: number): TriggerState {+function detectTrigger(editor: Editor): TriggerState {const { state } = editor;const { selection } = state;if (!selection.empty) return { kind: 'none' };@@ -850,13 +848,6 @@ function detectTrigger(editor: Editor, activeAtScopeFrom?: number): TriggerStateconst allowed = atIdx === 0 || /\s/.test(before);const after = textSoFar.slice(atIdx + 1);const from = pos - (textSoFar.length - atIdx);- if (allowed && activeAtScopeFrom === from && !/[\r\n]/.test(after)) {- return {- kind: 'at',- query: after,- from,- };- }if (allowed && !/\s/.test(after)) {return {kind: 'at',@@ -2381,6 +2372,26 @@ export function ChatInput({),[ghostsForCommand],);+ const atPluginItems = useMemo<AtResourceItem[]>(+ () => {+ // device-link 远程会话的插件运行在被控端;控制端清单既不代表远端+ // 已安装状态,选择后也无法用本地 InstalledGhost 解析并插入命令。+ if (deviceLinkDeviceId) return [];+ return pluginsForMenu+ .filter((ghost) => pluginAvailableIds.has(ghost.manifest.id) && ghost.manifest.command)+ .map((ghost) => ({+ type: 'plugin-command',+ name: ghost.manifest.name,+ relPath: ghost.manifest.command!,+ pluginId: ghost.manifest.id,+ ...(ghost.iconDataUrl ? { iconDataUrl: ghost.iconDataUrl } : {}),+ sourceLabel: ghost.manifest.command!,+ _nameLower: `${ghost.manifest.name} ${ghost.manifest.command}`.toLowerCase(),+ _relPathLower: `${ghost.manifest.command} ${ghost.manifest.id}`.toLowerCase(),+ }));+ },+ [deviceLinkDeviceId, pluginsForMenu, pluginAvailableIds],+ );useEffect(() => {setGhostCommandRoster(editor, ghostsForCommand);}, [editor, ghostsForCommand]);@@ -3202,13 +3213,8 @@ export function ChatInput({);// ── Slash / At panel state ─────────────────────────────────────────- const [atPluginScope, setAtPluginScope] = useState<{- provider: AtResourceItem;- triggerFrom: number;- } | null>(null);- const activeAtScopeFrom = atPluginScope?.triggerFrom;const trigger: TriggerState = editor- ? detectTrigger(editor, activeAtScopeFrom)+ ? detectTrigger(editor): { kind: 'none' };// Slash commands — palette refactor 后改成 loadAllCommands 一次性拉三源(desktop +@@ -3317,6 +3323,9 @@ export function ChatInput({if (prev.kind === 'ready' && normalizedQuery) {return { ...prev, searching: true };}+ if (atPluginItems.length > 0) {+ return { kind: 'ready', items: atPluginItems, truncated: false, searching: true };+ }return { kind: 'loading' };});scanAtResources(@@ -3335,8 +3344,8 @@ export function ChatInput({setAtState((prev) => ({kind: 'ready',items: preservePreviousItems && prev.kind === 'ready'- ? mergeAtResourceItems(prev.items, partial.items)- : partial.items,+ ? mergeAtResourceItems(prev.items, [...atPluginItems, ...partial.items])+ : [...atPluginItems, ...partial.items],truncated: partial.truncated || (prev.kind === 'ready' && prev.truncated),searching: true,}));@@ -3346,10 +3355,18 @@ export function ChatInput({.then((res) => {if (atScanSeqRef.current !== seq) return;if (!res.success) {- setAtState({ kind: 'error', message: res.error ?? 'scan failed' });+ if (atPluginItems.length > 0) {+ setAtState({ kind: 'ready', items: atPluginItems, truncated: false });+ } else {+ setAtState({ kind: 'error', message: res.error ?? 'scan failed' });+ }return;}- setAtState({ kind: 'ready', items: res.items, truncated: res.truncated });+ setAtState({+ kind: 'ready',+ items: [...atPluginItems, ...res.items],+ truncated: res.truncated,+ });}).catch((err: unknown) => {if (atScanSeqRef.current !== seq) return;@@ -3357,56 +3374,10 @@ export function ChatInput({setAtState({ kind: 'error', message: m });});},- [workingDir, paletteAgentKind, isRemoteSession, sessionId, deviceLinkDeviceId, t],- );-- useEffect(() => {- if (!editor || !atPluginScope) return;- const handleTransaction = ({ transaction }: { transaction: Transaction }) => {- // A caret-only move makes the end of a multi-word query ambiguous.- // Leave Plugin scope before the user can select a row against a prefix- // and accidentally leave the query suffix behind.- if (!transaction.docChanged && transaction.selectionSet) {- atScanSeqRef.current += 1;- setAtPluginScope(null);- runAtScan();- }- };- editor.on('transaction', handleTransaction);- return () => {- editor.off('transaction', handleTransaction);- };- }, [editor, atPluginScope, runAtScan]);-- const runAtPluginScan = useCallback(- (provider: AtResourceItem, query: string, reservedSeq?: number) => {- const seq = reservedSeq ?? ++atScanSeqRef.current;- if (atScanSeqRef.current !== seq) return;- setAtState((prev) => prev.kind === 'ready'- ? { ...prev, searching: true }- : { kind: 'loading' });- scanPluginAtResources(provider, query, workingDir ?? undefined, sessionId)- .then((res) => {- if (atScanSeqRef.current !== seq) return;- if (!res.success) {- setAtState({ kind: 'error', message: res.error ?? 'Plugin resource search failed' });- return;- }- setAtState({ kind: 'ready', items: res.items, truncated: res.truncated });- })- .catch((error: unknown) => {- if (atScanSeqRef.current !== seq) return;- setAtState({- kind: 'error',- message: error instanceof Error ? error.message : String(error),- });- });- },- [workingDir, sessionId],+ [workingDir, paletteAgentKind, isRemoteSession, sessionId, deviceLinkDeviceId, t, atPluginItems],);const atQuery = trigger.kind === 'at' ? trigger.query : '';- const atTriggerFrom = trigger.kind === 'at' ? trigger.from : null;// When `@` panel opens, rescan so newly created files/agents show immediately.useEffect(() => {@@ -3414,41 +3385,16 @@ export function ChatInput({runAtScan();}, [trigger.kind, workingDir, runAtScan]);- useEffect(() => {- if (- !atPluginScope- || trigger.kind !== 'at'- || atTriggerFrom !== atPluginScope.triggerFrom- ) {- if (atPluginScope) {- atScanSeqRef.current += 1;- setAtPluginScope(null);- if (trigger.kind === 'at') runAtScan(atQuery);- }- return;- }- // Never leave stale results selectable while a new scoped query is waiting- // for its debounce or network response.- const seq = ++atScanSeqRef.current;- setAtState({ kind: 'ready', items: [], truncated: false, searching: true });- const timer = window.setTimeout(- () => runAtPluginScan(atPluginScope.provider, atQuery, seq),- atQuery ? 200 : 0,- );- return () => window.clearTimeout(timer);- }, [atPluginScope, trigger.kind, atTriggerFrom, atQuery, runAtPluginScan, runAtScan]);-// Derive query string for stable memo deps — avoids re-filtering on// every editor tick when only the caret moved but the query didn't change.const filteredAt = useMemo(() => {if (!atQuery && trigger.kind !== 'at') return [];if (atState.kind !== 'ready') return [];- if (atPluginScope) return atState.items.slice(0, AT_MENTION_SEARCH_RESULT_LIMIT);const items = workingDir && localAttachmentPickerEnabled? [AT_FILE_PICKER_RESOURCE, ...atState.items]: atState.items;return filterAtResources(items, atQuery);- }, [atState, atQuery, trigger.kind, atPluginScope, workingDir, localAttachmentPickerEnabled]);+ }, [atState, atQuery, trigger.kind, workingDir, localAttachmentPickerEnabled]);// Focused row index for each paletteconst [slashFocus, setSlashFocus] = useState(0);@@ -3461,17 +3407,12 @@ export function ChatInput({useEffect(() => {if (atFocus >= filteredAt.length) setAtFocus(0);}, [filteredAt.length, atFocus]);- useEffect(() => {- if (atPluginScope) setAtFocus(0);- }, [atPluginScope?.provider.pluginId, atQuery]);-useEffect(() => {if (atQueryScanTimerRef.current !== null) {window.clearTimeout(atQueryScanTimerRef.current);atQueryScanTimerRef.current = null;}if (trigger.kind !== 'at') return;- if (atPluginScope) return;const normalizedQuery = atQuery.trim();if (normalizedQuery === atLastScanQueryRef.current) return;atLastScanQueryRef.current = normalizedQuery;@@ -3489,7 +3430,7 @@ export function ChatInput({atQueryScanTimerRef.current = null;}};- }, [trigger.kind, workingDir, atQuery, runAtScan, atPluginScope]);+ }, [trigger.kind, workingDir, atQuery, runAtScan]);// ── Panel-close flags (Esc cancelation) ────────────────────────────// Once the user cancels a panel (Esc), we must NOT reopen it until the@@ -3565,9 +3506,6 @@ export function ChatInput({insertAtResource(filteredAt[atFocus]);return true;}- // A scoped Plugin search owns Enter/Tab even while loading or- // empty; keep accidental sends from bypassing resource selection.- if (atOpen && atPluginScope) return true;return false;case 'Escape':if (slashOpen && trigger.kind === 'slash') {@@ -3575,20 +3513,12 @@ export function ChatInput({return true;}if (atOpen && trigger.kind === 'at') {- if (atPluginScope) {- exitAtPluginScope(true);- return true;- }setSuppressedAtAt(trigger.from);return true;}return false;case 'ArrowLeft':case 'Backspace':- if (atOpen && atPluginScope && !atQuery) {- exitAtPluginScope(false);- return true;- }return false;default:return false;@@ -3657,31 +3587,26 @@ export function ChatInput({const $from = editor.state.doc.resolve(from);const parent = $from.parent;const parentStart = $from.start();- // Scoped Plugin queries may contain spaces. Their explicit end is the- // current caret, so ordinary composer text after the caret is preserved.- const isAtScoped = activeAtScopeFrom === from;- let runEnd = isAtScoped ? editor.state.selection.from : from + 1;+ let runEnd = from + 1;const offset = from - parentStart + 1;- if (!isAtScoped) {- let stopped = false;- parent.forEach((child, childOffset) => {- if (stopped || childOffset + child.nodeSize <= offset) return;- if (child.type.name === 'mentionChip' || !child.isText) {+ let stopped = false;+ parent.forEach((child, childOffset) => {+ if (stopped || childOffset + child.nodeSize <= offset) return;+ if (child.type.name === 'mentionChip' || !child.isText) {+ stopped = true;+ return;+ }+ const localStart = Math.max(0, offset - childOffset);+ const text = child.text ?? '';+ for (let i = localStart; i < text.length; i++) {+ if (/\s/.test(text[i])) {+ runEnd = parentStart + childOffset + i;stopped = true;return;}- const localStart = Math.max(0, offset - childOffset);- const text = child.text ?? '';- for (let i = localStart; i < text.length; i++) {- if (/\s/.test(text[i])) {- runEnd = parentStart + childOffset + i;- stopped = true;- return;- }- }- runEnd = parentStart + childOffset + text.length;- });- }+ }+ runEnd = parentStart + childOffset + text.length;+ });const to = runEnd;let selectedItem = item;let selectedByNativePicker = false;@@ -3719,21 +3644,22 @@ export function ChatInput({// The synthetic action must always resolve to a concrete file/directory// before it can reach mention serialization.if (selectedItem.type === 'file-picker') return;- if (selectedItem.type === 'plugin-provider') {+ if (selectedItem.type === 'plugin-command') {if (!selectedItem.pluginId) return;+ const ghost = installedGhostsRef.current.find(+ (candidate) => candidate.manifest.id === selectedItem.pluginId,+ );+ if (!ghost?.enabled || !ghost.manifest.command) return;editor.chain().focus().command(({ tr }) => {- // The provider lives only in React state. Keeping ordinary `@`- // text means drafts and sends can never leak an internal sentinel.- tr.replaceWith(from, to, editor.schema.text('@'));+ tr.delete(from, to);return true;}).run();- atScanSeqRef.current += 1;- setAtPluginScope({ provider: selectedItem, triggerFrom: from });- setAtState({ kind: 'loading' });+ placeGhostAtComposerStart(editor, ghost, installedGhostsRef.current);+ setSuppressedAtAt(from);return;}const directoryQuery = selectedByNativePicker@@ -3749,7 +3675,6 @@ export function ChatInput({}).run();setAtFocus(0);- setAtPluginScope(null);return;}const attrs: MentionChipAttrs = {@@ -3785,35 +3710,10 @@ export function ChatInput({return true;}).run();- setAtPluginScope(null);},- [editor, trigger, activeAtScopeFrom, workingDir, storageKey],+ [editor, trigger, workingDir, storageKey],);- const exitAtPluginScope = useCallback((closePanel: boolean) => {- if (!editor || trigger.kind !== 'at') return;- const { from } = trigger;- if (!closePanel) {- const runEnd = editor.state.selection.from;- editor- .chain()- .focus()- .command(({ tr }) => {- tr.replaceWith(from, runEnd, editor.schema.text('@'));- return true;- })- .run();- }- setAtPluginScope(null);- atScanSeqRef.current += 1;- if (closePanel) {- setAtState({ kind: 'loading' });- setSuppressedAtAt(from);- } else {- runAtScan();- }- }, [editor, trigger, runAtScan]);-// ── Send / Stop wiring ─────────────────────────────────────────────const dispatchSendInFlightRef = useRef(false);const dispatchSendRef = useRef<(deliveryMode?: MessageDeliveryMode) => void | Promise<void>>(@@ -3827,10 +3727,6 @@ export function ChatInput({// 语音发送等所有入口,确保 host 已登记切换意图后才允许 maker:send。if (sessionId && hasPendingAgentSendDispatch(sessionId)) return;if (dispatchSendInFlightRef.current) return;- if (atPluginScope) {- atScanSeqRef.current += 1;- setAtPluginScope(null);- }const sourceSessionId = sessionId;const finishAgentSendDispatch = sourceSessionId? tryBeginAgentSendDispatch(sourceSessionId)@@ -4080,7 +3976,6 @@ export function ChatInput({remoteModelListStatus,confirmDialog,navigate,- atPluginScope,],);useEffect(() => {@@ -6223,20 +6118,10 @@ export function ChatInput({onSelect={(item) => insertAtResource(item)}onClose={() => {if (trigger.kind !== 'at') return;- if (atPluginScope) {- exitAtPluginScope(true);- } else {- setSuppressedAtAt(trigger.from);- }+ setSuppressedAtAt(trigger.from);}}- onRetry={() => atPluginScope- ? runAtPluginScan(atPluginScope.provider, atQuery)- : runAtScan(atQuery)}- scopedProviderName={atPluginScope?.provider.name}+ onRetry={() => runAtScan(atQuery)}filePickerEnabled={!!workingDir && localAttachmentPickerEnabled}- onBack={atPluginScope- ? () => exitAtPluginScope(false)- : undefined}maxHeight={paletteMaxHeight}/>)}diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsxindex 6650728465..f8798d5742 100644--- a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx@@ -32,7 +32,6 @@ import {MoreVertical,PanelLeft,PanelRight,- Plug,Radio,Sparkles,Terminal,@@ -99,7 +98,6 @@ const PERMISSION_ICON: Record<GhostPermissionItem['kind'], LucideIcon> = {agent: Bot,node: Cpu,tool: Wrench,- 'at-resource': Plug,command: Terminal,panel: PanelRight,code: FileCode2,diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex b59bf1b42e..fe7fba4006 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -3397,8 +3397,6 @@"nodeResident": "The Node program can stay running in the background","nodeResidentDetail": "Runs while the plugin is enabled and stops when disabled, updated, uninstalled, or when Cindy exits.","tool": "Tool \"{{name}}\"",- "atResourceProvider": "Can search Plugin resources in @ using \"{{name}}\"",- "atResourceProviderDetail": "The tool runs only after you explicitly select this Plugin in @. Plugin authors must keep this search free of side effects.","command": "Chat command ${{command}}","panelLeft": "Panel \"{{title}}\" · docked left of the chat","panelTab": "Panel \"{{title}}\" · opens inside the Plugins page",@@ -5299,6 +5297,8 @@}},"atMention": {+ "add": "Add",+ "plugins": "Plugins","filesAndFolders": "Files and folders","browserTab": "Browser tab","desktopWindow": "App window",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 7c21f63c5b..e8d85717c8 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -3396,8 +3396,6 @@"nodeResident": "Node プログラムをバックグラウンドで常駐実行できます","nodeResidentDetail": "プラグインが有効な間は実行を続け、無効化、更新、アンインストール、または Cindy 終了時に停止します。","tool": "ツール「{{name}}」",- "atResourceProvider": "@ で「{{name}}」を使ってプラグインリソースを検索できます",- "atResourceProviderDetail": "@ でこのプラグインを明示的に選択した後にのみツールが実行されます。プラグイン作者は検索に副作用がないことを保証する必要があります。","command": "チャット指令 ${{command}}","panelLeft": "パネル「{{title}}」· チャットの左側にドッキング","panelTab": "パネル「{{title}}」· プラグインページ内で開く",@@ -5297,6 +5295,8 @@}},"atMention": {+ "add": "追加",+ "plugins": "プラグイン","filesAndFolders": "ファイルとフォルダ","browserTab": "ブラウザタブ","desktopWindow": "アプリウィンドウ",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 7d05fbabd4..b1d2196d91 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -3396,8 +3396,6 @@"nodeResident": "Node 프로그램을 백그라운드에서 계속 실행할 수 있음","nodeResidentDetail": "플러그인이 활성화된 동안 실행되며 비활성화, 업데이트, 제거 또는 Cindy 종료 시 중지됩니다.","tool": "도구 \"{{name}}\"",- "atResourceProvider": "@에서 \"{{name}}\"으로 플러그인 리소스를 검색할 수 있음",- "atResourceProviderDetail": "@에서 이 플러그인을 명시적으로 선택한 뒤에만 도구가 실행됩니다. 플러그인 작성자는 검색에 부작용이 없도록 해야 합니다.","command": "채팅 명령 ${{command}}","panelLeft": "패널 \"{{title}}\" · 채팅 왼쪽에 도킹","panelTab": "패널 \"{{title}}\" · 플러그인 페이지에서 열기",@@ -5297,6 +5295,8 @@}},"atMention": {+ "add": "추가",+ "plugins": "플러그인","filesAndFolders": "파일 및 폴더","browserTab": "브라우저 탭","desktopWindow": "앱 창",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 1134a90353..309dd0b3c6 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -3396,8 +3396,6 @@"nodeResident": "Node 程序可常驻后台","nodeResidentDetail": "插件启用期间会一直运行;停用、更新、卸载或退出 Cindy 时关闭。","tool": "工具「{{name}}」",- "atResourceProvider": "可在 @ 中用「{{name}}」搜索插件资源",- "atResourceProviderDetail": "只有你在 @ 中明确选中这个插件后才会调用该工具;插件作者必须保证搜索没有副作用。","command": "对话指令 ${{command}}","panelLeft": "面板「{{title}}」· 停靠主对话区左侧","panelTab": "面板「{{title}}」· 插件页内打开",@@ -5297,6 +5295,8 @@}},"atMention": {+ "add": "添加",+ "plugins": "插件","filesAndFolders": "文件和文件夹","browserTab": "浏览器标签","desktopWindow": "应用窗口",diff --git a/apps/desktop/src/renderer/lib/atResourceService.ts b/apps/desktop/src/renderer/lib/atResourceService.tsindex b12f83a3f5..026e954027 100644--- a/apps/desktop/src/renderer/lib/atResourceService.ts+++ b/apps/desktop/src/renderer/lib/atResourceService.ts@@ -27,7 +27,7 @@ export type AtResourceType =| 'browser-tab'| 'desktop-window'| 'session'- | 'plugin-provider'+ | 'plugin-command'| 'plugin-resource';export interface AtResourceItem {@@ -45,10 +45,12 @@ export interface AtResourceItem {relPath: string;/** Agent description from YAML frontmatter (agents only). */description?: string;- /** Plugin display name for provider/resource rows and Agent projection. */+ /** Plugin display name for plugin rows and Agent projection. */sourceLabel?: string;- /** Stable Plugin id. Present on provider/resource rows only. */+ /** Stable Plugin id. Present on plugin rows only. */pluginId?: string;+ /** Installed plugin icon as a validated data URL. Present on plugin rows when declared. */+ iconDataUrl?: string;/** @internal Pre-computed lowercase for filter performance. */_nameLower?: string;/** @internal Pre-computed lowercase for filter performance. */@@ -77,7 +79,7 @@ const EMPTY_QUERY_SECTIONS: ReadonlyArray<ReadonlySet<AtResourceType>> = [new Set(['file-picker']),new Set(['browser-tab']),new Set(['agent']),- new Set(['plugin-provider']),+ new Set(['plugin-command']),];export type PaletteAgentKind = 'claude-code' | 'codex' | 'pi';@@ -142,7 +144,6 @@ function normalizedBrowserPageTitle(value: string): string {type RawWorkspaceScan = Awaited<ReturnType<typeof window.electronAPI.maker.scanAtResources>>;type RawContextScan = Awaited<ReturnType<typeof window.electronAPI.maker.listAtContext>>;-type RawPluginProviders = Awaited<ReturnType<typeof window.electronAPI.ghosts.listAtResourceProviders>>;function normalizeWorkspaceResources(res: RawWorkspaceScan | null): AtResourceItem[] {const agents: AtResourceItem[] = [];@@ -320,29 +321,6 @@ async function searchRemoteHistoricalTasks(}}-function normalizePluginProviderResources(- result: RawPluginProviders | null,-): AtResourceItem[] {- const pluginProviders: AtResourceItem[] = [];- for (const provider of result?.items ?? []) {- const ghostId = oneLineText(provider.ghostId, 32);- const name = oneLineText(provider.name, 128);- if (!ghostId || !name) continue;- const description = oneLineText(provider.description, 256);- pluginProviders.push({- type: 'plugin-provider',- name,- relPath: ghostId,- pluginId: ghostId,- sourceLabel: name,- ...(description ? { description } : {}),- _nameLower: name.toLowerCase(),- _relPathLower: `${ghostId} ${name} ${description}`.toLowerCase(),- });- }- return pluginProviders;-}-/*** Load candidate @-resources from independent workspace/context providers.* Partial provider failures keep the remaining candidates usable; the caller@@ -428,17 +406,9 @@ export async function scanAtResources(),): Promise.resolve(null);- const pluginProvidersPromise = !deviceId- ? window.electronAPI.ghosts.listAtResourceProviders({- ...(context?.sessionId ? { sessionId: context.sessionId } : {}),- ...(workingDir ? { workingDir } : {}),- })- : Promise.resolve(null);-const partial = {contextual: [] as AtResourceItem[],historicalTasks: [] as AtResourceItem[],- pluginProviders: [] as AtResourceItem[],workspace: [] as AtResourceItem[],truncated: false,};@@ -450,7 +420,6 @@ export async function scanAtResources(items: [...partial.contextual,...partial.historicalTasks,- ...partial.pluginProviders,...partial.workspace,],truncated: partial.truncated,@@ -475,17 +444,10 @@ export async function scanAtResources(partial.historicalTasks = value;emitPartial();}, () => undefined);- void pluginProvidersPromise.then((value) => {- if (!value) return;- partial.pluginProviders = normalizePluginProviderResources(value);- emitPartial();- }, () => undefined);-- const [workspaceSettled, contextSettled, taskHistorySettled, pluginProvidersSettled] = await Promise.allSettled([+ const [workspaceSettled, contextSettled, taskHistorySettled] = await Promise.allSettled([workspacePromise,contextPromise,taskHistoryPromise,- pluginProvidersPromise,]);const res = workspaceSettled.status === 'fulfilled' ? workspaceSettled.value : null;const contextResult = contextSettled.status === 'fulfilled' ? contextSettled.value : null;@@ -494,7 +456,6 @@ export async function scanAtResources();const contextFailed = includeLocalContext && contextSettled.status === 'rejected';const taskHistoryFailed = includeTaskHistory && taskHistorySettled.status === 'rejected';- const pluginProvidersFailed = !deviceId && pluginProvidersSettled.status === 'rejected';if (workspaceFailed) {log.warn('Workspace @ resource scan failed; keeping other providers available.',@@ -513,17 +474,10 @@ export async function scanAtResources(taskHistorySettled.status === 'rejected' ? taskHistorySettled.reason : undefined,);}- if (pluginProvidersFailed) {- log.warn(- 'Plugin @ provider listing failed; keeping other providers available.',- pluginProvidersSettled.status === 'rejected' ? pluginProvidersSettled.reason : undefined,- );- }if ((!workingDir || workspaceFailed)&& (!includeLocalContext || contextFailed)&& (!includeTaskHistory || taskHistoryFailed)- && (deviceId !== undefined || pluginProvidersFailed)) {return {success: false,@@ -543,65 +497,13 @@ export async function scanAtResources(&& Array.isArray(taskHistorySettled.value)? taskHistorySettled.value: [];- const pluginProviders = normalizePluginProviderResources(- pluginProvidersSettled.status === 'fulfilled' ? pluginProvidersSettled.value : null,- );-return {success: true,- items: [...contextual, ...historicalTasks, ...pluginProviders, ...workspace],+ items: [...contextual, ...historicalTasks, ...workspace],truncated: !!res?.truncated,};}-/** Search exactly one provider after the user explicitly selected it. */-export async function scanPluginAtResources(- provider: AtResourceItem,- query: string,- workingDir?: string,- sessionId?: string,-): Promise<ScanResult> {- if (provider.type !== 'plugin-provider' || !provider.pluginId) {- return { success: false, error: 'Plugin resource provider unavailable', items: [], truncated: false };- }- const result = await window.electronAPI.ghosts.queryAtResources({- ghostId: provider.pluginId,- ...(sessionId ? { sessionId } : {}),- ...(workingDir ? { workingDir } : {}),- query: query.trim(),- limit: 20,- });- if (!result.success) {- return {- success: false,- error: result.error ?? 'Plugin resource search failed',- items: [],- truncated: false,- };- }- const sourceLabel = oneLineText(result.pluginName || provider.sourceLabel || provider.name, 128);- const items: AtResourceItem[] = [];- for (const row of result.items) {- const name = oneLineText(row.label, 128);- const relPath = typeof row.href === 'string' && row.href.length <= 1_500- ? oneLineText(row.href, 1_500)- : '';- if (!name || !relPath) continue;- const description = oneLineText(row.description, 256);- items.push({- type: 'plugin-resource',- name,- relPath,- pluginId: provider.pluginId,- sourceLabel,- ...(description ? { description } : {}),- _nameLower: name.toLowerCase(),- _relPathLower: `${name} ${description}`.toLowerCase(),- });- }- return { success: true, items, truncated: result.truncated };-}-/*** Lightweight fuzzy scorer. Returns a positive number (higher = better) if* the query characters appear in order inside `name` or `relPath`. Returnsdiff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 6486d9a1c0..9720a38ee4 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -1122,23 +1122,7 @@ interface ElectronAPI {*/setupStatus: (id: string) => Promise<import('../shared/ghost').GhostSetupStatus>;/** 只列入口元数据,不运行插件工具;远程/device-link 不暴露。 */- listAtResourceProviders: (params: { sessionId?: string; workingDir?: string }) => Promise<{- items: Array<{ ghostId: string; name: string; description?: string }>;- }>;/** 用户选定一个入口后,按固定只读摘要契约搜索该插件。 */- queryAtResources: (params: {- ghostId: string;- sessionId?: string;- workingDir?: string;- query?: string;- limit?: number;- }) => Promise<{- success: boolean;- error?: string;- pluginName?: string;- items: Array<{ id: string; label: string; description?: string; href: string }>;- truncated: boolean;- }>;/** 最近使用顺序变化(发送 /卸载),多窗口同步。 */onRecentUsageChanged: (callback: (payload: { ids: string[] }) => void,diff --git a/apps/desktop/src/shared/__tests__/ghost.test.ts b/apps/desktop/src/shared/__tests__/ghost.test.tsindex 6b69f0a8be..bf6ea05a7f 100644--- a/apps/desktop/src/shared/__tests__/ghost.test.ts+++ b/apps/desktop/src/shared/__tests__/ghost.test.ts@@ -1057,7 +1057,6 @@ describe('ghost · 芯片型清单(schemaVersion 2)', () => {atResourceProvider: { tool: 'search_issues' },});expect(valid.ok).toBe(true);- expect(valid.ok && valid.manifest.atResourceProvider).toEqual({ tool: 'search_issues' });const missing = validateGhostManifest({...base,@@ -1069,8 +1068,6 @@ describe('ghost · 芯片型清单(schemaVersion 2)', () => {});expect(missing.ok).toBe(true);expect(extraField.ok).toBe(true);- expect(missing.ok ? missing.manifest.atResourceProvider : null).toBeUndefined();- expect(extraField.ok ? extraField.manifest.atResourceProvider : null).toBeUndefined();});it('忽略旧 manifest 中无效的同名未知字段', () => {@@ -1092,7 +1089,6 @@ describe('ghost · 芯片型清单(schemaVersion 2)', () => {atResourceProvider: legacyValue,});expect(result.ok, JSON.stringify(legacyValue)).toBe(true);- expect(result.ok && result.manifest.atResourceProvider).toBeUndefined();}});@@ -1119,16 +1115,10 @@ describe('ghost · 芯片型清单(schemaVersion 2)', () => {});expect(before.ok && after.ok).toBe(true);if (!before.ok || !after.ok) return;- expect(ghostPermissionBaselineKey(after.manifest)).not.toBe(+ expect(ghostPermissionBaselineKey(after.manifest)).toBe(ghostPermissionBaselineKey(before.manifest),);- expect(diffGhostPermissionItems(before.manifest, after.manifest).added).toEqual([- expect.objectContaining({- key: 'at-resource:search_issues',- kind: 'at-resource',- labelKey: 'atResourceProvider',- }),- ]);+ expect(diffGhostPermissionItems(before.manifest, after.manifest).added).toEqual([]);});it('会进入 locale 对象索引的清单 key 统一拒绝对象保留键名', () => {diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.tsindex 1fdbf80082..9f51f8178d 100644--- a/apps/desktop/src/shared/ghost.ts+++ b/apps/desktop/src/shared/ghost.ts@@ -388,19 +388,6 @@ export interface GhostToolDecl {parameters?: Record<string, unknown>;}-/**- * 把一个已经声明、已经过权限确认的工具接入 Composer `@` 资源搜索。- *- * 这不是新卡槽,也不扩大底层工具权限:旧宿主会按顶层未知字段兼容忽略;新版宿主- * 仅在用户明确选中该插件的资源入口后,以固定 `{ query, limit }` 参数调用该工具。- * 调用入口会单独进入安装/更新权限清单;工具必须无副作用,返回值由宿主按固定- * 资源摘要协议裁剪。- */-export interface GhostAtResourceProviderDecl {- /** 必须逐字引用同一 manifest 的 tools[].name。 */- tool: string;-}-/** cindy 槽·图像类可申请的动作(主机代办菜单的"图像"类目)。 */export const GHOST_MODEL_IMAGE_ACTIONS = ['generate', 'edit'] as const;export type GhostModelImageAction = (typeof GHOST_MODEL_IMAGE_ACTIONS)[number];@@ -1229,8 +1216,7 @@ export interface GhostManifest {card?: GhostCardNeeds;/** 注册给 agent 的工具声明(与 slots 含 'tool' 成对)。 */tools?: GhostToolDecl[];- /** 可选的 `@` 业务资源搜索入口;复用已声明工具并单独披露调用入口。 */- atResourceProvider?: GhostAtResourceProviderDecl;+ /** `@` 面板入口由已安装插件的 command 提供;不支持资源搜索字段。 *//*** cindy 槽能力详单(与 slots 含 'cindy' 成对;缺省 = 零能力,任何代办* 都会被拒并提示作者补声明)。清单里的旧字段名 model 在校验层作别名@@ -1442,7 +1428,7 @@ export interface GhostPermissionItem {/** 稳定键:更新 diff 按它对齐(内容变化视为移除+新增,如面板换边)。 */key: string;/** 图标分组(renderer 按 kind 选图标)。 */- kind: 'cindy' | 'agent' | 'node' | 'tool' | 'at-resource' | 'command' | 'panel' | 'code' | 'subscribe' | 'card' | 'network' | 'notify' | 'confirm' | 'fs' | 'session-context' | 'pick' | 'preview' | 'skill' | 'workspace';+ kind: 'cindy' | 'agent' | 'node' | 'tool' | 'command' | 'panel' | 'code' | 'subscribe' | 'card' | 'network' | 'notify' | 'confirm' | 'fs' | 'session-context' | 'pick' | 'preview' | 'skill' | 'workspace';/** i18n key 后缀,消费方拼 `settings.ghosts.perm.<labelKey>`。 */labelKey: string;/** i18n 插值参数(工具名、指令名、面板标题等)。 */@@ -1722,15 +1708,6 @@ export function ghostPermissionItems(manifest: GhostManifest): GhostPermissionItdetail: tool.description,});}- if (manifest.atResourceProvider) {- items.push({- key: `at-resource:${manifest.atResourceProvider.tool}`,- kind: 'at-resource',- labelKey: 'atResourceProvider',- labelArgs: { name: manifest.atResourceProvider.tool },- detailKey: 'atResourceProviderDetail',- });- }if (manifest.command) {items.push({key: `command:${manifest.command}`,@@ -2894,25 +2871,8 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {return { ok: false, reason: 'slots 声明了 "tool" 但缺少 tools(注册什么工具要写清楚)' };}- /**- * `@` 资源入口复用 `tool` 槽,不另造硬白名单 slot:旧版宿主会接受这类包,- * 并像其它未知顶层字段一样忽略 atResourceProvider。这个字段在本版之前也可能被- * 存量包当作自定义元数据使用,因此这里仅收窄出待审声明;安装运行时还必须命中- * Main 在 install/update 后写下的 host receipt。其它历史形态继续忽略,避免客户端- * 升级后让已安装插件消失或凭字段形状自动扩权。- */- let atResourceProvider: GhostAtResourceProviderDecl | undefined;- if (isPlainObject(raw.atResourceProvider)) {- const providerRaw = raw.atResourceProvider as Record<string, unknown>;- if (- Object.keys(providerRaw).length === 1- && typeof providerRaw.tool === 'string'- && tools?.some((tool) => tool.name === providerRaw.tool)- ) {- atResourceProvider = { tool: providerRaw.tool };- }- }-+ // 历史版本可能在 manifest 中带有已移除的资源搜索字段;它作为未知顶层字段忽略,+ // 保持存量插件可见且不因字段形状自动获得新的运行能力。// cindy 槽能力详单:与 slots 含 'cindy' 成对(有详单必有槽;有槽无详单// 允许装入但运行时零能力——老包不消失,只是代办被拒并提示作者更新)。// 字段旧名 model 作别名收入(两个都写以 cindy 为准)。@@ -4299,7 +4259,6 @@ export function validateGhostManifest(raw: unknown): ManifestValidation {...(raw.settingsHeight !== undefined ? { settingsHeight: raw.settingsHeight as number } : {}),slots,...(tools !== undefined ? { tools } : {}),- ...(atResourceProvider !== undefined ? { atResourceProvider } : {}),...(card !== undefined ? { card } : {}),...(cindy !== undefined ? { cindy } : {}),...(agent !== undefined ? { agent } : {}),diff --git a/package.json b/package.jsonindex c94d33b7d6..d11b862bbf 100644--- a/package.json+++ b/package.json@@ -90,7 +90,7 @@"install:ripgrep": "node scripts/ensure-agent-binaries.mjs --kinds=ripgrep","install:pi": "node scripts/ensure-agent-binaries.mjs --kinds=pi","install:agent-binaries": "node scripts/ensure-agent-binaries.mjs",- "postinstall": "node scripts/ensure-agent-binaries.mjs --best-effort && node scripts/fix-node-pty-perms.mjs",+ "postinstall": "node scripts/ensure-agent-binaries.mjs --best-effort && node scripts/fix-node-pty-perms.mjs && pnpm --filter @cindy/model-access-protocol build","dev:desktop": "node scripts/ensure-deps.mjs && node scripts/ensure-dev-runtime-assets.mjs && pnpm --filter desktop dev","dev:desktop:remote": "node scripts/ensure-deps.mjs && node scripts/ensure-dev-runtime-assets.mjs && pnpm --filter desktop dev:remote","restart:desktop:remote": "node scripts/desktop-restart-runner.mjs --wait-ready",