Open History to see the last commit
1import * as Path from "effect/Path";
2import { PROVIDER_SEND_TURN_MAX_IMAGE_BYTES } from "@t3tools/contracts";
3import { OpenCode, type OpenCodeClient } from "@opencode/client/effect";
4import { OpenCodeEvent } from "@opencode/protocol/groups/event";
5import * as Context from "effect/Context";
6import * as Effect from "effect/Effect";
7import * as Layer from "effect/Layer";
8import * as Option from "effect/Option";
9import * as Redacted from "effect/Redacted";
10import * as Result from "effect/Result";
11import * as Schema from "effect/Schema";
12import * as Stream from "effect/Stream";
13import * as Sse from "effect/encoding/Sse";
14import * as HttpClient from "effect/http/HttpClient";
15import * as HttpClientError from "effect/http/HttpClientError";
16import * as HttpClientRequest from "effect/http/HttpClientRequest";
17import * as HttpClientResponse from "effect/http/HttpClientResponse";
18
19/** OpenCode 2 accepts only HTTP Basic auth, always with this user name. */
20const OPENCODE_USERNAME = "opencode";
21
22export interface OpenCode2UnreadableTerminal {
23 readonly type: "unreadable.execution.ended";
24 readonly executionType: (typeof EXECUTION_ENDS)[number];
25 readonly sessionID: string;
26}
27
28export interface OpenCode2UnreadableStart {
29 readonly type: "unreadable.execution.started";
30 readonly sessionID: string;
31}
32
33const EXECUTION_ENDS = [
34 "session.execution.succeeded",
35 "session.execution.failed",
36 "session.execution.interrupted",
37] as const;
38const isExecutionEnd = (type: string): type is (typeof EXECUTION_ENDS)[number] =>
39 (EXECUTION_ENDS as ReadonlyArray<string>).includes(type);
40
41export class OpenCode2SilentStreamError extends Schema.TaggedError<OpenCode2SilentStreamError>()(
42 "OpenCode2SilentStreamError",
43 {},
44) {
45 override get message(): string {
46 return "The OpenCode server stopped sending events.";
47 }
48}
49
50export type OpenCode2StreamEvent =
51 | OpenCodeEvent
52 | OpenCode2UnreadableTerminal
53 | OpenCode2UnreadableStart;
54
55export class OpenCode2ImageError extends Schema.TaggedError<OpenCode2ImageError>()(
56 "OpenCode2ImageError",
57 { cause: Schema.Defect() },
58) {}
59
60const IMAGE_MIME: Readonly<Record<string, string>> = {
61 ".png": "image/png",
62 ".jpg": "image/jpeg",
63 ".jpeg": "image/jpeg",
64 ".webp": "image/webp",
65 ".gif": "image/gif",
66};
67export const imagePreviewMime = (extension: string) => IMAGE_MIME[extension.toLowerCase()];
68
69const NativeImageJob = Schema.Struct({
70 kind: Schema.Literal("image"),
71 id: Schema.String,
72 sessionID: Schema.String,
73 status: Schema.Literals(["running", "completed", "error", "cancelled"]),
74 path: Schema.String,
75 model: Schema.String,
76});
77const decodeJobs = Schema.decodeUnknownEffect(
78 Schema.Struct({ data: Schema.Array(Schema.Unknown) }),
79);
80const decodeImageJob = Schema.decodeUnknownOption(NativeImageJob);
81
82/** events resolves on subscription acceptance; subscribe before work because the stream is volatile. */
83export interface OpenCode2Api {
84 readonly client: OpenCodeClient;
85 readonly imageJobs: (
86 sessionID: string,
87 ) => Effect.Effect<ReadonlyArray<typeof NativeImageJob.Type>, OpenCode2ImageError>;
88 readonly readImage: (
89 path: string,
90 directory: string,
91 ) => Effect.Effect<{ uri: string; mime: string }, OpenCode2ImageError>;
92 readonly events: Effect.Effect<
93 Stream.Stream<
94 OpenCode2StreamEvent,
95 HttpClientError.HttpClientError | Sse.Retry | Sse.SseError | OpenCode2SilentStreamError
96 >,
97 HttpClientError.HttpClientError
98 >;
99}
100
101export class OpenCode2Client extends Context.Service<
102 OpenCode2Client,
103 {
104 readonly connect: (input: {
105 readonly baseUrl: string;
106 readonly password: string | Redacted.Redacted;
107 }) => Effect.Effect<OpenCode2Api>;
108 }
109>()("@t3tools/provider-opencode/server/v2/OpenCode2Client") {}
110
111// Heartbeats arrive every 10-15 seconds; longer silence means stuck, not idle.
112const SILENT_STREAM_TIMEOUT = "45 seconds";
113const SUBSCRIPTION_TIMEOUT = "10 seconds";
114
115const decodeEvent = Schema.decodeUnknownResult(Schema.fromJsonString(OpenCodeEvent));
116const decodeEnvelope = Schema.decodeUnknownOption(
117 Schema.fromJsonString(
118 Schema.Struct({
119 type: Schema.String,
120 data: Schema.optional(Schema.Struct({ sessionID: Schema.optional(Schema.String) })),
121 }),
122 ),
123);
124
125// Rejected stream frames can be frequent when the server introduces new event types.
126const undecodable = Effect.fnUntraced(function* (data: string) {
127 const envelope = decodeEnvelope(data);
128 const type = envelope._tag === "Some" ? envelope.value.type.slice(0, 80) : "<unreadable>";
129 const sessionID = envelope._tag === "Some" ? envelope.value.data?.sessionID : undefined;
130 if (isExecutionEnd(type) && sessionID !== undefined) {
131 yield* Effect.logWarning(
132 "Ended an OpenCode execution from an event this build cannot decode.",
133 {
134 type,
135 },
136 );
137 return Result.succeed<OpenCode2StreamEvent>({
138 type: "unreadable.execution.ended",
139 executionType: type,
140 sessionID,
141 });
142 }
143 if (type === "session.execution.started" && sessionID !== undefined) {
144 yield* Effect.logDebug("Read an OpenCode execution start this build cannot decode.");
145 return Result.succeed<OpenCode2StreamEvent>({
146 type: "unreadable.execution.started",
147 sessionID,
148 });
149 }
150 yield* Effect.logDebug("Skipped an OpenCode event this build cannot decode.", { type });
151 return Result.failVoid;
152});
153
154const readEvents = HttpClient.get("/api/event", {
155 headers: { accept: "text/event-stream" },
156}).pipe(
157 Effect.flatMap(HttpClientResponse.filterStatusOk),
158 Effect.map((response) =>
159 response.stream.pipe(
160 Stream.timeoutOrElse({
161 duration: SILENT_STREAM_TIMEOUT,
162 orElse: () => Stream.fail(new OpenCode2SilentStreamError()),
163 }),
164 Stream.decodeText,
165 Stream.pipeThroughChannel(Sse.decode()),
166 Stream.filterMapEffect((frame) => {
167 const decoded = decodeEvent(frame.data);
168 return Result.isSuccess(decoded)
169 ? Effect.succeed(Result.succeed<OpenCode2StreamEvent>(decoded.success))
170 : undecodable(frame.data);
171 }),
172 ),
173 ),
174);
175
176// OpenCode requires UTF-8 Basic credentials; HttpClientRequest.basicAuth uses Latin-1.
177const basicAuthorization = (password: string | Redacted.Redacted) => {
178 const plain = Redacted.isRedacted(password) ? Redacted.value(password) : password;
179 return `Basic ${Buffer.from(`${OPENCODE_USERNAME}:${plain}`, "utf8").toString("base64")}`;
180};
181
182const MESSAGE_LIST_URL = /\/api\/session\/[^/?#]+\/message(?:[?#]|$)/;
183
184/** Reads only the page's shape; each message stays opaque for the real schema to judge. */
185const MessagePage = Schema.fromJsonString(
186 Schema.StructWithRest(Schema.Struct({ data: Schema.Array(Schema.Unknown) }), [
187 Schema.Record(Schema.String, Schema.Unknown),
188 ]),
189);
190const decodePage = Schema.decodeUnknownOption(MessagePage);
191const encodePage = Schema.encodeSync(MessagePage);
192
193const CompactionWithRecent = Schema.Struct({
194 type: Schema.Literal("compaction"),
195 status: Schema.Literals(["running", "completed"]),
196 metadata: Schema.optionalKey(Schema.Unknown),
197});
198const isCompactionWithRecent = Schema.is(CompactionWithRecent);
199const isLegacyMetadata = Schema.is(Schema.Struct({ recent: Schema.String }));
200
201const fillCompactionRecent = (message: unknown) =>
202 isCompactionWithRecent(message) && !("recent" in message)
203 ? { ...message, recent: isLegacyMetadata(message.metadata) ? message.metadata.recent : "" }
204 : message;
205
206/**
207 * OpenCode 2.1 dropped a compaction's `recent`, which the bundled 2.0.28 schema requires.
208 * Migrated pre-2.1 compactions keep it under `metadata.recent`; native 2.1 ones have none.
209 * T3 never reads it, so fill the gap; every other field still validates downstream.
210 */
211const fillCompactionRecents = HttpClient.transformResponse(
212 Effect.fnUntraced(function* (
213 pending: Effect.Effect<HttpClientResponse.HttpClientResponse, HttpClientError.HttpClientError>,
214 ) {
215 const response = yield* pending;
216 const { request } = response;
217 if (
218 request.method !== "GET" ||
219 response.status !== 200 ||
220 !MESSAGE_LIST_URL.test(request.url)
221 ) {
222 return response;
223 }
224 const text = yield* response.text;
225 const page = decodePage(text);
226 // The response caches its body, so the untouched one still decodes downstream.
227 if (Option.isNone(page)) return response;
228 const filled = encodePage({ ...page.value, data: page.value.data.map(fillCompactionRecent) });
229 // The filled body is longer than the one the server measured.
230 const { "content-length": _, ...headers } = response.headers;
231 return HttpClientResponse.fromWeb(
232 request,
233 new Response(filled, { status: response.status, headers }),
234 );
235 }),
236);
237
238/** @public */
239export const make = Effect.gen(function* () {
240 const httpClient = yield* HttpClient.HttpClient;
241 const paths = yield* Path.Path.pipe(Effect.provide(Path.layer));
242 return OpenCode2Client.of({
243 connect: Effect.fn("OpenCode2Client.connect")(function ({ baseUrl, password }) {
244 const authenticated = HttpClient.mapRequest(
245 httpClient,
246 HttpClientRequest.setHeader("Authorization", basicAuthorization(password)),
247 );
248 return OpenCode.make({ baseUrl }).pipe(
249 Effect.provideService(HttpClient.HttpClient, fillCompactionRecents(authenticated)),
250 Effect.map((client) => ({
251 client,
252 imageJobs: (sessionID: string) =>
253 authenticated
254 .get(`${baseUrl}/api/experimental/job`, {
255 urlParams: { sessionID, kind: "image" },
256 })
257 .pipe(
258 Effect.flatMap(HttpClientResponse.filterStatusOk),
259 Effect.flatMap((response) => response.json),
260 Effect.flatMap(decodeJobs),
261 Effect.map((page) =>
262 page.data.flatMap((item) => {
263 const job = decodeImageJob(item);
264 return Option.isSome(job) && job.value.sessionID === sessionID
265 ? [job.value]
266 : [];
267 }),
268 ),
269 Effect.mapError((cause) => new OpenCode2ImageError({ cause })),
270 ),
271 readImage: Effect.fn("OpenCode2Client.readImage")(
272 function* (path: string, directory: string) {
273 const mime = imagePreviewMime(paths.extname(path));
274 if (mime === undefined)
275 return yield* new OpenCode2ImageError({ cause: "Unsupported image format" });
276 const relative = paths.relative(directory, path);
277 // OpenCode confines reads to the requested location, including its own temp images.
278 const outside =
279 relative === ".." ||
280 relative.startsWith(`..${paths.sep}`) ||
281 paths.isAbsolute(relative);
282 const location = outside ? paths.dirname(path) : directory;
283 const file = outside ? paths.basename(path) : relative;
284 const response = yield* authenticated
285 .get(`${baseUrl}/api/fs/read/${encodeURIComponent(file)}`, {
286 urlParams: { "location[directory]": location },
287 })
288 .pipe(Effect.flatMap(HttpClientResponse.filterStatusOk));
289 const bytes = yield* response.arrayBuffer;
290 if (bytes.byteLength > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES)
291 return yield* new OpenCode2ImageError({ cause: "Image exceeds preview limit" });
292 return { uri: `data:${mime};base64,${Buffer.from(bytes).toString("base64")}`, mime };
293 },
294 Effect.timeout("10 seconds"),
295 Effect.mapError((cause) => new OpenCode2ImageError({ cause })),
296 ),
297 events: readEvents.pipe(
298 Effect.provideService(
299 HttpClient.HttpClient,
300 HttpClient.mapRequest(authenticated, HttpClientRequest.prependUrl(baseUrl)).pipe(
301 HttpClient.timeout(SUBSCRIPTION_TIMEOUT),
302 ),
303 ),
304 ),
305 })),
306 );
307 }),
308 });
309});
310
311export const layer = Layer.effect(OpenCode2Client, make);
312
313/** Send input only initially; cursor pages must omit order or OpenCode rejects them. */
314export const paginate = <Input extends { readonly cursor?: unknown }, Item, E, R>(
315 input: Input,
316 list: (
317 input: Input,
318 ) => Effect.Effect<
319 { readonly data: ReadonlyArray<Item>; readonly cursor: { readonly next?: Input["cursor"] } },
320 E,
321 R
322 >,
323): Stream.Stream<Item, E, R> =>
324 Stream.paginate(input, (request) =>
325 list(request).pipe(
326 Effect.map(
327 (page) =>
328 [
329 page.data,
330 page.data.length === 0 || page.cursor.next === undefined
331 ? Option.none()
332 : Option.some({ ...request, order: undefined, cursor: page.cursor.next }),
333 ] as const,
334 ),
335 ),
336 );