refactor(config): make on-disk opencode.json the single source of truth (#354)

* refactor(config): make on-disk opencode.json the single source of truth

Make <workspace>/.config/opencode/opencode.json the only store for the active OpenCode configuration. One owner (opencode-config-file.ts) reads, validates, writes, archives, and seeds the file; one owner (opencode-config-apply.ts) decides how an edit is applied: restart pending, or a live patch with recovery. Settings routes, the internal assistant API, the health-watch supervisor, boot, and host import all go through them, so an edit that lands on the file without going through the database is visible immediately instead of at the next Manager boot.

Remove the named-config profiles. Migration 019 archives every opencode_configs row to .config/opencode-configs-archive/<name>.json, restores the default row to opencode.json when no file exists, then drops the table, its indexes, and repos.opencode_config_name. The /opencode-configs* and config/switch routes and the CreateConfigDialog/SwitchConfigDialog dialogs are gone, and the ocm tool gains GET/PUT /opencode-config backed by the same apply owner.

Harden the write path: serialize and atomically write config updates while preserving the file mode, keep withFileLock usable after a rejection, route reloadConfig's cleaned-config write through the file owner, stop boot from rewriting an existing valid config when importing state, prune the health-watch directory to its newest 20 entries, resolve archive paths with realpath, and share one frontend config query across dialogs.

* fix(mirror): canonicalize worktree paths before branch ownership check

* refactor(config): unify opencode config apply and rollback paths

- share one config route factory between public and internal mounts
- capture last-known-good before every config write and restore via one helper
- stop auto-restarting on save; flag restart-required fields and live-patch the rest
- add CONFIG_PATCH_TIMEOUT_MS for config patch requests
- extract canonicalPath helpers, health-watch artifact writer, and useProvidersWithModels hook

* refactor(model-state): use OpenCode state file as model state source of truth
This commit is contained in:
Chris Scott authored and GitHub committed 2026-09-19 00:28:34 -04:00
1 parent 7a3c5229df
commit 295d24ced7
116 files changed
+10291 -4208

No files matched your search

+7 -5
View File
@@ -4,10 +4,12 @@ import { readdir, stat, unlink } from 'fs/promises'
import path from 'path'
import os from 'os'
import { logger } from '../utils/logger'
import { canonicalPath } from '../utils/fs-safe'
import { getReposPath } from '@opencode-manager/shared/config/env'
function resolvePath(userPath: string): string {
return path.isAbsolute(userPath) ? userPath : path.join(getReposPath(), userPath)
async function resolvePath(userPath: string): Promise<string> {
const absolutePath = path.isAbsolute(userPath) ? userPath : path.join(getReposPath(), userPath)
return canonicalPath(absolutePath)
}
export interface ArchiveOptions {
@@ -205,7 +207,7 @@ async function filterIgnoredPaths(targetPath: string, allPaths: string[], option
}
export async function createRepoArchive(repoPath: string, options?: ArchiveOptions): Promise<string> {
repoPath = resolvePath(repoPath)
repoPath = await resolvePath(repoPath)
const repoName = path.basename(repoPath)
const tempFile = path.join(os.tmpdir(), `${repoName}-${Date.now()}.zip`)
@@ -243,7 +245,7 @@ export async function createRepoArchive(repoPath: string, options?: ArchiveOptio
}
export async function createDirectoryArchive(directoryPath: string, archiveName?: string, options?: ArchiveOptions): Promise<string> {
directoryPath = resolvePath(directoryPath)
directoryPath = await resolvePath(directoryPath)
const dirName = archiveName || path.basename(directoryPath)
const tempFile = path.join(os.tmpdir(), `${dirName}-${Date.now()}.zip`)
@@ -300,7 +302,7 @@ export async function getArchiveSize(filePath: string): Promise<number> {
}
export async function getIgnoredPathsList(directoryPath: string): Promise<string[]> {
directoryPath = resolvePath(directoryPath)
directoryPath = await resolvePath(directoryPath)
logger.debug('[getIgnoredPathsList] Starting for:', directoryPath)
const gitRoot = await findGitRoot(directoryPath)
logger.debug('[getIgnoredPathsList] Git root:', gitRoot)
+69 -7
View File
@@ -335,7 +335,7 @@ Use the \`${MANAGER_TOOL_NAME}\` tool with the \`request\` action. The tool runs
{
action: 'request',
params: {
method: 'GET' | 'POST' | 'PATCH' | 'DELETE',
method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE',
path: string // relative internal API path; query strings allowed
body?: object // JSON body for POST and PATCH routes
}
@@ -575,7 +575,7 @@ Sending is rate limited to **10 notifications per minute**. Beyond that the tool
export function buildSettingsSkill(): string {
return `---
name: manager-settings
description: Read and modify safe user preferences with the ${MANAGER_TOOL_NAME} tool
description: Read and modify safe user preferences and the OpenCode configuration file with the ${MANAGER_TOOL_NAME} tool
---
## When to Load
@@ -591,7 +591,7 @@ Use the \`${MANAGER_TOOL_NAME}\` tool with the \`request\` action. The tool runs
{
action: 'request',
params: {
method: 'GET' | 'POST' | 'PATCH' | 'DELETE',
method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE',
path: string // relative internal API path; query strings allowed
body?: object // JSON body for POST and PATCH routes
}
@@ -713,10 +713,73 @@ Reload the assistant workspace by disposing the current OpenCode instance. Use t
{ "success": true }
\`\`\`
## 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.
### GET /opencode-config
Read the current configuration file. Returns \`404\` when no config file exists yet.
**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
validationIssues?: Array<{ path: string, message: string }>
updatedAt: number // Unix timestamp of the last write
}
\`\`\`
**Example:**
\`\`\`json
{
"action": "request",
"params": {
"method": "GET",
"path": "/opencode-config"
}
}
\`\`\`
### 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.
**Request Body:**
\`\`\`ts
{ content: object } // The complete configuration to persist
\`\`\`
**Example:**
\`\`\`json
{
"action": "request",
"params": {
"method": "PUT",
"path": "/opencode-config",
"body": {
"content": {
"theme": "dark"
}
}
}
}
\`\`\`
**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 \`400\` with \`validationIssues\` when OpenCode rejects the configuration.
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
- This API intentionally rejects any attempt to modify credentials, API keys, or other sensitive settings
- If you need to change credentials (Git, TTS, STT, etc.), guide the user to use the full UI
- 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
- The settings PATCH endpoint does NOT trigger OpenCode reload or restart
`
}
@@ -740,7 +803,7 @@ Use the \`${MANAGER_TOOL_NAME}\` tool with the \`request\` action. The tool runs
{
action: 'request',
params: {
method: 'GET' | 'POST' | 'PATCH' | 'DELETE',
method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE',
path: string // relative internal API path; query strings allowed
body?: object // JSON body for POST and PATCH routes
}
@@ -779,7 +842,6 @@ List all repos available to OpenCode Manager. The repos are returned in the orde
clonedAt: number // Unix timestamp
lastPulled?: number
lastAccessedAt?: number
openCodeConfigName?: string
isWorktree?: boolean
isLocal?: boolean
}>
@@ -0,0 +1,121 @@
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 { 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[] }
export interface ApplyOpenCodeConfigInput {
content: OpenCodeConfigInput | string
openCodeClient: OpenCodeClient
settingsService: SettingsService
}
export async function captureLastKnownGoodOpenCodeConfig(settingsService: SettingsService): Promise<OpenCodeConfigFile | null> {
const previous = await readOpenCodeConfigFile()
if (previous?.isValid) {
settingsService.saveLastKnownGoodConfig(previous.rawContent)
}
return previous
}
export async function restoreLastKnownGoodOpenCodeConfig(settingsService: SettingsService): Promise<OpenCodeConfigFile | null> {
const lastGood = settingsService.getLastKnownGoodConfig()
if (!lastGood) {
return null
}
const config = await withOpenCodeConfigLock(() => writeOpenCodeConfigFile(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))
}
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 } }
}
if (result.status === 'applied') {
return {
status: 200,
body: result.removedFields.length > 0
? { ...result.config, removedFields: result.removedFields }
: { ...result.config },
}
}
return {
status: 400,
body: {
error: 'Config validation failed',
details: result.error,
validationIssues: result.validationIssues,
removedFields: result.removedFields,
},
}
}
export async function applyOpenCodeConfigUpdate(
input: ApplyOpenCodeConfigInput,
): Promise<ApplyOpenCodeConfigResult> {
return withOpenCodeConfigLock(async () => {
const { content, openCodeClient, settingsService } = input
const rawContent = normalizeOpenCodeConfigContent(content)
const nextContent = OpenCodeConfigSchema.parse(parseJsonc(rawContent))
const previous = await captureLastKnownGoodOpenCodeConfig(settingsService)
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 ?? [],
}
}
const removedFields = patchResult.removedFields ?? []
const contentToWrite = removedFields.length > 0
? JSON.stringify(patchResult.appliedConfig ?? nextContent, null, 2)
: rawContent
const config = await writeOpenCodeConfigFile(contentToWrite)
return { status: 'applied', config, removedFields }
})
}
@@ -0,0 +1,184 @@
import { readdir, rm, stat } from 'fs/promises'
import path from 'path'
import type { ZodIssue } from 'zod'
import { getOpenCodeConfigFilePath, getOpenCodeHealthWatchPath } from '@opencode-manager/shared/config/env'
import { OpenCodeConfigSchema } from '@opencode-manager/shared/schemas'
import { parseJsonc } from '@opencode-manager/shared/utils'
import type { OpenCodeConfigFile, OpenCodeConfigInput, 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'
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)
}
interface OpenCodeConfigParseResult {
content: Record<string, unknown>
isValid: boolean
validationIssues?: OpenCodeConfigValidationIssue[]
}
export function normalizeOpenCodeConfigContent(content: OpenCodeConfigInput | string): string {
return typeof content === 'string' ? content : JSON.stringify(content, null, 2)
}
export function toOpenCodeConfigValidationIssues(issues: ZodIssue[]): OpenCodeConfigValidationIssue[] {
return issues.map((issue) => ({
path: issue.path.length > 0 ? issue.path.join('.') : 'root',
message: issue.message,
}))
}
export function parseOpenCodeConfigContent(rawContent: string): OpenCodeConfigParseResult {
let parsed: unknown
try {
parsed = parseJsonc(rawContent)
} catch (error) {
const message = error instanceof Error ? error.message : 'Invalid JSONC'
logger.error(`Failed to parse OpenCode config: ${message}`)
return {
content: {},
isValid: false,
validationIssues: [{ path: 'root', message }],
}
}
const content = parsed && typeof parsed === 'object' && !Array.isArray(parsed)
? parsed as Record<string, unknown>
: {}
const validated = OpenCodeConfigSchema.safeParse(parsed)
if (validated.success) {
return {
content: validated.data as Record<string, unknown>,
isValid: true,
}
}
const validationIssues = toOpenCodeConfigValidationIssues(validated.error.issues)
logger.error(`Failed to validate OpenCode config: ${validationIssues.map((issue) => `${issue.path}: ${issue.message}`).join('; ')}`)
return {
content,
isValid: false,
validationIssues,
}
}
export async function readOpenCodeConfigFile(): Promise<OpenCodeConfigFile | null> {
const configPath = getOpenCodeConfigFilePath()
let updatedAt: number
try {
const stats = await stat(configPath)
updatedAt = stats.mtimeMs
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
return null
}
throw error
}
const rawContent = await readFileContent(configPath)
return {
path: configPath,
rawContent,
...parseOpenCodeConfigContent(rawContent),
updatedAt,
}
}
export async function writeOpenCodeConfigFile(rawContent: string): Promise<OpenCodeConfigFile> {
const parsed = OpenCodeConfigSchema.parse(parseJsonc(rawContent))
const configPath = getOpenCodeConfigFilePath()
await writeFileAtomic(configPath, rawContent, { mode: await existingFileMode(configPath) })
const stats = await stat(configPath)
return {
path: configPath,
rawContent,
content: parsed as Record<string, unknown>,
isValid: true,
updatedAt: stats.mtimeMs,
}
}
export async function pruneHealthWatchDirectory(dirPath: string): Promise<void> {
try {
const entries = await readdir(dirPath, { withFileTypes: true })
const files = await Promise.all(
entries
.filter((entry) => entry.isFile())
.map(async (entry) => {
const filePath = path.join(dirPath, entry.name)
const fileStats = await stat(filePath)
return { filePath, mtimeMs: fileStats.mtimeMs }
}),
)
if (files.length <= HEALTH_WATCH_MAX_ENTRIES) return
files.sort((left, right) => right.mtimeMs - left.mtimeMs)
await Promise.all(
files.slice(HEALTH_WATCH_MAX_ENTRIES).map((file) => rm(file.filePath, { force: true })),
)
} catch (error) {
logger.warn('Failed to prune OpenCode health-watch directory:', error)
}
}
export async function writeHealthWatchArtifact(
prefix: string,
buildContent: (timestamp: string) => string,
): Promise<string> {
const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
const artifactPath = path.join(getOpenCodeHealthWatchPath(), `${prefix}-${timestamp}.json`)
await ensureDirectoryExists(getOpenCodeHealthWatchPath())
await writeFileContent(artifactPath, buildContent(timestamp))
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)
logger.warn(`Archived broken OpenCode config to ${archivePath}`)
return archivePath
} catch (error) {
logger.error('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 true
} catch (error) {
logger.error('Failed to delete config file:', error)
return false
}
}
+27 -43
View File
@@ -1,12 +1,13 @@
import os from 'os'
import path from 'path'
import { existsSync } from 'node:fs'
import { cp, mkdtemp, readdir, rename, rm } from 'fs/promises'
import { Database as SQLiteDatabase, type Database } from 'bun:sqlite'
import { OpenCodeConfigSchema } from '@opencode-manager/shared/schemas'
import { Database as SQLiteDatabase } from 'bun:sqlite'
import { getOpenCodeConfigFilePath, getWorkspacePath } from '@opencode-manager/shared/config/env'
import { parse as parseJsonc } from 'jsonc-parser'
import { SettingsService } from './settings'
import { ensureDirectoryExists, fileExists, readFileContent, writeFileContent } from './file-operations'
import { parseOpenCodeConfigContent, withOpenCodeConfigLock, writeOpenCodeConfigFile } from './opencode-config-file'
import { captureLastKnownGoodOpenCodeConfig } from './opencode-config-apply'
import { ensureDirectoryExists, fileExists, readFileContent } from './file-operations'
import type { SettingsService } from './settings'
const OPENCODE_STATE_DB_FILENAMES = new Set(['opencode.db', 'opencode.db-shm', 'opencode.db-wal'])
@@ -19,10 +20,11 @@ export interface OpenCodeImportStatus {
}
export interface SyncOpenCodeImportOptions {
db: Database
userId?: string
overwriteState?: boolean
protectExistingState?: boolean
importConfig?: boolean
status?: OpenCodeImportStatus
settingsService?: SettingsService
}
export interface SyncOpenCodeImportResult extends OpenCodeImportStatus {
@@ -53,14 +55,11 @@ export function getImportPathCandidates(envKey: string, fallbackPath: string): s
return Array.from(new Set(candidates))
}
export async function getFirstExistingPath(paths: string[]): Promise<string | null> {
for (const candidate of paths) {
if (await fileExists(candidate)) {
return candidate
}
}
return null
export function getFirstExistingConfigSourcePath(): string | null {
return getImportPathCandidates(
'OPENCODE_IMPORT_CONFIG_PATH',
path.join(os.homedir(), '.config', 'opencode', 'opencode.json')
).find(candidate => existsSync(candidate)) ?? null
}
async function getFirstExistingPathWithDatabase(paths: string[]): Promise<string | null> {
@@ -140,9 +139,7 @@ export async function getOpenCodeImportStatus(): Promise<OpenCodeImportStatus> {
const workspaceStatePath = path.join(getWorkspacePath(), '.opencode', 'state', 'opencode')
const workspaceStateExists = await fileExists(path.join(workspaceStatePath, 'opencode.db'))
const configSourcePath = await getFirstExistingPath(
getImportPathCandidates('OPENCODE_IMPORT_CONFIG_PATH', path.join(os.homedir(), '.config', 'opencode', 'opencode.json'))
)
const configSourcePath = getFirstExistingConfigSourcePath()
const stateSourcePath = await getFirstExistingPathWithDatabase(
getImportPathCandidates('OPENCODE_IMPORT_STATE_PATH', path.join(os.homedir(), '.local', 'share', 'opencode'))
)
@@ -156,38 +153,25 @@ export async function getOpenCodeImportStatus(): Promise<OpenCodeImportStatus> {
}
}
async function importOpenCodeConfigFromSource(db: Database, userId: string, sourcePath: string, workspaceConfigPath: string): Promise<boolean> {
async function importOpenCodeConfigFromSource(sourcePath: string, settingsService?: SettingsService): Promise<boolean> {
const rawContent = await readFileContent(sourcePath)
const parsed = parseJsonc(rawContent)
const validation = OpenCodeConfigSchema.safeParse(parsed)
const { isValid } = parseOpenCodeConfigContent(rawContent)
if (!validation.success) {
if (!isValid) {
throw new Error('Importable OpenCode config is invalid')
}
const settingsService = new SettingsService(db)
const existingDefault = settingsService.getOpenCodeConfigByName('default', userId)
if (existingDefault) {
settingsService.updateOpenCodeConfig('default', {
content: rawContent,
isDefault: true,
}, userId)
} else {
settingsService.createOpenCodeConfig({
name: 'default',
content: rawContent,
isDefault: true,
}, userId)
}
await writeFileContent(workspaceConfigPath, rawContent)
await withOpenCodeConfigLock(async () => {
if (settingsService) {
await captureLastKnownGoodOpenCodeConfig(settingsService)
}
await writeOpenCodeConfigFile(rawContent)
})
return true
}
export async function syncOpenCodeImport(options: SyncOpenCodeImportOptions): Promise<SyncOpenCodeImportResult> {
const initialStatus = await getOpenCodeImportStatus()
const userId = options.userId || 'default'
const initialStatus = options.status ?? await getOpenCodeImportStatus()
const overwriteState = options.overwriteState === true
let configImported = false
let stateImported = false
@@ -198,8 +182,8 @@ export async function syncOpenCodeImport(options: SyncOpenCodeImportOptions): Pr
)
}
if (initialStatus.configSourcePath) {
configImported = await importOpenCodeConfigFromSource(options.db, userId, initialStatus.configSourcePath, initialStatus.workspaceConfigPath)
if (options.importConfig !== false && initialStatus.configSourcePath) {
configImported = await importOpenCodeConfigFromSource(initialStatus.configSourcePath, options.settingsService)
}
if (initialStatus.stateSourcePath && (overwriteState || !initialStatus.workspaceStateExists)) {
@@ -7,6 +7,8 @@ export const MANAGER_TOOL_REQUEST_TIMEOUT_MS = 15000
export const MANAGER_TOOL_ALLOWED_ROUTES = [
'GET /settings',
'PATCH /settings',
'GET /opencode-config',
'PUT /opencode-config',
'POST /assistant/reload',
'GET /repos',
'GET /repos/*/git-info',
@@ -26,7 +28,7 @@ export const MANAGER_TOOL_ALLOWED_ROUTES = [
'POST /repos/*/schedules/*/runs/*/cancel',
] as const
export const MANAGER_TOOL_ALLOWED_METHODS = ['GET', 'POST', 'PATCH', 'DELETE'] as const
export const MANAGER_TOOL_ALLOWED_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'] as const
export function parseAllowedRoute(route: string): { method: string; path: string } {
const separator = route.indexOf(' ')
@@ -159,7 +161,7 @@ export default async function () {
'The action runs inside OpenCode Manager itself, so it needs no token and no network access from the agent shell, and it works in sandboxed sessions and scheduled runs.',
'Actions:',
'- send_notification: send a push notification to every device the user has registered.',
'- request: call an allow-listed internal API route to read and manage settings, repos, OpenCode workspaces, and schedules.',
'- request: call an allow-listed internal API route to read and manage settings, the OpenCode configuration file, repos, OpenCode workspaces, and schedules.',
'Allowed request routes:',
].concat(ALLOWED_ROUTES.map(function (route) { return '- ' + route })).join('\\n'),
args: {
@@ -0,0 +1,101 @@
import { z } from 'zod'
import { getOpenCodeModelStatePath } from '@opencode-manager/shared/config/env'
import { readJsonSafe, withFileLock, writeJsonAtomic } from '../utils/atomic-json'
import { logger } from '../utils/logger'
export const ModelSelectionSchema = z.object({
providerID: z.string().min(1),
modelID: z.string().min(1),
})
export const ModelStateSchema = z.object({
recent: z.array(ModelSelectionSchema).default([]),
favorite: z.array(ModelSelectionSchema).default([]),
variant: z.record(z.string(), z.string().optional()).default({}),
}).passthrough()
export interface ModelSelectionRecord {
providerID: string
modelID: string
}
export interface OpenCodeModelStateRecord {
recent: ModelSelectionRecord[]
favorite: ModelSelectionRecord[]
variant: Record<string, string | undefined>
}
export const MAX_RECENT_MODELS = 10
function createEmptyState(): OpenCodeModelStateRecord {
return { recent: [], favorite: [], variant: {} }
}
function toRecord(data: z.infer<typeof ModelStateSchema>): OpenCodeModelStateRecord {
return { recent: data.recent, favorite: data.favorite, variant: data.variant }
}
export async function readOpenCodeModelState(): Promise<OpenCodeModelStateRecord> {
const raw = await readJsonSafe<unknown>(getOpenCodeModelStatePath(), null)
const parsed = ModelStateSchema.safeParse(raw)
if (!parsed.success) {
if (raw !== null) {
logger.warn('OpenCode model state file has invalid structure', parsed.error)
}
return createEmptyState()
}
return toRecord(parsed.data)
}
export function addRecentModel(state: OpenCodeModelStateRecord, model: ModelSelectionRecord): OpenCodeModelStateRecord {
const deduped = [
model,
...state.recent.filter(m => m.providerID !== model.providerID || m.modelID !== model.modelID),
]
return { ...state, recent: deduped.slice(0, MAX_RECENT_MODELS) }
}
export function removeRecentModel(state: OpenCodeModelStateRecord, model: ModelSelectionRecord): OpenCodeModelStateRecord {
return {
...state,
recent: state.recent.filter(m => m.providerID !== model.providerID || m.modelID !== model.modelID),
}
}
export function toggleFavoriteModel(state: OpenCodeModelStateRecord, model: ModelSelectionRecord): OpenCodeModelStateRecord {
const exists = state.favorite.some(
m => m.providerID === model.providerID && m.modelID === model.modelID,
)
const favorite = exists
? state.favorite.filter(m => m.providerID !== model.providerID || m.modelID !== model.modelID)
: [...state.favorite, model]
return { ...state, favorite }
}
export async function updateOpenCodeModelState(
mutate: (state: OpenCodeModelStateRecord) => OpenCodeModelStateRecord,
): Promise<OpenCodeModelStateRecord> {
const modelStatePath = getOpenCodeModelStatePath()
return withFileLock(modelStatePath, async () => {
const raw = await readJsonSafe<unknown>(modelStatePath, {})
const parsed = ModelStateSchema.safeParse(raw)
const current = parsed.success ? toRecord(parsed.data) : createEmptyState()
const next = mutate(current)
const rawObject = raw && typeof raw === 'object' && !Array.isArray(raw)
? raw as Record<string, unknown>
: {}
await writeJsonAtomic(modelStatePath, {
...rawObject,
recent: next.recent,
favorite: next.favorite,
variant: next.variant,
})
return next
})
}
@@ -3,7 +3,8 @@ import { lstat, realpath } from 'fs/promises'
import path from 'path'
import { parseJsonc } from '@opencode-manager/shared/utils'
import { logger } from '../utils/logger'
import { mkdirSafe, writeFileAtomic } from '../utils/fs-safe'
import { existingFileMode, mkdirSafe, writeFileAtomic } from '../utils/fs-safe'
import { withFileLock } from '../utils/atomic-json'
import { getOpenCodePluginDir } from './opencode/plugin-registry'
import {
isRecord,
@@ -242,14 +243,6 @@ async function restorePluginEntries(dir: string): Promise<void> {
}
}
async function existingFileMode(filePath: string): Promise<number | undefined> {
try {
return (await fs.stat(filePath)).mode & 0o777
} catch {
return undefined
}
}
async function restoreEnforcementConfigSections(configPath: string): Promise<void> {
const backupPath = `${configPath}${PLUGIN_CONFIG_BACKUP_SUFFIX}`
if (!(await pathExists(backupPath))) return
@@ -293,7 +286,8 @@ async function restoreEnforcementConfigSections(configPath: string): Promise<voi
const restored = restoreEnforcementSections(currentConfig, removed)
const restoredContent = JSON.stringify(restored, null, 2)
if (restoredContent !== currentContent) {
await writeFileAtomic(configPath, restoredContent, { mode: await existingFileMode(configPath) })
const mode = await existingFileMode(configPath)
await withFileLock(configPath, () => writeFileAtomic(configPath, restoredContent, { mode }))
}
await fs.rm(backupPath, { force: true })
}
-14
View File
@@ -1,7 +1,6 @@
import { opencodeServerManager } from './opencode-single-server'
import type { OpenCodeSupervisor } from './opencode-supervisor'
import type { OpenCodeRestartCoordinator } from './opencode-restart-coordinator'
import { logger } from '../utils/logger'
let restartCoordinator: OpenCodeRestartCoordinator | null = null
@@ -68,19 +67,6 @@ export async function restartOpenCode(supervisor?: OpenCodeSupervisor): Promise<
return { resumedSessionIDs: [] }
}
export async function restartOpenCodeAfterCommit(
supervisor?: OpenCodeSupervisor,
): Promise<{ restartFailed: boolean; restartError?: string }> {
try {
await restartOpenCode(supervisor)
return { restartFailed: false }
} catch (error) {
const restartError = error instanceof Error ? error.message : String(error)
logger.error('OpenCode restart failed after the change was persisted', error)
return { restartFailed: true, restartError }
}
}
/**
* Reloads OpenCode configuration via the non-disruptive API patch. This does
* NOT drop the server process, so active sessions keep running and there is
+50 -32
View File
@@ -26,12 +26,17 @@ import {
getOpenCodeTmpHome,
ENV,
} from '@opencode-manager/shared/config/env'
import { parseJsonc } from '@opencode-manager/shared/utils'
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 { writeFileContent } from './file-operations'
import {
readOpenCodeConfigFile,
toOpenCodeConfigValidationIssues,
withOpenCodeConfigLock,
writeOpenCodeConfigFile,
} from './opencode-config-file'
import { getOrCreateInternalToken } from './internal-token'
import { installManagedPlugins } from './opencode/plugin-registry'
import { getOpenCodePluginDiscoveryHome, restoreQuarantinedOpenCodePlugins } from './opencode-plugin-quarantine'
@@ -615,7 +620,7 @@ class OpenCodeServerManager {
}
logger.warn('Failed to install a generated OpenCode plugin (sandboxing is disabled):', error)
}
const configuredPlugins = await this.getConfiguredPlugins(openCodeConfigPath)
const configuredPlugins = await this.getConfiguredPlugins()
await this.installConfiguredPlugins(configuredPlugins)
const configuredPluginCount = configuredPlugins.length
const openCodeExecutable = resolveOpenCodeExecutable() ?? 'opencode'
@@ -957,13 +962,13 @@ class OpenCodeServerManager {
return options !== null && typeof options === 'object' && !Array.isArray(options)
}
private async getConfiguredPlugins(configPath: string): Promise<OpenCodePluginSpec[]> {
private async getConfiguredPlugins(): Promise<OpenCodePluginSpec[]> {
try {
const content = await fs.readFile(configPath, 'utf-8')
const config = parseJsonc(content) as { plugin?: unknown }
if (!Array.isArray(config.plugin)) return []
return config.plugin
.filter((plugin): plugin is OpenCodePluginSpec => this.isOpenCodePluginSpec(plugin))
const file = await readOpenCodeConfigFile()
const plugin = file?.content.plugin
if (!Array.isArray(plugin)) return []
return plugin
.filter((entry): entry is OpenCodePluginSpec => this.isOpenCodePluginSpec(entry))
} catch {
return []
}
@@ -1043,31 +1048,44 @@ class OpenCodeServerManager {
try {
logger.info('Reloading OpenCode configuration (via API)')
try {
const configPath = getOpenCodeConfigFilePath()
const fileContent = await fs.readFile(configPath, 'utf-8')
const fileConfig = parseJsonc(fileContent) as Record<string, unknown>
logger.info(`Read config from file for reload: ${configPath}`)
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 || []
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}`)
await withOpenCodeConfigLock(async () => {
const file = await readOpenCodeConfigFile()
if (file === null) {
throw new Error(`OpenCode config file not found: ${getOpenCodeConfigFilePath()}`)
}
if (removedFields.length > 0) {
logger.info(`Removed fields during config reload: ${removedFields.join(', ')}`)
}
throw new ConfigReloadError(errorMessage, validationIssues, removedFields)
}
logger.info(`Read config from file for reload: ${file.path}`)
if (patchResult.removedFields && patchResult.removedFields.length > 0 && patchResult.appliedConfig) {
await writeFileContent(configPath, JSON.stringify(patchResult.appliedConfig, null, 2))
logger.info(`Persisted cleaned config to ${configPath} after removing fields: ${patchResult.removedFields.join(', ')}`)
}
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))
+9 -47
View File
@@ -1,8 +1,8 @@
import path from 'path'
import type { SettingsService } from './settings'
import { logger } from '../utils/logger'
import { ensureDirectoryExists, writeFileContent } from './file-operations'
import { getOpenCodeConfigFilePath, getWorkspacePath, ENV } from '@opencode-manager/shared/config/env'
import { ENV } from '@opencode-manager/shared/config/env'
import { archiveBrokenOpenCodeConfigFile, writeHealthWatchArtifact } from './opencode-config-file'
import { restoreLastKnownGoodOpenCodeConfig, seedOpenCodeConfigFile } from './opencode-config-apply'
import type { OpenCodeServerManager } from './opencode-single-server'
export const OPENCODE_LIFECYCLE_STATES = [
@@ -55,7 +55,6 @@ export interface OpenCodeLifecycleStatus {
interface OpenCodeSupervisorOptions {
pollIntervalMs?: number
failureThreshold?: number
userId?: string
watchEnabled?: boolean
}
@@ -319,63 +318,30 @@ export class OpenCodeSupervisor {
}
private async captureDebugSnapshot(): Promise<void> {
const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
const debugPath = path.join(getWorkspacePath(), '.opencode', 'state', 'health-watch', `opencode-health-${timestamp}.json`)
const payload = JSON.stringify({
await writeHealthWatchArtifact('opencode-health', (timestamp) => JSON.stringify({
capturedAt: timestamp,
startupError: this.openCodeServerManager.getLastStartupError(),
lifecycleState: this.state,
attemptedRecoveryActions: this.attemptedRecoveryActions,
}, null, 2)
await ensureDirectoryExists(path.dirname(debugPath))
await writeFileContent(debugPath, payload)
}, null, 2))
}
private async rollbackToLastKnownGood(): Promise<void> {
this.settingsService.archiveBrokenConfig(this.userId)
const lastGood = this.settingsService.restoreToLastKnownGoodConfig(this.userId)
if (!lastGood) {
await archiveBrokenOpenCodeConfigFile()
const restored = await restoreLastKnownGoodOpenCodeConfig(this.settingsService)
if (!restored) {
throw new Error('No last known good config available')
}
const config = this.settingsService.updateOpenCodeConfig(lastGood.configName, { content: lastGood.content }, this.userId)
if (!config) {
throw new Error(`Failed to restore OpenCode config '${lastGood.configName}'`)
}
await this.writeConfig(lastGood.content)
this.openCodeServerManager.clearStartupError()
await this.openCodeServerManager.restart()
}
private async seedDefaultConfig(): Promise<void> {
const seedConfig = JSON.stringify({ $schema: 'https://opencode.ai/config.json' }, null, 2)
const defaultConfig = this.settingsService.getDefaultOpenCodeConfig(this.userId)
if (defaultConfig) {
this.settingsService.updateOpenCodeConfig(defaultConfig.name, { content: seedConfig }, this.userId)
} else {
this.settingsService.createOpenCodeConfig(
{
name: 'default',
content: seedConfig,
isDefault: true,
},
this.userId,
)
}
await this.writeConfig(seedConfig)
await seedOpenCodeConfigFile()
this.openCodeServerManager.clearStartupError()
await this.openCodeServerManager.restart()
}
private async writeConfig(content: string): Promise<void> {
const configPath = getOpenCodeConfigFilePath()
await writeFileContent(configPath, content)
}
private startWatching(): void {
if (!this.isWatchEnabled()) {
logger.info('OpenCode supervisor health polling disabled')
@@ -429,8 +395,4 @@ export class OpenCodeSupervisor {
private getNextRecoveryAction(): OpenCodeRecoveryAction | null {
return OPENCODE_RECOVERY_ACTIONS.find((action) => !this.attemptedRecoveryActions.includes(action)) ?? null
}
private get userId(): string {
return this.options.userId ?? 'default'
}
}
@@ -1,5 +1,6 @@
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 = {
@@ -150,17 +151,41 @@ function parseErrorResponse(responseText: string): { details: PatchConfigValidat
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 client.forward({
method: 'PATCH',
path: '/config',
body: JSON.stringify(config),
headers: { 'Content-Type': 'application/json' },
})
const response = await forwardConfigPatch(client, config)
if (response.ok) {
logger.info('Patched OpenCode config via API')
@@ -202,12 +227,7 @@ export async function patchConfigWithRecovery(
}
logger.info(`Retrying config patch after removing ${removedFields.length} problematic field(s): ${removedFields.join(', ')}`)
const retryResponse = await client.forward({
method: 'PATCH',
path: '/config',
body: JSON.stringify(cleanedConfig),
headers: { 'Content-Type': 'application/json' },
})
const retryResponse = await forwardConfigPatch(client, cleanedConfig)
if (retryResponse.ok) {
logger.info('Patched OpenCode config via API after removing invalid fields')
@@ -230,6 +250,11 @@ export async function patchConfigWithRecovery(
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 }
+9 -17
View File
@@ -1,5 +1,5 @@
import fs from 'fs/promises'
import { existsSync, rmSync, realpathSync } from 'node:fs'
import { existsSync, rmSync } from 'node:fs'
import { executeCommand } from '../utils/process'
import { ensureDirectoryExists } from './file-operations'
import { createRepo, getRepoByLocalPath, getRepoBySourcePath, getRepoById, updateRepoStatus, updateRepoBranch, updateLastPulled, deleteRepo, getRepoByUrlAndBranch } from '../db/queries'
@@ -19,20 +19,12 @@ import { listRepos } from '../db/queries'
import { listActiveScheduleRunWorkspaces } from '../db/schedules'
import { SettingsService } from './settings'
import type { OpenCodeClient } from './opencode/client'
import { mkdirSafe } from '../utils/fs-safe'
import { canonicalPathSync, mkdirSafe } from '../utils/fs-safe'
const GIT_CLONE_TIMEOUT = 300000
const DEFAULT_DISCOVERY_MAX_DEPTH = 4
const DISCOVERY_SKIP_DIRECTORIES = new Set(['.git', 'node_modules'])
function canonical(dir: string): string {
try {
return realpathSync(path.resolve(dir))
} catch {
return path.resolve(dir)
}
}
function enhanceCloneError(error: unknown, repoUrl: string, originalMessage: string): Error {
const message = originalMessage.toLowerCase()
@@ -1224,10 +1216,10 @@ export async function getSiblingRepos(
// Workspaces that are git main checkouts (not linked worktrees) are also
// excluded so the project's origin/main repository can never be surfaced
// as deletable.
const knownDirectories = new Set(repoSiblings.map((repo) => canonical(repo.fullPath)))
const targetDirectory = canonical(target.fullPath)
const reposRoot = canonical(getReposPath())
const scheduleWorktreeRoot = canonical(getScheduleWorktreesPath())
const knownDirectories = new Set(repoSiblings.map((repo) => canonicalPathSync(path.resolve(repo.fullPath))))
const targetDirectory = canonicalPathSync(path.resolve(target.fullPath))
const reposRoot = canonicalPathSync(path.resolve(getReposPath()))
const scheduleWorktreeRoot = canonicalPathSync(path.resolve(getScheduleWorktreesPath()))
// Schedule runs may create their isolated worktree via the OpenCode workspace
// API, which places it outside getScheduleWorktreesPath(). Exclude any live
@@ -1236,14 +1228,14 @@ export async function getSiblingRepos(
const activeRuns = listActiveScheduleRunWorkspaces(database)
const activeRunWorkspaceIds = new Set(activeRuns.map((run) => run.workspaceId).filter((id): id is string => id !== null))
const activeRunDirectories = new Set(
activeRuns.map((run) => run.worktreePath).filter((p): p is string => p !== null).map((p) => canonical(p)),
activeRuns.map((run) => run.worktreePath).filter((p): p is string => p !== null).map((p) => canonicalPathSync(path.resolve(p))),
)
const candidates = workspaces.filter((workspace) => {
if (workspace.projectID !== targetProjectId) return false
if (!workspace.directory) return false
const workspaceDirectory = canonical(workspace.directory)
const workspaceDirectory = canonicalPathSync(path.resolve(workspace.directory))
if (workspaceDirectory === targetDirectory) return false
if (workspaceDirectory === reposRoot) return false
if (workspaceDirectory.startsWith(`${scheduleWorktreeRoot}${path.sep}`)) return false
@@ -1262,7 +1254,7 @@ export async function getSiblingRepos(
candidates
.filter((_, index) => !mainChecks[index])
.forEach((workspace) => {
const directory = canonical(workspace.directory!)
const directory = canonicalPathSync(path.resolve(workspace.directory!))
if (!uniqueWorkspaces.has(directory)) {
uniqueWorkspaces.set(directory, workspace)
}
+11 -493
View File
@@ -1,49 +1,17 @@
import { Database } from 'bun:sqlite'
import { unlinkSync, existsSync } from 'fs'
import { getOpenCodeConfigFilePath } from '@opencode-manager/shared/config/env'
import { logger } from '../utils/logger'
import { parseJsonc } from '@opencode-manager/shared/utils'
import { z } from 'zod'
import { encryptSecret, decryptSecret } from '../utils/crypto'
import { ENV } from '@opencode-manager/shared/config/env'
import type {
UserPreferences,
SettingsResponse,
CreateOpenCodeConfigRequest,
UpdateOpenCodeConfigRequest
import type {
UserPreferences,
SettingsResponse,
} from '../types/settings'
import {
UserPreferencesSchema,
OpenCodeConfigSchema,
DEFAULT_USER_PREFERENCES,
} from '../types/settings'
interface OpenCodeConfigValidationIssue {
path: string
message: string
}
interface OpenCodeConfigWithRaw {
id: number
name: string
content: Record<string, unknown>
rawContent: string
validationIssues?: OpenCodeConfigValidationIssue[]
isValid: boolean
isDefault: boolean
createdAt: number
updatedAt: number
}
interface OpenCodeConfigResponseWithRaw {
configs: OpenCodeConfigWithRaw[]
defaultConfig: OpenCodeConfigWithRaw | null
}
interface CreateOpenCodeConfigOptions {
suppressAutoDefault?: boolean
}
interface OpenCodeServerPasswordState {
value: string
createdAt: number
@@ -56,37 +24,6 @@ export class SettingsService {
constructor(private db: Database) {}
private getValidationIssues(error: z.ZodError): OpenCodeConfigValidationIssue[] {
return error.issues.map((issue) => ({
path: issue.path.length > 0 ? issue.path.join('.') : 'root',
message: issue.message,
}))
}
private parseStoredConfig(rawContent: string, configName: string): { content: Record<string, unknown>; validationIssues?: OpenCodeConfigValidationIssue[]; isValid: boolean } {
const parsed = parseJsonc(rawContent)
const content = parsed && typeof parsed === 'object' && !Array.isArray(parsed)
? parsed as Record<string, unknown>
: {}
const validated = OpenCodeConfigSchema.safeParse(parsed)
if (validated.success) {
return {
content: validated.data as Record<string, unknown>,
isValid: true,
}
}
const validationIssues = this.getValidationIssues(validated.error)
logger.error(`Failed to validate config ${configName}: ${validationIssues.map((issue) => `${issue.path}: ${issue.message}`).join('; ')}`)
return {
content,
validationIssues,
isValid: false,
}
}
initializeLastKnownGoodConfig(userId: string = 'default'): void {
const settings = this.getSettings(userId)
if (settings.preferences.lastKnownGoodConfig) {
@@ -102,6 +39,10 @@ export class SettingsService {
}
}
getLastKnownGoodConfig(): string | null {
return SettingsService.lastKnownGoodConfigContent
}
getSettings(userId: string = 'default'): SettingsResponse {
const row = this.db
.query('SELECT preferences, updated_at FROM user_preferences WHERE user_id = ?')
@@ -177,433 +118,10 @@ export class SettingsService {
}
}
getOpenCodeConfigs(userId: string = 'default'): OpenCodeConfigResponseWithRaw {
const rows = this.db
.query('SELECT * FROM opencode_configs WHERE user_id = ? ORDER BY created_at DESC')
.all(userId) as Array<{
id: number
user_id: string
config_name: string
config_content: string
is_default: boolean
created_at: number
updated_at: number
}>
const configs: OpenCodeConfigWithRaw[] = []
let defaultConfig: OpenCodeConfigWithRaw | null = null
for (const row of rows) {
try {
const rawContent = row.config_content
const parsedConfig = this.parseStoredConfig(rawContent, row.config_name)
const config: OpenCodeConfigWithRaw = {
id: row.id,
name: row.config_name,
content: parsedConfig.content,
rawContent: rawContent,
validationIssues: parsedConfig.validationIssues,
isValid: parsedConfig.isValid,
isDefault: Boolean(row.is_default),
createdAt: row.created_at,
updatedAt: row.updated_at,
}
configs.push(config)
if (config.isDefault) {
defaultConfig = config
}
} catch (error) {
logger.error(`Failed to parse config ${row.config_name}:`, error)
}
}
return {
configs,
defaultConfig,
}
}
createOpenCodeConfig(
request: CreateOpenCodeConfigRequest,
userId: string = 'default',
options: CreateOpenCodeConfigOptions = {}
): OpenCodeConfigWithRaw {
// Check for existing config with the same name
const existing = this.getOpenCodeConfigByName(request.name, userId)
if (existing) {
throw new Error(`Config with name '${request.name}' already exists`)
}
const rawContent = typeof request.content === 'string'
? request.content
: JSON.stringify(request.content, null, 2)
const parsedContent = typeof request.content === 'string'
? parseJsonc(request.content)
: request.content
const contentValidated = OpenCodeConfigSchema.parse(parsedContent)
const now = Date.now()
const existingCount = this.db
.query('SELECT COUNT(*) as count FROM opencode_configs WHERE user_id = ?')
.get(userId) as { count: number }
const shouldBeDefault = request.isDefault || (!options.suppressAutoDefault && existingCount.count === 0)
if (shouldBeDefault) {
this.db
.query('UPDATE opencode_configs SET is_default = FALSE WHERE user_id = ?')
.run(userId)
}
const result = this.db
.query(
`INSERT INTO opencode_configs (user_id, config_name, config_content, is_default, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?)`
)
.run(
userId,
request.name,
rawContent,
shouldBeDefault,
now,
now
)
const config: OpenCodeConfigWithRaw = {
id: result.lastInsertRowid as number,
name: request.name,
content: contentValidated as Record<string, unknown>,
rawContent: rawContent,
isValid: true,
isDefault: shouldBeDefault,
createdAt: now,
updatedAt: now,
}
logger.info(`Created OpenCode config '${config.name}' for user: ${userId}`)
return config
}
updateOpenCodeConfig(
configName: string,
request: UpdateOpenCodeConfigRequest,
userId: string = 'default'
): OpenCodeConfigWithRaw | null {
const existing = this.db
.query('SELECT * FROM opencode_configs WHERE user_id = ? AND config_name = ?')
.get(userId, configName) as {
id: number
config_content: string
is_default: boolean
created_at: number
} | undefined
if (!existing) {
return null
}
const rawContent = typeof request.content === 'string'
? request.content
: JSON.stringify(request.content, null, 2)
const parsedContent = typeof request.content === 'string'
? parseJsonc(request.content)
: request.content
const contentValidated = OpenCodeConfigSchema.parse(parsedContent)
const now = Date.now()
if (request.isDefault) {
this.db
.query('UPDATE opencode_configs SET is_default = FALSE WHERE user_id = ?')
.run(userId)
}
this.db
.query(
`UPDATE opencode_configs
SET config_content = ?, is_default = ?, updated_at = ?
WHERE user_id = ? AND config_name = ?`
)
.run(
rawContent,
request.isDefault !== undefined ? request.isDefault : existing.is_default,
now,
userId,
configName
)
const config: OpenCodeConfigWithRaw = {
id: existing.id,
name: configName,
content: contentValidated as Record<string, unknown>,
rawContent: rawContent,
isValid: true,
isDefault: request.isDefault !== undefined ? request.isDefault : existing.is_default,
createdAt: existing.created_at,
updatedAt: now,
}
logger.info(`Updated OpenCode config '${configName}' for user: ${userId}`)
return config
}
deleteOpenCodeConfig(configName: string, userId: string = 'default'): boolean {
const result = this.db
.query('DELETE FROM opencode_configs WHERE user_id = ? AND config_name = ?')
.run(userId, configName)
const deleted = result.changes > 0
if (deleted) {
logger.info(`Deleted OpenCode config '${configName}' for user: ${userId}`)
this.ensureSingleConfigIsDefault(userId)
}
return deleted
}
setDefaultOpenCodeConfig(configName: string, userId: string = 'default'): OpenCodeConfigWithRaw | null {
const existing = this.db
.query('SELECT * FROM opencode_configs WHERE user_id = ? AND config_name = ?')
.get(userId, configName) as {
id: number
config_content: string
created_at: number
} | undefined
if (!existing) {
return null
}
this.db
.query('UPDATE opencode_configs SET is_default = FALSE WHERE user_id = ?')
.run(userId)
const now = Date.now()
this.db
.query(
`UPDATE opencode_configs
SET is_default = TRUE, updated_at = ?
WHERE user_id = ? AND config_name = ?`
)
.run(now, userId, configName)
try {
const rawContent = existing.config_content
const parsedConfig = this.parseStoredConfig(rawContent, configName)
const config: OpenCodeConfigWithRaw = {
id: existing.id,
name: configName,
content: parsedConfig.content,
rawContent: rawContent,
validationIssues: parsedConfig.validationIssues,
isValid: parsedConfig.isValid,
isDefault: true,
createdAt: existing.created_at,
updatedAt: now,
}
logger.info(`Set '${configName}' as default OpenCode config for user: ${userId}`)
return config
} catch (error) {
logger.error(`Failed to parse config ${configName}:`, error)
return null
}
}
getDefaultOpenCodeConfig(userId: string = 'default'): OpenCodeConfigWithRaw | null {
const row = this.db
.query('SELECT * FROM opencode_configs WHERE user_id = ? AND is_default = TRUE')
.get(userId) as {
id: number
config_name: string
config_content: string
created_at: number
updated_at: number
} | undefined
if (!row) {
return null
}
try {
const rawContent = row.config_content
const parsedConfig = this.parseStoredConfig(rawContent, row.config_name)
return {
id: row.id,
name: row.config_name,
content: parsedConfig.content,
rawContent: rawContent,
validationIssues: parsedConfig.validationIssues,
isValid: parsedConfig.isValid,
isDefault: true,
createdAt: row.created_at,
updatedAt: row.updated_at,
}
} catch (error) {
logger.error(`Failed to parse default config:`, error)
return null
}
}
getOpenCodeConfigByName(configName: string, userId: string = 'default'): OpenCodeConfigWithRaw | null {
const row = this.db
.query('SELECT * FROM opencode_configs WHERE user_id = ? AND config_name = ?')
.get(userId, configName) as {
id: number
config_name: string
config_content: string
is_default: boolean
created_at: number
updated_at: number
} | undefined
if (!row) {
return null
}
try {
const rawContent = row.config_content
const parsedConfig = this.parseStoredConfig(rawContent, configName)
return {
id: row.id,
name: row.config_name,
content: parsedConfig.content,
rawContent: rawContent,
validationIssues: parsedConfig.validationIssues,
isValid: parsedConfig.isValid,
isDefault: Boolean(row.is_default),
createdAt: row.created_at,
updatedAt: row.updated_at,
}
} catch (error) {
logger.error(`Failed to parse config ${configName}:`, error)
return null
}
}
getOpenCodeConfigContent(configName: string, userId: string = 'default'): string | null {
const row = this.db
.query('SELECT config_content FROM opencode_configs WHERE user_id = ? AND config_name = ?')
.get(userId, configName) as { config_content: string } | undefined
if (!row) {
logger.error(`Config '${configName}' not found for user ${userId}`)
return null
}
return row.config_content
}
ensureSingleConfigIsDefault(userId: string = 'default'): void {
const hasDefault = this.db
.query('SELECT COUNT(*) as count FROM opencode_configs WHERE user_id = ? AND is_default = TRUE')
.get(userId) as { count: number }
if (hasDefault.count === 0) {
const firstConfig = this.db
.query('SELECT config_name FROM opencode_configs WHERE user_id = ? ORDER BY created_at ASC LIMIT 1')
.get(userId) as { config_name: string } | undefined
if (firstConfig) {
this.db
.query('UPDATE opencode_configs SET is_default = TRUE WHERE user_id = ? AND config_name = ?')
.run(userId, firstConfig.config_name)
logger.info(`Auto-set '${firstConfig.config_name}' as default (only config)`)
}
}
}
saveLastKnownGoodConfig(userId: string = 'default'): void {
const config = this.getDefaultOpenCodeConfig(userId)
if (config) {
SettingsService.lastKnownGoodConfigContent = config.rawContent
this.persistLastKnownGoodConfig(userId)
logger.info(`Saved last known good config: ${config.name}`)
}
}
archiveBrokenConfig(userId: string = 'default'): string | null {
const current = this.getDefaultOpenCodeConfig(userId)
if (!current) {
return null
}
const ts = new Date().toISOString().replace(/[:.]/g, '-')
const backupName = `${current.name}-broken-${ts}`
try {
this.createOpenCodeConfig(
{
name: backupName,
content: current.rawContent,
isDefault: false,
},
userId,
{ suppressAutoDefault: true },
)
logger.warn(`Archived broken OpenCode config as '${backupName}'`)
return backupName
} catch (error) {
logger.error('Failed to archive broken config:', error)
return null
}
}
restoreToLastKnownGoodConfig(userId: string = 'default'): { configName: string; content: string } | null {
if (!SettingsService.lastKnownGoodConfigContent) {
logger.warn('No last known good config available for rollback')
return null
}
const configs = this.getOpenCodeConfigs(userId)
const defaultConfig = configs.defaultConfig
if (!defaultConfig) {
logger.error('Cannot rollback: no default config found')
return null
}
logger.info(`Restoring to last known good config for: ${defaultConfig.name}`)
return {
configName: defaultConfig.name,
content: SettingsService.lastKnownGoodConfigContent
}
}
rollbackToLastKnownGoodHealth(userId: string = 'default'): string | null {
const lastGood = this.restoreToLastKnownGoodConfig(userId)
if (!lastGood) {
return null
}
this.updateOpenCodeConfig(lastGood.configName, { content: lastGood.content }, userId)
return lastGood.configName
}
deleteFilesystemConfig(): boolean {
const configPath = getOpenCodeConfigFilePath()
if (!existsSync(configPath)) {
logger.warn('Config file does not exist:', configPath)
return false
}
try {
unlinkSync(configPath)
logger.info('Deleted filesystem config to allow server startup:', configPath)
return true
} catch (error) {
logger.error('Failed to delete config file:', error)
return false
}
saveLastKnownGoodConfig(rawContent: string): void {
SettingsService.lastKnownGoodConfigContent = rawContent
this.persistLastKnownGoodConfig()
logger.info('Saved last known good config')
}
getOpenCodeServerPassword(): string {