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,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,82 +1,24 @@
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) {
@@ -86,6 +28,7 @@ export function createDeviceFileSync(config) {
86
28
  const storage = join(dataDir, "device-transfers");
87
29
  if (within(root, dataDir) || within(root, storage))
88
30
  throw new Error("File sync dataDir and transfer storage must be outside the project root");
31
+ const chunkedReceiver = createChunkedTransferReceiver(config);
89
32
  const transfers = new Map();
90
33
  let total = 0;
91
34
  let closed = false;
@@ -100,29 +43,39 @@ export function createDeviceFileSync(config) {
100
43
  throw new Error("File sync is closed");
101
44
  checkSignal(signal);
102
45
  }
103
- async function roots() {
104
- await checkChain(root);
105
- if (!(await lstat(root)).isDirectory())
46
+ async function roots(signal) {
47
+ await checkChain(root, false, signal);
48
+ active(signal);
49
+ const stats = await lstat(root);
50
+ active(signal);
51
+ if (!stats.isDirectory())
106
52
  throw new Error("Project root must be a directory");
107
- await checkChain(storage, true);
108
- if (within(await realpath(root), dataDir))
53
+ await checkChain(storage, true, signal);
54
+ active(signal);
55
+ const canonical = await realpath(root);
56
+ active(signal);
57
+ if (within(canonical, dataDir))
109
58
  throw new Error("Unsafe data directory");
110
59
  }
111
- async function target(path) {
60
+ async function target(path, signal) {
112
61
  safePath(path);
113
- await roots();
62
+ await roots(signal);
63
+ active(signal);
114
64
  const full = join(root, ...path.split("/"));
115
65
  if (!within(root, full))
116
66
  throw new Error("Target escapes project root");
117
- await checkChain(full, true);
67
+ await checkChain(full, true, signal);
68
+ active(signal);
118
69
  return full;
119
70
  }
120
- async function readFile(path, signal) {
71
+ async function readFile(path, signal, remainingBytes = DEVICE_FILE_SYNC_LIMITS.bytes) {
72
+ active(signal);
73
+ const full = await target(path, signal);
121
74
  active(signal);
122
- const full = await target(path);
123
75
  let before;
124
76
  try {
125
77
  before = await lstat(full);
78
+ active(signal);
126
79
  }
127
80
  catch (e) {
128
81
  if (missing(e))
@@ -131,11 +84,13 @@ export function createDeviceFileSync(config) {
131
84
  }
132
85
  if (!before.isFile() || before.nlink > 1)
133
86
  throw new Error("Target must be a single-link regular file");
134
- if (before.size > DEVICE_FILE_SYNC_LIMITS.bytes)
87
+ if (before.size > remainingBytes)
135
88
  throw new Error("Target exceeds file budget");
136
89
  const handle = await open(full, constants.O_RDONLY | (constants.O_NOFOLLOW || 0));
137
90
  try {
91
+ active(signal);
138
92
  const opened = await handle.stat();
93
+ active(signal);
139
94
  if (!opened.isFile() || identity(opened) !== identity(before))
140
95
  throw new Error("File changed while opening");
141
96
  // Fixed buffer prevents unbounded allocation if a local writer grows it.
@@ -144,14 +99,18 @@ export function createDeviceFileSync(config) {
144
99
  while (count < buffer.length) {
145
100
  active(signal);
146
101
  const result = await handle.read(buffer, count, buffer.length - count, count);
102
+ active(signal);
147
103
  if (!result.bytesRead)
148
104
  break;
149
105
  count += result.bytesRead;
150
106
  }
151
- await target(path);
152
- if (count !== before.size ||
153
- identity(await handle.stat()) !== identity(before) ||
154
- identity(await lstat(full)) !== identity(before))
107
+ await target(path, signal);
108
+ active(signal);
109
+ const afterOpen = await handle.stat();
110
+ active(signal);
111
+ const afterPath = await lstat(full);
112
+ active(signal);
113
+ if (count !== before.size || identity(afterOpen) !== identity(before) || identity(afterPath) !== identity(before))
155
114
  throw new Error("File changed while reading");
156
115
  const bytes = buffer.subarray(0, count);
157
116
  return { bytes, snapshot: { hash: hash(bytes), identity: identity(before) } };
@@ -203,7 +162,26 @@ export function createDeviceFileSync(config) {
203
162
  for (const other of seen)
204
163
  if (other.startsWith(`${key}/`))
205
164
  throw new Error("Bundle file/ancestor collision");
206
- return { manifest: { version: 1, totalBytes: size, files: entries }, files };
165
+ let summary = {};
166
+ if (bundle.manifest.exclusions !== undefined || bundle.manifest.totalExcluded !== undefined) {
167
+ const { exclusions, totalExcluded } = bundle.manifest;
168
+ if (!Array.isArray(exclusions) ||
169
+ exclusions.length > DEVICE_FILE_SYNC_LIMITS.exclusions ||
170
+ !Number.isSafeInteger(totalExcluded) ||
171
+ totalExcluded < exclusions.length ||
172
+ totalExcluded < 1)
173
+ throw new Error("Invalid exclusions summary");
174
+ const sanitized = exclusions.map((item) => {
175
+ const path = safePath(item?.path, true);
176
+ if (item.reason !== "ignored" && item.reason !== "sensitive")
177
+ throw new Error("Invalid exclusion reason");
178
+ return { path, reason: item.reason };
179
+ });
180
+ if (Buffer.byteLength(JSON.stringify(sanitized)) > DEVICE_FILE_SYNC_LIMITS.exclusionBytes)
181
+ throw new Error("Exclusions summary exceeds budget");
182
+ summary = { exclusions: sanitized, totalExcluded };
183
+ }
184
+ return { manifest: { version: 1, totalBytes: size, files: entries, ...summary }, files };
207
185
  }
208
186
  async function makePreview(id, bundle, signal) {
209
187
  const baselines = [];
@@ -330,30 +308,127 @@ export function createDeviceFileSync(config) {
330
308
  }
331
309
  }
332
310
  return {
333
- prepare({ paths, signal }) {
311
+ prepare({ paths, signal, recursive = false, }) {
334
312
  return serialized(async () => {
335
313
  active(signal);
336
314
  if (!Array.isArray(paths) || !paths.length || paths.length > DEVICE_FILE_SYNC_LIMITS.files)
337
315
  throw new Error("Invalid file count");
316
+ if (typeof recursive !== "boolean")
317
+ throw new Error("Invalid recursive option");
318
+ const selected = paths.map((path) => safePath(path)).sort();
319
+ for (let i = 0; i < selected.length; i++) {
320
+ const key = selected[i].toLowerCase();
321
+ if (selected.some((other, j) => j !== i && (other.toLowerCase() === key || key.startsWith(`${other.toLowerCase()}/`))))
322
+ throw new Error("Duplicate or overlapping selected path");
323
+ }
338
324
  const files = [];
339
325
  const entries = [];
326
+ const exclusions = [];
327
+ let totalExcluded = 0;
328
+ let summaryFull = false;
340
329
  let bytes = 0;
330
+ let visited = 0;
331
+ let discoveredFiles = 0;
341
332
  const seen = new Set();
342
- for (const path of paths) {
343
- const key = safePath(path).toLowerCase();
333
+ const countVisit = () => {
334
+ active(signal);
335
+ if (++visited > DEVICE_FILE_SYNC_LIMITS.visitedEntries)
336
+ throw new Error("Directory scan entry budget exceeded");
337
+ };
338
+ const visit = async (path, selectedPath = false) => {
339
+ active(signal);
340
+ const key = path.toLowerCase();
344
341
  if (seen.has(key))
345
342
  throw new Error("Duplicate bundle path");
346
343
  seen.add(key);
347
- const file = await readFile(path, signal);
344
+ safePath(path, true);
345
+ const reason = deniedPart(path.split("/").at(-1));
346
+ if (!selectedPath && reason) {
347
+ const excluded = join(root, ...path.split("/"));
348
+ await checkChain(excluded, false, signal);
349
+ active(signal);
350
+ totalExcluded++;
351
+ const item = { path, reason };
352
+ if (!summaryFull &&
353
+ exclusions.length < DEVICE_FILE_SYNC_LIMITS.exclusions &&
354
+ Buffer.byteLength(JSON.stringify([...exclusions, item])) <= DEVICE_FILE_SYNC_LIMITS.exclusionBytes)
355
+ exclusions.push(item);
356
+ else
357
+ summaryFull = true;
358
+ return;
359
+ }
360
+ const full = await target(path, signal);
361
+ active(signal);
362
+ const before = await lstat(full);
363
+ active(signal);
364
+ if (before.isDirectory()) {
365
+ if (!recursive)
366
+ throw new Error("Directory selection requires recursive: true");
367
+ const directory = await opendir(full);
368
+ const names = [];
369
+ try {
370
+ active(signal);
371
+ while (true) {
372
+ const entry = await directory.read();
373
+ active(signal);
374
+ if (!entry)
375
+ break;
376
+ countVisit();
377
+ // Reject links even when their names would otherwise be excluded.
378
+ if (entry.isSymbolicLink())
379
+ throw new Error("Symlink paths are denied");
380
+ names.push(entry.name);
381
+ }
382
+ }
383
+ finally {
384
+ await directory.close();
385
+ }
386
+ active(signal);
387
+ await target(path, signal);
388
+ active(signal);
389
+ const opened = await lstat(full);
390
+ active(signal);
391
+ if (identity(opened) !== identity(before))
392
+ throw new Error("Directory changed while scanning");
393
+ for (const name of names.sort()) {
394
+ await visit(`${path}/${name}`);
395
+ active(signal);
396
+ }
397
+ await target(path, signal);
398
+ active(signal);
399
+ const after = await lstat(full);
400
+ active(signal);
401
+ if (identity(after) !== identity(before))
402
+ throw new Error("Directory changed while scanning");
403
+ return;
404
+ }
405
+ if (++discoveredFiles > DEVICE_FILE_SYNC_LIMITS.files)
406
+ throw new Error("Bundle exceeds file count budget");
407
+ const file = await readFile(path, signal, DEVICE_FILE_SYNC_LIMITS.bytes - bytes);
408
+ active(signal);
348
409
  if (!file)
349
410
  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");
411
+ bytes += file.bytes.length;
352
412
  entries.push({ path, size: file.bytes.length, sha256: file.snapshot.hash });
353
413
  files.push({ path, base64: file.bytes.toString("base64") });
414
+ };
415
+ for (const path of selected) {
416
+ countVisit();
417
+ await visit(path, true);
418
+ active(signal);
354
419
  }
420
+ if (!files.length)
421
+ throw new Error("Selection contains no transferable regular files");
355
422
  active(signal);
356
- return { manifest: { version: 1, totalBytes: bytes, files: entries }, files };
423
+ return {
424
+ manifest: {
425
+ version: 1,
426
+ totalBytes: bytes,
427
+ files: entries,
428
+ ...(totalExcluded ? { exclusions, totalExcluded } : {}),
429
+ },
430
+ files,
431
+ };
357
432
  });
358
433
  },
359
434
  stage(input, { signal } = {}) {
@@ -482,9 +557,23 @@ export function createDeviceFileSync(config) {
482
557
  await drop(id);
483
558
  });
484
559
  },
560
+ prepareChunked({ paths, signal, recursive = false, chunkSize, transferId, }) {
561
+ return prepareChunkedTransfer({ root, paths, recursive, chunkSize, transferId, signal });
562
+ },
563
+ readChunk({ path, offset, size, expectedFileSize, expectedChunkSha256, signal, }) {
564
+ return readChunkFromSource({ root, path, offset, size, expectedFileSize, expectedChunkSha256, signal });
565
+ },
566
+ initChunkedTransfer: chunkedReceiver.initTransfer,
567
+ writeTransferChunk: chunkedReceiver.writeChunk,
568
+ getTransferStatus: chunkedReceiver.getStatus,
569
+ abortChunkedTransfer: chunkedReceiver.abortTransfer,
570
+ getChunkedFilePage: chunkedReceiver.getFilePage,
571
+ previewChunked: chunkedReceiver.preview,
572
+ applyChunked: chunkedReceiver.apply,
485
573
  close() {
486
574
  closed = true;
487
575
  return serialized(async () => {
576
+ await chunkedReceiver.close();
488
577
  for (const id of transfers.keys())
489
578
  await drop(id);
490
579
  });
@@ -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
+ }