mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
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:
1 parent
6c2ebd764b
commit
dacde879d6
383 files changed
+29905
-46566
No files matched your search
@@ -0,0 +1,3 @@
|
||||
export function delay(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms))
|
||||
}
|
||||
@@ -10,7 +10,7 @@ function isPermissionError(err: unknown): boolean {
|
||||
return code === 'EACCES' || code === 'EPERM'
|
||||
}
|
||||
|
||||
function removeQuietly(filePath: string): void {
|
||||
export function removeQuietly(filePath: string): void {
|
||||
try {
|
||||
unlinkSync(filePath)
|
||||
} catch {
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
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()
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import { getRepoRoot, getDirtyPaths, getHeadSha, getBranchName, getMirrorPatch,
|
||||
import { resolveOpenCodeProjectId } from '@opencode-manager/shared/project-id'
|
||||
import type { ManagerApi } from './manager-api.js'
|
||||
import { ManagerApiError } from './manager-api.js'
|
||||
import { delay } from './delay.js'
|
||||
|
||||
const HARDCODED_EXCLUDES = ['node_modules', 'dist', '.next', '.venv', '__pycache__', '.turbo', '.DS_Store', '._*']
|
||||
const PART_RETRIES = 3
|
||||
@@ -147,10 +148,6 @@ export interface MirrorUpOpts {
|
||||
onProgress?: (p: MirrorProgress) => void
|
||||
}
|
||||
|
||||
function delay(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms))
|
||||
}
|
||||
|
||||
function isRetryablePartError(err: unknown): boolean {
|
||||
if (err instanceof ManagerApiError) {
|
||||
return err.status >= 500 || err.status === 408 || err.status === 429
|
||||
|
||||
@@ -36,6 +36,6 @@ export function pushPhaseProgress(phase: MirrorUpFastPhase): MoveProgress {
|
||||
}
|
||||
}
|
||||
|
||||
export function replayProgress(replayed: number, total: number): MoveProgress {
|
||||
return { label: `replaying session ${replayed}/${total} events`, fraction: total > 0 ? replayed / total : null }
|
||||
export function importProgress(imported: number, total: number): MoveProgress {
|
||||
return { label: `importing session ${imported}/${total} messages`, fraction: total > 0 ? imported / total : null }
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
import type { ReplayEvent } from './session-move.js'
|
||||
|
||||
export function createManagerReplay(managerUrl: string, token: string) {
|
||||
return async (remoteDirectory: string, events: ReplayEvent[]): Promise<{ sessionID: string }> => {
|
||||
const url = `${managerUrl}/api/opencode-proxy/sync/replay?directory=${encodeURIComponent(remoteDirectory)}`
|
||||
const res = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ directory: remoteDirectory, events }),
|
||||
})
|
||||
|
||||
if (!res.ok) {
|
||||
const text = await res.text().catch(() => '')
|
||||
throw new Error(`replay failed (${res.status}): ${text.slice(0, 200)}`)
|
||||
}
|
||||
|
||||
return (await res.json()) as { sessionID: string }
|
||||
}
|
||||
}
|
||||
|
||||
export function createManagerPromptAsync(managerUrl: string, token: string) {
|
||||
return async (remoteDirectory: string, sessionID: string, text: string): Promise<void> => {
|
||||
const url = `${managerUrl}/api/opencode-proxy/session/${encodeURIComponent(sessionID)}/prompt_async?directory=${encodeURIComponent(remoteDirectory)}`
|
||||
const res = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ noReply: true, parts: [{ type: 'text', text, synthetic: true }] }),
|
||||
})
|
||||
if (!res.ok) {
|
||||
const body = await res.text().catch(() => '')
|
||||
throw new Error(`prompt_async failed (${res.status}): ${body.slice(0, 200)}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { createOpenCodeApi, isSessionNotFoundError } from '@opencode-manager/shared/opencode'
|
||||
import type { SessionTransferData } from '@opencode-manager/shared/opencode'
|
||||
import { repoProxyBaseUrl } from './repo-proxy.js'
|
||||
|
||||
export type ManagerSessionTransfer = ReturnType<typeof createManagerSessionTransfer>
|
||||
|
||||
export function createManagerSessionTransfer(managerUrl: string, token: string) {
|
||||
const api = createOpenCodeApi({
|
||||
baseUrl: repoProxyBaseUrl(managerUrl),
|
||||
password: token,
|
||||
})
|
||||
|
||||
return {
|
||||
sessionExists: async (sessionID: string): Promise<boolean> => {
|
||||
try {
|
||||
await api.session.get({ sessionID })
|
||||
return true
|
||||
} catch (err) {
|
||||
if (isSessionNotFoundError(err)) return false
|
||||
throw err
|
||||
}
|
||||
},
|
||||
importSession: async (remoteDirectory: string, data: SessionTransferData): Promise<{ sessionID: string }> => {
|
||||
const session = await api.session.import({
|
||||
info: data.info,
|
||||
messages: data.messages,
|
||||
location: { directory: remoteDirectory },
|
||||
})
|
||||
return { sessionID: session.id }
|
||||
},
|
||||
addReminder: (sessionID: string, text: string) => api.session.synthetic({ sessionID, text, resume: false }),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import packageJson from '../package.json' with { type: 'json' }
|
||||
import { delay } from './delay.js'
|
||||
import { describeCause } from './token-store.js'
|
||||
|
||||
export const OCM_VERSION = packageJson.version
|
||||
export const MIN_MANAGER_VERSION = '0.19.0'
|
||||
|
||||
export class ManagerTooOldError extends Error {
|
||||
constructor(managerUrl: string) {
|
||||
super(`OpenCode Manager at ${managerUrl} is too old for ocm ${OCM_VERSION}; upgrade the Manager to >= ${MIN_MANAGER_VERSION}`)
|
||||
this.name = 'ManagerTooOldError'
|
||||
}
|
||||
}
|
||||
|
||||
export class RepoProxyNotFoundError extends Error {
|
||||
constructor(managerUrl: string, repoId: number) {
|
||||
super(`repo ${repoId} is not available on OpenCode Manager at ${managerUrl} (missing or not ready)`)
|
||||
this.name = 'RepoProxyNotFoundError'
|
||||
}
|
||||
}
|
||||
|
||||
export class ManagerTokenInvalidError extends Error {
|
||||
constructor(managerUrl: string) {
|
||||
super(`OpenCode Manager rejected the token for ${managerUrl} (HTTP 401). The token may have been rotated: copy the current one from Settings -> Manager Internal Token, then run \`ocm login ${managerUrl}\` to store it again.`)
|
||||
this.name = 'ManagerTokenInvalidError'
|
||||
}
|
||||
}
|
||||
|
||||
export class RepoProxyResponseError extends Error {
|
||||
constructor(managerUrl: string, status: number, body: string) {
|
||||
const detail = body.trim()
|
||||
super(`OpenCode Manager at ${managerUrl} returned HTTP ${status} from the repo proxy${detail ? `: ${detail}` : ''}`)
|
||||
this.name = 'RepoProxyResponseError'
|
||||
}
|
||||
}
|
||||
|
||||
export class RepoProxyUnreachableError extends Error {
|
||||
constructor(managerUrl: string, cause: unknown) {
|
||||
super(`could not reach OpenCode Manager at ${managerUrl}: ${describeCause(cause)}`, { cause })
|
||||
this.name = 'RepoProxyUnreachableError'
|
||||
}
|
||||
}
|
||||
|
||||
export type WarmRepoProxyOptions = {
|
||||
attempts?: number
|
||||
fetch?: typeof fetch
|
||||
wait?: (ms: number) => Promise<void>
|
||||
}
|
||||
|
||||
export function repoProxyBaseUrl(managerUrl: string): string {
|
||||
return `${managerUrl}/api/opencode-proxy`
|
||||
}
|
||||
|
||||
export function repoProxyUrl(managerUrl: string, repoId: number): string {
|
||||
return `${repoProxyBaseUrl(managerUrl)}/repos/${repoId}`
|
||||
}
|
||||
|
||||
function isRepoNotFoundBody(body: string): boolean {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(body)
|
||||
return typeof parsed === 'object' && parsed !== null && (parsed as { error?: unknown }).error === 'Repo not found'
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export async function warmRepoProxy(managerUrl: string, token: string, repoId: number, options: WarmRepoProxyOptions = {}): Promise<void> {
|
||||
const fetchImpl = options.fetch ?? fetch
|
||||
const attempts = Math.max(1, options.attempts ?? 3)
|
||||
const wait = options.wait ?? delay
|
||||
const url = `${repoProxyUrl(managerUrl, repoId)}/api/session?limit=1`
|
||||
|
||||
for (let attempt = 1; attempt <= attempts; attempt++) {
|
||||
let res: Response | null = null
|
||||
let networkError: unknown
|
||||
try {
|
||||
res = await fetchImpl(url, { headers: { Authorization: `Bearer ${token}` } })
|
||||
} catch (err) {
|
||||
networkError = err
|
||||
}
|
||||
|
||||
const isFinalAttempt = attempt === attempts
|
||||
|
||||
if (res) {
|
||||
const body = await res.text().catch(() => '')
|
||||
if (res.ok) return
|
||||
if (res.status === 404) {
|
||||
throw isRepoNotFoundBody(body) ? new RepoProxyNotFoundError(managerUrl, repoId) : new ManagerTooOldError(managerUrl)
|
||||
}
|
||||
if (res.status === 401) {
|
||||
throw new ManagerTokenInvalidError(managerUrl)
|
||||
}
|
||||
if (isFinalAttempt) {
|
||||
throw new RepoProxyResponseError(managerUrl, res.status, body)
|
||||
}
|
||||
} else if (isFinalAttempt) {
|
||||
throw new RepoProxyUnreachableError(managerUrl, networkError)
|
||||
}
|
||||
|
||||
await wait(attempt * 500)
|
||||
}
|
||||
}
|
||||
+60
-142
@@ -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))
|
||||
}
|
||||
@@ -45,6 +45,14 @@ export function clearState(): void {
|
||||
}
|
||||
}
|
||||
|
||||
export function writeInstallNotice(notice: InstallNotice): void {
|
||||
try {
|
||||
writeJsonFileAtomic(INSTALL_NOTICE_FILE, notice)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
export function readInstallNotice(): InstallNotice | null {
|
||||
let parsed: InstallNotice | null
|
||||
try {
|
||||
|
||||
@@ -1,38 +1,13 @@
|
||||
import type { TuiPluginApi } from './tui-types.js'
|
||||
import type { Context } from '@opencode/plugin/tui/context'
|
||||
|
||||
export function confirmDialog(api: TuiPluginApi, props: { title: string; message: string }): Promise<boolean> {
|
||||
return new Promise<boolean>((resolve) => {
|
||||
let settled = false
|
||||
const settle = (value: boolean, clearDialog = true) => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
if (clearDialog) api.ui.dialog.clear()
|
||||
resolve(value)
|
||||
}
|
||||
api.ui.dialog.replace(
|
||||
() => api.ui.DialogConfirm({ ...props, onConfirm: () => settle(true), onCancel: () => settle(false) }),
|
||||
() => settle(false, false),
|
||||
)
|
||||
})
|
||||
export function confirmDialog(context: Context, props: { title: string; message: string }): Promise<boolean> {
|
||||
return context.ui.dialog.confirm(props).then((value) => value === true)
|
||||
}
|
||||
|
||||
export function selectDialog<Value>(
|
||||
api: TuiPluginApi,
|
||||
context: Context,
|
||||
title: string,
|
||||
options: { title: string; description?: string; value: Value }[],
|
||||
): Promise<Value | undefined> {
|
||||
return new Promise<Value | undefined>((resolve) => {
|
||||
let settled = false
|
||||
const settle = (value: Value | undefined, clearDialog = true) => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
if (clearDialog) api.ui.dialog.clear()
|
||||
resolve(value)
|
||||
}
|
||||
const mapped = options.map((o) => ({ ...o, onSelect: () => settle(o.value) }))
|
||||
api.ui.dialog.replace(
|
||||
() => api.ui.DialogSelect({ title, options: mapped, onSelect: (o) => settle(o.value as Value) }),
|
||||
() => settle(undefined, false),
|
||||
)
|
||||
})
|
||||
}
|
||||
return context.ui.dialog.select({ title, options })
|
||||
}
|
||||
+75
-56
@@ -1,4 +1,4 @@
|
||||
import type { TuiPluginApi } from './tui-types.js'
|
||||
import type { Context } from '@opencode/plugin/tui/context'
|
||||
import { readInstallNotice, readState } from './state.js'
|
||||
import { getToken } from './internal-token-store.js'
|
||||
import { TokenStoreError } from './token-store.js'
|
||||
@@ -9,38 +9,46 @@ import { prepareMirror, checkPushDivergence, describePushDivergence, mirrorUpFas
|
||||
import type { MirrorPlan, RemoteRepoSummary } from './mirror.js'
|
||||
import { getBranchName } from './local-repo.js'
|
||||
import { transferSession, moveReminderText } from './session-move.js'
|
||||
import { createManagerReplay, createManagerPromptAsync } from './remote-replay.js'
|
||||
import { readSessionEvents } from './local-history.js'
|
||||
import { createManagerSessionTransfer } from './remote-session.js'
|
||||
import type { ManagerSessionTransfer } from './remote-session.js'
|
||||
import { confirmDialog, selectDialog } from './tui-dialogs.js'
|
||||
import { setPendingWarp, runPendingWarp } from './warp.js'
|
||||
import { pushPhaseProgress, replayProgress } from './move-progress.js'
|
||||
import { pushPhaseProgress, importProgress } from './move-progress.js'
|
||||
import { warmRepoProxy } from './repo-proxy.js'
|
||||
import type { MoveProgress } from './move-progress.js'
|
||||
|
||||
export type MoveProgressSetter = (progress: MoveProgress | null) => void
|
||||
|
||||
export async function setupOcm(api: TuiPluginApi, setMoveProgress: MoveProgressSetter): Promise<void> {
|
||||
showInstallNotice(api)
|
||||
api.keymap.registerLayer({
|
||||
commands: [
|
||||
{
|
||||
name: 'ocm.session.move',
|
||||
title: 'Move session to Manager',
|
||||
desc: 'Push repo state and move this session to OpenCode Manager',
|
||||
category: 'OpenCode Manager',
|
||||
namespace: 'palette',
|
||||
slashName: 'ocm-move',
|
||||
run: () => runSessionMove(api, setMoveProgress),
|
||||
},
|
||||
],
|
||||
export async function setupOcm(context: Context, setMoveProgress: MoveProgressSetter): Promise<() => void> {
|
||||
showInstallNotice(context)
|
||||
context.ui.slot({
|
||||
append: 'app',
|
||||
render: () => {
|
||||
context.keymap.layer(() => ({
|
||||
mode: 'global',
|
||||
commands: [
|
||||
{
|
||||
id: 'ocm.session.move',
|
||||
title: 'Move session to Manager',
|
||||
description: 'Push repo state and move this session to OpenCode Manager',
|
||||
group: 'OpenCode Manager',
|
||||
palette: true,
|
||||
slash: { name: 'ocm-move' },
|
||||
run: () => runSessionMove(context, setMoveProgress),
|
||||
},
|
||||
],
|
||||
}))
|
||||
return null
|
||||
},
|
||||
})
|
||||
api.lifecycle.onDispose(() => runPendingWarp())
|
||||
return () => runPendingWarp()
|
||||
}
|
||||
|
||||
function showInstallNotice(api: TuiPluginApi): void {
|
||||
function showInstallNotice(context: Context): void {
|
||||
const notice = readInstallNotice()
|
||||
if (!notice) return
|
||||
|
||||
api.ui.toast({
|
||||
context.ui.toast.show({
|
||||
variant: 'success',
|
||||
title: 'ocm installed',
|
||||
message: notice.pathMissing
|
||||
@@ -50,6 +58,16 @@ function showInstallNotice(api: TuiPluginApi): void {
|
||||
})
|
||||
}
|
||||
|
||||
async function describeMoveBlocker(transfer: ManagerSessionTransfer, sessionID: string, parentID: string | undefined): Promise<string | null> {
|
||||
if (await transfer.sessionExists(sessionID)) {
|
||||
return `Session ${sessionID} is already on the Manager, so it cannot be moved again. Nothing was pushed. Run \`ocm\` to attach to it.`
|
||||
}
|
||||
if (parentID && !(await transfer.sessionExists(parentID))) {
|
||||
return `This is a subagent session and its parent ${parentID} is not on the Manager. Move the parent session first. Nothing was pushed.`
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
async function describeRemoteDiscard(repoRoot: string, managerApi: ManagerApi, repoId: number): Promise<string[]> {
|
||||
try {
|
||||
return describePushDivergence(await checkPushDivergence(repoRoot, managerApi, repoId))
|
||||
@@ -83,24 +101,24 @@ async function resolveMoveTarget(managerApi: ManagerApi, matched: RemoteRepoSumm
|
||||
return managerApi.mirrorTargetPlan(matched.repoId, localBranch)
|
||||
}
|
||||
|
||||
async function runSessionMove(api: TuiPluginApi, setMoveProgress: MoveProgressSetter): Promise<void> {
|
||||
async function runSessionMove(context: Context, setMoveProgress: MoveProgressSetter): Promise<void> {
|
||||
try {
|
||||
const current = api.route.current
|
||||
if (current.name !== 'session' || !current.params) {
|
||||
api.ui.toast({ variant: 'error', message: 'Not in a session' })
|
||||
const current = context.ui.router.current()
|
||||
if (current.type !== 'session') {
|
||||
context.ui.toast.show({ variant: 'error', message: 'Not in a session' })
|
||||
return
|
||||
}
|
||||
const sessionID = String(current.params.sessionID)
|
||||
const sessionID = current.sessionID
|
||||
|
||||
const session = api.state.session.get(sessionID)
|
||||
if (!session?.directory) {
|
||||
api.ui.toast({ variant: 'error', message: 'Session has no directory' })
|
||||
const session = context.data.session.get(sessionID)
|
||||
if (!session?.location.directory) {
|
||||
context.ui.toast.show({ variant: 'error', message: 'Session has no directory' })
|
||||
return
|
||||
}
|
||||
|
||||
const state = readState()
|
||||
if (!state?.managerUrl) {
|
||||
api.ui.toast({ variant: 'error', message: 'No manager configured. Run `ocm login <url>` first.' })
|
||||
context.ui.toast.show({ variant: 'error', message: 'No manager configured. Run `ocm login <url>` first.' })
|
||||
return
|
||||
}
|
||||
|
||||
@@ -109,34 +127,43 @@ async function runSessionMove(api: TuiPluginApi, setMoveProgress: MoveProgressSe
|
||||
token = await getToken(state.managerUrl)
|
||||
} catch (err) {
|
||||
const reason = err instanceof TokenStoreError ? err.message : String(err)
|
||||
api.ui.toast({ variant: 'error', message: `Token store unavailable: ${reason}` })
|
||||
context.ui.toast.show({ variant: 'error', message: `Token store unavailable: ${reason}` })
|
||||
return
|
||||
}
|
||||
if (!token) {
|
||||
api.ui.toast({ variant: 'error', message: `No token stored. Run \`ocm login ${state.managerUrl}\`.` })
|
||||
context.ui.toast.show({ variant: 'error', message: `No token stored. Run \`ocm login ${state.managerUrl}\`.` })
|
||||
return
|
||||
}
|
||||
|
||||
const repos = await fetchRepos(state.managerUrl, token)
|
||||
const plan = await prepareMirror(session.directory, toRemoteRepoSummaries(repos))
|
||||
const plan = await prepareMirror(session.location.directory, toRemoteRepoSummaries(repos))
|
||||
|
||||
if (plan.matched.length === 0) {
|
||||
api.ui.toast({ variant: 'error', message: 'No matching Manager repo; run `ocm push --create` first' })
|
||||
context.ui.toast.show({ variant: 'error', message: 'No matching Manager repo; run `ocm push --create` first' })
|
||||
return
|
||||
}
|
||||
|
||||
const localBranch = getBranchName(plan.repoRoot)
|
||||
const matched = pickMatchedRepo(plan.matched, localBranch)
|
||||
?? await selectDialog(api, 'Move session to Manager repo', plan.matched.map((r) => ({ title: r.name, description: `id=${r.repoId} branch=${r.branch ?? '-'}`, value: r })))
|
||||
?? await selectDialog(context, 'Move session to Manager repo', plan.matched.map((r) => ({ title: r.name, description: `id=${r.repoId} branch=${r.branch ?? '-'}`, value: r })))
|
||||
if (!matched) return
|
||||
const matchedRepoId = matched.repoId
|
||||
const remoteRepo = repos.find((r) => r.repoId === matchedRepoId)!
|
||||
|
||||
await warmRepoProxy(state.managerUrl, token, matchedRepoId)
|
||||
|
||||
const transfer = createManagerSessionTransfer(state.managerUrl, token)
|
||||
const blocker = await describeMoveBlocker(transfer, sessionID, session.parentID)
|
||||
if (blocker) {
|
||||
context.ui.toast.show({ variant: 'error', message: blocker })
|
||||
return
|
||||
}
|
||||
|
||||
const managerApi = new ManagerApi(state.managerUrl, token)
|
||||
const target = await resolveMoveTarget(managerApi, matched, remoteRepo.directory, localBranch)
|
||||
const discardReasons = target.repoId === null ? [] : await describeRemoteDiscard(plan.repoRoot, managerApi, target.repoId)
|
||||
|
||||
const proceed = await confirmDialog(api, {
|
||||
const proceed = await confirmDialog(context, {
|
||||
title: 'Move session to Manager',
|
||||
message: moveConfirmMessage(matched.name, target, discardReasons),
|
||||
})
|
||||
@@ -159,42 +186,34 @@ async function runSessionMove(api: TuiPluginApi, setMoveProgress: MoveProgressSe
|
||||
const result = await transferSession(
|
||||
{ sessionID, localRoot: plan.repoRoot, remoteDirectory },
|
||||
{
|
||||
fetchLocalHistory: () => readSessionEvents(sessionID),
|
||||
replayEvents: createManagerReplay(state.managerUrl, token),
|
||||
onProgress: (replayed, total) => setMoveProgress(replayProgress(replayed, total)),
|
||||
exportSession: (id) => context.client.session.export({ sessionID: id }),
|
||||
importSession: transfer.importSession,
|
||||
onProgress: (transferred, total) => setMoveProgress(importProgress(transferred, total)),
|
||||
},
|
||||
)
|
||||
|
||||
switch (result.kind) {
|
||||
case 'moved': {
|
||||
setMoveProgress({ label: 'notifying moved session', fraction: null })
|
||||
await createManagerPromptAsync(state.managerUrl, token)(remoteDirectory, result.sessionID, moveReminderText(remoteDirectory)).catch(() => undefined)
|
||||
await transfer.addReminder(result.sessionID, moveReminderText(remoteDirectory)).catch(() => undefined)
|
||||
setMoveProgress(null)
|
||||
const warp = await confirmDialog(api, { title: 'Attach to moved session?', message: 'Exit this TUI and attach to the moved session on the Manager now?' })
|
||||
const warp = await confirmDialog(context, { title: 'Attach to moved session?', message: 'Exit this TUI and attach to the moved session on the Manager now?' })
|
||||
if (warp) {
|
||||
await fetch(`${state.managerUrl}/api/opencode-proxy/session?directory=${encodeURIComponent(remoteDirectory)}`, { headers: { authorization: `Bearer ${token}` } }).catch(() => undefined)
|
||||
setPendingWarp({ managerUrl: state.managerUrl, token, directory: remoteDirectory, sessionID: result.sessionID, repoName: matched.name })
|
||||
api.keymap.dispatchCommand('app.exit')
|
||||
await warmRepoProxy(state.managerUrl, token, pushed.repoId)
|
||||
setPendingWarp({ managerUrl: state.managerUrl, token, repoId: pushed.repoId, sessionID: result.sessionID, repoName: matched.name })
|
||||
context.keymap.dispatch('app.exit')
|
||||
return
|
||||
}
|
||||
api.ui.toast({ variant: 'success', message: `Session moved to Manager (${result.replayedEvents} events). Local copy kept — run \`ocm\` to attach.` })
|
||||
context.ui.toast.show({ variant: 'success', message: `Session moved to Manager (${result.importedMessages} messages). Local copy kept — run \`ocm\` to attach.` })
|
||||
break
|
||||
}
|
||||
case 'not-found':
|
||||
api.ui.toast({ variant: 'error', message: 'No durable history found for this session' })
|
||||
break
|
||||
case 'corrupt-history':
|
||||
api.ui.toast({ variant: 'error', message: `Session history has a gap at sequence ${result.missingSeq}` })
|
||||
break
|
||||
case 'replay-failed':
|
||||
api.ui.toast({ variant: 'error', message: `Replay failed: ${result.message}` })
|
||||
case 'import-failed':
|
||||
context.ui.toast.show({ variant: 'error', message: `Session import failed: ${result.message}` })
|
||||
break
|
||||
}
|
||||
} catch (err) {
|
||||
api.ui.toast({ variant: 'error', message: err instanceof Error ? err.message : String(err) })
|
||||
context.ui.toast.show({ variant: 'error', message: err instanceof Error ? err.message : String(err) })
|
||||
} finally {
|
||||
setMoveProgress(null)
|
||||
}
|
||||
}
|
||||
|
||||
export { readRemoteContext } from './remote-context.js'
|
||||
@@ -1,34 +0,0 @@
|
||||
import type { RGBA } from '@opentui/core'
|
||||
|
||||
export type TuiThemeColors = {
|
||||
accent: RGBA
|
||||
text: RGBA
|
||||
textMuted: RGBA
|
||||
backgroundElement: RGBA
|
||||
}
|
||||
|
||||
export type TuiSlotContext = { theme: { readonly current: TuiThemeColors } }
|
||||
|
||||
export type TuiSlotRegistration = {
|
||||
order?: number
|
||||
slots: Record<string, (ctx: TuiSlotContext, props: Record<string, unknown>) => unknown>
|
||||
}
|
||||
|
||||
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'; duration?: number }
|
||||
export type TuiCommandDef = { name: string; title: string; desc?: string; category?: string; namespace?: string; slashName?: string; run: () => void | Promise<void> }
|
||||
export type TuiDialogConfirmProps = { title: string; message: string; onConfirm?: () => void; onCancel?: () => void }
|
||||
export type TuiDialogSelectOption<Value = unknown> = { title: string; value?: Value; description?: string; disabled?: boolean; onSelect?: () => void }
|
||||
export type TuiDialogSelectProps<Value = unknown> = { title: string; placeholder?: string; options: TuiDialogSelectOption<Value>[]; onSelect?: (option: TuiDialogSelectOption<Value>) => void }
|
||||
export type TuiDialogStack = { replace: (render: () => unknown, onClose?: () => void) => void; clear: () => void }
|
||||
export type TuiLifecycle = { readonly signal: AbortSignal; onDispose: (fn: () => void | Promise<void>) => () => void }
|
||||
export type TuiPluginApi = {
|
||||
route: { readonly current: TuiRouteCurrent }
|
||||
state: { session: { get: (sessionID: string) => TuiSessionInfo | undefined } }
|
||||
ui: { toast: (input: TuiToast) => void; DialogConfirm: (props: TuiDialogConfirmProps) => unknown; DialogSelect: <Value = unknown>(props: TuiDialogSelectProps<Value>) => unknown; dialog: TuiDialogStack }
|
||||
keymap: { registerLayer: (layer: { commands: TuiCommandDef[]; bindings?: Record<string, unknown> }) => unknown; dispatchCommand: (name: string) => unknown }
|
||||
slots: { register: (registration: TuiSlotRegistration) => string }
|
||||
lifecycle: TuiLifecycle
|
||||
}
|
||||
export type TuiPluginModule = { id?: string; tui: (api: TuiPluginApi, options?: Record<string, unknown>) => Promise<void> }
|
||||
+37
-48
@@ -1,60 +1,49 @@
|
||||
/** @jsxImportSource @opentui/solid */
|
||||
import { createSignal, createEffect, onCleanup, Show } from 'solid-js'
|
||||
import { setupOcm, readRemoteContext } from './tui-plugin.js'
|
||||
import { Plugin } from '@opencode/plugin/tui'
|
||||
import { setupOcm } from './tui-plugin.js'
|
||||
import { formatMoveProgress } from './move-progress.js'
|
||||
import type { MoveProgress } from './move-progress.js'
|
||||
import type { TuiPluginApi, TuiPluginModule, TuiSlotContext } from './tui-types.js'
|
||||
import { readRemoteContext } from './remote-context.js'
|
||||
|
||||
const SPINNER_INTERVAL_MS = 80
|
||||
|
||||
const tui = async (api: TuiPluginApi): Promise<void> => {
|
||||
const [moveProgress, setMoveProgress] = createSignal<MoveProgress | null>(null)
|
||||
await setupOcm(api, setMoveProgress)
|
||||
export default Plugin.define({
|
||||
id: 'ocm',
|
||||
async setup(context) {
|
||||
const [moveProgress, setMoveProgress] = createSignal<MoveProgress | null>(null)
|
||||
|
||||
const moveIndicator = (ctx: TuiSlotContext) => {
|
||||
const theme = ctx.theme.current
|
||||
const [frame, setFrame] = createSignal(0)
|
||||
createEffect(() => {
|
||||
if (!moveProgress()) return
|
||||
const timer = setInterval(() => setFrame((f) => f + 1), SPINNER_INTERVAL_MS)
|
||||
onCleanup(() => clearInterval(timer))
|
||||
})
|
||||
return (
|
||||
<box flexDirection="row" flexShrink={0}>
|
||||
<Show when={moveProgress()}>
|
||||
{(progress) => <text fg={theme.accent}>{formatMoveProgress(progress(), frame())}</text>}
|
||||
</Show>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
const moveIndicator = () => {
|
||||
const [frame, setFrame] = createSignal(0)
|
||||
createEffect(() => {
|
||||
if (!moveProgress()) return
|
||||
const timer = setInterval(() => setFrame((f) => f + 1), SPINNER_INTERVAL_MS)
|
||||
onCleanup(() => clearInterval(timer))
|
||||
})
|
||||
return (
|
||||
<box flexDirection="row" flexShrink={0}>
|
||||
<Show when={moveProgress()}>
|
||||
{(progress) => <text fg={context.theme.hue.accent[200]}>{formatMoveProgress(progress(), frame())}</text>}
|
||||
</Show>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
|
||||
api.slots.register({
|
||||
order: 290,
|
||||
slots: { session_prompt_right: moveIndicator },
|
||||
})
|
||||
context.ui.slot({ append: 'prompt.footer.status', render: moveIndicator })
|
||||
|
||||
const remote = readRemoteContext(process.env)
|
||||
if (!remote) return
|
||||
const remote = readRemoteContext(process.env)
|
||||
if (remote) {
|
||||
const indicator = () => (
|
||||
<box flexDirection="row" flexShrink={0} gap={1}>
|
||||
<text fg={context.theme.hue.accent[200]}>{remote.managerHost}</text>
|
||||
{remote.repoName && <text fg={context.theme.text.muted}> · {remote.repoName}</text>}
|
||||
</box>
|
||||
)
|
||||
|
||||
const indicator = (ctx: TuiSlotContext) => {
|
||||
const theme = ctx.theme.current
|
||||
return (
|
||||
<box flexDirection="row" flexShrink={0} gap={1}>
|
||||
<text fg={theme.accent}>{remote.managerHost}</text>
|
||||
{remote.repoName && (
|
||||
<text fg={theme.textMuted}> · {remote.repoName}</text>
|
||||
)}
|
||||
</box>
|
||||
)
|
||||
}
|
||||
context.ui.slot({ append: 'prompt.footer.status', render: indicator })
|
||||
context.ui.slot({ append: 'home.footer.status', render: indicator })
|
||||
}
|
||||
|
||||
api.slots.register({
|
||||
order: 300,
|
||||
slots: {
|
||||
session_prompt_right: indicator,
|
||||
home_prompt_right: indicator,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export default { id: 'ocm', tui } satisfies TuiPluginModule
|
||||
return setupOcm(context, setMoveProgress)
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,208 @@
|
||||
import { chmodSync, cpSync, existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync } from 'fs'
|
||||
import { randomBytes } from 'crypto'
|
||||
import { homedir } from 'os'
|
||||
import { dirname, join, resolve } from 'path'
|
||||
import { applyEdits, modify, parse as parseJsonc, type ParseError } from 'jsonc-parser/lib/esm/main.js'
|
||||
import { removeQuietly } from './json-store.js'
|
||||
|
||||
export const OCM_PLUGIN_NAME = 'ocm-cli'
|
||||
export const OCM_PLUGIN_SPEC = './plugin/ocm-cli/dist'
|
||||
|
||||
const CLI_CONFIG_SCHEMA = 'https://opencode.ai/v2/cli.json'
|
||||
const COPIED_ENTRIES = ['dist', 'package.json', 'README.md', 'LICENSE'] as const
|
||||
|
||||
export class InstallError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message)
|
||||
this.name = 'InstallError'
|
||||
}
|
||||
}
|
||||
|
||||
export interface VendorPaths {
|
||||
pluginDir: string
|
||||
pluginDistDir: string
|
||||
cliConfigFile: string
|
||||
binDir: string
|
||||
binLink: string
|
||||
}
|
||||
|
||||
export interface InstallOptions {
|
||||
sourceDistDir: string
|
||||
configDir: string
|
||||
home?: string
|
||||
force?: boolean
|
||||
link?: boolean
|
||||
}
|
||||
|
||||
export interface InstallResult {
|
||||
pluginDir: string
|
||||
copied: string[]
|
||||
configFile: string
|
||||
configChanged: boolean
|
||||
binLink: string | null
|
||||
binLinkChanged: boolean
|
||||
pathMissing: boolean
|
||||
}
|
||||
|
||||
export function resolveOpenCodeConfigDir(env: NodeJS.ProcessEnv = process.env, home = homedir()): string {
|
||||
const override = env.OPENCODE_CONFIG_DIR?.trim()
|
||||
if (override) return override
|
||||
const base = env.XDG_CONFIG_HOME?.trim() || join(home, '.config')
|
||||
return join(base, 'opencode')
|
||||
}
|
||||
|
||||
export function resolveVendorPaths(configDir: string, home = homedir()): VendorPaths {
|
||||
const pluginDir = join(configDir, 'plugin', OCM_PLUGIN_NAME)
|
||||
const binDir = join(home, '.local', 'bin')
|
||||
return {
|
||||
pluginDir,
|
||||
pluginDistDir: join(pluginDir, 'dist'),
|
||||
cliConfigFile: join(configDir, 'cli.json'),
|
||||
binDir,
|
||||
binLink: join(binDir, 'ocm'),
|
||||
}
|
||||
}
|
||||
|
||||
function realPath(filePath: string): string {
|
||||
try {
|
||||
return realpathSync(filePath)
|
||||
} catch {
|
||||
return resolve(filePath)
|
||||
}
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function pluginEntrySpec(entry: unknown): string | undefined {
|
||||
if (typeof entry === 'string') return entry
|
||||
if (Array.isArray(entry) && typeof entry[0] === 'string') return entry[0]
|
||||
return undefined
|
||||
}
|
||||
|
||||
export function addPluginToCliConfig(text: string | null, spec = OCM_PLUGIN_SPEC): { text: string; changed: boolean } {
|
||||
if (!text || text.trim() === '') {
|
||||
return { text: `${JSON.stringify({ $schema: CLI_CONFIG_SCHEMA, plugins: [spec] }, null, 2)}\n`, changed: true }
|
||||
}
|
||||
|
||||
const errors: ParseError[] = []
|
||||
const parsed = parseJsonc(text, errors, { allowTrailingComma: true, disallowComments: false })
|
||||
if (errors.length > 0 || !isRecord(parsed)) {
|
||||
throw new InstallError('cli.json is not valid JSONC; add the plugin entry manually')
|
||||
}
|
||||
|
||||
const plugins = parsed.plugins
|
||||
if (plugins !== undefined && !Array.isArray(plugins)) {
|
||||
throw new InstallError('cli.json "plugins" is not an array; add the plugin entry manually')
|
||||
}
|
||||
if (Array.isArray(plugins) && plugins.some((entry) => pluginEntrySpec(entry) === spec)) {
|
||||
return { text, changed: false }
|
||||
}
|
||||
|
||||
const index = Array.isArray(plugins) ? plugins.length : 0
|
||||
const edits = modify(text, ['plugins', index], spec, { formattingOptions: { tabSize: 2, insertSpaces: true } })
|
||||
return { text: applyEdits(text, edits), changed: true }
|
||||
}
|
||||
|
||||
function copyEntry(from: string, to: string): boolean {
|
||||
if (!existsSync(from)) return false
|
||||
if (realPath(from) === realPath(to)) return false
|
||||
rmSync(to, { recursive: true, force: true })
|
||||
cpSync(from, to, { recursive: true })
|
||||
return true
|
||||
}
|
||||
|
||||
function writeTextAtomic(filePath: string, text: string): void {
|
||||
const tmp = `${filePath}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`
|
||||
let mode: number | undefined
|
||||
try {
|
||||
mode = statSync(filePath).mode
|
||||
} catch {
|
||||
mode = undefined
|
||||
}
|
||||
try {
|
||||
writeFileSync(tmp, text, { encoding: 'utf-8', ...(mode === undefined ? {} : { mode }) })
|
||||
renameSync(tmp, filePath)
|
||||
} catch (err) {
|
||||
removeQuietly(tmp)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
function linkBinary(paths: VendorPaths, force: boolean): { changed: boolean; pathMissing: boolean } {
|
||||
const target = join(paths.pluginDistDir, 'ocm.js')
|
||||
if (!existsSync(target)) {
|
||||
throw new InstallError(`vendored ocm.js missing at ${target}; re-run the install`)
|
||||
}
|
||||
chmodSync(target, 0o755)
|
||||
mkdirSync(paths.binDir, { recursive: true })
|
||||
|
||||
let changed = false
|
||||
let existing: ReturnType<typeof lstatSync> | undefined
|
||||
try {
|
||||
existing = lstatSync(paths.binLink)
|
||||
} catch {
|
||||
existing = undefined
|
||||
}
|
||||
|
||||
if (existing?.isSymbolicLink()) {
|
||||
if (realPath(paths.binLink) !== realPath(target)) {
|
||||
unlinkSync(paths.binLink)
|
||||
symlinkSync(target, paths.binLink)
|
||||
changed = true
|
||||
}
|
||||
} else if (existing) {
|
||||
if (!force) {
|
||||
throw new InstallError(`${paths.binLink} exists and is not a symlink; re-run with --force to replace it`)
|
||||
}
|
||||
rmSync(paths.binLink, { force: true })
|
||||
symlinkSync(target, paths.binLink)
|
||||
changed = true
|
||||
} else {
|
||||
symlinkSync(target, paths.binLink)
|
||||
changed = true
|
||||
}
|
||||
|
||||
const path = process.env.PATH ?? ''
|
||||
return { changed, pathMissing: !path.split(':').includes(paths.binDir) }
|
||||
}
|
||||
|
||||
export function installVendoredOcm(options: InstallOptions): InstallResult {
|
||||
const home = options.home ?? homedir()
|
||||
const force = options.force === true
|
||||
const link = options.link !== false
|
||||
const paths = resolveVendorPaths(options.configDir, home)
|
||||
const sourceDistDir = resolve(options.sourceDistDir)
|
||||
|
||||
if (!existsSync(join(sourceDistDir, 'ocm.js')) || !existsSync(join(sourceDistDir, 'tui.js'))) {
|
||||
throw new InstallError(`package build not found at ${sourceDistDir}; build or unpack the package first`)
|
||||
}
|
||||
|
||||
const sourceRoot = dirname(sourceDistDir)
|
||||
const copied: string[] = []
|
||||
for (const entry of COPIED_ENTRIES) {
|
||||
const from = entry === 'dist' ? sourceDistDir : join(sourceRoot, entry)
|
||||
if (copyEntry(from, join(paths.pluginDir, entry))) copied.push(entry)
|
||||
}
|
||||
|
||||
const cliConfigFile = paths.cliConfigFile
|
||||
let current: string | null = null
|
||||
if (existsSync(cliConfigFile)) {
|
||||
current = readFileSync(cliConfigFile, 'utf-8')
|
||||
}
|
||||
const patched = addPluginToCliConfig(current)
|
||||
if (patched.changed) writeTextAtomic(cliConfigFile, patched.text)
|
||||
|
||||
const bin = link ? linkBinary(paths, force) : { changed: false, pathMissing: false }
|
||||
|
||||
return {
|
||||
pluginDir: paths.pluginDir,
|
||||
copied,
|
||||
configFile: cliConfigFile,
|
||||
configChanged: patched.changed,
|
||||
binLink: link ? paths.binLink : null,
|
||||
binLinkChanged: bin.changed,
|
||||
pathMissing: bin.pathMissing,
|
||||
}
|
||||
}
|
||||
+23
-17
@@ -1,12 +1,22 @@
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { buildRemoteAttachEnv } from './remote-context.js'
|
||||
import { repoProxyUrl } from './repo-proxy.js'
|
||||
|
||||
export type WarpTarget = {
|
||||
export type AttachTarget = {
|
||||
managerUrl: string
|
||||
token: string
|
||||
directory: string
|
||||
sessionID: string
|
||||
repoId: number
|
||||
repoName: string
|
||||
sessionID?: string
|
||||
}
|
||||
|
||||
export type WarpTarget = AttachTarget & {
|
||||
sessionID: string
|
||||
}
|
||||
|
||||
export type AttachInvocation = {
|
||||
args: string[]
|
||||
env: NodeJS.ProcessEnv
|
||||
}
|
||||
|
||||
export type WarpSpawn = (
|
||||
@@ -27,26 +37,22 @@ export function takePendingWarp(): WarpTarget | undefined {
|
||||
return t
|
||||
}
|
||||
|
||||
export function buildAttachArgs(target: WarpTarget): string[] {
|
||||
return [
|
||||
'attach',
|
||||
`${target.managerUrl}/api/opencode-proxy`,
|
||||
'--dir', target.directory,
|
||||
'--session', target.sessionID,
|
||||
'--password', target.token,
|
||||
'--username', 'opencode',
|
||||
]
|
||||
export function buildAttachInvocation(target: AttachTarget): AttachInvocation {
|
||||
const args = ['--server', repoProxyUrl(target.managerUrl, target.repoId)]
|
||||
if (target.sessionID) args.push('--session', target.sessionID)
|
||||
return {
|
||||
args,
|
||||
env: { ...process.env, OPENCODE_PASSWORD: target.token, ...buildRemoteAttachEnv(target.managerUrl, target.repoName) },
|
||||
}
|
||||
}
|
||||
|
||||
export function runPendingWarp(spawn: WarpSpawn = spawnSync): void {
|
||||
const target = takePendingWarp()
|
||||
if (!target) return
|
||||
try {
|
||||
spawn('opencode', buildAttachArgs(target), {
|
||||
stdio: 'inherit',
|
||||
env: { ...process.env, ...buildRemoteAttachEnv(target.managerUrl, target.repoName) },
|
||||
})
|
||||
const { args, env } = buildAttachInvocation(target)
|
||||
spawn('opencode', args, { stdio: 'inherit', env })
|
||||
} catch {
|
||||
void 0
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user