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

presentation.ts

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