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
| 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 | type PeerLinkError, |
| 9 | type PeerLinkThreadHistoryInput, |
| 10 | type PeerLinkThreadInput, |
| 11 | type PeerLinkThreadItemInput, |
| 12 | PeerLinkThreadReadError, |
| 13 | } from "@t3tools/contracts"; |
| 14 | import * as Context from "effect/Context"; |
| 15 | import * as DateTime from "effect/DateTime"; |
| 16 | import * as Duration from "effect/Duration"; |
| 17 | import * as Effect from "effect/Effect"; |
| 18 | import * as Layer from "effect/Layer"; |
| 19 | import * as Option from "effect/Option"; |
| 20 | import * as Result from "effect/Result"; |
| 21 | import * as Schema from "effect/Schema"; |
| 22 | import type * as Scope from "effect/Scope"; |
| 23 | import * as Stream from "effect/Stream"; |
| 24 | import * as Sse from "effect/encoding/Sse"; |
| 25 | import * as HttpClient from "effect/http/HttpClient"; |
| 26 | import * as HttpClientRequest from "effect/http/HttpClientRequest"; |
| 27 | import type * as HttpClientResponse from "effect/http/HttpClientResponse"; |
| 28 | |
| 29 | import * as McpInvocationContext from "../mcp/McpInvocationContext.ts"; |
| 30 | import * as PeerLinks from "./PeerLinks.ts"; |
| 31 | |
| 32 | /** |
| 33 | * The linked environment sends a heartbeat every 20 seconds, so a stream this quiet has lost its |
| 34 | * connection without closing it. |
| 35 | */ |
| 36 | const SILENT_STREAM_TIMEOUT = Duration.seconds(75); |
| 37 | |
| 38 | /** |
| 39 | * Relays a linked environment's thread to a client of this environment, over the link this |
| 40 | * environment already holds. The stream is the linked environment's own thread subscription, |
| 41 | * passed on item by item; nothing is held here once the client stops listening. |
| 42 | */ |
| 43 | export class PeerThreadRelay extends Context.Service< |
| 44 | PeerThreadRelay, |
| 45 | { |
| 46 | /** A snapshot of the thread, then its live items, until the client or the peer ends it. */ |
| 47 | readonly subscribe: ( |
| 48 | input: PeerLinkThreadInput, |
| 49 | ) => Stream.Stream<OrchestrationV2ThreadStreamItem, PeerLinkThreadReadError>; |
| 50 | /** The turns before a snapshot's window, as the owner's client pages them. */ |
| 51 | readonly historyPage: ( |
| 52 | input: PeerLinkThreadHistoryInput, |
| 53 | ) => Effect.Effect<OrchestrationV2ThreadHistoryPage, PeerLinkThreadReadError>; |
| 54 | /** One item in full, for a row the reader opens. */ |
| 55 | readonly item: ( |
| 56 | input: PeerLinkThreadItemInput, |
| 57 | ) => Effect.Effect<OrchestrationV2GetTurnItemResult, PeerLinkThreadReadError>; |
| 58 | } |
| 59 | >()("t3/peer/PeerThreadRelay") {} |
| 60 | |
| 61 | const decodeStreamItem = Schema.decodeUnknownOption( |
| 62 | Schema.fromJsonString(Schema.toCodecJson(OrchestrationV2ThreadStreamItem)), |
| 63 | ); |
| 64 | const decodeHistoryPage = Schema.decodeUnknownEffect( |
| 65 | Schema.toCodecJson(OrchestrationV2ThreadHistoryPage), |
| 66 | ); |
| 67 | const decodeItem = Schema.decodeUnknownEffect(Schema.toCodecJson(OrchestrationV2GetTurnItemResult)); |
| 68 | const decodeRefusal = Schema.decodeUnknownOption(Schema.Struct({ error: Schema.String })); |
| 69 | |
| 70 | const unreachable = (label: string, cause?: unknown) => |
| 71 | new PeerLinkThreadReadError({ |
| 72 | reason: "unreachable", |
| 73 | label, |
| 74 | message: `${label} did not answer.`, |
| 75 | ...(cause === undefined ? {} : { cause }), |
| 76 | }); |
| 77 | |
| 78 | /** A link that cannot be used, as the client that asked hears it. */ |
| 79 | const fromLinkError = (error: PeerLinkError, label: string) => |
| 80 | new PeerLinkThreadReadError({ |
| 81 | reason: |
| 82 | error.reason === "unknown_link" || |
| 83 | error.reason === "expired" || |
| 84 | error.reason === "incompatible" |
| 85 | ? error.reason |
| 86 | : "unreachable", |
| 87 | label, |
| 88 | message: error.message, |
| 89 | cause: error, |
| 90 | }); |
| 91 | |
| 92 | /** The linked environment's refusal, as the client that asked hears it. */ |
| 93 | const fromStatus = (status: number, code: string | undefined, label: string) => { |
| 94 | if (status === 404 && code === "thread_not_found") { |
| 95 | return new PeerLinkThreadReadError({ |
| 96 | reason: "thread_not_found", |
| 97 | label, |
| 98 | message: `That thread is no longer on ${label}.`, |
| 99 | }); |
| 100 | } |
| 101 | // An address that stopped serving the route, as after a downgrade there. |
| 102 | if (status === 404) { |
| 103 | return new PeerLinkThreadReadError({ |
| 104 | reason: "incompatible", |
| 105 | label, |
| 106 | message: `${label} runs a T3 Code version that does not share its threads over a link. Update it to read its threads from here.`, |
| 107 | }); |
| 108 | } |
| 109 | if (status === 401 || status === 403) { |
| 110 | return new PeerLinkThreadReadError({ |
| 111 | reason: "rejected", |
| 112 | label, |
| 113 | message: |
| 114 | code === "linked_environments_off" |
| 115 | ? `${label} has Linked environments turned off. Turn it on in its Settings → Labs.` |
| 116 | : `${label} refused the read. Its link may have been revoked there; link it again.`, |
| 117 | }); |
| 118 | } |
| 119 | return unreachable(label, `HTTP ${status}`); |
| 120 | }; |
| 121 | |
| 122 | const make = Effect.gen(function* () { |
| 123 | const links = yield* PeerLinks.PeerLinks; |
| 124 | const httpClient = yield* HttpClient.HttpClient; |
| 125 | |
| 126 | /** |
| 127 | * Asks the linked environment for `route` of the thread. The response stays open until the |
| 128 | * scope closes, which is what ends a stream the client stopped listening to. |
| 129 | */ |
| 130 | const open = Effect.fn("PeerThreadRelay.open")(function* ( |
| 131 | input: PeerLinkThreadInput, |
| 132 | route: string, |
| 133 | params: Record<string, string>, |
| 134 | ): Effect.fn.Return< |
| 135 | { |
| 136 | readonly label: string; |
| 137 | readonly response: HttpClientResponse.HttpClientResponse; |
| 138 | /** How long the peer may take over the rest of an answer that is not a stream. */ |
| 139 | readonly timeout: Duration.Duration; |
| 140 | }, |
| 141 | PeerLinkThreadReadError, |
| 142 | Scope.Scope |
| 143 | > { |
| 144 | if (!(yield* links.enabled)) { |
| 145 | return yield* new PeerLinkThreadReadError({ |
| 146 | reason: "disabled", |
| 147 | label: null, |
| 148 | message: PeerLinks.LINKED_ENVIRONMENTS_OFF, |
| 149 | }); |
| 150 | } |
| 151 | const link = yield* links.get(input.environmentId).pipe( |
| 152 | Effect.mapError( |
| 153 | (error) => |
| 154 | new PeerLinkThreadReadError({ |
| 155 | reason: "unreachable", |
| 156 | label: null, |
| 157 | message: "This environment could not read its links.", |
| 158 | cause: error, |
| 159 | }), |
| 160 | ), |
| 161 | ); |
| 162 | if (Option.isNone(link)) { |
| 163 | return yield* new PeerLinkThreadReadError({ |
| 164 | reason: "unknown_link", |
| 165 | label: null, |
| 166 | message: "This environment is no longer linked to the one this thread is on.", |
| 167 | }); |
| 168 | } |
| 169 | const { label } = link.value; |
| 170 | const resolved = yield* links |
| 171 | .resolve(input.environmentId) |
| 172 | .pipe(Effect.mapError((error) => fromLinkError(error, label))); |
| 173 | if (resolved.capabilities.linkThreadStream !== true) { |
| 174 | return yield* fromStatus(404, undefined, label); |
| 175 | } |
| 176 | const timeout = PeerLinks.probeTimeout(resolved.url); |
| 177 | const query = new URLSearchParams({ thread: input.threadId, ...params }); |
| 178 | const response = yield* HttpClient.withScope(httpClient) |
| 179 | .execute( |
| 180 | HttpClientRequest.get(`${resolved.url}${route}?${query}`).pipe( |
| 181 | HttpClientRequest.setHeaders({ authorization: `Bearer ${resolved.token}` }), |
| 182 | ), |
| 183 | ) |
| 184 | .pipe( |
| 185 | // Bounds the headers only: an open stream stays quiet for as long as the thread does. |
| 186 | Effect.timeout(timeout), |
| 187 | Effect.mapError((error) => unreachable(label, error)), |
| 188 | Effect.tapError((error) => |
| 189 | links.recordOutcome(input.environmentId, { error: error.message }), |
| 190 | ), |
| 191 | ); |
| 192 | if (response.status !== 200) { |
| 193 | // A refusal whose body never arrives is still the refusal its status names. |
| 194 | const refusal = yield* response.json.pipe( |
| 195 | Effect.timeout(timeout), |
| 196 | Effect.map(decodeRefusal), |
| 197 | Effect.orElseSucceed(() => Option.none()), |
| 198 | ); |
| 199 | const failure = fromStatus(response.status, Option.getOrUndefined(refusal)?.error, label); |
| 200 | // A refusal is still an answer: the link reached the peer, except where it was turned away. |
| 201 | yield* links.recordOutcome(input.environmentId, { |
| 202 | error: failure.reason === "thread_not_found" ? null : failure.message, |
| 203 | }); |
| 204 | return yield* failure; |
| 205 | } |
| 206 | yield* links.recordOutcome(input.environmentId, { error: null }); |
| 207 | // A peer renews a link each time it is used, and says when it now ends. |
| 208 | const renewed = Option.flatMap( |
| 209 | Option.fromNullishOr(response.headers[McpInvocationContext.LINK_EXPIRES_AT_HEADER]), |
| 210 | DateTime.make, |
| 211 | ); |
| 212 | if (Option.isSome(renewed)) yield* links.recordExpiry(input.environmentId, renewed.value); |
| 213 | return { label, response, timeout }; |
| 214 | }); |
| 215 | |
| 216 | const readJson = <A>( |
| 217 | opened: ReturnType<typeof open>, |
| 218 | decode: (body: unknown) => Effect.Effect<A, Schema.SchemaError>, |
| 219 | ) => |
| 220 | opened.pipe( |
| 221 | Effect.flatMap(({ label, response, timeout }) => |
| 222 | response.json.pipe( |
| 223 | // A peer that sends headers and then stalls must not leave the read waiting. |
| 224 | Effect.timeout(timeout), |
| 225 | Effect.flatMap(decode), |
| 226 | Effect.mapError((error) => unreachable(label, error)), |
| 227 | ), |
| 228 | ), |
| 229 | Effect.scoped, |
| 230 | ); |
| 231 | |
| 232 | const subscribe: PeerThreadRelay["Service"]["subscribe"] = (input) => |
| 233 | Stream.unwrap( |
| 234 | open(input, PEER_LINK_THREAD_STREAM_ROUTE, {}).pipe( |
| 235 | Effect.map(({ label, response }) => |
| 236 | response.stream.pipe( |
| 237 | Stream.timeoutOrElse({ |
| 238 | duration: SILENT_STREAM_TIMEOUT, |
| 239 | orElse: () => Stream.fail(unreachable(label)), |
| 240 | }), |
| 241 | Stream.decodeText, |
| 242 | Stream.pipeThroughChannel(Sse.decode()), |
| 243 | // An item this version cannot read is skipped, as the owner's own client skips it. |
| 244 | // That includes an event type from a newer peer, which cannot be encoded again. |
| 245 | Stream.filterMap((event) => { |
| 246 | const item = decodeStreamItem(event.data); |
| 247 | return Option.isSome(item) && item.value.kind !== "unknown-event" |
| 248 | ? Result.succeed(item.value) |
| 249 | : Result.failVoid; |
| 250 | }), |
| 251 | Stream.mapError((error) => |
| 252 | error._tag === "PeerLinkThreadReadError" ? error : unreachable(label, error), |
| 253 | ), |
| 254 | // The peer closed the stream: the client hears it and asks again. |
| 255 | Stream.concat(Stream.fail(unreachable(label))), |
| 256 | ), |
| 257 | ), |
| 258 | ), |
| 259 | ).pipe(Stream.withSpan("PeerThreadRelay.subscribe")); |
| 260 | |
| 261 | return PeerThreadRelay.of({ |
| 262 | subscribe, |
| 263 | historyPage: Effect.fn("PeerThreadRelay.historyPage")((input) => |
| 264 | readJson( |
| 265 | open(input, PEER_LINK_THREAD_HISTORY_ROUTE, { cursor: input.cursor }), |
| 266 | decodeHistoryPage, |
| 267 | ), |
| 268 | ), |
| 269 | item: Effect.fn("PeerThreadRelay.item")((input) => |
| 270 | readJson(open(input, PEER_LINK_THREAD_ITEM_ROUTE, { item: input.itemId }), decodeItem), |
| 271 | ), |
| 272 | }); |
| 273 | }); |
| 274 | |
| 275 | export const layer = Layer.effect(PeerThreadRelay, make); |