|
| 1 | +// altimate_change - new file |
| 2 | +// |
| 3 | +// Wire client for the workspace-binding endpoints in altimate-backend |
| 4 | +// (/datamate-project-bindings/*, added by AI-8398). Shared between the TUI |
| 5 | +// plugin (packages/opencode/src/plugin/tui/altimate/workspace.tsx) and the |
| 6 | +// `altimate link` CLI subcommand (packages/opencode/src/cli/cmd/link.ts) so |
| 7 | +// the two entry points can't drift on request shape / error handling. |
| 8 | +// |
| 9 | +// Reads AltimateApi credentials on every call so an account switch is picked |
| 10 | +// up immediately without a plugin restart. All FastAPI HTTPException.detail |
| 11 | +// bodies come out as `{"detail": <string|object>}` — we parse the object form |
| 12 | +// for 409/412 and surface it as a typed error rather than a bare status code. |
| 13 | +import { AltimateApi } from "@/altimate/api/client" |
| 14 | + |
| 15 | +const REQUEST_TIMEOUT_MS = 15_000 |
| 16 | + |
| 17 | +export interface DatamateRef { |
| 18 | + id: number |
| 19 | + name: string |
| 20 | +} |
| 21 | + |
| 22 | +export interface Binding { |
| 23 | + id: number |
| 24 | + datamate_id: number |
| 25 | + datamate_name: string |
| 26 | + repo_remote: string |
| 27 | + created_at?: string |
| 28 | +} |
| 29 | + |
| 30 | +export interface CreateAndBindResponse { |
| 31 | + datamate: DatamateRef |
| 32 | + binding: Binding |
| 33 | + manage_url: string |
| 34 | +} |
| 35 | + |
| 36 | +export interface BindingResponse { |
| 37 | + binding: Binding |
| 38 | +} |
| 39 | + |
| 40 | +export interface GetBindingResponse { |
| 41 | + binding: Binding |
| 42 | + datamate: DatamateRef |
| 43 | +} |
| 44 | + |
| 45 | +export interface ConflictDetail { |
| 46 | + message: string |
| 47 | + existing_datamate_id?: number |
| 48 | + existing_datamate_name?: string | null |
| 49 | + repo_remote?: string |
| 50 | +} |
| 51 | + |
| 52 | +export interface PreconditionDetail { |
| 53 | + message: string |
| 54 | + actual_current_datamate_id?: number |
| 55 | + expected_current_datamate_id?: number |
| 56 | +} |
| 57 | + |
| 58 | +export class NotConfiguredError extends Error { |
| 59 | + constructor() { |
| 60 | + super("Altimate credentials not configured — sign in first.") |
| 61 | + this.name = "NotConfiguredError" |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +export class ConflictError extends Error { |
| 66 | + constructor(public readonly detail: ConflictDetail) { |
| 67 | + super(detail.message) |
| 68 | + this.name = "ConflictError" |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +export class PreconditionFailedError extends Error { |
| 73 | + constructor(public readonly detail: PreconditionDetail) { |
| 74 | + super(detail.message) |
| 75 | + this.name = "PreconditionFailedError" |
| 76 | + } |
| 77 | +} |
| 78 | + |
| 79 | +export class NotFoundError extends Error { |
| 80 | + constructor(msg = "Not found") { |
| 81 | + super(msg) |
| 82 | + this.name = "NotFoundError" |
| 83 | + } |
| 84 | +} |
| 85 | + |
| 86 | +export class ForbiddenError extends Error { |
| 87 | + constructor(msg = "Forbidden") { |
| 88 | + super(msg) |
| 89 | + this.name = "ForbiddenError" |
| 90 | + } |
| 91 | +} |
| 92 | + |
| 93 | +export class WorkspaceApiError extends Error { |
| 94 | + constructor( |
| 95 | + msg: string, |
| 96 | + public readonly status?: number, |
| 97 | + ) { |
| 98 | + super(msg) |
| 99 | + this.name = "WorkspaceApiError" |
| 100 | + } |
| 101 | +} |
| 102 | + |
| 103 | +async function creds(): Promise<{ url: string; instance: string; apiKey: string }> { |
| 104 | + if (!(await AltimateApi.isConfigured())) throw new NotConfiguredError() |
| 105 | + const c = await AltimateApi.getCredentials() |
| 106 | + return { url: c.altimateUrl, instance: c.altimateInstanceName, apiKey: c.altimateApiKey } |
| 107 | +} |
| 108 | + |
| 109 | +async function req<T>( |
| 110 | + method: string, |
| 111 | + subpath: string, |
| 112 | + opts: { body?: unknown; query?: Record<string, string> } = {}, |
| 113 | +): Promise<T> { |
| 114 | + const { url, instance, apiKey } = await creds() |
| 115 | + const qs = opts.query ? "?" + new URLSearchParams(opts.query).toString() : "" |
| 116 | + const target = `${url}/datamate-project-bindings${subpath}${qs}` |
| 117 | + const controller = new AbortController() |
| 118 | + const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS) |
| 119 | + let res: Response |
| 120 | + try { |
| 121 | + res = await fetch(target, { |
| 122 | + method, |
| 123 | + headers: { |
| 124 | + "Content-Type": "application/json", |
| 125 | + Authorization: `Bearer ${apiKey}`, |
| 126 | + "x-tenant": instance, |
| 127 | + }, |
| 128 | + signal: controller.signal, |
| 129 | + ...(opts.body !== undefined ? { body: JSON.stringify(opts.body) } : {}), |
| 130 | + }) |
| 131 | + } catch (err) { |
| 132 | + const msg = err instanceof Error ? err.message : String(err) |
| 133 | + throw new WorkspaceApiError(`Cannot reach ${target}: ${msg}`) |
| 134 | + } finally { |
| 135 | + clearTimeout(timeout) |
| 136 | + } |
| 137 | + let json: unknown = undefined |
| 138 | + const text = await res.text().catch(() => "") |
| 139 | + if (text) { |
| 140 | + try { |
| 141 | + json = JSON.parse(text) |
| 142 | + } catch { |
| 143 | + /* non-JSON body — surface as opaque via status code below */ |
| 144 | + } |
| 145 | + } |
| 146 | + const detail = (json as { detail?: unknown } | undefined)?.detail |
| 147 | + if (res.status === 404) throw new NotFoundError(typeof detail === "string" ? detail : "Not found") |
| 148 | + if (res.status === 403) throw new ForbiddenError(typeof detail === "string" ? detail : "Forbidden") |
| 149 | + if (res.status === 409) { |
| 150 | + const d = |
| 151 | + typeof detail === "object" && detail !== null |
| 152 | + ? (detail as ConflictDetail) |
| 153 | + : { message: typeof detail === "string" ? detail : "Conflict" } |
| 154 | + throw new ConflictError(d) |
| 155 | + } |
| 156 | + if (res.status === 412) { |
| 157 | + const d = |
| 158 | + typeof detail === "object" && detail !== null |
| 159 | + ? (detail as PreconditionDetail) |
| 160 | + : { message: typeof detail === "string" ? detail : "Precondition failed" } |
| 161 | + throw new PreconditionFailedError(d) |
| 162 | + } |
| 163 | + if (!res.ok) { |
| 164 | + throw new WorkspaceApiError( |
| 165 | + typeof detail === "string" ? detail : `Request failed with status ${res.status}`, |
| 166 | + res.status, |
| 167 | + ) |
| 168 | + } |
| 169 | + return json as T |
| 170 | +} |
| 171 | + |
| 172 | +export namespace WorkspaceApi { |
| 173 | + /** Server-authoritative pre-check: is this remote already bound in this tenant? */ |
| 174 | + export async function getBindingForRemote(remote: string): Promise<GetBindingResponse | null> { |
| 175 | + try { |
| 176 | + return await req<GetBindingResponse>("GET", "/by-remote", { query: { repo_remote: remote } }) |
| 177 | + } catch (err) { |
| 178 | + if (err instanceof NotFoundError) return null |
| 179 | + throw err |
| 180 | + } |
| 181 | + } |
| 182 | + |
| 183 | + export async function createAndBind(input: { |
| 184 | + name: string |
| 185 | + repoRemote: string |
| 186 | + description?: string |
| 187 | + }): Promise<CreateAndBindResponse> { |
| 188 | + return req<CreateAndBindResponse>("POST", "/", { |
| 189 | + body: { |
| 190 | + name: input.name, |
| 191 | + repo_remote: input.repoRemote, |
| 192 | + description: input.description ?? null, |
| 193 | + }, |
| 194 | + }) |
| 195 | + } |
| 196 | + |
| 197 | + export async function bindExisting(datamateId: number, remote: string): Promise<BindingResponse> { |
| 198 | + return req<BindingResponse>("POST", "/bind", { |
| 199 | + body: { datamate_id: datamateId, repo_remote: remote }, |
| 200 | + }) |
| 201 | + } |
| 202 | + |
| 203 | + export async function rebindByRemote(input: { |
| 204 | + remote: string |
| 205 | + targetDatamateId: number |
| 206 | + expectedCurrentDatamateId?: number |
| 207 | + }): Promise<BindingResponse> { |
| 208 | + return req<BindingResponse>("PUT", "/by-remote", { |
| 209 | + body: { |
| 210 | + repo_remote: input.remote, |
| 211 | + target_datamate_id: input.targetDatamateId, |
| 212 | + ...(input.expectedCurrentDatamateId !== undefined |
| 213 | + ? { expected_current_datamate_id: input.expectedCurrentDatamateId } |
| 214 | + : {}), |
| 215 | + }, |
| 216 | + }) |
| 217 | + } |
| 218 | + |
| 219 | + /** Populates the "link to existing workspace" picker. Reuses the existing |
| 220 | + * /datamates/ list endpoint on the datamates_router. */ |
| 221 | + export async function listDatamates(): Promise<DatamateRef[]> { |
| 222 | + const { url, instance, apiKey } = await creds() |
| 223 | + const res = await fetch(`${url}/datamates/`, { |
| 224 | + headers: { Authorization: `Bearer ${apiKey}`, "x-tenant": instance }, |
| 225 | + }) |
| 226 | + if (!res.ok) |
| 227 | + throw new WorkspaceApiError(`Failed to list workspaces (status ${res.status})`, res.status) |
| 228 | + const body = (await res.json()) as { datamates?: Array<{ id: number | string; name: string }> } |
| 229 | + return (body.datamates ?? []).map((d) => ({ id: Number(d.id), name: d.name })) |
| 230 | + } |
| 231 | +} |
0 commit comments