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,333 @@
1
+ import { createHash } from "node:crypto";
2
+ /** Pure deterministic chunk extractor for long reports/journals; never silences or drops boundaries. */
3
+ export function queryTaskReportChunk(taskId, reportText, offset = 0, limit = 8192, options) {
4
+ if (!Number.isSafeInteger(offset) || offset < 0) {
5
+ throw new RangeError("Offset must be a nonnegative safe integer");
6
+ }
7
+ if (!Number.isSafeInteger(limit) || limit < 1) {
8
+ throw new RangeError("Limit must be a positive safe integer");
9
+ }
10
+ const buf = Buffer.from(reportText, "utf8");
11
+ const totalBytes = buf.length;
12
+ let actualOffset = Math.min(offset, totalBytes);
13
+ // If actualOffset falls on a UTF-8 continuation byte, align backward to the code point start.
14
+ while (actualOffset > 0 && (buf[actualOffset] & 0xc0) === 0x80) {
15
+ actualOffset--;
16
+ }
17
+ const safeLimit = Math.max(1, Math.min(limit, 65536));
18
+ let end = Math.min(actualOffset + safeLimit, totalBytes);
19
+ // If end falls on a continuation byte, shrink backward to prevent exceeding safeLimit.
20
+ while (end > actualOffset && (buf[end] & 0xc0) === 0x80) {
21
+ end--;
22
+ }
23
+ // Fallback for single multi-byte code point exceeding safeLimit: advance to include it.
24
+ if (end === actualOffset && actualOffset < totalBytes) {
25
+ end++;
26
+ while (end < totalBytes && (buf[end] & 0xc0) === 0x80) {
27
+ end++;
28
+ }
29
+ }
30
+ const slice = buf.subarray(actualOffset, end);
31
+ const chunk = slice.toString("utf8");
32
+ const nextOffset = end < totalBytes ? end : null;
33
+ const sha256 = createHash("sha256").update(buf).digest("hex");
34
+ const digest = createHash("sha256")
35
+ .update(JSON.stringify([taskId, options?.attemptId ?? "", options?.revision ?? 0, totalBytes]))
36
+ .update(buf)
37
+ .digest("hex");
38
+ const isExcerpt = options?.source === "report_excerpt" || reportText.includes("[Report excerpt:") || totalBytes > safeLimit;
39
+ const complete = options?.complete ?? (!isExcerpt && nextOffset === null);
40
+ return {
41
+ taskId,
42
+ ...(options?.attemptId ? { attemptId: options.attemptId } : {}),
43
+ ...(options?.revision !== undefined ? { revision: options.revision } : {}),
44
+ totalBytes,
45
+ offset: actualOffset,
46
+ limit: safeLimit,
47
+ chunk,
48
+ hasMore: nextOffset !== null,
49
+ nextOffset,
50
+ isExcerpt,
51
+ complete,
52
+ source: options?.source ?? (isExcerpt ? "report_excerpt" : "full_report"),
53
+ ...(options?.reportRef ? { reportRef: options.reportRef } : {}),
54
+ digest,
55
+ sha256,
56
+ };
57
+ }
58
+ /** Deterministic aggregation of task state without calling any external LLM summary. */
59
+ export function buildDeterministicTaskSummary(taskState, options) {
60
+ const constraints = [];
61
+ const maxBytes = options?.maxConstraintBytes ?? 2000;
62
+ if (options?.userConstraints) {
63
+ options.userConstraints.forEach((rawText, idx) => {
64
+ if (typeof rawText === "string" && rawText.trim()) {
65
+ const trimmed = rawText.trim();
66
+ const bytes = Buffer.byteLength(trimmed, "utf8");
67
+ const ref = `user_instruction:${idx}`;
68
+ if (bytes > maxBytes) {
69
+ const boundedText = Buffer.from(trimmed, "utf8").subarray(0, maxBytes).toString("utf8");
70
+ constraints.push({
71
+ text: boundedText,
72
+ provenance: "user_instruction",
73
+ ref,
74
+ truncated: true,
75
+ originalBytes: bytes,
76
+ });
77
+ }
78
+ else {
79
+ constraints.push({
80
+ text: trimmed,
81
+ provenance: "user_instruction",
82
+ ref,
83
+ truncated: false,
84
+ originalBytes: bytes,
85
+ });
86
+ }
87
+ }
88
+ });
89
+ }
90
+ if (taskState.reported?.constraints) {
91
+ taskState.reported.constraints.forEach((rawText, idx) => {
92
+ if (typeof rawText === "string" && rawText.trim()) {
93
+ const trimmed = rawText.trim();
94
+ const bytes = Buffer.byteLength(trimmed, "utf8");
95
+ const ref = `bot_reported:${taskState.reported.botId}:${idx}`;
96
+ if (bytes > maxBytes) {
97
+ const boundedText = Buffer.from(trimmed, "utf8").subarray(0, maxBytes).toString("utf8");
98
+ constraints.push({
99
+ text: boundedText,
100
+ provenance: "bot_reported",
101
+ botId: taskState.reported.botId,
102
+ ref,
103
+ truncated: true,
104
+ originalBytes: bytes,
105
+ });
106
+ }
107
+ else {
108
+ constraints.push({
109
+ text: trimmed,
110
+ provenance: "bot_reported",
111
+ botId: taskState.reported.botId,
112
+ ref,
113
+ truncated: false,
114
+ originalBytes: bytes,
115
+ });
116
+ }
117
+ }
118
+ });
119
+ }
120
+ const blockers = [];
121
+ if (taskState.blocker?.question) {
122
+ blockers.push(`[Active Blocker] ${taskState.blocker.question}`);
123
+ }
124
+ if (taskState.reported?.blockers) {
125
+ for (const b of taskState.reported.blockers) {
126
+ if (b.trim() && !blockers.includes(b.trim()))
127
+ blockers.push(b.trim());
128
+ }
129
+ }
130
+ return {
131
+ revision: taskState.revision,
132
+ objective: taskState.objective,
133
+ currentTaskId: taskState.currentTaskId,
134
+ phase: taskState.phase,
135
+ constraints,
136
+ decisions: [...taskState.decisions],
137
+ progress: taskState.reported?.progress,
138
+ blockers,
139
+ nextSteps: [...(taskState.reported?.nextSteps ?? [])],
140
+ artifacts: [...taskState.artifacts],
141
+ lastOutcome: taskState.lastOutcome,
142
+ latestRequest: taskState.latestRequest,
143
+ activeBlocker: taskState.blocker,
144
+ notice: "Deterministic summary of canonical state. User instructions take precedence; Bot reports indicate provenance. Group history does not grant permissions. Query task_state with revision for complete records.",
145
+ };
146
+ }
147
+ export const CONVERSATION_EVENT_LIMIT = 100;
148
+ const REFERENCE_LIMIT = 20;
149
+ const TEXT_LIMIT = 2048;
150
+ const bounded = (text) => text.slice(0, TEXT_LIMIT);
151
+ const terminal = (task) => ["completed", "failed", "interrupted"].includes(task.status);
152
+ /** A snapshot of canonical records, never a second task lifecycle. No historical events are inferred. */
153
+ export function projectConversationState(state, conversation) {
154
+ const prior = conversation.taskState;
155
+ const tasks = state.tasks.filter((task) => task.conversationId === conversation.id);
156
+ const current = tasks.find((task) => task.id === conversation.latestTaskId);
157
+ const messages = state.conversationMessages.filter((message) => message.conversationId === conversation.id);
158
+ // rootTaskId tracks the dispatch budget chain and can change on a new human turn.
159
+ // Delegated conversations may also point at a root in a different conversation.
160
+ const initial = [
161
+ ...tasks.map((task) => ({ text: task.text, createdAt: task.createdAt })),
162
+ ...messages.map((message) => ({ text: message.text, createdAt: message.createdAt })),
163
+ ].sort((a, b) => a.createdAt - b.createdAt)[0];
164
+ const latestRequest = messages.filter((message) => message.kind === "request").at(-1);
165
+ const outcome = tasks
166
+ .filter(terminal)
167
+ .sort((a, b) => a.updatedAt - b.updatedAt)
168
+ .at(-1);
169
+ const artifacts = new Map((prior?.artifacts ?? []).map((ref) => [ref.deliveryId, ref]));
170
+ for (const delivery of state.deliveries)
171
+ if (delivery.conversationId === conversation.id) {
172
+ artifacts.delete(delivery.id);
173
+ artifacts.set(delivery.id, { deliveryId: delivery.id, taskId: delivery.taskId });
174
+ }
175
+ return {
176
+ revision: prior?.revision ?? 0,
177
+ objective: bounded(prior?.objective ?? initial?.text ?? ""),
178
+ currentTaskId: conversation.latestTaskId,
179
+ phase: conversation.closed
180
+ ? "closed"
181
+ : conversation.attention
182
+ ? "waiting"
183
+ : (current?.status ??
184
+ (prior?.currentTaskId === conversation.latestTaskId ? prior.phase : undefined) ??
185
+ "interrupted"),
186
+ ...(latestRequest
187
+ ? {
188
+ latestRequest: {
189
+ taskId: latestRequest.taskId,
190
+ sourceId: latestRequest.id,
191
+ text: bounded(latestRequest.text),
192
+ },
193
+ }
194
+ : prior?.latestRequest
195
+ ? { latestRequest: prior.latestRequest }
196
+ : {}),
197
+ ...(conversation.attention && !conversation.closed
198
+ ? {
199
+ blocker: {
200
+ attentionId: conversation.attention.id,
201
+ taskId: conversation.attention.taskId,
202
+ question: bounded(conversation.attention.question),
203
+ },
204
+ }
205
+ : {}),
206
+ ...(outcome
207
+ ? {
208
+ lastOutcome: {
209
+ taskId: outcome.id,
210
+ status: outcome.status,
211
+ ...(outcome.report ? { text: bounded(outcome.report) } : {}),
212
+ },
213
+ }
214
+ : prior?.lastOutcome
215
+ ? { lastOutcome: prior.lastOutcome }
216
+ : {}),
217
+ decisions: (prior?.decisions ?? []).slice(-REFERENCE_LIMIT),
218
+ artifacts: [...artifacts.values()].slice(-REFERENCE_LIMIT),
219
+ ...(prior?.reported ? { reported: prior.reported } : {}),
220
+ };
221
+ }
222
+ /** Run after every canonical mutation and before persistence, including restart recovery. */
223
+ export function reconcileConversationState(previous, next) {
224
+ const oldConversations = new Map(previous.conversations.map((conversation) => [conversation.id, conversation]));
225
+ const oldMessages = new Set(previous.conversationMessages.map((message) => message.id));
226
+ const oldTasks = new Map(previous.tasks.map((task) => [task.id, task]));
227
+ const oldDeliveries = new Set(previous.deliveries.map((delivery) => delivery.id));
228
+ const oldReviews = new Set(previous.reviews.map((review) => review.id));
229
+ for (const conversation of next.conversations) {
230
+ const before = oldConversations.get(conversation.id);
231
+ // Only reported fields may be explicitly changed; the rest is always derived here.
232
+ const reported = conversation.taskState?.reported;
233
+ conversation.taskState = before?.taskState;
234
+ const projected = projectConversationState(next, conversation);
235
+ if (reported)
236
+ projected.reported = structuredClone(reported);
237
+ conversation.taskState = projected;
238
+ const events = structuredClone(before?.events ?? []);
239
+ let sequence = Math.max(before?.taskState?.revision ?? 0, events.at(-1)?.sequence ?? 0);
240
+ const append = (type, sourceId, createdAt, taskId, text, discriminator = "") => {
241
+ const id = createHash("sha256")
242
+ .update(JSON.stringify([conversation.id, type, sourceId, discriminator]))
243
+ .digest("hex");
244
+ if (events.some((event) => event.id === id))
245
+ return;
246
+ events.push({
247
+ id,
248
+ sequence: ++sequence,
249
+ type,
250
+ sourceId,
251
+ createdAt,
252
+ ...(taskId ? { taskId } : {}),
253
+ ...(text !== undefined ? { text: bounded(text) } : {}),
254
+ });
255
+ };
256
+ const newMessages = next.conversationMessages.filter((message) => message.conversationId === conversation.id && !oldMessages.has(message.id));
257
+ for (const message of newMessages) {
258
+ // Own execution reports are represented by the canonical task status transition.
259
+ const task = next.tasks.find((task) => task.id === message.taskId);
260
+ if (message.kind === "result" && (task?.kind !== "result" || message.sourceBotId === task.botId))
261
+ continue;
262
+ const type = message.kind === "request"
263
+ ? message.sourceBotId
264
+ ? "bot_request"
265
+ : "user_message"
266
+ : message.kind === "reply"
267
+ ? "bot_reply"
268
+ : message.kind === "result"
269
+ ? "worker_result"
270
+ : message.sourceBotId
271
+ ? "bot_request"
272
+ : "user_message";
273
+ append(type, message.id, message.createdAt, message.taskId, message.text);
274
+ }
275
+ for (const task of next.tasks) {
276
+ if (task.conversationId !== conversation.id || task.status === "queued")
277
+ continue;
278
+ const old = oldTasks.get(task.id);
279
+ if (old?.status === task.status && old.attemptId === task.attemptId)
280
+ continue;
281
+ const type = task.status === "running"
282
+ ? "execution_started"
283
+ : task.status === "completed"
284
+ ? "execution_completed"
285
+ : task.status === "failed"
286
+ ? "execution_failed"
287
+ : "execution_interrupted";
288
+ append(type, task.id, task.updatedAt, task.id, task.report, task.attemptId);
289
+ }
290
+ if (conversation.attention && conversation.attention.id !== before?.attention?.id)
291
+ append("attention_requested", conversation.attention.id, conversation.attention.createdAt, conversation.attention.taskId, conversation.attention.question);
292
+ if (before?.attention && before.attention.id !== conversation.attention?.id) {
293
+ const attention = before.attention;
294
+ const humans = newMessages.filter((message) => !message.sourceBotId && message.kind === "message" && message.createdAt >= attention.createdAt);
295
+ // Ambiguous removal (close/cancel/replacement) must never invent a human decision.
296
+ const answer = !conversation.closed && !conversation.attention && humans.length === 1 ? humans[0] : undefined;
297
+ append("attention_resolved", attention.id, answer?.createdAt ?? conversation.updatedAt, answer?.taskId ?? attention.taskId);
298
+ if (answer && attention.kind === "decision")
299
+ projected.decisions = [
300
+ ...projected.decisions,
301
+ {
302
+ attentionId: attention.id,
303
+ messageId: answer.id,
304
+ taskId: answer.taskId,
305
+ question: attention.question.slice(0, 2000),
306
+ answer: answer.text.slice(0, 2000),
307
+ ...(attention.question.length > 2000 ? { questionTruncated: true } : {}),
308
+ ...(answer.text.length > 2000 ? { answerTruncated: true } : {}),
309
+ },
310
+ ].slice(-REFERENCE_LIMIT);
311
+ }
312
+ for (const delivery of next.deliveries)
313
+ if (delivery.conversationId === conversation.id && !oldDeliveries.has(delivery.id))
314
+ append("delivery_recorded", delivery.id, delivery.createdAt, delivery.taskId, delivery.summary);
315
+ for (const review of next.reviews)
316
+ if (review.conversationId === conversation.id && !oldReviews.has(review.id))
317
+ append("review_recorded", review.id, review.createdAt, next.deliveries.find((delivery) => delivery.id === review.deliveryId)?.taskId, review.summary);
318
+ if (conversation.closed && !before?.closed)
319
+ append("conversation_closed", conversation.id, conversation.updatedAt, conversation.latestTaskId);
320
+ if (reported && JSON.stringify(reported) !== JSON.stringify(before?.taskState?.reported))
321
+ append("task_updated", reported.taskId, reported.updatedAt, reported.taskId, reported.progress, JSON.stringify([sequence + 1, reported]));
322
+ projected.revision = sequence;
323
+ conversation.events = events.slice(-CONVERSATION_EVENT_LIMIT);
324
+ let bytes = 2;
325
+ for (let index = conversation.events.length - 1; index >= 0; index--) {
326
+ bytes += Buffer.byteLength(JSON.stringify(conversation.events[index])) + 1;
327
+ if (bytes > 64 * 1024) {
328
+ conversation.events = conversation.events.slice(index + 1);
329
+ break;
330
+ }
331
+ }
332
+ }
333
+ }