The best way to control Claude Code, Codex and more from any computer or phone

main
ts 240 lines 8.83 KB
Raw
1 import { DEFAULT_HOSTED_APP_URL } from "./connectAuth.ts";
2 import { parseUrl } from "./url.ts";
3
4 export const PROMPT_LINK_MAX_PROMPT_LENGTH = 8_000;
5
6 export interface PromptLinkRepository {
7 readonly owner: string;
8 readonly name: string;
9 }
10
11 export interface PromptLinkPullRequest extends PromptLinkRepository {
12 readonly number: number;
13 }
14
15 export interface LinkedPrompt {
16 readonly text: string;
17 readonly hiddenCharacters: number;
18 }
19
20 export 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
34 export 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.
39 const 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.
43 const isEmojiPart = (codePoint: number | undefined) =>
44 codePoint !== undefined &&
45 ((codePoint >= 0x1f000 && codePoint <= 0x1faff) ||
46 (codePoint >= 0x2190 && codePoint <= 0x2bff) ||
47 codePoint === 0xfe0f);
48
49 export 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 };
68 }
69
70 const OWNER = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/;
71 const NAME = /^[A-Za-z0-9._-]{1,100}$/;
72
73 function 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 };
77 }
78
79 export function parsePromptLinkRepository(value: string): PromptLinkRepository | null {
80 const trimmed = value.trim();
81 const url = /^https?:\/\/(?:www\.)?github\.com\/([^/?#]+)\/([^/?#]+)\/?$/i.exec(trimmed);
82 const short = /^([^/\s]+)\/([^/\s]+)$/.exec(trimmed);
83 const match = url ?? short;
84 return match?.[1] && match[2] ? repositoryOf(match[1], match[2]) : null;
85 }
86
87 function parsePromptLinkPullRequest(value: string): PromptLinkPullRequest | null {
88 const trimmed = value.trim();
89 const match =
90 /^https?:\/\/(?:www\.)?github\.com\/([^/?#]+)\/([^/?#]+)\/pull\/(\d+)(?:[/?#].*)?$/i.exec(
91 trimmed,
92 ) ?? /^([^/\s#]+)\/([^/\s#]+)(?:\/|#)(\d+)$/.exec(trimmed);
93 if (!match?.[1] || !match[2] || !match[3]) return null;
94 const repository = repositoryOf(match[1], match[2]);
95 const number = Number(match[3]);
96 return repository && Number.isSafeInteger(number) && number > 0
97 ? { ...repository, number }
98 : null;
99 }
100
101 export function promptLinkPullRequestUrl(pullRequest: PromptLinkPullRequest): string {
102 return `https://github.com/${pullRequest.owner}/${pullRequest.name}/pull/${pullRequest.number}`;
103 }
104
105 export type PromptLinkError =
106 | "prompt-too-long"
107 | "prompt-only-hidden"
108 | "unreadable-pull-request"
109 | "missing-prompt"
110 | "unreadable-repository";
111
112 function englishPromptLinkError(error: PromptLinkError): string {
113 switch (error) {
114 case "prompt-too-long":
115 return `This prompt is longer than ${PROMPT_LINK_MAX_PROMPT_LENGTH.toLocaleString("en-US")} characters, so T3 Code did not open it.`;
116 case "prompt-only-hidden":
117 return "This prompt had only hidden characters, so it may be malicious. T3 Code did not open it.";
118 case "unreadable-pull-request":
119 return "This link names a pull request T3 Code cannot read.";
120 case "missing-prompt":
121 return "This link has no prompt.";
122 case "unreadable-repository":
123 return "This link names a repository T3 Code cannot read.";
124 }
125 }
126
127 function readPrompt(
128 params: URLSearchParams,
129 describe: (error: PromptLinkError) => string,
130 ): PromptLinkResult<LinkedPrompt | null> {
131 const raw = params.get("prompt");
132 if (raw === null) return { ok: true, value: null };
133 if (raw.length > PROMPT_LINK_MAX_PROMPT_LENGTH) {
134 return { ok: false, error: describe("prompt-too-long") };
135 }
136 const prompt = sanitizeLinkedPrompt(raw);
137 if (prompt.text.length === 0 && prompt.hiddenCharacters > 0) {
138 return { ok: false, error: describe("prompt-only-hidden") };
139 }
140 return { ok: true, value: prompt.text.length > 0 ? prompt : null };
141 }
142
143 const optionalParam = (params: URLSearchParams, key: string) => params.get(key)?.trim() || null;
144
145 export function parseNewThreadLink(
146 search: string,
147 describe: (error: PromptLinkError) => string = englishPromptLinkError,
148 ): PromptLinkResult<NewThreadLink> {
149 const params = new URLSearchParams(search);
150 const prompt = readPrompt(params, describe);
151 if (!prompt.ok) return prompt;
152 const pr = params.get("pr");
153 if (pr !== null) {
154 const pullRequest = parsePromptLinkPullRequest(pr);
155 if (pullRequest === null) {
156 return { ok: false, error: describe("unreadable-pull-request") };
157 }
158 return { ok: true, value: { kind: "pull-request", pullRequest, prompt: prompt.value } };
159 }
160 if (prompt.value === null) return { ok: false, error: describe("missing-prompt") };
161 const repo = params.get("repo");
162 const repository = repo === null ? null : parsePromptLinkRepository(repo);
163 if (repo !== null && repository === null) {
164 return { ok: false, error: describe("unreadable-repository") };
165 }
166 return {
167 ok: true,
168 value: {
169 kind: "new",
170 prompt: prompt.value,
171 repository,
172 provider: optionalParam(params, "provider")?.toLowerCase() ?? null,
173 model: optionalParam(params, "model"),
174 },
175 };
176 }
177
178 export function parseThreadLinkPrompt(
179 search: string,
180 describe: (error: PromptLinkError) => string = englishPromptLinkError,
181 ): PromptLinkResult<LinkedPrompt | null> {
182 return readPrompt(new URLSearchParams(search), describe);
183 }
184
185 export function withoutPromptLinkParams(search: string): string {
186 const params = new URLSearchParams(search);
187 for (const key of ["prompt", "repo", "pr", "provider", "model"]) params.delete(key);
188 const rest = params.toString();
189 return rest ? `?${rest}` : "";
190 }
191
192 export function buildNewThreadLink(input: {
193 readonly prompt: string;
194 readonly repository?: PromptLinkRepository | null;
195 readonly provider?: string | null;
196 readonly model?: string | null;
197 readonly origin?: string;
198 }): string {
199 const url = new URL("/new", input.origin ?? DEFAULT_HOSTED_APP_URL);
200 url.searchParams.set("prompt", input.prompt);
201 if (input.repository) {
202 url.searchParams.set("repo", `${input.repository.owner}/${input.repository.name}`);
203 }
204 if (input.provider) url.searchParams.set("provider", input.provider);
205 if (input.provider && input.model) url.searchParams.set("model", input.model);
206 return url.toString();
207 }
208
209 const APP_SCHEME = /^t3code(?:-[a-z]+)?:$/;
210 const THREAD_PATH = /^\/([^/]+)\/([^/]+)\/?$/;
211
212 export function promptLinkAppPath(
213 value: string,
214 hostedAppUrl: string = DEFAULT_HOSTED_APP_URL,
215 ): string | null {
216 const url = parseUrl(value);
217 if (!url) return null;
218 if (APP_SCHEME.test(url.protocol)) {
219 if (url.host === "new" && (url.pathname === "" || url.pathname === "/")) {
220 return `/new${url.search}`;
221 }
222 const thread = url.host === "threads" ? THREAD_PATH.exec(url.pathname) : null;
223 return thread ? `/${thread[1]}/${thread[2]}${url.search}` : null;
224 }
225 if (url.origin !== parseUrl(hostedAppUrl)?.origin) return null;
226 if (url.pathname === "/new") return `/new${url.search}`;
227 // The web app's own thread route is a link only with a prompt, so reloading a tab never asks.
228 const thread = url.pathname.startsWith("/threads/")
229 ? THREAD_PATH.exec(url.pathname.slice("/threads".length))
230 : url.searchParams.has("prompt")
231 ? THREAD_PATH.exec(url.pathname)
232 : null;
233 return thread ? `/${thread[1]}/${thread[2]}${url.search}` : null;
234 }
235
236 export function promptLinkDeepLink(appPath: string, scheme = "t3code"): string {
237 const url = new URL(appPath, "https://app.invalid");
238 const host = url.pathname === "/new" ? "new" : `threads${url.pathname}`;
239 return `${scheme}://${host}${url.search}`;
240 }