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

OpenCode2Client.ts

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