@firstpick/pi-package-webui 0.9.2 → 0.9.4

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 (78) hide show
  1. package/README.md +14 -8
  2. package/bin/pi-webui.mjs +256 -39
  3. package/index.ts +266 -1
  4. package/lib/git-workflow-preferences.mjs +8 -25
  5. package/lib/intercom-conversations.mjs +491 -0
  6. package/lib/intercom-transcript-filter.mjs +99 -0
  7. package/lib/resource-selection.mjs +140 -0
  8. package/package.json +2 -2
  9. package/public/app.js +1061 -119
  10. package/public/index.html +31 -6
  11. package/public/service-worker.js +2 -1
  12. package/public/stream-output-controller.mjs +15 -0
  13. package/public/styles.css +426 -1
  14. package/public/syntax-highlight.mjs +622 -0
  15. package/tests/boot-failure-diagnostics.test.mjs +3 -3
  16. package/tests/browser/interaction-continuity.spec.mjs +34 -0
  17. package/tests/browser/intercom-conversation-viewer.spec.mjs +357 -0
  18. package/tests/browser/persistent-ui-layout.spec.mjs +61 -0
  19. package/tests/browser/resource-profiles.spec.mjs +200 -0
  20. package/tests/browser/subagent-observability.spec.mjs +29 -0
  21. package/tests/codex-fast-mode-static.test.mjs +7 -6
  22. package/tests/common-options-submenus-interaction-static.test.mjs +2 -0
  23. package/tests/common-options-submenus-markup-static.test.mjs +1 -0
  24. package/tests/composer-action-grid-reorder-static.test.mjs +3 -3
  25. package/tests/composer-skill-tag-layout.test.mjs +32 -2
  26. package/tests/control-deck-component-updates-static.test.mjs +4 -0
  27. package/tests/controls-layout-static.test.mjs +3 -3
  28. package/tests/fast-mode-client-static.test.mjs +2 -2
  29. package/tests/feature-decision-output-popup-static.test.mjs +2 -2
  30. package/tests/feature-system-prompt-optional-feature-static.test.mjs +5 -5
  31. package/tests/file-viewer-image-static.test.mjs +69 -0
  32. package/tests/fixtures/fake-pi.mjs +105 -6
  33. package/tests/foreground-transcript-catch-up-static.test.mjs +1 -1
  34. package/tests/git-panel-file-preview-static.test.mjs +5 -5
  35. package/tests/git-panel-live-updates-static.test.mjs +3 -3
  36. package/tests/git-workflow-preferences.test.mjs +4 -4
  37. package/tests/http-endpoints-harness.test.mjs +124 -2
  38. package/tests/intercom-conversation-viewer-static.test.mjs +106 -0
  39. package/tests/intercom-conversations-http.test.mjs +252 -0
  40. package/tests/intercom-conversations.test.mjs +374 -0
  41. package/tests/intercom-main-transcript-suppression-static.test.mjs +52 -0
  42. package/tests/intercom-tag-layout-static.test.mjs +46 -0
  43. package/tests/intercom-transcript-filter.test.mjs +98 -0
  44. package/tests/main-output-loading-static.test.mjs +59 -0
  45. package/tests/middle-button-drag-scroll-static.test.mjs +3 -3
  46. package/tests/mobile-compact-layout.test.mjs +2 -3
  47. package/tests/mobile-continuity-tablet-static.test.mjs +6 -6
  48. package/tests/mobile-foundation-static.test.mjs +3 -3
  49. package/tests/mobile-phone-experience-static.test.mjs +1 -1
  50. package/tests/mobile-static.test.mjs +66 -42
  51. package/tests/native-parity.test.mjs +8 -7
  52. package/tests/open-issue-wizard-static.test.mjs +1 -1
  53. package/tests/optional-feature-migration-frontend.test.mjs +5 -5
  54. package/tests/optional-feature-resource-setup-static.test.mjs +29 -0
  55. package/tests/persistent-ui-layout-static.test.mjs +3 -3
  56. package/tests/questionnaire-dialog.test.mjs +3 -3
  57. package/tests/remote-auth-settings-harness.test.mjs +1 -1
  58. package/tests/resource-defaults-helper.test.mjs +60 -6
  59. package/tests/resource-selection.test.mjs +114 -0
  60. package/tests/resource-tui-extension.test.mjs +23 -0
  61. package/tests/session-sampling-ui-static.test.mjs +3 -3
  62. package/tests/side-panel-section-height-removal-static.test.mjs +3 -3
  63. package/tests/stream-output-controller.test.mjs +8 -0
  64. package/tests/stream-output-isolation-static.test.mjs +2 -2
  65. package/tests/streaming-ui-coupling.test.mjs +5 -0
  66. package/tests/subagent-gate-visibility.test.mjs +1 -1
  67. package/tests/subagent-launch-slots.test.mjs +1 -1
  68. package/tests/subagent-observability-static.test.mjs +5 -3
  69. package/tests/subagent-reliability-integration.test.mjs +23 -1
  70. package/tests/subagent-workflow-section-static.test.mjs +67 -0
  71. package/tests/subagents-helper.test.mjs +313 -1
  72. package/tests/syntax-highlight.test.mjs +235 -0
  73. package/tests/syntax-highlighting-static.test.mjs +84 -0
  74. package/tests/terminal-cwd-grouping-static.test.mjs +22 -0
  75. package/tests/theme-customizer-static.test.mjs +5 -5
  76. package/tests/thinking-format-parser.test.mjs +64 -0
  77. package/tests/webui-settings-locking.test.mjs +1 -1
  78. package/webui-rpc-helper.mjs +417 -74
@@ -0,0 +1,491 @@
1
+ import { createHash } from "node:crypto";
2
+
3
+ export const INTERCOM_CONVERSATION_LIMITS = Object.freeze({
4
+ conversations: 32,
5
+ messagesPerConversation: 200,
6
+ messageTextBytes: 64 * 1024,
7
+ responseBytes: 2 * 1024 * 1024,
8
+ sourceEntries: 50_000,
9
+ acceptedEvents: 8_000,
10
+ acceptedTextBytes: 16 * 1024 * 1024,
11
+ });
12
+
13
+ const SYNTHETIC_PEERS = new Set(["subagent-control", "subagent-result"]);
14
+ const NATIVE_REPLY_MARKER = "\n\nReply with: subagent_supervisor(";
15
+
16
+ function objectValue(value) {
17
+ return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
18
+ }
19
+
20
+ function boundedString(value, maxLength = 240) {
21
+ if (typeof value !== "string") return "";
22
+ const text = value.trim();
23
+ return text ? text.slice(0, maxLength) : "";
24
+ }
25
+
26
+ function normalizedIdentity(value) {
27
+ return boundedString(value, 240).toLocaleLowerCase();
28
+ }
29
+
30
+ function isSyntheticPeer(id, name) {
31
+ return SYNTHETIC_PEERS.has(normalizedIdentity(id)) || SYNTHETIC_PEERS.has(normalizedIdentity(name));
32
+ }
33
+
34
+ function boundedLimit(value, fallback, minimum = 1) {
35
+ const numeric = Number(value);
36
+ if (!Number.isInteger(numeric) || numeric < minimum) return fallback;
37
+ return Math.min(numeric, fallback);
38
+ }
39
+
40
+ function textWithinBytes(value, maxBytes) {
41
+ if (typeof value !== "string" || !value.trim() || maxBytes < 1) return undefined;
42
+ const candidate = value.length > maxBytes ? value.slice(0, maxBytes) : value;
43
+ const candidateBytes = Buffer.byteLength(candidate, "utf8");
44
+ if (candidate.length === value.length && candidateBytes <= maxBytes) return { text: candidate, truncated: false };
45
+ let low = 0;
46
+ let high = candidate.length;
47
+ while (low < high) {
48
+ const middle = Math.ceil((low + high) / 2);
49
+ if (Buffer.byteLength(candidate.slice(0, middle), "utf8") <= maxBytes) low = middle;
50
+ else high = middle - 1;
51
+ }
52
+ let text = candidate.slice(0, low);
53
+ const finalCode = text.charCodeAt(text.length - 1);
54
+ if (finalCode >= 0xd800 && finalCode <= 0xdbff) text = text.slice(0, -1);
55
+ return { text, truncated: true };
56
+ }
57
+
58
+ function timestampData(primary, fallback, order) {
59
+ for (const candidate of [primary, fallback]) {
60
+ if (candidate === undefined || candidate === null || candidate === "") continue;
61
+ const date = new Date(candidate);
62
+ if (!Number.isNaN(date.getTime())) return { ms: date.getTime(), iso: date.toISOString(), order };
63
+ }
64
+ return { ms: 0, iso: null, order };
65
+ }
66
+
67
+ function opaqueId(prefix, value) {
68
+ return `${prefix}_${createHash("sha256").update(String(value)).digest("base64url").slice(0, 24)}`;
69
+ }
70
+
71
+ function positiveTimestamp(value) {
72
+ const numeric = Number(value);
73
+ if (Number.isFinite(numeric) && numeric > 0) return numeric;
74
+ if (typeof value !== "string" || !value.trim()) return 0;
75
+ const parsed = Date.parse(value);
76
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : 0;
77
+ }
78
+
79
+ function fullSessionId(value) {
80
+ const id = boundedString(value, 240);
81
+ return /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(id) ? id : "";
82
+ }
83
+
84
+ function sessionIdAlias(value) {
85
+ const id = normalizedIdentity(value);
86
+ const match = id.match(/^([0-9a-f]{8})(?:-|$)/i);
87
+ return match?.[1] || "";
88
+ }
89
+
90
+ function labelMatchesSessionId(label, id) {
91
+ const normalizedLabel = normalizedIdentity(label);
92
+ const normalizedId = normalizedIdentity(id);
93
+ if (!normalizedLabel || !normalizedId) return false;
94
+ if (normalizedLabel === normalizedId) return true;
95
+ const alias = sessionIdAlias(normalizedId);
96
+ return Boolean(alias) && normalizedLabel.split(/[^a-z0-9]+/).includes(alias);
97
+ }
98
+
99
+ function peerIdentity(value) {
100
+ const peer = objectValue(value);
101
+ if (peer) {
102
+ return {
103
+ id: boundedString(peer.id, 240),
104
+ name: boundedString(peer.name, 160),
105
+ startedAt: positiveTimestamp(peer.startedAt),
106
+ };
107
+ }
108
+ const name = boundedString(value, 160);
109
+ return { id: fullSessionId(name), name, startedAt: 0 };
110
+ }
111
+
112
+ function genericInbound(entry, order, maxTextBytes) {
113
+ if (entry?.type !== "custom_message" || entry.customType !== "intercom_message") return undefined;
114
+ const details = objectValue(entry.details);
115
+ const from = peerIdentity(details?.from);
116
+ const message = objectValue(details?.message);
117
+ const content = objectValue(message?.content);
118
+ const messageId = boundedString(message?.id, 240);
119
+ const boundedText = textWithinBytes(content?.text, maxTextBytes);
120
+ if (!messageId || !boundedText || (!from.id && !from.name) || isSyntheticPeer(from.id, from.name)) return undefined;
121
+ return {
122
+ eventKey: `generic:${messageId}`,
123
+ messageId,
124
+ precedence: 3,
125
+ direction: "peer",
126
+ peerId: from.id,
127
+ peerName: from.name || from.id,
128
+ peerStartedAt: from.startedAt,
129
+ replyTo: boundedString(message?.replyTo, 240),
130
+ text: boundedText.text,
131
+ truncatedText: boundedText.truncated,
132
+ time: timestampData(message?.timestamp, entry.timestamp, order),
133
+ };
134
+ }
135
+
136
+ function genericCustom(entry, order, maxTextBytes) {
137
+ if (entry?.type !== "custom" || (entry.customType !== "intercom_sent" && entry.customType !== "intercom_received")) return undefined;
138
+ const data = objectValue(entry.data);
139
+ const message = objectValue(data?.message);
140
+ const messageId = boundedString(data?.messageId, 240);
141
+ const boundedText = textWithinBytes(message?.text, maxTextBytes);
142
+ const outbound = entry.customType === "intercom_sent";
143
+ const peer = peerIdentity(outbound ? data?.to : data?.from);
144
+ if (!messageId || !boundedText || (!peer.id && !peer.name) || isSyntheticPeer(peer.id, peer.name)) return undefined;
145
+ return {
146
+ eventKey: `generic:${messageId}`,
147
+ messageId,
148
+ precedence: outbound ? 1 : 2,
149
+ direction: outbound ? "local" : "peer",
150
+ peerId: peer.id,
151
+ peerName: peer.name || peer.id,
152
+ replyTo: boundedString(message?.replyTo, 240),
153
+ text: boundedText.text,
154
+ truncatedText: boundedText.truncated,
155
+ time: timestampData(data?.timestamp, entry.timestamp, order),
156
+ };
157
+ }
158
+
159
+ function nativeRequestText(entry, maxTextBytes) {
160
+ if (typeof entry?.content !== "string") return undefined;
161
+ const markerIndex = entry.content.indexOf(NATIVE_REPLY_MARKER);
162
+ const visibleText = (markerIndex >= 0 ? entry.content.slice(0, markerIndex) : entry.content).trimEnd();
163
+ return textWithinBytes(visibleText, maxTextBytes);
164
+ }
165
+
166
+ function nativeRequest(entry, order, maxTextBytes) {
167
+ if (entry?.type !== "custom_message" || entry.customType !== "subagent_supervisor_request") return undefined;
168
+ const details = objectValue(entry.details);
169
+ const requestId = boundedString(details?.id, 240);
170
+ const runId = boundedString(details?.runId, 240);
171
+ const agent = boundedString(details?.agent, 160);
172
+ const childIndex = Number(details?.childIndex);
173
+ const boundedText = nativeRequestText(entry, maxTextBytes);
174
+ if (!requestId || !runId || !agent || !Number.isInteger(childIndex) || childIndex < 0 || !boundedText) return undefined;
175
+ return {
176
+ requestId,
177
+ runId,
178
+ agent,
179
+ childIndex,
180
+ eventKey: `native:${requestId}:request`,
181
+ direction: "peer",
182
+ text: boundedText.text,
183
+ truncatedText: boundedText.truncated,
184
+ time: timestampData(undefined, entry.timestamp, order),
185
+ };
186
+ }
187
+
188
+ function nativeReplyCall(entry, order, maxTextBytes) {
189
+ if (entry?.type !== "message" || entry.message?.role !== "assistant" || !Array.isArray(entry.message.content)) return [];
190
+ const calls = [];
191
+ for (const part of entry.message.content) {
192
+ if (part?.type !== "toolCall" || part.toolName !== "subagent_supervisor") continue;
193
+ const args = objectValue(part.arguments) || objectValue(part.args);
194
+ const toolCallId = boundedString(part.id || part.toolCallId, 512);
195
+ const requestId = boundedString(args?.replyTo, 240);
196
+ const boundedText = textWithinBytes(args?.message, maxTextBytes);
197
+ if (!toolCallId || args?.action !== "reply" || !requestId || !boundedText) continue;
198
+ calls.push({ toolCallId, requestId, text: boundedText.text, truncatedText: boundedText.truncated, time: timestampData(entry.message.timestamp, entry.timestamp, order) });
199
+ }
200
+ return calls;
201
+ }
202
+
203
+ function successfulNativeReplyResult(entry) {
204
+ if (entry?.type !== "message" || entry.message?.role !== "toolResult" || entry.message.toolName !== "subagent_supervisor" || entry.message.isError === true) return undefined;
205
+ const details = objectValue(entry.message.details);
206
+ const toolCallId = boundedString(entry.message.toolCallId, 512);
207
+ const requestId = boundedString(details?.replyTo, 240);
208
+ if (!toolCallId || !requestId) return undefined;
209
+ return {
210
+ toolCallId,
211
+ requestId,
212
+ runId: boundedString(details?.runId, 240),
213
+ agent: boundedString(details?.agent, 160),
214
+ time: timestampData(entry.message.timestamp, entry.timestamp, 0),
215
+ };
216
+ }
217
+
218
+ function compareEvents(left, right) {
219
+ return left.time.ms - right.time.ms || left.time.order - right.time.order || left.eventKey.localeCompare(right.eventKey);
220
+ }
221
+
222
+ function resolveGenericPeers(events) {
223
+ const parent = new Map(events.map((event) => [event.messageId, event.messageId]));
224
+ const rank = new Map(events.map((event) => [event.messageId, 0]));
225
+ const find = (messageId) => {
226
+ let root = messageId;
227
+ while (parent.get(root) !== root) root = parent.get(root);
228
+ let current = messageId;
229
+ while (current !== root) {
230
+ const next = parent.get(current);
231
+ parent.set(current, root);
232
+ current = next;
233
+ }
234
+ return root;
235
+ };
236
+ const union = (left, right) => {
237
+ let leftRoot = find(left);
238
+ let rightRoot = find(right);
239
+ if (leftRoot === rightRoot) return;
240
+ const leftRank = rank.get(leftRoot) || 0;
241
+ const rightRank = rank.get(rightRoot) || 0;
242
+ if (leftRank < rightRank) [leftRoot, rightRoot] = [rightRoot, leftRoot];
243
+ parent.set(rightRoot, leftRoot);
244
+ if (leftRank === rightRank) rank.set(leftRoot, leftRank + 1);
245
+ };
246
+
247
+ for (const event of events) {
248
+ if (event.replyTo && parent.has(event.replyTo)) union(event.messageId, event.replyTo);
249
+ }
250
+
251
+ const components = new Map();
252
+ const stablePeers = new Map();
253
+ for (const event of events) {
254
+ const root = find(event.messageId);
255
+ if (!components.has(root)) components.set(root, []);
256
+ components.get(root).push(event);
257
+ if (!event.peerId) continue;
258
+ if (!stablePeers.has(event.peerId)) {
259
+ stablePeers.set(event.peerId, { id: event.peerId, names: new Set(), startedAt: 0, canonicalName: "", canonicalOrder: -1 });
260
+ }
261
+ const peer = stablePeers.get(event.peerId);
262
+ const name = normalizedIdentity(event.peerName);
263
+ if (name) peer.names.add(name);
264
+ const startedAt = positiveTimestamp(event.peerStartedAt);
265
+ if (startedAt && (!peer.startedAt || startedAt < peer.startedAt)) peer.startedAt = startedAt;
266
+ if (event.peerName && event.time.order >= peer.canonicalOrder) {
267
+ peer.canonicalName = event.peerName;
268
+ peer.canonicalOrder = event.time.order;
269
+ }
270
+ }
271
+
272
+ const assignPeer = (component, peerId) => {
273
+ const canonicalName = stablePeers.get(peerId)?.canonicalName || "";
274
+ for (const event of component) {
275
+ if (!event.peerId) event.peerId = peerId;
276
+ if (canonicalName) event.peerName = canonicalName;
277
+ }
278
+ };
279
+
280
+ for (const component of components.values()) {
281
+ const existingIds = new Set(component.map((event) => event.peerId).filter(Boolean));
282
+ if (existingIds.size === 1) {
283
+ assignPeer(component, existingIds.values().next().value);
284
+ continue;
285
+ }
286
+ if (existingIds.size > 1) continue;
287
+
288
+ const aliasMatches = new Set();
289
+ for (const event of component) {
290
+ for (const peer of stablePeers.values()) {
291
+ if (labelMatchesSessionId(event.peerName, peer.id)) aliasMatches.add(peer.id);
292
+ }
293
+ }
294
+ if (aliasMatches.size === 1) {
295
+ assignPeer(component, aliasMatches.values().next().value);
296
+ continue;
297
+ }
298
+ if (aliasMatches.size > 1) continue;
299
+
300
+ const nameMatches = new Set();
301
+ for (const event of component) {
302
+ const name = normalizedIdentity(event.peerName);
303
+ if (!name || !event.time.ms) continue;
304
+ for (const peer of stablePeers.values()) {
305
+ if (peer.startedAt && peer.startedAt <= event.time.ms && peer.names.has(name)) nameMatches.add(peer.id);
306
+ }
307
+ }
308
+ if (nameMatches.size === 1) assignPeer(component, nameMatches.values().next().value);
309
+ }
310
+
311
+ for (const event of events) {
312
+ const canonicalName = stablePeers.get(event.peerId)?.canonicalName;
313
+ if (canonicalName) event.peerName = canonicalName;
314
+ }
315
+ }
316
+
317
+ function publicParticipant(id, name, fallback) {
318
+ const safeId = boundedString(id, 240);
319
+ const safeName = boundedString(name, 160) || safeId || fallback;
320
+ return { id: safeId || null, name: safeName };
321
+ }
322
+
323
+ function summaryForConversation(conversation) {
324
+ return {
325
+ id: conversation.id,
326
+ participants: conversation.participants,
327
+ messageCount: conversation.totalMessages,
328
+ lastMessageAt: conversation.lastMessageAt,
329
+ truncatedBefore: conversation.truncatedBefore,
330
+ };
331
+ }
332
+
333
+ function detailForConversation(conversation) {
334
+ return {
335
+ ...summaryForConversation(conversation),
336
+ messages: conversation.messages.map((message) => ({
337
+ id: opaqueId("msg", message.eventKey),
338
+ direction: message.direction,
339
+ sender: message.direction === "local" ? conversation.participants.local : conversation.participants.peer,
340
+ text: message.text,
341
+ timestamp: message.time.iso,
342
+ truncatedText: message.truncatedText,
343
+ })),
344
+ };
345
+ }
346
+
347
+ /**
348
+ * Project whitelisted active-branch Pi session entries into browser-safe agent conversations.
349
+ * The caller owns active-branch selection; pass SessionManager#getBranch(), never raw file entries.
350
+ */
351
+ export function projectIntercomConversations(entries, options = {}) {
352
+ const limits = {
353
+ conversations: boundedLimit(options.maxConversations, INTERCOM_CONVERSATION_LIMITS.conversations),
354
+ messages: boundedLimit(options.maxMessagesPerConversation, INTERCOM_CONVERSATION_LIMITS.messagesPerConversation),
355
+ textBytes: boundedLimit(options.maxMessageTextBytes, INTERCOM_CONVERSATION_LIMITS.messageTextBytes),
356
+ responseBytes: boundedLimit(options.maxResponseBytes, INTERCOM_CONVERSATION_LIMITS.responseBytes, 256),
357
+ sourceEntries: boundedLimit(options.maxSourceEntries, INTERCOM_CONVERSATION_LIMITS.sourceEntries),
358
+ acceptedEvents: boundedLimit(options.maxAcceptedEvents, INTERCOM_CONVERSATION_LIMITS.acceptedEvents),
359
+ acceptedTextBytes: boundedLimit(options.maxAcceptedTextBytes, INTERCOM_CONVERSATION_LIMITS.acceptedTextBytes),
360
+ };
361
+ const localId = boundedString(options.localSessionId, 240) || "local";
362
+ const localName = boundedString(options.localName, 160) || localId;
363
+ const requestedConversationId = boundedString(options.conversationId, 128);
364
+ const sourceEntries = Array.isArray(entries) ? entries : [];
365
+ const sourceStart = Math.max(0, sourceEntries.length - limits.sourceEntries);
366
+ let sourceTruncated = sourceStart > 0;
367
+ let acceptedEvents = 0;
368
+ let acceptedTextBytes = 0;
369
+
370
+ const genericByKey = new Map();
371
+ const requests = new Map();
372
+ const replyCalls = new Map();
373
+ const replyResults = [];
374
+ const acceptEvent = (event) => {
375
+ if (!event) return false;
376
+ const textBytes = typeof event.text === "string" ? Buffer.byteLength(event.text, "utf8") : 0;
377
+ if (acceptedEvents >= limits.acceptedEvents || acceptedTextBytes + textBytes > limits.acceptedTextBytes) {
378
+ sourceTruncated = true;
379
+ return false;
380
+ }
381
+ acceptedEvents += 1;
382
+ acceptedTextBytes += textBytes;
383
+ return true;
384
+ };
385
+
386
+ entryLoop: for (let order = sourceEntries.length - 1; order >= sourceStart; order--) {
387
+ if (acceptedEvents >= limits.acceptedEvents || acceptedTextBytes >= limits.acceptedTextBytes) {
388
+ sourceTruncated = true;
389
+ break;
390
+ }
391
+ const entry = sourceEntries[order];
392
+ const textLimit = Math.min(limits.textBytes, limits.acceptedTextBytes - acceptedTextBytes);
393
+ const generic = genericInbound(entry, order, textLimit) || genericCustom(entry, order, textLimit);
394
+ if (generic) {
395
+ if (!acceptEvent(generic)) break;
396
+ const current = genericByKey.get(generic.eventKey);
397
+ if (!current || generic.precedence > current.precedence) genericByKey.set(generic.eventKey, generic);
398
+ }
399
+ const request = nativeRequest(entry, order, textLimit);
400
+ if (request) {
401
+ if (!acceptEvent(request)) break;
402
+ if (!requests.has(request.requestId)) requests.set(request.requestId, request);
403
+ }
404
+ for (const call of nativeReplyCall(entry, order, textLimit)) {
405
+ if (!acceptEvent(call)) break entryLoop;
406
+ if (!replyCalls.has(call.toolCallId)) replyCalls.set(call.toolCallId, call);
407
+ }
408
+ const result = successfulNativeReplyResult(entry);
409
+ if (result) {
410
+ if (!acceptEvent(result)) break;
411
+ result.time.order = order;
412
+ replyResults.push(result);
413
+ }
414
+ }
415
+
416
+ const genericEvents = [...genericByKey.values()].sort(compareEvents);
417
+ resolveGenericPeers(genericEvents);
418
+ const groups = new Map();
419
+ const ensureGroup = (key, peerId, peerName) => {
420
+ if (!groups.has(key)) groups.set(key, { key, peerId, peerName, messagesByKey: new Map() });
421
+ const group = groups.get(key);
422
+ if (peerName) group.peerName = peerName;
423
+ if (peerId) group.peerId = peerId;
424
+ return group;
425
+ };
426
+ const appendGroupEvent = (group, event) => {
427
+ if (!group.messagesByKey.has(event.eventKey)) group.messagesByKey.set(event.eventKey, event);
428
+ };
429
+
430
+ for (const event of genericEvents) {
431
+ if (isSyntheticPeer(event.peerId, event.peerName)) continue;
432
+ const key = event.peerId ? `generic:id:${event.peerId}` : `generic:label:${normalizedIdentity(event.peerName)}`;
433
+ if (!normalizedIdentity(event.peerName) && !event.peerId) continue;
434
+ appendGroupEvent(ensureGroup(key, event.peerId, event.peerName), event);
435
+ }
436
+
437
+ for (const request of requests.values()) {
438
+ const key = `native:${localId}:${request.runId}:${request.childIndex}:${request.agent}`;
439
+ appendGroupEvent(ensureGroup(key, `${request.runId}:${request.childIndex}`, request.agent), request);
440
+ }
441
+ for (const result of replyResults) {
442
+ const call = replyCalls.get(result.toolCallId);
443
+ const request = requests.get(result.requestId);
444
+ if (!call || !request || call.requestId !== result.requestId) continue;
445
+ if ((result.runId && result.runId !== request.runId) || (result.agent && result.agent !== request.agent)) continue;
446
+ const key = `native:${localId}:${request.runId}:${request.childIndex}:${request.agent}`;
447
+ appendGroupEvent(ensureGroup(key, `${request.runId}:${request.childIndex}`, request.agent), {
448
+ eventKey: `native:${request.requestId}:reply`,
449
+ direction: "local",
450
+ text: call.text,
451
+ truncatedText: call.truncatedText,
452
+ time: { ...result.time, iso: result.time.iso || call.time.iso, ms: result.time.ms || call.time.ms },
453
+ });
454
+ }
455
+
456
+ const conversations = [...groups.values()].map((group) => {
457
+ const allMessages = [...group.messagesByKey.values()].sort(compareEvents);
458
+ const totalMessages = allMessages.length;
459
+ const messages = allMessages.slice(-limits.messages);
460
+ const lastMessage = allMessages.at(-1);
461
+ return {
462
+ id: opaqueId("conv", `${localId}\0${group.key}`),
463
+ participants: {
464
+ local: publicParticipant(localId, localName, "Local agent"),
465
+ peer: publicParticipant(group.peerId, group.peerName, "Peer agent"),
466
+ },
467
+ messages,
468
+ totalMessages,
469
+ lastMessageAt: lastMessage?.time.iso || null,
470
+ lastMessageOrder: lastMessage?.time.order || 0,
471
+ lastMessageMs: lastMessage?.time.ms || 0,
472
+ truncatedBefore: sourceTruncated || totalMessages > messages.length,
473
+ key: group.key,
474
+ };
475
+ });
476
+ conversations.sort((left, right) => right.lastMessageMs - left.lastMessageMs || right.lastMessageOrder - left.lastMessageOrder || left.key.localeCompare(right.key));
477
+
478
+ const visible = conversations.slice(0, limits.conversations);
479
+ const selected = requestedConversationId ? visible.find((conversation) => conversation.id === requestedConversationId) : undefined;
480
+ const result = {
481
+ version: 1,
482
+ conversations: requestedConversationId ? [] : visible.map(summaryForConversation),
483
+ conversation: selected ? detailForConversation(selected) : null,
484
+ truncatedConversations: requestedConversationId ? 0 : Math.max(0, conversations.length - visible.length),
485
+ };
486
+ while (result.conversation?.messages.length && Buffer.byteLength(JSON.stringify(result), "utf8") > limits.responseBytes) {
487
+ result.conversation.messages.shift();
488
+ result.conversation.truncatedBefore = true;
489
+ }
490
+ return result;
491
+ }
@@ -0,0 +1,99 @@
1
+ const INTERCOM_TOOL_NAME = "intercom";
2
+ const INTERCOM_CUSTOM_TYPE = "intercom_message";
3
+
4
+ function normalizedToolName(record) {
5
+ if (!record || typeof record !== "object" || Array.isArray(record)) return "";
6
+ const candidate = record.toolName || record.name || record.toolCall?.toolName || record.toolCall?.name;
7
+ return typeof candidate === "string" ? candidate.trim().toLowerCase() : "";
8
+ }
9
+
10
+ function normalizedId(value) {
11
+ return value === undefined || value === null ? "" : String(value).trim();
12
+ }
13
+
14
+ function assistantToolCallId(part) {
15
+ return normalizedId(part?.id ?? part?.toolCallId ?? part?.tool_call_id
16
+ ?? part?.toolCall?.id ?? part?.toolCall?.toolCallId ?? part?.toolCall?.tool_call_id);
17
+ }
18
+
19
+ function directToolCallId(message) {
20
+ return normalizedId(message?.toolCallId ?? message?.tool_call_id ?? message?.id
21
+ ?? message?.toolCall?.toolCallId ?? message?.toolCall?.tool_call_id ?? message?.toolCall?.id);
22
+ }
23
+
24
+ function toolResultCallId(message) {
25
+ return normalizedId(message?.toolCallId ?? message?.tool_call_id);
26
+ }
27
+
28
+ function isIntercomToolCallPart(part) {
29
+ return part?.type === "toolCall" && normalizedToolName(part) === INTERCOM_TOOL_NAME;
30
+ }
31
+
32
+ function isDirectIntercomToolCall(message) {
33
+ return message?.role === "toolCall" && normalizedToolName(message) === INTERCOM_TOOL_NAME;
34
+ }
35
+
36
+ function isIntercomCustomMessage(message) {
37
+ return message?.role === "custom" && message.customType === INTERCOM_CUSTOM_TYPE;
38
+ }
39
+
40
+ function isPairedIntercomToolResult(message, intercomToolCallIds) {
41
+ if (message?.role !== "toolResult") return false;
42
+ if (normalizedToolName(message) === INTERCOM_TOOL_NAME) return true;
43
+ const id = toolResultCallId(message);
44
+ return Boolean(id) && intercomToolCallIds.has(id);
45
+ }
46
+
47
+ function hasMeaningfulAssistantPart(part) {
48
+ if (typeof part === "string") return Boolean(part.trim());
49
+ if (!part || typeof part !== "object") return part !== undefined && part !== null;
50
+ if (part.type === "text") {
51
+ const text = part.text ?? part.content;
52
+ return typeof text !== "string" || Boolean(text.trim());
53
+ }
54
+ if (part.type === "thinking") {
55
+ const thinking = part.thinking ?? part.text ?? part.content;
56
+ return typeof thinking !== "string" || Boolean(thinking.trim());
57
+ }
58
+ return true;
59
+ }
60
+
61
+ /**
62
+ * Remove generic Intercom transport records from a normalized Pi transcript.
63
+ * The input array, messages, and content parts are never mutated.
64
+ */
65
+ export function filterIntercomTranscriptMessages(messages) {
66
+ if (!Array.isArray(messages)) return [];
67
+
68
+ const intercomToolCallIds = new Set();
69
+ for (const message of messages) {
70
+ if (isDirectIntercomToolCall(message)) {
71
+ const id = directToolCallId(message);
72
+ if (id) intercomToolCallIds.add(id);
73
+ }
74
+ if (message?.role !== "assistant" || !Array.isArray(message.content)) continue;
75
+ for (const part of message.content) {
76
+ if (!isIntercomToolCallPart(part)) continue;
77
+ const id = assistantToolCallId(part);
78
+ if (id) intercomToolCallIds.add(id);
79
+ }
80
+ }
81
+
82
+ const filtered = [];
83
+ for (const message of messages) {
84
+ if (isIntercomCustomMessage(message) || isDirectIntercomToolCall(message) || isPairedIntercomToolResult(message, intercomToolCallIds)) continue;
85
+
86
+ if (message?.role !== "assistant" || !Array.isArray(message.content)) {
87
+ filtered.push(message);
88
+ continue;
89
+ }
90
+
91
+ const content = message.content.filter((part) => !isIntercomToolCallPart(part));
92
+ if (content.length === message.content.length) {
93
+ filtered.push(message);
94
+ continue;
95
+ }
96
+ if (content.some(hasMeaningfulAssistantPart)) filtered.push({ ...message, content });
97
+ }
98
+ return filtered;
99
+ }