import type { JsonRecord, JsonValue } from "../common/types.js"; import { AgentRunError } from "../common/errors.js"; export class ManagerClient { constructor(readonly baseUrl: string) {} async get(path: string): Promise { return this.request("GET", path); } async post(path: string, body: JsonValue): Promise { return this.request("POST", path, body); } async put(path: string, body: JsonValue): Promise { return this.request("PUT", path, body); } async patch(path: string, body: JsonValue): Promise { return this.request("PATCH", path, body); } async delete(path: string): Promise { return this.request("DELETE", path); } private async request(method: string, path: string, body?: JsonValue): Promise { const init: RequestInit = { method }; if (body !== undefined) { init.headers = { "content-type": "application/json" }; init.body = JSON.stringify(body); } const response = await fetch(new URL(path, this.baseUrl), init); const text = await response.text(); if (text.trim().length === 0) throw new AgentRunError("infra-failed", `manager returned empty response for ${method} ${path}`, { httpStatus: 502 }); const envelope = JSON.parse(text) as JsonRecord; if (envelope.ok !== true) throw new AgentRunError(typeof envelope.failureKind === "string" ? envelope.failureKind as never : "infra-failed", typeof envelope.message === "string" ? envelope.message : `manager request failed: ${method} ${path}`, { httpStatus: response.status, details: envelope }); return envelope.data ?? null; } }