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

presentation.ts

776 lines26.4 KB

1import {
2 isOrchestrationV2WorkActive,
3 isToolLifecycleItemType,
4 type AssetResource,
5 type RuntimeItemStatus,
6 type ToolActivitySource,
7 type ToolActivitySurface,
8 type ToolActivityIcon,
9 type OrchestrationV2TurnItem,
10 type ThreadId,
11} from "@t3tools/contracts";
12import {
13 resolveT3McpToolDefinition,
14 type T3McpToolDefinition,
15 type T3McpToolSummaryAction,
16} from "@t3tools/shared/t3McpToolPresentation";
17import { classifyMarkdownImageSource } from "@t3tools/client-runtime/markdown-images";
18import { resolveMediaSource } from "@t3tools/client-runtime/media-source";
19import { parseChangeRequestUrl } from "@t3tools/shared/changeRequestUrl";
20import { isWorkspaceImagePreviewPath } from "@t3tools/shared/filePreview";
21import { formatTokens } from "@t3tools/shared/usageFormat";
22import { classifyToolActivity } from "@t3tools/shared/toolActivity";
23import { toolOutputIndicatesFailure } from "@t3tools/shared/toolOutput";
24​
25import {
26 summarizeT3ToolCalls,
27 t3ToolResultIndicatesFailure,
28 type T3ToolSummaryCall,
29} from "@t3tools/client-runtime/t3ToolSummary";
30​
31export type WorkLogToolLifecycleStatus = RuntimeItemStatus | "stopped" | "idle";
32​
33export function toolItemForDisplay(item: OrchestrationV2TurnItem): OrchestrationV2TurnItem {
34 switch (item.type) {
35 case "command_execution":
36 case "dynamic_tool": {
37 const { output: _output, ...displayItem } = item;
38 return displayItem;
39 }
40 case "file_change": {
41 const { diffStr, oldStr: _oldStr, newStr: _newStr, ...displayItem } = item;
42 // A failed edit's diffStr holds the provider's error, not a diff.
43 return item.status === "failed" && diffStr?.trim()
44 ? { ...displayItem, diffStr }
45 : displayItem;
46 }
47 default:
48 return item;
49 }
51​
52type CompactionLabelItem = Pick<
53 Extract<OrchestrationV2TurnItem, { type: "compaction" }>,
54 "status" | "beforeTokenCount" | "afterTokenCount"
55>;
56​
57export function contextCompactionTokenCounts(
58 item: CompactionLabelItem,
59): { readonly before: string; readonly after: string } | null {
60 if (
61 item.status === "running" ||
62 item.beforeTokenCount === undefined ||
63 item.afterTokenCount === undefined
64 ) {
65 return null;
66 }
67 return { before: formatTokens(item.beforeTokenCount), after: formatTokens(item.afterTokenCount) };
69​
70export function contextCompactionLabel(item: CompactionLabelItem): string {
71 if (item.status === "failed") return "Context compaction failed";
72 if (item.status === "cancelled" || item.status === "interrupted")
73 return "Context compaction stopped";
74 if (isOrchestrationV2WorkActive(item.status)) return "Compacting context";
75 const tokens = contextCompactionTokenCounts(item);
76 return tokens
77 ? `Context compacted ${tokens.before} → ${tokens.after} tokens`
78 : "Context compacted";
80​
81export interface WorkLogPresentationEntry {
82 readonly questionAnswer?: import("@t3tools/contracts").UserInputAttachmentAnswerPayload;
83 readonly id: string;
84 readonly createdAt: string;
85 readonly label: string;
86 readonly tone: "thinking" | "tool" | "info" | "error";
87 readonly command?: string;
88 readonly rawCommand?: string;
89 readonly detail?: string;
90 readonly viewedImagePath?: string;
91 readonly changedFiles?: ReadonlyArray<string>;
92 readonly toolTitle?: string;
93 readonly toolData?: unknown;
94 readonly requestKind?: string;
95 readonly itemType?: OrchestrationV2TurnItem["type"];
96 readonly toolLifecycleStatus?: WorkLogToolLifecycleStatus;
97 readonly structuredPayload?: OrchestrationV2TurnItem;
98 readonly toolSource?: ToolActivitySource;
99 readonly toolSurface?: ToolActivitySurface;
100 readonly toolIcon?: ToolActivityIcon;
102​
103export type ToolGroupAction =
104 | "link-pr"
105 | "unlink-pr"
106 | "list-prs"
107 | "watch-pr"
108 | "unwatch-pr"
109 | "read"
110 | "edit"
111 | "command"
112 | "thread-create"
113 | "browser"
114 | "device"
115 | "code-search"
116 | "search"
117 | "other"
118 | "update";
119​
120export type ToolGroupSummaryKind =
121 | "pull-request"
122 | ToolGroupAction
123 | "dynamic-tool"
124 | "reasoning"
125 | "agent-tool"
126 | "tone-tool"
127 | "mixed";
128​
129export function normalizeCompactToolLabel(value: string): string {
130 return value.replace(/\s+(?:complete|completed)\s*$/i, "").trim();
132​
133function workEntryToolName(
134 entry: Pick<WorkLogPresentationEntry, "label" | "toolTitle" | "toolData" | "structuredPayload">,
135): string | undefined {
136 const item = entry.structuredPayload;
137 if (item?.type === "dynamic_tool" && item.toolName) return item.toolName;
138 const data = asRecord(entry.toolData);
139 if (typeof data?.server === "string" && typeof data.tool === "string") {
140 return `${data.server}.${data.tool}`;
141 }
142 if (typeof data?.toolName === "string") return data.toolName;
143 return resolveT3McpToolDefinition(entry.toolTitle) ? entry.toolTitle : entry.label;
145​
146function workEntryToolOutput(
147 entry: Pick<WorkLogPresentationEntry, "toolData" | "structuredPayload">,
148): unknown {
149 const item = entry.structuredPayload;
150 const data = asRecord(entry.toolData);
151 return item?.type === "dynamic_tool"
152 ? item.output
153 : (data?.output ?? data?.result ?? data?.rawOutput ?? data?.content);
155​
156function resolveT3McpToolPresentation(
157 definition: T3McpToolDefinition | null,
158 status: string | undefined,
159 data?: unknown,
160) {
161 if (!definition) return null;
162 const [action, running, completed, detail] = definition.labels;
163 const verb =
164 status === "inProgress"
165 ? running
166 : status === "completed"
167 ? completed
168 : status === "failed"
169 ? `Failed to ${action.toLowerCase()}`
170 : status === "declined"
171 ? `Declined to ${action.toLowerCase()}`
172 : status === "stopped"
173 ? `Stopped ${running.toLowerCase()}`
174 : running;
175​
176 const actionKind =
177 definition.summaryAction === "link-pr" ||
178 definition.summaryAction === "unlink-pr" ||
179 definition.summaryAction === "list-prs" ||
180 definition.summaryAction === "watch-pr" ||
181 definition.summaryAction === "unwatch-pr"
182 ? definition.summaryAction
183 : undefined;
184 const payload = asRecord(data);
185 const input =
186 asRecord(payload?.arguments) ?? asRecord(payload?.input) ?? asRecord(payload?.rawInput);
187 const urlTarget = typeof input?.url === "string" ? parseChangeRequestUrl(input.url) : null;
188 const number = urlTarget?.number ?? input?.number;
189 const target =
190 actionKind !== undefined &&
191 actionKind !== "list-prs" &&
192 typeof number === "number" &&
193 Number.isSafeInteger(number) &&
194 number > 0
195 ? `PR #${number}`
196 : detail;
197 return {
198 displayName: `${verb} ${target}`,
199 icon: definition.icon,
200 ...(actionKind === undefined ? {} : { action: actionKind }),
201 };
203​
204export function liveActivityToolStatus(status: string | undefined, presentTense: boolean) {
205 if (status === "failed" || status === "declined" || status === "stopped" || status === "idle") {
206 return status;
207 }
208 if (presentTense || status === "inProgress") return "inProgress";
209 return "completed";
211​
212export function resolveWorkEntryToolPresentation(
213 entry: Pick<
214 WorkLogPresentationEntry,
215 "label" | "toolTitle" | "toolData" | "toolLifecycleStatus" | "structuredPayload"
216 >,
217 fallbackStatus?: "inProgress" | "completed",
218) {
219 const definition = resolveT3McpToolDefinition(workEntryToolName(entry));
220 const status = entry.toolLifecycleStatus ?? fallbackStatus;
221 return resolveT3McpToolPresentation(
222 definition,
223 definition && t3ToolResultIndicatesFailure(workEntryToolOutput(entry)) ? "failed" : status,
224 entry.toolData,
225 );
227​
228function asRecord(value: unknown): Record<string, unknown> | null {
229 return value !== null && typeof value === "object" && !Array.isArray(value)
230 ? (value as Record<string, unknown>)
231 : null;
233​
234function nonEmptyString(value: unknown): string | null {
235 return typeof value === "string" && value.trim().length > 0 ? value : null;
237​
238function commandResultContent(value: unknown): string | null {
239 const direct = nonEmptyString(value);
240 if (direct) return direct;
241​
242 const directContent = Array.isArray(value) ? value : null;
243 const record = asRecord(value);
244 const content = record?.content;
245 const contentText = nonEmptyString(content);
246 if (contentText) return contentText;
247 const blocks = directContent ?? (Array.isArray(content) ? content : null);
248 if (!blocks) return null;
249​
250 const chunks = blocks.flatMap((entry) => {
251 const text = nonEmptyString(entry) ?? nonEmptyString(asRecord(entry)?.text);
252 return text ? [text] : [];
253 });
254 return chunks.length > 0 ? chunks.join("\n") : null;
256​
257export function extractCommandOutputText(dataValue: unknown): string | null {
258 const data = asRecord(dataValue);
259 const item = asRecord(data?.item);
260 const itemResult = asRecord(item?.result);
261 const rawOutput = asRecord(data?.rawOutput);
262 const outputStreams = [
263 nonEmptyString(rawOutput?.stdout),
264 nonEmptyString(rawOutput?.stderr),
265 ].filter((value): value is string => value !== null);
266 const acpContent = Array.isArray(data?.content)
267 ? data.content
268 .flatMap((entryValue) => {
269 const entry = asRecord(entryValue);
270 const content = asRecord(entry?.content);
271 const text = entry?.type === "content" ? nonEmptyString(content?.text) : null;
272 return text ? [text] : [];
273 })
274 .join("\n")
275 : null;
276​
277 const candidates = [
278 item?.aggregatedOutput,
279 itemResult?.content,
280 data?.rawOutput,
281 rawOutput?.content,
282 outputStreams.length > 0 ? outputStreams.join("\n") : null,
283 rawOutput?.output,
284 acpContent,
285 data?.result,
286 ];
287 for (const candidate of candidates) {
288 const text = commandResultContent(candidate);
289 if (text) return text;
290 }
291 return null;
293​
294/**
295 * Ingestion caps tool details at 180 chars and appends "...", so a long command
296 * echo no longer equals the command it repeats. Treat a truncated prefix of the
297 * command as the same echo.
298 */
299function textRepeatsCommand(text: string, commands: ReadonlyArray<string | null>): boolean {
300 const truncated = text.endsWith("...")
301 ? text.slice(0, -3)
302 : text.endsWith("\u2026")
303 ? text.slice(0, -1)
304 : null;
305 return commands.some((candidate) => {
306 const command = candidate?.trim();
307 if (!command) return false;
308 if (command === text) return true;
309 return (
310 truncated !== null &&
311 truncated.length > 0 &&
312 command.length > truncated.length &&
313 command.startsWith(truncated)
314 );
315 });
317​
318/**
319 * OpenCode stores completed output in `detail` with no other output channel, so
320 * plain equality is only treated as synthetic when the payload shape shows the
321 * detail came from the command: Codex item metadata, an ACP tool call
322 * (`data.toolCallId`, `kind: "execute"`), a Claude tool-name prefix, or no
323 * structured command at all.
324 */
325export function commandDetailRepeatsCommand(input: {
326 readonly detail: string;
327 readonly command: string | null;
328 readonly rawCommand: string | null;
329 readonly toolName: unknown;
330 readonly data: unknown;
331}): boolean {
332 const toolName = nonEmptyString(input.toolName)?.trim();
333 const detail = input.detail.trim();
334 const commands = [input.command, input.rawCommand];
335 if (toolName) {
336 const prefix = `${toolName}:`;
337 if (detail.toLowerCase().startsWith(prefix.toLowerCase())) {
338 const unprefixed = detail.slice(prefix.length).trim();
339 if (textRepeatsCommand(unprefixed, commands)) return true;
340 }
341 }
342​
343 if (!textRepeatsCommand(detail, commands)) return false;
344​
345 const data = asRecord(input.data);
346 const item = asRecord(data?.item);
347 const itemInput = asRecord(item?.input);
348 const itemResult = asRecord(item?.result);
349 const hasStructuredCommand = [
350 item?.command,
351 itemInput?.command,
352 itemResult?.command,
353 data?.command,
354 ].some((value) =>
355 Array.isArray(value)
356 ? value.some((part) => nonEmptyString(part) !== null)
357 : nonEmptyString(value) !== null,
358 );
359 return (
360 !hasStructuredCommand ||
361 item !== null ||
362 data?.toolCallId !== undefined ||
363 nonEmptyString(data?.kind)?.toLowerCase() === "execute"
364 );
366​
367function workLogEntryIsToolLike(entry: WorkLogPresentationEntry): boolean {
368 if (entry.tone === "tool" || entry.tone === "thinking" || entry.tone === "error") return true;
369 if (entry.command !== undefined && entry.command.trim().length > 0) return true;
370 if (entry.requestKind !== undefined) return true;
371 return entry.itemType !== undefined && isToolLifecycleItemType(entry.itemType);
373​
374function workEntryIndicatesToolFailureFromOutput(
375 entry: WorkLogPresentationEntry,
376 includeCommand: boolean,
377): boolean {
378 if (
379 entry.tone === "error" ||
380 entry.toolLifecycleStatus === "failed" ||
381 entry.toolLifecycleStatus === "declined"
382 ) {
383 return true;
384 }
385 // Reasoning detail is the model's own prose (often tens of KB), not tool
386 // output: scanning it is slow on long threads and misreads phrases like
387 // "that exit code 2 is expected" as a failed tool.
388 if (!workLogEntryIsToolLike(entry) || entry.itemType === "reasoning") return false;
389 if (
390 resolveT3McpToolDefinition(workEntryToolName(entry)) &&
391 t3ToolResultIndicatesFailure(workEntryToolOutput(entry))
392 ) {
393 return true;
394 }
395 const item = entry.structuredPayload;
396 if (item?.type === "command_execution") {
397 if (item.outputIndicatesFailure || (item.exitCode !== undefined && item.exitCode !== 0)) {
398 return true;
399 }
400 if (item.output && toolOutputIndicatesFailure(item.output.slice(0, 32_768))) {
401 return true;
402 }
403 }
404 const output = includeCommand
405 ? [entry.detail, entry.command].filter(Boolean).join("\n")
406 : (entry.detail ?? "");
407 return output.length > 0 && toolOutputIndicatesFailure(output);
409​
410export function workEntryIndicatesToolFailure(entry: WorkLogPresentationEntry): boolean {
411 return workEntryIndicatesToolFailureFromOutput(entry, true);
413​
414export function workEntryDisplayIndicatesToolFailure(entry: WorkLogPresentationEntry): boolean {
415 return workEntryIndicatesToolFailureFromOutput(entry, false);
417​
418export function workEntryIndicatesToolSuccess(entry: WorkLogPresentationEntry): boolean {
419 return (
420 workLogEntryIsToolLike(entry) &&
421 !workEntryIndicatesToolFailure(entry) &&
422 entry.tone !== "thinking" &&
423 entry.toolLifecycleStatus !== "idle" &&
424 entry.toolLifecycleStatus !== "inProgress" &&
425 entry.toolLifecycleStatus !== "stopped"
426 );
428​
429function workLogEntryIsLocalCodeSearch(entry: WorkLogPresentationEntry): boolean {
430 return (
431 entry.itemType === "file_search" ||
432 (entry.itemType === "web_search" &&
433 /\bgrep\b/i.test(normalizeCompactToolLabel(entry.toolTitle ?? entry.label)))
434 );
436​
437export function toolGroupAction(entry: WorkLogPresentationEntry): ToolGroupAction {
438 if (entry.itemType === "thread_created") return "thread-create";
439 const presentation = resolveWorkEntryToolPresentation(entry);
440 if (presentation?.action !== undefined) return presentation.action;
441 if (presentation?.icon === "browser") return "browser";
442 if (presentation?.icon === "device") return "device";
443 if (entry.requestKind === "file-read" || entry.viewedImagePath !== undefined) return "read";
444 if (entry.itemType === "approval_request" || entry.itemType === "user_input_request") {
445 return workLogEntryIsToolLike(entry) ? "other" : "update";
446 }
447 const data = asRecord(entry.toolData) ?? {};
448 const toolName =
449 entry.structuredPayload?.type === "dynamic_tool"
450 ? entry.structuredPayload.toolName
451 : typeof data.toolName === "string"
452 ? data.toolName
453 : entry.toolTitle;
454 const classified = classifyToolActivity({
455 itemType:
456 entry.itemType === "command_execution" ||
457 entry.itemType === "file_change" ||
458 entry.itemType === "web_search"
459 ? entry.itemType
460 : entry.itemType === "dynamic_tool"
461 ? "dynamic_tool_call"
462 : undefined,
463 title: entry.toolTitle ?? entry.label,
464 data: {
465 ...data,
466 ...(toolName ? { toolName } : {}),
467 },
468 });
469 if (classified === "read") return "read";
470 if (classified === "file_change" || entry.itemType === "file_change") return "edit";
471 if (classified === "command" || entry.itemType === "command_execution" || entry.command) {
472 return "command";
473 }
474 if (classified === "search") {
475 return entry.itemType === "web_search" && !workLogEntryIsLocalCodeSearch(entry)
476 ? "search"
477 : "code-search";
478 }
479 if (workLogEntryIsLocalCodeSearch(entry)) return "code-search";
480 if (entry.itemType === "web_search") return "search";
481 if ((entry.changedFiles?.length ?? 0) > 0) return "edit";
482 return workLogEntryIsToolLike(entry) ? "other" : "update";
484​
485export function workEntryViewedImagePath(entry: WorkLogPresentationEntry): string | null {
486 const viewedImagePath = entry.viewedImagePath?.trim();
487 if (
488 viewedImagePath !== undefined &&
489 !/[\r\n]/.test(viewedImagePath) &&
490 isWorkspaceImagePreviewPath(viewedImagePath)
491 ) {
492 return viewedImagePath;
493 }
494 const detail = entry.detail?.trim();
495 return toolGroupAction(entry) === "read" &&
496 detail !== undefined &&
497 !/[\r\n]/.test(detail) &&
498 isWorkspaceImagePreviewPath(detail)
499 ? detail
500 : null;
502​
503export interface ViewedImageAsset {
504 readonly resource: Extract<AssetResource, { readonly _tag: "media-file" }>;
505 readonly alt: string;
506 readonly srcFragment: string;
508​
509export function resolveViewedImageAsset(
510 source: string,
511 input: {
512 readonly threadId: ThreadId;
513 readonly workspaceRoot?: string | null | undefined;
514 },
515): ViewedImageAsset | null {
516 const imageSource = classifyMarkdownImageSource(source, input.workspaceRoot ?? ".");
517 if (imageSource._tag !== "WorkspaceFile") return null;
518 const resolvedFilePath =
519 input.workspaceRoot == null && imageSource.path.startsWith("./")
520 ? imageSource.path.slice(2)
521 : imageSource.path;
522​
523 const media = resolveMediaSource(source, {
524 threadId: input.threadId,
525 workspaceRoot: input.workspaceRoot,
526 resolvedFilePath,
527 });
528 if (media === null || media.access !== "environment") return null;
529 return { resource: media.resource, alt: media.name, srcFragment: media.srcFragment };
531​
532function toolGroupActionCount(
533 action: ToolGroupAction,
534 entries: ReadonlyArray<WorkLogPresentationEntry>,
535): number {
536 if (action !== "edit") return entries.length;
537 const changedFiles = new Set<string>();
538 let editsWithoutFileDetails = 0;
539 for (const entry of entries) {
540 if (!entry.changedFiles || entry.changedFiles.length === 0) {
541 editsWithoutFileDetails += 1;
542 } else {
543 for (const file of entry.changedFiles) changedFiles.add(file);
544 }
545 }
546 return changedFiles.size + editsWithoutFileDetails;
548​
549function toolGroupActionLabel(action: ToolGroupAction, count: number): string {
550 switch (action) {
551 case "link-pr":
552 return `Linked ${count} ${count === 1 ? "pull request" : "pull requests"}`;
553 case "unlink-pr":
554 return `Unlinked ${count} ${count === 1 ? "pull request" : "pull requests"}`;
555 case "watch-pr":
556 return `Watching ${count} ${count === 1 ? "pull request" : "pull requests"}`;
557 case "unwatch-pr":
558 return `Stopped watching ${count} ${count === 1 ? "pull request" : "pull requests"}`;
559 case "list-prs":
560 return count === 1
561 ? "Checked linked pull requests"
562 : `Checked linked pull requests ${count} times`;
563 case "read":
564 return `Read ${count} ${count === 1 ? "file" : "files"}`;
565 case "edit":
566 return `Changed ${count} ${count === 1 ? "file" : "files"}`;
567 case "command":
568 return `Ran ${count} ${count === 1 ? "command" : "commands"}`;
569 case "thread-create":
570 return `Created ${count} ${count === 1 ? "thread" : "threads"}`;
571 case "device":
572 return `Used device controls ${count} ${count === 1 ? "time" : "times"}`;
573 case "browser":
574 return `Used browser ${count} ${count === 1 ? "time" : "times"}`;
575 case "search":
576 return `Searched the web ${count} ${count === 1 ? "time" : "times"}`;
577 case "code-search":
578 return `Searched code ${count} ${count === 1 ? "time" : "times"}`;
579 case "other":
580 return `Used ${count} ${count === 1 ? "tool" : "tools"}`;
581 case "update":
582 return `Received ${count} ${count === 1 ? "update" : "updates"}`;
583 }
585​
586function t3ToolSummaryCall(entry: WorkLogPresentationEntry): T3ToolSummaryCall {
587 const item = entry.structuredPayload;
588 const data =
589 entry.toolData !== null && typeof entry.toolData === "object"
590 ? (entry.toolData as Record<string, unknown>)
591 : undefined;
592 return {
593 input:
594 item?.type === "dynamic_tool"
595 ? item.input
596 : (data?.arguments ?? data?.input ?? data?.rawInput),
597 output: workEntryToolOutput(entry),
598 outcome:
599 entry.toolLifecycleStatus === "failed" ||
600 entry.toolLifecycleStatus === "declined" ||
601 entry.tone === "error"
602 ? "failed"
603 : entry.toolLifecycleStatus === "completed"
604 ? "completed"
605 : "unfinished",
606 };
608​
609function summaryActionPriority(action: ToolGroupAction | T3McpToolSummaryAction): number {
610 switch (action) {
611 case "command":
612 case "edit":
613 case "delegate":
614 case "task-cancel":
615 case "thread-create":
616 case "thread-send":
617 case "thread-interrupt":
618 case "workflow-stop":
619 case "schedule-create":
620 case "schedule-update":
621 case "schedule-delete":
622 case "schedule-run":
623 case "thread-configure":
624 case "thread-fork":
625 case "thread-merge":
626 case "thread-organize":
627 case "thread-update":
628 case "queue-edit":
629 case "queue-cancel":
630 case "queue-reorder":
631 case "queue-steer":
632 case "question-respond":
633 case "worktree-handoff":
634 case "project-create":
635 case "project-update":
636 case "project-delete":
637 case "project-clone":
638 case "environment-update":
639 case "attachment-prepare":
640 case "attachment-discard":
641 case "attachment-send":
642 return 0;
643 case "other":
644 case "update":
645 return 2;
646 default:
647 return 1;
648 }
650​
651export function summarizeToolGroup(entries: ReadonlyArray<WorkLogPresentationEntry>): {
652 summary: string;
653 hasFailure: boolean;
654} {
655 const toolEntries = entries.filter((entry) => entry.itemType !== "reasoning");
656 if (entries.length > 0 && toolEntries.length === 0) {
657 return {
658 summary: entries.length === 1 ? "Thought" : `Thought (×${entries.length})`,
659 hasFailure: false,
660 };
661 }
662 entries = toolEntries;
663 const groups = new Map<
664 ToolGroupAction | T3McpToolSummaryAction,
665 {
666 action: ToolGroupAction;
667 t3Action: T3McpToolSummaryAction | null;
668 entries: WorkLogPresentationEntry[];
669 }
670 >();
671 const sources = new Map<string, ToolActivitySource>();
672 for (const entry of entries) {
673 const t3Action = resolveT3McpToolDefinition(workEntryToolName(entry))?.summaryAction ?? null;
674 if (entry.toolSource && t3Action === null) {
675 sources.set(entry.toolSource.key, entry.toolSource);
676 continue;
677 }
678 const action = toolGroupAction(entry);
679 const key = t3Action ?? action;
680 const group = groups.get(key);
681 if (group) group.entries.push(entry);
682 else groups.set(key, { action, t3Action, entries: [entry] });
683 }
684 const summaries = [...groups].map(([action, group], index) => ({
685 index,
686 count: group.entries.length,
687 priority: summaryActionPriority(action),
688 ...(group.t3Action
689 ? summarizeT3ToolCalls(group.t3Action, group.entries.map(t3ToolSummaryCall))
690 : {
691 label: toolGroupActionLabel(
692 group.action,
693 toolGroupActionCount(group.action, group.entries),
694 ),
695 failedCount: group.entries.filter(workEntryDisplayIndicatesToolFailure).length,
696 }),
697 }));
698 const selected = [...summaries]
699 .sort((a, b) => a.priority - b.priority || a.index - b.index)
700 .slice(0, 2)
701 .sort((a, b) => a.index - b.index);
702 const labels = selected.map(({ label }) => label);
703 if (sources.size > 0) {
704 const sourceValues = [...sources.values()];
705 const sourceNames = [...new Set(sourceValues.map((source) => source.name))];
706 const formattedNames =
707 sourceNames.length < 2
708 ? sourceNames[0]!
709 : sourceNames.length === 2
710 ? sourceNames.join(" and ")
711 : `${sourceNames.slice(0, -1).join(", ")}, and ${sourceNames.at(-1)}`;
712 const allIntegrations = sourceValues.every((source) => source.kind === "integration");
713 labels.unshift(
714 `Used ${formattedNames}${allIntegrations ? ` ${sourceNames.length === 1 ? "integration" : "integrations"}` : ""}`,
715 );
716 }
717 const sourcedCount = entries.filter(
718 (entry) =>
719 entry.toolSource !== undefined &&
720 resolveT3McpToolDefinition(workEntryToolName(entry)) === null,
721 ).length;
722 const remainingCount =
723 entries.length - sourcedCount - selected.reduce((count, group) => count + group.count, 0);
724 if (remainingCount > 0) {
725 labels.push(`Performed ${remainingCount} other ${remainingCount === 1 ? "action" : "actions"}`);
726 }
727 const sentenceLabels = labels.map((label, index) =>
728 index === 0 ? label : label.charAt(0).toLowerCase() + label.slice(1),
729 );
730 const summary =
731 sentenceLabels.length < 3
732 ? sentenceLabels.join(" and ")
733 : `${sentenceLabels.slice(0, -1).join(", ")}, and ${sentenceLabels.at(-1)}`;
734 return { summary, hasFailure: summaries.some((group) => group.failedCount > 0) };
736​
737export function toolGroupSummaryKind(
738 entries: ReadonlyArray<WorkLogPresentationEntry>,
739): ToolGroupSummaryKind {
740 const toolEntries = entries.filter((entry) => entry.itemType !== "reasoning");
741 if (entries.length > 0 && toolEntries.length === 0) return "reasoning";
742 entries = toolEntries;
743 if (
744 entries.length > 0 &&
745 entries.every((entry) => resolveWorkEntryToolPresentation(entry)?.icon === "pull-request")
746 )
747 return "pull-request";
748 const actions = new Set(entries.map(toolGroupAction));
749 if (actions.size !== 1) return "mixed";
750 const action = actions.values().next().value!;
751 if (action !== "other") return action;
752 const fallbackKinds = new Set(
753 entries.map((entry): ToolGroupSummaryKind => {
754 if (entry.itemType === "dynamic_tool") return "dynamic-tool";
755 if (entry.itemType === "subagent") return "agent-tool";
756 if (entry.tone === "thinking") return "agent-tool";
757 if (entry.tone === "tool") return "tone-tool";
758 return "other";
759 }),
760 );
761 return fallbackKinds.size === 1 ? fallbackKinds.values().next().value! : "mixed";
763​
764export function liveThoughtLine(markdown: string): string {
765 const heading = /^\s*\*\*([^*\r\n]+)\*\*[ \t]*\r?(?:\n|$)/.exec(markdown)?.[1];
766 const text = (heading ?? markdown)
767 .replace(/!?\[([^\]]*)\]\([^)]*\)/g, "$1")
768 .replace(/^[ \t]*(?:#{1,6}|[-*+]|\d+\.)[ \t]+/gm, "")
769 .replace(/`+|\*\*|~~/g, "")
770 .replace(/(^|[^\w*])[*_]([^*_\n]+)[*_](?![\w*])/g, "$1$2")
771 .replace(/\s+/g, " ")
772 .trim();
773 if (heading !== undefined) return text;
774 const end = /[.?!]["'”’)]?(?=\s)/.exec(text);
775 return end ? text.slice(0, end.index + end[0].length) : text;