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";
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
145/** @public */
146export const make = Effect.gen(function* () {
147 const httpClient = yield* HttpClient.HttpClient;
148 return OpenCode2Client.of({
149 connect: ({ baseUrl, password }) => {
150 const authenticated = HttpClient.mapRequest(
151 httpClient,
152 HttpClientRequest.setHeader("Authorization", basicAuthorization(password)),
153 );
154 return OpenCode.make({ baseUrl }).pipe(
155 Effect.provideService(HttpClient.HttpClient, authenticated),
156 Effect.map((client) => ({
157 client,
158 events: readEvents.pipe(
159 Effect.provideService(
160 HttpClient.HttpClient,
161 HttpClient.mapRequest(authenticated, HttpClientRequest.prependUrl(baseUrl)),
162 ),
163 ),
164 })),
165 );
166 },
167 });
168});
169
170export const layer = Layer.effect(OpenCode2Client, make);
171
172/** Send input only initially; cursor pages must omit order or OpenCode rejects them. */
173export const paginate = <Input extends { readonly cursor?: unknown }, Item, E, R>(
174 input: Input,
175 list: (
176 input: Input,
177 ) => Effect.Effect<
178 { readonly data: ReadonlyArray<Item>; readonly cursor: { readonly next?: Input["cursor"] } },
179 E,
180 R
181 >,
182): Stream.Stream<Item, E, R> =>
183 Stream.paginate(input, (request) =>
184 list(request).pipe(
185 Effect.map(
186 (page) =>
187 [
188 page.data,
189 page.data.length === 0 || page.cursor.next === undefined
190 ? Option.none()
191 : Option.some({ ...request, order: undefined, cursor: page.cursor.next }),
192 ] as const,
193 ),
194 ),
195 );