Open History to see the last commit
1import {
2 type AuthMcpClientAccess,
3 type EnvironmentId,
4 type EnvironmentMachineKind,
5 type OrchestrationV2TurnItem,
6 type PeerLinkRequestAnswerInput,
7 type PeerLinkSummary,
8 resolveEnvironmentMachineKind,
9 type ServerConfig,
10} from "@t3tools/contracts";
11import * as Option from "effect/Option";
12
13import type { EnvironmentPresentation } from "./connection/presentation.ts";
14import { connectionRoutes, routeHttpBaseUrl } from "./connection/routes.ts";
15import type { RelayDiscoveredEnvironment } from "./relay/discovery.ts";
16
17export type LinkRequestItem = Extract<OrchestrationV2TurnItem, { readonly type: "link_request" }>;
18
19/** Whether an environment offers links: it supports them and its Linked environments beta is on. */
20export const offersLinkedEnvironments = (
21 config: Pick<ServerConfig, "environment" | "settings"> | null | undefined,
22): boolean =>
23 config?.environment.capabilities.peerLinks === true && config.settings.linkedEnvironmentsEnabled;
24
25/** The access a request opens with: the agent's suggestion, else supervised. */
26export const linkRequestDefaultAccess = (
27 item: Pick<LinkRequestItem, "requestedAccess">,
28): AuthMcpClientAccess => item.requestedAccess ?? "approval-required";
29
30/** What the card calls the other environment: its own name, else the address asked for. */
31export const linkRequestTargetName = (item: Pick<LinkRequestItem, "label" | "url">): string =>
32 item.label?.trim() || item.url || "a machine";
33
34/** A machine the user could link a thread's environment to. */
35export interface LinkableMachine {
36 readonly environmentId: EnvironmentId;
37 readonly label: string;
38 readonly machine: EnvironmentMachineKind;
39 readonly connected: boolean;
40 /** Found on the user's T3 Connect account rather than saved in this client. */
41 readonly connectOnly: boolean;
42 /** Whether the thread's environment already has a link to it. */
43 readonly linked: boolean;
44 /**
45 * Where the client knows it answers, most preferred first: the addresses it
46 * reports, then its saved routes, then its T3 Connect address. The server
47 * keeps only those that answer as this machine. Empty for a machine reached
48 * only over SSH, whose forward lives in this client.
49 */
50 readonly urls: ReadonlyArray<string>;
51}
52
53/**
54 * The catalog's machines other than the thread's own, in catalog order, then those only T3
55 * Connect knows. `links` are the thread environment's; an expired one no longer counts as
56 * linked. `connect` is what relay discovery found, and a server reaches a machine there as a
57 * browser does, so its Connect address is usable.
58 */
59export function linkableMachines(input: {
60 readonly environments: ReadonlyArray<
61 EnvironmentPresentation & { readonly environmentId: EnvironmentId }
62 >;
63 readonly threadEnvironmentId: EnvironmentId;
64 readonly links: ReadonlyArray<Pick<PeerLinkSummary, "environmentId" | "status">>;
65 readonly connect: ReadonlyMap<string, RelayDiscoveredEnvironment>;
66}): ReadonlyArray<LinkableMachine> {
67 const linkedIds = new Set(
68 input.links.flatMap((link) => (link.status === "expired" ? [] : [link.environmentId])),
69 );
70 const saved = input.environments
71 .filter((environment) => environment.environmentId !== input.threadEnvironmentId)
72 .map((environment) => {
73 const reported = (environment.serverConfig?.directEndpoints ?? []).map(
74 (endpoint) => endpoint.httpBaseUrl,
75 );
76 const routes = connectionRoutes(environment.entry).flatMap((route) => {
77 const url = route.target._tag === "RelayConnectionTarget" ? null : routeHttpBaseUrl(route);
78 return url === null ? [] : [url];
79 });
80 const connect = input.connect.get(environment.environmentId)?.environment.endpoint;
81 return {
82 environmentId: environment.environmentId,
83 label: environment.entry.target.label,
84 machine: resolveEnvironmentMachineKind(environment.serverConfig),
85 connected: environment.connection.phase === "connected",
86 connectOnly: false,
87 linked: linkedIds.has(environment.environmentId),
88 urls: [
89 ...new Set([
90 ...reported,
91 ...routes,
92 ...(connect === undefined ? [] : [connect.httpBaseUrl]),
93 ]),
94 ],
95 };
96 });
97 const savedIds = new Set<string>(saved.map((machine) => machine.environmentId));
98 const connectOnly = [...input.connect.values()]
99 .filter(
100 ({ environment }) =>
101 environment.environmentId !== input.threadEnvironmentId &&
102 !savedIds.has(environment.environmentId),
103 )
104 .map(({ environment, status }) => {
105 const descriptor = Option.getOrUndefined(status)?.descriptor;
106 return {
107 environmentId: environment.environmentId,
108 label: environment.label,
109 machine: resolveEnvironmentMachineKind(
110 descriptor === undefined ? null : { environment: descriptor },
111 ),
112 connected: false,
113 connectOnly: true,
114 linked: linkedIds.has(environment.environmentId),
115 urls: [environment.endpoint.httpBaseUrl],
116 };
117 });
118 return [...saved, ...connectOnly];
119}
120
121const words = (text: string) =>
122 ` ${text
123 .toLowerCase()
124 .split(/[^\p{L}\p{N}]+/u)
125 .join(" ")
126 .trim()} `;
127const NO_MATCH = 4;
128
129/**
130 * How well a machine's name matches the agent's hint, which is often the
131 * user's own words ("my box"): exact, prefix, substring, then a hint that
132 * names it among other words ("the box on hetzner").
133 */
134const hintRank = (label: string, hint: string) => {
135 const name = label.trim().toLowerCase();
136 const wanted = hint
137 .trim()
138 .toLowerCase()
139 .replace(/^(?:my|our|the)\s+/, "");
140 if (name === wanted) return 0;
141 if (name.startsWith(wanted)) return 1;
142 if (name.includes(wanted)) return 2;
143 if (words(wanted).includes(words(name))) return 3;
144 return NO_MATCH;
145};
146
147/** The machines best match for the agent's hint first, each rank in catalog order. */
148export function rankMachinesByHint<T extends { readonly label: string }>(
149 machines: ReadonlyArray<T>,
150 hint: string | undefined,
151): ReadonlyArray<T> {
152 if (hint === undefined || hint.trim().length === 0) return machines;
153 return machines
154 .map((machine, index) => ({ machine, index, rank: hintRank(machine.label, hint) }))
155 .sort((a, b) => a.rank - b.rank || a.index - b.index)
156 .map(({ machine }) => machine);
157}
158
159/** The machine a card opens on: the one it names, else the hint's best match. */
160export function linkRequestInitialMachine(
161 item: Pick<LinkRequestItem, "environmentId" | "hint">,
162 machines: ReadonlyArray<LinkableMachine>,
163): EnvironmentId | null {
164 if (item.environmentId !== undefined) return item.environmentId;
165 if (item.hint === undefined) return null;
166 const [best] = rankMachinesByHint(machines, item.hint);
167 return best !== undefined && hintRank(best.label, item.hint) < NO_MATCH
168 ? best.environmentId
169 : null;
170}
171
172/** What a link request card shows: the actions while pending, otherwise a one-line outcome. */
173export type LinkRequestDisplay =
174 | { readonly kind: "pending" }
175 | { readonly kind: "pending-elsewhere"; readonly label: string }
176 | {
177 readonly kind: "answered";
178 readonly outcome: "linked" | "declined" | "ended" | "failed";
179 readonly label: string;
180 };
181
182/**
183 * `visibility` is the projected row's: a request inherited from another
184 * thread (a fork) can only be answered where it was asked. `accessLabel`
185 * names an access level the way the client's access picker does.
186 */
187export function linkRequestDisplay(
188 item: Pick<
189 LinkRequestItem,
190 "linkStatus" | "label" | "url" | "linkedLabel" | "linkedAccess" | "failure"
191 >,
192 visibility: "local" | "inherited" | "synthetic",
193 accessLabel: (access: AuthMcpClientAccess) => string,
194): LinkRequestDisplay {
195 switch (item.linkStatus) {
196 case "pending":
197 return visibility === "local"
198 ? { kind: "pending" }
199 : { kind: "pending-elsewhere", label: "Waiting for an answer in the original thread" };
200 case "linked":
201 return {
202 kind: "answered",
203 outcome: "linked",
204 label: `Linked ${item.linkedLabel ?? linkRequestTargetName(item)}${
205 item.linkedAccess === undefined ? "" : ` · ${accessLabel(item.linkedAccess)}`
206 }`,
207 };
208 case "declined":
209 return { kind: "answered", outcome: "declined", label: "Declined" };
210 case "failed":
211 return {
212 kind: "answered",
213 outcome: "failed",
214 label: `Could not link: ${item.failure ?? "the other environment refused"}`,
215 };
216 case "cancelled":
217 return { kind: "answered", outcome: "ended", label: "Request ended" };
218 }
219}
220
221/**
222 * Builds the RPC payload for an answer. A link with a blank code returns null,
223 * since the server rejects it; callers keep Link disabled instead.
224 */
225export function linkRequestAnswerInput(
226 item: Pick<LinkRequestItem, "id" | "threadId">,
227 answer:
228 | {
229 readonly type: "link";
230 /** The machine picked, or an address typed in its place. */
231 readonly target:
232 | Pick<LinkableMachine, "environmentId" | "label" | "urls">
233 | { readonly url: string };
234 readonly access: AuthMcpClientAccess;
235 readonly pairingCode: string;
236 }
237 | { readonly type: "use-existing"; readonly environmentId: EnvironmentId }
238 | { readonly type: "decline" },
239): PeerLinkRequestAnswerInput | null {
240 const base = { threadId: item.threadId, turnItemId: item.id };
241 if (answer.type !== "link") return { ...base, answer };
242 const pairingCode = answer.pairingCode.trim();
243 if (pairingCode.length === 0) return null;
244 const { target } = answer;
245 if ("url" in target) {
246 const url = target.url.trim();
247 if (url.length === 0) return null;
248 return { ...base, answer: { type: "link", urls: [url], access: answer.access, pairingCode } };
249 }
250 const [first, ...rest] = target.urls;
251 if (first === undefined) return null;
252 return {
253 ...base,
254 answer: {
255 type: "link",
256 environmentId: target.environmentId,
257 label: target.label,
258 urls: [first, ...rest],
259 access: answer.access,
260 pairingCode,
261 },
262 };
263}
264
265/** Failures whose message is written for the user and never echoes the request payload. */
266const USER_FACING_FAILURE_TAGS = new Set([
267 "PeerLinkRequestError",
268 "EnvironmentAuthorizationError",
269 "PeerPairingCodeError",
270]);
271
272/**
273 * Inline error copy for a failed answer. Only known errors pass their message
274 * through: anything else (transport or encoding failures) gets the generic
275 * copy, so the pairing code can never surface in the UI.
276 */
277export function linkRequestFailureMessage(failure: unknown): string {
278 if (
279 typeof failure === "object" &&
280 failure !== null &&
281 "_tag" in failure &&
282 typeof failure._tag === "string" &&
283 USER_FACING_FAILURE_TAGS.has(failure._tag) &&
284 "message" in failure &&
285 typeof failure.message === "string" &&
286 failure.message.trim().length > 0
287 ) {
288 return failure.message;
289 }
290 return "Could not answer the request. Try again.";
291}