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

threadFindText.ts

194 lines6.7 KB

1import {
2 matchInlineSkills,
3 formatProviderSkillDisplayName,
4 type InlineSkill,
5} from "./inlineSkills.ts";
6import {
7 artifactTemplateFromHastProperties,
8 renderCodexInlineDirectivesAsMarkdown,
9} from "./codexMarkdownDirectives.ts";
10import { codexArtifactTemplatePresentationLabel } from "./codexArtifactTemplates.ts";
11import {
12 buildFileLinkParentSuffixByPath,
13 splitFilePathPosition,
14 fileLinkLabel,
15} from "./fileLinks.ts";
16import {
17 isMarkdownFileLinkLabel,
18 extractMarkdownLinkHrefs,
19 extractInlineCodeSpans,
20 inlineCodeFilePathCandidate,
21 resolveMarkdownFileLinkTarget,
22} from "./markdownLinks.ts";
23import { upgradeLegacyContextMessage } from "./composerContextLegacy.ts";
24import { parseComposerContextHref } from "./composerContextReferences.ts";
25import { assistantCitationLabel, parseAssistantCitationHref } from "./assistantCitations.ts";
26import type { OrchestrationV2ConversationMessage } from "@t3tools/contracts";
27import { proposedPlanTitle, stripDisplayedPlanMarkdown } from "./proposedPlanText.ts";
28import { unified } from "unified";
29import remarkParse from "remark-parse";
30import remarkRehype from "remark-rehype";
31import rehypeRaw from "rehype-raw";
32import {
33 shouldPreserveAssistantLineBreaks,
34 chatMarkdownRehypePlugins,
35 CHAT_MARKDOWN_REMARK_PLUGINS,
36 CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS,
37} from "./markdownPipeline.ts";
38import { THREAD_FIND_BLOCK_TAGS } from "./threadFindBlockTags.ts";
39​
40const CHAT_MARKDOWN_REHYPE_PLUGINS = chatMarkdownRehypePlugins(rehypeRaw);
41​
42const assistantProcessor = unified()
43 .use(remarkParse)
44 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
45 .use(remarkRehype, { allowDangerousHtml: true })
46 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
47const assistantBreaksProcessor = unified()
48 .use(remarkParse)
49 .use(CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS)
50 .use(remarkRehype, { allowDangerousHtml: true })
51 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
52const userProcessor = unified()
53 .use(remarkParse)
54 .use(CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS)
55 .use(remarkRehype, { allowDangerousHtml: true });
56​
57interface TextTree {
58 readonly type: string;
59 readonly tagName?: string;
60 readonly value?: string;
61 readonly properties?: {
62 readonly href?: unknown;
63 readonly src?: unknown;
64 readonly dataInlineCode?: unknown;
65 };
66 readonly children?: ReadonlyArray<TextTree>;
68​
69function markdownThreadFindText(
70 markdown: string,
71 userMessage = false,
72 cwd?: string,
73 skills: readonly InlineSkill[] = [],
74 lineBreaks = false,
75): string[] {
76 const processor = userMessage
77 ? userProcessor
78 : lineBreaks
79 ? assistantBreaksProcessor
80 : assistantProcessor;
81 const tree = processor.runSync(processor.parse(markdown));
82 const paths = [
83 ...extractMarkdownLinkHrefs(renderCodexInlineDirectivesAsMarkdown(markdown)),
84 ...extractInlineCodeSpans(markdown).flatMap((span) => inlineCodeFilePathCandidate(span) ?? []),
85 ].flatMap((href) => {
86 const target = resolveMarkdownFileLinkTarget(href, cwd);
87 return target ? [splitFilePathPosition(target).path] : [];
88 });
89 const parentSuffixes = buildFileLinkParentSuffixByPath(paths);
90 const segments: string[] = [];
91 let text = "";
92 const flush = () => {
93 if (text.trim()) segments.push(text);
94 text = "";
95 };
96 const visit = (node: TextTree, inPre = false, inlineSkills = false) => {
97 const href = node.properties?.href ?? node.properties?.src;
98 if (userMessage && typeof href === "string" && parseComposerContextHref(href)) {
99 flush();
100 return;
101 }
102 const citation =
103 node.tagName === "a" && typeof href === "string" ? parseAssistantCitationHref(href) : null;
104 if (citation) {
105 text += assistantCitationLabel(citation);
106 return;
107 }
108 {
109 let candidate: string | null = null;
110 if (node.tagName === "a" && typeof href === "string") {
111 candidate = href;
112 } else if (
113 node.tagName === "code" &&
114 !inPre &&
115 node.properties?.dataInlineCode !== undefined
116 ) {
117 candidate = inlineCodeFilePathCandidate(
118 (node.children ?? []).map((child) => child.value ?? "").join(""),
119 );
120 }
121 const target = candidate ? resolveMarkdownFileLinkTarget(candidate, cwd) : null;
122 if (target) {
123 const labelText = (node: TextTree): string =>
124 node.value ?? (node.children ?? []).map(labelText).join("");
125 const label = labelText(node);
126 if (node.tagName === "a" && candidate && !isMarkdownFileLinkLabel(label, candidate))
127 text += `${label} `;
128 text += fileLinkLabel(splitFilePathPosition(target), parentSuffixes);
129 return;
130 }
131 }
132 const template = artifactTemplateFromHastProperties(node.properties);
133 if (template) {
134 flush();
135 segments.push(
136 template.displayName,
137 codexArtifactTemplatePresentationLabel(template.artifactKind),
138 );
139 return;
140 }
141 const block = THREAD_FIND_BLOCK_TAGS.has(node.tagName ?? "");
142 if (block) flush();
143 if (node.type === "text" || (userMessage && node.type === "raw")) {
144 let value = node.value ?? "";
145 if (inlineSkills) {
146 let cursor = 0;
147 let rendered = "";
148 for (const { start, end, skill } of matchInlineSkills(value, skills)) {
149 rendered += value.slice(cursor, start) + formatProviderSkillDisplayName(skill);
150 cursor = end;
151 }
152 value = rendered + value.slice(cursor);
153 }
154 text += inPre ? value : value.replace(/\r?\n/g, " ");
155 }
156 const renderSkills =
157 node.tagName === "code" || node.tagName === "a"
158 ? false
159 : inlineSkills || node.tagName === "p" || node.tagName === "li";
160 for (const child of node.children ?? [])
161 visit(child, inPre || node.tagName === "pre", renderSkills);
162 if (block) flush();
163 };
164 visit(tree);
165 flush();
166 return segments;
168​
169/** Plans render `$skill` tokens literally (no skill chips), so they are indexed as written. */
170export function searchablePlanSegments(markdown: string, cwd?: string): readonly string[] {
171 return [
172 proposedPlanTitle(markdown) ?? "Proposed plan",
173 ...markdownThreadFindText(stripDisplayedPlanMarkdown(markdown), false, cwd, []),
174 ];
176​
177export function searchableMessageSegments(
178 message: Pick<OrchestrationV2ConversationMessage, "role" | "text" | "streaming" | "context">,
179 cwd?: string,
180 skills: readonly InlineSkill[] = [],
181): readonly string[] | null {
182 if (message.role === "user") {
183 const text = message.context ? message.text : upgradeLegacyContextMessage(message.text).text;
184 return markdownThreadFindText(text, true, cwd, skills);
185 }
186 if (message.role !== "assistant") return null;
187 return markdownThreadFindText(
188 message.text || (message.streaming ? "" : "(empty response)"),
189 false,
190 cwd,
191 skills,
192 shouldPreserveAssistantLineBreaks(message.text),
193 );