| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345 |
- import { SessionMessage } from "@opencode-ai/schema/session-message"
- import { SessionInput } from "@opencode-ai/schema/session-input"
- import { Prompt } from "@opencode-ai/schema/prompt"
- import { Session } from "@opencode-ai/schema/session"
- import { Project } from "@opencode-ai/schema/project"
- import { AbsolutePath, NonNegativeInt, PositiveInt, RelativePath, statics } from "@opencode-ai/schema/schema"
- import { Workspace } from "@opencode-ai/schema/workspace"
- import { Context, Encoding, Result, Schema, Struct } from "effect"
- import { HttpApiEndpoint, HttpApiGroup, HttpApiMiddleware, HttpApiSchema, OpenApi } from "effect/unstable/httpapi"
- import {
- ConflictError,
- InvalidCursorError,
- InvalidRequestError,
- MessageNotFoundError,
- ServiceUnavailableError,
- SessionNotFoundError,
- UnknownError,
- } from "../errors"
- import { Agent } from "@opencode-ai/schema/agent"
- import { Model } from "@opencode-ai/schema/model"
- import { Location } from "@opencode-ai/schema/location"
- import { Revert } from "@opencode-ai/schema/revert"
- import { SessionEvent } from "@opencode-ai/schema/session-event"
- const SessionsQueryFields = {
- workspace: Workspace.ID.pipe(Schema.optional),
- limit: Schema.NumberFromString.pipe(Schema.decodeTo(PositiveInt), Schema.optional).annotate({
- description: "Maximum number of sessions to return. Defaults to the newest 50 sessions.",
- }),
- order: Schema.optional(Schema.Union([Schema.Literal("asc"), Schema.Literal("desc")])).annotate({
- description: "Session order for the first page. Use desc for newest first or asc for oldest first.",
- }),
- search: Schema.optional(Schema.String),
- }
- const SessionsDirectoryQuery = Schema.Struct({
- ...SessionsQueryFields,
- directory: AbsolutePath,
- })
- const SessionsProjectQuery = Schema.Struct({
- ...SessionsQueryFields,
- project: Project.ID,
- subpath: RelativePath.pipe(Schema.optional),
- })
- const SessionsAllQuery = Schema.Struct(SessionsQueryFields)
- const withCursor = <Fields extends Schema.Struct.Fields>(schema: Schema.Struct<Fields>) =>
- schema.mapFields((fields) => ({
- ...Struct.omit(fields, ["limit"]),
- anchor: Session.ListAnchor,
- }))
- const SessionsCursorInput = Schema.Union([
- withCursor(SessionsDirectoryQuery),
- withCursor(SessionsProjectQuery),
- withCursor(SessionsAllQuery),
- ])
- const SessionsCursorJson = Schema.fromJsonString(SessionsCursorInput)
- const encodeSessionsCursor = Schema.encodeSync(SessionsCursorJson)
- const decodeSessionsCursor = Schema.decodeUnknownEffect(SessionsCursorJson)
- export const SessionsCursor = Schema.String.pipe(
- Schema.brand("SessionsCursor"),
- statics((schema) => {
- const make = schema.make.bind(schema)
- return {
- make: (input: typeof SessionsCursorInput.Type) => make(Encoding.encodeBase64Url(encodeSessionsCursor(input))),
- parse: (input: string) => decodeSessionsCursor(Result.getOrThrow(Encoding.decodeBase64UrlString(input))),
- }
- }),
- )
- export type SessionsCursor = typeof SessionsCursor.Type
- const SessionActive = Schema.Struct({
- type: Schema.Literal("running"),
- }).annotate({ identifier: "SessionActive" })
- const SessionsQueryCursor = SessionsCursor.annotate({
- description: "Opaque pagination cursor returned as cursor.previous or cursor.next in the previous response.",
- })
- export const SessionsQuery = Schema.Struct({
- ...SessionsQueryFields,
- directory: AbsolutePath.pipe(Schema.optional),
- project: Project.ID.pipe(Schema.optional),
- subpath: RelativePath.pipe(Schema.optional),
- cursor: SessionsQueryCursor.pipe(Schema.optional),
- }).annotate({ identifier: "SessionsQuery" })
- export const makeSessionGroup = <I extends HttpApiMiddleware.AnyId, S>(sessionLocationMiddleware: Context.Key<I, S>) =>
- HttpApiGroup.make("server.session")
- .add(
- HttpApiEndpoint.get("session.list", "/api/session", {
- query: SessionsQuery,
- success: Schema.Struct({
- data: Schema.Array(Session.Info),
- cursor: Schema.Struct({
- previous: SessionsCursor.pipe(Schema.optional),
- next: SessionsCursor.pipe(Schema.optional),
- }),
- }).annotate({ identifier: "SessionsResponse" }),
- error: [InvalidCursorError, InvalidRequestError],
- }).annotateMerge(
- OpenApi.annotations({
- identifier: "v2.session.list",
- summary: "List sessions",
- description:
- "Retrieve sessions in the requested order. Items keep that order across pages; use cursor.next or cursor.previous to move through the ordered list.",
- }),
- ),
- )
- .add(
- HttpApiEndpoint.post("session.create", "/api/session", {
- payload: Schema.Struct({
- id: Session.ID.pipe(Schema.optional),
- agent: Agent.ID.pipe(Schema.optional),
- model: Model.Ref.pipe(Schema.optional),
- location: Location.Ref.pipe(Schema.optional),
- }),
- success: Schema.Struct({ data: Session.Info }),
- }).annotateMerge(
- OpenApi.annotations({
- identifier: "v2.session.create",
- summary: "Create session",
- description: "Create a session at the requested location.",
- }),
- ),
- )
- .add(
- HttpApiEndpoint.get("session.active", "/api/session/active", {
- success: Schema.Struct({ data: Schema.Record(Session.ID, SessionActive) }),
- }).annotateMerge(
- OpenApi.annotations({
- identifier: "v2.session.active",
- summary: "List active sessions",
- description:
- "Retrieve foreground Session drains currently owned by this OpenCode process. Sessions absent from the result are inactive.",
- }),
- ),
- )
- .add(
- HttpApiEndpoint.get("session.get", "/api/session/:sessionID", {
- params: { sessionID: Session.ID },
- success: Schema.Struct({ data: Session.Info }),
- error: SessionNotFoundError,
- })
- .middleware(sessionLocationMiddleware)
- .annotateMerge(
- OpenApi.annotations({
- identifier: "v2.session.get",
- summary: "Get session",
- description: "Retrieve a session by ID.",
- }),
- ),
- )
- .add(
- HttpApiEndpoint.post("session.switchAgent", "/api/session/:sessionID/agent", {
- params: { sessionID: Session.ID },
- payload: Schema.Struct({ agent: Agent.ID }),
- success: HttpApiSchema.NoContent,
- error: SessionNotFoundError,
- })
- .middleware(sessionLocationMiddleware)
- .annotateMerge(
- OpenApi.annotations({
- identifier: "v2.session.switchAgent",
- summary: "Switch session agent",
- description: "Switch the agent used by subsequent provider turns.",
- }),
- ),
- )
- .add(
- HttpApiEndpoint.post("session.switchModel", "/api/session/:sessionID/model", {
- params: { sessionID: Session.ID },
- payload: Schema.Struct({ model: Model.Ref }),
- success: HttpApiSchema.NoContent,
- error: SessionNotFoundError,
- })
- .middleware(sessionLocationMiddleware)
- .annotateMerge(
- OpenApi.annotations({
- identifier: "v2.session.switchModel",
- summary: "Switch session model",
- description: "Switch the model used by subsequent provider turns.",
- }),
- ),
- )
- .add(
- HttpApiEndpoint.post("session.prompt", "/api/session/:sessionID/prompt", {
- params: { sessionID: Session.ID },
- payload: Schema.Struct({
- id: SessionMessage.ID.pipe(Schema.optional),
- prompt: Prompt,
- delivery: SessionInput.Delivery.pipe(Schema.optional),
- resume: Schema.Boolean.pipe(Schema.optional),
- }),
- success: Schema.Struct({ data: SessionInput.Admitted }),
- error: [ConflictError, SessionNotFoundError],
- })
- .middleware(sessionLocationMiddleware)
- .annotateMerge(
- OpenApi.annotations({
- identifier: "v2.session.prompt",
- summary: "Send message",
- description: "Durably admit one session input and schedule agent-loop execution unless resume is false.",
- }),
- ),
- )
- .add(
- HttpApiEndpoint.post("session.compact", "/api/session/:sessionID/compact", {
- params: { sessionID: Session.ID },
- success: HttpApiSchema.NoContent,
- error: [SessionNotFoundError, ServiceUnavailableError],
- })
- .middleware(sessionLocationMiddleware)
- .annotateMerge(
- OpenApi.annotations({
- identifier: "v2.session.compact",
- summary: "Compact session",
- description: "Compact a session conversation.",
- }),
- ),
- )
- .add(
- HttpApiEndpoint.post("session.wait", "/api/session/:sessionID/wait", {
- params: { sessionID: Session.ID },
- success: HttpApiSchema.NoContent,
- error: [SessionNotFoundError, ServiceUnavailableError],
- })
- .middleware(sessionLocationMiddleware)
- .annotateMerge(
- OpenApi.annotations({
- identifier: "v2.session.wait",
- summary: "Wait for session",
- description: "Wait for a session agent loop to become idle.",
- }),
- ),
- )
- .add(
- HttpApiEndpoint.post("session.revert.stage", "/api/session/:sessionID/revert/stage", {
- params: { sessionID: Session.ID },
- payload: Schema.Struct({ messageID: SessionMessage.ID, files: Schema.Boolean.pipe(Schema.optional) }),
- success: Schema.Struct({ data: Revert.State }),
- error: [MessageNotFoundError, SessionNotFoundError, UnknownError],
- })
- .middleware(sessionLocationMiddleware)
- .annotateMerge(
- OpenApi.annotations({
- identifier: "v2.session.revert.stage",
- summary: "Stage session revert",
- description: "Stage or move a reversible session boundary and optionally apply its file changes.",
- }),
- ),
- )
- .add(
- HttpApiEndpoint.post("session.revert.clear", "/api/session/:sessionID/revert/clear", {
- params: { sessionID: Session.ID },
- success: HttpApiSchema.NoContent,
- error: [SessionNotFoundError, UnknownError],
- })
- .middleware(sessionLocationMiddleware)
- .annotateMerge(OpenApi.annotations({ identifier: "v2.session.revert.clear", summary: "Clear staged revert" })),
- )
- .add(
- HttpApiEndpoint.post("session.revert.commit", "/api/session/:sessionID/revert/commit", {
- params: { sessionID: Session.ID },
- success: HttpApiSchema.NoContent,
- error: SessionNotFoundError,
- })
- .middleware(sessionLocationMiddleware)
- .annotateMerge(
- OpenApi.annotations({ identifier: "v2.session.revert.commit", summary: "Commit staged revert" }),
- ),
- )
- .add(
- HttpApiEndpoint.get("session.context", "/api/session/:sessionID/context", {
- params: { sessionID: Session.ID },
- success: Schema.Struct({ data: Schema.Array(SessionMessage.Message) }),
- error: [SessionNotFoundError, UnknownError],
- })
- .middleware(sessionLocationMiddleware)
- .annotateMerge(
- OpenApi.annotations({
- identifier: "v2.session.context",
- summary: "Get session context",
- description: "Retrieve the active context messages for a session (all messages after the last compaction).",
- }),
- ),
- )
- .add(
- HttpApiEndpoint.get("session.events", "/api/session/:sessionID/event", {
- params: { sessionID: Session.ID },
- query: {
- after: Schema.NumberFromString.pipe(Schema.decodeTo(NonNegativeInt), Schema.optional),
- },
- success: HttpApiSchema.StreamSse({ data: SessionEvent.Durable }),
- error: SessionNotFoundError,
- })
- .middleware(sessionLocationMiddleware)
- .annotateMerge(
- OpenApi.annotations({
- identifier: "v2.session.events",
- summary: "Subscribe to session events",
- description: "Replay durable events after an aggregate sequence, then continue with new durable events.",
- }),
- ),
- )
- .add(
- HttpApiEndpoint.post("session.interrupt", "/api/session/:sessionID/interrupt", {
- params: { sessionID: Session.ID },
- success: HttpApiSchema.NoContent,
- error: SessionNotFoundError,
- })
- .middleware(sessionLocationMiddleware)
- .annotateMerge(
- OpenApi.annotations({
- identifier: "v2.session.interrupt",
- summary: "Interrupt session execution",
- description: "Interrupt active execution owned by this OpenCode process. Idle interruption is a no-op.",
- }),
- ),
- )
- .add(
- HttpApiEndpoint.get("session.message", "/api/session/:sessionID/message/:messageID", {
- params: { sessionID: Session.ID, messageID: SessionMessage.ID },
- success: Schema.Struct({ data: SessionMessage.Message }),
- error: [SessionNotFoundError, MessageNotFoundError],
- })
- .middleware(sessionLocationMiddleware)
- .annotateMerge(
- OpenApi.annotations({
- identifier: "v2.session.message",
- summary: "Get session message",
- description: "Retrieve one projected message owned by the Session.",
- }),
- ),
- )
- .annotateMerge(
- OpenApi.annotations({
- title: "sessions",
- description: "Experimental session routes.",
- }),
- )
|