The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { |
| 2 | type AuthMcpClientAccess, |
| 3 | type EnvironmentId, |
| 4 | type PeerLinkCreateInput, |
| 5 | type PeerLinkFailureKind, |
| 6 | type PeerLinkSummary, |
| 7 | peerLinkFailureKind, |
| 8 | } from "@t3tools/contracts"; |
| 9 | import * as Result from "effect/Result"; |
| 10 | import { mFallback, msg } from "gt-i18n"; |
| 11 | import type { MFunctionType } from "gt-i18n/types"; |
| 12 | |
| 13 | import type { LinkableMachine } from "./linkRequest.ts"; |
| 14 | |
| 15 | /** Pairings a batch opens at once, so a fleet is not signed in to all at the same moment. */ |
| 16 | const LINK_BATCH_CONCURRENCY = 4; |
| 17 | |
| 18 | /** |
| 19 | * Why a batch cannot link a machine: the client mints each pairing code there |
| 20 | * with its own session, and sends it only to addresses it already has for it. |
| 21 | */ |
| 22 | export type LinkBatchBlock = |
| 23 | | "links_unknown" |
| 24 | | "linked" |
| 25 | | "not_connected" |
| 26 | | "no_access" |
| 27 | | "no_address"; |
| 28 | |
| 29 | /** Whether the linking environment's own links are known yet. */ |
| 30 | export type LinkListState = "loading" | "failed" | "loaded"; |
| 31 | |
| 32 | export const linkListState = (query: { |
| 33 | readonly data: unknown; |
| 34 | readonly error: unknown; |
| 35 | }): LinkListState => (query.data !== null ? "loaded" : query.error !== null ? "failed" : "loading"); |
| 36 | |
| 37 | export interface LinkBatchCandidate { |
| 38 | readonly machine: LinkableMachine; |
| 39 | readonly blocked: LinkBatchBlock | null; |
| 40 | } |
| 41 | |
| 42 | /** |
| 43 | * `writable` holds the machines where this client's session may create pairing codes. |
| 44 | * Until `links` has loaded, no machine's `linked` is known, and linking one that is |
| 45 | * already linked would replace its working token, so none is offered. |
| 46 | */ |
| 47 | export const linkBatchCandidates = ( |
| 48 | machines: ReadonlyArray<LinkableMachine>, |
| 49 | writable: ReadonlySet<EnvironmentId>, |
| 50 | links: LinkListState, |
| 51 | ): ReadonlyArray<LinkBatchCandidate> => |
| 52 | machines.map((machine) => ({ |
| 53 | machine, |
| 54 | blocked: |
| 55 | links !== "loaded" |
| 56 | ? "links_unknown" |
| 57 | : machine.linked |
| 58 | ? "linked" |
| 59 | : !machine.connected |
| 60 | ? "not_connected" |
| 61 | : !writable.has(machine.environmentId) |
| 62 | ? "no_access" |
| 63 | : machine.urls.length === 0 |
| 64 | ? "no_address" |
| 65 | : null, |
| 66 | })); |
| 67 | |
| 68 | export const linkBatchBlockLabel = ( |
| 69 | blocked: LinkBatchBlock, |
| 70 | resolve: MFunctionType = mFallback, |
| 71 | ): string => { |
| 72 | switch (blocked) { |
| 73 | case "links_unknown": |
| 74 | return resolve(msg("Not known yet whether it is linked")); |
| 75 | case "linked": |
| 76 | return resolve(msg("Already linked")); |
| 77 | case "not_connected": |
| 78 | return resolve(msg("This app is not connected to it")); |
| 79 | case "no_access": |
| 80 | return resolve(msg("Your session there cannot create pairing codes")); |
| 81 | case "no_address": |
| 82 | return resolve(msg("No address another machine can reach")); |
| 83 | } |
| 84 | }; |
| 85 | |
| 86 | /** Why the link back, from the linked machine to the linking one, is not offered. */ |
| 87 | export type LinkBackBlock = |
| 88 | | "target_links_off" |
| 89 | | "target_no_access" |
| 90 | | "source_no_access" |
| 91 | | "source_no_address"; |
| 92 | |
| 93 | /** |
| 94 | * `hidden`: the user would not expect it, so nothing is shown. `blocked`: both machines are |
| 95 | * the user's own connected environments, so one line says what is in the way. |
| 96 | */ |
| 97 | export type LinkBackOffer = |
| 98 | | { readonly kind: "offered" } |
| 99 | | { readonly kind: "blocked"; readonly reason: LinkBackBlock } |
| 100 | | { readonly kind: "hidden" }; |
| 101 | |
| 102 | /** |
| 103 | * Whether linking `source` to `target` can also link `target` back with no pasted code. The |
| 104 | * reverse is an ordinary link made on the target: the client creates it there and mints its |
| 105 | * pairing code on the source, each with its own session, at an address it has for the source. |
| 106 | */ |
| 107 | export const linkBackOffer = (input: { |
| 108 | /** Null for a machine the client has not saved, such as a typed address. */ |
| 109 | readonly target: { |
| 110 | readonly connected: boolean; |
| 111 | /** Linked environments is supported and switched on there. */ |
| 112 | readonly offersLinks: boolean; |
| 113 | /** The client's session there may create links: `access:write`. */ |
| 114 | readonly writable: boolean; |
| 115 | /** Its own links: null until they are known. */ |
| 116 | readonly links: ReadonlyArray<Pick<PeerLinkSummary, "environmentId" | "status">> | null; |
| 117 | } | null; |
| 118 | readonly source: { |
| 119 | readonly environmentId: EnvironmentId; |
| 120 | readonly connected: boolean; |
| 121 | /** The client's session there may create pairing codes: `access:write`. */ |
| 122 | readonly writable: boolean; |
| 123 | readonly urls: ReadonlyArray<string>; |
| 124 | }; |
| 125 | }): LinkBackOffer => { |
| 126 | const { target, source } = input; |
| 127 | if (target === null || !target.connected || !source.connected) return { kind: "hidden" }; |
| 128 | if (!target.offersLinks) return { kind: "blocked", reason: "target_links_off" }; |
| 129 | if (!target.writable) return { kind: "blocked", reason: "target_no_access" }; |
| 130 | if (!source.writable) return { kind: "blocked", reason: "source_no_access" }; |
| 131 | if (source.urls.length === 0) return { kind: "blocked", reason: "source_no_address" }; |
| 132 | // Unknown or already there: offering it could replace a working token. |
| 133 | if ( |
| 134 | target.links === null || |
| 135 | target.links.some( |
| 136 | (link) => link.environmentId === source.environmentId && link.status !== "expired", |
| 137 | ) |
| 138 | ) { |
| 139 | return { kind: "hidden" }; |
| 140 | } |
| 141 | return { kind: "offered" }; |
| 142 | }; |
| 143 | |
| 144 | export const linkBackBlockLabel = ( |
| 145 | blocked: LinkBackBlock, |
| 146 | names: { readonly source: string; readonly target: string }, |
| 147 | resolve: MFunctionType = mFallback, |
| 148 | ): string => { |
| 149 | switch (blocked) { |
| 150 | case "target_links_off": |
| 151 | return resolve( |
| 152 | msg("{target} cannot link back: Linked environments is off there.", { |
| 153 | target: names.target, |
| 154 | }), |
| 155 | ); |
| 156 | case "target_no_access": |
| 157 | return resolve( |
| 158 | msg("{target} cannot link back: your session there cannot create links.", { |
| 159 | target: names.target, |
| 160 | }), |
| 161 | ); |
| 162 | case "source_no_access": |
| 163 | return resolve( |
| 164 | msg("{target} cannot link back: your session on {source} cannot create pairing codes.", { |
| 165 | source: names.source, |
| 166 | target: names.target, |
| 167 | }), |
| 168 | ); |
| 169 | case "source_no_address": |
| 170 | return resolve( |
| 171 | msg("{target} cannot link back: this app has no address for {source} it can reach.", { |
| 172 | source: names.source, |
| 173 | target: names.target, |
| 174 | }), |
| 175 | ); |
| 176 | } |
| 177 | }; |
| 178 | |
| 179 | export type LinkBatchFailure = PeerLinkFailureKind | "no_code"; |
| 180 | |
| 181 | export type LinkAttemptOutcome = |
| 182 | | { readonly kind: "linked" } |
| 183 | | { readonly kind: "failed"; readonly failure: LinkBatchFailure; readonly detail: string | null }; |
| 184 | |
| 185 | /** `back` is set when the link back was asked for: it never changes how the link itself went. */ |
| 186 | export type LinkBatchOutcome = |
| 187 | | { readonly kind: "linked"; readonly back?: LinkAttemptOutcome } |
| 188 | | { readonly kind: "failed"; readonly failure: LinkBatchFailure; readonly detail: string | null }; |
| 189 | |
| 190 | export const linkBatchFailureLabel = ( |
| 191 | failure: LinkBatchFailure, |
| 192 | resolve: MFunctionType = mFallback, |
| 193 | ): string => { |
| 194 | switch (failure) { |
| 195 | case "unreachable": |
| 196 | return resolve(msg("Unreachable")); |
| 197 | case "code_refused": |
| 198 | return resolve(msg("Pairing code refused")); |
| 199 | case "wrong_environment": |
| 200 | return resolve(msg("Another environment answered")); |
| 201 | case "no_code": |
| 202 | return resolve(msg("Could not get a pairing code there")); |
| 203 | case "other": |
| 204 | return resolve(msg("Could not link")); |
| 205 | } |
| 206 | }; |
| 207 | |
| 208 | /** |
| 209 | * Only the linking environment's own error passes its message through: |
| 210 | * anything else may carry the request, and with it the pairing code. |
| 211 | */ |
| 212 | const linkFailure = (failure: unknown): LinkAttemptOutcome & { readonly kind: "failed" } => { |
| 213 | if ( |
| 214 | typeof failure === "object" && |
| 215 | failure !== null && |
| 216 | "_tag" in failure && |
| 217 | failure._tag === "PeerLinkError" && |
| 218 | "reason" in failure && |
| 219 | "message" in failure && |
| 220 | typeof failure.message === "string" |
| 221 | ) { |
| 222 | const error = failure as unknown as Parameters<typeof peerLinkFailureKind>[0]; |
| 223 | return { kind: "failed", failure: peerLinkFailureKind(error), detail: failure.message }; |
| 224 | } |
| 225 | return { kind: "failed", failure: "other", detail: null }; |
| 226 | }; |
| 227 | |
| 228 | type BatchMachine = Pick<LinkableMachine, "environmentId" | "label" | "urls">; |
| 229 | |
| 230 | type MintPairingCode = ( |
| 231 | environmentId: EnvironmentId, |
| 232 | access: AuthMcpClientAccess, |
| 233 | ) => Promise<Result.Result<string, unknown>>; |
| 234 | |
| 235 | /** |
| 236 | * One link to `machine`: a one-use code minted there with the client's session, handed to |
| 237 | * `link` with the addresses the client has for it. The code stays in this call. |
| 238 | */ |
| 239 | export async function linkWithMintedCode(input: { |
| 240 | readonly machine: BatchMachine; |
| 241 | readonly access: AuthMcpClientAccess; |
| 242 | readonly mint: MintPairingCode; |
| 243 | readonly link: (input: PeerLinkCreateInput) => Promise<Result.Result<unknown, unknown>>; |
| 244 | }): Promise<LinkAttemptOutcome> { |
| 245 | const { machine } = input; |
| 246 | const [url, ...alternateUrls] = machine.urls; |
| 247 | if (url === undefined) return { kind: "failed", failure: "unreachable", detail: null }; |
| 248 | try { |
| 249 | const minted = await input.mint(machine.environmentId, input.access); |
| 250 | if (Result.isFailure(minted)) return { kind: "failed", failure: "no_code", detail: null }; |
| 251 | const linked = await input.link({ |
| 252 | url, |
| 253 | ...(alternateUrls.length > 0 ? { alternateUrls } : {}), |
| 254 | expectedEnvironmentId: machine.environmentId, |
| 255 | expectedLabel: machine.label, |
| 256 | pairingCode: minted.success, |
| 257 | access: input.access, |
| 258 | }); |
| 259 | return Result.isSuccess(linked) ? { kind: "linked" } : linkFailure(linked.failure); |
| 260 | } catch { |
| 261 | return { kind: "failed", failure: "other", detail: null }; |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | /** |
| 266 | * Links each machine as a single link is made: a one-use code minted on that |
| 267 | * machine with the client's session there, then handed to the linking |
| 268 | * environment with the addresses the client has for it. A failure stops only |
| 269 | * its own machine. Codes stay in this call and are never reported. |
| 270 | */ |
| 271 | export async function runLinkBatch(input: { |
| 272 | readonly machines: ReadonlyArray<BatchMachine>; |
| 273 | readonly access: AuthMcpClientAccess; |
| 274 | readonly mint: MintPairingCode; |
| 275 | readonly link: (input: PeerLinkCreateInput) => Promise<Result.Result<unknown, unknown>>; |
| 276 | /** |
| 277 | * Also links each of `targets` back to `source` once its own link is made. `link` creates |
| 278 | * the link on that machine. A failure here is reported beside the link it follows. |
| 279 | */ |
| 280 | readonly back?: { |
| 281 | readonly source: BatchMachine; |
| 282 | readonly targets: ReadonlySet<EnvironmentId>; |
| 283 | readonly link: ( |
| 284 | environmentId: EnvironmentId, |
| 285 | input: PeerLinkCreateInput, |
| 286 | ) => Promise<Result.Result<unknown, unknown>>; |
| 287 | }; |
| 288 | /** Called once, at the end: listing probes every linked machine, so `link` must not refresh. */ |
| 289 | readonly refreshLinks: () => void; |
| 290 | readonly onOutcome?: (environmentId: EnvironmentId, outcome: LinkBatchOutcome) => void; |
| 291 | }): Promise<ReadonlyMap<EnvironmentId, LinkBatchOutcome>> { |
| 292 | const outcomes = new Map<EnvironmentId, LinkBatchOutcome>(); |
| 293 | const { access, mint, back } = input; |
| 294 | const linkOne = async (machine: BatchMachine): Promise<LinkBatchOutcome> => { |
| 295 | const outcome = await linkWithMintedCode({ machine, access, mint, link: input.link }); |
| 296 | if (outcome.kind !== "linked" || !back?.targets.has(machine.environmentId)) return outcome; |
| 297 | return { |
| 298 | kind: "linked", |
| 299 | back: await linkWithMintedCode({ |
| 300 | machine: back.source, |
| 301 | access, |
| 302 | mint, |
| 303 | link: (create) => back.link(machine.environmentId, create), |
| 304 | }), |
| 305 | }; |
| 306 | }; |
| 307 | const queue = [...input.machines]; |
| 308 | const worker = async () => { |
| 309 | for (let machine = queue.shift(); machine !== undefined; machine = queue.shift()) { |
| 310 | const outcome = await linkOne(machine); |
| 311 | outcomes.set(machine.environmentId, outcome); |
| 312 | input.onOutcome?.(machine.environmentId, outcome); |
| 313 | } |
| 314 | }; |
| 315 | await Promise.all(Array.from({ length: LINK_BATCH_CONCURRENCY }, worker)); |
| 316 | if ([...outcomes.values()].some((outcome) => outcome.kind === "linked")) input.refreshLinks(); |
| 317 | return outcomes; |
| 318 | } |
| 319 | |
| 320 | /** How a batch went, and the machines a retry would run again. */ |
| 321 | export const linkBatchSummary = (outcomes: ReadonlyMap<EnvironmentId, LinkBatchOutcome>) => { |
| 322 | const failed = [...outcomes].flatMap(([environmentId, outcome]) => |
| 323 | outcome.kind === "failed" ? [environmentId] : [], |
| 324 | ); |
| 325 | return { linked: outcomes.size - failed.length, failed }; |
| 326 | }; |