mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
feat(ocm-cli): add session move with local history export and TUI plugin
This commit is contained in:
1 parent
ac8ab89b4a
commit
b4dd57a862
12 files changed
+178
-104
No files matched your search
+10
-16
@@ -61,32 +61,26 @@ tarball mirror. If the fast path fails, `ocm` prompts before reverting to the
|
||||
tarball mirror (and proceeds automatically when there is no TTY to prompt). It
|
||||
refuses to overwrite uncommitted local changes unless `--force` is passed.
|
||||
|
||||
## OpenCode plugin
|
||||
## OpenCode TUI plugin
|
||||
|
||||
The package default export is an OpenCode plugin entrypoint. Importing the
|
||||
plugin performs a best-effort local `ocm` symlink install and then returns an
|
||||
empty plugin object.
|
||||
|
||||
```ts
|
||||
import ocm from '@opencode-manager/ocm-cli'
|
||||
|
||||
export default [ocm]
|
||||
```
|
||||
|
||||
The package also exposes an OpenCode TUI plugin at
|
||||
The package exposes an OpenCode TUI plugin at
|
||||
`@opencode-manager/ocm-cli/tui`. It registers `/ocm-move`, which keeps the
|
||||
local session and copies the active session to the Manager after pushing the
|
||||
current repo state. Use it from inside an OpenCode session after `ocm login`
|
||||
and after the repo already exists on the Manager (`ocm push --create` if
|
||||
needed).
|
||||
|
||||
```ts
|
||||
import ocm from '@opencode-manager/ocm-cli'
|
||||
import ocmTui from '@opencode-manager/ocm-cli/tui'
|
||||
Enable it in `tui.json`:
|
||||
|
||||
export default [ocm, ocmTui]
|
||||
```jsonc
|
||||
{
|
||||
"plugin": ["@opencode-manager/ocm-cli/tui"]
|
||||
}
|
||||
```
|
||||
|
||||
The `ocm` binary is installed via the package `postinstall` (or `bin` field on
|
||||
global installs); the plugin surface is TUI-only.
|
||||
|
||||
## Requirements
|
||||
|
||||
- `opencode` available on `PATH`
|
||||
|
||||
+21
-4
@@ -115,7 +115,24 @@ function requireToken(state: OcmState): string {
|
||||
return token
|
||||
}
|
||||
|
||||
function attach(managerUrl: string, token: string, repo: ManagerRepo): never {
|
||||
async function warmUpInstance(managerUrl: string, token: string, directory: string): Promise<void> {
|
||||
const url = `${managerUrl}/api/opencode-proxy/session?directory=${encodeURIComponent(directory)}`
|
||||
for (let attempt = 1; attempt <= 3; attempt++) {
|
||||
try {
|
||||
const res = await fetch(url, { headers: { Authorization: `Bearer ${token}` } })
|
||||
if (res.ok) {
|
||||
await res.text()
|
||||
return
|
||||
}
|
||||
} catch {
|
||||
/* retry */
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, attempt * 500))
|
||||
}
|
||||
}
|
||||
|
||||
async function attach(managerUrl: string, token: string, repo: ManagerRepo): Promise<never> {
|
||||
await warmUpInstance(managerUrl, token, repo.directory)
|
||||
const proxyUrl = `${managerUrl}/api/opencode-proxy`
|
||||
const args = [
|
||||
'attach',
|
||||
@@ -251,7 +268,7 @@ async function cmdUse(args: string[]): Promise<void> {
|
||||
lastRepoBranch: repo.branch,
|
||||
})
|
||||
|
||||
attach(state.managerUrl, token, repo)
|
||||
await attach(state.managerUrl, token, repo)
|
||||
}
|
||||
|
||||
async function cmdDefault(): Promise<void> {
|
||||
@@ -284,13 +301,13 @@ async function cmdDefault(): Promise<void> {
|
||||
lastRepoDir: repo.directory,
|
||||
lastRepoBranch: repo.branch,
|
||||
})
|
||||
attach(state.managerUrl, token, toManagerRepo(repo))
|
||||
await attach(state.managerUrl, token, toManagerRepo(repo))
|
||||
return
|
||||
}
|
||||
case 'last': {
|
||||
const repo = result.repo
|
||||
info(`attaching to ${repo.name} (last used)`)
|
||||
attach(state.managerUrl, token, toManagerRepo(repo))
|
||||
await attach(state.managerUrl, token, toManagerRepo(repo))
|
||||
return
|
||||
}
|
||||
case 'cwd-ambiguous': {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@opencode-manager/ocm-cli",
|
||||
"version": "0.2.0",
|
||||
"version": "0.2.1",
|
||||
"description": "OpenCode Manager CLI: attach a local OpenCode TUI to a Manager-hosted repo.",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
@@ -9,11 +9,10 @@
|
||||
"directory": "ocm-cli"
|
||||
},
|
||||
"type": "module",
|
||||
"main": "./dist/plugin.js",
|
||||
"oc-plugin": [
|
||||
"tui"
|
||||
],
|
||||
"exports": {
|
||||
".": {
|
||||
"import": "./dist/plugin.js"
|
||||
},
|
||||
"./tui": {
|
||||
"import": "./dist/tui.js"
|
||||
}
|
||||
@@ -35,10 +34,10 @@
|
||||
"test:watch": "vitest",
|
||||
"prepublishOnly": "bun scripts/build.ts"
|
||||
},
|
||||
"dependencies": {},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.36.0",
|
||||
"@opencode-manager/shared": "workspace:*",
|
||||
"@types/bun": "^1.3.14",
|
||||
"@types/node": "^22.0.0",
|
||||
"eslint": "^9.39.1",
|
||||
"typescript": "^5.5.0",
|
||||
|
||||
@@ -13,6 +13,7 @@ async function bundleEntry(label: string, entrypoint: string, outputName: string
|
||||
outdir: dist,
|
||||
target: 'node',
|
||||
format: 'esm',
|
||||
external: ['bun:sqlite'],
|
||||
naming: { entry: outputName },
|
||||
})
|
||||
|
||||
@@ -25,7 +26,6 @@ async function bundleEntry(label: string, entrypoint: string, outputName: string
|
||||
}
|
||||
|
||||
await bundleEntry('ocm CLI', join('bin', 'ocm.ts'), 'ocm.js')
|
||||
await bundleEntry('opencode plugin entry', join('src', 'plugin.ts'), 'plugin.js')
|
||||
await bundleEntry('TUI plugin entry', join('src', 'tui-plugin.ts'), 'tui.js')
|
||||
|
||||
const ocmJsPath = join(dist, 'ocm.js')
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import { existsSync, readdirSync, statSync } from 'fs'
|
||||
import { homedir } from 'os'
|
||||
import { isAbsolute, join } from 'path'
|
||||
import type { HistoryEventRow } from './session-move.js'
|
||||
|
||||
function opencodeDataDir(): string {
|
||||
const xdg = process.env.XDG_DATA_HOME
|
||||
return xdg ? join(xdg, 'opencode') : join(homedir(), '.local', 'share', 'opencode')
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the opencode durable-event database path the same way
|
||||
* `Database.path()` does in opencode core: an `OPENCODE_DB` override wins,
|
||||
* then the default `opencode.db`, then the newest channel-suffixed variant
|
||||
* (`opencode-<channel>.db`) for non-release channels.
|
||||
*/
|
||||
export function resolveOpencodeDbPath(): string | null {
|
||||
const override = process.env.OPENCODE_DB
|
||||
const dataDir = opencodeDataDir()
|
||||
if (override) {
|
||||
if (override === ':memory:' || isAbsolute(override)) return override
|
||||
return join(dataDir, override)
|
||||
}
|
||||
|
||||
const defaultPath = join(dataDir, 'opencode.db')
|
||||
if (existsSync(defaultPath)) return defaultPath
|
||||
if (!existsSync(dataDir)) return null
|
||||
|
||||
const variants = readdirSync(dataDir)
|
||||
.filter((name) => name.startsWith('opencode-') && name.endsWith('.db'))
|
||||
.map((name) => join(dataDir, name))
|
||||
.sort((a, b) => statSync(b).mtimeMs - statSync(a).mtimeMs)
|
||||
|
||||
return variants[0] ?? null
|
||||
}
|
||||
|
||||
export async function readSessionEvents(sessionID: string): Promise<HistoryEventRow[]> {
|
||||
const dbPath = resolveOpencodeDbPath()
|
||||
if (!dbPath) {
|
||||
throw new Error('opencode database not found; is this machine running opencode with durable history?')
|
||||
}
|
||||
|
||||
const { Database } = await import('bun:sqlite')
|
||||
const db = new Database(dbPath, { readonly: true })
|
||||
try {
|
||||
const rows = db
|
||||
.query<{ id: string; aggregate_id: string; seq: number; type: string; data: string }, [string]>(
|
||||
'SELECT id, aggregate_id, seq, type, data FROM event WHERE aggregate_id = ? ORDER BY seq ASC',
|
||||
)
|
||||
.all(sessionID)
|
||||
|
||||
return rows.map((row) => ({
|
||||
id: row.id,
|
||||
aggregate_id: row.aggregate_id,
|
||||
seq: row.seq,
|
||||
type: row.type,
|
||||
data: JSON.parse(row.data) as Record<string, unknown>,
|
||||
}))
|
||||
} finally {
|
||||
db.close()
|
||||
}
|
||||
}
|
||||
@@ -165,7 +165,7 @@ export class ManagerApi {
|
||||
const query = opts.force === true ? '?force=1' : ''
|
||||
const headers: Record<string, string> = { ...this.headers(), 'Content-Type': 'application/octet-stream' }
|
||||
if (opts.branch) headers['X-OCM-Branch'] = opts.branch
|
||||
const body = Readable.toWeb(createReadStream(bundlePath)) as ReadableStream<Uint8Array>
|
||||
const body = Readable.toWeb(createReadStream(bundlePath)) as unknown as ReadableStream<Uint8Array>
|
||||
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/bundle${query}`, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
|
||||
@@ -1,59 +0,0 @@
|
||||
import { mkdirSync, symlinkSync, lstatSync, readlinkSync, unlinkSync, existsSync, chmodSync } from 'node:fs'
|
||||
import { homedir } from 'node:os'
|
||||
import { dirname, join, resolve } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const OCM_TARGET = join(PACKAGE_ROOT, 'dist', 'ocm.js')
|
||||
const BIN_DIR = join(homedir(), '.local', 'bin')
|
||||
const BIN_LINK = join(BIN_DIR, 'ocm')
|
||||
|
||||
function ensureSymlink(): { installed: boolean; message?: string } {
|
||||
if (!existsSync(OCM_TARGET)) {
|
||||
return { installed: false, message: `ocm-cli: missing ${OCM_TARGET}, skipping bin install` }
|
||||
}
|
||||
|
||||
try {
|
||||
chmodSync(OCM_TARGET, 0o755)
|
||||
} catch {
|
||||
// best effort
|
||||
}
|
||||
|
||||
try {
|
||||
mkdirSync(BIN_DIR, { recursive: true })
|
||||
} catch (err) {
|
||||
return { installed: false, message: `ocm-cli: cannot create ${BIN_DIR}: ${(err as Error).message}` }
|
||||
}
|
||||
|
||||
try {
|
||||
const stat = lstatSync(BIN_LINK)
|
||||
if (stat.isSymbolicLink()) {
|
||||
if (readlinkSync(BIN_LINK) === OCM_TARGET) {
|
||||
return { installed: false }
|
||||
}
|
||||
unlinkSync(BIN_LINK)
|
||||
} else {
|
||||
return { installed: false, message: `ocm-cli: ${BIN_LINK} exists and is not a symlink; leaving alone` }
|
||||
}
|
||||
} catch {
|
||||
// missing — fine
|
||||
}
|
||||
|
||||
try {
|
||||
symlinkSync(OCM_TARGET, BIN_LINK)
|
||||
} catch (err) {
|
||||
return { installed: false, message: `ocm-cli: failed to symlink ${BIN_LINK}: ${(err as Error).message}` }
|
||||
}
|
||||
|
||||
const onPath = (process.env.PATH ?? '').split(':').includes(BIN_DIR)
|
||||
const pathHint = onPath ? '' : ` (add "${BIN_DIR}" to your PATH to run \`ocm\`)`
|
||||
return { installed: true, message: `ocm-cli: installed \`ocm\` at ${BIN_LINK}${pathHint}` }
|
||||
}
|
||||
|
||||
const result = ensureSymlink()
|
||||
if (result.message) {
|
||||
process.stderr.write(`${result.message}\n`)
|
||||
}
|
||||
|
||||
const plugin = async (): Promise<Record<string, never>> => ({})
|
||||
export default plugin
|
||||
@@ -4,8 +4,9 @@ import { getToken } from './keychain.js'
|
||||
import { fetchRepos, toRemoteRepoSummaries } from './manager-repos.js'
|
||||
import { ManagerApi, ManagerApiError } from './manager-api.js'
|
||||
import { prepareMirror, checkPushDivergence, mirrorUpFast } from './mirror.js'
|
||||
import { transferSession, type HistoryEventRow } from './session-move.js'
|
||||
import { transferSession } from './session-move.js'
|
||||
import { createManagerReplay } from './remote-replay.js'
|
||||
import { readSessionEvents } from './local-history.js'
|
||||
|
||||
const tui = async (api: TuiPluginApi): Promise<void> => {
|
||||
api.keymap.registerLayer({
|
||||
@@ -13,7 +14,9 @@ const tui = async (api: TuiPluginApi): Promise<void> => {
|
||||
{
|
||||
name: 'ocm.session.move',
|
||||
title: 'Move session to Manager',
|
||||
description: 'Push repo state and move this session to OpenCode Manager',
|
||||
desc: 'Push repo state and move this session to OpenCode Manager',
|
||||
category: 'OpenCode Manager',
|
||||
namespace: 'palette',
|
||||
slashName: 'ocm-move',
|
||||
run: () => runSessionMove(api),
|
||||
},
|
||||
@@ -82,19 +85,9 @@ async function runSessionMove(api: TuiPluginApi): Promise<void> {
|
||||
api.ui.toast({ message: 'Pushing repo state…' })
|
||||
await mirrorUpFast(plan, { api: managerApi, force: false })
|
||||
|
||||
if (!api.client.sync) {
|
||||
api.ui.toast({ variant: 'error', message: 'Local opencode is too old for session move (needs /sync API)' })
|
||||
return
|
||||
}
|
||||
|
||||
const raw = await api.client.sync.history.list({ body: {} })
|
||||
const rows: HistoryEventRow[] = Array.isArray(raw)
|
||||
? (raw as HistoryEventRow[])
|
||||
: ((raw as { data?: HistoryEventRow[] })?.data ?? [])
|
||||
|
||||
const result = await transferSession(
|
||||
{ sessionID, localRoot: plan.repoRoot, remoteDirectory },
|
||||
{ fetchLocalHistory: async () => rows, replayEvents: createManagerReplay(state.managerUrl, token) },
|
||||
{ fetchLocalHistory: () => readSessionEvents(sessionID), replayEvents: createManagerReplay(state.managerUrl, token) },
|
||||
)
|
||||
|
||||
switch (result.kind) {
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
export type TuiRouteCurrent = { name: 'session'; params: { sessionID: string } } | { name: string; params?: Record<string, unknown> }
|
||||
export type TuiSessionInfo = { id: string; directory: string; title?: string }
|
||||
export type TuiToast = { title?: string; message: string; variant?: 'info' | 'success' | 'error' | 'warning' }
|
||||
export type TuiCommandDef = { name: string; title: string; description?: string; slashName?: string; run: () => void | Promise<void> }
|
||||
export type TuiCommandDef = { name: string; title: string; desc?: string; category?: string; namespace?: string; slashName?: string; run: () => void | Promise<void> }
|
||||
export type TuiPluginApi = {
|
||||
route: { readonly current: TuiRouteCurrent }
|
||||
state: { session: { get: (sessionID: string) => TuiSessionInfo | undefined } }
|
||||
ui: { toast: (input: TuiToast) => void }
|
||||
keymap: { registerLayer: (layer: { commands: TuiCommandDef[]; bindings?: Record<string, unknown> }) => unknown }
|
||||
client: { sync?: { history: { list: (opts: { body: Record<string, number> }) => Promise<unknown> } } }
|
||||
}
|
||||
export type TuiPluginModule = { id?: string; tui: (api: TuiPluginApi, options?: Record<string, unknown>) => Promise<void> }
|
||||
@@ -0,0 +1,52 @@
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync, utimesSync } from 'fs'
|
||||
import { tmpdir } from 'os'
|
||||
import { join } from 'path'
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import { resolveOpencodeDbPath } from '../src/local-history.js'
|
||||
|
||||
describe('resolveOpencodeDbPath', () => {
|
||||
let dataHome: string
|
||||
let dataDir: string
|
||||
const savedEnv = { XDG_DATA_HOME: process.env.XDG_DATA_HOME, OPENCODE_DB: process.env.OPENCODE_DB }
|
||||
|
||||
beforeEach(() => {
|
||||
dataHome = mkdtempSync(join(tmpdir(), 'ocm-dbpath-'))
|
||||
dataDir = join(dataHome, 'opencode')
|
||||
mkdirSync(dataDir)
|
||||
process.env.XDG_DATA_HOME = dataHome
|
||||
delete process.env.OPENCODE_DB
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
rmSync(dataHome, { recursive: true, force: true })
|
||||
if (savedEnv.XDG_DATA_HOME === undefined) delete process.env.XDG_DATA_HOME
|
||||
else process.env.XDG_DATA_HOME = savedEnv.XDG_DATA_HOME
|
||||
if (savedEnv.OPENCODE_DB === undefined) delete process.env.OPENCODE_DB
|
||||
else process.env.OPENCODE_DB = savedEnv.OPENCODE_DB
|
||||
})
|
||||
|
||||
it('honours an absolute OPENCODE_DB override', () => {
|
||||
process.env.OPENCODE_DB = '/tmp/custom.db'
|
||||
expect(resolveOpencodeDbPath()).toBe('/tmp/custom.db')
|
||||
})
|
||||
|
||||
it('resolves a relative OPENCODE_DB override against the data dir', () => {
|
||||
process.env.OPENCODE_DB = 'custom.db'
|
||||
expect(resolveOpencodeDbPath()).toBe(join(dataDir, 'custom.db'))
|
||||
})
|
||||
|
||||
it('prefers the default opencode.db when present', () => {
|
||||
writeFileSync(join(dataDir, 'opencode.db'), '', { flag: 'w' })
|
||||
writeFileSync(join(dataDir, 'opencode-dev.db'), '')
|
||||
expect(resolveOpencodeDbPath()).toBe(join(dataDir, 'opencode.db'))
|
||||
})
|
||||
|
||||
it('falls back to the newest channel variant', () => {
|
||||
const older = join(dataDir, 'opencode-old.db')
|
||||
const newer = join(dataDir, 'opencode-dev.db')
|
||||
writeFileSync(older, '')
|
||||
writeFileSync(newer, '')
|
||||
utimesSync(older, new Date('2024-01-01'), new Date('2024-01-01'))
|
||||
expect(resolveOpencodeDbPath()).toBe(newer)
|
||||
})
|
||||
})
|
||||
@@ -4,7 +4,7 @@
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"lib": ["ES2022", "DOM"],
|
||||
"types": ["node"],
|
||||
"types": ["node", "bun"],
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
|
||||
Generated
+18
-1
@@ -281,6 +281,9 @@ importers:
|
||||
'@opencode-manager/shared':
|
||||
specifier: workspace:*
|
||||
version: link:../shared
|
||||
'@types/bun':
|
||||
specifier: ^1.3.14
|
||||
version: 1.3.14
|
||||
'@types/node':
|
||||
specifier: ^22.0.0
|
||||
version: 22.19.19
|
||||
@@ -1594,6 +1597,9 @@ packages:
|
||||
'@types/bun@1.3.10':
|
||||
resolution: {integrity: sha512-0+rlrUrOrTSskibryHbvQkDOWRJwJZqZlxrUs1u4oOoTln8+WIXBPmAuCF35SWB2z4Zl3E84Nl/D0P7803nigQ==}
|
||||
|
||||
'@types/bun@1.3.14':
|
||||
resolution: {integrity: sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw==}
|
||||
|
||||
'@types/chai@5.2.3':
|
||||
resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==}
|
||||
|
||||
@@ -2098,6 +2104,9 @@ packages:
|
||||
bun-types@1.3.10:
|
||||
resolution: {integrity: sha512-tcpfCCl6XWo6nCVnpcVrxQ+9AYN1iqMIzgrSKYMB/fjLtV2eyAVEg7AxQJuCq/26R6HpKWykQXuSOq/21RYcbg==}
|
||||
|
||||
bun-types@1.3.14:
|
||||
resolution: {integrity: sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ==}
|
||||
|
||||
cac@6.7.14:
|
||||
resolution: {integrity: sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==}
|
||||
engines: {node: '>=8'}
|
||||
@@ -5434,6 +5443,10 @@ snapshots:
|
||||
dependencies:
|
||||
bun-types: 1.3.10
|
||||
|
||||
'@types/bun@1.3.14':
|
||||
dependencies:
|
||||
bun-types: 1.3.14
|
||||
|
||||
'@types/chai@5.2.3':
|
||||
dependencies:
|
||||
'@types/deep-eql': 4.0.2
|
||||
@@ -5794,7 +5807,7 @@ snapshots:
|
||||
sirv: 3.0.2
|
||||
tinyglobby: 0.2.15
|
||||
tinyrainbow: 2.0.0
|
||||
vitest: 3.2.4(@types/debug@4.1.12)(@types/node@24.10.4)(@vitest/ui@3.2.4)(jiti@2.6.1)(jsdom@27.4.0)(lightningcss@1.30.2)(terser@5.46.0)(yaml@2.9.0)
|
||||
vitest: 3.2.4(@types/debug@4.1.12)(@types/node@22.19.19)(@vitest/ui@3.2.4)(jiti@2.6.1)(jsdom@27.4.0)(lightningcss@1.30.2)(terser@5.46.0)(yaml@2.9.0)
|
||||
|
||||
'@vitest/utils@3.2.4':
|
||||
dependencies:
|
||||
@@ -6009,6 +6022,10 @@ snapshots:
|
||||
dependencies:
|
||||
'@types/node': 24.10.4
|
||||
|
||||
bun-types@1.3.14:
|
||||
dependencies:
|
||||
'@types/node': 24.10.4
|
||||
|
||||
cac@6.7.14: {}
|
||||
|
||||
callsites@3.1.0: {}
|
||||
|
||||
Reference in new issue
Block a user