The best way to control Claude Code, Codex and more from any computer or phone

main
ts 162 lines 6.56 KB
Raw
1 import {
2 type EnvironmentId,
3 type PeerLinkSummary,
4 type PeerLinkThreadInput,
5 WS_METHODS,
6 } from "@t3tools/contracts";
7 import * as DateTime from "effect/DateTime";
8 import * as Duration from "effect/Duration";
9 import * as Effect from "effect/Effect";
10 import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";
11
12 import type { EnvironmentRegistry } from "../connection/registry.ts";
13 import {
14 followLinkedThread,
15 keepLinkedThreadView,
16 type LinkedThreadView,
17 } from "../linkedThread.ts";
18 import { request, subscribe } from "../rpc/client.ts";
19 import {
20 createEnvironmentRpcCommand,
21 createEnvironmentRpcQueryAtomFamily,
22 createEnvironmentSubscriptionAtomFamily,
23 } from "./runtime.ts";
24
25 /** The environment a client reads through, and the linked environment's thread it reads. */
26 export interface LinkedThreadViewTarget {
27 readonly environmentId: EnvironmentId;
28 readonly input: PeerLinkThreadInput;
29 }
30
31 const threadViewKey = ({ environmentId, input }: LinkedThreadViewTarget) =>
32 JSON.stringify({
33 environmentId,
34 input: { environmentId: input.environmentId, threadId: input.threadId },
35 });
36
37 export function createPeerLinkEnvironmentAtoms<R, E>(
38 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
39 ) {
40 const list = createEnvironmentRpcQueryAtomFamily(runtime, {
41 label: "environment-data:peer-links:list",
42 tag: WS_METHODS.peerLinksList,
43 // Listing probes every linked environment, so a list stays fresh briefly.
44 staleTimeMs: 10_000,
45 });
46 // Names only, for opening linked threads with thread read access; it probes nothing.
47 const names = createEnvironmentRpcQueryAtomFamily(runtime, {
48 label: "environment-data:peer-links:names",
49 tag: WS_METHODS.peerLinksNames,
50 staleTimeMs: 10_000,
51 });
52 const refreshLinks = (registry: AtomRegistry.AtomRegistry, environmentId: EnvironmentId) =>
53 Effect.sync(() => {
54 registry.refresh(list({ environmentId, input: {} }));
55 registry.refresh(names({ environmentId, input: {} }));
56 });
57 const threadStream = createEnvironmentSubscriptionAtomFamily(runtime, {
58 label: "environment-data:peer-links:thread-stream",
59 idleTtlMs: 0,
60 subscribe: (input: PeerLinkThreadInput) =>
61 followLinkedThread({
62 items: subscribe(WS_METHODS.peerLinksSubscribeThread, input),
63 historyPage: (cursor) =>
64 request(WS_METHODS.peerLinksThreadHistoryPage, { ...input, cursor }),
65 }),
66 });
67 /**
68 * What a view of the thread last showed. It outlives the subscription for a while, so coming
69 * back to the view shows the thread at once while the stream starts again.
70 */
71 const lastThreadView = Atom.family((key: string) =>
72 Atom.make<LinkedThreadView | null>(null).pipe(
73 Atom.setIdleTTL(5 * 60_000),
74 Atom.withLabel(`environment-data:peer-links:last-thread-view:${key}`),
75 ),
76 );
77 /**
78 * A linked environment's thread, streamed while a view reads it. The subscription ends with its
79 * last reader, which closes the stream at the linked environment too.
80 */
81 const threadView = Atom.family((key: string) => {
82 const stream = threadStream(JSON.parse(key) as LinkedThreadViewTarget);
83 return Atom.make((get) => {
84 const live = get(stream);
85 if (AsyncResult.isSuccess(live)) {
86 const kept = lastThreadView(key);
87 get.set(kept, keepLinkedThreadView(get.once(kept), live.value));
88 }
89 return live;
90 }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-data:peer-links:thread-view:${key}`));
91 });
92 return {
93 list,
94 names,
95 link: createEnvironmentRpcCommand(runtime, {
96 label: "environment-data:peer-links:link",
97 tag: WS_METHODS.peerLinksLink,
98 onSuccess: ({ environmentId }, registry) => refreshLinks(registry, environmentId),
99 }),
100 // Leaves the list alone: a batch refreshes it once, when it ends (`runLinkBatch`).
101 linkInBatch: createEnvironmentRpcCommand(runtime, {
102 label: "environment-data:peer-links:link-in-batch",
103 tag: WS_METHODS.peerLinksLink,
104 }),
105 unlink: createEnvironmentRpcCommand(runtime, {
106 label: "environment-data:peer-links:unlink",
107 tag: WS_METHODS.peerLinksUnlink,
108 onSuccess: ({ environmentId }, registry) => refreshLinks(registry, environmentId),
109 }),
110 threadView: (target: LinkedThreadViewTarget) => threadView(threadViewKey(target)),
111 lastThreadView: (target: LinkedThreadViewTarget) => lastThreadView(threadViewKey(target)),
112 /** One item of a linked environment's thread in full, for a row the reader opened. */
113 threadItem: createEnvironmentRpcQueryAtomFamily(runtime, {
114 label: "environment-data:peer-links:thread-item",
115 tag: WS_METHODS.peerLinksThreadItem,
116 idleTtlMs: 0,
117 }),
118 /** Asks for a one-time pairing with a linked environment. Its answer is a credential: never cached. */
119 pairClient: createEnvironmentRpcCommand(runtime, {
120 label: "environment-data:peer-links:pair-client",
121 tag: WS_METHODS.peerLinksPairClient,
122 concurrency: {
123 mode: "singleFlight",
124 key: ({ environmentId, input }) => JSON.stringify([environmentId, input.environmentId]),
125 },
126 }),
127 // An agent's link card. One answer per card at a time.
128 answerRequest: createEnvironmentRpcCommand(runtime, {
129 label: "environment-data:peer-links:answer-request",
130 tag: WS_METHODS.peerLinksAnswerRequest,
131 concurrency: {
132 mode: "singleFlight",
133 key: ({ environmentId, input }) =>
134 JSON.stringify([environmentId, input.threadId, input.turnItemId]),
135 },
136 onSuccess: ({ environmentId }, registry) => refreshLinks(registry, environmentId),
137 }),
138 };
139 }
140
141 const EXPIRY_WARNING_DAYS = 5;
142
143 export type PeerLinkHealth =
144 | { readonly kind: "reachable"; readonly expiresInDays: number | null }
145 | { readonly kind: "unreachable"; readonly detail: string | null }
146 | { readonly kind: "failing"; readonly detail: string }
147 | { readonly kind: "expired" };
148
149 /**
150 * Listing only checks that the peer answers, so a link whose last call failed
151 * (the peer revoked it, say) is `failing` with the recorded reason; the next
152 * successful call clears it.
153 */
154 export function peerLinkHealth(link: PeerLinkSummary, now: DateTime.Utc): PeerLinkHealth {
155 if (link.status === "expired" || DateTime.isLessThanOrEqualTo(link.expiresAt, now)) {
156 return { kind: "expired" };
157 }
158 if (link.status === "unreachable") return { kind: "unreachable", detail: link.lastError };
159 if (link.lastError !== null) return { kind: "failing", detail: link.lastError };
160 const days = Math.ceil(Duration.toDays(DateTime.distance(now, link.expiresAt)));
161 return { kind: "reachable", expiresInDays: days <= EXPIRY_WARNING_DAYS ? days : null };
162 }