Open History to see the last commit
1import type { ComposerContextRecord, EnvironmentId, ThreadId } from "@t3tools/contracts";
2import {
3 composerChipSizeSuffix,
4 contextChipIcon,
5 contextChipPresentation,
6 contextRecordFileName,
7 type ContextChipIconRef,
8 UNAVAILABLE_CONTEXT_CHIP_PRESENTATION,
9} from "./composerChipPresentation";
10import type { MessageResolver } from "../i18n/messages";
11import { formatComposerModelMention } from "@t3tools/client-runtime/composer-model-mentions";
12import type {
13 SelectableMarkdownModel,
14 SelectableMarkdownSkill,
15} from "../native/SelectableMarkdownText.types";
16import {
17 formatComposerContextHref,
18 parseComposerContextHref,
19} from "@t3tools/shared/composerContextReferences";
20import { hasThreadLinks, parseThreadLinkHref } from "@t3tools/shared/threadLinks";
21import { EXTENSIONLESS_FILE_NAMES } from "@t3tools/shared/markdownLinks";
22
23export function enrichedContextLinkPresentation(
24 href: string,
25 records?: ReadonlyArray<ComposerContextRecord>,
26 resolve?: MessageResolver,
27 locale?: string,
28): { accent?: string; icon: ContextChipIconRef; label?: string } | undefined {
29 const reference = parseComposerContextHref(href);
30 if (!reference) return undefined;
31 const record = records?.find((candidate) => candidate.contextId === reference.contextId);
32 const presentation =
33 records && !record
34 ? UNAVAILABLE_CONTEXT_CHIP_PRESENTATION
35 : contextChipPresentation(reference.kind, record);
36 const size = composerChipSizeSuffix(record, resolve, locale);
37 return {
38 ...(presentation.accent ? { accent: presentation.accent } : {}),
39 icon: contextChipIcon(presentation, contextRecordFileName(record)),
40 ...(record && size ? { label: `${record.label} · ${size}` } : {}),
41 };
42}
43
44export function enrichedThreadLinkPresentation(
45 href: string,
46): { accent?: string; icon: ContextChipIconRef } | undefined {
47 if (!parseThreadLinkHref(href)) return undefined;
48 const presentation = contextChipPresentation("thread");
49 return {
50 ...(presentation.accent ? { accent: presentation.accent } : {}),
51 icon: contextChipIcon(presentation, ""),
52 };
53}
54
55export interface ThreadChipTarget {
56 readonly href: string;
57 readonly environmentId: EnvironmentId;
58 readonly threadId: ThreadId;
59 readonly link: boolean;
60}
61
62export function threadChipTargets(
63 environmentId: EnvironmentId,
64 markdown: string,
65 records?: ReadonlyArray<ComposerContextRecord>,
66): ReadonlyArray<ThreadChipTarget> {
67 const targets = new Map<string, ThreadChipTarget>();
68 if (hasThreadLinks(markdown)) {
69 for (const [, href = ""] of markdown.matchAll(/\]\(<?(t3-thread:\/\/v[12]\/[^\s>)]+)>?\)/g)) {
70 const link = parseThreadLinkHref(href);
71 if (link) {
72 targets.set(href, {
73 href,
74 environmentId: link.environmentId ?? environmentId,
75 threadId: link.threadId,
76 link: true,
77 });
78 }
79 }
80 }
81 for (const record of records ?? []) {
82 if (record.kind !== "thread" || !("threadId" in record)) continue;
83 const href = formatComposerContextHref("thread", record.contextId);
84 targets.set(href, {
85 href,
86 environmentId: record.environmentId,
87 threadId: record.threadId,
88 link: false,
89 });
90 }
91 return [...targets.values()];
92}
93
94export function enrichedLinkVariantPattern(url: string) {
95 return `^${url.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}$`;
96}
97
98const EXTENSIONLESS_FILE_NAME_PATTERN = [...EXTENSIONLESS_FILE_NAMES]
99 .map((name) => name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))
100 .join("|");
101
102const INLINE_FILE_POSITION_PATTERN = String.raw`(?::\d+(?::\d+|-\d+)?|#[Ll]\d+(?:[Cc]\d+|-[Ll]?\d+)?)`;
103
104// Folder and file names take the shared parser's routing punctuation (`(group)/[id]/+page.svelte`).
105export const ENRICHED_INLINE_FILE_LINK_REGEX = new RegExp(
106 String.raw`^(?!\S*:\/\/)(?:(?:\.{1,2}[\\/]|~[\\/]|\/(?:Users|home|tmp|var|etc|opt|mnt|Volumes|private|root|usr|bin|sbin|lib|lib64|srv|dev|proc|sys|run|boot|media|workspace|workspaces)\/|[A-Za-z]:[\\/])[^\s\x60]+|(?:[\p{L}\p{M}\p{N}._$+@()[\]-]+[\\/])+(?:[\p{L}\p{M}\p{N}._$+@()[\]-]+\.[A-Za-z0-9_-]+|(?:${EXTENSIONLESS_FILE_NAME_PATTERN}))${INLINE_FILE_POSITION_PATTERN}?|[\p{L}\p{M}\p{N}._$+()[\]-]+\.[A-Za-z0-9_-]+${INLINE_FILE_POSITION_PATTERN})$`,
107 "u",
108);
109
110export function enrichedSkillLinkRegex(skills?: ReadonlyArray<SelectableMarkdownSkill>) {
111 const names = [...new Set(skills?.map((skill) => skill.name) ?? [])].filter(Boolean);
112 if (names.length === 0) return null;
113 names.sort((a, b) => b.length - a.length);
114 const alternatives = names.map((name) => name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
115 return new RegExp(
116 `(?<![A-Za-z0-9_-])(?<!\\p{Sc})\\p{Sc}(?:${alternatives.join("|")})(?![A-Za-z0-9_-])`,
117 "u",
118 );
119}
120
121export function enrichedSkillReference(
122 url: string,
123 skills?: ReadonlyArray<SelectableMarkdownSkill>,
124) {
125 const match = /^\p{Sc}(.+)$/u.exec(url);
126 return match ? skills?.find((skill) => skill.name === match[1]) : undefined;
127}
128
129export function enrichedSkillInstructionsPath(skill: SelectableMarkdownSkill) {
130 return skill.path && !/^[a-z][a-z\d+.-]*:\/\//i.test(skill.path) ? skill.path : undefined;
131}
132
133export function buildEnrichedModelReferences(
134 providers: ReadonlyArray<{
135 readonly instanceId: string;
136 readonly driver: string;
137 readonly displayName?: string | undefined;
138 readonly iconUrl?: string | undefined;
139 readonly models: ReadonlyArray<{
140 readonly slug: string;
141 readonly name: string;
142 readonly subProvider?: string | undefined;
143 }>;
144 }>,
145 sources?: ReadonlySet<string>,
146): ReadonlyArray<SelectableMarkdownModel> {
147 return providers.flatMap((provider) =>
148 provider.models
149 .filter(
150 (model) =>
151 !sources || sources.has(formatComposerModelMention(provider.instanceId, model.slug)),
152 )
153 .map((model) => {
154 const qualifier = model.subProvider?.trim();
155 const label = qualifier
156 ? model.name
157 .replace(
158 new RegExp(
159 `^${qualifier.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:\\s*[.:/-]\\s*|\\s+)`,
160 "iu",
161 ),
162 "",
163 )
164 .trim() || model.name
165 : model.name;
166 return {
167 source: formatComposerModelMention(provider.instanceId, model.slug),
168 label,
169 providerLabel: qualifier || provider.displayName || provider.instanceId,
170 driver: provider.driver,
171 iconUrl: provider.iconUrl,
172 };
173 }),
174 );
175}
176
177export function enrichedModelLinkRegex(models?: ReadonlyArray<SelectableMarkdownModel>) {
178 if (!models?.length) return null;
179 const alternatives = models
180 .map((model) => model.source)
181 .sort((a, b) => b.length - a.length)
182 .map((source) => source.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
183 // LRM and RLM can open a paragraph whose first word runs against the text direction.
184 return new RegExp(
185 `(?<![^\\s,(\\["'\\u200E\\u200F])(?:${alternatives.join("|")})(?=$|[\\s,"']|[.;:!?\\)\\]]+(?=$|[\\s,"']))`,
186 "u",
187 );
188}
189
190export function enrichedModelReference(
191 source: string,
192 models?: ReadonlyArray<SelectableMarkdownModel>,
193) {
194 return models?.find((model) => model.source === source);
195}
196
197export function enrichedModelDetails(model: SelectableMarkdownModel) {
198 return `${model.providerLabel}\n${model.source}`;
199}
200
201export function enrichedTextLinkRegex(
202 skills?: ReadonlyArray<SelectableMarkdownSkill>,
203 models?: ReadonlyArray<SelectableMarkdownModel>,
204) {
205 const patterns = [enrichedSkillLinkRegex(skills), enrichedModelLinkRegex(models)]
206 .filter((pattern) => pattern !== null)
207 .map((pattern) => `(?:${pattern.source})`);
208 return patterns.length ? new RegExp(patterns.join("|"), "u") : null;
209}