mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
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:
1 parent
6c2ebd764b
commit
dacde879d6
383 files changed
+29905
-46566
No files matched your search
@@ -1,10 +1,16 @@
|
||||
import { Hono } from 'hono'
|
||||
import type { Context } from 'hono'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { ENV } from '@opencode-manager/shared/config/env'
|
||||
import { buildOpenCodeBasicAuth } from '@opencode-manager/shared/opencode'
|
||||
import { createInternalTokenMiddleware } from '../auth/internal-token-middleware'
|
||||
import type { SettingsService } from '../services/settings'
|
||||
import { opencodeServerManager } from '../services/opencode-single-server'
|
||||
import { getOpenCodeUpstreamBaseUrl } from '../services/opencode/upstream'
|
||||
import {
|
||||
getOpenCodeUpstreamBaseUrl,
|
||||
OPENCODE_DIRECTORY_HEADER,
|
||||
withDefaultOpenCodeDirectory,
|
||||
} from '../services/opencode/upstream'
|
||||
import { getRepoById } from '../db/queries'
|
||||
|
||||
const HOP_BY_HOP_HEADERS = new Set([
|
||||
'connection',
|
||||
@@ -21,12 +27,61 @@ const HOP_BY_HOP_HEADERS = new Set([
|
||||
'authorization',
|
||||
])
|
||||
|
||||
interface ProxyRequestParts {
|
||||
method: string
|
||||
path: string
|
||||
headers: Record<string, string>
|
||||
searchParams: URLSearchParams
|
||||
}
|
||||
|
||||
type ProxyRewrite = (parts: ProxyRequestParts) => void
|
||||
|
||||
type ProxyBodyRewrite = (bodyText: string) => string | undefined
|
||||
|
||||
function isJsonContentType(contentType: string | undefined): boolean {
|
||||
return (contentType ?? '').toLowerCase().includes('application/json')
|
||||
}
|
||||
|
||||
function rewriteRepoLocation(parts: ProxyRequestParts, directory: string): void {
|
||||
parts.headers[OPENCODE_DIRECTORY_HEADER] = encodeURIComponent(directory)
|
||||
|
||||
if (parts.searchParams.has('location[directory]')) {
|
||||
parts.searchParams.set('location[directory]', directory)
|
||||
}
|
||||
|
||||
if (parts.method === 'GET' && parts.path === '/api/session') {
|
||||
parts.searchParams.set('directory', directory)
|
||||
}
|
||||
}
|
||||
|
||||
function rewriteRepoLocationBody(bodyText: string, directory: string): string | undefined {
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = JSON.parse(bodyText)
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
|
||||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return undefined
|
||||
|
||||
const location = (parsed as { location?: unknown }).location
|
||||
if (!location || typeof location !== 'object' || Array.isArray(location)) return undefined
|
||||
|
||||
;(parsed as { location: Record<string, unknown> }).location = { ...location, directory }
|
||||
return JSON.stringify(parsed)
|
||||
}
|
||||
|
||||
export function createOpenCodeProxyRoutes(db: Database, settingsService: SettingsService) {
|
||||
const app = new Hono()
|
||||
|
||||
app.use('/*', createInternalTokenMiddleware(db))
|
||||
|
||||
app.all('/*', async (c) => {
|
||||
async function forwardToOpenCode(
|
||||
c: Context,
|
||||
pathSuffix: string,
|
||||
rewrite?: ProxyRewrite,
|
||||
rewriteBody?: ProxyBodyRewrite,
|
||||
): Promise<Response> {
|
||||
if (!opencodeServerManager.isLifecycleInitialized()) {
|
||||
return c.json({ error: 'OpenCode lifecycle initialization is incomplete; refusing to proxy to an unmanaged server' }, 503)
|
||||
}
|
||||
@@ -38,26 +93,44 @@ export function createOpenCodeProxyRoutes(db: Database, settingsService: Setting
|
||||
}
|
||||
|
||||
const url = new URL(c.req.url)
|
||||
const pathSuffix = url.pathname.replace(/^\/api\/opencode-proxy/, '') || '/'
|
||||
const upstreamUrl = `${getOpenCodeUpstreamBaseUrl()}${pathSuffix}${url.search}`
|
||||
const hasBody = c.req.method !== 'GET' && c.req.method !== 'HEAD'
|
||||
|
||||
const headers: Record<string, string> = {}
|
||||
const forwardedHeaders: Record<string, string> = {}
|
||||
c.req.raw.headers.forEach((value, key) => {
|
||||
const lowerKey = key.toLowerCase()
|
||||
if (!HOP_BY_HOP_HEADERS.has(lowerKey)) {
|
||||
headers[key] = value
|
||||
forwardedHeaders[key] = value
|
||||
}
|
||||
})
|
||||
const headers = withDefaultOpenCodeDirectory(forwardedHeaders)
|
||||
|
||||
const password = settingsService.getOpenCodeServerPassword()
|
||||
const username = ENV.OPENCODE.SERVER_USERNAME
|
||||
headers['Authorization'] = `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`
|
||||
headers['Authorization'] = buildOpenCodeBasicAuth(settingsService.getOpenCodeServerPassword())
|
||||
|
||||
let requestBody: RequestInit['body'] = undefined
|
||||
if (c.req.method !== 'GET' && c.req.method !== 'HEAD') {
|
||||
requestBody = c.req.raw.body
|
||||
const isJson = isJsonContentType(headers['content-type'] ?? headers['Content-Type'])
|
||||
const shouldBufferBody = rewriteBody !== undefined && hasBody && isJson
|
||||
const rawBody = shouldBufferBody ? await c.req.arrayBuffer() : undefined
|
||||
|
||||
let requestBody: RequestInit['body'] = hasBody ? c.req.raw.body : undefined
|
||||
|
||||
if (rewrite) {
|
||||
const parts: ProxyRequestParts = {
|
||||
method: c.req.method,
|
||||
path: pathSuffix,
|
||||
headers,
|
||||
searchParams: url.searchParams,
|
||||
}
|
||||
rewrite(parts)
|
||||
url.search = parts.searchParams.toString()
|
||||
}
|
||||
|
||||
if (rewriteBody && rawBody !== undefined) {
|
||||
const bodyText = rawBody.byteLength > 0 ? new TextDecoder().decode(rawBody) : undefined
|
||||
const rewrittenBody = bodyText === undefined ? undefined : rewriteBody(bodyText)
|
||||
requestBody = rewrittenBody === undefined ? rawBody : rewrittenBody
|
||||
}
|
||||
|
||||
const upstreamUrl = `${getOpenCodeUpstreamBaseUrl()}${pathSuffix}${url.search}`
|
||||
|
||||
try {
|
||||
const upstreamResponse = await fetch(upstreamUrl, {
|
||||
method: c.req.method,
|
||||
@@ -83,6 +156,31 @@ export function createOpenCodeProxyRoutes(db: Database, settingsService: Setting
|
||||
} catch {
|
||||
return c.json({ error: 'Proxy request failed' }, 502)
|
||||
}
|
||||
}
|
||||
|
||||
app.all('/repos/:repoId/*', async (c) => {
|
||||
const repoId = Number(c.req.param('repoId'))
|
||||
const repo = Number.isInteger(repoId) ? getRepoById(db, repoId) : null
|
||||
if (!repo || repo.cloneStatus !== 'ready') {
|
||||
return c.json({ error: 'Repo not found' }, 404)
|
||||
}
|
||||
|
||||
const url = new URL(c.req.url)
|
||||
const pathSuffix = url.pathname.replace(/^\/api\/opencode-proxy\/repos\/[^/]+/, '') || '/'
|
||||
|
||||
return forwardToOpenCode(
|
||||
c,
|
||||
pathSuffix,
|
||||
(parts) => rewriteRepoLocation(parts, repo.fullPath),
|
||||
(bodyText) => rewriteRepoLocationBody(bodyText, repo.fullPath),
|
||||
)
|
||||
})
|
||||
|
||||
app.all('/*', async (c) => {
|
||||
const url = new URL(c.req.url)
|
||||
const pathSuffix = url.pathname.replace(/^\/api\/opencode-proxy/, '') || '/'
|
||||
|
||||
return forwardToOpenCode(c, pathSuffix)
|
||||
})
|
||||
|
||||
return app
|
||||
|
||||
Reference in new issue
Block a user