Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ActivityPayloadProjection.ts

689 lines21.5 KB

1import { projectQuestionToolInput } from "@t3tools/shared/toolActivity";
2import type {
3 OrchestrationEvent,
4 OrchestrationThreadActivity,
5 OrchestrationThreadDetailSnapshot,
6} from "@t3tools/contracts";
7import { isWorkspaceImagePreviewPath } from "@t3tools/shared/filePreview";
8import { extractJsonObject } from "@t3tools/shared/schemaJson";
9​
10function asRecord(value: unknown): Record<string, unknown> | null {
11 return value !== null && typeof value === "object" && !Array.isArray(value)
12 ? (value as Record<string, unknown>)
13 : null;
15​
16function asTrimmedString(value: unknown): string | null {
17 if (typeof value !== "string") {
18 return null;
19 }
20 const trimmed = value.trim();
21 return trimmed.length > 0 ? trimmed : null;
23​
24function pushChangedFile(target: string[], seen: Set<string>, value: unknown): void {
25 const normalized = asTrimmedString(value);
26 if (!normalized || seen.has(normalized)) {
27 return;
28 }
29 seen.add(normalized);
30 target.push(normalized);
32​
33function collectChangedFiles(
34 value: unknown,
35 target: string[],
36 seen: Set<string>,
37 depth: number,
38): void {
39 if (depth > 4 || target.length >= 12) {
40 return;
41 }
42 if (Array.isArray(value)) {
43 for (const entry of value) {
44 collectChangedFiles(entry, target, seen, depth + 1);
45 if (target.length >= 12) {
46 return;
47 }
48 }
49 return;
50 }
51​
52 const record = asRecord(value);
53 if (!record) {
54 return;
55 }
56​
57 pushChangedFile(target, seen, record.path);
58 pushChangedFile(target, seen, record.filePath);
59 pushChangedFile(target, seen, record.relativePath);
60 pushChangedFile(target, seen, record.filename);
61 pushChangedFile(target, seen, record.newPath);
62 pushChangedFile(target, seen, record.oldPath);
63​
64 for (const nestedKey of [
65 "item",
66 "result",
67 "input",
68 "data",
69 "changes",
70 "files",
71 "edits",
72 "patch",
73 "patches",
74 "operations",
75 ]) {
76 if (!(nestedKey in record)) {
77 continue;
78 }
79 collectChangedFiles(record[nestedKey], target, seen, depth + 1);
80 if (target.length >= 12) {
81 return;
82 }
83 }
85​
86function projectCommandData(data: Record<string, unknown>): Record<string, unknown> | undefined {
87 const item = asRecord(data.item);
88 if (!item) {
89 return undefined;
90 }
91​
92 const projectedItem: Record<string, unknown> = {};
93 if ("command" in item) {
94 projectedItem.command = item.command;
95 }
96​
97 const aggregatedOutput = asTrimmedString(item.aggregatedOutput);
98 if (aggregatedOutput) {
99 const summary = summarizeToolTextOutput(aggregatedOutput);
100 if (summary) {
101 projectedItem.aggregatedOutput = summary;
102 }
103 }
104​
105 const input = asRecord(item.input);
106 if (input && "command" in input) {
107 projectedItem.input = { command: input.command };
108 }
109​
110 const result = asRecord(item.result);
111 if (result) {
112 const projectedResult: Record<string, unknown> = {};
113 if ("command" in result) {
114 projectedResult.command = result.command;
115 }
116 const content = asTrimmedString(result.content);
117 if (content) {
118 const summary = summarizeToolTextOutput(content);
119 if (summary) {
120 projectedResult.content = summary;
121 }
122 }
123 if (Object.keys(projectedResult).length > 0) {
124 projectedItem.result = projectedResult;
125 }
126 }
127​
128 return Object.keys(projectedItem).length > 0 ? projectedItem : undefined;
130​
131function projectCommandValue(data: Record<string, unknown>): unknown {
132 if (data.command !== undefined) {
133 return data.command;
134 }
135​
136 const input = asRecord(data.input);
137 if (input?.command !== undefined) {
138 return input.command;
139 }
140​
141 const stateInput = asRecord(asRecord(data.state)?.input);
142 if (stateInput?.command !== undefined) {
143 return stateInput.command;
144 }
145​
146 return undefined;
148​
149function projectViewedImagePath(data: Record<string, unknown>): string | undefined {
150 const directPath = asTrimmedString(data.imagePath);
151 if (directPath && isWorkspaceImagePreviewPath(directPath)) {
152 return directPath;
153 }
154​
155 const toolName = asTrimmedString(data.toolName)?.toLowerCase();
156 if (toolName !== "read" && toolName !== "read file") {
157 return undefined;
158 }
159 const input = asRecord(data.input);
160 const inputPath = asTrimmedString(input?.file_path) ?? asTrimmedString(input?.path);
161 return inputPath && isWorkspaceImagePreviewPath(inputPath) ? inputPath : undefined;
163​
164function summarizeToolTextOutput(value: string): string | null {
165 let meaningfulLineCount = 0;
166 let offset = 0;
167​
168 while (offset <= value.length) {
169 const newlineIndex = value.indexOf("\n", offset);
170 const lineEnd = newlineIndex === -1 ? value.length : newlineIndex;
171 const line = value.slice(offset, lineEnd).replace(/\s+/g, " ").trim();
172 if (line.length > 0) {
173 meaningfulLineCount += 1;
174 if (line !== "```") {
175 const summary = line.length <= 84 ? line : `${line.slice(0, 83).trimEnd()}…`;
176 // V8 can retain the full tool output behind a short sliced string.
177 // Join a tiny character array so the returned preview owns its bytes.
178 return Array.from(summary).join("");
179 }
180 }
181 if (newlineIndex === -1) {
182 break;
183 }
184 offset = newlineIndex + 1;
185 }
186​
187 return meaningfulLineCount > 1 ? `${meaningfulLineCount.toLocaleString()} lines` : null;
189​
190/**
191 * Fields of an MCP tool-call item both clients render in the expanded
192 * work-log row. Everything else — notably `result`, which carries the full
193 * tool output and dominates wire size on MCP-heavy threads — is summarized
194 * or dropped. Full payloads remain in persistence.
195 */
196const MCP_ITEM_KEPT_FIELDS = [
197 "type",
198 "id",
199 "tool",
200 "server",
201 "status",
202 "arguments",
203 "appContext",
204 "error",
205 "durationMs",
206] as const;
207​
208/**
209 * Pulls renderable text out of an MCP tool result: either a Codex-style
210 * `{content: [{type: "text", text}, ...]}` record or a raw Claude
211 * `tool_result` block whose `content` is a string or block array.
212 */
213function extractMcpResultText(result: unknown): string | null {
214 const record = asRecord(result);
215 if (!record) {
216 return typeof result === "string" ? result : null;
217 }
218 if (typeof record.content === "string") {
219 return record.content;
220 }
221 if (Array.isArray(record.content)) {
222 const texts: string[] = [];
223 for (const entry of record.content) {
224 const text = asRecord(entry)?.text;
225 if (typeof text === "string" && text.trim().length > 0) {
226 texts.push(text);
227 }
228 }
229 if (texts.length > 0) {
230 return texts.join("\n");
231 }
232 }
233 return null;
235​
236function summarizeMcpResult(result: unknown): Record<string, unknown> | undefined {
237 if (result === undefined || result === null) {
238 return undefined;
239 }
240 const text = extractMcpResultText(result);
241 const summary = text ? summarizeToolTextOutput(text) : null;
242 return summary ? { content: summary } : undefined;
244​
245/** Reuse the page URL already returned by preview tools before slimming their output. */
246function projectPreviewToolMetadata(data: Record<string, unknown>, status: unknown) {
247 const item = asRecord(data.item);
248 const name = item ? `mcp__${item.server}__${item.tool}` : (data.toolName ?? data.tool);
249 if (
250 typeof name !== "string" ||
251 !/^(?:mcp__)?(?:t3-code|t3_code|t3code)_{1,2}preview_(?:open|navigate|status|snapshot|click|type|press|scroll|resize|set_appearance|evaluate|wait_for|recording_start|recording_stop)$/.test(
252 name,
253 )
254 )
255 return {};
256 const state = asRecord(data.state);
257 const result = item?.result ?? data.result ?? state?.output;
258 const record = asRecord(result);
259 if (
260 status === "failed" ||
261 status === "declined" ||
262 state?.status === "error" ||
263 item?.error != null ||
264 record?.isError === true ||
265 record?.is_error === true
266 )
267 return {};
268​
269 let page = record;
270 let output: unknown = result;
271 for (let depth = 0; depth < 3; depth += 1) {
272 if (page?.isError === true || page?.is_error === true) return {};
273 const structured = asRecord(page?.structuredContent);
274 if (structured) {
275 page = structured;
276 break;
277 }
278 const text = extractMcpResultText(output)?.slice(0, 2 * 1024 * 1024);
279 if (!text) break;
280 try {
281 page = asRecord(JSON.parse(extractJsonObject(text)));
282 } catch {
283 // A truncated MCP envelope can still contain a complete first text block.
284 const firstBlock = /^\s*\{\s*"content"\s*:\s*\[\s*/.exec(text);
285 if (!firstBlock) return {};
286 try {
287 const block = asRecord(JSON.parse(extractJsonObject(text.slice(firstBlock[0].length))));
288 page = block?.type === "text" ? { content: [block] } : null;
289 } catch {
290 return {};
291 }
292 }
293 output = page;
294 }
295 const rawUrl = asTrimmedString(
296 asRecord(page?.toolIcon)?.pageUrl ??
297 (/preview_(?:open|navigate|status|snapshot)$/.test(name) ? page?.url : undefined),
298 );
299 if (!rawUrl || rawUrl.length > 4096) return {};
300 try {
301 const url = new URL(rawUrl);
302 if (url.protocol !== "http:" && url.protocol !== "https:") return {};
303 return { toolIcon: { _tag: "website", pageUrl: url.href } };
304 } catch {
305 return {};
306 }
308​
309/**
310 * MCP tool calls carry full tool results (`data.item.result` on Codex,
311 * `data.result` on Claude/OpenCode) that used to bypass slimming entirely to
312 * keep the expanded-row UI working. Keep the fields the UI actually renders
313 * and summarize the result like regular tool output.
314 */
315function projectMcpToolCallData(data: Record<string, unknown>): Record<string, unknown> {
316 const projectedData: Record<string, unknown> = {};
317​
318 const item = asRecord(data.item);
319 if (item) {
320 const projectedItem: Record<string, unknown> = {};
321 for (const key of MCP_ITEM_KEPT_FIELDS) {
322 if (key in item) {
323 projectedItem[key] = item[key];
324 }
325 }
326 const result = summarizeMcpResult(item.result);
327 if (result) {
328 projectedItem.result = result;
329 }
330 projectedData.item = projectedItem;
331 }
332​
333 if ("toolName" in data) {
334 projectedData.toolName = data.toolName;
335 }
336 if ("input" in data) {
337 projectedData.input = data.input;
338 }
339 if (!item) {
340 const result = summarizeMcpResult(data.result);
341 if (result) {
342 projectedData.result = result;
343 }
344 }
345​
346 if ("toolCallId" in data) {
347 projectedData.toolCallId = data.toolCallId;
348 }
349 if ("kind" in data) {
350 projectedData.kind = data.kind;
351 }
352​
353 const changedFiles: string[] = [];
354 collectChangedFiles(data, changedFiles, new Set<string>(), 0);
355 if (changedFiles.length > 0) {
356 projectedData.files = changedFiles.map((path) => ({ path }));
357 }
358​
359 return projectedData;
361​
362function projectRawOutput(value: unknown): Record<string, unknown> | undefined {
363 const direct = asTrimmedString(value);
364 if (direct) {
365 const summary = summarizeToolTextOutput(direct);
366 return summary ? { content: summary } : undefined;
367 }
368​
369 const rawOutput = asRecord(value);
370 if (!rawOutput) {
371 return undefined;
372 }
373​
374 if (typeof rawOutput.totalFiles === "number" && Number.isFinite(rawOutput.totalFiles)) {
375 return {
376 totalFiles: rawOutput.totalFiles,
377 ...(rawOutput.truncated === true ? { truncated: true } : {}),
378 };
379 }
380​
381 const content = asTrimmedString(rawOutput.content);
382 if (content) {
383 const summary = summarizeToolTextOutput(content);
384 return summary ? { content: summary } : undefined;
385 }
386​
387 const stdout = asTrimmedString(rawOutput.stdout);
388 if (stdout) {
389 const summary = summarizeToolTextOutput(stdout);
390 return summary ? { content: summary } : undefined;
391 }
392​
393 const stderr = asTrimmedString(rawOutput.stderr);
394 if (stderr) {
395 const summary = summarizeToolTextOutput(stderr);
396 return summary ? { content: summary } : undefined;
397 }
398​
399 return undefined;
401​
402function projectAcpContent(value: unknown): Record<string, unknown> | undefined {
403 if (!Array.isArray(value)) {
404 return undefined;
405 }
406​
407 const text = value
408 .map((entryValue) => {
409 const entry = asRecord(entryValue);
410 const content = asRecord(entry?.content);
411 return entry?.type === "content" && content?.type === "text"
412 ? asTrimmedString(content.text)
413 : null;
414 })
415 .filter((entry): entry is string => entry !== null)
416 .join("\n");
417 const summary = summarizeToolTextOutput(text);
418 return summary ? { content: summary } : undefined;
420​
421/**
422 * Removes activity payload fields that no current client reads while retaining
423 * the full payload in persistence and the event store.
424 */
425export function projectActivityPayload(
426 activity: OrchestrationThreadActivity,
427): OrchestrationThreadActivity {
428 const payload = asRecord(activity.payload);
429 const data = asRecord(payload?.data);
430 if (!payload || !data) {
431 return activity;
432 }
433​
434 const itemStatus = asRecord(data.item)?.status;
435 const statusPayload =
436 payload.status === "completed" && (itemStatus === "failed" || itemStatus === "declined")
437 ? { ...payload, status: itemStatus }
438 : payload;
439 const projectedPayload = {
440 ...projectPreviewToolMetadata(data, statusPayload.status),
441 ...statusPayload,
442 };
443 const questionInput = projectQuestionToolInput(data, payload.title);
444​
445 if (payload.itemType === "mcp_tool_call") {
446 return {
447 ...activity,
448 payload: {
449 ...projectedPayload,
450 data: { ...projectMcpToolCallData(data), ...questionInput },
451 },
452 };
453 }
454​
455 const projectedData: Record<string, unknown> = { ...questionInput };
456 const item = projectCommandData(data);
457 if (item) {
458 projectedData.item = item;
459 }
460 const command = projectCommandValue(data);
461 if (command !== undefined) {
462 projectedData.command = command;
463 }
464 const imagePath = projectViewedImagePath(data);
465 if (imagePath) {
466 projectedData.imagePath = imagePath;
467 }
468​
469 const changedFiles: string[] = [];
470 collectChangedFiles(data, changedFiles, new Set<string>(), 0);
471 if (changedFiles.length > 0) {
472 // Both clients discover file names by walking objects with path-like keys.
473 projectedData.files = changedFiles.map((path) => ({ path }));
474 }
475​
476 if ("toolCallId" in data) {
477 projectedData.toolCallId = data.toolCallId;
478 }
479 if ("kind" in data) {
480 projectedData.kind = data.kind;
481 }
482 if ("toolName" in data) {
483 projectedData.toolName = data.toolName;
484 }
485​
486 const rawOutput =
487 projectRawOutput(data.rawOutput) ??
488 projectAcpContent(data.content) ??
489 (payload.itemType === "command_execution" ? summarizeMcpResult(data.result) : undefined);
490 if (rawOutput) {
491 projectedData.rawOutput = rawOutput;
492 }
493​
494 return {
495 ...activity,
496 payload: {
497 ...projectedPayload,
498 data: projectedData,
499 },
500 };
502​
503/**
504 * Matches the validity rule in the web client's
505 * `deriveLatestContextWindowSnapshot`: rows without a finite, non-negative
506 * `usedTokens` are skipped during its backward walk, so they must not shadow
507 * an earlier resolvable row here.
508 */
509function isResolvableContextWindowActivity(activity: OrchestrationThreadActivity): boolean {
510 if (activity.kind !== "context-window.updated") {
511 return false;
512 }
513 const payload = asRecord(activity.payload);
514 const usedTokens = payload?.usedTokens;
515 return typeof usedTokens === "number" && Number.isFinite(usedTokens) && usedTokens >= 0;
517​
518/**
519 * Drops all but the last resolvable context-window activity per turn from a
520 * snapshot. Clients only ever read the latest usage value (walking the array
521 * backwards), so shipping the full history — often thousands of rows on long
522 * threads — buys nothing. Retention is per turn rather than per thread because
523 * a live `thread.reverted` makes the client discard whole turns; keeping each
524 * turn's latest row means the meter can still resolve a value from the turns
525 * that survive. Malformed rows pass through untouched rather than shadowing a
526 * valid earlier row. Live `thread.activity-appended` events are untouched:
527 * newer updates still stream through and supersede the retained rows on the
528 * client.
529 */
530function dropStaleContextWindowActivities(
531 activities: ReadonlyArray<OrchestrationThreadActivity>,
532): ReadonlyArray<OrchestrationThreadActivity> {
533 const latestIndexByTurn = new Map<string | null, number>();
534 for (let index = 0; index < activities.length; index += 1) {
535 if (isResolvableContextWindowActivity(activities[index]!)) {
536 latestIndexByTurn.set(activities[index]!.turnId, index);
537 }
538 }
539 if (latestIndexByTurn.size === 0) {
540 return activities;
541 }
542 return activities.filter(
543 (activity, index) =>
544 !isResolvableContextWindowActivity(activity) ||
545 latestIndexByTurn.get(activity.turnId) === index,
546 );
548​
549/**
550 * Identity used to retain only the newest lifecycle row for each call in a
551 * thread snapshot. Prefer the runtime item id, then the legacy nested id, and
552 * finally the itemType/title/detail triple. Rows without any identity remain
553 * untouched.
554 */
555function toolLifecycleIdentity(activity: OrchestrationThreadActivity): string | null {
556 const payload = asRecord(activity.payload);
557 if (!payload) {
558 return null;
559 }
560​
561 const toolCallId =
562 asTrimmedString(payload.toolCallId) ?? asTrimmedString(asRecord(payload.data)?.toolCallId);
563 if (toolCallId) {
564 return `id:${toolCallId}`;
565 }
566​
567 const itemType = asTrimmedString(payload.itemType) ?? "";
568 // Mirrors the clients' `normalizeCompactToolLabel`: a completion's title may
569 // gain a trailing "complete"/"completed" the in-flight updates lack.
570 const label = (asTrimmedString(payload.title) ?? activity.summary)
571 .replace(/\s+(?:complete|completed)\s*$/iu, "")
572 .trim();
573 const detail = asTrimmedString(payload.detail) ?? "";
574 if (itemType.length === 0 && label.length === 0 && detail.length === 0) {
575 return null;
576 }
577 return [itemType, label, detail].join("");
579​
580/**
581 * Drops `tool.updated` rows a `tool.completed` row already supersedes. An
582 * update is the in-flight snapshot of a call; once the call completes, the
583 * completion carries the final state and the clients fold every matching
584 * update into it, so shipping the updates buys nothing — 47k such rows exist
585 * in one real database, and a single thread carries 2,291 of them totalling
586 * ~1MB post-slimming.
587 *
588 * Matching is per turn for the same reason `dropStaleContextWindowActivities`
589 * retains per turn: a live `thread.reverted` makes the client discard whole
590 * turns, so a completion in a different turn could vanish and leave the
591 * dropped update unrepresented. The completion must also come *after* the
592 * update within the turn — a later update belongs to a subsequent call that
593 * reuses the same identity and is still in flight. Rows without a lifecycle
594 * identity pass through, matching the clients, which never collapse them.
595 * Deliberate divergence from client collapse: clients fold only *adjacent*
596 * lifecycle rows, so a superseded update separated from its completion by an
597 * interleaved parallel call renders as its own row today, and this drop
598 * removes it. Measured against a real database, that affects 1.5% of dropped
599 * rows (553 of 36,581), all pure in-flight state whose final result the
600 * retained completion still shows. Dropping them is intentional; matching
601 * adjacency server-side would forfeit most of the win for parallel-heavy
602 * threads, which are exactly the heavy ones. Superseding completions always
603 * carry a payload superset of their updates (verified across all 49,515
604 * update rows: zero dropped rows held a client-merged field — detail, title,
605 * command, item, kind, files — their completion lacked), so no expanded-row
606 * content is lost.
607 */
608function dropSupersededToolUpdatedActivities(
609 activities: ReadonlyArray<OrchestrationThreadActivity>,
610): ReadonlyArray<OrchestrationThreadActivity> {
611 const completionIndicesByKey = new Map<string, number[]>();
612 for (let index = 0; index < activities.length; index += 1) {
613 const activity = activities[index]!;
614 if (activity.kind !== "tool.completed") {
615 continue;
616 }
617 const identity = toolLifecycleIdentity(activity);
618 if (!identity) {
619 continue;
620 }
621 const key = `${activity.turnId ?? ""}\u0000${identity}`;
622 const indices = completionIndicesByKey.get(key);
623 if (indices) {
624 indices.push(index);
625 } else {
626 completionIndicesByKey.set(key, [index]);
627 }
628 }
629 if (completionIndicesByKey.size === 0) {
630 return activities;
631 }
632​
633 return activities.filter((activity, index) => {
634 if (activity.kind !== "tool.updated") {
635 return true;
636 }
637 const identity = toolLifecycleIdentity(activity);
638 if (!identity) {
639 return true;
640 }
641 const indices = completionIndicesByKey.get(`${activity.turnId ?? ""}\u0000${identity}`);
642 return !indices?.some((completionIndex) => completionIndex > index);
643 });
645​
646export function projectThreadDetailSnapshot(
647 snapshot: OrchestrationThreadDetailSnapshot,
648 reasoningMessages = true,
649): OrchestrationThreadDetailSnapshot {
650 return {
651 ...snapshot,
652 thread: {
653 ...snapshot.thread,
654 messages: reasoningMessages
655 ? snapshot.thread.messages
656 : snapshot.thread.messages.map((message) =>
657 message.role === "reasoning" ? { ...message, role: "system" as const } : message,
658 ),
659 activities: dropSupersededToolUpdatedActivities(
660 dropStaleContextWindowActivities(snapshot.thread.activities),
661 ).map(projectActivityPayload),
662 },
663 };
665​
666export function projectActivityEvent(
667 event: OrchestrationEvent,
668 reasoningMessages = true,
669): OrchestrationEvent {
670 // Preserve sequence watermarks and message identities for clients whose role
671 // decoder predates reasoning. Filtering would strand their history pages.
672 if (
673 !reasoningMessages &&
674 event.type === "thread.message-sent" &&
675 event.payload.role === "reasoning"
676 ) {
677 return { ...event, payload: { ...event.payload, role: "system" } };
678 }
679 if (event.type !== "thread.activity-appended") {
680 return event;
681 }
682 return {
683 ...event,
684 payload: {
685 ...event.payload,
686 activity: projectActivityPayload(event.payload.activity),
687 },
688 };