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

main
ts 413 lines 15.4 KB
Raw
1 import { errorDisplayMessage } from "./errors/translatable.ts";
2 import {
3 type AuthMcpClientAccess,
4 type EnvironmentId,
5 type EnvironmentMachineKind,
6 type OrchestrationV2TurnItem,
7 type PeerLinkRequestAnswerInput,
8 type PeerLinkName,
9 type PeerLinkSummary,
10 resolveEnvironmentMachineKind,
11 type ServerConfig,
12 } from "@t3tools/contracts";
13 import { isLocalLoopbackHost } from "@t3tools/shared/hostClassification";
14 import * as Option from "effect/Option";
15
16 import type { EnvironmentPresentation } from "./connection/presentation.ts";
17 import { connectionRoutes, routeHttpBaseUrl } from "./connection/routes.ts";
18 import type { RelayDiscoveredEnvironment } from "./relay/discovery.ts";
19 import { mFallback, msg } from "gt-i18n";
20 import type { MFunctionType } from "gt-i18n/types";
21
22 export type LinkRequestItem = Extract<OrchestrationV2TurnItem, { readonly type: "link_request" }>;
23
24 /** Whether an environment offers links: it supports them and its Linked environments beta is on. */
25 export const offersLinkedEnvironments = (
26 config: Pick<ServerConfig, "environment" | "settings"> | null | undefined,
27 ): boolean =>
28 config?.environment.capabilities.peerLinks === true && config.settings.linkedEnvironmentsEnabled;
29
30 /**
31 * The machines an environment's agents can work on, by name: its unexpired links (the server
32 * leaves out expired ones), named as this client names them, else as the link does.
33 */
34 export function linkedEnvironmentNames(input: {
35 readonly links: ReadonlyArray<PeerLinkName>;
36 readonly environments: ReadonlyArray<{
37 readonly environmentId: EnvironmentId;
38 readonly label: string;
39 }>;
40 }): ReadonlyMap<EnvironmentId, string> {
41 const names = new Map(
42 input.environments.map((environment) => [environment.environmentId, environment.label]),
43 );
44 return new Map(
45 input.links.map(
46 (link) => [link.environmentId, names.get(link.environmentId) ?? link.label] as const,
47 ),
48 );
49 }
50
51 /** The access a request opens with: the agent's suggestion, else supervised. */
52 export const linkRequestDefaultAccess = (
53 item: Pick<LinkRequestItem, "requestedAccess">,
54 ): AuthMcpClientAccess => item.requestedAccess ?? "approval-required";
55
56 const parsedUrl = (url: string) => {
57 try {
58 return new URL(url);
59 } catch {
60 return undefined;
61 }
62 };
63
64 /** The http or https origin of an address: what the server links, and nothing else in it. */
65 const originOf = (url: string) => {
66 const parsed = parsedUrl(url);
67 return parsed?.protocol === "http:" || parsed?.protocol === "https:" ? parsed.origin : undefined;
68 };
69
70 /** Where a link to `address` sends its pairing code, which a username or path in it can hide. */
71 export const linkDestination = (address: string): string => originOf(address) ?? address.trim();
72
73 /** What the card calls the other environment: where the address asked for leads, never a name it answers with. */
74 export const linkRequestTargetName = (
75 item: Pick<LinkRequestItem, "url">,
76 resolve: MFunctionType = mFallback,
77 ): string => (item.url === undefined ? resolve(msg("a machine")) : linkDestination(item.url));
78
79 /** A machine the user could link a thread's environment to. */
80 export interface LinkableMachine {
81 readonly environmentId: EnvironmentId;
82 readonly label: string;
83 readonly machine: EnvironmentMachineKind;
84 readonly connected: boolean;
85 /** Found on the user's T3 Connect account rather than saved in this client. */
86 readonly connectOnly: boolean;
87 /** Whether the thread's environment already has a link to it. */
88 readonly linked: boolean;
89 /**
90 * Where the client knows it answers, most preferred first: the addresses it
91 * reports, then its saved routes, then its T3 Connect address. The server
92 * keeps only those that answer as this machine. Empty for a machine reached
93 * only over SSH or loopback, which name this client's device.
94 */
95 readonly urls: ReadonlyArray<string>;
96 }
97
98 /** A loopback address names whichever machine opens it: the linking server, not this one. */
99 const isLoopbackUrl = (url: string) => {
100 const hostname = parsedUrl(url)?.hostname;
101 return hostname !== undefined && isLocalLoopbackHost(hostname);
102 };
103
104 /**
105 * The catalog's machines other than the thread's own, in catalog order, then those only T3
106 * Connect knows. `links` are the thread environment's; an expired one no longer counts as
107 * linked. `connect` is what relay discovery found, and a server reaches a machine there as a
108 * browser does, so its Connect address is usable.
109 */
110 export function linkableMachines(input: {
111 readonly environments: ReadonlyArray<
112 EnvironmentPresentation & { readonly environmentId: EnvironmentId }
113 >;
114 /** Null lists every machine, for a view that is not about one environment. */
115 readonly threadEnvironmentId: EnvironmentId | null;
116 readonly links: ReadonlyArray<Pick<PeerLinkSummary, "environmentId" | "status">>;
117 readonly connect: ReadonlyMap<string, RelayDiscoveredEnvironment>;
118 }): ReadonlyArray<LinkableMachine> {
119 const linkedIds = new Set(
120 input.links.flatMap((link) => (link.status === "expired" ? [] : [link.environmentId])),
121 );
122 const saved = input.environments
123 .filter((environment) => environment.environmentId !== input.threadEnvironmentId)
124 .map((environment) => {
125 const reported = (environment.serverConfig?.directEndpoints ?? []).map(
126 (endpoint) => endpoint.httpBaseUrl,
127 );
128 const routes = connectionRoutes(environment.entry).flatMap((route) => {
129 const url = route.target._tag === "RelayConnectionTarget" ? null : routeHttpBaseUrl(route);
130 return url === null ? [] : [url];
131 });
132 const connect = input.connect.get(environment.environmentId)?.environment.endpoint;
133 return {
134 environmentId: environment.environmentId,
135 label: environment.entry.target.label,
136 machine: resolveEnvironmentMachineKind(environment.serverConfig),
137 connected: environment.connection.phase === "connected",
138 connectOnly: false,
139 linked: linkedIds.has(environment.environmentId),
140 urls: [
141 ...new Set([
142 ...reported,
143 ...routes,
144 ...(connect === undefined ? [] : [connect.httpBaseUrl]),
145 ]),
146 ].filter((url) => !isLoopbackUrl(url)),
147 };
148 });
149 const savedIds = new Set<string>(saved.map((machine) => machine.environmentId));
150 const connectOnly = [...input.connect.values()]
151 .filter(
152 ({ environment }) =>
153 environment.environmentId !== input.threadEnvironmentId &&
154 !savedIds.has(environment.environmentId),
155 )
156 .map(({ environment, status }) => {
157 const descriptor = Option.getOrUndefined(status)?.descriptor;
158 return {
159 environmentId: environment.environmentId,
160 label: environment.label,
161 machine: resolveEnvironmentMachineKind(
162 descriptor === undefined ? null : { environment: descriptor },
163 ),
164 connected: false,
165 connectOnly: true,
166 linked: linkedIds.has(environment.environmentId),
167 urls: [environment.endpoint.httpBaseUrl].filter((url) => !isLoopbackUrl(url)),
168 };
169 });
170 return [...saved, ...connectOnly];
171 }
172
173 const words = (text: string) =>
174 ` ${text
175 .toLowerCase()
176 .split(/[^\p{L}\p{N}]+/u)
177 .join(" ")
178 .trim()} `;
179 const NO_MATCH = 4;
180
181 /**
182 * How well a machine's name matches the agent's hint, which is often the
183 * user's own words ("my box"): exact, prefix, substring, then a hint that
184 * names it among other words ("the box on hetzner").
185 */
186 const hintRank = (label: string, hint: string) => {
187 const name = label.trim().toLowerCase();
188 const wanted = hint
189 .trim()
190 .toLowerCase()
191 .replace(/^(?:my|our|the)\s+/, "");
192 if (name === wanted) return 0;
193 if (name.startsWith(wanted)) return 1;
194 if (name.includes(wanted)) return 2;
195 if (words(wanted).includes(words(name))) return 3;
196 return NO_MATCH;
197 };
198
199 /** The machines best match for the agent's hint first, each rank in catalog order. */
200 export function rankMachinesByHint<T extends { readonly label: string }>(
201 machines: ReadonlyArray<T>,
202 hint: string | undefined,
203 ): ReadonlyArray<T> {
204 if (hint === undefined || hint.trim().length === 0) return machines;
205 return machines
206 .map((machine, index) => ({ machine, index, rank: hintRank(machine.label, hint) }))
207 .sort((a, b) => a.rank - b.rank || a.index - b.index)
208 .map(({ machine }) => machine);
209 }
210
211 /** The machine a card opens on: the one it names, else the hint's best match. */
212 export function linkRequestInitialMachine(
213 item: Pick<LinkRequestItem, "environmentId" | "hint">,
214 machines: ReadonlyArray<LinkableMachine>,
215 ): EnvironmentId | null {
216 if (item.environmentId !== undefined) return item.environmentId;
217 if (item.hint === undefined) return null;
218 const [best] = rankMachinesByHint(machines, item.hint);
219 return best !== undefined && hintRank(best.label, item.hint) < NO_MATCH
220 ? best.environmentId
221 : null;
222 }
223
224 /** The machine choice for linking by an address typed in. */
225 export const ANOTHER_ADDRESS = "another-address";
226
227 /**
228 * What a link request links: a machine from the client's catalog, or an address.
229 * `urls` is empty when the client knows no direct address for the machine,
230 * so the user types one.
231 */
232 export type LinkRequestTarget =
233 | { readonly kind: "none" }
234 | {
235 readonly kind: "machine";
236 readonly environmentId: EnvironmentId;
237 readonly label: string;
238 readonly urls: ReadonlyArray<string>;
239 readonly linked: boolean;
240 }
241 | { readonly kind: "address" };
242
243 /**
244 * Anything can answer at an address as any machine, so an address the agent
245 * gave is a machine only where this client already reaches that machine. Its
246 * pairing code is minted for, and sent to, the client's own addresses alone.
247 */
248 export function linkRequestTarget(
249 item: Pick<LinkRequestItem, "environmentId" | "url">,
250 machines: ReadonlyArray<LinkableMachine>,
251 choice: string | null,
252 resolve: MFunctionType = mFallback,
253 ): LinkRequestTarget {
254 const asked = item.url === undefined ? undefined : originOf(item.url);
255 // Two machines on separate networks can share a private address.
256 const [reached, ...others] =
257 asked === undefined
258 ? []
259 : machines.filter((machine) => machine.urls.some((url) => originOf(url) === asked));
260 const chosen =
261 item.url === undefined
262 ? (item.environmentId ?? choice)
263 : reached !== undefined && others.length === 0
264 ? reached.environmentId
265 : ANOTHER_ADDRESS;
266 if (chosen === null) return { kind: "none" };
267 if (chosen === ANOTHER_ADDRESS) return { kind: "address" };
268 const machine = machines.find((candidate) => candidate.environmentId === chosen);
269 return {
270 kind: "machine",
271 environmentId: machine?.environmentId ?? (chosen as EnvironmentId),
272 label: machine?.label ?? linkRequestTargetName(item, resolve),
273 urls: machine?.urls ?? [],
274 linked: machine?.linked ?? false,
275 };
276 }
277
278 /** What a link request card shows: the actions while pending, otherwise a one-line outcome. */
279 export type LinkRequestDisplay =
280 | { readonly kind: "pending" }
281 | { readonly kind: "pending-elsewhere"; readonly label: string }
282 | {
283 readonly kind: "answered";
284 readonly outcome: "linked" | "declined" | "ended" | "failed";
285 readonly label: string;
286 };
287
288 /**
289 * `visibility` is the projected row's: a request inherited from another
290 * thread (a fork) can only be answered where it was asked. `accessLabel`
291 * names an access level the way the client's access picker does.
292 */
293 export function linkRequestDisplay(
294 item: Pick<LinkRequestItem, "linkStatus" | "url" | "linkedLabel" | "linkedAccess" | "failure">,
295 visibility: "local" | "inherited" | "synthetic",
296 accessLabel: (access: AuthMcpClientAccess) => string,
297 resolve: MFunctionType = mFallback,
298 ): LinkRequestDisplay {
299 switch (item.linkStatus) {
300 case "pending":
301 return visibility === "local"
302 ? { kind: "pending" }
303 : {
304 kind: "pending-elsewhere",
305 label: resolve(msg("Waiting for an answer in the original thread")),
306 };
307 case "linked": {
308 const target =
309 item.linkedLabel ?? (item.url === undefined ? undefined : linkDestination(item.url));
310 const access = item.linkedAccess === undefined ? undefined : accessLabel(item.linkedAccess);
311 return {
312 kind: "answered",
313 outcome: "linked",
314 label:
315 access === undefined
316 ? target === undefined
317 ? resolve(msg("Linked a machine"))
318 : resolve(msg("Linked {target}", { target }))
319 : target === undefined
320 ? resolve(msg("Linked a machine · {access}", { access }))
321 : resolve(msg("Linked {target} · {access}", { target, access })),
322 };
323 }
324 case "declined":
325 return { kind: "answered", outcome: "declined", label: resolve(msg("Declined")) };
326 case "failed":
327 return {
328 kind: "answered",
329 outcome: "failed",
330 label:
331 item.failure === undefined
332 ? resolve(msg("Could not link: the other environment refused"))
333 : resolve(msg("Could not link: {failure}", { failure: item.failure })),
334 };
335 case "cancelled":
336 return { kind: "answered", outcome: "ended", label: resolve(msg("Request ended")) };
337 }
338 }
339
340 /**
341 * Builds the RPC payload for an answer. A link with a blank code returns null,
342 * since the server rejects it; callers keep Link disabled instead.
343 */
344 export function linkRequestAnswerInput(
345 item: Pick<LinkRequestItem, "id" | "threadId">,
346 answer:
347 | {
348 readonly type: "link";
349 /** The machine picked, or an address typed in its place. */
350 readonly target:
351 | Pick<LinkableMachine, "environmentId" | "label" | "urls">
352 | { readonly url: string };
353 readonly access: AuthMcpClientAccess;
354 readonly pairingCode: string;
355 }
356 | { readonly type: "use-existing"; readonly environmentId: EnvironmentId }
357 | { readonly type: "decline" },
358 ): PeerLinkRequestAnswerInput | null {
359 const base = { threadId: item.threadId, turnItemId: item.id };
360 if (answer.type !== "link") return { ...base, answer };
361 const pairingCode = answer.pairingCode.trim();
362 if (pairingCode.length === 0) return null;
363 const { target } = answer;
364 if ("url" in target) {
365 const url = target.url.trim();
366 if (url.length === 0) return null;
367 return { ...base, answer: { type: "link", urls: [url], access: answer.access, pairingCode } };
368 }
369 const [first, ...rest] = target.urls;
370 if (first === undefined) return null;
371 return {
372 ...base,
373 answer: {
374 type: "link",
375 environmentId: target.environmentId,
376 label: target.label,
377 urls: [first, ...rest],
378 access: answer.access,
379 pairingCode,
380 },
381 };
382 }
383
384 /** Failures whose message is written for the user and never echoes the request payload. */
385 const USER_FACING_FAILURE_TAGS = new Set([
386 "PeerLinkRequestError",
387 "EnvironmentAuthorizationError",
388 "PeerPairingCodeError",
389 ]);
390
391 /**
392 * Inline error copy for a failed answer. Only known errors pass their message
393 * through: anything else (transport or encoding failures) gets the generic
394 * copy, so the pairing code can never surface in the UI.
395 */
396 export function linkRequestFailureMessage(
397 failure: unknown,
398 resolve: MFunctionType = mFallback,
399 ): string {
400 if (
401 typeof failure === "object" &&
402 failure !== null &&
403 "_tag" in failure &&
404 typeof failure._tag === "string" &&
405 USER_FACING_FAILURE_TAGS.has(failure._tag) &&
406 "message" in failure &&
407 typeof failure.message === "string" &&
408 failure.message.trim().length > 0
409 ) {
410 return errorDisplayMessage(failure, resolve) ?? failure.message;
411 }
412 return resolve(msg("Could not answer the request. Try again."));
413 }