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

promptLinks.ts

213 lines8.1 KB

1import { DEFAULT_HOSTED_APP_URL } from "./connectAuth.ts";
2​
3export const PROMPT_LINK_MAX_PROMPT_LENGTH = 8_000;
4​
5export interface PromptLinkRepository {
6 readonly owner: string;
7 readonly name: string;
8}
9​
10export interface PromptLinkPullRequest extends PromptLinkRepository {
11 readonly number: number;
13​
14export interface LinkedPrompt {
15 readonly text: string;
16 readonly hiddenCharacters: number;
18​
19export type NewThreadLink =
20 | {
21 readonly kind: "new";
22 readonly prompt: LinkedPrompt;
23 readonly repository: PromptLinkRepository | null;
24 readonly provider: string | null;
25 readonly model: string | null;
26 }
27 | {
28 readonly kind: "pull-request";
29 readonly pullRequest: PromptLinkPullRequest;
30 readonly prompt: LinkedPrompt | null;
31 };
32​
33export type PromptLinkResult<T> =
34 | { readonly ok: true; readonly value: T }
35 | { readonly ok: false; readonly error: string };
36​
37// Zero-width and bidi controls, tag and variation-selector blocks, and other characters that
38// render as nothing. A model reads them; the person checking the draft cannot see them, which
39// makes them the usual way to hide instructions in a prompt.
40const HIDDEN_CHARACTERS =
41 // oxlint-disable-next-line no-control-regex, no-misleading-character-class -- these are the characters it removes.
42 /[\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;
43// Emoji and the pieces emoji sequences are built from: pictographs, symbols, skin tones, and the
44// emoji presentation selector. Numeric ranges, because Hermes lacks Unicode property escapes.
45const isEmojiPart = (codePoint: number | undefined) =>
46 codePoint !== undefined &&
47 ((codePoint >= 0x1f000 && codePoint <= 0x1faff) ||
48 (codePoint >= 0x2190 && codePoint <= 0x2bff) ||
49 codePoint === 0xfe0f);
50​
51export function sanitizeLinkedPrompt(raw: string): LinkedPrompt {
52 let hiddenCharacters = 0;
53 const visible = Array.from(
54 raw.replace(/\r\n?|[\u2028\u2029]/g, "\n").replace(HIDDEN_CHARACTERS, () => {
55 hiddenCharacters++;
56 return "";
57 }),
58 );
59 const text = visible
60 .filter((character, index) => {
61 if (character !== "\u200D") return true;
62 const kept =
63 isEmojiPart(visible[index - 1]?.codePointAt(0)) &&
64 isEmojiPart(visible[index + 1]?.codePointAt(0));
65 if (!kept) hiddenCharacters++;
66 return kept;
67 })
68 .join("");
69 return { text: text.trim(), hiddenCharacters };
71​
72const OWNER = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/;
73const NAME = /^[A-Za-z0-9._-]{1,100}$/;
74​
75function repositoryOf(owner: string, name: string): PromptLinkRepository | null {
76 const trimmedName = name.replace(/\.git$/i, "");
77 if (!OWNER.test(owner) || !NAME.test(trimmedName) || /^\.+$/.test(trimmedName)) return null;
78 return { owner, name: trimmedName };
80​
81export function parsePromptLinkRepository(value: string): PromptLinkRepository | null {
82 const trimmed = value.trim();
83 const url = /^https?:\/\/(?:www\.)?github\.com\/([^/?#]+)\/([^/?#]+)\/?$/i.exec(trimmed);
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​
107function readPrompt(params: URLSearchParams): PromptLinkResult<LinkedPrompt | null> {
108 const raw = params.get("prompt");
109 if (raw === null) return { ok: true, value: null };
110 if (raw.length > PROMPT_LINK_MAX_PROMPT_LENGTH) {
111 return {
112 ok: false,
113 error: `This prompt is longer than ${PROMPT_LINK_MAX_PROMPT_LENGTH.toLocaleString("en-US")} characters, so T3 Code did not open it.`,
114 };
115 }
116 const prompt = sanitizeLinkedPrompt(raw);
117 if (prompt.text.length === 0 && prompt.hiddenCharacters > 0) {
118 return {
119 ok: false,
120 error:
121 "This prompt had only hidden characters, so it may be malicious. T3 Code did not open it.",
122 };
123 }
124 return { ok: true, value: prompt.text.length > 0 ? prompt : null };
126​
127const optionalParam = (params: URLSearchParams, key: string) => params.get(key)?.trim() || null;
128​
129export function parseNewThreadLink(search: string): PromptLinkResult<NewThreadLink> {
130 const params = new URLSearchParams(search);
131 const prompt = readPrompt(params);
132 if (!prompt.ok) return prompt;
133 const pr = params.get("pr");
134 if (pr !== null) {
135 const pullRequest = parsePromptLinkPullRequest(pr);
136 if (pullRequest === null) {
137 return { ok: false, error: "This link names a pull request T3 Code cannot read." };
138 }
139 return { ok: true, value: { kind: "pull-request", pullRequest, prompt: prompt.value } };
140 }
141 if (prompt.value === null) return { ok: false, error: "This link has no prompt." };
142 const repo = params.get("repo");
143 const repository = repo === null ? null : parsePromptLinkRepository(repo);
144 if (repo !== null && repository === null) {
145 return { ok: false, error: "This link names a repository T3 Code cannot read." };
146 }
147 return {
148 ok: true,
149 value: {
150 kind: "new",
151 prompt: prompt.value,
152 repository,
153 provider: optionalParam(params, "provider")?.toLowerCase() ?? null,
154 model: optionalParam(params, "model"),
155 },
156 };
158​
159export function parseThreadLinkPrompt(search: string): PromptLinkResult<LinkedPrompt | null> {
160 return readPrompt(new URLSearchParams(search));
162​
163export function withoutPromptLinkParams(search: string): string {
164 const params = new URLSearchParams(search);
165 for (const key of ["prompt", "repo", "pr", "provider", "model"]) params.delete(key);
166 const rest = params.toString();
167 return rest ? `?${rest}` : "";
169​
170export function buildNewThreadLink(input: {
171 readonly prompt: string;
172 readonly repository?: PromptLinkRepository | null;
173 readonly provider?: string | null;
174 readonly model?: string | null;
175 readonly origin?: string;
176}): string {
177 const url = new URL("/new", input.origin ?? DEFAULT_HOSTED_APP_URL);
178 url.searchParams.set("prompt", input.prompt);
179 if (input.repository) {
180 url.searchParams.set("repo", `${input.repository.owner}/${input.repository.name}`);
181 }
182 if (input.provider) url.searchParams.set("provider", input.provider);
183 if (input.provider && input.model) url.searchParams.set("model", input.model);
184 return url.toString();
186​
187const APP_SCHEME = /^t3code(?:-[a-z]+)?:$/;
188const THREAD_PATH = /^\/([^/]+)\/([^/]+)\/?$/;
189​
190export function promptLinkAppPath(
191 value: string,
192 hostedAppUrl: string = DEFAULT_HOSTED_APP_URL,
193): string | null {
194 if (!URL.canParse(value)) return null;
195 const url = new URL(value);
196 if (APP_SCHEME.test(url.protocol)) {
197 if (url.host === "new" && (url.pathname === "" || url.pathname === "/")) {
198 return `/new${url.search}`;
199 }
200 const thread = url.host === "threads" ? THREAD_PATH.exec(url.pathname) : null;
201 return thread ? `/${thread[1]}/${thread[2]}${url.search}` : null;
202 }
203 if (!URL.canParse(hostedAppUrl) || url.origin !== new URL(hostedAppUrl).origin) return null;
204 if (url.pathname === "/new") return `/new${url.search}`;
205 const thread = url.searchParams.has("prompt") ? THREAD_PATH.exec(url.pathname) : null;
206 return thread ? `/${thread[1]}/${thread[2]}${url.search}` : null;
208​
209export function promptLinkDeepLink(appPath: string, scheme = "t3code"): string {
210 const url = new URL(appPath, "https://app.invalid");
211 const host = url.pathname === "/new" ? "new" : `threads${url.pathname}`;
212 return `${scheme}://${host}${url.search}`;