session.ts 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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 { SessionLocationMiddleware } from "../middleware/session-location"
  19. import { AgentV2 } from "@opencode-ai/core/agent"
  20. import { ModelV2 } from "@opencode-ai/core/model"
  21. import { Location } from "@opencode-ai/core/location"
  22. const SessionsQueryFields = {
  23. workspace: WorkspaceV2.ID.pipe(Schema.optional),
  24. limit: Schema.NumberFromString.pipe(Schema.decodeTo(PositiveInt), Schema.optional).annotate({
  25. description: "Maximum number of sessions to return. Defaults to the newest 50 sessions.",
  26. }),
  27. order: Schema.optional(Schema.Union([Schema.Literal("asc"), Schema.Literal("desc")])).annotate({
  28. description: "Session order for the first page. Use desc for newest first or asc for oldest first.",
  29. }),
  30. search: Schema.optional(Schema.String),
  31. }
  32. const SessionsDirectoryQuery = Schema.Struct({
  33. ...SessionsQueryFields,
  34. directory: AbsolutePath,
  35. })
  36. const SessionsProjectQuery = Schema.Struct({
  37. ...SessionsQueryFields,
  38. project: ProjectV2.ID,
  39. subpath: RelativePath.pipe(Schema.optional),
  40. })
  41. const SessionsAllQuery = Schema.Struct(SessionsQueryFields)
  42. const withCursor = <Fields extends Schema.Struct.Fields>(schema: Schema.Struct<Fields>) =>
  43. schema.mapFields((fields) => ({
  44. ...Struct.omit(fields, ["limit"]),
  45. anchor: SessionV2.ListAnchor,
  46. }))
  47. const SessionsCursorInput = Schema.Union([
  48. withCursor(SessionsDirectoryQuery),
  49. withCursor(SessionsProjectQuery),
  50. withCursor(SessionsAllQuery),
  51. ])
  52. const SessionsCursorJson = Schema.fromJsonString(SessionsCursorInput)
  53. const encodeSessionsCursor = Schema.encodeSync(SessionsCursorJson)
  54. const decodeSessionsCursor = Schema.decodeUnknownEffect(SessionsCursorJson)
  55. export const SessionsCursor = Schema.String.pipe(
  56. Schema.brand("SessionsCursor"),
  57. withStatics((schema) => {
  58. const make = schema.make
  59. return {
  60. make: (input: typeof SessionsCursorInput.Type) =>
  61. make(Buffer.from(encodeSessionsCursor(input)).toString("base64url")),
  62. parse: (input: string) => decodeSessionsCursor(Buffer.from(input, "base64url").toString("utf8")),
  63. }
  64. }),
  65. )
  66. export type SessionsCursor = typeof SessionsCursor.Type
  67. const SessionsCursorQuery = Schema.Struct({
  68. cursor: SessionsCursor.annotate({
  69. description: "Opaque pagination cursor returned as cursor.previous or cursor.next in the previous response.",
  70. }),
  71. limit: SessionsQueryFields.limit,
  72. })
  73. export const SessionsQuery = Schema.Struct({
  74. ...SessionsQueryFields,
  75. directory: AbsolutePath.pipe(Schema.optional),
  76. project: ProjectV2.ID.pipe(Schema.optional),
  77. subpath: RelativePath.pipe(Schema.optional),
  78. cursor: SessionsCursorQuery.fields.cursor.pipe(Schema.optional),
  79. }).annotate({ identifier: "SessionsQuery" })
  80. export const SessionGroup = HttpApiGroup.make("server.session")
  81. .add(
  82. HttpApiEndpoint.get("session.list", "/api/session", {
  83. query: SessionsQuery,
  84. success: Schema.Struct({
  85. data: Schema.Array(SessionV2.Info),
  86. cursor: Schema.Struct({
  87. previous: SessionsCursor.pipe(Schema.optional),
  88. next: SessionsCursor.pipe(Schema.optional),
  89. }),
  90. }).annotate({ identifier: "SessionsResponse" }),
  91. error: [InvalidCursorError, InvalidRequestError],
  92. }).annotateMerge(
  93. OpenApi.annotations({
  94. identifier: "v2.session.list",
  95. summary: "List sessions",
  96. description:
  97. "Retrieve sessions in the requested order. Items keep that order across pages; use cursor.next or cursor.previous to move through the ordered list.",
  98. }),
  99. ),
  100. )
  101. .add(
  102. HttpApiEndpoint.post("session.create", "/api/session", {
  103. payload: Schema.Struct({
  104. id: SessionV2.ID.pipe(Schema.optional),
  105. agent: AgentV2.ID.pipe(Schema.optional),
  106. model: ModelV2.Ref.pipe(Schema.optional),
  107. location: Location.Ref.pipe(Schema.optional),
  108. }),
  109. success: Schema.Struct({ data: SessionV2.Info }),
  110. }).annotateMerge(
  111. OpenApi.annotations({
  112. identifier: "v2.session.create",
  113. summary: "Create session",
  114. description: "Create a session at the requested location.",
  115. }),
  116. ),
  117. )
  118. .add(
  119. HttpApiEndpoint.get("session.get", "/api/session/:sessionID", {
  120. params: { sessionID: SessionV2.ID },
  121. success: Schema.Struct({ data: SessionV2.Info }),
  122. error: SessionNotFoundError,
  123. })
  124. .middleware(SessionLocationMiddleware)
  125. .annotateMerge(
  126. OpenApi.annotations({
  127. identifier: "v2.session.get",
  128. summary: "Get session",
  129. description: "Retrieve a session by ID.",
  130. }),
  131. ),
  132. )
  133. .add(
  134. HttpApiEndpoint.post("session.switchAgent", "/api/session/:sessionID/agent", {
  135. params: { sessionID: SessionV2.ID },
  136. payload: Schema.Struct({ agent: AgentV2.ID }),
  137. success: HttpApiSchema.NoContent,
  138. error: SessionNotFoundError,
  139. })
  140. .middleware(SessionLocationMiddleware)
  141. .annotateMerge(
  142. OpenApi.annotations({
  143. identifier: "v2.session.switchAgent",
  144. summary: "Switch session agent",
  145. description: "Switch the agent used by subsequent session activity.",
  146. }),
  147. ),
  148. )
  149. .add(
  150. HttpApiEndpoint.post("session.switchModel", "/api/session/:sessionID/model", {
  151. params: { sessionID: SessionV2.ID },
  152. payload: Schema.Struct({ model: ModelV2.Ref }),
  153. success: HttpApiSchema.NoContent,
  154. error: SessionNotFoundError,
  155. })
  156. .middleware(SessionLocationMiddleware)
  157. .annotateMerge(
  158. OpenApi.annotations({
  159. identifier: "v2.session.switchModel",
  160. summary: "Switch session model",
  161. description: "Switch the model used by subsequent session activity.",
  162. }),
  163. ),
  164. )
  165. .add(
  166. HttpApiEndpoint.post("session.prompt", "/api/session/:sessionID/prompt", {
  167. params: { sessionID: SessionV2.ID },
  168. payload: Schema.Struct({
  169. id: SessionMessage.ID.pipe(Schema.optional),
  170. prompt: Prompt,
  171. delivery: SessionInput.Delivery.pipe(Schema.optional),
  172. resume: Schema.Boolean.pipe(Schema.optional),
  173. }),
  174. success: Schema.Struct({ data: SessionInput.Admitted }),
  175. error: [ConflictError, SessionNotFoundError],
  176. })
  177. .middleware(SessionLocationMiddleware)
  178. .annotateMerge(
  179. OpenApi.annotations({
  180. identifier: "v2.session.prompt",
  181. summary: "Send message",
  182. description: "Durably admit one session input and schedule agent-loop execution unless resume is false.",
  183. }),
  184. ),
  185. )
  186. .add(
  187. HttpApiEndpoint.post("session.compact", "/api/session/:sessionID/compact", {
  188. params: { sessionID: SessionV2.ID },
  189. success: HttpApiSchema.NoContent,
  190. error: [SessionNotFoundError, ServiceUnavailableError],
  191. })
  192. .middleware(SessionLocationMiddleware)
  193. .annotateMerge(
  194. OpenApi.annotations({
  195. identifier: "v2.session.compact",
  196. summary: "Compact session",
  197. description: "Compact a session conversation.",
  198. }),
  199. ),
  200. )
  201. .add(
  202. HttpApiEndpoint.post("session.wait", "/api/session/:sessionID/wait", {
  203. params: { sessionID: SessionV2.ID },
  204. success: HttpApiSchema.NoContent,
  205. error: [SessionNotFoundError, ServiceUnavailableError],
  206. })
  207. .middleware(SessionLocationMiddleware)
  208. .annotateMerge(
  209. OpenApi.annotations({
  210. identifier: "v2.session.wait",
  211. summary: "Wait for session",
  212. description: "Wait for a session agent loop to become idle.",
  213. }),
  214. ),
  215. )
  216. .add(
  217. HttpApiEndpoint.get("session.context", "/api/session/:sessionID/context", {
  218. params: { sessionID: SessionV2.ID },
  219. success: Schema.Struct({ data: Schema.Array(SessionMessage.Message) }),
  220. error: [SessionNotFoundError, UnknownError],
  221. })
  222. .middleware(SessionLocationMiddleware)
  223. .annotateMerge(
  224. OpenApi.annotations({
  225. identifier: "v2.session.context",
  226. summary: "Get session context",
  227. description: "Retrieve the active context messages for a session (all messages after the last compaction).",
  228. }),
  229. ),
  230. )
  231. .annotateMerge(
  232. OpenApi.annotations({
  233. title: "sessions",
  234. description: "Experimental session routes.",
  235. }),
  236. )