mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
feat(sandbox): add KVM-backed agent sandboxing via microsandbox (#338)
* feat(sandbox): add KVM-backed agent sandboxing via microsandbox * feat(sandbox): route host-shell surfaces into microVM via shell wrapper * feat(sandbox): route host-shell surfaces into microVM via shell wrapper * fix(sandbox): harden enforcement validation and backup handling * fix(sandbox): bound lifecycle queue and harden install/backup paths Bound the OpenCode supervisor lifecycle queue to one running plus one pending operation so repeated restarts cannot stack unbounded HTTP requests, while exempting stop() so shutdown is never dropped. Reject enforcement backups that carry no recoverable removed sections, matching the existing fail-closed handling of unparseable backups. Install OpenCode through a private mktemp staging directory instead of the predictable /tmp/opencode path. Use named path/os imports in the files added by this branch. * refactor(sandbox): remove OpenCode version allowlist gating under enforcement * fix(settings): use resolved opencode binary and verify installed version * refactor(sandbox): scope enforcement to agent bash tool only * fix(sandbox): plan bash against factory directory and attest runtime tmpfs; align permission reply API * fix(sandbox): pin neutral entrypoint and persist opencode upgrades across rebuilds * fix(sandbox): align canonical spec with msb 0.6.8 runtime defaults * feat(sandbox): show unwrapped sandboxed bash commands in message UI * refactor(sandbox): pin shell shim to sandbox agent bash without rewriting commands * feat(sandbox): route notifications through a host-side manager tool * feat(sandbox): route all assistant capabilities through the ocm tool Add an allow-listed request action to the generated ocm plugin so agents reach settings, assistant reload, repos, git-info, workspaces, and schedules through the tool instead of curling the internal API with a bearer token, which is impossible under sandboxing. Rewrite the curl-based skills to use the ocm request action and drop the apiBaseUrl plumbing. Remove the now-unread .opencode/internal-token file and the sandbox tmpfs mask that hid it; attestation now rejects any tmpfs other than the runtime /tmp mount. * fix(sidebar): wire new-session and new-schedule actions to every page AssistantRedirect never registered a listener for the sidebar's new-session event, so the desktop sidebar CTA on /assistant was a no-op; the Schedules pages had the same gap for new-schedule. Make useSidebarAction the single source of truth for action keys and event dispatch, and warn when an action is dispatched with no mounted handler so an unhandled CTA fails loudly instead of silently. Wire the missing listeners to the existing per-page handlers. * feat(sandbox): forward git credentials into the microVM and add sandbox guest image * feat(sandbox): add git credential forwarding toggle to settings
This commit is contained in:
1 parent
411fee52f3
commit
90a3c29c12
122 files changed
+16946
-883
No files matched your search
@@ -1,6 +1,7 @@
|
||||
import { spawn, execSync, spawnSync } from 'child_process'
|
||||
import path from 'path'
|
||||
import { promises as fs } from 'fs'
|
||||
import os from 'os'
|
||||
import { promises as fs, accessSync, constants } from 'fs'
|
||||
import { logger } from '../utils/logger'
|
||||
import { createGitIdentityEnv, resolveGitIdentity } from '../utils/git-auth'
|
||||
import {
|
||||
@@ -24,9 +25,12 @@ import { patchConfigWithRecovery } from './opencode/config-recovery'
|
||||
import type { OpenCodeClient } from './opencode/client'
|
||||
import { writeFileContent } from './file-operations'
|
||||
import { getOrCreateInternalToken } from './internal-token'
|
||||
import { installGhEnvPlugin } from './opencode-gh-env-plugin'
|
||||
import { installManagedPlugins } from './opencode/plugin-registry'
|
||||
import { getOpenCodePluginDiscoveryHome, restoreQuarantinedOpenCodePlugins } from './opencode-plugin-quarantine'
|
||||
import { resolveProcessIdentityProvider } from './opencode/process-identity'
|
||||
import { SandboxRuntimeService } from './sandbox/runtime'
|
||||
import { CredentialProvider } from './credential-provider'
|
||||
import { mkdirSafe } from '../utils/fs-safe'
|
||||
import { mkdirSafe, writeFileAtomic } from '../utils/fs-safe'
|
||||
|
||||
|
||||
const MIN_OPENCODE_VERSION = '1.0.137'
|
||||
@@ -34,6 +38,7 @@ const MAX_STDERR_SIZE = 10240
|
||||
const PLUGIN_INSTALL_TIMEOUT_MS = 120000
|
||||
const PROCESS_EXIT_GRACE_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 = {
|
||||
@@ -56,6 +61,20 @@ export class ConfigReloadError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export class NonRecoverableStartupError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message)
|
||||
this.name = 'NonRecoverableStartupError'
|
||||
}
|
||||
}
|
||||
|
||||
export class OpenCodeOperationBusyError extends Error {
|
||||
constructor() {
|
||||
super('Another OpenCode server operation is already in progress; refusing to treat a contended transition as completed')
|
||||
this.name = 'OpenCodeOperationBusyError'
|
||||
}
|
||||
}
|
||||
|
||||
function parseStartupValidationIssues(stderrOutput: string): StartupValidationIssue[] {
|
||||
const match = stderrOutput.match(/ZodError:\s*(\[[\s\S]*?\])(?:\n\s+at |$)/)
|
||||
if (!match?.[1]) {
|
||||
@@ -102,6 +121,159 @@ 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> = {
|
||||
MSB_BACKEND: process.env.MSB_BACKEND ?? 'local',
|
||||
MSB_HOME: process.env.MSB_HOME ?? path.join(process.env.HOME ?? os.homedir(), '.microsandbox'),
|
||||
MSB_PATH: ENV.SANDBOX?.MSB_PATH ?? process.env.MSB_PATH ?? 'msb',
|
||||
}
|
||||
if (process.env.MSB_LIBKRUNFW_PATH) env.MSB_LIBKRUNFW_PATH = process.env.MSB_LIBKRUNFW_PATH
|
||||
if (process.env.MSB_PROFILE) env.MSB_PROFILE = process.env.MSB_PROFILE
|
||||
if (process.env.MSB_API_URL) env.MSB_API_URL = process.env.MSB_API_URL
|
||||
if (process.env.MSB_API_KEY) env.MSB_API_KEY = process.env.MSB_API_KEY
|
||||
return env
|
||||
}
|
||||
|
||||
function readProcessGroupId(pid: number): number | null {
|
||||
return resolveProcessIdentityProvider().readProcessStat(pid)?.pgrp ?? null
|
||||
}
|
||||
|
||||
function processGroupExists(pgid: number): boolean {
|
||||
try {
|
||||
process.kill(-pgid, 0)
|
||||
return true
|
||||
} catch (error) {
|
||||
const errorCode = error && typeof error === 'object' && 'code' in error ? (error as { code: string }).code : ''
|
||||
return errorCode !== 'ESRCH'
|
||||
}
|
||||
}
|
||||
|
||||
const CHILD_STATE_MARKER_FILENAME = 'opencode-server-child.json'
|
||||
const getChildStateMarkerPath = () => path.join(getOpenCodeServerDirectory(), '.opencode', 'state', CHILD_STATE_MARKER_FILENAME)
|
||||
const RESTART_GENERATION_KEY = 'opencode_restart_generation'
|
||||
|
||||
type ChildStateMarker = {
|
||||
pid: number
|
||||
pgid: number | null
|
||||
enforced: boolean
|
||||
startToken: string
|
||||
generation: number
|
||||
groupMembers: Array<{ pid: number; startToken: string }>
|
||||
}
|
||||
|
||||
function readProcessStartToken(pid: number): string | null {
|
||||
return resolveProcessIdentityProvider().readProcessStat(pid)?.startToken ?? null
|
||||
}
|
||||
|
||||
async function readProcessStartTokenWithRetry(pid: number): Promise<string | null> {
|
||||
for (let attempt = 0; attempt < 3; attempt++) {
|
||||
const token = readProcessStartToken(pid)
|
||||
if (token !== null) return token
|
||||
await new Promise((resolve) => setTimeout(resolve, 50))
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
async function readProcessGroupIdWithRetry(pid: number): Promise<number | null> {
|
||||
for (let attempt = 0; attempt < 3; attempt++) {
|
||||
const pgid = readProcessGroupId(pid)
|
||||
if (pgid !== null) return pgid
|
||||
await new Promise((resolve) => setTimeout(resolve, 50))
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function readDurableRestartGeneration(db: Database | null): number {
|
||||
if (!db) return 0
|
||||
try {
|
||||
const row = db.prepare('SELECT value FROM app_secrets WHERE key = ?').get(RESTART_GENERATION_KEY) as { value: string } | undefined
|
||||
if (row === undefined) return 0
|
||||
const parsed = Number(row.value)
|
||||
return Number.isFinite(parsed) && parsed >= 0 ? Math.floor(parsed) : 0
|
||||
} catch {
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
function advanceDurableRestartGeneration(db: Database | null): void {
|
||||
if (!db) return
|
||||
const next = readDurableRestartGeneration(db) + 1
|
||||
const now = Date.now()
|
||||
try {
|
||||
db.prepare(`
|
||||
INSERT INTO app_secrets (key, value, created_at, updated_at) VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at
|
||||
`).run(RESTART_GENERATION_KEY, String(next), now, now)
|
||||
} catch (error) {
|
||||
logger.warn('Failed to persist the OpenCode restart generation:', error)
|
||||
}
|
||||
}
|
||||
|
||||
async function writeChildStateMarker(marker: ChildStateMarker): Promise<void> {
|
||||
await writeFileAtomic(getChildStateMarkerPath(), JSON.stringify(marker, null, 2))
|
||||
}
|
||||
|
||||
async function readChildStateMarker(): Promise<ChildStateMarker | null> {
|
||||
try {
|
||||
const parsed = JSON.parse(await fs.readFile(getChildStateMarkerPath(), 'utf-8')) as Record<string, unknown>
|
||||
if (
|
||||
typeof parsed.pid === 'number' &&
|
||||
typeof parsed.enforced === 'boolean' &&
|
||||
typeof parsed.startToken === 'string' &&
|
||||
typeof parsed.generation === 'number'
|
||||
) {
|
||||
const pgid = typeof parsed.pgid === 'number' && parsed.pgid > 0 ? parsed.pgid : null
|
||||
const groupMembers = Array.isArray(parsed.groupMembers)
|
||||
? parsed.groupMembers.filter(
|
||||
(member): member is { pid: number; startToken: string } =>
|
||||
member !== null &&
|
||||
typeof member === 'object' &&
|
||||
!Array.isArray(member) &&
|
||||
typeof (member as { pid?: unknown }).pid === 'number' &&
|
||||
typeof (member as { startToken?: unknown }).startToken === 'string',
|
||||
)
|
||||
: []
|
||||
return {
|
||||
pid: parsed.pid,
|
||||
pgid,
|
||||
enforced: parsed.enforced,
|
||||
startToken: parsed.startToken,
|
||||
generation: parsed.generation,
|
||||
groupMembers,
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
async function removeChildStateMarker(): Promise<void> {
|
||||
try {
|
||||
await fs.rm(getChildStateMarkerPath(), { force: true })
|
||||
} catch (error) {
|
||||
logger.warn('Failed to remove the OpenCode child state marker:', error)
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveOpenCodeExecutable(): string | null {
|
||||
const candidates = [
|
||||
process.env.OPENCODE_BIN,
|
||||
path.join(getOpenCodePluginDiscoveryHome(), '.opencode', 'bin', 'opencode'),
|
||||
'/usr/local/bin/opencode',
|
||||
'/opt/opencode/bin/opencode',
|
||||
].filter((candidate): candidate is string => typeof candidate === 'string' && candidate.length > 0)
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
accessSync(candidate, constants.X_OK)
|
||||
return candidate
|
||||
} catch {
|
||||
// try the next candidate
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
class OpenCodeServerManager {
|
||||
private static instance: OpenCodeServerManager
|
||||
private serverProcess: ReturnType<typeof spawn> | null = null
|
||||
@@ -110,9 +282,14 @@ class OpenCodeServerManager {
|
||||
private db: Database | null = null
|
||||
private version: string | null = null
|
||||
private lastStartupError: string | null = null
|
||||
private lastStartupErrorNonRecoverable = false
|
||||
private restartPending: boolean = false
|
||||
private restartPendingGeneration: number = 0
|
||||
private opInProgress: boolean = false
|
||||
private openCodeClient: OpenCodeClient | null = null
|
||||
private sandboxEnforced: boolean = false
|
||||
private lifecycleInitialized: boolean = false
|
||||
private markerRefreshTimer: ReturnType<typeof setInterval> | null = null
|
||||
|
||||
private constructor() {}
|
||||
|
||||
@@ -127,7 +304,11 @@ class OpenCodeServerManager {
|
||||
async rebuildClient(): Promise<void> {
|
||||
const password = this.getResolvedPassword()
|
||||
const { createOpenCodeClient } = await import('./opencode/client')
|
||||
this.openCodeClient = createOpenCodeClient(password)
|
||||
this.openCodeClient = createOpenCodeClient(password, getOpenCodeServerHost())
|
||||
}
|
||||
|
||||
getEffectiveServerHost(): string {
|
||||
return getOpenCodeServerHost()
|
||||
}
|
||||
|
||||
private getResolvedPassword(): string {
|
||||
@@ -157,6 +338,10 @@ class OpenCodeServerManager {
|
||||
* Should only be used in test setup/teardown.
|
||||
*/
|
||||
static resetInstance(): void {
|
||||
const instance = OpenCodeServerManager.instance
|
||||
if (instance) {
|
||||
instance.stopChildStateMarkerRefresh()
|
||||
}
|
||||
OpenCodeServerManager.instance = null as unknown as OpenCodeServerManager
|
||||
}
|
||||
|
||||
@@ -182,18 +367,56 @@ class OpenCodeServerManager {
|
||||
async start(retryAfterPluginInstall = true, allowNested = false): Promise<void> {
|
||||
const acquired = this.acquireOp()
|
||||
if (!acquired && !allowNested) {
|
||||
return
|
||||
throw new OpenCodeOperationBusyError()
|
||||
}
|
||||
|
||||
try {
|
||||
const restartGenerationAtStart = this.restartPendingGeneration
|
||||
if (this.isHealthy) {
|
||||
logger.info('OpenCode server already running and healthy')
|
||||
return
|
||||
}
|
||||
|
||||
await this.rebuildClient()
|
||||
|
||||
const isDevelopment = ENV.SERVER.NODE_ENV !== 'production'
|
||||
let sandboxEnforced = false
|
||||
if (this.db) {
|
||||
try {
|
||||
sandboxEnforced = new SandboxRuntimeService(this.db).isEnabled()
|
||||
} catch (error) {
|
||||
sandboxEnforced = true
|
||||
this.sandboxEnforced = true
|
||||
const message = `Failed to determine sandbox enforcement state: ${error instanceof Error ? error.message : String(error)}`
|
||||
let existingProcesses: Array<{pid: number}> = []
|
||||
try {
|
||||
existingProcesses = await this.findProcessesByPort(getOpenCodeServerPort())
|
||||
} catch (inspectionError) {
|
||||
this.failNonRecoverable(
|
||||
`${message}; port-owner inspection failed: ${inspectionError instanceof Error ? inspectionError.message : String(inspectionError)}`,
|
||||
)
|
||||
}
|
||||
try {
|
||||
await this.terminateAttestedPredecessor(PROCESS_EXIT_GRACE_MS)
|
||||
if (existingProcesses.length > 0) {
|
||||
await this.terminatePortOwners(existingProcesses, PROCESS_EXIT_GRACE_MS)
|
||||
}
|
||||
} catch (cleanupError) {
|
||||
this.failNonRecoverable(
|
||||
`${message}; the previous OpenCode server could not be proven terminated and may still be reachable: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`,
|
||||
)
|
||||
}
|
||||
this.failNonRecoverable(message)
|
||||
}
|
||||
if (!sandboxEnforced && this.sandboxEnforced) {
|
||||
try {
|
||||
await new SandboxRuntimeService(this.db).stopWorkspaceSandboxForToggle()
|
||||
logger.info('Sandbox enforcement disabled: stopped the shared workspace microVM')
|
||||
} catch (error) {
|
||||
this.failNonRecoverable(`Failed to stop the workspace sandbox while disabling enforcement: ${error instanceof Error ? error.message : String(error)}`)
|
||||
}
|
||||
}
|
||||
logger.info(`OpenCode sandbox enforcement: ${sandboxEnforced ? 'enabled' : 'disabled'}`)
|
||||
}
|
||||
|
||||
const password = this.getResolvedPassword()
|
||||
const openCodeServerHost = getOpenCodeServerHost()
|
||||
const isExposed = openCodeServerHost !== '127.0.0.1' && openCodeServerHost !== 'localhost'
|
||||
@@ -223,7 +446,11 @@ class OpenCodeServerManager {
|
||||
rawEnvVars
|
||||
.filter(({ key }) => {
|
||||
const normalizedKey = key.trim()
|
||||
return normalizedKey !== '' && !(BLOCKED_SERVER_ENV_KEYS as readonly string[]).includes(normalizedKey)
|
||||
return (
|
||||
normalizedKey !== '' &&
|
||||
!(BLOCKED_SERVER_ENV_KEYS as readonly string[]).includes(normalizedKey) &&
|
||||
!normalizedKey.startsWith('MSB_')
|
||||
)
|
||||
})
|
||||
.map(({ key, value }) => [key.trim(), value])
|
||||
)
|
||||
@@ -240,42 +467,68 @@ class OpenCodeServerManager {
|
||||
}
|
||||
}
|
||||
|
||||
this.sandboxEnforced = sandboxEnforced
|
||||
if (sandboxEnforced && !resolveProcessIdentityProvider().attested) {
|
||||
this.failNonRecoverable(
|
||||
'Sandbox enforcement requires process identity attestation, which is unavailable on this platform; refusing to run an enforced server',
|
||||
)
|
||||
}
|
||||
await this.rebuildClient()
|
||||
const durableRestartGeneration = readDurableRestartGeneration(this.db)
|
||||
|
||||
const openCodeServerPort = getOpenCodeServerPort()
|
||||
const existingProcesses = await this.findProcessesByPort(openCodeServerPort)
|
||||
if (existingProcesses.length > 0) {
|
||||
let existingProcesses: Array<{pid: number}> = []
|
||||
try {
|
||||
existingProcesses = await this.findProcessesByPort(openCodeServerPort)
|
||||
} catch (inspectionError) {
|
||||
const inspectionMessage = `Cannot inspect port ${openCodeServerPort} ownership: ${inspectionError instanceof Error ? inspectionError.message : String(inspectionError)}`
|
||||
if (sandboxEnforced) {
|
||||
this.failNonRecoverable(inspectionMessage)
|
||||
}
|
||||
logger.warn(inspectionMessage)
|
||||
}
|
||||
let replacingExistingServer = false
|
||||
if (sandboxEnforced) {
|
||||
await this.terminateAttestedPredecessor(PROCESS_EXIT_GRACE_MS)
|
||||
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)
|
||||
replacingExistingServer = true
|
||||
}
|
||||
} else if (existingProcesses.length > 0) {
|
||||
logger.info(`OpenCode server already running on port ${openCodeServerPort}`)
|
||||
const healthy = await this.checkHealth()
|
||||
if (healthy) {
|
||||
if (isDevelopment) {
|
||||
logger.warn('Development mode: Killing existing server for hot reload')
|
||||
for (const proc of existingProcesses) {
|
||||
try {
|
||||
process.kill(proc.pid, 'SIGKILL')
|
||||
} catch (error) {
|
||||
logger.warn(`Failed to kill process ${proc.pid}:`, error)
|
||||
}
|
||||
}
|
||||
await new Promise(r => setTimeout(r, 2000))
|
||||
await this.terminatePortOwners(existingProcesses, PROCESS_EXIT_GRACE_MS)
|
||||
replacingExistingServer = true
|
||||
} else {
|
||||
this.isHealthy = true
|
||||
if (existingProcesses[0]) {
|
||||
this.serverPid = existingProcesses[0].pid
|
||||
const childState = await readChildStateMarker()
|
||||
const attestedUnenforced = childState !== null
|
||||
&& childState.enforced === false
|
||||
&& childState.generation === durableRestartGeneration
|
||||
&& childState.startToken !== ''
|
||||
&& childState.startToken === readProcessStartToken(childState.pid)
|
||||
&& existingProcesses.some((proc) => proc.pid === childState.pid)
|
||||
if (attestedUnenforced) {
|
||||
this.isHealthy = true
|
||||
this.serverPid = childState.pid
|
||||
return
|
||||
}
|
||||
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)
|
||||
replacingExistingServer = true
|
||||
}
|
||||
} else {
|
||||
logger.warn('Killing unhealthy OpenCode server')
|
||||
for (const proc of existingProcesses) {
|
||||
try {
|
||||
process.kill(proc.pid, 'SIGKILL')
|
||||
} catch (error) {
|
||||
logger.warn(`Failed to kill process ${proc.pid}:`, error)
|
||||
}
|
||||
}
|
||||
await new Promise(r => setTimeout(r, 1000))
|
||||
await this.terminatePortOwners(existingProcesses, PROCESS_EXIT_GRACE_MS)
|
||||
replacingExistingServer = true
|
||||
}
|
||||
}
|
||||
|
||||
await this.reconcileExitedChildMarker(PROCESS_EXIT_GRACE_MS)
|
||||
|
||||
const openCodeServerDirectory = getOpenCodeServerDirectory()
|
||||
const openCodeConfigPath = getOpenCodeConfigPath()
|
||||
logger.info(`OpenCode server working directory: ${openCodeServerDirectory}`)
|
||||
@@ -330,22 +583,42 @@ class OpenCodeServerManager {
|
||||
logger.info(`OpenCode server GIT_SSH_COMMAND: ${gitSshCommand}`)
|
||||
|
||||
await this.initializeOpencodeBinDirectory()
|
||||
await installGhEnvPlugin(path.join(openCodeServerDirectory, '.config'))
|
||||
const pluginConfigHome = path.join(openCodeServerDirectory, '.config')
|
||||
try {
|
||||
await restoreQuarantinedOpenCodePlugins(pluginConfigHome, openCodeConfigPath)
|
||||
} catch (error) {
|
||||
this.failNonRecoverable(
|
||||
`Failed to restore legacy quarantined OpenCode plugins before startup: ${error instanceof Error ? error.message : String(error)}`,
|
||||
)
|
||||
}
|
||||
try {
|
||||
await installManagedPlugins(pluginConfigHome)
|
||||
} catch (error) {
|
||||
if (sandboxEnforced) {
|
||||
logger.error('Failed to install a generated OpenCode plugin; refusing to start an enforced server', error)
|
||||
this.failNonRecoverable(error instanceof Error ? error.message : String(error))
|
||||
}
|
||||
logger.warn('Failed to install a generated OpenCode plugin (sandboxing is disabled):', error)
|
||||
}
|
||||
const configuredPlugins = await this.getConfiguredPlugins(openCodeConfigPath)
|
||||
await this.installConfiguredPlugins(configuredPlugins)
|
||||
const configuredPluginCount = configuredPlugins.length
|
||||
const openCodeExecutable = resolveOpenCodeExecutable() ?? 'opencode'
|
||||
|
||||
let stderrOutput = ''
|
||||
|
||||
const microsandboxEnv = resolveManagerMicrosandboxEnv()
|
||||
|
||||
const cleanEnv = { ...process.env }
|
||||
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
|
||||
|
||||
this.serverProcess = spawn(
|
||||
'opencode',
|
||||
openCodeExecutable,
|
||||
['serve', '--port', openCodeServerPort.toString(), '--hostname', openCodeServerHost],
|
||||
{
|
||||
cwd: openCodeServerDirectory,
|
||||
@@ -354,6 +627,7 @@ class OpenCodeServerManager {
|
||||
env: {
|
||||
...cleanEnv,
|
||||
...userEnvVars,
|
||||
...microsandboxEnv,
|
||||
...gitEnv,
|
||||
...gitIdentityEnv,
|
||||
...(this.db
|
||||
@@ -362,6 +636,8 @@ class OpenCodeServerManager {
|
||||
OCM_INTERNAL_TOKEN: getOrCreateInternalToken(this.db),
|
||||
}
|
||||
: {}),
|
||||
OCM_SANDBOX_ENFORCED: sandboxEnforced ? 'true' : 'false',
|
||||
OPENCODE_PURE: 'false',
|
||||
GIT_SSH_COMMAND: gitSshCommand,
|
||||
XDG_DATA_HOME: path.join(openCodeServerDirectory, '.opencode/state'),
|
||||
XDG_STATE_HOME: path.join(openCodeServerDirectory, '.opencode/state'),
|
||||
@@ -387,7 +663,13 @@ class OpenCodeServerManager {
|
||||
})
|
||||
}
|
||||
|
||||
const spawnedServerPid = this.serverProcess.pid
|
||||
this.serverProcess.on('exit', (code, signal) => {
|
||||
if (spawnedServerPid !== undefined && this.serverPid === spawnedServerPid) {
|
||||
this.serverPid = null
|
||||
this.isHealthy = false
|
||||
this.stopChildStateMarkerRefresh()
|
||||
}
|
||||
if (code !== null && code !== 0) {
|
||||
const fallback = `Server exited with code ${code}${stderrOutput ? `: ${stderrOutput.slice(-500)}` : ''}`
|
||||
this.lastStartupError = formatStartupError(stderrOutput, fallback)
|
||||
@@ -399,6 +681,43 @@ class OpenCodeServerManager {
|
||||
})
|
||||
|
||||
this.serverPid = this.serverProcess.pid ?? null
|
||||
if (this.serverPid !== null) {
|
||||
if (!isDevelopment) {
|
||||
if (!resolveProcessIdentityProvider().attested) {
|
||||
logger.warn('Process identity attestation is unavailable on this platform; tracking the OpenCode server as a direct child without PID-reuse attestation')
|
||||
} else {
|
||||
const startToken = await readProcessStartTokenWithRetry(this.serverPid)
|
||||
if (startToken === null) {
|
||||
const message = 'Failed to read the process identity of the freshly spawned OpenCode server; refusing to detach an unattestable child'
|
||||
this.lastStartupError = message
|
||||
logger.error(message)
|
||||
await this.stop(true)
|
||||
throw new Error(message)
|
||||
}
|
||||
try {
|
||||
const processGroup = await readProcessGroupIdWithRetry(this.serverPid)
|
||||
const groupMembers = processGroup !== null && processGroup === this.serverPid
|
||||
? resolveProcessIdentityProvider().readProcessGroupMembers(processGroup)
|
||||
: []
|
||||
await writeChildStateMarker({
|
||||
pid: this.serverPid,
|
||||
pgid: processGroup !== null && processGroup === this.serverPid ? processGroup : null,
|
||||
enforced: sandboxEnforced,
|
||||
startToken,
|
||||
generation: durableRestartGeneration,
|
||||
groupMembers,
|
||||
})
|
||||
} catch (error) {
|
||||
const message = `Failed to persist the OpenCode child state marker: ${error instanceof Error ? error.message : String(error)}`
|
||||
this.lastStartupError = message
|
||||
logger.error(message)
|
||||
await this.stop(true)
|
||||
throw new Error(message)
|
||||
}
|
||||
this.startChildStateMarkerRefresh()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logger.info(`OpenCode server started with PID ${this.serverPid}`)
|
||||
|
||||
@@ -417,8 +736,31 @@ class OpenCodeServerManager {
|
||||
throw new Error('OpenCode server failed to become healthy')
|
||||
}
|
||||
|
||||
if (sandboxEnforced || replacingExistingServer) {
|
||||
let portOwners: Array<{pid: number}> = []
|
||||
try {
|
||||
portOwners = await this.findProcessesByPort(openCodeServerPort)
|
||||
} catch (inspectionError) {
|
||||
const message = `Could not verify port ${openCodeServerPort} ownership after health; refusing to mark the server healthy: ${inspectionError instanceof Error ? inspectionError.message : String(inspectionError)}`
|
||||
this.lastStartupError = message
|
||||
logger.error(message)
|
||||
await this.stop(true)
|
||||
throw new Error(message)
|
||||
}
|
||||
if (this.serverPid === null || !portOwners.some((proc) => proc.pid === this.serverPid)) {
|
||||
const owners = portOwners.length > 0 ? `; port ${openCodeServerPort} is owned by PID(s) ${portOwners.map((proc) => proc.pid).join(', ')}` : `; no process owns port ${openCodeServerPort}`
|
||||
const message = `The newly started OpenCode server (PID ${this.serverPid ?? 'unknown'}) does not own the OpenCode port${owners}; refusing to mark the server healthy`
|
||||
this.lastStartupError = message
|
||||
logger.error(message)
|
||||
await this.stop(true)
|
||||
throw new Error(message)
|
||||
}
|
||||
}
|
||||
|
||||
this.isHealthy = true
|
||||
this.restartPending = false
|
||||
if (this.restartPendingGeneration === restartGenerationAtStart) {
|
||||
this.restartPending = false
|
||||
}
|
||||
logger.info('OpenCode server is healthy')
|
||||
|
||||
await this.fetchVersion()
|
||||
@@ -441,37 +783,58 @@ class OpenCodeServerManager {
|
||||
}
|
||||
|
||||
try {
|
||||
if (!this.serverPid) return
|
||||
if (!this.serverPid) {
|
||||
await this.reconcileExitedChildMarker(PROCESS_EXIT_GRACE_MS)
|
||||
return
|
||||
}
|
||||
|
||||
logger.info('Stopping OpenCode server')
|
||||
try {
|
||||
process.kill(this.serverPid, 'SIGTERM')
|
||||
} catch (error) {
|
||||
const errorCode = error && typeof error === 'object' && 'code' in error ? (error as { code: string }).code : ''
|
||||
if (errorCode === 'ESRCH') {
|
||||
logger.debug(`Process ${this.serverPid} already stopped`)
|
||||
} else {
|
||||
logger.warn(`Failed to send SIGTERM to ${this.serverPid}:`, error)
|
||||
const pid = this.serverPid
|
||||
const marker = await readChildStateMarker()
|
||||
let groupTarget: number | null = null
|
||||
|
||||
if (marker !== null && marker.pid === pid) {
|
||||
const target = this.resolveAttestedProcessTarget(marker)
|
||||
if (!target.pidAttested && !target.groupAttested) {
|
||||
this.isHealthy = false
|
||||
logger.warn(
|
||||
`Refusing to signal PID ${pid}: its process identity no longer matches the attested child state marker; the tracked child has exited and its PID may have been reused`,
|
||||
)
|
||||
return
|
||||
}
|
||||
groupTarget = target.groupTarget
|
||||
} else if (marker !== null) {
|
||||
this.isHealthy = false
|
||||
logger.warn(`Refusing to signal PID ${pid}: it does not match the child state marker PID ${marker.pid}`)
|
||||
return
|
||||
} else {
|
||||
const pgid = readProcessGroupId(pid)
|
||||
if (pgid !== null && pgid === pid) {
|
||||
groupTarget = pid
|
||||
}
|
||||
}
|
||||
|
||||
const exited = await this.waitForProcessExit(this.serverPid, PROCESS_EXIT_GRACE_MS)
|
||||
|
||||
if (!exited) {
|
||||
try {
|
||||
process.kill(this.serverPid, 'SIGKILL')
|
||||
} catch (error) {
|
||||
const errorCode = error && typeof error === 'object' && 'code' in error ? (error as { code: string }).code : ''
|
||||
if (errorCode === 'ESRCH') {
|
||||
logger.debug(`Process ${this.serverPid} already stopped`)
|
||||
} else {
|
||||
logger.warn(`Failed to send SIGKILL to ${this.serverPid}:`, error)
|
||||
}
|
||||
}
|
||||
if (groupTarget !== null) {
|
||||
logger.info(`Terminating OpenCode process group ${groupTarget} so host-executed descendants do not survive the stop`)
|
||||
}
|
||||
try {
|
||||
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',
|
||||
)
|
||||
} catch (error) {
|
||||
this.isHealthy = false
|
||||
throw error
|
||||
}
|
||||
|
||||
this.serverPid = null
|
||||
this.isHealthy = false
|
||||
this.stopChildStateMarkerRefresh()
|
||||
|
||||
await removeChildStateMarker()
|
||||
|
||||
try {
|
||||
await cleanupPersistentSSHKeys()
|
||||
@@ -627,7 +990,7 @@ class OpenCodeServerManager {
|
||||
async restart(): Promise<void> {
|
||||
const acquired = this.acquireOp()
|
||||
if (!acquired) {
|
||||
return
|
||||
throw new OpenCodeOperationBusyError()
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -642,7 +1005,7 @@ class OpenCodeServerManager {
|
||||
async reloadConfig(): Promise<void> {
|
||||
const acquired = this.acquireOp()
|
||||
if (!acquired) {
|
||||
return
|
||||
throw new OpenCodeOperationBusyError()
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -653,7 +1016,8 @@ class OpenCodeServerManager {
|
||||
const fileConfig = parseJsonc(fileContent) as Record<string, unknown>
|
||||
logger.info(`Read config from file for reload: ${configPath}`)
|
||||
|
||||
const patchResult = await patchConfigWithRecovery(this.requireClient(), fileConfig)
|
||||
const patchTarget = fileConfig
|
||||
const patchResult = await patchConfigWithRecovery(this.requireClient(), patchTarget)
|
||||
if (!patchResult.success) {
|
||||
const errorMessage = patchResult.error || 'Failed to reload config'
|
||||
const validationIssues = patchResult.details || []
|
||||
@@ -709,16 +1073,42 @@ class OpenCodeServerManager {
|
||||
return this.lastStartupError
|
||||
}
|
||||
|
||||
isLastStartupErrorNonRecoverable(): boolean {
|
||||
return this.lastStartupErrorNonRecoverable
|
||||
}
|
||||
|
||||
clearStartupError(): void {
|
||||
this.lastStartupError = null
|
||||
this.lastStartupErrorNonRecoverable = false
|
||||
}
|
||||
|
||||
private failNonRecoverable(message: string): never {
|
||||
this.lastStartupError = message
|
||||
this.lastStartupErrorNonRecoverable = true
|
||||
logger.error(message)
|
||||
throw new NonRecoverableStartupError(message)
|
||||
}
|
||||
|
||||
isRestartPending(): boolean {
|
||||
return this.restartPending
|
||||
}
|
||||
|
||||
isSandboxEnforced(): boolean {
|
||||
return this.sandboxEnforced
|
||||
}
|
||||
|
||||
setLifecycleInitialized(initialized: boolean): void {
|
||||
this.lifecycleInitialized = initialized
|
||||
}
|
||||
|
||||
isLifecycleInitialized(): boolean {
|
||||
return this.lifecycleInitialized
|
||||
}
|
||||
|
||||
markRestartPending(): void {
|
||||
this.restartPending = true
|
||||
this.restartPendingGeneration += 1
|
||||
advanceDurableRestartGeneration(this.db)
|
||||
}
|
||||
|
||||
async reinitializeBinDirectory(): Promise<void> {
|
||||
@@ -744,8 +1134,9 @@ class OpenCodeServerManager {
|
||||
|
||||
async fetchVersion(): Promise<string | null> {
|
||||
try {
|
||||
const result = execSync('opencode --version 2>&1', { encoding: 'utf8' })
|
||||
const match = result.match(/(\d+\.\d+\.\d+)/)
|
||||
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]
|
||||
return this.version
|
||||
@@ -756,22 +1147,221 @@ class OpenCodeServerManager {
|
||||
return null
|
||||
}
|
||||
|
||||
private async waitForProcessExit(pid: number, timeoutMs: number): Promise<boolean> {
|
||||
private processExists(pid: number): boolean {
|
||||
try {
|
||||
process.kill(pid, 0)
|
||||
return true
|
||||
} catch (error) {
|
||||
const errorCode = error && typeof error === 'object' && 'code' in error ? (error as { code: string }).code : ''
|
||||
return errorCode !== 'ESRCH'
|
||||
}
|
||||
}
|
||||
|
||||
private signalProcessOrGroup(pid: number, groupTarget: number | null, signal: NodeJS.Signals): void {
|
||||
const target = groupTarget !== null ? -groupTarget : pid
|
||||
try {
|
||||
process.kill(target, signal)
|
||||
} catch (error) {
|
||||
const errorCode = error && typeof error === 'object' && 'code' in error ? (error as { code: string }).code : ''
|
||||
if (errorCode === 'ESRCH') {
|
||||
logger.debug(`Process ${pid} already stopped`)
|
||||
} else {
|
||||
logger.warn(`Failed to send ${signal} to ${groupTarget !== null ? `process group ${groupTarget}` : `process ${pid}`}:`, error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async waitForProcessOrGroupExit(pid: number, groupTarget: number | null, timeoutMs: number): Promise<boolean> {
|
||||
const start = Date.now()
|
||||
while (Date.now() - start < timeoutMs) {
|
||||
try {
|
||||
process.kill(pid, 0)
|
||||
} catch (error) {
|
||||
const errorCode = error && typeof error === 'object' && 'code' in error ? (error as { code: string }).code : ''
|
||||
if (errorCode === 'ESRCH') {
|
||||
return true
|
||||
}
|
||||
const alive = groupTarget !== null ? processGroupExists(groupTarget) : this.processExists(pid)
|
||||
if (!alive) {
|
||||
return true
|
||||
}
|
||||
await new Promise(r => setTimeout(r, PROCESS_EXIT_POLL_MS))
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
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)
|
||||
if (exited) return
|
||||
this.signalProcessOrGroup(pid, groupTarget, 'SIGKILL')
|
||||
const killed = await this.waitForProcessOrGroupExit(pid, groupTarget, graceMs)
|
||||
if (!killed) {
|
||||
const message = `${context} (PID ${pid}${groupTarget !== null ? `, process group ${groupTarget}` : ''}) ${failurePhrase}`
|
||||
this.lastStartupError = message
|
||||
logger.error(message)
|
||||
throw new Error(message)
|
||||
}
|
||||
}
|
||||
|
||||
private async terminatePortOwners(processes: Array<{pid: number}>, graceMs: 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 }
|
||||
})
|
||||
for (const target of targets) {
|
||||
this.signalProcessOrGroup(target.pid, target.groupTarget, 'SIGKILL')
|
||||
}
|
||||
const survivors: number[] = []
|
||||
for (const target of targets) {
|
||||
const exited = await this.waitForProcessOrGroupExit(target.pid, target.groupTarget, graceMs)
|
||||
if (!exited) {
|
||||
survivors.push(target.pid)
|
||||
}
|
||||
}
|
||||
if (survivors.length > 0) {
|
||||
const message = `Failed to terminate the existing OpenCode server process(es) on port ${getOpenCodeServerPort()}: PID(s) ${survivors.join(', ')} still own the port or retain live process-group members; refusing to spawn a new server`
|
||||
this.lastStartupError = message
|
||||
logger.error(message)
|
||||
throw new Error(message)
|
||||
}
|
||||
}
|
||||
|
||||
private resolveAttestedProcessTarget(marker: ChildStateMarker): {
|
||||
pid: number
|
||||
groupTarget: number | null
|
||||
pidAttested: boolean
|
||||
groupAttested: boolean
|
||||
} {
|
||||
const pid = marker.pid
|
||||
const pidAttested = marker.startToken !== '' && readProcessStartToken(pid) === marker.startToken
|
||||
let groupTarget: number | null = null
|
||||
let groupAttested = false
|
||||
if (pidAttested) {
|
||||
const livePgid = readProcessGroupId(pid)
|
||||
if (livePgid !== null && livePgid === pid) {
|
||||
groupTarget = pid
|
||||
}
|
||||
} else if (marker.pgid !== null) {
|
||||
const currentMembers = resolveProcessIdentityProvider().readProcessGroupMembers(marker.pgid)
|
||||
groupAttested = marker.groupMembers.length > 0 && currentMembers.some(
|
||||
(member) => marker.groupMembers.some(
|
||||
(recorded) => recorded.pid === member.pid && recorded.startToken === member.startToken,
|
||||
),
|
||||
)
|
||||
if (groupAttested) {
|
||||
groupTarget = marker.pgid
|
||||
}
|
||||
}
|
||||
return { pid, groupTarget, pidAttested, groupAttested }
|
||||
}
|
||||
|
||||
private async terminateAttestedPredecessor(graceMs: number): Promise<void> {
|
||||
const marker = await readChildStateMarker()
|
||||
if (marker === null) return
|
||||
const target = this.resolveAttestedProcessTarget(marker)
|
||||
if (!target.pidAttested && marker.pgid !== null) {
|
||||
const currentMembers = resolveProcessIdentityProvider().readProcessGroupMembers(marker.pgid)
|
||||
if (currentMembers.length > 0 && !target.groupAttested) {
|
||||
const message = `Previous OpenCode server process (PID ${marker.pid}) has exited but process group ${marker.pgid} still exists and cannot be proven to belong to it; refusing to signal an unverified process group before starting an enforced server`
|
||||
this.lastStartupError = message
|
||||
logger.error(message)
|
||||
throw new Error(message)
|
||||
}
|
||||
}
|
||||
const pidAlive = target.pidAttested
|
||||
const groupAlive = target.groupTarget !== null && processGroupExists(target.groupTarget)
|
||||
if (!pidAlive && !groupAlive) return
|
||||
logger.warn(`Sandbox enforcement enabled: terminating the previous OpenCode process group (leader PID ${marker.pid}) so host-executed descendants cannot survive`)
|
||||
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> {
|
||||
this.isHealthy = false
|
||||
this.stopChildStateMarkerRefresh()
|
||||
const marker = await readChildStateMarker()
|
||||
if (marker === null) {
|
||||
return
|
||||
}
|
||||
const target = this.resolveAttestedProcessTarget(marker)
|
||||
if (target.pidAttested) {
|
||||
logger.warn(`Stopping OpenCode server leader PID ${target.pid} that was attested by the child state marker but is no longer tracked`)
|
||||
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',
|
||||
)
|
||||
await removeChildStateMarker()
|
||||
return
|
||||
}
|
||||
if (marker.pgid !== null) {
|
||||
const currentMembers = resolveProcessIdentityProvider().readProcessGroupMembers(marker.pgid)
|
||||
if (currentMembers.length > 0) {
|
||||
if (!target.groupAttested || target.groupTarget === null) {
|
||||
const message = `Previous OpenCode server leader (PID ${marker.pid}) has exited but process group ${marker.pgid} still exists and cannot be proven to belong to it; refusing to replace the child state marker while live processes may survive`
|
||||
this.lastStartupError = message
|
||||
logger.error(message)
|
||||
throw new Error(message)
|
||||
}
|
||||
logger.warn(
|
||||
`Previous OpenCode server leader (PID ${marker.pid}) has exited; terminating its attested process group ${marker.pgid} so host-executed descendants do not survive`,
|
||||
)
|
||||
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',
|
||||
)
|
||||
}
|
||||
}
|
||||
await removeChildStateMarker()
|
||||
}
|
||||
|
||||
private startChildStateMarkerRefresh(): void {
|
||||
this.stopChildStateMarkerRefresh()
|
||||
this.markerRefreshTimer = setInterval(() => {
|
||||
void this.refreshChildStateMarkerMembers()
|
||||
}, CHILD_STATE_MARKER_REFRESH_MS)
|
||||
}
|
||||
|
||||
private stopChildStateMarkerRefresh(): void {
|
||||
if (this.markerRefreshTimer !== null) {
|
||||
clearInterval(this.markerRefreshTimer)
|
||||
this.markerRefreshTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
private async refreshChildStateMarkerMembers(): Promise<void> {
|
||||
try {
|
||||
const marker = await readChildStateMarker()
|
||||
if (marker === null || marker.pgid === null) return
|
||||
const leaderStat = resolveProcessIdentityProvider().readProcessStat(marker.pid)
|
||||
if (leaderStat === null || leaderStat.startToken !== marker.startToken || leaderStat.pgrp !== marker.pgid) {
|
||||
this.stopChildStateMarkerRefresh()
|
||||
return
|
||||
}
|
||||
const groupMembers = resolveProcessIdentityProvider().readProcessGroupMembers(marker.pgid)
|
||||
const unchanged =
|
||||
groupMembers.length === marker.groupMembers.length &&
|
||||
groupMembers.every((member, index) => {
|
||||
const recorded = marker.groupMembers[index]
|
||||
return recorded !== undefined && recorded.pid === member.pid && recorded.startToken === member.startToken
|
||||
})
|
||||
if (unchanged) return
|
||||
await writeChildStateMarker({ ...marker, groupMembers })
|
||||
} catch (error) {
|
||||
logger.warn('Failed to refresh the OpenCode child state marker process group membership:', error)
|
||||
}
|
||||
}
|
||||
|
||||
private async waitForHealth(timeoutMs: number): Promise<boolean> {
|
||||
const start = Date.now()
|
||||
while (Date.now() - start < timeoutMs) {
|
||||
@@ -784,12 +1374,20 @@ class OpenCodeServerManager {
|
||||
}
|
||||
|
||||
private async findProcessesByPort(port: number): Promise<Array<{pid: number}>> {
|
||||
let output: string
|
||||
try {
|
||||
const pids = execSync(`lsof -ti:${port}`).toString().trim().split('\n')
|
||||
return pids.filter(Boolean).map(pid => ({ pid: parseInt(pid) }))
|
||||
} catch {
|
||||
output = execSync(`lsof -nP -t -iTCP:${port} -sTCP:LISTEN`).toString().trim()
|
||||
} catch (error) {
|
||||
const status = error && typeof error === 'object' && 'status' in error ? (error as { status: number | null }).status : null
|
||||
if (status === 1) {
|
||||
return []
|
||||
}
|
||||
throw new Error(`lsof failed to inspect port ${port}: ${error instanceof Error ? error.message : String(error)}`)
|
||||
}
|
||||
if (output === '') {
|
||||
return []
|
||||
}
|
||||
return output.split('\n').filter(Boolean).map(pid => ({ pid: parseInt(pid) }))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user