mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
chore(lint): replace ESLint with Oxlint and clear anti-slop findings
This commit is contained in:
1 parent
c6c13335e5
commit
b625acfc0c
1083 files changed
+67089
-80136
No files matched your search
+22
-13
@@ -1,12 +1,20 @@
|
||||
import { accessSync, chmodSync, constants, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'fs'
|
||||
import { randomBytes } from 'crypto'
|
||||
import { dirname } from 'path'
|
||||
import { z } from 'zod'
|
||||
|
||||
const DIR_MODE = 0o700
|
||||
const FILE_MODE = 0o600
|
||||
|
||||
function isPermissionError(err: unknown): boolean {
|
||||
const code = (err as NodeJS.ErrnoException).code
|
||||
const NodeErrorSchema = z.object({ code: z.string().optional() })
|
||||
|
||||
function nodeErrorCode(cause: unknown): string | undefined {
|
||||
const error = NodeErrorSchema.safeParse(cause)
|
||||
return error.success ? error.data.code : undefined
|
||||
}
|
||||
|
||||
function isPermissionError(cause: unknown): boolean {
|
||||
const code = nodeErrorCode(cause)
|
||||
return code === 'EACCES' || code === 'EPERM'
|
||||
}
|
||||
|
||||
@@ -21,12 +29,12 @@ export function removeQuietly(filePath: string): void {
|
||||
export function ensurePrivateDir(dir: string): void {
|
||||
try {
|
||||
mkdirSync(dir, { recursive: true, mode: DIR_MODE })
|
||||
} catch (err) {
|
||||
if (!isPermissionError(err)) throw err
|
||||
} catch (cause) {
|
||||
if (!isPermissionError(cause)) throw cause
|
||||
try {
|
||||
accessSync(dir, constants.X_OK)
|
||||
} catch {
|
||||
throw err
|
||||
throw cause
|
||||
}
|
||||
}
|
||||
try {
|
||||
@@ -36,31 +44,32 @@ export function ensurePrivateDir(dir: string): void {
|
||||
}
|
||||
}
|
||||
|
||||
export function readJsonFile<T>(filePath: string): T | null {
|
||||
export function readJsonFile<Schema extends z.ZodType>(filePath: string, schema: Schema): z.infer<Schema> | null {
|
||||
let contents: string
|
||||
try {
|
||||
contents = readFileSync(filePath, 'utf-8')
|
||||
} catch (err) {
|
||||
if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null
|
||||
throw err
|
||||
} catch (cause) {
|
||||
if (nodeErrorCode(cause) === 'ENOENT') return null
|
||||
throw cause
|
||||
}
|
||||
if (contents.trim() === '') return null
|
||||
try {
|
||||
return JSON.parse(contents) as T
|
||||
const parsed = schema.safeParse(JSON.parse(contents))
|
||||
return parsed.success ? parsed.data : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export function writeJsonFileAtomic(filePath: string, data: unknown): void {
|
||||
export function writeJsonFileAtomic<T>(filePath: string, data: T): void {
|
||||
ensurePrivateDir(dirname(filePath))
|
||||
const tmp = `${filePath}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`
|
||||
try {
|
||||
writeFileSync(tmp, JSON.stringify(data, null, 2), { encoding: 'utf-8', mode: FILE_MODE, flag: 'wx' })
|
||||
chmodSync(tmp, FILE_MODE)
|
||||
renameSync(tmp, filePath)
|
||||
} catch (err) {
|
||||
} catch (cause) {
|
||||
removeQuietly(tmp)
|
||||
throw err
|
||||
throw cause
|
||||
}
|
||||
}
|
||||
+42
-42
@@ -14,10 +14,16 @@ import {
|
||||
type OpenCodePairingCredentials,
|
||||
type OpenCodePairingEncryptedCredentials,
|
||||
} from '@opencode-manager/shared/opencode'
|
||||
import { trimUrlTrailingSlashes } from '@opencode-manager/shared/utils'
|
||||
import { z } from 'zod'
|
||||
import {
|
||||
JsonObjectSchema,
|
||||
parseJsonText,
|
||||
trimUrlTrailingSlashes,
|
||||
type JsonObject,
|
||||
type JsonValue,
|
||||
} from '@opencode-manager/shared/utils'
|
||||
|
||||
const DEFAULT_OPENCODE_PORT = 4096
|
||||
const DEFAULT_SERVICE_PORT = process.platform === 'win32' ? 45278 : 49374
|
||||
const DEFAULT_SERVICE_HOSTNAME = '127.0.0.1'
|
||||
const WILDCARD_HOSTS = new Set(['0.0.0.0', '::', '[::]'])
|
||||
const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '::1', '[::1]'])
|
||||
@@ -49,12 +55,10 @@ export type OpenCodeServerProbe =
|
||||
| { status: 'unauthorized' }
|
||||
| { status: 'unreachable'; message: string }
|
||||
|
||||
/** Generates a 32-byte random pairing code encoded as base64url. */
|
||||
export function generatePairingCode(): string {
|
||||
return randomBytes(32).toString('base64url')
|
||||
}
|
||||
|
||||
/** Returns the first non-internal IPv4 address, or null when the machine exposes none. */
|
||||
export function resolveLanIPv4(
|
||||
interfaces: NodeJS.Dict<NetworkInterfaceInfo[]> = networkInterfaces(),
|
||||
): string | null {
|
||||
@@ -68,7 +72,6 @@ export function resolveLanIPv4(
|
||||
return null
|
||||
}
|
||||
|
||||
/** Picks the OpenCode base URL from the first non-internal IPv4 interface, else loopback. */
|
||||
export function resolveDefaultBaseUrl(
|
||||
interfaces: NodeJS.Dict<NetworkInterfaceInfo[]> = networkInterfaces(),
|
||||
): string {
|
||||
@@ -87,12 +90,13 @@ export interface OpenCodeServiceDiscoveryOptions {
|
||||
env?: NodeJS.ProcessEnv
|
||||
home?: string
|
||||
interfaces?: NodeJS.Dict<NetworkInterfaceInfo[]>
|
||||
platform?: NodeJS.Platform
|
||||
}
|
||||
|
||||
function defaultServicePort(platform: NodeJS.Platform): number {
|
||||
return platform === 'win32' ? 45278 : 49374
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the OpenCode background service registration, then its config, and resolves the URL a
|
||||
* Manager should pair with. Never throws; returns null when neither file yields a usable service.
|
||||
*/
|
||||
export function discoverOpenCodeService(
|
||||
options: OpenCodeServiceDiscoveryOptions = {},
|
||||
): OpenCodeServiceDiscovery | null {
|
||||
@@ -118,7 +122,7 @@ export function discoverOpenCodeService(
|
||||
if (hostname === null && port === null && configPassword === null) return null
|
||||
|
||||
const configured = resolveServiceUrl(
|
||||
`http://${bracketHostname(hostname ?? DEFAULT_SERVICE_HOSTNAME)}:${port ?? DEFAULT_SERVICE_PORT}`,
|
||||
`http://${bracketHostname(hostname ?? DEFAULT_SERVICE_HOSTNAME)}:${port ?? defaultServicePort(options.platform ?? process.platform)}`,
|
||||
options.interfaces,
|
||||
)
|
||||
if (!configured) return null
|
||||
@@ -157,30 +161,29 @@ function resolveServiceUrl(
|
||||
return { baseUrl: trimUrlTrailingSlashes(parsed.href), loopbackOnly }
|
||||
}
|
||||
|
||||
function readServiceFile(file: string): Record<string, unknown> | null {
|
||||
function readServiceFile(file: string): JsonObject | null {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(readFileSync(file, 'utf8'))
|
||||
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return null
|
||||
return parsed as Record<string, unknown>
|
||||
const parsed = JsonObjectSchema.safeParse(parseJsonText(readFileSync(file, 'utf8')))
|
||||
return parsed.success ? parsed.data : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function readString(value: unknown): string | null {
|
||||
return typeof value === 'string' && value.length > 0 ? value : null
|
||||
function readString(value: JsonValue | undefined): string | null {
|
||||
const text = z.string().min(1).safeParse(value)
|
||||
return text.success ? text.data : null
|
||||
}
|
||||
|
||||
function readPort(value: unknown): number | null {
|
||||
return typeof value === 'number' && Number.isInteger(value) && value > 0 && value <= 65535 ? value : null
|
||||
function readPort(value: JsonValue | undefined): number | null {
|
||||
const port = z.number().int().min(1).max(65535).safeParse(value)
|
||||
return port.success ? port.data : null
|
||||
}
|
||||
|
||||
/** Renders the pairing link as a half-block QR code for terminals. */
|
||||
export function renderPairingQr(link: string): string {
|
||||
return renderUnicodeCompact(link, { ecc: 'M', border: 2 })
|
||||
}
|
||||
|
||||
/** Probes the OpenCode server info endpoint with Basic auth to report reachability and credentials validity. */
|
||||
export async function probeOpenCodeServer(
|
||||
baseUrl: string,
|
||||
credentials: PairingCredentials,
|
||||
@@ -214,15 +217,10 @@ export async function probeOpenCodeServer(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts a human-readable message from an unknown thrown value, falling back to `String(error)`
|
||||
* for non-`Error` values.
|
||||
*/
|
||||
function messageOf(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error)
|
||||
function messageOf(cause: unknown): string {
|
||||
return cause instanceof Error ? cause.message : String(cause)
|
||||
}
|
||||
|
||||
/** Serves the one-shot pairing redeem endpoint on `0.0.0.0` and reports how it ended. */
|
||||
export async function startPairingServer(options: PairingServerOptions): Promise<PairingServerHandle> {
|
||||
const { code, credentials, ttlMs, maxAttempts, port = 0, hostname = '0.0.0.0' } = options
|
||||
|
||||
@@ -293,7 +291,7 @@ export async function startPairingServer(options: PairingServerOptions): Promise
|
||||
return
|
||||
}
|
||||
|
||||
sendJson(response, 200, encrypted, () => {
|
||||
sendJson(response, 200, { ...encrypted }, () => {
|
||||
settle('linked')
|
||||
})
|
||||
}
|
||||
@@ -328,7 +326,8 @@ export async function startPairingServer(options: PairingServerOptions): Promise
|
||||
}
|
||||
|
||||
const address = server.address()
|
||||
const boundPort = typeof address === 'object' && address !== null ? address.port : port
|
||||
const parsedAddress = z.object({ port: z.number() }).safeParse(address)
|
||||
const boundPort = parsedAddress.success ? parsedAddress.data.port : port
|
||||
|
||||
return {
|
||||
url: `http://${hostname}:${boundPort}${REDEEM_PATH}`,
|
||||
@@ -346,19 +345,24 @@ interface PairingChallenge {
|
||||
proof: string
|
||||
}
|
||||
|
||||
function readPairingChallenge(body: unknown): PairingChallenge | null {
|
||||
if (typeof body !== 'object' || body === null) return null
|
||||
const { nonce, proof } = body as { nonce?: unknown; proof?: unknown }
|
||||
if (!isOpenCodePairingNonce(nonce) || typeof proof !== 'string' || proof.length === 0) return null
|
||||
return { nonce, proof }
|
||||
const PairingChallengeSchema = z.object({
|
||||
nonce: z.string(),
|
||||
proof: z.string().min(1),
|
||||
})
|
||||
|
||||
function readPairingChallenge(body: JsonValue | null): PairingChallenge | null {
|
||||
const challenge = PairingChallengeSchema.safeParse(body)
|
||||
if (!challenge.success) return null
|
||||
if (!isOpenCodePairingNonce(challenge.data.nonce)) return null
|
||||
return challenge.data
|
||||
}
|
||||
|
||||
function readJsonBody(request: IncomingMessage): Promise<unknown> {
|
||||
function readJsonBody(request: IncomingMessage): Promise<JsonValue | null> {
|
||||
return new Promise((resolve) => {
|
||||
const chunks: Buffer[] = []
|
||||
let size = 0
|
||||
let finished = false
|
||||
const finish = (value: unknown) => {
|
||||
const finish = (value: JsonValue | null) => {
|
||||
if (finished) return
|
||||
finished = true
|
||||
resolve(value)
|
||||
@@ -373,17 +377,13 @@ function readJsonBody(request: IncomingMessage): Promise<unknown> {
|
||||
chunks.push(chunk)
|
||||
})
|
||||
request.on('end', () => {
|
||||
try {
|
||||
finish(JSON.parse(Buffer.concat(chunks).toString('utf8')))
|
||||
} catch {
|
||||
finish(null)
|
||||
}
|
||||
finish(parseJsonText(Buffer.concat(chunks).toString('utf8')))
|
||||
})
|
||||
request.on('error', () => finish(null))
|
||||
})
|
||||
}
|
||||
|
||||
function sendJson(response: ServerResponse, status: number, body: unknown, onFlushed?: () => void): void {
|
||||
function sendJson(response: ServerResponse, status: number, body: JsonValue, onFlushed?: () => void): void {
|
||||
const payload = JSON.stringify(body)
|
||||
response.writeHead(status, {
|
||||
'content-type': 'application/json',
|
||||
|
||||
+166
-96
@@ -1,5 +1,6 @@
|
||||
import { createReadStream } from 'fs'
|
||||
import { Readable } from 'stream'
|
||||
import { z } from 'zod'
|
||||
import {
|
||||
MirrorCheckoutsResponseSchema,
|
||||
MirrorWorktreeCreateResponseSchema,
|
||||
@@ -10,69 +11,148 @@ import {
|
||||
type MirrorWorktreeCreateResponse,
|
||||
type MultiRun,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import { JsonValueSchema, parseJsonText, type JsonValue } from '@opencode-manager/shared/utils'
|
||||
|
||||
export interface MirrorBeginOpts {
|
||||
force?: boolean
|
||||
create?: { name: string; originUrl: string | null; branch: string | null }
|
||||
}
|
||||
|
||||
export interface MirrorBeginResult {
|
||||
uploadId: string
|
||||
repoId: number
|
||||
chunkSize: number
|
||||
created: boolean
|
||||
const MirrorBeginResultSchema = z.object({
|
||||
uploadId: z.string(),
|
||||
repoId: z.number(),
|
||||
chunkSize: z.number(),
|
||||
created: z.boolean(),
|
||||
})
|
||||
|
||||
export type MirrorBeginResult = z.infer<typeof MirrorBeginResultSchema>
|
||||
|
||||
const MirrorCommitResultSchema = z.object({
|
||||
repoId: z.number(),
|
||||
fullPath: z.string(),
|
||||
branch: z.string().nullable(),
|
||||
head: z.string().nullable(),
|
||||
created: z.boolean(),
|
||||
})
|
||||
|
||||
export type MirrorCommitResult = z.infer<typeof MirrorCommitResultSchema>
|
||||
|
||||
const MirrorPatchResultSchema = z.object({
|
||||
repoId: z.number(),
|
||||
fullPath: z.string(),
|
||||
branch: z.string().nullable(),
|
||||
head: z.string().nullable(),
|
||||
created: z.literal(false),
|
||||
applied: z.literal(true),
|
||||
})
|
||||
|
||||
export type MirrorPatchResult = z.infer<typeof MirrorPatchResultSchema>
|
||||
|
||||
const MirrorPatchSnapshotSchema = z.object({
|
||||
repoId: z.number(),
|
||||
branch: z.string().nullable(),
|
||||
head: z.string().nullable(),
|
||||
patch: z.string(),
|
||||
})
|
||||
|
||||
export type MirrorPatchSnapshot = z.infer<typeof MirrorPatchSnapshotSchema>
|
||||
|
||||
const MirrorHeadSchema = z.object({
|
||||
repoId: z.number(),
|
||||
branch: z.string().nullable(),
|
||||
head: z.string().nullable(),
|
||||
dirty: z.boolean(),
|
||||
})
|
||||
|
||||
export type MirrorHead = z.infer<typeof MirrorHeadSchema>
|
||||
|
||||
const MirrorBundleResultSchema = z.object({
|
||||
repoId: z.number(),
|
||||
fullPath: z.string(),
|
||||
branch: z.string().nullable(),
|
||||
head: z.string().nullable(),
|
||||
created: z.literal(false),
|
||||
})
|
||||
|
||||
export type MirrorBundleResult = z.infer<typeof MirrorBundleResultSchema>
|
||||
|
||||
const MirrorContainsResultSchema = z.object({
|
||||
repoId: z.number(),
|
||||
contained: z.boolean(),
|
||||
})
|
||||
|
||||
export type MirrorContainsResult = z.infer<typeof MirrorContainsResultSchema>
|
||||
|
||||
const MultiRunsResponseSchema = z.object({ runs: z.array(MultiRunSchema) })
|
||||
|
||||
const MultiRunResponseSchema = z.object({ run: MultiRunSchema })
|
||||
|
||||
const ManagerErrorBodySchema = z.object({
|
||||
error: z.string().optional(),
|
||||
message: z.string().optional(),
|
||||
code: z.string().optional(),
|
||||
details: JsonValueSchema.optional(),
|
||||
})
|
||||
|
||||
interface MirrorBeginPayload {
|
||||
force: boolean
|
||||
create?: true
|
||||
name?: string
|
||||
originUrl?: string
|
||||
branch?: string
|
||||
}
|
||||
|
||||
export interface MirrorCommitResult {
|
||||
repoId: number
|
||||
fullPath: string
|
||||
branch: string | null
|
||||
head: string | null
|
||||
created: boolean
|
||||
}
|
||||
|
||||
export interface MirrorPatchResult {
|
||||
repoId: number
|
||||
fullPath: string
|
||||
branch: string | null
|
||||
head: string | null
|
||||
created: false
|
||||
applied: true
|
||||
}
|
||||
|
||||
export interface MirrorPatchSnapshot {
|
||||
repoId: number
|
||||
branch: string | null
|
||||
head: string | null
|
||||
interface MirrorPatchPayload {
|
||||
baseHead: string | null
|
||||
patch: string
|
||||
force: boolean
|
||||
directory?: string
|
||||
}
|
||||
|
||||
export interface MirrorHead {
|
||||
repoId: number
|
||||
branch: string | null
|
||||
head: string | null
|
||||
dirty: boolean
|
||||
interface ManagerHeaders {
|
||||
[name: string]: string
|
||||
}
|
||||
|
||||
export interface MirrorBundleResult {
|
||||
repoId: number
|
||||
fullPath: string
|
||||
branch: string | null
|
||||
head: string | null
|
||||
created: false
|
||||
interface StreamingRequestInit extends RequestInit {
|
||||
duplex?: 'half'
|
||||
}
|
||||
|
||||
function createByteCounter(onProgress: (bytesSent: number) => void): TransformStream<Uint8Array, Uint8Array> {
|
||||
function toRequestBody(stream: Readable, onProgress?: (bytesSent: number) => void): ReadableStream<Uint8Array> {
|
||||
const iterator = stream[Symbol.asyncIterator]()
|
||||
let bytesSent = 0
|
||||
return new TransformStream<Uint8Array, Uint8Array>({
|
||||
transform(chunk, controller) {
|
||||
return new ReadableStream<Uint8Array>({
|
||||
async pull(controller) {
|
||||
const next = await iterator.next()
|
||||
if (next.done === true) {
|
||||
controller.close()
|
||||
return
|
||||
}
|
||||
const chunk: Uint8Array = next.value
|
||||
bytesSent += chunk.byteLength
|
||||
onProgress(bytesSent)
|
||||
onProgress?.(bytesSent)
|
||||
controller.enqueue(chunk)
|
||||
},
|
||||
async cancel() {
|
||||
await iterator.return?.(undefined)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
function headerRecord(headers: HeadersInit | undefined): ManagerHeaders {
|
||||
if (headers === undefined) return {}
|
||||
if (headers instanceof Headers) {
|
||||
const record: Record<string, string> = {}
|
||||
headers.forEach((value, key) => {
|
||||
record[key] = value
|
||||
})
|
||||
return record
|
||||
}
|
||||
const tupleEntries = z.array(z.tuple([z.string(), z.string()])).safeParse(headers)
|
||||
if (tupleEntries.success) return Object.fromEntries(tupleEntries.data)
|
||||
const record = z.record(z.string(), z.string()).safeParse(headers)
|
||||
return record.success ? record.data : {}
|
||||
}
|
||||
|
||||
export const MANAGER_FEATURE_MISSING = 'MANAGER_FEATURE_MISSING'
|
||||
|
||||
const DEFAULT_FEATURE_NAME = 'ocm multi-runs'
|
||||
@@ -88,7 +168,7 @@ export class ManagerApiError extends Error {
|
||||
public readonly status: number,
|
||||
public readonly code: string | null,
|
||||
public readonly operation: string,
|
||||
public readonly details: unknown = null,
|
||||
public readonly details: JsonValue | null = null,
|
||||
public readonly jsonBody: boolean = false,
|
||||
) {
|
||||
super(message)
|
||||
@@ -96,33 +176,25 @@ export class ManagerApiError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export function isManagerRouteMissing(error: unknown): boolean {
|
||||
if (!(error instanceof ManagerApiError)) return false
|
||||
if (error.code === MANAGER_FEATURE_MISSING) return true
|
||||
return error.status === 404 && !error.jsonBody
|
||||
export function isManagerRouteMissing(cause: unknown): boolean {
|
||||
if (!(cause instanceof ManagerApiError)) return false
|
||||
if (cause.code === MANAGER_FEATURE_MISSING) return true
|
||||
return cause.status === 404 && !cause.jsonBody
|
||||
}
|
||||
|
||||
async function formatErrorResponse(res: Response, operation: string): Promise<ManagerApiError> {
|
||||
const text = await res.text().catch(() => '')
|
||||
let code: string | null = null
|
||||
let detail = text
|
||||
let details: unknown = null
|
||||
let details: JsonValue | null = null
|
||||
let jsonBody = false
|
||||
if (text) {
|
||||
try {
|
||||
const parsed = JSON.parse(text) as unknown
|
||||
if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {
|
||||
jsonBody = true
|
||||
const body = parsed as { error?: unknown; message?: unknown; code?: unknown; details?: unknown }
|
||||
const codeField = typeof body.code === 'string' ? body.code : null
|
||||
const errField = typeof body.error === 'string' ? body.error : null
|
||||
const msgField = typeof body.message === 'string' ? body.message : null
|
||||
code = codeField
|
||||
detail = msgField ?? errField ?? text
|
||||
details = body.details ?? null
|
||||
}
|
||||
} catch {
|
||||
/* not JSON, keep raw text */
|
||||
const body = ManagerErrorBodySchema.safeParse(parseJsonText(text))
|
||||
if (body.success) {
|
||||
jsonBody = true
|
||||
code = body.data.code ?? null
|
||||
detail = body.data.message ?? body.data.error ?? text
|
||||
details = body.data.details ?? null
|
||||
}
|
||||
}
|
||||
const message = detail
|
||||
@@ -137,23 +209,22 @@ export class ManagerApi {
|
||||
private token: string,
|
||||
) {}
|
||||
|
||||
private headers(extra: Record<string, string> = {}): Record<string, string> {
|
||||
private headers(extra: Record<string, string> = {}): ManagerHeaders {
|
||||
return { Authorization: `Bearer ${this.token}`, ...extra }
|
||||
}
|
||||
|
||||
private async requestJson<T>(
|
||||
path: string,
|
||||
operation: string,
|
||||
parse: (body: unknown) => T,
|
||||
parse: (body: JsonValue) => T,
|
||||
init?: RequestInit & { feature?: boolean; featureName?: string },
|
||||
): Promise<T> {
|
||||
const { feature, featureName, ...requestInit } = init ?? {}
|
||||
const baseHeaders = this.headers(
|
||||
typeof requestInit.body === 'string' ? { 'Content-Type': 'application/json' } : {},
|
||||
)
|
||||
const jsonBody = z.string().safeParse(requestInit.body)
|
||||
const baseHeaders = this.headers(jsonBody.success ? { 'Content-Type': 'application/json' } : {})
|
||||
const res = await fetch(`${this.baseUrl}${path}`, {
|
||||
...requestInit,
|
||||
headers: { ...baseHeaders, ...(requestInit.headers as Record<string, string> | undefined) },
|
||||
headers: { ...baseHeaders, ...headerRecord(requestInit.headers) },
|
||||
})
|
||||
if (!res.ok) {
|
||||
const featureLabel = feature === true ? (featureName ?? DEFAULT_FEATURE_NAME) : null
|
||||
@@ -197,7 +268,7 @@ export class ManagerApi {
|
||||
|
||||
async mirrorBegin(repoId: number, opts: MirrorBeginOpts): Promise<MirrorBeginResult> {
|
||||
const url = `${this.baseUrl}/api/internal/repos/${repoId}/mirror/begin`
|
||||
const body: Record<string, unknown> = { force: opts.force === true }
|
||||
const body: MirrorBeginPayload = { force: opts.force === true }
|
||||
if (opts.create) {
|
||||
body.create = true
|
||||
body.name = opts.create.name
|
||||
@@ -210,16 +281,15 @@ export class ManagerApi {
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
if (!res.ok) throw await formatErrorResponse(res, 'mirror begin')
|
||||
return (await res.json()) as MirrorBeginResult
|
||||
return MirrorBeginResultSchema.parse(await res.json())
|
||||
}
|
||||
|
||||
async mirrorUploadPart(repoId: number, uploadId: string, index: number, chunk: Buffer): Promise<void> {
|
||||
const url = `${this.baseUrl}/api/internal/repos/${repoId}/mirror/parts/${uploadId}/${index}`
|
||||
const ab = chunk.buffer.slice(chunk.byteOffset, chunk.byteOffset + chunk.byteLength)
|
||||
const res = await fetch(url, {
|
||||
method: 'PUT',
|
||||
headers: { ...this.headers(), 'Content-Type': 'application/octet-stream' },
|
||||
body: ab as ArrayBuffer,
|
||||
body: new Uint8Array(chunk),
|
||||
})
|
||||
if (!res.ok) throw await formatErrorResponse(res, `mirror part ${index}`)
|
||||
}
|
||||
@@ -232,12 +302,12 @@ export class ManagerApi {
|
||||
body: JSON.stringify({ uploadId, totalParts, gzip }),
|
||||
})
|
||||
if (!res.ok) throw await formatErrorResponse(res, 'mirror commit')
|
||||
return (await res.json()) as MirrorCommitResult
|
||||
return MirrorCommitResultSchema.parse(await res.json())
|
||||
}
|
||||
|
||||
async mirrorAbort(repoId: number, uploadId: string): Promise<void> {
|
||||
const url = `${this.baseUrl}/api/internal/repos/${repoId}/mirror/uploads/${uploadId}`
|
||||
await fetch(url, { method: 'DELETE', headers: this.headers() }).catch(() => { /* best-effort */ })
|
||||
await fetch(url, { method: 'DELETE', headers: this.headers() }).catch(() => { })
|
||||
}
|
||||
|
||||
async mirrorDown(repoId: number, gzip: boolean): Promise<ReadableStream<Uint8Array>> {
|
||||
@@ -254,7 +324,7 @@ export class ManagerApi {
|
||||
repoId: number,
|
||||
body: { baseHead: string | null; patch: string; force?: boolean; directory?: string },
|
||||
): Promise<MirrorPatchResult> {
|
||||
const payload: Record<string, unknown> = { baseHead: body.baseHead, patch: body.patch, force: body.force === true }
|
||||
const payload: MirrorPatchPayload = { baseHead: body.baseHead, patch: body.patch, force: body.force === true }
|
||||
if (body.directory) payload.directory = body.directory
|
||||
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/patch`, {
|
||||
method: 'POST',
|
||||
@@ -263,7 +333,7 @@ export class ManagerApi {
|
||||
})
|
||||
|
||||
if (!res.ok) throw await formatErrorResponse(res, 'mirror patch')
|
||||
return (await res.json()) as MirrorPatchResult
|
||||
return MirrorPatchResultSchema.parse(await res.json())
|
||||
}
|
||||
|
||||
async mirrorUploadBundle(
|
||||
@@ -282,21 +352,21 @@ export class ManagerApi {
|
||||
if (opts.force === true) params.set('force', '1')
|
||||
if (opts.directory) params.set('directory', opts.directory)
|
||||
const query = params.size > 0 ? `?${params.toString()}` : ''
|
||||
const headers: Record<string, string> = { ...this.headers(), 'Content-Type': 'application/octet-stream' }
|
||||
const headers: ManagerHeaders = { ...this.headers(), 'Content-Type': 'application/octet-stream' }
|
||||
if (opts.branch) headers['X-OCM-Branch'] = opts.branch
|
||||
if (opts.requireCurrentBranch === true) headers['X-OCM-Require-Current-Branch'] = '1'
|
||||
if (opts.targetBranch) headers['X-OCM-Target-Branch'] = opts.targetBranch
|
||||
const fileStream = Readable.toWeb(createReadStream(bundlePath)) as unknown as ReadableStream<Uint8Array>
|
||||
const body = opts.onProgress ? fileStream.pipeThrough(createByteCounter(opts.onProgress)) : fileStream
|
||||
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/bundle${query}`, {
|
||||
const body = toRequestBody(createReadStream(bundlePath), opts.onProgress)
|
||||
const requestInit: StreamingRequestInit = {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: body as BodyInit,
|
||||
body,
|
||||
duplex: 'half',
|
||||
} as RequestInit & { duplex: 'half' })
|
||||
}
|
||||
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/bundle${query}`, requestInit)
|
||||
|
||||
if (!res.ok) throw await formatErrorResponse(res, 'mirror bundle upload')
|
||||
return (await res.json()) as MirrorBundleResult
|
||||
return MirrorBundleResultSchema.parse(await res.json())
|
||||
}
|
||||
|
||||
async mirrorHead(repoId: number, directory?: string): Promise<MirrorHead> {
|
||||
@@ -305,7 +375,7 @@ export class ManagerApi {
|
||||
})
|
||||
|
||||
if (!res.ok) throw await formatErrorResponse(res, 'mirror head')
|
||||
return (await res.json()) as MirrorHead
|
||||
return MirrorHeadSchema.parse(await res.json())
|
||||
}
|
||||
|
||||
async mirrorCheckouts(repoId: number, branch: string): Promise<MirrorCheckoutsResponse> {
|
||||
@@ -324,7 +394,7 @@ export class ManagerApi {
|
||||
opts: { branch: string; targetBranch: string; patch: string; onProgress?: (bytesSent: number) => void },
|
||||
): Promise<MirrorWorktreeCreateResponse> {
|
||||
const patchBuf = Buffer.from(opts.patch, 'utf-8')
|
||||
const headers: Record<string, string> = {
|
||||
const headers: ManagerHeaders = {
|
||||
...this.headers(),
|
||||
'Content-Type': 'application/octet-stream',
|
||||
'X-OCM-Branch': opts.branch,
|
||||
@@ -337,26 +407,26 @@ export class ManagerApi {
|
||||
yield* createReadStream(bundlePath)
|
||||
})(),
|
||||
)
|
||||
const fileStream = Readable.toWeb(source) as unknown as ReadableStream<Uint8Array>
|
||||
const body = opts.onProgress ? fileStream.pipeThrough(createByteCounter(opts.onProgress)) : fileStream
|
||||
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/worktree`, {
|
||||
const body = toRequestBody(source, opts.onProgress)
|
||||
const requestInit: StreamingRequestInit = {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: body as BodyInit,
|
||||
body,
|
||||
duplex: 'half',
|
||||
} as RequestInit & { duplex: 'half' })
|
||||
}
|
||||
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/worktree`, requestInit)
|
||||
|
||||
if (!res.ok) throw await this.handleErrorResponse(res, 'mirror create worktree', MOVE_FEATURE_NAME)
|
||||
return MirrorWorktreeCreateResponseSchema.parse(await res.json())
|
||||
}
|
||||
|
||||
async mirrorContains(repoId: number, sha: string, directory?: string): Promise<{ contained: boolean }> {
|
||||
async mirrorContains(repoId: number, sha: string, directory?: string): Promise<MirrorContainsResult> {
|
||||
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror/contains/${sha}${directoryQuery(directory)}`, {
|
||||
headers: this.headers(),
|
||||
})
|
||||
|
||||
if (!res.ok) throw await formatErrorResponse(res, 'mirror contains')
|
||||
return (await res.json()) as { repoId: number; contained: boolean }
|
||||
return MirrorContainsResultSchema.parse(await res.json())
|
||||
}
|
||||
|
||||
async mirrorDownloadBundle(repoId: number, directory?: string): Promise<ReadableStream<Uint8Array>> {
|
||||
@@ -374,14 +444,14 @@ export class ManagerApi {
|
||||
})
|
||||
|
||||
if (!res.ok) throw await formatErrorResponse(res, 'mirror patch snapshot')
|
||||
return (await res.json()) as MirrorPatchSnapshot
|
||||
return MirrorPatchSnapshotSchema.parse(await res.json())
|
||||
}
|
||||
|
||||
listMultiRuns(repoId: number): Promise<MultiRun[]> {
|
||||
return this.requestJson(
|
||||
`/api/internal/multi-runs?repoId=${encodeURIComponent(repoId)}`,
|
||||
'list multi-runs',
|
||||
(body) => MultiRunSchema.array().parse((body as { runs: unknown }).runs),
|
||||
(body) => MultiRunsResponseSchema.parse(body).runs,
|
||||
{ feature: true },
|
||||
)
|
||||
}
|
||||
@@ -390,7 +460,7 @@ export class ManagerApi {
|
||||
return this.requestJson(
|
||||
'/api/internal/multi-runs',
|
||||
'launch multi-run',
|
||||
(body) => MultiRunSchema.parse((body as { run: unknown }).run),
|
||||
(body) => MultiRunResponseSchema.parse(body).run,
|
||||
{ method: 'POST', body: JSON.stringify(request), feature: true },
|
||||
)
|
||||
}
|
||||
@@ -399,7 +469,7 @@ export class ManagerApi {
|
||||
return this.requestJson(
|
||||
`/api/internal/multi-runs/${encodeURIComponent(runId)}/fusions`,
|
||||
'fuse multi-run',
|
||||
(body) => MultiRunSchema.parse((body as { run: unknown }).run),
|
||||
(body) => MultiRunResponseSchema.parse(body).run,
|
||||
{ method: 'POST', body: JSON.stringify(request), feature: true },
|
||||
)
|
||||
}
|
||||
@@ -408,7 +478,7 @@ export class ManagerApi {
|
||||
return this.requestJson(
|
||||
`/api/internal/multi-runs/${encodeURIComponent(runId)}/entries/${encodeURIComponent(entryId)}/discard`,
|
||||
'discard multi-run entry',
|
||||
(body) => MultiRunSchema.parse((body as { run: unknown }).run),
|
||||
(body) => MultiRunResponseSchema.parse(body).run,
|
||||
{ method: 'POST', feature: true },
|
||||
)
|
||||
}
|
||||
|
||||
+24
-11
@@ -1,6 +1,7 @@
|
||||
import { readState } from './state.js'
|
||||
import { readState, type OcmState } from './state.js'
|
||||
import { getToken, describeTokenStore } from './internal-token-store.js'
|
||||
import { TokenStoreError } from './token-store.js'
|
||||
import type { TokenStoreDescription } from './token-store.js'
|
||||
import { ManagerApi } from './manager-api.js'
|
||||
import { trimUrlTrailingSlashes } from '@opencode-manager/shared/utils'
|
||||
|
||||
@@ -16,11 +17,20 @@ export type ResolveManagerApiResult =
|
||||
| { ok: true; auth: ManagerAuthOk; api: ManagerApi }
|
||||
| { ok: false; message: string }
|
||||
|
||||
/** Resolves the Manager URL and token used to authenticate CLI requests. */
|
||||
export interface ManagerAuthDeps {
|
||||
readState: () => OcmState | null
|
||||
getToken: (account: string) => Promise<string | null>
|
||||
describeTokenStore: () => TokenStoreDescription
|
||||
}
|
||||
|
||||
export const managerAuthDeps: ManagerAuthDeps = { readState, getToken, describeTokenStore }
|
||||
|
||||
export async function resolveManagerAuth(
|
||||
rawManagerUrl: string | undefined = readState()?.managerUrl,
|
||||
rawManagerUrl?: string,
|
||||
deps: ManagerAuthDeps = managerAuthDeps,
|
||||
): Promise<ManagerAuth> {
|
||||
const managerUrl = rawManagerUrl ? trimUrlTrailingSlashes(rawManagerUrl) : ''
|
||||
const requestedUrl = rawManagerUrl ?? deps.readState()?.managerUrl
|
||||
const managerUrl = requestedUrl ? trimUrlTrailingSlashes(requestedUrl) : ''
|
||||
if (!managerUrl) {
|
||||
return {
|
||||
ok: false,
|
||||
@@ -31,13 +41,13 @@ export async function resolveManagerAuth(
|
||||
|
||||
let token: string | null
|
||||
try {
|
||||
token = await getToken(managerUrl)
|
||||
token = await deps.getToken(managerUrl)
|
||||
} catch (err) {
|
||||
if (!(err instanceof TokenStoreError)) throw err
|
||||
return {
|
||||
ok: false,
|
||||
reason: 'token-store',
|
||||
message: `token store error (${tokenStoreLabel()}): ${err.message}. Run \`ocm login ${managerUrl}\` after fixing the store.`,
|
||||
message: `token store error (${tokenStoreLabel(deps)}): ${err.message}. Run \`ocm login ${managerUrl}\` after fixing the store.`,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,20 +55,23 @@ export async function resolveManagerAuth(
|
||||
return {
|
||||
ok: false,
|
||||
reason: 'no-token',
|
||||
message: `no token stored for ${managerUrl} (${tokenStoreLabel()}). Run \`ocm login ${managerUrl}\`.`,
|
||||
message: `no token stored for ${managerUrl} (${tokenStoreLabel(deps)}). Run \`ocm login ${managerUrl}\`.`,
|
||||
}
|
||||
}
|
||||
|
||||
return { ok: true, managerUrl, token }
|
||||
}
|
||||
|
||||
function tokenStoreLabel(): string {
|
||||
const store = describeTokenStore()
|
||||
function tokenStoreLabel(deps: ManagerAuthDeps): string {
|
||||
const store = deps.describeTokenStore()
|
||||
return `${store.kind}: ${store.location}`
|
||||
}
|
||||
|
||||
export async function resolveManagerApi(managerUrl?: string): Promise<ResolveManagerApiResult> {
|
||||
const auth = await resolveManagerAuth(managerUrl)
|
||||
export async function resolveManagerApi(
|
||||
managerUrl?: string,
|
||||
deps: ManagerAuthDeps = managerAuthDeps,
|
||||
): Promise<ResolveManagerApiResult> {
|
||||
const auth = await resolveManagerAuth(managerUrl, deps)
|
||||
if (!auth.ok) return { ok: false, message: auth.message }
|
||||
return { ok: true, auth, api: new ManagerApi(auth.managerUrl, auth.token) }
|
||||
}
|
||||
@@ -1,15 +1,24 @@
|
||||
import { z } from 'zod'
|
||||
import type { RemoteRepoSummary } from './mirror.js'
|
||||
|
||||
export interface ManagerRepo {
|
||||
repoId: number
|
||||
name: string
|
||||
branch: string | null
|
||||
cloneStatus: string
|
||||
directory: string
|
||||
projectId?: string | null
|
||||
isWorktree?: boolean
|
||||
extra: { repoId: number; localPath: string; fullPath: string }
|
||||
}
|
||||
const ManagerRepoSchema = z.object({
|
||||
repoId: z.number(),
|
||||
name: z.string(),
|
||||
branch: z.string().nullable(),
|
||||
cloneStatus: z.string(),
|
||||
directory: z.string(),
|
||||
projectId: z.string().nullable().optional(),
|
||||
isWorktree: z.boolean().optional(),
|
||||
extra: z.object({
|
||||
repoId: z.number(),
|
||||
localPath: z.string(),
|
||||
fullPath: z.string(),
|
||||
}),
|
||||
})
|
||||
|
||||
export type ManagerRepo = z.infer<typeof ManagerRepoSchema>
|
||||
|
||||
const ManagerReposResponseSchema = z.object({ workspaces: z.array(ManagerRepoSchema) })
|
||||
|
||||
export async function fetchRepos(managerUrl: string, token: string): Promise<ManagerRepo[]> {
|
||||
const res = await fetch(`${managerUrl}/api/internal/opencode-workspaces`, {
|
||||
@@ -18,8 +27,7 @@ export async function fetchRepos(managerUrl: string, token: string): Promise<Man
|
||||
if (!res.ok) {
|
||||
throw new Error(`manager responded ${res.status} ${res.statusText}`)
|
||||
}
|
||||
const data = (await res.json()) as { workspaces: ManagerRepo[] }
|
||||
return data.workspaces
|
||||
return ManagerReposResponseSchema.parse(await res.json()).workspaces
|
||||
}
|
||||
|
||||
export function toRemoteRepoSummaries(repos: ManagerRepo[]): RemoteRepoSummary[] {
|
||||
|
||||
+51
-20
@@ -17,6 +17,23 @@ const PART_RETRIES = 3
|
||||
const PART_BACKOFF_MS = [500, 2000, 8000]
|
||||
const MIRROR_GZIP = true
|
||||
|
||||
async function* webStreamChunks(stream: ReadableStream<Uint8Array>): AsyncGenerator<Buffer> {
|
||||
const reader = stream.getReader()
|
||||
try {
|
||||
while (true) {
|
||||
const next = await reader.read()
|
||||
if (next.done === true) return
|
||||
yield Buffer.from(next.value)
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock()
|
||||
}
|
||||
}
|
||||
|
||||
function readableFromWebStream(stream: ReadableStream<Uint8Array>): Readable {
|
||||
return Readable.from(webStreamChunks(stream))
|
||||
}
|
||||
|
||||
function getGitignoreExclusions(repoRoot: string): string[] {
|
||||
const res = spawnSync('git', ['ls-files', '--others', '--ignored', '--exclude-standard', '--directory'], {
|
||||
cwd: repoRoot,
|
||||
@@ -46,6 +63,16 @@ export class MirrorAbort extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export type MirrorHeadApi = Pick<ManagerApi, 'mirrorHead'>
|
||||
export type MirrorPullApi = Pick<ManagerApi, 'mirrorContains' | 'mirrorHead'>
|
||||
export type MirrorCheckoutsApi = Pick<ManagerApi, 'mirrorCheckouts'>
|
||||
export type MirrorUploadApi = Pick<ManagerApi, 'mirrorBegin' | 'mirrorUploadPart' | 'mirrorCommit' | 'mirrorAbort'>
|
||||
export type MirrorDownloadApi = Pick<ManagerApi, 'mirrorDown'>
|
||||
export type MirrorDownFastApi = Pick<ManagerApi, 'mirrorPatchSnapshot' | 'mirrorDownloadBundle'>
|
||||
export type MirrorPatchApi = Pick<ManagerApi, 'mirrorPatch'>
|
||||
export type MirrorUpFastApi = Pick<ManagerApi, 'mirrorCreateWorktree' | 'mirrorUploadBundle' | 'mirrorPatch'>
|
||||
export type MirrorMoveApi = MirrorCheckoutsApi & MirrorUpFastApi
|
||||
|
||||
export interface RemoteRepoSummary {
|
||||
repoId: number
|
||||
name: string
|
||||
@@ -87,7 +114,7 @@ export interface PushDivergence {
|
||||
|
||||
export async function checkPushDivergence(
|
||||
repoRoot: string,
|
||||
api: ManagerApi,
|
||||
api: MirrorHeadApi,
|
||||
repoId: number,
|
||||
directory?: string,
|
||||
): Promise<PushDivergence> {
|
||||
@@ -198,7 +225,7 @@ export interface PullDivergence {
|
||||
|
||||
export async function checkPullDivergence(
|
||||
repoRoot: string,
|
||||
api: ManagerApi,
|
||||
api: MirrorPullApi,
|
||||
repoId: number,
|
||||
directory?: string,
|
||||
): Promise<PullDivergence> {
|
||||
@@ -214,7 +241,6 @@ export async function checkPullDivergence(
|
||||
serverHead = (await api.mirrorHead(repoId, directory)).head
|
||||
if (serverHead) lostCommits = countCommitsAhead(repoRoot, serverHead, localHead)
|
||||
} catch {
|
||||
// best-effort: count is informational only
|
||||
}
|
||||
return { diverged: true, lostCommits, serverHead }
|
||||
}
|
||||
@@ -225,7 +251,7 @@ export interface BranchCheckoutSelection {
|
||||
}
|
||||
|
||||
export async function resolveBranchCheckout(
|
||||
api: ManagerApi,
|
||||
api: MirrorCheckoutsApi,
|
||||
repoId: number,
|
||||
repoRoot: string,
|
||||
): Promise<BranchCheckoutSelection> {
|
||||
@@ -254,21 +280,21 @@ export interface MirrorProgress {
|
||||
}
|
||||
|
||||
export interface MirrorUpOpts {
|
||||
api: ManagerApi
|
||||
api: MirrorUploadApi
|
||||
force: boolean
|
||||
create?: { name: string; originUrl: string | null; branch: string | null }
|
||||
onProgress?: (p: MirrorProgress) => void
|
||||
}
|
||||
|
||||
function isRetryablePartError(err: unknown): boolean {
|
||||
if (err instanceof ManagerApiError) {
|
||||
return err.status >= 500 || err.status === 408 || err.status === 429
|
||||
function isRetryablePartError(cause: unknown): boolean {
|
||||
if (cause instanceof ManagerApiError) {
|
||||
return cause.status >= 500 || cause.status === 408 || cause.status === 429
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
async function uploadPartWithRetry(
|
||||
api: ManagerApi,
|
||||
api: MirrorUploadApi,
|
||||
repoId: number,
|
||||
uploadId: string,
|
||||
index: number,
|
||||
@@ -296,7 +322,7 @@ interface PartFlusher {
|
||||
}
|
||||
|
||||
function createPartFlusher(
|
||||
api: ManagerApi,
|
||||
api: MirrorUploadApi,
|
||||
repoId: number,
|
||||
uploadId: string,
|
||||
chunkSize: number,
|
||||
@@ -382,9 +408,12 @@ export async function mirrorUp(
|
||||
const flusher = createPartFlusher(opts.api, begin.repoId, begin.uploadId, begin.chunkSize)
|
||||
|
||||
try {
|
||||
for await (const chunk of child.stdout as AsyncIterable<Buffer>) {
|
||||
await flusher.push(chunk)
|
||||
bytesSent += chunk.length
|
||||
const tarStdout = child.stdout
|
||||
if (!tarStdout) throw new Error('tar stdout is unavailable')
|
||||
for await (const chunk of tarStdout) {
|
||||
const data: Buffer = chunk
|
||||
await flusher.push(data)
|
||||
bytesSent += data.length
|
||||
opts.onProgress?.({ bytesSent })
|
||||
}
|
||||
await tarExit
|
||||
@@ -406,7 +435,7 @@ export async function mirrorUp(
|
||||
export async function mirrorDown(
|
||||
repoId: number,
|
||||
repoRoot: string,
|
||||
api: ManagerApi,
|
||||
api: MirrorDownloadApi,
|
||||
opts: { force: boolean; onProgress?: (bytesReceived: number) => void } = { force: false },
|
||||
): Promise<void> {
|
||||
if (!opts.force && getDirtyPaths(repoRoot).size > 0) {
|
||||
@@ -437,7 +466,7 @@ export async function mirrorDown(
|
||||
child.on('error', reject)
|
||||
})
|
||||
|
||||
const stdinWritable = Readable.fromWeb(tarball as unknown as Parameters<typeof Readable.fromWeb>[0])
|
||||
const stdinWritable = readableFromWebStream(tarball)
|
||||
let received = 0
|
||||
stdinWritable.on('data', (chunk: Buffer) => {
|
||||
received += chunk.length
|
||||
@@ -483,7 +512,7 @@ export async function mirrorDown(
|
||||
|
||||
export async function mirrorUpPatch(
|
||||
plan: MirrorPlan,
|
||||
opts: Pick<MirrorUpOpts, 'api' | 'force'> & { directory?: string },
|
||||
opts: { api: MirrorPatchApi; force: boolean; directory?: string },
|
||||
): Promise<{ repoId: number; fullPath: string; branch: string | null; head: string | null; created: false; applied: true }> {
|
||||
const repoId = plan.matched[0]!.repoId
|
||||
const patch = getMirrorPatch(plan.repoRoot)
|
||||
@@ -637,11 +666,11 @@ function importLocalBundle(
|
||||
}
|
||||
}
|
||||
|
||||
async function writeBundleStream(repoId: number, api: ManagerApi, directory?: string): Promise<string> {
|
||||
async function writeBundleStream(repoId: number, api: MirrorDownFastApi, directory?: string): Promise<string> {
|
||||
const bundlePath = join(tmpdir(), `ocm-bundle-down-${Date.now()}-${Math.random().toString(36).slice(2)}.bundle`)
|
||||
const stream = await api.mirrorDownloadBundle(repoId, directory)
|
||||
await pipeline(
|
||||
Readable.fromWeb(stream as unknown as Parameters<typeof Readable.fromWeb>[0]),
|
||||
readableFromWebStream(stream),
|
||||
createWriteStream(bundlePath),
|
||||
)
|
||||
return bundlePath
|
||||
@@ -653,7 +682,9 @@ export type MirrorUpFastPhase =
|
||||
| { kind: 'processing' }
|
||||
| { kind: 'patching' }
|
||||
|
||||
type MirrorUpFastOpts = Pick<MirrorUpOpts, 'api' | 'force'> & {
|
||||
export type MirrorUpFastOpts = {
|
||||
api: MirrorUpFastApi
|
||||
force: boolean
|
||||
requireCurrentBranch?: boolean
|
||||
directory?: string
|
||||
targetBranch?: string
|
||||
@@ -732,7 +763,7 @@ export async function mirrorUpFast(
|
||||
export async function mirrorDownFast(
|
||||
repoId: number,
|
||||
repoRoot: string,
|
||||
api: ManagerApi,
|
||||
api: MirrorDownFastApi,
|
||||
opts: { force: boolean; directory?: string; sourceBranch?: string; targetBranch?: string } = { force: false },
|
||||
): Promise<void> {
|
||||
if (!opts.force && getDirtyPaths(repoRoot).size > 0) {
|
||||
|
||||
@@ -12,12 +12,12 @@ export type RemoteContext = {
|
||||
repoId?: number
|
||||
}
|
||||
|
||||
export function buildRemoteAttachEnv(managerUrl: string, repoName: string, repoId: number): Record<string, string> {
|
||||
export function buildRemoteAttachEnv(managerUrl: string, repoName: string, repoId: number) {
|
||||
return {
|
||||
[REMOTE_MANAGER_URL_ENV]: managerUrl,
|
||||
[REMOTE_REPO_NAME_ENV]: repoName,
|
||||
[REMOTE_REPO_ID_ENV]: String(repoId),
|
||||
}
|
||||
} satisfies Record<string, string>
|
||||
}
|
||||
|
||||
export function readRemoteContext(env: NodeJS.ProcessEnv): RemoteContext | undefined {
|
||||
@@ -41,7 +41,6 @@ export function readRemoteContext(env: NodeJS.ProcessEnv): RemoteContext | undef
|
||||
return { managerUrl, managerHost, repoName, repoId }
|
||||
}
|
||||
|
||||
/** Returns the saved manager name when it belongs to the attached manager, else the manager host. */
|
||||
export function remoteDisplayName(remote: RemoteContext, state: OcmState | null): string {
|
||||
if (state?.managerName && trimUrlTrailingSlashes(state.managerUrl) === trimUrlTrailingSlashes(remote.managerUrl)) return state.managerName
|
||||
return remote.managerHost
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { z } from 'zod'
|
||||
import { parseJsonText } from '@opencode-manager/shared/utils'
|
||||
import packageJson from '../package.json' with { type: 'json' }
|
||||
import { delay } from './delay.js'
|
||||
import { describeCause } from './token-store.js'
|
||||
@@ -41,9 +43,11 @@ export class RepoProxyUnreachableError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export type RepoProxyFetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>
|
||||
|
||||
export type WarmRepoProxyOptions = {
|
||||
attempts?: number
|
||||
fetch?: typeof fetch
|
||||
fetch?: RepoProxyFetch
|
||||
wait?: (ms: number) => Promise<void>
|
||||
}
|
||||
|
||||
@@ -55,13 +59,11 @@ export function repoProxyUrl(managerUrl: string, repoId: number): string {
|
||||
return `${repoProxyBaseUrl(managerUrl)}/repos/${repoId}`
|
||||
}
|
||||
|
||||
const RepoProxyErrorBodySchema = z.object({ error: z.string().optional() })
|
||||
|
||||
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
|
||||
}
|
||||
const parsed = RepoProxyErrorBodySchema.safeParse(parseJsonText(body))
|
||||
return parsed.success && parsed.data.error === 'Repo not found'
|
||||
}
|
||||
|
||||
export async function warmRepoProxy(managerUrl: string, token: string, repoId: number, options: WarmRepoProxyOptions = {}): Promise<void> {
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url'
|
||||
import { z } from 'zod'
|
||||
import { isJsonContainer, type JsonContainer, type JsonValue } from '@opencode-manager/shared/utils'
|
||||
import type { SessionTransferData } from '@opencode-manager/shared/opencode'
|
||||
|
||||
export type RewriteContext = { localRoot: string; remoteRoot: string }
|
||||
@@ -10,15 +12,18 @@ export function rewriteTransferForRemote(data: SessionTransferData, ctx: Rewrite
|
||||
return cloned
|
||||
}
|
||||
|
||||
function relocateUris(value: unknown, ctx: RewriteContext): void {
|
||||
function relocateUris(value: JsonValue, ctx: RewriteContext): void {
|
||||
if (Array.isArray(value)) {
|
||||
for (const item of value) relocateUris(item, ctx)
|
||||
return
|
||||
}
|
||||
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)
|
||||
if (!isJsonContainer(value)) return
|
||||
const container: JsonContainer = value
|
||||
const uri = z.string().safeParse(container['uri'])
|
||||
if (uri.success) container['uri'] = relocateUri(uri.data, ctx)
|
||||
for (const child of Object.values(container)) {
|
||||
if (child !== undefined) relocateUris(child, ctx)
|
||||
}
|
||||
}
|
||||
|
||||
function relocateUri(uri: string, ctx: RewriteContext): string {
|
||||
|
||||
+21
-16
@@ -1,23 +1,28 @@
|
||||
import { existsSync, unlinkSync } from 'fs'
|
||||
import { homedir } from 'os'
|
||||
import { join } from 'path'
|
||||
import { z } from 'zod'
|
||||
import { readJsonFile, writeJsonFileAtomic } from './json-store.js'
|
||||
|
||||
export interface OcmState {
|
||||
managerUrl: string
|
||||
managerName?: string
|
||||
lastRepoId?: number
|
||||
lastRepoName?: string
|
||||
lastRepoDir?: string
|
||||
lastRepoBranch?: string | null
|
||||
updatedAt?: number
|
||||
}
|
||||
const OcmStateSchema = z.object({
|
||||
managerUrl: z.string(),
|
||||
managerName: z.string().optional(),
|
||||
lastRepoId: z.number().optional(),
|
||||
lastRepoName: z.string().optional(),
|
||||
lastRepoDir: z.string().optional(),
|
||||
lastRepoBranch: z.string().nullish(),
|
||||
updatedAt: z.number().optional(),
|
||||
})
|
||||
|
||||
export interface InstallNotice {
|
||||
link: string
|
||||
binDir: string
|
||||
pathMissing: boolean
|
||||
}
|
||||
const InstallNoticeSchema = z.object({
|
||||
link: z.string(),
|
||||
binDir: z.string(),
|
||||
pathMissing: z.boolean(),
|
||||
})
|
||||
|
||||
export type OcmState = z.infer<typeof OcmStateSchema>
|
||||
|
||||
export type InstallNotice = z.infer<typeof InstallNoticeSchema>
|
||||
|
||||
const STATE_DIR = join(homedir(), '.config', 'opencode-manager')
|
||||
const STATE_FILE = join(STATE_DIR, 'state.json')
|
||||
@@ -32,7 +37,7 @@ export function getStatePath(): string {
|
||||
}
|
||||
|
||||
export function readState(): OcmState | null {
|
||||
const parsed = readJsonFile<OcmState>(STATE_FILE)
|
||||
const parsed = readJsonFile(STATE_FILE, OcmStateSchema)
|
||||
return parsed?.managerUrl ? parsed : null
|
||||
}
|
||||
|
||||
@@ -57,7 +62,7 @@ export function writeInstallNotice(notice: InstallNotice): void {
|
||||
export function readInstallNotice(): InstallNotice | null {
|
||||
let parsed: InstallNotice | null
|
||||
try {
|
||||
parsed = readJsonFile<InstallNotice>(INSTALL_NOTICE_FILE)
|
||||
parsed = readJsonFile(INSTALL_NOTICE_FILE, InstallNoticeSchema)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { join } from 'path'
|
||||
import { z } from 'zod'
|
||||
import { JsonObjectSchema, JsonValueSchema, type JsonValue } from '@opencode-manager/shared/utils'
|
||||
import { getConfigDir } from './state.js'
|
||||
import { readJsonFile, writeJsonFileAtomic } from './json-store.js'
|
||||
import type { TokenStore, TokenStoreDescription } from './token-store.js'
|
||||
@@ -6,9 +8,10 @@ import { TokenStoreError, describeCause } from './token-store.js'
|
||||
|
||||
const DOCUMENT_VERSION = 1
|
||||
|
||||
type TokenDocument = Record<string, unknown> & {
|
||||
interface TokenDocument {
|
||||
version: number
|
||||
tokens: Record<string, string>
|
||||
[key: string]: JsonValue
|
||||
}
|
||||
|
||||
function tokenFilePath(): string {
|
||||
@@ -16,14 +19,16 @@ function tokenFilePath(): string {
|
||||
}
|
||||
|
||||
function readDocument(filePath: string): TokenDocument {
|
||||
let raw: Record<string, unknown> | null
|
||||
let content: JsonValue | null
|
||||
try {
|
||||
raw = readJsonFile<Record<string, unknown>>(filePath)
|
||||
} catch (err) {
|
||||
throw new TokenStoreError(`failed to read token file ${filePath}: ${describeCause(err)}`, 'file')
|
||||
content = readJsonFile(filePath, JsonValueSchema)
|
||||
} catch (cause) {
|
||||
throw new TokenStoreError(`failed to read token file ${filePath}: ${describeCause(cause)}`, 'file')
|
||||
}
|
||||
const empty: TokenDocument = { version: DOCUMENT_VERSION, tokens: {} }
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return empty
|
||||
const parsed = JsonObjectSchema.safeParse(content)
|
||||
if (!parsed.success) return empty
|
||||
const raw = parsed.data
|
||||
if (raw.version !== undefined && raw.version !== DOCUMENT_VERSION) {
|
||||
throw new TokenStoreError(
|
||||
`token file ${filePath} uses unsupported format version ${JSON.stringify(raw.version)}; upgrade ocm or remove the file`,
|
||||
@@ -31,9 +36,11 @@ function readDocument(filePath: string): TokenDocument {
|
||||
)
|
||||
}
|
||||
const tokens: Record<string, string> = {}
|
||||
if (raw.tokens && typeof raw.tokens === 'object' && !Array.isArray(raw.tokens)) {
|
||||
for (const [account, token] of Object.entries(raw.tokens as Record<string, unknown>)) {
|
||||
if (typeof token === 'string') tokens[account] = token
|
||||
const storedTokens = JsonObjectSchema.safeParse(raw.tokens)
|
||||
if (storedTokens.success) {
|
||||
for (const [account, token] of Object.entries(storedTokens.data)) {
|
||||
const value = z.string().safeParse(token)
|
||||
if (value.success) tokens[account] = value.data
|
||||
}
|
||||
}
|
||||
return { ...raw, version: DOCUMENT_VERSION, tokens }
|
||||
@@ -45,9 +52,9 @@ function mutateDocument(filePath: string, mutate: (tokens: Record<string, string
|
||||
if (!mutate(doc.tokens)) return false
|
||||
writeJsonFileAtomic(filePath, doc)
|
||||
return true
|
||||
} catch (err) {
|
||||
if (err instanceof TokenStoreError) throw err
|
||||
throw new TokenStoreError(`failed to write token file ${filePath}: ${describeCause(err)}`, 'file')
|
||||
} catch (cause) {
|
||||
if (cause instanceof TokenStoreError) throw cause
|
||||
throw new TokenStoreError(`failed to write token file ${filePath}: ${describeCause(cause)}`, 'file')
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { execFile } from 'child_process'
|
||||
import { z } from 'zod'
|
||||
import type { TokenStore, TokenStoreDescription } from './token-store.js'
|
||||
import { TokenStoreError } from './token-store.js'
|
||||
|
||||
@@ -15,7 +16,32 @@ export interface SecurityResult {
|
||||
|
||||
export type SecurityRunner = (args: string[]) => Promise<SecurityResult>
|
||||
|
||||
type ExecFileFailure = Error & { code?: number | string }
|
||||
export interface SecurityStdin {
|
||||
on(event: 'error', listener: () => void): void
|
||||
end(command: string): void
|
||||
}
|
||||
|
||||
export interface SecurityExecChild {
|
||||
stdin?: SecurityStdin | null
|
||||
}
|
||||
|
||||
export interface SecurityExecError {
|
||||
message: string
|
||||
code?: number | string | null
|
||||
}
|
||||
|
||||
export interface SecurityExecOptions {
|
||||
encoding: 'utf-8'
|
||||
}
|
||||
|
||||
export type SecurityExecCallback = (error: SecurityExecError | null, stdout: string, stderr: string) => void
|
||||
|
||||
export type SecurityExec = (
|
||||
bin: string,
|
||||
args: string[],
|
||||
options: SecurityExecOptions,
|
||||
callback: SecurityExecCallback,
|
||||
) => SecurityExecChild
|
||||
|
||||
export function formatSecurityCommand(args: string[]): string {
|
||||
const quoted = args.map((arg) => {
|
||||
@@ -27,22 +53,31 @@ export function formatSecurityCommand(args: string[]): string {
|
||||
return `${quoted.join(' ')}\n`
|
||||
}
|
||||
|
||||
function runSecurity(args: string[]): Promise<SecurityResult> {
|
||||
return new Promise<SecurityResult>((resolve, reject) => {
|
||||
const command = formatSecurityCommand(args)
|
||||
const child = execFile(SECURITY_BIN, ['-i'], { encoding: 'utf-8' }, (err, stdout, stderr) => {
|
||||
const exitCode = (err as ExecFileFailure | null)?.code ?? (err ? null : 0)
|
||||
if (typeof exitCode !== 'number') {
|
||||
reject(new TokenStoreError(`cannot run the macOS 'security' CLI: ${(err as Error).message}`, 'keychain'))
|
||||
return
|
||||
}
|
||||
resolve({ stdout: stdout ?? '', stderr: stderr ?? '', code: exitCode })
|
||||
})
|
||||
child.stdin?.on('error', () => undefined)
|
||||
child.stdin?.end(command)
|
||||
})
|
||||
function runExecFile(bin: string, args: string[], options: SecurityExecOptions, callback: SecurityExecCallback): SecurityExecChild {
|
||||
return execFile(bin, args, options, callback)
|
||||
}
|
||||
|
||||
export function createSecurityRunner(exec: SecurityExec = runExecFile): SecurityRunner {
|
||||
return (args: string[]): Promise<SecurityResult> => {
|
||||
return new Promise<SecurityResult>((resolve, reject) => {
|
||||
const command = formatSecurityCommand(args)
|
||||
const child = exec(SECURITY_BIN, ['-i'], { encoding: 'utf-8' }, (err, stdout, stderr) => {
|
||||
const exitCode = err?.code ?? (err ? null : 0)
|
||||
const code = z.number().safeParse(exitCode)
|
||||
if (!code.success) {
|
||||
reject(new TokenStoreError(`cannot run the macOS 'security' CLI: ${err?.message ?? 'unknown error'}`, 'keychain'))
|
||||
return
|
||||
}
|
||||
resolve({ stdout: stdout ?? '', stderr: stderr ?? '', code: code.data })
|
||||
})
|
||||
child.stdin?.on('error', () => undefined)
|
||||
child.stdin?.end(command)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const runSecurity = createSecurityRunner()
|
||||
|
||||
function describeFailure(res: SecurityResult): string {
|
||||
const stderr = res.stderr.trim()
|
||||
if (stderr) return stderr
|
||||
|
||||
@@ -19,6 +19,6 @@ export class TokenStoreError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export function describeCause(err: unknown): string {
|
||||
return err instanceof Error ? err.message : String(err)
|
||||
export function describeCause(cause: unknown): string {
|
||||
return cause instanceof Error ? cause.message : String(cause)
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { Context } from '@opencode/plugin/tui/context'
|
||||
|
||||
export type OcmTuiContext = {
|
||||
readonly ui: {
|
||||
readonly toast: Pick<Context['ui']['toast'], 'show'>
|
||||
readonly dialog: Pick<Context['ui']['dialog'], 'confirm' | 'select' | 'prompt'>
|
||||
readonly router: Pick<Context['ui']['router'], 'current' | 'navigate'>
|
||||
readonly tabs: Pick<Context['ui']['tabs'], 'enabled' | 'open' | 'focus'>
|
||||
readonly slot: Context['ui']['slot']
|
||||
}
|
||||
readonly data: {
|
||||
readonly session: Pick<Context['data']['session'], 'get'>
|
||||
readonly location: {
|
||||
readonly model: Pick<Context['data']['location']['model'], 'list' | 'sync'>
|
||||
readonly provider: Pick<Context['data']['location']['provider'], 'list' | 'sync'>
|
||||
}
|
||||
}
|
||||
readonly keymap: Pick<Context['keymap'], 'layer' | 'dispatch'>
|
||||
readonly client: {
|
||||
readonly session: Pick<Context['client']['session'], 'export'>
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,18 @@
|
||||
import type { Context, DialogSelectOption } from '@opencode/plugin/tui/context'
|
||||
import type { OcmTuiContext } from './tui-context.js'
|
||||
|
||||
export function confirmDialog(context: Context, props: { title: string; message: string }): Promise<boolean> {
|
||||
export type DialogHost = {
|
||||
readonly ui: {
|
||||
readonly dialog: Pick<Context['ui']['dialog'], 'confirm' | 'select'>
|
||||
}
|
||||
}
|
||||
|
||||
export function confirmDialog(context: DialogHost, props: { title: string; message: string }): Promise<boolean> {
|
||||
return context.ui.dialog.confirm(props).then((value) => value === true)
|
||||
}
|
||||
|
||||
export function selectDialog<Value>(
|
||||
context: Context,
|
||||
context: DialogHost,
|
||||
title: string,
|
||||
options: readonly DialogSelectOption<Value>[],
|
||||
): Promise<Value | undefined> {
|
||||
@@ -16,8 +23,7 @@ type SessionInfo = NonNullable<ReturnType<Context['data']['session']['get']>>
|
||||
|
||||
export type SessionTarget = { sessionID: string; directory: string; session: SessionInfo }
|
||||
|
||||
/** Resolves the routed session and its directory, or shows an error toast and returns undefined. */
|
||||
export function requireSessionTarget(context: Context): SessionTarget | undefined {
|
||||
export function requireSessionTarget(context: OcmTuiContext): SessionTarget | undefined {
|
||||
const route = context.ui.router.current()
|
||||
if (route.type !== 'session') {
|
||||
context.ui.toast.show({ variant: 'error', message: 'Not in a session' })
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
/** @jsxImportSource @opentui/solid */
|
||||
import { TextAttributes, type KeyEvent, type TextareaRenderable } from '@opentui/core'
|
||||
import { useKeyboard } from '@opentui/solid'
|
||||
import { createEffect, createMemo, createSignal, For, Show, type JSX } from 'solid-js'
|
||||
@@ -12,11 +11,6 @@ export type KeyHint = readonly [key: string, label: string]
|
||||
|
||||
const PICKER_ROWS = 8
|
||||
|
||||
/**
|
||||
* Row colors matching OpenCode's select dialogs: every text in the cursor row uses the
|
||||
* primary-action focused color on the focused background; a chosen row away from the
|
||||
* cursor uses the selected form-field color for its marker and title.
|
||||
*/
|
||||
export function rowColors(theme: DialogTheme, state: { active: boolean; chosen?: boolean }) {
|
||||
if (state.active) {
|
||||
const text = theme.text.action.primary.focused
|
||||
@@ -31,12 +25,10 @@ export function rowColors(theme: DialogTheme, state: { active: boolean; chosen?:
|
||||
}
|
||||
}
|
||||
|
||||
/** True for the dialog-wide submit chord. */
|
||||
export function isSubmitKey(event: KeyEvent): boolean {
|
||||
return event.ctrl && event.name === 's'
|
||||
}
|
||||
|
||||
/** Tab / Shift+Tab focus cycling over `count` fields; returns the focused index accessor. */
|
||||
export function useFieldFocus(count: () => number, enabled: () => boolean = () => true) {
|
||||
const [index, setIndex] = createSignal(0)
|
||||
createEffect(() => {
|
||||
@@ -163,7 +155,6 @@ export function TextAreaField(props: {
|
||||
)
|
||||
}
|
||||
|
||||
/** A two-way choice rendered as radio buttons; ←/→/space switch it while focused. */
|
||||
export function ChoiceField<Value>(props: {
|
||||
theme: DialogTheme
|
||||
label: string
|
||||
@@ -198,10 +189,6 @@ export function ChoiceField<Value>(props: {
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Filterable model list. Typing filters, ↑/↓ move, Enter toggles (multiple) or picks (single).
|
||||
* Selection state is owned by the caller.
|
||||
*/
|
||||
export function ModelPicker(props: {
|
||||
theme: DialogTheme
|
||||
label: string
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
/** @jsxImportSource @opentui/solid */
|
||||
import { TextAttributes } from '@opentui/core'
|
||||
import { useKeyboard } from '@opentui/solid'
|
||||
import { createEffect, createMemo, createSignal, For, on, onMount, Show } from 'solid-js'
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import type { Context, ToastOptions } from '@opencode/plugin/tui/context'
|
||||
import type { ToastOptions } from '@opencode/plugin/tui/context'
|
||||
import {
|
||||
FuseMultiRunRequestSchema,
|
||||
FusionRecoveredDetailsSchema,
|
||||
@@ -23,8 +23,10 @@ import {
|
||||
} from '@opencode-manager/shared/opencode'
|
||||
import { ManagerApi, ManagerApiError, isManagerRouteMissing } from './manager-api.js'
|
||||
import { resolveManagerApi } from './manager-auth.js'
|
||||
import type { ManagerAuthDeps } from './manager-auth.js'
|
||||
import { describeCause } from './token-store.js'
|
||||
import { slashArgument } from './tui-dialogs.js'
|
||||
import type { OcmTuiContext } from './tui-context.js'
|
||||
import type { RemoteContext } from './remote-context.js'
|
||||
|
||||
export const MULTI_RUN_COMMAND = 'ocm-multirun'
|
||||
@@ -56,7 +58,6 @@ export type FusionFormInput = {
|
||||
instructions: string
|
||||
}
|
||||
|
||||
/** Multi-run operations the dialogs call. Launch and fuse open the started sessions themselves and resolve to an error message, or null. */
|
||||
export type MultiRunActions = {
|
||||
loadModels(): Promise<ActionResult<ModelOption[]>>
|
||||
list(): Promise<ActionResult<MultiRun[]>>
|
||||
@@ -80,9 +81,10 @@ export type MultiRunCommandDeps = {
|
||||
remote: RemoteContext | undefined
|
||||
showLaunchDialog: (props: MultiRunLaunchDialogProps) => void
|
||||
showRunsDialog: (props: MultiRunsDialogProps) => void
|
||||
auth?: ManagerAuthDeps
|
||||
}
|
||||
|
||||
export async function listModelOptions(context: Context): Promise<ModelOption[]> {
|
||||
export async function listModelOptions(context: OcmTuiContext): Promise<ModelOption[]> {
|
||||
await Promise.all([context.data.location.model.sync(), context.data.location.provider.sync()])
|
||||
const providerNames = new Map(
|
||||
(context.data.location.provider.list() ?? [])
|
||||
@@ -104,7 +106,6 @@ export async function listModelOptions(context: Context): Promise<ModelOption[]>
|
||||
})
|
||||
}
|
||||
|
||||
/** Case-insensitive match of every whitespace-separated term against the model name or ref. */
|
||||
export function filterModelOptions(options: readonly ModelOption[], query: string): ModelOption[] {
|
||||
const terms = query.toLowerCase().split(/\s+/).filter(Boolean)
|
||||
if (terms.length === 0) return [...options]
|
||||
@@ -114,7 +115,7 @@ export function filterModelOptions(options: readonly ModelOption[], query: strin
|
||||
})
|
||||
}
|
||||
|
||||
export function openManagerSessions(context: Context, sessionIDs: string[]): void {
|
||||
export function openManagerSessions(context: OcmTuiContext, sessionIDs: string[]): void {
|
||||
const first = sessionIDs[0]
|
||||
if (!first) return
|
||||
|
||||
@@ -142,12 +143,10 @@ export function runSummary(run: MultiRun): string {
|
||||
return `${run.entries.length} models · ${started} started · ${run.fusions.length} fusions`
|
||||
}
|
||||
|
||||
/** Started entries backed by a session: the sessions to open and the valid fusion sources. */
|
||||
export function startedEntries(run: MultiRun): (MultiRunEntry & { sessionId: string })[] {
|
||||
return run.entries.filter(isFusionSourceEntry)
|
||||
}
|
||||
|
||||
/** Toggles an entry in the fusion selection, keeping run order and ignoring non-sources and selections past the model limit. */
|
||||
export function toggleFusionSource(run: MultiRun, selected: readonly number[], entryId: number): number[] {
|
||||
const sourceIds = startedEntries(run).map((entry) => entry.id)
|
||||
if (selected.includes(entryId)) return sourceIds.filter((id) => id !== entryId && selected.includes(id))
|
||||
@@ -163,14 +162,15 @@ export function parseLaunchForm(form: LaunchFormInput, repoId: number): ActionRe
|
||||
if (form.models.length > MULTI_RUN_MAX_MODELS) return { ok: false, error: `Choose at most ${MULTI_RUN_MAX_MODELS} models.` }
|
||||
|
||||
const baseRef = form.baseRef.trim()
|
||||
const parsed = LaunchMultiRunRequestSchema.safeParse({
|
||||
const payload: LaunchMultiRunRequest = {
|
||||
repoId,
|
||||
name,
|
||||
prompt,
|
||||
models: form.models,
|
||||
isolate: form.isolate,
|
||||
...(form.isolate && baseRef ? { baseRef } : {}),
|
||||
})
|
||||
}
|
||||
if (form.isolate && baseRef) payload.baseRef = baseRef
|
||||
const parsed = LaunchMultiRunRequestSchema.safeParse(payload)
|
||||
if (!parsed.success) return { ok: false, error: parsed.error.issues[0]?.message ?? 'Invalid multi-run.' }
|
||||
return { ok: true, value: parsed.data }
|
||||
}
|
||||
@@ -183,33 +183,38 @@ export function parseFusionForm(form: FusionFormInput, requestId: string): Actio
|
||||
|
||||
const instructions = form.instructions.trim()
|
||||
const baseRef = form.baseRef.trim()
|
||||
const parsed = FuseMultiRunRequestSchema.safeParse({
|
||||
const payload: FuseMultiRunRequest = {
|
||||
requestId,
|
||||
entryIds: form.entryIds,
|
||||
model: form.model,
|
||||
...(instructions ? { instructions } : {}),
|
||||
...(baseRef ? { baseRef } : {}),
|
||||
})
|
||||
}
|
||||
if (instructions) payload.instructions = instructions
|
||||
if (baseRef) payload.baseRef = baseRef
|
||||
const parsed = FuseMultiRunRequestSchema.safeParse(payload)
|
||||
if (!parsed.success) return { ok: false, error: parsed.error.issues[0]?.message ?? 'Invalid fusion.' }
|
||||
return { ok: true, value: parsed.data }
|
||||
}
|
||||
|
||||
/** Maps a Manager error to a message, plus the session of an earlier fusion attempt the Manager recovered instead. */
|
||||
export function describeMultiRunError(error: unknown): { message: string; recoveredSessionId?: string } {
|
||||
if (isManagerRouteMissing(error)) return { message: MULTI_RUN_ROUTE_MISSING }
|
||||
if (!(error instanceof ManagerApiError)) return { message: describeCause(error) }
|
||||
export interface MultiRunErrorDescription {
|
||||
message: string
|
||||
recoveredSessionId?: string
|
||||
}
|
||||
|
||||
const unavailable = FusionUnavailableDetailsSchema.safeParse(error.details)
|
||||
export function describeMultiRunError(cause: unknown): MultiRunErrorDescription {
|
||||
if (isManagerRouteMissing(cause)) return { message: MULTI_RUN_ROUTE_MISSING }
|
||||
if (!(cause instanceof ManagerApiError)) return { message: describeCause(cause) }
|
||||
|
||||
const unavailable = FusionUnavailableDetailsSchema.safeParse(cause.details)
|
||||
if (unavailable.success && unavailable.data.unavailableSources.length > 0) {
|
||||
return { message: unavailable.data.unavailableSources.map((source) => `${source.model}: ${source.message}`).join('\n') }
|
||||
}
|
||||
|
||||
const recovered =
|
||||
error.code === null || error.code === 'FUSION_ATTEMPT_RECOVERED' ? FusionRecoveredDetailsSchema.safeParse(error.details) : undefined
|
||||
cause.code === null || cause.code === 'FUSION_ATTEMPT_RECOVERED' ? FusionRecoveredDetailsSchema.safeParse(cause.details) : undefined
|
||||
const recoveredSessionId = recovered?.success ? recovered.data.fusions[0]?.sessionId : undefined
|
||||
if (recoveredSessionId) return { message: 'An earlier fusion attempt is already running.', recoveredSessionId }
|
||||
|
||||
return { message: error.message }
|
||||
return { message: cause.message }
|
||||
}
|
||||
|
||||
export function multiRunLaunchToast(run: MultiRun): ToastOptions {
|
||||
@@ -221,7 +226,7 @@ export function multiRunLaunchToast(run: MultiRun): ToastOptions {
|
||||
return { variant, message: lines.join('\n') }
|
||||
}
|
||||
|
||||
export async function runMultiRunCommand(context: Context, deps: MultiRunCommandDeps, input?: string): Promise<void> {
|
||||
export async function runMultiRunCommand(context: OcmTuiContext, deps: MultiRunCommandDeps, input?: string): Promise<void> {
|
||||
try {
|
||||
const repoId = deps.remote?.repoId
|
||||
if (!deps.remote || !repoId) {
|
||||
@@ -229,7 +234,7 @@ export async function runMultiRunCommand(context: Context, deps: MultiRunCommand
|
||||
return
|
||||
}
|
||||
|
||||
const resolved = await resolveManagerApi(deps.remote.managerUrl)
|
||||
const resolved = await resolveManagerApi(deps.remote.managerUrl, deps.auth)
|
||||
if (!resolved.ok) {
|
||||
context.ui.toast.show({ variant: 'error', message: resolved.message })
|
||||
return
|
||||
@@ -260,7 +265,7 @@ function fusionRequestKey(runId: number, form: FusionFormInput): string {
|
||||
|
||||
const pendingFusions = new Map<string, string>()
|
||||
|
||||
function createMultiRunActions(context: Context, api: ManagerApi, repoId: number): MultiRunActions {
|
||||
function createMultiRunActions(context: OcmTuiContext, api: ManagerApi, repoId: number): MultiRunActions {
|
||||
const attempt = async <Value>(operation: () => Promise<Value>): Promise<ActionResult<Value>> => {
|
||||
try {
|
||||
return { ok: true, value: await operation() }
|
||||
|
||||
+47
-22
@@ -1,17 +1,40 @@
|
||||
import type { Context } from '@opencode/plugin/tui/context'
|
||||
import { resolveOpenCodeProjectId } from '@opencode-manager/shared/project-id'
|
||||
import { resolveManagerAuth } from './manager-auth.js'
|
||||
import type { ManagerAuth } from './manager-auth.js'
|
||||
import { fetchRepos } from './manager-repos.js'
|
||||
import type { ManagerRepo } from './manager-repos.js'
|
||||
import { warmRepoProxy } from './repo-proxy.js'
|
||||
import { readState, writeState } from './state.js'
|
||||
import { readState, writeState, type OcmState } from './state.js'
|
||||
import { confirmDialog, selectDialog } from './tui-dialogs.js'
|
||||
import { setPendingWarp } from './warp.js'
|
||||
import type { PendingWarp } from './warp.js'
|
||||
import type { RemoteContext } from './remote-context.js'
|
||||
import type { OcmTuiContext } from './tui-context.js'
|
||||
|
||||
export interface OcmSwitchRuntime {
|
||||
resolveManagerAuth: (managerUrl?: string) => Promise<ManagerAuth>
|
||||
fetchRepos: (managerUrl: string, token: string) => Promise<ManagerRepo[]>
|
||||
resolveProjectId: (directory: string) => Promise<string | null>
|
||||
warmRepoProxy: (managerUrl: string, token: string, repoId: number) => Promise<void>
|
||||
readState: () => OcmState | null
|
||||
writeState: (state: OcmState) => void
|
||||
setPendingWarp: (warp: PendingWarp) => void
|
||||
}
|
||||
|
||||
export const ocmSwitchRuntime: OcmSwitchRuntime = {
|
||||
resolveManagerAuth,
|
||||
fetchRepos,
|
||||
resolveProjectId: resolveOpenCodeProjectId,
|
||||
warmRepoProxy,
|
||||
readState,
|
||||
writeState,
|
||||
setPendingWarp,
|
||||
}
|
||||
|
||||
export type OcmSwitchDeps = {
|
||||
remote: RemoteContext | undefined
|
||||
cwd?: string
|
||||
runtime?: OcmSwitchRuntime
|
||||
}
|
||||
|
||||
type SwitchChoice = { kind: 'repo'; repo: ManagerRepo } | { kind: 'local' }
|
||||
@@ -20,10 +43,10 @@ const MATCH_CATEGORY = 'Matches this directory'
|
||||
const REPO_CATEGORY = 'Manager repos'
|
||||
const LOCAL_CATEGORY = 'Local'
|
||||
|
||||
/** Switches this TUI to another server: a Manager repo, or back to local opencode when attached. */
|
||||
export async function runOcmSwitch(context: Context, deps: OcmSwitchDeps): Promise<void> {
|
||||
export async function runOcmSwitch(context: OcmTuiContext, deps: OcmSwitchDeps): Promise<void> {
|
||||
const runtime = deps.runtime ?? ocmSwitchRuntime
|
||||
try {
|
||||
const auth = await resolveManagerAuth(deps.remote?.managerUrl)
|
||||
const auth = await runtime.resolveManagerAuth(deps.remote?.managerUrl)
|
||||
if (!auth.ok && !deps.remote) {
|
||||
context.ui.toast.show({ variant: 'error', message: auth.message })
|
||||
return
|
||||
@@ -32,7 +55,7 @@ export async function runOcmSwitch(context: Context, deps: OcmSwitchDeps): Promi
|
||||
let repos: ManagerRepo[] = []
|
||||
if (auth.ok) {
|
||||
try {
|
||||
repos = (await fetchRepos(auth.managerUrl, auth.token)).filter((repo) => repo.cloneStatus === 'ready')
|
||||
repos = (await runtime.fetchRepos(auth.managerUrl, auth.token)).filter((repo) => repo.cloneStatus === 'ready')
|
||||
} catch (error) {
|
||||
if (!deps.remote) throw error
|
||||
}
|
||||
@@ -40,21 +63,21 @@ export async function runOcmSwitch(context: Context, deps: OcmSwitchDeps): Promi
|
||||
const choice = deps.remote
|
||||
? await chooseFromRemote(context, repos, deps.remote)
|
||||
: auth.ok
|
||||
? await chooseFromLocal(context, repos, auth.managerUrl, deps.cwd ?? localDirectory(context))
|
||||
? await chooseFromLocal(context, repos, auth.managerUrl, deps.cwd ?? localDirectory(context), runtime)
|
||||
: undefined
|
||||
if (!choice) return
|
||||
|
||||
if (choice.kind === 'local') {
|
||||
setPendingWarp({ kind: 'local' })
|
||||
runtime.setPendingWarp({ kind: 'local' })
|
||||
context.keymap.dispatch('app.exit')
|
||||
return
|
||||
}
|
||||
|
||||
if (!auth.ok) return
|
||||
|
||||
await warmRepoProxy(auth.managerUrl, auth.token, choice.repo.repoId)
|
||||
rememberLastRepo(choice.repo)
|
||||
setPendingWarp({
|
||||
await runtime.warmRepoProxy(auth.managerUrl, auth.token, choice.repo.repoId)
|
||||
rememberLastRepo(choice.repo, runtime)
|
||||
runtime.setPendingWarp({
|
||||
kind: 'attach',
|
||||
target: { managerUrl: auth.managerUrl, token: auth.token, repoId: choice.repo.repoId, repoName: choice.repo.name },
|
||||
})
|
||||
@@ -65,12 +88,13 @@ export async function runOcmSwitch(context: Context, deps: OcmSwitchDeps): Promi
|
||||
}
|
||||
|
||||
async function chooseFromLocal(
|
||||
context: Context,
|
||||
context: OcmTuiContext,
|
||||
repos: ManagerRepo[],
|
||||
managerUrl: string,
|
||||
directory: string,
|
||||
runtime: OcmSwitchRuntime,
|
||||
): Promise<SwitchChoice | undefined> {
|
||||
const projectId = await resolveOpenCodeProjectId(directory)
|
||||
const projectId = await runtime.resolveProjectId(directory)
|
||||
const matches = projectId ? repos.filter((repo) => repo.projectId === projectId) : []
|
||||
|
||||
if (matches.length === 1) {
|
||||
@@ -94,13 +118,14 @@ async function chooseFromLocal(
|
||||
])
|
||||
}
|
||||
|
||||
async function chooseFromRemote(context: Context, repos: ManagerRepo[], remote: RemoteContext): Promise<SwitchChoice | undefined> {
|
||||
async function chooseFromRemote(context: OcmTuiContext, repos: ManagerRepo[], remote: RemoteContext): Promise<SwitchChoice | undefined> {
|
||||
return selectDialog<SwitchChoice>(context, 'Switch server', [
|
||||
{ title: 'Local opencode', description: 'Leave the Manager and run opencode on this machine', value: { kind: 'local' }, category: LOCAL_CATEGORY },
|
||||
...repos.map((repo) => ({
|
||||
...repoOption(repo, REPO_CATEGORY),
|
||||
...(repo.repoId === remote.repoId ? { description: 'Current', disabled: true } : {}),
|
||||
})),
|
||||
...repos.map((repo) => {
|
||||
const option = repoOption(repo, REPO_CATEGORY)
|
||||
if (repo.repoId === remote.repoId) return { ...option, description: 'Current', disabled: true }
|
||||
return option
|
||||
}),
|
||||
])
|
||||
}
|
||||
|
||||
@@ -113,14 +138,14 @@ function repoOption(repo: ManagerRepo, category: string) {
|
||||
}
|
||||
}
|
||||
|
||||
function localDirectory(context: Context): string {
|
||||
function localDirectory(context: OcmTuiContext): string {
|
||||
const route = context.ui.router.current()
|
||||
const sessionDirectory = route.type === 'session' ? context.data.session.get(route.sessionID)?.location.directory : undefined
|
||||
return sessionDirectory ?? process.cwd()
|
||||
}
|
||||
|
||||
function rememberLastRepo(repo: ManagerRepo): void {
|
||||
const state = readState()
|
||||
function rememberLastRepo(repo: ManagerRepo, runtime: OcmSwitchRuntime): void {
|
||||
const state = runtime.readState()
|
||||
if (!state) return
|
||||
writeState({ ...state, lastRepoId: repo.repoId, lastRepoName: repo.name, lastRepoDir: repo.directory, lastRepoBranch: repo.branch })
|
||||
runtime.writeState({ ...state, lastRepoId: repo.repoId, lastRepoName: repo.name, lastRepoDir: repo.directory, lastRepoBranch: repo.branch })
|
||||
}
|
||||
+63
-21
@@ -1,16 +1,18 @@
|
||||
import type { Context } from '@opencode/plugin/tui/context'
|
||||
import type { InstallNotice } from './state.js'
|
||||
import { readInstallNotice } from './state.js'
|
||||
import { resolveManagerAuth } from './manager-auth.js'
|
||||
import type { ManagerAuth } from './manager-auth.js'
|
||||
import { fetchRepos, toRemoteRepoSummaries } from './manager-repos.js'
|
||||
import { ManagerApi } from './manager-api.js'
|
||||
import { prepareMirror, mirrorUpFast, pickMatchedRepo, chooseMoveDestination } from './mirror.js'
|
||||
import type { MirrorPlan, MoveDestination } from './mirror.js'
|
||||
import type { MirrorPlan, MirrorMoveApi, MirrorUpFastOpts, MirrorUpFastResult, MoveDestination } from './mirror.js'
|
||||
import { getBranchName } from './local-repo.js'
|
||||
import { transferSession, moveReminderText } from './session-move.js'
|
||||
import { createManagerSessionTransfer } from './remote-session.js'
|
||||
import type { ManagerSessionTransfer } from './remote-session.js'
|
||||
import { confirmDialog, requireSessionTarget, selectDialog } from './tui-dialogs.js'
|
||||
import { setPendingWarp, runPendingWarp } from './warp.js'
|
||||
import type { PendingWarp } from './warp.js'
|
||||
import { pushPhaseProgress, importProgress } from './move-progress.js'
|
||||
import { warmRepoProxy } from './repo-proxy.js'
|
||||
import type { MoveProgress } from './move-progress.js'
|
||||
@@ -18,6 +20,7 @@ import { MULTI_RUN_COMMAND, runMultiRunCommand } from './tui-multi-run.js'
|
||||
import type { MultiRunLaunchDialogProps, MultiRunsDialogProps } from './tui-multi-run.js'
|
||||
import { runOcmSwitch } from './tui-ocm.js'
|
||||
import type { RemoteContext } from './remote-context.js'
|
||||
import type { OcmTuiContext } from './tui-context.js'
|
||||
|
||||
export type MoveProgressSetter = (progress: MoveProgress | null) => void
|
||||
|
||||
@@ -31,8 +34,47 @@ export type OcmFeatures = {
|
||||
dialogs: OcmDialogs
|
||||
}
|
||||
|
||||
export async function setupOcm(context: Context, setMoveProgress: MoveProgressSetter, features: OcmFeatures): Promise<() => void> {
|
||||
showInstallNotice(context)
|
||||
export interface OcmPluginDeps {
|
||||
readInstallNotice: () => InstallNotice | null
|
||||
resolveManagerAuth: () => Promise<ManagerAuth>
|
||||
fetchRepos: typeof fetchRepos
|
||||
toRemoteRepoSummaries: typeof toRemoteRepoSummaries
|
||||
prepareMirror: typeof prepareMirror
|
||||
getBranchName: typeof getBranchName
|
||||
pickMatchedRepo: typeof pickMatchedRepo
|
||||
warmRepoProxy: typeof warmRepoProxy
|
||||
createManagerSessionTransfer: (managerUrl: string, token: string) => ManagerSessionTransfer
|
||||
createManagerApi: (managerUrl: string, token: string) => MirrorMoveApi
|
||||
chooseMoveDestination: typeof chooseMoveDestination
|
||||
mirrorUpFast: (plan: MirrorPlan, opts: MirrorUpFastOpts) => Promise<MirrorUpFastResult>
|
||||
setPendingWarp: (warp: PendingWarp) => void
|
||||
runPendingWarp: () => void
|
||||
}
|
||||
|
||||
export const ocmPluginDeps: OcmPluginDeps = {
|
||||
readInstallNotice,
|
||||
resolveManagerAuth: () => resolveManagerAuth(),
|
||||
fetchRepos,
|
||||
toRemoteRepoSummaries,
|
||||
prepareMirror,
|
||||
getBranchName,
|
||||
pickMatchedRepo,
|
||||
warmRepoProxy,
|
||||
createManagerSessionTransfer,
|
||||
createManagerApi: (managerUrl, token) => new ManagerApi(managerUrl, token),
|
||||
chooseMoveDestination,
|
||||
mirrorUpFast,
|
||||
setPendingWarp,
|
||||
runPendingWarp,
|
||||
}
|
||||
|
||||
export async function setupOcm(
|
||||
context: OcmTuiContext,
|
||||
setMoveProgress: MoveProgressSetter,
|
||||
features: OcmFeatures,
|
||||
deps: OcmPluginDeps = ocmPluginDeps,
|
||||
): Promise<() => void> {
|
||||
showInstallNotice(context, deps)
|
||||
context.ui.slot({
|
||||
append: 'app',
|
||||
render: () => {
|
||||
@@ -46,7 +88,7 @@ export async function setupOcm(context: Context, setMoveProgress: MoveProgressSe
|
||||
group: 'OpenCode Manager',
|
||||
palette: true,
|
||||
slash: { name: 'ocm-move' },
|
||||
run: () => runSessionMove(context, setMoveProgress),
|
||||
run: () => runSessionMove(context, setMoveProgress, deps),
|
||||
},
|
||||
{
|
||||
id: 'ocm.switch',
|
||||
@@ -80,11 +122,11 @@ export async function setupOcm(context: Context, setMoveProgress: MoveProgressSe
|
||||
return null
|
||||
},
|
||||
})
|
||||
return () => runPendingWarp()
|
||||
return () => deps.runPendingWarp()
|
||||
}
|
||||
|
||||
function showInstallNotice(context: Context): void {
|
||||
const notice = readInstallNotice()
|
||||
function showInstallNotice(context: OcmTuiContext, deps: OcmPluginDeps): void {
|
||||
const notice = deps.readInstallNotice()
|
||||
if (!notice) return
|
||||
|
||||
context.ui.toast.show({
|
||||
@@ -125,48 +167,48 @@ function moveConfirmMessage(repoName: string, destination: MoveDestination, loca
|
||||
}
|
||||
}
|
||||
|
||||
async function runSessionMove(context: Context, setMoveProgress: MoveProgressSetter): Promise<void> {
|
||||
async function runSessionMove(context: OcmTuiContext, setMoveProgress: MoveProgressSetter, deps: OcmPluginDeps): Promise<void> {
|
||||
try {
|
||||
const sessionTarget = requireSessionTarget(context)
|
||||
if (!sessionTarget) return
|
||||
const { sessionID, directory, session } = sessionTarget
|
||||
|
||||
const auth = await resolveManagerAuth()
|
||||
const auth = await deps.resolveManagerAuth()
|
||||
if (!auth.ok) {
|
||||
context.ui.toast.show({ variant: 'error', message: auth.message })
|
||||
return
|
||||
}
|
||||
|
||||
const repos = await fetchRepos(auth.managerUrl, auth.token)
|
||||
const plan = await prepareMirror(directory, toRemoteRepoSummaries(repos))
|
||||
const repos = await deps.fetchRepos(auth.managerUrl, auth.token)
|
||||
const plan = await deps.prepareMirror(directory, deps.toRemoteRepoSummaries(repos))
|
||||
|
||||
if (plan.matched.length === 0) {
|
||||
context.ui.toast.show({ variant: 'error', message: 'No matching Manager repo; run `ocm push --create` first' })
|
||||
return
|
||||
}
|
||||
|
||||
const localBranch = getBranchName(plan.repoRoot)
|
||||
const localBranch = deps.getBranchName(plan.repoRoot)
|
||||
if (!localBranch) {
|
||||
context.ui.toast.show({ variant: 'error', message: 'Check out a branch before moving; a detached HEAD cannot be moved.' })
|
||||
return
|
||||
}
|
||||
const matched = pickMatchedRepo(plan.matched, localBranch)
|
||||
const matched = deps.pickMatchedRepo(plan.matched, localBranch)
|
||||
?? 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
|
||||
|
||||
await warmRepoProxy(auth.managerUrl, auth.token, matchedRepoId)
|
||||
await deps.warmRepoProxy(auth.managerUrl, auth.token, matchedRepoId)
|
||||
|
||||
const transfer = createManagerSessionTransfer(auth.managerUrl, auth.token)
|
||||
const transfer = deps.createManagerSessionTransfer(auth.managerUrl, auth.token)
|
||||
const blocker = await describeMoveBlocker(transfer, sessionID, session.parentID)
|
||||
if (blocker) {
|
||||
context.ui.toast.show({ variant: 'error', message: blocker })
|
||||
return
|
||||
}
|
||||
|
||||
const managerApi = new ManagerApi(auth.managerUrl, auth.token)
|
||||
const managerApi = deps.createManagerApi(auth.managerUrl, auth.token)
|
||||
const checkouts = await managerApi.mirrorCheckouts(matched.repoId, localBranch)
|
||||
const destination = chooseMoveDestination(plan.repoRoot, localBranch, checkouts)
|
||||
const destination = deps.chooseMoveDestination(plan.repoRoot, localBranch, checkouts)
|
||||
|
||||
const proceed = await confirmDialog(context, {
|
||||
title: 'Move session to Manager',
|
||||
@@ -175,7 +217,7 @@ async function runSessionMove(context: Context, setMoveProgress: MoveProgressSet
|
||||
if (!proceed) return
|
||||
|
||||
const selectedPlan: MirrorPlan = { ...plan, matched: [matched] }
|
||||
const pushed = await mirrorUpFast(selectedPlan, {
|
||||
const pushed = await deps.mirrorUpFast(selectedPlan, {
|
||||
api: managerApi,
|
||||
force: true,
|
||||
...(destination.kind === 'new-worktree'
|
||||
@@ -214,8 +256,8 @@ async function runSessionMove(context: Context, setMoveProgress: MoveProgressSet
|
||||
setMoveProgress(null)
|
||||
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 warmRepoProxy(auth.managerUrl, auth.token, matched.repoId)
|
||||
setPendingWarp({
|
||||
await deps.warmRepoProxy(auth.managerUrl, auth.token, matched.repoId)
|
||||
deps.setPendingWarp({
|
||||
kind: 'attach',
|
||||
target: { managerUrl: auth.managerUrl, token: auth.token, repoId: matched.repoId, sessionID: result.sessionID, repoName: matched.name },
|
||||
})
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
/** @jsxImportSource @opentui/solid */
|
||||
import { createSignal, createEffect, onCleanup, Show } from 'solid-js'
|
||||
import { Plugin } from '@opencode/plugin/tui'
|
||||
import type { HueScale } from '@opencode/theme/tui'
|
||||
|
||||
@@ -3,6 +3,8 @@ 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 { z } from 'zod'
|
||||
import { JsonValueSchema, type JsonValue } from '@opencode-manager/shared/utils'
|
||||
import { removeQuietly } from './json-store.js'
|
||||
|
||||
export const OCM_PLUGIN_NAME = 'ocm-cli'
|
||||
@@ -71,28 +73,35 @@ function realPath(filePath: string): string {
|
||||
}
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
const CliConfigSchema = z.looseObject({ plugins: JsonValueSchema.optional() })
|
||||
|
||||
function pluginEntrySpec(entry: JsonValue): string | undefined {
|
||||
const spec = z.string().safeParse(entry)
|
||||
if (spec.success) return spec.data
|
||||
const entryArray = z.array(JsonValueSchema).safeParse(entry)
|
||||
if (!entryArray.success) return undefined
|
||||
const first = z.string().safeParse(entryArray.data[0])
|
||||
return first.success ? first.data : undefined
|
||||
}
|
||||
|
||||
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 interface CliConfigPatch {
|
||||
text: string
|
||||
changed: boolean
|
||||
}
|
||||
|
||||
export function addPluginToCliConfig(text: string | null, spec = OCM_PLUGIN_SPEC): { text: string; changed: boolean } {
|
||||
export function addPluginToCliConfig(text: string | null, spec = OCM_PLUGIN_SPEC): CliConfigPatch {
|
||||
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)) {
|
||||
const parsed: JsonValue = parseJsonc(text, errors, { allowTrailingComma: true, disallowComments: false })
|
||||
const config = CliConfigSchema.safeParse(parsed)
|
||||
if (errors.length > 0 || !config.success) {
|
||||
throw new InstallError('cli.json is not valid JSONC; add the plugin entry manually')
|
||||
}
|
||||
|
||||
const plugins = parsed.plugins
|
||||
const plugins = config.data.plugins
|
||||
if (plugins !== undefined && !Array.isArray(plugins)) {
|
||||
throw new InstallError('cli.json "plugins" is not an array; add the plugin entry manually')
|
||||
}
|
||||
@@ -122,7 +131,11 @@ function writeTextAtomic(filePath: string, text: string): void {
|
||||
mode = undefined
|
||||
}
|
||||
try {
|
||||
writeFileSync(tmp, text, { encoding: 'utf-8', ...(mode === undefined ? {} : { mode }) })
|
||||
if (mode === undefined) {
|
||||
writeFileSync(tmp, text, { encoding: 'utf-8' })
|
||||
} else {
|
||||
writeFileSync(tmp, text, { encoding: 'utf-8', mode })
|
||||
}
|
||||
renameSync(tmp, filePath)
|
||||
} catch (err) {
|
||||
removeQuietly(tmp)
|
||||
@@ -130,7 +143,12 @@ function writeTextAtomic(filePath: string, text: string): void {
|
||||
}
|
||||
}
|
||||
|
||||
function linkBinary(paths: VendorPaths, force: boolean): { changed: boolean; pathMissing: boolean } {
|
||||
interface LinkBinaryResult {
|
||||
changed: boolean
|
||||
pathMissing: boolean
|
||||
}
|
||||
|
||||
function linkBinary(paths: VendorPaths, force: boolean): LinkBinaryResult {
|
||||
const target = join(paths.pluginDistDir, 'ocm.js')
|
||||
if (!existsSync(target)) {
|
||||
throw new InstallError(`vendored ocm.js missing at ${target}; re-run the install`)
|
||||
|
||||
+3
-4
@@ -21,7 +21,7 @@ export type WarpSpawn = (
|
||||
command: string,
|
||||
args: string[],
|
||||
options: { stdio: 'inherit'; env: NodeJS.ProcessEnv },
|
||||
) => unknown
|
||||
) => void
|
||||
|
||||
export type WarpExec = (binary: string, args: string[], env: NodeJS.ProcessEnv) => void
|
||||
|
||||
@@ -48,7 +48,6 @@ export function buildAttachInvocation(target: AttachTarget): AttachInvocation {
|
||||
}
|
||||
}
|
||||
|
||||
/** Builds a plain local `opencode` launch with every Manager attach variable removed. */
|
||||
export function buildLocalInvocation(env: NodeJS.ProcessEnv = process.env): AttachInvocation {
|
||||
return {
|
||||
args: [],
|
||||
@@ -73,8 +72,8 @@ export function runPendingWarp(spawn: WarpSpawn = spawnSync, exec: WarpExec | un
|
||||
}
|
||||
|
||||
function defaultExec(command: string, args: string[], env: NodeJS.ProcessEnv): void {
|
||||
if (typeof Bun === 'undefined') return
|
||||
if (globalThis.Bun === undefined) return
|
||||
const binary = Bun.which(command)
|
||||
if (!binary || typeof process.execve !== 'function') return
|
||||
if (!binary || process.execve === undefined) return
|
||||
process.execve(binary, args, env)
|
||||
}
|
||||
Reference in new issue
Block a user