Open History to see the last commit
1import {
2 type EnvironmentId,
3 type PeerLinkSummary,
4 type PeerLinkThreadInput,
5 WS_METHODS,
6} from "@t3tools/contracts";
7import * as DateTime from "effect/DateTime";
8import * as Duration from "effect/Duration";
9import * as Effect from "effect/Effect";
10import * as Stream from "effect/Stream";
11import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";
12
13import type { EnvironmentRegistry } from "../connection/registry.ts";
14import {
15 followLinkedThread,
16 keepLinkedThreadView,
17 type LinkedThreadView,
18} from "../linkedThread.ts";
19import { request, subscribe } from "../rpc/client.ts";
20import {
21 createEnvironmentRpcCommand,
22 createEnvironmentRpcQueryAtomFamily,
23 followStreamInEnvironment,
24} from "./runtime.ts";
25
26/** The environment a client reads through, and the linked environment's thread it reads. */
27export interface LinkedThreadViewTarget {
28 readonly environmentId: EnvironmentId;
29 readonly input: PeerLinkThreadInput;
30}
31
32const threadViewKey = ({ environmentId, input }: LinkedThreadViewTarget) =>
33 JSON.stringify({
34 environmentId,
35 input: { environmentId: input.environmentId, threadId: input.threadId },
36 });
37
38export function createPeerLinkEnvironmentAtoms<R, E>(
39 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
40) {
41 const list = createEnvironmentRpcQueryAtomFamily(runtime, {
42 label: "environment-data:peer-links:list",
43 tag: WS_METHODS.peerLinksList,
44 // Listing probes every linked environment, so a list stays fresh briefly.
45 staleTimeMs: 10_000,
46 });
47 // Names only, for opening linked threads with thread read access; it probes nothing.
48 const names = createEnvironmentRpcQueryAtomFamily(runtime, {
49 label: "environment-data:peer-links:names",
50 tag: WS_METHODS.peerLinksNames,
51 staleTimeMs: 10_000,
52 });
53 const refreshLinks = (registry: AtomRegistry.AtomRegistry, environmentId: EnvironmentId) =>
54 Effect.sync(() => {
55 registry.refresh(list({ environmentId, input: {} }));
56 registry.refresh(names({ environmentId, input: {} }));
57 });
58 /**
59 * What a view of the thread last showed. It outlives the subscription for a while, so coming
60 * back to the view shows the thread at once while the stream starts again.
61 */
62 const lastThreadView = Atom.family((key: string) =>
63 Atom.make<LinkedThreadView | null>(null).pipe(
64 Atom.setIdleTTL(5 * 60_000),
65 Atom.withLabel(`environment-data:peer-links:last-thread-view:${key}`),
66 ),
67 );
68 /**
69 * A linked environment's thread, streamed while a view reads it. The subscription ends with its
70 * last reader, which closes the stream at the linked environment too.
71 */
72 const threadView = Atom.family((key: string) => {
73 const { environmentId, input } = JSON.parse(key) as LinkedThreadViewTarget;
74 const kept = lastThreadView(key);
75 const stream = runtime
76 .atom(({ registry }) =>
77 followStreamInEnvironment(
78 environmentId,
79 Stream.suspend(() =>
80 followLinkedThread({
81 items: subscribe(WS_METHODS.peerLinksSubscribeThread, input),
82 historyPage: (cursor) =>
83 request(WS_METHODS.peerLinksThreadHistoryPage, { ...input, cursor }),
84 previous: registry.get(kept),
85 }),
86 ),
87 ),
88 )
89 .pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-data:peer-links:thread-stream:${key}`));
90 return Atom.readable(
91 (get) => {
92 const live = get(stream);
93 if (AsyncResult.isSuccess(live)) {
94 get.set(kept, keepLinkedThreadView(get.once(kept), live.value));
95 }
96 return live;
97 },
98 (refresh) => refresh(stream),
99 ).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-data:peer-links:thread-view:${key}`));
100 });
101 return {
102 list,
103 names,
104 /**
105 * Rereads `environmentId`'s link names when they lack one of `wanted`, however fresh they
106 * are. Links made elsewhere (the CLI, another client, a batch) are not pushed, so a reader
107 * that meets a machine the names lack asks once more; a read under way already answers it.
108 */
109 refreshNamesLacking: (
110 registry: AtomRegistry.AtomRegistry,
111 environmentId: EnvironmentId,
112 wanted: ReadonlyArray<EnvironmentId>,
113 ) => {
114 const atom = names({ environmentId, input: {} });
115 const result = registry.get(atom);
116 if (!AsyncResult.isSuccess(result) || result.waiting) return;
117 const known = new Set(result.value.links.map((link) => link.environmentId));
118 if (wanted.every((id) => known.has(id))) return;
119 registry.refresh(atom);
120 },
121 link: createEnvironmentRpcCommand(runtime, {
122 label: "environment-data:peer-links:link",
123 tag: WS_METHODS.peerLinksLink,
124 onSuccess: ({ environmentId }, registry) => refreshLinks(registry, environmentId),
125 }),
126 // Leaves the list alone: a batch refreshes it once, when it ends (`runLinkBatch`).
127 linkInBatch: createEnvironmentRpcCommand(runtime, {
128 label: "environment-data:peer-links:link-in-batch",
129 tag: WS_METHODS.peerLinksLink,
130 }),
131 unlink: createEnvironmentRpcCommand(runtime, {
132 label: "environment-data:peer-links:unlink",
133 tag: WS_METHODS.peerLinksUnlink,
134 onSuccess: ({ environmentId }, registry) => refreshLinks(registry, environmentId),
135 }),
136 threadView: (target: LinkedThreadViewTarget) => threadView(threadViewKey(target)),
137 lastThreadView: (target: LinkedThreadViewTarget) => lastThreadView(threadViewKey(target)),
138 /** One item of a linked environment's thread in full, for a row the reader opened. */
139 threadItem: createEnvironmentRpcQueryAtomFamily(runtime, {
140 label: "environment-data:peer-links:thread-item",
141 tag: WS_METHODS.peerLinksThreadItem,
142 idleTtlMs: 0,
143 }),
144 /** Asks for a one-time pairing with a linked environment. Its answer is a credential: never cached. */
145 pairClient: createEnvironmentRpcCommand(runtime, {
146 label: "environment-data:peer-links:pair-client",
147 tag: WS_METHODS.peerLinksPairClient,
148 concurrency: {
149 mode: "singleFlight",
150 key: ({ environmentId, input }) => JSON.stringify([environmentId, input.environmentId]),
151 },
152 }),
153 /** Asks for a pairing code from a linked environment, to link another one there. Never cached. */
154 pairLink: createEnvironmentRpcCommand(runtime, {
155 label: "environment-data:peer-links:pair-link",
156 tag: WS_METHODS.peerLinksPairLink,
157 }),
158 // An agent's link card. One answer per card at a time.
159 answerRequest: createEnvironmentRpcCommand(runtime, {
160 label: "environment-data:peer-links:answer-request",
161 tag: WS_METHODS.peerLinksAnswerRequest,
162 concurrency: {
163 mode: "singleFlight",
164 key: ({ environmentId, input }) =>
165 JSON.stringify([environmentId, input.threadId, input.turnItemId]),
166 },
167 onSuccess: ({ environmentId }, registry) => refreshLinks(registry, environmentId),
168 }),
169 };
170}
171
172const EXPIRY_WARNING_DAYS = 5;
173
174export type PeerLinkHealth =
175 | { readonly kind: "reachable"; readonly expiresInDays: number | null }
176 | { readonly kind: "unreachable"; readonly detail: string | null }
177 | { readonly kind: "failing"; readonly detail: string }
178 | { readonly kind: "expired" };
179
180/**
181 * Listing only checks that the peer answers, so a link whose last call failed
182 * (the peer revoked it, say) is `failing` with the recorded reason; the next
183 * successful call clears it.
184 */
185export function peerLinkHealth(link: PeerLinkSummary, now: DateTime.Utc): PeerLinkHealth {
186 if (link.status === "expired" || DateTime.isLessThanOrEqualTo(link.expiresAt, now)) {
187 return { kind: "expired" };
188 }
189 if (link.status === "unreachable") return { kind: "unreachable", detail: link.lastError };
190 if (link.lastError !== null) return { kind: "failing", detail: link.lastError };
191 const days = Math.ceil(Duration.toDays(DateTime.distance(now, link.expiresAt)));
192 return { kind: "reachable", expiresInDays: days <= EXPIRY_WARNING_DAYS ? days : null };
193}
194
195/** A linked machine, and the environment that can get a pairing code from it. */
196export interface LinkThroughRoute {
197 readonly viaEnvironmentId: EnvironmentId;
198 readonly environmentId: EnvironmentId;
199 readonly label: string;
200 readonly urls: ReadonlyArray<string>;
201}
202
203/**
204 * The machines `sourceEnvironmentId` can link to without a pasted code: those another of the
205 * client's environments reaches over a full-access link that answers. `hosts` are environments
206 * the client is connected to and manages access on, the only ones it may ask.
207 */
208export function linkThroughRoutes(input: {
209 readonly sourceEnvironmentId: EnvironmentId;
210 readonly hosts: ReadonlyArray<{
211 readonly environmentId: EnvironmentId;
212 readonly links: ReadonlyArray<PeerLinkSummary>;
213 }>;
214 readonly now: DateTime.Utc;
215}): ReadonlyMap<EnvironmentId, LinkThroughRoute> {
216 const routes = new Map<EnvironmentId, LinkThroughRoute>();
217 for (const host of input.hosts) {
218 if (host.environmentId === input.sourceEnvironmentId) continue;
219 for (const link of host.links) {
220 if (
221 link.environmentId === input.sourceEnvironmentId ||
222 link.access !== "full-access" ||
223 routes.has(link.environmentId) ||
224 peerLinkHealth(link, input.now).kind !== "reachable"
225 ) {
226 continue;
227 }
228 routes.set(link.environmentId, {
229 viaEnvironmentId: host.environmentId,
230 environmentId: link.environmentId,
231 label: link.label,
232 urls: link.urls,
233 });
234 }
235 }
236 return routes;
237}