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,396 @@
1
+ /**
2
+ * Fork-free executable lookup for Android/Termux.
3
+ *
4
+ * Background: on POSIX the SDK resolves host executables with `spawnSync("which", …)`
5
+ * (`dist/utils/shell.js`) and probes availability with `spawnSync(cmd, ["--version"])`
6
+ * (`dist/utils/tools-manager.js`). On Android/Termux forking a child process can stall
7
+ * before it ever execs, so those probes never return and the first tool call hangs the
8
+ * server instead of failing fast. Both are pure lookups, so this patch answers them from
9
+ * PATH — no child process involved.
10
+ *
11
+ * The SDK sources are transformed in memory before compilation, never on disk (same seam
12
+ * as `server/patch-bash-process.ts`). The patch therefore survives every
13
+ * `npm i -g @earendil-works/pi-coding-agent` and applies to whichever copy
14
+ * `resolve-global-sdk.ts` picks. Drop this module once the SDK resolves executables from
15
+ * PATH itself.
16
+ *
17
+ * Two properties matter more than brevity here:
18
+ *
19
+ * 1. The replacement never relies on a binding that happens to exist in the SDK version
20
+ * at hand — it carries its own imports (`PREAMBLE`). Otherwise a version whose module
21
+ * header differs (SDK 1.1.0 has no `shellPathExists`) throws a ReferenceError that the
22
+ * surrounding `catch` swallows, and the hook reports `patched` while shell discovery
23
+ * silently falls back to `sh`.
24
+ * 2. It keeps the *semantics* of executable lookup: an entry only counts when it is a
25
+ * real file we may execute — not a directory and not an inert file. Existence alone
26
+ * made `ensureTool` claim a tool it could not spawn (`ENOENT` right after).
27
+ */
28
+ import { registerHooks } from "node:module";
29
+ export const SENTINEL = "// pi-web-ui #810: fork-free executable lookup v1";
30
+ export const PREAMBLE_START = "/* pi-web-ui #810: fork-free executable lookup v1 (preamble) */";
31
+ export const PREAMBLE_END = "/* pi-web-ui #810: fork-free executable lookup v1 (/preamble) */";
32
+ const TARGETS = {
33
+ shell: "/@earendil-works/pi-coding-agent/dist/utils/shell.js",
34
+ "tools-manager": "/@earendil-works/pi-coding-agent/dist/utils/tools-manager.js",
35
+ };
36
+ /**
37
+ * Self-contained definitions the replacement uses, injected ahead of the SDK source.
38
+ * Aliased names cannot collide with the SDK's own imports, so this works for every
39
+ * module header — including the shapes that predate `shellPathExists`.
40
+ */
41
+ export const PREAMBLE = `${PREAMBLE_START}
42
+ import {
43
+ accessSync as __piWebExecAccess,
44
+ constants as __piWebExecConstants,
45
+ statSync as __piWebExecStat,
46
+ } from "node:fs";
47
+ import { delimiter as __piWebExecDelimiter, join as __piWebExecJoin } from "node:path";
48
+ function __piWebExecProgram(candidate) {
49
+ let stats = null;
50
+ try {
51
+ stats = __piWebExecStat(candidate);
52
+ } catch {
53
+ stats = null;
54
+ }
55
+ if (stats === null) {
56
+ // An entry stat() cannot follow. On Windows these are app-execution aliases
57
+ // (0-byte reparse points; nodejs/node#36790) — runnable, so accept them.
58
+ if (process.platform !== "win32") return false;
59
+ try {
60
+ __piWebExecAccess(candidate, __piWebExecConstants.F_OK);
61
+ return true;
62
+ } catch {
63
+ return false;
64
+ }
65
+ }
66
+ // Directories are executable on POSIX but never runnable as a command; a symlink
67
+ // that points at a program resolves to one here.
68
+ if (!stats.isFile()) return false;
69
+ if (process.platform === "win32") return true;
70
+ try {
71
+ __piWebExecAccess(candidate, __piWebExecConstants.X_OK);
72
+ return true;
73
+ } catch {
74
+ return false;
75
+ }
76
+ }
77
+ ${PREAMBLE_END}`;
78
+ /** SDK 1.4.0 shape: `which` child process in the POSIX branch of findExecutableOnPath. */
79
+ const SHELL_LOOKUP_OLD = ` // Unix: Use 'which' and trust its output (handles Termux and special filesystems)
80
+ try {
81
+ const result = spawnSync("which", [executable], { encoding: "utf-8", timeout: 5000 });
82
+ if (result.status === 0 && result.stdout) {
83
+ const firstMatch = result.stdout.trim().split(/\\r?\\n/)[0];
84
+ if (firstMatch) {
85
+ return firstMatch;
86
+ }
87
+ }
88
+ }
89
+ catch {
90
+ // Ignore errors
91
+ }`;
92
+ /** SDK 1.4.0 shape: `--version` child process probe in commandExists. */
93
+ const TOOLS_LOOKUP_OLD = `function commandExists(cmd) {
94
+ try {
95
+ const result = spawnSync(cmd, ["--version"], { stdio: "pipe" });
96
+ // Check for ENOENT error (command not found)
97
+ return result.error === undefined || result.error === null;
98
+ }
99
+ catch {
100
+ return false;
101
+ }
102
+ }`;
103
+ const SHELL_LOOKUP_NEW = ` // Unix: resolve from PATH directly — a forked \`which\` can stall before exec on
104
+ // Android/Termux, which hung the first tool call instead of failing fast.
105
+ try {
106
+ for (const directory of (process.env.PATH ?? "").split(__piWebExecDelimiter)) {
107
+ if (!directory) continue;
108
+ const candidate = __piWebExecJoin(directory, executable);
109
+ if (__piWebExecProgram(candidate)) {
110
+ return candidate;
111
+ }
112
+ }
113
+ }
114
+ catch {
115
+ // Ignore errors
116
+ }`;
117
+ const TOOLS_LOOKUP_NEW = `function commandExists(cmd) {
118
+ // Android/Termux: resolve from PATH instead of forking \`cmd --version\` — the fork can
119
+ // stall before exec, so the probe hung instead of answering.
120
+ try {
121
+ // A name given as a path is resolved as that path, not searched for on PATH.
122
+ if (cmd.includes("/") || cmd.includes("\\\\")) return __piWebExecProgram(cmd);
123
+ const win = process.platform === "win32";
124
+ // CreateProcess itself only appends \`.exe\` (a .cmd/.bat needs a shell, which we must
125
+ // not spawn here); claiming those would be the same false positive this patch removes.
126
+ const extensions = win ? [".exe", ""] : [""];
127
+ return (process.env.PATH ?? "")
128
+ .split(win ? ";" : __piWebExecDelimiter)
129
+ .some((directory) => !!directory && extensions.some((ext) => __piWebExecProgram(__piWebExecJoin(directory, cmd + ext))));
130
+ }
131
+ catch {
132
+ return false;
133
+ }
134
+ }`;
135
+ /** Which target a loaded module URL belongs to, or null when it is not ours to touch. */
136
+ export function executableLookupTarget(url) {
137
+ const normalized = url.replaceAll("\\\\", "/");
138
+ for (const [target, suffix] of Object.entries(TARGETS)) {
139
+ if (normalized.endsWith(suffix))
140
+ return target;
141
+ }
142
+ return null;
143
+ }
144
+ const ANCHORS = {
145
+ shell: "function findExecutableOnPath",
146
+ "tools-manager": "function commandExists",
147
+ };
148
+ /** Any child process a lookup could still be forking through, however it is spelled. */
149
+ const FORKING_CALL = /\b(?:spawnSync|execSync|execFileSync)\s*\(/;
150
+ /** 在这些字符之后出现的 `/` 是正则字面量的开头,而不是除号。 */
151
+ const REGEX_PREFIX_CHARS = new Set("(,=:[!&|?{};+-*%<>~^".split(""));
152
+ /** 这些关键字之后同理(`return /…/` vs `a / b`)。 */
153
+ const REGEX_PREFIX_WORDS = new Set([
154
+ "return",
155
+ "typeof",
156
+ "instanceof",
157
+ "in",
158
+ "of",
159
+ "new",
160
+ "delete",
161
+ "void",
162
+ "throw",
163
+ "case",
164
+ "do",
165
+ "else",
166
+ "yield",
167
+ "await",
168
+ ]);
169
+ /** `/` 在这里是正则字面量而不是除号(只看前一个 token)。 */
170
+ function isRegexStart(source, i) {
171
+ let j = i - 1;
172
+ while (j >= 0 && /\s/.test(source[j]))
173
+ j--;
174
+ if (j < 0)
175
+ return true;
176
+ if (REGEX_PREFIX_CHARS.has(source[j]))
177
+ return true;
178
+ if (!/[A-Za-z0-9_$]/.test(source[j]))
179
+ return false;
180
+ let k = j;
181
+ while (k >= 0 && /[A-Za-z0-9_$]/.test(source[k]))
182
+ k--;
183
+ return REGEX_PREFIX_WORDS.has(source.slice(k + 1, j + 1));
184
+ }
185
+ /**
186
+ * `}` / `{` 在正则字面量里不是括号。不认正则的话,`/^}$/` 这种只带一个右花括号的
187
+ * 字面量会把深度算错:接着那个嵌套块自己的 `}` 就被当成「函数结束」,于是后面的
188
+ * `spawnSync` 落在被截断的 body 之外,已经打过叉的源码会被判成 `already` —— 正是
189
+ * 上游改写后最危险的那种误判(Android 上依然会卡死,却不报警)。
190
+ * 解析错方向的代价很低:误把代码当成字符串只会让 body 取不出来 → `unsupported`。
191
+ */
192
+ function skipRegex(source, i) {
193
+ let inClass = false;
194
+ for (let j = i + 1; j < source.length; j++) {
195
+ const char = source[j];
196
+ if (char === "\\") {
197
+ j++;
198
+ continue;
199
+ }
200
+ // 正则字面量不跨行:跑到行尾说明这是个除号,交给调用方按代码处理。
201
+ if (char === "\n")
202
+ return null;
203
+ if (inClass) {
204
+ if (char === "]")
205
+ inClass = false;
206
+ continue;
207
+ }
208
+ if (char === "[")
209
+ inClass = true;
210
+ else if (char === "/")
211
+ return j;
212
+ }
213
+ return null;
214
+ }
215
+ /** Index just past the comment or quoted literal starting at `i`, or null when it is code. */
216
+ function skipNonCode(source, i) {
217
+ const char = source[i];
218
+ if (char === "/" && source[i + 1] === "/") {
219
+ const end = source.indexOf("\n", i);
220
+ return end < 0 ? source.length : end;
221
+ }
222
+ if (char === "/" && source[i + 1] === "*") {
223
+ const end = source.indexOf("*/", i + 2);
224
+ return end < 0 ? null : end + 1;
225
+ }
226
+ if (char === "/" && isRegexStart(source, i))
227
+ return skipRegex(source, i);
228
+ if (char === '"' || char === "'" || char === "`") {
229
+ for (let j = i + 1; j < source.length; j++) {
230
+ if (source[j] === "\\")
231
+ j++;
232
+ else if (source[j] === char)
233
+ return j;
234
+ }
235
+ return null;
236
+ }
237
+ return null;
238
+ }
239
+ /**
240
+ * Body of the function starting at `anchor`, or null when it is not there.
241
+ * Skips comments and string/template contents so braces inside them cannot unbalance it.
242
+ */
243
+ export function functionBody(source, anchor) {
244
+ const start = source.indexOf(anchor);
245
+ if (start < 0)
246
+ return null;
247
+ const open = source.indexOf("{", start);
248
+ if (open < 0)
249
+ return null;
250
+ let depth = 0;
251
+ for (let i = open; i < source.length; i++) {
252
+ const skip = skipNonCode(source, i);
253
+ if (skip !== null) {
254
+ i = skip;
255
+ continue;
256
+ }
257
+ const char = source[i];
258
+ if (char === "{")
259
+ depth++;
260
+ else if (char === "}") {
261
+ // Only a brace that ends the line can close the function. A `}` inside a regex
262
+ // literal sits mid-statement, and treating it as the end would truncate the body —
263
+ // hiding a child process that comes later and reporting the lookup as fixed.
264
+ if (depth === 1) {
265
+ if (isStatementEnd(source, i + 1))
266
+ return source.slice(open, i + 1);
267
+ }
268
+ else
269
+ depth--;
270
+ }
271
+ }
272
+ return null;
273
+ }
274
+ /** Index of the `}` matching the `{` at `open`, or null when the block is unbalanced. */
275
+ function bracedBlockEnd(source, open) {
276
+ let depth = 0;
277
+ for (let i = open; i < source.length; i++) {
278
+ const skip = skipNonCode(source, i);
279
+ if (skip !== null) {
280
+ i = skip;
281
+ continue;
282
+ }
283
+ if (source[i] === "{")
284
+ depth++;
285
+ else if (source[i] === "}" && --depth === 0)
286
+ return i;
287
+ }
288
+ return null;
289
+ }
290
+ /**
291
+ * What actually runs on POSIX: the body without the `if (process.platform === "win32")`
292
+ * early return. The shell lookup keeps a `where` child process in that branch on every SDK
293
+ * version, and it never runs on Android/Termux — counting it as a fork would report a
294
+ * fork-free POSIX lookup as unrecognized and warn on every start.
295
+ */
296
+ export function posixPortion(body) {
297
+ const guard = body.search(/if \(process\.platform === "win32"\)\s*\{/);
298
+ if (guard < 0)
299
+ return body;
300
+ const open = body.indexOf("{", guard);
301
+ const close = bracedBlockEnd(body, open);
302
+ if (close === null)
303
+ return body;
304
+ return body.slice(0, guard) + body.slice(close + 1).replace(/^\s*return null;\s*/, "");
305
+ }
306
+ /** Whitespace (and an optional `;`) up to the end of the line — a statement boundary. */
307
+ function isStatementEnd(source, at) {
308
+ return /^[ \t]*;?[ \t]*(?:\r?\n|$)/.test(source.slice(at, at + 8));
309
+ }
310
+ /**
311
+ * A lookup counts as already fork-free only when that is positively identifiable:
312
+ * the function is still there, it scans `process.env.PATH`, and it forks nothing.
313
+ * Anything else — a reformatted probe, an unknown rewrite — stays `unsupported`, so an
314
+ * unrecognized SDK never gets reported as fixed while the probe is still in the way.
315
+ */
316
+ function isForkFreeLookup(source, anchor) {
317
+ const body = functionBody(source, anchor);
318
+ if (body === null)
319
+ return false;
320
+ const posix = posixPortion(body);
321
+ return !FORKING_CALL.test(posix) && posix.includes("process.env.PATH");
322
+ }
323
+ export function patchExecutableLookupSource(source, target) {
324
+ if (source.includes(SENTINEL))
325
+ return { code: source, status: "already" };
326
+ const old = target === "shell" ? SHELL_LOOKUP_OLD : TOOLS_LOOKUP_OLD;
327
+ const replacement = target === "shell" ? SHELL_LOOKUP_NEW : TOOLS_LOOKUP_NEW;
328
+ // Exact, single occurrence: a moved or rewritten lookup must fail loudly, never
329
+ // half-apply, because the alternative is a silently hanging server.
330
+ if (source.split(old).length !== 2) {
331
+ return { code: source, status: isForkFreeLookup(source, ANCHORS[target]) ? "already" : "unsupported" };
332
+ }
333
+ return { code: `${PREAMBLE}\n${source.replace(old, replacement)}\n${SENTINEL}\n`, status: "patched" };
334
+ }
335
+ const LOG_PREFIX = "[executable-lookup]";
336
+ const OPT_OUT = new Set(["off", "0", "false", "no"]);
337
+ const OPT_IN = new Set(["on", "1", "true", "yes"]);
338
+ /** Android/Termux only by default; `PI_WEB_EXEC_LOOKUP=off` opts out, `=on` forces. */
339
+ export function shouldPatchExecutableLookup(platform = process.platform, env = process.env) {
340
+ const flag = (env.PI_WEB_EXEC_LOOKUP ?? "").trim().toLowerCase();
341
+ if (OPT_OUT.has(flag))
342
+ return false;
343
+ if (OPT_IN.has(flag))
344
+ return true;
345
+ return platform === "android" || Boolean(env.TERMUX_VERSION);
346
+ }
347
+ /** Logged once per target, so every restart states whether the patch is really in place. */
348
+ export function describeLookupResult(target, status, url) {
349
+ if (status === "unsupported")
350
+ return {
351
+ level: "warn",
352
+ message: `${LOG_PREFIX} ${target}: NOT patched — unrecognized SDK source, falling back to the child-process lookup, ` +
353
+ `which can hang on Android/Termux (${url})`,
354
+ };
355
+ return { level: "log", message: `${LOG_PREFIX} ${target}: ${status === "patched" ? "patched" : "already patched"}` };
356
+ }
357
+ function report(target, status, url) {
358
+ const { level, message } = describeLookupResult(target, status, url);
359
+ if (level === "warn")
360
+ console.warn(message);
361
+ else
362
+ console.log(message);
363
+ }
364
+ /** Only ES modules can take the preamble; everything else keeps the SDK's own lookup. */
365
+ export function isPatchableFormat(format) {
366
+ return format === "module" || format === "module-typescript";
367
+ }
368
+ /* SDK sources are transformed in memory before compilation, never on disk. */
369
+ export function registerExecutableLookupPatch(platform = process.platform, env = process.env) {
370
+ if (!shouldPatchExecutableLookup(platform, env))
371
+ return;
372
+ const forced = OPT_IN.has((env.PI_WEB_EXEC_LOOKUP ?? "").trim().toLowerCase());
373
+ console.log(`${LOG_PREFIX} enabled (${forced ? "PI_WEB_EXEC_LOOKUP" : platform === "android" ? "android" : "termux"}) — ` +
374
+ "resolving SDK host executables from PATH; PI_WEB_EXEC_LOOKUP=off disables");
375
+ registerHooks({
376
+ load(url, context, nextLoad) {
377
+ const target = executableLookupTarget(url);
378
+ if (!target)
379
+ return nextLoad(url, context);
380
+ const loaded = nextLoad(url, context);
381
+ if (loaded.source == null)
382
+ return loaded;
383
+ // The preamble is an ES module head; injecting it into CommonJS would break the
384
+ // load instead of falling back to the lookup we were trying to improve.
385
+ if (!isPatchableFormat(loaded.format)) {
386
+ console.warn(`${LOG_PREFIX} ${target}: NOT patched — loaded as ${loaded.format ?? "an unknown format"}, ` +
387
+ `the patch only rewrites ES modules (${url})`);
388
+ return loaded;
389
+ }
390
+ const source = typeof loaded.source === "string" ? loaded.source : new TextDecoder().decode(loaded.source);
391
+ const result = patchExecutableLookupSource(source, target);
392
+ report(target, result.status, url);
393
+ return result.status === "patched" ? { ...loaded, source: result.code } : loaded;
394
+ },
395
+ });
396
+ }
@@ -1,5 +1,7 @@
1
1
  /** Shared upload and WebSocket limits. Keep this module free of runtime dependencies. */
2
2
  export const MAX_UPLOAD_BYTES = 100 * 1024 * 1024;
3
+ /** Authenticated report chunks: 16 KiB UTF-8, worst-case JSON escaping plus envelope. */
4
+ export const TASK_REPORT_UPLOAD_JSON_BYTES = 128 * 1024;
3
5
  export function normalizeUploadMaxMb(value, fallback) {
4
6
  return typeof value === "number" && Number.isFinite(value) ? Math.max(1, Math.min(100, Math.floor(value))) : fallback;
5
7
  }
@@ -34,6 +34,40 @@ export function llmInflight() {
34
34
  function fail(error) {
35
35
  return { ok: false, error };
36
36
  }
37
+ function validateImages(images) {
38
+ if (images === undefined)
39
+ return [];
40
+ if (!Array.isArray(images) || images.length > 8)
41
+ throw new Error("images must be an array of at most 8 images");
42
+ let total = 0;
43
+ return Array.from(images, (image) => {
44
+ if (!image || typeof image.data !== "string" || typeof image.mimeType !== "string")
45
+ throw new Error("invalid image data/mimeType");
46
+ const { data, mimeType } = image;
47
+ if (!["image/jpeg", "image/png", "image/webp"].includes(mimeType))
48
+ throw new Error("unsupported image MIME type");
49
+ if (!data.length ||
50
+ data.length > 4 * Math.ceil(1048576 / 3) ||
51
+ data.length % 4 !== 0 ||
52
+ !/^[A-Za-z0-9+/]*={0,2}$/.test(data))
53
+ throw new Error("invalid or oversized image base64");
54
+ const bytes = Buffer.from(data, "base64");
55
+ if (bytes.toString("base64") !== data)
56
+ throw new Error("invalid image base64 padding");
57
+ if (bytes.length > 1048576 || (total += bytes.length) > 6 * 1048576)
58
+ throw new Error("image exceeds 1 MiB or total images exceed 6 MiB");
59
+ const valid = mimeType === "image/jpeg"
60
+ ? bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff
61
+ : mimeType === "image/png"
62
+ ? bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))
63
+ : bytes.length >= 12 &&
64
+ bytes.subarray(0, 4).equals(Buffer.from("RIFF")) &&
65
+ bytes.subarray(8, 12).equals(Buffer.from("WEBP"));
66
+ if (!valid)
67
+ throw new Error("image signature does not match MIME type");
68
+ return { type: "image", data, mimeType };
69
+ });
70
+ }
37
71
  export async function completeWithIsolatedSession(env, req) {
38
72
  const prompt = String(req?.prompt ?? "");
39
73
  if (!prompt.trim())
@@ -43,14 +77,56 @@ export async function completeWithIsolatedSession(env, req) {
43
77
  const system = String(req?.system ?? "");
44
78
  if (system.length > MAX_SYSTEM_CHARS)
45
79
  return fail(`llm.complete: system 超长(${system.length} > ${MAX_SYSTEM_CHARS} 字),请裁剪后重发`);
80
+ let images;
81
+ try {
82
+ images = validateImages(req?.images);
83
+ }
84
+ catch (err) {
85
+ return fail(`llm.complete: ${err.message}`);
86
+ }
87
+ const signal = req?.signal;
88
+ if (signal?.aborted)
89
+ return fail("llm.complete: cancelled");
46
90
  if (inflight >= MAX_INFLIGHT)
47
91
  return fail(`llm.complete: 并发已满(${MAX_INFLIGHT} 路在飞),请稍后重试`);
48
92
  const maxChars = Math.min(Math.max(Number(req?.maxChars ?? DEFAULT_MAX_CHARS) || DEFAULT_MAX_CHARS, 1), MAX_MAX_CHARS);
49
93
  const timeoutMs = Math.min(Math.max(Number(req?.timeoutMs ?? DEFAULT_TIMEOUT_MS) || DEFAULT_TIMEOUT_MS, MIN_TIMEOUT_MS), MAX_TIMEOUT_MS);
50
94
  inflight += 1;
95
+ let stopped;
96
+ let dispose;
97
+ let abort;
98
+ let resolveStop;
99
+ const interruption = new Promise((resolve) => {
100
+ resolveStop = resolve;
101
+ });
102
+ const stop = (result) => {
103
+ if (stopped)
104
+ return;
105
+ stopped = result;
106
+ try {
107
+ void abort?.().catch(() => { });
108
+ }
109
+ catch {
110
+ /* best effort */
111
+ }
112
+ dispose?.();
113
+ resolveStop(result);
114
+ };
115
+ const onAbort = () => stop(fail("llm.complete: cancelled"));
116
+ signal?.addEventListener("abort", onAbort, { once: true });
117
+ if (signal?.aborted)
118
+ onAbort();
119
+ const timer = setTimeout(() => stop(fail(`llm.complete: 超时(约${Math.round(timeoutMs / 1000)}s)`)), timeoutMs);
51
120
  const run = (async () => {
52
- let dispose;
53
121
  try {
122
+ if (stopped)
123
+ return stopped;
124
+ const modelRuntime = await ModelRuntime.create({
125
+ authPath: join(env.agentDir, "auth.json"),
126
+ modelsPath: join(env.agentDir, "models.json"),
127
+ });
128
+ if (stopped)
129
+ return stopped;
54
130
  const services = await createAgentSessionServices({
55
131
  cwd: env.cwd,
56
132
  agentDir: env.agentDir,
@@ -58,11 +134,10 @@ export async function completeWithIsolatedSession(env, req) {
58
134
  resourceLoaderOptions: {
59
135
  skillsOverride: (res) => ({ ...res, skills: [] }),
60
136
  },
61
- modelRuntime: await ModelRuntime.create({
62
- authPath: join(env.agentDir, "auth.json"),
63
- modelsPath: join(env.agentDir, "models.json"),
64
- }),
137
+ modelRuntime,
65
138
  });
139
+ if (stopped)
140
+ return stopped;
66
141
  // 模型:显式指定 > 主会话回落 > 会话默认(与 reviewer 同优先级)。
67
142
  let model;
68
143
  let modelName = "default";
@@ -85,7 +160,12 @@ export async function completeWithIsolatedSession(env, req) {
85
160
  // 全部工具关闭("all"):纯补全,无副作用(SDK 的 noTools 是 "builtin"|"all" 枚举)。
86
161
  noTools: "all",
87
162
  });
163
+ let disposed = false;
164
+ abort = () => srv.session.abort();
88
165
  dispose = () => {
166
+ if (disposed)
167
+ return;
168
+ disposed = true;
89
169
  try {
90
170
  srv.session.dispose();
91
171
  }
@@ -93,8 +173,16 @@ export async function completeWithIsolatedSession(env, req) {
93
173
  /* dispose 尽力而为 */
94
174
  }
95
175
  };
176
+ if (stopped) {
177
+ dispose();
178
+ return stopped;
179
+ }
180
+ if (images.length && !srv.session.model?.input?.includes("image"))
181
+ return fail("llm.complete: selected model does not support image inputs");
96
182
  const text = system.trim() ? `系统指令:${system.trim()}\n\n---\n\n任务:${prompt}` : prompt;
97
- await srv.session.prompt(text, { expandPromptTemplates: false });
183
+ await srv.session.prompt(text, { expandPromptTemplates: false, ...(images.length ? { images } : {}) });
184
+ if (stopped)
185
+ return stopped;
98
186
  const raw = srv.session.getLastAssistantText() ?? "";
99
187
  let usage;
100
188
  try {
@@ -107,7 +195,7 @@ export async function completeWithIsolatedSession(env, req) {
107
195
  return { ok: true, text: raw.slice(0, maxChars), model: modelName, ...(usage ? { usage } : {}) };
108
196
  }
109
197
  finally {
110
- // 会话回收跟 run 走:超时竞速输了 run 还在飞,run 落定才 dispose,不留孤儿。
198
+ // 正常结束与异常均回收;中断路径会提前 abort/dispose,迟到的会话也在这里回收。
111
199
  try {
112
200
  dispose?.();
113
201
  }
@@ -126,10 +214,13 @@ export async function completeWithIsolatedSession(env, req) {
126
214
  inflight -= 1;
127
215
  });
128
216
  try {
129
- const timer = new Promise((resolve) => setTimeout(() => resolve(fail(`llm.complete: 超时(约${Math.round(timeoutMs / 1000)}s)`)), timeoutMs));
130
- return await Promise.race([run, timer]);
217
+ return await Promise.race([run, interruption]);
131
218
  }
132
219
  catch (err) {
133
220
  return fail(`llm.complete: ${err.message}`);
134
221
  }
222
+ finally {
223
+ clearTimeout(timer);
224
+ signal?.removeEventListener("abort", onAbort);
225
+ }
135
226
  }
@@ -3363,6 +3363,7 @@ export class PluginManager {
3363
3363
  }
3364
3364
  },
3365
3365
  llm: {
3366
+ supportsImages: true,
3366
3367
  complete: async (req) => {
3367
3368
  if (!can("llm"))
3368
3369
  return { ok: false, error: `插件未声明能力 "llm"(manifest.permissions)——请求被拒` };
@@ -62,6 +62,8 @@ export const PRESET_FIELD_GROUPS = {
62
62
  "skillsCatalogMaxDesc",
63
63
  "skillsCatalogShowLocation",
64
64
  "skillsCatalogBudget",
65
+ "skillsMaxFileBytes",
66
+ "skillsFullTextMaxBytes",
65
67
  ],
66
68
  // 模型侧行为与各专用提示词
67
69
  ai: [
@@ -361,6 +363,18 @@ export const PRESET_FIELD_META = {
361
363
  hintZh: "技能名录字符上限(默认 20000),超限自动降级为紧凑名称索引",
362
364
  hintEn: "Total catalog character limit (default 20000), falls back to compact name index when exceeded",
363
365
  },
366
+ skillsMaxFileBytes: {
367
+ labelZh: "技能单文件上限",
368
+ labelEn: "Skill File Limit",
369
+ hintZh: "单个技能正文上限(字节,默认 8192);全文注入与 skill 工具同口径,0 表示不设单文件上限",
370
+ hintEn: "Per-skill file size limit in bytes (default 8192), shared by full-text injection and the skill tool; 0 disables the per-file cap",
371
+ },
372
+ skillsFullTextMaxBytes: {
373
+ labelZh: "技能全文注入预算",
374
+ labelEn: "Skill Full-Text Budget",
375
+ hintZh: "{{skills}} 全文注入的总字节预算(默认 32768,按 UTF-8 字节计),0 表示不设总量上限",
376
+ hintEn: "Total byte budget for {{skills}} full-text injection (default 32768, counted in UTF-8 bytes); 0 disables the total cap",
377
+ },
364
378
  // ai
365
379
  steeringMode: {
366
380
  labelZh: "插话队列模式",
@@ -713,6 +727,16 @@ export function formatPresetFieldValue(field, value, lang = "zh") {
713
727
  const valText = n === 0 ? zeroText : isZh ? `${n} 字符` : `${n} chars`;
714
728
  return { summary: valText };
715
729
  }
730
+ if (field === "skillsMaxFileBytes" || field === "skillsFullTextMaxBytes") {
731
+ const n = Number(value);
732
+ const zeroText = isZh ? "不限" : "No limit";
733
+ const valText = n === 0
734
+ ? zeroText
735
+ : isZh
736
+ ? `${(n / 1024).toFixed(n % 1024 === 0 ? 0 : 1)} KB`
737
+ : `${(n / 1024).toFixed(n % 1024 === 0 ? 0 : 1)} KB`;
738
+ return { summary: valText };
739
+ }
716
740
  if (field === "skillsCatalogShowLocation") {
717
741
  return { summary: value ? (isZh ? "开启" : "Enabled") : isZh ? "关闭" : "Disabled" };
718
742
  }
@@ -263,6 +263,8 @@ const PRESET_FIELD_KINDS = {
263
263
  skillsCatalogMaxDesc: "number",
264
264
  skillsCatalogShowLocation: "bool",
265
265
  skillsCatalogBudget: "number",
266
+ skillsMaxFileBytes: "number",
267
+ skillsFullTextMaxBytes: "number",
266
268
  // -- ai --------------------------------------------------------------
267
269
  steeringMode: "queueMode",
268
270
  followUpMode: "queueMode",