@azowl/agentops-sdk
Version:
AgentOps REST client and local task execution SDK for Node.js
162 lines (155 loc) • 8.33 kB
JavaScript
import http from 'node:http';
import { createHash, randomBytes, randomUUID } from 'node:crypto';
import { mkdir, rename, rm, writeFile } from 'node:fs/promises';
import path from 'node:path';
import store from './local-queue-store.cjs';
import { connectionFile, queueDirectory, workerKey, uuidPattern } from './local-queue.js';
const { openLocalQueue, QueueError } = store;
const digest = value => createHash('sha256').update(value).digest('hex');
const invalid = (status, code) => { throw new QueueError(status, code); };
async function bodyOf(req) {
if (!/^application\/json(?:\s*;\s*charset=utf-8)?$/i.test(req.headers['content-type'] || '') ||
req.headers['content-encoding']) invalid(415, 'json_required');
const parts = [];
let bytes = 0;
for await (const chunk of req.iterator({ destroyOnReturn: false })) {
bytes += chunk.length;
if (bytes > 256 * 1024) invalid(413, 'payload_too_large');
parts.push(chunk);
}
try {
const value = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(parts)));
if (value && typeof value === 'object' && !Array.isArray(value)) return value;
} catch { /* Return the public protocol error below. */ }
invalid(400, 'invalid_json');
}
function runtimeTask(task) {
return { id: task.id, task_id: task.id, revision: task.status === 'queued' ? 0 : 1,
status: task.status === 'queued' ? 'pending' : task.status, target_team: 'local', assignee_runner_id: task.runnerId,
payload: { kind: 'local_tool_task', target_agent: task.agentId },
runnerId: task.runnerId, agentId: task.agentId, tool: task.tool, input: task.input };
}
export async function startLocalQueue({ port = 43180, directory, workers = [], leaseMs = 30000 } = {}) {
if (!Number.isInteger(port) || port < 0 || port > 65535 || (!port && !directory) ||
!Array.isArray(workers) || !workers.length || !Number.isInteger(leaseMs) || leaseMs < 1000) {
throw new TypeError('Specify valid queue options and at least one worker assignment.');
}
const assignments = new Set(workers.map(w => workerKey(w.runnerId, w.agentId)));
if (assignments.size !== workers.length) throw new TypeError('Duplicate worker assignment.');
const root = queueDirectory('http://127.0.0.1:' + port, directory);
const queue = await openLocalQueue({ directory: root, leaseMs });
const roles = new Map();
let ready = false;
function respond(res, status, data) {
res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' });
res.end(JSON.stringify(data));
}
async function handle(req, res) {
if (!ready) invalid(503, 'starting');
const currentPort = server.address()?.port;
if (req.headersDistinct.host?.length !== 1 ||
!['127.0.0.1:' + currentPort, 'localhost:' + currentPort].includes(req.headers.host) ||
req.headers.origin !== undefined || req.headers['sec-fetch-site'] === 'cross-site') invalid(403, 'invalid_origin');
const match = /^Bearer ([A-Za-z0-9_-]{32,128})$/.exec(req.headers.authorization || '');
const role = match && roles.get(digest(match[1]));
if (!role || req.headersDistinct.authorization?.length !== 1) invalid(401, 'unauthorized');
if (!req.url.startsWith('/') || req.url.startsWith('//')) invalid(400, 'invalid_path');
const url = new URL(req.url, 'http://127.0.0.1');
const route = url.pathname;
if (role.app) {
if (route === '/v1/tasks' && req.method === 'POST') {
const task = await bodyOf(req);
if (Object.keys(task).some(key => !['runnerId','agentId','tool','input','requestId'].includes(key)) ||
!Object.hasOwn(task, 'input')) invalid(400, 'invalid_task');
let key;
try { key = workerKey(task.runnerId, task.agentId); } catch { invalid(400, 'invalid_assignment'); }
if (!assignments.has(key)) invalid(422, 'unregistered_assignment');
return respond(res, 202, queue.enqueue(task));
}
if (route.startsWith('/v1/tasks/') && req.method === 'GET') {
const id = route.slice('/v1/tasks/'.length);
const task = uuidPattern.test(id) && queue.get(id);
if (!task) invalid(404, 'task_not_found');
return respond(res, 200, task);
}
invalid(403, 'producer_route_only');
}
for (const name of ['x-btk-runner-id', 'x-runner-id']) {
if (req.headers[name] !== undefined && req.headers[name] !== role.runnerId) invalid(403, 'runner_mismatch');
}
if (req.headers['x-team-id'] !== undefined && req.headers['x-team-id'] !== 'local') invalid(403, 'team_mismatch');
if (route === '/runtime/task' && req.method === 'GET') {
if ((url.searchParams.get('status') || 'pending') !== 'pending') invalid(400, 'pending_only');
const rawLimit = url.searchParams.get('limit');
if (rawLimit !== null && !/^[1-9]\d{0,3}$/.test(rawLimit)) invalid(400, 'invalid_limit');
const rows = queue.pending(role, Math.min(Number(rawLimit ?? 1), 32));
return respond(res, 200, { tasks: rows.map(runtimeTask), pagination: 'task_id', next_cursor: null });
}
const [prefix, group, noun, id, action, ...extra] = route.split('/');
if (prefix || group !== 'runtime' || noun !== 'task' || !uuidPattern.test(id ?? '') || extra.length) invalid(404, 'not_found');
const task = queue.get(id);
if (!task || task.runnerId !== role.runnerId || task.agentId !== role.agentId) invalid(404, 'task_not_found');
if (!action && req.method === 'GET') return respond(res, 200, { task: runtimeTask(task) });
if (req.method !== 'POST') invalid(405, 'method_not_allowed');
const data = await bodyOf(req);
const binding = { ...role, taskId: id, leaseId: data.lease_id };
if (action === 'claim' || action === 'renew-lease') {
if (action === 'claim' && data.observed_revision !== 0) invalid(409, 'stale_revision');
const claim = action === 'claim' ? queue.claim(binding) : queue.renew(binding);
if (!claim) invalid(409, 'not_available');
return respond(res, 200, { accepted: true, task: runtimeTask(claim.task),
lease_id: claim.leaseId, lease_expires_at: claim.expiresAt });
}
if (action === 'complete' || action === 'fail') {
if ((action === 'complete') !== (data.receipt?.status === 'completed')) invalid(400, 'invalid_receipt');
const finished = queue.finish({ ...binding, receipt: data.receipt });
return respond(res, 200, { accepted: true, task_id: id, status: finished.status });
}
invalid(404, 'not_found');
}
const server = http.createServer({ maxHeaderSize: 8192, requestTimeout: 10000, headersTimeout: 8000 }, (req, res) => {
handle(req, res).catch(error => {
if (!res.destroyed && !res.writableEnded) respond(res, error instanceof QueueError ? error.status : 500,
{ error: { code: error instanceof QueueError ? error.code : 'queue_error' } });
});
});
server.maxConnections = 64;
let closing;
function close() {
if (!closing) closing = (async () => {
ready = false;
if (server.listening) {
const stopped = new Promise(resolve => server.close(resolve));
server.closeAllConnections();
await stopped;
}
await queue.close();
})();
return closing;
}
try {
await new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(port, '127.0.0.1', () => { server.off('error', reject); resolve(); });
});
await mkdir(path.join(root, 'connections'), { recursive: true, mode: 0o700 });
for (const role of [{ app: true }, ...workers.map(({ runnerId, agentId }) => ({ runnerId, agentId }))]) {
const token = randomBytes(32).toString('base64url');
const key = role.app ? 'app' : workerKey(role.runnerId, role.agentId);
const dest = connectionFile(root, key);
const tmp = dest + '.' + randomUUID();
try {
await writeFile(tmp, token + '\n', { mode: 0o600, flag: 'wx' });
await rename(tmp, dest);
} finally {
await rm(tmp, { force: true });
}
roles.set(digest(token), role.app ? { app: true } : { runnerId: role.runnerId, agentId: role.agentId });
}
ready = true;
return { baseUrl: 'http://127.0.0.1:' + server.address().port, directory: root, close };
} catch (error) {
await close();
throw error;
}
}