Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
01d8f08
section 1: Phase 1: Shared reconnecting OpenCode event subscription and
chriswritescode-dev Nov 2, 2026
d749084
section 2: Phase 2: Local SSE aggregator streams through the local Open
chriswritescode-dev Nov 2, 2026
680a336
section 3: Phase 3: Remote server events use the registry client; remov
chriswritescode-dev Nov 2, 2026
2b00825
section 4: Phase 4: One streaming proxy forwarder used by both proxy ro
chriswritescode-dev Nov 2, 2026
66b5d1a
section 5: Phase 5: Stop buffering in /api/opencode/*
chriswritescode-dev Nov 2, 2026
48ca38c
section 6: Phase 6: Config.Info validation owner and v2 config types in
chriswritescode-dev Nov 2, 2026
19d4ae2
section 7: Phase 7: Entity saves replace the matching v1 entry in the s
chriswritescode-dev Nov 2, 2026
6578e11
section 8: Phase 8: Managed effective config read through api.config.ge
chriswritescode-dev Nov 2, 2026
81725fb
section 9: Phase 9: Settings agents and commands read managed v2 config
chriswritescode-dev Nov 2, 2026
1802cdc
section 10: Phase 10: Model/provider editor and MCP manager on v2 provid
chriswritescode-dev Nov 2, 2026
0b2303a
section 11: Phase 11: Assistant Mode writes v2 config; remove the hand-w
chriswritescode-dev Nov 2, 2026
717536c
section 12: Phase 12: One shared flattened stream event type; delete the
chriswritescode-dev Nov 2, 2026
2d4abe7
section 13: Phase 13: Session status from the client type, compaction-dr
chriswritescode-dev Nov 2, 2026
fbc3e02
section 14: Phase 14: Model view models use ModelInfo field names
chriswritescode-dev Nov 2, 2026
7c4cfd8
section 15: Phase 15: ocm-cli server probe through the client; full repo
chriswritescode-dev Nov 2, 2026
49bb4eb
loop: om-179-finish-adopting-op completed after 19 iterations
chriswritescode-dev Nov 2, 2026
8a6fd56
fix: keep config references on save and apply review batch 2 fixes (O…
chriswritescode-dev Nov 3, 2026
9fca96e
fix: refuse entity saves while a restart is pending and share replay …
chriswritescode-dev Nov 3, 2026
3e6ebbd
fix: hold the upstream resync until the OpenCode proxy accepts reques…
chriswritescode-dev Nov 3, 2026
8d92f86
fix: apply CodeRabbit auto-fixes
chriswritescode-dev Nov 3, 2026
38d618b
fix: limit the restart-pending 409 to entity patches and keep inherit…
chriswritescode-dev Nov 5, 2026
670c66f
fix: add a Default agent permission choice and stop forwarding cookie…
chriswritescode-dev Nov 5, 2026
58a9fcd
fix: leave agent temperature and top_p unset unless the user sets the…
chriswritescode-dev Nov 5, 2026
84aa8db
fix: refresh the managed config after a raw config save (OM-179)
chriswritescode-dev Nov 5, 2026
64e87ba
fix: guard the Assistant config conversion and place agent permission…
chriswritescode-dev Nov 5, 2026
6297403
docs: document the OpenCode client migration surfaces (OM-179)
chriswritescode-dev Nov 5, 2026
052b501
fix(backend): exclude dist from the type check (OM-179)
chriswritescode-dev Nov 5, 2026
8b6ed7a
fix: check the Assistant config inside its lock and pass bare stream …
chriswritescode-dev Nov 5, 2026
462b981
fix: delete an emptied permissions or request block instead of saving…
chriswritescode-dev Nov 5, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
"archiver": "^7.0.1",
"better-auth": "^1.7.12",
"croner": "^10.0.1",
"eventsource": "^4.1.0",
"hono": "^4.13.13",
"jsonc-parser": "^3.3.1",
"web-push": "^3.6.7",
Expand All @@ -35,7 +34,6 @@
"@types/archiver": "^7.0.0",
"@types/better-sqlite3": "^7.6.13",
"@types/bun": "latest",
"@types/eventsource": "^3.0.0",
"@types/web-push": "^3.6.4",
"@vitest/coverage-v8": "^3.2.4",
"@vitest/ui": "^3.2.4",
Expand Down
12 changes: 9 additions & 3 deletions backend/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ import { RepoWorkspaceService } from './services/repo-workspace'
import { createGitService } from './services/git/GitService'
import { ScheduleWorktreeManager } from './services/schedule-worktree'
import { migrateGlobalSkills } from './services/skills'
import { installAssistantWorkspace } from './services/assistant-mode'
import { installAssistantWorkspace, convertAssistantOpenCodeConfigToV2 } from './services/assistant-mode'
import { detectSandboxCapability } from './services/sandbox/capability'
import { SandboxRuntimeService, stopSandboxesOnShutdown } from './services/sandbox/runtime'
import { getOpenCodeImportStatus, syncOpenCodeImport } from './services/opencode-import'
Expand Down Expand Up @@ -359,12 +359,18 @@ if (ENV.VAPID.PUBLIC_KEY && ENV.VAPID.PRIVATE_KEY) {
})
}

sseAggregator.setPendingActionsFetcher(openCodeClient)
sseAggregator.setPasswordResolver(() => new SettingsService(db).getOpenCodeServerPassword())
sseAggregator.setOpenCodeClient(openCodeClient)
sseAggregator.setResyncGate(() => opencodeServerManager.isLifecycleInitialized())
opencodeServerManager.onLifecycleInitialized(() => sseAggregator.releasePendingResync())
sseAggregator.onServerConnected((serverId) => {
void sessionPermissionModeService.acceptPendingRequestsForActiveSessions(serverId).catch((err) => {
logger.error(`Failed to accept pending permission requests for server ${serverId}:`, err)
})
if (serverId === LOCAL_OPENCODE_SERVER_ID) {
void convertAssistantOpenCodeConfigToV2(openCodeClient.api).catch((err) => {
logger.error('Failed to convert the Assistant OpenCode config to v2:', err)
})
}
Comment thread
chriswritescode-dev marked this conversation as resolved.
Resolved
})
sseAggregator.start()

Expand Down
77 changes: 61 additions & 16 deletions backend/src/routes/opencode-config.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { Hono, type Context } from 'hono'
import { z } from 'zod'
import {
UpdateOpenCodeConfigPatchRequestSchema,
UpdateOpenCodeConfigRequestSchema,
Expand All @@ -20,11 +19,16 @@ import {
OpenCodeConfigRedactedValueError,
OpenCodeConfigShadowedRemovalError,
OpenCodeConfigSourceInvalidError,
OpenCodeConfigValidationError,
readOpenCodeConfigFile,
readOpenCodeConfigSnapshot,
withOpenCodeConfigLock,
} from '../services/opencode-config-file'
import { readManagedOpenCodeConfig } from '../services/opencode-config-effective'
import { applyOpenCodeConfigUpdate, toOpenCodeConfigApplyResponse } from '../services/opencode-config-apply'
import { redactOpenCodeConfigContent, redactOpenCodeConfigFile } from '../services/opencode-config-redact'
import { patchNamesOpenCodeConfigEntities } from '../services/opencode-config-references'
import { opencodeServerManager } from '../services/opencode-single-server'
import { logger } from '../utils/logger'

interface OpenCodeConfigRoutesOptions {
Expand Down Expand Up @@ -53,6 +57,26 @@ function mergeMcpServerStatus(views: McpServerView[], status: McpStatusMap) {
})
}

/**
* Maps a config read failure to a JSON error response: 503 when the OpenCode server is unreachable,
* 502 for other client errors, and 500 otherwise, using `message` as the client-facing text.
*/
function toClientReadErrorResponse(c: Context, error: unknown, message: string) {
if (error instanceof ClientError) {
if (error.reason === 'Transport') {
return c.json({ error: 'OpenCode server unavailable' }, 503)
}
return c.json({ error: message }, 502)
}
return c.json({ error: message }, 500)
}

/**
* Serves the OpenCode config read routes (`/`, `/effective`, `/managed`, `/mcp`) and the `PUT` and
* `PATCH` write routes. Reads and writes take the shared config file lock, `redactSecrets` masks
* secret values in every response, and a `PATCH` that names config entities is rejected with 409
* while OpenCode has not yet loaded the saved configuration.
*/
export function createOpenCodeConfigRoutes(
settingsService: SettingsService,
openCodeClient: OpenCodeClient,
Expand Down Expand Up @@ -90,30 +114,40 @@ export function createOpenCodeConfigRoutes(
})
} catch (error) {
logger.error('Failed to get effective OpenCode config:', error)
if (error instanceof ClientError) {
if (error.reason === 'Transport') {
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)
return toClientReadErrorResponse(c, error, 'Failed to get effective OpenCode config')
}
})

app.get('/managed', async (c) => {
try {
const snapshot = await withOpenCodeConfigLock(readOpenCodeConfigSnapshot)
const info = await readManagedOpenCodeConfig(openCodeClient.api, snapshot.sources)
return c.json({
info: options.redactSecrets
? redactOpenCodeConfigContent(info as Record<string, unknown>).content
: info,
})
} catch (error) {
logger.error('Failed to get managed OpenCode config:', error)
return toClientReadErrorResponse(c, error, 'Failed to get managed OpenCode config')
}
})

app.get('/mcp', async (c) => {
try {
const [config, status] = await Promise.all([
withOpenCodeConfigLock(readOpenCodeConfigFile),
const snapshot = await withOpenCodeConfigLock(readOpenCodeConfigSnapshot)
const [info, status] = await Promise.all([
readManagedOpenCodeConfig(openCodeClient.api, snapshot.sources),
readMcpStatus(openCodeClient),
])
const views = mcpServerViewsFromConfig(config?.content.mcp)
const views = mcpServerViewsFromConfig(info.mcp)
return c.json({
revision: config?.revision ?? null,
revision: snapshot.revision,
servers: mergeMcpServerStatus(views, status),
})
} catch (error) {
logger.error('Failed to get OpenCode MCP servers:', error)
return c.json({ error: 'Failed to get OpenCode MCP servers' }, 500)
return toClientReadErrorResponse(c, error, 'Failed to get OpenCode MCP servers')
}
})

Expand Down Expand Up @@ -152,6 +186,12 @@ export function createOpenCodeConfigRoutes(
return c.json({ error: 'Invalid config data', details: parsed.error.issues }, 400)
}

if (opencodeServerManager.isRestartPending() && patchNamesOpenCodeConfigEntities(parsed.data.patch)) {
return c.json({
error: 'OpenCode has not loaded the saved configuration yet. Restart OpenCode before editing entries.',
}, 409)
}

return applyUpdate(c, {
content: parsed.data.patch,
source: parsed.data.source,
Expand All @@ -165,6 +205,11 @@ export function createOpenCodeConfigRoutes(
return app
}

/**
* Applies a validated config update and maps the outcome to a JSON response, redacting secrets when
* `redactSecrets` is set and translating conflict, invalid-source, shadowed-removal, redacted-value
* and schema-validation failures into their matching status codes.
*/
async function applyUpdate(
c: Context,
input: Parameters<typeof applyOpenCodeConfigUpdate>[0],
Expand Down Expand Up @@ -198,12 +243,12 @@ async function applyUpdate(
if (error instanceof OpenCodeConfigRedactedValueError) {
return c.json({ error: error.message, paths: error.paths }, 400)
}
if (error instanceof z.ZodError) {
return c.json({ error: 'Invalid config data', details: error.issues }, 400)
if (error instanceof OpenCodeConfigValidationError) {
return c.json({ error: 'Invalid config data', validationIssues: 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)
return toClientReadErrorResponse(c, error, 'Failed to update OpenCode config')
}
}
26 changes: 15 additions & 11 deletions backend/src/routes/opencode-proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { getRepoById } from '../db/queries'
import { getTrustedOrigins, getWorkspacePath } from '@opencode-manager/shared/config/env'
import { isPathWithinRoot } from '../utils/fs-safe'
import { buildProxyResponseHeaders, filterProxyHeaders } from '../utils/proxy-headers'
import { forwardProxyRequest } from '../utils/proxy-forward'
import {
connectUpstreamWebSocket,
createBridgedSocketEvents,
Expand Down Expand Up @@ -112,6 +113,12 @@ function rewriteRepoLocationBody(bodyText: string, resolveDirectory: RepoDirecto
return JSON.stringify(parsed)
}

/**
* Serves `/repos/:repoId/*` and `/*` by forwarding to the managed OpenCode server, rewriting repo
* directory references in the path, query and JSON body. Every request needs the internal token
* except a ticketed persistent PTY WebSocket connect, which is origin-checked and bridged to the
* upstream socket.
*/
export function createOpenCodeProxyRoutes(db: Database, settingsService: SettingsService, upgradeWebSocket: UpgradeWebSocket) {
const app = new Hono()
const requireInternalToken = createInternalTokenMiddleware(db)
Expand Down Expand Up @@ -144,6 +151,11 @@ export function createOpenCodeProxyRoutes(db: Database, settingsService: Setting
return (await upgrade(c, async () => {})) ?? c.body(null)
}

/**
* Forwards the current request to the managed OpenCode server with basic auth and a default
* directory, letting the optional rewrites adjust path, query and JSON body first. Returns 503
* before lifecycle initialization, 501 for non-PTY upgrades and 502 when the upstream call fails.
*/
async function forwardToOpenCode(
c: Context,
pathSuffix: string,
Expand Down Expand Up @@ -192,20 +204,12 @@ export function createOpenCodeProxyRoutes(db: Database, settingsService: Setting
const upstreamUrl = `${getOpenCodeUpstreamBaseUrl()}${pathSuffix}${url.search}`

try {
const upstreamResponse = await fetch(upstreamUrl, {
return await forwardProxyRequest({
url: upstreamUrl,
method: c.req.method,
headers,
body: requestBody,
redirect: 'manual',
duplex: 'half',
})

const responseHeaders = buildProxyResponseHeaders(upstreamResponse.headers)

return new Response(upstreamResponse.body, {
status: upstreamResponse.status,
statusText: upstreamResponse.statusText,
headers: responseHeaders,
buildResponseHeaders: buildProxyResponseHeaders,
})
} catch {
return c.json({ error: 'Proxy request failed' }, 502)
Expand Down
60 changes: 18 additions & 42 deletions backend/src/routes/opencode-server-proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import {
type OpenCodeServerConnection,
type OpenCodeServerRegistry,
} from '../services/opencode-server-registry'
import { filterProxyHeaders, NULL_BODY_STATUSES } from '../utils/proxy-headers'
import { filterProxyHeaders } from '../utils/proxy-headers'
import { forwardProxyRequest, ProxyHeadersTimeoutError } from '../utils/proxy-forward'
import { logger } from '../utils/logger'

const MOUNT_PREFIX = '/api/opencode/servers/'
Expand Down Expand Up @@ -79,6 +80,11 @@ function isWithinUpstreamApiPath(basePath: string, pathname: string): boolean {
return pathname.startsWith(`${basePath}/api/`)
}

/**
* Serves `/:serverId/*` behind `requireAuth`, proxying each request to the registry-resolved remote
* OpenCode server while keeping the normalized upstream pathname inside that connection's own `/api/`
* space. Maps an upstream header timeout to 504 and an unreachable server to 502.
*/
export function createOpenCodeServerProxyRoutes(
registry: OpenCodeServerRegistry,
requireAuth: MiddlewareHandler,
Expand Down Expand Up @@ -117,58 +123,28 @@ export function createOpenCodeServerProxyRoutes(
headers.Authorization = connection.authorization
}

const hasBody = c.req.method !== 'GET' && c.req.method !== 'HEAD'

let headersTimeoutTimer: ReturnType<typeof setTimeout> | null = null
let headersTimedOut = false
let upstreamSignal = c.req.raw.signal
if (!hasBody) {
const timeoutController = new AbortController()
headersTimeoutTimer = setTimeout(() => {
headersTimedOut = true
timeoutController.abort()
}, upstreamHeadersTimeoutMs)
upstreamSignal = AbortSignal.any([c.req.raw.signal, timeoutController.signal])
}
const isBodylessMethod = c.req.method === 'GET' || c.req.method === 'HEAD'

try {
const upstreamResponse = await fetchFn(upstream.url.toString(), {
return await forwardProxyRequest({
url: upstream.url.toString(),
method: c.req.method,
headers,
body: hasBody ? c.req.raw.body : undefined,
redirect: 'manual',
signal: upstreamSignal,
duplex: 'half',
})

if (headersTimeoutTimer !== null) {
clearTimeout(headersTimeoutTimer)
headersTimeoutTimer = null
}

const responseHeaders = new Headers(
filterProxyHeaders(upstreamResponse.headers, RESPONSE_EXCLUDED_HEADERS),
)
const responseBody = NULL_BODY_STATUSES.has(upstreamResponse.status)
? null
: upstreamResponse.body

return new Response(responseBody, {
status: upstreamResponse.status,
statusText: upstreamResponse.statusText,
headers: responseHeaders,
body: isBodylessMethod ? null : c.req.raw.body,
signal: c.req.raw.signal,
headersTimeoutMs: isBodylessMethod ? upstreamHeadersTimeoutMs : undefined,
fetchFn,
buildResponseHeaders: (upstreamHeaders) => new Headers(
filterProxyHeaders(upstreamHeaders, RESPONSE_EXCLUDED_HEADERS),
),
})
} catch (error) {
if (headersTimedOut) {
if (error instanceof ProxyHeadersTimeoutError) {
logger.warn(`OpenCode server proxy timed out waiting for headers: ${c.req.method} ${upstream.url.host}${upstreamPath.path}`, error)
return c.json({ error: 'Remote OpenCode server timed out' }, 504)
}
logger.warn(`OpenCode server proxy request failed: ${c.req.method} ${upstream.url.host}${upstreamPath.path}`, error)
return c.json({ error: 'Remote OpenCode server unreachable' }, 502)
} finally {
if (headersTimeoutTimer !== null) {
clearTimeout(headersTimeoutTimer)
}
}
})

Expand Down
8 changes: 7 additions & 1 deletion backend/src/routes/repos.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import type { SecretsService } from '../services/secrets'
import type { RepoWorkspaceService } from '../services/repo-workspace'
import { createGitService } from '../services/git/GitService'
import { ScheduleService } from '../services/schedules'
import { ensureAssistantMode, getAssistantModeStatus } from '../services/assistant-mode'
import { ensureAssistantMode, getAssistantModeStatus, convertAssistantOpenCodeConfigToV2 } from '../services/assistant-mode'
import path from 'path'

const DeleteWorkspaceRequestSchema = z.object({
Expand All @@ -41,6 +41,11 @@ function withRepoSettings(database: Database, repo: Repo): Repo {
}
}

/**
* Mounts the repo git, terminal, project-config, schedule and secret/variable sub-routers, and serves
* repo CRUD with discovery, ordering, access, credential, identity, workspace, pull/branch, download
* and assistant-mode routes. Handler failures are mapped to their status codes with a JSON message.
*/
export function createRepoRoutes(
database: Database,
gitAuthService: GitAuthService,
Expand Down Expand Up @@ -614,6 +619,7 @@ app.get('/', async (c) => {
const options = AssistantModeInitRequestSchema.parse(body)

const status = await ensureAssistantMode(repo, options)
await convertAssistantOpenCodeConfigToV2(openCodeClient.api)
return c.json(status)
} catch (error: unknown) {
logger.error('Failed to initialize assistant mode:', error)
Expand Down
Loading
Loading