Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

versionProbe.ts

190 lines7.1 KB

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