The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts"; |
| 2 | import * as Option from "effect/Option"; |
| 3 | import * as Schema from "effect/Schema"; |
| 4 | |
| 5 | import { DEFAULT_HOSTED_APP_URL } from "./connectAuth.ts"; |
| 6 | |
| 7 | export const THREAD_LINK_PROTOCOL = "t3-thread"; |
| 8 | const V1_PREFIX = `${THREAD_LINK_PROTOCOL}://v1/`; |
| 9 | const V2_PREFIX = `${THREAD_LINK_PROTOCOL}://v2/`; |
| 10 | const HOSTED_PREFIX = `${DEFAULT_HOSTED_APP_URL}/threads/`; |
| 11 | const HOSTED_SEGMENT = "[A-Za-z0-9_%-]+"; |
| 12 | const HOSTED_LINK = `${HOSTED_PREFIX.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&")}${HOSTED_SEGMENT}/${HOSTED_SEGMENT}`; |
| 13 | const THREAD_HREF = String.raw`t3-thread:\/\/v[12]\/`; |
| 14 | // A label stops at any bracket, so a run of unclosed brackets is scanned once, not once per bracket. |
| 15 | const LABEL = String.raw`[^[\]\n]*`; |
| 16 | // Earlier alternatives claim text so later ones cannot match inside it: an escaped character opens |
| 17 | // nothing, code is literal, and a link to anywhere else keeps a thread URL in its label or href. |
| 18 | const THREAD_LINK_OUTSIDE_CODE = new RegExp( |
| 19 | [ |
| 20 | String.raw`\\[!-/:-@[-\`{-~]`, |
| 21 | String.raw`(?<fence>(\`{3,}|~{3,})[\s\S]*?(?:\2|$))`, |
| 22 | String.raw`(?<span>(\`+)[^\n]*?\4)`, |
| 23 | // A labeled link's destination may be angle-bracketed, as CommonMark allows: [label](<href>). |
| 24 | String.raw`\[(?<label>${LABEL})\]\((?:<(?<angleHref>${THREAD_HREF}[^\s<>]+|${HOSTED_LINK})>|(?<href>${THREAD_HREF}[^\s>)]+|${HOSTED_LINK}))\)`, |
| 25 | String.raw`\[${LABEL}\]\((?:<[^<>\n]*>|[^\s()]*(?:\([^\s()]*\)[^\s()]*)*)(?:[ \t]+(?:"[^"\n]*"|'[^'\n]*'))?\)`, |
| 26 | String.raw`<(?<autolink>${THREAD_HREF}[^\s<>]+|${HOSTED_LINK})>`, |
| 27 | // After a URL character the hosted link is part of a longer URL, such as a redirect target. |
| 28 | String.raw`(?<![A-Za-z0-9%/?#=&@+-])(?<bare>${HOSTED_LINK})(?![\w%/?#-])`, |
| 29 | ].join("|"), |
| 30 | "g", |
| 31 | ); |
| 32 | |
| 33 | const decodeThreadId = Schema.decodeUnknownOption(ThreadId); |
| 34 | const decodeEnvironmentId = Schema.decodeUnknownOption(EnvironmentId); |
| 35 | |
| 36 | /** A v1 link names no environment; the message's own, or a unique match, stands in. */ |
| 37 | export interface ThreadLink { |
| 38 | readonly environmentId: EnvironmentId | null; |
| 39 | readonly threadId: ThreadId; |
| 40 | } |
| 41 | |
| 42 | // Escapes even URL-safe punctuation, so a sentence's closing period never reads as part of an id. |
| 43 | const hostedSegment = (id: string) => |
| 44 | encodeURIComponent(id).replace( |
| 45 | /[.!~*'()]/g, |
| 46 | (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`, |
| 47 | ); |
| 48 | |
| 49 | /** Opens the thread from anywhere: the hosted app offers the desktop app, the mobile app, or itself. */ |
| 50 | export function hostedThreadLink(ref: ScopedThreadRef, origin = DEFAULT_HOSTED_APP_URL): string { |
| 51 | const path = `/threads/${hostedSegment(ref.environmentId)}/${hostedSegment(ref.threadId)}`; |
| 52 | return new URL(path, origin).toString(); |
| 53 | } |
| 54 | |
| 55 | const HOSTED_PATH = new RegExp(`^(${HOSTED_SEGMENT})/(${HOSTED_SEGMENT})$`); |
| 56 | |
| 57 | function parseHostedThreadLink(href: string): ThreadLink | null { |
| 58 | const match = HOSTED_PATH.exec(href.slice(HOSTED_PREFIX.length)); |
| 59 | if (!match) return null; |
| 60 | try { |
| 61 | const environmentId = Option.getOrNull(decodeEnvironmentId(decodeURIComponent(match[1]!))); |
| 62 | const threadId = Option.getOrNull(decodeThreadId(decodeURIComponent(match[2]!))); |
| 63 | return environmentId === null || threadId === null ? null : { environmentId, threadId }; |
| 64 | } catch { |
| 65 | return null; |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | /** |
| 70 | * The ids as written. Thread ids can hold percent escapes of their own, so they are not decoded, |
| 71 | * except in a hosted link, which escapes them itself. |
| 72 | */ |
| 73 | export function parseThreadLinkHref(href: string): ThreadLink | null { |
| 74 | if (href.startsWith(HOSTED_PREFIX)) return parseHostedThreadLink(href); |
| 75 | if (href.startsWith(V1_PREFIX)) { |
| 76 | const threadId = Option.getOrNull(decodeThreadId(href.slice(V1_PREFIX.length))); |
| 77 | return threadId === null ? null : { environmentId: null, threadId }; |
| 78 | } |
| 79 | if (!href.startsWith(V2_PREFIX)) return null; |
| 80 | const path = href.slice(V2_PREFIX.length); |
| 81 | const slash = path.indexOf("/"); |
| 82 | if (slash < 0) return null; |
| 83 | const environmentId = Option.getOrNull(decodeEnvironmentId(path.slice(0, slash))); |
| 84 | const threadId = Option.getOrNull(decodeThreadId(path.slice(slash + 1))); |
| 85 | return environmentId === null || threadId === null ? null : { environmentId, threadId }; |
| 86 | } |
| 87 | |
| 88 | function percentDecodedThreadLinkId(threadId: ThreadId): ThreadId | null { |
| 89 | try { |
| 90 | const decoded = decodeURIComponent(threadId); |
| 91 | return decoded === threadId ? null : Option.getOrNull(decodeThreadId(decoded)); |
| 92 | } catch { |
| 93 | return null; |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | /** The threads a link can name, in its own environment or else the message's: as written, then decoded. */ |
| 98 | export function threadLinkCandidates( |
| 99 | link: ThreadLink, |
| 100 | messageEnvironmentId: EnvironmentId, |
| 101 | ): ReadonlyArray<ScopedThreadRef> { |
| 102 | const environmentId = link.environmentId ?? messageEnvironmentId; |
| 103 | const decodedId = percentDecodedThreadLinkId(link.threadId); |
| 104 | const written = { environmentId, threadId: link.threadId }; |
| 105 | return decodedId === null ? [written] : [written, { environmentId, threadId: decodedId }]; |
| 106 | } |
| 107 | |
| 108 | /** A v1 link its message's environment lacks opens a unique match elsewhere; a v2 link never does. */ |
| 109 | export function guessThreadLinkRef( |
| 110 | link: ThreadLink, |
| 111 | refs: ReadonlyArray<ScopedThreadRef>, |
| 112 | ): ScopedThreadRef | null { |
| 113 | if (link.environmentId !== null) return null; |
| 114 | const decodedId = percentDecodedThreadLinkId(link.threadId); |
| 115 | for (const threadId of decodedId === null ? [link.threadId] : [link.threadId, decodedId]) { |
| 116 | let match: ScopedThreadRef | null = null; |
| 117 | for (const ref of refs) { |
| 118 | if (ref.threadId !== threadId) continue; |
| 119 | if (match !== null) return null; |
| 120 | match = ref; |
| 121 | } |
| 122 | if (match !== null) return match; |
| 123 | } |
| 124 | return null; |
| 125 | } |
| 126 | |
| 127 | function threadLinkHref(link: ThreadLink): string { |
| 128 | return link.environmentId === null |
| 129 | ? `${V1_PREFIX}${link.threadId}` |
| 130 | : `${V2_PREFIX}${link.environmentId}/${link.threadId}`; |
| 131 | } |
| 132 | |
| 133 | const linkLabel = (label: string | undefined) => |
| 134 | label |
| 135 | ?.replace(/[[\]\\\r\n]/g, " ") |
| 136 | .replace(/\s+/g, " ") |
| 137 | .trim(); |
| 138 | |
| 139 | /** Without a label, an autolink: clients show the thread's current title. */ |
| 140 | export function formatThreadLink(ref: ThreadLink, label?: string): string { |
| 141 | const cleaned = linkLabel(label); |
| 142 | const href = threadLinkHref(ref); |
| 143 | const destination = /[()]/.test(href) ? `<${href}>` : href; |
| 144 | return cleaned ? `[${cleaned}](${destination})` : `<${href}>`; |
| 145 | } |
| 146 | |
| 147 | /** What a person copies out of T3 Code: a Markdown link that opens the thread anywhere. */ |
| 148 | export function formatHostedThreadLink( |
| 149 | ref: ScopedThreadRef, |
| 150 | label: string, |
| 151 | origin?: string, |
| 152 | ): string { |
| 153 | const href = hostedThreadLink(ref, origin); |
| 154 | const cleaned = linkLabel(label); |
| 155 | return cleaned ? `[${cleaned}](${href})` : href; |
| 156 | } |
| 157 | |
| 158 | export function hasThreadLinks(markdown: string): boolean { |
| 159 | return markdown.includes(`${THREAD_LINK_PROTOCOL}://v`) || markdown.includes(HOSTED_PREFIX); |
| 160 | } |
| 161 | |
| 162 | /** Every thread the markdown's links can name, so their titles are keyed reads. */ |
| 163 | export function threadLinkRefs( |
| 164 | markdown: string, |
| 165 | messageEnvironmentId: EnvironmentId, |
| 166 | ): ReadonlyArray<ScopedThreadRef> { |
| 167 | const refs = new Map<string, ScopedThreadRef>(); |
| 168 | // Hermes' matchAll yields matches without `groups`; exec keeps them. |
| 169 | const pattern = new RegExp(THREAD_LINK_OUTSIDE_CODE); |
| 170 | for (let match = pattern.exec(markdown); match !== null; match = pattern.exec(markdown)) { |
| 171 | const href = |
| 172 | match.groups?.angleHref ?? match.groups?.href ?? match.groups?.autolink ?? match.groups?.bare; |
| 173 | const link = href === undefined ? null : parseThreadLinkHref(href); |
| 174 | if (link === null) continue; |
| 175 | for (const ref of threadLinkCandidates(link, messageEnvironmentId)) { |
| 176 | refs.set(`${ref.environmentId}/${ref.threadId}`, ref); |
| 177 | } |
| 178 | } |
| 179 | return [...refs.values()]; |
| 180 | } |
| 181 | |
| 182 | /** Rewrites each link outside code `replace` answers for. `label` is a Markdown link's own text. */ |
| 183 | export function replaceThreadLinks( |
| 184 | markdown: string, |
| 185 | replace: (link: ThreadLink, label: string | undefined) => string | undefined, |
| 186 | ): string { |
| 187 | if (!hasThreadLinks(markdown)) return markdown; |
| 188 | return markdown.replace(THREAD_LINK_OUTSIDE_CODE, (source, ...args) => { |
| 189 | const groups = args.at(-1) as Partial< |
| 190 | Record<"angleHref" | "href" | "autolink" | "bare" | "label", string> |
| 191 | >; |
| 192 | const href = groups.angleHref ?? groups.href ?? groups.autolink ?? groups.bare; |
| 193 | const link = href === undefined ? null : parseThreadLinkHref(href); |
| 194 | return (link && replace(link, groups.label)) ?? source; |
| 195 | }); |
| 196 | } |