Files
opencode-manager/ocm-cli/bin/ocm.ts

662 lines
24 KiB
TypeScript

import { spawn, spawnSync } from 'child_process'
import { basename, dirname, resolve } from 'path'
import { fileURLToPath } from 'url'
import { trimUrlTrailingSlashes } from '@opencode-manager/shared/utils'
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 { 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, resolveBranchCheckout } 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'
import { resolveManagerAuth } from '../src/manager-auth.js'
import type { ManagerAuthOk } from '../src/manager-auth.js'
const USAGE = `ocm v${VERSION} - OpenCode Manager workspace launcher
Usage:
ocm Attach to the Manager repo matching $PWD's OpenCode
project id; inside a git repo with no match, launch
local opencode; outside a git repo, use the last
selected repo, else launch local opencode
ocm login <url> [token] [--name <name>]
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?',
)
}
async function requireAuth(): Promise<{ auth: ManagerAuthOk; state: OcmState }> {
const auth = await resolveManagerAuth()
if (!auth.ok) die(auth.message)
return { auth, state: readState()! }
}
async function attach(managerUrl: string, token: string, repo: ManagerRepo, cwd: string): Promise<void> {
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}`))
}
function findRepo(repos: ManagerRepo[], needle: string): ManagerRepo | undefined {
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())
}
const LOGIN_USAGE = 'usage: ocm login <url> [token] [--name <name>]'
interface LoginArgs {
url: string
token?: string
managerName?: string
}
function parseLoginArgs(args: string[]): LoginArgs {
const positional: string[] = []
const managerNames: string[] = []
for (let index = 0; index < args.length; index++) {
const arg = args[index]
if (arg === '--name') {
const value = args[index + 1]
if (!value || value.startsWith('-')) die(LOGIN_USAGE)
managerNames.push(value)
index++
continue
}
if (arg.startsWith('-')) die(LOGIN_USAGE)
positional.push(arg)
}
if (managerNames.length > 1) die(LOGIN_USAGE)
const url = positional[0]
if (!url) die(LOGIN_USAGE)
return { url, token: positional[1], managerName: managerNames[0] }
}
export async function cmdLogin(args: string[]): Promise<void> {
const { url, token: providedToken, managerName } = parseLoginArgs(args)
const normalisedUrl = trimUrlTrailingSlashes(url)
let token = providedToken
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()
const sameManager = existing ? trimUrlTrailingSlashes(existing.managerUrl) === normalisedUrl : false
writeState({
...existing,
managerUrl: normalisedUrl,
managerName: managerName ?? (sameManager ? existing?.managerName : undefined),
})
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}`)
if (state.managerName) info(`manager name: ${state.managerName}`)
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 { auth } = await requireAuth()
const repos = await fetchRepos(auth.managerUrl, auth.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 { auth, state } = await requireAuth()
const repos = await fetchRepos(auth.managerUrl, auth.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(auth.managerUrl, auth.token, repo, process.cwd())
}
async function cmdDefault(): Promise<void> {
info(`ocm v${VERSION}`)
const { auth, state } = await requireAuth()
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(auth.managerUrl, auth.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(auth.managerUrl, auth.token, toManagerRepo(repo), result.repoRoot)
return
}
case 'last': {
const repo = result.repo
info(`attaching to ${repo.name} (last used)`)
await attach(auth.managerUrl, auth.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'): void {
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}`))
}
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 { auth } = await requireAuth()
const api = new ManagerApi(auth.managerUrl, auth.token)
const repos = await fetchRepos(auth.managerUrl, auth.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) {
const selection = await resolveBranchCheckout(api, plan.matched[0]!.repoId, plan.repoRoot)
if (!force) {
try {
const divergence = await checkPushDivergence(plan.repoRoot, api, plan.matched[0]!.repoId, selection.directory)
if (divergence.diverged || divergence.serverDirty) {
force = guardDivergentPush(plan.matched[0]!.name, divergence)
}
} catch (error) {
if (!(error instanceof ManagerApiError && error.status === 404)) throw error
}
}
if (selection.directory && full) {
die(`a Manager worktree is checked out for branch ${selection.targetBranch ?? 'this branch'}; --full would overwrite the main checkout. Run without --full.`)
}
if (!full) {
try {
const result = await mirrorUpFast(plan, {
api,
force,
directory: selection.directory,
targetBranch: selection.targetBranch,
requireCurrentBranch: selection.directory !== undefined,
})
const via = selection.directory ? ` into Manager worktree ${selection.directory}` : ''
info(`pushed ${plan.repoRoot} -> ${plan.matched[0]!.name}${via} via bundle (repoId=${result.repoId}, branch=${result.branch})`)
return
} catch (error) {
if (selection.directory) {
die(`patch push to Manager worktree ${selection.directory} failed: ${error instanceof Error ? error.message : String(error)}. Not falling back to a full mirror because it would overwrite the main checkout.`)
}
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)
}
}
export 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 { auth } = await requireAuth()
const api = new ManagerApi(auth.managerUrl, auth.token)
const repos = await fetchRepos(auth.managerUrl, auth.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)
}
const localBranch = getBranchName(plan.repoRoot)
const selection = await resolveBranchCheckout(api, plan.matched[0]!.repoId, plan.repoRoot)
if (!force) {
try {
const divergence = await checkPullDivergence(plan.repoRoot, api, plan.matched[0]!.repoId, selection.directory)
if (divergence.diverged) {
force = guardDivergentPull(plan.matched[0]!.name, divergence)
}
} catch (error) {
if (!(error instanceof ManagerApiError && error.status === 404)) throw error
}
}
if (selection.directory && full) {
die(`a Manager worktree is checked out for branch ${selection.targetBranch ?? 'this branch'}; --full cannot target it. Run without --full.`)
}
if (!full) {
try {
await mirrorDownFast(plan.matched[0]!.repoId, plan.repoRoot, api, {
force,
directory: selection.directory,
sourceBranch: selection.targetBranch,
targetBranch: selection.targetBranch ? (localBranch ?? undefined) : undefined,
})
const from = selection.directory ? ` from Manager worktree ${selection.directory}` : ''
info(`pulled ${plan.matched[0]!.name}${from} -> ${plan.repoRoot} via bundle`)
return
} catch (error) {
if (selection.directory) {
die(`patch pull from Manager worktree ${selection.directory} failed: ${error instanceof Error ? error.message : String(error)}. Not falling back to a full mirror because it would overwrite the main checkout.`)
}
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))
}
}
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()
}