@devries-cameron20 / t3code Mirror · read-only
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 21, 03:37 UTC

main
ts 162 lines 6.58 KB
Raw
1 import {
2 OrchestrationV2GetTurnItemResult,
3 OrchestrationV2ThreadHistoryPage,
4 OrchestrationV2ThreadStreamItem,
5 PEER_LINK_THREAD_HISTORY_ROUTE,
6 PEER_LINK_THREAD_ITEM_ROUTE,
7 PEER_LINK_THREAD_STREAM_ROUTE,
8 ThreadId,
9 TurnItemId,
10 } from "@t3tools/contracts";
11 import * as DateTime from "effect/DateTime";
12 import * as Duration from "effect/Duration";
13 import * as Effect from "effect/Effect";
14 import * as Layer from "effect/Layer";
15 import * as Schedule from "effect/Schedule";
16 import * as Schema from "effect/Schema";
17 import * as Stream from "effect/Stream";
18 import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";
19
20 import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
21 import { eventStreamResponse } from "../eventStreamResponse.ts";
22 import * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
23 import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
24 import * as ServerSettings from "../serverSettings.ts";
25 import { subscribeOrchestrationV2Thread } from "../ws.ts";
26
27 /** How soon an open stream ends after its link is revoked here or the beta is turned off. */
28 const ACCESS_RECHECK_INTERVAL = Duration.seconds(30);
29 const NO_STORE = { "cache-control": "no-store" };
30
31 // The owner's thread types hold DateTime values; the JSON codec writes them as strings.
32 const encodeStreamItem = Schema.encodeEffect(
33 Schema.fromJsonString(Schema.toCodecJson(OrchestrationV2ThreadStreamItem)),
34 );
35 const encodeHistoryPage = Schema.encodeEffect(Schema.toCodecJson(OrchestrationV2ThreadHistoryPage));
36 const encodeItem = Schema.encodeEffect(Schema.toCodecJson(OrchestrationV2GetTurnItemResult));
37
38 const refusal = (status: number, error: string) =>
39 HttpServerResponse.jsonUnsafe({ error }, { status, headers: NO_STORE });
40
41 /**
42 * Admits a peer link's session, as `/mcp` does: no browser origin, the link's own bearer, and the
43 * Linked environments beta on here. Every access level may read, as each reads through `/mcp`.
44 */
45 const admitLink = Effect.gen(function* () {
46 const request = yield* HttpServerRequest.HttpServerRequest;
47 if (request.headers.origin !== undefined) return refusal(403, "origin_not_allowed");
48 const auth = yield* EnvironmentAuth.EnvironmentAuth;
49 const settings = yield* ServerSettings.ServerSettingsService;
50 const linksEnabled = settings.getSettings.pipe(
51 Effect.map((current) => current.linkedEnvironmentsEnabled),
52 Effect.orElseSucceed(() => false),
53 );
54 // Verifying renews the link's session, as each `/mcp` call does.
55 const verify = auth.authenticateMcpClient(request).pipe(Effect.option);
56 const client = yield* verify;
57 if (client._tag === "None") return refusal(401, "unauthorized");
58 if (!client.value.peerLink) return refusal(403, "not_a_link_session");
59 if (!(yield* linksEnabled)) return refusal(403, "linked_environments_off");
60 const params = new URLSearchParams(request.url.split("?", 2)[1] ?? "");
61 const threadId = params.get("thread");
62 if (!threadId) return refusal(400, "invalid_request");
63 const threads = yield* ThreadManagement.ThreadManagementService;
64 const shell = yield* threads.getThreadShell(ThreadId.make(threadId)).pipe(Effect.option);
65 if (shell._tag === "None") return refusal(500, "thread_read_failed");
66 if (shell.value === null || shell.value.deletedAt !== null) {
67 return refusal(404, "thread_not_found");
68 }
69 return {
70 threadId: shell.value.id,
71 params,
72 linkExpiresAt: client.value.linkExpiresAt,
73 /** Completes once the link's session or the beta no longer admits it. */
74 revoked: Effect.all([verify, linksEnabled]).pipe(
75 Effect.repeat({
76 schedule: Schedule.spaced(ACCESS_RECHECK_INTERVAL),
77 until: ([current, enabled]) => current._tag === "None" || !enabled,
78 }),
79 ),
80 };
81 });
82
83 const withLinkExpiry = (
84 response: HttpServerResponse.HttpServerResponse,
85 linkExpiresAt: DateTime.Utc | undefined,
86 ) =>
87 linkExpiresAt === undefined
88 ? response
89 : HttpServerResponse.setHeader(
90 response,
91 McpInvocationContext.LINK_EXPIRES_AT_HEADER,
92 DateTime.formatIso(linkExpiresAt),
93 );
94
95 // The owner's thread subscription with a bounded snapshot: the same items, in the same order.
96 const streamRoute = HttpRouter.add(
97 "GET",
98 PEER_LINK_THREAD_STREAM_ROUTE,
99 Effect.gen(function* () {
100 const admitted = yield* admitLink;
101 if (HttpServerResponse.isHttpServerResponse(admitted)) return admitted;
102 const items = yield* subscribeOrchestrationV2Thread({
103 threadId: admitted.threadId,
104 acceptBoundedSnapshot: true,
105 }).pipe(Effect.option);
106 if (items._tag === "None") return refusal(500, "thread_read_failed");
107 return withLinkExpiry(
108 eventStreamResponse(
109 items.value.pipe(
110 // A failed read closes the response; the linking environment reports it and reconnects.
111 Stream.catchCause(() => Stream.empty),
112 Stream.interruptWhen(admitted.revoked),
113 ),
114 encodeStreamItem,
115 ),
116 admitted.linkExpiresAt,
117 );
118 }),
119 );
120
121 const historyRoute = HttpRouter.add(
122 "GET",
123 PEER_LINK_THREAD_HISTORY_ROUTE,
124 Effect.gen(function* () {
125 const admitted = yield* admitLink;
126 if (HttpServerResponse.isHttpServerResponse(admitted)) return admitted;
127 const cursor = admitted.params.get("cursor");
128 if (!cursor) return refusal(400, "invalid_request");
129 const threads = yield* ThreadManagement.ThreadManagementService;
130 const body = yield* threads
131 .getThreadHistoryPage(admitted.threadId, cursor)
132 .pipe(Effect.flatMap(encodeHistoryPage), Effect.option);
133 if (body._tag === "None") return refusal(500, "thread_read_failed");
134 return withLinkExpiry(
135 HttpServerResponse.jsonUnsafe(body.value, { headers: NO_STORE }),
136 admitted.linkExpiresAt,
137 );
138 }),
139 );
140
141 const itemRoute = HttpRouter.add(
142 "GET",
143 PEER_LINK_THREAD_ITEM_ROUTE,
144 Effect.gen(function* () {
145 const admitted = yield* admitLink;
146 if (HttpServerResponse.isHttpServerResponse(admitted)) return admitted;
147 const itemId = admitted.params.get("item");
148 if (!itemId) return refusal(400, "invalid_request");
149 const threads = yield* ThreadManagement.ThreadManagementService;
150 const body = yield* threads
151 .getTurnItem({ threadId: admitted.threadId, itemId: TurnItemId.make(itemId) })
152 .pipe(Effect.flatMap(encodeItem), Effect.option);
153 if (body._tag === "None") return refusal(500, "thread_read_failed");
154 return withLinkExpiry(
155 HttpServerResponse.jsonUnsafe(body.value, { headers: NO_STORE }),
156 admitted.linkExpiresAt,
157 );
158 }),
159 );
160
161 /** What an environment serves of its threads to the environments linked to it. */
162 export const layer = Layer.mergeAll(streamRoute, historyRoute, itemRoute);