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

promptLinks.ts

242 lines8.9 KB

1import { DEFAULT_HOSTED_APP_URL } from "./connectAuth.ts";
2import { parseUrl } from "./url.ts";
3​
4export const PROMPT_LINK_MAX_PROMPT_LENGTH = 8_000;
5​
6export interface PromptLinkRepository {
7 readonly owner: string;
8 readonly name: string;
9}
10​
11export interface PromptLinkPullRequest extends PromptLinkRepository {
12 readonly number: number;
14​
15export interface LinkedPrompt {
16 readonly text: string;
17 readonly hiddenCharacters: number;
19​
20export type NewThreadLink =
21 | {
22 readonly kind: "new";
23 readonly prompt: LinkedPrompt;
24 readonly repository: PromptLinkRepository | null;
25 readonly provider: string | null;
26 readonly model: string | null;
27 }
28 | {
29 readonly kind: "pull-request";
30 readonly pullRequest: PromptLinkPullRequest;
31 readonly prompt: LinkedPrompt | null;
32 };
33​
34export type PromptLinkResult<T> =
35 | { readonly ok: true; readonly value: T }
36 | { readonly ok: false; readonly error: string };
37​
38// Hidden characters let models read instructions invisible to the person reviewing the prompt.
39const HIDDEN_CHARACTERS =
40 // oxlint-disable-next-line no-misleading-character-class -- these are the characters it removes.
41 /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F\u00AD\u034F\u061C\u115F\u1160\u17B4\u17B5\u180B-\u180F\u200B\u200C\u200E\u200F\u202A-\u202E\u2060-\u206F\u3164\uFE00-\uFE0D\uFEFF\uFFA0\uFFF0-\uFFFB\u{1BCA0}-\u{1BCA3}\u{1D173}-\u{1D17A}\u{E0000}-\u{E0FFF}]/gu;
42// Numeric emoji ranges because Hermes lacks Unicode property escapes.
43const isEmojiPart = (codePoint: number | undefined) =>
44 codePoint !== undefined &&
45 ((codePoint >= 0x1f000 && codePoint <= 0x1faff) ||
46 (codePoint >= 0x2190 && codePoint <= 0x2bff) ||
47 codePoint === 0xfe0f);
48​
49export function sanitizeLinkedPrompt(raw: string): LinkedPrompt {
50 let hiddenCharacters = 0;
51 const visible = Array.from(
52 raw.replace(/\r\n?|[\u2028\u2029]/g, "\n").replace(HIDDEN_CHARACTERS, () => {
53 hiddenCharacters++;
54 return "";
55 }),
56 );
57 const text = visible
58 .filter((character, index) => {
59 if (character !== "\u200D") return true;
60 const kept =
61 isEmojiPart(visible[index - 1]?.codePointAt(0)) &&
62 isEmojiPart(visible[index + 1]?.codePointAt(0));
63 if (!kept) hiddenCharacters++;
64 return kept;
65 })
66 .join("");
67 return { text: text.trim(), hiddenCharacters };
69​
70const OWNER = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/;
71const NAME = /^[A-Za-z0-9._-]{1,100}$/;
72​
73function repositoryOf(owner: string, name: string): PromptLinkRepository | null {
74 const trimmedName = name.replace(/\.git$/i, "");
75 if (!OWNER.test(owner) || !NAME.test(trimmedName) || /^\.+$/.test(trimmedName)) return null;
76 return { owner, name: trimmedName };
78​
79export function parsePromptLinkRepository(value: string): PromptLinkRepository | null {
80 const trimmed = value.trim();
81 const url = /^https?:\/\/(?:www\.)?github\.com\/([^/?#]+)\/([^/?#]+)\/?(?:[?#].*)?$/i.exec(
82 trimmed,
83 );
84 const short = /^([^/\s]+)\/([^/\s]+)$/.exec(trimmed);
85 const match = url ?? short;
86 return match?.[1] && match[2] ? repositoryOf(match[1], match[2]) : null;
88​
89function parsePromptLinkPullRequest(value: string): PromptLinkPullRequest | null {
90 const trimmed = value.trim();
91 const match =
92 /^https?:\/\/(?:www\.)?github\.com\/([^/?#]+)\/([^/?#]+)\/pull\/(\d+)(?:[/?#].*)?$/i.exec(
93 trimmed,
94 ) ?? /^([^/\s#]+)\/([^/\s#]+)(?:\/|#)(\d+)$/.exec(trimmed);
95 if (!match?.[1] || !match[2] || !match[3]) return null;
96 const repository = repositoryOf(match[1], match[2]);
97 const number = Number(match[3]);
98 return repository && Number.isSafeInteger(number) && number > 0
99 ? { ...repository, number }
100 : null;
102​
103export function promptLinkPullRequestUrl(pullRequest: PromptLinkPullRequest): string {
104 return `https://github.com/${pullRequest.owner}/${pullRequest.name}/pull/${pullRequest.number}`;
106​
107export type PromptLinkError =
108 | "prompt-too-long"
109 | "prompt-only-hidden"
110 | "unreadable-pull-request"
111 | "missing-prompt"
112 | "unreadable-repository";
113​
114function englishPromptLinkError(error: PromptLinkError): string {
115 switch (error) {
116 case "prompt-too-long":
117 return `This prompt is longer than ${PROMPT_LINK_MAX_PROMPT_LENGTH.toLocaleString("en-US")} characters, so T3 Code did not open it.`;
118 case "prompt-only-hidden":
119 return "This prompt had only hidden characters, so it may be malicious. T3 Code did not open it.";
120 case "unreadable-pull-request":
121 return "This link names a pull request T3 Code cannot read.";
122 case "missing-prompt":
123 return "This link has no prompt.";
124 case "unreadable-repository":
125 return "This link names a repository T3 Code cannot read.";
126 }
128​
129function readPrompt(
130 params: URLSearchParams,
131 describe: (error: PromptLinkError) => string,
132): PromptLinkResult<LinkedPrompt | null> {
133 const raw = params.get("prompt");
134 if (raw === null) return { ok: true, value: null };
135 if (raw.length > PROMPT_LINK_MAX_PROMPT_LENGTH) {
136 return { ok: false, error: describe("prompt-too-long") };
137 }
138 const prompt = sanitizeLinkedPrompt(raw);
139 if (prompt.text.length === 0 && prompt.hiddenCharacters > 0) {
140 return { ok: false, error: describe("prompt-only-hidden") };
141 }
142 return { ok: true, value: prompt.text.length > 0 ? prompt : null };
144​
145const optionalParam = (params: URLSearchParams, key: string) => params.get(key)?.trim() || null;
146​
147export function parseNewThreadLink(
148 search: string,
149 describe: (error: PromptLinkError) => string = englishPromptLinkError,
150): PromptLinkResult<NewThreadLink> {
151 const params = new URLSearchParams(search);
152 const prompt = readPrompt(params, describe);
153 if (!prompt.ok) return prompt;
154 const pr = params.get("pr");
155 if (pr !== null) {
156 const pullRequest = parsePromptLinkPullRequest(pr);
157 if (pullRequest === null) {
158 return { ok: false, error: describe("unreadable-pull-request") };
159 }
160 return { ok: true, value: { kind: "pull-request", pullRequest, prompt: prompt.value } };
161 }
162 if (prompt.value === null) return { ok: false, error: describe("missing-prompt") };
163 const repo = params.get("repo");
164 const repository = repo === null ? null : parsePromptLinkRepository(repo);
165 if (repo !== null && repository === null) {
166 return { ok: false, error: describe("unreadable-repository") };
167 }
168 return {
169 ok: true,
170 value: {
171 kind: "new",
172 prompt: prompt.value,
173 repository,
174 provider: optionalParam(params, "provider")?.toLowerCase() ?? null,
175 model: optionalParam(params, "model"),
176 },
177 };
179​
180export function parseThreadLinkPrompt(
181 search: string,
182 describe: (error: PromptLinkError) => string = englishPromptLinkError,
183): PromptLinkResult<LinkedPrompt | null> {
184 return readPrompt(new URLSearchParams(search), describe);
186​
187export function withoutPromptLinkParams(search: string): string {
188 const params = new URLSearchParams(search);
189 for (const key of ["prompt", "repo", "pr", "provider", "model"]) params.delete(key);
190 const rest = params.toString();
191 return rest ? `?${rest}` : "";
193​
194export function buildNewThreadLink(input: {
195 readonly prompt: string;
196 readonly repository?: PromptLinkRepository | null;
197 readonly provider?: string | null;
198 readonly model?: string | null;
199 readonly origin?: string;
200}): string {
201 const url = new URL("/new", input.origin ?? DEFAULT_HOSTED_APP_URL);
202 url.searchParams.set("prompt", input.prompt);
203 if (input.repository) {
204 url.searchParams.set("repo", `${input.repository.owner}/${input.repository.name}`);
205 }
206 if (input.provider) url.searchParams.set("provider", input.provider);
207 if (input.provider && input.model) url.searchParams.set("model", input.model);
208 return url.toString();
210​
211const APP_SCHEME = /^t3code(?:-[a-z]+)?:$/;
212const THREAD_PATH = /^\/([^/]+)\/([^/]+)\/?$/;
213​
214export function promptLinkAppPath(
215 value: string,
216 hostedAppUrl: string = DEFAULT_HOSTED_APP_URL,
217): string | null {
218 const url = parseUrl(value);
219 if (!url) return null;
220 if (APP_SCHEME.test(url.protocol)) {
221 if (url.host === "new" && (url.pathname === "" || url.pathname === "/")) {
222 return `/new${url.search}`;
223 }
224 const thread = url.host === "threads" ? THREAD_PATH.exec(url.pathname) : null;
225 return thread ? `/${thread[1]}/${thread[2]}${url.search}` : null;
226 }
227 if (url.origin !== parseUrl(hostedAppUrl)?.origin) return null;
228 if (url.pathname === "/new" || url.pathname === "/new/") return `/new${url.search}`;
229 // The web app's own thread route is a link only with a prompt, so reloading a tab never asks.
230 const thread = url.pathname.startsWith("/threads/")
231 ? THREAD_PATH.exec(url.pathname.slice("/threads".length))
232 : url.searchParams.has("prompt")
233 ? THREAD_PATH.exec(url.pathname)
234 : null;
235 return thread ? `/${thread[1]}/${thread[2]}${url.search}` : null;
237​
238export function promptLinkDeepLink(appPath: string, scheme = "t3code"): string {
239 const url = new URL(appPath, "https://app.invalid");
240 const host = url.pathname === "/new" ? "new" : `threads${url.pathname}`;
241 return `${scheme}://${host}${url.search}`;