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

OpenCode2Client.ts

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