diff --git a/.env.example b/.env.example
index 8f0658c6..3c3efb52 100644
--- a/.env.example
+++ b/.env.example
@@ -17,16 +17,12 @@ LOG_LEVEL=info
OPENCODE_SERVER_PORT=5551
OPENCODE_HOST=127.0.0.1
-# Optional - bearer password required when OPENCODE_HOST=0.0.0.0 (external exposure).
-# The managed OpenCode server will refuse to start if OPENCODE_HOST is not
-# localhost/127.0.0.1 and no password is configured (either here or via
-# Settings → OpenCode → Server Auth).
-# DB-stored passwords (set via UI) override this env var.
+# Optional - Basic Auth password for the managed OpenCode server.
+# OpenCode 2 always requires a password: when this is unset and no password is
+# stored via Settings → OpenCode → Server Auth, OpenCode Manager generates one
+# and persists it. DB-stored passwords override this env var.
# OPENCODE_SERVER_PASSWORD=
-# Optional - Basic Auth username (default: opencode)
-# OPENCODE_SERVER_USERNAME=opencode
-
# Optional - import an existing standalone OpenCode install on first startup
# Useful for Docker when your host OpenCode data is bind-mounted into the container
# OPENCODE_IMPORT_CONFIG_PATH=/import/opencode-config/opencode.json
diff --git a/.github/workflows/docker-build.yml b/.github/workflows/docker-build.yml
index 417cc6d4..a52e3a52 100644
--- a/.github/workflows/docker-build.yml
+++ b/.github/workflows/docker-build.yml
@@ -20,7 +20,7 @@ jobs:
id: versions
run: |
UV_VERSION=0.12.7
- OPENCODE_VERSION=1.18.31
+ OPENCODE_VERSION=2.0.15
MICROSANDBOX_VERSION=0.7.2
PLAYWRIGHT_VERSION=1.63.0
echo "uv=${UV_VERSION}" >> $GITHUB_OUTPUT
diff --git a/AGENTS.md b/AGENTS.md
index 7c2e1043..a0224892 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -48,7 +48,7 @@
- **Dependency Inversion**: Depend on abstractions, not concretions—inject dependencies and avoid hard-coding implementations.
- YAGNI: Don’t build or keep code you don’t need. If you change something, remove the unused parts. use the new code or keep the old, but don’t keep both.
- Never leave dead code: remove unused code, commented-out blocks, and unused variables/imports.
-- ./temp/opencode is reference only, never commit has opencode src
+- `temp/opencode` is a reference clone of OpenCode 2 at tag `v2.0.15` (gitignored, never committed)
- Use shared types from workspace package (@opencode-manager/shared)
- OpenCode server runs on port 5551, backend API on port 5003
- Prefer pnpm over npm for all package management
diff --git a/Dockerfile b/Dockerfile
index e6183315..6c6ec80e 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -62,7 +62,7 @@ FROM base AS runner
# an arm64 host builds the amd64 platform; 0.12.7 is the newest verified-good
# release, so re-verify a bump there before moving it.
ARG UV_VERSION=0.12.7
-ARG OPENCODE_VERSION=1.18.31
+ARG OPENCODE_VERSION=2.0.15
ARG MICROSANDBOX_VERSION=0.7.2
ARG PLAYWRIGHT_VERSION=1.63.0
# Bump TOOLS_CACHEBUST (e.g. via --build-arg) to force a fresh uv/opencode
@@ -79,11 +79,7 @@ RUN echo "Installing uv=${UV_VERSION} opencode=${OPENCODE_VERSION} (cachebust=${
OC_ARCH=$(uname -m) && \
if [ "$OC_ARCH" = "aarch64" ]; then OC_ARCH="arm64"; fi && \
if [ "$OC_ARCH" = "x86_64" ]; then OC_ARCH="x64"; fi && \
- if [ "${OPENCODE_VERSION}" = "latest" ]; then \
- OC_DOWNLOAD_URL="https://github.com/anomalyco/opencode/releases/latest/download/opencode-linux-${OC_ARCH}.tar.gz"; \
- else \
- OC_DOWNLOAD_URL="https://github.com/anomalyco/opencode/releases/download/v${OPENCODE_VERSION}/opencode-linux-${OC_ARCH}.tar.gz"; \
- fi && \
+ OC_DOWNLOAD_URL="https://opencode.ai/files/bin/${OPENCODE_VERSION}/opencode-linux-${OC_ARCH}.tar.gz" && \
curl -fsSL "$OC_DOWNLOAD_URL" -o /tmp/opencode.tar.gz && \
tar -xzf /tmp/opencode.tar.gz -C /tmp && \
mkdir -p /opt/opencode/bin && \
diff --git a/README.md b/README.md
index 8dbabe34..4892ae06 100644
--- a/README.md
+++ b/README.md
@@ -30,6 +30,10 @@
+## Requirements
+
+OpenCode Manager requires **OpenCode 2.0.0 or newer** (bundled 2.0.15). OpenCode 1.x is not supported. If you are upgrading from OpenCode 1.x, see the [v1 → v2 migration guide](https://opencode.ai/v2/docs/migrate-v1).
+
## Quick Start
```bash
diff --git a/backend/src/db/migrations/021-drop-schedule-run-workspace-id.ts b/backend/src/db/migrations/021-drop-schedule-run-workspace-id.ts
new file mode 100644
index 00000000..d0795797
--- /dev/null
+++ b/backend/src/db/migrations/021-drop-schedule-run-workspace-id.ts
@@ -0,0 +1,23 @@
+import type { Migration } from '../migration-runner'
+
+interface ColumnInfo {
+ name: string
+}
+
+const migration: Migration = {
+ version: 21,
+ name: 'drop-schedule-run-workspace-id',
+
+ up(db) {
+ const cols = db.prepare('PRAGMA table_info(schedule_runs)').all() as ColumnInfo[]
+ if (cols.some((c) => c.name === 'workspace_id')) {
+ db.run('ALTER TABLE schedule_runs DROP COLUMN workspace_id')
+ }
+ },
+
+ down(_db) {
+ void _db
+ },
+}
+
+export default migration
diff --git a/backend/src/db/migrations/index.ts b/backend/src/db/migrations/index.ts
index bd1ab38d..c08f3e70 100644
--- a/backend/src/db/migrations/index.ts
+++ b/backend/src/db/migrations/index.ts
@@ -19,6 +19,7 @@ import migration017 from './017-schedule-run-workspace-id'
import migration018 from './018-session-pins'
import migration019 from './019-drop-opencode-configs'
import migration020 from './020-drop-opencode-model-state'
+import migration021 from './021-drop-schedule-run-workspace-id'
export const allMigrations: Migration[] = [
migration001,
@@ -41,4 +42,5 @@ export const allMigrations: Migration[] = [
migration018,
migration019,
migration020,
+ migration021,
]
diff --git a/backend/src/db/schedules.ts b/backend/src/db/schedules.ts
index d000e895..feb17588 100644
--- a/backend/src/db/schedules.ts
+++ b/backend/src/db/schedules.ts
@@ -53,7 +53,6 @@ interface ScheduleRunRow {
run_branch: string | null
commit_hash: string | null
worktree_path: string | null
- workspace_id: string | null
}
function parseSkillMetadata(raw: string | null) {
@@ -126,7 +125,6 @@ function rowToScheduleRun(row: ScheduleRunRow): ScheduleRun {
runBranch: row.run_branch,
commitHash: row.commit_hash,
worktreePath: row.worktree_path,
- workspaceId: row.workspace_id,
})
}
@@ -260,39 +258,25 @@ export interface ScheduleRunArtifact {
status: ScheduleRunStatus
runBranch: string | null
worktreePath: string | null
- workspaceId: string | null
}
export function listScheduleRunArtifactsByJob(db: Database, repoId: number, jobId: number): ScheduleRunArtifact[] {
const rows = db
- .prepare('SELECT id, status, run_branch, worktree_path, workspace_id FROM schedule_runs WHERE repo_id = ? AND job_id = ? ORDER BY id DESC')
- .all(repoId, jobId) as { id: number; status: string; run_branch: string | null; worktree_path: string | null; workspace_id: string | null }[]
+ .prepare('SELECT id, status, run_branch, worktree_path FROM schedule_runs WHERE repo_id = ? AND job_id = ? ORDER BY id DESC')
+ .all(repoId, jobId) as { id: number; status: string; run_branch: string | null; worktree_path: string | null }[]
return rows.map((row) => ({
id: row.id,
status: row.status as ScheduleRunStatus,
runBranch: row.run_branch,
worktreePath: row.worktree_path,
- workspaceId: row.workspace_id,
}))
}
-export interface ActiveScheduleRunWorkspace {
- worktreePath: string | null
- workspaceId: string | null
-}
-
-/**
- * Returns the worktree directories and OpenCode workspace IDs of schedule runs
- * that still hold a live worktree/workspace (both columns are cleared to null
- * on finalize). Used to keep an in-progress run's isolated worktree out of the
- * deletable Sibling surface, since worktrees created via the OpenCode workspace
- * API live outside getScheduleWorktreesPath().
- */
-export function listActiveScheduleRunWorkspaces(db: Database): ActiveScheduleRunWorkspace[] {
+export function listActiveScheduleRunWorktreePaths(db: Database): string[] {
const rows = db
- .prepare('SELECT worktree_path, workspace_id FROM schedule_runs WHERE worktree_path IS NOT NULL OR workspace_id IS NOT NULL')
- .all() as { worktree_path: string | null; workspace_id: string | null }[]
- return rows.map((row) => ({ worktreePath: row.worktree_path, workspaceId: row.workspace_id }))
+ .prepare('SELECT worktree_path FROM schedule_runs WHERE worktree_path IS NOT NULL')
+ .all() as { worktree_path: string }[]
+ return rows.map((row) => row.worktree_path)
}
export function deleteScheduleRunById(db: Database, repoId: number, jobId: number, runId: number): boolean {
@@ -445,7 +429,7 @@ export function updateScheduleRunWorktree(
repoId: number,
jobId: number,
runId: number,
- input: { worktreePath?: string | null; runBranch?: string | null; commitHash?: string | null; workspaceId?: string | null },
+ input: { worktreePath?: string | null; runBranch?: string | null; commitHash?: string | null },
): ScheduleRun | null {
const existing = getScheduleRunById(db, repoId, jobId, runId)
if (!existing) {
@@ -454,7 +438,7 @@ export function updateScheduleRunWorktree(
const stmt = db.prepare(`
UPDATE schedule_runs
- SET worktree_path = ?, run_branch = ?, commit_hash = ?, workspace_id = ?
+ SET worktree_path = ?, run_branch = ?, commit_hash = ?
WHERE repo_id = ? AND job_id = ? AND id = ?
`)
@@ -462,7 +446,6 @@ export function updateScheduleRunWorktree(
input.worktreePath === undefined ? existing.worktreePath : input.worktreePath,
input.runBranch === undefined ? existing.runBranch : input.runBranch,
input.commitHash === undefined ? existing.commitHash : input.commitHash,
- input.workspaceId === undefined ? existing.workspaceId : input.workspaceId,
repoId,
jobId,
runId,
@@ -517,8 +500,7 @@ export function listScheduleRunsByJob(db: Database, repoId: number, jobId: numbe
error_text,
run_branch,
commit_hash,
- worktree_path,
- workspace_id
+ worktree_path
FROM schedule_runs
WHERE repo_id = ? AND job_id = ?
ORDER BY started_at DESC
@@ -642,7 +624,7 @@ export function listAllScheduleRuns(db: Database, options: ListAllRunsOptions =
sr.started_at, sr.finished_at, sr.created_at,
sr.session_id, sr.session_title,
NULL AS log_text, NULL AS response_text, sr.error_text,
- sr.run_branch, sr.commit_hash, sr.worktree_path, sr.workspace_id,
+ sr.run_branch, sr.commit_hash, sr.worktree_path,
sj.name AS job_name, r.local_path AS repo_path, r.name AS repo_name,
r.repo_url AS repo_url, r.source_path AS repo_source_path
FROM schedule_runs sr
diff --git a/backend/src/index.ts b/backend/src/index.ts
index 6b6d7ba0..14b12765 100644
--- a/backend/src/index.ts
+++ b/backend/src/index.ts
@@ -55,7 +55,7 @@ import { installAssistantWorkspace } from './services/assistant-mode'
import { detectSandboxCapability } from './services/sandbox/capability'
import { SandboxRuntimeService, stopWorkspaceSandboxOnShutdown } from './services/sandbox/runtime'
import { getOpenCodeImportStatus, syncOpenCodeImport } from './services/opencode-import'
-import { readOpenCodeConfigFile } from './services/opencode-config-file'
+import { readOpenCodeConfigFile, foldLegacyConfigJsonSource, withOpenCodeConfigLock } from './services/opencode-config-file'
import { seedOpenCodeConfigFile } from './services/opencode-config-apply'
import { OpenCodeSupervisor } from './services/opencode-supervisor'
import { OpenCodeRestartCoordinator } from './services/opencode-restart-coordinator'
@@ -112,6 +112,8 @@ let ipcServer: IPCServer | undefined
const gitAuthService = new GitAuthService()
let openCodeSupervisor: OpenCodeSupervisor | undefined
async function ensureOpenCodeConfigFileExists(): Promise {
+ await withOpenCodeConfigLock(foldLegacyConfigJsonSource)
+
const existing = await readOpenCodeConfigFile()
if (existing) {
if (!existing.isValid) {
@@ -222,7 +224,7 @@ try {
const settingsServiceForSchedules = new SettingsService(db)
const credentialProvider = new CredentialProvider(db)
-const scheduleWorktreeManager = new ScheduleWorktreeManager(gitAuthService, settingsServiceForSchedules, credentialProvider, db, openCodeClient)
+const scheduleWorktreeManager = new ScheduleWorktreeManager(gitAuthService, settingsServiceForSchedules, credentialProvider, db)
const scheduleService = new ScheduleService(db, openCodeClient, scheduleWorktreeManager)
const scheduleRunnerInstance = new ScheduleRunner(scheduleService)
@@ -255,7 +257,7 @@ sseAggregator.setScheduledSessionsResolver(
() => scheduleService.getActiveRunSessions(),
)
-const openCodeRestartCoordinator = new OpenCodeRestartCoordinator(openCodeClient, sseAggregator)
+const openCodeRestartCoordinator = new OpenCodeRestartCoordinator(sseAggregator)
setOpenCodeRestartCoordinator(openCodeRestartCoordinator)
void scheduleRunnerInstance.start()
@@ -277,8 +279,8 @@ protectedApi.route('/repos', createRepoRoutes(db, gitAuthService, scheduleServic
protectedApi.route('/settings', createSettingsRoutes(db, gitAuthService, openCodeClient, openCodeSupervisor))
protectedApi.route('/files', createFileRoutes())
protectedApi.route('/filesystem', createFilesystemRoutes())
-protectedApi.route('/providers', createProvidersRoutes(openCodeClient, openCodeSupervisor))
-protectedApi.route('/oauth', createOAuthRoutes(openCodeClient, openCodeSupervisor))
+protectedApi.route('/providers', createProvidersRoutes(openCodeClient))
+protectedApi.route('/oauth', createOAuthRoutes(openCodeClient))
protectedApi.route('/tts', createTTSRoutes(db))
protectedApi.route('/stt', createSTTRoutes(db))
protectedApi.route('/sse', createSSERoutes())
diff --git a/backend/src/routes/internal/assistant.ts b/backend/src/routes/internal/assistant.ts
index 0bb47abe..9712226c 100644
--- a/backend/src/routes/internal/assistant.ts
+++ b/backend/src/routes/internal/assistant.ts
@@ -1,6 +1,6 @@
import { Hono } from 'hono'
import type { OpenCodeClient } from '../../services/opencode/client'
-import { getAssistantModeDirectory } from '../../services/assistant-mode'
+import { logger } from '../../utils/logger'
import { TokenBucketRateLimiter } from '../../utils/rate-limit'
export function createInternalAssistantRoutes(openCodeClient: OpenCodeClient) {
@@ -15,9 +15,10 @@ export function createInternalAssistantRoutes(openCodeClient: OpenCodeClient) {
return c.json({ error: 'Rate limit exceeded' }, 429)
}
- const directory = getAssistantModeDirectory()
- const response = await openCodeClient.forward({ method: 'POST', path: '/instance/dispose', directory })
- if (!response.ok) {
+ try {
+ await openCodeClient.api.location.reload()
+ } catch (error) {
+ logger.error('Failed to reload assistant workspace:', error)
return c.json({ error: 'Failed to reload assistant workspace' }, 502)
}
diff --git a/backend/src/routes/mcp-oauth-proxy.ts b/backend/src/routes/mcp-oauth-proxy.ts
index ded95253..238464d9 100644
--- a/backend/src/routes/mcp-oauth-proxy.ts
+++ b/backend/src/routes/mcp-oauth-proxy.ts
@@ -1,53 +1,35 @@
import { Hono } from 'hono'
-import type { OpenCodeClient } from '../services/opencode/client'
+import type { Context, MiddlewareHandler } from 'hono'
+import { createServer } from 'node:net'
+import type { AddressInfo } from 'node:net'
import { z } from 'zod'
-import crypto from 'crypto'
-import path from 'path'
-import { readFile, writeFile } from 'fs/promises'
-import { storeMcpOAuthFlow, consumeMcpOAuthFlow, deleteMcpOAuthFlow, markMcpOAuthFlowCompleted, markMcpOAuthFlowFailed, getMcpOAuthFlowResult } from '../services/mcp-oauth-state'
+import {
+ MCP_OAUTH_CALLBACK_PATH,
+ mcpOAuthRedirectUri,
+ mcpServerConfigFromConfig,
+ openCodeLocation,
+} from '@opencode-manager/shared/opencode'
+import type { V2McpServerConfig } from '@opencode-manager/shared/opencode'
+import type { OpenCodeClient } from '../services/opencode/client'
+import { storeMcpOAuthFlow, consumeMcpOAuthFlow, getMcpOAuthFlowByAttempt } from '../services/mcp-oauth-state'
import { logger } from '../utils/logger'
-import { mkdirSafe } from '../utils/fs-safe'
-import { getWorkspacePath } from '@opencode-manager/shared/config/env'
const StartSchema = z.object({
- serverName: z.string(),
- serverUrl: z.string().url(),
- scope: z.string().optional(),
- clientId: z.string().optional(),
- clientSecret: z.string().optional(),
+ serverName: z.string().min(1),
directory: z.string().optional(),
})
-function getMcpAuthPath(): string {
- return path.join(getWorkspacePath(), '.opencode/state/opencode/mcp-auth.json')
-}
+const DirectoryQuerySchema = z.object({
+ directory: z.string().optional(),
+})
-async function readMcpAuth(): Promise> {
- try {
- const content = await readFile(getMcpAuthPath(), 'utf-8')
- return JSON.parse(content) as Record
- } catch {
- return {}
+function requestOrigin(c: Context): string {
+ const host = c.req.header('host')
+ const forwardedProto = c.req.header('x-forwarded-proto')
+ if (forwardedProto && host) {
+ return `${forwardedProto}://${host}`
}
-}
-
-async function writeMcpAuth(data: Record): Promise {
- const filePath = getMcpAuthPath()
- await mkdirSafe(path.dirname(filePath))
- await writeFile(filePath, JSON.stringify(data, null, 2), { mode: 0o600 })
-}
-
-function generateState(): string {
- return crypto.randomBytes(32).toString('hex')
-}
-
-function generateCodeVerifier(): string {
- return crypto.randomBytes(32).toString('base64url')
-}
-
-async function generateCodeChallenge(verifier: string): Promise {
- const hash = crypto.createHash('sha256').update(verifier).digest()
- return hash.toString('base64url')
+ return c.req.header('origin') || `http://${host ?? 'localhost:5003'}`
}
function escapeHtml(unsafe: string): string {
@@ -82,142 +64,166 @@ function renderPage(heading: string, message: string, isSuccess: boolean): strin