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

presentation.ts

775 lines26.4 KB

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