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,385 @@
1
+ import { mkdir, readFile, readdir, unlink, appendFile, writeFile, stat } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { createHash, randomUUID } from "node:crypto";
4
+ import { sanitizeTextForJournal, sanitizeToolParameters } from "./task-progress.js";
5
+ export const MAX_JOURNAL_SEGMENT_ENTRIES = 50;
6
+ export const MAX_JOURNAL_SEGMENT_BYTES = 64 * 1024; // 64 KiB
7
+ export const MAX_JOURNAL_RETAINED_SEGMENTS = 20; // 20 segments * 50 entries = up to 1000 events
8
+ function sha256Hex(data) {
9
+ return createHash("sha256").update(data).digest("hex");
10
+ }
11
+ function safeTaskDirName(taskId) {
12
+ if (!taskId || typeof taskId !== "string")
13
+ throw new Error("Invalid taskId");
14
+ return sha256Hex(taskId).slice(0, 32);
15
+ }
16
+ export function encodeJournalCursor(taskId, attemptId, sequence) {
17
+ const raw = JSON.stringify({ taskId, attemptId, sequence });
18
+ return Buffer.from(raw, "utf8").toString("base64url");
19
+ }
20
+ export function decodeJournalCursor(cursorStr) {
21
+ try {
22
+ const raw = Buffer.from(cursorStr, "base64url").toString("utf8");
23
+ const obj = JSON.parse(raw);
24
+ if (typeof obj.taskId === "string" &&
25
+ typeof obj.attemptId === "string" &&
26
+ typeof obj.sequence === "number" &&
27
+ Number.isSafeInteger(obj.sequence) &&
28
+ obj.sequence >= 0) {
29
+ return { taskId: obj.taskId, attemptId: obj.attemptId, sequence: obj.sequence };
30
+ }
31
+ }
32
+ catch {
33
+ // invalid cursor
34
+ }
35
+ return null;
36
+ }
37
+ async function writeAtomicAsync(filePath, content) {
38
+ const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${randomUUID().slice(0, 8)}.tmp`;
39
+ await writeFile(tmpPath, content, "utf8");
40
+ try {
41
+ const { rename } = await import("node:fs/promises");
42
+ await rename(tmpPath, filePath);
43
+ }
44
+ catch (err) {
45
+ await unlink(tmpPath).catch(() => { });
46
+ throw err;
47
+ }
48
+ }
49
+ export function createTaskJournalManager(baseDir) {
50
+ const rootDir = join(baseDir, "task-journals");
51
+ let closed = false;
52
+ // In-memory active task state cache to avoid repeated disk reads on progress loops
53
+ const activeTasks = new Map();
54
+ // Asynchronous serialization tail Promise per task
55
+ const taskLocks = new Map();
56
+ function taskDir(taskId) {
57
+ return join(rootDir, safeTaskDirName(taskId));
58
+ }
59
+ function segmentFileName(index) {
60
+ return `segment-${String(index).padStart(6, "0")}.jsonl`;
61
+ }
62
+ async function loadMetaFromDisk(dir) {
63
+ const metaPath = join(dir, "meta.json");
64
+ try {
65
+ const data = await readFile(metaPath, "utf8");
66
+ return JSON.parse(data);
67
+ }
68
+ catch (cause) {
69
+ if (cause?.code === "ENOENT")
70
+ return null;
71
+ throw new Error("Task journal metadata is corrupted: " + String(cause));
72
+ }
73
+ }
74
+ async function getOrInitTaskState(taskId, context) {
75
+ const cached = activeTasks.get(taskId);
76
+ if (cached)
77
+ return cached;
78
+ const dir = taskDir(taskId);
79
+ let meta = await loadMetaFromDisk(dir);
80
+ if (!meta) {
81
+ if (!context)
82
+ throw new Error("Missing initial context to initialize task journal");
83
+ const now = Date.now();
84
+ meta = {
85
+ taskId,
86
+ roomId: context.roomId,
87
+ accountId: context.accountId,
88
+ botId: context.botId,
89
+ attemptId: context.attemptId,
90
+ createdAt: now,
91
+ updatedAt: now,
92
+ totalEvents: 0,
93
+ nextSequence: 1,
94
+ segmentCount: 1,
95
+ activeSegmentIndex: 0,
96
+ minRetainedSequence: 1,
97
+ truncated: false,
98
+ droppedCount: 0,
99
+ journalRef: safeTaskDirName(taskId),
100
+ };
101
+ await mkdir(dir, { recursive: true });
102
+ await writeAtomicAsync(join(dir, "meta.json"), JSON.stringify(meta, null, 2));
103
+ }
104
+ // Stat current active segment to track bytes and lines without full read
105
+ const segPath = join(dir, segmentFileName(meta.activeSegmentIndex));
106
+ let bytes = 0;
107
+ let lines = 0;
108
+ try {
109
+ const s = await stat(segPath);
110
+ bytes = s.size;
111
+ const content = await readFile(segPath, "utf8");
112
+ lines = content.split("\n").filter((l) => l.trim().length > 0).length;
113
+ }
114
+ catch {
115
+ // Segment does not exist yet
116
+ }
117
+ const state = {
118
+ meta,
119
+ currentSegBytes: bytes,
120
+ currentSegLines: lines,
121
+ };
122
+ activeTasks.set(taskId, state);
123
+ return state;
124
+ }
125
+ function sanitizeMetadata(input) {
126
+ if (!input || typeof input !== "object" || Array.isArray(input))
127
+ return;
128
+ const result = {};
129
+ for (const [k, v] of Object.entries(input)) {
130
+ if (/^[A-Za-z0-9_-]{1,64}$/.test(k)) {
131
+ if (typeof v === "string") {
132
+ result[k] = sanitizeTextForJournal(v).slice(0, 256);
133
+ }
134
+ else if (typeof v === "number" && Number.isFinite(v)) {
135
+ result[k] = v;
136
+ }
137
+ else if (typeof v === "boolean") {
138
+ result[k] = v;
139
+ }
140
+ }
141
+ }
142
+ return Object.keys(result).length > 0 ? result : undefined;
143
+ }
144
+ function withTaskQueue(taskId, fn) {
145
+ const tail = taskLocks.get(taskId) ?? Promise.resolve();
146
+ const next = tail.then(fn, fn);
147
+ taskLocks.set(taskId, next);
148
+ next.finally(() => {
149
+ if (taskLocks.get(taskId) === next)
150
+ taskLocks.delete(taskId);
151
+ });
152
+ return next;
153
+ }
154
+ return {
155
+ async append(taskId, entryInput, context) {
156
+ if (closed) {
157
+ throw new Error("Task journal manager is closed");
158
+ }
159
+ if (!taskId || !context?.roomId || !context?.accountId) {
160
+ throw new Error("Missing required binding context for journal append");
161
+ }
162
+ return withTaskQueue(taskId, async () => {
163
+ const dir = taskDir(taskId);
164
+ const taskState = await getOrInitTaskState(taskId, {
165
+ roomId: context.roomId,
166
+ accountId: context.accountId,
167
+ botId: entryInput.botId,
168
+ attemptId: entryInput.attemptId,
169
+ });
170
+ const meta = taskState.meta;
171
+ if (meta.accountId !== context.accountId || meta.roomId !== context.roomId) {
172
+ throw new Error("Account or room mismatch for existing task journal");
173
+ }
174
+ const seq = meta.nextSequence++;
175
+ const now = Date.now();
176
+ const timestamp = entryInput.timestamp || now;
177
+ const id = `${taskId}-${seq}`;
178
+ // Sanitize output, summary, reason, parameters
179
+ let sanitizedOutput;
180
+ if (typeof entryInput.output === "string") {
181
+ sanitizedOutput = sanitizeTextForJournal(entryInput.output).slice(0, 2048);
182
+ }
183
+ let sanitizedSummary;
184
+ if (typeof entryInput.summary === "string") {
185
+ sanitizedSummary = sanitizeTextForJournal(entryInput.summary).slice(0, 512);
186
+ }
187
+ let sanitizedReason;
188
+ if (typeof entryInput.reason === "string") {
189
+ sanitizedReason = sanitizeTextForJournal(entryInput.reason).slice(0, 512);
190
+ }
191
+ let safeParams;
192
+ if (entryInput.parametersPreview) {
193
+ if (entryInput.toolName && !("action" in entryInput.parametersPreview)) {
194
+ safeParams = sanitizeToolParameters(entryInput.toolName, entryInput.parametersPreview);
195
+ }
196
+ else {
197
+ safeParams = entryInput.parametersPreview;
198
+ }
199
+ }
200
+ const safeMeta = sanitizeMetadata(entryInput.metadata);
201
+ const entry = {
202
+ id,
203
+ sequence: seq,
204
+ timestamp,
205
+ taskId,
206
+ botId: entryInput.botId,
207
+ attemptId: entryInput.attemptId,
208
+ type: entryInput.type,
209
+ ...(entryInput.phase ? { phase: entryInput.phase } : {}),
210
+ ...(entryInput.toolName ? { toolName: entryInput.toolName } : {}),
211
+ ...(entryInput.toolCallId ? { toolCallId: entryInput.toolCallId } : {}),
212
+ ...(sanitizedSummary ? { summary: sanitizedSummary } : {}),
213
+ ...(sanitizedOutput ? { output: sanitizedOutput } : {}),
214
+ ...(safeParams ? { parametersPreview: safeParams } : {}),
215
+ ...(sanitizedReason ? { reason: sanitizedReason } : {}),
216
+ ...(safeMeta ? { metadata: safeMeta } : {}),
217
+ };
218
+ const line = JSON.stringify(entry) + "\n";
219
+ const lineBytes = Buffer.byteLength(line, "utf8");
220
+ // Rotate segment if needed
221
+ if (taskState.currentSegLines >= MAX_JOURNAL_SEGMENT_ENTRIES ||
222
+ taskState.currentSegBytes + lineBytes >= MAX_JOURNAL_SEGMENT_BYTES) {
223
+ meta.activeSegmentIndex++;
224
+ meta.segmentCount++;
225
+ taskState.currentSegBytes = 0;
226
+ taskState.currentSegLines = 0;
227
+ }
228
+ const segPath = join(dir, segmentFileName(meta.activeSegmentIndex));
229
+ // Direct non-blocking append to file, no full segment rewrite
230
+ await appendFile(segPath, line, "utf8");
231
+ taskState.currentSegBytes += lineBytes;
232
+ taskState.currentSegLines++;
233
+ meta.totalEvents++;
234
+ meta.updatedAt = now;
235
+ // Segment bound pruning
236
+ if (meta.segmentCount > MAX_JOURNAL_RETAINED_SEGMENTS) {
237
+ const files = (await readdir(dir)).filter((f) => f.startsWith("segment-") && f.endsWith(".jsonl")).sort();
238
+ if (files.length > MAX_JOURNAL_RETAINED_SEGMENTS) {
239
+ const toDelete = files.slice(0, files.length - MAX_JOURNAL_RETAINED_SEGMENTS);
240
+ for (const f of toDelete) {
241
+ try {
242
+ const oldLines = (await readFile(join(dir, f), "utf8")).split("\n").filter((l) => l.trim().length > 0);
243
+ meta.droppedCount += oldLines.length;
244
+ await unlink(join(dir, f));
245
+ }
246
+ catch {
247
+ // ignore
248
+ }
249
+ }
250
+ meta.truncated = true;
251
+ const remaining = (await readdir(dir))
252
+ .filter((f) => f.startsWith("segment-") && f.endsWith(".jsonl"))
253
+ .sort();
254
+ if (remaining[0]) {
255
+ try {
256
+ const firstLine = (await readFile(join(dir, remaining[0]), "utf8")).split("\n")[0];
257
+ if (firstLine) {
258
+ const parsed = JSON.parse(firstLine);
259
+ meta.minRetainedSequence = parsed.sequence;
260
+ }
261
+ }
262
+ catch {
263
+ // ignore
264
+ }
265
+ }
266
+ }
267
+ }
268
+ // Asynchronous metadata atomic write
269
+ await writeAtomicAsync(join(dir, "meta.json"), JSON.stringify(meta, null, 2));
270
+ return entry;
271
+ });
272
+ },
273
+ async getMeta(taskId, accountId, roomId) {
274
+ if (!taskId || !accountId || !roomId)
275
+ return null;
276
+ const cached = activeTasks.get(taskId);
277
+ if (cached) {
278
+ const m = cached.meta;
279
+ if (m.accountId !== accountId || m.roomId !== roomId)
280
+ return null;
281
+ return m;
282
+ }
283
+ const dir = taskDir(taskId);
284
+ const metaPath = join(dir, "meta.json");
285
+ try {
286
+ const data = await readFile(metaPath, "utf8");
287
+ const parsed = JSON.parse(data);
288
+ if (!parsed.accountId || parsed.accountId !== accountId || !parsed.roomId || parsed.roomId !== roomId) {
289
+ return null;
290
+ }
291
+ return parsed;
292
+ }
293
+ catch {
294
+ return null;
295
+ }
296
+ },
297
+ async getPage(taskId, accountId, roomId, options = {}) {
298
+ const meta = await this.getMeta(taskId, accountId, roomId);
299
+ if (!meta)
300
+ return null;
301
+ const dir = taskDir(taskId);
302
+ const limit = Math.min(Math.max(options.limit ?? 20, 1), 100);
303
+ const direction = options.direction === "backward" ? "backward" : "forward";
304
+ let cursorSeq;
305
+ let cursorExpired = false;
306
+ if (options.cursor) {
307
+ const decoded = decodeJournalCursor(options.cursor);
308
+ if (decoded && decoded.taskId === taskId) {
309
+ cursorSeq = decoded.sequence;
310
+ if (meta.truncated && cursorSeq < meta.minRetainedSequence) {
311
+ cursorExpired = true;
312
+ }
313
+ }
314
+ else {
315
+ return {
316
+ taskId,
317
+ items: [],
318
+ hasMore: false,
319
+ totalEvents: meta.totalEvents,
320
+ truncated: meta.truncated,
321
+ droppedCount: meta.droppedCount,
322
+ cursorExpired: true,
323
+ };
324
+ }
325
+ }
326
+ // Read retained segment entries asynchronously
327
+ const files = (await readdir(dir)).filter((f) => f.startsWith("segment-") && f.endsWith(".jsonl")).sort();
328
+ const allEntries = [];
329
+ let corrupted = false;
330
+ for (const file of files) {
331
+ try {
332
+ const content = await readFile(join(dir, file), "utf8");
333
+ const lines = content.split("\n").filter((l) => l.trim().length > 0);
334
+ for (const line of lines) {
335
+ try {
336
+ allEntries.push(JSON.parse(line));
337
+ }
338
+ catch {
339
+ corrupted = true;
340
+ }
341
+ }
342
+ }
343
+ catch {
344
+ corrupted = true;
345
+ }
346
+ }
347
+ allEntries.sort((a, b) => a.sequence - b.sequence);
348
+ let filtered;
349
+ if (direction === "forward") {
350
+ filtered = cursorSeq !== undefined ? allEntries.filter((e) => e.sequence > cursorSeq) : allEntries;
351
+ }
352
+ else {
353
+ filtered = cursorSeq !== undefined ? allEntries.filter((e) => e.sequence < cursorSeq) : allEntries;
354
+ filtered.reverse();
355
+ }
356
+ const pageItems = filtered.slice(0, limit);
357
+ const hasMore = filtered.length > limit;
358
+ let nextCursor;
359
+ if (hasMore && pageItems.length > 0) {
360
+ const lastItem = pageItems[pageItems.length - 1];
361
+ nextCursor = encodeJournalCursor(taskId, meta.attemptId, lastItem.sequence);
362
+ }
363
+ return {
364
+ taskId,
365
+ items: pageItems,
366
+ ...(nextCursor ? { nextCursor } : {}),
367
+ hasMore,
368
+ totalEvents: meta.totalEvents,
369
+ truncated: meta.truncated,
370
+ droppedCount: meta.droppedCount,
371
+ ...(cursorExpired ? { cursorExpired: true } : {}),
372
+ ...(corrupted ? { corrupted: true } : {}),
373
+ };
374
+ },
375
+ async close() {
376
+ closed = true;
377
+ while (taskLocks.size > 0) {
378
+ const inFlight = Array.from(taskLocks.values());
379
+ await Promise.allSettled(inFlight);
380
+ }
381
+ activeTasks.clear();
382
+ taskLocks.clear();
383
+ },
384
+ };
385
+ }
@@ -0,0 +1,33 @@
1
+ /** Reject invalid plans whole; never turn truncated or defaulted steps into an approval target. */
2
+ export function validateTaskPlan(value) {
3
+ if (!value || typeof value !== "object")
4
+ return;
5
+ const plan = value;
6
+ if (plan.state !== "ready" || !Array.isArray(plan.steps) || plan.steps.length < 1 || plan.steps.length > 32)
7
+ return;
8
+ if (plan.summary !== undefined && (typeof plan.summary !== "string" || plan.summary.length > 500))
9
+ return;
10
+ const ids = new Set();
11
+ const steps = [];
12
+ for (const raw of plan.steps) {
13
+ if (!raw || typeof raw !== "object")
14
+ return;
15
+ const step = raw;
16
+ if (typeof step.id !== "string" || !step.id.trim() || step.id.length > 64 || ids.has(step.id.trim()))
17
+ return;
18
+ if (typeof step.title !== "string" || !step.title.trim() || step.title.length > 200)
19
+ return;
20
+ if (!["pending", "in_progress", "done", "failed"].includes(step.status))
21
+ return;
22
+ if (step.description !== undefined && (typeof step.description !== "string" || step.description.length > 1000))
23
+ return;
24
+ ids.add(step.id.trim());
25
+ steps.push({
26
+ id: step.id.trim(),
27
+ title: step.title.trim(),
28
+ status: step.status,
29
+ ...(step.description === undefined ? {} : { description: step.description }),
30
+ });
31
+ }
32
+ return { state: "ready", steps, ...(plan.summary === undefined ? {} : { summary: plan.summary }) };
33
+ }
@@ -0,0 +1,141 @@
1
+ /**
2
+ * Filter out thought/reasoning fragments.
3
+ * Drops open or closed thought blocks entirely. If an open tag exists without closure,
4
+ * the trailing fragment is discarded to prevent streaming leaks.
5
+ */
6
+ export function sanitizeTextForJournal(input) {
7
+ if (!input)
8
+ return "";
9
+ let text = input;
10
+ // Drop closed thought tags
11
+ text = text.replace(/<thought[\s\S]*?<\/thought>/gi, "");
12
+ text = text.replace(/<thinking[\s\S]*?<\/thinking>/gi, "");
13
+ // Drop unclosed trailing thought tags (streaming fragment)
14
+ text = text.replace(/<(thought|thinking)[\s\S]*$/gi, "");
15
+ // Drop credential/token patterns (best-effort defense in depth)
16
+ text = text.replace(/((?:bearer|token|key|secret|password|passwd|credential|auth|api[-_]?key)[\s:="']{1,4})([A-Za-z0-9_\-./+=]{8,})/gi, "$1[REDACTED]");
17
+ text = text.replace(/-----BEGIN[A-Z0-9\s_-]+PRIVATE KEY-----[\s\S]*?-----END[A-Z0-9\s_-]+PRIVATE KEY-----/gi, "[REDACTED PRIVATE KEY]");
18
+ return text.trim();
19
+ }
20
+ /**
21
+ * Sanitize tool parameters into safe structural summaries.
22
+ * Never outputs raw commands, raw file contents, or raw sensitive file paths.
23
+ */
24
+ export function sanitizeToolParameters(toolName, params) {
25
+ if (!params || typeof params !== "object" || Array.isArray(params))
26
+ return;
27
+ const input = params;
28
+ const result = {};
29
+ if (toolName === "bash" || toolName === "terminal") {
30
+ if (typeof input.command === "string") {
31
+ result.commandLength = input.command.length;
32
+ result.action = "run_shell_command";
33
+ }
34
+ if (typeof input.timeout === "number")
35
+ result.timeout = input.timeout;
36
+ }
37
+ else if (toolName === "read") {
38
+ if (typeof input.path === "string") {
39
+ const ext = input.path.split(".").pop();
40
+ result.fileType = ext ? `.${ext.slice(0, 8)}` : "file";
41
+ result.action = "read_file";
42
+ }
43
+ }
44
+ else if (toolName === "write" || toolName === "edit" || toolName === "edit_soft") {
45
+ if (typeof input.path === "string") {
46
+ const ext = input.path.split(".").pop();
47
+ result.fileType = ext ? `.${ext.slice(0, 8)}` : "file";
48
+ result.action = toolName === "write" ? "write_file" : "edit_file";
49
+ }
50
+ if (typeof input.content === "string") {
51
+ result.contentBytes = Buffer.byteLength(input.content, "utf8");
52
+ }
53
+ if (Array.isArray(input.edits)) {
54
+ result.editCount = input.edits.length;
55
+ }
56
+ }
57
+ else {
58
+ // Generic tool summary: count parameters without exposing unknown values
59
+ result.parameterCount = Object.keys(input).length;
60
+ result.action = `invoke_${toolName}`;
61
+ }
62
+ return result;
63
+ }
64
+ export function summarizeToolOutput(toolName, output, isError = false) {
65
+ const byteLen = Buffer.byteLength(output, "utf8");
66
+ if (isError) {
67
+ return `[${toolName} failed: ${byteLen} bytes error output]`;
68
+ }
69
+ if (toolName === "read") {
70
+ return `[read completed: ${byteLen} bytes read]`;
71
+ }
72
+ if (toolName === "write" || toolName === "edit" || toolName === "edit_soft") {
73
+ return `[${toolName} completed: ${byteLen} bytes written]`;
74
+ }
75
+ if (toolName === "bash" || toolName === "terminal") {
76
+ return `[${toolName} completed: ${byteLen} bytes output]`;
77
+ }
78
+ return `[${toolName} completed: ${byteLen} bytes output]`;
79
+ }
80
+ /** Project tool lifecycle with strict parameter and credential redaction. */
81
+ export function projectToolLifecycle(value) {
82
+ if (!value || typeof value !== "object")
83
+ return;
84
+ const val = value;
85
+ if (typeof val.toolName !== "string" || !/^[A-Za-z0-9_.:-]{1,80}$/.test(val.toolName))
86
+ return;
87
+ const phase = ["start", "progress", "end", "failed"].includes(val.phase) ? val.phase : "progress";
88
+ const lifecycle = {
89
+ toolName: val.toolName,
90
+ phase,
91
+ };
92
+ if (typeof val.callId === "string" && val.callId.length <= 64)
93
+ lifecycle.callId = val.callId;
94
+ if (typeof val.summary === "string") {
95
+ lifecycle.summary = sanitizeTextForJournal(val.summary).slice(0, 256);
96
+ }
97
+ if (val.parameters) {
98
+ const safeParams = sanitizeToolParameters(val.toolName, val.parameters);
99
+ if (safeParams && Object.keys(safeParams).length > 0)
100
+ lifecycle.parametersPreview = safeParams;
101
+ }
102
+ if (typeof val.output === "string") {
103
+ // Never leak raw read/bash/write outputs or environment secrets; emit safe structural summary
104
+ lifecycle.outputSnippet = summarizeToolOutput(val.toolName, val.output, phase === "failed");
105
+ }
106
+ if (typeof val.durationMs === "number" && Number.isFinite(val.durationMs) && val.durationMs >= 0) {
107
+ lifecycle.durationMs = Math.round(val.durationMs);
108
+ }
109
+ return lifecycle;
110
+ }
111
+ /** Project explicitly allowed fields; never spread tool arguments or approval payloads. */
112
+ export function projectTaskActivity(value) {
113
+ if (!value || typeof value !== "object")
114
+ return;
115
+ const input = value;
116
+ if (!["model", "tool", "waiting"].includes(input.phase))
117
+ return;
118
+ let safeText;
119
+ if (typeof input.text === "string") {
120
+ const sanitized = sanitizeTextForJournal(input.text);
121
+ safeText = Buffer.from(sanitized)
122
+ .subarray(0, 2048)
123
+ .toString("utf8")
124
+ .replace(/\uFFFD$/u, "");
125
+ }
126
+ return {
127
+ phase: input.phase,
128
+ ...(safeText !== undefined ? { text: safeText } : {}),
129
+ ...(typeof input.toolName === "string" && /^[A-Za-z0-9_.:-]{1,80}$/.test(input.toolName)
130
+ ? { toolName: input.toolName }
131
+ : {}),
132
+ };
133
+ }
134
+ export function validTaskProgress(value) {
135
+ return (!!projectTaskActivity(value) &&
136
+ [value.taskId, value.botId, value.attemptId].every((id) => typeof id === "string" && id.length > 0 && id.length <= 128) &&
137
+ Number.isSafeInteger(value.sequence) &&
138
+ value.sequence > 0 &&
139
+ (value.text === undefined || (typeof value.text === "string" && Buffer.byteLength(value.text) <= 2048)) &&
140
+ (value.toolName === undefined || /^[A-Za-z0-9_.:-]{1,80}$/.test(value.toolName)));
141
+ }