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

main
ts 268 lines 10.7 KB
Raw
1 import * as Schema from "effect/Schema";
2
3 import { AuthEnvironmentScope, AuthMcpClientAccess } from "./auth.ts";
4 import { 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 */
12 export 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 });
23 export type PeerLink = typeof PeerLink.Type;
24
25 /** Whether a link can be used now, as worked out when it is listed. */
26 export const PeerLinkStatus = Schema.Literals(["reachable", "unreachable", "expired"]);
27 export type PeerLinkStatus = typeof PeerLinkStatus.Type;
28
29 export const PeerLinkSummary = Schema.Struct({
30 ...PeerLink.fields,
31 status: PeerLinkStatus,
32 });
33 export 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 */
39 export const PeerLinkName = Schema.Struct({
40 environmentId: EnvironmentId,
41 label: Schema.String,
42 });
43 export type PeerLinkName = typeof PeerLinkName.Type;
44
45 export 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 });
61 export type PeerLinkCreateInput = typeof PeerLinkCreateInput.Type;
62
63 export const PeerLinkRemoveInput = Schema.Struct({ environmentId: EnvironmentId });
64 export type PeerLinkRemoveInput = typeof PeerLinkRemoveInput.Type;
65
66 export const PeerLinkRemoveResult = Schema.Struct({ removed: Schema.Boolean });
67 export type PeerLinkRemoveResult = typeof PeerLinkRemoveResult.Type;
68
69 /** Why linking or calling a peer failed, in words a user can act on. */
70 export 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. */
89 export type PeerLinkFailureKind = "unreachable" | "code_refused" | "wrong_environment" | "other";
90
91 export 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 */
107 const PEER_LINK_THREAD_ROUTE_PREFIX = "/api/links/thread";
108 export const PEER_LINK_THREAD_STREAM_ROUTE = `${PEER_LINK_THREAD_ROUTE_PREFIX}/stream`;
109 export const PEER_LINK_THREAD_HISTORY_ROUTE = `${PEER_LINK_THREAD_ROUTE_PREFIX}/history`;
110 export 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. */
113 export const PeerLinkThreadInput = Schema.Struct({
114 /** The linked environment the thread lives in. */
115 environmentId: EnvironmentId,
116 threadId: ThreadId,
117 });
118 export type PeerLinkThreadInput = typeof PeerLinkThreadInput.Type;
119
120 export const PeerLinkThreadHistoryInput = Schema.Struct({
121 ...PeerLinkThreadInput.fields,
122 /** The `historyCursor` of the snapshot or of the page before. */
123 cursor: TrimmedNonEmptyString,
124 });
125 export type PeerLinkThreadHistoryInput = typeof PeerLinkThreadHistoryInput.Type;
126
127 export 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 });
133 export type PeerLinkThreadItemInput = typeof PeerLinkThreadItemInput.Type;
134
135 /** Why a linked environment's thread could not be read, with the reason in words. */
136 export 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. */
160 export const PeerLinkClientPairingInput = Schema.Struct({ environmentId: EnvironmentId });
161 export type PeerLinkClientPairingInput = typeof PeerLinkClientPairingInput.Type;
162
163 const peerLinkClientPairingTarget = {
164 environmentId: EnvironmentId,
165 label: Schema.String,
166 /** The addresses this environment reaches the linked one at; the client tries them itself. */
167 urls: Schema.Array(TrimmedNonEmptyString),
168 };
169
170 /**
171 * A one-time pairing credential from the linked environment, or why this link cannot get one, in
172 * which case the user pairs there with a code of their own.
173 */
174 export const PeerLinkClientPairingResult = Schema.Union([
175 Schema.Struct({
176 type: Schema.Literal("credential"),
177 ...peerLinkClientPairingTarget,
178 credential: TrimmedNonEmptyString,
179 expiresAt: Schema.DateTimeUtc,
180 }),
181 Schema.Struct({
182 type: Schema.Literal("unsupported"),
183 ...peerLinkClientPairingTarget,
184 reason: Schema.Literals([
185 /** The link is below full access, so it may not hand out a client's access. */
186 "link_access",
187 /** The linked environment runs a version from before this. */
188 "version",
189 /** The linked environment refused: the beta is off there, or its policy forbids pairing. */
190 "refused",
191 /** This environment could not reach the linked one; the client still might. */
192 "unreachable",
193 ]),
194 }),
195 ]);
196 export type PeerLinkClientPairingResult = typeof PeerLinkClientPairingResult.Type;
197
198 /** What a linking environment asks of the linked one, over the link, for one of its clients. */
199 export const PeerLinkClientPairingRequest = Schema.Struct({
200 /** The client's scopes on the linking environment. The credential never carries more. */
201 scopes: Schema.Array(AuthEnvironmentScope),
202 /** The client's name there, shown in Connections here. */
203 clientLabel: TrimmedNonEmptyString,
204 });
205 export type PeerLinkClientPairingRequest = typeof PeerLinkClientPairingRequest.Type;
206
207 export const PeerLinkClientPairingCredential = Schema.Struct({
208 credential: TrimmedNonEmptyString,
209 expiresAt: Schema.DateTimeUtc,
210 });
211 export type PeerLinkClientPairingCredential = typeof PeerLinkClientPairingCredential.Type;
212
213 /**
214 * The user's answer to an agent asking to link an environment. The pairing
215 * code is used once to link and is never recorded; the thread learns only the
216 * outcome and the access the user chose.
217 */
218 export const PeerLinkRequestAnswerInput = Schema.Struct({
219 threadId: ThreadId,
220 turnItemId: TurnItemId,
221 answer: Schema.Union([
222 Schema.Struct({
223 type: Schema.Literal("link"),
224 /** The machine the user picked, when they picked one rather than typing an address. */
225 environmentId: Schema.optionalKey(EnvironmentId),
226 /** What the client calls that machine. */
227 label: Schema.optionalKey(TrimmedNonEmptyString),
228 /** The addresses the client knows for that machine, most preferred first. */
229 urls: Schema.NonEmptyArray(TrimmedNonEmptyString),
230 access: AuthMcpClientAccess,
231 pairingCode: TrimmedNonEmptyString,
232 }),
233 /** Answers with a machine this environment is already linked to, as it is. */
234 Schema.Struct({ type: Schema.Literal("use-existing"), environmentId: EnvironmentId }),
235 Schema.Struct({ type: Schema.Literal("decline") }),
236 ]),
237 });
238 export type PeerLinkRequestAnswerInput = typeof PeerLinkRequestAnswerInput.Type;
239
240 const PEER_LINK_REQUEST_FAILURE_MESSAGES = {
241 load_failed: "Could not load the link request.",
242 not_found: "This link request no longer exists.",
243 already_answered: "This link request was already answered.",
244 record_failed: "Could not update the link request.",
245 } as const;
246
247 export const PeerLinkRequestFailureReason = Schema.Literals(
248 Object.keys(PEER_LINK_REQUEST_FAILURE_MESSAGES) as Array<
249 keyof typeof PEER_LINK_REQUEST_FAILURE_MESSAGES
250 >,
251 );
252 export type PeerLinkRequestFailureReason = typeof PeerLinkRequestFailureReason.Type;
253
254 /**
255 * Answering a link request failed before anything was linked. A link the
256 * other environment refused is not this error: the card records it as failed.
257 */
258 export class PeerLinkRequestError extends Schema.TaggedError<PeerLinkRequestError>()(
259 "PeerLinkRequestError",
260 {
261 reason: PeerLinkRequestFailureReason,
262 cause: Schema.optionalKey(Schema.Defect()),
263 },
264 ) {
265 override get message(): string {
266 return PEER_LINK_REQUEST_FAILURE_MESSAGES[this.reason];
267 }
268 }