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

PeerLinks.ts

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