本文档基于 docs/product/llm-command-palette-plugin-prd.md,为 LLM 桌面输入插件设计运行时架构、模块边界、配置模型、流式调用链路和实现拆分。
Moli.Desktop 已具备 WebView2 小组件窗口、插件 manifest、布局持久化、本地 HTTP API、WebSocket 事件和 window.moliDesktop 桥接能力。LLM 插件应复用这些基础设施,并新增一层宿主侧 LLM 代理能力,用于按 modelId 路由到不同供应商和不同 endpoint。
核心架构决策:
modelId、messages 和请求参数,不直接传 provider、endpoint 或 API key。provider、endpoint、authRef 和 apiModel。modelId 选择 provider adapter,并把不同供应商的流式响应统一转换成插件可消费的事件。widget 插件运行。flowchart TB
Plugin["sample.llm-command-palette WebView"]
Bridge["PluginBridgeScript / WebViewHost"]
Runtime["DesktopRuntimeCoordinator"]
LlmService["LlmGatewayService"]
Registry["LlmModelRegistry"]
SecretStore["CredentialStore"]
AdapterFactory["LlmProviderAdapterFactory"]
OpenAI["OpenAICompatibleAdapter"]
DeepSeek["DeepSeekAdapter"]
Local["LocalOpenAICompatibleAdapter"]
Config["ConfigurationService"]
Events["RuntimeEventBus"]
Diagnostics["DiagnosticsService"]
Plugin --> Bridge
Bridge --> Runtime
Runtime --> LlmService
LlmService --> Registry
Registry --> Config
LlmService --> SecretStore
LlmService --> AdapterFactory
AdapterFactory --> OpenAI
AdapterFactory --> DeepSeek
AdapterFactory --> Local
LlmService --> Events
LlmService --> Diagnostics
Bridge --> Plugin
| 模块 | 职责 | 不负责 |
|---|---|---|
sample.llm-command-palette |
输入、模型下拉、Enter 提交、流式文本渲染、错误展示 | 供应商 API 适配、密钥读取 |
PluginBridgeScript |
向 WebView 注入 window.moliDesktop.llm API,处理 Promise 与事件派发 |
直接发起外部 HTTP 请求 |
DesktopRuntimeCoordinator |
统一接收插件桥接命令,校验插件实例和权限,调用 LLM 服务 | 解析供应商流式协议 |
LlmGatewayService |
LLM 请求入口、模型路由、取消、超时、事件归一化 | 持久化布局或窗口状态 |
LlmModelRegistry |
加载和校验模型配置,按 modelId 查找模型 |
保存 API key 明文 |
CredentialStore |
按 authRef 提供密钥,隐藏真实 key |
保存普通插件配置 |
LlmProviderAdapter |
按 provider 适配请求和流式响应 | 决定插件 UI 行为 |
RuntimeEventBus |
广播 llm.delta、llm.completed、llm.error 等事件 |
存储历史对话 |
DiagnosticsService |
记录鉴权失败、endpoint 不可达、流解析失败、超时 | 记录完整 prompt 或 key |
window.moliDesktop.llm。LlmGatewayService 通过工厂创建或取得。ConfigurationService,不允许插件或 adapter 直接写 JSON。sequenceDiagram
participant Plugin
participant Bridge
participant Runtime
participant Llm as LlmGatewayService
participant Registry as LlmModelRegistry
Plugin->>Bridge: window.moliDesktop.llm.getModels()
Bridge->>Runtime: GetLlmModels(pluginId, instanceId)
Runtime->>Llm: GetAvailableModels(pluginId)
Llm->>Registry: Load enabled model summaries
Registry-->>Llm: model id, label, provider, supportsStreaming
Llm-->>Runtime: safe model summaries
Runtime-->>Bridge: summaries without endpoint/authRef
Bridge-->>Plugin: Promise resolve
插件模型下拉只能拿到安全摘要:
[
{
"id": "gpt-5.4",
"label": "GPT-5.4",
"provider": "openai-compatible",
"supportsStreaming": true,
"enabled": true
}
]
默认不返回 endpoint、authRef、API key 或其他敏感配置。管理窗口可以在受控 UI 中展示和编辑 endpoint,但插件前端不需要知道。
sequenceDiagram
participant Plugin
participant Bridge
participant Runtime
participant Llm as LlmGatewayService
participant Registry as LlmModelRegistry
participant Secret as CredentialStore
participant Adapter as ProviderAdapter
participant Upstream as LLM Provider
Plugin->>Bridge: streamChat(modelId, messages, options)
Bridge->>Runtime: StreamLlmChat(request)
Runtime->>Runtime: Validate plugin permission llm.stream
Runtime->>Llm: StreamChatAsync(request)
Llm->>Registry: Get model by modelId
Registry-->>Llm: provider, endpoint, authRef, apiModel
Llm->>Secret: Resolve authRef
Secret-->>Llm: credential or null
Llm->>Adapter: StreamAsync(normalized request)
Adapter->>Upstream: HTTP streaming request
Upstream-->>Adapter: provider stream chunks
Adapter-->>Llm: normalized deltas
Llm-->>Runtime: LlmStreamEvent
Runtime-->>Bridge: llm.delta / completed / error
Bridge-->>Plugin: DOM event or callback
MVP 可先实现“请求中忽略重复 Enter”。架构上预留取消能力:
streamChat 生成 requestId。LlmGatewayService 保存 requestId -> CancellationTokenSource。window.moliDesktop.llm.cancel(requestId)。建议新增独立配置文件:
%AppData%\DesktopEnhancer\config\llm-models.json
独立文件的好处:
layout.json 或普通插件 manifest。示例:
{
"schemaVersion": 1,
"defaultModel": "gpt-5.4",
"models": [
{
"id": "gpt-5.4",
"label": "GPT-5.4",
"provider": "openai-compatible",
"endpoint": "https://api.openai.example/v1/chat/completions",
"authRef": "llm.openai.primary",
"apiModel": "gpt-5.4",
"supportsStreaming": true,
"enabled": true,
"requestDefaults": {
"temperature": 0.7,
"maxTokens": 2048,
"timeoutMs": 60000
}
},
{
"id": "deepseek-chat",
"label": "DeepSeek",
"provider": "deepseek",
"endpoint": "https://api.deepseek.com/chat/completions",
"authRef": "llm.deepseek.primary",
"apiModel": "deepseek-chat",
"supportsStreaming": true,
"enabled": true,
"requestDefaults": {
"temperature": 0.7,
"maxTokens": 2048,
"timeoutMs": 60000
}
},
{
"id": "local-qwen",
"label": "Local Qwen",
"provider": "openai-compatible",
"endpoint": "http://127.0.0.1:11434/v1/chat/completions",
"authRef": null,
"apiModel": "qwen2.5:14b",
"supportsStreaming": true,
"enabled": false,
"requestDefaults": {
"temperature": 0.6,
"maxTokens": 2048,
"timeoutMs": 120000
}
}
]
}
| 字段 | 规则 |
|---|---|
schemaVersion |
必填,当前为 1 |
defaultModel |
必须为空或指向一个 enabled 模型 |
models[].id |
全局唯一,推荐 provider-name 或用户可读 id |
models[].label |
1 到 40 字符,供下拉展示 |
models[].provider |
必须存在对应 adapter |
models[].endpoint |
必须是 http 或 https 绝对 URL |
models[].authRef |
可为空;不为空时不得包含明文 key |
models[].apiModel |
必填,发送给上游供应商的真实模型名 |
models[].timeoutMs |
建议 5000..300000 |
MVP 建议优先顺序:
authRef 存取密钥。MOLI_LLM_OPENAI_PRIMARY_KEY。authRef 不直接等于环境变量名,可以通过宿主映射:
{
"authRef": "llm.openai.primary"
}
宿主解析顺序示例:
Windows Credential Manager: Moli.Desktop/llm.openai.primary
Environment variable: MOLI_LLM_OPENAI_PRIMARY
public interface ILlmGatewayService
{
Task<IReadOnlyList<LlmModelSummary>> GetModelsAsync(CancellationToken cancellationToken);
IAsyncEnumerable<LlmStreamEvent> StreamChatAsync(
LlmChatRequest request,
CancellationToken cancellationToken);
Task CancelAsync(string requestId, CancellationToken cancellationToken);
}
public interface ILlmModelRegistry
{
Task<LlmSettingsDocument> LoadAsync(CancellationToken cancellationToken);
Task<LlmModelConfig?> GetEnabledModelAsync(string modelId, CancellationToken cancellationToken);
}
public interface ILlmProviderAdapter
{
string Provider { get; }
IAsyncEnumerable<LlmProviderChunk> StreamAsync(
LlmProviderRequest request,
CancellationToken cancellationToken);
}
public interface ICredentialStore
{
Task<string?> ResolveSecretAsync(string authRef, CancellationToken cancellationToken);
}
public sealed record LlmChatRequest
{
public required string RequestId { get; init; }
public required string PluginId { get; init; }
public required string InstanceId { get; init; }
public required string ModelId { get; init; }
public required IReadOnlyList<LlmMessage> Messages { get; init; }
public LlmRequestOptions Options { get; init; } = new();
}
public sealed record LlmMessage
{
public required string Role { get; init; }
public required string Content { get; init; }
}
public sealed record LlmRequestOptions
{
public double? Temperature { get; init; }
public int? MaxTokens { get; init; }
public int? TimeoutMs { get; init; }
}
public abstract record LlmStreamEvent
{
public required string RequestId { get; init; }
}
public sealed record LlmDeltaEvent : LlmStreamEvent
{
public required string Delta { get; init; }
}
public sealed record LlmCompletedEvent : LlmStreamEvent
{
public LlmUsage? Usage { get; init; }
}
public sealed record LlmErrorEvent : LlmStreamEvent
{
public required string Code { get; init; }
public required string Message { get; init; }
}
type LlmModelSummary = {
id: string;
label: string;
provider: string;
supportsStreaming: boolean;
enabled: boolean;
};
type LlmStreamRequest = {
modelId: string;
messages: Array<{ role: "system" | "user" | "assistant"; content: string }>;
options?: {
temperature?: number;
maxTokens?: number;
timeoutMs?: number;
};
};
window.moliDesktop.llm = {
getModels(): Promise<LlmModelSummary[]>;
streamChat(request: LlmStreamRequest): Promise<{ requestId: string }>;
cancel(requestId: string): Promise<void>;
onDelta(handler: (event: { requestId: string; delta: string }) => void): () => void;
onCompleted(handler: (event: { requestId: string; usage?: object }) => void): () => void;
onError(handler: (event: { requestId: string; code: string; message: string }) => void): () => void;
};
不同供应商的适配器必须统一输出:
delta: 增量文本。completed: 正常结束和可选 usage。error: 供应商错误归一化。OpenAI-compatible adapter 可作为第一优先级,它能覆盖 OpenAI、DeepSeek 的兼容模式、本地 Ollama/LM Studio 等多数 MVP 场景。DeepSeek 如使用非兼容字段,再单独派生 adapter。
LLM 插件仍是普通 widget 实例,布局由 LayoutManager 和 WidgetWindow 控制。
默认安装规则建议由 DefaultContentInstaller 特判 sample.llm-command-palette:
width = min(760, primaryWorkArea.Width * 0.72)height = 72x = primaryWorkArea.X + (primaryWorkArea.Width - width) / 2y = primaryWorkArea.Y + 32locked = trueclickThrough = falsedisplayLayer = desktopopacity = 0.96输出展开高度存在两层约束:
max-height: 50vh。requestResize,宿主布局层限制组件总高度不超过当前显示器高度 50% + inputBarHeight + margin,避免窗口无限扩张。| 错误码 | 场景 | UI 行为 | 诊断 |
|---|---|---|---|
LlmModelNotFound |
modelId 不存在或 disabled |
输出区显示模型不可用 | Warning |
LlmProviderUnsupported |
provider 无 adapter | 输出区显示供应商不支持 | Error |
LlmCredentialMissing |
authRef 无法解析 |
输出区提示检查密钥 | Error,不记录 key |
LlmEndpointUnavailable |
网络失败、DNS、连接拒绝 | 输出区提示 endpoint 不可达 | Error,记录 endpoint host |
LlmUnauthorized |
401/403 | 输出区提示鉴权失败 | Error,不记录 key |
LlmRateLimited |
429 | 输出区提示稍后重试 | Warning |
LlmTimeout |
超时 | 输出区提示请求超时 | Warning |
LlmStreamParseFailed |
供应商流格式异常 | 保留已输出内容并提示解析失败 | Error |
日志规则:
requestId、modelId、provider、endpoint host、HTTP status。llm.stream 必须作为插件权限声明,未声明时桥接层拒绝调用。setConfig 不允许写入宿主级 LLM 模型注册表。127.0.0.1,并复用同一 ILlmGatewayService。file://、相对路径和非 HTTP 协议。| 方案 | 结论 | 原因 |
|---|---|---|
| 插件前端直接调用各供应商 API | 不采用 | 密钥暴露、跨供应商差异扩散到插件 UI、日志和错误边界难控 |
| 全局单 provider + 单 endpoint | 不采用 | 无法自然支持不同供应商和每模型独立 URL |
宿主统一代理,按 modelId 路由 |
采用 | 满足多供应商,密钥留在宿主,插件 UI 简洁 |
| 只实现 OpenAI-compatible adapter | MVP 可作为第一阶段 | 快速覆盖多数供应商,但保留 provider adapter 扩展点 |
| 把模型配置放进插件 manifest | 仅作为 fallback | manifest 属于插件包,不适合保存用户真实 endpoint 和密钥引用 |
把模型配置放进 appsettings.json |
可行但不推荐 | LLM 配置会增长,独立文件更利于管理和迁移 |
输出:
LlmSettingsDocumentLlmModelConfigLlmRequestDefaultsllm-models.json 默认生成和校验验收:
defaultModel 指向 disabled 或不存在模型时降级为空。输出:
ICredentialStore验收:
authRef = null 支持本地无鉴权模型。LlmCredentialMissing。输出:
ILlmProviderAdapterOpenAICompatibleAdapter验收:
data: ... 增量文本。[DONE]。输出:
ILlmGatewayService验收:
modelId 路由到不同 endpoint。LlmTimeout。LlmProviderUnsupported。输出:
window.moliDesktop.llm.getModelsstreamChatcancelonDelta / onCompleted / onErrorllm.stream验收:
输出:
samples/plugins/sample.llm-command-palette/plugin.jsonindex.html验收:
50%。输出:
authRef 状态但不显示明文 key。验收:
输出:
验收:
dotnet build 通过。LlmModelRegistry:重复 id、disabled model、非法 endpoint、默认模型降级。CredentialStore:空 authRef、缺失密钥、环境变量 fallback。OpenAICompatibleAdapter:SSE delta、[DONE]、错误响应、异常流。LlmGatewayService:模型路由、超时、取消、错误映射。modelId -> endpoint 路由。llm.delta 只派发给请求来源插件实例。llm-models.json 验证备份恢复和诊断。authRef,确认输出区显示鉴权配置错误。| 问题 | 建议默认值 | 后续触发条件 |
|---|---|---|
| 密钥生产存储 | Windows Credential Manager | 管理窗口实现密钥编辑时落地 |
| 默认 adapter | OpenAI-compatible | 先覆盖 OpenAI、DeepSeek 兼容接口和本地服务 |
| DeepSeek 是否独立 adapter | 暂不强制 | 如果实际接口与 OpenAI-compatible 差异明显再拆 |
| 是否暴露本地 HTTP LLM API | 暂不暴露 | 插件桥接先满足需求;外部自动化需要时再设计 |
| 是否保存 prompt 历史 | 默认不保存 | 用户明确需要历史或调试审计时再评估 |