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

+39 -14
View File
@@ -204,46 +204,71 @@ Returns the updated settings object.
### OpenCode Configuration
The OpenCode configuration file at `getOpenCodeConfigFilePath()` is the source of truth, and this endpoint is the only supported way to change it. The endpoint applies the same restart and live-patch rules as the Settings UI: changes to `agent`, `plugin`, `skills`, or `provider` mark an OpenCode server restart as required, and any other change is live-patched into the running OpenCode server.
The global OpenCode configuration files in the workspace `.config/opencode/` directory are the source of truth, and these endpoints are the only supported way to change them. Up to three sources are recognized and merged in OpenCode order — `config.json`, `opencode.json`, `opencode.jsonc` — with later files overriding earlier ones. The endpoint applies the same rules as the Settings UI: any semantic change is written to disk and marks an OpenCode server restart as required; comment-only edits and changes limited to `mcp` do not.
**GET `/api/internal/opencode-config`**
Read the current configuration file state.
Read the merged persisted configuration and its source files. This is not the running instance configuration: project overrides and expanded environment values are not included.
**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 // Absolute path of the preferred write target
content: object // Merged configuration across all sources
rawContent: string // Raw content of the preferred write target
sources: Array<{ // Recognized source files, in merge order
name: 'config.json' | 'opencode.json' | 'opencode.jsonc'
path: string
rawContent: string
content: object
isValid: boolean
validationIssues?: Array<{ path: string, message: string }>
updatedAt: number
}>
revision: string // Hash of the source set; send back as expectedRevision
isValid: boolean // Whether every source passes schema validation
validationIssues?: Array<{ path: string, message: string }>
updatedAt: number // Unix timestamp of the last write
updatedAt: number // Newest source mtime
}
```
**Status Codes:**
- `200`: Configuration file state returned
- `200`: Configuration state returned
- `401`: Missing or invalid bearer token
- `404`: No config file found
- `404`: No config source found
- `500`: Server error
**GET `/api/internal/opencode-config/effective`**
Read the running server's effective global configuration (OpenCode `GET /global/config`). Never copy this response into a save.
**Status Codes:**
- `200`: Effective configuration returned
- `401`: Missing or invalid bearer token
- `502`: OpenCode returned an error
- `503`: OpenCode server unavailable
**PUT `/api/internal/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 configuration first, change only the keys the user asked for, and send the complete object back with its `revision`. Only changed paths are patched into the preferred existing source (`opencode.jsonc` > `opencode.json` > `config.json`; a new installation gets `opencode.jsonc`); comments, unknown keys, and untouched inherited values are preserved. For a raw edit, send a string as `content` together with the exact `source` name.
**Request Body:**
```ts
{ content: object } // The complete configuration to persist
{
content: object | string // Complete merged object, or raw text for one source
expectedRevision?: string // From GET; a stale value is rejected with 409
source?: 'config.json' | 'opencode.json' | 'opencode.jsonc' // Required for raw string edits
}
```
**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 `OpenCodeConfigFile`. Adds `restartRequired: true` when the change needs an OpenCode server restart.
**Status Codes:**
- `200`: Configuration written (live-patched or restart pending)
- `400`: Invalid request body, or configuration rejected with `validationIssues`
- `200`: Configuration written
- `400`: Invalid request body, invalid configuration, or a source file that is not valid JSON/JSONC (`sources` lists them)
- `401`: Missing or invalid bearer token
- `409`: Stale `expectedRevision` (`expectedRevision`/`actualRevision` in the body), or the save would remove a value defined only in a lower-priority source (`paths`/`sources` in the body)
- `500`: Server error
### Assistant
+5 -3
View File
@@ -42,7 +42,7 @@ Health monitoring is configured through environment variables:
## Configuration Recovery
The on-disk `opencode.json` is the source of truth. When the file exists at boot but fails validation, the Manager logs a warning and starts with the file unchanged — an invalid config file is never automatically replaced or rolled back during boot.
The on-disk global configuration files in `.config/opencode/` are the source of truth. OpenCode merges up to three recognized sources in order — `config.json`, `opencode.json`, then `opencode.jsonc` — with later files overriding matching keys from earlier ones. The Manager reads and edits the same set: saves patch only the changed paths into the preferred existing source (`opencode.jsonc` > `opencode.json` > `config.json`), preserving comments and untouched keys, and a fresh installation is seeded with `opencode.jsonc`. When a source exists at boot but fails validation, the Manager logs a warning and starts with the files unchanged — an invalid config is never automatically replaced or rolled back during boot.
The health-watch ladder is the only automatic repair path. When the supervised OpenCode server fails repeated health checks, recovery runs these actions in order until the server is healthy:
@@ -53,7 +53,7 @@ The health-watch ladder is the only automatic repair path. When the supervised O
Because the ladder only runs after repeated failed health checks, a config file that fails validation but does not make the server unhealthy is left in place. Setting `OPENCODE_HEALTH_WATCH_ENABLED=false` disables the ladder entirely, leaving no automatic repair path.
The last known good config is captured from the current on-disk file before every write made through the Settings UI, the internal API, or a host config import, so any of those can be undone with `POST /api/settings/opencode-rollback` or by the ladder. Archived broken configs and debug snapshots are kept under `.opencode/state/health-watch/` in the workspace, pruned to the newest 20 files.
The last known good config is a snapshot of every recognized source file (including which ones exist), captured before every write made through the Settings UI, the internal API, or a host config import, so any of those can be undone with `POST /api/settings/opencode-rollback` or by the ladder. Restoring a snapshot rewrites the sources it contains and removes recognized sources it does not. Archived broken configs and debug snapshots are kept under `.opencode/state/health-watch/` in the workspace, pruned to the newest 20 files.
Earlier releases stored named configuration profiles in the Manager database. On first start after upgrading, each profile is archived to `.config/opencode-configs-archive/<name>.json` in the workspace, the default profile is restored to `opencode.json` if that file does not exist yet, and the database table is dropped.
@@ -89,4 +89,6 @@ Besides the explicit **Restart** button, the server is automatically restarted w
- **Config import completes** — Importing a standalone OpenCode config into the workspace
- **Version upgrade** — After installing a new OpenCode version
Saving the OpenCode configuration never restarts the server on its own. Changes to `agent`, `plugin`, `skills`, or `provider` are written to disk and flagged as **restart required**; the server keeps running on the previous configuration until you restart it. Every other change is live-patched into the running server without interrupting active sessions, and is only written to disk once the server has accepted it.
Saving the OpenCode configuration never restarts the server on its own. Any change to the merged configuration is written to disk and flagged as **restart required**; the server keeps running on the previous configuration until you restart it. Two exceptions do not set the flag: comment-only edits, and changes limited to the `mcp` section, which the Settings UI applies to the running server directly. Saving a provider credential, or completing a provider OAuth flow, restarts the server through the same session-resume flow so newly configured providers are discovered.
A save is rejected with `409` when the files changed since you loaded them (stale revision), or when it would remove a value that is defined only in a lower-priority source file — removing it from the preferred file would leave the inherited value in effect.