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

threadFindText.ts

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