pi-web-ui 0.113.1 → 0.114.1

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 (280) hide show
  1. package/CHANGELOG.md +71 -1
  2. package/README.md +187 -316
  3. package/README.zh-CN.md +227 -299
  4. package/README.zh-TW.md +227 -299
  5. package/bin/device-hub-cli.mjs +577 -0
  6. package/bin/frp-manager.mjs +1573 -1573
  7. package/bin/pi-device-hub.mjs +9 -0
  8. package/bin/pi-web-ui.mjs +4081 -4041
  9. package/deploy/nginx-subpath.conf +100 -100
  10. package/deploy/pi-web-ui.service +36 -36
  11. package/dist/server/agent-service-daemon.js +102 -24
  12. package/dist/server/agent-service.js +2419 -1174
  13. package/dist/server/approval-rules.js +29 -3
  14. package/dist/server/ask-user-question-tool.js +8 -8
  15. package/dist/server/atomic-file.js +35 -14
  16. package/dist/server/attachment-store.js +71 -35
  17. package/dist/server/attachments.js +69 -13
  18. package/dist/server/canvas/canvas-agent-tool.js +68 -18
  19. package/dist/server/canvas/canvas-cards.js +1 -1
  20. package/dist/server/canvas/canvas-dispatch.js +61 -20
  21. package/dist/server/canvas/canvas-orchestrator.js +519 -202
  22. package/dist/server/canvas/canvas-scheduled-task.js +45 -0
  23. package/dist/server/canvas/canvas-scheduler.js +99 -0
  24. package/dist/server/canvas/canvas-store.js +107 -54
  25. package/dist/server/canvas/canvas-validation.js +131 -0
  26. package/dist/server/canvas/canvas-workspace.js +284 -0
  27. package/dist/server/client-id-utils.js +8 -0
  28. package/dist/server/client-state.js +110 -24
  29. package/dist/server/communicate-tool.js +76 -0
  30. package/dist/server/compact-context-tool.js +2 -3
  31. package/dist/server/compaction-instructions.js +75 -0
  32. package/dist/server/compaction-markers.js +7 -2
  33. package/dist/server/compaction-state.js +84 -0
  34. package/dist/server/composer-drafts.js +43 -40
  35. package/dist/server/context-evidence.js +346 -0
  36. package/dist/server/conversation-communication.js +368 -0
  37. package/dist/server/conversation-read-tool.js +3 -4
  38. package/dist/server/conversation-tool-names.js +14 -0
  39. package/dist/server/conversation-tool.js +57 -0
  40. package/dist/server/delegate-mode.js +17 -4
  41. package/dist/server/device-center/bot-catalog.js +88 -0
  42. package/dist/server/device-center/bot-execution.js +106 -0
  43. package/dist/server/device-center/bots.js +170 -0
  44. package/dist/server/device-center/collab-service.js +153 -0
  45. package/dist/server/device-center/collab-tool.js +184 -0
  46. package/dist/server/device-center/connector.js +351 -0
  47. package/dist/server/device-center/desktop-linux.js +372 -0
  48. package/dist/server/device-center/desktop-native.js +413 -0
  49. package/dist/server/device-center/desktop-page.js +232 -0
  50. package/dist/server/device-center/desktop-setup.js +30 -0
  51. package/dist/server/device-center/desktop.js +387 -0
  52. package/dist/server/device-center/device-portals.js +241 -0
  53. package/dist/server/device-center/execution-failure.js +70 -0
  54. package/dist/server/device-center/executor.js +371 -0
  55. package/dist/server/device-center/file-sync.js +493 -0
  56. package/dist/server/device-center/hub-auth.js +69 -0
  57. package/dist/server/device-center/hub-page.js +68 -0
  58. package/dist/server/device-center/hub-setup.js +214 -0
  59. package/dist/server/device-center/hub.js +830 -0
  60. package/dist/server/device-center/local-hub.js +92 -0
  61. package/dist/server/device-center/local.js +529 -0
  62. package/dist/server/device-center/main.js +118 -0
  63. package/dist/server/device-center/native-desktop/macos.js +192 -0
  64. package/dist/server/device-center/native-desktop/windows.js +118 -0
  65. package/dist/server/device-center/path-portal.js +120 -0
  66. package/dist/server/device-center/relay.js +996 -0
  67. package/dist/server/device-center/runtime.js +253 -0
  68. package/dist/server/device-center/store.js +122 -0
  69. package/dist/server/device-center/task-error.js +14 -0
  70. package/dist/server/device-center/transfers.js +293 -0
  71. package/dist/server/device-center/workspaces.js +45 -0
  72. package/dist/server/dispatch-domain-handlers.js +84 -27
  73. package/dist/server/dsh/dsh-agent-service.js +282 -159
  74. package/dist/server/dsh/dsh-client.js +12 -2
  75. package/dist/server/dsh/runtime/cordis.yml +1 -1
  76. package/dist/server/dsh/runtime/custom-prompt.mjs +33 -33
  77. package/dist/server/dsh/runtime/goal-rpc.mjs +1309 -1309
  78. package/dist/server/dsh/runtime/launcher.mjs +235 -235
  79. package/dist/server/dsh/runtime/override.patch.yml +89 -89
  80. package/dist/server/dsh/runtime/runtime-root.mjs +405 -405
  81. package/dist/server/durable/durable-agent-service.js +1 -1
  82. package/dist/server/engine-probe.js +36 -6
  83. package/dist/server/eval-tool.js +135 -135
  84. package/dist/server/evidence-tool-hooks.js +49 -0
  85. package/dist/server/file-save.js +95 -0
  86. package/dist/server/file-transfer-routes.js +97 -47
  87. package/dist/server/files-service.js +38 -26
  88. package/dist/server/global-loader.js +40 -2
  89. package/dist/server/goal-review-gate.js +16 -6
  90. package/dist/server/goal-service.js +54 -30
  91. package/dist/server/http-proxy.js +120 -0
  92. package/dist/server/index.js +285 -255
  93. package/dist/server/load-timing.js +31 -0
  94. package/dist/server/mcp-bridge.js +219 -94
  95. package/dist/server/mcp-hot-reload.js +31 -5
  96. package/dist/server/mcp-manager.js +192 -93
  97. package/dist/server/mcp-oauth-login.js +169 -0
  98. package/dist/server/mcp-oauth-ui.js +137 -0
  99. package/dist/server/mcp-oauth.js +395 -0
  100. package/dist/server/mcp-project-runtime.js +207 -0
  101. package/dist/server/message-window.js +74 -21
  102. package/dist/server/net-guard.js +122 -20
  103. package/dist/server/patch-bash-process.js +125 -0
  104. package/dist/server/patch-tool.js +9 -9
  105. package/dist/server/patch-turn-end-boundary.js +3 -3
  106. package/dist/server/payload-limits.js +17 -0
  107. package/dist/server/pending-question.js +82 -0
  108. package/dist/server/persona-chain.js +8 -8
  109. package/dist/server/plan-mode.js +338 -137
  110. package/dist/server/plugin-assets.js +8 -4
  111. package/dist/server/plugin-chat-attachments.js +48 -0
  112. package/dist/server/plugin-facilities.js +67 -220
  113. package/dist/server/plugin-installer.js +2 -1
  114. package/dist/server/plugin-removal.js +49 -0
  115. package/dist/server/plugin-secrets.js +179 -0
  116. package/dist/server/plugins.js +288 -94
  117. package/dist/server/preset-fields.js +56 -0
  118. package/dist/server/preset-plugin-dependencies.js +57 -0
  119. package/dist/server/preset-share.js +113 -72
  120. package/dist/server/prompt-templates.js +106 -0
  121. package/dist/server/protocol-version.js +1 -1
  122. package/dist/server/queue-modes.js +10 -0
  123. package/dist/server/remote-ssh-service.js +199 -106
  124. package/dist/server/request-context.js +164 -0
  125. package/dist/server/resolve-global-sdk.js +2 -0
  126. package/dist/server/sandbox-data.js +655 -0
  127. package/dist/server/sandbox-engines.js +7 -0
  128. package/dist/server/sandbox-runtime-gate.js +41 -0
  129. package/dist/server/sandbox-service.js +139 -698
  130. package/dist/server/sandbox-tool.js +21 -4
  131. package/dist/server/schedule-agent-tool.js +39 -21
  132. package/dist/server/scheduler-tasks.js +106 -55
  133. package/dist/server/scm-commitmsg.js +10 -10
  134. package/dist/server/serialize.js +48 -19
  135. package/dist/server/session-branch.js +25 -3
  136. package/dist/server/session-parser.js +28 -18
  137. package/dist/server/session-scan.js +130 -0
  138. package/dist/server/session-search.js +51 -37
  139. package/dist/server/settings-service.js +273 -111
  140. package/dist/server/setup-config.js +58 -0
  141. package/dist/server/setup-page.js +620 -620
  142. package/dist/server/skill-maintenance.js +112 -24
  143. package/dist/server/subagent-helpers.js +4 -1
  144. package/dist/server/subagent-notify.js +4 -1
  145. package/dist/server/subagent-security-gate.js +52 -11
  146. package/dist/server/subagent-task.js +27 -0
  147. package/dist/server/subagents.js +217 -46
  148. package/dist/server/tabs.js +9 -1
  149. package/dist/server/terminals.js +467 -363
  150. package/dist/server/text-quote.js +9 -0
  151. package/dist/server/tool-guards.js +42 -6
  152. package/dist/server/tool-manager.js +48 -20
  153. package/dist/server/tool-overrides.js +13 -11
  154. package/dist/server/tool-prompt-overrides.js +32 -2
  155. package/dist/server/tool-prompts.js +1 -1
  156. package/dist/server/turn-timing.js +11 -0
  157. package/dist/server/universal/drivers/claude-code.js +5 -0
  158. package/dist/server/universal/drivers/codex.js +336 -0
  159. package/dist/server/universal/index.js +1 -0
  160. package/dist/server/universal/session-store.js +48 -6
  161. package/dist/server/universal/universal-attachments.js +24 -1
  162. package/dist/server/universal/universal-service.js +1 -1
  163. package/dist/server/universal/universal-session.js +357 -231
  164. package/dist/server/uploads.js +64 -5
  165. package/dist/server/vision-bridge.js +18 -18
  166. package/dist/server/worktree-service.js +32 -24
  167. package/dist/server/ws-pending-queue.js +73 -27
  168. package/docs/device-center.md +148 -0
  169. package/docs/device-desktop.md +48 -0
  170. package/docs/dsh-engine.md +493 -493
  171. package/extensions/webui.ts +335 -335
  172. package/package.json +5 -2
  173. package/plugin-sdk/README.md +174 -174
  174. package/plugin-sdk/client-utils.mjs +279 -279
  175. package/plugin-sdk/import-check.mjs +210 -210
  176. package/plugin-sdk/index.d.ts +698 -676
  177. package/plugin-sdk/index.mjs +696 -696
  178. package/plugin-sdk/package.json +13 -13
  179. package/plugin-sdk/ssh-host-trust.mjs +225 -0
  180. package/plugins/catalog.json +11 -1
  181. package/themes/aetheris.css +501 -607
  182. package/themes/ayu-light.css +116 -140
  183. package/themes/bases/flow-base.css +1357 -1363
  184. package/themes/bases/obsidian-base.css +895 -895
  185. package/themes/bases/statusbar-flat-base.css +112 -0
  186. package/themes/bases/zhujian-base.css +688 -687
  187. package/themes/bases/zhupi-base.css +660 -659
  188. package/themes/catppuccin-latte.css +119 -142
  189. package/themes/catppuccin.css +116 -147
  190. package/themes/claude-code-dark.css +147 -146
  191. package/themes/codex.css +114 -138
  192. package/themes/cyberpunk.css +50 -108
  193. package/themes/dark-teal.css +264 -265
  194. package/themes/dazzle.css +38 -108
  195. package/themes/everforest-light.css +115 -138
  196. package/themes/flow-light.css +164 -164
  197. package/themes/flow.css +161 -161
  198. package/themes/geist.css +114 -138
  199. package/themes/gruvbox-light.css +115 -138
  200. package/themes/kanagawa-lotus.css +115 -138
  201. package/themes/md-preview.css +24 -234
  202. package/themes/mist.css +166 -186
  203. package/themes/nord.css +107 -138
  204. package/themes/one-dark.css +106 -139
  205. package/themes/paper.css +174 -186
  206. package/themes/rose-pine-dawn.css +114 -138
  207. package/themes/sakura.css +166 -186
  208. package/themes/solarized-light.css +114 -137
  209. package/themes/tokyo-night.css +115 -146
  210. package/themes/translucent.css +85 -85
  211. package/themes/transparent.css +116 -116
  212. package/themes/vs-code-dark.css +147 -147
  213. package/themes/wallpaper-flow.css +382 -382
  214. package/themes/wallpaper-obsidian.css +74 -74
  215. package/themes/white.css +164 -186
  216. package/themes/zhujian-dark.css +115 -114
  217. package/themes/zhujian.css +114 -114
  218. package/themes/zhupi-dark.css +115 -114
  219. package/themes/zhupi.css +114 -114
  220. package/web/dist/.build-assets.json +1 -0
  221. package/web/dist/assets/BgTasksModal-BcXJ20RO.js +1 -0
  222. package/web/dist/assets/BgTasksModal-DjQmiKnE.js +1 -0
  223. package/web/dist/assets/CanvasStudio-PI9pid0Y.js +1579 -0
  224. package/web/dist/assets/CanvasStudio-nf5-HxLM.js +1579 -0
  225. package/web/dist/assets/DeviceCenter-CYttJw2a.js +3 -0
  226. package/web/dist/assets/DeviceCenter-DPe4sz74.js +3 -0
  227. package/web/dist/assets/DeviceGroups-D2rogxEN.js +1 -0
  228. package/web/dist/assets/Dropdown-ZLS04O8p.js +1 -0
  229. package/web/dist/assets/FilePreview-C9Ut4Lq6.js +2 -0
  230. package/web/dist/assets/FilePreview-CvK3ZzX5.js +2 -0
  231. package/web/dist/assets/GlobalSearchModal-C5e-OCw2.js +1 -0
  232. package/web/dist/assets/GlobalSearchModal-H7pFK2UC.js +1 -0
  233. package/web/dist/assets/GroupConversation-C2wNM0dQ.js +1 -0
  234. package/web/dist/assets/GroupConversation-ChN3TWQK.js +1 -0
  235. package/web/dist/assets/ModelConfigModal-DDZccDYt.js +2 -0
  236. package/web/dist/assets/PiSetupModal-DHbqfx8T.js +1 -0
  237. package/web/dist/assets/ProviderOAuthControls-C-MK36Dk.js +1 -0
  238. package/web/dist/assets/SCMPanel-buTGziDB.js +2 -0
  239. package/web/dist/assets/SCMPanel-kx-SCL2s.js +2 -0
  240. package/web/dist/assets/SettingsModal-BsUF8jqr.js +20 -0
  241. package/web/dist/assets/SettingsModal-D357Ky7P.js +20 -0
  242. package/web/dist/assets/TerminalPanel-BBuM_Sez.js +3 -0
  243. package/web/dist/assets/TerminalPanel-D6x6xz8Q.js +3 -0
  244. package/web/dist/assets/TuiOverlayModal-CdbGV3Za.js +1 -0
  245. package/web/dist/assets/TuiOverlayModal-d6x9u25n.js +1 -0
  246. package/web/dist/assets/app-globals-DcyO0UPi.js +1 -0
  247. package/web/dist/assets/desktop-YguLbrX1.js +1 -0
  248. package/web/dist/assets/es-DWMIuDU2.js +2 -0
  249. package/web/dist/assets/fi-DaSO0Q-m.js +325 -0
  250. package/web/dist/assets/index-BPvpea8t.js +85 -0
  251. package/web/dist/assets/index-D6u8xH0o.js +85 -0
  252. package/web/dist/assets/index-DDZMv6LO.css +1 -0
  253. package/web/dist/assets/markdown-BggnuQ4H.js +40 -0
  254. package/web/dist/assets/markdown-C8LL_u4z.css +1 -0
  255. package/web/dist/assets/math-1uRJCsA9.js +257 -0
  256. package/web/dist/assets/math-BorAY7qD.css +1 -0
  257. package/web/dist/assets/plugin-host-BRBg6zmQ.js +1 -0
  258. package/web/dist/assets/shortcut-stack-hhrDyRBn.js +1 -0
  259. package/web/dist/assets/theme-DDl-Oy1b.js +1 -0
  260. package/web/dist/assets/uuid-BzDIGCwP.js +1 -0
  261. package/web/dist/index.html +42 -35
  262. package/web/dist/sw.js +179 -179
  263. package/web/public/sw.js +179 -179
  264. package/dist/gh-comment-781.md +0 -5
  265. package/dist/server/durable/durable-capabilities.js +0 -11
  266. package/dist/server/markers/builtins/services.js +0 -123
  267. package/dist/server/markers/builtins/todo.js +0 -189
  268. package/dist/server/markers-list-tool.js +0 -34
  269. package/dist/server/orchestrator.js +0 -109
  270. package/dist/server/system-prompt-soul.js +0 -41
  271. package/dist/server/univer-service.js +0 -448
  272. package/dist/server/universal/drivers/dsh-driver.js +0 -379
  273. package/dist/test-artifact.md +0 -9
  274. package/dist/test-preview-modal.md +0 -11
  275. package/dist/test-report.html +0 -20
  276. package/web/dist/assets/TerminalPanel-Ci55JtJL.js +0 -3
  277. package/web/dist/assets/index-ByiO9f-N.js +0 -2008
  278. package/web/dist/assets/index-ycGLh4a4.css +0 -1
  279. package/web/dist/assets/markdown-BJZlfvdP.js +0 -296
  280. package/web/dist/assets/markdown-DSNUiDzp.css +0 -1
@@ -68,6 +68,18 @@ export function findBranchCandidates(entries) {
68
68
  if (leaves.length === 0)
69
69
  return [];
70
70
  const candidates = [];
71
+ // Shared ancestors are visited for every leaf. Cache by object (not ID, which
72
+ // may be duplicated), and only for this call so later entry edits stay visible.
73
+ // Path traversal and pathIds output still cost the sum of all branch depths.
74
+ const timestamps = new WeakMap();
75
+ const timestampOf = (entry) => {
76
+ const cached = timestamps.get(entry);
77
+ if (cached !== undefined)
78
+ return cached;
79
+ const timestamp = parseEntryTimestamp(entry.timestamp);
80
+ timestamps.set(entry, timestamp);
81
+ return timestamp;
82
+ };
71
83
  for (const leaf of leaves) {
72
84
  const leafId = leaf.id;
73
85
  const path = [];
@@ -85,13 +97,13 @@ export function findBranchCandidates(entries) {
85
97
  for (const node of path) {
86
98
  if (node.type === "message") {
87
99
  messageCount += 1;
88
- const ts = parseEntryTimestamp(node.timestamp);
100
+ const ts = timestampOf(node);
89
101
  if (ts > lastMessageTimestamp) {
90
102
  lastMessageTimestamp = ts;
91
103
  }
92
104
  }
93
105
  }
94
- const tailTimestamp = parseEntryTimestamp(leaf.timestamp);
106
+ const tailTimestamp = timestampOf(leaf);
95
107
  candidates.push({
96
108
  leafId,
97
109
  leafEntry: leaf,
@@ -129,9 +141,19 @@ function findLowestCommonAncestor(branchA, branchB) {
129
141
  * conversation in message count, selects the main branch leaf.
130
142
  */
131
143
  export function selectBestSessionLeaf(entries, currentLeafId) {
132
- const candidates = findBranchCandidates(entries);
144
+ let candidates = findBranchCandidates(entries);
133
145
  if (candidates.length === 0)
134
146
  return null;
147
+ // An edit/reask explicitly discards the later history in this same file.
148
+ // Honor the latest durable selection, even when abandoned history is longer.
149
+ const reask = [...entries]
150
+ .reverse()
151
+ .find((entry) => entry.type === "custom" && entry.customType === "pi-web-ui:reask");
152
+ if (reask?.id) {
153
+ const selected = candidates.filter((candidate) => candidate.pathIds.includes(reask.id));
154
+ if (selected.length > 0)
155
+ candidates = selected;
156
+ }
135
157
  if (candidates.length === 1) {
136
158
  const single = candidates[0];
137
159
  return {
@@ -8,6 +8,7 @@
8
8
  * 从 agent-service.ts 抽出为独立模块。
9
9
  */
10
10
  import { existsSync } from "node:fs";
11
+ import { sessionLines } from "./session-scan.js";
11
12
  import * as fsPromises from "node:fs/promises";
12
13
  import { basename, join, resolve } from "node:path";
13
14
  import { SessionManager } from "@earendil-works/pi-coding-agent";
@@ -149,13 +150,12 @@ export async function discoverRecentProjectsFromDisk(sessionRoots, limit = 30) {
149
150
  * 以及可选的转录全文 allMessagesText)。仅用于会话列表发现与搜索,避免调用 SDK 重型的全量树解析。
150
151
  *
151
152
  * withAllMessagesText=false(默认,列表路径)时不收集转录全文,allMessagesText 返回空串 ——
152
- * 全文单条可达 MB 级,绝不随列表进任何缓存(issue #440);true(搜索路径)时收集全文并在
153
- * MAX_SEARCH_TEXT_CHARS 处截断。
153
+ * 全文单条可达 MB 级,绝不随列表进任何缓存(issue #440);true 仅兼容旧调用,返回
154
+ * MAX_SEARCH_TEXT_CHARS 内的文本预览。全文搜索请使用 scanSessionForSearch,避免截断漏查。
155
+ * 逐行异步读取,内存仅保留当前 JSONL 记录及列表字段。
154
156
  */
155
157
  export async function parseSessionInfoFast(filePath, fileMtime, withAllMessagesText = false) {
156
158
  try {
157
- const content = await fsPromises.readFile(filePath, "utf8");
158
- const lines = content.split("\n");
159
159
  let id = "";
160
160
  let cwd = "";
161
161
  let name;
@@ -166,7 +166,7 @@ export async function parseSessionInfoFast(filePath, fileMtime, withAllMessagesT
166
166
  let headerTime = 0;
167
167
  const allMessages = withAllMessagesText ? [] : null;
168
168
  let collectedChars = 0;
169
- for (const line of lines) {
169
+ for await (const line of sessionLines(filePath)) {
170
170
  if (!line.trim())
171
171
  continue;
172
172
  // 列表路径(withAllMessagesText=false)已拿到 id 与首条消息后,跳过对大块长行
@@ -229,8 +229,10 @@ export async function parseSessionInfoFast(filePath, fileMtime, withAllMessagesT
229
229
  if (!firstMessage && msg.role === "user")
230
230
  firstMessage = text;
231
231
  if (allMessages && collectedChars < MAX_SEARCH_TEXT_CHARS) {
232
- allMessages.push(text);
233
- collectedChars += text.length + 1;
232
+ const remaining = MAX_SEARCH_TEXT_CHARS - collectedChars;
233
+ const excerpt = text.slice(0, remaining);
234
+ allMessages.push(excerpt);
235
+ collectedChars += excerpt.length + 1;
234
236
  }
235
237
  }
236
238
  }
@@ -293,26 +295,34 @@ export function filterForkedParentSessions(infos, showForkedParents = false) {
293
295
  }
294
296
  if (childrenOf.size === 0)
295
297
  return infos;
298
+ // 从去重后的边构建反向关系;重复 path 可能让同一节点有多个父节点。
299
+ const parentsOf = new Map();
300
+ for (const [parentKey, children] of childrenOf) {
301
+ for (const childKey of children) {
302
+ let parents = parentsOf.get(childKey);
303
+ if (!parents) {
304
+ parents = [];
305
+ parentsOf.set(childKey, parents);
306
+ }
307
+ parents.push(parentKey);
308
+ }
309
+ }
296
310
  const canReachLeaf = new Set();
311
+ const queue = [];
297
312
  for (const key of byKey.keys()) {
298
313
  const children = childrenOf.get(key);
299
314
  if (!children || children.size === 0) {
300
315
  canReachLeaf.add(key);
316
+ queue.push(key);
301
317
  }
302
318
  }
303
- let changed = true;
304
- while (changed) {
305
- changed = false;
306
- for (const [parentKey, children] of childrenOf.entries()) {
319
+ // 每个节点最多入队一次,每条反向边最多访问一次,避免长链反复全图扫描。
320
+ for (let head = 0; head < queue.length; head++) {
321
+ for (const parentKey of parentsOf.get(queue[head]) ?? []) {
307
322
  if (canReachLeaf.has(parentKey))
308
323
  continue;
309
- for (const childKey of children) {
310
- if (canReachLeaf.has(childKey)) {
311
- canReachLeaf.add(parentKey);
312
- changed = true;
313
- break;
314
- }
315
- }
324
+ canReachLeaf.add(parentKey);
325
+ queue.push(parentKey);
316
326
  }
317
327
  }
318
328
  const kept = infos.filter((info) => {
@@ -0,0 +1,130 @@
1
+ /** Shared streaming transcript reader. Memory scales with textual JSONL records,
2
+ * not the file or embedded binary `data` strings. */
3
+ import { createReadStream } from "node:fs";
4
+ import { setImmediate } from "node:timers/promises";
5
+ /** Discard JSON string values of `data` properties (embedded image/base64 payloads)
6
+ * before assembling lines. Preserve the empty string so JSON syntax stays valid.
7
+ * Text/content strings remain intact, including escaped quotes and newlines. */
8
+ class BinaryStringFilter {
9
+ inString = false;
10
+ escaped = false;
11
+ token = "";
12
+ dataKey = false;
13
+ awaitingValue = false;
14
+ discard = false;
15
+ push(chunk) {
16
+ const output = [];
17
+ for (const char of chunk) {
18
+ if (char === "\n") {
19
+ this.inString = false;
20
+ this.escaped = false;
21
+ this.discard = false;
22
+ }
23
+ if (this.inString) {
24
+ if (!this.discard)
25
+ output.push(char);
26
+ if (this.escaped) {
27
+ this.escaped = false;
28
+ if (this.token.length < 16)
29
+ this.token += char;
30
+ }
31
+ else if (char === "\\") {
32
+ this.escaped = true;
33
+ if (this.token.length < 16)
34
+ this.token += char;
35
+ }
36
+ else if (char === '"') {
37
+ this.inString = false;
38
+ if (this.discard)
39
+ output.push(char);
40
+ try {
41
+ this.dataKey = JSON.parse('"' + this.token + '"') === "data";
42
+ }
43
+ catch {
44
+ this.dataKey = false;
45
+ }
46
+ this.discard = false;
47
+ }
48
+ else if (this.token.length < 16)
49
+ this.token += char;
50
+ continue;
51
+ }
52
+ output.push(char);
53
+ if (char === '"') {
54
+ this.inString = true;
55
+ this.token = "";
56
+ this.discard = this.awaitingValue;
57
+ this.awaitingValue = false;
58
+ this.dataKey = false;
59
+ }
60
+ else if (!/\s/.test(char)) {
61
+ this.awaitingValue = char === ":" && this.dataKey;
62
+ this.dataKey = false;
63
+ }
64
+ // JSONL records are independent, including after malformed lines.
65
+ if (char === "\n") {
66
+ this.dataKey = false;
67
+ this.awaitingValue = false;
68
+ }
69
+ }
70
+ return output.join("");
71
+ }
72
+ }
73
+ /** Early return and errors close the file. Non-binary text records are not capped:
74
+ * an exceptionally large single text message still requires one record in memory. */
75
+ export async function* sessionLines(filePath, signal) {
76
+ signal?.throwIfAborted();
77
+ const input = createReadStream(filePath, { encoding: "utf8", highWaterMark: 64 * 1024, signal });
78
+ const filter = new BinaryStringFilter();
79
+ let pending = "";
80
+ let count = 0;
81
+ try {
82
+ for await (const chunk of input) {
83
+ signal?.throwIfAborted();
84
+ const text = filter.push(chunk);
85
+ let start = 0;
86
+ let end;
87
+ while ((end = text.indexOf("\n", start)) !== -1) {
88
+ const line = pending + text.slice(start, end);
89
+ pending = "";
90
+ if (++count % 128 === 0)
91
+ await setImmediate();
92
+ signal?.throwIfAborted();
93
+ yield line.endsWith("\r") ? line.slice(0, -1) : line;
94
+ start = end + 1;
95
+ }
96
+ pending += text.slice(start);
97
+ await setImmediate();
98
+ }
99
+ signal?.throwIfAborted();
100
+ if (pending)
101
+ yield pending;
102
+ signal?.throwIfAborted();
103
+ }
104
+ catch (error) {
105
+ signal?.throwIfAborted();
106
+ throw error;
107
+ }
108
+ finally {
109
+ input.destroy();
110
+ }
111
+ }
112
+ /** Bounded worker pool; results retain input order. No implicit list/result limit. */
113
+ export async function mapSessionsConcurrent(items, visit, concurrency = 4, signal) {
114
+ signal?.throwIfAborted();
115
+ if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > 32) {
116
+ throw new RangeError("concurrency must be an integer between 1 and 32");
117
+ }
118
+ const results = new Array(items.length);
119
+ let next = 0;
120
+ await Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, async () => {
121
+ while (next < items.length) {
122
+ signal?.throwIfAborted();
123
+ const index = next++;
124
+ results[index] = await visit(items[index], index);
125
+ signal?.throwIfAborted();
126
+ }
127
+ }));
128
+ signal?.throwIfAborted();
129
+ return results;
130
+ }
@@ -10,22 +10,19 @@
10
10
  *
11
11
  * 从 agent-service.ts 抽出为独立模块。
12
12
  */
13
- import { readFileSync, statSync } from "node:fs";
14
13
  import * as fsPromises from "node:fs/promises";
15
14
  import { basename, resolve, sep } from "node:path";
16
- /** 转录全文扫描/整读的大小上限(16MB,与 readHistorySession 一致):
17
- * 超限文件同步 readFileSync 会卡事件循环数百毫秒起,搜索不值得。 */
15
+ import { sessionLines, mapSessionsConcurrent } from "./session-scan.js";
16
+ export { mapSessionsConcurrent } from "./session-scan.js";
17
+ /** Legacy whole-file reader guard, retained for readHistorySession callers only.
18
+ * Streaming search has no file-size cutoff. */
18
19
  export const MAX_TRANSCRIPT_SCAN_BYTES = 16 * 1024 * 1024;
19
- /** 转录全文进入内存/缓存的字符上限(256K 字符):全文只服务搜索的命中判定
20
- * (issue #440 拆分后按需加载),封顶保证单条 worst case 内存可控(缓存 256 条
21
- * × 256K 字符 ≈ 64MB 上界,且只在搜索活动期间存在)。
22
- * 影响面:超长转录在截断点之后的内容不参与「是否命中」判定;命中后的消息级
23
- * 定位(collectSessionAnchors)仍扫全文件,不受此上限影响。 */
20
+ /** Legacy parser text-preview budget. Search must use scanSessionForSearch. */
24
21
  export const MAX_SEARCH_TEXT_CHARS = 256 * 1024;
25
22
  /** 会话元数据快速匹配(列表初筛):仅比对 session.name、会话文件名与第一条消息。
26
23
  * 显示名、当前项目内的文件名片段、首条消息。
27
24
  * 转录全文匹配不在这里:全文单条可达 MB 级,不再随列表缓存常驻(issue #440),
28
- * 由 filterSessionsForSearch 按需加载后判定(口径不变:user 与 assistant 消息文本)。 */
25
+ * 由 searchSessions / scanSessionForSearch 流式判定(仅 user 与 assistant 消息文本)。 */
29
26
  export function sessionMatchesMetadata(q, s) {
30
27
  if (s.name && s.name.toLowerCase().includes(q))
31
28
  return true;
@@ -53,49 +50,66 @@ export function messageSearchText(m) {
53
50
  }
54
51
  return parts.join("\n");
55
52
  }
56
- /** 扫描一个会话转录文件,收集文本命中查询的消息锚点(role + timestamp,
57
- * 按转录顺序,最多 cap 个)。仅 user/assistant 消息参与,与搜索范围一致。
58
- * 超过大小上限的转录直接跳过(stat 先行,不整读)—— 全局搜索逐会话同步
59
- * 扫描,无上限时一个大转录就能冻住整个事件循环。 */
60
- export function collectSessionAnchors(filePath, q, cap = 10) {
61
- const anchors = [];
53
+ /** One asynchronous pass determines the match and collects anchors. Only user and
54
+ * assistant text participates. A missing timestamp still counts as a text match.
55
+ * Invalid/unreadable records do not prevent searching other sessions. */
56
+ export async function scanSessionForSearch(filePath, query, cap = 10, signal) {
57
+ signal?.throwIfAborted();
58
+ const result = { matched: false, anchors: [] };
59
+ const q = query.trim().toLowerCase();
62
60
  if (!q)
63
- return anchors;
61
+ return result;
62
+ const limit = Number.isFinite(cap) ? Math.max(0, Math.floor(cap)) : 10;
64
63
  try {
65
- if (statSync(filePath).size > MAX_TRANSCRIPT_SCAN_BYTES)
66
- return anchors;
67
- const lines = readFileSync(filePath, "utf8").split("\n");
68
- for (const line of lines) {
69
- if (!line.trim())
70
- continue;
71
- let e;
64
+ for await (const line of sessionLines(filePath, signal)) {
65
+ let entry;
72
66
  try {
73
- e = JSON.parse(line);
67
+ entry = JSON.parse(line);
74
68
  }
75
69
  catch {
76
70
  continue;
77
71
  }
78
- if (e?.type !== "message")
79
- continue;
80
- const m = e.message;
81
- if (!m)
82
- continue;
83
- if (m.role !== "user" && m.role !== "assistant")
72
+ if (entry?.type !== "message")
84
73
  continue;
85
- if (typeof m.timestamp !== "number")
74
+ const message = entry.message;
75
+ if (message?.role !== "user" && message?.role !== "assistant")
86
76
  continue;
87
- const text = messageSearchText(m);
88
- if (!text || !text.toLowerCase().includes(q))
77
+ if (!messageSearchText(message).toLowerCase().includes(q))
89
78
  continue;
90
- anchors.push({ role: m.role, timestamp: m.timestamp });
91
- if (anchors.length >= cap)
79
+ result.matched = true;
80
+ if (typeof message.timestamp === "number" &&
81
+ Number.isFinite(message.timestamp) &&
82
+ result.anchors.length < limit) {
83
+ result.anchors.push({ role: message.role, timestamp: message.timestamp });
84
+ }
85
+ if (result.anchors.length >= limit)
92
86
  break;
93
87
  }
94
88
  }
95
89
  catch {
96
- // 单个转录损坏不影响其余会话
90
+ // Cancellation must propagate; only transcript errors are best effort.
91
+ signal?.throwIfAborted();
92
+ // Keep any matches already read from a partially readable transcript.
97
93
  }
98
- return anchors;
94
+ signal?.throwIfAborted();
95
+ return result;
96
+ }
97
+ /** Async compatibility entry point. Prefer scanSessionForSearch when also filtering. */
98
+ export async function collectSessionAnchors(filePath, q, cap = 10, signal) {
99
+ return (await scanSessionForSearch(filePath, q, cap, signal)).anchors;
100
+ }
101
+ /** Search every supplied candidate once, preserving order with bounded I/O.
102
+ * Metadata hits still scan text to provide anchors; no 200-session list limit.
103
+ * Empty queries return all candidates without opening their transcripts. */
104
+ export async function searchSessions(sessions, query, options = {}) {
105
+ const q = query.trim().toLowerCase();
106
+ const results = await mapSessionsConcurrent(sessions, async (session) => {
107
+ const scan = q
108
+ ? await scanSessionForSearch(session.path, q, options.anchorCap, options.signal)
109
+ : { matched: true, anchors: [] };
110
+ return scan.matched || sessionMatchesMetadata(q, session) ? { session, anchors: scan.anchors } : null;
111
+ }, options.concurrency ?? 4, options.signal);
112
+ return results.filter((result) => result !== null);
99
113
  }
100
114
  /**
101
115
  * pi 的会话存储根目录。设置了 `PI_CODING_AGENT_SESSION_DIR` 时,pi 将 transcript