pi-web-ui 0.114.3 → 0.116.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 (224) hide show
  1. package/CHANGELOG.md +62 -1
  2. package/bin/pi-web-ui.mjs +90 -8
  3. package/dist/gh-comment-781.md +5 -0
  4. package/dist/server/agent-service-daemon.js +522 -32
  5. package/dist/server/agent-service.js +954 -402
  6. package/dist/server/canvas/canvas-dispatch.js +13 -1
  7. package/dist/server/client-state.js +42 -2
  8. package/dist/server/communicate-tool.js +2 -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 +100 -9
  14. package/dist/server/device-center/bot-presets.js +46 -0
  15. package/dist/server/device-center/collab-service.js +362 -13
  16. package/dist/server/device-center/collab-tool.js +824 -13
  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 +20 -0
  22. package/dist/server/device-center/execution-settings.js +213 -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 +392 -40
  26. package/dist/server/device-center/file-sync-paths.js +171 -0
  27. package/dist/server/device-center/file-sync.js +186 -96
  28. package/dist/server/device-center/group-context-delta.js +37 -0
  29. package/dist/server/device-center/group-context-message.js +210 -0
  30. package/dist/server/device-center/group-context.js +179 -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 +233 -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-locks.js +320 -0
  37. package/dist/server/device-center/hub-page.js +13 -33
  38. package/dist/server/device-center/hub-webhooks.js +165 -0
  39. package/dist/server/device-center/hub.js +2379 -107
  40. package/dist/server/device-center/human-interaction.js +232 -0
  41. package/dist/server/device-center/integration-errors.js +25 -0
  42. package/dist/server/device-center/local-hub.js +20 -1
  43. package/dist/server/device-center/local-page.js +17 -0
  44. package/dist/server/device-center/local.js +430 -41
  45. package/dist/server/device-center/main.js +11 -1
  46. package/dist/server/device-center/partition-log.js +293 -0
  47. package/dist/server/device-center/path-portal.js +11 -3
  48. package/dist/server/device-center/relay.js +364 -35
  49. package/dist/server/device-center/report-metadata.js +66 -0
  50. package/dist/server/device-center/report-upload.js +63 -0
  51. package/dist/server/device-center/runtime.js +598 -41
  52. package/dist/server/device-center/smoke-preview.js +3 -0
  53. package/dist/server/device-center/store.js +203 -41
  54. package/dist/server/device-center/task-context-budget.js +161 -0
  55. package/dist/server/device-center/task-journal.js +385 -0
  56. package/dist/server/device-center/task-plan.js +33 -0
  57. package/dist/server/device-center/task-progress.js +141 -0
  58. package/dist/server/device-center/task-recovery.js +452 -0
  59. package/dist/server/device-center/task-report-outbox.js +216 -0
  60. package/dist/server/device-center/task-report.js +384 -0
  61. package/dist/server/device-center/task-scheduler.js +445 -0
  62. package/dist/server/device-center/task-state.js +333 -0
  63. package/dist/server/device-center/transfer-stream.js +1006 -0
  64. package/dist/server/device-center/transfers.js +841 -8
  65. package/dist/server/dispatch-domain-handlers.js +35 -6
  66. package/dist/server/dsh/dsh-agent-service.js +6 -0
  67. package/dist/server/durable/durable-capabilities.js +11 -0
  68. package/dist/server/engine-probe.js +112 -1
  69. package/dist/server/global-loader.js +119 -19
  70. package/dist/server/goal-service.js +10 -5
  71. package/dist/server/index.js +222 -29
  72. package/dist/server/managed.js +2 -0
  73. package/dist/server/markers/builtins/services.js +123 -0
  74. package/dist/server/markers/builtins/todo.js +189 -0
  75. package/dist/server/markers-list-tool.js +34 -0
  76. package/dist/server/message-deletion.js +40 -0
  77. package/dist/server/message-window.js +9 -0
  78. package/dist/server/model-admin.js +48 -6
  79. package/dist/server/model-enrich.js +10 -1
  80. package/dist/server/orchestrator.js +109 -0
  81. package/dist/server/patch-executable-lookup.js +396 -0
  82. package/dist/server/payload-limits.js +2 -0
  83. package/dist/server/plugin-llm.js +100 -9
  84. package/dist/server/plugins.js +65 -7
  85. package/dist/server/preset-fields.js +24 -0
  86. package/dist/server/preset-share.js +2 -0
  87. package/dist/server/prompt-base-store.js +85 -0
  88. package/dist/server/prompt-composer.js +44 -2
  89. package/dist/server/protocol-version.js +1 -1
  90. package/dist/server/protocol.js +2 -2
  91. package/dist/server/reasoning-registry.js +207 -0
  92. package/dist/server/remote-ssh-service.js +22 -9
  93. package/dist/server/resolve-global-sdk.js +2 -0
  94. package/dist/server/session-search.js +1 -1
  95. package/dist/server/settings-service.js +90 -39
  96. package/dist/server/skill-content-filler.js +29 -8
  97. package/dist/server/skill-tool.js +12 -3
  98. package/dist/server/startup-banner.js +35 -0
  99. package/dist/server/subagent-helpers.js +4 -1
  100. package/dist/server/subagents.js +52 -37
  101. package/dist/server/system-prompt-soul.js +41 -0
  102. package/dist/server/tool-host-factories.js +1 -0
  103. package/dist/server/tool-manager.js +17 -9
  104. package/dist/server/unauthorized-page.js +319 -0
  105. package/dist/server/univer-service.js +448 -0
  106. package/dist/server/universal/drivers/dsh-driver.js +379 -0
  107. package/dist/server/universal/universal-session.js +5 -0
  108. package/dist/server/webui-context.js +25 -5
  109. package/dist/test-artifact.md +9 -0
  110. package/dist/test-preview-modal.md +11 -0
  111. package/dist/test-report.html +20 -0
  112. package/docs/README.md +94 -0
  113. package/docs/architecture-plugins.md +946 -0
  114. package/docs/device-center.md +106 -12
  115. package/docs/dsh-engine.md +10 -10
  116. package/extensions/webui.ts +43 -1
  117. package/package.json +2 -1
  118. package/themes/aetheris.css +5 -0
  119. package/themes/ayu-light.css +6 -0
  120. package/themes/bases/flow-base.css +68 -68
  121. package/themes/catppuccin-latte.css +6 -0
  122. package/themes/catppuccin.css +6 -0
  123. package/themes/claude-code-dark.css +5 -0
  124. package/themes/codex.css +6 -0
  125. package/themes/cyberpunk.css +6 -0
  126. package/themes/dark-teal.css +6 -1
  127. package/themes/dazzle.css +6 -0
  128. package/themes/everforest-light.css +6 -0
  129. package/themes/flow-light.css +8 -1
  130. package/themes/flow.css +6 -1
  131. package/themes/geist.css +6 -0
  132. package/themes/gruvbox-light.css +6 -0
  133. package/themes/kanagawa-lotus.css +6 -0
  134. package/themes/md-preview.css +6 -0
  135. package/themes/mist.css +6 -0
  136. package/themes/nord.css +6 -0
  137. package/themes/one-dark.css +6 -0
  138. package/themes/paper.css +6 -0
  139. package/themes/rose-pine-dawn.css +6 -0
  140. package/themes/sakura.css +6 -0
  141. package/themes/solarized-light.css +6 -0
  142. package/themes/tokyo-night.css +6 -0
  143. package/themes/translucent.css +6 -0
  144. package/themes/transparent.css +6 -0
  145. package/themes/vs-code-dark.css +5 -0
  146. package/themes/wallpaper-flow.css +5 -1
  147. package/themes/wallpaper-obsidian.css +6 -0
  148. package/themes/white.css +6 -0
  149. package/themes/zhujian-dark.css +6 -1
  150. package/themes/zhujian.css +6 -1
  151. package/themes/zhupi-dark.css +6 -1
  152. package/themes/zhupi.css +6 -1
  153. package/web/dist/.build-assets.json +1 -1
  154. package/web/dist/assets/BgTasksModal-BDoOpj-F.js +1 -0
  155. package/web/dist/assets/BgTasksModal-C0i3O1FT.js +1 -0
  156. package/web/dist/assets/{CanvasStudio-BSg9ghPV.js → CanvasStudio-B8thymBN.js} +3 -3
  157. package/web/dist/assets/{CanvasStudio-DxW7C3Sz.js → CanvasStudio-zSxyIx1R.js} +3 -3
  158. package/web/dist/assets/DeviceCenter-DfAHKcid.js +3 -0
  159. package/web/dist/assets/DeviceCenter-ydvOTlzE.js +3 -0
  160. package/web/dist/assets/DeviceExecutionSettings-q5Ik8oXg.js +1 -0
  161. package/web/dist/assets/DeviceGroups-CI14_SRb.js +1 -0
  162. package/web/dist/assets/DeviceGroups-DvsB5IEU.js +1 -0
  163. package/web/dist/assets/Dropdown-C4LIhshN.js +1 -0
  164. package/web/dist/assets/FilePreview-BgGongmv.js +2 -0
  165. package/web/dist/assets/FilePreview-D4NrhF-U.js +2 -0
  166. package/web/dist/assets/GlobalSearchModal-BWgU8yPd.js +1 -0
  167. package/web/dist/assets/GlobalSearchModal-F7fNimKk.js +1 -0
  168. package/web/dist/assets/GroupConversation-Dh71Pdb-.js +17 -0
  169. package/web/dist/assets/GroupConversation-ZK3nRmNm.js +17 -0
  170. package/web/dist/assets/HintTip-c6d0TJoh.js +1 -0
  171. package/web/dist/assets/ModelConfigModal-YVEgyy34.js +2 -0
  172. package/web/dist/assets/ModelConfigModal-vWtg3srp.js +2 -0
  173. package/web/dist/assets/PiSetupModal-BmMrrgB9.js +1 -0
  174. package/web/dist/assets/ProviderOAuthControls-BGSBIKD7.js +1 -0
  175. package/web/dist/assets/SCMPanel-B8_EDxNr.js +2 -0
  176. package/web/dist/assets/SCMPanel-BU58qk3T.js +2 -0
  177. package/web/dist/assets/SettingsModal-CMUybq3J.js +32 -0
  178. package/web/dist/assets/SettingsModal-OBmGTh-5.js +32 -0
  179. package/web/dist/assets/TerminalPanel-0CYvD72B.js +3 -0
  180. package/web/dist/assets/TerminalPanel-DDavKvFr.js +3 -0
  181. package/web/dist/assets/TuiOverlayModal-BsA-QTvN.js +1 -0
  182. package/web/dist/assets/TuiOverlayModal-DzoVQBuG.js +1 -0
  183. package/web/dist/assets/app-globals-CZxzGvIo.js +123 -0
  184. package/web/dist/assets/canvas-client-CUnXlQYX.js +1 -0
  185. package/web/dist/assets/{desktop-7EvUHhKQ.js → desktop-aAKpvKJV.js} +1 -1
  186. package/web/dist/assets/group-view-state-CGCzYF8k.js +1 -0
  187. package/web/dist/assets/index-C6DwztqE.css +1 -0
  188. package/web/dist/assets/index-CuN802Sj.js +93 -0
  189. package/web/dist/assets/index-EH5Fw9fa.js +93 -0
  190. package/web/dist/assets/plugin-host-BRWib9DF.js +1 -0
  191. package/web/dist/assets/remote-ssh-client-CfYSMEZg.js +1 -0
  192. package/web/dist/assets/theme-D2l_mLNo.js +1 -0
  193. package/web/dist/index.html +10 -9
  194. package/web/dist/sw.js +1 -1
  195. package/web/dist/assets/BgTasksModal-BvnUHjFe.js +0 -1
  196. package/web/dist/assets/BgTasksModal-DSC8ncW3.js +0 -1
  197. package/web/dist/assets/DeviceCenter-Bmgr-Bwm.js +0 -3
  198. package/web/dist/assets/DeviceCenter-Cl9MBXaH.js +0 -3
  199. package/web/dist/assets/DeviceGroups-aeLD2msl.js +0 -1
  200. package/web/dist/assets/Dropdown-D1Jl35dw.js +0 -1
  201. package/web/dist/assets/FilePreview-6CqoDF_P.js +0 -2
  202. package/web/dist/assets/FilePreview-CJa27G_Q.js +0 -2
  203. package/web/dist/assets/GlobalSearchModal-CJX35rZL.js +0 -1
  204. package/web/dist/assets/GlobalSearchModal-CMW0xz0P.js +0 -1
  205. package/web/dist/assets/GroupConversation-Cq4daBFb.js +0 -1
  206. package/web/dist/assets/GroupConversation-DoELa83U.js +0 -1
  207. package/web/dist/assets/ModelConfigModal-Bp7tfKYh.js +0 -2
  208. package/web/dist/assets/PiSetupModal-DD8srwBJ.js +0 -1
  209. package/web/dist/assets/ProviderOAuthControls-C6tfXb88.js +0 -1
  210. package/web/dist/assets/SCMPanel-CghgsyBN.js +0 -2
  211. package/web/dist/assets/SCMPanel-D8-8aqwC.js +0 -2
  212. package/web/dist/assets/SettingsModal-BbBe2rYo.js +0 -20
  213. package/web/dist/assets/SettingsModal-qETiVPKj.js +0 -20
  214. package/web/dist/assets/TerminalPanel-Da-Xs4Wk.js +0 -3
  215. package/web/dist/assets/TerminalPanel-DnS4tFQO.js +0 -3
  216. package/web/dist/assets/TuiOverlayModal-CGyGkKYl.js +0 -1
  217. package/web/dist/assets/TuiOverlayModal-CpBKjG6x.js +0 -1
  218. package/web/dist/assets/app-globals-DcyO0UPi.js +0 -1
  219. package/web/dist/assets/fi-NyN-ZrgD.js +0 -325
  220. package/web/dist/assets/index-DK3F5ZJo.js +0 -85
  221. package/web/dist/assets/index-DQMii2he.js +0 -85
  222. package/web/dist/assets/index-vwBnwzkr.css +0 -1
  223. package/web/dist/assets/plugin-host-BCnX3P8U.js +0 -1
  224. package/web/dist/assets/theme-D2DMH6tH.js +0 -1
@@ -0,0 +1,171 @@
1
+ import { createHash } from "node:crypto";
2
+ import { access, lstat, mkdtemp, open, realpath, rename, rm } from "node:fs/promises";
3
+ import { constants } from "node:fs";
4
+ import { dirname, isAbsolute, join, parse, relative, resolve, sep } from "node:path";
5
+ import { execFile } from "node:child_process";
6
+ import { promisify } from "node:util";
7
+ const run = promisify(execFile);
8
+ const TIMEOUT_MS = 30_000;
9
+ export const hash = (bytes) => createHash("sha256").update(bytes).digest("hex");
10
+ export const missing = (e) => e.code === "ENOENT";
11
+ export const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
12
+ export const identity = (s) => `${s.dev}:${s.ino}:${s.size}:${s.mtimeMs}:${s.ctimeMs}:${s.nlink}`;
13
+ export function checkSignal(signal) {
14
+ signal?.throwIfAborted();
15
+ }
16
+ /** Portable paths only. Case-fold duplicates even on case-sensitive hosts so a
17
+ * bundle retains the same meaning when sent to Windows/macOS. */
18
+ export function deniedPart(part) {
19
+ if (/^(\.git|node_modules)$/i.test(part))
20
+ return "ignored";
21
+ if (/^(\.env.*|\.ssh|\.aws|\.azure|\.gnupg|\.kube|\.npmrc|\.pypirc|\.netrc|_netrc|\.git-credentials|credentials(?:\..*)?|secrets?(?:\..*)?|tokens?(?:\..*)?|id_(?:rsa|dsa|ecdsa|ed25519)(?:\..*)?|authorized_keys|known_hosts)$/i.test(part) ||
22
+ /\.(?:pem|key|p12|pfx|keystore)$/i.test(part))
23
+ return "sensitive";
24
+ return undefined;
25
+ }
26
+ export function safePath(value, allowDenied = false) {
27
+ if (typeof value !== "string" ||
28
+ !value ||
29
+ Buffer.byteLength(value, "utf8") > 1024 ||
30
+ Buffer.from(value, "utf8").toString("utf8") !== value ||
31
+ value.normalize("NFC") !== value ||
32
+ isAbsolute(value) ||
33
+ /[\\:\x00-\x1f\x7f]/.test(value))
34
+ throw new Error("Unsafe file path");
35
+ const parts = value.split("/");
36
+ if (parts.length > 32)
37
+ throw new Error("File path is too deep");
38
+ for (const part of parts) {
39
+ if (!part ||
40
+ part === "." ||
41
+ part === ".." ||
42
+ /[. ]$/.test(part) ||
43
+ Buffer.byteLength(part) > 255 ||
44
+ /[<>"|?*]/.test(part) ||
45
+ /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(?:\.|$)/i.test(part))
46
+ throw new Error("Unsafe file path component");
47
+ if (!allowDenied && deniedPart(part))
48
+ throw new Error("Sensitive file path is denied");
49
+ }
50
+ return value;
51
+ }
52
+ export function within(root, path) {
53
+ const rel = relative(root, path);
54
+ return rel === "" || (!isAbsolute(rel) && rel !== ".." && !rel.startsWith(`..${sep}`));
55
+ }
56
+ /** Reject symlinks/junctions at every existing component, including ancestors. */
57
+ export async function checkChain(path, allowMissing = false, signal) {
58
+ checkSignal(signal);
59
+ const absolute = resolve(path);
60
+ let current = parse(absolute).root;
61
+ const parts = absolute.slice(current.length).split(sep).filter(Boolean);
62
+ for (let i = 0; i < parts.length; i++) {
63
+ current = join(current, parts[i]);
64
+ let s;
65
+ try {
66
+ s = await lstat(current);
67
+ checkSignal(signal);
68
+ }
69
+ catch (e) {
70
+ if (allowMissing && missing(e))
71
+ return;
72
+ throw e;
73
+ }
74
+ if (s.isSymbolicLink())
75
+ throw new Error("Symlink paths are denied");
76
+ if (i < parts.length - 1 && !s.isDirectory())
77
+ throw new Error("Path ancestor is not a directory");
78
+ const canonical = await realpath(current);
79
+ checkSignal(signal);
80
+ if (relative(resolve(current), canonical) !== "")
81
+ throw new Error("Real path changed");
82
+ }
83
+ }
84
+ /** Deterministic JSON tuple hash for manifests */
85
+ export function computeManifestHash(files) {
86
+ const sorted = [...files].sort((a, b) => a.path.localeCompare(b.path));
87
+ const tuples = sorted.map((f) => [f.path, f.size, f.sha256]);
88
+ return hash(JSON.stringify(tuples));
89
+ }
90
+ /** Atomic metadata-preserving save for bytes, shared between file-sync and transfer-stream. */
91
+ export async function saveBytesPreservingMetadata({ path, bytes, baseline, signal, }) {
92
+ checkSignal(signal);
93
+ if (!["linux", "darwin", "freebsd", "win32"].includes(process.platform))
94
+ throw new Error(`Metadata-preserving saves unsupported on platform: ${process.platform}`);
95
+ await access(path, constants.W_OK);
96
+ const stageDir = await mkdtemp(join(dirname(path), ".pi-save-"));
97
+ const staged = join(stageDir, "content");
98
+ const backup = join(stageDir, "original");
99
+ let committed = false;
100
+ try {
101
+ checkSignal(signal);
102
+ if (process.platform !== "win32") {
103
+ await run("cp", process.platform === "linux"
104
+ ? ["--preserve=mode,ownership,timestamps,xattr", "--", path, staged]
105
+ : ["-p", path, staged], {
106
+ timeout: TIMEOUT_MS,
107
+ signal,
108
+ });
109
+ }
110
+ const handle = await open(staged, process.platform === "win32" ? "wx" : "r+", 0o600);
111
+ try {
112
+ checkSignal(signal);
113
+ await handle.writeFile(bytes);
114
+ await handle.truncate(bytes.length);
115
+ await handle.sync();
116
+ }
117
+ finally {
118
+ await handle.close();
119
+ }
120
+ if (process.platform === "linux") {
121
+ await run("cp", ["--attributes-only", "--preserve=mode,ownership,timestamps,xattr", "--", path, staged], {
122
+ timeout: TIMEOUT_MS,
123
+ signal,
124
+ });
125
+ }
126
+ checkSignal(signal);
127
+ const currentStat = await lstat(path);
128
+ if (baseline && baseline.identity !== identity(currentStat)) {
129
+ throw new Error("Baseline changed before replacement");
130
+ }
131
+ await checkChain(stageDir, false, signal);
132
+ if (process.platform === "win32") {
133
+ const script = "$ErrorActionPreference='Stop'; try { [IO.File]::Replace($env:PI_SAVE_SOURCE,$env:PI_SAVE_TARGET,$env:PI_SAVE_BACKUP,$false) } catch { [Console]::Error.WriteLine($_.Exception.ToString()); exit 1 }";
134
+ await run("powershell.exe", [
135
+ "-NoLogo",
136
+ "-NoProfile",
137
+ "-NonInteractive",
138
+ "-EncodedCommand",
139
+ Buffer.from(script, "utf16le").toString("base64"),
140
+ ], {
141
+ timeout: TIMEOUT_MS,
142
+ signal,
143
+ windowsHide: true,
144
+ env: { ...process.env, PI_SAVE_SOURCE: staged, PI_SAVE_TARGET: path, PI_SAVE_BACKUP: backup },
145
+ });
146
+ }
147
+ else {
148
+ await rename(staged, path);
149
+ }
150
+ committed = true;
151
+ }
152
+ catch (error) {
153
+ const hasBackup = await lstat(backup).then(() => true, (e) => {
154
+ if (missing(e))
155
+ return false;
156
+ throw e;
157
+ });
158
+ if (hasBackup)
159
+ throw new Error(`Replacement failed; recovery retained at ${backup}`, { cause: error });
160
+ throw error;
161
+ }
162
+ finally {
163
+ const hasBackup = await lstat(backup).then(() => true, (e) => {
164
+ if (missing(e))
165
+ return false;
166
+ throw e;
167
+ });
168
+ if (committed || !hasBackup)
169
+ await rm(stageDir, { recursive: true, force: true });
170
+ }
171
+ }
@@ -1,91 +1,35 @@
1
- import { createHash, randomUUID } from "node:crypto";
1
+ import { randomUUID } from "node:crypto";
2
2
  import { constants } from "node:fs";
3
- import { access, lstat, mkdir, mkdtemp, open, realpath, rename, rm } from "node:fs/promises";
4
- import { dirname, isAbsolute, join, parse, relative, resolve, sep } from "node:path";
3
+ import { access, lstat, mkdir, mkdtemp, open, opendir, realpath, rename, rm } from "node:fs/promises";
4
+ import { dirname, join, resolve } from "node:path";
5
5
  import { execFile } from "node:child_process";
6
6
  import { promisify } from "node:util";
7
+ import { createChunkedTransferReceiver, prepareChunkedTransfer, readChunkFromSource, CHUNKED_TRANSFER_LIMITS, } from "./transfer-stream.js";
8
+ export { CHUNKED_TRANSFER_LIMITS, createChunkedTransferReceiver, prepareChunkedTransfer, readChunkFromSource, };
7
9
  export const DEVICE_FILE_SYNC_LIMITS = Object.freeze({
8
10
  bytes: 8 * 1024 * 1024,
9
11
  files: 128,
10
12
  staged: 16,
11
13
  stagedBytes: 32 * 1024 * 1024,
14
+ visitedEntries: 4096,
15
+ exclusions: 128,
16
+ exclusionBytes: 8 * 1024,
12
17
  });
13
- const hash = (bytes) => createHash("sha256").update(bytes).digest("hex");
18
+ import { hash, missing, same, identity, checkSignal, deniedPart, safePath, within, checkChain, } from "./file-sync-paths.js";
14
19
  const run = promisify(execFile);
15
- const missing = (e) => e.code === "ENOENT";
16
- const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
17
- const identity = (s) => `${s.dev}:${s.ino}:${s.size}:${s.mtimeMs}:${s.ctimeMs}:${s.nlink}`;
18
- function checkSignal(signal) {
19
- signal?.throwIfAborted();
20
- }
21
- /** Portable paths only. Case-fold duplicates even on case-sensitive hosts so a
22
- * bundle retains the same meaning when sent to Windows/macOS. */
23
- function safePath(value) {
24
- if (typeof value !== "string" ||
25
- !value ||
26
- Buffer.byteLength(value, "utf8") > 1024 ||
27
- Buffer.from(value, "utf8").toString("utf8") !== value ||
28
- value.normalize("NFC") !== value ||
29
- isAbsolute(value) ||
30
- /[\\:\x00-\x1f\x7f]/.test(value))
31
- throw new Error("Unsafe file path");
32
- const parts = value.split("/");
33
- if (parts.length > 32)
34
- throw new Error("File path is too deep");
35
- for (const part of parts) {
36
- if (!part ||
37
- part === "." ||
38
- part === ".." ||
39
- /[. ]$/.test(part) ||
40
- Buffer.byteLength(part) > 255 ||
41
- /[<>"|?*]/.test(part) ||
42
- /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(?:\.|$)/i.test(part))
43
- throw new Error("Unsafe file path component");
44
- if (/^(\.git|node_modules|\.env(?:\..*)?|\.ssh|\.aws|\.azure|\.gnupg|\.kube|\.npmrc|\.pypirc|\.netrc|_netrc|\.git-credentials|credentials(?:\..*)?|secrets?(?:\..*)?|tokens?(?:\..*)?|id_(?:rsa|dsa|ecdsa|ed25519)(?:\..*)?|authorized_keys|known_hosts)$/i.test(part) ||
45
- /\.(?:pem|key|p12|pfx|keystore)$/i.test(part))
46
- throw new Error("Sensitive file path is denied");
47
- }
48
- return value;
49
- }
50
- function within(root, path) {
51
- const rel = relative(root, path);
52
- return rel === "" || (!isAbsolute(rel) && rel !== ".." && !rel.startsWith(`..${sep}`));
53
- }
54
- /** Reject symlinks/junctions at every existing component, including ancestors. */
55
- async function checkChain(path, allowMissing = false) {
56
- const absolute = resolve(path);
57
- let current = parse(absolute).root;
58
- const parts = absolute.slice(current.length).split(sep).filter(Boolean);
59
- for (let i = 0; i < parts.length; i++) {
60
- current = join(current, parts[i]);
61
- let s;
62
- try {
63
- s = await lstat(current);
64
- }
65
- catch (e) {
66
- if (allowMissing && missing(e))
67
- return;
68
- throw e;
69
- }
70
- if (s.isSymbolicLink())
71
- throw new Error("Symlink paths are denied");
72
- if (i < parts.length - 1 && !s.isDirectory())
73
- throw new Error("Path ancestor is not a directory");
74
- if (relative(resolve(current), await realpath(current)) !== "")
75
- throw new Error("Real path changed");
76
- }
77
- }
78
20
  /** Local capability: root never comes from an incoming bundle. No execution,
79
- * deletion or implicit directory traversal. Staged transfers are process-local;
21
+ * deletion or implicit directory traversal (recursive export is opt-in). Staged transfers are process-local;
80
22
  * close/cancel remove only this instance's private transfer directories. Node
81
23
  * path checks cannot exclude a hostile OS user racing filesystem operations. */
82
24
  export function createDeviceFileSync(config) {
25
+ const effectiveLimits = { ...DEVICE_FILE_SYNC_LIMITS, ...config.limits };
83
26
  const root = resolve(config.root);
84
27
  const dataDir = resolve(config.dataDir);
85
28
  const allowReceive = config.allowReceive === true;
86
29
  const storage = join(dataDir, "device-transfers");
87
30
  if (within(root, dataDir) || within(root, storage))
88
31
  throw new Error("File sync dataDir and transfer storage must be outside the project root");
32
+ const chunkedReceiver = createChunkedTransferReceiver(config);
89
33
  const transfers = new Map();
90
34
  let total = 0;
91
35
  let closed = false;
@@ -100,29 +44,39 @@ export function createDeviceFileSync(config) {
100
44
  throw new Error("File sync is closed");
101
45
  checkSignal(signal);
102
46
  }
103
- async function roots() {
104
- await checkChain(root);
105
- if (!(await lstat(root)).isDirectory())
47
+ async function roots(signal) {
48
+ await checkChain(root, false, signal);
49
+ active(signal);
50
+ const stats = await lstat(root);
51
+ active(signal);
52
+ if (!stats.isDirectory())
106
53
  throw new Error("Project root must be a directory");
107
- await checkChain(storage, true);
108
- if (within(await realpath(root), dataDir))
54
+ await checkChain(storage, true, signal);
55
+ active(signal);
56
+ const canonical = await realpath(root);
57
+ active(signal);
58
+ if (within(canonical, dataDir))
109
59
  throw new Error("Unsafe data directory");
110
60
  }
111
- async function target(path) {
61
+ async function target(path, signal) {
112
62
  safePath(path);
113
- await roots();
63
+ await roots(signal);
64
+ active(signal);
114
65
  const full = join(root, ...path.split("/"));
115
66
  if (!within(root, full))
116
67
  throw new Error("Target escapes project root");
117
- await checkChain(full, true);
68
+ await checkChain(full, true, signal);
69
+ active(signal);
118
70
  return full;
119
71
  }
120
- async function readFile(path, signal) {
72
+ async function readFile(path, signal, remainingBytes = effectiveLimits.bytes) {
73
+ active(signal);
74
+ const full = await target(path, signal);
121
75
  active(signal);
122
- const full = await target(path);
123
76
  let before;
124
77
  try {
125
78
  before = await lstat(full);
79
+ active(signal);
126
80
  }
127
81
  catch (e) {
128
82
  if (missing(e))
@@ -131,11 +85,13 @@ export function createDeviceFileSync(config) {
131
85
  }
132
86
  if (!before.isFile() || before.nlink > 1)
133
87
  throw new Error("Target must be a single-link regular file");
134
- if (before.size > DEVICE_FILE_SYNC_LIMITS.bytes)
88
+ if (before.size > remainingBytes)
135
89
  throw new Error("Target exceeds file budget");
136
90
  const handle = await open(full, constants.O_RDONLY | (constants.O_NOFOLLOW || 0));
137
91
  try {
92
+ active(signal);
138
93
  const opened = await handle.stat();
94
+ active(signal);
139
95
  if (!opened.isFile() || identity(opened) !== identity(before))
140
96
  throw new Error("File changed while opening");
141
97
  // Fixed buffer prevents unbounded allocation if a local writer grows it.
@@ -144,14 +100,18 @@ export function createDeviceFileSync(config) {
144
100
  while (count < buffer.length) {
145
101
  active(signal);
146
102
  const result = await handle.read(buffer, count, buffer.length - count, count);
103
+ active(signal);
147
104
  if (!result.bytesRead)
148
105
  break;
149
106
  count += result.bytesRead;
150
107
  }
151
- await target(path);
152
- if (count !== before.size ||
153
- identity(await handle.stat()) !== identity(before) ||
154
- identity(await lstat(full)) !== identity(before))
108
+ await target(path, signal);
109
+ active(signal);
110
+ const afterOpen = await handle.stat();
111
+ active(signal);
112
+ const afterPath = await lstat(full);
113
+ active(signal);
114
+ if (count !== before.size || identity(afterOpen) !== identity(before) || identity(afterPath) !== identity(before))
155
115
  throw new Error("File changed while reading");
156
116
  const bytes = buffer.subarray(0, count);
157
117
  return { bytes, snapshot: { hash: hash(bytes), identity: identity(before) } };
@@ -167,7 +127,7 @@ export function createDeviceFileSync(config) {
167
127
  !Array.isArray(bundle.manifest.files) ||
168
128
  !Array.isArray(bundle.files) ||
169
129
  !bundle.files.length ||
170
- bundle.files.length > DEVICE_FILE_SYNC_LIMITS.files ||
130
+ bundle.files.length > effectiveLimits.files ||
171
131
  bundle.files.length !== bundle.manifest.files.length)
172
132
  throw new Error("Invalid bundle manifest");
173
133
  const seen = new Set();
@@ -184,7 +144,7 @@ export function createDeviceFileSync(config) {
184
144
  seen.add(key);
185
145
  if (!Number.isSafeInteger(entry.size) ||
186
146
  entry.size < 0 ||
187
- (size += entry.size) > DEVICE_FILE_SYNC_LIMITS.bytes ||
147
+ (size += entry.size) > effectiveLimits.bytes ||
188
148
  typeof entry.sha256 !== "string" ||
189
149
  !/^[a-f0-9]{64}$/.test(entry.sha256) ||
190
150
  file?.path !== path ||
@@ -203,7 +163,26 @@ export function createDeviceFileSync(config) {
203
163
  for (const other of seen)
204
164
  if (other.startsWith(`${key}/`))
205
165
  throw new Error("Bundle file/ancestor collision");
206
- return { manifest: { version: 1, totalBytes: size, files: entries }, files };
166
+ let summary = {};
167
+ if (bundle.manifest.exclusions !== undefined || bundle.manifest.totalExcluded !== undefined) {
168
+ const { exclusions, totalExcluded } = bundle.manifest;
169
+ if (!Array.isArray(exclusions) ||
170
+ exclusions.length > effectiveLimits.exclusions ||
171
+ !Number.isSafeInteger(totalExcluded) ||
172
+ totalExcluded < exclusions.length ||
173
+ totalExcluded < 1)
174
+ throw new Error("Invalid exclusions summary");
175
+ const sanitized = exclusions.map((item) => {
176
+ const path = safePath(item?.path, true);
177
+ if (item.reason !== "ignored" && item.reason !== "sensitive")
178
+ throw new Error("Invalid exclusion reason");
179
+ return { path, reason: item.reason };
180
+ });
181
+ if (Buffer.byteLength(JSON.stringify(sanitized)) > effectiveLimits.exclusionBytes)
182
+ throw new Error("Exclusions summary exceeds budget");
183
+ summary = { exclusions: sanitized, totalExcluded };
184
+ }
185
+ return { manifest: { version: 1, totalBytes: size, files: entries, ...summary }, files };
207
186
  }
208
187
  async function makePreview(id, bundle, signal) {
209
188
  const baselines = [];
@@ -330,30 +309,127 @@ export function createDeviceFileSync(config) {
330
309
  }
331
310
  }
332
311
  return {
333
- prepare({ paths, signal }) {
312
+ prepare({ paths, signal, recursive = false, }) {
334
313
  return serialized(async () => {
335
314
  active(signal);
336
- if (!Array.isArray(paths) || !paths.length || paths.length > DEVICE_FILE_SYNC_LIMITS.files)
315
+ if (!Array.isArray(paths) || !paths.length || paths.length > effectiveLimits.files)
337
316
  throw new Error("Invalid file count");
317
+ if (typeof recursive !== "boolean")
318
+ throw new Error("Invalid recursive option");
319
+ const selected = paths.map((path) => safePath(path)).sort();
320
+ for (let i = 0; i < selected.length; i++) {
321
+ const key = selected[i].toLowerCase();
322
+ if (selected.some((other, j) => j !== i && (other.toLowerCase() === key || key.startsWith(`${other.toLowerCase()}/`))))
323
+ throw new Error("Duplicate or overlapping selected path");
324
+ }
338
325
  const files = [];
339
326
  const entries = [];
327
+ const exclusions = [];
328
+ let totalExcluded = 0;
329
+ let summaryFull = false;
340
330
  let bytes = 0;
331
+ let visited = 0;
332
+ let discoveredFiles = 0;
341
333
  const seen = new Set();
342
- for (const path of paths) {
343
- const key = safePath(path).toLowerCase();
334
+ const countVisit = () => {
335
+ active(signal);
336
+ if (++visited > effectiveLimits.visitedEntries)
337
+ throw new Error("Directory scan entry budget exceeded");
338
+ };
339
+ const visit = async (path, selectedPath = false) => {
340
+ active(signal);
341
+ const key = path.toLowerCase();
344
342
  if (seen.has(key))
345
343
  throw new Error("Duplicate bundle path");
346
344
  seen.add(key);
347
- const file = await readFile(path, signal);
345
+ safePath(path, true);
346
+ const reason = deniedPart(path.split("/").at(-1));
347
+ if (!selectedPath && reason) {
348
+ const excluded = join(root, ...path.split("/"));
349
+ await checkChain(excluded, false, signal);
350
+ active(signal);
351
+ totalExcluded++;
352
+ const item = { path, reason };
353
+ if (!summaryFull &&
354
+ exclusions.length < effectiveLimits.exclusions &&
355
+ Buffer.byteLength(JSON.stringify([...exclusions, item])) <= effectiveLimits.exclusionBytes)
356
+ exclusions.push(item);
357
+ else
358
+ summaryFull = true;
359
+ return;
360
+ }
361
+ const full = await target(path, signal);
362
+ active(signal);
363
+ const before = await lstat(full);
364
+ active(signal);
365
+ if (before.isDirectory()) {
366
+ if (!recursive)
367
+ throw new Error("Directory selection requires recursive: true");
368
+ const directory = await opendir(full);
369
+ const names = [];
370
+ try {
371
+ active(signal);
372
+ while (true) {
373
+ const entry = await directory.read();
374
+ active(signal);
375
+ if (!entry)
376
+ break;
377
+ countVisit();
378
+ // Reject links even when their names would otherwise be excluded.
379
+ if (entry.isSymbolicLink())
380
+ throw new Error("Symlink paths are denied");
381
+ names.push(entry.name);
382
+ }
383
+ }
384
+ finally {
385
+ await directory.close();
386
+ }
387
+ active(signal);
388
+ await target(path, signal);
389
+ active(signal);
390
+ const opened = await lstat(full);
391
+ active(signal);
392
+ if (identity(opened) !== identity(before))
393
+ throw new Error("Directory changed while scanning");
394
+ for (const name of names.sort()) {
395
+ await visit(`${path}/${name}`);
396
+ active(signal);
397
+ }
398
+ await target(path, signal);
399
+ active(signal);
400
+ const after = await lstat(full);
401
+ active(signal);
402
+ if (identity(after) !== identity(before))
403
+ throw new Error("Directory changed while scanning");
404
+ return;
405
+ }
406
+ if (++discoveredFiles > effectiveLimits.files)
407
+ throw new Error("Bundle exceeds file count budget");
408
+ const file = await readFile(path, signal, effectiveLimits.bytes - bytes);
409
+ active(signal);
348
410
  if (!file)
349
411
  throw new Error("Source file does not exist");
350
- if ((bytes += file.bytes.length) > DEVICE_FILE_SYNC_LIMITS.bytes)
351
- throw new Error("Bundle exceeds byte budget");
412
+ bytes += file.bytes.length;
352
413
  entries.push({ path, size: file.bytes.length, sha256: file.snapshot.hash });
353
414
  files.push({ path, base64: file.bytes.toString("base64") });
415
+ };
416
+ for (const path of selected) {
417
+ countVisit();
418
+ await visit(path, true);
419
+ active(signal);
354
420
  }
421
+ if (!files.length)
422
+ throw new Error("Selection contains no transferable regular files");
355
423
  active(signal);
356
- return { manifest: { version: 1, totalBytes: bytes, files: entries }, files };
424
+ return {
425
+ manifest: {
426
+ version: 1,
427
+ totalBytes: bytes,
428
+ files: entries,
429
+ ...(totalExcluded ? { exclusions, totalExcluded } : {}),
430
+ },
431
+ files,
432
+ };
357
433
  });
358
434
  },
359
435
  stage(input, { signal } = {}) {
@@ -362,8 +438,8 @@ export function createDeviceFileSync(config) {
362
438
  if (!allowReceive)
363
439
  throw new Error("Receiving files is disabled");
364
440
  const bundle = validate(input);
365
- if (transfers.size >= DEVICE_FILE_SYNC_LIMITS.staged ||
366
- total + bundle.manifest.totalBytes > DEVICE_FILE_SYNC_LIMITS.stagedBytes)
441
+ if (transfers.size >= effectiveLimits.staged ||
442
+ total + bundle.manifest.totalBytes > effectiveLimits.stagedBytes)
367
443
  throw new Error("Staging budget exceeded");
368
444
  const id = randomUUID();
369
445
  const result = await makePreview(id, bundle, signal);
@@ -482,9 +558,23 @@ export function createDeviceFileSync(config) {
482
558
  await drop(id);
483
559
  });
484
560
  },
561
+ prepareChunked({ paths, signal, recursive = false, chunkSize, transferId, }) {
562
+ return prepareChunkedTransfer({ root, paths, recursive, chunkSize, transferId, signal });
563
+ },
564
+ readChunk({ path, offset, size, expectedFileSize, expectedChunkSha256, signal, }) {
565
+ return readChunkFromSource({ root, path, offset, size, expectedFileSize, expectedChunkSha256, signal });
566
+ },
567
+ initChunkedTransfer: chunkedReceiver.initTransfer,
568
+ writeTransferChunk: chunkedReceiver.writeChunk,
569
+ getTransferStatus: chunkedReceiver.getStatus,
570
+ abortChunkedTransfer: chunkedReceiver.abortTransfer,
571
+ getChunkedFilePage: chunkedReceiver.getFilePage,
572
+ previewChunked: chunkedReceiver.preview,
573
+ applyChunked: chunkedReceiver.apply,
485
574
  close() {
486
575
  closed = true;
487
576
  return serialized(async () => {
577
+ await chunkedReceiver.close();
488
578
  for (const id of transfers.keys())
489
579
  await drop(id);
490
580
  });
@@ -0,0 +1,37 @@
1
+ // Serialize explicitly so object insertion order cannot change equality. Array order is significant.
2
+ function chunkKey(message) {
3
+ return JSON.stringify([
4
+ message.id,
5
+ message.textStart,
6
+ message.textEnd,
7
+ message.fullTextLength,
8
+ message.text,
9
+ message.sender.type,
10
+ message.sender.id,
11
+ message.sender.name,
12
+ message.createdAt,
13
+ message.targetBotIds,
14
+ ]);
15
+ }
16
+ /**
17
+ * Previous must aggregate ONLY exact chunks still present in the active model context, with
18
+ * the newest delivered throughMessageId. A persisted transcript or last planned snapshot
19
+ * cannot establish that evidence, especially after compaction. Omit previous when uncertain.
20
+ * This filters history only: callers must always retain the complete current task text.
21
+ * A snapshot remains bounded by current.truncated/retentionLimit; it never claims full history.
22
+ */
23
+ export function planGroupContext(current, previous) {
24
+ if (!previous || previous.roomId !== current.roomId) {
25
+ return { ...current, delivery: { mode: "snapshot" } };
26
+ }
27
+ const previousThroughMessageId = previous.throughMessageId;
28
+ if (previousThroughMessageId !== null && !current.messages.some((row) => row.id === previousThroughMessageId)) {
29
+ return { ...current, delivery: { mode: "snapshot", previousThroughMessageId, gap: true } };
30
+ }
31
+ const present = new Set(previous.messages.map(chunkKey));
32
+ return {
33
+ ...current,
34
+ messages: current.messages.filter((row) => !present.has(chunkKey(row))),
35
+ delivery: { mode: "delta", previousThroughMessageId },
36
+ };
37
+ }