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

peerLink.ts

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