pi-web-ui 0.110.0 → 0.112.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 (110) hide show
  1. package/CHANGELOG.md +55 -2
  2. package/bin/frp-manager.mjs +92 -7
  3. package/dist/server/agent-formatters.js +10 -6
  4. package/dist/server/agent-service-daemon.js +27 -9
  5. package/dist/server/agent-service.js +1442 -489
  6. package/dist/server/approval-audit.js +119 -0
  7. package/dist/server/approval-default-rules.js +4 -4
  8. package/dist/server/approval-rules.js +42 -17
  9. package/dist/server/attachment-store.js +8 -8
  10. package/dist/server/attachments.js +114 -31
  11. package/dist/server/canvas/canvas-agent-tool.js +593 -0
  12. package/dist/server/canvas/canvas-cards.js +144 -0
  13. package/dist/server/canvas/canvas-dispatch.js +155 -0
  14. package/dist/server/canvas/canvas-orchestrator.js +1094 -0
  15. package/dist/server/canvas/canvas-store.js +260 -0
  16. package/dist/server/client-id-utils.js +2 -2
  17. package/dist/server/client-state.js +52 -0
  18. package/dist/server/context-budget.js +6 -3
  19. package/dist/server/delegate-mode.js +6 -3
  20. package/dist/server/delegate-task.js +18 -3
  21. package/dist/server/dispatch-domain-handlers.js +3 -0
  22. package/dist/server/dsh/dsh-agent-service.js +357 -20
  23. package/dist/server/dsh/dsh-client.js +10 -1
  24. package/dist/server/dsh/dsh-serialize.js +1 -1
  25. package/dist/server/dsh/runtime/goal-rpc.mjs +128 -3
  26. package/dist/server/dsh/runtime/launcher.mjs +59 -5
  27. package/dist/server/dsh/runtime/runtime-root.mjs +353 -40
  28. package/dist/server/durable/durable-agent-service.js +3 -0
  29. package/dist/server/durable/durable-driver.js +75 -9
  30. package/dist/server/durable/durable-loader.js +1 -14
  31. package/dist/server/durable/durable-models.js +107 -0
  32. package/dist/server/durable/index.js +0 -4
  33. package/dist/server/engine-probe.js +76 -37
  34. package/dist/server/eval-tool.js +28 -3
  35. package/dist/server/file-transfer-routes.js +8 -2
  36. package/dist/server/files-service.js +10 -2
  37. package/dist/server/goal-service.js +7 -0
  38. package/dist/server/index.js +480 -59
  39. package/dist/server/json-utils.js +57 -0
  40. package/dist/server/marker-service.js +11 -1
  41. package/dist/server/markers/marker.js +45 -4
  42. package/dist/server/markers/registry.js +31 -0
  43. package/dist/server/message-window.js +44 -8
  44. package/dist/server/model-admin.js +68 -106
  45. package/dist/server/model-resolver.js +66 -44
  46. package/dist/server/office-parse.js +394 -7
  47. package/dist/server/plan-manager.js +3 -6
  48. package/dist/server/plugin-api-catalog.js +7 -0
  49. package/dist/server/plugin-assets.js +238 -0
  50. package/dist/server/plugin-facilities.js +22 -0
  51. package/dist/server/plugin-ui-slots.js +1 -0
  52. package/dist/server/plugins.js +296 -25
  53. package/dist/server/preset-fields.js +60 -2
  54. package/dist/server/preset-share.js +8 -2
  55. package/dist/server/prompt-assembler.js +9 -2
  56. package/dist/server/prompt-composer.js +84 -44
  57. package/dist/server/protocol-version.js +1 -1
  58. package/dist/server/queue-utils.js +156 -0
  59. package/dist/server/remote-ssh-service.js +16 -4
  60. package/dist/server/sdk-builtin-extensions.js +85 -0
  61. package/dist/server/server-config.js +66 -0
  62. package/dist/server/session-parser.js +49 -13
  63. package/dist/server/session-search.js +4 -3
  64. package/dist/server/settings-service.js +56 -7
  65. package/dist/server/soft-cap.js +8 -6
  66. package/dist/server/subagent-helpers.js +22 -1
  67. package/dist/server/subagent-notify.js +93 -0
  68. package/dist/server/subagent-security-gate.js +282 -0
  69. package/dist/server/subagent-templates.js +8 -0
  70. package/dist/server/subagents.js +144 -17
  71. package/dist/server/terminals.js +196 -8
  72. package/dist/server/text-quote.js +61 -0
  73. package/dist/server/tool-approval.js +63 -4
  74. package/dist/server/tool-guards.js +208 -0
  75. package/dist/server/tool-host-factories.js +46 -10
  76. package/dist/server/tool-manager.js +30 -0
  77. package/dist/server/tool-overrides.js +21 -11
  78. package/dist/server/univer-service.js +448 -0
  79. package/dist/server/universal/driver-base.js +8 -0
  80. package/dist/server/universal/drivers/claude-code.js +39 -5
  81. package/dist/server/universal/drivers/dsh-driver.js +3 -0
  82. package/dist/server/universal/index.js +0 -1
  83. package/dist/server/universal/universal-attachments.js +5 -0
  84. package/dist/server/universal/universal-service.js +5 -0
  85. package/dist/server/universal/universal-session.js +114 -21
  86. package/dist/server/update-check.js +90 -5
  87. package/dist/server/workspace-snapshot.js +33 -2
  88. package/dist/server/worktree-service.js +189 -1
  89. package/docs/dsh-engine.md +493 -0
  90. package/package.json +5 -4
  91. package/plugin-sdk/client-utils.mjs +192 -5
  92. package/plugin-sdk/index.d.ts +80 -1
  93. package/plugin-sdk/index.mjs +99 -0
  94. package/plugin-sdk/package.json +5 -1
  95. package/plugins/catalog.json +33 -0
  96. package/themes/aetheris.css +114 -0
  97. package/themes/bases/obsidian-base.css +216 -0
  98. package/themes/md-preview.css +113 -0
  99. package/themes/wallpaper-flow.css +182 -0
  100. package/web/dist/assets/{TerminalPanel-BHjM6pzY.js → TerminalPanel-Dqr1dK28.js} +2 -2
  101. package/web/dist/assets/index-Dh8BX-lP.js +720 -0
  102. package/web/dist/assets/index-DqrC1I_a.css +1 -0
  103. package/web/dist/assets/{markdown-DXwnfD9T.js → markdown-BJZlfvdP.js} +24 -24
  104. package/web/dist/assets/markdown-DSNUiDzp.css +1 -0
  105. package/web/dist/index.html +13 -4
  106. package/web/dist/sw.js +1 -1
  107. package/web/dist/assets/es-DIDZppIF.js +0 -2
  108. package/web/dist/assets/index-DwInT7-a.css +0 -1
  109. package/web/dist/assets/index-GfVFIgIL.js +0 -693
  110. package/web/dist/assets/markdown-CCeVCbci.css +0 -1
@@ -10,8 +10,9 @@
10
10
  import { BaseAgentDriver } from "../universal/driver-base.js";
11
11
  import { openDurableStorage } from "./durable-storage.js";
12
12
  import { setupDurableRegistry } from "./durable-tools.js";
13
- import { listGlobalAvailableModels, setupDurableModels, resolveDurableModelChoice, } from "./durable-models.js";
13
+ import { listGlobalAvailableModels, setupDurableModels, resolveDurableModelChoice, resolveDurableThinkingLevels, } from "./durable-models.js";
14
14
  import { loadDurableModule, loadDurablePeerModule } from "./durable-loader.js";
15
+ import { DEFAULT_DURABLE_CAPABILITIES } from "../engine-capabilities.js";
15
16
  export class DurableAgentDriver extends BaseAgentDriver {
16
17
  id = "durable";
17
18
  name = "Pi Durable Agent";
@@ -24,6 +25,9 @@ export class DurableAgentDriver extends BaseAgentDriver {
24
25
  supportsAskUser: true,
25
26
  supportsSubagents: true,
26
27
  };
28
+ getEngineCapabilities() {
29
+ return DEFAULT_DURABLE_CAPABILITIES;
30
+ }
27
31
  dataDir;
28
32
  agentDir;
29
33
  currentModelId;
@@ -34,16 +38,50 @@ export class DurableAgentDriver extends BaseAgentDriver {
34
38
  storage = null;
35
39
  harness = null;
36
40
  backgroundContext = null;
41
+ models = null;
37
42
  initPromise = null;
38
43
  initError = null;
39
44
  currentConversationId = null;
40
45
  activeWatch = null;
41
46
  currentRunningConv = null;
47
+ currentThinkingLevel = "medium";
42
48
  constructor(cwd, opts) {
43
49
  super(cwd);
44
50
  this.dataDir = opts?.dataDir ?? process.cwd();
45
51
  this.agentDir = opts?.agentDir;
46
52
  }
53
+ setThinkingLevel(level) {
54
+ this.currentThinkingLevel = level;
55
+ // 动态应用到当前活动或持久会话,确保后续思考轮次即刻生效
56
+ if (this.currentRunningConv && typeof this.currentRunningConv.configure === "function") {
57
+ try {
58
+ void this.currentRunningConv.configure({ thinkingLevel: level }, this.backgroundContext).catch(() => { });
59
+ }
60
+ catch {
61
+ /* best effort */
62
+ }
63
+ }
64
+ else if (this.harness && this.currentConversationId) {
65
+ const numericId = Number(this.currentConversationId);
66
+ if (Number.isSafeInteger(numericId) && numericId > 0 && typeof this.harness.conversation === "function") {
67
+ void this.harness
68
+ .conversation(numericId, this.backgroundContext)
69
+ .then((conv) => {
70
+ if (conv && typeof conv.configure === "function") {
71
+ return conv.configure({ thinkingLevel: level }, this.backgroundContext);
72
+ }
73
+ })
74
+ .catch(() => { });
75
+ }
76
+ }
77
+ }
78
+ getSupportedThinkingLevels(modelId) {
79
+ return resolveDurableThinkingLevels(modelId || this.currentModelId, {
80
+ modelsContainer: this.models,
81
+ cachedModels: this.cachedModels,
82
+ agentDir: this.agentDir,
83
+ });
84
+ }
47
85
  /**
48
86
  * 初始化 Pi Durable 运行环境(按需异步单例)。
49
87
  */
@@ -68,6 +106,7 @@ export class DurableAgentDriver extends BaseAgentDriver {
68
106
  const { registry } = await setupDurableRegistry(this.cwd);
69
107
  // 5. 继承全局模型配置(读取 models.json、auth.json 并装配 Providers)
70
108
  const models = await setupDurableModels(this.agentDir);
109
+ this.models = models;
71
110
  // 6. 动态加载本地执行环境(支撑 read/write/edit/bash 等官方编码工具)
72
111
  const envModule = await loadDurableModule("env/node").catch(() => null);
73
112
  const envFactory = envModule?.NodeExecutionEnv
@@ -105,7 +144,12 @@ export class DurableAgentDriver extends BaseAgentDriver {
105
144
  if (this.harness && typeof this.harness.createConversation === "function") {
106
145
  try {
107
146
  const modelChoice = resolveDurableModelChoice(this.currentModelId, this.cachedModels, this.agentDir);
108
- const agentOpts = modelChoice ? { agent: { model: modelChoice } } : {};
147
+ const agentOpts = {
148
+ agent: {
149
+ ...(modelChoice ? { model: modelChoice } : {}),
150
+ thinkingLevel: this.currentThinkingLevel,
151
+ },
152
+ };
109
153
  const conv = await this.harness.createConversation({
110
154
  ownership: { kind: "ownerless" },
111
155
  ...agentOpts,
@@ -131,7 +175,13 @@ export class DurableAgentDriver extends BaseAgentDriver {
131
175
  this.harness &&
132
176
  typeof this.harness.conversation === "function") {
133
177
  try {
134
- await this.harness.conversation(numericId, this.backgroundContext);
178
+ const conv = await this.harness.conversation(numericId, this.backgroundContext);
179
+ if (conv && typeof conv.agent === "function") {
180
+ const agent = await conv.agent(this.backgroundContext).catch(() => null);
181
+ if (agent?.thinkingLevel) {
182
+ this.currentThinkingLevel = agent.thinkingLevel;
183
+ }
184
+ }
135
185
  }
136
186
  catch {
137
187
  /* fallback */
@@ -151,7 +201,12 @@ export class DurableAgentDriver extends BaseAgentDriver {
151
201
  const parentConv = await this.harness.conversation(numericId, this.backgroundContext);
152
202
  if (parentConv && typeof parentConv.fork === "function") {
153
203
  const modelChoice = resolveDurableModelChoice(this.currentModelId, this.cachedModels, this.agentDir);
154
- const agentOpts = modelChoice ? { agent: { model: modelChoice } } : {};
204
+ const agentOpts = {
205
+ agent: {
206
+ ...(modelChoice ? { model: modelChoice } : {}),
207
+ thinkingLevel: this.currentThinkingLevel,
208
+ },
209
+ };
155
210
  const forked = await parentConv.fork(atEntryId, {
156
211
  ownership: { kind: "ownerless" },
157
212
  ...agentOpts,
@@ -188,7 +243,12 @@ export class DurableAgentDriver extends BaseAgentDriver {
188
243
  try {
189
244
  // 获取当前活动会话或工作区根会话
190
245
  const modelChoice = resolveDurableModelChoice(this.currentModelId, this.cachedModels, this.agentDir);
191
- const agentOpts = modelChoice ? { agent: { model: modelChoice } } : undefined;
246
+ const agentOpts = {
247
+ agent: {
248
+ ...(modelChoice ? { model: modelChoice } : {}),
249
+ thinkingLevel: this.currentThinkingLevel,
250
+ },
251
+ };
192
252
  let targetConv = null;
193
253
  const numericId = this.currentConversationId ? Number(this.currentConversationId) : NaN;
194
254
  if (Number.isSafeInteger(numericId) &&
@@ -202,10 +262,13 @@ export class DurableAgentDriver extends BaseAgentDriver {
202
262
  }
203
263
  if (this.aborted)
204
264
  return;
205
- // 若指定了模型选择,确保目标会话已应用最新模型配置
206
- if (modelChoice && typeof targetConv.configure === "function") {
265
+ // 若指定了模型选择或思考强度,确保目标会话已应用最新配置
266
+ if (typeof targetConv.configure === "function") {
207
267
  try {
208
- await targetConv.configure({ model: modelChoice }, this.backgroundContext);
268
+ await targetConv.configure({
269
+ ...(modelChoice ? { model: modelChoice } : {}),
270
+ thinkingLevel: this.currentThinkingLevel,
271
+ }, this.backgroundContext);
209
272
  }
210
273
  catch {
211
274
  /* best effort */
@@ -448,7 +511,10 @@ export class DurableAgentDriver extends BaseAgentDriver {
448
511
  if (conv && typeof conv.configure === "function") {
449
512
  const choice = resolveDurableModelChoice(modelId, this.cachedModels, this.agentDir);
450
513
  if (choice) {
451
- await conv.configure({ model: choice }, this.backgroundContext);
514
+ await conv.configure({
515
+ model: choice,
516
+ thinkingLevel: this.currentThinkingLevel,
517
+ }, this.backgroundContext);
452
518
  }
453
519
  }
454
520
  }
@@ -3,20 +3,8 @@
3
3
  *
4
4
  * 统一委托给通用全局加载器,消除代码冗余。
5
5
  */
6
- import { dynamicImportGlobalPackage, probeGlobalPackage, resolvePackageRoot, resolvePackageEntryFile, } from "../global-loader.js";
6
+ import { dynamicImportGlobalPackage } from "../global-loader.js";
7
7
  const DURABLE_PKG = "@earendil-works/pi-durable";
8
- /**
9
- * 解析并定位 @earendil-works/pi-durable 包的物理安装根目录。
10
- */
11
- export function findDurablePackageRoot(forceRefresh = false) {
12
- return resolvePackageRoot(DURABLE_PKG, { refresh: forceRefresh });
13
- }
14
- /**
15
- * 探测 Pi Durable 引擎的安装元数据(包版本号与物理路径)。
16
- */
17
- export function probeDurableInstallation(forceRefresh = false) {
18
- return probeGlobalPackage(DURABLE_PKG, { refresh: forceRefresh });
19
- }
20
8
  /**
21
9
  * 动态加载 @earendil-works/pi-durable 核心模块或其子路径模块。
22
10
  * @param subpath 子路径标识,如 ""(主包)、"tools"、"storage/sqlite/node"、"storage/memory"
@@ -35,4 +23,3 @@ export async function loadDurablePeerModule(packageName, subpath = "") {
35
23
  return null;
36
24
  }
37
25
  }
38
- export { resolvePackageEntryFile };
@@ -281,3 +281,110 @@ export function resolveDurableModelChoice(modelId, fallbackList, agentDir) {
281
281
  modelId: trimmed,
282
282
  };
283
283
  }
284
+ /**
285
+ * 根据模型配置(reasoning 与 thinkingLevelMap)解析支持的思考强度档位。
286
+ */
287
+ export function calculateSupportedThinkingLevels(modelDef) {
288
+ if (!modelDef) {
289
+ return ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
290
+ }
291
+ if (modelDef.reasoning === false) {
292
+ return ["off"];
293
+ }
294
+ const allLevels = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
295
+ if (modelDef.thinkingLevelMap && typeof modelDef.thinkingLevelMap === "object") {
296
+ return allLevels.filter((lvl) => {
297
+ const mapped = modelDef.thinkingLevelMap?.[lvl];
298
+ if (mapped === null)
299
+ return false;
300
+ if (lvl === "xhigh" || lvl === "max")
301
+ return mapped !== undefined;
302
+ return true;
303
+ });
304
+ }
305
+ // 默认具备 reasoning 能力时支持 off, minimal, low, medium, high
306
+ return ["off", "minimal", "low", "medium", "high"];
307
+ }
308
+ /**
309
+ * 快速同步解析指定模型的思考能力(优先 models 容器,次之 models.json / models-store.json / cachedModels)。
310
+ */
311
+ export function resolveDurableThinkingLevels(modelId, options) {
312
+ if (!modelId || !modelId.trim() || modelId === "default") {
313
+ return ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
314
+ }
315
+ const choice = resolveDurableModelChoice(modelId, options?.cachedModels, options?.agentDir);
316
+ const provider = choice?.provider;
317
+ const bareModelId = choice?.modelId;
318
+ // 1. 尝试从已装配的 models 容器中取
319
+ if (options?.modelsContainer && typeof options.modelsContainer.getModel === "function" && provider && bareModelId) {
320
+ try {
321
+ const m = options.modelsContainer.getModel(provider, bareModelId);
322
+ if (m) {
323
+ return calculateSupportedThinkingLevels(m);
324
+ }
325
+ }
326
+ catch {
327
+ /* ignore */
328
+ }
329
+ }
330
+ // 2. 尝试从 models.json 中取
331
+ try {
332
+ const { providers } = readModelsJson(options?.agentDir);
333
+ if (provider && providers[provider]?.models && Array.isArray(providers[provider].models)) {
334
+ const list = providers[provider].models;
335
+ const found = list.find((m) => m.id === bareModelId);
336
+ if (found) {
337
+ return calculateSupportedThinkingLevels(found);
338
+ }
339
+ }
340
+ // 若按 provider 未匹配,遍历所有 provider 寻找裸模型 ID 匹配
341
+ for (const pConfig of Object.values(providers)) {
342
+ if (Array.isArray(pConfig?.models)) {
343
+ const found = pConfig.models.find((m) => m.id === bareModelId);
344
+ if (found) {
345
+ return calculateSupportedThinkingLevels(found);
346
+ }
347
+ }
348
+ }
349
+ }
350
+ catch {
351
+ /* ignore */
352
+ }
353
+ // 3. 尝试从 models-store.json 中取
354
+ try {
355
+ const userAgentDir = options?.agentDir || join(homedir(), ".pi", "agent");
356
+ const storePath = join(userAgentDir, "models-store.json");
357
+ if (existsSync(storePath)) {
358
+ const store = JSON.parse(readFileSync(storePath, "utf8"));
359
+ if (provider && Array.isArray(store[provider]?.models)) {
360
+ const found = store[provider].models.find((m) => m.id === bareModelId);
361
+ if (found) {
362
+ return calculateSupportedThinkingLevels(found);
363
+ }
364
+ }
365
+ // 若按 provider 未匹配,遍历 store 所有 provider 寻找裸模型 ID 匹配
366
+ for (const pData of Object.values(store)) {
367
+ if (Array.isArray(pData?.models)) {
368
+ const found = pData.models.find((m) => m.id === bareModelId);
369
+ if (found) {
370
+ return calculateSupportedThinkingLevels(found);
371
+ }
372
+ }
373
+ }
374
+ }
375
+ }
376
+ catch {
377
+ /* ignore */
378
+ }
379
+ // 4. 尝试从 cachedModels 中取
380
+ if (options?.cachedModels && options.cachedModels.length > 0) {
381
+ const found = options.cachedModels.find((m) => m.id === modelId ||
382
+ m.id.endsWith(`/${bareModelId}`) ||
383
+ (provider && m.provider === provider && m.id.endsWith(bareModelId)));
384
+ if (found && found.reasoning === false) {
385
+ return ["off"];
386
+ }
387
+ }
388
+ // 未明确识别或通用兜底
389
+ return ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
390
+ }
@@ -2,7 +2,3 @@
2
2
  * server/durable/index.ts — Pi Durable 独立智能体引擎模块统一出口。
3
3
  */
4
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";
@@ -34,20 +34,47 @@ const CACHE_TTL_MS = 5000;
34
34
  /** 远端 npm registry 查询缓存:5 分钟 */
35
35
  const REGISTRY_CACHE_TTL_MS = 5 * 60 * 1000;
36
36
  const registryCache = new Map();
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
- }));
37
+ /** 引擎状态原子字典:单一事实源,收敛 status / probedAt / updating 三元组,杜绝独立状态撕裂 */
38
+ const engineRegistry = new Map([
39
+ [
40
+ "pi",
41
+ {
42
+ status: { id: "pi", installed: true, packageName: ENGINE_PACKAGES.pi.packageName, version: VERSION },
43
+ probedAt: 0,
44
+ updating: false,
45
+ },
46
+ ],
47
+ [
48
+ "dsh",
49
+ {
50
+ status: { id: "dsh", installed: false, packageName: ENGINE_PACKAGES.dsh.packageName },
51
+ probedAt: 0,
52
+ updating: false,
53
+ },
54
+ ],
55
+ [
56
+ "claude",
57
+ {
58
+ status: { id: "claude", installed: false, packageName: ENGINE_PACKAGES.claude.packageName },
59
+ probedAt: 0,
60
+ updating: false,
61
+ },
62
+ ],
63
+ [
64
+ "durable",
65
+ {
66
+ status: { id: "durable", installed: false, packageName: ENGINE_PACKAGES.durable.packageName },
67
+ probedAt: 0,
68
+ updating: false,
69
+ },
70
+ ],
71
+ ]);
72
+ function toPublicStatus(entry) {
73
+ return {
74
+ ...entry.status,
75
+ ...(entry.updating ? { updating: true } : {}),
76
+ };
44
77
  }
45
- let cachedStatuses = [
46
- { id: "pi", installed: true, packageName: ENGINE_PACKAGES.pi.packageName, version: VERSION },
47
- { id: "dsh", installed: false, packageName: ENGINE_PACKAGES.dsh.packageName },
48
- { id: "claude", installed: false, packageName: ENGINE_PACKAGES.claude.packageName },
49
- { id: "durable", installed: false, packageName: ENGINE_PACKAGES.durable.packageName },
50
- ];
51
78
  /**
52
79
  * 查询全局包在 npm 远端的最新版本号(带 5 分钟缓存)。
53
80
  */
@@ -222,10 +249,9 @@ export async function probeDurable(force = false) {
222
249
  export async function probeEngine(id, force = false) {
223
250
  if (id === "pi")
224
251
  return probePi();
225
- if (!force && Date.now() - lastProbeAt < CACHE_TTL_MS) {
226
- const found = cachedStatuses.find((e) => e.id === id);
227
- if (found)
228
- return found;
252
+ const entry = engineRegistry.get(id);
253
+ if (!force && entry && entry.probedAt > 0 && Date.now() - entry.probedAt < CACHE_TTL_MS) {
254
+ return toPublicStatus(entry);
229
255
  }
230
256
  let result;
231
257
  if (id === "dsh") {
@@ -241,23 +267,23 @@ export async function probeEngine(id, force = false) {
241
267
  result = { id: id, installed: false };
242
268
  }
243
269
  await enrichWithUpdateInfo(result, force);
244
- // 更新单项缓存
245
- const idx = cachedStatuses.findIndex((e) => e.id === id);
246
- if (idx >= 0)
247
- cachedStatuses[idx] = result;
248
- else
249
- cachedStatuses.push(result);
250
- return {
251
- ...result,
252
- ...(updatingEngineIds.has(id) ? { updating: true } : {}),
270
+ const updatedEntry = {
271
+ status: result,
272
+ probedAt: Date.now(),
273
+ updating: entry?.updating ?? false,
253
274
  };
275
+ engineRegistry.set(id, updatedEntry);
276
+ return toPublicStatus(updatedEntry);
254
277
  }
255
278
  /**
256
279
  * 探测全部已知引擎并返回最新状态列表(带 TTL 缓存防抖)。
257
280
  */
258
281
  export async function probeAllEngines(force = false) {
259
- if (!force && Date.now() - lastProbeAt < CACHE_TTL_MS && cachedStatuses.length > 0) {
260
- return applyUpdatingFlag(cachedStatuses);
282
+ const now = Date.now();
283
+ const entries = Array.from(engineRegistry.values());
284
+ const allFresh = entries.every((e) => e.probedAt > 0 && now - e.probedAt < CACHE_TTL_MS);
285
+ if (!force && allFresh && entries.length > 0) {
286
+ return entries.map(toPublicStatus);
261
287
  }
262
288
  const [pi, dsh, claude, durable] = await Promise.all([probePi(), probeDsh(), probeClaude(), probeDurable()]);
263
289
  await Promise.all([
@@ -266,21 +292,29 @@ export async function probeAllEngines(force = false) {
266
292
  enrichWithUpdateInfo(claude, force),
267
293
  enrichWithUpdateInfo(durable, force),
268
294
  ]);
269
- cachedStatuses = [pi, dsh, claude, durable];
270
- lastProbeAt = Date.now();
271
- return applyUpdatingFlag(cachedStatuses);
295
+ const timestamp = Date.now();
296
+ const results = [pi, dsh, claude, durable];
297
+ for (const res of results) {
298
+ const existing = engineRegistry.get(res.id);
299
+ engineRegistry.set(res.id, {
300
+ status: res,
301
+ probedAt: timestamp,
302
+ updating: existing?.updating ?? false,
303
+ });
304
+ }
305
+ return Array.from(engineRegistry.values()).map(toPublicStatus);
272
306
  }
273
307
  /**
274
308
  * 同步获取当前缓存的引擎探测结果(握手帧或即时读取使用)。
275
309
  */
276
310
  export function getCachedEngineStatuses() {
277
- return applyUpdatingFlag(cachedStatuses);
311
+ return Array.from(engineRegistry.values()).map(toPublicStatus);
278
312
  }
279
313
  /**
280
314
  * 查询指定引擎是否正在执行后台更新子进程。
281
315
  */
282
316
  export function isEngineUpdating(engineId) {
283
- return updatingEngineIds.has(engineId);
317
+ return engineRegistry.get(engineId)?.updating ?? false;
284
318
  }
285
319
  /**
286
320
  * 在后台子进程中执行引擎全局包更新(npm i -g <pkg>@latest)。
@@ -291,10 +325,12 @@ export async function updateEngineBackground(engineId, options) {
291
325
  if (!meta || !meta.packageName) {
292
326
  return { ok: false, error: `不支持或未知的引擎「${engineId}」` };
293
327
  }
294
- if (updatingEngineIds.has(engineId)) {
328
+ const currentEntry = engineRegistry.get(engineId);
329
+ if (currentEntry?.updating) {
295
330
  return { ok: false, error: `引擎「${engineId}」正在后台更新中,请勿重复操作` };
296
331
  }
297
- updatingEngineIds.add(engineId);
332
+ if (currentEntry)
333
+ currentEntry.updating = true;
298
334
  const pkg = meta.packageName;
299
335
  const timeoutMs = Math.max(10_000, Number(options?.timeoutMs ?? 300_000));
300
336
  const isWin = process.platform === "win32";
@@ -367,7 +403,9 @@ export async function updateEngineBackground(engineId, options) {
367
403
  };
368
404
  }
369
405
  finally {
370
- updatingEngineIds.delete(engineId);
406
+ const finalEntry = engineRegistry.get(engineId);
407
+ if (finalEntry)
408
+ finalEntry.updating = false;
371
409
  }
372
410
  }
373
411
  /**
@@ -375,7 +413,8 @@ export async function updateEngineBackground(engineId, options) {
375
413
  */
376
414
  export function collectInstalledEngineTargets() {
377
415
  const out = [];
378
- for (const status of cachedStatuses) {
416
+ for (const entry of engineRegistry.values()) {
417
+ const status = entry.status;
379
418
  // pi-core 在 collectTargets 中已有独立专属条目(PI_CORE_PACKAGE),此处收纳其他已安装引擎全局包
380
419
  if (status.id !== "pi" && status.installed && status.packageName && status.version) {
381
420
  out.push({
@@ -70,6 +70,16 @@ function resolvePythonCmd() {
70
70
  const PYTHON_DRIVER_SCRIPT = `
71
71
  import sys, io, ast, json, traceback, os
72
72
 
73
+ # 跨平台编码对齐:Windows 默认代码页(如 CP936/GBK)读取 UTF-8 管道会导致多字节截断、
74
+ # 反斜杠被吞噬破坏 JSON 结构(报 Expecting ',' delimiter)或触发 UnicodeDecodeError。
75
+ # 强制标准流一律按 UTF-8 重配并附带容错替换策略,避免解码死锁。
76
+ if hasattr(sys.stdin, "reconfigure"):
77
+ sys.stdin.reconfigure(encoding="utf-8", errors="replace")
78
+ if hasattr(sys.stdout, "reconfigure"):
79
+ sys.stdout.reconfigure(encoding="utf-8", errors="backslashreplace")
80
+ if hasattr(sys.stderr, "reconfigure"):
81
+ sys.stderr.reconfigure(encoding="utf-8", errors="backslashreplace")
82
+
73
83
  WORKDIR = os.environ.get('PI_EVAL_WORKDIR', '')
74
84
  PROJECT_DIR = os.environ.get('PI_EVAL_PROJECT_DIR', '')
75
85
 
@@ -119,7 +129,7 @@ for line in sys.stdin:
119
129
  except Exception as e:
120
130
  resp = {'ok': False, 'stdout': '', 'stderr': '', 'result': None, 'error': traceback.format_exc()}
121
131
 
122
- sys.stdout.write('__PI_EVAL_RES__' + json.dumps(resp, ensure_ascii=False) + '\\n')
132
+ sys.stdout.write('__PI_EVAL_RES__' + json.dumps(resp, ensure_ascii=True) + '\\n')
123
133
  sys.stdout.flush()
124
134
  `;
125
135
  const NODE_DRIVER_SCRIPT = `
@@ -247,6 +257,19 @@ export function sanitizeEvalEnv(sourceEnv) {
247
257
  }
248
258
  return cleanEnv;
249
259
  }
260
+ /**
261
+ * 传输层 ASCII 安全序列化:
262
+ * 将所有非 ASCII 字符(> 0x7F,含中文、特殊符号与 Emoji 代理对)转义为标准 JSON \uXXXX 格式。
263
+ * 纯 7-bit ASCII 传输流在跨平台任何操作系统本地代码页(如 Windows CP936/GBK/Shift-JIS)下
264
+ * 绝不会发生反斜杠 0x5C 被多字节汉字首字节“吞噬”导致 JSON 结构损毁或崩溃的问题。
265
+ */
266
+ export function toAsciiJson(data) {
267
+ const raw = JSON.stringify(data);
268
+ if (!/[^\x00-\x7F]/.test(raw)) {
269
+ return raw;
270
+ }
271
+ return raw.replace(/[^\x00-\x7F]/g, (c) => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0"));
272
+ }
250
273
  /** 单个持久内核工作进程包装。 */
251
274
  class EvalKernel {
252
275
  language;
@@ -277,6 +300,8 @@ class EvalKernel {
277
300
  ...sanitizeEvalEnv(process.env),
278
301
  PI_EVAL_WORKDIR: this.workdir,
279
302
  PI_EVAL_PROJECT_DIR: this.cwd,
303
+ PYTHONUTF8: "1",
304
+ PYTHONIOENCODING: "utf-8",
280
305
  },
281
306
  };
282
307
  if (this.language === "py") {
@@ -284,7 +309,7 @@ class EvalKernel {
284
309
  if (!pyCmd) {
285
310
  throw new Error("Python executable not found in PATH. Please install Python or use language: 'js'.");
286
311
  }
287
- this.proc = spawn(pyCmd, ["-u", "-c", PYTHON_DRIVER_SCRIPT], spawnOpts);
312
+ this.proc = spawn(pyCmd, ["-X", "utf8", "-u", "-c", PYTHON_DRIVER_SCRIPT], spawnOpts);
288
313
  }
289
314
  else {
290
315
  // js / ts:独立 node -e 驱动,ts 时带 --experimental-strip-types 支持 TypeScript 原生剥离执行。
@@ -403,7 +428,7 @@ class EvalKernel {
403
428
  const item = this.queue.shift();
404
429
  this.current = item;
405
430
  try {
406
- this.proc.stdin.write(JSON.stringify(item.req) + "\n");
431
+ this.proc.stdin.write(toAsciiJson(item.req) + "\n");
407
432
  }
408
433
  catch (err) {
409
434
  this.current = null;
@@ -31,8 +31,14 @@ export function registerFileTransferRoutes(app, getCwd, temporaryRoot = tmpdir()
31
31
  const parsed = parseRemoteWorkspaceUri(cwd);
32
32
  if (!parsed)
33
33
  throw new Error("Invalid remote workspace");
34
- const trimmed = raw.trim();
35
- if (!trimmed) {
34
+ let trimmed = raw.trim();
35
+ if (isRemoteWorkspaceUri(trimmed)) {
36
+ const parsedRaw = parseRemoteWorkspaceUri(trimmed);
37
+ if (parsedRaw) {
38
+ trimmed = parsedRaw.remotePath;
39
+ }
40
+ }
41
+ if (!trimmed || trimmed === ".") {
36
42
  if (!allowRoot)
37
43
  throw new Error("Invalid path");
38
44
  return parsed.remotePath;
@@ -831,6 +831,7 @@ export class FilesService {
831
831
  kind: "text",
832
832
  lines: countLines(Buffer.from(office.text)),
833
833
  size: stat.size,
834
+ slides: office.slides,
834
835
  });
835
836
  return;
836
837
  }
@@ -1633,10 +1634,16 @@ export class FilesService {
1633
1634
  const parsed = parseRemoteWorkspaceUri(rawCwd);
1634
1635
  if (!parsed)
1635
1636
  return null;
1636
- const trimmed = (p || "").trim();
1637
+ let trimmed = (p || "").trim();
1637
1638
  if (trimmed === MACHINE_ROOT || trimmed === MACHINE_ROOT + "/")
1638
1639
  return null;
1639
- if (!trimmed) {
1640
+ if (isRemoteWorkspaceUri(trimmed)) {
1641
+ const parsedUri = parseRemoteWorkspaceUri(trimmed);
1642
+ if (parsedUri) {
1643
+ trimmed = parsedUri.remotePath;
1644
+ }
1645
+ }
1646
+ if (!trimmed || trimmed === ".") {
1640
1647
  if (!allowRoot)
1641
1648
  return null;
1642
1649
  return { abs: parsed.remotePath, rel: "", parentRel: "", absolute: false };
@@ -1839,6 +1846,7 @@ export class FilesService {
1839
1846
  kind: "text",
1840
1847
  lines: countLines(Buffer.from(office.text)),
1841
1848
  size: st.size,
1849
+ slides: office.slides,
1842
1850
  });
1843
1851
  return;
1844
1852
  }
@@ -1531,6 +1531,13 @@ export class GoalService {
1531
1531
  }
1532
1532
  conv.goal.phase = "idle";
1533
1533
  }
1534
+ /** 会话关闭/移除时(removeConversation)彻底终止目标循环并清理关联的执行者与向导。 */
1535
+ notifyConversationRemoved(conv) {
1536
+ this.notifyTakeover(conv);
1537
+ if (this.wizardOwnerId === conv.id) {
1538
+ void this.abortWizard();
1539
+ }
1540
+ }
1534
1541
  /** 读某会话累计用量(取不到返回 undefined;getSessionStats 会遍历转写,只在轮次边界调)。 */
1535
1542
  sessionUsage(session) {
1536
1543
  try {