session.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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, NonNegativeInt, PositiveInt, RelativePath, statics } 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. import { SessionEvent } from "@opencode-ai/schema/session-event"
  24. const SessionsQueryFields = {
  25. workspace: Workspace.ID.pipe(Schema.optional),
  26. limit: Schema.NumberFromString.pipe(Schema.decodeTo(PositiveInt), Schema.optional).annotate({
  27. description: "Maximum number of sessions to return. Defaults to the newest 50 sessions.",
  28. }),
  29. order: Schema.optional(Schema.Union([Schema.Literal("asc"), Schema.Literal("desc")])).annotate({
  30. description: "Session order for the first page. Use desc for newest first or asc for oldest first.",
  31. }),
  32. search: Schema.optional(Schema.String),
  33. }
  34. const SessionsDirectoryQuery = Schema.Struct({
  35. ...SessionsQueryFields,
  36. directory: AbsolutePath,
  37. })
  38. const SessionsProjectQuery = Schema.Struct({
  39. ...SessionsQueryFields,
  40. project: Project.ID,
  41. subpath: RelativePath.pipe(Schema.optional),
  42. })
  43. const SessionsAllQuery = Schema.Struct(SessionsQueryFields)
  44. const withCursor = <Fields extends Schema.Struct.Fields>(schema: Schema.Struct<Fields>) =>
  45. schema.mapFields((fields) => ({
  46. ...Struct.omit(fields, ["limit"]),
  47. anchor: Session.ListAnchor,
  48. }))
  49. const SessionsCursorInput = Schema.Union([
  50. withCursor(SessionsDirectoryQuery),
  51. withCursor(SessionsProjectQuery),
  52. withCursor(SessionsAllQuery),
  53. ])
  54. const SessionsCursorJson = Schema.fromJsonString(SessionsCursorInput)
  55. const encodeSessionsCursor = Schema.encodeSync(SessionsCursorJson)
  56. const decodeSessionsCursor = Schema.decodeUnknownEffect(SessionsCursorJson)
  57. export const SessionsCursor = Schema.String.pipe(
  58. Schema.brand("SessionsCursor"),
  59. statics((schema) => {
  60. const make = schema.make.bind(schema)
  61. return {
  62. make: (input: typeof SessionsCursorInput.Type) => make(Encoding.encodeBase64Url(encodeSessionsCursor(input))),
  63. parse: (input: string) => decodeSessionsCursor(Result.getOrThrow(Encoding.decodeBase64UrlString(input))),
  64. }
  65. }),
  66. )
  67. export type SessionsCursor = typeof SessionsCursor.Type
  68. const SessionActive = Schema.Struct({
  69. type: Schema.Literal("running"),
  70. }).annotate({ identifier: "SessionActive" })
  71. const SessionsQueryCursor = SessionsCursor.annotate({
  72. description: "Opaque pagination cursor returned as cursor.previous or cursor.next in the previous response.",
  73. })
  74. export const SessionsQuery = Schema.Struct({
  75. ...SessionsQueryFields,
  76. directory: AbsolutePath.pipe(Schema.optional),
  77. project: Project.ID.pipe(Schema.optional),
  78. subpath: RelativePath.pipe(Schema.optional),
  79. cursor: SessionsQueryCursor.pipe(Schema.optional),
  80. }).annotate({ identifier: "SessionsQuery" })
  81. export const makeSessionGroup = <I extends HttpApiMiddleware.AnyId, S>(sessionLocationMiddleware: Context.Key<I, S>) =>
  82. HttpApiGroup.make("server.session")
  83. .add(
  84. HttpApiEndpoint.get("session.list", "/api/session", {
  85. query: SessionsQuery,
  86. success: Schema.Struct({
  87. data: Schema.Array(Session.Info),
  88. cursor: Schema.Struct({
  89. previous: SessionsCursor.pipe(Schema.optional),
  90. next: SessionsCursor.pipe(Schema.optional),
  91. }),
  92. }).annotate({ identifier: "SessionsResponse" }),
  93. error: [InvalidCursorError, InvalidRequestError],
  94. }).annotateMerge(
  95. OpenApi.annotations({
  96. identifier: "v2.session.list",
  97. summary: "List sessions",
  98. description:
  99. "Retrieve sessions in the requested order. Items keep that order across pages; use cursor.next or cursor.previous to move through the ordered list.",
  100. }),
  101. ),
  102. )
  103. .add(
  104. HttpApiEndpoint.post("session.create", "/api/session", {
  105. payload: Schema.Struct({
  106. id: Session.ID.pipe(Schema.optional),
  107. agent: Agent.ID.pipe(Schema.optional),
  108. model: Model.Ref.pipe(Schema.optional),
  109. location: Location.Ref.pipe(Schema.optional),
  110. }),
  111. success: Schema.Struct({ data: Session.Info }),
  112. }).annotateMerge(
  113. OpenApi.annotations({
  114. identifier: "v2.session.create",
  115. summary: "Create session",
  116. description: "Create a session at the requested location.",
  117. }),
  118. ),
  119. )
  120. .add(
  121. HttpApiEndpoint.get("session.active", "/api/session/active", {
  122. success: Schema.Struct({ data: Schema.Record(Session.ID, SessionActive) }),
  123. }).annotateMerge(
  124. OpenApi.annotations({
  125. identifier: "v2.session.active",
  126. summary: "List active sessions",
  127. description:
  128. "Retrieve foreground Session drains currently owned by this OpenCode process. Sessions absent from the result are inactive.",
  129. }),
  130. ),
  131. )
  132. .add(
  133. HttpApiEndpoint.get("session.get", "/api/session/:sessionID", {
  134. params: { sessionID: Session.ID },
  135. success: Schema.Struct({ data: Session.Info }),
  136. error: SessionNotFoundError,
  137. })
  138. .middleware(sessionLocationMiddleware)
  139. .annotateMerge(
  140. OpenApi.annotations({
  141. identifier: "v2.session.get",
  142. summary: "Get session",
  143. description: "Retrieve a session by ID.",
  144. }),
  145. ),
  146. )
  147. .add(
  148. HttpApiEndpoint.post("session.switchAgent", "/api/session/:sessionID/agent", {
  149. params: { sessionID: Session.ID },
  150. payload: Schema.Struct({ agent: Agent.ID }),
  151. success: HttpApiSchema.NoContent,
  152. error: SessionNotFoundError,
  153. })
  154. .middleware(sessionLocationMiddleware)
  155. .annotateMerge(
  156. OpenApi.annotations({
  157. identifier: "v2.session.switchAgent",
  158. summary: "Switch session agent",
  159. description: "Switch the agent used by subsequent provider turns.",
  160. }),
  161. ),
  162. )
  163. .add(
  164. HttpApiEndpoint.post("session.switchModel", "/api/session/:sessionID/model", {
  165. params: { sessionID: Session.ID },
  166. payload: Schema.Struct({ model: Model.Ref }),
  167. success: HttpApiSchema.NoContent,
  168. error: SessionNotFoundError,
  169. })
  170. .middleware(sessionLocationMiddleware)
  171. .annotateMerge(
  172. OpenApi.annotations({
  173. identifier: "v2.session.switchModel",
  174. summary: "Switch session model",
  175. description: "Switch the model used by subsequent provider turns.",
  176. }),
  177. ),
  178. )
  179. .add(
  180. HttpApiEndpoint.post("session.prompt", "/api/session/:sessionID/prompt", {
  181. params: { sessionID: Session.ID },
  182. payload: Schema.Struct({
  183. id: SessionMessage.ID.pipe(Schema.optional),
  184. prompt: Prompt,
  185. delivery: SessionInput.Delivery.pipe(Schema.optional),
  186. resume: Schema.Boolean.pipe(Schema.optional),
  187. }),
  188. success: Schema.Struct({ data: SessionInput.Admitted }),
  189. error: [ConflictError, SessionNotFoundError],
  190. })
  191. .middleware(sessionLocationMiddleware)
  192. .annotateMerge(
  193. OpenApi.annotations({
  194. identifier: "v2.session.prompt",
  195. summary: "Send message",
  196. description: "Durably admit one session input and schedule agent-loop execution unless resume is false.",
  197. }),
  198. ),
  199. )
  200. .add(
  201. HttpApiEndpoint.post("session.compact", "/api/session/:sessionID/compact", {
  202. params: { sessionID: Session.ID },
  203. success: HttpApiSchema.NoContent,
  204. error: [SessionNotFoundError, ServiceUnavailableError],
  205. })
  206. .middleware(sessionLocationMiddleware)
  207. .annotateMerge(
  208. OpenApi.annotations({
  209. identifier: "v2.session.compact",
  210. summary: "Compact session",
  211. description: "Compact a session conversation.",
  212. }),
  213. ),
  214. )
  215. .add(
  216. HttpApiEndpoint.post("session.wait", "/api/session/:sessionID/wait", {
  217. params: { sessionID: Session.ID },
  218. success: HttpApiSchema.NoContent,
  219. error: [SessionNotFoundError, ServiceUnavailableError],
  220. })
  221. .middleware(sessionLocationMiddleware)
  222. .annotateMerge(
  223. OpenApi.annotations({
  224. identifier: "v2.session.wait",
  225. summary: "Wait for session",
  226. description: "Wait for a session agent loop to become idle.",
  227. }),
  228. ),
  229. )
  230. .add(
  231. HttpApiEndpoint.post("session.revert.stage", "/api/session/:sessionID/revert/stage", {
  232. params: { sessionID: Session.ID },
  233. payload: Schema.Struct({ messageID: SessionMessage.ID, files: Schema.Boolean.pipe(Schema.optional) }),
  234. success: Schema.Struct({ data: Revert.State }),
  235. error: [MessageNotFoundError, SessionNotFoundError, UnknownError],
  236. })
  237. .middleware(sessionLocationMiddleware)
  238. .annotateMerge(
  239. OpenApi.annotations({
  240. identifier: "v2.session.revert.stage",
  241. summary: "Stage session revert",
  242. description: "Stage or move a reversible session boundary and optionally apply its file changes.",
  243. }),
  244. ),
  245. )
  246. .add(
  247. HttpApiEndpoint.post("session.revert.clear", "/api/session/:sessionID/revert/clear", {
  248. params: { sessionID: Session.ID },
  249. success: HttpApiSchema.NoContent,
  250. error: [SessionNotFoundError, UnknownError],
  251. })
  252. .middleware(sessionLocationMiddleware)
  253. .annotateMerge(OpenApi.annotations({ identifier: "v2.session.revert.clear", summary: "Clear staged revert" })),
  254. )
  255. .add(
  256. HttpApiEndpoint.post("session.revert.commit", "/api/session/:sessionID/revert/commit", {
  257. params: { sessionID: Session.ID },
  258. success: HttpApiSchema.NoContent,
  259. error: SessionNotFoundError,
  260. })
  261. .middleware(sessionLocationMiddleware)
  262. .annotateMerge(
  263. OpenApi.annotations({ identifier: "v2.session.revert.commit", summary: "Commit staged revert" }),
  264. ),
  265. )
  266. .add(
  267. HttpApiEndpoint.get("session.context", "/api/session/:sessionID/context", {
  268. params: { sessionID: Session.ID },
  269. success: Schema.Struct({ data: Schema.Array(SessionMessage.Message) }),
  270. error: [SessionNotFoundError, UnknownError],
  271. })
  272. .middleware(sessionLocationMiddleware)
  273. .annotateMerge(
  274. OpenApi.annotations({
  275. identifier: "v2.session.context",
  276. summary: "Get session context",
  277. description: "Retrieve the active context messages for a session (all messages after the last compaction).",
  278. }),
  279. ),
  280. )
  281. .add(
  282. HttpApiEndpoint.get("session.events", "/api/session/:sessionID/event", {
  283. params: { sessionID: Session.ID },
  284. query: {
  285. after: Schema.NumberFromString.pipe(Schema.decodeTo(NonNegativeInt), Schema.optional),
  286. },
  287. success: HttpApiSchema.StreamSse({ data: SessionEvent.Durable }),
  288. error: SessionNotFoundError,
  289. })
  290. .middleware(sessionLocationMiddleware)
  291. .annotateMerge(
  292. OpenApi.annotations({
  293. identifier: "v2.session.events",
  294. summary: "Subscribe to session events",
  295. description: "Replay durable events after an aggregate sequence, then continue with new durable events.",
  296. }),
  297. ),
  298. )
  299. .add(
  300. HttpApiEndpoint.post("session.interrupt", "/api/session/:sessionID/interrupt", {
  301. params: { sessionID: Session.ID },
  302. success: HttpApiSchema.NoContent,
  303. error: SessionNotFoundError,
  304. })
  305. .middleware(sessionLocationMiddleware)
  306. .annotateMerge(
  307. OpenApi.annotations({
  308. identifier: "v2.session.interrupt",
  309. summary: "Interrupt session execution",
  310. description: "Interrupt active execution owned by this OpenCode process. Idle interruption is a no-op.",
  311. }),
  312. ),
  313. )
  314. .add(
  315. HttpApiEndpoint.get("session.message", "/api/session/:sessionID/message/:messageID", {
  316. params: { sessionID: Session.ID, messageID: SessionMessage.ID },
  317. success: Schema.Struct({ data: SessionMessage.Message }),
  318. error: [SessionNotFoundError, MessageNotFoundError],
  319. })
  320. .middleware(sessionLocationMiddleware)
  321. .annotateMerge(
  322. OpenApi.annotations({
  323. identifier: "v2.session.message",
  324. summary: "Get session message",
  325. description: "Retrieve one projected message owned by the Session.",
  326. }),
  327. ),
  328. )
  329. .annotateMerge(
  330. OpenApi.annotations({
  331. title: "sessions",
  332. description: "Experimental session routes.",
  333. }),
  334. )