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