@devries-cameron20 / t3code Mirror · read-only / commits / 4005759adf
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 14:30 UTC

feat(server): link to another environment (#16655)

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Julius Marminge committed Oct 27, 2026 at 14:04 UTC 4005759adf35c0355892ea1083ecd9426526a12c
18 files changed +1524
apps/server/src/auth/RpcAuthorization.ts
+4
@@ -5,6 +5,7 @@ import {
5 authScopeRequiredResponse,
6 AssetCreateUrlInput,
7 AuthAccessReadScope,
8 + AuthAccessWriteScope,
9 ServerSettingsPatch,
10 ProviderInstanceMutation,
11 requiredScopesForServerSettingsPatch,
@@ -86,6 +87,9 @@ export const RPC_REQUIRED_SCOPES = {
87 [WS_METHODS.serverGetStorageCleanupReport]: AuthOrchestrationReadScope,
88 [WS_METHODS.serverGetDatabaseStorage]: AuthOrchestrationReadScope,
89 [WS_METHODS.serverGetSettings]: AuthOrchestrationReadScope,
90 + [WS_METHODS.peerLinksList]: AuthAccessReadScope,
91 + [WS_METHODS.peerLinksLink]: AuthAccessWriteScope,
92 + [WS_METHODS.peerLinksUnlink]: AuthAccessWriteScope,
93 [WS_METHODS.serverUpdateSettings]: AuthSettingsWriteScope,
94 [WS_METHODS.serverSearchAcpRegistry]: AuthOrchestrationReadScope,
95 [WS_METHODS.serverPrepareAcpRegistryAgent]: AuthProvidersManageScope,
apps/server/src/binCli.ts
+2
@@ -10,6 +10,7 @@ import * as NetService from "@t3tools/shared/Net";
10 import packageJson from "../package.json" with { type: "json" };
11 import { acpMcpBridgeCommand, acpMcpCallCommand } from "./cli/acpMcpBridge.ts";
12 import { authCommand } from "./cli/auth.ts";
13 +import { environmentCommand } from "./cli/environment.ts";
14 import { appCommand } from "./cli/app.ts";
15 import { browserCommand } from "./cli/browser.ts";
16 import { connectCommand } from "./cli/connect.ts";
@@ -75,6 +76,7 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>
76 appCommand,
77 pairCommand,
78 authCommand,
79 + environmentCommand,
80 browserCommand,
81 projectCommand,
82 threadCommand,
apps/server/src/cli/environment.ts new
+158
@@ -0,0 +1,158 @@
1 +import { AuthMcpClientAccess, EnvironmentId, type PeerLinkSummary } from "@t3tools/contracts";
2 +import * as Console from "effect/Console";
3 +import * as DateTime from "effect/DateTime";
4 +import * as Effect from "effect/Effect";
5 +import * as Layer from "effect/Layer";
6 +import * as References from "effect/References";
7 +import * as Schema from "effect/Schema";
8 +import * as Argument from "effect/cli/Argument";
9 +import * as Command from "effect/cli/Command";
10 +import * as Flag from "effect/cli/Flag";
11 +import * as GlobalFlag from "effect/cli/GlobalFlag";
12 +import * as FetchHttpClient from "effect/http/FetchHttpClient";
13 +
14 +import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
15 +import * as ServerConfig from "../config.ts";
16 +import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
17 +import * as PeerLinks from "../peer/PeerLinks.ts";
18 +import * as SqlitePersistence from "../persistence/Sqlite.ts";
19 +import { authLocationFlags, type CliAuthLocationFlags, resolveCliAuthConfig } from "./config.ts";
20 +
21 +/**
22 + * Links live in this environment's database and secret store, so these
23 + * commands work whether or not its server is running.
24 + */
25 +const runWithPeerLinks = Effect.fn("environment.runWithPeerLinks")(function* <A, E>(
26 + flags: CliAuthLocationFlags,
27 + run: (links: PeerLinks.PeerLinks["Service"]) => Effect.Effect<A, E>,
28 + options?: { readonly quietLogs?: boolean },
29 +) {
30 + const logLevel = yield* GlobalFlag.LogLevel;
31 + const config = yield* resolveCliAuthConfig(flags, logLevel);
32 + return yield* PeerLinks.PeerLinks.pipe(
33 + Effect.flatMap(run),
34 + Effect.provide(
35 + PeerLinks.layer.pipe(
36 + Layer.provide(
37 + Layer.mergeAll(
38 + ServerSecretStore.layer,
39 + SqlitePersistence.layerConfig,
40 + FetchHttpClient.layer,
41 + ),
42 + ),
43 + Layer.provide(ServerEnvironment.layer.pipe(Layer.provide(ServerSecretStore.layer))),
44 + Layer.provide(ServerConfig.layer(config)),
45 + Layer.provide(
46 + Layer.succeed(References.MinimumLogLevel, options?.quietLogs ? "Error" : config.logLevel),
47 + ),
48 + ),
49 + ),
50 + );
51 +});
52 +
53 +const jsonFlag = Flag.Boolean("json").pipe(
54 + Flag.withDescription("Emit JSON instead of human-readable output."),
55 + Flag.withDefault(false),
56 +);
57 +
58 +const encodeLinks = Schema.encodeEffect(
59 + Schema.fromJsonString(Schema.Array(Schema.toEncoded(Schema.Unknown))),
60 +);
61 +
62 +const formatLinks = (links: ReadonlyArray<PeerLinkSummary>) =>
63 + links.length === 0
64 + ? "No linked environments.\n"
65 + : `${links
66 + .map(
67 + (link) =>
68 + `${link.label} (${link.environmentId})\n ${link.status}, access ${link.access}, expires ${DateTime.formatIso(link.expiresAt)}\n ${link.urls.join(", ")}${link.lastError === null ? "" : `\n last error: ${link.lastError}`}`,
69 + )
70 + .join("\n\n")}\n`;
71 +
72 +const environmentLinkCommand = Command.make("link", {
73 + ...authLocationFlags,
74 + url: Argument.String("url").pipe(
75 + Argument.withDescription(
76 + "Where the other environment answers: its T3 Connect, Tailscale, LAN or loopback address.",
77 + ),
78 + ),
79 + alternateUrl: Flag.String("url").pipe(
80 + Flag.withDescription("Another address for the same environment, tried after the first."),
81 + Flag.atLeast(0),
82 + ),
83 + pairingCode: Flag.String("pairing-code").pipe(
84 + Flag.withDescription("A pairing code from the other environment (`t3 pair` there)."),
85 + ),
86 + access: Flag.Literals("access", AuthMcpClientAccess.literals).pipe(
87 + Flag.withDescription(
88 + "What this environment's agents may do there: read-only, or the broadest runtime mode.",
89 + ),
90 + Flag.withDefault("approval-required" as const),
91 + ),
92 +}).pipe(
93 + Command.withDescription(
94 + "Link another T3 Code environment, so agents here can work there. It shows up there under Settings → Connections, where it can be revoked.",
95 + ),
96 + Command.withHandler((flags) =>
97 + runWithPeerLinks(flags, (links) =>
98 + Effect.gen(function* () {
99 + const linked = yield* links.link({
100 + url: flags.url,
101 + alternateUrls: flags.alternateUrl,
102 + pairingCode: flags.pairingCode,
103 + access: flags.access,
104 + });
105 + yield* Console.log(
106 + `Linked ${linked.label} (${linked.environmentId}) with ${linked.access} access, until ${DateTime.formatIso(linked.expiresAt)}.\n`,
107 + );
108 + }),
109 + ),
110 + ),
111 +);
112 +
113 +const environmentListCommand = Command.make("list", { ...authLocationFlags, json: jsonFlag }).pipe(
114 + Command.withDescription("List linked environments and whether each answers now."),
115 + Command.withHandler((flags) =>
116 + runWithPeerLinks(
117 + flags,
118 + (links) =>
119 + Effect.gen(function* () {
120 + const listed = yield* links.list;
121 + yield* Console.log(flags.json ? `${yield* encodeLinks(listed)}\n` : formatLinks(listed));
122 + }),
123 + { quietLogs: flags.json },
124 + ),
125 + ),
126 +);
127 +
128 +const environmentUnlinkCommand = Command.make("unlink", {
129 + ...authLocationFlags,
130 + environmentId: Argument.String("environment-id").pipe(
131 + Argument.withDescription("The linked environment's id, from `t3 environment list`."),
132 + ),
133 +}).pipe(
134 + Command.withDescription(
135 + "Forget a linked environment here. Revoke it in that environment's Connections to end its session there too.",
136 + ),
137 + Command.withHandler((flags) =>
138 + runWithPeerLinks(flags, (links) =>
139 + Effect.gen(function* () {
140 + const removed = yield* links.unlink(EnvironmentId.make(flags.environmentId));
141 + yield* Console.log(
142 + removed
143 + ? `Forgot ${flags.environmentId}. Revoke it in that environment's Connections to end its session there.\n`
144 + : `No linked environment ${flags.environmentId}.\n`,
145 + );
146 + }),
147 + ),
148 + ),
149 +);
150 +
151 +export const environmentCommand = Command.make("environment").pipe(
152 + Command.withDescription("Link other T3 Code environments, so agents here can work there."),
153 + Command.withSubcommands([
154 + environmentLinkCommand,
155 + environmentListCommand,
156 + environmentUnlinkCommand,
157 + ]),
158 +);
apps/server/src/environment/ServerEnvironment.ts
+2
@@ -265,6 +265,8 @@ export const make = Effect.gen(function* () {
265 : {}),
266 ...(desktopAppUpdate ? { desktopAppUpdate: true } : {}),
267 serverBrowser: true,
268 + peerLinks: true,
269 + mcpModeLimitHeader: true,
270 },
271 };
272
apps/server/src/observability/RpcInstrumentation.ts
+3
@@ -59,6 +59,9 @@ const RPC_AGGREGATES = {
59 [WS_METHODS.serverGetStorageCleanupReport]: "server",
60 [WS_METHODS.serverGetDatabaseStorage]: "server",
61 [WS_METHODS.serverGetSettings]: "server",
62 + [WS_METHODS.peerLinksList]: "peerLinks",
63 + [WS_METHODS.peerLinksLink]: "peerLinks",
64 + [WS_METHODS.peerLinksUnlink]: "peerLinks",
65 [WS_METHODS.serverUpdateSettings]: "server",
66 [WS_METHODS.serverSearchAcpRegistry]: "server",
67 [WS_METHODS.serverPrepareAcpRegistryAgent]: "server",
apps/server/src/peer/PeerLinks.test.ts new
+463
@@ -0,0 +1,463 @@
1 +import { NodeHttpServer } from "@effect/platform-node";
2 +import * as NodeServices from "@effect/platform-node/NodeServices";
3 +import {
4 + EnvironmentHttpApi,
5 + EnvironmentId,
6 + type ExecutionEnvironmentDescriptor,
7 + OrchestratorMcpFailure,
8 +} from "@t3tools/contracts";
9 +import { expect, it } from "@effect/vitest";
10 +import * as Context from "effect/Context";
11 +import * as Duration from "effect/Duration";
12 +import * as Effect from "effect/Effect";
13 +import * as Layer from "effect/Layer";
14 +import * as Option from "effect/Option";
15 +import * as Ref from "effect/Ref";
16 +import * as Schema from "effect/Schema";
17 +import * as TestClock from "effect/testing/TestClock";
18 +import { Tool, Toolkit } from "effect/ai";
19 +import {
20 + FetchHttpClient,
21 + HttpClient,
22 + HttpRouter,
23 + HttpServer,
24 + HttpServerRequest,
25 + HttpServerResponse,
26 +} from "effect/http";
27 +import * as HttpApi from "effect/http-api/HttpApi";
28 +import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
29 +
30 +import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
31 +import * as AuthHttp from "../auth/http.ts";
32 +import * as McpOAuth from "../auth/McpOAuth.ts";
33 +import * as McpOAuthHttp from "../auth/mcpOAuthHttp.ts";
34 +import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
35 +import * as ServerConfig from "../config.ts";
36 +import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
37 +import * as ServerHttp from "../http.ts";
38 +import * as McpHttpServer from "../mcp/McpHttpServer.ts";
39 +import * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
40 +import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts";
41 +import * as McpToolAccess from "../mcp/McpToolAccess.ts";
42 +import * as Sqlite from "../persistence/Sqlite.ts";
43 +import * as PeerLinks from "./PeerLinks.ts";
44 +import * as PeerMcpClient from "./PeerMcpClient.ts";
45 +
46 +class PeerTestApi extends HttpApi.make("environment")
47 + .add(EnvironmentHttpApi.groups.metadata)
48 + .add(EnvironmentHttpApi.groups.mcpOAuth) {}
49 +
50 +const descriptorOf = (
51 + environmentId: string,
52 + label: string,
53 + capabilities: Partial<ExecutionEnvironmentDescriptor["capabilities"]> = {},
54 +): ExecutionEnvironmentDescriptor => ({
55 + environmentId: EnvironmentId.make(environmentId),
56 + label,
57 + platform: { os: "linux", arch: "x64" },
58 + serverVersion: "0.0.0-test",
59 + capabilities: { repositoryIdentity: true, mcpModeLimitHeader: true, ...capabilities },
60 +});
61 +
62 +/** What B's probe saw: the calling client and the modes it may start work with. */
63 +const Probe = Schema.Struct({ caller: Schema.String, modes: Schema.String });
64 +
65 +const ProbeToolkit = Toolkit.make(
66 + Tool.make("probe", {
67 + description: "Reports the calling client and the modes it may start work with.",
68 + success: Probe,
69 + failure: OrchestratorMcpFailure,
70 + failureMode: "return",
71 + dependencies: [McpInvocationContext.McpInvocationContext],
72 + }),
73 + Tool.make("refuse", {
74 + description: "Always refuses.",
75 + success: Probe,
76 + failure: OrchestratorMcpFailure,
77 + failureMode: "return",
78 + }),
79 +);
80 +
81 +/**
82 + * Environment B as it runs: its descriptor, MCP OAuth, and `/mcp` behind the
83 + * real client authenticator, on a real socket. The descriptor can be swapped,
84 + * as when B's address comes to answer as another environment.
85 + */
86 +const serveB = (initial: ExecutionEnvironmentDescriptor) =>
87 + Effect.gen(function* () {
88 + const descriptor = yield* Ref.make(initial);
89 + const bearers = yield* Ref.make<ReadonlyArray<string>>([]);
90 + const probes = yield* Ref.make(0);
91 + const layerEnvironment = Layer.succeed(ServerEnvironment.ServerEnvironment, {
92 + getEnvironmentId: Ref.get(descriptor).pipe(Effect.map((current) => current.environmentId)),
93 + getDescriptor: Ref.get(descriptor),
94 + });
95 + const authContext = yield* EnvironmentAuth.layer.pipe(
96 + Layer.provide(Sqlite.layerMemory),
97 + Layer.provideMerge(ServerSecretStore.layer),
98 + Layer.provideMerge(ServerEnvironment.layerIdentity),
99 + Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-peer-link-b-" })),
100 + Layer.provideMerge(NodeServices.layer),
101 + Layer.fresh,
102 + Layer.build,
103 + );
104 + // Every bearer B receives, on any route, so a test can show one was never sent.
105 + const layerRecordBearers = HttpRouter.middleware(
106 + (httpEffect) =>
107 + Effect.gen(function* () {
108 + const request = yield* HttpServerRequest.HttpServerRequest;
109 + if (request.url.startsWith("/.well-known/t3/environment")) {
110 + yield* Ref.update(probes, (count) => count + 1);
111 + }
112 + const authorization = request.headers.authorization;
113 + if (authorization !== undefined) {
114 + yield* Ref.update(bearers, (seen) => [...seen, authorization]);
115 + }
116 + return yield* httpEffect;
117 + }),
118 + { global: true },
119 + );
120 + const layerRoutes = Layer.mergeAll(
121 + HttpApiBuilder.layer(PeerTestApi).pipe(
122 + Layer.provide(McpOAuthHttp.layer.pipe(Layer.provide(McpOAuth.layer))),
123 + Layer.provide(ServerHttp.layerServerEnvironmentHttpApi),
124 + Layer.provide(AuthHttp.layerAuthenticatedAuth),
125 + ),
126 + McpHttpServer.toolkitRegistration(
127 + ProbeToolkit,
128 + McpToolAccess.toLayer(ProbeToolkit, {
129 + probe: McpToolAccess.reads(() =>
130 + McpInvocationContext.McpInvocationContext.pipe(
131 + Effect.map((scope) => {
132 + const modes = McpInvocationContext.clientModeCeiling(scope.client);
133 + return {
134 + caller: scope.client?.label ?? "none",
135 + modes: `${modes.runtimeMode}/${modes.interactionMode}`,
136 + };
137 + }),
138 + ),
139 + ),
140 + refuse: McpToolAccess.reads(() =>
141 + Effect.fail(
142 + new OrchestratorMcpFailure({ code: "thread_not_found", message: "No such thread." }),
143 + ),
144 + ),
145 + }),
146 + ).pipe(
147 + Layer.provideMerge(McpHttpServer.layerMcpTransport),
148 + Layer.provide(
149 + Layer.mock(McpSessionRegistry.McpSessionRegistry)({
150 + // @effect-diagnostics-next-line effectSucceedWithVoid:off - This optional result requires undefined, not the wider void type.
151 + resolve: () => Effect.succeed(undefined),
152 + }),
153 + ),
154 + Layer.provide(McpOAuth.layerMcpClientAuthenticator),
155 + ),
156 + ).pipe(
157 + Layer.provide(layerRecordBearers),
158 + Layer.provide(layerEnvironment),
159 + Layer.provide(Layer.succeedContext(authContext)),
160 + );
161 + yield* HttpRouter.serve(layerRoutes, { disableListenLog: true, disableLogger: true }).pipe(
162 + Layer.build,
163 + );
164 + const address = (yield* HttpServer.HttpServer).address;
165 + if (address._tag === "UnixPathAddress") return yield* Effect.die("expected a TCP address");
166 + return {
167 + url: `http://127.0.0.1:${address.port}`,
168 + auth: Context.get(authContext, EnvironmentAuth.EnvironmentAuth),
169 + descriptor,
170 + bearers,
171 + /** How often its descriptor was asked for, as a probe of whether it answers. */
172 + probes,
173 + };
174 + });
175 +
176 +/** Environment A: its own database and secret store, reaching B over plain HTTP. */
177 +const makeA = (descriptor: ExecutionEnvironmentDescriptor) =>
178 + Effect.gen(function* () {
179 + const context = yield* PeerMcpClient.layer.pipe(
180 + Layer.provideMerge(PeerLinks.layer),
181 + Layer.provide(
182 + Layer.mergeAll(
183 + Sqlite.layerMemory,
184 + ServerSecretStore.layer,
185 + FetchHttpClient.layer,
186 + Layer.succeed(ServerEnvironment.ServerEnvironment, {
187 + getEnvironmentId: Effect.succeed(descriptor.environmentId),
188 + getDescriptor: Effect.succeed(descriptor),
189 + }),
190 + ),
191 + ),
192 + Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-peer-link-a-" })),
193 + Layer.provide(NodeServices.layer),
194 + Layer.fresh,
195 + Layer.build,
196 + );
197 + return {
198 + links: Context.get(context, PeerLinks.PeerLinks),
199 + peer: Context.get(context, PeerMcpClient.PeerMcpClient),
200 + };
201 + });
202 +
203 +const laptop = descriptorOf("environment-laptop", "Laptop");
204 +const box = descriptorOf("environment-box", "Box");
205 +const probe = (
206 + a: Effect.Success<ReturnType<typeof makeA>>,
207 + limits: PeerMcpClient.PeerCallLimits = { runtimeMode: "full-access", interactionMode: "default" },
208 + tool = "probe",
209 +) =>
210 + a.peer.call({
211 + environmentId: box.environmentId,
212 + tool,
213 + arguments: {},
214 + limits,
215 + success: Probe,
216 + });
217 +
218 +const linkedSessions = (b: Effect.Success<ReturnType<typeof serveB>>) =>
219 + b.auth
220 + .listSessions()
221 + .pipe(
222 + Effect.map((sessions) =>
223 + sessions.filter((session) => session.client.label?.startsWith("T3 Code · ")),
224 + ),
225 + );
226 +
227 +it.effect("links with a pairing code, and the peer holds its agents to the limits they carry", () =>
228 + Effect.scoped(
229 + Effect.gen(function* () {
230 + const b = yield* serveB(box);
231 + const a = yield* makeA(laptop);
232 +
233 + const refused = yield* a.links
234 + .link({ url: b.url, pairingCode: "not-a-code", access: "auto" })
235 + .pipe(Effect.flip);
236 + expect(refused.reason).toBe("pairing_rejected");
237 + expect(yield* linkedSessions(b)).toEqual([]);
238 +
239 + const pairing = yield* b.auth.issuePairingCredential();
240 + const linked = yield* a.links.link({
241 + url: b.url,
242 + pairingCode: pairing.credential,
243 + access: "auto",
244 + });
245 + expect(linked).toMatchObject({
246 + environmentId: box.environmentId,
247 + label: "Box",
248 + urls: [b.url],
249 + access: "auto",
250 + });
251 + // B lists the link under A's name, where it can be revoked.
252 + expect((yield* linkedSessions(b)).map((session) => session.client.label)).toEqual([
253 + "T3 Code · Laptop",
254 + ]);
255 + expect(
256 + (yield* a.links.list).map(({ environmentId, status }) => [environmentId, status]),
257 + ).toEqual([[box.environmentId, "reachable"]]);
258 +
259 + // The caller's limits narrow the link's access; they never widen it.
260 + expect(
261 + yield* probe(a, { runtimeMode: "approval-required", interactionMode: "plan" }),
262 + ).toEqual({ caller: "T3 Code · Laptop", modes: "approval-required/plan" });
263 + expect(yield* probe(a)).toEqual({ caller: "T3 Code · Laptop", modes: "auto/default" });
264 +
265 + // A refusal keeps the peer's reason.
266 + const notFound = yield* probe(a, undefined, "refuse").pipe(Effect.flip);
267 + expect(notFound).toMatchObject({ code: "thread_not_found", message: "No such thread." });
268 + }),
269 + ).pipe(Effect.provide(NodeHttpServer.layerTest)),
270 +);
271 +
272 +it.effect("two links racing to one peer leave the stored access matching the token", () =>
273 + Effect.scoped(
274 + Effect.gen(function* () {
275 + const b = yield* serveB(box);
276 + const a = yield* makeA(laptop);
277 + const [first, second] = yield* Effect.all(
278 + [b.auth.issuePairingCredential(), b.auth.issuePairingCredential()],
279 + { concurrency: 2 },
280 + );
281 + yield* Effect.all(
282 + [
283 + a.links.link({ url: b.url, pairingCode: first.credential, access: "read-only" }),
284 + a.links.link({ url: b.url, pairingCode: second.credential, access: "full-access" }),
285 + ],
286 + { concurrency: 2 },
287 + );
288 + const [stored] = yield* a.links.list;
289 + // The token sent is the one issued with the access the row records.
290 + const { modes } = yield* probe(a);
291 + expect(modes).toBe(
292 + stored!.access === "read-only" ? "approval-required/default" : "full-access/default",
293 + );
294 + }),
295 + ).pipe(Effect.provide(NodeHttpServer.layerTest)),
296 +);
297 +
298 +/** A bare HTTP server on a socket of its own, answering with `handle`. */
299 +const serveRaw = <E, R>(
300 + handle: (
301 + request: HttpServerRequest.HttpServerRequest,
302 + ) => Effect.Effect<HttpServerResponse.HttpServerResponse, E, R>,
303 +) =>
304 + Layer.build(Layer.fresh(NodeHttpServer.layerTest)).pipe(
305 + Effect.flatMap((server) =>
306 + Effect.gen(function* () {
307 + yield* HttpServer.serve(Effect.flatMap(HttpServerRequest.HttpServerRequest, handle)).pipe(
308 + Layer.build,
309 + );
310 + const address = (yield* HttpServer.HttpServer).address;
311 + if (address._tag === "UnixPathAddress") return yield* Effect.die("expected a TCP address");
312 + return `http://127.0.0.1:${address.port}`;
313 + }).pipe(Effect.provideContext(server)),
314 + ),
315 + );
316 +
317 +it.effect("never follows a peer's redirect with the pairing code", () =>
318 + Effect.scoped(
319 + Effect.gen(function* () {
320 + const b = yield* serveB(box);
321 + const received = yield* Ref.make<ReadonlyArray<string>>([]);
322 + const elsewhere = yield* serveRaw((request) =>
323 + Ref.update(received, (seen) => [...seen, `${request.method} ${request.url}`]).pipe(
324 + Effect.as(HttpServerResponse.empty({ status: 404 })),
325 + ),
326 + );
327 + // Answers as B, then sends every linking request on to another address.
328 + const front = yield* serveRaw((request) =>
329 + request.url.startsWith("/.well-known/t3/environment")
330 + ? HttpClient.get(`${b.url}${request.url}`).pipe(
331 + Effect.flatMap((response) => response.text),
332 + Effect.map((body) =>
333 + HttpServerResponse.text(body, { contentType: "application/json" }),
334 + ),
335 + Effect.provide(FetchHttpClient.layer),
336 + Effect.orDie,
337 + )
338 + : Effect.succeed(
339 + HttpServerResponse.empty({
340 + status: 307,
341 + headers: { location: `${elsewhere}${request.url}` },
342 + }),
343 + ),
344 + );
345 + const a = yield* makeA(laptop);
346 + const pairing = yield* b.auth.issuePairingCredential();
347 + yield* a.links
348 + .link({ url: front, pairingCode: pairing.credential, access: "auto" })
349 + .pipe(Effect.flip);
350 + expect(yield* Ref.get(received)).toEqual([]);
351 + expect(yield* a.links.list).toEqual([]);
352 + }),
353 + ).pipe(Effect.provide(NodeHttpServer.layerTest)),
354 +);
355 +
356 +it.effect("never sends a link's token to an address that stops answering as that peer", () =>
357 + Effect.scoped(
358 + Effect.gen(function* () {
359 + const b = yield* serveB(box);
360 + const a = yield* makeA(laptop);
361 + const pairing = yield* b.auth.issuePairingCredential();
362 + yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
363 + yield* probe(a);
364 + expect((yield* Ref.get(b.bearers)).length).toBeGreaterThan(0);
365 +
366 + // The address now answers as another environment, as a reused LAN address would.
367 + yield* Ref.set(b.descriptor, descriptorOf("environment-impostor", "Impostor"));
368 + yield* Ref.set(b.bearers, []);
369 + const failed = yield* probe(a).pipe(Effect.flip);
370 + expect(failed.message).toContain("Box did not answer");
371 + expect(yield* Ref.get(b.bearers)).toEqual([]);
372 + expect((yield* a.links.list).map((link) => link.status)).toEqual(["unreachable"]);
373 + }),
374 + ).pipe(Effect.provide(NodeHttpServer.layerTest)),
375 +);
376 +
377 +it.effect("reads one stored link without asking the peer", () =>
378 + Effect.scoped(
379 + Effect.gen(function* () {
380 + const b = yield* serveB(box);
381 + const a = yield* makeA(laptop);
382 + const pairing = yield* b.auth.issuePairingCredential();
383 + yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
384 + yield* Ref.set(b.probes, 0);
385 +
386 + const stored = yield* a.links.get(box.environmentId);
387 + expect(Option.map(stored, (link) => link.label)).toEqual(Option.some("Box"));
388 + expect(Option.isNone(yield* a.links.get(laptop.environmentId))).toBe(true);
389 + expect(yield* Ref.get(b.probes)).toBe(0);
390 + }),
391 + ).pipe(Effect.provide(NodeHttpServer.layerTest)),
392 +);
393 +
394 +it.effect("tells the agent to link again once the peer revokes the link or it expires", () =>
395 + Effect.scoped(
396 + Effect.gen(function* () {
397 + const b = yield* serveB(box);
398 + const a = yield* makeA(laptop);
399 + const pairing = yield* b.auth.issuePairingCredential();
400 + yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
401 + yield* probe(a);
402 +
403 + const [session] = yield* linkedSessions(b);
404 + yield* b.auth.revokeSession(session!.sessionId);
405 + const revoked = yield* probe(a).pipe(Effect.flip);
406 + expect(revoked.code).toBe("capability_denied");
407 + expect(revoked.message).toContain("revoked there");
408 +
409 + yield* TestClock.adjust(Duration.days(31));
410 + expect((yield* a.links.list).map((link) => link.status)).toEqual(["expired"]);
411 + yield* Ref.set(b.bearers, []);
412 + const expired = yield* probe(a).pipe(Effect.flip);
413 + expect(expired.code).toBe("capability_denied");
414 + expect(expired.message).toContain("expired");
415 + expect(yield* Ref.get(b.bearers)).toEqual([]);
416 + }),
417 + ).pipe(Effect.provide(NodeHttpServer.layerTest)),
418 +);
419 +
420 +it.effect(
421 + "refuses to link itself, plain http off this machine and the tailnet, or a peer that cannot hold a linked agent to its limits",
422 + () =>
423 + Effect.scoped(
424 + Effect.gen(function* () {
425 + const b = yield* serveB(
426 + descriptorOf("environment-box", "Box", { mcpModeLimitHeader: false }),
427 + );
428 + const a = yield* makeA(laptop);
429 + const pairing = yield* b.auth.issuePairingCredential();
430 + const older = yield* a.links
431 + .link({ url: b.url, pairingCode: pairing.credential, access: "auto" })
432 + .pipe(Effect.flip);
433 + expect(older.reason).toBe("incompatible");
434 +
435 + // Plain http to a LAN address would carry the code and token in clear.
436 + const lan = yield* a.links
437 + .link({
438 + url: "http://192.168.1.20:3773",
439 + pairingCode: pairing.credential,
440 + access: "auto",
441 + })
442 + .pipe(Effect.flip);
443 + expect(lan.message).toContain("plain http");
444 + const lanAlternate = yield* a.links
445 + .link({
446 + url: b.url,
447 + alternateUrls: ["http://192.168.1.20:3773"],
448 + pairingCode: pairing.credential,
449 + access: "auto",
450 + })
451 + .pipe(Effect.flip);
452 + expect(lanAlternate.message).toContain("plain http");
453 +
454 + yield* Ref.set(b.descriptor, laptop);
455 + const self = yield* a.links
456 + .link({ url: b.url, pairingCode: pairing.credential, access: "auto" })
457 + .pipe(Effect.flip);
458 + expect(self.reason).toBe("self");
459 + // Neither attempt spent the pairing code on a session.
460 + expect(yield* linkedSessions(b)).toEqual([]);
461 + }),
462 + ).pipe(Effect.provide(NodeHttpServer.layerTest)),
463 +);
apps/server/src/peer/PeerLinks.ts new
+489
@@ -0,0 +1,489 @@
1 +import {
2 + AuthMcpClientAccess,
3 + AuthMcpRegistrationError,
4 + AuthMcpTokenError,
5 + EnvironmentHttpApi,
6 + EnvironmentId,
7 + type PeerLink,
8 + type PeerLinkCreateInput,
9 + PeerLinkError,
10 + type PeerLinkStatus,
11 + type PeerLinkSummary,
12 +} from "@t3tools/contracts";
13 +import * as Context from "effect/Context";
14 +import * as Crypto from "effect/Crypto";
15 +import * as DateTime from "effect/DateTime";
16 +import * as Duration from "effect/Duration";
17 +import * as Effect from "effect/Effect";
18 +import * as Base64Url from "effect/encoding/Base64Url";
19 +import * as Hex from "effect/encoding/Hex";
20 +import * as Layer from "effect/Layer";
21 +import * as Option from "effect/Option";
22 +import * as Schema from "effect/Schema";
23 +import * as SqlClient from "effect/sql/SqlClient";
24 +import * as FetchHttpClient from "effect/http/FetchHttpClient";
25 +import * as HttpClient from "effect/http/HttpClient";
26 +import * as HttpApiClient from "effect/http-api/HttpApiClient";
27 +import { isLocalLoopbackHost, isTailnetHost } from "@t3tools/shared/hostClassification";
28 +
29 +import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
30 +import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
31 +
32 +/** The redirect registered for a link. Nothing ever listens there: the code comes back in the response. */
33 +const LINK_REDIRECT_URI = "http://127.0.0.1/t3code-peer-link";
34 +/**
35 + * How long a peer's descriptor may take before a route counts as unreachable.
36 + * A tailnet or relayed route to a machine that is waking up takes longer.
37 + */
38 +const probeTimeout = (origin: string) =>
39 + isLocalLoopbackHost(new URL(origin).hostname) ? Duration.seconds(3) : Duration.seconds(10);
40 +
41 +/** A usable link: where to reach the peer and the token to send there. */
42 +export interface ResolvedPeerLink {
43 + readonly link: PeerLink;
44 + /** The first address that answered as this peer. */
45 + readonly url: string;
46 + readonly token: string;
47 +}
48 +
49 +/**
50 + * Links from this environment to others. Linking signs this environment in to
51 + * the peer's `/mcp` as an outside agent with a pairing code from the peer, the
52 + * same MCP OAuth flow an outside agent uses, without a browser. The peer's
53 + * session token is kept in the server secret store; the table keeps the rest.
54 + */
55 +export class PeerLinks extends Context.Service<
56 + PeerLinks,
57 + {
58 + readonly link: (input: PeerLinkCreateInput) => Effect.Effect<PeerLink, PeerLinkError>;
59 + readonly list: Effect.Effect<ReadonlyArray<PeerLinkSummary>, PeerLinkError>;
60 + /** The stored link, without asking the peer whether it answers. */
61 + readonly get: (
62 + environmentId: EnvironmentId,
63 + ) => Effect.Effect<Option.Option<PeerLink>, PeerLinkError>;
64 + /** Forgets the link here. The peer still lists the session until it is revoked there. */
65 + readonly unlink: (environmentId: EnvironmentId) => Effect.Effect<boolean, PeerLinkError>;
66 + /** An address that answers as the linked peer, with its token, ready to call. */
67 + readonly resolve: (
68 + environmentId: EnvironmentId,
69 + ) => Effect.Effect<ResolvedPeerLink, PeerLinkError>;
70 + /** Records the outcome of a call, so listing shows whether the peer answered last time. */
71 + readonly recordOutcome: (
72 + environmentId: EnvironmentId,
73 + outcome: { readonly error: string | null },
74 + ) => Effect.Effect<void>;
75 + }
76 +>()("t3/peer/PeerLinks") {}
77 +
78 +interface PeerLinkRow {
79 + readonly environment_id: string;
80 + readonly secret_name: string;
81 + readonly label: string;
82 + readonly urls_json: string;
83 + readonly access: string;
84 + readonly linked_at: string;
85 + readonly expires_at: string;
86 + readonly last_reached_at: string | null;
87 + readonly last_error: string | null;
88 +}
89 +
90 +const decodeUrls = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Array(Schema.String)));
91 +const encodeUrls = Schema.encodeEffect(Schema.fromJsonString(Schema.Array(Schema.String)));
92 +const decodeAccess = Schema.decodeUnknownEffect(AuthMcpClientAccess);
93 +
94 +/** Fails with a fixed storage error that keeps its cause; the log gets the details. */
95 +const failStorage = (cause: unknown) =>
96 + Effect.logWarning("Peer link storage failed", cause).pipe(
97 + Effect.andThen(
98 + Effect.fail(
99 + new PeerLinkError({
100 + reason: "storage",
101 + message:
102 + "Linked environments could not be read or saved here. The server log has details.",
103 + cause,
104 + }),
105 + ),
106 + ),
107 + );
108 +
109 +/**
110 + * The base URL a peer is reached at, normalised to its origin. The pairing
111 + * code and then the link's token travel to it, so plain http is accepted only
112 + * where the network already encrypts: this machine, or a Tailscale address.
113 + */
114 +const peerOrigin = (url: string) => {
115 + const parsed = URL.parse(url);
116 + if (parsed === null || (parsed.protocol !== "https:" && parsed.protocol !== "http:")) {
117 + return Effect.fail(
118 + new PeerLinkError({
119 + reason: "unreachable",
120 + message: `${url} is not an http or https address.`,
121 + }),
122 + );
123 + }
124 + if (
125 + parsed.protocol === "http:" &&
126 + !isLocalLoopbackHost(parsed.hostname) &&
127 + !isTailnetHost(parsed.hostname)
128 + ) {
129 + return Effect.fail(
130 + new PeerLinkError({
131 + reason: "unreachable",
132 + message: `${url} is plain http, which would send the link's credentials unencrypted. Use its https address, or its Tailscale address.`,
133 + }),
134 + );
135 + }
136 + return Effect.succeed(parsed.origin);
137 +};
138 +
139 +const make = Effect.gen(function* () {
140 + const sql = yield* SqlClient.SqlClient;
141 + const secrets = yield* ServerSecretStore.ServerSecretStore;
142 + const crypto = yield* Crypto.Crypto;
143 + const httpClient = yield* HttpClient.HttpClient;
144 + const environment = yield* ServerEnvironment.ServerEnvironment;
145 +
146 + /** A fresh name for one link's token; the row records it. */
147 + const newSecretName = crypto.randomBytes(16).pipe(
148 + Effect.map((bytes) => `peer-link-${Hex.encode(bytes)}`),
149 + Effect.orDie,
150 + );
151 +
152 + // Only the origin `peerOrigin` checked may receive a pairing code or token:
153 + // a redirect could forward them anywhere, including plain http.
154 + const peerHttpClient = HttpClient.transform(httpClient, (response) =>
155 + Effect.provideService(response, FetchHttpClient.RequestInit, { redirect: "manual" }),
156 + );
157 +
158 + const clientFor = (origin: string) =>
159 + HttpApiClient.make(EnvironmentHttpApi, { baseUrl: origin }).pipe(
160 + Effect.provideService(HttpClient.HttpClient, peerHttpClient),
161 + );
162 +
163 + /** The environment answering at `origin`, or nothing when it does not answer as T3 Code. */
164 + const describe = (origin: string) =>
165 + clientFor(origin).pipe(
166 + Effect.flatMap((client) => client.metadata.descriptor()),
167 + Effect.timeout(probeTimeout(origin)),
168 + Effect.option,
169 + );
170 +
171 + const toLink = Effect.fn("PeerLinks.toLink")(function* (row: PeerLinkRow) {
172 + return {
173 + environmentId: EnvironmentId.make(row.environment_id),
174 + label: row.label,
175 + urls: yield* decodeUrls(row.urls_json),
176 + access: yield* decodeAccess(row.access),
177 + linkedAt: DateTime.makeUnsafe(row.linked_at),
178 + expiresAt: DateTime.makeUnsafe(row.expires_at),
179 + lastReachedAt: row.last_reached_at === null ? null : DateTime.makeUnsafe(row.last_reached_at),
180 + lastError: row.last_error,
181 + } satisfies PeerLink;
182 + }, Effect.catch(failStorage));
183 +
184 + const readRows = sql<PeerLinkRow>`
185 + SELECT * FROM peer_environment_links ORDER BY label, environment_id
186 + `.pipe(Effect.catch(failStorage));
187 +
188 + const readRow = (environmentId: EnvironmentId) =>
189 + sql<PeerLinkRow>`
190 + SELECT * FROM peer_environment_links WHERE environment_id = ${environmentId}
191 + `.pipe(
192 + Effect.catch(failStorage),
193 + Effect.map((rows) => Option.fromNullishOr(rows[0])),
194 + );
195 +
196 + /** Signs in to the peer's `/mcp` with a pairing code: register, decide, exchange. */
197 + const signIn = Effect.fn("PeerLinks.signIn")(
198 + function* (origin: string, input: PeerLinkCreateInput, clientName: string) {
199 + const client = yield* clientFor(origin);
200 + // Only the peer's own refusals are rejections. A dropped connection or
201 + // an answer this version cannot read is classified below.
202 + const registered = yield* client.mcpOAuth
203 + .register({ payload: { client_name: clientName, redirect_uris: [LINK_REDIRECT_URI] } })
204 + .pipe(
205 + // A plain Schema.Error has no tag to catch by.
206 + Effect.catchIf(Schema.is(AuthMcpRegistrationError), (error) =>
207 + Effect.fail(
208 + new PeerLinkError({
209 + reason: "pairing_rejected",
210 + message: `The peer refused to register this environment: ${error.message}`,
211 + }),
212 + ),
213 + ),
214 + );
215 + const verifier = Base64Url.encode(yield* crypto.randomBytes(32).pipe(Effect.orDie));
216 + const challenge = Base64Url.encode(
217 + yield* crypto.digest("SHA-256", new TextEncoder().encode(verifier)).pipe(Effect.orDie),
218 + );
219 + const state = Base64Url.encode(yield* crypto.randomBytes(16).pipe(Effect.orDie));
220 + const resource = `${origin}/mcp`;
221 + const decided = yield* client.mcpOAuth
222 + .decision({
223 + payload: {
224 + authorization: {
225 + response_type: "code",
226 + client_id: registered.client_id,
227 + redirect_uri: LINK_REDIRECT_URI,
228 + code_challenge: challenge,
229 + code_challenge_method: "S256",
230 + state,
231 + resource,
232 + },
233 + decision: { _tag: "pairing-code", access: input.access, code: input.pairingCode },
234 + },
235 + })
236 + .pipe(
237 + Effect.catchTags({
238 + AuthMcpApprovalError: (error) =>
239 + Effect.fail(
240 + new PeerLinkError({ reason: "pairing_rejected", message: error.message }),
241 + ),
242 + }),
243 + );
244 + const redirect = URL.parse(decided.redirectTo);
245 + if (redirect === null) {
246 + return yield* new PeerLinkError({
247 + reason: "incompatible",
248 + message: `${origin} answered the sign-in with an address this version cannot read. Update both environments.`,
249 + });
250 + }
251 + const code = redirect.searchParams.get("code");
252 + if (code === null || redirect.searchParams.get("state") !== state) {
253 + return yield* new PeerLinkError({
254 + reason: "pairing_rejected",
255 + message:
256 + redirect.searchParams.get("error_description") ??
257 + "The peer did not approve the link. Check the pairing code and try again.",
258 + });
259 + }
260 + return yield* client.mcpOAuth
261 + .token({
262 + payload: {
263 + grant_type: "authorization_code",
264 + code,
265 + redirect_uri: LINK_REDIRECT_URI,
266 + client_id: registered.client_id,
267 + code_verifier: verifier,
268 + resource,
269 + },
270 + })
271 + .pipe(
272 + Effect.catchIf(Schema.is(AuthMcpTokenError), (error) =>
273 + Effect.fail(
274 + new PeerLinkError({
275 + reason: "pairing_rejected",
276 + message: `The peer refused the sign-in: ${error.message}`,
277 + }),
278 + ),
279 + ),
280 + );
281 + },
282 + (effect, origin) =>
283 + effect.pipe(
284 + // Endpoint errors are mapped above; what is left is the transport or an
285 + // answer this version cannot decode.
286 + Effect.catchTags({
287 + SchemaError: (cause) =>
288 + Effect.fail(
289 + new PeerLinkError({
290 + reason: "incompatible",
291 + message: `${origin} answered in a shape this version does not understand. Update both environments.`,
292 + cause,
293 + }),
294 + ),
295 + HttpClientError: (cause) =>
296 + Effect.fail(
297 + new PeerLinkError({
298 + reason: "unreachable",
299 + message: `${origin} stopped answering while linking.`,
300 + cause,
301 + }),
302 + ),
303 + }),
304 + ),
305 + );
306 +
307 + const link: PeerLinks["Service"]["link"] = Effect.fn("PeerLinks.link")(function* (input) {
308 + const origins = yield* Effect.forEach([input.url, ...(input.alternateUrls ?? [])], peerOrigin);
309 + const primary = origins[0]!;
310 + const descriptor = yield* describe(primary);
311 + if (Option.isNone(descriptor)) {
312 + return yield* new PeerLinkError({
313 + reason: "not_a_t3_environment",
314 + message: `Nothing at ${primary} answered as a T3 Code environment.`,
315 + });
316 + }
317 + const peer = descriptor.value;
318 + const self = yield* environment.getDescriptor;
319 + if (peer.environmentId === self.environmentId) {
320 + return yield* new PeerLinkError({
321 + reason: "self",
322 + message: "That address is this environment.",
323 + });
324 + }
325 + if (peer.capabilities.mcpModeLimitHeader !== true) {
326 + return yield* new PeerLinkError({
327 + reason: "incompatible",
328 + message: `${peer.label} runs a T3 Code version that cannot keep a linked agent's limits. Update it, then link again.`,
329 + });
330 + }
331 + const issued = yield* signIn(primary, input, `T3 Code · ${self.label}`);
332 + const now = yield* DateTime.now;
333 + const linked: PeerLink = {
334 + environmentId: peer.environmentId,
335 + label: peer.label,
336 + urls: origins,
337 + access: input.access,
338 + linkedAt: now,
339 + expiresAt: DateTime.add(now, { seconds: issued.expires_in }),
340 + lastReachedAt: now,
341 + lastError: null,
342 + };
343 + // The token goes under a name of its own before the row points at it,
344 + // so the row and its token are replaced together.
345 + const secretName = yield* newSecretName;
346 + yield* secrets
347 + .set(secretName, new TextEncoder().encode(issued.access_token))
348 + .pipe(Effect.catch(failStorage));
349 + const urlsJson = yield* encodeUrls(origins).pipe(Effect.catch(failStorage));
350 + const previous = yield* readRow(peer.environmentId);
351 + yield* sql`
352 + INSERT INTO peer_environment_links (
353 + environment_id, secret_name, label, urls_json, access, linked_at, expires_at,
354 + last_reached_at, last_error
355 + ) VALUES (
356 + ${linked.environmentId}, ${secretName}, ${linked.label}, ${urlsJson}, ${linked.access},
357 + ${DateTime.formatIso(linked.linkedAt)}, ${DateTime.formatIso(linked.expiresAt)},
358 + ${DateTime.formatIso(now)}, NULL
359 + )
360 + ON CONFLICT (environment_id) DO UPDATE SET
361 + secret_name = excluded.secret_name,
362 + label = excluded.label,
363 + urls_json = excluded.urls_json,
364 + access = excluded.access,
365 + linked_at = excluded.linked_at,
366 + expires_at = excluded.expires_at,
367 + last_reached_at = excluded.last_reached_at,
368 + last_error = NULL
369 + `.pipe(Effect.catch(failStorage));
370 + // Linking again replaces the old token. A racing link may leave its own
371 + // behind; it is unused either way.
372 + if (Option.isSome(previous) && previous.value.secret_name !== secretName) {
373 + yield* secrets.remove(previous.value.secret_name).pipe(Effect.ignore);
374 + }
375 + return linked;
376 + });
377 +
378 + const statusOf = (link: PeerLink, now: DateTime.Utc) =>
379 + DateTime.isLessThanOrEqualTo(link.expiresAt, now)
380 + ? Effect.succeed<PeerLinkStatus>("expired")
381 + : Effect.findFirst(link.urls, (url) =>
382 + describe(url).pipe(
383 + Effect.map(
384 + (found) => Option.isSome(found) && found.value.environmentId === link.environmentId,
385 + ),
386 + ),
387 + ).pipe(
388 + Effect.map((answered): PeerLinkStatus =>
389 + Option.isSome(answered) ? "reachable" : "unreachable",
390 + ),
391 + );
392 +
393 + const list: PeerLinks["Service"]["list"] = Effect.gen(function* () {
394 + const links = yield* Effect.forEach(yield* readRows, toLink);
395 + const now = yield* DateTime.now;
396 + return yield* Effect.forEach(
397 + links,
398 + (link) => statusOf(link, now).pipe(Effect.map((status) => ({ ...link, status }))),
399 + { concurrency: "unbounded" },
400 + );
401 + });
402 +
403 + const get: PeerLinks["Service"]["get"] = (environmentId) =>
404 + readRow(environmentId).pipe(
405 + Effect.flatMap(
406 + Option.match({
407 + onNone: () => Effect.succeedNone,
408 + onSome: (row) => Effect.asSome(toLink(row)),
409 + }),
410 + ),
411 + );
412 +
413 + const unlink: PeerLinks["Service"]["unlink"] = Effect.fn("PeerLinks.unlink")(
414 + function* (environmentId) {
415 + const deleted = yield* sql<{ secret_name: string }>`
416 + DELETE FROM peer_environment_links WHERE environment_id = ${environmentId}
417 + RETURNING secret_name
418 + `.pipe(Effect.catch(failStorage));
419 + for (const row of deleted) {
420 + yield* secrets.remove(row.secret_name).pipe(Effect.catch(failStorage));
421 + }
422 + return deleted.length > 0;
423 + },
424 + );
425 +
426 + const resolve: PeerLinks["Service"]["resolve"] = Effect.fn("PeerLinks.resolve")(
427 + function* (environmentId) {
428 + const row = yield* readRow(environmentId);
429 + if (Option.isNone(row)) {
430 + return yield* new PeerLinkError({
431 + reason: "unknown_link",
432 + message: `This environment is not linked to ${environmentId}. t3_environment_links lists the linked ones.`,
433 + });
434 + }
435 + const link = yield* toLink(row.value);
436 + if (DateTime.isLessThanOrEqualTo(link.expiresAt, yield* DateTime.now)) {
437 + return yield* new PeerLinkError({
438 + reason: "expired",
439 + message: `The link to ${link.label} expired. Link it again with a new pairing code from ${link.label}.`,
440 + });
441 + }
442 + const stored = yield* secrets.get(row.value.secret_name).pipe(Effect.catch(failStorage));
443 + if (Option.isNone(stored)) {
444 + return yield* new PeerLinkError({
445 + reason: "unknown_link",
446 + message: `The link to ${link.label} lost its credential. Link it again.`,
447 + });
448 + }
449 + // The token goes only to an address that proves it is this peer, so a
450 + // reused LAN address or a moved hostname never receives it.
451 + const url = yield* Effect.findFirst(link.urls, (candidate) =>
452 + describe(candidate).pipe(
453 + Effect.map(
454 + (found) => Option.isSome(found) && found.value.environmentId === environmentId,
455 + ),
456 + ),
457 + );
458 + if (Option.isNone(url)) {
459 + return yield* new PeerLinkError({
460 + reason: "unreachable",
461 + message: `${link.label} did not answer at ${link.urls.join(", ")}.`,
462 + });
463 + }
464 + return { link, url: url.value, token: new TextDecoder().decode(stored.value) };
465 + },
466 + );
467 +
468 + const recordOutcome: PeerLinks["Service"]["recordOutcome"] = (environmentId, outcome) =>
469 + DateTime.now.pipe(
470 + Effect.flatMap((now) =>
471 + outcome.error === null
472 + ? sql`
473 + UPDATE peer_environment_links
474 + SET last_reached_at = ${DateTime.formatIso(now)}, last_error = NULL
475 + WHERE environment_id = ${environmentId}
476 + `
477 + : sql`
478 + UPDATE peer_environment_links SET last_error = ${outcome.error}
479 + WHERE environment_id = ${environmentId}
480 + `,
481 + ),
482 + Effect.asVoid,
483 + Effect.ignoreCause({ log: true }),
484 + );
485 +
486 + return PeerLinks.of({ link, list, get, unlink, resolve, recordOutcome });
487 +});
488 +
489 +export const layer = Layer.effect(PeerLinks, make);
apps/server/src/peer/PeerMcpClient.ts new
+253
@@ -0,0 +1,253 @@
1 +import {
2 + type EnvironmentId,
3 + OrchestratorMcpFailure,
4 + type PeerLinkError,
5 + type ProviderInteractionMode,
6 + type RuntimeMode,
7 +} from "@t3tools/contracts";
8 +import * as Context from "effect/Context";
9 +import * as Effect from "effect/Effect";
10 +import * as Layer from "effect/Layer";
11 +import * as Ref from "effect/Ref";
12 +import * as Schema from "effect/Schema";
13 +import * as HttpBody from "effect/http/HttpBody";
14 +import * as HttpClient from "effect/http/HttpClient";
15 +import * as HttpClientRequest from "effect/http/HttpClientRequest";
16 +
17 +import * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
18 +import * as PeerLinks from "./PeerLinks.ts";
19 +
20 +/** The only MCP protocol version a T3 Code `/mcp` registers. */
21 +const PROTOCOL_VERSION = "2025-06-18";
22 +
23 +/** The limits a call carries to the peer: the calling agent's modes here. */
24 +export interface PeerCallLimits {
25 + readonly runtimeMode: RuntimeMode;
26 + readonly interactionMode: ProviderInteractionMode;
27 +}
28 +
29 +/**
30 + * Calls a linked environment's T3 MCP tools as this environment's outside
31 + * agent. Each call carries the calling agent's limits in `T3-Mode-Limit`, so
32 + * the peer enforces the narrower of those and the link's own access.
33 + */
34 +export class PeerMcpClient extends Context.Service<
35 + PeerMcpClient,
36 + {
37 + /** Calls `tool` on the peer and decodes its structured result with `success`. */
38 + readonly call: <S extends Schema.Decoder<unknown>>(input: {
39 + readonly environmentId: EnvironmentId;
40 + readonly tool: string;
41 + readonly arguments: Record<string, unknown>;
42 + readonly limits: PeerCallLimits;
43 + readonly success: S;
44 + }) => Effect.Effect<S["Type"], OrchestratorMcpFailure>;
45 + }
46 +>()("t3/peer/PeerMcpClient") {}
47 +
48 +const ToolCallResponse = Schema.Struct({
49 + result: Schema.optional(
50 + Schema.Struct({
51 + content: Schema.Array(
52 + Schema.Struct({ type: Schema.String, text: Schema.optional(Schema.String) }),
53 + ),
54 + structuredContent: Schema.optional(Schema.Unknown),
55 + isError: Schema.optional(Schema.Boolean),
56 + }),
57 + ),
58 + error: Schema.optional(Schema.Struct({ code: Schema.Number, message: Schema.String })),
59 +});
60 +const decodeToolCallResponse = Schema.decodeUnknownEffect(Schema.fromJsonString(ToolCallResponse));
61 +const decodeFailure = Schema.decodeUnknownOption(
62 + Schema.fromJsonString(
63 + Schema.Struct({ code: OrchestratorMcpFailure.fields.code, message: Schema.String }),
64 + ),
65 +);
66 +
67 +/** A peer link problem, as the agent that asked hears it. */
68 +const fromLinkError = (error: PeerLinkError) =>
69 + new OrchestratorMcpFailure({
70 + code:
71 + error.reason === "unknown_link"
72 + ? "invalid_request"
73 + : error.reason === "expired"
74 + ? "capability_denied"
75 + : "orchestration_error",
76 + message: error.message,
77 + });
78 +
79 +/** The body of an MCP response: JSON, or a single server-sent event carrying JSON. */
80 +const responseJson = (contentType: string | undefined, text: string) =>
81 + contentType?.includes("text/event-stream") === true
82 + ? text
83 + .split("\n")
84 + .filter((line) => line.startsWith("data:"))
85 + .map((line) => line.slice("data:".length).trim())
86 + .join("")
87 + : text;
88 +
89 +const make = Effect.gen(function* () {
90 + const links = yield* PeerLinks.PeerLinks;
91 + const httpClient = yield* HttpClient.HttpClient;
92 + // One MCP session per peer and address, reused across calls. The peer keeps
93 + // sessions in memory, so a restart there answers 404 and we start a new one.
94 + const sessions = yield* Ref.make<ReadonlyMap<string, string>>(new Map());
95 +
96 + const post = (url: string, token: string, body: unknown, headers: Record<string, string>) =>
97 + httpClient.execute(
98 + HttpClientRequest.post(`${url}/mcp`).pipe(
99 + HttpClientRequest.setHeaders({
100 + accept: "application/json, text/event-stream",
101 + authorization: `Bearer ${token}`,
102 + ...headers,
103 + }),
104 + HttpClientRequest.setBody(HttpBody.text(JSON.stringify(body), "application/json")),
105 + ),
106 + );
107 +
108 + const openSession = Effect.fn("PeerMcpClient.openSession")(function* (
109 + url: string,
110 + token: string,
111 + limitHeader: Record<string, string>,
112 + ) {
113 + const initialized = yield* post(
114 + url,
115 + token,
116 + {
117 + jsonrpc: "2.0",
118 + id: 0,
119 + method: "initialize",
120 + params: {
121 + protocolVersion: PROTOCOL_VERSION,
122 + capabilities: {},
123 + clientInfo: { name: "t3code-peer", version: "1" },
124 + },
125 + },
126 + limitHeader,
127 + );
128 + const sessionId = initialized.headers["mcp-session-id"];
129 + if (initialized.status !== 200 || sessionId === undefined) {
130 + return yield* new OrchestratorMcpFailure({
131 + code: initialized.status === 401 ? "capability_denied" : "orchestration_error",
132 + message:
133 + initialized.status === 401
134 + ? "The linked environment no longer accepts this link. It may have been revoked there; link it again."
135 + : `The linked environment refused to start an MCP session (HTTP ${initialized.status}).`,
136 + });
137 + }
138 + yield* post(
139 + url,
140 + token,
141 + { jsonrpc: "2.0", method: "notifications/initialized" },
142 + { ...limitHeader, "mcp-session-id": sessionId, "mcp-protocol-version": PROTOCOL_VERSION },
143 + );
144 + return sessionId;
145 + });
146 +
147 + const call: PeerMcpClient["Service"]["call"] = Effect.fn("PeerMcpClient.call")(
148 + function* (input) {
149 + const resolved = yield* links
150 + .resolve(input.environmentId)
151 + .pipe(Effect.mapError(fromLinkError));
152 + const limitHeader = {
153 + [McpInvocationContext.MODE_LIMIT_HEADER]: `${input.limits.runtimeMode}/${input.limits.interactionMode}`,
154 + };
155 + const sessionKey = `${input.environmentId} ${resolved.url}`;
156 + const callOnce = (sessionId: string) =>
157 + post(
158 + resolved.url,
159 + resolved.token,
160 + {
161 + jsonrpc: "2.0",
162 + id: 1,
163 + method: "tools/call",
164 + params: { name: input.tool, arguments: input.arguments },
165 + },
166 + { ...limitHeader, "mcp-session-id": sessionId, "mcp-protocol-version": PROTOCOL_VERSION },
167 + );
168 + const existing = (yield* Ref.get(sessions)).get(sessionKey);
169 + const sessionId = existing ?? (yield* openSession(resolved.url, resolved.token, limitHeader));
170 + let response = yield* callOnce(sessionId);
171 + if (response.status === 404) {
172 + const renewed = yield* openSession(resolved.url, resolved.token, limitHeader);
173 + yield* Ref.update(sessions, (current) => new Map(current).set(sessionKey, renewed));
174 + response = yield* callOnce(renewed);
175 + } else if (existing === undefined) {
176 + yield* Ref.update(sessions, (current) => new Map(current).set(sessionKey, sessionId));
177 + }
178 + if (response.status === 401) {
179 + return yield* new OrchestratorMcpFailure({
180 + code: "capability_denied",
181 + message:
182 + "The linked environment no longer accepts this link. It may have been revoked there; link it again.",
183 + });
184 + }
185 + if (response.status !== 200) {
186 + return yield* new OrchestratorMcpFailure({
187 + code: "orchestration_error",
188 + message: `The linked environment answered HTTP ${response.status}.`,
189 + });
190 + }
191 + const body = yield* decodeToolCallResponse(
192 + responseJson(response.headers["content-type"], yield* response.text),
193 + ).pipe(
194 + Effect.mapError(
195 + () =>
196 + new OrchestratorMcpFailure({
197 + code: "orchestration_error",
198 + message: "The linked environment answered in an unexpected shape.",
199 + }),
200 + ),
201 + );
202 + if (body.error !== undefined || body.result === undefined) {
203 + return yield* new OrchestratorMcpFailure({
204 + code: "invalid_request",
205 + message: body.error?.message ?? "The linked environment returned no result.",
206 + });
207 + }
208 + const text = body.result.content.map((part) => part.text ?? "").join("");
209 + if (body.result.isError === true) {
210 + // A refusal keeps the peer's own code, so the agent sees why it was refused.
211 + const refused = decodeFailure(text);
212 + return yield* refused._tag === "Some"
213 + ? new OrchestratorMcpFailure({ code: refused.value.code, message: refused.value.message })
214 + : new OrchestratorMcpFailure({
215 + code: "orchestration_error",
216 + message: text || "The linked environment refused the call.",
217 + });
218 + }
219 + const success = Schema.fromJsonString(input.success);
220 + return yield* Schema.decodeEffect(success)(text).pipe(
221 + Effect.mapError(
222 + () =>
223 + new OrchestratorMcpFailure({
224 + code: "orchestration_error",
225 + message:
226 + "The linked environment's answer did not match this version. Update both environments.",
227 + }),
228 + ),
229 + );
230 + },
231 + (effect, input) =>
232 + effect.pipe(
233 + Effect.tapError((error) =>
234 + links.recordOutcome(input.environmentId, { error: error.message }),
235 + ),
236 + Effect.tap(() => links.recordOutcome(input.environmentId, { error: null })),
237 + // Recorded above with the transport's own message; the agent hears it plainly.
238 + Effect.catchTags({
239 + HttpClientError: () =>
240 + Effect.fail(
241 + new OrchestratorMcpFailure({
242 + code: "orchestration_error",
243 + message: "The linked environment stopped answering.",
244 + }),
245 + ),
246 + }),
247 + ),
248 + );
249 +
250 + return PeerMcpClient.of({ call });
251 +});
252 +
253 +export const layer = Layer.effect(PeerMcpClient, make);
apps/server/src/persistence/Migrations.ts
+2
@@ -72,6 +72,7 @@ import Migration0066 from "./Migrations/066_RepairClientSettlementTimestamps.ts"
72 import Migration0067 from "./Migrations/067_WebhookDedupe.ts";
73 import Migration0068 from "./Migrations/068_ShellStopRequestIndex.ts";
74 import Migration0069 from "./Migrations/069_ThreadMessageSearch.ts";
75 +import Migration0070 from "./Migrations/070_PeerLinks.ts";
76
77 const migrationEntries = [
78 [1, "OrchestrationEvents", Migration0001],
@@ -144,6 +145,7 @@ const migrationEntries = [
145 [67, "WebhookDedupe", Migration0067],
146 [68, "ShellStopRequestIndex", Migration0068],
147 [69, "ThreadMessageSearch", Migration0069],
148 + [70, "PeerLinks", Migration0070],
149 ] as const;
150
151 export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
apps/server/src/persistence/Migrations/070_PeerLinks.ts new
+24
@@ -0,0 +1,24 @@
1 +import * as Effect from "effect/Effect";
2 +import * as SqlClient from "effect/sql/SqlClient";
3 +
4 +export default Effect.gen(function* () {
5 + const sql = yield* SqlClient.SqlClient;
6 +
7 + // Other environments this one signed in to as an outside MCP agent. The
8 + // session token itself is kept in the server secret store under
9 + // `secret_name`, which is unique to each link, so a row always names its
10 + // own token even when two links to one environment race.
11 + yield* sql`
12 + CREATE TABLE IF NOT EXISTS peer_environment_links (
13 + environment_id TEXT PRIMARY KEY,
14 + secret_name TEXT NOT NULL,
15 + label TEXT NOT NULL,
16 + urls_json TEXT NOT NULL,
17 + access TEXT NOT NULL,
18 + linked_at TEXT NOT NULL,
19 + expires_at TEXT NOT NULL,
20 + last_reached_at TEXT,
21 + last_error TEXT
22 + )
23 + `;
24 +});
apps/server/src/persistence/reconcileV2PreviewMigration.test.ts
+2
@@ -49,6 +49,7 @@ describe("V2 preview upgrade", () => {
49 [67, "WebhookDedupe"],
50 [68, "ShellStopRequestIndex"],
51 [69, "ThreadMessageSearch"],
52 + [70, "PeerLinks"],
53 ]);
54 assert.deepStrictEqual(yield* runMigrations(), []);
55 assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports);
@@ -141,6 +142,7 @@ describe("V2 preview upgrade", () => {
142 [67, "WebhookDedupe"],
143 [68, "ShellStopRequestIndex"],
144 [69, "ThreadMessageSearch"],
145 + [70, "PeerLinks"],
146 ]);
147 }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
148 );
apps/server/src/server.ts
+4
@@ -67,6 +67,8 @@ import * as ProviderInstanceRegistryHydration from "./provider/ProviderInstanceR
67 import * as ProjectSettingsOverrideSweep from "./provider/ProjectSettingsOverrideSweep.ts";
68 import * as TerminalManager from "./terminal/Manager.ts";
69 import * as McpHttpServer from "./mcp/McpHttpServer.ts";
70 +import * as PeerLinks from "./peer/PeerLinks.ts";
71 +import * as PeerMcpClient from "./peer/PeerMcpClient.ts";
72 import * as McpSessionRegistry from "./mcp/McpSessionRegistry.ts";
73 import * as PreviewAutomationBroker from "./mcp/PreviewAutomationBroker.ts";
74 import * as DeviceService from "./device/DeviceService.ts";
@@ -740,6 +742,8 @@ const layerMakeRoutes = Layer.mergeAll(
742 ),
743 ),
744 Layer.provide(PreviewBrowser.layer),
745 + // Links to other environments, shared by Settings (WebSocket) and agents (/mcp).
746 + Layer.provide(PeerMcpClient.layer.pipe(Layer.provideMerge(PeerLinks.layer))),
747 Layer.provide(PreviewAutomationBroker.layer),
748 Layer.provide(ServerSelfUpdate.layer.pipe(Layer.provide(layerDesktopAppUpdate))),
749 Layer.provide(layerCommandReadiness),
apps/server/src/ws.test.ts
+2
@@ -54,6 +54,7 @@ import * as ModelManifest from "./provider/ModelManifest.ts";
54 import * as Orchestrator from "./orchestration-v2/Orchestrator.ts";
55 import * as OtlpEndpointCheck from "./observability/OtlpEndpointCheck.ts";
56 import * as PairingGrantStore from "./auth/PairingGrantStore.ts";
57 +import * as PeerLinks from "./peer/PeerLinks.ts";
58 import * as PortScanner from "./preview/PortScanner.ts";
59 import * as PreviewManager from "./preview/Manager.ts";
60 import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
@@ -419,6 +420,7 @@ const layerUnusedConfigRpcServices = Layer.mergeAll(
420 Layer.mock(Orchestrator.OrchestratorV2)({}),
421 Layer.mock(OtlpEndpointCheck.OtlpEndpointCheck)({}),
422 Layer.mock(PairingGrantStore.PairingGrantStore)({}),
423 + Layer.mock(PeerLinks.PeerLinks)({}),
424 Layer.mock(PortScanner.PortDiscovery)({}),
425 Layer.mock(PreviewManager.PreviewManager)({}),
426 Layer.mock(ProcessDiagnostics.ProcessDiagnostics)({}),
apps/server/src/ws.ts
+9
@@ -2,6 +2,7 @@ import { OrchestrationDispatchCommandError } from "@t3tools/contracts";
2 import * as Context from "effect/Context";
3 import * as Crypto from "effect/Crypto";
4 import * as Orchestrator from "./orchestration-v2/Orchestrator.ts";
5 +import * as PeerLinks from "./peer/PeerLinks.ts";
6
7 import * as DateTime from "effect/DateTime";
8 import * as Duration from "effect/Duration";
@@ -1343,6 +1344,7 @@ export const layerWsRpc = (
1344 const storageCleanup = yield* StorageCleanup.StorageCleanup;
1345 const databaseStorage = yield* DatabaseStorage.DatabaseStorage;
1346 const serverSettings = yield* ServerSettings.ServerSettingsService;
1347 + const peerLinks = yield* PeerLinks.PeerLinks;
1348 const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup;
1349 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
1350 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
@@ -2535,6 +2537,11 @@ export const layerWsRpc = (
2537 [WS_METHODS.serverRunStorageCleanup]: () => storageCleanup.runNow,
2538 [WS_METHODS.serverGetStorageCleanupReport]: () => storageCleanup.reports,
2539 [WS_METHODS.serverGetDatabaseStorage]: () => databaseStorage.status,
2540 + [WS_METHODS.peerLinksList]: (_input) =>
2541 + peerLinks.list.pipe(Effect.map((links) => ({ links }))),
2542 + [WS_METHODS.peerLinksLink]: (input) => peerLinks.link(input),
2543 + [WS_METHODS.peerLinksUnlink]: ({ environmentId }) =>
2544 + peerLinks.unlink(environmentId).pipe(Effect.map((removed) => ({ removed }))),
2545 [WS_METHODS.serverGetSettings]: (_input) =>
2546 serverSettings.getSettings.pipe(Effect.map(ServerSettings.redactServerSettingsForClient)),
2547 [WS_METHODS.serverUpdateSettings]:
@@ -3305,6 +3312,7 @@ export const layer = Layer.unwrap(
3312 const serverSelfUpdate = yield* ServerSelfUpdate.ServerSelfUpdate;
3313 const pullRequests = yield* PullRequestService.PullRequestService;
3314 const reviewGuides = yield* PullRequestReviewGuideService.PullRequestReviewGuideService;
3315 + const peerLinks = yield* PeerLinks.PeerLinks;
3316 const sql = yield* SqlClient.SqlClient;
3317 return HttpRouter.add(
3318 "GET",
@@ -3392,6 +3400,7 @@ export const layer = Layer.unwrap(
3400 reviewGuides,
3401 ),
3402 ),
3403 + Layer.provide(Layer.succeed(PeerLinks.PeerLinks, peerLinks)),
3404 Layer.provide(
3405 SourceControlDiscovery.layer.pipe(
3406 Layer.provide(
packages/contracts/src/environment.ts
+8
@@ -134,6 +134,14 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
134 commandOutputStreaming: Schema.optionalKey(Schema.Boolean),
135 /** Hosts headless Chromium tabs streamed over /api/preview-stream for clients without a local runtime. */
136 serverBrowser: Schema.optionalKey(Schema.Boolean),
137 + /** Server links to other environments (`PeerLink`) and its agents can work
138 + in them. Absent on servers from before linking, which clients must not
139 + offer linking for. */
140 + peerLinks: Schema.optionalKey(Schema.Boolean),
141 + /** Server's `/mcp` narrows an OAuth client's modes from `T3-Mode-Limit`, so
142 + a linked environment's calls keep its agent's limits. Another environment
143 + links to this one only when it is set. */
144 + mcpModeLimitHeader: Schema.optionalKey(Schema.Boolean),
145 });
146 export type ExecutionEnvironmentCapabilities = typeof ExecutionEnvironmentCapabilities.Type;
147
packages/contracts/src/index.ts
+1
@@ -41,6 +41,7 @@ export * from "./guestShare.ts";
41 export * from "./guestStream.ts";
42 export * from "./applicationEvent.ts";
43 export * from "./orchestratorMcp.ts";
44 +export * from "./peerLink.ts";
45 export * from "./threadMetadataMcp.ts";
46 export * from "./threadPullRequest.ts";
47 export * from "./threadSearch.ts";
packages/contracts/src/peerLink.ts new
+66
@@ -0,0 +1,66 @@
1 +import * as Schema from "effect/Schema";
2 +
3 +import { AuthMcpClientAccess } from "./auth.ts";
4 +import { EnvironmentId, TrimmedNonEmptyString } 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 +export const PeerLinkCreateInput = Schema.Struct({
36 + /** Where the peer answers: an https, Tailscale, LAN or loopback base URL. */
37 + url: TrimmedNonEmptyString,
38 + /** More addresses for the same peer, tried after `url`. */
39 + alternateUrls: Schema.optionalKey(Schema.Array(TrimmedNonEmptyString)),
40 + /** A pairing code from the peer (`t3 pair` there, or its Connections settings). */
41 + pairingCode: TrimmedNonEmptyString,
42 + access: AuthMcpClientAccess,
43 +});
44 +export type PeerLinkCreateInput = typeof PeerLinkCreateInput.Type;
45 +
46 +export const PeerLinkRemoveInput = Schema.Struct({ environmentId: EnvironmentId });
47 +export type PeerLinkRemoveInput = typeof PeerLinkRemoveInput.Type;
48 +
49 +export const PeerLinkRemoveResult = Schema.Struct({ removed: Schema.Boolean });
50 +export type PeerLinkRemoveResult = typeof PeerLinkRemoveResult.Type;
51 +
52 +/** Why linking or calling a peer failed, in words a user can act on. */
53 +export class PeerLinkError extends Schema.TaggedError<PeerLinkError>()("PeerLinkError", {
54 + reason: Schema.Literals([
55 + "unreachable",
56 + "not_a_t3_environment",
57 + "incompatible",
58 + "self",
59 + "pairing_rejected",
60 + "expired",
61 + "unknown_link",
62 + "storage",
63 + ]),
64 + message: Schema.String,
65 + cause: Schema.optionalKey(Schema.Defect()),
66 +}) {}
packages/contracts/src/rpc.ts
+32
@@ -16,6 +16,14 @@ import {
16 McpAppToolInfoInput,
17 McpAppUpdateModelContextInput,
18 } from "./mcpApps.ts";
19 +import {
20 + PeerLink,
21 + PeerLinkCreateInput,
22 + PeerLinkError,
23 + PeerLinkRemoveInput,
24 + PeerLinkRemoveResult,
25 + PeerLinkSummary,
26 +} from "./peerLink.ts";
27 import {
28 ChatGptReconnectProfileInput,
29 ChatGptReconnectProfile,
@@ -486,6 +494,9 @@ export const WS_METHODS = {
494 serverRunStorageCleanup: "server.runStorageCleanup",
495 serverGetStorageCleanupReport: "server.getStorageCleanupReport",
496 serverGetDatabaseStorage: "server.getDatabaseStorage",
497 + peerLinksList: "peerLinks.list",
498 + peerLinksLink: "peerLinks.link",
499 + peerLinksUnlink: "peerLinks.unlink",
500 serverGetSettings: "server.getSettings",
501 serverUpdateSettings: "server.updateSettings",
502 serverDiscoverSourceControl: "server.discoverSourceControl",
@@ -768,6 +779,24 @@ const WsServerGetDatabaseStorageRpc = Rpc.make(WS_METHODS.serverGetDatabaseStora
779 error: EnvironmentAuthorizationError,
780 });
781
782 +const WsPeerLinksListRpc = Rpc.make(WS_METHODS.peerLinksList, {
783 + payload: Schema.Struct({}),
784 + success: Schema.Struct({ links: Schema.Array(PeerLinkSummary) }),
785 + error: Schema.Union([PeerLinkError, EnvironmentAuthorizationError]),
786 +});
787 +
788 +const WsPeerLinksLinkRpc = Rpc.make(WS_METHODS.peerLinksLink, {
789 + payload: PeerLinkCreateInput,
790 + success: PeerLink,
791 + error: Schema.Union([PeerLinkError, EnvironmentAuthorizationError]),
792 +});
793 +
794 +const WsPeerLinksUnlinkRpc = Rpc.make(WS_METHODS.peerLinksUnlink, {
795 + payload: PeerLinkRemoveInput,
796 + success: PeerLinkRemoveResult,
797 + error: Schema.Union([PeerLinkError, EnvironmentAuthorizationError]),
798 +});
799 +
800 const WsServerGetSettingsRpc = Rpc.make(WS_METHODS.serverGetSettings, {
801 payload: Schema.Struct({}),
802 success: ServerSettings,
@@ -1945,6 +1974,9 @@ export const WsRpcGroup = RpcGroup.make(
1974 WsServerGetDatabaseStorageRpc,
1975 WsServerGetSettingsRpc,
1976 WsServerUpdateSettingsRpc,
1977 + WsPeerLinksListRpc,
1978 + WsPeerLinksLinkRpc,
1979 + WsPeerLinksUnlinkRpc,
1980 WsServerDiscoverSourceControlRpc,
1981 WsServerSearchAcpRegistryRpc,
1982 WsServerPrepareAcpRegistryAgentRpc,