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

presentation.ts

645 lines22.2 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​
294export function workEntryIndicatesToolFailure(entry: WorkLogPresentationEntry): boolean {
295 return workEntryIndicatesToolFailureFromOutput(entry, true);
297​
298export function workEntryDisplayIndicatesToolFailure(entry: WorkLogPresentationEntry): boolean {
299 return workEntryIndicatesToolFailureFromOutput(entry, false);
301​
302function workLogEntryIsLocalCodeSearch(entry: WorkLogPresentationEntry): boolean {
303 return (
304 entry.itemType === "file_search" ||
305 (entry.itemType === "web_search" &&
306 /\bgrep\b/i.test(normalizeCompactToolLabel(entry.toolTitle ?? entry.label)))
307 );
309​
310export function toolGroupAction(entry: WorkLogPresentationEntry): ToolGroupAction {
311 if (entry.itemType === "thread_created") return "thread-create";
312 const presentation = resolveWorkEntryToolPresentation(entry);
313 if (presentation?.action !== undefined) return presentation.action;
314 if (presentation?.icon === "browser") return "browser";
315 if (presentation?.icon === "device") return "device";
316 if (entry.requestKind === "file-read" || entry.viewedImagePath !== undefined) return "read";
317 if (entry.itemType === "approval_request" || entry.itemType === "user_input_request") {
318 return workLogEntryIsToolLike(entry) ? "other" : "update";
319 }
320 const data = asRecord(entry.toolData) ?? {};
321 const toolName =
322 entry.structuredPayload?.type === "dynamic_tool"
323 ? entry.structuredPayload.toolName
324 : typeof data.toolName === "string"
325 ? data.toolName
326 : entry.toolTitle;
327 const classified = classifyToolActivity({
328 itemType:
329 entry.itemType === "command_execution" ||
330 entry.itemType === "file_change" ||
331 entry.itemType === "web_search"
332 ? entry.itemType
333 : entry.itemType === "dynamic_tool"
334 ? "dynamic_tool_call"
335 : undefined,
336 title: entry.toolTitle ?? entry.label,
337 data: {
338 ...data,
339 ...(toolName ? { toolName } : {}),
340 },
341 });
342 if (classified === "read") return "read";
343 if (classified === "file_change" || entry.itemType === "file_change") return "edit";
344 if (classified === "command" || entry.itemType === "command_execution" || entry.command) {
345 return "command";
346 }
347 if (classified === "search") {
348 return entry.itemType === "web_search" && !workLogEntryIsLocalCodeSearch(entry)
349 ? "search"
350 : "code-search";
351 }
352 if (workLogEntryIsLocalCodeSearch(entry)) return "code-search";
353 if (entry.itemType === "web_search") return "search";
354 if ((entry.changedFiles?.length ?? 0) > 0) return "edit";
355 return workLogEntryIsToolLike(entry) ? "other" : "update";
357​
358export function workEntryViewedImagePath(entry: WorkLogPresentationEntry): string | null {
359 const viewedImagePath = entry.viewedImagePath?.trim();
360 if (
361 viewedImagePath !== undefined &&
362 !/[\r\n]/.test(viewedImagePath) &&
363 isWorkspaceImagePreviewPath(viewedImagePath)
364 ) {
365 return viewedImagePath;
366 }
367 const detail = entry.detail?.trim();
368 return toolGroupAction(entry) === "read" &&
369 detail !== undefined &&
370 !/[\r\n]/.test(detail) &&
371 isWorkspaceImagePreviewPath(detail)
372 ? detail
373 : null;
375​
376export interface ViewedImageAsset {
377 readonly resource: Extract<AssetResource, { readonly _tag: "media-file" }>;
378 readonly alt: string;
379 readonly srcFragment: string;
381​
382export function resolveViewedImageAsset(
383 source: string,
384 input: {
385 readonly threadId: ThreadId;
386 readonly workspaceRoot?: string | null | undefined;
387 },
388): ViewedImageAsset | null {
389 const imageSource = classifyMarkdownImageSource(source, input.workspaceRoot ?? ".");
390 if (imageSource._tag !== "WorkspaceFile") return null;
391 const resolvedFilePath =
392 input.workspaceRoot == null && imageSource.path.startsWith("./")
393 ? imageSource.path.slice(2)
394 : imageSource.path;
395​
396 const media = resolveMediaSource(source, {
397 threadId: input.threadId,
398 workspaceRoot: input.workspaceRoot,
399 resolvedFilePath,
400 });
401 if (media === null || media.access !== "environment") return null;
402 return { resource: media.resource, alt: media.name, srcFragment: media.srcFragment };
404​
405function toolGroupActionCount(
406 action: ToolGroupAction,
407 entries: ReadonlyArray<WorkLogPresentationEntry>,
408): number {
409 if (action !== "edit") return entries.length;
410 const changedFiles = new Set<string>();
411 let editsWithoutFileDetails = 0;
412 for (const entry of entries) {
413 if (!entry.changedFiles || entry.changedFiles.length === 0) {
414 editsWithoutFileDetails += 1;
415 } else {
416 for (const file of entry.changedFiles) changedFiles.add(file);
417 }
418 }
419 return changedFiles.size + editsWithoutFileDetails;
421​
422function toolGroupActionLabel(action: ToolGroupAction, count: number): string {
423 switch (action) {
424 case "link-pr":
425 return `Linked ${count} ${count === 1 ? "pull request" : "pull requests"}`;
426 case "unlink-pr":
427 return `Unlinked ${count} ${count === 1 ? "pull request" : "pull requests"}`;
428 case "watch-pr":
429 return `Watching ${count} ${count === 1 ? "pull request" : "pull requests"}`;
430 case "unwatch-pr":
431 return `Stopped watching ${count} ${count === 1 ? "pull request" : "pull requests"}`;
432 case "list-prs":
433 return count === 1
434 ? "Checked linked pull requests"
435 : `Checked linked pull requests ${count} times`;
436 case "read":
437 return `Read ${count} ${count === 1 ? "file" : "files"}`;
438 case "edit":
439 return `Changed ${count} ${count === 1 ? "file" : "files"}`;
440 case "command":
441 return `Ran ${count} ${count === 1 ? "command" : "commands"}`;
442 case "thread-create":
443 return `Created ${count} ${count === 1 ? "thread" : "threads"}`;
444 case "device":
445 return `Used device controls ${count} ${count === 1 ? "time" : "times"}`;
446 case "browser":
447 return `Used browser ${count} ${count === 1 ? "time" : "times"}`;
448 case "search":
449 return `Searched the web ${count} ${count === 1 ? "time" : "times"}`;
450 case "code-search":
451 return `Searched code ${count} ${count === 1 ? "time" : "times"}`;
452 case "other":
453 return `Used ${count} ${count === 1 ? "tool" : "tools"}`;
454 case "update":
455 return `Received ${count} ${count === 1 ? "update" : "updates"}`;
456 }
458​
459function t3ToolSummaryCall(entry: WorkLogPresentationEntry): T3ToolSummaryCall {
460 return {
461 input: workEntryToolInput(entry),
462 output: workEntryToolOutput(entry),
463 outcome:
464 entry.toolLifecycleStatus === "failed" ||
465 entry.toolLifecycleStatus === "declined" ||
466 entry.tone === "error"
467 ? "failed"
468 : entry.toolLifecycleStatus === "completed"
469 ? "completed"
470 : "unfinished",
471 };
473​
474function summaryActionPriority(action: ToolGroupAction | T3McpToolSummaryAction): number {
475 switch (action) {
476 case "command":
477 case "edit":
478 case "delegate":
479 case "task-cancel":
480 case "thread-create":
481 case "thread-send":
482 case "thread-interrupt":
483 case "workflow-stop":
484 case "background-wait":
485 case "schedule-create":
486 case "schedule-update":
487 case "schedule-delete":
488 case "schedule-run":
489 case "thread-configure":
490 case "thread-fork":
491 case "thread-merge":
492 case "thread-organize":
493 case "thread-update":
494 case "queue-edit":
495 case "queue-cancel":
496 case "queue-reorder":
497 case "queue-steer":
498 case "question-respond":
499 case "worktree-handoff":
500 case "project-create":
501 case "project-update":
502 case "project-delete":
503 case "project-clone":
504 case "environment-update":
505 case "attachment-prepare":
506 case "attachment-discard":
507 case "attachment-send":
508 return 0;
509 case "other":
510 case "update":
511 return 2;
512 default:
513 return 1;
514 }
516​
517export function summarizeToolGroup(entries: ReadonlyArray<WorkLogPresentationEntry>): {
518 summary: string;
519 hasFailure: boolean;
520} {
521 const toolEntries = entries.filter((entry) => entry.itemType !== "reasoning");
522 if (entries.length > 0 && toolEntries.length === 0) {
523 return {
524 summary: entries.length === 1 ? "Thought" : `Thought (×${entries.length})`,
525 hasFailure: false,
526 };
527 }
528 entries = toolEntries;
529 const groups = new Map<
530 ToolGroupAction | T3McpToolSummaryAction,
531 {
532 action: ToolGroupAction;
533 t3Action: T3McpToolSummaryAction | null;
534 entries: WorkLogPresentationEntry[];
535 }
536 >();
537 const sources = new Map<string, ToolActivitySource>();
538 for (const entry of entries) {
539 const t3Action = resolveT3McpSummaryAction(
540 workEntryToolName(entry),
541 t3ToolSummaryCall(entry).input,
542 );
543 if (entry.toolSource && t3Action === null) {
544 sources.set(entry.toolSource.key, entry.toolSource);
545 continue;
546 }
547 const action = toolGroupAction(entry);
548 const key = t3Action ?? action;
549 const group = groups.get(key);
550 if (group) group.entries.push(entry);
551 else groups.set(key, { action, t3Action, entries: [entry] });
552 }
553 const summaries = [...groups].map(([action, group], index) => ({
554 index,
555 count: group.entries.length,
556 priority: summaryActionPriority(action),
557 ...(group.t3Action
558 ? summarizeT3ToolCalls(group.t3Action, group.entries.map(t3ToolSummaryCall))
559 : {
560 label: toolGroupActionLabel(
561 group.action,
562 toolGroupActionCount(group.action, group.entries),
563 ),
564 failedCount: group.entries.filter(workEntryDisplayIndicatesToolFailure).length,
565 }),
566 }));
567 const selected = [...summaries]
568 .sort((a, b) => a.priority - b.priority || a.index - b.index)
569 .slice(0, 2)
570 .sort((a, b) => a.index - b.index);
571 const labels = selected.map(({ label }) => label);
572 if (sources.size > 0) {
573 const sourceValues = [...sources.values()];
574 const sourceNames = [...new Set(sourceValues.map((source) => source.name))];
575 const formattedNames =
576 sourceNames.length < 2
577 ? sourceNames[0]!
578 : sourceNames.length === 2
579 ? sourceNames.join(" and ")
580 : `${sourceNames.slice(0, -1).join(", ")}, and ${sourceNames.at(-1)}`;
581 const allIntegrations = sourceValues.every((source) => source.kind === "integration");
582 labels.unshift(
583 `Used ${formattedNames}${allIntegrations ? ` ${sourceNames.length === 1 ? "integration" : "integrations"}` : ""}`,
584 );
585 }
586 const sourcedCount = entries.filter(
587 (entry) =>
588 entry.toolSource !== undefined &&
589 resolveT3McpToolDefinition(workEntryToolName(entry)) === null,
590 ).length;
591 const remainingCount =
592 entries.length - sourcedCount - selected.reduce((count, group) => count + group.count, 0);
593 if (remainingCount > 0) {
594 labels.push(`Performed ${remainingCount} other ${remainingCount === 1 ? "action" : "actions"}`);
595 }
596 const sentenceLabels = labels.map((label, index) =>
597 index === 0 ? label : label.charAt(0).toLowerCase() + label.slice(1),
598 );
599 const summary =
600 sentenceLabels.length < 3
601 ? sentenceLabels.join(" and ")
602 : `${sentenceLabels.slice(0, -1).join(", ")}, and ${sentenceLabels.at(-1)}`;
603 return { summary, hasFailure: summaries.some((group) => group.failedCount > 0) };
605​
606export function toolGroupSummaryKind(
607 entries: ReadonlyArray<WorkLogPresentationEntry>,
608): ToolGroupSummaryKind {
609 const toolEntries = entries.filter((entry) => entry.itemType !== "reasoning");
610 if (entries.length > 0 && toolEntries.length === 0) return "reasoning";
611 entries = toolEntries;
612 if (
613 entries.length > 0 &&
614 entries.every((entry) => resolveWorkEntryToolPresentation(entry)?.icon === "pull-request")
615 )
616 return "pull-request";
617 const actions = new Set(entries.map(toolGroupAction));
618 if (actions.size !== 1) return "mixed";
619 const action = actions.values().next().value!;
620 if (action !== "other") return action;
621 const fallbackKinds = new Set(
622 entries.map((entry): ToolGroupSummaryKind => {
623 if (entry.itemType === "dynamic_tool") return "dynamic-tool";
624 if (entry.itemType === "subagent") return "agent-tool";
625 if (entry.tone === "thinking") return "agent-tool";
626 if (entry.tone === "tool") return "tone-tool";
627 return "other";
628 }),
629 );
630 return fallbackKinds.size === 1 ? fallbackKinds.values().next().value! : "mixed";
632​
633export function liveThoughtLine(markdown: string): string {
634 const heading = /^\s*\*\*([^*\r\n]+)\*\*[ \t]*\r?(?:\n|$)/.exec(markdown)?.[1];
635 const text = (heading ?? markdown)
636 .replace(/!?\[([^\]]*)\]\([^)]*\)/g, "$1")
637 .replace(/^[ \t]*(?:#{1,6}|[-*+]|\d+\.)[ \t]+/gm, "")
638 .replace(/`+|\*\*|~~/g, "")
639 .replace(/(^|[^\w*])[*_]([^*_\n]+)[*_](?![\w*])/g, "$1$2")
640 .replace(/\s+/g, " ")
641 .trim();
642 if (heading !== undefined) return text;
643 const end = /[.?!]["'”’)]?(?=\s)/.exec(text);
644 return end ? text.slice(0, end.index + end[0].length) : text;