pi-web-ui 0.106.0 → 0.107.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/CHANGELOG.md +41 -1
  2. package/README.zh-TW.md +2 -2
  3. package/dist/server/agent-service.js +32 -16
  4. package/dist/server/client-state.js +2 -2
  5. package/dist/server/dsh/dsh-agent-service.js +15 -10
  6. package/dist/server/durable/durable-agent-service.js +153 -0
  7. package/dist/server/durable/durable-capabilities.js +11 -0
  8. package/dist/server/durable/durable-driver.js +481 -0
  9. package/dist/server/durable/durable-loader.js +38 -0
  10. package/dist/server/durable/durable-models.js +283 -0
  11. package/dist/server/durable/durable-storage.js +42 -0
  12. package/dist/server/durable/durable-tools.js +45 -0
  13. package/dist/server/durable/index.js +8 -0
  14. package/dist/server/engine-capabilities.js +20 -1
  15. package/dist/server/engine-probe.js +156 -8
  16. package/dist/server/global-loader.js +335 -0
  17. package/dist/server/index.js +127 -17
  18. package/dist/server/managed.js +2 -0
  19. package/dist/server/marker-service.js +5 -19
  20. package/dist/server/markers/index.js +1 -3
  21. package/dist/server/model-resolver.js +91 -3
  22. package/dist/server/plugins.js +18 -1
  23. package/dist/server/sdk-origin.js +2 -2
  24. package/dist/server/serialize.js +1 -1
  25. package/dist/server/tool-manager.js +3 -19
  26. package/dist/server/universal/driver-base.js +4 -0
  27. package/dist/server/universal/drivers/claude-code.js +3 -2
  28. package/dist/server/universal/universal-service.js +19 -2
  29. package/dist/server/universal/universal-session.js +61 -7
  30. package/dist/server/update-check.js +20 -8
  31. package/package.json +1 -1
  32. package/plugins/catalog.json +13 -2
  33. package/themes/dark-teal.css +0 -1
  34. package/themes/flow-light.css +1085 -0
  35. package/themes/flow.css +1094 -0
  36. package/themes/wallpaper-flow.css +1158 -0
  37. package/themes/wallpaper-obsidian.css +50 -0
  38. package/themes/zhujian-dark.css +0 -7
  39. package/themes/zhujian.css +0 -7
  40. package/themes/zhupi-dark.css +0 -7
  41. package/themes/zhupi.css +0 -7
  42. package/web/dist/assets/{TerminalPanel-CfxKLDW9.js → TerminalPanel-BnViyTlx.js} +2 -2
  43. package/web/dist/assets/index-cCRCYMwT.css +1 -0
  44. package/web/dist/assets/index-fH5vhkAE.js +690 -0
  45. package/web/dist/index.html +2 -2
  46. package/web/dist/sw.js +1 -1
  47. package/web/dist/assets/index-BtcP6BDk.css +0 -1
  48. package/web/dist/assets/index-XVtCzcHR.js +0 -690
@@ -0,0 +1,283 @@
1
+ /**
2
+ * durable-models.ts — Pi Durable 引擎的全局模型继承与提供商装配器。
3
+ *
4
+ * 职责:
5
+ * 1. 继承全局模型事实源:从 SDK ModelRuntime 与 models.json 聚合全量可用模型;
6
+ * 2. 装配 @earendil-works/pi-ai 的 models 容器,注入内置与自定义 Providers(带 API Key 与 BaseURL);
7
+ * 3. 解析用户选择的 activeModel,传递给 Durable Conversation 运行时。
8
+ */
9
+ import { existsSync, readFileSync } from "node:fs";
10
+ import { join } from "node:path";
11
+ import { homedir } from "node:os";
12
+ import { listCustomModelsFromConfig, readModelsJson, resolveProviderCredential, isProtocolSupportedByEngine, } from "../model-resolver.js";
13
+ import { loadDurablePeerModule } from "./durable-loader.js";
14
+ /**
15
+ * 聚合全局所有已鉴权、可用的模型名录(包括官方内置模型与用户自定义模型)。
16
+ * 优先收录并前置展示 models.json 中的用户自定义服务商与模型。
17
+ */
18
+ export async function listGlobalAvailableModels(cwd, agentDir) {
19
+ const modelMap = new Map();
20
+ // 1. 优先收录 models.json 中的用户自定义模型(本地代理/自定义端点通常为首选活动端点)
21
+ try {
22
+ const customModels = listCustomModelsFromConfig(agentDir, (entry) => isProtocolSupportedByEngine("durable", entry.api, entry.providerId, entry.modelId));
23
+ for (const cm of customModels) {
24
+ const fullId = `${cm.providerId}/${cm.modelId}`;
25
+ if (!modelMap.has(fullId)) {
26
+ modelMap.set(fullId, {
27
+ id: fullId,
28
+ name: cm.name || cm.modelId,
29
+ provider: cm.providerId,
30
+ vision: cm.vision ?? false,
31
+ reasoning: cm.reasoning ?? false,
32
+ });
33
+ }
34
+ }
35
+ }
36
+ catch {
37
+ /* ignore */
38
+ }
39
+ // 2. 补充 SDK ModelRuntime 动态获取的官方与外部模型
40
+ try {
41
+ const piSdk = await import(/* webpackIgnore: true */ "@earendil-works/pi-coding-agent").catch(() => null);
42
+ if (piSdk && typeof piSdk.createAgentSessionServices === "function") {
43
+ const services = await piSdk.createAgentSessionServices({ cwd, agentDir });
44
+ const available = await services.modelRuntime.getAvailable();
45
+ for (const m of available) {
46
+ // 严格按照实际协议类型进行过滤(绝不按模型名字猜测)
47
+ if (!isProtocolSupportedByEngine("durable", m.api, m.provider, m.id)) {
48
+ continue;
49
+ }
50
+ const fullId = `${m.provider}/${m.id}`;
51
+ if (!modelMap.has(fullId)) {
52
+ modelMap.set(fullId, {
53
+ id: fullId,
54
+ name: (m.name || m.id).replace(/\s*\(new\)$/i, "").trim(),
55
+ provider: m.provider,
56
+ vision: m.input?.includes("image") ?? false,
57
+ reasoning: m.reasoning,
58
+ });
59
+ }
60
+ }
61
+ }
62
+ }
63
+ catch {
64
+ /* SDK model runtime load failed, fall back to models.json */
65
+ }
66
+ return Array.from(modelMap.values());
67
+ }
68
+ /**
69
+ * 为 Pi Durable Harness 装配并初始化全局模型服务(@earendil-works/pi-ai Models 实例)。
70
+ */
71
+ export async function setupDurableModels(agentDir) {
72
+ const aiModule = await loadDurablePeerModule("@earendil-works/pi-ai", "models").catch(() => null);
73
+ if (!aiModule || typeof aiModule.createModels !== "function") {
74
+ return {};
75
+ }
76
+ const models = aiModule.createModels();
77
+ // 1. 尝试全量装载内置提供商(providers/all 包含 opencode-go、openrouter 等 42+ 个提供商)
78
+ try {
79
+ const allProvidersModule = await loadDurablePeerModule("@earendil-works/pi-ai", "providers/all").catch(() => null);
80
+ if (allProvidersModule && typeof allProvidersModule.builtinProviders === "function") {
81
+ const builtins = allProvidersModule.builtinProviders();
82
+ for (const p of builtins) {
83
+ if (typeof models.setProvider === "function") {
84
+ models.setProvider(p);
85
+ }
86
+ }
87
+ }
88
+ }
89
+ catch {
90
+ /* ignore fallback to minimal builtins */
91
+ }
92
+ // 2. 兜底保障基础内置提供商
93
+ const fallbackBuiltinIds = ["openai", "anthropic", "google", "mistral", "groq", "deepseek"];
94
+ for (const pid of fallbackBuiltinIds) {
95
+ if (models.providers && models.providers.has(pid))
96
+ continue;
97
+ try {
98
+ const providerModule = await loadDurablePeerModule("@earendil-works/pi-ai", `providers/${pid}`).catch(() => null);
99
+ const providerFactory = providerModule?.[`${pid}Provider`] || providerModule?.default;
100
+ if (typeof providerFactory === "function") {
101
+ const instance = providerFactory();
102
+ if (typeof models.setProvider === "function") {
103
+ models.setProvider(instance);
104
+ }
105
+ }
106
+ }
107
+ catch {
108
+ /* provider loading skipped */
109
+ }
110
+ }
111
+ // 3. 动态加载 models.json 中的自定义服务商与模型
112
+ try {
113
+ const { providers: customProviders } = readModelsJson(agentDir);
114
+ const oCompModule = await loadDurablePeerModule("@earendil-works/pi-ai", "api/openai-completions.lazy").catch(() => null);
115
+ const oRespModule = await loadDurablePeerModule("@earendil-works/pi-ai", "api/openai-responses.lazy").catch(() => null);
116
+ const aMsgModule = await loadDurablePeerModule("@earendil-works/pi-ai", "api/anthropic-messages.lazy").catch(() => null);
117
+ for (const [providerId, pConfig] of Object.entries(customProviders)) {
118
+ if (!pConfig || typeof pConfig !== "object")
119
+ continue;
120
+ const cred = resolveProviderCredential(agentDir, providerId);
121
+ const apiProtocol = (typeof pConfig.api === "string" ? pConfig.api : "").toLowerCase();
122
+ let apiImpl = null;
123
+ if (apiProtocol === "anthropic-messages" && aMsgModule?.anthropicMessagesApi) {
124
+ apiImpl = aMsgModule.anthropicMessagesApi();
125
+ }
126
+ else if (apiProtocol === "openai-responses" && oRespModule?.openAIResponsesApi) {
127
+ apiImpl = oRespModule.openAIResponsesApi();
128
+ }
129
+ else if (oCompModule?.openAICompletionsApi) {
130
+ apiImpl = oCompModule.openAICompletionsApi();
131
+ }
132
+ if (apiImpl && typeof aiModule.createProvider === "function") {
133
+ const rawModels = Array.isArray(pConfig.models) ? pConfig.models : [];
134
+ const customProvider = aiModule.createProvider({
135
+ id: providerId,
136
+ name: pConfig.name || providerId,
137
+ baseUrl: cred.baseUrl,
138
+ headers: cred.headers,
139
+ auth: {
140
+ apiKey: {
141
+ name: `${providerId} API key`,
142
+ login: async () => ({ type: "api_key", key: cred.apiKey || "" }),
143
+ resolve: async () => (cred.apiKey ? { auth: { apiKey: cred.apiKey }, source: "config" } : undefined),
144
+ },
145
+ },
146
+ models: rawModels.map((m) => ({
147
+ ...m,
148
+ provider: providerId,
149
+ api: m.api || pConfig.api || "openai-completions",
150
+ baseUrl: cred.baseUrl,
151
+ cost: m.cost ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
152
+ type: "chat",
153
+ })),
154
+ api: apiImpl,
155
+ });
156
+ models.setProvider(customProvider);
157
+ }
158
+ }
159
+ }
160
+ catch {
161
+ /* custom provider setup skipped */
162
+ }
163
+ // 4. 继承持久化动态模型缓存 (~/.pi/agent/models-store.json)
164
+ try {
165
+ const userAgentDir = agentDir || join(homedir(), ".pi", "agent");
166
+ const storePath = join(userAgentDir, "models-store.json");
167
+ if (existsSync(storePath)) {
168
+ const store = JSON.parse(readFileSync(storePath, "utf8"));
169
+ for (const [providerId, pData] of Object.entries(store)) {
170
+ const p = typeof models.getProvider === "function" ? models.getProvider(providerId) : undefined;
171
+ if (p && Array.isArray(pData?.models)) {
172
+ const extraModels = pData.models;
173
+ const origGetModels = typeof p.getModels === "function" ? p.getModels.bind(p) : null;
174
+ const origGetAllModels = typeof p.getAllModels === "function" ? p.getAllModels.bind(p) : null;
175
+ if (origGetModels) {
176
+ p.getModels = () => {
177
+ const list = origGetModels();
178
+ const ids = new Set(list.map((m) => m.id));
179
+ const added = extraModels
180
+ .filter((m) => !ids.has(m.id))
181
+ .map((m) => ({
182
+ ...m,
183
+ cost: m.cost ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
184
+ }));
185
+ return [...list, ...added];
186
+ };
187
+ }
188
+ if (origGetAllModels) {
189
+ p.getAllModels = () => {
190
+ const list = origGetAllModels();
191
+ const ids = new Set(list.map((m) => m.id));
192
+ const added = extraModels
193
+ .filter((m) => !ids.has(m.id))
194
+ .map((m) => ({
195
+ ...m,
196
+ cost: m.cost ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
197
+ }));
198
+ return [...list, ...added];
199
+ };
200
+ }
201
+ }
202
+ }
203
+ }
204
+ }
205
+ catch {
206
+ /* dynamic models store read skipped */
207
+ }
208
+ // 5. 为所有已注册 Provider 注入凭证与 BaseURL
209
+ try {
210
+ if (models.providers && typeof models.providers.keys === "function") {
211
+ for (const providerId of models.providers.keys()) {
212
+ const cred = resolveProviderCredential(agentDir, providerId);
213
+ if (cred.apiKey && models.credentials && typeof models.credentials.modify === "function") {
214
+ await models.credentials
215
+ .modify(providerId, async () => ({
216
+ type: "api_key",
217
+ key: cred.apiKey,
218
+ }))
219
+ .catch(() => { });
220
+ }
221
+ if (cred.baseUrl) {
222
+ const p = models.getProvider(providerId);
223
+ if (p)
224
+ p.baseUrl = cred.baseUrl;
225
+ }
226
+ if (cred.headers) {
227
+ const p = models.getProvider(providerId);
228
+ if (p)
229
+ p.headers = { ...p.headers, ...cred.headers };
230
+ }
231
+ }
232
+ }
233
+ }
234
+ catch {
235
+ /* credential hydration skipped */
236
+ }
237
+ return models;
238
+ }
239
+ /**
240
+ * 将形如 "openai/gpt-4o" 或 "gpt-4o" 的模型标识解析为 Durable 引擎可识别的 provider 与 modelId。
241
+ */
242
+ export function resolveDurableModelChoice(modelId, fallbackList, agentDir) {
243
+ if (!modelId || !modelId.trim() || modelId === "default") {
244
+ if (fallbackList && fallbackList.length > 0) {
245
+ // 1. 优先在 fallbackList 中寻找用户在 models.json 里明确配置的自定义端点模型
246
+ const { providers: customConfig } = readModelsJson(agentDir);
247
+ const customFirst = fallbackList.find((m) => Object.prototype.hasOwnProperty.call(customConfig, m.provider));
248
+ if (customFirst) {
249
+ return { provider: customFirst.provider, modelId: customFirst.id.replace(`${customFirst.provider}/`, "") };
250
+ }
251
+ // 2. 其次寻找具备有效 baseUrl 或独立 apiKey 的可用模型
252
+ const configured = fallbackList.find((m) => {
253
+ const cred = resolveProviderCredential(agentDir, m.provider);
254
+ return Boolean(cred.baseUrl || cred.apiKey);
255
+ });
256
+ const chosen = configured ?? fallbackList[0];
257
+ return { provider: chosen.provider, modelId: chosen.id.replace(`${chosen.provider}/`, "") };
258
+ }
259
+ return undefined;
260
+ }
261
+ const trimmed = modelId.trim();
262
+ if (trimmed.includes("/")) {
263
+ const slashIdx = trimmed.indexOf("/");
264
+ return {
265
+ provider: trimmed.slice(0, slashIdx),
266
+ modelId: trimmed.slice(slashIdx + 1),
267
+ };
268
+ }
269
+ // 若未带 provider 前缀,尝试在已知列表中寻找匹配项
270
+ if (fallbackList) {
271
+ const found = fallbackList.find((m) => m.id === trimmed || m.id.endsWith(`/${trimmed}`));
272
+ if (found) {
273
+ return {
274
+ provider: found.provider,
275
+ modelId: found.id.replace(`${found.provider}/`, ""),
276
+ };
277
+ }
278
+ }
279
+ return {
280
+ provider: "openai",
281
+ modelId: trimmed,
282
+ };
283
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * durable-storage.ts — Pi Durable 存储后端管理与目录初始化。
3
+ *
4
+ * 职责:
5
+ * 1. 自动为每个工作区或全局建立 SQLite 持久化存储(WAL 模式);
6
+ * 2. 动态加载 @earendil-works/pi-durable 的持久化仓储驱动;
7
+ * 3. 当未安装原生包或缺少编译依赖时,优雅回退到内存存储或报错。
8
+ */
9
+ import { existsSync, mkdirSync } from "node:fs";
10
+ import { createHash } from "node:crypto";
11
+ import { join } from "node:path";
12
+ import { loadDurableModule } from "./durable-loader.js";
13
+ /**
14
+ * 为指定工作区 cwd 解析或创建 SQLite 存储实例。
15
+ */
16
+ export async function openDurableStorage(dataDir, cwd) {
17
+ const durableDir = join(dataDir, "durable");
18
+ if (!existsSync(durableDir)) {
19
+ mkdirSync(durableDir, { recursive: true });
20
+ }
21
+ // 按 cwd 的 hash 区分项目存储,避免多项目写入同一库发生锁争用
22
+ const slug = createHash("sha256").update(cwd).digest("hex").slice(0, 12);
23
+ const dbPath = join(durableDir, `session-${slug}.sqlite`);
24
+ try {
25
+ // 动态通过全局/本地加载器加载 SQLite 持久层
26
+ const sqliteModule = await loadDurableModule("storage/sqlite/node").catch(() => null);
27
+ if (sqliteModule && typeof sqliteModule.openNodeSqliteStorage === "function") {
28
+ const storage = await sqliteModule.openNodeSqliteStorage(dbPath);
29
+ return { storage, path: dbPath, isMemory: false };
30
+ }
31
+ }
32
+ catch {
33
+ /* sqlite native driver not available, fall back to memory */
34
+ }
35
+ // 动态尝试加载 MemoryStorage
36
+ const coreModule = await loadDurableModule().catch(() => null);
37
+ if (coreModule && coreModule.MemoryStorage) {
38
+ const storage = new coreModule.MemoryStorage();
39
+ return { storage, isMemory: true };
40
+ }
41
+ throw new Error("Pi Durable 依赖未安装。请运行 npm i -g @earendil-works/pi-durable 启用该引擎。");
42
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * durable-tools.ts — Pi Durable 引擎的工具加载与环境装配。
3
+ *
4
+ * 职责:
5
+ * 1. 动态加载 @earendil-works/pi-durable/tools 中的官方 CodingTools(read/write/edit/bash);
6
+ * 2. 装配 Registry,注入工作区路径、图片处理器及自定义扩展;
7
+ * 3. 将现有的工具结果(三通道:output / structuredOutput / details)安全适配给 UI。
8
+ */
9
+ import { loadDurableModule } from "./durable-loader.js";
10
+ /**
11
+ * 为指定工作区配置 Durable Registry 和工具链。
12
+ */
13
+ export async function setupDurableRegistry(cwd, options) {
14
+ const durableModule = await loadDurableModule().catch(() => null);
15
+ if (!durableModule || typeof durableModule.createRegistry !== "function") {
16
+ throw new Error("Pi Durable 依赖未安装。请运行 npm i -g @earendil-works/pi-durable 启用该引擎。");
17
+ }
18
+ const registry = durableModule.createRegistry();
19
+ const installedToolNames = [];
20
+ // 动态尝试加载官方编码工具
21
+ try {
22
+ const toolsModule = await loadDurableModule("tools").catch(() => null);
23
+ if (toolsModule && toolsModule.CodingTools) {
24
+ registry.install(toolsModule.CodingTools);
25
+ installedToolNames.push("read", "write", "edit", "bash");
26
+ }
27
+ }
28
+ catch {
29
+ /* coding tools load failed */
30
+ }
31
+ // 注入工作区路径环境配置(如果存在 defineExtension)
32
+ if (typeof durableModule.defineExtension === "function") {
33
+ const WorkspaceEnv = durableModule.defineExtension({
34
+ name: "workspace_env",
35
+ environment: {
36
+ cwd,
37
+ },
38
+ });
39
+ registry.install(WorkspaceEnv);
40
+ }
41
+ return {
42
+ registry,
43
+ installedToolNames,
44
+ };
45
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * server/durable/index.ts — Pi Durable 独立智能体引擎模块统一出口。
3
+ */
4
+ export { DurableAgentService } from "./durable-agent-service.js";
5
+ export { DurableAgentDriver } from "./durable-driver.js";
6
+ export { openDurableStorage } from "./durable-storage.js";
7
+ export { setupDurableRegistry } from "./durable-tools.js";
8
+ export { DEFAULT_DURABLE_CAPABILITIES, resolveDurableCapabilities } from "./durable-capabilities.js";
@@ -63,10 +63,29 @@ export const DEFAULT_UNIVERSAL_CAPABILITIES = Object.freeze({
63
63
  steer: false,
64
64
  ephemeralChat: true,
65
65
  });
66
+ /** Pi Durable 引擎能力:事务化、任务图驱动的持久执行底座 */
67
+ export const DEFAULT_DURABLE_CAPABILITIES = Object.freeze({
68
+ remoteSsh: false,
69
+ sandboxes: false,
70
+ workspaceRoots: true,
71
+ conversationRef: true,
72
+ pageRef: true,
73
+ presentFiles: true,
74
+ planMode: false,
75
+ delegateMode: false,
76
+ subagents: true,
77
+ toolPromptOverride: false,
78
+ lazyTools: false,
79
+ softCap: false,
80
+ treeFork: true,
81
+ messageEdit: true,
82
+ steer: true,
83
+ ephemeralChat: true,
84
+ });
66
85
  /** 合并并归一化能力声明(默认回落到通用基座保守值) */
67
86
  export function resolveEngineCapabilities(caps, base = DEFAULT_UNIVERSAL_CAPABILITIES) {
68
87
  return {
69
88
  ...base,
70
- ...(caps ?? {}),
89
+ ...caps,
71
90
  };
72
91
  }
@@ -1,10 +1,12 @@
1
- import { execFile } from "node:child_process";
1
+ import { execFile, spawn } from "node:child_process";
2
2
  import { existsSync, readFileSync } from "node:fs";
3
3
  import { join } from "node:path";
4
4
  import { VERSION } from "@earendil-works/pi-coding-agent";
5
5
  import { runtimeBaseCandidates } from "./dsh/preset-clones.js";
6
+ import { killPidTree } from "./process-utils.js";
6
7
  import { probeClaudeCode } from "./universal/drivers/claude-code.js";
7
8
  import { compareVersions, defaultFetcher, fetchLatest, NPM_DEFAULT_REGISTRY, } from "./update-check.js";
9
+ import { probeGlobalPackage } from "./global-loader.js";
8
10
  export const ENGINE_PACKAGES = {
9
11
  pi: {
10
12
  id: "pi",
@@ -21,6 +23,11 @@ export const ENGINE_PACKAGES = {
21
23
  packageName: "@anthropic-ai/claude-code",
22
24
  installCommand: "npm i -g @anthropic-ai/claude-code",
23
25
  },
26
+ durable: {
27
+ id: "durable",
28
+ packageName: "@earendil-works/pi-durable",
29
+ installCommand: "npm i -g @earendil-works/pi-durable",
30
+ },
24
31
  };
25
32
  /** 探针缓存 TTL:5 秒(短时多次连接或 UI 打开时免除重复频繁执行进程调用) */
26
33
  const CACHE_TTL_MS = 5000;
@@ -28,10 +35,18 @@ const CACHE_TTL_MS = 5000;
28
35
  const REGISTRY_CACHE_TTL_MS = 5 * 60 * 1000;
29
36
  const registryCache = new Map();
30
37
  let lastProbeAt = 0;
38
+ const updatingEngineIds = new Set();
39
+ function applyUpdatingFlag(list) {
40
+ return list.map((s) => ({
41
+ ...s,
42
+ ...(updatingEngineIds.has(s.id) ? { updating: true } : {}),
43
+ }));
44
+ }
31
45
  let cachedStatuses = [
32
46
  { id: "pi", installed: true, packageName: ENGINE_PACKAGES.pi.packageName, version: VERSION },
33
47
  { id: "dsh", installed: false, packageName: ENGINE_PACKAGES.dsh.packageName },
34
48
  { id: "claude", installed: false, packageName: ENGINE_PACKAGES.claude.packageName },
49
+ { id: "durable", installed: false, packageName: ENGINE_PACKAGES.durable.packageName },
35
50
  ];
36
51
  /**
37
52
  * 查询全局包在 npm 远端的最新版本号(带 5 分钟缓存)。
@@ -88,6 +103,16 @@ export function probePi() {
88
103
  */
89
104
  export async function probeDsh() {
90
105
  const pkgName = ENGINE_PACKAGES.dsh.packageName;
106
+ // 0. 通用全局包探测器(覆盖 fnm / nvm / pnpm / 全局 prefix 等)
107
+ try {
108
+ const globalProbe = probeGlobalPackage(pkgName);
109
+ if (globalProbe.installed) {
110
+ return { id: "dsh", installed: true, packageName: pkgName, version: globalProbe.version };
111
+ }
112
+ }
113
+ catch {
114
+ /* ignore */
115
+ }
91
116
  // 1. 路径快速探测(纯 fs 访问,无进程派生开销)
92
117
  try {
93
118
  for (const root of runtimeBaseCandidates()) {
@@ -169,6 +194,28 @@ export async function probeClaude() {
169
194
  return { id: "claude", installed: false, packageName: pkgName };
170
195
  }
171
196
  }
197
+ /**
198
+ * 探测 Pi Durable 引擎状态。
199
+ * 检查当前项目或全局环境(npm -g, fnm, nvm 等)下是否安装了 @earendil-works/pi-durable。
200
+ */
201
+ export async function probeDurable(force = false) {
202
+ const pkgName = ENGINE_PACKAGES.durable.packageName;
203
+ try {
204
+ const probe = probeGlobalPackage(pkgName, { refresh: force });
205
+ if (probe.installed) {
206
+ return {
207
+ id: "durable",
208
+ installed: true,
209
+ packageName: pkgName,
210
+ version: probe.version,
211
+ };
212
+ }
213
+ }
214
+ catch {
215
+ /* ignore */
216
+ }
217
+ return { id: "durable", installed: false, packageName: pkgName };
218
+ }
172
219
  /**
173
220
  * 按引擎 ID 单独探测状态。
174
221
  */
@@ -187,8 +234,11 @@ export async function probeEngine(id, force = false) {
187
234
  else if (id === "claude") {
188
235
  result = await probeClaude();
189
236
  }
237
+ else if (id === "durable") {
238
+ result = await probeDurable();
239
+ }
190
240
  else {
191
- result = { id, installed: false };
241
+ result = { id: id, installed: false };
192
242
  }
193
243
  await enrichWithUpdateInfo(result, force);
194
244
  // 更新单项缓存
@@ -197,30 +247,128 @@ export async function probeEngine(id, force = false) {
197
247
  cachedStatuses[idx] = result;
198
248
  else
199
249
  cachedStatuses.push(result);
200
- return result;
250
+ return {
251
+ ...result,
252
+ ...(updatingEngineIds.has(id) ? { updating: true } : {}),
253
+ };
201
254
  }
202
255
  /**
203
256
  * 探测全部已知引擎并返回最新状态列表(带 TTL 缓存防抖)。
204
257
  */
205
258
  export async function probeAllEngines(force = false) {
206
259
  if (!force && Date.now() - lastProbeAt < CACHE_TTL_MS && cachedStatuses.length > 0) {
207
- return cachedStatuses;
260
+ return applyUpdatingFlag(cachedStatuses);
208
261
  }
209
- const [pi, dsh, claude] = await Promise.all([probePi(), probeDsh(), probeClaude()]);
262
+ const [pi, dsh, claude, durable] = await Promise.all([probePi(), probeDsh(), probeClaude(), probeDurable()]);
210
263
  await Promise.all([
211
264
  enrichWithUpdateInfo(pi, force),
212
265
  enrichWithUpdateInfo(dsh, force),
213
266
  enrichWithUpdateInfo(claude, force),
267
+ enrichWithUpdateInfo(durable, force),
214
268
  ]);
215
- cachedStatuses = [pi, dsh, claude];
269
+ cachedStatuses = [pi, dsh, claude, durable];
216
270
  lastProbeAt = Date.now();
217
- return cachedStatuses;
271
+ return applyUpdatingFlag(cachedStatuses);
218
272
  }
219
273
  /**
220
274
  * 同步获取当前缓存的引擎探测结果(握手帧或即时读取使用)。
221
275
  */
222
276
  export function getCachedEngineStatuses() {
223
- return [...cachedStatuses];
277
+ return applyUpdatingFlag(cachedStatuses);
278
+ }
279
+ /**
280
+ * 查询指定引擎是否正在执行后台更新子进程。
281
+ */
282
+ export function isEngineUpdating(engineId) {
283
+ return updatingEngineIds.has(engineId);
284
+ }
285
+ /**
286
+ * 在后台子进程中执行引擎全局包更新(npm i -g <pkg>@latest)。
287
+ * 避免在可见终端中通过 PTY 模拟输入导致命令首字母丢失或输入不全的问题。
288
+ */
289
+ export async function updateEngineBackground(engineId, options) {
290
+ const meta = ENGINE_PACKAGES[engineId];
291
+ if (!meta || !meta.packageName) {
292
+ return { ok: false, error: `不支持或未知的引擎「${engineId}」` };
293
+ }
294
+ if (updatingEngineIds.has(engineId)) {
295
+ return { ok: false, error: `引擎「${engineId}」正在后台更新中,请勿重复操作` };
296
+ }
297
+ updatingEngineIds.add(engineId);
298
+ const pkg = meta.packageName;
299
+ const timeoutMs = Math.max(10_000, Number(options?.timeoutMs ?? 300_000));
300
+ const isWin = process.platform === "win32";
301
+ const spawnCmd = isWin ? process.env.ComSpec || "cmd.exe" : "npm";
302
+ const spawnArgs = isWin ? ["/d", "/s", "/c", "npm", "i", "-g", `${pkg}@latest`] : ["i", "-g", `${pkg}@latest`];
303
+ try {
304
+ const child = spawn(spawnCmd, spawnArgs, {
305
+ windowsHide: true,
306
+ detached: !isWin,
307
+ stdio: ["ignore", "pipe", "pipe"],
308
+ env: {
309
+ ...process.env,
310
+ NO_COLOR: "1",
311
+ },
312
+ });
313
+ let out = "";
314
+ const appendOut = (chunk) => {
315
+ out = (out + chunk.toString()).slice(-8000);
316
+ };
317
+ child.stdout?.on("data", appendOut);
318
+ child.stderr?.on("data", appendOut);
319
+ const res = await new Promise((resolve) => {
320
+ let done = false;
321
+ const timer = setTimeout(() => {
322
+ if (done)
323
+ return;
324
+ done = true;
325
+ if (child.pid)
326
+ void killPidTree(child.pid);
327
+ resolve({ ok: false, code: null, error: `更新超时(超过 ${Math.round(timeoutMs / 1000)} 秒)` });
328
+ }, timeoutMs);
329
+ child.on("error", (err) => {
330
+ if (done)
331
+ return;
332
+ done = true;
333
+ clearTimeout(timer);
334
+ resolve({ ok: false, code: null, error: err.message });
335
+ });
336
+ child.on("close", (code) => {
337
+ if (done)
338
+ return;
339
+ done = true;
340
+ clearTimeout(timer);
341
+ resolve({
342
+ ok: code === 0,
343
+ code,
344
+ error: code === 0 ? undefined : `npm 退出码 ${code}`,
345
+ });
346
+ });
347
+ });
348
+ if (res.ok) {
349
+ registryCache.delete(pkg);
350
+ try {
351
+ await probeAllEngines(true);
352
+ }
353
+ catch {
354
+ /* best effort */
355
+ }
356
+ }
357
+ return {
358
+ ok: res.ok,
359
+ error: res.error,
360
+ output: out.trim(),
361
+ };
362
+ }
363
+ catch (err) {
364
+ return {
365
+ ok: false,
366
+ error: err.message,
367
+ };
368
+ }
369
+ finally {
370
+ updatingEngineIds.delete(engineId);
371
+ }
224
372
  }
225
373
  /**
226
374
  * 收集已安装的第三方全局引擎包,供全量更新检查(check_updates_all)纳入统一检查名录。