Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
/**
* Plugin list/detail view models derived only from the installed Ghost contract.
*
* Inputs: shared Ghost manifests and install records.
* Outputs: renderer-safe list/detail facts, including the optional Host task settings card.
* [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md
*/
import {
ghostContentKeys,
ghostFallbackDisplayAuthor,
ghostPermissionItems,
type GhostInstallApproval,
type GhostPermissionItem,
type GhostTrustInfo,
type GhostToolDecl,
type InstalledGhost,
} from '../../../../shared/ghost';
import { installedGhostStoragePart } from '../../../../shared/pluginIdentity';
import type { PluginMarketItem } from '../../../../shared/pluginMarket';
import { marketItemMatchesInstalledGhost } from './pluginMarketPresentation';
export interface GhostPluginListItem {
/** Instance key (storage part). Use this for enable/uninstall/panel IPC. */
id: string;
/** Logical plugin id from the manifest. */
ghostId: string;
name: string;
description: string;
publisherKind?: PluginMarketItem['publisherKind'];
version: string;
enabled: boolean;
canUse: boolean;
/**
* Host 是否持有完整、可验证的安装记录。非 `approved` 的安装不可运行,列表与
* 详情都必须如实说明并给出恢复入口,而不是让它看起来只是“被关掉了”。
*/
approvalState: GhostInstallApproval['state'];
/** 随包内置插件(main 按种子清单投影)。安装记录异常时文案与恢复入口都不同。 */
builtin: boolean;
/** 声明了插件页内独占面板(panel.position:'tab'),主动作为「使用」(打开面板)。 */
tabPanel: boolean;
/** 声明了应用级主视图;只用于侧边栏与详情配置,不参与插件主动作。 */
hasMainView: boolean;
/** 本地化后的主视图标题;未声明时为 null。 */
mainViewTitle: string | null;
/** 声明了由 Host 承载、但可从插件 UI 主动进入的能力。 */
retirement?: InstalledGhost['retirement'];
oauthAuthorizationExpired?: boolean;
trust?: GhostTrustInfo;
iconDataUrl?: string;
}
/**
* 卡片主动作(只驱动右下角胶囊;整卡点击一律进详情):
* - `panel`:有页签面板 → 「使用」直接打开面板;
* - `command`:只有 $指令 → 「对话」把指令插进输入框起话题;
* - `capability`:Host 承载的能力 → 「对话」进入该能力的工作流;
* - `manage`:纯工具型(Agent 对话中自动调用)→ 无主按钮。
* 停靠形态(left/right)的面板由布局树承载,不算 panel 主动作。
*/
export type GhostPrimaryAction = 'panel' | 'command' | 'manage';
export function ghostPrimaryAction(
item: Pick<GhostPluginListItem, 'tabPanel' | 'canUse'>,
): GhostPrimaryAction {
if (item.tabPanel) return 'panel';
if (item.canUse) return 'command';
return 'manage';
}
export interface GhostPluginDetail extends GhostPluginListItem {
releaseNotes?: string;
trust: GhostTrustInfo;
author: string | null;
contents: readonly string[];
permissions: GhostPermissionItem[];
tools: readonly GhostToolDecl[];
hasSettingsUi: boolean;
/**
* 宿主「模型与任务」卡:插件的唯一模型字段(快问快答与新建任务共用)。声明了
* 快问快答(cindy.text 含 oneshot)或任何新建任务能力即展示;图像/视频/向量
* 没有逐插件选模,始终跟随系统默认。showTaskPreferences:false 仅隐藏该卡。
*/
hasTaskPreferences: boolean;
/** 能新建任务(agent.tasks / 旧 agent.errand / workspace):卡片额外展示权限与工作目录。 */
hasPluginTasks: boolean;
panelMinWidth: number | null;
installDir: string | null;
}
/**
* 展示投影只覆盖用户能看到的四个字段;运行时仍完全来自本地安装包。
*
* `iconDataUrl` 是有意要求存在的字段:服务端市场项的 `icon: null` 仍覆盖本地
* 包图标。Git 市场是窄例外:精确匹配到已安装版本时,可复用安装包里已验证的图标。
*/
export interface GhostPluginMarketPresentation {
name: string;
description: string;
author: string | null;
publisherKind?: PluginMarketItem['publisherKind'];
iconDataUrl: string | undefined;
}
/**
* Returns a market presentation only when the installed package is the exact
* market-owned version. A verified older installation keeps its local content
* and uses only the saved public attribution and privacy projection from Main.
*/
export function marketPresentationForInstalledGhost(
ghost: Pick<InstalledGhost, 'manifest' | 'iconDataUrl'>,
marketItem:
| (Pick<
PluginMarketItem,
| 'ghostId'
| 'installState'
| 'version'
| 'name'
| 'description'
| 'author'
| 'installedAuthor'
| 'icon'
| 'sourceType'
> &
Pick<PluginMarketItem, 'namespace'> &
Partial<Pick<PluginMarketItem, 'scope' | 'publisherKind'>>)
| null
| undefined,
): GhostPluginMarketPresentation | null {
if (
!marketItem ||
!marketItemMatchesInstalledGhost(marketItem, ghost)
) return null;
const publisherKind = marketItem.sourceType === 'server' && marketItem.scope === 'public'
? marketItem.publisherKind : undefined;
if (marketItem.sourceType === 'server' && marketItem.installState === 'update-available'
&& marketItem.installedAuthor !== undefined) {
return { name: ghost.manifest.name, description: ghost.manifest.description ?? '',
iconDataUrl: ghost.iconDataUrl, author: marketItem.installedAuthor, publisherKind };
}
if (
marketItem.installState !== 'installed' ||
marketItem.version !== ghost.manifest.version
) {
return null;
}
return {
name: marketItem.name,
description: marketItem.description ?? '',
author: marketItem.author,
publisherKind,
iconDataUrl:
marketItem.sourceType === 'git-market' && !marketItem.icon
? ghost.iconDataUrl
: marketItem.icon?.url,
};
}
export type GhostFallbackIconKind =
'diagram' | 'media' | 'search' | 'communication' | 'code' | 'calendar' | 'generic';
/**
* Chooses a restrained local symbol when a Plugin package has no icon asset.
* This is presentation-only: a package-provided icon always wins.
*/
export function ghostFallbackIconKind(name: string, id: string): GhostFallbackIconKind {
const identity = `${id} ${name}`.toLocaleLowerCase();
if (/mermaid|diagram|flow|chart|draw|绘图|流程|图表/u.test(identity)) return 'diagram';
if (/mivo|art|image|video|media|photo|图片|图像|视频/u.test(identity)) return 'media';
if (/search|browser|web|网页|搜索/u.test(identity)) return 'search';
if (/feishu|lark|slack|chat|message|mail|飞书|消息/u.test(identity)) return 'communication';
if (/github|gitlab|git|code|dev|代码/u.test(identity)) return 'code';
if (/calendar|schedule|日历|日程/u.test(identity)) return 'calendar';
return 'generic';
}
/**
* Applies the Plugin list's search semantics in one place so the result list
* and every count use the same matching set.
*/
export function filterGhostPluginItems<T extends GhostPluginListItem>(
items: readonly T[],
query: string,
): T[] {
const normalizedQuery = query.trim().toLocaleLowerCase();
return items.filter((item) =>
`${item.name} ${item.description} ${item.ghostId} ${item.id}`.toLocaleLowerCase().includes(normalizedQuery),
);
}
/**
* Orders installed shortcuts by host-recorded recency while keeping never-used items stable.
* Unknown/stale ids are ignored, so uninstall or migration residue cannot hide an item.
*/
export function sortGhostPluginItemsByRecentUse<T extends Pick<GhostPluginListItem, 'id' | 'retirement'>>(
items: readonly T[],
recentIds: readonly string[],
): T[] {
const recentIndex = new Map(recentIds.map((id, index) => [id, index]));
return items
.map((item, stableIndex) => ({ item, stableIndex }))
.sort((a, b) => {
const aRecent = recentIndex.get(a.item.id);
const bRecent = recentIndex.get(b.item.id);
if (aRecent !== undefined || bRecent !== undefined) {
if (aRecent === undefined) return 1;
if (bRecent === undefined) return -1;
if (aRecent !== bRecent) return aRecent - bRecent;
}
return a.stableIndex - b.stableIndex;
})
.map(({ item }) => item);
}
/**
* Ranks the installed shortcut row for display. Three lexicographic tiers:
* 1. Plugins with an unread notification (notify.badge) first, newest badge (larger `at`) on top.
* A pushed notification has no other entry point, so surfacing it is the whole point.
* 2. Then recently used (host-recorded MRU), newest first.
* 3. Then base install order, stably.
* `marketUpdate` is deliberately NOT a key: the updates banner already surfaces updatable plugins,
* so letting them jump the row would only bury the unread signal.
* Pure and reactive — recompute freely from current signals; there is no frozen snapshot to go stale.
*/
export function sortInstalledForDisplay<T extends Pick<GhostPluginListItem, 'id' | 'retirement'>>(
items: readonly T[],
{
recentIds,
unreadAtById,
}: { recentIds: readonly string[]; unreadAtById: ReadonlyMap<string, number> },
): T[] {
const recentIndex = new Map(recentIds.map((id, index) => [id, index]));
return items
.map((item, stableIndex) => ({ item, stableIndex }))
.sort((a, b) => {
// Tier 1 — unread notifications, newest badge first.
const aAt = a.item.retirement?.unread ? Number.MAX_SAFE_INTEGER : unreadAtById.get(a.item.id);
const bAt = b.item.retirement?.unread ? Number.MAX_SAFE_INTEGER : unreadAtById.get(b.item.id);
if ((aAt !== undefined) !== (bAt !== undefined)) return aAt !== undefined ? -1 : 1;
if (aAt !== undefined && bAt !== undefined && aAt !== bAt) return bAt - aAt;
// Tier 2 — recently used, newest first.
const aRecent = recentIndex.get(a.item.id);
const bRecent = recentIndex.get(b.item.id);
if (aRecent !== undefined || bRecent !== undefined) {
if (aRecent === undefined) return 1;
if (bRecent === undefined) return -1;
if (aRecent !== bRecent) return aRecent - bRecent;
}
// Tier 3 — base install order, stable.
return a.stableIndex - b.stableIndex;
})
.map(({ item }) => item);
}
/**
* Size of the always-visible installed window: at least `cap`, expanded to also cover every
* plugin carrying an unread notification. Because `sortInstalledForDisplay` ranks unread items
* first, taking this many from the front guarantees no unread plugin is ever folded away — even
* when the user has many plugins. Updatable-but-read plugins can still fold (the banner surfaces
* updates).
*/
export function installedVisibleCount<T extends Pick<GhostPluginListItem, 'id' | 'retirement'>>(
items: readonly T[],
unreadAtById: ReadonlyMap<string, number>,
cap: number,
): number {
const unreadCount = items.reduce((count, item) => count + ((item.retirement?.unread || unreadAtById.has(item.id)) ? 1 : 0), 0);
return Math.max(cap, unreadCount);
}
/**
* 将安装清单转换成列表卡片需要的最小字段。
*
* 安装量、使用量等没有事实来源的旧原型字段不加入;发布身份仅消费
* Host 核实后的 public 市场投影,不能从包内声明或昵称推断。
*/
export function toGhostPluginListItem(
ghost: InstalledGhost,
presentation?: GhostPluginMarketPresentation | null,
): GhostPluginListItem {
const { manifest } = ghost;
const display = presentation ?? {
name: manifest.name,
description: manifest.description ?? '',
iconDataUrl: ghost.iconDataUrl,
};
return {
id: installedGhostStoragePart(ghost),
ghostId: manifest.id,
name: display.name,
description: display.description,
publisherKind: presentation?.publisherKind,
version: manifest.version,
enabled: ghost.enabled,
canUse: Boolean(manifest.command),
approvalState: ghost.approval.state,
builtin: ghost.builtin === true,
tabPanel: manifest.panel?.position === 'tab',
hasMainView: manifest.mainView !== undefined,
mainViewTitle: manifest.mainView ? (manifest.mainView.title ?? manifest.name) : null,
retirement: ghost.retirement,
oauthAuthorizationExpired: ghost.oauthAuthorizationExpired !== undefined,
trust: ghost.trust ?? {
level: 'unverified',
publisherSigned: false,
publisherVerified: false,
reviewed: false,
},
...(display.iconDataUrl !== undefined ? { iconDataUrl: display.iconDataUrl } : {}),
};
}
/**
* 详情页复用列表 adapter 的基础字段,再补充 manifest 明确声明的权限与工具。
* 权限与详情卡共用 shared/ghost.ts 的纯推导函数,不在 renderer 复制规则。
*/
export function toGhostPluginDetail(
ghost: InstalledGhost,
presentation?: GhostPluginMarketPresentation | null,
): GhostPluginDetail {
const listItem = toGhostPluginListItem(ghost, presentation);
const { manifest } = ghost;
const hasPluginTasks =
!!manifest.workspace || manifest.agent?.errand === true || manifest.agent?.tasks === true;
return {
...listItem,
trust: listItem.trust!,
releaseNotes: manifest.releaseNotes,
author: presentation ? presentation.author : ghostFallbackDisplayAuthor(ghost),
contents: ghostContentKeys(manifest),
permissions: ghostPermissionItems(manifest),
tools: manifest.tools ?? [],
hasSettingsUi: Boolean(manifest.settingsHtml),
hasTaskPreferences:
manifest.showTaskPreferences !== false &&
(hasPluginTasks || (manifest.cindy?.text ?? []).includes('oneshot')),
hasPluginTasks,
panelMinWidth: manifest.panel ? (manifest.panel.minWidth ?? 280) : null,
installDir: ghost.dir,
};
}
/**
* 插件可见 WebView 宿主的数据归属键(panel / main-view 共用)。
*
* 面板承载的是 webview,里面可能存着账号 A 的登录态、表单、已加载数据。
* 两个账号装了**同 id、同版本、同入口**的插件时,只按 ghostId 做宿主 key
* 会让 React 复用同一实例——切到账号 B 后 A 的 DOM 与内存态原样留着。
* 所以 key 必须含 owner 身份:换身份即卸载重建。
*/
export function ghostWebviewOwnerKey(
mode: 'signed-out' | 'local' | 'cloud',
dataOwnerId: string | null,
): string {
return `${mode}:${dataOwnerId ?? ''}`;
}
/**
* owner 变化时在开的面板应保留还是关闭。
* 返回下一个 openPanelId:身份变了一律关(返回 null),没变则原样保留。
*/
export function nextOpenPanelIdForOwner(
previousOwnerKey: string,
nextOwnerKey: string,
currentOpenPanelId: string | null,
): string | null {
return previousOwnerKey === nextOwnerKey ? currentOpenPanelId : null;
}