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

PeerLinks.ts

628 lines24.1 KB

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