diff --git a/packages/client/src/promise/api.ts b/packages/client/src/promise/api.ts index 2c3d7d67c11..ede1fdaf749 100644 --- a/packages/client/src/promise/api.ts +++ b/packages/client/src/promise/api.ts @@ -16,6 +16,7 @@ export type ExperimentalGenerateApi = Client["experimental"]["generate"] export type ExperimentalSessionApi = Client["experimental"]["session"] export type IntegrationApi = Client["integration"] export type McpApi = Client["mcp"] +export type MessageApi = Client["message"] export type ModelApi = Client["model"] export type PluginApi = Client["plugin"] export type PermissionApi = Client["permission"] diff --git a/packages/core/src/plugin/host.ts b/packages/core/src/plugin/host.ts index 19a163d9aee..2e1a9300275 100644 --- a/packages/core/src/plugin/host.ts +++ b/packages/core/src/plugin/host.ts @@ -4,6 +4,7 @@ import { Plugin } from "@opencode/plugin/effect" import type { IntegrationMethodRegistration } from "@opencode/plugin/effect/integration" import { EventManifest } from "@opencode/schema/event-manifest" import type { Event } from "@opencode/schema/event" +import { PublicLocationSwitched, SessionMessagesQuery } from "@opencode/schema/session-message-page" import { ServerConfig } from "@opencode/schema/mcp" import { App } from "../app.js" import { Effect, Schema, Stream } from "effect" @@ -21,6 +22,7 @@ import { LocationServiceMap } from "../location-service-map.js" import { Model } from "../model.js" import { Mcp } from "../mcp/index.js" import { Session } from "../session.js" +import { MessagePage } from "../session/message-page.js" import { InstructionEntry } from "../session/instruction-entry.js" import { PersistentPty } from "../persistent-pty.js" import { Provider } from "../provider.js" @@ -41,6 +43,8 @@ import type { Interface } from "../plugin.js" import { LayerNode } from "@opencode/util/effect/layer-node" const mutable = (value: T) => value as DeepMutable +const decodeMessageQuery = Schema.decodeUnknownEffect(Schema.toType(SessionMessagesQuery)) +const publicLocationSwitch = Schema.decodeSync(Schema.toType(PublicLocationSwitched)) type RpcEvent = Event.Payload & { readonly type: `rpc.${string}` readonly location: Location.Ref @@ -607,6 +611,18 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: Pick ({ interrupted }))), wait: (input) => sessions.wait(input.sessionID), context: (input) => sessions.context(input.sessionID), + message: { + list: Effect.fn(function* (input) { + const query = yield* decodeMessageQuery(input) + const page = yield* MessagePage.list(sessions.messages, { ...query, sessionID: input.sessionID }) + return { + cursor: page.cursor, + data: page.data.map((message) => + message.type === "location-switched" ? publicLocationSwitch(message) : message, + ), + } + }), + }, instructions: { entry: { list: Effect.fn(function* (input) { diff --git a/packages/core/src/session/message-page.ts b/packages/core/src/session/message-page.ts new file mode 100644 index 00000000000..c4cb8b04c21 --- /dev/null +++ b/packages/core/src/session/message-page.ts @@ -0,0 +1,54 @@ +export * as MessagePage from "./message-page.js" + +import { InvalidCursorError, SessionNotFoundError, UnknownError } from "@opencode/schema/api-error" +import type { SessionMessagesQuery } from "@opencode/schema/session-message-page" +import { Effect, Option, Schema } from "effect" +import type { Session } from "../session.js" +import { SessionMessage } from "./message.js" +import type { SessionStore } from "./store.js" + +const Cursor = Schema.Struct({ + id: SessionMessage.ID, + order: Schema.Literals(["asc", "desc"]), + direction: Schema.Literals(["previous", "next"]), +}) +const decodeCursor = Schema.decodeUnknownOption(Schema.fromJsonString(Cursor)) + +export const list = Effect.fn("MessagePage.list")(function* ( + read: ( + input: SessionStore.MessagesInput, + ) => Effect.Effect, Session.NotFoundError | Session.MessageDecodeError>, + input: SessionMessagesQuery & { readonly sessionID: Session.ID }, +) { + if (input.cursor && input.order !== undefined) + return yield* new InvalidCursorError({ message: "Cursor cannot be combined with order" }) + const decoded = input.cursor + ? (Option.getOrUndefined(decodeCursor(Buffer.from(input.cursor, "base64url").toString("utf8"))) ?? + (yield* new InvalidCursorError({ message: "Invalid cursor" }))) + : undefined + const order = decoded?.order ?? input.order ?? "desc" + const messages = yield* read({ ...input, limit: input.limit ?? 50, order, cursor: decoded }).pipe( + Effect.catchTag("Session.NotFoundError", missingSession), + Effect.catchTag("Session.MessageDecodeError", failedMessageDecode), + ) + const cursor = (message: M | undefined, direction: "previous" | "next") => + message ? Buffer.from(JSON.stringify({ id: message.id, order, direction })).toString("base64url") : undefined + return { + data: messages, + cursor: { previous: cursor(messages[0], "previous"), next: cursor(messages.at(-1), "next") }, + } +}) + +export function missingSession(error: Session.NotFoundError) { + return new SessionNotFoundError({ sessionID: error.sessionID, message: `Session not found: ${error.sessionID}` }) +} + +export function failedMessageDecode(error: Session.MessageDecodeError) { + const ref = `err_${crypto.randomUUID().slice(0, 8)}` + return Effect.logError("failed to decode session message").pipe( + Effect.annotateLogs({ ref, sessionID: error.sessionID, messageID: error.messageID }), + Effect.andThen( + Effect.fail(new UnknownError({ message: "Unexpected server error. Check server logs for details.", ref })), + ), + ) +} diff --git a/packages/core/test/plugin/host.ts b/packages/core/test/plugin/host.ts index bc436ab7d24..bdc1319b72b 100644 --- a/packages/core/test/plugin/host.ts +++ b/packages/core/test/plugin/host.ts @@ -194,6 +194,7 @@ export function host(overrides: Overrides = {}): Plugin.Context { interrupt: overrides.session?.interrupt ?? (() => Effect.die("unused session.interrupt")), wait: overrides.session?.wait ?? (() => Effect.die("unused session.wait")), context: overrides.session?.context ?? (() => Effect.die("unused session.context")), + message: overrides.session?.message ?? { list: () => Effect.die("unused session.message.list") }, instructions: overrides.session?.instructions ?? { entry: { list: () => Effect.die("unused session.instructions.entry.list"), diff --git a/packages/core/test/plugin/session-messages.test.ts b/packages/core/test/plugin/session-messages.test.ts new file mode 100644 index 00000000000..540dee767db --- /dev/null +++ b/packages/core/test/plugin/session-messages.test.ts @@ -0,0 +1,70 @@ +import { expect } from "bun:test" +import { Database } from "@opencode/core/database/database" +import { Plugin } from "@opencode/core/plugin" +import { PluginHost } from "@opencode/core/plugin/host" +import { PluginPromise } from "@opencode/core/plugin/promise" +import { Session } from "@opencode/core/session" +import { SessionMessage } from "@opencode/core/session/message" +import { SessionMessageTable } from "@opencode/core/session/sql" +import { Effect } from "effect" +import { testEffect } from "../lib/effect" +import { PluginTestLayer } from "./fixture" + +const it = testEffect(PluginTestLayer) + +it.live("Promise and Effect plugins can follow the same filtered transcript page forward and backward", () => + Effect.gen(function* () { + const plugins = yield* Plugin.Service + const host = yield* PluginHost.make(plugins, "test") + const session = yield* host.session.create({ title: "Message pages" }) + const { db } = yield* Database.Service + const ids = [SessionMessage.ID.create(), SessionMessage.ID.create(), SessionMessage.ID.create()] as const + const location = { directory: host.location.directory, workspaceID: "wrk_internal" } + const rows = ids.map((id, i) => ({ + id, + session_id: session.id, + type: i === 1 ? ("location-switched" as const) : ("user" as const), + seq: 100 + i, + data: { + ...(i === 1 ? { location, previous: { location } } : { text: `message ${i}` }), + time: { created: 300 - i }, + }, + })) + yield* db.insert(SessionMessageTable).values(rows).run() + const input = { sessionID: session.id, limit: 1, type: "user" } as const + const first = yield* host.session.message.list(input) + expect(first.data.map((m) => m.id)).toEqual([ids[2]]) + const moves = yield* host.session.message.list({ sessionID: session.id, type: "location-switched" }) + const move = moves.data.find((m) => m.type === "location-switched" && m.id === ids[1]) + expect(move).toBeDefined() + if (move?.type === "location-switched") { + expect(move.location).toEqual({ directory: location.directory }) + expect(move.previous?.location).toEqual({ directory: location.directory }) + } + expect(yield* host.session.message.list({ ...input, limit: 201 }).pipe(Effect.flip)).toMatchObject({ + _tag: "SchemaError", + }) + expect(yield* host.session.message.list({ ...input, cursor: "invalid" }).pipe(Effect.flip)).toMatchObject({ + _tag: "InvalidCursorError", + }) + expect( + yield* host.session.message.list({ ...input, sessionID: Session.ID.create() }).pipe(Effect.flip), + ).toMatchObject({ _tag: "SessionNotFoundError" }) + yield* PluginPromise.fromPromise({ + id: "test.session-messages", + async setup(ctx) { + expect(first.cursor.next).toBeString() + const next = await ctx.session.message.list({ ...input, cursor: first.cursor.next }) + expect(next.data.map((m) => m.id)).toEqual([ids[0]]) + expect(next.cursor.previous).toBeString() + const previous = await ctx.session.message.list({ ...input, cursor: next.cursor.previous ?? undefined }) + expect(previous.data.map((m) => m.id)).toEqual([ids[2]]) + const end = await ctx.session.message.list({ ...input, cursor: next.cursor.next ?? undefined }) + expect(end).toEqual({ data: [], cursor: { previous: null, next: null } }) + await expect( + ctx.session.message.list({ ...input, order: "desc", cursor: first.cursor.next }), + ).rejects.toMatchObject({ _tag: "InvalidCursorError" }) + }, + }).effect(host) + }), +) diff --git a/packages/plugin/src/effect/session.ts b/packages/plugin/src/effect/session.ts index 129a921f1f6..dc2806e4b74 100644 --- a/packages/plugin/src/effect/session.ts +++ b/packages/plugin/src/effect/session.ts @@ -1,4 +1,4 @@ -import type { ExperimentalSessionApi, SessionApi } from "@opencode/client/effect/api" +import type { ExperimentalSessionApi, MessageApi, SessionApi } from "@opencode/client/effect/api" import type { GenerationOptionsFields, Message, SystemPart } from "@opencode/ai/effect" import type { Agent } from "@opencode/schema/agent" import type { Model } from "@opencode/schema/model" @@ -232,5 +232,6 @@ export type SessionDomain = Pick< | "context" > & Pick, "wait" | "instructions"> & { + readonly message: Pick, "list"> readonly hook: ModelHooks } diff --git a/packages/plugin/src/promise/adapter.ts b/packages/plugin/src/promise/adapter.ts index ba81e6ee224..4ea62e13a88 100644 --- a/packages/plugin/src/promise/adapter.ts +++ b/packages/plugin/src/promise/adapter.ts @@ -231,6 +231,7 @@ export function fromPromise(plugin: Plugin) { const GenerateEndpoints = ClientApi.groups["server.generate"].endpoints const IntegrationEndpoints = ClientApi.groups["server.integration"].endpoints const McpEndpoints = ClientApi.groups["server.mcp"].endpoints + const MessageEndpoints = ClientApi.groups["server.message"].endpoints const ModelEndpoints = ClientApi.groups["server.model"].endpoints const PluginEndpoints = ClientApi.groups["server.plugin"].endpoints const PermissionEndpoints = ClientApi.groups["server.permission"].endpoints @@ -647,6 +648,7 @@ export function fromPromise(plugin: Plugin) { move: adaptApiMethod(SessionEndpoints["session.move"], host.session.move), wait: adaptApiMethod(SessionEndpoints["session.wait"], host.session.wait), context: adaptApiMethod(SessionEndpoints["session.context"], host.session.context), + message: { list: adaptApiMethod(MessageEndpoints["session.messages"], host.session.message.list) }, instructions: { entry: { list: adaptApiMethod( diff --git a/packages/plugin/src/promise/session.ts b/packages/plugin/src/promise/session.ts index c1c0523b557..7655cc21966 100644 --- a/packages/plugin/src/promise/session.ts +++ b/packages/plugin/src/promise/session.ts @@ -1,4 +1,4 @@ -import type { ExperimentalSessionApi, SessionApi } from "@opencode/client/promise/api" +import type { ExperimentalSessionApi, MessageApi, SessionApi } from "@opencode/client/promise/api" import type { GenerationOptionsFields, Message, SystemPart } from "@opencode/ai/effect" import type { Agent } from "@opencode/schema/agent" import type { Model } from "@opencode/schema/model" @@ -232,5 +232,6 @@ export type SessionDomain = Pick< | "context" > & Pick & { + readonly message: Pick readonly hook: ModelHooks } diff --git a/packages/protocol/src/errors.ts b/packages/protocol/src/errors.ts index 5b9937c646f..bd0614c27de 100644 --- a/packages/protocol/src/errors.ts +++ b/packages/protocol/src/errors.ts @@ -2,6 +2,8 @@ import { Schema } from "effect" import { Skill } from "@opencode/schema/skill" import { Location } from "@opencode/schema/location" +export { InvalidCursorError, SessionNotFoundError, UnknownError } from "@opencode/schema/api-error" + export class LocationNotFoundError extends Schema.TaggedError()( "LocationNotFoundError", { location: Location.PublicRef, message: Schema.String }, @@ -71,15 +73,6 @@ export class ServiceUnavailableError extends Schema.TaggedError()( - "UnknownError", - { - message: Schema.String, - ref: Schema.optional(Schema.String), - }, - { httpApiStatus: 500 }, -) {} - export class ProviderNotFoundError extends Schema.TaggedError()( "ProviderNotFoundError", { @@ -153,15 +146,6 @@ export class AgentNotFoundError extends Schema.TaggedError() { httpApiStatus: 404 }, ) {} -export class SessionNotFoundError extends Schema.TaggedError()( - "SessionNotFoundError", - { - sessionID: Schema.String, - message: Schema.String, - }, - { httpApiStatus: 404 }, -) {} - export class MessageNotFoundError extends Schema.TaggedError()( "MessageNotFoundError", { @@ -208,12 +192,6 @@ export class CommandExecutionError extends Schema.TaggedError()( - "InvalidCursorError", - { message: Schema.String }, - { httpApiStatus: 400 }, -) {} - export class PermissionNotFoundError extends Schema.TaggedError()( "PermissionNotFoundError", { diff --git a/packages/protocol/src/groups/message.ts b/packages/protocol/src/groups/message.ts index a50080af095..f377e55ac94 100644 --- a/packages/protocol/src/groups/message.ts +++ b/packages/protocol/src/groups/message.ts @@ -1,55 +1,11 @@ import { Session } from "@opencode/schema/session" import { SessionMessage } from "@opencode/schema/session-message" -import { Location } from "@opencode/schema/location" -import { Schema, Struct } from "effect" +import { PublicLocationSwitched, SessionMessagesQuery } from "@opencode/schema/session-message-page" +import { Schema } from "effect" import { HttpApiEndpoint, HttpApiGroup, OpenApi } from "effect/http-api" import { InvalidCursorError, SessionNotFoundError, UnknownError } from "../errors.js" -// Keyed by message type so a new message type cannot be left out of the filter. -const MessageTypes = { - "agent-switched": true, - "model-switched": true, - "location-switched": true, - user: true, - synthetic: true, - system: true, - skill: true, - shell: true, - assistant: true, - compaction: true, - idle: true, -} satisfies Record - -export const SessionMessagesQuery = Schema.Struct({ - limit: Schema.optional( - Schema.NumberFromString.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(1), Schema.isLessThanOrEqualTo(200)), - ).annotate({ - description: "Maximum number of messages to return. When omitted, the endpoint returns its default page size.", - }), - order: Schema.optional(Schema.Union([Schema.Literal("asc"), Schema.Literal("desc")])).annotate({ - description: "Message order for the first page. Use desc for newest first or asc for oldest first.", - }), - cursor: Schema.optional( - Schema.String.annotate({ - description: - "Opaque pagination cursor returned as cursor.previous or cursor.next in the previous response. Do not combine with order.", - }), - ), - type: Schema.optional(Schema.Literals(Object.keys(MessageTypes) as ReadonlyArray)).annotate({ - description: - "Filter by message type before pagination. When omitted, all message types are returned. Pass the same type when following cursors.", - }), -}).annotate({ identifier: "SessionMessagesQuery" }) - -const PublicLocationSwitched = Schema.Struct({ - ...Struct.omit(SessionMessage.LocationSwitched.fields, ["location", "previous"]), - location: Location.PublicRef, - previous: Schema.Struct({ - location: Location.PublicRef, - projectID: SessionMessage.LocationSwitched.fields.projectID, - subpath: SessionMessage.LocationSwitched.fields.subpath, - }).pipe(Schema.optional), -}).annotate({ identifier: "Session.Message.LocationSwitched" }) +export { SessionMessagesQuery } export const PublicSessionMessage = Schema.Union([ SessionMessage.AgentSelected, diff --git a/packages/schema/src/api-error.ts b/packages/schema/src/api-error.ts new file mode 100644 index 00000000000..881eb186578 --- /dev/null +++ b/packages/schema/src/api-error.ts @@ -0,0 +1,19 @@ +import { Schema } from "effect" + +export class InvalidCursorError extends Schema.TaggedError()( + "InvalidCursorError", + { message: Schema.String }, + { httpApiStatus: 400 }, +) {} + +export class SessionNotFoundError extends Schema.TaggedError()( + "SessionNotFoundError", + { sessionID: Schema.String, message: Schema.String }, + { httpApiStatus: 404 }, +) {} + +export class UnknownError extends Schema.TaggedError()( + "UnknownError", + { message: Schema.String, ref: Schema.optional(Schema.String) }, + { httpApiStatus: 500 }, +) {} diff --git a/packages/schema/src/session-message-page.ts b/packages/schema/src/session-message-page.ts new file mode 100644 index 00000000000..eec1eddf5b5 --- /dev/null +++ b/packages/schema/src/session-message-page.ts @@ -0,0 +1,51 @@ +import { SessionMessage } from "./session-message.js" +import { Location } from "./location.js" +import { Schema, Struct } from "effect" + +// Keyed by message type so a new message type cannot be left out of the filter. +const MessageTypes = { + "agent-switched": true, + "model-switched": true, + "location-switched": true, + user: true, + synthetic: true, + system: true, + skill: true, + shell: true, + assistant: true, + compaction: true, + idle: true, +} satisfies Record + +export const SessionMessagesQuery = Schema.Struct({ + limit: Schema.optional( + Schema.NumberFromString.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(1), Schema.isLessThanOrEqualTo(200)), + ).annotate({ + description: "Maximum number of messages to return. When omitted, the endpoint returns its default page size.", + }), + order: Schema.optional(Schema.Union([Schema.Literal("asc"), Schema.Literal("desc")])).annotate({ + description: "Message order for the first page. Use desc for newest first or asc for oldest first.", + }), + cursor: Schema.optional( + Schema.String.annotate({ + description: + "Opaque pagination cursor returned as cursor.previous or cursor.next in the previous response. Do not combine with order.", + }), + ), + type: Schema.optional(Schema.Literals(Object.keys(MessageTypes) as ReadonlyArray)).annotate({ + description: + "Filter by message type before pagination. When omitted, all message types are returned. Pass the same type when following cursors.", + }), +}).annotate({ identifier: "SessionMessagesQuery" }) + +export interface SessionMessagesQuery extends Schema.Schema.Type {} + +export const PublicLocationSwitched = Schema.Struct({ + ...Struct.omit(SessionMessage.LocationSwitched.fields, ["location", "previous"]), + location: Location.PublicRef, + previous: Schema.Struct({ + location: Location.PublicRef, + projectID: SessionMessage.LocationSwitched.fields.projectID, + subpath: SessionMessage.LocationSwitched.fields.subpath, + }).pipe(Schema.optional), +}).annotate({ identifier: "Session.Message.LocationSwitched" }) diff --git a/packages/server/src/handlers/message.ts b/packages/server/src/handlers/message.ts index 5956a8f1512..f69e47e4cfb 100644 --- a/packages/server/src/handlers/message.ts +++ b/packages/server/src/handlers/message.ts @@ -1,81 +1,24 @@ -import { SessionMessage } from "@opencode/core/session/message" +import { MessagePage } from "@opencode/core/session/message-page" import { Session } from "@opencode/core/session" -import { Effect, Option, Schema } from "effect" +import { SessionMediaMessagesResponse } from "@opencode/protocol/groups/message" +import { Effect } from "effect" import { HttpServerResponse } from "effect/http" import { HttpApiBuilder } from "effect/http-api" import { Api } from "../api" import { wantsMediaRefs } from "../media-uri" -import { InvalidCursorError } from "@opencode/protocol/errors" -import { SessionMediaMessagesResponse } from "@opencode/protocol/groups/message" -import { failedMessageDecode, missingSession } from "./session-error" - -const DefaultMessagesLimit = 50 - -const Cursor = Schema.Struct({ - id: SessionMessage.ID, - order: Schema.Union([Schema.Literal("asc"), Schema.Literal("desc")]), - direction: Schema.Union([Schema.Literal("previous"), Schema.Literal("next")]), -}) - -const decodeCursor = Schema.decodeUnknownOption(Schema.fromJsonString(Cursor)) - -const cursor = { - encode(message: { readonly id: SessionMessage.ID }, order: "asc" | "desc", direction: "previous" | "next") { - return Buffer.from(JSON.stringify({ id: message.id, order, direction })).toString("base64url") - }, - decode(input: string) { - return decodeCursor(Buffer.from(input, "base64url").toString("utf8")) - }, -} export const MessageHandler = HttpApiBuilder.group(Api, "server.message", (handlers) => Effect.gen(function* () { const session = yield* Session.Service - return handlers.handle( "session.messages", Effect.fn(function* (ctx) { - if (ctx.query.cursor && ctx.query.order !== undefined) - return yield* new InvalidCursorError({ message: "Cursor cannot be combined with order" }) - const decoded = ctx.query.cursor - ? (Option.getOrUndefined(cursor.decode(ctx.query.cursor)) ?? - (yield* new InvalidCursorError({ message: "Invalid cursor" }))) - : undefined - const order = decoded?.order ?? ctx.query.order ?? "desc" - const input = { - sessionID: ctx.params.sessionID, - limit: ctx.query.limit ?? DefaultMessagesLimit, - order, - type: ctx.query.type, - cursor: decoded ? { id: decoded.id, direction: decoded.direction } : undefined, - } - const page = (messages: ReadonlyArray) => { - const first = messages[0] - const last = messages.at(-1) - return { - data: messages, - cursor: { - previous: first ? cursor.encode(first, order, "previous") : undefined, - next: last ? cursor.encode(last, order, "next") : undefined, - }, - } - } + const input = { ...ctx.params, ...ctx.query } if (wantsMediaRefs(ctx.request)) { - const messages = yield* session - .messagesWithRefs(input) - .pipe( - Effect.catchTag("Session.NotFoundError", missingSession), - Effect.catchTag("Session.MessageDecodeError", failedMessageDecode), - ) - return yield* HttpServerResponse.schemaJson(SessionMediaMessagesResponse)(page(messages)).pipe(Effect.orDie) + const page = yield* MessagePage.list(session.messagesWithRefs, input) + return yield* HttpServerResponse.schemaJson(SessionMediaMessagesResponse)(page).pipe(Effect.orDie) } - const messages = yield* session - .messages(input) - .pipe( - Effect.catchTag("Session.NotFoundError", missingSession), - Effect.catchTag("Session.MessageDecodeError", failedMessageDecode), - ) - return page(messages) + return yield* MessagePage.list(session.messages, input) }), ) }), diff --git a/packages/server/src/handlers/session-error.ts b/packages/server/src/handlers/session-error.ts index 6a4ab921dca..2aca7a313d5 100644 --- a/packages/server/src/handlers/session-error.ts +++ b/packages/server/src/handlers/session-error.ts @@ -1,14 +1,9 @@ import { Session } from "@opencode/core/session" import type { Snapshot } from "@opencode/core/snapshot" -import { MessageNotFoundError, SessionNotFoundError, UnknownError } from "@opencode/protocol/errors" +import { MessageNotFoundError, UnknownError } from "@opencode/protocol/errors" import { Effect } from "effect" -export function missingSession(error: Session.NotFoundError) { - return new SessionNotFoundError({ - sessionID: error.sessionID, - message: `Session not found: ${error.sessionID}`, - }) -} +export { failedMessageDecode, missingSession } from "@opencode/core/session/message-page" export function missingMessage(error: Session.MessageNotFoundError) { return new MessageNotFoundError({ @@ -18,16 +13,6 @@ export function missingMessage(error: Session.MessageNotFoundError) { }) } -export function failedMessageDecode(error: Session.MessageDecodeError) { - const ref = `err_${crypto.randomUUID().slice(0, 8)}` - return Effect.logError("failed to decode session message").pipe( - Effect.annotateLogs({ ref, sessionID: error.sessionID, messageID: error.messageID }), - Effect.andThen( - Effect.fail(new UnknownError({ message: "Unexpected server error. Check server logs for details.", ref })), - ), - ) -} - /** Snapshot repositories are host state clients cannot repair, so surface only a log reference. */ export function failedSnapshot(operation: string, sessionID: Session.ID) { return (error: Snapshot.Error) => { diff --git a/services/site/src/docs/content/build/plugins/effect.mdx b/services/site/src/docs/content/build/plugins/effect.mdx index efa318a7215..3f546fc9d74 100644 --- a/services/site/src/docs/content/build/plugins/effect.mdx +++ b/services/site/src/docs/content/build/plugins/effect.mdx @@ -840,6 +840,13 @@ effect: (ctx) => }), ``` +Read projected messages newest first, or pass `order: "asc"` for oldest first. When following `cursor.next` or `cursor.previous`, omit `order` and repeat any `type` filter. + +```ts +const input = { sessionID, type: "user", limit: 20 } as const +const page = yield* ctx.session.message.list(input) +``` + Remove a temporary session with `remove`. Removal stops active execution and recursively deletes child sessions. ```ts @@ -897,10 +904,11 @@ type SessionDomain = Pick< | "interrupt" | "update" | "move" - | "wait" | "context" - | "instructions" -> +> & Pick, "wait" | "instructions"> & { + readonly message: Pick, "list"> + readonly hook: ModelHooks +} ``` ### Skills diff --git a/services/site/src/docs/content/build/plugins/server.mdx b/services/site/src/docs/content/build/plugins/server.mdx index a980b878fc6..b4998f4e7c3 100644 --- a/services/site/src/docs/content/build/plugins/server.mdx +++ b/services/site/src/docs/content/build/plugins/server.mdx @@ -778,6 +778,14 @@ const session = await ctx.session.get({ sessionID }) const messages = await ctx.session.context({ sessionID }) ``` +Read the projected transcript with `ctx.session.message.list`. Pages default to the newest 50 messages. Set `order` only on the first page and repeat the `type` filter when following `cursor.next` or `cursor.previous`. An empty page ends the traversal. + +```ts +const input = { sessionID, type: "user", limit: 20 } as const +const page = await ctx.session.message.list({ ...input, order: "asc" }) +const next = page.cursor.next ? await ctx.session.message.list({ ...input, cursor: page.cursor.next }) : undefined +``` + List sessions a page at a time. To get the next page, pass `cursor.next` back as `cursor`. The cursor remembers your filters, so you don't need to repeat them.