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

OpenCode2Client.ts

251 lines8.9 KB

1import { OpenCode, type OpenCodeClient } from "@opencode/client/effect";
2import { OpenCodeEvent } from "@opencode/protocol/groups/event";
3import * as Context from "effect/Context";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import * as Redacted from "effect/Redacted";
8import * as Result from "effect/Result";
9import * as Schema from "effect/Schema";
10import * as Stream from "effect/Stream";
11import * as Sse from "effect/encoding/Sse";
12import * as HttpClient from "effect/http/HttpClient";
13import * as HttpClientError from "effect/http/HttpClientError";
14import * as HttpClientRequest from "effect/http/HttpClientRequest";
15import * as HttpClientResponse from "effect/http/HttpClientResponse";
16​
17/** OpenCode 2 accepts only HTTP Basic auth, always with this user name. */
18const OPENCODE_USERNAME = "opencode";
19​
20export interface OpenCode2UnreadableTerminal {
21 readonly type: "unreadable.execution.ended";
22 readonly executionType: (typeof EXECUTION_ENDS)[number];
23 readonly sessionID: string;
25​
26export interface OpenCode2UnreadableStart {
27 readonly type: "unreadable.execution.started";
28 readonly sessionID: string;
30​
31const EXECUTION_ENDS = [
32 "session.execution.succeeded",
33 "session.execution.failed",
34 "session.execution.interrupted",
35] as const;
36const isExecutionEnd = (type: string): type is (typeof EXECUTION_ENDS)[number] =>
37 (EXECUTION_ENDS as ReadonlyArray<string>).includes(type);
38​
39export class OpenCode2SilentStreamError extends Schema.TaggedError<OpenCode2SilentStreamError>()(
40 "OpenCode2SilentStreamError",
41 {},
42) {
43 override get message(): string {
44 return "The OpenCode server stopped sending events.";
45 }
47​
48export type OpenCode2StreamEvent =
49 | OpenCodeEvent
50 | OpenCode2UnreadableTerminal
51 | OpenCode2UnreadableStart;
52​
53/** events resolves on subscription acceptance; subscribe before work because the stream is volatile. */
54export interface OpenCode2Api {
55 readonly client: OpenCodeClient;
56 readonly events: Effect.Effect<
57 Stream.Stream<
58 OpenCode2StreamEvent,
59 HttpClientError.HttpClientError | Sse.Retry | Sse.SseError | OpenCode2SilentStreamError
60 >,
61 HttpClientError.HttpClientError
62 >;
64​
65export class OpenCode2Client extends Context.Service<
66 OpenCode2Client,
67 {
68 readonly connect: (input: {
69 readonly baseUrl: string;
70 readonly password: string | Redacted.Redacted;
71 }) => Effect.Effect<OpenCode2Api>;
72 }
73>()("@t3tools/provider-opencode/server/v2/OpenCode2Client") {}
74​
75// Heartbeats arrive every 10-15 seconds; longer silence means stuck, not idle.
76const SILENT_STREAM_TIMEOUT = "45 seconds";
77​
78const decodeEvent = Schema.decodeUnknownResult(Schema.fromJsonString(OpenCodeEvent));
79const decodeEnvelope = Schema.decodeUnknownOption(
80 Schema.fromJsonString(
81 Schema.Struct({
82 type: Schema.String,
83 data: Schema.optional(Schema.Struct({ sessionID: Schema.optional(Schema.String) })),
84 }),
85 ),
86);
87​
88// Rejected stream frames can be frequent when the server introduces new event types.
89const undecodable = Effect.fnUntraced(function* (data: string) {
90 const envelope = decodeEnvelope(data);
91 const type = envelope._tag === "Some" ? envelope.value.type.slice(0, 80) : "<unreadable>";
92 const sessionID = envelope._tag === "Some" ? envelope.value.data?.sessionID : undefined;
93 if (isExecutionEnd(type) && sessionID !== undefined) {
94 yield* Effect.logWarning(
95 "Ended an OpenCode execution from an event this build cannot decode.",
96 {
97 type,
98 },
99 );
100 return Result.succeed<OpenCode2StreamEvent>({
101 type: "unreadable.execution.ended",
102 executionType: type,
103 sessionID,
104 });
105 }
106 if (type === "session.execution.started" && sessionID !== undefined) {
107 yield* Effect.logDebug("Read an OpenCode execution start this build cannot decode.");
108 return Result.succeed<OpenCode2StreamEvent>({
109 type: "unreadable.execution.started",
110 sessionID,
111 });
112 }
113 yield* Effect.logDebug("Skipped an OpenCode event this build cannot decode.", { type });
114 return Result.failVoid;
115});
116​
117const readEvents = HttpClient.get("/api/event", {
118 headers: { accept: "text/event-stream" },
119}).pipe(
120 Effect.flatMap(HttpClientResponse.filterStatusOk),
121 Effect.map((response) =>
122 response.stream.pipe(
123 Stream.timeoutOrElse({
124 duration: SILENT_STREAM_TIMEOUT,
125 orElse: () => Stream.fail(new OpenCode2SilentStreamError()),
126 }),
127 Stream.decodeText,
128 Stream.pipeThroughChannel(Sse.decode()),
129 Stream.filterMapEffect((frame) => {
130 const decoded = decodeEvent(frame.data);
131 return Result.isSuccess(decoded)
132 ? Effect.succeed(Result.succeed<OpenCode2StreamEvent>(decoded.success))
133 : undecodable(frame.data);
134 }),
135 ),
136 ),
137);
138​
139// OpenCode requires UTF-8 Basic credentials; HttpClientRequest.basicAuth uses Latin-1.
140const basicAuthorization = (password: string | Redacted.Redacted) => {
141 const plain = Redacted.isRedacted(password) ? Redacted.value(password) : password;
142 return `Basic ${Buffer.from(`${OPENCODE_USERNAME}:${plain}`, "utf8").toString("base64")}`;
143};
144​
145const MESSAGE_LIST_URL = /\/api\/session\/[^/?#]+\/message(?:[?#]|$)/;
146​
147/** Reads only the page's shape; each message stays opaque for the real schema to judge. */
148const MessagePage = Schema.fromJsonString(
149 Schema.StructWithRest(Schema.Struct({ data: Schema.Array(Schema.Unknown) }), [
150 Schema.Record(Schema.String, Schema.Unknown),
151 ]),
152);
153const decodePage = Schema.decodeUnknownOption(MessagePage);
154const encodePage = Schema.encodeSync(MessagePage);
155​
156const CompactionWithRecent = Schema.Struct({
157 type: Schema.Literal("compaction"),
158 status: Schema.Literals(["running", "completed"]),
159 metadata: Schema.optionalKey(Schema.Unknown),
160});
161const isCompactionWithRecent = Schema.is(CompactionWithRecent);
162const isLegacyMetadata = Schema.is(Schema.Struct({ recent: Schema.String }));
163​
164const fillCompactionRecent = (message: unknown) =>
165 isCompactionWithRecent(message) && !("recent" in message)
166 ? { ...message, recent: isLegacyMetadata(message.metadata) ? message.metadata.recent : "" }
167 : message;
168​
169/**
170 * OpenCode 2.1 dropped a compaction's `recent`, which the bundled 2.0.28 schema requires.
171 * Migrated pre-2.1 compactions keep it under `metadata.recent`; native 2.1 ones have none.
172 * T3 never reads it, so fill the gap; every other field still validates downstream.
173 */
174const fillCompactionRecents = HttpClient.transformResponse(
175 Effect.fnUntraced(function* (
176 pending: Effect.Effect<HttpClientResponse.HttpClientResponse, HttpClientError.HttpClientError>,
177 ) {
178 const response = yield* pending;
179 const { request } = response;
180 if (
181 request.method !== "GET" ||
182 response.status !== 200 ||
183 !MESSAGE_LIST_URL.test(request.url)
184 ) {
185 return response;
186 }
187 const text = yield* response.text;
188 const page = decodePage(text);
189 // The response caches its body, so the untouched one still decodes downstream.
190 if (Option.isNone(page)) return response;
191 const filled = encodePage({ ...page.value, data: page.value.data.map(fillCompactionRecent) });
192 // The filled body is longer than the one the server measured.
193 const { "content-length": _, ...headers } = response.headers;
194 return HttpClientResponse.fromWeb(
195 request,
196 new Response(filled, { status: response.status, headers }),
197 );
198 }),
199);
200​
201/** @public */
202export const make = Effect.gen(function* () {
203 const httpClient = yield* HttpClient.HttpClient;
204 return OpenCode2Client.of({
205 connect: Effect.fn("OpenCode2Client.connect")(function ({ baseUrl, password }) {
206 const authenticated = HttpClient.mapRequest(
207 httpClient,
208 HttpClientRequest.setHeader("Authorization", basicAuthorization(password)),
209 );
210 return OpenCode.make({ baseUrl }).pipe(
211 Effect.provideService(HttpClient.HttpClient, fillCompactionRecents(authenticated)),
212 Effect.map((client) => ({
213 client,
214 events: readEvents.pipe(
215 Effect.provideService(
216 HttpClient.HttpClient,
217 HttpClient.mapRequest(authenticated, HttpClientRequest.prependUrl(baseUrl)),
218 ),
219 ),
220 })),
221 );
222 }),
223 });
224});
225​
226export const layer = Layer.effect(OpenCode2Client, make);
227​
228/** Send input only initially; cursor pages must omit order or OpenCode rejects them. */
229export const paginate = <Input extends { readonly cursor?: unknown }, Item, E, R>(
230 input: Input,
231 list: (
232 input: Input,
233 ) => Effect.Effect<
234 { readonly data: ReadonlyArray<Item>; readonly cursor: { readonly next?: Input["cursor"] } },
235 E,
236 R
237 >,
238): Stream.Stream<Item, E, R> =>
239 Stream.paginate(input, (request) =>
240 list(request).pipe(
241 Effect.map(
242 (page) =>
243 [
244 page.data,
245 page.data.length === 0 || page.cursor.next === undefined
246 ? Option.none()
247 : Option.some({ ...request, order: undefined, cursor: page.cursor.next }),
248 ] as const,
249 ),
250 ),
251 );