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, 04:45 UTC
| 1 | import { resolveProviderProbeTimeoutMs } from "@t3tools/provider-core/server/snapshotProbe"; |
| 2 | import { parseSemver } from "@t3tools/shared/semver"; |
| 3 | import * as Cache from "effect/Cache"; |
| 4 | import * as Duration from "effect/Duration"; |
| 5 | import * as Effect from "effect/Effect"; |
| 6 | import * as Exit from "effect/Exit"; |
| 7 | import * as Option from "effect/Option"; |
| 8 | import * as Schema from "effect/Schema"; |
| 9 | import * as HttpClient from "effect/http/HttpClient"; |
| 10 | import * as HttpClientRequest from "effect/http/HttpClientRequest"; |
| 11 | |
| 12 | import * as OpenCodeRuntime from "./OpenCodeRuntime.ts"; |
| 13 | import { parseGenericCliVersion } from "@t3tools/provider-core/server/snapshotProbe"; |
| 14 | |
| 15 | export interface ProbedOpenCode { |
| 16 | readonly generation: "v1" | "v2"; |
| 17 | readonly version: string; |
| 18 | } |
| 19 | |
| 20 | // Meant to stop a hung `--version`; wrapped installs can take several seconds to start cold. |
| 21 | const OPENCODE_VERSION_PROBE_TIMEOUT_MS = 10_000; |
| 22 | const OPENCODE_SERVER_PROBE_TIMEOUT_MS = 5_000; |
| 23 | // 2.x's own CLI decodes `{version, pid}` from `/api/info`; requiring both keeps unrelated JSON out. |
| 24 | const decodeApiInfo = Schema.decodeUnknownOption( |
| 25 | Schema.fromJsonString(Schema.Struct({ version: Schema.String, pid: Schema.Int })), |
| 26 | ); |
| 27 | const decodeGlobalHealth = Schema.decodeUnknownOption( |
| 28 | Schema.fromJsonString(Schema.Struct({ healthy: Schema.Literal(true), version: Schema.String })), |
| 29 | ); |
| 30 | |
| 31 | function probed(version: string | null | undefined): ProbedOpenCode | undefined { |
| 32 | const major = parseSemver(version ?? "")?.major; |
| 33 | if (!version || major === undefined) return undefined; |
| 34 | return { generation: major >= 2 ? "v2" : "v1", version }; |
| 35 | } |
| 36 | |
| 37 | export const classifyOpenCodeCliVersion = (output: string) => |
| 38 | probed(parseGenericCliVersion(output)); |
| 39 | |
| 40 | // Cross-version paths return HTML 200s, so require JSON; either version returns 401 for bad passwords. |
| 41 | function classifyOpenCodeProbeResponse( |
| 42 | path: "/api/info" | "/global/health", |
| 43 | response: { |
| 44 | readonly status: number; |
| 45 | readonly contentType: string | undefined; |
| 46 | readonly body: string; |
| 47 | }, |
| 48 | ): ProbedOpenCode | "unauthorized" | undefined { |
| 49 | if (response.status === 401) return "unauthorized"; |
| 50 | const mediaType = response.contentType?.split(";")[0]?.trim().toLowerCase(); |
| 51 | if (response.status !== 200 || mediaType !== "application/json") return undefined; |
| 52 | const version: Option.Option<string> = |
| 53 | path === "/api/info" |
| 54 | ? Option.map(decodeApiInfo(response.body), (info) => info.version) |
| 55 | : Option.map(decodeGlobalHealth(response.body), (health) => health.version); |
| 56 | return probed(Option.getOrUndefined(version)); |
| 57 | } |
| 58 | |
| 59 | export const probeOpenCodeBinary = Effect.fn("probeOpenCodeBinary")(function* ( |
| 60 | binaryPath: string, |
| 61 | environment: NodeJS.ProcessEnv | undefined, |
| 62 | ) { |
| 63 | const runtime = yield* OpenCodeRuntime.OpenCodeRuntime; |
| 64 | const timeoutMs = resolveProviderProbeTimeoutMs( |
| 65 | "opencode", |
| 66 | OPENCODE_VERSION_PROBE_TIMEOUT_MS, |
| 67 | environment, |
| 68 | ); |
| 69 | const { stdout } = yield* runtime |
| 70 | .runOpenCodeCommand({ |
| 71 | binaryPath, |
| 72 | args: ["--version"], |
| 73 | ...(environment === undefined ? {} : { environment }), |
| 74 | }) |
| 75 | .pipe( |
| 76 | Effect.timeoutOrElse({ |
| 77 | duration: timeoutMs, |
| 78 | orElse: () => |
| 79 | Effect.fail( |
| 80 | new OpenCodeRuntime.OpenCodeRuntimeError({ |
| 81 | operation: "probeOpenCodeBinary", |
| 82 | detail: `OpenCode CLI version probe timed out after ${timeoutMs / 1_000} seconds.`, |
| 83 | }), |
| 84 | ), |
| 85 | }), |
| 86 | ); |
| 87 | const result = classifyOpenCodeCliVersion(stdout); |
| 88 | if (result) return result; |
| 89 | return yield* new OpenCodeRuntime.OpenCodeRuntimeError({ |
| 90 | operation: "probeOpenCodeBinary", |
| 91 | detail: "Unable to determine OpenCode version from `opencode --version` output.", |
| 92 | }); |
| 93 | }); |
| 94 | |
| 95 | // Use fixed status text; underlying errors may expose URLs, credentials, or password headers. |
| 96 | const probeOpenCodeServer = Effect.fn("probeOpenCodeServer")(function* ( |
| 97 | serverUrl: string, |
| 98 | serverPassword: string, |
| 99 | environment?: NodeJS.ProcessEnv, |
| 100 | ) { |
| 101 | const client = yield* HttpClient.HttpClient; |
| 102 | const baseUrl = URL.parse(serverUrl.trim()); |
| 103 | if (baseUrl?.protocol !== "http:" && baseUrl?.protocol !== "https:") { |
| 104 | return yield* new OpenCodeRuntime.OpenCodeRuntimeError({ |
| 105 | operation: "probeOpenCodeServer", |
| 106 | detail: "The OpenCode server URL is not a valid http:// or https:// URL.", |
| 107 | }); |
| 108 | } |
| 109 | // UTF-8, as the 1.x SDK client sends it; `HttpClientRequest.basicAuth` uses Latin-1 `btoa`. |
| 110 | const authorization = serverPassword |
| 111 | ? `Basic ${Buffer.from(`opencode:${serverPassword}`, "utf8").toString("base64")}` |
| 112 | : undefined; |
| 113 | for (const path of ["/api/info", "/global/health"] as const) { |
| 114 | const url = new URL(baseUrl); |
| 115 | url.pathname = `${url.pathname.replace(/\/+$/, "")}${path}`; |
| 116 | const request = HttpClientRequest.get(url.href); |
| 117 | const result = yield* client |
| 118 | .execute( |
| 119 | authorization |
| 120 | ? HttpClientRequest.setHeader(request, "authorization", authorization) |
| 121 | : request, |
| 122 | ) |
| 123 | .pipe( |
| 124 | Effect.flatMap((response) => |
| 125 | Effect.map(response.text, (body) => |
| 126 | classifyOpenCodeProbeResponse(path, { |
| 127 | status: response.status, |
| 128 | contentType: response.headers["content-type"], |
| 129 | body, |
| 130 | }), |
| 131 | ), |
| 132 | ), |
| 133 | Effect.mapError( |
| 134 | (cause) => |
| 135 | new OpenCodeRuntime.OpenCodeRuntimeError({ |
| 136 | operation: "probeOpenCodeServer", |
| 137 | detail: "Couldn't reach the OpenCode server.", |
| 138 | cause, |
| 139 | }), |
| 140 | ), |
| 141 | Effect.timeoutOrElse({ |
| 142 | duration: resolveProviderProbeTimeoutMs( |
| 143 | "opencode", |
| 144 | OPENCODE_SERVER_PROBE_TIMEOUT_MS, |
| 145 | environment, |
| 146 | ), |
| 147 | orElse: () => |
| 148 | Effect.fail( |
| 149 | new OpenCodeRuntime.OpenCodeRuntimeError({ |
| 150 | operation: "probeOpenCodeServer", |
| 151 | detail: "Timed out while checking the OpenCode server version.", |
| 152 | }), |
| 153 | ), |
| 154 | }), |
| 155 | ); |
| 156 | if (result === "unauthorized") { |
| 157 | return yield* new OpenCodeRuntime.OpenCodeRuntimeError({ |
| 158 | operation: "probeOpenCodeServer", |
| 159 | detail: "401 Unauthorized: the OpenCode server rejected the password.", |
| 160 | }); |
| 161 | } |
| 162 | if (result !== undefined) return result; |
| 163 | } |
| 164 | return yield* new OpenCodeRuntime.OpenCodeRuntimeError({ |
| 165 | operation: "probeOpenCodeServer", |
| 166 | detail: "The server did not identify itself as OpenCode.", |
| 167 | }); |
| 168 | }); |
| 169 | |
| 170 | export const probeOpenCodeRuntime = ( |
| 171 | settings: { |
| 172 | readonly binaryPath: string; |
| 173 | readonly serverUrl: string; |
| 174 | readonly serverPassword: string; |
| 175 | }, |
| 176 | environment?: NodeJS.ProcessEnv, |
| 177 | ): Effect.Effect< |
| 178 | ProbedOpenCode, |
| 179 | OpenCodeRuntime.OpenCodeRuntimeError, |
| 180 | HttpClient.HttpClient | OpenCodeRuntime.OpenCodeRuntime |
| 181 | > => |
| 182 | settings.serverUrl.trim().length > 0 |
| 183 | ? probeOpenCodeServer(settings.serverUrl, settings.serverPassword, environment) |
| 184 | : probeOpenCodeBinary(settings.binaryPath, environment); |
| 185 | |
| 186 | // Only 2.x is kept: 1.x can be upgraded in place while T3 runs, and 2.x converts the shared |
| 187 | // database, so going back is unsupported. |
| 188 | export const makeOpenCodeRuntimeProbe = <E>(probe: Effect.Effect<ProbedOpenCode, E>) => |
| 189 | Effect.map( |
| 190 | Cache.makeWith(() => probe, { |
| 191 | capacity: 1, |
| 192 | timeToLive: (exit) => |
| 193 | Exit.isSuccess(exit) && exit.value.generation === "v2" ? Duration.infinity : Duration.zero, |
| 194 | }), |
| 195 | (cache) => ({ |
| 196 | get: Cache.get(cache, undefined), |
| 197 | refresh: Cache.refresh(cache, undefined), |
| 198 | lastSuccess: Cache.getSuccess(cache, undefined), |
| 199 | record: (probed: ProbedOpenCode) => Cache.set(cache, undefined, probed), |
| 200 | }), |
| 201 | ); |