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