Files
pikasTech-agentrun/src/mgr/client.ts
T
2026-06-05 16:07:26 +08:00

41 lines
1.6 KiB
TypeScript

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<JsonValue> {
return this.request("GET", path);
}
async post(path: string, body: JsonValue): Promise<JsonValue> {
return this.request("POST", path, body);
}
async put(path: string, body: JsonValue): Promise<JsonValue> {
return this.request("PUT", path, body);
}
async patch(path: string, body: JsonValue): Promise<JsonValue> {
return this.request("PATCH", path, body);
}
async delete(path: string): Promise<JsonValue> {
return this.request("DELETE", path);
}
private async request(method: string, path: string, body?: JsonValue): Promise<JsonValue> {
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;
}
}