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

+6 -11
View File
@@ -1,18 +1,13 @@
import { ENV } from '@opencode-manager/shared/config/env'
import { buildOpenCodeBasicAuth } from '@opencode-manager/shared/opencode'
export type OpenCodePasswordResolver = () => string | Promise<string>
export function getOpenCodeBasicAuthHeader(): string | null
export function getOpenCodeBasicAuthHeader(password: string): string | null
export function getOpenCodeBasicAuthHeader(passwordResolver: OpenCodePasswordResolver): Promise<string | null>
export function getOpenCodeBasicAuthHeader(source?: string | OpenCodePasswordResolver): string | null | Promise<string | null> {
export function getOpenCodeBasicAuthHeader(password: string): string
export function getOpenCodeBasicAuthHeader(passwordResolver: OpenCodePasswordResolver): Promise<string>
export function getOpenCodeBasicAuthHeader(source: string | OpenCodePasswordResolver): string | Promise<string> {
if (typeof source === 'function') {
return Promise.resolve(source()).then((password) => getOpenCodeBasicAuthHeader(password))
return Promise.resolve(source()).then((password) => buildOpenCodeBasicAuth(password))
}
const password = source ?? ENV.OPENCODE.SERVER_PASSWORD
const username = ENV.OPENCODE.SERVER_USERNAME
if (!password) return null
const token = Buffer.from(`${username}:${password}`).toString('base64')
return `Basic ${token}`
return buildOpenCodeBasicAuth(source)
}
+26 -127
View File
@@ -1,41 +1,12 @@
import { logger } from '../../utils/logger'
import { ENV } from '@opencode-manager/shared/config/env'
import { createOpenCodeApi, type OpenCodeApi } from '@opencode-manager/shared/opencode'
import { getOpenCodeBasicAuthHeader, type OpenCodePasswordResolver } from './auth'
import { getOpenCodeUpstreamBaseUrl } from './upstream'
export interface ForwardRequest {
method: string
path: string
body?: string
headers?: Record<string, string>
directory?: string
signal?: AbortSignal
}
export interface JsonRequestOptions {
directory?: string
headers?: Record<string, string>
signal?: AbortSignal
}
export class UpstreamError extends Error {
constructor(
public readonly status: number,
public readonly bodyText: string,
message?: string,
) {
super(message ?? `OpenCode upstream returned ${status}`)
this.name = 'UpstreamError'
}
}
import { getOpenCodeUpstreamBaseUrl, withDefaultOpenCodeDirectory } from './upstream'
export interface OpenCodeClient {
forward(req: ForwardRequest): Promise<Response>
readonly api: OpenCodeApi
forwardRaw(request: Request): Promise<Response>
getJson<T>(path: string, opts?: JsonRequestOptions): Promise<T>
postJson<T>(path: string, body: unknown, opts?: JsonRequestOptions): Promise<T>
setProviderAuth(providerId: string, apiKey: string): Promise<boolean>
deleteProviderAuth(providerId: string): Promise<boolean>
}
export type OpenCodeClientHost = string | (() => string)
@@ -48,7 +19,14 @@ export interface FetchOpenCodeClientConfig {
}
export class FetchOpenCodeClient implements OpenCodeClient {
constructor(private readonly config: FetchOpenCodeClientConfig) {}
readonly api: OpenCodeApi
constructor(private readonly config: FetchOpenCodeClientConfig) {
this.api = createOpenCodeApi({
baseUrl: this.resolveBaseUrl(),
fetch: ((input, init) => this.fetchWithResolvedAuth(input, init)) as typeof fetch,
})
}
private get fetchFn(): typeof fetch {
return this.config.fetchFn ?? fetch
@@ -63,17 +41,25 @@ export class FetchOpenCodeClient implements OpenCodeClient {
return this.config.basicAuth ?? ''
}
return await getOpenCodeBasicAuthHeader(this.config.passwordResolver) ?? ''
return await getOpenCodeBasicAuthHeader(this.config.passwordResolver)
}
private async request(req: ForwardRequest): Promise<Response> {
const url = new URL(this.resolveBaseUrl() + req.path)
private async fetchWithResolvedAuth(input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]): Promise<Response> {
const headers = new Headers(withDefaultOpenCodeDirectory(Object.fromEntries(new Headers(init?.headers))))
const basicAuth = await this.getBasicAuth()
if (req.directory) {
url.searchParams.set('directory', req.directory)
if (basicAuth) {
headers.set('Authorization', basicAuth)
}
const headers: Record<string, string> = { ...(req.headers ?? {}) }
return this.fetchFn(input, { ...init, headers })
}
private async request(req: { method: string; path: string; body?: string; headers?: Record<string, string> }): Promise<Response> {
const url = new URL(this.resolveBaseUrl() + req.path)
const headers: Record<string, string> = withDefaultOpenCodeDirectory({ ...(req.headers ?? {}) })
const basicAuth = await this.getBasicAuth()
if (basicAuth) {
@@ -85,7 +71,6 @@ export class FetchOpenCodeClient implements OpenCodeClient {
method: req.method,
headers,
body: req.body,
signal: req.signal,
})
const filteredHeaders: Record<string, string> = {}
@@ -120,10 +105,6 @@ export class FetchOpenCodeClient implements OpenCodeClient {
}
}
async forward(req: ForwardRequest): Promise<Response> {
return this.request(req)
}
async forwardRaw(request: Request): Promise<Response> {
const url = new URL(request.url)
const cleanPathname = url.pathname.replace(/^\/api\/opencode/, '')
@@ -151,88 +132,6 @@ export class FetchOpenCodeClient implements OpenCodeClient {
headers,
})
}
async getJson<T>(path: string, opts?: JsonRequestOptions): Promise<T> {
const response = await this.request({
method: 'GET',
path,
directory: opts?.directory,
headers: opts?.headers,
signal: opts?.signal,
})
if (!response.ok) {
const bodyText = await response.text()
throw new UpstreamError(response.status, bodyText)
}
return (await response.json()) as T
}
async postJson<T>(path: string, body: unknown, opts?: JsonRequestOptions): Promise<T> {
const headers: Record<string, string> = {
'Content-Type': 'application/json',
...(opts?.headers ?? {}),
}
const response = await this.request({
method: 'POST',
path,
body: JSON.stringify(body),
headers,
directory: opts?.directory,
signal: opts?.signal,
})
if (!response.ok) {
const bodyText = await response.text()
throw new UpstreamError(response.status, bodyText)
}
return (await response.json()) as T
}
async setProviderAuth(providerId: string, apiKey: string): Promise<boolean> {
const response = await this.request({
method: 'PUT',
path: `/auth/${encodeURIComponent(providerId)}`,
body: JSON.stringify({ type: 'api', key: apiKey }),
headers: { 'Content-Type': 'application/json' },
})
if (response.ok) {
logger.info(`Set OpenCode auth for provider: ${providerId}`)
return true
}
if (response.status === 502) {
logger.error(`Failed to set OpenCode auth for provider: ${providerId}`)
return false
}
logger.error(`Failed to set OpenCode auth: ${response.status} ${response.statusText}`)
return false
}
async deleteProviderAuth(providerId: string): Promise<boolean> {
const response = await this.request({
method: 'DELETE',
path: `/auth/${encodeURIComponent(providerId)}`,
})
if (response.ok) {
logger.info(`Deleted OpenCode auth for provider: ${providerId}`)
return true
}
if (response.status === 502) {
logger.error(`Failed to delete OpenCode auth for provider: ${providerId}`)
return false
}
logger.error(`Failed to delete OpenCode auth: ${response.status} ${response.statusText}`)
return false
}
}
export function createOpenCodeClient(
@@ -243,7 +142,7 @@ export function createOpenCodeClient(
const baseUrl: OpenCodeClientHost = () => getOpenCodeUpstreamBaseUrl(resolveConfiguredHost())
const passwordResolver = typeof passwordOverride === 'function' ? passwordOverride : undefined
const password = typeof passwordOverride === 'string' ? passwordOverride : ENV.OPENCODE.SERVER_PASSWORD
const basicAuth = getOpenCodeBasicAuthHeader(password)
const basicAuth = password ? getOpenCodeBasicAuthHeader(password) : null
return new FetchOpenCodeClient({ baseUrl, basicAuth, passwordResolver })
}
@@ -0,0 +1,45 @@
import { isIntegrationNotFoundError, type OpenCodeApi } from '@opencode-manager/shared/opencode'
export const INTEGRATION_READY_POLL_INTERVAL_MS = 100
export const INTEGRATION_READY_TIMEOUT_MS = 2000
export type IntegrationTarget = Parameters<OpenCodeApi['integration']['get']>[0]
type IntegrationReader = Pick<OpenCodeApi, 'integration'>
function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms))
}
async function isIntegrationAvailable(api: IntegrationReader, target: IntegrationTarget): Promise<boolean | undefined> {
try {
await api.integration.get(target)
return true
} catch (error) {
return isIntegrationNotFoundError(error) ? false : undefined
}
}
async function waitForIntegration(api: IntegrationReader, target: IntegrationTarget): Promise<boolean> {
const deadline = Date.now() + INTEGRATION_READY_TIMEOUT_MS
while (Date.now() < deadline) {
await delay(INTEGRATION_READY_POLL_INTERVAL_MS)
const available = await isIntegrationAvailable(api, target)
if (available !== false) return available === true
}
return false
}
export async function runWhenIntegrationReady<T>(
api: IntegrationReader,
target: IntegrationTarget,
action: () => Promise<T>,
): Promise<T> {
try {
return await action()
} catch (error) {
if (!isIntegrationNotFoundError(error)) throw error
if (!(await waitForIntegration(api, target))) throw error
return await action()
}
}
@@ -1,29 +1,53 @@
import { promises as fs } from 'fs'
import { join } from 'path'
import { writeFileAtomic } from '../../utils/fs-safe'
import { buildGhEnvPluginSource } from '../opencode-gh-env-plugin'
import { buildManagerToolPluginSource } from '../opencode-manager-tool-plugin'
import { buildSandboxPluginSource } from '../opencode-sandbox-plugin'
import { getOpenCodeServiceSettingsPath } from '../opencode-service-mode'
import { ensureSandboxShellShim } from '../sandbox/shell-shim'
const MANAGED_OPENCODE_PLUGIN_IDS = {
ghEnv: 'ocm.gh-env',
manager: 'ocm.manager',
sandbox: 'ocm.sandbox',
} as const
type ManagedOpenCodePlugin = {
id: string
filename: string
buildSource: (context: { shellShimPath: string }) => string
buildSource: (context: { id: string; shellShimPath: string; serviceSettingsPath: string }) => string
}
const MANAGED_OPENCODE_PLUGINS: readonly ManagedOpenCodePlugin[] = [
{ filename: 'ocm-gh-env.js', buildSource: () => buildGhEnvPluginSource() },
{ filename: 'ocm-manager.js', buildSource: () => buildManagerToolPluginSource() },
{ filename: 'ocm-sandbox.js', buildSource: ({ shellShimPath }) => buildSandboxPluginSource(shellShimPath) },
{
id: MANAGED_OPENCODE_PLUGIN_IDS.ghEnv,
filename: 'ocm-gh-env.js',
buildSource: ({ id }) => buildGhEnvPluginSource(id),
},
{
id: MANAGED_OPENCODE_PLUGIN_IDS.manager,
filename: 'ocm-manager.js',
buildSource: ({ id }) => buildManagerToolPluginSource(id),
},
{
id: MANAGED_OPENCODE_PLUGIN_IDS.sandbox,
filename: 'ocm-sandbox.js',
buildSource: ({ id, shellShimPath, serviceSettingsPath }) => buildSandboxPluginSource(id, shellShimPath, serviceSettingsPath),
},
]
export function getOpenCodePluginDir(configHome: string): string {
return join(configHome, 'opencode', 'plugin')
return join(configHome, 'opencode', 'plugins')
}
export async function installManagedPlugins(configHome: string): Promise<void> {
const shellShimPath = await ensureSandboxShellShim(configHome)
const serviceSettingsPath = getOpenCodeServiceSettingsPath()
const dir = getOpenCodePluginDir(configHome)
const legacyDir = join(configHome, 'opencode', 'plugin')
for (const plugin of MANAGED_OPENCODE_PLUGINS) {
await writeFileAtomic(join(dir, plugin.filename), plugin.buildSource({ shellShimPath }))
await writeFileAtomic(join(dir, plugin.filename), plugin.buildSource({ id: plugin.id, shellShimPath, serviceSettingsPath }))
await fs.rm(join(legacyDir, plugin.filename), { force: true })
}
}
+8 -1
View File
@@ -1,4 +1,6 @@
import { ENV } from '@opencode-manager/shared/config/env'
import { ENV, getWorkspacePath } from '@opencode-manager/shared/config/env'
export const OPENCODE_DIRECTORY_HEADER = 'x-opencode-directory'
function formatOpenCodeHostForUrl(host: string): string {
if (host.startsWith('[') && host.endsWith(']')) return host
@@ -10,3 +12,8 @@ export function getOpenCodeUpstreamBaseUrl(hostOverride?: string | (() => string
const normalizedHost = configuredHost === '0.0.0.0' ? '127.0.0.1' : configuredHost
return `http://${formatOpenCodeHostForUrl(normalizedHost)}:${ENV.OPENCODE.PORT}`
}
export function withDefaultOpenCodeDirectory(headers: Record<string, string>): Record<string, string> {
const hasDirectory = Object.keys(headers).some((key) => key.toLowerCase() === OPENCODE_DIRECTORY_HEADER)
return hasDirectory ? headers : { ...headers, [OPENCODE_DIRECTORY_HEADER]: encodeURIComponent(getWorkspacePath()) }
}