Open History to see the last commit
1import { EnvironmentId, ThreadId } from "@t3tools/contracts";
2import * as Option from "effect/Option";
3import * as Schema from "effect/Schema";
4
5/**
6 * In-app links to threads. Agents put them in Markdown as
7 * `[title](t3-thread://v1/<environmentId>/<threadId>)`, and clients open the
8 * thread instead of a browser. Thread tools return a ready `link` for each
9 * thread, so agents never build one by hand.
10 */
11export const THREAD_LINK_PROTOCOL = "t3-thread";
12const THREAD_LINK_HREF_PREFIX = `${THREAD_LINK_PROTOCOL}://v1/`;
13const LINK_LABEL_MAX_CHARS = 120;
14
15const decodeEnvironmentId = Schema.decodeUnknownOption(EnvironmentId);
16const decodeThreadId = Schema.decodeUnknownOption(ThreadId);
17
18// encodeURIComponent keeps parentheses, and a raw `)` would end the Markdown link early.
19function encodeIdSegment(id: string): string {
20 return encodeURIComponent(id).replace(/\(/g, "%28").replace(/\)/g, "%29");
21}
22
23function formatThreadLinkHref(environmentId: string, threadId: string): string {
24 return `${THREAD_LINK_HREF_PREFIX}${encodeIdSegment(environmentId)}/${encodeIdSegment(threadId)}`;
25}
26
27/** A Markdown link to the thread, labeled with its title. */
28export function formatThreadLink(thread: {
29 readonly environmentId: string;
30 readonly threadId: string;
31 readonly title: string;
32}): string {
33 const label =
34 thread.title
35 .replace(/[[\]\\\r\n]/g, " ")
36 .replace(/\s+/g, " ")
37 .trim()
38 .slice(0, LINK_LABEL_MAX_CHARS) || "Untitled thread";
39 return `[${label}](${formatThreadLinkHref(thread.environmentId, thread.threadId)})`;
40}
41
42export function parseThreadLinkHref(
43 href: string,
44): { readonly environmentId: EnvironmentId; readonly threadId: ThreadId } | null {
45 if (!href.startsWith(THREAD_LINK_HREF_PREFIX)) return null;
46 const parts = href.slice(THREAD_LINK_HREF_PREFIX.length).split("/");
47 if (parts.length !== 2) return null;
48 try {
49 const environmentId = decodeEnvironmentId(decodeURIComponent(parts[0]!));
50 const threadId = decodeThreadId(decodeURIComponent(parts[1]!));
51 return Option.isSome(environmentId) && Option.isSome(threadId)
52 ? { environmentId: environmentId.value, threadId: threadId.value }
53 : null;
54 } catch {
55 // Malformed percent encoding.
56 return null;
57 }
58}