pi-web-ui 0.114.2 → 0.115.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 (195) hide show
  1. package/CHANGELOG.md +55 -1
  2. package/bin/pi-web-ui.mjs +69 -7
  3. package/dist/server/agent-service-daemon.js +440 -32
  4. package/dist/server/agent-service.js +878 -383
  5. package/dist/server/canvas/canvas-dispatch.js +13 -1
  6. package/dist/server/client-state.js +25 -0
  7. package/dist/server/communicate-tool.js +2 -0
  8. package/dist/server/context-usage.js +105 -0
  9. package/dist/server/conversation-communication.js +14 -0
  10. package/dist/server/conversation-identity.js +27 -0
  11. package/dist/server/device-center/approval-summary.js +31 -0
  12. package/dist/server/device-center/bot-catalog.js +21 -7
  13. package/dist/server/device-center/bot-execution.js +72 -9
  14. package/dist/server/device-center/bot-presets.js +46 -0
  15. package/dist/server/device-center/collab-service.js +328 -10
  16. package/dist/server/device-center/collab-tool.js +738 -12
  17. package/dist/server/device-center/connector.js +359 -23
  18. package/dist/server/device-center/desktop-page.js +22 -16
  19. package/dist/server/device-center/device-integration.js +595 -0
  20. package/dist/server/device-center/execution-guides.js +32 -0
  21. package/dist/server/device-center/execution-instructions.js +19 -0
  22. package/dist/server/device-center/execution-settings.js +100 -0
  23. package/dist/server/device-center/execution-system-prompt.js +38 -0
  24. package/dist/server/device-center/execution-workspace.js +20 -0
  25. package/dist/server/device-center/executor.js +389 -40
  26. package/dist/server/device-center/file-sync-paths.js +171 -0
  27. package/dist/server/device-center/file-sync.js +180 -91
  28. package/dist/server/device-center/group-context-delta.js +37 -0
  29. package/dist/server/device-center/group-context-message.js +208 -0
  30. package/dist/server/device-center/group-context.js +109 -0
  31. package/dist/server/device-center/group-events.js +136 -0
  32. package/dist/server/device-center/group-plan-guard.js +138 -0
  33. package/dist/server/device-center/hub-conversations.js +178 -0
  34. package/dist/server/device-center/hub-deliveries.js +277 -0
  35. package/dist/server/device-center/hub-integration.js +451 -0
  36. package/dist/server/device-center/hub.js +1544 -80
  37. package/dist/server/device-center/human-interaction.js +232 -0
  38. package/dist/server/device-center/integration-errors.js +25 -0
  39. package/dist/server/device-center/local-hub.js +18 -0
  40. package/dist/server/device-center/local.js +356 -40
  41. package/dist/server/device-center/main.js +11 -1
  42. package/dist/server/device-center/path-portal.js +11 -3
  43. package/dist/server/device-center/relay.js +364 -35
  44. package/dist/server/device-center/report-metadata.js +66 -0
  45. package/dist/server/device-center/report-upload.js +63 -0
  46. package/dist/server/device-center/runtime.js +549 -41
  47. package/dist/server/device-center/store.js +66 -3
  48. package/dist/server/device-center/task-context-budget.js +161 -0
  49. package/dist/server/device-center/task-journal.js +385 -0
  50. package/dist/server/device-center/task-plan.js +33 -0
  51. package/dist/server/device-center/task-progress.js +141 -0
  52. package/dist/server/device-center/task-recovery.js +452 -0
  53. package/dist/server/device-center/task-report-outbox.js +216 -0
  54. package/dist/server/device-center/task-report.js +384 -0
  55. package/dist/server/device-center/task-scheduler.js +400 -0
  56. package/dist/server/device-center/task-state.js +333 -0
  57. package/dist/server/device-center/transfer-stream.js +1006 -0
  58. package/dist/server/device-center/transfers.js +815 -8
  59. package/dist/server/dispatch-domain-handlers.js +21 -3
  60. package/dist/server/dsh/dsh-agent-service.js +6 -0
  61. package/dist/server/goal-service.js +10 -5
  62. package/dist/server/index.js +89 -13
  63. package/dist/server/message-deletion.js +40 -0
  64. package/dist/server/message-window.js +9 -0
  65. package/dist/server/patch-executable-lookup.js +396 -0
  66. package/dist/server/payload-limits.js +2 -0
  67. package/dist/server/plugin-llm.js +100 -9
  68. package/dist/server/plugins.js +1 -0
  69. package/dist/server/preset-fields.js +24 -0
  70. package/dist/server/preset-share.js +2 -0
  71. package/dist/server/prompt-base-store.js +85 -0
  72. package/dist/server/prompt-composer.js +5 -2
  73. package/dist/server/protocol-version.js +1 -1
  74. package/dist/server/protocol.js +2 -2
  75. package/dist/server/remote-ssh-service.js +22 -9
  76. package/dist/server/resolve-global-sdk.js +2 -0
  77. package/dist/server/session-search.js +1 -1
  78. package/dist/server/settings-service.js +90 -39
  79. package/dist/server/skill-content-filler.js +29 -8
  80. package/dist/server/skill-tool.js +12 -3
  81. package/dist/server/subagent-helpers.js +4 -1
  82. package/dist/server/subagents.js +50 -36
  83. package/dist/server/tool-host-factories.js +1 -0
  84. package/dist/server/universal/universal-session.js +5 -0
  85. package/dist/server/webui-context.js +25 -5
  86. package/docs/README.md +94 -0
  87. package/docs/device-center.md +100 -12
  88. package/docs/dsh-engine.md +10 -10
  89. package/extensions/webui.ts +43 -1
  90. package/package.json +1 -1
  91. package/themes/aetheris.css +5 -0
  92. package/themes/ayu-light.css +6 -0
  93. package/themes/bases/flow-base.css +68 -68
  94. package/themes/catppuccin-latte.css +6 -0
  95. package/themes/catppuccin.css +6 -0
  96. package/themes/claude-code-dark.css +5 -0
  97. package/themes/codex.css +6 -0
  98. package/themes/cyberpunk.css +6 -0
  99. package/themes/dark-teal.css +6 -1
  100. package/themes/dazzle.css +6 -0
  101. package/themes/everforest-light.css +6 -0
  102. package/themes/flow-light.css +8 -1
  103. package/themes/flow.css +6 -1
  104. package/themes/geist.css +6 -0
  105. package/themes/gruvbox-light.css +6 -0
  106. package/themes/kanagawa-lotus.css +6 -0
  107. package/themes/md-preview.css +6 -0
  108. package/themes/mist.css +6 -0
  109. package/themes/nord.css +6 -0
  110. package/themes/one-dark.css +6 -0
  111. package/themes/paper.css +6 -0
  112. package/themes/rose-pine-dawn.css +6 -0
  113. package/themes/sakura.css +6 -0
  114. package/themes/solarized-light.css +6 -0
  115. package/themes/tokyo-night.css +6 -0
  116. package/themes/translucent.css +6 -0
  117. package/themes/transparent.css +6 -0
  118. package/themes/vs-code-dark.css +5 -0
  119. package/themes/wallpaper-flow.css +5 -1
  120. package/themes/wallpaper-obsidian.css +6 -0
  121. package/themes/white.css +6 -0
  122. package/themes/zhujian-dark.css +6 -1
  123. package/themes/zhujian.css +6 -1
  124. package/themes/zhupi-dark.css +6 -1
  125. package/themes/zhupi.css +6 -1
  126. package/web/dist/.build-assets.json +1 -1
  127. package/web/dist/assets/BgTasksModal-BYzPgmoq.js +1 -0
  128. package/web/dist/assets/BgTasksModal-ni0VTmAQ.js +1 -0
  129. package/web/dist/assets/{CanvasStudio-B3W6b_rA.js → CanvasStudio-BCUeEf25.js} +3 -3
  130. package/web/dist/assets/{CanvasStudio-Csv1Sj1-.js → CanvasStudio-DNmDNBod.js} +3 -3
  131. package/web/dist/assets/DeviceCenter-BcBhRgL6.js +3 -0
  132. package/web/dist/assets/DeviceCenter-CmL5FZmt.js +3 -0
  133. package/web/dist/assets/DeviceGroups-CLdpdnI7.js +1 -0
  134. package/web/dist/assets/DeviceGroups-CgBaDPrD.js +1 -0
  135. package/web/dist/assets/Dropdown-CGXD0DfT.js +1 -0
  136. package/web/dist/assets/FilePreview-B8iqnBjy.js +2 -0
  137. package/web/dist/assets/FilePreview-BqviZKCN.js +2 -0
  138. package/web/dist/assets/GlobalSearchModal-mevF-ySi.js +1 -0
  139. package/web/dist/assets/GlobalSearchModal-qL99FN_F.js +1 -0
  140. package/web/dist/assets/GroupConversation-B88Yy-lt.js +3 -0
  141. package/web/dist/assets/GroupConversation-BwP5NVOE.js +3 -0
  142. package/web/dist/assets/HintTip-LHwkS2jV.js +1 -0
  143. package/web/dist/assets/ModelConfigModal-Do3Fe3jH.js +2 -0
  144. package/web/dist/assets/PiSetupModal-DE5-gEtI.js +1 -0
  145. package/web/dist/assets/ProviderOAuthControls-6UMARucA.js +1 -0
  146. package/web/dist/assets/SCMPanel-Hi6QqC1Q.js +2 -0
  147. package/web/dist/assets/SCMPanel-ezY_ZtCu.js +2 -0
  148. package/web/dist/assets/SettingsModal-6HgeEsJ8.js +20 -0
  149. package/web/dist/assets/SettingsModal-CF-7MwqS.js +20 -0
  150. package/web/dist/assets/TerminalPanel-CTp_BZ4S.js +3 -0
  151. package/web/dist/assets/TerminalPanel-CkYxC-Gh.js +3 -0
  152. package/web/dist/assets/TuiOverlayModal-1cRLP8IF.js +1 -0
  153. package/web/dist/assets/TuiOverlayModal-2xlptqWX.js +1 -0
  154. package/web/dist/assets/app-globals-DZNa9v8u.js +325 -0
  155. package/web/dist/assets/canvas-client-Bye9nSFO.js +1 -0
  156. package/web/dist/assets/{desktop-YguLbrX1.js → desktop-kjBoE3Nu.js} +1 -1
  157. package/web/dist/assets/group-view-state-CGCzYF8k.js +1 -0
  158. package/web/dist/assets/index-CsFs_HMb.css +1 -0
  159. package/web/dist/assets/index-DHeeHS_l.js +85 -0
  160. package/web/dist/assets/index-DTZch8uz.js +85 -0
  161. package/web/dist/assets/plugin-host-C8mNgghx.js +1 -0
  162. package/web/dist/assets/remote-ssh-client-CeP3CLUW.js +1 -0
  163. package/web/dist/assets/theme-BXGpyTMh.js +1 -0
  164. package/web/dist/index.html +10 -9
  165. package/web/dist/sw.js +1 -1
  166. package/web/dist/assets/BgTasksModal-BIlQ89vr.js +0 -1
  167. package/web/dist/assets/BgTasksModal-Ck2sjlPM.js +0 -1
  168. package/web/dist/assets/DeviceCenter-BQdDcO8A.js +0 -3
  169. package/web/dist/assets/DeviceCenter-CHRKL0Vy.js +0 -3
  170. package/web/dist/assets/DeviceGroups-D2rogxEN.js +0 -1
  171. package/web/dist/assets/Dropdown-ZLS04O8p.js +0 -1
  172. package/web/dist/assets/FilePreview-B9xoU6ON.js +0 -2
  173. package/web/dist/assets/FilePreview-DUQpVZkH.js +0 -2
  174. package/web/dist/assets/GlobalSearchModal-BXEGvUZq.js +0 -1
  175. package/web/dist/assets/GlobalSearchModal-CnVPmfOI.js +0 -1
  176. package/web/dist/assets/GroupConversation-CyIpQzDd.js +0 -1
  177. package/web/dist/assets/GroupConversation-DgYV3uYS.js +0 -1
  178. package/web/dist/assets/ModelConfigModal-DDZccDYt.js +0 -2
  179. package/web/dist/assets/PiSetupModal-DHbqfx8T.js +0 -1
  180. package/web/dist/assets/ProviderOAuthControls-C-MK36Dk.js +0 -1
  181. package/web/dist/assets/SCMPanel-imYI2Ecw.js +0 -2
  182. package/web/dist/assets/SCMPanel-sVZcV7dR.js +0 -2
  183. package/web/dist/assets/SettingsModal-Xw1Yoi3_.js +0 -20
  184. package/web/dist/assets/SettingsModal-mb4e34-0.js +0 -20
  185. package/web/dist/assets/TerminalPanel-CLkJJvxg.js +0 -3
  186. package/web/dist/assets/TerminalPanel-DpcIellm.js +0 -3
  187. package/web/dist/assets/TuiOverlayModal-4-fFAZe7.js +0 -1
  188. package/web/dist/assets/TuiOverlayModal-DCu01lks.js +0 -1
  189. package/web/dist/assets/app-globals-DcyO0UPi.js +0 -1
  190. package/web/dist/assets/fi-DaSO0Q-m.js +0 -325
  191. package/web/dist/assets/index-Cdh3sibd.js +0 -85
  192. package/web/dist/assets/index-DDZMv6LO.css +0 -1
  193. package/web/dist/assets/index-DWw_SxRq.js +0 -85
  194. package/web/dist/assets/plugin-host-BRBg6zmQ.js +0 -1
  195. package/web/dist/assets/theme-DDl-Oy1b.js +0 -1
@@ -0,0 +1,85 @@
1
+ /**
2
+ * prompt-base-store — SYSTEM.md / APPEND_SYSTEM.md 原文(SDK override **之前**的
3
+ * base)的归属登记处,以及生产这两份 base 的 override 工厂。
4
+ *
5
+ * ## 为什么归到 loader 名下(issue #812)
6
+ *
7
+ * SDK 的 `systemPromptOverride` / `appendSystemPromptOverride` 是**回调**:它把
8
+ * 「本次 reload 发现的 base」推给宿主。若宿主把「最近一次看到的值」存成
9
+ * `AgentService` 字段(= 每个浏览器客户端一份),那份状态的生命周期就是**客户端**,
10
+ * 而真相的生命周期是 **session**(= 一个 cwd 的 loader):
11
+ *
12
+ * - 切项目 → 新会话的 base 是 `undefined`(没有 `.pi/SYSTEM.md`)→ 旧值没人清 →
13
+ * 上一个项目的系统提示词泄漏到本项目的设置预览与新建对话,只有偶然访问一个
14
+ * 含空白 SYSTEM.md 的项目才会「被修复」;
15
+ * - 过户 → 搬的是 session 本体,客户端级字段留在旧宿主身上,新宿主读不到真相。
16
+ *
17
+ * 所以归属必须跟 loader 走:**key = resourceLoader 对象**(session 持有它,过户时
18
+ * 跟着走;session 销毁后 WeakMap 自动回收,不需要清理钩子)。每次 reload 无条件
19
+ * 覆盖式写入(base 缺失即写空),「没有文件」永远是空记录——结构上不可能串账。
20
+ *
21
+ * ## 为什么是工厂
22
+ *
23
+ * 「观察到 base → 登记到 loader 名下 → 再决定返回什么给 SDK」是同一件事的三步,
24
+ * 拆到调用方(17k 行的 agent-service)里手写一遍,就等于允许有人只抄前两步——
25
+ * 那正是本 bug 的形态。这里把三步收成一个单元,调用方只提供「拿到 base 后返回
26
+ * 什么」(子代理模板替换等业务规则)。
27
+ *
28
+ * 注意登记的是 override **之前**的原文:子代理模板 replace 会把 base 整个换掉,
29
+ * 但 {{soul}} 仍要反映用户写的 SYSTEM.md,预览与 token 估算才对得上。
30
+ */
31
+ /** 空记录:没有 SYSTEM.md / APPEND_SYSTEM.md。共享常量避免每次分配。 */
32
+ const EMPTY = { system: "", append: [] };
33
+ /** key = resourceLoader 对象本身(见模块头注释:归属跟 session 走)。 */
34
+ const store = new WeakMap();
35
+ /** 登记某 loader 本次 reload 的 base(归一:undefined / null 一律记为空)。 */
36
+ function writeRecord(loader, record) {
37
+ if (!loader)
38
+ return;
39
+ store.set(loader, {
40
+ system: typeof record.system === "string" ? record.system : "",
41
+ append: Array.isArray(record.append) ? record.append.slice() : [],
42
+ });
43
+ }
44
+ /** 读某 loader 归属的 base。loader 缺失或无记录 → 空记录(= 内置默认提示词)。 */
45
+ export function readPromptBase(loader) {
46
+ if (!loader)
47
+ return EMPTY;
48
+ return store.get(loader) ?? EMPTY;
49
+ }
50
+ /**
51
+ * 直接登记(给不经过 override 的调用方/测试用)。**必须每次 reload 都调用**,
52
+ * 包括 base 为空时:覆盖式写入是「不跨会话串账」的唯一保证,任何「非空才写」
53
+ * 的写法都会重新引入 issue #812。
54
+ */
55
+ export function recordPromptBaseLoader(loader, record) {
56
+ writeRecord(loader, record);
57
+ }
58
+ /**
59
+ * 造一对 override:**先登记归属,再问调用方返回什么**。
60
+ *
61
+ * `handlers.system` / `handlers.append` 是可选的业务规则(缺省 = 原样返回,
62
+ * 即 TUI 语义:SYSTEM.md / APPEND_SYSTEM.md 直达 SDK)。
63
+ */
64
+ export function createPromptBaseObservers(handlers = {}) {
65
+ const observed = { system: "", append: [] };
66
+ let loader;
67
+ return {
68
+ systemPromptOverride: (base) => {
69
+ observed.system = typeof base === "string" ? base : "";
70
+ writeRecord(loader, observed);
71
+ return handlers.system ? handlers.system(base) : base;
72
+ },
73
+ appendSystemPromptOverride: (base) => {
74
+ observed.append = base.slice();
75
+ writeRecord(loader, observed);
76
+ return handlers.append ? handlers.append(base) : base;
77
+ },
78
+ bind: (next) => {
79
+ loader = next;
80
+ // override 首次重放发生在 loader 创建过程中(那时还没有句柄):这里补写一次,
81
+ // 之后的 reload 直接按 loader 写。
82
+ writeRecord(loader, observed);
83
+ },
84
+ };
85
+ }
@@ -256,8 +256,11 @@ export function buildToolsSchemaText(tools) {
256
256
  export function resolveSectionTexts(inputs) {
257
257
  const cwd = inputs.cwd.replace(/\\/g, "/");
258
258
  const lang = inputs.lang ?? "en";
259
- // soul:用户 SYSTEM.md 优先;无则按 lang 选内置默认(调用方自定义的 builtinSoul 原样保留)。
260
- let soul = inputs.systemPromptFile?.trim() ? inputs.systemPromptFile : inputs.builtinSoul;
259
+ // soul:用户 SYSTEM.md 优先(真值判定,与 SDK `if (customPrompt)` 同语义:
260
+ // 纯空白文件 = 空提示词,不是「没文件」);无则按 lang 选内置默认(调用方
261
+ // 自定义的 builtinSoul 原样保留)。
262
+ const soulSource = inputs.systemPromptFile;
263
+ let soul = soulSource ? soulSource : inputs.builtinSoul;
261
264
  if (lang === "zh" && soul === BUILTIN_SOUL)
262
265
  soul = BUILTIN_SOUL_ZH;
263
266
  else if (soul === BUILTIN_SOUL)
@@ -8,4 +8,4 @@
8
8
  * its own copy in web/src/protocol-version.ts; scripts/check-protocol-sync.mjs
9
9
  * verifies the two never drift.
10
10
  */
11
- export const PROTOCOL_VERSION = 39;
11
+ export const PROTOCOL_VERSION = 42;
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Wire protocol between the browser client and the pi-web-ui server.
3
- * Pure JSON over WebSocket. The web frontend mirrors these types in
4
- * web/src/types.ts (kept in sync by hand — types only, no shared runtime code).
3
+ * Pure JSON over WebSocket. The web frontend re-exports these types from
4
+ * web/src/types.ts (types only, no shared runtime code).
5
5
  */
6
6
  export {};
@@ -1367,25 +1367,38 @@ fi
1367
1367
  stream.destroy();
1368
1368
  };
1369
1369
  const abort = () => stop(signal?.reason ?? new Error("SFTP write aborted"));
1370
+ // ssh2's SFTP WriteStream calls `destroy()` from inside `_final`, so Writable never emits
1371
+ // `finish` (proved by instrumenting the real stream: only `close` arrives, after the SFTP
1372
+ // CLOSE acknowledgement). Completion is therefore decided by `close` _after_ `_final` ran:
1373
+ // `_final` only runs once every WRITE has been acknowledged, so `finalCalled` means flushed.
1374
+ const flushed = () => !!state?.finalCalled || stream.writableFinished;
1375
+ const settle = (error) => {
1376
+ if (settled)
1377
+ return;
1378
+ settled = true;
1379
+ clearTimeout(timer);
1380
+ signal?.removeEventListener("abort", abort);
1381
+ if (failed)
1382
+ reject(failure);
1383
+ else if (error)
1384
+ reject(error);
1385
+ else
1386
+ resolve();
1387
+ };
1370
1388
  // Keep this listener after close as ssh2 may still report a late error.
1371
1389
  stream.on("error", stop);
1390
+ // Recorded only: `close` stays the completion signal, since a bare `finish` does not prove
1391
+ // the SFTP CLOSE acknowledgement (durable flush) ever arrived.
1372
1392
  stream.on("finish", () => {
1373
1393
  finished = true;
1374
1394
  });
1375
1395
  stream.on("close", () => {
1376
- // ssh2 may close synchronously inside _final, before finish is emitted.
1377
1396
  queueMicrotask(() => {
1378
1397
  if (settled)
1379
1398
  return;
1380
- settled = true;
1381
- clearTimeout(timer);
1382
- signal?.removeEventListener("abort", abort);
1383
1399
  if (failed)
1384
- reject(failure);
1385
- else if (finished || stream.writableFinished)
1386
- resolve();
1387
- else
1388
- reject(new Error("SFTP write closed before finishing"));
1400
+ return settle();
1401
+ settle(finished || flushed() ? undefined : new Error("SFTP write closed before finishing"));
1389
1402
  });
1390
1403
  });
1391
1404
  signal?.addEventListener("abort", abort, { once: true });
@@ -26,6 +26,7 @@
26
26
  * 或前台启动时在 import 服务入口之前先 import 它)。
27
27
  */
28
28
  import { registerBashProcessPatch } from "./patch-bash-process.js";
29
+ import { registerExecutableLookupPatch } from "./patch-executable-lookup.js";
29
30
  import { existsSync, readFileSync } from "node:fs";
30
31
  import { registerHooks } from "node:module";
31
32
  import { dirname, join } from "node:path";
@@ -151,6 +152,7 @@ export function registerGlobalSdkPreference(mode = process.env.PI_WEB_SDK, fromF
151
152
  }
152
153
  // ---- 副作用:被 `--import` 加载时立刻生效 --------------------------------
153
154
  registerBashProcessPatch();
155
+ registerExecutableLookupPatch();
154
156
  const used = registerGlobalSdkPreference();
155
157
  if (used) {
156
158
  console.log(`[pi-web-ui] following a newer pi SDK on this machine: ${used.path} (v${used.version}; ` +
@@ -140,7 +140,7 @@ export function piSessionsRoot() {
140
140
  export function isInsideSessionsDir(agentDir, targetPath) {
141
141
  const fold = (p) => (process.platform === "win32" ? p.toLowerCase() : p);
142
142
  const abs = fold(resolve(targetPath));
143
- const roots = [fold(resolve(agentDir, "sessions"))];
143
+ const roots = [fold(resolve(agentDir, "sessions")), fold(resolve(agentDir, "bot-sessions"))];
144
144
  const extra = piSessionsRoot();
145
145
  if (extra)
146
146
  roots.push(fold(resolve(extra)));
@@ -9,7 +9,7 @@
9
9
  import { existsSync, readFileSync } from "node:fs";
10
10
  import { basename, dirname, join } from "node:path";
11
11
  import { fileURLToPath } from "node:url";
12
- import { extensionKey, isInternalExtension, normalizeBgCleanupMinutes, normalizeDisabledPluginTools, normalizeRetryMaxAttempts, normalizeKeepRecentMessages, normalizeSkillList, normalizeSkillsCatalogBudget, normalizeSkillsCatalogMaxDesc, normalizeToolWatchdogTimeoutMs, normalizeUiLayout, defaultSubagentAutoWakeMaxTurns, normalizeSubagentAutoWakeMaxTurns, settingsPresetToUi, } from "./client-state.js";
12
+ import { extensionKey, isInternalExtension, normalizeBgCleanupMinutes, normalizeDisabledPluginTools, normalizeRetryMaxAttempts, normalizeKeepRecentMessages, normalizeSkillList, normalizeSkillsCatalogBudget, normalizeSkillsCatalogMaxDesc, normalizeSkillsFullTextMaxBytes, normalizeSkillsMaxFileBytes, normalizeToolWatchdogTimeoutMs, normalizeUiLayout, defaultSubagentAutoWakeMaxTurns, normalizeSubagentAutoWakeMaxTurns, settingsPresetToUi, } from "./client-state.js";
13
13
  import { normalizeSoftCapByModel, normalizeSoftCapTokens } from "./soft-cap.js";
14
14
  import { findVisionModels, SYSTEM_PROMPT } from "./vision-bridge.js";
15
15
  import { COMMITMSG_SYSTEM_PROMPT } from "./scm-commitmsg.js";
@@ -30,6 +30,7 @@ export class SettingsService {
30
30
  knownExtensions = new Map();
31
31
  /** 流式中改了需要 reload 的设置 → agent_end 后延迟应用(防拆毁运行中 run)。 */
32
32
  pendingReload = false;
33
+ pendingRuntimeReloads = new Set();
33
34
  unsubscribeSettings;
34
35
  sharedVersion = 0;
35
36
  sharedQueue = Promise.resolve();
@@ -69,6 +70,7 @@ export class SettingsService {
69
70
  this.unsubscribeSettings?.();
70
71
  this.unsubscribeSettings = undefined;
71
72
  this.pendingReload = false;
73
+ this.pendingRuntimeReloads.clear();
72
74
  }
73
75
  /** Apply a durable commit without saving it again. Serialize reloads; ignore stale deliveries. */
74
76
  receiveSharedSettings(change) {
@@ -110,7 +112,7 @@ export class SettingsService {
110
112
  this.host.onGoalModeDisabled?.();
111
113
  if (changed("showForkedParentSessions"))
112
114
  this.host.onSessionsFilterChanged?.();
113
- this.push(false);
115
+ this.push();
114
116
  this.host.flushSnapshot();
115
117
  if (changed("promptMode", "customSystemPrompt", "promptTemplate", "promptOverrides", "promptDisabled", "disabledSkills", "disabledExtensions"))
116
118
  await this.applyRuntime();
@@ -150,15 +152,22 @@ export class SettingsService {
150
152
  }
151
153
  return false;
152
154
  }
153
- hasPendingReload() {
154
- return this.pendingReload;
155
+ hasPendingReload(runtimeTarget) {
156
+ return runtimeTarget ? this.pendingRuntimeReloads.has(runtimeTarget) : this.pendingReload;
155
157
  }
156
- setPendingReload(v) {
157
- this.pendingReload = v;
158
+ setPendingReload(v, runtimeTarget) {
159
+ if (runtimeTarget) {
160
+ if (v)
161
+ this.pendingRuntimeReloads.add(runtimeTarget);
162
+ else
163
+ this.pendingRuntimeReloads.delete(runtimeTarget);
164
+ }
165
+ else
166
+ this.pendingReload = v;
158
167
  }
159
- consumePendingReload() {
160
- const v = this.pendingReload;
161
- this.pendingReload = false;
168
+ consumePendingReload(runtimeTarget) {
169
+ const v = this.hasPendingReload(runtimeTarget);
170
+ this.setPendingReload(false, runtimeTarget);
162
171
  return v;
163
172
  }
164
173
  /** 判断某个 skill 名是否仍存在于磁盘任何来源(各类 Agent 项目区 / 全局 / 祖先 / npm 包等)。
@@ -219,14 +228,14 @@ export class SettingsService {
219
228
  }
220
229
  return false;
221
230
  }
222
- push(maintain = true) {
231
+ /** Discover disk resources and prune stale preferences only on explicit refresh. Never reloads. */
232
+ refreshResources() {
223
233
  if (this.disposed || this.host.isDisposed())
224
234
  return;
235
+ this.resetResourceCatalog();
225
236
  this.settings = this.host.stateStore.getSettings(this.host.clientId);
226
237
  this.presets = this.host.stateStore.getPresets(this.host.clientId);
227
238
  const disabledSkills = new Set(this.settings.disabledSkills);
228
- const reviewDisabledSkills = new Set(this.settings.reviewDisabledSkills);
229
- const disabledExts = new Set(this.settings.disabledExtensions);
230
239
  let loadedSkillNames = null;
231
240
  let loadedExtNames = null;
232
241
  try {
@@ -241,17 +250,12 @@ export class SettingsService {
241
250
  agentDir: this.host.agentDir(),
242
251
  });
243
252
  const diskSkills = this.host.filterDiskSkills?.(discoveredSkills) ?? discoveredSkills;
244
- // Prune entries that no longer exist on disk AND aren't disabled
245
- // (e.g. a skill/extension file was deleted). Disabled entries are
246
- // kept so they can be re-enabled even when filtered out of the loader.
247
- const keepSkills = new Set([
248
- ...loadedSkills.map((s) => s.name),
249
- ...diskSkills.map((s) => s.name),
250
- ...this.settings.disabledSkills,
251
- ]);
253
+ // Rebuild membership from loaded and discovered resources so deleted
254
+ // disabled entries cannot keep themselves alive through the cache.
255
+ const keepSkills = new Set([...loadedSkills.map((s) => s.name), ...diskSkills.map((s) => s.name)]);
252
256
  const keepExts = new Set([
253
257
  ...loadedExts.map((e) => extensionKey(e)),
254
- ...this.settings.disabledExtensions.filter((id) => !isInternalExtension({ path: id })),
258
+ ...this.settings.disabledExtensions.filter((id) => !isInternalExtension({ path: id }) && this.extensionStillOnDisk(id)),
255
259
  ]);
256
260
  // eslint-disable-next-line unicorn/no-useless-spread -- snapshot: handlers may unsubscribe mid-emit
257
261
  for (const name of [...this.knownSkills.keys()]) {
@@ -292,11 +296,6 @@ export class SettingsService {
292
296
  enabled: true,
293
297
  });
294
298
  }
295
- // 若发现磁盘新增了 loader 尚未加载的技能,触发会话后台异步 reload 以刷新提示词和技能工具
296
- const hasUnloadedDiskSkills = diskSkills.some((ds) => !loadedSkillNames.has(ds.name));
297
- if (maintain && hasUnloadedDiskSkills && !this.host.isStreaming()) {
298
- void this.applyRuntime();
299
- }
300
299
  }
301
300
  catch {
302
301
  // Session not ready yet — keep whatever we already know.
@@ -305,7 +304,7 @@ export class SettingsService {
305
304
  // disabledSkills / reviewDisabledSkills 持久化记录中移除——否则每次
306
305
  // 推送都会把已删除的 skill 以灰条形式永恒地补回面板(“关闭过的
307
306
  // skill 被一直记录”)。session 未就绪时保守跳过。
308
- if (maintain && loadedSkillNames !== null) {
307
+ if (loadedSkillNames !== null) {
309
308
  const stale = [
310
309
  ...new Set([
311
310
  ...this.settings.disabledSkills,
@@ -330,7 +329,7 @@ export class SettingsService {
330
329
  // disabledExtensions 同理:已卸载(loader 里没有、磁盘/配置里也没有)的扩展
331
330
  // 从禁用记录里剔除并持久化 —— 否则卸载过的扩展以“已禁用”灰条永生(issue #192)。
332
331
  // loadedExtNames 非 null 即 session 就绪;取不到(catch 分支)时保守跳过。
333
- if (maintain && loadedExtNames !== null) {
332
+ if (loadedExtNames !== null) {
334
333
  const staleExts = this.settings.disabledExtensions.filter((id) => isInternalExtension({ path: id }) || (!loadedExtNames.has(id) && !this.extensionStillOnDisk(id)));
335
334
  if (staleExts.length > 0) {
336
335
  this.settings.disabledExtensions = this.settings.disabledExtensions.filter((n) => !staleExts.includes(n));
@@ -362,6 +361,50 @@ export class SettingsService {
362
361
  });
363
362
  }
364
363
  }
364
+ this.push();
365
+ }
366
+ catalogCwd;
367
+ resetResourceCatalog() {
368
+ const cwd = this.host.cwd();
369
+ if (cwd === this.catalogCwd)
370
+ return;
371
+ this.catalogCwd = cwd;
372
+ this.knownSkills.clear();
373
+ this.knownExtensions.clear();
374
+ }
375
+ /** Publish persisted preferences and the current in-memory resource catalog. No discovery, writes or reloads. */
376
+ push() {
377
+ if (this.disposed || this.host.isDisposed())
378
+ return;
379
+ this.resetResourceCatalog();
380
+ this.settings = this.host.stateStore.getSettings(this.host.clientId);
381
+ this.presets = this.host.stateStore.getPresets(this.host.clientId);
382
+ const disabledSkills = new Set(this.settings.disabledSkills);
383
+ const reviewDisabledSkills = new Set(this.settings.reviewDisabledSkills);
384
+ const disabledExts = new Set(this.settings.disabledExtensions);
385
+ try {
386
+ const loader = this.host.getSession().resourceLoader;
387
+ for (const skill of loader.getSkills().skills) {
388
+ this.knownSkills.set(skill.name, { name: skill.name, description: skill.description, enabled: true });
389
+ }
390
+ for (const extension of loader.getExtensions().extensions) {
391
+ if (isInternalExtension(extension))
392
+ continue;
393
+ const id = extensionKey(extension);
394
+ const path = extension.sourceInfo?.path ?? extension.path;
395
+ this.knownExtensions.set(id, {
396
+ id,
397
+ name: extension.sourceInfo?.origin === "package" && extension.sourceInfo.source
398
+ ? extension.sourceInfo.source
399
+ : basename(path),
400
+ path,
401
+ enabled: true,
402
+ });
403
+ }
404
+ }
405
+ catch {
406
+ // Session initialization may still be in progress.
407
+ }
365
408
  const skills = [...this.knownSkills.values()]
366
409
  .map((s) => ({ ...s, enabled: !disabledSkills.has(s.name) }))
367
410
  .sort((a, b) => a.name.localeCompare(b.name));
@@ -438,6 +481,8 @@ export class SettingsService {
438
481
  skillsCatalogMaxDesc: this.settings.skillsCatalogMaxDesc,
439
482
  skillsCatalogShowLocation: this.settings.skillsCatalogShowLocation,
440
483
  skillsCatalogBudget: this.settings.skillsCatalogBudget,
484
+ skillsMaxFileBytes: this.settings.skillsMaxFileBytes,
485
+ skillsFullTextMaxBytes: this.settings.skillsFullTextMaxBytes,
441
486
  // The composed system prompt actually in effect (read-only view).
442
487
  effectiveSystemPrompt: promptSnap.full,
443
488
  // 每个来源未覆盖时的默认(自动)内容(「各来源」行预览用)。
@@ -713,6 +758,12 @@ export class SettingsService {
713
758
  if (partial.skillsCatalogBudget !== undefined) {
714
759
  next.skillsCatalogBudget = normalizeSkillsCatalogBudget(partial.skillsCatalogBudget);
715
760
  }
761
+ if (partial.skillsMaxFileBytes !== undefined) {
762
+ next.skillsMaxFileBytes = normalizeSkillsMaxFileBytes(partial.skillsMaxFileBytes);
763
+ }
764
+ if (partial.skillsFullTextMaxBytes !== undefined) {
765
+ next.skillsFullTextMaxBytes = normalizeSkillsFullTextMaxBytes(partial.skillsFullTextMaxBytes);
766
+ }
716
767
  for (const key of ["chatUploadMaxMb", "workspaceUploadMaxMb", "folderUploadMaxMb"]) {
717
768
  if (partial[key] !== undefined)
718
769
  next[key] = partial[key];
@@ -880,7 +931,7 @@ export class SettingsService {
880
931
  return { ...s, name };
881
932
  }
882
933
  /** Replace the current settings with the named preset and apply it. */
883
- async applyPreset(name) {
934
+ async applyPreset(name, runtimeTarget) {
884
935
  this.settings = this.current;
885
936
  this.presets = this.host.stateStore.getPresets(this.host.clientId);
886
937
  const p = this.presets.find((x) => x.name === name);
@@ -936,7 +987,7 @@ export class SettingsService {
936
987
  if ((this.settings.showForkedParentSessions ?? false) !== prevShowForked) {
937
988
  this.host.onSessionsFilterChanged?.();
938
989
  }
939
- await this.applyRuntime(true);
990
+ await this.applyRuntime(true, runtimeTarget);
940
991
  }
941
992
  /** Remove a named preset. */
942
993
  async deletePreset(name) {
@@ -1122,11 +1173,11 @@ export class SettingsService {
1122
1173
  * overrides read this.settings at call time, so a reload re-applies them.
1123
1174
  * Reloading mid-stream would tear down the in-flight run — defer instead.
1124
1175
  */
1125
- async applyRuntime(throwOnError = false) {
1176
+ async applyRuntime(throwOnError = false, runtimeTarget) {
1126
1177
  if (this.disposed || this.host.isDisposed())
1127
1178
  return;
1128
- if (this.host.isStreaming()) {
1129
- this.pendingReload = true;
1179
+ if ((runtimeTarget ?? this.host).isStreaming()) {
1180
+ this.setPendingReload(true, runtimeTarget);
1130
1181
  this.host.emit({
1131
1182
  type: "notice",
1132
1183
  level: "info",
@@ -1135,14 +1186,14 @@ export class SettingsService {
1135
1186
  });
1136
1187
  return;
1137
1188
  }
1138
- await this.applyReload(throwOnError);
1189
+ await this.applyReload(throwOnError, runtimeTarget);
1139
1190
  }
1140
1191
  /** session.reload() + refresh the slash-command catalog + push state. */
1141
- async applyReload(throwOnError = false) {
1192
+ async applyReload(throwOnError = false, runtimeTarget) {
1142
1193
  if (this.disposed || this.host.isDisposed())
1143
1194
  return;
1144
- if (this.host.isStreaming()) {
1145
- this.pendingReload = true;
1195
+ if ((runtimeTarget ?? this.host).isStreaming()) {
1196
+ this.setPendingReload(true, runtimeTarget);
1146
1197
  this.host.emit({
1147
1198
  type: "notice",
1148
1199
  level: "info",
@@ -1152,10 +1203,10 @@ export class SettingsService {
1152
1203
  return;
1153
1204
  }
1154
1205
  try {
1155
- await this.host.reloadSession();
1206
+ await (runtimeTarget ?? this.host).reloadSession();
1156
1207
  if (this.disposed || this.host.isDisposed())
1157
1208
  return;
1158
- this.push(false);
1209
+ this.refreshResources();
1159
1210
  this.host.flushSnapshot();
1160
1211
  this.host.emit({ type: "notice", level: "info", text: "设置已应用", textEn: "Settings applied" });
1161
1212
  }
@@ -2,29 +2,50 @@
2
2
  * skill-content-filler — 技能全文注入({{skills}} 全文模式)内容填充器。
3
3
  *
4
4
  * 负责读取名单里技能的文件正文。
5
- * 单文件 8KB、总量 32KB 封顶,失败/超限/不在名单回落名录(无 content)。
5
+ * 单文件上限(默认 8KB)与总量预算(默认 32KB)都由调用方传入,缺省即历史硬编码值
6
+ * (设置项 skillsMaxFileBytes / skillsFullTextMaxBytes,见 issue #819);
7
+ * 失败/超限/不在名单回落名录(无 content)。
6
8
  * 名单为空时零开销:原样返回,不碰磁盘。
7
9
  *
10
+ * 预算口径是 **UTF-8 字节**:注入的是文本,模型按 token 付费,而字节数才是文件大小
11
+ * 与上下文占用的共同尺度。以前按 `raw.length`(JavaScript 字符数)扣预算,同样的
12
+ * 中文技能会被低估约 3 倍,总量可以冲出上限。
13
+ *
8
14
  * 从 agent-service.ts 抽出为独立模块。
9
15
  */
10
16
  import { readFileSync, statSync } from "node:fs";
11
17
  import { decodeText } from "./text-sniff.js";
12
- import { normalizeSkillList } from "./client-state.js";
13
- export function fillSkillContents(skills, skillsFullTextConfig) {
18
+ import { DEFAULT_SKILLS_FULL_TEXT_MAX_BYTES, DEFAULT_SKILLS_MAX_FILE_BYTES, normalizeSkillList, normalizeSkillsFullTextMaxBytes, normalizeSkillsMaxFileBytes, } from "./client-state.js";
19
+ export function fillSkillContents(skills, skillsFullTextConfig, limits = {}) {
14
20
  const wanted = new Set(normalizeSkillList(skillsFullTextConfig));
15
21
  if (wanted.size === 0)
16
22
  return skills;
17
- let budget = 32 * 1024;
23
+ const maxFile = limits.maxFileBytes === undefined
24
+ ? DEFAULT_SKILLS_MAX_FILE_BYTES
25
+ : normalizeSkillsMaxFileBytes(limits.maxFileBytes);
26
+ const maxTotal = limits.maxTotalBytes === undefined
27
+ ? DEFAULT_SKILLS_FULL_TEXT_MAX_BYTES
28
+ : normalizeSkillsFullTextMaxBytes(limits.maxTotalBytes);
29
+ // 0 = 显式不设限:用 Infinity 让下面的预算判断保持单一路径。
30
+ let budget = maxTotal > 0 ? maxTotal : Number.POSITIVE_INFINITY;
18
31
  return skills.map((s) => {
19
32
  if (!wanted.has(s.name) || !s.filePath || budget <= 0)
20
33
  return s;
21
34
  try {
22
35
  const st = statSync(s.filePath);
23
- if (!st.isFile() || st.size <= 0 || st.size > 8192)
36
+ if (!st.isFile() || st.size <= 0)
37
+ return s;
38
+ if (maxFile > 0 && st.size > maxFile)
39
+ return s;
40
+ const room = Math.min(st.size, budget);
41
+ const slice = readFileSync(s.filePath).subarray(0, room);
42
+ // 按预算截断时末尾可能是半个多字节字符,解码成 U+FFFD —— 丢掉它,别把乱码塞进提示词。
43
+ const text = decodeText(slice);
44
+ const raw = (room < st.size ? text.replace(/\uFFFD+$/u, "") : text).trim();
45
+ if (!raw)
24
46
  return s;
25
- const raw = decodeText(readFileSync(s.filePath).subarray(0, Math.min(st.size, budget))).trim();
26
- budget -= raw.length;
27
- return raw ? { ...s, content: raw } : s;
47
+ budget -= Buffer.byteLength(raw, "utf8");
48
+ return { ...s, content: raw };
28
49
  }
29
50
  catch {
30
51
  return s;
@@ -23,8 +23,15 @@ import { Type } from "typebox";
23
23
  import { pick } from "./i18n.js";
24
24
  import { SKILL_TOOL_NAME } from "./tool-manager.js";
25
25
  import { decodeText } from "./text-sniff.js";
26
- /** 单文件正文上限(与 agent-service fillSkillContents 同口径:8KB)。 */
26
+ /** 单文件正文上限的出厂默认(= 设置项 skillsMaxFileBytes 的默认值,8KB)。 */
27
27
  export const SKILL_TOOL_FILE_CAP = 8192;
28
+ /** 实际生效的单文件上限:非负整数,非法/未设置回退出厂默认。0 = 不设单文件上限。 */
29
+ function effectiveFileCap(host) {
30
+ const raw = host.maxFileBytes?.();
31
+ if (typeof raw === "number" && Number.isFinite(raw) && raw >= 0)
32
+ return Math.floor(raw);
33
+ return SKILL_TOOL_FILE_CAP;
34
+ }
28
35
  /** 精确名匹配(大小写敏感,与 skillsFullText 名单语义一致)。 */
29
36
  export function findSkill(skills, name) {
30
37
  const n = name.trim();
@@ -127,8 +134,10 @@ export function makeSkillTool(host, lang) {
127
134
  }
128
135
  try {
129
136
  const st = statSync(found.filePath);
130
- const kb = SKILL_TOOL_FILE_CAP / 1024;
131
- if (!st.isFile() || st.size <= 0 || st.size > SKILL_TOOL_FILE_CAP) {
137
+ const cap = effectiveFileCap(host);
138
+ // 0 = 不设单文件上限(设置项显式打开);否则超限回落可读错误,不截断正文。
139
+ const kb = Math.max(1, Math.round(cap / 1024));
140
+ if (!st.isFile() || st.size <= 0 || (cap > 0 && st.size > cap)) {
132
141
  return text(pick(L, `技能 ${name} 的文件不可读(不存在/超 ${kb}KB 上限)。`, `Skill ${name} file unreadable (missing or over the ${kb}KB cap).`, "skill.file.unreadable", { name, kb }));
133
142
  }
134
143
  const body = decodeText(readFileSync(found.filePath).subarray(0, st.size)).trim();
@@ -1,4 +1,5 @@
1
1
  import { SUBAGENT_PROMPT_SNAPSHOT_CAP } from "./agent-formatters.js";
2
+ import { conversationIdentity, parentConversationIdentity, conversationParent } from "./conversation-identity.js";
2
3
  /** 子代理是否处于活跃(流式运行中或首轮投递启动中)状态。
3
4
  * #589:名额与可见性解耦——仅活跃(非终态)子代理占用 MAX_SUBAGENTS 并发名额;
4
5
  * 已结束(done / canceled / error)的子代理保留在左栏供用户审阅追溯,不再占名额。 */
@@ -96,6 +97,8 @@ export function toSubagentSnapshot(conv) {
96
97
  const modelKey = m ? `${m.provider}/${m.id}` : (conv.subagentTemplate?.model ?? undefined);
97
98
  return {
98
99
  convId: conv.id,
100
+ executionId: conversationIdentity(conv),
101
+ parentExecutionId: parentConversationIdentity(conv),
99
102
  type: conv.subagentType ?? "general",
100
103
  title: conv.title,
101
104
  prompt: fullPrompt.length > SUBAGENT_PROMPT_SNAPSHOT_CAP
@@ -110,7 +113,7 @@ export function toSubagentSnapshot(conv) {
110
113
  model: modelKey,
111
114
  thinkingLevel,
112
115
  output: conv.session.getLastAssistantText() ?? "",
113
- parentId: conv.parentId,
116
+ parentId: conversationParent(conv)?.id,
114
117
  persisted: isPersisted,
115
118
  handoffTo: conv.peerHandoffTo ? [...conv.peerHandoffTo] : undefined,
116
119
  handoffFrom: conv.peerHandoffFrom ? [...conv.peerHandoffFrom] : undefined,