@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 852 lines 28.2 KB
Raw
1 import {
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";
12 import type { ToolCallVisibility } from "@t3tools/contracts/settings";
13 import {
14 resolveT3McpSummaryAction,
15 resolveT3McpToolDefinition,
16 type T3McpToolDefinition,
17 type T3McpToolSummaryAction,
18 } from "@t3tools/shared/t3McpToolPresentation";
19 import { classifyMarkdownImageSource } from "@t3tools/client-runtime/markdown-images";
20 import { resolveMediaSource } from "@t3tools/client-runtime/media-source";
21 import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
22 import { isWorkspaceImagePreviewPath } from "@t3tools/shared/mediaPreview";
23 import { formatTokens } from "@t3tools/shared/usageFormat";
24 import { classifyToolActivity } from "@t3tools/shared/toolActivity";
25 import { toolOutputIndicatesFailure } from "@t3tools/shared/toolOutput";
26
27 import {
28 summarizeT3ToolCalls,
29 t3ToolResultIndicatesFailure,
30 type T3ToolSummaryCall,
31 } from "@t3tools/client-runtime/t3ToolSummary";
32 import { mFallback, msg } from "gt-i18n";
33 import { t3ToolSentence } from "./t3ToolSentences.ts";
34 import type { MFunctionType } from "gt-i18n/types";
35
36 export type WorkLogToolLifecycleStatus = RuntimeItemStatus | "stopped" | "idle";
37
38 export function toolItemForDisplay(item: OrchestrationV2TurnItem): OrchestrationV2TurnItem {
39 switch (item.type) {
40 case "command_execution":
41 case "dynamic_tool": {
42 const { output: _output, ...displayItem } = item;
43 return displayItem;
44 }
45 case "file_change": {
46 const { diffStr, oldStr: _oldStr, newStr: _newStr, ...displayItem } = item;
47 // A failed edit's diffStr holds the provider's error, not a diff.
48 return item.status === "failed" && diffStr?.trim()
49 ? { ...displayItem, diffStr }
50 : displayItem;
51 }
52 default:
53 return item;
54 }
55 }
56
57 type CompactionLabelItem = Pick<
58 Extract<OrchestrationV2TurnItem, { type: "compaction" }>,
59 "status" | "beforeTokenCount" | "afterTokenCount"
60 >;
61
62 export function contextCompactionTokenCounts(
63 item: CompactionLabelItem,
64 ): { readonly before: string; readonly after: string } | null {
65 if (
66 item.status === "running" ||
67 item.beforeTokenCount === undefined ||
68 item.afterTokenCount === undefined
69 ) {
70 return null;
71 }
72 return { before: formatTokens(item.beforeTokenCount), after: formatTokens(item.afterTokenCount) };
73 }
74
75 export function contextCompactionLabel(
76 item: CompactionLabelItem,
77 resolve: MFunctionType = mFallback,
78 ): string {
79 if (item.status === "failed") return resolve(msg("Context compaction failed"));
80 if (item.status === "cancelled" || item.status === "interrupted")
81 return resolve(msg("Context compaction stopped"));
82 if (isOrchestrationV2WorkActive(item.status)) return resolve(msg("Compacting context"));
83 const tokens = contextCompactionTokenCounts(item);
84 return tokens
85 ? resolve(msg("Context compacted {before} → {after} tokens", tokens))
86 : resolve(msg("Context compacted"));
87 }
88
89 export interface WorkLogPresentationEntry {
90 readonly questionAnswer?: import("@t3tools/contracts").UserInputAttachmentAnswerPayload;
91 readonly id: string;
92 readonly createdAt: string;
93 readonly label: string;
94 readonly tone: "thinking" | "tool" | "info" | "error";
95 readonly command?: string;
96 readonly rawCommand?: string;
97 readonly detail?: string;
98 readonly viewedImagePath?: string;
99 readonly changedFiles?: ReadonlyArray<string>;
100 readonly toolTitle?: string;
101 readonly toolData?: unknown;
102 readonly requestKind?: string;
103 readonly itemType?: OrchestrationV2TurnItem["type"];
104 readonly toolLifecycleStatus?: WorkLogToolLifecycleStatus;
105 readonly structuredPayload?: OrchestrationV2TurnItem;
106 readonly toolSource?: ToolActivitySource;
107 readonly toolSurface?: ToolActivitySurface;
108 readonly toolIcon?: ToolActivityIcon;
109 }
110
111 export type ToolGroupAction =
112 | "link-pr"
113 | "unlink-pr"
114 | "list-prs"
115 | "watch-pr"
116 | "unwatch-pr"
117 | "read"
118 | "edit"
119 | "command"
120 | "thread-create"
121 | "browser"
122 | "device"
123 | "code-search"
124 | "search"
125 | "other"
126 | "update";
127
128 export type ToolGroupSummaryKind =
129 | "pull-request"
130 | ToolGroupAction
131 | "dynamic-tool"
132 | "reasoning"
133 | "agent-tool"
134 | "tone-tool"
135 | "mixed";
136
137 export function normalizeCompactToolLabel(value: string): string {
138 return value.replace(/\s+(?:complete|completed)\s*$/i, "").trim();
139 }
140
141 function workEntryToolName(
142 entry: Pick<WorkLogPresentationEntry, "label" | "toolTitle" | "toolData" | "structuredPayload">,
143 ): string | undefined {
144 const item = entry.structuredPayload;
145 if (item?.type === "dynamic_tool" && item.toolName) return item.toolName;
146 const data = asRecord(entry.toolData);
147 if (typeof data?.server === "string" && typeof data.tool === "string") {
148 return `${data.server}.${data.tool}`;
149 }
150 if (typeof data?.toolName === "string") return data.toolName;
151 return resolveT3McpToolDefinition(entry.toolTitle) ? entry.toolTitle : entry.label;
152 }
153
154 function workEntryToolInput(
155 entry: Pick<WorkLogPresentationEntry, "toolData" | "structuredPayload">,
156 ): unknown {
157 const item = entry.structuredPayload;
158 const data = asRecord(entry.toolData);
159 return item?.type === "dynamic_tool"
160 ? item.input
161 : (data?.arguments ?? data?.input ?? data?.rawInput);
162 }
163
164 function workEntryToolOutput(
165 entry: Pick<WorkLogPresentationEntry, "toolData" | "structuredPayload">,
166 ): unknown {
167 const item = entry.structuredPayload;
168 const data = asRecord(entry.toolData);
169 return item?.type === "dynamic_tool"
170 ? item.output
171 : (data?.output ?? data?.result ?? data?.rawOutput ?? data?.content);
172 }
173
174 function t3ToolStatusKey(status: string | undefined) {
175 return status === "inProgress" ||
176 status === "completed" ||
177 status === "failed" ||
178 status === "declined" ||
179 status === "stopped"
180 ? status
181 : "other";
182 }
183
184 function resolveT3McpToolPresentation(
185 definition: T3McpToolDefinition | null,
186 status: string | undefined,
187 data: unknown,
188 resolve: MFunctionType,
189 ) {
190 if (!definition) return null;
191 const detail = definition.labels[3];
192
193 const actionKind =
194 definition.summaryAction === "link-pr" ||
195 definition.summaryAction === "unlink-pr" ||
196 definition.summaryAction === "list-prs" ||
197 definition.summaryAction === "watch-pr" ||
198 definition.summaryAction === "unwatch-pr"
199 ? definition.summaryAction
200 : undefined;
201 const payload = asRecord(data);
202 const input =
203 asRecord(payload?.arguments) ?? asRecord(payload?.input) ?? asRecord(payload?.rawInput);
204 const urlTarget =
205 typeof input?.url === "string" ? sourceControlClients.parseChangeRequestUrl(input.url) : null;
206 const number = urlTarget?.link.number ?? input?.number;
207 const { shortLabel } = (urlTarget?.definition ?? sourceControlClients.get(undefined))
208 .changeRequest;
209 const pullRequestNumber =
210 actionKind !== undefined &&
211 actionKind !== "list-prs" &&
212 typeof number === "number" &&
213 Number.isSafeInteger(number) &&
214 number > 0
215 ? number
216 : null;
217 const sentence = t3ToolSentence(definition.labels);
218 const statusKey = t3ToolStatusKey(status);
219 // A tool added to the shared table after `t3ToolSentences.ts` was generated.
220 const [action, running, completed] = definition.labels;
221 const fallbackVerb =
222 status === "inProgress"
223 ? running
224 : status === "completed"
225 ? completed
226 : status === "failed"
227 ? `Failed to ${action.toLowerCase()}`
228 : status === "declined"
229 ? `Declined to ${action.toLowerCase()}`
230 : status === "stopped"
231 ? `Stopped ${running.toLowerCase()}`
232 : running;
233 const displayName =
234 sentence === undefined
235 ? `${fallbackVerb} ${pullRequestNumber === null ? detail : `${shortLabel} #${pullRequestNumber}`}`
236 : pullRequestNumber !== null && sentence.changeRequest !== undefined
237 ? resolve(sentence.changeRequest, {
238 status: statusKey,
239 changeRequest: shortLabel,
240 number: String(pullRequestNumber),
241 })
242 : resolve(sentence.detail, { status: statusKey });
243 return {
244 displayName,
245 icon: definition.icon,
246 ...(actionKind === undefined ? {} : { action: actionKind }),
247 };
248 }
249
250 export function liveActivityToolStatus(status: string | undefined, presentTense: boolean) {
251 if (status === "failed" || status === "declined" || status === "stopped" || status === "idle") {
252 return status;
253 }
254 if (presentTense || status === "inProgress") return "inProgress";
255 return "completed";
256 }
257
258 export function genericCommandStatusLabel(
259 status: ReturnType<typeof liveActivityToolStatus>,
260 resolve: MFunctionType = mFallback,
261 ) {
262 return resolve(
263 status === "inProgress"
264 ? msg("Running command")
265 : status === "failed"
266 ? msg("Failed command")
267 : status === "declined"
268 ? msg("Declined command")
269 : status === "stopped"
270 ? msg("Stopped command")
271 : msg("Ran command"),
272 );
273 }
274
275 const GENERIC_COMMAND_TITLES = new Set(["Ran command", "Run command", "Command"]);
276
277 export function commandlessCommandLabel(
278 entry: Pick<
279 WorkLogPresentationEntry,
280 "itemType" | "command" | "toolTitle" | "label" | "structuredPayload"
281 >,
282 status: ReturnType<typeof liveActivityToolStatus>,
283 resolve: MFunctionType = mFallback,
284 ): string | null {
285 if (entry.itemType !== "command_execution" || entry.command?.trim()) return null;
286 // The provider's own title, before a client substitutes its translated fallback.
287 const title = (
288 entry.structuredPayload ? entry.structuredPayload.title : entry.toolTitle || entry.label
289 )?.trim();
290 return !title || GENERIC_COMMAND_TITLES.has(normalizeCompactToolLabel(title))
291 ? genericCommandStatusLabel(status, resolve)
292 : null;
293 }
294
295 export function resolveWorkEntryToolPresentation(
296 entry: Pick<
297 WorkLogPresentationEntry,
298 "label" | "toolTitle" | "toolData" | "toolLifecycleStatus" | "structuredPayload"
299 >,
300 fallbackStatus?: "inProgress" | "completed",
301 resolve: MFunctionType = mFallback,
302 ) {
303 const definition = resolveT3McpToolDefinition(
304 workEntryToolName(entry),
305 workEntryToolInput(entry),
306 );
307 const status = entry.toolLifecycleStatus ?? fallbackStatus;
308 return resolveT3McpToolPresentation(
309 definition,
310 definition && t3ToolResultIndicatesFailure(workEntryToolOutput(entry)) ? "failed" : status,
311 entry.toolData,
312 resolve,
313 );
314 }
315
316 function asRecord(value: unknown): Record<string, unknown> | null {
317 return value !== null && typeof value === "object" && !Array.isArray(value)
318 ? (value as Record<string, unknown>)
319 : null;
320 }
321
322 function workLogEntryIsToolLike(entry: WorkLogPresentationEntry): boolean {
323 if (entry.tone === "tool" || entry.tone === "thinking" || entry.tone === "error") return true;
324 if (entry.command !== undefined && entry.command.trim().length > 0) return true;
325 if (entry.requestKind !== undefined) return true;
326 return entry.itemType !== undefined && isToolLifecycleItemType(entry.itemType);
327 }
328
329 function workEntryIndicatesToolFailureFromOutput(
330 entry: WorkLogPresentationEntry,
331 includeCommand: boolean,
332 ): boolean {
333 if (
334 entry.tone === "error" ||
335 entry.toolLifecycleStatus === "failed" ||
336 entry.toolLifecycleStatus === "declined"
337 ) {
338 return true;
339 }
340 // Reasoning detail is the model's own prose (often tens of KB), not tool
341 // output: scanning it is slow on long threads and misreads phrases like
342 // "that exit code 2 is expected" as a failed tool.
343 if (!workLogEntryIsToolLike(entry) || entry.itemType === "reasoning") return false;
344 if (
345 resolveT3McpToolDefinition(workEntryToolName(entry)) &&
346 t3ToolResultIndicatesFailure(workEntryToolOutput(entry))
347 ) {
348 return true;
349 }
350 const item = entry.structuredPayload;
351 if (item?.type === "command_execution") {
352 // The exit code outranks text in the output or the command itself.
353 if (item.exitCode !== undefined) return item.exitCode !== 0;
354 if (item.outputIndicatesFailure) return true;
355 if (item.output && toolOutputIndicatesFailure(item.output.slice(0, 32_768))) {
356 return true;
357 }
358 }
359 const output = includeCommand
360 ? [entry.detail, entry.command].filter(Boolean).join("\n")
361 : (entry.detail ?? "");
362 return output.length > 0 && toolOutputIndicatesFailure(output);
363 }
364
365 // Rows are re-derived on every timeline update but entries are reused while
366 // their item is unchanged, so these per-entry checks are computed once.
367 const entryChecks = new WeakMap<
368 WorkLogPresentationEntry,
369 { failure?: boolean; displayFailure?: boolean; action?: ToolGroupAction }
370 >();
371
372 function checksFor(entry: WorkLogPresentationEntry) {
373 let checks = entryChecks.get(entry);
374 if (!checks) {
375 checks = {};
376 entryChecks.set(entry, checks);
377 }
378 return checks;
379 }
380
381 export function workEntryIndicatesToolFailure(entry: WorkLogPresentationEntry): boolean {
382 return (checksFor(entry).failure ??= workEntryIndicatesToolFailureFromOutput(entry, true));
383 }
384
385 export function workEntryDisplayIndicatesToolFailure(entry: WorkLogPresentationEntry): boolean {
386 return (checksFor(entry).displayFailure ??= workEntryIndicatesToolFailureFromOutput(
387 entry,
388 false,
389 ));
390 }
391
392 const HIDEABLE_TOOL_CALL_ITEM_TYPES: ReadonlySet<WorkLogPresentationEntry["itemType"]> = new Set([
393 "command_execution",
394 "file_change",
395 "file_search",
396 "web_search",
397 "dynamic_tool",
398 ]);
399
400 export function workEntryHiddenByToolCallVisibility(
401 entry: WorkLogPresentationEntry,
402 visibility: ToolCallVisibility,
403 ): boolean {
404 if (visibility === "showAll" || !HIDEABLE_TOOL_CALL_ITEM_TYPES.has(entry.itemType)) return false;
405 if (visibility !== "hideSuccessful") return true;
406 return entry.toolLifecycleStatus === "completed" && !workEntryDisplayIndicatesToolFailure(entry);
407 }
408
409 function workLogEntryIsLocalCodeSearch(entry: WorkLogPresentationEntry): boolean {
410 return (
411 entry.itemType === "file_search" ||
412 (entry.itemType === "web_search" &&
413 /\bgrep\b/i.test(normalizeCompactToolLabel(entry.toolTitle ?? entry.label)))
414 );
415 }
416
417 export function toolGroupAction(entry: WorkLogPresentationEntry): ToolGroupAction {
418 return (checksFor(entry).action ??= computeToolGroupAction(entry));
419 }
420
421 function computeToolGroupAction(entry: WorkLogPresentationEntry): ToolGroupAction {
422 if (entry.itemType === "thread_created") return "thread-create";
423 const presentation = resolveWorkEntryToolPresentation(entry);
424 if (presentation?.action !== undefined) return presentation.action;
425 if (presentation?.icon === "browser") return "browser";
426 if (presentation?.icon === "device") return "device";
427 if (entry.requestKind === "file-read" || entry.viewedImagePath !== undefined) return "read";
428 if (entry.itemType === "approval_request" || entry.itemType === "user_input_request") {
429 return workLogEntryIsToolLike(entry) ? "other" : "update";
430 }
431 const data = asRecord(entry.toolData) ?? {};
432 const toolName =
433 entry.structuredPayload?.type === "dynamic_tool"
434 ? entry.structuredPayload.toolName
435 : typeof data.toolName === "string"
436 ? data.toolName
437 : entry.toolTitle;
438 const classified = classifyToolActivity({
439 itemType:
440 entry.itemType === "command_execution" ||
441 entry.itemType === "file_change" ||
442 entry.itemType === "web_search"
443 ? entry.itemType
444 : entry.itemType === "dynamic_tool"
445 ? "dynamic_tool_call"
446 : undefined,
447 title: entry.toolTitle ?? entry.label,
448 data: {
449 ...data,
450 ...(toolName ? { toolName } : {}),
451 },
452 });
453 if (classified === "read") return "read";
454 if (classified === "file_change" || entry.itemType === "file_change") return "edit";
455 if (classified === "command" || entry.itemType === "command_execution" || entry.command) {
456 return "command";
457 }
458 if (classified === "search") {
459 return entry.itemType === "web_search" && !workLogEntryIsLocalCodeSearch(entry)
460 ? "search"
461 : "code-search";
462 }
463 if (workLogEntryIsLocalCodeSearch(entry)) return "code-search";
464 if (entry.itemType === "web_search") return "search";
465 if ((entry.changedFiles?.length ?? 0) > 0) return "edit";
466 return workLogEntryIsToolLike(entry) ? "other" : "update";
467 }
468
469 export function workEntryViewedImagePath(entry: WorkLogPresentationEntry): string | null {
470 const viewedImagePath = entry.viewedImagePath?.trim();
471 if (
472 viewedImagePath !== undefined &&
473 !/[\r\n]/.test(viewedImagePath) &&
474 isWorkspaceImagePreviewPath(viewedImagePath)
475 ) {
476 return viewedImagePath;
477 }
478 const detail = entry.detail?.trim();
479 return toolGroupAction(entry) === "read" &&
480 detail !== undefined &&
481 !/[\r\n]/.test(detail) &&
482 isWorkspaceImagePreviewPath(detail)
483 ? detail
484 : null;
485 }
486
487 /** Distinct images the agent opened across a tool group, in viewing order. */
488 export function workEntriesViewedImagePaths(
489 entries: ReadonlyArray<WorkLogPresentationEntry>,
490 ): string[] {
491 return [...new Set(entries.flatMap((entry) => workEntryViewedImagePath(entry) ?? []))];
492 }
493
494 export interface ViewedImageAsset {
495 readonly resource: Extract<AssetResource, { readonly _tag: "media-file" }>;
496 readonly alt: string;
497 readonly srcFragment: string;
498 }
499
500 export function resolveViewedImageAsset(
501 source: string,
502 input: {
503 readonly threadId: ThreadId;
504 readonly workspaceRoot?: string | null | undefined;
505 },
506 ): ViewedImageAsset | null {
507 const imageSource = classifyMarkdownImageSource(source, input.workspaceRoot ?? ".");
508 if (imageSource._tag !== "WorkspaceFile") return null;
509 const resolvedFilePath =
510 input.workspaceRoot == null && imageSource.path.startsWith("./")
511 ? imageSource.path.slice(2)
512 : imageSource.path;
513
514 const media = resolveMediaSource(source, {
515 threadId: input.threadId,
516 workspaceRoot: input.workspaceRoot,
517 resolvedFilePath,
518 });
519 if (media === null || media.access !== "environment") return null;
520 return { resource: media.resource, alt: media.name, srcFragment: media.srcFragment };
521 }
522
523 function toolGroupActionCount(
524 action: ToolGroupAction,
525 entries: ReadonlyArray<WorkLogPresentationEntry>,
526 ): number {
527 if (action !== "edit") return entries.length;
528 const changedFiles = new Set<string>();
529 let editsWithoutFileDetails = 0;
530 for (const entry of entries) {
531 if (!entry.changedFiles || entry.changedFiles.length === 0) {
532 editsWithoutFileDetails += 1;
533 } else {
534 for (const file of entry.changedFiles) changedFiles.add(file);
535 }
536 }
537 return changedFiles.size + editsWithoutFileDetails;
538 }
539
540 function toolGroupActionLabel(
541 action: ToolGroupAction,
542 count: number,
543 resolve: MFunctionType,
544 ): string {
545 switch (action) {
546 case "link-pr":
547 return resolve(
548 msg(
549 "{count, plural, one {Linked {count} pull request} other {Linked {count} pull requests}}",
550 {
551 count,
552 },
553 ),
554 );
555 case "unlink-pr":
556 return resolve(
557 msg(
558 "{count, plural, one {Unlinked {count} pull request} other {Unlinked {count} pull requests}}",
559 { count },
560 ),
561 );
562 case "watch-pr":
563 return resolve(
564 msg(
565 "{count, plural, one {Watching {count} pull request} other {Watching {count} pull requests}}",
566 { count },
567 ),
568 );
569 case "unwatch-pr":
570 return resolve(
571 msg(
572 "{count, plural, one {Stopped watching {count} pull request} other {Stopped watching {count} pull requests}}",
573 { count },
574 ),
575 );
576 case "list-prs":
577 return resolve(
578 msg(
579 "{count, plural, =1 {Checked linked pull requests} other {Checked linked pull requests {count} times}}",
580 { count },
581 ),
582 );
583 case "read":
584 return resolve(
585 msg("{count, plural, one {Read {count} file} other {Read {count} files}}", { count }),
586 );
587 case "edit":
588 return resolve(
589 msg("{count, plural, one {Changed {count} file} other {Changed {count} files}}", { count }),
590 );
591 case "command":
592 return resolve(
593 msg("{count, plural, one {Ran {count} command} other {Ran {count} commands}}", { count }),
594 );
595 case "thread-create":
596 return resolve(
597 msg("{count, plural, one {Created {count} thread} other {Created {count} threads}}", {
598 count,
599 }),
600 );
601 case "device":
602 return resolve(
603 msg(
604 "{count, plural, one {Used device controls {count} time} other {Used device controls {count} times}}",
605 { count },
606 ),
607 );
608 case "browser":
609 return resolve(
610 msg("{count, plural, one {Used browser {count} time} other {Used browser {count} times}}", {
611 count,
612 }),
613 );
614 case "search":
615 return resolve(
616 msg(
617 "{count, plural, one {Searched the web {count} time} other {Searched the web {count} times}}",
618 { count },
619 ),
620 );
621 case "code-search":
622 return resolve(
623 msg(
624 "{count, plural, one {Searched code {count} time} other {Searched code {count} times}}",
625 { count },
626 ),
627 );
628 case "other":
629 return resolve(
630 msg("{count, plural, one {Used {count} tool} other {Used {count} tools}}", { count }),
631 );
632 case "update":
633 return resolve(
634 msg("{count, plural, one {Received {count} update} other {Received {count} updates}}", {
635 count,
636 }),
637 );
638 }
639 }
640
641 function joinClauses(items: ReadonlyArray<string>, resolve: MFunctionType): string {
642 if (items.length < 2) return items[0] ?? "";
643 if (items.length === 2) {
644 return resolve(msg("{first} and {second}", { first: items[0]!, second: items[1]! }));
645 }
646 return resolve(
647 msg("{items}, and {last}", { items: items.slice(0, -1).join(", "), last: items.at(-1)! }),
648 );
649 }
650
651 function t3ToolSummaryCall(entry: WorkLogPresentationEntry): T3ToolSummaryCall {
652 return {
653 input: workEntryToolInput(entry),
654 output: workEntryToolOutput(entry),
655 outcome:
656 entry.toolLifecycleStatus === "failed" ||
657 entry.toolLifecycleStatus === "declined" ||
658 entry.tone === "error"
659 ? "failed"
660 : entry.toolLifecycleStatus === "completed"
661 ? "completed"
662 : "unfinished",
663 };
664 }
665
666 function summaryActionPriority(action: ToolGroupAction | T3McpToolSummaryAction): number {
667 switch (action) {
668 case "command":
669 case "edit":
670 case "delegate":
671 case "task-cancel":
672 case "thread-create":
673 case "thread-send":
674 case "thread-interrupt":
675 case "workflow-stop":
676 case "background-wait":
677 case "schedule-create":
678 case "schedule-update":
679 case "schedule-delete":
680 case "schedule-run":
681 case "thread-configure":
682 case "thread-fork":
683 case "thread-merge":
684 case "thread-organize":
685 case "thread-update":
686 case "queue-edit":
687 case "queue-cancel":
688 case "queue-reorder":
689 case "queue-steer":
690 case "question-respond":
691 case "worktree-handoff":
692 case "project-create":
693 case "project-update":
694 case "project-delete":
695 case "project-clone":
696 case "environment-update":
697 case "theme-set":
698 case "attachment-prepare":
699 case "attachment-discard":
700 case "attachment-send":
701 return 0;
702 case "other":
703 case "update":
704 return 2;
705 default:
706 return 1;
707 }
708 }
709
710 export function summarizeToolGroup(
711 entries: ReadonlyArray<WorkLogPresentationEntry>,
712 resolve: MFunctionType = mFallback,
713 ): {
714 summary: string;
715 hasFailure: boolean;
716 } {
717 const toolEntries = entries.filter((entry) => entry.itemType !== "reasoning");
718 if (entries.length > 0 && toolEntries.length === 0) {
719 return {
720 summary:
721 entries.length === 1
722 ? resolve(msg("Thought", { $context: "noun, a reasoning step" }))
723 : resolve(msg("Thought (×{count})", { count: entries.length })),
724 hasFailure: false,
725 };
726 }
727 entries = toolEntries;
728 const groups = new Map<
729 ToolGroupAction | T3McpToolSummaryAction,
730 {
731 action: ToolGroupAction;
732 t3Action: T3McpToolSummaryAction | null;
733 entries: WorkLogPresentationEntry[];
734 }
735 >();
736 const sources = new Map<string, ToolActivitySource>();
737 for (const entry of entries) {
738 const t3Action = resolveT3McpSummaryAction(
739 workEntryToolName(entry),
740 t3ToolSummaryCall(entry).input,
741 );
742 if (entry.toolSource && t3Action === null) {
743 sources.set(entry.toolSource.key, entry.toolSource);
744 continue;
745 }
746 const action = toolGroupAction(entry);
747 const key = t3Action ?? action;
748 const group = groups.get(key);
749 if (group) group.entries.push(entry);
750 else groups.set(key, { action, t3Action, entries: [entry] });
751 }
752 const summaries = [...groups].map(([action, group], index) => ({
753 index,
754 count: group.entries.length,
755 priority: summaryActionPriority(action),
756 ...(group.t3Action
757 ? summarizeT3ToolCalls(group.t3Action, group.entries.map(t3ToolSummaryCall), resolve)
758 : {
759 label: toolGroupActionLabel(
760 group.action,
761 toolGroupActionCount(group.action, group.entries),
762 resolve,
763 ),
764 failedCount: group.entries.filter(workEntryDisplayIndicatesToolFailure).length,
765 }),
766 }));
767 const selected = [...summaries]
768 .sort((a, b) => a.priority - b.priority || a.index - b.index)
769 .slice(0, 2)
770 .sort((a, b) => a.index - b.index);
771 const labels = selected.map(({ label }) => label);
772 if (sources.size > 0) {
773 const sourceValues = [...sources.values()];
774 const sourceNames = [...new Set(sourceValues.map((source) => source.name))];
775 const names = joinClauses(sourceNames, resolve);
776 const allIntegrations = sourceValues.every((source) => source.kind === "integration");
777 labels.unshift(
778 allIntegrations
779 ? resolve(
780 msg(
781 "{count, plural, =1 {Used {names} integration} other {Used {names} integrations}}",
782 { count: sourceNames.length, names },
783 ),
784 )
785 : resolve(msg("Used {names}", { names })),
786 );
787 }
788 const sourcedCount = entries.filter(
789 (entry) =>
790 entry.toolSource !== undefined &&
791 resolveT3McpToolDefinition(workEntryToolName(entry)) === null,
792 ).length;
793 const remainingCount =
794 entries.length - sourcedCount - selected.reduce((count, group) => count + group.count, 0);
795 if (remainingCount > 0) {
796 labels.push(
797 resolve(
798 msg(
799 "{count, plural, one {Performed {count} other action} other {Performed {count} other actions}}",
800 { count: remainingCount },
801 ),
802 ),
803 );
804 }
805 const sentenceLabels = labels.map((label, index) =>
806 index === 0 ? label : label.charAt(0).toLowerCase() + label.slice(1),
807 );
808 const summary = joinClauses(sentenceLabels, resolve);
809 return { summary, hasFailure: summaries.some((group) => group.failedCount > 0) };
810 }
811
812 export function toolGroupSummaryKind(
813 entries: ReadonlyArray<WorkLogPresentationEntry>,
814 ): ToolGroupSummaryKind {
815 const toolEntries = entries.filter((entry) => entry.itemType !== "reasoning");
816 if (entries.length > 0 && toolEntries.length === 0) return "reasoning";
817 entries = toolEntries;
818 if (
819 entries.length > 0 &&
820 entries.every((entry) => resolveWorkEntryToolPresentation(entry)?.icon === "pull-request")
821 )
822 return "pull-request";
823 const actions = new Set(entries.map(toolGroupAction));
824 if (actions.size !== 1) return "mixed";
825 const action = actions.values().next().value!;
826 if (action !== "other") return action;
827 const fallbackKinds = new Set(
828 entries.map((entry): ToolGroupSummaryKind => {
829 if (entry.itemType === "dynamic_tool") return "dynamic-tool";
830 if (entry.itemType === "subagent") return "agent-tool";
831 if (entry.tone === "thinking") return "agent-tool";
832 if (entry.tone === "tool") return "tone-tool";
833 return "other";
834 }),
835 );
836 return fallbackKinds.size === 1 ? fallbackKinds.values().next().value! : "mixed";
837 }
838
839 export function liveThoughtLine(markdown: string): string {
840 const heading = /^\s*\*\*([^*\r\n]+)\*\*[ \t]*\r?(?:\n|$)/.exec(markdown)?.[1];
841 const text = (heading ?? markdown)
842 .replace(/!?\[([^\]]*)\]\([^)]*\)/g, "$1")
843 .replace(/^[ \t]*(?:#{1,6}|[-*+]|\d+\.)[ \t]+/gm, "")
844 .replace(/`+|\*\*|~~/g, "")
845 .replace(/(^|[^\w*])[*_]([^*_\n]+)[*_](?![\w*])/g, "$1$2")
846 .replace(/\s+/g, " ")
847 .trim();
848 if (heading !== undefined) return text;
849 // CJK sentences end in full-width marks with no space after them.
850 const end = /[.?!]["'”’)]?(?=\s)|[。!?]["'”’)」』]?/.exec(text);
851 return end ? text.slice(0, end.index + end[0].length) : text;
852 }