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

OpenCode2Client.ts

360 lines13.5 KB

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