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