feat(config): support layered OpenCode config sources with revision-guarded saves (#358)

* feat(config): support layered OpenCode config sources with revision-guarded saves

* refactor(config): harden multi-source OpenCode config handling

- extract shared config-source helpers and default source name
- reject shadowed removals with 409 and require sources/revision
- restart the server on reload with session resume
- mirror multiple host config files on import and warn on removals
- skip restart for mcp-only saves
- drop removedFields and CONFIG_PATCH_TIMEOUT_MS

* fix(config): return null when archiving broken OpenCode config fails
This commit is contained in:
Chris Scott authored and GitHub committed 2026-09-20 15:51:40 -04:00
1 parent 97370a8296
commit b5dd900efb
53 files changed
+3003 -1665

No files matched your search

+3 -2
View File
@@ -55,7 +55,8 @@ import { installAssistantWorkspace } from './services/assistant-mode'
import { detectSandboxCapability } from './services/sandbox/capability'
import { SandboxRuntimeService, stopWorkspaceSandboxOnShutdown } from './services/sandbox/runtime'
import { getOpenCodeImportStatus, syncOpenCodeImport } from './services/opencode-import'
import { readOpenCodeConfigFile, writeOpenCodeConfigFile, OPENCODE_CONFIG_SEED } from './services/opencode-config-file'
import { readOpenCodeConfigFile } from './services/opencode-config-file'
import { seedOpenCodeConfigFile } from './services/opencode-config-apply'
import { OpenCodeSupervisor } from './services/opencode-supervisor'
import { OpenCodeRestartCoordinator } from './services/opencode-restart-coordinator'
import { setOpenCodeRestartCoordinator } from './services/opencode-restart'
@@ -133,7 +134,7 @@ async function ensureOpenCodeConfigFileExists(): Promise<void> {
}
}
await writeOpenCodeConfigFile(OPENCODE_CONFIG_SEED)
await seedOpenCodeConfigFile()
logger.info('Created minimal seed config')
}
+43 -4
View File
@@ -2,8 +2,14 @@ import { Hono } from 'hono'
import { z } from 'zod'
import { UpdateOpenCodeConfigRequestSchema } from '@opencode-manager/shared/schemas'
import type { SettingsService } from '../services/settings'
import type { OpenCodeClient } from '../services/opencode/client'
import { readOpenCodeConfigFile } from '../services/opencode-config-file'
import { UpstreamError, type OpenCodeClient } from '../services/opencode/client'
import {
OpenCodeConfigConflictError,
OpenCodeConfigShadowedRemovalError,
OpenCodeConfigSourceInvalidError,
readOpenCodeConfigFile,
withOpenCodeConfigLock,
} from '../services/opencode-config-file'
import { applyOpenCodeConfigUpdate, toOpenCodeConfigApplyResponse } from '../services/opencode-config-apply'
import { logger } from '../utils/logger'
@@ -12,7 +18,7 @@ export function createOpenCodeConfigRoutes(settingsService: SettingsService, ope
app.get('/', async (c) => {
try {
const config = await readOpenCodeConfigFile()
const config = await withOpenCodeConfigLock(readOpenCodeConfigFile)
if (!config) {
return c.json({ error: 'No OpenCode config file found' }, 404)
}
@@ -23,6 +29,22 @@ export function createOpenCodeConfigRoutes(settingsService: SettingsService, ope
}
})
app.get('/effective', async (c) => {
try {
const config = await openCodeClient.getJson<Record<string, unknown>>('/global/config')
return c.json(config)
} catch (error) {
logger.error('Failed to get effective OpenCode config:', error)
if (error instanceof UpstreamError) {
if (error.status === 502) {
return c.json({ error: 'OpenCode server unavailable' }, 503)
}
return c.json({ error: 'Failed to get effective OpenCode config' }, 502)
}
return c.json({ error: 'Failed to get effective OpenCode config' }, 500)
}
})
app.put('/', async (c) => {
let body: unknown
try {
@@ -39,16 +61,33 @@ export function createOpenCodeConfigRoutes(settingsService: SettingsService, ope
try {
const result = await applyOpenCodeConfigUpdate({
content: parsed.data.content,
openCodeClient,
source: parsed.data.source,
expectedRevision: parsed.data.expectedRevision,
settingsService,
})
const { status, body: responseBody } = toOpenCodeConfigApplyResponse(result)
return c.json(responseBody, status)
} catch (error) {
logger.error('Failed to update OpenCode config:', error)
if (error instanceof OpenCodeConfigConflictError) {
return c.json({
error: error.message,
expectedRevision: error.expectedRevision,
actualRevision: error.actualRevision,
}, 409)
}
if (error instanceof OpenCodeConfigSourceInvalidError) {
return c.json({ error: error.message, sources: error.sources }, 400)
}
if (error instanceof OpenCodeConfigShadowedRemovalError) {
return c.json({ error: error.message, paths: error.paths, sources: error.sources }, 409)
}
if (error instanceof z.ZodError) {
return c.json({ error: 'Invalid config data', details: error.issues }, 400)
}
if (error instanceof SyntaxError) {
return c.json({ error: 'Invalid config data', details: error.message }, 400)
}
return c.json({ error: 'Failed to update OpenCode config' }, 500)
}
})
+8 -4
View File
@@ -7,7 +7,7 @@ import { resolve, dirname } from 'path'
import type { Database } from 'bun:sqlite'
import { SettingsService } from '../services/settings'
import { writeFileContent, readFileContent, fileExists } from '../services/file-operations'
import { deleteOpenCodeConfigFile } from '../services/opencode-config-file'
import { archiveBrokenOpenCodeConfigFile, deleteOpenCodeConfigFile } from '../services/opencode-config-file'
import { restoreLastKnownGoodOpenCodeConfig } from '../services/opencode-config-apply'
import { createOpenCodeConfigRoutes } from './opencode-config'
import type { OpenCodeClient } from '../services/opencode/client'
@@ -517,8 +517,12 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
app.post('/opencode-reload', async (c) => {
try {
logger.info('OpenCode configuration reload requested')
await reloadOpenCodeConfig(openCodeSupervisor)
return c.json({ success: true, message: 'OpenCode configuration reloaded successfully' })
const { resumedSessionIDs } = await reloadOpenCodeConfig(openCodeSupervisor)
return c.json({
success: true,
message: 'OpenCode server restarted with the current configuration',
resumedSessions: resumedSessionIDs,
})
} catch (error) {
logger.error('Failed to reload OpenCode config:', error)
if (error instanceof ConfigReloadError) {
@@ -529,7 +533,6 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
error: error.message,
details,
validationIssues: error.validationIssues,
removedFields: error.removedFields
}, 500)
}
return c.json({
@@ -555,6 +558,7 @@ export function createSettingsRoutes(db: Database, gitAuthService: GitAuthServic
} catch (reloadError) {
logger.error('Rollback config reload failed, attempting restart:', reloadError)
await archiveBrokenOpenCodeConfigFile()
const deleted = await deleteOpenCodeConfigFile()
if (deleted) {
logger.info('Deleted filesystem config, attempting restart with fallback')
+17 -12
View File
@@ -715,21 +715,23 @@ Reload the assistant workspace by disposing the current OpenCode instance. Use t
## OpenCode Configuration
The OpenCode configuration file on disk is the source of truth, and this endpoint is the only supported way to change it. Never edit \`opencode.json\` directly.
The global configuration files on disk are the source of truth. Use the \`ocm\` tool's \`request\` action with the endpoints below to read or change them; never edit the files directly. Global sources merge in order: \`config.json\`, \`opencode.json\`, then \`opencode.jsonc\`.
### GET /opencode-config
Read the current configuration file. Returns \`404\` when no config file exists yet.
Read the merged persisted global configuration and its source files. Returns \`404\` when no source exists. This is not the running instance configuration: project overrides and expanded environment values are not included. \`GET /opencode-config/effective\` reads the running server's effective global configuration separately; never copy that response into a save.
**Response (\`OpenCodeConfigFile\`):**
\`\`\`ts
{
path: string // Absolute path of the configuration file
content: object // Parsed configuration
rawContent: string // Raw file content, including comments
isValid: boolean // Whether the file passes schema validation
path: string
content: object
rawContent: string
sources: Array<{ name: string, path: string, rawContent: string, content: object, isValid: boolean }>
revision: string
isValid: boolean
validationIssues?: Array<{ path: string, message: string }>
updatedAt: number // Unix timestamp of the last write
updatedAt: number
}
\`\`\`
@@ -746,11 +748,13 @@ Read the current configuration file. Returns \`404\` when no config file exists
### PUT /opencode-config
Persist a complete configuration. Read the file first, change only the keys the user asked for, and send the complete object back.
Read the merged persisted configuration first, change only the keys the user asked for, and send the complete object back with its revision. Only changed fields are patched into the preferred existing source: JSONC, JSON, then legacy config.json. New installations use opencode.jsonc. Unchanged inherited values and comments are preserved. Removing a field removes only its override in the write target; a lower-priority value can reappear.
For a raw edit, send a string with the exact source name from \`sources\`. Never send merged JSON as raw source text. A \`409\` means the source files changed: read again and reconcile rather than retrying stale content.
**Request Body:**
\`\`\`ts
{ content: object } // The complete configuration to persist
{ content: object | string, expectedRevision: string, source?: "config.json" | "opencode.json" | "opencode.jsonc" }
\`\`\`
**Example:**
@@ -761,6 +765,7 @@ Persist a complete configuration. Read the file first, change only the keys the
"method": "PUT",
"path": "/opencode-config",
"body": {
"expectedRevision": "revision-from-get",
"content": {
"theme": "dark"
}
@@ -770,16 +775,16 @@ Persist a complete configuration. Read the file first, change only the keys the
\`\`\`
**Response:**
Returns the written \`OpenCodeConfigFile\`. Adds \`restartRequired: true\` when the change needs an OpenCode server restart, and \`removedFields\` when OpenCode dropped fields it does not accept.
Returns the refreshed merged configuration and source files. Adds \`restartRequired: true\` for semantic configuration changes, except changes limited to \`mcp\`, which are saved without it; to make an MCP change take effect immediately, tell the user to reconnect or reload the server from Settings → MCP. Comment-only changes do not require a restart. Saving never silently drops unsupported fields.
Returns \`400\` with \`validationIssues\` when OpenCode rejects the configuration.
Returns \`400\` for invalid configuration and \`409\` for a stale revision.
When the response contains \`restartRequired: true\`, tell the user to restart the OpenCode server from Settings. Never attempt the restart yourself: it would terminate your own session.
## Safety
- The settings PATCH endpoint rejects any attempt to modify credentials, API keys, or other sensitive settings; guide the user to the full UI for Git, TTS, and STT credentials
- PUT /opencode-config writes the complete OpenCode configuration, including \`plugin\`, \`mcp\`, and \`provider\` entries; change only the keys the user explicitly asked for and never add plugins, MCP servers, or provider credentials the user did not request
- PUT /opencode-config patches changed global settings, including \`plugin\`, \`mcp\`, and \`provider\` entries; change only the keys the user explicitly asked for and never add plugins, MCP servers, or provider credentials the user did not request
- The settings PATCH endpoint does NOT trigger OpenCode reload or restart
`
}
+61 -69
View File
@@ -1,27 +1,35 @@
import { OpenCodeConfigSchema } from '@opencode-manager/shared/schemas'
import { parseJsonc } from '@opencode-manager/shared/utils'
import type { OpenCodeConfigFile, OpenCodeConfigInput } from '../types/settings'
import { OPENCODE_CONFIG_SEED, normalizeOpenCodeConfigContent, readOpenCodeConfigFile, withOpenCodeConfigLock, writeOpenCodeConfigFile } from './opencode-config-file'
import { patchConfigWithRecovery, type PatchConfigValidationIssue } from './opencode/config-recovery'
import type { OpenCodeClient } from './opencode/client'
import { isDeepStrictEqual } from 'node:util'
import type {
OpenCodeConfigFile,
OpenCodeConfigSourceName,
} from '../types/settings'
import {
buildOpenCodeConfigSeedSnapshot,
readOpenCodeConfigFile,
readOpenCodeConfigSnapshot,
restoreOpenCodeConfigSnapshot,
serializeOpenCodeConfigSnapshot,
updateOpenCodeConfigFile,
withOpenCodeConfigLock,
} from './opencode-config-file'
import { opencodeServerManager } from './opencode-single-server'
import type { SettingsService } from './settings'
export type ApplyOpenCodeConfigResult =
| { status: 'restart_pending'; config: OpenCodeConfigFile }
| { status: 'applied'; config: OpenCodeConfigFile; removedFields: string[] }
| { status: 'rejected'; error: string; validationIssues: PatchConfigValidationIssue[]; removedFields: string[] }
| { status: 'applied'; config: OpenCodeConfigFile }
export interface ApplyOpenCodeConfigInput {
content: OpenCodeConfigInput | string
openCodeClient: OpenCodeClient
content: Record<string, unknown> | string
source?: OpenCodeConfigSourceName
expectedRevision?: string
settingsService: SettingsService
}
export async function captureLastKnownGoodOpenCodeConfig(settingsService: SettingsService): Promise<OpenCodeConfigFile | null> {
const previous = await readOpenCodeConfigFile()
if (previous?.isValid) {
settingsService.saveLastKnownGoodConfig(previous.rawContent)
settingsService.saveLastKnownGoodConfig(serializeOpenCodeConfigSnapshot(previous))
}
return previous
}
@@ -32,90 +40,74 @@ export async function restoreLastKnownGoodOpenCodeConfig(settingsService: Settin
return null
}
const config = await withOpenCodeConfigLock(() => writeOpenCodeConfigFile(lastGood))
const config = await withOpenCodeConfigLock(() => restoreOpenCodeConfigSnapshot(lastGood))
opencodeServerManager.clearStartupError()
return config
}
export async function seedOpenCodeConfigFile(): Promise<OpenCodeConfigFile> {
return withOpenCodeConfigLock(() => writeOpenCodeConfigFile(OPENCODE_CONFIG_SEED))
}
function didConfigFieldChange(
previous: Record<string, unknown> | undefined,
next: Record<string, unknown> | undefined,
field: string,
): boolean {
return JSON.stringify(previous?.[field]) !== JSON.stringify(next?.[field])
}
function needsOpenCodeRestart(
previous: Record<string, unknown> | undefined,
next: Record<string, unknown> | undefined,
): boolean {
return ['agent', 'plugin', 'skills', 'provider'].some((field) => didConfigFieldChange(previous, next, field))
return withOpenCodeConfigLock(async () => {
const config = await restoreOpenCodeConfigSnapshot(buildOpenCodeConfigSeedSnapshot())
if (!config) {
throw new Error('Failed to seed OpenCode config')
}
return config
})
}
export function toOpenCodeConfigApplyResponse(
result: ApplyOpenCodeConfigResult,
): { status: 200 | 400; body: Record<string, unknown> } {
if (result.status === 'restart_pending') {
return { status: 200, body: { ...result.config, restartRequired: true } }
): { status: 200; body: Record<string, unknown> } {
return {
status: 200,
body: result.status === 'restart_pending'
? { ...result.config, restartRequired: true }
: { ...result.config },
}
}
function requiresOpenCodeRestart(previous: OpenCodeConfigFile | null, next: OpenCodeConfigFile): boolean {
if (previous?.isValid !== next.isValid) {
return true
}
if (result.status === 'applied') {
return {
status: 200,
body: result.removedFields.length > 0
? { ...result.config, removedFields: result.removedFields }
: { ...result.config },
const previousContent = previous?.content ?? {}
const keys = new Set([...Object.keys(previousContent), ...Object.keys(next.content)])
for (const key of keys) {
if (!isDeepStrictEqual(previousContent[key], next.content[key]) && key !== 'mcp') {
return true
}
}
return {
status: 400,
body: {
error: 'Config validation failed',
details: result.error,
validationIssues: result.validationIssues,
removedFields: result.removedFields,
},
}
return false
}
export async function applyOpenCodeConfigUpdate(
input: ApplyOpenCodeConfigInput,
): Promise<ApplyOpenCodeConfigResult> {
return withOpenCodeConfigLock(async () => {
const { content, openCodeClient, settingsService } = input
const { content, source, expectedRevision, settingsService } = input
const rawContent = normalizeOpenCodeConfigContent(content)
const nextContent = OpenCodeConfigSchema.parse(parseJsonc(rawContent))
const snapshot = await readOpenCodeConfigSnapshot()
const previous = await readOpenCodeConfigFile(snapshot)
const previous = await captureLastKnownGoodOpenCodeConfig(settingsService)
const next = await updateOpenCodeConfigFile(content, { source, expectedRevision, snapshot })
if (needsOpenCodeRestart(previous?.content, nextContent)) {
const config = await writeOpenCodeConfigFile(rawContent)
opencodeServerManager.markRestartPending()
return { status: 'restart_pending', config }
}
const patchResult = await patchConfigWithRecovery(openCodeClient, nextContent)
if (!patchResult.success) {
return {
status: 'rejected',
error: patchResult.error ?? 'Config validation failed',
validationIssues: patchResult.details ?? [],
removedFields: patchResult.removedFields ?? [],
if (previous?.isValid) {
const snapshot = serializeOpenCodeConfigSnapshot(previous)
try {
settingsService.saveLastKnownGoodConfig(snapshot)
} catch (error) {
await restoreOpenCodeConfigSnapshot(snapshot)
throw error
}
}
const removedFields = patchResult.removedFields ?? []
const contentToWrite = removedFields.length > 0
? JSON.stringify(patchResult.appliedConfig ?? nextContent, null, 2)
: rawContent
const config = await writeOpenCodeConfigFile(contentToWrite)
if (requiresOpenCodeRestart(previous, next)) {
opencodeServerManager.markRestartPending()
return { status: 'restart_pending', config: next }
}
return { status: 'applied', config, removedFields }
return { status: 'applied', config: next }
})
}
+541 -53
View File
@@ -1,21 +1,86 @@
import { readdir, rm, stat } from 'fs/promises'
import { createHash } from 'crypto'
import { readFile, readdir, rm, stat } from 'fs/promises'
import path from 'path'
import { isDeepStrictEqual } from 'node:util'
import { applyEdits, modify, type JSONPath } from 'jsonc-parser'
import type { ZodIssue } from 'zod'
import { getOpenCodeConfigFilePath, getOpenCodeHealthWatchPath } from '@opencode-manager/shared/config/env'
import { getConfigPath, getOpenCodeHealthWatchPath } from '@opencode-manager/shared/config/env'
import {
DEFAULT_OPENCODE_CONFIG_SOURCE_NAME,
OPENCODE_CONFIG_SOURCE_NAMES,
isOpenCodeConfigSourceName,
selectPreferredOpenCodeConfigSourceName,
} from '@opencode-manager/shared'
import { OpenCodeConfigSchema } from '@opencode-manager/shared/schemas'
import { parseJsonc } from '@opencode-manager/shared/utils'
import type { OpenCodeConfigFile, OpenCodeConfigInput, OpenCodeConfigValidationIssue } from '../types/settings'
import type {
OpenCodeConfigFile,
OpenCodeConfigSourceFile,
OpenCodeConfigSourceName,
OpenCodeConfigValidationIssue,
} from '../types/settings'
import { logger } from '../utils/logger'
import { withFileLock } from '../utils/atomic-json'
import { existingFileMode, writeFileAtomic } from '../utils/fs-safe'
import { ensureDirectoryExists, fileExists, readFileContent, writeFileContent } from './file-operations'
import { ensureDirectoryExists } from './file-operations'
export const OPENCODE_CONFIG_SEED = JSON.stringify({ $schema: 'https://opencode.ai/config.json' }, null, 2)
export const HEALTH_WATCH_MAX_ENTRIES = 20
export function withOpenCodeConfigLock<T>(fn: () => Promise<T>): Promise<T> {
return withFileLock(getOpenCodeConfigFilePath(), fn)
const OPENCODE_CONFIG_SOURCE_ORDER: readonly OpenCodeConfigSourceName[] = OPENCODE_CONFIG_SOURCE_NAMES
const OPENCODE_CONFIG_SNAPSHOT_VERSION = 1
const OPENCODE_CONFIG_SNAPSHOT_MARKER = 'opencode-config-snapshot'
const OPENCODE_CONFIG_SNAPSHOT_ARTIFACT_PREFIX = 'opencode-config-broken'
export interface UpdateOpenCodeConfigOptions {
source?: OpenCodeConfigSourceName
expectedRevision?: string
snapshot?: OpenCodeConfigSnapshot
}
export class OpenCodeConfigConflictError extends Error {
readonly expectedRevision: string
readonly actualRevision: string
constructor(expectedRevision: string, actualRevision: string) {
super('OpenCode config was modified by another writer')
this.name = 'OpenCodeConfigConflictError'
this.expectedRevision = expectedRevision
this.actualRevision = actualRevision
}
}
export class OpenCodeConfigSourceInvalidError extends Error {
readonly sources: OpenCodeConfigSourceName[]
constructor(sources: OpenCodeConfigSourceName[]) {
super(`OpenCode config source is invalid: ${sources.join(', ')}`)
this.name = 'OpenCodeConfigSourceInvalidError'
this.sources = sources
}
}
export class OpenCodeConfigSnapshotError extends Error {
constructor(message: string) {
super(message)
this.name = 'OpenCodeConfigSnapshotError'
}
}
export class OpenCodeConfigShadowedRemovalError extends Error {
readonly paths: string[]
readonly sources: OpenCodeConfigSourceName[]
constructor(paths: string[], sources: OpenCodeConfigSourceName[], targetName: OpenCodeConfigSourceName) {
super(`Cannot remove ${paths.join(', ')}: defined in ${sources.join(', ')}, not in ${targetName}`)
this.name = 'OpenCodeConfigShadowedRemovalError'
this.paths = paths
this.sources = sources
}
}
interface OpenCodeConfigParseResult {
@@ -24,8 +89,113 @@ interface OpenCodeConfigParseResult {
validationIssues?: OpenCodeConfigValidationIssue[]
}
export function normalizeOpenCodeConfigContent(content: OpenCodeConfigInput | string): string {
return typeof content === 'string' ? content : JSON.stringify(content, null, 2)
export interface OpenCodeConfigSnapshot {
sources: OpenCodeConfigSourceFile[]
content: Record<string, unknown>
revision: string
updatedAt: number
path: string
rawContent: string
}
interface OpenCodeConfigSourceFileState {
name: OpenCodeConfigSourceName
rawContent: string | null
}
interface PreparedOpenCodeConfigSourceFileState extends OpenCodeConfigSourceFileState {
path: string
previousMode: number | undefined
previousRawContent: string | null
}
interface AppliedOpenCodeConfigSourceFileState {
name: OpenCodeConfigSourceName
previousRawContent: string | null
previousMode: number | undefined
}
interface OpenCodeConfigPathOperation {
path: JSONPath
value: unknown
}
interface OpenCodeConfigSnapshotEnvelopeSource {
name: OpenCodeConfigSourceName
rawContent: string
}
interface OpenCodeConfigSnapshotEnvelope {
marker: string
version: number
sources: OpenCodeConfigSnapshotEnvelopeSource[]
}
function getOpenCodeConfigDirectory(): string {
return getConfigPath()
}
function getOpenCodeConfigSourcePath(name: OpenCodeConfigSourceName): string {
return path.join(getOpenCodeConfigDirectory(), name)
}
function assertOpenCodeConfigSourceName(value: string): OpenCodeConfigSourceName {
if (!isOpenCodeConfigSourceName(value)) {
throw new Error(`Unsupported OpenCode config source: ${value}`)
}
return value
}
function isPlainObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
function hasOwn(object: Record<string, unknown>, key: string): boolean {
return Object.prototype.hasOwnProperty.call(object, key)
}
function hasOpenCodeConfigPath(content: Record<string, unknown>, jsonPath: JSONPath): boolean {
let current: unknown = content
for (const segment of jsonPath) {
if (typeof segment === 'number') {
if (!Array.isArray(current) || segment < 0 || segment >= current.length) return false
current = current[segment]
continue
}
if (!isPlainObject(current) || !hasOwn(current, segment)) return false
current = current[segment]
}
return true
}
function defineOwnConfigValue(target: Record<string, unknown>, key: string, value: unknown): void {
Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true })
}
function mergeOpenCodeConfigValues(
target: Record<string, unknown>,
source: Record<string, unknown>,
): Record<string, unknown> {
const output: Record<string, unknown> = {}
for (const key of Object.keys(target)) {
defineOwnConfigValue(output, key, target[key])
}
for (const key of Object.keys(source)) {
const sourceValue = source[key]
const targetValue = hasOwn(output, key) ? output[key] : undefined
defineOwnConfigValue(
output,
key,
isPlainObject(targetValue) && isPlainObject(sourceValue)
? mergeOpenCodeConfigValues(targetValue, sourceValue)
: sourceValue,
)
}
return output
}
export function withOpenCodeConfigLock<T>(fn: () => Promise<T>): Promise<T> {
return withFileLock(getOpenCodeConfigDirectory(), fn)
}
export function toOpenCodeConfigValidationIssues(issues: ZodIssue[]): OpenCodeConfigValidationIssue[] {
@@ -49,14 +219,12 @@ export function parseOpenCodeConfigContent(rawContent: string): OpenCodeConfigPa
}
}
const content = parsed && typeof parsed === 'object' && !Array.isArray(parsed)
? parsed as Record<string, unknown>
: {}
const content = isPlainObject(parsed) ? parsed : {}
const validated = OpenCodeConfigSchema.safeParse(parsed)
if (validated.success) {
return {
content: validated.data as Record<string, unknown>,
content,
isValid: true,
}
}
@@ -71,47 +239,372 @@ export function parseOpenCodeConfigContent(rawContent: string): OpenCodeConfigPa
}
}
export async function readOpenCodeConfigFile(): Promise<OpenCodeConfigFile | null> {
const configPath = getOpenCodeConfigFilePath()
async function readOpenCodeConfigSourceFile(name: OpenCodeConfigSourceName): Promise<OpenCodeConfigSourceFile | null> {
const sourcePath = getOpenCodeConfigSourcePath(name)
let updatedAt: number
try {
const stats = await stat(configPath)
const stats = await stat(sourcePath)
if (!stats.isFile()) return null
updatedAt = stats.mtimeMs
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
return null
}
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null
throw error
}
const rawContent = await readFileContent(configPath)
const rawContent = await readFile(sourcePath, 'utf8')
return {
path: configPath,
name,
path: sourcePath,
rawContent,
...parseOpenCodeConfigContent(rawContent),
updatedAt,
}
}
export async function writeOpenCodeConfigFile(rawContent: string): Promise<OpenCodeConfigFile> {
const parsed = OpenCodeConfigSchema.parse(parseJsonc(rawContent))
function selectWritableSource(sources: OpenCodeConfigSourceFile[]): OpenCodeConfigSourceFile | null {
const name = selectPreferredOpenCodeConfigSourceName(sources.map((source) => source.name))
return name ? sources.find((source) => source.name === name) ?? null : null
}
const configPath = getOpenCodeConfigFilePath()
await writeFileAtomic(configPath, rawContent, { mode: await existingFileMode(configPath) })
function computeOpenCodeConfigRevision(sources: OpenCodeConfigSourceFile[]): string {
const hash = createHash('sha256')
const byName = new Map(sources.map((source) => [source.name, source]))
for (const name of OPENCODE_CONFIG_SOURCE_ORDER) {
const source = byName.get(name)
hash.update(name)
hash.update('\0')
hash.update(source ? '1' : '0')
hash.update('\0')
hash.update(source?.rawContent ?? '')
hash.update('\0')
}
return hash.digest('hex')
}
const stats = await stat(configPath)
export async function readOpenCodeConfigSnapshot(): Promise<OpenCodeConfigSnapshot> {
const discovered = await Promise.all(OPENCODE_CONFIG_SOURCE_ORDER.map(readOpenCodeConfigSourceFile))
const sources = discovered.filter((source): source is OpenCodeConfigSourceFile => source !== null)
const content = sources.reduce<Record<string, unknown>>(
(merged, source) => mergeOpenCodeConfigValues(merged, source.content),
{},
)
const selected = selectWritableSource(sources)
return {
path: configPath,
rawContent,
content: parsed as Record<string, unknown>,
isValid: true,
updatedAt: stats.mtimeMs,
sources,
content,
revision: computeOpenCodeConfigRevision(sources),
updatedAt: sources.reduce((latest, source) => Math.max(latest, source.updatedAt), 0),
path: selected ? selected.path : getOpenCodeConfigSourcePath(DEFAULT_OPENCODE_CONFIG_SOURCE_NAME),
rawContent: selected ? selected.rawContent : '',
}
}
function toOpenCodeConfigFile(snapshot: OpenCodeConfigSnapshot): OpenCodeConfigFile {
const validationIssues = snapshot.sources.flatMap((source) => source.validationIssues ?? [])
return {
path: snapshot.path,
rawContent: snapshot.rawContent,
content: snapshot.content,
isValid: snapshot.sources.every((source) => source.isValid),
validationIssues: validationIssues.length > 0 ? validationIssues : undefined,
updatedAt: snapshot.updatedAt,
sources: snapshot.sources,
revision: snapshot.revision,
}
}
export async function readOpenCodeConfigFile(
snapshot?: OpenCodeConfigSnapshot,
): Promise<OpenCodeConfigFile | null> {
const resolved = snapshot ?? await readOpenCodeConfigSnapshot()
if (resolved.sources.length === 0) return null
return toOpenCodeConfigFile(resolved)
}
export async function writeOpenCodeConfigFile(
rawContent: string,
source?: OpenCodeConfigSourceName,
snapshot?: OpenCodeConfigSnapshot,
): Promise<OpenCodeConfigFile> {
OpenCodeConfigSchema.parse(parseJsonc(rawContent))
const resolved = snapshot ?? await readOpenCodeConfigSnapshot()
const targetName = source !== undefined
? assertOpenCodeConfigSourceName(source)
: selectWritableSource(resolved.sources)?.name ?? DEFAULT_OPENCODE_CONFIG_SOURCE_NAME
const targetPath = getOpenCodeConfigSourcePath(targetName)
await writeFileAtomic(targetPath, rawContent, { mode: await existingFileMode(targetPath) })
return toOpenCodeConfigFile(await readOpenCodeConfigSnapshot())
}
function collectOpenCodeConfigPathOperations(
requested: Record<string, unknown>,
current: Record<string, unknown>,
basePath: JSONPath = [],
): OpenCodeConfigPathOperation[] {
const operations: OpenCodeConfigPathOperation[] = []
for (const key of Object.keys(requested)) {
const requestedValue = requested[key]
const hasCurrent = hasOwn(current, key)
const currentValue = hasCurrent ? current[key] : undefined
const nextPath = [...basePath, key]
if (isPlainObject(requestedValue) && isPlainObject(currentValue)) {
operations.push(...collectOpenCodeConfigPathOperations(requestedValue, currentValue, nextPath))
} else if (!hasCurrent || !isDeepStrictEqual(requestedValue, currentValue)) {
operations.push({ path: nextPath, value: requestedValue })
}
}
for (const key of Object.keys(current)) {
if (hasOwn(requested, key)) continue
operations.push({ path: [...basePath, key], value: undefined })
}
return operations
}
function applyOpenCodeConfigPathOperations(
rawContent: string,
operations: OpenCodeConfigPathOperation[],
): string {
let text = rawContent
for (const operation of operations) {
const edits = modify(text, operation.path, operation.value, {
formattingOptions: { insertSpaces: true, tabSize: 2 },
})
text = applyEdits(text, edits)
}
return text
}
function assertNoShadowedOpenCodeConfigRemovals(
operations: OpenCodeConfigPathOperation[],
targetSource: OpenCodeConfigSourceFile | undefined,
sources: OpenCodeConfigSourceFile[],
targetName: OpenCodeConfigSourceName,
): void {
const targetContent = targetSource?.content ?? {}
const shadowedPaths: string[] = []
const shadowedSources = new Set<OpenCodeConfigSourceName>()
for (const operation of operations) {
if (operation.value !== undefined) continue
if (hasOpenCodeConfigPath(targetContent, operation.path)) continue
const definingSources = sources.filter(
(source) => source.name !== targetName && hasOpenCodeConfigPath(source.content, operation.path),
)
if (definingSources.length === 0) continue
shadowedPaths.push(operation.path.join('.'))
for (const source of definingSources) shadowedSources.add(source.name)
}
if (shadowedPaths.length > 0) {
throw new OpenCodeConfigShadowedRemovalError(shadowedPaths, [...shadowedSources], targetName)
}
}
export async function updateOpenCodeConfigFile(
content: Record<string, unknown> | string,
options: UpdateOpenCodeConfigOptions = {},
): Promise<OpenCodeConfigFile> {
const snapshot = options.snapshot ?? await readOpenCodeConfigSnapshot()
if (options.expectedRevision !== undefined && options.expectedRevision !== snapshot.revision) {
throw new OpenCodeConfigConflictError(options.expectedRevision, snapshot.revision)
}
const targetName = options.source !== undefined
? assertOpenCodeConfigSourceName(options.source)
: selectWritableSource(snapshot.sources)?.name ?? DEFAULT_OPENCODE_CONFIG_SOURCE_NAME
const targetSource = snapshot.sources.find((source) => source.name === targetName)
const targetPath = getOpenCodeConfigSourcePath(targetName)
if (typeof content === 'string') {
if (targetSource?.rawContent === content) {
return toOpenCodeConfigFile(snapshot)
}
return writeOpenCodeConfigFile(content, targetName, snapshot)
}
const invalidSources = snapshot.sources.filter((source) => !source.isValid).map((source) => source.name)
if (invalidSources.length > 0) {
throw new OpenCodeConfigSourceInvalidError(invalidSources)
}
OpenCodeConfigSchema.parse(content)
const originalText = targetSource?.rawContent ?? '{}\n'
const operations = collectOpenCodeConfigPathOperations(content, snapshot.content)
assertNoShadowedOpenCodeConfigRemovals(operations, targetSource, snapshot.sources, targetName)
const updatedText = applyOpenCodeConfigPathOperations(originalText, operations)
if (updatedText !== originalText) {
OpenCodeConfigSchema.parse(parseJsonc(updatedText))
await writeFileAtomic(targetPath, updatedText, { mode: await existingFileMode(targetPath) })
}
return toOpenCodeConfigFile(await readOpenCodeConfigSnapshot())
}
export function serializeOpenCodeConfigSourceSnapshot(
entries: ReadonlyArray<{ name: OpenCodeConfigSourceName; rawContent: string }>,
): string {
const envelope: OpenCodeConfigSnapshotEnvelope = {
marker: OPENCODE_CONFIG_SNAPSHOT_MARKER,
version: OPENCODE_CONFIG_SNAPSHOT_VERSION,
sources: entries.map((entry) => ({ name: entry.name, rawContent: entry.rawContent })),
}
return JSON.stringify(envelope, null, 2)
}
export function serializeOpenCodeConfigSnapshot(
config: Pick<OpenCodeConfigFile, 'sources'>,
): string {
return serializeOpenCodeConfigSourceSnapshot(config.sources)
}
export function buildOpenCodeConfigSeedSnapshot(): string {
return serializeOpenCodeConfigSourceSnapshot([
{ name: DEFAULT_OPENCODE_CONFIG_SOURCE_NAME, rawContent: OPENCODE_CONFIG_SEED },
])
}
function isSnapshotEnvelopeCandidate(parsed: Record<string, unknown>): boolean {
return hasOwn(parsed, 'marker') || (hasOwn(parsed, 'sources') && hasOwn(parsed, 'version'))
}
function parseOpenCodeConfigSnapshot(snapshot: string): Map<OpenCodeConfigSourceName, string> {
let parsed: unknown
try {
parsed = parseJsonc(snapshot)
} catch {
throw new OpenCodeConfigSnapshotError('Invalid OpenCode config snapshot content')
}
if (isPlainObject(parsed) && isSnapshotEnvelopeCandidate(parsed)) {
if (hasOwn(parsed, 'marker') && parsed.marker !== OPENCODE_CONFIG_SNAPSHOT_MARKER) {
throw new OpenCodeConfigSnapshotError('Invalid OpenCode config snapshot marker')
}
if (parsed.version !== OPENCODE_CONFIG_SNAPSHOT_VERSION) {
throw new OpenCodeConfigSnapshotError(`Unsupported OpenCode config snapshot version: ${String(parsed.version)}`)
}
if (!Array.isArray(parsed.sources)) {
throw new OpenCodeConfigSnapshotError('Invalid OpenCode config snapshot sources')
}
const sources = new Map<OpenCodeConfigSourceName, string>()
for (const entry of parsed.sources) {
if (!isPlainObject(entry)) {
throw new OpenCodeConfigSnapshotError('Invalid OpenCode config snapshot source')
}
if (typeof entry.name !== 'string' || !isOpenCodeConfigSourceName(entry.name)) {
throw new OpenCodeConfigSnapshotError(`Invalid OpenCode config snapshot source name: ${String(entry.name)}`)
}
if (typeof entry.rawContent !== 'string') {
throw new OpenCodeConfigSnapshotError('Invalid OpenCode config snapshot source content')
}
if (sources.has(entry.name)) {
throw new OpenCodeConfigSnapshotError(`Duplicate OpenCode config snapshot source: ${entry.name}`)
}
if (!parseOpenCodeConfigContent(entry.rawContent).isValid) {
throw new OpenCodeConfigSnapshotError(`Invalid OpenCode config snapshot content: ${entry.name}`)
}
sources.set(entry.name, entry.rawContent)
}
return sources
}
if (!parseOpenCodeConfigContent(snapshot).isValid) {
throw new OpenCodeConfigSnapshotError('Invalid OpenCode config snapshot content')
}
return new Map([['opencode.json', snapshot]])
}
async function rollbackOpenCodeConfigSourceFileStates(
applied: AppliedOpenCodeConfigSourceFileState[],
): Promise<Error[]> {
const failures: Error[] = []
for (const entry of [...applied].reverse()) {
const sourcePath = getOpenCodeConfigSourcePath(entry.name)
try {
if (entry.previousRawContent === null) {
await rm(sourcePath, { force: true })
} else {
await writeFileAtomic(sourcePath, entry.previousRawContent, { mode: entry.previousMode })
}
} catch (error) {
failures.push(error instanceof Error ? error : new Error(String(error)))
}
}
return failures
}
async function applyOpenCodeConfigSourceFileStates(
states: OpenCodeConfigSourceFileState[],
current: OpenCodeConfigSnapshot,
): Promise<void> {
const previousByName = new Map<OpenCodeConfigSourceName, string | null>(
current.sources.map((source) => [source.name, source.rawContent]),
)
const prepared: PreparedOpenCodeConfigSourceFileState[] = []
for (const state of states) {
const sourcePath = getOpenCodeConfigSourcePath(state.name)
const previousMode = await existingFileMode(sourcePath)
const previousRawContent = previousByName.get(state.name) ?? null
prepared.push({ ...state, path: sourcePath, previousMode, previousRawContent })
}
const applied: AppliedOpenCodeConfigSourceFileState[] = []
try {
for (const state of prepared) {
if (state.rawContent === null) {
await rm(state.path, { force: true })
} else {
await writeFileAtomic(state.path, state.rawContent, { mode: state.previousMode })
}
applied.push({
name: state.name,
previousRawContent: state.previousRawContent,
previousMode: state.previousMode,
})
}
} catch (error) {
const rollbackFailures = await rollbackOpenCodeConfigSourceFileStates(applied)
if (rollbackFailures.length > 0) {
throw new AggregateError(
[error, ...rollbackFailures],
'Failed to apply OpenCode config source states and roll back',
)
}
throw error
}
}
export async function restoreOpenCodeConfigSnapshot(snapshot: string): Promise<OpenCodeConfigFile | null> {
const desired = parseOpenCodeConfigSnapshot(snapshot)
const current = await readOpenCodeConfigSnapshot()
const currentNames = new Set(current.sources.map((source) => source.name))
const states: OpenCodeConfigSourceFileState[] = []
for (const name of OPENCODE_CONFIG_SOURCE_ORDER) {
if (desired.has(name)) {
states.push({ name, rawContent: desired.get(name) ?? '' })
} else if (currentNames.has(name)) {
states.push({ name, rawContent: null })
}
}
await applyOpenCodeConfigSourceFileStates(states, current)
return readOpenCodeConfigFile()
}
export async function pruneHealthWatchDirectory(dirPath: string): Promise<void> {
try {
const entries = await readdir(dirPath, { withFileTypes: true })
@@ -143,42 +636,37 @@ export async function writeHealthWatchArtifact(
const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
const artifactPath = path.join(getOpenCodeHealthWatchPath(), `${prefix}-${timestamp}.json`)
await ensureDirectoryExists(getOpenCodeHealthWatchPath())
await writeFileContent(artifactPath, buildContent(timestamp))
await writeFileAtomic(artifactPath, buildContent(timestamp), { mode: 0o600 })
await pruneHealthWatchDirectory(getOpenCodeHealthWatchPath())
return artifactPath
}
export async function archiveBrokenOpenCodeConfigFile(): Promise<string | null> {
const configPath = getOpenCodeConfigFilePath()
if (!(await fileExists(configPath))) {
return null
}
try {
const content = await readFileContent(configPath)
const archivePath = await writeHealthWatchArtifact('opencode-config-broken', () => content)
const snapshot = await readOpenCodeConfigSnapshot()
if (snapshot.sources.length === 0) {
return null
}
const payload = serializeOpenCodeConfigSnapshot(toOpenCodeConfigFile(snapshot))
const archivePath = await writeHealthWatchArtifact(OPENCODE_CONFIG_SNAPSHOT_ARTIFACT_PREFIX, () => payload)
logger.warn(`Archived broken OpenCode config to ${archivePath}`)
return archivePath
} catch (error) {
logger.error('Failed to archive broken OpenCode config:', error)
logger.warn('Failed to archive broken OpenCode config:', error)
return null
}
}
export async function deleteOpenCodeConfigFile(): Promise<boolean> {
const configPath = getOpenCodeConfigFilePath()
if (!(await fileExists(configPath))) {
logger.warn('Config file does not exist:', configPath)
return false
}
try {
await rm(configPath, { force: true })
logger.info('Deleted filesystem config to allow server startup:', configPath)
return withOpenCodeConfigLock(async () => {
const snapshot = await readOpenCodeConfigSnapshot()
if (snapshot.sources.length === 0) return false
await applyOpenCodeConfigSourceFileStates(
snapshot.sources.map((source) => ({ name: source.name, rawContent: null })),
snapshot,
)
logger.info('Deleted filesystem config to allow server startup:', snapshot.sources.map((source) => source.path).join(', '))
return true
} catch (error) {
logger.error('Failed to delete config file:', error)
return false
}
})
}
+52 -18
View File
@@ -3,8 +3,14 @@ import path from 'path'
import { existsSync } from 'node:fs'
import { cp, mkdtemp, readdir, rename, rm } from 'fs/promises'
import { Database as SQLiteDatabase } from 'bun:sqlite'
import { getOpenCodeConfigFilePath, getWorkspacePath } from '@opencode-manager/shared/config/env'
import { parseOpenCodeConfigContent, withOpenCodeConfigLock, writeOpenCodeConfigFile } from './opencode-config-file'
import { getConfigPath, getWorkspacePath } from '@opencode-manager/shared/config/env'
import {
DEFAULT_OPENCODE_CONFIG_SOURCE_NAME,
OPENCODE_CONFIG_SOURCE_NAMES,
isOpenCodeConfigSourceName,
selectPreferredOpenCodeConfigSourceName,
} from '@opencode-manager/shared'
import { parseOpenCodeConfigContent, restoreOpenCodeConfigSnapshot, serializeOpenCodeConfigSourceSnapshot, withOpenCodeConfigLock } from './opencode-config-file'
import { captureLastKnownGoodOpenCodeConfig } from './opencode-config-apply'
import { ensureDirectoryExists, fileExists, readFileContent } from './file-operations'
import type { SettingsService } from './settings'
@@ -13,8 +19,10 @@ const OPENCODE_STATE_DB_FILENAMES = new Set(['opencode.db', 'opencode.db-shm', '
export interface OpenCodeImportStatus {
configSourcePath: string | null
configSourcePaths: string[]
stateSourcePath: string | null
workspaceConfigPath: string
workspaceConfigPathsToRemove: string[]
workspaceStatePath: string
workspaceStateExists: boolean
}
@@ -55,11 +63,14 @@ export function getImportPathCandidates(envKey: string, fallbackPath: string): s
return Array.from(new Set(candidates))
}
export function getFirstExistingConfigSourcePath(): string | null {
return getImportPathCandidates(
'OPENCODE_IMPORT_CONFIG_PATH',
path.join(os.homedir(), '.config', 'opencode', 'opencode.json')
).find(candidate => existsSync(candidate)) ?? null
function getExistingConfigSourcePaths(): string[] {
const explicitPath = process.env.OPENCODE_IMPORT_CONFIG_PATH
if (explicitPath && existsSync(path.resolve(explicitPath))) {
return [path.resolve(explicitPath)]
}
return OPENCODE_CONFIG_SOURCE_NAMES
.map(name => path.join(os.homedir(), '.config', 'opencode', name))
.filter(candidate => existsSync(candidate))
}
async function getFirstExistingPathWithDatabase(paths: string[]): Promise<string | null> {
@@ -135,37 +146,60 @@ export async function importOpenCodeStateDirectory(sourcePath: string, targetPat
}
export async function getOpenCodeImportStatus(): Promise<OpenCodeImportStatus> {
const workspaceConfigPath = getOpenCodeConfigFilePath()
const configDir = getConfigPath()
const workspaceConfigNames = OPENCODE_CONFIG_SOURCE_NAMES.filter(name => existsSync(path.join(configDir, name)))
const workspaceConfigPaths = workspaceConfigNames.map(name => path.join(configDir, name))
const workspaceConfigPath = path.join(
configDir,
selectPreferredOpenCodeConfigSourceName(workspaceConfigNames) ?? DEFAULT_OPENCODE_CONFIG_SOURCE_NAME,
)
const workspaceStatePath = path.join(getWorkspacePath(), '.opencode', 'state', 'opencode')
const workspaceStateExists = await fileExists(path.join(workspaceStatePath, 'opencode.db'))
const configSourcePath = getFirstExistingConfigSourcePath()
const configSourcePaths = getExistingConfigSourcePaths()
const configSourcePath = configSourcePaths.at(-1) ?? null
const hostSourceNames = new Set(configSourcePaths.map(sourcePath => path.basename(sourcePath)))
const workspaceConfigPathsToRemove = configSourcePaths.length === 0
? []
: workspaceConfigPaths.filter(workspaceSourcePath => !hostSourceNames.has(path.basename(workspaceSourcePath)))
const stateSourcePath = await getFirstExistingPathWithDatabase(
getImportPathCandidates('OPENCODE_IMPORT_STATE_PATH', path.join(os.homedir(), '.local', 'share', 'opencode'))
)
return {
configSourcePath,
configSourcePaths,
stateSourcePath,
workspaceConfigPath,
workspaceConfigPathsToRemove,
workspaceStatePath,
workspaceStateExists,
}
}
async function importOpenCodeConfigFromSource(sourcePath: string, settingsService?: SettingsService): Promise<boolean> {
const rawContent = await readFileContent(sourcePath)
const { isValid } = parseOpenCodeConfigContent(rawContent)
if (!isValid) {
throw new Error('Importable OpenCode config is invalid')
}
async function importOpenCodeConfigFromSources(sourcePaths: string[], settingsService?: SettingsService): Promise<boolean> {
const configDir = getConfigPath()
const sources = await Promise.all(sourcePaths.map(async sourcePath => {
const basename = path.basename(sourcePath)
const name = isOpenCodeConfigSourceName(basename) ? basename : DEFAULT_OPENCODE_CONFIG_SOURCE_NAME
const rawContent = await readFileContent(sourcePath)
if (!parseOpenCodeConfigContent(rawContent).isValid) {
throw new Error('Importable OpenCode config is invalid')
}
return { name, path: path.join(configDir, name), rawContent }
}))
const selected = sources.at(-1)
if (!selected) return false
if (sources.every((source, index) => path.resolve(sourcePaths[index]!) === path.resolve(source.path))) return false
const snapshot = serializeOpenCodeConfigSourceSnapshot(
sources.map(source => ({ name: source.name, rawContent: source.rawContent })),
)
await withOpenCodeConfigLock(async () => {
if (settingsService) {
await captureLastKnownGoodOpenCodeConfig(settingsService)
}
await writeOpenCodeConfigFile(rawContent)
await restoreOpenCodeConfigSnapshot(snapshot)
})
return true
}
@@ -183,7 +217,7 @@ export async function syncOpenCodeImport(options: SyncOpenCodeImportOptions): Pr
}
if (options.importConfig !== false && initialStatus.configSourcePath) {
configImported = await importOpenCodeConfigFromSource(initialStatus.configSourcePath, options.settingsService)
configImported = await importOpenCodeConfigFromSources(initialStatus.configSourcePaths, options.settingsService)
}
if (initialStatus.stateSourcePath && (overwriteState || !initialStatus.workspaceStateExists)) {
@@ -8,6 +8,7 @@ export const MANAGER_TOOL_ALLOWED_ROUTES = [
'GET /settings',
'PATCH /settings',
'GET /opencode-config',
'GET /opencode-config/effective',
'PUT /opencode-config',
'POST /assistant/reload',
'GET /repos',
@@ -4,7 +4,7 @@ import path from 'path'
import { parseJsonc } from '@opencode-manager/shared/utils'
import { logger } from '../utils/logger'
import { existingFileMode, mkdirSafe, writeFileAtomic } from '../utils/fs-safe'
import { withFileLock } from '../utils/atomic-json'
import { withOpenCodeConfigLock } from './opencode-config-file'
import { getOpenCodePluginDir } from './opencode/plugin-registry'
import {
isRecord,
@@ -287,7 +287,7 @@ async function restoreEnforcementConfigSections(configPath: string): Promise<voi
const restoredContent = JSON.stringify(restored, null, 2)
if (restoredContent !== currentContent) {
const mode = await existingFileMode(configPath)
await withFileLock(configPath, () => writeFileAtomic(configPath, restoredContent, { mode }))
await withOpenCodeConfigLock(() => writeFileAtomic(configPath, restoredContent, { mode }))
}
await fs.rm(backupPath, { force: true })
}
+19 -21
View File
@@ -1,5 +1,6 @@
import { opencodeServerManager } from './opencode-single-server'
import type { OpenCodeSupervisor } from './opencode-supervisor'
import { opencodeServerManager, ConfigReloadError } from './opencode-single-server'
import { readOpenCodeConfigFile } from './opencode-config-file'
import type { OpenCodeOperationReason, OpenCodeSupervisor } from './opencode-supervisor'
import type { OpenCodeRestartCoordinator } from './opencode-restart-coordinator'
let restartCoordinator: OpenCodeRestartCoordinator | null = null
@@ -22,9 +23,9 @@ function restartFailureError(): Error {
return new Error(startupError ?? 'OpenCode server restart did not complete successfully')
}
async function performRestart(supervisor?: OpenCodeSupervisor): Promise<boolean> {
async function performRestart(supervisor: OpenCodeSupervisor | undefined, reason: OpenCodeOperationReason): Promise<boolean> {
if (supervisor) {
return (await supervisor.restart('settings_restart')).healthy
return (await supervisor.restart(reason)).healthy
}
opencodeServerManager.clearStartupError()
await opencodeServerManager.restart()
@@ -43,16 +44,19 @@ async function performRestart(supervisor?: OpenCodeSupervisor): Promise<boolean>
* A full process restart drops in-flight sessions; resuming re-issues a
* "continue" prompt once the server is healthy again.
*/
export async function restartOpenCode(supervisor?: OpenCodeSupervisor): Promise<{ resumedSessionIDs: string[] }> {
export async function restartOpenCode(
supervisor?: OpenCodeSupervisor,
reason: OpenCodeOperationReason = 'settings_restart',
): Promise<{ resumedSessionIDs: string[] }> {
if (restartCoordinator) {
const result = await restartCoordinator.runWithResume(() => performRestart(supervisor))
const result = await restartCoordinator.runWithResume(() => performRestart(supervisor, reason))
if (!result.healthy) {
throw restartFailureError()
}
return { resumedSessionIDs: result.resumedSessionIDs }
}
if (supervisor) {
const status = await supervisor.restart('settings_restart')
const status = await supervisor.restart(reason)
if (!status.healthy) {
throw restartFailureError()
}
@@ -67,19 +71,13 @@ export async function restartOpenCode(supervisor?: OpenCodeSupervisor): Promise<
return { resumedSessionIDs: [] }
}
/**
* Reloads OpenCode configuration via the non-disruptive API patch. This does
* NOT drop the server process, so active sessions keep running and there is
* nothing to resume.
*/
export async function reloadOpenCodeConfig(supervisor?: OpenCodeSupervisor): Promise<void> {
if (supervisor) {
const status = await supervisor.reloadConfig('settings_reload')
if (!status.healthy) {
const startupError = opencodeServerManager.getLastStartupError()
throw new Error(startupError ?? 'OpenCode server reload did not complete successfully')
}
return
export async function reloadOpenCodeConfig(supervisor?: OpenCodeSupervisor): Promise<{ resumedSessionIDs: string[] }> {
const config = await readOpenCodeConfigFile()
if (!config) {
throw new ConfigReloadError('No OpenCode global configuration files found')
}
await opencodeServerManager.reloadConfig()
if (!config.isValid) {
throw new ConfigReloadError('OpenCode global configuration is invalid', config.validationIssues)
}
return restartOpenCode(supervisor, 'settings_reload')
}
+3 -79
View File
@@ -26,16 +26,11 @@ import {
getOpenCodeTmpHome,
ENV,
} from '@opencode-manager/shared/config/env'
import { ZodError } from 'zod'
import type { Database } from 'bun:sqlite'
import { compareVersions } from '../utils/version-utils'
import { patchConfigWithRecovery } from './opencode/config-recovery'
import type { OpenCodeClient } from './opencode/client'
import {
readOpenCodeConfigFile,
toOpenCodeConfigValidationIssues,
withOpenCodeConfigLock,
writeOpenCodeConfigFile,
} from './opencode-config-file'
import { getOrCreateInternalToken } from './internal-token'
import { installManagedPlugins } from './opencode/plugin-registry'
@@ -65,13 +60,11 @@ type OpenCodePluginSpec = string | [string, OpenCodePluginOptions]
export class ConfigReloadError extends Error {
validationIssues: StartupValidationIssue[]
removedFields: string[]
constructor(message: string, validationIssues: StartupValidationIssue[] = [], removedFields: string[] = []) {
constructor(message: string, validationIssues: StartupValidationIssue[] = []) {
super(message)
this.name = 'ConfigReloadError'
this.validationIssues = validationIssues
this.removedFields = removedFields
}
}
@@ -333,13 +326,6 @@ class OpenCodeServerManager {
return ENV.OPENCODE.SERVER_PASSWORD
}
private requireClient(): OpenCodeClient {
if (!this.openCodeClient) {
throw new Error('OpenCodeClient not configured on OpenCodeServerManager. Call setOpenCodeClient() during startup.')
}
return this.openCodeClient
}
static getInstance(): OpenCodeServerManager {
if (!OpenCodeServerManager.instance) {
OpenCodeServerManager.instance = new OpenCodeServerManager()
@@ -636,6 +622,8 @@ class OpenCodeServerManager {
delete cleanEnv.OPENCODE_PID
delete cleanEnv.OPENCODE
delete cleanEnv.OPENCODE_PURE
delete cleanEnv.OPENCODE_CONFIG
delete userEnvVars.OPENCODE_CONFIG
this.serverProcess = spawn(
openCodeExecutable,
@@ -670,7 +658,6 @@ class OpenCodeServerManager {
OPENCODE_SERVER_USERNAME: getOpenCodeServerUsername(),
}
: {}),
OPENCODE_CONFIG: openCodeConfigPath,
}
}
)
@@ -1039,69 +1026,6 @@ class OpenCodeServerManager {
}
}
async reloadConfig(): Promise<void> {
const acquired = this.acquireOp()
if (!acquired) {
throw new OpenCodeOperationBusyError()
}
try {
logger.info('Reloading OpenCode configuration (via API)')
try {
await withOpenCodeConfigLock(async () => {
const file = await readOpenCodeConfigFile()
if (file === null) {
throw new Error(`OpenCode config file not found: ${getOpenCodeConfigFilePath()}`)
}
logger.info(`Read config from file for reload: ${file.path}`)
const patchResult = await patchConfigWithRecovery(this.requireClient(), file.content)
if (!patchResult.success) {
const errorMessage = patchResult.error || 'Failed to reload config'
const validationIssues = patchResult.details || []
const removedFields = patchResult.removedFields || []
if (validationIssues.length > 0) {
const issueSummary = validationIssues.map((d) => `${d.path}: ${d.message}`).join('; ')
logger.error(`Config reload validation errors: ${issueSummary}`)
}
if (removedFields.length > 0) {
logger.info(`Removed fields during config reload: ${removedFields.join(', ')}`)
}
throw new ConfigReloadError(errorMessage, validationIssues, removedFields)
}
if (patchResult.removedFields && patchResult.removedFields.length > 0 && patchResult.appliedConfig) {
const cleanedConfigContent = JSON.stringify(patchResult.appliedConfig, null, 2)
try {
await writeOpenCodeConfigFile(cleanedConfigContent)
} catch (error) {
if (error instanceof ZodError) {
const validationIssues = toOpenCodeConfigValidationIssues(error.issues)
const issueSummary = validationIssues.map((d) => `${d.path}: ${d.message}`).join('; ')
logger.error(`Config reload validation errors: ${issueSummary}`)
throw new ConfigReloadError('Cleaned config failed validation', validationIssues, patchResult.removedFields)
}
throw error
}
logger.info(`Persisted cleaned config to ${file.path} after removing fields: ${patchResult.removedFields.join(', ')}`)
}
})
logger.info('OpenCode configuration reloaded successfully')
await new Promise(r => setTimeout(r, 500))
const healthy = await this.checkHealth()
if (!healthy) {
throw new Error('Server unhealthy after config reload')
}
} catch (error) {
logger.error('Failed to reload OpenCode config:', error)
throw error
}
} finally {
this.releaseOp(acquired)
}
}
getPort(): number {
return getOpenCodeServerPort()
}
+1 -15
View File
@@ -130,21 +130,6 @@ export class OpenCodeSupervisor {
})
}
async reloadConfig(reason: OpenCodeOperationReason): Promise<OpenCodeLifecycleStatus> {
return this.runLifecycleOperation(async () => {
this.setState('starting')
try {
this.openCodeServerManager.clearStartupError()
await this.openCodeServerManager.reloadConfig()
return this.refreshHealthOrRecover(reason)
} catch (error) {
this.recordFailure(error)
return this.recover(reason)
}
})
}
async checkNow(reason: OpenCodeOperationReason): Promise<OpenCodeLifecycleStatus> {
if (reason === 'health_poll' && !this.isWatchEnabled()) {
return this.getStatus()
@@ -337,6 +322,7 @@ export class OpenCodeSupervisor {
}
private async seedDefaultConfig(): Promise<void> {
await archiveBrokenOpenCodeConfigFile()
await seedOpenCodeConfigFile()
this.openCodeServerManager.clearStartupError()
await this.openCodeServerManager.restart()
@@ -1,262 +0,0 @@
import type { OpenCodeClient } from './client'
import { logger } from '../../utils/logger'
import { TIMEOUTS } from '@opencode-manager/shared/config/env'
import { parseJsonc } from '@opencode-manager/shared/utils'
export type PatchConfigValidationIssue = {
path: string
message: string
}
export type PatchConfigResult = {
success: boolean
error?: string
details?: PatchConfigValidationIssue[]
removedFields?: string[]
appliedConfig?: Record<string, unknown>
}
function getIssuePath(value: unknown): string {
if (Array.isArray(value)) {
const path = value
.map((part) => typeof part === 'string' || typeof part === 'number' ? String(part) : '')
.filter(Boolean)
.join('.')
return path || 'root'
}
if (typeof value === 'string' && value.length > 0) {
if (value.startsWith('/')) {
const pointerPath = value
.split('/')
.filter(Boolean)
.map((part) => part.replace(/~1/g, '/').replace(/~0/g, '~'))
.join('.')
return pointerPath || 'root'
}
return value
}
if (typeof value === 'number') {
return String(value)
}
return 'root'
}
function getIssueMessage(value: unknown): string {
if (typeof value === 'string' && value.length > 0) {
return value
}
return 'Validation error'
}
function extractValidationIssues(value: unknown): PatchConfigValidationIssue[] {
if (!Array.isArray(value)) {
return []
}
return value.flatMap((item) => {
if (!item || typeof item !== 'object') {
return []
}
const issue = item as Record<string, unknown>
const nestedIssues = extractValidationIssues(issue.issues ?? issue.errors)
if (nestedIssues.length > 0) {
return nestedIssues
}
if (
typeof issue.message === 'string'
|| typeof issue.path === 'string'
|| Array.isArray(issue.path)
|| typeof issue.instancePath === 'string'
|| Array.isArray(issue.instancePath)
) {
return [{
path: getIssuePath(issue.path ?? issue.instancePath),
message: getIssueMessage(issue.message),
}]
}
return []
})
}
function removeFieldFromConfig(config: Record<string, unknown>, path: string): Record<string, unknown> {
const result = JSON.parse(JSON.stringify(config)) as Record<string, unknown>
const parts = path.split('.')
let current: Record<string, unknown> = result
for (let i = 0; i < parts.length - 1; i++) {
const part = parts[i]
if (!part || !current[part] || typeof current[part] !== 'object') {
return result
}
current = current[part] as Record<string, unknown>
}
const lastPart = parts[parts.length - 1]
if (lastPart) {
delete current[lastPart]
}
return result
}
function parseErrorResponse(responseText: string): { details: PatchConfigValidationIssue[]; errorMessage: string } {
const details: PatchConfigValidationIssue[] = []
let errorMessage = 'Unknown error'
try {
const errorBody = parseJsonc(responseText) as Record<string, unknown>
const structuredIssues = extractValidationIssues(
errorBody?.errors
?? errorBody?.issues
?? (errorBody?.data && typeof errorBody.data === 'object'
? (errorBody.data as Record<string, unknown>).errors ?? (errorBody.data as Record<string, unknown>).issues
: undefined)
)
if (structuredIssues.length > 0) {
details.push(...structuredIssues)
errorMessage = details.map((d) => `${d.path}: ${d.message}`).join('; ')
} else if (errorBody?.name === 'ConfigInvalidError' && errorBody?.data) {
const data = errorBody.data as { issues?: Array<{ message: string; path?: string[] }> }
if (data.issues) {
for (const issue of data.issues) {
const path = issue.path ? issue.path.join('.') : 'root'
details.push({ path, message: issue.message })
}
errorMessage = details.map((d) => `${d.path}: ${d.message}`).join('; ')
}
} else if (typeof errorBody?.error === 'string') {
errorMessage = errorBody.error
} else if (typeof errorBody?.message === 'string') {
errorMessage = errorBody.message
} else if (typeof errorBody?.success === 'boolean' && errorBody.success === false && errorBody?.data) {
errorMessage = 'Config validation failed'
} else {
const snippet = responseText.slice(0, 300)
errorMessage = `Request failed (${snippet.length < responseText.length ? 'truncated' : 'raw'} response): ${snippet}`
}
} catch {
const snippet = responseText.slice(0, 300)
errorMessage = `Parse error: ${snippet}`
}
return { details, errorMessage }
}
const CONFIG_PATCH_TIMEOUT_ERROR = `Timed out waiting for OpenCode config patch after ${TIMEOUTS.CONFIG_PATCH_TIMEOUT_MS}ms`
function isTimeoutError(error: unknown): boolean {
return typeof error === 'object'
&& error !== null
&& 'name' in error
&& (error as { name?: unknown }).name === 'TimeoutError'
}
async function forwardConfigPatch(
client: OpenCodeClient,
config: Record<string, unknown>,
): Promise<Response> {
const signal = AbortSignal.timeout(TIMEOUTS.CONFIG_PATCH_TIMEOUT_MS)
const response = await client.forward({
method: 'PATCH',
path: '/config',
body: JSON.stringify(config),
headers: { 'Content-Type': 'application/json' },
signal,
})
if (!response.ok && signal.aborted) {
throw new DOMException(CONFIG_PATCH_TIMEOUT_ERROR, 'TimeoutError')
}
return response
}
export async function patchConfigWithRecovery(
client: OpenCodeClient,
config: Record<string, unknown>,
): Promise<PatchConfigResult> {
try {
const response = await forwardConfigPatch(client, config)
if (response.ok) {
logger.info('Patched OpenCode config via API')
return { success: true, appliedConfig: config }
}
const responseText = await response.text()
logger.warn(`OpenCode PATCH response (${response.status}): ${responseText.slice(0, 500)}`)
const { details, errorMessage: initialError } = parseErrorResponse(responseText)
if (details.length === 0) {
logger.error(`Failed to patch OpenCode config: ${initialError}`)
return { success: false, error: initialError, details }
}
logger.warn(`OpenCode rejected config with validation errors: ${initialError}`)
const problematicPaths = [...new Set(details.map((d) => d.path))]
const removablePaths = problematicPaths.filter((path) => path !== 'root' && path.split('.').length <= 3)
const nonRemovablePaths = problematicPaths.filter((path) => path === 'root' || path.split('.').length > 3)
if (nonRemovablePaths.length > 0) {
logger.error(`Failed to patch OpenCode config: ${initialError}`)
return { success: false, error: initialError, details }
}
if (removablePaths.length === 0) {
logger.error(`Failed to patch OpenCode config: ${initialError}`)
return { success: false, error: initialError, details }
}
let cleanedConfig = config
const removedFields: string[] = []
for (const path of removablePaths) {
cleanedConfig = removeFieldFromConfig(cleanedConfig, path)
removedFields.push(path)
logger.info(`Removed problematic field from config: ${path}`)
}
logger.info(`Retrying config patch after removing ${removedFields.length} problematic field(s): ${removedFields.join(', ')}`)
const retryResponse = await forwardConfigPatch(client, cleanedConfig)
if (retryResponse.ok) {
logger.info('Patched OpenCode config via API after removing invalid fields')
return {
success: true,
appliedConfig: cleanedConfig,
removedFields,
details
}
}
const retryResponseText = await retryResponse.text()
const { details: retryDetails, errorMessage } = parseErrorResponse(retryResponseText)
logger.error(`Failed to patch OpenCode config even after removing invalid fields: ${errorMessage}`)
return {
success: false,
error: errorMessage,
details: retryDetails.length > 0 ? retryDetails : details,
removedFields
}
} catch (error) {
if (isTimeoutError(error)) {
logger.error(`Failed to patch OpenCode config: ${CONFIG_PATCH_TIMEOUT_ERROR}`)
return { success: false, error: CONFIG_PATCH_TIMEOUT_ERROR }
}
const errorMessage = error instanceof Error ? error.message : 'Unknown error'
logger.error('Failed to patch OpenCode config:', error)
return { success: false, error: errorMessage }
}
}