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

presentation.ts

668 lines22.9 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 resolveT3McpSummaryAction,
14 resolveT3McpToolDefinition,
15 type T3McpToolDefinition,
16 type T3McpToolSummaryAction,
17} from "@t3tools/shared/t3McpToolPresentation";
18import { classifyMarkdownImageSource } from "@t3tools/client-runtime/markdown-images";
19import { resolveMediaSource } from "@t3tools/client-runtime/media-source";
20import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
21import { isWorkspaceImagePreviewPath } from "@t3tools/shared/mediaPreview";
22import { formatTokens } from "@t3tools/shared/usageFormat";
23import { classifyToolActivity } from "@t3tools/shared/toolActivity";
24import { toolOutputIndicatesFailure } from "@t3tools/shared/toolOutput";
25​
26import {
27 summarizeT3ToolCalls,
28 t3ToolResultIndicatesFailure,
29 type T3ToolSummaryCall,
30} from "@t3tools/client-runtime/t3ToolSummary";
31​
32export type WorkLogToolLifecycleStatus = RuntimeItemStatus | "stopped" | "idle";
33​
34export function toolItemForDisplay(item: OrchestrationV2TurnItem): OrchestrationV2TurnItem {
35 switch (item.type) {
36 case "command_execution":
37 case "dynamic_tool": {
38 const { output: _output, ...displayItem } = item;
39 return displayItem;
40 }
41 case "file_change": {
42 const { diffStr, oldStr: _oldStr, newStr: _newStr, ...displayItem } = item;
43 // A failed edit's diffStr holds the provider's error, not a diff.
44 return item.status === "failed" && diffStr?.trim()
45 ? { ...displayItem, diffStr }
46 : displayItem;
47 }
48 default:
49 return item;
50 }
52​
53type CompactionLabelItem = Pick<
54 Extract<OrchestrationV2TurnItem, { type: "compaction" }>,
55 "status" | "beforeTokenCount" | "afterTokenCount"
56>;
57​
58export function contextCompactionTokenCounts(
59 item: CompactionLabelItem,
60): { readonly before: string; readonly after: string } | null {
61 if (
62 item.status === "running" ||
63 item.beforeTokenCount === undefined ||
64 item.afterTokenCount === undefined
65 ) {
66 return null;
67 }
68 return { before: formatTokens(item.beforeTokenCount), after: formatTokens(item.afterTokenCount) };
70​
71export function contextCompactionLabel(item: CompactionLabelItem): string {
72 if (item.status === "failed") return "Context compaction failed";
73 if (item.status === "cancelled" || item.status === "interrupted")
74 return "Context compaction stopped";
75 if (isOrchestrationV2WorkActive(item.status)) return "Compacting context";
76 const tokens = contextCompactionTokenCounts(item);
77 return tokens
78 ? `Context compacted ${tokens.before} → ${tokens.after} tokens`
79 : "Context compacted";
81​
82export interface WorkLogPresentationEntry {
83 readonly questionAnswer?: import("@t3tools/contracts").UserInputAttachmentAnswerPayload;
84 readonly id: string;
85 readonly createdAt: string;
86 readonly label: string;
87 readonly tone: "thinking" | "tool" | "info" | "error";
88 readonly command?: string;
89 readonly rawCommand?: string;
90 readonly detail?: string;
91 readonly viewedImagePath?: string;
92 readonly changedFiles?: ReadonlyArray<string>;
93 readonly toolTitle?: string;
94 readonly toolData?: unknown;
95 readonly requestKind?: string;
96 readonly itemType?: OrchestrationV2TurnItem["type"];
97 readonly toolLifecycleStatus?: WorkLogToolLifecycleStatus;
98 readonly structuredPayload?: OrchestrationV2TurnItem;
99 readonly toolSource?: ToolActivitySource;
100 readonly toolSurface?: ToolActivitySurface;
101 readonly toolIcon?: ToolActivityIcon;
103​
104export type ToolGroupAction =
105 | "link-pr"
106 | "unlink-pr"
107 | "list-prs"
108 | "watch-pr"
109 | "unwatch-pr"
110 | "read"
111 | "edit"
112 | "command"
113 | "thread-create"
114 | "browser"
115 | "device"
116 | "code-search"
117 | "search"
118 | "other"
119 | "update";
120​
121export type ToolGroupSummaryKind =
122 | "pull-request"
123 | ToolGroupAction
124 | "dynamic-tool"
125 | "reasoning"
126 | "agent-tool"
127 | "tone-tool"
128 | "mixed";
129​
130export function normalizeCompactToolLabel(value: string): string {
131 return value.replace(/\s+(?:complete|completed)\s*$/i, "").trim();
133​
134function workEntryToolName(
135 entry: Pick<WorkLogPresentationEntry, "label" | "toolTitle" | "toolData" | "structuredPayload">,
136): string | undefined {
137 const item = entry.structuredPayload;
138 if (item?.type === "dynamic_tool" && item.toolName) return item.toolName;
139 const data = asRecord(entry.toolData);
140 if (typeof data?.server === "string" && typeof data.tool === "string") {
141 return `${data.server}.${data.tool}`;
142 }
143 if (typeof data?.toolName === "string") return data.toolName;
144 return resolveT3McpToolDefinition(entry.toolTitle) ? entry.toolTitle : entry.label;
146​
147function workEntryToolInput(
148 entry: Pick<WorkLogPresentationEntry, "toolData" | "structuredPayload">,
149): unknown {
150 const item = entry.structuredPayload;
151 const data = asRecord(entry.toolData);
152 return item?.type === "dynamic_tool"
153 ? item.input
154 : (data?.arguments ?? data?.input ?? data?.rawInput);
156​
157function workEntryToolOutput(
158 entry: Pick<WorkLogPresentationEntry, "toolData" | "structuredPayload">,
159): unknown {
160 const item = entry.structuredPayload;
161 const data = asRecord(entry.toolData);
162 return item?.type === "dynamic_tool"
163 ? item.output
164 : (data?.output ?? data?.result ?? data?.rawOutput ?? data?.content);
166​
167function resolveT3McpToolPresentation(
168 definition: T3McpToolDefinition | null,
169 status: string | undefined,
170 data?: unknown,
171) {
172 if (!definition) return null;
173 const [action, running, completed, detail] = definition.labels;
174 const verb =
175 status === "inProgress"
176 ? running
177 : status === "completed"
178 ? completed
179 : status === "failed"
180 ? `Failed to ${action.toLowerCase()}`
181 : status === "declined"
182 ? `Declined to ${action.toLowerCase()}`
183 : status === "stopped"
184 ? `Stopped ${running.toLowerCase()}`
185 : running;
186​
187 const actionKind =
188 definition.summaryAction === "link-pr" ||
189 definition.summaryAction === "unlink-pr" ||
190 definition.summaryAction === "list-prs" ||
191 definition.summaryAction === "watch-pr" ||
192 definition.summaryAction === "unwatch-pr"
193 ? definition.summaryAction
194 : undefined;
195 const payload = asRecord(data);
196 const input =
197 asRecord(payload?.arguments) ?? asRecord(payload?.input) ?? asRecord(payload?.rawInput);
198 const urlTarget =
199 typeof input?.url === "string" ? sourceControlClients.parseChangeRequestUrl(input.url) : null;
200 const number = urlTarget?.link.number ?? input?.number;
201 const { shortLabel } = (urlTarget?.definition ?? sourceControlClients.get(undefined))
202 .changeRequest;
203 const target =
204 actionKind !== undefined &&
205 actionKind !== "list-prs" &&
206 typeof number === "number" &&
207 Number.isSafeInteger(number) &&
208 number > 0
209 ? `${shortLabel} #${number}`
210 : detail;
211 return {
212 displayName: `${verb} ${target}`,
213 icon: definition.icon,
214 ...(actionKind === undefined ? {} : { action: actionKind }),
215 };
217​
218export function liveActivityToolStatus(status: string | undefined, presentTense: boolean) {
219 if (status === "failed" || status === "declined" || status === "stopped" || status === "idle") {
220 return status;
221 }
222 if (presentTense || status === "inProgress") return "inProgress";
223 return "completed";
225​
226export function resolveWorkEntryToolPresentation(
227 entry: Pick<
228 WorkLogPresentationEntry,
229 "label" | "toolTitle" | "toolData" | "toolLifecycleStatus" | "structuredPayload"
230 >,
231 fallbackStatus?: "inProgress" | "completed",
232) {
233 const definition = resolveT3McpToolDefinition(
234 workEntryToolName(entry),
235 workEntryToolInput(entry),
236 );
237 const status = entry.toolLifecycleStatus ?? fallbackStatus;
238 return resolveT3McpToolPresentation(
239 definition,
240 definition && t3ToolResultIndicatesFailure(workEntryToolOutput(entry)) ? "failed" : status,
241 entry.toolData,
242 );
244​
245function asRecord(value: unknown): Record<string, unknown> | null {
246 return value !== null && typeof value === "object" && !Array.isArray(value)
247 ? (value as Record<string, unknown>)
248 : null;
250​
251function workLogEntryIsToolLike(entry: WorkLogPresentationEntry): boolean {
252 if (entry.tone === "tool" || entry.tone === "thinking" || entry.tone === "error") return true;
253 if (entry.command !== undefined && entry.command.trim().length > 0) return true;
254 if (entry.requestKind !== undefined) return true;
255 return entry.itemType !== undefined && isToolLifecycleItemType(entry.itemType);
257​
258function workEntryIndicatesToolFailureFromOutput(
259 entry: WorkLogPresentationEntry,
260 includeCommand: boolean,
261): boolean {
262 if (
263 entry.tone === "error" ||
264 entry.toolLifecycleStatus === "failed" ||
265 entry.toolLifecycleStatus === "declined"
266 ) {
267 return true;
268 }
269 // Reasoning detail is the model's own prose (often tens of KB), not tool
270 // output: scanning it is slow on long threads and misreads phrases like
271 // "that exit code 2 is expected" as a failed tool.
272 if (!workLogEntryIsToolLike(entry) || entry.itemType === "reasoning") return false;
273 if (
274 resolveT3McpToolDefinition(workEntryToolName(entry)) &&
275 t3ToolResultIndicatesFailure(workEntryToolOutput(entry))
276 ) {
277 return true;
278 }
279 const item = entry.structuredPayload;
280 if (item?.type === "command_execution") {
281 // The exit code outranks text in the output or the command itself.
282 if (item.exitCode !== undefined) return item.exitCode !== 0;
283 if (item.outputIndicatesFailure) return true;
284 if (item.output && toolOutputIndicatesFailure(item.output.slice(0, 32_768))) {
285 return true;
286 }
287 }
288 const output = includeCommand
289 ? [entry.detail, entry.command].filter(Boolean).join("\n")
290 : (entry.detail ?? "");
291 return output.length > 0 && toolOutputIndicatesFailure(output);
293​
294// Rows are re-derived on every timeline update but entries are reused while
295// their item is unchanged, so these per-entry checks are computed once.
296const entryChecks = new WeakMap<
297 WorkLogPresentationEntry,
298 { failure?: boolean; displayFailure?: boolean; action?: ToolGroupAction }
299>();
300​
301function checksFor(entry: WorkLogPresentationEntry) {
302 let checks = entryChecks.get(entry);
303 if (!checks) {
304 checks = {};
305 entryChecks.set(entry, checks);
306 }
307 return checks;
309​
310export function workEntryIndicatesToolFailure(entry: WorkLogPresentationEntry): boolean {
311 return (checksFor(entry).failure ??= workEntryIndicatesToolFailureFromOutput(entry, true));
313​
314export function workEntryDisplayIndicatesToolFailure(entry: WorkLogPresentationEntry): boolean {
315 return (checksFor(entry).displayFailure ??= workEntryIndicatesToolFailureFromOutput(
316 entry,
317 false,
318 ));
320​
321function workLogEntryIsLocalCodeSearch(entry: WorkLogPresentationEntry): boolean {
322 return (
323 entry.itemType === "file_search" ||
324 (entry.itemType === "web_search" &&
325 /\bgrep\b/i.test(normalizeCompactToolLabel(entry.toolTitle ?? entry.label)))
326 );
328​
329export function toolGroupAction(entry: WorkLogPresentationEntry): ToolGroupAction {
330 return (checksFor(entry).action ??= computeToolGroupAction(entry));
332​
333function computeToolGroupAction(entry: WorkLogPresentationEntry): ToolGroupAction {
334 if (entry.itemType === "thread_created") return "thread-create";
335 const presentation = resolveWorkEntryToolPresentation(entry);
336 if (presentation?.action !== undefined) return presentation.action;
337 if (presentation?.icon === "browser") return "browser";
338 if (presentation?.icon === "device") return "device";
339 if (entry.requestKind === "file-read" || entry.viewedImagePath !== undefined) return "read";
340 if (entry.itemType === "approval_request" || entry.itemType === "user_input_request") {
341 return workLogEntryIsToolLike(entry) ? "other" : "update";
342 }
343 const data = asRecord(entry.toolData) ?? {};
344 const toolName =
345 entry.structuredPayload?.type === "dynamic_tool"
346 ? entry.structuredPayload.toolName
347 : typeof data.toolName === "string"
348 ? data.toolName
349 : entry.toolTitle;
350 const classified = classifyToolActivity({
351 itemType:
352 entry.itemType === "command_execution" ||
353 entry.itemType === "file_change" ||
354 entry.itemType === "web_search"
355 ? entry.itemType
356 : entry.itemType === "dynamic_tool"
357 ? "dynamic_tool_call"
358 : undefined,
359 title: entry.toolTitle ?? entry.label,
360 data: {
361 ...data,
362 ...(toolName ? { toolName } : {}),
363 },
364 });
365 if (classified === "read") return "read";
366 if (classified === "file_change" || entry.itemType === "file_change") return "edit";
367 if (classified === "command" || entry.itemType === "command_execution" || entry.command) {
368 return "command";
369 }
370 if (classified === "search") {
371 return entry.itemType === "web_search" && !workLogEntryIsLocalCodeSearch(entry)
372 ? "search"
373 : "code-search";
374 }
375 if (workLogEntryIsLocalCodeSearch(entry)) return "code-search";
376 if (entry.itemType === "web_search") return "search";
377 if ((entry.changedFiles?.length ?? 0) > 0) return "edit";
378 return workLogEntryIsToolLike(entry) ? "other" : "update";
380​
381export function workEntryViewedImagePath(entry: WorkLogPresentationEntry): string | null {
382 const viewedImagePath = entry.viewedImagePath?.trim();
383 if (
384 viewedImagePath !== undefined &&
385 !/[\r\n]/.test(viewedImagePath) &&
386 isWorkspaceImagePreviewPath(viewedImagePath)
387 ) {
388 return viewedImagePath;
389 }
390 const detail = entry.detail?.trim();
391 return toolGroupAction(entry) === "read" &&
392 detail !== undefined &&
393 !/[\r\n]/.test(detail) &&
394 isWorkspaceImagePreviewPath(detail)
395 ? detail
396 : null;
398​
399export interface ViewedImageAsset {
400 readonly resource: Extract<AssetResource, { readonly _tag: "media-file" }>;
401 readonly alt: string;
402 readonly srcFragment: string;
404​
405export function resolveViewedImageAsset(
406 source: string,
407 input: {
408 readonly threadId: ThreadId;
409 readonly workspaceRoot?: string | null | undefined;
410 },
411): ViewedImageAsset | null {
412 const imageSource = classifyMarkdownImageSource(source, input.workspaceRoot ?? ".");
413 if (imageSource._tag !== "WorkspaceFile") return null;
414 const resolvedFilePath =
415 input.workspaceRoot == null && imageSource.path.startsWith("./")
416 ? imageSource.path.slice(2)
417 : imageSource.path;
418​
419 const media = resolveMediaSource(source, {
420 threadId: input.threadId,
421 workspaceRoot: input.workspaceRoot,
422 resolvedFilePath,
423 });
424 if (media === null || media.access !== "environment") return null;
425 return { resource: media.resource, alt: media.name, srcFragment: media.srcFragment };
427​
428function toolGroupActionCount(
429 action: ToolGroupAction,
430 entries: ReadonlyArray<WorkLogPresentationEntry>,
431): number {
432 if (action !== "edit") return entries.length;
433 const changedFiles = new Set<string>();
434 let editsWithoutFileDetails = 0;
435 for (const entry of entries) {
436 if (!entry.changedFiles || entry.changedFiles.length === 0) {
437 editsWithoutFileDetails += 1;
438 } else {
439 for (const file of entry.changedFiles) changedFiles.add(file);
440 }
441 }
442 return changedFiles.size + editsWithoutFileDetails;
444​
445function toolGroupActionLabel(action: ToolGroupAction, count: number): string {
446 switch (action) {
447 case "link-pr":
448 return `Linked ${count} ${count === 1 ? "pull request" : "pull requests"}`;
449 case "unlink-pr":
450 return `Unlinked ${count} ${count === 1 ? "pull request" : "pull requests"}`;
451 case "watch-pr":
452 return `Watching ${count} ${count === 1 ? "pull request" : "pull requests"}`;
453 case "unwatch-pr":
454 return `Stopped watching ${count} ${count === 1 ? "pull request" : "pull requests"}`;
455 case "list-prs":
456 return count === 1
457 ? "Checked linked pull requests"
458 : `Checked linked pull requests ${count} times`;
459 case "read":
460 return `Read ${count} ${count === 1 ? "file" : "files"}`;
461 case "edit":
462 return `Changed ${count} ${count === 1 ? "file" : "files"}`;
463 case "command":
464 return `Ran ${count} ${count === 1 ? "command" : "commands"}`;
465 case "thread-create":
466 return `Created ${count} ${count === 1 ? "thread" : "threads"}`;
467 case "device":
468 return `Used device controls ${count} ${count === 1 ? "time" : "times"}`;
469 case "browser":
470 return `Used browser ${count} ${count === 1 ? "time" : "times"}`;
471 case "search":
472 return `Searched the web ${count} ${count === 1 ? "time" : "times"}`;
473 case "code-search":
474 return `Searched code ${count} ${count === 1 ? "time" : "times"}`;
475 case "other":
476 return `Used ${count} ${count === 1 ? "tool" : "tools"}`;
477 case "update":
478 return `Received ${count} ${count === 1 ? "update" : "updates"}`;
479 }
481​
482function t3ToolSummaryCall(entry: WorkLogPresentationEntry): T3ToolSummaryCall {
483 return {
484 input: workEntryToolInput(entry),
485 output: workEntryToolOutput(entry),
486 outcome:
487 entry.toolLifecycleStatus === "failed" ||
488 entry.toolLifecycleStatus === "declined" ||
489 entry.tone === "error"
490 ? "failed"
491 : entry.toolLifecycleStatus === "completed"
492 ? "completed"
493 : "unfinished",
494 };
496​
497function summaryActionPriority(action: ToolGroupAction | T3McpToolSummaryAction): number {
498 switch (action) {
499 case "command":
500 case "edit":
501 case "delegate":
502 case "task-cancel":
503 case "thread-create":
504 case "thread-send":
505 case "thread-interrupt":
506 case "workflow-stop":
507 case "background-wait":
508 case "schedule-create":
509 case "schedule-update":
510 case "schedule-delete":
511 case "schedule-run":
512 case "thread-configure":
513 case "thread-fork":
514 case "thread-merge":
515 case "thread-organize":
516 case "thread-update":
517 case "queue-edit":
518 case "queue-cancel":
519 case "queue-reorder":
520 case "queue-steer":
521 case "question-respond":
522 case "worktree-handoff":
523 case "project-create":
524 case "project-update":
525 case "project-delete":
526 case "project-clone":
527 case "environment-update":
528 case "attachment-prepare":
529 case "attachment-discard":
530 case "attachment-send":
531 return 0;
532 case "other":
533 case "update":
534 return 2;
535 default:
536 return 1;
537 }
539​
540export function summarizeToolGroup(entries: ReadonlyArray<WorkLogPresentationEntry>): {
541 summary: string;
542 hasFailure: boolean;
543} {
544 const toolEntries = entries.filter((entry) => entry.itemType !== "reasoning");
545 if (entries.length > 0 && toolEntries.length === 0) {
546 return {
547 summary: entries.length === 1 ? "Thought" : `Thought (×${entries.length})`,
548 hasFailure: false,
549 };
550 }
551 entries = toolEntries;
552 const groups = new Map<
553 ToolGroupAction | T3McpToolSummaryAction,
554 {
555 action: ToolGroupAction;
556 t3Action: T3McpToolSummaryAction | null;
557 entries: WorkLogPresentationEntry[];
558 }
559 >();
560 const sources = new Map<string, ToolActivitySource>();
561 for (const entry of entries) {
562 const t3Action = resolveT3McpSummaryAction(
563 workEntryToolName(entry),
564 t3ToolSummaryCall(entry).input,
565 );
566 if (entry.toolSource && t3Action === null) {
567 sources.set(entry.toolSource.key, entry.toolSource);
568 continue;
569 }
570 const action = toolGroupAction(entry);
571 const key = t3Action ?? action;
572 const group = groups.get(key);
573 if (group) group.entries.push(entry);
574 else groups.set(key, { action, t3Action, entries: [entry] });
575 }
576 const summaries = [...groups].map(([action, group], index) => ({
577 index,
578 count: group.entries.length,
579 priority: summaryActionPriority(action),
580 ...(group.t3Action
581 ? summarizeT3ToolCalls(group.t3Action, group.entries.map(t3ToolSummaryCall))
582 : {
583 label: toolGroupActionLabel(
584 group.action,
585 toolGroupActionCount(group.action, group.entries),
586 ),
587 failedCount: group.entries.filter(workEntryDisplayIndicatesToolFailure).length,
588 }),
589 }));
590 const selected = [...summaries]
591 .sort((a, b) => a.priority - b.priority || a.index - b.index)
592 .slice(0, 2)
593 .sort((a, b) => a.index - b.index);
594 const labels = selected.map(({ label }) => label);
595 if (sources.size > 0) {
596 const sourceValues = [...sources.values()];
597 const sourceNames = [...new Set(sourceValues.map((source) => source.name))];
598 const formattedNames =
599 sourceNames.length < 2
600 ? sourceNames[0]!
601 : sourceNames.length === 2
602 ? sourceNames.join(" and ")
603 : `${sourceNames.slice(0, -1).join(", ")}, and ${sourceNames.at(-1)}`;
604 const allIntegrations = sourceValues.every((source) => source.kind === "integration");
605 labels.unshift(
606 `Used ${formattedNames}${allIntegrations ? ` ${sourceNames.length === 1 ? "integration" : "integrations"}` : ""}`,
607 );
608 }
609 const sourcedCount = entries.filter(
610 (entry) =>
611 entry.toolSource !== undefined &&
612 resolveT3McpToolDefinition(workEntryToolName(entry)) === null,
613 ).length;
614 const remainingCount =
615 entries.length - sourcedCount - selected.reduce((count, group) => count + group.count, 0);
616 if (remainingCount > 0) {
617 labels.push(`Performed ${remainingCount} other ${remainingCount === 1 ? "action" : "actions"}`);
618 }
619 const sentenceLabels = labels.map((label, index) =>
620 index === 0 ? label : label.charAt(0).toLowerCase() + label.slice(1),
621 );
622 const summary =
623 sentenceLabels.length < 3
624 ? sentenceLabels.join(" and ")
625 : `${sentenceLabels.slice(0, -1).join(", ")}, and ${sentenceLabels.at(-1)}`;
626 return { summary, hasFailure: summaries.some((group) => group.failedCount > 0) };
628​
629export function toolGroupSummaryKind(
630 entries: ReadonlyArray<WorkLogPresentationEntry>,
631): ToolGroupSummaryKind {
632 const toolEntries = entries.filter((entry) => entry.itemType !== "reasoning");
633 if (entries.length > 0 && toolEntries.length === 0) return "reasoning";
634 entries = toolEntries;
635 if (
636 entries.length > 0 &&
637 entries.every((entry) => resolveWorkEntryToolPresentation(entry)?.icon === "pull-request")
638 )
639 return "pull-request";
640 const actions = new Set(entries.map(toolGroupAction));
641 if (actions.size !== 1) return "mixed";
642 const action = actions.values().next().value!;
643 if (action !== "other") return action;
644 const fallbackKinds = new Set(
645 entries.map((entry): ToolGroupSummaryKind => {
646 if (entry.itemType === "dynamic_tool") return "dynamic-tool";
647 if (entry.itemType === "subagent") return "agent-tool";
648 if (entry.tone === "thinking") return "agent-tool";
649 if (entry.tone === "tool") return "tone-tool";
650 return "other";
651 }),
652 );
653 return fallbackKinds.size === 1 ? fallbackKinds.values().next().value! : "mixed";
655​
656export function liveThoughtLine(markdown: string): string {
657 const heading = /^\s*\*\*([^*\r\n]+)\*\*[ \t]*\r?(?:\n|$)/.exec(markdown)?.[1];
658 const text = (heading ?? markdown)
659 .replace(/!?\[([^\]]*)\]\([^)]*\)/g, "$1")
660 .replace(/^[ \t]*(?:#{1,6}|[-*+]|\d+\.)[ \t]+/gm, "")
661 .replace(/`+|\*\*|~~/g, "")
662 .replace(/(^|[^\w*])[*_]([^*_\n]+)[*_](?![\w*])/g, "$1$2")
663 .replace(/\s+/g, " ")
664 .trim();
665 if (heading !== undefined) return text;
666 const end = /[.?!]["'”’)]?(?=\s)/.exec(text);
667 return end ? text.slice(0, end.index + end[0].length) : text;