Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PeerLinks.ts

689 lines26.4 KB

1import {
2 AuthMcpClientAccess,
3 AuthMcpRegistrationError,
4 AuthMcpTokenError,
5 EnvironmentHttpApi,
6 EnvironmentId,
7 type ExecutionEnvironmentCapabilities,
8 type ExecutionEnvironmentDescriptor,
9 MCP_PEER_LINK_SOFTWARE_ID,
10 type PeerLink,
11 type PeerLinkCreateInput,
12 PeerLinkError,
13 type PeerLinkSummary,
14} from "@t3tools/contracts";
15import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
16import * as Context from "effect/Context";
17import * as Digest from "effect/crypto/Digest";
18import * as SecureRandom from "effect/crypto/SecureRandom";
19import * as DateTime from "effect/DateTime";
20import * as Duration from "effect/Duration";
21import * as Effect from "effect/Effect";
22import * as Base64Url from "effect/encoding/Base64Url";
23import * as Hex from "effect/encoding/Hex";
24import * as Layer from "effect/Layer";
25import * as Option from "effect/Option";
26import * as Predicate from "effect/Predicate";
27import * as Redacted from "effect/Redacted";
28import * as Result from "effect/Result";
29import * as Schema from "effect/Schema";
30import * as SqlClient from "effect/sql/SqlClient";
31import * as FetchHttpClient from "effect/http/FetchHttpClient";
32import * as HttpClient from "effect/http/HttpClient";
33import * as HttpApi from "effect/http-api/HttpApi";
34import * as HttpApiClient from "effect/http-api/HttpApiClient";
35import { isLocalLoopbackHost, isTailnetHost } from "@t3tools/shared/hostClassification";
36​
37import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
38import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
39import * as ServerSettings from "../serverSettings.ts";
40​
41const PeerHttpApi = HttpApi.make(EnvironmentHttpApi.identifier)
42 .add(EnvironmentHttpApi.groups.metadata)
43 .add(EnvironmentHttpApi.groups.mcpOAuth)
44 .annotateMerge(EnvironmentHttpApi.annotations);
45​
46/** The redirect registered for a link. Nothing ever listens there: the code comes back in the response. */
47const LINK_REDIRECT_URI = "http://127.0.0.1/t3code-peer-link";
48/**
49 * How long a peer's descriptor may take before a route counts as unreachable.
50 * A tailnet or relayed route to a machine that is waking up takes longer.
51 */
52const probeTimeout = (origin: string) =>
53 isLocalLoopbackHost(new URL(origin).hostname) ? Duration.seconds(3) : Duration.seconds(10);
54​
55/** Node's TLS verification code in a failed request's cause chain, if any. */
56export const certificateErrorCode = (error: unknown) => {
57 let current = error;
58 for (let depth = 0; depth < 6 && Predicate.isObject(current); depth++) {
59 if (
60 Predicate.hasProperty(current, "code") &&
61 typeof current.code === "string" &&
62 /CERT|SELF_SIGNED|UNABLE_TO_(GET|VERIFY)|INVALID_(CA|PURPOSE)|PATH_LENGTH_EXCEEDED|HOSTNAME_MISMATCH/.test(
63 current.code,
64 )
65 )
66 return current.code;
67 current = Predicate.hasProperty(current, "cause") ? current.cause : undefined;
68 }
69 return undefined;
70};
71​
72/** A usable link: where to reach the peer and the token to send there. */
73export interface ResolvedPeerLink {
74 readonly link: PeerLink;
75 /** The first address that answered as this peer. */
76 readonly url: string;
77 readonly token: string;
79​
80export const LINKED_ENVIRONMENTS_OFF =
81 "Linked environments is off on this machine. Turn it on in Settings → Labs.";
82​
83/**
84 * Links from this environment to others. Linking signs this environment in to
85 * the peer's `/mcp` as an outside agent with a pairing code from the peer, the
86 * same MCP OAuth flow an outside agent uses, without a browser. The peer's
87 * session token is kept in the server secret store; the table keeps the rest.
88 */
89export class PeerLinks extends Context.Service<
90 PeerLinks,
91 {
92 /** Whether the Linked environments beta (Settings → Labs) is on here. */
93 readonly enabled: Effect.Effect<boolean>;
94 readonly link: (input: PeerLinkCreateInput) => Effect.Effect<PeerLink, PeerLinkError>;
95 /**
96 * The environment answering at `url`, or nothing when it is not a usable
97 * address or does not answer as T3 Code. Sends no credential.
98 */
99 readonly describe: (
100 url: string,
101 ) => Effect.Effect<
102 Option.Option<{ readonly environmentId: EnvironmentId; readonly label: string }>
103 >;
104 readonly list: Effect.Effect<ReadonlyArray<PeerLinkSummary>, PeerLinkError>;
105 /** The stored link, without asking the peer whether it answers. */
106 readonly get: (
107 environmentId: EnvironmentId,
108 ) => Effect.Effect<Option.Option<PeerLink>, PeerLinkError>;
109 /** Forgets the link here. The peer still lists the session until it is revoked there. */
110 readonly unlink: (environmentId: EnvironmentId) => Effect.Effect<boolean, PeerLinkError>;
111 /** An address that answers as the linked peer, with its token, ready to call. */
112 readonly resolve: (
113 environmentId: EnvironmentId,
114 ) => Effect.Effect<ResolvedPeerLink, PeerLinkError>;
115 /** Records the outcome of a call, so listing shows whether the peer answered last time. */
116 readonly recordOutcome: (
117 environmentId: EnvironmentId,
118 outcome: { readonly error: string | null },
119 ) => Effect.Effect<void>;
120 }
121>()("t3/peer/PeerLinks") {}
122​
123interface PeerLinkRow {
124 readonly environment_id: string;
125 readonly secret_name: string;
126 readonly label: string;
127 readonly urls_json: string;
128 readonly access: string;
129 readonly linked_at: string;
130 readonly expires_at: string;
131 readonly last_reached_at: string | null;
132 readonly last_error: string | null;
133 readonly fenced: number;
135​
136const decodeUrls = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Array(Schema.String)));
137const encodeUrls = Schema.encodeEffect(Schema.fromJsonString(Schema.Array(Schema.String)));
138const decodeAccess = Schema.decodeUnknownEffect(AuthMcpClientAccess);
139​
140/** Fails with a fixed storage error that keeps its cause; the log gets the details. */
141const failStorage = (cause: unknown) =>
142 Effect.logWarning("Peer link storage failed", cause).pipe(
143 Effect.andThen(
144 Effect.fail(
145 new PeerLinkError({
146 reason: "storage",
147 message:
148 "Linked environments could not be read or saved here. The server log has details.",
149 cause,
150 }),
151 ),
152 ),
153 );
154​
155/**
156 * The base URL a peer is reached at, normalised to its origin. The pairing
157 * code and then the link's token travel to it, so plain http is accepted only
158 * where the network already encrypts: this machine, or a Tailscale address.
159 */
160const peerOrigin = (url: string) => {
161 const parsed = URL.parse(url);
162 if (parsed === null || (parsed.protocol !== "https:" && parsed.protocol !== "http:")) {
163 return Effect.fail(
164 new PeerLinkError({
165 reason: "unreachable",
166 message: `${url} is not an http or https address.`,
167 }),
168 );
169 }
170 if (
171 parsed.protocol === "http:" &&
172 !isLocalLoopbackHost(parsed.hostname) &&
173 !isTailnetHost(parsed.hostname)
174 ) {
175 return Effect.fail(
176 new PeerLinkError({
177 reason: "unreachable",
178 message: `${url} is plain http, which would send the link's credentials unencrypted. Use its https address, or its Tailscale address.`,
179 }),
180 );
181 }
182 return Effect.succeed(parsed.origin);
183};
184​
185/** Whether a peer holds a linked agent to its limits and keeps its work within its link. */
186const linkLimitsHold = (peer: { readonly capabilities: ExecutionEnvironmentCapabilities }) =>
187 peer.capabilities.mcpModeLimitHeader === true && peer.capabilities.linkFence === true;
188​
189const make = Effect.gen(function* () {
190 const sql = yield* SqlClient.SqlClient;
191 const secrets = yield* ServerSecretStore.ServerSecretStore;
192 const random = yield* SecureRandom.SecureRandom;
193 const digest = yield* Digest.Digest;
194 const httpClient = yield* HttpClient.HttpClient;
195 const environment = yield* ServerEnvironment.ServerEnvironment;
196 const serverSettings = yield* ServerSettings.ServerSettingsService;
197 const enabled = serverSettings.getSettings.pipe(
198 Effect.map((settings) => settings.linkedEnvironmentsEnabled),
199 Effect.orElseSucceed(() => false),
200 );
201​
202 /** A fresh name for one link's token; the row records it. */
203 const newSecretName = random.randomBytes(16).pipe(
204 Effect.map((bytes) => `peer-link-${Hex.encode(bytes)}`),
205 Effect.orDie,
206 );
207​
208 // Only the origin `peerOrigin` checked may receive a pairing code or token:
209 // a redirect could forward them anywhere, including plain http.
210 const peerHttpClient = HttpClient.transform(httpClient, (response) =>
211 Effect.provideService(response, FetchHttpClient.RequestInit, { redirect: "manual" }),
212 );
213​
214 const clientFor = (origin: string) =>
215 HttpApiClient.make(PeerHttpApi, { baseUrl: origin }).pipe(
216 Effect.provideService(HttpClient.HttpClient, peerHttpClient),
217 );
218​
219 /**
220 * The environment answering at `origin`, or nothing when it does not answer
221 * as T3 Code. A certificate this machine rejects fails instead, since
222 * the peer may well be there.
223 */
224 const describe = (origin: string) =>
225 clientFor(origin).pipe(
226 Effect.flatMap((client) => client.metadata.descriptor()),
227 Effect.timeout(probeTimeout(origin)),
228 Effect.asSome,
229 Effect.catch((error) => {
230 const code = certificateErrorCode(error);
231 return code === undefined
232 ? Effect.succeed(Option.none<ExecutionEnvironmentDescriptor>())
233 : Effect.fail(
234 new PeerLinkError({
235 reason: "unreachable",
236 message: `${origin} presented a certificate this machine rejected (${code}).`,
237 }),
238 );
239 }),
240 );
241​
242 /** Whether `url` answers as `environmentId`, counting an untrusted certificate as no. */
243 const answersAs = Effect.fn("PeerLinks.answersAs")(function* (
244 url: string,
245 environmentId: EnvironmentId,
246 ) {
247 const found = yield* describe(url).pipe(Effect.orElseSucceed(() => Option.none()));
248 return Option.filter(found, (peer) => peer.environmentId === environmentId);
249 });
250​
251 const toLink = Effect.fn("PeerLinks.toLink")(function* (row: PeerLinkRow) {
252 return {
253 environmentId: EnvironmentId.make(row.environment_id),
254 label: row.label,
255 urls: yield* decodeUrls(row.urls_json),
256 access: yield* decodeAccess(row.access),
257 linkedAt: DateTime.makeUnsafe(row.linked_at),
258 // Its token predates link fencing, so the peer would not fence its work:
259 // like an expired link, only a new pairing code brings it back.
260 expiresAt: DateTime.makeUnsafe(row.fenced === 1 ? row.expires_at : row.linked_at),
261 lastReachedAt: row.last_reached_at === null ? null : DateTime.makeUnsafe(row.last_reached_at),
262 lastError: row.last_error,
263 } satisfies PeerLink;
264 }, Effect.catch(failStorage));
265​
266 const readRows = sql<PeerLinkRow>`
267 SELECT * FROM peer_environment_links ORDER BY label, environment_id
268 `.pipe(NodeSqliteClient.readOnly, Effect.catch(failStorage));
269​
270 const readRow = (environmentId: EnvironmentId) =>
271 sql<PeerLinkRow>`
272 SELECT * FROM peer_environment_links WHERE environment_id = ${environmentId}
273 `.pipe(
274 NodeSqliteClient.readOnly,
275 Effect.catch(failStorage),
276 Effect.map((rows) => Option.fromNullishOr(rows[0])),
277 );
278​
279 /** Signs in to the peer's `/mcp` with a pairing code: register, decide, exchange. */
280 const signIn = Effect.fn("PeerLinks.signIn")(
281 function* (origin: string, input: PeerLinkCreateInput, clientName: string) {
282 const client = yield* clientFor(origin);
283 // Only the peer's own refusals are rejections. A dropped connection or
284 // an answer this version cannot read is classified below.
285 const registered = yield* client.mcpOAuth
286 .register({
287 payload: {
288 client_name: clientName,
289 redirect_uris: [LINK_REDIRECT_URI],
290 software_id: MCP_PEER_LINK_SOFTWARE_ID,
291 },
292 })
293 .pipe(
294 // A plain Schema.Error has no tag to catch by.
295 Effect.catchIf(Schema.is(AuthMcpRegistrationError), (error) =>
296 Effect.fail(
297 new PeerLinkError({
298 reason: "pairing_rejected",
299 message: `The peer refused to register this environment: ${error.message}`,
300 }),
301 ),
302 ),
303 );
304 const verifier = Base64Url.encode(yield* random.randomBytes(32));
305 const challenge = Base64Url.encode(
306 yield* digest.digest(Digest.sha256, new TextEncoder().encode(verifier)).pipe(Effect.orDie),
307 );
308 const state = Base64Url.encode(yield* random.randomBytes(16));
309 const resource = `${origin}/mcp`;
310 const decided = yield* client.mcpOAuth
311 .decision({
312 payload: {
313 authorization: {
314 response_type: "code",
315 client_id: registered.client_id,
316 redirect_uri: LINK_REDIRECT_URI,
317 code_challenge: challenge,
318 code_challenge_method: "S256",
319 state: Redacted.make(state),
320 resource,
321 },
322 decision: { _tag: "pairing-code", access: input.access, code: input.pairingCode },
323 },
324 })
325 .pipe(
326 Effect.catchTags({
327 AuthMcpApprovalError: (error) =>
328 Effect.fail(
329 new PeerLinkError({ reason: "pairing_rejected", message: error.message }),
330 ),
331 }),
332 );
333 const redirect = URL.parse(decided.redirectTo);
334 if (redirect === null) {
335 return yield* new PeerLinkError({
336 reason: "incompatible",
337 message: `${origin} answered the sign-in with an address this version cannot read. Update both environments.`,
338 });
339 }
340 const code = redirect.searchParams.get("code");
341 if (code === null || redirect.searchParams.get("state") !== state) {
342 return yield* new PeerLinkError({
343 reason: "pairing_rejected",
344 message:
345 redirect.searchParams.get("error_description") ??
346 "The peer did not approve the link. Check the pairing code and try again.",
347 });
348 }
349 return yield* client.mcpOAuth
350 .token({
351 payload: {
352 grant_type: "authorization_code",
353 code: Redacted.make(code),
354 redirect_uri: LINK_REDIRECT_URI,
355 client_id: registered.client_id,
356 code_verifier: Redacted.make(verifier),
357 resource,
358 },
359 })
360 .pipe(
361 Effect.catchIf(Schema.is(AuthMcpTokenError), (error) =>
362 Effect.fail(
363 new PeerLinkError({
364 reason: "pairing_rejected",
365 message: `The peer refused the sign-in: ${error.message}`,
366 }),
367 ),
368 ),
369 );
370 },
371 (effect, origin) =>
372 effect.pipe(
373 // Endpoint errors are mapped above; what is left is the transport or an
374 // answer this version cannot decode.
375 Effect.catchTags({
376 SchemaError: (cause) =>
377 Effect.fail(
378 new PeerLinkError({
379 reason: "incompatible",
380 message: `${origin} answered in a shape this version does not understand. Update both environments.`,
381 cause,
382 }),
383 ),
384 HttpClientError: (cause) =>
385 Effect.fail(
386 new PeerLinkError({
387 reason: "unreachable",
388 message: `${origin} stopped answering while linking.`,
389 cause,
390 }),
391 ),
392 }),
393 ),
394 );
395​
396 /**
397 * The addresses that answer as `environmentId`, in the order given, with
398 * what the first one answered. Addresses this environment would not send
399 * credentials to are skipped; when every one is, the failure says why.
400 */
401 const answeringAs = Effect.fn("PeerLinks.answeringAs")(function* (
402 urls: ReadonlyArray<string>,
403 environmentId: EnvironmentId,
404 name: string,
405 ) {
406 const checked = yield* Effect.forEach(
407 urls,
408 (url) =>
409 Effect.gen(function* () {
410 const origin = yield* peerOrigin(url);
411 return { origin, descriptor: yield* describe(origin) };
412 }).pipe(Effect.result),
413 { concurrency: "unbounded" },
414 );
415 const matching = checked.flatMap((result) =>
416 Result.isSuccess(result) &&
417 Option.isSome(result.success.descriptor) &&
418 result.success.descriptor.value.environmentId === environmentId
419 ? [{ origin: result.success.origin, descriptor: result.success.descriptor.value }]
420 : [],
421 );
422 const first = matching[0];
423 if (first === undefined) {
424 const refusals = checked.flatMap((result) =>
425 Result.isFailure(result) ? [result.failure.message] : [],
426 );
427 return yield* new PeerLinkError({
428 reason: "unreachable",
429 message:
430 refusals.length === checked.length
431 ? `This environment could not reach ${name}: ${refusals.join(" ")}`
432 : `This environment could not reach ${name} at ${urls.join(", ")}.`,
433 });
434 }
435 // Each address is kept once, even when two spellings share an origin.
436 const origins = [...new Set(matching.map((found) => found.origin))];
437 return { primary: first.origin, peer: first.descriptor, origins };
438 });
439​
440 /** The peer at `url`, with every address checked for credentials first. */
441 const answeringAt = Effect.fn("PeerLinks.answeringAt")(function* (urls: ReadonlyArray<string>) {
442 const origins = yield* Effect.forEach(urls, peerOrigin);
443 const primary = origins[0]!;
444 const descriptor = yield* describe(primary);
445 if (Option.isNone(descriptor)) {
446 return yield* new PeerLinkError({
447 reason: "not_a_t3_environment",
448 message: `Nothing at ${primary} answered as a T3 Code environment.`,
449 });
450 }
451 return { primary, peer: descriptor.value, origins };
452 });
453​
454 const link: PeerLinks["Service"]["link"] = Effect.fn("PeerLinks.link")(function* (input) {
455 if (!(yield* enabled)) {
456 return yield* new PeerLinkError({ reason: "disabled", message: LINKED_ENVIRONMENTS_OFF });
457 }
458 const urls = [input.url, ...(input.alternateUrls ?? [])];
459 // The user picked a machine: link through the addresses that prove to
460 // be it, so a reused LAN address never receives the pairing code.
461 const { primary, peer, origins } =
462 input.expectedEnvironmentId === undefined
463 ? yield* answeringAt(urls)
464 : yield* answeringAs(
465 urls,
466 input.expectedEnvironmentId,
467 input.expectedLabel ?? input.expectedEnvironmentId,
468 );
469 const self = yield* environment.getDescriptor;
470 if (peer.environmentId === self.environmentId) {
471 return yield* new PeerLinkError({
472 reason: "self",
473 message: "That address is this environment.",
474 });
475 }
476 if (!linkLimitsHold(peer)) {
477 return yield* new PeerLinkError({
478 reason: "incompatible",
479 message: `${peer.label} runs a T3 Code version that cannot keep a linked agent's limits. Update it, then link again.`,
480 });
481 }
482 const issued = yield* signIn(primary, input, `T3 Code · ${self.label}`);
483 const now = yield* DateTime.now;
484 const linked: PeerLink = {
485 environmentId: peer.environmentId,
486 label: peer.label,
487 urls: origins,
488 access: input.access,
489 linkedAt: now,
490 expiresAt: DateTime.add(now, { seconds: issued.expires_in }),
491 lastReachedAt: now,
492 lastError: null,
493 };
494 // The token goes under a name of its own before the row points at it,
495 // so the row and its token are replaced together.
496 const secretName = yield* newSecretName;
497 yield* secrets
498 .set(secretName, new TextEncoder().encode(issued.access_token))
499 .pipe(Effect.catch(failStorage));
500 // A token no row names could never be removed.
501 const previous = yield* Effect.gen(function* () {
502 const urlsJson = yield* encodeUrls(origins).pipe(Effect.catch(failStorage));
503 const previous = yield* readRow(peer.environmentId);
504 yield* sql`
505 INSERT INTO peer_environment_links (
506 environment_id, secret_name, label, urls_json, access, linked_at, expires_at,
507 last_reached_at, last_error, fenced
508 ) VALUES (
509 ${linked.environmentId}, ${secretName}, ${linked.label}, ${urlsJson}, ${linked.access},
510 ${DateTime.formatIso(linked.linkedAt)}, ${DateTime.formatIso(linked.expiresAt)},
511 ${DateTime.formatIso(now)}, NULL, 1
512 )
513 ON CONFLICT (environment_id) DO UPDATE SET
514 secret_name = excluded.secret_name,
515 fenced = excluded.fenced,
516 label = excluded.label,
517 urls_json = excluded.urls_json,
518 access = excluded.access,
519 linked_at = excluded.linked_at,
520 expires_at = excluded.expires_at,
521 last_reached_at = excluded.last_reached_at,
522 last_error = NULL
523 `.pipe(Effect.catch(failStorage));
524 return previous;
525 }).pipe(Effect.onError(() => secrets.remove(secretName).pipe(Effect.ignore)));
526 // Linking again replaces the old token. A racing link may leave its own
527 // behind; it is unused either way.
528 if (Option.isSome(previous) && previous.value.secret_name !== secretName) {
529 yield* secrets.remove(previous.value.secret_name).pipe(Effect.ignore);
530 }
531 return linked;
532 });
533​
534 const describeUrl: PeerLinks["Service"]["describe"] = (url) =>
535 peerOrigin(url).pipe(
536 Effect.flatMap(describe),
537 Effect.map(Option.map((peer) => ({ environmentId: peer.environmentId, label: peer.label }))),
538 Effect.orElseSucceed(() => Option.none()),
539 );
540​
541 /** A peer's label follows its machine name, so the link takes the one its own address answers with. */
542 const withLabel = (link: PeerLink, label: string) =>
543 label === link.label
544 ? Effect.succeed(link)
545 : sql`
546 UPDATE peer_environment_links SET label = ${label}
547 WHERE environment_id = ${link.environmentId}
548 `.pipe(Effect.ignoreCause({ log: true }), Effect.as({ ...link, label }));
549​
550 const statusOf = Effect.fn("PeerLinks.statusOf")(function* (
551 link: PeerLink,
552 now: DateTime.Utc,
553 ): Effect.fn.Return<PeerLinkSummary> {
554 if (DateTime.isLessThanOrEqualTo(link.expiresAt, now)) return { ...link, status: "expired" };
555 let label = link.label;
556 const answered = yield* Effect.findFirst(link.urls, (url) =>
557 answersAs(url, link.environmentId).pipe(
558 Effect.map((found) => {
559 if (Option.isNone(found)) return false;
560 label = found.value.label;
561 return true;
562 }),
563 ),
564 );
565 if (Option.isNone(answered)) return { ...link, status: "unreachable" };
566 return { ...(yield* withLabel(link, label)), status: "reachable" };
567 });
568​
569 const list: PeerLinks["Service"]["list"] = Effect.gen(function* () {
570 const links = yield* Effect.forEach(yield* readRows, toLink);
571 const now = yield* DateTime.now;
572 return yield* Effect.forEach(links, (link) => statusOf(link, now), {
573 concurrency: "unbounded",
574 });
575 });
576​
577 const get: PeerLinks["Service"]["get"] = (environmentId) =>
578 readRow(environmentId).pipe(
579 Effect.flatMap(
580 Option.match({
581 onNone: () => Effect.succeedNone,
582 onSome: (row) => Effect.asSome(toLink(row)),
583 }),
584 ),
585 );
586​
587 const unlink: PeerLinks["Service"]["unlink"] = Effect.fn("PeerLinks.unlink")(
588 function* (environmentId) {
589 const deleted = yield* sql<{ secret_name: string }>`
590 DELETE FROM peer_environment_links WHERE environment_id = ${environmentId}
591 RETURNING secret_name
592 `.pipe(Effect.catch(failStorage));
593 for (const row of deleted) {
594 yield* secrets.remove(row.secret_name).pipe(Effect.catch(failStorage));
595 }
596 return deleted.length > 0;
597 },
598 );
599​
600 const resolve: PeerLinks["Service"]["resolve"] = Effect.fn("PeerLinks.resolve")(
601 function* (environmentId) {
602 const row = yield* readRow(environmentId);
603 if (Option.isNone(row)) {
604 return yield* new PeerLinkError({
605 reason: "unknown_link",
606 message: `This environment is not linked to ${environmentId}. t3_environment_links lists the linked ones.`,
607 });
608 }
609 const link = yield* toLink(row.value);
610 if (DateTime.isLessThanOrEqualTo(link.expiresAt, yield* DateTime.now)) {
611 return yield* new PeerLinkError({
612 reason: "expired",
613 message: `The link to ${link.label} expired. Link it again with a new pairing code from ${link.label}.`,
614 });
615 }
616 const stored = yield* secrets.get(row.value.secret_name).pipe(Effect.catch(failStorage));
617 if (Option.isNone(stored)) {
618 return yield* new PeerLinkError({
619 reason: "unknown_link",
620 message: `The link to ${link.label} lost its credential. Link it again.`,
621 });
622 }
623 // The token goes only to an address that proves it is this peer, so a
624 // reused LAN address or a moved hostname never receives it.
625 let fenced = true;
626 let label = link.label;
627 const url = yield* Effect.findFirst(link.urls, (candidate) =>
628 answersAs(candidate, environmentId).pipe(
629 Effect.map((found) => {
630 if (Option.isNone(found)) return false;
631 fenced = linkLimitsHold(found.value);
632 label = found.value.label;
633 return true;
634 }),
635 ),
636 );
637 if (Option.isNone(url)) {
638 return yield* new PeerLinkError({
639 reason: "unreachable",
640 message: `${link.label} did not answer at ${link.urls.join(", ")}.`,
641 });
642 }
643 // A link made before the peer had to fence linked work, or a peer moved
644 // back to such a version, would carry work past those limits.
645 if (!fenced) {
646 return yield* new PeerLinkError({
647 reason: "incompatible",
648 message: `${link.label} runs a T3 Code version that cannot keep a linked agent's limits. Update it, then link again.`,
649 });
650 }
651 return {
652 link: yield* withLabel(link, label),
653 url: url.value,
654 token: new TextDecoder().decode(stored.value),
655 };
656 },
657 );
658​
659 const recordOutcome: PeerLinks["Service"]["recordOutcome"] = (environmentId, outcome) =>
660 DateTime.now.pipe(
661 Effect.flatMap((now) =>
662 outcome.error === null
663 ? sql`
664 UPDATE peer_environment_links
665 SET last_reached_at = ${DateTime.formatIso(now)}, last_error = NULL
666 WHERE environment_id = ${environmentId}
667 `
668 : sql`
669 UPDATE peer_environment_links SET last_error = ${outcome.error}
670 WHERE environment_id = ${environmentId}
671 `,
672 ),
673 Effect.asVoid,
674 Effect.ignoreCause({ log: true }),
675 );
676​
677 return PeerLinks.of({
678 enabled,
679 link,
680 describe: describeUrl,
681 list,
682 get,
683 unlink,
684 resolve,
685 recordOutcome,
686 });
687});
688​
689export const layer = Layer.effect(PeerLinks, make);