The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { type AuthEnvironmentScope, EnvironmentHttpApi } from "@t3tools/contracts"; |
| 2 | import * as Cause from "effect/Cause"; |
| 3 | import * as Duration from "effect/Duration"; |
| 4 | import * as Effect from "effect/Effect"; |
| 5 | import * as Option from "effect/Option"; |
| 6 | import * as Predicate from "effect/Predicate"; |
| 7 | import * as Schema from "effect/Schema"; |
| 8 | import * as FetchHttpClient from "effect/http/FetchHttpClient"; |
| 9 | import * as HttpClient from "effect/http/HttpClient"; |
| 10 | import * as HttpClientError from "effect/http/HttpClientError"; |
| 11 | import * as HttpClientRequest from "effect/http/HttpClientRequest"; |
| 12 | import * as HttpApiClient from "effect/http-api/HttpApiClient"; |
| 13 | |
| 14 | import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts"; |
| 15 | import * as ServerConfig from "../config.ts"; |
| 16 | import * as ProcessRunner from "../processRunner.ts"; |
| 17 | import * as ServerOwnership from "../serverOwnership.ts"; |
| 18 | import { |
| 19 | clearPersistedServerRuntimeState, |
| 20 | readLiveServerRuntimeState, |
| 21 | } from "../serverRuntimeState.ts"; |
| 22 | |
| 23 | export class RunningServerUnreachableError extends Schema.TaggedError<RunningServerUnreachableError>()( |
| 24 | "RunningServerUnreachableError", |
| 25 | { origin: Schema.String, cause: Schema.Defect() }, |
| 26 | ) { |
| 27 | override get message(): string { |
| 28 | return `The T3 Code server at ${this.origin} is running but refused the connection, so nothing was changed. Retry, or restart the server and retry.`; |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | export class RunningServerNoReplyError extends Schema.TaggedError<RunningServerNoReplyError>()( |
| 33 | "RunningServerNoReplyError", |
| 34 | { origin: Schema.String, cause: Schema.Defect() }, |
| 35 | ) { |
| 36 | override get message(): string { |
| 37 | return `The T3 Code server at ${this.origin} did not reply, so the change may or may not have been made. Check the current state before you retry.`; |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | export type ServerClient = HttpApiClient.ForApi<typeof EnvironmentHttpApi>; |
| 42 | |
| 43 | // The scope revokes the session; the TTL bounds it if that never runs. |
| 44 | const SESSION_TTL = Duration.minutes(2); |
| 45 | const REQUEST_TIMEOUT = Duration.seconds(30); |
| 46 | |
| 47 | /** A client of the server at `origin`, signed in as a short-lived session for the scope. */ |
| 48 | export const serverClient = Effect.fn("RunningServer.serverClient")(function* ( |
| 49 | origin: string, |
| 50 | scopes: ReadonlyArray<AuthEnvironmentScope>, |
| 51 | ) { |
| 52 | const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth; |
| 53 | const session = yield* Effect.acquireRelease( |
| 54 | environmentAuth.issueSession({ scopes, subject: "cli", label: "t3 cli", ttl: SESSION_TTL }), |
| 55 | ({ sessionId }) => environmentAuth.revokeSession(sessionId).pipe(Effect.ignore({ log: true })), |
| 56 | ); |
| 57 | return yield* HttpApiClient.make(EnvironmentHttpApi, { |
| 58 | baseUrl: origin, |
| 59 | transformClient: HttpClient.mapRequest(HttpClientRequest.bearerToken(session.token)), |
| 60 | }).pipe(Effect.provide(FetchHttpClient.layer)); |
| 61 | }); |
| 62 | |
| 63 | // The request never reached a server, so it changed nothing there. |
| 64 | const NOT_CONNECTED_CODES = new Set([ |
| 65 | "ECONNREFUSED", |
| 66 | "ENOTFOUND", |
| 67 | "EHOSTUNREACH", |
| 68 | "ENETUNREACH", |
| 69 | "EADDRNOTAVAIL", |
| 70 | "UND_ERR_CONNECT_TIMEOUT", |
| 71 | ]); |
| 72 | const systemErrorCode = (error: unknown) => |
| 73 | [error, Predicate.hasProperty(error, "cause") ? error.cause : undefined] |
| 74 | .map((candidate) => (Predicate.hasProperty(candidate, "code") ? candidate.code : undefined)) |
| 75 | .find(Predicate.isString); |
| 76 | const neverConnected = (cause: unknown) => { |
| 77 | if (!HttpClientError.isHttpClientError(cause) || cause.reason._tag !== "TransportError") { |
| 78 | return false; |
| 79 | } |
| 80 | const code = systemErrorCode(cause.reason.cause); |
| 81 | return code !== undefined && NOT_CONNECTED_CODES.has(code); |
| 82 | }; |
| 83 | const isUnanswered = (cause: unknown) => |
| 84 | Cause.isTimeoutError(cause) || |
| 85 | (HttpClientError.isHttpClientError(cause) && cause.response === undefined); |
| 86 | |
| 87 | /** |
| 88 | * Makes a change through the running server, so the server applies it and its clients see it. |
| 89 | * With no server, makes it locally while holding the ownership lock, so none starts midway. |
| 90 | */ |
| 91 | export const changeState = Effect.fn("RunningServer.changeState")(function* <A, E, R, E2, R2>({ |
| 92 | scopes, |
| 93 | viaServer, |
| 94 | locally, |
| 95 | }: { |
| 96 | readonly scopes: ReadonlyArray<AuthEnvironmentScope>; |
| 97 | readonly viaServer: (client: ServerClient) => Effect.Effect<A, E, R>; |
| 98 | readonly locally: Effect.Effect<A, E2, R2>; |
| 99 | }) { |
| 100 | const { serverRuntimeStatePath } = yield* ServerConfig.ServerConfig; |
| 101 | const changeLocally = <E3>( |
| 102 | ifServerRuns: (error: ServerOwnership.ServerAlreadyRunningError) => Effect.Effect<never, E3>, |
| 103 | ) => |
| 104 | ServerOwnership.acquireServerOwnership(serverRuntimeStatePath).pipe( |
| 105 | Effect.provide(ProcessRunner.layer), |
| 106 | Effect.catchTags({ ServerAlreadyRunningError: ifServerRuns }), |
| 107 | Effect.andThen(locally), |
| 108 | // The lock proves the recorded server is gone; drop its record once the change lands. |
| 109 | Effect.tap(() => clearPersistedServerRuntimeState(serverRuntimeStatePath)), |
| 110 | Effect.scoped, |
| 111 | ); |
| 112 | |
| 113 | const running = yield* readLiveServerRuntimeState(serverRuntimeStatePath); |
| 114 | if (Option.isNone(running)) return yield* changeLocally(Effect.fail); |
| 115 | const { origin } = running.value; |
| 116 | return yield* serverClient(origin, scopes).pipe( |
| 117 | Effect.flatMap(viaServer), |
| 118 | Effect.timeout(REQUEST_TIMEOUT), |
| 119 | Effect.scoped, |
| 120 | // A refused connection reached no server, so the lock decides whether one still runs. |
| 121 | Effect.catchIf(neverConnected, (cause) => |
| 122 | changeLocally(() => Effect.fail(new RunningServerUnreachableError({ origin, cause }))), |
| 123 | ), |
| 124 | // Once connected, the server may have made the change; writing it again could repeat it. |
| 125 | Effect.catchIf(isUnanswered, (cause) => |
| 126 | Effect.fail(new RunningServerNoReplyError({ origin, cause })), |
| 127 | ), |
| 128 | ); |
| 129 | }); |