import type { paths } from './opencode-types' import { fetchWrapper, fetchWrapperVoid } from './fetchWrapper' type SessionListResponse = paths['/session']['get']['responses']['200']['content']['application/json'] type SessionResponse = paths['/session/{sessionID}']['get']['responses']['200']['content']['application/json'] type SessionListParams = NonNullable & { roots?: boolean } type CreateSessionRequest = NonNullable['content']['application/json'] type MessageListResponse = paths['/session/{sessionID}/message']['get']['responses']['200']['content']['application/json'] type SendPromptRequest = NonNullable['content']['application/json'] type SendPromptAsyncRequest = NonNullable['content']['application/json'] type ConfigResponse = paths['/config']['get']['responses']['200']['content']['application/json'] type CommandListResponse = paths['/command']['get']['responses']['200']['content']['application/json'] type CommandRequest = NonNullable['content']['application/json'] type SendCommandResponse = paths['/session/{sessionID}/command']['post']['responses']['200']['content']['application/json'] type ShellRequest = NonNullable['content']['application/json'] type AgentListResponse = paths['/agent']['get']['responses']['200']['content']['application/json'] type PermissionListResponse = paths['/permission']['get']['responses']['200']['content']['application/json'] type QuestionListResponse = paths['/question']['get']['responses']['200']['content']['application/json'] type SendPromptResponse = paths['/session/{sessionID}/message']['post']['responses']['200']['content']['application/json'] type LspStatusResponse = paths['/lsp']['get']['responses']['200']['content']['application/json'] type LspStatus = LspStatusResponse[number] type LegacySession = SessionListResponse[number] /** Pre-v1.16.0 session shape returned by /api/session */ type SessionV2InfoV1 = { id: string parentID?: string projectID: string workspaceID?: string title: string time: { created: number; updated: number; compacting?: number; archived?: number } path?: unknown } /** v1.16.0+ session shape returned by /api/session */ type SessionV2InfoV2 = { id: string parentID?: string projectID: string title: string time: { created: number; updated: number; archived?: number } location: { directory: string; workspaceID?: string } agent?: string model?: { id: string; providerID: string; variant?: string } cost: number tokens: { input: number; output: number; reasoning: number; cache: { read: number; write: number } } subpath?: string } type SessionV2Info = SessionV2InfoV1 | SessionV2InfoV2 type SessionPageCursor = { previous?: string; next?: string } /** Response from /api/session — may be old (items) or new (data) format */ type SessionPageResponse = { data?: SessionV2InfoV2[] items?: SessionV2InfoV1[] cursor?: SessionPageCursor } type SessionPageParams = { limit?: number; order?: 'asc' | 'desc'; search?: string; cursor?: string } type SessionPage = { items: LegacySession[]; nextCursor?: string } function isNewSession(session: SessionV2Info): session is SessionV2InfoV2 { return 'location' in session && session.location !== undefined } function toLegacySession(session: SessionV2Info, directory?: string): LegacySession { if (isNewSession(session)) { return { id: session.id, projectID: session.projectID, workspaceID: session.location.workspaceID, directory: directory ?? session.location.directory ?? '', parentID: session.parentID, title: session.title || 'Untitled Session', version: 'v2', time: session.time, } as LegacySession } return { id: session.id, projectID: session.projectID, workspaceID: session.workspaceID, directory: directory ?? '', parentID: session.parentID, title: session.title || 'Untitled Session', version: 'v2', time: session.time, } as LegacySession } export type { SendPromptResponse, SendCommandResponse, LspStatus } export class OpenCodeClient { private baseURL: string private directory?: string constructor(baseURL: string, directory?: string) { this.baseURL = baseURL this.directory = directory } setDirectory(directory: string) { this.directory = directory } private getParams(params?: Record) { if (!this.directory) return params return { ...params, directory: this.directory } } async listSessions(params?: SessionListParams) { return fetchWrapper(`${this.baseURL}/session`, { params: this.getParams(params), }) } async listSessionsPage(params?: SessionPageParams): Promise { const isCursorRequest = params?.cursor !== undefined const queryParams = isCursorRequest ? { cursor: params.cursor } : this.getParams({ ...(params?.limit !== undefined && { limit: params.limit }), ...(params?.order !== undefined && { order: params.order }), ...(params?.search !== undefined && { search: params.search }), }) const response = await fetchWrapper(`${this.baseURL}/api/session`, { params: queryParams, }) const rawItems = response.data ?? response.items ?? [] return { items: rawItems.map((item) => toLegacySession(item, this.directory)), nextCursor: response.cursor?.next, } } async getSession(sessionID: string) { return fetchWrapper(`${this.baseURL}/session/${sessionID}`, { params: this.getParams(), }) } async createSession(data: CreateSessionRequest) { return fetchWrapper(`${this.baseURL}/session`, { method: 'POST', params: this.getParams(), headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data), }) } async deleteSession(sessionID: string) { return fetchWrapperVoid(`${this.baseURL}/session/${sessionID}`, { method: 'DELETE', params: this.getParams(), }) } async deleteWorkspace(workspaceID: string) { return fetchWrapperVoid(`${this.baseURL}/experimental/workspace/${workspaceID}`, { method: 'DELETE', params: this.getParams(), }) } async updateSession(sessionID: string, data: { title?: string }) { return fetchWrapper(`${this.baseURL}/session/${sessionID}`, { method: 'PATCH', params: this.getParams(), headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data), }) } async forkSession(sessionID: string, messageID?: string) { return fetchWrapper(`${this.baseURL}/session/${sessionID}/fork`, { method: 'POST', params: this.getParams(), headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ messageID }), }) } async abortSession(sessionID: string) { return fetchWrapper(`${this.baseURL}/session/${sessionID}/abort`, { method: 'POST', params: this.getParams(), }) } async listMessages(sessionID: string) { return fetchWrapper(`${this.baseURL}/session/${sessionID}/message`, { params: this.getParams(), }) } async sendPrompt(sessionID: string, data: SendPromptRequest): Promise { return fetchWrapper( `${this.baseURL}/session/${sessionID}/message`, { method: 'POST', params: this.getParams(), headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data), timeout: 0, } ) } async sendPromptAsync(sessionID: string, data: SendPromptAsyncRequest): Promise { return fetchWrapperVoid( `${this.baseURL}/session/${sessionID}/prompt_async`, { method: 'POST', params: this.getParams(), headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data), timeout: 0, } ) } async summarizeSession(sessionID: string, providerID: string, modelID: string) { return fetchWrapper(`${this.baseURL}/session/${sessionID}/summarize`, { method: 'POST', params: this.getParams(), headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ providerID, modelID }), }) } async getConfig() { return fetchWrapper(`${this.baseURL}/config`, { params: this.getParams(), }) } async getLSPStatus() { return fetchWrapper(`${this.baseURL}/lsp`, { params: this.getParams(), }) } async updateConfig(config: Partial) { return fetchWrapper(`${this.baseURL}/config`, { method: 'PATCH', params: this.getParams(), headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(config), }) } async getProviders() { return fetchWrapper(`${this.baseURL}/provider`, { params: this.getParams(), }) } async getConfigProviders() { return fetchWrapper(`${this.baseURL}/config/providers`, { params: this.getParams(), }) } async listCommands() { return fetchWrapper(`${this.baseURL}/command`, { params: this.getParams(), }) } async sendCommand(sessionID: string, data: CommandRequest): Promise { return fetchWrapper(`${this.baseURL}/session/${sessionID}/command`, { method: 'POST', params: this.getParams(), headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data), timeout: 0, }) } async sendShell(sessionID: string, data: ShellRequest) { return fetchWrapper(`${this.baseURL}/session/${sessionID}/shell`, { method: 'POST', params: this.getParams(), headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data), }) } async respondToPermission(sessionID: string, permissionID: string, response: 'once' | 'always' | 'reject') { return fetchWrapper(`${this.baseURL}/session/${sessionID}/permissions/${permissionID}`, { method: 'POST', params: this.getParams(), headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ response }), }) } async listPendingPermissions() { return fetchWrapper(`${this.baseURL}/permission`, { params: this.getParams(), }) } async replyToQuestion(requestID: string, answers: string[][]) { return fetchWrapper(`${this.baseURL}/question/${requestID}/reply`, { method: 'POST', params: this.getParams(), headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ answers }), }) } async rejectQuestion(requestID: string) { return fetchWrapper(`${this.baseURL}/question/${requestID}/reject`, { method: 'POST', params: this.getParams(), }) } async listPendingQuestions() { return fetchWrapper(`${this.baseURL}/question`, { params: this.getParams(), }) } async listAgents() { return fetchWrapper(`${this.baseURL}/agent`, { params: this.getParams(), }) } async revertMessage(sessionID: string, data: { messageID: string, partID?: string }) { return fetchWrapper(`${this.baseURL}/session/${sessionID}/revert`, { method: 'POST', params: this.getParams(), headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data), }) } async unrevertSession(sessionID: string) { return fetchWrapper(`${this.baseURL}/session/${sessionID}/unrevert`, { method: 'POST', params: this.getParams(), }) } async getSessionStatuses() { return fetchWrapper>(`${this.baseURL}/session/status`, { params: this.getParams(), }) } getEventSourceURL() { const base = this.baseURL.startsWith('http') ? this.baseURL : `${window.location.origin}${this.baseURL}` const url = new URL(`${base}/event`) if (this.directory) { url.searchParams.set('directory', this.directory) } return url.toString() } } export const createOpenCodeClient = (baseURL: string, directory?: string) => { return new OpenCodeClient(baseURL, directory) }