Open History to see the last commit
1import {
2 type EnvironmentId,
3 isMovedThreadId,
4 linkOriginIsFenced,
5 type OrchestrationV2ThreadShell,
6 type PeerLinkSummary,
7 type PeerLinkThreadInput,
8 WS_METHODS,
9} from "@t3tools/contracts";
10import * as DateTime from "effect/DateTime";
11import * as Duration from "effect/Duration";
12import * as Effect from "effect/Effect";
13import * as Stream from "effect/Stream";
14import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";
15
16import type { EnvironmentRegistry } from "../connection/registry.ts";
17import {
18 followLinkedThread,
19 keepLinkedThreadView,
20 type LinkedThreadView,
21} from "../linkedThread.ts";
22import { request, subscribe } from "../rpc/client.ts";
23import {
24 createEnvironmentRpcCommand,
25 createEnvironmentRpcQueryAtomFamily,
26 followStreamInEnvironment,
27} from "./runtime.ts";
28
29/** The environment a client reads through, and the linked environment's thread it reads. */
30export interface LinkedThreadViewTarget {
31 readonly environmentId: EnvironmentId;
32 readonly input: PeerLinkThreadInput;
33}
34
35const threadViewKey = ({ environmentId, input }: LinkedThreadViewTarget) =>
36 JSON.stringify({
37 environmentId,
38 input: { environmentId: input.environmentId, threadId: input.threadId },
39 });
40
41export function createPeerLinkEnvironmentAtoms<R, E>(
42 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
43) {
44 const list = createEnvironmentRpcQueryAtomFamily(runtime, {
45 label: "environment-data:peer-links:list",
46 tag: WS_METHODS.peerLinksList,
47 // Listing probes every linked environment, so a list stays fresh briefly.
48 staleTimeMs: 10_000,
49 });
50 // Names only, for opening linked threads with thread read access; it probes nothing.
51 const names = createEnvironmentRpcQueryAtomFamily(runtime, {
52 label: "environment-data:peer-links:names",
53 tag: WS_METHODS.peerLinksNames,
54 staleTimeMs: 10_000,
55 });
56 const refreshLinks = (registry: AtomRegistry.AtomRegistry, environmentId: EnvironmentId) =>
57 Effect.sync(() => {
58 registry.refresh(list({ environmentId, input: {} }));
59 registry.refresh(names({ environmentId, input: {} }));
60 });
61 /**
62 * What a view of the thread last showed. It outlives the subscription for a while, so coming
63 * back to the view shows the thread at once while the stream starts again.
64 */
65 const lastThreadView = Atom.family((key: string) =>
66 Atom.make<LinkedThreadView | null>(null).pipe(
67 Atom.setIdleTTL(5 * 60_000),
68 Atom.withLabel(`environment-data:peer-links:last-thread-view:${key}`),
69 ),
70 );
71 /**
72 * A linked environment's thread, streamed while a view reads it. The subscription ends with its
73 * last reader, which closes the stream at the linked environment too.
74 */
75 const threadView = Atom.family((key: string) => {
76 const { environmentId, input } = JSON.parse(key) as LinkedThreadViewTarget;
77 const kept = lastThreadView(key);
78 const stream = runtime
79 .atom(({ registry }) =>
80 followStreamInEnvironment(
81 environmentId,
82 Stream.suspend(() =>
83 followLinkedThread({
84 items: subscribe(WS_METHODS.peerLinksSubscribeThread, input),
85 historyPage: (cursor) =>
86 request(WS_METHODS.peerLinksThreadHistoryPage, { ...input, cursor }),
87 previous: registry.get(kept),
88 }),
89 ),
90 ),
91 )
92 .pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-data:peer-links:thread-stream:${key}`));
93 return Atom.readable(
94 (get) => {
95 const live = get(stream);
96 if (AsyncResult.isSuccess(live)) {
97 get.set(kept, keepLinkedThreadView(get.once(kept), live.value));
98 }
99 return live;
100 },
101 (refresh) => refresh(stream),
102 ).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-data:peer-links:thread-view:${key}`));
103 });
104 return {
105 list,
106 names,
107 /**
108 * Rereads `environmentId`'s link names when they lack one of `wanted`, however fresh they
109 * are. Links made elsewhere (the CLI, another client, a batch) are not pushed, so a reader
110 * that meets a machine the names lack asks once more; a read under way already answers it.
111 */
112 refreshNamesLacking: (
113 registry: AtomRegistry.AtomRegistry,
114 environmentId: EnvironmentId,
115 wanted: ReadonlyArray<EnvironmentId>,
116 ) => {
117 const atom = names({ environmentId, input: {} });
118 const result = registry.get(atom);
119 if (!AsyncResult.isSuccess(result) || result.waiting) return;
120 const known = new Set(result.value.links.map((link) => link.environmentId));
121 if (wanted.every((id) => known.has(id))) return;
122 registry.refresh(atom);
123 },
124 link: createEnvironmentRpcCommand(runtime, {
125 label: "environment-data:peer-links:link",
126 tag: WS_METHODS.peerLinksLink,
127 onSuccess: ({ environmentId }, registry) => refreshLinks(registry, environmentId),
128 }),
129 // Leaves the list alone: a batch refreshes it once, when it ends (`runLinkBatch`).
130 linkInBatch: createEnvironmentRpcCommand(runtime, {
131 label: "environment-data:peer-links:link-in-batch",
132 tag: WS_METHODS.peerLinksLink,
133 }),
134 unlink: createEnvironmentRpcCommand(runtime, {
135 label: "environment-data:peer-links:unlink",
136 tag: WS_METHODS.peerLinksUnlink,
137 onSuccess: ({ environmentId }, registry) => refreshLinks(registry, environmentId),
138 }),
139 threadView: (target: LinkedThreadViewTarget) => threadView(threadViewKey(target)),
140 lastThreadView: (target: LinkedThreadViewTarget) => lastThreadView(threadViewKey(target)),
141 /** One item of a linked environment's thread in full, for a row the reader opened. */
142 threadItem: createEnvironmentRpcQueryAtomFamily(runtime, {
143 label: "environment-data:peer-links:thread-item",
144 tag: WS_METHODS.peerLinksThreadItem,
145 idleTtlMs: 0,
146 }),
147 /** Asks for a one-time pairing with a linked environment. Its answer is a credential: never cached. */
148 pairClient: createEnvironmentRpcCommand(runtime, {
149 label: "environment-data:peer-links:pair-client",
150 tag: WS_METHODS.peerLinksPairClient,
151 concurrency: {
152 mode: "singleFlight",
153 key: ({ environmentId, input }) => JSON.stringify([environmentId, input.environmentId]),
154 },
155 }),
156 /** Asks for a pairing code from a linked environment, to link another one there. Never cached. */
157 pairLink: createEnvironmentRpcCommand(runtime, {
158 label: "environment-data:peer-links:pair-link",
159 tag: WS_METHODS.peerLinksPairLink,
160 }),
161 // An agent's link card. One answer per card at a time.
162 answerRequest: createEnvironmentRpcCommand(runtime, {
163 label: "environment-data:peer-links:answer-request",
164 tag: WS_METHODS.peerLinksAnswerRequest,
165 concurrency: {
166 mode: "singleFlight",
167 key: ({ environmentId, input }) =>
168 JSON.stringify([environmentId, input.threadId, input.turnItemId]),
169 },
170 onSuccess: ({ environmentId }, registry) => refreshLinks(registry, environmentId),
171 }),
172 };
173}
174
175/** Moving threads to linked environments, as one environment's server does it. */
176export function createThreadHandoffEnvironmentAtoms<R, E>(
177 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
178) {
179 const sameThread = {
180 mode: "singleFlight" as const,
181 key: (target: {
182 readonly environmentId: EnvironmentId;
183 readonly input: { threadId: string };
184 }) => JSON.stringify([target.environmentId, target.input.threadId]),
185 };
186 const adopt = createEnvironmentRpcCommand(runtime, {
187 label: "environment-data:thread-handoff:adopt",
188 tag: WS_METHODS.threadHandoffAdopt,
189 concurrency: sameThread,
190 });
191 return {
192 adopt,
193 options: createEnvironmentRpcQueryAtomFamily(runtime, {
194 label: "environment-data:thread-handoff:options",
195 tag: WS_METHODS.threadHandoffOptions,
196 // Each read asks every linked environment for a matching project.
197 staleTimeMs: 15_000,
198 }),
199 start: createEnvironmentRpcCommand(runtime, {
200 label: "environment-data:thread-handoff:start",
201 tag: WS_METHODS.threadHandoffStart,
202 concurrency: sameThread,
203 // The user who moved the thread makes it theirs where it landed, when this client has
204 // its own connection there. Otherwise the thread offers that itself once they open it.
205 onSuccess: (_target, registry, moved) =>
206 moved.state === "departed"
207 ? adopt
208 .run(registry, {
209 environmentId: moved.environmentId,
210 input: { threadId: moved.threadId },
211 })
212 .pipe(Effect.ignore)
213 : Effect.void,
214 }),
215 cancel: createEnvironmentRpcCommand(runtime, {
216 label: "environment-data:thread-handoff:cancel",
217 tag: WS_METHODS.threadHandoffCancel,
218 concurrency: sameThread,
219 }),
220 };
221}
222
223type ThreadHandoff = NonNullable<OrchestrationV2ThreadShell["handoff"]>;
224
225/**
226 * Whether a thread was moved here over a link below full access and nobody here has taken it
227 * over yet: its agent may still change only what that link started.
228 */
229export const threadAwaitsAdoption = (thread: {
230 readonly id: string;
231 readonly linkOrigin?: OrchestrationV2ThreadShell["linkOrigin"] | null;
232}): boolean =>
233 isMovedThreadId(thread.id) && thread.linkOrigin != null && linkOriginIsFenced(thread.linkOrigin);
234
235/** A thread can start a move unless one is waiting, under way or done. */
236export const threadCanStartHandoff = (handoff: ThreadHandoff | null | undefined): boolean =>
237 handoff == null || handoff.state === "failed";
238
239/**
240 * The machine a move starts on before the user picks: `preferred` while it can take the thread,
241 * else the only one that can. Several with no preference leave the choice blank.
242 */
243export const defaultHandoffTarget = <
244 Option extends {
245 readonly environmentId: EnvironmentId;
246 readonly reason: string | null;
247 readonly projectSelectionRequired?: boolean;
248 },
249>(
250 options: ReadonlyArray<Option>,
251 preferred: EnvironmentId | null | undefined,
252): Option | undefined => {
253 const movable = options.filter(
254 (option) => option.reason === null || option.projectSelectionRequired,
255 );
256 return (
257 movable.find((option) => option.environmentId === preferred) ??
258 (movable.length === 1 ? movable[0] : undefined)
259 );
260};
261
262/** The copy left behind takes no messages once the move is under way. */
263export const threadHandoffClosesComposer = (
264 handoff: ThreadHandoff | null | undefined,
265): handoff is Extract<ThreadHandoff, { state: "departing" | "departed" }> =>
266 handoff?.state === "departing" || handoff?.state === "departed";
267
268const EXPIRY_WARNING_DAYS = 5;
269
270export type PeerLinkHealth =
271 | { readonly kind: "reachable"; readonly expiresInDays: number | null }
272 | { readonly kind: "unreachable"; readonly detail: string | null }
273 | { readonly kind: "failing"; readonly detail: string }
274 | { readonly kind: "expired" };
275
276/**
277 * Listing only checks that the peer answers, so a link whose last call failed
278 * (the peer revoked it, say) is `failing` with the recorded reason; the next
279 * successful call clears it.
280 */
281export function peerLinkHealth(link: PeerLinkSummary, now: DateTime.Utc): PeerLinkHealth {
282 if (link.status === "expired" || DateTime.isLessThanOrEqualTo(link.expiresAt, now)) {
283 return { kind: "expired" };
284 }
285 if (link.status === "unreachable") return { kind: "unreachable", detail: link.lastError };
286 if (link.lastError !== null) return { kind: "failing", detail: link.lastError };
287 const days = Math.ceil(Duration.toDays(DateTime.distance(now, link.expiresAt)));
288 return { kind: "reachable", expiresInDays: days <= EXPIRY_WARNING_DAYS ? days : null };
289}
290
291/** A linked machine, and the environment that can get a pairing code from it. */
292export interface LinkThroughRoute {
293 readonly viaEnvironmentId: EnvironmentId;
294 readonly environmentId: EnvironmentId;
295 readonly label: string;
296 readonly urls: ReadonlyArray<string>;
297}
298
299/**
300 * The machines `sourceEnvironmentId` can link to without a pasted code: those another of the
301 * client's environments reaches over a full-access link that answers. `hosts` are environments
302 * the client is connected to and manages access on, the only ones it may ask.
303 */
304export function linkThroughRoutes(input: {
305 readonly sourceEnvironmentId: EnvironmentId;
306 readonly hosts: ReadonlyArray<{
307 readonly environmentId: EnvironmentId;
308 readonly links: ReadonlyArray<PeerLinkSummary>;
309 }>;
310 readonly now: DateTime.Utc;
311}): ReadonlyMap<EnvironmentId, LinkThroughRoute> {
312 const routes = new Map<EnvironmentId, LinkThroughRoute>();
313 for (const host of input.hosts) {
314 if (host.environmentId === input.sourceEnvironmentId) continue;
315 for (const link of host.links) {
316 if (
317 link.environmentId === input.sourceEnvironmentId ||
318 link.access !== "full-access" ||
319 routes.has(link.environmentId) ||
320 peerLinkHealth(link, input.now).kind !== "reachable"
321 ) {
322 continue;
323 }
324 routes.set(link.environmentId, {
325 viaEnvironmentId: host.environmentId,
326 environmentId: link.environmentId,
327 label: link.label,
328 urls: link.urls,
329 });
330 }
331 }
332 return routes;
333}