Open History to see the last commit
1/**
2 * A 2.x server serves every location from one process, so an instance shares
3 * one server across all of its threads and directories.
4 */
5import type { OpenCodeClient } from "@opencode/client/effect";
6import * as Context from "effect/Context";
7import * as Crypto from "effect/Crypto";
8import * as Effect from "effect/Effect";
9import * as Base64Url from "effect/encoding/Base64Url";
10import * as P from "effect/Predicate";
11import * as Redacted from "effect/Redacted";
12import * as HttpClientError from "effect/http/HttpClientError";
13
14import * as OpenCodeRuntime from "../OpenCodeRuntime.ts";
15import * as OpenCodeServerOwner from "../OpenCodeServerOwner.ts";
16import * as OpenCode2Client from "./OpenCode2Client.ts";
17
18const INFO_TIMEOUT = "5 seconds";
19
20export interface OpenCode2Connection extends OpenCode2Client.OpenCode2Api {
21 readonly url: string;
22 readonly version: string;
23 readonly external: boolean;
24}
25
26export class OpenCode2Server extends Context.Service<
27 OpenCode2Server,
28 {
29 readonly withConnection: <A, E, R>(
30 use: (connection: OpenCode2Connection) => Effect.Effect<A, E, R>,
31 ) => Effect.Effect<A, E | OpenCodeRuntime.OpenCodeRuntimeError, R>;
32 }
33>()("@t3tools/provider-opencode/server/v2/OpenCode2Server") {}
34
35/**
36 * OpenCode 2 always requires one and prints a generated one to stdout
37 * otherwise, so T3 supplies its own and keeps it in memory.
38 */
39const generatePassword = Effect.gen(function* () {
40 const crypto = yield* Crypto.Crypto;
41 const bytes = yield* crypto.randomBytes(32).pipe(Effect.orDie);
42 return Redacted.make(Base64Url.encode(bytes), { label: "OPENCODE_PASSWORD" });
43});
44
45/**
46 * `OPENCODE_PASSWORD` wins over `OPENCODE_SERVER_PASSWORD` in OpenCode 2, so
47 * the inherited 1.x variable is dropped to keep the T3 password the only one in
48 * play.
49 */
50export const serverEnvironment = (
51 environment: NodeJS.ProcessEnv,
52 password: Redacted.Redacted,
53): NodeJS.ProcessEnv => {
54 const { OPENCODE_SERVER_PASSWORD: _inherited, ...rest } = environment;
55 return { ...rest, OPENCODE_PASSWORD: Redacted.value(password) };
56};
57
58/** The client wraps HTTP failures in a `ClientError`; this unwraps either shape. */
59const httpFailureOf = (cause: unknown): HttpClientError.HttpClientError | undefined => {
60 if (HttpClientError.isHttpClientError(cause)) return cause;
61 if (
62 P.isTagged(cause, "ClientError") &&
63 P.hasProperty(cause, "cause") &&
64 HttpClientError.isHttpClientError(cause.cause)
65 ) {
66 return cause.cause;
67 }
68 return undefined;
69};
70
71/**
72 * Only a transport failure means the server is unreachable; a 401 without the
73 * 2.x error body is still a rejected password (1.x sends it empty), and any
74 * other failed status is a server error. A 2xx the client cannot decode is not
75 * OpenCode 2 (1.x answers with HTML).
76 */
77const describeInfoFailure = (cause: unknown) => {
78 const failure = httpFailureOf(cause);
79 if (failure?.reason._tag === "TransportError") {
80 return "Could not reach the OpenCode server.";
81 }
82 const status = failure?.response?.status;
83 if (status === 401) return "The OpenCode server rejected the server password.";
84 if (status !== undefined && (status < 200 || status >= 300)) {
85 return `The OpenCode server returned HTTP ${status}.`;
86 }
87 return "The server is not an OpenCode 2 server.";
88};
89
90/**
91 * `/health` and friends answer 200 with the web UI's HTML on every version, so
92 * only this endpoint proves readiness. Details are fixed text because they
93 * reach clients and a `serverUrl` can carry credentials; the underlying failure
94 * stays in `cause`.
95 */
96export const verifyServer = (client: OpenCodeClient) =>
97 client.server.info().pipe(
98 Effect.timeoutOrElse({
99 duration: INFO_TIMEOUT,
100 orElse: () =>
101 Effect.fail(
102 new OpenCodeRuntime.OpenCodeRuntimeError({
103 operation: "server.info",
104 detail: "Timed out waiting for the OpenCode server.",
105 }),
106 ),
107 }),
108 Effect.catchTags({
109 UnauthorizedError: (cause) =>
110 Effect.fail(
111 new OpenCodeRuntime.OpenCodeRuntimeError({
112 operation: "server.info",
113 detail: "The OpenCode server rejected the server password.",
114 cause,
115 }),
116 ),
117 }),
118 Effect.mapError((cause) =>
119 OpenCodeRuntime.isOpenCodeRuntimeError(cause)
120 ? cause
121 : new OpenCodeRuntime.OpenCodeRuntimeError({
122 operation: "server.info",
123 detail: describeInfoFailure(cause),
124 cause,
125 }),
126 ),
127 Effect.map((info) => info.version),
128 );
129
130export const make = Effect.fn("OpenCode2Server.make")(function* (input: {
131 readonly binaryPath: string;
132 readonly serverUrl: string;
133 readonly serverPassword: string;
134 readonly directory: string;
135 readonly environment: NodeJS.ProcessEnv;
136}) {
137 const opencode = yield* OpenCode2Client.OpenCode2Client;
138 const connectTo = Effect.fn("OpenCode2Server.connectTo")(function* (
139 url: string,
140 password: Redacted.Redacted,
141 external: boolean,
142 ) {
143 const api = yield* opencode.connect({ baseUrl: url, password });
144 const version = yield* verifyServer(api.client);
145 return { ...api, url, version, external } satisfies OpenCode2Connection;
146 });
147 let latest: OpenCode2Connection | undefined;
148 const remember = (connection: OpenCode2Connection) =>
149 Effect.sync(() => {
150 latest = connection;
151 return connection.version;
152 });
153
154 const serverUrl = input.serverUrl.trim();
155 if (serverUrl.length > 0) {
156 const connect = connectTo(serverUrl, Redacted.make(input.serverPassword), true).pipe(
157 Effect.tap(remember),
158 );
159 return OpenCode2Server.of({
160 withConnection: (use) =>
161 Effect.suspend(() => (latest === undefined ? connect : Effect.succeed(latest))).pipe(
162 Effect.flatMap(use),
163 ),
164 });
165 }
166
167 const password = yield* generatePassword;
168 const owner = yield* OpenCodeServerOwner.make({
169 binaryPath: input.binaryPath,
170 directory: input.directory,
171 environment: serverEnvironment(input.environment, password),
172 verify: (url) => connectTo(url, password, false).pipe(Effect.flatMap(remember)),
173 });
174 return OpenCode2Server.of({
175 withConnection: (use) =>
176 owner.withServer((server) =>
177 latest?.url === server.url
178 ? use(latest)
179 : Effect.die(new Error("OpenCode 2 server was lent before verification.")),
180 ),
181 });
182});