@azowl/agentops-sdk
Version:
AgentOps REST client and local task execution SDK for Node.js
85 lines (76 loc) • 3.84 kB
JavaScript
import { createHash, randomUUID } from 'node:crypto';
import { readFile } from 'node:fs/promises';
import { homedir } from 'node:os';
import path from 'node:path';
import { AgentOpsError } from './client-http.js';
export const defaultUrl = 'http://127.0.0.1:43180';
export const namePattern = /^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,159}$/;
export const uuidPattern = /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i;
export function localOrigin(value = defaultUrl) {
const match = /^http:\/\/(?:localhost|127\.0\.0\.1):([1-9]\d{0,4})\/?$/.exec(value);
if (!match || match[0] !== value || Number(match[1]) > 65535) {
throw new TypeError('Specify a loopback HTTP origin with an explicit port.');
}
return 'http://127.0.0.1:' + match[1];
}
export function queueDirectory(baseUrl, directory) {
if (directory) return path.resolve(directory);
const config = process.platform === 'win32'
? process.env.LOCALAPPDATA || path.join(homedir(), 'AppData', 'Local')
: process.env.XDG_CONFIG_HOME || path.join(homedir(), '.config');
return path.join(config, 'AZOWL', 'local-queue', new URL(baseUrl).port);
}
export function workerKey(runnerId, agentId) {
if (![runnerId, agentId].every(s => typeof s === 'string' && namePattern.test(s) && s.trim() === s)) {
throw new TypeError('Supply valid runner and agent identifiers.');
}
return createHash('sha256').update(runnerId + '/' + agentId).digest('hex');
}
export function connectionFile(directory, key) {
return path.join(directory, 'connections', key + '.token');
}
export async function apiRequest(origin, token, resource, body, method = body === undefined ? 'GET' : 'POST') {
if (typeof token !== 'string' || !/^[A-Za-z0-9_-]{32,128}$/.test(token) || token.trim() !== token) {
throw new TypeError('Invalid local queue credential.');
}
const headers = { accept: 'application/json', authorization: 'Bearer ' + token };
if (body !== undefined) headers['content-type'] = 'application/json';
const response = await fetch(origin + resource, { method, headers,
body: body === undefined ? undefined : JSON.stringify(body), redirect: 'error',
signal: AbortSignal.timeout(5000), cache: 'no-store', credentials: 'omit' });
if (!response.ok) {
const error = await response.json().catch(() => ({}));
throw new AgentOpsError('Local queue request failed (HTTP ' + response.status + ').',
{ code: error?.error?.code || 'QUEUE_ERROR', status: response.status, outcomeUnknown: method === 'POST' && response.status >= 500 });
}
return response.json();
}
export async function readCredential(directory, key) {
return (await readFile(connectionFile(directory, key), 'utf8')).trim();
}
/** Node.js client for one local, persistent work queue. */
export class LocalQueueClient {
constructor(options = {}) {
const origin = localOrigin(options.baseUrl);
const directory = queueDirectory(origin, options.directory);
const send = async (resource, body) => apiRequest(origin,
options.token ?? await readCredential(directory, 'app'), resource, body);
this.tasks = Object.freeze({
create: async input => {
const requestId = input.requestId ?? randomUUID();
try {
return await send('/v1/tasks', { ...input, requestId });
} catch (error) {
const status = error.status ?? null;
throw new AgentOpsError('Queue submission could not be confirmed. Retain the request ID for retries.', {
requestId, status, code: error.code ?? 'QUEUE_REQUEST_FAILED', outcomeUnknown: status === null || status >= 500,
});
}
},
get: id => {
if (typeof id !== 'string' || !uuidPattern.test(id) || id.trim() !== id) throw new TypeError('Invalid task UUID.');
return send('/v1/tasks/' + id);
},
});
}
}