fix: keep config references on save and apply review batch 2 fixes (OM-179)

This commit is contained in:
Chris Scott committed 2026-11-02 23:21:33 -05:00
1 parent 49bb4ebd36
commit 8a6fd56e9a
17 files changed
+524 -60

No files matched your search

+78 -43
View File
@@ -19,7 +19,8 @@ import type { OpenCodeAgentConfig, OpenCodeApi, OpenCodeConfigInfo } from '@open
import { validateOpenCodeConfig } from '@opencode-manager/shared/opencode/config-validation'
import type { Database } from 'bun:sqlite'
import { ensureAssistantRepo } from '../db/queries'
import { applyOpenCodeConfigEdits, removeOpenCodeConfigProperty, type OpenCodeConfigPathOperation } from './opencode-config-file'
import { applyOpenCodeConfigEdits, removeOpenCodeConfigProperty, V1_ENTITY_PATHS, type OpenCodeConfigPathOperation } from './opencode-config-file'
import { readConfigValueAtPath, restoreOpenCodeConfigReferences } from './opencode-config-references'
import { readOpenCodeConfigDocuments } from './opencode-config-effective'
import { logger } from '../utils/logger'
@@ -788,9 +789,9 @@ Read the merged persisted global configuration and its source files. Returns \`4
### PATCH /opencode-config
Change only the paths the user asked for. Send a nested \`patch\` object naming those paths and the values to set; every path you do not name is left untouched, and a \`null\` value removes a path. Only changed fields are patched into the preferred existing source: JSONC, then JSON. New installations use opencode.jsonc. Unchanged inherited values and comments are preserved.
Change only the paths the user asked for. Send a nested \`patch\` object naming those paths and the values to set; a path you do not name keeps its current value, and a \`null\` value removes a path. Naming a v2 entity (\`agents.<name>\`, \`commands.<name>\`, \`providers.<id>\`, \`mcp.servers.<name>\`, or \`permissions\`) also deletes its v1 counterpart (\`agent.<name>\`, \`command.<name>\`, \`provider.<id>\`, \`mcp.<name>\`, or \`permission\`) in the same edit. \`{env:…}\` and \`{file:…}\` references in fields whose value is sent back unchanged are kept. Only changed fields are patched into the preferred existing source: JSONC, then JSON. New installations use opencode.jsonc. Unchanged inherited values and comments are preserved.
Send \`expectedRevision\` from a read. A \`409\` means the source files changed: read again and reconcile rather than retrying stale content.
Send \`expectedRevision\` from a read. A \`409\` means either \`expectedRevision\` is stale or the v1 entry to remove exists only in a lower-priority config source (the \`OpenCodeConfigShadowedRemovalError\` case): read again and reconcile rather than retrying stale content.
**Request Body:**
\`\`\`ts
@@ -818,11 +819,11 @@ Send \`expectedRevision\` from a read. A \`409\` means the source files changed:
\`\`\`
**Response:**
Returns the refreshed merged configuration and source files, with secrets redacted. A semantic change is applied automatically: the Manager reloads OpenCode without restarting the server, so agents, permissions, providers, models, and plugins take effect on the next message and running sessions keep running. An \`mcp\` change is applied the same way, and only the servers whose configuration changed reconnect. Comment-only changes do nothing. Saving never silently drops unsupported fields.
Returns the refreshed merged configuration and source files, with secrets redacted. A semantic change is applied automatically: the Manager reloads OpenCode without restarting the server, so agents, permissions, providers, models, and plugins take effect on the next message and running sessions keep running. An \`mcp\` change is applied the same way, and only the servers whose configuration changed reconnect. Comment-only changes do nothing.
The response adds \`restartRequired: true\` only when the automatic reload failed, for example because the OpenCode server is unavailable.
Returns \`400\` for invalid configuration or a \`<redacted>\` value (\`paths\` lists them), and \`409\` for a stale revision.
Returns \`400\` for invalid configuration or a \`<redacted>\` value (\`paths\` lists them), and \`409\` when \`expectedRevision\` is stale or the v1 entry to remove exists only in a lower-priority config source.
### GET /opencode-config/mcp
@@ -1359,9 +1360,26 @@ function parseAssistantOpenCodeConfig(rawContent: string): Record<string, unknow
}
}
/**
* Resolves the v1 container that OpenCode converts into the given v2 container.
*/
function resolveV1EntityPath(v2Path: readonly string[]): string[] {
const mapping = V1_ENTITY_PATHS.find(
(entry) => entry.v2Path.length === v2Path.length && entry.v2Path.every((segment, index) => segment === v2Path[index]),
)
if (mapping === undefined) {
throw new Error(`No v1 config path is defined for ${v2Path.join('.')}`)
}
return [...mapping.v1Path]
}
const ASSISTANT_V1_AGENT_PATH = resolveV1EntityPath(['agents'])
const ASSISTANT_V1_PERMISSION_PATH = resolveV1EntityPath(['permissions'])
function hasAssistantV1OpenCodeConfig(config: Record<string, unknown>): boolean {
if (config.permission !== undefined) return true
return isRecord(config.agent) && isRecord(config.agent.assistant)
if (readConfigValueAtPath(config, ASSISTANT_V1_PERMISSION_PATH) !== undefined) return true
const v1Agents = readConfigValueAtPath(config, ASSISTANT_V1_AGENT_PATH)
return isRecord(v1Agents) && isRecord(v1Agents[ASSISTANT_DEFAULT_AGENT_NAME])
}
function assistantOpenCodeConfigNeedsRepair(config: OpenCodeConfigInfo): boolean {
@@ -1377,9 +1395,7 @@ function assistantOpenCodeConfigNeedsRepair(config: OpenCodeConfigInfo): boolean
}
function assistantOpenCodeConfigHasGeneratedAgentPersona(config: OpenCodeConfigInfo): boolean {
const agent = config.agents?.[ASSISTANT_DEFAULT_AGENT_NAME]
if (typeof agent !== 'object' || agent === null) return false
return matchesGeneratedAssistantAgentPrompt(agent.system)
return normalizeAssistantAgent(config.agents?.[ASSISTANT_DEFAULT_AGENT_NAME]) !== undefined
}
function resolveValidAssistantMode(agent: unknown): 'primary' | 'all' {
@@ -1387,15 +1403,24 @@ function resolveValidAssistantMode(agent: unknown): 'primary' | 'all' {
return mode === 'primary' || mode === 'all' ? mode : 'primary'
}
/**
* Reduces a generated assistant persona to a mode-only agent, leaving a customized persona to the caller.
*/
function normalizeAssistantAgent(agent: unknown): OpenCodeAgentConfig | undefined {
if (!isRecord(agent) || !matchesGeneratedAssistantAgentPrompt(agent.system)) return undefined
return { mode: resolveValidAssistantMode(agent) }
}
function stripGeneratedAssistantAgentPersona(config: OpenCodeConfigInfo): OpenCodeConfigInfo {
const existingAssistantAgent = config.agents?.[ASSISTANT_DEFAULT_AGENT_NAME]
const validMode = resolveValidAssistantMode(existingAssistantAgent)
return {
...config,
agents: {
...(config.agents ?? {}),
[ASSISTANT_DEFAULT_AGENT_NAME]: { mode: validMode },
[ASSISTANT_DEFAULT_AGENT_NAME]: normalizeAssistantAgent(existingAssistantAgent) ?? {
mode: resolveValidAssistantMode(existingAssistantAgent),
},
},
}
}
@@ -1404,20 +1429,10 @@ function mergeAssistantOpenCodeConfig(existing?: OpenCodeConfigInfo): OpenCodeCo
const generated = buildAssistantOpenCodeConfig()
const existingAssistantAgent = existing?.agents?.[ASSISTANT_DEFAULT_AGENT_NAME]
const validMode = resolveValidAssistantMode(existingAssistantAgent)
const existingIsGenerated = typeof existingAssistantAgent === 'object' &&
existingAssistantAgent !== null &&
matchesGeneratedAssistantAgentPrompt(existingAssistantAgent.system)
let mergedAssistantAgent: OpenCodeAgentConfig
if (existingIsGenerated) {
mergedAssistantAgent = { mode: validMode }
} else {
mergedAssistantAgent = {
...(typeof existingAssistantAgent === 'object' && existingAssistantAgent !== null ? existingAssistantAgent : {}),
mode: validMode,
disabled: false,
}
const mergedAssistantAgent: OpenCodeAgentConfig = normalizeAssistantAgent(existingAssistantAgent) ?? {
...(existingAssistantAgent ?? {}),
mode: validMode,
disabled: false,
}
return {
@@ -1432,15 +1447,20 @@ function mergeAssistantOpenCodeConfig(existing?: OpenCodeConfigInfo): OpenCodeCo
}
}
function buildAssistantV1ConfigRemovalPaths(config: Record<string, unknown>): string[][] {
const v1Agent = config.agent
function buildAssistantV1ConfigRemovalPaths(
config: Record<string, unknown>,
convertedPermissions: unknown,
): string[][] {
const v1Agent = readConfigValueAtPath(config, ASSISTANT_V1_AGENT_PATH)
const removeWholeAgent = isRecord(v1Agent) &&
Object.keys(v1Agent).length === 1 &&
isRecord(v1Agent.assistant)
isRecord(v1Agent[ASSISTANT_DEFAULT_AGENT_NAME])
const paths: string[][] = [removeWholeAgent ? ['agent'] : ['agent', ASSISTANT_DEFAULT_AGENT_NAME]]
if (config.permission !== undefined) {
paths.push(['permission'])
const paths: string[][] = [
removeWholeAgent ? ASSISTANT_V1_AGENT_PATH : [...ASSISTANT_V1_AGENT_PATH, ASSISTANT_DEFAULT_AGENT_NAME],
]
if (convertedPermissions !== undefined && readConfigValueAtPath(config, ASSISTANT_V1_PERMISSION_PATH) !== undefined) {
paths.push(ASSISTANT_V1_PERMISSION_PATH)
}
return paths
}
@@ -1449,12 +1469,22 @@ function resolveConvertedAssistantAgent(
agent: OpenCodeAgentConfig | undefined,
v1Agent: unknown,
): OpenCodeAgentConfig {
if (agent === undefined) {
return { mode: resolveValidAssistantMode(v1Agent) }
}
return matchesGeneratedAssistantAgentPrompt(agent.system)
? { mode: resolveValidAssistantMode(agent) }
: agent
return normalizeAssistantAgent(agent) ?? agent ?? { mode: resolveValidAssistantMode(v1Agent) }
}
function restoreAssistantAgentReferences(
agent: OpenCodeAgentConfig,
resolved: OpenCodeConfigInfo,
raw: Record<string, unknown>,
): OpenCodeAgentConfig {
const restored = restoreOpenCodeConfigReferences(
{ agents: { [ASSISTANT_DEFAULT_AGENT_NAME]: agent } },
resolved as Record<string, unknown>,
raw,
)
const restoredAgent = readConfigValueAtPath(restored, ['agents', ASSISTANT_DEFAULT_AGENT_NAME])
if (typeof restoredAgent !== 'object' || restoredAgent === null) return agent
return restoredAgent as OpenCodeAgentConfig
}
/**
@@ -1476,13 +1506,18 @@ export async function convertAssistantOpenCodeConfigToV2(api: OpenCodeApi): Prom
const documentInfo = documents.get(path.resolve(opencodeJsonPath))
if (documentInfo === undefined) return false
const v1AssistantAgent = isRecord(rawConfig.agent) ? rawConfig.agent.assistant : undefined
const v1Assistants = readConfigValueAtPath(rawConfig, ASSISTANT_V1_AGENT_PATH)
const v1AssistantAgent = isRecord(v1Assistants) ? v1Assistants[ASSISTANT_DEFAULT_AGENT_NAME] : undefined
const setOperations: OpenCodeConfigPathOperation[] = [
{
path: ['agents', ASSISTANT_DEFAULT_AGENT_NAME],
value: resolveConvertedAssistantAgent(
documentInfo.agents?.[ASSISTANT_DEFAULT_AGENT_NAME],
v1AssistantAgent,
value: restoreAssistantAgentReferences(
resolveConvertedAssistantAgent(
documentInfo.agents?.[ASSISTANT_DEFAULT_AGENT_NAME],
v1AssistantAgent,
),
documentInfo,
rawConfig,
),
},
]
@@ -1491,7 +1526,7 @@ export async function convertAssistantOpenCodeConfigToV2(api: OpenCodeApi): Prom
}
let updatedText = applyOpenCodeConfigEdits(rawContent, setOperations)
for (const removalPath of buildAssistantV1ConfigRemovalPaths(rawConfig)) {
for (const removalPath of buildAssistantV1ConfigRemovalPaths(rawConfig, documentInfo.permissions)) {
updatedText = removeOpenCodeConfigProperty(updatedText, removalPath)
}
+21 -1
View File
@@ -10,9 +10,12 @@ import {
restoreOpenCodeConfigSnapshot,
serializeOpenCodeConfigSnapshot,
updateOpenCodeConfigFile,
type OpenCodeConfigSnapshot,
type OpenCodeConfigUpdateMode,
withOpenCodeConfigLock,
} from './opencode-config-file'
import { readManagedOpenCodeConfig } from './opencode-config-effective'
import { restoreOpenCodeConfigReferences } from './opencode-config-references'
import { opencodeServerManager } from './opencode-single-server'
import { reloadOpenCodeConfig } from './opencode-restart'
import type { OpenCodeClient } from './opencode/client'
@@ -98,6 +101,20 @@ function requiresOpenCodeReload(previous: OpenCodeConfigFile | null, next: OpenC
return listChangedTopLevelKeys(previous?.content ?? {}, next.content).length > 0
}
async function keepOpenCodeConfigReferences(
patch: Record<string, unknown>,
snapshot: OpenCodeConfigSnapshot,
openCodeClient: OpenCodeClient,
): Promise<Record<string, unknown>> {
try {
const resolved = await readManagedOpenCodeConfig(openCodeClient.api, snapshot.sources)
return restoreOpenCodeConfigReferences(patch, resolved as Record<string, unknown>, snapshot.content)
} catch (error) {
logger.warn('Could not read the resolved OpenCode config; saving the patch without reference restoration:', error)
return patch
}
}
export async function applyOpenCodeConfigUpdate(
input: ApplyOpenCodeConfigOptions,
): Promise<ApplyOpenCodeConfigResult> {
@@ -106,8 +123,11 @@ export async function applyOpenCodeConfigUpdate(
const snapshot = await readOpenCodeConfigSnapshot()
const previous = await readOpenCodeConfigFile(snapshot)
const savedContent = mode === 'merge' && typeof content !== 'string'
? await keepOpenCodeConfigReferences(content, snapshot, input.openCodeClient)
: content
const next = await updateOpenCodeConfigFile(content, { source, expectedRevision, snapshot, mode })
const next = await updateOpenCodeConfigFile(savedContent, { source, expectedRevision, snapshot, mode })
if (previous?.isValid) {
const snapshot = serializeOpenCodeConfigSnapshot(previous)
+3 -2
View File
@@ -153,7 +153,8 @@ export interface OpenCodeConfigPathOperation {
value: unknown
}
interface OpenCodeConfigV1EntityPath {
/** Maps a v2 config entity container to the v1 container OpenCode converts it from. */
export interface OpenCodeConfigV1EntityPath {
v2Path: string[]
v1Path: string[]
named: boolean
@@ -165,7 +166,7 @@ interface OpenCodeConfigV1EntityRemoval {
container?: JSONPath
}
const V1_ENTITY_PATHS: readonly OpenCodeConfigV1EntityPath[] = [
export const V1_ENTITY_PATHS: readonly OpenCodeConfigV1EntityPath[] = [
{ v2Path: ['agents'], v1Path: ['agent'], named: true },
{ v2Path: ['commands'], v1Path: ['command'], named: true },
{ v2Path: ['providers'], v1Path: ['provider'], named: true },
@@ -1,5 +1,5 @@
import { isRecord } from '@opencode-manager/shared/utils'
import type { OpenCodeConfigFile } from '../types/settings'
import { isRecord } from './opencode/enforcement-config'
import { OPENCODE_CONFIG_REDACTED_VALUE } from './opencode-config-file'
const SECRET_KEYS = new Set([
@@ -0,0 +1,156 @@
import { isRecord } from '@opencode-manager/shared/utils'
import { V1_ENTITY_PATHS, type OpenCodeConfigV1EntityPath } from './opencode-config-file'
const CONFIG_REFERENCE_PATTERN = /\{(?:env|file):[^}]+\}/
type FieldAlias = readonly [v2Prefix: readonly string[], v1Prefix: readonly string[]]
const V1_FIELD_ALIASES: Readonly<Record<string, readonly FieldAlias[]>> = {
agents: [
[['system'], ['prompt']],
[['request', 'body', 'temperature'], ['temperature']],
[['request', 'body', 'top_p'], ['top_p']],
[['request', 'body'], ['options']],
],
providers: [
[['settings', 'baseURL'], ['api']],
[['headers'], ['options', 'headers']],
[['body'], ['options', 'body']],
[['settings'], ['options']],
],
'mcp.servers': [
[['oauth', 'client_id'], ['oauth', 'clientId']],
[['oauth', 'client_secret'], ['oauth', 'clientSecret']],
[['oauth', 'redirect_uri'], ['oauth', 'redirectUri']],
],
}
interface RawEntityCandidate {
entity: unknown
aliases: readonly FieldAlias[]
}
/** Reads a nested config value by object keys and array indices, or `undefined` when absent. */
export function readConfigValueAtPath(value: unknown, path: readonly string[]): unknown {
let current = value
for (const segment of path) {
if (Array.isArray(current)) {
current = current[Number(segment)]
continue
}
if (!isRecord(current) || !Object.prototype.hasOwnProperty.call(current, segment)) return undefined
current = current[segment]
}
return current
}
function startsWithPath(path: readonly string[], prefix: readonly string[]): boolean {
return prefix.length <= path.length && prefix.every((segment, index) => path[index] === segment)
}
function readRawReference(candidates: readonly RawEntityCandidate[], path: readonly string[]): string | undefined {
for (const candidate of candidates) {
const paths = [
path,
...candidate.aliases
.filter(([v2Prefix]) => startsWithPath(path, v2Prefix))
.map(([v2Prefix, v1Prefix]) => [...v1Prefix, ...path.slice(v2Prefix.length)]),
]
for (const rawPath of paths) {
const raw = readConfigValueAtPath(candidate.entity, rawPath)
if (typeof raw === 'string' && CONFIG_REFERENCE_PATTERN.test(raw)) return raw
}
}
return undefined
}
function restoreEntityReferences(
next: unknown,
path: readonly string[],
resolvedEntity: unknown,
candidates: readonly RawEntityCandidate[],
): unknown {
if (typeof next === 'string') {
if (readConfigValueAtPath(resolvedEntity, path) !== next) return next
return readRawReference(candidates, path) ?? next
}
if (Array.isArray(next)) {
return next.map((item, index) => restoreEntityReferences(item, [...path, String(index)], resolvedEntity, candidates))
}
if (isRecord(next)) {
return Object.fromEntries(
Object.entries(next).map(([key, value]) => [key, restoreEntityReferences(value, [...path, key], resolvedEntity, candidates)]),
)
}
return next
}
function findRenameSource(
patchContainer: Record<string, unknown>,
resolvedContainer: Record<string, unknown>,
): string | undefined {
const removed = Object.keys(patchContainer).filter(
(name) => patchContainer[name] === null && Object.prototype.hasOwnProperty.call(resolvedContainer, name),
)
return removed.length === 1 ? removed[0] : undefined
}
function restoreContainerReferences(
mapping: OpenCodeConfigV1EntityPath,
patchContainer: Record<string, unknown>,
resolved: Record<string, unknown>,
raw: Record<string, unknown>,
): Record<string, unknown> {
const resolvedContainer = readConfigValueAtPath(resolved, mapping.v2Path)
if (!isRecord(resolvedContainer)) return patchContainer
const rawV2Container = readConfigValueAtPath(raw, mapping.v2Path)
const rawV1Container = readConfigValueAtPath(raw, mapping.v1Path)
const aliases = V1_FIELD_ALIASES[mapping.v2Path.join('.')] ?? []
return Object.fromEntries(
Object.entries(patchContainer).map(([name, value]) => {
if (!isRecord(value)) return [name, value]
const sourceName = Object.prototype.hasOwnProperty.call(resolvedContainer, name)
? name
: findRenameSource(patchContainer, resolvedContainer)
if (sourceName === undefined) return [name, value]
const candidates: RawEntityCandidate[] = [
{ entity: isRecord(rawV2Container) ? rawV2Container[sourceName] : undefined, aliases: [] },
]
if (!mapping.reservedNames?.includes(sourceName)) {
candidates.push({ entity: isRecord(rawV1Container) ? rawV1Container[sourceName] : undefined, aliases })
}
return [name, restoreEntityReferences(value, [], resolvedContainer[sourceName], candidates)]
}),
)
}
function setValueAtPath(target: Record<string, unknown>, path: readonly string[], value: unknown): Record<string, unknown> {
const [head, ...rest] = path
if (head === undefined) return target
const child = target[head]
return {
...target,
[head]: rest.length === 0 ? value : setValueAtPath(isRecord(child) ? child : {}, rest, value),
}
}
/**
* Keeps `{env:…}` and `{file:…}` references in a merge patch of named config entities.
*
* Settings edits entities from OpenCode's resolved config, so an untouched field arrives with its
* substituted value. A string that still equals the resolved value is replaced by the reference
* stored in the raw config: the same entity, the entity being renamed, or its v1 definition.
*/
export function restoreOpenCodeConfigReferences(
patch: Record<string, unknown>,
resolved: Record<string, unknown>,
raw: Record<string, unknown>,
): Record<string, unknown> {
return V1_ENTITY_PATHS.filter((mapping) => mapping.named).reduce((current, mapping) => {
const patchContainer = readConfigValueAtPath(current, mapping.v2Path)
if (!isRecord(patchContainer)) return current
return setValueAtPath(current, mapping.v2Path, restoreContainerReferences(mapping, patchContainer, resolved, raw))
}, patch)
}
@@ -130,14 +130,24 @@ export function subscribeOpenCodeEvents(options: OpenCodeEventSubscriptionOption
if (closed || token !== loopToken) return
options.onDisconnect(stallError ?? failure)
try {
options.onDisconnect(stallError ?? failure)
} catch (error) {
logger.error(`${options.label}: disconnect handler failed`, error)
}
await wait(currentDelay)
if (closed || token !== loopToken) return
currentDelay = nextBackoffDelay(currentDelay, maxReconnectDelayMs)
}
}
void run(loopToken)
const startLoop = (token: number): void => {
void run(token).catch((error) => {
logger.error(`${options.label}: subscription loop failed`, error)
})
}
startLoop(loopToken)
return {
close: () => {
@@ -153,7 +163,7 @@ export function subscribeOpenCodeEvents(options: OpenCodeEventSubscriptionOption
stopDelay()
stopAttempt()
currentDelay = reconnectDelayMs
void run(loopToken)
startLoop(loopToken)
},
}
}
@@ -1,8 +1,6 @@
export type EnforcementRemovedSections = Record<string, unknown>
import { isRecord } from '@opencode-manager/shared/utils'
export function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
export type EnforcementRemovedSections = Record<string, unknown>
function mergeRecordSections(target: Record<string, unknown>, key: string, value: Record<string, unknown>): void {
const current = isRecord(target[key]) ? { ...(target[key] as Record<string, unknown>) } : {}
+1
View File
@@ -553,6 +553,7 @@ class SSEAggregator {
}
case 'session.deleted': {
this.unmarkSubagentSession(directory, event.data.sessionID)
this.markSessionIdle(directory, event.data.sessionID)
return
}
}