session.ts 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. import { SessionMessage } from "@opencode-ai/core/session/message"
  2. import { SessionInput } from "@opencode-ai/core/session/input"
  3. import { Prompt } from "@opencode-ai/core/session/prompt"
  4. import { SessionV2 } from "@opencode-ai/core/session"
  5. import { ProjectV2 } from "@opencode-ai/core/project"
  6. import { AbsolutePath, PositiveInt, RelativePath, withStatics } from "@opencode-ai/core/schema"
  7. import { WorkspaceV2 } from "@opencode-ai/core/workspace"
  8. import { Schema, Struct } from "effect"
  9. import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema, OpenApi } from "effect/unstable/httpapi"
  10. import {
  11. ConflictError,
  12. InvalidCursorError,
  13. InvalidRequestError,
  14. ServiceUnavailableError,
  15. SessionNotFoundError,
  16. UnknownError,
  17. } from "../../errors"
  18. import { V2Authorization } from "../../middleware/authorization"
  19. const SessionsQueryFields = {
  20. workspace: WorkspaceV2.ID.pipe(Schema.optional),
  21. limit: Schema.NumberFromString.pipe(Schema.decodeTo(PositiveInt), Schema.optional).annotate({
  22. description: "Maximum number of sessions to return. Defaults to the newest 50 sessions.",
  23. }),
  24. order: Schema.optional(Schema.Union([Schema.Literal("asc"), Schema.Literal("desc")])).annotate({
  25. description: "Session order for the first page. Use desc for newest first or asc for oldest first.",
  26. }),
  27. search: Schema.optional(Schema.String),
  28. }
  29. const SessionsDirectoryQuery = Schema.Struct({
  30. ...SessionsQueryFields,
  31. directory: AbsolutePath,
  32. })
  33. const SessionsProjectQuery = Schema.Struct({
  34. ...SessionsQueryFields,
  35. project: ProjectV2.ID,
  36. subpath: RelativePath.pipe(Schema.optional),
  37. })
  38. const SessionsAllQuery = Schema.Struct(SessionsQueryFields)
  39. const withCursor = <Fields extends Schema.Struct.Fields>(schema: Schema.Struct<Fields>) =>
  40. schema.mapFields((fields) => ({
  41. ...Struct.omit(fields, ["limit"]),
  42. anchor: SessionV2.ListAnchor,
  43. }))
  44. const SessionsCursorInput = Schema.Union([
  45. withCursor(SessionsDirectoryQuery),
  46. withCursor(SessionsProjectQuery),
  47. withCursor(SessionsAllQuery),
  48. ])
  49. const SessionsCursorJson = Schema.fromJsonString(SessionsCursorInput)
  50. const encodeSessionsCursor = Schema.encodeSync(SessionsCursorJson)
  51. const decodeSessionsCursor = Schema.decodeUnknownEffect(SessionsCursorJson)
  52. export const SessionsCursor = Schema.String.pipe(
  53. Schema.brand("V2SessionsCursor"),
  54. withStatics((schema) => {
  55. const make = schema.make
  56. return {
  57. make: (input: typeof SessionsCursorInput.Type) =>
  58. make(Buffer.from(encodeSessionsCursor(input)).toString("base64url")),
  59. parse: (input: string) => decodeSessionsCursor(Buffer.from(input, "base64url").toString("utf8")),
  60. }
  61. }),
  62. )
  63. export type SessionsCursor = typeof SessionsCursor.Type
  64. const SessionsCursorQuery = Schema.Struct({
  65. cursor: SessionsCursor.annotate({
  66. description: "Opaque pagination cursor returned as cursor.previous or cursor.next in the previous response.",
  67. }),
  68. limit: SessionsQueryFields.limit,
  69. })
  70. export const SessionsQuery = Schema.Struct({
  71. ...SessionsQueryFields,
  72. directory: AbsolutePath.pipe(Schema.optional),
  73. project: ProjectV2.ID.pipe(Schema.optional),
  74. subpath: RelativePath.pipe(Schema.optional),
  75. cursor: SessionsCursorQuery.fields.cursor.pipe(Schema.optional),
  76. }).annotate({ identifier: "V2SessionsQuery" })
  77. export const SessionGroup = HttpApiGroup.make("v2.session")
  78. .add(
  79. HttpApiEndpoint.get("sessions", "/api/session", {
  80. query: SessionsQuery,
  81. success: Schema.Struct({
  82. data: Schema.Array(SessionV2.Info),
  83. cursor: Schema.Struct({
  84. previous: SessionsCursor.pipe(Schema.optional),
  85. next: SessionsCursor.pipe(Schema.optional),
  86. }),
  87. }).annotate({ identifier: "V2SessionsResponse" }),
  88. error: [InvalidCursorError, InvalidRequestError],
  89. }).annotateMerge(
  90. OpenApi.annotations({
  91. identifier: "v2.session.list",
  92. summary: "List v2 sessions",
  93. description:
  94. "Retrieve sessions in the requested order. Items keep that order across pages; use cursor.next or cursor.previous to move through the ordered list.",
  95. }),
  96. ),
  97. )
  98. .add(
  99. HttpApiEndpoint.post("prompt", "/api/session/:sessionID/prompt", {
  100. params: { sessionID: SessionV2.ID },
  101. payload: Schema.Struct({
  102. id: SessionMessage.ID.pipe(Schema.optional),
  103. prompt: Prompt,
  104. delivery: SessionInput.Delivery.pipe(Schema.optional),
  105. resume: Schema.Boolean.pipe(Schema.optional),
  106. }),
  107. success: Schema.Struct({ data: SessionInput.Admitted }),
  108. error: [ConflictError, SessionNotFoundError],
  109. }).annotateMerge(
  110. OpenApi.annotations({
  111. identifier: "v2.session.prompt",
  112. summary: "Send v2 message",
  113. description: "Durably admit one v2 session input and schedule agent-loop execution unless resume is false.",
  114. }),
  115. ),
  116. )
  117. .add(
  118. HttpApiEndpoint.post("compact", "/api/session/:sessionID/compact", {
  119. params: { sessionID: SessionV2.ID },
  120. success: HttpApiSchema.NoContent,
  121. error: [SessionNotFoundError, ServiceUnavailableError],
  122. }).annotateMerge(
  123. OpenApi.annotations({
  124. identifier: "v2.session.compact",
  125. summary: "Compact v2 session",
  126. description: "Compact a v2 session conversation.",
  127. }),
  128. ),
  129. )
  130. .add(
  131. HttpApiEndpoint.post("wait", "/api/session/:sessionID/wait", {
  132. params: { sessionID: SessionV2.ID },
  133. success: HttpApiSchema.NoContent,
  134. error: [SessionNotFoundError, ServiceUnavailableError],
  135. }).annotateMerge(
  136. OpenApi.annotations({
  137. identifier: "v2.session.wait",
  138. summary: "Wait for v2 session",
  139. description: "Wait for a v2 session agent loop to become idle.",
  140. }),
  141. ),
  142. )
  143. .add(
  144. HttpApiEndpoint.get("context", "/api/session/:sessionID/context", {
  145. params: { sessionID: SessionV2.ID },
  146. success: Schema.Struct({ data: Schema.Array(SessionMessage.Message) }),
  147. error: [SessionNotFoundError, UnknownError],
  148. }).annotateMerge(
  149. OpenApi.annotations({
  150. identifier: "v2.session.context",
  151. summary: "Get v2 session context",
  152. description: "Retrieve the active context messages for a v2 session (all messages after the last compaction).",
  153. }),
  154. ),
  155. )
  156. .annotateMerge(
  157. OpenApi.annotations({
  158. title: "v2",
  159. description: "Experimental v2 routes.",
  160. }),
  161. )
  162. .middleware(V2Authorization)