session.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. import { SessionMessage } from "@opencode-ai/schema/session-message"
  2. import { SessionInput } from "@opencode-ai/schema/session-input"
  3. import { Prompt } from "@opencode-ai/schema/prompt"
  4. import { Session } from "@opencode-ai/schema/session"
  5. import { Project } from "@opencode-ai/schema/project"
  6. import { AbsolutePath, PositiveInt, RelativePath, withStatics } from "@opencode-ai/schema/schema"
  7. import { Workspace } from "@opencode-ai/schema/workspace"
  8. import { Context, Encoding, Result, Schema, Struct } from "effect"
  9. import { HttpApiEndpoint, HttpApiGroup, HttpApiMiddleware, HttpApiSchema, OpenApi } from "effect/unstable/httpapi"
  10. import {
  11. ConflictError,
  12. InvalidCursorError,
  13. InvalidRequestError,
  14. MessageNotFoundError,
  15. ServiceUnavailableError,
  16. SessionNotFoundError,
  17. UnknownError,
  18. } from "../errors"
  19. import { Agent } from "@opencode-ai/schema/agent"
  20. import { Model } from "@opencode-ai/schema/model"
  21. import { Location } from "@opencode-ai/schema/location"
  22. import { Revert } from "@opencode-ai/schema/revert"
  23. const SessionsQueryFields = {
  24. workspace: Workspace.ID.pipe(Schema.optional),
  25. limit: Schema.NumberFromString.pipe(Schema.decodeTo(PositiveInt), Schema.optional).annotate({
  26. description: "Maximum number of sessions to return. Defaults to the newest 50 sessions.",
  27. }),
  28. order: Schema.optional(Schema.Union([Schema.Literal("asc"), Schema.Literal("desc")])).annotate({
  29. description: "Session order for the first page. Use desc for newest first or asc for oldest first.",
  30. }),
  31. search: Schema.optional(Schema.String),
  32. }
  33. const SessionsDirectoryQuery = Schema.Struct({
  34. ...SessionsQueryFields,
  35. directory: AbsolutePath,
  36. })
  37. const SessionsProjectQuery = Schema.Struct({
  38. ...SessionsQueryFields,
  39. project: Project.ID,
  40. subpath: RelativePath.pipe(Schema.optional),
  41. })
  42. const SessionsAllQuery = Schema.Struct(SessionsQueryFields)
  43. const withCursor = <Fields extends Schema.Struct.Fields>(schema: Schema.Struct<Fields>) =>
  44. schema.mapFields((fields) => ({
  45. ...Struct.omit(fields, ["limit"]),
  46. anchor: Session.ListAnchor,
  47. }))
  48. const SessionsCursorInput = Schema.Union([
  49. withCursor(SessionsDirectoryQuery),
  50. withCursor(SessionsProjectQuery),
  51. withCursor(SessionsAllQuery),
  52. ])
  53. const SessionsCursorJson = Schema.fromJsonString(SessionsCursorInput)
  54. const encodeSessionsCursor = Schema.encodeSync(SessionsCursorJson)
  55. const decodeSessionsCursor = Schema.decodeUnknownEffect(SessionsCursorJson)
  56. export const SessionsCursor = Schema.String.pipe(
  57. Schema.brand("SessionsCursor"),
  58. withStatics((schema) => {
  59. const make = schema.make.bind(schema)
  60. return {
  61. make: (input: typeof SessionsCursorInput.Type) => make(Encoding.encodeBase64Url(encodeSessionsCursor(input))),
  62. parse: (input: string) => decodeSessionsCursor(Result.getOrThrow(Encoding.decodeBase64UrlString(input))),
  63. }
  64. }),
  65. )
  66. export type SessionsCursor = typeof SessionsCursor.Type
  67. const SessionsQueryCursor = SessionsCursor.annotate({
  68. description: "Opaque pagination cursor returned as cursor.previous or cursor.next in the previous response.",
  69. })
  70. export const SessionsQuery = Schema.Struct({
  71. ...SessionsQueryFields,
  72. directory: AbsolutePath.pipe(Schema.optional),
  73. project: Project.ID.pipe(Schema.optional),
  74. subpath: RelativePath.pipe(Schema.optional),
  75. cursor: SessionsQueryCursor.pipe(Schema.optional),
  76. }).annotate({ identifier: "SessionsQuery" })
  77. export const makeSessionGroup = <I extends HttpApiMiddleware.AnyId, S>(sessionLocationMiddleware: Context.Key<I, S>) =>
  78. HttpApiGroup.make("server.session")
  79. .add(
  80. HttpApiEndpoint.get("session.list", "/api/session", {
  81. query: SessionsQuery,
  82. success: Schema.Struct({
  83. data: Schema.Array(Session.Info),
  84. cursor: Schema.Struct({
  85. previous: SessionsCursor.pipe(Schema.optional),
  86. next: SessionsCursor.pipe(Schema.optional),
  87. }),
  88. }).annotate({ identifier: "SessionsResponse" }),
  89. error: [InvalidCursorError, InvalidRequestError],
  90. }).annotateMerge(
  91. OpenApi.annotations({
  92. identifier: "v2.session.list",
  93. summary: "List sessions",
  94. description:
  95. "Retrieve sessions in the requested order. Items keep that order across pages; use cursor.next or cursor.previous to move through the ordered list.",
  96. }),
  97. ),
  98. )
  99. .add(
  100. HttpApiEndpoint.post("session.create", "/api/session", {
  101. payload: Schema.Struct({
  102. id: Session.ID.pipe(Schema.optional),
  103. agent: Agent.ID.pipe(Schema.optional),
  104. model: Model.Ref.pipe(Schema.optional),
  105. location: Location.Ref.pipe(Schema.optional),
  106. }),
  107. success: Schema.Struct({ data: Session.Info }),
  108. }).annotateMerge(
  109. OpenApi.annotations({
  110. identifier: "v2.session.create",
  111. summary: "Create session",
  112. description: "Create a session at the requested location.",
  113. }),
  114. ),
  115. )
  116. .add(
  117. HttpApiEndpoint.get("session.get", "/api/session/:sessionID", {
  118. params: { sessionID: Session.ID },
  119. success: Schema.Struct({ data: Session.Info }),
  120. error: SessionNotFoundError,
  121. })
  122. .middleware(sessionLocationMiddleware)
  123. .annotateMerge(
  124. OpenApi.annotations({
  125. identifier: "v2.session.get",
  126. summary: "Get session",
  127. description: "Retrieve a session by ID.",
  128. }),
  129. ),
  130. )
  131. .add(
  132. HttpApiEndpoint.post("session.switchAgent", "/api/session/:sessionID/agent", {
  133. params: { sessionID: Session.ID },
  134. payload: Schema.Struct({ agent: Agent.ID }),
  135. success: HttpApiSchema.NoContent,
  136. error: SessionNotFoundError,
  137. })
  138. .middleware(sessionLocationMiddleware)
  139. .annotateMerge(
  140. OpenApi.annotations({
  141. identifier: "v2.session.switchAgent",
  142. summary: "Switch session agent",
  143. description: "Switch the agent used by subsequent provider turns.",
  144. }),
  145. ),
  146. )
  147. .add(
  148. HttpApiEndpoint.post("session.switchModel", "/api/session/:sessionID/model", {
  149. params: { sessionID: Session.ID },
  150. payload: Schema.Struct({ model: Model.Ref }),
  151. success: HttpApiSchema.NoContent,
  152. error: SessionNotFoundError,
  153. })
  154. .middleware(sessionLocationMiddleware)
  155. .annotateMerge(
  156. OpenApi.annotations({
  157. identifier: "v2.session.switchModel",
  158. summary: "Switch session model",
  159. description: "Switch the model used by subsequent provider turns.",
  160. }),
  161. ),
  162. )
  163. .add(
  164. HttpApiEndpoint.post("session.prompt", "/api/session/:sessionID/prompt", {
  165. params: { sessionID: Session.ID },
  166. payload: Schema.Struct({
  167. id: SessionMessage.ID.pipe(Schema.optional),
  168. prompt: Prompt,
  169. delivery: SessionInput.Delivery.pipe(Schema.optional),
  170. resume: Schema.Boolean.pipe(Schema.optional),
  171. }),
  172. success: Schema.Struct({ data: SessionInput.Admitted }),
  173. error: [ConflictError, SessionNotFoundError],
  174. })
  175. .middleware(sessionLocationMiddleware)
  176. .annotateMerge(
  177. OpenApi.annotations({
  178. identifier: "v2.session.prompt",
  179. summary: "Send message",
  180. description: "Durably admit one session input and schedule agent-loop execution unless resume is false.",
  181. }),
  182. ),
  183. )
  184. .add(
  185. HttpApiEndpoint.post("session.compact", "/api/session/:sessionID/compact", {
  186. params: { sessionID: Session.ID },
  187. success: HttpApiSchema.NoContent,
  188. error: [SessionNotFoundError, ServiceUnavailableError],
  189. })
  190. .middleware(sessionLocationMiddleware)
  191. .annotateMerge(
  192. OpenApi.annotations({
  193. identifier: "v2.session.compact",
  194. summary: "Compact session",
  195. description: "Compact a session conversation.",
  196. }),
  197. ),
  198. )
  199. .add(
  200. HttpApiEndpoint.post("session.wait", "/api/session/:sessionID/wait", {
  201. params: { sessionID: Session.ID },
  202. success: HttpApiSchema.NoContent,
  203. error: [SessionNotFoundError, ServiceUnavailableError],
  204. })
  205. .middleware(sessionLocationMiddleware)
  206. .annotateMerge(
  207. OpenApi.annotations({
  208. identifier: "v2.session.wait",
  209. summary: "Wait for session",
  210. description: "Wait for a session agent loop to become idle.",
  211. }),
  212. ),
  213. )
  214. .add(
  215. HttpApiEndpoint.post("session.revert.stage", "/api/session/:sessionID/revert/stage", {
  216. params: { sessionID: Session.ID },
  217. payload: Schema.Struct({ messageID: SessionMessage.ID, files: Schema.Boolean.pipe(Schema.optional) }),
  218. success: Schema.Struct({ data: Revert.State }),
  219. error: [MessageNotFoundError, SessionNotFoundError, UnknownError],
  220. })
  221. .middleware(sessionLocationMiddleware)
  222. .annotateMerge(
  223. OpenApi.annotations({
  224. identifier: "v2.session.revert.stage",
  225. summary: "Stage session revert",
  226. description: "Stage or move a reversible session boundary and optionally apply its file changes.",
  227. }),
  228. ),
  229. )
  230. .add(
  231. HttpApiEndpoint.post("session.revert.clear", "/api/session/:sessionID/revert/clear", {
  232. params: { sessionID: Session.ID },
  233. success: HttpApiSchema.NoContent,
  234. error: [SessionNotFoundError, UnknownError],
  235. })
  236. .middleware(sessionLocationMiddleware)
  237. .annotateMerge(OpenApi.annotations({ identifier: "v2.session.revert.clear", summary: "Clear staged revert" })),
  238. )
  239. .add(
  240. HttpApiEndpoint.post("session.revert.commit", "/api/session/:sessionID/revert/commit", {
  241. params: { sessionID: Session.ID },
  242. success: HttpApiSchema.NoContent,
  243. error: SessionNotFoundError,
  244. })
  245. .middleware(sessionLocationMiddleware)
  246. .annotateMerge(
  247. OpenApi.annotations({ identifier: "v2.session.revert.commit", summary: "Commit staged revert" }),
  248. ),
  249. )
  250. .add(
  251. HttpApiEndpoint.get("session.context", "/api/session/:sessionID/context", {
  252. params: { sessionID: Session.ID },
  253. success: Schema.Struct({ data: Schema.Array(SessionMessage.Message) }),
  254. error: [SessionNotFoundError, UnknownError],
  255. })
  256. .middleware(sessionLocationMiddleware)
  257. .annotateMerge(
  258. OpenApi.annotations({
  259. identifier: "v2.session.context",
  260. summary: "Get session context",
  261. description: "Retrieve the active context messages for a session (all messages after the last compaction).",
  262. }),
  263. ),
  264. )
  265. .annotateMerge(
  266. OpenApi.annotations({
  267. title: "sessions",
  268. description: "Experimental session routes.",
  269. }),
  270. )