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

OpenCode2Client.ts

214 lines7.3 KB

1import type { OpenCodeClient } from "@opencode/client/effect";
2import type { 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/**
54 * `events` succeeds once the server accepted the subscription: the stream is
55 * volatile, so callers subscribe before they start work whose events they need.
56 */
57export interface OpenCode2Api {
58 readonly client: OpenCodeClient;
59 readonly events: Effect.Effect<
60 Stream.Stream<
61 OpenCode2StreamEvent,
62 HttpClientError.HttpClientError | Sse.Retry | Sse.SseError | OpenCode2SilentStreamError
63 >,
64 HttpClientError.HttpClientError
65 >;
67​
68export class OpenCode2Client extends Context.Service<
69 OpenCode2Client,
70 {
71 readonly connect: (input: {
72 readonly baseUrl: string;
73 readonly password: string | Redacted.Redacted;
74 }) => Effect.Effect<OpenCode2Api>;
75 }
76>()("@t3tools/provider-opencode/server/v2/OpenCode2Client") {}
77​
78/**
79 * OpenCode writes a `: heartbeat` comment every 10 to 15 seconds, so this long
80 * without a single byte means the server is stuck, not idle.
81 */
82const SILENT_STREAM_TIMEOUT = "45 seconds";
83​
84// Just enough of an event to route it, for frames the full schema rejects.
85const decodeEnvelope = Schema.decodeUnknownOption(
86 Schema.fromJsonString(
87 Schema.Struct({
88 type: Schema.String,
89 data: Schema.optional(Schema.Struct({ sessionID: Schema.optional(Schema.String) })),
90 }),
91 ),
92);
93​
94const undecodable = (data: string) =>
95 Effect.gen(function* () {
96 const envelope = decodeEnvelope(data);
97 const type = envelope._tag === "Some" ? envelope.value.type.slice(0, 80) : "<unreadable>";
98 const sessionID = envelope._tag === "Some" ? envelope.value.data?.sessionID : undefined;
99 if (isExecutionEnd(type) && sessionID !== undefined) {
100 yield* Effect.logWarning(
101 "Ended an OpenCode execution from an event this build cannot decode.",
102 {
103 type,
104 },
105 );
106 return Result.succeed<OpenCode2StreamEvent>({
107 type: "unreadable.execution.ended",
108 executionType: type,
109 sessionID,
110 });
111 }
112 if (type === "session.execution.started" && sessionID !== undefined) {
113 yield* Effect.logDebug("Read an OpenCode execution start this build cannot decode.");
114 return Result.succeed<OpenCode2StreamEvent>({
115 type: "unreadable.execution.started",
116 sessionID,
117 });
118 }
119 yield* Effect.logDebug("Skipped an OpenCode event this build cannot decode.", { type });
120 return Result.failVoid;
121 });
122​
123/** Subscribes to `/api/event`, then streams every frame this build can route. */
124const readEvents = Effect.gen(function* () {
125 const { OpenCodeEvent } = yield* Effect.promise(() => import("@opencode/protocol/groups/event"));
126 const decodeEvent = Schema.decodeUnknownResult(Schema.fromJsonString(OpenCodeEvent));
127 return yield* HttpClient.get("/api/event", {
128 headers: { accept: "text/event-stream" },
129 }).pipe(
130 Effect.flatMap(HttpClientResponse.filterStatusOk),
131 Effect.map((response) =>
132 response.stream.pipe(
133 Stream.timeoutOrElse({
134 duration: SILENT_STREAM_TIMEOUT,
135 orElse: () => Stream.fail(new OpenCode2SilentStreamError()),
136 }),
137 Stream.decodeText,
138 Stream.pipeThroughChannel(Sse.decode()),
139 Stream.filterMapEffect((frame) => {
140 const decoded = decodeEvent(frame.data);
141 return Result.isSuccess(decoded)
142 ? Effect.succeed(Result.succeed<OpenCode2StreamEvent>(decoded.success))
143 : undecodable(frame.data);
144 }),
145 ),
146 ),
147 );
148});
149​
150/**
151 * OpenCode decodes Basic credentials as UTF-8. `HttpClientRequest.basicAuth`
152 * encodes them as Latin-1 (`btoa`), which gets non-ASCII passwords rejected.
153 */
154const basicAuthorization = (password: string | Redacted.Redacted) => {
155 const plain = Redacted.isRedacted(password) ? Redacted.value(password) : password;
156 return `Basic ${Buffer.from(`${OPENCODE_USERNAME}:${plain}`, "utf8").toString("base64")}`;
157};
158​
159/** @public Service construction is part of the canonical Effect module API. */
160export const make = Effect.gen(function* () {
161 const httpClient = yield* HttpClient.HttpClient;
162 return OpenCode2Client.of({
163 connect: ({ baseUrl, password }) => {
164 const authenticated = HttpClient.mapRequest(
165 httpClient,
166 HttpClientRequest.setHeader("Authorization", basicAuthorization(password)),
167 );
168 return Effect.promise(() => import("@opencode/client/effect")).pipe(
169 Effect.flatMap(({ OpenCode }) => OpenCode.make({ baseUrl })),
170 Effect.provideService(HttpClient.HttpClient, authenticated),
171 Effect.map((client) => ({
172 client,
173 events: readEvents.pipe(
174 Effect.provideService(
175 HttpClient.HttpClient,
176 HttpClient.mapRequest(authenticated, HttpClientRequest.prependUrl(baseUrl)),
177 ),
178 ),
179 })),
180 );
181 },
182 });
183});
184​
185export const layer = Layer.effect(OpenCode2Client, make);
186​
187/**
188 * The first request carries the caller's input (including `order`); later
189 * requests send only the cursor, because OpenCode rejects a cursor combined
190 * with `order`.
191 */
192export const paginate = <Input extends { readonly cursor?: unknown }, Item, E, R>(
193 input: Input,
194 list: (
195 input: Input,
196 ) => Effect.Effect<
197 { readonly data: ReadonlyArray<Item>; readonly cursor: { readonly next?: Input["cursor"] } },
198 E,
199 R
200 >,
201): Stream.Stream<Item, E, R> =>
202 Stream.paginate(input, (request) =>
203 list(request).pipe(
204 Effect.map(
205 (page) =>
206 [
207 page.data,
208 page.data.length === 0 || page.cursor.next === undefined
209 ? Option.none()
210 : Option.some({ ...request, order: undefined, cursor: page.cursor.next }),
211 ] as const,
212 ),
213 ),
214 );