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,216 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { createHash } from "node:crypto";
4
+ import { writeJsonAtomicSync } from "../atomic-file.js";
5
+ import { createTaskReportStore, MAX_TASK_FULL_REPORT_BYTES } from "./task-report.js";
6
+ import { checkedUrl } from "./relay.js";
7
+ export const REPORT_OUTBOX_MAX_ENTRIES = 128;
8
+ export const REPORT_OUTBOX_MAX_BYTES = 64 * 1024 * 1024;
9
+ const ACCEPTED_RETENTION = 32;
10
+ const errors = new Set(["Report exceeds 4 MiB quota", "Executor supplied no full report", "Report upload pending"]);
11
+ const bindingKeys = ["id", "attemptId", "roomId", "botId"];
12
+ function binding(task) {
13
+ for (const field of bindingKeys)
14
+ if (typeof task[field] !== "string" || !task[field] || task[field].length > 256)
15
+ throw new Error("Invalid report binding");
16
+ if (task.botRevision !== undefined && (!Number.isSafeInteger(task.botRevision) || task.botRevision < 1))
17
+ throw new Error("Invalid report Bot revision");
18
+ return {
19
+ id: task.id,
20
+ attemptId: task.attemptId,
21
+ roomId: task.roomId,
22
+ botId: task.botId,
23
+ ...(task.botRevision ? { botRevision: task.botRevision } : {}),
24
+ };
25
+ }
26
+ function validEntry(value) {
27
+ if (!value || typeof value !== "object" || Array.isArray(value))
28
+ return false;
29
+ const e = value;
30
+ try {
31
+ binding(e);
32
+ }
33
+ catch {
34
+ return false;
35
+ }
36
+ const allowed = new Set([
37
+ ...bindingKeys,
38
+ "botRevision",
39
+ "reportRef",
40
+ "sha256",
41
+ "totalBytes",
42
+ "uploadPending",
43
+ "missing",
44
+ "rejected",
45
+ "lastError",
46
+ ]);
47
+ return (Object.keys(e).every((key) => allowed.has(key)) &&
48
+ Number.isSafeInteger(e.totalBytes) &&
49
+ e.totalBytes >= 0 &&
50
+ ["uploadPending", "missing", "rejected"].every((key) => typeof e[key] === "boolean") &&
51
+ (e.sha256 === undefined || /^[a-f0-9]{64}$/.test(e.sha256)) &&
52
+ (e.reportRef === undefined || /^[a-f0-9]{32,64}$/.test(e.reportRef)) &&
53
+ (e.lastError === undefined || errors.has(e.lastError)) &&
54
+ (!e.uploadPending || (!e.rejected && !!e.sha256 && e.totalBytes <= MAX_TASK_FULL_REPORT_BYTES)) &&
55
+ (e.rejected || e.missing || (!!e.sha256 && !!e.reportRef)));
56
+ }
57
+ /** Separate from terminal-result ACKs: a result never acknowledges report bytes. */
58
+ export function createTaskReportOutbox(dataDir, deviceId, hubUrl = "") {
59
+ const scope = { deviceId, hubUrl: hubUrl ? checkedUrl(hubUrl).href.replace(/\/$/, "") : "" };
60
+ const scopeKey = createHash("sha256").update(JSON.stringify(scope)).digest("hex").slice(0, 32);
61
+ // Scope both the queue and report bytes, so rebinding never replays another Hub's reports.
62
+ const scopedDir = dataDir ? join(dataDir, "task-report-outboxes", scopeKey) : undefined;
63
+ const store = scopedDir ? createTaskReportStore(scopedDir, "device") : undefined;
64
+ const file = scopedDir ? join(scopedDir, "outbox.json") : undefined;
65
+ let entries = [];
66
+ const memory = new Map();
67
+ const key = (task) => `${task.id}:${task.attemptId}`;
68
+ const bytes = (items) => items.reduce((sum, e) => sum + (e.rejected ? 0 : e.totalBytes), 0);
69
+ if (file) {
70
+ try {
71
+ const document = JSON.parse(readFileSync(file, "utf8"));
72
+ if (document.version !== 1 ||
73
+ document.deviceId !== scope.deviceId ||
74
+ document.hubUrl !== scope.hubUrl ||
75
+ !Array.isArray(document.entries) ||
76
+ !document.entries.every(validEntry) ||
77
+ document.entries.length > REPORT_OUTBOX_MAX_ENTRIES ||
78
+ bytes(document.entries) > REPORT_OUTBOX_MAX_BYTES ||
79
+ new Set(document.entries.map(key)).size !== document.entries.length)
80
+ throw new Error("Invalid report outbox");
81
+ entries = document.entries;
82
+ }
83
+ catch (error) {
84
+ if (error.code !== "ENOENT")
85
+ throw error;
86
+ }
87
+ }
88
+ function update(entry) {
89
+ if (!validEntry(entry))
90
+ throw new Error("Invalid report outbox entry");
91
+ const next = entries.filter((e) => key(e) !== key(entry)).concat(entry);
92
+ const removable = next.filter((e) => !e.uploadPending && !e.missing && !e.rejected && key(e) !== key(entry));
93
+ const removed = [];
94
+ while (removable.length &&
95
+ (next.length > REPORT_OUTBOX_MAX_ENTRIES ||
96
+ bytes(next) > REPORT_OUTBOX_MAX_BYTES ||
97
+ next.filter((e) => !e.uploadPending && !e.missing && !e.rejected).length > ACCEPTED_RETENTION)) {
98
+ const old = removable.shift();
99
+ next.splice(next.indexOf(old), 1);
100
+ removed.push(old);
101
+ }
102
+ if (next.length > REPORT_OUTBOX_MAX_ENTRIES || bytes(next) > REPORT_OUTBOX_MAX_BYTES)
103
+ throw new Error("Report outbox capacity exceeded; pending reports retained");
104
+ // Delete bytes before dropping their registry entry; a failed cleanup stays discoverable.
105
+ for (const old of removed) {
106
+ store?.removeReport(old.id, old.attemptId, deviceId, old.roomId);
107
+ memory.delete(key(old));
108
+ }
109
+ if (file)
110
+ writeJsonAtomicSync(file, { version: 1, ...scope, entries: next });
111
+ entries = next;
112
+ return { ...entry };
113
+ }
114
+ return {
115
+ capture(taskInput, text) {
116
+ const task = binding(taskInput);
117
+ let meta;
118
+ const totalBytes = Buffer.byteLength(text);
119
+ const sha256 = createHash("sha256").update(text).digest("hex");
120
+ const previous = entries.find((e) => key(e) === key(task));
121
+ if (previous &&
122
+ (previous.roomId !== task.roomId ||
123
+ previous.botId !== task.botId ||
124
+ previous.botRevision !== task.botRevision ||
125
+ (previous.sha256 && previous.sha256 !== sha256)))
126
+ throw new Error("Report attempt content or binding conflict");
127
+ if (previous && previous.sha256 === sha256 && !previous.missing)
128
+ return { ...previous };
129
+ if (totalBytes > MAX_TASK_FULL_REPORT_BYTES)
130
+ return update({
131
+ ...task,
132
+ sha256,
133
+ totalBytes,
134
+ uploadPending: false,
135
+ missing: true,
136
+ rejected: true,
137
+ lastError: "Report exceeds 4 MiB quota",
138
+ });
139
+ // Commit intent first; recovery can read the store if interrupted after its atomic write.
140
+ update({
141
+ ...task,
142
+ reportRef: store
143
+ ? createHash("sha256").update(`${task.id}:${task.attemptId}`).digest("hex").slice(0, 32)
144
+ : sha256,
145
+ sha256,
146
+ totalBytes,
147
+ uploadPending: true,
148
+ missing: true,
149
+ rejected: false,
150
+ });
151
+ meta = store?.saveFullReport(task.id, task.attemptId, task.roomId, deviceId, text);
152
+ if (!store)
153
+ memory.set(key(task), text);
154
+ return update({
155
+ ...task,
156
+ reportRef: meta?.storageLocation.reportRef ?? sha256,
157
+ sha256,
158
+ totalBytes,
159
+ uploadPending: true,
160
+ missing: false,
161
+ rejected: false,
162
+ });
163
+ },
164
+ get(task) {
165
+ const entry = entries.find((e) => key(e) === key(task));
166
+ return entry ? { ...entry } : undefined;
167
+ },
168
+ markMissing(taskInput) {
169
+ const task = binding(taskInput);
170
+ const previous = entries.find((e) => key(e) === key(task));
171
+ return previous
172
+ ? { ...previous }
173
+ : update({
174
+ ...task,
175
+ totalBytes: 0,
176
+ uploadPending: false,
177
+ missing: true,
178
+ rejected: false,
179
+ lastError: "Executor supplied no full report",
180
+ });
181
+ },
182
+ pending() {
183
+ return entries.filter((e) => e.uploadPending && !e.rejected).map((e) => ({ ...e }));
184
+ },
185
+ read(entry) {
186
+ let text = memory.get(key(entry));
187
+ if (store) {
188
+ let offset = 0;
189
+ const parts = [];
190
+ do {
191
+ const page = store.getReport(entry.id, entry.attemptId, deviceId, entry.roomId, { offset, limit: 262144 });
192
+ if (!page || page.text === undefined)
193
+ throw new Error("Local full report missing");
194
+ parts.push(page.text);
195
+ if (!page.hasMore)
196
+ break;
197
+ if (!page.nextOffset || page.nextOffset <= offset)
198
+ throw new Error("Invalid local report pagination");
199
+ offset = page.nextOffset;
200
+ } while (offset < entry.totalBytes);
201
+ text = parts.join("");
202
+ }
203
+ if (text === undefined ||
204
+ Buffer.byteLength(text) !== entry.totalBytes ||
205
+ createHash("sha256").update(text).digest("hex") !== entry.sha256)
206
+ throw new Error("Local full report is missing or failed integrity verification");
207
+ return text;
208
+ },
209
+ accepted(entry) {
210
+ return update({ ...entry, uploadPending: false, missing: false, lastError: undefined });
211
+ },
212
+ failed(entry, _error) {
213
+ return update({ ...entry, uploadPending: true, lastError: "Report upload pending" });
214
+ },
215
+ };
216
+ }
@@ -0,0 +1,384 @@
1
+ import { mkdirSync, readFileSync, readdirSync, existsSync, rmSync, statSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { createHash } from "node:crypto";
4
+ import { writeAtomicSync, writeJsonAtomicSync } from "../atomic-file.js";
5
+ export const TASK_REPORT_BYTES = 16 * 1024;
6
+ export const MAX_TASK_FULL_REPORT_BYTES = 4 * 1024 * 1024; // 4 MiB hard quota
7
+ export const MAX_TASK_REPORT_CHUNK_BYTES = 64 * 1024; // 64 KiB per transport chunk
8
+ /** Keep the opening context and final conclusions within the wire report budget. */
9
+ export function boundTaskReport(text, limit = TASK_REPORT_BYTES) {
10
+ const bytes = Buffer.from(text, "utf8");
11
+ if (bytes.length <= limit)
12
+ return text;
13
+ if (!Number.isSafeInteger(limit) || limit < 256)
14
+ throw new Error("Invalid report byte limit");
15
+ const marker = `\n[Report excerpt: ${bytes.length} original UTF-8 bytes; middle omitted]\n`;
16
+ const budget = limit - Buffer.byteLength(marker);
17
+ let start = Math.floor(budget / 2);
18
+ let end = bytes.length - (budget - start);
19
+ // UTF-8 continuation bytes cannot begin either retained boundary.
20
+ while (start > 0 && (bytes[start] & 0xc0) === 0x80)
21
+ start--;
22
+ while (end < bytes.length && (bytes[end] & 0xc0) === 0x80)
23
+ end++;
24
+ return bytes.subarray(0, start).toString("utf8") + marker + bytes.subarray(end).toString("utf8");
25
+ }
26
+ export class TaskReportQuotaError extends Error {
27
+ totalBytes;
28
+ quotaLimit;
29
+ constructor(message, totalBytes, quotaLimit) {
30
+ super(message);
31
+ this.totalBytes = totalBytes;
32
+ this.quotaLimit = quotaLimit;
33
+ this.name = "TaskReportQuotaError";
34
+ }
35
+ }
36
+ export class TaskReportConflictError extends Error {
37
+ constructor(message) {
38
+ super(message);
39
+ this.name = "TaskReportConflictError";
40
+ }
41
+ }
42
+ function sha256Hex(data) {
43
+ return createHash("sha256").update(data).digest("hex");
44
+ }
45
+ function safePathKey(taskId, attemptId) {
46
+ const raw = `${taskId}:${attemptId}`;
47
+ return sha256Hex(raw).slice(0, 32);
48
+ }
49
+ export function createTaskReportStore(baseDir, role = "hub") {
50
+ const reportsRoot = join(baseDir, "task-reports");
51
+ function attemptDir(taskId, attemptId) {
52
+ const key = safePathKey(taskId, attemptId);
53
+ return join(reportsRoot, key);
54
+ }
55
+ function readMeta(dir) {
56
+ const metaPath = join(dir, "report-meta.json");
57
+ if (!existsSync(metaPath))
58
+ return null;
59
+ try {
60
+ return JSON.parse(readFileSync(metaPath, "utf8"));
61
+ }
62
+ catch {
63
+ throw new Error("Report metadata is corrupted");
64
+ }
65
+ }
66
+ return {
67
+ removeReport(taskId, attemptId, accountId, roomId) {
68
+ const dir = attemptDir(taskId, attemptId);
69
+ const meta = readMeta(dir);
70
+ if (!meta || meta.accountId !== accountId || meta.roomId !== roomId)
71
+ return;
72
+ rmSync(dir, { recursive: true });
73
+ },
74
+ saveFullReport(taskId, attemptId, roomId, accountId, text, quotaLimit = MAX_TASK_FULL_REPORT_BYTES) {
75
+ if (!taskId || !attemptId || !roomId || !accountId) {
76
+ throw new Error("Missing required binding fields for task report");
77
+ }
78
+ const bytes = Buffer.byteLength(text, "utf8");
79
+ const dir = attemptDir(taskId, attemptId);
80
+ const ref = `${safePathKey(taskId, attemptId)}`;
81
+ const now = Date.now();
82
+ const existing = readMeta(dir);
83
+ if (existing && (existing.accountId !== accountId || existing.roomId !== roomId))
84
+ throw new TaskReportConflictError("Report account or room binding conflict");
85
+ if (existing?.complete) {
86
+ if (existing.sha256 === sha256Hex(text))
87
+ return existing;
88
+ throw new TaskReportConflictError("Completed task report cannot be overwritten");
89
+ }
90
+ // Pre-flight quota check before writing any bytes to disk
91
+ if (bytes > quotaLimit) {
92
+ mkdirSync(dir, { recursive: true });
93
+ const meta = {
94
+ taskId,
95
+ attemptId,
96
+ roomId,
97
+ accountId,
98
+ createdAt: now,
99
+ updatedAt: now,
100
+ totalBytes: bytes,
101
+ totalChunks: 1,
102
+ receivedChunks: 0,
103
+ storageLocation: { role, reportRef: ref },
104
+ quotaLimit,
105
+ quotaExceeded: true,
106
+ rejected: true,
107
+ complete: false,
108
+ };
109
+ writeJsonAtomicSync(join(dir, "report-meta.json"), meta);
110
+ throw new TaskReportQuotaError(`Task report exceeds maximum quota (${bytes} > ${quotaLimit} bytes). Rejected without partial truncation disguise.`, bytes, quotaLimit);
111
+ }
112
+ mkdirSync(dir, { recursive: true });
113
+ const hash = sha256Hex(text);
114
+ const meta = {
115
+ taskId,
116
+ attemptId,
117
+ roomId,
118
+ accountId,
119
+ createdAt: existing?.createdAt ?? now,
120
+ updatedAt: now,
121
+ totalBytes: bytes,
122
+ totalChunks: Math.max(1, Math.ceil(bytes / (32 * 1024))),
123
+ receivedChunks: Math.max(1, Math.ceil(bytes / (32 * 1024))),
124
+ storageLocation: { role, reportRef: ref },
125
+ quotaLimit,
126
+ quotaExceeded: false,
127
+ rejected: false,
128
+ complete: true,
129
+ sha256: hash,
130
+ };
131
+ writeAtomicSync(join(dir, "full-report.txt"), text);
132
+ writeJsonAtomicSync(join(dir, "report-meta.json"), meta);
133
+ return meta;
134
+ },
135
+ appendReportChunk(input, roomId, accountId, quotaLimit = MAX_TASK_FULL_REPORT_BYTES) {
136
+ const { taskId, attemptId, chunkIndex, totalChunks, text, sha256 } = input;
137
+ if (!taskId || !attemptId || !roomId || !accountId) {
138
+ throw new Error("Missing required binding fields for report chunk");
139
+ }
140
+ if (!Number.isSafeInteger(chunkIndex) || chunkIndex < 0)
141
+ throw new Error("Invalid chunkIndex");
142
+ if (!Number.isSafeInteger(totalChunks) || totalChunks <= 0 || totalChunks > 4096 || chunkIndex >= totalChunks) {
143
+ throw new Error("Invalid totalChunks");
144
+ }
145
+ const chunkBytes = Buffer.byteLength(text, "utf8");
146
+ if (chunkBytes > MAX_TASK_REPORT_CHUNK_BYTES) {
147
+ throw new Error(`Report chunk exceeds single chunk budget (${chunkBytes} > ${MAX_TASK_REPORT_CHUNK_BYTES})`);
148
+ }
149
+ const chunkHash = sha256Hex(text);
150
+ if (sha256 && sha256 !== chunkHash) {
151
+ throw new Error("Chunk integrity hash mismatch");
152
+ }
153
+ const dir = attemptDir(taskId, attemptId);
154
+ const chunksDir = join(dir, "chunks");
155
+ const ref = safePathKey(taskId, attemptId);
156
+ const existing = readMeta(dir);
157
+ if (existing) {
158
+ if (existing.totalChunks !== totalChunks)
159
+ throw new TaskReportConflictError("Report chunk count changed");
160
+ if (existing.accountId !== accountId || existing.roomId !== roomId) {
161
+ throw new Error("Account or room mismatch for report binding");
162
+ }
163
+ if (existing.complete) {
164
+ // Check idempotence
165
+ const chunkFile = join(chunksDir, `chunk-${String(chunkIndex).padStart(4, "0")}.txt`);
166
+ if (existsSync(chunkFile)) {
167
+ const prev = readFileSync(chunkFile, "utf8");
168
+ if (sha256Hex(prev) === chunkHash)
169
+ return existing;
170
+ }
171
+ throw new TaskReportConflictError("Cannot overwrite chunk of an already completed report");
172
+ }
173
+ if (existing.quotaExceeded || existing.rejected) {
174
+ throw new TaskReportQuotaError("Task report was already rejected due to quota overflow", existing.totalBytes, quotaLimit);
175
+ }
176
+ }
177
+ // Pre-flight check cumulative bytes with new chunk before disk write
178
+ mkdirSync(chunksDir, { recursive: true });
179
+ const chunkFile = join(chunksDir, `chunk-${String(chunkIndex).padStart(4, "0")}.txt`);
180
+ if (existsSync(chunkFile)) {
181
+ const existingText = readFileSync(chunkFile, "utf8");
182
+ if (sha256Hex(existingText) !== chunkHash)
183
+ throw new TaskReportConflictError(`Conflicting content for chunk ${chunkIndex}`);
184
+ // Rebuild metadata below: a process may have stopped after writing the chunk.
185
+ }
186
+ let currentAccumulated = 0;
187
+ const chunkFiles = readdirSync(chunksDir).filter((f) => f.startsWith("chunk-") && f.endsWith(".txt"));
188
+ for (const f of chunkFiles) {
189
+ currentAccumulated += Buffer.byteLength(readFileSync(join(chunksDir, f), "utf8"), "utf8");
190
+ }
191
+ const addedBytes = existsSync(chunkFile) ? 0 : chunkBytes;
192
+ if (currentAccumulated + addedBytes > quotaLimit) {
193
+ const meta = {
194
+ taskId,
195
+ attemptId,
196
+ roomId,
197
+ accountId,
198
+ createdAt: existing?.createdAt ?? Date.now(),
199
+ updatedAt: Date.now(),
200
+ totalBytes: currentAccumulated + chunkBytes,
201
+ totalChunks,
202
+ receivedChunks: chunkFiles.length,
203
+ storageLocation: { role, reportRef: ref },
204
+ quotaLimit,
205
+ quotaExceeded: true,
206
+ rejected: true,
207
+ complete: false,
208
+ };
209
+ writeJsonAtomicSync(join(dir, "report-meta.json"), meta);
210
+ throw new TaskReportQuotaError(`Accumulated report chunks exceed quota (${currentAccumulated + chunkBytes} > ${quotaLimit})`, currentAccumulated + chunkBytes, quotaLimit);
211
+ }
212
+ // Safe atomic write chunk
213
+ writeAtomicSync(chunkFile, text);
214
+ // Count all chunks
215
+ const allChunkFiles = readdirSync(chunksDir)
216
+ .filter((f) => f.startsWith("chunk-") && f.endsWith(".txt"))
217
+ .sort();
218
+ let totalBytes = 0;
219
+ const chunkContents = [];
220
+ let complete = false;
221
+ if (allChunkFiles.length === totalChunks) {
222
+ let allPresent = true;
223
+ for (let i = 0; i < totalChunks; i++) {
224
+ const cPath = join(chunksDir, `chunk-${String(i).padStart(4, "0")}.txt`);
225
+ if (!existsSync(cPath)) {
226
+ allPresent = false;
227
+ break;
228
+ }
229
+ const content = readFileSync(cPath, "utf8");
230
+ chunkContents.push(content);
231
+ totalBytes += Buffer.byteLength(content, "utf8");
232
+ }
233
+ if (allPresent && chunkContents.length === totalChunks) {
234
+ complete = true;
235
+ }
236
+ }
237
+ else {
238
+ for (const f of allChunkFiles) {
239
+ totalBytes += Buffer.byteLength(readFileSync(join(chunksDir, f), "utf8"), "utf8");
240
+ }
241
+ }
242
+ let fullHash;
243
+ if (complete) {
244
+ const assembled = chunkContents.join("");
245
+ fullHash = sha256Hex(assembled);
246
+ if ((input.fullSha256 && input.fullSha256 !== fullHash) ||
247
+ (input.totalBytes !== undefined && input.totalBytes !== totalBytes))
248
+ throw new TaskReportConflictError("Assembled full report integrity mismatch");
249
+ writeAtomicSync(join(dir, "full-report.txt"), assembled);
250
+ }
251
+ const meta = {
252
+ taskId,
253
+ attemptId,
254
+ roomId,
255
+ accountId,
256
+ createdAt: existing?.createdAt ?? Date.now(),
257
+ updatedAt: Date.now(),
258
+ totalBytes,
259
+ totalChunks,
260
+ receivedChunks: allChunkFiles.length,
261
+ storageLocation: { role, reportRef: ref },
262
+ quotaLimit,
263
+ quotaExceeded: false,
264
+ rejected: false,
265
+ complete,
266
+ uploadPending: !complete,
267
+ missing: false,
268
+ ...(fullHash ? { sha256: fullHash } : {}),
269
+ };
270
+ writeJsonAtomicSync(join(dir, "report-meta.json"), meta);
271
+ return meta;
272
+ },
273
+ getReportMeta(taskId, attemptId, accountId, roomId) {
274
+ const dir = attemptDir(taskId, attemptId);
275
+ const meta = readMeta(dir);
276
+ if (!meta)
277
+ return null;
278
+ if (meta.accountId !== accountId || meta.roomId !== roomId)
279
+ return null;
280
+ if (meta.complete) {
281
+ try {
282
+ const file = statSync(join(dir, "full-report.txt"));
283
+ if (!file.isFile() || file.size !== meta.totalBytes)
284
+ return { ...meta, complete: false, missing: true, uploadPending: false };
285
+ }
286
+ catch {
287
+ return { ...meta, complete: false, missing: true, uploadPending: false };
288
+ }
289
+ }
290
+ return meta;
291
+ },
292
+ getReport(taskId, attemptId, accountId, roomId, options) {
293
+ const meta = this.getReportMeta(taskId, attemptId, accountId, roomId);
294
+ if (!meta)
295
+ return null;
296
+ const dir = attemptDir(taskId, attemptId);
297
+ const filePath = join(dir, "full-report.txt");
298
+ let text;
299
+ let hasMore = false;
300
+ let nextOffset = null;
301
+ let actualOffset = 0;
302
+ let limit = 65536;
303
+ let digest;
304
+ let sha256 = meta.sha256;
305
+ if (existsSync(filePath)) {
306
+ const buf = readFileSync(filePath);
307
+ const totalBytes = buf.length;
308
+ if (!sha256) {
309
+ sha256 = sha256Hex(buf);
310
+ }
311
+ digest = createHash("sha256")
312
+ .update(JSON.stringify([taskId, attemptId, options?.revision ?? 0, totalBytes, sha256]))
313
+ .digest("hex");
314
+ if (options?.expectedDigest && options.expectedDigest !== digest) {
315
+ return { meta, versionMismatch: true, digest, sha256 };
316
+ }
317
+ if (options?.offset !== undefined || options?.limit !== undefined) {
318
+ actualOffset = Math.max(0, options.offset ?? 0);
319
+ while (actualOffset > 0 && (buf[actualOffset] & 0xc0) === 0x80) {
320
+ actualOffset--;
321
+ }
322
+ limit = Math.max(1, Math.min(options.limit ?? 65536, 262144));
323
+ let end = Math.min(actualOffset + limit, totalBytes);
324
+ while (end > actualOffset && (buf[end] & 0xc0) === 0x80) {
325
+ end--;
326
+ }
327
+ if (end === actualOffset && actualOffset < totalBytes) {
328
+ end++;
329
+ while (end < totalBytes && (buf[end] & 0xc0) === 0x80)
330
+ end++;
331
+ }
332
+ text = buf.subarray(actualOffset, end).toString("utf8");
333
+ hasMore = end < totalBytes;
334
+ nextOffset = hasMore ? end : null;
335
+ }
336
+ else {
337
+ if (totalBytes > 65536) {
338
+ let end = 65536;
339
+ while (end > 0 && (buf[end] & 0xc0) === 0x80)
340
+ end--;
341
+ text = buf.subarray(0, end).toString("utf8");
342
+ hasMore = true;
343
+ nextOffset = end;
344
+ }
345
+ else {
346
+ text = buf.toString("utf8");
347
+ hasMore = false;
348
+ nextOffset = null;
349
+ }
350
+ }
351
+ }
352
+ return { meta, text, hasMore, nextOffset, offset: actualOffset, limit, digest, sha256 };
353
+ },
354
+ getReportChunk(taskId, attemptId, accountId, roomId, chunkIndex) {
355
+ const meta = this.getReportMeta(taskId, attemptId, accountId, roomId);
356
+ if (!meta || !Number.isSafeInteger(chunkIndex) || chunkIndex < 0 || chunkIndex >= meta.totalChunks)
357
+ return null;
358
+ const dir = attemptDir(taskId, attemptId);
359
+ const chunksDir = join(dir, "chunks");
360
+ const chunkFile = join(chunksDir, `chunk-${String(chunkIndex).padStart(4, "0")}.txt`);
361
+ let text;
362
+ if (existsSync(chunkFile)) {
363
+ text = readFileSync(chunkFile, "utf8");
364
+ }
365
+ else {
366
+ const fullPath = join(dir, "full-report.txt");
367
+ if (existsSync(fullPath)) {
368
+ const buf = readFileSync(fullPath);
369
+ const CHUNK_SIZE = 32 * 1024;
370
+ let start = chunkIndex * CHUNK_SIZE;
371
+ let end = Math.min((chunkIndex + 1) * CHUNK_SIZE, buf.length);
372
+ while (start > 0 && (buf[start] & 0xc0) === 0x80)
373
+ start--;
374
+ while (end > start && (buf[end] & 0xc0) === 0x80)
375
+ end--;
376
+ if (start < buf.length) {
377
+ text = buf.subarray(start, end).toString("utf8");
378
+ }
379
+ }
380
+ }
381
+ return { meta, text: text ?? "" };
382
+ },
383
+ };
384
+ }