@azowl/agentops-sdk
Version:
AgentOps REST client and local task execution SDK for Node.js
340 lines (319 loc) • 16.3 kB
JavaScript
import {
AgentOpsError, HASH, IDENTIFIER, duration, fail, invalidResponse, jsonBody, object, scopeMismatch, uuid, validUuid,
} from "./client-http.js";
import { waitForTask, watchTask } from "./task-observation.js";
export { AgentOpsError };
function inputText(value, field) {
if (typeof value !== "string") fail("INVALID_INPUT", `${field} must be text.`);
const text = value.trim();
if (!text || Array.from(text).length > 12_000 || /[\uD800-\uDFFF]/u.test(text)) {
fail("INVALID_INPUT", `${field} must contain 1 to 12000 Unicode characters.`);
}
return text;
}
function baseURL(value) {
let url;
try { url = new URL(value); } catch { fail("INVALID_INPUT", "baseUrl must be an absolute API URL."); }
const local = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
if ((url.protocol !== "https:" && !(url.protocol === "http:" && local)) ||
url.username || url.password || url.search || url.hash) {
fail("INVALID_INPUT", "baseUrl must use HTTPS (or local HTTP) without credentials, a query, or a fragment.");
}
return url.href.replace(/\/+$/, "");
}
function sameUuid(left, right) {
return validUuid(left) && validUuid(right) && left.toLowerCase() === right.toLowerCase();
}
function time(value) {
return typeof value === "string" && Number.isFinite(Date.parse(value));
}
function validateTask(value, organizationId) {
if (!object(value)) invalidResponse();
if (!sameUuid(value.organization_id, organizationId)) scopeMismatch();
if (!validUuid(value.id) || !validUuid(value.client_request_id) ||
typeof value.task_id !== "string" || !value.task_id ||
typeof value.status !== "string" || !value.status ||
typeof value.prompt !== "string" || !(value.result === null || typeof value.result === "string") ||
!time(value.created_at) || !time(value.updated_at) ||
!(value.error_code == null || typeof value.error_code === "string")) invalidResponse();
if (value.pc_host_id != null || value.pc_profile_sha256 != null) {
if (!validUuid(value.pc_host_id) || typeof value.pc_profile_sha256 !== "string" ||
!HASH.test(value.pc_profile_sha256)) invalidResponse();
}
if (value.question !== null && (!object(value.question) ||
typeof value.question.question_id !== "string" || typeof value.question.question !== "string")) invalidResponse();
if (value.answer_receipt !== null && (!object(value.answer_receipt) ||
!validUuid(value.answer_receipt.client_request_id) ||
typeof value.answer_receipt.question_id !== "string" ||
typeof value.answer_receipt.status !== "string")) invalidResponse();
return value;
}
function retryAfter(value) {
if (!value) return null;
const seconds = Number(value);
if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1000;
const date = Date.parse(value);
return Number.isFinite(date) ? Math.max(0, date - Date.now()) : null;
}
function safeText(value, max, token) {
if (typeof value !== "string") return null;
return value.split(token).join("[redacted]").replace(/[\x00-\x1f\x7f]/g, " ").slice(0, max);
}
/** Uses the existing product-user API. It does not enroll or start a runner. */
export class AgentOpsClient {
#baseUrl;
#organizationId;
#token;
#fetch;
#timeoutMs;
constructor(options) {
if (!object(options)) fail("INVALID_INPUT", "Client options are required.");
this.#baseUrl = baseURL(options.baseUrl);
this.#organizationId = uuid(options.organizationId, "organizationId");
if (typeof options.token !== "string" && typeof options.token !== "function") {
fail("INVALID_INPUT", "A product-user token or token callback is required.");
}
this.#token = options.token;
this.#fetch = options.fetch ?? globalThis.fetch;
if (typeof this.#fetch !== "function") fail("INVALID_INPUT", "A Fetch implementation is required.");
this.#timeoutMs = duration(options.timeoutMs ?? 30_000, "timeoutMs");
this.profile = Object.freeze({ get: (request) => this.#readProfile(request) });
this.connection = Object.freeze({ get: (request) => this.#readConnection(request) });
this.devices = Object.freeze({
list: (request) => this.#listDevices(request),
getProfileConnection: (profileId, request) => this.#getProfileConnection(profileId, request),
});
const readTask = (id, request) => this.#getTask(id, request);
this.tasks = Object.freeze({
list: (request) => this.#listTasks(request),
get: readTask,
create: (input, request) => this.#createTask(input, request),
answer: (id, input, request) => this.#answerTask(id, input, request),
wait: (id, request) => waitForTask(readTask, id, request),
watch: (id, request) => watchTask(readTask, id, request),
});
}
#scoped(value) {
if (!object(value)) invalidResponse();
if (!sameUuid(value.organization_id, this.#organizationId)) scopeMismatch();
return value;
}
#readProfile(options) {
return this.#request("/profile", options, (value) => {
this.#scoped(value);
if (typeof value.configured !== "boolean" || !Number.isSafeInteger(value.revision) || value.revision < 0) invalidResponse();
return value;
});
}
#readConnection(options) {
return this.#request("/connection", options, (value) => {
this.#scoped(value);
if (typeof value.can_run !== "boolean" || !time(value.checked_at) ||
!object(value.infrastructure) || !object(value.runtime) || !object(value.provider)) invalidResponse();
return value;
});
}
#listDevices(options) {
return this.#request("/pc", options, (value) => {
this.#scoped(value);
if (value.schema !== "azwol.agentops.pc.v1" || !time(value.checked_at) || !Array.isArray(value.hosts)) invalidResponse();
const seen = new Set();
const hosts = value.hosts.map((host) => {
if (!object(host)) invalidResponse();
if (Object.hasOwn(host, "organization_id")) this.#scoped(host);
const { id, hostname, execution_status, profile_sha256, can_send_task } = host;
if (!validUuid(id) || typeof hostname !== "string" || !hostname.trim() ||
typeof execution_status !== "string" || !execution_status.trim() || typeof can_send_task !== "boolean" ||
(Object.hasOwn(host, "profile_id") && !validUuid(host.profile_id)) ||
!(profile_sha256 === null || (typeof profile_sha256 === "string" && HASH.test(profile_sha256))) ||
(can_send_task && (profile_sha256 === null || execution_status !== "ready"))) invalidResponse();
const key = id.toLowerCase();
if (seen.has(key)) invalidResponse();
seen.add(key);
return { id, hostname, execution_status, profile_sha256, can_send_task,
...(host.profile_id === undefined ? {} : { profile_id: host.profile_id }) };
});
return { organization_id: value.organization_id, checked_at: value.checked_at, hosts };
});
}
async #getProfileConnection(profileId, options) {
const id = uuid(profileId, "profileId");
return this.#request(`/pc/registry/profiles/${id}/connection`, options, (value) => {
this.#scoped(value);
if (value.schema !== "azwol.agentops.profile-connection.v1" || !time(value.checked_at) ||
!object(value.selected) || !Array.isArray(value.devices)) invalidResponse();
const { profile_uuid, profile_revision, record_sha256 } = value.selected;
if (!validUuid(profile_uuid) || !Number.isSafeInteger(profile_revision) || profile_revision < 1 ||
typeof record_sha256 !== "string" || !HASH.test(record_sha256)) invalidResponse();
if (!sameUuid(profile_uuid, id)) scopeMismatch();
const seen = new Set();
const devices = value.devices.map((host) => {
if (!object(host)) invalidResponse();
if (Object.hasOwn(host, "organization_id")) this.#scoped(host);
const { host_uuid, hostname, profile_version, profile_sha256, materialized,
binding_current, profile_update_pending, enrollment_status, heartbeat_at, runtime } = host;
if (!validUuid(host_uuid) || typeof hostname !== "string" || !hostname.trim() ||
!(profile_version === null || (typeof profile_version === "string" && profile_version.trim())) ||
!(profile_sha256 === null || (typeof profile_sha256 === "string" && HASH.test(profile_sha256))) ||
typeof materialized !== "boolean" || typeof binding_current !== "boolean" ||
typeof profile_update_pending !== "boolean" || typeof enrollment_status !== "string" || !enrollment_status.trim() ||
!(heartbeat_at === null || time(heartbeat_at)) || !object(runtime) || typeof runtime.state !== "string" || !runtime.state.trim() ||
(materialized && (!binding_current || profile_update_pending || profile_version === null || profile_sha256 === null))) invalidResponse();
const key = host_uuid.toLowerCase();
if (seen.has(key)) invalidResponse();
seen.add(key);
return { host_uuid, hostname, expected_profile_version: profile_version, expected_profile_sha256: profile_sha256,
materialized, binding_current, profile_update_pending, enrollment_status, heartbeat_at, runtime_state: runtime.state };
});
return { organization_id: value.organization_id, checked_at: value.checked_at,
selected: { profile_uuid, profile_revision, record_sha256 }, devices };
});
}
#listTasks(options) {
return this.#request("/tasks", options, (value) => {
this.#scoped(value);
if (!Array.isArray(value.items)) invalidResponse();
for (const task of value.items) validateTask(task, this.#organizationId);
return value;
});
}
async #getTask(id, options) {
id = uuid(id, "taskId");
return this.#request(`/tasks/${id}`, options, (value) => {
validateTask(value, this.#organizationId);
if (!sameUuid(value.id, id)) scopeMismatch();
return value;
});
}
async #createTask(input, options) {
if (!object(input)) fail("INVALID_INPUT", "Task input is required.");
const clientRequestId = uuid(input.clientRequestId, "clientRequestId");
const prompt = inputText(input.prompt, "prompt");
if (!Number.isSafeInteger(input.profileRevision) || input.profileRevision < 1) {
fail("INVALID_INPUT", "profileRevision must be a positive integer from profile.get().");
}
const body = {
expected_org_id: this.#organizationId,
client_request_id: clientRequestId,
prompt,
expected_profile_revision: input.profileRevision,
};
const pcRequested = input.pcHostId !== undefined || input.pcProfileSha256 !== undefined;
if (pcRequested) {
body.pc_host_id = uuid(input.pcHostId, "pcHostId");
if (typeof input.pcProfileSha256 !== "string" || !HASH.test(input.pcProfileSha256)) {
fail("INVALID_INPUT", "A PC host and its exact lowercase SHA256 must be supplied together.");
}
body.expected_pc_profile_sha256 = input.pcProfileSha256;
}
return this.#request("/tasks", options, (value) => {
validateTask(value, this.#organizationId);
if (!sameUuid(value.client_request_id, clientRequestId) ||
(pcRequested ? !sameUuid(value.pc_host_id, body.pc_host_id) || value.pc_profile_sha256 !== body.expected_pc_profile_sha256
: value.pc_host_id != null || value.pc_profile_sha256 != null)) scopeMismatch();
return value;
}, body, clientRequestId);
}
async #answerTask(id, input, options) {
id = uuid(id, "taskId");
if (!object(input)) fail("INVALID_INPUT", "Answer input is required.");
const clientRequestId = uuid(input.clientRequestId, "clientRequestId");
if (typeof input.questionId !== "string" || !IDENTIFIER.test(input.questionId)) {
fail("INVALID_INPUT", "questionId must be an existing question identifier of at most 160 characters.");
}
const body = {
expected_org_id: this.#organizationId,
client_request_id: clientRequestId,
question_id: input.questionId,
answer: inputText(input.answer, "answer"),
};
return this.#request(`/tasks/${id}/answers`, options, (value) => {
validateTask(value, this.#organizationId);
const receipt = value.answer_receipt;
if (!sameUuid(value.id, id) || !receipt ||
!sameUuid(receipt.client_request_id, clientRequestId) || receipt.question_id !== body.question_id) scopeMismatch();
return value;
}, body, clientRequestId);
}
async #request(path, options = {}, validate, body, clientRequestId = null) {
const controller = new AbortController();
const write = body !== undefined;
let sent = false;
let timedOut = false;
let status = null;
let requestId = null;
let abortReject;
const aborted = new Promise((_, reject) => { abortReject = reject; });
const onAbort = () => {
controller.abort();
abortReject(new AgentOpsError(timedOut ? "The request timed out." : "The request was aborted.", {
code: timedOut ? "REQUEST_TIMEOUT" : "REQUEST_ABORTED",
status, clientRequestId, requestId, outcomeUnknown: write && sent,
}));
};
const externalAbort = () => onAbort();
const timer = setTimeout(() => { timedOut = true; onAbort(); }, this.#timeoutMs);
try {
if (options.signal?.aborted) onAbort();
else options.signal?.addEventListener("abort", externalAbort, { once: true });
const perform = async () => {
controller.signal.throwIfAborted();
const token = typeof this.#token === "function" ? await this.#token() : this.#token;
controller.signal.throwIfAborted();
if (typeof token !== "string" || !token || /[\x00-\x20\x7f]/.test(token)) {
fail("INVALID_INPUT", "The token callback must return a nonempty bearer token without whitespace.");
}
const headers = { Accept: "application/json", Authorization: `Bearer ${token}` };
if (write) {
headers["Content-Type"] = "application/json";
headers["Idempotency-Key"] = clientRequestId;
}
sent = true;
const fetcher = this.#fetch;
const response = await fetcher(this.#baseUrl + path, {
method: write ? "POST" : "GET", headers,
...(write ? { body: JSON.stringify(body) } : {}),
signal: controller.signal, redirect: "error", credentials: "omit", cache: "no-store",
});
status = response.status;
requestId = safeText(response.headers.get("x-btk-request-id") ?? response.headers.get("x-request-id"), 160, token);
let payload;
try { payload = await jsonBody(response); }
catch (error) { if (response.ok) throw error; }
controller.signal.throwIfAborted();
if (!response.ok) {
const detail = object(payload?.detail) ? payload.detail : payload;
const code = safeText(detail?.code, 80, token);
throw new AgentOpsError(
safeText(detail?.message, 512, token) ?? `The service returned HTTP ${status}.`,
{
code: code && /^[A-Za-z][A-Za-z0-9_.:-]*$/.test(code) ? code : `HTTP_${status}`,
status, clientRequestId,
requestId: requestId ?? safeText(detail?.request_id, 160, token),
retryAfterMs: retryAfter(response.headers.get("retry-after")),
outcomeUnknown: write && (status >= 500 || status === 408),
},
);
}
return validate(payload);
};
return await Promise.race([perform(), aborted]);
} catch (error) {
if (error instanceof AgentOpsError) {
error.clientRequestId ??= clientRequestId;
error.status ??= status;
error.requestId ??= requestId;
if (write && sent && ["INVALID_RESPONSE", "RESPONSE_SCOPE_MISMATCH"].includes(error.code)) error.outcomeUnknown = true;
throw error;
}
throw new AgentOpsError("The service request could not be verified.", {
code: controller.signal.aborted ? timedOut ? "REQUEST_TIMEOUT" : "REQUEST_ABORTED" : "REQUEST_FAILED",
status, clientRequestId, requestId, outcomeUnknown: write && sent,
});
} finally {
clearTimeout(timer);
controller.abort();
options.signal?.removeEventListener("abort", externalAbort);
}
}
}