session.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { RequestError, type McpServer } from "@agentclientprotocol/sdk"
  2. import type { ACPSessionState } from "./types"
  3. import { Log } from "@/util/log"
  4. import type { OpencodeClient } from "@opencode-ai/sdk"
  5. const log = Log.create({ service: "acp-session-manager" })
  6. export class ACPSessionManager {
  7. private sessions = new Map<string, ACPSessionState>()
  8. private sdk: OpencodeClient
  9. constructor(sdk: OpencodeClient) {
  10. this.sdk = sdk
  11. }
  12. async create(
  13. cwd: string,
  14. mcpServers: McpServer[],
  15. model?: ACPSessionState["model"],
  16. ): Promise<ACPSessionState> {
  17. const session = await this.sdk.session
  18. .create({
  19. body: {
  20. title: `ACP Session ${crypto.randomUUID()}`,
  21. },
  22. query: {
  23. directory: cwd,
  24. },
  25. throwOnError: true,
  26. })
  27. .then((x) => x.data)
  28. const sessionId = session.id
  29. const resolvedModel = model
  30. const state: ACPSessionState = {
  31. id: sessionId,
  32. cwd,
  33. mcpServers,
  34. createdAt: new Date(),
  35. model: resolvedModel,
  36. }
  37. log.info("creating_session", { state })
  38. this.sessions.set(sessionId, state)
  39. return state
  40. }
  41. get(sessionId: string): ACPSessionState {
  42. const session = this.sessions.get(sessionId)
  43. if (!session) {
  44. log.error("session not found", { sessionId })
  45. throw RequestError.invalidParams(JSON.stringify({ error: `Session not found: ${sessionId}` }))
  46. }
  47. return session
  48. }
  49. getModel(sessionId: string) {
  50. const session = this.get(sessionId)
  51. return session.model
  52. }
  53. setModel(sessionId: string, model: ACPSessionState["model"]) {
  54. const session = this.get(sessionId)
  55. session.model = model
  56. this.sessions.set(sessionId, session)
  57. return session
  58. }
  59. setMode(sessionId: string, modeId: string) {
  60. const session = this.get(sessionId)
  61. session.modeId = modeId
  62. this.sessions.set(sessionId, session)
  63. return session
  64. }
  65. }