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

OpenCode2Server.ts

183 lines6.4 KB

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