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

+85 -286
View File
@@ -15,7 +15,14 @@ import {
parseSSHHost
} from '../utils/ssh-key-manager'
import { decryptSecret } from '../utils/crypto'
import { BLOCKED_SERVER_ENV_KEYS, DEFAULT_SERVER_ENV_VARS } from '@opencode-manager/shared'
import { BLOCKED_SERVER_ENV_KEYS } from '@opencode-manager/shared'
import {
OPENCODE_PINNED_VERSION,
describeUnsupportedOpenCodeVersion,
isSupportedOpenCodeVersion,
parseOpenCodeVersionOutput,
} from '@opencode-manager/shared/opencode'
import { resolveOpenCodeBinaryPath } from './opencode-installer'
import { SettingsService } from './settings'
import {
getWorkspacePath,
@@ -27,37 +34,31 @@ import {
ENV,
} from '@opencode-manager/shared/config/env'
import type { Database } from 'bun:sqlite'
import { compareVersions } from '../utils/version-utils'
import type { OpenCodeClient } from './opencode/client'
import {
readOpenCodeConfigFile,
} from './opencode-config-file'
import { getOrCreateInternalToken } from './internal-token'
import { installManagedPlugins } from './opencode/plugin-registry'
import { getOpenCodePluginDiscoveryHome, restoreQuarantinedOpenCodePlugins } from './opencode-plugin-quarantine'
import { getOpenCodeHome } from './opencode-home'
import { restoreQuarantinedOpenCodePlugins } from './opencode-plugin-quarantine'
import { resolveProcessIdentityProvider } from './opencode/process-identity'
import { SandboxRuntimeService } from './sandbox/runtime'
import { CredentialProvider } from './credential-provider'
import { mkdirSafe, writeFileAtomic } from '../utils/fs-safe'
import { createProcessLogForwarder } from '../utils/log-buffer'
import { OPENCODE_SERVICE_SERVE_ARGS, prepareOpenCodeServiceLaunch } from './opencode-service-mode'
const MIN_OPENCODE_VERSION = '1.0.137'
const MAX_STDERR_SIZE = 10240
const PLUGIN_INSTALL_TIMEOUT_MS = 120000
const PROCESS_EXIT_GRACE_MS = 2000
const STARTUP_HEALTH_TIMEOUT_MS = 30000
const PROCESS_SIGTERM_GRACE_MS = 10000
const PROCESS_SIGKILL_CONFIRM_MS = 2000
const PROCESS_EXIT_POLL_MS = 50
const CHILD_STATE_MARKER_REFRESH_MS = 60000
const DEPRECATED_PLUGIN_PACKAGES = ['opencode-openai-codex-auth', 'opencode-copilot-auth']
type StartupValidationIssue = {
path: string
message: string
}
type OpenCodePluginOptions = Record<string, unknown>
type OpenCodePluginSpec = string | [string, OpenCodePluginOptions]
export class ConfigReloadError extends Error {
validationIssues: StartupValidationIssue[]
@@ -82,51 +83,12 @@ export class OpenCodeOperationBusyError extends Error {
}
}
function parseStartupValidationIssues(stderrOutput: string): StartupValidationIssue[] {
const match = stderrOutput.match(/ZodError:\s*(\[[\s\S]*?\])(?:\n\s+at |$)/)
if (!match?.[1]) {
return []
}
try {
const parsed = JSON.parse(match[1]) as Array<{ path?: unknown; message?: unknown }>
return parsed
.map((issue) => ({
path: Array.isArray(issue.path) && issue.path.length > 0 ? issue.path.join('.') : 'root',
message: typeof issue.message === 'string' ? issue.message : 'Invalid value',
}))
.filter((issue) => issue.message)
} catch {
return []
}
}
function formatStartupError(stderrOutput: string, fallback: string): string {
const validationIssues = parseStartupValidationIssues(stderrOutput)
if (validationIssues.length === 0) {
return fallback
}
const summary = validationIssues
.slice(0, 8)
.map((issue) => `${issue.path}: ${issue.message}`)
.join('; ')
const remainder = validationIssues.length > 8
? ` (${validationIssues.length - 8} more issue${validationIssues.length - 8 === 1 ? '' : 's'})`
: ''
return `OpenCode config validation failed: ${summary}${remainder}`
}
// Helper getters to ensure values are computed at runtime (not module load time)
// This allows proper mocking in tests
const getOpenCodeServerDirectory = () => getWorkspacePath()
const getOpenCodeConfigPath = () => getOpenCodeConfigFilePath()
const getOpenCodeServerPort = () => ENV.OPENCODE.PORT
const getOpenCodeServerHost = () => ENV.OPENCODE.HOST
const getOpenCodeServerPublicUrl = () => ENV.OPENCODE.PUBLIC_URL
const getOpenCodeServerUsername = () => ENV.OPENCODE.SERVER_USERNAME
function resolveManagerMicrosandboxEnv(): Record<string, string> {
const env: Record<string, string> = {
@@ -266,7 +228,7 @@ async function removeChildStateMarker(): Promise<void> {
export function resolveOpenCodeExecutable(): string | null {
const candidates = [
process.env.OPENCODE_BIN,
path.join(getOpenCodePluginDiscoveryHome(), '.opencode', 'bin', 'opencode'),
resolveOpenCodeBinaryPath(getOpenCodeHome()),
'/usr/local/bin/opencode',
'/opt/opencode/bin/opencode',
].filter((candidate): candidate is string => typeof candidate === 'string' && candidate.length > 0)
@@ -364,7 +326,7 @@ class OpenCodeServerManager {
return this.opInProgress
}
async start(retryAfterPluginInstall = true, allowNested = false): Promise<void> {
async start(allowNested = false): Promise<void> {
const acquired = this.acquireOp()
if (!acquired && !allowNested) {
throw new OpenCodeOperationBusyError()
@@ -395,9 +357,9 @@ class OpenCodeServerManager {
)
}
try {
await this.terminateAttestedPredecessor(PROCESS_EXIT_GRACE_MS)
await this.terminateAttestedPredecessor()
if (existingProcesses.length > 0) {
await this.terminatePortOwners(existingProcesses, PROCESS_EXIT_GRACE_MS)
await this.terminatePortOwners(existingProcesses)
}
} catch (cleanupError) {
this.failNonRecoverable(
@@ -424,13 +386,6 @@ class OpenCodeServerManager {
const password = this.getResolvedPassword()
const openCodeServerHost = getOpenCodeServerHost()
const isExposed = openCodeServerHost !== '127.0.0.1' && openCodeServerHost !== 'localhost'
if (isExposed && !password) {
const msg = `OPENCODE_HOST=${openCodeServerHost} exposes the OpenCode server externally but no password is configured. Set OPENCODE_SERVER_PASSWORD env var or configure a password via Settings → OpenCode → Server Auth.`
this.lastStartupError = msg
logger.error(msg)
throw new Error(msg)
}
let credentialProvider: CredentialProvider | null = null
let gitIdentityEnv: Record<string, string> = {}
@@ -441,11 +396,7 @@ class OpenCodeServerManager {
const settingsService = new SettingsService(this.db)
const settings = settingsService.getSettings('default')
const gitCredentials = credentialProvider.getGitCredentials()
const disabledDefaultEnvVars = new Set(settings.preferences.disabledDefaultServerEnvVars || [])
const rawEnvVars = [
...DEFAULT_SERVER_ENV_VARS.filter((envVar) => !disabledDefaultEnvVars.has(envVar.key)),
...(settings.preferences.serverEnvVars || []),
]
const rawEnvVars = settings.preferences.serverEnvVars || []
if (rawEnvVars.length > 0) {
userEnvVars = Object.fromEntries(
rawEnvVars
@@ -494,10 +445,10 @@ class OpenCodeServerManager {
}
let replacingExistingServer = false
if (sandboxEnforced) {
await this.terminateAttestedPredecessor(PROCESS_EXIT_GRACE_MS)
await this.terminateAttestedPredecessor()
if (existingProcesses.length > 0) {
logger.warn('Sandbox enforcement enabled: killing existing OpenCode server to guarantee a sandboxed startup')
await this.terminatePortOwners(existingProcesses, PROCESS_EXIT_GRACE_MS)
await this.terminatePortOwners(existingProcesses)
replacingExistingServer = true
}
} else if (existingProcesses.length > 0) {
@@ -506,7 +457,7 @@ class OpenCodeServerManager {
if (healthy) {
if (isDevelopment) {
logger.warn('Development mode: Killing existing server for hot reload')
await this.terminatePortOwners(existingProcesses, PROCESS_EXIT_GRACE_MS)
await this.terminatePortOwners(existingProcesses)
replacingExistingServer = true
} else {
const childState = await readChildStateMarker()
@@ -522,17 +473,17 @@ class OpenCodeServerManager {
return
}
logger.warn(`Existing OpenCode server on port ${openCodeServerPort} is not attested as a matching unenforced child; terminating it to guarantee consistent sandbox enforcement`)
await this.terminatePortOwners(existingProcesses, PROCESS_EXIT_GRACE_MS)
await this.terminatePortOwners(existingProcesses)
replacingExistingServer = true
}
} else {
logger.warn('Killing unhealthy OpenCode server')
await this.terminatePortOwners(existingProcesses, PROCESS_EXIT_GRACE_MS)
await this.terminatePortOwners(existingProcesses)
replacingExistingServer = true
}
}
await this.reconcileExitedChildMarker(PROCESS_EXIT_GRACE_MS)
await this.reconcileExitedChildMarker()
const openCodeServerDirectory = getOpenCodeServerDirectory()
const openCodeConfigPath = getOpenCodeConfigPath()
@@ -587,7 +538,12 @@ class OpenCodeServerManager {
logger.info(`OpenCode server GIT_SSH_COMMAND: ${gitSshCommand}`)
await this.initializeOpencodeBinDirectory()
await this.fetchVersion()
if (this.version && !this.isVersionSupported()) {
this.failNonRecoverable(
`${describeUnsupportedOpenCodeVersion(this.version)}. Install a supported version from Settings → OpenCode.`,
)
}
await this.resetAgentTmpDirectory()
const pluginConfigHome = getOpenCodeConfigHome()
try {
@@ -606,9 +562,6 @@ class OpenCodeServerManager {
}
logger.warn('Failed to install a generated OpenCode plugin (sandboxing is disabled):', error)
}
const configuredPlugins = await this.getConfiguredPlugins()
await this.installConfiguredPlugins(configuredPlugins)
const configuredPluginCount = configuredPlugins.length
const openCodeExecutable = resolveOpenCodeExecutable() ?? 'opencode'
let stderrOutput = ''
@@ -616,49 +569,56 @@ class OpenCodeServerManager {
const microsandboxEnv = resolveManagerMicrosandboxEnv()
const cleanEnv = { ...process.env }
delete cleanEnv.OPENCODE_PASSWORD
delete cleanEnv.OPENCODE_SERVER_PASSWORD
delete cleanEnv.OPENCODE_RUN_ID
delete cleanEnv.OPENCODE_PROCESS_ROLE
delete cleanEnv.OPENCODE_PID
delete cleanEnv.OPENCODE
delete cleanEnv.OPENCODE_PURE
delete cleanEnv.OPENCODE_CONFIG
delete cleanEnv.OPENCODE_CONFIG_DIR
delete cleanEnv.OPENCODE_CONFIG_CONTENT
delete userEnvVars.OPENCODE_CONFIG
delete userEnvVars.OPENCODE_CONFIG_DIR
delete userEnvVars.OPENCODE_CONFIG_CONTENT
const serverEnv = {
...cleanEnv,
...userEnvVars,
...microsandboxEnv,
...gitEnv,
...gitIdentityEnv,
...(this.db
? {
OCM_INTERNAL_API_URL: `http://localhost:${ENV.SERVER.PORT}/api/internal`,
OCM_INTERNAL_TOKEN: getOrCreateInternalToken(this.db),
}
: {}),
OCM_SANDBOX_ENFORCED: sandboxEnforced ? 'true' : 'false',
GIT_SSH_COMMAND: gitSshCommand,
XDG_DATA_HOME: getOpenCodeStateHome(),
XDG_STATE_HOME: getOpenCodeStateHome(),
XDG_CONFIG_HOME: getOpenCodeConfigHome(),
TMPDIR: getOpenCodeTmpHome(),
}
try {
await prepareOpenCodeServiceLaunch(serverEnv, password)
} catch (error) {
const message = `Failed to prepare the OpenCode service settings: ${error instanceof Error ? error.message : String(error)}`
this.lastStartupError = message
logger.error(message)
throw new Error(message)
}
this.serverProcess = spawn(
openCodeExecutable,
['serve', '--port', openCodeServerPort.toString(), '--hostname', openCodeServerHost],
[...OPENCODE_SERVICE_SERVE_ARGS, '--port', openCodeServerPort.toString(), '--hostname', openCodeServerHost],
{
cwd: openCodeServerDirectory,
detached: !isDevelopment,
stdio: isDevelopment ? 'inherit' : ['ignore', 'pipe', 'pipe'],
env: {
...cleanEnv,
...userEnvVars,
...microsandboxEnv,
...gitEnv,
...gitIdentityEnv,
...(this.db
? {
OCM_INTERNAL_API_URL: `http://localhost:${ENV.SERVER.PORT}/api/internal`,
OCM_INTERNAL_TOKEN: getOrCreateInternalToken(this.db),
}
: {}),
OCM_SANDBOX_ENFORCED: sandboxEnforced ? 'true' : 'false',
OPENCODE_PURE: 'false',
GIT_SSH_COMMAND: gitSshCommand,
XDG_DATA_HOME: getOpenCodeStateHome(),
XDG_STATE_HOME: getOpenCodeStateHome(),
XDG_CONFIG_HOME: getOpenCodeConfigHome(),
TMPDIR: getOpenCodeTmpHome(),
...(getOpenCodeServerPublicUrl() ? { OPENCODE_PUBLIC_URL: getOpenCodeServerPublicUrl() } : {}),
...(password
? {
OPENCODE_SERVER_PASSWORD: password,
OPENCODE_SERVER_USERNAME: getOpenCodeServerUsername(),
}
: {}),
}
env: serverEnv,
}
)
@@ -690,8 +650,7 @@ class OpenCodeServerManager {
this.stopChildStateMarkerRefresh()
}
if (code !== null && code !== 0) {
const fallback = `Server exited with code ${code}${stderrOutput ? `: ${stderrOutput.slice(-500)}` : ''}`
this.lastStartupError = formatStartupError(stderrOutput, fallback)
this.lastStartupError = `Server exited with code ${code}${stderrOutput ? `: ${stderrOutput.slice(-500)}` : ''}`
logger.error('OpenCode server process exited:', this.lastStartupError)
} else if (signal) {
this.lastStartupError = `Server terminated by signal ${signal}`
@@ -740,18 +699,9 @@ class OpenCodeServerManager {
logger.info(`OpenCode server started with PID ${this.serverPid}`)
const healthTimeoutMs = configuredPluginCount > 0 ? 120000 : 30000
const healthy = await this.waitForHealth(healthTimeoutMs)
const healthy = await this.waitForHealth(STARTUP_HEALTH_TIMEOUT_MS)
if (!healthy) {
const fallback = `Server failed to become healthy after ${Math.round(healthTimeoutMs / 1000)}s${stderrOutput ? `. Last error: ${stderrOutput.slice(-500)}` : ''}`
this.lastStartupError = formatStartupError(stderrOutput, fallback)
if (configuredPluginCount > 0 && retryAfterPluginInstall) {
logger.warn(`OpenCode server did not become healthy after installing ${configuredPluginCount} configured plugin(s); restarting once`)
await this.stop(true)
await new Promise(r => setTimeout(r, 1000))
await this.start(false, true)
return
}
this.lastStartupError = `Server failed to become healthy after ${Math.round(STARTUP_HEALTH_TIMEOUT_MS / 1000)}s${stderrOutput ? `. Last error: ${stderrOutput.slice(-500)}` : ''}`
throw new Error('OpenCode server failed to become healthy')
}
@@ -785,10 +735,6 @@ class OpenCodeServerManager {
await this.fetchVersion()
if (this.version) {
logger.info(`OpenCode version: ${this.version}`)
if (!this.isVersionSupported()) {
logger.warn(`OpenCode version ${this.version} is below minimum required version ${MIN_OPENCODE_VERSION}`)
logger.warn('Some features like MCP management may not work correctly')
}
}
} finally {
this.releaseOp(acquired)
@@ -803,7 +749,7 @@ class OpenCodeServerManager {
try {
if (!this.serverPid) {
await this.reconcileExitedChildMarker(PROCESS_EXIT_GRACE_MS)
await this.reconcileExitedChildMarker()
return
}
@@ -840,7 +786,6 @@ class OpenCodeServerManager {
await this.terminateAndConfirm(
pid,
groupTarget,
PROCESS_EXIT_GRACE_MS,
'OpenCode server',
'retained live processes after SIGTERM and SIGKILL; refusing to complete the stop while host-executed processes may survive',
)
@@ -876,141 +821,6 @@ class OpenCodeServerManager {
}
}
private async initializeOpencodeBinDirectory(): Promise<void> {
const binDir = path.join(getOpenCodeStateHome(), 'opencode', 'bin')
const packageJsonPath = path.join(binDir, 'package.json')
try {
await mkdirSafe(binDir)
const packageJsonExists = await fs.access(packageJsonPath)
.then(() => true)
.catch((error: NodeJS.ErrnoException) => {
if (error.code === 'ENOENT') return false
throw error
})
if (!packageJsonExists) {
try {
execSync('bun init -y', {
cwd: binDir,
stdio: 'inherit',
timeout: 30000
})
logger.info('OpenCode bin directory initialized successfully')
} catch (error) {
logger.error('bun init failed:', error)
throw new Error(`bun init failed: ${error}`)
}
}
} catch (error) {
logger.error('Failed to initialize OpenCode bin directory:', error)
}
}
private isPathPluginSpec(spec: string): boolean {
return spec.startsWith('file://') || spec.startsWith('.') || path.isAbsolute(spec)
}
private getPluginInstallSpec(spec: string): string {
if (spec.startsWith('@')) {
const slashIndex = spec.indexOf('/')
return slashIndex !== -1 && spec.indexOf('@', slashIndex + 1) === -1 ? `${spec}@latest` : spec
}
return spec.includes('@') ? spec : `${spec}@latest`
}
private getPluginPackageName(spec: string): string {
if (spec.startsWith('@')) {
const slashIndex = spec.indexOf('/')
if (slashIndex === -1) return spec
const versionIndex = spec.indexOf('@', slashIndex + 1)
return versionIndex === -1 ? spec : spec.slice(0, versionIndex)
}
const versionIndex = spec.indexOf('@')
return versionIndex === -1 ? spec : spec.slice(0, versionIndex)
}
private sanitizeNpmCacheSegment(spec: string): string {
if (process.platform !== 'win32') return spec
return Array.from(spec, (char) => /[<>:"|?*]/.test(char) || char.charCodeAt(0) < 32 ? '_' : char).join('')
}
private getPluginSpecifier(plugin: OpenCodePluginSpec): string {
return Array.isArray(plugin) ? plugin[0] : plugin
}
private isOpenCodePluginSpec(plugin: unknown): plugin is OpenCodePluginSpec {
if (typeof plugin === 'string') return plugin.trim().length > 0
if (!Array.isArray(plugin) || plugin.length !== 2 || typeof plugin[0] !== 'string' || plugin[0].trim().length === 0) return false
const options = plugin[1]
return options !== null && typeof options === 'object' && !Array.isArray(options)
}
private async getConfiguredPlugins(): Promise<OpenCodePluginSpec[]> {
try {
const file = await readOpenCodeConfigFile()
const plugin = file?.content.plugin
if (!Array.isArray(plugin)) return []
return plugin
.filter((entry): entry is OpenCodePluginSpec => this.isOpenCodePluginSpec(entry))
} catch {
return []
}
}
private async installConfiguredPlugins(plugins: OpenCodePluginSpec[]): Promise<void> {
const npmPlugins = plugins
.map((plugin) => this.getPluginSpecifier(plugin))
.filter((plugin) => !this.isPathPluginSpec(plugin) && !DEPRECATED_PLUGIN_PACKAGES.some((pkg) => plugin.includes(pkg)))
if (npmPlugins.length === 0) return
const cacheHome = process.env.XDG_CACHE_HOME || path.join(process.env.HOME || '/home/node', '.cache')
logger.info(`Pre-installing ${npmPlugins.length} configured OpenCode plugin(s)`)
for (const plugin of npmPlugins) {
const installSpec = this.getPluginInstallSpec(plugin)
const packageName = this.getPluginPackageName(plugin)
const installDir = path.join(cacheHome, 'opencode', 'packages', this.sanitizeNpmCacheSegment(installSpec))
const packageJsonPath = path.join(installDir, 'node_modules', packageName, 'package.json')
try {
await fs.access(packageJsonPath)
logger.info(`OpenCode plugin already installed: ${plugin}`)
continue
} catch (error) {
const errorCode = error && typeof error === 'object' && 'code' in error ? (error as NodeJS.ErrnoException).code : ''
if (errorCode !== 'ENOENT') {
logger.warn(`Could not check OpenCode plugin install state for ${plugin}:`, error)
}
}
await mkdirSafe(installDir)
if (!await fs.access(path.join(installDir, 'package.json')).then(() => true).catch(() => false)) {
const init = spawnSync('bun', ['init', '-y'], { cwd: installDir, encoding: 'utf8', timeout: 30000 })
if (init.status !== 0) {
logger.warn(`Failed to initialize OpenCode plugin cache for ${plugin}: ${init.stderr || init.stdout}`)
continue
}
}
const result = spawnSync('bun', ['add', '--ignore-scripts', installSpec], { cwd: installDir, encoding: 'utf8', timeout: PLUGIN_INSTALL_TIMEOUT_MS })
if (result.status === 0) {
logger.info(`Installed OpenCode plugin: ${plugin}`)
continue
}
if (result.error) {
logger.warn(`Failed to install OpenCode plugin ${plugin}: ${result.error.message}`)
continue
}
logger.warn(`Failed to install OpenCode plugin ${plugin}: ${result.stderr || result.stdout}`)
}
}
async restart(): Promise<void> {
const acquired = this.acquireOp()
if (!acquired) {
@@ -1020,7 +830,7 @@ class OpenCodeServerManager {
try {
logger.info('Restarting OpenCode server (full process restart)')
await this.stop(true)
await this.start(false, true)
await this.start(true)
} finally {
this.releaseOp(acquired)
}
@@ -1035,12 +845,12 @@ class OpenCodeServerManager {
}
getMinVersion(): string {
return MIN_OPENCODE_VERSION
return OPENCODE_PINNED_VERSION
}
isVersionSupported(): boolean {
if (!this.version) return false
return compareVersions(this.version, MIN_OPENCODE_VERSION) >= 0
return isSupportedOpenCodeVersion(this.version)
}
getLastStartupError(): string | null {
@@ -1085,22 +895,15 @@ class OpenCodeServerManager {
advanceDurableRestartGeneration(this.db)
}
async reinitializeBinDirectory(): Promise<void> {
logger.info('Reinitializing OpenCode bin directory')
await this.initializeOpencodeBinDirectory()
}
async checkHealth(): Promise<boolean> {
if (!this.openCodeClient) {
return false
}
try {
const response = await this.openCodeClient.forward({
method: 'GET',
path: '/global/health',
await this.openCodeClient.api.server.info({
signal: AbortSignal.timeout(ENV.TIMEOUTS.HEALTH_CHECK_TIMEOUT_MS),
})
return response.ok
return true
} catch {
return false
}
@@ -1110,9 +913,9 @@ class OpenCodeServerManager {
try {
const executable = resolveOpenCodeExecutable() ?? 'opencode'
const result = spawnSync(executable, ['--version'], { encoding: 'utf8' })
const match = `${result.stdout ?? ''}${result.stderr ?? ''}`.match(/(\d+\.\d+\.\d+)/)
if (match && match[1]) {
this.version = match[1]
const version = parseOpenCodeVersionOutput(`${result.stdout ?? ''}${result.stderr ?? ''}`)
if (version) {
this.version = version
return this.version
}
} catch (error) {
@@ -1160,15 +963,14 @@ class OpenCodeServerManager {
private async terminateAndConfirm(
pid: number,
groupTarget: number | null,
graceMs: number,
context: string,
failurePhrase: string,
): Promise<void> {
this.signalProcessOrGroup(pid, groupTarget, 'SIGTERM')
const exited = await this.waitForProcessOrGroupExit(pid, groupTarget, graceMs)
const exited = await this.waitForProcessOrGroupExit(pid, groupTarget, PROCESS_SIGTERM_GRACE_MS)
if (exited) return
this.signalProcessOrGroup(pid, groupTarget, 'SIGKILL')
const killed = await this.waitForProcessOrGroupExit(pid, groupTarget, graceMs)
const killed = await this.waitForProcessOrGroupExit(pid, groupTarget, PROCESS_SIGKILL_CONFIRM_MS)
if (!killed) {
const message = `${context} (PID ${pid}${groupTarget !== null ? `, process group ${groupTarget}` : ''}) ${failurePhrase}`
this.lastStartupError = message
@@ -1177,7 +979,7 @@ class OpenCodeServerManager {
}
}
private async terminatePortOwners(processes: Array<{pid: number}>, graceMs: number): Promise<void> {
private async terminatePortOwners(processes: Array<{pid: number}>): Promise<void> {
const targets = processes.map((proc) => {
const pgid = readProcessGroupId(proc.pid)
return { pid: proc.pid, groupTarget: pgid !== null && pgid === proc.pid ? proc.pid : null }
@@ -1187,7 +989,7 @@ class OpenCodeServerManager {
}
const survivors: number[] = []
for (const target of targets) {
const exited = await this.waitForProcessOrGroupExit(target.pid, target.groupTarget, graceMs)
const exited = await this.waitForProcessOrGroupExit(target.pid, target.groupTarget, PROCESS_SIGKILL_CONFIRM_MS)
if (!exited) {
survivors.push(target.pid)
}
@@ -1229,7 +1031,7 @@ class OpenCodeServerManager {
return { pid, groupTarget, pidAttested, groupAttested }
}
private async terminateAttestedPredecessor(graceMs: number): Promise<void> {
private async terminateAttestedPredecessor(): Promise<void> {
const marker = await readChildStateMarker()
if (marker === null) return
const target = this.resolveAttestedProcessTarget(marker)
@@ -1249,13 +1051,12 @@ class OpenCodeServerManager {
await this.terminateAndConfirm(
target.pid,
target.groupTarget,
graceMs,
'Previous OpenCode server process',
'retained live processes after SIGTERM and SIGKILL; refusing to start an enforced server while host-executed processes may survive',
)
}
private async reconcileExitedChildMarker(graceMs: number): Promise<void> {
private async reconcileExitedChildMarker(): Promise<void> {
this.isHealthy = false
this.stopChildStateMarkerRefresh()
const marker = await readChildStateMarker()
@@ -1268,7 +1069,6 @@ class OpenCodeServerManager {
await this.terminateAndConfirm(
target.pid,
target.groupTarget,
graceMs,
'OpenCode server',
'retained live processes after SIGTERM and SIGKILL; refusing to complete the stop while host-executed processes may survive',
)
@@ -1290,7 +1090,6 @@ class OpenCodeServerManager {
await this.terminateAndConfirm(
target.pid,
target.groupTarget,
graceMs,
'Previous OpenCode server process group',
'retained live processes after SIGTERM and SIGKILL; refusing to replace the child state marker while host-executed processes may survive',
)