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

threadFindText.ts

252 lines7.8 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 {
25 isAttachmentOnlyBootstrapPrompt,
26 parseComposerContextHref,
27} from "./composerContextReferences.ts";
28import { parseAssistantCitationHref } from "./assistantCitations.ts";
29import type { OrchestrationV2ConversationMessage } from "@t3tools/contracts";
30import { proposedPlanTitle, stripDisplayedPlanMarkdown } from "./proposedPlanText.ts";
31import { unified } from "unified";
32import remarkParse from "remark-parse";
33import remarkRehype from "remark-rehype";
34import {
35 shouldPreserveAssistantLineBreaks,
36 remarkAssistantInsights,
37 CHAT_MARKDOWN_REHYPE_PLUGINS,
38 CHAT_MARKDOWN_REMARK_PLUGINS,
39 CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS,
40 CHAT_USER_MARKDOWN_REMARK_PLUGINS,
41 decodeMarkdownLinkEscapes,
42} from "./markdownPipeline.ts";
43​
44// Inline wrappers (including Shiki token spans) must not split a search phrase.
45export const THREAD_FIND_BLOCK_TAGS = new Set([
46 "address",
47 "article",
48 "aside",
49 "blockquote",
50 "br",
51 "dd",
52 "details",
53 "div",
54 "dl",
55 "dt",
56 "figcaption",
57 "figure",
58 "footer",
59 "h1",
60 "h2",
61 "h3",
62 "h4",
63 "h5",
64 "h6",
65 "header",
66 "hr",
67 "li",
68 "main",
69 "nav",
70 "ol",
71 "p",
72 "pre",
73 "section",
74 "summary",
75 "table",
76 "tbody",
77 "td",
78 "th",
79 "thead",
80 "tr",
81 "ul",
82]);
83​
84function assistantTextProcessor(lineBreaks = false, renderInsights = false) {
85 return unified()
86 .use(remarkParse)
87 .use(renderInsights ? [remarkAssistantInsights] : [])
88 .use(lineBreaks ? CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS : CHAT_MARKDOWN_REMARK_PLUGINS)
89 .use(remarkRehype, { allowDangerousHtml: true })
90 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
92const assistantProcessor = assistantTextProcessor();
93const assistantBreaksProcessor = assistantTextProcessor(true);
94const insightProcessor = assistantTextProcessor(false, true);
95const insightBreaksProcessor = assistantTextProcessor(true, true);
96const userProcessor = unified()
97 .use(remarkParse)
98 .use(CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS)
99 .use(CHAT_USER_MARKDOWN_REMARK_PLUGINS)
100 .use(remarkRehype, { allowDangerousHtml: true });
101​
102interface TextTree {
103 readonly type: string;
104 readonly tagName?: string;
105 readonly value?: string;
106 readonly properties?: {
107 readonly href?: unknown;
108 readonly src?: unknown;
109 readonly dataInlineCode?: unknown;
110 };
111 readonly children?: ReadonlyArray<TextTree>;
113​
114function markdownThreadFindText(
115 markdown: string,
116 userMessage = false,
117 cwd?: string,
118 skills: readonly InlineSkill[] = [],
119 lineBreaks = false,
120 renderInsights = false,
121): string[] {
122 const processor = userMessage
123 ? userProcessor
124 : lineBreaks
125 ? assistantBreaksProcessor
126 : assistantProcessor;
127 const renderer = renderInsights
128 ? lineBreaks
129 ? insightBreaksProcessor
130 : insightProcessor
131 : processor;
132 const tree = renderer.runSync(renderer.parse(markdown), markdown);
133 const paths = [
134 ...extractMarkdownLinkHrefs(renderCodexInlineDirectivesAsMarkdown(markdown)).map(
135 decodeMarkdownLinkEscapes,
136 ),
137 ...extractInlineCodeSpans(markdown).flatMap((span) => inlineCodeFilePathCandidate(span) ?? []),
138 ].flatMap((href) => {
139 const target = resolveMarkdownFileLinkTarget(href, cwd);
140 return target ? [splitFilePathPosition(target).path] : [];
141 });
142 const parentSuffixes = buildFileLinkParentSuffixByPath(paths);
143 const segments: string[] = [];
144 let text = "";
145 const flush = () => {
146 if (text.trim()) segments.push(text);
147 text = "";
148 };
149 const visit = (node: TextTree, inPre = false, inlineSkills = false) => {
150 const href = node.properties?.href ?? node.properties?.src;
151 if (userMessage && typeof href === "string" && parseComposerContextHref(href)) {
152 flush();
153 return;
154 }
155 const citation =
156 node.tagName === "a" && typeof href === "string" ? parseAssistantCitationHref(href) : null;
157 if (citation) {
158 // The quote card is not searched, and it splits the text before it from its comment.
159 flush();
160 text += (citation.comment ?? "").replace(/\r?\n/g, " ");
161 return;
162 }
163 {
164 let candidate: string | null = null;
165 if (node.tagName === "a" && typeof href === "string") {
166 candidate = href;
167 } else if (
168 node.tagName === "code" &&
169 !inPre &&
170 node.properties?.dataInlineCode !== undefined
171 ) {
172 candidate = inlineCodeFilePathCandidate(
173 (node.children ?? []).map((child) => child.value ?? "").join(""),
174 );
175 }
176 const target = candidate ? resolveMarkdownFileLinkTarget(candidate, cwd) : null;
177 if (target) {
178 const labelText = (node: TextTree): string =>
179 node.value ?? (node.children ?? []).map(labelText).join("");
180 const label = labelText(node);
181 if (node.tagName === "a" && candidate && !isMarkdownFileLinkLabel(label, candidate))
182 text += `${label} `;
183 text += fileLinkLabel(splitFilePathPosition(target), parentSuffixes);
184 return;
185 }
186 }
187 const template = artifactTemplateFromHastProperties(node.properties);
188 if (template) {
189 flush();
190 segments.push(
191 template.displayName,
192 codexArtifactTemplatePresentationLabel(template.artifactKind),
193 );
194 return;
195 }
196 const block = THREAD_FIND_BLOCK_TAGS.has(node.tagName ?? "");
197 if (block) flush();
198 if (node.type === "text" || (userMessage && node.type === "raw")) {
199 let value = node.value ?? "";
200 if (inlineSkills) {
201 let cursor = 0;
202 let rendered = "";
203 for (const { start, end, skill } of matchInlineSkills(value, skills)) {
204 rendered += value.slice(cursor, start) + formatProviderSkillDisplayName(skill);
205 cursor = end;
206 }
207 value = rendered + value.slice(cursor);
208 }
209 text += inPre ? value : value.replace(/\r?\n/g, " ");
210 }
211 const renderSkills =
212 node.tagName === "code" || node.tagName === "a"
213 ? false
214 : inlineSkills || node.tagName === "p" || node.tagName === "li";
215 for (const child of node.children ?? [])
216 visit(child, inPre || node.tagName === "pre", renderSkills);
217 if (block) flush();
218 };
219 visit(tree);
220 flush();
221 return segments;
223​
224/** Plans render `$skill` tokens literally (no skill chips), so they are indexed as written. */
225export function searchablePlanSegments(markdown: string, cwd?: string): readonly string[] {
226 return [
227 proposedPlanTitle(markdown) ?? "Proposed plan",
228 ...markdownThreadFindText(stripDisplayedPlanMarkdown(markdown), false, cwd, []),
229 ];
231​
232export function searchableMessageSegments(
233 message: Pick<OrchestrationV2ConversationMessage, "role" | "text" | "streaming" | "context">,
234 cwd?: string,
235 skills: readonly InlineSkill[] = [],
236): readonly string[] | null {
237 if (message.role === "user") {
238 // Clients hide this prompt, so find must not match text nobody can see.
239 if (isAttachmentOnlyBootstrapPrompt(message.text)) return [];
240 const text = message.context ? message.text : upgradeLegacyContextMessage(message.text).text;
241 return markdownThreadFindText(text, true, cwd, skills);
242 }
243 if (message.role !== "assistant") return null;
244 return markdownThreadFindText(
245 message.text || (message.streaming ? "" : "(empty response)"),
246 false,
247 cwd,
248 skills,
249 shouldPreserveAssistantLineBreaks(message.text),
250 true,
251 );