Open History to see the last commit
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;
24}
25
26export interface OpenCode2UnreadableStart {
27 readonly type: "unreadable.execution.started";
28 readonly sessionID: string;
29}
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 }
46}
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 >;
66}
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
84const decodeEvent = Schema.decodeUnknownResult(Schema.fromJsonString(OpenCodeEvent));
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
94// Rejected stream frames can be frequent when the server introduces new event types.
95const undecodable = Effect.fnUntraced(function* (data: string) {
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
123const readEvents = HttpClient.get("/api/event", {
124 headers: { accept: "text/event-stream" },
125}).pipe(
126 Effect.flatMap(HttpClientResponse.filterStatusOk),
127 Effect.map((response) =>
128 response.stream.pipe(
129 Stream.timeoutOrElse({
130 duration: SILENT_STREAM_TIMEOUT,
131 orElse: () => Stream.fail(new OpenCode2SilentStreamError()),
132 }),
133 Stream.decodeText,
134 Stream.pipeThroughChannel(Sse.decode()),
135 Stream.filterMapEffect((frame) => {
136 const decoded = decodeEvent(frame.data);
137 return Result.isSuccess(decoded)
138 ? Effect.succeed(Result.succeed<OpenCode2StreamEvent>(decoded.success))
139 : undecodable(frame.data);
140 }),
141 ),
142 ),
143);
144
145/**
146 * OpenCode decodes Basic credentials as UTF-8. `HttpClientRequest.basicAuth`
147 * encodes them as Latin-1 (`btoa`), which gets non-ASCII passwords rejected.
148 */
149const basicAuthorization = (password: string | Redacted.Redacted) => {
150 const plain = Redacted.isRedacted(password) ? Redacted.value(password) : password;
151 return `Basic ${Buffer.from(`${OPENCODE_USERNAME}:${plain}`, "utf8").toString("base64")}`;
152};
153
154/** @public Service construction is part of the canonical Effect module API. */
155export const make = Effect.gen(function* () {
156 const httpClient = yield* HttpClient.HttpClient;
157 return OpenCode2Client.of({
158 connect: ({ baseUrl, password }) => {
159 const authenticated = HttpClient.mapRequest(
160 httpClient,
161 HttpClientRequest.setHeader("Authorization", basicAuthorization(password)),
162 );
163 return OpenCode.make({ baseUrl }).pipe(
164 Effect.provideService(HttpClient.HttpClient, authenticated),
165 Effect.map((client) => ({
166 client,
167 events: readEvents.pipe(
168 Effect.provideService(
169 HttpClient.HttpClient,
170 HttpClient.mapRequest(authenticated, HttpClientRequest.prependUrl(baseUrl)),
171 ),
172 ),
173 })),
174 );
175 },
176 });
177});
178
179export const layer = Layer.effect(OpenCode2Client, make);
180
181/**
182 * The first request carries the caller's input (including `order`); later
183 * requests send only the cursor, because OpenCode rejects a cursor combined
184 * with `order`.
185 */
186export const paginate = <Input extends { readonly cursor?: unknown }, Item, E, R>(
187 input: Input,
188 list: (
189 input: Input,
190 ) => Effect.Effect<
191 { readonly data: ReadonlyArray<Item>; readonly cursor: { readonly next?: Input["cursor"] } },
192 E,
193 R
194 >,
195): Stream.Stream<Item, E, R> =>
196 Stream.paginate(input, (request) =>
197 list(request).pipe(
198 Effect.map(
199 (page) =>
200 [
201 page.data,
202 page.data.length === 0 || page.cursor.next === undefined
203 ? Option.none()
204 : Option.some({ ...request, order: undefined, cursor: page.cursor.next }),
205 ] as const,
206 ),
207 ),
208 );