session.ts 15 KB

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