mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
section 3: Phase 3: Shared Manager auth helper and Manager API client f
This commit is contained in:
1 parent
b316cb960c
commit
a99e69f653
5 files changed
+427
-27
No files matched your search
+106
-2
@@ -3,8 +3,15 @@ import { Readable } from 'stream'
|
||||
import {
|
||||
MirrorTargetEnsureResponseSchema,
|
||||
MirrorTargetPlanResponseSchema,
|
||||
MultiRunSchema,
|
||||
SessionGoalSchema,
|
||||
type FuseMultiRunRequest,
|
||||
type LaunchMultiRunRequest,
|
||||
type MirrorTargetEnsureResponse,
|
||||
type MirrorTargetPlanResponse,
|
||||
type MultiRun,
|
||||
type SessionGoal,
|
||||
type StartSessionGoalRequest,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
|
||||
export interface MirrorBeginOpts {
|
||||
@@ -75,23 +82,30 @@ export class ManagerApiError extends Error {
|
||||
public readonly status: number,
|
||||
public readonly code: string | null,
|
||||
public readonly operation: string,
|
||||
public readonly details: unknown = null,
|
||||
) {
|
||||
super(message)
|
||||
this.name = 'ManagerApiError'
|
||||
}
|
||||
}
|
||||
|
||||
export function isManagerRouteMissing(error: unknown): boolean {
|
||||
return error instanceof ManagerApiError && error.status === 404 && error.code === null
|
||||
}
|
||||
|
||||
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
|
||||
if (text) {
|
||||
try {
|
||||
const parsed = JSON.parse(text) as { error?: unknown; message?: unknown }
|
||||
const parsed = JSON.parse(text) as { error?: unknown; message?: unknown; details?: unknown }
|
||||
const errField = typeof parsed.error === 'string' ? parsed.error : null
|
||||
const msgField = typeof parsed.message === 'string' ? parsed.message : null
|
||||
code = errField
|
||||
detail = msgField ?? errField ?? text
|
||||
details = parsed.details ?? null
|
||||
} catch {
|
||||
/* not JSON, keep raw text */
|
||||
}
|
||||
@@ -99,7 +113,7 @@ async function formatErrorResponse(res: Response, operation: string): Promise<Ma
|
||||
const message = detail
|
||||
? `${operation} failed (${res.status}): ${detail}`
|
||||
: `${operation} failed (${res.status})`
|
||||
return new ManagerApiError(message, res.status, code, operation)
|
||||
return new ManagerApiError(message, res.status, code, operation, details)
|
||||
}
|
||||
|
||||
export class ManagerApi {
|
||||
@@ -255,4 +269,94 @@ export class ManagerApi {
|
||||
if (!res.ok) throw await formatErrorResponse(res, 'mirror patch snapshot')
|
||||
return (await res.json()) as MirrorPatchSnapshot
|
||||
}
|
||||
|
||||
async getLatestSessionGoal(sessionId: string): Promise<SessionGoal | null> {
|
||||
const res = await fetch(`${this.baseUrl}/api/internal/session-goals?sessionId=${encodeURIComponent(sessionId)}`, {
|
||||
headers: this.headers(),
|
||||
})
|
||||
|
||||
if (!res.ok) throw await formatErrorResponse(res, 'read session goal')
|
||||
const body = (await res.json()) as { goal: unknown }
|
||||
return SessionGoalSchema.nullable().parse(body.goal)
|
||||
}
|
||||
|
||||
async startSessionGoal(input: StartSessionGoalRequest): Promise<SessionGoal> {
|
||||
const res = await fetch(`${this.baseUrl}/api/internal/session-goals`, {
|
||||
method: 'POST',
|
||||
headers: { ...this.headers(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(input),
|
||||
})
|
||||
|
||||
if (!res.ok) throw await formatErrorResponse(res, 'start session goal')
|
||||
const body = (await res.json()) as { goal: unknown }
|
||||
return SessionGoalSchema.parse(body.goal)
|
||||
}
|
||||
|
||||
private async runSessionGoalAction(id: number, action: 'pause' | 'resume' | 'cancel'): Promise<SessionGoal> {
|
||||
const res = await fetch(`${this.baseUrl}/api/internal/session-goals/${encodeURIComponent(id)}/${action}`, {
|
||||
method: 'POST',
|
||||
headers: this.headers(),
|
||||
})
|
||||
|
||||
if (!res.ok) throw await formatErrorResponse(res, `${action} session goal`)
|
||||
const body = (await res.json()) as { goal: unknown }
|
||||
return SessionGoalSchema.parse(body.goal)
|
||||
}
|
||||
|
||||
pauseSessionGoal(id: number): Promise<SessionGoal> {
|
||||
return this.runSessionGoalAction(id, 'pause')
|
||||
}
|
||||
|
||||
resumeSessionGoal(id: number): Promise<SessionGoal> {
|
||||
return this.runSessionGoalAction(id, 'resume')
|
||||
}
|
||||
|
||||
cancelSessionGoal(id: number): Promise<SessionGoal> {
|
||||
return this.runSessionGoalAction(id, 'cancel')
|
||||
}
|
||||
|
||||
async listMultiRuns(repoId: number): Promise<MultiRun[]> {
|
||||
const res = await fetch(`${this.baseUrl}/api/internal/multi-runs?repoId=${encodeURIComponent(repoId)}`, {
|
||||
headers: this.headers(),
|
||||
})
|
||||
|
||||
if (!res.ok) throw await formatErrorResponse(res, 'list multi-runs')
|
||||
const body = (await res.json()) as { runs: unknown }
|
||||
return MultiRunSchema.array().parse(body.runs)
|
||||
}
|
||||
|
||||
async launchMultiRun(request: LaunchMultiRunRequest): Promise<MultiRun> {
|
||||
const res = await fetch(`${this.baseUrl}/api/internal/multi-runs`, {
|
||||
method: 'POST',
|
||||
headers: { ...this.headers(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(request),
|
||||
})
|
||||
|
||||
if (!res.ok) throw await formatErrorResponse(res, 'launch multi-run')
|
||||
const body = (await res.json()) as { run: unknown }
|
||||
return MultiRunSchema.parse(body.run)
|
||||
}
|
||||
|
||||
async fuseMultiRun(runId: number, request: FuseMultiRunRequest): Promise<MultiRun> {
|
||||
const res = await fetch(`${this.baseUrl}/api/internal/multi-runs/${encodeURIComponent(runId)}/fusions`, {
|
||||
method: 'POST',
|
||||
headers: { ...this.headers(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(request),
|
||||
})
|
||||
|
||||
if (!res.ok) throw await formatErrorResponse(res, 'fuse multi-run')
|
||||
const body = (await res.json()) as { run: unknown }
|
||||
return MultiRunSchema.parse(body.run)
|
||||
}
|
||||
|
||||
async discardMultiRunEntry(runId: number, entryId: number): Promise<MultiRun> {
|
||||
const res = await fetch(`${this.baseUrl}/api/internal/multi-runs/${encodeURIComponent(runId)}/entries/${encodeURIComponent(entryId)}/discard`, {
|
||||
method: 'POST',
|
||||
headers: this.headers(),
|
||||
})
|
||||
|
||||
if (!res.ok) throw await formatErrorResponse(res, 'discard multi-run entry')
|
||||
const body = (await res.json()) as { run: unknown }
|
||||
return MultiRunSchema.parse(body.run)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { readState } from './state.js'
|
||||
import { getToken } from './internal-token-store.js'
|
||||
import { TokenStoreError } from './token-store.js'
|
||||
|
||||
export type ManagerAuth =
|
||||
| { ok: true; managerUrl: string; token: string }
|
||||
| { ok: false; message: string }
|
||||
|
||||
export async function resolveManagerAuth(
|
||||
managerUrl: string | undefined = readState()?.managerUrl,
|
||||
): Promise<ManagerAuth> {
|
||||
if (!managerUrl) {
|
||||
return { ok: false, message: 'No manager configured. Run `ocm login <url>` first.' }
|
||||
}
|
||||
|
||||
let token: string | null
|
||||
try {
|
||||
token = await getToken(managerUrl)
|
||||
} catch (err) {
|
||||
const reason = err instanceof TokenStoreError ? err.message : String(err)
|
||||
return { ok: false, message: `Token store unavailable: ${reason}` }
|
||||
}
|
||||
|
||||
if (!token) {
|
||||
return { ok: false, message: `No token stored. Run \`ocm login ${managerUrl}\`.` }
|
||||
}
|
||||
|
||||
return { ok: true, managerUrl, token }
|
||||
}
|
||||
+11
-25
@@ -1,7 +1,6 @@
|
||||
import type { Context } from '@opencode/plugin/tui/context'
|
||||
import { readInstallNotice, readState } from './state.js'
|
||||
import { getToken } from './internal-token-store.js'
|
||||
import { TokenStoreError } from './token-store.js'
|
||||
import { readInstallNotice } from './state.js'
|
||||
import { resolveManagerAuth } from './manager-auth.js'
|
||||
import { fetchRepos, toRemoteRepoSummaries } from './manager-repos.js'
|
||||
import { ManagerApi, ManagerApiError } from './manager-api.js'
|
||||
import type { MirrorTargetPlanResponse } from '@opencode-manager/shared/schemas'
|
||||
@@ -116,26 +115,13 @@ async function runSessionMove(context: Context, setMoveProgress: MoveProgressSet
|
||||
return
|
||||
}
|
||||
|
||||
const state = readState()
|
||||
if (!state?.managerUrl) {
|
||||
context.ui.toast.show({ variant: 'error', message: 'No manager configured. Run `ocm login <url>` first.' })
|
||||
const auth = await resolveManagerAuth()
|
||||
if (!auth.ok) {
|
||||
context.ui.toast.show({ variant: 'error', message: auth.message })
|
||||
return
|
||||
}
|
||||
|
||||
let token: string | null
|
||||
try {
|
||||
token = await getToken(state.managerUrl)
|
||||
} catch (err) {
|
||||
const reason = err instanceof TokenStoreError ? err.message : String(err)
|
||||
context.ui.toast.show({ variant: 'error', message: `Token store unavailable: ${reason}` })
|
||||
return
|
||||
}
|
||||
if (!token) {
|
||||
context.ui.toast.show({ variant: 'error', message: `No token stored. Run \`ocm login ${state.managerUrl}\`.` })
|
||||
return
|
||||
}
|
||||
|
||||
const repos = await fetchRepos(state.managerUrl, token)
|
||||
const repos = await fetchRepos(auth.managerUrl, auth.token)
|
||||
const plan = await prepareMirror(session.location.directory, toRemoteRepoSummaries(repos))
|
||||
|
||||
if (plan.matched.length === 0) {
|
||||
@@ -150,16 +136,16 @@ async function runSessionMove(context: Context, setMoveProgress: MoveProgressSet
|
||||
const matchedRepoId = matched.repoId
|
||||
const remoteRepo = repos.find((r) => r.repoId === matchedRepoId)!
|
||||
|
||||
await warmRepoProxy(state.managerUrl, token, matchedRepoId)
|
||||
await warmRepoProxy(auth.managerUrl, auth.token, matchedRepoId)
|
||||
|
||||
const transfer = createManagerSessionTransfer(state.managerUrl, token)
|
||||
const transfer = 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(state.managerUrl, token)
|
||||
const managerApi = new ManagerApi(auth.managerUrl, auth.token)
|
||||
const target = await resolveMoveTarget(managerApi, matched, remoteRepo.directory, localBranch)
|
||||
const discardReasons = target.repoId === null ? [] : await describeRemoteDiscard(plan.repoRoot, managerApi, target.repoId)
|
||||
|
||||
@@ -199,8 +185,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(state.managerUrl, token, pushed.repoId)
|
||||
setPendingWarp({ managerUrl: state.managerUrl, token, repoId: pushed.repoId, sessionID: result.sessionID, repoName: matched.name })
|
||||
await warmRepoProxy(auth.managerUrl, auth.token, pushed.repoId)
|
||||
setPendingWarp({ managerUrl: auth.managerUrl, token: auth.token, repoId: pushed.repoId, sessionID: result.sessionID, repoName: matched.name })
|
||||
context.keymap.dispatch('app.exit')
|
||||
return
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user