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

composerTrigger.ts

182 lines6.1 KB

1import { parseMarkdownFileLink } from "./markdownLinks.ts";
2​
3export type ComposerTriggerKind = "path" | "pull-request" | "slash-command" | "skill";
4export type ComposerSlashCommand = "model" | "plan" | "default";
5​
6export interface ComposerTrigger {
7 kind: ComposerTriggerKind;
8 query: string;
9 rangeStart: number;
10 rangeEnd: number;
12​
13function composerFileLinkBasename(path: string): string {
14 const separatorIndex = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
15 return separatorIndex >= 0 ? path.slice(separatorIndex + 1) : path;
17​
18// Emphasis markers too: `__init__.py` would otherwise render as bold "init.py",
19// which no longer matches the path, so the label shows beside the chip.
20function escapeMarkdownLinkLabel(label: string): string {
21 return label.replace(/[\\[\]*_&]/g, "\\$&");
23​
24function encodeMarkdownLinkDestination(path: string): string {
25 return encodeURI(path)
26 .replaceAll("(", "%28")
27 .replaceAll(")", "%29")
28 .replaceAll("&", "%26")
29 .replaceAll("#", "%23")
30 .replaceAll("?", "%3F")
31 .replaceAll("\\", "%5C");
33​
34const URI_OR_ROOTED_PATH_PATTERN = /^(?:[a-z][a-z\d+.-]*:|[\\/])/i;
35​
36// A relative destination the parser rejects (`C%23/Program.cs`) gets `./`, as codexFileCitations does.
37function needsDotSlashPrefix(path: string): boolean {
38 return (
39 path.length > 0 &&
40 !parseMarkdownFileLink(encodeMarkdownLinkDestination(path)) &&
41 !URI_OR_ROOTED_PATH_PATTERN.test(path)
42 );
44​
45export function serializeComposerFileLink(path: string): string {
46 const label = escapeMarkdownLinkLabel(composerFileLinkBasename(path));
47 const destination = encodeMarkdownLinkDestination(path);
48 return `[${label}](${needsDotSlashPrefix(path) ? `./${destination}` : destination})`;
50​
51/** The file a composer link names. Drops only the `./` serializeComposerFileLink adds, not one the author wrote. */
52export function composerFileLinkPath(encodedDestination: string, decodedPath: string): string {
53 if (!encodedDestination.startsWith("./")) return decodedPath;
54 const bare = decodedPath.slice(2);
55 return needsDotSlashPrefix(bare) &&
56 encodeMarkdownLinkDestination(bare) === encodedDestination.slice(2)
57 ? bare
58 : decodedPath;
60​
61function clampCursor(text: string, cursor: number): number {
62 if (!Number.isFinite(cursor)) return text.length;
63 return Math.max(0, Math.min(text.length, Math.floor(cursor)));
65​
66function isWhitespace(char: string): boolean {
67 return char === " " || char === "\n" || char === "\t" || char === "\r";
69​
70/** A second slash or backslash makes the whole word a path, even when the caret precedes it. */
71export function isPathWord(
72 text: string,
73 wordStart: number,
74 cursor: number,
75 isWhitespaceChar: (char: string) => boolean,
76): boolean {
77 let wordEnd = cursor;
78 while (wordEnd < text.length && !isWhitespaceChar(text[wordEnd] ?? "")) {
79 wordEnd += 1;
80 }
81 return /[/\\]/.test(text.slice(wordStart + 1, wordEnd));
83​
84/**
85 * `$5`, `€9.99` and `$10k` are money, not skills. Matches the amounts the inline skill
86 * token regexes already refuse to render as skills, plus the punctuation prose puts after
87 * one (`$10k.`, `($5)`).
88 */
89export function isCurrencyAmountQuery(query: string): boolean {
90 return /^\.?[0-9][0-9,._]*(?:[kKmMbBtT]|[eE][0-9]+)?[.,;:!?)]*$/.test(query);
92​
93export function detectComposerPullRequestTrigger(token: string, cursor: number) {
94 if (/^[@\p{Sc}]/u.test(token)) return null;
95 const match = /(?:^|\p{Ps})#([\p{L}\p{N}][\p{L}\p{N}_-]*)?$/u.exec(token);
96 if (!match) return null;
97 const query = match[1] ?? "";
98 return {
99 kind: "pull-request" as const,
100 query,
101 rangeStart: cursor - query.length - 1,
102 rangeEnd: cursor,
103 };
105​
106export function detectComposerTrigger(
107 text: string,
108 cursorInput: number,
109 isWhitespaceChar?: (char: string) => boolean,
110): ComposerTrigger | null {
111 const cursor = clampCursor(text, cursorInput);
112 const wsCheck = isWhitespaceChar ?? isWhitespace;
113 let tokenIdx = cursor - 1;
114 while (tokenIdx >= 0 && !wsCheck(text[tokenIdx] ?? "")) {
115 tokenIdx -= 1;
116 }
117 const tokenStart = tokenIdx + 1;
118​
119 const token = text.slice(tokenStart, cursor);
120 if (token.startsWith("/")) {
121 if (isPathWord(text, tokenStart, cursor, wsCheck)) return null;
122 return {
123 kind: "slash-command",
124 query: token.slice(1),
125 rangeStart: tokenStart,
126 rangeEnd: cursor,
127 };
128 }
129 const pullRequestTrigger = detectComposerPullRequestTrigger(token, cursor);
130 if (pullRequestTrigger) return pullRequestTrigger;
131 const skillPrefix = /^\p{Sc}/u.exec(token);
132 if (skillPrefix) {
133 if (isCurrencyAmountQuery(token.slice(skillPrefix[0].length))) return null;
134 return {
135 kind: "skill",
136 query: token.slice(skillPrefix[0].length),
137 rangeStart: tokenStart,
138 rangeEnd: cursor,
139 };
140 }
141 if (!token.startsWith("@")) {
142 return null;
143 }
144​
145 return {
146 kind: "path",
147 query: token.slice(1),
148 rangeStart: tokenStart,
149 rangeEnd: cursor,
150 };
152​
153export function replaceTextRange(
154 text: string,
155 rangeStart: number,
156 rangeEnd: number,
157 replacement: string,
158): { text: string; cursor: number } {
159 const safeStart = Math.max(0, Math.min(text.length, rangeStart));
160 const safeEnd = Math.max(safeStart, Math.min(text.length, rangeEnd));
161 const nextText = `${text.slice(0, safeStart)}${replacement}${text.slice(safeEnd)}`;
162 return { text: nextText, cursor: safeStart + replacement.length };
164​
165/** A message that only invokes a slash command, such as `/context all`, not a path like `/src/a.ts`. */
166export function isSlashCommand(message: {
167 readonly text: string;
168 readonly attachments: ReadonlyArray<unknown>;
169}): boolean {
170 return message.attachments.length === 0 && /^\/[\w:-]+(?:\s|$)/u.test(message.text.trim());
172​
173/** `/clear` as the whole message arms a fresh session instead of sending. */
174export function isClearComposerCommand(text: string): boolean {
175 return /^\/clear\s*$/i.test(text.trim());
177​
178/** `/side [prompt]`, or its alias `/btw [prompt]`, as the whole message. */
179export function parseSideChatCommand(text: string): { prompt: string } | null {
180 const match = /^\/(?:side|btw)(?:\s+([\s\S]*))?$/i.exec(text.trim());
181 return match ? { prompt: match[1]?.trim() ?? "" } : null;