Files
opencode-manager/ocm-cli/bin/ocm.ts
Chris Scott dacde879d6 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
2026-09-26 13:16:45 -04:00

624 lines
22 KiB
TypeScript

import { spawn, spawnSync } from 'child_process'
import { basename, dirname, resolve } from 'path'
import { fileURLToPath } from 'url'
import { readState, writeState, clearState, getStatePath, writeInstallNotice, type OcmState } from '../src/state.js'
import { installVendoredOcm, resolveOpenCodeConfigDir, InstallError, OCM_PLUGIN_SPEC } from '../src/vendor-install.js'
import { getToken, setToken, deleteToken, hasStoredToken, describeTokenStore, describeTokenWriteTarget, envToken, TOKEN_ENV, TokenStoreError } from '../src/internal-token-store.js'
import { ManagerApi, ManagerApiError } from '../src/manager-api.js'
import { mirrorUp, mirrorDown, mirrorUpFast, mirrorDownFast, prepareMirror, MirrorAbort, checkPushDivergence, checkPullDivergence, describePushDivergence } from '../src/mirror.js'
import type { RemoteRepoSummary, MirrorProgress, PushDivergence, PullDivergence } from '../src/mirror.js'
import { createProgressReporter } from '../src/progress.js'
import { getBranchName, getOriginUrl } from '../src/local-repo.js'
import { resolveOpenCodeProjectId } from '@opencode-manager/shared/project-id'
import { resolveTarget, formatRepoIdentities, parseRepoIdPositional, restrictMatchesToRequestedRepo } from '../src/resolve-target.js'
import { buildAttachInvocation } from '../src/warp.js'
import { type ManagerRepo, fetchRepos, toRemoteRepoSummaries } from '../src/manager-repos.js'
import { OCM_VERSION as VERSION, warmRepoProxy } from '../src/repo-proxy.js'
const USAGE = `ocm v${VERSION} - OpenCode Manager workspace launcher
Usage:
ocm Attach to the Manager repo matching $PWD's git origin,
fall back to the last selected repo, or launch local
opencode when no Manager target applies
ocm login <url> [token] Save manager URL + token (token via stdin if omitted)
ocm logout Forget saved token and state
ocm status Show current manager URL, repo, and whether token is set
ocm list List ready repos from the manager
ocm use <repoId|name> Attach to a specific repo and remember it as last
ocm push [repoId] [--force] [--create] [--yes] [--full]
Mirror $PWD to the matching Manager repo (fast patch sync by default)
ocm pull [repoId] [--force] [--full]
Mirror the matching Manager repo over $PWD (fast patch sync by default)
ocm install [--dir <path>] [--force] [--no-link]
Vendor the CLI + TUI plugin into the OpenCode config dir
ocm --version Show the installed ocm version
ocm --help Show this help
`
function die(msg: string, code = 1): never {
process.stderr.write(`ocm: ${msg}\n`)
process.exit(code)
}
function info(msg: string): void {
process.stdout.write(`${msg}\n`)
}
function promptYesNo(question: string): boolean {
process.stderr.write(`${question} [y/N] `)
const res = spawnSync('bash', ['-c', 'read LINE && printf "%s" "$LINE"'], {
stdio: ['inherit', 'pipe', 'inherit'],
encoding: 'utf-8',
})
const answer = (res.stdout ?? '').trim().toLowerCase()
return answer === 'y' || answer === 'yes'
}
function confirmFullFallback(): void {
if (!process.stdin.isTTY) return
if (!promptYesNo('Fall back to a full mirror? This replaces the entire server working tree (no merge, no conflict resolution).')) {
die('aborted')
}
}
function confirmOverwrite(headline: string, reasons: string[], question: string, note?: string): boolean {
process.stderr.write(`ocm: warning: ${headline}\n`)
for (const reason of reasons) process.stderr.write(` - ${reason}\n`)
if (note) process.stderr.write(` ${note}\n`)
if (!process.stdin.isTTY) {
die('refusing to discard work; re-run with --force to override')
}
if (!promptYesNo(question)) {
die('aborted')
}
return true
}
function guardDivergentPush(repoName: string, div: PushDivergence): boolean {
return confirmOverwrite(
`pushing to ${repoName} will discard server-side work:`,
describePushDivergence(div),
'Overwrite server-side work and push anyway?',
'This work is likely from OpenCode agent sessions on the manager.',
)
}
function guardDivergentPull(repoName: string, div: PullDivergence): boolean {
const reasons = [div.lostCommits >= 0
? `your local branch is ${div.lostCommits} commit(s) ahead of ${repoName}`
: `your local branch has commit(s) not present on ${repoName}`]
return confirmOverwrite(
`pulling ${repoName} will discard local commits:`,
reasons,
'Discard local commits and pull anyway?',
)
}
function requireState(): OcmState {
const state = readState()
if (!state || !state.managerUrl) {
die(`no manager configured. Run \`ocm login <url>\` first.`)
}
return state
}
async function requireToken(state: OcmState): Promise<string> {
const store = describeTokenStore()
let token: string | null
try {
token = await getToken(state.managerUrl)
} catch (err) {
if (!(err instanceof TokenStoreError)) throw err
die(`token store error (${store.kind}: ${store.location}): ${err.message}. Run \`ocm login ${state.managerUrl}\` after fixing the store.`)
}
if (!token) {
die(`no token stored for ${state.managerUrl} (${store.kind}: ${store.location}). Run \`ocm login ${state.managerUrl}\`.`)
}
return token
}
async function attach(managerUrl: string, token: string, repo: ManagerRepo, cwd: string): Promise<never> {
try {
await warmRepoProxy(managerUrl, token, repo.repoId)
} catch (err) {
die(err instanceof Error ? err.message : String(err))
}
const { args, env } = buildAttachInvocation({ managerUrl, token, repoId: repo.repoId, repoName: repo.name })
const child = spawn('opencode', args, {
stdio: 'inherit',
cwd,
env,
})
child.on('close', (code) => process.exit(code ?? 0))
child.on('error', (err) => die(`failed to spawn opencode: ${err.message}`))
return undefined as never
}
function findRepo(repos: ManagerRepo[], needle: string | number): ManagerRepo | undefined {
if (typeof needle === 'number') {
return repos.find((r) => r.repoId === needle)
}
const asNum = Number(needle)
if (!Number.isNaN(asNum)) {
const byId = repos.find((r) => r.repoId === asNum)
if (byId) return byId
}
return repos.find((r) => r.name === needle) ?? repos.find((r) => r.name.toLowerCase() === needle.toLowerCase())
}
export async function cmdLogin(args: string[]): Promise<void> {
const url = args[0]
if (!url) die('usage: ocm login <url> [token]')
const normalisedUrl = url.replace(/\/+$/, '')
let token = args[1]
if (!token) {
if (process.stdin.isTTY) {
process.stderr.write('Paste token (input hidden): ')
const res = spawnSync('bash', ['-c', 'read -s LINE && printf "%s" "$LINE"'], {
stdio: ['inherit', 'pipe', 'inherit'],
encoding: 'utf-8',
})
process.stderr.write('\n')
token = (res.stdout ?? '').trim()
} else {
token = await new Promise<string>((resolve) => {
const chunks: Buffer[] = []
process.stdin.on('data', (c) => chunks.push(c))
process.stdin.on('end', () => resolve(Buffer.concat(chunks).toString('utf-8').trim()))
})
}
}
if (!token) die('no token provided')
try {
await setToken(normalisedUrl, token)
} catch (err) {
if (err instanceof TokenStoreError) die(`token store error: ${err.message}`)
throw err
}
const existing = readState()
writeState({
...existing,
managerUrl: normalisedUrl,
})
const store = describeTokenWriteTarget()
info(`Saved token for ${normalisedUrl} (${store.kind}: ${store.location}).`)
info(`State file: ${getStatePath()}`)
warnEnvTokenPrecedence()
}
export async function cmdLogout(): Promise<void> {
const state = readState()
if (!state || !state.managerUrl) {
info('Nothing to log out from.')
return
}
let deleted = false
let storeError: TokenStoreError | undefined
try {
deleted = await deleteToken(state.managerUrl)
} catch (err) {
if (!(err instanceof TokenStoreError)) throw err
storeError = err
}
clearState()
if (storeError) {
info('State cleared.')
die(`token store error: ${storeError.message}. The stored token may still exist.`)
}
info(deleted ? `Removed stored token for ${state.managerUrl}.` : 'No stored token found.')
info('State cleared.')
warnEnvTokenPrecedence()
}
function warnEnvTokenPrecedence(): void {
if (envToken()) {
info(`note: ${TOKEN_ENV} is set and takes precedence over the stored token; unset it to use the token store.`)
}
}
async function describeTokenPresence(account: string | undefined): Promise<string> {
try {
return (await hasStoredToken(account)) ? 'yes' : 'no'
} catch (err) {
if (!(err instanceof TokenStoreError)) throw err
return `unavailable (${err.message})`
}
}
export async function cmdStatus(): Promise<void> {
const store = describeTokenStore()
const state = readState()
if (!state) {
info(`version: ${VERSION}`)
info(`token store: ${store.kind} (${store.location})`)
info(`token: ${await describeTokenPresence(undefined)}`)
info('no state. run: ocm login <url>')
return
}
info(`version: ${VERSION}`)
info(`manager url: ${state.managerUrl}`)
info(`token: ${await describeTokenPresence(state.managerUrl)}`)
info(`token store: ${store.kind} (${store.location})`)
if (state.lastRepoId !== undefined) {
info(`last repo: ${state.lastRepoName} (id=${state.lastRepoId}, branch=${state.lastRepoBranch ?? 'n/a'})`)
info(`last repo dir: ${state.lastRepoDir}`)
} else {
info('last repo: (none)')
}
info(`state file: ${getStatePath()}`)
}
async function cmdList(): Promise<void> {
const state = requireState()
const token = await requireToken(state)
const repos = await fetchRepos(state.managerUrl, token)
if (repos.length === 0) {
info('No ready repos.')
return
}
const idWidth = Math.max(...repos.map((r) => String(r.repoId).length))
const nameWidth = Math.max(...repos.map((r) => r.name.length))
for (const r of repos) {
const id = String(r.repoId).padStart(idWidth)
const name = r.name.padEnd(nameWidth)
const branch = r.branch ? ` (${r.branch})` : ''
info(`${id} ${name} ${r.cloneStatus}${branch}`)
}
}
async function cmdUse(args: string[]): Promise<void> {
const needle = args[0]
if (!needle) die('usage: ocm use <repoId|name>')
const state = requireState()
const token = await requireToken(state)
const repos = await fetchRepos(state.managerUrl, token)
const repo = findRepo(repos, needle)
if (!repo) die(`repo not found: ${needle}`)
writeState({
...state,
lastRepoId: repo.repoId,
lastRepoName: repo.name,
lastRepoDir: repo.directory,
lastRepoBranch: repo.branch,
})
await attach(state.managerUrl, token, repo, process.cwd())
}
async function cmdDefault(): Promise<void> {
info(`ocm v${VERSION}`)
const state = requireState()
const token = await requireToken(state)
const last = state.lastRepoId !== undefined && state.lastRepoDir
? {
repoId: state.lastRepoId,
name: state.lastRepoName ?? `repo-${state.lastRepoId}`,
directory: state.lastRepoDir,
branch: state.lastRepoBranch ?? null,
}
: undefined
info('connecting...')
const repos = await fetchRepos(state.managerUrl, token)
const localProjectId = await resolveOpenCodeProjectId(process.cwd())
const result = resolveTarget({ cwd: process.cwd(), repos, localProjectId, last })
switch (result.kind) {
case 'cwd-match': {
const repo = result.repo
info(`attaching to ${repo.name}`)
writeState({
...state,
lastRepoId: repo.repoId,
lastRepoName: repo.name,
lastRepoDir: repo.directory,
lastRepoBranch: repo.branch,
})
await attach(state.managerUrl, token, toManagerRepo(repo), result.repoRoot)
return
}
case 'last': {
const repo = result.repo
info(`attaching to ${repo.name} (last used)`)
await attach(state.managerUrl, token, toManagerRepo(repo), process.cwd())
return
}
case 'cwd-ambiguous': {
die(`multiple Manager repos match project ${result.localProjectId}: ${formatRepoIdentities(result.matches)}; disambiguate with \`ocm use <repoId>\``)
break
}
case 'local':
runLocalOpencode(result.reason)
return
}
}
function runLocalOpencode(reason: 'no-match' | 'no-target'): never {
const message = reason === 'no-match'
? 'no Manager repo matches $PWD; launching local opencode'
: 'no last repo; launching local opencode'
process.stderr.write(`ocm: ${message}\n`)
const child = spawn('opencode', [], { stdio: 'inherit' })
child.on('close', (code) => process.exit(code ?? 0))
child.on('error', (err) => die(`failed to spawn opencode: ${err.message}`))
return undefined as never
}
function toManagerRepo(repo: { repoId: number; name: string; branch: string | null; directory: string }): ManagerRepo {
return {
repoId: repo.repoId,
name: repo.name,
branch: repo.branch,
cloneStatus: 'ready',
directory: repo.directory,
extra: { repoId: repo.repoId, localPath: '', fullPath: repo.directory },
}
}
const PUSH_FLAGS = ['--force', '--create', '--yes', '--full'] as const
const PULL_FLAGS = ['--force', '--full'] as const
function dieAmbiguousProjectMatch(command: 'push' | 'pull', localProjectId: string, repos: readonly ManagerRepo[], matches: readonly RemoteRepoSummary[]): never {
const matchedIds = new Set(matches.map((m) => m.repoId))
die(`multiple Manager repos match project ${localProjectId}: ${formatRepoIdentities(repos.filter((r) => matchedIds.has(r.repoId)))}; disambiguate with \`ocm ${command} <repoId>\``)
}
export async function cmdPush(args: string[]): Promise<void> {
const parsed = parseRepoIdPositional(args, PUSH_FLAGS)
if (parsed.error) die(parsed.error)
let force = false
let create = false
let yes = false
let full = false
for (const arg of args) {
if (arg === '--force') force = true
else if (arg === '--create') create = true
else if (arg === '--yes') yes = true
else if (arg === '--full') full = true
}
const state = requireState()
const token = await requireToken(state)
const api = new ManagerApi(state.managerUrl, token)
const repos = await fetchRepos(state.managerUrl, token)
const remotes: RemoteRepoSummary[] = toRemoteRepoSummaries(repos)
const plan = await prepareMirror(process.cwd(), remotes)
const restriction = restrictMatchesToRequestedRepo(plan.matched, parsed.repoId, plan.localProjectId)
if (restriction.error) die(restriction.error)
plan.matched = restriction.matches
if (plan.matched.length === 0) {
if (!create) {
die(`no matching Manager repo for project ${plan.localProjectId}. Re-run with --create to create one.`)
}
const name = basename(plan.repoRoot)
const branch = getBranchName(plan.repoRoot)
const originUrl = getOriginUrl(plan.repoRoot)
if (process.stdin.isTTY && !yes) {
if (!promptYesNo(`Create Manager repo "${name}" by uploading ${plan.repoRoot} (project: ${plan.localProjectId})?`)) {
die('aborted')
}
} else if (!process.stdin.isTTY && !yes) {
die('stdin is not a TTY; pass --yes to confirm creation')
}
const progress = createProgressReporter('push')
const onProgress = (p: MirrorProgress) => progress.tick(p.bytesSent)
const result = await mirrorUp(plan, {
api,
force,
create: { name, originUrl, branch },
onProgress,
})
progress.done()
info(`pushed ${plan.repoRoot} -> ${result.created ? 'created' : 'updated'} (repoId=${result.repoId}, branch=${result.branch})`)
} else if (plan.matched.length === 1) {
if (!force) {
try {
const divergence = await checkPushDivergence(plan.repoRoot, api, plan.matched[0]!.repoId)
if (divergence.diverged || divergence.serverDirty) {
force = guardDivergentPush(plan.matched[0]!.name, divergence)
}
} catch (error) {
if (!(error instanceof ManagerApiError && error.status === 404)) throw error
}
}
if (!full) {
try {
const result = await mirrorUpFast(plan, { api, force })
info(`pushed ${plan.repoRoot} -> ${plan.matched[0]!.name} via bundle (repoId=${result.repoId}, branch=${result.branch})`)
return
} catch (error) {
if (error instanceof MirrorAbort) throw error
process.stderr.write(`ocm: patch push failed: ${error instanceof Error ? error.message : String(error)}\n`)
confirmFullFallback()
}
}
const progress = createProgressReporter('push')
const onProgress = (p: MirrorProgress) => progress.tick(p.bytesSent)
const result = await mirrorUp(plan, { api, force, onProgress })
progress.done()
info(`pushed ${plan.repoRoot} -> ${plan.matched[0]!.name} (repoId=${result.repoId}, branch=${result.branch})`)
} else {
dieAmbiguousProjectMatch('push', plan.localProjectId, repos, plan.matched)
}
}
async function cmdPull(args: string[]): Promise<void> {
const parsed = parseRepoIdPositional(args, PULL_FLAGS)
if (parsed.error) die(parsed.error)
let force = false
let full = false
for (const arg of args) {
if (arg === '--force') force = true
else if (arg === '--full') full = true
}
const state = requireState()
const token = await requireToken(state)
const api = new ManagerApi(state.managerUrl, token)
const repos = await fetchRepos(state.managerUrl, token)
const remotes: RemoteRepoSummary[] = toRemoteRepoSummaries(repos)
const plan = await prepareMirror(process.cwd(), remotes)
const restriction = restrictMatchesToRequestedRepo(plan.matched, parsed.repoId, plan.localProjectId)
if (restriction.error) die(restriction.error)
plan.matched = restriction.matches
if (plan.matched.length === 0) {
die(`no matching Manager repo for project ${plan.localProjectId}.`)
}
if (plan.matched.length > 1) {
dieAmbiguousProjectMatch('pull', plan.localProjectId, repos, plan.matched)
}
if (!force) {
try {
const divergence = await checkPullDivergence(plan.repoRoot, api, plan.matched[0]!.repoId)
if (divergence.diverged) {
force = guardDivergentPull(plan.matched[0]!.name, divergence)
}
} catch (error) {
if (!(error instanceof ManagerApiError && error.status === 404)) throw error
}
}
if (!full) {
try {
await mirrorDownFast(plan.matched[0]!.repoId, plan.repoRoot, api, { force })
info(`pulled ${plan.matched[0]!.name} -> ${plan.repoRoot} via bundle`)
return
} catch (error) {
if (error instanceof MirrorAbort && !error.message.includes('falling back')) throw error
process.stderr.write(`ocm: patch pull failed: ${error instanceof Error ? error.message : String(error)}\n`)
confirmFullFallback()
}
}
const progress = createProgressReporter('pull')
try {
await mirrorDown(plan.matched[0]!.repoId, plan.repoRoot, api, { force, onProgress: (bytes) => progress.tick(bytes) })
} finally {
progress.done()
}
info(`pulled ${plan.matched[0]!.name} -> ${plan.repoRoot}`)
}
function getSourceDistDir(): string {
return resolve(dirname(fileURLToPath(import.meta.url)), '..', 'dist')
}
export async function cmdInstall(args: string[]): Promise<void> {
let configDir: string | undefined
let force = false
let link = true
for (let i = 0; i < args.length; i++) {
const arg = args[i]!
if (arg === '--force') force = true
else if (arg === '--no-link') link = false
else if (arg === '--dir') {
configDir = args[++i]
if (!configDir) die('usage: ocm install [--dir <path>] [--force] [--no-link]')
} else if (arg.startsWith('--dir=')) {
configDir = arg.slice('--dir='.length)
} else {
die(`unknown option: ${arg}. run \`ocm --help\``)
}
}
const resolvedConfigDir = configDir ?? resolveOpenCodeConfigDir()
let result
try {
result = installVendoredOcm({ sourceDistDir: getSourceDistDir(), configDir: resolvedConfigDir, force, link })
} catch (err) {
if (err instanceof InstallError) die(err.message)
throw err
}
info(`vendored ocm into ${result.pluginDir}`)
info(result.copied.length > 0 ? `copied: ${result.copied.join(', ')}` : 'package files already up to date')
info(result.configChanged ? `registered ${OCM_PLUGIN_SPEC} in ${result.configFile}` : `plugin already registered in ${result.configFile}`)
if (result.binLink === null) {
info('skipped the ocm symlink (--no-link)')
} else {
writeInstallNotice({ link: result.binLink, binDir: dirname(result.binLink), pathMissing: result.pathMissing })
info(result.binLinkChanged ? `linked ${result.binLink}` : `already linked at ${result.binLink}`)
if (result.pathMissing) info('note: add export PATH="$HOME/.local/bin:$PATH" to your shell rc')
}
}
async function main(): Promise<void> {
const [, , cmd, ...rest] = process.argv
if (cmd === '--help' || cmd === '-h' || cmd === 'help') {
process.stdout.write(USAGE)
return
}
if (cmd === '--version' || cmd === '-v' || cmd === 'version') {
info(VERSION)
return
}
try {
switch (cmd) {
case undefined:
await cmdDefault()
break
case 'login':
await cmdLogin(rest)
break
case 'logout':
await cmdLogout()
break
case 'status':
await cmdStatus()
break
case 'list':
case 'ls':
await cmdList()
break
case 'use':
case 'attach':
await cmdUse(rest)
break
case 'push':
await cmdPush(rest)
break
case 'pull':
await cmdPull(rest)
break
case 'install':
await cmdInstall(rest)
break
default:
die(`unknown command: ${cmd}. run \`ocm --help\``)
}
} catch (err) {
die(err instanceof Error ? err.message : String(err))
}
}
// Only run main when executed directly (not imported by tests).
const entryUrl = process.argv[1] ? `file://${process.argv[1]}` : ''
if (entryUrl === import.meta.url || process.argv[1]?.endsWith('/ocm.js') || process.argv[1]?.endsWith('/ocm')) {
void main()
}