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