UNPKG

@azowl/agentops-sdk

Version:

AgentOps REST client and local task execution SDK for Node.js

158 lines (149 loc) • 7.65 kB
import { AgentOpsError, HASH, IDENTIFIER, duration, fail, invalidResponse, jsonBody, object, scopeMismatch, uuid, validUuid, } from "./client-http.js"; export { AgentOpsError }; // Agent URLs identify one origin. Reject alternative IP spellings and paths // before WHATWG URL normalization can turn them into a trusted loopback URL. function agentOrigin(value) { const match = typeof value === "string" && /^(https?):\/\/(\[[0-9a-f:]+\]|[a-z0-9.-]+)(?::(\d+))?\/?$/i.exec(value); if (!match || match[0] !== value) fail("INVALID_INPUT", "baseUrl must be an HTTP(S) agent origin."); let url; try { url = new URL(value); } catch { fail("INVALID_INPUT", "Invalid agent address."); } const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname); if (match[2].toLowerCase() !== url.hostname || (match[3] && Number(match[3]) === 0) || (url.protocol === "http:" && !loopback)) { fail("INVALID_INPUT", "Use a canonical loopback address for HTTP, or HTTPS for a remote agent."); } return url; } async function agentToken(url, configured) { let token = configured ?? process.env.AZWOL_AGENT_TOKEN; let origin = url.origin; if (token === undefined && url.protocol === "http:") { try { const { readFile } = await import("node:fs/promises"); const { join, isAbsolute } = await import("node:path"); const { homedir } = await import("node:os"); const windows = process.platform === "win32"; const home = windows ? process.env.LOCALAPPDATA || join(homedir(), "AppData", "Local") : process.env.XDG_CONFIG_HOME || join(homedir(), ".config"); if (!home || !isAbsolute(home)) throw new Error(); const directory = windows ? join(home, "AZWOL", "Agent", "connections") : join(home, "azwol-agent", "connections"); const prefix = url.hostname === "[::1]" ? "loopback6-" : "loopback-"; token = (await readFile(join(directory, prefix + (url.port || "80") + ".token"), "utf8")).trim(); if (url.hostname === "localhost") { const ipv4 = new URL(url); ipv4.hostname = "127.0.0.1"; origin = ipv4.origin; } } catch { fail("AGENT_TOKEN_REQUIRED", "Start the local agent for this OS user and port, or configure its bearer token."); } } if (typeof token !== "string" || token.length < 32 || token.length > 256 || !/^[A-Za-z0-9._~+/-]+=*$/.test(token) || /\s/.test(token)) { fail("AGENT_TOKEN_REQUIRED", "Configure a valid agent bearer token."); } return { token, origin }; } function agentReceipt(value) { if (!object(value) || !validUuid(value.id) || value.mode !== "local" || typeof value.runnerId !== "string" || typeof value.agentId !== "string" || typeof value.tool !== "string" || !["completed", "blocked", "failed"].includes(value.status) || !Object.hasOwn(value, "result") || (value.status === "completed" ? value.error !== null : value.result !== null || (value.status === "blocked" ? value.error?.code !== "tool_blocked" : !["tool_failed", "invalid_result"].includes(value.error?.code))) || !object(value.policy) || value.policy.decision !== (value.status === "blocked" ? "deny" : "allow") || typeof value.policy.profile !== "string" || typeof value.policy.sha256 !== "string" || !HASH.test(value.policy.sha256) || typeof value.policy.reason !== "string" || (value.policy.memorySha256 !== undefined && (typeof value.policy.memorySha256 !== "string" || !HASH.test(value.policy.memorySha256))) || ["teamId", "role", "provider", "model", "thinking"].some(key => value[key] !== undefined && typeof value[key] !== "string")) { invalidResponse(); } return value; } /** Submit a tool task directly to an independently running AZWOL Agent. */ export class AgentClient { #url; #token; #fetch; #timeoutMs; constructor(options) { if (!object(options)) fail("INVALID_INPUT", "Agent connection options are required."); this.#url = agentOrigin(options.baseUrl); 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 ?? 150_000, "timeoutMs"); this.tasks = Object.freeze({ create: (input) => this.#create(input), get: async (id) => { const key = uuid(id, "taskId"); return this.#send("/v1/tasks/" + key, { id: key }); }, }); } async #create(task) { if (!object(task) || typeof task.runnerId !== "string" || !IDENTIFIER.test(task.runnerId) || typeof task.agentId !== "string" || !IDENTIFIER.test(task.agentId) || typeof task.tool !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(task.tool) || !Object.hasOwn(task, "input") || Object.keys(task).some(key => !["runnerId", "agentId", "tool", "input"].includes(key))) { fail("INVALID_INPUT", "Supply runnerId, agentId, tool and a JSON input."); } let body; try { body = JSON.stringify({ runnerId: task.runnerId, agentId: task.agentId, tool: task.tool, input: task.input }, (_key, value) => { if (["undefined", "function", "symbol"].includes(typeof value) || (typeof value === "number" && !Number.isFinite(value))) throw new TypeError(); return value; }); } catch { fail("INVALID_INPUT", "The task input must be JSON serializable."); } return this.#send("/v1/tasks", { runnerId: task.runnerId, agentId: task.agentId, tool: task.tool }, body); } async #send(path, expected, body) { const write = body !== undefined; const { token, origin } = await agentToken(this.#url, this.#token); const controller = new AbortController(); const headers = { Accept: "application/json", Authorization: "Bearer " + token }; if (write) headers["Content-Type"] = "application/json"; let status = null; let timer; const deadline = new Promise((_, reject) => { timer = setTimeout(() => { controller.abort(); reject(new AgentOpsError("The agent response timed out.", { code: "REQUEST_TIMEOUT", status, outcomeUnknown: write })); }, this.#timeoutMs); }); try { const fetcher = this.#fetch; const response = await Promise.race([fetcher(origin + path, { method: write ? "POST" : "GET", headers, body, signal: controller.signal, redirect: "error", credentials: "omit", cache: "no-store", }), deadline]); status = response.status; if (status !== (write ? 201 : 200)) { void response.body?.cancel().catch(() => {}); throw new AgentOpsError("Agent returned HTTP " + status + ".", { code: "HTTP_" + status, status, outcomeUnknown: write && (status < 400 || status === 408 || status >= 500), }); } const receipt = agentReceipt(await Promise.race([jsonBody(response), deadline])); if (Object.entries(expected).some(([field, value]) => receipt[field] !== value)) scopeMismatch(); return receipt; } catch (error) { if (error instanceof AgentOpsError) { error.status ??= status; if (write && ["INVALID_RESPONSE", "RESPONSE_SCOPE_MISMATCH"].includes(error.code)) error.outcomeUnknown = true; throw error; } throw new AgentOpsError(write ? "Task submission could not be confirmed. Check the agent history before resubmitting." : "The agent response could not be confirmed.", { code: "REQUEST_FAILED", status, outcomeUnknown: write, }); } finally { clearTimeout(timer); controller.abort(); } } }