TypeScript
fix(opencode): decode compaction history from OpenCode 2.1 (#22661)
Julius Marminge53e168fef5ef
diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.tsindex 0ee94d49439..c334af4fad1 100644--- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts+++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts@@ -3630,6 +3630,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {status: "completed",reason: "auto",summary: "First turn summary",+ recent: 42,},{ id: "msg_dropped", time: { created: 3 }, text: "second", type: "user" },],diff --git a/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts b/packages/provider-opencode/src/server/v2/OpenCode2Client.test.tsindex cee3372e146..cf99beeecb2 100644--- a/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts+++ b/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts@@ -1,7 +1,9 @@import { assert, it } from "@effect/vitest";+import { Session } from "@opencode/client/effect";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import * as Redacted from "effect/Redacted";+import * as Schema from "effect/Schema";import * as HttpClient from "effect/http/HttpClient";import * as HttpClientResponse from "effect/http/HttpClientResponse";import { describe } from "vite-plus/test";@@ -45,3 +47,89 @@ describe("OpenCode2Client authorization", () => {}),);});++const previous = {+ id: "msg_repro088",+ type: "synthetic",+ text: "Fixture message 88",+ time: { created: 1088 },+};++const compaction = (fields: Record<string, unknown>) => ({+ type: "compaction",+ id: "msg_repro089",+ time: { created: 1089 },+ reason: "manual",+ summary: "Fixture compaction",+ ...fields,+});++const listHistory = (messages: ReadonlyArray<unknown>) =>+ Effect.gen(function* () {+ const transport = Layer.succeed(+ HttpClient.HttpClient,+ HttpClient.make((request) =>+ Effect.sync(() => {+ assert.include(request.url, "/api/session/ses_repro/message");+ return HttpClientResponse.fromWeb(+ request,+ new Response(JSON.stringify({ data: messages, cursor: {} }), {+ headers: { "content-type": "application/json" },+ }),+ );+ }),+ ),+ );+ const opencode = yield* OpenCode2Client.OpenCode2Client.pipe(+ Effect.provide(OpenCode2Client.layer.pipe(Layer.provide(transport))),+ );+ const { client } = yield* opencode.connect({+ baseUrl: "http://127.0.0.1:4096",+ password: "test-password",+ });+ return yield* client.message.list({ sessionID: Session.ID.make("ses_repro"), order: "asc" });+ });++describe("OpenCode2Client message history", () => {+ it.effect.each([+ { status: "running", shape: "native keepID", fields: { metadata: { keepID: previous.id } } },+ { status: "completed", shape: "native keepID", fields: { metadata: { keepID: previous.id } } },+ { status: "running", shape: "native without metadata", fields: {} },+ { status: "completed", shape: "native without metadata", fields: {} },+ {+ status: "completed",+ shape: "legacy metadata",+ fields: { metadata: { recent: previous.id } },+ },+ { status: "running", shape: "top-level", fields: { recent: previous.id } },+ ] as const)("decodes a $status compaction in the $shape format", ({ status, fields }) =>+ Effect.gen(function* () {+ const history = yield* listHistory([previous, compaction({ status, ...fields })]);++ assert.deepStrictEqual(+ history.data.map((message) => message.id),+ [previous.id, "msg_repro089"],+ );+ assert.deepInclude(history.data[1], {+ type: "compaction",+ status,+ summary: "Fixture compaction",+ recent:+ "metadata" in fields && "recent" in fields.metadata ? previous.id : (fields.recent ?? ""),+ });+ }),+ );++ it.effect.each([+ { field: "recent", fields: { status: "completed", recent: 42 } },+ { field: "reason", fields: { status: "completed", reason: "scheduled", recent: previous.id } },+ ] as const)("keeps a compaction with an invalid $field an error", ({ field, fields }) =>+ Effect.gen(function* () {+ const error = yield* listHistory([compaction(fields)]).pipe(Effect.flip);++ assert.strictEqual(error._tag, "ClientError");+ assert.isTrue(Schema.isSchemaError(error.cause));+ assert.include(String(error.cause), field);+ }),+ );+});diff --git a/packages/provider-opencode/src/server/v2/OpenCode2Client.ts b/packages/provider-opencode/src/server/v2/OpenCode2Client.tsindex 79f6d5f9173..dc7de72ae13 100644--- a/packages/provider-opencode/src/server/v2/OpenCode2Client.ts+++ b/packages/provider-opencode/src/server/v2/OpenCode2Client.ts@@ -142,6 +142,62 @@ const basicAuthorization = (password: string | Redacted.Redacted) => {return `Basic ${Buffer.from(`${OPENCODE_USERNAME}:${plain}`, "utf8").toString("base64")}`;};+const MESSAGE_LIST_URL = /\/api\/session\/[^/?#]+\/message(?:[?#]|$)/;++/** Reads only the page's shape; each message stays opaque for the real schema to judge. */+const MessagePage = Schema.fromJsonString(+ Schema.StructWithRest(Schema.Struct({ data: Schema.Array(Schema.Unknown) }), [+ Schema.Record(Schema.String, Schema.Unknown),+ ]),+);+const decodePage = Schema.decodeUnknownOption(MessagePage);+const encodePage = Schema.encodeSync(MessagePage);++const CompactionWithRecent = Schema.Struct({+ type: Schema.Literal("compaction"),+ status: Schema.Literals(["running", "completed"]),+ metadata: Schema.optionalKey(Schema.Unknown),+});+const isCompactionWithRecent = Schema.is(CompactionWithRecent);+const isLegacyMetadata = Schema.is(Schema.Struct({ recent: Schema.String }));++const fillCompactionRecent = (message: unknown) =>+ isCompactionWithRecent(message) && !("recent" in message)+ ? { ...message, recent: isLegacyMetadata(message.metadata) ? message.metadata.recent : "" }+ : message;++/**+ * OpenCode 2.1 dropped a compaction's `recent`, which the bundled 2.0.28 schema requires.+ * Migrated pre-2.1 compactions keep it under `metadata.recent`; native 2.1 ones have none.+ * T3 never reads it, so fill the gap; every other field still validates downstream.+ */+const fillCompactionRecents = HttpClient.transformResponse(+ Effect.fnUntraced(function* (+ pending: Effect.Effect<HttpClientResponse.HttpClientResponse, HttpClientError.HttpClientError>,+ ) {+ const response = yield* pending;+ const { request } = response;+ if (+ request.method !== "GET" ||+ response.status !== 200 ||+ !MESSAGE_LIST_URL.test(request.url)+ ) {+ return response;+ }+ const text = yield* response.text;+ const page = decodePage(text);+ // The response caches its body, so the untouched one still decodes downstream.+ if (Option.isNone(page)) return response;+ const filled = encodePage({ ...page.value, data: page.value.data.map(fillCompactionRecent) });+ // The filled body is longer than the one the server measured.+ const { "content-length": _, ...headers } = response.headers;+ return HttpClientResponse.fromWeb(+ request,+ new Response(filled, { status: response.status, headers }),+ );+ }),+);+/** @public */export const make = Effect.gen(function* () {const httpClient = yield* HttpClient.HttpClient;@@ -152,7 +208,7 @@ export const make = Effect.gen(function* () {HttpClientRequest.setHeader("Authorization", basicAuthorization(password)),);return OpenCode.make({ baseUrl }).pipe(- Effect.provideService(HttpClient.HttpClient, authenticated),+ Effect.provideService(HttpClient.HttpClient, fillCompactionRecents(authenticated)),Effect.map((client) => ({client,events: readEvents.pipe(