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/** 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 >;
63}
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";
77const SUBSCRIPTION_TIMEOUT = "10 seconds";
78
79const decodeEvent = Schema.decodeUnknownResult(Schema.fromJsonString(OpenCodeEvent));
80const decodeEnvelope = Schema.decodeUnknownOption(
81 Schema.fromJsonString(
82 Schema.Struct({
83 type: Schema.String,
84 data: Schema.optional(Schema.Struct({ sessionID: Schema.optional(Schema.String) })),
85 }),
86 ),
87);
88
89// Rejected stream frames can be frequent when the server introduces new event types.
90const undecodable = Effect.fnUntraced(function* (data: string) {
91 const envelope = decodeEnvelope(data);
92 const type = envelope._tag === "Some" ? envelope.value.type.slice(0, 80) : "<unreadable>";
93 const sessionID = envelope._tag === "Some" ? envelope.value.data?.sessionID : undefined;
94 if (isExecutionEnd(type) && sessionID !== undefined) {
95 yield* Effect.logWarning(
96 "Ended an OpenCode execution from an event this build cannot decode.",
97 {
98 type,
99 },
100 );
101 return Result.succeed<OpenCode2StreamEvent>({
102 type: "unreadable.execution.ended",
103 executionType: type,
104 sessionID,
105 });
106 }
107 if (type === "session.execution.started" && sessionID !== undefined) {
108 yield* Effect.logDebug("Read an OpenCode execution start this build cannot decode.");
109 return Result.succeed<OpenCode2StreamEvent>({
110 type: "unreadable.execution.started",
111 sessionID,
112 });
113 }
114 yield* Effect.logDebug("Skipped an OpenCode event this build cannot decode.", { type });
115 return Result.failVoid;
116});
117
118const readEvents = HttpClient.get("/api/event", {
119 headers: { accept: "text/event-stream" },
120}).pipe(
121 Effect.flatMap(HttpClientResponse.filterStatusOk),
122 Effect.map((response) =>
123 response.stream.pipe(
124 Stream.timeoutOrElse({
125 duration: SILENT_STREAM_TIMEOUT,
126 orElse: () => Stream.fail(new OpenCode2SilentStreamError()),
127 }),
128 Stream.decodeText,
129 Stream.pipeThroughChannel(Sse.decode()),
130 Stream.filterMapEffect((frame) => {
131 const decoded = decodeEvent(frame.data);
132 return Result.isSuccess(decoded)
133 ? Effect.succeed(Result.succeed<OpenCode2StreamEvent>(decoded.success))
134 : undecodable(frame.data);
135 }),
136 ),
137 ),
138);
139
140// OpenCode requires UTF-8 Basic credentials; HttpClientRequest.basicAuth uses Latin-1.
141const basicAuthorization = (password: string | Redacted.Redacted) => {
142 const plain = Redacted.isRedacted(password) ? Redacted.value(password) : password;
143 return `Basic ${Buffer.from(`${OPENCODE_USERNAME}:${plain}`, "utf8").toString("base64")}`;
144};
145
146const MESSAGE_LIST_URL = /\/api\/session\/[^/?#]+\/message(?:[?#]|$)/;
147
148/** Reads only the page's shape; each message stays opaque for the real schema to judge. */
149const MessagePage = Schema.fromJsonString(
150 Schema.StructWithRest(Schema.Struct({ data: Schema.Array(Schema.Unknown) }), [
151 Schema.Record(Schema.String, Schema.Unknown),
152 ]),
153);
154const decodePage = Schema.decodeUnknownOption(MessagePage);
155const encodePage = Schema.encodeSync(MessagePage);
156
157const CompactionWithRecent = Schema.Struct({
158 type: Schema.Literal("compaction"),
159 status: Schema.Literals(["running", "completed"]),
160 metadata: Schema.optionalKey(Schema.Unknown),
161});
162const isCompactionWithRecent = Schema.is(CompactionWithRecent);
163const isLegacyMetadata = Schema.is(Schema.Struct({ recent: Schema.String }));
164
165const fillCompactionRecent = (message: unknown) =>
166 isCompactionWithRecent(message) && !("recent" in message)
167 ? { ...message, recent: isLegacyMetadata(message.metadata) ? message.metadata.recent : "" }
168 : message;
169
170/**
171 * OpenCode 2.1 dropped a compaction's `recent`, which the bundled 2.0.28 schema requires.
172 * Migrated pre-2.1 compactions keep it under `metadata.recent`; native 2.1 ones have none.
173 * T3 never reads it, so fill the gap; every other field still validates downstream.
174 */
175const fillCompactionRecents = HttpClient.transformResponse(
176 Effect.fnUntraced(function* (
177 pending: Effect.Effect<HttpClientResponse.HttpClientResponse, HttpClientError.HttpClientError>,
178 ) {
179 const response = yield* pending;
180 const { request } = response;
181 if (
182 request.method !== "GET" ||
183 response.status !== 200 ||
184 !MESSAGE_LIST_URL.test(request.url)
185 ) {
186 return response;
187 }
188 const text = yield* response.text;
189 const page = decodePage(text);
190 // The response caches its body, so the untouched one still decodes downstream.
191 if (Option.isNone(page)) return response;
192 const filled = encodePage({ ...page.value, data: page.value.data.map(fillCompactionRecent) });
193 // The filled body is longer than the one the server measured.
194 const { "content-length": _, ...headers } = response.headers;
195 return HttpClientResponse.fromWeb(
196 request,
197 new Response(filled, { status: response.status, headers }),
198 );
199 }),
200);
201
202/** @public */
203export const make = Effect.gen(function* () {
204 const httpClient = yield* HttpClient.HttpClient;
205 return OpenCode2Client.of({
206 connect: Effect.fn("OpenCode2Client.connect")(function ({ baseUrl, password }) {
207 const authenticated = HttpClient.mapRequest(
208 httpClient,
209 HttpClientRequest.setHeader("Authorization", basicAuthorization(password)),
210 );
211 return OpenCode.make({ baseUrl }).pipe(
212 Effect.provideService(HttpClient.HttpClient, fillCompactionRecents(authenticated)),
213 Effect.map((client) => ({
214 client,
215 events: readEvents.pipe(
216 Effect.provideService(
217 HttpClient.HttpClient,
218 HttpClient.mapRequest(authenticated, HttpClientRequest.prependUrl(baseUrl)).pipe(
219 HttpClient.timeout(SUBSCRIPTION_TIMEOUT),
220 ),
221 ),
222 ),
223 })),
224 );
225 }),
226 });
227});
228
229export const layer = Layer.effect(OpenCode2Client, make);
230
231/** Send input only initially; cursor pages must omit order or OpenCode rejects them. */
232export const paginate = <Input extends { readonly cursor?: unknown }, Item, E, R>(
233 input: Input,
234 list: (
235 input: Input,
236 ) => Effect.Effect<
237 { readonly data: ReadonlyArray<Item>; readonly cursor: { readonly next?: Input["cursor"] } },
238 E,
239 R
240 >,
241): Stream.Stream<Item, E, R> =>
242 Stream.paginate(input, (request) =>
243 list(request).pipe(
244 Effect.map(
245 (page) =>
246 [
247 page.data,
248 page.data.length === 0 || page.cursor.next === undefined
249 ? Option.none()
250 : Option.some({ ...request, order: undefined, cursor: page.cursor.next }),
251 ] as const,
252 ),
253 ),
254 );