feat(opencode): migrate OpenCode Manager to OpenCode 2 (#359)

* feat(opencode): migrate OpenCode Manager to OpenCode 2

Port the backend lifecycle, generated plugins, event aggregation,
schedules, worktrees, provider credentials, MCP, config handling, the
frontend chat model, and the ocm CLI to OpenCode 2.

Adopt @opencode/client 2.0.15 as the single typed V2 API contract,
require OpenCode 2.0.0 or newer (pinned 2.0.15), and delete every
V1-only code path.

* refactor(opencode): reload config in place and drop v1 compatibility shims

Route config/skill/AGENTS.md changes through the OpenCode location reload
API instead of a full server restart, stop auto-resuming interrupted
sessions, remove the restart coordinator and v1 MCP/version shims, and pin
support to OpenCode >=2.0.15 <3.0.0. Adds integration-ready retries,
service-mode launch, ocm-cli repo proxy, and new frontend form/MCP helpers.

* refactor(opencode): consolidate v2 migration helpers and harden install, proxy, and session flows

- extract shared semver and model-ref utilities, reuse across version checks
- share the OpenCode release download script across Docker, entrypoint, dev setup
- unify install/upgrade failure recovery and guard externally managed OPENCODE_BIN
- scope the repo proxy location rewrite and surface ocm proxy errors
- rework frontend session projection, permission lookup, and cache invalidation

* fix(schedules): reject unavailable agents before creating a session

* feat(opencode): add ocm install, schedule agent fallback, and session move guards
This commit is contained in:
Chris Scott authored and GitHub committed 2026-09-26 13:16:45 -04:00
1 parent 6c2ebd764b
commit dacde879d6
383 files changed
+29905 -46566

No files matched your search

+261 -341
View File
@@ -1,356 +1,276 @@
import type { paths } from './opencode-types'
import { fetchWrapper, fetchWrapperVoid } from './fetchWrapper'
import { openCodeLocation, parseOpenCodeModelRef } from '@opencode-manager/shared/opencode'
import { callOpenCode } from './opencodeApi'
import type {
AgentInfo,
CommandInfo,
FormAnswer,
FormInfo,
ModelRef,
OpenCodeApi,
PermissionRequest,
SessionInboxCompaction,
SessionInboxUser,
SessionInfo,
SessionMessageInfo,
SessionRevert,
} from '@opencode-manager/shared/opencode'
import type { SessionSnapshot } from '@/lib/session-projection'
type SessionListResponse = paths['/session']['get']['responses']['200']['content']['application/json']
type SessionResponse = paths['/session/{sessionID}']['get']['responses']['200']['content']['application/json']
type SessionListParams = NonNullable<paths['/session']['get']['parameters']['query']> & {
roots?: boolean
}
type CreateSessionRequest = NonNullable<paths['/session']['post']['requestBody']>['content']['application/json']
type MessageListResponse = paths['/session/{sessionID}/message']['get']['responses']['200']['content']['application/json']
type SendPromptAsyncRequest = NonNullable<paths['/session/{sessionID}/prompt_async']['post']['requestBody']>['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<paths['/session/{sessionID}/command']['post']['requestBody']>['content']['application/json']
type SendCommandResponse = paths['/session/{sessionID}/command']['post']['responses']['200']['content']['application/json']
type ShellRequest = NonNullable<paths['/session/{sessionID}/shell']['post']['requestBody']>['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 LspStatusResponse = paths['/lsp']['get']['responses']['200']['content']['application/json']
type LspStatus = LspStatusResponse[number]
type SessionPromptInput = Parameters<OpenCodeApi['session']['prompt']>[0]
type LegacySession = SessionListResponse[number]
export type PromptFileInput = NonNullable<SessionPromptInput['files']>[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
export type PromptAgentInput = NonNullable<SessionPromptInput['agents']>[number]
export type PromptSkillInput = NonNullable<SessionPromptInput['skills']>[number]
export type ActiveSessions = Awaited<ReturnType<OpenCodeApi['session']['active']>>
export interface SessionPage {
items: SessionInfo[]
nextCursor?: string
}
/** 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 }
export interface SessionPageInput {
directory: string
limit?: number
order?: 'asc' | 'desc'
search?: string
cursor?: string
}
export interface CreateSessionInput {
directory: string
title?: 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
model?: 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
export interface FindFilesInput {
directory?: string
query: string
limit?: number
}
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
}
export interface SessionMessagesPage {
messages: SessionMessageInfo[]
nextCursor?: string
}
export interface SessionMessagesInput {
cursor?: string
limit?: number
}
export interface SendPromptInput {
sessionID: string
text: string
files?: PromptFileInput[]
agents?: PromptAgentInput[]
skills?: PromptSkillInput[]
delivery?: 'steer' | 'queue'
}
export type RunCommandInput = SendPromptInput & { name: string }
type PromptFields = Pick<SendPromptInput, 'text' | 'files' | 'agents' | 'skills' | 'delivery'>
function buildPromptFields(input: PromptFields) {
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 { 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<string, string | number | boolean | undefined>) {
if (!this.directory) return params
return { ...params, directory: this.directory }
}
async listSessions(params?: SessionListParams) {
return fetchWrapper<SessionListResponse>(`${this.baseURL}/session`, {
params: this.getParams(params),
})
}
async listSessionsPage(params?: SessionPageParams): Promise<SessionPage> {
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<SessionPageResponse>(`${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<SessionResponse>(`${this.baseURL}/session/${sessionID}`, {
params: this.getParams(),
})
}
async createSession(data: CreateSessionRequest) {
return fetchWrapper<SessionResponse>(`${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<SessionResponse>(`${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<MessageListResponse>(`${this.baseURL}/session/${sessionID}/message`, {
params: this.getParams(),
})
}
async sendPromptAsync(sessionID: string, data: SendPromptAsyncRequest): Promise<void> {
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<ConfigResponse>(`${this.baseURL}/config`, {
params: this.getParams(),
})
}
async getLSPStatus() {
return fetchWrapper<LspStatusResponse>(`${this.baseURL}/lsp`, {
params: this.getParams(),
})
}
async updateConfig(config: Partial<ConfigResponse>) {
return fetchWrapper<ConfigResponse>(`${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<CommandListResponse>(`${this.baseURL}/command`, {
params: this.getParams(),
})
}
async sendCommand(sessionID: string, data: CommandRequest): Promise<SendCommandResponse> {
return fetchWrapper<SendCommandResponse>(`${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(permissionID: string, response: 'once' | 'always' | 'reject') {
return fetchWrapper(`${this.baseURL}/permission/${permissionID}/reply`, {
method: 'POST',
params: this.getParams(),
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ reply: response }),
})
}
async listPendingPermissions() {
return fetchWrapper<PermissionListResponse>(`${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<QuestionListResponse>(`${this.baseURL}/question`, {
params: this.getParams(),
})
}
async listAgents() {
return fetchWrapper<AgentListResponse>(`${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<Record<string, { type: 'idle' } | { type: 'busy' } | { type: 'retry'; attempt: number; message: string; next: number }>>(`${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()
text: input.text,
...(input.files ? { files: input.files } : {}),
...(input.agents ? { agents: input.agents } : {}),
...(input.skills ? { skills: input.skills } : {}),
...(input.delivery ? { delivery: input.delivery } : {}),
}
}
export const createOpenCodeClient = (baseURL: string, directory?: string) => {
return new OpenCodeClient(baseURL, directory)
export async function listSessionPage(input: SessionPageInput): Promise<SessionPage> {
const { data, cursor } = await callOpenCode((api) =>
api.session.list({
directory: input.directory,
parentID: 'null',
limit: input.limit,
order: input.order,
search: input.search,
cursor: input.cursor,
}),
)
return { items: data, nextCursor: cursor.next ?? undefined }
}
export async function getSession(sessionID: string): Promise<SessionInfo> {
return callOpenCode((api) => api.session.get({ sessionID }))
}
export async function createSession(input: CreateSessionInput): Promise<SessionInfo> {
const model = input.model ? parseOpenCodeModelRef(input.model) : undefined
return callOpenCode((api) =>
api.session.create({
...(input.title !== undefined ? { title: input.title } : {}),
...(input.agent !== undefined ? { agent: input.agent } : {}),
...(model ? { model } : {}),
location: { directory: input.directory },
}),
)
}
export async function deleteSession(sessionID: string): Promise<void> {
await callOpenCode((api) => api.session.remove({ sessionID }))
}
export async function renameSession(sessionID: string, title: string): Promise<void> {
await callOpenCode((api) => api.session.update({ sessionID, title }))
}
export async function forkSession(sessionID: string, before?: string): Promise<SessionInfo> {
return callOpenCode((api) =>
api.session.fork({
sessionID,
...(before ? { before } : {}),
}),
)
}
export async function switchSessionModel(sessionID: string, model: ModelRef): Promise<void> {
await callOpenCode((api) => api.session.switchModel({ sessionID, model }))
}
export async function switchSessionAgent(sessionID: string, agent: string): Promise<void> {
await callOpenCode((api) => api.session.switchAgent({ sessionID, agent }))
}
export async function sendPrompt(input: SendPromptInput): Promise<SessionInboxUser> {
return callOpenCode((api) =>
api.session.prompt({
sessionID: input.sessionID,
...buildPromptFields(input),
}),
)
}
export async function runCommand(input: RunCommandInput): Promise<void> {
await callOpenCode((api) =>
api.session.command({
sessionID: input.sessionID,
name: input.name,
...buildPromptFields(input),
}),
)
}
export async function runShell(sessionID: string, command: string): Promise<void> {
await callOpenCode((api) => api.session.shell({ sessionID, command }))
}
export async function interruptSession(sessionID: string): Promise<void> {
await callOpenCode((api) => api.session.interrupt({ sessionID }))
}
export async function stageRevert(sessionID: string, messageID: string): Promise<SessionRevert> {
return callOpenCode((api) => api.session.revert.stage({ sessionID, messageID }))
}
export async function commitRevert(sessionID: string): Promise<void> {
await callOpenCode((api) => api.session.revert.commit({ sessionID }))
}
export async function clearRevert(sessionID: string): Promise<void> {
await callOpenCode((api) => api.session.revert.clear({ sessionID }))
}
export async function compactSession(sessionID: string): Promise<SessionInboxCompaction> {
return callOpenCode((api) => api.session.compact({ sessionID }))
}
export async function activateSkill(sessionID: string, id: string): Promise<void> {
await callOpenCode((api) => api.session.skill({ sessionID, id }))
}
export async function listActiveSessions(): Promise<ActiveSessions> {
return callOpenCode((api) => api.session.active())
}
export async function listAgents(directory?: string): Promise<AgentInfo[]> {
const { data } = await callOpenCode((api) => api.agent.list(openCodeLocation(directory)))
return data
}
export async function listCommands(directory?: string): Promise<CommandInfo[]> {
const { data } = await callOpenCode((api) => api.command.list(openCodeLocation(directory)))
return data
}
export async function listPendingPermissions(directory: string): Promise<PermissionRequest[]> {
const { data } = await callOpenCode((api) => api.permission.request.list(openCodeLocation(directory)))
return data
}
export async function replyPermission(
sessionID: string,
requestID: string,
decision: 'once' | 'always' | 'reject',
message?: string,
): Promise<void> {
await callOpenCode((api) =>
api.permission.reply({
sessionID,
requestID,
decision,
...(message ? { message } : {}),
}),
)
}
export async function listPendingForms(directory: string): Promise<FormInfo[]> {
const { data } = await callOpenCode((api) => api.form.list(openCodeLocation(directory)))
return data
}
export async function replyForm(sessionID: string, formID: string, answer: FormAnswer): Promise<void> {
await callOpenCode((api) => api.session.form.reply({ sessionID, formID, answer }))
}
export async function cancelForm(sessionID: string, formID: string): Promise<void> {
await callOpenCode((api) => api.session.form.cancel({ sessionID, formID }))
}
export async function findFiles(input: FindFilesInput): Promise<string[]> {
const { data } = await callOpenCode((api) =>
api.file.find({
...openCodeLocation(input.directory),
query: input.query,
type: 'file',
limit: input.limit,
}),
)
return data.map((entry) => entry.path)
}
export async function listSessionMessages(
sessionID: string,
input: SessionMessagesInput = {},
): Promise<SessionMessagesPage> {
const { data, cursor } = await callOpenCode((api) =>
api.message.list({
sessionID,
...(input.limit === undefined ? {} : { limit: input.limit }),
...(input.cursor === undefined ? { order: 'desc' as const } : { cursor: input.cursor }),
}),
)
return { messages: [...data].reverse(), nextCursor: cursor.next ?? undefined }
}
export async function readSessionSnapshot(sessionID: string): Promise<SessionSnapshot> {
const [page, pending, active] = await Promise.all([
listSessionMessages(sessionID),
callOpenCode((api) => api.session.inbox.list({ sessionID })),
listActiveSessions(),
])
return {
messages: page.messages,
nextCursor: page.nextCursor,
pending,
status: active[sessionID] ? 'busy' : 'idle',
}
}