feat(opencode): migrate OpenCode Manager to OpenCode 2 (#359)

* feat(opencode): migrate OpenCode Manager to OpenCode 2

Port the backend lifecycle, generated plugins, event aggregation,
schedules, worktrees, provider credentials, MCP, config handling, the
frontend chat model, and the ocm CLI to OpenCode 2.

Adopt @opencode/client 2.0.15 as the single typed V2 API contract,
require OpenCode 2.0.0 or newer (pinned 2.0.15), and delete every
V1-only code path.

* refactor(opencode): reload config in place and drop v1 compatibility shims

Route config/skill/AGENTS.md changes through the OpenCode location reload
API instead of a full server restart, stop auto-resuming interrupted
sessions, remove the restart coordinator and v1 MCP/version shims, and pin
support to OpenCode >=2.0.15 <3.0.0. Adds integration-ready retries,
service-mode launch, ocm-cli repo proxy, and new frontend form/MCP helpers.

* refactor(opencode): consolidate v2 migration helpers and harden install, proxy, and session flows

- extract shared semver and model-ref utilities, reuse across version checks
- share the OpenCode release download script across Docker, entrypoint, dev setup
- unify install/upgrade failure recovery and guard externally managed OPENCODE_BIN
- scope the repo proxy location rewrite and surface ocm proxy errors
- rework frontend session projection, permission lookup, and cache invalidation

* fix(schedules): reject unavailable agents before creating a session

* feat(opencode): add ocm install, schedule agent fallback, and session move guards
This commit is contained in:
Chris Scott authored and GitHub committed 2026-09-26 13:16:45 -04:00
1 parent 6c2ebd764b
commit dacde879d6
383 files changed
+29905 -46566

No files matched your search

+60 -142
View File
@@ -1,82 +1,53 @@
export type HistoryEventRow = { id: string; aggregate_id: string; seq: number; type: string; data: Record<string, unknown> }
export type ReplayEvent = { id: string; aggregateID: string; seq: number; type: string; data: Record<string, unknown> }
export type CollectResult =
| { kind: 'ok'; events: ReplayEvent[] }
| { kind: 'empty' }
| { kind: 'gap'; missingSeq: number }
import { fileURLToPath, pathToFileURL } from 'node:url'
import type { SessionTransferData } from '@opencode-manager/shared/opencode'
export type RewriteContext = { localRoot: string; remoteRoot: string }
export function collectSessionEvents(rows: HistoryEventRow[], sessionID: string): CollectResult {
const filtered = rows.filter((r) => r.aggregate_id === sessionID)
if (filtered.length === 0) return { kind: 'empty' }
export function rewriteTransferForRemote(data: SessionTransferData, ctx: RewriteContext): SessionTransferData {
const cloned = structuredClone(data)
cloned.info.location.directory = relocatePath(cloned.info.location.directory, ctx)
relocateUris(cloned.messages, ctx)
return cloned
}
const sorted = [...filtered].sort((a, b) => a.seq - b.seq)
if (sorted[0]!.seq !== 0) return { kind: 'gap', missingSeq: 0 }
for (let i = 1; i < sorted.length; i++) {
if (sorted[i]!.seq !== sorted[i - 1]!.seq + 1) {
return { kind: 'gap', missingSeq: sorted[i - 1]!.seq + 1 }
}
function relocateUris(value: unknown, ctx: RewriteContext): void {
if (Array.isArray(value)) {
for (const item of value) relocateUris(item, ctx)
return
}
const events: ReplayEvent[] = sorted.map((r) => ({
id: r.id,
aggregateID: r.aggregate_id,
seq: r.seq,
type: r.type,
data: r.data,
}))
return { kind: 'ok', events }
if (!value || typeof value !== 'object') return
const record = value as Record<string, unknown>
if (typeof record.uri === 'string') record.uri = relocateUri(record.uri, ctx)
for (const child of Object.values(record)) relocateUris(child, ctx)
}
/**
* Rewrites collected replay events for replay on a remote Manager server.
*
* Coercion rule for `data.timestamp` matches the prior implementation in
* commit 686c820d (`coerceReplayBodyTimestamps`): ISO 8601 string timestamps
* are converted to epoch milliseconds via `Date.parse`; already-numeric values
* are left untouched.
*/
export function rewriteEventsForRemote(events: ReplayEvent[], ctx: RewriteContext): ReplayEvent[] {
return events.map((event) => {
const data = deepClone(event.data)
function relocateUri(uri: string, ctx: RewriteContext): string {
const fileUrl = parseLocalFileUrl(uri)
if (!fileUrl) return relocatePath(uri, ctx)
if (shouldRewriteDirectory(event.type)) {
rewriteDirectory(data, 'info', ctx)
stripWorkspaceID(data, 'info')
}
if (isMovedEvent(event.type)) {
rewriteDirectory(data, 'location', ctx)
stripWorkspaceID(data, 'location')
}
if (isMessageUpdated(event.type)) {
rewriteMessagePath(data, ctx)
}
coerceTimestamp(data)
return { ...event, data }
})
const relocated = relocatePath(fileUrl.path, ctx)
if (relocated === fileUrl.path) return uri
return `${pathToFileURL(relocated).href}${fileUrl.search}${fileUrl.hash}`
}
function shouldRewriteDirectory(type: string): boolean {
return type.startsWith('session.created') || type.startsWith('session.updated')
}
function parseLocalFileUrl(uri: string): { path: string; search: string; hash: string } | null {
if (!uri.startsWith('file:')) return null
function isMovedEvent(type: string): boolean {
return type.startsWith('session.next.moved')
}
let url: URL
try {
url = new URL(uri)
} catch {
return null
}
if (url.protocol !== 'file:' || (url.host !== '' && url.host !== 'localhost')) return null
function isMessageUpdated(type: string): boolean {
return type.startsWith('message.updated')
}
function asRecord(value: unknown): Record<string, unknown> | null {
return value && typeof value === 'object' ? (value as Record<string, unknown>) : null
let path: string
try {
path = fileURLToPath(url)
} catch {
return null
}
return { path, search: url.search, hash: url.hash }
}
function relocatePath(path: string, ctx: RewriteContext): string {
@@ -85,97 +56,44 @@ function relocatePath(path: string, ctx: RewriteContext): string {
return path
}
function relocateField(obj: Record<string, unknown>, key: string, ctx: RewriteContext): void {
const value = obj[key]
if (typeof value === 'string') obj[key] = relocatePath(value, ctx)
}
function rewriteDirectory(
data: Record<string, unknown>,
key: 'info' | 'location',
ctx: RewriteContext,
): void {
const container = asRecord(data[key])
if (container) relocateField(container, 'directory', ctx)
}
function rewriteMessagePath(data: Record<string, unknown>, ctx: RewriteContext): void {
const path = asRecord(asRecord(data.info)?.path)
if (!path) return
relocateField(path, 'cwd', ctx)
relocateField(path, 'root', ctx)
}
function stripWorkspaceID(data: Record<string, unknown>, key: 'info' | 'location'): void {
const container = asRecord(data[key])
if (container) delete container.workspaceID
}
/** Per commit 686c820d: coerce `data.timestamp` from ISO string to epoch ms. */
function coerceTimestamp(data: Record<string, unknown>): void {
const ts = data.timestamp
if (typeof ts !== 'string') return
const epoch = Date.parse(ts)
if (!Number.isFinite(epoch)) return
data.timestamp = epoch
}
export type TransferDeps = {
fetchLocalHistory: () => Promise<HistoryEventRow[]>
replayEvents: (remoteDirectory: string, events: ReplayEvent[]) => Promise<{ sessionID: string }>
onProgress?: (replayed: number, total: number) => void
exportSession: (sessionID: string) => Promise<SessionTransferData>
importSession: (remoteDirectory: string, data: SessionTransferData) => Promise<{ sessionID: string }>
onProgress?: (transferred: number, total: number) => void
}
export type TransferInput = { sessionID: string; localRoot: string; remoteDirectory: string }
export type TransferResult =
| { kind: 'moved'; sessionID: string; replayedEvents: number }
| { kind: 'not-found' }
| { kind: 'corrupt-history'; missingSeq: number }
| { kind: 'replay-failed'; message: string }
export function planReplayBatches(events: ReplayEvent[], batchSize = 10): ReplayEvent[][] {
const batches: ReplayEvent[][] = []
for (let i = 0; i < events.length; i += batchSize) {
batches.push(events.slice(i, i + batchSize))
}
return batches
}
| { kind: 'moved'; sessionID: string; importedMessages: number }
| { kind: 'import-failed'; message: string }
export async function transferSession(input: TransferInput, deps: TransferDeps): Promise<TransferResult> {
const rows = await deps.fetchLocalHistory()
const collect = collectSessionEvents(rows, input.sessionID)
let data: SessionTransferData
try {
data = await deps.exportSession(input.sessionID)
} catch (err) {
return { kind: 'import-failed', message: err instanceof Error ? err.message : String(err) }
}
if (collect.kind === 'empty') return { kind: 'not-found' }
if (collect.kind === 'gap') return { kind: 'corrupt-history', missingSeq: collect.missingSeq }
const rewritten = rewriteEventsForRemote(collect.events, {
const rewritten = rewriteTransferForRemote(data, {
localRoot: input.localRoot,
remoteRoot: input.remoteDirectory,
})
const total = rewritten.messages.length
deps.onProgress?.(0, total)
const batches = planReplayBatches(rewritten)
const total = rewritten.length
let replayed = 0
deps.onProgress?.(replayed, total)
for (const batch of batches) {
try {
await deps.replayEvents(input.remoteDirectory, batch)
replayed += batch.length
deps.onProgress?.(replayed, total)
} catch (err) {
return { kind: 'replay-failed', message: err instanceof Error ? err.message : String(err) }
}
let imported: { sessionID: string }
try {
imported = await deps.importSession(input.remoteDirectory, rewritten)
} catch (err) {
return { kind: 'import-failed', message: err instanceof Error ? err.message : String(err) }
}
return { kind: 'moved', sessionID: input.sessionID, replayedEvents: replayed }
deps.onProgress?.(total, total)
return { kind: 'moved', sessionID: imported.sessionID, importedMessages: total }
}
export function moveReminderText(directory: string): string {
return `<system-reminder>The user has changed the current working directory to "${directory}". This is still the same project but at a possibly new location; take this into account when working with any files from now on.</system-reminder>`
}
function deepClone<T>(obj: T): T {
return JSON.parse(JSON.stringify(obj))
}