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

peerLink.ts

284 lines11.3 KB

1import * as Schema from "effect/Schema";
2​
3import { AuthEnvironmentScope, AuthMcpClientAccess } from "./auth.ts";
4import { EnvironmentId, ThreadId, TrimmedNonEmptyString, TurnItemId } from "./baseSchemas.ts";
5​
6/**
7 * A link from this environment to another one (the peer). This environment
8 * signed in to the peer's `/mcp` as an outside agent, with a pairing code from
9 * the peer, so its agents can work there. The peer enforces the access chosen
10 * at linking, and revokes the link from its own Connections.
11 */
12export const PeerLink = Schema.Struct({
13 environmentId: EnvironmentId,
14 label: Schema.String,
15 /** Addresses the peer was linked at, tried in order. */
16 urls: Schema.Array(TrimmedNonEmptyString),
17 access: AuthMcpClientAccess,
18 linkedAt: Schema.DateTimeUtc,
19 expiresAt: Schema.DateTimeUtc,
20 lastReachedAt: Schema.NullOr(Schema.DateTimeUtc),
21 lastError: Schema.NullOr(Schema.String),
22});
23export type PeerLink = typeof PeerLink.Type;
24​
25/** Whether a link can be used now, as worked out when it is listed. */
26export const PeerLinkStatus = Schema.Literals(["reachable", "unreachable", "expired"]);
27export type PeerLinkStatus = typeof PeerLinkStatus.Type;
28​
29export const PeerLinkSummary = Schema.Struct({
30 ...PeerLink.fields,
31 status: PeerLinkStatus,
32});
33export type PeerLinkSummary = typeof PeerLinkSummary.Type;
34​
35/**
36 * A link's name only, for a client that may read threads here but not manage access: enough to
37 * name and open a linked environment's threads, without its addresses, access or health.
38 */
39export const PeerLinkName = Schema.Struct({
40 environmentId: EnvironmentId,
41 label: Schema.String,
42});
43export type PeerLinkName = typeof PeerLinkName.Type;
44​
45export const PeerLinkCreateInput = Schema.Struct({
46 /** Where the peer answers: an https, Tailscale, LAN or loopback base URL. */
47 url: TrimmedNonEmptyString,
48 /** More addresses for the same peer, tried after `url`. */
49 alternateUrls: Schema.optionalKey(Schema.Array(TrimmedNonEmptyString)),
50 /** A pairing code from the peer (`t3 pair` there, or its Connections settings). */
51 pairingCode: TrimmedNonEmptyString,
52 access: AuthMcpClientAccess,
53 /**
54 * The environment the user means. Addresses that answer as another one are
55 * skipped, and only those that answer as this one are kept.
56 */
57 expectedEnvironmentId: Schema.optionalKey(EnvironmentId),
58 /** What the user calls that environment, to name it when it cannot be reached. */
59 expectedLabel: Schema.optionalKey(TrimmedNonEmptyString),
60});
61export type PeerLinkCreateInput = typeof PeerLinkCreateInput.Type;
62​
63export const PeerLinkRemoveInput = Schema.Struct({ environmentId: EnvironmentId });
64export type PeerLinkRemoveInput = typeof PeerLinkRemoveInput.Type;
65​
66export const PeerLinkRemoveResult = Schema.Struct({ removed: Schema.Boolean });
67export type PeerLinkRemoveResult = typeof PeerLinkRemoveResult.Type;
68​
69/** Why linking or calling a peer failed, in words a user can act on. */
70export class PeerLinkError extends Schema.TaggedError<PeerLinkError>()("PeerLinkError", {
71 reason: Schema.Literals([
72 "unreachable",
73 "not_a_t3_environment",
74 "incompatible",
75 "self",
76 "pairing_rejected",
77 "expired",
78 "unknown_link",
79 "storage",
80 "disabled",
81 ]),
82 message: Schema.String,
83 /** The environment that answered at the addresses of the one the user picked, when one did. */
84 answeredAs: Schema.optionalKey(Schema.String),
85 cause: Schema.optionalKey(Schema.Defect()),
86}) {}
87​
88/** What went wrong with one link, as a batch reports it per machine. */
89export type PeerLinkFailureKind = "unreachable" | "code_refused" | "wrong_environment" | "other";
90​
91export const peerLinkFailureKind = (
92 error: Pick<PeerLinkError, "reason" | "answeredAs">,
93): PeerLinkFailureKind =>
94 error.answeredAs !== undefined
95 ? "wrong_environment"
96 : error.reason === "unreachable" || error.reason === "not_a_t3_environment"
97 ? "unreachable"
98 : error.reason === "pairing_rejected"
99 ? "code_refused"
100 : "other";
101​
102/**
103 * Where an environment serves one of its threads to an environment linked to it, signed in with
104 * the link's own session as on `/mcp`. The stream carries the same items the owner's thread
105 * subscription does; history pages and item detail are the owner's too.
106 */
107const PEER_LINK_THREAD_ROUTE_PREFIX = "/api/links/thread";
108export const PEER_LINK_THREAD_STREAM_ROUTE = `${PEER_LINK_THREAD_ROUTE_PREFIX}/stream`;
109export const PEER_LINK_THREAD_HISTORY_ROUTE = `${PEER_LINK_THREAD_ROUTE_PREFIX}/history`;
110export const PEER_LINK_THREAD_ITEM_ROUTE = `${PEER_LINK_THREAD_ROUTE_PREFIX}/item`;
111​
112/** A thread on a linked environment, as a client of this environment names it. */
113export const PeerLinkThreadInput = Schema.Struct({
114 /** The linked environment the thread lives in. */
115 environmentId: EnvironmentId,
116 threadId: ThreadId,
117});
118export type PeerLinkThreadInput = typeof PeerLinkThreadInput.Type;
119​
120export const PeerLinkThreadHistoryInput = Schema.Struct({
121 ...PeerLinkThreadInput.fields,
122 /** The `historyCursor` of the snapshot or of the page before. */
123 cursor: TrimmedNonEmptyString,
124});
125export type PeerLinkThreadHistoryInput = typeof PeerLinkThreadHistoryInput.Type;
126​
127export const PeerLinkThreadItemInput = Schema.Struct({
128 ...PeerLinkThreadInput.fields,
129 itemId: TurnItemId,
130 /** Unused by the server; a client keys its cache on it, as for its own threads' items. */
131 revision: Schema.optional(Schema.String),
132});
133export type PeerLinkThreadItemInput = typeof PeerLinkThreadItemInput.Type;
134​
135/** Why a linked environment's thread could not be read, with the reason in words. */
136export class PeerLinkThreadReadError extends Schema.TaggedError<PeerLinkThreadReadError>()(
137 "PeerLinkThreadReadError",
138 {
139 reason: Schema.Literals([
140 /** Linked environments is off here. */
141 "disabled",
142 "unknown_link",
143 "expired",
144 /** The linked environment no longer accepts the link, or refuses the read. */
145 "rejected",
146 "unreachable",
147 "thread_not_found",
148 /** The linked environment runs a version that does not serve its threads to a link. */
149 "incompatible",
150 ]),
151 /** What this environment calls the linked one, when it still has the link. */
152 label: Schema.NullOr(Schema.String),
153 message: Schema.String,
154 /** The failure underneath, when the read got as far as the link or the linked environment. */
155 cause: Schema.optionalKey(Schema.Defect()),
156 },
157) {}
158​
159/** A client of this environment asks to pair with one it links to, without typing a code. */
160export const PeerLinkClientPairingInput = Schema.Struct({ environmentId: EnvironmentId });
161export type PeerLinkClientPairingInput = typeof PeerLinkClientPairingInput.Type;
162​
163/**
164 * A client of this environment asks it for a pairing code from one it links to, to link another
165 * environment there with: the linked one mints it, so the user fetches none.
166 */
167export const PeerLinkLinkPairingInput = Schema.Struct({
168 environmentId: EnvironmentId,
169 /** The access the new link will have. */
170 access: AuthMcpClientAccess,
171});
172export type PeerLinkLinkPairingInput = typeof PeerLinkLinkPairingInput.Type;
173​
174const peerLinkClientPairingTarget = {
175 environmentId: EnvironmentId,
176 label: Schema.String,
177 /** The addresses this environment reaches the linked one at; the client tries them itself. */
178 urls: Schema.Array(TrimmedNonEmptyString),
179};
180​
181/**
182 * A one-time pairing credential from the linked environment, or why this link cannot get one, in
183 * which case the user pairs there with a code of their own.
184 */
185export const PeerLinkClientPairingResult = Schema.Union([
186 Schema.Struct({
187 type: Schema.Literal("credential"),
188 ...peerLinkClientPairingTarget,
189 credential: TrimmedNonEmptyString,
190 expiresAt: Schema.DateTimeUtc,
191 }),
192 Schema.Struct({
193 type: Schema.Literal("unsupported"),
194 ...peerLinkClientPairingTarget,
195 reason: Schema.Literals([
196 /** The link is below full access, so it may not hand out a client's access. */
197 "link_access",
198 /** The linked environment runs a version from before this. */
199 "version",
200 /** The linked environment refused: the beta is off there, or its policy forbids pairing. */
201 "refused",
202 /** This environment could not reach the linked one; the client still might. */
203 "unreachable",
204 ]),
205 }),
206]);
207export type PeerLinkClientPairingResult = typeof PeerLinkClientPairingResult.Type;
208​
209/** What a linking environment asks of the linked one, over the link, for one of its clients. */
210export const PeerLinkClientPairingRequest = Schema.Struct({
211 /** The client's scopes on the linking environment. The credential never carries more. */
212 scopes: Schema.Array(AuthEnvironmentScope),
213 /** The client's name there, shown in Connections here. */
214 clientLabel: TrimmedNonEmptyString,
215 /**
216 * Set when the pairing is for a link from another environment, not for the client itself: the
217 * credential is then a link pairing code at this access, and `scopes` is not used.
218 */
219 link: Schema.optionalKey(Schema.Struct({ access: AuthMcpClientAccess })),
220});
221export type PeerLinkClientPairingRequest = typeof PeerLinkClientPairingRequest.Type;
222​
223export const PeerLinkClientPairingCredential = Schema.Struct({
224 credential: TrimmedNonEmptyString,
225 expiresAt: Schema.DateTimeUtc,
226});
227export type PeerLinkClientPairingCredential = typeof PeerLinkClientPairingCredential.Type;
228​
229/**
230 * The user's answer to an agent asking to link an environment. The pairing
231 * code is used once to link and is never recorded; the thread learns only the
232 * outcome and the access the user chose.
233 */
234export const PeerLinkRequestAnswerInput = Schema.Struct({
235 threadId: ThreadId,
236 turnItemId: TurnItemId,
237 answer: Schema.Union([
238 Schema.Struct({
239 type: Schema.Literal("link"),
240 /** The machine the user picked, when they picked one rather than typing an address. */
241 environmentId: Schema.optionalKey(EnvironmentId),
242 /** What the client calls that machine. */
243 label: Schema.optionalKey(TrimmedNonEmptyString),
244 /** The addresses the client knows for that machine, most preferred first. */
245 urls: Schema.NonEmptyArray(TrimmedNonEmptyString),
246 access: AuthMcpClientAccess,
247 pairingCode: TrimmedNonEmptyString,
248 }),
249 /** Answers with a machine this environment is already linked to, as it is. */
250 Schema.Struct({ type: Schema.Literal("use-existing"), environmentId: EnvironmentId }),
251 Schema.Struct({ type: Schema.Literal("decline") }),
252 ]),
253});
254export type PeerLinkRequestAnswerInput = typeof PeerLinkRequestAnswerInput.Type;
255​
256const PEER_LINK_REQUEST_FAILURE_MESSAGES = {
257 load_failed: "Could not load the link request.",
258 not_found: "This link request no longer exists.",
259 already_answered: "This link request was already answered.",
260 record_failed: "Could not update the link request.",
261} as const;
262​
263export const PeerLinkRequestFailureReason = Schema.Literals(
264 Object.keys(PEER_LINK_REQUEST_FAILURE_MESSAGES) as Array<
265 keyof typeof PEER_LINK_REQUEST_FAILURE_MESSAGES
266 >,
267);
268export type PeerLinkRequestFailureReason = typeof PeerLinkRequestFailureReason.Type;
269​
270/**
271 * Answering a link request failed before anything was linked. A link the
272 * other environment refused is not this error: the card records it as failed.
273 */
274export class PeerLinkRequestError extends Schema.TaggedError<PeerLinkRequestError>()(
275 "PeerLinkRequestError",
276 {
277 reason: PeerLinkRequestFailureReason,
278 cause: Schema.optionalKey(Schema.Defect()),
279 },
280) {
281 override get message(): string {
282 return PEER_LINK_REQUEST_FAILURE_MESSAGES[this.reason];
283 }